123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296 |
- module BABYLON {
- // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
- export class VolumetricLightScatteringPostProcess extends PostProcess {
- // Members
- private _volumetricLightScatteringPass: Effect;
- private _volumetricLightScatteringRTT: RenderTargetTexture;
- private _viewPort: Viewport;
- private _screenCoordinates: Vector2 = Vector2.Zero();
- private _cachedDefines: string;
- private _customMeshPosition: Vector3;
- /**
- * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
- * @type {boolean}
- */
- public useCustomMeshPosition: boolean = false;
- /**
- * If the post-process should inverse the light scattering direction
- * @type {boolean}
- */
- public invert: boolean = true;
- /**
- * The internal mesh used by the post-process
- * @type {boolean}
- */
- public mesh: Mesh;
- /**
- * Array containing the excluded meshes not rendered in the internal pass
- */
- public excludedMeshes = new Array<AbstractMesh>();
- public exposure = 0.3;
- public decay = 0.96815;
- public weight = 0.58767;
- public density = 0.926;
- /**
- * @constructor
- * @param {string} name - The post-process name
- * @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)
- * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
- * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
- * @param {number} samples - The post-process quality, default 100
- * @param {number} samplingMode - The post-process filtering mode
- * @param {BABYLON.Engine} engine - The babylon engine
- * @param {boolean} reusable - If the post-process is reusable
- */
- constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples: number = 100, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean) {
- super(name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
- var scene = camera.getScene();
- this._viewPort = new Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
- // Configure mesh
- this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
- // Configure
- this._createPass(scene, ratio.passRatio || ratio);
- this.onApply = (effect: Effect) => {
- this._updateMeshScreenCoordinates(scene);
- effect.setTexture("lightScatteringSampler", this._volumetricLightScatteringRTT);
- effect.setFloat("exposure", this.exposure);
- effect.setFloat("decay", this.decay);
- effect.setFloat("weight", this.weight);
- effect.setFloat("density", this.density);
- effect.setVector2("meshPositionOnScreen", this._screenCoordinates);
- };
- }
- public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
- var mesh = subMesh.getMesh();
- var defines = [];
- var attribs = [VertexBuffer.PositionKind];
- var material: any = subMesh.getMaterial();
- // Render this.mesh as default
- if (mesh === this.mesh) {
- defines.push("#define BASIC_RENDER");
- }
- // Alpha test
- if (material) {
- if (material.needAlphaTesting() || mesh === this.mesh)
- defines.push("#define ALPHATEST");
- if (material.opacityTexture !== undefined)
- defines.push("#define OPACITY");
- if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
- attribs.push(VertexBuffer.UVKind);
- defines.push("#define UV1");
- }
- if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
- attribs.push(VertexBuffer.UV2Kind);
- defines.push("#define UV2");
- }
- }
- // Bones
- if (mesh.useBones) {
- attribs.push(VertexBuffer.MatricesIndicesKind);
- attribs.push(VertexBuffer.MatricesWeightsKind);
- defines.push("#define BONES");
- defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
- }
- // Instances
- if (useInstances) {
- defines.push("#define INSTANCES");
- attribs.push("world0");
- attribs.push("world1");
- attribs.push("world2");
- attribs.push("world3");
- }
- // Get correct effect
- var join = defines.join("\n");
- if (this._cachedDefines !== join) {
- this._cachedDefines = join;
- this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect(
- { vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" },
- attribs,
- ["world", "mBones", "viewProjection", "diffuseMatrix", "far"],
- ["diffuseSampler", "opacitySampler"], join);
- }
- return this._volumetricLightScatteringPass.isReady();
- }
- /**
- * Sets the new light position for light scattering effect
- * @param {BABYLON.Vector3} The new custom light position
- */
- public setCustomMeshPosition(position: Vector3): void {
- this._customMeshPosition = position;
- }
- /**
- * Returns the light position for light scattering effect
- * @return {BABYLON.Vector3} The custom light position
- */
- public getCustomMeshPosition(): Vector3 {
- return this._customMeshPosition;
- }
- /**
- * Disposes the internal assets and detaches the post-process from the camera
- */
- public dispose(camera: Camera): void {
- var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
- if (rttIndex !== -1) {
- camera.getScene().customRenderTargets.splice(rttIndex, 1);
- }
-
- this._volumetricLightScatteringRTT.dispose();
- super.dispose(camera);
- }
- /**
- * Returns the render target texture used by the post-process
- * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
- */
- public getPass(): RenderTargetTexture {
- return this._volumetricLightScatteringRTT;
- }
- // Private methods
- private _meshExcluded(mesh: AbstractMesh) {
- if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
- return true;
- }
- return false;
- }
- private _createPass(scene: Scene, ratio: number): void {
- var engine = scene.getEngine();
- this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, Engine.TEXTURETYPE_UNSIGNED_INT);
- this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;
- this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;
- this._volumetricLightScatteringRTT.renderList = null;
- this._volumetricLightScatteringRTT.renderParticles = false;
- scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
- // Custom render function for submeshes
- var renderSubMesh = (subMesh: SubMesh): void => {
- var mesh = subMesh.getRenderingMesh();
- if (this._meshExcluded(mesh)) {
- return;
- }
- var scene = mesh.getScene();
- var engine = scene.getEngine();
- // Culling
- engine.setState(subMesh.getMaterial().backFaceCulling);
- // Managing instances
- var batch = mesh._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
- if (this.isReady(subMesh, hardwareInstancedRendering)) {
- engine.enableEffect(this._volumetricLightScatteringPass);
- mesh._bind(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode);
- var material: any = subMesh.getMaterial();
- this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
- // Alpha test
- if (material && (mesh === this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
- var alphaTexture = material.getAlphaTestTexture();
- this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
- if (this.mesh.material && alphaTexture)
- this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
- if (material.opacityTexture !== undefined)
- this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
- }
- // Bones
- if (mesh.useBones) {
- this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
- }
- // Draw
- mesh._processRendering(subMesh, this._volumetricLightScatteringPass, Material.TriangleFillMode, batch, hardwareInstancedRendering,
- (isInstance, world) => this._volumetricLightScatteringPass.setMatrix("world", world));
- }
- };
- // Render target texture callbacks
- var savedSceneClearColor: Color3;
- var sceneClearColor = new Color3(0.0, 0.0, 0.0);
- this._volumetricLightScatteringRTT.onBeforeRender = (): void => {
- savedSceneClearColor = scene.clearColor;
- scene.clearColor = sceneClearColor;
- };
- this._volumetricLightScatteringRTT.onAfterRender = (): void => {
- scene.clearColor = savedSceneClearColor;
- };
- this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
- var index;
- for (index = 0; index < opaqueSubMeshes.length; index++) {
- renderSubMesh(opaqueSubMeshes.data[index]);
- }
- for (index = 0; index < alphaTestSubMeshes.length; index++) {
- renderSubMesh(alphaTestSubMeshes.data[index]);
- }
- for (index = 0; index < transparentSubMeshes.length; index++) {
- renderSubMesh(transparentSubMeshes.data[index]);
- }
- };
- }
- private _updateMeshScreenCoordinates(scene: Scene): void {
- var transform = scene.getTransformMatrix();
- var pos = Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, Matrix.Identity(), transform, this._viewPort);
- this._screenCoordinates.x = pos.x / this._viewPort.width;
- this._screenCoordinates.y = pos.y / this._viewPort.height;
- if (this.invert)
- this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
- }
- // Static methods
- /**
- * Creates a default mesh for the Volumeric Light Scattering post-process
- * @param {string} The mesh name
- * @param {BABYLON.Scene} The scene where to create the mesh
- * @return {BABYLON.Mesh} the default mesh
- */
- public static CreateDefaultMesh(name: string, scene: Scene): Mesh {
- var mesh = Mesh.CreatePlane(name, 1, scene);
- mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;
- mesh.material = new StandardMaterial(name + "Material", scene);
- return mesh;
- }
- }
- }
|