NodeBuilder.js 23 KB

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