NodeMaterial.js 11 KB

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