NodeBuilder.js 23 KB

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