NodeBuilder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. /**
  2. * @author sunag / http://www.sunag.com.br/
  3. */
  4. import { NodeUniform } from './NodeUniform.js';
  5. import { NodeUtils } from './NodeUtils.js';
  6. import { NodeLib } from './NodeLib.js';
  7. import { FunctionNode } from './FunctionNode.js';
  8. import { ConstNode } from './ConstNode.js';
  9. import { StructNode } from './StructNode.js';
  10. import { Vector2Node } from '../inputs/Vector2Node.js';
  11. import { Vector3Node } from '../inputs/Vector3Node.js';
  12. import { Vector4Node } from '../inputs/Vector4Node.js';
  13. import { TextureNode } from '../inputs/TextureNode.js';
  14. import { CubeTextureNode } from '../inputs/CubeTextureNode.js';
  15. var elements = NodeUtils.elements,
  16. constructors = [ 'float', 'vec2', 'vec3', 'vec4' ],
  17. convertFormatToType = {
  18. float: 'f',
  19. vec2: 'v2',
  20. vec3: 'v3',
  21. vec4: 'v4',
  22. mat4: 'v4',
  23. int: 'i'
  24. },
  25. convertTypeToFormat = {
  26. t: 'sampler2D',
  27. tc: 'samplerCube',
  28. b: 'bool',
  29. i: 'int',
  30. f: 'float',
  31. c: 'vec3',
  32. v2: 'vec2',
  33. v3: 'vec3',
  34. v4: 'vec4',
  35. m3: 'mat3',
  36. m4: 'mat4'
  37. };
  38. function NodeBuilder() {
  39. this.slots = [];
  40. this.caches = [];
  41. this.contexts = [];
  42. this.keywords = {};
  43. this.nodeData = {};
  44. this.requires = {
  45. uv: [],
  46. color: [],
  47. lights: false,
  48. fog: false
  49. };
  50. this.includes = {
  51. consts: [],
  52. functions: [],
  53. structs: []
  54. };
  55. this.attributes = {};
  56. this.prefixCode = [
  57. "#ifdef GL_EXT_shader_texture_lod",
  58. " #define texCube(a, b) textureCube(a, b)",
  59. " #define texCubeBias(a, b, c) textureCubeLodEXT(a, b, c)",
  60. " #define tex2D(a, b) texture2D(a, b)",
  61. " #define tex2DBias(a, b, c) texture2DLodEXT(a, b, c)",
  62. "#else",
  63. " #define texCube(a, b) textureCube(a, b)",
  64. " #define texCubeBias(a, b, c) textureCube(a, b, c)",
  65. " #define tex2D(a, b) texture2D(a, b)",
  66. " #define tex2DBias(a, b, c) texture2D(a, b, c)",
  67. "#endif",
  68. "#include <packing>"
  69. ].join( "\n" );
  70. this.parsCode = {
  71. vertex: '',
  72. fragment: ''
  73. };
  74. this.code = {
  75. vertex: '',
  76. fragment: ''
  77. };
  78. this.nodeCode = {
  79. vertex: '',
  80. fragment: ''
  81. };
  82. this.resultCode = {
  83. vertex: '',
  84. fragment: ''
  85. };
  86. this.finalCode = {
  87. vertex: '',
  88. fragment: ''
  89. };
  90. this.inputs = {
  91. uniforms: {
  92. list: [],
  93. vertex: [],
  94. fragment: []
  95. },
  96. vars: {
  97. varying: [],
  98. vertex: [],
  99. fragment: []
  100. }
  101. };
  102. // send to material
  103. this.defines = {};
  104. this.uniforms = {};
  105. this.extensions = {};
  106. this.updaters = [];
  107. this.nodes = [];
  108. // --
  109. this.parsing = false;
  110. this.optimize = true;
  111. };
  112. NodeBuilder.prototype = {
  113. constructor: NodeBuilder,
  114. build: function( vertex, fragment ) {
  115. this.buildShader( 'vertex', vertex );
  116. this.buildShader( 'fragment', fragment );
  117. if ( this.requires.uv[ 0 ] ) {
  118. this.addVaryCode( 'varying vec2 vUv;' );
  119. this.addVertexFinalCode( 'vUv = uv;' );
  120. }
  121. if ( this.requires.uv[ 1 ] ) {
  122. this.addVaryCode( 'varying vec2 vUv2;' );
  123. this.addVertexParsCode( 'attribute vec2 uv2;' );
  124. this.addVertexFinalCode( 'vUv2 = uv2;' );
  125. }
  126. if ( this.requires.color[ 0 ] ) {
  127. this.addVaryCode( 'varying vec4 vColor;' );
  128. this.addVertexParsCode( 'attribute vec4 color;' );
  129. this.addVertexFinalCode( 'vColor = color;' );
  130. }
  131. if ( this.requires.color[ 1 ] ) {
  132. this.addVaryCode( 'varying vec4 vColor2;' );
  133. this.addVertexParsCode( 'attribute vec4 color2;' );
  134. this.addVertexFinalCode( 'vColor2 = color2;' );
  135. }
  136. if ( this.requires.position ) {
  137. this.addVaryCode( 'varying vec3 vPosition;' );
  138. this.addVertexFinalCode( 'vPosition = transformed;' );
  139. }
  140. if ( this.requires.worldPosition ) {
  141. this.addVaryCode( 'varying vec3 vWPosition;' );
  142. this.addVertexFinalCode( 'vWPosition = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;' );
  143. }
  144. if ( this.requires.normal ) {
  145. this.addVaryCode( 'varying vec3 vObjectNormal;' );
  146. this.addVertexFinalCode( 'vObjectNormal = normal;' );
  147. }
  148. if ( this.requires.worldNormal ) {
  149. this.addVaryCode( 'varying vec3 vWNormal;' );
  150. this.addVertexFinalCode( 'vWNormal = ( modelMatrix * vec4( objectNormal, 0.0 ) ).xyz;' );
  151. }
  152. return this;
  153. },
  154. buildShader: function( shader, node ) {
  155. this.resultCode[shader] = node.build( this.setShader( shader ), 'v4' );
  156. },
  157. setMaterial: function( material, renderer ) {
  158. this.material = material;
  159. this.renderer = renderer;
  160. this.requires.lights = material.lights;
  161. this.requires.fog = material.fog;
  162. this.mergeDefines( material.defines );
  163. return this;
  164. },
  165. addFlow: function ( slot, cache, context ) {
  166. return this.addSlot( slot ).addCache( cache ).addContext( context );
  167. },
  168. removeFlow: function () {
  169. return this.removeSlot().removeCache().removeContext();
  170. },
  171. addCache: function ( name ) {
  172. this.cache = name || '';
  173. this.caches.push( this.cache );
  174. return this;
  175. },
  176. removeCache: function () {
  177. this.caches.pop();
  178. this.cache = this.caches[ this.caches.length - 1 ] || '';
  179. return this;
  180. },
  181. addContext: function ( context ) {
  182. this.context = Object.assign( {}, this.context || {}, context || {} );
  183. this.contexts.push( this.context );
  184. return this;
  185. },
  186. removeContext: function () {
  187. this.contexts.pop();
  188. this.context = this.contexts[ this.contexts.length - 1 ] || {};
  189. return this;
  190. },
  191. addSlot: function ( name ) {
  192. this.slot = name || '';
  193. this.slots.push( this.slot );
  194. return this;
  195. },
  196. removeSlot: function () {
  197. this.slots.pop();
  198. this.slot = this.slots[ this.slots.length - 1 ] || '';
  199. return this;
  200. },
  201. addVertexCode: function ( code ) {
  202. this.addCode( code, 'vertex' );
  203. },
  204. addFragmentCode: function ( code ) {
  205. this.addCode( code, 'fragment' );
  206. },
  207. addCode: function ( code, shader ) {
  208. this.code[shader || this.shader] += code + '\n';
  209. },
  210. addVertexNodeCode: function ( code ) {
  211. this.addNodeCode( code, 'vertex' );
  212. },
  213. addFragmentNodeCode: function ( code ) {
  214. this.addNodeCode( code, 'fragment' );
  215. },
  216. addNodeCode: function ( code, shader ) {
  217. this.nodeCode[shader || this.shader] += code + '\n';
  218. },
  219. clearNodeCode: function ( shader ) {
  220. shader = shader || this.shader;
  221. var code = this.nodeCode[shader];
  222. this.nodeCode[shader] = '';
  223. return code;
  224. },
  225. clearVertexNodeCode: function ( ) {
  226. return this.clearNodeCode( 'vertex' );
  227. },
  228. clearFragmentNodeCode: function ( ) {
  229. return this.clearNodeCode( 'fragment' );
  230. },
  231. addVertexFinalCode: function ( code ) {
  232. this.addFinalCode( code, 'vertex' );
  233. },
  234. addFragmentFinalCode: function ( code ) {
  235. this.addFinalCode( code, 'fragment' );
  236. },
  237. addFinalCode: function ( code, shader ) {
  238. this.finalCode[shader || this.shader] += code + '\n';
  239. },
  240. addVertexParsCode: function ( code ) {
  241. this.addParsCode( code, 'vertex' );
  242. },
  243. addFragmentParsCode: function ( code ) {
  244. this.addParsCode( code, 'fragment' );
  245. },
  246. addParsCode: function ( code, shader ) {
  247. this.parsCode[shader || this.shader] += code + '\n';
  248. },
  249. addVaryCode: function ( code ) {
  250. this.addVertexParsCode( code );
  251. this.addFragmentParsCode( code );
  252. },
  253. isCache: function ( name ) {
  254. return this.caches.indexOf( name ) !== -1;
  255. },
  256. isSlot: function ( name ) {
  257. return this.slots.indexOf( name ) !== -1;
  258. },
  259. define: function ( name, value ) {
  260. this.defines[ name ] = value === undefined ? 1 : value;
  261. },
  262. isDefined: function ( name ) {
  263. return this.defines[ name ] !== undefined;
  264. },
  265. getVar: function ( uuid, type, ns, shader ) {
  266. shader = shader || 'varying';
  267. var vars = this.getVars(shader),
  268. data = vars[ uuid ];
  269. if ( ! data ) {
  270. var index = vars.length,
  271. name = ns ? ns : 'nVv' + index;
  272. data = { name: name, type: type };
  273. vars.push( data );
  274. vars[ uuid ] = data;
  275. }
  276. return data;
  277. },
  278. getTempVar: function ( uuid, type, ns ) {
  279. return this.getVar( uuid, type, ns, this.shader );
  280. },
  281. getAttribute: function ( name, type ) {
  282. if ( ! this.attributes[ name ] ) {
  283. var varying = this.getVar( name, type );
  284. this.addVertexParsCode( 'attribute ' + type + ' ' + name + ';' );
  285. this.addVertexFinalCode( varying.name + ' = ' + name + ';' );
  286. this.attributes[ name ] = { varying: varying, name: name, type: type };
  287. }
  288. return this.attributes[ name ];
  289. },
  290. getCode: function( shader ) {
  291. return [
  292. this.prefixCode,
  293. this.parsCode[ shader ],
  294. this.getVarListCode( this.getVars('varying'), 'varying' ),
  295. this.getVarListCode( this.inputs.uniforms[shader], 'uniform' ),
  296. this.getIncludesCode( 'consts', shader ),
  297. this.getIncludesCode( 'structs', shader ),
  298. this.getIncludesCode( 'functions', shader ),
  299. 'void main() {',
  300. this.getVarListCode( this.getVars(shader) ),
  301. this.code[ shader ],
  302. this.resultCode[ shader ],
  303. this.finalCode[ shader ],
  304. '}'
  305. ].join( "\n" );
  306. },
  307. getVarListCode: function ( vars, prefix ) {
  308. prefix = prefix || '';
  309. var code = '';
  310. for ( var i = 0, l = vars.length; i < l; ++ i ) {
  311. var nVar = vars[i],
  312. type = nVar.type,
  313. name = nVar.name;
  314. var formatType = this.getFormatByType( type );
  315. if ( formatType === undefined ) {
  316. throw new Error( "Node pars " + formatType + " not found." );
  317. }
  318. code += prefix + ' ' + formatType + ' ' + name + ';\n';
  319. }
  320. return code;
  321. },
  322. getVars: function ( shader ) {
  323. return this.inputs.vars[ shader || this.shader ];
  324. },
  325. getNodeData: function ( node ) {
  326. var uuid = node.isNode ? node.uuid : node;
  327. return this.nodeData[ uuid ] = this.nodeData[ uuid ] || {};
  328. },
  329. createUniform: function ( shader, type, node, ns, needsUpdate ) {
  330. var uniforms = this.inputs.uniforms,
  331. index = uniforms.list.length;
  332. var uniform = new NodeUniform( {
  333. type: type,
  334. name: ns ? ns : 'nVu' + index,
  335. node: node,
  336. needsUpdate: needsUpdate
  337. } );
  338. uniforms.list.push( uniform );
  339. uniforms[shader].push( uniform );
  340. uniforms[shader][ uniform.name ] = uniform;
  341. this.uniforms[ uniform.name ] = uniform;
  342. return uniform;
  343. },
  344. createVertexUniform: function ( type, node, ns, needsUpdate ) {
  345. return this.createUniform( 'vertex', type, node, ns, needsUpdate );
  346. },
  347. createFragmentUniform: function ( type, node, ns, needsUpdate ) {
  348. return this.createUniform( 'fragment', type, node, ns, needsUpdate );
  349. },
  350. include: function ( node, parent, source ) {
  351. var includesStruct;
  352. node = typeof node === 'string' ? NodeLib.get( node ) : node;
  353. if (this.context.include === false) {
  354. return node.name;
  355. }
  356. if ( node instanceof FunctionNode ) {
  357. includesStruct = this.includes.functions;
  358. } else if ( node instanceof ConstNode ) {
  359. includesStruct = this.includes.consts;
  360. } else if ( node instanceof StructNode ) {
  361. includesStruct = this.includes.structs;
  362. }
  363. var includes = includesStruct[ this.shader ] = includesStruct[ this.shader ] || [];
  364. if (node) {
  365. var included = includes[ node.name ];
  366. if ( ! included ) {
  367. included = includes[ node.name ] = {
  368. node: node,
  369. deps: []
  370. };
  371. includes.push( included );
  372. included.src = node.build( this, 'source' );
  373. }
  374. if ( node instanceof FunctionNode && parent && includes[ parent.name ] && includes[ parent.name ].deps.indexOf( node ) == - 1 ) {
  375. includes[ parent.name ].deps.push( node );
  376. if ( node.includes && node.includes.length ) {
  377. var i = 0;
  378. do {
  379. this.include( node.includes[ i ++ ], parent );
  380. } while ( i < node.includes.length );
  381. }
  382. }
  383. if ( source ) {
  384. included.src = source;
  385. }
  386. return node.name;
  387. } else {
  388. throw new Error("Include not found.");
  389. }
  390. },
  391. colorToVectorProperties: function ( color ) {
  392. return color.replace( 'r', 'x' ).replace( 'g', 'y' ).replace( 'b', 'z' ).replace( 'a', 'w' );
  393. },
  394. colorToVector: function ( color ) {
  395. return color.replace( /c/g, 'v3' );
  396. },
  397. getIncludes: function ( type, shader ) {
  398. return this.includes[type][shader || this.shader];
  399. },
  400. getIncludesCode: function () {
  401. function sortByPosition( a, b ) {
  402. return a.deps.length - b.deps.length;
  403. }
  404. return function getIncludesCode( type, shader ) {
  405. var includes = this.getIncludes( type, shader );
  406. if ( ! includes ) return '';
  407. var code = '',
  408. includes = includes.sort( sortByPosition );
  409. for ( var i = 0; i < includes.length; i ++ ) {
  410. if ( includes[ i ].src ) code += includes[ i ].src + '\n';
  411. }
  412. return code;
  413. };
  414. }(),
  415. getConstructorFromLength: function ( len ) {
  416. return constructors[ len - 1 ];
  417. },
  418. isTypeMatrix: function ( format ) {
  419. return /^m/.test( format );
  420. },
  421. getTypeLength: function ( type ) {
  422. if ( type === 'f' ) return 1;
  423. return parseInt( this.colorToVector( type ).substr( 1 ) );
  424. },
  425. getTypeFromLength: function ( len ) {
  426. if ( len === 1 ) return 'f';
  427. return 'v' + len;
  428. },
  429. findNode: function() {
  430. for(var i = 0; i < arguments.length; i++) {
  431. var nodeCandidate = arguments[i];
  432. if (nodeCandidate !== undefined && nodeCandidate.isNode) {
  433. return nodeCandidate;
  434. }
  435. }
  436. },
  437. resolve: function() {
  438. for(var i = 0; i < arguments.length; i++) {
  439. var nodeCandidate = arguments[i];
  440. if (nodeCandidate !== undefined) {
  441. if (nodeCandidate.isNode) {
  442. return nodeCandidate;
  443. } else if (nodeCandidate.isTexture) {
  444. switch( nodeCandidate.mapping ) {
  445. case THREE.CubeReflectionMapping:
  446. case THREE.CubeRefractionMapping:
  447. return new CubeTextureNode( nodeCandidate );
  448. break;
  449. case THREE.CubeUVReflectionMapping:
  450. case THREE.CubeUVRefractionMapping:
  451. return new TextureCubeNode( new TextureNode( nodeCandidate ) );
  452. break;
  453. default:
  454. return new TextureNode( nodeCandidate );
  455. }
  456. } else if (nodeCandidate.isVector2) {
  457. return new Vector2Node( nodeCandidate );
  458. } else if (nodeCandidate.isVector3) {
  459. return new Vector3Node( nodeCandidate );
  460. } else if (nodeCandidate.isVector4) {
  461. return new Vector4Node( nodeCandidate );
  462. }
  463. }
  464. }
  465. },
  466. format: function ( code, from, to ) {
  467. var typeToType = this.colorToVector( to + ' <- ' + from );
  468. switch ( typeToType ) {
  469. case 'f <- v2': return code + '.x';
  470. case 'f <- v3': return code + '.x';
  471. case 'f <- v4': return code + '.x';
  472. case 'f <- i': return 'float( ' + code + ' )';
  473. case 'v2 <- f': return 'vec2( ' + code + ' )';
  474. case 'v2 <- v3': return code + '.xy';
  475. case 'v2 <- v4': return code + '.xy';
  476. case 'v2 <- i': return 'vec2( float( ' + code + ' ) )';
  477. case 'v3 <- f': return 'vec3( ' + code + ' )';
  478. case 'v3 <- v2': return 'vec3( ' + code + ', 0.0 )';
  479. case 'v3 <- v4': return code + '.xyz';
  480. case 'v3 <- i': return 'vec2( float( ' + code + ' ) )';
  481. case 'v4 <- f': return 'vec4( ' + code + ' )';
  482. case 'v4 <- v2': return 'vec4( ' + code + ', 0.0, 1.0 )';
  483. case 'v4 <- v3': return 'vec4( ' + code + ', 1.0 )';
  484. case 'v4 <- i': return 'vec4( float( ' + code + ' ) )';
  485. case 'i <- f': return 'int( ' + code + ' )';
  486. case 'i <- v2': return 'int( ' + code + '.x )';
  487. case 'i <- v3': return 'int( ' + code + '.x )';
  488. case 'i <- v4': return 'int( ' + code + '.x )';
  489. }
  490. return code;
  491. },
  492. getTypeByFormat: function ( format ) {
  493. return convertFormatToType[ format ] || format;
  494. },
  495. getFormatByType: function ( type ) {
  496. return convertTypeToFormat[ type ] || type;
  497. },
  498. getUuid: function ( uuid, useCache ) {
  499. useCache = useCache !== undefined ? useCache : true;
  500. if ( useCache && this.cache ) uuid = this.cache + '-' + uuid;
  501. return uuid;
  502. },
  503. getElementByIndex: function ( index ) {
  504. return elements[ index ];
  505. },
  506. getIndexByElement: function ( elm ) {
  507. return elements.indexOf( elm );
  508. },
  509. isShader: function ( shader ) {
  510. return this.shader === shader;
  511. },
  512. setShader: function ( shader ) {
  513. this.shader = shader;
  514. return this;
  515. },
  516. mergeDefines: function ( defines ) {
  517. for ( var name in defines ) {
  518. this.defines[ name ] = defines[ name ];
  519. }
  520. return this.defines;
  521. },
  522. mergeUniform: function ( uniforms ) {
  523. for ( var name in uniforms ) {
  524. this.uniforms[ name ] = uniforms[ name ];
  525. }
  526. return this.uniforms;
  527. },
  528. getTextureEncodingFromMap: function ( map, gammaOverrideLinear ) {
  529. gammaOverrideLinear = gammaOverrideLinear !== undefined ? gammaOverrideLinear : this.context.gamma && ( this.renderer ? this.renderer.gammaInput : false );
  530. var encoding;
  531. if ( ! map ) {
  532. encoding = THREE.LinearEncoding;
  533. } else if ( map.isTexture ) {
  534. encoding = map.encoding;
  535. } else if ( map.isWebGLRenderTarget ) {
  536. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  537. encoding = map.texture.encoding;
  538. }
  539. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  540. if ( encoding === THREE.LinearEncoding && gammaOverrideLinear ) {
  541. encoding = THREE.GammaEncoding;
  542. }
  543. return encoding;
  544. }
  545. };
  546. export { NodeBuilder };