volumetricLightScatteringPostProcess.ts 18 KB

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