NodeBuilder.js 16 KB

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