NodeBuilder.js 12 KB

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