2
0

NodeMaterial.js 12 KB

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