babylon.volumetricLightScatteringPostProcess.ts 18 KB

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