WebGLNodeBuilder.js 17 KB

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