NodeBuilder.js 26 KB

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