NodeBuilder.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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 { createNodeMaterialFromType } from '../materials/NodeMaterial.js';
  10. import { NodeUpdateType, defaultBuildStages, shaderStages } from './constants.js';
  11. import {
  12. FloatNodeUniform, Vector2NodeUniform, Vector3NodeUniform, Vector4NodeUniform,
  13. ColorNodeUniform, Matrix3NodeUniform, Matrix4NodeUniform
  14. } from '../../renderers/common/nodes/NodeUniform.js';
  15. import { REVISION, RenderTarget, NoColorSpace, LinearEncoding, sRGBEncoding, SRGBColorSpace, Color, Vector2, Vector3, Vector4, Float16BufferAttribute } from 'three';
  16. import { stack } from './StackNode.js';
  17. import { getCurrentStack, setCurrentStack } from '../shadernode/ShaderNode.js';
  18. import { maxMipLevel } from '../utils/MaxMipLevelNode.js';
  19. import CubeRenderTarget from '../../renderers/common/CubeRenderTarget.js';
  20. import ChainMap from '../../renderers/common/ChainMap.js';
  21. const uniformsGroupCache = new ChainMap();
  22. const typeFromLength = new Map( [
  23. [ 2, 'vec2' ],
  24. [ 3, 'vec3' ],
  25. [ 4, 'vec4' ],
  26. [ 9, 'mat3' ],
  27. [ 16, 'mat4' ]
  28. ] );
  29. const typeFromArray = new Map( [
  30. [ Int8Array, 'int' ],
  31. [ Int16Array, 'int' ],
  32. [ Int32Array, 'int' ],
  33. [ Uint8Array, 'uint' ],
  34. [ Uint16Array, 'uint' ],
  35. [ Uint32Array, 'uint' ],
  36. [ Float32Array, 'float' ]
  37. ] );
  38. const isNonPaddingElementArray = new Set( [ Int32Array, Uint32Array, Float32Array ] );
  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.toneMappingNode = 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.context = {
  80. keywords: new NodeKeywords(),
  81. material: this.material,
  82. getMIPLevelAlgorithmNode: ( textureNode, levelNode ) => levelNode.mul( maxMipLevel( textureNode ) )
  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. getRenderTarget( width, height, options ) {
  91. return new RenderTarget( width, height, options );
  92. }
  93. getCubeRenderTarget( size, options ) {
  94. return new CubeRenderTarget( size, options );
  95. }
  96. includes( node ) {
  97. return this.nodes.includes( node );
  98. }
  99. _getSharedBindings( bindings ) {
  100. const shared = [];
  101. for ( const binding of bindings ) {
  102. if ( binding.shared === true ) {
  103. // nodes is the chainmap key
  104. const nodes = binding.getNodes();
  105. let sharedBinding = uniformsGroupCache.get( nodes );
  106. if ( sharedBinding === undefined ) {
  107. uniformsGroupCache.set( nodes, binding );
  108. sharedBinding = binding;
  109. }
  110. shared.push( sharedBinding );
  111. } else {
  112. shared.push( binding );
  113. }
  114. }
  115. return shared;
  116. }
  117. getBindings() {
  118. let bindingsArray = this.bindingsArray;
  119. if ( bindingsArray === null ) {
  120. const bindings = this.bindings;
  121. this.bindingsArray = bindingsArray = this._getSharedBindings( ( this.material !== null ) ? [ ...bindings.vertex, ...bindings.fragment ] : bindings.compute );
  122. }
  123. return bindingsArray;
  124. }
  125. setHashNode( node, hash ) {
  126. this.hashNodes[ hash ] = node;
  127. }
  128. addNode( node ) {
  129. if ( this.nodes.includes( node ) === false ) {
  130. this.nodes.push( node );
  131. this.setHashNode( node, node.getHash( this ) );
  132. }
  133. }
  134. buildUpdateNodes() {
  135. for ( const node of this.nodes ) {
  136. const updateType = node.getUpdateType();
  137. const updateBeforeType = node.getUpdateBeforeType();
  138. if ( updateType !== NodeUpdateType.NONE ) {
  139. this.updateNodes.push( node.getSelf() );
  140. }
  141. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  142. this.updateBeforeNodes.push( node );
  143. }
  144. }
  145. }
  146. get currentNode() {
  147. return this.chaining[ this.chaining.length - 1 ];
  148. }
  149. addChain( node ) {
  150. /*
  151. if ( this.chaining.indexOf( node ) !== - 1 ) {
  152. console.warn( 'Recursive node: ', node );
  153. }
  154. */
  155. this.chaining.push( node );
  156. }
  157. removeChain( node ) {
  158. const lastChain = this.chaining.pop();
  159. if ( lastChain !== node ) {
  160. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  161. }
  162. }
  163. getMethod( method ) {
  164. return method;
  165. }
  166. getNodeFromHash( hash ) {
  167. return this.hashNodes[ hash ];
  168. }
  169. addFlow( shaderStage, node ) {
  170. this.flowNodes[ shaderStage ].push( node );
  171. return node;
  172. }
  173. setContext( context ) {
  174. this.context = context;
  175. }
  176. getContext() {
  177. return this.context;
  178. }
  179. setCache( cache ) {
  180. this.cache = cache;
  181. }
  182. getCache() {
  183. return this.cache;
  184. }
  185. isAvailable( /*name*/ ) {
  186. return false;
  187. }
  188. getVertexIndex() {
  189. console.warn( 'Abstract function.' );
  190. }
  191. getInstanceIndex() {
  192. console.warn( 'Abstract function.' );
  193. }
  194. getFrontFacing() {
  195. console.warn( 'Abstract function.' );
  196. }
  197. getFragCoord() {
  198. console.warn( 'Abstract function.' );
  199. }
  200. isFlipY() {
  201. return false;
  202. }
  203. getTexture( /* texture, textureProperty, uvSnippet */ ) {
  204. console.warn( 'Abstract function.' );
  205. }
  206. getTextureLevel( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  207. console.warn( 'Abstract function.' );
  208. }
  209. // @TODO: rename to .generateConst()
  210. getConst( type, value = null ) {
  211. if ( value === null ) {
  212. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  213. else if ( type === 'bool' ) value = false;
  214. else if ( type === 'color' ) value = new Color();
  215. else if ( type === 'vec2' ) value = new Vector2();
  216. else if ( type === 'vec3' ) value = new Vector3();
  217. else if ( type === 'vec4' ) value = new Vector4();
  218. }
  219. if ( type === 'float' ) return toFloat( value );
  220. if ( type === 'int' ) return `${ Math.round( value ) }`;
  221. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  222. if ( type === 'bool' ) return value ? 'true' : 'false';
  223. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  224. const typeLength = this.getTypeLength( type );
  225. const componentType = this.getComponentType( type );
  226. const getConst = value => this.getConst( componentType, value );
  227. if ( typeLength === 2 ) {
  228. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) } )`;
  229. } else if ( typeLength === 3 ) {
  230. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) } )`;
  231. } else if ( typeLength === 4 ) {
  232. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) }, ${ getConst( value.w ) } )`;
  233. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  234. return `${ this.getType( type ) }( ${ value.elements.map( getConst ).join( ', ' ) } )`;
  235. } else if ( typeLength > 4 ) {
  236. return `${ this.getType( type ) }()`;
  237. }
  238. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  239. }
  240. getType( type ) {
  241. if ( type === 'color' ) return 'vec3';
  242. return type;
  243. }
  244. generateMethod( method ) {
  245. return method;
  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';
  274. }
  275. needsColorSpaceToLinear( /*texture*/ ) {
  276. return false;
  277. }
  278. /** @deprecated, r152 */
  279. getTextureEncodingFromMap( map ) {
  280. console.warn( 'THREE.NodeBuilder: Method .getTextureEncodingFromMap replaced by .getTextureColorSpaceFromMap in r152+.' );
  281. return this.getTextureColorSpaceFromMap( map ) === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  282. }
  283. getTextureColorSpaceFromMap( map ) {
  284. let colorSpace;
  285. if ( map && map.isTexture ) {
  286. colorSpace = map.colorSpace;
  287. } else if ( map && map.isWebGLRenderTarget ) {
  288. colorSpace = map.texture.colorSpace;
  289. } else {
  290. colorSpace = NoColorSpace;
  291. }
  292. return colorSpace;
  293. }
  294. getComponentType( type ) {
  295. type = this.getVectorType( type );
  296. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  297. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  298. if ( componentType === null ) return null;
  299. if ( componentType[ 1 ] === 'b' ) return 'bool';
  300. if ( componentType[ 1 ] === 'i' ) return 'int';
  301. if ( componentType[ 1 ] === 'u' ) return 'uint';
  302. return 'float';
  303. }
  304. getVectorType( type ) {
  305. if ( type === 'color' ) return 'vec3';
  306. if ( type === 'texture' ) return 'vec4';
  307. return type;
  308. }
  309. getTypeFromLength( length, componentType = 'float' ) {
  310. if ( length === 1 ) return componentType;
  311. const baseType = typeFromLength.get( length );
  312. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  313. return prefix + baseType;
  314. }
  315. getTypeFromArray( array ) {
  316. return typeFromArray.get( array.constructor );
  317. }
  318. getTypeFromAttribute( attribute ) {
  319. let dataAttribute = attribute;
  320. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  321. const array = dataAttribute.array;
  322. const itemSize = isNonPaddingElementArray.has( array.constructor ) ? attribute.itemSize : dataAttribute.stride || attribute.itemSize;
  323. const normalized = attribute.normalized;
  324. let arrayType;
  325. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  326. arrayType = this.getTypeFromArray( array );
  327. }
  328. return this.getTypeFromLength( itemSize, arrayType );
  329. }
  330. getTypeLength( type ) {
  331. const vecType = this.getVectorType( type );
  332. const vecNum = /vec([2-4])/.exec( vecType );
  333. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  334. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  335. if ( /mat3/.test( type ) === true ) return 9;
  336. if ( /mat4/.test( type ) === true ) return 16;
  337. return 0;
  338. }
  339. getVectorFromMatrix( type ) {
  340. return type.replace( 'mat', 'vec' );
  341. }
  342. changeComponentType( type, newComponentType ) {
  343. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  344. }
  345. getIntegerType( type ) {
  346. const componentType = this.getComponentType( type );
  347. if ( componentType === 'int' || componentType === 'uint' ) return type;
  348. return this.changeComponentType( type, 'int' );
  349. }
  350. addStack() {
  351. this.stack = stack( this.stack );
  352. this.stacks.push( getCurrentStack() || this.stack );
  353. setCurrentStack( this.stack );
  354. return this.stack;
  355. }
  356. removeStack() {
  357. const lastStack = this.stack;
  358. this.stack = lastStack.parent;
  359. setCurrentStack( this.stacks.pop() );
  360. return lastStack;
  361. }
  362. getDataFromNode( node, shaderStage = this.shaderStage ) {
  363. const cache = node.isGlobal( this ) ? this.globalCache : this.cache;
  364. let nodeData = cache.getNodeData( node );
  365. if ( nodeData === undefined ) {
  366. nodeData = {};
  367. cache.setNodeData( node, nodeData );
  368. }
  369. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  370. return nodeData[ shaderStage ];
  371. }
  372. getNodeProperties( node, shaderStage = 'any' ) {
  373. const nodeData = this.getDataFromNode( node, shaderStage );
  374. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  375. }
  376. getBufferAttributeFromNode( node, type ) {
  377. const nodeData = this.getDataFromNode( node );
  378. let bufferAttribute = nodeData.bufferAttribute;
  379. if ( bufferAttribute === undefined ) {
  380. const index = this.uniforms.index ++;
  381. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  382. this.bufferAttributes.push( bufferAttribute );
  383. nodeData.bufferAttribute = bufferAttribute;
  384. }
  385. return bufferAttribute;
  386. }
  387. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  388. const nodeData = this.getDataFromNode( node, shaderStage );
  389. if ( nodeData.structType === undefined ) {
  390. const index = this.structs.index ++;
  391. node.name = `StructType${ index }`;
  392. this.structs[ shaderStage ].push( node );
  393. nodeData.structType = node;
  394. }
  395. return node;
  396. }
  397. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  398. const nodeData = this.getDataFromNode( node, shaderStage );
  399. let nodeUniform = nodeData.uniform;
  400. if ( nodeUniform === undefined ) {
  401. const index = this.uniforms.index ++;
  402. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  403. this.uniforms[ shaderStage ].push( nodeUniform );
  404. nodeData.uniform = nodeUniform;
  405. }
  406. return nodeUniform;
  407. }
  408. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  409. const nodeData = this.getDataFromNode( node, shaderStage );
  410. let nodeVar = nodeData.variable;
  411. if ( nodeVar === undefined ) {
  412. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  413. if ( name === null ) name = 'nodeVar' + vars.length;
  414. nodeVar = new NodeVar( name, type );
  415. vars.push( nodeVar );
  416. nodeData.variable = nodeVar;
  417. }
  418. return nodeVar;
  419. }
  420. getVaryingFromNode( node, type ) {
  421. const nodeData = this.getDataFromNode( node, 'any' );
  422. let nodeVarying = nodeData.varying;
  423. if ( nodeVarying === undefined ) {
  424. const varyings = this.varyings;
  425. const index = varyings.length;
  426. nodeVarying = new NodeVarying( 'nodeVarying' + index, 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. flowShaderNode( shaderNode ) {
  475. const layout = shaderNode.layout;
  476. let inputs;
  477. if ( shaderNode.isArrayInput ) {
  478. inputs = [];
  479. for ( const input of layout.inputs ) {
  480. inputs.push( new ParameterNode( input.type, input.name ) );
  481. }
  482. } else {
  483. inputs = {};
  484. for ( const input of layout.inputs ) {
  485. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  486. }
  487. }
  488. //
  489. shaderNode.layout = null;
  490. const callNode = shaderNode.call( inputs );
  491. const flowData = this.flowStagesNode( callNode, layout.type );
  492. shaderNode.layout = layout;
  493. return flowData;
  494. }
  495. flowStagesNode( node, output = null ) {
  496. const previousFlow = this.flow;
  497. const previousVars = this.vars;
  498. const previousBuildStage = this.buildStage;
  499. const flow = {
  500. code: ''
  501. };
  502. this.flow = flow;
  503. this.vars = {};
  504. for ( const buildStage of defaultBuildStages ) {
  505. this.setBuildStage( buildStage );
  506. flow.result = node.build( this, output );
  507. }
  508. flow.vars = this.getVars( this.shaderStage );
  509. this.flow = previousFlow;
  510. this.vars = previousVars;
  511. this.setBuildStage( previousBuildStage );
  512. return flow;
  513. }
  514. flowChildNode( node, output = null ) {
  515. const previousFlow = this.flow;
  516. const flow = {
  517. code: ''
  518. };
  519. this.flow = flow;
  520. flow.result = node.build( this, output );
  521. this.flow = previousFlow;
  522. return flow;
  523. }
  524. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  525. const previousShaderStage = this.shaderStage;
  526. this.setShaderStage( shaderStage );
  527. const flowData = this.flowChildNode( node, output );
  528. if ( propertyName !== null ) {
  529. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  530. }
  531. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  532. this.setShaderStage( previousShaderStage );
  533. return flowData;
  534. }
  535. getAttributesArray() {
  536. return this.attributes.concat( this.bufferAttributes );
  537. }
  538. getAttributes( /*shaderStage*/ ) {
  539. console.warn( 'Abstract function.' );
  540. }
  541. getVaryings( /*shaderStage*/ ) {
  542. console.warn( 'Abstract function.' );
  543. }
  544. getVar( type, name ) {
  545. return `${ this.getType( type ) } ${ name }`;
  546. }
  547. getVars( shaderStage ) {
  548. let snippet = '';
  549. const vars = this.vars[ shaderStage ];
  550. if ( vars !== undefined ) {
  551. for ( const variable of vars ) {
  552. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  553. }
  554. }
  555. return snippet;
  556. }
  557. getUniforms( /*shaderStage*/ ) {
  558. console.warn( 'Abstract function.' );
  559. }
  560. getCodes( shaderStage ) {
  561. const codes = this.codes[ shaderStage ];
  562. let code = '';
  563. if ( codes !== undefined ) {
  564. for ( const nodeCode of codes ) {
  565. code += nodeCode.code + '\n';
  566. }
  567. }
  568. return code;
  569. }
  570. getHash() {
  571. return this.vertexShader + this.fragmentShader + this.computeShader;
  572. }
  573. setShaderStage( shaderStage ) {
  574. this.shaderStage = shaderStage;
  575. }
  576. getShaderStage() {
  577. return this.shaderStage;
  578. }
  579. setBuildStage( buildStage ) {
  580. this.buildStage = buildStage;
  581. }
  582. getBuildStage() {
  583. return this.buildStage;
  584. }
  585. buildCode() {
  586. console.warn( 'Abstract function.' );
  587. }
  588. build() {
  589. // setup() -> stage 1: create possible new nodes and returns an output reference node
  590. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  591. // generate() -> stage 3: generate shader
  592. for ( const buildStage of defaultBuildStages ) {
  593. this.setBuildStage( buildStage );
  594. if ( this.context.vertex && this.context.vertex.isNode ) {
  595. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  596. }
  597. for ( const shaderStage of shaderStages ) {
  598. this.setShaderStage( shaderStage );
  599. const flowNodes = this.flowNodes[ shaderStage ];
  600. for ( const node of flowNodes ) {
  601. if ( buildStage === 'generate' ) {
  602. this.flowNode( node );
  603. } else {
  604. node.build( this );
  605. }
  606. }
  607. }
  608. }
  609. this.setBuildStage( null );
  610. this.setShaderStage( null );
  611. // stage 4: build code for a specific output
  612. this.buildCode();
  613. this.buildUpdateNodes();
  614. return this;
  615. }
  616. getNodeUniform( uniformNode, type ) {
  617. if ( type === 'float' ) return new FloatNodeUniform( uniformNode );
  618. if ( type === 'vec2' ) return new Vector2NodeUniform( uniformNode );
  619. if ( type === 'vec3' ) return new Vector3NodeUniform( uniformNode );
  620. if ( type === 'vec4' ) return new Vector4NodeUniform( uniformNode );
  621. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  622. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  623. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  624. throw new Error( `Uniform "${type}" not declared.` );
  625. }
  626. createNodeMaterial( type ) {
  627. return createNodeMaterialFromType( type );
  628. }
  629. getPrimitiveType( type ) {
  630. let primitiveType;
  631. if ( type[ 0 ] === 'i' ) primitiveType = 'int';
  632. else if ( type[ 0 ] === 'u' ) primitiveType = 'uint';
  633. else primitiveType = 'float';
  634. return primitiveType;
  635. }
  636. format( snippet, fromType, toType ) {
  637. fromType = this.getVectorType( fromType );
  638. toType = this.getVectorType( toType );
  639. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  640. return snippet;
  641. }
  642. const fromTypeLength = this.getTypeLength( fromType );
  643. const toTypeLength = this.getTypeLength( toType );
  644. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  645. // @TODO: ignore for now
  646. return snippet;
  647. }
  648. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  649. // @TODO: ignore for now
  650. return snippet;
  651. }
  652. if ( fromTypeLength === toTypeLength ) {
  653. return `${ this.getType( toType ) }( ${ snippet } )`;
  654. }
  655. if ( fromTypeLength > toTypeLength ) {
  656. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  657. }
  658. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  659. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  660. }
  661. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  662. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  663. }
  664. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType[ 0 ] !== toType[ 0 ] ) { // fromType is float-like
  665. // convert a number value to vector type, e.g:
  666. // vec3( 1u ) -> vec3( float( 1u ) )
  667. snippet = `${ this.getType( this.getPrimitiveType( toType ) ) }( ${ snippet } )`;
  668. }
  669. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  670. }
  671. getSignature() {
  672. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  673. }
  674. }
  675. export default NodeBuilder;