Shader

Lighthouse

A lighthouse on a rock at night, seen from a boat. Clear air shows no beam, so the light is given fog to meet. Every pixel adds up the lamp's light that the fog on its ray sends towards the eye, with its steps laid out evenly in angle as the lamp sees them. The lens throws two beams that turn once in ten seconds, the lantern's window bars cut them into shafts, banks of fog drift through them, the sea mirrors the lamp, and every five seconds a beam finds the eye.

· Atmosphere · Fragment shader

Teaches A beam through fog, light shafts, a sea at night

Builds on Flowing Color Field (hash21), Floating 3D Scene, Cracked Clay (integer hash, sound noise), Kiln Fire (3D hash, 3D value noise, 3D fractal noise), Smoke Stack (night sky), Rain on Glass, Lightning, Sunset

Watch

The idea

You never see a beam of light from the side. You see what it meets: dust, smoke, drops of water. On a clear night a lighthouse is a point that flashes. In fog it is two long arms sweeping the sea, because every drop a beam touches sends a little of its light somewhere else, and some of that comes to you.

So this shader is mostly about fog. A pixel looks along a ray and asks, at each step, how much fog is there, how much of the lamp's light reaches it, and how much of that turns towards the eye. It is the marching of Smoke Stack and Sunset, with one difference that changes how the steps are laid out: the light is not a far-off sun but a lamp inside the picture, and nearly all of its light is close to it. It is built in five steps.

Stage 1 · A tower at night

The eye is on a boat 4.4 units from a rock, 0.3 above the water, and looks at a point 0.72 up the tower. A ray through each pixel meets one of three things. towerDist is the distance from a point to the rock and the lighthouse on it: a tower 0.11 in radius at its foot and 0.07 under the gallery, the gallery, the lantern room and a pointed roof. meetTower marches towards it, each step as long as that distance, as Floating 3D Scene does. A ray that points down and misses the tower meets the sea at -EYE.y / rd.y, with no marching, because the sea is flat. The rest is sky.

The sky is two dark blues, the paler one along the horizon (nightSky). The flat sea mirrors it: 2% of it seen from straight above and nearly all of it at a glancing angle, which is why the far water is as pale as the sky it meets. The tower has bands of cream and ember, lit by almost nothing, and the lantern's glass glows where the lamp is, 0.97 up. The lamp is on. Nothing shows where its light goes.

stage-1-a-tower-at-night.metal
// Stage 1 · A tower at night
// A lighthouse on a rock, seen from a boat at night. A ray through each
// pixel meets the tower, the sea or the sky. The tower is found by
// marching: step by the distance to it until none is left. The lamp is
// lit, but the air is clear, so nothing shows where its light goes.

// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The eye, on a boat 4.4 units out, and the lamp, 0.97 up the tower.
constant float3 EYE = float3(0.0, 0.3, -4.4);
constant float3 LAMP = float3(0.0, 0.97, 0.0);
// The lamp's color.
constant float3 GOLD = float3(1.0, 0.64, 0.3);
constant float FAR = 16.0;

// The distance to the rock and the lighthouse: a tower that narrows as
// it rises, a gallery, the lantern room and its roof.
float towerDist(float3 q) {
    float r = length(q.xz);
    float rock = (length(q / float3(0.62, 0.15, 0.5)) - 1.0) * 0.15;
    float h = clamp((q.y - 0.08) / 0.78, 0.0, 1.0);
    float shaft = max(r - mix(0.11, 0.07, h), abs(q.y - 0.47) - 0.39);
    float gallery = max(r - 0.1, abs(q.y - 0.87) - 0.012);
    float room = max(r - 0.058, abs(q.y - 0.97) - 0.09);
    float roof = max(r - 0.75 * (1.16 - q.y), abs(q.y - 1.11) - 0.05);
    return min(min(rock, shaft), min(min(gallery, room), roof));
}

float3 towerNormal(float3 q) {
    float2 e = float2(0.002, 0.0);
    return normalize(float3(
        towerDist(q + e.xyy) - towerDist(q - e.xyy),
        towerDist(q + e.yxy) - towerDist(q - e.yxy),
        towerDist(q + e.yyx) - towerDist(q - e.yyx)));
}

// How far along the ray it meets the rock or the tower, or FAR.
float meetTower(float3 rd) {
    float s = 3.2;
    for (int i = 0; i < 56; i++) {
        float d = towerDist(EYE + rd * s);
        if (d < 0.0015) return s;
        s += d;
        if (s > 8.0) break;
    }
    return FAR;
}

// The night sky in a direction: dark, a little paler at the horizon.
float3 nightSky(float3 d) {
    float up = max(d.y, 0.0);
    return mix(float3(0.007, 0.009, 0.015),
               float3(0.0015, 0.002, 0.006), pow(up, 0.45));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    // The camera looks from the boat at a point on the tower.
    float3 fw = normalize(float3(0.0, 0.72, 0.0) - EYE);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 upw = cross(fw, right);
    float3 rd = normalize(fw * 2.0 + right * s.x + upw * s.y);

    // What the ray meets: the tower, the sea, or the sky.
    float3 col = float3(0.0);
    float reach = meetTower(rd);
    float sea = rd.y < 0.0 ? -EYE.y / rd.y : 2.0 * FAR;
    if (reach < FAR && reach < sea) {
        float3 q = EYE + rd * reach;
        float3 n = towerNormal(q);
        float r = length(q.xz);
        // Bands of cream and ember up the tower, under a dark sky.
        float band = step(0.5, fract(q.y * 3.2 + 0.2));
        float3 paint = mix(float3(0.75, 0.2, 0.08),
                           float3(0.9, 0.85, 0.74), band);
        if (q.y < 0.085 || q.y > 0.855) paint = float3(0.12, 0.11, 0.1);
        col = paint * (0.01 + 0.03 * max(n.y, 0.0)
                       + 0.02 * max(-n.z, 0.0));
        // The lantern's glass shows the lamp.
        if (q.y > 0.885 && q.y < 1.055 && r < 0.07) {
            float lens = exp(-pow((q.y - LAMP.y) / 0.035, 2.0));
            col = GOLD * (0.05 + 3.0 * lens);
        }
    } else if (rd.y < 0.0) {
        reach = min(sea, 60.0);
        // Flat water mirrors the sky, more the flatter you look across it.
        float3 r = float3(rd.x, -rd.y, rd.z);
        float mirror = 0.02 + 0.98 * pow(1.0 - max(-rd.y, 0.0), 5.0);
        col = nightSky(r) * mirror + float3(0.0012, 0.002, 0.003);
    } else {
        reach = FAR;
        col = nightSky(rd);
    }

    // Bright light goes to white, then the screen's curve.
    col = 1.0 - exp(-col * 1.6);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// ---- The sound ---------------------------------------------------------
// The sound: the sea, noise that washes in every seven seconds or so.

// Integer hash, so noise stays exact for minutes of sound.
float hashU(uint n) {
    n = (n << 13u) ^ n;
    n = n * (n * n * 15731u + 789221u) + 1376312589u;
    return float(n & 0x7fffffffu) / float(0x7fffffff);
}

// Cracked Clay's sound noise: random values joined `rate` times a second.
float noise1(float t, float rate, uint seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    uint k = uint(i) + seed * 7919u;
    return mix(hashU(k), hashU(k + 1u), f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    // The sea: two bands of noise, washing in every seven seconds or so.
    float wash = 0.5 + 0.5 * sin(TAU * t / 7.0 + sin(TAU * t / 19.0));
    float run = (0.25 + 0.75 * wash * wash) * 0.64;
    float low = noise1(t, 420.0, 1u), high = noise1(t, 2100.0, 2u);
    float2 surf = float2(0.7 * low + 0.3 * high,
                         0.7 * noise1(t, 450.0, 3u) + 0.3 * high);
    surf *= 0.16 * run;

    float2 all = surf;
    // Silence where the minute comes round, so it ends without a click.
    float round = fract(t / 60.0);
    float fade = 1.0 - exp(-min(round, 1.0 - round) * 60.0 * 30.0);
    return tanh(all * 2.4) * 0.85 * p.volume * fade;
}

Stage 2 · Fog holds the light

fogGlow adds up the lamp's light that fog sends to the eye along the ray. At a point on the ray, that is how much fog is there (thickest on the water, with 37% of it left 0.9 up), times what is left of the light after the fog between the lamp and the point and between the point and the eye (kept), divided by the square of the distance from the lamp, since light spreads out. For now the lamp shines every way alike and so does each drop of fog, sending 1/(4π) of its light in each direction.

That last division is the trouble. A ray that passes 0.05 from the lamp gets nearly all of its light from a stretch a tenth of a unit long, and steps of even length would mostly land in the dark on either side of it. So the steps are laid out another way. along is how far down the ray it passes nearest the lamp, and miss by how much. Seen from the lamp, the ray's two ends are at the angles a0 and a1, and the 56 steps are even in that angle: s = along + miss · tan(angle). They crowd together where the lamp is near and spread out where it is far. A step's length works out as r² / miss times its angle, which cancels the 1/r² exactly, so every step stands for the same share of the light, and the sum is only multiplied by (a1 − a0) / miss at the end. This is called equi-angular sampling.

The fog between the eye and a point is not the same all the way, since it thins with height. fogCrossed gives the sum of exp(−height / 0.9) along the ray in closed form. The same number hides what is behind the fog: the tower, the sea and the sky are multiplied by exp(−0.11 · fog · fogCrossed). The picture is a halo round a bare lamp.

stage-2-fog-holds-the-light.metal37 new lines since stage 1
// Stage 2 · Fog holds the light
// Light shows in the air only where it meets something. Each drop of fog
// sends a little of the lamp's light towards the eye, and a pixel adds
// that up along its ray. The lamp shines every way alike, so the fog
// shows a halo.

// @param fog 1 0 3 How much fog there is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The eye, on a boat 4.4 units out, and the lamp, 0.97 up the tower.
constant float3 EYE = float3(0.0, 0.3, -4.4);
constant float3 LAMP = float3(0.0, 0.97, 0.0);
// The lamp's color, and how strong it is.
constant float3 GOLD = float3(1.0, 0.64, 0.3);
constant float POWER = 3.5;
// What a unit of fog takes out of light crossing it.
constant float THICK = 0.11;
constant int FOG_STEPS = 56;
// Fog thins with height: 0.9 up there is 1/e of it left.
constant float FOG_HEIGHT = 0.9;
constant float FAR = 16.0;

// The distance to the rock and the lighthouse: a tower that narrows as
// it rises, a gallery, the lantern room and its roof.
float towerDist(float3 q) {
    float r = length(q.xz);
    float rock = (length(q / float3(0.62, 0.15, 0.5)) - 1.0) * 0.15;
    float h = clamp((q.y - 0.08) / 0.78, 0.0, 1.0);
    float shaft = max(r - mix(0.11, 0.07, h), abs(q.y - 0.47) - 0.39);
    float gallery = max(r - 0.1, abs(q.y - 0.87) - 0.012);
    float room = max(r - 0.058, abs(q.y - 0.97) - 0.09);
    float roof = max(r - 0.75 * (1.16 - q.y), abs(q.y - 1.11) - 0.05);
    return min(min(rock, shaft), min(min(gallery, room), roof));
}

float3 towerNormal(float3 q) {
    float2 e = float2(0.002, 0.0);
    return normalize(float3(
        towerDist(q + e.xyy) - towerDist(q - e.xyy),
        towerDist(q + e.yxy) - towerDist(q - e.yxy),
        towerDist(q + e.yyx) - towerDist(q - e.yyx)));
}

// How far along the ray it meets the rock or the tower, or FAR.
float meetTower(float3 rd) {
    float s = 3.2;
    for (int i = 0; i < 56; i++) {
        float d = towerDist(EYE + rd * s);
        if (d < 0.0015) return s;
        s += d;
        if (s > 8.0) break;
    }
    return FAR;
}

// How much fog a ray from the eye has crossed after s units: the sum of
// exp(-height / FOG_HEIGHT) along it, which has a closed form.
float fogCrossed(float3 rd, float s) {
    float k = rd.y / FOG_HEIGHT;
    float start = exp(-EYE.y / FOG_HEIGHT);
    if (abs(k) < 0.001) return start * s;
    return start * (1.0 - exp(-k * s)) / k;
}

// The lamp's light the fog sends along the ray to the eye.
float fogGlow(float3 rd, float reach, constant Params& p) {
    // Where the ray passes nearest the lamp, and how far off.
    float along = dot(LAMP - EYE, rd);
    float miss = max(length(EYE + rd * along - LAMP), 0.03);
    float a0 = atan2(-along, miss);
    float a1 = atan2(reach - along, miss);
    float glow = 0.0;
    for (int i = 0; i < FOG_STEPS; i++) {
        // Steps even in the angle the lamp sees crowd where it is near.
        float f = (float(i) + 0.5) / float(FOG_STEPS);
        float s = along + miss * tan(mix(a0, a1, f));
        float3 q = EYE + rd * s;
        float3 d = q - LAMP;
        float r = length(d);
        float between = r * exp(-0.5 * (q.y + LAMP.y) / FOG_HEIGHT);
        float crossed = between + fogCrossed(rd, s);
        float kept = exp(-THICK * p.fog * crossed);
        // Fog sends light every way alike.
        float low = exp(-max(q.y, 0.0) / FOG_HEIGHT);
        glow += p.fog * low * kept / (4.0 * PI);
    }
    // Even angles have already paid the 1 / r².
    return POWER * glow * (a1 - a0) / (miss * float(FOG_STEPS));
}

// The night sky in a direction: dark, a little paler at the horizon.
float3 nightSky(float3 d) {
    float up = max(d.y, 0.0);
    return mix(float3(0.007, 0.009, 0.015),
               float3(0.0015, 0.002, 0.006), pow(up, 0.45));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    // The camera looks from the boat at a point on the tower.
    float3 fw = normalize(float3(0.0, 0.72, 0.0) - EYE);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 upw = cross(fw, right);
    float3 rd = normalize(fw * 2.0 + right * s.x + upw * s.y);

    // What the ray meets: the tower, the sea, or the sky.
    float3 col = float3(0.0);
    float reach = meetTower(rd);
    float sea = rd.y < 0.0 ? -EYE.y / rd.y : 2.0 * FAR;
    if (reach < FAR && reach < sea) {
        float3 q = EYE + rd * reach;
        float3 n = towerNormal(q);
        float r = length(q.xz);
        // Bands of cream and ember up the tower, under a dark sky.
        float band = step(0.5, fract(q.y * 3.2 + 0.2));
        float3 paint = mix(float3(0.75, 0.2, 0.08),
                           float3(0.9, 0.85, 0.74), band);
        if (q.y < 0.085 || q.y > 0.855) paint = float3(0.12, 0.11, 0.1);
        col = paint * (0.01 + 0.03 * max(n.y, 0.0)
                       + 0.02 * max(-n.z, 0.0));
        // The lantern's glass shows the lamp.
        if (q.y > 0.885 && q.y < 1.055 && r < 0.07) {
            float lens = exp(-pow((q.y - LAMP.y) / 0.035, 2.0));
            col = GOLD * (0.05 + 3.0 * lens);
        }
    } else if (rd.y < 0.0) {
        reach = min(sea, 60.0);
        // Flat water mirrors the sky, more the flatter you look across it.
        float3 r = float3(rd.x, -rd.y, rd.z);
        float mirror = 0.02 + 0.98 * pow(1.0 - max(-rd.y, 0.0), 5.0);
        col = nightSky(r) * mirror + float3(0.0012, 0.002, 0.003);
    } else {
        reach = FAR;
        col = nightSky(rd);
    }

    // Fog in front of it: it hides what is behind, glows a little by
    // itself, and carries the lamp's light.
    float kept = exp(-THICK * p.fog * fogCrossed(rd, reach));
    float3 haze = float3(0.004, 0.005, 0.008);
    col = col * kept + haze * (1.0 - kept);
    col += GOLD * fogGlow(rd, reach, p);

    // Bright light goes to white, then the screen's curve.
    col = 1.0 - exp(-col * 1.6);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// ---- The sound ---------------------------------------------------------
// The sound: the sea, and the lamp's steady hum.

// Integer hash, so noise stays exact for minutes of sound.
float hashU(uint n) {
    n = (n << 13u) ^ n;
    n = n * (n * n * 15731u + 789221u) + 1376312589u;
    return float(n & 0x7fffffffu) / float(0x7fffffff);
}

// Cracked Clay's sound noise: random values joined `rate` times a second.
float noise1(float t, float rate, uint seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    uint k = uint(i) + seed * 7919u;
    return mix(hashU(k), hashU(k + 1u), f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    // The sea: two bands of noise, washing in every seven seconds or so.
    float wash = 0.5 + 0.5 * sin(TAU * t / 7.0 + sin(TAU * t / 19.0));
    float run = (0.25 + 0.75 * wash * wash) * 0.64;
    float low = noise1(t, 420.0, 1u), high = noise1(t, 2100.0, 2u);
    float2 surf = float2(0.7 * low + 0.3 * high,
                         0.7 * noise1(t, 450.0, 3u) + 0.3 * high);
    surf *= 0.16 * run;

    // The lamp: a steady hum on D2 and A2.
    float hum = (sin(TAU * 73.42 * t) + 0.5 * sin(TAU * 110.0 * t)) * 0.045;
    float2 lens = float2(hum, hum);

    float2 all = surf + lens;
    // Silence where the minute comes round, so it ends without a click.
    float round = fract(t / 60.0);
    float fade = 1.0 - exp(-min(round, 1.0 - round) * 60.0 * 30.0);
    return tanh(all * 2.4) * 0.85 * p.volume * fade;
}
1 line from stage 1 that are gone
    float2 all = surf;

Stage 3 · Two beams that turn

A lighthouse lens gathers the lamp's light into beams and turns. lampShine says how much light leaves the lamp in a direction. around is the direction's angle about the tower, and a its angle from the middle of the nearest beam, which turns by a whole turn every turn seconds: 36° a second at 10. The light falls off as exp(−a² / w²), where w is spread: at 6° off the middle of a 6° beam 37% is left, at 12° under 2%. Up and down the beam is a fan 9° high (FAN, 0.16 radians). A little light, 0.6% of a beam's, still goes every way. With the light gathered, POWER goes from 3.5 to 56.

Fog does not send its light every way alike either. forwardShare is Henyey and Greenstein's phase function with g = 0.22: light that carries nearly straight on is 2.3 times as bright as light turned a quarter turn, and 3.8 times as bright as light sent straight back. So a beam is at its dimmest pointing away from you, brighter side on, and brightest when it swings towards you, since then the fog all along it is sending its light your way.

Every five seconds one of the two beams points at the boat: at 4 s, 9 s, 14 s and so on (FIRST). The eye is 8.7° under the level of the lamp, a little below the middle of the fan, so it gets 41% of the beam, and the whole picture fills with lit fog for a moment.

stage-3-two-beams-that-turn.metal33 new lines since stage 2
// Stage 3 · Two beams that turn
// The lens gathers the lamp's light into beams and turns. A point of fog
// gets less light the further it is, as an angle, from a beam's middle.
// Fog sends more of its light straight on than to the sides, so a beam
// grows bright as it swings towards the eye: every five seconds.

// @param turn 10 4 30 Seconds the lens takes to go round once
// @param beams 2 1 4 How many beams the lens throws
// @param spread 6 2 20 How wide each beam is, in degrees
// @param fog 1 0 3 How much fog there is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The eye, on a boat 4.4 units out, and the lamp, 0.97 up the tower.
constant float3 EYE = float3(0.0, 0.3, -4.4);
constant float3 LAMP = float3(0.0, 0.97, 0.0);
// The lamp's color, and how strong it is: the lens gathers its light
// into beams, sixteen times as bright as the bare lamp.
constant float3 GOLD = float3(1.0, 0.64, 0.3);
constant float POWER = 56.0;
// What a unit of fog takes out of light crossing it.
constant float THICK = 0.11;
// How much of fog's light goes straight on (Henyey and Greenstein's g).
constant float FORWARD = 0.22;
// The beams' height: a fan 9 degrees up and down.
constant float FAN = 0.16;
// When a beam first points at the eye.
constant float FIRST = 4.0;
constant int FOG_STEPS = 56;
// Fog thins with height: 0.9 up there is 1/e of it left.
constant float FOG_HEIGHT = 0.9;
constant float FAR = 16.0;

// The distance to the rock and the lighthouse: a tower that narrows as
// it rises, a gallery, the lantern room and its roof.
float towerDist(float3 q) {
    float r = length(q.xz);
    float rock = (length(q / float3(0.62, 0.15, 0.5)) - 1.0) * 0.15;
    float h = clamp((q.y - 0.08) / 0.78, 0.0, 1.0);
    float shaft = max(r - mix(0.11, 0.07, h), abs(q.y - 0.47) - 0.39);
    float gallery = max(r - 0.1, abs(q.y - 0.87) - 0.012);
    float room = max(r - 0.058, abs(q.y - 0.97) - 0.09);
    float roof = max(r - 0.75 * (1.16 - q.y), abs(q.y - 1.11) - 0.05);
    return min(min(rock, shaft), min(min(gallery, room), roof));
}

float3 towerNormal(float3 q) {
    float2 e = float2(0.002, 0.0);
    return normalize(float3(
        towerDist(q + e.xyy) - towerDist(q - e.xyy),
        towerDist(q + e.yxy) - towerDist(q - e.yxy),
        towerDist(q + e.yyx) - towerDist(q - e.yyx)));
}

// How far along the ray it meets the rock or the tower, or FAR.
float meetTower(float3 rd) {
    float s = 3.2;
    for (int i = 0; i < 56; i++) {
        float d = towerDist(EYE + rd * s);
        if (d < 0.0015) return s;
        s += d;
        if (s > 8.0) break;
    }
    return FAR;
}

// The light leaving the lamp in direction d: a little every way, and
// the beams, which turn.
float lampShine(float3 d, float t, constant Params& p) {
    float around = atan2(d.x, d.z);
    float slice = TAU / max(floor(p.beams + 0.5), 1.0);
    float a = around - PI - TAU * (t - FIRST) / p.turn;
    a -= slice * floor(a / slice + 0.5);
    float w = p.spread * PI / 180.0;
    float up = asin(clamp(d.y, -1.0, 1.0));
    float beam = exp(-a * a / (w * w) - up * up / (FAN * FAN));
    return 0.006 + beam;
}

// How much fog a ray from the eye has crossed after s units: the sum of
// exp(-height / FOG_HEIGHT) along it, which has a closed form.
float fogCrossed(float3 rd, float s) {
    float k = rd.y / FOG_HEIGHT;
    float start = exp(-EYE.y / FOG_HEIGHT);
    if (abs(k) < 0.001) return start * s;
    return start * (1.0 - exp(-k * s)) / k;
}

// The share of fog-scattered light that turns by the angle whose cosine
// is mu: most of it goes nearly straight on.
float forwardShare(float mu) {
    float g = FORWARD;
    return (1.0 - g * g) / (4.0 * PI * pow(1.0 + g * g - 2.0 * g * mu, 1.5));
}

// The lamp's light the fog sends along the ray to the eye.
float fogGlow(float3 rd, float reach, float t, constant Params& p) {
    // Where the ray passes nearest the lamp, and how far off.
    float along = dot(LAMP - EYE, rd);
    float miss = max(length(EYE + rd * along - LAMP), 0.03);
    float a0 = atan2(-along, miss);
    float a1 = atan2(reach - along, miss);
    float glow = 0.0;
    for (int i = 0; i < FOG_STEPS; i++) {
        // Steps even in the angle the lamp sees crowd where it is near.
        float f = (float(i) + 0.5) / float(FOG_STEPS);
        float s = along + miss * tan(mix(a0, a1, f));
        float3 q = EYE + rd * s;
        float3 d = q - LAMP;
        float r = length(d);
        d /= r;
        float between = r * exp(-0.5 * (q.y + LAMP.y) / FOG_HEIGHT);
        float crossed = between + fogCrossed(rd, s);
        float kept = exp(-THICK * p.fog * crossed);
        float turned = forwardShare(dot(d, -rd));
        float low = exp(-max(q.y, 0.0) / FOG_HEIGHT);
        glow += p.fog * low * lampShine(d, t, p) * turned * kept;
    }
    // Even angles have already paid the 1 / r².
    return POWER * glow * (a1 - a0) / (miss * float(FOG_STEPS));
}

// The night sky in a direction: dark, a little paler at the horizon.
float3 nightSky(float3 d) {
    float up = max(d.y, 0.0);
    return mix(float3(0.007, 0.009, 0.015),
               float3(0.0015, 0.002, 0.006), pow(up, 0.45));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float t = u.time;
    // The camera looks from the boat at a point on the tower.
    float3 fw = normalize(float3(0.0, 0.72, 0.0) - EYE);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 upw = cross(fw, right);
    float3 rd = normalize(fw * 2.0 + right * s.x + upw * s.y);

    // What the ray meets: the tower, the sea, or the sky.
    float3 col = float3(0.0);
    float reach = meetTower(rd);
    float sea = rd.y < 0.0 ? -EYE.y / rd.y : 2.0 * FAR;
    if (reach < FAR && reach < sea) {
        float3 q = EYE + rd * reach;
        float3 n = towerNormal(q);
        float r = length(q.xz);
        // Bands of cream and ember up the tower, under a dark sky.
        float band = step(0.5, fract(q.y * 3.2 + 0.2));
        float3 paint = mix(float3(0.75, 0.2, 0.08),
                           float3(0.9, 0.85, 0.74), band);
        if (q.y < 0.085 || q.y > 0.855) paint = float3(0.12, 0.11, 0.1);
        col = paint * (0.01 + 0.03 * max(n.y, 0.0)
                       + 0.02 * max(-n.z, 0.0));
        // The lantern's glass shows the lamp.
        if (q.y > 0.885 && q.y < 1.055 && r < 0.07) {
            // It is brightest where a beam points out through it.
            float3 out = normalize(float3(q.x, 0.0, q.z));
            float lit = lampShine(out, t, p);
            float lens = exp(-pow((q.y - LAMP.y) / 0.035, 2.0));
            col = GOLD * (0.05 + 0.5 * lens + 9.0 * lit * lens);
        }
    } else if (rd.y < 0.0) {
        reach = min(sea, 60.0);
        // Flat water mirrors the sky, more the flatter you look across it.
        float3 r = float3(rd.x, -rd.y, rd.z);
        float mirror = 0.02 + 0.98 * pow(1.0 - max(-rd.y, 0.0), 5.0);
        col = nightSky(r) * mirror + float3(0.0012, 0.002, 0.003);
    } else {
        reach = FAR;
        col = nightSky(rd);
    }

    // Fog in front of it: it hides what is behind, glows a little by
    // itself, and carries the lamp's light.
    float kept = exp(-THICK * p.fog * fogCrossed(rd, reach));
    float3 haze = float3(0.004, 0.005, 0.008);
    col = col * kept + haze * (1.0 - kept);
    col += GOLD * fogGlow(rd, reach, t, p);

    // Bright light goes to white, then the screen's curve.
    col = 1.0 - exp(-col * 1.6);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// ---- The sound ---------------------------------------------------------
// The sound: the sea, and the lens, which hums to the side its beam
// points and swells as a beam passes over the listener.

// Integer hash, so noise stays exact for minutes of sound.
float hashU(uint n) {
    n = (n << 13u) ^ n;
    n = n * (n * n * 15731u + 789221u) + 1376312589u;
    return float(n & 0x7fffffffu) / float(0x7fffffff);
}

// Cracked Clay's sound noise: random values joined `rate` times a second.
float noise1(float t, float rate, uint seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    uint k = uint(i) + seed * 7919u;
    return mix(hashU(k), hashU(k + 1u), f) * 2.0 - 1.0;
}

float2 sound(float t, constant Params& p) {
    // The sea: two bands of noise, washing in every seven seconds or so.
    float wash = 0.5 + 0.5 * sin(TAU * t / 7.0 + sin(TAU * t / 19.0));
    float run = (0.25 + 0.75 * wash * wash) * 0.64;
    float low = noise1(t, 420.0, 1u), high = noise1(t, 2100.0, 2u);
    float2 surf = float2(0.7 * low + 0.3 * high,
                         0.7 * noise1(t, 450.0, 3u) + 0.3 * high);
    surf *= 0.16 * run;

    // The lens: a hum on D2 and A2 that leans to the side its beam points,
    // and a swell on D3 as a beam passes over the listener.
    float angle = TAU * (t - FIRST) / p.turn;
    float pan = 0.5 + 0.35 * sin(angle);
    float hum = (sin(TAU * 73.42 * t) + 0.5 * sin(TAU * 110.0 * t)) * 0.045;
    float pass = lampShine(normalize(EYE - LAMP), t, p);
    float beam = (sin(TAU * 146.83 * t) + 0.4 * sin(TAU * 293.66 * t)
                  + 0.2 * sin(TAU * 440.0 * t)) * 0.16 * sqrt(pass);
    float2 lens = float2(1.0 - pan, pan) * hum * 2.0 + beam;

    float2 all = surf + lens;
    // Silence where the minute comes round, so it ends without a click.
    float round = fract(t / 60.0);
    float fade = 1.0 - exp(-min(round, 1.0 - round) * 60.0 * 30.0);
    return tanh(all * 2.4) * 0.85 * p.volume * fade;
}
6 lines from stage 2 that are gone
constant float POWER = 3.5;
⋯
float fogGlow(float3 rd, float reach, constant Params& p) {
⋯
        glow += p.fog * low * kept / (4.0 * PI);
⋯
            col = GOLD * (0.05 + 3.0 * lens);
⋯
    col += GOLD * fogGlow(rd, reach, p);
⋯
    float2 lens = float2(hum, hum);

Stage 4 · Shafts and banks

Two things break the beams up. The lantern room has eight window bars. They stand still while the lens turns, so bars depends on around alone, not on the time: −cos(8 · around) is near 1 in eight narrow slices of direction, and there up to 85% of the light is taken away. Each bar throws a dark shaft through whatever beam is passing it. None of the eight points at the boat.

And fog is never even. fogAt multiplies it by three sizes of noise, Kiln Fire's fbm3, drifting slowly sideways, so there is between a fifth and twice as much of it from place to place. A beam is bright where it crosses a bank and faint between banks, and its edge is no longer straight.

Lumpy fog shows the steps. All the pixels of a neighborhood take their 56 samples at nearly the same places, so a bank that falls between two samples is missed by all of them, and the picture gets bands. dither moves each pixel's samples by a different part of a step, from a pattern that spreads those parts evenly over nearby pixels (Jorge Jimenez's interleaved gradient noise), which turns the bands into grain too fine to notice.

stage-4-shafts-and-banks.metal62 new lines since stage 3
// Stage 4 · Shafts and banks
// Two things break the beams up. The lantern's eight window bars stand
// still while the lens turns, and each throws a dark shaft through the
// light. And fog is never even: noise makes banks that drift, so a beam
// is bright where it crosses one and faint between them.

// @param turn 10 4 30 Seconds the lens takes to go round once
// @param beams 2 1 4 How many beams the lens throws
// @param spread 6 2 20 How wide each beam is, in degrees
// @param fog 1 0 3 How much fog there is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The eye, on a boat 4.4 units out, and the lamp, 0.97 up the tower.
constant float3 EYE = float3(0.0, 0.3, -4.4);
constant float3 LAMP = float3(0.0, 0.97, 0.0);
// The lamp's color, and how strong it is: the lens gathers its light
// into beams, sixteen times as bright as the bare lamp.
constant float3 GOLD = float3(1.0, 0.64, 0.3);
constant float POWER = 56.0;
// What a unit of fog takes out of light crossing it.
constant float THICK = 0.11;
// How much of fog's light goes straight on (Henyey and Greenstein's g).
constant float FORWARD = 0.22;
// The beams' height: a fan 9 degrees up and down.
constant float FAN = 0.16;
// When a beam first points at the eye.
constant float FIRST = 4.0;
constant int FOG_STEPS = 56;
// Fog thins with height: 0.9 up there is 1/e of it left.
constant float FOG_HEIGHT = 0.9;
constant float FAR = 16.0;

// Kiln Fire's 3D hash, value noise and fractal noise.
float hash31(float3 p) {
    uint3 v = uint3(int3(floor(p))) * 1664525u + 1013904223u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    v ^= v >> 16u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    return float(v.x) * (1.0 / 4294967295.0);
}

float vnoise3(float3 p) {
    float3 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash31(i),                     b = hash31(i + float3(1, 0, 0));
    float c = hash31(i + float3(0, 1, 0)),   d = hash31(i + float3(1, 1, 0));
    float e = hash31(i + float3(0, 0, 1)),   g = hash31(i + float3(1, 0, 1));
    float h = hash31(i + float3(0, 1, 1)),   k = hash31(i + float3(1, 1, 1));
    float lo = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
    float hi = mix(mix(e, g, f.x), mix(h, k, f.x), f.y);
    return mix(lo, hi, f.z);
}

float fbm3(float3 p, int octaves) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < octaves; i++) {
        v += a * vnoise3(p);
        p = p * 2.02 + float3(17.1, 9.2, 4.7);
        a *= 0.5;
    }
    return v;
}

// The distance to the rock and the lighthouse: a tower that narrows as
// it rises, a gallery, the lantern room and its roof.
float towerDist(float3 q) {
    float r = length(q.xz);
    float rock = (length(q / float3(0.62, 0.15, 0.5)) - 1.0) * 0.15;
    float h = clamp((q.y - 0.08) / 0.78, 0.0, 1.0);
    float shaft = max(r - mix(0.11, 0.07, h), abs(q.y - 0.47) - 0.39);
    float gallery = max(r - 0.1, abs(q.y - 0.87) - 0.012);
    float room = max(r - 0.058, abs(q.y - 0.97) - 0.09);
    float roof = max(r - 0.75 * (1.16 - q.y), abs(q.y - 1.11) - 0.05);
    return min(min(rock, shaft), min(min(gallery, room), roof));
}

float3 towerNormal(float3 q) {
    float2 e = float2(0.002, 0.0);
    return normalize(float3(
        towerDist(q + e.xyy) - towerDist(q - e.xyy),
        towerDist(q + e.yxy) - towerDist(q - e.yxy),
        towerDist(q + e.yyx) - towerDist(q - e.yyx)));
}

// How far along the ray it meets the rock or the tower, or FAR.
float meetTower(float3 rd) {
    float s = 3.2;
    for (int i = 0; i < 56; i++) {
        float d = towerDist(EYE + rd * s);
        if (d < 0.0015) return s;
        s += d;
        if (s > 8.0) break;
    }
    return FAR;
}

// The light leaving the lamp in direction d: a little every way, and
// the beams, which turn.
float lampShine(float3 d, float t, constant Params& p) {
    float around = atan2(d.x, d.z);
    float slice = TAU / max(floor(p.beams + 0.5), 1.0);
    float a = around - PI - TAU * (t - FIRST) / p.turn;
    a -= slice * floor(a / slice + 0.5);
    float w = p.spread * PI / 180.0;
    float up = asin(clamp(d.y, -1.0, 1.0));
    float beam = exp(-a * a / (w * w) - up * up / (FAN * FAN));
    // The lantern's eight window bars stand still and shade the light.
    float bars = 1.0 - 0.85 * smoothstep(0.74, 0.96, -cos(8.0 * around));
    return 0.006 + beam * bars;
}

// How much fog there is at a point: thickest on the water, in drifting
// banks.
float fogAt(float3 q, float t, constant Params& p) {
    float low = exp(-max(q.y, 0.0) / FOG_HEIGHT);
    float3 drift = float3(0.09, 0.015, 0.04) * t;
    float banks = fbm3(q * 1.3 + drift, 3);
    return p.fog * low * (0.2 + 1.8 * smoothstep(0.15, 0.75, banks));
}

// How much fog a ray from the eye has crossed after s units: the sum of
// exp(-height / FOG_HEIGHT) along it, which has a closed form.
float fogCrossed(float3 rd, float s) {
    float k = rd.y / FOG_HEIGHT;
    float start = exp(-EYE.y / FOG_HEIGHT);
    if (abs(k) < 0.001) return start * s;
    return start * (1.0 - exp(-k * s)) / k;
}

// The share of fog-scattered light that turns by the angle whose cosine
// is mu: most of it goes nearly straight on.
float forwardShare(float mu) {
    float g = FORWARD;
    return (1.0 - g * g) / (4.0 * PI * pow(1.0 + g * g - 2.0 * g * mu, 1.5));
}

// The lamp's light the fog sends along the ray to the eye.
float fogGlow(float3 rd, float reach, float dither, float t,
              constant Params& p) {
    // Where the ray passes nearest the lamp, and how far off.
    float along = dot(LAMP - EYE, rd);
    float miss = max(length(EYE + rd * along - LAMP), 0.03);
    float a0 = atan2(-along, miss);
    float a1 = atan2(reach - along, miss);
    float glow = 0.0;
    for (int i = 0; i < FOG_STEPS; i++) {
        // Steps even in the angle the lamp sees crowd where it is near.
        float f = (float(i) + dither) / float(FOG_STEPS);
        float s = along + miss * tan(mix(a0, a1, f));
        float3 q = EYE + rd * s;
        float3 d = q - LAMP;
        float r = length(d);
        d /= r;
        float between = r * exp(-0.5 * (q.y + LAMP.y) / FOG_HEIGHT);
        float crossed = between + fogCrossed(rd, s);
        float kept = exp(-THICK * p.fog * crossed);
        float turned = forwardShare(dot(d, -rd));
        glow += fogAt(q, t, p) * lampShine(d, t, p) * turned * kept;
    }
    // Even angles have already paid the 1 / r².
    return POWER * glow * (a1 - a0) / (miss * float(FOG_STEPS));
}

// The night sky in a direction: dark, a little paler at the horizon.
float3 nightSky(float3 d) {
    float up = max(d.y, 0.0);
    return mix(float3(0.007, 0.009, 0.015),
               float3(0.0015, 0.002, 0.006), pow(up, 0.45));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float t = u.time;
    // The camera looks from the boat at a point on the tower.
    float3 fw = normalize(float3(0.0, 0.72, 0.0) - EYE);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 upw = cross(fw, right);
    float3 rd = normalize(fw * 2.0 + right * s.x + upw * s.y);

    // What the ray meets: the tower, the sea, or the sky.
    float3 col = float3(0.0);
    float reach = meetTower(rd);
    float sea = rd.y < 0.0 ? -EYE.y / rd.y : 2.0 * FAR;
    if (reach < FAR && reach < sea) {
        float3 q = EYE + rd * reach;
        float3 n = towerNormal(q);
        float r = length(q.xz);
        // Bands of cream and ember up the tower, under a dark sky.
        float band = step(0.5, fract(q.y * 3.2 + 0.2));
        float3 paint = mix(float3(0.75, 0.2, 0.08),
                           float3(0.9, 0.85, 0.74), band);
        if (q.y < 0.085 || q.y > 0.855) paint = float3(0.12, 0.11, 0.1);
        col = paint * (0.01 + 0.03 * max(n.y, 0.0)
                       + 0.02 * max(-n.z, 0.0));
        // The lantern's glass shows the lamp.
        if (q.y > 0.885 && q.y < 1.055 && r < 0.07) {
            // It is brightest where a beam points out through it.
            float3 out = normalize(float3(q.x, 0.0, q.z));
            float lit = lampShine(out, t, p);
            float lens = exp(-pow((q.y - LAMP.y) / 0.035, 2.0));
            col = GOLD * (0.05 + 0.5 * lens + 9.0 * lit * lens);
        }
    } else if (rd.y < 0.0) {
        reach = min(sea, 60.0);
        // Flat water mirrors the sky, more the flatter you look across it.
        float3 r = float3(rd.x, -rd.y, rd.z);
        float mirror = 0.02 + 0.98 * pow(1.0 - max(-rd.y, 0.0), 5.0);
        col = nightSky(r) * mirror + float3(0.0012, 0.002, 0.003);
    } else {
        reach = FAR;
        col = nightSky(rd);
    }

    // Fog in front of it: it hides what is behind, glows a little by
    // itself, and carries the lamp's light.
    float kept = exp(-THICK * p.fog * fogCrossed(rd, reach));
    float3 haze = float3(0.004, 0.005, 0.008);
    col = col * kept + haze * (1.0 - kept);
    // Each pixel starts its steps a little differently, in a pattern that
    // spreads the difference evenly, so bands become fine grain.
    float2 px = floor(uv * u.resolution);
    float dither = fract(52.9829189
                         * fract(dot(px, float2(0.06711056, 0.00583715))));
    col += GOLD * fogGlow(rd, reach, dither, t, p);

    // Bright light goes to white, then the screen's curve.
    col = 1.0 - exp(-col * 1.6);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// ---- The sound ---------------------------------------------------------
// The sound: the sea, the lens, and a foghorn, two notes every twenty
// seconds, louder the thicker the fog.

// Integer hash, so noise stays exact for minutes of sound.
float hashU(uint n) {
    n = (n << 13u) ^ n;
    n = n * (n * n * 15731u + 789221u) + 1376312589u;
    return float(n & 0x7fffffffu) / float(0x7fffffff);
}

// Cracked Clay's sound noise: random values joined `rate` times a second.
float noise1(float t, float rate, uint seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    uint k = uint(i) + seed * 7919u;
    return mix(hashU(k), hashU(k + 1u), f) * 2.0 - 1.0;
}

// One blast of the horn at `since` seconds after it starts: a low note
// with its overtones, `lasts` seconds from swell to fall.
float horn(float since, float hz, float lasts) {
    if (since < 0.0 || since > lasts) return 0.0;
    float env = smoothstep(0.0, 0.25, since)
              * (1.0 - smoothstep(lasts - 0.5, lasts, since));
    float tone = 0.0;
    for (int k = 1; k <= 6; k++) {
        float level = 1.0 / float(k * k) + (k == 3 ? 0.25 : 0.0);
        tone += sin(TAU * hz * float(k) * since) * level;
    }
    return tone * env;
}

float2 sound(float t, constant Params& p) {
    // The sea: two bands of noise, washing in every seven seconds or so.
    float wash = 0.5 + 0.5 * sin(TAU * t / 7.0 + sin(TAU * t / 19.0));
    float run = (0.25 + 0.75 * wash * wash) * 0.64;
    float low = noise1(t, 420.0, 1u), high = noise1(t, 2100.0, 2u);
    float2 surf = float2(0.7 * low + 0.3 * high,
                         0.7 * noise1(t, 450.0, 3u) + 0.3 * high);
    surf *= 0.16 * run;

    // The lens: a hum on D2 and A2 that leans to the side its beam points,
    // and a swell on D3 as a beam passes over the listener.
    float angle = TAU * (t - FIRST) / p.turn;
    float pan = 0.5 + 0.35 * sin(angle);
    float hum = (sin(TAU * 73.42 * t) + 0.5 * sin(TAU * 110.0 * t)) * 0.045;
    float pass = lampShine(normalize(EYE - LAMP), t, p);
    float beam = (sin(TAU * 146.83 * t) + 0.4 * sin(TAU * 293.66 * t)
                  + 0.2 * sin(TAU * 440.0 * t)) * 0.16 * sqrt(pass);
    float2 lens = float2(1.0 - pan, pan) * hum * 2.0 + beam;

    // The foghorn: F2 for two seconds, then C2, and their echo.
    float since = fract(t / 20.0) * 20.0 - 6.0;
    float call = horn(since, 87.31, 2.0) + horn(since - 2.3, 65.41, 2.6);
    float echo = horn(since - 0.7, 87.31, 2.0)
               + horn(since - 3.0, 65.41, 2.6);
    float thick = min(p.fog, 2.0) * 0.5;
    float2 fogHorn = (float2(0.55, 0.45) * call
                      + float2(0.2, 0.3) * echo * 0.5) * 0.3 * thick;

    float2 all = surf + lens + fogHorn;
    // Silence where the minute comes round, so it ends without a click.
    float round = fract(t / 60.0);
    float fade = 1.0 - exp(-min(round, 1.0 - round) * 60.0 * 30.0);
    return tanh(all * 2.4) * 0.85 * p.volume * fade;
}
7 lines from stage 3 that are gone
    return 0.006 + beam;
⋯
float fogGlow(float3 rd, float reach, float t, constant Params& p) {
⋯
        float f = (float(i) + 0.5) / float(FOG_STEPS);
⋯
        float low = exp(-max(q.y, 0.0) / FOG_HEIGHT);
        glow += p.fog * low * lampShine(d, t, p) * turned * kept;
⋯
    col += GOLD * fogGlow(rd, reach, t, p);
⋯
    float2 all = surf + lens;

Stage 5 · Lighthouse

The sea moves. swellAt is four trains of sine waves crossing each other, and seaNormal reads the way the water faces from its height a small step to each side. Far waves are smaller than a pixel, so their slopes fade with distance. The water still mirrors the sky, but now each slope mirrors a different part of it, and where a slope sends the lamp's own light to the eye there is a glint: the lamp's image in the water, broken into a road of bright dashes by the waves. Where a beam lands on the water there is a faint patch.

starsAt lays a grid over the directions, 70 squares to a radian, and puts a star in 7% of them, each twinkling at its own rate. They are in the sky only, not in its mirror image, where they would be smaller than the waves that carry them.

The lens itself is a point too bright for an eye or a camera: when a beam points at the boat, seen rises and a halo and a streak across it are added on top of everything, as glare. glare sets how much.

shade(), from the finished shader
float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float t = u.time;
    // The camera looks from the boat at a point on the tower.
    float3 fw = normalize(float3(0.0, 0.72, 0.0) - EYE);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 upw = cross(fw, right);
    float3 rd = normalize(fw * 2.0 + right * s.x + upw * s.y);

    // What the ray meets: the tower, the sea, or the sky.
    float3 col = float3(0.0);
    float reach = meetTower(rd);
    float sea = rd.y < 0.0 ? -EYE.y / rd.y : 2.0 * FAR;
    if (reach < FAR && reach < sea) {
        float3 q = EYE + rd * reach;
        float3 n = towerNormal(q);
        float r = length(q.xz);
        // Bands of cream and ember up the tower, under a dark sky.
        float band = step(0.5, fract(q.y * 3.2 + 0.2));
        float3 paint = mix(float3(0.75, 0.2, 0.08),
                           float3(0.9, 0.85, 0.74), band);
        if (q.y < 0.085 || q.y > 0.855) paint = float3(0.12, 0.11, 0.1);
        col = paint * (0.01 + 0.03 * max(n.y, 0.0)
                       + 0.02 * max(-n.z, 0.0));
        // The lantern's glass shows the lamp.
        if (q.y > 0.885 && q.y < 1.055 && r < 0.07) {
            // It is brightest where a beam points out through it.
            float3 out = normalize(float3(q.x, 0.0, q.z));
            float lit = lampShine(out, t, p);
            float lens = exp(-pow((q.y - LAMP.y) / 0.035, 2.0));
            col = GOLD * (0.05 + 0.5 * lens + 9.0 * lit * lens);
        }
    } else if (rd.y < 0.0) {
        reach = min(sea, 60.0);
        float3 q = EYE + rd * sea;
        float3 n = seaNormal(q.xz, t, sea, p);
        float3 r = reflect(rd, n);
        r.y = abs(r.y);
        // Water mirrors more the flatter you look across it.
        float facing = max(dot(-rd, n), 0.0);
        float mirror = 0.02 + 0.98 * pow(1.0 - facing, 5.0);
        col = nightSky(r) * mirror + float3(0.0012, 0.002, 0.003);
        // The lamp in the waves: a glint where a slope mirrors it to the
        // eye, and a soft patch where a beam lands.
        float3 l = LAMP - q;
        float lr = length(l);
        l /= lr;
        float dim = exp(-THICK * p.fog * lr * exp(-0.5 * LAMP.y / FOG_HEIGHT));
        float shine = lampShine(-l, t, p) * dim;
        float glint = pow(max(dot(r, l), 0.0), 700.0);
        float patch = 0.012 * max(dot(n, l), 0.0);
        col += GOLD * POWER * shine * (glint * 12.0 + patch) / (lr * lr);
    } else {
        reach = FAR;
        col = nightSky(rd) + float3(0.8, 0.85, 1.0) * starsAt(rd, t);
    }

    // Fog in front of it: it hides what is behind, glows a little by
    // itself, and carries the lamp's light.
    float kept = exp(-THICK * p.fog * fogCrossed(rd, reach));
    float3 haze = float3(0.004, 0.005, 0.008);
    col = col * kept + haze * (1.0 - kept);
    // Each pixel starts its steps a little differently, in a pattern that
    // spreads the difference evenly, so bands become fine grain.
    float2 px = floor(uv * u.resolution);
    float dither = fract(52.9829189
                         * fract(dot(px, float2(0.06711056, 0.00583715))));
    col += GOLD * fogGlow(rd, reach, dither, t, p);

    // The lens itself, when a beam points at the eye: a glare with a
    // streak across it, as an eye or a camera sees a bright point.
    float3 toLamp = LAMP - EYE;
    float away = length(toLamp);
    toLamp /= away;
    float2 lampAt = float2(dot(toLamp, right), dot(toLamp, upw))
                  * 2.0 / dot(toLamp, fw);
    float2 from = s - lampAt;
    float seen = lampShine(-toLamp, t, p)
               * exp(-THICK * p.fog * fogCrossed(toLamp, away));
    float halo = 0.0009 / (dot(from, from) + 0.0003);
    float streak = 0.004 / (abs(from.y) * 90.0 + 0.05)
                 * exp(-abs(from.x) * 2.2);
    col += GOLD * p.glare * seen * (halo + streak) * 6.0;

    // Bright light goes to white, then the screen's curve.
    col = 1.0 - exp(-col * 1.6);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}
lighthouse.metal, the whole file58 new lines since stage 4
// Ray Kiln · Lighthouse
//
// @episode Lighthouse
// @length 60
// @variation 30
// @variations 1,2,3,4,5,7,8,10
// @sweeps fog, spread, swell
// @still 13
// @teaches A beam through fog, light shafts, a sea at night
// @category Fragment
// @tags fog, volume rendering, light shafts, equi-angular sampling, phase function, raymarching, reflection, procedural sound
// @final Lighthouse | The sea rolls and mirrors the lamp, stars come out, and the lens glares when a beam finds you.
//
// A lighthouse on a rock at night, seen from a boat. Air alone shows no
// beam: the light has to meet something on its way. Here it meets fog.
// Every pixel looks along a ray and adds up the lamp's light that the fog
// on it sends towards the eye, with its steps laid out evenly in angle as
// the lamp sees them, so most fall where the ray passes nearest the lamp.
// The lens throws two beams that turn once in ten seconds, the lantern's
// window bars cut them into shafts, and every five seconds a beam finds
// the eye.
// Each @param line below becomes a slider in the host app and a row in the page's parameters table:
//   // @param name default min max description

// @param turn 10 4 30 Seconds the lens takes to go round once
// @param beams 2 1 4 How many beams the lens throws
// @param spread 6 2 20 How wide each beam is, in degrees
// @param fog 1 0 3 How much fog there is
// @param swell 1 0 2.5 How high the sea runs
// @param glare 1 0 2 How much the lens glares when a beam finds the eye
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The eye, on a boat 4.4 units out, and the lamp, 0.97 up the tower.
constant float3 EYE = float3(0.0, 0.3, -4.4);
constant float3 LAMP = float3(0.0, 0.97, 0.0);
// The lamp's color, and how strong it is: the lens gathers its light
// into beams, sixteen times as bright as the bare lamp.
constant float3 GOLD = float3(1.0, 0.64, 0.3);
constant float POWER = 56.0;
// What a unit of fog takes out of light crossing it.
constant float THICK = 0.11;
// How much of fog's light goes straight on (Henyey and Greenstein's g).
constant float FORWARD = 0.22;
// The beams' height: a fan 9 degrees up and down.
constant float FAN = 0.16;
// When a beam first points at the eye.
constant float FIRST = 4.0;
constant int FOG_STEPS = 56;
// Fog thins with height: 0.9 up there is 1/e of it left.
constant float FOG_HEIGHT = 0.9;
constant float FAR = 16.0;

float hash21(float2 p) {
    p = fract(p * float2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

// Kiln Fire's 3D hash, value noise and fractal noise.
float hash31(float3 p) {
    uint3 v = uint3(int3(floor(p))) * 1664525u + 1013904223u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    v ^= v >> 16u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    return float(v.x) * (1.0 / 4294967295.0);
}

float vnoise3(float3 p) {
    float3 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash31(i),                     b = hash31(i + float3(1, 0, 0));
    float c = hash31(i + float3(0, 1, 0)),   d = hash31(i + float3(1, 1, 0));
    float e = hash31(i + float3(0, 0, 1)),   g = hash31(i + float3(1, 0, 1));
    float h = hash31(i + float3(0, 1, 1)),   k = hash31(i + float3(1, 1, 1));
    float lo = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
    float hi = mix(mix(e, g, f.x), mix(h, k, f.x), f.y);
    return mix(lo, hi, f.z);
}

float fbm3(float3 p, int octaves) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < octaves; i++) {
        v += a * vnoise3(p);
        p = p * 2.02 + float3(17.1, 9.2, 4.7);
        a *= 0.5;
    }
    return v;
}

// The distance to the rock and the lighthouse: a tower that narrows as
// it rises, a gallery, the lantern room and its roof.
float towerDist(float3 q) {
    float r = length(q.xz);
    float rock = (length(q / float3(0.62, 0.15, 0.5)) - 1.0) * 0.15;
    float h = clamp((q.y - 0.08) / 0.78, 0.0, 1.0);
    float shaft = max(r - mix(0.11, 0.07, h), abs(q.y - 0.47) - 0.39);
    float gallery = max(r - 0.1, abs(q.y - 0.87) - 0.012);
    float room = max(r - 0.058, abs(q.y - 0.97) - 0.09);
    float roof = max(r - 0.75 * (1.16 - q.y), abs(q.y - 1.11) - 0.05);
    return min(min(rock, shaft), min(min(gallery, room), roof));
}

float3 towerNormal(float3 q) {
    float2 e = float2(0.002, 0.0);
    return normalize(float3(
        towerDist(q + e.xyy) - towerDist(q - e.xyy),
        towerDist(q + e.yxy) - towerDist(q - e.yxy),
        towerDist(q + e.yyx) - towerDist(q - e.yyx)));
}

// How far along the ray it meets the rock or the tower, or FAR.
float meetTower(float3 rd) {
    float s = 3.2;
    for (int i = 0; i < 56; i++) {
        float d = towerDist(EYE + rd * s);
        if (d < 0.0015) return s;
        s += d;
        if (s > 8.0) break;
    }
    return FAR;
}

// The light leaving the lamp in direction d: a little every way, and
// the beams, which turn.
float lampShine(float3 d, float t, constant Params& p) {
    float around = atan2(d.x, d.z);
    float slice = TAU / max(floor(p.beams + 0.5), 1.0);
    float a = around - PI - TAU * (t - FIRST) / p.turn;
    a -= slice * floor(a / slice + 0.5);
    float w = p.spread * PI / 180.0;
    float up = asin(clamp(d.y, -1.0, 1.0));
    float beam = exp(-a * a / (w * w) - up * up / (FAN * FAN));
    // The lantern's eight window bars stand still and shade the light.
    float bars = 1.0 - 0.85 * smoothstep(0.74, 0.96, -cos(8.0 * around));
    return 0.006 + beam * bars;
}

// How much fog there is at a point: thickest on the water, in drifting
// banks.
float fogAt(float3 q, float t, constant Params& p) {
    float low = exp(-max(q.y, 0.0) / FOG_HEIGHT);
    float3 drift = float3(0.09, 0.015, 0.04) * t;
    float banks = fbm3(q * 1.3 + drift, 3);
    return p.fog * low * (0.2 + 1.8 * smoothstep(0.15, 0.75, banks));
}

// How much fog a ray from the eye has crossed after s units: the sum of
// exp(-height / FOG_HEIGHT) along it, which has a closed form.
float fogCrossed(float3 rd, float s) {
    float k = rd.y / FOG_HEIGHT;
    float start = exp(-EYE.y / FOG_HEIGHT);
    if (abs(k) < 0.001) return start * s;
    return start * (1.0 - exp(-k * s)) / k;
}

// The share of fog-scattered light that turns by the angle whose cosine
// is mu: most of it goes nearly straight on.
float forwardShare(float mu) {
    float g = FORWARD;
    return (1.0 - g * g) / (4.0 * PI * pow(1.0 + g * g - 2.0 * g * mu, 1.5));
}

// The lamp's light the fog sends along the ray to the eye.
float fogGlow(float3 rd, float reach, float dither, float t,
              constant Params& p) {
    // Where the ray passes nearest the lamp, and how far off.
    float along = dot(LAMP - EYE, rd);
    float miss = max(length(EYE + rd * along - LAMP), 0.03);
    float a0 = atan2(-along, miss);
    float a1 = atan2(reach - along, miss);
    float glow = 0.0;
    for (int i = 0; i < FOG_STEPS; i++) {
        // Steps even in the angle the lamp sees crowd where it is near.
        float f = (float(i) + dither) / float(FOG_STEPS);
        float s = along + miss * tan(mix(a0, a1, f));
        float3 q = EYE + rd * s;
        float3 d = q - LAMP;
        float r = length(d);
        d /= r;
        float between = r * exp(-0.5 * (q.y + LAMP.y) / FOG_HEIGHT);
        float crossed = between + fogCrossed(rd, s);
        float kept = exp(-THICK * p.fog * crossed);
        float turned = forwardShare(dot(d, -rd));
        glow += fogAt(q, t, p) * lampShine(d, t, p) * turned * kept;
    }
    // Even angles have already paid the 1 / r².
    return POWER * glow * (a1 - a0) / (miss * float(FOG_STEPS));
}

// The night sky in a direction: dark, a little paler at the horizon.
float3 nightSky(float3 d) {
    float up = max(d.y, 0.0);
    return mix(float3(0.007, 0.009, 0.015),
               float3(0.0015, 0.002, 0.006), pow(up, 0.45));
}

// The stars in a direction.
float starsAt(float3 d, float t) {
    float up = max(d.y, 0.0);
    // One star in some squares of a grid laid over the directions.
    float2 q = float2(atan2(d.x, d.z), asin(clamp(d.y, -1.0, 1.0))) * 70.0;
    float2 cell = floor(q);
    float pick = hash21(cell);
    float2 at = float2(hash21(cell + 3.1), hash21(cell + 7.7)) * 0.6 + 0.2;
    float2 off = fract(q) - at;
    float star = step(0.93, pick) * exp(-dot(off, off) * 110.0);
    float twinkle = 0.75 + 0.25 * sin(t * (2.0 + 5.0 * pick) + pick * 90.0);
    return star * twinkle * (pick - 0.93) * 9.0;
}

// The sea's height at a place: four trains of waves crossing each other.
float swellAt(float2 q, float t) {
    float h = 0.5 * sin(dot(q, float2(0.6, 2.0)) + t * 1.1);
    h += 0.3 * sin(dot(q, float2(-2.6, 2.9)) + t * 1.5);
    h += 0.16 * sin(dot(q, float2(5.6, 3.1)) + t * 2.0);
    h += 0.09 * sin(dot(q, float2(-2.3, 10.6)) + t * 2.7);
    return h;
}

// The way the water faces there, from the height a small step each way.
float3 seaNormal(float2 q, float t, float far, constant Params& p) {
    // Far waves are smaller than a pixel: let them flatten out.
    float tall = 0.06 * p.swell * exp(-0.1 * far);
    float2 e = float2(0.02, 0.0);
    float dx = swellAt(q + e.xy, t) - swellAt(q - e.xy, t);
    float dz = swellAt(q + e.yx, t) - swellAt(q - e.yx, t);
    return normalize(float3(-dx * tall / 0.04, 1.0, -dz * tall / 0.04));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float t = u.time;
    // The camera looks from the boat at a point on the tower.
    float3 fw = normalize(float3(0.0, 0.72, 0.0) - EYE);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 upw = cross(fw, right);
    float3 rd = normalize(fw * 2.0 + right * s.x + upw * s.y);

    // What the ray meets: the tower, the sea, or the sky.
    float3 col = float3(0.0);
    float reach = meetTower(rd);
    float sea = rd.y < 0.0 ? -EYE.y / rd.y : 2.0 * FAR;
    if (reach < FAR && reach < sea) {
        float3 q = EYE + rd * reach;
        float3 n = towerNormal(q);
        float r = length(q.xz);
        // Bands of cream and ember up the tower, under a dark sky.
        float band = step(0.5, fract(q.y * 3.2 + 0.2));
        float3 paint = mix(float3(0.75, 0.2, 0.08),
                           float3(0.9, 0.85, 0.74), band);
        if (q.y < 0.085 || q.y > 0.855) paint = float3(0.12, 0.11, 0.1);
        col = paint * (0.01 + 0.03 * max(n.y, 0.0)
                       + 0.02 * max(-n.z, 0.0));
        // The lantern's glass shows the lamp.
        if (q.y > 0.885 && q.y < 1.055 && r < 0.07) {
            // It is brightest where a beam points out through it.
            float3 out = normalize(float3(q.x, 0.0, q.z));
            float lit = lampShine(out, t, p);
            float lens = exp(-pow((q.y - LAMP.y) / 0.035, 2.0));
            col = GOLD * (0.05 + 0.5 * lens + 9.0 * lit * lens);
        }
    } else if (rd.y < 0.0) {
        reach = min(sea, 60.0);
        float3 q = EYE + rd * sea;
        float3 n = seaNormal(q.xz, t, sea, p);
        float3 r = reflect(rd, n);
        r.y = abs(r.y);
        // Water mirrors more the flatter you look across it.
        float facing = max(dot(-rd, n), 0.0);
        float mirror = 0.02 + 0.98 * pow(1.0 - facing, 5.0);
        col = nightSky(r) * mirror + float3(0.0012, 0.002, 0.003);
        // The lamp in the waves: a glint where a slope mirrors it to the
        // eye, and a soft patch where a beam lands.
        float3 l = LAMP - q;
        float lr = length(l);
        l /= lr;
        float dim = exp(-THICK * p.fog * lr * exp(-0.5 * LAMP.y / FOG_HEIGHT));
        float shine = lampShine(-l, t, p) * dim;
        float glint = pow(max(dot(r, l), 0.0), 700.0);
        float patch = 0.012 * max(dot(n, l), 0.0);
        col += GOLD * POWER * shine * (glint * 12.0 + patch) / (lr * lr);
    } else {
        reach = FAR;
        col = nightSky(rd) + float3(0.8, 0.85, 1.0) * starsAt(rd, t);
    }

    // Fog in front of it: it hides what is behind, glows a little by
    // itself, and carries the lamp's light.
    float kept = exp(-THICK * p.fog * fogCrossed(rd, reach));
    float3 haze = float3(0.004, 0.005, 0.008);
    col = col * kept + haze * (1.0 - kept);
    // Each pixel starts its steps a little differently, in a pattern that
    // spreads the difference evenly, so bands become fine grain.
    float2 px = floor(uv * u.resolution);
    float dither = fract(52.9829189
                         * fract(dot(px, float2(0.06711056, 0.00583715))));
    col += GOLD * fogGlow(rd, reach, dither, t, p);

    // The lens itself, when a beam points at the eye: a glare with a
    // streak across it, as an eye or a camera sees a bright point.
    float3 toLamp = LAMP - EYE;
    float away = length(toLamp);
    toLamp /= away;
    float2 lampAt = float2(dot(toLamp, right), dot(toLamp, upw))
                  * 2.0 / dot(toLamp, fw);
    float2 from = s - lampAt;
    float seen = lampShine(-toLamp, t, p)
               * exp(-THICK * p.fog * fogCrossed(toLamp, away));
    float halo = 0.0009 / (dot(from, from) + 0.0003);
    float streak = 0.004 / (abs(from.y) * 90.0 + 0.05)
                 * exp(-abs(from.x) * 2.2);
    col += GOLD * p.glare * seen * (halo + streak) * 6.0;

    // Bright light goes to white, then the screen's curve.
    col = 1.0 - exp(-col * 1.6);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// ---- The sound ---------------------------------------------------------
// The same night, heard. The sea is noise that swells and falls with the
// waves, the lens hums as it turns and swells when a beam passes over the
// listener, and a foghorn sounds two notes every twenty seconds, louder
// the thicker the fog.

// Integer hash, so noise stays exact for minutes of sound.
float hashU(uint n) {
    n = (n << 13u) ^ n;
    n = n * (n * n * 15731u + 789221u) + 1376312589u;
    return float(n & 0x7fffffffu) / float(0x7fffffff);
}

// Cracked Clay's sound noise: random values joined `rate` times a second.
float noise1(float t, float rate, uint seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    uint k = uint(i) + seed * 7919u;
    return mix(hashU(k), hashU(k + 1u), f) * 2.0 - 1.0;
}

// One blast of the horn at `since` seconds after it starts: a low note
// with its overtones, `lasts` seconds from swell to fall.
float horn(float since, float hz, float lasts) {
    if (since < 0.0 || since > lasts) return 0.0;
    float env = smoothstep(0.0, 0.25, since)
              * (1.0 - smoothstep(lasts - 0.5, lasts, since));
    float tone = 0.0;
    for (int k = 1; k <= 6; k++) {
        float level = 1.0 / float(k * k) + (k == 3 ? 0.25 : 0.0);
        tone += sin(TAU * hz * float(k) * since) * level;
    }
    return tone * env;
}

float2 sound(float t, constant Params& p) {
    // The sea: two bands of noise, washing in every seven seconds or so.
    float wash = 0.5 + 0.5 * sin(TAU * t / 7.0 + sin(TAU * t / 19.0));
    float run = (0.25 + 0.75 * wash * wash) * (0.4 + 0.6 * p.swell / 2.5);
    float low = noise1(t, 420.0, 1u), high = noise1(t, 2100.0, 2u);
    float2 surf = float2(0.7 * low + 0.3 * high,
                         0.7 * noise1(t, 450.0, 3u) + 0.3 * high);
    surf *= 0.16 * run;

    // The lens: a hum on D2 and A2 that leans to the side its beam points,
    // and a swell on D3 as a beam passes over the listener.
    float angle = TAU * (t - FIRST) / p.turn;
    float pan = 0.5 + 0.35 * sin(angle);
    float hum = (sin(TAU * 73.42 * t) + 0.5 * sin(TAU * 110.0 * t)) * 0.045;
    float pass = lampShine(normalize(EYE - LAMP), t, p);
    float beam = (sin(TAU * 146.83 * t) + 0.4 * sin(TAU * 293.66 * t)
                  + 0.2 * sin(TAU * 440.0 * t)) * 0.16 * sqrt(pass);
    float2 lens = float2(1.0 - pan, pan) * hum * 2.0 + beam;

    // The foghorn: F2 for two seconds, then C2, and their echo.
    float since = fract(t / 20.0) * 20.0 - 6.0;
    float call = horn(since, 87.31, 2.0) + horn(since - 2.3, 65.41, 2.6);
    float echo = horn(since - 0.7, 87.31, 2.0)
               + horn(since - 3.0, 65.41, 2.6);
    float thick = min(p.fog, 2.0) * 0.5;
    float2 fogHorn = (float2(0.55, 0.45) * call
                      + float2(0.2, 0.3) * echo * 0.5) * 0.3 * thick;

    float2 all = surf + lens + fogHorn;
    // Silence where the minute comes round, so it ends without a click.
    float round = fract(t / 60.0);
    float fade = 1.0 - exp(-min(round, 1.0 - round) * 60.0 * 30.0);
    return tanh(all * 2.4) * 0.85 * p.volume * fade;
}
4 lines from stage 4 that are gone
        float3 r = float3(rd.x, -rd.y, rd.z);
        float mirror = 0.02 + 0.98 * pow(1.0 - max(-rd.y, 0.0), 5.0);
⋯
        col = nightSky(rd);
⋯
    float run = (0.25 + 0.75 * wash * wash) * 0.64;

The sound

The same night, heard. The sea is noise made by hashing the time and smoothing between the hashes, 420 and 450 values a second for the two ears with 2,100 a second on top, washing in about every seven seconds and louder with swell.

The lens hums as it turns: D2 and A2 (73.4 and 110 Hz), leaning to the left or right ear with the side a beam points. pass is lampShine in the direction of the boat, the same number that makes the glare, and a chord on D3 swells with its square root, so you hear each beam go over you as you see it: every five seconds at the defaults.

Every twenty seconds a foghorn sounds, six seconds in: F2 (87.3 Hz) for two seconds, then C2 (65.4 Hz) for 2.6, each with five overtones, and an echo 0.7 s behind. It is louder the thicker the fog, up to fog 2, and silent with no fog at all. The sound falls to silence for a moment where the minute comes round.

At the defaults the peak is −6.8 dBFS and the average (RMS) −20.8 dBFS over the minute. With volume, fog and swell at their highest it reaches a peak of −3.1 dBFS and an RMS of −16.3 dBFS.

New in Ray Kiln

Pin a pixel. The pixel loupe tells you a pixel's color now. Pinning tells you what it does over time. In the playground, hold Shift and click a point of the picture, or press Pin and then click (on a phone, tap). A ring marks the point, and a plot appears under the picture: the last ten seconds of the clock, with that pixel's red, green and blue as thin lines and its brightness as a thicker cream one. The pixel is read back from every frame drawn, with the time of the frame it came from. Each peak of the brightness gets a gold mark along the top, and the line under the plot gives the color now, the brightness's range, when the last peak was and how long after the one before it came.

Brightness here is relative luminance, measured in linear light, the same measure the flash check uses, so it is a much smaller number than the bytes suggest for a dark pixel: a gray of 128 out of 255 has a brightness of 0.216. The pin stays on the same point when the picture changes size. Pausing holds the plot, and Restart or dragging the clock back starts it again. Shift-click somewhere else moves the pin; Unpin lets it go. It works on any shader.

A lighthouse is known by its timing: sailors tell one from another by counting the seconds between flashes. Pin the lantern, the bright point at the top of the tower, and let the clock run past 14 s. The glass is bright all the time, and its brightness climbs to 1 each time a beam finds you; the line under the plot says each peak came 5.0 s after the one before, give or take a frame: two beams on a lens that turns once in ten seconds. Set beams to 3 and the peaks come 3.3 s apart. Now set it back and pin a point in the fog well to the right of the tower. That fog is dim, about 0.02 to 0.2, and it peaks before the lantern does, since the beam crosses it on its way round to you, with more than one hump on the way: the beam that reaches it has been broken up by the window bars and the banks.

Try this

  • Set fog to 0. The beams are gone, and so is the foghorn. The lamp, the stars and the lamp's image in the water are all that is left, and the lens still glares every five seconds: the light was always there, with nothing to show it.
  • Set spread to 2 and wait for a beam to find you: instead of filling the picture, the lit fog is a narrow pillar standing over the lamp.
  • Set beams to 4 and spread to 20 for a lamp that is nearly bare again, the stage 2 halo with four soft arms.
  • Set swell to 0: the lamp's image in the water is one round spot. At 2.5 it is a long road of dashes.
  • In the code, change FORWARD from 0.22 to 0.8, fog that sends nearly all its light straight on. The beam pointing away from you nearly vanishes, and when a beam finds you the glow round the lamp is a ball of white.
  • Pin a point in the fog to the left of the tower, and see whether its peaks come before or after the lantern's.

Parameters

ParameterDefaultRangeWhat it does
turn104 to 30Seconds the lens takes to go round once
beams21 to 4How many beams the lens throws
spread62 to 20How wide each beam is, in degrees
fog10 to 3How much fog there is
swell10 to 2.5How high the sea runs
glare10 to 2How much the lens glares when a beam finds the eye
volume0.80 to 1Loudness of the sound

More from this shader

The same shader 8 more ways: each from a different moment, with different settings, one after another. Each chapter below says which settings moved most, then lists them all.

Wallpapers

A still from the shader, rendered at full size for a desktop or a phone screen. Free to use as your wallpaper.

Clips to post

Fifteen seconds of the shader with its sound, sized for posting: square for feeds, vertical for stories and short videos. Free to post, ideally with a link to this page.

The full source

This is the whole episode: the picture, the parameters and the sound.

lighthouse.metal
// Ray Kiln · Lighthouse
//
// @episode Lighthouse
// @length 60
// @variation 30
// @variations 1,2,3,4,5,7,8,10
// @sweeps fog, spread, swell
// @still 13
// @teaches A beam through fog, light shafts, a sea at night
// @category Fragment
// @tags fog, volume rendering, light shafts, equi-angular sampling, phase function, raymarching, reflection, procedural sound
// @final Lighthouse | The sea rolls and mirrors the lamp, stars come out, and the lens glares when a beam finds you.
//
// A lighthouse on a rock at night, seen from a boat. Air alone shows no
// beam: the light has to meet something on its way. Here it meets fog.
// Every pixel looks along a ray and adds up the lamp's light that the fog
// on it sends towards the eye, with its steps laid out evenly in angle as
// the lamp sees them, so most fall where the ray passes nearest the lamp.
// The lens throws two beams that turn once in ten seconds, the lantern's
// window bars cut them into shafts, and every five seconds a beam finds
// the eye.
// Each @param line below becomes a slider in the host app and a row in the page's parameters table:
//   // @param name default min max description

// @param turn 10 4 30 Seconds the lens takes to go round once
// @param beams 2 1 4 How many beams the lens throws
// @param spread 6 2 20 How wide each beam is, in degrees
// @param fog 1 0 3 How much fog there is
// @param swell 1 0 2.5 How high the sea runs
// @param glare 1 0 2 How much the lens glares when a beam finds the eye
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The eye, on a boat 4.4 units out, and the lamp, 0.97 up the tower.
constant float3 EYE = float3(0.0, 0.3, -4.4);
constant float3 LAMP = float3(0.0, 0.97, 0.0);
// The lamp's color, and how strong it is: the lens gathers its light
// into beams, sixteen times as bright as the bare lamp.
constant float3 GOLD = float3(1.0, 0.64, 0.3);
constant float POWER = 56.0;
// What a unit of fog takes out of light crossing it.
constant float THICK = 0.11;
// How much of fog's light goes straight on (Henyey and Greenstein's g).
constant float FORWARD = 0.22;
// The beams' height: a fan 9 degrees up and down.
constant float FAN = 0.16;
// When a beam first points at the eye.
constant float FIRST = 4.0;
constant int FOG_STEPS = 56;
// Fog thins with height: 0.9 up there is 1/e of it left.
constant float FOG_HEIGHT = 0.9;
constant float FAR = 16.0;

float hash21(float2 p) {
    p = fract(p * float2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
}

// Kiln Fire's 3D hash, value noise and fractal noise.
float hash31(float3 p) {
    uint3 v = uint3(int3(floor(p))) * 1664525u + 1013904223u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    v ^= v >> 16u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    return float(v.x) * (1.0 / 4294967295.0);
}

float vnoise3(float3 p) {
    float3 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash31(i),                     b = hash31(i + float3(1, 0, 0));
    float c = hash31(i + float3(0, 1, 0)),   d = hash31(i + float3(1, 1, 0));
    float e = hash31(i + float3(0, 0, 1)),   g = hash31(i + float3(1, 0, 1));
    float h = hash31(i + float3(0, 1, 1)),   k = hash31(i + float3(1, 1, 1));
    float lo = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
    float hi = mix(mix(e, g, f.x), mix(h, k, f.x), f.y);
    return mix(lo, hi, f.z);
}

float fbm3(float3 p, int octaves) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < octaves; i++) {
        v += a * vnoise3(p);
        p = p * 2.02 + float3(17.1, 9.2, 4.7);
        a *= 0.5;
    }
    return v;
}

// The distance to the rock and the lighthouse: a tower that narrows as
// it rises, a gallery, the lantern room and its roof.
float towerDist(float3 q) {
    float r = length(q.xz);
    float rock = (length(q / float3(0.62, 0.15, 0.5)) - 1.0) * 0.15;
    float h = clamp((q.y - 0.08) / 0.78, 0.0, 1.0);
    float shaft = max(r - mix(0.11, 0.07, h), abs(q.y - 0.47) - 0.39);
    float gallery = max(r - 0.1, abs(q.y - 0.87) - 0.012);
    float room = max(r - 0.058, abs(q.y - 0.97) - 0.09);
    float roof = max(r - 0.75 * (1.16 - q.y), abs(q.y - 1.11) - 0.05);
    return min(min(rock, shaft), min(min(gallery, room), roof));
}

float3 towerNormal(float3 q) {
    float2 e = float2(0.002, 0.0);
    return normalize(float3(
        towerDist(q + e.xyy) - towerDist(q - e.xyy),
        towerDist(q + e.yxy) - towerDist(q - e.yxy),
        towerDist(q + e.yyx) - towerDist(q - e.yyx)));
}

// How far along the ray it meets the rock or the tower, or FAR.
float meetTower(float3 rd) {
    float s = 3.2;
    for (int i = 0; i < 56; i++) {
        float d = towerDist(EYE + rd * s);
        if (d < 0.0015) return s;
        s += d;
        if (s > 8.0) break;
    }
    return FAR;
}

// The light leaving the lamp in direction d: a little every way, and
// the beams, which turn.
float lampShine(float3 d, float t, constant Params& p) {
    float around = atan2(d.x, d.z);
    float slice = TAU / max(floor(p.beams + 0.5), 1.0);
    float a = around - PI - TAU * (t - FIRST) / p.turn;
    a -= slice * floor(a / slice + 0.5);
    float w = p.spread * PI / 180.0;
    float up = asin(clamp(d.y, -1.0, 1.0));
    float beam = exp(-a * a / (w * w) - up * up / (FAN * FAN));
    // The lantern's eight window bars stand still and shade the light.
    float bars = 1.0 - 0.85 * smoothstep(0.74, 0.96, -cos(8.0 * around));
    return 0.006 + beam * bars;
}

// How much fog there is at a point: thickest on the water, in drifting
// banks.
float fogAt(float3 q, float t, constant Params& p) {
    float low = exp(-max(q.y, 0.0) / FOG_HEIGHT);
    float3 drift = float3(0.09, 0.015, 0.04) * t;
    float banks = fbm3(q * 1.3 + drift, 3);
    return p.fog * low * (0.2 + 1.8 * smoothstep(0.15, 0.75, banks));
}

// How much fog a ray from the eye has crossed after s units: the sum of
// exp(-height / FOG_HEIGHT) along it, which has a closed form.
float fogCrossed(float3 rd, float s) {
    float k = rd.y / FOG_HEIGHT;
    float start = exp(-EYE.y / FOG_HEIGHT);
    if (abs(k) < 0.001) return start * s;
    return start * (1.0 - exp(-k * s)) / k;
}

// The share of fog-scattered light that turns by the angle whose cosine
// is mu: most of it goes nearly straight on.
float forwardShare(float mu) {
    float g = FORWARD;
    return (1.0 - g * g) / (4.0 * PI * pow(1.0 + g * g - 2.0 * g * mu, 1.5));
}

// The lamp's light the fog sends along the ray to the eye.
float fogGlow(float3 rd, float reach, float dither, float t,
              constant Params& p) {
    // Where the ray passes nearest the lamp, and how far off.
    float along = dot(LAMP - EYE, rd);
    float miss = max(length(EYE + rd * along - LAMP), 0.03);
    float a0 = atan2(-along, miss);
    float a1 = atan2(reach - along, miss);
    float glow = 0.0;
    for (int i = 0; i < FOG_STEPS; i++) {
        // Steps even in the angle the lamp sees crowd where it is near.
        float f = (float(i) + dither) / float(FOG_STEPS);
        float s = along + miss * tan(mix(a0, a1, f));
        float3 q = EYE + rd * s;
        float3 d = q - LAMP;
        float r = length(d);
        d /= r;
        float between = r * exp(-0.5 * (q.y + LAMP.y) / FOG_HEIGHT);
        float crossed = between + fogCrossed(rd, s);
        float kept = exp(-THICK * p.fog * crossed);
        float turned = forwardShare(dot(d, -rd));
        glow += fogAt(q, t, p) * lampShine(d, t, p) * turned * kept;
    }
    // Even angles have already paid the 1 / r².
    return POWER * glow * (a1 - a0) / (miss * float(FOG_STEPS));
}

// The night sky in a direction: dark, a little paler at the horizon.
float3 nightSky(float3 d) {
    float up = max(d.y, 0.0);
    return mix(float3(0.007, 0.009, 0.015),
               float3(0.0015, 0.002, 0.006), pow(up, 0.45));
}

// The stars in a direction.
float starsAt(float3 d, float t) {
    float up = max(d.y, 0.0);
    // One star in some squares of a grid laid over the directions.
    float2 q = float2(atan2(d.x, d.z), asin(clamp(d.y, -1.0, 1.0))) * 70.0;
    float2 cell = floor(q);
    float pick = hash21(cell);
    float2 at = float2(hash21(cell + 3.1), hash21(cell + 7.7)) * 0.6 + 0.2;
    float2 off = fract(q) - at;
    float star = step(0.93, pick) * exp(-dot(off, off) * 110.0);
    float twinkle = 0.75 + 0.25 * sin(t * (2.0 + 5.0 * pick) + pick * 90.0);
    return star * twinkle * (pick - 0.93) * 9.0;
}

// The sea's height at a place: four trains of waves crossing each other.
float swellAt(float2 q, float t) {
    float h = 0.5 * sin(dot(q, float2(0.6, 2.0)) + t * 1.1);
    h += 0.3 * sin(dot(q, float2(-2.6, 2.9)) + t * 1.5);
    h += 0.16 * sin(dot(q, float2(5.6, 3.1)) + t * 2.0);
    h += 0.09 * sin(dot(q, float2(-2.3, 10.6)) + t * 2.7);
    return h;
}

// The way the water faces there, from the height a small step each way.
float3 seaNormal(float2 q, float t, float far, constant Params& p) {
    // Far waves are smaller than a pixel: let them flatten out.
    float tall = 0.06 * p.swell * exp(-0.1 * far);
    float2 e = float2(0.02, 0.0);
    float dx = swellAt(q + e.xy, t) - swellAt(q - e.xy, t);
    float dz = swellAt(q + e.yx, t) - swellAt(q - e.yx, t);
    return normalize(float3(-dx * tall / 0.04, 1.0, -dz * tall / 0.04));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float t = u.time;
    // The camera looks from the boat at a point on the tower.
    float3 fw = normalize(float3(0.0, 0.72, 0.0) - EYE);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 upw = cross(fw, right);
    float3 rd = normalize(fw * 2.0 + right * s.x + upw * s.y);

    // What the ray meets: the tower, the sea, or the sky.
    float3 col = float3(0.0);
    float reach = meetTower(rd);
    float sea = rd.y < 0.0 ? -EYE.y / rd.y : 2.0 * FAR;
    if (reach < FAR && reach < sea) {
        float3 q = EYE + rd * reach;
        float3 n = towerNormal(q);
        float r = length(q.xz);
        // Bands of cream and ember up the tower, under a dark sky.
        float band = step(0.5, fract(q.y * 3.2 + 0.2));
        float3 paint = mix(float3(0.75, 0.2, 0.08),
                           float3(0.9, 0.85, 0.74), band);
        if (q.y < 0.085 || q.y > 0.855) paint = float3(0.12, 0.11, 0.1);
        col = paint * (0.01 + 0.03 * max(n.y, 0.0)
                       + 0.02 * max(-n.z, 0.0));
        // The lantern's glass shows the lamp.
        if (q.y > 0.885 && q.y < 1.055 && r < 0.07) {
            // It is brightest where a beam points out through it.
            float3 out = normalize(float3(q.x, 0.0, q.z));
            float lit = lampShine(out, t, p);
            float lens = exp(-pow((q.y - LAMP.y) / 0.035, 2.0));
            col = GOLD * (0.05 + 0.5 * lens + 9.0 * lit * lens);
        }
    } else if (rd.y < 0.0) {
        reach = min(sea, 60.0);
        float3 q = EYE + rd * sea;
        float3 n = seaNormal(q.xz, t, sea, p);
        float3 r = reflect(rd, n);
        r.y = abs(r.y);
        // Water mirrors more the flatter you look across it.
        float facing = max(dot(-rd, n), 0.0);
        float mirror = 0.02 + 0.98 * pow(1.0 - facing, 5.0);
        col = nightSky(r) * mirror + float3(0.0012, 0.002, 0.003);
        // The lamp in the waves: a glint where a slope mirrors it to the
        // eye, and a soft patch where a beam lands.
        float3 l = LAMP - q;
        float lr = length(l);
        l /= lr;
        float dim = exp(-THICK * p.fog * lr * exp(-0.5 * LAMP.y / FOG_HEIGHT));
        float shine = lampShine(-l, t, p) * dim;
        float glint = pow(max(dot(r, l), 0.0), 700.0);
        float patch = 0.012 * max(dot(n, l), 0.0);
        col += GOLD * POWER * shine * (glint * 12.0 + patch) / (lr * lr);
    } else {
        reach = FAR;
        col = nightSky(rd) + float3(0.8, 0.85, 1.0) * starsAt(rd, t);
    }

    // Fog in front of it: it hides what is behind, glows a little by
    // itself, and carries the lamp's light.
    float kept = exp(-THICK * p.fog * fogCrossed(rd, reach));
    float3 haze = float3(0.004, 0.005, 0.008);
    col = col * kept + haze * (1.0 - kept);
    // Each pixel starts its steps a little differently, in a pattern that
    // spreads the difference evenly, so bands become fine grain.
    float2 px = floor(uv * u.resolution);
    float dither = fract(52.9829189
                         * fract(dot(px, float2(0.06711056, 0.00583715))));
    col += GOLD * fogGlow(rd, reach, dither, t, p);

    // The lens itself, when a beam points at the eye: a glare with a
    // streak across it, as an eye or a camera sees a bright point.
    float3 toLamp = LAMP - EYE;
    float away = length(toLamp);
    toLamp /= away;
    float2 lampAt = float2(dot(toLamp, right), dot(toLamp, upw))
                  * 2.0 / dot(toLamp, fw);
    float2 from = s - lampAt;
    float seen = lampShine(-toLamp, t, p)
               * exp(-THICK * p.fog * fogCrossed(toLamp, away));
    float halo = 0.0009 / (dot(from, from) + 0.0003);
    float streak = 0.004 / (abs(from.y) * 90.0 + 0.05)
                 * exp(-abs(from.x) * 2.2);
    col += GOLD * p.glare * seen * (halo + streak) * 6.0;

    // Bright light goes to white, then the screen's curve.
    col = 1.0 - exp(-col * 1.6);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// ---- The sound ---------------------------------------------------------
// The same night, heard. The sea is noise that swells and falls with the
// waves, the lens hums as it turns and swells when a beam passes over the
// listener, and a foghorn sounds two notes every twenty seconds, louder
// the thicker the fog.

// Integer hash, so noise stays exact for minutes of sound.
float hashU(uint n) {
    n = (n << 13u) ^ n;
    n = n * (n * n * 15731u + 789221u) + 1376312589u;
    return float(n & 0x7fffffffu) / float(0x7fffffff);
}

// Cracked Clay's sound noise: random values joined `rate` times a second.
float noise1(float t, float rate, uint seed) {
    float x = t * rate;
    float i = floor(x), f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    uint k = uint(i) + seed * 7919u;
    return mix(hashU(k), hashU(k + 1u), f) * 2.0 - 1.0;
}

// One blast of the horn at `since` seconds after it starts: a low note
// with its overtones, `lasts` seconds from swell to fall.
float horn(float since, float hz, float lasts) {
    if (since < 0.0 || since > lasts) return 0.0;
    float env = smoothstep(0.0, 0.25, since)
              * (1.0 - smoothstep(lasts - 0.5, lasts, since));
    float tone = 0.0;
    for (int k = 1; k <= 6; k++) {
        float level = 1.0 / float(k * k) + (k == 3 ? 0.25 : 0.0);
        tone += sin(TAU * hz * float(k) * since) * level;
    }
    return tone * env;
}

float2 sound(float t, constant Params& p) {
    // The sea: two bands of noise, washing in every seven seconds or so.
    float wash = 0.5 + 0.5 * sin(TAU * t / 7.0 + sin(TAU * t / 19.0));
    float run = (0.25 + 0.75 * wash * wash) * (0.4 + 0.6 * p.swell / 2.5);
    float low = noise1(t, 420.0, 1u), high = noise1(t, 2100.0, 2u);
    float2 surf = float2(0.7 * low + 0.3 * high,
                         0.7 * noise1(t, 450.0, 3u) + 0.3 * high);
    surf *= 0.16 * run;

    // The lens: a hum on D2 and A2 that leans to the side its beam points,
    // and a swell on D3 as a beam passes over the listener.
    float angle = TAU * (t - FIRST) / p.turn;
    float pan = 0.5 + 0.35 * sin(angle);
    float hum = (sin(TAU * 73.42 * t) + 0.5 * sin(TAU * 110.0 * t)) * 0.045;
    float pass = lampShine(normalize(EYE - LAMP), t, p);
    float beam = (sin(TAU * 146.83 * t) + 0.4 * sin(TAU * 293.66 * t)
                  + 0.2 * sin(TAU * 440.0 * t)) * 0.16 * sqrt(pass);
    float2 lens = float2(1.0 - pan, pan) * hum * 2.0 + beam;

    // The foghorn: F2 for two seconds, then C2, and their echo.
    float since = fract(t / 20.0) * 20.0 - 6.0;
    float call = horn(since, 87.31, 2.0) + horn(since - 2.3, 65.41, 2.6);
    float echo = horn(since - 0.7, 87.31, 2.0)
               + horn(since - 3.0, 65.41, 2.6);
    float thick = min(p.fog, 2.0) * 0.5;
    float2 fogHorn = (float2(0.55, 0.45) * call
                      + float2(0.2, 0.3) * echo * 0.5) * 0.3 * thick;

    float2 all = surf + lens + fogHorn;
    // Silence where the minute comes round, so it ends without a click.
    float round = fract(t / 60.0);
    float fade = 1.0 - exp(-min(round, 1.0 - round) * 60.0 * 30.0);
    return tanh(all * 2.4) * 0.85 * p.volume * fade;
}

Running it in your own project

Every Ray Kiln shader is the same shape. The standalone download above is the shader with the small wrapper around it that the Ray Kiln host adds, so it compiles with the ordinary Metal compiler and runs in your own app. It defines three entry points: rk_vertex (a full-screen triangle), rk_fragment (calls the shader's shade) and, for shaders with sound, the compute kernel rk_sound.

To draw it, pass the uniforms at fragment buffer 0 and the parameter values at buffer 1, in the order they are declared:

Drawing it, in Swift
struct Uniforms {
    var resolution: SIMD2<Float>
    var time: Float
    var timeDelta: Float
    var mouse: SIMD2<Float>
    var frame: UInt32
    var pad: UInt32 = 0
}

let library = try device.makeLibrary(source: standaloneSource, options: nil)
let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = library.makeFunction(name: "rk_vertex")
descriptor.fragmentFunction = library.makeFunction(name: "rk_fragment")
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
let pipeline = try device.makeRenderPipelineState(descriptor: descriptor)

// Each frame, inside a render pass:
var uniforms = Uniforms(resolution: size, time: time, timeDelta: dt, mouse: mouse, frame: frame)
var params: [Float] = [10, 2, 6, 1, 1, 1, 0.8]     // the @param defaults, in the order they are declared
encoder.setRenderPipelineState(pipeline)
encoder.setFragmentBytes(&uniforms, length: MemoryLayout<Uniforms>.stride, index: 0)
encoder.setFragmentBytes(&params, length: params.count * MemoryLayout<Float>.stride, index: 1)
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)

Time is in seconds, mouse is in pixels from the bottom left, and uv in the shader runs 0 to 1 with (0, 0) at the bottom left. Write the output as sRGB: the shader's numbers go to the screen as they are.

More in Atmosphere