WebGLNodeBuilder.js 17 KB

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