NodeBuilder.js 21 KB

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