NodeBuilder.js 11 KB

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