babylon.volumetricLightScatteringPostProcess.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. var __extends = (this && 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. * Set to true to use the diffuseColor instead of the diffuseTexture
  41. * @type {boolean}
  42. */
  43. this.useDiffuseColor = false;
  44. /**
  45. * Array containing the excluded meshes not rendered in the internal pass
  46. */
  47. this.excludedMeshes = new Array();
  48. /**
  49. * Controls the overall intensity of the post-process
  50. * @type {number}
  51. */
  52. this.exposure = 0.3;
  53. /**
  54. * Dissipates each sample's contribution in range [0, 1]
  55. * @type {number}
  56. */
  57. this.decay = 0.96815;
  58. /**
  59. * Controls the overall intensity of each sample
  60. * @type {number}
  61. */
  62. this.weight = 0.58767;
  63. /**
  64. * Controls the density of each sample
  65. * @type {number}
  66. */
  67. this.density = 0.926;
  68. var scene = camera.getScene();
  69. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  70. // Configure mesh
  71. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  72. // Configure
  73. this._createPass(scene, ratio.passRatio || ratio);
  74. this.onApply = function (effect) {
  75. _this._updateMeshScreenCoordinates(scene);
  76. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77. effect.setFloat("exposure", _this.exposure);
  78. effect.setFloat("decay", _this.decay);
  79. effect.setFloat("weight", _this.weight);
  80. effect.setFloat("density", _this.density);
  81. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  82. };
  83. }
  84. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  85. var mesh = subMesh.getMesh();
  86. var defines = [];
  87. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88. var material = subMesh.getMaterial();
  89. var needUV = false;
  90. // Render this.mesh as default
  91. if (mesh === this.mesh) {
  92. if (this.useDiffuseColor) {
  93. defines.push("#define DIFFUSE_COLOR_RENDER");
  94. }
  95. else if (material) {
  96. if (material.diffuseTexture !== undefined) {
  97. defines.push("#define BASIC_RENDER");
  98. }
  99. else {
  100. defines.push("#define DIFFUSE_COLOR_RENDER");
  101. }
  102. }
  103. defines.push("#define NEED_UV");
  104. needUV = true;
  105. }
  106. // Alpha test
  107. if (material) {
  108. if (material.needAlphaTesting()) {
  109. defines.push("#define ALPHATEST");
  110. }
  111. if (material.opacityTexture !== undefined) {
  112. defines.push("#define OPACITY");
  113. if (material.opacityTexture.getAlphaFromRGB) {
  114. defines.push("#define OPACITYRGB");
  115. }
  116. if (!needUV) {
  117. defines.push("#define NEED_UV");
  118. }
  119. }
  120. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  121. attribs.push(BABYLON.VertexBuffer.UVKind);
  122. defines.push("#define UV1");
  123. }
  124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  125. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  126. defines.push("#define UV2");
  127. }
  128. }
  129. // Bones
  130. if (mesh.useBones) {
  131. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  132. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  133. defines.push("#define BONES");
  134. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  135. }
  136. // Instances
  137. if (useInstances) {
  138. defines.push("#define INSTANCES");
  139. attribs.push("world0");
  140. attribs.push("world1");
  141. attribs.push("world2");
  142. attribs.push("world3");
  143. }
  144. // Get correct effect
  145. var join = defines.join("\n");
  146. if (this._cachedDefines !== join) {
  147. this._cachedDefines = join;
  148. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  149. }
  150. return this._volumetricLightScatteringPass.isReady();
  151. };
  152. /**
  153. * Sets the new light position for light scattering effect
  154. * @param {BABYLON.Vector3} The new custom light position
  155. */
  156. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  157. this._customMeshPosition = position;
  158. };
  159. /**
  160. * Returns the light position for light scattering effect
  161. * @return {BABYLON.Vector3} The custom light position
  162. */
  163. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  164. return this._customMeshPosition;
  165. };
  166. /**
  167. * Disposes the internal assets and detaches the post-process from the camera
  168. */
  169. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  170. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  171. if (rttIndex !== -1) {
  172. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  173. }
  174. this._volumetricLightScatteringRTT.dispose();
  175. _super.prototype.dispose.call(this, camera);
  176. };
  177. /**
  178. * Returns the render target texture used by the post-process
  179. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  180. */
  181. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  182. return this._volumetricLightScatteringRTT;
  183. };
  184. // Private methods
  185. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  186. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  187. return true;
  188. }
  189. return false;
  190. };
  191. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  192. var _this = this;
  193. var engine = scene.getEngine();
  194. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  195. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  196. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  197. this._volumetricLightScatteringRTT.renderList = null;
  198. this._volumetricLightScatteringRTT.renderParticles = false;
  199. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  200. // Custom render function for submeshes
  201. var renderSubMesh = function (subMesh) {
  202. var mesh = subMesh.getRenderingMesh();
  203. if (_this._meshExcluded(mesh)) {
  204. return;
  205. }
  206. var scene = mesh.getScene();
  207. var engine = scene.getEngine();
  208. // Culling
  209. engine.setState(subMesh.getMaterial().backFaceCulling);
  210. // Managing instances
  211. var batch = mesh._getInstancesRenderList(subMesh._id);
  212. if (batch.mustReturn) {
  213. return;
  214. }
  215. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  216. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  217. engine.enableEffect(_this._volumetricLightScatteringPass);
  218. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  219. var material = subMesh.getMaterial();
  220. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  221. // Alpha test
  222. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  223. var alphaTexture = material.getAlphaTestTexture();
  224. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  225. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  226. }
  227. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  228. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  229. if (alphaTexture) {
  230. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  231. }
  232. }
  233. if (material.opacityTexture !== undefined) {
  234. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  235. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  236. }
  237. }
  238. // Bones
  239. if (mesh.useBones) {
  240. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  241. }
  242. // Draw
  243. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  244. }
  245. };
  246. // Render target texture callbacks
  247. var savedSceneClearColor;
  248. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  249. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  250. savedSceneClearColor = scene.clearColor;
  251. scene.clearColor = sceneClearColor;
  252. };
  253. this._volumetricLightScatteringRTT.onAfterRender = function () {
  254. scene.clearColor = savedSceneClearColor;
  255. };
  256. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  257. var engine = scene.getEngine();
  258. var index;
  259. for (index = 0; index < opaqueSubMeshes.length; index++) {
  260. renderSubMesh(opaqueSubMeshes.data[index]);
  261. }
  262. engine.setAlphaTesting(true);
  263. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  264. renderSubMesh(alphaTestSubMeshes.data[index]);
  265. }
  266. engine.setAlphaTesting(false);
  267. if (transparentSubMeshes.length) {
  268. // Sort sub meshes
  269. for (index = 0; index < transparentSubMeshes.length; index++) {
  270. var submesh = transparentSubMeshes.data[index];
  271. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  272. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  273. }
  274. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  275. sortedArray.sort(function (a, b) {
  276. // Alpha index first
  277. if (a._alphaIndex > b._alphaIndex) {
  278. return 1;
  279. }
  280. if (a._alphaIndex < b._alphaIndex) {
  281. return -1;
  282. }
  283. // Then distance to camera
  284. if (a._distanceToCamera < b._distanceToCamera) {
  285. return 1;
  286. }
  287. if (a._distanceToCamera > b._distanceToCamera) {
  288. return -1;
  289. }
  290. return 0;
  291. });
  292. // Render sub meshes
  293. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  294. for (index = 0; index < sortedArray.length; index++) {
  295. renderSubMesh(sortedArray[index]);
  296. }
  297. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  298. }
  299. };
  300. };
  301. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  302. var transform = scene.getTransformMatrix();
  303. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  304. this._screenCoordinates.x = pos.x / this._viewPort.width;
  305. this._screenCoordinates.y = pos.y / this._viewPort.height;
  306. if (this.invert)
  307. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  308. };
  309. // Static methods
  310. /**
  311. * Creates a default mesh for the Volumeric Light Scattering post-process
  312. * @param {string} The mesh name
  313. * @param {BABYLON.Scene} The scene where to create the mesh
  314. * @return {BABYLON.Mesh} the default mesh
  315. */
  316. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  317. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  318. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  319. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  320. return mesh;
  321. };
  322. return VolumetricLightScatteringPostProcess;
  323. })(BABYLON.PostProcess);
  324. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  325. })(BABYLON || (BABYLON = {}));
  326. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map