CSM.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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.mainFrustum = new Frustum();
  45. this.frustums = [];
  46. this.breaks = [];
  47. this.lights = [];
  48. this.materials = [];
  49. this.createLights();
  50. this.getBreaks();
  51. this.initCascades();
  52. this.injectInclude();
  53. }
  54. createLights() {
  55. for ( let i = 0; i < this.cascades; i ++ ) {
  56. const light = new DirectionalLight( 0xffffff, this.lightIntensity );
  57. light.castShadow = true;
  58. light.shadow.mapSize.width = this.shadowMapSize;
  59. light.shadow.mapSize.height = this.shadowMapSize;
  60. light.shadow.camera.near = this.lightNear;
  61. light.shadow.camera.far = this.lightFar;
  62. light.shadow.bias = this.shadowBias;
  63. this.parent.add( light );
  64. this.parent.add( light.target );
  65. this.lights.push( light );
  66. }
  67. }
  68. initCascades() {
  69. const camera = this.camera;
  70. camera.updateProjectionMatrix();
  71. this.mainFrustum.setFromProjectionMatrix( camera.projectionMatrix, this.maxFar );
  72. this.mainFrustum.split( this.breaks, this.frustums );
  73. }
  74. getBreaks() {
  75. const camera = this.camera;
  76. const far = Math.min(camera.far, this.maxFar);
  77. this.breaks.length = 0;
  78. switch ( this.mode ) {
  79. case 'uniform':
  80. uniformSplit( this.cascades, camera.near, far, this.breaks );
  81. break;
  82. case 'logarithmic':
  83. logarithmicSplit( this.cascades, camera.near, far, this.breaks );
  84. break;
  85. case 'practical':
  86. practicalSplit( this.cascades, camera.near, far, 0.5, this.breaks );
  87. break;
  88. case 'custom':
  89. if ( this.customSplitsCallback === undefined ) console.error( 'CSM: Custom split scheme callback not defined.' );
  90. this.customSplitsCallback( this.cascades, camera.near, far, this.breaks );
  91. break;
  92. }
  93. function uniformSplit( amount, near, far, target ) {
  94. for ( let i = 1; i < amount; i ++ ) {
  95. target.push( ( near + ( far - near ) * i / amount ) / far );
  96. }
  97. target.push( 1 );
  98. }
  99. function logarithmicSplit( amount, near, far, target ) {
  100. for ( let i = 1; i < amount; i ++ ) {
  101. target.push( ( near * ( far / near ) ** ( i / amount ) ) / far );
  102. }
  103. target.push( 1 );
  104. }
  105. function practicalSplit( amount, near, far, lambda, target ) {
  106. _uniformArray.length = 0;
  107. _logArray.length = 0;
  108. const log = logarithmicSplit( amount, near, far, _logArray );
  109. const uni = uniformSplit( amount, near, far, _uniformArray );
  110. for ( let i = 1; i < amount; i ++ ) {
  111. target.push( MathUtils.lerp( _uniformArray[ i - 1 ], _logArray[ i - 1 ], lambda ) );
  112. }
  113. target.push( 1 );
  114. }
  115. }
  116. update( cameraMatrix ) {
  117. for ( let i = 0; i < this.frustums.length; i ++ ) {
  118. const light = this.lights[ i ];
  119. light.shadow.camera.updateMatrixWorld( true );
  120. _cameraToLightMatrix.multiplyMatrices( light.shadow.camera.matrixWorldInverse, cameraMatrix );
  121. this.frustums[ i ].toSpace( _cameraToLightMatrix, _lightSpaceFrustum );
  122. _bbox.makeEmpty();
  123. for ( let j = 0; j < 4; j ++ ) {
  124. _bbox.expandByPoint( _lightSpaceFrustum.vertices.near[ j ] );
  125. _bbox.expandByPoint( _lightSpaceFrustum.vertices.far[ j ] );
  126. }
  127. _bbox.getSize( _size );
  128. _bbox.getCenter( _center );
  129. _center.z = _bbox.max.z + this.lightMargin;
  130. _center.applyMatrix4( light.shadow.camera.matrixWorld );
  131. const squaredBBWidth = Math.max( _size.x, _size.y );
  132. light.shadow.camera.left = - squaredBBWidth / 2;
  133. light.shadow.camera.right = squaredBBWidth / 2;
  134. light.shadow.camera.top = squaredBBWidth / 2;
  135. light.shadow.camera.bottom = - squaredBBWidth / 2;
  136. light.position.copy( _center );
  137. light.target.position.copy( _center );
  138. light.target.position.x += this.lightDirection.x;
  139. light.target.position.y += this.lightDirection.y;
  140. light.target.position.z += this.lightDirection.z;
  141. light.shadow.camera.updateProjectionMatrix();
  142. light.shadow.camera.updateMatrixWorld();
  143. }
  144. }
  145. injectInclude() {
  146. ShaderChunk.lights_fragment_begin = Shader.lights_fragment_begin;
  147. ShaderChunk.lights_pars_begin = Shader.lights_pars_begin;
  148. }
  149. setupMaterial( material ) {
  150. material.defines = material.defines || {};
  151. material.defines.USE_CSM = 1;
  152. material.defines.CSM_CASCADES = this.cascades;
  153. const breaksVec2 = [];
  154. this.getExtendedBreaks( breaksVec2 );
  155. const self = this;
  156. const far = Math.min(this.camera.far, this.maxFar);
  157. material.onBeforeCompile = function ( shader ) {
  158. shader.uniforms.CSM_cascades = { value: breaksVec2 };
  159. shader.uniforms.cameraNear = { value: self.camera.near };
  160. shader.uniforms.shadowFar = { value: far };
  161. self.materials.push( shader );
  162. };
  163. }
  164. updateUniforms() {
  165. const far = Math.min(this.camera.far, this.maxFar);
  166. for ( let i = 0; i < this.materials.length; i ++ ) {
  167. const uniforms = this.materials[ i ].uniforms;
  168. this.getExtendedBreaks( uniforms.CSM_cascades.value );
  169. uniforms.cameraNear.value = this.camera.near;
  170. uniforms.shadowFar.value = far;
  171. }
  172. }
  173. getExtendedBreaks( target ) {
  174. while ( target.length < this.breaks.length ) {
  175. target.push( new Vector2() );
  176. }
  177. target.length = this.breaks.length;
  178. for ( let i = 0; i < this.cascades; i ++ ) {
  179. let amount = this.breaks[ i ];
  180. let prev = this.breaks[ i - 1 ] || 0;
  181. target[ i ].x = prev;
  182. target[ i ].y = amount;
  183. }
  184. }
  185. updateFrustums() {
  186. this.getBreaks();
  187. this.initCascades();
  188. this.updateUniforms();
  189. }
  190. helper( cameraMatrix ) {
  191. let geometry, vertices;
  192. const material = new LineBasicMaterial( { color: 0xffffff } );
  193. const object = new Object3D();
  194. for ( let i = 0; i < this.frustums.length; i ++ ) {
  195. this.frustums[ i ].toSpace( cameraMatrix, _frustum );
  196. geometry = new BufferGeometry();
  197. vertices = [];
  198. for ( let i = 0; i < 5; i ++ ) {
  199. const point = _frustum.vertices.near[ i === 4 ? 0 : i ];
  200. vertices.push( point.x, point.y, point.z );
  201. }
  202. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  203. object.add( new Line( geometry, material ) );
  204. geometry = new BufferGeometry();
  205. vertices = [];
  206. for ( let i = 0; i < 5; i ++ ) {
  207. const point = _frustum.vertices.far[ i === 4 ? 0 : i ];
  208. vertices.push( point.x, point.y, point.z );
  209. }
  210. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  211. object.add( new Line( geometry, material ) );
  212. for ( let i = 0; i < 4; i ++ ) {
  213. geometry = new BufferGeometry();
  214. vertices = [];
  215. const near = _frustum.vertices.near[ i ];
  216. const far = _frustum.vertices.far[ i ];
  217. vertices.push( near.x, near.y, near.z );
  218. vertices.push( far.x, far.y, far.z );
  219. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( vertices ), 3 ) );
  220. object.add( new Line( geometry, material ) );
  221. }
  222. }
  223. return object;
  224. }
  225. remove() {
  226. for ( let i = 0; i < this.lights.length; i ++ ) {
  227. this.parent.remove( this.lights[ i ] );
  228. }
  229. }
  230. }