Devlog ·

Caustics you can see through water

Our 3D renderer keeps caustics in a world-space hash grid instead of on the screen. This is how it works, with the shader code and the bit of maths that decided the layout.

Caustics are the bright, wobbly lines on the bottom of a swimming pool. Water and glass bend sunlight, a lot of it ends up in the same few spots, and those spots come out brighter than everything around them. Leave them out and a glass of water on a table looks like a glass of plastic.

There are two well-known ways to do them in real time. Caustic maps (Shah et al. 2007) work like a shadow map: you render what receives the light from the sun's point of view, splat the refracted light into that picture, and the camera looks it up by projecting each point into the sun's view. That one is anchored to the light, but it holds one receiving surface per texel. The other is photon splatting in screen space (Kim in Ray Tracing Gems, Yang and Ouyang in Ray Tracing Gems II). You trace photons from the sun through the glass, and when one lands you project the landing point to the screen and add light to that pixel. It's cheap and it looks good, as long as you look straight at the spot where the light landed.

The trouble is the pool. You look at the bottom of a pool through the water. Our primary rays follow mirrors and glass (up to sixteen surfaces) before they settle on the surface they show, so the pixel that shows the floor sits wherever the refracted ray puts it on screen. The photon that landed on the floor gets projected to where the floor would be with no water in the way. It lights the wrong pixel, or nothing. Mirrors have the same problem. NVIDIA's chapter lists it among the limitations of both its own methods: caustics seen through reflection and refraction are limited to screen space, and water caustics can't be seen in ray-traced reflections. Our first version splatted on the screen too, and did exactly that: the bottom of the pool (the one place caustics are for) came out dark.

So we stopped putting the light on the screen. A photon writes its energy into the world, and the surface each pixel's eye ray settles on, after up to sixteen mirrors and refractions, reads it back from the world. It doesn't matter if that ray came straight from the camera or through the side of a tank first. (Bounce light and glossy reflections don't see caustics yet, only that settled surface does.)

Looking down into an aquarium through the water: bright, rippling lines of light cover the sand between the stones and the fish. The same view of the aquarium with caustics switched off: the sand is evenly lit.
The aquarium from above, through the water, with caustics and without.

Sending the photons

Every frame we send 220 photons, about a million, and only toward the glass, water and mirrors in the scene. Each piece of glass, and each mirror built from the engine's own props, has a bounding sphere of radius rj, and a photon picks a piece with probability proportional to rj2, then starts from a uniform point on a disc of that radius facing the sun (r = R√u). That makes every photon carry the same power:

Φ = Esun · π ∑j rj2 / (N · c)

where Esun is the sun's irradiance (times how much of it the clouds let through) and N the photon count. c is the number of discs the photon's line crosses. A tank of water is six faces whose discs overlap, and without c the sunlight over an overlap gets counted once for every disc on top of it.

The photon is then traced through the mirrors and glass it meets, up to sixteen of them. At each glass surface it keeps the part Fresnel lets through, 1−F, and inside a medium it loses light by Beer-Lambert, e−σad. It is laid down where it first hits something that is neither glass nor a mirror. A photon whose first hit isn't glass or a mirror is just dropped, since that light is the ordinary direct sun and already in the picture.

Where the light is kept

The obvious way to keep light in world space is a 3D grid, splatting each photon trilinearly into the eight cells around it and reading back with the same weights. That doesn't work on a floor, and it's easy to show why.

Take a flat floor sitting at an offset t between two layers of cells along its normal. Every photon that lands on it has the same t, so layer one collects (1−t)·S and layer two collects t·S. Reading back at the floor with the same weights gives

(1−t)·(1−t)S + t·t S = ((1−t)2 + t2) S

which is all of it at t = 0, 62.5% at t = 0.25 and half at t = 0.5. The same caustic gets brighter or darker depending on where the floor happens to sit in the grid. Inside the plane of the floor this doesn't happen, because there the photons land at every offset. A cell collects ρ ∫ w dA = ρh2 for a photon density ρ and a cell size h, and since the four bilinear weights always sum to one, a uniform field reads back exactly. We checked it numerically too. It reads back the true density to within the photon noise, about 3% either way.

So a cell lives in the plane its surface faces. Every cell has one of six facings (±x, ±y, ±z, whichever axis the normal is closest to), is h square across that plane, and along the facing's axis it is a 25 cm slab with no interpolation at all. A surface only ever needs the light that landed on itself, so it doesn't need resolution in depth.

Footing footing(vec3 p, uint facing, uint level) {
    uint axis = facing >> 1;
    uint u = axis == 0u ? 1u : 0u, v = axis == 2u ? 1u : 2u;
    vec2 f = vec2(p[u], p[v]) / CAUSTIC_CELLS[level] - 0.5;
    Footing ft;
    ft.base = ivec3(0);
    ft.base[u] = int(floor(f.x));
    ft.base[v] = int(floor(f.y));
    float ahead = (facing & 1u) == 0u ? 0.5 * CAUSTIC_SLAB : -0.5 * CAUSTIC_SLAB;
    ft.base[axis] = int(floor((p[axis] + ahead) / CAUSTIC_SLAB));
    ft.t = f - floor(f);
    ft.u = u;
    ft.v = v;
    return ft;
}

The facing also keeps a table top and the underside of a shelf just above it from sharing light.

Laying a photon down

A cell stores irradiance over π, which is what a Lambertian surface multiplies by its albedo to get outgoing radiance. A cell's square is axis-aligned and the surface usually isn't, so a cell of area h2 covers h2/|na| of tilted surface, where na is the normal's component along the facing axis. One photon is worth

e = Φ · |na| / (π h2)

spread over the four cells round it with bilinear weights. The fourth channel adds up the weights, so after a frame it holds how many photons landed in that cell.

void deposit(Surface s, vec3 light) {
    uint facing = facing_of(s.geo);
    float across = abs(s.geo[facing >> 1]);
    for (uint level = 0u; level < 2u; level++) {
        Footing ft = footing(s.p, facing, level);
        float cell = CAUSTIC_CELLS[level];
        vec3 e = light * across / (cell * cell * 3.14159265);
        for (uint k = 0u; k < 4u; k++) {
            uint c = caustic_claim(caustic_key(corner(ft, k), facing, level));
            if (c == 0xffffffffu) {
                continue;
            }
            float w = corner_weight(ft, k);
            add_float(caustic_acc, 4u * c, w * e.r);
            add_float(caustic_acc, 4u * c + 1u, w * e.g);
            add_float(caustic_acc, 4u * c + 2u, w * e.b);
            add_float(caustic_acc, 4u * c + 3u, w);
        }
    }
}

add_float is the card's float atomic add, or a compare-and-swap loop on the float's bits on cards that don't have one (AMD before RDNA 3, the Steam Deck included).

The hash table

Light only lands in a few places, so a dense grid over the whole scene would be almost all zeros. The cells live in a hash table of 220 slots instead, with open addressing and up to 24 linear probes. A key packs everything that names a cell into 64 bits: an occupied bit, the level, the facing and 18 bits for each coordinate.

uint64_t caustic_key(ivec3 c, uint facing, uint level) {
    uint64_t m = 0x3ffffUL;
    uint64_t x = uint64_t(c.x + 131072) & m, y = uint64_t(c.y + 131072) & m, z = uint64_t(c.z + 131072) & m;
    return (1UL << 63) | (uint64_t(level) << 57) | (uint64_t(facing) << 54) | (z << 36) | (y << 18) | x;
}

At 2 cm a side that covers 2.6 km each way from the origin. The whole table (keys, light, and this frame's sums) is about 40 MB.

The sun moves and the glass moves, so cells go dark and the table would fill up. Deleting a key from an open-addressing table breaks the probe chains of every key stored past it, and the usual fix is tombstones. We don't delete at all. A cell whose photon count has faded below a threshold can be taken over in place by a new key with one atomicCompSwap, so every chain stays whole.

if (seen == 0UL || caustic_val[s].w < CAUSTIC_STALE) {
    uint64_t was = atomicCompSwap(caustic_keys[s], seen, key);
    if (was == seen) {
        caustic_val[s] = vec4(0.0, 0.0, 0.0, 1.0);
        return s;
    }
    if (was == key) {
        return s;
    }
}

A freshly claimed cell starts out counting one photon a frame, so another thread can't steal it back before this frame's photons are counted.

Over time

A 2 cm cell catches tens of photons a frame at most outside a focus, which is noisy. Each cell eases toward what this frame's photons say:

V ← V + τ (A − V),   τ = 0.11

That is an exponential moving average with a time constant of about 9 frames. Its steady-state variance is τ/(2−τ) ≈ 0.058 of one frame's, so the noise drops to about a quarter, the same as averaging 17 frames. A caustic on moving water trails about nine frames (150 ms at 60 fps) behind, and doesn't flicker. This is also where we saved time: half the photons, eased about twice as slowly, average nearly as many photons (17 million against 18), so a still caustic looks the same and a moving one trails a little more. That cut the photon pass in the marbles scene at 4K from 4.9 ms to 2.5.

A silver ring lying on a white tablecloth, seen from above. Light reflected off its inner wall draws a bright curve with a sharp point on the cloth inside it. The same silver ring with caustics switched off: the cloth inside the ring is in shadow.
A silver ring on a tablecloth, with caustics and without. The curve inside it is light off its inner wall.

Reading it back

Where photons crowd together (the focus of a lens, the curve in the ring) the fine cells are good. Where only a few land, a fine cell catches one now and then and the faint light around a focus turns into coloured grain. So every photon goes into two levels, 2 cm and 12 cm. A coarse cell has 36 times the area and so 36 times the photons, which is 6 times less relative noise. The read takes the fine level once it has about six photons a frame behind it, and blends toward the coarse one below that:

vec3 caustic_at(vec3 p, vec3 geo) {
    if (switched_off(OFF_CAUSTICS)) {
        return vec3(0.0);
    }
    uint facing = facing_of(geo);
    vec4 fine = caustic_level(p, facing, 0u);
    if (fine.w >= CAUSTIC_TRUSTED) {
        return fine.rgb;
    }
    vec4 coarse = caustic_level(p, facing, 1u);
    return mix(coarse.rgb, fine.rgb, smoothstep(0.0, CAUSTIC_TRUSTED, fine.w));
}

That light is added to the indirect light at the surface the pixel settled on, after every mirror and refraction, and goes through the same diffuse albedo and the same transmittance of whatever glass and water the eye ray passed.

vec3 c = (direct + (e + caustic_at(p.xyz, n.xyz)) * diffuse * (1.0 - fr) + specular) * through.rgb + coat.rgb;

That one line is the whole fix for the pool. The lookup uses the floor's world position, so it doesn't care how the ray got there.

Colour

Photons go out in threes from the same point. Glass that disperses gives each of the three its own wavelength, stratified across the spectrum (k mod 3 plus a random offset, over three), and each one bends at its own index of refraction. So a prism throws a proper spectrum instead of three coloured copies of the hole in the shutter. Mirrors and thin panes never split the light, so their caustics stay white. Water and ordinary glass take crown glass's small spread unless a material names its own, and in the aquarium the colours land within about a centimetre of each other, well inside one cell, so they still add up to white. (On rough glass each photon picks its own microfacet, so the three spread a little more.)

A dark room lit through holes in a shutter. A glass prism on a stand splits a beam into rainbow streaks across the far wall and the floor.
A dark room with the sun let in through three holes in the shutter, and a prism, a glass ball and a cut crystal in the three beams. The small rainbows are the crystal's. The prism's spread is three times flint glass's, so the band fills the wall.

Cost

Tracing the photons costs 1.1 ms in the aquarium and 2.4 ms in the still life at 1080p on an RTX 5070. The pass that folds each frame's sums into the cells costs 0.06 ms. At night or in heavy rain no photons are sent and the light already in the cells fades out.

There's a side benefit too: the caustics don't swim around anymore when the camera moves, because nothing about them lives on the screen. They stay on the table where the light put them.

Further reading

All devlog posts