WebGLNodeBuilder.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. import NodeBuilder, { defaultShaderStages } from 'three-nodes/core/NodeBuilder.js';
  2. import NodeFrame from 'three-nodes/core/NodeFrame.js';
  3. import SlotNode from './SlotNode.js';
  4. import GLSLNodeParser from 'three-nodes/parsers/GLSLNodeParser.js';
  5. import { PerspectiveCamera, ShaderChunk, ShaderLib, UniformsUtils, UniformsLib,
  6. LinearEncoding, RGBAFormat, UnsignedByteType, sRGBEncoding } from 'three';
  7. import MathNode from '../../../nodes/math/MathNode.js';
  8. const nodeFrame = new NodeFrame();
  9. nodeFrame.camera = new PerspectiveCamera();
  10. const nodeShaderLib = {
  11. LineBasicNodeMaterial: ShaderLib.basic,
  12. MeshBasicNodeMaterial: ShaderLib.basic,
  13. PointsNodeMaterial: ShaderLib.points,
  14. MeshStandardNodeMaterial: ShaderLib.standard,
  15. MeshPhysicalNodeMaterial: ShaderLib.physical
  16. };
  17. const glslMethods = {
  18. [ MathNode.ATAN2 ]: 'atan'
  19. };
  20. function getIncludeSnippet( name ) {
  21. return `#include <${name}>`;
  22. }
  23. function getShaderStageProperty( shaderStage ) {
  24. return `${shaderStage}Shader`;
  25. }
  26. class WebGLNodeBuilder extends NodeBuilder {
  27. constructor( object, renderer, shader ) {
  28. super( object, renderer, new GLSLNodeParser() );
  29. this.shader = shader;
  30. this.slots = { vertex: [], fragment: [] };
  31. this._parseShaderLib();
  32. this._parseInclude( 'fragment', 'lights_physical_fragment', 'clearcoat_normal_fragment_begin', 'transmission_fragment' );
  33. this._parseObject();
  34. this._sortSlotsToFlow();
  35. }
  36. getMethod( method ) {
  37. return glslMethods[ method ] || method;
  38. }
  39. addSlot( shaderStage, slotNode ) {
  40. this.slots[ shaderStage ].push( slotNode );
  41. }
  42. addFlowCode( code ) {
  43. if ( ! /;\s*$/.test( code ) ) {
  44. code += ';';
  45. }
  46. super.addFlowCode( code + '\n\t' );
  47. }
  48. _parseShaderLib() {
  49. const type = this.material.type;
  50. // shader lib
  51. if ( nodeShaderLib[ type ] !== undefined ) {
  52. const shaderLib = nodeShaderLib[ type ];
  53. const shader = this.shader;
  54. shader.vertexShader = shaderLib.vertexShader;
  55. shader.fragmentShader = shaderLib.fragmentShader;
  56. shader.uniforms = UniformsUtils.merge( [ shaderLib.uniforms, UniformsLib.lights ] );
  57. }
  58. }
  59. _parseObject() {
  60. const { material, renderer } = this;
  61. if ( renderer.toneMappingNode?.isNode === true ) {
  62. this.addSlot( 'fragment', new SlotNode( {
  63. node: material.colorNode,
  64. nodeType: 'vec4',
  65. source: getIncludeSnippet( 'tonemapping_fragment' ),
  66. target: ''
  67. } ) );
  68. }
  69. // parse inputs
  70. if ( material.colorNode && material.colorNode.isNode ) {
  71. this.addSlot( 'fragment', new SlotNode( {
  72. node: material.colorNode,
  73. nodeType: 'vec4',
  74. source: getIncludeSnippet( 'color_fragment' ),
  75. target: 'diffuseColor = %RESULT%;',
  76. inclusionType: 'append'
  77. } ) );
  78. }
  79. if ( material.opacityNode && material.opacityNode.isNode ) {
  80. this.addSlot( 'fragment', new SlotNode( {
  81. node: material.opacityNode,
  82. nodeType: 'float',
  83. source: getIncludeSnippet( 'alphatest_fragment' ),
  84. target: 'diffuseColor.a = %RESULT%;',
  85. inclusionType: 'append'
  86. } ) );
  87. }
  88. if ( material.normalNode && material.normalNode.isNode ) {
  89. this.addSlot( 'fragment', new SlotNode( {
  90. node: material.normalNode,
  91. nodeType: 'vec3',
  92. source: getIncludeSnippet( 'normal_fragment_begin' ),
  93. target: 'normal = %RESULT%;',
  94. inclusionType: 'append'
  95. } ) );
  96. }
  97. if ( material.emissiveNode && material.emissiveNode.isNode ) {
  98. this.addSlot( 'fragment', new SlotNode( {
  99. node: material.emissiveNode,
  100. nodeType: 'vec3',
  101. source: getIncludeSnippet( 'emissivemap_fragment' ),
  102. target: 'totalEmissiveRadiance = %RESULT%;',
  103. inclusionType: 'append'
  104. } ) );
  105. }
  106. if ( material.isMeshStandardNodeMaterial ) {
  107. if ( material.metalnessNode && material.metalnessNode.isNode ) {
  108. this.addSlot( 'fragment', new SlotNode( {
  109. node: material.metalnessNode,
  110. nodeType: 'float',
  111. source: getIncludeSnippet( 'metalnessmap_fragment' ),
  112. target: 'metalnessFactor = %RESULT%;',
  113. inclusionType: 'append'
  114. } ) );
  115. }
  116. if ( material.roughnessNode && material.roughnessNode.isNode ) {
  117. this.addSlot( 'fragment', new SlotNode( {
  118. node: material.roughnessNode,
  119. nodeType: 'float',
  120. source: getIncludeSnippet( 'roughnessmap_fragment' ),
  121. target: 'roughnessFactor = %RESULT%;',
  122. inclusionType: 'append'
  123. } ) );
  124. }
  125. if ( material.isMeshPhysicalNodeMaterial ) {
  126. if ( material.clearcoatNode && material.clearcoatNode.isNode ) {
  127. this.addSlot( 'fragment', new SlotNode( {
  128. node: material.clearcoatNode,
  129. nodeType: 'float',
  130. source: 'material.clearcoat = clearcoat;',
  131. target: 'material.clearcoat = %RESULT%;'
  132. } ) );
  133. if ( material.clearcoatRoughnessNode && material.clearcoatRoughnessNode.isNode ) {
  134. this.addSlot( 'fragment', new SlotNode( {
  135. node: material.clearcoatRoughnessNode,
  136. nodeType: 'float',
  137. source: 'material.clearcoatRoughness = clearcoatRoughness;',
  138. target: 'material.clearcoatRoughness = %RESULT%;'
  139. } ) );
  140. }
  141. if ( material.clearcoatNormalNode && material.clearcoatNormalNode.isNode ) {
  142. this.addSlot( 'fragment', new SlotNode( {
  143. node: material.clearcoatNormalNode,
  144. nodeType: 'vec3',
  145. source: 'vec3 clearcoatNormal = geometryNormal;',
  146. target: 'vec3 clearcoatNormal = %RESULT%;'
  147. } ) );
  148. }
  149. material.defines.USE_CLEARCOAT = '';
  150. } else {
  151. delete material.defines.USE_CLEARCOAT;
  152. }
  153. if ( material.sheenNode && material.sheenNode.isNode ) {
  154. this.addSlot( 'fragment', new SlotNode( {
  155. node: material.sheenNode,
  156. nodeType: 'vec3',
  157. source: 'material.sheenColor = sheenColor;',
  158. target: 'material.sheenColor = %RESULT%;'
  159. } ) );
  160. if ( material.sheenRoughnessNode && material.sheenRoughnessNode.isNode ) {
  161. this.addSlot( 'fragment', new SlotNode( {
  162. node: material.sheenRoughnessNode,
  163. nodeType: 'float',
  164. source: 'material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );',
  165. target: 'material.sheenRoughness = clamp( %RESULT%, 0.07, 1.0 );'
  166. } ) );
  167. }
  168. material.defines.USE_SHEEN = '';
  169. } else {
  170. delete material.defines.USE_SHEEN;
  171. }
  172. if ( material.iridescenceNode && material.iridescenceNode.isNode ) {
  173. this.addSlot( 'fragment', new SlotNode( {
  174. node: material.iridescenceNode,
  175. nodeType: 'float',
  176. source: 'material.iridescence = iridescence;',
  177. target: 'material.iridescence = %RESULT%;'
  178. } ) );
  179. if ( material.iridescenceIORNode && material.iridescenceIORNode.isNode ) {
  180. this.addSlot( 'fragment', new SlotNode( {
  181. node: material.iridescenceIORNode,
  182. nodeType: 'float',
  183. source: 'material.iridescenceIOR = iridescenceIOR;',
  184. target: 'material.iridescenceIOR = %RESULT%;'
  185. } ) );
  186. }
  187. if ( material.iridescenceThicknessNode && material.iridescenceThicknessNode.isNode ) {
  188. this.addSlot( 'fragment', new SlotNode( {
  189. node: material.iridescenceThicknessNode,
  190. nodeType: 'float',
  191. source: 'material.iridescenceThickness = iridescenceThicknessMaximum;',
  192. target: 'material.iridescenceThickness = %RESULT%;'
  193. } ) );
  194. }
  195. material.defines.USE_IRIDESCENCE = '';
  196. } else {
  197. delete material.defines.USE_IRIDESCENCE;
  198. }
  199. if ( material.iorNode && material.iorNode.isNode ) {
  200. this.addSlot( 'fragment', new SlotNode( {
  201. node: material.iorNode,
  202. nodeType: 'float',
  203. source: 'material.ior = ior;',
  204. target: 'material.ior = %RESULT%;'
  205. } ) );
  206. }
  207. if ( material.specularColorNode && material.specularColorNode.isNode ) {
  208. this.addSlot( 'fragment', new SlotNode( {
  209. node: material.specularColorNode,
  210. nodeType: 'vec3',
  211. source: 'vec3 specularColorFactor = specularColor;',
  212. target: 'vec3 specularColorFactor = %RESULT%;'
  213. } ) );
  214. }
  215. if ( material.specularIntensityNode && material.specularIntensityNode.isNode ) {
  216. this.addSlot( 'fragment', new SlotNode( {
  217. node: material.specularIntensityNode,
  218. nodeType: 'float',
  219. source: 'float specularIntensityFactor = specularIntensity;',
  220. target: 'float specularIntensityFactor = %RESULT%;'
  221. } ) );
  222. }
  223. if ( material.transmissionNode && material.transmissionNode.isNode ) {
  224. this.addSlot( 'fragment', new SlotNode( {
  225. node: material.transmissionNode,
  226. nodeType: 'float',
  227. source: 'material.transmission = transmission;',
  228. target: 'material.transmission = %RESULT%;'
  229. } ) );
  230. if ( material.thicknessNode && material.thicknessNode.isNode ) {
  231. this.addSlot( 'fragment', new SlotNode( {
  232. node: material.thicknessNode,
  233. nodeType: 'float',
  234. source: 'material.thickness = thickness;',
  235. target: 'material.thickness = %RESULT%;'
  236. } ) );
  237. }
  238. if ( material.thicknessNode && material.thicknessNode.isNode ) {
  239. this.addSlot( 'fragment', new SlotNode( {
  240. node: material.thicknessNode,
  241. nodeType: 'float',
  242. source: 'material.thickness = thickness;',
  243. target: 'material.thickness = %RESULT%;'
  244. } ) );
  245. }
  246. if ( material.attenuationDistanceNode && material.attenuationDistanceNode.isNode ) {
  247. this.addSlot( 'fragment', new SlotNode( {
  248. node: material.attenuationDistanceNode,
  249. nodeType: 'float',
  250. source: 'material.attenuationDistance = attenuationDistance;',
  251. target: 'material.attenuationDistance = %RESULT%;'
  252. } ) );
  253. }
  254. if ( material.attenuationColorNode && material.attenuationColorNode.isNode ) {
  255. this.addSlot( 'fragment', new SlotNode( {
  256. node: material.attenuationColorNode,
  257. nodeType: 'vec3',
  258. source: 'material.attenuationColor = attenuationColor;',
  259. target: 'material.attenuationColor = %RESULT%;'
  260. } ) );
  261. }
  262. material.transmission = 1;
  263. material.defines.USE_TRANSMISSION = '';
  264. } else {
  265. material.transmission = 0;
  266. delete material.defines.USE_TRANSMISSION;
  267. }
  268. }
  269. }
  270. //
  271. if ( material.positionNode && material.positionNode.isNode ) {
  272. this.addSlot( 'vertex', new SlotNode( {
  273. node: material.positionNode,
  274. nodeType: 'vec3',
  275. source: getIncludeSnippet( 'begin_vertex' ),
  276. target: 'transformed = %RESULT%;',
  277. inclusionType: 'append'
  278. } ) );
  279. }
  280. if ( material.sizeNode && material.sizeNode.isNode ) {
  281. this.addSlot( 'vertex', new SlotNode( {
  282. node: material.sizeNode,
  283. nodeType: 'float',
  284. source: 'gl_PointSize = size;',
  285. target: 'gl_PointSize = %RESULT%;'
  286. } ) );
  287. }
  288. }
  289. getTexture( textureProperty, uvSnippet ) {
  290. return `texture2D( ${textureProperty}, ${uvSnippet} )`;
  291. }
  292. getTextureBias( textureProperty, uvSnippet, biasSnippet ) {
  293. if ( this.material.extensions !== undefined ) this.material.extensions.shaderTextureLOD = true;
  294. return `textureLod( ${textureProperty}, ${uvSnippet}, ${biasSnippet} )`;
  295. }
  296. getCubeTexture( textureProperty, uvSnippet ) {
  297. return `textureCube( ${textureProperty}, ${uvSnippet} )`;
  298. }
  299. getCubeTextureBias( textureProperty, uvSnippet, biasSnippet ) {
  300. if ( this.material.extensions !== undefined ) this.material.extensions.shaderTextureLOD = true;
  301. return `textureLod( ${textureProperty}, ${uvSnippet}, ${biasSnippet} )`;
  302. }
  303. getUniforms( shaderStage ) {
  304. const uniforms = this.uniforms[ shaderStage ];
  305. let snippet = '';
  306. for ( const uniform of uniforms ) {
  307. if ( uniform.type === 'texture' ) {
  308. snippet += `uniform sampler2D ${uniform.name}; `;
  309. } else if ( uniform.type === 'cubeTexture' ) {
  310. snippet += `uniform samplerCube ${uniform.name}; `;
  311. } else {
  312. const vectorType = this.getVectorType( uniform.type );
  313. snippet += `uniform ${vectorType} ${uniform.name}; `;
  314. }
  315. }
  316. return snippet;
  317. }
  318. getAttributes( shaderStage ) {
  319. let snippet = '';
  320. if ( shaderStage === 'vertex' ) {
  321. const attributes = this.attributes;
  322. for ( const attribute of attributes ) {
  323. // ignore common attributes to prevent redefinitions
  324. if ( attribute.name === 'uv' || attribute.name === 'position' || attribute.name === 'normal' )
  325. continue;
  326. snippet += `attribute ${attribute.type} ${attribute.name}; `;
  327. }
  328. }
  329. return snippet;
  330. }
  331. getVaryings( /* shaderStage */ ) {
  332. let snippet = '';
  333. const varyings = this.varyings;
  334. for ( const varying of varyings ) {
  335. snippet += `varying ${varying.type} ${varying.name}; `;
  336. }
  337. return snippet;
  338. }
  339. addCodeAfterCode( shaderStage, snippet, code ) {
  340. const shaderProperty = getShaderStageProperty( shaderStage );
  341. let source = this[ shaderProperty ];
  342. const index = source.indexOf( snippet );
  343. if ( index !== - 1 ) {
  344. const start = source.substring( 0, index + snippet.length );
  345. const end = source.substring( index + snippet.length );
  346. source = `${start}\n${code}\n${end}`;
  347. }
  348. this[ shaderProperty ] = source;
  349. }
  350. replaceCode( shaderStage, source, target ) {
  351. const shaderProperty = getShaderStageProperty( shaderStage );
  352. this[ shaderProperty ] = this[ shaderProperty ].replaceAll( source, target );
  353. }
  354. getTextureEncodingFromMap( map ) {
  355. const isWebGL2 = this.renderer.capabilities.isWebGL2;
  356. if ( isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding ) {
  357. return LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
  358. }
  359. return super.getTextureEncodingFromMap( map );
  360. }
  361. getFrontFacing() {
  362. return 'gl_FrontFacing';
  363. }
  364. buildCode() {
  365. const shaderData = {};
  366. for ( const shaderStage of defaultShaderStages ) {
  367. const uniforms = this.getUniforms( shaderStage );
  368. const attributes = this.getAttributes( shaderStage );
  369. const varyings = this.getVaryings( shaderStage );
  370. const vars = this.getVars( shaderStage );
  371. const codes = this.getCodes( shaderStage );
  372. shaderData[ shaderStage ] = `${this.getSignature()}
  373. // <node_builder>
  374. // uniforms
  375. ${uniforms}
  376. // attributes
  377. ${attributes}
  378. // varyings
  379. ${varyings}
  380. // vars
  381. ${vars}
  382. // codes
  383. ${codes}
  384. // </node_builder>
  385. ${this.shader[ getShaderStageProperty( shaderStage ) ]}
  386. `;
  387. }
  388. this.vertexShader = shaderData.vertex;
  389. this.fragmentShader = shaderData.fragment;
  390. }
  391. build() {
  392. super.build();
  393. this._addSnippets();
  394. this._addUniforms();
  395. this._updateUniforms();
  396. this.shader.vertexShader = this.vertexShader;
  397. this.shader.fragmentShader = this.fragmentShader;
  398. return this;
  399. }
  400. _parseInclude( shaderStage, ...includes ) {
  401. for ( const name of includes ) {
  402. const includeSnippet = getIncludeSnippet( name );
  403. const code = ShaderChunk[ name ];
  404. const shaderProperty = getShaderStageProperty( shaderStage );
  405. this.shader[ shaderProperty ] = this.shader[ shaderProperty ].replaceAll( includeSnippet, code );
  406. }
  407. }
  408. _sortSlotsToFlow() {
  409. for ( const shaderStage of defaultShaderStages ) {
  410. const sourceCode = this.shader[ getShaderStageProperty( shaderStage ) ];
  411. const slots = this.slots[ shaderStage ].sort( ( slotA, slotB ) => {
  412. if ( sourceCode.indexOf( slotA.source ) == - 1 ) {
  413. //console.log( slotA, sourceCode.indexOf( slotA.source ), sourceCode.indexOf( slotB.source ) );
  414. //console.log(sourceCode);
  415. }
  416. return sourceCode.indexOf( slotA.source ) > sourceCode.indexOf( slotB.source ) ? 1 : - 1;
  417. } );
  418. for ( const slotNode of slots ) {
  419. this.addFlow( shaderStage, slotNode );
  420. }
  421. }
  422. }
  423. _addSnippets() {
  424. for ( const shaderStage of defaultShaderStages ) {
  425. for ( const slotNode of this.slots[ shaderStage ] ) {
  426. const flowData = this.getFlowData( slotNode/*, shaderStage*/ );
  427. const inclusionType = slotNode.inclusionType;
  428. const source = slotNode.source;
  429. const target = flowData.code + '\n\t' + slotNode.target.replace( '%RESULT%', flowData.result );
  430. if ( inclusionType === 'append' ) {
  431. this.addCodeAfterCode( shaderStage, source, target );
  432. } else if ( inclusionType === 'replace' ) {
  433. this.replaceCode( shaderStage, source, target );
  434. } else {
  435. console.warn( `Inclusion type "${ inclusionType }" not compatible.` );
  436. }
  437. }
  438. this.addCodeAfterCode(
  439. shaderStage,
  440. 'main() {',
  441. this.flowCode[ shaderStage ]
  442. );
  443. }
  444. }
  445. _addUniforms() {
  446. for ( const shaderStage of defaultShaderStages ) {
  447. // uniforms
  448. for ( const uniform of this.uniforms[ shaderStage ] ) {
  449. this.shader.uniforms[ uniform.name ] = uniform;
  450. }
  451. }
  452. }
  453. _updateUniforms() {
  454. nodeFrame.object = this.object;
  455. nodeFrame.renderer = this.renderer;
  456. for ( const node of this.updateNodes ) {
  457. nodeFrame.updateNode( node );
  458. }
  459. }
  460. }
  461. export { WebGLNodeBuilder };