NodeBuilder.js 11 KB

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