NodeBuilder.js 15 KB

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