NodeBuilder.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. import NodeUniform from './NodeUniform.js';
  2. import NodeAttribute from './NodeAttribute.js';
  3. import NodeVary from './NodeVary.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 } 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.varys = [];
  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. getTexture( /* textureProperty, uvSnippet */ ) {
  113. console.warn( 'Abstract function.' );
  114. }
  115. getTextureLevel( /* textureProperty, uvSnippet, levelSnippet */ ) {
  116. console.warn( 'Abstract function.' );
  117. }
  118. getCubeTexture( /* textureProperty, uvSnippet */ ) {
  119. console.warn( 'Abstract function.' );
  120. }
  121. getCubeTextureLevel( /* textureProperty, uvSnippet, levelSnippet */ ) {
  122. console.warn( 'Abstract function.' );
  123. }
  124. // @TODO: rename to .generateConst()
  125. getConst( type, value ) {
  126. if ( type === 'float' ) return toFloat( value );
  127. if ( type === 'int' ) return `${ Math.round( value ) }`;
  128. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  129. if ( type === 'bool' ) return value ? 'true' : 'false';
  130. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  131. const typeLength = this.getTypeLength( type );
  132. const componentType = this.getComponentType( type );
  133. const getConst = value => this.getConst( componentType, value );
  134. if ( typeLength === 2 ) {
  135. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) } )`;
  136. } else if ( typeLength === 3 ) {
  137. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) } )`;
  138. } else if ( typeLength === 4 ) {
  139. return `${ this.getType( type ) }( ${ getConst( value.x ) }, ${ getConst( value.y ) }, ${ getConst( value.z ) }, ${ getConst( value.w ) } )`;
  140. } else if ( typeLength > 4 ) {
  141. return `${ this.getType( type ) }()`;
  142. }
  143. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  144. }
  145. getType( type ) {
  146. return type;
  147. }
  148. generateMethod( method ) {
  149. return method;
  150. }
  151. getAttribute( name, type ) {
  152. const attributes = this.attributes;
  153. // find attribute
  154. for ( const attribute of attributes ) {
  155. if ( attribute.name === name ) {
  156. return attribute;
  157. }
  158. }
  159. // create a new if no exist
  160. const attribute = new NodeAttribute( name, type );
  161. attributes.push( attribute );
  162. return attribute;
  163. }
  164. getPropertyName( node/*, shaderStage*/ ) {
  165. return node.name;
  166. }
  167. isVector( type ) {
  168. return /vec\d/.test( type );
  169. }
  170. isMatrix( type ) {
  171. return /mat\d/.test( type );
  172. }
  173. isReference( type ) {
  174. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture';
  175. }
  176. isShaderStage( shaderStage ) {
  177. return this.shaderStage === shaderStage;
  178. }
  179. getTextureEncodingFromMap( map ) {
  180. let encoding;
  181. if ( map && map.isTexture ) {
  182. encoding = map.encoding;
  183. } else if ( map && map.isWebGLRenderTarget ) {
  184. encoding = map.texture.encoding;
  185. } else {
  186. encoding = LinearEncoding;
  187. }
  188. return encoding;
  189. }
  190. getComponentType( type ) {
  191. type = this.getVectorType( type );
  192. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  193. if ( componentType === null ) return null;
  194. if ( componentType[ 1 ] === 'b' ) return 'bool';
  195. if ( componentType[ 1 ] === 'i' ) return 'int';
  196. if ( componentType[ 1 ] === 'u' ) return 'uint';
  197. return 'float';
  198. }
  199. getVectorType( type ) {
  200. if ( type === 'color' ) return 'vec3';
  201. if ( type === 'texture' ) return 'vec4';
  202. return type;
  203. }
  204. getTypeFromLength( length ) {
  205. return typeFromLength.get( length );
  206. }
  207. getTypeLength( type ) {
  208. const vecType = this.getVectorType( type );
  209. const vecNum = /vec([2-4])/.exec( vecType );
  210. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  211. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  212. if ( /mat3/.test( type ) === true ) return 9;
  213. if ( /mat4/.test( type ) === true ) return 16;
  214. return 0;
  215. }
  216. getVectorFromMatrix( type ) {
  217. return type.replace( 'mat', 'vec' );
  218. }
  219. getDataFromNode( node, shaderStage = this.shaderStage ) {
  220. let nodeData = this.nodesData.get( node );
  221. if ( nodeData === undefined ) {
  222. nodeData = { vertex: {}, fragment: {}, compute: {} };
  223. this.nodesData.set( node, nodeData );
  224. }
  225. return shaderStage !== null ? nodeData[ shaderStage ] : nodeData;
  226. }
  227. getNodeProperties( node, shaderStage = this.shaderStage ) {
  228. const nodeData = this.getDataFromNode( this, shaderStage );
  229. const constructHash = node.getConstructHash( this );
  230. nodeData.properties = nodeData.properties || {};
  231. nodeData.properties[ constructHash ] = nodeData.properties[ constructHash ] || { outputNode: null };
  232. return nodeData.properties[ constructHash ];
  233. }
  234. getUniformFromNode( node, shaderStage, type ) {
  235. const nodeData = this.getDataFromNode( node, shaderStage );
  236. let nodeUniform = nodeData.uniform;
  237. if ( nodeUniform === undefined ) {
  238. const index = this.uniforms.index ++;
  239. nodeUniform = new NodeUniform( 'nodeUniform' + index, type, node );
  240. this.uniforms[ shaderStage ].push( nodeUniform );
  241. nodeData.uniform = nodeUniform;
  242. }
  243. return nodeUniform;
  244. }
  245. getVarFromNode( node, type, shaderStage = this.shaderStage ) {
  246. const nodeData = this.getDataFromNode( node, shaderStage );
  247. let nodeVar = nodeData.variable;
  248. if ( nodeVar === undefined ) {
  249. const vars = this.vars[ shaderStage ];
  250. const index = vars.length;
  251. nodeVar = new NodeVar( 'nodeVar' + index, type );
  252. vars.push( nodeVar );
  253. nodeData.variable = nodeVar;
  254. }
  255. return nodeVar;
  256. }
  257. getVaryFromNode( node, type ) {
  258. const nodeData = this.getDataFromNode( node, null );
  259. let nodeVary = nodeData.vary;
  260. if ( nodeVary === undefined ) {
  261. const varys = this.varys;
  262. const index = varys.length;
  263. nodeVary = new NodeVary( 'nodeVary' + index, type );
  264. varys.push( nodeVary );
  265. nodeData.vary = nodeVary;
  266. }
  267. return nodeVary;
  268. }
  269. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  270. const nodeData = this.getDataFromNode( node );
  271. let nodeCode = nodeData.code;
  272. if ( nodeCode === undefined ) {
  273. const codes = this.codes[ shaderStage ];
  274. const index = codes.length;
  275. nodeCode = new NodeCode( 'nodeCode' + index, type );
  276. codes.push( nodeCode );
  277. nodeData.code = nodeCode;
  278. }
  279. return nodeCode;
  280. }
  281. addFlowCode( code ) {
  282. this.flow.code += code;
  283. }
  284. getFlowData( node/*, shaderStage*/ ) {
  285. return this.flowsData.get( node );
  286. }
  287. flowNode( node ) {
  288. const output = node.getNodeType( this );
  289. const flowData = this.flowChildNode( node, output );
  290. this.flowsData.set( node, flowData );
  291. return flowData;
  292. }
  293. flowChildNode( node, output = null ) {
  294. const previousFlow = this.flow;
  295. const flow = {
  296. code: '',
  297. };
  298. this.flow = flow;
  299. flow.result = node.build( this, output );
  300. this.flow = previousFlow;
  301. return flow;
  302. }
  303. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  304. const previousShaderStage = this.shaderStage;
  305. this.setShaderStage( shaderStage );
  306. const flowData = this.flowChildNode( node, output );
  307. if ( propertyName !== null ) {
  308. flowData.code += `${propertyName} = ${flowData.result};\n\t`;
  309. }
  310. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  311. this.setShaderStage( previousShaderStage );
  312. return flowData;
  313. }
  314. getAttributes( /*shaderStage*/ ) {
  315. console.warn( 'Abstract function.' );
  316. }
  317. getVarys( /*shaderStage*/ ) {
  318. console.warn( 'Abstract function.' );
  319. }
  320. getVars( shaderStage ) {
  321. let snippet = '';
  322. const vars = this.vars[ shaderStage ];
  323. for ( const variable of vars ) {
  324. snippet += `${variable.type} ${variable.name}; `;
  325. }
  326. return snippet;
  327. }
  328. getUniforms( /*shaderStage*/ ) {
  329. console.warn( 'Abstract function.' );
  330. }
  331. getCodes( shaderStage ) {
  332. const codes = this.codes[ shaderStage ];
  333. let code = '';
  334. for ( const nodeCode of codes ) {
  335. code += nodeCode.code + '\n';
  336. }
  337. return code;
  338. }
  339. getHash() {
  340. return this.vertexShader + this.fragmentShader + this.computeShader;
  341. }
  342. setShaderStage( shaderStage ) {
  343. this.shaderStage = shaderStage;
  344. }
  345. getShaderStage() {
  346. return this.shaderStage;
  347. }
  348. setBuildStage( buildStage ) {
  349. this.buildStage = buildStage;
  350. }
  351. getBuildStage() {
  352. return this.buildStage;
  353. }
  354. buildCode() {
  355. console.warn( 'Abstract function.' );
  356. }
  357. build() {
  358. // stage 1: generate shader node
  359. this.setBuildStage( 'construct' );
  360. for ( const shaderStage of shaderStages ) {
  361. this.setShaderStage( shaderStage );
  362. const flowNodes = this.flowNodes[ shaderStage ];
  363. for ( const node of flowNodes ) {
  364. node.build( this );
  365. }
  366. }
  367. // stage 2: analyze nodes to possible optimization and validation
  368. this.setBuildStage( 'analyze' );
  369. for ( const shaderStage of shaderStages ) {
  370. this.setShaderStage( shaderStage );
  371. const flowNodes = this.flowNodes[ shaderStage ];
  372. for ( const node of flowNodes ) {
  373. node.build( this );
  374. }
  375. }
  376. // stage 3: pre-build vertex code used in fragment shader
  377. this.setBuildStage( 'generate' );
  378. if ( this.context.vertex && this.context.vertex.isNode ) {
  379. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  380. }
  381. // stage 4: generate shader
  382. this.setBuildStage( 'generate' );
  383. for ( const shaderStage of shaderStages ) {
  384. this.setShaderStage( shaderStage );
  385. const flowNodes = this.flowNodes[ shaderStage ];
  386. for ( const node of flowNodes ) {
  387. this.flowNode( node );
  388. }
  389. }
  390. this.setBuildStage( null );
  391. this.setShaderStage( null );
  392. // stage 5: build code for a specific output
  393. this.buildCode();
  394. return this;
  395. }
  396. format( snippet, fromType, toType ) {
  397. fromType = this.getVectorType( fromType );
  398. toType = this.getVectorType( toType );
  399. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  400. return snippet;
  401. }
  402. const fromTypeLength = this.getTypeLength( fromType );
  403. const toTypeLength = this.getTypeLength( toType );
  404. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  405. // @TODO: ignore for now
  406. return snippet;
  407. }
  408. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  409. // @TODO: ignore for now
  410. return snippet;
  411. }
  412. if ( fromTypeLength === toTypeLength ) {
  413. return `${ this.getType( toType ) }( ${ snippet } )`;
  414. }
  415. if ( fromTypeLength > toTypeLength ) {
  416. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength ), toType );
  417. }
  418. if ( toTypeLength === 4 ) { // toType is vec4-like
  419. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  420. }
  421. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  422. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  423. }
  424. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  425. }
  426. getSignature() {
  427. return `// Three.js r${ REVISION } - NodeMaterial System\n`;
  428. }
  429. }
  430. export default NodeBuilder;