WGSLNodeBuilder.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. import { NoColorSpace, FloatType } from 'three';
  2. import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
  3. import NodeSampler from '../../common/nodes/NodeSampler.js';
  4. import { NodeSampledTexture, NodeSampledCubeTexture } from '../../common/nodes/NodeSampledTexture.js';
  5. import NodeUniformBuffer from '../../common/nodes/NodeUniformBuffer.js';
  6. import NodeStorageBuffer from '../../common/nodes/NodeStorageBuffer.js';
  7. import { NodeBuilder, CodeNode } from '../../../nodes/Nodes.js';
  8. import { getFormat } from '../utils/WebGPUTextureUtils.js';
  9. import WGSLNodeParser from './WGSLNodeParser.js';
  10. // GPUShaderStage is not defined in browsers not supporting WebGPU
  11. const GPUShaderStage = self.GPUShaderStage;
  12. const gpuShaderStageLib = {
  13. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  14. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  15. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  16. };
  17. const supports = {
  18. instance: true,
  19. storageBuffer: true
  20. };
  21. const wgslFnOpLib = {
  22. '^^': 'threejs_xor'
  23. };
  24. const wgslTypeLib = {
  25. float: 'f32',
  26. int: 'i32',
  27. uint: 'u32',
  28. bool: 'bool',
  29. color: 'vec3<f32>',
  30. vec2: 'vec2<f32>',
  31. ivec2: 'vec2<i32>',
  32. uvec2: 'vec2<u32>',
  33. bvec2: 'vec2<bool>',
  34. vec3: 'vec3<f32>',
  35. ivec3: 'vec3<i32>',
  36. uvec3: 'vec3<u32>',
  37. bvec3: 'vec3<bool>',
  38. vec4: 'vec4<f32>',
  39. ivec4: 'vec4<i32>',
  40. uvec4: 'vec4<u32>',
  41. bvec4: 'vec4<bool>',
  42. mat2: 'mat2x2<f32>',
  43. imat2: 'mat2x2<i32>',
  44. umat2: 'mat2x2<u32>',
  45. bmat2: 'mat2x2<bool>',
  46. mat3: 'mat3x3<f32>',
  47. imat3: 'mat3x3<i32>',
  48. umat3: 'mat3x3<u32>',
  49. bmat3: 'mat3x3<bool>',
  50. mat4: 'mat4x4<f32>',
  51. imat4: 'mat4x4<i32>',
  52. umat4: 'mat4x4<u32>',
  53. bmat4: 'mat4x4<bool>'
  54. };
  55. const wgslMethods = {
  56. dFdx: 'dpdx',
  57. dFdy: '- dpdy',
  58. mod_float: 'threejs_mod_float',
  59. mod_vec2: 'threejs_mod_vec2',
  60. mod_vec3: 'threejs_mod_vec3',
  61. mod_vec4: 'threejs_mod_vec4',
  62. equals_bool: 'threejs_equals_bool',
  63. equals_bvec2: 'threejs_equals_bvec2',
  64. equals_bvec3: 'threejs_equals_bvec3',
  65. equals_bvec4: 'threejs_equals_bvec4',
  66. lessThanEqual: 'threejs_lessThanEqual',
  67. greaterThan: 'threejs_greaterThan',
  68. inversesqrt: 'inverseSqrt',
  69. bitcast: 'bitcast<f32>'
  70. };
  71. const wgslPolyfill = {
  72. threejs_xor: new CodeNode( `
  73. fn threejs_xor( a : bool, b : bool ) -> bool {
  74. return ( a || b ) && !( a && b );
  75. }
  76. ` ),
  77. lessThanEqual: new CodeNode( `
  78. fn threejs_lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  79. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  80. }
  81. ` ),
  82. greaterThan: new CodeNode( `
  83. fn threejs_greaterThan( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  84. return vec3<bool>( a.x > b.x, a.y > b.y, a.z > b.z );
  85. }
  86. ` ),
  87. mod_float: new CodeNode( 'fn threejs_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  88. mod_vec2: new CodeNode( 'fn threejs_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  89. mod_vec3: new CodeNode( 'fn threejs_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  90. mod_vec4: new CodeNode( 'fn threejs_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  91. equals_bool: new CodeNode( 'fn threejs_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  92. equals_bvec2: new CodeNode( 'fn threejs_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  93. equals_bvec3: new CodeNode( 'fn threejs_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  94. equals_bvec4: new CodeNode( 'fn threejs_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  95. repeatWrapping: new CodeNode( `
  96. fn threejs_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  97. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  98. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  99. }
  100. ` )
  101. };
  102. class WGSLNodeBuilder extends NodeBuilder {
  103. constructor( object, renderer, scene = null ) {
  104. super( object, renderer, new WGSLNodeParser(), scene );
  105. this.uniformGroups = {};
  106. this.builtins = {};
  107. }
  108. needsColorSpaceToLinear( texture ) {
  109. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  110. }
  111. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  112. if ( shaderStage === 'fragment' ) {
  113. if ( depthSnippet ) {
  114. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  115. } else {
  116. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  117. }
  118. } else {
  119. return this.generateTextureLod( texture, textureProperty, uvSnippet );
  120. }
  121. }
  122. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  123. if ( shaderStage === 'fragment' ) {
  124. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  125. } else {
  126. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  127. }
  128. }
  129. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  130. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  131. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  132. } else {
  133. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  134. }
  135. }
  136. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  137. this._include( 'repeatWrapping' );
  138. const dimension = `textureDimensions( ${ textureProperty }, 0 )`;
  139. return `textureLoad( ${ textureProperty }, threejs_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  140. }
  141. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  142. if ( depthSnippet ) {
  143. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  144. } else {
  145. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  146. }
  147. }
  148. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  149. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  150. }
  151. isUnfilterable( texture ) {
  152. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( texture.isDataTexture === true && texture.type === FloatType );
  153. }
  154. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  155. let snippet = null;
  156. if ( texture.isVideoTexture === true ) {
  157. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  158. } else if ( this.isUnfilterable( texture ) ) {
  159. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  160. } else {
  161. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  162. }
  163. return snippet;
  164. }
  165. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  166. if ( shaderStage === 'fragment' ) {
  167. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  168. } else {
  169. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  170. }
  171. }
  172. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  173. let snippet = null;
  174. if ( texture.isVideoTexture === true ) {
  175. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  176. } else {
  177. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  178. }
  179. return snippet;
  180. }
  181. getPropertyName( node, shaderStage = this.shaderStage ) {
  182. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  183. if ( shaderStage === 'vertex' ) {
  184. return `varyings.${ node.name }`;
  185. }
  186. } else if ( node.isNodeUniform === true ) {
  187. const name = node.name;
  188. const type = node.type;
  189. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) {
  190. return name;
  191. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  192. return `NodeBuffer_${ node.id }.${name}`;
  193. } else {
  194. return node.groupNode.name + '.' + name;
  195. }
  196. }
  197. return super.getPropertyName( node );
  198. }
  199. _getUniformGroupCount( shaderStage ) {
  200. return Object.keys( this.uniforms[ shaderStage ] ).length;
  201. }
  202. getFunctionOperator( op ) {
  203. const fnOp = wgslFnOpLib[ op ];
  204. if ( fnOp !== undefined ) {
  205. this._include( fnOp );
  206. return fnOp;
  207. }
  208. return null;
  209. }
  210. getUniformFromNode( node, type, shaderStage, name = null ) {
  211. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  212. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  213. if ( nodeData.uniformGPU === undefined ) {
  214. let uniformGPU;
  215. const bindings = this.bindings[ shaderStage ];
  216. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) {
  217. let texture = null;
  218. if ( type === 'texture' || type === 'storageTexture' ) {
  219. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node );
  220. } else if ( type === 'cubeTexture' ) {
  221. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  222. }
  223. texture.store = node.isStoreTextureNode === true;
  224. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  225. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  226. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node );
  227. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  228. bindings.push( sampler, texture );
  229. uniformGPU = [ sampler, texture ];
  230. } else {
  231. bindings.push( texture );
  232. uniformGPU = [ texture ];
  233. }
  234. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  235. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  236. const buffer = new bufferClass( node );
  237. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  238. bindings.push( buffer );
  239. uniformGPU = buffer;
  240. } else {
  241. const group = node.groupNode;
  242. const groupName = group.name;
  243. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  244. let uniformsGroup = uniformsStage[ groupName ];
  245. if ( uniformsGroup === undefined ) {
  246. uniformsGroup = new NodeUniformsGroup( groupName, group );
  247. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  248. uniformsStage[ groupName ] = uniformsGroup;
  249. bindings.push( uniformsGroup );
  250. }
  251. uniformGPU = this.getNodeUniform( uniformNode, type );
  252. uniformsGroup.addUniform( uniformGPU );
  253. }
  254. nodeData.uniformGPU = uniformGPU;
  255. if ( shaderStage === 'vertex' ) {
  256. this.bindingsOffset[ 'fragment' ] = bindings.length;
  257. }
  258. }
  259. return uniformNode;
  260. }
  261. isReference( type ) {
  262. return super.isReference( type ) || type === 'texture_2d' || type === 'texture_cube' || type === 'texture_depth_2d' || type === 'texture_storage_2d';
  263. }
  264. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  265. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  266. if ( map.has( name ) === false ) {
  267. map.set( name, {
  268. name,
  269. property,
  270. type
  271. } );
  272. }
  273. return property;
  274. }
  275. getVertexIndex() {
  276. if ( this.shaderStage === 'vertex' ) {
  277. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  278. }
  279. return 'vertexIndex';
  280. }
  281. buildFunctionCode( shaderNode ) {
  282. const layout = shaderNode.layout;
  283. const flowData = this.flowShaderNode( shaderNode );
  284. const parameters = [];
  285. for ( const input of layout.inputs ) {
  286. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  287. }
  288. //
  289. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  290. ${ flowData.vars }
  291. ${ flowData.code }
  292. return ${ flowData.result };
  293. }`;
  294. //
  295. return code;
  296. }
  297. getInstanceIndex() {
  298. if ( this.shaderStage === 'vertex' ) {
  299. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  300. }
  301. return 'instanceIndex';
  302. }
  303. getFrontFacing() {
  304. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  305. }
  306. getFragCoord() {
  307. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  308. }
  309. getFragDepth() {
  310. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  311. }
  312. isFlipY() {
  313. return false;
  314. }
  315. getBuiltins( shaderStage ) {
  316. const snippets = [];
  317. const builtins = this.builtins[ shaderStage ];
  318. if ( builtins !== undefined ) {
  319. for ( const { name, property, type } of builtins.values() ) {
  320. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  321. }
  322. }
  323. return snippets.join( ',\n\t' );
  324. }
  325. getAttributes( shaderStage ) {
  326. const snippets = [];
  327. if ( shaderStage === 'compute' ) {
  328. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  329. }
  330. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  331. const builtins = this.getBuiltins( 'attribute' );
  332. if ( builtins ) snippets.push( builtins );
  333. const attributes = this.getAttributesArray();
  334. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  335. const attribute = attributes[ index ];
  336. const name = attribute.name;
  337. const type = this.getType( attribute.type );
  338. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  339. }
  340. }
  341. return snippets.join( ',\n\t' );
  342. }
  343. getStructMembers( struct ) {
  344. const snippets = [];
  345. const members = struct.getMemberTypes();
  346. for ( let i = 0; i < members.length; i ++ ) {
  347. const member = members[ i ];
  348. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  349. }
  350. return snippets.join( ',\n' );
  351. }
  352. getStructs( shaderStage ) {
  353. const snippets = [];
  354. const structs = this.structs[ shaderStage ];
  355. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  356. const struct = structs[ index ];
  357. const name = struct.name;
  358. let snippet = `\struct ${ name } {\n`;
  359. snippet += this.getStructMembers( struct );
  360. snippet += '\n}';
  361. snippets.push( snippet );
  362. }
  363. return snippets.join( '\n\n' );
  364. }
  365. getVar( type, name ) {
  366. return `var ${ name } : ${ this.getType( type ) }`;
  367. }
  368. getVars( shaderStage ) {
  369. const snippets = [];
  370. const vars = this.vars[ shaderStage ];
  371. if ( vars !== undefined ) {
  372. for ( const variable of vars ) {
  373. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  374. }
  375. }
  376. return `\n${ snippets.join( '\n' ) }\n`;
  377. }
  378. getVaryings( shaderStage ) {
  379. const snippets = [];
  380. if ( shaderStage === 'vertex' ) {
  381. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  382. }
  383. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  384. const varyings = this.varyings;
  385. const vars = this.vars[ shaderStage ];
  386. for ( let index = 0; index < varyings.length; index ++ ) {
  387. const varying = varyings[ index ];
  388. if ( varying.needsInterpolation ) {
  389. let attributesSnippet = `@location( ${index} )`;
  390. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  391. attributesSnippet += ' @interpolate( flat )';
  392. }
  393. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  394. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  395. vars.push( varying );
  396. }
  397. }
  398. }
  399. const builtins = this.getBuiltins( shaderStage );
  400. if ( builtins ) snippets.push( builtins );
  401. const code = snippets.join( ',\n\t' );
  402. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  403. }
  404. getUniforms( shaderStage ) {
  405. const uniforms = this.uniforms[ shaderStage ];
  406. const bindingSnippets = [];
  407. const bufferSnippets = [];
  408. const structSnippets = [];
  409. const uniformGroups = {};
  410. let index = this.bindingsOffset[ shaderStage ];
  411. for ( const uniform of uniforms ) {
  412. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' ) {
  413. const texture = uniform.node.value;
  414. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStoreTextureNode !== true ) {
  415. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  416. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler_comparison;` );
  417. } else {
  418. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler;` );
  419. }
  420. }
  421. let textureType;
  422. if ( texture.isCubeTexture === true ) {
  423. textureType = 'texture_cube<f32>';
  424. } else if ( texture.isDataArrayTexture === true ) {
  425. textureType = 'texture_2d_array<f32>';
  426. } else if ( texture.isDepthTexture === true ) {
  427. textureType = 'texture_depth_2d';
  428. } else if ( texture.isVideoTexture === true ) {
  429. textureType = 'texture_external';
  430. } else if ( uniform.node.isStoreTextureNode === true ) {
  431. const format = getFormat( texture );
  432. textureType = `texture_storage_2d<${ format }, write>`;
  433. } else {
  434. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  435. textureType = `texture_2d<${ componentPrefix }32>`;
  436. }
  437. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name} : ${textureType};` );
  438. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  439. const bufferNode = uniform.node;
  440. const bufferType = this.getType( bufferNode.bufferType );
  441. const bufferCount = bufferNode.bufferCount;
  442. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  443. const bufferSnippet = `\t${uniform.name} : array< ${bufferType}${bufferCountSnippet} >\n`;
  444. const bufferAccessMode = bufferNode.isStorageBufferNode ? 'storage,read_write' : 'uniform';
  445. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, index ++ ) );
  446. } else {
  447. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  448. const groupName = uniform.groupNode.name;
  449. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  450. index: index ++,
  451. snippets: []
  452. } );
  453. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  454. }
  455. }
  456. for ( const name in uniformGroups ) {
  457. const group = uniformGroups[ name ];
  458. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index ) );
  459. }
  460. let code = bindingSnippets.join( '\n' );
  461. code += bufferSnippets.join( '\n' );
  462. code += structSnippets.join( '\n' );
  463. return code;
  464. }
  465. buildCode() {
  466. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  467. for ( const shaderStage in shadersData ) {
  468. const stageData = shadersData[ shaderStage ];
  469. stageData.uniforms = this.getUniforms( shaderStage );
  470. stageData.attributes = this.getAttributes( shaderStage );
  471. stageData.varyings = this.getVaryings( shaderStage );
  472. stageData.structs = this.getStructs( shaderStage );
  473. stageData.vars = this.getVars( shaderStage );
  474. stageData.codes = this.getCodes( shaderStage );
  475. //
  476. let flow = '// code\n\n';
  477. flow += this.flowCode[ shaderStage ];
  478. const flowNodes = this.flowNodes[ shaderStage ];
  479. const mainNode = flowNodes[ flowNodes.length - 1 ];
  480. const outputNode = mainNode.outputNode;
  481. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  482. for ( const node of flowNodes ) {
  483. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  484. const slotName = node.name;
  485. if ( slotName ) {
  486. if ( flow.length > 0 ) flow += '\n';
  487. flow += `\t// flow -> ${ slotName }\n\t`;
  488. }
  489. flow += `${ flowSlotData.code }\n\t`;
  490. if ( node === mainNode && shaderStage !== 'compute' ) {
  491. flow += '// result\n\n\t';
  492. if ( shaderStage === 'vertex' ) {
  493. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  494. } else if ( shaderStage === 'fragment' ) {
  495. if ( isOutputStruct ) {
  496. stageData.returnType = outputNode.nodeType;
  497. flow += `return ${ flowSlotData.result };`;
  498. } else {
  499. let structSnippet = '\t@location(0) color: vec4<f32>';
  500. const builtins = this.getBuiltins( 'output' );
  501. if ( builtins ) structSnippet += ',\n\t' + builtins;
  502. stageData.returnType = 'OutputStruct';
  503. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  504. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  505. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  506. }
  507. }
  508. }
  509. }
  510. stageData.flow = flow;
  511. }
  512. if ( this.material !== null ) {
  513. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  514. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  515. } else {
  516. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  517. }
  518. }
  519. getMethod( method, output = null ) {
  520. let wgslMethod;
  521. if ( output !== null ) {
  522. wgslMethod = this._getWGSLMethod( method + '_' + output );
  523. }
  524. if ( wgslMethod === undefined ) {
  525. wgslMethod = this._getWGSLMethod( method );
  526. }
  527. return wgslMethod || method;
  528. }
  529. getType( type ) {
  530. return wgslTypeLib[ type ] || type;
  531. }
  532. isAvailable( name ) {
  533. return supports[ name ] === true;
  534. }
  535. _getWGSLMethod( method ) {
  536. if ( wgslPolyfill[ method ] !== undefined ) {
  537. this._include( method );
  538. }
  539. return wgslMethods[ method ];
  540. }
  541. _include( name ) {
  542. const codeNode = wgslPolyfill[ name ];
  543. codeNode.build( this );
  544. if ( this.currentFunctionNode !== null ) {
  545. this.currentFunctionNode.includes.push( codeNode );
  546. }
  547. return codeNode;
  548. }
  549. _getWGSLVertexCode( shaderData ) {
  550. return `${ this.getSignature() }
  551. // uniforms
  552. ${shaderData.uniforms}
  553. // varyings
  554. ${shaderData.varyings}
  555. var<private> varyings : VaryingsStruct;
  556. // codes
  557. ${shaderData.codes}
  558. @vertex
  559. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  560. // vars
  561. ${shaderData.vars}
  562. // flow
  563. ${shaderData.flow}
  564. return varyings;
  565. }
  566. `;
  567. }
  568. _getWGSLFragmentCode( shaderData ) {
  569. return `${ this.getSignature() }
  570. // uniforms
  571. ${shaderData.uniforms}
  572. // structs
  573. ${shaderData.structs}
  574. // codes
  575. ${shaderData.codes}
  576. @fragment
  577. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  578. // vars
  579. ${shaderData.vars}
  580. // flow
  581. ${shaderData.flow}
  582. }
  583. `;
  584. }
  585. _getWGSLComputeCode( shaderData, workgroupSize ) {
  586. return `${ this.getSignature() }
  587. // system
  588. var<private> instanceIndex : u32;
  589. // uniforms
  590. ${shaderData.uniforms}
  591. // codes
  592. ${shaderData.codes}
  593. @compute @workgroup_size( ${workgroupSize} )
  594. fn main( ${shaderData.attributes} ) {
  595. // system
  596. instanceIndex = id.x;
  597. // vars
  598. ${shaderData.vars}
  599. // flow
  600. ${shaderData.flow}
  601. }
  602. `;
  603. }
  604. _getWGSLStruct( name, vars ) {
  605. return `
  606. struct ${name} {
  607. ${vars}
  608. };`;
  609. }
  610. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  611. const structName = name + 'Struct';
  612. const structSnippet = this._getWGSLStruct( structName, vars );
  613. return `${structSnippet}
  614. @binding( ${binding} ) @group( ${group} )
  615. var<${access}> ${name} : ${structName};`;
  616. }
  617. }
  618. export default WGSLNodeBuilder;