NodeMaterial.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 { skinning } from '../accessors/SkinningNode.js';
  11. import { morph } from '../accessors/MorphNode.js';
  12. import { texture } from '../accessors/TextureNode.js';
  13. import { cubeTexture } from '../accessors/CubeTextureNode.js';
  14. import { lightNodes } 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. const NodeMaterials = new Map();
  21. class NodeMaterial extends ShaderMaterial {
  22. constructor() {
  23. super();
  24. this.isNodeMaterial = true;
  25. this.type = this.constructor.type;
  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.setup( builder );
  49. }
  50. setup( builder ) {
  51. // < VERTEX STAGE >
  52. builder.addStack();
  53. builder.stack.outputNode = this.setupPosition( 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.setupNormal( builder );
  60. this.setupDiffuseColor( builder );
  61. this.setupVariants( builder );
  62. const outgoingLightNode = this.setupLighting( builder );
  63. outputNode = this.setupOutput( builder, vec4( outgoingLightNode, diffuseColor.a ) );
  64. // OUTPUT NODE
  65. output.assign( outputNode );
  66. //
  67. if ( this.outputNode !== null ) outputNode = this.outputNode;
  68. } else {
  69. outputNode = this.setupOutput( builder, this.outputNode || vec4( 0, 0, 0, 1 ) );
  70. }
  71. builder.stack.outputNode = outputNode;
  72. builder.addFlow( 'fragment', builder.removeStack() );
  73. }
  74. setupPosition( 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. morph( object ).append();
  80. }
  81. if ( object.isSkinnedMesh === true ) {
  82. skinning( object ).append();
  83. }
  84. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) && builder.isAvailable( 'instance' ) === true ) {
  85. instance( object ).append();
  86. }
  87. if ( this.positionNode !== null ) {
  88. positionLocal.assign( this.positionNode );
  89. }
  90. builder.context.vertex = builder.removeStack();
  91. return this.vertexNode || modelViewProjection();
  92. }
  93. setupDiffuseColor( { 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. diffuseColor.assign( colorNode );
  101. // OPACITY
  102. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  103. diffuseColor.a.assign( 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. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  108. }
  109. }
  110. setupVariants( /*builder*/ ) {
  111. // Interface function.
  112. }
  113. setupNormal() {
  114. // NORMAL VIEW
  115. if ( this.flatShading === true ) {
  116. const normalNode = positionView.dFdx().cross( positionView.dFdy() ).normalize();
  117. transformedNormalView.assign( normalNode );
  118. } else {
  119. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  120. transformedNormalView.assign( normalNode );
  121. }
  122. }
  123. getEnvNode( builder ) {
  124. let node = null;
  125. if ( this.envNode ) {
  126. node = this.envNode;
  127. } else if ( this.envMap ) {
  128. node = this.envMap.isCubeTexture ? cubeTexture( this.envMap ) : texture( this.envMap );
  129. } else if ( builder.environmentNode ) {
  130. node = builder.environmentNode;
  131. }
  132. return node;
  133. }
  134. setupLights( builder ) {
  135. const envNode = this.getEnvNode( builder );
  136. //
  137. const materialLightsNode = [];
  138. if ( envNode ) {
  139. materialLightsNode.push( new EnvironmentNode( envNode ) );
  140. }
  141. if ( builder.material.aoMap ) {
  142. materialLightsNode.push( new AONode( texture( builder.material.aoMap ) ) );
  143. }
  144. let lightsNode = this.lightsNode || builder.lightsNode;
  145. if ( materialLightsNode.length > 0 ) {
  146. lightsNode = lightNodes( [ ...lightsNode.lightNodes, ...materialLightsNode ] );
  147. }
  148. return lightsNode;
  149. }
  150. setupLightingModel( /*builder*/ ) {
  151. // Interface function.
  152. }
  153. setupLighting( builder ) {
  154. const { material } = builder;
  155. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  156. // OUTGOING LIGHT
  157. const lights = this.lights === true || this.lightsNode !== null;
  158. const lightsNode = lights ? this.setupLights( builder ) : null;
  159. let outgoingLightNode = diffuseColor.rgb;
  160. if ( lightsNode && lightsNode.hasLight !== false ) {
  161. const lightingModel = this.setupLightingModel( builder );
  162. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  163. } else if ( backdropNode !== null ) {
  164. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  165. }
  166. // EMISSIVE
  167. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  168. outgoingLightNode = outgoingLightNode.add( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  169. }
  170. return outgoingLightNode;
  171. }
  172. setupOutput( builder, outputNode ) {
  173. const renderer = builder.renderer;
  174. // TONE MAPPING
  175. const toneMappingNode = builder.toneMappingNode;
  176. if ( toneMappingNode ) {
  177. outputNode = vec4( toneMappingNode.context( { color: outputNode.rgb } ), outputNode.a );
  178. }
  179. // FOG
  180. if ( this.fog === true ) {
  181. const fogNode = builder.fogNode;
  182. if ( fogNode ) outputNode = vec4( fogNode.mixAssign( outputNode.rgb ), outputNode.a );
  183. }
  184. // ENCODING
  185. if ( this.colorSpace === true ) {
  186. const renderTarget = renderer.getRenderTarget();
  187. let outputColorSpace;
  188. if ( renderTarget !== null ) {
  189. if ( Array.isArray( renderTarget.texture ) ) {
  190. outputColorSpace = renderTarget.texture[ 0 ].colorSpace;
  191. } else {
  192. outputColorSpace = renderTarget.texture.colorSpace;
  193. }
  194. } else {
  195. outputColorSpace = renderer.outputColorSpace;
  196. }
  197. if ( outputColorSpace !== LinearSRGBColorSpace && outputColorSpace !== NoColorSpace ) {
  198. outputNode = outputNode.linearToColorSpace( outputColorSpace );
  199. }
  200. }
  201. return outputNode;
  202. }
  203. setDefaultValues( material ) {
  204. // This approach is to reuse the native refreshUniforms*
  205. // and turn available the use of features like transmission and environment in core
  206. for ( const property in material ) {
  207. const value = material[ property ];
  208. if ( this[ property ] === undefined ) {
  209. this[ property ] = value;
  210. if ( value && value.clone ) this[ property ] = value.clone();
  211. }
  212. }
  213. Object.assign( this.defines, material.defines );
  214. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  215. for ( const key in descriptors ) {
  216. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  217. descriptors[ key ].get !== undefined ) {
  218. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  219. }
  220. }
  221. }
  222. toJSON( meta ) {
  223. const isRoot = ( meta === undefined || typeof meta === 'string' );
  224. if ( isRoot ) {
  225. meta = {
  226. textures: {},
  227. images: {},
  228. nodes: {}
  229. };
  230. }
  231. const data = Material.prototype.toJSON.call( this, meta );
  232. const nodeChildren = getNodeChildren( this );
  233. data.inputNodes = {};
  234. for ( const { property, childNode } of nodeChildren ) {
  235. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  236. }
  237. // TODO: Copied from Object3D.toJSON
  238. function extractFromCache( cache ) {
  239. const values = [];
  240. for ( const key in cache ) {
  241. const data = cache[ key ];
  242. delete data.metadata;
  243. values.push( data );
  244. }
  245. return values;
  246. }
  247. if ( isRoot ) {
  248. const textures = extractFromCache( meta.textures );
  249. const images = extractFromCache( meta.images );
  250. const nodes = extractFromCache( meta.nodes );
  251. if ( textures.length > 0 ) data.textures = textures;
  252. if ( images.length > 0 ) data.images = images;
  253. if ( nodes.length > 0 ) data.nodes = nodes;
  254. }
  255. return data;
  256. }
  257. copy( source ) {
  258. this.lightsNode = source.lightsNode;
  259. this.envNode = source.envNode;
  260. this.colorNode = source.colorNode;
  261. this.normalNode = source.normalNode;
  262. this.opacityNode = source.opacityNode;
  263. this.backdropNode = source.backdropNode;
  264. this.backdropAlphaNode = source.backdropAlphaNode;
  265. this.alphaTestNode = source.alphaTestNode;
  266. this.positionNode = source.positionNode;
  267. this.outputNode = source.outputNode;
  268. this.vertexNode = source.vertexNode;
  269. return super.copy( source );
  270. }
  271. static fromMaterial( material ) {
  272. if ( material.isNodeMaterial === true ) { // is already a node material
  273. return material;
  274. }
  275. const type = material.type.replace( 'Material', 'NodeMaterial' );
  276. const nodeMaterial = createNodeMaterialFromType( type );
  277. if ( nodeMaterial === undefined ) {
  278. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  279. }
  280. for ( const key in material ) {
  281. nodeMaterial[ key ] = material[ key ];
  282. }
  283. return nodeMaterial;
  284. }
  285. }
  286. export default NodeMaterial;
  287. export function addNodeMaterial( type, nodeMaterial ) {
  288. if ( typeof nodeMaterial !== 'function' || ! type ) throw new Error( `Node material ${ type } is not a class` );
  289. if ( NodeMaterials.has( type ) ) throw new Error( `Redefinition of node material ${ type }` );
  290. NodeMaterials.set( type, nodeMaterial );
  291. nodeMaterial.type = type;
  292. }
  293. export function createNodeMaterialFromType( type ) {
  294. const Material = NodeMaterials.get( type );
  295. if ( Material !== undefined ) {
  296. return new Material();
  297. }
  298. }
  299. addNodeMaterial( 'NodeMaterial', NodeMaterial );