WGSLNodeBuilder.js 25 KB

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