cascadedShadowGenerator.ts 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. import { Nullable } from "../../types";
  2. import { Scene } from "../../scene";
  3. import { Matrix, Vector3 } from "../../Maths/math.vector";
  4. import { SubMesh } from "../../Meshes/subMesh";
  5. import { IShadowLight } from "../../Lights/shadowLight";
  6. import { Effect } from "../../Materials/effect";
  7. import { RenderTargetTexture } from "../../Materials/Textures/renderTargetTexture";
  8. import { Constants } from "../../Engines/constants";
  9. import "../../Shaders/shadowMap.fragment";
  10. import "../../Shaders/shadowMap.vertex";
  11. import "../../Shaders/depthBoxBlur.fragment";
  12. import { Observer } from '../../Misc/observable';
  13. import { _DevTools } from '../../Misc/devTools';
  14. import { ShadowGenerator } from './shadowGenerator';
  15. import { DirectionalLight } from '../directionalLight';
  16. import { BoundingInfo } from '../../Culling/boundingInfo';
  17. import { DepthRenderer } from '../../Rendering/depthRenderer';
  18. import { DepthReducer } from '../../Misc/depthReducer';
  19. import { Logger } from "../../Misc/logger";
  20. import { EngineStore } from '../../Engines/engineStore';
  21. interface ICascade {
  22. prevBreakDistance: number;
  23. breakDistance: number;
  24. }
  25. const UpDir = Vector3.Up();
  26. const ZeroVec = Vector3.Zero();
  27. let tmpv1 = new Vector3(),
  28. tmpv2 = new Vector3(),
  29. matrix = new Matrix();
  30. /**
  31. * A CSM implementation allowing casting shadows on large scenes.
  32. * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows
  33. * Based on: https://github.com/TheRealMJP/Shadows and https://johanmedestrom.wordpress.com/2016/03/18/opengl-cascaded-shadow-maps/
  34. */
  35. export class CascadedShadowGenerator extends ShadowGenerator {
  36. private static readonly frustumCornersNDCSpace = [
  37. new Vector3(-1.0, +1.0, -1.0),
  38. new Vector3(+1.0, +1.0, -1.0),
  39. new Vector3(+1.0, -1.0, -1.0),
  40. new Vector3(-1.0, -1.0, -1.0),
  41. new Vector3(-1.0, +1.0, +1.0),
  42. new Vector3(+1.0, +1.0, +1.0),
  43. new Vector3(+1.0, -1.0, +1.0),
  44. new Vector3(-1.0, -1.0, +1.0),
  45. ];
  46. /**
  47. * Name of the CSM class
  48. */
  49. public static CLASSNAME = "CascadedShadowGenerator";
  50. /**
  51. * Defines the default number of cascades used by the CSM.
  52. */
  53. public static readonly DEFAULT_CASCADES_COUNT = 4;
  54. /**
  55. * Defines the minimum number of cascades used by the CSM.
  56. */
  57. public static readonly MIN_CASCADES_COUNT = 2;
  58. /**
  59. * Defines the maximum number of cascades used by the CSM.
  60. */
  61. public static readonly MAX_CASCADES_COUNT = 4;
  62. protected _validateFilter(filter: number): number {
  63. if (filter === ShadowGenerator.FILTER_NONE ||
  64. filter === ShadowGenerator.FILTER_PCF ||
  65. filter === ShadowGenerator.FILTER_PCSS)
  66. {
  67. return filter;
  68. }
  69. console.error('Unsupported filter "' + filter + '"!');
  70. return ShadowGenerator.FILTER_NONE;
  71. }
  72. /**
  73. * Gets or sets the actual darkness of the soft shadows while using PCSS filtering (value between 0. and 1.)
  74. */
  75. public penumbraDarkness: number;
  76. private _numCascades: number;
  77. /**
  78. * Gets or set the number of cascades used by the CSM.
  79. */
  80. public get numCascades(): number {
  81. return this._numCascades;
  82. }
  83. public set numCascades(value: number) {
  84. value = Math.min(Math.max(value, CascadedShadowGenerator.MIN_CASCADES_COUNT), CascadedShadowGenerator.MAX_CASCADES_COUNT);
  85. if (value === this._numCascades) {
  86. return;
  87. }
  88. this._numCascades = value;
  89. this.recreateShadowMap();
  90. }
  91. /**
  92. * Sets this to true if you want that the edges of the shadows don't "swimm" / "shimmer" when rotating the camera.
  93. * The trade off is that you loose some precision in the shadow rendering when enabling this setting.
  94. */
  95. public stabilizeCascades: boolean;
  96. private _freezeShadowCastersBoundingInfo: boolean;
  97. private _freezeShadowCastersBoundingInfoObservable: Nullable<Observer<Scene>>;
  98. /**
  99. * Enables or disables the shadow casters bounding info computation.
  100. * If your shadow casters don't move, you can disable this feature.
  101. * If it is enabled, the bounding box computation is done every frame.
  102. */
  103. public get freezeShadowCastersBoundingInfo(): boolean {
  104. return this._freezeShadowCastersBoundingInfo;
  105. }
  106. public set freezeShadowCastersBoundingInfo(freeze: boolean) {
  107. if (this._freezeShadowCastersBoundingInfoObservable && freeze) {
  108. this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);
  109. this._freezeShadowCastersBoundingInfoObservable = null;
  110. }
  111. if (!this._freezeShadowCastersBoundingInfoObservable && !freeze) {
  112. this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this));
  113. }
  114. this._freezeShadowCastersBoundingInfo = freeze;
  115. if (freeze) {
  116. this._computeShadowCastersBoundingInfo();
  117. }
  118. }
  119. private _scbiMin: Vector3;
  120. private _scbiMax: Vector3;
  121. protected _computeShadowCastersBoundingInfo(): void {
  122. this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  123. this._scbiMax.copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);
  124. if (this._shadowMap && this._shadowMap.renderList) {
  125. const renderList = this._shadowMap.renderList;
  126. for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  127. const mesh = renderList[meshIndex];
  128. if (!mesh) {
  129. continue;
  130. }
  131. const boundingInfo = mesh.getBoundingInfo(),
  132. boundingBox = boundingInfo.boundingBox;
  133. this._scbiMin.minimizeInPlace(boundingBox.minimumWorld);
  134. this._scbiMax.maximizeInPlace(boundingBox.maximumWorld);
  135. }
  136. const meshes = this._scene.meshes;
  137. for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  138. const mesh = meshes[meshIndex];
  139. if (!mesh || !mesh.isVisible || !mesh.isEnabled || !mesh.receiveShadows) {
  140. continue;
  141. }
  142. const boundingInfo = mesh.getBoundingInfo(),
  143. boundingBox = boundingInfo.boundingBox;
  144. this._scbiMin.minimizeInPlace(boundingBox.minimumWorld);
  145. this._scbiMax.maximizeInPlace(boundingBox.maximumWorld);
  146. }
  147. }
  148. this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax);
  149. }
  150. protected _shadowCastersBoundingInfo: BoundingInfo;
  151. /**
  152. * Gets or sets the shadow casters bounding info.
  153. * If you provide your own shadow casters bounding info, first enable freezeShadowCastersBoundingInfo
  154. * so that the system won't overwrite the bounds you provide
  155. */
  156. public get shadowCastersBoundingInfo(): BoundingInfo {
  157. return this._shadowCastersBoundingInfo;
  158. }
  159. public set shadowCastersBoundingInfo(boundingInfo: BoundingInfo) {
  160. this._shadowCastersBoundingInfo = boundingInfo;
  161. }
  162. protected _breaksAreDirty: boolean;
  163. protected _minDistance: number;
  164. protected _maxDistance: number;
  165. /**
  166. * Sets the minimal and maximal distances to use when computing the cascade breaks.
  167. *
  168. * The values of min / max are typically the depth zmin and zmax values of your scene, for a given frame.
  169. * If you don't know these values, simply leave them to their defaults and don't call this function.
  170. * @param min minimal distance for the breaks (default to 0.)
  171. * @param max maximal distance for the breaks (default to 1.)
  172. */
  173. public setMinMaxDistance(min: number, max: number): void {
  174. if (this._minDistance === min && this._maxDistance === max) {
  175. return;
  176. }
  177. if (min > max) {
  178. min = 0;
  179. max = 1;
  180. }
  181. if (min < 0) {
  182. min = 0;
  183. }
  184. if (max > 1) {
  185. max = 1;
  186. }
  187. this._minDistance = min;
  188. this._maxDistance = max;
  189. this._breaksAreDirty = true;
  190. }
  191. /** Gets the minimal distance used in the cascade break computation */
  192. public get minDistance(): number {
  193. return this._minDistance;
  194. }
  195. /** Gets the maximal distance used in the cascade break computation */
  196. public get maxDistance(): number {
  197. return this._maxDistance;
  198. }
  199. /**
  200. * Gets the class name of that object
  201. * @returns "CascadedShadowGenerator"
  202. */
  203. public getClassName(): string {
  204. return CascadedShadowGenerator.CLASSNAME;
  205. }
  206. private _cascadeMinExtents: Array<Vector3>;
  207. private _cascadeMaxExtents: Array<Vector3>;
  208. /**
  209. * Gets a cascade minimum extents
  210. * @param cascadeIndex index of the cascade
  211. * @returns the minimum cascade extents
  212. */
  213. public getCascadeMinExtents(cascadeIndex: number): Nullable<Vector3> {
  214. return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMinExtents[cascadeIndex] : null;
  215. }
  216. /**
  217. * Gets a cascade maximum extents
  218. * @param cascadeIndex index of the cascade
  219. * @returns the maximum cascade extents
  220. */
  221. public getCascadeMaxExtents(cascadeIndex: number): Nullable<Vector3> {
  222. return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMaxExtents[cascadeIndex] : null;
  223. }
  224. private _cascades: Array<ICascade>;
  225. private _currentLayer: number;
  226. private _viewSpaceFrustumsZ: Array<number>;
  227. private _viewMatrices: Array<Matrix>;
  228. private _projectionMatrices: Array<Matrix>;
  229. private _transformMatrices: Array<Matrix>;
  230. private _transformMatricesAsArray: Float32Array;
  231. private _frustumLengths: Array<number>;
  232. private _lightSizeUVCorrection: Array<number>;
  233. private _depthCorrection: Array<number>;
  234. private _frustumCornersWorldSpace: Array<Array<Vector3>>;
  235. private _frustumCenter: Array<Vector3>;
  236. private _shadowCameraPos: Array<Vector3>;
  237. private _shadowMaxZ: number;
  238. /**
  239. * Gets the shadow max z distance. It's the limit beyond which shadows are not displayed.
  240. * It defaults to camera.maxZ
  241. */
  242. public get shadowMaxZ(): number {
  243. if (!this._scene || !this._scene.activeCamera) {
  244. return 0;
  245. }
  246. return this._shadowMaxZ;
  247. }
  248. /**
  249. * Sets the shadow max z distance.
  250. */
  251. public set shadowMaxZ(value: number) {
  252. if (!this._scene || !this._scene.activeCamera) {
  253. this._shadowMaxZ = value;
  254. return;
  255. }
  256. if (this._shadowMaxZ === value || value < this._scene.activeCamera.minZ || value > this._scene.activeCamera.maxZ) {
  257. return;
  258. }
  259. this._shadowMaxZ = value;
  260. this._light._markMeshesAsLightDirty();
  261. this._breaksAreDirty = true;
  262. }
  263. protected _debug: boolean;
  264. /**
  265. * Gets or sets the debug flag.
  266. * When enabled, the cascades are materialized by different colors on the screen.
  267. */
  268. public get debug(): boolean {
  269. return this._debug;
  270. }
  271. public set debug(dbg: boolean) {
  272. this._debug = dbg;
  273. this._light._markMeshesAsLightDirty();
  274. }
  275. private _depthClamp: boolean;
  276. /**
  277. * Gets or sets the depth clamping value.
  278. *
  279. * When enabled, it improves the shadow quality because the near z plane of the light frustum don't need to be adjusted
  280. * to account for the shadow casters far away.
  281. *
  282. * Note that this property is incompatible with PCSS filtering, so it won't be used in that case.
  283. */
  284. public get depthClamp(): boolean {
  285. return this._depthClamp;
  286. }
  287. public set depthClamp(value: boolean) {
  288. this._depthClamp = value;
  289. }
  290. private _cascadeBlendPercentage: number;
  291. /**
  292. * Gets or sets the percentage of blending between two cascades (value between 0. and 1.).
  293. * It defaults to 0.1 (10% blending).
  294. */
  295. public get cascadeBlendPercentage(): number {
  296. return this._cascadeBlendPercentage;
  297. }
  298. public set cascadeBlendPercentage(value: number) {
  299. this._cascadeBlendPercentage = value;
  300. this._light._markMeshesAsLightDirty();
  301. }
  302. private _lambda: number;
  303. /**
  304. * Gets or set the lambda parameter.
  305. * This parameter is used to split the camera frustum and create the cascades.
  306. * It's a value between 0. and 1.: If 0, the split is a uniform split of the frustum, if 1 it is a logarithmic split.
  307. * For all values in-between, it's a linear combination of the uniform and logarithm split algorithm.
  308. */
  309. public get lambda(): number {
  310. return this._lambda;
  311. }
  312. public set lambda(value: number) {
  313. const lambda = Math.min(Math.max(value, 0), 1);
  314. if (this._lambda == lambda) {
  315. return;
  316. }
  317. this._lambda = lambda;
  318. this._breaksAreDirty = true;
  319. }
  320. /**
  321. * Gets the view matrix corresponding to a given cascade
  322. * @param cascadeNum cascade to retrieve the view matrix from
  323. * @returns the cascade view matrix
  324. */
  325. public getCascadeViewMatrix(cascadeNum: number): Nullable<Matrix> {
  326. return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._viewMatrices[cascadeNum] : null;
  327. }
  328. /**
  329. * Gets the projection matrix corresponding to a given cascade
  330. * @param cascadeNum cascade to retrieve the projection matrix from
  331. * @returns the cascade projection matrix
  332. */
  333. public getCascadeProjectionMatrix(cascadeNum: number): Nullable<Matrix> {
  334. return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._projectionMatrices[cascadeNum] : null;
  335. }
  336. /**
  337. * Gets the transformation matrix corresponding to a given cascade
  338. * @param cascadeNum cascade to retrieve the transformation matrix from
  339. * @returns the cascade transformation matrix
  340. */
  341. public getCascadeTransformMatrix(cascadeNum: number): Nullable<Matrix> {
  342. return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._transformMatrices[cascadeNum] : null;
  343. }
  344. private _depthRenderer: Nullable<DepthRenderer>;
  345. /**
  346. * Sets the depth renderer to use when autoCalcDepthBounds is enabled.
  347. *
  348. * Note that if no depth renderer is set, a new one will be automatically created internally when necessary.
  349. *
  350. * You should call this function if you already have a depth renderer enabled in your scene, to avoid
  351. * doing multiple depth rendering each frame. If you provide your own depth renderer, make sure it stores linear depth!
  352. * @param depthRenderer The depth renderer to use when autoCalcDepthBounds is enabled. If you pass null or don't call this function at all, a depth renderer will be automatically created
  353. */
  354. public setDepthRenderer(depthRenderer: Nullable<DepthRenderer>): void {
  355. this._depthRenderer = depthRenderer;
  356. if (this._depthReducer) {
  357. this._depthReducer.setDepthRenderer(this._depthRenderer);
  358. }
  359. }
  360. private _depthReducer: Nullable<DepthReducer>;
  361. private _autoCalcDepthBounds: boolean;
  362. /**
  363. * Gets or sets the autoCalcDepthBounds property.
  364. *
  365. * When enabled, a depth rendering pass is first performed (with an internally created depth renderer or with the one
  366. * you provide by calling setDepthRenderer). Then, a min/max reducing is applied on the depth map to compute the
  367. * minimal and maximal depth of the map and those values are used as inputs for the setMinMaxDistance() function.
  368. * It can greatly enhance the shadow quality, at the expense of more GPU works.
  369. * When using this option, you should increase the value of the lambda parameter, and even set it to 1 for best results.
  370. */
  371. public get autoCalcDepthBounds(): boolean {
  372. return this._autoCalcDepthBounds;
  373. }
  374. public set autoCalcDepthBounds(value: boolean) {
  375. const camera = this._scene.activeCamera;
  376. if (!camera) {
  377. return;
  378. }
  379. this._autoCalcDepthBounds = value;
  380. if (!value) {
  381. if (this._depthReducer) {
  382. this._depthReducer.deactivate();
  383. }
  384. this.setMinMaxDistance(0, 1);
  385. return;
  386. }
  387. if (!this._depthReducer) {
  388. this._depthReducer = new DepthReducer(camera);
  389. this._depthReducer.onAfterReductionPerformed.add((minmax: { min: number, max: number}) => {
  390. let min = minmax.min, max = minmax.max;
  391. if (min >= max) {
  392. min = 0;
  393. max = 1;
  394. }
  395. if (min != this._minDistance || max != this._maxDistance) {
  396. this.setMinMaxDistance(min, max);
  397. }
  398. });
  399. this._depthReducer.setDepthRenderer(this._depthRenderer);
  400. }
  401. this._depthReducer.activate();
  402. }
  403. /**
  404. * Defines the refresh rate of the min/max computation used when autoCalcDepthBounds is set to true
  405. * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on...
  406. * Note that if you provided your own depth renderer through a call to setDepthRenderer, you are responsible
  407. * for setting the refresh rate on the renderer yourself!
  408. */
  409. public get autoCalcDepthBoundsRefreshRate(): number {
  410. return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate ?? -1;
  411. }
  412. public set autoCalcDepthBoundsRefreshRate(value: number) {
  413. if (this._depthReducer?.depthRenderer) {
  414. this._depthReducer.depthRenderer.getDepthMap().refreshRate = value;
  415. }
  416. }
  417. /**
  418. * Create the cascade breaks according to the lambda, shadowMaxZ and min/max distance properties, as well as the camera near and far planes.
  419. * This function is automatically called when updating lambda, shadowMaxZ and min/max distances, however you should call it yourself if
  420. * you change the camera near/far planes!
  421. */
  422. public splitFrustum(): void {
  423. this._breaksAreDirty = true;
  424. }
  425. private _splitFrustum(): void {
  426. let camera = this._scene.activeCamera;
  427. if (!camera) {
  428. return;
  429. }
  430. const near = camera.minZ,
  431. far = camera.maxZ,
  432. cameraRange = far - near,
  433. minDistance = this._minDistance,
  434. maxDistance = this._shadowMaxZ < far && this._shadowMaxZ >= near ? Math.min((this._shadowMaxZ - near) / (far - near), this._maxDistance) : this._maxDistance;
  435. const minZ = near + minDistance * cameraRange,
  436. maxZ = near + maxDistance * cameraRange;
  437. const range = maxZ - minZ,
  438. ratio = maxZ / minZ;
  439. for (let cascadeIndex = 0; cascadeIndex < this._cascades.length; ++cascadeIndex) {
  440. const p = (cascadeIndex + 1) / this._numCascades,
  441. log = minZ * (ratio ** p),
  442. uniform = minZ + range * p;
  443. const d = this._lambda * (log - uniform) + uniform;
  444. this._cascades[cascadeIndex].prevBreakDistance = cascadeIndex === 0 ? minDistance : this._cascades[cascadeIndex - 1].breakDistance;
  445. this._cascades[cascadeIndex].breakDistance = (d - near) / cameraRange;
  446. this._viewSpaceFrustumsZ[cascadeIndex] = near + this._cascades[cascadeIndex].breakDistance * cameraRange;
  447. this._frustumLengths[cascadeIndex] = (this._cascades[cascadeIndex].breakDistance - this._cascades[cascadeIndex].prevBreakDistance) * cameraRange;
  448. }
  449. this._breaksAreDirty = false;
  450. }
  451. private _computeMatrices(): void {
  452. var scene = this._scene;
  453. let camera = scene.activeCamera;
  454. if (!camera) {
  455. return;
  456. }
  457. Vector3.NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection);
  458. if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {
  459. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  460. }
  461. this._cachedDirection.copyFrom(this._lightDirection);
  462. for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {
  463. this._computeFrustumInWorldSpace(cascadeIndex);
  464. this._computeCascadeFrustum(cascadeIndex);
  465. this._cascadeMaxExtents[cascadeIndex].subtractToRef(this._cascadeMinExtents[cascadeIndex], tmpv1); // tmpv1 = cascadeExtents
  466. // Get position of the shadow camera
  467. this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]);
  468. // Come up with a new orthographic camera for the shadow caster
  469. Matrix.LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]);
  470. let minZ = 0, maxZ = tmpv1.z;
  471. // Try to tighten minZ and maxZ based on the bounding box of the shadow casters
  472. const boundingInfo = this._shadowCastersBoundingInfo;
  473. boundingInfo.update(this._viewMatrices[cascadeIndex]);
  474. maxZ = Math.min(maxZ, boundingInfo.boundingBox.maximumWorld.z);
  475. if (!this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS) {
  476. // If we don't use depth clamping, we must set minZ so that all shadow casters are in the light frustum
  477. minZ = Math.min(minZ, boundingInfo.boundingBox.minimumWorld.z);
  478. } else {
  479. // If using depth clamping, we can adjust minZ to reduce the [minZ, maxZ] range (and get some additional precision in the shadow map)
  480. minZ = Math.max(minZ, boundingInfo.boundingBox.minimumWorld.z);
  481. }
  482. Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[cascadeIndex].x, this._cascadeMaxExtents[cascadeIndex].x, this._cascadeMinExtents[cascadeIndex].y, this._cascadeMaxExtents[cascadeIndex].y, minZ, maxZ, this._projectionMatrices[cascadeIndex]);
  483. this._cascadeMinExtents[cascadeIndex].z = minZ;
  484. this._cascadeMaxExtents[cascadeIndex].z = maxZ;
  485. this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);
  486. // Create the rounding matrix, by projecting the world-space origin and determining
  487. // the fractional offset in texel space
  488. Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], tmpv1); // tmpv1 = shadowOrigin
  489. tmpv1.scaleInPlace(this._mapSize / 2);
  490. tmpv2.copyFromFloats(Math.round(tmpv1.x), Math.round(tmpv1.y), Math.round(tmpv1.z)); // tmpv2 = roundedOrigin
  491. tmpv2.subtractInPlace(tmpv1).scaleInPlace(2 / this._mapSize); // tmpv2 = roundOffset
  492. Matrix.TranslationToRef(tmpv2.x, tmpv2.y, 0.0, matrix);
  493. this._projectionMatrices[cascadeIndex].multiplyToRef(matrix, this._projectionMatrices[cascadeIndex]);
  494. this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);
  495. this._transformMatrices[cascadeIndex].copyToArray(this._transformMatricesAsArray, cascadeIndex * 16);
  496. }
  497. }
  498. // Get the 8 points of the view frustum in world space
  499. private _computeFrustumInWorldSpace(cascadeIndex: number): void {
  500. if (!this._scene.activeCamera) {
  501. return;
  502. }
  503. const prevSplitDist = this._cascades[cascadeIndex].prevBreakDistance,
  504. splitDist = this._cascades[cascadeIndex].breakDistance;
  505. this._scene.activeCamera.getViewMatrix(); // make sure the transformation matrix we get when calling 'getTransformationMatrix()' is calculated with an up to date view matrix
  506. const invViewProj = Matrix.Invert(this._scene.activeCamera.getTransformationMatrix());
  507. for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator.frustumCornersNDCSpace.length; ++cornerIndex) {
  508. Vector3.TransformCoordinatesToRef(CascadedShadowGenerator.frustumCornersNDCSpace[cornerIndex], invViewProj, this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
  509. }
  510. // Get the corners of the current cascade slice of the view frustum
  511. for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator.frustumCornersNDCSpace.length / 2; ++cornerIndex) {
  512. tmpv1.copyFrom(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4]).subtractInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
  513. tmpv2.copyFrom(tmpv1).scaleInPlace(prevSplitDist); // near corner ray
  514. tmpv1.scaleInPlace(splitDist); // far corner ray
  515. tmpv1.addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
  516. this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4].copyFrom(tmpv1);
  517. this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].addInPlace(tmpv2);
  518. }
  519. }
  520. private _computeCascadeFrustum(cascadeIndex: number): void {
  521. this._cascadeMinExtents[cascadeIndex].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  522. this._cascadeMaxExtents[cascadeIndex].copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);
  523. this._frustumCenter[cascadeIndex].copyFromFloats(0, 0, 0);
  524. const camera = this._scene.activeCamera;
  525. if (!camera) {
  526. return;
  527. }
  528. // Calculate the centroid of the view frustum slice
  529. for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
  530. this._frustumCenter[cascadeIndex].addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
  531. }
  532. this._frustumCenter[cascadeIndex].scaleInPlace(1 / this._frustumCornersWorldSpace[cascadeIndex].length);
  533. if (this.stabilizeCascades) {
  534. // Calculate the radius of a bounding sphere surrounding the frustum corners
  535. let sphereRadius = 0;
  536. for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
  537. const dist = this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].subtractToRef(this._frustumCenter[cascadeIndex], tmpv1).length();
  538. sphereRadius = Math.max(sphereRadius, dist);
  539. }
  540. sphereRadius = Math.ceil(sphereRadius * 16) / 16;
  541. this._cascadeMaxExtents[cascadeIndex].copyFromFloats(sphereRadius, sphereRadius, sphereRadius);
  542. this._cascadeMinExtents[cascadeIndex].copyFromFloats(-sphereRadius, -sphereRadius, -sphereRadius);
  543. } else {
  544. // Create a temporary view matrix for the light
  545. const lightCameraPos = this._frustumCenter[cascadeIndex];
  546. this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, tmpv1); // tmpv1 = look at
  547. Matrix.LookAtLHToRef(lightCameraPos, tmpv1, UpDir, matrix); // matrix = lightView
  548. // Calculate an AABB around the frustum corners
  549. for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
  550. Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex], matrix, tmpv1);
  551. this._cascadeMinExtents[cascadeIndex].minimizeInPlace(tmpv1);
  552. this._cascadeMaxExtents[cascadeIndex].maximizeInPlace(tmpv1);
  553. }
  554. }
  555. }
  556. /**
  557. * Support test.
  558. */
  559. public static get IsSupported(): boolean {
  560. var engine = EngineStore.LastCreatedEngine;
  561. if (!engine) {
  562. return false;
  563. }
  564. return engine.webGLVersion != 1;
  565. }
  566. /** @hidden */
  567. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  568. throw _DevTools.WarnImport("ShadowGeneratorSceneComponent");
  569. }
  570. /**
  571. * Creates a Cascaded Shadow Generator object.
  572. * A ShadowGenerator is the required tool to use the shadows.
  573. * Each directional light casting shadows needs to use its own ShadowGenerator.
  574. * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows
  575. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  576. * @param light The directional light object generating the shadows.
  577. * @param usefulFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  578. */
  579. constructor(mapSize: number, light: DirectionalLight, usefulFloatFirst?: boolean) {
  580. super(mapSize, light, usefulFloatFirst);
  581. if (!CascadedShadowGenerator.IsSupported) {
  582. Logger.Error("CascadedShadowMap needs WebGL 2 support.");
  583. return;
  584. }
  585. this.usePercentageCloserFiltering = true;
  586. }
  587. protected _initializeGenerator(): void {
  588. this.penumbraDarkness = this.penumbraDarkness ?? 1.0;
  589. this._numCascades = this._numCascades ?? CascadedShadowGenerator.DEFAULT_CASCADES_COUNT;
  590. this.stabilizeCascades = this.stabilizeCascades ?? false;
  591. this._freezeShadowCastersBoundingInfoObservable = this._freezeShadowCastersBoundingInfoObservable ?? null;
  592. this.freezeShadowCastersBoundingInfo = this.freezeShadowCastersBoundingInfo ?? false;
  593. this._scbiMin = this._scbiMin ?? new Vector3(0, 0, 0);
  594. this._scbiMax = this._scbiMax ?? new Vector3(0, 0, 0);
  595. this._shadowCastersBoundingInfo = this._shadowCastersBoundingInfo ?? new BoundingInfo(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
  596. this._breaksAreDirty = this._breaksAreDirty ?? true;
  597. this._minDistance = this._minDistance ?? 0;
  598. this._maxDistance = this._maxDistance ?? 1;
  599. this._currentLayer = this._currentLayer ?? 0;
  600. this._shadowMaxZ = this._shadowMaxZ ?? this._scene.activeCamera?.maxZ ?? 10000;
  601. this._debug = this._debug ?? false;
  602. this._depthClamp = this._depthClamp ?? true;
  603. this._cascadeBlendPercentage = this._cascadeBlendPercentage ?? 0.1;
  604. this._lambda = this._lambda ?? 0.5;
  605. this._autoCalcDepthBounds = this._autoCalcDepthBounds ?? false;
  606. super._initializeGenerator();
  607. }
  608. protected _createTargetRenderTexture(): void {
  609. const size = { width: this._mapSize, height: this._mapSize, layers: this.numCascades };
  610. this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", size, this._scene, false, true, this._textureType, false, undefined, false, false, undefined/*, Constants.TEXTUREFORMAT_RED*/);
  611. this._shadowMap.createDepthStencilTexture(Constants.LESS, true);
  612. }
  613. protected _initializeShadowMap(): void {
  614. super._initializeShadowMap();
  615. if (this._shadowMap === null) {
  616. return;
  617. }
  618. this._transformMatricesAsArray = new Float32Array(this._numCascades * 16);
  619. this._viewSpaceFrustumsZ = new Array(this._numCascades);
  620. this._frustumLengths = new Array(this._numCascades);
  621. this._lightSizeUVCorrection = new Array(this._numCascades * 2);
  622. this._depthCorrection = new Array(this._numCascades);
  623. this._cascades = [];
  624. this._viewMatrices = [];
  625. this._projectionMatrices = [];
  626. this._transformMatrices = [];
  627. this._cascadeMinExtents = [];
  628. this._cascadeMaxExtents = [];
  629. this._frustumCenter = [];
  630. this._shadowCameraPos = [];
  631. this._frustumCornersWorldSpace = [];
  632. for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {
  633. this._cascades[cascadeIndex] = {
  634. prevBreakDistance: 0,
  635. breakDistance: 0,
  636. };
  637. this._viewMatrices[cascadeIndex] = Matrix.Zero();
  638. this._projectionMatrices[cascadeIndex] = Matrix.Zero();
  639. this._transformMatrices[cascadeIndex] = Matrix.Zero();
  640. this._cascadeMinExtents[cascadeIndex] = new Vector3();
  641. this._cascadeMaxExtents[cascadeIndex] = new Vector3();
  642. this._frustumCenter[cascadeIndex] = new Vector3();
  643. this._shadowCameraPos[cascadeIndex] = new Vector3();
  644. this._frustumCornersWorldSpace[cascadeIndex] = new Array(CascadedShadowGenerator.frustumCornersNDCSpace.length);
  645. for (let i = 0; i < CascadedShadowGenerator.frustumCornersNDCSpace.length; ++i) {
  646. this._frustumCornersWorldSpace[cascadeIndex][i] = new Vector3();
  647. }
  648. }
  649. this._shadowMap.onBeforeRenderObservable.add((layer: number) => {
  650. this._currentLayer = layer;
  651. if (this._scene.getSceneUniformBuffer().useUbo) {
  652. const sceneUBO = this._scene.getSceneUniformBuffer();
  653. sceneUBO.updateMatrix("viewProjection", this.getCascadeTransformMatrix(layer)!);
  654. sceneUBO.updateMatrix("view", this.getCascadeViewMatrix(layer)!);
  655. sceneUBO.update();
  656. }
  657. });
  658. this._shadowMap.onBeforeBindObservable.add(() => {
  659. if (this._breaksAreDirty) {
  660. this._splitFrustum();
  661. }
  662. this._computeMatrices();
  663. });
  664. this._splitFrustum();
  665. }
  666. protected _bindCustomEffectForRenderSubMeshForShadowMap(subMesh: SubMesh, effect: Effect, matriceNames: any): void {
  667. effect.setMatrix(matriceNames?.viewProjection ?? "viewProjection", this.getCascadeTransformMatrix(this._currentLayer)!);
  668. effect.setMatrix(matriceNames?.view ?? "view", this.getCascadeViewMatrix(this._currentLayer)!);
  669. effect.setMatrix(matriceNames?.projection ?? "projection", this.getCascadeProjectionMatrix(this._currentLayer)!);
  670. }
  671. protected _isReadyCustomDefines(defines: any, subMesh: SubMesh, useInstances: boolean): void {
  672. defines.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS ? "1" : "0"));
  673. }
  674. /**
  675. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  676. * @param defines Defines of the material we want to update
  677. * @param lightIndex Index of the light in the enabled light list of the material
  678. */
  679. public prepareDefines(defines: any, lightIndex: number): void {
  680. super.prepareDefines(defines, lightIndex);
  681. var scene = this._scene;
  682. var light = this._light;
  683. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  684. return;
  685. }
  686. defines["SHADOWCSM" + lightIndex] = true;
  687. defines["SHADOWCSMDEBUG" + lightIndex] = this.debug;
  688. defines["SHADOWCSMNUM_CASCADES" + lightIndex] = this.numCascades;
  689. defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = scene.useRightHandedSystem;
  690. const camera = scene.activeCamera;
  691. if (camera && this._shadowMaxZ < camera.maxZ) {
  692. defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = true;
  693. }
  694. if (this.cascadeBlendPercentage === 0) {
  695. defines["SHADOWCSMNOBLEND" + lightIndex] = true;
  696. }
  697. }
  698. /**
  699. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  700. * defined in the generator but impacting the effect).
  701. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  702. * @param effect The effect we are binfing the information for
  703. */
  704. public bindShadowLight(lightIndex: string, effect: Effect): void {
  705. const light = this._light;
  706. const scene = this._scene;
  707. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  708. return;
  709. }
  710. const camera = scene.activeCamera;
  711. if (!camera) {
  712. return;
  713. }
  714. const shadowMap = this.getShadowMap();
  715. if (!shadowMap) {
  716. return;
  717. }
  718. const width = shadowMap.getSize().width;
  719. effect.setMatrices("lightMatrix" + lightIndex, this._transformMatricesAsArray);
  720. effect.setArray("viewFrustumZ" + lightIndex, this._viewSpaceFrustumsZ);
  721. effect.setFloat("cascadeBlendFactor" + lightIndex, this.cascadeBlendPercentage === 0 ? 10000 : 1 / this.cascadeBlendPercentage);
  722. effect.setArray("frustumLengths" + lightIndex, this._frustumLengths);
  723. // Only PCF uses depth stencil texture.
  724. if (this._filter === ShadowGenerator.FILTER_PCF) {
  725. effect.setDepthStencilTexture("shadowSampler" + lightIndex, shadowMap);
  726. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);
  727. } else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  728. for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {
  729. this._lightSizeUVCorrection[cascadeIndex * 2 + 0] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[cascadeIndex].x - this._cascadeMinExtents[cascadeIndex].x); // x correction
  730. this._lightSizeUVCorrection[cascadeIndex * 2 + 1] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y); // y correction
  731. this._depthCorrection[cascadeIndex] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[cascadeIndex].z - this._cascadeMinExtents[cascadeIndex].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z);
  732. }
  733. effect.setDepthStencilTexture("shadowSampler" + lightIndex, shadowMap);
  734. effect.setTexture("depthSampler" + lightIndex, shadowMap);
  735. effect.setArray2("lightSizeUVCorrection" + lightIndex, this._lightSizeUVCorrection);
  736. effect.setArray("depthCorrection" + lightIndex, this._depthCorrection);
  737. effect.setFloat("penumbraDarkness" + lightIndex, this.penumbraDarkness);
  738. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / width, this._contactHardeningLightSizeUVRatio * width, this.frustumEdgeFalloff, lightIndex);
  739. }
  740. else {
  741. effect.setTexture("shadowSampler" + lightIndex, shadowMap);
  742. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);
  743. }
  744. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  745. }
  746. /**
  747. * Gets the transformation matrix of the first cascade used to project the meshes into the map from the light point of view.
  748. * (eq to view projection * shadow projection matrices)
  749. * @returns The transform matrix used to create the shadow map
  750. */
  751. public getTransformMatrix(): Matrix {
  752. return this.getCascadeTransformMatrix(0)!;
  753. }
  754. /**
  755. * Disposes the ShadowGenerator.
  756. * Returns nothing.
  757. */
  758. public dispose(): void {
  759. super.dispose();
  760. if (this._freezeShadowCastersBoundingInfoObservable) {
  761. this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);
  762. this._freezeShadowCastersBoundingInfoObservable = null;
  763. }
  764. if (this._depthReducer) {
  765. this._depthReducer.dispose();
  766. this._depthReducer = null;
  767. }
  768. }
  769. /**
  770. * Serializes the shadow generator setup to a json object.
  771. * @returns The serialized JSON object
  772. */
  773. public serialize(): any {
  774. var serializationObject: any = super.serialize();
  775. var shadowMap = this.getShadowMap();
  776. if (!shadowMap) {
  777. return serializationObject;
  778. }
  779. serializationObject.numCascades = this._numCascades;
  780. serializationObject.debug = this._debug;
  781. serializationObject.stabilizeCascades = this.stabilizeCascades;
  782. serializationObject.lambda = this._lambda;
  783. serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage;
  784. serializationObject.depthClamp = this._depthClamp;
  785. serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds;
  786. serializationObject.shadowMaxZ = this._shadowMaxZ;
  787. serializationObject.penumbraDarkness = this.penumbraDarkness;
  788. serializationObject.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo;
  789. serializationObject.minDistance = this.minDistance;
  790. serializationObject.maxDistance = this.maxDistance;
  791. serializationObject.renderList = [];
  792. if (shadowMap.renderList) {
  793. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  794. var mesh = shadowMap.renderList[meshIndex];
  795. serializationObject.renderList.push(mesh.id);
  796. }
  797. }
  798. return serializationObject;
  799. }
  800. /**
  801. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  802. * @param parsedShadowGenerator The JSON object to parse
  803. * @param scene The scene to create the shadow map for
  804. * @returns The parsed shadow generator
  805. */
  806. public static Parse(parsedShadowGenerator: any, scene: Scene): ShadowGenerator {
  807. var shadowGenerator = ShadowGenerator.Parse(parsedShadowGenerator, scene, (mapSize: number, light: IShadowLight) => new CascadedShadowGenerator(mapSize, <DirectionalLight>light)) as CascadedShadowGenerator;
  808. if (parsedShadowGenerator.numCascades !== undefined) {
  809. shadowGenerator.numCascades = parsedShadowGenerator.numCascades;
  810. }
  811. if (parsedShadowGenerator.debug !== undefined) {
  812. shadowGenerator.debug = parsedShadowGenerator.debug;
  813. }
  814. if (parsedShadowGenerator.stabilizeCascades !== undefined) {
  815. shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades;
  816. }
  817. if (parsedShadowGenerator.lambda !== undefined) {
  818. shadowGenerator.lambda = parsedShadowGenerator.lambda;
  819. }
  820. if (parsedShadowGenerator.cascadeBlendPercentage !== undefined) {
  821. shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage;
  822. }
  823. if (parsedShadowGenerator.depthClamp !== undefined) {
  824. shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp;
  825. }
  826. if (parsedShadowGenerator.autoCalcDepthBounds !== undefined) {
  827. shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds;
  828. }
  829. if (parsedShadowGenerator.shadowMaxZ !== undefined) {
  830. shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ;
  831. }
  832. if (parsedShadowGenerator.penumbraDarkness !== undefined) {
  833. shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness;
  834. }
  835. if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== undefined) {
  836. shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo;
  837. }
  838. if (parsedShadowGenerator.minDistance !== undefined && parsedShadowGenerator.maxDistance !== undefined) {
  839. shadowGenerator.setMinMaxDistance(parsedShadowGenerator.minDistance, parsedShadowGenerator.maxDistance);
  840. }
  841. return shadowGenerator;
  842. }
  843. }