NodeBuilder.js 17 KB

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