CSM.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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. }
  178. }
  179. injectInclude() {
  180. ShaderChunk.lights_fragment_begin = Shader.lights_fragment_begin;
  181. ShaderChunk.lights_pars_begin = Shader.lights_pars_begin;
  182. }
  183. setupMaterial( material ) {
  184. material.defines = material.defines || {};
  185. material.defines.USE_CSM = 1;
  186. material.defines.CSM_CASCADES = this.cascades;
  187. if ( this.fade ) {
  188. material.defines.CSM_FADE = '';
  189. }
  190. const breaksVec2 = [];
  191. const self = this;
  192. const shaders = this.shaders;
  193. material.onBeforeCompile = function ( shader ) {
  194. const far = Math.min( self.camera.far, self.maxFar );
  195. self.getExtendedBreaks( breaksVec2 );
  196. shader.uniforms.CSM_cascades = { value: breaksVec2 };
  197. shader.uniforms.cameraNear = { value: self.camera.near };
  198. shader.uniforms.shadowFar = { value: far };
  199. shaders.set( material, shader );
  200. };
  201. shaders.set( material, null );
  202. }
  203. updateUniforms() {
  204. const far = Math.min( this.camera.far, this.maxFar );
  205. const shaders = this.shaders;
  206. shaders.forEach( function ( shader, material ) {
  207. if ( shader !== null ) {
  208. const uniforms = shader.uniforms;
  209. this.getExtendedBreaks( uniforms.CSM_cascades.value );
  210. uniforms.cameraNear.value = this.camera.near;
  211. uniforms.shadowFar.value = far;
  212. }
  213. if ( ! this.fade && 'CSM_FADE' in material.defines ) {
  214. delete material.defines.CSM_FADE;
  215. material.needsUpdate = true;
  216. } else if ( this.fade && ! ( 'CSM_FADE' in material.defines ) ) {
  217. material.defines.CSM_FADE = '';
  218. material.needsUpdate = true;
  219. }
  220. }, this );
  221. }
  222. getExtendedBreaks( target ) {
  223. while ( target.length < this.breaks.length ) {
  224. target.push( new Vector2() );
  225. }
  226. target.length = this.breaks.length;
  227. for ( let i = 0; i < this.cascades; i ++ ) {
  228. let amount = this.breaks[ i ];
  229. let prev = this.breaks[ i - 1 ] || 0;
  230. target[ i ].x = prev;
  231. target[ i ].y = amount;
  232. }
  233. }
  234. updateFrustums() {
  235. this.getBreaks();
  236. this.initCascades();
  237. this.updateShadowBounds();
  238. this.updateUniforms();
  239. }
  240. helper( cameraMatrix ) {
  241. let geometry, vertices;
  242. const material = new LineBasicMaterial( { color: 0xffffff } );
  243. const object = new Object3D();
  244. for ( let i = 0; i < this.frustums.length; i ++ ) {
  245. this.frustums[ i ].toSpace( cameraMatrix, _frustum );
  246. geometry = new BufferGeometry();
  247. vertices = [];
  248. for ( let i = 0; i < 5; i ++ ) {
  249. const point = _frustum.vertices.near[ i === 4 ? 0 : i ];
  250. vertices.push( point.x, point.y, point.z );
  251. }
  252. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  253. object.add( new Line( geometry, material ) );
  254. geometry = new BufferGeometry();
  255. vertices = [];
  256. for ( let i = 0; i < 5; i ++ ) {
  257. const point = _frustum.vertices.far[ i === 4 ? 0 : i ];
  258. vertices.push( point.x, point.y, point.z );
  259. }
  260. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  261. object.add( new Line( geometry, material ) );
  262. for ( let i = 0; i < 4; i ++ ) {
  263. geometry = new BufferGeometry();
  264. vertices = [];
  265. const near = _frustum.vertices.near[ i ];
  266. const far = _frustum.vertices.far[ i ];
  267. vertices.push( near.x, near.y, near.z );
  268. vertices.push( far.x, far.y, far.z );
  269. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  270. object.add( new Line( geometry, material ) );
  271. }
  272. }
  273. return object;
  274. }
  275. remove() {
  276. for ( let i = 0; i < this.lights.length; i ++ ) {
  277. this.parent.remove( this.lights[ i ] );
  278. }
  279. }
  280. dispose() {
  281. const shaders = this.shaders;
  282. shaders.forEach( function ( shader, material ) {
  283. delete material.onBeforeCompile;
  284. delete material.defines.USE_CSM;
  285. delete material.defines.CSM_CASCADES;
  286. delete material.defines.CSM_FADE;
  287. delete shader.uniforms.CSM_cascades;
  288. delete shader.uniforms.cameraNear;
  289. delete shader.uniforms.shadowFar;
  290. material.needsUpdate = true;
  291. } );
  292. shaders.clear();
  293. }
  294. }