Compare commits

..
Author SHA1 Message Date
shinyobjectz 053d780f31 The default mix's graph moves to raea-sys-tone, and its test to its own file, so raea-sys-mix is under 2000 lines
CI's size gate: raea-sys-mix was 2048 lines and offline.rs 530. DEFAULT_GRAPH, DEFAULT_DUCK_DB and default_bus are
the default Tone graph, so they live with the graph format in raea-sys-tone (defaults.rs) and raea-sys-mix re-exports
them; the duck test is duck_test.rs.
2026-11-30 15:03:08 -08:00
shinyobjectz dcfaaba739 The voice check judges the bed only on enough gaps between words
Body Shop's host-hook cut read "1.5 dB above what's under it" off a single 0.34 s gap between two "Mmm"s, where the
speaker was still humming; the agent's own measure (pauses of 0.8 s and more) read 11.7 dB. A tightly cut take has few
gaps, so the bed is judged only on 3 or more gaps and 1 s of them in all.
2026-11-30 14:51:23 -08:00
shinyobjectz 118b58f4de raea ducks music under the talking by default, and goal check holds the hook and the air between words
Shane 11-30: the StreetTalk cuts' music was "about 4 or 5 decibels too loud ... make sure standards and measurements
correctly mix by default to move audio down in the mix, especially while talking, but a CTA with no audio is fine";
Elfster's Voted cut opened on 1.5 s of a silent whiteboard ("a hook really should have audio and video stimulation");
and "measuring and cutting air gaps safely ... it CANNOT destroy words".

- systems/mix: an edit with no Tone graph gets DEFAULT_GRAPH: footage and voice files on a `talk` bus, effects on the
  master, any other audio file on a `bed` bus ducked DEFAULT_DUCK_DB (-6) under the talking, released where nobody
  talks. The names aren't raea/tone's, so an edit's own buses never change; `bus="master"` opts a sound out. Offline
  bounce and live play pick it the same way (score.rs routes a bus-less sound by default_bus). Test: the music sits
  6 dB down under the talk and comes back after it.
- @raea/video airgaps: airGaps(words) and tighten(words, { levels }): the spans of a take to keep, gaps cut to 0.15 s
  in the hook and 0.25 s after, only between words, 80 ms kept either side, each cut pulled back while the take is
  still loud (a transcript's early word end).
- goal packs hook and airgaps (cut and floor): a first word over 1 s in with a quiet opening is an error (Voted:
  1.5 s, -15 dB); gaps over 0.5 s in the first 3 s are errors, over 0.3 s warnings, over 0.8 s after warnings.
- sound pack: bus-less files classed as the mixer routes them (a music file with any name is music, not a voice
  line), the default duck counted, and music within 10 dB of the voice warns (was 6), as the voice pack does.
2026-11-30 14:46:02 -08:00
shinyobjectz ec691c7e8d raea goal check holds every size the brief asks for at done (sizes-all)
Shane 11-30: "it will show completed but what about doing all the resizes". Dutch finished on its 9:16 masters alone:
the brief's 4:5, 1:1 and 16:9 were never made, because one-size-first was a rule against resizing early and nothing
asked for the other sizes at the end. At done, every ad's newest version (adOf, _v#) must be in every format its
brief names (cut `formats`, the brief's and each cut's), unless a person's answer to the open item about "sizes"
names fewer. The finding says which sizes are missing and the file name each takes. test/sizes.test.ts.
2026-11-30 13:57:51 -08:00
shinyobjectz 7f8937d357 raea goal check times on-screen text against its words: the reading pack
Shane 11-30: "the words on screen relative to duration ... if a wordy CTA or component or scene is meant to be fully
read or if it just adds glossable content or context, and if it's on screen long enough to be read."

From the farm's texts, every line that isn't a caption (nor words shown as they're said) is followed frame to frame;
lines that come up together are one block. A block needs 0.5 s plus 3 words a second: under that a warning, under 60%
of it an error. A block of 25 words or more, small text (under 54 px of 1080x1920) or a phone's screen (a status-bar
clock) is texture: a warning that asks whether it's meant to be read. Frames with more than 6 lines (a shelf of
labels, an app shot whole) and blocks of 3 words or fewer are left out. Every finding gives words, seconds and words
a second.

Calibrated on the 8 Elfster/Body Shop cuts and 4 shipped refs: it finds Elfster cut 2's 15-word hook card up 1 s and
Body Shop's reaction CTA card (11 words, 2 s); the refs give one error (an Elfster app screen up 1 s). In cut and floor.
2026-11-30 13:32:00 -08:00
shinyobjectz 15be70a394 raea goal check reads an export's captions and hears its voice: captions and voice packs, and the farm reads text
Shane 11-30: "running a transcription and ocr pass on the final output ... catch if audio captions pick up something
else that's not supposed to be there or if we cut off words. as well we should be checking audio if it's too quiet
for dialogue". Elfster's cut 1 shipped hand-typed captions that dropped "when they get", "okay, this is" and
"organize your"; Body Shop's reaction cut buried the host 7 dB over its music. No check saw either.

captions (sdk/goal/src/packs/captions.ts): the farm's /v1/scene now reads each line of text (texts, RapidOCR
PP-OCRv4, Apache-2.0, about 0.13 s a 540-wide frame on CPU). A line is a caption when it fits what's said while
it's up with few edits (capitals, a badge's style, held stricter), lasts under 4.5 s, sits in a row with other
captions, in a frame with 3 lines or fewer, and the cut has a track of them (8 showings, 40% of the speech).
Shown-not-said: letters no word near it holds. Said-not-shown: words between captioned words that no caption has,
an error for 3 or more in a row where the captions are phrases; a line at a caption run's edge is a warning.
Calibrated on our 8 Elfster/Body Shop cuts and 4 shipped client refs: the refs' phrase captions pass clean but
one (Body Shop Video6's opening line under its hook card), and ours find what was found by hand.

voice (packs/voice.ts): on the export, the speech's level (80th percentile inside words) over the bed between
words: under 6 dB an error, under 10 a warning; each line against the typical line: 6 dB quieter an error, 4 a
warning. The 4 refs are clean; Elfster 2am (4.5 dB) and Body Shop edible (4.4) fail.

Both are in the cut and floor sets. The Scene type carries texts; media.ts passes them through. The farm needs a
deploy (rapidocr in the image) before captions reads anything; until then it notes the reader has no texts.
2026-11-30 13:20:47 -08:00
1268 changed files with 11 additions and 390844 deletions

No files matched your search

+2 -12
View File
@@ -2,7 +2,7 @@
title: "raea make component"
summary: "Copy a ready-made component or set into the project's components/, or the workspace's shared/components/, to use and change as your own."
order: 103
sources: ["engine/cli/src/index.ts", "engine/cli/src/registry.gen.ts", "engine/cli/src/catalog.ts"]
sources: ["engine/cli/src/index.ts", "engine/cli/src/registry.gen.ts"]
---
Components are ready-made pieces of a composition (captions, lower thirds, end cards and the like) and sets of them.
@@ -10,20 +10,10 @@ Components are ready-made pieces of a composition (captions, lower thirds, end c
never updates or overwrites it unasked. With `--shared` it goes into the workspace's `shared/components/` instead, for
every project to import as `@shared/components/NAME`. `raea part` is the old name and still works.
Beside raea's own sets is the library: several hundred open-source components (text reveals, counters, charts,
transitions, product-screen demos, game HUDs and more), sorted by what they're for rather than who made them.
`raea make component list` ends with its categories; `list WORDS` searches it by a category (`text`), a category and
type (`text/reveal`), or words in a name or description (`"count up"`). `add NAME` copies the component into
`components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's first line names
the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
```sh
raea make component list
raea make component add captions end-card
raea make component add reel --shared
raea make component list text/reveal
raea make component list count up
raea make component add soft-blur-in
```
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
@@ -31,7 +21,7 @@ raea make component add soft-blur-in
## Usage
```sh
raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, "count up")
raea make component list | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change)
```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
-48
View File
@@ -1,48 +0,0 @@
// The component library (sdk/raea/library/components, catalog.ts): every listed file is there, every relative import
// in it lands on a file of the library, nothing imports another video framework, and the search finds by use.
import { describe, expect, test } from "bun:test";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, normalize } from "node:path";
import { listed, type Item } from "../src/catalog";
const lib = join(import.meta.dir, "../../../sdk/raea/library/components");
const cat = JSON.parse(readFileSync(join(lib, "catalog.json"), "utf8")) as { sources: Record<string, { licence: string }>; items: Item[] };
describe("the component library", () => {
test("each item's files and the shared files it needs are there, and each item names a known source", () => {
const missing = cat.items.flatMap((i) => [...i.files, ...i.needs].filter((f) => !existsSync(join(lib, f))).map((f) => `${i.name}: ${f}`));
expect(missing).toEqual([]);
expect(cat.items.filter((i) => !cat.sources[i.from]?.licence).map((i) => i.name)).toEqual([]);
});
test("an item's relative imports land inside what it copies, and none is another framework's", () => {
const bad: string[] = [];
for (const i of cat.items) {
const copied = new Set([...i.files, ...i.needs]);
for (const f of i.files.concat(i.needs).filter((f) => /\.tsx?$/.test(f))) {
const src = readFileSync(join(lib, f), "utf8");
if (/from\s+["']@?remotion/.test(src)) bad.push(`${f}: imports remotion`);
// a package it imports is one `add` installs (its packages), or raea's own, or React
for (const [, pkg] of src.matchAll(/from\s+"([^".][^"]*)"/g)) if (!/^(raea|raea\/[\w/]+|react|react-dom)$/.test(pkg) && !(i.packages ?? []).includes(pkg)) bad.push(`${f}: imports ${pkg}, not in its packages`);
for (const [, spec] of src.matchAll(/(?:from\s+|import\s*\(?)"(\.[^"<]*)"/g)) {
const base = normalize(join(dirname(f), spec));
if (![base, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`, `${base}/index.tsx`].some((c) => copied.has(c))) bad.push(`${i.name}: ${f} -> ${spec}`);
}
}
}
expect(bad).toEqual([]);
});
test("names are unique, so `add NAME` means one thing", () => {
const names = cat.items.map((i) => i.name);
expect(names.filter((n, k) => names.indexOf(n) !== k)).toEqual([]);
});
test("search: a category, a category/type, and words in what it does", () => {
expect(listed(cat.items, [])).toContain("text");
expect(listed(cat.items, ["text/reveal"])).toContain("text/soft-blur-in");
expect(listed(cat.items, ["text/reveal"])).not.toContain("numbers/");
expect(listed(cat.items, ["count", "up"]).split("\n")[0]).toContain("count");
expect(listed(cat.items, ["zzqx"])).toContain("no component in the library");
});
});
-80
View File
@@ -1,80 +0,0 @@
// The component library (sdk/raea/library/components): other people's open components, sorted by what they're for,
// not by who wrote them. catalog.json lists each: its category and type, what it does, its own files, the shared files
// it needs, the fonts it loads and where it came from (CREDITS.md beside it holds the licences). `raea make component
// list WORDS` searches it and `raea make component add NAME` copies one into the project (index.ts). The host half
// (the files) runs on the native raea; the rest is plain strings.
import { existsSync, readFileSync, realpathSync } from "node:fs";
import { dirname, join } from "node:path";
export type Item = { name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string };
type Catalog = { sources: Record<string, { url: string; licence: string }>; items: Item[] };
export type Got = { item: Item; licence: string; files: Record<string, string> };
/** The library's folder: in RAEA_HOME, beside a release's bin/raea (share/raea), or in the tree a built raea is in */
function home(raea: string, env: Record<string, string | undefined>): string | undefined {
const bin = dirname(realpathSync(raea));
const rel = "sdk/raea/library/components";
return [env.RAEA_HOME && join(env.RAEA_HOME, rel), join(bin, "../share/raea", rel), join(bin, "../..", rel)].find((p) => p && existsSync(join(p, "catalog.json")));
}
/** Host op "components": {op: "list"} is every item, {op: "get", name} one item with its files' text (by its path in
* the library, which is its path under components/). No library beside this raea: an empty list, and no item. */
export function componentsHost(raea: string, env: Record<string, string | undefined>, a: Record<string, unknown>): Item[] | Got | null {
const dir = home(raea, env);
if (!dir) return a.op === "get" ? null : [];
const cat = JSON.parse(readFileSync(join(dir, "catalog.json"), "utf8")) as Catalog;
if (a.op !== "get") return cat.items;
const want = String(a.name).replace(/^\/+|\/+$/g, "");
const item = cat.items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
if (!item) return null;
const files = Object.fromEntries([...item.files, ...item.needs].map((f) => [f, readFileSync(join(dir, f), "utf8")]));
return { item, licence: cat.sources[item.from]?.licence ?? "", files };
}
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${i.says.split(". ")[0].slice(0, 110)}`;
/** `raea make component list`'s lines for the library: with no words, each category and its types; with words, the
* items they name. A word is a category ("text"), a category/type ("text/reveal"), or anything in a name or in what
* an item does; every word must be found, and a name's own words count first. */
export function listed(items: Item[], words: string[]): string {
if (!items.length) return "";
if (!words.length) {
const cats = [...new Set(items.map((i) => i.category))].sort();
const line = (c: string) => {
const of = items.filter((i) => i.category === c);
const types = [...new Set(of.map((i) => i.type))].sort().map((t) => `${t} ${of.filter((i) => i.type === t).length}`);
return `${c.padEnd(14)} ${String(of.length).padStart(3)} ${types.join(", ")}`;
};
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "count up"; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
}
const ws = words.join(" ").toLowerCase().split(/\s+/).filter(Boolean);
const phrase = ws.join(" ");
const score = (i: Item) => {
// the words together, as written, in what it does: ahead of the same words scattered
let s = ws.length > 1 && i.says.toLowerCase().includes(phrase) ? 3 : 0;
for (const w of ws) {
const [c, t] = w.split("/");
if (w.includes("/") ? i.category === c && (!t || i.type === t) : i.category === w || i.type === w) s += 4;
else if (i.name.split("-").includes(w)) s += 3;
else if (i.name.includes(w)) s += 2;
else if (i.says.toLowerCase().includes(w)) s += 1;
else return 0;
}
return s;
};
const found = items.map((i) => [score(i), i] as const).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0] || a[1].name.localeCompare(b[1].name));
if (!found.length) return `no component in the library for "${words.join(" ")}" (raea make component list shows the categories)\n`;
return found.map(([, i]) => row(i)).join("\n") + "\n";
}
/** What `add` says of a copied item: where it is, how to import it, the fonts it loads, whose it was */
export function added(g: Got, home: string, from: string, wrote: number, kept: number, installed = ""): string {
const i = g.item;
const pk = i.packages?.length ? `\n npm packages: ${i.packages.join(", ")}${installed ? ` (${installed})` : ` (not installed: raea add ${i.packages.join(" ")})`}` : "";
const shared = i.needs.length ? `, ${i.needs.length} shared under ${home}/_lib and beside it` : "";
const fonts = i.fonts.length ? `\n fonts: ${i.fonts.join(", ")} (loaded by name; set your brand's in its props or the file)` : "";
return `${home}/${i.category}/${i.name}/ ${i.files.length} files${shared}${kept ? ` (${kept} already here, kept)` : ""}; ${wrote} written
import ${i.default ? i.component : `{ ${i.component} }`} from "${from}/${i.category}/${i.name}"; (${i.says.split(". ")[0]})
its props and their defaults are at the top of index.tsx (or none: then its words and colours are in the file): the source's samples, make them the brief's${fonts}${pk}
from ${i.from}, ${g.licence}: yours to change; the first line of each file keeps the credit\n`;
}
+1 -1
View File
@@ -149,7 +149,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, format!("{GOAL_USAGE}\n {}", raea_app_make::USAGE), raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, \"count up\")\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
+3 -31
View File
@@ -27,8 +27,6 @@ import { libraryVerb } from "./library";
import { absolute, fromCwd, labelsIn, showVerb } from "./show";
// `raea make clothes` (clothes.ts): garments for SOMA's body from words
import { clothesVerb } from "./clothes";
// the component library (catalog.ts): open components sorted by use, listed and copied by `raea make component`
import { added, listed, type Got, type Item } from "./catalog";
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
import { bugVerb } from "./bug";
@@ -193,11 +191,8 @@ export function raeaHandler(host?: Host, engine?: Engine) {
// LY4), or with --shared into the workspace's shared/components/, which every project imports as @shared/components/
case "component": {
const was = "";
// the library beside this raea (none in a shell with no host: raea's own sets are all it lists)
const shelf = (): Item[] => (host ? (host("components", { op: "list" }) as Item[]) : []);
if (args[1] === undefined) return out(parts() + listed(shelf(), []), 0, was);
if (args[1] === "list") return out(clean(args.slice(2)).length ? listed(shelf(), clean(args.slice(2))) : parts() + listed(shelf(), []), 0, was);
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force]\n`);
if (args[1] === "list" || args[1] === undefined) return out(parts(), 0, was);
if (args[1] !== "add") return out("", 2, `${was}raea make component list | raea make component add NAME ... [--shared] [--force]\n`);
const names = clean(args.slice(2));
if (!names.length) return out("", 2, `${was}raea make component add NAME ... (raea make component list shows them)\n`);
const force = args.includes("--force");
@@ -225,30 +220,7 @@ export function raeaHandler(host?: Host, engine?: Engine) {
continue;
}
const src = single(n);
// a library component: its folder under components/CATEGORY/NAME/, with the shared files it needs
const got = src || !host ? null : (host("components", { op: "get", name: n }) as Got | null);
if (got) {
let wrote = 0;
let kept = 0;
for (const [f, text] of Object.entries(got.files)) {
const dest = p(`${home}/${f}`);
if (!force && (await c.fs.exists(dest))) kept++;
else {
await c.fs.mkdir(dest.slice(0, dest.lastIndexOf("/")), { recursive: true });
await c.fs.writeFile(dest, text);
wrote++;
}
}
// its npm packages (culori and the like), installed by the engine's package manager when there is one
let installed = "";
if (got.item.packages?.length && engine) {
const r = await native(["add", ...got.item.packages]);
installed = r.exitCode ? `raea add failed: ${(r.stderr || r.stdout).trim().split("\n")[0]}` : "installed";
}
done.push(added(got, absolute(home) ? "shared/components" : home, from, wrote, kept, installed));
continue;
}
if (!src) return out(done.join(""), 1, `raea make component add: no component or set "${n}" (raea make component list shows them, list WORDS searches the library)\n`);
if (!src) return out(done.join(""), 1, `raea make component add: no component or set "${n}" (raea make component list shows them)\n`);
const dest = p(`${home}/${n}.tsx`);
if (!force && (await c.fs.exists(dest))) {
done.push(`${shown(`${home}/${n}.tsx`)} is already here (yours now; --force replaces it)\n`);
-3
View File
@@ -13,7 +13,6 @@ import { wordsOf } from "./heard";
import { harness, library, show, task } from "./app";
import { fromCwd } from "./show";
import { clothesHost } from "./wardrobe";
import { componentsHost } from "./catalog";
import { raeaHandler, type Engine, type Host } from "./index";
const [raea, ...args] = process.argv.slice(2);
@@ -427,8 +426,6 @@ const host: Host = (op, a) => {
return playable(a as { file: string });
case "clothes":
return clothesHost(raea, cwd, process.env, a);
case "components":
return componentsHost(raea, process.env, a);
case "bug":
return bug(a as { report: Record<string, unknown>; dry?: boolean });
case "harness":
+3 -6
View File
@@ -11,12 +11,9 @@ docs/components.md in the raea repository.
1. **List the components before writing any.** From the brief (and its story, and each hero's `NAME.parts.ts`), name
every thing the piece needs as a component: `Kitchen`, `Kettle`, `Steam`, `BrushedSteel`, `MorningLook`,
`PriceCard`. One component is one concern: one object, one surface, one effect, one card.
2. **Look before making.** `raea make component list` shows raea's own and the library's categories; `raea make
component list WORDS` searches the library by what a piece is for (`text/reveal`, `numbers/counter`, `transitions`,
`"count up"`): several hundred open-source text reveals, counters, charts, logo stings, HUDs and screen demos. A
project's `components/` and the workspace's `shared/components/` hold what this person already has; `raea library
search "WORDS"` finds their assets. Interface pieces (forms, tables, dashboards) come from shadcn, never rebuilt:
see "shadcn" below. A library piece arrives with its source's sample words, colours and fonts: pass the brief's.
2. **Look before making.** `raea make component list` shows raea's own; a project's `components/` and the workspace's
`shared/components/` hold what this person already has; `raea library search "WORDS"` finds their assets. Interface
pieces (forms, tables, charts, dashboards) come from shadcn, never rebuilt: see "shadcn" below.
3. **Add, then adapt.** `raea make component add NAME` copies a component into `components/` (`--shared` into the
workspace's `shared/components/`, imported as `@shared/components/NAME`). It's the project's own once copied: change
it freely. Nothing updates it behind your back.
-45
View File
@@ -1,45 +0,0 @@
# Credits
The components in this folder come from other people's open libraries, sorted here by what they're used for.
Each file's first line names its source; catalog.json's `from` does the same per component.
## React Video Editor's free templates
https://github.com/reactvideoeditor/remotion-templates. Its README: "All templates in this repository are available
under the MIT License. You can use them in personal and commercial projects, but attribution is appreciated where
applicable." (the repository has no LICENSE file of its own). Created by the team at https://www.reactvideoeditor.com.
Changed for raea: imports, and the header comment replaced by this credit.
## snapcn
https://github.com/shadcn-labs/snapcn, MIT, Copyright (c) 2026 Sri Nath (snap-cn). Changed for raea: imports, fonts
(raea/text's loadFont), Remotion's getRemotionEnvironment replaced by a stand-in (_lib/snapcn/lib/raea-env.ts), and
shadcn's cn by a plain join (_lib/snapcn/lib/utils.ts). Some need npm packages (culori), which `raea make component add`
installs.
## remocn
https://github.com/Remocn/remocn, MIT. Changed for raea: imports (raea's own names for the frame, the
clock and the layout pieces), fonts (raea/text's loadFont), and one glyph helper replaced by a no-op.
MIT License
Copyright (c) 2026 Remocn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because it is too large. Load diff
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Afacad";
export const loadFont = (..._: unknown[]) => ({ ...load("Afacad"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Albert Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("Albert Sans"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Anton";
export const loadFont = (..._: unknown[]) => ({ ...load("Anton"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Antonio";
export const loadFont = (..._: unknown[]) => ({ ...load("Antonio"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Archivo";
export const loadFont = (..._: unknown[]) => ({ ...load("Archivo"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Archivo Narrow";
export const loadFont = (..._: unknown[]) => ({ ...load("Archivo Narrow"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Arimo";
export const loadFont = (..._: unknown[]) => ({ ...load("Arimo"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Azeret Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("Azeret Mono"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Barlow Condensed";
export const loadFont = (..._: unknown[]) => ({ ...load("Barlow Condensed"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Big Shoulders";
export const loadFont = (..._: unknown[]) => ({ ...load("Big Shoulders"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Bitter";
export const loadFont = (..._: unknown[]) => ({ ...load("Bitter"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Bricolage Grotesque";
export const loadFont = (..._: unknown[]) => ({ ...load("Bricolage Grotesque"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Caveat";
export const loadFont = (..._: unknown[]) => ({ ...load("Caveat"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Chakra Petch";
export const loadFont = (..._: unknown[]) => ({ ...load("Chakra Petch"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "DMSans";
export const loadFont = (..._: unknown[]) => ({ ...load("DMSans"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Epilogue";
export const loadFont = (..._: unknown[]) => ({ ...load("Epilogue"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Familjen Grotesk";
export const loadFont = (..._: unknown[]) => ({ ...load("Familjen Grotesk"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Figtree";
export const loadFont = (..._: unknown[]) => ({ ...load("Figtree"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Fraunces";
export const loadFont = (..._: unknown[]) => ({ ...load("Fraunces"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Fredoka";
export const loadFont = (..._: unknown[]) => ({ ...load("Fredoka"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Funnel Display";
export const loadFont = (..._: unknown[]) => ({ ...load("Funnel Display"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Gabarito";
export const loadFont = (..._: unknown[]) => ({ ...load("Gabarito"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Geist";
export const loadFont = (..._: unknown[]) => ({ ...load("Geist"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Geist Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("Geist Mono"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Geologica";
export const loadFont = (..._: unknown[]) => ({ ...load("Geologica"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Gloock";
export const loadFont = (..._: unknown[]) => ({ ...load("Gloock"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Golos Text";
export const loadFont = (..._: unknown[]) => ({ ...load("Golos Text"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Hanken Grotesk";
export const loadFont = (..._: unknown[]) => ({ ...load("Hanken Grotesk"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Hubot Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("Hubot Sans"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "IBMPlex Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("IBMPlex Mono"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "IBMPlex Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("IBMPlex Sans"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Instrument Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("Instrument Sans"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Instrument Serif";
export const loadFont = (..._: unknown[]) => ({ ...load("Instrument Serif"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Inter";
export const loadFont = (..._: unknown[]) => ({ ...load("Inter"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Inter Tight";
export const loadFont = (..._: unknown[]) => ({ ...load("Inter Tight"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Jet Brains Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("Jet Brains Mono"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Lexend";
export const loadFont = (..._: unknown[]) => ({ ...load("Lexend"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Lexend Exa";
export const loadFont = (..._: unknown[]) => ({ ...load("Lexend Exa"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Manrope";
export const loadFont = (..._: unknown[]) => ({ ...load("Manrope"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Newsreader";
export const loadFont = (..._: unknown[]) => ({ ...load("Newsreader"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Nunito";
export const loadFont = (..._: unknown[]) => ({ ...load("Nunito"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Onest";
export const loadFont = (..._: unknown[]) => ({ ...load("Onest"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Oswald";
export const loadFont = (..._: unknown[]) => ({ ...load("Oswald"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Outfit";
export const loadFont = (..._: unknown[]) => ({ ...load("Outfit"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Playfair Display";
export const loadFont = (..._: unknown[]) => ({ ...load("Playfair Display"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Plus Jakarta Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("Plus Jakarta Sans"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Red Hat Display";
export const loadFont = (..._: unknown[]) => ({ ...load("Red Hat Display"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Rubik";
export const loadFont = (..._: unknown[]) => ({ ...load("Rubik"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Saira";
export const loadFont = (..._: unknown[]) => ({ ...load("Saira"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Schibsted Grotesk";
export const loadFont = (..._: unknown[]) => ({ ...load("Schibsted Grotesk"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Silkscreen";
export const loadFont = (..._: unknown[]) => ({ ...load("Silkscreen"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Sora";
export const loadFont = (..._: unknown[]) => ({ ...load("Sora"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Source Serif 4";
export const loadFont = (..._: unknown[]) => ({ ...load("Source Serif 4"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Space Grotesk";
export const loadFont = (..._: unknown[]) => ({ ...load("Space Grotesk"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Space Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("Space Mono"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Syne";
export const loadFont = (..._: unknown[]) => ({ ...load("Syne"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Tektur";
export const loadFont = (..._: unknown[]) => ({ ...load("Tektur"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Unbounded";
export const loadFont = (..._: unknown[]) => ({ ...load("Unbounded"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Young Serif";
export const loadFont = (..._: unknown[]) => ({ ...load("Young Serif"), waitUntilDone: () => Promise.resolve() });
@@ -1,4 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Zen Kaku Gothic New";
export const loadFont = (..._: unknown[]) => ({ ...load("Zen Kaku Gothic New"), waitUntilDone: () => Promise.resolve() });
@@ -1,72 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../CREDITS.md. Changed for raea: imports and fonts.
import { useMemo } from "react";
import { useCurrentFrame, useVideoConfig } from "raea";
// Every timing in remocn is written in frames of a 30 fps timeline: a delay
// of 12, a rise over 20, a spring fed `fps`. Read straight from Remotion,
// those numbers mean something else in a 60 fps composition: a tween runs
// twice as fast, while a spring keeps its length, so a scene does not even
// speed up evenly.
//
// These two hooks stand in for Remotion's and answer on that 30 fps timeline
// whatever rate the composition runs at. At 60 fps the frame goes 0, 0.5, 1,
// 1.5: the scene lasts the same number of seconds and every frame in between
// is a new picture. At 30 fps they return exactly what Remotion does.
//
// const frame = useSceneFrame();
// const { fps, width } = useSceneConfig();
//
// What a component hands back to Remotion is still counted in the
// composition's own frames: `from` and `durationInFrames` of a `<Sequence>`,
// the length of a transition. `useCompositionFrames()` converts those.
/** The frame rate remocn timings are written in. */
export const SCENE_FPS = 30;
/** `useCurrentFrame()` in 30 fps frames; fractional above 30 fps. */
export function useSceneFrame(): number {
const { fps } = useVideoConfig();
return (useCurrentFrame() * SCENE_FPS) / fps;
}
/**
* `useVideoConfig()` on the 30 fps timeline: `fps` is 30 and
* `durationInFrames` counts 30 fps frames. Size and the rest are untouched.
*/
export function useSceneConfig(): ReturnType<typeof useVideoConfig> {
const config = useVideoConfig();
return useMemo(
() => ({
...config,
fps: SCENE_FPS,
durationInFrames: (config.durationInFrames * SCENE_FPS) / config.fps,
}),
[config],
);
}
/**
* Turns a count of 30 fps frames into the composition's own, for what
* Remotion itself reads: `<Sequence from={frames(24)}>`. Whole frames only,
* as Remotion requires.
*/
export function useCompositionFrames(): (sceneFrames: number) => number {
const { fps } = useVideoConfig();
return useMemo(
() => (sceneFrames: number) => Math.round((sceneFrames * fps) / SCENE_FPS),
[fps],
);
}
/**
* The other way round: a count Remotion gives a component in the
* composition's own frames, in 30 fps frames. A transition's presentation
* gets its length that way (`presentationDurationInFrames`).
*/
export function useSceneFrameCount(): (compositionFrames: number) => number {
const { fps } = useVideoConfig();
return useMemo(
() => (compositionFrames: number) => (compositionFrames * SCENE_FPS) / fps,
[fps],
);
}
@@ -1,3 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../CREDITS.md. Changed for raea: imports and fonts.
// remocn's glide works around Chrome's glyph rasteriser; raea draws text itself, so it adds nothing.
export const useGlide = () => (_moving: boolean) => "";
@@ -1,90 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
/**
* The seam between live gradients (mount.ts, scheduler.ts) and the GPU API
* that draws them. A backend hands out leases: a renderer drawing into an
* offscreen canvas that the mount copies onto its own 2D canvas. Because the
* visible canvas only ever holds a 2D context, switching backends (or losing
* one mid-session) never touches the DOM, and the last frame stays on screen.
*
* Two backends: WebGPU (webgpu.ts), chosen per kind when the page passed
* its adapter checks and the kind has a WGSL twin that compiled, and WebGL2
* (pool.ts) for everything else. A WebGPU kind still compiling, or a page
* still probing, gets no lease yet; the scheduler retries when WebGPU
* reports a change.
*
* Exports do not go through a backend; they use export.ts (WebGL) directly.
*/
import { acquireContext, releaseContext, webglUnsupported } from "./pool";
import type { AnyCanvas, ColorResolver } from "./renderer";
import type {
FrameInput,
GradientKind,
GradientParams,
RenderTarget,
} from "./types";
import {
acquireSurface,
releaseSurface,
webgpuStatus,
webgpuUnsupported,
} from "./webgpu";
export type BackendName = "webgl2" | "webgpu";
/** One leased renderer. Stays with its backend between leases, so `loaded` survives. */
export interface BackendLease {
/** Where frames land; the mount copies from it with drawImage. */
readonly canvas: AnyCanvas;
/** First row of the frame in `canvas` (a WebGPU lease may draw a spare row above it). */
readonly sourceY: number;
/** Colour resolver used by the renderer; set by the current leaseholder. */
resolver: ColorResolver;
/** Which params (owner and version) the renderer was last loaded with. */
loaded: { owner: object; version: number } | null;
setParams(params: GradientParams): void;
renderFrame(frame: FrameInput, target: RenderTarget): void;
/** True once the GPU resources are gone; the canvas then holds no new frame. */
isLost(): boolean;
}
export interface GradientBackend {
readonly name: BackendName;
/** Whether this backend can draw the kind right now; mounts check it before acquiring. */
supports(kind: GradientKind): boolean;
/**
* Leases a renderer, or null when the budget is used up or the backend
* cannot run. `onLost` runs if the lease is lost; it has ended by then.
* `pixels` is the size the lease will render at, for memory caps.
*/
acquire(onLost?: (() => void) | null, pixels?: number): BackendLease | null;
release(lease: BackendLease): void;
/** True once this backend has failed for good on this page. */
unsupported(): boolean;
}
export const webglBackend: GradientBackend = {
acquire: (onLost = null) => acquireContext(onLost),
name: "webgl2",
// Only ever handed its own pooled contexts back.
release: releaseContext,
supports: () => true,
unsupported: webglUnsupported,
};
export const webgpuBackend: GradientBackend = {
acquire: (onLost = null, pixels = 0) => acquireSurface(onLost, pixels),
name: "webgpu",
release: releaseSurface,
// Ready to draw now: probed, and the kind's pipeline compiled.
supports: (kind) => webgpuStatus(kind) === "ready",
unsupported: webgpuUnsupported,
};
/**
* The backend that draws `kind` on this page: WebGPU unless the
* preference, the adapter, the probes, the kind (no WGSL, or it failed to
* compile) or a device loss rule it out.
*/
export function backendFor(kind: GradientKind): GradientBackend {
return webgpuStatus(kind) === "unavailable" ? webglBackend : webgpuBackend;
}
@@ -1,190 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
export type Rgb = readonly [number, number, number];
export type Oklab = readonly [number, number, number];
const FALLBACK_RGB: Rgb = [0.5, 0.5, 0.5];
function srgbToLinear(c: number): number {
return c <= 0.040_45 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
}
function linearToSrgb(c: number): number {
return c <= 0.003_130_8 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
}
/** sRGB (0-1, gamma encoded) to OKLab. */
export function srgbToOklab(rgb: Rgb): Oklab {
const r = srgbToLinear(rgb[0]);
const g = srgbToLinear(rgb[1]);
const b = srgbToLinear(rgb[2]);
const l = Math.cbrt(
0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b,
);
const m = Math.cbrt(
0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b,
);
const s = Math.cbrt(
0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b,
);
return [
0.210_454_255_3 * l + 0.793_617_785 * m - 0.004_072_046_8 * s,
1.977_998_495_1 * l - 2.428_592_205 * m + 0.450_593_709_9 * s,
0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766 * s,
];
}
/** OKLab to sRGB (0-1, gamma encoded, clamped). */
export function oklabToSrgb(lab: Oklab): Rgb {
const l = (lab[0] + 0.396_337_777_4 * lab[1] + 0.215_803_757_3 * lab[2]) ** 3;
const m = (lab[0] - 0.105_561_345_8 * lab[1] - 0.063_854_172_8 * lab[2]) ** 3;
const s = (lab[0] - 0.089_484_177_5 * lab[1] - 1.291_485_548 * lab[2]) ** 3;
const out = [
4.076_741_662_1 * l - 3.307_711_591_3 * m + 0.230_969_929_2 * s,
-1.268_438_004_6 * l + 2.609_757_401_1 * m - 0.341_319_396_5 * s,
-0.004_196_086_3 * l - 0.703_418_614_7 * m + 1.707_614_701 * s,
].map((c) => Math.min(1, Math.max(0, linearToSrgb(c))));
return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
}
const HEX_RE = /^#([0-9a-f]{3,8})$/i;
const RGB_RE = /^rgba?\(\s*([^)]+)\)$/i;
function parseChannel(token: string): number | null {
const value = Number.parseFloat(token);
if (Number.isNaN(value)) {
return null;
}
return token.endsWith("%") ? value / 100 : value / 255;
}
/** Parses hex and rgb() colours without a DOM. Returns null for anything else. */
export function parseColorLiteral(value: string): Rgb | null {
const input = value.trim();
const hex = HEX_RE.exec(input)?.[1];
if (hex) {
const full = hex.length <= 4 ? [...hex].map((ch) => ch + ch).join("") : hex;
if (full.length !== 6 && full.length !== 8) {
return null;
}
return [
Number.parseInt(full.slice(0, 2), 16) / 255,
Number.parseInt(full.slice(2, 4), 16) / 255,
Number.parseInt(full.slice(4, 6), 16) / 255,
];
}
const body = RGB_RE.exec(input)?.[1];
if (body) {
const parts = body
.split(/[\s,/]+/)
.filter(Boolean)
.slice(0, 3);
const channels = parts.map(parseChannel);
const [r, g, b] = channels;
if (channels.length === 3 && r != null && g != null && b != null) {
return [r, g, b];
}
}
return null;
}
type Probe = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
let probe: Probe | null | undefined;
function getProbe(): Probe | null {
if (probe !== undefined) {
return probe;
}
probe = null;
// OffscreenCanvas first: it works in Workers and never touches document.
if (typeof OffscreenCanvas !== "undefined") {
probe = new OffscreenCanvas(1, 1).getContext("2d", {
willReadFrequently: true,
});
} else if (typeof document !== "undefined") {
const canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
probe = canvas.getContext("2d", { willReadFrequently: true });
}
return probe;
}
/** Lets the browser parse any CSS colour (oklch, hsl, names...) by painting one pixel. */
function probeColor(value: string): Rgb | null {
const ctx = getProbe();
if (!ctx) {
return null;
}
const sentinel = "#010203";
ctx.fillStyle = sentinel;
ctx.fillStyle = value;
if (ctx.fillStyle === sentinel && value.trim().toLowerCase() !== sentinel) {
return null;
}
ctx.clearRect(0, 0, 1, 1);
ctx.fillRect(0, 0, 1, 1);
const [r = 0, g = 0, b = 0] = ctx.getImageData(0, 0, 1, 1).data;
return [r / 255, g / 255, b / 255];
}
const VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*([\s\S]+))?\)$/;
/** Expands var(--x) (with fallbacks, nested) against an element's computed style. */
export function resolveCssVariables(
value: string,
scope: Element | null,
depth = 0,
): string {
const match = VAR_RE.exec(value.trim());
if (!match || depth > 8) {
return value.trim();
}
const [, name = "", fallback] = match;
const resolved =
scope && typeof getComputedStyle !== "undefined"
? getComputedStyle(scope).getPropertyValue(name).trim()
: "";
if (resolved) {
return resolveCssVariables(resolved, scope, depth + 1);
}
return fallback ? resolveCssVariables(fallback, scope, depth + 1) : "";
}
const literalCache = new Map<string, Rgb>();
/** Resolves any CSS colour, including var(--x), to sRGB. Unknown colours become mid grey. */
export function resolveColor(value: string, scope: Element | null): Rgb {
const literal = resolveCssVariables(value, scope);
const cached = literalCache.get(literal);
if (cached) {
return cached;
}
const rgb = parseColorLiteral(literal) ?? probeColor(literal) ?? FALLBACK_RGB;
if (literalCache.size > 256) {
literalCache.clear();
}
literalCache.set(literal, rgb);
return rgb;
}
export function hasCssVariable(values: readonly string[]): boolean {
return values.some((value) => value.includes("var("));
}
function toHex(rgb: Rgb): string {
return `#${rgb
.map((channel) =>
Math.round(Math.min(1, Math.max(0, channel)) * 255)
.toString(16)
.padStart(2, "0"),
)
.join("")}`;
}
/** Resolves any CSS colour (var(), oklch, names...) to a concrete #rrggbb. */
export function resolveColorToHex(
value: string,
scope: Element | null,
): string {
return toHex(resolveColor(value, scope));
}
@@ -1,201 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import {
hasCssVariable,
resolveColor,
resolveColorToHex,
srgbToOklab,
} from "./color";
import { normalizeParams } from "./params";
import type { AnyCanvas, ColorResolver } from "./renderer";
import { createWebGLRenderer, getWebGL2 } from "./renderer";
import type { GradientParams, GradientRenderer } from "./types";
/** What the GPU allows for one export tile. Every tile edge must be at most `maxTileSize`. */
export interface ExportLimits {
/** Largest square tile this renderer can draw: the smallest of the limits below (and the requested size). */
maxTileSize: number;
maxTextureSize: number;
maxRenderbufferSize: number;
maxViewportDims: readonly [number, number];
}
export interface ExportRenderer extends GradientRenderer {
readonly limits: ExportLimits;
}
function queryLimits(
gl: WebGL2RenderingContext,
): Omit<ExportLimits, "maxTileSize"> {
const viewport: unknown = gl.getParameter(gl.MAX_VIEWPORT_DIMS);
const dims =
viewport instanceof Int32Array && viewport.length >= 2
? ([viewport[0] ?? 0, viewport[1] ?? 0] as const)
: ([0, 0] as const);
return {
maxRenderbufferSize: Number(gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)) || 0,
maxTextureSize: Number(gl.getParameter(gl.MAX_TEXTURE_SIZE)) || 0,
maxViewportDims: dims,
};
}
function tileLimit(
limits: Omit<ExportLimits, "maxTileSize">,
requested: number,
): number {
return Math.max(
1,
Math.min(
Math.floor(requested),
limits.maxTextureSize,
limits.maxRenderbufferSize,
limits.maxViewportDims[0],
limits.maxViewportDims[1],
),
);
}
function createExportCanvas(): AnyCanvas {
// Start at 1x1: a huge requested size can fail before limits are known.
if (typeof OffscreenCanvas !== "undefined") {
return new OffscreenCanvas(1, 1);
}
if (typeof document !== "undefined") {
return document.createElement("canvas");
}
throw new Error("Export needs OffscreenCanvas or a document");
}
let cachedLimits: Omit<ExportLimits, "maxTileSize"> | null = null;
/**
* The GPU's export limits, so an export UI can offer only tile and image
* sizes that will work. Probes once with a throwaway context, then caches.
* Pass the tile size you want; `maxTileSize` comes back clamped.
*/
export function getExportLimits(requestedTileSize = 2048): ExportLimits {
if (!cachedLimits) {
const canvas = createExportCanvas();
const gl = getWebGL2(canvas, { preserveDrawingBuffer: false });
if (!gl) {
throw new Error("WebGL2 is not available for export");
}
cachedLimits = queryLimits(gl);
gl.getExtension("WEBGL_lose_context")?.loseContext();
}
return {
...cachedLimits,
maxTileSize: tileLimit(cachedLimits, requestedTileSize),
};
}
/**
* Returns params whose colours are concrete #rrggbb values. Run it on the
* main thread before handing params to a Worker: var(--x) needs
* getComputedStyle, which Workers don't have. `element` scopes the
* variables (default <html>).
*/
export function resolveParamsColors(
params: GradientParams,
element?: Element,
): GradientParams {
const scope =
element ??
(typeof document === "undefined" ? null : document.documentElement);
if (!scope && hasCssVariable([...params.colors, params.background])) {
throw new Error(
"resolveParamsColors: var() colours need a document; call it on the main thread",
);
}
return {
...params,
background: resolveColorToHex(params.background, scope),
colors: params.colors.map((color) => resolveColorToHex(color, scope)),
};
}
/**
* Concrete colours never touch document or getComputedStyle. var() colours
* are resolved against <html> when a document exists, and are an error in a
* Worker.
*/
const exportColorResolver: ColorResolver = (value) => {
if (hasCssVariable([value])) {
if (typeof document === "undefined") {
throw new Error(
`createExportRenderer: unresolved colour "${value}" and no document. Call resolveParamsColors(params) on the main thread first.`,
);
}
return srgbToOklab(resolveColor(value, document.documentElement));
}
return srgbToOklab(resolveColor(value, null));
};
/**
* Offscreen renderer for exports: preserveDrawingBuffer on, no listeners, no
* DPR logic. Works in a Worker when params have concrete colours (see
* resolveParamsColors). The tile size is clamped to the GPU's texture,
* renderbuffer and viewport limits; read the result from `limits`.
*/
export function createExportRenderer(
params: GradientParams,
maxTileSize = 2048,
): ExportRenderer {
// New pinned paths must complete an integer number of laps over the export
// loop. Legacy params omit drift and retain their exact historical frames.
const normalized = normalizeParams(params);
const exportParams =
normalized.drift === undefined
? normalized
: { ...normalized, speed: Math.round(normalized.speed) };
const canvas = createExportCanvas();
const gl = getWebGL2(canvas, { preserveDrawingBuffer: true });
if (!gl) {
throw new Error("WebGL2 is not available for export");
}
const queried = queryLimits(gl);
cachedLimits ??= queried;
const limits: ExportLimits = {
...queried,
maxTileSize: tileLimit(queried, maxTileSize),
};
const size = limits.maxTileSize;
canvas.width = size;
canvas.height = size;
let renderer: ReturnType<typeof createWebGLRenderer>;
try {
renderer = createWebGLRenderer({
canvas,
gl,
params: exportParams,
resolveColor: exportColorResolver,
});
} catch (error) {
gl.getExtension("WEBGL_lose_context")?.loseContext();
throw error;
}
const live = renderer;
return {
canvas,
destroy() {
live.destroy();
gl.getExtension("WEBGL_lose_context")?.loseContext();
},
limits,
renderFrame(frame, target) {
if (target && (target.width > size || target.height > size)) {
throw new RangeError(
`Tile ${target.width}x${target.height} exceeds the export tile limit ${size} (GPU max texture ${limits.maxTextureSize}, renderbuffer ${limits.maxRenderbufferSize}, viewport ${limits.maxViewportDims.join("x")})`,
);
}
live.renderFrame(
{
frameIndex: frame.frameIndex,
timeSeconds: frame.timeSeconds,
frameRate: frame.frameRate,
},
target,
);
},
setParams: (patch) => live.setParams(patch),
};
}
@@ -1,22 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import { getKind } from "./kinds";
import type { GradientParams } from "./types";
function grainLayer(amount: number): string {
const opacity = (0.06 + amount * 0.16).toFixed(3);
const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 ${opacity}'/></filter><rect width='100%' height='100%' filter='url(#n)'/></svg>`;
return `url("data:image/svg+xml,${encodeURIComponent(svg)}") 0 0 / 180px 180px repeat`;
}
/**
* A CSS `background` value that resembles the gradient: layered radial and
* linear gradients built from the same colours, so pages never show a blank
* box. var(--x) colours are kept as-is and follow the theme natively.
*/
export function staticFallbackCss(p: GradientParams): string {
const layers = getKind(p.kind).fallbackLayers(p.colors, p.background);
if (p.grain >= 0.2) {
layers.unshift(grainLayer(p.grain));
}
return [...layers, p.background].join(", ");
}
@@ -1,44 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
export type { ExportLimits, ExportRenderer } from "./export";
export {
createExportRenderer,
getExportLimits,
resolveParamsColors,
} from "./export";
export { staticFallbackCss } from "./fallback";
export type { GradientKindDefinition } from "./kind";
export { getKind, kindDefaults, listKinds, registerKind } from "./kinds";
export {
LOOP_RADIUS,
loopPhase,
loopVector,
loopVectorAtPhase,
splitTiles,
videoFrameTimes,
} from "./loop";
export type { MountedGradient, MountOptions } from "./mount";
export { mountGradient } from "./mount";
export {
defaultParams,
mergeParams,
normalizeParams,
parseParams,
serializeParams,
} from "./params";
export {
contextStats,
MAX_LIVE_CONTEXTS,
PIXEL_BUDGET,
PRIMARY_PIXEL_BUDGET,
paceStats,
resetPace,
setPixelBudget,
takePaintStats,
} from "./scheduler";
export type {
FrameInput,
GradientKind,
GradientParams,
GradientRenderer,
RenderTarget,
} from "./types";
@@ -1,55 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientParams } from "./types";
/**
* One gradient kind. `glsl` defines `vec3 kindColor(vec2 p, vec2 uv)` and
* returns OKLab. `p` is centred, y up, with the short side spanning -0.5..0.5;
* `uv` is 0..1 from the top left. Use loopNoise/fbm/u_loop for motion, never
* raw time, so the loop stays seamless.
*/
export interface GradientKindDefinition {
readonly name: string;
readonly label: string;
readonly description: string;
/** Hand-tuned params for this kind. */
readonly defaults: Omit<GradientParams, "kind">;
readonly glsl: string;
/**
* Optional WGSL twin of `glsl`: `fn kindColor(p: vec2f, uv: vec2f) -> vec3f`,
* same maths, against shaders/wgsl-common.ts. Kinds with it can render on
* WebGPU (and in Node); kinds without it always render with WebGL.
*
* A loader, not the source: keep the WGSL in its own module and return
* `import("./wgsl/<kind>").then((module) => module.wgsl)`, so bundlers
* split it out and only pages that pick WebGPU download it.
*/
readonly wgsl?: () => Promise<string>;
/**
* Set when `wgsl` uses fwidth/dpdx/dpdy. Screen-space derivatives come
* from 2x2 quads whose choice of row is driver-defined, so such a kind is
* near-exact against WebGL in the browser (checked with a tolerance in
* the engine lab tests) rather than bit-exact, and Node keeps rendering
* it through Chrome.
*/
readonly wgslUsesDerivatives?: true;
/** CSS background layers (without the base colour) that resemble the kind. */
readonly fallbackLayers: (
colors: readonly string[],
background: string,
) => string[];
}
/** Picks colour i, cycling when the palette is shorter. */
export function pick(colors: readonly string[], i: number): string {
return colors[i % colors.length] ?? "transparent";
}
/** Evenly spaced colour stops for CSS gradients. */
export function stops(colors: readonly string[], from = 0, to = 100): string {
const last = Math.max(1, colors.length - 1);
return colors
.map(
(color, i) => `${color} ${(from + ((to - from) * i) / last).toFixed(1)}%`,
)
.join(", ");
}
@@ -1,78 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "./kind";
import { aurora } from "./shaders/aurora";
import { beam } from "./shaders/beam";
import { chrome } from "./shaders/chrome";
import { ditherBurst } from "./shaders/dither-burst";
import { ditherField } from "./shaders/dither-field";
import { fluted } from "./shaders/fluted";
import { grain } from "./shaders/grain";
import { halo } from "./shaders/halo";
import { horizon } from "./shaders/horizon";
import { limb } from "./shaders/limb";
import { linearFlow } from "./shaders/linear-flow";
import { mesh } from "./shaders/mesh";
import { mist } from "./shaders/mist";
import { pixelGlass } from "./shaders/pixel-glass";
import { radialGlow } from "./shaders/radial-glow";
import { ribbon } from "./shaders/ribbon";
import { rise } from "./shaders/rise";
import { silk } from "./shaders/silk";
import { smear } from "./shaders/smear";
import { spectrum } from "./shaders/spectrum";
import { swirl } from "./shaders/swirl";
import { voidKind } from "./shaders/void";
import { waves } from "./shaders/waves";
import type { GradientKind, GradientParams } from "./types";
export type { GradientKindDefinition } from "./kind";
const registry = new Map<string, GradientKindDefinition>();
/** Adds a kind. Re-registering a name replaces it. */
export function registerKind(definition: GradientKindDefinition): void {
registry.set(definition.name, definition);
}
for (const definition of [
mesh,
grain,
aurora,
waves,
radialGlow,
linearFlow,
horizon,
ditherField,
halo,
beam,
voidKind,
limb,
ditherBurst,
pixelGlass,
fluted,
spectrum,
silk,
ribbon,
chrome,
rise,
mist,
smear,
swirl,
]) {
registerKind(definition);
}
/** The kind's definition, or mesh when the name is unknown. */
export function getKind(kind: GradientKind): GradientKindDefinition {
return registry.get(kind) ?? mesh;
}
export function listKinds(): GradientKindDefinition[] {
return [...registry.values()];
}
/** Full params tuned for a kind. */
export function kindDefaults(kind: GradientKind): GradientParams {
const definition = getKind(kind);
return { ...definition.defaults, kind: definition.name };
}
@@ -1,97 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import type { RenderTarget } from "./types";
/** Radius of the time circle in noise space at speed 1. */
export const LOOP_RADIUS = 0.6;
/** Frame rate the live loop uses to derive `frameIndex`. */
export const LIVE_FPS = 60;
/** Position along one loop, 0 to 2π. Endpoint input always wraps to zero. */
export function loopPhase(timeSeconds: number, loopSeconds: number): number {
const wrapped = ((timeSeconds % loopSeconds) + loopSeconds) % loopSeconds;
return (2 * Math.PI * wrapped) / loopSeconds;
}
/**
* Noise-space time input. Without an explicit drift, retain the original
* speed-scaled radius and one lap per loop for saved params. With drift, speed
* changes pace around the pinned path.
*/
export function loopVector(
timeSeconds: number,
loopSeconds: number,
speed: number,
drift?: number,
): readonly [number, number] {
const legacy = drift === undefined;
const phase = loopPhase(timeSeconds, loopSeconds) * (legacy ? 1 : speed);
const radius = legacy ? speed * LOOP_RADIUS : drift;
return [Math.cos(phase) * radius, Math.sin(phase) * radius];
}
/** Evaluates the fixed path at an already accumulated runtime phase. */
export function loopVectorAtPhase(
phase: number,
drift = LOOP_RADIUS,
): readonly [number, number] {
return [Math.cos(phase) * drift, Math.sin(phase) * drift];
}
/**
* Grain seed for a frame. It wraps at the live loop length so the grain
* pattern repeats with the loop too.
*/
export function grainFrame(
frameIndex: number,
loopSeconds: number,
frameRate = LIVE_FPS,
): number {
const period = Math.max(1, Math.round(loopSeconds * frameRate));
return ((Math.floor(frameIndex) % period) + period) % period;
}
/** Video frame rule: N = round(loopSeconds * fps) frames at i / fps; the endpoint is omitted. */
export function videoFrameTimes(loopSeconds: number, fps: number): number[] {
const count = Math.round(loopSeconds * fps);
return Array.from({ length: count }, (_, i) => i / fps);
}
export function fullTarget(width: number, height: number): RenderTarget {
return { fullHeight: height, fullWidth: width, height, width, x: 0, y: 0 };
}
/**
* Splits an image into tiles no larger than maxTile, row by row from the
* top left. Tiles are quad-aligned so a tiled render equals the full one
* even for kinds that use screen-space derivatives (fwidth), which the GPU
* computes over 2x2 pixel quads: every tile starts at an even x, and every
* tile's bottom edge sits an even number of rows above the image's bottom
* (WebGL pairs rows from the bottom). The step is maxTile rounded down to
* even, and any odd remainder goes to the top row of tiles.
*/
export function splitTiles(
fullWidth: number,
fullHeight: number,
maxTile: number,
): RenderTarget[] {
const step = Math.max(2, Math.floor(maxTile / 2) * 2);
const rows: { y: number; height: number }[] = [];
for (let bottom = fullHeight; bottom > 0; bottom -= step) {
const y = Math.max(0, bottom - step);
rows.unshift({ height: bottom - y, y });
}
const tiles: RenderTarget[] = [];
for (const { y, height } of rows) {
for (let x = 0; x < fullWidth; x += step) {
tiles.push({
fullHeight,
fullWidth,
height,
width: Math.min(step, fullWidth - x),
x,
y,
});
}
}
return tiles;
}
@@ -1,442 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import type { BackendLease, GradientBackend } from "./backend";
import { backendFor } from "./backend";
import { hasCssVariable, resolveColor, srgbToOklab } from "./color";
import { staticFallbackCss } from "./fallback";
import { fullTarget, LIVE_FPS, LOOP_RADIUS, loopPhase } from "./loop";
import { mergeParams, normalizeParams } from "./params";
import type { ContextSlot, FrameQuality } from "./scheduler";
import {
GRAIN_CRISP,
MIN_RENDER_SCALE,
noteFrame,
recordPaint,
registerSlot,
relearnDisplayRate,
scheduleContexts,
slotLostContext,
unregisterSlot,
} from "./scheduler";
import type { FrameInput, GradientParams } from "./types";
export interface MountOptions {
/** Device pixel ratio cap. Default 1.5. */
maxDpr?: number;
/** "respect" renders one still frame when the user prefers reduced motion. Default "respect". */
reducedMotion?: "respect" | "ignore";
/** The page's one hero canvas: renders from PRIMARY_PIXEL_BUDGET, not the shared one. Default false. */
primary?: boolean;
}
export interface MountedGradient {
setParams(p: Partial<GradientParams>): void;
unmount(): void;
}
/**
* Live, on-page gradient. Owns canvas sizing (ResizeObserver, DPR capped at
* maxDpr), rAF, pausing offscreen or when the document is hidden, smoothed
* pointer and scroll-velocity influence, reduced motion, theme colour
* re-resolution and its share of the page's WebGL context budget.
*
* The canvas gets a 2D context. Frames are rendered in a leased GPU
* surface (WebGPU, or a WebGL context from the shared pool; see backend.ts)
* and copied over, so a suspended gradient
* keeps its last frame and never shows the browser's lost-context box.
* Behind it, the canvas background is `staticFallbackCss`, which is what
* shows when WebGL2 is unavailable.
*/
export function mountGradient(
canvas: HTMLCanvasElement,
params: GradientParams,
options: MountOptions = {},
): MountedGradient {
const maxDpr = options.maxDpr ?? 1.5;
let current = normalizeParams(params);
let lease: BackendLease | null = null;
/** The backend `lease` came from; picked per kind when a lease is taken. */
let leaseBackend: GradientBackend = backendFor(current.kind);
/** The 2D canvas shows a frame that matches the current params and theme. */
let fresh = false;
let visible = false;
let raf = 0;
let lastNow: number | null = null;
let time = 0;
let phase = 0;
/** Bumped whenever params or resolved colours change. */
let version = 0;
/** Render scale and frame rate from the shared pixel budget. */
let quality: FrameQuality = { halfRate: false, scale: 1 };
let skipNext = false;
const display = canvas.getContext("2d");
/** Pixels a frame renders at, at this render scale. */
const renderPixels = (scale: number) =>
Math.max(1, Math.round(canvas.width * scale)) *
Math.max(1, Math.round(canvas.height * scale));
const initialBackground = canvas.style.background;
const motionQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
const reduced = () =>
options.reducedMotion !== "ignore" && motionQuery.matches;
// Pointer and scroll targets, eased toward in the frame loop.
const pointerTarget = { strength: 0, x: 0.5, y: 0.5 };
const pointer = { strength: 0, x: 0.5, y: 0.5 };
let scrollImpulse = 0;
let scrollVelocity = 0;
let lastScroll = { t: performance.now(), y: window.scrollY };
const resolver = (value: string) =>
srgbToOklab(resolveColor(value, canvas.isConnected ? canvas : null));
const applyBackground = () => {
canvas.style.background = staticFallbackCss(current);
};
const frameInput = (): FrameInput => {
if (reduced()) {
return { frameIndex: 0, timeSeconds: 0 };
}
const input: FrameInput = {
frameIndex: Math.floor(time * LIVE_FPS),
timeSeconds: time,
};
if (current.drift !== undefined) {
input.phase = phase;
}
if (pointer.strength > 0.001) {
input.pointer = { ...pointer };
}
if (Math.abs(scrollVelocity) > 0.001) {
input.scroll = { velocity: scrollVelocity };
}
return input;
};
/** Renders one frame with a pooled context and copies it onto the canvas. */
const paintWith = (context: BackendLease, frame: FrameInput, scale = 1) => {
if (!display || context.isLost() || canvas.width === 0) {
return;
}
if (context.loaded?.owner !== slot || context.loaded.version !== version) {
context.resolver = resolver;
context.setParams(current);
context.loaded = { owner: slot, version };
}
// Over the pixel budget, render smaller and let drawImage upscale.
const width = Math.max(1, Math.round(canvas.width * scale));
const height = Math.max(1, Math.round(canvas.height * scale));
context.renderFrame(frame, fullTarget(width, height));
if (context.isLost()) {
return;
}
display.clearRect(0, 0, canvas.width, canvas.height);
// Upscaling smooths pixel-cell kinds into blur; keep their cells crisp.
display.imageSmoothingEnabled = !(
current.kind === "dither-field" || current.dither.enabled
);
// Copying right after queue.submit() is safe: reading a WebGPU canvas
// (drawImage included) runs "get a copy of the image contents of a
// context", which first ensures all submitted work has finished writing the
// current texture (https://gpuweb.github.io/gpuweb/#abstract-opdef-get-a-copy-of-the-image-contents-of-a-context,
// via #canvas-hooks). The engine lab checks it: heavy kinds at 2560x1440,
// each frame copied the moment it is submitted, never stale or blank.
display.drawImage(
context.canvas,
0,
context.sourceY,
width,
height,
0,
0,
canvas.width,
canvas.height,
);
fresh = true;
};
const draw = () => {
if (lease) {
const start = performance.now();
paintWith(lease, frameInput(), quality.scale);
recordPaint(performance.now() - start);
}
};
/** Drops a stale frame so the theme-aware CSS fallback shows instead. */
const invalidate = () => {
version += 1;
fresh = false;
if (!lease) {
display?.clearRect(0, 0, canvas.width, canvas.height);
scheduleContexts();
}
};
const shouldAnimate = () =>
lease !== null && visible && !document.hidden && !reduced();
const tick = (now: number) => {
raf = 0;
noteFrame(now);
const dt = lastNow === null ? 0 : Math.min(0.1, (now - lastNow) / 1000);
lastNow = now;
time += dt;
if (current.drift !== undefined) {
phase += (dt * current.speed * 2 * Math.PI) / current.loopSeconds;
phase %= 2 * Math.PI;
}
const ease = 1 - Math.exp(-dt * 6);
pointer.x += (pointerTarget.x - pointer.x) * ease;
pointer.y += (pointerTarget.y - pointer.y) * ease;
pointer.strength += (pointerTarget.strength - pointer.strength) * ease;
scrollImpulse *= Math.exp(-dt * 7);
scrollVelocity +=
(scrollImpulse - scrollVelocity) * (1 - Math.exp(-dt * 5));
// At half rate, time still advances every frame; only drawing skips.
skipNext = quality.halfRate && !skipNext;
if (!skipNext) {
draw();
}
if (shouldAnimate()) {
raf = window.requestAnimationFrame(tick);
}
};
/** Starts or stops the frame loop to match the current state. */
const sync = () => {
if (shouldAnimate()) {
if (raf === 0) {
lastNow = null;
raf = window.requestAnimationFrame(tick);
}
return;
}
if (raf !== 0) {
window.cancelAnimationFrame(raf);
raf = 0;
}
draw();
};
const slot: ContextSlot = {
element: canvas,
grant() {
if (lease) {
return true;
}
if (!display) {
return false;
}
leaseBackend = backendFor(current.kind);
// Still probing or compiling: no lease yet; the scheduler re-runs when ready.
lease = leaseBackend.supports(current.kind)
? leaseBackend.acquire(onLost, renderPixels(quality.scale))
: null;
if (!lease) {
if (leaseBackend.unsupported()) {
unregisterSlot(slot);
}
return false;
}
draw();
sync();
return true;
},
primary() {
return options.primary === true;
},
minScale() {
if (current.dither.enabled) {
return 1;
}
return current.grain >= GRAIN_CRISP ? 0.8 : MIN_RENDER_SCALE;
},
pixels() {
return canvas.width * canvas.height;
},
backend() {
return backendFor(current.kind).name;
},
setQuality(next) {
quality = next;
// Readable in devtools and by the engine lab's checks.
canvas.dataset.renderScale = next.scale.toFixed(3);
},
paintStill() {
if (lease || fresh || !display) {
return;
}
const backend = backendFor(current.kind);
const painter = backend.supports(current.kind)
? backend.acquire(null, renderPixels(1))
: null;
if (!painter) {
return;
}
paintWith(painter, frameInput());
backend.release(painter);
},
revoke() {
if (raf !== 0) {
window.cancelAnimationFrame(raf);
raf = 0;
}
if (lease) {
leaseBackend.release(lease);
lease = null;
}
},
setVisible(next) {
visible = next;
sync();
},
};
/**
* The pool lost our context and already ended the lease. Keep the last
* frame on screen and let the scheduler find another context; it re-runs
* again when the lost one is restored.
*/
function onLost() {
lease = null;
if (raf !== 0) {
window.cancelAnimationFrame(raf);
raf = 0;
}
slotLostContext(slot);
}
const resize = () => {
const dpr = Math.min(maxDpr, window.devicePixelRatio || 1);
const width = Math.max(1, Math.round(canvas.clientWidth * dpr));
const height = Math.max(1, Math.round(canvas.clientHeight * dpr));
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
// Resizing clears the canvas.
fresh = false;
draw();
relearnDisplayRate();
}
scheduleContexts();
};
const onPointerMove = (event: PointerEvent) => {
if (current.interaction.pointer <= 0) {
return;
}
const rect = canvas.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) {
return;
}
const x = (event.clientX - rect.left) / rect.width;
const y = (event.clientY - rect.top) / rect.height;
const inside = x >= -0.1 && x <= 1.1 && y >= -0.1 && y <= 1.1;
pointerTarget.strength = inside ? 1 : 0;
if (inside) {
pointerTarget.x = x;
pointerTarget.y = y;
}
};
const onPointerLeave = () => {
pointerTarget.strength = 0;
};
const onScroll = () => {
const now = performance.now();
const dt = Math.max(1, now - lastScroll.t) / 1000;
const dy = window.scrollY - lastScroll.y;
lastScroll = { t: now, y: window.scrollY };
if (current.interaction.scroll <= 0) {
return;
}
// Viewport heights per second, so the feel is the same on every screen.
const velocity = dy / Math.max(1, window.innerHeight) / dt;
scrollImpulse = Math.max(-6, Math.min(6, velocity));
};
const onVisibility = () => {
relearnDisplayRate();
sync();
};
const onMotionChange = () => {
time = 0;
phase = 0;
invalidate();
sync();
};
const themeObserver = new MutationObserver(() => {
if (!hasCssVariable([...current.colors, current.background])) {
return;
}
invalidate();
draw();
});
const resizeObserver = new ResizeObserver(resize);
window.addEventListener("pointermove", onPointerMove, { passive: true });
document.documentElement.addEventListener("pointerleave", onPointerLeave);
window.addEventListener("scroll", onScroll, { passive: true });
document.addEventListener("visibilitychange", onVisibility);
motionQuery.addEventListener("change", onMotionChange);
themeObserver.observe(document.documentElement, {
attributeFilter: ["class", "style"],
attributes: true,
});
resizeObserver.observe(canvas);
applyBackground();
canvas.dataset.renderScale = quality.scale.toFixed(3);
resize();
if (display) {
registerSlot(slot);
}
return {
setParams(patch) {
const speedChanged =
patch.speed !== undefined && patch.speed !== current.speed;
const enteringPinnedPath = speedChanged && current.drift === undefined;
const fullParamsPatch =
"kind" in patch && "colors" in patch && "speed" in patch;
const nextPatch: Partial<GradientParams> = enteringPinnedPath
? { ...patch, drift: current.speed * LOOP_RADIUS }
: current.drift !== undefined &&
patch.drift === undefined &&
!fullParamsPatch
? { ...patch, drift: current.drift }
: patch;
if (enteringPinnedPath) {
// Legacy frames use the angle once around the loop. Keep that angle
// while switching to the pinned path so the first edit cannot jump.
phase = loopPhase(time, current.loopSeconds);
}
current = mergeParams(current, nextPatch);
applyBackground();
if (lease && backendFor(current.kind) !== leaseBackend) {
// The new kind draws with the other backend: give the lease back and
// let the scheduler grant one from the right backend.
slot.revoke();
slotLostContext(slot);
}
invalidate();
draw();
},
unmount() {
slot.revoke();
unregisterSlot(slot);
resizeObserver.disconnect();
themeObserver.disconnect();
window.removeEventListener("pointermove", onPointerMove);
document.documentElement.removeEventListener(
"pointerleave",
onPointerLeave,
);
window.removeEventListener("scroll", onScroll);
document.removeEventListener("visibilitychange", onVisibility);
motionQuery.removeEventListener("change", onMotionChange);
display?.clearRect(0, 0, canvas.width, canvas.height);
canvas.style.background = initialBackground;
delete canvas.dataset.renderScale;
},
};
}
@@ -1,204 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import { mesh } from "./shaders/mesh";
import type { GradientParams } from "./types";
/** The mesh kind with its tuned defaults. */
export const defaultParams: GradientParams = { ...mesh.defaults, kind: "mesh" };
const clamp = (n: number, min: number, max: number) =>
Math.min(max, Math.max(min, n));
function record(input: unknown): Record<string, unknown> {
if (typeof input !== "object" || input === null || Array.isArray(input)) {
throw new TypeError("Expected an object");
}
// Own enumerable fields are intentional: unlike zod, inherited properties are rejected.
return Object.fromEntries(Object.entries(input));
}
function number(value: unknown, name: string): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
throw new TypeError(`${name} must be a number`);
}
return value;
}
function integer(value: unknown, name: string): number {
const parsed = number(value, name);
if (!Number.isInteger(parsed)) {
throw new TypeError(`${name} must be an integer`);
}
return parsed;
}
function string(value: unknown, name: string): string {
if (typeof value !== "string") {
throw new TypeError(`${name} must be a string`);
}
return value;
}
function fullParams(input: unknown): GradientParams {
const value = record(input);
const colors = value.colors;
if (!Array.isArray(colors) || colors.length < 2 || colors.length > 6) {
throw new TypeError("colors must contain 2 to 6 entries");
}
const dither = record(value.dither);
const interaction = record(value.interaction);
const parsed = {
background: string(value.background, "background"),
blur: number(value.blur, "blur"),
colors: colors.map((color) => string(color, "colors")),
dither: {
cell: number(dither.cell, "dither.cell"),
enabled: boolean(dither.enabled, "dither.enabled"),
levels: number(dither.levels, "dither.levels"),
},
grain: number(value.grain, "grain"),
interaction: {
pointer: number(interaction.pointer, "interaction.pointer"),
scroll: number(interaction.scroll, "interaction.scroll"),
},
kind: string(value.kind, "kind"),
loopSeconds: number(value.loopSeconds, "loopSeconds"),
scale: number(value.scale, "scale"),
seed: integer(value.seed, "seed"),
speed: number(value.speed, "speed"),
warp: number(value.warp, "warp"),
};
return value.drift === undefined
? parsed
: { ...parsed, drift: number(value.drift, "drift") };
}
function boolean(value: unknown, name: string): boolean {
if (typeof value !== "boolean") {
throw new TypeError(`${name} must be a boolean`);
}
return value;
}
function partialParams(input: unknown): Partial<GradientParams> {
const value = record(input);
const output: Partial<GradientParams> = {};
if ("background" in value)
output.background = string(value.background, "background");
if ("blur" in value) output.blur = number(value.blur, "blur");
if ("colors" in value) {
if (
!Array.isArray(value.colors) ||
value.colors.length < 2 ||
value.colors.length > 6
)
throw new TypeError("colors must contain 2 to 6 entries");
output.colors = value.colors.map((color) => string(color, "colors"));
}
if ("grain" in value) output.grain = number(value.grain, "grain");
if ("kind" in value) output.kind = string(value.kind, "kind");
if ("drift" in value) output.drift = number(value.drift, "drift");
if ("loopSeconds" in value)
output.loopSeconds = number(value.loopSeconds, "loopSeconds");
if ("scale" in value) output.scale = number(value.scale, "scale");
if ("seed" in value) output.seed = integer(value.seed, "seed");
if ("speed" in value) output.speed = number(value.speed, "speed");
if ("warp" in value) output.warp = number(value.warp, "warp");
if ("dither" in value) {
const dither = partialDither(value.dither);
output.dither = {
...defaultParams.dither,
...dither,
};
}
if ("interaction" in value) {
const interaction = partialInteraction(value.interaction);
output.interaction = {
...defaultParams.interaction,
...interaction,
};
}
return output;
}
function partialDither(input: unknown): Partial<GradientParams["dither"]> {
const value = record(input);
const output: Partial<GradientParams["dither"]> = {};
if ("cell" in value) output.cell = number(value.cell, "dither.cell");
if ("levels" in value) output.levels = number(value.levels, "dither.levels");
if ("enabled" in value) {
output.enabled = boolean(value.enabled, "dither.enabled");
}
return output;
}
function partialInteraction(
input: unknown,
): Partial<GradientParams["interaction"]> {
const value = record(input);
const output: Partial<GradientParams["interaction"]> = {};
if ("pointer" in value)
output.pointer = number(value.pointer, "interaction.pointer");
if ("scroll" in value)
output.scroll = number(value.scroll, "interaction.scroll");
return output;
}
/** Validates and clamps a full params object. Throws on a malformed shape. */
export function normalizeParams(input: GradientParams): GradientParams {
const parsed = fullParams(input);
const normalized = {
...parsed,
blur: clamp(parsed.blur, 0, 1),
colors: parsed.colors.slice(0, 6),
dither: {
cell: Math.round(clamp(parsed.dither.cell, 1, 32)),
enabled: parsed.dither.enabled,
levels: Math.round(clamp(parsed.dither.levels, 2, 32)),
},
grain: clamp(parsed.grain, 0, 1),
interaction: {
pointer: clamp(parsed.interaction.pointer, 0, 1),
scroll: clamp(parsed.interaction.scroll, 0, 1),
},
loopSeconds: clamp(parsed.loopSeconds, 4, 30),
scale: clamp(parsed.scale, 0.25, 4),
speed: clamp(parsed.speed, 0, 2),
warp: clamp(parsed.warp, 0, 1),
};
if (parsed.drift !== undefined) {
normalized.drift = clamp(parsed.drift, 0, 2);
}
return normalized;
}
/** Merges a partial update into full params, keeping nested objects whole. */
export function mergeParams(
base: GradientParams,
patch: Partial<GradientParams>,
): GradientParams {
return normalizeParams({
...base,
...patch,
dither: { ...base.dither, ...patch.dither },
interaction: { ...base.interaction, ...patch.interaction },
});
}
export function serializeParams(p: GradientParams): string {
return encodeURIComponent(JSON.stringify(normalizeParams(p)));
}
export function parseParams(s: string): GradientParams {
try {
const raw: unknown = JSON.parse(decodeURIComponent(s));
const parsed = partialParams(raw);
return normalizeParams({
...defaultParams,
...parsed,
dither: { ...defaultParams.dither, ...parsed.dither },
interaction: { ...defaultParams.interaction, ...parsed.interaction },
});
} catch {
return defaultParams;
}
}
@@ -1,199 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
/**
* The page's WebGL contexts. Gradients never hold a context on their own
* canvas; they lease one of at most MAX_LIVE_CONTEXTS offscreen contexts,
* render into it and copy the frame onto their 2D canvas. Returning a lease
* keeps the last frame on screen, and contexts are reused instead of being
* lost and restored.
*
* When the browser loses a context, its lease ends at once: the holder is
* told (it keeps its last frame), the context stays unavailable, and the
* scheduler re-runs so the gradient can lease another one. When the context
* is restored it becomes available again and the scheduler re-runs.
*/
import type { BackendLease } from "./backend";
import { defaultParams } from "./params";
import type { AnyCanvas, WebGLRenderer } from "./renderer";
import {
createWebGLRenderer,
documentColorResolver,
getWebGL2,
} from "./renderer";
export const MAX_LIVE_CONTEXTS = 8;
export interface PooledContext extends BackendLease {
readonly canvas: AnyCanvas;
readonly gl: WebGL2RenderingContext;
readonly renderer: WebGLRenderer;
leased: boolean;
lost: boolean;
/** Called once if the context is lost while leased. */
onLost: (() => void) | null;
}
const contexts = new Set<PooledContext>();
let unsupported = false;
const changeListeners = new Set<() => void>();
/** Runs `listener` whenever a context is lost or restored. */
export function onPoolChange(listener: () => void): () => void {
changeListeners.add(listener);
return () => changeListeners.delete(listener);
}
function notifyChange() {
for (const listener of changeListeners) {
listener();
}
}
function createCanvas(): AnyCanvas {
if (typeof OffscreenCanvas !== "undefined") {
return new OffscreenCanvas(1, 1);
}
return document.createElement("canvas");
}
function create(): PooledContext | null {
if (unsupported) {
return null;
}
let canvas = createCanvas();
let gl = getWebGL2(canvas, { preserveDrawingBuffer: false });
if (
!gl &&
typeof document !== "undefined" &&
!(canvas instanceof HTMLCanvasElement)
) {
// Some browsers have OffscreenCanvas without WebGL2 on it.
canvas = document.createElement("canvas");
gl = getWebGL2(canvas, { preserveDrawingBuffer: false });
}
if (!gl) {
unsupported = true;
return null;
}
const holder = { resolver: documentColorResolver };
const renderer = createWebGLRenderer({
canvas,
gl,
params: defaultParams,
resolveColor: (value) => holder.resolver(value),
});
const context: PooledContext = {
canvas,
gl,
isLost: () => context.lost || gl.isContextLost(),
leased: false,
loaded: null,
sourceY: 0,
lost: false,
onLost: null,
renderFrame: (frame, target) => renderer.renderFrame(frame, target),
renderer,
setParams: (next) => renderer.setParams(next),
get resolver() {
return holder.resolver;
},
set resolver(next) {
holder.resolver = next;
},
};
canvas.addEventListener("webglcontextlost", (event) => {
event.preventDefault();
context.lost = true;
context.loaded = null;
const holder = context.onLost;
context.onLost = null;
context.leased = false;
holder?.();
notifyChange();
});
canvas.addEventListener("webglcontextrestored", () => {
if (!contexts.has(context)) {
// Trimmed while lost: don't keep a restored context outside the budget.
gl.getExtension("WEBGL_lose_context")?.loseContext();
return;
}
context.lost = false;
context.loaded = null;
try {
context.renderer.restore();
} catch {
destroy(context);
}
notifyChange();
});
contexts.add(context);
return context;
}
/** True once creating a WebGL2 context has failed on this page. */
export function webglUnsupported(): boolean {
return unsupported;
}
/**
* Leases an idle context, creating one if the budget allows. `onLost` runs if
* the browser loses the context during the lease; the lease is already over
* by then.
*/
export function acquireContext(
onLost: (() => void) | null = null,
): PooledContext | null {
for (const context of contexts) {
if (!context.leased && !context.lost) {
context.leased = true;
context.onLost = onLost;
return context;
}
}
if (contexts.size >= MAX_LIVE_CONTEXTS) {
return null;
}
try {
const context = create();
if (context) {
context.leased = true;
context.onLost = onLost;
}
return context;
} catch {
// A shader that fails to compile means this engine cannot run here.
unsupported = true;
return null;
}
}
export function releaseContext(context: PooledContext): void {
context.leased = false;
context.onLost = null;
}
function destroy(context: PooledContext) {
context.renderer.destroy();
context.gl.getExtension("WEBGL_lose_context")?.loseContext();
contexts.delete(context);
}
/** Frees idle contexts until at most `keep` contexts remain. */
export function trimContexts(keep: number): void {
for (const context of [...contexts]) {
if (contexts.size <= keep) {
return;
}
if (!context.leased) {
destroy(context);
}
}
}
export function liveContextCount(): number {
return contexts.size;
}
/** The pool's contexts. For tests and the engine lab only. */
export function pooledContexts(): readonly PooledContext[] {
return [...contexts];
}
@@ -1,277 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import type { Oklab } from "./color";
import { resolveColor, srgbToOklab } from "./color";
import { getKind } from "./kinds";
import { fullTarget } from "./loop";
import { mergeParams, normalizeParams } from "./params";
import {
fragmentPostlude,
fragmentPrelude,
vertexShader,
} from "./shaders/common";
import type {
FrameInput,
GradientParams,
GradientRenderer,
RenderTarget,
} from "./types";
import { frameUniforms } from "./uniforms";
export type AnyCanvas = HTMLCanvasElement | OffscreenCanvas;
export interface ContextOptions {
preserveDrawingBuffer: boolean;
}
const UNIFORMS = [
"u_full",
"u_tile",
"u_loop",
"u_seed",
"u_scale",
"u_warp",
"u_blur",
"u_grain",
"u_frame",
"u_dither",
"u_colors",
"u_count",
"u_bg",
"u_pointer",
"u_scroll",
] as const;
type UniformName = (typeof UNIFORMS)[number];
interface ProgramInfo {
program: WebGLProgram;
uniforms: Record<UniformName, WebGLUniformLocation | null>;
}
export class ShaderError extends Error {
override name = "ShaderError";
}
function isOffscreen(canvas: AnyCanvas): canvas is OffscreenCanvas {
return (
typeof OffscreenCanvas !== "undefined" && canvas instanceof OffscreenCanvas
);
}
/** Gets (or returns the existing) WebGL2 context. Null when WebGL2 is unavailable. */
export function getWebGL2(
canvas: AnyCanvas,
options: ContextOptions,
): WebGL2RenderingContext | null {
const attributes: WebGLContextAttributes = {
alpha: true,
antialias: false,
depth: false,
powerPreference: "low-power",
premultipliedAlpha: true,
preserveDrawingBuffer: options.preserveDrawingBuffer,
stencil: false,
};
try {
return isOffscreen(canvas)
? canvas.getContext("webgl2", attributes)
: canvas.getContext("webgl2", attributes);
} catch {
return null;
}
}
function compile(
gl: WebGL2RenderingContext,
type: number,
source: string,
): WebGLShader {
const shader = gl.createShader(type);
if (!shader) {
throw new ShaderError("Unable to create shader");
}
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (
!gl.getShaderParameter(shader, gl.COMPILE_STATUS) &&
!gl.isContextLost()
) {
const log = gl.getShaderInfoLog(shader) ?? "";
gl.deleteShader(shader);
throw new ShaderError(`Shader compile failed: ${log}`);
}
return shader;
}
export type ColorResolver = (value: string) => Oklab;
export const documentColorResolver: ColorResolver = (value) =>
srgbToOklab(
resolveColor(
value,
typeof document === "undefined" ? null : document.documentElement,
),
);
export interface WebGLRenderer extends GradientRenderer {
readonly gl: WebGL2RenderingContext;
readonly params: GradientParams;
/** Rebuilds GPU resources after `webglcontextrestored`. */
restore(): void;
/** Re-resolves colours, for example after a theme change. */
refreshColors(): void;
}
/**
* Pure renderer over an existing WebGL2 context. No rAF, listeners or CSS.
* Throws ShaderError when a kind's shader cannot compile.
*/
export function createWebGLRenderer(options: {
canvas: AnyCanvas;
gl: WebGL2RenderingContext;
params: GradientParams;
resolveColor?: ColorResolver;
}): WebGLRenderer {
const { canvas, gl } = options;
const resolve = options.resolveColor ?? documentColorResolver;
let params = normalizeParams(options.params);
let colors: Oklab[] = [];
let background: Oklab = [0, 0, 0];
let programs = new Map<string, ProgramInfo>();
let buffer: WebGLBuffer | null = null;
let vao: WebGLVertexArrayObject | null = null;
const refreshColors = () => {
colors = params.colors.map((value) => resolve(value));
background = resolve(params.background);
};
const buildGeometry = () => {
buffer = gl.createBuffer();
vao = gl.createVertexArray();
gl.bindVertexArray(vao);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),
gl.STATIC_DRAW,
);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
gl.bindVertexArray(null);
};
const programFor = (kindName: string): ProgramInfo => {
const kind = getKind(kindName);
const cached = programs.get(kind.name);
if (cached) {
return cached;
}
const vs = compile(gl, gl.VERTEX_SHADER, vertexShader);
const fs = compile(
gl,
gl.FRAGMENT_SHADER,
`${fragmentPrelude}\n${kind.glsl}\n${fragmentPostlude}`,
);
const program = gl.createProgram();
if (!program) {
throw new ShaderError("Unable to create program");
}
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.bindAttribLocation(program, 0, "a_position");
gl.linkProgram(program);
gl.deleteShader(vs);
gl.deleteShader(fs);
if (
!gl.getProgramParameter(program, gl.LINK_STATUS) &&
!gl.isContextLost()
) {
const log = gl.getProgramInfoLog(program) ?? "";
gl.deleteProgram(program);
throw new ShaderError(`Program link failed: ${log}`);
}
const uniforms = Object.fromEntries(
UNIFORMS.map((name) => [name, gl.getUniformLocation(program, name)]),
) as Record<UniformName, WebGLUniformLocation | null>;
const info = { program, uniforms };
programs.set(kind.name, info);
return info;
};
const restore = () => {
programs = new Map();
buildGeometry();
programFor(params.kind);
};
refreshColors();
restore();
return {
get canvas() {
return canvas;
},
destroy() {
if (!gl.isContextLost()) {
for (const { program } of programs.values()) {
gl.deleteProgram(program);
}
gl.deleteBuffer(buffer);
gl.deleteVertexArray(vao);
}
programs = new Map();
},
gl,
get params() {
return params;
},
refreshColors,
renderFrame(frame: FrameInput, target?: RenderTarget) {
if (gl.isContextLost()) {
return;
}
const t = target ?? fullTarget(canvas.width, canvas.height);
if (canvas.width !== t.width || canvas.height !== t.height) {
canvas.width = t.width;
canvas.height = t.height;
}
const { program, uniforms: u } = programFor(params.kind);
const f = frameUniforms(params, colors, background, frame, t);
const palette = new Float32Array(18);
f.colors.forEach(([l, a, b], i) => {
palette.set([l, a, b], i * 3);
});
gl.viewport(0, 0, t.width, t.height);
// biome-ignore lint/correctness/useHookAtTopLevel: WebGL call, not a React hook
gl.useProgram(program);
gl.bindVertexArray(vao);
gl.uniform2f(u.u_full, f.full[0], f.full[1]);
gl.uniform4f(u.u_tile, f.tile[0], f.tile[1], f.tile[2], f.tile[3]);
gl.uniform2f(u.u_loop, f.loopv[0], f.loopv[1]);
gl.uniform2f(u.u_seed, f.seed[0], f.seed[1]);
gl.uniform1f(u.u_scale, f.scale);
gl.uniform1f(u.u_warp, f.warp);
gl.uniform1f(u.u_blur, f.blur);
gl.uniform1f(u.u_grain, f.grain);
gl.uniform1f(u.u_frame, f.frame);
gl.uniform3f(u.u_dither, f.dither[0], f.dither[1], f.dither[2]);
gl.uniform3fv(u.u_colors, palette);
gl.uniform1i(u.u_count, f.count);
gl.uniform3f(u.u_bg, f.bg[0], f.bg[1], f.bg[2]);
gl.uniform3f(u.u_pointer, f.pointer[0], f.pointer[1], f.pointer[2]);
gl.uniform1f(u.u_scroll, f.scroll);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.bindVertexArray(null);
},
restore,
setParams(patch: Partial<GradientParams>) {
const colorsChanged =
patch.colors !== undefined || patch.background !== undefined;
params = mergeParams(params, patch);
if (colorsChanged) {
refreshColors();
}
},
};
}
@@ -1,718 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
/**
* Module-level GPU budget: at most MAX_LIVE_CONTEXTS WebGL contexts and
* MAX_WEBGPU_SURFACES WebGPU surfaces per page, each gradient counting
* against its own kind's backend. Gradients near the viewport lease one, nearest first; the rest are
* suspended and keep their last frame (or the CSS fallback) until they come
* close again. When more gradients are near than the budget allows, one
* context is kept back to paint still frames for the ones left over, so they
* never fall back to the rougher CSS approximation.
*
* Pixel budget: every animating gradient copies its frame onto its canvas,
* so the cost per frame grows with the total pixel count, not the number of
* gradients. Animating gradients share PIXEL_BUDGET drawing-buffer pixels per
* frame (about one 1440x900 viewport at DPR 1.25). Over budget, every
* animating gradient renders at the same lower internal scale and is
* upscaled when copied; the soft kinds hide this well. Grain and dither are
* per-pixel detail, so params with grain >= GRAIN_CRISP or dither on are
* never scaled below their floor (0.8 and 1). If the floors still leave the
* total over budget, all animating gradients drop to half the display rate.
*
* A primary gradient (a page's one hero canvas) has its own
* PRIMARY_PIXEL_BUDGET. A frame-time governor (judgePace) caps the pixels
* per frame, for every gradient alike, when frames fall behind the display rate.
*/
import type { BackendName } from "./backend";
import {
liveContextCount,
MAX_LIVE_CONTEXTS,
onPoolChange,
trimContexts,
} from "./pool";
import {
MAX_WEBGPU_SURFACES,
onWebGPUChange,
trimSurfaces,
webgpuStats,
} from "./webgpu";
export interface EngineStats {
renderedPixels: number;
animatingMounts: number;
mounted: number;
renderScale: number;
fpsTier: "full" | "half";
scrolling: boolean;
paceCap: number;
rafIntervals: number[];
gpuTimeMs: number | null;
}
declare global {
interface Window {
__gcnEngineStats?: () => EngineStats;
}
}
export { MAX_LIVE_CONTEXTS } from "./pool";
/** Drawing-buffer pixels per frame shared by all animating gradients. */
export const PIXEL_BUDGET = 2_000_000;
/**
* Drawing-buffer pixels per frame for primary gradients, on top of
* PIXEL_BUDGET: a 1230x760 studio stage at DPR 2 (3.7 MP) fits whole.
*/
export const PRIMARY_PIXEL_BUDGET = 4_500_000;
/** Lowest internal render scale for soft gradients. */
export const MIN_RENDER_SCALE = 0.5;
/** Grain at or above this keeps a render scale of at least 0.8. */
export const GRAIN_CRISP = 0.3;
/** How far outside the viewport (as a fraction of its height) a gradient still counts as near. */
const APPROACH_MARGIN = 0.5;
export interface FrameQuality {
/** Internal render scale, 0-1, applied to both axes. */
scale: number;
/** Render every other display frame (half the display refresh rate). */
halfRate: boolean;
}
export interface ContextSlot {
readonly element: Element;
/** Give this gradient a context. Returns false when none could be leased. */
grant(): boolean;
/** Take its context away. */
revoke(): void;
/** Whether any part of it is inside the viewport. */
setVisible(visible: boolean): void;
/** Near the viewport but over budget: show a still frame. */
paintStill(): void;
/** Drawing-buffer pixels at full scale. */
pixels(): number;
/** Lowest render scale these params tolerate. */
minScale(): number;
/** Draws from PRIMARY_PIXEL_BUDGET instead of the shared budget. */
primary(): boolean;
setQuality(quality: FrameQuality): void;
/** The backend this gradient's kind draws with on this page. */
backend(): BackendName;
}
interface SlotState {
live: boolean;
visible: boolean;
quality: FrameQuality;
}
const slots = new Map<ContextSlot, SlotState>();
let wantedSlots = new Set<ContextSlot>();
let frame = 0;
let listening = false;
let observer: IntersectionObserver | null = null;
let pixelBudget = PIXEL_BUDGET;
function distanceToViewport(rect: DOMRect, width: number, height: number) {
const dx = Math.max(0, rect.left - width, -rect.right);
const dy = Math.max(0, rect.top - height, -rect.bottom);
return Math.hypot(dx, dy);
}
/** The 60 Hz default until rAF gives us a display measurement. */
const DEFAULT_FRAME_MS = 1000 / 60;
/** Display intervals used by the rolling estimator (60-240 Hz range). */
const MIN_DISPLAY_MS = 4;
const MAX_DISPLAY_MS = DEFAULT_FRAME_MS * 1.25;
const DISPLAY_SAMPLES = 24;
/**
* Safe primary ceiling: 8.3M RGBA pixels are about 32 MB for one buffer and
* 96 MB for WebGPU's three-buffer swap-chain cap. WebGL has no memory guard,
* so the same conservative limit protects both backends.
*/
const MAX_PRIMARY_PIXEL_BUDGET = 8_300_000;
/** rAF intervals per governor decision. */
const PACE_WINDOW = 10;
/** Steady windows in a row before the cap rises. */
const STEADY_WINDOWS = 5;
/** Gaps longer than this are pauses or hitches, not frame time. */
const MAX_INTERVAL_MS = 250;
/** Ticks ignored after the animating set or its quality changes (compiles, hydration). */
const WARMUP_TICKS = 30;
/** Steady windows at the ceiling (~10s) before it lifts a step. */
const CEILING_WINDOWS = 60;
interface Pace {
/** Most drawing-buffer pixels per frame, over every animating gradient. */
cap: number;
/** Pixels per frame that were too slow; the cap never rises back to it. */
ceiling: number;
lastTick: number | null;
intervals: number[];
/** Ticks left to ignore; see WARMUP_TICKS. */
warmup: number;
slowWindows: number;
steadyWindows: number;
/** Steady windows in a row spent at the ceiling. */
ceilingWindows: number;
/** Learned display interval; starts at the historical 60 Hz target. */
targetMs: number;
/** Rolling valid rAF intervals used to learn targetMs. */
displaySamples: number[];
/** Quality changes suppress display-rate learning during warm-up. */
suppressDisplayLearning: boolean;
}
const pace: Pace = {
cap: Number.POSITIVE_INFINITY,
ceiling: Number.POSITIVE_INFINITY,
ceilingWindows: 0,
intervals: [],
lastTick: null,
slowWindows: 0,
steadyWindows: 0,
warmup: WARMUP_TICKS,
targetMs: DEFAULT_FRAME_MS,
displaySamples: [],
suppressDisplayLearning: false,
};
/** Pixels rendered per frame at the current quality, for the governor. */
let renderedPixels = 0;
/** Slots animating at the last assignQuality, to notice a change. */
let animatingCount = 0;
let primaryBudget = PRIMARY_PIXEL_BUDGET;
let scrolling = false;
let scrollIdleTimer = 0;
const SCROLL_PIXEL_FACTOR = 0.65;
const SCROLL_IDLE_MS = 150;
/** Starts a fresh measurement after the work per frame changed. */
function restartPace() {
if (pace.lastTick !== null) pace.suppressDisplayLearning = true;
pace.warmup = WARMUP_TICKS;
pace.intervals = [];
pace.slowWindows = 0;
pace.steadyWindows = 0;
}
interface QualityGroup {
slots: [ContextSlot, SlotState][];
budget: number;
}
/** Shared render scale for one budget group, then each slot's floor. */
function groupScales({ slots: group, budget }: QualityGroup) {
const total = group.reduce((sum, [slot]) => sum + slot.pixels(), 0);
const shared =
total > budget ? Math.max(MIN_RENDER_SCALE, Math.sqrt(budget / total)) : 1;
let rendered = 0;
const scales = group.map(([slot]) => {
const scale = Math.min(1, Math.max(shared, slot.minScale()));
rendered += slot.pixels() * scale * scale;
return scale;
});
// Small tolerance: the shared scale lands exactly on the budget.
return { halfRate: rendered > budget * 1.01, rendered, scales };
}
/** Reserve every other live WebGPU lease before growing a primary surface. */
function primarySurfaceBudget() {
let webgpuPrimary = false;
let reserved = 0;
for (const [slot, state] of slots) {
if ((!state.live && !wantedSlots.has(slot)) || slot.backend() !== "webgpu")
continue;
if (slot.primary()) webgpuPrimary = true;
// Reserve full-size needs, including near but invisible leases. This also
// allows thumbnails to regain quality without evicting the primary.
else reserved += slot.pixels();
}
return webgpuPrimary
? Math.max(0, MAX_PRIMARY_PIXEL_BUDGET - reserved)
: MAX_PRIMARY_PIXEL_BUDGET;
}
/** Splits the pixel budgets across the gradients that are animating. */
function assignQuality() {
const animating = [...slots].filter(
([slot, state]) => (state.live || wantedSlots.has(slot)) && state.visible,
);
const groups: QualityGroup[] = [
{
budget:
Math.min(primaryBudget, primarySurfaceBudget()) *
(scrolling ? SCROLL_PIXEL_FACTOR : 1),
slots: animating.filter(([slot]) => slot.primary()),
},
{
budget: pixelBudget * (scrolling ? SCROLL_PIXEL_FACTOR : 1),
slots: animating.filter(([slot]) => !slot.primary()),
},
];
let results = groups.map(groupScales);
const rendered = results.reduce((sum, result) => sum + result.rendered, 0);
if (rendered > pace.cap) {
// The governor's cap: shrink each group's budget to its share of it.
const share = pace.cap / rendered;
results = groups.map((group, i) =>
groupScales({
budget: Math.min(group.budget, results[i]?.rendered ?? 0) * share,
slots: group.slots,
}),
);
}
renderedPixels = 0;
let changed = animating.length !== animatingCount;
animatingCount = animating.length;
groups.forEach((group, g) => {
const result = results[g];
if (!result) {
return;
}
renderedPixels += result.rendered;
group.slots.forEach(([slot, state], i) => {
const scale = result.scales[i] ?? 1;
const { halfRate } = result;
if (
state.quality.scale !== scale ||
state.quality.halfRate !== halfRate
) {
// Paused primaries may never paint the smaller buffer. Release the
// old allocation before admission; grant() paints at the new scale.
if (
state.live &&
slot.primary() &&
slot.backend() === "webgpu" &&
scale < state.quality.scale
) {
state.live = false;
slot.revoke();
scheduleContexts();
}
state.quality = { halfRate, scale };
slot.setQuality(state.quality);
changed = true;
}
});
});
if (changed) {
restartPace();
}
}
/** Temporarily lowers render work while a scroll is actively moving. */
export function noteScroll(): void {
if (!scrolling) {
scrolling = true;
assignQuality();
}
if (
typeof window !== "undefined" &&
typeof window.setTimeout === "function"
) {
window.clearTimeout(scrollIdleTimer);
scrollIdleTimer = window.setTimeout(() => {
scrolling = false;
assignQuality();
}, SCROLL_IDLE_MS);
}
}
/**
* One decision from a window's mean rAF interval. Not the median: a
* pipelining browser keeps most ticks on time and drops whole frames.
*/
function judgePace(meanMs: number) {
const slow = meanMs > pace.targetMs * 1.12;
pace.slowWindows = slow ? pace.slowWindows + 1 : 0;
pace.steadyWindows =
meanMs <= pace.targetMs * 1.05 ? pace.steadyWindows + 1 : 0;
// Far too slow acts at once; a little slow must repeat, to skip hitches.
if (slow && (meanMs > pace.targetMs * 2 || pace.slowWindows >= 2)) {
pace.slowWindows = 0;
pace.ceilingWindows = 0;
pace.ceiling = Math.min(pace.ceiling, renderedPixels);
// Pixel cost is about linear, so aim a little under the target.
const factor = Math.min(0.9, Math.max(0.5, (pace.targetMs / meanMs) * 0.9));
pace.cap = Math.min(pace.cap, renderedPixels) * factor;
scheduleContexts();
return;
}
if (
pace.steadyWindows < STEADY_WINDOWS ||
(Number.isFinite(pace.cap) && renderedPixels < pace.cap * 0.98)
) {
return;
}
if (!Number.isFinite(pace.cap)) {
// Keep grids on their existing shared budget. Only the primary group's
// budget grows, and only while the governor has sustained headroom.
primaryBudget = Math.min(primarySurfaceBudget(), primaryBudget * 1.2);
pace.steadyWindows = 0;
scheduleContexts();
return;
}
pace.steadyWindows = 0;
const limit = pace.ceiling * 0.9;
if (pace.cap >= limit) {
// Held steady at the ceiling for a long while: it may have been set by
// a passing slowdown, so lift it a step and try again.
pace.ceilingWindows += STEADY_WINDOWS;
if (pace.ceilingWindows < CEILING_WINDOWS) {
return;
}
pace.ceilingWindows = 0;
pace.ceiling *= 1.15;
}
pace.cap = Math.min(pace.cap * 1.2, pace.ceiling * 0.9);
scheduleContexts();
}
function observeDisplayInterval(interval: number) {
if (interval < MIN_DISPLAY_MS || interval > MAX_DISPLAY_MS) {
return;
}
pace.displaySamples.push(interval);
if (pace.displaySamples.length > DISPLAY_SAMPLES) {
pace.displaySamples.shift();
}
if (pace.displaySamples.length >= DISPLAY_SAMPLES / 2) {
// The low quartile tracks the fastest cadence while rejecting a dropped
// frame, and the rolling window relearns after a monitor/VRR change.
const sorted = [...pace.displaySamples].sort((a, b) => a - b);
pace.targetMs =
sorted[Math.floor((sorted.length - 1) * 0.25)] ?? DEFAULT_FRAME_MS;
}
}
/** Mounts call this on every animated rAF tick; a shared tick counts once. */
export function noteFrame(now: number): void {
const last = pace.lastTick;
if (now === last) {
return;
}
pace.lastTick = now;
if (last === null) {
return;
}
const interval = now - last;
const framePaintMs = pendingFramePaintMs;
pendingFramePaintMs = 0;
if (interval > MAX_INTERVAL_MS) {
pace.intervals = [];
pace.displaySamples = [];
pace.targetMs = DEFAULT_FRAME_MS;
return;
}
if (!pace.suppressDisplayLearning) observeDisplayInterval(interval);
if (pace.warmup > 0) {
pace.warmup -= 1;
if (pace.warmup === 0) pace.suppressDisplayLearning = false;
return;
}
// A visible animation can be throttled to a low VRR cadence while its
// paint work is idle. Do not call that a slowdown; heavy paint is judged.
if (
interval > pace.targetMs * 2 &&
framePaintMs > 0 &&
framePaintMs < pace.targetMs * 0.75
) {
pace.intervals = [];
return;
}
pace.intervals.push(interval);
if (pace.intervals.length >= PACE_WINDOW) {
const total = pace.intervals.reduce((sum, ms) => sum + ms, 0);
judgePace(total / pace.intervals.length);
pace.intervals = [];
}
}
function run() {
frame = 0;
const width = window.innerWidth;
const height = window.innerHeight;
const margin = height * APPROACH_MARGIN;
const ranked: { slot: ContextSlot; distance: number }[] = [];
for (const [slot, state] of slots) {
const rect = slot.element.getBoundingClientRect();
const distance = distanceToViewport(rect, width, height);
const hasArea = rect.width > 0 && rect.height > 0;
const visible = hasArea && distance === 0;
if (visible !== state.visible) {
state.visible = visible;
slot.setVisible(visible);
}
// An invisible primary cannot paint a smaller surface to make room for
// new thumbnails. Release its large WebGPU lease until it is visible.
const invisiblePrimary =
!visible && slot.primary() && slot.backend() === "webgpu";
if (hasArea && distance <= margin && !invisiblePrimary) {
ranked.push({ distance, slot });
}
}
ranked.sort((a, b) => a.distance - b.distance);
// Each backend has its own budget (WebGL contexts, WebGPU surfaces), so on
// a mixed page neither starves the other; nearest first within each. A
// backend with more near gradients than its budget keeps one back to paint
// still frames for the rest. The pixel budget below is shared by both.
const limits: Record<BackendName, number> = {
webgl2: MAX_LIVE_CONTEXTS,
webgpu: MAX_WEBGPU_SURFACES,
};
const near: Record<BackendName, number> = { webgl2: 0, webgpu: 0 };
const backends = new Map(ranked.map(({ slot }) => [slot, slot.backend()]));
for (const name of backends.values()) {
near[name] += 1;
}
const budget = (name: BackendName) =>
near[name] > limits[name] ? limits[name] - 1 : limits[name];
const granted: Record<BackendName, number> = { webgl2: 0, webgpu: 0 };
const wanted = new Set<ContextSlot>();
const leftover: ContextSlot[] = [];
for (const { slot } of ranked) {
const name = backends.get(slot) ?? "webgl2";
if (granted[name] < budget(name)) {
granted[name] += 1;
wanted.add(slot);
} else {
leftover.push(slot);
}
}
// Release first so the budget is free before granting.
for (const [slot, state] of slots) {
if (state.live && !wanted.has(slot)) {
state.live = false;
slot.revoke();
}
}
wantedSlots = wanted;
// Apply the reservation before admission, so a full-size pending surface
// does not get denied forever beside an already-grown primary.
assignQuality();
for (const slot of wanted) {
const state = slots.get(slot);
if (state && !state.live) {
state.live = slot.grant();
}
}
for (const slot of leftover) {
slot.paintStill();
}
trimContexts(granted.webgl2 + (near.webgl2 > limits.webgl2 ? 1 : 0));
trimSurfaces(granted.webgpu + (near.webgpu > limits.webgpu ? 1 : 0));
assignQuality();
}
/** Re-ranks on the next animation frame. Cheap to call often. */
export function scheduleContexts(): void {
if (frame === 0 && typeof window !== "undefined") {
frame = window.requestAnimationFrame(run);
}
}
/** Relearns the display cadence after a visibility, resize, or display change. */
export function relearnDisplayRate(): void {
pace.displaySamples = [];
pace.targetMs = DEFAULT_FRAME_MS;
pace.intervals = [];
}
function onWindowResize() {
relearnDisplayRate();
pendingFramePaintMs = 0;
scheduleContexts();
}
onPoolChange(scheduleContexts);
onWebGPUChange(scheduleContexts);
/** A gradient lost its context (the pool already ended the lease). */
export function slotLostContext(slot: ContextSlot): void {
const state = slots.get(slot);
if (state) {
state.live = false;
}
scheduleContexts();
}
function listen(on: boolean) {
if (on === listening) {
return;
}
listening = on;
if (on) {
window.addEventListener("scroll", scheduleContexts, {
capture: true,
passive: true,
});
window.addEventListener("scroll", noteScroll, {
capture: true,
passive: true,
});
window.addEventListener("resize", onWindowResize, { passive: true });
observer = new IntersectionObserver(scheduleContexts, {
rootMargin: `${APPROACH_MARGIN * 100}% 0px`,
});
for (const slot of slots.keys()) {
observer.observe(slot.element);
}
} else {
window.removeEventListener("scroll", scheduleContexts, { capture: true });
window.removeEventListener("scroll", noteScroll, { capture: true });
window.removeEventListener("resize", onWindowResize);
observer?.disconnect();
observer = null;
window.cancelAnimationFrame(frame);
frame = 0;
}
}
export function registerSlot(slot: ContextSlot): void {
slots.set(slot, {
live: false,
quality: { halfRate: false, scale: 1 },
visible: false,
});
listen(true);
observer?.observe(slot.element);
scheduleContexts();
}
export function unregisterSlot(slot: ContextSlot): void {
if (!slots.delete(slot)) {
return;
}
observer?.unobserve(slot.element);
if (slots.size === 0) {
listen(false);
trimContexts(0);
trimSurfaces(0);
} else {
scheduleContexts();
}
}
/** Changes the per-frame pixel budget (Infinity turns it off). For tuning and the engine lab. */
export function setPixelBudget(pixels: number): void {
pixelBudget = pixels > 0 ? pixels : PIXEL_BUDGET;
scheduleContexts();
}
/** The governor's state. For tests and the engine lab. */
export function paceStats(): {
/** Most pixels per frame; Infinity until frames have been slow. */
cap: number;
/** Current rolling display interval estimate in milliseconds. */
targetMs: number;
/** Ignoring ticks after the animating set or its quality changed. */
warmingUp: boolean;
} {
return { cap: pace.cap, targetMs: pace.targetMs, warmingUp: pace.warmup > 0 };
}
/** Forgets what the governor learned. For tests and the engine lab. */
export function resetPace(): void {
pace.cap = Number.POSITIVE_INFINITY;
pace.ceiling = Number.POSITIVE_INFINITY;
pace.ceilingWindows = 0;
pace.lastTick = null;
pace.suppressDisplayLearning = false;
relearnDisplayRate();
primaryBudget = PRIMARY_PIXEL_BUDGET;
scrolling = false;
if (
typeof window !== "undefined" &&
typeof window.clearTimeout === "function"
) {
window.clearTimeout(scrollIdleTimer);
}
restartPace();
scheduleContexts();
}
/** Counts for tests and the engine lab. */
export function contextStats(): {
/** WebGL contexts that exist right now, never more than MAX_LIVE_CONTEXTS. */
contexts: number;
/** WebGPU surfaces that exist right now, never more than MAX_WEBGPU_SURFACES. */
surfaces: number;
/** Animating gradients per backend. */
liveByBackend: Record<BackendName, number>;
/** Gradients currently animating with a leased context. */
live: number;
mounted: number;
/** Drawing-buffer pixels rendered per frame by animating gradients. */
pixelsPerFrame: number;
halfRate: boolean;
} {
let live = 0;
let pixelsPerFrame = 0;
let halfRate = false;
const liveByBackend: Record<BackendName, number> = { webgl2: 0, webgpu: 0 };
for (const [slot, state] of slots) {
if (state.live) {
live += 1;
liveByBackend[slot.backend()] += 1;
}
if (state.live && state.visible) {
pixelsPerFrame += slot.pixels() * state.quality.scale ** 2;
halfRate ||= state.quality.halfRate;
}
}
return {
contexts: liveContextCount(),
halfRate,
live,
liveByBackend,
mounted: slots.size,
pixelsPerFrame: Math.round(pixelsPerFrame),
surfaces: webgpuStats().surfaces,
};
}
let paintMs = 0;
let pendingFramePaintMs = 0;
let paintCount = 0;
/** Called by mounts with the time one animated frame took to render and copy. */
export function recordPaint(ms: number): void {
paintMs += ms;
pendingFramePaintMs += ms;
paintCount += 1;
}
/** Paint time totals since the last call, then resets them. For the engine lab. */
export function takePaintStats(): { paints: number; ms: number } {
const stats = { ms: paintMs, paints: paintCount };
paintMs = 0;
paintCount = 0;
return stats;
}
function engineStats(): EngineStats {
let scaleTotal = 0;
let scaleCount = 0;
let halfRate = false;
for (const [, state] of slots) {
if (state.live && state.visible) {
scaleTotal += state.quality.scale;
scaleCount += 1;
halfRate ||= state.quality.halfRate;
}
}
return {
animatingMounts: animatingCount,
fpsTier: halfRate ? "half" : "full",
gpuTimeMs: null,
mounted: slots.size,
paceCap: pace.cap,
rafIntervals: pace.intervals.slice(),
renderScale: scaleCount === 0 ? 1 : scaleTotal / scaleCount,
renderedPixels: Math.round(renderedPixels),
scrolling,
};
}
if (typeof globalThis.window !== "undefined") {
globalThis.window.__gcnEngineStats = engineStats;
}
@@ -1,69 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick } from "../kind";
export const aurora: GradientKindDefinition = {
defaults: {
background: "#03050b",
blur: 0.35,
colors: ["#a0f0c8", "#3fb5a3", "#5147b6", "#b25c9c"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.1,
interaction: { pointer: 0.2, scroll: 0.2 },
loopSeconds: 18,
scale: 1,
seed: 3,
speed: 0.7,
warp: 0.5,
},
description: "Folded curtains of light hanging over a night sky.",
fallbackLayers: (colors) => [
...colors.map(
(_, i) =>
`radial-gradient(30% 55% at ${15 + (70 * i) / Math.max(1, colors.length - 1)}% 30%, color-mix(in oklab, ${pick(colors, i)} 75%, transparent) 0%, transparent 70%)`,
),
`linear-gradient(180deg, transparent 35%, color-mix(in oklab, ${pick(colors, 0)} 45%, transparent) 58%, transparent 80%)`,
],
glsl: `
// One curtain sheet. Returns its intensity and the height above its hem (0..1).
vec2 auroraSheet(vec2 p, float layer, float hem0, bool detail) {
float x = p.x * u_scale;
// Folds sway the sheet sideways, more so higher up.
float fold = flowNoise(vec2(x * 0.5, p.y * 0.25 + layer), layer);
float xf = x + (0.1 + 0.3 * u_warp) * fold;
float hem = hem0 + 0.24 * flowNoise(vec2(xf * 0.6, layer * 3.1), layer + 1.0)
+ 0.1 * sin(x * 1.2 + layer) + 0.06 * fold + 0.08 * x * x;
float rise = p.y - hem;
float up = exp(-max(rise, 0.0) * (2.8 - 1.0 * u_blur));
float down = exp(min(rise, 0.0) * (9.0 - 5.0 * u_blur));
// Rays: fine across the sheet, stretched along it.
float n = 0.65 * flowNoise(vec2(xf * 4.0, p.y * 0.15), layer + 2.0);
if (detail) {
n += 0.35 * flowNoise(vec2(xf * 11.0, p.y * 0.3), layer + 3.0);
}
float rays = mix(1.0, 0.6 + 0.55 * n, 0.85 - 0.45 * u_blur);
// The sheet thins where it folds edge-on.
float density = 0.45 + 0.55 * smoothstep(-0.6, 0.6, fold);
return vec2(up * down * rays * density, clamp(rise / 0.75, 0.0, 1.0));
}
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
vec3 lab = u_bg;
lab.x += 0.035 * smoothstep(0.3, -h.y, p.y);
vec2 back = auroraSheet(p * vec2(0.75, 1.0) + vec2(0.9, 0.0), 11.0, -0.02, false);
vec2 front = auroraSheet(p, 13.0, -0.3, true);
lab = labMix(lab, ramp(0.3 + 0.7 * back.y), clamp(back.x * 0.35, 0.0, 1.0));
lab = labMix(lab, ramp(front.y), clamp(front.x * 1.45, 0.0, 1.0));
// A bright hem, and the light it throws onto the horizon.
lab.x += 0.12 * front.x * (1.0 - front.y);
float horizon = exp(-(p.y + h.y) * 5.0) * (0.5 + 0.5 * front.x);
lab = labMix(lab, paletteColor(1), clamp(horizon * 0.2, 0.0, 1.0));
lab.x *= vignette(p, 0.3);
return filmGrade(lab);
}
`,
wgsl: () => import("./wgsl/aurora").then((module) => module.wgsl),
label: "Aurora",
name: "aurora",
};
@@ -1,139 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick } from "../kind";
export const beam: GradientKindDefinition = {
defaults: {
background: "#02030a",
blur: 0.35,
colors: ["#f4f7ff", "#8fb4ff", "#3d5bff", "#1a1660"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.2,
interaction: { pointer: 0.15, scroll: 0.1 },
loopSeconds: 14,
scale: 1,
seed: 2,
speed: 0.6,
warp: 0.6,
},
description:
"A cone of streaked light thrown from a source on the edge of the frame.",
fallbackLayers: (colors) => [
`radial-gradient(60% 90% at 50% 100%, color-mix(in oklab, ${pick(colors, 0)} 80%, transparent) 0%, color-mix(in oklab, ${pick(colors, 1)} 55%, transparent) 18%, color-mix(in oklab, ${pick(colors, 2)} 30%, transparent) 45%, transparent 75%)`,
`conic-gradient(from 315deg at 50% 100%, transparent 0deg, color-mix(in oklab, ${pick(colors, 3)} 25%, transparent) 45deg, transparent 90deg)`,
],
glsl: `
// Light from a point on or beyond the frame edge, spread into a cone of
// rays. The rays are noise sampled across the cone's angle, so they are
// fine across and long along the beam. scale widens the cone; warp sets
// ray contrast.
// One beam. Returns glow, the palette position, and how much of the light
// is the white-hot core and needle.
vec3 beamLight(vec2 p, vec2 source, float aim, float width, float reach, float layer, float omni) {
vec2 axis = vec2(sin(aim), cos(aim));
vec2 v = p - source;
float dist = length(v);
float along = dot(v, axis);
float across = axis.x * v.y - axis.y * v.x;
float ang = atan(across, max(along, 1e-3));
float u = ang / width;
float forward = smoothstep(-0.02, 0.06, along);
float cone = exp(-u * u) * forward;
// Rays: two scales of noise across the cone, stretched along it. A flare
// rays out all round, so it samples on the unit circle instead, which
// has no seam behind the source.
vec2 dir = v / max(dist, 1e-4);
vec2 coarseAt = omni > 0.5 ? dir * 3.2 + vec2(dist * 0.35, 0.0) : vec2(u * 2.2, dist * 0.35);
vec2 fineAt = omni > 0.5 ? dir * 9.0 + vec2(13.0, dist * 0.9) : vec2(u * 6.0 + 13.0, dist * 0.9);
float coarse = flowNoise(coarseAt, layer);
float fine = flowNoise(fineAt, layer + 1.0);
cone = mix(cone, 0.55 + 0.45 * exp(-u * u), omni);
forward = mix(forward, 1.0, omni);
float fineAmount = 0.55 * (1.0 - 0.6 * u_blur);
float rays = 0.5 + 0.5 * (coarse + fineAmount * fine) / (1.0 + fineAmount);
rays = mix(1.0, smoothstep(0.1, 0.95, rays) * 1.5, u_warp);
float fall = exp(-dist / reach);
float core = exp(-dist / (0.05 + 0.05 * u_blur));
// A hairline down the axis, the brightest ray.
float needle = exp(-pow(across / (0.0035 + 0.01 * u_blur), 2.0)) * exp(-dist / (0.6 * reach)) * smoothstep(0.0, 0.03, along) * u_warp * (1.0 - 0.5 * omni);
float haze = exp(-dist / (0.4 + 0.5 * u_blur));
// A broad, soft fill under the rays gives the beam volume.
float fill = mix(exp(-u * u * 0.35), 1.0, omni) * forward * fall;
float glow = cone * fall * (0.2 + 0.8 * rays) + 0.22 * fill + 0.85 * core + 0.55 * needle + 0.08 * haze;
// Near the source the light is colour 0; colour takes over along the
// beam and at the cone's edges.
float t = clamp(dist / (reach * 1.4) + 0.35 * abs(u) * (1.0 - omni) - 0.25 * core, 0.0, 1.0);
return vec3(glow, t, clamp(core + needle, 0.0, 1.0));
}
vec3 kindColor(vec2 p, vec2 uv) {
float lightBg = smoothstep(0.55, 0.85, u_bg.x);
vec2 h = frameHalf();
// The seed picks the source: bottom centre, a bottom corner, the top
// edge, a top corner, a side edge, two crossing beams from the bottom
// corners, a source far below or above the frame, so only its rays
// reach in, or a flare inside the frame raying out all round.
float framing = floor(fract(u_seed.x * 0.0731 + 0.5) * 9.0);
float side = sign(u_seed.y + 0.01);
vec2 source = vec2(0.0, -h.y - 0.02);
float aim = 0.0;
float width = 0.3 * u_scale;
float reach = 0.55 + 0.6 * u_scale;
if (framing == 1.0) {
source = vec2(-side * (h.x - 0.06), -h.y - 0.02);
aim = side * 0.62;
} else if (framing == 2.0) {
source = vec2(0.0, h.y + 0.02);
aim = 3.14159265;
} else if (framing == 3.0) {
source = vec2(-side * (h.x - 0.1), h.y + 0.02);
aim = 3.14159265 - side * 0.5;
} else if (framing == 4.0) {
source = vec2(-side * (h.x + 0.02), -0.12);
aim = side * 1.32;
} else if (framing == 5.0) {
source = vec2(-(h.x - 0.12), -h.y - 0.02);
aim = 0.42;
width *= 0.7;
} else if (framing == 6.0) {
source = vec2(0.3 * h.x * side, -h.y - 1.0);
aim = -side * 0.12;
width *= 0.45;
reach *= 2.4;
} else if (framing == 7.0) {
source = vec2(0.3 * h.x * side, h.y + 1.0);
aim = 3.14159265 + side * 0.15;
width *= 0.45;
reach *= 2.4;
} else if (framing == 8.0) {
source = vec2(0.22 * h.x * side, 0.04);
aim = seedAngle();
width = 0.6 * u_scale;
reach = 0.3 + 0.3 * u_scale;
}
// The cone sways a little through the loop.
float sway = 0.22 * u_loop.y;
vec3 light = beamLight(p, source, aim + sway, width, reach, 1.0, framing == 8.0 ? 1.0 : 0.0);
if (framing == 5.0) {
// The second beam mirrors the first and sways the other way.
vec3 twin = beamLight(p, vec2(-source.x, source.y), -aim - sway, width, reach, 4.0, 0.0);
float total = max(light.x + twin.x, 1e-4);
light = vec3(light.x + twin.x, (light.x * light.y + twin.x * twin.y) / total, max(light.z, twin.z));
}
float glow = light.x;
vec3 col = ramp(light.y);
col = labMix(col, paletteColor(0), light.z);
vec3 lab = labMix(u_bg, col, clamp(glow, 0.0, 1.0));
lab.x += 0.08 * max(glow - 0.9, 0.0) * (1.0 - lightBg);
return filmGrade(lab);
}
`,
wgsl: () => import("./wgsl/beam").then((module) => module.wgsl),
label: "Beam",
name: "beam",
};
@@ -1,89 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick } from "../kind";
/**
* Liquid chrome filling the frame. A slow, flowing surface reflects a
* studio of soft light bands, so highlights run along the folds and the
* troughs fall to black. Colour 1 is the studio light the metal mostly
* shows, colour 2 the hot highlight, colour 3 an optional cool rim seen at
* grazing angles. `scale` sets the size of the swells, `warp` how much the
* surface folds, `blur` softens the reflections.
*/
export const chrome: GradientKindDefinition = {
defaults: {
background: "#050203",
blur: 0.2,
colors: ["#e0202e", "#ffd6b8", "#4fe3f0"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.06,
interaction: { pointer: 0.2, scroll: 0.2 },
loopSeconds: 24,
scale: 1,
seed: 6,
speed: 0.5,
warp: 0.5,
},
description: "Liquid metal folding slowly under studio light.",
fallbackLayers: (colors) => [
`radial-gradient(60% 30% at 40% 38%, color-mix(in oklab, ${pick(colors, 1)} 70%, transparent), transparent 70%)`,
`linear-gradient(160deg, transparent 20%, ${pick(colors, 0)} 45%, transparent 60%, color-mix(in oklab, ${pick(colors, 0)} 60%, transparent) 75%, transparent 90%)`,
`linear-gradient(20deg, transparent 60%, color-mix(in oklab, ${pick(colors, 2)} 35%, transparent) 70%, transparent 78%)`,
],
glsl: `
// Height of the metal: long folds running one way, their crests bent by a
// slow noise field so they curve and bunch like draped cloth, with a faint
// cross fold. Ridges rather than domes, so reflections stream along the
// folds instead of ringing. The folds roll a whole wavelength each loop.
float chromeHeight(vec2 q, vec2 t1, vec2 t2) {
float bendBy = (0.9 + 1.6 * u_warp) * flowNoise(q * vec2(0.35, 0.55), 2.0);
float a = 2.1 * q.y + bendBy;
float c = 1.3 * q.x + 0.4 * bendBy + 1.3;
return sin(a) * t1.x - cos(a) * t1.y
+ 0.2 * (sin(2.0 * a + 0.9) * t2.x - cos(2.0 * a + 0.9) * t2.y) * (1.0 - 0.6 * u_blur)
+ 0.15 * (sin(c) * t2.x - cos(c) * t2.y);
}
// The studio as seen in a reflection direction: a dark floor with a soft
// bounce and a light behind the camera, a dark horizon line, a bright sky with a cool band and a hot key, and darker ceiling.
vec3 chromeStudio(vec3 r, float sa) {
float t = r.y * 0.9 + 0.3 * r.x * cos(sa);
float soft = 0.04 + 0.12 * u_blur;
vec3 floorC = labMix(u_bg, paletteColor(0), 0.08 + 0.5 * smoothstep(0.9, 1.0, r.z));
// A broad, dimmer bounce off the floor, so downward slopes still read as metal.
floorC = labMix(floorC, paletteColor(0), 0.7 * exp(-pow((t + 0.5) / (0.18 + soft), 2.0)));
vec3 env = labMix(floorC, paletteColor(0), smoothstep(0.1, 0.3, t));
float horizon = exp(-pow((t - 0.12) / (soft * 1.3), 2.0));
env = labMix(env, u_bg, 0.92 * horizon);
float cool = exp(-pow((t - 0.4) / (soft * 0.9), 2.0));
env = labMix(env, paletteColor(u_count > 2 ? 2 : 1), 0.55 * cool);
float key = exp(-pow((t - 0.58) / soft, 2.0));
env = labMix(env, paletteColor(1), key);
env.x += 0.16 * key * key;
env = labMix(env, u_bg, 0.6 * smoothstep(0.75, 1.0, t));
return env;
}
vec3 kindColor(vec2 p, vec2 uv) {
float sa = seedAngle();
vec2 t1 = loopTurn();
vec2 t2 = vec2(t1.x * t1.x - t1.y * t1.y, 2.0 * t1.x * t1.y);
vec2 q = rot2(0.6 * sin(sa) + 0.3) * p * 1.75 * u_scale + vec2(1.7, -0.9) * cos(sa);
float e = 0.004;
float h = chromeHeight(q, t1, t2);
vec2 g = vec2(chromeHeight(q + vec2(e, 0.0), t1, t2) - h, chromeHeight(q + vec2(0.0, e), t1, t2) - h) / e;
vec3 n = normalize(vec3(-g * 0.6 / sqrt(u_scale), 1.0));
vec3 r = reflect(vec3(0.0, 0.0, -1.0), n);
vec3 lab = chromeStudio(r, sa);
// Low ground sits in shadow.
lab = labMix(lab, u_bg, 0.3 * (1.0 - smoothstep(-1.8, -0.6, h)));
lab.x *= vignette(p, 0.35);
return filmGrade(lab);
}
`,
label: "Chrome",
name: "chrome",
wgsl: () => import("./wgsl/chrome").then((module) => module.wgsl),
};
@@ -1,351 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
/**
* Shared GLSL for every kind. A kind supplies `vec3 kindColor(vec2 p, vec2 uv)`
* returning OKLab; the prelude gives it noise, palette helpers and coordinates,
* and the postlude converts to sRGB and applies grain and dither.
*
* Coordinates are always derived from the full image (u_full) plus the tile
* origin (u_tile), so a tiled render matches a full render pixel for pixel.
* Motion only ever reads u_loop, a point on a circle, so frames repeat exactly
* every loop.
*/
export const vertexShader = `#version 300 es
in vec2 a_position;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
}
`;
export const fragmentPrelude = `#version 300 es
precision highp float;
precision highp int;
uniform vec2 u_full; // full image size in pixels
uniform vec4 u_tile; // tile x, y (top-left origin), width, height
uniform vec2 u_loop; // (cos, sin)(phase) * speed * radius
uniform vec2 u_seed; // seed offset in noise space
uniform float u_scale;
uniform float u_warp;
uniform float u_blur;
uniform float u_grain;
uniform float u_frame; // grain seed
uniform vec3 u_dither; // enabled, cell, levels
uniform vec3 u_colors[6]; // OKLab
uniform int u_count;
uniform vec3 u_bg; // OKLab
uniform vec3 u_pointer; // x, y in image uv (top-left origin), influence
uniform float u_scroll; // smoothed scroll velocity * influence
out vec4 outColor;
// 4D simplex noise. Ian McEwan, Stefan Gustavson, Ashima Arts (MIT).
vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
float mod289(float x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec4 permute(vec4 x) { return mod289(((x * 34.0) + 10.0) * x); }
float permute(float x) { return mod289(((x * 34.0) + 10.0) * x); }
vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }
float taylorInvSqrt(float r) { return 1.79284291400159 - 0.85373472095314 * r; }
vec4 grad4(float j, vec4 ip) {
const vec4 ones = vec4(1.0, 1.0, 1.0, -1.0);
vec4 p, s;
p.xyz = floor(fract(vec3(j) * ip.xyz) * 7.0) * ip.z - 1.0;
p.w = 1.5 - dot(abs(p.xyz), ones.xyz);
s = vec4(lessThan(p, vec4(0.0)));
p.xyz = p.xyz + (s.xyz * 2.0 - 1.0) * s.www;
return p;
}
float snoise(vec4 v) {
const vec4 C = vec4(0.138196601125011, 0.276393202250021, 0.414589803375032, -0.447213595499958);
vec4 i = floor(v + dot(v, vec4(0.309016994374947451)));
vec4 x0 = v - i + dot(i, C.xxxx);
vec4 i0;
vec3 isX = step(x0.yzw, x0.xxx);
vec3 isYZ = step(x0.zww, x0.yyz);
i0.x = isX.x + isX.y + isX.z;
i0.yzw = 1.0 - isX;
i0.y += isYZ.x + isYZ.y;
i0.zw += 1.0 - isYZ.xy;
i0.z += isYZ.z;
i0.w += 1.0 - isYZ.z;
vec4 i3 = clamp(i0, 0.0, 1.0);
vec4 i2 = clamp(i0 - 1.0, 0.0, 1.0);
vec4 i1 = clamp(i0 - 2.0, 0.0, 1.0);
vec4 x1 = x0 - i1 + C.xxxx;
vec4 x2 = x0 - i2 + C.yyyy;
vec4 x3 = x0 - i3 + C.zzzz;
vec4 x4 = x0 + C.wwww;
i = mod289(i);
float j0 = permute(permute(permute(permute(i.w) + i.z) + i.y) + i.x);
vec4 j1 = permute(permute(permute(permute(
i.w + vec4(i1.w, i2.w, i3.w, 1.0))
+ i.z + vec4(i1.z, i2.z, i3.z, 1.0))
+ i.y + vec4(i1.y, i2.y, i3.y, 1.0))
+ i.x + vec4(i1.x, i2.x, i3.x, 1.0));
vec4 ip = vec4(1.0 / 294.0, 1.0 / 49.0, 1.0 / 7.0, 0.0);
vec4 p0 = grad4(j0, ip);
vec4 p1 = grad4(j1.x, ip);
vec4 p2 = grad4(j1.y, ip);
vec4 p3 = grad4(j1.z, ip);
vec4 p4 = grad4(j1.w, ip);
vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3)));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
p4 *= taylorInvSqrt(dot(p4, p4));
vec3 m0 = max(0.6 - vec3(dot(x0, x0), dot(x1, x1), dot(x2, x2)), 0.0);
vec2 m1 = max(0.6 - vec2(dot(x3, x3), dot(x4, x4)), 0.0);
m0 = m0 * m0;
m1 = m1 * m1;
return 49.0 * (dot(m0 * m0, vec3(dot(p0, x0), dot(p1, x1), dot(p2, x2)))
+ dot(m1 * m1, vec2(dot(p3, x3), dot(p4, x4))));
}
// 2D simplex noise, same authors and licence. About a third of the cost of
// snoise(vec4), so kinds use it for structure and keep the 4D noise for the
// few places that need the field itself to morph.
vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec2 mod289(vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }
vec3 permute(vec3 x) { return mod289(((x * 34.0) + 10.0) * x); }
float snoise2(vec2 v) {
const vec4 C = vec4(0.211324865405187, 0.366025403784439, -0.577350269189626, 0.024390243902439);
vec2 i = floor(v + dot(v, C.yy));
vec2 x0 = v - i + dot(i, C.xx);
vec2 i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
vec4 x12 = x0.xyxy + C.xxzz;
x12.xy -= i1;
i = mod289(i);
vec3 p = permute(permute(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0));
vec3 m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), 0.0);
m = m * m;
m = m * m;
vec3 x = 2.0 * fract(p * C.www) - 1.0;
vec3 h = abs(x) - 0.5;
vec3 ox = floor(x + 0.5);
vec3 a0 = x - ox;
m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);
vec3 g;
g.x = a0.x * x0.x + h.x * x0.y;
g.yz = a0.yz * x12.xz + h.yz * x12.yw;
return 130.0 * dot(m, g);
}
// Time coordinates for a noise layer. Every layer moves on its own circle.
vec2 loopAt(float layer) {
return u_loop + vec2(layer * 1.71, layer * -2.37);
}
// Looping noise: spatial position plus a point on the time circle.
float loopNoise(vec2 p, float layer) {
return snoise(vec4(p + u_seed, loopAt(layer)));
}
// Three octaves; blur fades out the fine ones.
float fbm(vec2 p, float layer) {
float fine = 1.0 - 0.85 * u_blur;
float sum = loopNoise(p, layer);
sum += 0.5 * fine * loopNoise(p * 2.03 + 17.1, layer + 0.5);
sum += 0.25 * fine * fine * loopNoise(p * 4.07 - 9.7, layer + 1.0);
return sum / (1.0 + 0.5 * fine + 0.25 * fine * fine);
}
// The loop point rotated per layer. Translating a field by it is seamless,
// and layers drifting in different directions read as slow morphing.
vec2 drift(float layer) {
float a = layer * 2.39996;
float c = cos(a);
float s = sin(a);
return mat2(c, s, -s, c) * u_loop;
}
// Cheap looping noise: a 2D field translated around the loop circle.
float flowNoise(vec2 p, float layer) {
return snoise2(p + u_seed + drift(layer) + vec2(layer * 7.13, layer * 3.71));
}
// The loop angle as a unit vector, so waves can travel a whole period per
// loop. Frozen when speed is 0.
vec2 loopTurn() {
float r = length(u_loop);
return r > 1e-6 ? u_loop / r : vec2(1.0, 0.0);
}
// sin(a - angle), where cs = (cos, sin)(angle).
float turnSin(float a, vec2 cs) {
return sin(a) * cs.x - cos(a) * cs.y;
}
mat2 rot2(float a) {
float c = cos(a);
float s = sin(a);
return mat2(c, s, -s, c);
}
// tanh that stays finite: some GPUs evaluate tanh(x) as a ratio of exps,
// which is inf/inf = NaN for large x.
float safeTanh(float x) {
return tanh(clamp(x, -9.0, 9.0));
}
// The brightest lightness and strongest chroma among the supplied colours.
vec2 paletteRange() {
float l = u_bg.x;
float c = length(u_bg.yz);
for (int i = 0; i < 6; i++) {
if (i >= u_count) break;
l = max(l, u_colors[i].x);
c = max(c, length(u_colors[i].yz));
}
return vec2(l, c);
}
// Filmic grade in OKLab for the light a kind adds. It is an identity map for
// anything inside the palette's own range, so supplied colours and theme
// tokens render as chosen. Only highlights pushed past the brightest colour
// get a soft shoulder, and only chroma pushed past both the most saturated
// colour and a film-like cap (which eases off toward black and white) rolls off.
vec3 filmGrade(vec3 lab) {
vec2 range = paletteRange();
float l = max(lab.x, 0.0);
float shoulder = max(range.x, 0.8);
if (l > shoulder) {
float room = max(1.0 - shoulder, 1e-3);
l = shoulder + room * safeTanh((l - shoulder) / room);
}
float c = length(lab.yz);
float cap = 0.05 + 0.9 * l * (1.0 - l) * (0.5 + 0.5 * l);
float knee = max(range.y, 0.6 * cap);
float top = max(cap, knee + 0.02);
float soft = c <= knee ? c : knee + (top - knee) * safeTanh((c - knee) / (top - knee));
float k = c > 1e-5 ? soft / c : 1.0;
return vec3(l, lab.yz * k);
}
// Darkens the corners in OKLab lightness; amount 0..1.
float vignette(vec2 p, float amount) {
vec2 q = p / (0.5 * u_full / min(u_full.x, u_full.y));
return 1.0 - amount * smoothstep(0.35, 1.45, dot(q, q) * 0.55);
}
// Half the frame size in p units; the short side spans -0.5..0.5.
vec2 frameHalf() {
return 0.5 * u_full / min(u_full.x, u_full.y);
}
float seedAngle() {
return fract(u_seed.x * 0.1371 + u_seed.y * 0.0713) * 6.28318530718;
}
// Mix in OKLab, then pull chroma back toward the endpoints so midpoints stay vivid.
vec3 labMix(vec3 a, vec3 b, float t) {
vec3 m = mix(a, b, t);
float target = mix(length(a.yz), length(b.yz), t);
float current = length(m.yz);
if (current > 1e-4) {
m.yz *= mix(1.0, target / current, 0.75);
}
return m;
}
vec3 paletteColor(int i) {
return u_colors[clamp(i, 0, u_count - 1)];
}
// Smooth ramp through the palette, t in 0..1.
vec3 ramp(float t) {
float x = clamp(t, 0.0, 1.0) * float(u_count - 1);
int i = int(floor(x));
float f = x - float(i);
f = f * f * (3.0 - 2.0 * f);
return labMix(paletteColor(i), paletteColor(i + 1), f);
}
// Pointer: a soft lens that pulls the field toward the cursor.
// Scroll: velocity shears the field vertically.
vec2 interact(vec2 p) {
vec2 half_ = frameHalf();
vec2 ptr = (u_pointer.xy - 0.5) * 2.0 * half_;
ptr.y = -ptr.y;
vec2 d = p - ptr;
float f = exp(-dot(d, d) * 5.0) * u_pointer.z;
p -= d * f * 0.45;
p.y += u_scroll * 0.08 * (0.6 + 0.4 * sin(p.x * 3.0));
return p;
}
`;
export const fragmentPostlude = `
vec3 oklabToLinear(vec3 lab) {
float l = lab.x + 0.3963377774 * lab.y + 0.2158037573 * lab.z;
float m = lab.x - 0.1055613458 * lab.y - 0.0638541728 * lab.z;
float s = lab.x - 0.0894841775 * lab.y - 1.2914855480 * lab.z;
l = l * l * l;
m = m * m * m;
s = s * s * s;
return vec3(
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s
);
}
vec3 linearToSrgb(vec3 c) {
c = clamp(c, 0.0, 1.0);
vec3 lo = c * 12.92;
vec3 hi = 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055;
return mix(hi, lo, vec3(lessThanEqual(c, vec3(0.0031308))));
}
uint hashU(uint x) {
x ^= x >> 16;
x *= 0x7feb352du;
x ^= x >> 15;
x *= 0x846ca68bu;
x ^= x >> 16;
return x;
}
float hash01(uvec2 p, uint s) {
return float(hashU(p.x ^ hashU(p.y ^ hashU(s)))) / 4294967295.0;
}
const float BAYER[16] = float[16](
0.0, 8.0, 2.0, 10.0,
12.0, 4.0, 14.0, 6.0,
3.0, 11.0, 1.0, 9.0,
15.0, 7.0, 13.0, 5.0
);
void main() {
vec2 px = vec2(u_tile.x + gl_FragCoord.x, u_tile.y + (u_tile.w - gl_FragCoord.y));
bool dither = u_dither.x > 0.5;
vec2 cell = floor(px / u_dither.y);
vec2 samplePx = dither ? (cell + 0.5) * u_dither.y : px;
vec2 uv = samplePx / u_full;
vec2 p = (samplePx - 0.5 * u_full) / min(u_full.x, u_full.y);
p.y = -p.y;
p = interact(p);
vec3 rgb = linearToSrgb(oklabToLinear(kindColor(p, uv)));
// Triangular, deterministic grain seeded by the frame. A trace stays on even
// at grain 0 to break up 8-bit banding.
uvec2 ip = uvec2(px);
uint frame = uint(u_frame);
float n = hash01(ip, frame * 2u + 1u) + hash01(ip, frame * 2u + 2u) - 1.0;
float lum = dot(rgb, vec3(0.2126, 0.7152, 0.0722));
float amp = u_grain * 0.2 * (0.55 + 0.9 * lum * (1.0 - lum)) + (dither ? 0.0 : 1.0 / 255.0);
rgb += n * amp;
if (dither) {
ivec2 b = ivec2(mod(cell, 4.0));
float threshold = (BAYER[b.y * 4 + b.x] + 0.5) / 16.0;
float steps = u_dither.z - 1.0;
rgb = floor(clamp(rgb, 0.0, 1.0) * steps + threshold) / steps;
}
outColor = vec4(clamp(rgb, 0.0, 1.0), 1.0);
}
`;
@@ -1,203 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { stops } from "../kind";
/**
* One soft light drawn through ordered dither. The light is a single
* structure (rays bursting from an edge, a horizon glowing up out of the
* dark, a diagonal beam, or a bloom from a corner), and it is quantised per
* sRGB channel in square cells, so ramps keep every hue in between and
* mid-tones fizz with neighbouring colours. That is the difference from
* dither-field and the Pro dither-gradient, which pick whole palette stops.
*
* The seed picks the structure, the side the light comes from, and the
* threshold matrix (Bayer 8x8 or interleaved gradient noise, which reads
* like blue noise). Colours run from the light's outer edge (first) to its
* core (last); the background is the dark (or paper) it falls into.
*
* The dither is the kind's own look, always on: 3px cells and 12 steps per
* channel. Switch the engine's dither on and it replaces this one, with its
* own cell and levels, on the same soft light. `scale` sizes the light,
* `warp` sets ray and edge contrast, `blur` its softness.
*
* Helpers are prefixed `db` and only depend on the prelude.
*/
export const ditherBurst: GradientKindDefinition = {
defaults: {
background: "#030305",
blur: 0.5,
colors: ["#1b2cc1", "#3d7bff", "#bcd3ff", "#f6f4ef"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0,
interaction: { pointer: 0.15, scroll: 0 },
loopSeconds: 18,
scale: 1,
seed: 2,
speed: 0.5,
warp: 0.55,
},
description:
"A soft burst of light resolved into crisp dither cells, every hue kept.",
// The light rising from below, core colour at the bottom edge.
fallbackLayers: (colors) => [
`radial-gradient(90% 80% at 50% 108%, ${stops([...colors].reverse(), 6, 62)}, transparent 76%)`,
],
glsl: `
float dbBayer2(vec2 a) {
a = floor(a);
return fract(dot(a, vec2(0.5, a.y * 0.75)));
}
float dbBayer8(vec2 a) {
return dbBayer2(0.25 * a) * 0.0625 + dbBayer2(0.5 * a) * 0.25 + dbBayer2(a);
}
// Interleaved gradient noise (Jimenez 2014): ordered, but with no visible
// period, so it reads like blue noise.
float dbIgn(vec2 a) {
return fract(52.9829189 * fract(dot(floor(a), vec2(0.06711056, 0.00583715))));
}
vec3 dbLabToSrgb(vec3 lab) {
float l = lab.x + 0.3963377774 * lab.y + 0.2158037573 * lab.z;
float m = lab.x - 0.1055613458 * lab.y - 0.0638541728 * lab.z;
float s = lab.x - 0.0894841775 * lab.y - 1.2914855480 * lab.z;
vec3 lin = vec3(
4.0767416621 * l * l * l - 3.3077115913 * m * m * m + 0.2309699292 * s * s * s,
-1.2684380046 * l * l * l + 2.6097574011 * m * m * m - 0.3413193965 * s * s * s,
-0.0041960863 * l * l * l - 0.7034186147 * m * m * m + 1.7076147010 * s * s * s
);
lin = clamp(lin, 0.0, 1.0);
return mix(1.055 * pow(lin, vec3(1.0 / 2.4)) - 0.055, lin * 12.92, vec3(lessThanEqual(lin, vec3(0.0031308))));
}
vec3 dbSrgbToLab(vec3 c) {
vec3 lin = mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, vec3(lessThanEqual(c, vec3(0.04045))));
float l = 0.4122214708 * lin.r + 0.5363325363 * lin.g + 0.0514459929 * lin.b;
float m = 0.2119034982 * lin.r + 0.6806995451 * lin.g + 0.1073969566 * lin.b;
float s = 0.0883024619 * lin.r + 0.2817188376 * lin.g + 0.6299787005 * lin.b;
vec3 lms = pow(max(vec3(l, m, s), 0.0), vec3(1.0 / 3.0));
return vec3(
0.2104542553 * lms.x + 0.7936177850 * lms.y - 0.0040720468 * lms.z,
1.9779984951 * lms.x - 2.4285922050 * lms.y + 0.4505937099 * lms.z,
0.0259040371 * lms.x + 0.7827717662 * lms.y - 0.8086757660 * lms.z
);
}
// How far the palette strays from the background. A flat palette has
// nothing to dither between, so it renders flat.
float dbSpread() {
float d = 0.0;
for (int i = 0; i < 6; i++) {
if (i >= u_count) break;
d = max(d, length(u_colors[i] - u_bg));
}
return smoothstep(0.0, 0.04, d);
}
// The light's intensity at q: 0 is the background, 1 the core.
float dbLight(vec2 q, vec2 h, float mode, float side) {
float s = 1.0 / u_scale;
float soft = 0.6 + 0.8 * u_blur;
if (mode < 1.0) {
// Burst: broad, blurred rays from a point just past one edge.
float a = 1.5708 + (side - 0.5) * 2.4;
vec2 src = vec2(cos(a), -abs(sin(a))) * h * vec2(1.0, 1.4) + 0.3 * drift(1.0);
vec2 d = q - src;
float r = length(d);
vec2 dir = d / max(r, 1e-4);
// Rays are noise on the unit circle, low in angle so they stay broad;
// they fade in away from the source so it never reads as a star.
float rays = 0.5 + 0.5 * flowNoise(dir * (1.6 + 1.4 * u_warp), 2.0);
rays = mix(rays, 0.5 + 0.5 * flowNoise(dir * 4.0 + 7.0, 3.0), 0.3);
float ray = mix(1.0, 0.25 + 1.2 * rays * rays, (0.35 + 0.55 * u_warp) * smoothstep(0.05, 0.7, r));
float body = exp(-r / (0.62 * s * soft));
return 1.15 * body * ray + 0.3 * exp(-r / (0.2 * s * soft));
}
if (mode < 2.0) {
// Horizon: a huge disc rising from below, glowing into the dark.
float tilt = (side - 0.5) * 0.5;
vec2 t = rot2(tilt) * q;
float radius = 1.7 * s;
float lift = (0.12 + 0.18 * u_scale) * h.y + 0.1 * flowNoise(vec2(0.4, 0.9), 1.0);
vec2 centre = vec2(0.45 * drift(2.0).x, -h.y - radius + lift);
float x = length(t - centre) - radius;
// The edge undulates, and with warp it drips into vertical streaks.
x += 0.035 * u_warp * flowNoise(vec2(t.x * 2.2, 0.3), 3.0);
x += 0.06 * u_warp * u_warp * flowNoise(vec2(t.x * 9.0, t.y * 0.6), 4.0) * (1.0 - smoothstep(-0.05, 0.25, x));
float above = exp(-max(x, 0.0) / (0.14 * soft));
float below = mix(1.0, 0.72, (1.0 - smoothstep(-0.6, 0.0, x)));
return x > 0.0 ? 0.92 * above : 0.92 + 0.3 * below * (1.0 - smoothstep(-0.08, 0.0, x));
}
if (mode < 3.0) {
// Beam: a long diagonal band, a thin hot core in a wide soft halo.
float a = 0.45 + (side - 0.5) * 1.1;
vec2 dir = vec2(cos(a), sin(a));
vec2 n = vec2(-dir.y, dir.x);
float u = dot(q, dir);
float v = dot(q, n) + 0.08 * h.y + 0.14 * u_loop.y + 0.07 * u_warp * flowNoise(vec2(u * 0.9, 0.5), 2.0) - 0.12 * u * u;
float w = 0.05 * s * soft;
float core = exp(-v * v / (w * w));
float halo = exp(-abs(v) / (4.0 * w));
float along = smoothstep(-1.4 * h.x, 0.3 * h.x, u) * (0.85 + 0.15 * flowNoise(vec2(u * 1.2, 1.7), 3.0));
return (0.75 * core + 0.6 * halo) * along;
}
// Bloom: light leaning in from a lower corner, with a hard-ish shoulder
// where it meets the dark, bent by the flow.
vec2 corner = vec2(side < 0.5 ? -1.0 : 1.0, -1.0) * h;
vec2 c = corner * 0.92 + 0.3 * drift(3.0);
vec2 w = q + 0.1 * u_warp * vec2(flowNoise(q * 1.1, 4.0), flowNoise(q * 1.1 + 3.3, 5.0));
vec2 d = rot2((side - 0.5) * 1.4) * (w - c);
float r = length(d * vec2(0.75, 1.0));
// The light spills out of the lobe in a long, uneven tail.
float tail = exp(-r / (0.55 * s * soft)) * (0.7 + 0.3 * flowNoise(d * 1.6 + 2.0, 7.0));
float edge = 1.0 - smoothstep((1.0 - 0.6 * soft) * s, s, r);
return 0.95 * edge * exp(-r / (1.1 * s * soft)) + 0.45 * tail;
}
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
// The built-in dither; the engine's, when on, replaces it.
bool own = u_dither.x < 0.5;
float cell = own ? 3.0 : 1.0;
vec2 px = uv * u_full;
vec2 id = floor(px / cell);
vec2 centre = (id + 0.5) * cell;
vec2 q = (centre - 0.5 * u_full) / min(u_full.x, u_full.y);
q.y = -q.y;
q = interact(q);
float pick8 = floor(fract(u_seed.x * 0.0731 + 0.5) * 8.0);
float mode = mod(pick8, 4.0);
float side = fract(u_seed.y * 0.0917 + 0.5);
float light = dbLight(q, h, mode, side);
float t = clamp(pow(max(light, 0.0), 1.25), 0.0, 1.0);
vec3 lab = labMix(u_bg, ramp(t), smoothstep(0.0, 0.4, t));
// Past the core the light bleaches toward the palette's brightest.
vec3 hot = paletteColor(u_count - 1);
lab = labMix(lab, vec3(min(hot.x + 0.04, 1.0), hot.yz * 0.7), clamp((light - 1.0) * 1.5, 0.0, 1.0));
float lightBg = smoothstep(0.55, 0.85, u_bg.x);
lab.x *= vignette(q, 0.25 * (1.0 - lightBg));
lab = filmGrade(lab);
if (!own) return lab;
// Ordered dither per sRGB channel, one threshold per cell.
float spread = dbSpread();
float threshold = pick8 < 4.0 ? dbBayer8(id) : dbIgn(id);
float steps = 11.0;
vec3 rgb = dbLabToSrgb(lab);
vec3 dithered = floor(rgb * steps + threshold) / steps;
rgb = mix(rgb, dithered, spread);
// The cells read as a display: a faint seam on two edges.
vec2 local = px - id * cell;
if (local.x >= cell - 1.0 || local.y >= cell - 1.0) {
rgb *= 1.0 - 0.1 * spread;
}
return dbSrgbToLab(clamp(rgb, 0.0, 1.0));
}
`,
wgsl: () => import("./wgsl/dither-burst").then((module) => module.wgsl),
label: "Dither burst",
name: "dither-burst",
};
@@ -1,165 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick } from "../kind";
/**
* A gradient map drawn through ordered dither. A slow glowing body is mapped
* onto the ramp background → colour 0 → colour 1 → …, and every pixel picks
* one ramp stop with a 4x4 Bayer threshold, so the field is made of solid
* cells in palette colours only.
*
* Cells form a quadtree around a focus: coarse cells far away, halving twice
* toward it, and smooth colour at its centre. The focus idles on a small loop
* and follows the pointer when one is over the canvas.
*
* Params: `scale` sets the coarse cell, 16px at 1 (4px steps from 8 to 64);
* `warp` bends the body; `blur` widens the smooth core. Scroll has no
* effect. Cells are measured in
* canvas pixels, so mount it with `maxDpr: 1` and `image-rendering: pixelated`
* for cells in CSS pixels.
*
* The kind dithers by itself, so params keep the engine's dither off: its
* cells would resample this field and its levels would shift the palette.
*
* Helpers are prefixed `df` and only depend on the prelude.
*/
export const ditherField: GradientKindDefinition = {
defaults: {
background: "#050505",
blur: 0.4,
colors: ["#2b3dd8", "#ff6a3d", "#ffd9a8"],
dither: { cell: 4, enabled: false, levels: 4 },
grain: 0,
interaction: { pointer: 1, scroll: 0 },
loopSeconds: 20,
scale: 1,
seed: 3,
speed: 0.5,
warp: 0.5,
},
description:
"A gradient map in ordered-dither cells that resolves to smooth colour around the pointer.",
// Stepped rings, the CSS version of the quantised ramp.
fallbackLayers: (colors, background) => {
const ring = (i: number) => pick(colors, i);
return [
`radial-gradient(70% 85% at 72% 55%, ${ring(2)} 0 14%, ${ring(1)} 14% 30%, ${ring(0)} 30% 52%, color-mix(in oklab, ${ring(0)} 45%, ${background}) 52% 66%, transparent 66%)`,
];
},
glsl: `
const float BAYER_DF[16] = float[16](
0.0, 8.0, 2.0, 10.0,
12.0, 4.0, 14.0, 6.0,
3.0, 11.0, 1.0, 9.0,
15.0, 7.0, 13.0, 5.0
);
// Ramp stop i: 0 is the background, then the palette.
vec3 dfStop(int i) {
return i <= 0 ? u_bg : u_colors[min(i - 1, u_count - 1)];
}
// The body's height, 0..1, at q (p units). It sits right of centre, or low
// in portrait frames, and falls to 0 well before the opposite side.
float dfField(vec2 q, vec2 h) {
float portrait = clamp((h.y / h.x - 0.8) / 0.6, 0.0, 1.0);
vec2 centre = mix(vec2(0.52 * h.x, -0.02), vec2(0.04, -0.62 * h.y), portrait);
float reach = mix(0.56, 0.5, portrait);
vec2 w = q + u_warp * 0.2 * vec2(flowNoise(q * 1.1, 1.0), flowNoise(q * 1.1 + 4.1, 2.0));
vec2 d = (w - centre) * vec2(0.9, 1.0);
float body = pow(clamp(1.0 - length(d) / reach, 0.0, 1.0), 0.75);
// A second, smaller lobe circling the first.
vec2 orbit = centre + 0.3 * normalize(drift(3.0) + vec2(1e-4)) * vec2(1.2, 0.7);
float lobe = pow(clamp(1.0 - length(w - orbit) / 0.24, 0.0, 1.0), 1.4);
body = max(body, 0.55 * lobe) + 0.25 * body * lobe;
body += 0.06 * flowNoise(w * 2.4, 4.0) * smoothstep(0.0, 0.2, body);
// Keep clear of the opposite side, where a hero puts its copy.
float side = mix(q.x / h.x, -q.y / h.y, portrait);
body *= smoothstep(mix(-0.18, 0.1, portrait), mix(0.25, 0.42, portrait), side);
return clamp(body, 0.0, 1.0);
}
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
float minSide = min(u_full.x, u_full.y);
vec2 px = floor(uv * u_full);
float coarse = 4.0 * clamp(floor(u_scale * 4.0 + 0.5), 2.0, 16.0);
// The focus: an idle drift, eased toward the pointer while it is near.
vec2 idle = mix(vec2(0.46 * h.x, 0.04), vec2(0.0, -0.6 * h.y), clamp((h.y / h.x - 0.8) / 0.6, 0.0, 1.0)) + 0.12 * drift(1.5);
vec2 ptr = (u_pointer.xy - 0.5) * 2.0 * h;
ptr.y = -ptr.y;
vec2 focus = mix(idle, ptr, clamp(u_pointer.z, 0.0, 1.0));
// Quadtree: a cell splits while its centre is inside the next radius.
float core = 0.07 + 0.08 * u_blur;
float radii[3] = float[3](core * 3.6, core * 2.2, core);
float size = coarse;
vec2 id = floor(px / size);
int tier = 0;
for (int k = 0; k < 3; k++) {
vec2 centre = (id + 0.5) * size;
vec2 cq = (centre - 0.5 * u_full) / minSide;
cq.y = -cq.y;
vec2 dq = abs(cq - focus);
if (max(dq.x, dq.y) >= radii[k]) break;
tier = k + 1;
if (k < 2) {
size *= 0.5;
id = floor(px / size);
}
}
// Viewfinder brackets around the smooth square, in the ramp's last stop,
// shown only while the square sits on the body.
float fine = coarse * 0.25;
vec2 fpx = vec2(focus.x, -focus.y) * minSide + 0.5 * u_full;
float corePx = radii[2] * minSide;
vec2 lo = (ceil((fpx - corePx) / fine - 0.5)) * fine;
vec2 hi = (floor((fpx + corePx) / fine - 0.5) + 1.0) * fine;
float gap = 3.0;
float arm = max(10.0, fine * 3.0);
bool inBox = all(greaterThan(px, lo - gap - 3.0)) && all(lessThan(px, hi + gap + 3.0));
bool inner = all(greaterThan(px, lo - gap - 1.0)) && all(lessThan(px, hi + gap + 1.0));
bool nearCorner = (min(abs(px.x - lo.x), abs(px.x - hi.x)) < arm) && (min(abs(px.y - lo.y), abs(px.y - hi.y)) < arm);
if (hi.x > lo.x && inBox && !inner && nearCorner && dfField(focus, h) > 0.2) {
return dfStop(u_count);
}
float stops = float(u_count);
if (tier == 3) {
// Sampled from the pixel itself: the prelude's pointer lens bends p,
// which would tear the core away from the cells around it.
vec2 sq = (px + 0.5 - 0.5 * u_full) / minSide;
sq.y = -sq.y;
float x = dfField(sq, h) * stops;
int i = int(floor(x));
float f = smoothstep(0.0, 1.0, fract(x));
return labMix(dfStop(i), dfStop(i + 1), f);
}
vec2 cellPx = (id + 0.5) * size;
vec2 q = (cellPx - 0.5 * u_full) / minSide;
q.y = -q.y;
float x = dfField(q, h) * stops;
ivec2 b = ivec2(mod(id, 4.0));
float threshold = (BAYER_DF[b.y * 4 + b.x] + 0.5) / 16.0;
int i = int(floor(x)) + (fract(x) > threshold ? 1 : 0);
// Coarse cells read as a display: a hairline gap between lit cells, and a
// faint unlit pixel at the centre of every empty one.
vec2 local = px - id * size;
if (i == 0) {
vec2 dot_ = abs(local - (size * 0.5 - 1.0));
bool lit = tier == 0 && max(dot_.x, dot_.y) < 1.0;
return lit ? mix(u_bg, dfStop(1), 0.4) : u_bg;
}
if (tier == 0 && (local.x >= size - 1.0 || local.y >= size - 1.0)) {
return mix(dfStop(i), u_bg, 0.35);
}
return dfStop(i);
}
`,
wgsl: () => import("./wgsl/dither-field").then((module) => module.wgsl),
label: "Dither field",
name: "dither-field",
};
@@ -1,132 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { stops } from "../kind";
/**
* Flowing light seen through a wall of vertical flutes. Behind the glass is
* one soft structure: a ribbon of light sweeping across the frame, an arch
* of light rising from below, or a ribbon crossed by a column of light. Each flute shifts the image sideways by
* an amount that grows across its width, so every bright edge breaks into a
* fine sawtooth, and flutes vary in width like hand-drawn glass.
*
* Unlike the Pro reeded glass (lamps seen through mirrored flutes), the
* light here is a single swept form and the refraction is progressive.
*
* The seed picks ribbon, arch or ribbon and column, and where they sit.
* Colours run from the light's outer edge (first) to its hot core (last);
* the column takes the last colour. `scale` sets flute width (about 36
* flutes across the long side at 1), `warp` the refraction, `blur` the
* softness.
*
* Helpers are prefixed `fl` and only depend on the prelude.
*/
export const fluted: GradientKindDefinition = {
defaults: {
background: "#050507",
blur: 0.5,
colors: ["#1d2a8f", "#2f7bff", "#ff7a3d", "#ffe2c4"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.16,
interaction: { pointer: 0.15, scroll: 0.1 },
loopSeconds: 20,
scale: 1,
seed: 5,
speed: 0.5,
warp: 0.5,
},
description:
"A sweep of light behind fluted glass, every edge broken into fine teeth.",
fallbackLayers: (colors) => [
`repeating-linear-gradient(90deg, rgb(255 255 255 / 0.05) 0 1px, transparent 1px 4.5%)`,
`linear-gradient(155deg, transparent 30%, ${stops(colors, 40, 60)}, transparent 72%)`,
],
glsl: `
// The light behind the glass at q: intensity (x) and the column's core (y).
vec2 flLight(vec2 q, vec2 h, float mode, float side) {
float soft = 0.5 + 0.9 * u_blur;
float ribbon = 0.0;
if (mode != 1.0) {
// A ribbon sweeping corner to corner, bending with the flow.
float a = -0.6 + (side - 0.5) * 0.9;
vec2 dir = vec2(cos(a), sin(a));
vec2 n = vec2(-dir.y, dir.x);
float u = dot(q, dir);
float v = dot(q, n) - 0.18 * sin(u * 2.2 + 1.3 * side) * h.y;
v += 0.1 * flowNoise(vec2(u * 0.8, 0.2), 1.0);
// Lit from above: a crisp bright lip, then a long fall into the dark.
float w = 0.13 * soft;
float lip = v > 0.0 ? exp(-v * v / (0.5 * w * w)) : exp(v / (1.4 * w));
float glow = exp(-abs(v) / (5.0 * w));
// A second, fainter fold under the first.
float v2 = v + 0.3 + 0.06 * flowNoise(vec2(u * 0.7, 2.1), 2.0);
float fold = 0.3 * (v2 > 0.0 ? exp(-v2 * v2 / (0.2 * w * w)) : exp(v2 / (2.0 * w)));
ribbon = (0.95 * lip + 0.15 * glow + 0.75 * fold) * (0.8 + 0.2 * flowNoise(vec2(u * 1.5, 3.0), 3.0));
}
float column = 0.0;
float core = 0.0;
if (mode == 1.0) {
// An arch: the top of a big soft disc rising from below, its rim lit
// hardest at the crown and its body falling away into the dark.
vec2 c = vec2((side - 0.5) * 1.1 * h.x, -1.35 * h.y) + vec2(0.06, 0.03) * drift(4.0);
float radius = 1.05 * h.y + 0.3 * h.x * abs(side - 0.5);
vec2 d = (q - c) * vec2(0.8, 1.0);
float r = length(d);
float x = r - radius + 0.03 * flowNoise(d * 1.4, 5.0);
float crown = 0.45 + 0.55 * smoothstep(-0.2, 1.0, d.y / max(r, 1e-3));
float w = 0.08 * soft;
float rim = exp(-x * x / (w * w));
float body = x < 0.0 ? exp(x / (0.3 * soft)) : exp(-x / (0.22 * soft));
column = 0.85 * (0.5 * rim + 0.75 * body) * crown;
} else if (mode == 2.0) {
float x0 = (side - 0.5) * 0.9 * h.x + 0.04 * drift(4.0).x + 0.025 * flowNoise(vec2(0.5, q.y * 1.2), 7.0);
float dx = q.x - x0;
float tall = smoothstep(-1.2 * h.y, 0.3 * h.y, q.y + 0.15 * flowNoise(vec2(0.3, q.y), 5.0));
core = exp(-dx * dx / (0.006 * soft)) * mix(0.6, 1.0, tall);
column = 0.85 * core + 0.35 * exp(-abs(dx) / (0.16 * soft)) * mix(0.55, 1.0, tall);
}
return vec2(ribbon + column, core);
}
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
float minSide = min(u_full.x, u_full.y);
float mode = floor(fract(u_seed.x * 0.0731 + 0.5) * 3.0);
float side = fract(u_seed.y * 0.0917 + 0.5);
// Flutes: an uneven but monotonic stretch of x, so widths vary.
float w = (2.0 * h.x) / (36.0 * u_scale);
float x = p.x / w;
float xf = x + 0.32 * sin(x * 0.61 + 1.7) + 0.18 * sin(x * 1.37 + 0.4);
float u = fract(xf);
float idx = floor(xf);
// Progressive refraction: the image slides across each flute.
float shift = (0.3 + 1.6 * u_warp) * w;
vec2 q = p;
q.x += (u - 0.5) * shift;
// Each flute leans the image a touch, so diagonal edges turn into teeth.
q.y += (u - 0.5) * shift * 0.35 * sin(idx * 2.3);
vec2 light = flLight(q, h, mode, side);
float t = clamp(pow(light.x, 1.15), 0.0, 1.0);
vec3 col = ramp(t);
col = labMix(col, paletteColor(u_count - 1), light.y * 0.85);
vec3 lab = labMix(u_bg, col, smoothstep(0.0, 0.45, t));
// Glass: the curve catches a thin highlight near one side of each flute
// and darkens toward the seams.
float seen = clamp(length(lab - u_bg) * 4.0, 0.0, 1.0);
// Hand-made glass: each flute is a touch brighter or darker.
lab.x *= 1.0 + 0.07 * seen * (fract(sin(idx * 12.9898) * 43758.5453) - 0.5);
float curve = sin(u * 3.14159265);
lab.x += (0.05 * exp(-pow((u - 0.28) / 0.07, 2.0)) - 0.04 * (1.0 - curve)) * mix(0.35, 1.0, seen);
float seamPx = min(u, 1.0 - u) * w * minSide;
lab.x -= 0.05 * (1.0 - smoothstep(0.0, 1.2, seamPx)) * seen;
float lightBg = smoothstep(0.55, 0.85, u_bg.x);
lab.x *= vignette(p, 0.3 * (1.0 - lightBg));
return filmGrade(lab);
}
`,
wgsl: () => import("./wgsl/fluted").then((module) => module.wgsl),
label: "Fluted",
name: "fluted",
};
@@ -1,62 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick, stops } from "../kind";
export const grain: GradientKindDefinition = {
defaults: {
background: "#070505",
blur: 0.55,
colors: ["#ffd8b4", "#e0703b", "#8a2c1d", "#2b1015"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.5,
interaction: { pointer: 0.25, scroll: 0.15 },
loopSeconds: 16,
scale: 1,
seed: 7,
speed: 0.6,
warp: 0.55,
},
description: "A grainy beam of light from one corner, brushed into the dark.",
fallbackLayers: (colors) => [
`radial-gradient(60% 45% at 18% 20%, ${pick(colors, 0)} 0%, transparent 60%)`,
`linear-gradient(150deg, ${stops(colors, 0, 70)}, transparent 85%)`,
],
glsl: `
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
// The light sits just outside the frame and throws a beam across it.
float a = seedAngle();
vec2 dir = vec2(cos(a), sin(a));
vec2 across = vec2(-dir.y, dir.x);
vec2 src = -dir * (abs(dir.x) * h.x + abs(dir.y) * h.y + 0.12);
vec2 q = p - src;
float u = dot(q, dir);
float v = dot(q, across);
float bend = 0.06 * sin(u * 1.4 + 0.6 * u_loop.x + a)
+ 0.12 * u_warp * flowNoise(vec2(u * 0.7, 1.3) * u_scale, 1.0);
float width = (0.1 + 0.18 * u_blur) * (0.45 + 0.7 * u);
float vb = v - bend;
float beam = exp(-vb * vb / (width * width));
// Brushed streaks: long along the beam, short across it.
float streak = flowNoise(vec2(u * 0.8, vb * 9.0 / (0.45 + u_blur)) * u_scale, 2.0);
// A wider, dimmer sheet behind it for depth.
float vb2 = v + 0.3 - 0.5 * bend;
float beam2 = exp(-vb2 * vb2 / (width * width * 4.0));
float fall = exp(-u * 0.75);
float source = exp(-dot(q, q) * 2.2);
float intensity = (beam * (0.88 + 0.3 * streak) + 0.35 * beam2 * (0.8 + 0.3 * streak)) * fall * 1.5
+ 0.55 * source;
float ti = 1.0 - exp(-1.6 * intensity);
vec3 col = ramp(1.0 - ti);
vec3 lab = labMix(u_bg, col, smoothstep(0.0, 0.75, ti));
lab.x += 0.08 * max(intensity - 1.0, 0.0);
lab.x *= vignette(p, 0.35);
return filmGrade(lab);
}
`,
wgsl: () => import("./wgsl/grain").then((module) => module.wgsl),
label: "Grain",
name: "grain",
};
@@ -1,116 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick } from "../kind";
export const halo: GradientKindDefinition = {
defaults: {
background: "#030306",
blur: 0.4,
colors: ["#fff4ec", "#ffb36b", "#e2457a", "#3d4dff"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.16,
interaction: { pointer: 0.15, scroll: 0.1 },
loopSeconds: 16,
scale: 1,
seed: 3,
speed: 0.6,
warp: 0.55,
},
description:
"A ring of light round a dark core, with a sharp inner rim and colour running round it.",
fallbackLayers: (colors) => [
`radial-gradient(circle at 50% 50%, transparent 24%, color-mix(in oklab, ${pick(colors, 0)} 85%, transparent) 25%, color-mix(in oklab, ${pick(colors, 1)} 60%, transparent) 30%, color-mix(in oklab, ${pick(colors, 2)} 30%, transparent) 37%, transparent 52%)`,
`radial-gradient(circle at 50% 50%, transparent 30%, color-mix(in oklab, ${pick(colors, 3)} 22%, transparent) 40%, transparent 70%)`,
],
glsl: `
// A thick torus of light: the inner edge is crisp, the body holds its
// brightness then rolls off into a wide haze. warp sets how lopsided the
// light is and how far the hue wanders round the ring; blur softens the
// rim and widens the haze.
float haloBody(float x, float soft, float width) {
float edge = smoothstep(-soft, soft, x);
float xo = max(x, 0.0) / width;
float x4 = xo * xo * xo * xo;
return edge / (1.0 + x4 * x4);
}
vec3 kindColor(vec2 p, vec2 uv) {
float lightBg = smoothstep(0.55, 0.85, u_bg.x);
vec2 h = frameHalf();
// The seed picks a framing: centred, rising from the bottom edge, off to
// one side, hanging in a top corner and cropped by the frame, or tilted
// into an ellipse, as if seen at an angle, centred or low like a portal.
float framing = floor(fract(u_seed.x * 0.0731 + 0.5) * 6.0);
float side = sign(u_seed.y + 0.01);
vec2 centre = vec2(0.0, 0.0);
float radius = 0.19;
float tilt = 0.0;
float squash = 1.0;
if (framing == 1.0) {
centre = vec2(0.0, -0.56);
radius = 0.3;
} else if (framing == 2.0) {
centre = vec2(0.34 * h.x * side, -0.02);
radius = 0.2;
} else if (framing == 3.0) {
centre = vec2(-side * (h.x - 0.12), h.y - 0.1);
radius = 0.3;
} else if (framing == 4.0) {
radius = 0.3;
tilt = 0.22 * side;
squash = 0.4;
} else if (framing == 5.0) {
centre = vec2(0.0, -0.3);
radius = 0.44;
tilt = 0.08 * side;
squash = 0.28;
}
radius *= u_scale;
// The hot side sways slowly round the ring.
float swing = seedAngle() + 2.4 * u_loop.x;
vec2 hotDir = vec2(sin(swing), cos(swing));
vec2 d = rot2(tilt) * (p - centre);
d.y /= squash;
float r = length(d);
vec2 dir = d / max(r, 1e-4);
float x = r / radius - 1.0;
float soft = 0.01 + 0.06 * u_blur;
float width = 0.42 + 0.2 * u_blur;
float hot = 0.5 + 0.5 * dot(dir, hotDir);
float key = mix(1.0, 0.22 + 0.78 * hot * hot, 0.3 + 0.6 * u_warp);
// Noise sampled on the unit circle (so it has no seam) drifts the hue
// and, a little, the thickness round the ring.
float around = flowNoise(dir * 0.8 + vec2(3.1, 0.0), 2.0);
float body = haloBody(x, soft, width * (1.0 + 0.07 * u_warp * flowNoise(dir * 0.7, 1.0)));
// A ghost exposure, nudged toward the hot side: a doubled, glassy rim.
vec2 dg = d - hotDir * radius * 0.08;
float xg = length(dg) / radius - 1.06;
float ghost = smoothstep(-soft, soft, xg) * exp(-max(xg, 0.0) / (0.05 + 0.08 * u_blur));
float haze = exp(-max(x, 0.0) / (0.6 + 0.8 * u_blur)) * smoothstep(0.0, width, x);
// Faint tinted fog inside the core, so the dark has depth.
float fog = (1.0 - smoothstep(-soft, soft, x)) * exp(x / 0.25);
float glow = 0.95 * body * key + 0.3 * ghost * (0.3 + 0.7 * hot) + 0.12 * haze * (0.4 + 0.6 * key) + 0.12 * fog * (0.3 + 0.7 * hot);
// Colour: the inner rim runs hot (colour 0), the body moves through the
// palette outward, and the hue drifts round the ring.
float depth = clamp(max(x, 0.0) / (width * 1.6), 0.0, 1.0);
float t = clamp(0.12 + 0.45 * depth + 0.5 * u_warp * (0.5 + 0.5 * around) + 0.35 * (1.0 - hot), 0.0, 1.0);
vec3 col = ramp(t);
float rimLine = smoothstep(-soft, soft, x) * exp(-max(x, 0.0) / (0.06 + 0.1 * u_blur));
col = labMix(col, paletteColor(0), rimLine * hot * 0.8);
col = labMix(col, paletteColor(u_count - 1), fog * 0.6);
vec3 lab = labMix(u_bg, col, clamp(glow, 0.0, 1.0));
lab.x += 0.08 * max(glow - 0.85, 0.0) * (1.0 - lightBg);
return filmGrade(lab);
}
`,
wgsl: () => import("./wgsl/halo").then((module) => module.wgsl),
label: "Halo",
name: "halo",
};
@@ -1,292 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick } from "../kind";
/**
* A black-hole horizon: a void with a curved lower edge, faint ripple rings
* just inside it, and layered, lensed light streaks converging on a vanishing
* point below the frame, finished with star flares and a vignette.
*
* Palette roles: 0 core streak, 1 secondary streak, 2 rim (cool edge),
* 3 deep shadow, 4 highlight. Shorter palettes reuse the last colour.
*
* Horizon is a scene kind: its colours drive the palette, but the scene adds
* its own lighting (void, haze, rings, highlights, vignette), so a flat
* palette does not render as that flat colour. It is exempt from the ΔE 0.02
* flat-colour fidelity check the other kinds meet.
*
* Helpers are prefixed `hz` and self-contained so the kind only depends on
* the prelude's uniforms.
*/
export const horizon: GradientKindDefinition = {
defaults: {
background: "#000000",
blur: 0.35,
colors: ["#b4553a", "#c98f8a", "#6f8fb0", "#3a1f33", "#dfe8ff"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.12,
interaction: { pointer: 0.15, scroll: 0.2 },
loopSeconds: 24,
scale: 1,
seed: 7,
speed: 0.6,
warp: 0.5,
},
description:
"An event horizon over a void, with lensed light streaks and star flares.",
// Static horizon for CSS: a curved void edge with a thin cool rim, flat
// streak ellipses in the band, a soft well at the bottom and a plum base.
fallbackLayers: (colors, background) => {
const mix = (i: number, amount: number) =>
`color-mix(in oklab, ${pick(colors, i)} ${amount}%, transparent)`;
return [
`radial-gradient(1000px 79% at 46% 0%, ${background} 95%, transparent 100%)`,
`radial-gradient(1030px 82% at 46% 0%, transparent 93%, ${mix(2, 45)} 96.5%, transparent 100%)`,
`radial-gradient(14% 6% at 47% 98%, ${background} 0%, transparent 100%)`,
`radial-gradient(20% 3% at 40% 90%, ${mix(4, 45)} 0%, transparent 100%)`,
`radial-gradient(42% 8% at 16% 76%, ${mix(0, 75)} 0%, transparent 100%)`,
`radial-gradient(38% 6% at 20% 86%, ${mix(1, 50)} 0%, transparent 100%)`,
`radial-gradient(34% 12% at 86% 66%, ${mix(1, 70)} 0%, transparent 100%)`,
`radial-gradient(30% 7% at 80% 84%, ${mix(0, 65)} 0%, transparent 100%)`,
`linear-gradient(180deg, transparent 55%, ${mix(3, 70)} 100%)`,
];
},
glsl: `
vec3 hzCol(int i) { return u_colors[min(i, u_count - 1)]; }
// Sin-free lattice hash (Dave Hoskins), -1..1.
vec2 hzHash(vec2 p) {
vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.103, 0.0973));
p3 += dot(p3, p3.yzx + 33.33);
return fract((p3.xx + p3.yz) * p3.zy) * 2.0 - 1.0;
}
// 2D gradient noise, roughly -0.7..0.7.
float hzNoise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
float a = dot(hzHash(i), f);
float b = dot(hzHash(i + vec2(1.0, 0.0)), f - vec2(1.0, 0.0));
float c = dot(hzHash(i + vec2(0.0, 1.0)), f - vec2(0.0, 1.0));
float d = dot(hzHash(i + vec2(1.0, 1.0)), f - vec2(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
// Gradient noise with its analytic derivative: (value, d/dx, d/dy).
vec3 hzNoiseD(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
vec2 du = 30.0 * f * f * (f * (f - 2.0) + 1.0);
vec2 ga = hzHash(i);
vec2 gb = hzHash(i + vec2(1.0, 0.0));
vec2 gc = hzHash(i + vec2(0.0, 1.0));
vec2 gd = hzHash(i + vec2(1.0, 1.0));
float va = dot(ga, f);
float vb = dot(gb, f - vec2(1.0, 0.0));
float vc = dot(gc, f - vec2(0.0, 1.0));
float vd = dot(gd, f - vec2(1.0, 1.0));
float k = va - vb - vc + vd;
float v = va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * k;
vec2 d = ga + u.x * (gb - ga) + u.y * (gc - ga) + u.x * u.y * (ga - gb - gc + gd)
+ du * (u.yx * k + vec2(vb, vc) - va);
return vec3(v, d);
}
// The loop point rotated by a per-layer angle: still periodic, out of phase.
vec2 hzLoop(float a) {
float c = cos(a);
float s = sin(a);
return vec2(c * u_loop.x - s * u_loop.y, s * u_loop.x + c * u_loop.y);
}
// Sheet coordinates: stretched, drifting on the loop circle, seeded.
vec2 hzSheet(vec2 sp, vec2 freq, float layer) {
return sp * freq + hzLoop(layer * 2.1) * vec2(0.9, 0.5) + u_seed * 0.37 + layer * 13.7;
}
// Height of the horizon at x, measured against grainient's hero: a wide well
// just right of centre, a gentle shelf on the left and a late climb on the
// right. Portrait frames sit the horizon lower.
float hzRim(float x, float portrait, float breathe) {
float well = exp(-(x - 0.08) * (x - 0.08) * 4.5);
float r = max(x - 0.4, 0.0);
float shelf = -0.145 - 0.035 * (1.0 - smoothstep(-0.6, 0.0, x));
return shelf - (0.19 + breathe) * well * (1.0 - 0.75 * portrait) + 0.65 * r * r - 0.11 * portrait;
}
// The void: black, with a cool haze bleeding up from the horizon and faint
// ripple rings inside it.
vec3 hzVoid(float inside, float sideGlow) {
float haze = (exp(-inside * 30.0) * 0.2 + exp(-inside * 10.0) * 0.06) * sideGlow;
float rings = sin(inside * 210.0 - 0.8 * hzLoop(2.5).y) * exp(-inside * 6.0);
return vec3(haze * (1.0 + 0.22 * rings) + 0.005 * rings, hzCol(2).yz * haze * 0.55);
}
// Star flares: x in half-widths, y in half-heights, size.
const vec3 HZ_STARS[5] = vec3[5](
vec3(-0.29, -0.71, 1.2),
vec3(0.31, -0.88, 1.0),
vec3(0.79, -0.8, 0.7),
vec3(-0.53, -0.55, 0.5),
vec3(0.15, -0.94, 0.45)
);
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
float portrait = clamp((h.y / h.x - 0.65) / 1.2, 0.0, 1.0);
float tilt = (fract(u_seed.x * 0.0193) - 0.5) * 0.1;
float x = p.x - tilt;
float breathe = 0.01 * hzLoop(0.7).x;
float rimY = hzRim(x, portrait, breathe);
float slope = (hzRim(x + 0.01, portrait, breathe) - rimY) * 100.0;
float out_ = (rimY - p.y) / sqrt(1.0 + slope * slope); // > 0 in the light
float sideGlow = 0.55 + 0.7 * smoothstep(0.15, 0.85, abs(p.x) / h.x);
vec2 vq = (uv - 0.5) * vec2(1.0, 1.1);
float vignette = 1.0 - 0.6 * dot(vq, vq);
// Most of the frame is void: skip the light entirely there.
if (out_ < -0.012) {
vec3 lab = hzVoid(-out_, sideGlow);
lab.x *= vignette;
return lab + u_bg;
}
// The well: a dark funnel at the bottom centre.
vec2 vp = vec2(-0.03 + tilt * 0.5, -0.91 * h.y);
vec2 hq = (p - vp) / vec2(0.19, 0.068);
float hd = length(hq);
float landscape = 1.0 - portrait;
// Deeper bands flatten toward the horizontal, like a ground plane.
float rimMin = -0.32 - 0.11 * portrait;
float yRef = mix(rimY, rimMin + (rimY - rimMin) * 0.3, smoothstep(0.0, 0.3, out_));
float depth = max(yRef - p.y, 0.0);
// Perspective: bands crowd toward the horizon and widen toward the viewer.
float across = log(1.0 + depth * 7.0) * 0.32;
float along = p.x;
across += 0.035 * u_warp * sin(along * 3.1 + across * 9.0 + hzLoop(4.0).x * 2.0);
// Near the well the bands dip and dive into it, like light bent by a
// black hole.
float wrap = (1.0 - smoothstep(0.9, 2.6, hd)) * landscape;
across = max(across - 0.09 * wrap * smoothstep(0.0, 0.15, across), 0.0);
along = mix(along, along * (1.0 + 0.8 * wrap), wrap);
float sc = u_scale;
vec2 f0 = vec2(1.0, 6.0) * sc;
vec2 f1 = vec2(1.7, 14.0) * sc;
float s0 = hzNoise(hzSheet(vec2(along, across), f0, 0.0));
vec3 n1 = hzNoiseD(hzSheet(vec2(along + s0 * 0.45, across + s0 * 0.012), f1, 1.0));
float s1 = n1.x;
// Turbulence: slanted wisps that cross the bands and fray them, strongest
// where the streaks climb on the right.
float rise = smoothstep(0.1, 0.75, p.x / h.x);
vec2 q2 = vec2(along, across + along * (0.08 + 0.3 * rise));
float s2 = hzNoise(hzSheet(q2, vec2(2.0, 15.0) * sc, 2.0));
float env = smoothstep(-0.012, 0.05, out_) * (0.75 + 0.25 * exp(-out_ * 3.0));
// The well fades from the surrounding light into black over a wide falloff.
float hole = mix(pow(1.0 - exp(-hd * hd * 0.38), 1.6), 1.0, portrait);
float nearWell = (1.0 - smoothstep(1.0, 2.6, hd)) * landscape;
// The band is quieter and darker just under the hero copy.
float quiet = exp(-p.x * p.x * 9.0) * (1.0 - smoothstep(0.04, 0.16, out_)) * landscape;
// The hottest light arches over the well and runs down its flanks.
float flank = smoothstep(-0.7, 0.1, hq.y / max(hd, 1e-3));
float ring = exp(-max(hd - 1.7, 0.0) * 1.3) * smoothstep(0.9, 2.0, hd) * flank * landscape;
float side = 0.8 + 0.45 * smoothstep(0.1, 0.8, abs(p.x) / h.x);
// The bottom corners fall away to teal-black.
float corner = (1.0 - smoothstep(-h.y, -0.55 * h.y, p.y)) * smoothstep(0.35, 0.9, abs(p.x) / h.x) * landscape;
side *= 1.0 - 0.55 * corner;
float glow = clamp(0.5 + 0.9 * s0, 0.0, 1.0);
float fray = (0.16 + 0.12 * rise) * (1.0 - 0.8 * portrait);
float v = mix(s1 + 0.4 * s0 + fray * s2 + 0.08 * rise, 0.2 + 0.3 * s0, portrait * 0.85);
// Long-exposure softness: a wide transfer, and the dark gaps between bands
// are lifted so few near-black stripes remain inside the band.
float streak = smoothstep(-0.4 - 0.3 * u_blur, 0.55 + 0.2 * u_blur, v);
streak = mix(0.18, 1.0, streak);
// Near the well the streaks smooth out so its outline stays a clean ellipse.
streak = mix(streak, 0.7, nearWell * 0.25);
// Where a streak brightens going down, its upper edge catches cool light
// and the lower edge stays warm.
float grad = n1.z * f1.y * 0.01;
float coolEdge = smoothstep(0.02, 0.18, grad) * streak;
float warmEdge = smoothstep(0.02, 0.18, -grad) * streak;
// Colour: teal-black gaps, rust and rose bodies, steel-blue upper edges and
// rim, pale blue-white on the brightest edges.
vec3 gap = mix(hzCol(3), vec3(hzCol(2).x * 0.45, hzCol(2).yz * 0.7), 0.55 + 0.35 * s0);
float warmPick = smoothstep(-0.05, 0.5, s1 - 0.5 * s0);
vec3 body = mix(hzCol(0), hzCol(1), warmPick);
body = mix(body, hzCol(0), warmEdge * 0.5);
// Glow, not paint: part of the body falls to desaturated mauve and grey-blue.
vec3 mauve = mix(body, hzCol(2), 0.25 + 0.25 * (1.0 - smoothstep(-0.3, 0.3, s0)));
body = mix(body, vec3(mauve.x, mauve.yz * 0.7), (0.1 + 0.12 * rise) * landscape);
vec3 col = mix(gap, body, smoothstep(0.2, 0.75, streak));
// Portrait frames grade softly from steel at the edge through rose to rust.
vec3 tall = mix(hzCol(2), mix(hzCol(1), hzCol(0), 0.6 * smoothstep(0.15, 0.55, out_)), smoothstep(0.03, 0.22, out_));
col = mix(col, tall, portrait * 0.7);
float rimness = exp(-max(out_, 0.0) * mix(24.0, 5.0, portrait));
col = mix(col, hzCol(2), clamp(coolEdge * 0.6 + rimness * 0.9 + ring * 0.5, 0.0, 1.0));
col = mix(col, gap, 0.65 * corner);
col = mix(col, hzCol(4), clamp(coolEdge * coolEdge * 0.7 + ring * streak * 0.6 + rimness * glow * 0.25, 0.0, 1.0));
// A broad bloom where the coarse sheet peaks.
float bloom = smoothstep(0.2, 0.75, s0) * exp(-out_ * 2.5);
float energy = env * hole * side * (1.0 - 0.45 * quiet) * (0.12 + 0.1 * rise + glow * glow * 0.3 + streak * 0.8 + coolEdge * 0.45 + bloom * 0.35)
+ env * ring * (0.45 + 1.35 * streak)
+ exp(-abs(out_ - 0.018) * 30.0) * (0.25 + 0.6 * glow) * env;
energy = mix(energy, env * (0.75 + 0.35 * glow) * (1.0 - 0.5 * smoothstep(0.25, 0.8, out_)), portrait * 0.6);
// Filmic tone: soft shoulder on lightness, chroma follows the light and
// rolls off in the highlights.
float lum = 1.0 - exp(-energy * 1.7);
float L = col.x * lum * 1.22;
// Darks desaturate toward black, like a film toe.
float chroma = smoothstep(0.0, 0.45, lum) * mix(0.5, 1.0, smoothstep(0.25, 0.7, lum));
vec3 lab = vec3(L, col.yz * chroma * mix(0.87, 1.0, portrait) * (1.0 - 0.45 * smoothstep(0.7, 1.0, L)));
// Chromatic fringing: a thin cyan line on upper edges, red on lower edges.
float mid = 4.0 * streak * (1.0 - streak);
float fringe = mid * mid * mid * clamp(grad * 6.0, -1.0, 1.0) * lum * landscape;
lab.yz -= fringe * (fringe > 0.0 ? vec2(0.045, 0.034) : vec2(0.03, 0.018));
// The very peaks run to near-white, over tiny areas.
float hot = smoothstep(1.2, 2.3, energy);
lab = mix(lab, vec3(0.965, -0.004, -0.014), hot * 0.85);
// The haze runs continuously across the edge and fades into the band.
lab += hzVoid(max(-out_, 0.0), sideGlow) * exp(-max(out_, 0.0) * 30.0);
// Star flares: a soft glow and core, long hair-fine horizontal flare and a
// shorter vertical one. Pixels outside a star's reach skip it.
for (int i = 0; i < 5; i++) {
vec3 st = HZ_STARS[i];
vec2 sd = p - vec2(st.x * h.x + tilt, st.y * h.y);
float size = st.z;
if (abs(sd.x) > 0.42 * size || abs(sd.y) > 0.22 * size) continue;
float tw = clamp(0.7 + 0.5 * hzLoop(float(i) * 1.9 + 0.4).x, 0.15, 1.2);
float r2 = dot(sd, sd);
float core = exp(-r2 * 45000.0);
float halo = exp(-r2 * 1800.0 / (size * size)) * 0.1 * smoothstep(0.6, 1.2, size);
float fx = exp(-abs(sd.y) * 2200.0) * exp(-abs(sd.x) * 6.0 / size)
* (1.0 - smoothstep(0.25, 0.42, abs(sd.x) / size));
float fy = exp(-abs(sd.x) * 2200.0) * exp(-abs(sd.y) * 12.0 / size)
* (1.0 - smoothstep(0.12, 0.22, abs(sd.y) / size));
float star = (core * 1.4 + halo + (fx + fy) * 0.55) * size * tw * smoothstep(0.0, 0.08, out_);
lab.x += star * 0.7;
vec3 tint = i == 1 || i == 2 ? hzCol(4) : hzCol(1);
lab.yz = mix(lab.yz, tint.yz * 0.6, clamp(star, 0.0, 1.0));
}
lab.x *= vignette;
return lab + u_bg;
}
`,
wgsl: () => import("./wgsl/horizon").then((module) => module.wgsl),
label: "Horizon",
name: "horizon",
};
@@ -1,122 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick } from "../kind";
export const limb: GradientKindDefinition = {
defaults: {
background: "#030308",
blur: 0.35,
colors: ["#e9ecff", "#8a8bff", "#4b2bd6", "#160c3a"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.16,
interaction: { pointer: 0.15, scroll: 0.1 },
loopSeconds: 20,
scale: 1,
seed: 1,
speed: 0.5,
warp: 0.5,
},
description:
"The lit edge of a planet or moon against the dark: a thin bright crest over a soft atmosphere.",
fallbackLayers: (colors) => [
`radial-gradient(120% 120% at 50% 130%, transparent 58%, color-mix(in oklab, ${pick(colors, 3)} 50%, transparent) 61%, color-mix(in oklab, ${pick(colors, 2)} 70%, transparent) 64%, color-mix(in oklab, ${pick(colors, 1)} 75%, transparent) 66%, color-mix(in oklab, ${pick(colors, 0)} 80%, transparent) 67%, transparent 70%)`,
],
glsl: `
// A planet much larger than the frame, or a moon inside it, lit from one
// side. The light is three layers: a thin crest at the edge, a saturated
// band just inside it, and atmosphere glowing just outside. warp sets how
// far the light wraps round; blur softens every layer.
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
// The seed picks the body: a planet whose top arc crosses the frame, a
// horizon tilted across the frame, a moon lit from the side, a planet
// hanging from the top edge, a planet filling one side, a planet crossing
// the frame on a diagonal, or a small moon lit from behind, ringed in light.
float framing = floor(fract(u_seed.x * 0.0731 + 0.5) * 7.0);
float side = sign(u_seed.y + 0.01);
float tilt = sin(seedAngle());
float radius = 0.95;
vec2 centre = vec2(0.0, -1.02 + (1.0 - u_scale) * 0.3);
// Arcs are lit from a little off overhead, so one end of the arc fades.
float lightAngle = 0.5 * tilt;
float backlit = 0.0;
if (framing == 1.0) {
radius = 2.6;
centre = vec2(0.9 * side, -2.62);
lightAngle = side * 0.35 + 0.2 * tilt;
} else if (framing == 2.0) {
radius = 0.3;
centre = vec2(0.18 * h.x * side, 0.0);
lightAngle = side * 1.9 + 0.2 * tilt;
} else if (framing == 3.0) {
radius = 1.1;
centre = vec2(0.2 * side, 1.38);
lightAngle = 3.14159265 + 0.4 * tilt;
} else if (framing == 4.0) {
radius = 1.3;
centre = vec2(-side * (h.x + 0.98), -0.15);
lightAngle = side * (1.45 + 0.2 * tilt);
} else if (framing == 5.0) {
radius = 1.25;
centre = vec2(-side * (h.x + 0.5), -h.y - 0.62);
lightAngle = side * 0.78;
} else if (framing == 6.0) {
radius = 0.2;
centre = vec2(0.0, 0.02);
lightAngle = 0.4 * tilt;
backlit = 1.0;
}
radius *= u_scale;
lightAngle += 0.9 * u_loop.y;
vec2 light = vec2(sin(lightAngle), cos(lightAngle));
vec2 d = p - centre;
float r = length(d);
vec2 dir = d / max(r, 1e-4);
float x = r - radius;
// How squarely each point of the rim faces the light. warp lets the
// light wrap further round the body.
float facing = dot(dir, light);
float lit = smoothstep(-0.15 - 0.6 * u_warp, 0.95, facing);
lit *= lit;
// A body lit from behind glows all the way round.
lit = mix(lit, 0.45 + 0.55 * lit, backlit);
// The atmosphere breathes and drifts along the arc.
float shimmer = 0.7 + 0.3 * flowNoise(dir * 2.4 + vec2(x * 3.0, 0.0), 1.0);
// A small backlit moon shows its whole rim, so keep its outline round.
shimmer = mix(shimmer, 1.0, 0.7 * backlit);
float b = 0.6 + 0.8 * u_blur;
float inside = 1.0 - smoothstep(-0.006 * b, 0.004 * b, x);
// Outside the edge: a pale atmosphere band that holds, then fades.
// The atmosphere breathes with the loop phase: the same depth at any
// speed above 0.5, fading out toward a still frame at speed 0, and never
// thinner than 0.5x, so the falloff below never divides by zero.
float loopR = length(u_loop);
float breath = loopR > 1e-4 ? (u_loop.x / loopR) * min(loopR / 0.3, 1.0) : 0.0;
float atmosW = 0.07 * b * (0.7 + 0.6 * u_warp) * (1.0 + 0.5 * breath);
float xa = max(x, 0.0) / atmosW;
float atmos = smoothstep(-0.02 * b, 0.0, x) / (1.0 + xa * xa * xa * xa);
// The edge itself, in the saturated colour, then the body falling away.
float edgeBand = exp(-pow(x / (0.03 * b), 2.0));
float band = inside * exp(x / (0.09 * b));
float deep = inside * exp(x / (0.35 * b));
float halo = exp(-max(x, 0.0) / (0.18 * b));
float glow = (0.6 * atmos * shimmer + 0.8 * edgeBand + 0.6 * band + 0.25 * deep + 0.12 * halo) * lit;
// The atmosphere in colour 0, the edge in 1, the body through 2 to the last.
vec3 col = labMix(paletteColor(2), paletteColor(u_count - 1), clamp(1.0 - band, 0.0, 1.0));
col = labMix(col, paletteColor(1), clamp(edgeBand * 1.1 + 0.5 * band, 0.0, 1.0));
col = labMix(col, paletteColor(0), clamp(0.8 * atmos * (0.75 + 0.25 * shimmer) * smoothstep(-0.004, 0.025 * b, x), 0.0, 1.0));
vec3 lab = labMix(u_bg, col, clamp(glow, 0.0, 1.0));
return filmGrade(lab);
}
`,
wgsl: () => import("./wgsl/limb").then((module) => module.wgsl),
label: "Limb",
name: "limb",
};
@@ -1,56 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { stops } from "../kind";
export const linearFlow: GradientKindDefinition = {
defaults: {
background: "#06070c",
blur: 0.5,
colors: ["#c13b3b", "#140a0e", "#2c55c5", "#eef2ff"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.08,
interaction: { pointer: 0.15, scroll: 0.15 },
loopSeconds: 18,
scale: 1,
seed: 21,
speed: 0.5,
warp: 0.22,
},
description:
"A directional blend with bowed light lines and a soft light leak.",
fallbackLayers: (colors) => [`linear-gradient(120deg, ${stops(colors)})`],
glsl: `
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
float angle = 0.6 + 1.2 * (fract(u_seed.y * 0.137) - 0.5) + 0.3 * u_loop.y;
vec2 dir = vec2(cos(angle), sin(angle));
vec2 perp = vec2(-dir.y, dir.x);
float extent = abs(dir.x) * h.x + abs(dir.y) * h.y;
float a = dot(p, dir) / extent;
float b = dot(p, perp) / extent;
// Iso-lines bow, as if the light wraps round a curved surface.
float s = a + 0.16 * b * b - 0.05;
s += u_warp * 0.18 * flowNoise(p * 0.6 * u_scale, 1.0);
float t = clamp(0.5 + 0.5 * s * u_scale, 0.0, 1.0);
vec3 lab = ramp(t * t * (3.0 - 2.0 * t));
// Light leak: a soft streak along the iso-lines toward the bright end.
float w = 0.1 + 0.18 * u_blur;
float sd = (s - 0.5 + 0.08 * flowNoise(vec2(b * 1.1, 3.0), 2.0)) / w;
float streak = exp(-sd * sd) * (0.65 + 0.35 * flowNoise(vec2(b * 2.2, 7.0), 3.0));
lab.x += 0.12 * streak;
lab.yz *= 1.0 - 0.3 * streak;
// The dark end falls into shadow and the corners sink toward the base colour.
float dark = 1.0 - smoothstep(0.55, 0.85, u_bg.x);
lab.x *= mix(1.0, mix(0.72, 1.0, smoothstep(-1.2, 0.1, s)), dark);
float corner = smoothstep(0.45, 1.15, length(p / h) * 0.75);
lab = labMix(lab, u_bg, corner * 0.3);
lab.x *= vignette(p, 0.2 * dark);
return filmGrade(lab);
}
`,
wgsl: () => import("./wgsl/linear-flow").then((module) => module.wgsl),
label: "Linear flow",
name: "linear-flow",
};
@@ -1,91 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick } from "../kind";
const BLOBS = [
[16, 20],
[84, 26],
[72, 86],
[22, 80],
[52, 48],
[92, 62],
] as const;
export const mesh: GradientKindDefinition = {
defaults: {
background: "#0a0d24",
blur: 0.45,
colors: ["#ecdcf2", "#8796ee", "#2e45b7", "#0e1645"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.1,
interaction: { pointer: 0.2, scroll: 0.1 },
loopSeconds: 14,
scale: 1,
seed: 42,
speed: 0.6,
warp: 0.4,
},
description: "Soft, lit colour fields drifting through each other.",
fallbackLayers: (colors) =>
colors.map((_, i) => {
const [x, y] = BLOBS[i % BLOBS.length] ?? [50, 50];
return `radial-gradient(85% 95% at ${x}% ${y}%, ${pick(colors, i)} 0%, transparent 68%)`;
}),
glsl: `
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
// The palette marches from a lit corner to the far one: colour 0 sits in
// the light, the last colour in the shadow.
float theta = seedAngle();
vec2 axis = vec2(cos(theta), sin(theta));
vec2 side = vec2(-axis.y, axis.x);
float span = abs(axis.x) * h.x + abs(axis.y) * h.y;
vec2 q = p + u_warp * 0.14 * vec2(
flowNoise(p * 1.2 * u_scale, 1.0),
flowNoise(p * 1.2 * u_scale + 4.1, 2.0)
);
float sigma = (0.22 + 0.2 * u_blur) / u_scale;
float inv = 1.0 / (sigma * sigma);
float count = float(u_count);
float wb = 0.06;
vec3 lab = u_bg * wb;
float chroma = length(u_bg.yz) * wb;
float total = wb;
for (int i = 0; i < 6; i++) {
if (i >= u_count) break;
float fi = float(i);
float k = fi / max(1.0, count - 1.0);
float zig = (mod(fi, 2.0) * 2.0 - 1.0) * (0.25 + 0.5 * fract(fi * 0.618 + 0.3));
vec2 c = axis * span * (0.9 - 1.8 * k) + side * span * 0.5 * zig
+ 0.25 * h * (rot2(fi * 1.7) * u_loop);
vec2 d = q - c;
// Fields are wider across the axis than along it: soft bands of light.
d = vec2(dot(d, axis) * 1.2, dot(d, side) * 0.65);
float w = exp(-dot(d, d) * inv);
lab += u_colors[i] * w;
chroma += length(u_colors[i].yz) * w;
total += w;
}
lab /= total;
chroma /= total;
float current = length(lab.yz);
if (current > 1e-4) {
lab.yz *= mix(1.0, chroma / current, 0.85);
}
lab.x += 0.05 * dot(p, axis) / span;
// One long silk fold across the frame: a lit crest, then the cloth turns
// into shadow behind it.
float along = dot(q, side);
float crest = 0.16 * sin(along * 1.6 + 0.8 * dot(u_loop, vec2(0.6, 0.8)) + theta)
+ 0.08 * flowNoise(vec2(along * 0.6, 2.0), 3.0);
float acrossFold = dot(q, axis) - crest;
float fw = 0.05 + 0.08 * u_blur;
lab.x += 0.06 * exp(-acrossFold * acrossFold / (fw * fw)) - 0.07 * smoothstep(0.0, 0.5, -acrossFold);
lab.x *= vignette(p, 0.18);
return filmGrade(lab);
}
`,
label: "Mesh",
name: "mesh",
wgsl: () => import("./wgsl/mesh").then((module) => module.wgsl),
};
@@ -1,89 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick, stops } from "../kind";
export const mist: GradientKindDefinition = {
defaults: {
background: "#040407",
blur: 0.55,
colors: ["#f4d9ff", "#a77bff", "#3b2a9e", "#120d33"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.14,
interaction: { pointer: 0.2, scroll: 0.15 },
loopSeconds: 18,
scale: 1,
seed: 2,
speed: 0.5,
warp: 0.45,
},
description:
"Out-of-focus folds of light: a curved edge glowing against the dark.",
fallbackLayers: (colors) => [
`radial-gradient(120% 70% at 70% 100%, ${stops(colors, 0, 80)}, transparent 100%)`,
`linear-gradient(160deg, transparent 40%, color-mix(in oklab, ${pick(colors, 1)} 40%, transparent) 70%, transparent 95%)`,
],
glsl: `
// Signed distance-ish to one fold: a broad S-curve across the frame.
// Negative on the lit side.
float mistFold(vec2 q, float layer, float amp) {
float bend = amp * sin(q.x * 1.6 * u_scale + 0.9 * layer + 0.35 * u_loop.y)
+ (0.08 + 0.22 * u_warp) * flowNoise(vec2(q.x * 0.55 * u_scale, layer * 2.3), layer);
return q.y - bend - 0.12 * q.x;
}
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
float lightBg = smoothstep(0.55, 0.85, u_bg.x);
float a = seedAngle();
// Mostly near-horizontal folds; the seed tilts and flips them.
float tilt = 0.55 * sin(a) + (cos(a) < 0.0 ? 3.14159265 : 0.0);
vec2 q = rot2(tilt) * p;
float x = q.x / max(h.x, 1e-3);
// The fold drifts slowly up and down through the loop.
float lift = 0.05 * flowNoise(vec2(0.21, 0.67), 7.0);
float s = mistFold(q + vec2(0.0, lift), 1.0, 0.16);
// Along-fold shading: long, soft streaks like light on satin.
float sheen = flowNoise(vec2(q.x * 0.9 * u_scale, s * 4.0 / (0.5 + u_blur)), 2.0);
// Lit side: the palette runs from the hot lip into its deep colours.
float span = 0.45 + 0.35 * u_blur;
float lit = clamp(-s / span, 0.0, 1.0);
vec3 col = ramp(0.12 + 0.88 * pow(lit, 0.8));
// Light spilling past the fold takes the second colour, not white.
col = labMix(col, paletteColor(1), smoothstep(0.0, 0.2, s) * 0.8);
float soft = 0.02 + 0.09 * u_blur;
float side = 1.0 - smoothstep(-soft, soft, s);
// Light falls off into the far side and fades deep into the lit side.
float spill = exp(-max(s, 0.0) / (0.05 + 0.18 * u_blur));
float depth = exp(-max(-s - 0.1, 0.0) / (0.35 + 0.45 * u_blur));
float amount = max(side * mix(0.3, 1.0, depth), spill * 0.7);
amount *= 0.86 + 0.18 * sheen;
// Depth of field: the fold sharpens near the middle of the frame.
amount *= 1.0 - 0.25 * smoothstep(0.6, 1.2, abs(x));
vec3 lab = labMix(u_bg, col, clamp(amount, 0.0, 1.0));
// The lip: bright on dark grounds, an ink crease on light ones.
float lipW = 0.02 + 0.06 * u_blur;
// The lip sits just inside the lit side, so it reads as light catching the
// fold rather than a line drawn on it.
float sl = s + 0.6 * lipW;
float lip = exp(-sl * sl / (lipW * lipW)) * (0.75 + 0.25 * sheen);
vec3 hot = vec3(min(1.0, paletteColor(0).x + 0.05), paletteColor(0).yz * 0.85);
vec3 ink = vec3(paletteColor(u_count - 1).x * 0.6, paletteColor(u_count - 1).yz);
lab = labMix(lab, mix(hot, ink, lightBg), clamp(lip * (0.22 + 0.05 * lightBg), 0.0, 1.0));
// A second, fainter fold behind, offset so the frame has depth.
float s2 = mistFold(q * vec2(0.8, 1.0) + vec2(0.7, -0.32 + lift), 4.0, 0.22);
float back = (1.0 - smoothstep(-0.25, 0.08 + 0.1 * u_blur, s2)) * exp(-max(-s2, 0.0) / 0.5);
back *= 1.0 - side;
lab = labMix(lab, ramp(0.55), clamp(back * 0.35 * (0.8 + 0.2 * sheen), 0.0, 1.0));
lab.x *= vignette(p, 0.25 * (1.0 - lightBg));
return filmGrade(lab);
}
`,
wgsl: () => import("./wgsl/mist").then((module) => module.wgsl),
label: "Mist",
name: "mist",
};
@@ -1,174 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
/**
* Light seen through a wall of square glass blocks. Behind the glass, one
* soft blob per colour drifts on its own path. Each block takes one clear
* tone from the light behind its centre and refracts the patch around it
* like a small lens, then catches the light on a bevelled edge that faces
* the brightest neighbour, with a pressed inner face and a dark grout seam.
* The brightest cells bloom over the grout. The glass stays put and only
* the light behind it moves.
*
* Params: `scale` sets the block size (about 14 blocks across the short side
* at 1), `warp` the lens strength (0 is flat glass, 1 flips each block's
* image), `blur` the softness of the blobs. The seed lays the blobs out.
* Pale backgrounds read as frosted glass on paper, dark ones as a lit wall
* at night.
*
* Helpers are prefixed `pg` and only depend on the prelude.
*/
export const pixelGlass: GradientKindDefinition = {
defaults: {
background: "#f4f3f1",
blur: 0.55,
colors: ["#7a3cff", "#ff4fb8", "#3d6bff"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.05,
interaction: { pointer: 0.2, scroll: 0 },
loopSeconds: 20,
scale: 1,
seed: 4,
speed: 0.5,
warp: 0.5,
},
description:
"Soft colour drifting behind a wall of square glass blocks, each a small lens.",
// One soft blob per colour, along a loose arc.
fallbackLayers: (colors) =>
colors.map(
(color, i) =>
`radial-gradient(${24 - 3 * i}% ${30 - 3 * i}% at ${34 + 16 * i}% ${50 - 8 * (i % 2)}%, ${color}, transparent 72%)`,
),
glsl: `
// The light behind the glass: one soft, elongated blob per colour.
vec3 pgScene(vec2 q, vec2 h) {
vec3 lab = u_bg;
float lightBg = smoothstep(0.55, 0.85, u_bg.x);
float a0 = seedAngle();
float size = (0.17 + 0.1 * u_blur);
// The cluster leans off centre, toward an edge picked by the seed.
vec2 lean = vec2(cos(a0 + 1.3), sin(a0 + 1.3)) * vec2(0.32, 0.3) * h;
for (int i = 0; i < 6; i++) {
if (i >= u_count) break;
float fi = float(i);
// A loose arc of blobs, big first, each drifting on its own circle.
float a = a0 + fi * 2.1;
vec2 base = vec2(cos(a) * 0.42 * h.x, sin(a) * 0.3 * h.y) * min(fi, 1.0) * (0.8 + 0.25 * fi);
vec2 c = lean + base + vec2(0.55, 0.38) * drift(fi + 1.0);
float r = size * (1.0 - 0.5 * min(fi, 1.0) / (1.0 + 0.4 * fi)) * mix(1.0, 1.15, lightBg);
vec2 d = rot2(a * 0.5 + 0.4 * fi) * (q - c);
d *= vec2(0.62, 1.0);
float k = dot(d, d) / (r * r);
float w = exp(-k * (1.3 - 0.6 * u_blur));
// A brighter, shifted rim, the way colour pools at a blob's edge.
vec3 col = paletteColor(i);
vec3 rim = labMix(col, paletteColor(i + 1), 0.55);
col = labMix(col, rim, smoothstep(0.15, 0.9, k) * 0.7);
lab = labMix(lab, col, clamp(w * 1.15, 0.0, 1.0));
}
return lab;
}
// How far the palette stands from the background. Clear glass over a plain
// ground is invisible, so with nothing to bend the wall disappears and a
// flat palette renders flat.
float pgGlass() {
float most = 0.0;
for (int i = 0; i < 6; i++) {
if (i >= u_count) break;
most = max(most, length(u_colors[i] - u_bg));
}
return clamp(most * 7.0, 0.0, 1.0);
}
// Lightness of the light behind the glass, for a block's shading to face.
float pgLight(vec2 q, vec2 h) {
return pgScene(q, h).x;
}
vec3 kindColor(vec2 p, vec2 uv) {
vec2 h = frameHalf();
float minSide = min(u_full.x, u_full.y);
float lightBg = smoothstep(0.55, 0.85, u_bg.x);
// Whole pixels per block, so the grid is crisp at any size.
float block = max(8.0, floor(minSide * 0.072 / u_scale + 0.5));
vec2 px = uv * u_full;
// Centre the grid on the frame.
vec2 g = px - 0.5 * u_full;
vec2 id = floor(g / block);
vec2 inPx = g - id * block;
vec2 lp = inPx / block - 0.5;
lp.y = -lp.y;
vec2 c = (id + 0.5) * block / minSide;
c.y = -c.y;
vec2 ci = interact(c);
float cell = block / minSide;
// Each block holds one clear tone, the light behind its centre, so the
// wall reads as crisp cells rather than a smudge. Inside, the block is a
// small lens: it shows the patch behind it squeezed (warp 0.5) or flipped
// (warp 1), which keeps every cell's edge distinct from its neighbour's.
vec3 tone = pgScene(ci, h);
float lens = mix(0.6, -0.9, u_warp);
vec3 seenThrough = pgScene(ci + 1.6 * cell * lens * lp, h);
vec3 lab = labMix(tone, seenThrough, 0.55);
// Which way the light brightens across this block: the side facing it
// catches the bevel, the far side falls into shade.
float e = 0.75 * cell;
vec2 grad = vec2(
pgLight(ci + vec2(e, 0.0), h) - pgLight(ci - vec2(e, 0.0), h),
pgLight(ci + vec2(0.0, e), h) - pgLight(ci - vec2(0.0, e), h)
);
float slope = length(grad);
vec2 toLight = normalize(mix(vec2(-0.7071, 0.7071), grad / max(slope, 1e-4), smoothstep(0.002, 0.03, slope)));
// How much light this block passes, against the bare background.
float glow = clamp((tone.x - u_bg.x) * mix(3.0, -3.0, lightBg), 0.0, 1.0);
// Unlit blocks still show as faint glass, so the wall reads edge to edge.
float glass = pgGlass();
float lit = max(glow, mix(0.18, 0.35, lightBg) * glass);
// A convex block: brighter toward the light, falling off to its rim.
float r = max(abs(lp.x), abs(lp.y));
float facing = dot(lp, toLight) / 0.5;
lab.x += lit * (0.05 * facing - 0.07 * smoothstep(0.22, 0.5, r)) * mix(1.0, 0.5, lightBg);
// A broad sheen where the lens focuses the light, toward its source.
vec2 spot = lp - 0.18 * toLight;
lab.x += glow * 0.05 * exp(-dot(spot, spot) * 9.0) * mix(1.0, 0.4, lightBg);
// Bevel: a bright lip on the edges that face the light, shade opposite.
vec2 fromEdge = min(inPx, block - inPx);
float edgePx = min(fromEdge.x, fromEdge.y);
float lipWidth = max(1.5, block * 0.07);
float lip = 1.0 - smoothstep(0.0, lipWidth, edgePx);
vec2 side = abs(lp.x) > abs(lp.y) ? vec2(sign(lp.x), 0.0) : vec2(0.0, sign(lp.y));
float toward = dot(side, toLight);
lab.x += lip * lit * (toward > 0.0 ? 0.11 * toward : 0.06 * toward) * mix(1.0, 0.45, lightBg);
// Glass blocks are pressed with a recessed inner face: a thin ring a
// third of the way in, shaded on the side toward the light.
float ringPx = abs(r - 0.32) * block;
float ring = 1.0 - smoothstep(0.0, max(1.0, block * 0.022), ringPx);
float inner = dot(side, toLight);
lab.x += ring * lit * (0.03 - 0.07 * inner) * mix(1.0, 0.5, lightBg);
// Grout: a dark seam between blocks, a little wider on big blocks.
float grout = max(1.0, block * 0.03);
float seam = 1.0 - smoothstep(grout - 0.5, grout + 0.5, edgePx);
lab = labMix(lab, u_bg * vec3(mix(0.55, 0.9, lightBg), 1.0, 1.0), seam * glass * mix(0.85, 0.5, lightBg));
// Where the light is strongest it blooms past the glass and over the
// grout, so the bright cells glow instead of sitting flat.
vec2 q = interact(vec2(g.x, -g.y) / minSide);
vec3 halo = pgScene(q, h);
float bloom = clamp((halo.x - u_bg.x) * mix(1.0, -1.0, lightBg), 0.0, 1.0);
lab = labMix(lab, halo, 0.32 * bloom * bloom * (1.0 - lightBg));
return filmGrade(lab);
}
`,
label: "Pixel glass",
name: "pixel-glass",
wgsl: () => import("./wgsl/pixel-glass").then((module) => module.wgsl),
};
@@ -1,112 +0,0 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "../kind";
import { pick } from "../kind";
function haze(colors: readonly string[]): string {
const last = Math.max(1, colors.length - 1);
return colors
.map(
(color, i) =>
`color-mix(in oklab, ${color} ${Math.round(45 - (30 * i) / last)}%, transparent) ${(29 + (40 * i) / last).toFixed(1)}%`,
)
.join(", ");
}
export const radialGlow: GradientKindDefinition = {
defaults: {
background: "#020204",
blur: 0.45,
colors: ["#f3f1ff", "#9db4ff", "#5a46cb", "#1d1240"],
dither: { cell: 3, enabled: false, levels: 8 },
grain: 0.14,
interaction: { pointer: 0.2, scroll: 0.1 },
loopSeconds: 14,
scale: 1,
seed: 11,
speed: 0.6,
warp: 0.5,
},
description:
"An eclipse: light spilling round a dark disc, with a corona and god rays.",
fallbackLayers: (colors) => [
`radial-gradient(42% 58% at 50% 82%, transparent 54%, color-mix(in oklab, ${pick(colors, 0)} 80%, transparent) 58%, color-mix(in oklab, ${pick(colors, 1)} 45%, transparent) 64%, transparent 82%)`,
// Haze outside the ring only, so the disc keeps the background colour.
`radial-gradient(84% 116% at 50% 82%, transparent 27%, ${haze(colors)}, transparent 85%)`,
],
glsl: `
vec3 kindColor(vec2 p, vec2 uv) {
// Light-mode backgrounds get a glowing halo instead of a dark disc.
float lightBg = smoothstep(0.55, 0.85, u_bg.x);
// The seed picks a layout: a disc rising from the bottom edge, a full ring
// in the frame, or the rim of a planet low and off to one side.
vec2 h = frameHalf();
float framing = fract(u_seed.x * 0.0731 + 0.5);
float radius = 0.34;
vec2 centre = vec2(0.0, -0.3);
float spread = 0.28;
if (framing > 0.7) {
radius = 0.75;
centre = vec2(0.35 * h.x * sign(u_seed.y), -0.95);
spread = 0.1;
} else if (framing > 0.4) {
radius = 0.26;
centre = vec2(0.0, -0.04);
spread = 0.6;
}
radius /= u_scale;
centre.y -= 0.04 * flowNoise(vec2(0.3, 0.7), 1.0);
vec2 d = p - centre;
float r = length(d);
vec2 dir = d / max(r, 1e-4);
float x = r - radius;
float xo = max(x, 0.0);
float soft = (0.01 + 0.045 * u_blur) * (1.0 + 5.0 * lightBg);
// The source sits behind the disc, so the top of the rim is lit hardest.
// The source drifts round behind the disc, so the hot side wanders.
float sweep = 1.3 * u_loop.x;
vec2 up = vec2(sin(sweep), cos(sweep));
float facing = 0.5 + 0.5 * dot(dir, up) * smoothstep(0.0, radius, r);
float key = mix(spread, 1.0, facing * facing);
// God rays: noise sampled on the unit circle, so they radiate with no seam,
// fine in angle and drifting slowly outward in radius.
float rays = 0.5 + 0.5 * flowNoise(dir * 2.6 - vec2(0.0, r * 0.35), 2.0);
rays = mix(rays, 0.5 + 0.5 * flowNoise(dir * 6.0 - vec2(r * 0.5, 0.0), 3.0), 0.35);
rays = mix(1.0, 0.25 + 1.3 * rays * rays, u_warp);
float rim = exp(-xo / soft);
float corona = exp(-xo / (0.05 + 0.1 * u_blur));
float haze = exp(-xo / (0.3 + 0.3 * u_blur));
// A thin halo ring just outside the rim, in the palette's middle colour.
float ringD = (x - 0.05 - 0.04 * u_blur) / ((0.018 + 0.03 * u_blur) * (1.0 + 2.0 * lightBg));
float ring = exp(-ringD * ringD);
float glow = (rim + 0.5 * corona * (0.6 + 0.4 * rays) + (0.4 + 0.35 * lightBg) * haze * mix(1.0, rays, 0.8) + 0.35 * ring) * key;
// Inside: the occluder, with a hairline of light just inside its edge.
float inside = 1.0 - smoothstep(-soft * 0.5, soft * 0.5, x);
float innerRim = exp(min(x, 0.0) / (0.01 + 0.12 * lightBg));
glow = mix(glow, (0.3 * innerRim + 0.06) * key, inside * (1.0 - 0.85 * lightBg));
// Palette runs outward from the rim; the hottest light bleaches toward white.
// A dark disc hides the rim, so colour can rise sharply there; a light
// glow has no disc edge to hide behind, so it eases in.
float reach = clamp(xo / (0.6 + 0.3 * u_blur), 0.0, 1.0);
float t = mix(sqrt(reach), smoothstep(0.0, 0.7, reach), lightBg);
vec3 col = ramp(t);
vec3 hot = vec3(min(1.0, paletteColor(0).x + 0.06), paletteColor(0).yz * 0.4);
col = labMix(col, hot, rim * (1.0 - inside) * (0.45 + 0.5 * lightBg));
col = labMix(col, paletteColor(2), ring * (0.6 - 0.35 * lightBg) * (1.0 - rim));
vec3 base = u_bg;
base.x *= mix(1.0, mix(0.35, 1.0, lightBg), inside);
vec3 lab = labMix(base, col, clamp(glow, 0.0, 1.0));
lab.x += 0.1 * max(glow - 0.9, 0.0);
lab.x *= vignette(p, 0.3 * (1.0 - lightBg));
return filmGrade(lab);
}
`,
wgsl: () => import("./wgsl/radial-glow").then((module) => module.wgsl),
label: "Radial glow",
name: "radial-glow",
};
Loaded 100 of 1268 files, more files were not shown because too many files have changed in this diff. Show more