TExcelTAD

Fog

Fog is the cheapest atmosphere money can buy. It hides the far clip plane where the world ends, it gives a sense of scale (distant mountains fade into blue), it sets a mood (green fog in a swamp, orange dust on Mars) and it lets an open world draw fewer distant objects. In a shader, basic fog is one line: blend the surface color toward a fog color by a factor that grows with distance.

glsl
color = mix(color, fogColor, fogAmount);

All the variety is in how you compute fogAmount.

Three falloff curves

Fog type fogAmount Character
linear clamp((dist - start) / (end - start), 0.0, 1.0) starts and ends at chosen distances; easy for artists, looks artificial
exponential 1.0 - exp(-dist * density) physically motivated: each meter absorbs the same fraction of light
exponential squared 1.0 - exp(-pow(dist * density, 2.0)) clear near the camera, then thickens quickly

These are the same three modes OpenGL's old fixed-function pipeline offered (GL_LINEAR, GL_EXP, GL_EXP2), and that Unity still exposes in its Lighting window's fog settings.

The scene below is a field of spheres. The frame is split into three vertical strips, one per curve:

glsl · try it yourself
float map(vec3 p) {
    vec3 q = p;
    q.xz = mod(q.xz + 2.0, 4.0) - 2.0;                    // repeat a sphere every 4 units
    return min(length(q - vec3(0.0, 0.5, 0.0)) - 0.8, p.y + 0.3);
}
vec3 calcNormal(vec3 p) {
    vec2 e = vec2(0.001, 0.0);
    return normalize(vec3(map(p + e.xyy) - map(p - e.xyy),
                          map(p + e.yxy) - map(p - e.yxy),
                          map(p + e.yyx) - map(p - e.yyx)));
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
    vec3 ro = vec3(2.0, 1.2, -iTime * 2.0);               // fly between the rows of spheres
    vec3 rd = normalize(vec3(p.x, p.y - 0.1, -1.2));
    vec3 lightDir = normalize(vec3(0.5, 0.8, 0.2));
    vec3 fogColor = vec3(0.6, 0.65, 0.7);

    float t = 0.0;
    for (int i = 0; i < 128; i++) {
        float d = map(ro + rd * t);
        if (d < 0.001 || t > 80.0) break;
        t += d;
    }
    vec3 color = fogColor;
    if (t < 80.0) {
        vec3 pos = ro + rd * t;
        vec3 n = calcNormal(pos);
        vec3 albedo = pos.y < -0.29 ? vec3(0.35, 0.3, 0.25) : vec3(0.8, 0.3, 0.2);
        color = albedo * (0.2 + 0.8 * max(dot(n, lightDir), 0.0));
    }

    float strip = fragCoord.x / iResolution.x;
    float fog;
    if (strip < 0.333)      fog = clamp((t - 5.0) / (40.0 - 5.0), 0.0, 1.0);   // linear
    else if (strip < 0.667) fog = 1.0 - exp(-t * 0.06);                          // exp
    else                    fog = 1.0 - exp(-pow(t * 0.05, 2.0));                // exp2
    color = mix(color, fogColor, fog);
    if (abs(strip - 0.333) < 0.002 || abs(strip - 0.667) < 0.002) color = vec3(1.0);
    fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}

Rays that miss everything (t > 80) are given the fog color directly, so the horizon blends seamlessly into the sky. In a real game, the sky is usually drawn without fog and the fog color is chosen to match the sky near the horizon.

Distance or depth?

Which "distance" do you use? There are two choices:

  • View-space depth (the z distance along the camera's forward axis): what many engines historically used because the depth buffer already has it. Fog then changes when you rotate the camera: objects at the edge of the screen look clearer than ones in the middle at the same distance.
  • Radial distance (length(position - cameraPosition)): stable under rotation. A raymarcher gets it for free as t.

Prefer radial distance whenever you can compute it.

Height fog

Real mist pools in valleys: it is thicker near the ground and thins out with altitude. If the density falls off exponentially with height, density(y) = a * exp(-b * y), the total fog along a ray has a closed-form solution (from Inigo Quilez's fog article), so it stays a single line of math:

glsl · try it yourself
float map(vec3 p) {
    vec3 q = p;
    q.xz = mod(q.xz + 3.0, 6.0) - 3.0;
    float pillar = length(q.xz) - 0.6;
    float hills = p.y + 1.0 - 0.5 * sin(p.x * 0.3) * sin(p.z * 0.25);
    return min(max(pillar, p.y - 3.0), hills * 0.7);
}
vec3 calcNormal(vec3 p) {
    vec2 e = vec2(0.001, 0.0);
    return normalize(vec3(map(p + e.xyy) - map(p - e.xyy),
                          map(p + e.yxy) - map(p - e.yxy),
                          map(p + e.yyx) - map(p - e.yyx)));
}

// Fog for a ray from ro along rd, length t, with density a * exp(-b * y).
float heightFog(vec3 ro, vec3 rd, float t, float a, float b) {
    float k = abs(rd.y) < 1e-4 ? 1e-4 : rd.y;              // avoid dividing by zero for level rays
    return clamp(a * exp(-ro.y * b) * (1.0 - exp(-t * k * b)) / (k * b), 0.0, 1.0);
}

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 p = (fragCoord - 0.5 * iResolution.xy) / iResolution.y;
    vec3 ro = vec3(iTime, 2.5, 0.0);
    vec3 rd = normalize(vec3(p.x, p.y - 0.2, -1.0));
    vec3 lightDir = normalize(vec3(-0.4, 0.6, -0.5));

    float t = 0.0;
    for (int i = 0; i < 150; i++) {
        float d = map(ro + rd * t);
        if (d < 0.002 || t > 60.0) break;
        t += d;
    }
    vec3 sky = mix(vec3(0.8, 0.75, 0.7), vec3(0.35, 0.5, 0.75), clamp(rd.y * 3.0, 0.0, 1.0));
    vec3 color = sky;
    if (t < 60.0) {
        vec3 n = calcNormal(ro + rd * t);
        color = vec3(0.45, 0.4, 0.35) * (0.15 + 0.85 * max(dot(n, lightDir), 0.0));
    } else {
        t = 60.0;
    }
    float fog = heightFog(ro, rd, t, 0.25, 0.6);
    color = mix(color, vec3(0.75, 0.78, 0.8), fog);
    fragColor = vec4(pow(color, vec3(1.0 / 2.2)), 1.0);
}

The pillar bases disappear into the mist, while their tops stay sharp even far away. Change b (the falloff with height) from 0.6 to 0.2 and the fog layer gets much thicker vertically.

Sun-tinted fog

One more cheap trick adds a lot of realism: when you look toward the sun, fog glows warmer, because light scatters forward through the haze. Tint the fog color by how closely the view ray points at the sun:

glsl
float sunAmount = max(dot(rd, sunDir), 0.0);
vec3 fogColor = mix(vec3(0.5, 0.6, 0.7), vec3(1.0, 0.9, 0.7), pow(sunAmount, 8.0));

Try adding it to the height-fog example (use lightDir as sunDir).

Fog in engines

Engine Built-in fog Notes
Unity URP Lighting window → Environment → Fog (linear, exponential, exponential squared) custom shaders apply it with ComputeFogFactor and MixFog from the URP shader library
Unreal Exponential Height Fog actor, with optional Volumetric Fog translucent materials have an Apply Fogging option in their translucency settings
Godot 4 Environment → Fog (distance fog with optional height falloff) and Volumetric Fog spatial shaders get it unless render_mode fog_disabled is set
Three.js scene.fog = new THREE.Fog(color, near, far) or THREE.FogExp2(color, density) ShaderMaterial needs fog: true plus the fog shader chunks

Custom shaders are where fog usually breaks: a hand-written unlit shader that forgets to apply the engine's fog glows bright in the middle of a foggy scene. When you write an engine shader, check fog first.

Test yourself

Which fog formula models each unit of distance absorbing the same fraction of light?

  1. Linear
  2. Exponential: 1 - exp(-dist * density)
  3. Step
  4. Inverse square

Why prefer radial distance over view-space depth for fog?

  1. It is cheaper
  2. Depth-based fog changes when the camera rotates; radial distance does not
  3. Depth is always zero
  4. Radial fog is required by GPUs

What is a common bug with custom shaders in a foggy scene?

  1. They render upside down
  2. They forget to apply the engine's fog and stand out unfogged
  3. They cast no shadows
  4. They disable bloom