NodeMaterial.js 13 KB

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