NodeBuilder.js 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. import NodeUniform from './NodeUniform.js';
  2. import NodeAttribute from './NodeAttribute.js';
  3. import NodeVarying from './NodeVarying.js';
  4. import NodeVar from './NodeVar.js';
  5. import NodeCode from './NodeCode.js';
  6. import NodeKeywords from './NodeKeywords.js';
  7. import NodeCache from './NodeCache.js';
  8. import ParameterNode from './ParameterNode.js';
  9. import FunctionNode from '../code/FunctionNode.js';
  10. import { createNodeMaterialFromType, default as NodeMaterial } from '../materials/NodeMaterial.js';
  11. import { NodeUpdateType, defaultBuildStages, shaderStages } from './constants.js';
  12. import {
  13. FloatNodeUniform, Vector2NodeUniform, Vector3NodeUniform, Vector4NodeUniform,
  14. ColorNodeUniform, Matrix3NodeUniform, Matrix4NodeUniform
  15. } from '../../renderers/common/nodes/NodeUniform.js';
  16. import { REVISION, RenderTarget, Color, Vector2, Vector3, Vector4, IntType, UnsignedIntType, Float16BufferAttribute } from 'three';
  17. import { stack } from './StackNode.js';
  18. import { getCurrentStack, setCurrentStack } from '../shadernode/ShaderNode.js';
  19. import CubeRenderTarget from '../../renderers/common/CubeRenderTarget.js';
  20. import ChainMap from '../../renderers/common/ChainMap.js';
  21. import PMREMGenerator from '../../renderers/common/extras/PMREMGenerator.js';
  22. const uniformsGroupCache = new ChainMap();
  23. const typeFromLength = new Map( [
  24. [ 2, 'vec2' ],
  25. [ 3, 'vec3' ],
  26. [ 4, 'vec4' ],
  27. [ 9, 'mat3' ],
  28. [ 16, 'mat4' ]
  29. ] );
  30. const typeFromArray = new Map( [
  31. [ Int8Array, 'int' ],
  32. [ Int16Array, 'int' ],
  33. [ Int32Array, 'int' ],
  34. [ Uint8Array, 'uint' ],
  35. [ Uint16Array, 'uint' ],
  36. [ Uint32Array, 'uint' ],
  37. [ Float32Array, 'float' ]
  38. ] );
  39. const toFloat = ( value ) => {
  40. value = Number( value );
  41. return value + ( value % 1 ? '' : '.0' );
  42. };
  43. class NodeBuilder {
  44. constructor( object, renderer, parser, scene = null, material = null ) {
  45. this.object = object;
  46. this.material = material || ( object && object.material ) || null;
  47. this.geometry = ( object && object.geometry ) || null;
  48. this.renderer = renderer;
  49. this.parser = parser;
  50. this.scene = scene;
  51. this.nodes = [];
  52. this.updateNodes = [];
  53. this.updateBeforeNodes = [];
  54. this.hashNodes = {};
  55. this.lightsNode = null;
  56. this.environmentNode = null;
  57. this.fogNode = null;
  58. this.clippingContext = null;
  59. this.vertexShader = null;
  60. this.fragmentShader = null;
  61. this.computeShader = null;
  62. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  63. this.flowCode = { vertex: '', fragment: '', compute: '' };
  64. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  65. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  66. this.bindings = { vertex: [], fragment: [], compute: [] };
  67. this.bindingsOffset = { vertex: 0, fragment: 0, compute: 0 };
  68. this.bindingsArray = null;
  69. this.attributes = [];
  70. this.bufferAttributes = [];
  71. this.varyings = [];
  72. this.codes = {};
  73. this.vars = {};
  74. this.flow = { code: '' };
  75. this.chaining = [];
  76. this.stack = stack();
  77. this.stacks = [];
  78. this.tab = '\t';
  79. this.currentFunctionNode = null;
  80. this.context = {
  81. keywords: new NodeKeywords(),
  82. material: this.material
  83. };
  84. this.cache = new NodeCache();
  85. this.globalCache = this.cache;
  86. this.flowsData = new WeakMap();
  87. this.shaderStage = null;
  88. this.buildStage = null;
  89. }
  90. createRenderTarget( width, height, options ) {
  91. return new RenderTarget( width, height, options );
  92. }
  93. createCubeRenderTarget( size, options ) {
  94. return new CubeRenderTarget( size, options );
  95. }
  96. createPMREMGenerator() {
  97. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  98. return new PMREMGenerator( this.renderer );
  99. }
  100. includes( node ) {
  101. return this.nodes.includes( node );
  102. }
  103. _getSharedBindings( bindings ) {
  104. const shared = [];
  105. for ( const binding of bindings ) {
  106. if ( binding.shared === true ) {
  107. // nodes is the chainmap key
  108. const nodes = binding.getNodes();
  109. let sharedBinding = uniformsGroupCache.get( nodes );
  110. if ( sharedBinding === undefined ) {
  111. uniformsGroupCache.set( nodes, binding );
  112. sharedBinding = binding;
  113. }
  114. shared.push( sharedBinding );
  115. } else {
  116. shared.push( binding );
  117. }
  118. }
  119. return shared;
  120. }
  121. getBindings() {
  122. let bindingsArray = this.bindingsArray;
  123. if ( bindingsArray === null ) {
  124. const bindings = this.bindings;
  125. this.bindingsArray = bindingsArray = this._getSharedBindings( ( this.material !== null ) ? [ ...bindings.vertex, ...bindings.fragment ] : bindings.compute );
  126. }
  127. return bindingsArray;
  128. }
  129. setHashNode( node, hash ) {
  130. this.hashNodes[ hash ] = node;
  131. }
  132. addNode( node ) {
  133. if ( this.nodes.includes( node ) === false ) {
  134. this.nodes.push( node );
  135. this.setHashNode( node, node.getHash( this ) );
  136. }
  137. }
  138. buildUpdateNodes() {
  139. for ( const node of this.nodes ) {
  140. const updateType = node.getUpdateType();
  141. const updateBeforeType = node.getUpdateBeforeType();
  142. if ( updateType !== NodeUpdateType.NONE ) {
  143. this.updateNodes.push( node.getSelf() );
  144. }
  145. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  146. this.updateBeforeNodes.push( node );
  147. }
  148. }
  149. }
  150. get currentNode() {
  151. return this.chaining[ this.chaining.length - 1 ];
  152. }
  153. addChain( node ) {
  154. /*
  155. if ( this.chaining.indexOf( node ) !== - 1 ) {
  156. console.warn( 'Recursive node: ', node );
  157. }
  158. */
  159. this.chaining.push( node );
  160. }
  161. removeChain( node ) {
  162. const lastChain = this.chaining.pop();
  163. if ( lastChain !== node ) {
  164. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  165. }
  166. }
  167. getMethod( method ) {
  168. return method;
  169. }
  170. getNodeFromHash( hash ) {
  171. return this.hashNodes[ hash ];
  172. }
  173. addFlow( shaderStage, node ) {
  174. this.flowNodes[ shaderStage ].push( node );
  175. return node;
  176. }
  177. setContext( context ) {
  178. this.context = context;
  179. }
  180. getContext() {
  181. return this.context;
  182. }
  183. setCache( cache ) {
  184. this.cache = cache;
  185. }
  186. getCache() {
  187. return this.cache;
  188. }
  189. isAvailable( /*name*/ ) {
  190. return false;
  191. }
  192. getVertexIndex() {
  193. console.warn( 'Abstract function.' );
  194. }
  195. getInstanceIndex() {
  196. console.warn( 'Abstract function.' );
  197. }
  198. getFrontFacing() {
  199. console.warn( 'Abstract function.' );
  200. }
  201. getFragCoord() {
  202. console.warn( 'Abstract function.' );
  203. }
  204. isFlipY() {
  205. return false;
  206. }
  207. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  208. console.warn( 'Abstract function.' );
  209. }
  210. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  211. console.warn( 'Abstract function.' );
  212. }
  213. generateConst( type, value = null ) {
  214. if ( value === null ) {
  215. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  216. else if ( type === 'bool' ) value = false;
  217. else if ( type === 'color' ) value = new Color();
  218. else if ( type === 'vec2' ) value = new Vector2();
  219. else if ( type === 'vec3' ) value = new Vector3();
  220. else if ( type === 'vec4' ) value = new Vector4();
  221. }
  222. if ( type === 'float' ) return toFloat( value );
  223. if ( type === 'int' ) return `${ Math.round( value ) }`;
  224. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  225. if ( type === 'bool' ) return value ? 'true' : 'false';
  226. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  227. const typeLength = this.getTypeLength( type );
  228. const componentType = this.getComponentType( type );
  229. const generateConst = value => this.generateConst( componentType, value );
  230. if ( typeLength === 2 ) {
  231. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  232. } else if ( typeLength === 3 ) {
  233. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  234. } else if ( typeLength === 4 ) {
  235. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  236. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  237. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  238. } else if ( typeLength > 4 ) {
  239. return `${ this.getType( type ) }()`;
  240. }
  241. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  242. }
  243. getType( type ) {
  244. if ( type === 'color' ) return 'vec3';
  245. return type;
  246. }
  247. hasGeometryAttribute( name ) {
  248. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  249. }
  250. getAttribute( name, type ) {
  251. const attributes = this.attributes;
  252. // find attribute
  253. for ( const attribute of attributes ) {
  254. if ( attribute.name === name ) {
  255. return attribute;
  256. }
  257. }
  258. // create a new if no exist
  259. const attribute = new NodeAttribute( name, type );
  260. attributes.push( attribute );
  261. return attribute;
  262. }
  263. getPropertyName( node/*, shaderStage*/ ) {
  264. return node.name;
  265. }
  266. isVector( type ) {
  267. return /vec\d/.test( type );
  268. }
  269. isMatrix( type ) {
  270. return /mat\d/.test( type );
  271. }
  272. isReference( type ) {
  273. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D';
  274. }
  275. needsColorSpaceToLinear( /*texture*/ ) {
  276. return false;
  277. }
  278. getComponentTypeFromTexture( texture ) {
  279. const type = texture.type;
  280. if ( texture.isDataTexture ) {
  281. if ( type === IntType ) return 'int';
  282. if ( type === UnsignedIntType ) return 'uint';
  283. }
  284. return 'float';
  285. }
  286. getElementType( type ) {
  287. if ( type === 'mat2' ) return 'vec2';
  288. if ( type === 'mat3' ) return 'vec3';
  289. if ( type === 'mat4' ) return 'vec4';
  290. return this.getComponentType( type );
  291. }
  292. getComponentType( type ) {
  293. type = this.getVectorType( type );
  294. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  295. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  296. if ( componentType === null ) return null;
  297. if ( componentType[ 1 ] === 'b' ) return 'bool';
  298. if ( componentType[ 1 ] === 'i' ) return 'int';
  299. if ( componentType[ 1 ] === 'u' ) return 'uint';
  300. return 'float';
  301. }
  302. getVectorType( type ) {
  303. if ( type === 'color' ) return 'vec3';
  304. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  305. return type;
  306. }
  307. getTypeFromLength( length, componentType = 'float' ) {
  308. if ( length === 1 ) return componentType;
  309. const baseType = typeFromLength.get( length );
  310. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  311. return prefix + baseType;
  312. }
  313. getTypeFromArray( array ) {
  314. return typeFromArray.get( array.constructor );
  315. }
  316. getTypeFromAttribute( attribute ) {
  317. let dataAttribute = attribute;
  318. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  319. const array = dataAttribute.array;
  320. const itemSize = attribute.itemSize;
  321. const normalized = attribute.normalized;
  322. let arrayType;
  323. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  324. arrayType = this.getTypeFromArray( array );
  325. }
  326. return this.getTypeFromLength( itemSize, arrayType );
  327. }
  328. getTypeLength( type ) {
  329. const vecType = this.getVectorType( type );
  330. const vecNum = /vec([2-4])/.exec( vecType );
  331. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  332. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  333. if ( /mat2/.test( type ) === true ) return 4;
  334. if ( /mat3/.test( type ) === true ) return 9;
  335. if ( /mat4/.test( type ) === true ) return 16;
  336. return 0;
  337. }
  338. getVectorFromMatrix( type ) {
  339. return type.replace( 'mat', 'vec' );
  340. }
  341. changeComponentType( type, newComponentType ) {
  342. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  343. }
  344. getIntegerType( type ) {
  345. const componentType = this.getComponentType( type );
  346. if ( componentType === 'int' || componentType === 'uint' ) return type;
  347. return this.changeComponentType( type, 'int' );
  348. }
  349. addStack() {
  350. this.stack = stack( this.stack );
  351. this.stacks.push( getCurrentStack() || this.stack );
  352. setCurrentStack( this.stack );
  353. return this.stack;
  354. }
  355. removeStack() {
  356. const lastStack = this.stack;
  357. this.stack = lastStack.parent;
  358. setCurrentStack( this.stacks.pop() );
  359. return lastStack;
  360. }
  361. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  362. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  363. let nodeData = cache.getNodeData( node );
  364. if ( nodeData === undefined ) {
  365. nodeData = {};
  366. cache.setNodeData( node, nodeData );
  367. }
  368. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  369. return nodeData[ shaderStage ];
  370. }
  371. getNodeProperties( node, shaderStage = 'any' ) {
  372. const nodeData = this.getDataFromNode( node, shaderStage );
  373. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  374. }
  375. getBufferAttributeFromNode( node, type ) {
  376. const nodeData = this.getDataFromNode( node );
  377. let bufferAttribute = nodeData.bufferAttribute;
  378. if ( bufferAttribute === undefined ) {
  379. const index = this.uniforms.index ++;
  380. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  381. this.bufferAttributes.push( bufferAttribute );
  382. nodeData.bufferAttribute = bufferAttribute;
  383. }
  384. return bufferAttribute;
  385. }
  386. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  387. const nodeData = this.getDataFromNode( node, shaderStage );
  388. if ( nodeData.structType === undefined ) {
  389. const index = this.structs.index ++;
  390. node.name = `StructType${ index }`;
  391. this.structs[ shaderStage ].push( node );
  392. nodeData.structType = node;
  393. }
  394. return node;
  395. }
  396. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  397. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  398. let nodeUniform = nodeData.uniform;
  399. if ( nodeUniform === undefined ) {
  400. const index = this.uniforms.index ++;
  401. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  402. this.uniforms[ shaderStage ].push( nodeUniform );
  403. nodeData.uniform = nodeUniform;
  404. }
  405. return nodeUniform;
  406. }
  407. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  408. const nodeData = this.getDataFromNode( node, shaderStage );
  409. let nodeVar = nodeData.variable;
  410. if ( nodeVar === undefined ) {
  411. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  412. if ( name === null ) name = 'nodeVar' + vars.length;
  413. nodeVar = new NodeVar( name, type );
  414. vars.push( nodeVar );
  415. nodeData.variable = nodeVar;
  416. }
  417. return nodeVar;
  418. }
  419. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  420. const nodeData = this.getDataFromNode( node, 'any' );
  421. let nodeVarying = nodeData.varying;
  422. if ( nodeVarying === undefined ) {
  423. const varyings = this.varyings;
  424. const index = varyings.length;
  425. if ( name === null ) name = 'nodeVarying' + index;
  426. nodeVarying = new NodeVarying( name, type );
  427. varyings.push( nodeVarying );
  428. nodeData.varying = nodeVarying;
  429. }
  430. return nodeVarying;
  431. }
  432. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  433. const nodeData = this.getDataFromNode( node );
  434. let nodeCode = nodeData.code;
  435. if ( nodeCode === undefined ) {
  436. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  437. const index = codes.length;
  438. nodeCode = new NodeCode( 'nodeCode' + index, type );
  439. codes.push( nodeCode );
  440. nodeData.code = nodeCode;
  441. }
  442. return nodeCode;
  443. }
  444. addLineFlowCode( code ) {
  445. if ( code === '' ) return this;
  446. code = this.tab + code;
  447. if ( ! /;\s*$/.test( code ) ) {
  448. code = code + ';\n';
  449. }
  450. this.flow.code += code;
  451. return this;
  452. }
  453. addFlowCode( code ) {
  454. this.flow.code += code;
  455. return this;
  456. }
  457. addFlowTab() {
  458. this.tab += '\t';
  459. return this;
  460. }
  461. removeFlowTab() {
  462. this.tab = this.tab.slice( 0, - 1 );
  463. return this;
  464. }
  465. getFlowData( node/*, shaderStage*/ ) {
  466. return this.flowsData.get( node );
  467. }
  468. flowNode( node ) {
  469. const output = node.getNodeType( this );
  470. const flowData = this.flowChildNode( node, output );
  471. this.flowsData.set( node, flowData );
  472. return flowData;
  473. }
  474. buildFunctionNode( shaderNode ) {
  475. const fn = new FunctionNode();
  476. const previous = this.currentFunctionNode;
  477. this.currentFunctionNode = fn;
  478. fn.code = this.buildFunctionCode( shaderNode );
  479. this.currentFunctionNode = previous;
  480. return fn;
  481. }
  482. flowShaderNode( shaderNode ) {
  483. const layout = shaderNode.layout;
  484. let inputs;
  485. if ( shaderNode.isArrayInput ) {
  486. inputs = [];
  487. for ( const input of layout.inputs ) {
  488. inputs.push( new ParameterNode( input.type, input.name ) );
  489. }
  490. } else {
  491. inputs = {};
  492. for ( const input of layout.inputs ) {
  493. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  494. }
  495. }
  496. //
  497. shaderNode.layout = null;
  498. const callNode = shaderNode.call( inputs );
  499. const flowData = this.flowStagesNode( callNode, layout.type );
  500. shaderNode.layout = layout;
  501. return flowData;
  502. }
  503. flowStagesNode( node, output = null ) {
  504. const previousFlow = this.flow;
  505. const previousVars = this.vars;
  506. const previousBuildStage = this.buildStage;
  507. const flow = {
  508. code: ''
  509. };
  510. this.flow = flow;
  511. this.vars = {};
  512. for ( const buildStage of defaultBuildStages ) {
  513. this.setBuildStage( buildStage );
  514. flow.result = node.build( this, output );
  515. }
  516. flow.vars = this.getVars( this.shaderStage );
  517. this.flow = previousFlow;
  518. this.vars = previousVars;
  519. this.setBuildStage( previousBuildStage );
  520. return flow;
  521. }
  522. getFunctionOperator() {
  523. return null;
  524. }
  525. flowChildNode( node, output = null ) {
  526. const previousFlow = this.flow;
  527. const flow = {
  528. code: ''
  529. };
  530. this.flow = flow;
  531. flow.result = node.build( this, output );
  532. this.flow = previousFlow;
  533. return flow;
  534. }
  535. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  536. const previousShaderStage = this.shaderStage;
  537. this.setShaderStage( shaderStage );
  538. const flowData = this.flowChildNode( node, output );
  539. if ( propertyName !== null ) {
  540. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  541. }
  542. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  543. this.setShaderStage( previousShaderStage );
  544. return flowData;
  545. }
  546. getAttributesArray() {
  547. return this.attributes.concat( this.bufferAttributes );
  548. }
  549. getAttributes( /*shaderStage*/ ) {
  550. console.warn( 'Abstract function.' );
  551. }
  552. getVaryings( /*shaderStage*/ ) {
  553. console.warn( 'Abstract function.' );
  554. }
  555. getVar( type, name ) {
  556. return `${ this.getType( type ) } ${ name }`;
  557. }
  558. getVars( shaderStage ) {
  559. let snippet = '';
  560. const vars = this.vars[ shaderStage ];
  561. if ( vars !== undefined ) {
  562. for ( const variable of vars ) {
  563. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  564. }
  565. }
  566. return snippet;
  567. }
  568. getUniforms( /*shaderStage*/ ) {
  569. console.warn( 'Abstract function.' );
  570. }
  571. getCodes( shaderStage ) {
  572. const codes = this.codes[ shaderStage ];
  573. let code = '';
  574. if ( codes !== undefined ) {
  575. for ( const nodeCode of codes ) {
  576. code += nodeCode.code + '\n';
  577. }
  578. }
  579. return code;
  580. }
  581. getHash() {
  582. return this.vertexShader + this.fragmentShader + this.computeShader;
  583. }
  584. setShaderStage( shaderStage ) {
  585. this.shaderStage = shaderStage;
  586. }
  587. getShaderStage() {
  588. return this.shaderStage;
  589. }
  590. setBuildStage( buildStage ) {
  591. this.buildStage = buildStage;
  592. }
  593. getBuildStage() {
  594. return this.buildStage;
  595. }
  596. buildCode() {
  597. console.warn( 'Abstract function.' );
  598. }
  599. build() {
  600. const { object, material } = this;
  601. if ( material !== null ) {
  602. NodeMaterial.fromMaterial( material ).build( this );
  603. } else {
  604. this.addFlow( 'compute', object );
  605. }
  606. // setup() -> stage 1: create possible new nodes and returns an output reference node
  607. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  608. // generate() -> stage 3: generate shader
  609. for ( const buildStage of defaultBuildStages ) {
  610. this.setBuildStage( buildStage );
  611. if ( this.context.vertex && this.context.vertex.isNode ) {
  612. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  613. }
  614. for ( const shaderStage of shaderStages ) {
  615. this.setShaderStage( shaderStage );
  616. const flowNodes = this.flowNodes[ shaderStage ];
  617. for ( const node of flowNodes ) {
  618. if ( buildStage === 'generate' ) {
  619. this.flowNode( node );
  620. } else {
  621. node.build( this );
  622. }
  623. }
  624. }
  625. }
  626. this.setBuildStage( null );
  627. this.setShaderStage( null );
  628. // stage 4: build code for a specific output
  629. this.buildCode();
  630. this.buildUpdateNodes();
  631. return this;
  632. }
  633. getNodeUniform( uniformNode, type ) {
  634. if ( type === 'float' ) return new FloatNodeUniform( uniformNode );
  635. if ( type === 'vec2' ) return new Vector2NodeUniform( uniformNode );
  636. if ( type === 'vec3' ) return new Vector3NodeUniform( uniformNode );
  637. if ( type === 'vec4' ) return new Vector4NodeUniform( uniformNode );
  638. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  639. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  640. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  641. throw new Error( `Uniform "${type}" not declared.` );
  642. }
  643. createNodeMaterial( type = 'NodeMaterial' ) {
  644. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  645. return createNodeMaterialFromType( type );
  646. }
  647. format( snippet, fromType, toType ) {
  648. fromType = this.getVectorType( fromType );
  649. toType = this.getVectorType( toType );
  650. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  651. return snippet;
  652. }
  653. const fromTypeLength = this.getTypeLength( fromType );
  654. const toTypeLength = this.getTypeLength( toType );
  655. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  656. // @TODO: ignore for now
  657. return snippet;
  658. }
  659. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  660. // @TODO: ignore for now
  661. return snippet;
  662. }
  663. if ( fromTypeLength === toTypeLength ) {
  664. return `${ this.getType( toType ) }( ${ snippet } )`;
  665. }
  666. if ( fromTypeLength > toTypeLength ) {
  667. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  668. }
  669. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  670. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  671. }
  672. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  673. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  674. }
  675. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType[ 0 ] !== toType[ 0 ] ) { // fromType is float-like
  676. // convert a number value to vector type, e.g:
  677. // vec3( 1u ) -> vec3( float( 1u ) )
  678. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  679. }
  680. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  681. }
  682. getSignature() {
  683. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  684. }
  685. }
  686. export default NodeBuilder;