babylon.shadowGenerator.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. public get bias(): number {
  26. return this._bias;
  27. }
  28. public set bias(bias: number) {
  29. this._bias = bias;
  30. }
  31. public get blurBoxOffset(): number {
  32. return this._blurBoxOffset;
  33. }
  34. public set blurBoxOffset(value: number) {
  35. if (this._blurBoxOffset === value) {
  36. return;
  37. }
  38. this._blurBoxOffset = value;
  39. if (this._boxBlurPostprocess) {
  40. this._boxBlurPostprocess.dispose();
  41. }
  42. this._boxBlurPostprocess = new PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  43. this._boxBlurPostprocess.onApply = effect => {
  44. effect.setFloat2("screenSize", this._mapSize / this.blurScale, this._mapSize / this.blurScale);
  45. };
  46. }
  47. public get filter(): number {
  48. return this._filter;
  49. }
  50. public set filter(value: number) {
  51. if (this._filter === value) {
  52. return;
  53. }
  54. this._filter = value;
  55. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  56. this._shadowMap.anisotropicFilteringLevel = 16;
  57. this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  58. } else {
  59. this._shadowMap.anisotropicFilteringLevel = 1;
  60. this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
  61. }
  62. }
  63. public get useVarianceShadowMap(): boolean {
  64. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  65. }
  66. public set useVarianceShadowMap(value: boolean) {
  67. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  68. }
  69. public get usePoissonSampling(): boolean {
  70. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  71. (!this._light.supportsVSM() && (
  72. this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  73. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP
  74. ));
  75. }
  76. public set usePoissonSampling(value: boolean) {
  77. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  78. }
  79. public get useBlurVarianceShadowMap(): boolean {
  80. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  81. }
  82. public set useBlurVarianceShadowMap(value: boolean) {
  83. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  84. }
  85. private _light: IShadowLight;
  86. private _scene: Scene;
  87. private _shadowMap: RenderTargetTexture;
  88. private _shadowMap2: RenderTargetTexture;
  89. private _darkness = 0;
  90. private _transparencyShadow = false;
  91. private _effect: Effect;
  92. private _viewMatrix = Matrix.Zero();
  93. private _projectionMatrix = Matrix.Zero();
  94. private _transformMatrix = Matrix.Zero();
  95. private _worldViewProjection = Matrix.Zero();
  96. private _cachedPosition: Vector3;
  97. private _cachedDirection: Vector3;
  98. private _cachedDefines: string;
  99. private _currentRenderID: number;
  100. private _downSamplePostprocess: PassPostProcess;
  101. private _boxBlurPostprocess: PostProcess;
  102. private _mapSize: number;
  103. constructor(mapSize: number, light: IShadowLight) {
  104. this._light = light;
  105. this._scene = light.getScene();
  106. this._mapSize = mapSize;
  107. light._shadowGenerator = this;
  108. // Render target
  109. this._shadowMap = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  110. this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;
  111. this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;
  112. this._shadowMap.anisotropicFilteringLevel = 1;
  113. this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);
  114. this._shadowMap.renderParticles = false;
  115. this._shadowMap.onAfterUnbind = () => {
  116. if (!this.useBlurVarianceShadowMap) {
  117. return;
  118. }
  119. if (!this._shadowMap2) {
  120. this._shadowMap2 = new RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  121. this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;
  122. this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;
  123. this._shadowMap2.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
  124. this._downSamplePostprocess = new PassPostProcess("downScale", 1.0 / this.blurScale, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  125. this._downSamplePostprocess.onApply = effect => {
  126. effect.setTexture("textureSampler", this._shadowMap);
  127. };
  128. this.blurBoxOffset = 1;
  129. }
  130. this._scene.postProcessManager.directRender([this._downSamplePostprocess, this._boxBlurPostprocess], this._shadowMap2.getInternalTexture());
  131. }
  132. // Custom render function
  133. var renderSubMesh = (subMesh: SubMesh): void => {
  134. var mesh = subMesh.getRenderingMesh();
  135. var scene = this._scene;
  136. var engine = scene.getEngine();
  137. // Culling
  138. engine.setState(subMesh.getMaterial().backFaceCulling);
  139. // Managing instances
  140. var batch = mesh._getInstancesRenderList(subMesh._id);
  141. if (batch.mustReturn) {
  142. return;
  143. }
  144. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  145. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  146. engine.enableEffect(this._effect);
  147. mesh._bind(subMesh, this._effect, Material.TriangleFillMode);
  148. var material = subMesh.getMaterial();
  149. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  150. // Alpha test
  151. if (material && material.needAlphaTesting()) {
  152. var alphaTexture = material.getAlphaTestTexture();
  153. this._effect.setTexture("diffuseSampler", alphaTexture);
  154. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  155. }
  156. // Bones
  157. if (mesh.useBones) {
  158. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  159. }
  160. // Draw
  161. mesh._processRendering(subMesh, this._effect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  162. (isInstance, world) => this._effect.setMatrix("world", world));
  163. } else {
  164. // Need to reset refresh rate of the shadowMap
  165. this._shadowMap.resetRefreshCounter();
  166. }
  167. };
  168. this._shadowMap.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
  169. var index: number;
  170. for (index = 0; index < opaqueSubMeshes.length; index++) {
  171. renderSubMesh(opaqueSubMeshes.data[index]);
  172. }
  173. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  174. renderSubMesh(alphaTestSubMeshes.data[index]);
  175. }
  176. if (this._transparencyShadow) {
  177. for (index = 0; index < transparentSubMeshes.length; index++) {
  178. renderSubMesh(transparentSubMeshes.data[index]);
  179. }
  180. }
  181. };
  182. this._shadowMap.onClear = (engine: Engine) => {
  183. if (this.useBlurVarianceShadowMap || this.useVarianceShadowMap) {
  184. engine.clear(new Color4(0, 0, 0, 0), true, true);
  185. } else {
  186. engine.clear(new Color4(1.0, 1.0, 1.0, 1.0), true, true);
  187. }
  188. }
  189. }
  190. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  191. var defines = [];
  192. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  193. defines.push("#define VSM");
  194. }
  195. var attribs = [VertexBuffer.PositionKind];
  196. var mesh = subMesh.getMesh();
  197. var material = subMesh.getMaterial();
  198. // Alpha test
  199. if (material && material.needAlphaTesting()) {
  200. defines.push("#define ALPHATEST");
  201. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  202. attribs.push(VertexBuffer.UVKind);
  203. defines.push("#define UV1");
  204. }
  205. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  206. attribs.push(VertexBuffer.UV2Kind);
  207. defines.push("#define UV2");
  208. }
  209. }
  210. // Bones
  211. if (mesh.useBones) {
  212. attribs.push(VertexBuffer.MatricesIndicesKind);
  213. attribs.push(VertexBuffer.MatricesWeightsKind);
  214. defines.push("#define BONES");
  215. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  216. }
  217. // Instances
  218. if (useInstances) {
  219. defines.push("#define INSTANCES");
  220. attribs.push("world0");
  221. attribs.push("world1");
  222. attribs.push("world2");
  223. attribs.push("world3");
  224. }
  225. // Get correct effect
  226. var join = defines.join("\n");
  227. if (this._cachedDefines !== join) {
  228. this._cachedDefines = join;
  229. this._effect = this._scene.getEngine().createEffect("shadowMap",
  230. attribs,
  231. ["world", "mBones", "viewProjection", "diffuseMatrix"],
  232. ["diffuseSampler"], join);
  233. }
  234. return this._effect.isReady();
  235. }
  236. public getShadowMap(): RenderTargetTexture {
  237. return this._shadowMap;
  238. }
  239. public getShadowMapForRendering(): RenderTargetTexture {
  240. if (this._shadowMap2) {
  241. return this._shadowMap2;
  242. }
  243. return this._shadowMap;
  244. }
  245. public getLight(): IShadowLight {
  246. return this._light;
  247. }
  248. // Methods
  249. public getTransformMatrix(): Matrix {
  250. var scene = this._scene;
  251. if (this._currentRenderID === scene.getRenderId()) {
  252. return this._transformMatrix;
  253. }
  254. this._currentRenderID = scene.getRenderId();
  255. var lightPosition = this._light.position;
  256. var lightDirection = this._light.direction;
  257. if (this._light.computeTransformedPosition()) {
  258. lightPosition = this._light.transformedPosition;
  259. }
  260. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  261. this._cachedPosition = lightPosition.clone();
  262. this._cachedDirection = lightDirection.clone();
  263. Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), Vector3.Up(), this._viewMatrix);
  264. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  265. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  266. }
  267. return this._transformMatrix;
  268. }
  269. public getDarkness(): number {
  270. return this._darkness;
  271. }
  272. public setDarkness(darkness: number): void {
  273. if (darkness >= 1.0)
  274. this._darkness = 1.0;
  275. else if (darkness <= 0.0)
  276. this._darkness = 0.0;
  277. else
  278. this._darkness = darkness;
  279. }
  280. public setTransparencyShadow(hasShadow: boolean): void {
  281. this._transparencyShadow = hasShadow;
  282. }
  283. private _packHalf(depth: number): Vector2 {
  284. var scale = depth * 255.0;
  285. var fract = scale - Math.floor(scale);
  286. return new Vector2(depth - fract / 255.0, fract);
  287. }
  288. public dispose(): void {
  289. this._shadowMap.dispose();
  290. if (this._shadowMap2) {
  291. this._shadowMap2.dispose();
  292. }
  293. if (this._downSamplePostprocess) {
  294. this._downSamplePostprocess.dispose();
  295. }
  296. if (this._boxBlurPostprocess) {
  297. this._boxBlurPostprocess.dispose();
  298. }
  299. }
  300. }
  301. }