NodeMaterial.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. import { Material, ShaderMaterial, NoToneMapping } from 'three';
  2. import { getNodeChildren, getCacheKey } from '../core/NodeUtils.js';
  3. import { attribute } from '../core/AttributeNode.js';
  4. import { 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 } from '../accessors/PositionNode.js';
  11. import { reference } from '../accessors/ReferenceNode.js';
  12. import { skinning } from '../accessors/SkinningNode.js';
  13. import { texture } from '../accessors/TextureNode.js';
  14. import { toneMapping } from '../display/ToneMappingNode.js';
  15. import { rangeFog } from '../fog/FogRangeNode.js';
  16. import { densityFog } from '../fog/FogExp2Node.js';
  17. import { lightsWithoutWrap } from '../lighting/LightsNode.js';
  18. import AONode from '../lighting/AONode.js';
  19. import EnvironmentNode from '../lighting/EnvironmentNode.js';
  20. import { float, vec3, vec4 } from '../shadernode/ShaderNode.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.lights = true;
  28. this.normals = true;
  29. this.lightsNode = null;
  30. }
  31. customProgramCacheKey() {
  32. return getCacheKey( this );
  33. }
  34. build( builder ) {
  35. this.construct( builder );
  36. }
  37. construct( builder ) {
  38. // < VERTEX STAGE >
  39. builder.addStack();
  40. builder.stack.outputNode = this.constructPosition( builder );
  41. builder.addFlow( 'vertex', builder.removeStack() );
  42. // < FRAGMENT STAGE >
  43. builder.addStack();
  44. if ( this.normals === true ) this.constructNormal( builder );
  45. this.constructDiffuseColor( builder );
  46. this.constructVariants( builder );
  47. const outgoingLightNode = this.constructLighting( builder );
  48. builder.stack.outputNode = this.constructOutput( builder, outgoingLightNode, diffuseColor.a );
  49. builder.addFlow( 'fragment', builder.removeStack() );
  50. }
  51. constructPosition( builder ) {
  52. const object = builder.object;
  53. let vertex = positionLocal;
  54. if ( this.positionNode !== null ) {
  55. vertex = vertex.bypass( positionLocal.assign( this.positionNode ) );
  56. }
  57. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) && builder.isAvailable( 'instance' ) === true ) {
  58. vertex = vertex.bypass( instance( object ) );
  59. }
  60. if ( object.isSkinnedMesh === true ) {
  61. vertex = vertex.bypass( skinning( object ) );
  62. }
  63. builder.context.vertex = vertex;
  64. return modelViewProjection();
  65. }
  66. constructDiffuseColor( { stack, geometry } ) {
  67. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  68. // VERTEX COLORS
  69. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  70. colorNode = vec4( colorNode.xyz.mul( attribute( 'color' ) ), colorNode.a );
  71. }
  72. // COLOR
  73. stack.assign( diffuseColor, colorNode );
  74. // OPACITY
  75. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  76. stack.assign( diffuseColor.a, diffuseColor.a.mul( opacityNode ) );
  77. // ALPHA TEST
  78. if ( this.alphaTestNode || this.alphaTest > 0 ) {
  79. const alphaTestNode = this.alphaTestNode ? float( this.alphaTestNode ) : materialAlphaTest;
  80. stack.add( diffuseColor.a.lessThanEqual( alphaTestNode ).discard() );
  81. }
  82. }
  83. constructVariants( /*builder*/ ) {
  84. // Interface function.
  85. }
  86. constructNormal( { stack } ) {
  87. // NORMAL VIEW
  88. const normalNode = this.normalNode ? vec3( this.normalNode ) : materialNormal;
  89. stack.assign( transformedNormalView, normalNode );
  90. return normalNode;
  91. }
  92. constructLights( builder ) {
  93. let lightsNode = this.lightsNode || builder.lightsNode;
  94. const envNode = this.envNode || builder.scene.environmentNode;
  95. const materialLightsNode = [];
  96. if ( envNode ) {
  97. materialLightsNode.push( new EnvironmentNode( envNode ) );
  98. }
  99. if ( builder.material.aoMap ) {
  100. materialLightsNode.push( new AONode( texture( builder.material.aoMap ) ) );
  101. }
  102. if ( materialLightsNode.length > 0 ) {
  103. lightsNode = lightsWithoutWrap( [ ...lightsNode.lightNodes, ...materialLightsNode ] );
  104. }
  105. return lightsNode;
  106. }
  107. constructLightingModel( /*builder*/ ) {
  108. // Interface function.
  109. }
  110. constructLighting( builder ) {
  111. const { material } = builder;
  112. // OUTGOING LIGHT
  113. const lights = this.lights === true || this.lightsNode !== null;
  114. const lightsNode = lights ? this.constructLights( builder ) : null;
  115. const lightingModelNode = lightsNode ? this.constructLightingModel( builder ) : null;
  116. let outgoingLightNode = diffuseColor.rgb;
  117. if ( lightsNode && lightsNode.hasLight !== false ) {
  118. outgoingLightNode = lightsNode.lightingContext( lightingModelNode );
  119. }
  120. // EMISSIVE
  121. if ( ( this.emissiveNode && this.emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  122. outgoingLightNode = outgoingLightNode.add( this.emissiveNode ? vec3( this.emissiveNode ) : materialEmissive );
  123. }
  124. return outgoingLightNode;
  125. }
  126. constructOutput( builder, outgoingLight, opacity ) {
  127. const renderer = builder.renderer;
  128. // TONE MAPPING
  129. let toneMappingNode = renderer.toneMappingNode;
  130. if ( ! toneMappingNode && renderer.toneMapping !== NoToneMapping ) {
  131. toneMappingNode = toneMapping( renderer.toneMapping, reference( 'toneMappingExposure', 'float', renderer ), outgoingLight );
  132. }
  133. if ( toneMappingNode && toneMappingNode.isNode === true ) {
  134. outgoingLight = toneMappingNode.context( { color: outgoingLight } );
  135. }
  136. // @TODO: Optimize outputNode to vec3.
  137. let outputNode = vec4( outgoingLight, opacity );
  138. // ENCODING
  139. outputNode = outputNode.colorSpace( renderer.outputEncoding );
  140. // FOG
  141. let fogNode = builder.fogNode;
  142. if ( ( fogNode && fogNode.isNode !== true ) && builder.scene.fog ) {
  143. const fog = builder.scene.fog;
  144. if ( fog.isFogExp2 ) {
  145. fogNode = densityFog( reference( 'color', 'color', fog ), reference( 'density', 'float', fog ) );
  146. } else if ( fog.isFog ) {
  147. fogNode = rangeFog( reference( 'color', 'color', fog ), reference( 'near', 'float', fog ), reference( 'far', 'float', fog ) );
  148. } else {
  149. console.error( 'NodeMaterial: Unsupported fog configuration.', fog );
  150. }
  151. }
  152. if ( fogNode ) outputNode = vec4( fogNode.mixAssign( outputNode.rgb ), outputNode.a );
  153. return outputNode;
  154. }
  155. setDefaultValues( values ) {
  156. // This approach is to reuse the native refreshUniforms*
  157. // and turn available the use of features like transmission and environment in core
  158. for ( const property in values ) {
  159. const value = values[ property ];
  160. if ( this[ property ] === undefined ) {
  161. this[ property ] = value;
  162. if ( value && value.clone ) this[ property ] = value.clone();
  163. }
  164. }
  165. Object.assign( this.defines, values.defines );
  166. }
  167. toJSON( meta ) {
  168. const isRoot = ( meta === undefined || typeof meta === 'string' );
  169. if ( isRoot ) {
  170. meta = {
  171. textures: {},
  172. images: {},
  173. nodes: {}
  174. };
  175. }
  176. const data = Material.prototype.toJSON.call( this, meta );
  177. const nodeChildren = getNodeChildren( this );
  178. data.inputNodes = {};
  179. for ( const { property, childNode } of nodeChildren ) {
  180. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  181. }
  182. // TODO: Copied from Object3D.toJSON
  183. function extractFromCache( cache ) {
  184. const values = [];
  185. for ( const key in cache ) {
  186. const data = cache[ key ];
  187. delete data.metadata;
  188. values.push( data );
  189. }
  190. return values;
  191. }
  192. if ( isRoot ) {
  193. const textures = extractFromCache( meta.textures );
  194. const images = extractFromCache( meta.images );
  195. const nodes = extractFromCache( meta.nodes );
  196. if ( textures.length > 0 ) data.textures = textures;
  197. if ( images.length > 0 ) data.images = images;
  198. if ( nodes.length > 0 ) data.nodes = nodes;
  199. }
  200. return data;
  201. }
  202. static fromMaterial( material ) {
  203. const type = material.type.replace( 'Material', 'NodeMaterial' );
  204. const nodeMaterial = createNodeMaterialFromType( type );
  205. if ( nodeMaterial === undefined ) {
  206. if ( material.isNodeMaterial !== true ) {
  207. throw new Error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  208. }
  209. return material; // is already a node material
  210. }
  211. for ( const key in material ) {
  212. nodeMaterial[ key ] = material[ key ];
  213. }
  214. return nodeMaterial;
  215. }
  216. }
  217. export default NodeMaterial;
  218. export function addNodeMaterial( nodeMaterial ) {
  219. if ( typeof nodeMaterial !== 'function' || ! nodeMaterial.name ) throw new Error( `Node material ${ nodeMaterial.name } is not a class` );
  220. if ( NodeMaterials.has( nodeMaterial.name ) ) throw new Error( `Redefinition of node material ${ nodeMaterial.name }` );
  221. NodeMaterials.set( nodeMaterial.name, nodeMaterial );
  222. }
  223. export function createNodeMaterialFromType( type ) {
  224. const Material = NodeMaterials.get( type );
  225. if ( Material !== undefined ) {
  226. return new Material();
  227. }
  228. }
  229. addNodeMaterial( NodeMaterial );