NodeMaterial.js 12 KB

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