#include <metal_stdlib>
using namespace metal;

struct Uniforms {
    float2 resolution;
    float  time;
    float  timeDelta;
    float2 mouse;
    uint   frame;
    uint   pad;
};

struct Params {
    float turns;
    float tick;
    float size;
    float heat;
    float glow;
    float volume;
};

struct RKVertexOut {
    float4 position [[position]];
    float2 uv;
};

vertex RKVertexOut rk_vertex(uint vid [[vertex_id]]) {
    float2 p = float2((vid << 1) & 2, vid & 2);
    RKVertexOut o;
    o.position = float4(p * 2.0 - 1.0, 0.0, 1.0);
    o.uv = p;
    return o;
}

#line 1 "shader.metal"
// Ray Kiln · Clockwork
//
// @episode Clockwork
// @length 60
// @variation 30
// @variations 1,2,4,5,6,9,11,12
// @sweeps size, heat, glow
// @still 21.3
// @teaches Gears from 2D distance fields, teeth that mesh, ratios that loop
// @category Fragment
// @tags gears, signed distance fields, polar coordinates, gear ratios, seamless loop, procedural sound
// @final Clockwork | The train ticks like an escapement, lit from the kiln below, and a minute later every gear is back where it began.
//
// Six gears in front of the kiln, each one a distance field in polar
// coordinates: a circle whose edge rises into a tooth and falls into a gap as
// the angle goes round. A gear sits beside the gear that drives it, as far
// from it as their two radii added, and turns the other way, slower by the
// ratio of their teeth, with its teeth set half a tooth over so they fall into
// the other's gaps. The big gear turns six times a minute. Each gear's tooth
// count divides six times its 24 teeth, so in sixty seconds every gear turns
// a whole number of times, and the minute loops: the frame at 60 s is the
// first frame again.
// 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 turns 6 1 12 How many times the big gear turns in a minute, in whole turns
// @param tick 0.8 0 1 From smooth turning (0) to the step and settle of an escapement (1)
// @param size 1 0.6 1.6 How big the gears are on screen
// @param heat 0.5 0 1 The metal from cool iron (0) to white-hot brass (1)
// @param glow 0.6 0 1 How brightly the kiln below lights the edges
// @param volume 0.8 0 1 Loudness of the sound

constant float TAU = 6.2831853;
constant float PI = 3.14159265;
// The loop: sixty seconds, two ticks a second.
constant float LOOP = 60.0;
constant float TICKS = 120.0;
// The size of a tooth: a gear's radius is MODULE times half its teeth, so any
// two gears with the same module mesh.
constant float MODULE = 0.04;
// The train: each gear's teeth, the gear that drives it, the direction from
// that gear's center to its own, and its spokes. The first is the driver.
constant int GEARS = 6;
constant float TEETH[6] = {24.0, 36.0, 12.0, 16.0, 48.0, 18.0};
constant int PARENT[6] = {-1, 0, 0, 1, 0, 1};
constant float DIR[6] = {0.0, -0.2, 2.3, 1.6, -1.9, -0.9};
constant float SPOKES[6] = {6.0, 6.0, 0.0, 4.0, 8.0, 3.0};
constant float2 DRIVER = float2(-0.35, 0.05);

// ---- Noise (Flowing Color Field) ------------------------------------------

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

float vnoise(float2 p) {
    float2 i = floor(p), f = fract(p);
    f = f * f * (3.0 - 2.0 * f);
    float a = hash21(i), b = hash21(i + float2(1, 0));
    float c = hash21(i + float2(0, 1)), d = hash21(i + float2(1, 1));
    return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
}

float fbm(float2 p) {
    float v = 0.0, a = 0.5;
    for (int i = 0; i < 4; i++) {
        v += a * vnoise(p);
        p = p * 2.03 + float2(17.1, 9.2);
        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));
}

// ---- A gear ---------------------------------------------------------------
// In polar coordinates round its center, a gear's edge is its radius plus a
// tooth profile: cos(n * a) clamped, so each tooth has a flat top, a flat
// root and straight flanks, one tooth every 1/n of a turn. Its distance is
// the radius minus the edge, divided by how steeply the edge climbs, so the
// flanks are as sharp as the round parts.

float gearEdge(float2 p, float n, float spin) {
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    a -= TAU * floor(a / TAU);
    float c = cos(n * a) * 1.6 - 0.05;
    float tooth = clamp(c, -1.0, 1.0);
    // The tip rises one module above the radius, the root 1.25 below.
    float rise = tooth > 0.0 ? tooth : tooth * 1.25;
    float edge = MODULE * (n * 0.5 + rise);
    // How fast the edge moves per unit of length round the circle, out at
    // the teeth (nearer the axle the flanks are far away anyway).
    float slope = MODULE * 1.6 * n * abs(sin(n * a)) / max(r, edge);
    float climb = abs(c) < 1.0 ? slope : 0.0;
    climb *= tooth > 0.0 ? 1.0 : 1.25;
    return (r - edge) / sqrt(1.0 + climb * climb);
}

// The windows between the spokes: a ring between the hub and the rim, with s
// spokes left standing across it. Positive outside a window.
float gearWindows(float2 p, float n, float s, float spin) {
    if (s < 1.0) return 1.0;
    float R = MODULE * n * 0.5;
    float hub = max(0.07, 0.2 * R), rim = R - 2.8 * MODULE;
    float r = length(p);
    float a = atan2(p.y, p.x) - spin;
    float ring = abs(r - 0.5 * (hub + rim)) - 0.5 * (rim - hub);
    float slice = TAU / s;
    float aa = a - slice * floor(a / slice + 0.5);
    float spoke = abs(r * sin(aa)) - (0.022 + 0.03 * R);
    return max(ring, -spoke);
}

// ---- The train ------------------------------------------------------------
// The driver turns; each other gear turns from its parent. Where they touch,
// in direction dir from the parent, the parent's tooth phase n_p(dir - spin_p)
// and the child's n(dir + pi - spin) always add up to half a tooth, so a tooth
// meets a gap: spin = dir + pi - (pi - n_p(dir - spin_p)) / n. That makes the
// child turn -n_p/n times as fast as its parent: its ratio.
// The angles are kept small: each gear's turns so far as a fraction of a
// turn. A minute in, the driver alone is 37 radians round, and cos(48 * a)
// of that rounds differently from cos of the same angle near 0, enough to
// move a tooth's edge by a pixel and break the loop.

struct Train {
    float2 centre[6];
    float spin[6];
};

Train train(float driven, float zoom) {
    Train g;
    float rest[6];
    float ratio[6];
    g.centre[0] = DRIVER * zoom;
    rest[0] = 0.0;
    ratio[0] = 1.0;
    for (int i = 1; i < GEARS; i++) {
        int j = PARENT[i];
        float n = TEETH[i], np = TEETH[j];
        float dir = DIR[i];
        float reach = MODULE * 0.5 * (n + np) * zoom;
        g.centre[i] = g.centre[j] + reach * float2(cos(dir), sin(dir));
        rest[i] = dir + PI - (PI - np * (dir - rest[j])) / n;
        ratio[i] = -ratio[j] * np / n;
    }
    for (int i = 0; i < GEARS; i++) {
        g.spin[i] = rest[i] + TAU * fract(ratio[i] * driven);
    }
    return g;
}

// How many turns the driver has made at time t (clockwise, so negative): two
// ticks a second, each a step that springs and settles (an escapement), or
// smooth turning with tick 0. At t = 60 the count is 120 ticks exactly, and
// the driver has made `turns` whole turns.
float driverTurns(float t, float turns, float tick) {
    float x = t * TICKS / LOOP;
    float f = fract(x);
    float settle = 1.0 - exp(-f * 22.0) * cos(f * 34.0);
    float ticked = floor(x) + settle;
    return -turns * mix(x, ticked, tick) / TICKS;
}

// The whole train's distance: its nearest gear, and which one it is.
float trainDistance(float2 q, Train g, float zoom, thread int& id) {
    float d = 1e3;
    for (int i = 0; i < GEARS; i++) {
        float2 p = (q - g.centre[i]) / zoom;
        float n = TEETH[i];
        float gd = length(p) - MODULE * (n * 0.5 + 1.0);
        // Only near a gear is its tooth profile worth working out.
        if (gd < 0.05) {
            float s = g.spin[i];
            gd = max(gearEdge(p, n, s), -gearWindows(p, n, SPOKES[i], s));
        }
        gd *= zoom;
        if (gd < d) { d = gd; id = i; }
    }
    return d;
}

float4 shade(float2 uv, constant Uniforms& u, constant Params& p) {
    float px = 2.0 / u.resolution.y;
    float2 q = (uv - 0.5) * u.resolution * px;
    float t = u.time;
    float turns = max(floor(p.turns + 0.5), 1.0);
    float zoom = p.size;

    Train g = train(driverTurns(t, turns, p.tick), zoom);

    int id = 0;
    float d = trainDistance(q, g, zoom, id);
    int shadowId = 0;
    float shadow = trainDistance(q - float2(0.035, -0.05), g, zoom, shadowId);

    // The wall: dark smoke drifting round a circle once a minute, so it loops
    // too, and the kiln's glow rising from below the picture.
    float2 drift = 0.35 * float2(cos(TAU * t / LOOP), sin(TAU * t / LOOP));
    float wall = 0.05 + 0.12 * fbm(q * 1.6 + drift);
    float kilnGlow = exp(-length(q - float2(0.0, -1.5)) * 1.1);
    wall += 0.2 * kilnGlow;
    wall *= 1.0 - 0.55 * (1.0 - smoothstep(-0.02, 0.06, shadow));

    // The metal, brushed in rings round its axle, warmer lower down.
    float2 local = (q - g.centre[id]) / zoom;
    float r = length(local);
    float n = TEETH[id];
    float R = MODULE * n * 0.5;
    float2 radial = local / max(r, 1e-4);
    float brush = vnoise(float2(r * 420.0, float(id) * 13.0));
    // A streak of light through the axle that stays put as it turns.
    float sheen = pow(abs(radial.y), 12.0) * (radial.y < 0.0 ? 0.16 : 0.07);
    float metal = 0.27 + 0.035 * brush + sheen + 0.14 * kilnGlow;
    metal -= 0.05 * local.y / max(R, 0.1);
    metal += (p.heat - 0.5) * 0.4;
    // A bevel round each edge, lit where it faces down to the kiln.
    float outer = gearEdge(local, n, g.spin[id]) * zoom;
    float window = gearWindows(local, n, SPOKES[id], g.spin[id]) * zoom;
    float2 facing = outer > -window ? radial : -radial;
    float bevel = 1.0 - smoothstep(0.0, 0.018, -d);
    float lit = 0.5 + 0.5 * dot(facing, float2(0.0, -1.0));
    metal += bevel * (0.12 + 0.36 * lit * p.glow);
    // The axle cap, and the hot mark that shows each gear's turn.
    float axle = r - 0.035;
    metal = mix(metal, 0.72, 1.0 - smoothstep(-px, px, axle * zoom));
    metal = mix(metal, 0.08, 1.0 - smoothstep(-px, px, (r - 0.012) * zoom));
    float onSpoke = 0.5 * (max(0.07, 0.2 * R) + R - 2.8 * MODULE);
    float reach = SPOKES[id] > 0.0 ? onSpoke : 0.6 * R;
    float2 mark = reach * float2(cos(g.spin[id]), sin(g.spin[id]));
    float rivet = length(local - mark) - 0.022;
    metal = mix(metal, 0.93, 1.0 - smoothstep(-px, px, rivet * zoom));

    float heat = mix(metal, wall, smoothstep(-px, px, d));
    // A thin dark line round every gear, so two that touch still read as two.
    heat *= 0.55 + 0.45 * smoothstep(0.0, 1.5 * px, abs(d));
    return float4(kiln(heat), 1.0);
}

// ---- Sound ----------------------------------------------------------------
// The same clock in time. Two ticks a second, a tick and a tock a little
// lower, each a burst of noise ringing a small metal ping; every time the big
// gear comes round, a bell; under them the low hum of the train turning. Each
// starts from silence at its own moment, and the hum's 55 Hz makes a whole
// number of cycles in a minute, so the sound loops with the picture.

float tickSound(float since, float parity) {
    float attack = 1.0 - exp(-since * 4000.0);
    float sample = floor(since * 48000.0);
    float noise = hash21(float2(sample, parity * 7.1)) * 2.0 - 1.0;
    float click = noise * exp(-since * 700.0);
    float f = parity > 0.5 ? 1850.0 : 2400.0;
    float ping = sin(TAU * f * since) * exp(-since * 55.0);
    return (0.6 * click + ping) * attack;
}

float gearBell(float since) {
    float attack = 1.0 - exp(-since * 900.0);
    float b = sin(TAU * 392.0 * since) * exp(-since * 0.9);
    b += 0.5 * sin(TAU * 392.0 * 2.76 * since) * exp(-since * 2.2);
    b += 0.25 * sin(TAU * 392.0 * 5.40 * since) * exp(-since * 4.0);
    return b * attack;
}

float2 sound(float t, constant Params& p) {
    float turns = max(floor(p.turns + 0.5), 1.0);
    float x = t * TICKS / LOOP;
    float k = floor(x);
    float since = fract(x) * LOOP / TICKS;
    float parity = k - 2.0 * floor(k * 0.5);
    float tk = tickSound(since, parity);
    // The tick sits a little left, the tock a little right.
    float2 side = parity > 0.5 ? float2(0.75, 1.0) : float2(1.0, 0.75);
    float2 ticks = tk * side * 0.4;

    // A bell each turn of the driver: the turn's count, and the one before
    // still ringing under it.
    float turn = t * turns / LOOP;
    float ring = 0.0;
    for (int back = 0; back < 2; back++) {
        float since2 = (fract(turn) + float(back)) * LOOP / turns;
        if (floor(turn) - float(back) >= 0.0) ring += gearBell(since2);
    }
    float2 bells = float2(ring, ring) * 0.2;

    float hum = sin(TAU * 55.0 * t) + 0.35 * sin(TAU * 110.0 * t);
    float2 drone = float2(hum, hum) * 0.075;

    return tanh((ticks + bells + drone) * 1.5) * p.volume;
}

#line 1 "rk_host"
fragment float4 rk_fragment(RKVertexOut in [[stage_in]],
                                constant Uniforms& u [[buffer(0)]],
                                constant Params& p [[buffer(1)]]) {
    return shade(in.uv, u, p);
}

struct SoundUniforms { float start; float rate; uint count; uint pad; };
kernel void rk_sound(device float2* out [[buffer(0)]],
                         constant SoundUniforms& su [[buffer(1)]],
                         constant Params& p [[buffer(2)]],
                         uint i [[thread_position_in_grid]]) {
    if (i >= su.count) return;
    out[i] = clamp(sound(su.start + float(i) / su.rate, p), -1.0, 1.0);
}