NodeBuilder.js 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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, 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, cache = null ) {
  361. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : 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, this.globalCache );
  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( convertMaterial = true ) {
  599. const { object, material } = this;
  600. if ( convertMaterial ) {
  601. if ( material !== null ) {
  602. NodeMaterial.fromMaterial( material ).build( this );
  603. } else {
  604. this.addFlow( 'compute', object );
  605. }
  606. }
  607. // setup() -> stage 1: create possible new nodes and returns an output reference node
  608. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  609. // generate() -> stage 3: generate shader
  610. for ( const buildStage of defaultBuildStages ) {
  611. this.setBuildStage( buildStage );
  612. if ( this.context.vertex && this.context.vertex.isNode ) {
  613. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  614. }
  615. for ( const shaderStage of shaderStages ) {
  616. this.setShaderStage( shaderStage );
  617. const flowNodes = this.flowNodes[ shaderStage ];
  618. for ( const node of flowNodes ) {
  619. if ( buildStage === 'generate' ) {
  620. this.flowNode( node );
  621. } else {
  622. node.build( this );
  623. }
  624. }
  625. }
  626. }
  627. this.setBuildStage( null );
  628. this.setShaderStage( null );
  629. // stage 4: build code for a specific output
  630. this.buildCode();
  631. this.buildUpdateNodes();
  632. return this;
  633. }
  634. getNodeUniform( uniformNode, type ) {
  635. if ( type === 'float' ) return new FloatNodeUniform( uniformNode );
  636. if ( type === 'vec2' ) return new Vector2NodeUniform( uniformNode );
  637. if ( type === 'vec3' ) return new Vector3NodeUniform( uniformNode );
  638. if ( type === 'vec4' ) return new Vector4NodeUniform( uniformNode );
  639. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  640. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  641. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  642. throw new Error( `Uniform "${type}" not declared.` );
  643. }
  644. createNodeMaterial( type ) {
  645. return createNodeMaterialFromType( type );
  646. }
  647. getPrimitiveType( type ) {
  648. let primitiveType;
  649. if ( type[ 0 ] === 'i' ) primitiveType = 'int';
  650. else if ( type[ 0 ] === 'u' ) primitiveType = 'uint';
  651. else primitiveType = 'float';
  652. return primitiveType;
  653. }
  654. format( snippet, fromType, toType ) {
  655. fromType = this.getVectorType( fromType );
  656. toType = this.getVectorType( toType );
  657. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  658. return snippet;
  659. }
  660. const fromTypeLength = this.getTypeLength( fromType );
  661. const toTypeLength = this.getTypeLength( toType );
  662. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  663. // @TODO: ignore for now
  664. return snippet;
  665. }
  666. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  667. // @TODO: ignore for now
  668. return snippet;
  669. }
  670. if ( fromTypeLength === toTypeLength ) {
  671. return `${ this.getType( toType ) }( ${ snippet } )`;
  672. }
  673. if ( fromTypeLength > toTypeLength ) {
  674. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  675. }
  676. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  677. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  678. }
  679. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  680. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  681. }
  682. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType[ 0 ] !== toType[ 0 ] ) { // fromType is float-like
  683. // convert a number value to vector type, e.g:
  684. // vec3( 1u ) -> vec3( float( 1u ) )
  685. snippet = `${ this.getType( this.getPrimitiveType( toType ) ) }( ${ snippet } )`;
  686. }
  687. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  688. }
  689. getSignature() {
  690. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  691. }
  692. }
  693. export default NodeBuilder;