NodeBuilder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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 TEXTURE_LOD_EXT",
  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. "#include <common>"
  70. ].join( "\n" );
  71. this.parsCode = {
  72. vertex: '',
  73. fragment: ''
  74. };
  75. this.code = {
  76. vertex: '',
  77. fragment: ''
  78. };
  79. this.nodeCode = {
  80. vertex: '',
  81. fragment: ''
  82. };
  83. this.resultCode = {
  84. vertex: '',
  85. fragment: ''
  86. };
  87. this.finalCode = {
  88. vertex: '',
  89. fragment: ''
  90. };
  91. this.inputs = {
  92. uniforms: {
  93. list: [],
  94. vertex: [],
  95. fragment: []
  96. },
  97. vars: {
  98. varying: [],
  99. vertex: [],
  100. fragment: []
  101. }
  102. };
  103. // send to material
  104. this.defines = {};
  105. this.uniforms = {};
  106. this.extensions = {};
  107. this.updaters = [];
  108. this.nodes = [];
  109. // --
  110. this.parsing = false;
  111. this.optimize = true;
  112. }
  113. NodeBuilder.prototype = {
  114. constructor: NodeBuilder,
  115. build: function ( vertex, fragment ) {
  116. this.buildShader( 'vertex', vertex );
  117. this.buildShader( 'fragment', fragment );
  118. if ( this.requires.uv[ 0 ] ) {
  119. this.addVaryCode( 'varying vec2 vUv;' );
  120. this.addVertexFinalCode( 'vUv = uv;' );
  121. }
  122. if ( this.requires.uv[ 1 ] ) {
  123. this.addVaryCode( 'varying vec2 vUv2;' );
  124. this.addVertexParsCode( 'attribute vec2 uv2;' );
  125. this.addVertexFinalCode( 'vUv2 = uv2;' );
  126. }
  127. if ( this.requires.color[ 0 ] ) {
  128. this.addVaryCode( 'varying vec4 vColor;' );
  129. this.addVertexParsCode( 'attribute vec4 color;' );
  130. this.addVertexFinalCode( 'vColor = color;' );
  131. }
  132. if ( this.requires.color[ 1 ] ) {
  133. this.addVaryCode( 'varying vec4 vColor2;' );
  134. this.addVertexParsCode( 'attribute vec4 color2;' );
  135. this.addVertexFinalCode( 'vColor2 = color2;' );
  136. }
  137. if ( this.requires.position ) {
  138. this.addVaryCode( 'varying vec3 vPosition;' );
  139. this.addVertexFinalCode( 'vPosition = transformed;' );
  140. }
  141. if ( this.requires.worldPosition ) {
  142. this.addVaryCode( 'varying vec3 vWPosition;' );
  143. this.addVertexFinalCode( 'vWPosition = ( modelMatrix * vec4( transformed, 1.0 ) ).xyz;' );
  144. }
  145. if ( this.requires.normal ) {
  146. this.addVaryCode( 'varying vec3 vObjectNormal;' );
  147. this.addVertexFinalCode( 'vObjectNormal = normal;' );
  148. }
  149. if ( this.requires.worldNormal ) {
  150. this.addVaryCode( 'varying vec3 vWNormal;' );
  151. this.addVertexFinalCode( 'vWNormal = ( modelMatrix * vec4( objectNormal, 0.0 ) ).xyz;' );
  152. }
  153. return this;
  154. },
  155. buildShader: function ( shader, node ) {
  156. this.resultCode[ shader ] = node.build( this.setShader( shader ), 'v4' );
  157. },
  158. setMaterial: function ( material, renderer ) {
  159. this.material = material;
  160. this.renderer = renderer;
  161. this.requires.lights = material.lights;
  162. this.requires.fog = material.fog;
  163. this.mergeDefines( material.defines );
  164. return this;
  165. },
  166. addFlow: function ( slot, cache, context ) {
  167. return this.addSlot( slot ).addCache( cache ).addContext( context );
  168. },
  169. removeFlow: function () {
  170. return this.removeSlot().removeCache().removeContext();
  171. },
  172. addCache: function ( name ) {
  173. this.cache = name || '';
  174. this.caches.push( this.cache );
  175. return this;
  176. },
  177. removeCache: function () {
  178. this.caches.pop();
  179. this.cache = this.caches[ this.caches.length - 1 ] || '';
  180. return this;
  181. },
  182. addContext: function ( context ) {
  183. this.context = Object.assign( {}, this.context, context );
  184. this.contexts.push( this.context );
  185. return this;
  186. },
  187. removeContext: function () {
  188. this.contexts.pop();
  189. this.context = this.contexts[ this.contexts.length - 1 ] || {};
  190. return this;
  191. },
  192. addSlot: function ( name ) {
  193. this.slot = name || '';
  194. this.slots.push( this.slot );
  195. return this;
  196. },
  197. removeSlot: function () {
  198. this.slots.pop();
  199. this.slot = this.slots[ this.slots.length - 1 ] || '';
  200. return this;
  201. },
  202. addVertexCode: function ( code ) {
  203. this.addCode( code, 'vertex' );
  204. },
  205. addFragmentCode: function ( code ) {
  206. this.addCode( code, 'fragment' );
  207. },
  208. addCode: function ( code, shader ) {
  209. this.code[ shader || this.shader ] += code + '\n';
  210. },
  211. addVertexNodeCode: function ( code ) {
  212. this.addNodeCode( code, 'vertex' );
  213. },
  214. addFragmentNodeCode: function ( code ) {
  215. this.addNodeCode( code, 'fragment' );
  216. },
  217. addNodeCode: function ( code, shader ) {
  218. this.nodeCode[ shader || this.shader ] += code + '\n';
  219. },
  220. clearNodeCode: function ( shader ) {
  221. shader = shader || this.shader;
  222. var code = this.nodeCode[ shader ];
  223. this.nodeCode[ shader ] = '';
  224. return code;
  225. },
  226. clearVertexNodeCode: function ( ) {
  227. return this.clearNodeCode( 'vertex' );
  228. },
  229. clearFragmentNodeCode: function ( ) {
  230. return this.clearNodeCode( 'fragment' );
  231. },
  232. addVertexFinalCode: function ( code ) {
  233. this.addFinalCode( code, 'vertex' );
  234. },
  235. addFragmentFinalCode: function ( code ) {
  236. this.addFinalCode( code, 'fragment' );
  237. },
  238. addFinalCode: function ( code, shader ) {
  239. this.finalCode[ shader || this.shader ] += code + '\n';
  240. },
  241. addVertexParsCode: function ( code ) {
  242. this.addParsCode( code, 'vertex' );
  243. },
  244. addFragmentParsCode: function ( code ) {
  245. this.addParsCode( code, 'fragment' );
  246. },
  247. addParsCode: function ( code, shader ) {
  248. this.parsCode[ shader || this.shader ] += code + '\n';
  249. },
  250. addVaryCode: function ( code ) {
  251. this.addVertexParsCode( code );
  252. this.addFragmentParsCode( code );
  253. },
  254. isCache: function ( name ) {
  255. return this.caches.indexOf( name ) !== - 1;
  256. },
  257. isSlot: function ( name ) {
  258. return this.slots.indexOf( name ) !== - 1;
  259. },
  260. define: function ( name, value ) {
  261. this.defines[ name ] = value === undefined ? 1 : value;
  262. },
  263. isDefined: function ( name ) {
  264. return this.defines[ name ] !== undefined;
  265. },
  266. getVar: function ( uuid, type, ns, shader ) {
  267. shader = shader || 'varying';
  268. var vars = this.getVars( shader ),
  269. data = vars[ uuid ];
  270. if ( ! data ) {
  271. var index = vars.length,
  272. name = ns ? ns : 'nVv' + index;
  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 ) {
  280. return this.getVar( uuid, type, ns, this.shader );
  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 ) {
  331. var uniforms = this.inputs.uniforms,
  332. index = uniforms.list.length;
  333. var uniform = new NodeUniform( {
  334. type: type,
  335. name: ns ? ns : 'nVu' + index,
  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 ) {
  346. return this.createUniform( 'vertex', type, node, ns, needsUpdate );
  347. },
  348. createFragmentUniform: function ( type, node, ns, needsUpdate ) {
  349. return this.createUniform( 'fragment', type, node, ns, needsUpdate );
  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' : return 'float( ' + code + ' )';
  474. case 'v2 <- f' : return 'vec2( ' + code + ' )';
  475. case 'v2 <- v3': return code + '.xy';
  476. case 'v2 <- v4': return code + '.xy';
  477. case 'v2 <- i' : return 'vec2( float( ' + code + ' ) )';
  478. case 'v3 <- f' : return 'vec3( ' + code + ' )';
  479. case 'v3 <- v2': return 'vec3( ' + code + ', 0.0 )';
  480. case 'v3 <- v4': return code + '.xyz';
  481. case 'v3 <- i' : return 'vec2( float( ' + code + ' ) )';
  482. case 'v4 <- f' : return 'vec4( ' + code + ' )';
  483. case 'v4 <- v2': return 'vec4( ' + code + ', 0.0, 1.0 )';
  484. case 'v4 <- v3': return 'vec4( ' + code + ', 1.0 )';
  485. case 'v4 <- i' : return 'vec4( float( ' + code + ' ) )';
  486. case 'i <- f' : return 'int( ' + code + ' )';
  487. case 'i <- v2' : return 'int( ' + code + '.x )';
  488. case 'i <- v3' : return 'int( ' + code + '.x )';
  489. case 'i <- v4' : return 'int( ' + code + '.x )';
  490. }
  491. return code;
  492. },
  493. getTypeByFormat: function ( format ) {
  494. return convertFormatToType[ format ] || format;
  495. },
  496. getFormatByType: function ( type ) {
  497. return convertTypeToFormat[ type ] || type;
  498. },
  499. getUuid: function ( uuid, useCache ) {
  500. useCache = useCache !== undefined ? useCache : true;
  501. if ( useCache && this.cache ) uuid = this.cache + '-' + uuid;
  502. return uuid;
  503. },
  504. getElementByIndex: function ( index ) {
  505. return elements[ index ];
  506. },
  507. getIndexByElement: function ( elm ) {
  508. return elements.indexOf( elm );
  509. },
  510. isShader: function ( shader ) {
  511. return this.shader === shader;
  512. },
  513. setShader: function ( shader ) {
  514. this.shader = shader;
  515. return this;
  516. },
  517. mergeDefines: function ( defines ) {
  518. for ( var name in defines ) {
  519. this.defines[ name ] = defines[ name ];
  520. }
  521. return this.defines;
  522. },
  523. mergeUniform: function ( uniforms ) {
  524. for ( var name in uniforms ) {
  525. this.uniforms[ name ] = uniforms[ name ];
  526. }
  527. return this.uniforms;
  528. },
  529. getTextureEncodingFromMap: function ( map, gammaOverrideLinear ) {
  530. gammaOverrideLinear = gammaOverrideLinear !== undefined ? gammaOverrideLinear : this.context.gamma && ( this.renderer ? this.renderer.gammaInput : false );
  531. var encoding;
  532. if ( ! map ) {
  533. encoding = THREE.LinearEncoding;
  534. } else if ( map.isTexture ) {
  535. encoding = map.encoding;
  536. } else if ( map.isWebGLRenderTarget ) {
  537. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  538. encoding = map.texture.encoding;
  539. }
  540. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  541. if ( encoding === THREE.LinearEncoding && gammaOverrideLinear ) {
  542. encoding = THREE.GammaEncoding;
  543. }
  544. return encoding;
  545. }
  546. };
  547. export { NodeBuilder };