Shader

Soap Bubble

A soap bubble drifting in a dark room, its colors made the way a real one makes them. The film reflects light twice, off its front and off its back, and the two reflections meet out of step by an amount set by the film's thickness. Sixteen wavelengths are reflected one at a time and added up through the eye's color matching curves, and the film drains under gravity and swirls, so it shows bands of color, a black cap at the top and the window twice, once upside down.

· Light & Materials · Fragment shader

Teaches Thin-film interference, color from a film's thickness

Builds on Flowing Color Field, Kiln Fire (3D hash, 3D value noise, 3D fractal noise)

Watch

The idea

A soap bubble has no color of its own: its water is clear. The color comes from its thickness. The film is a few hundred nanometers thick, about as thin as a wavelength of light, and it reflects light twice, once off its front and once off its back. The light off the back has gone through the film and back, so it comes out behind the light off the front, by twice the thickness, times the water's refractive index of 1.33. The light off the front is also turned over, half a wave out, because it bounced off something denser than the air it came through. A wavelength that comes back in step adds up and is bright; one that comes back out of step cancels. Which wavelengths survive depends on the thickness, so every thickness has its own color. That is thin-film interference.

Red, green and blue can't do this on their own, since what happens depends on the exact wavelength. So the shader does it one wavelength at a time, spectral rendering: 16 wavelengths from violet to red, each reflected, then added up into a color through the eye's color matching functions. The rest is a bubble to put that on: a film that drains, thin at the top, thick at the bottom, swirling as it goes, and a room for it to reflect. It is built in four steps, and each step is a shader you can run on its own.

Stage 1 · Color from thickness

Across the picture the film gets thicker, from 0 nm on the left to 1200 on the right (thickness stretches that), lit head on by white light. The ticks along the top are 100 nm apart.

filmReflect is how much of one wavelength w the film reflects. The two reflections are delta = 2 × TAU × 1.33 × d × cosT / w out of step: the path through the film and back, in waves, as an angle. Each surface reflects a share F, and the two add as 2F(1 − cos δ) / (1 + F² − 2F cos δ) (the Airy formula, counting every bounce inside the film). At 0 nm, cos δ is 1 and the result is exactly 0: the front reflection was turned over, so it cancels the back one. A film much thinner than light is black.

wavelengthColor turns a wavelength in nanometers into the color it looks. It is the CIE 1931 color matching functions as Wyman, Sloan and Shirley fit them, each curve a few bell curves wider on one side than the other (lobe), and then the standard matrix from those X, Y and Z amounts to a screen's linear red, green and blue. filmColor reflects 16 wavelengths, 400 to 700 nm, 20 apart, adds up each one's color times what the film reflects of it, and divides by the same sum for a perfect mirror, so a film that reflected everything would be white. A film reflects only a few percent, so the picture multiplies it by 10 (times light), and the result is encoded for the screen with a power of 1/2.2.

What it draws is Newton's series of interference colors: black, then gray and white (every wavelength partly back), straw yellow, a deep purple near 210 nm, where green cancels, blue, then yellow, magenta, green again, each order paler than the one before as more wavelengths come back in step at once. The white line is the thickness the sound plays.

stage-1-color-from-thickness.metal
// Stage 1 · Color from thickness
// Light off a film's front and off its back meets a little out of step.
// Here thickness runs from 0 nm on the left to 1200 on the right, in white
// light, head on: 16 wavelengths reflected one by one and added up through
// the eye's color matching curves. At 0 nm it is black.

// @param thickness 1 0.2 3 How thick the film is: thicker gives paler colors
// @param light 1 0.3 3 How bright the light on the film
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
// Everything loops in this many seconds.
constant float LOOP = 60.0;
// Soapy water's refractive index.
constant float FILM_N = 1.33;
// What one surface reflects head on, ((n - 1) / (n + 1))².
constant float F0 = 0.0201;

// Half a bell curve each side of mu.
float lobe(float x, float mu, float lo, float hi) {
    float k = (x - mu) / (x < mu ? lo : hi);
    return exp(-0.5 * k * k);
}

// A wavelength (nm) as linear RGB: the CIE 1931 color matching curves,
// then a screen's red, green and blue.
float3 wavelengthColor(float w) {
    float x = 1.056 * lobe(w, 599.8, 37.9, 31.0)
            + 0.362 * lobe(w, 442.0, 16.0, 26.7)
            - 0.065 * lobe(w, 501.1, 20.4, 26.2);
    float y = 0.821 * lobe(w, 568.8, 46.9, 40.5)
            + 0.286 * lobe(w, 530.9, 16.3, 31.1);
    float z = 1.217 * lobe(w, 437.0, 11.8, 36.0)
            + 0.681 * lobe(w, 459.0, 26.0, 13.8);
    return float3( 3.2406 * x - 1.5372 * y - 0.4986 * z,
                  -0.9689 * x + 1.8758 * y + 0.0415 * z,
                   0.0557 * x - 0.2040 * y + 1.0570 * z);
}

// The share of wavelength w a film d nm thick reflects: 0 at d = 0.
float filmReflect(float d, float w, float cosT, float F) {
    float delta = 2.0 * TAU * FILM_N * d * cosT / w;
    float c = cos(delta);
    return 2.0 * F * (1.0 - c) / (1.0 + F * F - 2.0 * F * c);
}

// 16 wavelengths, 400 to 700 nm, added up; white light gives white.
float3 filmColor(float d, float cosI) {
    // Snell's law: steeper inside the film.
    float cosT = sqrt(1.0 - (1.0 - cosI * cosI) / (FILM_N * FILM_N));
    // Fresnel: more at a glancing angle.
    float F = F0 + (1.0 - F0) * pow(1.0 - cosI, 5.0);
    float3 sum = float3(0.0), white = float3(0.0);
    for (int i = 0; i < 16; i++) {
        float w = 390.0 + 20.0 * (float(i) + 0.5);
        float3 s = wavelengthColor(w);
        sum += s * filmReflect(d, w, cosT, F);
        white += s;
    }
    return max(sum / white, 0.0);
}

// The thickness the sound plays: 50 to 1150 nm and back.
float sweep(float t, constant Params& p) {
    return (600.0 - 550.0 * cos(TAU * t / LOOP)) * p.thickness;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = fmod(u.time, LOOP);
    // Left to right: 0 to 1200 nm of film (times the thickness slider).
    float d = uv.x * 1200.0 * p.thickness;
    // A bright light on the film: it reflects only a few percent.
    float3 col = filmColor(d, 1.0) * 10.0 * p.light;
    // A tick every 100 nm along the top.
    float px = 1.0 / u.resolution.x;
    float tick = fract(uv.x * 12.0 + 0.5);
    float mark = step(abs(tick - 0.5), 1.5 * px * 12.0);
    col = mix(col, float3(1.0, 0.95, 0.87), mark * step(0.94, uv.y));
    // The cursor: the thickness heard now.
    float at = sweep(t, p) / (1200.0 * p.thickness);
    col = mix(col, float3(1.0), step(abs(uv.x - at), 1.5 * px));
    return float4(pow(max(col, 0.0), float3(1.0 / 2.2)), 1.0);
}

// The bubble, heard. Three tones stand for three colors of light: 220 Hz
// for red (650 nm), 277.2 for green (550 nm), 329.6 for blue (450 nm).
// Each is played twice, the copy out of step by what the light's second
// reflection is at the film in the middle of the bubble, and turned over
// as the first reflection is. They add as the light does: a color the
// film keeps is loud, a color it cancels goes quiet, so the chord follows
// the color in the middle as the film swirls past.

// One tone and its copy, delta out of step and turned over.
float twoWaves(float t, float f, float delta) {
    return sin(TAU * f * t) - sin(TAU * f * t + delta);
}

float2 sound(float t, constant Params& p) {
    float d = sweep(t, p);
    float3 w = float3(650.0, 550.0, 450.0);
    float3 delta = 2.0 * TAU * FILM_N * d / w;
    float red = twoWaves(t, 220.0, delta.x);
    float green = twoWaves(t, 277.2, delta.y);
    float blue = twoWaves(t, 329.6, delta.z);
    // A faint octave over each, the film's shimmer.
    red += 0.25 * twoWaves(t, 440.0, 2.0 * delta.x);
    green += 0.25 * twoWaves(t, 554.4, 2.0 * delta.y);
    blue += 0.25 * twoWaves(t, 659.2, 2.0 * delta.z);
    // Red to the left, blue to the right, green in the middle.
    float2 mixLR = float2(0.8 * red + 0.5 * green + 0.25 * blue,
                          0.25 * red + 0.5 * green + 0.8 * blue);
    // Fade in over the first 50 ms, so it starts without a click.
    return mixLR * 0.12 * p.volume * min(t * 20.0, 1.0);
}

Stage 2 · A bubble that drains

Now the film is a ball, its radius 0.62 (times size) in a picture 2 high, less in a tall picture so it still fits across, drifting a little: its middle moves by 0.05 sin 3a and 0.04 sin 4a, where a goes once round in the 60 seconds of the loop. For a pixel on the ball, n is the point on the ball facing the viewer, and cosI, its z, is how squarely the film faces the eye. The film reflects the room from the direction r, the view direction mirrored about n.

Gravity pulls the water down. thicknessAt makes it 30 + 820 × drain^1.4 nm, where drain goes from 0 at the top of the ball to 1 at the bottom, so the colors lie in bands round it, Newton's series again, from the top down.

At a slant two things change, both in filmColor. The light crosses the film at a slant, more steeply than it hits it (Snell's law: cosT from cosI and the index 1.33), which shortens the path out of step, so the bands shift towards thinner colors near the rim. And each surface reflects more, by Fresnel: F grows from 0.0201 head on, ((1.33 − 1) / (1.33 + 1))², towards 1 at a glance (Schlick's approximation), which is why a bubble's rim is bright.

room is what the bubble reflects, in linear light: a dark warm room from the kiln palette (kiln, from Flowing Color Field), a soft light from the ceiling, a window up to the left with four panes, by far the brightest thing in it, and the kiln's glow low on the right. The film's color multiplies it, so the window and the ceiling show the film's colors best, and where the room is dark the bubble nearly vanishes, as a real one does. Behind, the light goes through the film almost untouched (the background is kept at 96%).

stage-2-a-bubble-that-drains.metal53 new lines since stage 1
// Stage 2 · A bubble that drains
// Now the film is a ball. Gravity pulls the water down, so it is thin at
// the top and thick at the bottom, and the colors lie in bands. Each point
// reflects the room: a window, a ceiling light, the kiln's glow. Seen at a
// slant, the light crosses the film at a slant and each surface reflects
// more.

// @param thickness 1 0.2 3 How thick the film is: thicker gives paler colors
// @param light 1 0.3 3 How bright the room the bubble reflects
// @param size 1 0.6 1.3 How big the bubble is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
// Everything loops in this many seconds.
constant float LOOP = 60.0;
// Soapy water's refractive index.
constant float FILM_N = 1.33;
// What one surface reflects head on, ((n - 1) / (n + 1))².
constant float F0 = 0.0201;

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));
}

// Half a bell curve each side of mu.
float lobe(float x, float mu, float lo, float hi) {
    float k = (x - mu) / (x < mu ? lo : hi);
    return exp(-0.5 * k * k);
}

// A wavelength (nm) as linear RGB: the CIE 1931 color matching curves,
// then a screen's red, green and blue.
float3 wavelengthColor(float w) {
    float x = 1.056 * lobe(w, 599.8, 37.9, 31.0)
            + 0.362 * lobe(w, 442.0, 16.0, 26.7)
            - 0.065 * lobe(w, 501.1, 20.4, 26.2);
    float y = 0.821 * lobe(w, 568.8, 46.9, 40.5)
            + 0.286 * lobe(w, 530.9, 16.3, 31.1);
    float z = 1.217 * lobe(w, 437.0, 11.8, 36.0)
            + 0.681 * lobe(w, 459.0, 26.0, 13.8);
    return float3( 3.2406 * x - 1.5372 * y - 0.4986 * z,
                  -0.9689 * x + 1.8758 * y + 0.0415 * z,
                   0.0557 * x - 0.2040 * y + 1.0570 * z);
}

// The share of wavelength w a film d nm thick reflects: 0 at d = 0.
float filmReflect(float d, float w, float cosT, float F) {
    float delta = 2.0 * TAU * FILM_N * d * cosT / w;
    float c = cos(delta);
    return 2.0 * F * (1.0 - c) / (1.0 + F * F - 2.0 * F * c);
}

// 16 wavelengths, 400 to 700 nm, added up; white light gives white.
float3 filmColor(float d, float cosI) {
    // Snell's law: steeper inside the film.
    float cosT = sqrt(1.0 - (1.0 - cosI * cosI) / (FILM_N * FILM_N));
    // Fresnel: more at a glancing angle.
    float F = F0 + (1.0 - F0) * pow(1.0 - cosI, 5.0);
    float3 sum = float3(0.0), white = float3(0.0);
    for (int i = 0; i < 16; i++) {
        float w = 390.0 + 20.0 * (float(i) + 0.5);
        float3 s = wavelengthColor(w);
        sum += s * filmReflect(d, w, cosT, F);
        white += s;
    }
    return max(sum / white, 0.0);
}

// The film's thickness in nm at a point p on the bubble (from its center,
// length 1, y up).
float thicknessAt(float3 p, float t, constant Params& pr) {
    // Gravity drains it: about 30 nm at the top, 850 at the bottom.
    float drain = 0.5 - 0.5 * p.y;
    float d = 30.0 + 820.0 * pow(drain, 1.4);
    return d * pr.thickness;
}

// What the bubble reflects from direction r (linear light): a dark warm
// room lit from the ceiling, a window up to the left with four panes, and
// the kiln's glow low on the right.
float3 room(float3 r, constant Params& p) {
    float3 col = pow(kiln(0.22 + 0.1 * r.y), 2.2);
    // A soft light from the ceiling, so the top of the bubble shows its film.
    col += float3(1.0, 0.95, 0.87) * 1.6 * smoothstep(0.2, 0.9, r.y);
    float3 w = normalize(float3(-0.55, 0.5, 0.67));
    float3 side = normalize(cross(float3(0, 1, 0), w));
    float3 up = cross(w, side);
    float2 f = float2(dot(r, side), dot(r, up)) / max(dot(r, w), 0.01);
    float pane = step(abs(f.x), 0.42) * step(abs(f.y), 0.32);
    pane *= step(0.025, abs(f.x)) * step(0.025, abs(f.y));
    pane *= step(0.0, dot(r, w));
    col += float3(1.0, 0.95, 0.87) * pane * 9.0;
    float3 g = normalize(float3(0.7, -0.45, 0.55));
    float glow = exp(-8.0 * (1.0 - dot(r, g)));
    col += pow(float3(1.0, 0.69, 0.38), 2.2) * glow * 6.0;
    return col * p.light;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 q = (uv - 0.5) * 2.0 * float2(u.resolution.x / u.resolution.y, 1.0);
    float t = fmod(u.time, LOOP);
    float a = TAU * t / LOOP;
    // The background: near-black, warmed low on the right by the kiln.
    float glow = exp(-1.6 * length(q - float2(1.3, -1.2)));
    float3 bg = pow(kiln(0.06 + 0.3 * glow), 2.2);
    float3 col = bg;

    // The bubble drifts a little and comes back each minute.
    float2 c = float2(0.05 * sin(3.0 * a), 0.04 * sin(4.0 * a));
    // Smaller in a tall picture, so it still fits across.
    float fit = min(1.0, 0.9 * u.resolution.x / u.resolution.y);
    float R = 0.62 * p.size * fit;
    float2 s = (q - c) / R;
    float r2 = dot(s, s);
    if (r2 < 1.0) {
        // Its front: n is the point on the ball and the way it faces.
        float3 n = float3(s, sqrt(1.0 - r2));
        float cosI = n.z;
        float3 r = float3(2.0 * cosI * n.xy, 2.0 * cosI * cosI - 1.0);
        float3 front = room(r, p) * filmColor(thicknessAt(n, t, p), cosI);
        // Light goes through the film nearly untouched.
        col = col * 0.96 + front;
    }
    // A soft edge, a pixel wide.
    float px = 2.0 / u.resolution.y / R;
    float edge = smoothstep(1.0 + px, 1.0 - px, sqrt(r2));
    col = mix(bg, col, edge);
    return float4(pow(max(col, 0.0), float3(1.0 / 2.2)), 1.0);
}

// The bubble, heard. Three tones stand for three colors of light: 220 Hz
// for red (650 nm), 277.2 for green (550 nm), 329.6 for blue (450 nm).
// Each is played twice, the copy out of step by what the light's second
// reflection is at the film in the middle of the bubble, and turned over
// as the first reflection is. They add as the light does: a color the
// film keeps is loud, a color it cancels goes quiet, so the chord follows
// the color in the middle as the film swirls past.

// One tone and its copy, delta out of step and turned over.
float twoWaves(float t, float f, float delta) {
    return sin(TAU * f * t) - sin(TAU * f * t + delta);
}

float2 sound(float t, constant Params& p) {
    float d = thicknessAt(float3(0.0, 0.0, 1.0), t, p);
    float3 w = float3(650.0, 550.0, 450.0);
    float3 delta = 2.0 * TAU * FILM_N * d / w;
    float red = twoWaves(t, 220.0, delta.x);
    float green = twoWaves(t, 277.2, delta.y);
    float blue = twoWaves(t, 329.6, delta.z);
    // A faint octave over each, the film's shimmer.
    red += 0.25 * twoWaves(t, 440.0, 2.0 * delta.x);
    green += 0.25 * twoWaves(t, 554.4, 2.0 * delta.y);
    blue += 0.25 * twoWaves(t, 659.2, 2.0 * delta.z);
    // Red to the left, blue to the right, green in the middle.
    float2 mixLR = float2(0.8 * red + 0.5 * green + 0.25 * blue,
                          0.25 * red + 0.5 * green + 0.8 * blue);
    // Fade in over the first 50 ms, so it starts without a click.
    return mixLR * 0.12 * p.volume * min(t * 20.0, 1.0);
}
11 lines from stage 1 that are gone
float sweep(float t, constant Params& p) {
    return (600.0 - 550.0 * cos(TAU * t / LOOP)) * p.thickness;
⋯
    float d = uv.x * 1200.0 * p.thickness;
⋯
    float3 col = filmColor(d, 1.0) * 10.0 * p.light;
⋯
    float px = 1.0 / u.resolution.x;
    float tick = fract(uv.x * 12.0 + 0.5);
    float mark = step(abs(tick - 0.5), 1.5 * px * 12.0);
    col = mix(col, float3(1.0, 0.95, 0.87), mark * step(0.94, uv.y));
⋯
    float at = sweep(t, p) / (1200.0 * p.thickness);
    col = mix(col, float3(1.0), step(abs(uv.x - at), 1.5 * px));
⋯
    float d = sweep(t, p);

Stage 3 · Swirls and black film

A real film doesn't drain evenly: it swirls. thicknessAt turns the point on the ball round its vertical axis once a minute, bends it by two fractal noises (fbm3, three octaves) whose offset circles twice a minute, and reads a third, four-octave noise there. That n makes the film thinner by up to 65% or thicker by up to about 57% (swirl scales it), less near the top, where there is little water left to stir.

At the very top the film turns to black film: past an edge that the noise and a slow sway push about, it thins at once to 6 nm, and there it reflects almost nothing, so the top of the bubble shows a dark cap. A real bubble gets one shortly before it bursts.

stage-3-swirls-and-black-film.metal38 new lines since stage 2
// Stage 3 · Swirls and black film
// A real film never drains evenly: it swirls. Noise turned round the
// bubble, bent by more noise, stirs the thickness. At the very top the
// film snaps to black film, a few nm thick, that reflects almost nothing:
// a dark cap, as a bubble gets shortly before it bursts.

// @param thickness 1 0.2 3 How thick the film is: thicker gives paler colors
// @param swirl 1 0 2 How much the film swirls as it drains
// @param light 1 0.3 3 How bright the room the bubble reflects
// @param size 1 0.6 1.3 How big the bubble is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
// Everything loops in this many seconds.
constant float LOOP = 60.0;
// Soapy water's refractive index.
constant float FILM_N = 1.33;
// What one surface reflects head on, ((n - 1) / (n + 1))².
constant float F0 = 0.0201;

float hash31(float3 p) {
    uint3 v = uint3(int3(floor(p))) * 1664525u + 1013904223u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    v ^= v >> 16u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    return float(v.x) * (1.0 / 4294967295.0);
}

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

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

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));
}

// Half a bell curve each side of mu.
float lobe(float x, float mu, float lo, float hi) {
    float k = (x - mu) / (x < mu ? lo : hi);
    return exp(-0.5 * k * k);
}

// A wavelength (nm) as linear RGB: the CIE 1931 color matching curves,
// then a screen's red, green and blue.
float3 wavelengthColor(float w) {
    float x = 1.056 * lobe(w, 599.8, 37.9, 31.0)
            + 0.362 * lobe(w, 442.0, 16.0, 26.7)
            - 0.065 * lobe(w, 501.1, 20.4, 26.2);
    float y = 0.821 * lobe(w, 568.8, 46.9, 40.5)
            + 0.286 * lobe(w, 530.9, 16.3, 31.1);
    float z = 1.217 * lobe(w, 437.0, 11.8, 36.0)
            + 0.681 * lobe(w, 459.0, 26.0, 13.8);
    return float3( 3.2406 * x - 1.5372 * y - 0.4986 * z,
                  -0.9689 * x + 1.8758 * y + 0.0415 * z,
                   0.0557 * x - 0.2040 * y + 1.0570 * z);
}

// The share of wavelength w a film d nm thick reflects: 0 at d = 0.
float filmReflect(float d, float w, float cosT, float F) {
    float delta = 2.0 * TAU * FILM_N * d * cosT / w;
    float c = cos(delta);
    return 2.0 * F * (1.0 - c) / (1.0 + F * F - 2.0 * F * c);
}

// 16 wavelengths, 400 to 700 nm, added up; white light gives white.
float3 filmColor(float d, float cosI) {
    // Snell's law: steeper inside the film.
    float cosT = sqrt(1.0 - (1.0 - cosI * cosI) / (FILM_N * FILM_N));
    // Fresnel: more at a glancing angle.
    float F = F0 + (1.0 - F0) * pow(1.0 - cosI, 5.0);
    float3 sum = float3(0.0), white = float3(0.0);
    for (int i = 0; i < 16; i++) {
        float w = 390.0 + 20.0 * (float(i) + 0.5);
        float3 s = wavelengthColor(w);
        sum += s * filmReflect(d, w, cosT, F);
        white += s;
    }
    return max(sum / white, 0.0);
}

// The film's thickness in nm at a point p on the bubble (from its center,
// length 1, y up) at time t.
float thicknessAt(float3 p, float t, constant Params& pr) {
    // Gravity drains it: about 30 nm near the top, 850 at the bottom.
    float drain = 0.5 - 0.5 * p.y;
    float d = 30.0 + 820.0 * pow(drain, 1.4);
    // Swirls: noise turned round once a minute, bent by noise that turns
    // twice.
    float a = TAU * t / LOOP;
    float3 r = float3(p.x * cos(a) - p.z * sin(a), p.y,
                      p.x * sin(a) + p.z * cos(a));
    float3 b = float3(cos(2.0 * a), sin(2.0 * a), 0.0);
    float3 warp = float3(fbm3(r * 1.7 + b, 3),
                         fbm3(r * 1.7 + b.yxz + 5.2, 3), 0.0);
    float n = fbm3(r * 2.2 + 2.5 * warp, 4);
    // They stir the film, less near the top.
    d *= 1.0 + pr.swirl * (1.3 * n - 0.65) * smoothstep(-0.1, 0.5, drain);
    // Black film: at the very top, about 6 nm, reflecting almost nothing.
    float cap = drain + 0.08 * (n - 0.5) - 0.02 * sin(3.0 * a);
    d = mix(6.0, d, smoothstep(0.11, 0.125, cap));
    return max(d, 0.0) * pr.thickness;
}

// What the bubble reflects from direction r (linear light): a dark warm
// room lit from the ceiling, a window up to the left with four panes, and
// the kiln's glow low on the right.
float3 room(float3 r, constant Params& p) {
    float3 col = pow(kiln(0.22 + 0.1 * r.y), 2.2);
    // A soft light from the ceiling, so the top of the bubble shows its film.
    col += float3(1.0, 0.95, 0.87) * 1.6 * smoothstep(0.2, 0.9, r.y);
    float3 w = normalize(float3(-0.55, 0.5, 0.67));
    float3 side = normalize(cross(float3(0, 1, 0), w));
    float3 up = cross(w, side);
    float2 f = float2(dot(r, side), dot(r, up)) / max(dot(r, w), 0.01);
    float pane = step(abs(f.x), 0.42) * step(abs(f.y), 0.32);
    pane *= step(0.025, abs(f.x)) * step(0.025, abs(f.y));
    pane *= step(0.0, dot(r, w));
    col += float3(1.0, 0.95, 0.87) * pane * 9.0;
    float3 g = normalize(float3(0.7, -0.45, 0.55));
    float glow = exp(-8.0 * (1.0 - dot(r, g)));
    col += pow(float3(1.0, 0.69, 0.38), 2.2) * glow * 6.0;
    return col * p.light;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 q = (uv - 0.5) * 2.0 * float2(u.resolution.x / u.resolution.y, 1.0);
    float t = fmod(u.time, LOOP);
    float a = TAU * t / LOOP;
    // The background: near-black, warmed low on the right by the kiln.
    float glow = exp(-1.6 * length(q - float2(1.3, -1.2)));
    float3 bg = pow(kiln(0.06 + 0.3 * glow), 2.2);
    float3 col = bg;

    // The bubble drifts a little and comes back each minute.
    float2 c = float2(0.05 * sin(3.0 * a), 0.04 * sin(4.0 * a));
    // Smaller in a tall picture, so it still fits across.
    float fit = min(1.0, 0.9 * u.resolution.x / u.resolution.y);
    float R = 0.62 * p.size * fit;
    float2 s = (q - c) / R;
    float r2 = dot(s, s);
    if (r2 < 1.0) {
        // Its front: n is the point on the ball and the way it faces.
        float3 n = float3(s, sqrt(1.0 - r2));
        float cosI = n.z;
        float3 r = float3(2.0 * cosI * n.xy, 2.0 * cosI * cosI - 1.0);
        float3 front = room(r, p) * filmColor(thicknessAt(n, t, p), cosI);
        // Light goes through the film nearly untouched.
        col = col * 0.96 + front;
    }
    // A soft edge, a pixel wide.
    float px = 2.0 / u.resolution.y / R;
    float edge = smoothstep(1.0 + px, 1.0 - px, sqrt(r2));
    col = mix(bg, col, edge);
    return float4(pow(max(col, 0.0), float3(1.0 / 2.2)), 1.0);
}

// The bubble, heard. Three tones stand for three colors of light: 220 Hz
// for red (650 nm), 277.2 for green (550 nm), 329.6 for blue (450 nm).
// Each is played twice, the copy out of step by what the light's second
// reflection is at the film in the middle of the bubble, and turned over
// as the first reflection is. They add as the light does: a color the
// film keeps is loud, a color it cancels goes quiet, so the chord follows
// the color in the middle as the film swirls past.

// One tone and its copy, delta out of step and turned over.
float twoWaves(float t, float f, float delta) {
    return sin(TAU * f * t) - sin(TAU * f * t + delta);
}

float2 sound(float t, constant Params& p) {
    float d = thicknessAt(float3(0.0, 0.0, 1.0), t, p);
    float3 w = float3(650.0, 550.0, 450.0);
    float3 delta = 2.0 * TAU * FILM_N * d / w;
    float red = twoWaves(t, 220.0, delta.x);
    float green = twoWaves(t, 277.2, delta.y);
    float blue = twoWaves(t, 329.6, delta.z);
    // A faint octave over each, the film's shimmer.
    red += 0.25 * twoWaves(t, 440.0, 2.0 * delta.x);
    green += 0.25 * twoWaves(t, 554.4, 2.0 * delta.y);
    blue += 0.25 * twoWaves(t, 659.2, 2.0 * delta.z);
    // Red to the left, blue to the right, green in the middle.
    float2 mixLR = float2(0.8 * red + 0.5 * green + 0.25 * blue,
                          0.25 * red + 0.5 * green + 0.8 * blue);
    // Fade in over the first 50 ms, so it starts without a click.
    return mixLR * 0.12 * p.volume * min(t * 20.0, 1.0);
}
1 line from stage 2 that are gone
    return d * pr.thickness;

Stage 4 · Soap Bubble

The finished shader adds the bubble's back wall. Seen through the front, its inside reflects the room as well, from the point behind (b, with z turned round), in the direction rb, the front's reflection with its x and y turned round. So the window shows twice: upright on the front, upside down on the back, each in its own film's colors. The back's reflection is added at 80%. All of it loops: every movement is a whole number of turns in 60 seconds.

the kiln palette and shade(), from the finished shader
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) {
    float2 q = (uv - 0.5) * 2.0 * float2(u.resolution.x / u.resolution.y, 1.0);
    float t = fmod(u.time, LOOP);
    float a = TAU * t / LOOP;
    // The background: near-black, warmed low on the right by the kiln.
    float glow = exp(-1.6 * length(q - float2(1.3, -1.2)));
    float3 bg = pow(kiln(0.06 + 0.3 * glow), 2.2);
    float3 col = bg;

    // The bubble drifts a little and comes back each minute.
    float2 c = float2(0.05 * sin(3.0 * a), 0.04 * sin(4.0 * a));
    // Smaller in a tall picture, so it still fits across.
    float fit = min(1.0, 0.9 * u.resolution.x / u.resolution.y);
    float R = 0.62 * p.size * fit;
    float2 s = (q - c) / R;
    float r2 = dot(s, s);
    if (r2 < 1.0) {
        // Its front: n is the point on the ball and the way it faces.
        float3 n = float3(s, sqrt(1.0 - r2));
        float cosI = n.z;
        float3 r = float3(2.0 * cosI * n.xy, 2.0 * cosI * cosI - 1.0);
        float3 front = room(r, p) * filmColor(thicknessAt(n, t, p), cosI);
        // Its back wall, seen through it from inside: the same reflection
        // turned round, so the window shows again, upside down.
        float3 b = float3(n.xy, -n.z);
        float3 rb = float3(-r.xy, r.z);
        float3 back = room(rb, p) * filmColor(thicknessAt(b, t, p), cosI);
        // Light goes through the film nearly untouched.
        col = col * 0.96 + front + 0.8 * back;
    }
    // A soft edge, a pixel wide.
    float px = 2.0 / u.resolution.y / R;
    float edge = smoothstep(1.0 + px, 1.0 - px, sqrt(r2));
    col = mix(bg, col, edge);
    return float4(pow(max(col, 0.0), float3(1.0 / 2.2)), 1.0);
}
soap-bubble.metal, the whole file4 new lines since stage 3
// Ray Kiln · Soap Bubble
//
// @episode Soap Bubble
// @length 60
// @variation 30
// @variations 1,2,4,6,8,10,11,12
// @sweeps thickness, swirl, light
// @still 21
// @teaches Thin-film interference, color from a film's thickness
// @category Fragment
// @tags thin-film interference, spectral rendering, color matching functions, fresnel, procedural sound
// @final Soap Bubble | Its back wall reflects the room too: the window again, upside down.
//
// A soap bubble has no color of its own. Its film, a few hundred
// nanometers of soapy water, reflects light twice: off its front and off
// its back. The two reflections meet a little out of step, by twice the
// film's thickness, and the front one is turned over by half a wave. A
// wavelength that comes back in step is bright; one that comes back out
// of step cancels. Which wavelengths survive depends on the thickness, so
// the thickness is the color. Here 16 wavelengths are reflected one by
// one, added up through the eye's color matching curves, and the film
// drains under gravity, thin at the top and thick at the bottom, while it
// swirls. Where it is thinnest it reflects nothing and goes black.
// 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 thickness 1 0.2 3 How thick the film is: thicker gives paler colors
// @param swirl 1 0 2 How much the film swirls as it drains
// @param light 1 0.3 3 How bright the room the bubble reflects
// @param size 1 0.6 1.3 How big the bubble is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
// Everything loops in this many seconds.
constant float LOOP = 60.0;
// Soapy water's refractive index.
constant float FILM_N = 1.33;
// What one surface reflects head on, ((n - 1) / (n + 1))².
constant float F0 = 0.0201;

float hash31(float3 p) {
    uint3 v = uint3(int3(floor(p))) * 1664525u + 1013904223u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    v ^= v >> 16u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    return float(v.x) * (1.0 / 4294967295.0);
}

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

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

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));
}

// Half a bell curve each side of mu.
float lobe(float x, float mu, float lo, float hi) {
    float k = (x - mu) / (x < mu ? lo : hi);
    return exp(-0.5 * k * k);
}

// A wavelength (nm) as linear RGB: the CIE 1931 color matching curves,
// then a screen's red, green and blue.
float3 wavelengthColor(float w) {
    float x = 1.056 * lobe(w, 599.8, 37.9, 31.0)
            + 0.362 * lobe(w, 442.0, 16.0, 26.7)
            - 0.065 * lobe(w, 501.1, 20.4, 26.2);
    float y = 0.821 * lobe(w, 568.8, 46.9, 40.5)
            + 0.286 * lobe(w, 530.9, 16.3, 31.1);
    float z = 1.217 * lobe(w, 437.0, 11.8, 36.0)
            + 0.681 * lobe(w, 459.0, 26.0, 13.8);
    return float3( 3.2406 * x - 1.5372 * y - 0.4986 * z,
                  -0.9689 * x + 1.8758 * y + 0.0415 * z,
                   0.0557 * x - 0.2040 * y + 1.0570 * z);
}

// The share of wavelength w a film d nm thick reflects: 0 at d = 0.
float filmReflect(float d, float w, float cosT, float F) {
    float delta = 2.0 * TAU * FILM_N * d * cosT / w;
    float c = cos(delta);
    return 2.0 * F * (1.0 - c) / (1.0 + F * F - 2.0 * F * c);
}

// 16 wavelengths, 400 to 700 nm, added up; white light gives white.
float3 filmColor(float d, float cosI) {
    // Snell's law: steeper inside the film.
    float cosT = sqrt(1.0 - (1.0 - cosI * cosI) / (FILM_N * FILM_N));
    // Fresnel: more at a glancing angle.
    float F = F0 + (1.0 - F0) * pow(1.0 - cosI, 5.0);
    float3 sum = float3(0.0), white = float3(0.0);
    for (int i = 0; i < 16; i++) {
        float w = 390.0 + 20.0 * (float(i) + 0.5);
        float3 s = wavelengthColor(w);
        sum += s * filmReflect(d, w, cosT, F);
        white += s;
    }
    return max(sum / white, 0.0);
}

// The film's thickness in nm at a point p on the bubble (from its center,
// length 1, y up) at time t.
float thicknessAt(float3 p, float t, constant Params& pr) {
    // Gravity drains it: about 30 nm near the top, 850 at the bottom.
    float drain = 0.5 - 0.5 * p.y;
    float d = 30.0 + 820.0 * pow(drain, 1.4);
    // Swirls: noise turned round once a minute, bent by noise that turns
    // twice.
    float a = TAU * t / LOOP;
    float3 r = float3(p.x * cos(a) - p.z * sin(a), p.y,
                      p.x * sin(a) + p.z * cos(a));
    float3 b = float3(cos(2.0 * a), sin(2.0 * a), 0.0);
    float3 warp = float3(fbm3(r * 1.7 + b, 3),
                         fbm3(r * 1.7 + b.yxz + 5.2, 3), 0.0);
    float n = fbm3(r * 2.2 + 2.5 * warp, 4);
    // They stir the film, less near the top.
    d *= 1.0 + pr.swirl * (1.3 * n - 0.65) * smoothstep(-0.1, 0.5, drain);
    // Black film: at the very top, about 6 nm, reflecting almost nothing.
    float cap = drain + 0.08 * (n - 0.5) - 0.02 * sin(3.0 * a);
    d = mix(6.0, d, smoothstep(0.11, 0.125, cap));
    return max(d, 0.0) * pr.thickness;
}

// What the bubble reflects from direction r (linear light): a dark warm
// room lit from the ceiling, a window up to the left with four panes, and
// the kiln's glow low on the right.
float3 room(float3 r, constant Params& p) {
    float3 col = pow(kiln(0.22 + 0.1 * r.y), 2.2);
    // A soft light from the ceiling, so the top of the bubble shows its film.
    col += float3(1.0, 0.95, 0.87) * 1.6 * smoothstep(0.2, 0.9, r.y);
    float3 w = normalize(float3(-0.55, 0.5, 0.67));
    float3 side = normalize(cross(float3(0, 1, 0), w));
    float3 up = cross(w, side);
    float2 f = float2(dot(r, side), dot(r, up)) / max(dot(r, w), 0.01);
    float pane = step(abs(f.x), 0.42) * step(abs(f.y), 0.32);
    pane *= step(0.025, abs(f.x)) * step(0.025, abs(f.y));
    pane *= step(0.0, dot(r, w));
    col += float3(1.0, 0.95, 0.87) * pane * 9.0;
    float3 g = normalize(float3(0.7, -0.45, 0.55));
    float glow = exp(-8.0 * (1.0 - dot(r, g)));
    col += pow(float3(1.0, 0.69, 0.38), 2.2) * glow * 6.0;
    return col * p.light;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 q = (uv - 0.5) * 2.0 * float2(u.resolution.x / u.resolution.y, 1.0);
    float t = fmod(u.time, LOOP);
    float a = TAU * t / LOOP;
    // The background: near-black, warmed low on the right by the kiln.
    float glow = exp(-1.6 * length(q - float2(1.3, -1.2)));
    float3 bg = pow(kiln(0.06 + 0.3 * glow), 2.2);
    float3 col = bg;

    // The bubble drifts a little and comes back each minute.
    float2 c = float2(0.05 * sin(3.0 * a), 0.04 * sin(4.0 * a));
    // Smaller in a tall picture, so it still fits across.
    float fit = min(1.0, 0.9 * u.resolution.x / u.resolution.y);
    float R = 0.62 * p.size * fit;
    float2 s = (q - c) / R;
    float r2 = dot(s, s);
    if (r2 < 1.0) {
        // Its front: n is the point on the ball and the way it faces.
        float3 n = float3(s, sqrt(1.0 - r2));
        float cosI = n.z;
        float3 r = float3(2.0 * cosI * n.xy, 2.0 * cosI * cosI - 1.0);
        float3 front = room(r, p) * filmColor(thicknessAt(n, t, p), cosI);
        // Its back wall, seen through it from inside: the same reflection
        // turned round, so the window shows again, upside down.
        float3 b = float3(n.xy, -n.z);
        float3 rb = float3(-r.xy, r.z);
        float3 back = room(rb, p) * filmColor(thicknessAt(b, t, p), cosI);
        // Light goes through the film nearly untouched.
        col = col * 0.96 + front + 0.8 * back;
    }
    // A soft edge, a pixel wide.
    float px = 2.0 / u.resolution.y / R;
    float edge = smoothstep(1.0 + px, 1.0 - px, sqrt(r2));
    col = mix(bg, col, edge);
    return float4(pow(max(col, 0.0), float3(1.0 / 2.2)), 1.0);
}

// The bubble, heard. Three tones stand for three colors of light: 220 Hz
// for red (650 nm), 277.2 for green (550 nm), 329.6 for blue (450 nm).
// Each is played twice, the copy out of step by what the light's second
// reflection is at the film in the middle of the bubble, and turned over
// as the first reflection is. They add as the light does: a color the
// film keeps is loud, a color it cancels goes quiet, so the chord follows
// the color in the middle as the film swirls past.

// One tone and its copy, delta out of step and turned over.
float twoWaves(float t, float f, float delta) {
    return sin(TAU * f * t) - sin(TAU * f * t + delta);
}

float2 sound(float t, constant Params& p) {
    float d = thicknessAt(float3(0.0, 0.0, 1.0), t, p);
    float3 w = float3(650.0, 550.0, 450.0);
    float3 delta = 2.0 * TAU * FILM_N * d / w;
    float red = twoWaves(t, 220.0, delta.x);
    float green = twoWaves(t, 277.2, delta.y);
    float blue = twoWaves(t, 329.6, delta.z);
    // A faint octave over each, the film's shimmer.
    red += 0.25 * twoWaves(t, 440.0, 2.0 * delta.x);
    green += 0.25 * twoWaves(t, 554.4, 2.0 * delta.y);
    blue += 0.25 * twoWaves(t, 659.2, 2.0 * delta.z);
    // Red to the left, blue to the right, green in the middle.
    float2 mixLR = float2(0.8 * red + 0.5 * green + 0.25 * blue,
                          0.25 * red + 0.5 * green + 0.8 * blue);
    // Fade in over the first 50 ms, so it starts without a click.
    return mixLR * 0.12 * p.volume * min(t * 20.0, 1.0);
}
1 line from stage 3 that are gone
        col = col * 0.96 + front;

The sound

The sound plays the color in the middle of the bubble. Three tones stand for three wavelengths: 220 Hz for red (650 nm), 277.2 Hz for green (550 nm) and 329.6 Hz for blue (450 nm), an A major chord. Each is played twice by twoWaves, sin(x) − sin(x + δ): the copy is out of step by the same delta the light gets in the film at the middle of the bubble (thicknessAt at the point facing the viewer), and it is subtracted, turned over as the front reflection is. Two waves like that add up to 2 |sin(δ / 2)| times one wave, so a tone is loud when its color comes back in step and silent when it cancels, as the light is. A quieter octave over each uses twice the delta, as a wavelength half as long would. Red leans left, blue right, green sits in the middle, and as the film swirls past the middle the chord's balance moves with the color there.

At the defaults the peak is −11.5 dBFS and the RMS −20.0 dBFS over the minute. With thickness at 0.2 it is −9.9 and −19.0 dBFS, at 3 it is −10.2 and −20.2, and with swirl at 0 (a steady chord) −12.4 and −20.1. The sound fades in over the first 50 ms, so it starts without a click. Every frequency makes a whole number of cycles in the minute and the film comes back to where it started, so as the picture loops the sound carries on unbroken; only a recording cut at exactly 60 s ends mid-wave.

New in Ray Kiln

Picture scopes in the playground. Press Scopes under the picture and histograms of the live frame appear under the tools: red, green and blue laid over each other on the left, brightness on the right, black at the left end of each and white at the right. Under them are each channel's mean and the share of pixels clipped at black (all three channels 0) and at white (any channel 255), and a hot bar marks either end when anything is clipped there. Brightness is the luma video scopes show, 0.2126 red + 0.7152 green + 0.0722 blue of the values on screen. About ten times a second the frame is copied and point-sampled on the GPU to 192 × 108 of its own pixels (never averaged, so a clipped pixel stays clipped), read back and counted. It reads the shader's own colors, before the color vision menu changes them, and works on any shader.

A bubble is mostly dark with small, very bright reflections, which is just what scopes are for. Open Soap Bubble in the playground and press Scopes: most of the picture piles up near black (a brightness mean of about 20 of 255), with long, thin tails out to the right where the window and the film's colors are, and under 0.1% clipped at white. Drag light to 3 and the tails stretch right, a spike grows at 255 in red, where the window and the bright rim burn out, and the share clipped at white climbs to about 1.4%. In stage 1, the red, green and blue histograms spread out across the range, and dragging thickness changes how they spread.

Try this

  • Set swirl to 0: the film drains evenly, and the colors lie in clean bands round the bubble, Newton's series from the black cap down.
  • Set thickness to 0.2: the whole film is in the first order, gray and white with a little straw yellow. At 3 it climbs to the high orders, where so many wavelengths come back in step at once that the colors wash out towards white.
  • In filmReflect, change 2.0 * F * (1.0 - c) to 2.0 * F * (1.0 + c): no half-wave turn at the front. The thinnest film is now brightest instead of black, and every band moves to its complement.
  • In filmColor, change the loop to 3 wavelengths, w = 450.0 + 100.0 * float(i) for i < 3: red, green and blue alone. The colors go garish and the higher orders never wash out, which is why the shader samples 16.
  • In room, raise the window's 9.0 to 30.0 and watch the scopes clip at white.
  • Set FILM_N to 1.0: no refraction. The bands spread out, since the path through the film is shorter for the same thickness.

Parameters

ParameterDefaultRangeWhat it does
thickness10.2 to 3How thick the film is: thicker gives paler colors
swirl10 to 2How much the film swirls as it drains
light10.3 to 3How bright the room the bubble reflects
size10.6 to 1.3How big the bubble is
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.

soap-bubble.metal
// Ray Kiln · Soap Bubble
//
// @episode Soap Bubble
// @length 60
// @variation 30
// @variations 1,2,4,6,8,10,11,12
// @sweeps thickness, swirl, light
// @still 21
// @teaches Thin-film interference, color from a film's thickness
// @category Fragment
// @tags thin-film interference, spectral rendering, color matching functions, fresnel, procedural sound
// @final Soap Bubble | Its back wall reflects the room too: the window again, upside down.
//
// A soap bubble has no color of its own. Its film, a few hundred
// nanometers of soapy water, reflects light twice: off its front and off
// its back. The two reflections meet a little out of step, by twice the
// film's thickness, and the front one is turned over by half a wave. A
// wavelength that comes back in step is bright; one that comes back out
// of step cancels. Which wavelengths survive depends on the thickness, so
// the thickness is the color. Here 16 wavelengths are reflected one by
// one, added up through the eye's color matching curves, and the film
// drains under gravity, thin at the top and thick at the bottom, while it
// swirls. Where it is thinnest it reflects nothing and goes black.
// 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 thickness 1 0.2 3 How thick the film is: thicker gives paler colors
// @param swirl 1 0 2 How much the film swirls as it drains
// @param light 1 0.3 3 How bright the room the bubble reflects
// @param size 1 0.6 1.3 How big the bubble is
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
// Everything loops in this many seconds.
constant float LOOP = 60.0;
// Soapy water's refractive index.
constant float FILM_N = 1.33;
// What one surface reflects head on, ((n - 1) / (n + 1))².
constant float F0 = 0.0201;

float hash31(float3 p) {
    uint3 v = uint3(int3(floor(p))) * 1664525u + 1013904223u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    v ^= v >> 16u;
    v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
    return float(v.x) * (1.0 / 4294967295.0);
}

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

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

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));
}

// Half a bell curve each side of mu.
float lobe(float x, float mu, float lo, float hi) {
    float k = (x - mu) / (x < mu ? lo : hi);
    return exp(-0.5 * k * k);
}

// A wavelength (nm) as linear RGB: the CIE 1931 color matching curves,
// then a screen's red, green and blue.
float3 wavelengthColor(float w) {
    float x = 1.056 * lobe(w, 599.8, 37.9, 31.0)
            + 0.362 * lobe(w, 442.0, 16.0, 26.7)
            - 0.065 * lobe(w, 501.1, 20.4, 26.2);
    float y = 0.821 * lobe(w, 568.8, 46.9, 40.5)
            + 0.286 * lobe(w, 530.9, 16.3, 31.1);
    float z = 1.217 * lobe(w, 437.0, 11.8, 36.0)
            + 0.681 * lobe(w, 459.0, 26.0, 13.8);
    return float3( 3.2406 * x - 1.5372 * y - 0.4986 * z,
                  -0.9689 * x + 1.8758 * y + 0.0415 * z,
                   0.0557 * x - 0.2040 * y + 1.0570 * z);
}

// The share of wavelength w a film d nm thick reflects: 0 at d = 0.
float filmReflect(float d, float w, float cosT, float F) {
    float delta = 2.0 * TAU * FILM_N * d * cosT / w;
    float c = cos(delta);
    return 2.0 * F * (1.0 - c) / (1.0 + F * F - 2.0 * F * c);
}

// 16 wavelengths, 400 to 700 nm, added up; white light gives white.
float3 filmColor(float d, float cosI) {
    // Snell's law: steeper inside the film.
    float cosT = sqrt(1.0 - (1.0 - cosI * cosI) / (FILM_N * FILM_N));
    // Fresnel: more at a glancing angle.
    float F = F0 + (1.0 - F0) * pow(1.0 - cosI, 5.0);
    float3 sum = float3(0.0), white = float3(0.0);
    for (int i = 0; i < 16; i++) {
        float w = 390.0 + 20.0 * (float(i) + 0.5);
        float3 s = wavelengthColor(w);
        sum += s * filmReflect(d, w, cosT, F);
        white += s;
    }
    return max(sum / white, 0.0);
}

// The film's thickness in nm at a point p on the bubble (from its center,
// length 1, y up) at time t.
float thicknessAt(float3 p, float t, constant Params& pr) {
    // Gravity drains it: about 30 nm near the top, 850 at the bottom.
    float drain = 0.5 - 0.5 * p.y;
    float d = 30.0 + 820.0 * pow(drain, 1.4);
    // Swirls: noise turned round once a minute, bent by noise that turns
    // twice.
    float a = TAU * t / LOOP;
    float3 r = float3(p.x * cos(a) - p.z * sin(a), p.y,
                      p.x * sin(a) + p.z * cos(a));
    float3 b = float3(cos(2.0 * a), sin(2.0 * a), 0.0);
    float3 warp = float3(fbm3(r * 1.7 + b, 3),
                         fbm3(r * 1.7 + b.yxz + 5.2, 3), 0.0);
    float n = fbm3(r * 2.2 + 2.5 * warp, 4);
    // They stir the film, less near the top.
    d *= 1.0 + pr.swirl * (1.3 * n - 0.65) * smoothstep(-0.1, 0.5, drain);
    // Black film: at the very top, about 6 nm, reflecting almost nothing.
    float cap = drain + 0.08 * (n - 0.5) - 0.02 * sin(3.0 * a);
    d = mix(6.0, d, smoothstep(0.11, 0.125, cap));
    return max(d, 0.0) * pr.thickness;
}

// What the bubble reflects from direction r (linear light): a dark warm
// room lit from the ceiling, a window up to the left with four panes, and
// the kiln's glow low on the right.
float3 room(float3 r, constant Params& p) {
    float3 col = pow(kiln(0.22 + 0.1 * r.y), 2.2);
    // A soft light from the ceiling, so the top of the bubble shows its film.
    col += float3(1.0, 0.95, 0.87) * 1.6 * smoothstep(0.2, 0.9, r.y);
    float3 w = normalize(float3(-0.55, 0.5, 0.67));
    float3 side = normalize(cross(float3(0, 1, 0), w));
    float3 up = cross(w, side);
    float2 f = float2(dot(r, side), dot(r, up)) / max(dot(r, w), 0.01);
    float pane = step(abs(f.x), 0.42) * step(abs(f.y), 0.32);
    pane *= step(0.025, abs(f.x)) * step(0.025, abs(f.y));
    pane *= step(0.0, dot(r, w));
    col += float3(1.0, 0.95, 0.87) * pane * 9.0;
    float3 g = normalize(float3(0.7, -0.45, 0.55));
    float glow = exp(-8.0 * (1.0 - dot(r, g)));
    col += pow(float3(1.0, 0.69, 0.38), 2.2) * glow * 6.0;
    return col * p.light;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float2 q = (uv - 0.5) * 2.0 * float2(u.resolution.x / u.resolution.y, 1.0);
    float t = fmod(u.time, LOOP);
    float a = TAU * t / LOOP;
    // The background: near-black, warmed low on the right by the kiln.
    float glow = exp(-1.6 * length(q - float2(1.3, -1.2)));
    float3 bg = pow(kiln(0.06 + 0.3 * glow), 2.2);
    float3 col = bg;

    // The bubble drifts a little and comes back each minute.
    float2 c = float2(0.05 * sin(3.0 * a), 0.04 * sin(4.0 * a));
    // Smaller in a tall picture, so it still fits across.
    float fit = min(1.0, 0.9 * u.resolution.x / u.resolution.y);
    float R = 0.62 * p.size * fit;
    float2 s = (q - c) / R;
    float r2 = dot(s, s);
    if (r2 < 1.0) {
        // Its front: n is the point on the ball and the way it faces.
        float3 n = float3(s, sqrt(1.0 - r2));
        float cosI = n.z;
        float3 r = float3(2.0 * cosI * n.xy, 2.0 * cosI * cosI - 1.0);
        float3 front = room(r, p) * filmColor(thicknessAt(n, t, p), cosI);
        // Its back wall, seen through it from inside: the same reflection
        // turned round, so the window shows again, upside down.
        float3 b = float3(n.xy, -n.z);
        float3 rb = float3(-r.xy, r.z);
        float3 back = room(rb, p) * filmColor(thicknessAt(b, t, p), cosI);
        // Light goes through the film nearly untouched.
        col = col * 0.96 + front + 0.8 * back;
    }
    // A soft edge, a pixel wide.
    float px = 2.0 / u.resolution.y / R;
    float edge = smoothstep(1.0 + px, 1.0 - px, sqrt(r2));
    col = mix(bg, col, edge);
    return float4(pow(max(col, 0.0), float3(1.0 / 2.2)), 1.0);
}

// The bubble, heard. Three tones stand for three colors of light: 220 Hz
// for red (650 nm), 277.2 for green (550 nm), 329.6 for blue (450 nm).
// Each is played twice, the copy out of step by what the light's second
// reflection is at the film in the middle of the bubble, and turned over
// as the first reflection is. They add as the light does: a color the
// film keeps is loud, a color it cancels goes quiet, so the chord follows
// the color in the middle as the film swirls past.

// One tone and its copy, delta out of step and turned over.
float twoWaves(float t, float f, float delta) {
    return sin(TAU * f * t) - sin(TAU * f * t + delta);
}

float2 sound(float t, constant Params& p) {
    float d = thicknessAt(float3(0.0, 0.0, 1.0), t, p);
    float3 w = float3(650.0, 550.0, 450.0);
    float3 delta = 2.0 * TAU * FILM_N * d / w;
    float red = twoWaves(t, 220.0, delta.x);
    float green = twoWaves(t, 277.2, delta.y);
    float blue = twoWaves(t, 329.6, delta.z);
    // A faint octave over each, the film's shimmer.
    red += 0.25 * twoWaves(t, 440.0, 2.0 * delta.x);
    green += 0.25 * twoWaves(t, 554.4, 2.0 * delta.y);
    blue += 0.25 * twoWaves(t, 659.2, 2.0 * delta.z);
    // Red to the left, blue to the right, green in the middle.
    float2 mixLR = float2(0.8 * red + 0.5 * green + 0.25 * blue,
                          0.25 * red + 0.5 * green + 0.8 * blue);
    // Fade in over the first 50 ms, so it starts without a click.
    return mixLR * 0.12 * p.volume * min(t * 20.0, 1.0);
}

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] = [1, 1, 1, 1, 0.8]     // the @param defaults, in the order they are declared
encoder.setRenderPipelineState(pipeline)
encoder.setFragmentBytes(&uniforms, length: MemoryLayout<Uniforms>.stride, index: 0)
encoder.setFragmentBytes(&params, length: params.count * MemoryLayout<Float>.stride, index: 1)
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)

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

More in Light & Materials