NodeBuilder.js 24 KB

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