NodeMaterial.js 11 KB

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