NodeBuilder.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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. generateMethod( method ) {
  248. return method;
  249. }
  250. hasGeometryAttribute( name ) {
  251. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  252. }
  253. getAttribute( name, type ) {
  254. const attributes = this.attributes;
  255. // find attribute
  256. for ( const attribute of attributes ) {
  257. if ( attribute.name === name ) {
  258. return attribute;
  259. }
  260. }
  261. // create a new if no exist
  262. const attribute = new NodeAttribute( name, type );
  263. attributes.push( attribute );
  264. return attribute;
  265. }
  266. getPropertyName( node/*, shaderStage*/ ) {
  267. return node.name;
  268. }
  269. isVector( type ) {
  270. return /vec\d/.test( type );
  271. }
  272. isMatrix( type ) {
  273. return /mat\d/.test( type );
  274. }
  275. isReference( type ) {
  276. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture';
  277. }
  278. needsColorSpaceToLinear( /*texture*/ ) {
  279. return false;
  280. }
  281. getComponentTypeFromTexture( texture ) {
  282. const type = texture.type;
  283. if ( texture.isDataTexture ) {
  284. if ( type === IntType ) return 'int';
  285. if ( type === UnsignedIntType ) return 'uint';
  286. }
  287. return 'float';
  288. }
  289. getComponentType( type ) {
  290. type = this.getVectorType( type );
  291. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  292. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  293. if ( componentType === null ) return null;
  294. if ( componentType[ 1 ] === 'b' ) return 'bool';
  295. if ( componentType[ 1 ] === 'i' ) return 'int';
  296. if ( componentType[ 1 ] === 'u' ) return 'uint';
  297. return 'float';
  298. }
  299. getVectorType( type ) {
  300. if ( type === 'color' ) return 'vec3';
  301. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' ) return 'vec4';
  302. return type;
  303. }
  304. getTypeFromLength( length, componentType = 'float' ) {
  305. if ( length === 1 ) return componentType;
  306. const baseType = typeFromLength.get( length );
  307. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  308. return prefix + baseType;
  309. }
  310. getTypeFromArray( array ) {
  311. return typeFromArray.get( array.constructor );
  312. }
  313. getTypeFromAttribute( attribute ) {
  314. let dataAttribute = attribute;
  315. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  316. const array = dataAttribute.array;
  317. const itemSize = attribute.itemSize;
  318. const normalized = attribute.normalized;
  319. let arrayType;
  320. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  321. arrayType = this.getTypeFromArray( array );
  322. }
  323. return this.getTypeFromLength( itemSize, arrayType );
  324. }
  325. getTypeLength( type ) {
  326. const vecType = this.getVectorType( type );
  327. const vecNum = /vec([2-4])/.exec( vecType );
  328. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  329. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  330. if ( /mat2/.test( type ) === true ) return 4;
  331. if ( /mat3/.test( type ) === true ) return 9;
  332. if ( /mat4/.test( type ) === true ) return 16;
  333. return 0;
  334. }
  335. getVectorFromMatrix( type ) {
  336. return type.replace( 'mat', 'vec' );
  337. }
  338. changeComponentType( type, newComponentType ) {
  339. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  340. }
  341. getIntegerType( type ) {
  342. const componentType = this.getComponentType( type );
  343. if ( componentType === 'int' || componentType === 'uint' ) return type;
  344. return this.changeComponentType( type, 'int' );
  345. }
  346. addStack() {
  347. this.stack = stack( this.stack );
  348. this.stacks.push( getCurrentStack() || this.stack );
  349. setCurrentStack( this.stack );
  350. return this.stack;
  351. }
  352. removeStack() {
  353. const lastStack = this.stack;
  354. this.stack = lastStack.parent;
  355. setCurrentStack( this.stacks.pop() );
  356. return lastStack;
  357. }
  358. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  359. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  360. let nodeData = cache.getNodeData( node );
  361. if ( nodeData === undefined ) {
  362. nodeData = {};
  363. cache.setNodeData( node, nodeData );
  364. }
  365. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  366. return nodeData[ shaderStage ];
  367. }
  368. getNodeProperties( node, shaderStage = 'any' ) {
  369. const nodeData = this.getDataFromNode( node, shaderStage );
  370. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  371. }
  372. getBufferAttributeFromNode( node, type ) {
  373. const nodeData = this.getDataFromNode( node );
  374. let bufferAttribute = nodeData.bufferAttribute;
  375. if ( bufferAttribute === undefined ) {
  376. const index = this.uniforms.index ++;
  377. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  378. this.bufferAttributes.push( bufferAttribute );
  379. nodeData.bufferAttribute = bufferAttribute;
  380. }
  381. return bufferAttribute;
  382. }
  383. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  384. const nodeData = this.getDataFromNode( node, shaderStage );
  385. if ( nodeData.structType === undefined ) {
  386. const index = this.structs.index ++;
  387. node.name = `StructType${ index }`;
  388. this.structs[ shaderStage ].push( node );
  389. nodeData.structType = node;
  390. }
  391. return node;
  392. }
  393. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  394. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  395. let nodeUniform = nodeData.uniform;
  396. if ( nodeUniform === undefined ) {
  397. const index = this.uniforms.index ++;
  398. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  399. this.uniforms[ shaderStage ].push( nodeUniform );
  400. nodeData.uniform = nodeUniform;
  401. }
  402. return nodeUniform;
  403. }
  404. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  405. const nodeData = this.getDataFromNode( node, shaderStage );
  406. let nodeVar = nodeData.variable;
  407. if ( nodeVar === undefined ) {
  408. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  409. if ( name === null ) name = 'nodeVar' + vars.length;
  410. nodeVar = new NodeVar( name, type );
  411. vars.push( nodeVar );
  412. nodeData.variable = nodeVar;
  413. }
  414. return nodeVar;
  415. }
  416. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  417. const nodeData = this.getDataFromNode( node, 'any' );
  418. let nodeVarying = nodeData.varying;
  419. if ( nodeVarying === undefined ) {
  420. const varyings = this.varyings;
  421. const index = varyings.length;
  422. if ( name === null ) name = 'nodeVarying' + index;
  423. nodeVarying = new NodeVarying( name, type );
  424. varyings.push( nodeVarying );
  425. nodeData.varying = nodeVarying;
  426. }
  427. return nodeVarying;
  428. }
  429. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  430. const nodeData = this.getDataFromNode( node );
  431. let nodeCode = nodeData.code;
  432. if ( nodeCode === undefined ) {
  433. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  434. const index = codes.length;
  435. nodeCode = new NodeCode( 'nodeCode' + index, type );
  436. codes.push( nodeCode );
  437. nodeData.code = nodeCode;
  438. }
  439. return nodeCode;
  440. }
  441. addLineFlowCode( code ) {
  442. if ( code === '' ) return this;
  443. code = this.tab + code;
  444. if ( ! /;\s*$/.test( code ) ) {
  445. code = code + ';\n';
  446. }
  447. this.flow.code += code;
  448. return this;
  449. }
  450. addFlowCode( code ) {
  451. this.flow.code += code;
  452. return this;
  453. }
  454. addFlowTab() {
  455. this.tab += '\t';
  456. return this;
  457. }
  458. removeFlowTab() {
  459. this.tab = this.tab.slice( 0, - 1 );
  460. return this;
  461. }
  462. getFlowData( node/*, shaderStage*/ ) {
  463. return this.flowsData.get( node );
  464. }
  465. flowNode( node ) {
  466. const output = node.getNodeType( this );
  467. const flowData = this.flowChildNode( node, output );
  468. this.flowsData.set( node, flowData );
  469. return flowData;
  470. }
  471. buildFunctionNode( shaderNode ) {
  472. const fn = new FunctionNode();
  473. const previous = this.currentFunctionNode;
  474. this.currentFunctionNode = fn;
  475. fn.code = this.buildFunctionCode( shaderNode );
  476. this.currentFunctionNode = previous;
  477. return fn;
  478. }
  479. flowShaderNode( shaderNode ) {
  480. const layout = shaderNode.layout;
  481. let inputs;
  482. if ( shaderNode.isArrayInput ) {
  483. inputs = [];
  484. for ( const input of layout.inputs ) {
  485. inputs.push( new ParameterNode( input.type, input.name ) );
  486. }
  487. } else {
  488. inputs = {};
  489. for ( const input of layout.inputs ) {
  490. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  491. }
  492. }
  493. //
  494. shaderNode.layout = null;
  495. const callNode = shaderNode.call( inputs );
  496. const flowData = this.flowStagesNode( callNode, layout.type );
  497. shaderNode.layout = layout;
  498. return flowData;
  499. }
  500. flowStagesNode( node, output = null ) {
  501. const previousFlow = this.flow;
  502. const previousVars = this.vars;
  503. const previousBuildStage = this.buildStage;
  504. const flow = {
  505. code: ''
  506. };
  507. this.flow = flow;
  508. this.vars = {};
  509. for ( const buildStage of defaultBuildStages ) {
  510. this.setBuildStage( buildStage );
  511. flow.result = node.build( this, output );
  512. }
  513. flow.vars = this.getVars( this.shaderStage );
  514. this.flow = previousFlow;
  515. this.vars = previousVars;
  516. this.setBuildStage( previousBuildStage );
  517. return flow;
  518. }
  519. getFunctionOperator() {
  520. return null;
  521. }
  522. flowChildNode( node, output = null ) {
  523. const previousFlow = this.flow;
  524. const flow = {
  525. code: ''
  526. };
  527. this.flow = flow;
  528. flow.result = node.build( this, output );
  529. this.flow = previousFlow;
  530. return flow;
  531. }
  532. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  533. const previousShaderStage = this.shaderStage;
  534. this.setShaderStage( shaderStage );
  535. const flowData = this.flowChildNode( node, output );
  536. if ( propertyName !== null ) {
  537. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  538. }
  539. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  540. this.setShaderStage( previousShaderStage );
  541. return flowData;
  542. }
  543. getAttributesArray() {
  544. return this.attributes.concat( this.bufferAttributes );
  545. }
  546. getAttributes( /*shaderStage*/ ) {
  547. console.warn( 'Abstract function.' );
  548. }
  549. getVaryings( /*shaderStage*/ ) {
  550. console.warn( 'Abstract function.' );
  551. }
  552. getVar( type, name ) {
  553. return `${ this.getType( type ) } ${ name }`;
  554. }
  555. getVars( shaderStage ) {
  556. let snippet = '';
  557. const vars = this.vars[ shaderStage ];
  558. if ( vars !== undefined ) {
  559. for ( const variable of vars ) {
  560. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  561. }
  562. }
  563. return snippet;
  564. }
  565. getUniforms( /*shaderStage*/ ) {
  566. console.warn( 'Abstract function.' );
  567. }
  568. getCodes( shaderStage ) {
  569. const codes = this.codes[ shaderStage ];
  570. let code = '';
  571. if ( codes !== undefined ) {
  572. for ( const nodeCode of codes ) {
  573. code += nodeCode.code + '\n';
  574. }
  575. }
  576. return code;
  577. }
  578. getHash() {
  579. return this.vertexShader + this.fragmentShader + this.computeShader;
  580. }
  581. setShaderStage( shaderStage ) {
  582. this.shaderStage = shaderStage;
  583. }
  584. getShaderStage() {
  585. return this.shaderStage;
  586. }
  587. setBuildStage( buildStage ) {
  588. this.buildStage = buildStage;
  589. }
  590. getBuildStage() {
  591. return this.buildStage;
  592. }
  593. buildCode() {
  594. console.warn( 'Abstract function.' );
  595. }
  596. build() {
  597. const { object, material } = this;
  598. if ( material !== null ) {
  599. NodeMaterial.fromMaterial( material ).build( this );
  600. } else {
  601. this.addFlow( 'compute', object );
  602. }
  603. // setup() -> stage 1: create possible new nodes and returns an output reference node
  604. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  605. // generate() -> stage 3: generate shader
  606. for ( const buildStage of defaultBuildStages ) {
  607. this.setBuildStage( buildStage );
  608. if ( this.context.vertex && this.context.vertex.isNode ) {
  609. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  610. }
  611. for ( const shaderStage of shaderStages ) {
  612. this.setShaderStage( shaderStage );
  613. const flowNodes = this.flowNodes[ shaderStage ];
  614. for ( const node of flowNodes ) {
  615. if ( buildStage === 'generate' ) {
  616. this.flowNode( node );
  617. } else {
  618. node.build( this );
  619. }
  620. }
  621. }
  622. }
  623. this.setBuildStage( null );
  624. this.setShaderStage( null );
  625. // stage 4: build code for a specific output
  626. this.buildCode();
  627. this.buildUpdateNodes();
  628. return this;
  629. }
  630. getNodeUniform( uniformNode, type ) {
  631. if ( type === 'float' ) return new FloatNodeUniform( uniformNode );
  632. if ( type === 'vec2' ) return new Vector2NodeUniform( uniformNode );
  633. if ( type === 'vec3' ) return new Vector3NodeUniform( uniformNode );
  634. if ( type === 'vec4' ) return new Vector4NodeUniform( uniformNode );
  635. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  636. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  637. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  638. throw new Error( `Uniform "${type}" not declared.` );
  639. }
  640. createNodeMaterial( type = 'NodeMaterial' ) {
  641. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  642. return createNodeMaterialFromType( type );
  643. }
  644. format( snippet, fromType, toType ) {
  645. fromType = this.getVectorType( fromType );
  646. toType = this.getVectorType( toType );
  647. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  648. return snippet;
  649. }
  650. const fromTypeLength = this.getTypeLength( fromType );
  651. const toTypeLength = this.getTypeLength( toType );
  652. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  653. // @TODO: ignore for now
  654. return snippet;
  655. }
  656. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  657. // @TODO: ignore for now
  658. return snippet;
  659. }
  660. if ( fromTypeLength === toTypeLength ) {
  661. return `${ this.getType( toType ) }( ${ snippet } )`;
  662. }
  663. if ( fromTypeLength > toTypeLength ) {
  664. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  665. }
  666. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  667. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  668. }
  669. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  670. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  671. }
  672. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType[ 0 ] !== toType[ 0 ] ) { // fromType is float-like
  673. // convert a number value to vector type, e.g:
  674. // vec3( 1u ) -> vec3( float( 1u ) )
  675. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  676. }
  677. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  678. }
  679. getSignature() {
  680. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  681. }
  682. }
  683. export default NodeBuilder;