CSM.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /**
  2. * @author vHawk / https://github.com/vHawk/
  3. */
  4. import {
  5. Vector2,
  6. Vector3,
  7. DirectionalLight,
  8. MathUtils,
  9. ShaderChunk,
  10. LineBasicMaterial,
  11. Object3D,
  12. BufferGeometry,
  13. BufferAttribute,
  14. Line,
  15. Matrix4,
  16. Box3
  17. } from '../../../build/three.module.js';
  18. import Frustum from './Frustum.js';
  19. import Shader from './Shader.js';
  20. const _cameraToLightMatrix = new Matrix4();
  21. const _lightSpaceFrustum = new Frustum();
  22. const _frustum = new Frustum();
  23. const _center = new Vector3();
  24. const _bbox = new Box3();
  25. const _uniformArray = [];
  26. const _logArray = [];
  27. export default class CSM {
  28. constructor( data ) {
  29. data = data || {};
  30. this.camera = data.camera;
  31. this.parent = data.parent;
  32. this.cascades = data.cascades || 3;
  33. this.maxFar = data.maxFar || 100000;
  34. this.mode = data.mode || 'practical';
  35. this.shadowMapSize = data.shadowMapSize || 2048;
  36. this.shadowBias = data.shadowBias || 0.000001;
  37. this.lightDirection = data.lightDirection || new Vector3( 1, - 1, 1 ).normalize();
  38. this.lightIntensity = data.lightIntensity || 1;
  39. this.lightNear = data.lightNear || 1;
  40. this.lightFar = data.lightFar || 2000;
  41. this.lightMargin = data.lightMargin || 200;
  42. this.customSplitsCallback = data.customSplitsCallback;
  43. this.fade = false;
  44. this.mainFrustum = new Frustum();
  45. this.frustums = [];
  46. this.breaks = [];
  47. this.lights = [];
  48. this.shaders = new Map();
  49. this.createLights();
  50. this.updateFrustums();
  51. this.injectInclude();
  52. }
  53. createLights() {
  54. for ( let i = 0; i < this.cascades; i ++ ) {
  55. const light = new DirectionalLight( 0xffffff, this.lightIntensity );
  56. light.castShadow = true;
  57. light.shadow.mapSize.width = this.shadowMapSize;
  58. light.shadow.mapSize.height = this.shadowMapSize;
  59. light.shadow.camera.near = this.lightNear;
  60. light.shadow.camera.far = this.lightFar;
  61. light.shadow.bias = this.shadowBias;
  62. this.parent.add( light );
  63. this.parent.add( light.target );
  64. this.lights.push( light );
  65. }
  66. }
  67. initCascades() {
  68. const camera = this.camera;
  69. camera.updateProjectionMatrix();
  70. this.mainFrustum.setFromProjectionMatrix( camera.projectionMatrix, this.maxFar );
  71. this.mainFrustum.split( this.breaks, this.frustums );
  72. }
  73. updateShadowBounds() {
  74. const frustums = this.frustums;
  75. for ( let i = 0; i < frustums.length; i ++ ) {
  76. const light = this.lights[ i ];
  77. const shadowCam = light.shadow.camera;
  78. const frustum = this.frustums[ i ];
  79. // Get the two points that represent that furthest points on the frustum assuming
  80. // that's either the diagonal across the far plane or the diagonal across the whole
  81. // frustum itself.
  82. const nearVerts = frustum.vertices.near;
  83. const farVerts = frustum.vertices.far;
  84. const point1 = farVerts[ 0 ];
  85. let point2;
  86. if ( point1.distanceTo( farVerts[ 2 ] ) > point1.distanceTo( nearVerts[ 2 ] ) ) {
  87. point2 = farVerts[ 2 ];
  88. } else {
  89. point2 = nearVerts[ 2 ];
  90. }
  91. let squaredBBWidth = point1.distanceTo( point2 );
  92. if ( this.fade ) {
  93. // expand the shadow extents by the fade margin if fade is enabled.
  94. const camera = this.camera;
  95. const far = Math.max( camera.far, this.maxFar );
  96. const linearDepth = frustum.vertices.far[ 0 ].z / ( far - camera.near );
  97. const margin = 0.25 * Math.pow( linearDepth, 2.0 ) * ( far - camera.near );
  98. squaredBBWidth += margin;
  99. }
  100. shadowCam.left = - squaredBBWidth / 2;
  101. shadowCam.right = squaredBBWidth / 2;
  102. shadowCam.top = squaredBBWidth / 2;
  103. shadowCam.bottom = - squaredBBWidth / 2;
  104. shadowCam.updateProjectionMatrix();
  105. }
  106. }
  107. getBreaks() {
  108. const camera = this.camera;
  109. const far = Math.min( camera.far, this.maxFar );
  110. this.breaks.length = 0;
  111. switch ( this.mode ) {
  112. case 'uniform':
  113. uniformSplit( this.cascades, camera.near, far, this.breaks );
  114. break;
  115. case 'logarithmic':
  116. logarithmicSplit( this.cascades, camera.near, far, this.breaks );
  117. break;
  118. case 'practical':
  119. practicalSplit( this.cascades, camera.near, far, 0.5, this.breaks );
  120. break;
  121. case 'custom':
  122. if ( this.customSplitsCallback === undefined ) console.error( 'CSM: Custom split scheme callback not defined.' );
  123. this.customSplitsCallback( this.cascades, camera.near, far, this.breaks );
  124. break;
  125. }
  126. function uniformSplit( amount, near, far, target ) {
  127. for ( let i = 1; i < amount; i ++ ) {
  128. target.push( ( near + ( far - near ) * i / amount ) / far );
  129. }
  130. target.push( 1 );
  131. }
  132. function logarithmicSplit( amount, near, far, target ) {
  133. for ( let i = 1; i < amount; i ++ ) {
  134. target.push( ( near * ( far / near ) ** ( i / amount ) ) / far );
  135. }
  136. target.push( 1 );
  137. }
  138. function practicalSplit( amount, near, far, lambda, target ) {
  139. _uniformArray.length = 0;
  140. _logArray.length = 0;
  141. logarithmicSplit( amount, near, far, _logArray );
  142. uniformSplit( amount, near, far, _uniformArray );
  143. for ( let i = 1; i < amount; i ++ ) {
  144. target.push( MathUtils.lerp( _uniformArray[ i - 1 ], _logArray[ i - 1 ], lambda ) );
  145. }
  146. target.push( 1 );
  147. }
  148. }
  149. update() {
  150. const camera = this.camera;
  151. const frustums = this.frustums;
  152. for ( let i = 0; i < frustums.length; i ++ ) {
  153. const light = this.lights[ i ];
  154. const shadowCam = light.shadow.camera;
  155. const texelWidth = ( shadowCam.right - shadowCam.left ) / this.shadowMapSize;
  156. const texelHeight = ( shadowCam.top - shadowCam.bottom ) / this.shadowMapSize;
  157. light.shadow.camera.updateMatrixWorld( true );
  158. _cameraToLightMatrix.multiplyMatrices( light.shadow.camera.matrixWorldInverse, camera.matrixWorld );
  159. frustums[ i ].toSpace( _cameraToLightMatrix, _lightSpaceFrustum );
  160. const nearVerts = _lightSpaceFrustum.vertices.near;
  161. const farVerts = _lightSpaceFrustum.vertices.far;
  162. _bbox.makeEmpty();
  163. for ( let j = 0; j < 4; j ++ ) {
  164. _bbox.expandByPoint( nearVerts[ j ] );
  165. _bbox.expandByPoint( farVerts[ j ] );
  166. }
  167. _bbox.getCenter( _center );
  168. _center.z = _bbox.max.z + this.lightMargin;
  169. _center.x = Math.floor( _center.x / texelWidth ) * texelWidth;
  170. _center.y = Math.floor( _center.y / texelHeight ) * texelHeight;
  171. _center.applyMatrix4( light.shadow.camera.matrixWorld );
  172. light.position.copy( _center );
  173. light.target.position.copy( _center );
  174. light.target.position.x += this.lightDirection.x;
  175. light.target.position.y += this.lightDirection.y;
  176. light.target.position.z += this.lightDirection.z;
  177. light.shadow.camera.updateMatrixWorld();
  178. light.shadow.camera.updateProjectionMatrix();
  179. }
  180. }
  181. injectInclude() {
  182. ShaderChunk.lights_fragment_begin = Shader.lights_fragment_begin;
  183. ShaderChunk.lights_pars_begin = Shader.lights_pars_begin;
  184. }
  185. setupMaterial( material ) {
  186. material.defines = material.defines || {};
  187. material.defines.USE_CSM = 1;
  188. material.defines.CSM_CASCADES = this.cascades;
  189. if ( this.fade ) {
  190. material.defines.CSM_FADE = '';
  191. }
  192. const breaksVec2 = [];
  193. const self = this;
  194. const shaders = this.shaders;
  195. material.onBeforeCompile = function ( shader ) {
  196. const far = Math.min( self.camera.far, self.maxFar );
  197. self.getExtendedBreaks( breaksVec2 );
  198. shader.uniforms.CSM_cascades = { value: breaksVec2 };
  199. shader.uniforms.cameraNear = { value: self.camera.near };
  200. shader.uniforms.shadowFar = { value: far };
  201. shaders.set( material, shader );
  202. };
  203. shaders.set( material, null );
  204. }
  205. updateUniforms() {
  206. const far = Math.min( this.camera.far, this.maxFar );
  207. const shaders = this.shaders;
  208. shaders.forEach( function ( shader, material ) {
  209. if ( shader !== null ) {
  210. const uniforms = shader.uniforms;
  211. this.getExtendedBreaks( uniforms.CSM_cascades.value );
  212. uniforms.cameraNear.value = this.camera.near;
  213. uniforms.shadowFar.value = far;
  214. }
  215. if ( ! this.fade && 'CSM_FADE' in material.defines ) {
  216. delete material.defines.CSM_FADE;
  217. material.needsUpdate = true;
  218. } else if ( this.fade && ! ( 'CSM_FADE' in material.defines ) ) {
  219. material.defines.CSM_FADE = '';
  220. material.needsUpdate = true;
  221. }
  222. }, this );
  223. }
  224. getExtendedBreaks( target ) {
  225. while ( target.length < this.breaks.length ) {
  226. target.push( new Vector2() );
  227. }
  228. target.length = this.breaks.length;
  229. for ( let i = 0; i < this.cascades; i ++ ) {
  230. let amount = this.breaks[ i ];
  231. let prev = this.breaks[ i - 1 ] || 0;
  232. target[ i ].x = prev;
  233. target[ i ].y = amount;
  234. }
  235. }
  236. updateFrustums() {
  237. this.getBreaks();
  238. this.initCascades();
  239. this.updateShadowBounds();
  240. this.updateUniforms();
  241. }
  242. helper( cameraMatrix ) {
  243. let geometry, vertices;
  244. const material = new LineBasicMaterial( { color: 0xffffff } );
  245. const object = new Object3D();
  246. for ( let i = 0; i < this.frustums.length; i ++ ) {
  247. this.frustums[ i ].toSpace( cameraMatrix, _frustum );
  248. geometry = new BufferGeometry();
  249. vertices = [];
  250. for ( let i = 0; i < 5; i ++ ) {
  251. const point = _frustum.vertices.near[ i === 4 ? 0 : i ];
  252. vertices.push( point.x, point.y, point.z );
  253. }
  254. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  255. object.add( new Line( geometry, material ) );
  256. geometry = new BufferGeometry();
  257. vertices = [];
  258. for ( let i = 0; i < 5; i ++ ) {
  259. const point = _frustum.vertices.far[ i === 4 ? 0 : i ];
  260. vertices.push( point.x, point.y, point.z );
  261. }
  262. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  263. object.add( new Line( geometry, material ) );
  264. for ( let i = 0; i < 4; i ++ ) {
  265. geometry = new BufferGeometry();
  266. vertices = [];
  267. const near = _frustum.vertices.near[ i ];
  268. const far = _frustum.vertices.far[ i ];
  269. vertices.push( near.x, near.y, near.z );
  270. vertices.push( far.x, far.y, far.z );
  271. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  272. object.add( new Line( geometry, material ) );
  273. }
  274. }
  275. return object;
  276. }
  277. remove() {
  278. for ( let i = 0; i < this.lights.length; i ++ ) {
  279. this.parent.remove( this.lights[ i ] );
  280. }
  281. }
  282. dispose() {
  283. const shaders = this.shaders;
  284. shaders.forEach( function ( shader, material ) {
  285. delete material.onBeforeCompile;
  286. delete material.defines.USE_CSM;
  287. delete material.defines.CSM_CASCADES;
  288. delete material.defines.CSM_FADE;
  289. delete shader.uniforms.CSM_cascades;
  290. delete shader.uniforms.cameraNear;
  291. delete shader.uniforms.shadowFar;
  292. material.needsUpdate = true;
  293. } );
  294. shaders.clear();
  295. }
  296. }