CSM.js 9.8 KB

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