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