babylon.shadowGenerator.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. module BABYLON {
  2. export class ShadowGenerator {
  3. private static _FILTER_NONE = 0;
  4. private static _FILTER_VARIANCESHADOWMAP = 1;
  5. private static _FILTER_POISSONSAMPLING = 2;
  6. private static _FILTER_BLURVARIANCESHADOWMAP = 3;
  7. // Static
  8. public static get FILTER_NONE(): number {
  9. return ShadowGenerator._FILTER_NONE;
  10. }
  11. public static get FILTER_VARIANCESHADOWMAP(): number {
  12. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  13. }
  14. public static get FILTER_POISSONSAMPLING(): number {
  15. return ShadowGenerator._FILTER_POISSONSAMPLING;
  16. }
  17. public static get FILTER_BLURVARIANCESHADOWMAP(): number {
  18. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  19. }
  20. // Members
  21. private _filter = ShadowGenerator.FILTER_NONE;
  22. public blurScale = 2;
  23. private _blurBoxOffset = 0;
  24. private _bias = 0.00005;
  25. private _lightDirection = Vector3.Zero();
  26. public get bias(): number {
  27. return this._bias;
  28. }
  29. public set bias(bias: number) {
  30. this._bias = bias;
  31. }
  32. public get blurBoxOffset(): number {
  33. return this._blurBoxOffset;
  34. }
  35. public set blurBoxOffset(value: number) {
  36. if (this._blurBoxOffset === value) {
  37. return;
  38. }
  39. this._blurBoxOffset = value;
  40. if (this._boxBlurPostprocess) {
  41. this._boxBlurPostprocess.dispose();
  42. }
  43. this._boxBlurPostprocess = new PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  44. this._boxBlurPostprocess.onApply = effect => {
  45. effect.setFloat2("screenSize", this._mapSize / this.blurScale, this._mapSize / this.blurScale);
  46. };
  47. }
  48. public get filter(): number {
  49. return this._filter;
  50. }
  51. public set filter(value: number) {
  52. if (this._filter === value) {
  53. return;
  54. }
  55. this._filter = value;
  56. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  57. this._shadowMap.anisotropicFilteringLevel = 16;
  58. this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  59. } else {
  60. this._shadowMap.anisotropicFilteringLevel = 1;
  61. this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
  62. }
  63. }
  64. public get useVarianceShadowMap(): boolean {
  65. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  66. }
  67. public set useVarianceShadowMap(value: boolean) {
  68. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  69. }
  70. public get usePoissonSampling(): boolean {
  71. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  72. (!this._light.supportsVSM() && (
  73. this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  74. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP
  75. ));
  76. }
  77. public set usePoissonSampling(value: boolean) {
  78. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  79. }
  80. public get useBlurVarianceShadowMap(): boolean {
  81. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  82. }
  83. public set useBlurVarianceShadowMap(value: boolean) {
  84. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  85. }
  86. private _light: IShadowLight;
  87. private _scene: Scene;
  88. private _shadowMap: RenderTargetTexture;
  89. private _shadowMap2: RenderTargetTexture;
  90. private _darkness = 0;
  91. private _transparencyShadow = false;
  92. private _effect: Effect;
  93. private _viewMatrix = Matrix.Zero();
  94. private _projectionMatrix = Matrix.Zero();
  95. private _transformMatrix = Matrix.Zero();
  96. private _worldViewProjection = Matrix.Zero();
  97. private _cachedPosition: Vector3;
  98. private _cachedDirection: Vector3;
  99. private _cachedDefines: string;
  100. private _currentRenderID: number;
  101. private _downSamplePostprocess: PassPostProcess;
  102. private _boxBlurPostprocess: PostProcess;
  103. private _mapSize: number;
  104. private _currentFaceIndex = 0;
  105. private _currentFaceIndexCache = 0;
  106. constructor(mapSize: number, light: IShadowLight) {
  107. this._light = light;
  108. this._scene = light.getScene();
  109. this._mapSize = mapSize;
  110. light._shadowGenerator = this;
  111. // Render target
  112. this._shadowMap = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  113. this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
  114. this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
  115. this._shadowMap.anisotropicFilteringLevel = 1;
  116. this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
  117. this._shadowMap.renderParticles = false;
  118. this._shadowMap.onBeforeRender = (faceIndex: number) => {
  119. this._currentFaceIndex = faceIndex;
  120. }
  121. this._shadowMap.onAfterUnbind = () => {
  122. if (!this.useBlurVarianceShadowMap) {
  123. return;
  124. }
  125. if (!this._shadowMap2) {
  126. this._shadowMap2 = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  127. this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
  128. this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
  129. this._shadowMap2.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
  130. this._downSamplePostprocess = new PassPostProcess("downScale", 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  131. this._downSamplePostprocess.onApply = effect => {
  132. effect.setTexture("textureSampler", this._shadowMap);
  133. };
  134. this.blurBoxOffset = 1;
  135. }
  136. this._scene.postProcessManager.directRender([this._downSamplePostprocess, this._boxBlurPostprocess], this._shadowMap2.getInternalTexture());
  137. }
  138. // Custom render function
  139. var renderSubMesh = (subMesh: SubMesh): void => {
  140. var mesh = subMesh.getRenderingMesh();
  141. var scene = this._scene;
  142. var engine = scene.getEngine();
  143. // Culling
  144. engine.setState(subMesh.getMaterial().backFaceCulling);
  145. // Managing instances
  146. var batch = mesh._getInstancesRenderList(subMesh._id);
  147. if (batch.mustReturn) {
  148. return;
  149. }
  150. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  151. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  152. engine.enableEffect(this._effect);
  153. mesh._bind(subMesh, this._effect, Material.TriangleFillMode);
  154. var material = subMesh.getMaterial();
  155. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  156. // Alpha test
  157. if (material && material.needAlphaTesting()) {
  158. var alphaTexture = material.getAlphaTestTexture();
  159. this._effect.setTexture("diffuseSampler", alphaTexture);
  160. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  161. }
  162. // Bones
  163. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  164. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  165. }
  166. // Draw
  167. mesh._processRendering(subMesh, this._effect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  168. (isInstance, world) => this._effect.setMatrix("world", world));
  169. } else {
  170. // Need to reset refresh rate of the shadowMap
  171. this._shadowMap.resetRefreshCounter();
  172. }
  173. };
  174. this._shadowMap.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
  175. var index: number;
  176. for (index = 0; index < opaqueSubMeshes.length; index++) {
  177. renderSubMesh(opaqueSubMeshes.data[index]);
  178. }
  179. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  180. renderSubMesh(alphaTestSubMeshes.data[index]);
  181. }
  182. if (this._transparencyShadow) {
  183. for (index = 0; index < transparentSubMeshes.length; index++) {
  184. renderSubMesh(transparentSubMeshes.data[index]);
  185. }
  186. }
  187. };
  188. this._shadowMap.onClear = (engine: Engine) => {
  189. if (this.useBlurVarianceShadowMap || this.useVarianceShadowMap) {
  190. engine.clear(new Color4(0, 0, 0, 0), true, true);
  191. } else {
  192. engine.clear(new Color4(1.0, 1.0, 1.0, 1.0), true, true);
  193. }
  194. }
  195. }
  196. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  197. var defines = [];
  198. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  199. defines.push("#define VSM");
  200. }
  201. var attribs = [VertexBuffer.PositionKind];
  202. var mesh = subMesh.getMesh();
  203. var material = subMesh.getMaterial();
  204. // Alpha test
  205. if (material && material.needAlphaTesting()) {
  206. defines.push("#define ALPHATEST");
  207. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  208. attribs.push(VertexBuffer.UVKind);
  209. defines.push("#define UV1");
  210. }
  211. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  212. attribs.push(VertexBuffer.UV2Kind);
  213. defines.push("#define UV2");
  214. }
  215. }
  216. // Bones
  217. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  218. attribs.push(VertexBuffer.MatricesIndicesKind);
  219. attribs.push(VertexBuffer.MatricesWeightsKind);
  220. if (mesh.numBoneInfluencers > 4) {
  221. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  222. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  223. }
  224. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  225. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  226. } else {
  227. defines.push("#define NUM_BONE_INFLUENCERS 0");
  228. }
  229. // Instances
  230. if (useInstances) {
  231. defines.push("#define INSTANCES");
  232. attribs.push("world0");
  233. attribs.push("world1");
  234. attribs.push("world2");
  235. attribs.push("world3");
  236. }
  237. // Get correct effect
  238. var join = defines.join("\n");
  239. if (this._cachedDefines !== join) {
  240. this._cachedDefines = join;
  241. this._effect = this._scene.getEngine().createEffect("shadowMap",
  242. attribs,
  243. ["world", "mBones", "viewProjection", "diffuseMatrix"],
  244. ["diffuseSampler"], join);
  245. }
  246. return this._effect.isReady();
  247. }
  248. public getShadowMap(): RenderTargetTexture {
  249. return this._shadowMap;
  250. }
  251. public getShadowMapForRendering(): RenderTargetTexture {
  252. if (this._shadowMap2) {
  253. return this._shadowMap2;
  254. }
  255. return this._shadowMap;
  256. }
  257. public getLight(): IShadowLight {
  258. return this._light;
  259. }
  260. // Methods
  261. public getTransformMatrix(): Matrix {
  262. var scene = this._scene;
  263. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  264. return this._transformMatrix;
  265. }
  266. this._currentRenderID = scene.getRenderId();
  267. this._currentFaceIndexCache = this._currentFaceIndex;
  268. var lightPosition = this._light.position;
  269. Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  270. if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {
  271. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  272. }
  273. if (this._light.computeTransformedPosition()) {
  274. lightPosition = this._light.transformedPosition;
  275. }
  276. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  277. this._cachedPosition = lightPosition.clone();
  278. this._cachedDirection = this._lightDirection.clone();
  279. Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), Vector3.Up(), this._viewMatrix);
  280. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  281. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  282. }
  283. return this._transformMatrix;
  284. }
  285. public getDarkness(): number {
  286. return this._darkness;
  287. }
  288. public setDarkness(darkness: number): void {
  289. if (darkness >= 1.0)
  290. this._darkness = 1.0;
  291. else if (darkness <= 0.0)
  292. this._darkness = 0.0;
  293. else
  294. this._darkness = darkness;
  295. }
  296. public setTransparencyShadow(hasShadow: boolean): void {
  297. this._transparencyShadow = hasShadow;
  298. }
  299. private _packHalf(depth: number): Vector2 {
  300. var scale = depth * 255.0;
  301. var fract = scale - Math.floor(scale);
  302. return new Vector2(depth - fract / 255.0, fract);
  303. }
  304. public dispose(): void {
  305. this._shadowMap.dispose();
  306. if (this._shadowMap2) {
  307. this._shadowMap2.dispose();
  308. }
  309. if (this._downSamplePostprocess) {
  310. this._downSamplePostprocess.dispose();
  311. }
  312. if (this._boxBlurPostprocess) {
  313. this._boxBlurPostprocess.dispose();
  314. }
  315. }
  316. public serialize(): any {
  317. var serializationObject: any = {};
  318. serializationObject.lightId = this._light.id;
  319. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  320. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  321. serializationObject.usePoissonSampling = this.usePoissonSampling;
  322. serializationObject.renderList = [];
  323. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  324. var mesh = this.getShadowMap().renderList[meshIndex];
  325. serializationObject.renderList.push(mesh.id);
  326. }
  327. return serializationObject;
  328. }
  329. public static ParseShadowGenerator(parsedShadowGenerator: any, scene: Scene): ShadowGenerator {
  330. //casting to point light, as light is missing the position attr and typescript complains.
  331. var light = <PointLight>scene.getLightByID(parsedShadowGenerator.lightId);
  332. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  333. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  334. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  335. shadowGenerator.getShadowMap().renderList.push(mesh);
  336. }
  337. if (parsedShadowGenerator.usePoissonSampling) {
  338. shadowGenerator.usePoissonSampling = true;
  339. } else if (parsedShadowGenerator.useVarianceShadowMap) {
  340. shadowGenerator.useVarianceShadowMap = true;
  341. } else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  342. shadowGenerator.useBlurVarianceShadowMap = true;
  343. if (parsedShadowGenerator.blurScale) {
  344. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  345. }
  346. if (parsedShadowGenerator.blurBoxOffset) {
  347. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  348. }
  349. }
  350. if (parsedShadowGenerator.bias !== undefined) {
  351. shadowGenerator.bias = parsedShadowGenerator.bias;
  352. }
  353. return shadowGenerator;
  354. }
  355. }
  356. }