NodeBuilder.js 15 KB

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