NodeBuilder.js 16 KB

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