WebGLShadowMap.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. import { FrontSide, BackSide, DoubleSide, NearestFilter, PCFShadowMap, VSMShadowMap, RGBADepthPacking, NoBlending } from '../../constants.js';
  2. import { WebGLRenderTarget } from '../WebGLRenderTarget.js';
  3. import { MeshDepthMaterial } from '../../materials/MeshDepthMaterial.js';
  4. import { MeshDistanceMaterial } from '../../materials/MeshDistanceMaterial.js';
  5. import { ShaderMaterial } from '../../materials/ShaderMaterial.js';
  6. import { BufferAttribute } from '../../core/BufferAttribute.js';
  7. import { BufferGeometry } from '../../core/BufferGeometry.js';
  8. import { Mesh } from '../../objects/Mesh.js';
  9. import { Vector4 } from '../../math/Vector4.js';
  10. import { Vector2 } from '../../math/Vector2.js';
  11. import { Frustum } from '../../math/Frustum.js';
  12. import * as vsm from '../shaders/ShaderLib/vsm.glsl.js';
  13. function WebGLShadowMap( renderer, objects, capabilities ) {
  14. let _frustum = new Frustum();
  15. const _shadowMapSize = new Vector2(),
  16. _viewportSize = new Vector2(),
  17. _viewport = new Vector4(),
  18. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  19. _distanceMaterial = new MeshDistanceMaterial(),
  20. _materialCache = {},
  21. _maxTextureSize = capabilities.maxTextureSize;
  22. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  23. const shadowMaterialVertical = new ShaderMaterial( {
  24. defines: {
  25. VSM_SAMPLES: 8
  26. },
  27. uniforms: {
  28. shadow_pass: { value: null },
  29. resolution: { value: new Vector2() },
  30. radius: { value: 4.0 }
  31. },
  32. vertexShader: vsm.vertex,
  33. fragmentShader: vsm.fragment
  34. } );
  35. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  36. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  37. const fullScreenTri = new BufferGeometry();
  38. fullScreenTri.setAttribute(
  39. 'position',
  40. new BufferAttribute(
  41. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  42. 3
  43. )
  44. );
  45. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  46. const scope = this;
  47. this.enabled = false;
  48. this.autoUpdate = true;
  49. this.needsUpdate = false;
  50. this.type = PCFShadowMap;
  51. let _previousType = this.type;
  52. this.render = function ( lights, scene, camera ) {
  53. if ( scope.enabled === false ) return;
  54. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  55. if ( lights.length === 0 ) return;
  56. const currentRenderTarget = renderer.getRenderTarget();
  57. const activeCubeFace = renderer.getActiveCubeFace();
  58. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  59. const _state = renderer.state;
  60. // Set GL state for depth map.
  61. _state.setBlending( NoBlending );
  62. if ( _state.buffers.depth.getReversed() ) {
  63. _state.buffers.color.setClear( 0, 0, 0, 0 );
  64. } else {
  65. _state.buffers.color.setClear( 1, 1, 1, 1 );
  66. }
  67. _state.buffers.depth.setTest( true );
  68. _state.setScissorTest( false );
  69. // check for shadow map type changes
  70. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  71. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  72. // render depth map
  73. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  74. const light = lights[ i ];
  75. const shadow = light.shadow;
  76. if ( shadow === undefined ) {
  77. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  78. continue;
  79. }
  80. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  81. _shadowMapSize.copy( shadow.mapSize );
  82. const shadowFrameExtents = shadow.getFrameExtents();
  83. _shadowMapSize.multiply( shadowFrameExtents );
  84. _viewportSize.copy( shadow.mapSize );
  85. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  86. if ( _shadowMapSize.x > _maxTextureSize ) {
  87. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  88. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  89. shadow.mapSize.x = _viewportSize.x;
  90. }
  91. if ( _shadowMapSize.y > _maxTextureSize ) {
  92. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  93. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  94. shadow.mapSize.y = _viewportSize.y;
  95. }
  96. }
  97. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  98. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  99. if ( shadow.map !== null ) {
  100. shadow.map.dispose();
  101. }
  102. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  103. shadow.map.texture.name = light.name + '.shadowMap';
  104. shadow.camera.updateProjectionMatrix();
  105. }
  106. renderer.setRenderTarget( shadow.map );
  107. renderer.clear();
  108. const viewportCount = shadow.getViewportCount();
  109. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  110. const viewport = shadow.getViewport( vp );
  111. _viewport.set(
  112. _viewportSize.x * viewport.x,
  113. _viewportSize.y * viewport.y,
  114. _viewportSize.x * viewport.z,
  115. _viewportSize.y * viewport.w
  116. );
  117. _state.viewport( _viewport );
  118. shadow.updateMatrices( light, vp );
  119. _frustum = shadow.getFrustum();
  120. renderObject( scene, camera, shadow.camera, light, this.type );
  121. }
  122. // do blur pass for VSM
  123. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  124. VSMPass( shadow, camera );
  125. }
  126. shadow.needsUpdate = false;
  127. }
  128. _previousType = this.type;
  129. scope.needsUpdate = false;
  130. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  131. };
  132. function VSMPass( shadow, camera ) {
  133. const geometry = objects.update( fullScreenMesh );
  134. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  135. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  136. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  137. shadowMaterialVertical.needsUpdate = true;
  138. shadowMaterialHorizontal.needsUpdate = true;
  139. }
  140. if ( shadow.mapPass === null ) {
  141. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  142. }
  143. // vertical pass
  144. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  145. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  146. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  147. renderer.setRenderTarget( shadow.mapPass );
  148. renderer.clear();
  149. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  150. // horizontal pass
  151. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  152. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  153. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  154. renderer.setRenderTarget( shadow.map );
  155. renderer.clear();
  156. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  157. }
  158. function getDepthMaterial( object, material, light, type ) {
  159. let result = null;
  160. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  161. if ( customMaterial !== undefined ) {
  162. result = customMaterial;
  163. } else {
  164. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  165. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  166. ( material.displacementMap && material.displacementScale !== 0 ) ||
  167. ( material.alphaMap && material.alphaTest > 0 ) ||
  168. ( material.map && material.alphaTest > 0 ) ||
  169. ( material.alphaToCoverage === true ) ) {
  170. // in this case we need a unique material instance reflecting the
  171. // appropriate state
  172. const keyA = result.uuid, keyB = material.uuid;
  173. let materialsForVariant = _materialCache[ keyA ];
  174. if ( materialsForVariant === undefined ) {
  175. materialsForVariant = {};
  176. _materialCache[ keyA ] = materialsForVariant;
  177. }
  178. let cachedMaterial = materialsForVariant[ keyB ];
  179. if ( cachedMaterial === undefined ) {
  180. cachedMaterial = result.clone();
  181. materialsForVariant[ keyB ] = cachedMaterial;
  182. material.addEventListener( 'dispose', onMaterialDispose );
  183. }
  184. result = cachedMaterial;
  185. }
  186. }
  187. result.visible = material.visible;
  188. result.wireframe = material.wireframe;
  189. if ( type === VSMShadowMap ) {
  190. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  191. } else {
  192. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  193. }
  194. result.alphaMap = material.alphaMap;
  195. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  196. result.map = material.map;
  197. result.clipShadows = material.clipShadows;
  198. result.clippingPlanes = material.clippingPlanes;
  199. result.clipIntersection = material.clipIntersection;
  200. result.displacementMap = material.displacementMap;
  201. result.displacementScale = material.displacementScale;
  202. result.displacementBias = material.displacementBias;
  203. result.wireframeLinewidth = material.wireframeLinewidth;
  204. result.linewidth = material.linewidth;
  205. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  206. const materialProperties = renderer.properties.get( result );
  207. materialProperties.light = light;
  208. }
  209. return result;
  210. }
  211. function renderObject( object, camera, shadowCamera, light, type ) {
  212. if ( object.visible === false ) return;
  213. const visible = object.layers.test( camera.layers );
  214. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  215. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  216. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  217. const geometry = objects.update( object );
  218. const material = object.material;
  219. if ( Array.isArray( material ) ) {
  220. const groups = geometry.groups;
  221. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  222. const group = groups[ k ];
  223. const groupMaterial = material[ group.materialIndex ];
  224. if ( groupMaterial && groupMaterial.visible ) {
  225. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  226. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  227. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  228. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  229. }
  230. }
  231. } else if ( material.visible ) {
  232. const depthMaterial = getDepthMaterial( object, material, light, type );
  233. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  234. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  235. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  236. }
  237. }
  238. }
  239. const children = object.children;
  240. for ( let i = 0, l = children.length; i < l; i ++ ) {
  241. renderObject( children[ i ], camera, shadowCamera, light, type );
  242. }
  243. }
  244. function onMaterialDispose( event ) {
  245. const material = event.target;
  246. material.removeEventListener( 'dispose', onMaterialDispose );
  247. // make sure to remove the unique distance/depth materials used for shadow map rendering
  248. for ( const id in _materialCache ) {
  249. const cache = _materialCache[ id ];
  250. const uuid = event.target.uuid;
  251. if ( uuid in cache ) {
  252. const shadowMaterial = cache[ uuid ];
  253. shadowMaterial.dispose();
  254. delete cache[ uuid ];
  255. }
  256. }
  257. }
  258. }
  259. export { WebGLShadowMap };
粤ICP备19079148号