babylon.volumetricLightScatteringPostProcess.ts 19 KB

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