NodeMaterial.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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.type;
  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.setup( builder );
  50. }
  51. setup( builder ) {
  52. // < VERTEX STAGE >
  53. builder.addStack();
  54. builder.stack.outputNode = this.setupPosition( 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.setupNormal( builder );
  61. this.setupDiffuseColor( builder );
  62. this.setupVariants( builder );
  63. const outgoingLightNode = this.setupLighting( builder );
  64. outputNode = this.setupOutput( 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.setupOutput( builder, this.outputNode || vec4( 0, 0, 0, 1 ) );
  71. }
  72. builder.stack.outputNode = outputNode;
  73. builder.addFlow( 'fragment', builder.removeStack() );
  74. }
  75. setupPosition( 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. setupDiffuseColor( { 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. setupVariants( /*builder*/ ) {
  112. // Interface function.
  113. }
  114. setupNormal( { stack } ) {
  115. // NORMAL VIEW
  116. if ( this.flatShading === true ) {
  117. const fdx = dFdx( positionView );
  118. const fdy = dFdy( 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. setupLights( 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. setupLightingModel( /*builder*/ ) {
  154. // Interface function.
  155. }
  156. setupLighting( 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.setupLights( builder ) : null;
  162. let outgoingLightNode = diffuseColor.rgb;
  163. if ( lightsNode && lightsNode.hasLight !== false ) {
  164. const lightingModelNode = this.setupLightingModel( 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. setupOutput( 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. if ( Array.isArray( renderTarget.texture ) ) {
  193. outputColorSpace = renderTarget.texture[ 0 ].colorSpace;
  194. } else {
  195. outputColorSpace = renderTarget.texture.colorSpace;
  196. }
  197. } else {
  198. outputColorSpace = renderer.outputColorSpace;
  199. }
  200. if ( outputColorSpace !== LinearSRGBColorSpace && outputColorSpace !== NoColorSpace ) {
  201. outputNode = outputNode.linearToColorSpace( outputColorSpace );
  202. }
  203. }
  204. return outputNode;
  205. }
  206. setDefaultValues( material ) {
  207. // This approach is to reuse the native refreshUniforms*
  208. // and turn available the use of features like transmission and environment in core
  209. for ( const property in material ) {
  210. const value = material[ property ];
  211. if ( this[ property ] === undefined ) {
  212. this[ property ] = value;
  213. if ( value && value.clone ) this[ property ] = value.clone();
  214. }
  215. }
  216. Object.assign( this.defines, material.defines );
  217. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  218. for ( const key in descriptors ) {
  219. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  220. descriptors[ key ].get !== undefined ) {
  221. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  222. }
  223. }
  224. }
  225. toJSON( meta ) {
  226. const isRoot = ( meta === undefined || typeof meta === 'string' );
  227. if ( isRoot ) {
  228. meta = {
  229. textures: {},
  230. images: {},
  231. nodes: {}
  232. };
  233. }
  234. const data = Material.prototype.toJSON.call( this, meta );
  235. const nodeChildren = getNodeChildren( this );
  236. data.inputNodes = {};
  237. for ( const { property, childNode } of nodeChildren ) {
  238. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  239. }
  240. // TODO: Copied from Object3D.toJSON
  241. function extractFromCache( cache ) {
  242. const values = [];
  243. for ( const key in cache ) {
  244. const data = cache[ key ];
  245. delete data.metadata;
  246. values.push( data );
  247. }
  248. return values;
  249. }
  250. if ( isRoot ) {
  251. const textures = extractFromCache( meta.textures );
  252. const images = extractFromCache( meta.images );
  253. const nodes = extractFromCache( meta.nodes );
  254. if ( textures.length > 0 ) data.textures = textures;
  255. if ( images.length > 0 ) data.images = images;
  256. if ( nodes.length > 0 ) data.nodes = nodes;
  257. }
  258. return data;
  259. }
  260. copy( source ) {
  261. this.lightsNode = source.lightsNode;
  262. this.envNode = source.envNode;
  263. this.colorNode = source.colorNode;
  264. this.normalNode = source.normalNode;
  265. this.opacityNode = source.opacityNode;
  266. this.backdropNode = source.backdropNode;
  267. this.backdropAlphaNode = source.backdropAlphaNode;
  268. this.alphaTestNode = source.alphaTestNode;
  269. this.positionNode = source.positionNode;
  270. this.outputNode = source.outputNode;
  271. this.vertexNode = source.vertexNode;
  272. return super.copy( source );
  273. }
  274. static fromMaterial( material ) {
  275. if ( material.isNodeMaterial === true ) { // is already a node material
  276. return material;
  277. }
  278. const type = material.type.replace( 'Material', 'NodeMaterial' );
  279. const nodeMaterial = createNodeMaterialFromType( type );
  280. if ( nodeMaterial === undefined ) {
  281. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  282. }
  283. for ( const key in material ) {
  284. nodeMaterial[ key ] = material[ key ];
  285. }
  286. return nodeMaterial;
  287. }
  288. }
  289. export default NodeMaterial;
  290. export function addNodeMaterial( type, nodeMaterial ) {
  291. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  292. if ( NodeMaterials.has( type ) ) throw new Error( `Redefinition of node material ${ type }` );
  293. NodeMaterials.set( type, nodeMaterial );
  294. nodeMaterial.type = type;
  295. }
  296. export function createNodeMaterialFromType( type ) {
  297. const Material = NodeMaterials.get( type );
  298. if ( Material !== undefined ) {
  299. return new Material();
  300. }
  301. }
  302. addNodeMaterial( 'NodeMaterial', NodeMaterial );