NodeMaterial.js 12 KB

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