babylon.volumetricLightScatteringPostProcess.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  10. var VolumetricLightScatteringPostProcess = (function (_super) {
  11. __extends(VolumetricLightScatteringPostProcess, _super);
  12. /**
  13. * @constructor
  14. * @param {string} name - The post-process name
  15. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  16. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  17. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  18. * @param {number} samples - The post-process quality, default 100
  19. * @param {number} samplingMode - The post-process filtering mode
  20. * @param {BABYLON.Engine} engine - The babylon engine
  21. * @param {boolean} reusable - If the post-process is reusable
  22. */
  23. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  24. var _this = this;
  25. if (samples === void 0) { samples = 100; }
  26. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  27. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28. this._screenCoordinates = BABYLON.Vector2.Zero();
  29. /**
  30. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31. * @type {boolean}
  32. */
  33. this.useCustomMeshPosition = false;
  34. /**
  35. * If the post-process should inverse the light scattering direction
  36. * @type {boolean}
  37. */
  38. this.invert = true;
  39. /**
  40. * Array containing the excluded meshes not rendered in the internal pass
  41. */
  42. this.excludedMeshes = new Array();
  43. this.exposure = 0.3;
  44. this.decay = 0.96815;
  45. this.weight = 0.58767;
  46. this.density = 0.926;
  47. var scene = camera.getScene();
  48. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  49. // Configure mesh
  50. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  51. // Configure
  52. this._createPass(scene, ratio.passRatio || ratio);
  53. this.onApply = function (effect) {
  54. _this._updateMeshScreenCoordinates(scene);
  55. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  56. effect.setFloat("exposure", _this.exposure);
  57. effect.setFloat("decay", _this.decay);
  58. effect.setFloat("weight", _this.weight);
  59. effect.setFloat("density", _this.density);
  60. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  61. };
  62. }
  63. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  64. var mesh = subMesh.getMesh();
  65. var defines = [];
  66. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67. var material = subMesh.getMaterial();
  68. var needUV = false;
  69. // Render this.mesh as default
  70. if (mesh === this.mesh) {
  71. defines.push("#define BASIC_RENDER");
  72. defines.push("#define NEED_UV");
  73. needUV = true;
  74. }
  75. // Alpha test
  76. if (material) {
  77. if (material.needAlphaTesting() || mesh === this.mesh)
  78. defines.push("#define ALPHATEST");
  79. if (material.opacityTexture !== undefined) {
  80. defines.push("#define OPACITY");
  81. if (material.opacityTexture.getAlphaFromRGB)
  82. defines.push("#define OPACITYRGB");
  83. if (!needUV)
  84. defines.push("#define NEED_UV");
  85. }
  86. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87. attribs.push(BABYLON.VertexBuffer.UVKind);
  88. defines.push("#define UV1");
  89. }
  90. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92. defines.push("#define UV2");
  93. }
  94. }
  95. // Bones
  96. if (mesh.useBones) {
  97. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  98. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  99. defines.push("#define BONES");
  100. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  101. }
  102. // Instances
  103. if (useInstances) {
  104. defines.push("#define INSTANCES");
  105. attribs.push("world0");
  106. attribs.push("world1");
  107. attribs.push("world2");
  108. attribs.push("world3");
  109. }
  110. // Get correct effect
  111. var join = defines.join("\n");
  112. if (this._cachedDefines !== join) {
  113. this._cachedDefines = join;
  114. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  115. }
  116. return this._volumetricLightScatteringPass.isReady();
  117. };
  118. /**
  119. * Sets the new light position for light scattering effect
  120. * @param {BABYLON.Vector3} The new custom light position
  121. */
  122. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  123. this._customMeshPosition = position;
  124. };
  125. /**
  126. * Returns the light position for light scattering effect
  127. * @return {BABYLON.Vector3} The custom light position
  128. */
  129. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  130. return this._customMeshPosition;
  131. };
  132. /**
  133. * Disposes the internal assets and detaches the post-process from the camera
  134. */
  135. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  136. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  137. if (rttIndex !== -1) {
  138. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  139. }
  140. this._volumetricLightScatteringRTT.dispose();
  141. _super.prototype.dispose.call(this, camera);
  142. };
  143. /**
  144. * Returns the render target texture used by the post-process
  145. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  146. */
  147. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  148. return this._volumetricLightScatteringRTT;
  149. };
  150. // Private methods
  151. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  152. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  153. return true;
  154. }
  155. return false;
  156. };
  157. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  158. var _this = this;
  159. var engine = scene.getEngine();
  160. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  161. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  162. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  163. this._volumetricLightScatteringRTT.renderList = null;
  164. this._volumetricLightScatteringRTT.renderParticles = false;
  165. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  166. // Custom render function for submeshes
  167. var renderSubMesh = function (subMesh) {
  168. var mesh = subMesh.getRenderingMesh();
  169. if (_this._meshExcluded(mesh)) {
  170. return;
  171. }
  172. var scene = mesh.getScene();
  173. var engine = scene.getEngine();
  174. // Culling
  175. engine.setState(subMesh.getMaterial().backFaceCulling);
  176. // Managing instances
  177. var batch = mesh._getInstancesRenderList(subMesh._id);
  178. if (batch.mustReturn) {
  179. return;
  180. }
  181. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  182. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  183. engine.enableEffect(_this._volumetricLightScatteringPass);
  184. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  185. var material = subMesh.getMaterial();
  186. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  187. // Alpha test
  188. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  189. var alphaTexture = material.getAlphaTestTexture();
  190. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  191. if (alphaTexture) {
  192. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  193. }
  194. if (material.opacityTexture !== undefined) {
  195. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  196. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  197. }
  198. }
  199. // Bones
  200. if (mesh.useBones) {
  201. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  202. }
  203. // Draw
  204. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  205. }
  206. };
  207. // Render target texture callbacks
  208. var savedSceneClearColor;
  209. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  210. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  211. savedSceneClearColor = scene.clearColor;
  212. scene.clearColor = sceneClearColor;
  213. };
  214. this._volumetricLightScatteringRTT.onAfterRender = function () {
  215. scene.clearColor = savedSceneClearColor;
  216. };
  217. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  218. var engine = scene.getEngine();
  219. var index;
  220. for (index = 0; index < opaqueSubMeshes.length; index++) {
  221. renderSubMesh(opaqueSubMeshes.data[index]);
  222. }
  223. engine.setAlphaTesting(true);
  224. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  225. renderSubMesh(alphaTestSubMeshes.data[index]);
  226. }
  227. engine.setAlphaTesting(false);
  228. if (transparentSubMeshes.length) {
  229. // Sort sub meshes
  230. for (index = 0; index < transparentSubMeshes.length; index++) {
  231. var submesh = transparentSubMeshes.data[index];
  232. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  233. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  234. }
  235. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  236. sortedArray.sort(function (a, b) {
  237. // Alpha index first
  238. if (a._alphaIndex > b._alphaIndex) {
  239. return 1;
  240. }
  241. if (a._alphaIndex < b._alphaIndex) {
  242. return -1;
  243. }
  244. // Then distance to camera
  245. if (a._distanceToCamera < b._distanceToCamera) {
  246. return 1;
  247. }
  248. if (a._distanceToCamera > b._distanceToCamera) {
  249. return -1;
  250. }
  251. return 0;
  252. });
  253. // Render sub meshes
  254. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  255. for (index = 0; index < sortedArray.length; index++) {
  256. renderSubMesh(sortedArray[index]);
  257. }
  258. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  259. }
  260. };
  261. };
  262. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  263. var transform = scene.getTransformMatrix();
  264. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  265. this._screenCoordinates.x = pos.x / this._viewPort.width;
  266. this._screenCoordinates.y = pos.y / this._viewPort.height;
  267. if (this.invert)
  268. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  269. };
  270. // Static methods
  271. /**
  272. * Creates a default mesh for the Volumeric Light Scattering post-process
  273. * @param {string} The mesh name
  274. * @param {BABYLON.Scene} The scene where to create the mesh
  275. * @return {BABYLON.Mesh} the default mesh
  276. */
  277. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  278. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  279. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  280. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  281. return mesh;
  282. };
  283. return VolumetricLightScatteringPostProcess;
  284. })(BABYLON.PostProcess);
  285. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  286. })(BABYLON || (BABYLON = {}));
  287. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map