WGSLNodeBuilder.js 22 KB

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