NodeMaterial.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. import { Material, NormalBlending } from 'three';
  2. import { getNodeChildren, getCacheKey } from '../core/NodeUtils.js';
  3. import { attribute } from '../core/AttributeNode.js';
  4. import { output, diffuseColor, varyingProperty } from '../core/PropertyNode.js';
  5. import { materialAlphaTest, materialColor, materialOpacity, materialEmissive, materialNormal } from '../accessors/MaterialNode.js';
  6. import { modelViewProjection } from '../accessors/ModelViewProjectionNode.js';
  7. import { transformedNormalView, normalLocal } from '../accessors/NormalNode.js';
  8. import { instance } from '../accessors/InstanceNode.js';
  9. import { batch } from '../accessors/BatchNode.js';
  10. import { materialReference } from '../accessors/MaterialReferenceNode.js';
  11. import { positionLocal, positionView } from '../accessors/PositionNode.js';
  12. import { skinningReference } from '../accessors/SkinningNode.js';
  13. import { morphReference } from '../accessors/MorphNode.js';
  14. import { texture } from '../accessors/TextureNode.js';
  15. import { cubeTexture } from '../accessors/CubeTextureNode.js';
  16. import { lightsNode } from '../lighting/LightsNode.js';
  17. import { mix } from '../math/MathNode.js';
  18. import { float, vec3, vec4 } from '../shadernode/ShaderNode.js';
  19. import AONode from '../lighting/AONode.js';
  20. import { lightingContext } from '../lighting/LightingContextNode.js';
  21. import EnvironmentNode from '../lighting/EnvironmentNode.js';
  22. import IrradianceNode from '../lighting/IrradianceNode.js';
  23. import { depth } from '../display/ViewportDepthNode.js';
  24. import { cameraLogDepth } from '../accessors/CameraNode.js';
  25. import { clipping, clippingAlpha } from '../accessors/ClippingNode.js';
  26. import { faceDirection } from '../display/FrontFacingNode.js';
  27. const NodeMaterials = new Map();
  28. class NodeMaterial extends Material {
  29. constructor() {
  30. super();
  31. this.isNodeMaterial = true;
  32. this.type = this.constructor.type;
  33. this.forceSinglePass = false;
  34. this.fog = true;
  35. this.lights = true;
  36. this.normals = true;
  37. this.lightsNode = null;
  38. this.envNode = null;
  39. this.aoNode = null;
  40. this.colorNode = null;
  41. this.normalNode = null;
  42. this.opacityNode = null;
  43. this.backdropNode = null;
  44. this.backdropAlphaNode = null;
  45. this.alphaTestNode = null;
  46. this.positionNode = null;
  47. this.depthNode = null;
  48. this.shadowNode = null;
  49. this.shadowPositionNode = null;
  50. this.outputNode = null;
  51. this.fragmentNode = null;
  52. this.vertexNode = null;
  53. }
  54. customProgramCacheKey() {
  55. return this.type + getCacheKey( this );
  56. }
  57. build( builder ) {
  58. this.setup( builder );
  59. }
  60. setup( builder ) {
  61. // < VERTEX STAGE >
  62. builder.addStack();
  63. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  64. builder.addFlow( 'vertex', builder.removeStack() );
  65. // < FRAGMENT STAGE >
  66. builder.addStack();
  67. let resultNode;
  68. const clippingNode = this.setupClipping( builder );
  69. if ( this.depthWrite === true ) this.setupDepth( builder );
  70. if ( this.fragmentNode === null ) {
  71. if ( this.normals === true ) this.setupNormal( builder );
  72. this.setupDiffuseColor( builder );
  73. this.setupVariants( builder );
  74. const outgoingLightNode = this.setupLighting( builder );
  75. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  76. // force unsigned floats - useful for RenderTargets
  77. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  78. resultNode = this.setupOutput( builder, basicOutput );
  79. // OUTPUT NODE
  80. output.assign( resultNode );
  81. //
  82. if ( this.outputNode !== null ) resultNode = this.outputNode;
  83. } else {
  84. let fragmentNode = this.fragmentNode;
  85. if ( fragmentNode.isOutputStructNode !== true ) {
  86. fragmentNode = vec4( fragmentNode );
  87. }
  88. resultNode = this.setupOutput( builder, fragmentNode );
  89. }
  90. builder.stack.outputNode = resultNode;
  91. builder.addFlow( 'fragment', builder.removeStack() );
  92. }
  93. setupClipping( builder ) {
  94. if ( builder.clippingContext === null ) return null;
  95. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  96. let result = null;
  97. if ( globalClippingCount || localClippingCount ) {
  98. if ( this.alphaToCoverage ) {
  99. // to be added to flow when the color/alpha value has been determined
  100. result = clippingAlpha();
  101. } else {
  102. builder.stack.add( clipping() );
  103. }
  104. }
  105. return result;
  106. }
  107. setupDepth( builder ) {
  108. const { renderer } = builder;
  109. // Depth
  110. let depthNode = this.depthNode;
  111. if ( depthNode === null && renderer.logarithmicDepthBuffer === true ) {
  112. const fragDepth = modelViewProjection().w.add( 1 );
  113. depthNode = fragDepth.log2().mul( cameraLogDepth ).mul( 0.5 );
  114. }
  115. if ( depthNode !== null ) {
  116. depth.assign( depthNode ).append();
  117. }
  118. }
  119. setupPosition( builder ) {
  120. const { object } = builder;
  121. const geometry = object.geometry;
  122. builder.addStack();
  123. // Vertex
  124. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  125. morphReference( object ).append();
  126. }
  127. if ( object.isSkinnedMesh === true ) {
  128. skinningReference( object ).append();
  129. }
  130. if ( this.displacementMap ) {
  131. const displacementMap = materialReference( 'displacementMap', 'texture' );
  132. const displacementScale = materialReference( 'displacementScale', 'float' );
  133. const displacementBias = materialReference( 'displacementBias', 'float' );
  134. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  135. }
  136. if ( object.isBatchedMesh ) {
  137. batch( object ).append();
  138. }
  139. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  140. instance( object ).append();
  141. }
  142. if ( this.positionNode !== null ) {
  143. positionLocal.assign( this.positionNode );
  144. }
  145. const mvp = modelViewProjection();
  146. builder.context.vertex = builder.removeStack();
  147. builder.context.mvp = mvp;
  148. return mvp;
  149. }
  150. setupDiffuseColor( { object, geometry } ) {
  151. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  152. // VERTEX COLORS
  153. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  154. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  155. }
  156. // Instanced colors
  157. if ( object.instanceColor ) {
  158. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  159. colorNode = instanceColor.mul( colorNode );
  160. }
  161. // COLOR
  162. diffuseColor.assign( colorNode );
  163. // OPACITY
  164. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  165. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  166. // ALPHA TEST
  167. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  168. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  169. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  170. }
  171. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  172. diffuseColor.a.assign( 1.0 );
  173. }
  174. }
  175. setupVariants( /*builder*/ ) {
  176. // Interface function.
  177. }
  178. setupNormal() {
  179. // NORMAL VIEW
  180. if ( this.flatShading === true ) {
  181. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  182. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  183. } else {
  184. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  185. transformedNormalView.assign( normalNode.mul( faceDirection ) );
  186. }
  187. }
  188. getEnvNode( builder ) {
  189. let node = null;
  190. if ( this.envNode ) {
  191. node = this.envNode;
  192. } else if ( this.envMap ) {
  193. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  194. } else if ( builder.environmentNode ) {
  195. node = builder.environmentNode;
  196. }
  197. return node;
  198. }
  199. setupLights( builder ) {
  200. const envNode = this.getEnvNode( builder );
  201. //
  202. const materialLightsNode = [];
  203. if ( envNode ) {
  204. materialLightsNode.push( new EnvironmentNode( envNode ) );
  205. }
  206. if ( builder.material.lightMap ) {
  207. materialLightsNode.push( new IrradianceNode( materialReference( 'lightMap', 'texture' ) ) );
  208. }
  209. if ( this.aoNode !== null || builder.material.aoMap ) {
  210. const aoNode = this.aoNode !== null ? this.aoNode : texture( builder.material.aoMap );
  211. materialLightsNode.push( new AONode( aoNode ) );
  212. }
  213. let lightsN = this.lightsNode || builder.lightsNode;
  214. if ( materialLightsNode.length > 0 ) {
  215. lightsN = lightsNode( [ ...lightsN.lightNodes, ...materialLightsNode ] );
  216. }
  217. return lightsN;
  218. }
  219. setupLightingModel( /*builder*/ ) {
  220. // Interface function.
  221. }
  222. setupLighting( builder ) {
  223. const { material } = builder;
  224. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  225. // OUTGOING LIGHT
  226. const lights = this.lights === true || this.lightsNode !== null;
  227. const lightsNode = lights ? this.setupLights( builder ) : null;
  228. let outgoingLightNode = diffuseColor.rgb;
  229. if ( lightsNode && lightsNode.hasLight !== false ) {
  230. const lightingModel = this.setupLightingModel( builder );
  231. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  232. } else if ( backdropNode !== null ) {
  233. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  234. }
  235. // EMISSIVE
  236. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  237. outgoingLightNode = outgoingLightNode.add( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  238. }
  239. return outgoingLightNode;
  240. }
  241. setupOutput( builder, outputNode ) {
  242. // FOG
  243. if ( this.fog === true ) {
  244. const fogNode = builder.fogNode;
  245. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  246. }
  247. return outputNode;
  248. }
  249. setDefaultValues( material ) {
  250. // This approach is to reuse the native refreshUniforms*
  251. // and turn available the use of features like transmission and environment in core
  252. for ( const property in material ) {
  253. const value = material[ property ];
  254. if ( this[ property ] === undefined ) {
  255. this[ property ] = value;
  256. if ( value && value.clone ) this[ property ] = value.clone();
  257. }
  258. }
  259. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  260. for ( const key in descriptors ) {
  261. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  262. descriptors[ key ].get !== undefined ) {
  263. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  264. }
  265. }
  266. }
  267. toJSON( meta ) {
  268. const isRoot = ( meta === undefined || typeof meta === 'string' );
  269. if ( isRoot ) {
  270. meta = {
  271. textures: {},
  272. images: {},
  273. nodes: {}
  274. };
  275. }
  276. const data = Material.prototype.toJSON.call( this, meta );
  277. const nodeChildren = getNodeChildren( this );
  278. data.inputNodes = {};
  279. for ( const { property, childNode } of nodeChildren ) {
  280. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  281. }
  282. // TODO: Copied from Object3D.toJSON
  283. function extractFromCache( cache ) {
  284. const values = [];
  285. for ( const key in cache ) {
  286. const data = cache[ key ];
  287. delete data.metadata;
  288. values.push( data );
  289. }
  290. return values;
  291. }
  292. if ( isRoot ) {
  293. const textures = extractFromCache( meta.textures );
  294. const images = extractFromCache( meta.images );
  295. const nodes = extractFromCache( meta.nodes );
  296. if ( textures.length > 0 ) data.textures = textures;
  297. if ( images.length > 0 ) data.images = images;
  298. if ( nodes.length > 0 ) data.nodes = nodes;
  299. }
  300. return data;
  301. }
  302. copy( source ) {
  303. this.lightsNode = source.lightsNode;
  304. this.envNode = source.envNode;
  305. this.colorNode = source.colorNode;
  306. this.normalNode = source.normalNode;
  307. this.opacityNode = source.opacityNode;
  308. this.backdropNode = source.backdropNode;
  309. this.backdropAlphaNode = source.backdropAlphaNode;
  310. this.alphaTestNode = source.alphaTestNode;
  311. this.positionNode = source.positionNode;
  312. this.depthNode = source.depthNode;
  313. this.shadowNode = source.shadowNode;
  314. this.shadowPositionNode = source.shadowPositionNode;
  315. this.outputNode = source.outputNode;
  316. this.fragmentNode = source.fragmentNode;
  317. this.vertexNode = source.vertexNode;
  318. return super.copy( source );
  319. }
  320. static fromMaterial( material ) {
  321. if ( material.isNodeMaterial === true ) { // is already a node material
  322. return material;
  323. }
  324. const type = material.type.replace( 'Material', 'NodeMaterial' );
  325. const nodeMaterial = createNodeMaterialFromType( type );
  326. if ( nodeMaterial === undefined ) {
  327. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  328. }
  329. for ( const key in material ) {
  330. nodeMaterial[ key ] = material[ key ];
  331. }
  332. return nodeMaterial;
  333. }
  334. }
  335. export default NodeMaterial;
  336. export function addNodeMaterial( type, nodeMaterial ) {
  337. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  338. if ( NodeMaterials.has( type ) ) {
  339. console.warn( `Redefinition of node material ${ type }` );
  340. return;
  341. }
  342. NodeMaterials.set( type, nodeMaterial );
  343. nodeMaterial.type = type;
  344. }
  345. export function createNodeMaterialFromType( type ) {
  346. const Material = NodeMaterials.get( type );
  347. if ( Material !== undefined ) {
  348. return new Material();
  349. }
  350. }
  351. addNodeMaterial( 'NodeMaterial', NodeMaterial );