NodeBuilder.js 15 KB

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