2
0

CSM.js 9.1 KB

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