volumetricLightScatteringPostProcess.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. import { serializeAsVector3, serialize, serializeAsMeshReference } from "../Misc/decorators";
  2. import { SmartArray } from "../Misc/smartArray";
  3. import { Logger } from "../Misc/logger";
  4. import { Color4, Color3, Vector2, Vector3, Matrix, Viewport } from "../Maths/math";
  5. import { VertexBuffer } from "../Meshes/buffer";
  6. import { AbstractMesh } from "../Meshes/abstractMesh";
  7. import { SubMesh } from "../Meshes/subMesh";
  8. import { Mesh } from "../Meshes/mesh";
  9. import { Camera } from "../Cameras/camera";
  10. import { Effect } from "../Materials/effect";
  11. import { Material } from "../Materials/material";
  12. import { StandardMaterial } from "../Materials/standardMaterial";
  13. import { Texture } from "../Materials/Textures/texture";
  14. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  15. import { PostProcess } from "./postProcess";
  16. import { Constants } from "../Engines/constants";
  17. import { Scene } from "../scene";
  18. import "../Meshes/Builders/planeBuilder";
  19. import "../Shaders/depth.vertex";
  20. import "../Shaders/volumetricLightScattering.fragment";
  21. import "../Shaders/volumetricLightScatteringPass.fragment";
  22. declare type Engine = import("../Engines/engine").Engine;
  23. /**
  24. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  25. */
  26. export class VolumetricLightScatteringPostProcess extends PostProcess {
  27. // Members
  28. private _volumetricLightScatteringPass: Effect;
  29. private _volumetricLightScatteringRTT: RenderTargetTexture;
  30. private _viewPort: Viewport;
  31. private _screenCoordinates: Vector2 = Vector2.Zero();
  32. private _cachedDefines: string;
  33. /**
  34. * If not undefined, the mesh position is computed from the attached node position
  35. */
  36. public attachedNode: { position: Vector3 };
  37. /**
  38. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  39. */
  40. @serializeAsVector3()
  41. public customMeshPosition: Vector3 = Vector3.Zero();
  42. /**
  43. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  44. */
  45. @serialize()
  46. public useCustomMeshPosition: boolean = false;
  47. /**
  48. * If the post-process should inverse the light scattering direction
  49. */
  50. @serialize()
  51. public invert: boolean = true;
  52. /**
  53. * The internal mesh used by the post-process
  54. */
  55. @serializeAsMeshReference()
  56. public mesh: Mesh;
  57. /**
  58. * @hidden
  59. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  60. */
  61. public get useDiffuseColor(): boolean {
  62. Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  63. return false;
  64. }
  65. public set useDiffuseColor(useDiffuseColor: boolean) {
  66. Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67. }
  68. /**
  69. * Array containing the excluded meshes not rendered in the internal pass
  70. */
  71. @serialize()
  72. public excludedMeshes = new Array<AbstractMesh>();
  73. /**
  74. * Controls the overall intensity of the post-process
  75. */
  76. @serialize()
  77. public exposure = 0.3;
  78. /**
  79. * Dissipates each sample's contribution in range [0, 1]
  80. */
  81. @serialize()
  82. public decay = 0.96815;
  83. /**
  84. * Controls the overall intensity of each sample
  85. */
  86. @serialize()
  87. public weight = 0.58767;
  88. /**
  89. * Controls the density of each sample
  90. */
  91. @serialize()
  92. public density = 0.926;
  93. /**
  94. * @constructor
  95. * @param name The post-process name
  96. * @param 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)
  97. * @param camera The camera that the post-process will be attached to
  98. * @param mesh The mesh used to create the light scattering
  99. * @param samples The post-process quality, default 100
  100. * @param samplingModeThe post-process filtering mode
  101. * @param engine The babylon engine
  102. * @param reusable If the post-process is reusable
  103. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  104. */
  105. constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples: number = 100, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean, scene?: Scene) {
  106. super(name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  107. scene = <Scene>((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  108. engine = scene.getEngine();
  109. this._viewPort = new Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  110. // Configure mesh
  111. this.mesh = (<Mesh>((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene)));
  112. // Configure
  113. this._createPass(scene, ratio.passRatio || ratio);
  114. this.onActivate = (camera: Camera) => {
  115. if (!this.isSupported) {
  116. this.dispose(camera);
  117. }
  118. this.onActivate = null;
  119. };
  120. this.onApplyObservable.add((effect: Effect) => {
  121. this._updateMeshScreenCoordinates(<Scene>scene);
  122. effect.setTexture("lightScatteringSampler", this._volumetricLightScatteringRTT);
  123. effect.setFloat("exposure", this.exposure);
  124. effect.setFloat("decay", this.decay);
  125. effect.setFloat("weight", this.weight);
  126. effect.setFloat("density", this.density);
  127. effect.setVector2("meshPositionOnScreen", this._screenCoordinates);
  128. });
  129. }
  130. /**
  131. * Returns the string "VolumetricLightScatteringPostProcess"
  132. * @returns "VolumetricLightScatteringPostProcess"
  133. */
  134. public getClassName(): string {
  135. return "VolumetricLightScatteringPostProcess";
  136. }
  137. private _isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  138. var mesh = subMesh.getMesh();
  139. // Render this.mesh as default
  140. if (mesh === this.mesh && mesh.material) {
  141. return mesh.material.isReady(mesh);
  142. }
  143. var defines = [];
  144. var attribs = [VertexBuffer.PositionKind];
  145. var material: any = subMesh.getMaterial();
  146. // Alpha test
  147. if (material) {
  148. if (material.needAlphaTesting()) {
  149. defines.push("#define ALPHATEST");
  150. }
  151. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  152. attribs.push(VertexBuffer.UVKind);
  153. defines.push("#define UV1");
  154. }
  155. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  156. attribs.push(VertexBuffer.UV2Kind);
  157. defines.push("#define UV2");
  158. }
  159. }
  160. // Bones
  161. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  162. attribs.push(VertexBuffer.MatricesIndicesKind);
  163. attribs.push(VertexBuffer.MatricesWeightsKind);
  164. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  165. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  166. } else {
  167. defines.push("#define NUM_BONE_INFLUENCERS 0");
  168. }
  169. // Instances
  170. if (useInstances) {
  171. defines.push("#define INSTANCES");
  172. attribs.push("world0");
  173. attribs.push("world1");
  174. attribs.push("world2");
  175. attribs.push("world3");
  176. }
  177. // Get correct effect
  178. var join = defines.join("\n");
  179. if (this._cachedDefines !== join) {
  180. this._cachedDefines = join;
  181. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect(
  182. { vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" },
  183. attribs,
  184. ["world", "mBones", "viewProjection", "diffuseMatrix"],
  185. ["diffuseSampler"], join);
  186. }
  187. return this._volumetricLightScatteringPass.isReady();
  188. }
  189. /**
  190. * Sets the new light position for light scattering effect
  191. * @param position The new custom light position
  192. */
  193. public setCustomMeshPosition(position: Vector3): void {
  194. this.customMeshPosition = position;
  195. }
  196. /**
  197. * Returns the light position for light scattering effect
  198. * @return Vector3 The custom light position
  199. */
  200. public getCustomMeshPosition(): Vector3 {
  201. return this.customMeshPosition;
  202. }
  203. /**
  204. * Disposes the internal assets and detaches the post-process from the camera
  205. */
  206. public dispose(camera: Camera): void {
  207. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  208. if (rttIndex !== -1) {
  209. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  210. }
  211. this._volumetricLightScatteringRTT.dispose();
  212. super.dispose(camera);
  213. }
  214. /**
  215. * Returns the render target texture used by the post-process
  216. * @return the render target texture used by the post-process
  217. */
  218. public getPass(): RenderTargetTexture {
  219. return this._volumetricLightScatteringRTT;
  220. }
  221. // Private methods
  222. private _meshExcluded(mesh: AbstractMesh) {
  223. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  224. return true;
  225. }
  226. return false;
  227. }
  228. private _createPass(scene: Scene, ratio: number): void {
  229. var engine = scene.getEngine();
  230. this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, Constants.TEXTURETYPE_UNSIGNED_INT);
  231. this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;
  232. this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;
  233. this._volumetricLightScatteringRTT.renderList = null;
  234. this._volumetricLightScatteringRTT.renderParticles = false;
  235. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  236. var camera = this.getCamera();
  237. if (camera) {
  238. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  239. } else {
  240. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  241. }
  242. // Custom render function for submeshes
  243. var renderSubMesh = (subMesh: SubMesh): void => {
  244. var mesh = subMesh.getRenderingMesh();
  245. if (this._meshExcluded(mesh)) {
  246. return;
  247. }
  248. let material = subMesh.getMaterial();
  249. if (!material) {
  250. return;
  251. }
  252. var scene = mesh.getScene();
  253. var engine = scene.getEngine();
  254. // Culling
  255. engine.setState(material.backFaceCulling);
  256. // Managing instances
  257. var batch = mesh._getInstancesRenderList(subMesh._id);
  258. if (batch.mustReturn) {
  259. return;
  260. }
  261. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  262. if (this._isReady(subMesh, hardwareInstancedRendering)) {
  263. var effect: Effect = this._volumetricLightScatteringPass;
  264. if (mesh === this.mesh) {
  265. if (subMesh.effect) {
  266. effect = subMesh.effect;
  267. } else {
  268. effect = <Effect>material.getEffect();
  269. }
  270. }
  271. engine.enableEffect(effect);
  272. mesh._bind(subMesh, effect, Material.TriangleFillMode);
  273. if (mesh === this.mesh) {
  274. material.bind(mesh.getWorldMatrix(), mesh);
  275. }
  276. else {
  277. this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  278. // Alpha test
  279. if (material && material.needAlphaTesting()) {
  280. var alphaTexture = material.getAlphaTestTexture();
  281. this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  282. if (alphaTexture) {
  283. this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  284. }
  285. }
  286. // Bones
  287. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  288. this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  289. }
  290. }
  291. // Draw
  292. mesh._processRendering(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  293. (isInstance, world) => effect.setMatrix("world", world));
  294. }
  295. };
  296. // Render target texture callbacks
  297. var savedSceneClearColor: Color4;
  298. var sceneClearColor = new Color4(0.0, 0.0, 0.0, 1.0);
  299. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((): void => {
  300. savedSceneClearColor = scene.clearColor;
  301. scene.clearColor = sceneClearColor;
  302. });
  303. this._volumetricLightScatteringRTT.onAfterRenderObservable.add((): void => {
  304. scene.clearColor = savedSceneClearColor;
  305. });
  306. this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
  307. var engine = scene.getEngine();
  308. var index: number;
  309. if (depthOnlySubMeshes.length) {
  310. engine.setColorWrite(false);
  311. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  312. renderSubMesh(depthOnlySubMeshes.data[index]);
  313. }
  314. engine.setColorWrite(true);
  315. }
  316. for (index = 0; index < opaqueSubMeshes.length; index++) {
  317. renderSubMesh(opaqueSubMeshes.data[index]);
  318. }
  319. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  320. renderSubMesh(alphaTestSubMeshes.data[index]);
  321. }
  322. if (transparentSubMeshes.length) {
  323. // Sort sub meshes
  324. for (index = 0; index < transparentSubMeshes.length; index++) {
  325. var submesh = transparentSubMeshes.data[index];
  326. let boundingInfo = submesh.getBoundingInfo();
  327. if (boundingInfo && scene.activeCamera) {
  328. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  329. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  330. }
  331. }
  332. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  333. sortedArray.sort((a, b) => {
  334. // Alpha index first
  335. if (a._alphaIndex > b._alphaIndex) {
  336. return 1;
  337. }
  338. if (a._alphaIndex < b._alphaIndex) {
  339. return -1;
  340. }
  341. // Then distance to camera
  342. if (a._distanceToCamera < b._distanceToCamera) {
  343. return 1;
  344. }
  345. if (a._distanceToCamera > b._distanceToCamera) {
  346. return -1;
  347. }
  348. return 0;
  349. });
  350. // Render sub meshes
  351. engine.setAlphaMode(Constants.ALPHA_COMBINE);
  352. for (index = 0; index < sortedArray.length; index++) {
  353. renderSubMesh(sortedArray[index]);
  354. }
  355. engine.setAlphaMode(Constants.ALPHA_DISABLE);
  356. }
  357. };
  358. }
  359. private _updateMeshScreenCoordinates(scene: Scene): void {
  360. var transform = scene.getTransformMatrix();
  361. var meshPosition: Vector3;
  362. if (this.useCustomMeshPosition) {
  363. meshPosition = this.customMeshPosition;
  364. }
  365. else if (this.attachedNode) {
  366. meshPosition = this.attachedNode.position;
  367. }
  368. else {
  369. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  370. }
  371. var pos = Vector3.Project(meshPosition, Matrix.Identity(), transform, this._viewPort);
  372. this._screenCoordinates.x = pos.x / this._viewPort.width;
  373. this._screenCoordinates.y = pos.y / this._viewPort.height;
  374. if (this.invert) {
  375. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  376. }
  377. }
  378. // Static methods
  379. /**
  380. * Creates a default mesh for the Volumeric Light Scattering post-process
  381. * @param name The mesh name
  382. * @param scene The scene where to create the mesh
  383. * @return the default mesh
  384. */
  385. public static CreateDefaultMesh(name: string, scene: Scene): Mesh {
  386. var mesh = Mesh.CreatePlane(name, 1, scene);
  387. mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
  388. var material = new StandardMaterial(name + "Material", scene);
  389. material.emissiveColor = new Color3(1, 1, 1);
  390. mesh.material = material;
  391. return mesh;
  392. }
  393. }