WebGLNodeBuilder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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: 'void main() {',
  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. return `textureLod( ${textureProperty}, ${uvSnippet}, ${biasSnippet} )`;
  300. }
  301. buildFunctionCode( shaderNode ) {
  302. const layout = shaderNode.layout;
  303. const flowData = this.flowShaderNode( shaderNode );
  304. const parameters = [];
  305. for ( const input of layout.inputs ) {
  306. parameters.push( this.getType( input.type ) + ' ' + input.name );
  307. }
  308. //
  309. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  310. ${ flowData.vars }
  311. ${ flowData.code }
  312. return ${ flowData.result };
  313. }`;
  314. //
  315. return code;
  316. }
  317. getUniforms( shaderStage ) {
  318. const uniforms = this.uniforms[ shaderStage ];
  319. let output = '';
  320. for ( const uniform of uniforms ) {
  321. if ( /^(modelViewMatrix|projectionMatrix)$/.test( uniform.name ) )
  322. continue;
  323. let snippet = null;
  324. if ( uniform.type === 'texture' ) {
  325. snippet = `sampler2D ${uniform.name}; `;
  326. } else if ( uniform.type === 'cubeTexture' ) {
  327. snippet = `samplerCube ${uniform.name}; `;
  328. } else {
  329. const vectorType = this.getVectorType( uniform.type );
  330. snippet = `${vectorType} ${uniform.name}; `;
  331. }
  332. const precision = uniform.node.precision;
  333. if ( precision !== null ) {
  334. snippet = 'uniform ' + precisionLib[ precision ] + ' ' + snippet;
  335. } else {
  336. snippet = 'uniform ' + snippet;
  337. }
  338. output += snippet;
  339. }
  340. return output;
  341. }
  342. getAttributes( shaderStage ) {
  343. let snippet = '';
  344. if ( shaderStage === 'vertex' ) {
  345. const attributes = this.attributes;
  346. for ( const attribute of attributes ) {
  347. // ignore common attributes to prevent redefinitions
  348. if ( /^(position|normal|uv[1-3]?)$/.test( attribute.name ) )
  349. continue;
  350. snippet += `attribute ${attribute.type} ${attribute.name}; `;
  351. }
  352. }
  353. return snippet;
  354. }
  355. getVaryings( shaderStage ) {
  356. let snippet = '';
  357. const varyings = this.varyings;
  358. if ( shaderStage === 'vertex' ) {
  359. for ( const varying of varyings ) {
  360. snippet += `${varying.needsInterpolation ? 'varying' : '/*varying*/'} ${varying.type} ${varying.name}; `;
  361. }
  362. } else if ( shaderStage === 'fragment' ) {
  363. for ( const varying of varyings ) {
  364. if ( varying.needsInterpolation ) {
  365. snippet += `varying ${varying.type} ${varying.name}; `;
  366. }
  367. }
  368. }
  369. return snippet;
  370. }
  371. addCode( shaderStage, source, code, scope = this ) {
  372. const shaderProperty = getShaderStageProperty( shaderStage );
  373. let snippet = scope[ shaderProperty ];
  374. const index = snippet.indexOf( source );
  375. if ( index !== - 1 ) {
  376. const start = snippet.substring( 0, index + source.length );
  377. const end = snippet.substring( index + source.length );
  378. snippet = `${start}\n${code}\n${end}`;
  379. }
  380. scope[ shaderProperty ] = snippet;
  381. }
  382. replaceCode( shaderStage, source, target, scope = this ) {
  383. const shaderProperty = getShaderStageProperty( shaderStage );
  384. scope[ shaderProperty ] = scope[ shaderProperty ].replaceAll( source, target );
  385. }
  386. getVertexIndex() {
  387. return 'gl_VertexID';
  388. }
  389. getFrontFacing() {
  390. return 'gl_FrontFacing';
  391. }
  392. getFragCoord() {
  393. return 'gl_FragCoord';
  394. }
  395. isFlipY() {
  396. return true;
  397. }
  398. buildCode() {
  399. const shaderData = {};
  400. for ( const shaderStage of defaultShaderStages ) {
  401. const uniforms = this.getUniforms( shaderStage );
  402. const attributes = this.getAttributes( shaderStage );
  403. const varyings = this.getVaryings( shaderStage );
  404. const vars = this.getVars( shaderStage );
  405. const codes = this.getCodes( shaderStage );
  406. shaderData[ shaderStage ] = `${this.getSignature()}
  407. // <node_builder>
  408. // uniforms
  409. ${uniforms}
  410. // attributes
  411. ${attributes}
  412. // varyings
  413. ${varyings}
  414. // vars
  415. ${vars}
  416. // codes
  417. ${codes}
  418. // </node_builder>
  419. ${this.shader[ getShaderStageProperty( shaderStage ) ]}
  420. `;
  421. }
  422. this.vertexShader = shaderData.vertex;
  423. this.fragmentShader = shaderData.fragment;
  424. }
  425. build() {
  426. super.build( false );
  427. this._addSnippets();
  428. this._addUniforms();
  429. this._updateUniforms();
  430. this.shader.vertexShader = this.vertexShader;
  431. this.shader.fragmentShader = this.fragmentShader;
  432. return this;
  433. }
  434. _parseInclude( shaderStage, ...includes ) {
  435. for ( const name of includes ) {
  436. const includeSnippet = getIncludeSnippet( name );
  437. const code = ShaderChunk[ name ];
  438. const shaderProperty = getShaderStageProperty( shaderStage );
  439. this.shader[ shaderProperty ] = this.shader[ shaderProperty ].replaceAll( includeSnippet, code );
  440. }
  441. }
  442. _sortSlotsToFlow() {
  443. for ( const shaderStage of defaultShaderStages ) {
  444. const sourceCode = this.shader[ getShaderStageProperty( shaderStage ) ];
  445. const slots = this.slots[ shaderStage ].sort( ( slotA, slotB ) => {
  446. return sourceCode.indexOf( slotA.source ) > sourceCode.indexOf( slotB.source ) ? 1 : - 1;
  447. } );
  448. for ( const slotNode of slots ) {
  449. this.addFlow( shaderStage, slotNode );
  450. }
  451. }
  452. }
  453. _addSnippets() {
  454. for ( const shaderStage of defaultShaderStages ) {
  455. for ( const slotNode of this.slots[ shaderStage ] ) {
  456. const flowData = this.getFlowData( slotNode/*, shaderStage*/ );
  457. const inclusionType = slotNode.inclusionType;
  458. const source = slotNode.source;
  459. const target = flowData.code + '\n\t' + slotNode.target.replace( '%RESULT%', flowData.result );
  460. if ( inclusionType === 'append' ) {
  461. this.addCode( shaderStage, source, target );
  462. } else if ( inclusionType === 'replace' ) {
  463. this.replaceCode( shaderStage, source, target );
  464. } else {
  465. console.warn( `Inclusion type "${ inclusionType }" not compatible.` );
  466. }
  467. }
  468. this.addCode(
  469. shaderStage,
  470. 'main() {',
  471. '\n\t' + this.flowCode[ shaderStage ]
  472. );
  473. }
  474. }
  475. _addUniforms() {
  476. for ( const shaderStage of defaultShaderStages ) {
  477. // uniforms
  478. for ( const uniform of this.uniforms[ shaderStage ] ) {
  479. this.shader.uniforms[ uniform.name ] = uniform;
  480. }
  481. }
  482. }
  483. _updateUniforms() {
  484. nodeFrame.object = this.object;
  485. nodeFrame.renderer = this.renderer;
  486. for ( const node of this.updateNodes ) {
  487. nodeFrame.updateNode( node );
  488. }
  489. }
  490. }
  491. export { WebGLNodeBuilder };