GLSLNodeBuilder.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. import { MathNode, GLSLNodeParser, NodeBuilder, UniformNode, vectorComponents } from '../../../nodes/Nodes.js';
  2. import NodeUniformBuffer from '../../common/nodes/NodeUniformBuffer.js';
  3. import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
  4. import { NodeSampledTexture, NodeSampledCubeTexture } from '../../common/nodes/NodeSampledTexture.js';
  5. import { RedFormat, RGFormat, IntType, DataTexture, RGBAFormat, FloatType } from 'three';
  6. const glslMethods = {
  7. [ MathNode.ATAN2 ]: 'atan',
  8. textureDimensions: 'textureSize',
  9. equals: 'equal'
  10. };
  11. const precisionLib = {
  12. low: 'lowp',
  13. medium: 'mediump',
  14. high: 'highp'
  15. };
  16. const supports = {
  17. instance: true,
  18. swizzleAssign: true
  19. };
  20. const defaultPrecisions = `
  21. precision highp float;
  22. precision highp int;
  23. precision mediump sampler2DArray;
  24. precision lowp sampler2DShadow;
  25. `;
  26. class GLSLNodeBuilder extends NodeBuilder {
  27. constructor( object, renderer, scene = null ) {
  28. super( object, renderer, new GLSLNodeParser(), scene );
  29. this.uniformGroups = {};
  30. this.transforms = [];
  31. }
  32. getMethod( method ) {
  33. return glslMethods[ method ] || method;
  34. }
  35. getPropertyName( node, shaderStage ) {
  36. if ( node.isOutputStructVar ) return '';
  37. return super.getPropertyName( node, shaderStage );
  38. }
  39. buildFunctionCode( shaderNode ) {
  40. const layout = shaderNode.layout;
  41. const flowData = this.flowShaderNode( shaderNode );
  42. const parameters = [];
  43. for ( const input of layout.inputs ) {
  44. parameters.push( this.getType( input.type ) + ' ' + input.name );
  45. }
  46. //
  47. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  48. ${ flowData.vars }
  49. ${ flowData.code }
  50. return ${ flowData.result };
  51. }`;
  52. //
  53. return code;
  54. }
  55. setupPBO( storageBufferNode ) {
  56. const attribute = storageBufferNode.value;
  57. if ( attribute.pbo === undefined ) {
  58. const originalArray = attribute.array;
  59. const numElements = attribute.count * attribute.itemSize;
  60. const { itemSize } = attribute;
  61. let format = RedFormat;
  62. if ( itemSize === 2 ) {
  63. format = RGFormat;
  64. } else if ( itemSize === 3 ) {
  65. format = 6407; // patch since legacy doesn't use RGBFormat for rendering but here it's needed for packing optimization
  66. } else if ( itemSize === 4 ) {
  67. format = RGBAFormat;
  68. }
  69. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  70. let height = Math.ceil( ( numElements / itemSize ) / width );
  71. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  72. const newSize = width * height * itemSize;
  73. const newArray = new Float32Array( newSize );
  74. newArray.set( originalArray, 0 );
  75. attribute.array = newArray;
  76. const pboTexture = new DataTexture( attribute.array, width, height, format, FloatType );
  77. pboTexture.needsUpdate = true;
  78. pboTexture.isPBOTexture = true;
  79. const pbo = new UniformNode( pboTexture );
  80. pbo.setPrecision( 'high' );
  81. attribute.pboNode = pbo;
  82. attribute.pbo = pbo.value;
  83. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  84. }
  85. }
  86. generatePBO( storageArrayElementNode ) {
  87. const { node, indexNode } = storageArrayElementNode;
  88. const attribute = node.value;
  89. if ( this.renderer.backend.has( attribute ) ) {
  90. const attributeData = this.renderer.backend.get( attribute );
  91. attributeData.pbo = attribute.pbo;
  92. }
  93. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  94. const textureName = this.getPropertyName( nodeUniform );
  95. indexNode.increaseUsage( this ); // force cache generate to be used as index in x,y
  96. const indexSnippet = indexNode.build( this, 'uint' );
  97. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  98. let propertyName = elementNodeData.propertyName;
  99. if ( propertyName === undefined ) {
  100. // property element
  101. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  102. propertyName = this.getPropertyName( nodeVar );
  103. // property size
  104. const bufferNodeData = this.getDataFromNode( node );
  105. let propertySizeName = bufferNodeData.propertySizeName;
  106. if ( propertySizeName === undefined ) {
  107. propertySizeName = propertyName + 'Size';
  108. this.getVarFromNode( node, propertySizeName, 'uint' );
  109. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )` );
  110. bufferNodeData.propertySizeName = propertySizeName;
  111. }
  112. //
  113. const { itemSize } = attribute;
  114. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  115. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  116. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  117. //
  118. this.addLineFlowCode( `${ propertyName } = ${ snippet + channel }` );
  119. elementNodeData.propertyName = propertyName;
  120. }
  121. return propertyName;
  122. }
  123. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  124. if ( depthSnippet ) {
  125. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  126. } else {
  127. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  128. }
  129. }
  130. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  131. if ( texture.isDepthTexture ) {
  132. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  133. } else {
  134. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  135. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  136. }
  137. }
  138. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  139. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  140. }
  141. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  142. if ( shaderStage === 'fragment' ) {
  143. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  144. } else {
  145. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  146. }
  147. }
  148. getVars( shaderStage ) {
  149. const snippets = [];
  150. const vars = this.vars[ shaderStage ];
  151. if ( vars !== undefined ) {
  152. for ( const variable of vars ) {
  153. if ( variable.isOutputStructVar ) continue;
  154. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  155. }
  156. }
  157. return snippets.join( '\n\t' );
  158. }
  159. getUniforms( shaderStage ) {
  160. const uniforms = this.uniforms[ shaderStage ];
  161. const bindingSnippets = [];
  162. const uniformGroups = {};
  163. for ( const uniform of uniforms ) {
  164. let snippet = null;
  165. let group = false;
  166. if ( uniform.type === 'texture' ) {
  167. const texture = uniform.node.value;
  168. if ( texture.compareFunction ) {
  169. snippet = `sampler2DShadow ${ uniform.name };`;
  170. } else if ( texture.isDataArrayTexture === true ) {
  171. snippet = `sampler2DArray ${ uniform.name };`;
  172. } else {
  173. snippet = `sampler2D ${ uniform.name };`;
  174. }
  175. } else if ( uniform.type === 'cubeTexture' ) {
  176. snippet = `samplerCube ${ uniform.name };`;
  177. } else if ( uniform.type === 'buffer' ) {
  178. const bufferNode = uniform.node;
  179. const bufferType = this.getType( bufferNode.bufferType );
  180. const bufferCount = bufferNode.bufferCount;
  181. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  182. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  183. } else {
  184. const vectorType = this.getVectorType( uniform.type );
  185. snippet = `${vectorType} ${uniform.name};`;
  186. group = true;
  187. }
  188. const precision = uniform.node.precision;
  189. if ( precision !== null ) {
  190. snippet = precisionLib[ precision ] + ' ' + snippet;
  191. }
  192. if ( group ) {
  193. snippet = '\t' + snippet;
  194. const groupName = uniform.groupNode.name;
  195. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  196. groupSnippets.push( snippet );
  197. } else {
  198. snippet = 'uniform ' + snippet;
  199. bindingSnippets.push( snippet );
  200. }
  201. }
  202. let output = '';
  203. for ( const name in uniformGroups ) {
  204. const groupSnippets = uniformGroups[ name ];
  205. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  206. }
  207. output += bindingSnippets.join( '\n' );
  208. return output;
  209. }
  210. getTypeFromAttribute( attribute ) {
  211. let nodeType = super.getTypeFromAttribute( attribute );
  212. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  213. let dataAttribute = attribute;
  214. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  215. const array = dataAttribute.array;
  216. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  217. nodeType = nodeType.slice( 1 );
  218. }
  219. }
  220. return nodeType;
  221. }
  222. getAttributes( shaderStage ) {
  223. let snippet = '';
  224. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  225. const attributes = this.getAttributesArray();
  226. let location = 0;
  227. for ( const attribute of attributes ) {
  228. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  229. }
  230. }
  231. return snippet;
  232. }
  233. getStructMembers( struct ) {
  234. const snippets = [];
  235. const members = struct.getMemberTypes();
  236. for ( let i = 0; i < members.length; i ++ ) {
  237. const member = members[ i ];
  238. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  239. }
  240. return snippets.join( '\n' );
  241. }
  242. getStructs( shaderStage ) {
  243. const snippets = [];
  244. const structs = this.structs[ shaderStage ];
  245. if ( structs.length === 0 ) {
  246. return 'layout( location = 0 ) out vec4 fragColor;\n';
  247. }
  248. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  249. const struct = structs[ index ];
  250. let snippet = '\n';
  251. snippet += this.getStructMembers( struct );
  252. snippet += '\n';
  253. snippets.push( snippet );
  254. }
  255. return snippets.join( '\n\n' );
  256. }
  257. getVaryings( shaderStage ) {
  258. let snippet = '';
  259. const varyings = this.varyings;
  260. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  261. for ( const varying of varyings ) {
  262. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  263. const type = varying.type;
  264. const flat = type === 'int' || type === 'uint' ? 'flat ' : '';
  265. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  266. }
  267. } else if ( shaderStage === 'fragment' ) {
  268. for ( const varying of varyings ) {
  269. if ( varying.needsInterpolation ) {
  270. const type = varying.type;
  271. const flat = type === 'int' || type === 'uint' ? 'flat ' : '';
  272. snippet += `${flat}in ${type} ${varying.name};\n`;
  273. }
  274. }
  275. }
  276. return snippet;
  277. }
  278. getVertexIndex() {
  279. return 'uint( gl_VertexID )';
  280. }
  281. getInstanceIndex() {
  282. return 'uint( gl_InstanceID )';
  283. }
  284. getFrontFacing() {
  285. return 'gl_FrontFacing';
  286. }
  287. getFragCoord() {
  288. return 'gl_FragCoord';
  289. }
  290. getFragDepth() {
  291. return 'gl_FragDepth';
  292. }
  293. isAvailable( name ) {
  294. return supports[ name ] === true;
  295. }
  296. isFlipY() {
  297. return true;
  298. }
  299. registerTransform( varyingName, attributeNode ) {
  300. this.transforms.push( { varyingName, attributeNode } );
  301. }
  302. getTransforms( /* shaderStage */ ) {
  303. const transforms = this.transforms;
  304. let snippet = '';
  305. for ( let i = 0; i < transforms.length; i ++ ) {
  306. const transform = transforms[ i ];
  307. const attributeName = this.getPropertyName( transform.attributeNode );
  308. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  309. }
  310. return snippet;
  311. }
  312. _getGLSLUniformStruct( name, vars ) {
  313. return `
  314. layout( std140 ) uniform ${name} {
  315. ${vars}
  316. };`;
  317. }
  318. _getGLSLVertexCode( shaderData ) {
  319. return `#version 300 es
  320. ${ this.getSignature() }
  321. // precision
  322. ${ defaultPrecisions }
  323. // uniforms
  324. ${shaderData.uniforms}
  325. // varyings
  326. ${shaderData.varyings}
  327. // attributes
  328. ${shaderData.attributes}
  329. // codes
  330. ${shaderData.codes}
  331. void main() {
  332. // vars
  333. ${shaderData.vars}
  334. // transforms
  335. ${shaderData.transforms}
  336. // flow
  337. ${shaderData.flow}
  338. gl_PointSize = 1.0;
  339. }
  340. `;
  341. }
  342. _getGLSLFragmentCode( shaderData ) {
  343. return `#version 300 es
  344. ${ this.getSignature() }
  345. // precision
  346. ${ defaultPrecisions }
  347. // uniforms
  348. ${shaderData.uniforms}
  349. // varyings
  350. ${shaderData.varyings}
  351. // codes
  352. ${shaderData.codes}
  353. ${shaderData.structs}
  354. void main() {
  355. // vars
  356. ${shaderData.vars}
  357. // flow
  358. ${shaderData.flow}
  359. }
  360. `;
  361. }
  362. buildCode() {
  363. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  364. for ( const shaderStage in shadersData ) {
  365. let flow = '// code\n\n';
  366. flow += this.flowCode[ shaderStage ];
  367. const flowNodes = this.flowNodes[ shaderStage ];
  368. const mainNode = flowNodes[ flowNodes.length - 1 ];
  369. for ( const node of flowNodes ) {
  370. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  371. const slotName = node.name;
  372. if ( slotName ) {
  373. if ( flow.length > 0 ) flow += '\n';
  374. flow += `\t// flow -> ${ slotName }\n\t`;
  375. }
  376. flow += `${ flowSlotData.code }\n\t`;
  377. if ( node === mainNode && shaderStage !== 'compute' ) {
  378. flow += '// result\n\t';
  379. if ( shaderStage === 'vertex' ) {
  380. flow += 'gl_Position = ';
  381. flow += `${ flowSlotData.result };`;
  382. } else if ( shaderStage === 'fragment' ) {
  383. if ( ! node.outputNode.isOutputStructNode ) {
  384. flow += 'fragColor = ';
  385. flow += `${ flowSlotData.result };`;
  386. }
  387. }
  388. }
  389. }
  390. const stageData = shadersData[ shaderStage ];
  391. stageData.uniforms = this.getUniforms( shaderStage );
  392. stageData.attributes = this.getAttributes( shaderStage );
  393. stageData.varyings = this.getVaryings( shaderStage );
  394. stageData.vars = this.getVars( shaderStage );
  395. stageData.structs = this.getStructs( shaderStage );
  396. stageData.codes = this.getCodes( shaderStage );
  397. stageData.transforms = this.getTransforms( shaderStage );
  398. stageData.flow = flow;
  399. }
  400. if ( this.material !== null ) {
  401. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  402. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  403. } else {
  404. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  405. }
  406. }
  407. getUniformFromNode( node, type, shaderStage, name = null ) {
  408. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  409. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  410. let uniformGPU = nodeData.uniformGPU;
  411. if ( uniformGPU === undefined ) {
  412. if ( type === 'texture' ) {
  413. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node );
  414. this.bindings[ shaderStage ].push( uniformGPU );
  415. } else if ( type === 'cubeTexture' ) {
  416. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  417. this.bindings[ shaderStage ].push( uniformGPU );
  418. } else if ( type === 'buffer' ) {
  419. node.name = `NodeBuffer_${ node.id }`;
  420. uniformNode.name = `buffer${ node.id }`;
  421. const buffer = new NodeUniformBuffer( node );
  422. buffer.name = node.name;
  423. this.bindings[ shaderStage ].push( buffer );
  424. uniformGPU = buffer;
  425. } else {
  426. const group = node.groupNode;
  427. const groupName = group.name;
  428. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  429. let uniformsGroup = uniformsStage[ groupName ];
  430. if ( uniformsGroup === undefined ) {
  431. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  432. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  433. uniformsStage[ groupName ] = uniformsGroup;
  434. this.bindings[ shaderStage ].push( uniformsGroup );
  435. }
  436. uniformGPU = this.getNodeUniform( uniformNode, type );
  437. uniformsGroup.addUniform( uniformGPU );
  438. }
  439. nodeData.uniformGPU = uniformGPU;
  440. }
  441. return uniformNode;
  442. }
  443. }
  444. export default GLSLNodeBuilder;