babylon.volumetricLightScatteringPostProcess.ts 17 KB

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