NodeBuilder.js 13 KB

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