NodeBuilder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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 { NodeUpdateType, defaultBuildStages, shaderStages } from './constants.js';
  9. import { REVISION, NoColorSpace, LinearEncoding, sRGBEncoding, SRGBColorSpace, Color, Vector2, Vector3, Vector4, Float16BufferAttribute } from 'three';
  10. import { stack } from './StackNode.js';
  11. import { maxMipLevel } from '../utils/MaxMipLevelNode.js';
  12. const typeFromLength = new Map( [
  13. [ 2, 'vec2' ],
  14. [ 3, 'vec3' ],
  15. [ 4, 'vec4' ],
  16. [ 9, 'mat3' ],
  17. [ 16, 'mat4' ]
  18. ] );
  19. const typeFromArray = new Map( [
  20. [ Int8Array, 'int' ],
  21. [ Int16Array, 'int' ],
  22. [ Int32Array, 'int' ],
  23. [ Uint8Array, 'uint' ],
  24. [ Uint16Array, 'uint' ],
  25. [ Uint32Array, 'uint' ],
  26. [ Float32Array, 'float' ]
  27. ] );
  28. const isNonPaddingElementArray = new Set( [ Int32Array, Uint32Array, Float32Array ] );
  29. const toFloat = ( value ) => {
  30. value = Number( value );
  31. return value + ( value % 1 ? '' : '.0' );
  32. };
  33. class NodeBuilder {
  34. constructor( object, renderer, parser ) {
  35. this.object = object;
  36. this.material = object && ( object.material || null );
  37. this.geometry = object && ( object.geometry || null );
  38. this.renderer = renderer;
  39. this.parser = parser;
  40. this.nodes = [];
  41. this.updateNodes = [];
  42. this.updateBeforeNodes = [];
  43. this.hashNodes = {};
  44. this.lightsNode = null;
  45. this.environmentNode = null;
  46. this.fogNode = null;
  47. this.toneMappingNode = null;
  48. this.vertexShader = null;
  49. this.fragmentShader = null;
  50. this.computeShader = null;
  51. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  52. this.flowCode = { vertex: '', fragment: '', compute: [] };
  53. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  54. this.codes = { vertex: [], fragment: [], compute: [] };
  55. this.attributes = [];
  56. this.bufferAttributes = [];
  57. this.varyings = [];
  58. this.vars = { vertex: [], fragment: [], compute: [] };
  59. this.flow = { code: '' };
  60. this.chaining = [];
  61. this.stack = stack();
  62. this.tab = '\t';
  63. this.context = {
  64. keywords: new NodeKeywords(),
  65. material: this.material,
  66. getMIPLevelAlgorithmNode: ( textureNode, levelNode ) => levelNode.mul( maxMipLevel( textureNode ) )
  67. };
  68. this.cache = new NodeCache();
  69. this.globalCache = this.cache;
  70. this.flowsData = new WeakMap();
  71. this.shaderStage = null;
  72. this.buildStage = null;
  73. }
  74. setHashNode( node, hash ) {
  75. this.hashNodes[ hash ] = node;
  76. }
  77. addNode( node ) {
  78. if ( this.nodes.indexOf( node ) === - 1 ) {
  79. const updateType = node.getUpdateType();
  80. const updateBeforeType = node.getUpdateBeforeType();
  81. if ( updateType !== NodeUpdateType.NONE ) {
  82. this.updateNodes.push( node );
  83. }
  84. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  85. this.updateBeforeNodes.push( node );
  86. }
  87. this.nodes.push( node );
  88. this.setHashNode( node, node.getHash( this ) );
  89. }
  90. }
  91. get currentNode() {
  92. return this.chaining[ this.chaining.length - 1 ];
  93. }
  94. addChain( node ) {
  95. /*
  96. if ( this.chaining.indexOf( node ) !== - 1 ) {
  97. console.warn( 'Recursive node: ', node );
  98. }
  99. */
  100. this.chaining.push( node );
  101. }
  102. removeChain( node ) {
  103. const lastChain = this.chaining.pop();
  104. if ( lastChain !== node ) {
  105. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  106. }
  107. }
  108. getMethod( method ) {
  109. return method;
  110. }
  111. getNodeFromHash( hash ) {
  112. return this.hashNodes[ hash ];
  113. }
  114. addFlow( shaderStage, node ) {
  115. this.flowNodes[ shaderStage ].push( node );
  116. return node;
  117. }
  118. setContext( context ) {
  119. this.context = context;
  120. }
  121. getContext() {
  122. return this.context;
  123. }
  124. setCache( cache ) {
  125. this.cache = cache;
  126. }
  127. getCache() {
  128. return this.cache;
  129. }
  130. isAvailable( /*name*/ ) {
  131. return false;
  132. }
  133. getInstanceIndex() {
  134. console.warn( 'Abstract function.' );
  135. }
  136. getFrontFacing() {
  137. console.warn( 'Abstract function.' );
  138. }
  139. getFragCoord() {
  140. console.warn( 'Abstract function.' );
  141. }
  142. isFlipY() {
  143. return false;
  144. }
  145. getTexture( /* texture, textureProperty, uvSnippet */ ) {
  146. console.warn( 'Abstract function.' );
  147. }
  148. getTextureLevel( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  149. console.warn( 'Abstract function.' );
  150. }
  151. // @TODO: rename to .generateConst()
  152. getConst( type, value = null ) {
  153. if ( value === null ) {
  154. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  155. else if ( type === 'bool' ) value = false;
  156. else if ( type === 'color' ) value = new Color();
  157. else if ( type === 'vec2' ) value = new Vector2();
  158. else if ( type === 'vec3' ) value = new Vector3();
  159. else if ( type === 'vec4' ) value = new Vector4();
  160. }
  161. if ( type === 'float' ) return toFloat( value );
  162. if ( type === 'int' ) return `${ Math.round( value ) }`;
  163. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  164. if ( type === 'bool' ) return value ? 'true' : 'false';
  165. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  166. const typeLength = this.getTypeLength( type );
  167. const componentType = this.getComponentType( type );
  168. const getConst = value => this.getConst( componentType, value );
  169. if ( typeLength === 2 ) {
  170. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) } )`;
  171. } else if ( typeLength === 3 ) {
  172. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) } )`;
  173. } else if ( typeLength === 4 ) {
  174. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) }, ${ getConst( value.w ) } )`;
  175. } else if ( typeLength > 4 ) {
  176. return `${ this.getType( type ) }()`;
  177. }
  178. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  179. }
  180. getType( type ) {
  181. return type;
  182. }
  183. generateMethod( method ) {
  184. return method;
  185. }
  186. hasGeometryAttribute( name ) {
  187. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  188. }
  189. getAttribute( name, type ) {
  190. const attributes = this.attributes;
  191. // find attribute
  192. for ( const attribute of attributes ) {
  193. if ( attribute.name === name ) {
  194. return attribute;
  195. }
  196. }
  197. // create a new if no exist
  198. const attribute = new NodeAttribute( name, type );
  199. attributes.push( attribute );
  200. return attribute;
  201. }
  202. getPropertyName( node/*, shaderStage*/ ) {
  203. return node.name;
  204. }
  205. isVector( type ) {
  206. return /vec\d/.test( type );
  207. }
  208. isMatrix( type ) {
  209. return /mat\d/.test( type );
  210. }
  211. isReference( type ) {
  212. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture';
  213. }
  214. isShaderStage( shaderStage ) {
  215. return this.shaderStage === shaderStage;
  216. }
  217. /** @deprecated, r152 */
  218. getTextureEncodingFromMap( map ) {
  219. console.warn( 'THREE.NodeBuilder: Method .getTextureEncodingFromMap replaced by .getTextureColorSpaceFromMap in r152+.' );
  220. return this.getTextureColorSpaceFromMap( map ) === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  221. }
  222. getTextureColorSpaceFromMap( map ) {
  223. let colorSpace;
  224. if ( map && map.isTexture ) {
  225. colorSpace = map.colorSpace;
  226. } else if ( map && map.isWebGLRenderTarget ) {
  227. colorSpace = map.texture.colorSpace;
  228. } else {
  229. colorSpace = NoColorSpace;
  230. }
  231. return colorSpace;
  232. }
  233. getComponentType( type ) {
  234. type = this.getVectorType( type );
  235. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  236. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  237. if ( componentType === null ) return null;
  238. if ( componentType[ 1 ] === 'b' ) return 'bool';
  239. if ( componentType[ 1 ] === 'i' ) return 'int';
  240. if ( componentType[ 1 ] === 'u' ) return 'uint';
  241. return 'float';
  242. }
  243. getVectorType( type ) {
  244. if ( type === 'color' ) return 'vec3';
  245. if ( type === 'texture' ) return 'vec4';
  246. return type;
  247. }
  248. getTypeFromLength( length, componentType = 'float' ) {
  249. if ( length === 1 ) return componentType;
  250. const baseType = typeFromLength.get( length );
  251. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  252. return prefix + baseType;
  253. }
  254. getTypeFromArray( array ) {
  255. return typeFromArray.get( array.constructor );
  256. }
  257. getTypeFromAttribute( attribute ) {
  258. let dataAttribute = attribute;
  259. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  260. const array = dataAttribute.array;
  261. const itemSize = isNonPaddingElementArray.has( array.constructor ) ? attribute.itemSize : dataAttribute.stride || attribute.itemSize;
  262. const normalized = attribute.normalized;
  263. let arrayType;
  264. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  265. arrayType = this.getTypeFromArray( array );
  266. }
  267. return this.getTypeFromLength( itemSize, arrayType );
  268. }
  269. getTypeLength( type ) {
  270. const vecType = this.getVectorType( type );
  271. const vecNum = /vec([2-4])/.exec( vecType );
  272. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  273. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  274. if ( /mat3/.test( type ) === true ) return 9;
  275. if ( /mat4/.test( type ) === true ) return 16;
  276. return 0;
  277. }
  278. getVectorFromMatrix( type ) {
  279. return type.replace( 'mat', 'vec' );
  280. }
  281. changeComponentType( type, newComponentType ) {
  282. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  283. }
  284. getIntegerType( type ) {
  285. const componentType = this.getComponentType( type );
  286. if ( componentType === 'int' || componentType === 'uint' ) return type;
  287. return this.changeComponentType( type, 'int' );
  288. }
  289. addStack() {
  290. this.stack = stack( this.stack );
  291. return this.stack;
  292. }
  293. removeStack() {
  294. const currentStack = this.stack;
  295. this.stack = currentStack.parent;
  296. return currentStack;
  297. }
  298. getDataFromNode( node, shaderStage = this.shaderStage ) {
  299. const cache = node.isGlobal( this ) ? this.globalCache : this.cache;
  300. let nodeData = cache.getNodeData( node );
  301. if ( nodeData === undefined ) {
  302. nodeData = { vertex: {}, fragment: {}, compute: {} };
  303. cache.setNodeData( node, nodeData );
  304. }
  305. return shaderStage !== null ? nodeData[ shaderStage ] : nodeData;
  306. }
  307. getNodeProperties( node, shaderStage = this.shaderStage ) {
  308. const nodeData = this.getDataFromNode( node, shaderStage );
  309. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  310. }
  311. getBufferAttributeFromNode( node, type ) {
  312. const nodeData = this.getDataFromNode( node );
  313. let bufferAttribute = nodeData.bufferAttribute;
  314. if ( bufferAttribute === undefined ) {
  315. const index = this.uniforms.index ++;
  316. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  317. this.bufferAttributes.push( bufferAttribute );
  318. nodeData.bufferAttribute = bufferAttribute;
  319. }
  320. return bufferAttribute;
  321. }
  322. getUniformFromNode( node, type, shaderStage = this.shaderStage ) {
  323. const nodeData = this.getDataFromNode( node, shaderStage );
  324. let nodeUniform = nodeData.uniform;
  325. if ( nodeUniform === undefined ) {
  326. const index = this.uniforms.index ++;
  327. nodeUniform = new NodeUniform( 'nodeUniform' + index, type, node );
  328. this.uniforms[ shaderStage ].push( nodeUniform );
  329. nodeData.uniform = nodeUniform;
  330. }
  331. return nodeUniform;
  332. }
  333. getVarFromNode( node, type, shaderStage = this.shaderStage ) {
  334. const nodeData = this.getDataFromNode( node, shaderStage );
  335. let nodeVar = nodeData.variable;
  336. if ( nodeVar === undefined ) {
  337. const vars = this.vars[ shaderStage ];
  338. const index = vars.length;
  339. nodeVar = new NodeVar( 'nodeVar' + index, type );
  340. vars.push( nodeVar );
  341. nodeData.variable = nodeVar;
  342. }
  343. return nodeVar;
  344. }
  345. getVaryingFromNode( node, type ) {
  346. const nodeData = this.getDataFromNode( node, null );
  347. let nodeVarying = nodeData.varying;
  348. if ( nodeVarying === undefined ) {
  349. const varyings = this.varyings;
  350. const index = varyings.length;
  351. nodeVarying = new NodeVarying( 'nodeVarying' + index, type );
  352. varyings.push( nodeVarying );
  353. nodeData.varying = nodeVarying;
  354. }
  355. return nodeVarying;
  356. }
  357. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  358. const nodeData = this.getDataFromNode( node );
  359. let nodeCode = nodeData.code;
  360. if ( nodeCode === undefined ) {
  361. const codes = this.codes[ shaderStage ];
  362. const index = codes.length;
  363. nodeCode = new NodeCode( 'nodeCode' + index, type );
  364. codes.push( nodeCode );
  365. nodeData.code = nodeCode;
  366. }
  367. return nodeCode;
  368. }
  369. addLineFlowCode( code ) {
  370. if ( code === '' ) return this;
  371. code = this.tab + code;
  372. if ( ! /;\s*$/.test( code ) ) {
  373. code = code + ';\n';
  374. }
  375. this.flow.code += code;
  376. return this;
  377. }
  378. addFlowCode( code ) {
  379. this.flow.code += code;
  380. return this;
  381. }
  382. addFlowTab() {
  383. this.tab += '\t';
  384. return this;
  385. }
  386. removeFlowTab() {
  387. this.tab = this.tab.slice( 0, - 1 );
  388. return this;
  389. }
  390. getFlowData( node/*, shaderStage*/ ) {
  391. return this.flowsData.get( node );
  392. }
  393. flowNode( node ) {
  394. const output = node.getNodeType( this );
  395. const flowData = this.flowChildNode( node, output );
  396. this.flowsData.set( node, flowData );
  397. return flowData;
  398. }
  399. flowChildNode( node, output = null ) {
  400. const previousFlow = this.flow;
  401. const flow = {
  402. code: '',
  403. };
  404. this.flow = flow;
  405. flow.result = node.build( this, output );
  406. this.flow = previousFlow;
  407. return flow;
  408. }
  409. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  410. const previousShaderStage = this.shaderStage;
  411. this.setShaderStage( shaderStage );
  412. const flowData = this.flowChildNode( node, output );
  413. if ( propertyName !== null ) {
  414. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  415. }
  416. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  417. this.setShaderStage( previousShaderStage );
  418. return flowData;
  419. }
  420. getAttributesArray() {
  421. return this.attributes.concat( this.bufferAttributes );
  422. }
  423. getAttributes( /*shaderStage*/ ) {
  424. console.warn( 'Abstract function.' );
  425. }
  426. getVaryings( /*shaderStage*/ ) {
  427. console.warn( 'Abstract function.' );
  428. }
  429. getVar( type, name ) {
  430. return `${type} ${name}`;
  431. }
  432. getVars( shaderStage ) {
  433. let snippet = '';
  434. const vars = this.vars[ shaderStage ];
  435. for ( const variable of vars ) {
  436. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  437. }
  438. return snippet;
  439. }
  440. getUniforms( /*shaderStage*/ ) {
  441. console.warn( 'Abstract function.' );
  442. }
  443. getCodes( shaderStage ) {
  444. const codes = this.codes[ shaderStage ];
  445. let code = '';
  446. for ( const nodeCode of codes ) {
  447. code += nodeCode.code + '\n';
  448. }
  449. return code;
  450. }
  451. getHash() {
  452. return this.vertexShader + this.fragmentShader + this.computeShader;
  453. }
  454. setShaderStage( shaderStage ) {
  455. this.shaderStage = shaderStage;
  456. }
  457. getShaderStage() {
  458. return this.shaderStage;
  459. }
  460. setBuildStage( buildStage ) {
  461. this.buildStage = buildStage;
  462. }
  463. getBuildStage() {
  464. return this.buildStage;
  465. }
  466. buildCode() {
  467. console.warn( 'Abstract function.' );
  468. }
  469. build() {
  470. // construct() -> stage 1: create possible new nodes and returns an output reference node
  471. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  472. // generate() -> stage 3: generate shader
  473. for ( const buildStage of defaultBuildStages ) {
  474. this.setBuildStage( buildStage );
  475. if ( this.context.vertex && this.context.vertex.isNode ) {
  476. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  477. }
  478. for ( const shaderStage of shaderStages ) {
  479. this.setShaderStage( shaderStage );
  480. const flowNodes = this.flowNodes[ shaderStage ];
  481. for ( const node of flowNodes ) {
  482. if ( buildStage === 'generate' ) {
  483. this.flowNode( node );
  484. } else {
  485. node.build( this );
  486. }
  487. }
  488. }
  489. }
  490. this.setBuildStage( null );
  491. this.setShaderStage( null );
  492. // stage 4: build code for a specific output
  493. this.buildCode();
  494. return this;
  495. }
  496. format( snippet, fromType, toType ) {
  497. fromType = this.getVectorType( fromType );
  498. toType = this.getVectorType( toType );
  499. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  500. return snippet;
  501. }
  502. const fromTypeLength = this.getTypeLength( fromType );
  503. const toTypeLength = this.getTypeLength( toType );
  504. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  505. // @TODO: ignore for now
  506. return snippet;
  507. }
  508. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  509. // @TODO: ignore for now
  510. return snippet;
  511. }
  512. if ( fromTypeLength === toTypeLength ) {
  513. return `${ this.getType( toType ) }( ${ snippet } )`;
  514. }
  515. if ( fromTypeLength > toTypeLength ) {
  516. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  517. }
  518. if ( toTypeLength === 4 ) { // toType is vec4-like
  519. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  520. }
  521. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  522. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  523. }
  524. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  525. }
  526. getSignature() {
  527. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  528. }
  529. }
  530. export default NodeBuilder;