babylon.volumetricLightScatteringPostProcess.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. module BABYLON {
  2. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  3. export class VolumetricLightScatteringPostProcess extends PostProcess {
  4. // Members
  5. private _volumetricLightScatteringPass: Effect;
  6. private _volumetricLightScatteringRTT: RenderTargetTexture;
  7. private _viewPort: Viewport;
  8. private _screenCoordinates: Vector2 = Vector2.Zero();
  9. private _cachedDefines: string;
  10. private _customMeshPosition: Vector3;
  11. /**
  12. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  13. * @type {boolean}
  14. */
  15. public useCustomMeshPosition: boolean = false;
  16. /**
  17. * If the post-process should inverse the light scattering direction
  18. * @type {boolean}
  19. */
  20. public invert: boolean = true;
  21. /**
  22. * The internal mesh used by the post-process
  23. * @type {boolean}
  24. */
  25. public mesh: Mesh;
  26. /**
  27. * Array containing the excluded meshes not rendered in the internal pass
  28. */
  29. public excludedMeshes = new Array<AbstractMesh>();
  30. public exposure = 0.3;
  31. public decay = 0.96815;
  32. public weight = 0.58767;
  33. public density = 0.926;
  34. /**
  35. * @constructor
  36. * @param {string} name - The post-process name
  37. * @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)
  38. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  39. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  40. * @param {number} samples - The post-process quality, default 100
  41. * @param {number} samplingMode - The post-process filtering mode
  42. * @param {BABYLON.Engine} engine - The babylon engine
  43. * @param {boolean} reusable - If the post-process is reusable
  44. */
  45. constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples: number = 100, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean) {
  46. super(name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  47. var scene = camera.getScene();
  48. this._viewPort = new 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 = (effect: 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. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  64. var mesh = subMesh.getMesh();
  65. var defines = [];
  66. var attribs = [VertexBuffer.PositionKind];
  67. var material: any = subMesh.getMaterial();
  68. var needUV: boolean = 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 (!needUV)
  82. defines.push("#define NEED_UV");
  83. }
  84. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  85. attribs.push(VertexBuffer.UVKind);
  86. defines.push("#define UV1");
  87. }
  88. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  89. attribs.push(VertexBuffer.UV2Kind);
  90. defines.push("#define UV2");
  91. }
  92. }
  93. // Bones
  94. if (mesh.useBones) {
  95. attribs.push(VertexBuffer.MatricesIndicesKind);
  96. attribs.push(VertexBuffer.MatricesWeightsKind);
  97. defines.push("#define BONES");
  98. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  99. }
  100. // Instances
  101. if (useInstances) {
  102. defines.push("#define INSTANCES");
  103. attribs.push("world0");
  104. attribs.push("world1");
  105. attribs.push("world2");
  106. attribs.push("world3");
  107. }
  108. // Get correct effect
  109. var join = defines.join("\n");
  110. if (this._cachedDefines !== join) {
  111. this._cachedDefines = join;
  112. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect(
  113. { vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" },
  114. attribs,
  115. ["world", "mBones", "viewProjection", "diffuseMatrix"],
  116. ["diffuseSampler", "opacitySampler"], join);
  117. }
  118. return this._volumetricLightScatteringPass.isReady();
  119. }
  120. /**
  121. * Sets the new light position for light scattering effect
  122. * @param {BABYLON.Vector3} The new custom light position
  123. */
  124. public setCustomMeshPosition(position: Vector3): void {
  125. this._customMeshPosition = position;
  126. }
  127. /**
  128. * Returns the light position for light scattering effect
  129. * @return {BABYLON.Vector3} The custom light position
  130. */
  131. public getCustomMeshPosition(): Vector3 {
  132. return this._customMeshPosition;
  133. }
  134. /**
  135. * Disposes the internal assets and detaches the post-process from the camera
  136. */
  137. public dispose(camera: Camera): void {
  138. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  139. if (rttIndex !== -1) {
  140. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  141. }
  142. this._volumetricLightScatteringRTT.dispose();
  143. super.dispose(camera);
  144. }
  145. /**
  146. * Returns the render target texture used by the post-process
  147. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  148. */
  149. public getPass(): RenderTargetTexture {
  150. return this._volumetricLightScatteringRTT;
  151. }
  152. // Private methods
  153. private _meshExcluded(mesh: AbstractMesh) {
  154. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  155. return true;
  156. }
  157. return false;
  158. }
  159. private _createPass(scene: Scene, ratio: number): void {
  160. var engine = scene.getEngine();
  161. this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, Engine.TEXTURETYPE_UNSIGNED_INT);
  162. this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;
  163. this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;
  164. this._volumetricLightScatteringRTT.renderList = null;
  165. this._volumetricLightScatteringRTT.renderParticles = false;
  166. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  167. // Custom render function for submeshes
  168. var renderSubMesh = (subMesh: SubMesh): void => {
  169. var mesh = subMesh.getRenderingMesh();
  170. if (this._meshExcluded(mesh)) {
  171. return;
  172. }
  173. var scene = mesh.getScene();
  174. var engine = scene.getEngine();
  175. // Culling
  176. engine.setState(subMesh.getMaterial().backFaceCulling);
  177. // Managing instances
  178. var batch = mesh._getInstancesRenderList(subMesh._id);
  179. if (batch.mustReturn) {
  180. return;
  181. }
  182. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  183. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  184. engine.enableEffect(this._volumetricLightScatteringPass);
  185. mesh._bind(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode);
  186. var material: any = subMesh.getMaterial();
  187. this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  188. // Alpha test
  189. if (material && (mesh === this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  190. var alphaTexture = material.getAlphaTestTexture();
  191. this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  192. if (alphaTexture) {
  193. this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  194. }
  195. if (material.opacityTexture !== undefined)
  196. this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  197. }
  198. // Bones
  199. if (mesh.useBones) {
  200. this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  201. }
  202. // Draw
  203. mesh._processRendering(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  204. (isInstance, world) => this._volumetricLightScatteringPass.setMatrix("world", world));
  205. }
  206. };
  207. // Render target texture callbacks
  208. var savedSceneClearColor: Color3;
  209. var sceneClearColor = new Color3(0.0, 0.0, 0.0);
  210. this._volumetricLightScatteringRTT.onBeforeRender = (): void => {
  211. savedSceneClearColor = scene.clearColor;
  212. scene.clearColor = sceneClearColor;
  213. };
  214. this._volumetricLightScatteringRTT.onAfterRender = (): void => {
  215. scene.clearColor = savedSceneClearColor;
  216. };
  217. this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
  218. var index;
  219. for (index = 0; index < opaqueSubMeshes.length; index++) {
  220. renderSubMesh(opaqueSubMeshes.data[index]);
  221. }
  222. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  223. renderSubMesh(alphaTestSubMeshes.data[index]);
  224. }
  225. for (index = 0; index < transparentSubMeshes.length; index++) {
  226. renderSubMesh(transparentSubMeshes.data[index]);
  227. }
  228. };
  229. }
  230. private _updateMeshScreenCoordinates(scene: Scene): void {
  231. var transform = scene.getTransformMatrix();
  232. var pos = Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, Matrix.Identity(), transform, this._viewPort);
  233. this._screenCoordinates.x = pos.x / this._viewPort.width;
  234. this._screenCoordinates.y = pos.y / this._viewPort.height;
  235. if (this.invert)
  236. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  237. }
  238. // Static methods
  239. /**
  240. * Creates a default mesh for the Volumeric Light Scattering post-process
  241. * @param {string} The mesh name
  242. * @param {BABYLON.Scene} The scene where to create the mesh
  243. * @return {BABYLON.Mesh} the default mesh
  244. */
  245. public static CreateDefaultMesh(name: string, scene: Scene): Mesh {
  246. var mesh = Mesh.CreatePlane(name, 1, scene);
  247. mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
  248. mesh.material = new StandardMaterial(name + "Material", scene);
  249. return mesh;
  250. }
  251. }
  252. }