shadowGenerator.ts 65 KB

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