babylon.volumetricLightScatteringPostProcess.js 17 KB

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