2
0

NodeMaterial.js 13 KB

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