GLSLNodeBuilder.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. import { MathNode, GLSLNodeParser, NodeBuilder } from '../../../nodes/Nodes.js';
  2. import UniformBuffer from '../../common/UniformBuffer.js';
  3. import NodeUniformsGroup from '../../common/nodes/NodeUniformsGroup.js';
  4. import { NodeSampledTexture, NodeSampledCubeTexture } from '../../common/nodes/NodeSampledTexture.js';
  5. import { IntType } from 'three';
  6. const glslMethods = {
  7. [ MathNode.ATAN2 ]: 'atan',
  8. textureDimensions: 'textureSize'
  9. };
  10. const precisionLib = {
  11. low: 'lowp',
  12. medium: 'mediump',
  13. high: 'highp'
  14. };
  15. const supports = {
  16. instance: true
  17. };
  18. const defaultPrecisions = `
  19. precision highp float;
  20. precision highp int;
  21. precision mediump sampler2DArray;
  22. precision lowp sampler2DShadow;
  23. `;
  24. class GLSLNodeBuilder extends NodeBuilder {
  25. constructor( object, renderer, scene = null ) {
  26. super( object, renderer, new GLSLNodeParser(), scene );
  27. this.uniformGroups = {};
  28. this.transforms = [];
  29. }
  30. getMethod( method ) {
  31. return glslMethods[ method ] || method;
  32. }
  33. getPropertyName( node, shaderStage ) {
  34. if ( node.isOutputStructVar ) return '';
  35. return super.getPropertyName( node, shaderStage );
  36. }
  37. buildFunctionCode( shaderNode ) {
  38. const layout = shaderNode.layout;
  39. const flowData = this.flowShaderNode( shaderNode );
  40. const parameters = [];
  41. for ( const input of layout.inputs ) {
  42. parameters.push( this.getType( input.type ) + ' ' + input.name );
  43. }
  44. //
  45. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  46. ${ flowData.vars }
  47. ${ flowData.code }
  48. return ${ flowData.result };
  49. }`;
  50. //
  51. return code;
  52. }
  53. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  54. if ( depthSnippet ) {
  55. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  56. } else {
  57. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  58. }
  59. }
  60. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  61. if ( texture.isDepthTexture ) {
  62. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  63. } else {
  64. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  65. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  66. }
  67. }
  68. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  69. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  70. }
  71. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  72. if ( shaderStage === 'fragment' ) {
  73. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  74. } else {
  75. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  76. }
  77. }
  78. getVars( shaderStage ) {
  79. const snippets = [];
  80. const vars = this.vars[ shaderStage ];
  81. if ( vars !== undefined ) {
  82. for ( const variable of vars ) {
  83. if ( variable.isOutputStructVar ) continue;
  84. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  85. }
  86. }
  87. return snippets.join( '\n\t' );
  88. }
  89. getUniforms( shaderStage ) {
  90. const uniforms = this.uniforms[ shaderStage ];
  91. const bindingSnippets = [];
  92. const uniformGroups = {};
  93. for ( const uniform of uniforms ) {
  94. let snippet = null;
  95. let group = false;
  96. if ( uniform.type === 'texture' ) {
  97. const texture = uniform.node.value;
  98. if ( texture.compareFunction ) {
  99. snippet = `sampler2DShadow ${ uniform.name };`;
  100. } else if ( texture.isDataArrayTexture === true ) {
  101. snippet = `sampler2DArray ${ uniform.name };`;
  102. } else {
  103. snippet = `sampler2D ${ uniform.name };`;
  104. }
  105. } else if ( uniform.type === 'cubeTexture' ) {
  106. snippet = `samplerCube ${ uniform.name };`;
  107. } else if ( uniform.type === 'buffer' ) {
  108. const bufferNode = uniform.node;
  109. const bufferType = this.getType( bufferNode.bufferType );
  110. const bufferCount = bufferNode.bufferCount;
  111. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  112. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  113. } else {
  114. const vectorType = this.getVectorType( uniform.type );
  115. snippet = `${vectorType} ${uniform.name};`;
  116. group = true;
  117. }
  118. const precision = uniform.node.precision;
  119. if ( precision !== null ) {
  120. snippet = precisionLib[ precision ] + ' ' + snippet;
  121. }
  122. if ( group ) {
  123. snippet = '\t' + snippet;
  124. const groupName = uniform.groupNode.name;
  125. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  126. groupSnippets.push( snippet );
  127. } else {
  128. snippet = 'uniform ' + snippet;
  129. bindingSnippets.push( snippet );
  130. }
  131. }
  132. let output = '';
  133. for ( const name in uniformGroups ) {
  134. const groupSnippets = uniformGroups[ name ];
  135. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  136. }
  137. output += bindingSnippets.join( '\n' );
  138. return output;
  139. }
  140. getTypeFromAttribute( attribute ) {
  141. let nodeType = super.getTypeFromAttribute( attribute );
  142. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  143. let dataAttribute = attribute;
  144. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  145. const array = dataAttribute.array;
  146. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  147. nodeType = nodeType.slice( 1 );
  148. }
  149. }
  150. return nodeType;
  151. }
  152. getAttributes( shaderStage ) {
  153. let snippet = '';
  154. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  155. const attributes = this.getAttributesArray();
  156. let location = 0;
  157. for ( const attribute of attributes ) {
  158. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  159. }
  160. }
  161. return snippet;
  162. }
  163. getStructMembers( struct ) {
  164. const snippets = [];
  165. const members = struct.getMemberTypes();
  166. for ( let i = 0; i < members.length; i ++ ) {
  167. const member = members[ i ];
  168. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  169. }
  170. return snippets.join( '\n' );
  171. }
  172. getStructs( shaderStage ) {
  173. const snippets = [];
  174. const structs = this.structs[ shaderStage ];
  175. if ( structs.length === 0 ) {
  176. return 'layout( location = 0 ) out vec4 fragColor;\n';
  177. }
  178. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  179. const struct = structs[ index ];
  180. let snippet = '\n';
  181. snippet += this.getStructMembers( struct );
  182. snippet += '\n';
  183. snippets.push( snippet );
  184. }
  185. return snippets.join( '\n\n' );
  186. }
  187. getVaryings( shaderStage ) {
  188. let snippet = '';
  189. const varyings = this.varyings;
  190. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  191. for ( const varying of varyings ) {
  192. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  193. const type = varying.type;
  194. const flat = type === 'int' || type === 'uint' ? 'flat ' : '';
  195. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  196. }
  197. } else if ( shaderStage === 'fragment' ) {
  198. for ( const varying of varyings ) {
  199. if ( varying.needsInterpolation ) {
  200. const type = varying.type;
  201. const flat = type === 'int' || type === 'uint' ? 'flat ' : '';
  202. snippet += `${flat}in ${type} ${varying.name};\n`;
  203. }
  204. }
  205. }
  206. return snippet;
  207. }
  208. getVertexIndex() {
  209. return 'uint( gl_VertexID )';
  210. }
  211. getInstanceIndex() {
  212. return 'uint( gl_InstanceID )';
  213. }
  214. getFrontFacing() {
  215. return 'gl_FrontFacing';
  216. }
  217. getFragCoord() {
  218. return 'gl_FragCoord';
  219. }
  220. getFragDepth() {
  221. return 'gl_FragDepth';
  222. }
  223. isAvailable( name ) {
  224. return supports[ name ] === true;
  225. }
  226. isFlipY() {
  227. return true;
  228. }
  229. registerTransform( varyingName, attributeNode ) {
  230. this.transforms.push( { varyingName, attributeNode } );
  231. }
  232. getTransforms( /* shaderStage */ ) {
  233. const transforms = this.transforms;
  234. let snippet = '';
  235. for ( let i = 0; i < transforms.length; i ++ ) {
  236. const transform = transforms[ i ];
  237. const attributeName = this.getPropertyName( transform.attributeNode );
  238. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  239. }
  240. return snippet;
  241. }
  242. _getGLSLUniformStruct( name, vars ) {
  243. return `
  244. layout( std140 ) uniform ${name} {
  245. ${vars}
  246. };`;
  247. }
  248. _getGLSLVertexCode( shaderData ) {
  249. return `#version 300 es
  250. ${ this.getSignature() }
  251. // precision
  252. ${ defaultPrecisions }
  253. // uniforms
  254. ${shaderData.uniforms}
  255. // varyings
  256. ${shaderData.varyings}
  257. // attributes
  258. ${shaderData.attributes}
  259. // codes
  260. ${shaderData.codes}
  261. void main() {
  262. // vars
  263. ${shaderData.vars}
  264. // transforms
  265. ${shaderData.transforms}
  266. // flow
  267. ${shaderData.flow}
  268. gl_PointSize = 1.0;
  269. }
  270. `;
  271. }
  272. _getGLSLFragmentCode( shaderData ) {
  273. return `#version 300 es
  274. ${ this.getSignature() }
  275. // precision
  276. ${ defaultPrecisions }
  277. // uniforms
  278. ${shaderData.uniforms}
  279. // varyings
  280. ${shaderData.varyings}
  281. // codes
  282. ${shaderData.codes}
  283. ${shaderData.structs}
  284. void main() {
  285. // vars
  286. ${shaderData.vars}
  287. // flow
  288. ${shaderData.flow}
  289. }
  290. `;
  291. }
  292. buildCode() {
  293. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  294. for ( const shaderStage in shadersData ) {
  295. let flow = '// code\n\n';
  296. flow += this.flowCode[ shaderStage ];
  297. const flowNodes = this.flowNodes[ shaderStage ];
  298. const mainNode = flowNodes[ flowNodes.length - 1 ];
  299. for ( const node of flowNodes ) {
  300. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  301. const slotName = node.name;
  302. if ( slotName ) {
  303. if ( flow.length > 0 ) flow += '\n';
  304. flow += `\t// flow -> ${ slotName }\n\t`;
  305. }
  306. flow += `${ flowSlotData.code }\n\t`;
  307. if ( node === mainNode && shaderStage !== 'compute' ) {
  308. flow += '// result\n\t';
  309. if ( shaderStage === 'vertex' ) {
  310. flow += 'gl_Position = ';
  311. flow += `${ flowSlotData.result };`;
  312. } else if ( shaderStage === 'fragment' ) {
  313. if ( ! node.outputNode.isOutputStructNode ) {
  314. flow += 'fragColor = ';
  315. flow += `${ flowSlotData.result };`;
  316. }
  317. }
  318. }
  319. }
  320. const stageData = shadersData[ shaderStage ];
  321. stageData.uniforms = this.getUniforms( shaderStage );
  322. stageData.attributes = this.getAttributes( shaderStage );
  323. stageData.varyings = this.getVaryings( shaderStage );
  324. stageData.vars = this.getVars( shaderStage );
  325. stageData.structs = this.getStructs( shaderStage );
  326. stageData.codes = this.getCodes( shaderStage );
  327. stageData.transforms = this.getTransforms( shaderStage );
  328. stageData.flow = flow;
  329. }
  330. if ( this.material !== null ) {
  331. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  332. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  333. } else {
  334. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  335. }
  336. }
  337. getUniformFromNode( node, type, shaderStage, name = null ) {
  338. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  339. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  340. let uniformGPU = nodeData.uniformGPU;
  341. if ( uniformGPU === undefined ) {
  342. if ( type === 'texture' ) {
  343. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node );
  344. this.bindings[ shaderStage ].push( uniformGPU );
  345. } else if ( type === 'cubeTexture' ) {
  346. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node );
  347. this.bindings[ shaderStage ].push( uniformGPU );
  348. } else if ( type === 'buffer' ) {
  349. node.name = `NodeBuffer_${node.id}`;
  350. const buffer = new UniformBuffer( node.name, node.value );
  351. uniformNode.name = `buffer${node.id}`;
  352. this.bindings[ shaderStage ].push( buffer );
  353. uniformGPU = buffer;
  354. } else {
  355. const group = node.groupNode;
  356. const groupName = group.name;
  357. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  358. let uniformsGroup = uniformsStage[ groupName ];
  359. if ( uniformsGroup === undefined ) {
  360. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  361. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  362. uniformsStage[ groupName ] = uniformsGroup;
  363. this.bindings[ shaderStage ].push( uniformsGroup );
  364. }
  365. uniformGPU = this.getNodeUniform( uniformNode, type );
  366. uniformsGroup.addUniform( uniformGPU );
  367. }
  368. nodeData.uniformGPU = uniformGPU;
  369. }
  370. return uniformNode;
  371. }
  372. }
  373. export default GLSLNodeBuilder;