NodeBuilder.js 24 KB

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