NodeMaterial.js 12 KB

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