NodeBuilder.js 17 KB

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