WebGPUNodeBuilder.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. import WebGPUNodeUniformsGroup from './WebGPUNodeUniformsGroup.js';
  2. import {
  3. FloatNodeUniform, Vector2NodeUniform, Vector3NodeUniform, Vector4NodeUniform,
  4. ColorNodeUniform, Matrix3NodeUniform, Matrix4NodeUniform
  5. } from './WebGPUNodeUniform.js';
  6. import WebGPUNodeSampler from './WebGPUNodeSampler.js';
  7. import { WebGPUNodeSampledTexture, WebGPUNodeSampledCubeTexture } from './WebGPUNodeSampledTexture.js';
  8. import WebGPUUniformBuffer from '../WebGPUUniformBuffer.js';
  9. import { getVectorLength, getStrideLength } from '../WebGPUBufferUtils.js';
  10. import NodeBuilder from 'three-nodes/core/NodeBuilder.js';
  11. import WGSLNodeParser from 'three-nodes/parsers/WGSLNodeParser.js';
  12. import CodeNode from 'three-nodes/core/CodeNode.js';
  13. import { NodeMaterial } from 'three-nodes/materials/Materials.js';
  14. const supports = {
  15. instance: true
  16. };
  17. const wgslTypeLib = {
  18. float: 'f32',
  19. int: 'i32',
  20. uint: 'u32',
  21. bool: 'bool',
  22. vec2: 'vec2<f32>',
  23. ivec2: 'vec2<i32>',
  24. uvec2: 'vec2<u32>',
  25. bvec2: 'vec2<bool>',
  26. vec3: 'vec3<f32>',
  27. ivec3: 'vec3<i32>',
  28. uvec3: 'vec3<u32>',
  29. bvec3: 'vec3<bool>',
  30. vec4: 'vec4<f32>',
  31. ivec4: 'vec4<i32>',
  32. uvec4: 'vec4<u32>',
  33. bvec4: 'vec4<bool>',
  34. mat3: 'mat3x3<f32>',
  35. imat3: 'mat3x3<i32>',
  36. umat3: 'mat3x3<u32>',
  37. bmat3: 'mat3x3<bool>',
  38. mat4: 'mat4x4<f32>',
  39. imat4: 'mat4x4<i32>',
  40. umat4: 'mat4x4<u32>',
  41. bmat4: 'mat4x4<bool>'
  42. };
  43. const wgslMethods = {
  44. dFdx: 'dpdx',
  45. dFdy: 'dpdy',
  46. inversesqrt: 'inverseSqrt'
  47. };
  48. const wgslPolyfill = {
  49. lessThanEqual: new CodeNode( `
  50. fn lessThanEqual( a : vec3<f32>, b : vec3<f32> ) -> vec3<bool> {
  51. return vec3<bool>( a.x <= b.x, a.y <= b.y, a.z <= b.z );
  52. }
  53. ` ),
  54. mod: new CodeNode( `
  55. fn mod( x : f32, y : f32 ) -> f32 {
  56. return x - y * floor( x / y );
  57. }
  58. ` ),
  59. repeatWrapping: new CodeNode( `
  60. fn repeatWrapping( uv : vec2<f32>, dimension : vec2<i32> ) -> vec2<i32> {
  61. let uvScaled = vec2<i32>( uv * vec2<f32>( dimension ) );
  62. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  63. }
  64. ` )
  65. };
  66. class WebGPUNodeBuilder extends NodeBuilder {
  67. constructor( object, renderer ) {
  68. super( object, renderer, new WGSLNodeParser() );
  69. this.lightNode = null;
  70. this.fogNode = null;
  71. this.bindings = { vertex: [], fragment: [] };
  72. this.bindingsOffset = { vertex: 0, fragment: 0 };
  73. this.uniformsGroup = {};
  74. this.builtins = new Set();
  75. }
  76. build() {
  77. NodeMaterial.fromMaterial( this.material ).build( this );
  78. return super.build();
  79. }
  80. addFlowCode( code ) {
  81. if ( ! /;\s*$/.test( code ) ) {
  82. code += ';';
  83. }
  84. super.addFlowCode( code + '\n\t' );
  85. }
  86. getSampler( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  87. if ( shaderStage === 'fragment' ) {
  88. return `textureSample( ${textureProperty}, ${textureProperty}_sampler, ${uvSnippet} )`;
  89. } else {
  90. this._include( 'repeatWrapping' );
  91. const dimension = `textureDimensions( ${textureProperty}, 0 )`;
  92. return `textureLoad( ${textureProperty}, repeatWrapping( ${uvSnippet}, ${dimension} ), 0 )`;
  93. }
  94. }
  95. getSamplerBias( textureProperty, uvSnippet, biasSnippet, shaderStage = this.shaderStage ) {
  96. if ( shaderStage === 'fragment' ) {
  97. return `textureSampleBias( ${textureProperty}, ${textureProperty}_sampler, ${uvSnippet}, ${biasSnippet} )`;
  98. } else {
  99. this._include( 'repeatWrapping' );
  100. const dimension = `textureDimensions( ${textureProperty}, 0 )`;
  101. return `textureLoad( ${textureProperty}, repeatWrapping( ${uvSnippet}, ${dimension} ), i32( ${biasSnippet} ) )`;
  102. }
  103. }
  104. getTexture( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  105. return this.getSampler( textureProperty, uvSnippet, shaderStage );
  106. }
  107. getTextureBias( textureProperty, uvSnippet, biasSnippet, shaderStage = this.shaderStage ) {
  108. return this.getSamplerBias( textureProperty, uvSnippet, biasSnippet, shaderStage );
  109. }
  110. getCubeTexture( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  111. return this.getSampler( textureProperty, uvSnippet, shaderStage );
  112. }
  113. getCubeTextureBias( textureProperty, uvSnippet, biasSnippet, shaderStage = this.shaderStage ) {
  114. return this.getSamplerBias( textureProperty, uvSnippet, biasSnippet, shaderStage );
  115. }
  116. getPropertyName( node, shaderStage = this.shaderStage ) {
  117. if ( node.isNodeVary === true ) {
  118. if ( shaderStage === 'vertex' ) {
  119. return `NodeVarys.${ node.name }`;
  120. }
  121. } else if ( node.isNodeUniform === true ) {
  122. const name = node.name;
  123. const type = node.type;
  124. if ( type === 'texture' || type === 'cubeTexture' ) {
  125. return name;
  126. } else if ( type === 'buffer' ) {
  127. return `NodeBuffer_${node.node.id}.${name}`;
  128. } else {
  129. return `NodeUniforms.${name}`;
  130. }
  131. }
  132. return super.getPropertyName( node );
  133. }
  134. getBindings() {
  135. const bindings = this.bindings;
  136. return [ ...bindings.vertex, ...bindings.fragment ];
  137. }
  138. getUniformFromNode( node, shaderStage, type ) {
  139. const uniformNode = super.getUniformFromNode( node, shaderStage, type );
  140. const nodeData = this.getDataFromNode( node, shaderStage );
  141. if ( nodeData.uniformGPU === undefined ) {
  142. let uniformGPU;
  143. const bindings = this.bindings[ shaderStage ];
  144. if ( type === 'texture' || type === 'cubeTexture' ) {
  145. const sampler = new WebGPUNodeSampler( `${uniformNode.name}_sampler`, uniformNode.node );
  146. let texture = null;
  147. if ( type === 'texture' ) {
  148. texture = new WebGPUNodeSampledTexture( uniformNode.name, uniformNode.node );
  149. } else if ( type === 'cubeTexture' ) {
  150. texture = new WebGPUNodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  151. }
  152. // add first textures in sequence and group for last
  153. const lastBinding = bindings[ bindings.length - 1 ];
  154. const index = lastBinding && lastBinding.isUniformsGroup ? bindings.length - 1 : bindings.length;
  155. if ( shaderStage === 'fragment' ) {
  156. bindings.splice( index, 0, sampler, texture );
  157. uniformGPU = [ sampler, texture ];
  158. } else {
  159. bindings.splice( index, 0, texture );
  160. uniformGPU = [ texture ];
  161. }
  162. } else if ( type === 'buffer' ) {
  163. const buffer = new WebGPUUniformBuffer( 'NodeBuffer_' + node.id, node.value );
  164. // add first textures in sequence and group for last
  165. const lastBinding = bindings[ bindings.length - 1 ];
  166. const index = lastBinding && lastBinding.isUniformsGroup ? bindings.length - 1 : bindings.length;
  167. bindings.splice( index, 0, buffer );
  168. uniformGPU = buffer;
  169. } else {
  170. let uniformsGroup = this.uniformsGroup[ shaderStage ];
  171. if ( uniformsGroup === undefined ) {
  172. uniformsGroup = new WebGPUNodeUniformsGroup( shaderStage );
  173. this.uniformsGroup[ shaderStage ] = uniformsGroup;
  174. bindings.push( uniformsGroup );
  175. }
  176. if ( node.isArrayUniformNode === true ) {
  177. uniformGPU = [];
  178. for ( const uniformNode of node.nodes ) {
  179. const uniformNodeGPU = this._getNodeUniform( uniformNode, type );
  180. // fit bounds to buffer
  181. uniformNodeGPU.boundary = getVectorLength( uniformNodeGPU.itemSize );
  182. uniformNodeGPU.itemSize = getStrideLength( uniformNodeGPU.itemSize );
  183. uniformsGroup.addUniform( uniformNodeGPU );
  184. uniformGPU.push( uniformNodeGPU );
  185. }
  186. } else {
  187. uniformGPU = this._getNodeUniform( uniformNode, type );
  188. uniformsGroup.addUniform( uniformGPU );
  189. }
  190. }
  191. nodeData.uniformGPU = uniformGPU;
  192. if ( shaderStage === 'vertex' ) {
  193. this.bindingsOffset[ 'fragment' ] = bindings.length;
  194. }
  195. }
  196. return uniformNode;
  197. }
  198. isReference( type ) {
  199. return super.isReference( type ) || type === 'texture_2d' || type === 'texture_cube';
  200. }
  201. getInstanceIndex( shaderStage = this.shaderStage ) {
  202. this.builtins.add( 'instance_index' );
  203. if ( shaderStage === 'vertex' ) {
  204. return 'instanceIndex';
  205. }
  206. }
  207. getAttributes( shaderStage ) {
  208. const snippets = [];
  209. if ( shaderStage === 'vertex' ) {
  210. if ( this.builtins.has( 'instance_index' ) ) {
  211. snippets.push( `@builtin( instance_index ) instanceIndex : u32` );
  212. }
  213. const attributes = this.attributes;
  214. const length = attributes.length;
  215. for ( let index = 0; index < length; index ++ ) {
  216. const attribute = attributes[ index ];
  217. const name = attribute.name;
  218. const type = this.getType( attribute.type );
  219. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  220. }
  221. }
  222. return snippets.join( ',\n\t' );
  223. }
  224. getVars( shaderStage ) {
  225. const snippets = [];
  226. const vars = this.vars[ shaderStage ];
  227. for ( let index = 0; index < vars.length; index ++ ) {
  228. const variable = vars[ index ];
  229. const name = variable.name;
  230. const type = this.getType( variable.type );
  231. snippets.push( `\tvar ${name} : ${type};` );
  232. }
  233. return `\n${ snippets.join( '\n' ) }\n`;
  234. }
  235. getVarys( shaderStage ) {
  236. const snippets = [];
  237. if ( shaderStage === 'vertex' ) {
  238. snippets.push( '@builtin( position ) Vertex: vec4<f32>' );
  239. const varys = this.varys;
  240. for ( let index = 0; index < varys.length; index ++ ) {
  241. const vary = varys[ index ];
  242. snippets.push( `@location( ${index} ) ${ vary.name } : ${ this.getType( vary.type ) }` );
  243. }
  244. } else if ( shaderStage === 'fragment' ) {
  245. const varys = this.varys;
  246. for ( let index = 0; index < varys.length; index ++ ) {
  247. const vary = varys[ index ];
  248. snippets.push( `@location( ${index} ) ${ vary.name } : ${ this.getType( vary.type ) }` );
  249. }
  250. }
  251. const code = snippets.join( ',\n\t' );
  252. return shaderStage === 'vertex' ? this._getWGSLStruct( 'NodeVarysStruct', '\t' + code ) : code;
  253. }
  254. getUniforms( shaderStage ) {
  255. const uniforms = this.uniforms[ shaderStage ];
  256. const bindingSnippets = [];
  257. const bufferSnippets = [];
  258. const groupSnippets = [];
  259. let index = this.bindingsOffset[ shaderStage ];
  260. for ( const uniform of uniforms ) {
  261. if ( uniform.type === 'texture' ) {
  262. if ( shaderStage === 'fragment' ) {
  263. bindingSnippets.push( `@group( 0 ) @binding( ${index ++} ) var ${uniform.name}_sampler : sampler;` );
  264. }
  265. bindingSnippets.push( `@group( 0 ) @binding( ${index ++} ) var ${uniform.name} : texture_2d<f32>;` );
  266. } else if ( uniform.type === 'cubeTexture' ) {
  267. if ( shaderStage === 'fragment' ) {
  268. bindingSnippets.push( `@group( 0 ) @binding( ${index ++} ) var ${uniform.name}_sampler : sampler;` );
  269. }
  270. bindingSnippets.push( `@group( 0 ) @binding( ${index ++} ) var ${uniform.name} : texture_cube<f32>;` );
  271. } else if ( uniform.type === 'buffer' ) {
  272. const bufferNode = uniform.node;
  273. const bufferType = this.getType( bufferNode.bufferType );
  274. const bufferCount = bufferNode.bufferCount;
  275. const bufferSnippet = `\t${uniform.name} : array< ${bufferType}, ${bufferCount} >\n`;
  276. bufferSnippets.push( this._getWGSLUniforms( 'NodeBuffer_' + bufferNode.id, bufferSnippet, index ++ ) );
  277. } else {
  278. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  279. if ( Array.isArray( uniform.value ) === true ) {
  280. const length = uniform.value.length;
  281. groupSnippets.push( `uniform ${vectorType}[ ${length} ] ${uniform.name}` );
  282. } else {
  283. groupSnippets.push( `\t${uniform.name} : ${ vectorType}` );
  284. }
  285. }
  286. }
  287. let code = bindingSnippets.join( '\n' );
  288. code += bufferSnippets.join( '\n' );
  289. if ( groupSnippets.length > 0 ) {
  290. code += this._getWGSLUniforms( 'NodeUniforms', groupSnippets.join( ',\n' ), index ++ );
  291. }
  292. return code;
  293. }
  294. buildCode() {
  295. const shadersData = { fragment: {}, vertex: {} };
  296. for ( const shaderStage in shadersData ) {
  297. let flow = '// code\n';
  298. flow += `\t${ this.flowCode[ shaderStage ] }`;
  299. flow += '\n\t';
  300. const flowNodes = this.flowNodes[ shaderStage ];
  301. const mainNode = flowNodes[ flowNodes.length - 1 ];
  302. for ( const node of flowNodes ) {
  303. const flowSlotData = this.getFlowData( shaderStage, node );
  304. const slotName = node.name;
  305. if ( slotName ) {
  306. if ( flow.length > 0 ) flow += '\n';
  307. flow += `\t// FLOW -> ${ slotName }\n\t`;
  308. }
  309. flow += `${ flowSlotData.code }\n\t`;
  310. if ( node === mainNode ) {
  311. flow += '// FLOW RESULT\n\t';
  312. if ( shaderStage === 'vertex' ) {
  313. flow += 'NodeVarys.Vertex = ';
  314. } else if ( shaderStage === 'fragment' ) {
  315. flow += 'return ';
  316. }
  317. flow += `${ flowSlotData.result };`;
  318. }
  319. }
  320. const stageData = shadersData[ shaderStage ];
  321. stageData.uniforms = this.getUniforms( shaderStage );
  322. stageData.attributes = this.getAttributes( shaderStage );
  323. stageData.varys = this.getVarys( shaderStage );
  324. stageData.vars = this.getVars( shaderStage );
  325. stageData.codes = this.getCodes( shaderStage );
  326. stageData.flow = flow;
  327. }
  328. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  329. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  330. }
  331. getMethod( method ) {
  332. if ( wgslPolyfill[ method ] !== undefined ) {
  333. this._include( method );
  334. }
  335. return wgslMethods[ method ] || method;
  336. }
  337. getType( type ) {
  338. return wgslTypeLib[ type ] || type;
  339. }
  340. isAvailable( name ) {
  341. return supports[ name ] === true;
  342. }
  343. _include( name ) {
  344. wgslPolyfill[ name ].build( this );
  345. }
  346. _getNodeUniform( uniformNode, type ) {
  347. if ( type === 'float' ) return new FloatNodeUniform( uniformNode );
  348. if ( type === 'vec2' ) return new Vector2NodeUniform( uniformNode );
  349. if ( type === 'vec3' ) return new Vector3NodeUniform( uniformNode );
  350. if ( type === 'vec4' ) return new Vector4NodeUniform( uniformNode );
  351. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  352. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  353. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  354. throw new Error( `Uniform "${type}" not declared.` );
  355. }
  356. _getWGSLVertexCode( shaderData ) {
  357. return `${ this.getSignature() }
  358. // uniforms
  359. ${shaderData.uniforms}
  360. // varys
  361. ${shaderData.varys}
  362. // codes
  363. ${shaderData.codes}
  364. @stage( vertex )
  365. fn main( ${shaderData.attributes} ) -> NodeVarysStruct {
  366. // system
  367. var NodeVarys: NodeVarysStruct;
  368. // vars
  369. ${shaderData.vars}
  370. // flow
  371. ${shaderData.flow}
  372. return NodeVarys;
  373. }
  374. `;
  375. }
  376. _getWGSLFragmentCode( shaderData ) {
  377. return `${ this.getSignature() }
  378. // uniforms
  379. ${shaderData.uniforms}
  380. // codes
  381. ${shaderData.codes}
  382. @stage( fragment )
  383. fn main( ${shaderData.varys} ) -> @location( 0 ) vec4<f32> {
  384. // vars
  385. ${shaderData.vars}
  386. // flow
  387. ${shaderData.flow}
  388. }
  389. `;
  390. }
  391. _getWGSLStruct( name, vars ) {
  392. return `
  393. struct ${name} {
  394. ${vars}
  395. };`;
  396. }
  397. _getWGSLUniforms( name, vars, binding = 0, group = 0 ) {
  398. const structName = name + 'Struct';
  399. const structSnippet = this._getWGSLStruct( structName, vars );
  400. return `${structSnippet}
  401. @binding( ${binding} ) @group( ${group} )
  402. var<uniform> ${name} : ${structName};`;
  403. }
  404. }
  405. export default WebGPUNodeBuilder;