Shader

Hall of Mirrors

A small room whose four walls are mirrors, with a glazed ball on a tiled floor and lamps circling it. A ray from the eye meets a mirror, turns the way a ball bounces off a wall, and goes on to the next surface, and the next: one turn of a loop for each surface, up to seven bounces. Each mirror passes on only part of the light and takes a little blue out of it, so the rooms seen in the mirrors grow dimmer and more copper the farther back they are. A glass chime echoes the same way, once for each bounce.

· 3D Scenes · Fragment shader

Teaches Many bounces of reflection, rays that keep going

Builds on Floating 3D Scene, Cracked Clay (integer hash), Glass Orb, Stained Glass

Watch

The idea

Stand between two mirrors and the room goes on forever: the mirror in front shows the mirror behind, which shows the one in front again, smaller and farther off each time. Glass Orb reflected a ray once. Where it met the glass, reflect turned it, and the turned ray asked env what the room looked like there, and that was the end of it. Here the turned ray is traced again, through the same room, and if it meets another mirror it turns again. A loop follows it from one surface to the next, one bounce per turn.

Nothing in this room needs marching. The walls, floor and ceiling are the six faces of a box, and a ray leaves a box through the face it reaches first, which takes one division per axis. The ball and the lamps are spheres, and where a ray meets a sphere is the root of a quadratic. So each bounce costs the same few lines, and eight of them are cheap. It is built in four steps.

Stage 1 · A room and a ray

The room is 4 wide, 6 deep and 2.6 high, with the floor at 0 and the middle of the floor at the origin. A ball 0.55 in radius stands in the middle, and one lamp, a small sphere 0.07 across, hangs in front of it and to the left. The eye wanders slowly near the front wall, never more than 0.75 to either side, and looks at a point 0.8 up that sways a little. The camera's three directions, fw, right and up, are made as in Floating 3D Scene, and the lens is 1.5: each ray is fw * 1.5 plus the pixel's place across and up.

hallTrace finds the nearest thing on a ray. To leave the box, each axis heads for the face on the side the ray moves toward: select(lo, hi, rd > 0.0) picks that face, and (face − ro) / rd is how far along the ray it is, for x, y and z at once. The smallest of the three is where the ray leaves, and which one it was says the surface: a side wall for x or z, the floor or the ceiling for y, with the normal facing back at the ray. Then hallSphere checks the ball and the lamp. With oc from the sphere's center to the ray's start and b = dot(oc, rd), the ray meets the sphere where h = b² − |oc|² + r² is positive, at −b − √h. Whatever is nearer wins.

What it meets is painted and lit. The floor is half-meter checkers of cream and charcoal, and hallTiles averages them over the width the pixel covers there, so far tiles fade to an even tone instead of flickering. That width, blur, is travel * pixel, how far the ray has gone times how wide a pixel is one meter away, made wider on a slant. A wall is panes of glass in dark bronze: hallGlass is 0 on a frame bar every meter (10 cm wide), on a baseboard below 0.32 and on a cornice above 2.3, and 1 on the glass between, softened over blur. hallLit lights a surface by how squarely it faces the lamp, with a sharp gloss on the bronze, the ball and the floor, less the farther the lamp is, and a shadow where the line to the lamp passes the ball. For now the glass shows only a dark, cool sheen, (0.03, 0.035, 0.04): four slate-gray walls.

The light is added up in linear numbers, and only at the end does 1 − exp(−1.1 · light) roll bright light off toward white before the screen's curve.

stage-1-a-room-and-a-ray.metal
// Stage 1 · A room and a ray
// A ball on a tiled floor in a small room, lit by one lamp. Each pixel's
// ray finds what it meets with no marching: it leaves the box of the
// room by the nearest face, and a sphere is a quadratic. The walls are
// panes of dark glass in bronze frames.

// The room: 4 wide, 6 deep, 2.6 high, the floor at 0.
constant float3 ROOM = float3(2.0, 2.6, 3.0);
// The ball in the middle, and its radius.
constant float3 BALL = float3(0.0, 0.55, 0.0);
constant float BALL_R = 0.55;
// One lamp, in front of the ball and to the left.
constant float3 LAMP = float3(-0.8, 1.8, -0.6);
constant float LAMP_R = 0.07;
// A miss: a distance far beyond the room.
constant float FAR = 1e9;

// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

// What a ray meets: how far along, which way the surface faces,
// and what: 0 floor, 1 ceiling, 2 wall, 3 ball, 4 the lamp.
struct HallHit {
    float dist;
    float3 normal;
    int kind;
};

// How far along a ray it meets a sphere, or FAR.
float hallSphere(float3 ro, float3 rd, float3 c, float r) {
    float3 oc = ro - c;
    float b = dot(oc, rd);
    float h = b * b - dot(oc, oc) + r * r;
    if (h < 0.0) return FAR;
    float d = -b - sqrt(h);
    return d > 0.0 ? d : FAR;
}

// The nearest thing along a ray. To leave the box, each axis
// heads for the face on the side the ray moves toward.
HallHit hallTrace(float3 ro, float3 rd, float t, constant Params& p) {
    float3 lo = float3(-ROOM.x, 0.0, -ROOM.z);
    float3 hi = ROOM;
    float3 safe = select(float3(1e-6), rd, abs(rd) > 1e-6);
    float3 wall = (select(lo, hi, rd > 0.0) - ro) / safe;
    HallHit hit;
    hit.dist = min(wall.x, min(wall.y, wall.z));
    if (hit.dist == wall.x) {
        hit.normal = float3(-sign(rd.x), 0.0, 0.0);
        hit.kind = 2;
    } else if (hit.dist == wall.z) {
        hit.normal = float3(0.0, 0.0, -sign(rd.z));
        hit.kind = 2;
    } else {
        hit.normal = float3(0.0, -sign(rd.y), 0.0);
        hit.kind = rd.y < 0.0 ? 0 : 1;
    }
    // The ball, standing on the floor.
    float b = hallSphere(ro, rd, BALL, BALL_R);
    if (b < hit.dist) {
        hit.dist = b;
        hit.normal = normalize(ro + rd * b - BALL);
        hit.kind = 3;
    }
    // The lamp.
    float d = hallSphere(ro, rd, LAMP, LAMP_R);
    if (d < hit.dist) {
        hit.dist = d;
        hit.normal = normalize(ro + rd * d - LAMP);
        hit.kind = 4;
    }
    return hit;
}

// How much of a wall is glass, framed by a bar every meter,
// its edges softened over blur, the width a pixel covers.
float hallGlass(float3 q, float3 n, float3 rd, int kind, float blur) {
    if (kind != 2) return 0.0;
    float along = abs(n.x) > 0.5 ? q.z : q.x;
    float bar = abs(fract(along + 0.5) - 0.5);
    float side = smoothstep(0.05 - blur, 0.05 + blur, bar);
    // A baseboard below the glass and a cornice above it.
    float low = smoothstep(0.32 - blur, 0.32 + blur, q.y);
    float high = smoothstep(ROOM.y - 0.3 + blur, ROOM.y - 0.3 - blur, q.y);
    return side * low * high;
}

// Half-meter checkers, averaged over the pixel's width.
float hallTiles(float2 q, float blur) {
    float2 w = float2(max(blur * 2.0, 1e-3));
    float2 a = abs(fract((q - 0.5 * w) * 0.5) - 0.5);
    float2 b = abs(fract((q + 0.5 * w) * 0.5) - 0.5);
    float2 i = 2.0 * (a - b) / w;
    return 0.5 - 0.5 * i.x * i.y;
}

// The light on a surface: a little from all around, and the lamp's.
float3 hallLit(float3 q, float3 n, float3 rd, float shine,
               float t, constant Params& p) {
    float3 lit = float3(0.02, 0.014, 0.012);
    // The ball hides some of the room's light near it.
    float3 toBall = BALL - q;
    float near = dot(toBall, toBall);
    lit *= 1.0 - BALL_R * BALL_R / near * max(dot(n, toBall), 0.0)
               * rsqrt(near);
    // The lamp lights what faces it, less the farther it is.
    float3 l = LAMP - q;
    float d2 = dot(l, l);
    float far = sqrt(d2);
    l /= far;
    float face = max(dot(n, l), 0.0);
    float gloss = pow(max(dot(reflect(rd, n), l), 0.0), 40.0);
    // The ball's shadow: where the line to the lamp passes it.
    float along = dot(toBall, l);
    float miss = length(toBall - l * along);
    float shadow = along > 0.0 && along < far
                 ? smoothstep(BALL_R * 0.8, BALL_R * 1.1, miss) : 1.0;
    float3 c = kiln(0.86) * 2.4 / (0.4 + d2);
    lit += c * (face + shine * gloss * 6.0) * shadow;
    return lit;
}

// What a surface that is not glass looks like, lit.
float3 hallSurface(float3 q, float3 rd, int kind, float3 n, float blur,
                   float t, constant Params& p) {
    if (kind == 4) {
        // The lamp glows, white-hot in the middle.
        float core = max(dot(-rd, n), 0.0);
        return kiln(0.86) * (2.0 + 5.0 * core);
    }
    float3 paint;
    float shine = 0.0;
    if (kind == 0) {
        // The floor: cream and charcoal tiles.
        float tile = hallTiles(q.xz * 2.0, blur * 2.0);
        float3 cream = float3(0.4, 0.31, 0.23);
        paint = mix(float3(0.03, 0.024, 0.022), cream, tile);
        shine = 0.3;
    } else if (kind == 1) {
        // The ceiling, dark.
        paint = float3(0.03, 0.022, 0.02);
    } else if (kind == 2) {
        // The frames, baseboard and cornice: dark bronze.
        paint = float3(0.08, 0.04, 0.022);
        shine = 0.6;
    } else {
        // The ball: an ember glaze.
        paint = float3(0.75, 0.2, 0.05);
        shine = 1.0;
    }
    return paint * hallLit(q, n, rd, shine, t, p);
}

// The eye wanders slowly, never near a wall.
float3 hallEye(float t, constant Params& p) {
    float a = t * 0.09;
    float x = 0.75 * sin(a);
    float z = -2.15 + 0.3 * sin(a * 1.7 + 1.0);
    float y = 1.25 + 0.15 * sin(t * 0.13);
    return float3(x, y, z);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float3 ro = hallEye(t, p);
    float3 look = float3(0.25 * sin(t * 0.07), 0.8, 0.0);
    float3 fw = normalize(look - ro);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 up = cross(fw, right);
    float lens = 1.5;
    float3 rd = normalize(fw * lens + right * s.x + up * s.y);
    // How wide a pixel is one meter away.
    float pixel = 2.0 / (u.resolution.y * lens);

    // The first surface the ray meets.
    HallHit hit = hallTrace(ro, rd, t, p);
    float3 pos = ro + rd * hit.dist;
    float3 n = hit.normal;
    float travel = hit.dist;
    // The width a pixel covers there, wider on a slant.
    float blur = travel * pixel / max(abs(dot(rd, n)), 0.25);
    float glass = hallGlass(pos, n, rd, hit.kind, blur);
    float3 seen = hallSurface(pos, rd, hit.kind, n, blur, t, p);
    float3 light = seen * (1.0 - glass);
    // The glass is only dark for now.
    light += glass * float3(0.03, 0.035, 0.04);

    // Bright light rolls off toward white, then the screen's curve.
    float3 col = 1.0 - exp(-light * 1.1);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

Stage 2 · One bounce

Now the glass is a mirror. reflect(rd, n) turns the ray as a ball bounces off a wall: the part of the direction along the normal is flipped, the rest is kept, so the angle out equals the angle in. The new ray starts a millimeter off the glass (pos + n * 0.001), so it doesn't meet the pane it just left, and hallTrace runs again. What it finds is what the mirror shows: the room again, seen from the other side, with its ball, its lamp and its floor. travel keeps growing over both legs, so the mirrored floor is blurred for the distance the light really went.

Where the glass is part of a pixel, at a frame's soft edge, the pixel is that share of the mirror and the rest frame: light += glass * shown. A mirror seen in the mirror is still bare glass, so behind the reflected room the far walls are slate again.

stage-2-one-bounce.metal12 new lines since stage 1
// Stage 2 · One bounce
// Now the glass is a mirror. Where the ray meets it, it turns as a ball
// bounces, the angle out equal to the angle in, and is traced once more.
// What it finds is what the mirror shows: the room again. A mirror seen
// in a mirror is still bare glass.

// The room: 4 wide, 6 deep, 2.6 high, the floor at 0.
constant float3 ROOM = float3(2.0, 2.6, 3.0);
// The ball in the middle, and its radius.
constant float3 BALL = float3(0.0, 0.55, 0.0);
constant float BALL_R = 0.55;
// One lamp, in front of the ball and to the left.
constant float3 LAMP = float3(-0.8, 1.8, -0.6);
constant float LAMP_R = 0.07;
// A miss: a distance far beyond the room.
constant float FAR = 1e9;

// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

// What a ray meets: how far along, which way the surface faces,
// and what: 0 floor, 1 ceiling, 2 wall, 3 ball, 4 the lamp.
struct HallHit {
    float dist;
    float3 normal;
    int kind;
};

// How far along a ray it meets a sphere, or FAR.
float hallSphere(float3 ro, float3 rd, float3 c, float r) {
    float3 oc = ro - c;
    float b = dot(oc, rd);
    float h = b * b - dot(oc, oc) + r * r;
    if (h < 0.0) return FAR;
    float d = -b - sqrt(h);
    return d > 0.0 ? d : FAR;
}

// The nearest thing along a ray. To leave the box, each axis
// heads for the face on the side the ray moves toward.
HallHit hallTrace(float3 ro, float3 rd, float t, constant Params& p) {
    float3 lo = float3(-ROOM.x, 0.0, -ROOM.z);
    float3 hi = ROOM;
    float3 safe = select(float3(1e-6), rd, abs(rd) > 1e-6);
    float3 wall = (select(lo, hi, rd > 0.0) - ro) / safe;
    HallHit hit;
    hit.dist = min(wall.x, min(wall.y, wall.z));
    if (hit.dist == wall.x) {
        hit.normal = float3(-sign(rd.x), 0.0, 0.0);
        hit.kind = 2;
    } else if (hit.dist == wall.z) {
        hit.normal = float3(0.0, 0.0, -sign(rd.z));
        hit.kind = 2;
    } else {
        hit.normal = float3(0.0, -sign(rd.y), 0.0);
        hit.kind = rd.y < 0.0 ? 0 : 1;
    }
    // The ball, standing on the floor.
    float b = hallSphere(ro, rd, BALL, BALL_R);
    if (b < hit.dist) {
        hit.dist = b;
        hit.normal = normalize(ro + rd * b - BALL);
        hit.kind = 3;
    }
    // The lamp.
    float d = hallSphere(ro, rd, LAMP, LAMP_R);
    if (d < hit.dist) {
        hit.dist = d;
        hit.normal = normalize(ro + rd * d - LAMP);
        hit.kind = 4;
    }
    return hit;
}

// How much of a wall is glass, framed by a bar every meter,
// its edges softened over blur, the width a pixel covers.
float hallGlass(float3 q, float3 n, float3 rd, int kind, float blur) {
    if (kind != 2) return 0.0;
    float along = abs(n.x) > 0.5 ? q.z : q.x;
    float bar = abs(fract(along + 0.5) - 0.5);
    float side = smoothstep(0.05 - blur, 0.05 + blur, bar);
    // A baseboard below the glass and a cornice above it.
    float low = smoothstep(0.32 - blur, 0.32 + blur, q.y);
    float high = smoothstep(ROOM.y - 0.3 + blur, ROOM.y - 0.3 - blur, q.y);
    return side * low * high;
}

// Half-meter checkers, averaged over the pixel's width.
float hallTiles(float2 q, float blur) {
    float2 w = float2(max(blur * 2.0, 1e-3));
    float2 a = abs(fract((q - 0.5 * w) * 0.5) - 0.5);
    float2 b = abs(fract((q + 0.5 * w) * 0.5) - 0.5);
    float2 i = 2.0 * (a - b) / w;
    return 0.5 - 0.5 * i.x * i.y;
}

// The light on a surface: a little from all around, and the lamp's.
float3 hallLit(float3 q, float3 n, float3 rd, float shine,
               float t, constant Params& p) {
    float3 lit = float3(0.02, 0.014, 0.012);
    // The ball hides some of the room's light near it.
    float3 toBall = BALL - q;
    float near = dot(toBall, toBall);
    lit *= 1.0 - BALL_R * BALL_R / near * max(dot(n, toBall), 0.0)
               * rsqrt(near);
    // The lamp lights what faces it, less the farther it is.
    float3 l = LAMP - q;
    float d2 = dot(l, l);
    float far = sqrt(d2);
    l /= far;
    float face = max(dot(n, l), 0.0);
    float gloss = pow(max(dot(reflect(rd, n), l), 0.0), 40.0);
    // The ball's shadow: where the line to the lamp passes it.
    float along = dot(toBall, l);
    float miss = length(toBall - l * along);
    float shadow = along > 0.0 && along < far
                 ? smoothstep(BALL_R * 0.8, BALL_R * 1.1, miss) : 1.0;
    float3 c = kiln(0.86) * 2.4 / (0.4 + d2);
    lit += c * (face + shine * gloss * 6.0) * shadow;
    return lit;
}

// What a surface that is not glass looks like, lit.
float3 hallSurface(float3 q, float3 rd, int kind, float3 n, float blur,
                   float t, constant Params& p) {
    if (kind == 4) {
        // The lamp glows, white-hot in the middle.
        float core = max(dot(-rd, n), 0.0);
        return kiln(0.86) * (2.0 + 5.0 * core);
    }
    float3 paint;
    float shine = 0.0;
    if (kind == 0) {
        // The floor: cream and charcoal tiles.
        float tile = hallTiles(q.xz * 2.0, blur * 2.0);
        float3 cream = float3(0.4, 0.31, 0.23);
        paint = mix(float3(0.03, 0.024, 0.022), cream, tile);
        shine = 0.3;
    } else if (kind == 1) {
        // The ceiling, dark.
        paint = float3(0.03, 0.022, 0.02);
    } else if (kind == 2) {
        // The frames, baseboard and cornice: dark bronze.
        paint = float3(0.08, 0.04, 0.022);
        shine = 0.6;
    } else {
        // The ball: an ember glaze.
        paint = float3(0.75, 0.2, 0.05);
        shine = 1.0;
    }
    return paint * hallLit(q, n, rd, shine, t, p);
}

// The eye wanders slowly, never near a wall.
float3 hallEye(float t, constant Params& p) {
    float a = t * 0.09;
    float x = 0.75 * sin(a);
    float z = -2.15 + 0.3 * sin(a * 1.7 + 1.0);
    float y = 1.25 + 0.15 * sin(t * 0.13);
    return float3(x, y, z);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float3 ro = hallEye(t, p);
    float3 look = float3(0.25 * sin(t * 0.07), 0.8, 0.0);
    float3 fw = normalize(look - ro);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 up = cross(fw, right);
    float lens = 1.5;
    float3 rd = normalize(fw * lens + right * s.x + up * s.y);
    // How wide a pixel is one meter away.
    float pixel = 2.0 / (u.resolution.y * lens);

    // The first surface the ray meets.
    HallHit hit = hallTrace(ro, rd, t, p);
    float3 pos = ro + rd * hit.dist;
    float3 n = hit.normal;
    float travel = hit.dist;
    // The width a pixel covers there, wider on a slant.
    float blur = travel * pixel / max(abs(dot(rd, n)), 0.25);
    float glass = hallGlass(pos, n, rd, hit.kind, blur);
    float3 seen = hallSurface(pos, rd, hit.kind, n, blur, t, p);
    float3 light = seen * (1.0 - glass);
    // The mirror turns the ray: reflect flips its part along n.
    float3 rd2 = reflect(rd, n);
    // It starts again a hair off the glass, so as not to meet it.
    float3 ro2 = pos + n * 0.001;
    HallHit hit2 = hallTrace(ro2, rd2, t, p);
    float3 pos2 = ro2 + rd2 * hit2.dist;
    float3 n2 = hit2.normal;
    travel += hit2.dist;
    float blur2 = travel * pixel / max(abs(dot(rd2, n2)), 0.25);
    float glass2 = hallGlass(pos2, n2, rd2, hit2.kind, blur2);
    float3 seen2 = hallSurface(pos2, rd2, hit2.kind, n2, blur2, t, p);
    // What the mirror shows, where a mirror in it is bare glass.
    float3 shown = seen2 * (1.0 - glass2);
    shown += glass2 * float3(0.03, 0.035, 0.04);
    light += glass * shown;

    // Bright light rolls off toward white, then the screen's curve.
    float3 col = 1.0 - exp(-light * 1.1);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}
1 line from stage 1 that are gone
    light += glass * float3(0.03, 0.035, 0.04);

Stage 3 · Rays that keep going

Stage 2's two traces were the same lines twice. A loop writes them once. Each turn finds the next surface, adds what it shows, and, while it is a mirror, turns the ray and goes on. carry is how much of the pixel the ray still stands for: it starts at 1, and each mirror multiplies it by its glass, so a ray that passed a frame's soft edge carries only the glass's share of it. Each surface adds carry * seen * (1 − glass), the part of it that is not mirror.

Two things end a ray. A surface that is not glass (glass < 0.01) stops it: the floor, the ceiling, a frame, the ball, the lamp. And a ray may be mirrored only bounces times. On its turn after the last mirror the glass there shows only the dark sheen, and the loop breaks. The loop allows 8 turns, so with bounces at its highest, 7, the eighth turn is that last one.

These mirrors are perfect: carry stays 1 on clear glass, so every room is as bright as the first, deep into the picture, until the bounces run out and slate-gray glass shows at the far end of the hall.

stage-3-rays-that-keep-going.metal15 new lines since stage 2
// Stage 3 · Rays that keep going
// A loop follows the ray: each turn finds the next surface, and while
// that is a mirror the ray turns and goes on, one bounce per turn.
// Perfect mirrors keep every room as bright as the first, until the
// bounces run out and the last glass shows only a dark sheen.

// @param bounces 6 0 7 How many times a ray may be mirrored before it stops: 0 shows the bare glass

// The room: 4 wide, 6 deep, 2.6 high, the floor at 0.
constant float3 ROOM = float3(2.0, 2.6, 3.0);
// The ball in the middle, and its radius.
constant float3 BALL = float3(0.0, 0.55, 0.0);
constant float BALL_R = 0.55;
// One lamp, in front of the ball and to the left.
constant float3 LAMP = float3(-0.8, 1.8, -0.6);
constant float LAMP_R = 0.07;
// A miss: a distance far beyond the room.
constant float FAR = 1e9;

// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

// What a ray meets: how far along, which way the surface faces,
// and what: 0 floor, 1 ceiling, 2 wall, 3 ball, 4 the lamp.
struct HallHit {
    float dist;
    float3 normal;
    int kind;
};

// How far along a ray it meets a sphere, or FAR.
float hallSphere(float3 ro, float3 rd, float3 c, float r) {
    float3 oc = ro - c;
    float b = dot(oc, rd);
    float h = b * b - dot(oc, oc) + r * r;
    if (h < 0.0) return FAR;
    float d = -b - sqrt(h);
    return d > 0.0 ? d : FAR;
}

// The nearest thing along a ray. To leave the box, each axis
// heads for the face on the side the ray moves toward.
HallHit hallTrace(float3 ro, float3 rd, float t, constant Params& p) {
    float3 lo = float3(-ROOM.x, 0.0, -ROOM.z);
    float3 hi = ROOM;
    float3 safe = select(float3(1e-6), rd, abs(rd) > 1e-6);
    float3 wall = (select(lo, hi, rd > 0.0) - ro) / safe;
    HallHit hit;
    hit.dist = min(wall.x, min(wall.y, wall.z));
    if (hit.dist == wall.x) {
        hit.normal = float3(-sign(rd.x), 0.0, 0.0);
        hit.kind = 2;
    } else if (hit.dist == wall.z) {
        hit.normal = float3(0.0, 0.0, -sign(rd.z));
        hit.kind = 2;
    } else {
        hit.normal = float3(0.0, -sign(rd.y), 0.0);
        hit.kind = rd.y < 0.0 ? 0 : 1;
    }
    // The ball, standing on the floor.
    float b = hallSphere(ro, rd, BALL, BALL_R);
    if (b < hit.dist) {
        hit.dist = b;
        hit.normal = normalize(ro + rd * b - BALL);
        hit.kind = 3;
    }
    // The lamp.
    float d = hallSphere(ro, rd, LAMP, LAMP_R);
    if (d < hit.dist) {
        hit.dist = d;
        hit.normal = normalize(ro + rd * d - LAMP);
        hit.kind = 4;
    }
    return hit;
}

// How much of a wall is glass, framed by a bar every meter,
// its edges softened over blur, the width a pixel covers.
float hallGlass(float3 q, float3 n, float3 rd, int kind, float blur) {
    if (kind != 2) return 0.0;
    float along = abs(n.x) > 0.5 ? q.z : q.x;
    float bar = abs(fract(along + 0.5) - 0.5);
    float side = smoothstep(0.05 - blur, 0.05 + blur, bar);
    // A baseboard below the glass and a cornice above it.
    float low = smoothstep(0.32 - blur, 0.32 + blur, q.y);
    float high = smoothstep(ROOM.y - 0.3 + blur, ROOM.y - 0.3 - blur, q.y);
    return side * low * high;
}

// Half-meter checkers, averaged over the pixel's width.
float hallTiles(float2 q, float blur) {
    float2 w = float2(max(blur * 2.0, 1e-3));
    float2 a = abs(fract((q - 0.5 * w) * 0.5) - 0.5);
    float2 b = abs(fract((q + 0.5 * w) * 0.5) - 0.5);
    float2 i = 2.0 * (a - b) / w;
    return 0.5 - 0.5 * i.x * i.y;
}

// The light on a surface: a little from all around, and the lamp's.
float3 hallLit(float3 q, float3 n, float3 rd, float shine,
               float t, constant Params& p) {
    float3 lit = float3(0.02, 0.014, 0.012);
    // The ball hides some of the room's light near it.
    float3 toBall = BALL - q;
    float near = dot(toBall, toBall);
    lit *= 1.0 - BALL_R * BALL_R / near * max(dot(n, toBall), 0.0)
               * rsqrt(near);
    // The lamp lights what faces it, less the farther it is.
    float3 l = LAMP - q;
    float d2 = dot(l, l);
    float far = sqrt(d2);
    l /= far;
    float face = max(dot(n, l), 0.0);
    float gloss = pow(max(dot(reflect(rd, n), l), 0.0), 40.0);
    // The ball's shadow: where the line to the lamp passes it.
    float along = dot(toBall, l);
    float miss = length(toBall - l * along);
    float shadow = along > 0.0 && along < far
                 ? smoothstep(BALL_R * 0.8, BALL_R * 1.1, miss) : 1.0;
    float3 c = kiln(0.86) * 2.4 / (0.4 + d2);
    lit += c * (face + shine * gloss * 6.0) * shadow;
    return lit;
}

// What a surface that is not glass looks like, lit.
float3 hallSurface(float3 q, float3 rd, int kind, float3 n, float blur,
                   float t, constant Params& p) {
    if (kind == 4) {
        // The lamp glows, white-hot in the middle.
        float core = max(dot(-rd, n), 0.0);
        return kiln(0.86) * (2.0 + 5.0 * core);
    }
    float3 paint;
    float shine = 0.0;
    if (kind == 0) {
        // The floor: cream and charcoal tiles.
        float tile = hallTiles(q.xz * 2.0, blur * 2.0);
        float3 cream = float3(0.4, 0.31, 0.23);
        paint = mix(float3(0.03, 0.024, 0.022), cream, tile);
        shine = 0.3;
    } else if (kind == 1) {
        // The ceiling, dark.
        paint = float3(0.03, 0.022, 0.02);
    } else if (kind == 2) {
        // The frames, baseboard and cornice: dark bronze.
        paint = float3(0.08, 0.04, 0.022);
        shine = 0.6;
    } else {
        // The ball: an ember glaze.
        paint = float3(0.75, 0.2, 0.05);
        shine = 1.0;
    }
    return paint * hallLit(q, n, rd, shine, t, p);
}

// The eye wanders slowly, never near a wall.
float3 hallEye(float t, constant Params& p) {
    float a = t * 0.09;
    float x = 0.75 * sin(a);
    float z = -2.15 + 0.3 * sin(a * 1.7 + 1.0);
    float y = 1.25 + 0.15 * sin(t * 0.13);
    return float3(x, y, z);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float3 ro = hallEye(t, p);
    float3 look = float3(0.25 * sin(t * 0.07), 0.8, 0.0);
    float3 fw = normalize(look - ro);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 up = cross(fw, right);
    float lens = 1.5;
    float3 rd = normalize(fw * lens + right * s.x + up * s.y);
    // How wide a pixel is one meter away.
    float pixel = 2.0 / (u.resolution.y * lens);

    // The bounce loop: each turn finds the next surface. A mirror
    // sends the ray on; anything else ends it.
    float3 light = float3(0.0);
    float3 carry = float3(1.0);
    float travel = 0.0;
    for (int bounce = 0; bounce < 8; bounce++) {
        HallHit hit = hallTrace(ro, rd, t, p);
        float3 pos = ro + rd * hit.dist;
        float3 n = hit.normal;
        travel += hit.dist;
        // The width a pixel covers there, wider on a slant.
        float blur = travel * pixel / max(abs(dot(rd, n)), 0.25);
        float glass = hallGlass(pos, n, rd, hit.kind, blur);
        float3 seen = hallSurface(pos, rd, hit.kind, n, blur, t, p);
        light += carry * seen * (1.0 - glass);
        // Out of bounces, the glass shows only a dark sheen.
        bool last = float(bounce) + 0.5 > p.bounces;
        if (glass < 0.01 || last) {
            light += carry * glass * float3(0.03, 0.035, 0.04);
            break;
        }
        // The mirror sends the ray on, turned; a frame stops it.
        carry *= glass;
        rd = reflect(rd, n);
        ro = pos + n * 0.001;
    }

    // Bright light rolls off toward white, then the screen's curve.
    float3 col = 1.0 - exp(-light * 1.1);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}
14 lines from stage 2 that are gone
    float travel = hit.dist;
⋯
    float3 light = seen * (1.0 - glass);
⋯
    float3 rd2 = reflect(rd, n);
⋯
    float3 ro2 = pos + n * 0.001;
    HallHit hit2 = hallTrace(ro2, rd2, t, p);
    float3 pos2 = ro2 + rd2 * hit2.dist;
    float3 n2 = hit2.normal;
    travel += hit2.dist;
    float blur2 = travel * pixel / max(abs(dot(rd2, n2)), 0.25);
    float glass2 = hallGlass(pos2, n2, rd2, hit2.kind, blur2);
    float3 seen2 = hallSurface(pos2, rd2, hit2.kind, n2, blur2, t, p);
⋯
    float3 shown = seen2 * (1.0 - glass2);
    shown += glass2 * float3(0.03, 0.035, 0.04);
    light += glass * shown;

Stage 4 · Each mirror dims and warms

No mirror is perfect. Silvered glass sends back most of the light, not all of it, and old glass tints what it sends. Now each mirror multiplies carry by silver too, and by warm, which is white with tint at 0 and (1, 0.74, 0.48) at 1: it keeps the red, less of the green and less still of the blue. This is the same carry *= … Glass Orb used for the light bouncing inside its glass.

After six mirrors, at the defaults, a ray carries 0.86⁶ of its red, 40%, but only 18% of its green and 7% of its blue. So the rooms deep in the mirrors grow dimmer and more copper the farther back they are, and the hall seems to go on into the dark.

stage-4-each-mirror-dims-and-warms.metal2 new lines since stage 3
// Stage 4 · Each mirror dims and warms
// No mirror is perfect. Each passes on only silver of the light and
// takes a little blue out of it, so carry shrinks and warms at every
// turn. The rooms in the mirrors grow dimmer and more copper the deeper
// they are, and the hall seems to go on into the dark.

// @param bounces 6 0 7 How many times a ray may be mirrored before it stops: 0 shows the bare glass
// @param silver 0.86 0.5 0.98 How much of the light each mirror passes on
// @param tint 0.5 0 1 How much warmer each mirror makes the light it passes on

// The room: 4 wide, 6 deep, 2.6 high, the floor at 0.
constant float3 ROOM = float3(2.0, 2.6, 3.0);
// The ball in the middle, and its radius.
constant float3 BALL = float3(0.0, 0.55, 0.0);
constant float BALL_R = 0.55;
// One lamp, in front of the ball and to the left.
constant float3 LAMP = float3(-0.8, 1.8, -0.6);
constant float LAMP_R = 0.07;
// A miss: a distance far beyond the room.
constant float FAR = 1e9;

// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

// What a ray meets: how far along, which way the surface faces,
// and what: 0 floor, 1 ceiling, 2 wall, 3 ball, 4 the lamp.
struct HallHit {
    float dist;
    float3 normal;
    int kind;
};

// How far along a ray it meets a sphere, or FAR.
float hallSphere(float3 ro, float3 rd, float3 c, float r) {
    float3 oc = ro - c;
    float b = dot(oc, rd);
    float h = b * b - dot(oc, oc) + r * r;
    if (h < 0.0) return FAR;
    float d = -b - sqrt(h);
    return d > 0.0 ? d : FAR;
}

// The nearest thing along a ray. To leave the box, each axis
// heads for the face on the side the ray moves toward.
HallHit hallTrace(float3 ro, float3 rd, float t, constant Params& p) {
    float3 lo = float3(-ROOM.x, 0.0, -ROOM.z);
    float3 hi = ROOM;
    float3 safe = select(float3(1e-6), rd, abs(rd) > 1e-6);
    float3 wall = (select(lo, hi, rd > 0.0) - ro) / safe;
    HallHit hit;
    hit.dist = min(wall.x, min(wall.y, wall.z));
    if (hit.dist == wall.x) {
        hit.normal = float3(-sign(rd.x), 0.0, 0.0);
        hit.kind = 2;
    } else if (hit.dist == wall.z) {
        hit.normal = float3(0.0, 0.0, -sign(rd.z));
        hit.kind = 2;
    } else {
        hit.normal = float3(0.0, -sign(rd.y), 0.0);
        hit.kind = rd.y < 0.0 ? 0 : 1;
    }
    // The ball, standing on the floor.
    float b = hallSphere(ro, rd, BALL, BALL_R);
    if (b < hit.dist) {
        hit.dist = b;
        hit.normal = normalize(ro + rd * b - BALL);
        hit.kind = 3;
    }
    // The lamp.
    float d = hallSphere(ro, rd, LAMP, LAMP_R);
    if (d < hit.dist) {
        hit.dist = d;
        hit.normal = normalize(ro + rd * d - LAMP);
        hit.kind = 4;
    }
    return hit;
}

// How much of a wall is glass, framed by a bar every meter,
// its edges softened over blur, the width a pixel covers.
float hallGlass(float3 q, float3 n, float3 rd, int kind, float blur) {
    if (kind != 2) return 0.0;
    float along = abs(n.x) > 0.5 ? q.z : q.x;
    float bar = abs(fract(along + 0.5) - 0.5);
    float side = smoothstep(0.05 - blur, 0.05 + blur, bar);
    // A baseboard below the glass and a cornice above it.
    float low = smoothstep(0.32 - blur, 0.32 + blur, q.y);
    float high = smoothstep(ROOM.y - 0.3 + blur, ROOM.y - 0.3 - blur, q.y);
    return side * low * high;
}

// Half-meter checkers, averaged over the pixel's width.
float hallTiles(float2 q, float blur) {
    float2 w = float2(max(blur * 2.0, 1e-3));
    float2 a = abs(fract((q - 0.5 * w) * 0.5) - 0.5);
    float2 b = abs(fract((q + 0.5 * w) * 0.5) - 0.5);
    float2 i = 2.0 * (a - b) / w;
    return 0.5 - 0.5 * i.x * i.y;
}

// The light on a surface: a little from all around, and the lamp's.
float3 hallLit(float3 q, float3 n, float3 rd, float shine,
               float t, constant Params& p) {
    float3 lit = float3(0.02, 0.014, 0.012);
    // The ball hides some of the room's light near it.
    float3 toBall = BALL - q;
    float near = dot(toBall, toBall);
    lit *= 1.0 - BALL_R * BALL_R / near * max(dot(n, toBall), 0.0)
               * rsqrt(near);
    // The lamp lights what faces it, less the farther it is.
    float3 l = LAMP - q;
    float d2 = dot(l, l);
    float far = sqrt(d2);
    l /= far;
    float face = max(dot(n, l), 0.0);
    float gloss = pow(max(dot(reflect(rd, n), l), 0.0), 40.0);
    // The ball's shadow: where the line to the lamp passes it.
    float along = dot(toBall, l);
    float miss = length(toBall - l * along);
    float shadow = along > 0.0 && along < far
                 ? smoothstep(BALL_R * 0.8, BALL_R * 1.1, miss) : 1.0;
    float3 c = kiln(0.86) * 2.4 / (0.4 + d2);
    lit += c * (face + shine * gloss * 6.0) * shadow;
    return lit;
}

// What a surface that is not glass looks like, lit.
float3 hallSurface(float3 q, float3 rd, int kind, float3 n, float blur,
                   float t, constant Params& p) {
    if (kind == 4) {
        // The lamp glows, white-hot in the middle.
        float core = max(dot(-rd, n), 0.0);
        return kiln(0.86) * (2.0 + 5.0 * core);
    }
    float3 paint;
    float shine = 0.0;
    if (kind == 0) {
        // The floor: cream and charcoal tiles.
        float tile = hallTiles(q.xz * 2.0, blur * 2.0);
        float3 cream = float3(0.4, 0.31, 0.23);
        paint = mix(float3(0.03, 0.024, 0.022), cream, tile);
        shine = 0.3;
    } else if (kind == 1) {
        // The ceiling, dark.
        paint = float3(0.03, 0.022, 0.02);
    } else if (kind == 2) {
        // The frames, baseboard and cornice: dark bronze.
        paint = float3(0.08, 0.04, 0.022);
        shine = 0.6;
    } else {
        // The ball: an ember glaze.
        paint = float3(0.75, 0.2, 0.05);
        shine = 1.0;
    }
    return paint * hallLit(q, n, rd, shine, t, p);
}

// The eye wanders slowly, never near a wall.
float3 hallEye(float t, constant Params& p) {
    float a = t * 0.09;
    float x = 0.75 * sin(a);
    float z = -2.15 + 0.3 * sin(a * 1.7 + 1.0);
    float y = 1.25 + 0.15 * sin(t * 0.13);
    return float3(x, y, z);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float3 ro = hallEye(t, p);
    float3 look = float3(0.25 * sin(t * 0.07), 0.8, 0.0);
    float3 fw = normalize(look - ro);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 up = cross(fw, right);
    float lens = 1.5;
    float3 rd = normalize(fw * lens + right * s.x + up * s.y);
    // How wide a pixel is one meter away.
    float pixel = 2.0 / (u.resolution.y * lens);
    // Each mirror takes some blue out of the light it passes on.
    float3 warm = mix(float3(1.0), float3(1.0, 0.74, 0.48), p.tint);

    // The bounce loop: each turn finds the next surface. A mirror
    // sends the ray on; anything else ends it.
    float3 light = float3(0.0);
    float3 carry = float3(1.0);
    float travel = 0.0;
    for (int bounce = 0; bounce < 8; bounce++) {
        HallHit hit = hallTrace(ro, rd, t, p);
        float3 pos = ro + rd * hit.dist;
        float3 n = hit.normal;
        travel += hit.dist;
        // The width a pixel covers there, wider on a slant.
        float blur = travel * pixel / max(abs(dot(rd, n)), 0.25);
        float glass = hallGlass(pos, n, rd, hit.kind, blur);
        float3 seen = hallSurface(pos, rd, hit.kind, n, blur, t, p);
        light += carry * seen * (1.0 - glass);
        // Out of bounces, the glass shows only a dark sheen.
        bool last = float(bounce) + 0.5 > p.bounces;
        if (glass < 0.01 || last) {
            light += carry * glass * float3(0.03, 0.035, 0.04);
            break;
        }
        // The mirror keeps silver of the light, warmed.
        carry *= glass * p.silver * warm;
        rd = reflect(rd, n);
        ro = pos + n * 0.001;
    }

    // Bright light rolls off toward white, then the screen's curve.
    float3 col = 1.0 - exp(-light * 1.1);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}
1 line from stage 3 that are gone
        carry *= glass;

Stage 5 · Hall of Mirrors

The finished shader has more light in the room and a better mirror for it.

The lamps: lamps of them, 1 to 6, spaced evenly round a circle 1.15 from the ball, 1.75 up, going round slowly (0.13 radians a second) and bobbing, each its own color from the kiln palette, gold to white-hot. hallTrace, hallLit and the glow all loop over them. hallHalo is the glow lamps leave in the air: for each lamp, the point on the ray's leg nearest to it, and a glow that falls off as 0.004 / (miss² + 0.003). It is added on every turn, times carry, so the lamps glow in the mirrors too.

A lamp deep in the mirrors is smaller than a pixel. Its edge now fades over a pixel, and a lamp smaller than a few pixels fades as a whole by its share of the pixel, leaving its glow, so the far lamps don't sparkle as the camera moves.

The ball's glaze mirrors too. hallGlass gives it 0.2 + 0.6 · (1 − cos)⁴: a fifth of the light head-on and up to four fifths at its rim, as glaze does at a glancing angle, so the ball carries a small curved copy of the whole hall. A curved mirror spreads the rays it sends on, so the pixel's width needs more care. width is how wide the pixel is where the ray is, and spread is how fast it grows per meter: it starts at pixel, and each bounce off the ball adds 2 · width / BALL_R, the way a convex mirror widens a beam. The tiles and frames seen in the ball are blurred by that width, and stay smooth.

drift sets how far the eye wanders: at 0 it stands still, centered between the side walls, at 2 it swings well toward the side walls.

the kiln palette and shade(), from the finished shader
// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float3 ro = hallEye(t, p);
    float3 look = float3(0.25 * p.drift * sin(t * 0.07), 0.8, 0.0);
    float3 fw = normalize(look - ro);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 up = cross(fw, right);
    float lens = 1.5;
    float3 rd = normalize(fw * lens + right * s.x + up * s.y);
    // How wide a pixel is one meter away.
    float pixel = 2.0 / (u.resolution.y * lens);
    // Each mirror takes some blue out of the light it passes on.
    float3 warm = mix(float3(1.0), float3(1.0, 0.74, 0.48), p.tint);

    // The bounce loop: each turn finds the next surface. A mirror
    // sends the ray on; anything else ends it.
    float3 light = float3(0.0);
    float3 carry = float3(1.0);
    // The width a pixel covers, and how fast it grows.
    float width = 0.0;
    float spread = pixel;
    for (int bounce = 0; bounce < 8; bounce++) {
        HallHit hit = hallTrace(ro, rd, t, p);
        float3 pos = ro + rd * hit.dist;
        float3 n = hit.normal;
        width += spread * hit.dist;
        // The width a pixel covers there, wider on a slant.
        float blur = width / max(abs(dot(rd, n)), 0.25);
        float glass = hallGlass(pos, n, rd, hit.kind, blur);
        float3 seen = hallSurface(pos, rd, hit.kind, n, blur, t, p);
        float3 halo = hallHalo(ro, rd, hit.dist, t, p);
        // The lamps' glow on the way, then the surface.
        light += carry * (halo + seen * (1.0 - glass));
        // Out of bounces, the glass shows only a dark sheen.
        bool last = float(bounce) + 0.5 > p.bounces;
        if (glass < 0.01 || last) {
            light += carry * glass * float3(0.03, 0.035, 0.04);
            break;
        }
        // The mirror keeps silver of the light, warmed.
        carry *= glass * p.silver * warm;
        // The glaze is curved, so the rays it sends on spread.
        spread += hit.kind == 3 ? 2.0 * width / BALL_R : 0.0;
        rd = reflect(rd, n);
        ro = pos + n * 0.001;
    }

    // Bright light rolls off toward white, then the screen's curve.
    float3 col = 1.0 - exp(-light * 1.1);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}
hall-of-mirrors.metal, the whole file105 new lines since stage 4
// Ray Kiln · Hall of Mirrors
//
// @episode Hall of Mirrors
// @length 60
// @variation 30
// @variations 1,3,4,5,7,9,10,11
// @still 21
// @teaches Many bounces of reflection, rays that keep going
// @category Fragment
// @tags reflection, ray tracing, lighting, procedural sound, exponential decay
// @final Hall of Mirrors | Lamps circle the ball, the glaze mirrors the hall, and the camera wanders, while every mirror hands the light on, dimmer and warmer each time.
//
// A small room whose four walls are mirrors. A ray from the eye meets a
// wall, the mirror sends it on, and it meets another wall, and another.
// One turn of a loop follows the ray from one surface to the next. Each
// mirror keeps only part of the light and warms it a little, so the
// rooms seen in the mirrors fade and turn copper as they go back.
// 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 bounces 6 0 7 How many times a ray may be mirrored before it stops: 0 shows the bare glass
// @param silver 0.86 0.5 0.98 How much of the light each mirror passes on
// @param tint 0.5 0 1 How much warmer each mirror makes the light it passes on
// @param lamps 3 1 6 How many lamps circle the ball
// @param drift 1 0 2 How far the camera wanders around the room
// @param volume 0.8 0 1 Loudness of the sound

// A full turn, in radians.
constant float TAU = 6.2831853;
// The room: 4 wide, 6 deep, 2.6 high, the floor at 0.
constant float3 ROOM = float3(2.0, 2.6, 3.0);
// The ball in the middle, and its radius.
constant float3 BALL = float3(0.0, 0.55, 0.0);
constant float BALL_R = 0.55;
constant float LAMP_R = 0.07;
// A miss: a distance far beyond the room.
constant float FAR = 1e9;

// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

// What a ray meets: how far along, which way the surface faces,
// and what: 0 floor, 1 ceiling, 2 wall, 3 ball, 4 and up a lamp.
struct HallHit {
    float dist;
    float3 normal;
    int kind;
};

// How far along a ray it meets a sphere, or FAR.
float hallSphere(float3 ro, float3 rd, float3 c, float r) {
    float3 oc = ro - c;
    float b = dot(oc, rd);
    float h = b * b - dot(oc, oc) + r * r;
    if (h < 0.0) return FAR;
    float d = -b - sqrt(h);
    return d > 0.0 ? d : FAR;
}

// Where lamp i is: the lamps circle the ball slowly and bob.
float3 hallLampAt(int i, float t, constant Params& p) {
    float n = max(floor(p.lamps + 0.5), 1.0);
    float a = TAU * float(i) / n + t * 0.13;
    float y = 1.75 + 0.18 * sin(t * 0.7 + float(i) * 2.1);
    return float3(1.15 * cos(a), y, 1.15 * sin(a));
}

// Lamp i's color, gold to white-hot.
float3 hallLampColor(int i) {
    return kiln(0.8 + 0.06 * float(i % 3));
}

// The nearest thing along a ray. To leave the box, each axis
// heads for the face on the side the ray moves toward.
HallHit hallTrace(float3 ro, float3 rd, float t, constant Params& p) {
    float3 lo = float3(-ROOM.x, 0.0, -ROOM.z);
    float3 hi = ROOM;
    float3 safe = select(float3(1e-6), rd, abs(rd) > 1e-6);
    float3 wall = (select(lo, hi, rd > 0.0) - ro) / safe;
    HallHit hit;
    hit.dist = min(wall.x, min(wall.y, wall.z));
    if (hit.dist == wall.x) {
        hit.normal = float3(-sign(rd.x), 0.0, 0.0);
        hit.kind = 2;
    } else if (hit.dist == wall.z) {
        hit.normal = float3(0.0, 0.0, -sign(rd.z));
        hit.kind = 2;
    } else {
        hit.normal = float3(0.0, -sign(rd.y), 0.0);
        hit.kind = rd.y < 0.0 ? 0 : 1;
    }
    // The ball, standing on the floor.
    float b = hallSphere(ro, rd, BALL, BALL_R);
    if (b < hit.dist) {
        hit.dist = b;
        hit.normal = normalize(ro + rd * b - BALL);
        hit.kind = 3;
    }
    // The lamps, as many as the slider asks for.
    for (int i = 0; i < 6; i++) {
        if (float(i) + 0.5 > p.lamps) break;
        float3 c = hallLampAt(i, t, p);
        float d = hallSphere(ro, rd, c, LAMP_R);
        if (d < hit.dist) {
            hit.dist = d;
            hit.normal = normalize(ro + rd * d - c);
            hit.kind = 4 + i;
        }
    }
    return hit;
}

// How much of a wall is glass, framed by a bar every meter,
// its edges softened over blur, the width a pixel covers.
float hallGlass(float3 q, float3 n, float3 rd, int kind, float blur) {
    // The ball's glaze mirrors a little, more at its edges.
    if (kind == 3) return 0.2 + 0.6 * pow(1.0 - abs(dot(rd, n)), 4.0);
    if (kind != 2) return 0.0;
    float along = abs(n.x) > 0.5 ? q.z : q.x;
    float bar = abs(fract(along + 0.5) - 0.5);
    float side = smoothstep(0.05 - blur, 0.05 + blur, bar);
    // A baseboard below the glass and a cornice above it.
    float low = smoothstep(0.32 - blur, 0.32 + blur, q.y);
    float high = smoothstep(ROOM.y - 0.3 + blur, ROOM.y - 0.3 - blur, q.y);
    return side * low * high;
}

// Half-meter checkers, averaged over the pixel's width.
float hallTiles(float2 q, float blur) {
    float2 w = float2(max(blur * 2.0, 1e-3));
    float2 a = abs(fract((q - 0.5 * w) * 0.5) - 0.5);
    float2 b = abs(fract((q + 0.5 * w) * 0.5) - 0.5);
    float2 i = 2.0 * (a - b) / w;
    return 0.5 - 0.5 * i.x * i.y;
}

// The light on a surface: a little from all around, and the lamp's.
float3 hallLit(float3 q, float3 n, float3 rd, float shine,
               float t, constant Params& p) {
    float3 lit = float3(0.02, 0.014, 0.012);
    // The ball hides some of the room's light near it.
    float3 toBall = BALL - q;
    float near = dot(toBall, toBall);
    lit *= 1.0 - BALL_R * BALL_R / near * max(dot(n, toBall), 0.0)
               * rsqrt(near);
    // Each lamp lights what faces it, less the farther it is.
    for (int i = 0; i < 6; i++) {
        if (float(i) + 0.5 > p.lamps) break;
        float3 l = hallLampAt(i, t, p) - q;
        float d2 = dot(l, l);
        float far = sqrt(d2);
        l /= far;
        float face = max(dot(n, l), 0.0);
        float gloss = pow(max(dot(reflect(rd, n), l), 0.0), 40.0);
        float along = dot(toBall, l);
        float miss = length(toBall - l * along);
        float shadow = along > 0.0 && along < far
                     ? smoothstep(BALL_R * 0.8, BALL_R * 1.1, miss) : 1.0;
        float3 c = hallLampColor(i) * 1.1 / (0.4 + d2);
        lit += c * (face + shine * gloss * 6.0) * shadow;
    }
    return lit;
}

// What a surface that is not glass looks like, lit.
float3 hallSurface(float3 q, float3 rd, int kind, float3 n, float blur,
                   float t, constant Params& p) {
    if (kind >= 4) {
        // A lamp glows in its own color, white-hot in the middle.
        float core = max(dot(-rd, n), 0.0);
        // Its rim fades over a pixel, and a lamp smaller than a few
        // pixels fades too, leaving its glow.
        float rim = (1.0 - sqrt(1.0 - core * core)) * LAMP_R / blur;
        float cover = min(LAMP_R * LAMP_R / (4.0 * blur * blur), 1.0);
        float shown = min(rim, 1.0) * cover;
        return hallLampColor(kind - 4) * (1.2 + 2.0 * core) * shown;
    }
    float3 paint;
    float shine = 0.0;
    if (kind == 0) {
        // The floor: cream and charcoal tiles.
        float tile = hallTiles(q.xz * 2.0, blur * 2.0);
        float3 cream = float3(0.4, 0.31, 0.23);
        paint = mix(float3(0.03, 0.024, 0.022), cream, tile);
        shine = 0.3;
    } else if (kind == 1) {
        // The ceiling, dark.
        paint = float3(0.03, 0.022, 0.02);
    } else if (kind == 2) {
        // The frames, baseboard and cornice: dark bronze.
        paint = float3(0.08, 0.04, 0.022);
        shine = 0.6;
    } else {
        // The ball: an ember glaze.
        paint = float3(0.75, 0.2, 0.05);
        shine = 1.0;
    }
    return paint * hallLit(q, n, rd, shine, t, p);
}

// The glow lamps leave in the air: the nearer the ray passes
// a lamp before it ends, the brighter.
float3 hallHalo(float3 ro, float3 rd, float reach, float t,
                constant Params& p) {
    float3 halo = float3(0.0);
    for (int i = 0; i < 6; i++) {
        if (float(i) + 0.5 > p.lamps) break;
        float3 c = hallLampAt(i, t, p) - ro;
        float along = clamp(dot(c, rd), 0.0, reach);
        float3 miss = c - rd * along;
        halo += hallLampColor(i) * 0.004 / (dot(miss, miss) + 0.003);
    }
    return halo;
}

// The eye wanders slowly, never near a wall.
float3 hallEye(float t, constant Params& p) {
    float a = t * 0.09;
    // drift sets how far it wanders; at 0 it stands still.
    float x = 0.75 * p.drift * sin(a);
    float z = -2.15 + 0.3 * p.drift * sin(a * 1.7 + 1.0);
    float y = 1.25 + 0.15 * p.drift * sin(t * 0.13);
    return float3(x, y, z);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float3 ro = hallEye(t, p);
    float3 look = float3(0.25 * p.drift * sin(t * 0.07), 0.8, 0.0);
    float3 fw = normalize(look - ro);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 up = cross(fw, right);
    float lens = 1.5;
    float3 rd = normalize(fw * lens + right * s.x + up * s.y);
    // How wide a pixel is one meter away.
    float pixel = 2.0 / (u.resolution.y * lens);
    // Each mirror takes some blue out of the light it passes on.
    float3 warm = mix(float3(1.0), float3(1.0, 0.74, 0.48), p.tint);

    // The bounce loop: each turn finds the next surface. A mirror
    // sends the ray on; anything else ends it.
    float3 light = float3(0.0);
    float3 carry = float3(1.0);
    // The width a pixel covers, and how fast it grows.
    float width = 0.0;
    float spread = pixel;
    for (int bounce = 0; bounce < 8; bounce++) {
        HallHit hit = hallTrace(ro, rd, t, p);
        float3 pos = ro + rd * hit.dist;
        float3 n = hit.normal;
        width += spread * hit.dist;
        // The width a pixel covers there, wider on a slant.
        float blur = width / max(abs(dot(rd, n)), 0.25);
        float glass = hallGlass(pos, n, rd, hit.kind, blur);
        float3 seen = hallSurface(pos, rd, hit.kind, n, blur, t, p);
        float3 halo = hallHalo(ro, rd, hit.dist, t, p);
        // The lamps' glow on the way, then the surface.
        light += carry * (halo + seen * (1.0 - glass));
        // Out of bounces, the glass shows only a dark sheen.
        bool last = float(bounce) + 0.5 > p.bounces;
        if (glass < 0.01 || last) {
            light += carry * glass * float3(0.03, 0.035, 0.04);
            break;
        }
        // The mirror keeps silver of the light, warmed.
        carry *= glass * p.silver * warm;
        // The glaze is curved, so the rays it sends on spread.
        spread += hit.kind == 3 ? 2.0 * width / BALL_R : 0.0;
        rd = reflect(rd, n);
        ro = pos + n * 0.001;
    }

    // Bright light rolls off toward white, then the screen's curve.
    float3 col = 1.0 - exp(-light * 1.1);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// ---- The sound ---------------------------------------------------------
// The hall, heard. A glass chime is struck every few seconds, and its
// sound comes back from the mirrors, one echo per bounce, each quieter
// by silver and duller by tint, from the left and the right in turn. A
// low hum, one voice per lamp, sits under it.

// Cracked Clay's integer hash.
float hashU(uint n) {
    n = (n << 13u) ^ n;
    n = n * (n * n * 15731u + 789221u) + 1376312589u;
    return float(n & 0x7fffffffu) / float(0x7fffffff);
}

// A struck glass chime `since` seconds ago, at f hertz. Dull lowers its
// upper partials, as a warm mirror takes the blue out of light.
float hallChime(float since, float f, float dull) {
    if (since < 0.0 || since > 6.0) return 0.0;
    float attack = 1.0 - exp(-since * 90.0);
    float a = sin(TAU * fract(f * since)) * exp(-since * 1.1);
    a += 0.45 * dull * sin(TAU * fract(f * 2.76 * since)) * exp(-since * 2.2);
    a += 0.2 * dull * dull * sin(TAU * fract(f * 5.4 * since))
       * exp(-since * 3.6);
    return a * attack;
}

float2 sound(float t, constant Params& p) {
    // Where in the minute it is: no strikes in its last eight seconds.
    float m = fract(t / 60.0) * 60.0;
    float minute = floor(t / 60.0);
    float gap = 2.4;
    float2 chime = float2(0.0);
    float slot = floor(m / gap);
    for (int k = -2; k <= 0; k++) {
        float j = slot + float(k);
        if (j < 0.0 || j * gap > 51.0) continue;
        uint id = uint(j + minute * 25.0);
        float rank = floor(hashU(id * 3u + 1u) * 5.0);
        float semis = rank < 1.0 ? 0.0 : rank < 2.0 ? 3.0 : rank < 3.0 ? 5.0
                    : rank < 4.0 ? 7.0 : 10.0;
        float f = 440.0 * exp2(semis / 12.0);
        float since = m - j * gap;
        // The strike itself, in the middle, then its echoes.
        float c = hallChime(since, f, 1.0);
        chime += float2(c, c) * 0.7;
        float keep = 1.0;
        float dull = 1.0;
        for (int e = 1; e <= 7; e++) {
            if (float(e) - 0.5 > p.bounces) break;
            keep *= p.silver;
            dull *= 1.0 - 0.3 * p.tint;
            float echo = hallChime(since - 0.19 * float(e), f, dull) * keep;
            float side = e % 2 == 1 ? 0.8 : 0.2;
            chime += float2(1.0 - side, side) * echo;
        }
    }
    // The lamps' hum: a low A and its fifth, one voice per lamp, each a
    // little apart in pitch so they beat slowly.
    float2 hum = float2(0.0);
    for (int i = 0; i < 6; i++) {
        if (float(i) + 0.5 > p.lamps) break;
        float f = (i % 2 == 0 ? 110.0 : 164.81) * (1.0 + 0.002 * float(i));
        float v = sin(TAU * fract(f * t) + float(i));
        float side = 0.5 + 0.3 * sin(float(i) * 2.4);
        hum += float2(1.0 - side, side) * v;
    }
    hum *= 0.06 / sqrt(max(floor(p.lamps + 0.5), 1.0));

    float fade = smoothstep(0.0, 2.0, m) * (1.0 - smoothstep(56.0, 59.9, m));
    return tanh((chime * 0.4 + hum) * 1.2) * 0.8 * p.volume * fade;
}
16 lines from stage 4 that are gone
constant float3 LAMP = float3(-0.8, 1.8, -0.6);
⋯
    float d = hallSphere(ro, rd, LAMP, LAMP_R);
⋯
        hit.normal = normalize(ro + rd * d - LAMP);
        hit.kind = 4;
⋯
    float3 l = LAMP - q;
⋯
    float3 c = kiln(0.86) * 2.4 / (0.4 + d2);
⋯
    if (kind == 4) {
⋯
        return kiln(0.86) * (2.0 + 5.0 * core);
⋯
    float x = 0.75 * sin(a);
    float z = -2.15 + 0.3 * sin(a * 1.7 + 1.0);
    float y = 1.25 + 0.15 * sin(t * 0.13);
⋯
    float3 look = float3(0.25 * sin(t * 0.07), 0.8, 0.0);
⋯
    float travel = 0.0;
⋯
        travel += hit.dist;
⋯
        float blur = travel * pixel / max(abs(dot(rd, n)), 0.25);
⋯
        light += carry * seen * (1.0 - glass);

The sound

The hall, heard. A glass chime is struck every 2.4 s through the first 50.4 s of the minute. Each strike is A (440 Hz) or one of four notes above it, C, D, E or G (3, 5, 7 or 10 semitones up), picked by hashing the strike's number with Cracked Clay's hashU. hallChime is a struck tone with two partials at 2.76 and 5.4 times its pitch, the ratios of the bell in Stained Glass, the higher ones dying away sooner.

The strike sounds in the middle, and then the mirrors answer: one echo for each bounce, bounces of them, each 0.19 s after the one before. Each is quieter by another factor of silver and duller by another factor of 1 − 0.3 · tint on its upper partials, as a mirror warms the light by taking out its blue. The echoes alternate, 80% to the right and then 80% to the left. With bounces at 0 the strike rings alone, in the middle.

Under it is a low hum, one voice per lamp: A2 (110 Hz) and E3 (164.81 Hz) in turn, each lamp's voice raised 0.2% more than the one before, so voices on the same note beat slowly, each set somewhere between the two ears. The hum is divided by the square root of the number of lamps, so more lamps don't make it much louder. The sound fades in over the first two seconds and out over the last four of the minute.

At the defaults the peak is −7.2 dBFS and the average (RMS) −20.2 dBFS over the minute. With volume 1, silver 0.98, tint 0, bounces 7 and lamps 6 it reaches a peak of −3.9 dBFS and an RMS of −15.4 dBFS.

New in Ray Kiln

Show a value, turn by turn. Show a value puts a variable of shade on the picture, as each pixel last passed its line. Inside a loop, that is the last turn, and every earlier turn is hidden. Now you can pick the turn. In the playground, put the cursor on a variable on a line inside a loop in shade and press Show a value (or Alt-click the variable). The bar gets a row: Turn, a slider, a number, "of 8" here, and Last. Last is the default and shows the last pass each pixel runs, as before. Drag the slider and let go, or type a number and press Enter, to see that turn, 1 being the loop's first pass. The picture, the reading under the pointer and Auto all use it, and a pixel whose loop ended before that turn, or that skipped the line on it, is black. It works in a fragment shader's shade, and only live in the playground, not in Save or Export.

The bounce loop is made for it. Show glass on the line float glass = hallGlass(pos, n, rd, hit.kind, blur); and set Turn to 1: the room's own panes are white, the frames and floor black, and the ball gray, a fifth mirror in its middle and more at its rim. Move Turn to 2: only the pixels whose ray met a mirror still run the line, and they show the glass of the room in the mirror, a band that narrows toward the middle. Each turn after that is one room farther back. At the default bounces 6, turn 7 is a ray's last, and turn 8 is black everywhere. Now show carry on carry *= glass * p.silver * warm; from 0 to 1: at turn 1 the panes are tan, 0.86 of the red and less of the green and blue, and each turn they are darker and more copper. Turn 7 is black, because on its last turn a ray leaves the loop before that line.

Try this

  • Set bounces to 0: the walls are bare slate glass, the ball's glaze shows nothing of the room, and the chime rings with no echoes. At 1, each wall shows one room, whose own mirrors are slate.
  • Set silver to 0.5: the rooms in the mirrors fade into the dark after a couple of bounces. At 0.98 the far rooms stay bright to the end of the hall.
  • Set tint to 0: the far rooms keep the near room's color, and the slate of the last glass shows blue at the end of the hall. At 1 they turn deep copper. Then, in shade, change float3(1.0, 0.74, 0.48) to float3(0.55, 0.8, 1.0): each mirror takes out red instead of blue, and the hall turns blue as it goes back.
  • Set lamps to 1 for a much darker room, then to 6 for rows of lamps running down every mirror.
  • In the playground, show glass turn by turn, set bounces to 2 and step Turn from 1: turn 3 is the last that shows anything, and turn 4 is black.
  • In hallGlass, change the ball's line to if (kind == 3) return 1.0;: the glaze becomes a perfect mirror, a chrome ball holding the checkered floor and the whole hall.

Parameters

ParameterDefaultRangeWhat it does
bounces60 to 7How many times a ray may be mirrored before it stops: 0 shows the bare glass
silver0.860.5 to 0.98How much of the light each mirror passes on
tint0.50 to 1How much warmer each mirror makes the light it passes on
lamps31 to 6How many lamps circle the ball
drift10 to 2How far the camera wanders around the room
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.

hall-of-mirrors.metal
// Ray Kiln · Hall of Mirrors
//
// @episode Hall of Mirrors
// @length 60
// @variation 30
// @variations 1,3,4,5,7,9,10,11
// @still 21
// @teaches Many bounces of reflection, rays that keep going
// @category Fragment
// @tags reflection, ray tracing, lighting, procedural sound, exponential decay
// @final Hall of Mirrors | Lamps circle the ball, the glaze mirrors the hall, and the camera wanders, while every mirror hands the light on, dimmer and warmer each time.
//
// A small room whose four walls are mirrors. A ray from the eye meets a
// wall, the mirror sends it on, and it meets another wall, and another.
// One turn of a loop follows the ray from one surface to the next. Each
// mirror keeps only part of the light and warms it a little, so the
// rooms seen in the mirrors fade and turn copper as they go back.
// 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 bounces 6 0 7 How many times a ray may be mirrored before it stops: 0 shows the bare glass
// @param silver 0.86 0.5 0.98 How much of the light each mirror passes on
// @param tint 0.5 0 1 How much warmer each mirror makes the light it passes on
// @param lamps 3 1 6 How many lamps circle the ball
// @param drift 1 0 2 How far the camera wanders around the room
// @param volume 0.8 0 1 Loudness of the sound

// A full turn, in radians.
constant float TAU = 6.2831853;
// The room: 4 wide, 6 deep, 2.6 high, the floor at 0.
constant float3 ROOM = float3(2.0, 2.6, 3.0);
// The ball in the middle, and its radius.
constant float3 BALL = float3(0.0, 0.55, 0.0);
constant float BALL_R = 0.55;
constant float LAMP_R = 0.07;
// A miss: a distance far beyond the room.
constant float FAR = 1e9;

// The kiln palette from Flowing Color Field.
float3 kiln(float t) {
    float3 c0 = float3(0.020, 0.012, 0.020);
    float3 c1 = float3(0.280, 0.040, 0.030);
    float3 c2 = float3(0.880, 0.260, 0.050);
    float3 c3 = float3(1.000, 0.680, 0.200);
    float3 c4 = float3(1.000, 0.970, 0.840);
    t = clamp(t, 0.0, 1.0);
    float3 c = mix(c0, c1, smoothstep(0.00, 0.22, t));
    c = mix(c, c2, smoothstep(0.22, 0.50, t));
    c = mix(c, c3, smoothstep(0.50, 0.76, t));
    return mix(c, c4, smoothstep(0.76, 1.00, t));
}

// What a ray meets: how far along, which way the surface faces,
// and what: 0 floor, 1 ceiling, 2 wall, 3 ball, 4 and up a lamp.
struct HallHit {
    float dist;
    float3 normal;
    int kind;
};

// How far along a ray it meets a sphere, or FAR.
float hallSphere(float3 ro, float3 rd, float3 c, float r) {
    float3 oc = ro - c;
    float b = dot(oc, rd);
    float h = b * b - dot(oc, oc) + r * r;
    if (h < 0.0) return FAR;
    float d = -b - sqrt(h);
    return d > 0.0 ? d : FAR;
}

// Where lamp i is: the lamps circle the ball slowly and bob.
float3 hallLampAt(int i, float t, constant Params& p) {
    float n = max(floor(p.lamps + 0.5), 1.0);
    float a = TAU * float(i) / n + t * 0.13;
    float y = 1.75 + 0.18 * sin(t * 0.7 + float(i) * 2.1);
    return float3(1.15 * cos(a), y, 1.15 * sin(a));
}

// Lamp i's color, gold to white-hot.
float3 hallLampColor(int i) {
    return kiln(0.8 + 0.06 * float(i % 3));
}

// The nearest thing along a ray. To leave the box, each axis
// heads for the face on the side the ray moves toward.
HallHit hallTrace(float3 ro, float3 rd, float t, constant Params& p) {
    float3 lo = float3(-ROOM.x, 0.0, -ROOM.z);
    float3 hi = ROOM;
    float3 safe = select(float3(1e-6), rd, abs(rd) > 1e-6);
    float3 wall = (select(lo, hi, rd > 0.0) - ro) / safe;
    HallHit hit;
    hit.dist = min(wall.x, min(wall.y, wall.z));
    if (hit.dist == wall.x) {
        hit.normal = float3(-sign(rd.x), 0.0, 0.0);
        hit.kind = 2;
    } else if (hit.dist == wall.z) {
        hit.normal = float3(0.0, 0.0, -sign(rd.z));
        hit.kind = 2;
    } else {
        hit.normal = float3(0.0, -sign(rd.y), 0.0);
        hit.kind = rd.y < 0.0 ? 0 : 1;
    }
    // The ball, standing on the floor.
    float b = hallSphere(ro, rd, BALL, BALL_R);
    if (b < hit.dist) {
        hit.dist = b;
        hit.normal = normalize(ro + rd * b - BALL);
        hit.kind = 3;
    }
    // The lamps, as many as the slider asks for.
    for (int i = 0; i < 6; i++) {
        if (float(i) + 0.5 > p.lamps) break;
        float3 c = hallLampAt(i, t, p);
        float d = hallSphere(ro, rd, c, LAMP_R);
        if (d < hit.dist) {
            hit.dist = d;
            hit.normal = normalize(ro + rd * d - c);
            hit.kind = 4 + i;
        }
    }
    return hit;
}

// How much of a wall is glass, framed by a bar every meter,
// its edges softened over blur, the width a pixel covers.
float hallGlass(float3 q, float3 n, float3 rd, int kind, float blur) {
    // The ball's glaze mirrors a little, more at its edges.
    if (kind == 3) return 0.2 + 0.6 * pow(1.0 - abs(dot(rd, n)), 4.0);
    if (kind != 2) return 0.0;
    float along = abs(n.x) > 0.5 ? q.z : q.x;
    float bar = abs(fract(along + 0.5) - 0.5);
    float side = smoothstep(0.05 - blur, 0.05 + blur, bar);
    // A baseboard below the glass and a cornice above it.
    float low = smoothstep(0.32 - blur, 0.32 + blur, q.y);
    float high = smoothstep(ROOM.y - 0.3 + blur, ROOM.y - 0.3 - blur, q.y);
    return side * low * high;
}

// Half-meter checkers, averaged over the pixel's width.
float hallTiles(float2 q, float blur) {
    float2 w = float2(max(blur * 2.0, 1e-3));
    float2 a = abs(fract((q - 0.5 * w) * 0.5) - 0.5);
    float2 b = abs(fract((q + 0.5 * w) * 0.5) - 0.5);
    float2 i = 2.0 * (a - b) / w;
    return 0.5 - 0.5 * i.x * i.y;
}

// The light on a surface: a little from all around, and the lamp's.
float3 hallLit(float3 q, float3 n, float3 rd, float shine,
               float t, constant Params& p) {
    float3 lit = float3(0.02, 0.014, 0.012);
    // The ball hides some of the room's light near it.
    float3 toBall = BALL - q;
    float near = dot(toBall, toBall);
    lit *= 1.0 - BALL_R * BALL_R / near * max(dot(n, toBall), 0.0)
               * rsqrt(near);
    // Each lamp lights what faces it, less the farther it is.
    for (int i = 0; i < 6; i++) {
        if (float(i) + 0.5 > p.lamps) break;
        float3 l = hallLampAt(i, t, p) - q;
        float d2 = dot(l, l);
        float far = sqrt(d2);
        l /= far;
        float face = max(dot(n, l), 0.0);
        float gloss = pow(max(dot(reflect(rd, n), l), 0.0), 40.0);
        float along = dot(toBall, l);
        float miss = length(toBall - l * along);
        float shadow = along > 0.0 && along < far
                     ? smoothstep(BALL_R * 0.8, BALL_R * 1.1, miss) : 1.0;
        float3 c = hallLampColor(i) * 1.1 / (0.4 + d2);
        lit += c * (face + shine * gloss * 6.0) * shadow;
    }
    return lit;
}

// What a surface that is not glass looks like, lit.
float3 hallSurface(float3 q, float3 rd, int kind, float3 n, float blur,
                   float t, constant Params& p) {
    if (kind >= 4) {
        // A lamp glows in its own color, white-hot in the middle.
        float core = max(dot(-rd, n), 0.0);
        // Its rim fades over a pixel, and a lamp smaller than a few
        // pixels fades too, leaving its glow.
        float rim = (1.0 - sqrt(1.0 - core * core)) * LAMP_R / blur;
        float cover = min(LAMP_R * LAMP_R / (4.0 * blur * blur), 1.0);
        float shown = min(rim, 1.0) * cover;
        return hallLampColor(kind - 4) * (1.2 + 2.0 * core) * shown;
    }
    float3 paint;
    float shine = 0.0;
    if (kind == 0) {
        // The floor: cream and charcoal tiles.
        float tile = hallTiles(q.xz * 2.0, blur * 2.0);
        float3 cream = float3(0.4, 0.31, 0.23);
        paint = mix(float3(0.03, 0.024, 0.022), cream, tile);
        shine = 0.3;
    } else if (kind == 1) {
        // The ceiling, dark.
        paint = float3(0.03, 0.022, 0.02);
    } else if (kind == 2) {
        // The frames, baseboard and cornice: dark bronze.
        paint = float3(0.08, 0.04, 0.022);
        shine = 0.6;
    } else {
        // The ball: an ember glaze.
        paint = float3(0.75, 0.2, 0.05);
        shine = 1.0;
    }
    return paint * hallLit(q, n, rd, shine, t, p);
}

// The glow lamps leave in the air: the nearer the ray passes
// a lamp before it ends, the brighter.
float3 hallHalo(float3 ro, float3 rd, float reach, float t,
                constant Params& p) {
    float3 halo = float3(0.0);
    for (int i = 0; i < 6; i++) {
        if (float(i) + 0.5 > p.lamps) break;
        float3 c = hallLampAt(i, t, p) - ro;
        float along = clamp(dot(c, rd), 0.0, reach);
        float3 miss = c - rd * along;
        halo += hallLampColor(i) * 0.004 / (dot(miss, miss) + 0.003);
    }
    return halo;
}

// The eye wanders slowly, never near a wall.
float3 hallEye(float t, constant Params& p) {
    float a = t * 0.09;
    // drift sets how far it wanders; at 0 it stands still.
    float x = 0.75 * p.drift * sin(a);
    float z = -2.15 + 0.3 * p.drift * sin(a * 1.7 + 1.0);
    float y = 1.25 + 0.15 * p.drift * sin(t * 0.13);
    return float3(x, y, z);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float2 s = (uv - 0.5) * u.resolution * 2.0 / u.resolution.y;
    float3 ro = hallEye(t, p);
    float3 look = float3(0.25 * p.drift * sin(t * 0.07), 0.8, 0.0);
    float3 fw = normalize(look - ro);
    float3 right = normalize(cross(float3(0.0, 1.0, 0.0), fw));
    float3 up = cross(fw, right);
    float lens = 1.5;
    float3 rd = normalize(fw * lens + right * s.x + up * s.y);
    // How wide a pixel is one meter away.
    float pixel = 2.0 / (u.resolution.y * lens);
    // Each mirror takes some blue out of the light it passes on.
    float3 warm = mix(float3(1.0), float3(1.0, 0.74, 0.48), p.tint);

    // The bounce loop: each turn finds the next surface. A mirror
    // sends the ray on; anything else ends it.
    float3 light = float3(0.0);
    float3 carry = float3(1.0);
    // The width a pixel covers, and how fast it grows.
    float width = 0.0;
    float spread = pixel;
    for (int bounce = 0; bounce < 8; bounce++) {
        HallHit hit = hallTrace(ro, rd, t, p);
        float3 pos = ro + rd * hit.dist;
        float3 n = hit.normal;
        width += spread * hit.dist;
        // The width a pixel covers there, wider on a slant.
        float blur = width / max(abs(dot(rd, n)), 0.25);
        float glass = hallGlass(pos, n, rd, hit.kind, blur);
        float3 seen = hallSurface(pos, rd, hit.kind, n, blur, t, p);
        float3 halo = hallHalo(ro, rd, hit.dist, t, p);
        // The lamps' glow on the way, then the surface.
        light += carry * (halo + seen * (1.0 - glass));
        // Out of bounces, the glass shows only a dark sheen.
        bool last = float(bounce) + 0.5 > p.bounces;
        if (glass < 0.01 || last) {
            light += carry * glass * float3(0.03, 0.035, 0.04);
            break;
        }
        // The mirror keeps silver of the light, warmed.
        carry *= glass * p.silver * warm;
        // The glaze is curved, so the rays it sends on spread.
        spread += hit.kind == 3 ? 2.0 * width / BALL_R : 0.0;
        rd = reflect(rd, n);
        ro = pos + n * 0.001;
    }

    // Bright light rolls off toward white, then the screen's curve.
    float3 col = 1.0 - exp(-light * 1.1);
    col = pow(col, float3(1.0 / 2.2));
    return float4(col, 1.0);
}

// ---- The sound ---------------------------------------------------------
// The hall, heard. A glass chime is struck every few seconds, and its
// sound comes back from the mirrors, one echo per bounce, each quieter
// by silver and duller by tint, from the left and the right in turn. A
// low hum, one voice per lamp, sits under it.

// Cracked Clay's integer hash.
float hashU(uint n) {
    n = (n << 13u) ^ n;
    n = n * (n * n * 15731u + 789221u) + 1376312589u;
    return float(n & 0x7fffffffu) / float(0x7fffffff);
}

// A struck glass chime `since` seconds ago, at f hertz. Dull lowers its
// upper partials, as a warm mirror takes the blue out of light.
float hallChime(float since, float f, float dull) {
    if (since < 0.0 || since > 6.0) return 0.0;
    float attack = 1.0 - exp(-since * 90.0);
    float a = sin(TAU * fract(f * since)) * exp(-since * 1.1);
    a += 0.45 * dull * sin(TAU * fract(f * 2.76 * since)) * exp(-since * 2.2);
    a += 0.2 * dull * dull * sin(TAU * fract(f * 5.4 * since))
       * exp(-since * 3.6);
    return a * attack;
}

float2 sound(float t, constant Params& p) {
    // Where in the minute it is: no strikes in its last eight seconds.
    float m = fract(t / 60.0) * 60.0;
    float minute = floor(t / 60.0);
    float gap = 2.4;
    float2 chime = float2(0.0);
    float slot = floor(m / gap);
    for (int k = -2; k <= 0; k++) {
        float j = slot + float(k);
        if (j < 0.0 || j * gap > 51.0) continue;
        uint id = uint(j + minute * 25.0);
        float rank = floor(hashU(id * 3u + 1u) * 5.0);
        float semis = rank < 1.0 ? 0.0 : rank < 2.0 ? 3.0 : rank < 3.0 ? 5.0
                    : rank < 4.0 ? 7.0 : 10.0;
        float f = 440.0 * exp2(semis / 12.0);
        float since = m - j * gap;
        // The strike itself, in the middle, then its echoes.
        float c = hallChime(since, f, 1.0);
        chime += float2(c, c) * 0.7;
        float keep = 1.0;
        float dull = 1.0;
        for (int e = 1; e <= 7; e++) {
            if (float(e) - 0.5 > p.bounces) break;
            keep *= p.silver;
            dull *= 1.0 - 0.3 * p.tint;
            float echo = hallChime(since - 0.19 * float(e), f, dull) * keep;
            float side = e % 2 == 1 ? 0.8 : 0.2;
            chime += float2(1.0 - side, side) * echo;
        }
    }
    // The lamps' hum: a low A and its fifth, one voice per lamp, each a
    // little apart in pitch so they beat slowly.
    float2 hum = float2(0.0);
    for (int i = 0; i < 6; i++) {
        if (float(i) + 0.5 > p.lamps) break;
        float f = (i % 2 == 0 ? 110.0 : 164.81) * (1.0 + 0.002 * float(i));
        float v = sin(TAU * fract(f * t) + float(i));
        float side = 0.5 + 0.3 * sin(float(i) * 2.4);
        hum += float2(1.0 - side, side) * v;
    }
    hum *= 0.06 / sqrt(max(floor(p.lamps + 0.5), 1.0));

    float fade = smoothstep(0.0, 2.0, m) * (1.0 - smoothstep(56.0, 59.9, m));
    return tanh((chime * 0.4 + hum) * 1.2) * 0.8 * 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] = [6, 0.86, 0.5, 3, 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 3D Scenes