WebGLShadowMap.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /**
  2. * @author alteredq / http://alteredqualia.com/
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. import { FrontSide, BackSide, DoubleSide, RGBAFormat, NearestFilter, PCFShadowMap, RGBADepthPacking } from '../../constants';
  6. import { WebGLRenderTarget } from '../WebGLRenderTarget';
  7. import { ShaderMaterial } from '../../materials/ShaderMaterial';
  8. import { UniformsUtils } from '../shaders/UniformsUtils';
  9. import { ShaderLib } from '../shaders/ShaderLib';
  10. import { MeshDepthMaterial } from '../../materials/MeshDepthMaterial';
  11. import { Vector4 } from '../../math/Vector4';
  12. import { Vector3 } from '../../math/Vector3';
  13. import { Vector2 } from '../../math/Vector2';
  14. import { Matrix4 } from '../../math/Matrix4';
  15. import { Frustum } from '../../math/Frustum';
  16. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  17. var _gl = _renderer.context,
  18. _state = _renderer.state,
  19. _frustum = new Frustum(),
  20. _projScreenMatrix = new Matrix4(),
  21. _lightShadows = _lights.shadows,
  22. _shadowMapSize = new Vector2(),
  23. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  24. _lookTarget = new Vector3(),
  25. _lightPositionWorld = new Vector3(),
  26. _MorphingFlag = 1,
  27. _SkinningFlag = 2,
  28. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  29. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  30. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  31. _materialCache = {};
  32. var cubeDirections = [
  33. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  34. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  35. ];
  36. var cubeUps = [
  37. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  38. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  39. ];
  40. var cube2DViewPorts = [
  41. new Vector4(), new Vector4(), new Vector4(),
  42. new Vector4(), new Vector4(), new Vector4()
  43. ];
  44. // init
  45. var depthMaterialTemplate = new MeshDepthMaterial();
  46. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  47. depthMaterialTemplate.clipping = true;
  48. var distanceShader = ShaderLib[ "distanceRGBA" ];
  49. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  50. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  51. var useMorphing = ( i & _MorphingFlag ) !== 0;
  52. var useSkinning = ( i & _SkinningFlag ) !== 0;
  53. var depthMaterial = depthMaterialTemplate.clone();
  54. depthMaterial.morphTargets = useMorphing;
  55. depthMaterial.skinning = useSkinning;
  56. _depthMaterials[ i ] = depthMaterial;
  57. var distanceMaterial = new ShaderMaterial( {
  58. defines: {
  59. 'USE_SHADOWMAP': ''
  60. },
  61. uniforms: distanceUniforms,
  62. vertexShader: distanceShader.vertexShader,
  63. fragmentShader: distanceShader.fragmentShader,
  64. morphTargets: useMorphing,
  65. skinning: useSkinning,
  66. clipping: true
  67. } );
  68. _distanceMaterials[ i ] = distanceMaterial;
  69. }
  70. //
  71. var scope = this;
  72. this.enabled = false;
  73. this.autoUpdate = true;
  74. this.needsUpdate = false;
  75. this.type = PCFShadowMap;
  76. this.renderReverseSided = true;
  77. this.renderSingleSided = true;
  78. this.render = function ( scene, camera ) {
  79. if ( scope.enabled === false ) return;
  80. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  81. if ( _lightShadows.length === 0 ) return;
  82. // Set GL state for depth map.
  83. _state.disable( _gl.BLEND );
  84. _state.buffers.color.setClear( 1, 1, 1, 1 );
  85. _state.buffers.depth.setTest( true );
  86. _state.setScissorTest( false );
  87. // render depth map
  88. var faceCount, isPointLight;
  89. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  90. var light = _lightShadows[ i ];
  91. var shadow = light.shadow;
  92. if ( shadow === undefined ) {
  93. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  94. continue;
  95. }
  96. var shadowCamera = shadow.camera;
  97. _shadowMapSize.copy( shadow.mapSize );
  98. _shadowMapSize.min( _maxShadowMapSize );
  99. if ( light && light.isPointLight ) {
  100. faceCount = 6;
  101. isPointLight = true;
  102. var vpWidth = _shadowMapSize.x;
  103. var vpHeight = _shadowMapSize.y;
  104. // These viewports map a cube-map onto a 2D texture with the
  105. // following orientation:
  106. //
  107. // xzXZ
  108. // y Y
  109. //
  110. // X - Positive x direction
  111. // x - Negative x direction
  112. // Y - Positive y direction
  113. // y - Negative y direction
  114. // Z - Positive z direction
  115. // z - Negative z direction
  116. // positive X
  117. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  118. // negative X
  119. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  120. // positive Z
  121. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  122. // negative Z
  123. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  124. // positive Y
  125. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  126. // negative Y
  127. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  128. _shadowMapSize.x *= 4.0;
  129. _shadowMapSize.y *= 2.0;
  130. } else {
  131. faceCount = 1;
  132. isPointLight = false;
  133. }
  134. if ( shadow.map === null ) {
  135. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  136. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  137. shadow.map.texture.name = light.name + ".shadowMap";
  138. shadowCamera.updateProjectionMatrix();
  139. }
  140. if ( shadow.isSpotLightShadow ) {
  141. shadow.update( light );
  142. }
  143. var shadowMap = shadow.map;
  144. var shadowMatrix = shadow.matrix;
  145. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  146. shadowCamera.position.copy( _lightPositionWorld );
  147. _renderer.setRenderTarget( shadowMap );
  148. _renderer.clear();
  149. // render shadow map for each cube face (if omni-directional) or
  150. // run a single pass if not
  151. for ( var face = 0; face < faceCount; face ++ ) {
  152. if ( isPointLight ) {
  153. _lookTarget.copy( shadowCamera.position );
  154. _lookTarget.add( cubeDirections[ face ] );
  155. shadowCamera.up.copy( cubeUps[ face ] );
  156. shadowCamera.lookAt( _lookTarget );
  157. var vpDimensions = cube2DViewPorts[ face ];
  158. _state.viewport( vpDimensions );
  159. } else {
  160. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  161. shadowCamera.lookAt( _lookTarget );
  162. }
  163. shadowCamera.updateMatrixWorld();
  164. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  165. // compute shadow matrix
  166. shadowMatrix.set(
  167. 0.5, 0.0, 0.0, 0.5,
  168. 0.0, 0.5, 0.0, 0.5,
  169. 0.0, 0.0, 0.5, 0.5,
  170. 0.0, 0.0, 0.0, 1.0
  171. );
  172. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  173. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  174. // update camera matrices and frustum
  175. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  176. _frustum.setFromMatrix( _projScreenMatrix );
  177. // set object matrices & frustum culling
  178. renderObject( scene, camera, shadowCamera, isPointLight );
  179. }
  180. }
  181. // Restore GL state.
  182. var clearColor = _renderer.getClearColor();
  183. var clearAlpha = _renderer.getClearAlpha();
  184. _renderer.setClearColor( clearColor, clearAlpha );
  185. scope.needsUpdate = false;
  186. };
  187. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  188. var geometry = object.geometry;
  189. var result = null;
  190. var materialVariants = _depthMaterials;
  191. var customMaterial = object.customDepthMaterial;
  192. if ( isPointLight ) {
  193. materialVariants = _distanceMaterials;
  194. customMaterial = object.customDistanceMaterial;
  195. }
  196. if ( ! customMaterial ) {
  197. var useMorphing = false;
  198. if ( material.morphTargets ) {
  199. if ( geometry && geometry.isBufferGeometry ) {
  200. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  201. } else if ( geometry && geometry.isGeometry ) {
  202. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  203. }
  204. }
  205. if ( object.isSkinnedMesh && material.skinning === false ) {
  206. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  207. }
  208. var useSkinning = object.isSkinnedMesh && material.skinning;
  209. var variantIndex = 0;
  210. if ( useMorphing ) variantIndex |= _MorphingFlag;
  211. if ( useSkinning ) variantIndex |= _SkinningFlag;
  212. result = materialVariants[ variantIndex ];
  213. } else {
  214. result = customMaterial;
  215. }
  216. if ( _renderer.localClippingEnabled &&
  217. material.clipShadows === true &&
  218. material.clippingPlanes.length !== 0 ) {
  219. // in this case we need a unique material instance reflecting the
  220. // appropriate state
  221. var keyA = result.uuid, keyB = material.uuid;
  222. var materialsForVariant = _materialCache[ keyA ];
  223. if ( materialsForVariant === undefined ) {
  224. materialsForVariant = {};
  225. _materialCache[ keyA ] = materialsForVariant;
  226. }
  227. var cachedMaterial = materialsForVariant[ keyB ];
  228. if ( cachedMaterial === undefined ) {
  229. cachedMaterial = result.clone();
  230. materialsForVariant[ keyB ] = cachedMaterial;
  231. }
  232. result = cachedMaterial;
  233. }
  234. result.visible = material.visible;
  235. result.wireframe = material.wireframe;
  236. var side = material.side;
  237. if ( scope.renderSingleSided && side == DoubleSide ) {
  238. side = FrontSide;
  239. }
  240. if ( scope.renderReverseSided ) {
  241. if ( side === FrontSide ) side = BackSide;
  242. else if ( side === BackSide ) side = FrontSide;
  243. }
  244. result.side = side;
  245. result.clipShadows = material.clipShadows;
  246. result.clippingPlanes = material.clippingPlanes;
  247. result.wireframeLinewidth = material.wireframeLinewidth;
  248. result.linewidth = material.linewidth;
  249. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  250. result.uniforms.lightPos.value.copy( lightPositionWorld );
  251. }
  252. return result;
  253. }
  254. function renderObject( object, camera, shadowCamera, isPointLight ) {
  255. if ( object.visible === false ) return;
  256. var visible = object.layers.test( camera.layers );
  257. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  258. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  259. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  260. var geometry = _objects.update( object );
  261. var material = object.material;
  262. if ( Array.isArray( material ) ) {
  263. var groups = geometry.groups;
  264. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  265. var group = groups[ k ];
  266. var groupMaterial = material[ group.materialIndex ];
  267. if ( groupMaterial && groupMaterial.visible ) {
  268. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  269. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  270. }
  271. }
  272. } else if ( material.visible ) {
  273. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  274. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  275. }
  276. }
  277. }
  278. var children = object.children;
  279. for ( var i = 0, l = children.length; i < l; i ++ ) {
  280. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  281. }
  282. }
  283. }
  284. export { WebGLShadowMap };