shadowGenerator.ts 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757
  1. import { SmartArray } from "../../Misc/smartArray";
  2. import { Nullable } from "../../types";
  3. import { Scene } from "../../scene";
  4. import { Matrix, Vector3, Vector2 } from "../../Maths/math.vector";
  5. import { Color4 } from "../../Maths/math.color";
  6. import { VertexBuffer } from "../../Meshes/buffer";
  7. import { SubMesh } from "../../Meshes/subMesh";
  8. import { AbstractMesh } from "../../Meshes/abstractMesh";
  9. import { Mesh } from "../../Meshes/mesh";
  10. import { IShadowLight } from "../../Lights/shadowLight";
  11. import { Light } from "../../Lights/light";
  12. import { MaterialDefines } from "../../Materials/materialDefines";
  13. import { MaterialHelper } from "../../Materials/materialHelper";
  14. import { Effect } from "../../Materials/effect";
  15. import { Texture } from "../../Materials/Textures/texture";
  16. import { RenderTargetTexture } from "../../Materials/Textures/renderTargetTexture";
  17. import { PostProcess } from "../../PostProcesses/postProcess";
  18. import { BlurPostProcess } from "../../PostProcesses/blurPostProcess";
  19. import { Constants } from "../../Engines/constants";
  20. import "../../Shaders/shadowMap.fragment";
  21. import "../../Shaders/shadowMap.vertex";
  22. import "../../Shaders/depthBoxBlur.fragment";
  23. import { Observable } from '../../Misc/observable';
  24. import { _DevTools } from '../../Misc/devTools';
  25. import { EffectFallbacks } from '../../Materials/effectFallbacks';
  26. /**
  27. * Defines the options associated with the creation of a custom shader for a shadow generator.
  28. */
  29. export interface ICustomShaderOptions {
  30. /**
  31. * Gets or sets the custom shader name to use
  32. */
  33. shaderName: string;
  34. /**
  35. * The list of attribute names used in the shader
  36. */
  37. attributes?: string[];
  38. /**
  39. * The list of unifrom names used in the shader
  40. */
  41. uniforms?: string[];
  42. /**
  43. * The list of sampler names used in the shader
  44. */
  45. samplers?: string[];
  46. /**
  47. * The list of defines used in the shader
  48. */
  49. defines?: string[];
  50. }
  51. /**
  52. * Interface to implement to create a shadow generator compatible with BJS.
  53. */
  54. export interface IShadowGenerator {
  55. /**
  56. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  57. * @returns The render target texture if present otherwise, null
  58. */
  59. getShadowMap(): Nullable<RenderTargetTexture>;
  60. /**
  61. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  62. * @param subMesh The submesh we want to render in the shadow map
  63. * @param useInstances Defines wether will draw in the map using instances
  64. * @returns true if ready otherwise, false
  65. */
  66. isReady(subMesh: SubMesh, useInstances: boolean): boolean;
  67. /**
  68. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69. * @param defines Defines of the material we want to update
  70. * @param lightIndex Index of the light in the enabled light list of the material
  71. */
  72. prepareDefines(defines: MaterialDefines, lightIndex: number): void;
  73. /**
  74. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  75. * defined in the generator but impacting the effect).
  76. * It implies the unifroms available on the materials are the standard BJS ones.
  77. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  78. * @param effect The effect we are binfing the information for
  79. */
  80. bindShadowLight(lightIndex: string, effect: Effect): void;
  81. /**
  82. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  83. * (eq to shadow prjection matrix * light transform matrix)
  84. * @returns The transform matrix used to create the shadow map
  85. */
  86. getTransformMatrix(): Matrix;
  87. /**
  88. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  89. * Cube and 2D textures for instance.
  90. */
  91. recreateShadowMap(): void;
  92. /**
  93. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  94. * @param onCompiled Callback triggered at the and of the effects compilation
  95. * @param options Sets of optional options forcing the compilation with different modes
  96. */
  97. forceCompilation(onCompiled?: (generator: IShadowGenerator) => void, options?: Partial<{ useInstances: boolean }>): void;
  98. /**
  99. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  100. * @param options Sets of optional options forcing the compilation with different modes
  101. * @returns A promise that resolves when the compilation completes
  102. */
  103. forceCompilationAsync(options?: Partial<{ useInstances: boolean }>): Promise<void>;
  104. /**
  105. * Serializes the shadow generator setup to a json object.
  106. * @returns The serialized JSON object
  107. */
  108. serialize(): any;
  109. /**
  110. * Disposes the Shadow map and related Textures and effects.
  111. */
  112. dispose(): void;
  113. }
  114. /**
  115. * Default implementation IShadowGenerator.
  116. * This is the main object responsible of generating shadows in the framework.
  117. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  118. */
  119. export class ShadowGenerator implements IShadowGenerator {
  120. /**
  121. * Name of the shadow generator class
  122. */
  123. public static CLASSNAME = "ShadowGenerator";
  124. /**
  125. * Shadow generator mode None: no filtering applied.
  126. */
  127. public static readonly FILTER_NONE = 0;
  128. /**
  129. * Shadow generator mode ESM: Exponential Shadow Mapping.
  130. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  131. */
  132. public static readonly FILTER_EXPONENTIALSHADOWMAP = 1;
  133. /**
  134. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  135. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  136. */
  137. public static readonly FILTER_POISSONSAMPLING = 2;
  138. /**
  139. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  140. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  141. */
  142. public static readonly FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  143. /**
  144. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  145. * edge artifacts on steep falloff.
  146. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  147. */
  148. public static readonly FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  149. /**
  150. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  151. * edge artifacts on steep falloff.
  152. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  153. */
  154. public static readonly FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  155. /**
  156. * Shadow generator mode PCF: Percentage Closer Filtering
  157. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  158. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  159. */
  160. public static readonly FILTER_PCF = 6;
  161. /**
  162. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  163. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  164. * Contact Hardening
  165. */
  166. public static readonly FILTER_PCSS = 7;
  167. /**
  168. * Reserved for PCF and PCSS
  169. * Highest Quality.
  170. *
  171. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  172. *
  173. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  174. */
  175. public static readonly QUALITY_HIGH = 0;
  176. /**
  177. * Reserved for PCF and PCSS
  178. * Good tradeoff for quality/perf cross devices
  179. *
  180. * Execute PCF on a 3*3 kernel.
  181. *
  182. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  183. */
  184. public static readonly QUALITY_MEDIUM = 1;
  185. /**
  186. * Reserved for PCF and PCSS
  187. * The lowest quality but the fastest.
  188. *
  189. * Execute PCF on a 1*1 kernel.
  190. *
  191. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  192. */
  193. public static readonly QUALITY_LOW = 2;
  194. /** Gets or sets the custom shader name to use */
  195. public customShaderOptions: ICustomShaderOptions;
  196. /**
  197. * Observable triggered before the shadow is rendered. Can be used to update internal effect state
  198. */
  199. public onBeforeShadowMapRenderObservable = new Observable<Effect>();
  200. /**
  201. * Observable triggered after the shadow is rendered. Can be used to restore internal effect state
  202. */
  203. public onAfterShadowMapRenderObservable = new Observable<Effect>();
  204. /**
  205. * Observable triggered before a mesh is rendered in the shadow map.
  206. * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable)
  207. */
  208. public onBeforeShadowMapRenderMeshObservable = new Observable<Mesh>();
  209. /**
  210. * Observable triggered after a mesh is rendered in the shadow map.
  211. * Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable)
  212. */
  213. public onAfterShadowMapRenderMeshObservable = new Observable<Mesh>();
  214. protected _bias = 0.00005;
  215. /**
  216. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  217. */
  218. public get bias(): number {
  219. return this._bias;
  220. }
  221. /**
  222. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  223. */
  224. public set bias(bias: number) {
  225. this._bias = bias;
  226. }
  227. protected _normalBias = 0;
  228. /**
  229. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  230. */
  231. public get normalBias(): number {
  232. return this._normalBias;
  233. }
  234. /**
  235. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  236. */
  237. public set normalBias(normalBias: number) {
  238. this._normalBias = normalBias;
  239. }
  240. protected _blurBoxOffset = 1;
  241. /**
  242. * Gets the blur box offset: offset applied during the blur pass.
  243. * Only useful if useKernelBlur = false
  244. */
  245. public get blurBoxOffset(): number {
  246. return this._blurBoxOffset;
  247. }
  248. /**
  249. * Sets the blur box offset: offset applied during the blur pass.
  250. * Only useful if useKernelBlur = false
  251. */
  252. public set blurBoxOffset(value: number) {
  253. if (this._blurBoxOffset === value) {
  254. return;
  255. }
  256. this._blurBoxOffset = value;
  257. this._disposeBlurPostProcesses();
  258. }
  259. protected _blurScale = 2;
  260. /**
  261. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  262. * 2 means half of the size.
  263. */
  264. public get blurScale(): number {
  265. return this._blurScale;
  266. }
  267. /**
  268. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  269. * 2 means half of the size.
  270. */
  271. public set blurScale(value: number) {
  272. if (this._blurScale === value) {
  273. return;
  274. }
  275. this._blurScale = value;
  276. this._disposeBlurPostProcesses();
  277. }
  278. protected _blurKernel = 1;
  279. /**
  280. * Gets the blur kernel: kernel size of the blur pass.
  281. * Only useful if useKernelBlur = true
  282. */
  283. public get blurKernel(): number {
  284. return this._blurKernel;
  285. }
  286. /**
  287. * Sets the blur kernel: kernel size of the blur pass.
  288. * Only useful if useKernelBlur = true
  289. */
  290. public set blurKernel(value: number) {
  291. if (this._blurKernel === value) {
  292. return;
  293. }
  294. this._blurKernel = value;
  295. this._disposeBlurPostProcesses();
  296. }
  297. protected _useKernelBlur = false;
  298. /**
  299. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  300. * Only useful in filtered mode (useBlurExponentialShadowMap...)
  301. */
  302. public get useKernelBlur(): boolean {
  303. return this._useKernelBlur;
  304. }
  305. /**
  306. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  307. * Only useful in filtered mode (useBlurExponentialShadowMap...)
  308. */
  309. public set useKernelBlur(value: boolean) {
  310. if (this._useKernelBlur === value) {
  311. return;
  312. }
  313. this._useKernelBlur = value;
  314. this._disposeBlurPostProcesses();
  315. }
  316. protected _depthScale: number;
  317. /**
  318. * Gets the depth scale used in ESM mode.
  319. */
  320. public get depthScale(): number {
  321. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  322. }
  323. /**
  324. * Sets the depth scale used in ESM mode.
  325. * This can override the scale stored on the light.
  326. */
  327. public set depthScale(value: number) {
  328. this._depthScale = value;
  329. }
  330. protected _validateFilter(filter: number): number {
  331. return filter;
  332. }
  333. protected _filter = ShadowGenerator.FILTER_NONE;
  334. /**
  335. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  336. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  337. */
  338. public get filter(): number {
  339. return this._filter;
  340. }
  341. /**
  342. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  343. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  344. */
  345. public set filter(value: number) {
  346. value = this._validateFilter(value);
  347. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  348. if (this._light.needCube()) {
  349. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  350. this.useExponentialShadowMap = true;
  351. return;
  352. }
  353. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  354. this.useCloseExponentialShadowMap = true;
  355. return;
  356. }
  357. // PCF on cubemap would also be expensive
  358. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  359. this.usePoissonSampling = true;
  360. return;
  361. }
  362. }
  363. // Weblg1 fallback for PCF.
  364. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  365. if (this._scene.getEngine().webGLVersion === 1) {
  366. this.usePoissonSampling = true;
  367. return;
  368. }
  369. }
  370. if (this._filter === value) {
  371. return;
  372. }
  373. this._filter = value;
  374. this._disposeBlurPostProcesses();
  375. this._applyFilterValues();
  376. this._light._markMeshesAsLightDirty();
  377. }
  378. /**
  379. * Gets if the current filter is set to Poisson Sampling.
  380. */
  381. public get usePoissonSampling(): boolean {
  382. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  383. }
  384. /**
  385. * Sets the current filter to Poisson Sampling.
  386. */
  387. public set usePoissonSampling(value: boolean) {
  388. let filter = this._validateFilter(ShadowGenerator.FILTER_POISSONSAMPLING);
  389. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  390. return;
  391. }
  392. this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
  393. }
  394. /**
  395. * Gets if the current filter is set to ESM.
  396. */
  397. public get useExponentialShadowMap(): boolean {
  398. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  399. }
  400. /**
  401. * Sets the current filter is to ESM.
  402. */
  403. public set useExponentialShadowMap(value: boolean) {
  404. let filter = this._validateFilter(ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);
  405. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  406. return;
  407. }
  408. this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
  409. }
  410. /**
  411. * Gets if the current filter is set to filtered ESM.
  412. */
  413. public get useBlurExponentialShadowMap(): boolean {
  414. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  415. }
  416. /**
  417. * Gets if the current filter is set to filtered ESM.
  418. */
  419. public set useBlurExponentialShadowMap(value: boolean) {
  420. let filter = this._validateFilter(ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);
  421. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  422. return;
  423. }
  424. this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
  425. }
  426. /**
  427. * Gets if the current filter is set to "close ESM" (using the inverse of the
  428. * exponential to prevent steep falloff artifacts).
  429. */
  430. public get useCloseExponentialShadowMap(): boolean {
  431. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  432. }
  433. /**
  434. * Sets the current filter to "close ESM" (using the inverse of the
  435. * exponential to prevent steep falloff artifacts).
  436. */
  437. public set useCloseExponentialShadowMap(value: boolean) {
  438. let filter = this._validateFilter(ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);
  439. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  440. return;
  441. }
  442. this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
  443. }
  444. /**
  445. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  446. * exponential to prevent steep falloff artifacts).
  447. */
  448. public get useBlurCloseExponentialShadowMap(): boolean {
  449. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  450. }
  451. /**
  452. * Sets the current filter to filtered "close ESM" (using the inverse of the
  453. * exponential to prevent steep falloff artifacts).
  454. */
  455. public set useBlurCloseExponentialShadowMap(value: boolean) {
  456. let filter = this._validateFilter(ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);
  457. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  458. return;
  459. }
  460. this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
  461. }
  462. /**
  463. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  464. */
  465. public get usePercentageCloserFiltering(): boolean {
  466. return this.filter === ShadowGenerator.FILTER_PCF;
  467. }
  468. /**
  469. * Sets the current filter to "PCF" (percentage closer filtering).
  470. */
  471. public set usePercentageCloserFiltering(value: boolean) {
  472. let filter = this._validateFilter(ShadowGenerator.FILTER_PCF);
  473. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  474. return;
  475. }
  476. this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
  477. }
  478. protected _filteringQuality = ShadowGenerator.QUALITY_HIGH;
  479. /**
  480. * Gets the PCF or PCSS Quality.
  481. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  482. */
  483. public get filteringQuality(): number {
  484. return this._filteringQuality;
  485. }
  486. /**
  487. * Sets the PCF or PCSS Quality.
  488. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  489. */
  490. public set filteringQuality(filteringQuality: number) {
  491. if (this._filteringQuality === filteringQuality) {
  492. return;
  493. }
  494. this._filteringQuality = filteringQuality;
  495. this._disposeBlurPostProcesses();
  496. this._applyFilterValues();
  497. this._light._markMeshesAsLightDirty();
  498. }
  499. /**
  500. * Gets if the current filter is set to "PCSS" (contact hardening).
  501. */
  502. public get useContactHardeningShadow(): boolean {
  503. return this.filter === ShadowGenerator.FILTER_PCSS;
  504. }
  505. /**
  506. * Sets the current filter to "PCSS" (contact hardening).
  507. */
  508. public set useContactHardeningShadow(value: boolean) {
  509. let filter = this._validateFilter(ShadowGenerator.FILTER_PCSS);
  510. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  511. return;
  512. }
  513. this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
  514. }
  515. protected _contactHardeningLightSizeUVRatio = 0.1;
  516. /**
  517. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  518. * Using a ratio helps keeping shape stability independently of the map size.
  519. *
  520. * It does not account for the light projection as it was having too much
  521. * instability during the light setup or during light position changes.
  522. *
  523. * Only valid if useContactHardeningShadow is true.
  524. */
  525. public get contactHardeningLightSizeUVRatio(): number {
  526. return this._contactHardeningLightSizeUVRatio;
  527. }
  528. /**
  529. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  530. * Using a ratio helps keeping shape stability independently of the map size.
  531. *
  532. * It does not account for the light projection as it was having too much
  533. * instability during the light setup or during light position changes.
  534. *
  535. * Only valid if useContactHardeningShadow is true.
  536. */
  537. public set contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio: number) {
  538. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  539. }
  540. protected _darkness = 0;
  541. /** Gets or sets the actual darkness of a shadow */
  542. public get darkness() {
  543. return this._darkness;
  544. }
  545. public set darkness(value: number) {
  546. this.setDarkness(value);
  547. }
  548. /**
  549. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  550. * 0 means strongest and 1 would means no shadow.
  551. * @returns the darkness.
  552. */
  553. public getDarkness(): number {
  554. return this._darkness;
  555. }
  556. /**
  557. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  558. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  559. * @returns the shadow generator allowing fluent coding.
  560. */
  561. public setDarkness(darkness: number): ShadowGenerator {
  562. if (darkness >= 1.0) {
  563. this._darkness = 1.0;
  564. }
  565. else if (darkness <= 0.0) {
  566. this._darkness = 0.0;
  567. }
  568. else {
  569. this._darkness = darkness;
  570. }
  571. return this;
  572. }
  573. protected _transparencyShadow = false;
  574. /** Gets or sets the ability to have transparent shadow */
  575. public get transparencyShadow() {
  576. return this._transparencyShadow;
  577. }
  578. public set transparencyShadow(value: boolean) {
  579. this.setTransparencyShadow(value);
  580. }
  581. /**
  582. * Sets the ability to have transparent shadow (boolean).
  583. * @param transparent True if transparent else False
  584. * @returns the shadow generator allowing fluent coding
  585. */
  586. public setTransparencyShadow(transparent: boolean): ShadowGenerator {
  587. this._transparencyShadow = transparent;
  588. return this;
  589. }
  590. protected _shadowMap: Nullable<RenderTargetTexture>;
  591. protected _shadowMap2: Nullable<RenderTargetTexture>;
  592. /**
  593. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  594. * @returns The render target texture if present otherwise, null
  595. */
  596. public getShadowMap(): Nullable<RenderTargetTexture> {
  597. return this._shadowMap;
  598. }
  599. /**
  600. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  601. * @returns The render target texture if the shadow map is present otherwise, null
  602. */
  603. public getShadowMapForRendering(): Nullable<RenderTargetTexture> {
  604. if (this._shadowMap2) {
  605. return this._shadowMap2;
  606. }
  607. return this._shadowMap;
  608. }
  609. /**
  610. * Gets the class name of that object
  611. * @returns "ShadowGenerator"
  612. */
  613. public getClassName(): string {
  614. return ShadowGenerator.CLASSNAME;
  615. }
  616. /**
  617. * Helper function to add a mesh and its descendants to the list of shadow casters.
  618. * @param mesh Mesh to add
  619. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  620. * @returns the Shadow Generator itself
  621. */
  622. public addShadowCaster(mesh: AbstractMesh, includeDescendants = true): ShadowGenerator {
  623. if (!this._shadowMap) {
  624. return this;
  625. }
  626. if (!this._shadowMap.renderList) {
  627. this._shadowMap.renderList = [];
  628. }
  629. this._shadowMap.renderList.push(mesh);
  630. if (includeDescendants) {
  631. this._shadowMap.renderList.push(...mesh.getChildMeshes());
  632. }
  633. return this;
  634. }
  635. /**
  636. * Helper function to remove a mesh and its descendants from the list of shadow casters
  637. * @param mesh Mesh to remove
  638. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  639. * @returns the Shadow Generator itself
  640. */
  641. public removeShadowCaster(mesh: AbstractMesh, includeDescendants = true): ShadowGenerator {
  642. if (!this._shadowMap || !this._shadowMap.renderList) {
  643. return this;
  644. }
  645. var index = this._shadowMap.renderList.indexOf(mesh);
  646. if (index !== -1) {
  647. this._shadowMap.renderList.splice(index, 1);
  648. }
  649. if (includeDescendants) {
  650. for (var child of mesh.getChildren()) {
  651. this.removeShadowCaster(<any>child);
  652. }
  653. }
  654. return this;
  655. }
  656. /**
  657. * Controls the extent to which the shadows fade out at the edge of the frustum
  658. */
  659. public frustumEdgeFalloff = 0;
  660. protected _light: IShadowLight;
  661. /**
  662. * Returns the associated light object.
  663. * @returns the light generating the shadow
  664. */
  665. public getLight(): IShadowLight {
  666. return this._light;
  667. }
  668. /**
  669. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  670. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  671. * It might on the other hand introduce peter panning.
  672. */
  673. public forceBackFacesOnly = false;
  674. protected _scene: Scene;
  675. protected _lightDirection = Vector3.Zero();
  676. protected _effect: Effect;
  677. protected _viewMatrix = Matrix.Zero();
  678. protected _projectionMatrix = Matrix.Zero();
  679. protected _transformMatrix = Matrix.Zero();
  680. protected _cachedPosition: Vector3 = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  681. protected _cachedDirection: Vector3 = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  682. protected _cachedDefines: string;
  683. protected _currentRenderID: number;
  684. protected _boxBlurPostprocess: Nullable<PostProcess>;
  685. protected _kernelBlurXPostprocess: Nullable<PostProcess>;
  686. protected _kernelBlurYPostprocess: Nullable<PostProcess>;
  687. protected _blurPostProcesses: PostProcess[];
  688. protected _mapSize: number;
  689. protected _currentFaceIndex = 0;
  690. protected _currentFaceIndexCache = 0;
  691. protected _textureType: number;
  692. protected _defaultTextureMatrix = Matrix.Identity();
  693. protected _storedUniqueId: Nullable<number>;
  694. /** @hidden */
  695. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  696. throw _DevTools.WarnImport("ShadowGeneratorSceneComponent");
  697. }
  698. /**
  699. * Creates a ShadowGenerator object.
  700. * A ShadowGenerator is the required tool to use the shadows.
  701. * Each light casting shadows needs to use its own ShadowGenerator.
  702. * Documentation : https://doc.babylonjs.com/babylon101/shadows
  703. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  704. * @param light The light object generating the shadows.
  705. * @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.
  706. */
  707. constructor(mapSize: number, light: IShadowLight, usefulFloatFirst?: boolean) {
  708. this._mapSize = mapSize;
  709. this._light = light;
  710. this._scene = light.getScene();
  711. light._shadowGenerator = this;
  712. ShadowGenerator._SceneComponentInitialization(this._scene);
  713. // Texture type fallback from float to int if not supported.
  714. var caps = this._scene.getEngine().getCaps();
  715. if (!usefulFloatFirst) {
  716. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  717. this._textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  718. }
  719. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  720. this._textureType = Constants.TEXTURETYPE_FLOAT;
  721. }
  722. else {
  723. this._textureType = Constants.TEXTURETYPE_UNSIGNED_INT;
  724. }
  725. } else {
  726. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  727. this._textureType = Constants.TEXTURETYPE_FLOAT;
  728. }
  729. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  730. this._textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  731. }
  732. else {
  733. this._textureType = Constants.TEXTURETYPE_UNSIGNED_INT;
  734. }
  735. }
  736. this._initializeGenerator();
  737. this._applyFilterValues();
  738. }
  739. protected _initializeGenerator(): void {
  740. this._light._markMeshesAsLightDirty();
  741. this._initializeShadowMap();
  742. }
  743. protected _createTargetRenderTexture(): void {
  744. let engine = this._scene.getEngine();
  745. if (engine.webGLVersion > 1) {
  746. this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  747. this._shadowMap.createDepthStencilTexture(Constants.LESS, true);
  748. }
  749. else {
  750. this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  751. }
  752. }
  753. protected _initializeShadowMap(): void {
  754. this._createTargetRenderTexture();
  755. if (this._shadowMap === null) {
  756. return;
  757. }
  758. this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
  759. this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
  760. this._shadowMap.anisotropicFilteringLevel = 1;
  761. this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  762. this._shadowMap.renderParticles = false;
  763. this._shadowMap.ignoreCameraViewport = true;
  764. if (this._storedUniqueId) {
  765. this._shadowMap.uniqueId = this._storedUniqueId;
  766. }
  767. // Custom render function.
  768. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  769. let engine = this._scene.getEngine();
  770. // Record Face Index before render.
  771. this._shadowMap.onBeforeRenderObservable.add((faceIndex: number) => {
  772. this._currentFaceIndex = faceIndex;
  773. if (this._filter === ShadowGenerator.FILTER_PCF) {
  774. engine.setColorWrite(false);
  775. }
  776. });
  777. // Blur if required afer render.
  778. this._shadowMap.onAfterUnbindObservable.add(() => {
  779. if (this._filter === ShadowGenerator.FILTER_PCF) {
  780. engine.setColorWrite(true);
  781. }
  782. if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) {
  783. return;
  784. }
  785. let shadowMap = this.getShadowMapForRendering();
  786. if (shadowMap) {
  787. this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  788. }
  789. });
  790. // Clear according to the chosen filter.
  791. var clearZero = new Color4(0, 0, 0, 0);
  792. var clearOne = new Color4(1.0, 1.0, 1.0, 1.0);
  793. this._shadowMap.onClearObservable.add((engine) => {
  794. if (this._filter === ShadowGenerator.FILTER_PCF) {
  795. engine.clear(clearOne, false, true, false);
  796. }
  797. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  798. engine.clear(clearZero, true, true, false);
  799. }
  800. else {
  801. engine.clear(clearOne, true, true, false);
  802. }
  803. });
  804. // Recreate on resize.
  805. this._shadowMap.onResizeObservable.add((RTT) => {
  806. this._storedUniqueId = this._shadowMap!.uniqueId;
  807. this._mapSize = RTT.getRenderSize();
  808. this._light._markMeshesAsLightDirty();
  809. this.recreateShadowMap();
  810. });
  811. }
  812. protected _initializeBlurRTTAndPostProcesses(): void {
  813. var engine = this._scene.getEngine();
  814. var targetSize = this._mapSize / this.blurScale;
  815. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  816. this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  817. this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
  818. this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
  819. this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  820. }
  821. if (this.useKernelBlur) {
  822. this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + "KernelBlurX", new Vector2(1, 0), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  823. this._kernelBlurXPostprocess.width = targetSize;
  824. this._kernelBlurXPostprocess.height = targetSize;
  825. this._kernelBlurXPostprocess.onApplyObservable.add((effect) => {
  826. effect.setTexture("textureSampler", this._shadowMap);
  827. });
  828. this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY", new Vector2(0, 1), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  829. this._kernelBlurXPostprocess.autoClear = false;
  830. this._kernelBlurYPostprocess.autoClear = false;
  831. if (this._textureType === Constants.TEXTURETYPE_UNSIGNED_INT) {
  832. (<BlurPostProcess>this._kernelBlurXPostprocess).packedFloat = true;
  833. (<BlurPostProcess>this._kernelBlurYPostprocess).packedFloat = true;
  834. }
  835. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  836. }
  837. else {
  838. this._boxBlurPostprocess = new PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  839. this._boxBlurPostprocess.onApplyObservable.add((effect) => {
  840. effect.setFloat2("screenSize", targetSize, targetSize);
  841. effect.setTexture("textureSampler", this._shadowMap);
  842. });
  843. this._boxBlurPostprocess.autoClear = false;
  844. this._blurPostProcesses = [this._boxBlurPostprocess];
  845. }
  846. }
  847. protected _renderForShadowMap(opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void {
  848. var index: number;
  849. let engine = this._scene.getEngine();
  850. const colorWrite = engine.getColorWrite();
  851. if (depthOnlySubMeshes.length) {
  852. engine.setColorWrite(false);
  853. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  854. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  855. }
  856. engine.setColorWrite(colorWrite);
  857. }
  858. for (index = 0; index < opaqueSubMeshes.length; index++) {
  859. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  860. }
  861. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  862. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  863. }
  864. if (this._transparencyShadow) {
  865. for (index = 0; index < transparentSubMeshes.length; index++) {
  866. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  867. }
  868. }
  869. }
  870. protected _bindCustomEffectForRenderSubMeshForShadowMap(subMesh: SubMesh, effect: Effect): void {
  871. }
  872. protected _renderSubMeshForShadowMap(subMesh: SubMesh): void {
  873. var mesh = subMesh.getRenderingMesh();
  874. var scene = this._scene;
  875. var engine = scene.getEngine();
  876. let material = subMesh.getMaterial();
  877. mesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
  878. if (!material || subMesh.verticesCount === 0) {
  879. return;
  880. }
  881. // Culling
  882. engine.setState(material.backFaceCulling);
  883. // Managing instances
  884. var batch = mesh._getInstancesRenderList(subMesh._id);
  885. if (batch.mustReturn) {
  886. return;
  887. }
  888. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  889. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  890. engine.enableEffect(this._effect);
  891. mesh._bind(subMesh, this._effect, material.fillMode);
  892. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  893. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  894. if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  895. this._effect.setVector3("lightData", this._cachedDirection);
  896. }
  897. else {
  898. this._effect.setVector3("lightData", this._cachedPosition);
  899. }
  900. if (scene.activeCamera) {
  901. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  902. }
  903. // Alpha test
  904. if (material && material.needAlphaTesting()) {
  905. var alphaTexture = material.getAlphaTestTexture();
  906. if (alphaTexture) {
  907. this._effect.setTexture("diffuseSampler", alphaTexture);
  908. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  909. }
  910. }
  911. // Bones
  912. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  913. const skeleton = mesh.skeleton;
  914. if (skeleton.isUsingTextureForMatrices) {
  915. const boneTexture = skeleton.getTransformMatrixTexture(mesh);
  916. if (!boneTexture) {
  917. return;
  918. }
  919. this._effect.setTexture("boneSampler", boneTexture);
  920. this._effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
  921. } else {
  922. this._effect.setMatrices("mBones", skeleton.getTransformMatrices((mesh)));
  923. }
  924. }
  925. // Morph targets
  926. MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  927. // Clip planes
  928. MaterialHelper.BindClipPlane(this._effect, scene);
  929. this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, this._effect);
  930. if (this.forceBackFacesOnly) {
  931. engine.setState(true, 0, false, true);
  932. }
  933. // Observables
  934. this.onBeforeShadowMapRenderMeshObservable.notifyObservers(mesh);
  935. this.onBeforeShadowMapRenderObservable.notifyObservers(this._effect);
  936. // Draw
  937. mesh._processRendering(subMesh, this._effect, material.fillMode, batch, hardwareInstancedRendering,
  938. (isInstance, world) => this._effect.setMatrix("world", world));
  939. if (this.forceBackFacesOnly) {
  940. engine.setState(true, 0, false, false);
  941. }
  942. // Observables
  943. this.onAfterShadowMapRenderObservable.notifyObservers(this._effect);
  944. this.onAfterShadowMapRenderMeshObservable.notifyObservers(mesh);
  945. } else {
  946. // Need to reset refresh rate of the shadowMap
  947. if (this._shadowMap) {
  948. this._shadowMap.resetRefreshCounter();
  949. }
  950. }
  951. }
  952. protected _applyFilterValues(): void {
  953. if (!this._shadowMap) {
  954. return;
  955. }
  956. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  957. this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
  958. } else {
  959. this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  960. }
  961. }
  962. /**
  963. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  964. * @param onCompiled Callback triggered at the and of the effects compilation
  965. * @param options Sets of optional options forcing the compilation with different modes
  966. */
  967. public forceCompilation(onCompiled?: (generator: IShadowGenerator) => void, options?: Partial<{ useInstances: boolean }>): void {
  968. let localOptions = {
  969. useInstances: false,
  970. ...options
  971. };
  972. let shadowMap = this.getShadowMap();
  973. if (!shadowMap) {
  974. if (onCompiled) {
  975. onCompiled(this);
  976. }
  977. return;
  978. }
  979. let renderList = shadowMap.renderList;
  980. if (!renderList) {
  981. if (onCompiled) {
  982. onCompiled(this);
  983. }
  984. return;
  985. }
  986. var subMeshes = new Array<SubMesh>();
  987. for (var mesh of renderList) {
  988. subMeshes.push(...mesh.subMeshes);
  989. }
  990. if (subMeshes.length === 0) {
  991. if (onCompiled) {
  992. onCompiled(this);
  993. }
  994. return;
  995. }
  996. var currentIndex = 0;
  997. var checkReady = () => {
  998. if (!this._scene || !this._scene.getEngine()) {
  999. return;
  1000. }
  1001. while (this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  1002. currentIndex++;
  1003. if (currentIndex >= subMeshes.length) {
  1004. if (onCompiled) {
  1005. onCompiled(this);
  1006. }
  1007. return;
  1008. }
  1009. }
  1010. setTimeout(checkReady, 16);
  1011. };
  1012. checkReady();
  1013. }
  1014. /**
  1015. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  1016. * @param options Sets of optional options forcing the compilation with different modes
  1017. * @returns A promise that resolves when the compilation completes
  1018. */
  1019. public forceCompilationAsync(options?: Partial<{ useInstances: boolean }>): Promise<void> {
  1020. return new Promise((resolve) => {
  1021. this.forceCompilation(() => {
  1022. resolve();
  1023. }, options);
  1024. });
  1025. }
  1026. protected _isReadyCustomDefines(defines: any, subMesh: SubMesh, useInstances: boolean): void {
  1027. }
  1028. /**
  1029. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  1030. * @param subMesh The submesh we want to render in the shadow map
  1031. * @param useInstances Defines wether will draw in the map using instances
  1032. * @returns true if ready otherwise, false
  1033. */
  1034. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  1035. var defines = [];
  1036. if (this._textureType !== Constants.TEXTURETYPE_UNSIGNED_INT) {
  1037. defines.push("#define FLOAT");
  1038. }
  1039. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  1040. defines.push("#define ESM");
  1041. }
  1042. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  1043. defines.push("#define DEPTHTEXTURE");
  1044. }
  1045. var attribs = [VertexBuffer.PositionKind];
  1046. var mesh = subMesh.getMesh();
  1047. var material = subMesh.getMaterial();
  1048. // Normal bias.
  1049. if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1050. attribs.push(VertexBuffer.NormalKind);
  1051. defines.push("#define NORMAL");
  1052. if (mesh.nonUniformScaling) {
  1053. defines.push("#define NONUNIFORMSCALING");
  1054. }
  1055. if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  1056. defines.push("#define DIRECTIONINLIGHTDATA");
  1057. }
  1058. }
  1059. // Alpha test
  1060. if (material && material.needAlphaTesting()) {
  1061. var alphaTexture = material.getAlphaTestTexture();
  1062. if (alphaTexture) {
  1063. defines.push("#define ALPHATEST");
  1064. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  1065. attribs.push(VertexBuffer.UVKind);
  1066. defines.push("#define UV1");
  1067. }
  1068. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  1069. if (alphaTexture.coordinatesIndex === 1) {
  1070. attribs.push(VertexBuffer.UV2Kind);
  1071. defines.push("#define UV2");
  1072. }
  1073. }
  1074. }
  1075. }
  1076. // Bones
  1077. const fallbacks = new EffectFallbacks();
  1078. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  1079. attribs.push(VertexBuffer.MatricesIndicesKind);
  1080. attribs.push(VertexBuffer.MatricesWeightsKind);
  1081. if (mesh.numBoneInfluencers > 4) {
  1082. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  1083. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  1084. }
  1085. const skeleton = mesh.skeleton;
  1086. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  1087. if (mesh.numBoneInfluencers > 0) {
  1088. fallbacks.addCPUSkinningFallback(0, mesh);
  1089. }
  1090. if (skeleton.isUsingTextureForMatrices) {
  1091. defines.push("#define BONETEXTURE");
  1092. } else {
  1093. defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
  1094. }
  1095. } else {
  1096. defines.push("#define NUM_BONE_INFLUENCERS 0");
  1097. }
  1098. // Morph targets
  1099. var manager = (<Mesh>mesh).morphTargetManager;
  1100. let morphInfluencers = 0;
  1101. if (manager) {
  1102. if (manager.numInfluencers > 0) {
  1103. defines.push("#define MORPHTARGETS");
  1104. morphInfluencers = manager.numInfluencers;
  1105. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  1106. MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);
  1107. }
  1108. }
  1109. // ClipPlanes
  1110. const scene = this._scene;
  1111. if (scene.clipPlane) {
  1112. defines.push("#define CLIPPLANE");
  1113. }
  1114. if (scene.clipPlane2) {
  1115. defines.push("#define CLIPPLANE2");
  1116. }
  1117. if (scene.clipPlane3) {
  1118. defines.push("#define CLIPPLANE3");
  1119. }
  1120. if (scene.clipPlane4) {
  1121. defines.push("#define CLIPPLANE4");
  1122. }
  1123. if (scene.clipPlane5) {
  1124. defines.push("#define CLIPPLANE5");
  1125. }
  1126. if (scene.clipPlane6) {
  1127. defines.push("#define CLIPPLANE6");
  1128. }
  1129. // Instances
  1130. if (useInstances) {
  1131. defines.push("#define INSTANCES");
  1132. MaterialHelper.PushAttributesForInstances(attribs);
  1133. }
  1134. if (this.customShaderOptions) {
  1135. if (this.customShaderOptions.defines) {
  1136. for (var define of this.customShaderOptions.defines) {
  1137. if (defines.indexOf(define) === -1) {
  1138. defines.push(define);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. // Point light
  1144. if (this._light.needCube()) {
  1145. defines.push("#define USEDISTANCE");
  1146. }
  1147. this._isReadyCustomDefines(defines, subMesh, useInstances);
  1148. // Get correct effect
  1149. var join = defines.join("\n");
  1150. if (this._cachedDefines !== join) {
  1151. this._cachedDefines = join;
  1152. let shaderName = "shadowMap";
  1153. let uniforms = ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences", "boneTextureWidth",
  1154. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6"];
  1155. let samplers = ["diffuseSampler", "boneSampler"];
  1156. // Custom shader?
  1157. if (this.customShaderOptions) {
  1158. shaderName = this.customShaderOptions.shaderName;
  1159. if (this.customShaderOptions.attributes) {
  1160. for (var attrib of this.customShaderOptions.attributes) {
  1161. if (attribs.indexOf(attrib) === -1) {
  1162. attribs.push(attrib);
  1163. }
  1164. }
  1165. }
  1166. if (this.customShaderOptions.uniforms) {
  1167. for (var uniform of this.customShaderOptions.uniforms) {
  1168. if (uniforms.indexOf(uniform) === -1) {
  1169. uniforms.push(uniform);
  1170. }
  1171. }
  1172. }
  1173. if (this.customShaderOptions.samplers) {
  1174. for (var sampler of this.customShaderOptions.samplers) {
  1175. if (samplers.indexOf(sampler) === -1) {
  1176. samplers.push(sampler);
  1177. }
  1178. }
  1179. }
  1180. }
  1181. this._effect = this._scene.getEngine().createEffect(shaderName,
  1182. attribs, uniforms,
  1183. samplers, join,
  1184. fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  1185. }
  1186. if (!this._effect.isReady()) {
  1187. return false;
  1188. }
  1189. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  1190. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  1191. this._initializeBlurRTTAndPostProcesses();
  1192. }
  1193. }
  1194. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  1195. return false;
  1196. }
  1197. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  1198. return false;
  1199. }
  1200. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  1201. return false;
  1202. }
  1203. return true;
  1204. }
  1205. /**
  1206. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  1207. * @param defines Defines of the material we want to update
  1208. * @param lightIndex Index of the light in the enabled light list of the material
  1209. */
  1210. public prepareDefines(defines: any, lightIndex: number): void {
  1211. var scene = this._scene;
  1212. var light = this._light;
  1213. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  1214. return;
  1215. }
  1216. defines["SHADOW" + lightIndex] = true;
  1217. if (this.useContactHardeningShadow) {
  1218. defines["SHADOWPCSS" + lightIndex] = true;
  1219. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  1220. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  1221. }
  1222. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  1223. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  1224. }
  1225. // else default to high.
  1226. }
  1227. else if (this.usePercentageCloserFiltering) {
  1228. defines["SHADOWPCF" + lightIndex] = true;
  1229. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  1230. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  1231. }
  1232. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  1233. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  1234. }
  1235. // else default to high.
  1236. }
  1237. else if (this.usePoissonSampling) {
  1238. defines["SHADOWPOISSON" + lightIndex] = true;
  1239. }
  1240. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  1241. defines["SHADOWESM" + lightIndex] = true;
  1242. }
  1243. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  1244. defines["SHADOWCLOSEESM" + lightIndex] = true;
  1245. }
  1246. if (light.needCube()) {
  1247. defines["SHADOWCUBE" + lightIndex] = true;
  1248. }
  1249. }
  1250. /**
  1251. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  1252. * defined in the generator but impacting the effect).
  1253. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  1254. * @param effect The effect we are binfing the information for
  1255. */
  1256. public bindShadowLight(lightIndex: string, effect: Effect): void {
  1257. const light = this._light;
  1258. const scene = this._scene;
  1259. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  1260. return;
  1261. }
  1262. const camera = scene.activeCamera;
  1263. if (!camera) {
  1264. return;
  1265. }
  1266. const shadowMap = this.getShadowMap();
  1267. if (!shadowMap) {
  1268. return;
  1269. }
  1270. if (!light.needCube()) {
  1271. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  1272. }
  1273. // Only PCF uses depth stencil texture.
  1274. if (this._filter === ShadowGenerator.FILTER_PCF) {
  1275. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  1276. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  1277. }
  1278. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  1279. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  1280. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  1281. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  1282. }
  1283. else {
  1284. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  1285. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  1286. }
  1287. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  1288. }
  1289. /**
  1290. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  1291. * (eq to shadow prjection matrix * light transform matrix)
  1292. * @returns The transform matrix used to create the shadow map
  1293. */
  1294. public getTransformMatrix(): Matrix {
  1295. var scene = this._scene;
  1296. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  1297. return this._transformMatrix;
  1298. }
  1299. this._currentRenderID = scene.getRenderId();
  1300. this._currentFaceIndexCache = this._currentFaceIndex;
  1301. var lightPosition = this._light.position;
  1302. if (this._light.computeTransformedInformation()) {
  1303. lightPosition = this._light.transformedPosition;
  1304. }
  1305. Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  1306. if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {
  1307. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  1308. }
  1309. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  1310. this._cachedPosition.copyFrom(lightPosition);
  1311. this._cachedDirection.copyFrom(this._lightDirection);
  1312. Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
  1313. let shadowMap = this.getShadowMap();
  1314. if (shadowMap) {
  1315. let renderList = shadowMap.renderList;
  1316. if (renderList) {
  1317. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  1318. }
  1319. }
  1320. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  1321. }
  1322. return this._transformMatrix;
  1323. }
  1324. /**
  1325. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  1326. * Cube and 2D textures for instance.
  1327. */
  1328. public recreateShadowMap(): void {
  1329. let shadowMap = this._shadowMap;
  1330. if (!shadowMap) {
  1331. return;
  1332. }
  1333. // Track render list.
  1334. var renderList = shadowMap.renderList;
  1335. // Clean up existing data.
  1336. this._disposeRTTandPostProcesses();
  1337. // Reinitializes.
  1338. this._initializeGenerator();
  1339. // Reaffect the filter to ensure a correct fallback if necessary.
  1340. this.filter = this.filter;
  1341. // Reaffect the filter.
  1342. this._applyFilterValues();
  1343. // Reaffect Render List.
  1344. this._shadowMap!.renderList = renderList;
  1345. }
  1346. protected _disposeBlurPostProcesses(): void {
  1347. if (this._shadowMap2) {
  1348. this._shadowMap2.dispose();
  1349. this._shadowMap2 = null;
  1350. }
  1351. if (this._boxBlurPostprocess) {
  1352. this._boxBlurPostprocess.dispose();
  1353. this._boxBlurPostprocess = null;
  1354. }
  1355. if (this._kernelBlurXPostprocess) {
  1356. this._kernelBlurXPostprocess.dispose();
  1357. this._kernelBlurXPostprocess = null;
  1358. }
  1359. if (this._kernelBlurYPostprocess) {
  1360. this._kernelBlurYPostprocess.dispose();
  1361. this._kernelBlurYPostprocess = null;
  1362. }
  1363. this._blurPostProcesses = [];
  1364. }
  1365. protected _disposeRTTandPostProcesses(): void {
  1366. if (this._shadowMap) {
  1367. this._shadowMap.dispose();
  1368. this._shadowMap = null;
  1369. }
  1370. this._disposeBlurPostProcesses();
  1371. }
  1372. /**
  1373. * Disposes the ShadowGenerator.
  1374. * Returns nothing.
  1375. */
  1376. public dispose(): void {
  1377. this._disposeRTTandPostProcesses();
  1378. if (this._light) {
  1379. this._light._shadowGenerator = null;
  1380. this._light._markMeshesAsLightDirty();
  1381. }
  1382. this.onBeforeShadowMapRenderMeshObservable.clear();
  1383. this.onBeforeShadowMapRenderObservable.clear();
  1384. this.onAfterShadowMapRenderMeshObservable.clear();
  1385. this.onAfterShadowMapRenderObservable.clear();
  1386. }
  1387. /**
  1388. * Serializes the shadow generator setup to a json object.
  1389. * @returns The serialized JSON object
  1390. */
  1391. public serialize(): any {
  1392. var serializationObject: any = {};
  1393. var shadowMap = this.getShadowMap();
  1394. if (!shadowMap) {
  1395. return serializationObject;
  1396. }
  1397. serializationObject.className = this.getClassName();
  1398. serializationObject.lightId = this._light.id;
  1399. serializationObject.mapSize = shadowMap.getRenderSize();
  1400. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  1401. serializationObject.darkness = this.getDarkness();
  1402. serializationObject.transparencyShadow = this._transparencyShadow;
  1403. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  1404. serializationObject.bias = this.bias;
  1405. serializationObject.normalBias = this.normalBias;
  1406. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  1407. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  1408. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  1409. serializationObject.filteringQuality = this.filteringQuality;
  1410. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  1411. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  1412. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  1413. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  1414. serializationObject.usePoissonSampling = this.usePoissonSampling;
  1415. serializationObject.depthScale = this.depthScale;
  1416. serializationObject.blurBoxOffset = this.blurBoxOffset;
  1417. serializationObject.blurKernel = this.blurKernel;
  1418. serializationObject.blurScale = this.blurScale;
  1419. serializationObject.useKernelBlur = this.useKernelBlur;
  1420. serializationObject.renderList = [];
  1421. if (shadowMap.renderList) {
  1422. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  1423. var mesh = shadowMap.renderList[meshIndex];
  1424. serializationObject.renderList.push(mesh.id);
  1425. }
  1426. }
  1427. return serializationObject;
  1428. }
  1429. /**
  1430. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  1431. * @param parsedShadowGenerator The JSON object to parse
  1432. * @param scene The scene to create the shadow map for
  1433. * @param constr A function that builds a shadow generator or undefined to create an instance of the default shadow generator
  1434. * @returns The parsed shadow generator
  1435. */
  1436. public static Parse(parsedShadowGenerator: any, scene: Scene, constr?: (mapSize: number, light: IShadowLight) => ShadowGenerator): ShadowGenerator {
  1437. var light = <IShadowLight>scene.getLightByID(parsedShadowGenerator.lightId);
  1438. var shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light) : new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  1439. var shadowMap = shadowGenerator.getShadowMap();
  1440. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  1441. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  1442. meshes.forEach(function(mesh) {
  1443. if (!shadowMap) {
  1444. return;
  1445. }
  1446. if (!shadowMap.renderList) {
  1447. shadowMap.renderList = [];
  1448. }
  1449. shadowMap.renderList.push(mesh);
  1450. });
  1451. }
  1452. shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly;
  1453. if (parsedShadowGenerator.darkness !== undefined) {
  1454. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  1455. }
  1456. if (parsedShadowGenerator.transparencyShadow) {
  1457. shadowGenerator.setTransparencyShadow(true);
  1458. }
  1459. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  1460. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  1461. }
  1462. if (parsedShadowGenerator.bias !== undefined) {
  1463. shadowGenerator.bias = parsedShadowGenerator.bias;
  1464. }
  1465. if (parsedShadowGenerator.normalBias !== undefined) {
  1466. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  1467. }
  1468. if (parsedShadowGenerator.usePercentageCloserFiltering) {
  1469. shadowGenerator.usePercentageCloserFiltering = true;
  1470. } else if (parsedShadowGenerator.useContactHardeningShadow) {
  1471. shadowGenerator.useContactHardeningShadow = true;
  1472. } else if (parsedShadowGenerator.usePoissonSampling) {
  1473. shadowGenerator.usePoissonSampling = true;
  1474. } else if (parsedShadowGenerator.useExponentialShadowMap) {
  1475. shadowGenerator.useExponentialShadowMap = true;
  1476. } else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  1477. shadowGenerator.useBlurExponentialShadowMap = true;
  1478. } else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  1479. shadowGenerator.useCloseExponentialShadowMap = true;
  1480. } else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  1481. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  1482. } else
  1483. // Backward compat
  1484. if (parsedShadowGenerator.useVarianceShadowMap) {
  1485. shadowGenerator.useExponentialShadowMap = true;
  1486. } else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  1487. shadowGenerator.useBlurExponentialShadowMap = true;
  1488. }
  1489. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== undefined) {
  1490. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  1491. }
  1492. if (parsedShadowGenerator.filteringQuality !== undefined) {
  1493. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  1494. }
  1495. if (parsedShadowGenerator.depthScale) {
  1496. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  1497. }
  1498. if (parsedShadowGenerator.blurScale) {
  1499. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  1500. }
  1501. if (parsedShadowGenerator.blurBoxOffset) {
  1502. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  1503. }
  1504. if (parsedShadowGenerator.useKernelBlur) {
  1505. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  1506. }
  1507. if (parsedShadowGenerator.blurKernel) {
  1508. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  1509. }
  1510. return shadowGenerator;
  1511. }
  1512. }