NodeBuilder.js 14 KB

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