NodeMaterial.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. import { Material } from '../Material.js';
  2. import { NormalBlending } from '../../constants.js';
  3. import { getNodeChildren, getCacheKey } from '../../nodes/core/NodeUtils.js';
  4. import { output, diffuseColor, emissive, varyingProperty } from '../../nodes/core/PropertyNode.js';
  5. import { materialAlphaTest, materialColor, materialOpacity, materialEmissive, materialNormal, materialLightMap, materialAO } from '../../nodes/accessors/MaterialNode.js';
  6. import { modelViewProjection } from '../../nodes/accessors/ModelViewProjectionNode.js';
  7. import { normalLocal } from '../../nodes/accessors/Normal.js';
  8. import { instancedMesh } from '../../nodes/accessors/InstancedMeshNode.js';
  9. import { batch } from '../../nodes/accessors/BatchNode.js';
  10. import { materialReference } from '../../nodes/accessors/MaterialReferenceNode.js';
  11. import { positionLocal, positionView } from '../../nodes/accessors/Position.js';
  12. import { skinning } from '../../nodes/accessors/SkinningNode.js';
  13. import { morphReference } from '../../nodes/accessors/MorphNode.js';
  14. import { mix } from '../../nodes/math/MathNode.js';
  15. import { namespace, float, vec3, vec4, bool } from '../../nodes/tsl/TSLBase.js';
  16. import AONode from '../../nodes/lighting/AONode.js';
  17. import { lightingContext } from '../../nodes/lighting/LightingContextNode.js';
  18. import IrradianceNode from '../../nodes/lighting/IrradianceNode.js';
  19. import { depth, viewZToLogarithmicDepth, viewZToOrthographicDepth } from '../../nodes/display/ViewportDepthNode.js';
  20. import { cameraFar, cameraNear, cameraProjectionMatrix } from '../../nodes/accessors/Camera.js';
  21. import { clipping, clippingAlpha, hardwareClipping } from '../../nodes/accessors/ClippingNode.js';
  22. import NodeMaterialObserver from './manager/NodeMaterialObserver.js';
  23. import getAlphaHashThreshold from '../../nodes/functions/material/getAlphaHashThreshold.js';
  24. import { modelViewMatrix } from '../../nodes/accessors/ModelNode.js';
  25. import { vertexColor } from '../../nodes/accessors/VertexColorNode.js';
  26. /**
  27. * Base class for all node materials.
  28. *
  29. * @augments Material
  30. */
  31. class NodeMaterial extends Material {
  32. static get type() {
  33. return 'NodeMaterial';
  34. }
  35. /**
  36. * Represents the type of the node material.
  37. *
  38. * @type {string}
  39. */
  40. get type() {
  41. return this.constructor.type;
  42. }
  43. set type( _value ) { /* */ }
  44. /**
  45. * Constructs a new node material.
  46. */
  47. constructor() {
  48. super();
  49. /**
  50. * This flag can be used for type testing.
  51. *
  52. * @type {boolean}
  53. * @readonly
  54. * @default true
  55. */
  56. this.isNodeMaterial = true;
  57. /**
  58. * Whether this material is affected by fog or not.
  59. *
  60. * @type {boolean}
  61. * @default true
  62. */
  63. this.fog = true;
  64. /**
  65. * Whether this material is affected by lights or not.
  66. *
  67. * @type {boolean}
  68. * @default false
  69. */
  70. this.lights = false;
  71. /**
  72. * Whether this material uses hardware clipping or not.
  73. * This property is managed by the engine and should not be
  74. * modified by apps.
  75. *
  76. * @type {boolean}
  77. * @default false
  78. */
  79. this.hardwareClipping = false;
  80. /**
  81. * Node materials which set their `lights` property to `true`
  82. * are affected by all lights of the scene. Sometimes selective
  83. * lighting is wanted which means only _some_ lights in the scene
  84. * affect a material. This can be achieved by creating an instance
  85. * of {@link LightsNode} with a list of selective
  86. * lights and assign the node to this property.
  87. *
  88. * ```js
  89. * const customLightsNode = lights( [ light1, light2 ] );
  90. * material.lightsNode = customLightsNode;
  91. * ```
  92. *
  93. * @type {?LightsNode}
  94. * @default null
  95. */
  96. this.lightsNode = null;
  97. /**
  98. * The environment of node materials can be defined by an environment
  99. * map assigned to the `envMap` property or by `Scene.environment`
  100. * if the node material is a PBR material. This node property allows to overwrite
  101. * the default behavior and define the environment with a custom node.
  102. *
  103. * ```js
  104. * material.envNode = pmremTexture( renderTarget.texture );
  105. * ```
  106. *
  107. * @type {?Node<vec3>}
  108. * @default null
  109. */
  110. this.envNode = null;
  111. /**
  112. * The lighting of node materials might be influenced by ambient occlusion.
  113. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  114. * and the respective `aoMapIntensity`. This node property allows to overwrite
  115. * the default and define the ambient occlusion with a custom node instead.
  116. *
  117. * If you don't want to overwrite the diffuse color but modify the existing
  118. * values instead, use {@link materialAO}.
  119. *
  120. * @type {?Node<float>}
  121. * @default null
  122. */
  123. this.aoNode = null;
  124. /**
  125. * The diffuse color of node materials is by default inferred from the
  126. * `color` and `map` properties. This node property allows to overwrite the default
  127. * and define the diffuse color with a node instead.
  128. *
  129. * ```js
  130. * material.colorNode = color( 0xff0000 ); // define red color
  131. * ```
  132. *
  133. * If you don't want to overwrite the diffuse color but modify the existing
  134. * values instead, use {@link materialColor}.
  135. *
  136. * ```js
  137. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  138. * ```
  139. *
  140. * @type {?Node<vec3>}
  141. * @default null
  142. */
  143. this.colorNode = null;
  144. /**
  145. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  146. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  147. * and define the normals with a node instead.
  148. *
  149. * If you don't want to overwrite the normals but modify the existing values instead,
  150. * use {@link materialNormal}.
  151. *
  152. * @type {?Node<vec3>}
  153. * @default null
  154. */
  155. this.normalNode = null;
  156. /**
  157. * The opacity of node materials is by default inferred from the `opacity`
  158. * and `alphaMap` properties. This node property allows to overwrite the default
  159. * and define the opacity with a node instead.
  160. *
  161. * If you don't want to overwrite the normals but modify the existing
  162. * value instead, use {@link materialOpacity}.
  163. *
  164. * @type {?Node<float>}
  165. * @default null
  166. */
  167. this.opacityNode = null;
  168. /**
  169. * This node can be used to implement a variety of filter-like effects. The idea is
  170. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  171. * to create an arbitrary effect and then assign the node composition to this property.
  172. * Everything behind the object using this material will now be affected by a filter.
  173. *
  174. * ```js
  175. * const material = new NodeMaterial()
  176. * material.transparent = true;
  177. *
  178. * // everything behind the object will be monochromatic
  179. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  180. * ```
  181. *
  182. * Backdrop computations are part of the lighting so only lit materials can use this property.
  183. *
  184. * @type {?Node<vec3>}
  185. * @default null
  186. */
  187. this.backdropNode = null;
  188. /**
  189. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  190. *
  191. * @type {?Node<float>}
  192. * @default null
  193. */
  194. this.backdropAlphaNode = null;
  195. /**
  196. * The alpha test of node materials is by default inferred from the `alphaTest`
  197. * property. This node property allows to overwrite the default and define the
  198. * alpha test with a node instead.
  199. *
  200. * If you don't want to overwrite the alpha test but modify the existing
  201. * value instead, use {@link materialAlphaTest}.
  202. *
  203. * @type {?Node<float>}
  204. * @default null
  205. */
  206. this.alphaTestNode = null;
  207. /**
  208. * Discards the fragment if the mask value is `false`.
  209. *
  210. * @type {?Node<bool>}
  211. * @default null
  212. */
  213. this.maskNode = null;
  214. /**
  215. * The local vertex positions are computed based on multiple factors like the
  216. * attribute data, morphing or skinning. This node property allows to overwrite
  217. * the default and define local vertex positions with nodes instead.
  218. *
  219. * If you don't want to overwrite the vertex positions but modify the existing
  220. * values instead, use {@link positionLocal}.
  221. *
  222. *```js
  223. * material.positionNode = positionLocal.add( displace );
  224. * ```
  225. *
  226. * @type {?Node<vec3>}
  227. * @default null
  228. */
  229. this.positionNode = null;
  230. /**
  231. * This node property is intended for logic which modifies geometry data once or per animation step.
  232. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  233. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  234. * can be implemented.
  235. *
  236. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  237. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  238. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  239. * eventually assigned to `geometryNode`.
  240. *
  241. * @type {?Function}
  242. * @default null
  243. */
  244. this.geometryNode = null;
  245. /**
  246. * Allows to overwrite depth values in the fragment shader.
  247. *
  248. * @type {?Node<float>}
  249. * @default null
  250. */
  251. this.depthNode = null;
  252. /**
  253. * Allows to overwrite the position used for shadow map rendering which
  254. * is by default {@link positionWorld}, the vertex position
  255. * in world space.
  256. *
  257. * @type {?Node<float>}
  258. * @default null
  259. */
  260. this.receivedShadowPositionNode = null;
  261. /**
  262. * Allows to overwrite the geometry position used for shadow map projection which
  263. * is by default {@link positionLocal}, the vertex position in local space.
  264. *
  265. * @type {?Node<float>}
  266. * @default null
  267. */
  268. this.castShadowPositionNode = null;
  269. /**
  270. * This node can be used to influence how an object using this node material
  271. * receive shadows.
  272. *
  273. * ```js
  274. * const totalShadows = float( 1 ).toVar();
  275. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  276. * totalShadows.mulAssign( shadow );
  277. * //return float( 1 ); // bypass received shadows
  278. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  279. * } );
  280. *
  281. * @type {?(Function|FunctionNode<vec4>)}
  282. * @default null
  283. */
  284. this.receivedShadowNode = null;
  285. /**
  286. * This node can be used to influence how an object using this node material
  287. * casts shadows. To apply a color to shadows, you can simply do:
  288. *
  289. * ```js
  290. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  291. * ```
  292. *
  293. * Which can be nice to fake colored shadows of semi-transparent objects. It
  294. * is also common to use the property with `Fn` function so checks are performed
  295. * per fragment.
  296. *
  297. * ```js
  298. * materialCustomShadow.castShadowNode = Fn( () => {
  299. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  300. * return materialColor;
  301. * } )();
  302. * ```
  303. *
  304. * @type {?Node<vec4>}
  305. * @default null
  306. */
  307. this.castShadowNode = null;
  308. /**
  309. * This node can be used to define the final output of the material.
  310. *
  311. * TODO: Explain the differences to `fragmentNode`.
  312. *
  313. * @type {?Node<vec4>}
  314. * @default null
  315. */
  316. this.outputNode = null;
  317. /**
  318. * MRT configuration is done on renderer or pass level. This node allows to
  319. * overwrite what values are written into MRT targets on material level. This
  320. * can be useful for implementing selective FX features that should only affect
  321. * specific objects.
  322. *
  323. * @type {?MRTNode}
  324. * @default null
  325. */
  326. this.mrtNode = null;
  327. /**
  328. * This node property can be used if you need complete freedom in implementing
  329. * the fragment shader. Assigning a node will replace the built-in material
  330. * logic used in the fragment stage.
  331. *
  332. * @type {?Node<vec4>}
  333. * @default null
  334. */
  335. this.fragmentNode = null;
  336. /**
  337. * This node property can be used if you need complete freedom in implementing
  338. * the vertex shader. Assigning a node will replace the built-in material logic
  339. * used in the vertex stage.
  340. *
  341. * @type {?Node<vec4>}
  342. * @default null
  343. */
  344. this.vertexNode = null;
  345. // Deprecated properties
  346. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  347. get: () => {
  348. return this.receivedShadowPositionNode;
  349. },
  350. set: ( value ) => {
  351. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  352. this.receivedShadowPositionNode = value;
  353. }
  354. } );
  355. }
  356. /**
  357. * Allows to define a custom cache key that influence the material key computation
  358. * for render objects.
  359. *
  360. * @return {string} The custom cache key.
  361. */
  362. customProgramCacheKey() {
  363. return this.type + getCacheKey( this );
  364. }
  365. /**
  366. * Builds this material with the given node builder.
  367. *
  368. * @param {NodeBuilder} builder - The current node builder.
  369. */
  370. build( builder ) {
  371. this.setup( builder );
  372. }
  373. /**
  374. * Setups a node material observer with the given builder.
  375. *
  376. * @param {NodeBuilder} builder - The current node builder.
  377. * @return {NodeMaterialObserver} The node material observer.
  378. */
  379. setupObserver( builder ) {
  380. return new NodeMaterialObserver( builder );
  381. }
  382. /**
  383. * Setups the vertex and fragment stage of this node material.
  384. *
  385. * @param {NodeBuilder} builder - The current node builder.
  386. */
  387. setup( builder ) {
  388. builder.context.setupNormal = () => this.setupNormal( builder );
  389. builder.context.setupPositionView = () => this.setupPositionView( builder );
  390. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  391. const renderer = builder.renderer;
  392. const renderTarget = renderer.getRenderTarget();
  393. // < VERTEX STAGE >
  394. builder.addStack();
  395. const mvp = this.setupVertex( builder );
  396. const vertexNode = this.vertexNode || mvp;
  397. builder.stack.outputNode = vertexNode;
  398. this.setupHardwareClipping( builder );
  399. if ( this.geometryNode !== null ) {
  400. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  401. }
  402. builder.addFlow( 'vertex', builder.removeStack() );
  403. // < FRAGMENT STAGE >
  404. builder.addStack();
  405. let resultNode;
  406. const clippingNode = this.setupClipping( builder );
  407. if ( this.depthWrite === true || this.depthTest === true ) {
  408. // only write depth if depth buffer is configured
  409. if ( renderTarget !== null ) {
  410. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  411. } else {
  412. if ( renderer.depth === true ) this.setupDepth( builder );
  413. }
  414. }
  415. if ( this.fragmentNode === null ) {
  416. this.setupDiffuseColor( builder );
  417. this.setupVariants( builder );
  418. const outgoingLightNode = this.setupLighting( builder );
  419. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  420. // force unsigned floats - useful for RenderTargets
  421. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  422. resultNode = this.setupOutput( builder, basicOutput );
  423. // OUTPUT NODE
  424. output.assign( resultNode );
  425. //
  426. const isCustomOutput = this.outputNode !== null;
  427. if ( isCustomOutput ) resultNode = this.outputNode;
  428. // MRT
  429. if ( renderTarget !== null ) {
  430. const mrt = renderer.getMRT();
  431. const materialMRT = this.mrtNode;
  432. if ( mrt !== null ) {
  433. if ( isCustomOutput ) output.assign( resultNode );
  434. resultNode = mrt;
  435. if ( materialMRT !== null ) {
  436. resultNode = mrt.merge( materialMRT );
  437. }
  438. } else if ( materialMRT !== null ) {
  439. resultNode = materialMRT;
  440. }
  441. }
  442. } else {
  443. let fragmentNode = this.fragmentNode;
  444. if ( fragmentNode.isOutputStructNode !== true ) {
  445. fragmentNode = vec4( fragmentNode );
  446. }
  447. resultNode = this.setupOutput( builder, fragmentNode );
  448. }
  449. builder.stack.outputNode = resultNode;
  450. builder.addFlow( 'fragment', builder.removeStack() );
  451. // < OBSERVER >
  452. builder.observer = this.setupObserver( builder );
  453. }
  454. /**
  455. * Setups the clipping node.
  456. *
  457. * @param {NodeBuilder} builder - The current node builder.
  458. * @return {ClippingNode} The clipping node.
  459. */
  460. setupClipping( builder ) {
  461. if ( builder.clippingContext === null ) return null;
  462. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  463. let result = null;
  464. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  465. const samples = builder.renderer.samples;
  466. if ( this.alphaToCoverage && samples > 1 ) {
  467. // to be added to flow when the color/alpha value has been determined
  468. result = clippingAlpha();
  469. } else {
  470. builder.stack.add( clipping() );
  471. }
  472. }
  473. return result;
  474. }
  475. /**
  476. * Setups the hardware clipping if available on the current device.
  477. *
  478. * @param {NodeBuilder} builder - The current node builder.
  479. */
  480. setupHardwareClipping( builder ) {
  481. this.hardwareClipping = false;
  482. if ( builder.clippingContext === null ) return;
  483. const candidateCount = builder.clippingContext.unionPlanes.length;
  484. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  485. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  486. builder.stack.add( hardwareClipping() );
  487. this.hardwareClipping = true;
  488. }
  489. return;
  490. }
  491. /**
  492. * Setups the depth of this material.
  493. *
  494. * @param {NodeBuilder} builder - The current node builder.
  495. */
  496. setupDepth( builder ) {
  497. const { renderer, camera } = builder;
  498. // Depth
  499. let depthNode = this.depthNode;
  500. if ( depthNode === null ) {
  501. const mrt = renderer.getMRT();
  502. if ( mrt && mrt.has( 'depth' ) ) {
  503. depthNode = mrt.get( 'depth' );
  504. } else if ( renderer.logarithmicDepthBuffer === true ) {
  505. if ( camera.isPerspectiveCamera ) {
  506. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  507. } else {
  508. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  509. }
  510. }
  511. }
  512. if ( depthNode !== null ) {
  513. depth.assign( depthNode ).toStack();
  514. }
  515. }
  516. /**
  517. * Setups the position node in view space. This method exists
  518. * so derived node materials can modify the implementation e.g. sprite materials.
  519. *
  520. * @param {NodeBuilder} builder - The current node builder.
  521. * @return {Node<vec3>} The position in view space.
  522. */
  523. setupPositionView( /*builder*/ ) {
  524. return modelViewMatrix.mul( positionLocal ).xyz;
  525. }
  526. /**
  527. * Setups the position in clip space.
  528. *
  529. * @param {NodeBuilder} builder - The current node builder.
  530. * @return {Node<vec4>} The position in view space.
  531. */
  532. setupModelViewProjection( /*builder*/ ) {
  533. return cameraProjectionMatrix.mul( positionView );
  534. }
  535. /**
  536. * Setups the logic for the vertex stage.
  537. *
  538. * @param {NodeBuilder} builder - The current node builder.
  539. * @return {Node<vec4>} The position in clip space.
  540. */
  541. setupVertex( builder ) {
  542. builder.addStack();
  543. this.setupPosition( builder );
  544. builder.context.vertex = builder.removeStack();
  545. return modelViewProjection;
  546. }
  547. /**
  548. * Setups the computation of the position in local space.
  549. *
  550. * @param {NodeBuilder} builder - The current node builder.
  551. * @return {Node<vec3>} The position in local space.
  552. */
  553. setupPosition( builder ) {
  554. const { object, geometry } = builder;
  555. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  556. morphReference( object ).toStack();
  557. }
  558. if ( object.isSkinnedMesh === true ) {
  559. skinning( object ).toStack();
  560. }
  561. if ( this.displacementMap ) {
  562. const displacementMap = materialReference( 'displacementMap', 'texture' );
  563. const displacementScale = materialReference( 'displacementScale', 'float' );
  564. const displacementBias = materialReference( 'displacementBias', 'float' );
  565. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  566. }
  567. if ( object.isBatchedMesh ) {
  568. batch( object ).toStack();
  569. }
  570. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  571. instancedMesh( object ).toStack();
  572. }
  573. if ( this.positionNode !== null ) {
  574. positionLocal.assign( namespace( this.positionNode, 'POSITION' ) );
  575. }
  576. return positionLocal;
  577. }
  578. /**
  579. * Setups the computation of the material's diffuse color.
  580. *
  581. * @param {NodeBuilder} builder - The current node builder.
  582. * @param {BufferGeometry} geometry - The geometry.
  583. */
  584. setupDiffuseColor( { object, geometry } ) {
  585. // MASK
  586. if ( this.maskNode !== null ) {
  587. // Discard if the mask is `false`
  588. bool( this.maskNode ).not().discard();
  589. }
  590. // COLOR
  591. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  592. // VERTEX COLORS
  593. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  594. colorNode = colorNode.mul( vertexColor() );
  595. }
  596. // INSTANCED COLORS
  597. if ( object.instanceColor ) {
  598. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  599. colorNode = instanceColor.mul( colorNode );
  600. }
  601. if ( object.isBatchedMesh && object._colorsTexture ) {
  602. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  603. colorNode = batchColor.mul( colorNode );
  604. }
  605. // DIFFUSE COLOR
  606. diffuseColor.assign( colorNode );
  607. // OPACITY
  608. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  609. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  610. // ALPHA TEST
  611. let alphaTestNode = null;
  612. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  613. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  614. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  615. }
  616. // ALPHA HASH
  617. if ( this.alphaHash === true ) {
  618. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  619. }
  620. // OPAQUE
  621. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  622. if ( isOpaque ) {
  623. diffuseColor.a.assign( 1.0 );
  624. } else if ( alphaTestNode === null ) {
  625. diffuseColor.a.lessThanEqual( 0 ).discard();
  626. }
  627. }
  628. /**
  629. * Abstract interface method that can be implemented by derived materials
  630. * to setup material-specific node variables.
  631. *
  632. * @abstract
  633. * @param {NodeBuilder} builder - The current node builder.
  634. */
  635. setupVariants( /*builder*/ ) {
  636. // Interface function.
  637. }
  638. /**
  639. * Setups the outgoing light node variable
  640. *
  641. * @return {Node<vec3>} The outgoing light node.
  642. */
  643. setupOutgoingLight() {
  644. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  645. }
  646. /**
  647. * Setups the normal node from the material.
  648. *
  649. * @return {Node<vec3>} The normal node.
  650. */
  651. setupNormal() {
  652. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  653. }
  654. /**
  655. * Setups the environment node from the material.
  656. *
  657. * @param {NodeBuilder} builder - The current node builder.
  658. * @return {Node<vec4>} The environment node.
  659. */
  660. setupEnvironment( /*builder*/ ) {
  661. let node = null;
  662. if ( this.envNode ) {
  663. node = this.envNode;
  664. } else if ( this.envMap ) {
  665. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  666. }
  667. return node;
  668. }
  669. /**
  670. * Setups the light map node from the material.
  671. *
  672. * @param {NodeBuilder} builder - The current node builder.
  673. * @return {Node<vec3>} The light map node.
  674. */
  675. setupLightMap( builder ) {
  676. let node = null;
  677. if ( builder.material.lightMap ) {
  678. node = new IrradianceNode( materialLightMap );
  679. }
  680. return node;
  681. }
  682. /**
  683. * Setups the lights node based on the scene, environment and material.
  684. *
  685. * @param {NodeBuilder} builder - The current node builder.
  686. * @return {LightsNode} The lights node.
  687. */
  688. setupLights( builder ) {
  689. const materialLightsNode = [];
  690. //
  691. const envNode = this.setupEnvironment( builder );
  692. if ( envNode && envNode.isLightingNode ) {
  693. materialLightsNode.push( envNode );
  694. }
  695. const lightMapNode = this.setupLightMap( builder );
  696. if ( lightMapNode && lightMapNode.isLightingNode ) {
  697. materialLightsNode.push( lightMapNode );
  698. }
  699. if ( this.aoNode !== null || builder.material.aoMap ) {
  700. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  701. materialLightsNode.push( new AONode( aoNode ) );
  702. }
  703. let lightsN = this.lightsNode || builder.lightsNode;
  704. if ( materialLightsNode.length > 0 ) {
  705. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  706. }
  707. return lightsN;
  708. }
  709. /**
  710. * This method should be implemented by most derived materials
  711. * since it defines the material's lighting model.
  712. *
  713. * @abstract
  714. * @param {NodeBuilder} builder - The current node builder.
  715. * @return {LightingModel} The lighting model.
  716. */
  717. setupLightingModel( /*builder*/ ) {
  718. // Interface function.
  719. }
  720. /**
  721. * Setups the outgoing light node.
  722. *
  723. * @param {NodeBuilder} builder - The current node builder.
  724. * @return {Node<vec3>} The outgoing light node.
  725. */
  726. setupLighting( builder ) {
  727. const { material } = builder;
  728. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  729. // OUTGOING LIGHT
  730. const lights = this.lights === true || this.lightsNode !== null;
  731. const lightsNode = lights ? this.setupLights( builder ) : null;
  732. let outgoingLightNode = this.setupOutgoingLight( builder );
  733. if ( lightsNode && lightsNode.getScope().hasLights ) {
  734. const lightingModel = this.setupLightingModel( builder ) || null;
  735. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  736. } else if ( backdropNode !== null ) {
  737. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  738. }
  739. // EMISSIVE
  740. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  741. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  742. outgoingLightNode = outgoingLightNode.add( emissive );
  743. }
  744. return outgoingLightNode;
  745. }
  746. /**
  747. * Setup the fog.
  748. *
  749. * @param {NodeBuilder} builder - The current node builder.
  750. * @param {Node<vec4>} outputNode - The existing output node.
  751. * @return {Node<vec4>} The output node.
  752. */
  753. setupFog( builder, outputNode ) {
  754. const fogNode = builder.fogNode;
  755. if ( fogNode ) {
  756. output.assign( outputNode );
  757. outputNode = vec4( fogNode );
  758. }
  759. return outputNode;
  760. }
  761. /**
  762. * Setups the output node.
  763. *
  764. * @param {NodeBuilder} builder - The current node builder.
  765. * @param {Node<vec4>} outputNode - The existing output node.
  766. * @return {Node<vec4>} The output node.
  767. */
  768. setupOutput( builder, outputNode ) {
  769. // FOG
  770. if ( this.fog === true ) {
  771. outputNode = this.setupFog( builder, outputNode );
  772. }
  773. return outputNode;
  774. }
  775. /**
  776. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  777. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  778. * defining all material properties of the classic type in the node type.
  779. *
  780. * @param {Material} material - The material to copy properties with their values to this node material.
  781. */
  782. setDefaultValues( material ) {
  783. // This approach is to reuse the native refreshUniforms*
  784. // and turn available the use of features like transmission and environment in core
  785. for ( const property in material ) {
  786. const value = material[ property ];
  787. if ( this[ property ] === undefined ) {
  788. this[ property ] = value;
  789. if ( value && value.clone ) this[ property ] = value.clone();
  790. }
  791. }
  792. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  793. for ( const key in descriptors ) {
  794. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  795. descriptors[ key ].get !== undefined ) {
  796. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  797. }
  798. }
  799. }
  800. /**
  801. * Serializes this material to JSON.
  802. *
  803. * @param {?(Object|string)} meta - The meta information for serialization.
  804. * @return {Object} The serialized node.
  805. */
  806. toJSON( meta ) {
  807. const isRoot = ( meta === undefined || typeof meta === 'string' );
  808. if ( isRoot ) {
  809. meta = {
  810. textures: {},
  811. images: {},
  812. nodes: {}
  813. };
  814. }
  815. const data = Material.prototype.toJSON.call( this, meta );
  816. const nodeChildren = getNodeChildren( this );
  817. data.inputNodes = {};
  818. for ( const { property, childNode } of nodeChildren ) {
  819. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  820. }
  821. // TODO: Copied from Object3D.toJSON
  822. function extractFromCache( cache ) {
  823. const values = [];
  824. for ( const key in cache ) {
  825. const data = cache[ key ];
  826. delete data.metadata;
  827. values.push( data );
  828. }
  829. return values;
  830. }
  831. if ( isRoot ) {
  832. const textures = extractFromCache( meta.textures );
  833. const images = extractFromCache( meta.images );
  834. const nodes = extractFromCache( meta.nodes );
  835. if ( textures.length > 0 ) data.textures = textures;
  836. if ( images.length > 0 ) data.images = images;
  837. if ( nodes.length > 0 ) data.nodes = nodes;
  838. }
  839. return data;
  840. }
  841. /**
  842. * Copies the properties of the given node material to this instance.
  843. *
  844. * @param {NodeMaterial} source - The material to copy.
  845. * @return {NodeMaterial} A reference to this node material.
  846. */
  847. copy( source ) {
  848. this.lightsNode = source.lightsNode;
  849. this.envNode = source.envNode;
  850. this.colorNode = source.colorNode;
  851. this.normalNode = source.normalNode;
  852. this.opacityNode = source.opacityNode;
  853. this.backdropNode = source.backdropNode;
  854. this.backdropAlphaNode = source.backdropAlphaNode;
  855. this.alphaTestNode = source.alphaTestNode;
  856. this.maskNode = source.maskNode;
  857. this.positionNode = source.positionNode;
  858. this.geometryNode = source.geometryNode;
  859. this.depthNode = source.depthNode;
  860. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  861. this.castShadowPositionNode = source.castShadowPositionNode;
  862. this.receivedShadowNode = source.receivedShadowNode;
  863. this.castShadowNode = source.castShadowNode;
  864. this.outputNode = source.outputNode;
  865. this.mrtNode = source.mrtNode;
  866. this.fragmentNode = source.fragmentNode;
  867. this.vertexNode = source.vertexNode;
  868. return super.copy( source );
  869. }
  870. }
  871. export default NodeMaterial;
粤ICP备19079148号