WGSLNodeBuilder.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  166. if ( shaderStage === 'fragment' ) {
  167. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  168. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  169. } else {
  170. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  171. }
  172. }
  173. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  174. if ( shaderStage === 'fragment' ) {
  175. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  176. } else {
  177. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  178. }
  179. }
  180. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  181. let snippet = null;
  182. if ( texture.isVideoTexture === true ) {
  183. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  184. } else {
  185. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  186. }
  187. return snippet;
  188. }
  189. getPropertyName( node, shaderStage = this.shaderStage ) {
  190. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  191. if ( shaderStage === 'vertex' ) {
  192. return `varyings.${ node.name }`;
  193. }
  194. } else if ( node.isNodeUniform === true ) {
  195. const name = node.name;
  196. const type = node.type;
  197. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) {
  198. return name;
  199. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  200. return `NodeBuffer_${ node.id }.${name}`;
  201. } else {
  202. return node.groupNode.name + '.' + name;
  203. }
  204. }
  205. return super.getPropertyName( node );
  206. }
  207. _getUniformGroupCount( shaderStage ) {
  208. return Object.keys( this.uniforms[ shaderStage ] ).length;
  209. }
  210. getFunctionOperator( op ) {
  211. const fnOp = wgslFnOpLib[ op ];
  212. if ( fnOp !== undefined ) {
  213. this._include( fnOp );
  214. return fnOp;
  215. }
  216. return null;
  217. }
  218. getUniformFromNode( node, type, shaderStage, name = null ) {
  219. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  220. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  221. if ( nodeData.uniformGPU === undefined ) {
  222. let uniformGPU;
  223. const bindings = this.bindings[ shaderStage ];
  224. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) {
  225. let texture = null;
  226. if ( type === 'texture' || type === 'storageTexture' ) {
  227. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node );
  228. } else if ( type === 'cubeTexture' ) {
  229. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  230. }
  231. texture.store = node.isStoreTextureNode === true;
  232. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  233. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  234. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node );
  235. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  236. bindings.push( sampler, texture );
  237. uniformGPU = [ sampler, texture ];
  238. } else {
  239. bindings.push( texture );
  240. uniformGPU = [ texture ];
  241. }
  242. } else if ( type === 'buffer' || type === 'storageBuffer' ) {
  243. const bufferClass = type === 'storageBuffer' ? NodeStorageBuffer : NodeUniformBuffer;
  244. const buffer = new bufferClass( node );
  245. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  246. bindings.push( buffer );
  247. uniformGPU = buffer;
  248. } else {
  249. const group = node.groupNode;
  250. const groupName = group.name;
  251. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  252. let uniformsGroup = uniformsStage[ groupName ];
  253. if ( uniformsGroup === undefined ) {
  254. uniformsGroup = new NodeUniformsGroup( groupName, group );
  255. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  256. uniformsStage[ groupName ] = uniformsGroup;
  257. bindings.push( uniformsGroup );
  258. }
  259. uniformGPU = this.getNodeUniform( uniformNode, type );
  260. uniformsGroup.addUniform( uniformGPU );
  261. }
  262. nodeData.uniformGPU = uniformGPU;
  263. if ( shaderStage === 'vertex' ) {
  264. this.bindingsOffset[ 'fragment' ] = bindings.length;
  265. }
  266. }
  267. return uniformNode;
  268. }
  269. isReference( type ) {
  270. return super.isReference( type ) || type === 'texture_2d' || type === 'texture_cube' || type === 'texture_depth_2d' || type === 'texture_storage_2d';
  271. }
  272. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  273. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  274. if ( map.has( name ) === false ) {
  275. map.set( name, {
  276. name,
  277. property,
  278. type
  279. } );
  280. }
  281. return property;
  282. }
  283. getVertexIndex() {
  284. if ( this.shaderStage === 'vertex' ) {
  285. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  286. }
  287. return 'vertexIndex';
  288. }
  289. buildFunctionCode( shaderNode ) {
  290. const layout = shaderNode.layout;
  291. const flowData = this.flowShaderNode( shaderNode );
  292. const parameters = [];
  293. for ( const input of layout.inputs ) {
  294. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  295. }
  296. //
  297. const code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  298. ${ flowData.vars }
  299. ${ flowData.code }
  300. return ${ flowData.result };
  301. }`;
  302. //
  303. return code;
  304. }
  305. getInstanceIndex() {
  306. if ( this.shaderStage === 'vertex' ) {
  307. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  308. }
  309. return 'instanceIndex';
  310. }
  311. getFrontFacing() {
  312. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  313. }
  314. getFragCoord() {
  315. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xyz';
  316. }
  317. getFragDepth() {
  318. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  319. }
  320. isFlipY() {
  321. return false;
  322. }
  323. getBuiltins( shaderStage ) {
  324. const snippets = [];
  325. const builtins = this.builtins[ shaderStage ];
  326. if ( builtins !== undefined ) {
  327. for ( const { name, property, type } of builtins.values() ) {
  328. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  329. }
  330. }
  331. return snippets.join( ',\n\t' );
  332. }
  333. getAttributes( shaderStage ) {
  334. const snippets = [];
  335. if ( shaderStage === 'compute' ) {
  336. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  337. }
  338. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  339. const builtins = this.getBuiltins( 'attribute' );
  340. if ( builtins ) snippets.push( builtins );
  341. const attributes = this.getAttributesArray();
  342. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  343. const attribute = attributes[ index ];
  344. const name = attribute.name;
  345. const type = this.getType( attribute.type );
  346. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  347. }
  348. }
  349. return snippets.join( ',\n\t' );
  350. }
  351. getStructMembers( struct ) {
  352. const snippets = [];
  353. const members = struct.getMemberTypes();
  354. for ( let i = 0; i < members.length; i ++ ) {
  355. const member = members[ i ];
  356. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  357. }
  358. return snippets.join( ',\n' );
  359. }
  360. getStructs( shaderStage ) {
  361. const snippets = [];
  362. const structs = this.structs[ shaderStage ];
  363. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  364. const struct = structs[ index ];
  365. const name = struct.name;
  366. let snippet = `\struct ${ name } {\n`;
  367. snippet += this.getStructMembers( struct );
  368. snippet += '\n}';
  369. snippets.push( snippet );
  370. }
  371. return snippets.join( '\n\n' );
  372. }
  373. getVar( type, name ) {
  374. return `var ${ name } : ${ this.getType( type ) }`;
  375. }
  376. getVars( shaderStage ) {
  377. const snippets = [];
  378. const vars = this.vars[ shaderStage ];
  379. if ( vars !== undefined ) {
  380. for ( const variable of vars ) {
  381. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  382. }
  383. }
  384. return `\n${ snippets.join( '\n' ) }\n`;
  385. }
  386. getVaryings( shaderStage ) {
  387. const snippets = [];
  388. if ( shaderStage === 'vertex' ) {
  389. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  390. }
  391. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  392. const varyings = this.varyings;
  393. const vars = this.vars[ shaderStage ];
  394. for ( let index = 0; index < varyings.length; index ++ ) {
  395. const varying = varyings[ index ];
  396. if ( varying.needsInterpolation ) {
  397. let attributesSnippet = `@location( ${index} )`;
  398. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  399. attributesSnippet += ' @interpolate( flat )';
  400. }
  401. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  402. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  403. vars.push( varying );
  404. }
  405. }
  406. }
  407. const builtins = this.getBuiltins( shaderStage );
  408. if ( builtins ) snippets.push( builtins );
  409. const code = snippets.join( ',\n\t' );
  410. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  411. }
  412. getUniforms( shaderStage ) {
  413. const uniforms = this.uniforms[ shaderStage ];
  414. const bindingSnippets = [];
  415. const bufferSnippets = [];
  416. const structSnippets = [];
  417. const uniformGroups = {};
  418. let index = this.bindingsOffset[ shaderStage ];
  419. for ( const uniform of uniforms ) {
  420. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' ) {
  421. const texture = uniform.node.value;
  422. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStoreTextureNode !== true ) {
  423. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  424. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler_comparison;` );
  425. } else {
  426. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name}_sampler : sampler;` );
  427. }
  428. }
  429. let textureType;
  430. if ( texture.isCubeTexture === true ) {
  431. textureType = 'texture_cube<f32>';
  432. } else if ( texture.isDataArrayTexture === true ) {
  433. textureType = 'texture_2d_array<f32>';
  434. } else if ( texture.isDepthTexture === true ) {
  435. textureType = 'texture_depth_2d';
  436. } else if ( texture.isVideoTexture === true ) {
  437. textureType = 'texture_external';
  438. } else if ( uniform.node.isStoreTextureNode === true ) {
  439. const format = getFormat( texture );
  440. textureType = `texture_storage_2d<${ format }, write>`;
  441. } else {
  442. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  443. textureType = `texture_2d<${ componentPrefix }32>`;
  444. }
  445. bindingSnippets.push( `@binding( ${index ++} ) @group( 0 ) var ${uniform.name} : ${textureType};` );
  446. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' ) {
  447. const bufferNode = uniform.node;
  448. const bufferType = this.getType( bufferNode.bufferType );
  449. const bufferCount = bufferNode.bufferCount;
  450. const bufferCountSnippet = bufferCount > 0 ? ', ' + bufferCount : '';
  451. const bufferSnippet = `\t${uniform.name} : array< ${bufferType}${bufferCountSnippet} >\n`;
  452. const bufferAccessMode = bufferNode.isStorageBufferNode ? 'storage,read_write' : 'uniform';
  453. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, index ++ ) );
  454. } else {
  455. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  456. const groupName = uniform.groupNode.name;
  457. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  458. index: index ++,
  459. snippets: []
  460. } );
  461. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  462. }
  463. }
  464. for ( const name in uniformGroups ) {
  465. const group = uniformGroups[ name ];
  466. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index ) );
  467. }
  468. let code = bindingSnippets.join( '\n' );
  469. code += bufferSnippets.join( '\n' );
  470. code += structSnippets.join( '\n' );
  471. return code;
  472. }
  473. buildCode() {
  474. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  475. for ( const shaderStage in shadersData ) {
  476. const stageData = shadersData[ shaderStage ];
  477. stageData.uniforms = this.getUniforms( shaderStage );
  478. stageData.attributes = this.getAttributes( shaderStage );
  479. stageData.varyings = this.getVaryings( shaderStage );
  480. stageData.structs = this.getStructs( shaderStage );
  481. stageData.vars = this.getVars( shaderStage );
  482. stageData.codes = this.getCodes( shaderStage );
  483. //
  484. let flow = '// code\n\n';
  485. flow += this.flowCode[ shaderStage ];
  486. const flowNodes = this.flowNodes[ shaderStage ];
  487. const mainNode = flowNodes[ flowNodes.length - 1 ];
  488. const outputNode = mainNode.outputNode;
  489. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  490. for ( const node of flowNodes ) {
  491. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  492. const slotName = node.name;
  493. if ( slotName ) {
  494. if ( flow.length > 0 ) flow += '\n';
  495. flow += `\t// flow -> ${ slotName }\n\t`;
  496. }
  497. flow += `${ flowSlotData.code }\n\t`;
  498. if ( node === mainNode && shaderStage !== 'compute' ) {
  499. flow += '// result\n\n\t';
  500. if ( shaderStage === 'vertex' ) {
  501. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  502. } else if ( shaderStage === 'fragment' ) {
  503. if ( isOutputStruct ) {
  504. stageData.returnType = outputNode.nodeType;
  505. flow += `return ${ flowSlotData.result };`;
  506. } else {
  507. let structSnippet = '\t@location(0) color: vec4<f32>';
  508. const builtins = this.getBuiltins( 'output' );
  509. if ( builtins ) structSnippet += ',\n\t' + builtins;
  510. stageData.returnType = 'OutputStruct';
  511. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  512. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  513. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  514. }
  515. }
  516. }
  517. }
  518. stageData.flow = flow;
  519. }
  520. if ( this.material !== null ) {
  521. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  522. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  523. } else {
  524. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  525. }
  526. }
  527. getMethod( method, output = null ) {
  528. let wgslMethod;
  529. if ( output !== null ) {
  530. wgslMethod = this._getWGSLMethod( method + '_' + output );
  531. }
  532. if ( wgslMethod === undefined ) {
  533. wgslMethod = this._getWGSLMethod( method );
  534. }
  535. return wgslMethod || method;
  536. }
  537. getType( type ) {
  538. return wgslTypeLib[ type ] || type;
  539. }
  540. isAvailable( name ) {
  541. return supports[ name ] === true;
  542. }
  543. _getWGSLMethod( method ) {
  544. if ( wgslPolyfill[ method ] !== undefined ) {
  545. this._include( method );
  546. }
  547. return wgslMethods[ method ];
  548. }
  549. _include( name ) {
  550. const codeNode = wgslPolyfill[ name ];
  551. codeNode.build( this );
  552. if ( this.currentFunctionNode !== null ) {
  553. this.currentFunctionNode.includes.push( codeNode );
  554. }
  555. return codeNode;
  556. }
  557. _getWGSLVertexCode( shaderData ) {
  558. return `${ this.getSignature() }
  559. // uniforms
  560. ${shaderData.uniforms}
  561. // varyings
  562. ${shaderData.varyings}
  563. var<private> varyings : VaryingsStruct;
  564. // codes
  565. ${shaderData.codes}
  566. @vertex
  567. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  568. // vars
  569. ${shaderData.vars}
  570. // flow
  571. ${shaderData.flow}
  572. return varyings;
  573. }
  574. `;
  575. }
  576. _getWGSLFragmentCode( shaderData ) {
  577. return `${ this.getSignature() }
  578. // uniforms
  579. ${shaderData.uniforms}
  580. // structs
  581. ${shaderData.structs}
  582. // codes
  583. ${shaderData.codes}
  584. @fragment
  585. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  586. // vars
  587. ${shaderData.vars}
  588. // flow
  589. ${shaderData.flow}
  590. }
  591. `;
  592. }
  593. _getWGSLComputeCode( shaderData, workgroupSize ) {
  594. return `${ this.getSignature() }
  595. // system
  596. var<private> instanceIndex : u32;
  597. // uniforms
  598. ${shaderData.uniforms}
  599. // codes
  600. ${shaderData.codes}
  601. @compute @workgroup_size( ${workgroupSize} )
  602. fn main( ${shaderData.attributes} ) {
  603. // system
  604. instanceIndex = id.x;
  605. // vars
  606. ${shaderData.vars}
  607. // flow
  608. ${shaderData.flow}
  609. }
  610. `;
  611. }
  612. _getWGSLStruct( name, vars ) {
  613. return `
  614. struct ${name} {
  615. ${vars}
  616. };`;
  617. }
  618. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  619. const structName = name + 'Struct';
  620. const structSnippet = this._getWGSLStruct( structName, vars );
  621. return `${structSnippet}
  622. @binding( ${binding} ) @group( ${group} )
  623. var<${access}> ${name} : ${structName};`;
  624. }
  625. }
  626. export default WGSLNodeBuilder;