NodeBuilder.js 12 KB

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