The Lights

A strip of 100 colour lights, animated by short programs that AI writes from a plain description. Ask for an idea below, and see what's playing and everything made so far.

Now showing

Preview of Fireplace: each column is one light, time runs downward.

Fireplace

“A fireplace – the flames should undulate loosely in response to the beats”

A cozy fireplace: a bed of glowing embers with flames licking and flickering along the hearth in deep red, orange and gold; the music breathes into the fire, each beat loosely swelling the flames in a lazy wave that rolls along the hearth before settling, with an occasional crackling spark

Ask for a new design

Describe an animation in a sentence or two: colours, mood, movement, and whether it should move to music. Requests are read and made from time to time, so it may not appear right away.

Plain words only, up to 400 characters. No links or code.

All designs

DesignRequestMadeCode
Fireplace showing A fireplace – the flames should undulate loosely in response to the beats
View code
META = {
    "name": "fireplace",
    "audio": True,
    "description": "A cozy fireplace: a bed of glowing embers with flames licking and flickering along the hearth "
                   "in deep red, orange and gold; the music breathes into the fire, each beat loosely swelling "
                   "the flames in a lazy wave that rolls along the hearth before settling, with an occasional "
                   "crackling spark",
}
PARAMS = {
    "response": 1.0,    # how much the beats swell the flames (0 = plain fire)
    "flicker": 1.0,     # fast flame flicker amount
    "embers": 1.0,      # brightness of the ember bed
    "sparks": 1.0,      # crackle sparks
}

# heat 0..1 -> color: black, deep red, red-orange, orange, gold, pale yellow
FIRE = [(0.0, (0, 0, 0)), (0.2, (60, 2, 0)), (0.4, (170, 20, 0)), (0.6, (255, 70, 0)),
        (0.8, (255, 150, 10)), (1.0, (255, 220, 120))]


def setup(sdk):
    np = sdk.np
    rng = np.random.default_rng(4)
    n = sdk.n
    sdk.state.update(
        rng=rng, self_beat=0.0,
        k=rng.uniform(0.08, 0.35, 5), w=rng.uniform(0.4, 1.6, 5) * rng.choice((-1, 1), 5),
        ph=rng.uniform(0, 6.28, 5),
        flick=np.zeros(n), swell=0.0, swell_target=0.0, wave_x=n / 2, wave_dir=1.0,
        sparks=np.zeros(n),
    )
    fx = np.array([p for p, _ in FIRE])
    fc = np.array([c for _, c in FIRE], dtype=float)
    sdk.state.update(fx=fx, fc=fc)


def render(t, dt, n, sdk, params):
    st, a, np, m = sdk.state, sdk.audio, sdk.np, sdk.math
    rng = st["rng"]
    idx = np.arange(n, dtype=float)

    # beat: real music, or a lazy built-in 90 BPM breath in silence
    if a.active and a.level > 0.02:
        beat, onset = a.beat, a.onset
    else:
        st["self_beat"] += dt * 1.5
        beat, onset = st["self_beat"] >= 1, False
        st["self_beat"] %= 1

    # loose response: beats raise a target, the swell drifts toward it, everything relaxes slowly
    if beat:
        st["swell_target"] = min(1.0, st["swell_target"] + 0.45)
        st["wave_x"] = rng.uniform(0, n)                      # the swell starts somewhere new
        st["wave_dir"] = rng.choice((-1.0, 1.0))
    st["swell_target"] *= m.exp(-dt * 1.4)
    st["swell"] += (st["swell_target"] - st["swell"]) * min(1.0, dt * 3.0)
    swell = st["swell"] * params["response"]
    st["wave_x"] += st["wave_dir"] * 18 * dt                  # the swell rolls along the hearth

    # 1) slow licking flames: interfering waves drifting both ways; they move faster when swollen
    st["ph"] += st["w"] * dt * (1 + 1.2 * swell)
    licks = np.sin(np.outer(idx, st["k"]) + st["ph"]).mean(axis=1)         # -1..1
    # 2) fast flicker: smoothed per-pixel noise
    st["flick"] += (rng.normal(0, 1, n) - st["flick"]) * min(1.0, dt * 14)
    flick = np.convolve(st["flick"], np.array([1, 2, 3, 2, 1]) / 9.0, mode="same")   # flickers come in tongues
    # 3) beat swell: a broad hump of extra heat rolling along
    hump = np.exp(-((idx - st["wave_x"]) / (n * 0.3)) ** 2) * swell

    tongues = np.clip(licks * 1.7 + 0.5, 0, 1) ** 1.5          # distinct flames with dark gaps
    heat = (0.17 * params["embers"] + 0.55 * tongues + 0.16 * params["flicker"] * flick
            + 0.3 * hump * (0.4 + tongues))
    # sparks: crackles pop bright gold and fade
    if (onset and rng.random() < 0.3) or rng.random() < 0.6 * dt:
        st["sparks"][rng.integers(n)] = params["sparks"]
    st["sparks"] *= m.exp(-dt * 8)
    heat = np.clip(np.maximum(heat, st["sparks"]), 0, 1)

    # palette lookup per channel
    out = np.stack([np.interp(heat, st["fx"], st["fc"][:, c]) for c in range(3)], axis=1)
    return np.clip(out, 0, 255).astype(np.uint8)
Runway Glitzy, pulsating fashion show lights – not too chaotic
View code
META = {
    "name": "runway",
    "audio": True,
    "description": "Glitzy fashion-show runway: a soft pink and champagne runway glow that pulses with the beat, "
                   "a warm white spotlight that struts down the runway in step with the music, pauses at the end "
                   "to pose under a burst of camera flashes, then walks back; occasional paparazzi flashes and "
                   "gold glitter twinkle on the beats",
}
PARAMS = {
    "pulse": 1.0,       # how strongly the runway glow pulses on the beat
    "flashes": 1.0,     # camera flash amount
    "glitter": 1.0,     # gold glitter amount
    "walk_beats": 16,   # beats to walk the full runway
}

PINK, BLUSH, GOLD = (255, 15, 110), (255, 80, 150), (255, 160, 70)
SPOT, FLASH = (255, 225, 200), (255, 255, 255)


def setup(sdk):
    n = sdk.n
    sdk.state.update(rng=sdk.rand(9), self_beat=0.0, kick=0.0, beats=0,
                     pos=0.0, target=0.0, dir=1, pose=0, flashes=[], glitter=sdk.np.zeros(n))


def render(t, dt, n, sdk, params):
    st, a, np, m = sdk.state, sdk.audio, sdk.np, sdk.math
    rng = st["rng"]
    idx = np.arange(n, dtype=float)

    # beat: real music, or a built-in 118 BPM strut in silence
    if a.active and a.level > 0.02:
        beat = a.beat
    else:
        st["self_beat"] += dt * 118 / 60
        beat = st["self_beat"] >= 1
        st["self_beat"] %= 1

    end = n - 4.0
    if beat:
        st["beats"] += 1
        st["kick"] = 1.0
        # the walk: one step per beat; at the end of the runway, pose for 4 beats, then turn around
        if st["pose"] > 0:
            st["pose"] -= 1
            if st["pose"] == 0:
                st["dir"] = -st["dir"]
        else:
            step = end / max(4, int(params["walk_beats"]))
            st["target"] = min(end, max(3.0, st["target"] + st["dir"] * step))
            if st["target"] in (end, 3.0):
                st["pose"] = 4
                if st["target"] == end:                     # camera flash burst at the pose
                    for _ in range(int(6 * params["flashes"])):
                        st["flashes"].append([rng.uniform(n * 0.55, n - 1), rng.uniform(-0.3, 0.0)])
        # a couple of paparazzi flashes and some gold glitter on each beat
        if rng.random() < 0.5 * params["flashes"]:
            st["flashes"].append([rng.uniform(0, n - 1), 0.0])
        for _ in range(int(3 * params["glitter"])):
            st["glitter"][rng.randrange(n)] = 1.0
    st["kick"] *= m.exp(-dt * 4)

    # the spotlight glides each step like a stride: quick, then settling
    st["pos"] += (st["target"] - st["pos"]) * min(1.0, dt * 6)

    # 1) runway glow: pink in the middle fading to blush at the edges, pulsing on the beat
    edge = np.abs(idx - (n - 1) / 2) / (n / 2)
    base = np.array(PINK, float) * (1 - edge[:, None]) + np.array(BLUSH, float) * edge[:, None]
    shimmer = 0.85 + 0.15 * np.sin(idx * 0.4 - t * 2.0)       # slow sheen rolling down the runway
    out = base * (0.12 + 0.18 * params["pulse"] * st["kick"]) * shimmer[:, None]

    # 2) spotlight with a warm halo
    d = idx - st["pos"]
    out += np.exp(-(d / 2.0) ** 2)[:, None] * np.array(SPOT, float) * 0.85
    out += np.exp(-(d / 7.0) ** 2)[:, None] * np.array(GOLD, float) * 0.18

    # 3) gold glitter: crisp single-pixel twinkles that fade
    st["glitter"] *= m.exp(-dt * 5)
    out += st["glitter"][:, None] * np.array(GOLD, float)

    # 4) camera flashes: very short white pops (staggered starts for the burst)
    keep = []
    for f in st["flashes"]:
        f[1] += dt
        if f[1] > 0.18:
            continue
        keep.append(f)
        if f[1] >= 0:
            v = m.exp(-f[1] * 25)
            out += np.exp(-((idx - f[0]) / 1.2) ** 2)[:, None] * np.array(FLASH, float) * v
    st["flashes"] = keep[-16:]

    return np.clip(out, 0, 255).astype(np.uint8)
Barber Pole A barber pole pattern that shifts with every beat
View code
META = {
    "name": "barber_pole",
    "audio": True,
    "description": "Barber pole stripes (red, white, blue) that hold still and snap forward one stripe on every beat",
}
PARAMS = {
    "stripe": 4,       # stripe width in pixels
    "snap": 0.12,      # seconds the shift takes (0 = instant jump)
}

COLORS = [(255, 0, 0), (150, 150, 150), (0, 40, 255)]   # white toned down so it doesn't wash out


def setup(sdk):
    sdk.state.update(target=0.0, pos=0.0, self_beat=0.0)


def render(t, dt, n, sdk, params):
    st, a, np = sdk.state, sdk.audio, sdk.np
    w = max(1, int(params["stripe"]))

    # beat: real music, or a built-in 120 BPM pulse in silence
    if a.active and a.level > 0.02:
        beat = a.beat
    else:
        st["self_beat"] += dt * 2.0
        beat = st["self_beat"] >= 1
        st["self_beat"] %= 1
    if beat:
        st["target"] += w

    # slide toward the target quickly, then hold
    snap = params["snap"]
    step = w * dt / snap if snap > 0 else 1e9
    st["pos"] = min(st["target"], st["pos"] + step)
    period = w * len(COLORS)
    st["target"] %= period * 1000
    if st["pos"] > st["target"]:
        st["pos"] = st["target"]

    # crisp stripes with one anti-aliased edge pixel while moving
    x = (np.arange(n, dtype=float) - st["pos"]) % period
    k = (x // w).astype(int)
    f = np.clip(x - k * w, 0, 1)[:, None]             # fraction into the stripe's first pixel
    P = np.array(COLORS, dtype=float)
    return np.clip(P[k] * f + P[(k - 1) % len(COLORS)] * (1 - f), 0, 255).astype(np.uint8)
Beat Stars Stars that twinkle with every beat
View code
META = {
    "name": "beat_stars",
    "audio": True,
    "description": "A black sky of faint stars; on every beat a handful of them twinkle bright, flaring and "
                   "shimmering as they fade back down",
}
PARAMS = {
    "stars": 18,        # how many stars in the sky
    "per_beat": 4,      # stars that twinkle on each beat
    "fade": 3.0,        # how fast a twinkle fades (higher = quicker)
    "glow": 0.06,       # resting brightness of the sky's stars (0 = invisible until they twinkle)
}

# star tints: cool blue-white, white, warm white, pale gold
TINTS = [(170, 200, 255), (230, 235, 255), (255, 230, 200), (255, 210, 140)]


def setup(sdk):
    rng = sdk.rand(21)
    sdk.state.update(rng=rng, stars=[], self_beat=0.0)


def _place(st, n, count):
    rng = st["rng"]
    spots = rng.sample(range(n), min(n, count))
    st["stars"] = [{"i": i, "tint": rng.choice(TINTS), "b": 0.0, "ph": rng.random() * 6.28} for i in spots]


def render(t, dt, n, sdk, params):
    st, a, np, m = sdk.state, sdk.audio, sdk.np, sdk.math
    rng = st["rng"]
    if len(st["stars"]) != int(params["stars"]):
        _place(st, n, max(1, int(params["stars"])))

    # beat: real music, or a built-in 120 BPM pulse in silence
    if a.active and a.level > 0.02:
        beat = a.beat
    else:
        st["self_beat"] += dt * 2.0
        beat = st["self_beat"] >= 1
        st["self_beat"] %= 1
    if beat:
        for s in rng.sample(st["stars"], min(len(st["stars"]), int(params["per_beat"]))):
            s["b"] = rng.uniform(0.7, 1.0)

    out = np.zeros((n, 3))
    fade = m.exp(-dt * params["fade"])
    for s in st["stars"]:
        # shimmer while bright: a fast flicker that dies away with the twinkle
        shimmer = 1.0 - 0.35 * s["b"] * (0.5 + 0.5 * m.sin(t * 40 + s["ph"]))
        v = max(params["glow"], s["b"] * shimmer)
        col = np.array(s["tint"], float) * v
        out[s["i"]] += col
        if s["b"] > 0.3:                                   # bright stars bleed a little into neighbours
            for j in (s["i"] - 1, s["i"] + 1):
                if 0 <= j < n:
                    out[j] += col * 0.25 * s["b"]
        s["b"] *= fade
    return np.clip(out, 0, 255).astype(np.uint8)
Beat Runner One light runner that changes direction and speed with the beat, on a black background, changing colours gradually
View code
META = {
    "name": "beat_runner",
    "audio": True,
    "description": "One light runner on pure black: every beat it picks a new random speed and direction, "
                   "bouncing off the ends with a short tail, while its color drifts slowly around the rainbow",
}
PARAMS = {
    "energy": 1.0,        # speed multiplier
    "size": 3,            # runner length in pixels
    "tail": 0.25,         # tail length, seconds
    "color_speed": 0.03,  # rainbow turns per second (0.03 = one full cycle every ~33 s)
}

SPEEDS = (8, 15, 25, 40, 60, 90)   # pixels per second


def setup(sdk):
    sdk.state.update(rng=sdk.rand(3), x=sdk.n / 2, v=25.0, want=25.0, self_beat=0.0,
                     tail=sdk.np.zeros((sdk.n, 3)))


def render(t, dt, n, sdk, params):
    st, a, np, m = sdk.state, sdk.audio, sdk.np, sdk.math
    rng = st["rng"]

    # beat: real music, or a built-in 120 BPM pulse in silence
    if a.active and a.level > 0.02:
        beat = a.beat
    else:
        st["self_beat"] += dt * 2.0
        beat = st["self_beat"] >= 1
        st["self_beat"] %= 1
    if beat:
        direction = -1 if rng.random() < 0.6 else 1                # usually reverse
        st["want"] = direction * (1 if st["v"] >= 0 else -1) * rng.choice(SPEEDS) * params["energy"]

    # quick ease into the new velocity (snappy but not a teleport), bounce off the ends
    st["v"] += (st["want"] - st["v"]) * min(1.0, dt * 12)
    size = max(1.0, float(params["size"]))
    st["x"] += st["v"] * dt
    if st["x"] < 0:
        st["x"], st["v"], st["want"] = 0.0, abs(st["v"]), abs(st["want"])
    elif st["x"] > n - size:
        st["x"], st["v"], st["want"] = n - size, -abs(st["v"]), -abs(st["want"])

    # crisp runner: exact pixel coverage so it moves smoothly without blur
    idx = np.arange(n, dtype=float)
    cover = np.clip(np.minimum(idx + 1, st["x"] + size) - np.maximum(idx, st["x"]), 0, 1)
    color = np.array(sdk.hsv(t * params["color_speed"]), dtype=float)
    head = cover[:, None] * color
    st["tail"] = np.maximum(st["tail"] * m.exp(-dt / max(0.02, params["tail"])), head * 0.5)
    return np.clip(np.maximum(st["tail"], head), 0, 255).astype(np.uint8)
Psychedelia Distinct sliding segments of light on a dark background, like bricks, with light tracers
View code
META = {
    "name": "psychedelia",
    "audio": True,
    "description": "Neon bricks on black: solid hard-edged blocks of color slide back and forth and knock into each "
                   "other; every beat kicks each brick to a new random speed and direction and makes it flare; "
                   "thin light tracers zip across with short crisp tails; every few bars the bricks switch to a "
                   "new color scheme",
}
PARAMS = {
    "energy": 1.0,      # overall motion speed multiplier
    "bricks": 5,        # number of sliding bricks
    "tracers": 1.0,     # how many tracers launch per beat
    "tail": 0.12,       # tracer tail length, seconds (short = crisp)
    "bars": 4,          # bars between color-scheme changes
}

SCHEMES = [
    [(255, 0, 140), (120, 0, 255), (0, 200, 255), (255, 120, 0)],      # neon rave
    [(255, 40, 0), (255, 170, 0), (255, 0, 90), (200, 0, 255)],        # lava
    [(0, 255, 120), (0, 110, 255), (170, 0, 255), (0, 255, 255)],      # aurora
    [(255, 0, 255), (0, 255, 60), (255, 230, 0), (0, 80, 255)],        # acid
    [(255, 60, 140), (255, 180, 60), (80, 200, 255), (180, 90, 255)],  # candy
    [(255, 0, 0), (0, 40, 255), (255, 0, 200), (0, 200, 255)],         # police disco
]
TRACER = (255, 255, 255)


def setup(sdk):
    sdk.state.update(rng=sdk.rand(11), bricks=[], scheme=0, beats=0, self_beat=0.0,
                     tracers=[], tail=sdk.np.zeros((sdk.n, 3)))


def _make_bricks(st, n, count, energy):
    rng = st["rng"]
    slot = n / count
    st["bricks"] = [{"x": k * slot + rng.uniform(0, slot * 0.3), "len": rng.randint(5, 11),
                     "v": rng.choice((-1, 1)) * rng.uniform(5, 20) * energy, "want": 0.0,
                     "c": k % 4, "flare": 0.0} for k in range(count)]
    for b in st["bricks"]:
        b["want"] = b["v"]


def _cover(np, idx, lo, hi):
    """Per-pixel coverage of the span [lo, hi): crisp edges that still move smoothly."""
    return np.clip(np.minimum(idx + 1, hi) - np.maximum(idx, lo), 0, 1)


def render(t, dt, n, sdk, params):
    st, a, np, m = sdk.state, sdk.audio, sdk.np, sdk.math
    rng = st["rng"]
    energy = max(0.1, params["energy"])
    count = max(1, min(12, int(params["bricks"])))
    if len(st["bricks"]) != count:
        _make_bricks(st, n, count, energy)
    live = a.active and a.level > 0.02

    # --- pulse: real beats, or a built-in 124 BPM groove in silence -----------------------------
    if live:
        beat = a.beat
    else:
        st["self_beat"] += dt * 124 / 60
        beat = st["self_beat"] >= 1
        st["self_beat"] %= 1

    if beat:
        st["beats"] += 1
        for b in st["bricks"]:
            b["want"] = rng.choice((4, 10, 18, 30, 50)) * energy * rng.choice((-1, 1))
            b["flare"] = 1.0
        for _ in range(int(round(params["tracers"] * rng.choice((1, 1, 2))))):
            d = rng.choice((-1, 1))
            st["tracers"].append([0.0 if d > 0 else n - 1.0, d * rng.uniform(70, 140) * energy])
        if st["beats"] % (4 * max(1, int(params["bars"]))) == 0:
            st["scheme"] = (st["scheme"] + rng.randrange(1, len(SCHEMES))) % len(SCHEMES)
    if live and a.onset and rng.random() < 0.2 and len(st["tracers"]) < 6:
        d = rng.choice((-1, 1))
        st["tracers"].append([rng.uniform(0, n - 1), d * rng.uniform(90, 160) * energy])

    # --- move bricks: ease to new speed, bounce off walls and off each other --------------------
    bricks = st["bricks"]
    for b in bricks:
        b["v"] += (b["want"] - b["v"]) * min(1.0, dt * 8)
        b["x"] += b["v"] * dt
        b["flare"] *= m.exp(-dt * 7)
        if b["x"] < 0:
            b["x"], b["v"], b["want"] = 0.0, abs(b["v"]), abs(b["want"])
        elif b["x"] + b["len"] > n:
            b["x"], b["v"], b["want"] = n - b["len"], -abs(b["v"]), -abs(b["want"])
    bricks.sort(key=lambda b: b["x"])
    for left, right in zip(bricks, bricks[1:]):
        overlap = left["x"] + left["len"] + 1 - right["x"]        # keep at least a 1-pixel black gap
        if overlap > 0:
            left["x"] -= overlap / 2
            right["x"] += overlap / 2
            left["v"], right["v"] = right["v"], left["v"]          # elastic knock
            left["want"], right["want"] = -abs(left["want"]), abs(right["want"])

    idx = np.arange(n, dtype=float)
    scheme = SCHEMES[st["scheme"]]
    out = np.zeros((n, 3))
    for b in bricks:
        cov = _cover(np, idx, b["x"], b["x"] + b["len"])
        col = np.array(scheme[b["c"]], float) * (0.55 + 0.45 * b["flare"])
        out = np.maximum(out, cov[:, None] * col)

    # --- tracers: single bright pixels with short crisp tails, passing over the bricks ----------
    head = np.zeros((n, 3))
    keep = []
    for tr in st["tracers"]:
        tr[0] += tr[1] * dt
        if 0 <= tr[0] <= n - 1:
            keep.append(tr)
            head += _cover(np, idx, tr[0] - 0.5, tr[0] + 0.5)[:, None] * np.array(TRACER, float)
    st["tracers"] = keep
    st["tail"] = np.maximum(st["tail"] * m.exp(-dt / max(0.02, params["tail"])), head * 0.6)
    out = np.maximum(out, st["tail"])
    out = np.maximum(out, head)

    return np.clip(out, 0, 255).astype(np.uint8)
Clair De Lune Something for Clair de Lune, not beat responsive – with a single neon butterfly that flaps around leaving a faint trail, cycling through neon colours
View code
META = {
    "name": "clair_de_lune",
    "audio": False,
    "description": "Moonlight on still water, after Debussy: a deep indigo night, a pale moon drifting slowly "
                   "along the strip with a soft halo, its silver glitter path trembling on the water below; "
                   "flowing arpeggio ripples of lavender and silver roll across in unhurried rubato, and the "
                   "whole scene swells and settles in long breathing phrases; a single neon butterfly flutters "
                   "through the moonlight, wings opening and closing, leaving a faint glowing trail",
}
PARAMS = {
    "pace": 1.0,        # overall tempo of the piece (lower = dreamier)
    "glitter": 1.0,     # moonlight sparkle on the water
    "ripples": 1.0,     # arpeggio wave brightness
    "night": 0.35,      # background sky/water brightness
    "butterfly": 1.0,   # neon butterfly brightness (0 = hidden)
    "trail": 1.0,       # how long its faint trail lingers, seconds
    "color_seconds": 6.0,  # how long the butterfly holds each neon color
}

NIGHT_A, NIGHT_B = (2, 3, 16), (6, 4, 22)          # indigo -> violet
SILVER, LAVENDER, MOON = (170, 190, 255), (120, 90, 210), (255, 240, 205)
BODY = (255, 220, 255)
# neon (wing, tip) pairs the butterfly cycles through: pink, green, orange, cyan, purple, yellow
NEON = [((255, 0, 170), (0, 230, 255)), ((40, 255, 20), (255, 255, 60)), ((255, 130, 0), (255, 0, 120)),
        ((0, 230, 255), (180, 0, 255)), ((170, 0, 255), (255, 0, 170)), ((255, 230, 0), (40, 255, 20))]


def setup(sdk):
    np = sdk.np
    rng = np.random.default_rng(7)
    sdk.state.update(
        glit_phase=rng.uniform(0, 6.283, sdk.n),
        glit_speed=rng.uniform(1.2, 3.5, sdk.n),
        ripples=[],          # [pos, dir, age, speed, hue_mix, width]
        next_ripple=0.5,
        rng=rng, clock=0.0,
        bx=sdk.n * 0.3, bv=0.0, btarget=sdk.n * 0.6, brest=0.0, flap=0.0,
        btrail=np.zeros((sdk.n, 3)),
    )


def _neon(t, hold, np, m):
    """Hold each neon color, then glide to the next over the last third of the hold."""
    k = t / max(0.5, hold)
    i, f = int(k) % len(NEON), k - int(k)
    mix = 0.0 if f < 0.67 else 0.5 - 0.5 * m.cos((f - 0.67) / 0.33 * m.pi)
    a, b = NEON[i], NEON[(i + 1) % len(NEON)]
    return [np.array(a[j], float) * (1 - mix) + np.array(b[j], float) * mix for j in (0, 1)]


def _butterfly(st, t, dt, n, np, m, rng, idx, pace, wing, edge):
    """Flutter toward a wandering target with jittery bursts; sometimes alight and rest."""
    if st["brest"] > 0:
        st["brest"] -= dt
        st["bv"] *= m.exp(-dt * 6)
        flap_hz = 1.2                                       # slow, lazy flaps while resting
    else:
        if abs(st["btarget"] - st["bx"]) < 2 or rng.random() < 0.15 * dt:
            st["btarget"] = rng.uniform(3, n - 4)
            if rng.random() < 0.3:
                st["brest"] = rng.uniform(1.5, 4.0)       # alight for a moment
        want = 14.0 * pace * (1 if st["btarget"] > st["bx"] else -1)
        st["bv"] += (want - st["bv"]) * min(1.0, dt * 2.5)
        st["bv"] += rng.normal(0, 40) * dt                   # erratic flutter
        flap_hz = 6.0
    st["bx"] = min(n - 2.0, max(1.0, st["bx"] + st["bv"] * dt))
    st["flap"] += dt * flap_hz * 2 * m.pi
    open_ = 0.5 + 0.5 * m.sin(st["flap"])                  # 0 = wings closed, 1 = spread
    x = st["bx"]
    d = np.abs(idx - x)
    span = 0.6 + 2.6 * open_
    wings = np.exp(-((d - span * 0.6) / (0.5 + 0.6 * open_)) ** 2) * (0.35 + 0.65 * open_)
    tips = np.exp(-((d - span) / 0.6) ** 2) * open_
    body = np.exp(-(d / 0.6) ** 2)
    return (wings[:, None] * wing + tips[:, None] * edge
            + body[:, None] * np.array(BODY, float) * 0.7)


def render(t, dt, n, sdk, params):
    st, np, m = sdk.state, sdk.np, sdk.math
    rng = st["rng"]
    pace = max(0.1, params["pace"])
    # rubato: the piece's clock speeds up and slows down gently, like a pianist breathing
    st["clock"] += dt * pace * (0.75 + 0.25 * m.sin(t * 0.21 * pace))
    c = st["clock"]
    idx = np.arange(n, dtype=float)
    u = idx / max(1, n - 1)

    # long phrase swell (~24 s) shared by everything
    swell = 0.65 + 0.35 * (0.5 - 0.5 * m.cos(c * 0.26))

    # --- night: slow indigo/violet drift ------------------------------------------------------
    drift = 0.5 + 0.5 * np.sin(u * 5.0 + c * 0.11) * np.sin(u * 2.3 - c * 0.07)
    out = (np.array(NIGHT_A) + (np.array(NIGHT_B) - np.array(NIGHT_A)) * drift[:, None]) * params["night"]

    # --- moon: wanders slowly across the strip and back ---------------------------------------
    mx = (0.5 + 0.38 * m.sin(c * 0.045)) * (n - 1)
    d = idx - mx
    halo = np.exp(-(d / (n * 0.16)) ** 2) * 0.15 + np.exp(-(d / 3.0) ** 2) * 0.9
    out += halo[:, None] * np.array(MOON, float) * 0.55 * swell

    # --- glitter path: trembling silver sparkles, densest under the moon ---------------------
    path = np.exp(-(d / (n * 0.22)) ** 2)
    tw = np.sin(st["glit_phase"] + t * st["glit_speed"] * pace)
    sparkle = np.clip(tw, 0, 1) ** 6 * path
    out += sparkle[:, None] * np.array(SILVER, float) * 0.9 * params["glitter"] * swell

    # --- arpeggio ripples: wave packets that roll outward from the moon ----------------------
    st["next_ripple"] -= dt * pace
    if st["next_ripple"] <= 0:
        # arpeggios come in little runs of 2-4 notes, then a pause
        run = int(rng.integers(2, 5))
        for k in range(run):
            st["ripples"].append([mx, float(rng.choice((-1, 1))), -k * 0.28, rng.uniform(9, 15),
                                  rng.random(), rng.uniform(2.5, 5.0)])
        st["next_ripple"] = rng.uniform(2.0, 4.5)
    keep = []
    for r in st["ripples"]:
        r[2] += dt * pace
        pos, direction, age, speed, mix, width = r
        if age > 6.0:
            continue
        keep.append(r)
        if age < 0:
            continue
        x = pos + direction * speed * age
        env = m.sin(min(1.0, age / 0.6) * m.pi / 2) * m.exp(-age * 0.45)
        w = np.exp(-((idx - x) / width) ** 2) * env
        col = np.array(SILVER, float) * (1 - mix) + np.array(LAVENDER, float) * mix
        out += w[:, None] * col * 0.6 * params["ripples"]
    st["ripples"] = keep[-24:]

    # --- neon butterfly with a faint trail ----------------------------------------------------
    if params["butterfly"] > 0:
        wing, edge = _neon(t, params["color_seconds"], np, m)
        fly = _butterfly(st, t, dt, n, np, m, rng, idx, pace, wing, edge) * params["butterfly"]
        fade = m.exp(-dt / max(0.05, params["trail"]))
        st["btrail"] = np.maximum(st["btrail"] * fade, fly * 0.22)
        out = np.maximum(out + st["btrail"], fly)

    return np.clip(out, 0, 255).astype(np.uint8)
Beat Blocks Show the beats more distinctly against a black backdrop
View code
META = {
    "name": "beat_blocks",
    "audio": True,
    "description": "Pure black until a beat lands: each beat slams a bold block of color into the next quarter "
                   "of the strip (counting 1-2-3-4 across it), with a crisp attack and fast fade back to black; "
                   "the downbeat lights brighter and the color changes every bar",
}
PARAMS = {
    "trigger": "beat",   # beat = tracked tempo beats | kick = actual bass hits | both
    "segments": 4,       # blocks per bar (4 = one per beat in 4/4)
    "decay": 7.0,        # how fast a block fades to black (higher = snappier)
    "gap": 2,            # black pixels between blocks
}

COLORS = [(255, 0, 40), (0, 220, 255), (255, 0, 200), (255, 150, 0), (40, 60, 255), (0, 255, 90)]


def setup(sdk):
    sdk.state.update(count=0, hits=[], last_hit=-1.0)


def _hit(st, t, strength):
    if t - st["last_hit"] < 0.18:          # never double-fire on one drum hit
        return
    st["last_hit"] = t
    st["hits"].append([st["count"], 1.0, strength])
    st["count"] += 1
    st["hits"] = st["hits"][-8:]


def render(t, dt, n, sdk, params):
    st, a, np, m = sdk.state, sdk.audio, sdk.np, sdk.math
    live = a.active and a.level > 0.0
    mode = params["trigger"]
    if live:
        kick = a.onset and a.bass > 0.45
        if (mode in ("beat", "both") and a.beat) or (mode in ("kick", "both") and kick):
            _hit(st, t, 0.6 + 0.4 * max(a.bass, a.level))

    segs = max(1, int(params["segments"]))
    gap = max(0, int(params["gap"]))
    seg_len = n / segs
    out = np.zeros((n, 3))
    idx = np.arange(n, dtype=float)
    fade = m.exp(-params["decay"] * dt)
    keep = []
    for h in st["hits"]:
        count, life, strength = h
        if life < 0.02:
            continue
        keep.append(h)
        k = count % segs
        bar = count // segs
        color = np.array(COLORS[bar % len(COLORS)], dtype=float)
        downbeat = k == 0
        v = life * strength * (1.0 if downbeat else 0.8)
        lo, hi = k * seg_len + gap / 2, (k + 1) * seg_len - gap / 2
        # crisp block; brief white-hot core right at the attack
        inside = (idx >= lo) & (idx < hi)
        block = inside[:, None] * color * v
        attack = max(0.0, life - 0.75) * 4                  # first ~40 ms
        block += inside[:, None] * np.array((255.0, 255.0, 255.0)) * attack * 0.5
        out = np.maximum(out, block)
        if downbeat:                                        # faint whole-bar pulse on the "1"
            out = np.maximum(out, color * 0.12 * life ** 2)
        h[1] = life * fade
    st["hits"] = keep
    return np.clip(out, 0, 255).astype(np.uint8)
Echo One that is highly sensitive to the microphone
View code
META = {
    "name": "echo",
    "audio": True,
    "description": "Hyper-sensitive sound ripples: every sound is painted at the center and travels outward "
                   "to both ends, so the strip shows the last few seconds of sound; color = timbre "
                   "(bass warm red/magenta, voice green/cyan, hiss/snaps blue/violet); sharp sounds flash white "
                   "and throw sparks; a faint heartbeat glow in silence",
}
PARAMS = {
    "sensitivity": 2.5,   # boost for quiet sounds (1 = linear)
    "speed": 45.0,        # how fast echoes travel outward, pixels per second
    "reach": 0.4,         # brightness an echo still has when it reaches the ends (0..1)
    "sparks": 1.0,        # onset spark amount
}

LOW, MID, HIGH = (255, 20, 70), (20, 255, 120), (60, 60, 255)


def setup(sdk):
    half = (sdk.n + 1) // 2
    sdk.state.update(
        buf=sdk.np.zeros((half, 3)),   # index 0 = center, grows outward
        acc=0.0, peak=sdk.np.zeros(3), flash=0.0,
        sparks=sdk.Trail(sdk.n), rng=sdk.rand(3),
    )


def render(t, dt, n, sdk, params):
    st, a, np, m = sdk.state, sdk.audio, sdk.np, sdk.math
    buf = st["buf"]
    half = len(buf)
    live = a.active and a.level > 0.0

    # --- what are we hearing right now? ------------------------------------------------------
    b = a.bands
    low, mid, high = max(b[0], b[1], b[2]), max(b[3], b[4]), max(b[5], b[6], b[7])
    loud = a.level ** (1.0 / max(0.5, params["sensitivity"])) if live else 0.0   # boost quiet sounds
    total = low + mid + high
    if total > 1e-6:
        mix = np.array(LOW) * (low / total) + np.array(MID) * (mid / total) + np.array(HIGH) * (high / total)
        # saturate the mix so it stays vivid, then scale by loudness
        mix = mix * (255.0 / max(1.0, mix.max()))
        color = mix * loud
    else:
        color = np.zeros(3)
    # keep the loudest color since the last step so short sounds are never missed between steps
    st["peak"] = np.maximum(st["peak"], color)

    # --- travel outward ------------------------------------------------------------------------
    st["acc"] += params["speed"] * dt
    steps = int(st["acc"])
    if steps:
        st["acc"] -= steps
        keep = sdk.clamp(params["reach"], 0.01, 1.0) ** (1.0 / half)
        for _ in range(min(steps, half)):
            buf[1:] = buf[:-1] * keep
            buf[0] = st["peak"]
        st["peak"] = np.zeros(3)
    else:
        buf[0] = np.maximum(buf[0], st["peak"])

    # --- sharp sounds: white flash at the center + sparks flying out --------------------------
    sparks, rng = st["sparks"], st["rng"]
    sparks.fade(m.exp(-dt * 6.0))
    if live and a.onset and a.level > 0.15:
        st["flash"] = 0.4 + 0.6 * a.level
        c = (n - 1) / 2
        for _ in range(int(params["sparks"] * (1 + 5 * a.level))):
            j = int(c + rng.gauss(0, n * 0.18))
            if 0 <= j < n:
                sparks.add(j, (150, 150, 200))
    st["flash"] *= m.exp(-dt * 10.0)

    # --- mirror the echo buffer around the center ----------------------------------------------
    out = np.zeros((n, 3))
    left = buf[::-1]                                # far-left .. center
    out[:half] = left
    out[n - half:] = np.maximum(out[n - half:], buf)
    idx = np.arange(n, dtype=float)
    center = (n - 1) / 2
    d = np.abs(idx - center)
    out += (np.exp(-(d / 2.0) ** 2) * 200 * st["flash"])[:, None]
    out += np.array(sparks.pixels(), dtype=float)

    # --- silence: a faint heartbeat at the center so you know it's listening --------------------
    if out.max() < 12:
        beat = sdk.wave(t * 0.8) ** 8
        out += (np.exp(-(d / 3.0) ** 2) * (6 + 24 * beat))[:, None] * np.array((0.6, 0.2, 1.0))

    return np.clip(out, 0, 255).astype(np.uint8)
Supernova Galactic supernovae in response to the beats
View code
META = {
    "name": "supernova",
    "audio": True,
    "description": "Deep space: a slowly drifting violet/teal nebula, twinkling stars and a warm galactic core "
                   "that breathes with the bass; every beat detonates a supernova whose white-hot core flashes, "
                   "shockwave races outward cooling from blue-white to magenta to red, and leaves a glowing remnant",
}
PARAMS = {
    "intensity": 1.0,   # supernova brightness
    "size": 1.0,        # how far shockwaves travel
    "nebula": 1.0,      # background nebula/core brightness (0 = black space)
    "every": 2,         # detonate on every Nth beat; the beats in between pulse the galactic core
    "idle_rate": 0.4,   # spontaneous supernovae per second when there is no music
}

# shock/remnant colour as the gas cools: white-hot -> blue-white -> cyan -> magenta -> ember red
COOLING = [(0.0, (255, 255, 255)), (0.15, (170, 210, 255)), (0.35, (60, 170, 255)),
           (0.6, (200, 40, 210)), (0.85, (170, 10, 60)), (1.0, (60, 0, 20))]
NEB_A, NEB_B, NEB_C = (2, 0, 9), (13, 2, 24), (0, 9, 15)
LIFE = 5.5


def _cool(x, sdk):
    x = sdk.clamp(x)
    for (p0, c0), (p1, c1) in zip(COOLING, COOLING[1:]):
        if x <= p1:
            return sdk.blend(c0, c1, (x - p0) / (p1 - p0))
    return COOLING[-1][1]


def setup(sdk):
    rng = sdk.rand(42)
    sdk.state.update(
        rng=rng, novae=[], beats=0, pulse=0.0,
        stars=[(rng.randrange(sdk.n), rng.random(), 0.0) for _ in range(14)],
    )


def _detonate(st, n, strength):
    rng = st["rng"]
    st["novae"].append({"x": rng.uniform(4, n - 5), "age": 0.0, "s": strength,
                        "late": rng.uniform(0.85, 1.15)})          # per-star cooling variety
    st["novae"] = st["novae"][-8:]


def render(t, dt, n, sdk, params):
    st, a, np, m = sdk.state, sdk.audio, sdk.np, sdk.math
    rng = st["rng"]
    live = a.active and a.level > 0.02

    # --- triggers: beats detonate; onsets make stars flare; idle novae in silence --------------
    if live and a.beat:
        st["beats"] += 1
        if st["beats"] % max(1, int(params["every"])) == 0:
            _detonate(st, n, 0.55 + 0.45 * a.bass)
        else:
            st["pulse"] = 1.0
    elif not live and rng.random() < params["idle_rate"] * dt:
        _detonate(st, n, rng.uniform(0.5, 1.0))
    stars = st["stars"]
    if live and a.onset and stars:
        k = rng.randrange(len(stars))
        i, ph, _ = stars[k]
        stars[k] = (i, ph, 1.0)

    idx = np.arange(n, dtype=float)
    c = (n - 1) / 2

    # --- background: drifting nebula, galactic core, stars ---------------------------------
    out = np.zeros((n, 3))
    neb = params["nebula"]
    if neb > 0:
        for i in range(n):
            u = sdk.noise(i * 0.05 + t * 0.03, t * 0.02)
            v = sdk.noise(i * 0.13 - t * 0.05 + 30, 0.5)
            col = sdk.blend(NEB_A, NEB_B, u)
            out[i] = sdk.blend(col, NEB_C, v * 0.6)
        st["pulse"] *= m.exp(-dt * 4)
        core = np.exp(-((idx - c) / (n * 0.13)) ** 2) * (0.7 + 0.5 * (a.bass if live else 0.2) + 1.5 * st["pulse"])
        arms = 0.6 + 0.4 * np.cos(np.abs(idx - c) * 0.35 - t * 0.4)   # spiral arms winding outward
        out += (core * arms)[:, None] * np.array((34.0, 24.0, 12.0))
        out *= neb
    new_stars = []
    for i, ph, flare in stars:
        tw = 0.5 + 0.5 * m.sin(t * (0.7 + 1.6 * ph) + ph * 40)
        out[i] += np.array((50.0, 50.0, 70.0)) * tw ** 3 + np.array((200.0, 220.0, 255.0)) * flare
        new_stars.append((i, ph, flare * m.exp(-dt * 5)))
    st["stars"] = new_stars

    # --- supernovae ------------------------------------------------------------------------
    keep = []
    gain = params["intensity"]
    for nv in st["novae"]:
        nv["age"] += dt
        age, s, x = nv["age"], nv["s"], nv["x"]
        if age > LIFE:
            continue
        keep.append(nv)
        d = np.abs(idx - x)
        cool = age / (2.6 * nv["late"])
        # 1) white-hot core flash
        core = np.exp(-(d / (0.8 + age * 3)) ** 2) * m.exp(-age * 5) * s
        out += core[:, None] * np.array((255.0, 250.0, 240.0)) * gain
        # 2) shockwave: two fronts racing outward, decelerating and cooling
        r = (8 + 22 * s) * params["size"] * (1 - m.exp(-age * 1.8))
        width = 1.0 + age * 1.1
        ring = np.exp(-((d - r) / width) ** 2) * m.exp(-age * 0.75) * s
        out += ring[:, None] * np.array(_cool(cool, sdk), float) * gain
        # 3) remnant: a lumpy glowing cloud inside the shell, fading slowly
        if r > 1:
            inside = np.clip(1 - d / r, 0, 1) ** 1.5
            lumps = 0.6 + 0.4 * np.cos(d * 1.3 + x - t * 0.8)
            rem = inside * lumps * 0.35 * s * m.exp(-age * 0.55) * sdk.clamp(age * 2)
            out += rem[:, None] * np.array(_cool(min(1.0, cool + 0.35), sdk), float) * gain
    st["novae"] = keep

    return np.clip(out, 0, 255).astype(np.uint8)
Cat And Mouse A cat chasing a mouse through the house
View code
META = {
    "name": "cat_and_mouse",
    "audio": False,
    "description": "A cartoon chase through the house: a big blue-gray cat with heavy inertia chases a quick "
                   "orange mouse through four rooms; the mouse jukes past, the cat skids, and when the mouse "
                   "dives into its hole at the start of the strip the cat smacks into the wall and sees stars",
}
PARAMS = {
    "speed": 1.0,          # overall chase speed multiplier
    "chase_seconds": 12.0, # how long each chase lasts before the mouse heads for its hole
    "house": 0.6,          # brightness of the room colors (0 = dark house)
    "trail": 0.25,         # speed-line afterglow, seconds
}

CAT = (80, 100, 170)
CAT_NOSE = (230, 230, 240)
MOUSE = (240, 120, 20)
STAR = (255, 220, 60)
# rooms from the mouse hole outward: kitchen, living room, hallway, bedroom (fraction of strip, tint)
ROOMS = [(0.30, (16, 9, 2)), (0.55, (3, 11, 8)), (0.80, (9, 4, 11)), (1.00, (2, 5, 15))]


def setup(sdk):
    n = sdk.n
    sdk.state.update(
        phase="peek", timer=0.0, chase_t=0.0, juke_cd=2.0,
        cat_x=n * 0.6, cat_v=0.0, mouse_x=1.0, mouse_dir=1, mouse_seen=True,
        flash=0.0, skid=0.0,
        glow=sdk.np.zeros((n, 3)), rng=sdk.rand(5),
    )


def _blob(np, idx, x, width, color, b):
    w = np.exp(-((idx - x) / width) ** 2) * b
    return w[:, None] * np.array(color, dtype=float)


def render(t, dt, n, sdk, params):
    st, np, m = sdk.state, sdk.np, sdk.math
    rng = st["rng"]
    k = max(0.2, params["speed"]) * n / 100.0
    mouse_speed, cat_top, cat_acc = 24.0 * k, 19.0 * k, 32.0 * k
    hole, wall = 0.8, 2.6
    st["timer"] += dt

    # ---------------- story state machine ----------------
    phase = st["phase"]
    if phase in ("chase", "home"):
        st["chase_t"] += dt
        mx, cx = st["mouse_x"], st["cat_x"]
        if phase == "chase":
            st["juke_cd"] -= dt
            # juke: dart back between the cat's legs when it gets close
            if st["juke_cd"] <= 0 and abs(cx - mx) < 10 and rng.random() < 0.15:
                st["mouse_dir"] = -1 if cx < mx else 1   # toward and past the cat
                st["juke_cd"] = rng.uniform(1.5, 3.5)
            if mx > n - 4:
                st["mouse_dir"] = -1
            elif mx < 6:
                st["mouse_dir"] = 1
            if st["chase_t"] > params["chase_seconds"]:
                st["phase"], st["mouse_dir"] = "home", -1
        st["mouse_x"] = max(hole, min(n - 1.0, mx + st["mouse_dir"] * mouse_speed * dt))
        if st["phase"] == "home" and st["mouse_x"] <= hole:
            st["mouse_seen"] = False                       # safe in the hole

        # the cat: heavy, accelerates toward the mouse (or the hole), skids when reversing
        target = st["mouse_x"] if st["mouse_seen"] else 0.0
        want = cat_top if target > cx else -cat_top
        dv = want - st["cat_v"]
        step = max(-cat_acc * dt, min(cat_acc * dt, dv))
        if st["cat_v"] * want < 0:
            st["skid"] = 1.0
        st["cat_v"] += step
        st["cat_x"] = cx + st["cat_v"] * dt
        if st["cat_x"] >= n - 1:
            st["cat_x"], st["cat_v"] = n - 1.0, 0.0
        if not st["mouse_seen"] and st["cat_x"] <= wall:   # SMACK
            st["cat_x"], st["cat_v"] = wall, 0.0
            st["phase"], st["timer"], st["flash"] = "bonk", 0.0, 1.0
    elif phase == "bonk":
        if st["timer"] > 3.0:
            st["phase"], st["timer"] = "peek", 0.0
            st["mouse_x"], st["mouse_seen"] = hole, True
    elif phase == "peek":
        # mouse peeks out of the hole while the dazed cat drifts back, then the chase restarts
        st["cat_x"] = min(st["cat_x"] + 4.0 * k * dt, n * 0.25)
        if st["timer"] > 1.6:
            st["phase"], st["timer"], st["chase_t"] = "chase", 0.0, 0.0
            st["mouse_dir"], st["cat_v"], st["juke_cd"] = 1, 0.0, 2.0
    st["flash"] *= m.exp(-dt * 5.0)
    st["skid"] *= m.exp(-dt * 6.0)

    # ---------------- draw ----------------
    idx = np.arange(n, dtype=float)
    new = np.zeros((n, 3))
    cx, mx = st["cat_x"], st["mouse_x"]
    dazed = st["phase"] == "bonk"
    # cat: wide body, white nose on the leading side (squashed flat and dim when dazed)
    if dazed:
        new += _blob(np, idx, cx + 0.8, 1.2, CAT, 0.55)
        for s in range(3):                                  # stars circling the cat's head
            ang = t * 7.0 + s * 2.094
            if m.sin(ang) > -0.3:                           # behind the head = hidden
                new += _blob(np, idx, cx + 1.5 + 3.0 * m.cos(ang), 0.5, STAR, 0.9)
    else:
        face = 1.0 if st["cat_v"] >= 0 else -1.0
        new += _blob(np, idx, cx, 2.0, CAT, 1.0)
        new += _blob(np, idx, cx + face * 2.4, 0.55, CAT_NOSE, 0.8)
        if st["skid"] > 0.05:                               # skid sparks at the cat's feet
            for _ in range(2):
                j = int(cx - face * rng.uniform(1, 4))
                if 0 <= j < n and rng.random() < st["skid"]:
                    new[j] += np.array((255, 160, 60)) * st["skid"]
    # mouse: small, bright, quick; peeking = blinking in the hole
    if st["mouse_seen"]:
        b = 0.5 + 0.5 * sdk.pulse(t * 3.0) if st["phase"] == "peek" else 1.0
        new += _blob(np, idx, mx, 0.7, MOUSE, b)
    keep = m.exp(-dt / max(0.03, params["trail"]))
    st["glow"] = np.maximum(st["glow"] * keep, np.minimum(new, 255.0))

    # house: dim rooms with dark doorways; the smack shakes the kitchen lights
    house = np.zeros((n, 3))
    start = 0
    for frac, tint in ROOMS:
        end = int(round(frac * n))
        house[start:end] = tint
        if end < n:
            house[end - 1] = (0, 0, 0)                     # doorway
        start = end
    house *= params["house"]
    house[0] = (1, 0, 0)                                   # the mouse hole
    if st["flash"] > 0.01:
        k_end = int(ROOMS[0][0] * n)
        shake = 0.6 + 0.4 * m.sin(t * 60)
        house[:k_end] += np.array((90.0, 80.0, 60.0)) * st["flash"] * shake

    return np.clip(house + st["glow"], 0, 255).astype(np.uint8)
Christmas Christmas – be creative and impress me
View code
META = {
    "name": "christmas",
    "audio": True,
    "description": "A Christmas show in five acts that crossfade forever: snowfall piling into a drift, "
                   "old-fashioned C9 tree bulbs that switch on and chase, a shining candy cane, Santa's "
                   "sleigh led by a red-nosed reindeer across the night sky, and a golden star finale",
}
PARAMS = {
    "scene": "auto",   # auto | snow | tree | candy | sleigh | finale
    "pace": 1.0,       # story speed
}

FADE = 2.5
SCENES = [("snow", 18.0), ("tree", 18.0), ("candy", 10.0), ("sleigh", 12.0), ("finale", 14.0)]
BULBS = [(255, 20, 0), (0, 200, 20), (255, 110, 0), (0, 40, 255), (255, 0, 90)]
GOLD = (255, 170, 30)


# ----------------------------------------------------------------------------- helpers
def _blobs(np, idx, xs, width, colors, bs):
    """Sum of soft round lights: xs (k,), colors (k,3), bs (k,) brightness -> (n,3)."""
    if len(xs) == 0:
        return np.zeros((len(idx), 3))
    w = np.exp(-((idx[None, :] - np.asarray(xs, float)[:, None]) / width) ** 2) * np.asarray(bs, float)[:, None]
    return w.T @ np.asarray(colors, float)


def _night(np, n, lt, sdk, s, stars=10):
    if "stars" not in s:
        s["stars"] = [(s["rng"].randrange(n), s["rng"].random()) for _ in range(stars)]
    sky = np.tile(np.array((0.0, 1.5, 9.0)), (n, 1))
    for i, k in s["stars"]:
        tw = 0.5 + 0.5 * sdk.math.sin(lt * (0.8 + 1.5 * k) + k * 30)
        sky[i] += np.array((40.0, 40.0, 55.0)) * tw ** 3
    return sky


# ----------------------------------------------------------------------------- act 1
def snow(lt, dt, dur, n, sdk, s, a):
    np, m, rng = sdk.np, sdk.math, s["rng"]
    if "flakes" not in s:
        s["flakes"] = [[rng.uniform(n * 0.2, n), rng.uniform(3, 7), rng.uniform(0, 6.3), rng.uniform(0.4, 1)]
                       for _ in range(12)]
        s["pile"] = 0.0
    rate = 2.8 + (4.0 * a.level if a.active else 0.0)
    if rng.random() < rate * dt:
        s["flakes"].append([n + rng.random() * 2, rng.uniform(3, 7), rng.uniform(0, 6.3), rng.uniform(0.4, 1)])
    keep = []
    for f in s["flakes"]:
        f[0] -= f[1] * dt
        if f[0] <= s["pile"]:
            s["pile"] = min(n * 0.22, s["pile"] + 0.3)   # lands on the drift
        else:
            keep.append(f)
    s["flakes"] = keep
    idx = np.arange(n, dtype=float)
    xs = [f[0] + 1.2 * m.sin(lt * 1.3 + f[2]) for f in keep]
    bs = [f[3] * (0.7 + 0.3 * m.sin(lt * 7 + f[2] * 3)) for f in keep]
    out = _night(np, n, lt, sdk, s, stars=6)
    out += _blobs(np, idx, xs, 0.65, [(190, 215, 255)] * len(xs), bs)
    drift = np.clip(s["pile"] - idx, 0, 1)
    out += drift[:, None] * np.array((110.0, 120.0, 150.0))
    if s["pile"] > 1 and rng.random() < 0.3:              # glints on the drift
        out[rng.randrange(int(s["pile"]))] += 140
    return out


# ----------------------------------------------------------------------------- act 2
def tree(lt, dt, dur, n, sdk, s, a):
    np, m, rng = sdk.np, sdk.math, s["rng"]
    spacing = 5
    pos = list(range(2, n, spacing))
    mid = len(pos) / 2
    if "flare" not in s:
        s["flare"] = [0.0] * len(pos)
    if a.beat and a.active:
        s["flare"][rng.randrange(len(pos))] = 1.0
    # marquee chase in the middle third of the act, eased in and out
    chase = sdk.clamp(min(lt - dur * 0.4, dur * 0.75 - lt) / 1.5)
    xs, cols, bs = [], [], []
    for b, p in enumerate(pos):
        on = sdk.clamp((lt - 0.12 * abs(b - mid)) * 3)  # switch on from the middle outward
        steady = 0.75 + 0.25 * sdk.noise(b * 3.1, lt * 0.8)
        run = 0.15 + 0.85 * sdk.wave(b / 6 - lt * 0.9) ** 3
        s["flare"][b] *= m.exp(-dt * 3)
        v = on * min(1.0, sdk.lerp(steady, run, chase) + s["flare"][b])
        xs.append(p)
        cols.append(BULBS[b % len(BULBS)])
        bs.append(v)
    idx = np.arange(n, dtype=float)
    out = _blobs(np, idx, xs, 0.9, cols, bs)
    # warm white mini-light garland between the bulbs
    warm = np.array(sdk.kelvin(2400), float)
    for i in range(n):
        if i % spacing in (0, 4) and i % 2 == 0:
            tw = 0.5 + 0.5 * sdk.noise(i * 0.7, lt * 2.0)
            out[i] += warm * 0.18 * tw * sdk.clamp(lt - 1.5)
    return out


# ----------------------------------------------------------------------------- act 3
def candy(lt, dt, dur, n, sdk, s, a):
    np = sdk.np
    idx = np.arange(n, dtype=float)
    f = (idx * 0.1 + lt * 0.6) % 1.0
    v = 0.5 + 0.5 * np.sin(2 * np.pi * f)
    white = np.clip((v - 0.5) * 5 + 0.5, 0, 1)
    out = (1 - white)[:, None] * np.array((255.0, 0.0, 0.0)) + white[:, None] * np.array((190.0, 190.0, 190.0))
    pos = (lt * 28.0) % (n + 40) - 20                       # glossy shine sweeping along
    out += np.exp(-((idx - pos) / 3.0) ** 2)[:, None] * np.array((150.0, 150.0, 150.0))
    if a.onset and a.active:
        out *= 1.15
    return out


# ----------------------------------------------------------------------------- act 4
def sleigh(lt, dt, dur, n, sdk, s, a):
    np, m, rng = sdk.np, sdk.math, s["rng"]
    if "dust" not in s:
        s["dust"] = np.zeros((n, 3))
    p = -6 + (n + 30) * lt / (dur - 1.0)                  # Rudolph's nose position
    xs, cols, bs = [], [], []
    xs.append(p + 1); cols.append((255, 0, 0)); bs.append(0.75 + 0.25 * m.sin(lt * 9))     # the red nose
    for r in range(4):                                     # reindeer, galloping (bobbing brightness)
        xs.append(p - 1.5 - r * 2.3); cols.append((110, 45, 8))
        bs.append(0.7 + 0.3 * m.sin(lt * 12 + r * 1.7))
    xs.append(p - 10.0); cols.append(GOLD); bs.append(0.35)                # harness
    for k, c in enumerate([(220, 0, 0), (255, 255, 255), (220, 0, 0)]):   # sleigh with Santa
        xs.append(p - 12 - k * 1.1); cols.append(c); bs.append(0.9 if k != 1 else 0.6)
    xs.append(p - 15.5); cols.append(GOLD); bs.append(0.6)               # runner curl
    idx = np.arange(n, dtype=float)
    # stardust shed behind the sleigh, plus jingle sparkles on onsets
    s["dust"] *= m.exp(-dt * 1.4)
    sparks = 3 + (6 if (a.onset and a.active) else 0)
    for _ in range(sparks):
        j = int(p - 16 - rng.random() * 8)
        if 0 <= j < n and rng.random() < 0.6:
            s["dust"][j] = np.maximum(s["dust"][j], (255, 200, 90) if rng.random() < 0.7 else (220, 230, 255))
    out = _night(np, n, lt, sdk, s)
    out += s["dust"] * 0.8
    out += _blobs(np, idx, xs, 0.7, cols, bs)
    return out


# ----------------------------------------------------------------------------- act 5
def finale(lt, dt, dur, n, sdk, s, a):
    np, m, rng = sdk.np, sdk.math, s["rng"]
    idx = np.arange(n, dtype=float)
    c = (n - 1) / 2
    if "buf" not in s:
        s["buf"] = np.zeros((n, 3))
        s["parts"] = []
        s["burst"] = False
    s["buf"] *= m.exp(-dt * 5)
    out = np.zeros((n, 3))
    if lt < 3.0:                                           # two golden comets race to the middle
        x = c * sdk.ease_in(lt / 3.0)
        s["buf"] = np.maximum(s["buf"], _blobs(np, idx, [x, n - 1 - x], 0.8, [GOLD, GOLD], [1, 1]))
    elif not s["burst"]:                                   # ... and burst
        s["burst"] = True
        pal = [(255, 20, 0), (0, 220, 40), GOLD, (255, 255, 255)]
        for _ in range(36):
            s["parts"].append([c, rng.uniform(-38, 38), pal[rng.randrange(4)], rng.uniform(0, 6.3)])
        s["flash"] = 1.0
    age = lt - 3.0
    if s["burst"]:
        for q in s["parts"]:
            q[1] *= m.exp(-dt * 1.6)
            q[0] += q[1] * dt
        life = m.exp(-age * 0.8)
        bs = [life * (0.6 + 0.4 * m.sin(lt * 14 + q[3])) for q in s["parts"]]
        out += _blobs(np, idx, [q[0] for q in s["parts"]], 0.6, [q[2] for q in s["parts"]], bs)
        s["flash"] = s.get("flash", 0) * m.exp(-dt * 6)
        out += _blobs(np, idx, [c], 6.0, [(255, 240, 200)], [s["flash"]])
    if age > 2.5:                                          # candle-warm glow and a shining star
        warm = sdk.clamp((age - 2.5) / 3.0)
        flick = 0.85 + 0.15 * np.array([sdk.noise(i * 0.4, lt * 3) for i in range(n)])
        out += (flick * 0.3 * warm)[:, None] * np.array(sdk.kelvin(2300), float)
        glow = warm * (0.75 + 0.25 * sdk.wave(lt * 0.5))
        out += _blobs(np, idx, [c], 2.2, [(255, 190, 60)], [glow])
        if rng.random() < 0.25 * warm:
            j = int(c + rng.uniform(-6, 6))
            s["buf"][j] = np.maximum(s["buf"][j], (255, 230, 160))
    return out + s["buf"]


ACTS = {"snow": snow, "tree": tree, "candy": candy, "sleigh": sleigh, "finale": finale}


# ----------------------------------------------------------------------------- director
def setup(sdk):
    sdk.state.update(acts={}, seed=0)


def _run(name, inst, lt, dt, dur, n, sdk, a):
    """Render one act instance; a new instance (next loop) gets fresh state."""
    st = sdk.state
    s = st["acts"].get(name)
    if s is None or s["inst"] != inst:
        st["seed"] += 1
        s = {"inst": inst, "rng": sdk.rand(st["seed"])}
        st["acts"][name] = s
    return ACTS[name](lt, dt, dur, n, sdk, s, a)


def render(t, dt, n, sdk, params):
    np, a = sdk.np, sdk.audio
    pace = max(0.1, params["pace"])
    t, dt = t * pace, dt * pace
    durs = dict(SCENES)
    if params["scene"] in ACTS:
        name = params["scene"]
        dur = durs[name]
        out = _run(name, int(t // dur), t % dur, dt, dur, n, sdk, a)
        return np.clip(out, 0, 255).astype(np.uint8)

    # acts overlap by FADE seconds; the loop wraps so the finale fades into snowfall
    starts, acc = [], 0.0
    for _, d in SCENES:
        starts.append(acc)
        acc += d - FADE
    loop = acc
    ct = t % loop
    live = []
    for (name, d), s0 in zip(SCENES, starts):
        for shift in (0.0, loop):
            lt = ct + shift - s0
            if 0 <= lt < d and t - lt >= -1e-9:
                live.append((lt, name, d, int((t - lt) // loop)))
    live.sort(reverse=True)                                # oldest act first
    out = _run(live[0][1], live[0][3], live[0][0], dt, live[0][2], n, sdk, a)
    if len(live) > 1:
        lt, name, d, inst = live[1]
        w = sdk.ease_in_out(lt / FADE)
        out = out * (1 - w) + _run(name, inst, lt, dt, d, n, sdk, a) * w
    return np.clip(out, 0, 255).astype(np.uint8)
Fireflies Fireflies chase each other through a velvet night sky
View code
META = {
    "name": "fireflies",
    "audio": True,
    "description": "Fireflies chase each other through a velvet night sky: runners wander and dart, "
                   "chasers pursue with glowing trails; faint stars twinkle; beats make them flash in sync",
}
PARAMS = {
    "pairs": 3,          # runner/chaser pairs (1..6)
    "speed": 7.0,        # cruising speed, pixels per second
    "trail": 0.45,       # afterglow length, seconds
    "blink": 1.0,        # how much fireflies blink (0 = steady glow)
    "sky": 0.0,          # velvet sky brightness (0 = black)
}

FLY_COLORS = [(170, 255, 30), (255, 210, 40), (120, 255, 80), (220, 255, 60)]
SKY_DEEP = (3, 0, 12)
SKY_VELVET = (18, 3, 42)


def _wrap(d, n):
    return (d + n / 2) % n - n / 2


def _spawn(st, pairs, n):
    rng = st["rng"]
    flies = []
    for p in range(pairs):
        x = rng.random() * n
        heading = 1 if p % 2 == 0 else -1
        color = FLY_COLORS[p % len(FLY_COLORS)]
        flies.append(dict(x=x, v=0.0, runner=True, heading=heading, seed=p * 13.7, dart=0.0,
                          period=rng.uniform(1.6, 2.8), phase=rng.random(), color=color))
        flies.append(dict(x=(x - heading * rng.uniform(6, 14)) % n, v=0.0, runner=False,
                          prey=len(flies) - 1, seed=p * 13.7 + 6.1,
                          period=rng.uniform(1.6, 2.8), phase=rng.random(), color=color))
    st["flies"], st["pairs"] = flies, pairs


def setup(sdk):
    rng = sdk.rand(7)
    sdk.state.update(
        rng=rng, flies=[], pairs=0, flash=0.0,
        glow=sdk.np.zeros((sdk.n, 3)),
        stars=[(rng.randrange(sdk.n), rng.random()) for _ in range(9)],
    )


def render(t, dt, n, sdk, params):
    st, a, np, m = sdk.state, sdk.audio, sdk.np, sdk.math
    pairs = int(sdk.clamp(params["pairs"], 1, 6))
    if pairs != st["pairs"]:
        _spawn(st, pairs, n)
    flies = st["flies"]
    speed = max(0.5, params["speed"])
    ease = min(1.0, dt * 2.5)

    # --- movement: runners wander (and sometimes turn around), chasers pursue ---------------
    for f in flies:
        if f["runner"]:
            turn = 1 if sdk.noise(f["seed"] + 40, t * 0.04) > 0.42 else -1
            want = f["heading"] * turn * speed * (0.4 + 1.2 * sdk.noise(f["seed"], t * 0.3))
            want += f["dart"] * speed * 2.5
            f["dart"] *= m.exp(-dt * 2.0)
            f["v"] += (want - f["v"]) * ease
        else:
            prey = flies[f["prey"]]
            d = _wrap(prey["x"] - f["x"], n)
            jitter = (sdk.noise(f["seed"], t * 0.5) - 0.5) * speed
            want = max(-1.5 * speed, min(1.5 * speed, d * 1.1)) + jitter
            f["v"] += (want - f["v"]) * min(1.0, dt * 3.0)
            if abs(d) < 2.0 and abs(prey["dart"]) < 0.2:      # caught up: prey darts away
                prey["dart"] = 1.0 if d > 0 else -1.0
        f["x"] = (f["x"] + f["v"] * dt) % n

    # --- light: blinking bodies + afterglow --------------------------------------------------
    if a.beat and a.active:
        st["flash"] = 1.0
    st["flash"] *= m.exp(-dt * 4.0)
    idx = np.arange(n)
    new = np.zeros((n, 3))
    for f in flies:
        pulse = sdk.wave(t / f["period"] + f["phase"])
        b = 1.0 - params["blink"] * (0.82 - 0.82 * pulse ** 3)
        partner = flies[f["prey"]] if not f["runner"] else None
        if partner is not None:                                # excited glow when close
            b = max(b, 0.9 * sdk.clamp(1 - abs(_wrap(partner["x"] - f["x"], n)) / 8))
        b = max(b, 0.85 * st["flash"])
        dist = np.abs(_wrap(idx - f["x"], n))
        blob = np.exp(-(dist / 0.85) ** 2) * b
        new += blob[:, None] * np.array(f["color"], dtype=float)
    keep = m.exp(-dt / max(0.05, params["trail"]))
    st["glow"] = np.maximum(st["glow"] * keep, np.minimum(new, 255.0))

    # --- velvet sky with faint twinkling stars ---------------------------------------------
    sky = np.zeros((n, 3))
    for i in range(n):
        v = sdk.noise(i * 0.06, t * 0.05)
        sky[i] = sdk.blend(SKY_DEEP, SKY_VELVET, v)
    sky *= params["sky"]
    for i, s in st["stars"]:
        tw = 0.5 + 0.5 * m.sin(t * (0.6 + 1.4 * s) + s * 20.0)
        sky[i] += np.array((22.0, 22.0, 34.0)) * tw * tw * params["sky"]

    return np.clip(sky + st["glow"], 0, 255).astype(np.uint8)