babylon.volumetricLightScatteringPostProcess.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 getClassName(): string {
  113. return "VolumetricLightScatteringPostProcess";
  114. }
  115. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  116. var mesh = subMesh.getMesh();
  117. // Render this.mesh as default
  118. if (mesh === this.mesh) {
  119. return mesh.material.isReady(mesh);
  120. }
  121. var defines = [];
  122. var attribs = [VertexBuffer.PositionKind];
  123. var material: any = subMesh.getMaterial();
  124. var needUV: boolean = false;
  125. // Alpha test
  126. if (material) {
  127. if (material.needAlphaTesting()) {
  128. defines.push("#define ALPHATEST");
  129. }
  130. if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  131. attribs.push(VertexBuffer.UVKind);
  132. defines.push("#define UV1");
  133. }
  134. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  135. attribs.push(VertexBuffer.UV2Kind);
  136. defines.push("#define UV2");
  137. }
  138. }
  139. // Bones
  140. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  141. attribs.push(VertexBuffer.MatricesIndicesKind);
  142. attribs.push(VertexBuffer.MatricesWeightsKind);
  143. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  144. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  145. } else {
  146. defines.push("#define NUM_BONE_INFLUENCERS 0");
  147. }
  148. // Instances
  149. if (useInstances) {
  150. defines.push("#define INSTANCES");
  151. attribs.push("world0");
  152. attribs.push("world1");
  153. attribs.push("world2");
  154. attribs.push("world3");
  155. }
  156. // Get correct effect
  157. var join = defines.join("\n");
  158. if (this._cachedDefines !== join) {
  159. this._cachedDefines = join;
  160. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect(
  161. { vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" },
  162. attribs,
  163. ["world", "mBones", "viewProjection", "diffuseMatrix"],
  164. ["diffuseSampler"], join);
  165. }
  166. return this._volumetricLightScatteringPass.isReady();
  167. }
  168. /**
  169. * Sets the new light position for light scattering effect
  170. * @param {BABYLON.Vector3} The new custom light position
  171. */
  172. public setCustomMeshPosition(position: Vector3): void {
  173. this.customMeshPosition = position;
  174. }
  175. /**
  176. * Returns the light position for light scattering effect
  177. * @return {BABYLON.Vector3} The custom light position
  178. */
  179. public getCustomMeshPosition(): Vector3 {
  180. return this.customMeshPosition;
  181. }
  182. /**
  183. * Disposes the internal assets and detaches the post-process from the camera
  184. */
  185. public dispose(camera: Camera): void {
  186. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  187. if (rttIndex !== -1) {
  188. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  189. }
  190. this._volumetricLightScatteringRTT.dispose();
  191. super.dispose(camera);
  192. }
  193. /**
  194. * Returns the render target texture used by the post-process
  195. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  196. */
  197. public getPass(): RenderTargetTexture {
  198. return this._volumetricLightScatteringRTT;
  199. }
  200. // Private methods
  201. private _meshExcluded(mesh: AbstractMesh) {
  202. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  203. return true;
  204. }
  205. return false;
  206. }
  207. private _createPass(scene: Scene, ratio: number): void {
  208. var engine = scene.getEngine();
  209. this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, Engine.TEXTURETYPE_UNSIGNED_INT);
  210. this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;
  211. this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;
  212. this._volumetricLightScatteringRTT.renderList = null;
  213. this._volumetricLightScatteringRTT.renderParticles = false;
  214. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  215. // Custom render function for submeshes
  216. var renderSubMesh = (subMesh: SubMesh): void => {
  217. var mesh = subMesh.getRenderingMesh();
  218. if (this._meshExcluded(mesh)) {
  219. return;
  220. }
  221. var scene = mesh.getScene();
  222. var engine = scene.getEngine();
  223. // Culling
  224. engine.setState(subMesh.getMaterial().backFaceCulling);
  225. // Managing instances
  226. var batch = mesh._getInstancesRenderList(subMesh._id);
  227. if (batch.mustReturn) {
  228. return;
  229. }
  230. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  231. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  232. var effect: Effect = this._volumetricLightScatteringPass;
  233. if (mesh === this.mesh) {
  234. if (subMesh.effect) {
  235. effect = subMesh.effect;
  236. } else {
  237. effect = subMesh.getMaterial().getEffect();
  238. }
  239. }
  240. engine.enableEffect(effect);
  241. mesh._bind(subMesh, effect, Material.TriangleFillMode);
  242. if (mesh === this.mesh) {
  243. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  244. }
  245. else {
  246. var material: any = subMesh.getMaterial();
  247. this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  248. // Alpha test
  249. if (material && material.needAlphaTesting()) {
  250. var alphaTexture = material.getAlphaTestTexture();
  251. this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  252. if (alphaTexture) {
  253. this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  254. }
  255. }
  256. // Bones
  257. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  258. this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  259. }
  260. }
  261. // Draw
  262. mesh._processRendering(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  263. (isInstance, world) => effect.setMatrix("world", world));
  264. }
  265. };
  266. // Render target texture callbacks
  267. var savedSceneClearColor: Color4;
  268. var sceneClearColor = new Color4(0.0, 0.0, 0.0, 1.0);
  269. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((): void => {
  270. savedSceneClearColor = scene.clearColor;
  271. scene.clearColor = sceneClearColor;
  272. });
  273. this._volumetricLightScatteringRTT.onAfterRenderObservable.add((): void => {
  274. scene.clearColor = savedSceneClearColor;
  275. });
  276. this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
  277. var engine = scene.getEngine();
  278. var index: number;
  279. if (depthOnlySubMeshes.length) {
  280. engine.setColorWrite(false);
  281. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  282. renderSubMesh(depthOnlySubMeshes.data[index]);
  283. }
  284. engine.setColorWrite(true);
  285. }
  286. for (index = 0; index < opaqueSubMeshes.length; index++) {
  287. renderSubMesh(opaqueSubMeshes.data[index]);
  288. }
  289. engine.setAlphaTesting(true);
  290. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  291. renderSubMesh(alphaTestSubMeshes.data[index]);
  292. }
  293. engine.setAlphaTesting(false);
  294. if (transparentSubMeshes.length) {
  295. // Sort sub meshes
  296. for (index = 0; index < transparentSubMeshes.length; index++) {
  297. var submesh = transparentSubMeshes.data[index];
  298. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  299. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  300. }
  301. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  302. sortedArray.sort((a, b) => {
  303. // Alpha index first
  304. if (a._alphaIndex > b._alphaIndex) {
  305. return 1;
  306. }
  307. if (a._alphaIndex < b._alphaIndex) {
  308. return -1;
  309. }
  310. // Then distance to camera
  311. if (a._distanceToCamera < b._distanceToCamera) {
  312. return 1;
  313. }
  314. if (a._distanceToCamera > b._distanceToCamera) {
  315. return -1;
  316. }
  317. return 0;
  318. });
  319. // Render sub meshes
  320. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  321. for (index = 0; index < sortedArray.length; index++) {
  322. renderSubMesh(sortedArray[index]);
  323. }
  324. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  325. }
  326. };
  327. }
  328. private _updateMeshScreenCoordinates(scene: Scene): void {
  329. var transform = scene.getTransformMatrix();
  330. var meshPosition: Vector3;
  331. if (this.useCustomMeshPosition) {
  332. meshPosition = this.customMeshPosition;
  333. }
  334. else if (this.attachedNode) {
  335. meshPosition = this.attachedNode.position;
  336. }
  337. else {
  338. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  339. }
  340. var pos = Vector3.Project(meshPosition, Matrix.Identity(), transform, this._viewPort);
  341. this._screenCoordinates.x = pos.x / this._viewPort.width;
  342. this._screenCoordinates.y = pos.y / this._viewPort.height;
  343. if (this.invert)
  344. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  345. }
  346. // Static methods
  347. /**
  348. * Creates a default mesh for the Volumeric Light Scattering post-process
  349. * @param {string} The mesh name
  350. * @param {BABYLON.Scene} The scene where to create the mesh
  351. * @return {BABYLON.Mesh} the default mesh
  352. */
  353. public static CreateDefaultMesh(name: string, scene: Scene): Mesh {
  354. var mesh = Mesh.CreatePlane(name, 1, scene);
  355. mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
  356. var material = new StandardMaterial(name + "Material", scene);
  357. material.emissiveColor = new Color3(1, 1, 1);
  358. mesh.material = material;
  359. return mesh;
  360. }
  361. }
  362. }