babylon.shadowGenerator.js 21 KB

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