Shader

Plucked Strings

Six strings on a board, plucked in a four-bar tune in D minor pentatonic. Karplus-Strong makes a string from a loop of samples filled with noise and averaged on every trip round, which takes the high harmonics first, so a bright buzz mellows into a note. A shader's sound has no memory to keep that loop in, so this one adds up the harmonics the loop would hold, each dying away at the rate the loop would give it. The picture draws each string from the same harmonics, as the standing waves they are between its two ends, swung 48 times slower than they sound and glowing as hot as the string still rings.

· Sound & Rhythm · Fragment shader

Teaches Karplus-Strong synthesis, strings drawn as they vibrate

Builds on Flowing Color Field, A Shader That Keeps the Beat (whole-number hash), Murmuration (segment distance), Pulse Synth (line from a distance), Wind Chimes

Watch

The idea

In 1983 Kevin Karplus and Alex Strong published a very cheap way to make a plucked string. Take a loop of N samples, a delay line, and fill it with noise. Play it round and round, and on every trip average each sample with its neighbor. Noise that repeats every N samples is no longer noise: it is a tone at the sample rate over N, made of harmonics at whole multiples of that pitch, each at a random size. The averaging is a gentle filter. On each trip it keeps cos(π k f / 48000) of harmonic k of a string at f Hz: nearly all of the lowest, less of each one above. There are f trips a second, so each harmonic dies away exponentially, and the higher it is, the sooner. The pluck starts as a buzz and settles into a note.

A Ray Kiln shader's sound(t) can't run that loop. It is a pure function of the time: each sample is worked out on its own, with no memory of the one before, so there is nowhere to keep a delay line. But what the loop does to each harmonic has a closed form: after t seconds, harmonic k has been through f · t trips and is exp(f · t · log(keep)) of its starting size. So this shader never keeps a loop. For every pluck it adds up the first 24 harmonics the loop would hold, each a sine at k times the pitch, each fading at the rate the loop would give it. It is the same idea as Wind Chimes, a struck object as a sum of sines that ring down at their own rates, with the rates taken from Karplus-Strong's filter.

The same harmonics draw the strings. On a string held at both ends, harmonic k is a standing wave, sin(k π s) along it, with k arches, so each string is drawn as the sum of its harmonics, bent as the sound is made. It is built in five steps.

Stage 1 · One string, one sine

One string between two pins, plucked every two seconds from 1.5 s. Its simplest motion is a single arch, sin(π s) along it (s runs from 0 at the left pin to 1 at the right), swinging at its pitch, A3 at 220 Hz. The sound is that one sine. On each cycle it keeps 1 − 0.008 · damping of its swing, so at the default damping of 0.2 it dies away with a time constant of 2.8 seconds, and at 0 it doesn't die away at all.

A pluck rises over 3 ms, so it starts without a click, and when the next pluck comes, the one before is stopped within 30 ms. Only the last two plucks are added up, since any older one has already been stopped.

The picture can't swing at 220 times a second, so the arch swings slow (48) times slower than it sounds: 4.6 times a second. The string's heat is how much of its swing is left, times 1.5 and held at 1, and that heat is its place on the kiln palette from Flowing Color Field (plus a glow around it as hot as it is): white-hot after a pluck, cooling through gold and orange toward the dull red of a string at rest. At the default damping the next pluck comes while it is still gold. The heat rises over 40 ms rather than in one frame.

stage-1-one-string-one-sine.metal
// Stage 1 · One string, one sine
// A string held at both ends, plucked every two seconds. Its simplest motion is one arch, half a sine along it,
// swinging at its pitch, A3 at 220 Hz. The sound is that sine, losing a little swing each cycle; the string glows
// as hot as it rings.

// @param damping 0.2 0 1 How much of its swing the string loses on each cycle
// @param slow 48 16 256 How many times slower the picture swings than the sound
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.1415927;

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

// The string's pitch, A3.
constant float NOTE = 220.0;

// How much of the swing is left after one cycle, as a logarithm.
float tripLoss(float f, constant Params& p) {
    return log(1.0 - 0.008 * p.damping);
}

// A pluck rises over 3 ms, so it starts without a click.
float rise(float since) {
    return smoothstep(0.0, 0.003, since);
}

// A pluck every two seconds, the first at 1.5 s.
constant float EVERY = 2.0;
constant float FIRST = 1.5;

// The last two plucks before t: when, and which (-1 when there is none).
void lastPlucks(float t, thread float& when0, thread int& id0,
                thread float& when1, thread int& id1) {
    int now = int(floor((t - FIRST) / EVERY));
    id0 = now;
    id1 = now - 1;
    when0 = FIRST + EVERY * float(now);
    when1 = when0 - EVERY;
    if (id0 < 0) id0 = -1;
    if (id1 < 0) id1 = -1;
}

// How much one pluck still sounds: its rise, and a newer pluck stopping
// it within 30 ms.
float pluckGain(float since, float t, float newer, bool stopped) {
    float g = rise(since);
    if (stopped) g *= 1.0 - smoothstep(0.0, 0.03, t - newer);
    return g;
}

// The string at t: a sine at its pitch for each of its last two plucks,
// shrinking by tripLoss on each of the f cycles a second.
float stringSound(float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(t, when0, id0, when1, id1);
    float f = NOTE;
    float sum = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Whole cycles dropped first, so the phase stays precise.
        float cycles = fract(f * since);
        float left = exp(f * since * tripLoss(f, p));
        sum += g * left * sin(TAU * cycles);
    }
    return sum;
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// The string's shape at s (0 at the left end, 1 at the right) at t: how
// far it is bent, its slope along s, and how hot it is. Its one arch,
// sin(pi s), swings `slow` times slower than it sounds.
float4 stringShape(float s, float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(t, when0, id0, when1, id1);
    float f = NOTE;
    float bend = 0.0, slope = 0.0, now = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Heat rises over 40 ms, not in one frame.
        float warm = smoothstep(0.0, 0.04, since);
        float seen = fract(f * since / p.slow);
        float a = g * exp(f * since * tripLoss(f, p));
        float move = sin(TAU * seen);
        bend += a * sin(PI * s) * move;
        slope += a * PI * cos(PI * s) * move;
        now += a * a * warm;
    }
    return float4(bend, slope, 0.0, sqrt(now));
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float aspect = u.resolution.x / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y);
    float px = 1.0 / u.resolution.y;
    float cx = 0.5 * aspect;
    // Narrower than 16:9, the string shortens with the picture.
    float wide = min(aspect / 1.7778, 1.0);

    // A dark ground, warmer toward the middle.
    float heat = 0.04 + 0.04 * exp(-2.0 * length(q - float2(cx, 0.5)));

    // The string runs between two pins.
    float3 at = float3(0.5, cx - 0.7 * wide, cx + 0.7 * wide);
    for (int e = 0; e < 2; e++) {
        float pin = length(q - float2(e == 0 ? at.y : at.z, at.x)) - 0.012;
        heat = max(heat, 0.5 * lineAt(pin, 1.5 * px));
    }

    float len = at.z - at.y;
    float s = clamp((q.x - at.y) / len, 0.0, 1.0);
    float4 shape = stringShape(s, t, p);
    float size = 0.12;
    float y = at.x + size * shape.x;
    // The distance to a curve: how far off it, over the slope's stretch.
    float tilt = size * shape.y / len;
    float d = abs(q.y - y) / sqrt(1.0 + tilt * tilt);
    // Past an end, the distance is to that end.
    float past = q.x - clamp(q.x, at.y, at.z);
    d = sqrt(d * d + past * past);
    float thick = 0.003;
    float hot = min(1.5 * shape.w, 1.0);

    // A glow as hot as the string rings, then the string itself.
    heat += 0.22 * hot * exp(-max(d - thick, 0.0) / 0.01);
    float lit = 0.34 + 0.66 * hot;
    heat = mix(heat, lit, lineAt(d - thick, 1.5 * px));
    return float4(kiln(heat), 1.0);
}

float2 sound(float t, constant Params& p) {
    return float2(tanh(stringSound(t, p) * 0.3)) * p.volume;
}

Stage 2 · A burst of noise

Karplus-Strong starts a string with noise, and noise that repeats once a cycle is a sum of harmonics. burst gives harmonic k of pluck number id a size, (0.35 + 0.65 · hash) / 3, and a phase, both from the integer hash, so every pluck is a different burst. There are 24 of them, sines at 220, 440, 660 Hz and on up to 5,280 Hz, added up in stringSound.

Each is drawn as a standing wave with k arches, sin(k π s), swinging k times as fast as the first, and their sum is a jagged string. The heat is now the square root of the share of the pluck's starting energy that is left. Here all 24 lose the same share on each cycle, so the string stays jagged as it fades: more than a second after a pluck, it is still a tangle of small waves.

stage-2-a-burst-of-noise.metal35 new lines since stage 1
// Stage 2 · A burst of noise
// Karplus-Strong starts a string with noise. Noise that repeats once a cycle is a sum of harmonics, whole multiples
// of the pitch at random sizes and phases, each a standing wave with k arches. Here all 24 fade alike, so the
// string stays jagged.

// @param damping 0.2 0 1 How much of its swing each harmonic loses on each cycle
// @param slow 48 16 256 How many times slower the picture swings than the sound
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.1415927;

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

uint hashBits(uint x) {
    x ^= x >> 16;
    x *= 0x7feb352du;
    x ^= x >> 15;
    x *= 0x846ca68bu;
    x ^= x >> 16;
    return x;
}

// A whole number in, a number from 0 to 1 out.
float noiseOf(uint x) {
    return float(hashBits(x) & 0xffffu) / 65535.0;
}

// The lowest 24 harmonics of the noise are kept.
constant int HARMONICS = 24;

// The string's pitch, A3.
constant float NOTE = 220.0;

// How much of the swing is left after one cycle, as a logarithm.
float tripLoss(float f, constant Params& p) {
    return log(1.0 - 0.008 * p.damping);
}

// A pluck rises over 3 ms, so it starts without a click.
float rise(float since) {
    return smoothstep(0.0, 0.003, since);
}

// A pluck every two seconds, the first at 1.5 s.
constant float EVERY = 2.0;
constant float FIRST = 1.5;

// The last two plucks before t: when, and which (-1 when there is none).
void lastPlucks(float t, thread float& when0, thread int& id0,
                thread float& when1, thread int& id1) {
    int now = int(floor((t - FIRST) / EVERY));
    id0 = now;
    id1 = now - 1;
    when0 = FIRST + EVERY * float(now);
    when1 = when0 - EVERY;
    if (id0 < 0) id0 = -1;
    if (id1 < 0) id1 = -1;
}

// The noise, seen as harmonics: harmonic k of the pluck numbered `id`
// starts at this size, at this phase.
float2 burst(int id, int k, constant Params& p) {
    uint seed = uint(id) * 7919u + uint(k) * 31u;
    float size = (0.35 + 0.65 * noiseOf(seed)) / 3.0;
    return float2(size, noiseOf(seed + 17u));
}

// How much one pluck still sounds: its rise, and a newer pluck stopping
// it within 30 ms.
float pluckGain(float since, float t, float newer, bool stopped) {
    float g = rise(since);
    if (stopped) g *= 1.0 - smoothstep(0.0, 0.03, t - newer);
    return g;
}

// The string at t: each of its last two plucks, harmonic by harmonic,
// each harmonic shrinking by tripLoss on each of the f cycles a second.
float stringSound(float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(t, when0, id0, when1, id1);
    float f = NOTE;
    float sum = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Whole cycles dropped first, so the phase stays precise.
        float cycles = fract(f * since);
        for (int k = 1; k <= HARMONICS; k++) {
            float2 b = burst(id, k, p);
            float left = exp(f * since * tripLoss(f, p));
            sum += g * b.x * left * sin(TAU * (float(k) * cycles + b.y));
        }
    }
    return sum;
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// The string's shape at s (0 at the left end, 1 at the right) at t: how
// far it is bent, its slope along s, and how hot it is. Harmonic k is a
// standing wave, sin(k pi s), whose swing runs `slow` times slower than
// it sounds.
float4 stringShape(float s, float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(t, when0, id0, when1, id1);
    float f = NOTE;
    float bend = 0.0, slope = 0.0, now = 0.0, start = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Heat rises over 40 ms, not in one frame.
        float warm = smoothstep(0.0, 0.04, since);
        float seen = fract(f * since / p.slow);
        for (int k = 1; k <= HARMONICS; k++) {
            float2 b = burst(id, k, p);
            float a = g * b.x * exp(f * since * tripLoss(f, p));
            float kp = float(k) * PI;
            float move = sin(TAU * (float(k) * seen + b.y));
            bend += a * sin(kp * s) * move;
            slope += a * kp * cos(kp * s) * move;
            now += a * a * warm;
            if (j == 0) start += b.x * b.x;
        }
    }
    float hot = start > 0.0 ? sqrt(now / start) : 0.0;
    return float4(bend, slope, 0.0, hot);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float aspect = u.resolution.x / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y);
    float px = 1.0 / u.resolution.y;
    float cx = 0.5 * aspect;
    // Narrower than 16:9, the string shortens with the picture.
    float wide = min(aspect / 1.7778, 1.0);

    // A dark ground, warmer toward the middle.
    float heat = 0.04 + 0.04 * exp(-2.0 * length(q - float2(cx, 0.5)));

    // The string runs between two pins.
    float3 at = float3(0.5, cx - 0.7 * wide, cx + 0.7 * wide);
    for (int e = 0; e < 2; e++) {
        float pin = length(q - float2(e == 0 ? at.y : at.z, at.x)) - 0.012;
        heat = max(heat, 0.5 * lineAt(pin, 1.5 * px));
    }

    float len = at.z - at.y;
    float s = clamp((q.x - at.y) / len, 0.0, 1.0);
    float4 shape = stringShape(s, t, p);
    float size = 0.06;
    float y = at.x + size * shape.x;
    // The distance to a curve: how far off it, over the slope's stretch.
    float tilt = size * shape.y / len;
    float d = abs(q.y - y) / sqrt(1.0 + tilt * tilt);
    // Past an end, the distance is to that end.
    float past = q.x - clamp(q.x, at.y, at.z);
    d = sqrt(d * d + past * past);
    float thick = 0.003;
    float hot = min(1.5 * shape.w, 1.0);

    // A glow as hot as the string rings, then the string itself.
    heat += 0.22 * hot * exp(-max(d - thick, 0.0) / 0.01);
    float lit = 0.34 + 0.66 * hot;
    heat = mix(heat, lit, lineAt(d - thick, 1.5 * px));
    return float4(kiln(heat), 1.0);
}

float2 sound(float t, constant Params& p) {
    return float2(tanh(stringSound(t, p) * 0.25)) * p.volume;
}
9 lines from stage 1 that are gone
        sum += g * left * sin(TAU * cycles);
⋯
    float bend = 0.0, slope = 0.0, now = 0.0;
⋯
        float a = g * exp(f * since * tripLoss(f, p));
        float move = sin(TAU * seen);
        bend += a * sin(PI * s) * move;
        slope += a * PI * cos(PI * s) * move;
⋯
    return float4(bend, slope, 0.0, sqrt(now));
⋯
    float size = 0.12;
⋯
    return float2(tanh(stringSound(t, p) * 0.3)) * p.volume;

Stage 3 · The loop's filter

Now the harmonics die away as Karplus-Strong's loop would make them, though there is still no loop in the code. A loop is a whole number of samples, N = floor(48000 / 220 − 0.5), 217, and the averaging delays the sound by another half sample, so the string plays 48000 / 217.5: 220.69 Hz, close to A3 and never quite on it. loopPitch works that out.

tripLoss is what one trip round the loop leaves of harmonic k, as a logarithm: log(cos(π k f / 48000)) for the averaging, plus log(1 − 0.008 · damping) taken from every harmonic alike. Times the f trips a second it is the rate each harmonic dies at. At the default damping of 0.2, the fundamental's time constant is 2.7 s, the 8th harmonic's 0.55 s and the 24th's 0.07 s. With the averaging alone, at damping 0, the fundamental would ring with a time constant of 43 s. So the high harmonics go first: the buzz of the pluck mellows into a tone, and the string drawn from the same harmonics loses its small waves and smooths into a few broad arches as it cools. Harmonics that would reach half the sample rate are skipped (none do here).

stage-3-the-loops-filter.metal15 new lines since stage 2
// Stage 3 · The loop's filter
// This is Karplus-Strong: a loop of N samples, each averaged with its neighbor every trip round. That keeps
// cos(pi k f / rate) of harmonic k a trip, less the higher k is, so the buzz mellows into a tone and the string
// smooths.

// @param damping 0.2 0 1 Loss on each trip round the loop besides the averaging: 0 is plain Karplus-Strong
// @param slow 48 16 256 How many times slower the picture swings than the sound
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.1415927;

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

uint hashBits(uint x) {
    x ^= x >> 16;
    x *= 0x7feb352du;
    x ^= x >> 15;
    x *= 0x846ca68bu;
    x ^= x >> 16;
    return x;
}

// A whole number in, a number from 0 to 1 out.
float noiseOf(uint x) {
    return float(hashBits(x) & 0xffffu) / 65535.0;
}

// The sound's rate, and the loop's: 48,000 samples a second.
constant float RATE = 48000.0;
// The lowest 24 harmonics of the noise are kept; the ones above them
// die within a fraction of a second.
constant int HARMONICS = 24;

// The string's pitch, A3.
constant float NOTE = 220.0;

// A loop is a whole number of samples, N, and the averaging adds half a
// sample, so a string plays RATE / (N + 0.5). A3 plays 220.69 Hz.
float loopPitch(float hz) {
    float n = floor(RATE / hz - 0.5);
    return RATE / (n + 0.5);
}

// What is left of harmonic k after a trip, as a log; `damping` takes a
// little more off each.
float tripLoss(int k, float f, constant Params& p) {
    float keep = cos(PI * float(k) * f / RATE);
    float extra = 1.0 - 0.008 * p.damping;
    return log(max(keep, 0.000001)) + log(extra);
}

// A pluck rises over 3 ms, so it starts without a click.
float rise(float since) {
    return smoothstep(0.0, 0.003, since);
}

// A pluck every two seconds, the first at 1.5 s.
constant float EVERY = 2.0;
constant float FIRST = 1.5;

// The last two plucks before t: when, and which (-1 when there is none).
void lastPlucks(float t, thread float& when0, thread int& id0,
                thread float& when1, thread int& id1) {
    int now = int(floor((t - FIRST) / EVERY));
    id0 = now;
    id1 = now - 1;
    when0 = FIRST + EVERY * float(now);
    when1 = when0 - EVERY;
    if (id0 < 0) id0 = -1;
    if (id1 < 0) id1 = -1;
}

// The noise, seen as harmonics: harmonic k of the pluck numbered `id`
// starts at this size, at this phase.
float2 burst(int id, int k, constant Params& p) {
    uint seed = uint(id) * 7919u + uint(k) * 31u;
    float size = (0.35 + 0.65 * noiseOf(seed)) / 3.0;
    return float2(size, noiseOf(seed + 17u));
}

// How much one pluck still sounds: its rise, and a newer pluck stopping
// it within 30 ms.
float pluckGain(float since, float t, float newer, bool stopped) {
    float g = rise(since);
    if (stopped) g *= 1.0 - smoothstep(0.0, 0.03, t - newer);
    return g;
}

// The string at t: each of its last two plucks, harmonic by harmonic,
// each harmonic falling by tripLoss on each of the f trips a second.
float stringSound(float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(t, when0, id0, when1, id1);
    float f = loopPitch(NOTE);
    float sum = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Whole cycles dropped first, so the phase stays precise.
        float cycles = fract(f * since);
        for (int k = 1; k <= HARMONICS; k++) {
            if (float(k) * f >= 0.5 * RATE) break;
            float2 b = burst(id, k, p);
            float left = exp(f * since * tripLoss(k, f, p));
            sum += g * b.x * left * sin(TAU * (float(k) * cycles + b.y));
        }
    }
    return sum;
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// The string's shape at s (0 at the left end, 1 at the right) at t: how
// far it is bent, its slope along s, and how hot it is. Harmonic k is a
// standing wave, sin(k pi s), whose swing runs `slow` times slower than
// it sounds.
float4 stringShape(float s, float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(t, when0, id0, when1, id1);
    float f = loopPitch(NOTE);
    float bend = 0.0, slope = 0.0, now = 0.0, start = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Heat rises over 40 ms, not in one frame.
        float warm = smoothstep(0.0, 0.04, since);
        float seen = fract(f * since / p.slow);
        for (int k = 1; k <= HARMONICS; k++) {
            float2 b = burst(id, k, p);
            float a = g * b.x * exp(f * since * tripLoss(k, f, p));
            float kp = float(k) * PI;
            float move = sin(TAU * (float(k) * seen + b.y));
            bend += a * sin(kp * s) * move;
            slope += a * kp * cos(kp * s) * move;
            now += a * a * warm;
            if (j == 0) start += b.x * b.x;
        }
    }
    float hot = start > 0.0 ? sqrt(now / start) : 0.0;
    return float4(bend, slope, 0.0, hot);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = u.time;
    float aspect = u.resolution.x / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y);
    float px = 1.0 / u.resolution.y;
    float cx = 0.5 * aspect;
    // Narrower than 16:9, the string shortens with the picture.
    float wide = min(aspect / 1.7778, 1.0);

    // A dark ground, warmer toward the middle.
    float heat = 0.04 + 0.04 * exp(-2.0 * length(q - float2(cx, 0.5)));

    // The string runs between two pins.
    float3 at = float3(0.5, cx - 0.7 * wide, cx + 0.7 * wide);
    for (int e = 0; e < 2; e++) {
        float pin = length(q - float2(e == 0 ? at.y : at.z, at.x)) - 0.012;
        heat = max(heat, 0.5 * lineAt(pin, 1.5 * px));
    }

    float len = at.z - at.y;
    float s = clamp((q.x - at.y) / len, 0.0, 1.0);
    float4 shape = stringShape(s, t, p);
    float size = 0.06;
    float y = at.x + size * shape.x;
    // The distance to a curve: how far off it, over the slope's stretch.
    float tilt = size * shape.y / len;
    float d = abs(q.y - y) / sqrt(1.0 + tilt * tilt);
    // Past an end, the distance is to that end.
    float past = q.x - clamp(q.x, at.y, at.z);
    d = sqrt(d * d + past * past);
    float thick = 0.003;
    float hot = min(1.5 * shape.w, 1.0);

    // A glow as hot as the string rings, then the string itself.
    heat += 0.22 * hot * exp(-max(d - thick, 0.0) / 0.01);
    float lit = 0.34 + 0.66 * hot;
    heat = mix(heat, lit, lineAt(d - thick, 1.5 * px));
    return float4(kiln(heat), 1.0);
}

float2 sound(float t, constant Params& p) {
    return float2(tanh(stringSound(t, p) * 0.4)) * p.volume;
}
7 lines from stage 2 that are gone
float tripLoss(float f, constant Params& p) {
    return log(1.0 - 0.008 * p.damping);
⋯
    float f = NOTE;
⋯
            float left = exp(f * since * tripLoss(f, p));
⋯
    float f = NOTE;
⋯
            float a = g * b.x * exp(f * since * tripLoss(f, p));
⋯
    return float2(tanh(stringSound(t, p) * 0.25)) * p.volume;

Stage 4 · Six strings and a tune

Six strings in D minor pentatonic, D3, F3, G3, A3, C4 and D4, from bottom to top. Each plays its loop's pitch rather than the note: 147.01, 174.86, 196.32, 220.69, 263.01 and 295.38 Hz, from loops of 326, 274, 244, 217, 182 and 162 samples. A string's length goes as one over its pitch, so the top D is half as long as the bottom one. They all end at a nut on the right, with a tuning peg past each, and start at a pin on the left, where a slanted edge of the board runs along the pins. A higher string is drawn thinner and its swing smaller. Behind them is the board, a faint grain across it and a dark sound hole with a ring round it.

The tune is 32 eighths, four bars in TUNE: which string each eighth plucks, or a rest. An eighth is 30 / tempo seconds, a third of a second at the default 90, so the tune opens D3, A3, C4, D4, C4, A3, a rest, G3, F3, A3, D4, C4. It has 27 plucks and 5 rests, and plays round and round: 142 plucks a minute. lastPlucks looks back from the moment for the last two eighths that plucked each string, as far as 16 seconds back; a new pluck stops the one before on that string within 30 ms, and an old one is forgotten over its 12th to 16th second.

The piece is a minute long. Plucks stop at 56 s, a hand lays across the strings from 56.5 s and has stilled them by 59.5 s, and both picture and sound read the time within the minute, so at 60 s it starts again from the first frame. The strings are spread between the ears, D3 to the left and D4 to the right.

stage-4-six-strings-and-a-tune.metal105 new lines since stage 3
// Stage 4 · Six strings and a tune
// Six strings in D minor pentatonic, each as long as one over its pitch, play a four-bar tune in eighths. A new
// pluck refills a string's loop, stopping its last note in 30 ms. At 56 s a hand mutes them, so the minute ends
// still.

// @param tempo 90 60 160 Beats a minute; the tune moves in eighths
// @param damping 0.2 0 1 Loss on each trip round the loop besides the averaging: 0 is plain Karplus-Strong
// @param slow 48 16 256 How many times slower the picture swings than the sound
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.1415927;

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

uint hashBits(uint x) {
    x ^= x >> 16;
    x *= 0x7feb352du;
    x ^= x >> 15;
    x *= 0x846ca68bu;
    x ^= x >> 16;
    return x;
}

// A whole number in, a number from 0 to 1 out.
float noiseOf(uint x) {
    return float(hashBits(x) & 0xffffu) / 65535.0;
}

// The sound runs at 48,000 samples a second, the rate of the loop.
constant float RATE = 48000.0;
// The lowest 24 harmonics of the noise are kept; the ones above them
// die within a fraction of a second.
constant int HARMONICS = 24;

// A loop is a whole number of samples, N, and the averaging delays the
// sound by half of one more, so a string plays RATE / (N + 0.5): close to
// the note asked for, never quite on it. D3 plays 147.01 Hz.
float loopPitch(float hz) {
    float n = floor(RATE / hz - 0.5);
    return RATE / (n + 0.5);
}

// How much of harmonic k is left after one trip round the loop, as a
// logarithm. Averaging two neighbors keeps cos(pi k f / RATE) of it;
// `damping` takes a little more off every harmonic alike.
float tripLoss(int k, float f, constant Params& p) {
    float keep = cos(PI * float(k) * f / RATE);
    float extra = 1.0 - 0.008 * p.damping;
    return log(max(keep, 0.000001)) + log(extra);
}

// A pluck rises over 3 ms, so it starts without a click.
float rise(float since) {
    return smoothstep(0.0, 0.003, since);
}

// Six strings in D minor pentatonic, D3 to D4, low to high.
constant int STRINGS = 6;
float stringNote(int i) {
    const float hz[6] = {146.83, 174.61, 196.00, 220.00, 261.63, 293.66};
    return hz[clamp(i, 0, 5)];
}

// The tune: which string each eighth plucks, -1 for a rest, four bars.
constant int TUNE[32] = {0, 3, 4, 5, 4, 3, -1, 2,
                         1, 3, 5, 4, -1, 3, 2, 3,
                         0, 2, 4, 5, 3, 4, -1, 5,
                         1, 4, 3, 2, -1, 3, 1, -1};

// The piece is a minute long: plucks stop at 56 s, a hand lays across
// the strings from 56.5 s, and at 59.5 s all is still for the next round.
constant float LOOP = 60.0;
constant float LAST = 56.0;
float handOff(float t) {
    return 1.0 - smoothstep(56.5, 59.5, t);
}

// Time within the minute.
float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// A pluck is forgotten over its 12th to 16th second.
constant float MEMORY = 16.0;
float kept(float since) {
    return 1.0 - smoothstep(12.0, MEMORY, since);
}

// The last two eighths that plucked string i before t: when, and which
// eighth (-1 when there is none).
void lastPlucks(int i, float t, constant Params& p,
                thread float& when0, thread int& id0,
                thread float& when1, thread int& id1) {
    float len = 30.0 / p.tempo;
    int now = int(floor(t / len));
    id0 = -1;
    id1 = -1;
    when0 = 0.0;
    when1 = 0.0;
    for (int back = 0; back < 96; back++) {
        int e = now - back;
        if (e < 0) break;
        float at = float(e) * len;
        if (t - at > MEMORY) break;
        if (at >= LAST || TUNE[e % 32] != i) continue;
        if (id0 < 0) {
            id0 = e;
            when0 = at;
        } else {
            id1 = e;
            when1 = at;
            break;
        }
    }
}

// The noise that fills the loop, seen as harmonics: harmonic k of the
// pluck numbered `id` on string i starts at this size, at this phase.
float2 burst(int i, int id, int k, constant Params& p) {
    uint seed = uint(id) * 7919u + uint(i) * 104729u + uint(k) * 31u;
    float size = (0.35 + 0.65 * noiseOf(seed)) / 3.0;
    return float2(size, noiseOf(seed + 17u));
}

// How much one pluck still sounds: its rise, the hand at the end, and a
// newer pluck on the same string stopping it within 30 ms.
float pluckGain(float since, float t, float newer, bool stopped) {
    float g = rise(since) * kept(since) * handOff(t);
    if (stopped) g *= 1.0 - smoothstep(0.0, 0.03, t - newer);
    return g;
}

// String i at t: each of its last two plucks, harmonic by harmonic, each
// harmonic falling by tripLoss on each of the f trips a second.
float stringSound(int i, float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(i, t, p, when0, id0, when1, id1);
    float f = loopPitch(stringNote(i));
    float sum = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Whole cycles dropped first, so the phase stays precise.
        float cycles = fract(f * since);
        for (int k = 1; k <= HARMONICS; k++) {
            if (float(k) * f >= 0.5 * RATE) break;
            float2 b = burst(i, id, k, p);
            float left = exp(f * since * tripLoss(k, f, p));
            sum += g * b.x * left * sin(TAU * (float(k) * cycles + b.y));
        }
    }
    return sum;
}

// All six, low strings to the left, high to the right.
float2 strings(float t, constant Params& p) {
    float tl = loopTime(t);
    float2 sum = float2(0.0);
    for (int i = 0; i < STRINGS; i++) {
        float pan = 0.25 + 0.5 * float(i) / float(STRINGS - 1);
        float s = stringSound(i, tl, p);
        sum += s * float2(cos(pan * 1.5707963), sin(pan * 1.5707963));
    }
    return tanh(sum * 0.22);
}

// The distance from point p to the segment from a to b.
float segment(float2 p, float2 a, float2 b) {
    float2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// Where string i lies: its height, and its left (bridge) and right (nut)
// ends. A string's length goes as 1 / pitch, so the low ones are longest.
float3 stringPlace(int i, float cx, float wide) {
    float y = 0.2 + 0.12 * float(i);
    float right = cx + 0.7 * wide;
    float len = 1.4 * wide * 146.83 / stringNote(i);
    return float3(y, right - len, right);
}

// String i's shape at s (0 at the bridge, 1 at the nut) at t: how far it
// is bent, its slope along s, and how hot it is. Harmonic k is a
// standing wave, sin(k pi s), whose swing runs `slow` times slower than
// it sounds.
float4 stringShape(int i, float s, float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(i, t, p, when0, id0, when1, id1);
    float f = loopPitch(stringNote(i));
    float bend = 0.0, slope = 0.0, now = 0.0, start = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Heat rises over 40 ms, not in one frame.
        float warm = smoothstep(0.0, 0.04, since);
        float seen = fract(f * since / p.slow);
        for (int k = 1; k <= HARMONICS; k++) {
            float2 b = burst(i, id, k, p);
            float a = g * b.x * exp(f * since * tripLoss(k, f, p));
            float kp = float(k) * PI;
            float move = sin(TAU * (float(k) * seen + b.y));
            bend += a * sin(kp * s) * move;
            slope += a * kp * cos(kp * s) * move;
            now += a * a * warm;
            if (j == 0) start += b.x * b.x;
        }
    }
    float hot = start > 0.0 ? sqrt(now / start) : 0.0;
    return float4(bend, slope, 0.0, hot);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = loopTime(u.time);
    float aspect = u.resolution.x / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y);
    float px = 1.0 / u.resolution.y;
    float cx = 0.5 * aspect;
    // Narrower than 16:9, the board narrows with the picture.
    float wide = min(aspect / 1.7778, 1.0);

    // A dark ground, warmer toward the middle.
    float heat = 0.04 + 0.04 * exp(-2.0 * length(q - float2(cx, 0.5)));

    // The board: a slanted edge along the bridges, a square one at the nut.
    float3 low = stringPlace(0, cx, wide);
    float3 high = stringPlace(STRINGS - 1, cx, wide);
    float2 a = float2(low.y - 0.06 * wide, low.x - 0.09);
    float2 b = float2(high.y - 0.06 * wide, high.x + 0.09);
    float edge = (q.x - a.x) * (b.y - a.y) - (q.y - a.y) * (b.x - a.x);
    edge /= length(b - a);
    float inside = step(0.0, edge) * step(a.y, q.y) * step(q.y, b.y);
    inside *= step(q.x, low.z + 0.07 * wide);
    float grain = 0.5 + 0.5 * sin(q.y * 310.0 + 3.0 * sin(q.x * 9.0));
    heat = mix(heat, 0.085 + 0.012 * grain, inside);

    // The sound hole, under the low strings, with a ring round it.
    float2 hole = float2(cx + 0.02 * wide, 0.38);
    float r = length(q - hole);
    heat = mix(heat, 0.015, lineAt(r - 0.08, 1.5 * px));
    heat = max(heat, 0.3 * lineAt(abs(r - 0.093) - 0.004, 1.5 * px));

    // The nut, a bar across the right ends.
    float nut = segment(q, float2(low.z, low.x - 0.04),
                        float2(high.z, high.x + 0.04)) - 0.006;
    heat = max(heat, 0.42 * lineAt(nut, 1.5 * px));

    for (int i = 0; i < STRINGS; i++) {
        float3 at = stringPlace(i, cx, wide);
        // The bridge: a pin under each left end, and a tuning peg past the
        // nut.
        float pin = length(q - float2(at.y, at.x)) - 0.009;
        heat = max(heat, 0.5 * lineAt(pin, 1.5 * px));
        float peg = length(q - float2(at.z + 0.035 * wide, at.x)) - 0.011;
        heat = max(heat, 0.36 * lineAt(peg, 1.5 * px));

        if (abs(q.y - at.x) > 0.11) continue;
        if (q.x < at.y - 0.05 || q.x > at.z + 0.05) continue;
        float len = at.z - at.y;
        float s = clamp((q.x - at.y) / len, 0.0, 1.0);
        float4 shape = stringShape(i, s, t, p);
        // The swing is drawn smaller for a shorter string.
        float size = 0.04 * sqrt(len / (1.4 * wide));
        float y = at.x + size * shape.x;
        float tilt = size * shape.y / len;
        float d = abs(q.y - y) / sqrt(1.0 + tilt * tilt);
        // Past an end, the distance is to that end.
        float past = q.x - clamp(q.x, at.y, at.z);
        d = sqrt(d * d + past * past);
        float thick = 0.0028 - 0.0003 * float(i);
        float hot = min(1.5 * shape.w, 1.0);

        // A glow as hot as the string rings, then the string itself.
        heat += 0.22 * hot * exp(-max(d - thick, 0.0) / 0.01);
        float lit = 0.34 + 0.66 * hot;
        heat = mix(heat, lit, lineAt(d - thick, 1.5 * px));
    }
    return float4(kiln(heat), 1.0);
}

// What you hear is strings(): the same plucks the picture draws.
float2 sound(float t, constant Params& p) {
    return strings(t, p) * p.volume;
}
31 lines from stage 3 that are gone
constant float NOTE = 220.0;
⋯
constant float EVERY = 2.0;
constant float FIRST = 1.5;
⋯
void lastPlucks(float t, thread float& when0, thread int& id0,
⋯
    int now = int(floor((t - FIRST) / EVERY));
    id0 = now;
    id1 = now - 1;
    when0 = FIRST + EVERY * float(now);
    when1 = when0 - EVERY;
    if (id0 < 0) id0 = -1;
    if (id1 < 0) id1 = -1;
⋯
float2 burst(int id, int k, constant Params& p) {
    uint seed = uint(id) * 7919u + uint(k) * 31u;
⋯
    float g = rise(since);
⋯
float stringSound(float t, constant Params& p) {
⋯
    lastPlucks(t, when0, id0, when1, id1);
    float f = loopPitch(NOTE);
⋯
            float2 b = burst(id, k, p);
⋯
float4 stringShape(float s, float t, constant Params& p) {
⋯
    lastPlucks(t, when0, id0, when1, id1);
    float f = loopPitch(NOTE);
⋯
            float2 b = burst(id, k, p);
⋯
    float t = u.time;
⋯
    float3 at = float3(0.5, cx - 0.7 * wide, cx + 0.7 * wide);
    for (int e = 0; e < 2; e++) {
        float pin = length(q - float2(e == 0 ? at.y : at.z, at.x)) - 0.012;
⋯
    }
⋯
    float4 shape = stringShape(s, t, p);
    float size = 0.06;
⋯
    float thick = 0.003;
⋯
    return float2(tanh(stringSound(t, p) * 0.4)) * p.volume;

Stage 5 · Plucked Strings

A real string is plucked at one point, and pluck says where: the fraction of the way along from the bridge, 0.2 by default. A plucked string can't start with a harmonic that has a still point where it was pulled, so burst scales harmonic k by sin(k π · pluck), and all by 1.41 to keep the loudness. At 0.2, sin(k π / 5) is zero for every fifth harmonic, so the 5th, 10th, 15th and 20th are missing: in the sound right after the first pluck they measure 45 dB or more below the loudest. A spark marks the pluck point on each string's line of rest, cooling as the string does.

Around each string is a faint haze, about 1.5 times its swing (as a root mean square) above and below its line of rest: roughly where the eye would see a blur. The swing that draws it is slowed down 48 times, and still not slow enough for all of it. A harmonic whose picture swings more than 30 times a second, half of 60 frames a second, jumps further between two frames than a frame can show: on the D3 string that is every harmonic from the 10th up, on D4 from the 5th. They carry much of a fresh pluck's bend and the faster ones die soonest, so for the first part of a second after a pluck the string jumps between jagged shapes from frame to frame. Measured at 720 rows, D3's line moves 13 pixels between two frames on average a tenth of a second after its first pluck, a quarter of its whole swing, and 9 pixels at 0.6 s. As the high harmonics die away it settles into a slow, smooth swing: the fundamentals swing 3.1 (D3) to 6.2 (D4) times a second.

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 = loopTime(u.time);
    float aspect = u.resolution.x / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y);
    float px = 1.0 / u.resolution.y;
    float cx = 0.5 * aspect;
    // Narrower than 16:9, the board narrows with the picture.
    float wide = min(aspect / 1.7778, 1.0);

    // A dark ground, warmer toward the middle.
    float heat = 0.04 + 0.04 * exp(-2.0 * length(q - float2(cx, 0.5)));

    // The board: a slanted edge along the bridges, a square one at the nut.
    float3 low = stringPlace(0, cx, wide);
    float3 high = stringPlace(STRINGS - 1, cx, wide);
    float2 a = float2(low.y - 0.06 * wide, low.x - 0.09);
    float2 b = float2(high.y - 0.06 * wide, high.x + 0.09);
    float edge = (q.x - a.x) * (b.y - a.y) - (q.y - a.y) * (b.x - a.x);
    edge /= length(b - a);
    float inside = step(0.0, edge) * step(a.y, q.y) * step(q.y, b.y);
    inside *= step(q.x, low.z + 0.07 * wide);
    float grain = 0.5 + 0.5 * sin(q.y * 310.0 + 3.0 * sin(q.x * 9.0));
    heat = mix(heat, 0.085 + 0.012 * grain, inside);

    // The sound hole, under the low strings, with a ring round it.
    float2 hole = float2(cx + 0.02 * wide, 0.38);
    float r = length(q - hole);
    heat = mix(heat, 0.015, lineAt(r - 0.08, 1.5 * px));
    heat = max(heat, 0.3 * lineAt(abs(r - 0.093) - 0.004, 1.5 * px));

    // The nut, a bar across the right ends.
    float nut = segment(q, float2(low.z, low.x - 0.04),
                        float2(high.z, high.x + 0.04)) - 0.006;
    heat = max(heat, 0.42 * lineAt(nut, 1.5 * px));

    for (int i = 0; i < STRINGS; i++) {
        float3 at = stringPlace(i, cx, wide);
        // The bridge: a pin under each left end, and a tuning peg past the
        // nut.
        float pin = length(q - float2(at.y, at.x)) - 0.009;
        heat = max(heat, 0.5 * lineAt(pin, 1.5 * px));
        float peg = length(q - float2(at.z + 0.035 * wide, at.x)) - 0.011;
        heat = max(heat, 0.36 * lineAt(peg, 1.5 * px));

        if (abs(q.y - at.x) > 0.11) continue;
        if (q.x < at.y - 0.05 || q.x > at.z + 0.05) continue;
        float len = at.z - at.y;
        float s = clamp((q.x - at.y) / len, 0.0, 1.0);
        float4 shape = stringShape(i, s, t, p);
        // The swing is drawn smaller for a shorter string.
        float size = 0.04 * sqrt(len / (1.4 * wide));
        float y = at.x + size * shape.x;
        float tilt = size * shape.y / len;
        float d = abs(q.y - y) / sqrt(1.0 + tilt * tilt);
        // Past an end, the distance is to that end.
        float past = q.x - clamp(q.x, at.y, at.z);
        d = sqrt(d * d + past * past);
        float thick = 0.0028 - 0.0003 * float(i);
        float hot = min(1.5 * shape.w, 1.0);

        // The blur the eye would see: a haze about as wide as its swing.
        float spread = 1.5 * size * shape.z + 2.0 * px;
        float off = (q.y - at.x) / spread;
        heat += 0.08 * hot * exp(-off * off) * lineAt(abs(past), 0.01);

        // A glow as hot as the string rings, then the string itself.
        heat += 0.22 * hot * exp(-max(d - thick, 0.0) / 0.01);
        float lit = 0.34 + 0.66 * hot;
        heat = mix(heat, lit, lineAt(d - thick, 1.5 * px));

        // Where it is plucked, a spark that cools as the string does.
        float2 mark = float2(at.y + p.pluck * len, at.x);
        float spark = lineAt(length(q - mark) - 0.007, 1.5 * px);
        heat = max(heat, spark * (0.3 + 0.7 * hot));
    }
    return float4(kiln(heat), 1.0);
}
plucked-strings.metal, the whole file10 new lines since stage 4
// Ray Kiln · Plucked Strings
//
// @episode Plucked Strings
// @length 60
// @variation 30
// @variations 1,4,5,6,7,8,10,12
// @sweeps tempo, pluck, damping
// @still 21.43
// @teaches Karplus-Strong synthesis, strings drawn as they vibrate
// @category Fragment
// @tags Karplus-Strong, plucked string, harmonics, standing wave, delay line, exponential decay, procedural sound
// @final Plucked Strings | Each string is plucked at one point along it, which leaves some harmonics out, and the blur of its swing shows around it.
//
// Six strings on a board, plucked in a tune. Karplus-Strong makes a string from a loop of samples: fill it with
// noise, and on every trip round, average each sample with its neighbor. The noise repeats once a trip, so it is a
// sum of harmonics of one pitch, and the averaging takes a little more from each harmonic the higher it is, so a
// pluck starts as a bright buzz and mellows into a tone. A shader's sound has no memory to keep a loop in, so this
// one adds up those harmonics directly, each dying at the rate the loop would give it. The picture draws each
// string from the same harmonics, as the standing waves they are between the two fixed ends, slowed down to be seen.
// 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 tempo 90 60 160 Beats a minute; the tune moves in eighths
// @param damping 0.2 0 1 Loss on each trip round the loop besides the averaging: 0 is plain Karplus-Strong
// @param pluck 0.2 0.05 0.5 Where along each string it is plucked, from the bridge: 0.5 is the middle
// @param slow 48 16 256 How many times slower the picture swings than the sound
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.1415927;

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

uint hashBits(uint x) {
    x ^= x >> 16;
    x *= 0x7feb352du;
    x ^= x >> 15;
    x *= 0x846ca68bu;
    x ^= x >> 16;
    return x;
}

// A whole number in, a number from 0 to 1 out.
float noiseOf(uint x) {
    return float(hashBits(x) & 0xffffu) / 65535.0;
}

// The sound runs at 48,000 samples a second, the rate of the loop.
constant float RATE = 48000.0;
// The lowest 24 harmonics of the noise are kept; the ones above them
// die within a fraction of a second.
constant int HARMONICS = 24;

// A loop is a whole number of samples, N, and the averaging delays the
// sound by half of one more, so a string plays RATE / (N + 0.5): close to
// the note asked for, never quite on it. D3 plays 147.01 Hz.
float loopPitch(float hz) {
    float n = floor(RATE / hz - 0.5);
    return RATE / (n + 0.5);
}

// How much of harmonic k is left after one trip round the loop, as a
// logarithm. Averaging two neighbors keeps cos(pi k f / RATE) of it;
// `damping` takes a little more off every harmonic alike.
float tripLoss(int k, float f, constant Params& p) {
    float keep = cos(PI * float(k) * f / RATE);
    float extra = 1.0 - 0.008 * p.damping;
    return log(max(keep, 0.000001)) + log(extra);
}

// A pluck rises over 3 ms, so it starts without a click.
float rise(float since) {
    return smoothstep(0.0, 0.003, since);
}

// Six strings in D minor pentatonic, D3 to D4, low to high.
constant int STRINGS = 6;
float stringNote(int i) {
    const float hz[6] = {146.83, 174.61, 196.00, 220.00, 261.63, 293.66};
    return hz[clamp(i, 0, 5)];
}

// The tune: which string each eighth plucks, -1 for a rest, four bars.
constant int TUNE[32] = {0, 3, 4, 5, 4, 3, -1, 2,
                         1, 3, 5, 4, -1, 3, 2, 3,
                         0, 2, 4, 5, 3, 4, -1, 5,
                         1, 4, 3, 2, -1, 3, 1, -1};

// The piece is a minute long: plucks stop at 56 s, a hand lays across
// the strings from 56.5 s, and at 59.5 s all is still for the next round.
constant float LOOP = 60.0;
constant float LAST = 56.0;
float handOff(float t) {
    return 1.0 - smoothstep(56.5, 59.5, t);
}

// Time within the minute.
float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// A pluck is forgotten over its 12th to 16th second.
constant float MEMORY = 16.0;
float kept(float since) {
    return 1.0 - smoothstep(12.0, MEMORY, since);
}

// The last two eighths that plucked string i before t: when, and which
// eighth (-1 when there is none).
void lastPlucks(int i, float t, constant Params& p,
                thread float& when0, thread int& id0,
                thread float& when1, thread int& id1) {
    float len = 30.0 / p.tempo;
    int now = int(floor(t / len));
    id0 = -1;
    id1 = -1;
    when0 = 0.0;
    when1 = 0.0;
    for (int back = 0; back < 96; back++) {
        int e = now - back;
        if (e < 0) break;
        float at = float(e) * len;
        if (t - at > MEMORY) break;
        if (at >= LAST || TUNE[e % 32] != i) continue;
        if (id0 < 0) {
            id0 = e;
            when0 = at;
        } else {
            id1 = e;
            when1 = at;
            break;
        }
    }
}

// The noise that fills the loop, seen as harmonics: harmonic k of the
// pluck numbered `id` on string i starts at this size, at this phase.
float2 burst(int i, int id, int k, constant Params& p) {
    uint seed = uint(id) * 7919u + uint(i) * 104729u + uint(k) * 31u;
    float size = (0.35 + 0.65 * noiseOf(seed)) / 3.0;
    // Plucked at `pluck` along it, a string can't start with a harmonic
    // that has a still point there: each is scaled by sin(k pi pluck),
    // and all by 1.41 to keep the loudness.
    size *= sin(float(k) * PI * p.pluck) * 1.41;
    return float2(size, noiseOf(seed + 17u));
}

// How much one pluck still sounds: its rise, the hand at the end, and a
// newer pluck on the same string stopping it within 30 ms.
float pluckGain(float since, float t, float newer, bool stopped) {
    float g = rise(since) * kept(since) * handOff(t);
    if (stopped) g *= 1.0 - smoothstep(0.0, 0.03, t - newer);
    return g;
}

// String i at t: each of its last two plucks, harmonic by harmonic, each
// harmonic falling by tripLoss on each of the f trips a second.
float stringSound(int i, float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(i, t, p, when0, id0, when1, id1);
    float f = loopPitch(stringNote(i));
    float sum = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Whole cycles dropped first, so the phase stays precise.
        float cycles = fract(f * since);
        for (int k = 1; k <= HARMONICS; k++) {
            if (float(k) * f >= 0.5 * RATE) break;
            float2 b = burst(i, id, k, p);
            float left = exp(f * since * tripLoss(k, f, p));
            sum += g * b.x * left * sin(TAU * (float(k) * cycles + b.y));
        }
    }
    return sum;
}

// All six, low strings to the left, high to the right.
float2 strings(float t, constant Params& p) {
    float tl = loopTime(t);
    float2 sum = float2(0.0);
    for (int i = 0; i < STRINGS; i++) {
        float pan = 0.25 + 0.5 * float(i) / float(STRINGS - 1);
        float s = stringSound(i, tl, p);
        sum += s * float2(cos(pan * 1.5707963), sin(pan * 1.5707963));
    }
    return tanh(sum * 0.22);
}

// The distance from point p to the segment from a to b.
float segment(float2 p, float2 a, float2 b) {
    float2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// Where string i lies: its height, and its left (bridge) and right (nut)
// ends. A string's length goes as 1 / pitch, so the low ones are longest.
float3 stringPlace(int i, float cx, float wide) {
    float y = 0.2 + 0.12 * float(i);
    float right = cx + 0.7 * wide;
    float len = 1.4 * wide * 146.83 / stringNote(i);
    return float3(y, right - len, right);
}

// String i's shape at s (0 at the bridge, 1 at the nut) at t: how far it
// is bent, its slope along s, its swing as a root mean square, and how
// hot it is. Harmonic k is a standing wave, sin(k pi s), whose swing runs
// `slow` times slower than it sounds.
float4 stringShape(int i, float s, float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(i, t, p, when0, id0, when1, id1);
    float f = loopPitch(stringNote(i));
    float bend = 0.0, slope = 0.0, swing = 0.0, now = 0.0, start = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Heat rises over 40 ms, not in one frame.
        float warm = smoothstep(0.0, 0.04, since);
        float seen = fract(f * since / p.slow);
        for (int k = 1; k <= HARMONICS; k++) {
            float2 b = burst(i, id, k, p);
            float a = g * b.x * exp(f * since * tripLoss(k, f, p));
            float kp = float(k) * PI;
            float move = sin(TAU * (float(k) * seen + b.y));
            bend += a * sin(kp * s) * move;
            slope += a * kp * cos(kp * s) * move;
            swing += a * a * sin(kp * s) * sin(kp * s) * 0.5;
            now += a * a * warm;
            if (j == 0) start += b.x * b.x;
        }
    }
    float hot = start > 0.0 ? sqrt(now / start) : 0.0;
    return float4(bend, slope, sqrt(swing), hot);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = loopTime(u.time);
    float aspect = u.resolution.x / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y);
    float px = 1.0 / u.resolution.y;
    float cx = 0.5 * aspect;
    // Narrower than 16:9, the board narrows with the picture.
    float wide = min(aspect / 1.7778, 1.0);

    // A dark ground, warmer toward the middle.
    float heat = 0.04 + 0.04 * exp(-2.0 * length(q - float2(cx, 0.5)));

    // The board: a slanted edge along the bridges, a square one at the nut.
    float3 low = stringPlace(0, cx, wide);
    float3 high = stringPlace(STRINGS - 1, cx, wide);
    float2 a = float2(low.y - 0.06 * wide, low.x - 0.09);
    float2 b = float2(high.y - 0.06 * wide, high.x + 0.09);
    float edge = (q.x - a.x) * (b.y - a.y) - (q.y - a.y) * (b.x - a.x);
    edge /= length(b - a);
    float inside = step(0.0, edge) * step(a.y, q.y) * step(q.y, b.y);
    inside *= step(q.x, low.z + 0.07 * wide);
    float grain = 0.5 + 0.5 * sin(q.y * 310.0 + 3.0 * sin(q.x * 9.0));
    heat = mix(heat, 0.085 + 0.012 * grain, inside);

    // The sound hole, under the low strings, with a ring round it.
    float2 hole = float2(cx + 0.02 * wide, 0.38);
    float r = length(q - hole);
    heat = mix(heat, 0.015, lineAt(r - 0.08, 1.5 * px));
    heat = max(heat, 0.3 * lineAt(abs(r - 0.093) - 0.004, 1.5 * px));

    // The nut, a bar across the right ends.
    float nut = segment(q, float2(low.z, low.x - 0.04),
                        float2(high.z, high.x + 0.04)) - 0.006;
    heat = max(heat, 0.42 * lineAt(nut, 1.5 * px));

    for (int i = 0; i < STRINGS; i++) {
        float3 at = stringPlace(i, cx, wide);
        // The bridge: a pin under each left end, and a tuning peg past the
        // nut.
        float pin = length(q - float2(at.y, at.x)) - 0.009;
        heat = max(heat, 0.5 * lineAt(pin, 1.5 * px));
        float peg = length(q - float2(at.z + 0.035 * wide, at.x)) - 0.011;
        heat = max(heat, 0.36 * lineAt(peg, 1.5 * px));

        if (abs(q.y - at.x) > 0.11) continue;
        if (q.x < at.y - 0.05 || q.x > at.z + 0.05) continue;
        float len = at.z - at.y;
        float s = clamp((q.x - at.y) / len, 0.0, 1.0);
        float4 shape = stringShape(i, s, t, p);
        // The swing is drawn smaller for a shorter string.
        float size = 0.04 * sqrt(len / (1.4 * wide));
        float y = at.x + size * shape.x;
        float tilt = size * shape.y / len;
        float d = abs(q.y - y) / sqrt(1.0 + tilt * tilt);
        // Past an end, the distance is to that end.
        float past = q.x - clamp(q.x, at.y, at.z);
        d = sqrt(d * d + past * past);
        float thick = 0.0028 - 0.0003 * float(i);
        float hot = min(1.5 * shape.w, 1.0);

        // The blur the eye would see: a haze about as wide as its swing.
        float spread = 1.5 * size * shape.z + 2.0 * px;
        float off = (q.y - at.x) / spread;
        heat += 0.08 * hot * exp(-off * off) * lineAt(abs(past), 0.01);

        // A glow as hot as the string rings, then the string itself.
        heat += 0.22 * hot * exp(-max(d - thick, 0.0) / 0.01);
        float lit = 0.34 + 0.66 * hot;
        heat = mix(heat, lit, lineAt(d - thick, 1.5 * px));

        // Where it is plucked, a spark that cools as the string does.
        float2 mark = float2(at.y + p.pluck * len, at.x);
        float spark = lineAt(length(q - mark) - 0.007, 1.5 * px);
        heat = max(heat, spark * (0.3 + 0.7 * hot));
    }
    return float4(kiln(heat), 1.0);
}

// What you hear is strings(): the same plucks the picture draws.
float2 sound(float t, constant Params& p) {
    return strings(t, p) * p.volume;
}
2 lines from stage 4 that are gone
    float bend = 0.0, slope = 0.0, now = 0.0, start = 0.0;
⋯
    return float4(bend, slope, 0.0, hot);

The sound

The sound is the same plucks the picture draws. stringSound takes each string's last two plucks and adds up their 24 harmonics, each a sine at k times the loop's pitch, starting at its size from burst and fading by exp(f · since · tripLoss), times the pluck's gain: its 3 ms rise, the hand at the end, and the 30 ms stop when a newer pluck comes. The whole cycles are dropped from f · since before the sine is taken, so the phase of the high harmonics stays precise many cycles after a pluck.

At the default damping of 0.2, the time constants run from 4.1 s for D3's fundamental, 1.5 s for its 8th harmonic and 0.24 s for its 24th, to 1.9 s, 0.25 s and 0.03 s for D4's. So a low string rings on under the tune while the high ones are short. With damping at 0, plain Karplus-Strong, the fundamentals would ring with time constants of 18 s (D4) to 147 s (D3); here a string is stopped by its next pluck or forgotten after 12 to 16 seconds first.

strings places each string between the ears with an equal-power pan, from a quarter of the way across for D3 to three quarters for D4, and passes the sum through tanh(0.22 · sum), which rounds off the loudest moments, before volume. It starts at exactly 0 (a pluck rises from silence), and the last half second is silent. Over the 60 seconds at the defaults the peak is −6.1 dBFS and the RMS −21.6 dBFS; with volume at 1, −4.2 dBFS and −19.7 dBFS; at the loudest settings tried (damping 0, tempo 160, volume 1), −3.1 dBFS and −16.4 dBFS. slow changes only the picture: the sound with slow at 256 is the same file, sample for sample.

New in Ray Kiln

A spectrogram in the playground. In the playground, turn on Sound, and under the waveform and spectrum a third picture now scrolls: the spectrum over time. The last 6 seconds run across it, the newest at the right, 60 columns a second. Frequency runs up on a log scale from 30 Hz to 16 kHz, the same 256 bins as the spectrum above it, with lines at 100 Hz, 1 kHz and 10 kHz. Each bin's level, from −70 dB to −6 dB, is drawn in the kiln's colors, near-black through hot, ember and gold to white-hot. The levels are not smoothed, so a fast decay fades as fast as it is heard. There is nothing to press: it comes with the scope whenever a shader's sound plays, Pause or Stop sound hides it with the scope and it carries on when the sound does, and Restart or opening another shader empties it. It is in the playground only, not in Run it live on these pages, and free.

The analysis is 2048 samples, about 23 Hz a bin, so a note's harmonics come apart as separate lines from a fundamental of about 150 Hz up. D3, the lowest string here at 147 Hz, sits right at that limit, and its low harmonics still show as separate lines.

Open Plucked Strings in the playground with Sound on. Each pluck lights a stack of horizontal lines at once, its harmonics, evenly spaced in hertz and so closer together toward the top on the log scale, up to the 24th (3.5 kHz for D3, 7.1 kHz for D4) and nothing above. A low string's top lines run together into a band, where the log scale's rows are wider than the gap between them. The top lines go dark first and the lowest last longest. It is plainest with one string: stage 3 plucks A3 alone every two seconds, and there the 24th harmonic's line is dark after about 0.3 s, the 16th's after 0.7 s and the 12th's after 1.1 s, while the 8th and those below are still lit when the next pluck comes. With damping at 1 the middle lines shorten most: the 12th's goes dark after 0.8 s and the 4th's after 1.1 s. In the finished shader, set pluck to 0.5 and each string's stack loses every second line, its even harmonics. With several strings ringing, one string's lines fill another's gaps, so it shows best in the first third of a second after Restart, while the low D sounds alone. slow changes nothing there, since it only slows the picture.

Try this

  • Set pluck to 0.5, the middle: only odd harmonics are left, each symmetric about the middle, so every string's shape is a mirror image of itself about its center, with the spark in the middle. Right after the first pluck, the even harmonics measure more than 95 dB below the loudest.
  • Set pluck to 0.05, near the bridge: sin(k π · 0.05) is small for the low harmonics, so D3's fundamental starts 18 dB under its loudest harmonic (7 dB at the default), and only the 20th is missing instead of every fifth.
  • Set damping to 0 for plain Karplus-Strong, with only the averaging: the strings cool more slowly between plucks. 5.3 s after its first pluck the D3 string still glows orange, where at the default it has cooled to red. The RMS goes up from −21.6 to −19.5 dBFS.
  • Set damping to 1: the fundamentals' time constants drop to 0.84 s (D3) to 0.41 s (D4), and 1.2 s after its pluck the D3 string is nearly still and dull. The RMS falls to −25.2 dBFS.
  • Set slow to 256: every harmonic of every string now swings fewer than 30 times a second on screen, and right after a pluck the D3 string moves about half as far between frames as at 48 (a third as far 0.6 s in). The sound doesn't change.
  • Set tempo to 160 for 253 plucks a minute instead of 142, or to 60 for 95.

Parameters

ParameterDefaultRangeWhat it does
tempo9060 to 160Beats a minute; the tune moves in eighths
damping0.20 to 1Loss on each trip round the loop besides the averaging: 0 is plain Karplus-Strong
pluck0.20.05 to 0.5Where along each string it is plucked, from the bridge: 0.5 is the middle
slow4816 to 256How many times slower the picture swings than the sound
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.

plucked-strings.metal
// Ray Kiln · Plucked Strings
//
// @episode Plucked Strings
// @length 60
// @variation 30
// @variations 1,4,5,6,7,8,10,12
// @sweeps tempo, pluck, damping
// @still 21.43
// @teaches Karplus-Strong synthesis, strings drawn as they vibrate
// @category Fragment
// @tags Karplus-Strong, plucked string, harmonics, standing wave, delay line, exponential decay, procedural sound
// @final Plucked Strings | Each string is plucked at one point along it, which leaves some harmonics out, and the blur of its swing shows around it.
//
// Six strings on a board, plucked in a tune. Karplus-Strong makes a string from a loop of samples: fill it with
// noise, and on every trip round, average each sample with its neighbor. The noise repeats once a trip, so it is a
// sum of harmonics of one pitch, and the averaging takes a little more from each harmonic the higher it is, so a
// pluck starts as a bright buzz and mellows into a tone. A shader's sound has no memory to keep a loop in, so this
// one adds up those harmonics directly, each dying at the rate the loop would give it. The picture draws each
// string from the same harmonics, as the standing waves they are between the two fixed ends, slowed down to be seen.
// 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 tempo 90 60 160 Beats a minute; the tune moves in eighths
// @param damping 0.2 0 1 Loss on each trip round the loop besides the averaging: 0 is plain Karplus-Strong
// @param pluck 0.2 0.05 0.5 Where along each string it is plucked, from the bridge: 0.5 is the middle
// @param slow 48 16 256 How many times slower the picture swings than the sound
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.1415927;

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

uint hashBits(uint x) {
    x ^= x >> 16;
    x *= 0x7feb352du;
    x ^= x >> 15;
    x *= 0x846ca68bu;
    x ^= x >> 16;
    return x;
}

// A whole number in, a number from 0 to 1 out.
float noiseOf(uint x) {
    return float(hashBits(x) & 0xffffu) / 65535.0;
}

// The sound runs at 48,000 samples a second, the rate of the loop.
constant float RATE = 48000.0;
// The lowest 24 harmonics of the noise are kept; the ones above them
// die within a fraction of a second.
constant int HARMONICS = 24;

// A loop is a whole number of samples, N, and the averaging delays the
// sound by half of one more, so a string plays RATE / (N + 0.5): close to
// the note asked for, never quite on it. D3 plays 147.01 Hz.
float loopPitch(float hz) {
    float n = floor(RATE / hz - 0.5);
    return RATE / (n + 0.5);
}

// How much of harmonic k is left after one trip round the loop, as a
// logarithm. Averaging two neighbors keeps cos(pi k f / RATE) of it;
// `damping` takes a little more off every harmonic alike.
float tripLoss(int k, float f, constant Params& p) {
    float keep = cos(PI * float(k) * f / RATE);
    float extra = 1.0 - 0.008 * p.damping;
    return log(max(keep, 0.000001)) + log(extra);
}

// A pluck rises over 3 ms, so it starts without a click.
float rise(float since) {
    return smoothstep(0.0, 0.003, since);
}

// Six strings in D minor pentatonic, D3 to D4, low to high.
constant int STRINGS = 6;
float stringNote(int i) {
    const float hz[6] = {146.83, 174.61, 196.00, 220.00, 261.63, 293.66};
    return hz[clamp(i, 0, 5)];
}

// The tune: which string each eighth plucks, -1 for a rest, four bars.
constant int TUNE[32] = {0, 3, 4, 5, 4, 3, -1, 2,
                         1, 3, 5, 4, -1, 3, 2, 3,
                         0, 2, 4, 5, 3, 4, -1, 5,
                         1, 4, 3, 2, -1, 3, 1, -1};

// The piece is a minute long: plucks stop at 56 s, a hand lays across
// the strings from 56.5 s, and at 59.5 s all is still for the next round.
constant float LOOP = 60.0;
constant float LAST = 56.0;
float handOff(float t) {
    return 1.0 - smoothstep(56.5, 59.5, t);
}

// Time within the minute.
float loopTime(float t) {
    return t - LOOP * floor(t / LOOP);
}

// A pluck is forgotten over its 12th to 16th second.
constant float MEMORY = 16.0;
float kept(float since) {
    return 1.0 - smoothstep(12.0, MEMORY, since);
}

// The last two eighths that plucked string i before t: when, and which
// eighth (-1 when there is none).
void lastPlucks(int i, float t, constant Params& p,
                thread float& when0, thread int& id0,
                thread float& when1, thread int& id1) {
    float len = 30.0 / p.tempo;
    int now = int(floor(t / len));
    id0 = -1;
    id1 = -1;
    when0 = 0.0;
    when1 = 0.0;
    for (int back = 0; back < 96; back++) {
        int e = now - back;
        if (e < 0) break;
        float at = float(e) * len;
        if (t - at > MEMORY) break;
        if (at >= LAST || TUNE[e % 32] != i) continue;
        if (id0 < 0) {
            id0 = e;
            when0 = at;
        } else {
            id1 = e;
            when1 = at;
            break;
        }
    }
}

// The noise that fills the loop, seen as harmonics: harmonic k of the
// pluck numbered `id` on string i starts at this size, at this phase.
float2 burst(int i, int id, int k, constant Params& p) {
    uint seed = uint(id) * 7919u + uint(i) * 104729u + uint(k) * 31u;
    float size = (0.35 + 0.65 * noiseOf(seed)) / 3.0;
    // Plucked at `pluck` along it, a string can't start with a harmonic
    // that has a still point there: each is scaled by sin(k pi pluck),
    // and all by 1.41 to keep the loudness.
    size *= sin(float(k) * PI * p.pluck) * 1.41;
    return float2(size, noiseOf(seed + 17u));
}

// How much one pluck still sounds: its rise, the hand at the end, and a
// newer pluck on the same string stopping it within 30 ms.
float pluckGain(float since, float t, float newer, bool stopped) {
    float g = rise(since) * kept(since) * handOff(t);
    if (stopped) g *= 1.0 - smoothstep(0.0, 0.03, t - newer);
    return g;
}

// String i at t: each of its last two plucks, harmonic by harmonic, each
// harmonic falling by tripLoss on each of the f trips a second.
float stringSound(int i, float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(i, t, p, when0, id0, when1, id1);
    float f = loopPitch(stringNote(i));
    float sum = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Whole cycles dropped first, so the phase stays precise.
        float cycles = fract(f * since);
        for (int k = 1; k <= HARMONICS; k++) {
            if (float(k) * f >= 0.5 * RATE) break;
            float2 b = burst(i, id, k, p);
            float left = exp(f * since * tripLoss(k, f, p));
            sum += g * b.x * left * sin(TAU * (float(k) * cycles + b.y));
        }
    }
    return sum;
}

// All six, low strings to the left, high to the right.
float2 strings(float t, constant Params& p) {
    float tl = loopTime(t);
    float2 sum = float2(0.0);
    for (int i = 0; i < STRINGS; i++) {
        float pan = 0.25 + 0.5 * float(i) / float(STRINGS - 1);
        float s = stringSound(i, tl, p);
        sum += s * float2(cos(pan * 1.5707963), sin(pan * 1.5707963));
    }
    return tanh(sum * 0.22);
}

// The distance from point p to the segment from a to b.
float segment(float2 p, float2 a, float2 b) {
    float2 pa = p - a, ba = b - a;
    return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
}

// 1 on a shape d away, fading out over w.
float lineAt(float d, float w) {
    return 1.0 - smoothstep(0.0, w, d);
}

// Where string i lies: its height, and its left (bridge) and right (nut)
// ends. A string's length goes as 1 / pitch, so the low ones are longest.
float3 stringPlace(int i, float cx, float wide) {
    float y = 0.2 + 0.12 * float(i);
    float right = cx + 0.7 * wide;
    float len = 1.4 * wide * 146.83 / stringNote(i);
    return float3(y, right - len, right);
}

// String i's shape at s (0 at the bridge, 1 at the nut) at t: how far it
// is bent, its slope along s, its swing as a root mean square, and how
// hot it is. Harmonic k is a standing wave, sin(k pi s), whose swing runs
// `slow` times slower than it sounds.
float4 stringShape(int i, float s, float t, constant Params& p) {
    float when0, when1;
    int id0, id1;
    lastPlucks(i, t, p, when0, id0, when1, id1);
    float f = loopPitch(stringNote(i));
    float bend = 0.0, slope = 0.0, swing = 0.0, now = 0.0, start = 0.0;
    for (int j = 0; j < 2; j++) {
        int id = j == 0 ? id0 : id1;
        if (id < 0) continue;
        float since = t - (j == 0 ? when0 : when1);
        float g = pluckGain(since, t, when0, j == 1);
        if (g <= 0.0) continue;
        // Heat rises over 40 ms, not in one frame.
        float warm = smoothstep(0.0, 0.04, since);
        float seen = fract(f * since / p.slow);
        for (int k = 1; k <= HARMONICS; k++) {
            float2 b = burst(i, id, k, p);
            float a = g * b.x * exp(f * since * tripLoss(k, f, p));
            float kp = float(k) * PI;
            float move = sin(TAU * (float(k) * seen + b.y));
            bend += a * sin(kp * s) * move;
            slope += a * kp * cos(kp * s) * move;
            swing += a * a * sin(kp * s) * sin(kp * s) * 0.5;
            now += a * a * warm;
            if (j == 0) start += b.x * b.x;
        }
    }
    float hot = start > 0.0 ? sqrt(now / start) : 0.0;
    return float4(bend, slope, sqrt(swing), hot);
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float t = loopTime(u.time);
    float aspect = u.resolution.x / u.resolution.y;
    float2 q = float2(uv.x * aspect, uv.y);
    float px = 1.0 / u.resolution.y;
    float cx = 0.5 * aspect;
    // Narrower than 16:9, the board narrows with the picture.
    float wide = min(aspect / 1.7778, 1.0);

    // A dark ground, warmer toward the middle.
    float heat = 0.04 + 0.04 * exp(-2.0 * length(q - float2(cx, 0.5)));

    // The board: a slanted edge along the bridges, a square one at the nut.
    float3 low = stringPlace(0, cx, wide);
    float3 high = stringPlace(STRINGS - 1, cx, wide);
    float2 a = float2(low.y - 0.06 * wide, low.x - 0.09);
    float2 b = float2(high.y - 0.06 * wide, high.x + 0.09);
    float edge = (q.x - a.x) * (b.y - a.y) - (q.y - a.y) * (b.x - a.x);
    edge /= length(b - a);
    float inside = step(0.0, edge) * step(a.y, q.y) * step(q.y, b.y);
    inside *= step(q.x, low.z + 0.07 * wide);
    float grain = 0.5 + 0.5 * sin(q.y * 310.0 + 3.0 * sin(q.x * 9.0));
    heat = mix(heat, 0.085 + 0.012 * grain, inside);

    // The sound hole, under the low strings, with a ring round it.
    float2 hole = float2(cx + 0.02 * wide, 0.38);
    float r = length(q - hole);
    heat = mix(heat, 0.015, lineAt(r - 0.08, 1.5 * px));
    heat = max(heat, 0.3 * lineAt(abs(r - 0.093) - 0.004, 1.5 * px));

    // The nut, a bar across the right ends.
    float nut = segment(q, float2(low.z, low.x - 0.04),
                        float2(high.z, high.x + 0.04)) - 0.006;
    heat = max(heat, 0.42 * lineAt(nut, 1.5 * px));

    for (int i = 0; i < STRINGS; i++) {
        float3 at = stringPlace(i, cx, wide);
        // The bridge: a pin under each left end, and a tuning peg past the
        // nut.
        float pin = length(q - float2(at.y, at.x)) - 0.009;
        heat = max(heat, 0.5 * lineAt(pin, 1.5 * px));
        float peg = length(q - float2(at.z + 0.035 * wide, at.x)) - 0.011;
        heat = max(heat, 0.36 * lineAt(peg, 1.5 * px));

        if (abs(q.y - at.x) > 0.11) continue;
        if (q.x < at.y - 0.05 || q.x > at.z + 0.05) continue;
        float len = at.z - at.y;
        float s = clamp((q.x - at.y) / len, 0.0, 1.0);
        float4 shape = stringShape(i, s, t, p);
        // The swing is drawn smaller for a shorter string.
        float size = 0.04 * sqrt(len / (1.4 * wide));
        float y = at.x + size * shape.x;
        float tilt = size * shape.y / len;
        float d = abs(q.y - y) / sqrt(1.0 + tilt * tilt);
        // Past an end, the distance is to that end.
        float past = q.x - clamp(q.x, at.y, at.z);
        d = sqrt(d * d + past * past);
        float thick = 0.0028 - 0.0003 * float(i);
        float hot = min(1.5 * shape.w, 1.0);

        // The blur the eye would see: a haze about as wide as its swing.
        float spread = 1.5 * size * shape.z + 2.0 * px;
        float off = (q.y - at.x) / spread;
        heat += 0.08 * hot * exp(-off * off) * lineAt(abs(past), 0.01);

        // A glow as hot as the string rings, then the string itself.
        heat += 0.22 * hot * exp(-max(d - thick, 0.0) / 0.01);
        float lit = 0.34 + 0.66 * hot;
        heat = mix(heat, lit, lineAt(d - thick, 1.5 * px));

        // Where it is plucked, a spark that cools as the string does.
        float2 mark = float2(at.y + p.pluck * len, at.x);
        float spark = lineAt(length(q - mark) - 0.007, 1.5 * px);
        heat = max(heat, spark * (0.3 + 0.7 * hot));
    }
    return float4(kiln(heat), 1.0);
}

// What you hear is strings(): the same plucks the picture draws.
float2 sound(float t, constant Params& p) {
    return strings(t, p) * p.volume;
}

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] = [90, 0.2, 0.2, 48, 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.

Built on later

More in Sound & Rhythm