Formula to calculate Far Plane from Fog Exp2 Density?

Would anyone know the formula to calculate the maximum distance you can see with a certain fog density, in fog exp2 mode?
Thanks.

You want to put your far clip plane at Sqrt( Log( 1/0.0019 ) )/density for Exp2 fog.

A general solution for any type of fog would be:

    if( RenderSettings.fogMode == FogMode.Linear ) {
        camera.farClipPlane = RenderSettings.fogEndDistance;
    } else if( RenderSettings.fogMode == FogMode.Exponential ) {
        camera.farClipPlane = Mathf.Log( 1f / 0.0019f ) / RenderSettings.fogDensity;
    } else if( RenderSettings.fogMode == FogMode.ExponentialSquared ) {
        camera.farClipPlane = Mathf.Sqrt( Mathf.Log( 1f / 0.0019f ) ) / RenderSettings.fogDensity;
    }

The Fog Formulas are detailed here.

For Exp2 fog, that’s f = 1/e^((d * density)^2), where:

  • f=0 is all fog and f=1 is no fog.
  • d is distance from the camera to the pixel being rendered.
  • density is the fog density set in Unity, limited between 0.0 and 1.0.

So we want to calculate d, such that f will be 0. However, for f to be zero, e^((d * density)^2) would have to be infinity, so instead we can just solve for a sufficiently small f of 0.0019 (0.0019 is just under 0.5/255, so the contribution of the scene should round down to 0 at this point, assuming an LDR pixel).

Solving for d gives you this, as noted above:

d = Sqrt( Log( 1/0.0019 ) )/density

Note that the OpenGL docs regarding this can be confusing for a number of reasons, mostly because of bad formatting on many of the web pages I’ve seen.

the fog calculation for exp2 is: F = e^((-D * z)^2)
(F=1 means no fog, and F=0 is complete fog)
see: http://forum.unity3d.com/threads/28812-Fog-falloff-quot-equation-quot

which means the distance has to be infinte for the fog to be completely opaque

but almost opaque should be good enough, so use:

float getFogDistance(float D, float F=0.005f) //0.005 is almost completely opaque fog
{
	return Mathf.Sqrt(Mathf.Log(F))/-D; //note that for F=0, it will throw an error (i think)
}

I’m not a fog expert but doesn’t fog setup work in a way where you set fogStartDistance and fogEndDistance? fogEndDistance being that maximum distance where your object is completely not visible. fog density is just a function that determines how much fog is applied on objects between fogStartDistance and fogEndDistance.