WebGLNodeBuilder.js 17 KB

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