NodeBuilder.js 23 KB

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