GLSLNodeBuilder.js 16 KB

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