2
0

WGSLNodeBuilder.js 24 KB

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