Skip to content

Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.

0.6.1: motion grammar, transitions, callouts and shape handoffs, a one-frame pop scan, a harshness measure for sound effects, and the cheetah showcase film

Alex Greenshpunbe78507e2e20
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 88f8195..5304177 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -13,7 +13,7 @@
"name": "anidoodle",
"source": "./",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with scores composed in code.",
- "version": "0.6.0",
+ "version": "0.6.1",
"author": {
"name": "Alex Greenshpun",
"url": "https://linkedin.com/in/alexgreensh"
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 77c9ba8..09f2b2d 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -2,7 +2,7 @@
"name": "anidoodle",
"displayName": "anidoodle",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with scores composed in code.",
- "version": "0.6.0",
+ "version": "0.6.1",
"icon": "./assets/icon.png",
"author": {
"name": "Alex Greenshpun",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 55fd1ca..5a3368d 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "anidoodle",
- "version": "0.6.0",
+ "version": "0.6.1",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with scores composed in code.",
"skills": "./skills/",
"interface": {
diff --git a/.grok-plugin/marketplace.json b/.grok-plugin/marketplace.json
index ebe3c97..8c061fb 100644
--- a/.grok-plugin/marketplace.json
+++ b/.grok-plugin/marketplace.json
@@ -10,7 +10,7 @@
"name": "anidoodle",
"source": "./plugins/anidoodle",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with scores composed in code.",
- "version": "0.6.0",
+ "version": "0.6.1",
"author": {
"name": "Alex Greenshpun",
"url": "https://linkedin.com/in/alexgreensh"
diff --git a/plugins/anidoodle/.claude-plugin/plugin.json b/plugins/anidoodle/.claude-plugin/plugin.json
index 77c9ba8..09f2b2d 100644
--- a/plugins/anidoodle/.claude-plugin/plugin.json
+++ b/plugins/anidoodle/.claude-plugin/plugin.json
@@ -2,7 +2,7 @@
"name": "anidoodle",
"displayName": "anidoodle",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with scores composed in code.",
- "version": "0.6.0",
+ "version": "0.6.1",
"icon": "./assets/icon.png",
"author": {
"name": "Alex Greenshpun",
diff --git a/plugins/anidoodle/.codex-plugin/plugin.json b/plugins/anidoodle/.codex-plugin/plugin.json
index 55fd1ca..5a3368d 100644
--- a/plugins/anidoodle/.codex-plugin/plugin.json
+++ b/plugins/anidoodle/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "anidoodle",
- "version": "0.6.0",
+ "version": "0.6.1",
"description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 31 styles, with scores composed in code.",
"skills": "./skills/",
"interface": {
diff --git a/plugins/anidoodle/skills/anidoodle/SKILL.md b/plugins/anidoodle/skills/anidoodle/SKILL.md
index bfac277..257361b 100644
--- a/plugins/anidoodle/skills/anidoodle/SKILL.md
+++ b/plugins/anidoodle/skills/anidoodle/SKILL.md
@@ -102,8 +102,8 @@ draws itself declares `kind: "drawing"` and is judged on a finer floor; a freeze
`engine/` is the portable art core plus the tooling. `engine/src/canvas-core` knows nothing
about the DOM or any backend. `W`, `H`, `fps` and `durationFrames` come from the film's `meta`.
-Camera moves (pans, zooms, parallax, shake) come from `engine/src/canvas-core/camera.ts`:
-`references/camera.md`. `render.mjs --blur auto` renders with motion blur (subframes per frame
+Camera moves (pans, zooms, parallax, shake): `engine/src/canvas-core/camera.ts`, `references/camera.md`.
+Seams between scenes: `references/motion-grammar.md`. `render.mjs --blur auto` renders with motion blur (subframes per frame
from its measured on-screen speed, averaged in linear light, `--shutter 180`); the default path is untouched.
```bash
diff --git a/plugins/anidoodle/skills/anidoodle/engine/package.json b/plugins/anidoodle/skills/anidoodle/engine/package.json
index 8a5aa81..83bb2d9 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/package.json
+++ b/plugins/anidoodle/skills/anidoodle/engine/package.json
@@ -1,6 +1,6 @@
{
"name": "anidoodle-engine",
- "version": "0.6.0",
+ "version": "0.6.1",
"private": true,
"type": "module",
"description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/callout.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/callout.ts
new file mode 100644
index 0000000..15f5ef0
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/callout.ts
@@ -0,0 +1,113 @@
+// CALLOUT. A label that names one thing in the picture, and can carry the viewer into the next
+// scene: a dot lands on the thing, a leader line is drawn out from it, the label is written at the
+// end of the line. The thing may move (the anchor is asked for every frame, so pin it to the world
+// with camera.ts: `anchor: (f) => cam.toScreen(worldPoint, f, z)`); the label stays put so it can
+// be read. Screen coordinates in logical px, any frame size. Pure functions of their arguments.
+//
+// It is type over the picture, so that judgement applies (references/workflows/launch-video.md,
+// Type): the label sits on a calm area, names the thing it points at, and one or two are on screen
+// at a time. Where the picture under it is not calm, give it a `backing`, or do not use a callout.
+//
+// const c: Callout = { text: "LIVE PREVIEW", anchor: (f) => cam.toScreen([820, 410], f), label: { p: [1180, 300], size: 44 }, t0: 60, out: 150 };
+// drawCallout(ctx, env, c, f);
+//
+// THE HANDOFF. Instead of leaving, the label can travel to where the next scene starts and become
+// its heading: `handoff: { leave, at, pose }`. From `leave` the dot and line retract while the
+// label moves and resizes; on frame `at`, the next scene's first frame, it sits exactly on `pose`,
+// and from there the next scene draws it itself with drawLabel at that pose. checkHandoff holds the
+// two sides to within 2 px, the motif's rule (motif.ts), and throws if the seam jumps.
+import type { Ctx, Env, P } from "./core";
+import { clamp, inOut, lerp, out3, ramp, rr } from "./launchKit";
+import { measure, setType, setWidth, writeOn, type KStyle } from "./kinetic";
+import { checkRelay } from "./motif";
+
+/** Where a label sits: `p` is the left end of its baseline, `size` its cap height (drawn) or font px (clean). */
+export type LabelPose = { p: P; size: number };
+export type Callout = {
+ text: string;
+ anchor: (f: number) => P; // the thing named, on screen, at frame f
+ label: LabelPose;
+ t0: number; // the frame the dot lands; the line and the label follow
+ out?: number; // the frame it starts to leave (the label is taken back, the line retracts); omit to stay
+ handoff?: { leave: number; at: number; pose: LabelPose; arc?: number }; // see THE HANDOFF; `arc` lifts the path (px, up)
+ register?: "drawn" | "clean"; // drawn: written in ink with a hand's curved line. clean: set type, an elbow line, an underline
+ style?: KStyle; color?: string; accent?: string;
+ backing?: string; // a chip of this colour behind the label, for a picture that is not calm there
+ dot?: number; // the dot's radius (default 0.16 x size)
+};
+// frames after t0: the dot lands, the line is drawn, the label is written; and how long leaving takes
+export const CALLOUT_T = { dot: [0, 7], line: [4, 17], text: [11, 30], leave: 12 } as const;
+/** The frame a callout is fully on screen and readable. */
+export const calloutReady = (c: Callout) => c.t0 + CALLOUT_T.text[1];
+
+const widthOf = (ctx: Ctx, c: Pick<Callout, "text" | "register">, size: number) => (c.register === "clean" ? setWidth(ctx, c.text, size) : measure(c.text, size, { weight: 1.15 }));
+/** The label's pose at frame f (pure): its own until a handoff leaves, then on the way, then the destination on `at`. Null before t0. */
+export const calloutPose = (c: Callout, f: number): LabelPose | null => {
+ if (f < c.t0) return null;
+ const h = c.handoff; if (!h || f <= h.leave) return c.label;
+ const u = ramp(f, h.leave, h.at), e = inOut(u), a = c.label, b = h.pose;
+ return { p: [lerp(a.p[0], b.p[0], e), lerp(a.p[1], b.p[1], e) - Math.sin(Math.PI * u) * (h.arc ?? 0)], size: a.size > 0 && b.size > 0 ? a.size * Math.pow(b.size / a.size, e) : lerp(a.size, b.size, e) }; // size eased as a ratio
+};
+/** The label alone, at a pose: what the next scene calls from the handoff frame on, so both sides draw the same marks. */
+export const drawLabel = (ctx: Ctx, env: Env, c: Pick<Callout, "text" | "register" | "style" | "color" | "backing">, pose: LabelPose, p = 1, chip = true) => {
+ if (chip && c.backing) { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); const s = pose.size, w = widthOf(ctx, c, s), pad = s * 0.38; ctx.fillStyle = c.backing; rr(ctx, pose.p[0] - pad, pose.p[1] - s * 1.02 - pad * 0.5, w + pad * 2, s * 1.42 + pad, s * 0.22); ctx.fill(); } // the chip travels with the label
+ if (c.register === "clean") setType(ctx, env, c.text, pose.p[0], pose.p[1], pose.size, p, { color: c.color ?? "#111214" });
+ else writeOn(ctx, env, c.text, pose.p[0], pose.p[1], pose.size, p, c.style ?? "ink", { color: c.color ?? "#1b1510", seed: 7, weight: 1.15, pop: 0.7 });
+};
+/** Throws unless the callout's label lands on the next scene's heading within `tol` px (position and size). */
+export const checkHandoff = (c: Callout, into: LabelPose, tol = 2) => {
+ const h = c.handoff; if (!h) throw new Error(`callout "${c.text}": no handoff to check`);
+ if (h.at - h.leave < CALLOUT_T.leave || h.leave < calloutReady(c)) throw new Error(`callout "${c.text}": the handoff leaves at ${h.leave} and lands at ${h.at}; it must leave after the label is readable (frame ${calloutReady(c)}) and take at least ${CALLOUT_T.leave} frames, the time the dot and line need to retract`);
+ const out = calloutPose(c, h.at)!;
+ return checkRelay([{ frame: h.at, label: `callout "${c.text}"`, out: { p: out.p, r: out.size }, into: { p: into.p, r: into.size } }], tol);
+};
+
+// the first `u` of a polyline, by length
+const partial = (pts: P[], u: number): P[] => {
+ const L = pts.slice(1).map((q, i) => Math.hypot(q[0] - pts[i][0], q[1] - pts[i][1])), tot = L.reduce((a, b) => a + b, 0);
+ let left = tot * clamp(u); const out: P[] = [pts[0]];
+ for (let i = 0; i < L.length && left > 0; i++) { const k = Math.min(1, left / (L[i] || 1)); out.push([lerp(pts[i][0], pts[i + 1][0], k), lerp(pts[i][1], pts[i + 1][1], k)]); left -= L[i]; }
+ return out;
+};
+/** The leader line from the thing to the label (pure), in screen px: an elbow and an underline (clean), or one bowed stroke (drawn). */
+export const leaderPath = (anchor: P, pose: LabelPose, width: number, register: "drawn" | "clean" = "drawn", dot = pose.size * 0.16, side?: boolean): P[] => {
+ const [x0, y] = pose.p, s = pose.size, right = side ?? anchor[0] <= x0 + width / 2; // the label is to the right of the thing (`side` pins it)
+ if (register === "clean") {
+ const uy = y + s * 0.34, near: P = [right ? x0 - s * 0.1 : x0 + width + s * 0.1, uy], far: P = [right ? x0 + width + s * 0.1 : x0 - s * 0.1, uy];
+ const d = Math.hypot(near[0] - anchor[0], near[1] - anchor[1]) || 1, a: P = [anchor[0] + ((near[0] - anchor[0]) / d) * dot * 2, anchor[1] + ((near[1] - anchor[1]) / d) * dot * 2];
+ return [a, near, far];
+ }
+ const e: P = [right ? x0 - s * 0.35 : x0 + width + s * 0.35, y - s * 0.42], d = Math.hypot(e[0] - anchor[0], e[1] - anchor[1]) || 1;
+ const a: P = [anchor[0] + ((e[0] - anchor[0]) / d) * dot * 2.2, anchor[1] + ((e[1] - anchor[1]) / d) * dot * 2.2];
+ const bow = Math.min(d * 0.18, s * 1.6) * (right ? 1 : -1), m: P = [(a[0] + e[0]) / 2 + ((e[1] - a[1]) / d) * bow, (a[1] + e[1]) / 2 - ((e[0] - a[0]) / d) * bow];
+ return Array.from({ length: 25 }, (_, i): P => { const t = i / 24; return [(1 - t) ** 2 * a[0] + 2 * (1 - t) * t * m[0] + t * t * e[0], (1 - t) ** 2 * a[1] + 2 * (1 - t) * t * m[1] + t * t * e[1]]; });
+};
+
+export const drawCallout = (ctx: Ctx, env: Env, c: Callout, f: number) => {
+ const h = c.handoff, T = CALLOUT_T;
+ if (f < c.t0 || (h && f >= h.at)) return; // from `at` on, the next scene owns the label
+ const pose = calloutPose(c, f)!, clean = c.register === "clean", accent = c.accent ?? "#d4622b", L = f - c.t0;
+ // leaving: everything is taken back in the reverse of the order it was made; on a handoff only the dot and line go
+ const gone = h ? ramp(f, h.leave, h.leave + T.leave) : c.out === undefined ? 0 : ramp(f, c.out, c.out + T.leave);
+ const pd = ramp(L, T.dot[0], T.dot[1]), pl = out3(ramp(L, T.line[0], T.line[1])) * (1 - inOut(gone)), pt = h ? ramp(L, T.text[0], T.text[1]) : ramp(L, T.text[0], T.text[1]) * (1 - inOut(clamp(gone * 1.4)));
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+ const w = widthOf(ctx, c, pose.size), s = pose.size, A = c.anchor(f), dotR = c.dot ?? c.label.size * 0.16;
+ const right = A[0] <= c.label.p[0] + widthOf(ctx, c, c.label.size) / 2; // which side the line leaves from is the settled label's, so it cannot flip while the label travels
+ ctx.save(); ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.globalAlpha = 1;
+ if (c.backing && pt > 0) { // a chip that grows from the line's side as the label is written
+ const pad = s * 0.38, bw = (w + pad * 2) * out3(pt);
+ ctx.fillStyle = c.backing; rr(ctx, right ? pose.p[0] - pad : pose.p[0] + w + pad - bw, pose.p[1] - s * 1.02 - pad * 0.5, bw, s * 1.42 + pad, s * 0.22); ctx.fill();
+ }
+ if (pl > 0) {
+ const pts = partial(leaderPath(A, pose, w, clean ? "clean" : "drawn", dotR, right), pl);
+ ctx.strokeStyle = accent; ctx.lineWidth = clean ? Math.max(2, s * 0.05) : s * 0.06;
+ ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.stroke();
+ }
+ const r = dotR * (out3(pd) + 0.3 * Math.sin(Math.PI * pd) * (1 - pd)) * (1 - inOut(gone)); // lands with a small overshoot
+ if (r > 0.2) {
+ if (clean) { ctx.strokeStyle = accent; ctx.lineWidth = Math.max(2, s * 0.05); ctx.beginPath(); ctx.arc(A[0], A[1], r * 1.5, 0, Math.PI * 2); ctx.stroke(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(A[0], A[1], r * 0.55, 0, Math.PI * 2); ctx.fill(); }
+ else { ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(A[0], A[1], r, 0, Math.PI * 2); ctx.fill(); }
+ }
+ ctx.restore();
+ if (pt > 0) drawLabel(ctx, env, c, pose, pt, false);
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/calloutDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/calloutDemo.ts
new file mode 100644
index 0000000..5a12887
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/calloutDemo.ts
@@ -0,0 +1,49 @@
+// CALLOUT DEMO. One callout pinned to a thing while the camera moves, its handoff into the next
+// scene, and a second callout there that leaves the plain way (120 bpm: a beat is 15 frames).
+// 0-135 the fox plate, the camera easing in toward the moon. At 20 a dot lands on the moon,
+// the line is drawn out, "THE MOON" is written in the calm of the sky; the dot follows
+// the moon as the camera moves, the label holds still.
+// 105-135 THE HANDOFF: the dot and line retract, the label travels up and left and grows; an
+// iris opens the next scene from the moon underneath it.
+// 135-285 the label is the page's heading, on the frame it lands. The phases rise in below it;
+// a second callout names the full moon from the calm ground under the card, then leaves.
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import { Camera } from "./camera";
+import { out3, plateLayer, ramp, rr } from "./launchKit";
+import { calloutPose, checkHandoff, drawCallout, drawLabel, type Callout, type LabelPose } from "./callout";
+import { iris, seam } from "./transitions";
+import { fox } from "./fox";
+import { moonPhases } from "./moonPhases";
+
+const W = 1080, H = 1080, N = 285, AT = 135, CREAM = "#f1e7cf", GOLD = "#e9a23b", BOARD = "#1d2b28";
+const MOON: P = [214, 204], HEAD: LabelPose = { p: [84, 196], size: 92 };
+const cam = new Camera([W / 2, H / 2], [{ f: 0, look: [540, 540], zoom: 1 }, { f: AT, look: [452, 440], zoom: 1.28 }]);
+
+const moon: Callout = { text: "THE MOON", anchor: (f) => cam.toScreen(MOON, f), label: { p: [470, 150], size: 46 }, t0: 20, color: CREAM, accent: GOLD, handoff: { leave: 105, at: AT, pose: HEAD, arc: 36 } };
+checkHandoff(moon, HEAD);
+// the phases, cropped from the chalkboard plate: source rows 170-760, set down as a card
+const CARD = { x: 60, y: 300, w: 960, h: 545, sx: 20, sy: 170, sw: 1040, sh: 590 };
+const full: Callout = { text: "FULL, DAY 15", anchor: () => [CARD.x + ((540 - CARD.sx) / CARD.sw) * CARD.w, CARD.y + ((372 - CARD.sy) / CARD.sh) * CARD.h], label: { p: [610, 960], size: 38 }, t0: 178, out: 250, color: CREAM, accent: GOLD };
+
+const scene1 = (env: Env, f: number) => (c: Ctx) => {
+ const L = plateLayer(env, "calloutdemo:fox", fox, 0, Math.round(W * env.scale * 1.3), true).canvas, o = cam.toScreen([0, 0], f), k = cam.at(f).zoom;
+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.globalAlpha = 1; c.drawImage(L, o[0], o[1], W * k, H * k);
+};
+const scene2 = (env: Env, f: number) => (c: Ctx) => {
+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.globalAlpha = 1; c.fillStyle = BOARD; c.fillRect(0, 0, W, H);
+ const L = plateLayer(env, "calloutdemo:moon", moonPhases, 0, Math.round(W * env.scale), true).canvas, q = L.width / W, y = CARD.y + (1 - out3(ramp(f, AT - 14, AT + 10))) * (H - CARD.y + 20);
+ c.save(); rr(c, CARD.x, y, CARD.w, CARD.h, 18); c.clip(); c.drawImage(L, CARD.sx * q, CARD.sy * q, CARD.sw * q, CARD.sh * q, CARD.x, y, CARD.w, CARD.h); c.restore();
+};
+const draw = (ctx: Ctx, f: number, env: Env) => {
+ if (f < AT) { iris(ctx, env, seam(f, 117, AT - 117), scene1(env, f), scene2(env, f), { center: cam.toScreen(MOON, f) }); drawCallout(ctx, env, moon, f); return; }
+ scene2(env, f)(ctx);
+ drawLabel(ctx, env, moon, calloutPose(moon, AT)!); // the heading: the same marks, where the label landed
+ drawCallout(ctx, env, full, f);
+};
+
+export const calloutDemo: Film = {
+ meta: { title: "callout · anchor, leader, label, handoff", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },
+ assets: { images: {} },
+ shots: [{ id: "callout", start: 0, end: N, draw }],
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/cheetahDusk.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/cheetahDusk.ts
new file mode 100644
index 0000000..d3693ae
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/cheetahDusk.ts
@@ -0,0 +1,183 @@
+// CHEETAH, DUSK. A 12 s loop for the motion graphics reel. The picture is timed in frames on a
+// 120 bpm grid; the score is four bars at 80 bpm, the same 12 s, meeting it every 1.5 s.
+// The coat is rings of tapered tufts radiating from the bridge of the nose; the tear lines are the
+// one big black shape; the sun sits low behind the head and the moon is in the pupil.
+// 0-60 night. The crescent moon sets as the sun comes up behind the grass.
+// 60-180 the face makes itself: the head's mass, then the coat ring by ring from the nose
+// outward, the ears, the spots in waves, the tear lines drawn down, the muzzle, whiskers.
+// 150-170 the eyes open; the moon is already in them. One blink at 236.
+// 180-290 alive: the coat breathes in a ripple, an ear flicks, the grass moves, a slow push in.
+// 290-338 the camera goes into the left pupil. The crescent in it is carried, at one size on
+// screen, to where the moon hangs in the sky (the persistent actor across the seam).
+// 322-360 the pupil is the night; the grass comes back up. Frame 359 hands over to frame 0.
+import { rng, type Ctx, type Env, type Layer, type P } from "./core";
+import type { Film } from "./film";
+import { mix } from "./gallery";
+import { cheetahDuskScore } from "./music/pieces/cheetah";
+import { renderLoop } from "./music/render";
+
+const W = 1080, H = 1080, N = 360;
+const NIGHT = "#0d1a22", TEAL = "#2a6a70", RUST = "#b8452a", OCHRE = "#e3a23a", GOLD = "#efb84e", CREAM = "#f2e4c5", PALE = "#fff5de", CORAL = "#f2643c", DARK = "#0a1216", PUPIL = "#070b0e";
+const F: P = [540, 610], EYE_L: P = [388, 512], EYE_R: P = [692, 512], MOON: P = [760, 220], MOON_R = 46;
+const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
+const ramp = (f: number, a: number, b: number) => clamp((f - a) / (b - a));
+const out3 = (t: number) => 1 - Math.pow(1 - clamp(t), 3);
+const inOut = (t: number) => { const c = clamp(t); return c < 0.5 ? 4 * c * c * c : 1 - Math.pow(-2 * c + 2, 3) / 2; };
+const back = (t: number) => { const c = clamp(t) - 1; return 1 + 2.4 * c * c * c + 1.4 * c * c; }; // lands a little past, then settles
+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+
+// a tuft: a tapered leaf from radius r0 to r1 along angle a, darker at its root
+const tuft = (c: Ctx, o: P, a: number, r0: number, r1: number, w: number, col: string, vein = 0.22) => {
+ if (r1 - r0 < 1.5 || w < 0.6) return;
+ const ca = Math.cos(a), sa = Math.sin(a), b: P = [o[0] + ca * r0, o[1] + sa * r0], t: P = [o[0] + ca * r1, o[1] + sa * r1], m = r0 + (r1 - r0) * 0.42, mx = o[0] + ca * m, my = o[1] + sa * m;
+ const g = c.createLinearGradient(b[0], b[1], t[0], t[1]); g.addColorStop(0, mix(col, DARK, 0.6)); g.addColorStop(0.45, col); g.addColorStop(1, mix(col, "#ffffff", 0.16));
+ c.fillStyle = g; c.beginPath(); c.moveTo(b[0], b[1]); c.quadraticCurveTo(mx - sa * w, my + ca * w, t[0], t[1]); c.quadraticCurveTo(mx + sa * w, my - ca * w, b[0], b[1]); c.fill();
+ if (vein > 0) { c.strokeStyle = mix(col, DARK, 0.7); c.globalAlpha = vein; c.lineWidth = 1; c.beginPath(); c.moveTo(b[0], b[1]); c.lineTo(o[0] + ca * (r1 - 6), o[1] + sa * (r1 - 6)); c.stroke(); c.globalAlpha = 1; }
+};
+const crescent = (c: Ctx, x: number, y: number, R: number, col: string) => { // a true crescent, so it needs no ground colour behind it
+ const ix = x + R * 0.5, iy = y - R * 0.24, ir = R * 0.9, out: P[] = [], inn: P[] = [];
+ for (let i = 0; i < 90; i++) { const a = (i / 90) * Math.PI * 2 + 0.3, p: P = [x + Math.cos(a) * R, y + Math.sin(a) * R]; if (Math.hypot(p[0] - ix, p[1] - iy) >= ir) out.push(p); }
+ for (let i = 0; i < 90; i++) { const a = (i / 90) * Math.PI * 2 + 0.3, p: P = [ix + Math.cos(a) * ir, iy + Math.sin(a) * ir]; if (Math.hypot(p[0] - x, p[1] - y) <= R) inn.push(p); }
+ // both runs are contiguous once rotated to start at a gap
+ const rot = (q: P[], far: (p: P) => number) => { let k = 0, best = -1; for (let i = 0; i < q.length; i++) { const d = Math.hypot(q[i][0] - q[(i + 1) % q.length][0], q[i][1] - q[(i + 1) % q.length][1]); if (d > best) { best = d; k = i + 1; } } void far; return [...q.slice(k), ...q.slice(0, k)]; };
+ const A = rot(out, () => 0), B = rot(inn, () => 0).reverse();
+ c.fillStyle = col; c.beginPath(); [...A, ...B].forEach((p, i) => (i ? c.lineTo(p[0], p[1]) : c.moveTo(p[0], p[1]))); c.closePath(); c.fill();
+};
+
+// ---------------------------------------------------------------- the parts, laid out once
+const COAT = [
+ { r0: 318, r1: 432, n: 92, w: 20, col: "#a9601f" }, { r0: 268, r1: 368, n: 84, w: 20, col: "#cf8a2c" }, { r0: 216, r1: 310, n: 74, w: 19, col: OCHRE },
+ { r0: 164, r1: 254, n: 62, w: 18, col: GOLD }, { r0: 112, r1: 198, n: 50, w: 17, col: "#f2c263" }, { r0: 62, r1: 142, n: 38, w: 15, col: "#f4cd7e" },
+];
+type T = { a: number; r0: number; r1: number; w: number; col: string; t0: number; ring: number };
+const PARTS = (() => {
+ const r = rng(11);
+ const neck = Array.from({ length: 6 * 14 }, (_, i) => { const row = 5 - Math.floor(i / 14), k = (i % 14) - 1; return { x: k * 94 + (row % 2) * 47 + 10, y: 820 + row * 56, col: mix(["#a9601f", "#cf8a2c", "#8f4f1c"][row % 3], DARK, 0.2 + row * 0.07 + r() * 0.1), t0: 52 + row * 5 + r() * 6 }; });
+ const coat: T[] = [];
+ COAT.forEach((k, i) => { for (let j = 0; j < k.n; j++) { const a = ((j + (i % 2) * 0.5) / k.n) * Math.PI * 2, down = clamp((Math.sin(a) - 0.25) * 1.7) * clamp((i - 1) / 3), len = 1 + (r() - 0.5) * 0.12; coat.push({ a, r0: k.r0, r1: k.r0 + (k.r1 - k.r0) * len, w: k.w, col: mix(mix(k.col, CREAM, down), DARK, r() * 0.1), t0: 72 + (5 - i) * 9 + (((a + Math.PI / 2) / (Math.PI * 2) + 1) % 1) * 12, ring: i }); } });
+ const sr = rng(5), spots: { x: number; y: number; s: number; a: number; t0: number }[] = [];
+ for (let ring = 0; ring < 9; ring++) { const rad = 150 + ring * 29, n = Math.round((rad * 2 * Math.PI) / 40);
+ for (let j = 0; j < n; j++) { const a = ((j + (ring % 2) * 0.5 + (sr() - 0.5) * 0.3) / n) * Math.PI * 2, x = F[0] + Math.cos(a) * rad, y = F[1] + Math.sin(a) * rad * 0.95, s = 4.2 + ring * 0.55 + sr() * 1.8, jit = sr();
+ if (Math.sin(a) > 0.2 && rad < 330) continue; if (Math.hypot(x - EYE_L[0], y - EYE_L[1]) < 132 || Math.hypot(x - EYE_R[0], y - EYE_R[1]) < 132) continue; if (Math.abs(x - 540) < 46 && y > 430) continue;
+ spots.push({ x, y, s, a, t0: 128 + ring * 4 + jit * 8 }); } }
+ const gr = rng(41), grass = Array.from({ length: 70 }, () => ({ x: gr() * W, h: 90 + gr() * 220, a: (gr() - 0.5) * 0.5, w: 9 + gr() * 8, col: gr() < 0.15 ? TEAL : mix(NIGHT, TEAL, gr() * 0.5), ph: gr() * 6.28 }));
+ return { neck, coat, spots, grass };
+})();
+
+const ear = (c: Ctx, o: P, side: number, f: number) => {
+ const g = back(ramp(f, 122, 140)); if (g <= 0) return;
+ const flick = side < 0 ? Math.sin(ramp(f, 206, 222) * Math.PI * 2) * 0.16 * (1 - ramp(f, 206, 222)) : 0;
+ c.save(); c.translate(o[0] + side * 40, o[1] + 70); c.rotate(flick); c.scale(g, g); c.translate(-o[0] - side * 40, -o[1] - 70);
+ c.fillStyle = DARK; c.beginPath(); c.ellipse(o[0], o[1], 84, 92, side * 0.35, 0, Math.PI * 2); c.fill();
+ for (let j = 0; j < 30; j++) tuft(c, [o[0] + side * 12, o[1] + 38], -Math.PI / 2 + side * 0.3 + (j / 29 - 0.5) * 2.3, 8, 78 - Math.abs(j - 14.5) * 1.8, 9, j % 2 ? CREAM : "#e9c98a", 0.15);
+ for (let j = 0; j < 46; j++) tuft(c, o, (j / 46) * Math.PI * 2, 68, 100, 8, j % 3 ? "#a9601f" : OCHRE, 0);
+ c.restore();
+};
+const eye = (c: Ctx, o: P, side: number, f: number, pupilCol: string, moon: boolean) => {
+ const patch = ramp(f, 118, 138);
+ for (let j = 0; j < 34; j++) { const g = back(clamp(patch * 1.6 - (j / 34) * 0.6)); tuft(c, o, (j / 34) * Math.PI * 2, 58, 58 + (54 + (j % 2) * 8) * g, 11 * g, j % 2 ? CREAM : PALE, 0.15); }
+ const blink = 1 - 0.92 * Math.sin(ramp(f, 234, 246) * Math.PI), open = out3(ramp(f, 150, 170)) * blink; if (patch <= 0) return;
+ const lid = (g: number) => { c.beginPath(); c.moveTo(o[0] - side * (86 + g), o[1] + 30 + g * 0.4); c.bezierCurveTo(o[0] - side * 40, o[1] - 62 - g, o[0] + side * 50, o[1] - 70 - g, o[0] + side * (92 + g), o[1] - 22); c.bezierCurveTo(o[0] + side * 46, o[1] + 58 + g, o[0] - side * 30, o[1] + 66 + g, o[0] - side * (86 + g), o[1] + 30 + g * 0.4); c.closePath(); };
+ c.save(); c.translate(o[0], o[1]); c.scale(patch, Math.max(0.07, open) * patch); c.translate(-o[0], -o[1]);
+ c.fillStyle = DARK; lid(15); c.fill();
+ c.save(); lid(0); c.clip();
+ const g = c.createRadialGradient(o[0], o[1], 16, o[0], o[1], 70); g.addColorStop(0, "#ffd24a"); g.addColorStop(0.55, "#f39a1e"); g.addColorStop(1, "#b84a14");
+ c.fillStyle = g; c.fillRect(o[0] - 120, o[1] - 100, 240, 200);
+ const r = rng(90 + side); c.lineCap = "round";
+ for (let i = 0; i < 150; i++) { const a = (i / 150) * Math.PI * 2 + r() * 0.03, a0 = 30 + r() * 8, a1 = 44 + r() * 30, lt = r() < 0.4; c.strokeStyle = lt ? "#ffe9a0" : "#8a2c0c"; c.globalAlpha = 0.18 + r() * 0.3; c.lineWidth = 0.8 + r() * 1.3; c.beginPath(); c.moveTo(o[0] + Math.cos(a) * a0, o[1] + Math.sin(a) * a0); c.lineTo(o[0] + Math.cos(a) * a1, o[1] + Math.sin(a) * a1); c.stroke(); }
+ c.globalAlpha = 1; c.fillStyle = "rgba(40,10,4,0.4)"; c.beginPath(); c.ellipse(o[0], o[1] - 96, 150, 66, 0, 0, Math.PI * 2); c.fill(); // the lid's shadow
+ // the pupil: wide as the eye opens, narrowing in the light, widening again as the camera comes in
+ const pr = 29 * (1.3 - 0.3 * out3(ramp(f, 166, 200)) + 0.35 * inOut(ramp(f, 286, 320)));
+ c.fillStyle = pupilCol; c.beginPath(); c.arc(o[0], o[1] - 2, pr, 0, Math.PI * 2); c.fill();
+ if (moon) crescent(c, o[0] - 10, o[1] - 12, 9.5, PALE);
+ c.fillStyle = "rgba(255,245,222,0.9)"; c.globalAlpha = 1 - ramp(f, 300, 318); c.beginPath(); c.arc(o[0] + 13, o[1] + 11, 2.6, 0, Math.PI * 2); c.fill(); c.globalAlpha = 1;
+ c.restore(); c.restore();
+};
+// the tear line: one black stroke from the inner corner of the eye, round the muzzle, to the mouth
+const tear = (c: Ctx, side: number, prog: number) => {
+ if (prog <= 0) return;
+ const p: P[] = [[540 - side * 76, 548], [540 - side * 70, 640], [540 - side * 128, 720], [540 - side * 110, 836]], bz = (t: number): P => { const u = 1 - t; return [u * u * u * p[0][0] + 3 * u * u * t * p[1][0] + 3 * u * t * t * p[2][0] + t * t * t * p[3][0], u * u * u * p[0][1] + 3 * u * u * t * p[1][1] + 3 * u * t * t * p[2][1] + t * t * t * p[3][1]]; };
+ const L: P[] = [], R: P[] = [], n = 40, m = Math.max(1, Math.round(n * prog));
+ for (let i = 0; i <= m; i++) { const t = i / n, a = bz(t), b = bz(Math.min(1, t + 0.01)), d = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1, nx = -(b[1] - a[1]) / d, ny = (b[0] - a[0]) / d, w = (7 + 15 * Math.sin(Math.PI * Math.pow(t, 0.6)) * (1 - t * 0.35)) * (i === m && prog < 1 ? 0.3 : 1); L.push([a[0] + nx * w, a[1] + ny * w]); R.push([a[0] - nx * w, a[1] - ny * w]); }
+ c.fillStyle = DARK; c.beginPath(); [...L, ...R.reverse()].forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill();
+};
+const grass = (c: Ctx, f: number, grow: number) => { for (const g of PARTS.grass) tuft(c, [g.x, H + 20], -Math.PI / 2 + g.a + Math.sin(f * (Math.PI / 45) + g.ph) * 0.07, 0, g.h * grow, g.w, g.col, 0); };
+
+// the night's stars: they are out while it is night, at the start and again at the end, never still
+const STARS = (() => { const r = rng(19); return Array.from({ length: 46 }, () => ({ x: r() * W, y: r() * 760, s: 1.2 + r() * 2.2, ph: r() * 6.28, cyc: [4, 6, 8, 9, 12][Math.floor(r() * 5)] })); })(); // cyc: whole twinkles per loop, so frame 359 meets frame 0
+const stars = (c: Ctx, f: number, k: number) => { if (k <= 0) return; for (const st of STARS) { c.globalAlpha = k * (0.35 + 0.65 * (0.5 + 0.5 * Math.sin((f / N) * Math.PI * 2 * st.cyc + st.ph))); c.fillStyle = PALE; c.beginPath(); c.arc(st.x, st.y, st.s, 0, Math.PI * 2); c.fill(); } c.globalAlpha = 1; };
+
+// ---------------------------------------------------------------- the camera
+const camAt = (f: number) => {
+ const a = inOut(ramp(f, 180, 290)), b = ramp(f, 290, 338), z = Math.pow(2, lerp(0, Math.log2(1.14), a) + inOut(b) * (Math.log2(52) - Math.log2(1.14))), lk = out3(b * 1.5);
+ return { z, look: [lerp(lerp(540, 506, a), EYE_L[0], lk), lerp(lerp(540, 532, a), EYE_L[1] - 2, lk)] as P };
+};
+
+const grainLayer = (env: Env): Layer => { // the paper's tooth and the dusk settling at the edges: laid once, the same on every frame
+ const key = "cheetah:grain"; let L = env.cache.get(key) as Layer | undefined; if (L) return L;
+ L = env.canvas(Math.round(W * env.scale), Math.round(H * env.scale)); env.cache.set(key, L);
+ const c = L.ctx, q = rng(77); c.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+ for (let i = 0; i < 200000; i++) { const x = q() * W, y = q() * H, d = Math.hypot(x - 540, y - 520) / 740; if (q() > d * d * d * 1.1) continue; c.fillStyle = DARK; c.globalAlpha = 0.42; c.fillRect(x, y, 1.1, 1.1); }
+ for (let i = 0; i < 30000; i++) { const x = q() * W, y = q() * H, lt = q() < 0.5; c.fillStyle = lt ? "#fff5de" : "#000000"; c.globalAlpha = lt ? 0.06 : 0.08; c.fillRect(x, y, 1.1, 1.1); }
+ return L;
+};
+
+const draw = (ctx: Ctx, f: number, env: Env) => {
+ const c = ctx, s = env.scale, cam = camAt(f), pupilCol = mix(PUPIL, NIGHT, ramp(f, 312, 336));
+ c.setTransform(s, 0, 0, s, 0, 0); c.fillStyle = NIGHT; c.fillRect(0, 0, W, H);
+ if (f < 60) stars(c, f, 1 - ramp(f, 14, 52));
+ c.setTransform(s * cam.z, 0, 0, s * cam.z, s * (540 - cam.look[0] * cam.z), s * (540 - cam.look[1] * cam.z));
+ // the moon, setting; the sun, rising behind the grass with its rays opening
+ const set = ramp(f, 4, 52); if (set < 1) crescent(c, MOON[0] - set * set * 160, MOON[1] + set * set * 1000, MOON_R, PALE);
+ const rise = out3(ramp(f, 8, 74)), sy = lerp(1700, 430, rise), rays = back(ramp(f, 40, 86));
+ for (let j = 0; j < 96; j++) tuft(c, [540, sy], (j / 96) * Math.PI * 2 + f * 0.0016, 440, 440 + (80 + (j % 2) * 26) * rays, 12, j % 2 ? RUST : "#8f3a26", 0);
+ const sg = c.createRadialGradient(540, sy, 80, 540, sy, 470); sg.addColorStop(0, "#ff8a4a"); sg.addColorStop(1, CORAL); c.fillStyle = sg; c.beginPath(); c.arc(540, sy, 470, 0, Math.PI * 2); c.fill();
+ // neck and shoulders rise
+ for (const n of PARTS.neck) { const g = back(ramp(f, n.t0, n.t0 + 16)); tuft(c, [n.x, n.y - 70 + (1 - g) * 60], Math.PI / 2, 0, 150 * g, 52 * g, n.col, 0.3); }
+ ear(c, [262, 300], -1, f); ear(c, [818, 300], 1, f);
+ // the head's own mass, then the coat over it: rings of tufts from the nose outward, breathing once it is whole
+ const mass = ramp(f, 70, 132); // it spreads just under the coat as the rings open, never a bare disc
+ if (mass > 0) { c.fillStyle = "#b9731f"; c.beginPath(); c.ellipse(F[0], F[1], lerp(50, 372, mass), lerp(48, 352, mass), 0, 0, Math.PI * 2); c.fill(); }
+ c.save(); c.translate(F[0], F[1]); c.scale(1, 0.95); c.translate(-F[0], -F[1]);
+ const alive = ramp(f, 170, 200) * (1 - ramp(f, 300, 330));
+ for (const t of PARTS.coat) { const g = back(ramp(f, t.t0, t.t0 + 15)); if (g <= 0) continue; const br = 1 + 0.045 * alive * Math.sin(f * (Math.PI / 45) + t.ring * 0.9); tuft(c, F, t.a, t.r0, t.r0 + (t.r1 - t.r0) * g * br, t.w * Math.min(1, g), t.col); }
+ c.restore();
+ for (const p of PARTS.spots) { const g = back(ramp(f, p.t0, p.t0 + 9)); if (g <= 0) continue; c.fillStyle = DARK; c.beginPath(); c.ellipse(p.x, p.y, p.s * 1.12 * g, p.s * 0.94 * g, p.a, 0, Math.PI * 2); c.fill(); }
+ // the bridge of the nose: a pale fan falling from between the eyes
+ for (let i = -4; i <= 4; i++) { const g = back(ramp(f, 108 + Math.abs(i) * 2, 126 + Math.abs(i) * 2)); tuft(c, [540, 452], Math.PI / 2 + i * 0.075, 20, 20 + (194 - Math.abs(i) * 12) * g, 13 * g, i % 2 ? "#f4cd7e" : "#f8dca0", 0.18); }
+ tear(c, 1, inOut(ramp(f, 134, 162))); tear(c, -1, inOut(ramp(f, 134, 162)));
+ eye(c, EYE_L, -1, f, pupilCol, f < 290); eye(c, EYE_R, 1, f, pupilCol, true);
+ // the muzzle: two pale lobes and the chin
+ const mz = ramp(f, 124, 150);
+ for (let j = 0; j < 22; j++) { const g = back(clamp(mz * 1.5 - 0.25)); tuft(c, [540, 760], Math.PI / 2 + (j / 21 - 0.5) * 1.7, 30, 30 + 98 * g, 13 * g, j % 2 ? CREAM : PALE, 0.15); }
+ for (const sd of [-1, 1]) for (let j = 0; j < 30; j++) { const g = back(clamp(mz * 1.6 - (j / 30) * 0.5)); tuft(c, [540 + sd * 52, 742], (j / 30) * Math.PI * 2, 6, 6 + (72 + (j % 2) * 6) * g, 12 * g, j % 2 ? PALE : CREAM, 0.15); }
+ const dots = ramp(f, 150, 162); if (dots > 0) for (const sd of [-1, 1]) for (let row = 0; row < 3; row++) for (let k = 0; k < 4; k++) { c.fillStyle = "#2a1a12"; c.beginPath(); c.arc(540 + sd * (36 + k * 20 + row * 5), 742 + row * 17 - k * 3, 3.2 * dots, 0, Math.PI * 2); c.fill(); }
+ // nose, mouth, whiskers
+ const ns = back(ramp(f, 140, 154));
+ if (ns > 0) { c.save(); c.translate(540, 690); c.scale(ns, ns); c.translate(-540, -690);
+ c.fillStyle = "#1a0f0c"; c.beginPath(); c.moveTo(488, 672); c.bezierCurveTo(510, 656, 570, 656, 592, 672); c.bezierCurveTo(588, 706, 560, 728, 540, 734); c.bezierCurveTo(520, 728, 492, 706, 488, 672); c.fill();
+ c.strokeStyle = "rgba(255,245,222,0.35)"; c.lineWidth = 3; c.lineCap = "round"; c.beginPath(); c.moveTo(506, 674); c.quadraticCurveTo(540, 664, 574, 674); c.stroke(); c.restore(); }
+ const mo = ramp(f, 152, 166); if (mo > 0) { c.strokeStyle = "#1a0f0c"; c.lineWidth = 5; c.lineCap = "round"; c.beginPath(); c.moveTo(540, 732); c.lineTo(540, 732 + 36 * mo); if (mo >= 1) { const q = ramp(f, 166, 176); c.moveTo(540, 768); c.quadraticCurveTo(540 - 28 * q, 768 + 32 * q, 540 - 70 * q, 768 + 18 * q); c.moveTo(540, 768); c.quadraticCurveTo(540 + 28 * q, 768 + 32 * q, 540 + 70 * q, 768 + 18 * q); } c.stroke(); }
+ const wh = out3(ramp(f, 160, 184)); if (wh > 0) for (const sd of [-1, 1]) for (let k = 0; k < 5; k++) { const sway = Math.sin(f * (Math.PI / 60) + k) * 6 * alive, a: P = [540 + sd * 96, 742 + k * 9], m: P = [540 + sd * 250, 720 + k * 22 + sway * 0.5], e: P = [540 + sd * (400 + k * 14), 690 + k * 46 + sway]; c.strokeStyle = PALE; c.globalAlpha = 0.85; c.lineWidth = 2; c.beginPath(); c.moveTo(a[0], a[1]); for (let i = 1; i <= 16; i++) { const t = (i / 16) * wh, u = 1 - t; c.lineTo(u * u * a[0] + 2 * u * t * m[0] + t * t * e[0], u * u * a[1] + 2 * u * t * m[1] + t * t * e[1]); } c.stroke(); }
+ c.globalAlpha = 1;
+ grass(c, f, 1);
+ // screen space: the crescent carried out of the pupil to its place in the sky, and the grass coming back
+ c.setTransform(s, 0, 0, s, 0, 0);
+ if (f >= 290) { const u = ramp(f, 290, 338), e = inOut(u), from: P = [540 + (EYE_L[0] - 10 - cam.look[0]) * Math.min(cam.z, 1.6), 540 + (EYE_L[1] - 12 - cam.look[1]) * Math.min(cam.z, 1.6)]; crescent(c, lerp(from[0], MOON[0], e), lerp(from[1], MOON[1], e) - Math.sin(Math.PI * u) * 40, 9.5 * Math.pow(MOON_R / 9.5, e), PALE); }
+ if (f >= 322) { stars(c, f, ramp(f, 326, 352)); grass(c, f, inOut(ramp(f, 322, 359))); }
+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.drawImage(grainLayer(env).canvas, 0, 0);
+};
+
+// the score: four bars at 80 bpm are the film's 12 s exactly, so the loop is the music's own
+const audio = (sr: number): [Float32Array, Float32Array] => {
+ const n = Math.round((N / 30) * sr), L = new Float32Array(n), R = new Float32Array(n), m = renderLoop(cheetahDuskScore(), sr); // its tail folded back onto its start: no cut at the seam
+ for (let i = 0; i < n && i < m.L.length; i++) { L[i] = m.L[i]; R[i] = m.R[i]; }
+ return [L, R];
+};
+
+export const cheetahDusk: Film = {
+ meta: { title: "Cheetah, dusk", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu", kind: "loop", poster: 260, score: { tempo: 80, form: "4 bars, looping: pad and phrase, groove, climb, half-time home" } },
+ assets: { images: {} },
+ shots: [{ id: "cheetah", start: 0, end: N, draw }],
+ audio: Object.assign(audio, { scores: [cheetahDuskScore()] }),
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/morph.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/morph.ts
new file mode 100644
index 0000000..93436c3
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/morph.ts
@@ -0,0 +1,94 @@
+// MORPH. One silhouette carried across a seam: the ink drop becomes the card, the seal becomes the
+// next page. The viewer follows a single object, so the next scene is not a new picture, it is what
+// that object turned into (references/motion-grammar.md, "Persistent actor"). Until now the bloom
+// and the drop were one-offs; this is the general move.
+//
+// A shape is a closed outline in screen px. A handoff takes a source shape, a target shape and the
+// frames it leaves and lands, and gives the outline at every frame between: it travels (on an arc
+// if asked), stretches a little along its own direction while it is moving, and turns into the
+// target mostly in the second half of the trip, so it reads as one thing going somewhere and then
+// becoming something. On the landing frame it is the target, point for point.
+//
+// const h = handoff({ from: circleShape([820, 300], 16), to: rectShape(240, 420, 600, 380, 28), t0: 45, t1: 80, arc: 90 });
+// h.at(f) the outline at frame f (exactly the source until t0, exactly the target from t1)
+// fillShape(ctx, env, h.at(f), INK);
+// checkShapes(h.at(80), cardOutlineOfTheNextScene); throws if the seam jumps more than 2 px
+//
+// Keep the object's colour and edge the same on both sides: a black drop that lands as a white card
+// is two objects. Pure functions of their arguments; nothing here touches the clock or Math.random.
+import type { Ctx, Env, P } from "./core";
+import { blot, clamp, inOut, lerp, ramp } from "./launchKit";
+
+export type Shape = P[];
+export const circleShape = (c: P, r: number, n = 72): Shape => Array.from({ length: n }, (_, i): P => { const a = (i / n) * Math.PI * 2; return [c[0] + Math.cos(a) * r, c[1] + Math.sin(a) * r]; });
+/** An ink blot, the bloom's wobbling rim (launchKit's `blot`). */
+export const blotShape = (c: P, r: number, seed = 88): Shape => blot(c, r, seed);
+export const rectShape = (x: number, y: number, w: number, h: number, r = 0, perCorner = 10): Shape => {
+ const q = Math.min(r, w / 2, h / 2), pts: P[] = [];
+ const corner = (cx: number, cy: number, a0: number) => { if (q <= 0) { pts.push([cx, cy]); return; } for (let i = 0; i <= perCorner; i++) { const a = a0 + (i / perCorner) * (Math.PI / 2); pts.push([cx + Math.cos(a) * q, cy + Math.sin(a) * q]); } };
+ corner(x + w - q, y + q, -Math.PI / 2); corner(x + w - q, y + h - q, 0); corner(x + q, y + h - q, Math.PI / 2); corner(x + q, y + q, Math.PI);
+ return pts;
+};
+
+const inside = (p: P, s: Shape) => { let c = false; for (let i = 0, j = s.length - 1; i < s.length; j = i++) { const a = s[i], b = s[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0]) c = !c; } return c; };
+/** The same shape, centred on the frame and grown until the whole frame (plus `pad`) is inside it: a card opening into the page. */
+export const coverShape = (s: Shape, W: number, H: number, pad = 24): Shape => {
+ const c = centreOf(s), at = (k: number) => s.map(([x, y]): P => [W / 2 + (x - c[0]) * k, H / 2 + (y - c[1]) * k]), corners: P[] = [[-pad, -pad], [W + pad, -pad], [W + pad, H + pad], [-pad, H + pad]];
+ let lo = 0, hi = 1; while (!corners.every((q) => inside(q, at(hi)))) { hi *= 2; if (hi > 1e4) throw new Error("morph: this shape cannot cover the frame (its centre must be inside it)"); }
+ for (let i = 0; i < 30; i++) { const mid = (lo + hi) / 2; if (corners.every((q) => inside(q, at(mid)))) hi = mid; else lo = mid; }
+ return at(hi);
+};
+const area = (s: Shape) => s.reduce((a, p, i) => { const q = s[(i + 1) % s.length]; return a + p[0] * q[1] - q[0] * p[1]; }, 0) / 2;
+/** The middle of a shape's bounding box: the point a handoff carries along its path. */
+export const centreOf = (s: Shape): P => { const xs = s.map((p) => p[0]), ys = s.map((p) => p[1]); return [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...ys) + Math.max(...ys)) / 2]; };
+/** `n` points spaced evenly along the outline, clockwise on screen, so any two shapes can be paired point for point. */
+export const resample = (shape: Shape, n = 120): Shape => {
+ const s = area(shape) < 0 ? [...shape].reverse() : shape, m = s.length, L = s.map((p, i) => Math.hypot(s[(i + 1) % m][0] - p[0], s[(i + 1) % m][1] - p[1])), tot = L.reduce((a, b) => a + b, 0);
+ if (m < 3 || tot <= 0) throw new Error("morph: a shape needs at least three points and some size");
+ const out: P[] = []; let i = 0, acc = 0;
+ for (let k = 0; k < n; k++) { const d = (k / n) * tot; while (i < m - 1 && acc + L[i] < d) acc += L[i++]; const u = L[i] ? (d - acc) / L[i] : 0, a = s[i], b = s[(i + 1) % m]; out.push([lerp(a[0], b[0], u), lerp(a[1], b[1], u)]); }
+ return out;
+};
+// the rotation of b's point order that pairs it best with a, each taken about its own centre and at its own size
+const pairUp = (a: Shape, b: Shape): Shape => {
+ const n = a.length, norm = (s: Shape) => { const c = centreOf(s), k = Math.sqrt(s.reduce((t, p) => t + (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2, 0) / n) || 1; return s.map(([x, y]): P => [(x - c[0]) / k, (y - c[1]) / k]); };
+ const A = norm(a), B = norm(b); let best = 0, bd = Infinity;
+ for (let k = 0; k < n; k++) { let d = 0; for (let i = 0; i < n && d < bd; i++) { const q = B[(i + k) % n]; d += (A[i][0] - q[0]) ** 2 + (A[i][1] - q[1]) ** 2; } if (d < bd) { bd = d; best = k; } }
+ return b.map((_, i) => b[(i + best) % n]);
+};
+
+export type HandoffSpec = {
+ from: Shape; to: Shape;
+ t0: number; t1: number; // the frame it leaves, the frame it has landed
+ arc?: number; // lifts the path between the two (px, up)
+ stretch?: number; // how much it lengthens along its travel at mid-flight (default 0.16; 0 for none)
+ turn?: [number, number]; // the part of the trip in which it becomes the target (default [0.3, 1])
+ ease?: (t: number) => number; points?: number;
+};
+/** A handoff, its shapes paired once. `at(f)` is the outline at frame f; `centre(f)` where it is. */
+export const handoff = (h: HandoffSpec) => {
+ if (!(h.t1 > h.t0)) throw new Error(`morph: the handoff lands at ${h.t1}, not after it leaves at ${h.t0}`);
+ if (h.turn && !(h.turn[1] > h.turn[0])) throw new Error(`morph: turn [${h.turn}] must end after it starts`);
+ const n = Math.max(8, Math.round(h.points ?? 160)), A = resample(h.from, n), B = pairUp(A, resample(h.to, n)), ca = centreOf(A), cb = centreOf(B), ease = h.ease ?? inOut, [m0, m1] = h.turn ?? [0.3, 1];
+ const centre = (f: number): P => { const u = ramp(f, h.t0, h.t1), e = ease(u); return [lerp(ca[0], cb[0], e), lerp(ca[1], cb[1], e) - Math.sin(Math.PI * u) * (h.arc ?? 0)]; };
+ const at = (f: number): Shape => {
+ if (f <= h.t0) return h.from; if (f >= h.t1) return h.to; // exact at both ends: the seam is the shape itself
+ const u = ramp(f, h.t0, h.t1), m = inOut(ramp(u, m0, m1)), c = centre(f), c2 = centre(f + 0.5), c1 = centre(f - 0.5), vx = c2[0] - c1[0], vy = c2[1] - c1[1], v = Math.hypot(vx, vy);
+ const k = 1 + (h.stretch ?? 0.16) * Math.sin(Math.PI * u) * clamp(v / 6) * (1 - m), dx = v ? vx / v : 1, dy = v ? vy / v : 0; // longer along the travel, thinner across it, less so as it becomes the target
+ return A.map((a, i): P => { const b = B[i], x = lerp(a[0] - ca[0], b[0] - cb[0], m), y = lerp(a[1] - ca[1], b[1] - cb[1], m), al = (x * dx + y * dy) * k, ac = (-x * dy + y * dx) / k; return [c[0] + al * dx - ac * dy, c[1] + al * dy + ac * dx]; });
+ };
+ return { at, centre, t0: h.t0, t1: h.t1 };
+};
+// distance from a point to a closed outline (its edges, not only its points)
+const toOutline = (p: P, s: Shape) => { let d = Infinity; for (let i = 0; i < s.length; i++) { const a = s[i], b = s[(i + 1) % s.length], vx = b[0] - a[0], vy = b[1] - a[1], t = clamp(((p[0] - a[0]) * vx + (p[1] - a[1]) * vy) / (vx * vx + vy * vy || 1)); d = Math.min(d, Math.hypot(p[0] - a[0] - vx * t, p[1] - a[1] - vy * t)); } return d; };
+/** The largest distance between two outlines in px: every point of each (and 240 more along it) to the other's nearest edge. */
+export const shapeGap = (a: Shape, b: Shape) => Math.max(...[...a, ...resample(a, 240)].map((p) => toOutline(p, b)), ...[...b, ...resample(b, 240)].map((p) => toOutline(p, a)));
+/** Throws unless the two sides of a seam put the outline in the same place within `tol` px. */
+export const checkShapes = (out: Shape, into: Shape, label = "handoff", tol = 2) => {
+ const g = shapeGap(out, into);
+ if (!(g <= tol)) throw new Error(`morph: ${label} jumps ${g.toFixed(1)} px at the seam; the shape must sit in the same place on both sides`);
+ return g;
+};
+export const pathShape = (ctx: Ctx, s: Shape) => { ctx.beginPath(); s.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); };
+/** The silhouette, filled, in screen px. */
+export const fillShape = (ctx: Ctx, env: Env, s: Shape, color: string) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.globalAlpha = 1; ctx.fillStyle = color; pathShape(ctx, s); ctx.fill(); };
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/morphDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/morphDemo.ts
new file mode 100644
index 0000000..969b45a
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/morphDemo.ts
@@ -0,0 +1,36 @@
+// MORPH DEMO. One ink shape, three states, never cut (120 bpm: a beat is 15 frames).
+// 0-45 "ONE SHAPE" is written; its full stop lands as a drop of ink
+// 48-84 the full stop drops, swings in under the words, and lands as a card (the first handoff)
+// 88-138 "CARRIED" is written on the card in the paper's colour, then taken back
+// 140-172 the card opens into the whole page (the second handoff)
+// 174-240 "ACROSS THE CUT" is written on the page
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import { out3, ramp } from "./launchKit";
+import { measure, writeOn } from "./kinetic";
+import { checkShapes, circleShape, coverShape, fillShape, handoff, rectShape } from "./morph";
+
+const W = 1080, H = 1080, N = 240, PAPER = "#ece6da", INK = "#1d1a16", SIZE = 104, BASE = 330;
+const STOP: P = [W / 2 + measure("ONE SHAPE", SIZE) / 2 + 40, BASE - 15], R = 17;
+const CARD = rectShape(210, 500, 660, 400, 34), PAGE = coverShape(rectShape(210, 500, 660, 400, 34), W, H);
+const h1 = handoff({ from: circleShape(STOP, R), to: CARD, t0: 48, t1: 84, arc: -70 });
+const h2 = handoff({ from: CARD, to: PAGE, t0: 140, t1: 172, stretch: 0, turn: [0, 1] });
+checkShapes(h1.at(84), CARD, "the full stop into the card");
+checkShapes(h2.at(172), PAGE, "the card into the page");
+
+const draw = (ctx: Ctx, f: number, env: Env) => {
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER; ctx.fillRect(0, 0, W, H);
+ writeOn(ctx, env, "ONE SHAPE", W / 2, BASE, SIZE, ramp(f, 4, 32), "ink", { color: INK, align: "center", seed: 5 });
+ if (f >= 32) {
+ const pop = ramp(f, 32, 42), r = R * (out3(pop) + 0.35 * Math.sin(Math.PI * pop) * (1 - pop)); // the drop lands with a small overshoot
+ fillShape(ctx, env, f < 48 ? circleShape(STOP, r) : f < 140 ? h1.at(f) : h2.at(f), INK);
+ }
+ if (f >= 88 && f < 140) writeOn(ctx, env, "CARRIED", W / 2, 738, 88, ramp(f, 88, 112) * (1 - ramp(f, 126, 138)), "ink", { color: PAPER, align: "center", seed: 9 });
+ if (f >= 174) writeOn(ctx, env, "ACROSS THE CUT", W / 2, 580, 84, ramp(f, 174, 206), "ink", { color: PAPER, align: "center", seed: 11 });
+};
+
+export const morphDemo: Film = {
+ meta: { title: "morph · one shape carried across the seam", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu", holds: [[206, N, "the last line, read"]] },
+ assets: { images: {} },
+ shots: [{ id: "morph", start: 0, end: N, draw }],
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/cheetah.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/cheetah.ts
new file mode 100644
index 0000000..14652a1
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/cheetah.ts
@@ -0,0 +1,36 @@
+// CHEETAH, DUSK: the score. Four bars at 80 bpm, exactly the film's 12 s, written to loop.
+// Chill lo-fi electronic in D major, a drifting IV-iii-vi-V: Gmaj9, F#m7, Bm9, A11.
+// BARS [film]: 1 pad and a first phrase, no drums [night, the sun comes up] · 2 the groove enters,
+// the phrase answers itself [the face makes itself] · 3 the phrase climbs, a high counter-line
+// joins [alive] · 4 half-time, the line falls back home [into the eye], and round again.
+import { type Piece } from "../plan";
+import { composePiece, type Material } from "../compose";
+
+export const cheetahDuskMaterial = (): Material => ({
+ style: "lofiElectronic", title: "Cheetah, dusk", seed: 4107, mood: "calm", bpm: 80, key: "D", mode: "major", swing: 0.55, loop: true, tail: 1.2, levels: { lead: 2.8, counter: -5, chords: -2, snare: -1.5 },
+ chords: {
+ Gmaj9: { voicing: "[B3 D4 F#4 A4]", bass: "G1:2.5 r:.5 G1:1" },
+ "F#m7": { voicing: "[A3 C#4 E4 F#4]", bass: "F#1:2.5 r:.5 C#2:1" },
+ Bm9: { voicing: "[A3 C#4 D4 F#4]", bass: "B1:2.5 r:.5 F#1:1" },
+ A11: { voicing: "[G3 B3 D4 E4]", bass: "A1:2.5 r:.5 E2:1" },
+ },
+ motifs: {
+ rise: "r:1 F#5:.5 A5:.5 B5:1.5 A5:.5",
+ answer: "r:.5 E5:.5 F#5:.5 A5:1 F#5:.5 E5:1",
+ climb: "r:1 D5:.5 F#5:.5 A5:1 B5:.5 D6:.5",
+ home: "C#6:1.5 B5:.5 A5:1 r:1",
+ rest: "r:4",
+ glint: "r:2 F#6:.5 E6:.5 D6:1",
+ settle: "r:1 E6:.5 C#6:.5 A5:2",
+ },
+ grooves: {
+ main: { kick: ["C4:1 r:.5 C4:[email protected] r:.5 C4:[email protected]"], snare: ["r:1 C4:1 r:1 C4:1"], ghost: ["r:3.5 C4:[email protected]"], hat: ["C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]"], cycle: "piece" },
+ half: { kick: ["C4:2.5 C4:[email protected]"], snare: ["r:2 C4:2"], hat: ["C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]"], cycle: "piece" },
+ },
+ sections: [
+ { kind: "intro", bars: 1, harmony: ["Gmaj9"], lead: ["rise"], chordVel: 0.8 },
+ { kind: "hook", bars: 2, harmony: ["F#m7", "Bm9"], lead: ["answer", "climb"], counter: ["rest", "glint"] },
+ { kind: "half", bars: 1, harmony: ["A11"], lead: ["home"], counter: ["settle"] },
+ ],
+});
+export const cheetahDuskScore = (): Piece => composePiece(cheetahDuskMaterial());
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfx.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfx.ts
index 15a3d41..be694fe 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfx.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfx.ts
@@ -1,5 +1,5 @@
// anidoodle sound effects: the kit (sfxKit), its building blocks (sfxCore) and film placement (sfxMix).
// Docs: references/music/sound-design.md. Tool: engine/tools/sfx.mjs.
export { SFX, SFX_KINDS, sfxVariants, sfxInfo, renderSfx, validateSfx, sfxNeeds, parseKey, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";
-export { placeSfx, sfxDuck, sfxAudibility, mixSfx, assertSfxAudible, filmSfx, validateSfxPlan, resolveSfxPlan, type SfxCue, type SfxPlan, type SfxSnap, type PlacedCue, type SfxAudibility, type SfxMix } from "./sfxMix";
+export { placeSfx, sfxDuck, sfxAudibility, sfxHarshness, SFX_HARSH_CAPS, mixSfx, assertSfxAudible, filmSfx, validateSfxPlan, resolveSfxPlan, type SfxCue, type SfxPlan, type SfxSnap, type PlacedCue, type SfxAudibility, type SfxHarshOptions, type SfxHarshness, type SfxMix } from "./sfxMix";
export { type SfxStereo } from "./sfxCore";
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts
index d756727..3bbc4f5 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts
@@ -4,12 +4,13 @@
// mix FAILS if a cue sits more than minDb under it (a cue nobody hears is a bug, not a choice).
import { renderSfx, validateSfx, sfxNeeds, SFX, SFX_KINDS, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";
import { kWeight, winLufs, mixSeed, strSeed, secs, type SfxStereo } from "./sfxCore";
-import { db } from "./dsp";
+import { Biquad, db } from "./dsp";
import { MODES } from "./theory";
import type { Piece } from "./plan";
import { loudness, truePeak } from "./meter";
export type SfxSnap = "none" | "bar" | "beat" | "8th" | "16th";
+export type SfxHarshOptions = { mode?: "report" | "throw" | "tame"; maxLiftDb?: number; maxTiltDb?: number; maxPeakDb?: number };
export type SfxCue = SfxOpts & {
/** the whole frame the sound's sync point lands on (the hit; the pass-by of a whoosh; the END of a riser). A fractional frame throws. */
frame: number; kind: SfxKind; label?: string;
@@ -19,6 +20,8 @@ export type SfxCue = SfxOpts & {
duckDb?: number;
/** audibility floor for this cue (dB vs the score); default plan.minDb ?? -6. */
minDb?: number;
+ /** Overrides plan.harsh field by field (including mode). */
+ harsh?: SfxHarshOptions;
};
export type SfxPlan = {
fps: number; frames: number; cues: SfxCue[];
@@ -35,13 +38,34 @@ export type SfxPlan = {
minDb?: number;
/** final true-peak ceiling in dBTP. Default -1. */
ceilingDb?: number;
+ /** Default report: samples stay frozen. Caps are cue-minus-score band RMS, band-minus-full RMS,
+ * and absolute sample peak dBFS. Tame scales cues only, never the score or duck envelope. */
+ harsh?: SfxHarshOptions;
};
export type PlacedCue = { i: number; cue: SfxCue; sound: SfxSound; hitS: number; snappedFromS: number; start: number; window: [number, number] };
export type SfxAudibility = { i: number; kind: SfxKind; variant: string; label: string; atS: number; cueLufs: number; musicLufs: number; marginDb: number; peakMarginDb: number; minDb: number; ok: boolean };
-export type SfxMix = { L: Float32Array; R: Float32Array; sfx: SfxStereo; music: SfxStereo; duck: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; ok: boolean; lufs: number; dbtp: number; limiterDb: number };
+export type SfxHarshness = {
+ i: number; kind: SfxKind; variant: string; label: string; atS: number;
+ cueBandDb: number; musicBandDb: number; liftDb: number | null; cueRmsDb: number; tiltDb: number;
+ peakDb: number; musicPeakDb: number; peakMarginDb: number | null; peakAtS: number; bodyDb: number; crestDb: number;
+ mode: "report" | "throw" | "tame"; maxLiftDb: number; maxTiltDb: number; maxPeakDb: number;
+ violations: { metric: "liftDb" | "tiltDb" | "peakDb"; valueDb: number; capDb: number; excessDb: number }[];
+ ok: boolean; reductionDb: number; conflict: "audibility floor" | "tilt cannot be fixed by gain" | null;
+};
+export type SfxMix = { L: Float32Array; R: Float32Array; sfx: SfxStereo; music: SfxStereo; duck: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; harshness: SfxHarshness[]; ok: boolean; lufs: number; dbtp: number; limiterDb: number };
+
+// test/sfxKitSurvey.ts: all 44 variants, default gain/seed 1, C/90 bpm, 48 kHz, silence and
+// a steady mid-level score. Maxima 16.49 / -0.80 / -1.00; margins 1.01 / 0.55 / 0.50 dB.
+export const SFX_HARSH_CAPS = Object.freeze({ maxLiftDb: 17.5, maxTiltDb: -0.25, maxPeakDb: -0.5 });
const GRID: Record<Exclude<SfxSnap, "none">, number> = { bar: 0, beat: 1, "8th": 0.5, "16th": 0.25 };
const name = (c: SfxCue, i: number) => `cue #${i} (${c.kind}${c.variant ? ":" + c.variant : ""}${c.label ? ` "${c.label}"` : ""} @ frame ${c.frame})`;
+const validateHarsh = (o: SfxHarshOptions | undefined, where: string) => {
+ if (o === undefined) return;
+ if (!o || typeof o !== "object" || Array.isArray(o)) throw new Error(`sfx plan: ${where}: harsh must be an options object`);
+ if (o.mode !== undefined && !["report", "throw", "tame"].includes(o.mode)) throw new Error(`sfx plan: ${where}: harsh.mode must be report|throw|tame`);
+ for (const key of ["maxLiftDb", "maxTiltDb", "maxPeakDb"] as const) if (o[key] !== undefined && !Number.isFinite(o[key])) throw new Error(`sfx plan: ${where}: harsh.${key} must be a finite number`);
+};
/** A plan with key / bpm / beatsPerBar filled in from its score (explicit plan values win). */
export const resolveSfxPlan = (p: SfxPlan): SfxPlan => {
@@ -59,6 +83,7 @@ export const validateSfxPlan = (plan: SfxPlan) => {
if (p.seed !== undefined && (!Number.isSafeInteger(p.seed) || p.seed < 0 || p.seed > 0xffffffff)) throw new Error(`sfx plan: seed must be an integer 0..4294967295, got ${String(p.seed)}`);
if (p.bpm !== undefined && (!Number.isFinite(p.bpm) || p.bpm < 20 || p.bpm > 300)) throw new Error(`sfx plan: bpm must be 20..300, got ${String(p.bpm)}`);
if (p.minDb !== undefined && !Number.isFinite(p.minDb)) throw new Error("sfx plan: minDb must be a finite number");
+ validateHarsh(p.harsh, "plan");
if (!Array.isArray(p.cues)) throw new Error("sfx plan: cues must be an array");
p.cues.forEach((c, i) => {
if (!c || typeof c !== "object") throw new Error(`sfx plan: cue #${i} is not an object`);
@@ -69,6 +94,7 @@ export const validateSfxPlan = (plan: SfxPlan) => {
if (!(snap === "none" || snap in GRID)) throw new Error(`sfx plan: ${name(c, i)}: snap must be none|bar|beat|8th|16th`);
if ((snap !== "none" || c.beats !== undefined) && p.bpm === undefined && c.bpm === undefined) throw new Error(`sfx plan: ${name(c, i)}: snap/beats need a bpm (plan.bpm)`);
if (c.duckDb !== undefined && (!Number.isFinite(c.duckDb) || c.duckDb < 0 || c.duckDb > 18)) throw new Error(`sfx plan: ${name(c, i)}: duckDb must be 0..18`);
+ validateHarsh(c.harsh, name(c, i));
try { validateSfx(c.kind, optsOf(p, c, 0)); } catch (e) { throw new Error(`sfx plan: ${name(c, i)}: ${(e as Error).message}`); }
const o = optsOf(p, c, 0), need = sfxNeeds(c.kind, c.variant ?? SFX[c.kind].variants[0], o);
if (need.key && o.key === undefined) throw new Error(`sfx plan: ${name(c, i)} is tuned: set plan.key, cue.key, or plan.score (the film's piece); there is no default key`);
@@ -142,6 +168,49 @@ export const sfxAudibility = (placed: PlacedCue[], music: SfxStereo, sr: number,
});
};
+// Measurement only: RBJ 2nd-order Butterworth HP at 2 kHz then LP at 8 kHz, zero state,
+// Float64 throughout, run from buffer start (not reset at the speaking window). No K weighting.
+const presence = (x: Float32Array, sr: number) => {
+ const hp = Biquad.make(sr, "hp", 2000, Math.SQRT1_2), lp = Biquad.make(sr, "lp", 8000, Math.SQRT1_2), out = new Float64Array(x.length);
+ for (let i = 0; i < x.length; i++) out[i] = lp.tick(hp.tick(x[i]));
+ return out;
+};
+// Stereo mean power: a duplicated mono sine has its ordinary RMS dBFS, not +3 dB.
+// A body window is always the full 150 ms; a short tail contributes zero after its end.
+const rmsDb = (L: ArrayLike<number>, R: ArrayLike<number>, a: number, b: number, pad = false) => {
+ const lo = Math.max(0, a), hi = Math.min(L.length, b); let e = 0;
+ for (let i = lo; i < hi; i++) e += L[i] * L[i] + R[i] * R[i];
+ return 10 * Math.log10(Math.max(e / (2 * Math.max(1, pad ? b - a : hi - lo)), 1e-20));
+};
+const peakOf = (L: Float32Array, R: Float32Array, a: number, b: number) => {
+ let peak = 0, at = Math.max(0, a);
+ for (let i = Math.max(0, a); i < Math.min(L.length, b); i++) { const v = Math.max(Math.abs(L[i]), Math.abs(R[i])); if (v > peak) { peak = v; at = i; } }
+ return { db: 20 * Math.log10(Math.max(peak, 1e-12)), at };
+};
+
+/** Pre-master cue harshness vs the ducked score. Score windows match sfxAudibility's 100 ms
+ * minimum. Silence-relative measurements are null below -70 dBFS; levels have a -200 dB RMS /
+ * -240 dB peak numeric floor. The body starts one sample AFTER the first largest window peak. */
+export const sfxHarshness = (placed: PlacedCue[], music: SfxStereo, sr: number, p: Pick<SfxPlan, "minDb" | "harsh">): SfxHarshness[] => {
+ if (!placed.length) return [];
+ const mL = presence(music[0], sr), mR = presence(music[1], sr), minWin = secs(sr, 0.1);
+ return placed.map((pc) => {
+ const s = pc.sound, [wa, wb] = s.window, cueBandDb = rmsDb(presence(s.L, sr), presence(s.R, sr), wa, wb), cueRmsDb = rmsDb(s.L, s.R, wa, wb);
+ let [a, b] = pc.window; if (b - a < minWin) { const c = (a + b) >> 1; a = c - (minWin >> 1); b = a + minWin; }
+ const musicBandDb = rmsDb(mL, mR, a, b), peak = peakOf(s.L, s.R, wa, wb), musicPeakDb = peakOf(music[0], music[1], a, b).db;
+ const bodyDb = rmsDb(s.L, s.R, peak.at + 1, peak.at + 1 + secs(sr, 0.15), true);
+ const o = pc.cue.harsh, mode = o?.mode ?? p.harsh?.mode ?? "report", maxLiftDb = o?.maxLiftDb ?? p.harsh?.maxLiftDb ?? SFX_HARSH_CAPS.maxLiftDb,
+ maxTiltDb = o?.maxTiltDb ?? p.harsh?.maxTiltDb ?? SFX_HARSH_CAPS.maxTiltDb, maxPeakDb = o?.maxPeakDb ?? p.harsh?.maxPeakDb ?? SFX_HARSH_CAPS.maxPeakDb;
+ const liftDb = musicBandDb < -70 ? null : cueBandDb - musicBandDb, tiltDb = cueBandDb - cueRmsDb, violations: SfxHarshness["violations"] = [];
+ for (const [metric, valueDb, capDb] of [["liftDb", liftDb, maxLiftDb], ["tiltDb", tiltDb, maxTiltDb], ["peakDb", peak.db, maxPeakDb]] as const)
+ if (valueDb !== null && valueDb > capDb) violations.push({ metric, valueDb, capDb, excessDb: valueDb - capDb });
+ return { i: pc.i, kind: pc.cue.kind, variant: s.variant, label: pc.cue.label ?? "", atS: pc.hitS,
+ cueBandDb, musicBandDb, liftDb, cueRmsDb, tiltDb,
+ peakDb: peak.db, musicPeakDb, peakMarginDb: musicPeakDb < -70 ? null : peak.db - musicPeakDb, peakAtS: (pc.start + peak.at) / sr, bodyDb, crestDb: peak.db - bodyDb,
+ mode, maxLiftDb, maxTiltDb, maxPeakDb, violations, ok: !violations.length, reductionDb: 0, conflict: null };
+ });
+};
+
/**
* The whole film's sound: score (any length; padded or cut to the film) ducked under the cues,
* effects added, one true-peak ceiling. `music` null = effects only. Does not throw on an inaudible
@@ -149,17 +218,38 @@ export const sfxAudibility = (placed: PlacedCue[], music: SfxStereo, sr: number,
*/
export const mixSfx = (music: SfxStereo | null, p: SfxPlan, sr = 48000): SfxMix => {
const n = Math.round((p.frames / p.fps) * sr), placed = placeSfx(p, sr);
- const fxL = new Float32Array(n), fxR = new Float32Array(n);
- for (const pc of placed) { const { L, R } = pc.sound; for (let i = 0; i < L.length && pc.start + i < n; i++) { fxL[pc.start + i] += L[i]; fxR[pc.start + i] += R[i]; } }
const duck = sfxDuck(placed, n, sr, p.duck), mL = new Float32Array(n), mR = new Float32Array(n);
if (music) { const m = Math.min(n, music[0].length); for (let i = 0; i < m; i++) { mL[i] = music[0][i] * duck[i]; mR[i] = music[1][i] * duck[i]; } }
+ let harshness = sfxHarshness(placed, [mL, mR], sr, p);
+ const changes = new Map<number, { reductionDb: number; conflict: SfxHarshness["conflict"] }>();
+ if (harshness.some((h) => h.mode === "tame" && !h.ok)) {
+ const aud = sfxAudibility(placed, [mL, mR], sr, p);
+ for (let i = 0; i < placed.length; i++) {
+ const h = harshness[i]; if (h.mode !== "tame" || h.ok) continue;
+ // Gain cannot change spectral tilt. Leave this cue untouched, even if another cap broke.
+ if (h.violations.some((v) => v.metric === "tiltDb")) { changes.set(h.i, { reductionDb: 0, conflict: "tilt cannot be fixed by gain" }); continue; }
+ const a = aud[i], excess = Math.max(...h.violations.map((v) => v.excessDb)), room = a.musicLufs < -70 ? Infinity : Math.max(0, a.marginDb - a.minDb - 1e-5);
+ // Float32 scaling can move a measurement by a few ulps: stay just inside both boundaries.
+ const down = a.ok ? Math.min(excess + 1e-5, room) : 0, pc = placed[i], g = db(-down);
+ if (down > 0) {
+ for (let j = 0; j < pc.sound.L.length; j++) { pc.sound.L[j] *= g; pc.sound.R[j] *= g; }
+ pc.sound.lufs -= down; pc.cue = { ...pc.cue, gainDb: (pc.cue.gainDb ?? 0) - down };
+ }
+ changes.set(h.i, { reductionDb: down, conflict: down < excess ? "audibility floor" : null });
+ }
+ harshness = sfxHarshness(placed, [mL, mR], sr, p).map((h) => ({ ...h, ...changes.get(h.i) }));
+ }
+ const bad = harshness.filter((h) => h.mode === "throw" && !h.ok);
+ if (bad.length) throw new Error(`sfx: ${bad.length} harsh cue(s):\n` + bad.map((h) => ` #${h.i} ${h.kind}:${h.variant}${h.label ? ` "${h.label}"` : ""} @ ${h.atS.toFixed(2)} s: ` + h.violations.map((v) => `${v.metric} ${v.valueDb.toFixed(2)} dB (cap ${v.capDb} dB, excess ${v.excessDb.toFixed(2)} dB)`).join(", ")).join("\n"));
+ const fxL = new Float32Array(n), fxR = new Float32Array(n);
+ for (const pc of placed) { const { L, R } = pc.sound; for (let i = 0; i < L.length && pc.start + i < n; i++) { fxL[pc.start + i] += L[i]; fxR[pc.start + i] += R[i]; } }
const L = new Float32Array(n), R = new Float32Array(n);
for (let i = 0; i < n; i++) { L[i] = mL[i] + fxL[i]; R[i] = mR[i] + fxR[i]; }
const limiterDb = ceiling(L, R, sr, db((p.ceilingDb ?? -1) - 0.3));
const fade = Math.min(n, secs(sr, 0.015)); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }
const audibility = sfxAudibility(placed, [mL, mR], sr, p);
const lu = n >= secs(sr, 0.4) ? loudness([L, R], sr).integrated : NaN;
- return { L, R, sfx: [fxL, fxR], music: [mL, mR], duck, placed, audibility, ok: audibility.every((a) => a.ok), lufs: lu, dbtp: truePeak([L, R]).dbtp, limiterDb };
+ return { L, R, sfx: [fxL, fxR], music: [mL, mR], duck, placed, audibility, harshness, ok: audibility.every((a) => a.ok), lufs: lu, dbtp: truePeak([L, R]).dbtp, limiterDb };
};
export const assertSfxAudible = (m: SfxMix) => {
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/transitions.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/transitions.ts
new file mode 100644
index 0000000..5bdf4a3
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/transitions.ts
@@ -0,0 +1,135 @@
+// TRANSITIONS. Three seams every film used to hand-roll, as reusable calls: a brush wipe, an iris,
+// and a flash on a cut. Each takes the two scenes as draw functions and a progress, at any frame
+// size, and is a pure function of its arguments (the brush's bristles come from rng(seed), never
+// from the clock). A gentle move stays the default seam (references/workflows/launch-video.md,
+// Motion); which of these fits a seam, and when none does, is references/motion-grammar.md.
+//
+// const p = seam(local, 120, 22); progress 0..1 over frames 120-142
+// brushWipe(ctx, env, p, drawA, drawB, { angle: -0.2, ink: "#1d1a16" });
+// iris(ctx, env, p, drawA, drawB, { center: [1400, 300] }); opens on B from a point
+// iris(ctx, env, p, drawA, drawB, { close: true }); closes on A, B is behind it
+// flashCut(ctx, env, local, 240, drawA, drawB); A until 240, B from 240
+// checkFlashes([240, 400], fps); throws if they could strobe
+//
+// A scene is drawn in its own coordinates: it sets its transform itself, as every film's shots do.
+// The incoming scene is already complete under the seam on every frame, so there is never an empty
+// frame between two scenes. At p <= 0 only the outgoing scene is drawn, at p >= 1 only the incoming.
+import { rng, type Ctx, type Env, type P } from "./core";
+import { blot, clamp, inOut, lerp, pathOf, ramp, selfLayer } from "./launchKit";
+
+export type Scene = (ctx: Ctx) => void;
+/** Progress of a seam that starts at frame `at` and lasts `len` frames. */
+export const seam = (local: number, at: number, len: number) => (len > 0 ? ramp(local, at, at + len) : local >= at ? 1 : 0);
+
+// the incoming scene on its own full-frame surface, then set down through a clip in logical units
+const through = (ctx: Ctx, env: Env, key: string, scene: Scene, clip: () => void, rim?: () => void) => {
+ const L = selfLayer(env, `seam:${key}`, Math.round(env.W * env.scale), Math.round(env.H * env.scale));
+ const lc = L.ctx as Ctx & { reset?: () => void }; // a clean context every frame: nothing a scene left behind may reach the next one
+ if (typeof lc.reset === "function") lc.reset(); else { lc.globalAlpha = 1; lc.globalCompositeOperation = "source-over"; lc.setLineDash([]); lc.shadowBlur = 0; }
+ scene(L.ctx);
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
+ ctx.save(); rim?.(); clip(); ctx.clip();
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(L.canvas, 0, 0); ctx.restore();
+};
+
+// ---------------------------------------------------------------- brush wipe
+// A loaded flat brush pulled across the frame. Two edges, both the brush's own: the incoming
+// picture's edge, and ahead of it the front of the wet ink the brush carries (`ink`; leave it out
+// for a clean edge). Each is a row of fine bristles of uneven width following a slow curve, each
+// bristle a little ahead of or behind its neighbour. A few bristles are loaded and streak well
+// ahead of the ink; a few drag, and leave a thread of ink over the new picture for a moment. The
+// two edges have different profiles, so the ink between them is thick here and thin there, as a
+// stroke is. The bristles splay in the middle of the stroke and close up where it starts and lands.
+export type WipeOpts = {
+ angle?: number; // direction of travel in radians: 0 left to right, PI/2 top to bottom
+ seed?: number;
+ bristles?: number; // how many across the stroke (default 96)
+ ragged?: number; // how far the bristle tips vary, in logical px (default 5% of the frame's diagonal)
+ stray?: number; // share of bristles that streak ahead (ink) or drag behind (picture) (default 0.1)
+ ink?: string; band?: number; // the wet ink's colour and its mean width (default 1.1 x ragged)
+ ease?: (t: number) => number;
+};
+const STRAY = 2.4; // a stray bristle runs up to this many times `ragged` from the edge
+const smooth = (t: number) => t * t * (3 - 2 * t);
+/** One edge of the stroke as the polygon of everything behind it, in logical px (pure): the incoming picture's, or the ink's. */
+export const wipeFront = (p: number, W: number, H: number, o: WipeOpts = {}, edge: "picture" | "ink" = "picture"): P[] => {
+ const a = o.angle ?? 0, dx = Math.cos(a), dy = Math.sin(a), n = Math.max(1, Math.round(o.bristles ?? 96)), rag = o.ragged ?? Math.hypot(W, H) * 0.05, band = o.ink ? o.band ?? rag * 1.1 : 0, ink = edge === "ink";
+ const cs: P[] = [[0, 0], [W, 0], [W, H], [0, H]], S = cs.map(([x, y]) => x * dx + y * dy), T = cs.map(([x, y]) => -x * dy + y * dx);
+ const s0 = Math.min(...S), s1 = Math.max(...S), t0 = Math.min(...T) - 4, t1 = Math.max(...T) + 4, back = s0 - 8;
+ const e = clamp((o.ease ?? smooth)(clamp(p))), splay = 0.4 + 0.6 * Math.sin(Math.PI * e), base = lerp(s0 - band - rag * (0.4 * (1 + STRAY) + 0.1), s1 + rag * STRAY, e);
+ const r = rng((o.seed ?? 31) + (ink ? 101 : 0)), ph = [r() * 6.28, r() * 6.28, r() * 6.28], stray = o.stray ?? 0.1;
+ // bristle widths and reaches, fixed for the whole stroke: the profile of one brush
+ const br = Array.from({ length: n }, (_, i) => {
+ const u = i / n, body = clamp(0.5 + 0.3 * Math.sin(u * 5.1 + ph[0]) + 0.16 * Math.sin(u * 13.7 + ph[1]) + 0.07 * Math.sin(u * 41 + ph[2]) + (r() - 0.5) * 0.16), st = r() < stray, far = 0.5 + r() * (STRAY - 0.5);
+ return { w: st ? 0.35 + r() * 0.3 : 0.6 + r() * 0.8, reach: st ? (ink ? body + far : body - far) : body };
+ });
+ const tot = br.reduce((s, b) => s + b.w, 0), at = (s: number, t: number): P => [s * dx - t * dy, s * dy + t * dx];
+ const pts: P[] = [at(back, t0)];
+ let t = t0;
+ for (const b of br) { const w = (b.w / tot) * (t1 - t0), f = Math.max(back, base + b.reach * rag * splay + (ink ? band : 0)); pts.push(at(f, t), at(f, t + w)); t += w; } // square-ended: bristle marks
+ pts.push(at(back, t1));
+ return pts;
+};
+export const brushWipe = (ctx: Ctx, env: Env, p: number, from: Scene, to: Scene, o: WipeOpts = {}) => {
+ if (p >= 1) { to(ctx); return; }
+ from(ctx);
+ if (!(p > 0)) return; // before the seam, or not a number: the outgoing scene, whole
+ const W = env.W, H = env.H;
+ through(ctx, env, "wipe", to, () => pathOf(ctx, wipeFront(p, W, H, o)), o.ink ? () => { pathOf(ctx, wipeFront(p, W, H, o, "ink")); ctx.fillStyle = o.ink!; ctx.fill(); } : undefined);
+};
+
+// ---------------------------------------------------------------- iris
+// A round opening that grows from a point until the incoming scene fills the frame, or (`close`)
+// shrinks to a point on the outgoing one. Open it from the thing the next scene is about, close it
+// on the thing this scene was about: an iris centred on nothing is only a shape. "blot" gives the
+// ink bloom's wobbling rim instead of a clean circle; `rim` is the edge's width in `ink`.
+export type IrisOpts = { center?: P; close?: boolean; shape?: "circle" | "blot"; rim?: number; ink?: string; seed?: number; ease?: (t: number) => number };
+/** The opening's radius in logical px (pure): 0 at p = 0, past the farthest corner at p = 1 (the reverse with `close`). */
+export const irisRadius = (p: number, W: number, H: number, o: IrisOpts = {}) => {
+ const [cx, cy] = o.center ?? [W / 2, H / 2], far = Math.max(Math.hypot(cx, cy), Math.hypot(W - cx, cy), Math.hypot(cx, H - cy), Math.hypot(W - cx, H - cy));
+ const e = clamp((o.ease ?? inOut)(clamp(p))), full = (far + (o.rim ?? 0) + 2) / (o.shape === "blot" ? 0.86 : 1); // a blot's rim dips to 0.9 R
+ return full * (o.close ? 1 - e : e);
+};
+/** The ink rim's width at an opening of radius R (pure): it grows with the opening, so it never appears or vanishes in one frame. */
+export const irisRim = (R: number, o: IrisOpts = {}) => (o.rim ?? (o.shape === "blot" ? 22 : 0)) * clamp(R / 70);
+export const iris = (ctx: Ctx, env: Env, p: number, from: Scene, to: Scene, o: IrisOpts = {}) => {
+ if (p >= 1) { to(ctx); return; }
+ if (!(p > 0)) { from(ctx); return; }
+ const W = env.W, H = env.H, c: P = o.center ?? [W / 2, H / 2], R = irisRadius(p, W, H, o), rim = irisRim(R, o);
+ const edge = (r: number) => { if (o.shape === "blot") pathOf(ctx, blot(c, Math.max(0, r), o.seed ?? 88)); else { ctx.beginPath(); ctx.arc(c[0], c[1], Math.max(0, r), 0, Math.PI * 2); } };
+ // opening: B grows inside the hole over A. closing: A shrinks inside the hole over B.
+ const [outer, inner] = o.close ? [to, from] : [from, to];
+ outer(ctx);
+ if (R < 1) return;
+ through(ctx, env, "iris", inner, () => edge(R - (rim > 0 ? 3 : 0)), rim > 0 ? () => { edge(R + rim); ctx.fillStyle = o.ink ?? "#1d1a16"; ctx.fill(); } : undefined);
+};
+
+// ---------------------------------------------------------------- flash
+// A cut hidden under a burst of light: the frame lifts toward `color` over `inF` frames, the scene
+// changes on the brightest frame, and the light falls away over `outF`. It is a hard cut, so the
+// hard cut's conditions apply (a strong beat, in a piece whose energy asks for it), and it is the
+// one seam here that can hurt: a flash is never a single frame, never full white by default, and
+// never repeated quickly: two flashes are at least half a second apart, which also keeps a film
+// well under three a second. checkFlashes holds a film to that.
+export type FlashOpts = { color?: string; peak?: number; inF?: number; outF?: number };
+const FLASH = { color: "#fff8ea", peak: 0.86, inF: 2, outF: 9 };
+/** The light's opacity at a frame (pure): `peak` on the cut frame, 0 outside [cut - inF, cut + outF). */
+export const flashAlpha = (local: number, cut: number, o: FlashOpts = {}) => {
+ const peak = o.peak ?? FLASH.peak, inF = o.inF ?? FLASH.inF, outF = o.outF ?? FLASH.outF;
+ if (inF < 1 || outF < 3) throw new Error(`flash: inF ${inF}, outF ${outF}: the light must rise over at least 1 frame and fall over at least 3 (a one-frame flash is a fault, not a transition)`);
+ if (local <= cut - inF - 1 || local >= cut + outF) return 0;
+ const k = local < cut ? (local - (cut - inF - 1)) / (inF + 1) : Math.pow(1 - (local - cut) / outF, 2);
+ return clamp(peak) * clamp(k);
+};
+/** The light alone, over whatever is already drawn (when the film switches the scene itself). */
+export const flash = (ctx: Ctx, env: Env, local: number, cut: number, o: FlashOpts = {}) => {
+ const a = flashAlpha(local, cut, o); if (a <= 0) return;
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.globalCompositeOperation = "source-over"; ctx.globalAlpha = a; ctx.fillStyle = o.color ?? FLASH.color; ctx.fillRect(0, 0, env.W, env.H); ctx.globalAlpha = 1;
+};
+export const flashCut = (ctx: Ctx, env: Env, local: number, cut: number, from: Scene, to: Scene, o: FlashOpts = {}) => { (local < cut ? from : to)(ctx); flash(ctx, env, local, cut, o); };
+/** Throws when a film's flashes could strobe: any two closer than half a second. */
+export const checkFlashes = (cuts: number[], fps: number) => {
+ const c = [...cuts].sort((a, b) => a - b);
+ for (let i = 1; i < c.length; i++) if (c[i] - c[i - 1] < fps / 2) throw new Error(`flash: frames ${c[i - 1]} and ${c[i]} are ${((c[i] - c[i - 1]) / fps).toFixed(2)} s apart: leave at least half a second between flashes`);
+ return cuts;
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/transitionsDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/transitionsDemo.ts
new file mode 100644
index 0000000..be44397
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/transitionsDemo.ts
@@ -0,0 +1,39 @@
+// TRANSITIONS DEMO. The three seams of transitions.ts, each once, between four finished plates
+// (120 bpm: a beat is 15 frames). Every plate creeps in a little while it is held, so nothing sits still.
+// 0-30 the lighthouse
+// 26-56 BRUSH WIPE, a loaded ink brush pulled across and slightly down, onto the fox
+// 100-126 IRIS, an ink blot opening from the fox's eye onto the koi
+// 170-194 IRIS closing to a clean round point on the koi's eye; the balloon is behind it
+// 240 FLASH on the cut back to the lighthouse; frame 299 hands over to frame 0
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import { plateLayer } from "./launchKit";
+import { brushWipe, checkFlashes, flashCut, iris, seam, type Scene } from "./transitions";
+import { lighthouse } from "./lighthouse";
+import { fox } from "./fox";
+import { koi } from "./koi";
+import { balloon } from "./balloon";
+
+const W = 1080, H = 1080, N = 300, INK = "#1d1a16";
+const FOX_EYE: P = [596, 466], KOI_EYE: P = [690, 420];
+checkFlashes([240], 30);
+
+// a plate, held: it fills the frame and creeps in by 4% from frame `a` to frame `b`
+const plate = (env: Env, key: string, film: Film, f: number, a: number, b: number): Scene => (c: Ctx) => {
+ const L = plateLayer(env, `seamdemo:${key}`, film, 0, Math.round(W * env.scale), true).canvas, z = 1 + 0.04 * Math.max(0, Math.min(1, (f - a) / (b - a))), s = W * env.scale;
+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.drawImage(L, (s - s * z) / 2, (s - s * z) / 2, s * z, s * z);
+};
+
+const draw = (ctx: Ctx, f: number, env: Env) => {
+ const light = plate(env, "light", lighthouse, f < 150 ? f : f - 300, -60, 56), foxS = plate(env, "fox", fox, f, 30, 126), koiS = plate(env, "koi", koi, f, 100, 194), bal = plate(env, "balloon", balloon, f, 170, 240);
+ if (f < 56) brushWipe(ctx, env, seam(f, 26, 30), light, foxS, { angle: 0.22, ink: INK, seed: 31 });
+ else if (f < 126) iris(ctx, env, seam(f, 100, 26), foxS, koiS, { center: FOX_EYE, shape: "blot", ink: INK });
+ else if (f < 194) iris(ctx, env, seam(f, 170, 24), koiS, bal, { center: KOI_EYE, close: true, rim: 10, ink: INK });
+ else flashCut(ctx, env, f, 240, bal, light);
+};
+
+export const transitionsDemo: Film = {
+ meta: { title: "transitions · brush wipe, iris, flash", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },
+ assets: { images: {} },
+ shots: [{ id: "seams", start: 0, end: N, draw }],
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-calloutDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-calloutDemo.ts
new file mode 100644
index 0000000..5d14c3e
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-calloutDemo.ts
@@ -0,0 +1,4 @@
+import { calloutDemo } from "../canvas-core/calloutDemo";
+import { mountFilm } from "./page";
+
+mountFilm(calloutDemo);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-cheetahDusk.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-cheetahDusk.ts
new file mode 100644
index 0000000..e34f643
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-cheetahDusk.ts
@@ -0,0 +1,4 @@
+import { cheetahDusk } from "../canvas-core/cheetahDusk";
+import { mountFilm } from "./page";
+
+mountFilm(cheetahDusk);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-morphDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-morphDemo.ts
new file mode 100644
index 0000000..b25a3d4
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-morphDemo.ts
@@ -0,0 +1,4 @@
+import { morphDemo } from "../canvas-core/morphDemo";
+import { mountFilm } from "./page";
+
+mountFilm(morphDemo);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-transitionsDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-transitionsDemo.ts
new file mode 100644
index 0000000..ac31725
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-transitionsDemo.ts
@@ -0,0 +1,4 @@
+import { transitionsDemo } from "../canvas-core/transitionsDemo";
+import { mountFilm } from "./page";
+
+mountFilm(transitionsDemo);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/callout.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/callout.test.ts
new file mode 100644
index 0000000..9142425
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/callout.test.ts
@@ -0,0 +1,82 @@
+// CALLOUT TESTS. calloutPose, calloutReady, leaderPath and checkHandoff in
+// src/canvas-core/callout.ts are pure and are held to numbers here. drawCallout and drawLabel
+// draw through kinetic.ts (writeOn / setType) and are not covered. node tools/test.mjs
+import { CALLOUT_T, calloutPose, calloutReady, checkHandoff, leaderPath, type Callout, type LabelPose } from "../src/canvas-core/callout";
+import type { P } from "../src/canvas-core/core";
+
+export const name = "callout";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
+ const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
+ const dist = (a: P, b: P) => Math.hypot(a[0] - b[0], a[1] - b[1]);
+ const anchor = (): P => [500, 600];
+ const base: Callout = { text: "LIVE PREVIEW", anchor, label: { p: [1000, 300], size: 40 }, t0: 60 };
+ const same = (a: LabelPose | null, b: LabelPose) => !!a && near(a.p[0], b.p[0]) && near(a.p[1], b.p[1]) && near(a.size, b.size);
+
+ // 1. calloutPose: null before t0, the label's own pose until a handoff leaves, exactly the
+ // destination pose on `at`
+ ok(calloutPose(base, 0) === null && calloutPose(base, 59) === null, "calloutPose is null before t0");
+ ok(same(calloutPose(base, 60), base.label) && same(calloutPose({ ...base, out: 100 }, 500), base.label), "without a handoff the pose is the label's, leaving included");
+ const hc: Callout = { ...base, handoff: { leave: 120, at: 150, pose: { p: [200, 800], size: 80 }, arc: 60 } };
+ ok(same(calloutPose(hc, 120), base.label), "until leave the pose is still the label's");
+ const landed = calloutPose(hc, 150)!;
+ ok(near(landed.p[0], 200) && near(landed.p[1], 800) && near(landed.size, 80), "on the handoff frame the pose is exactly the next scene's heading");
+ const mid = calloutPose(hc, 135)!; // u = 0.5 -> e = 0.5
+ ok(near(mid.p[0], 600) && near(mid.p[1], 550 - 60, 1e-6), "mid-handoff the label sits on the eased midpoint, lifted by the arc");
+ ok(near(mid.size, Math.sqrt(40 * 80)), `size is eased as a ratio (${mid.size.toFixed(1)} = the geometric mean, not 60)`);
+
+ // 2. calloutReady: the frame the label is fully written
+ ok(calloutReady(base) === 60 + CALLOUT_T.text[1] && calloutReady(base) === 90, "calloutReady is t0 + the text's write-on time");
+
+ // 3. leaderPath, both registers, label to the right and to the left of the anchor
+ const pose: LabelPose = { p: [1000, 300], size: 40 }, w = 300, dot = pose.size * 0.16;
+ const drawn = leaderPath(anchor(), pose, w, "drawn");
+ ok(drawn.length === 25, "a drawn leader is a 25-point bowed stroke");
+ ok(near(dist(drawn[0], anchor()), dot * 2.2), "the drawn line starts off the anchor by the dot gap");
+ ok(near(drawn[24][0], 1000 - 40 * 0.35) && near(drawn[24][1], 300 - 40 * 0.42), "the drawn line ends at the label");
+ const chord: P = [(drawn[0][0] + drawn[24][0]) / 2, (drawn[0][1] + drawn[24][1]) / 2];
+ ok(dist(chord, drawn[12]) > 2, `the drawn line bows off its chord (${dist(chord, drawn[12]).toFixed(1)} px)`);
+ const drawnL = leaderPath([1500, 600], pose, w, "drawn");
+ ok(near(drawnL[24][0], 1000 + w + 40 * 0.35), "label left of the thing: the drawn line lands on its right edge");
+
+ const clean = leaderPath(anchor(), pose, w, "clean");
+ ok(clean.length === 3, "a clean leader is an elbow and an underline");
+ ok(near(dist(clean[0], anchor()), dot * 2), "the clean line starts off the anchor by the dot gap");
+ ok(clean[1][1] === clean[2][1] && near(clean[1][1], 300 + 40 * 0.34), "the underline is horizontal, just under the baseline");
+ ok(clean[1][0] <= 1000 && clean[2][0] >= 1300, "the underline spans the label's whole width");
+ const cleanL = leaderPath([1500, 600], pose, w, "clean");
+ ok(near(cleanL[1][0], 1000 + w + 40 * 0.1) && near(cleanL[2][0], 1000 - 40 * 0.1), "label left of the thing: the elbow meets its right edge and the underline runs left");
+
+ // 4. checkHandoff: a matching pose passes; a 5 px miss, an early leave, or a backwards
+ // window all throw
+ ok(checkHandoff(hc, hc.handoff!.pose).every((g) => g.dp < 1e-6 && g.dr < 1e-6), "a matching pose passes within tolerance");
+ ok(throws(() => checkHandoff(hc, { p: [205, 800], size: 80 })), "a 5 px miss throws");
+ ok(throws(() => checkHandoff(hc, { p: [200, 800], size: 84 })), "a 4 px size miss throws");
+ const early: Callout = { ...base, handoff: { leave: 80, at: 150, pose: { p: [200, 800], size: 80 } } };
+ ok(throws(() => checkHandoff(early, { p: [200, 800], size: 80 })), "leaving at 80, before the label is readable at 90, throws");
+ const back: Callout = { ...base, handoff: { leave: 160, at: 150, pose: { p: [200, 800], size: 80 } } };
+ ok(throws(() => checkHandoff(back, { p: [200, 800], size: 80 })), "landing before it leaves throws");
+ ok(throws(() => checkHandoff(base, { p: [0, 0], size: 10 })), "a callout with no handoff has nothing to check: throws");
+
+ // 5. checkHandoff needs the dot and line's CALLOUT_T.leave frames to retract: a shorter
+ // trip throws even when the pose matches, exactly CALLOUT_T.leave frames is legal
+ const tight: Callout = { ...base, handoff: { leave: 130, at: 141, pose: { p: [200, 800], size: 80 } } };
+ ok(throws(() => checkHandoff(tight, { p: [200, 800], size: 80 })), `a handoff trip under ${CALLOUT_T.leave} frames throws even with a matching pose`);
+ const just: Callout = { ...base, handoff: { leave: 130, at: 130 + CALLOUT_T.leave, pose: { p: [200, 800], size: 80 } } };
+ ok(!throws(() => checkHandoff(just, { p: [200, 800], size: 80 })), `a trip of exactly ${CALLOUT_T.leave} frames is legal`);
+
+ // 6. calloutPose with a size of 0 on either side falls back to a linear ease: finite numbers
+ const zeroA: Callout = { ...base, label: { p: [1000, 300], size: 0 }, handoff: { leave: 120, at: 150, pose: { p: [200, 800], size: 80 } } };
+ const zeroB: Callout = { ...base, handoff: { leave: 120, at: 150, pose: { p: [200, 800], size: 0 } } };
+ for (const c of [zeroA, zeroB]) for (const f of [120, 135, 149, 150]) {
+ const p = calloutPose(c, f)!;
+ ok(Number.isFinite(p.p[0]) && Number.isFinite(p.p[1]) && Number.isFinite(p.size), `a size of 0 gives finite numbers through the handoff (f=${f})`);
+ }
+ ok(near(calloutPose(zeroA, 135)!.size, 40), "0 -> 80 eases linearly through 40 at the midpoint");
+
+ // 7. leaderPath's `side` pins which edge the line meets, wherever the anchor sits
+ ok(near(leaderPath([500, 600], pose, w, "drawn", undefined, false)[24][0], 1000 + w + 40 * 0.35), "side=false: the drawn line meets the label's right edge though the anchor is left of it");
+ ok(near(leaderPath([1500, 600], pose, w, "drawn", undefined, true)[24][0], 1000 - 40 * 0.35), "side=true: the drawn line meets the label's left edge though the anchor is right of it");
+ const pinned = leaderPath([500, 600], pose, w, "clean", undefined, false);
+ ok(near(pinned[1][0], 1000 + w + 40 * 0.1) && near(pinned[2][0], 1000 - 40 * 0.1), "side=false pins the clean elbow and underline the same way");
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/morph.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/morph.test.ts
new file mode 100644
index 0000000..0df43cf
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/morph.test.ts
@@ -0,0 +1,96 @@
+// MORPH TESTS. resample, centreOf, handoff, coverShape, shapeGap and checkShapes in
+// src/canvas-core/morph.ts are pure and are held to numbers here. pathShape / fillShape get a
+// tiny recording ctx; nothing else draws. node tools/test.mjs
+import { blotShape, centreOf, checkShapes, circleShape, coverShape, fillShape, handoff, pathShape, rectShape, resample, shapeGap, type Shape } from "../src/canvas-core/morph";
+import type { Ctx, Env, P } from "../src/canvas-core/core";
+
+export const name = "morph";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
+ const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
+ const inside = (p: P, s: Shape) => { let c = false; for (let i = 0, j = s.length - 1; i < s.length; j = i++) { const a = s[i], b = s[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0]) c = !c; } return c; };
+ const area = (s: Shape) => s.reduce((a, p, i) => { const q = s[(i + 1) % s.length]; return a + p[0] * q[1] - q[0] * p[1]; }, 0) / 2;
+ const centred = (s: Shape, c: P): Shape => { const m = centreOf(s); return s.map(([x, y]): P => [x - m[0] + c[0], y - m[1] + c[1]]); };
+ const sq = rectShape(0, 0, 100, 50);
+
+ // 1. resample: exactly n points, clockwise on screen whatever the input winding, evenly
+ // spaced along the outline; degenerate shapes are refused
+ const r60 = resample(sq, 60);
+ ok(r60.length === 60 && resample(sq, 160).length === 160, "resample returns exactly n points");
+ ok(area(r60) > 0 && area(resample([...sq].reverse(), 60)) > 0, "resampled outlines run clockwise on screen, either input winding");
+ const circ = resample(circleShape([0, 0], 30, 72), 60), step = (2 * Math.PI * 30) / 60;
+ const gaps = circ.map((p, i) => Math.hypot(p[0] - circ[(i + 59) % 60][0], p[1] - circ[(i + 59) % 60][1]));
+ ok(gaps.every((g) => g > step * 0.98 && g <= step * 1.000001), `resample spaces points evenly along the outline (step ${step.toFixed(2)} px)`);
+ ok(JSON.stringify(resample(sq, 60)) === JSON.stringify(r60), "resample is deterministic");
+ ok(throws(() => resample([[0, 0], [1, 1]], 60)) && throws(() => resample([[5, 5], [5, 5], [5, 5]], 60)), "resample refuses fewer than 3 points or a zero-size shape");
+
+ // 2. the shape builders and centreOf
+ ok(circleShape([10, 20], 5).every((p) => near(Math.hypot(p[0] - 10, p[1] - 20), 5)), "circleShape's points sit on the circle");
+ ok(JSON.stringify(rectShape(0, 0, 100, 50)) === JSON.stringify([[100, 0], [100, 50], [0, 50], [0, 0]]), "a sharp rect is its four corners, clockwise");
+ const rr = rectShape(0, 0, 100, 50, 10, 4);
+ ok(rr.length === 20 && rr.every(([x, y]) => x >= -1e-9 && x <= 100 + 1e-9 && y >= -1e-9 && y <= 50 + 1e-9), "a rounded rect is perCorner points a corner, inside the box");
+ ok(blotShape([0, 0], 40, 7).every((p) => { const d = Math.hypot(p[0], p[1]); return d >= 40 * 0.9 - 1e-9 && d <= 40 * 1.12 + 1e-9; }), "blotShape's rim wobbles inside [0.9, 1.12] R");
+ ok(centreOf(sq)[0] === 50 && centreOf(sq)[1] === 25, "centreOf is the middle of the bounding box");
+ ok(centreOf([[0, 0], [10, 0], [0, 40]])[0] === 5 && centreOf([[0, 0], [10, 0], [0, 40]])[1] === 20, "centreOf uses the box, not the centroid");
+
+ // 3. handoff: exact at both ends, the centre rides the arc, stretch is zero at the ends
+ ok(throws(() => handoff({ from: circleShape([0, 0], 10), to: circleShape([100, 0], 10), t0: 50, t1: 50 })) && throws(() => handoff({ from: sq, to: sq, t0: 50, t1: 40 })), "t1 <= t0 throws");
+ const from = circleShape([820, 300], 16), to = rectShape(240, 420, 600, 380, 28);
+ const h = handoff({ from, to, t0: 45, t1: 80, arc: 90 });
+ ok(h.at(0) === from && h.at(45) === from && h.at(80) === to && h.at(200) === to, "handoff returns exactly the source until t0 and exactly the target from t1");
+ const ca = centreOf(resample(from, 160)), cb = centreOf(resample(to, 160));
+ ok(near(h.centre(45)[0], ca[0]) && near(h.centre(45)[1], ca[1]) && near(h.centre(80)[0], cb[0], 1e-6) && near(h.centre(80)[1], cb[1], 1e-6), "the centre starts and lands on the two shapes' centres");
+ const cm = h.centre(62.5); // u = 0.5 -> e = 0.5
+ ok(near(cm[0], (ca[0] + cb[0]) / 2, 1e-6) && near(cm[1], (ca[1] + cb[1]) / 2 - 90, 1e-6), "mid-flight the centre is the eased midpoint, lifted by the arc");
+ const long = handoff({ from, to, t0: 0, t1: 200, arc: 90 });
+ ok(shapeGap(long.at(1), centred(resample(from, 160), long.centre(1))) < 0.5, "just after t0 the outline is the un-stretched source at its centre");
+ ok(shapeGap(long.at(199), centred(resample(to, 160), long.centre(199))) < 0.5, "just before t1 the outline is the un-stretched target at its centre");
+ const spec = { from, to, t0: 45, t1: 80, arc: 90 };
+ ok(JSON.stringify(handoff(spec).at(60)) === JSON.stringify(h.at(60)), "a handoff is a pure function of its spec");
+
+ // 4. coverShape: a uniform scale about the frame's centre until every corner is inside
+ for (const s of [circleShape([820, 300], 16), sq, blotShape([500, 300], 40, 3)]) {
+ const cov = coverShape(s, 1920, 1080, 24), cs: P[] = [[-24, -24], [1944, -24], [1944, 1104], [-24, 1104]];
+ ok(cs.every((q) => inside(q, cov)), "coverShape puts every padded frame corner inside");
+ }
+ const wide = rectShape(300, 300, 100, 40), cov = coverShape(wide, 1920, 1080, 24);
+ const box = (s: Shape) => { const xs = s.map((p) => p[0]), ys = s.map((p) => p[1]); return [Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)]; };
+ const [w0, h0] = box(wide), [w1, h1] = box(cov);
+ ok(near(w1 / h1, w0 / h0), `coverShape keeps the shape's proportions (aspect ${(w1 / h1).toFixed(3)} = the source's)`);
+ ok(near(centreOf(cov)[0], 960, 1e-6) && near(centreOf(cov)[1], 540, 1e-6), "the shape's centre lands on the frame's centre");
+ // a shape whose bounding-box centre sits in its own hole can never cover the frame
+ const ring: Shape = [];
+ for (let i = 0; i <= 40; i++) { const a = -2.97 + (i * 5.94) / 40; ring.push([400 + Math.cos(a) * 60, 300 + Math.sin(a) * 60]); }
+ for (let i = 40; i >= 0; i--) { const a = -2.97 + (i * 5.94) / 40; ring.push([400 + Math.cos(a) * 40, 300 + Math.sin(a) * 40]); }
+ ok(!inside(centreOf(ring), ring), "the test ring's centre is in its hole");
+ ok(throws(() => coverShape(ring, 1920, 1080)), "coverShape throws when no scale can cover");
+
+ // 5. shapeGap and checkShapes: 0 for identical outlines, a real offset measured, tol enforced
+ const selfGap = shapeGap(sq, sq);
+ ok(selfGap < 1e-9, `a shape has zero gap to itself (${selfGap.toExponential(1)} of resample noise)`);
+ const c0 = circleShape([0, 0], 30), drift: Shape = c0.map(([x, y]): P => [x + 10, y]);
+ const g = shapeGap(c0, drift);
+ ok(Math.abs(g - 10) <= 0.5, `a 10 px offset is measured as ${g.toFixed(2)} px`);
+ ok(near(shapeGap(drift, c0), g), "shapeGap is symmetric");
+ ok(near(checkShapes(sq, sq), selfGap) && !throws(() => checkShapes(sq, sq, "self")), "checkShapes passes on a matching outline");
+ ok(throws(() => checkShapes(c0, drift, "probe", 2)), "checkShapes throws past tol");
+ ok(near(checkShapes(c0, drift, "probe", 20), g), "checkShapes returns the measured gap inside tol");
+
+ // 6. pathShape / fillShape on a recording ctx
+ const calls: string[] = [];
+ const fx = { beginPath() { calls.push("begin"); }, moveTo() { calls.push("m"); }, lineTo() { calls.push("l"); }, closePath() { calls.push("close"); }, setTransform(...a: number[]) { calls.push(`t${a.join("/")}`); }, fill() { calls.push("fill"); }, fillStyle: "", globalAlpha: 0 };
+ pathShape(fx as unknown as Ctx, sq);
+ ok(calls.join(",") === "begin,m,l,l,l,close", "pathShape traces the outline and closes it");
+ calls.length = 0;
+ fillShape(fx as unknown as Ctx, { scale: 2 } as unknown as Env, sq, "#123456");
+ ok(calls.includes("fill") && fx.fillStyle === "#123456" && calls.includes("t2/0/0/2/0/0"), "fillShape fills the outline in the film's scale");
+
+ // 7. the checks refuse bad input: NaN in a shape, a turn that ends where it starts, a NaN
+ // landing frame; a points: 2 ask still gets a usable outline (the floor is 8)
+ const nanShape: Shape = [[NaN, 0], [0, 10], [10, 0]];
+ ok(throws(() => checkShapes(nanShape, sq, "nan-out")) && throws(() => checkShapes(sq, nanShape, "nan-into")), "checkShapes throws when a shape contains NaN");
+ ok(throws(() => handoff({ from, to, t0: 45, t1: 80, turn: [0.5, 0.5] })) && throws(() => handoff({ from, to, t0: 45, t1: 80, turn: [1, 0.2] })), "a turn that does not end after it starts throws");
+ ok(throws(() => handoff({ from, to, t0: 45, t1: NaN })) && throws(() => handoff({ from, to, t0: NaN, t1: 80 })), "a NaN t0 or t1 throws");
+ const coarse = handoff({ from, to, t0: 45, t1: 80, points: 2 }).at(60);
+ ok(coarse.length === 8 && coarse.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y)), "points: 2 still yields a valid outline (8 finite points)");
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/sfxFrozenPlans.ts b/plugins/anidoodle/skills/anidoodle/engine/test/sfxFrozenPlans.ts
new file mode 100644
index 0000000..552b9d1
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/sfxFrozenPlans.ts
@@ -0,0 +1,26 @@
+// Launch-template cue sequences (launchTemplate.ts): typing, Generate/drop/card, reveal.
+import { launchLofi3 } from "../src/canvas-core/music/index";
+import { renderPiece } from "../src/canvas-core/music/render";
+import type { SfxPlan } from "../src/canvas-core/music/sfxMix";
+export const frozenPlans = (sr: number) => {
+ const piece = launchLofi3(), r = renderPiece(piece, sr), music: [Float32Array, Float32Array] = [r.L, r.R];
+ const base = { fps: 30, frames: 240, seed: 7, score: { piece } };
+ const plans: SfxPlan[] = [
+ { ...base, cues: [
+ { frame: 12, kind: "tick", variant: "key", gainDb: 1.5, label: 'key "m"' },
+ { frame: 16, kind: "tick", variant: "key" }, { frame: 19, kind: "tick", variant: "space" },
+ { frame: 24, kind: "tick", variant: "key" }, { frame: 28, kind: "tick", variant: "key" },
+ ] },
+ { ...base, cues: [
+ { frame: 30, kind: "press", variant: "thock", label: "Generate" },
+ { frame: 37, kind: "ink", variant: "plip", label: "the drop lifts" },
+ { frame: 48, kind: "ink", variant: "bloom", label: "it blooms into the card" },
+ { frame: 54, kind: "pop", variant: "cork", label: "the card lands (spring)" },
+ ] },
+ { ...base, cues: [
+ { frame: 120, kind: "riser", variant: "soft", beats: 4, label: "into the reveal" },
+ { frame: 120, kind: "impact", variant: "bloom", label: "the reveal" },
+ ] },
+ ];
+ return { plans, music };
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.ts
new file mode 100644
index 0000000..624cfb8
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.ts
@@ -0,0 +1,68 @@
+import { mixSfx, filmSfx, sfxHarshness, type PlacedCue, type SfxPlan, type SfxHarshOptions } from "../src/canvas-core/music/sfxMix";
+import { frozenPlans } from "./sfxFrozenPlans";
+import { survey } from "./sfxKitSurvey";
+const cryptoModule = "node:crypto", { createHash } = await import(cryptoModule);
+const hash = (L: Float32Array, R: Float32Array) => createHash("sha256").update(new Uint8Array(L.buffer)).update(new Uint8Array(R.buffer)).digest("hex");
+export const name = "sfx harshness";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const sr = 48000, n = sr * 2;
+ const music: [Float32Array, Float32Array] = [Float32Array.from({ length: n }, (_, i) => 0.04 * Math.sin(2 * Math.PI * 220 * i / sr) + 0.006 * Math.sin(2 * Math.PI * 4000 * i / sr)), new Float32Array(n)];
+ music[1].set(music[0]);
+ const synth = (f: number): PlacedCue => {
+ const L = Float32Array.from({ length: sr / 4 }, (_, i) => i < sr * 0.02 ? 0.5 * Math.sin(2 * Math.PI * f * i / sr) : 0), R = L.slice();
+ return { i: 0, cue: { frame: 15, kind: "tick", label: `${f} Hz` }, sound: { L, R, sr, kind: "tick", variant: "ui", seed: 1, hit: 0, window: [0, sr * 0.02], lufs: 0 }, hitS: 0.5, snappedFromS: 0.5, start: sr / 2, window: [sr / 2, sr * 0.52] };
+ };
+ const piercing = synth(4000), dull = synth(100), before = hash(piercing.sound.L, piercing.sound.R);
+ const high = sfxHarshness([piercing], music, sr, {})[0], low = sfxHarshness([dull], music, sr, {})[0];
+ ok(!high.ok && high.violations?.some((v) => v.metric === "liftDb"), "a loud 4 kHz burst exceeds the default lift cap");
+ ok(low.ok && Math.abs(low.cueRmsDb - high.cueRmsDb) < 1e-6, "a 100 Hz thump at the same RMS passes");
+ ok(high.peakDb > high.bodyDb + 10 && high.crestDb === high.peakDb - high.bodyDb, "a short peak with little following body has a large peak-body gap");
+ ok(hash(piercing.sound.L, piercing.sound.R) === before, "measurement never changes the cue samples");
+ const silence: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)], silent = sfxHarshness([piercing], silence, sr, {})[0];
+ ok(silent.liftDb === null && silent.peakMarginDb === null && silent.violations.every((v) => v.metric !== "liftDb"), "silence-relative fields are null and lift is skipped");
+ const click = synth(4000); click.sound.L.fill(0); click.sound.R.fill(0); click.sound.L[0] = click.sound.R[0] = 0.5;
+ const impulse = sfxHarshness([click], silence, sr, {})[0];
+ ok(impulse.bodyDb === -200 && impulse.peakAtS === 0.5 && Math.abs(impulse.peakDb + 6.020599913) < 1e-8, "body starts after the first peak: a single sample has no body");
+ const tail = synth(4000); tail.sound.L.fill(0); tail.sound.R.fill(0); tail.sound.L[0] = tail.sound.R[0] = 0.5;
+ tail.sound.L.fill(0.1, 1, 1 + sr * 0.15); tail.sound.R.set(tail.sound.L);
+ const body = sfxHarshness([tail], silence, sr, {})[0];
+ ok(Math.abs(body.bodyDb + 20) < 1e-6, "the 150 ms body uses stereo mean-power RMS without a +3 dB boost");
+ const plan: SfxPlan = { fps: 30, frames: 60, cues: [{ frame: 15, kind: "tick", variant: "ui", label: "piercing key" }] };
+ const report = mixSfx(music, plan, sr), cap = report.harshness[0].peakDb - 3, options: SfxHarshOptions = { maxPeakDb: cap, maxTiltDb: 0, maxLiftDb: 100 };
+ const explicit = mixSfx(music, { ...plan, harsh: { ...options, mode: "report" } }, sr);
+ ok(hash(report.L, report.R) === hash(explicit.L, explicit.R) && explicit.ok && !explicit.harshness[0].ok, "report flags a peak breach and keeps samples and audibility verdict unchanged");
+ let message = "";
+ try { mixSfx(music, { ...plan, harsh: { ...options, mode: "throw" } }, sr); } catch (e) { message = (e as Error).message; }
+ ok(/piercing key/.test(message) && /peakDb/.test(message) && /cap/.test(message), `throw names the cue, metric, measured value and cap: ${message.replace(/\n/g, " ")}`);
+ const tame = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame" } }, sr), tameAgain = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame" } }, sr);
+ ok(tame.harshness[0].ok && tame.harshness[0].peakDb <= cap && tame.ok && tame.harshness[0].reductionDb >= 3, "tame lowers the peak under the cap and keeps the cue audible");
+ ok(hash(tame.L, tame.R) === hash(tameAgain.L, tameAgain.R) && plan.cues[0].gainDb === undefined, "tame is deterministic and leaves the caller's plan alone");
+ const liftCap = report.harshness[0].liftDb! - 2, lifted = mixSfx(music, { ...plan, harsh: { mode: "tame", maxLiftDb: liftCap, maxTiltDb: 0 } }, sr);
+ ok(lifted.harshness[0].ok && lifted.harshness[0].liftDb! <= liftCap && lifted.ok, "tame lowers a lift breach under the cap while audible");
+ const conflict = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame", maxPeakDb: cap - 60 } }, sr);
+ ok(!conflict.harshness[0].ok && conflict.harshness[0].conflict === "audibility floor" && conflict.ok && conflict.audibility[0].marginDb >= conflict.audibility[0].minDb, "an impossible cap reports an audibility conflict and stays audible");
+ const tiltCap = report.harshness[0].tiltDb - 1, tilt = mixSfx(music, { ...plan, harsh: { mode: "tame", maxTiltDb: tiltCap, maxPeakDb: cap } }, sr);
+ ok(hash(tilt.L, tilt.R) === hash(report.L, report.R) && tilt.harshness[0].conflict === "tilt cannot be fixed by gain" && tilt.harshness[0].reductionDb === 0, "a tilt breach leaves the cue unchanged and explains that gain cannot fix it");
+ message = ""; try { mixSfx(null, { ...plan, harsh: { mode: "throw", maxTiltDb: tiltCap } }, sr); } catch (e) { message = (e as Error).message; }
+ ok(/tiltDb/.test(message) && /piercing key/.test(message), "throw still rejects a tilt breach over silence");
+ const override = mixSfx(music, { ...plan, harsh: { ...options, mode: "throw" }, cues: [{ ...plan.cues[0], harsh: { maxPeakDb: 0 } }] }, sr);
+ ok(override.harshness[0].ok, "a per-cue cap overrides the plan cap");
+ const floor = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame", maxPeakDb: cap - 60 }, cues: [{ ...plan.cues[0], minDb: 0 }] }, sr);
+ ok(floor.ok && floor.audibility[0].marginDb >= 0, "tame respects the per-cue audibility floor");
+ const buriedPlan: SfxPlan = { ...plan, cues: [{ ...plan.cues[0], gainDb: -40 }], harsh: { mode: "tame", maxPeakDb: -100 } }, buried = mixSfx(music, buriedPlan, sr);
+ ok(!buried.ok && buried.harshness[0].conflict === "audibility floor" && buried.harshness[0].reductionDb === 0, "tame never lowers an already buried cue");
+ const overSilence = mixSfx(null, { ...plan, harsh: { ...options, mode: "tame" } }, sr);
+ ok(overSilence.ok && overSilence.harshness[0].ok && overSilence.harshness[0].liftDb === null, "over silence, tame still enforces the absolute peak cap");
+ for (const harsh of [{ mode: "unknown" }, { maxLiftDb: NaN }, { maxTiltDb: Infinity }, { maxPeakDb: "hot" }]) {
+ message = ""; try { mixSfx(null, { ...plan, harsh: harsh as SfxHarshOptions }, sr); } catch (e) { message = (e as Error).message; }
+ ok(/harsh\./.test(message), `invalid harsh option rejected: ${JSON.stringify(harsh)}`);
+ }
+ // Captured from production sources at c1beddfe4264a34d12531dbe931acef611fb0a02,
+ // loaded by git show and bundled with these fixtures before the mixer was edited.
+ const hashes = ["5db7c646b1e61b0016c5dd8a114e875f6cedbaed17f6b702a225ba2dcc187a85", "3064c924f76acb857c509a5c294cf043380451d544fda0b5372ce06d33ef133a", "3a42c3f453a9a1a0285bd2287bc9874e6e330fc3bd6baa263587e10443eaa94e"];
+ const frozen = frozenPlans(sr);
+ frozen.plans.forEach((p, i) => { const m = mixSfx(frozen.music, p, sr), f = filmSfx(() => frozen.music, p)(sr);
+ ok(hash(m.L, m.R) === hashes[i] && hash(...f) === hashes[i], `launch cue plan ${i}: mixSfx and filmSfx match base SHA-256 ${hashes[i]}`);
+ });
+ for (const row of survey()) ok(row.ok, `${row.kind}:${row.variant} over ${row.context}: default gain passes the measured default caps`);
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/sfxKitSurvey.ts b/plugins/anidoodle/skills/anidoodle/engine/test/sfxKitSurvey.ts
new file mode 100644
index 0000000..af4fe38
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/sfxKitSurvey.ts
@@ -0,0 +1,14 @@
+// Fixed calibration context: default gain, C major / 90 bpm, seed 1, 48 kHz.
+// A steady -22.36 dBFS score (220 Hz + 440 Hz + a quiet 4 kHz partial), no modulation.
+import { SFX_KINDS, sfxVariants, renderSfx } from "../src/canvas-core/music/sfxKit";
+import { sfxDuck, sfxHarshness, type PlacedCue } from "../src/canvas-core/music/sfxMix";
+export const survey = () => {
+ const sr = 48000, n = sr * 12, L = Float32Array.from({ length: n }, (_, i) => 0.1 * Math.sin(2 * Math.PI * 220 * i / sr) + 0.035 * Math.sin(2 * Math.PI * 440 * i / sr) + 0.02 * Math.sin(2 * Math.PI * 4000 * i / sr));
+ const silence: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)];
+ return SFX_KINDS.flatMap((kind) => sfxVariants(kind).flatMap((variant) => {
+ const sound = renderSfx(kind, { variant, key: "C", bpm: 90 }, sr), start = 4 * sr - sound.hit;
+ const pc: PlacedCue = { i: 0, cue: { kind, variant, frame: 120 }, sound, hitS: 4, snappedFromS: 4, start, window: [start + sound.window[0], start + sound.window[1]] };
+ const duck = sfxDuck([pc], n, sr), bed = Float32Array.from(L, (x, i) => x * duck[i]);
+ return ([["silence", silence], ["score", [bed, bed]]] as [string, [Float32Array, Float32Array]][]).map(([context, music]) => ({ context, ...sfxHarshness([pc], music, sr, {})[0] }));
+ }));
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/transitions.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/transitions.test.ts
new file mode 100644
index 0000000..d081895
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/test/transitions.test.ts
@@ -0,0 +1,98 @@
+// TRANSITION TESTS. The seam math in src/canvas-core/transitions.ts is pure (wipeFront,
+// irisRadius, flashAlpha, checkFlashes, seam), so it is held to numbers here with no browser.
+// brushWipe / iris / flashCut draw through layers and are not covered; flash gets a tiny
+// recording ctx. node tools/test.mjs
+import { checkFlashes, flash, flashAlpha, irisRadius, irisRim, seam, wipeFront } from "../src/canvas-core/transitions";
+import { blot } from "../src/canvas-core/launchKit";
+import type { Ctx, Env, P } from "../src/canvas-core/core";
+
+export const name = "transitions";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
+ const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
+ // the same point-in-polygon ray cast morph.ts uses (it is private there)
+ const inside = (p: P, s: P[]) => { let c = false; for (let i = 0, j = s.length - 1; i < s.length; j = i++) { const a = s[i], b = s[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0]) c = !c; } return c; };
+ const W = 1920, H = 1080, corners: P[] = [[0, 0], [W, 0], [W, H], [0, H]];
+
+ // 1. seam: a clamped ramp over [at, at + len]
+ ok(seam(100, 120, 22) === 0 && seam(119.9, 120, 22) === 0, "seam is 0 before its window");
+ ok(seam(131, 120, 22) === 0.5 && seam(142, 120, 22) === 1 && seam(500, 120, 22) === 1, "seam is 0.5 mid-window and 1 from at+len on");
+
+ // 2. wipeFront: at p = 0 nothing of the frame is inside the picture polygon, at p = 1 all
+ // four corners are - for a straight, a diagonal, a vertical and a backwards stroke
+ const mid: P[] = [[W / 2, H / 2], [W * 0.25, H * 0.75], [W * 0.8, H * 0.2]];
+ for (const angle of [0, 0.22, Math.PI / 2, Math.PI]) for (const ink of [undefined, "#1d1a16"] as (string | undefined)[]) {
+ const o = { angle, ink, seed: 11 };
+ ok([...corners, ...mid].every((c) => !inside(c, wipeFront(0, W, H, o))), `wipeFront p=0 angle ${angle.toFixed(2)} ink ${!!ink}: nothing of the frame is inside`);
+ ok(corners.every((c) => inside(c, wipeFront(1, W, H, o))), `wipeFront p=1 angle ${angle.toFixed(2)} ink ${!!ink}: all four corners are inside`);
+ }
+
+ // 3. the ink edge never trails the picture edge: a point inside the picture polygon is
+ // inside the ink polygon too, at any progress and any angle
+ for (const angle of [0, 0.22, Math.PI / 2, Math.PI]) for (const p of [0.15, 0.5, 0.85]) {
+ const pic = wipeFront(p, W, H, { angle, ink: "#1d1a16", seed: 5 }), inked = wipeFront(p, W, H, { angle, ink: "#1d1a16", seed: 5 }, "ink");
+ let lead = true;
+ for (let y = 0; y <= 20 && lead; y++) for (let x = 0; x <= 36 && lead; x++) { const q: P = [(x * W) / 36, (y * H) / 20]; if (inside(q, pic) && !inside(q, inked)) lead = false; }
+ ok(lead, `wipeFront angle ${angle.toFixed(2)} p ${p}: the ink edge is ahead of or equal to the picture edge`);
+ }
+
+ // 4. the stroke is a pure function of its arguments: same seed, same points
+ const w1 = wipeFront(0.5, W, H, { angle: 0.3, seed: 7 });
+ ok(JSON.stringify(w1) === JSON.stringify(wipeFront(0.5, W, H, { angle: 0.3, seed: 7 })), "wipeFront: same seed gives identical points");
+ ok(JSON.stringify(w1) !== JSON.stringify(wipeFront(0.5, W, H, { angle: 0.3, seed: 8 })), "wipeFront: a different seed is a different brush");
+
+ // 5. irisRadius: 0 at p = 0, past the farthest corner at p = 1 even off-centre, reversed
+ // with close; a blot's wobbling rim needs more radius than a clean circle
+ ok(irisRadius(0, W, H) === 0, "irisRadius is 0 at p = 0");
+ const c: P = [120, 90], far = Math.max(...corners.map(([x, y]) => Math.hypot(x - c[0], y - c[1])));
+ ok(irisRadius(1, W, H, { center: c }) >= far, `irisRadius at p = 1 covers the farthest corner (${far.toFixed(0)} px from an off-centre centre)`);
+ ok(irisRadius(0, W, H, { center: c, close: true }) >= far && near(irisRadius(1, W, H, { close: true }), 0), "close: full radius at p = 0, 0 at p = 1");
+ const rb = irisRadius(1, W, H, { shape: "blot", center: [300, 200] }), rc = irisRadius(1, W, H, { center: [300, 200] });
+ ok(rb > rc, `a blot needs more radius than a circle (${rb.toFixed(0)} > ${rc.toFixed(0)})`);
+ ok([1, 42, 99].every((seed) => corners.every((q) => inside(q, blot([300, 200], rb, seed)))), "the blot's deepest rim dip still covers every corner at p = 1");
+
+ // 6. flashAlpha: peak on the cut frame, 0 outside [cut - inF, cut + outF), and the legal
+ // minimum still lights four frames - a one-frame flash cannot be built
+ ok(near(flashAlpha(100, 100), 0.86), "flashAlpha peaks on the cut frame");
+ const lit = Array.from({ length: 30 }, (_, i) => i + 90).filter((f) => flashAlpha(f, 100) > 0);
+ ok(lit.length === 11 && lit[0] === 98 && lit[10] === 108, `flashAlpha is > 0 on exactly the inF + outF frames around the cut (${lit.length})`);
+ ok(flashAlpha(97, 100) === 0 && flashAlpha(109, 100) === 0, "flashAlpha is 0 outside its window");
+ ok(flashAlpha(98, 100) < flashAlpha(99, 100) && flashAlpha(99, 100) < flashAlpha(100, 100), "the light rises into the cut");
+ ok(Array.from({ length: 10 }, (_, i) => i + 95).filter((f) => flashAlpha(f, 100, { inF: 1, outF: 3 }) > 0).length === 4, "the tightest legal flash lights 4 frames: never a one-frame flash");
+ ok(throws(() => flashAlpha(50, 100, { outF: 2 })) && throws(() => flashAlpha(50, 100, { inF: 0 })), "flashAlpha throws for outF < 3 or inF < 1");
+
+ // 7. checkFlashes: one rule - any two flashes closer than half a second throw; the
+ // boundary is strict, and however many flashes there are, only the nearest pair matters
+ ok(throws(() => checkFlashes([0, 14], 30)), "two flashes 0.47 s apart throw");
+ ok(!throws(() => checkFlashes([0, 15], 30)), "two flashes exactly 0.5 s apart pass");
+ ok(!throws(() => checkFlashes([0, 15, 30, 45], 30)), "four flashes, all at least half a second apart, pass: the only rule is the pair rule");
+ ok(throws(() => checkFlashes([0, 29, 14], 30)), "a close pair throws however the cuts were listed");
+ const cuts = [400, 240];
+ ok(checkFlashes(cuts, 30) === cuts, "checkFlashes sorts a copy and returns the argument");
+
+ // 8. flash() on a recording ctx: one full-frame fill at the computed alpha
+ let seen: { a: number; r: number[] } | undefined;
+ const rec = { setTransform() {}, globalCompositeOperation: "", globalAlpha: 0, fillStyle: "", fillRect: (...r: number[]) => { seen = { a: rec.globalAlpha, r }; } };
+ flash(rec as unknown as Ctx, { W, H, scale: 2 } as unknown as Env, 100, 100);
+ ok(near(seen?.a ?? -1, 0.86) && JSON.stringify(seen?.r) === JSON.stringify([0, 0, W, H]), "flash paints the whole frame at the computed alpha");
+
+ // 9. seam with len 0 is a hard cut that still answers 0 or 1, never NaN
+ ok(seam(119.9, 120, 0) === 0 && seam(120, 120, 0) === 1 && seam(500, 120, 0) === 1, "seam(local, at, 0): 0 before at, 1 from at");
+ ok(seam(119.9, 120, -3) === 0 && seam(120, 120, -3) === 1, "a negative len behaves the same");
+ ok([seam(NaN, 120, 0), seam(-1e9, 120, 0), seam(1e9, 120, 0)].every((v) => v === 0 || v === 1), "seam is never NaN");
+
+ // 10. irisRim: 0 at R = 0, grows without a step bigger than rim/20 per px, full width by
+ // R = 70 - so the ink rim never appears or vanishes in one frame
+ for (const [o, rim] of [[{ shape: "blot" }, 22], [{ rim: 10 }, 10]] as const) {
+ ok(irisRim(0, o) === 0 && irisRim(70, o) === rim && irisRim(200, o) === rim, `irisRim (rim ${rim}): 0 at R = 0, full ${rim} px from R = 70`);
+ let prev = 0, stepOk = true;
+ for (let R = 0.5; R <= 100; R += 0.5) { const v = irisRim(R, o); if (v - prev > rim / 20 + 1e-12 || v < prev - 1e-12) stepOk = false; prev = v; }
+ ok(stepOk, `irisRim (rim ${rim}) grows continuously, no step over ${(rim / 20).toFixed(2)} px`);
+ }
+ ok(irisRim(50, {}) === 0 && irisRim(50, { shape: "circle" }) === 0, "a clean circle has no rim");
+
+ // 11. wipeFront stays finite on degenerate input: no bristles, an ease that overshoots
+ const finite = (s: P[]) => s.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y));
+ ok(finite(wipeFront(0.5, W, H, { bristles: 0 })), "wipeFront with bristles: 0 still gives finite points");
+ ok(finite(wipeFront(0.5, W, H, { ease: () => 1.7 })) && finite(wipeFront(0.5, W, H, { ease: () => -0.4 })), "wipeFront with an ease returning 1.7 or -0.4 still gives finite points");
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/motion.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/motion.mjs
index 873453a..7b4b7e5 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/motion.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/motion.mjs
@@ -22,3 +22,32 @@ export const changedArea = async (file, width, height, threshold = 4, stride = 1
if (pending.length) throw new Error(`incomplete decoded frame: ${pending.length} bytes`);
return changed;
};
+
+// The frames themselves, one at a time, same small grey decode as changedArea: a Buffer of
+// width*height luma bytes per frame. Tools that need pixel neighbourhoods (popscan's triple
+// diff) rather than a pairwise summary consume this stream. `frames` caps the decode; a
+// consumer that stops early kills the encoder instead of buffering the rest of the film.
+export const greyFrames = async function* (file, width, height, frames = Infinity) {
+ const px = width * height;
+ const args = ["-v", "error", "-i", file, "-vf", `scale=${width}:${height}`];
+ if (Number.isFinite(frames)) args.push("-frames:v", String(frames));
+ args.push("-pix_fmt", "gray", "-f", "rawvideo", "-");
+ const ff = spawn("ffmpeg", args);
+ let pending = Buffer.alloc(0), error = "";
+ ff.stderr.on("data", (chunk) => { error += chunk.toString(); });
+ const closed = new Promise((resolve, reject) => { ff.on("error", reject); ff.on("close", (code) => code ? reject(new Error(error || `ffmpeg exited ${code}`)) : resolve()); });
+ closed.catch(() => {}); // a consumer that breaks early leaves ffmpeg to the kill below, not an unhandled rejection
+ try {
+ for await (const chunk of ff.stdout) {
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
+ while (pending.length >= px) {
+ yield Buffer.from(pending.subarray(0, px));
+ pending = pending.subarray(px);
+ }
+ }
+ await closed;
+ if (pending.length) throw new Error(`incomplete decoded frame: ${pending.length} bytes`);
+ } finally {
+ if (ff.exitCode === null) ff.kill("SIGKILL");
+ }
+};
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/popscan-unit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/popscan-unit.mjs
new file mode 100644
index 0000000..b14f38a
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/popscan-unit.mjs
@@ -0,0 +1,200 @@
+#!/usr/bin/env node
+// Unit + end-to-end tests for tools/popscan.mjs. The detector (scanPops) is pure, so the unit
+// half feeds it synthetic greyscale frames - no video needed. The e2e half builds two tiny
+// MP4s with ffmpeg lavfi (no assets) under a temp dir inside out/: one with a known one-frame
+// pop at a known frame and place, one clean clip holding a hard cut and continuous motion.
+// popscan must report exactly the known pop and nothing else. Temp dir removed afterwards.
+// Boundary rule under test: the first and last frames can never be pops - a pop needs a
+// neighbour on both sides.
+// node tools/popscan-unit.mjs
+import { execFileSync } from "node:child_process";
+import { strict as assert } from "node:assert";
+import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { scanPops } from "./popscan.mjs";
+
+const TOOLS = import.meta.dirname;
+const ENGINE = resolve(TOOLS, "..");
+const root = join(ENGINE, "out", ".popscan-unit");
+rmSync(root, { recursive: true, force: true });
+mkdirSync(root, { recursive: true });
+let pass = 0;
+const ok = (name) => console.log(`PASS ${++pass} ${name}`);
+
+// ---------------------------------------------------------------- synthetic frames: 48x48, grid 4 -> 12px tiles
+const W = 48, H = 48;
+const OPTS = { width: W, height: H, grid: 4, min: 0.01, ratio: 0.35, thresh: 4 }; // min is a fraction here (1% of a tile)
+const flat = (v = 30) => new Uint8Array(W * H).fill(v);
+const rect = (f, x0, y0, x1, y1, v) => { for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) f[y * W + x] = v; return f; };
+const tex = (seed) => { const f = flat(30); let s = seed; for (let y = 14; y < 24; y++) for (let x = 14; x < 24; x++) { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; f[y * W + x] = 40 + (s >>> 0) % 180; } return f; };
+
+// a one-frame APPEAR: a bright block exists on frame 2 only (inside tile (1,1): x12-23, y12-23)
+{
+ const fs = [flat(), flat(), rect(flat(), 14, 14, 24, 24, 220), flat(), flat()];
+ const r = await scanPops(fs, OPTS);
+ assert.equal(r.length, 1, "one finding");
+ assert.equal(r[0].frame, 2);
+ assert.deepEqual(r[0].box.map((v) => +v.toFixed(4)), [0.25, 0.25, 0.5, 0.5], "box is tile (1,1)");
+ assert.equal(r[0].kind, "appears");
+}
+ok("one-frame appear: found at frame 2 with the tile's box, kind appears");
+
+// a one-frame VANISH: the block exists on every frame except 2
+{
+ const block = () => rect(flat(), 14, 14, 24, 24, 220);
+ const r = await scanPops([block(), block(), flat(), block(), block()], OPTS);
+ assert.equal(r.length, 1);
+ assert.equal(r[0].frame, 2);
+ assert.equal(r[0].kind, "vanishes");
+}
+ok("one-frame vanish: found at frame 2, kind vanishes");
+
+// a JUMP: same texture, shifted inside the region for one frame (texture kept -> not appears/vanishes)
+{
+ const base = () => tex(7);
+ const jumped = () => { const f = flat(), t = tex(7); for (let y = 14; y < 24; y++) for (let x = 14; x < 24; x++) f[y * W + x + 3] = t[y * W + x]; return f; };
+ const r = await scanPops([base(), base(), jumped(), base(), base()], OPTS);
+ assert.equal(r.length, 1);
+ assert.equal(r[0].kind, "jumps");
+}
+ok("one-frame rearrange: found, kind jumps (texture preserved)");
+
+// a HARD CUT is not a pop: after the cut, f and f+1 agree
+{
+ const r = await scanPops([flat(30), flat(30), flat(200), flat(200), flat(200)], OPTS);
+ assert.equal(r.length, 0, "hard cut produces no finding");
+}
+ok("hard cut: no finding");
+
+// FAST CONTINUOUS MOTION is not a pop: f-1 and f+1 differ too
+{
+ const moved = (x) => rect(flat(), x, 14, x + 10, 24, 220);
+ const r = await scanPops([moved(2), moved(6), moved(10), moved(14), moved(18)], OPTS);
+ assert.equal(r.length, 0, "a sliding block never pops");
+}
+ok("smooth fast motion: no finding");
+
+// a SMALL POP in one tile of an otherwise moving frame: the busy top row moves every frame
+// (whole-frame change is high everywhere it matters), the quiet tile still gets caught
+{
+ const busy = (x, pop) => { const f = flat(24); rect(f, x, 2, x + 12, 8, 200); if (pop) rect(f, 38, 26, 46, 34, 210); return f; };
+ const fs = [busy(2), busy(5), busy(8, true), busy(11), busy(14)];
+ const r = await scanPops(fs, OPTS);
+ assert.equal(r.length, 1, "only the quiet-tile pop is found");
+ assert.equal(r[0].frame, 2);
+ assert.deepEqual(r[0].box.map((v) => +v.toFixed(4)), [0.75, 0.5, 1, 0.75], "box is tile (3,2) only");
+}
+ok("small pop in a busy frame: found, box is the one tile");
+
+// TWO POPS on different frames -> two findings
+{
+ const fs = [flat(), flat(), rect(flat(), 2, 2, 10, 10, 220), flat(), flat(), rect(flat(), 40, 40, 47, 47, 220), flat()];
+ const r = await scanPops(fs, OPTS);
+ assert.equal(r.length, 2);
+ assert.deepEqual(r.map((x) => x.frame), [2, 5]);
+}
+ok("two pops on different frames: two findings");
+
+// BOUNDARY: a pop on the first or last frame is never reported - both neighbours are required
+{
+ const first = await scanPops([rect(flat(), 14, 14, 24, 24, 220), flat(), flat(), flat(), flat()], OPTS);
+ const last = await scanPops([flat(), flat(), flat(), flat(), rect(flat(), 14, 14, 24, 24, 220)], OPTS);
+ assert.equal(first.length, 0, "frame 0 has no f-1, cannot pop");
+ assert.equal(last.length, 0, "last frame has no f+1, cannot pop");
+}
+ok("first/last frame can never be a pop");
+
+// ADJACENT popping tiles merge into ONE finding; DISJOINT regions are two findings
+{
+ const merged = await scanPops([flat(), flat(), rect(flat(), 18, 14, 30, 24, 220), flat(), flat()], OPTS);
+ assert.equal(merged.length, 1, "a block spanning tiles (1,1)+(2,1) is one finding");
+ assert.deepEqual(merged[0].box.map((v) => +v.toFixed(4)), [0.25, 0.25, 0.75, 0.5], "merged box covers both tiles");
+ assert.equal(merged[0].tiles, 2);
+ const two = await scanPops([flat(), flat(), rect(rect(flat(), 2, 2, 10, 10, 220), 40, 40, 47, 47, 220), flat(), flat()], OPTS);
+ assert.equal(two.length, 2, "two separated pops on one frame are two findings");
+}
+ok("adjacent tiles merge to one finding; disjoint regions stay separate");
+
+// --min gates: a 2x2 px blip under the floor is not a pop; --from/--to bound eligibility
+{
+ const fs = [flat(), flat(), rect(flat(), 14, 14, 16, 16, 220), flat(), flat()];
+ assert.equal((await scanPops(fs, { ...OPTS, min: 0.05 })).length, 0, "blip under --min is ignored");
+ const pop = [flat(), flat(), rect(flat(), 14, 14, 24, 24, 220), flat(), flat()];
+ assert.equal((await scanPops(pop, { ...OPTS, to: 1 })).length, 0, "--to 1 excludes frame 2");
+ assert.equal((await scanPops(pop, { ...OPTS, from: 3 })).length, 0, "--from 3 excludes frame 2");
+ assert.equal((await scanPops(pop, { ...OPTS, from: 2, to: 2 })).length, 1, "--from 2 --to 2 keeps it");
+}
+ok("--min floor and --from/--to bounds respected");
+
+// ---------------------------------------------------------------- end to end, real MP4s via lavfi
+const popMp4 = join(root, "pop.mp4"), cleanMp4 = join(root, "clean.mp4");
+try {
+ // a 36x24 white box on frame 15 only: x60-96 of 160 (37.5-60%), y48-72 of 120 (40-60%)
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x202830:s=160x120:r=30:d=1,drawbox=x=60:y=48:w=36:h=24:c=0xf0f0f0:t=fill:enable='eq(n,15)'", "-pix_fmt", "yuv420p", popMp4]);
+ // two 30-frame halves, each with a box in continuous motion, concatenated -> a hard cut at 30
+ execFileSync("ffmpeg", ["-v", "error", "-y",
+ "-f", "lavfi", "-i", "color=c=0x182028:s=160x120:r=30:d=1",
+ "-f", "lavfi", "-i", "color=c=0xe8e8e8:s=20x20:r=30:d=1",
+ "-f", "lavfi", "-i", "color=c=0x3a2020:s=160x120:r=30:d=1",
+ "-f", "lavfi", "-i", "color=c=0x30c0b0:s=16x16:r=30:d=1",
+ "-filter_complex", "[0:v][1:v]overlay=x='4+4*n':y=30[a];[2:v][3:v]overlay=x='140-4*n':y=70[b];[a][b]concat=n=2:v=1[out]",
+ "-map", "[out]", "-pix_fmt", "yuv420p", "-r", "30", cleanMp4]);
+ ok("lavfi fixtures built: pop.mp4 (pop at frame 15), clean.mp4 (cut + motion)");
+
+ const run = (args) => JSON.parse(execFileSync("node", [join(TOOLS, "popscan.mjs"), ...args, "--json"], { cwd: ENGINE, encoding: "utf8" }));
+ const pops = run([popMp4]);
+ assert.equal(pops.length, 1, `expected exactly one finding, got ${pops.length}`);
+ assert.equal(pops[0].frame, 15, "the known pop frame");
+ assert(pops[0].box[0] <= 48.75 && pops[0].box[2] >= 48.75 && pops[0].box[1] <= 50 && pops[0].box[3] >= 50, `box ${pops[0].box} contains the drawn box centre`);
+ assert.equal(pops[0].kind, "appears");
+ assert(pops[0].strip.includes("eq(n,15)") && pops[0].strip.includes("tile=5x1"), "review strip command embedded");
+ ok("e2e pop clip: exactly the known pop at frame 15, box covers it, strip command given");
+
+ const clean = run([cleanMp4]);
+ assert.equal(clean.length, 0, `the clean clip reports nothing, got ${JSON.stringify(clean)}`);
+ ok("e2e clean clip: hard cut and motion report zero findings");
+
+ try { execFileSync("node", [join(TOOLS, "popscan.mjs"), "definitely-not-a-film"], { cwd: ENGINE, encoding: "utf8" }); assert.fail("missing file must exit 2"); }
+ catch (e) { assert.equal(e.status, 2, "unreadable/missing file exits 2"); }
+ const okExit = execFileSync("node", [join(TOOLS, "popscan.mjs"), cleanMp4], { cwd: ENGINE, encoding: "utf8" });
+ assert(okExit.includes("POPSCAN: clean"), "a film never fails: clean scan exits 0 and says so");
+ ok("exit codes: 0 always after a scan, 2 for a file that cannot be read");
+
+ // the printed strip command is POSIX-paste-safe for any filename: the metacharacters below
+ // must arrive at ffmpeg as literal bytes, so an injected command never runs
+ {
+ const nasty = join(root, `pop 'q' $(touch INJECTED-A) \`touch INJECTED-B\` "dq".mp4`);
+ copyFileSync(popMp4, nasty);
+ const r = run([nasty]);
+ assert.equal(r.length, 1, "a shell-hostile name still scans");
+ const cmd = r[0].strip;
+ assert(cmd.includes("-fps_mode passthrough") && !cmd.includes("-vsync"), "the strip uses -fps_mode passthrough, not the deprecated -vsync");
+ assert(cmd.includes(`'\\''`), "a single quote in the name is '\\\\''-escaped");
+ const outDir = join(ENGINE, "out"), pngsBefore = readdirSync(outDir);
+ execFileSync("sh", ["-c", cmd], { cwd: ENGINE }); // really paste it: a quoting slip makes ffmpeg fail or runs the injection
+ assert(!existsSync(join(ENGINE, "INJECTED-A")) && !existsSync(join(ENGINE, "INJECTED-B")), "no injected command ran");
+ const png = readdirSync(outDir).filter((f) => f.startsWith("popscan-") && f.endsWith("-f15.png") && !pngsBefore.includes(f));
+ assert.equal(png.length, 1, `the strip rendered its review PNG (${png[0]})`);
+ rmSync(join(outDir, png[0]));
+ }
+ ok("strip command: paste-safe under shell metacharacters, -fps_mode passthrough, renders the PNG");
+
+ // a missing or failing ffprobe/ffmpeg is one clear line and exit 2, not a stack trace
+ {
+ const oneLine = (e) => { assert.equal(e.status, 2, "exit 2"); const err = (e.stderr || "").trim(); assert.equal(err.split("\n").length, 1, `one line on stderr, got: ${err.slice(0, 120)}`); assert(err.startsWith("popscan:"), `the line names the tool: ${err}`); };
+ writeFileSync(join(root, "not-video.mp4"), "this is not a video");
+ try { execFileSync("node", [join(TOOLS, "popscan.mjs"), join(root, "not-video.mp4")], { cwd: ENGINE, encoding: "utf8" }); assert.fail("a non-video must exit 2"); }
+ catch (e) { oneLine(e); }
+ try { execFileSync(process.execPath, [join(TOOLS, "popscan.mjs"), cleanMp4], { cwd: ENGINE, encoding: "utf8", env: { PATH: "/nonexistent-dir" } }); assert.fail("missing ffprobe must exit 2"); }
+ catch (e) { oneLine(e); }
+ const stub = join(root, "stub-bin"); mkdirSync(stub); // ffprobe answers, ffmpeg is gone
+ writeFileSync(join(stub, "ffprobe"), `#!/bin/sh\necho '{"streams":[{"width":160,"height":120,"avg_frame_rate":"30/1"}]}'\n`);
+ chmodSync(join(stub, "ffprobe"), 0o755);
+ try { execFileSync(process.execPath, [join(TOOLS, "popscan.mjs"), cleanMp4], { cwd: ENGINE, encoding: "utf8", env: { PATH: stub } }); assert.fail("missing ffmpeg must exit 2"); }
+ catch (e) { oneLine(e); }
+ }
+ ok("tool failures: unprobeable file, missing ffprobe, missing ffmpeg -> one clear line, exit 2");
+} finally {
+ rmSync(root, { recursive: true, force: true });
+}
+console.log(`\nPOPSCAN-UNIT: PASS ${pass} checks`);
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/popscan.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/popscan.mjs
new file mode 100644
index 0000000..529f704
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/popscan.mjs
@@ -0,0 +1,120 @@
+// node tools/popscan.mjs <film|path.mp4> [--from F] [--to T] [--grid 12] [--min 0.4] [--ratio 0.35] [--json]
+// POPSCAN. Finds the one-frame pop: a frame that differs from BOTH neighbours while the
+// neighbours agree with each other (a flashed element, a vanished element, a one-frame jump).
+// A hard cut is not a pop (after it, f and f+1 agree); fast continuous motion is not a pop
+// (f-1 and f+1 differ too); an intentional one-frame flash IS listed - a human reviews, the
+// tool never fails a film. The first and last frames cannot pop: a pop needs both neighbours.
+//
+// Measured per TILE, not per frame: a small pop inside a busy frame vanishes in a whole-frame
+// number. Decoded small and grey like deadair, split into a grid x grid of tiles, three
+// differences per tile: in = d(f-1,f), out = d(f,f+1), across = d(f-1,f+1). A tile pops when
+// in and out are both at least --min percent of the tile and across is at most --ratio of the
+// smaller of the two. Adjacent (diagonals count) popping tiles on one frame are ONE finding
+// with a bounding box. `kind` is a cheap guess from texture in the box: appears/vanishes
+// add/remove it, jumps rearrange it. --from/--to bound which frames may be findings; the
+// decode still runs from 0 so frame numbers stay absolute (a --to stops it early).
+import { execFileSync } from "node:child_process";
+import { existsSync, mkdirSync } from "node:fs";
+import { basename, resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { greyFrames } from "./motion.mjs";
+
+// The detector: pure, frames in -> findings out, no I/O. `frames` is any (sync or async)
+// iterable of width*height greyscale bytes. Findings: { frame, box [x0,y0,x1,y1] as frame
+// fractions, in, out, across as changed shares 0..1, tiles, kind }.
+export const scanPops = async (frames, { width: W, height: H, grid = 12, min = 0.004, ratio = 0.35, thresh = 4, from = 1, to = Infinity } = {}) => {
+ const g2 = grid * grid, px = W * H;
+ const tileOf = new Uint16Array(px), size = new Uint32Array(g2);
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { const t = Math.floor((y * grid) / H) * grid + Math.floor((x * grid) / W); tileOf[y * W + x] = t; size[t]++; }
+ const diff = (a, b) => { const c = new Uint32Array(g2); for (let i = 0; i < px; i++) if (Math.abs(a[i] - b[i]) > thresh) c[tileOf[i]]++; return Float64Array.from(c, (v, t) => v / size[t]); };
+ const std = (f, x0, y0, x1, y1) => { let s = 0, s2 = 0; for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const v = f[y * W + x]; s += v; s2 += v * v; } const n = (x1 - x0) * (y1 - y0), m = s / n; return Math.sqrt(Math.max(0, s2 / n - m * m)); };
+ const findings = [];
+ let index = -1, p2 = null, p1 = null, dIn = null;
+ for await (const cur of frames) {
+ index++;
+ if (p1 === null) { p1 = cur; continue; }
+ const dOut = diff(p1, cur), f = index - 1;
+ const dAcross = dIn && p2 && f >= from && f <= to ? diff(p2, cur) : null; // skip the third diff on ineligible frames
+ if (dAcross) {
+ const hit = new Uint8Array(g2);
+ for (let t = 0; t < g2; t++) if (dIn[t] >= min && dOut[t] >= min && dAcross[t] <= ratio * Math.min(dIn[t], dOut[t])) hit[t] = 1;
+ const seen = new Uint8Array(g2);
+ for (let t = 0; t < g2; t++) {
+ if (!hit[t] || seen[t]) continue;
+ const stack = [t], tiles = []; seen[t] = 1;
+ let tx0 = grid, ty0 = grid, tx1 = -1, ty1 = -1;
+ while (stack.length) {
+ const u = stack.pop(); tiles.push(u);
+ const uy = Math.floor(u / grid), ux = u % grid;
+ tx0 = Math.min(tx0, ux); ty0 = Math.min(ty0, uy); tx1 = Math.max(tx1, ux); ty1 = Math.max(ty1, uy);
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
+ if (!dx && !dy) continue;
+ const vy = uy + dy, vx = ux + dx;
+ if (vx < 0 || vy < 0 || vx >= grid || vy >= grid) continue;
+ const v = vy * grid + vx;
+ if (hit[v] && !seen[v]) { seen[v] = 1; stack.push(v); }
+ }
+ }
+ let iN = Infinity, oU = Infinity, aC = 0;
+ for (const t of tiles) { iN = Math.min(iN, dIn[t]); oU = Math.min(oU, dOut[t]); aC = Math.max(aC, dAcross[t]); }
+ const px0 = Math.floor((tx0 * W) / grid), py0 = Math.floor((ty0 * H) / grid), px1 = Math.floor(((tx1 + 1) * W) / grid), py1 = Math.floor(((ty1 + 1) * H) / grid);
+ const dStd = std(p1, px0, py0, px1, py1) - (std(p2, px0, py0, px1, py1) + std(cur, px0, py0, px1, py1)) / 2;
+ findings.push({ frame: f, tiles: tiles.length, box: [px0 / W, py0 / H, px1 / W, py1 / H], in: iN, out: oU, across: aC, kind: dStd > 3 ? "appears" : dStd < -3 ? "vanishes" : "jumps" });
+ }
+ }
+ p2 = p1; p1 = cur; dIn = dOut;
+ }
+ return findings;
+};
+
+const MAIN = process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
+if (MAIN) {
+ const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d; };
+ const die = (m) => { console.error(`popscan: ${m}`); process.exit(2); };
+ const a0 = process.argv[2];
+ if (!a0 || a0.startsWith("--")) { console.error("usage: node tools/popscan.mjs <film|path.mp4> [--from F] [--to T] [--grid 12] [--min 0.4] [--ratio 0.35] [--json]"); process.exit(2); }
+ const file = resolve(a0.endsWith(".mp4") ? a0 : `out/${a0}.mp4`);
+ if (!existsSync(file)) die(`no such file: ${file}`);
+ let probe;
+ try { probe = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,avg_frame_rate", "-of", "json", file], { stdio: ["pipe", "pipe", "pipe"] })); }
+ catch (e) { die(`ffprobe cannot read ${file}: ${String(e.stderr || e.message).trim().split("\n")[0] || "failed"}`); }
+ const stream = probe.streams?.[0];
+ if (!stream) die(`ffprobe finds no video stream in ${file}`);
+ const [fpsNum, fpsDen] = stream.avg_frame_rate.split("/").map(Number);
+ const fps = fpsNum / fpsDen || 30;
+ const GRID = Number(arg("grid", 12)), MIN = Number(arg("min", 0.4)) / 100, RATIO = Number(arg("ratio", 0.35)), THRESH = Number(arg("thresh", 4)), SIZE = Number(arg("size", 270));
+ const FROM = Number(arg("from", 1)), TO = arg("to") === undefined ? Infinity : Number(arg("to"));
+ if ([GRID, MIN, RATIO, THRESH, SIZE, FROM].some((v) => !Number.isFinite(v)) || Number.isNaN(TO)) die("a numeric option is not a number");
+ if (!Number.isInteger(GRID) || GRID < 2 || GRID > 64) die("--grid wants an integer in [2, 64]");
+ if (!(MIN > 0 && MIN < 1) || !(RATIO > 0)) die("--min wants a percent in (0, 100), --ratio a positive number");
+ const W = SIZE, H = Math.max(2, Math.round((SIZE * stream.height) / stream.width));
+ if (Math.floor(W / GRID) < 2 || Math.floor(H / GRID) < 2) die(`--grid ${GRID} leaves tiles under 2px at ${W}x${H}`);
+ const OUT = resolve("out"); mkdirSync(OUT, { recursive: true });
+ const stem = basename(file).replace(/\.[^.]*$/, "").replace(/[^\w.-]+/g, "-");
+ let n = 0;
+ const counted = (async function* () { for await (const fr of greyFrames(file, W, H, TO === Infinity ? Infinity : TO + 2)) { n++; yield fr; } })();
+ let findings;
+ try { findings = await scanPops(counted, { width: W, height: H, grid: GRID, min: MIN, ratio: RATIO, thresh: THRESH, from: FROM, to: TO }); }
+ catch (e) { die(String(e.message || e).trim().split("\n")[0]); }
+ if (!n) die("decoded 0 frames");
+ const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`; // POSIX single-quote: the strip is safe to paste whatever the film is named
+ const strip = (f) => {
+ const lo = Math.max(0, f - 2), hi = Math.min(n - 1, f + 2), sel = [];
+ for (let i = lo; i <= hi; i++) sel.push(`eq(n,${i})`);
+ const png = resolve(OUT, `popscan-${stem}-f${f}.png`);
+ return `ffmpeg -v error -y -i ${shq(file)} -vf "select='${sel.join("+")}',scale=384:-2,tile=${hi - lo + 1}x1" -fps_mode passthrough -frames:v 1 ${shq(png)}`;
+ };
+ const pct = (v) => +(v * 100).toFixed(2);
+ if (process.argv.includes("--json")) {
+ console.log(JSON.stringify(findings.map((r) => ({ frame: r.frame, t: +(r.frame / fps).toFixed(3), box: r.box.map(pct), in: pct(r.in), out: pct(r.out), across: pct(r.across), tiles: r.tiles, kind: r.kind, strip: strip(r.frame) })), null, 2));
+ } else {
+ console.log(`${file}\n ${n} frames decoded at ${W}x${H} grey, ${GRID}x${GRID} tiles, threshold ${THRESH}/255`);
+ for (const r of findings) {
+ console.log(` POP frame ${r.frame} t=${(r.frame / fps).toFixed(3)}s box ${r.box.map((v) => (v * 100).toFixed(1)).join(",")}% in ${pct(r.in)}% out ${pct(r.out)}% across ${pct(r.across)}% ${r.kind} (${r.tiles} tile${r.tiles > 1 ? "s" : ""})`);
+ console.log(` strip: ${strip(r.frame)}`);
+ }
+ console.log(findings.length ? ` POPSCAN: ${findings.length} finding(s) to review (a flag, never a fail)` : " POPSCAN: clean, no one-frame pops");
+ }
+ // exitCode, not process.exit: a big --json write to a pipe would otherwise truncate at 64k
+ process.exitCode = 0;
+}
diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/sfx.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/sfx.mjs
index 1fb4e2f..e84c4cd 100644
--- a/plugins/anidoodle/skills/anidoodle/engine/tools/sfx.mjs
+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/sfx.mjs
@@ -39,6 +39,13 @@ const hfShare = (M, L) => {
return 10 * Math.log10(Math.max(hi, 1e-30) / Math.max(tot, 1e-30));
};
const dcOf = (L) => { let s = 0; for (const x of L) s += x; return s / L.length; };
+const harshColumns = (h) => {
+ const f = (v) => v === null ? "n/a" : v.toFixed(2);
+ return `band cue/score ${f(h.cueBandDb)}/${f(h.musicBandDb)} lift ${f(h.liftDb)} full ${f(h.cueRmsDb)} tilt ${f(h.tiltDb)} peak/score ${f(h.peakDb)}/${f(h.musicPeakDb)} peak over score ${f(h.peakMarginDb)} body(150ms) ${f(h.bodyDb)} peak-body ${f(h.crestDb)} dB harsh ${h.ok ? "PASS" : "FAIL"}${h.mode === "tame" ? ` tame -${f(h.reductionDb)} dB` : ""}${h.conflict ? " conflict: " + h.conflict : ""}`;
+};
+const printAudibility = (mix) => {
+ for (const a of mix.audibility) console.log(` ${a.atS.toFixed(2).padStart(6)} s ${(a.kind + ":" + a.variant).padEnd(16)} ${a.label.padEnd(22)} margin ${a.marginDb.toFixed(1).padStart(5)} dB (peak ${a.peakMarginDb.toFixed(1)} dB) ${harshColumns(mix.harshness.find((h) => h.i === a.i))}`);
+};
/** Three varied hits of one variant, back to back, so the ear hears the variation. */
const reel = (M, kind, variant, opts = {}) => {
@@ -116,14 +123,14 @@ const kit = async (outdir) => {
writeAudio(join(dir, "demo-sfx-only.mp3"), mix.sfx[0], mix.sfx[1]);
writeAudio(join(dir, "demo-music-only.mp3"), music[0], music[1]);
execFileSync("ffmpeg", ["-v", "error", "-y", "-i", join(dir, "demo.mp3"), "-lavfi", "showspectrumpic=s=900x220:legend=0:scale=log", join(dir, "spectra", "demo.png")]);
- meters.demo = { ok: mix.ok, lufs: +mix.lufs.toFixed(1), dbtp: +mix.dbtp.toFixed(2), limiterDb: +mix.limiterDb.toFixed(2), cues: mix.audibility.map((a) => ({ kind: `${a.kind}:${a.variant}`, label: a.label, atS: +a.atS.toFixed(2), marginDb: +a.marginDb.toFixed(1), peakMarginDb: +a.peakMarginDb.toFixed(1) })) };
+ meters.demo = { ok: mix.ok, lufs: +mix.lufs.toFixed(1), dbtp: +mix.dbtp.toFixed(2), limiterDb: +mix.limiterDb.toFixed(2), cues: mix.audibility.map((a) => ({ kind: `${a.kind}:${a.variant}`, label: a.label, atS: +a.atS.toFixed(2), marginDb: +a.marginDb.toFixed(1), peakMarginDb: +a.peakMarginDb.toFixed(1), harshness: mix.harshness.find((h) => h.i === a.i) })) };
writeFileSync(join(dir, "meters.json"), JSON.stringify(meters, null, 1));
const demo = [["demo.mp3", "demo: score + kit", `15 s, ${plan.cues.length} cues, ${mix.lufs.toFixed(1)} LUFS, ${mix.dbtp.toFixed(1)} dBTP, every cue audible: ${mix.ok}`], ["demo-sfx-only.mp3", "demo: kit only", "the same cues without the score"], ["demo-music-only.mp3", "demo: score only", "launchLofi3, first 15 s, undipped"],
...Object.keys(meters.baseline).map((k) => [`baseline-${k}.mp3`, `baseline: launch3 ${k}`, "the launch film's current effect, for A/B"])];
writeFileSync(join(dir, "index.html"), page(rows, demo));
console.log(`wrote ${dir}: ${rows.reduce((a, r) => a + r[2].length, 0)} variant reels, 3 demo files, ${Object.keys(meters.baseline).length} baselines, index.html, meters.json, spectra/`);
console.log(`demo: ${mix.lufs.toFixed(1)} LUFS, ${mix.dbtp.toFixed(2)} dBTP, limiter ${mix.limiterDb.toFixed(2)} dB, all audible: ${mix.ok}`);
- for (const a of mix.audibility) console.log(` ${a.atS.toFixed(2).padStart(6)} s ${(a.kind + ":" + a.variant).padEnd(16)} ${a.label.padEnd(22)} margin ${a.marginDb.toFixed(1).padStart(5)} dB (peak ${a.peakMarginDb.toFixed(1)} dB)`);
+ printAudibility(mix);
};
const test = async () => {
@@ -181,6 +188,7 @@ const test = async () => {
ok(m1.L.length === Math.round((DEMO_FRAMES / FPS) * SR), "demo mix is exactly the film length");
ok(m1.dbtp <= -0.9, `demo true peak <= -1 dBTP (got ${m1.dbtp.toFixed(2)})`);
ok(m1.ok && m1.audibility.every((a) => a.marginDb >= -6), `demo: every cue within 6 dB of the score (worst ${Math.min(...m1.audibility.map((a) => a.marginDb)).toFixed(1)} dB)`);
+ printAudibility(m1);
const g = m1.placed.find((p) => p.cue.label === "Generate"); ok(g && Math.abs(g.hitS - 160 / 30) < 1e-9, `snap to beat: frame 157 -> 160 (got ${g && (g.hitS * 30).toFixed(2)})`);
const imp = m1.placed.find((p) => p.cue.kind === "impact"); ok(imp && Math.min(...Array.from(m1.duck.subarray(imp.window[0], imp.window[1]))) < 0.55, "score ducks >= 5 dB under the impact");
// a buried cue must FAIL
diff --git a/plugins/anidoodle/skills/anidoodle/references/craft-bar.md b/plugins/anidoodle/skills/anidoodle/references/craft-bar.md
index 865127c..ce7b1e6 100644
--- a/plugins/anidoodle/skills/anidoodle/references/craft-bar.md
+++ b/plugins/anidoodle/skills/anidoodle/references/craft-bar.md
@@ -19,9 +19,9 @@ The test: would a proud human illustrator ship this, or is it mechanical shape-a
| The same character drawn differently shot to shot | One character module; shots pose it, never redraw it (`workflows/character-consistency.md`) |
| A silhouette filled with texture, no mouth line, no toes | Interior contours: mouth, eyelids, nostrils, toes, joins between forms (the detail pass below) |
| A drawing film where the finished picture fades in | Marks made in the medium's order; the last frames are the still (`workflows/drawing-process.md`) |
-| Words laid over the art or the UI | Type gets its own frame; corner marks step aside when the camera brings UI under them |
+| Words laid over busy art, a face or the UI | Type gets its own frame by default; over the picture only as a composed label or kinetic line on a calm area (`workflows/launch-video.md`, Type) |
| A loop playing in place and called "alive" | Real travel through a world that changes as the subject moves |
-| A hard cut or a sharp swoosh between scenes | A gentle move: a bloom, a flip, a push, the card grows into the frame |
+| An unmatched hard cut or a sharp swoosh between scenes | A gentle move (a bloom, a flip, a push, the card grows into the frame), or a cut matched on shape, position or beat |
**No dead air** in anything that moves: something visibly changes in every second, from frame 0.
Check it with the tool AND by eye: a creeping camera changes every pixel and satisfies the tool
diff --git a/plugins/anidoodle/skills/anidoodle/references/motion-grammar.md b/plugins/anidoodle/skills/anidoodle/references/motion-grammar.md
new file mode 100644
index 0000000..dfb74c4
--- /dev/null
+++ b/plugins/anidoodle/skills/anidoodle/references/motion-grammar.md
@@ -0,0 +1,163 @@
+# Motion grammar: six ways to get from one picture to the next
+
+A film that shows one good thing, then another unrelated good thing, reads as a slideshow however
+well each is animated. These six mechanisms are ways to make the next picture come OUT of the
+current one. They are a grammar to compose from, never presets: pick the one the story is already
+asking for, and build it for that film's subject and medium.
+
+**The default does not change.** A gentle move (a bloom, a flip, a push) is still the standard
+seam (`workflows/launch-video.md`, Motion). Each mechanism below is a judgement with conditions.
+If its "use it when" does not clearly hold, use the gentle move.
+
+Three things hold for all six:
+
+- **The destination is in place before the move starts.** The next scene is already drawn under
+ or behind the move, so there is never an empty frame between scenes.
+- **Something is carried across**: a shape, a position, a direction of travel. That is what
+ separates a designed seam from a transition laid over a join.
+- **One or two mechanisms a film, each used for the seams that matter.** All six in 30 seconds is
+ a demo reel of moves, not a story.
+
+## 1. Foreground as transition
+
+Something already in the scene (a word, a mark, a shape) grows or sweeps until it covers the
+frame, and when it clears the next scene is there.
+
+- **Use it when** the covering thing is part of the story (the brand's ink, the product's mark,
+ the claim itself) and the two scenes share nothing else to carry across.
+- **Not when** the cover would be an arbitrary shape brought in only to hide the join, or when it
+ would happen on every seam: the third time, it reads as a wipe preset.
+- **Ours**: the type frames of the launch film (`launch3.ts`, `typeFrame` in `launchCut.ts`). Ink
+ blooms open from a point over the picture, the word letters itself on the page inside the
+ bloom, and the ink closes to a point on the NEXT picture. The bloom takes the content frame it
+ opens over and the one it closes onto as data (`type(lines, len, before, after)`), so the next
+ scene is always waiting under it.
+
+## 2. Persistent actor
+
+One object keeps its identity through the whole film while the scenes change around it.
+
+- **Use it when** the story already owns such an object (a cursor, the product's dot, a
+ character, a line being drawn) and it has a reason to be in every scene it visits.
+- **Not when** it has to be invented for the purpose, or dragged through scenes where it does
+ nothing: a mascot that only watches is decoration.
+- **Ours**: the ink drop in the launch template (`launchTemplate.ts`). Every press of Generate
+ sends a drop into the thread, where it blooms into the answer card; at the end it lifts off
+ Generate one last time, lands as the dot of the end card's mark, and the end card opens from
+ it. `motif.ts` holds it to the rule: same screen position and size on both sides of the seam,
+ within 2 px, or `checkRelay` throws.
+
+- **The general move**: `engine/src/canvas-core/morph.ts`. `handoff({ from, to, t0, t1 })` carries
+ one outline from a source shape to a target shape: it travels, stretches a little while it is
+ moving, and becomes the target in the second half of the trip, landing on it exactly.
+ `coverShape` grows a shape until it is the whole page. Keep the object's colour and edge the
+ same on both sides, and hold the seam with `checkShapes` (2 px). `morphDemo.ts`: a full stop
+ becomes a card, the card becomes the page.
+
+## 3. Selection to expansion
+
+One item in a set is picked, and it grows until it IS the next scene.
+
+- **Use it when** the story moves from many to one: a wall of options, then the one being used;
+ a list, then the item opened. The viewer sees where the next scene came from.
+- **Not when** the set was only there to be left (build the set because the story needs range,
+ not as a launch pad), or when the item's small and full-frame versions do not match: frame the
+ full scene's first frame exactly like the card it grew from.
+- **Ours**: the style wall (`launchGallery.ts`, used in `launch2.ts`). The camera punches into
+ cards and comes back out; the last punch does not come back, the card fills the frame and
+ becomes the scene. The koi does the same from a still: `koiWorld.ts` frames its first frame
+ exactly like the koi plate, so the card hands over to the swimming world with no seam.
+
+## 4. Registered decomposition
+
+A whole stays recognisable while its parts move into groups, each part traceable from where it
+was to where it lands.
+
+- **Use it when** the point is that the product sorts, extracts or reorganises something the
+ viewer has just seen: a crowded week becoming a plan, a document becoming fields.
+- **Not when** the parts cannot be followed. Past about seven moving at once, or with parts that
+ cross paths, the viewer loses the map; stagger them, or move groups rather than items.
+- **Ours**: `productUI.ts` (a `kind: "ui"` ask in the launch template). The interface is drawn
+ from data in two states. One press of the product's action and every item, matched by id,
+ springs from its place in the before state to its place in the after: rows travel to their new
+ slots, values count to their new numbers, new items arrive, old ones leave.
+
+## 5. Continuous canvas
+
+All the scenes live in one layout bigger than the frame, and the camera travels between them
+instead of cutting.
+
+- **Use it when** the places are really related in space (sections of one page, rooms of one
+ building, steps along one path) and the route between them tells the viewer how.
+- **Not when** the places are unrelated (the travel then invents a relationship that is not
+ there), or when the journey between two stops is long and empty: every second must change
+ (`craft-bar.md`, no dead air). One camera for every plane (`camera.md`).
+- **Ours**: `webTour.ts`. Three sections on one long page, a visible cursor, and a camera that
+ shows the whole page, then pushes in on every click and every field. `koiWorld.ts` is the
+ drawn version: a pond much bigger than the frame, with the scenery placed in the world so it
+ changes as the fish travels.
+
+## 6. Exploded layers
+
+One object separates into its layers along its depth, holds so each can be read, then closes
+back into the object.
+
+- **Use it when** what is inside is the point: how a thing is built, what a stack is made of.
+ The layers must be real parts of the subject, in their real order.
+- **Not when** the subject has no true layers and they would be invented for the effect, or when
+ the pieces are not held long enough apart to be read. If it never closes again, it is a
+ diagram, which may be what the film wants; decide which.
+- **Ours, in one direction only**: `paperCraft.ts`, the toy theatre. The scene is built from the
+ back, flat by flat, with real gaps between the flats: each piece travels held above the stack,
+ its shadow wide and far, and the shadow closes as it lands. That is the closing half. No film
+ of ours yet starts whole and separates; treat the opening half as unproven until one does.
+
+## Three ready-made seams
+
+For a plain change of scene that still wants a made mark, `engine/src/canvas-core/transitions.ts`
+has three calls. Each takes the two scenes as draw functions and a progress, at any frame size,
+with the incoming scene already complete underneath. `transitionsDemo.ts` shows each once.
+
+- **`brushWipe`**: a loaded brush pulled across; with `ink`, a band of wet ink ahead of the new
+ picture (without it, a clean bristled edge).
+ For the drawn register, in the direction the story is already moving. Not in the clean
+ register, and not more than once or twice a film.
+- **`iris`**: a round opening from a point, or closing to one. Open it from the thing the next
+ scene is about, close it on the thing this one was about; centred on nothing it is only a
+ shape. `shape: "blot"` for ink, the plain circle for the clean register.
+- **`flashCut`**: a hard cut under a short burst of light, so the hard cut's conditions apply
+ (a strong beat, in a piece whose energy asks for it). Never one frame, never full white by
+ default, never repeated quickly: declare a film's flashes to `checkFlashes`, which throws on
+ any two within half a second.
+
+## Callouts and the label handoff
+
+`engine/src/canvas-core/callout.ts` names one thing in the picture: a dot lands on it, a leader
+line is drawn out, a label is written at the end. The dot follows the thing as the camera moves
+(pin it with `cam.toScreen`, `camera.md`); the label holds still so it can be read. It is type
+over the picture, so that judgement applies in full (`workflows/launch-video.md`, Type): a calm
+area, a label that names what it points at, one or two on screen at a time. Where the picture is
+busy, give the label a `backing` or leave the callout out.
+
+The label can also be the persistent actor across a seam. With `handoff`, the dot and line
+retract and the label travels to where the next scene starts, landing as its heading on that
+scene's first frame; the next scene draws it from there with `drawLabel` at the same pose.
+`checkHandoff` holds the two sides to within 2 px and throws if the seam jumps.
+`calloutDemo.ts` shows both.
+
+## Choosing
+
+Ask what the seam has to tell the viewer, then take the mechanism that says it:
+
+| The seam says | Mechanism |
+|---|---|
+| "and now this", with nothing shared but the brand | Foreground as transition |
+| "the same thing, further along" | Persistent actor |
+| "this one, out of all of those" | Selection to expansion |
+| "the same things, put in order" | Registered decomposition |
+| "next to that, over here" | Continuous canvas |
+| "and this is what is inside" | Exploded layers |
+
+If none of these is what the seam says, it is a plain change of scene: use the gentle move, or
+a matched hard cut where its conditions hold. Review every designed seam as a before/after pair
+of stills, and as a strip of the frames between them, before the film is rendered in full.
diff --git a/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md
index b4754a1..5cdf9b6 100644
--- a/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md
+++ b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md
@@ -112,8 +112,8 @@ music, and its test only checked that they existed.)
makes it land.
- **One signature riser, one impact per film.** They mark the big reveal. A second riser halves
both.
-- Transitions are gentle moves, so their sound is gentle: `whoosh:soft` and `swish:soft`. Never a
- sharp swoosh.
+- Transitions are gentle moves by default, so their sound is gentle: `whoosh:soft` and
+ `swish:soft`. A matched hard cut takes a short hit on the beat or nothing. Never a sharp swoosh.
- Typing is one `tick` per character at the typing cadence, with `space` on spaces. Its level sits
above the intro and under the groove.
- Put at most two cues in any 100 ms. A thock on the kick merges into the kick, which is lovely
diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md
index d0651c7..7510821 100644
--- a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md
+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md
@@ -50,12 +50,19 @@ pieces are examples of the craft, never material for someone else's film.
## Type
-- **Words NEVER sit over the art or the UI.** A word gets its own full frame: an ink bloom
+- **Words get their own space by default.** A word gets its own full frame: an ink bloom
opens, a brush writes the word, the bloom closes on the next scene (`typeFrame`). Or, for a
feature beat, its own COLUMN: words on the left, the live UI on the right (words above, UI
below on a phone), each in its own area of the layout (`split`), faster than a full word page.
Corner marks step aside when the camera brings UI under them, and sit in their own strip on a
phone frame.
+- **Type over the picture is a judgement, and the answer is usually still no.** It earns its
+ place only when all of these hold: the picture under the word is calm there (flat or quiet,
+ and not moving through the letters); the word belongs to the scene (a label on the thing it
+ names, a callout, a kinetic line composed with the picture, not a caption dropped on top);
+ the frame would pass as a poster; and it reads with the sound off. Never over a face, a
+ product's UI, the detail the shot is about, or busy texture. Check it in a review still at
+ the smallest delivery size. In doubt, the word gets its own frame.
- **3-7 words a frame, few frames.** Collapse word cards into one claim then proof ("JUST CODE."
then "31 STYLES"); fewer cards leave more time for the proof.
- **Hold each settled word 0.5 s or more**, longer for the claim.
@@ -64,8 +71,14 @@ pieces are examples of the craft, never material for someone else's film.
## Motion
-- **Every transition is a gentle move**: bloom, card flip, push, the card GROWS into the frame.
- Never a hard cut, never a sharp swoosh. Ease in and out; the camera is `references/camera.md`.
+- **A gentle move is the default transition**: bloom, card flip, push, the card GROWS into the
+ frame. Ease in and out; the camera is `references/camera.md`.
+- **A hard cut is a judgement.** It works when it is matched: the same shape, position or
+ direction of travel on both sides, or a cut on a strong beat in a piece whose energy asks for
+ it. A cut with nothing carried across it, and any sharp swoosh, still reads as a slideshow.
+- **A designed seam is a judgement too.** Six ways to make the next picture come out of the
+ current one, each with when it fits and when it does not: `references/motion-grammar.md`.
+ Use one where its conditions clearly hold; otherwise the gentle move.
- **Drawings play 3-6x faster than real time**; a loop is held long enough to see it loop.
- **Alive means real motion**: the koi swims through a scrolling world, not an in-place GIF
(`start-here.md`, "Alive means real motion").
diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/long-film.md b/plugins/anidoodle/skills/anidoodle/references/workflows/long-film.md
index 6be565d..cbb813c 100644
--- a/plugins/anidoodle/skills/anidoodle/references/workflows/long-film.md
+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/long-film.md
@@ -24,7 +24,8 @@ A long film is a sequence of chapters, each with its own small arc, joined by on
section moods. Chapters import it; nobody changes it privately.
4. **Transitions carry the story**: each chapter hands over with a match cut, a covered switch
(a shape passing, a page turning, a fog at full density) or a shared token. A hard cut to
- black between every chapter is a slideshow.
+ black between every chapter is a slideshow. The six mechanisms, with when each fits, are
+ in `references/motion-grammar.md`.
5. **Music follows the chapters**: one theme, varied per chapter mood (see
`references/music/`), with the transitions scored (pre-lap, pivot chord, texture handoff).
6. **Review per chapter, then once whole**: a contact sheet per chapter at one tile per beat,
diff --git a/skills/anidoodle/SKILL.md b/skills/anidoodle/SKILL.md
index bfac277..257361b 100644
--- a/skills/anidoodle/SKILL.md
+++ b/skills/anidoodle/SKILL.md
@@ -102,8 +102,8 @@ draws itself declares `kind: "drawing"` and is judged on a finer floor; a freeze
`engine/` is the portable art core plus the tooling. `engine/src/canvas-core` knows nothing
about the DOM or any backend. `W`, `H`, `fps` and `durationFrames` come from the film's `meta`.
-Camera moves (pans, zooms, parallax, shake) come from `engine/src/canvas-core/camera.ts`:
-`references/camera.md`. `render.mjs --blur auto` renders with motion blur (subframes per frame
+Camera moves (pans, zooms, parallax, shake): `engine/src/canvas-core/camera.ts`, `references/camera.md`.
+Seams between scenes: `references/motion-grammar.md`. `render.mjs --blur auto` renders with motion blur (subframes per frame
from its measured on-screen speed, averaged in linear light, `--shutter 180`); the default path is untouched.
```bash
diff --git a/skills/anidoodle/engine/package-lock.json b/skills/anidoodle/engine/package-lock.json
index a1c0c85..bf7aeae 100644
--- a/skills/anidoodle/engine/package-lock.json
+++ b/skills/anidoodle/engine/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "anidoodle-engine",
- "version": "0.6.0",
+ "version": "0.6.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "anidoodle-engine",
- "version": "0.6.0",
+ "version": "0.6.1",
"dependencies": {
"esbuild": "0.25.12"
},
diff --git a/skills/anidoodle/engine/package.json b/skills/anidoodle/engine/package.json
index 8a5aa81..83bb2d9 100644
--- a/skills/anidoodle/engine/package.json
+++ b/skills/anidoodle/engine/package.json
@@ -1,6 +1,6 @@
{
"name": "anidoodle-engine",
- "version": "0.6.0",
+ "version": "0.6.1",
"private": true,
"type": "module",
"description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",
diff --git a/skills/anidoodle/engine/src/canvas-core/callout.ts b/skills/anidoodle/engine/src/canvas-core/callout.ts
new file mode 100644
index 0000000..15f5ef0
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/callout.ts
@@ -0,0 +1,113 @@
+// CALLOUT. A label that names one thing in the picture, and can carry the viewer into the next
+// scene: a dot lands on the thing, a leader line is drawn out from it, the label is written at the
+// end of the line. The thing may move (the anchor is asked for every frame, so pin it to the world
+// with camera.ts: `anchor: (f) => cam.toScreen(worldPoint, f, z)`); the label stays put so it can
+// be read. Screen coordinates in logical px, any frame size. Pure functions of their arguments.
+//
+// It is type over the picture, so that judgement applies (references/workflows/launch-video.md,
+// Type): the label sits on a calm area, names the thing it points at, and one or two are on screen
+// at a time. Where the picture under it is not calm, give it a `backing`, or do not use a callout.
+//
+// const c: Callout = { text: "LIVE PREVIEW", anchor: (f) => cam.toScreen([820, 410], f), label: { p: [1180, 300], size: 44 }, t0: 60, out: 150 };
+// drawCallout(ctx, env, c, f);
+//
+// THE HANDOFF. Instead of leaving, the label can travel to where the next scene starts and become
+// its heading: `handoff: { leave, at, pose }`. From `leave` the dot and line retract while the
+// label moves and resizes; on frame `at`, the next scene's first frame, it sits exactly on `pose`,
+// and from there the next scene draws it itself with drawLabel at that pose. checkHandoff holds the
+// two sides to within 2 px, the motif's rule (motif.ts), and throws if the seam jumps.
+import type { Ctx, Env, P } from "./core";
+import { clamp, inOut, lerp, out3, ramp, rr } from "./launchKit";
+import { measure, setType, setWidth, writeOn, type KStyle } from "./kinetic";
+import { checkRelay } from "./motif";
+
+/** Where a label sits: `p` is the left end of its baseline, `size` its cap height (drawn) or font px (clean). */
+export type LabelPose = { p: P; size: number };
+export type Callout = {
+ text: string;
+ anchor: (f: number) => P; // the thing named, on screen, at frame f
+ label: LabelPose;
+ t0: number; // the frame the dot lands; the line and the label follow
+ out?: number; // the frame it starts to leave (the label is taken back, the line retracts); omit to stay
+ handoff?: { leave: number; at: number; pose: LabelPose; arc?: number }; // see THE HANDOFF; `arc` lifts the path (px, up)
+ register?: "drawn" | "clean"; // drawn: written in ink with a hand's curved line. clean: set type, an elbow line, an underline
+ style?: KStyle; color?: string; accent?: string;
+ backing?: string; // a chip of this colour behind the label, for a picture that is not calm there
+ dot?: number; // the dot's radius (default 0.16 x size)
+};
+// frames after t0: the dot lands, the line is drawn, the label is written; and how long leaving takes
+export const CALLOUT_T = { dot: [0, 7], line: [4, 17], text: [11, 30], leave: 12 } as const;
+/** The frame a callout is fully on screen and readable. */
+export const calloutReady = (c: Callout) => c.t0 + CALLOUT_T.text[1];
+
+const widthOf = (ctx: Ctx, c: Pick<Callout, "text" | "register">, size: number) => (c.register === "clean" ? setWidth(ctx, c.text, size) : measure(c.text, size, { weight: 1.15 }));
+/** The label's pose at frame f (pure): its own until a handoff leaves, then on the way, then the destination on `at`. Null before t0. */
+export const calloutPose = (c: Callout, f: number): LabelPose | null => {
+ if (f < c.t0) return null;
+ const h = c.handoff; if (!h || f <= h.leave) return c.label;
+ const u = ramp(f, h.leave, h.at), e = inOut(u), a = c.label, b = h.pose;
+ return { p: [lerp(a.p[0], b.p[0], e), lerp(a.p[1], b.p[1], e) - Math.sin(Math.PI * u) * (h.arc ?? 0)], size: a.size > 0 && b.size > 0 ? a.size * Math.pow(b.size / a.size, e) : lerp(a.size, b.size, e) }; // size eased as a ratio
+};
+/** The label alone, at a pose: what the next scene calls from the handoff frame on, so both sides draw the same marks. */
+export const drawLabel = (ctx: Ctx, env: Env, c: Pick<Callout, "text" | "register" | "style" | "color" | "backing">, pose: LabelPose, p = 1, chip = true) => {
+ if (chip && c.backing) { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); const s = pose.size, w = widthOf(ctx, c, s), pad = s * 0.38; ctx.fillStyle = c.backing; rr(ctx, pose.p[0] - pad, pose.p[1] - s * 1.02 - pad * 0.5, w + pad * 2, s * 1.42 + pad, s * 0.22); ctx.fill(); } // the chip travels with the label
+ if (c.register === "clean") setType(ctx, env, c.text, pose.p[0], pose.p[1], pose.size, p, { color: c.color ?? "#111214" });
+ else writeOn(ctx, env, c.text, pose.p[0], pose.p[1], pose.size, p, c.style ?? "ink", { color: c.color ?? "#1b1510", seed: 7, weight: 1.15, pop: 0.7 });
+};
+/** Throws unless the callout's label lands on the next scene's heading within `tol` px (position and size). */
+export const checkHandoff = (c: Callout, into: LabelPose, tol = 2) => {
+ const h = c.handoff; if (!h) throw new Error(`callout "${c.text}": no handoff to check`);
+ if (h.at - h.leave < CALLOUT_T.leave || h.leave < calloutReady(c)) throw new Error(`callout "${c.text}": the handoff leaves at ${h.leave} and lands at ${h.at}; it must leave after the label is readable (frame ${calloutReady(c)}) and take at least ${CALLOUT_T.leave} frames, the time the dot and line need to retract`);
+ const out = calloutPose(c, h.at)!;
+ return checkRelay([{ frame: h.at, label: `callout "${c.text}"`, out: { p: out.p, r: out.size }, into: { p: into.p, r: into.size } }], tol);
+};
+
+// the first `u` of a polyline, by length
+const partial = (pts: P[], u: number): P[] => {
+ const L = pts.slice(1).map((q, i) => Math.hypot(q[0] - pts[i][0], q[1] - pts[i][1])), tot = L.reduce((a, b) => a + b, 0);
+ let left = tot * clamp(u); const out: P[] = [pts[0]];
+ for (let i = 0; i < L.length && left > 0; i++) { const k = Math.min(1, left / (L[i] || 1)); out.push([lerp(pts[i][0], pts[i + 1][0], k), lerp(pts[i][1], pts[i + 1][1], k)]); left -= L[i]; }
+ return out;
+};
+/** The leader line from the thing to the label (pure), in screen px: an elbow and an underline (clean), or one bowed stroke (drawn). */
+export const leaderPath = (anchor: P, pose: LabelPose, width: number, register: "drawn" | "clean" = "drawn", dot = pose.size * 0.16, side?: boolean): P[] => {
+ const [x0, y] = pose.p, s = pose.size, right = side ?? anchor[0] <= x0 + width / 2; // the label is to the right of the thing (`side` pins it)
+ if (register === "clean") {
+ const uy = y + s * 0.34, near: P = [right ? x0 - s * 0.1 : x0 + width + s * 0.1, uy], far: P = [right ? x0 + width + s * 0.1 : x0 - s * 0.1, uy];
+ const d = Math.hypot(near[0] - anchor[0], near[1] - anchor[1]) || 1, a: P = [anchor[0] + ((near[0] - anchor[0]) / d) * dot * 2, anchor[1] + ((near[1] - anchor[1]) / d) * dot * 2];
+ return [a, near, far];
+ }
+ const e: P = [right ? x0 - s * 0.35 : x0 + width + s * 0.35, y - s * 0.42], d = Math.hypot(e[0] - anchor[0], e[1] - anchor[1]) || 1;
+ const a: P = [anchor[0] + ((e[0] - anchor[0]) / d) * dot * 2.2, anchor[1] + ((e[1] - anchor[1]) / d) * dot * 2.2];
+ const bow = Math.min(d * 0.18, s * 1.6) * (right ? 1 : -1), m: P = [(a[0] + e[0]) / 2 + ((e[1] - a[1]) / d) * bow, (a[1] + e[1]) / 2 - ((e[0] - a[0]) / d) * bow];
+ return Array.from({ length: 25 }, (_, i): P => { const t = i / 24; return [(1 - t) ** 2 * a[0] + 2 * (1 - t) * t * m[0] + t * t * e[0], (1 - t) ** 2 * a[1] + 2 * (1 - t) * t * m[1] + t * t * e[1]]; });
+};
+
+export const drawCallout = (ctx: Ctx, env: Env, c: Callout, f: number) => {
+ const h = c.handoff, T = CALLOUT_T;
+ if (f < c.t0 || (h && f >= h.at)) return; // from `at` on, the next scene owns the label
+ const pose = calloutPose(c, f)!, clean = c.register === "clean", accent = c.accent ?? "#d4622b", L = f - c.t0;
+ // leaving: everything is taken back in the reverse of the order it was made; on a handoff only the dot and line go
+ const gone = h ? ramp(f, h.leave, h.leave + T.leave) : c.out === undefined ? 0 : ramp(f, c.out, c.out + T.leave);
+ const pd = ramp(L, T.dot[0], T.dot[1]), pl = out3(ramp(L, T.line[0], T.line[1])) * (1 - inOut(gone)), pt = h ? ramp(L, T.text[0], T.text[1]) : ramp(L, T.text[0], T.text[1]) * (1 - inOut(clamp(gone * 1.4)));
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+ const w = widthOf(ctx, c, pose.size), s = pose.size, A = c.anchor(f), dotR = c.dot ?? c.label.size * 0.16;
+ const right = A[0] <= c.label.p[0] + widthOf(ctx, c, c.label.size) / 2; // which side the line leaves from is the settled label's, so it cannot flip while the label travels
+ ctx.save(); ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.globalAlpha = 1;
+ if (c.backing && pt > 0) { // a chip that grows from the line's side as the label is written
+ const pad = s * 0.38, bw = (w + pad * 2) * out3(pt);
+ ctx.fillStyle = c.backing; rr(ctx, right ? pose.p[0] - pad : pose.p[0] + w + pad - bw, pose.p[1] - s * 1.02 - pad * 0.5, bw, s * 1.42 + pad, s * 0.22); ctx.fill();
+ }
+ if (pl > 0) {
+ const pts = partial(leaderPath(A, pose, w, clean ? "clean" : "drawn", dotR, right), pl);
+ ctx.strokeStyle = accent; ctx.lineWidth = clean ? Math.max(2, s * 0.05) : s * 0.06;
+ ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.stroke();
+ }
+ const r = dotR * (out3(pd) + 0.3 * Math.sin(Math.PI * pd) * (1 - pd)) * (1 - inOut(gone)); // lands with a small overshoot
+ if (r > 0.2) {
+ if (clean) { ctx.strokeStyle = accent; ctx.lineWidth = Math.max(2, s * 0.05); ctx.beginPath(); ctx.arc(A[0], A[1], r * 1.5, 0, Math.PI * 2); ctx.stroke(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(A[0], A[1], r * 0.55, 0, Math.PI * 2); ctx.fill(); }
+ else { ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(A[0], A[1], r, 0, Math.PI * 2); ctx.fill(); }
+ }
+ ctx.restore();
+ if (pt > 0) drawLabel(ctx, env, c, pose, pt, false);
+};
diff --git a/skills/anidoodle/engine/src/canvas-core/calloutDemo.ts b/skills/anidoodle/engine/src/canvas-core/calloutDemo.ts
new file mode 100644
index 0000000..5a12887
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/calloutDemo.ts
@@ -0,0 +1,49 @@
+// CALLOUT DEMO. One callout pinned to a thing while the camera moves, its handoff into the next
+// scene, and a second callout there that leaves the plain way (120 bpm: a beat is 15 frames).
+// 0-135 the fox plate, the camera easing in toward the moon. At 20 a dot lands on the moon,
+// the line is drawn out, "THE MOON" is written in the calm of the sky; the dot follows
+// the moon as the camera moves, the label holds still.
+// 105-135 THE HANDOFF: the dot and line retract, the label travels up and left and grows; an
+// iris opens the next scene from the moon underneath it.
+// 135-285 the label is the page's heading, on the frame it lands. The phases rise in below it;
+// a second callout names the full moon from the calm ground under the card, then leaves.
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import { Camera } from "./camera";
+import { out3, plateLayer, ramp, rr } from "./launchKit";
+import { calloutPose, checkHandoff, drawCallout, drawLabel, type Callout, type LabelPose } from "./callout";
+import { iris, seam } from "./transitions";
+import { fox } from "./fox";
+import { moonPhases } from "./moonPhases";
+
+const W = 1080, H = 1080, N = 285, AT = 135, CREAM = "#f1e7cf", GOLD = "#e9a23b", BOARD = "#1d2b28";
+const MOON: P = [214, 204], HEAD: LabelPose = { p: [84, 196], size: 92 };
+const cam = new Camera([W / 2, H / 2], [{ f: 0, look: [540, 540], zoom: 1 }, { f: AT, look: [452, 440], zoom: 1.28 }]);
+
+const moon: Callout = { text: "THE MOON", anchor: (f) => cam.toScreen(MOON, f), label: { p: [470, 150], size: 46 }, t0: 20, color: CREAM, accent: GOLD, handoff: { leave: 105, at: AT, pose: HEAD, arc: 36 } };
+checkHandoff(moon, HEAD);
+// the phases, cropped from the chalkboard plate: source rows 170-760, set down as a card
+const CARD = { x: 60, y: 300, w: 960, h: 545, sx: 20, sy: 170, sw: 1040, sh: 590 };
+const full: Callout = { text: "FULL, DAY 15", anchor: () => [CARD.x + ((540 - CARD.sx) / CARD.sw) * CARD.w, CARD.y + ((372 - CARD.sy) / CARD.sh) * CARD.h], label: { p: [610, 960], size: 38 }, t0: 178, out: 250, color: CREAM, accent: GOLD };
+
+const scene1 = (env: Env, f: number) => (c: Ctx) => {
+ const L = plateLayer(env, "calloutdemo:fox", fox, 0, Math.round(W * env.scale * 1.3), true).canvas, o = cam.toScreen([0, 0], f), k = cam.at(f).zoom;
+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.globalAlpha = 1; c.drawImage(L, o[0], o[1], W * k, H * k);
+};
+const scene2 = (env: Env, f: number) => (c: Ctx) => {
+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.globalAlpha = 1; c.fillStyle = BOARD; c.fillRect(0, 0, W, H);
+ const L = plateLayer(env, "calloutdemo:moon", moonPhases, 0, Math.round(W * env.scale), true).canvas, q = L.width / W, y = CARD.y + (1 - out3(ramp(f, AT - 14, AT + 10))) * (H - CARD.y + 20);
+ c.save(); rr(c, CARD.x, y, CARD.w, CARD.h, 18); c.clip(); c.drawImage(L, CARD.sx * q, CARD.sy * q, CARD.sw * q, CARD.sh * q, CARD.x, y, CARD.w, CARD.h); c.restore();
+};
+const draw = (ctx: Ctx, f: number, env: Env) => {
+ if (f < AT) { iris(ctx, env, seam(f, 117, AT - 117), scene1(env, f), scene2(env, f), { center: cam.toScreen(MOON, f) }); drawCallout(ctx, env, moon, f); return; }
+ scene2(env, f)(ctx);
+ drawLabel(ctx, env, moon, calloutPose(moon, AT)!); // the heading: the same marks, where the label landed
+ drawCallout(ctx, env, full, f);
+};
+
+export const calloutDemo: Film = {
+ meta: { title: "callout · anchor, leader, label, handoff", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },
+ assets: { images: {} },
+ shots: [{ id: "callout", start: 0, end: N, draw }],
+};
diff --git a/skills/anidoodle/engine/src/canvas-core/cheetahDusk.ts b/skills/anidoodle/engine/src/canvas-core/cheetahDusk.ts
new file mode 100644
index 0000000..d3693ae
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/cheetahDusk.ts
@@ -0,0 +1,183 @@
+// CHEETAH, DUSK. A 12 s loop for the motion graphics reel. The picture is timed in frames on a
+// 120 bpm grid; the score is four bars at 80 bpm, the same 12 s, meeting it every 1.5 s.
+// The coat is rings of tapered tufts radiating from the bridge of the nose; the tear lines are the
+// one big black shape; the sun sits low behind the head and the moon is in the pupil.
+// 0-60 night. The crescent moon sets as the sun comes up behind the grass.
+// 60-180 the face makes itself: the head's mass, then the coat ring by ring from the nose
+// outward, the ears, the spots in waves, the tear lines drawn down, the muzzle, whiskers.
+// 150-170 the eyes open; the moon is already in them. One blink at 236.
+// 180-290 alive: the coat breathes in a ripple, an ear flicks, the grass moves, a slow push in.
+// 290-338 the camera goes into the left pupil. The crescent in it is carried, at one size on
+// screen, to where the moon hangs in the sky (the persistent actor across the seam).
+// 322-360 the pupil is the night; the grass comes back up. Frame 359 hands over to frame 0.
+import { rng, type Ctx, type Env, type Layer, type P } from "./core";
+import type { Film } from "./film";
+import { mix } from "./gallery";
+import { cheetahDuskScore } from "./music/pieces/cheetah";
+import { renderLoop } from "./music/render";
+
+const W = 1080, H = 1080, N = 360;
+const NIGHT = "#0d1a22", TEAL = "#2a6a70", RUST = "#b8452a", OCHRE = "#e3a23a", GOLD = "#efb84e", CREAM = "#f2e4c5", PALE = "#fff5de", CORAL = "#f2643c", DARK = "#0a1216", PUPIL = "#070b0e";
+const F: P = [540, 610], EYE_L: P = [388, 512], EYE_R: P = [692, 512], MOON: P = [760, 220], MOON_R = 46;
+const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
+const ramp = (f: number, a: number, b: number) => clamp((f - a) / (b - a));
+const out3 = (t: number) => 1 - Math.pow(1 - clamp(t), 3);
+const inOut = (t: number) => { const c = clamp(t); return c < 0.5 ? 4 * c * c * c : 1 - Math.pow(-2 * c + 2, 3) / 2; };
+const back = (t: number) => { const c = clamp(t) - 1; return 1 + 2.4 * c * c * c + 1.4 * c * c; }; // lands a little past, then settles
+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+
+// a tuft: a tapered leaf from radius r0 to r1 along angle a, darker at its root
+const tuft = (c: Ctx, o: P, a: number, r0: number, r1: number, w: number, col: string, vein = 0.22) => {
+ if (r1 - r0 < 1.5 || w < 0.6) return;
+ const ca = Math.cos(a), sa = Math.sin(a), b: P = [o[0] + ca * r0, o[1] + sa * r0], t: P = [o[0] + ca * r1, o[1] + sa * r1], m = r0 + (r1 - r0) * 0.42, mx = o[0] + ca * m, my = o[1] + sa * m;
+ const g = c.createLinearGradient(b[0], b[1], t[0], t[1]); g.addColorStop(0, mix(col, DARK, 0.6)); g.addColorStop(0.45, col); g.addColorStop(1, mix(col, "#ffffff", 0.16));
+ c.fillStyle = g; c.beginPath(); c.moveTo(b[0], b[1]); c.quadraticCurveTo(mx - sa * w, my + ca * w, t[0], t[1]); c.quadraticCurveTo(mx + sa * w, my - ca * w, b[0], b[1]); c.fill();
+ if (vein > 0) { c.strokeStyle = mix(col, DARK, 0.7); c.globalAlpha = vein; c.lineWidth = 1; c.beginPath(); c.moveTo(b[0], b[1]); c.lineTo(o[0] + ca * (r1 - 6), o[1] + sa * (r1 - 6)); c.stroke(); c.globalAlpha = 1; }
+};
+const crescent = (c: Ctx, x: number, y: number, R: number, col: string) => { // a true crescent, so it needs no ground colour behind it
+ const ix = x + R * 0.5, iy = y - R * 0.24, ir = R * 0.9, out: P[] = [], inn: P[] = [];
+ for (let i = 0; i < 90; i++) { const a = (i / 90) * Math.PI * 2 + 0.3, p: P = [x + Math.cos(a) * R, y + Math.sin(a) * R]; if (Math.hypot(p[0] - ix, p[1] - iy) >= ir) out.push(p); }
+ for (let i = 0; i < 90; i++) { const a = (i / 90) * Math.PI * 2 + 0.3, p: P = [ix + Math.cos(a) * ir, iy + Math.sin(a) * ir]; if (Math.hypot(p[0] - x, p[1] - y) <= R) inn.push(p); }
+ // both runs are contiguous once rotated to start at a gap
+ const rot = (q: P[], far: (p: P) => number) => { let k = 0, best = -1; for (let i = 0; i < q.length; i++) { const d = Math.hypot(q[i][0] - q[(i + 1) % q.length][0], q[i][1] - q[(i + 1) % q.length][1]); if (d > best) { best = d; k = i + 1; } } void far; return [...q.slice(k), ...q.slice(0, k)]; };
+ const A = rot(out, () => 0), B = rot(inn, () => 0).reverse();
+ c.fillStyle = col; c.beginPath(); [...A, ...B].forEach((p, i) => (i ? c.lineTo(p[0], p[1]) : c.moveTo(p[0], p[1]))); c.closePath(); c.fill();
+};
+
+// ---------------------------------------------------------------- the parts, laid out once
+const COAT = [
+ { r0: 318, r1: 432, n: 92, w: 20, col: "#a9601f" }, { r0: 268, r1: 368, n: 84, w: 20, col: "#cf8a2c" }, { r0: 216, r1: 310, n: 74, w: 19, col: OCHRE },
+ { r0: 164, r1: 254, n: 62, w: 18, col: GOLD }, { r0: 112, r1: 198, n: 50, w: 17, col: "#f2c263" }, { r0: 62, r1: 142, n: 38, w: 15, col: "#f4cd7e" },
+];
+type T = { a: number; r0: number; r1: number; w: number; col: string; t0: number; ring: number };
+const PARTS = (() => {
+ const r = rng(11);
+ const neck = Array.from({ length: 6 * 14 }, (_, i) => { const row = 5 - Math.floor(i / 14), k = (i % 14) - 1; return { x: k * 94 + (row % 2) * 47 + 10, y: 820 + row * 56, col: mix(["#a9601f", "#cf8a2c", "#8f4f1c"][row % 3], DARK, 0.2 + row * 0.07 + r() * 0.1), t0: 52 + row * 5 + r() * 6 }; });
+ const coat: T[] = [];
+ COAT.forEach((k, i) => { for (let j = 0; j < k.n; j++) { const a = ((j + (i % 2) * 0.5) / k.n) * Math.PI * 2, down = clamp((Math.sin(a) - 0.25) * 1.7) * clamp((i - 1) / 3), len = 1 + (r() - 0.5) * 0.12; coat.push({ a, r0: k.r0, r1: k.r0 + (k.r1 - k.r0) * len, w: k.w, col: mix(mix(k.col, CREAM, down), DARK, r() * 0.1), t0: 72 + (5 - i) * 9 + (((a + Math.PI / 2) / (Math.PI * 2) + 1) % 1) * 12, ring: i }); } });
+ const sr = rng(5), spots: { x: number; y: number; s: number; a: number; t0: number }[] = [];
+ for (let ring = 0; ring < 9; ring++) { const rad = 150 + ring * 29, n = Math.round((rad * 2 * Math.PI) / 40);
+ for (let j = 0; j < n; j++) { const a = ((j + (ring % 2) * 0.5 + (sr() - 0.5) * 0.3) / n) * Math.PI * 2, x = F[0] + Math.cos(a) * rad, y = F[1] + Math.sin(a) * rad * 0.95, s = 4.2 + ring * 0.55 + sr() * 1.8, jit = sr();
+ if (Math.sin(a) > 0.2 && rad < 330) continue; if (Math.hypot(x - EYE_L[0], y - EYE_L[1]) < 132 || Math.hypot(x - EYE_R[0], y - EYE_R[1]) < 132) continue; if (Math.abs(x - 540) < 46 && y > 430) continue;
+ spots.push({ x, y, s, a, t0: 128 + ring * 4 + jit * 8 }); } }
+ const gr = rng(41), grass = Array.from({ length: 70 }, () => ({ x: gr() * W, h: 90 + gr() * 220, a: (gr() - 0.5) * 0.5, w: 9 + gr() * 8, col: gr() < 0.15 ? TEAL : mix(NIGHT, TEAL, gr() * 0.5), ph: gr() * 6.28 }));
+ return { neck, coat, spots, grass };
+})();
+
+const ear = (c: Ctx, o: P, side: number, f: number) => {
+ const g = back(ramp(f, 122, 140)); if (g <= 0) return;
+ const flick = side < 0 ? Math.sin(ramp(f, 206, 222) * Math.PI * 2) * 0.16 * (1 - ramp(f, 206, 222)) : 0;
+ c.save(); c.translate(o[0] + side * 40, o[1] + 70); c.rotate(flick); c.scale(g, g); c.translate(-o[0] - side * 40, -o[1] - 70);
+ c.fillStyle = DARK; c.beginPath(); c.ellipse(o[0], o[1], 84, 92, side * 0.35, 0, Math.PI * 2); c.fill();
+ for (let j = 0; j < 30; j++) tuft(c, [o[0] + side * 12, o[1] + 38], -Math.PI / 2 + side * 0.3 + (j / 29 - 0.5) * 2.3, 8, 78 - Math.abs(j - 14.5) * 1.8, 9, j % 2 ? CREAM : "#e9c98a", 0.15);
+ for (let j = 0; j < 46; j++) tuft(c, o, (j / 46) * Math.PI * 2, 68, 100, 8, j % 3 ? "#a9601f" : OCHRE, 0);
+ c.restore();
+};
+const eye = (c: Ctx, o: P, side: number, f: number, pupilCol: string, moon: boolean) => {
+ const patch = ramp(f, 118, 138);
+ for (let j = 0; j < 34; j++) { const g = back(clamp(patch * 1.6 - (j / 34) * 0.6)); tuft(c, o, (j / 34) * Math.PI * 2, 58, 58 + (54 + (j % 2) * 8) * g, 11 * g, j % 2 ? CREAM : PALE, 0.15); }
+ const blink = 1 - 0.92 * Math.sin(ramp(f, 234, 246) * Math.PI), open = out3(ramp(f, 150, 170)) * blink; if (patch <= 0) return;
+ const lid = (g: number) => { c.beginPath(); c.moveTo(o[0] - side * (86 + g), o[1] + 30 + g * 0.4); c.bezierCurveTo(o[0] - side * 40, o[1] - 62 - g, o[0] + side * 50, o[1] - 70 - g, o[0] + side * (92 + g), o[1] - 22); c.bezierCurveTo(o[0] + side * 46, o[1] + 58 + g, o[0] - side * 30, o[1] + 66 + g, o[0] - side * (86 + g), o[1] + 30 + g * 0.4); c.closePath(); };
+ c.save(); c.translate(o[0], o[1]); c.scale(patch, Math.max(0.07, open) * patch); c.translate(-o[0], -o[1]);
+ c.fillStyle = DARK; lid(15); c.fill();
+ c.save(); lid(0); c.clip();
+ const g = c.createRadialGradient(o[0], o[1], 16, o[0], o[1], 70); g.addColorStop(0, "#ffd24a"); g.addColorStop(0.55, "#f39a1e"); g.addColorStop(1, "#b84a14");
+ c.fillStyle = g; c.fillRect(o[0] - 120, o[1] - 100, 240, 200);
+ const r = rng(90 + side); c.lineCap = "round";
+ for (let i = 0; i < 150; i++) { const a = (i / 150) * Math.PI * 2 + r() * 0.03, a0 = 30 + r() * 8, a1 = 44 + r() * 30, lt = r() < 0.4; c.strokeStyle = lt ? "#ffe9a0" : "#8a2c0c"; c.globalAlpha = 0.18 + r() * 0.3; c.lineWidth = 0.8 + r() * 1.3; c.beginPath(); c.moveTo(o[0] + Math.cos(a) * a0, o[1] + Math.sin(a) * a0); c.lineTo(o[0] + Math.cos(a) * a1, o[1] + Math.sin(a) * a1); c.stroke(); }
+ c.globalAlpha = 1; c.fillStyle = "rgba(40,10,4,0.4)"; c.beginPath(); c.ellipse(o[0], o[1] - 96, 150, 66, 0, 0, Math.PI * 2); c.fill(); // the lid's shadow
+ // the pupil: wide as the eye opens, narrowing in the light, widening again as the camera comes in
+ const pr = 29 * (1.3 - 0.3 * out3(ramp(f, 166, 200)) + 0.35 * inOut(ramp(f, 286, 320)));
+ c.fillStyle = pupilCol; c.beginPath(); c.arc(o[0], o[1] - 2, pr, 0, Math.PI * 2); c.fill();
+ if (moon) crescent(c, o[0] - 10, o[1] - 12, 9.5, PALE);
+ c.fillStyle = "rgba(255,245,222,0.9)"; c.globalAlpha = 1 - ramp(f, 300, 318); c.beginPath(); c.arc(o[0] + 13, o[1] + 11, 2.6, 0, Math.PI * 2); c.fill(); c.globalAlpha = 1;
+ c.restore(); c.restore();
+};
+// the tear line: one black stroke from the inner corner of the eye, round the muzzle, to the mouth
+const tear = (c: Ctx, side: number, prog: number) => {
+ if (prog <= 0) return;
+ const p: P[] = [[540 - side * 76, 548], [540 - side * 70, 640], [540 - side * 128, 720], [540 - side * 110, 836]], bz = (t: number): P => { const u = 1 - t; return [u * u * u * p[0][0] + 3 * u * u * t * p[1][0] + 3 * u * t * t * p[2][0] + t * t * t * p[3][0], u * u * u * p[0][1] + 3 * u * u * t * p[1][1] + 3 * u * t * t * p[2][1] + t * t * t * p[3][1]]; };
+ const L: P[] = [], R: P[] = [], n = 40, m = Math.max(1, Math.round(n * prog));
+ for (let i = 0; i <= m; i++) { const t = i / n, a = bz(t), b = bz(Math.min(1, t + 0.01)), d = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1, nx = -(b[1] - a[1]) / d, ny = (b[0] - a[0]) / d, w = (7 + 15 * Math.sin(Math.PI * Math.pow(t, 0.6)) * (1 - t * 0.35)) * (i === m && prog < 1 ? 0.3 : 1); L.push([a[0] + nx * w, a[1] + ny * w]); R.push([a[0] - nx * w, a[1] - ny * w]); }
+ c.fillStyle = DARK; c.beginPath(); [...L, ...R.reverse()].forEach(([x, y], i) => (i ? c.lineTo(x, y) : c.moveTo(x, y))); c.closePath(); c.fill();
+};
+const grass = (c: Ctx, f: number, grow: number) => { for (const g of PARTS.grass) tuft(c, [g.x, H + 20], -Math.PI / 2 + g.a + Math.sin(f * (Math.PI / 45) + g.ph) * 0.07, 0, g.h * grow, g.w, g.col, 0); };
+
+// the night's stars: they are out while it is night, at the start and again at the end, never still
+const STARS = (() => { const r = rng(19); return Array.from({ length: 46 }, () => ({ x: r() * W, y: r() * 760, s: 1.2 + r() * 2.2, ph: r() * 6.28, cyc: [4, 6, 8, 9, 12][Math.floor(r() * 5)] })); })(); // cyc: whole twinkles per loop, so frame 359 meets frame 0
+const stars = (c: Ctx, f: number, k: number) => { if (k <= 0) return; for (const st of STARS) { c.globalAlpha = k * (0.35 + 0.65 * (0.5 + 0.5 * Math.sin((f / N) * Math.PI * 2 * st.cyc + st.ph))); c.fillStyle = PALE; c.beginPath(); c.arc(st.x, st.y, st.s, 0, Math.PI * 2); c.fill(); } c.globalAlpha = 1; };
+
+// ---------------------------------------------------------------- the camera
+const camAt = (f: number) => {
+ const a = inOut(ramp(f, 180, 290)), b = ramp(f, 290, 338), z = Math.pow(2, lerp(0, Math.log2(1.14), a) + inOut(b) * (Math.log2(52) - Math.log2(1.14))), lk = out3(b * 1.5);
+ return { z, look: [lerp(lerp(540, 506, a), EYE_L[0], lk), lerp(lerp(540, 532, a), EYE_L[1] - 2, lk)] as P };
+};
+
+const grainLayer = (env: Env): Layer => { // the paper's tooth and the dusk settling at the edges: laid once, the same on every frame
+ const key = "cheetah:grain"; let L = env.cache.get(key) as Layer | undefined; if (L) return L;
+ L = env.canvas(Math.round(W * env.scale), Math.round(H * env.scale)); env.cache.set(key, L);
+ const c = L.ctx, q = rng(77); c.setTransform(env.scale, 0, 0, env.scale, 0, 0);
+ for (let i = 0; i < 200000; i++) { const x = q() * W, y = q() * H, d = Math.hypot(x - 540, y - 520) / 740; if (q() > d * d * d * 1.1) continue; c.fillStyle = DARK; c.globalAlpha = 0.42; c.fillRect(x, y, 1.1, 1.1); }
+ for (let i = 0; i < 30000; i++) { const x = q() * W, y = q() * H, lt = q() < 0.5; c.fillStyle = lt ? "#fff5de" : "#000000"; c.globalAlpha = lt ? 0.06 : 0.08; c.fillRect(x, y, 1.1, 1.1); }
+ return L;
+};
+
+const draw = (ctx: Ctx, f: number, env: Env) => {
+ const c = ctx, s = env.scale, cam = camAt(f), pupilCol = mix(PUPIL, NIGHT, ramp(f, 312, 336));
+ c.setTransform(s, 0, 0, s, 0, 0); c.fillStyle = NIGHT; c.fillRect(0, 0, W, H);
+ if (f < 60) stars(c, f, 1 - ramp(f, 14, 52));
+ c.setTransform(s * cam.z, 0, 0, s * cam.z, s * (540 - cam.look[0] * cam.z), s * (540 - cam.look[1] * cam.z));
+ // the moon, setting; the sun, rising behind the grass with its rays opening
+ const set = ramp(f, 4, 52); if (set < 1) crescent(c, MOON[0] - set * set * 160, MOON[1] + set * set * 1000, MOON_R, PALE);
+ const rise = out3(ramp(f, 8, 74)), sy = lerp(1700, 430, rise), rays = back(ramp(f, 40, 86));
+ for (let j = 0; j < 96; j++) tuft(c, [540, sy], (j / 96) * Math.PI * 2 + f * 0.0016, 440, 440 + (80 + (j % 2) * 26) * rays, 12, j % 2 ? RUST : "#8f3a26", 0);
+ const sg = c.createRadialGradient(540, sy, 80, 540, sy, 470); sg.addColorStop(0, "#ff8a4a"); sg.addColorStop(1, CORAL); c.fillStyle = sg; c.beginPath(); c.arc(540, sy, 470, 0, Math.PI * 2); c.fill();
+ // neck and shoulders rise
+ for (const n of PARTS.neck) { const g = back(ramp(f, n.t0, n.t0 + 16)); tuft(c, [n.x, n.y - 70 + (1 - g) * 60], Math.PI / 2, 0, 150 * g, 52 * g, n.col, 0.3); }
+ ear(c, [262, 300], -1, f); ear(c, [818, 300], 1, f);
+ // the head's own mass, then the coat over it: rings of tufts from the nose outward, breathing once it is whole
+ const mass = ramp(f, 70, 132); // it spreads just under the coat as the rings open, never a bare disc
+ if (mass > 0) { c.fillStyle = "#b9731f"; c.beginPath(); c.ellipse(F[0], F[1], lerp(50, 372, mass), lerp(48, 352, mass), 0, 0, Math.PI * 2); c.fill(); }
+ c.save(); c.translate(F[0], F[1]); c.scale(1, 0.95); c.translate(-F[0], -F[1]);
+ const alive = ramp(f, 170, 200) * (1 - ramp(f, 300, 330));
+ for (const t of PARTS.coat) { const g = back(ramp(f, t.t0, t.t0 + 15)); if (g <= 0) continue; const br = 1 + 0.045 * alive * Math.sin(f * (Math.PI / 45) + t.ring * 0.9); tuft(c, F, t.a, t.r0, t.r0 + (t.r1 - t.r0) * g * br, t.w * Math.min(1, g), t.col); }
+ c.restore();
+ for (const p of PARTS.spots) { const g = back(ramp(f, p.t0, p.t0 + 9)); if (g <= 0) continue; c.fillStyle = DARK; c.beginPath(); c.ellipse(p.x, p.y, p.s * 1.12 * g, p.s * 0.94 * g, p.a, 0, Math.PI * 2); c.fill(); }
+ // the bridge of the nose: a pale fan falling from between the eyes
+ for (let i = -4; i <= 4; i++) { const g = back(ramp(f, 108 + Math.abs(i) * 2, 126 + Math.abs(i) * 2)); tuft(c, [540, 452], Math.PI / 2 + i * 0.075, 20, 20 + (194 - Math.abs(i) * 12) * g, 13 * g, i % 2 ? "#f4cd7e" : "#f8dca0", 0.18); }
+ tear(c, 1, inOut(ramp(f, 134, 162))); tear(c, -1, inOut(ramp(f, 134, 162)));
+ eye(c, EYE_L, -1, f, pupilCol, f < 290); eye(c, EYE_R, 1, f, pupilCol, true);
+ // the muzzle: two pale lobes and the chin
+ const mz = ramp(f, 124, 150);
+ for (let j = 0; j < 22; j++) { const g = back(clamp(mz * 1.5 - 0.25)); tuft(c, [540, 760], Math.PI / 2 + (j / 21 - 0.5) * 1.7, 30, 30 + 98 * g, 13 * g, j % 2 ? CREAM : PALE, 0.15); }
+ for (const sd of [-1, 1]) for (let j = 0; j < 30; j++) { const g = back(clamp(mz * 1.6 - (j / 30) * 0.5)); tuft(c, [540 + sd * 52, 742], (j / 30) * Math.PI * 2, 6, 6 + (72 + (j % 2) * 6) * g, 12 * g, j % 2 ? PALE : CREAM, 0.15); }
+ const dots = ramp(f, 150, 162); if (dots > 0) for (const sd of [-1, 1]) for (let row = 0; row < 3; row++) for (let k = 0; k < 4; k++) { c.fillStyle = "#2a1a12"; c.beginPath(); c.arc(540 + sd * (36 + k * 20 + row * 5), 742 + row * 17 - k * 3, 3.2 * dots, 0, Math.PI * 2); c.fill(); }
+ // nose, mouth, whiskers
+ const ns = back(ramp(f, 140, 154));
+ if (ns > 0) { c.save(); c.translate(540, 690); c.scale(ns, ns); c.translate(-540, -690);
+ c.fillStyle = "#1a0f0c"; c.beginPath(); c.moveTo(488, 672); c.bezierCurveTo(510, 656, 570, 656, 592, 672); c.bezierCurveTo(588, 706, 560, 728, 540, 734); c.bezierCurveTo(520, 728, 492, 706, 488, 672); c.fill();
+ c.strokeStyle = "rgba(255,245,222,0.35)"; c.lineWidth = 3; c.lineCap = "round"; c.beginPath(); c.moveTo(506, 674); c.quadraticCurveTo(540, 664, 574, 674); c.stroke(); c.restore(); }
+ const mo = ramp(f, 152, 166); if (mo > 0) { c.strokeStyle = "#1a0f0c"; c.lineWidth = 5; c.lineCap = "round"; c.beginPath(); c.moveTo(540, 732); c.lineTo(540, 732 + 36 * mo); if (mo >= 1) { const q = ramp(f, 166, 176); c.moveTo(540, 768); c.quadraticCurveTo(540 - 28 * q, 768 + 32 * q, 540 - 70 * q, 768 + 18 * q); c.moveTo(540, 768); c.quadraticCurveTo(540 + 28 * q, 768 + 32 * q, 540 + 70 * q, 768 + 18 * q); } c.stroke(); }
+ const wh = out3(ramp(f, 160, 184)); if (wh > 0) for (const sd of [-1, 1]) for (let k = 0; k < 5; k++) { const sway = Math.sin(f * (Math.PI / 60) + k) * 6 * alive, a: P = [540 + sd * 96, 742 + k * 9], m: P = [540 + sd * 250, 720 + k * 22 + sway * 0.5], e: P = [540 + sd * (400 + k * 14), 690 + k * 46 + sway]; c.strokeStyle = PALE; c.globalAlpha = 0.85; c.lineWidth = 2; c.beginPath(); c.moveTo(a[0], a[1]); for (let i = 1; i <= 16; i++) { const t = (i / 16) * wh, u = 1 - t; c.lineTo(u * u * a[0] + 2 * u * t * m[0] + t * t * e[0], u * u * a[1] + 2 * u * t * m[1] + t * t * e[1]); } c.stroke(); }
+ c.globalAlpha = 1;
+ grass(c, f, 1);
+ // screen space: the crescent carried out of the pupil to its place in the sky, and the grass coming back
+ c.setTransform(s, 0, 0, s, 0, 0);
+ if (f >= 290) { const u = ramp(f, 290, 338), e = inOut(u), from: P = [540 + (EYE_L[0] - 10 - cam.look[0]) * Math.min(cam.z, 1.6), 540 + (EYE_L[1] - 12 - cam.look[1]) * Math.min(cam.z, 1.6)]; crescent(c, lerp(from[0], MOON[0], e), lerp(from[1], MOON[1], e) - Math.sin(Math.PI * u) * 40, 9.5 * Math.pow(MOON_R / 9.5, e), PALE); }
+ if (f >= 322) { stars(c, f, ramp(f, 326, 352)); grass(c, f, inOut(ramp(f, 322, 359))); }
+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.drawImage(grainLayer(env).canvas, 0, 0);
+};
+
+// the score: four bars at 80 bpm are the film's 12 s exactly, so the loop is the music's own
+const audio = (sr: number): [Float32Array, Float32Array] => {
+ const n = Math.round((N / 30) * sr), L = new Float32Array(n), R = new Float32Array(n), m = renderLoop(cheetahDuskScore(), sr); // its tail folded back onto its start: no cut at the seam
+ for (let i = 0; i < n && i < m.L.length; i++) { L[i] = m.L[i]; R[i] = m.R[i]; }
+ return [L, R];
+};
+
+export const cheetahDusk: Film = {
+ meta: { title: "Cheetah, dusk", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu", kind: "loop", poster: 260, score: { tempo: 80, form: "4 bars, looping: pad and phrase, groove, climb, half-time home" } },
+ assets: { images: {} },
+ shots: [{ id: "cheetah", start: 0, end: N, draw }],
+ audio: Object.assign(audio, { scores: [cheetahDuskScore()] }),
+};
diff --git a/skills/anidoodle/engine/src/canvas-core/morph.ts b/skills/anidoodle/engine/src/canvas-core/morph.ts
new file mode 100644
index 0000000..93436c3
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/morph.ts
@@ -0,0 +1,94 @@
+// MORPH. One silhouette carried across a seam: the ink drop becomes the card, the seal becomes the
+// next page. The viewer follows a single object, so the next scene is not a new picture, it is what
+// that object turned into (references/motion-grammar.md, "Persistent actor"). Until now the bloom
+// and the drop were one-offs; this is the general move.
+//
+// A shape is a closed outline in screen px. A handoff takes a source shape, a target shape and the
+// frames it leaves and lands, and gives the outline at every frame between: it travels (on an arc
+// if asked), stretches a little along its own direction while it is moving, and turns into the
+// target mostly in the second half of the trip, so it reads as one thing going somewhere and then
+// becoming something. On the landing frame it is the target, point for point.
+//
+// const h = handoff({ from: circleShape([820, 300], 16), to: rectShape(240, 420, 600, 380, 28), t0: 45, t1: 80, arc: 90 });
+// h.at(f) the outline at frame f (exactly the source until t0, exactly the target from t1)
+// fillShape(ctx, env, h.at(f), INK);
+// checkShapes(h.at(80), cardOutlineOfTheNextScene); throws if the seam jumps more than 2 px
+//
+// Keep the object's colour and edge the same on both sides: a black drop that lands as a white card
+// is two objects. Pure functions of their arguments; nothing here touches the clock or Math.random.
+import type { Ctx, Env, P } from "./core";
+import { blot, clamp, inOut, lerp, ramp } from "./launchKit";
+
+export type Shape = P[];
+export const circleShape = (c: P, r: number, n = 72): Shape => Array.from({ length: n }, (_, i): P => { const a = (i / n) * Math.PI * 2; return [c[0] + Math.cos(a) * r, c[1] + Math.sin(a) * r]; });
+/** An ink blot, the bloom's wobbling rim (launchKit's `blot`). */
+export const blotShape = (c: P, r: number, seed = 88): Shape => blot(c, r, seed);
+export const rectShape = (x: number, y: number, w: number, h: number, r = 0, perCorner = 10): Shape => {
+ const q = Math.min(r, w / 2, h / 2), pts: P[] = [];
+ const corner = (cx: number, cy: number, a0: number) => { if (q <= 0) { pts.push([cx, cy]); return; } for (let i = 0; i <= perCorner; i++) { const a = a0 + (i / perCorner) * (Math.PI / 2); pts.push([cx + Math.cos(a) * q, cy + Math.sin(a) * q]); } };
+ corner(x + w - q, y + q, -Math.PI / 2); corner(x + w - q, y + h - q, 0); corner(x + q, y + h - q, Math.PI / 2); corner(x + q, y + q, Math.PI);
+ return pts;
+};
+
+const inside = (p: P, s: Shape) => { let c = false; for (let i = 0, j = s.length - 1; i < s.length; j = i++) { const a = s[i], b = s[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0]) c = !c; } return c; };
+/** The same shape, centred on the frame and grown until the whole frame (plus `pad`) is inside it: a card opening into the page. */
+export const coverShape = (s: Shape, W: number, H: number, pad = 24): Shape => {
+ const c = centreOf(s), at = (k: number) => s.map(([x, y]): P => [W / 2 + (x - c[0]) * k, H / 2 + (y - c[1]) * k]), corners: P[] = [[-pad, -pad], [W + pad, -pad], [W + pad, H + pad], [-pad, H + pad]];
+ let lo = 0, hi = 1; while (!corners.every((q) => inside(q, at(hi)))) { hi *= 2; if (hi > 1e4) throw new Error("morph: this shape cannot cover the frame (its centre must be inside it)"); }
+ for (let i = 0; i < 30; i++) { const mid = (lo + hi) / 2; if (corners.every((q) => inside(q, at(mid)))) hi = mid; else lo = mid; }
+ return at(hi);
+};
+const area = (s: Shape) => s.reduce((a, p, i) => { const q = s[(i + 1) % s.length]; return a + p[0] * q[1] - q[0] * p[1]; }, 0) / 2;
+/** The middle of a shape's bounding box: the point a handoff carries along its path. */
+export const centreOf = (s: Shape): P => { const xs = s.map((p) => p[0]), ys = s.map((p) => p[1]); return [(Math.min(...xs) + Math.max(...xs)) / 2, (Math.min(...ys) + Math.max(...ys)) / 2]; };
+/** `n` points spaced evenly along the outline, clockwise on screen, so any two shapes can be paired point for point. */
+export const resample = (shape: Shape, n = 120): Shape => {
+ const s = area(shape) < 0 ? [...shape].reverse() : shape, m = s.length, L = s.map((p, i) => Math.hypot(s[(i + 1) % m][0] - p[0], s[(i + 1) % m][1] - p[1])), tot = L.reduce((a, b) => a + b, 0);
+ if (m < 3 || tot <= 0) throw new Error("morph: a shape needs at least three points and some size");
+ const out: P[] = []; let i = 0, acc = 0;
+ for (let k = 0; k < n; k++) { const d = (k / n) * tot; while (i < m - 1 && acc + L[i] < d) acc += L[i++]; const u = L[i] ? (d - acc) / L[i] : 0, a = s[i], b = s[(i + 1) % m]; out.push([lerp(a[0], b[0], u), lerp(a[1], b[1], u)]); }
+ return out;
+};
+// the rotation of b's point order that pairs it best with a, each taken about its own centre and at its own size
+const pairUp = (a: Shape, b: Shape): Shape => {
+ const n = a.length, norm = (s: Shape) => { const c = centreOf(s), k = Math.sqrt(s.reduce((t, p) => t + (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2, 0) / n) || 1; return s.map(([x, y]): P => [(x - c[0]) / k, (y - c[1]) / k]); };
+ const A = norm(a), B = norm(b); let best = 0, bd = Infinity;
+ for (let k = 0; k < n; k++) { let d = 0; for (let i = 0; i < n && d < bd; i++) { const q = B[(i + k) % n]; d += (A[i][0] - q[0]) ** 2 + (A[i][1] - q[1]) ** 2; } if (d < bd) { bd = d; best = k; } }
+ return b.map((_, i) => b[(i + best) % n]);
+};
+
+export type HandoffSpec = {
+ from: Shape; to: Shape;
+ t0: number; t1: number; // the frame it leaves, the frame it has landed
+ arc?: number; // lifts the path between the two (px, up)
+ stretch?: number; // how much it lengthens along its travel at mid-flight (default 0.16; 0 for none)
+ turn?: [number, number]; // the part of the trip in which it becomes the target (default [0.3, 1])
+ ease?: (t: number) => number; points?: number;
+};
+/** A handoff, its shapes paired once. `at(f)` is the outline at frame f; `centre(f)` where it is. */
+export const handoff = (h: HandoffSpec) => {
+ if (!(h.t1 > h.t0)) throw new Error(`morph: the handoff lands at ${h.t1}, not after it leaves at ${h.t0}`);
+ if (h.turn && !(h.turn[1] > h.turn[0])) throw new Error(`morph: turn [${h.turn}] must end after it starts`);
+ const n = Math.max(8, Math.round(h.points ?? 160)), A = resample(h.from, n), B = pairUp(A, resample(h.to, n)), ca = centreOf(A), cb = centreOf(B), ease = h.ease ?? inOut, [m0, m1] = h.turn ?? [0.3, 1];
+ const centre = (f: number): P => { const u = ramp(f, h.t0, h.t1), e = ease(u); return [lerp(ca[0], cb[0], e), lerp(ca[1], cb[1], e) - Math.sin(Math.PI * u) * (h.arc ?? 0)]; };
+ const at = (f: number): Shape => {
+ if (f <= h.t0) return h.from; if (f >= h.t1) return h.to; // exact at both ends: the seam is the shape itself
+ const u = ramp(f, h.t0, h.t1), m = inOut(ramp(u, m0, m1)), c = centre(f), c2 = centre(f + 0.5), c1 = centre(f - 0.5), vx = c2[0] - c1[0], vy = c2[1] - c1[1], v = Math.hypot(vx, vy);
+ const k = 1 + (h.stretch ?? 0.16) * Math.sin(Math.PI * u) * clamp(v / 6) * (1 - m), dx = v ? vx / v : 1, dy = v ? vy / v : 0; // longer along the travel, thinner across it, less so as it becomes the target
+ return A.map((a, i): P => { const b = B[i], x = lerp(a[0] - ca[0], b[0] - cb[0], m), y = lerp(a[1] - ca[1], b[1] - cb[1], m), al = (x * dx + y * dy) * k, ac = (-x * dy + y * dx) / k; return [c[0] + al * dx - ac * dy, c[1] + al * dy + ac * dx]; });
+ };
+ return { at, centre, t0: h.t0, t1: h.t1 };
+};
+// distance from a point to a closed outline (its edges, not only its points)
+const toOutline = (p: P, s: Shape) => { let d = Infinity; for (let i = 0; i < s.length; i++) { const a = s[i], b = s[(i + 1) % s.length], vx = b[0] - a[0], vy = b[1] - a[1], t = clamp(((p[0] - a[0]) * vx + (p[1] - a[1]) * vy) / (vx * vx + vy * vy || 1)); d = Math.min(d, Math.hypot(p[0] - a[0] - vx * t, p[1] - a[1] - vy * t)); } return d; };
+/** The largest distance between two outlines in px: every point of each (and 240 more along it) to the other's nearest edge. */
+export const shapeGap = (a: Shape, b: Shape) => Math.max(...[...a, ...resample(a, 240)].map((p) => toOutline(p, b)), ...[...b, ...resample(b, 240)].map((p) => toOutline(p, a)));
+/** Throws unless the two sides of a seam put the outline in the same place within `tol` px. */
+export const checkShapes = (out: Shape, into: Shape, label = "handoff", tol = 2) => {
+ const g = shapeGap(out, into);
+ if (!(g <= tol)) throw new Error(`morph: ${label} jumps ${g.toFixed(1)} px at the seam; the shape must sit in the same place on both sides`);
+ return g;
+};
+export const pathShape = (ctx: Ctx, s: Shape) => { ctx.beginPath(); s.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); };
+/** The silhouette, filled, in screen px. */
+export const fillShape = (ctx: Ctx, env: Env, s: Shape, color: string) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.globalAlpha = 1; ctx.fillStyle = color; pathShape(ctx, s); ctx.fill(); };
diff --git a/skills/anidoodle/engine/src/canvas-core/morphDemo.ts b/skills/anidoodle/engine/src/canvas-core/morphDemo.ts
new file mode 100644
index 0000000..969b45a
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/morphDemo.ts
@@ -0,0 +1,36 @@
+// MORPH DEMO. One ink shape, three states, never cut (120 bpm: a beat is 15 frames).
+// 0-45 "ONE SHAPE" is written; its full stop lands as a drop of ink
+// 48-84 the full stop drops, swings in under the words, and lands as a card (the first handoff)
+// 88-138 "CARRIED" is written on the card in the paper's colour, then taken back
+// 140-172 the card opens into the whole page (the second handoff)
+// 174-240 "ACROSS THE CUT" is written on the page
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import { out3, ramp } from "./launchKit";
+import { measure, writeOn } from "./kinetic";
+import { checkShapes, circleShape, coverShape, fillShape, handoff, rectShape } from "./morph";
+
+const W = 1080, H = 1080, N = 240, PAPER = "#ece6da", INK = "#1d1a16", SIZE = 104, BASE = 330;
+const STOP: P = [W / 2 + measure("ONE SHAPE", SIZE) / 2 + 40, BASE - 15], R = 17;
+const CARD = rectShape(210, 500, 660, 400, 34), PAGE = coverShape(rectShape(210, 500, 660, 400, 34), W, H);
+const h1 = handoff({ from: circleShape(STOP, R), to: CARD, t0: 48, t1: 84, arc: -70 });
+const h2 = handoff({ from: CARD, to: PAGE, t0: 140, t1: 172, stretch: 0, turn: [0, 1] });
+checkShapes(h1.at(84), CARD, "the full stop into the card");
+checkShapes(h2.at(172), PAGE, "the card into the page");
+
+const draw = (ctx: Ctx, f: number, env: Env) => {
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER; ctx.fillRect(0, 0, W, H);
+ writeOn(ctx, env, "ONE SHAPE", W / 2, BASE, SIZE, ramp(f, 4, 32), "ink", { color: INK, align: "center", seed: 5 });
+ if (f >= 32) {
+ const pop = ramp(f, 32, 42), r = R * (out3(pop) + 0.35 * Math.sin(Math.PI * pop) * (1 - pop)); // the drop lands with a small overshoot
+ fillShape(ctx, env, f < 48 ? circleShape(STOP, r) : f < 140 ? h1.at(f) : h2.at(f), INK);
+ }
+ if (f >= 88 && f < 140) writeOn(ctx, env, "CARRIED", W / 2, 738, 88, ramp(f, 88, 112) * (1 - ramp(f, 126, 138)), "ink", { color: PAPER, align: "center", seed: 9 });
+ if (f >= 174) writeOn(ctx, env, "ACROSS THE CUT", W / 2, 580, 84, ramp(f, 174, 206), "ink", { color: PAPER, align: "center", seed: 11 });
+};
+
+export const morphDemo: Film = {
+ meta: { title: "morph · one shape carried across the seam", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu", holds: [[206, N, "the last line, read"]] },
+ assets: { images: {} },
+ shots: [{ id: "morph", start: 0, end: N, draw }],
+};
diff --git a/skills/anidoodle/engine/src/canvas-core/music/pieces/cheetah.ts b/skills/anidoodle/engine/src/canvas-core/music/pieces/cheetah.ts
new file mode 100644
index 0000000..14652a1
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/music/pieces/cheetah.ts
@@ -0,0 +1,36 @@
+// CHEETAH, DUSK: the score. Four bars at 80 bpm, exactly the film's 12 s, written to loop.
+// Chill lo-fi electronic in D major, a drifting IV-iii-vi-V: Gmaj9, F#m7, Bm9, A11.
+// BARS [film]: 1 pad and a first phrase, no drums [night, the sun comes up] · 2 the groove enters,
+// the phrase answers itself [the face makes itself] · 3 the phrase climbs, a high counter-line
+// joins [alive] · 4 half-time, the line falls back home [into the eye], and round again.
+import { type Piece } from "../plan";
+import { composePiece, type Material } from "../compose";
+
+export const cheetahDuskMaterial = (): Material => ({
+ style: "lofiElectronic", title: "Cheetah, dusk", seed: 4107, mood: "calm", bpm: 80, key: "D", mode: "major", swing: 0.55, loop: true, tail: 1.2, levels: { lead: 2.8, counter: -5, chords: -2, snare: -1.5 },
+ chords: {
+ Gmaj9: { voicing: "[B3 D4 F#4 A4]", bass: "G1:2.5 r:.5 G1:1" },
+ "F#m7": { voicing: "[A3 C#4 E4 F#4]", bass: "F#1:2.5 r:.5 C#2:1" },
+ Bm9: { voicing: "[A3 C#4 D4 F#4]", bass: "B1:2.5 r:.5 F#1:1" },
+ A11: { voicing: "[G3 B3 D4 E4]", bass: "A1:2.5 r:.5 E2:1" },
+ },
+ motifs: {
+ rise: "r:1 F#5:.5 A5:.5 B5:1.5 A5:.5",
+ answer: "r:.5 E5:.5 F#5:.5 A5:1 F#5:.5 E5:1",
+ climb: "r:1 D5:.5 F#5:.5 A5:1 B5:.5 D6:.5",
+ home: "C#6:1.5 B5:.5 A5:1 r:1",
+ rest: "r:4",
+ glint: "r:2 F#6:.5 E6:.5 D6:1",
+ settle: "r:1 E6:.5 C#6:.5 A5:2",
+ },
+ grooves: {
+ main: { kick: ["C4:1 r:.5 C4:[email protected] r:.5 C4:[email protected]"], snare: ["r:1 C4:1 r:1 C4:1"], ghost: ["r:3.5 C4:[email protected]"], hat: ["C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]"], cycle: "piece" },
+ half: { kick: ["C4:2.5 C4:[email protected]"], snare: ["r:2 C4:2"], hat: ["C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]"], cycle: "piece" },
+ },
+ sections: [
+ { kind: "intro", bars: 1, harmony: ["Gmaj9"], lead: ["rise"], chordVel: 0.8 },
+ { kind: "hook", bars: 2, harmony: ["F#m7", "Bm9"], lead: ["answer", "climb"], counter: ["rest", "glint"] },
+ { kind: "half", bars: 1, harmony: ["A11"], lead: ["home"], counter: ["settle"] },
+ ],
+});
+export const cheetahDuskScore = (): Piece => composePiece(cheetahDuskMaterial());
diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfx.ts b/skills/anidoodle/engine/src/canvas-core/music/sfx.ts
index 15a3d41..be694fe 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/sfx.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/sfx.ts
@@ -1,5 +1,5 @@
// anidoodle sound effects: the kit (sfxKit), its building blocks (sfxCore) and film placement (sfxMix).
// Docs: references/music/sound-design.md. Tool: engine/tools/sfx.mjs.
export { SFX, SFX_KINDS, sfxVariants, sfxInfo, renderSfx, validateSfx, sfxNeeds, parseKey, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";
-export { placeSfx, sfxDuck, sfxAudibility, mixSfx, assertSfxAudible, filmSfx, validateSfxPlan, resolveSfxPlan, type SfxCue, type SfxPlan, type SfxSnap, type PlacedCue, type SfxAudibility, type SfxMix } from "./sfxMix";
+export { placeSfx, sfxDuck, sfxAudibility, sfxHarshness, SFX_HARSH_CAPS, mixSfx, assertSfxAudible, filmSfx, validateSfxPlan, resolveSfxPlan, type SfxCue, type SfxPlan, type SfxSnap, type PlacedCue, type SfxAudibility, type SfxHarshOptions, type SfxHarshness, type SfxMix } from "./sfxMix";
export { type SfxStereo } from "./sfxCore";
diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts b/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts
index d756727..3bbc4f5 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts
@@ -4,12 +4,13 @@
// mix FAILS if a cue sits more than minDb under it (a cue nobody hears is a bug, not a choice).
import { renderSfx, validateSfx, sfxNeeds, SFX, SFX_KINDS, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";
import { kWeight, winLufs, mixSeed, strSeed, secs, type SfxStereo } from "./sfxCore";
-import { db } from "./dsp";
+import { Biquad, db } from "./dsp";
import { MODES } from "./theory";
import type { Piece } from "./plan";
import { loudness, truePeak } from "./meter";
export type SfxSnap = "none" | "bar" | "beat" | "8th" | "16th";
+export type SfxHarshOptions = { mode?: "report" | "throw" | "tame"; maxLiftDb?: number; maxTiltDb?: number; maxPeakDb?: number };
export type SfxCue = SfxOpts & {
/** the whole frame the sound's sync point lands on (the hit; the pass-by of a whoosh; the END of a riser). A fractional frame throws. */
frame: number; kind: SfxKind; label?: string;
@@ -19,6 +20,8 @@ export type SfxCue = SfxOpts & {
duckDb?: number;
/** audibility floor for this cue (dB vs the score); default plan.minDb ?? -6. */
minDb?: number;
+ /** Overrides plan.harsh field by field (including mode). */
+ harsh?: SfxHarshOptions;
};
export type SfxPlan = {
fps: number; frames: number; cues: SfxCue[];
@@ -35,13 +38,34 @@ export type SfxPlan = {
minDb?: number;
/** final true-peak ceiling in dBTP. Default -1. */
ceilingDb?: number;
+ /** Default report: samples stay frozen. Caps are cue-minus-score band RMS, band-minus-full RMS,
+ * and absolute sample peak dBFS. Tame scales cues only, never the score or duck envelope. */
+ harsh?: SfxHarshOptions;
};
export type PlacedCue = { i: number; cue: SfxCue; sound: SfxSound; hitS: number; snappedFromS: number; start: number; window: [number, number] };
export type SfxAudibility = { i: number; kind: SfxKind; variant: string; label: string; atS: number; cueLufs: number; musicLufs: number; marginDb: number; peakMarginDb: number; minDb: number; ok: boolean };
-export type SfxMix = { L: Float32Array; R: Float32Array; sfx: SfxStereo; music: SfxStereo; duck: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; ok: boolean; lufs: number; dbtp: number; limiterDb: number };
+export type SfxHarshness = {
+ i: number; kind: SfxKind; variant: string; label: string; atS: number;
+ cueBandDb: number; musicBandDb: number; liftDb: number | null; cueRmsDb: number; tiltDb: number;
+ peakDb: number; musicPeakDb: number; peakMarginDb: number | null; peakAtS: number; bodyDb: number; crestDb: number;
+ mode: "report" | "throw" | "tame"; maxLiftDb: number; maxTiltDb: number; maxPeakDb: number;
+ violations: { metric: "liftDb" | "tiltDb" | "peakDb"; valueDb: number; capDb: number; excessDb: number }[];
+ ok: boolean; reductionDb: number; conflict: "audibility floor" | "tilt cannot be fixed by gain" | null;
+};
+export type SfxMix = { L: Float32Array; R: Float32Array; sfx: SfxStereo; music: SfxStereo; duck: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; harshness: SfxHarshness[]; ok: boolean; lufs: number; dbtp: number; limiterDb: number };
+
+// test/sfxKitSurvey.ts: all 44 variants, default gain/seed 1, C/90 bpm, 48 kHz, silence and
+// a steady mid-level score. Maxima 16.49 / -0.80 / -1.00; margins 1.01 / 0.55 / 0.50 dB.
+export const SFX_HARSH_CAPS = Object.freeze({ maxLiftDb: 17.5, maxTiltDb: -0.25, maxPeakDb: -0.5 });
const GRID: Record<Exclude<SfxSnap, "none">, number> = { bar: 0, beat: 1, "8th": 0.5, "16th": 0.25 };
const name = (c: SfxCue, i: number) => `cue #${i} (${c.kind}${c.variant ? ":" + c.variant : ""}${c.label ? ` "${c.label}"` : ""} @ frame ${c.frame})`;
+const validateHarsh = (o: SfxHarshOptions | undefined, where: string) => {
+ if (o === undefined) return;
+ if (!o || typeof o !== "object" || Array.isArray(o)) throw new Error(`sfx plan: ${where}: harsh must be an options object`);
+ if (o.mode !== undefined && !["report", "throw", "tame"].includes(o.mode)) throw new Error(`sfx plan: ${where}: harsh.mode must be report|throw|tame`);
+ for (const key of ["maxLiftDb", "maxTiltDb", "maxPeakDb"] as const) if (o[key] !== undefined && !Number.isFinite(o[key])) throw new Error(`sfx plan: ${where}: harsh.${key} must be a finite number`);
+};
/** A plan with key / bpm / beatsPerBar filled in from its score (explicit plan values win). */
export const resolveSfxPlan = (p: SfxPlan): SfxPlan => {
@@ -59,6 +83,7 @@ export const validateSfxPlan = (plan: SfxPlan) => {
if (p.seed !== undefined && (!Number.isSafeInteger(p.seed) || p.seed < 0 || p.seed > 0xffffffff)) throw new Error(`sfx plan: seed must be an integer 0..4294967295, got ${String(p.seed)}`);
if (p.bpm !== undefined && (!Number.isFinite(p.bpm) || p.bpm < 20 || p.bpm > 300)) throw new Error(`sfx plan: bpm must be 20..300, got ${String(p.bpm)}`);
if (p.minDb !== undefined && !Number.isFinite(p.minDb)) throw new Error("sfx plan: minDb must be a finite number");
+ validateHarsh(p.harsh, "plan");
if (!Array.isArray(p.cues)) throw new Error("sfx plan: cues must be an array");
p.cues.forEach((c, i) => {
if (!c || typeof c !== "object") throw new Error(`sfx plan: cue #${i} is not an object`);
@@ -69,6 +94,7 @@ export const validateSfxPlan = (plan: SfxPlan) => {
if (!(snap === "none" || snap in GRID)) throw new Error(`sfx plan: ${name(c, i)}: snap must be none|bar|beat|8th|16th`);
if ((snap !== "none" || c.beats !== undefined) && p.bpm === undefined && c.bpm === undefined) throw new Error(`sfx plan: ${name(c, i)}: snap/beats need a bpm (plan.bpm)`);
if (c.duckDb !== undefined && (!Number.isFinite(c.duckDb) || c.duckDb < 0 || c.duckDb > 18)) throw new Error(`sfx plan: ${name(c, i)}: duckDb must be 0..18`);
+ validateHarsh(c.harsh, name(c, i));
try { validateSfx(c.kind, optsOf(p, c, 0)); } catch (e) { throw new Error(`sfx plan: ${name(c, i)}: ${(e as Error).message}`); }
const o = optsOf(p, c, 0), need = sfxNeeds(c.kind, c.variant ?? SFX[c.kind].variants[0], o);
if (need.key && o.key === undefined) throw new Error(`sfx plan: ${name(c, i)} is tuned: set plan.key, cue.key, or plan.score (the film's piece); there is no default key`);
@@ -142,6 +168,49 @@ export const sfxAudibility = (placed: PlacedCue[], music: SfxStereo, sr: number,
});
};
+// Measurement only: RBJ 2nd-order Butterworth HP at 2 kHz then LP at 8 kHz, zero state,
+// Float64 throughout, run from buffer start (not reset at the speaking window). No K weighting.
+const presence = (x: Float32Array, sr: number) => {
+ const hp = Biquad.make(sr, "hp", 2000, Math.SQRT1_2), lp = Biquad.make(sr, "lp", 8000, Math.SQRT1_2), out = new Float64Array(x.length);
+ for (let i = 0; i < x.length; i++) out[i] = lp.tick(hp.tick(x[i]));
+ return out;
+};
+// Stereo mean power: a duplicated mono sine has its ordinary RMS dBFS, not +3 dB.
+// A body window is always the full 150 ms; a short tail contributes zero after its end.
+const rmsDb = (L: ArrayLike<number>, R: ArrayLike<number>, a: number, b: number, pad = false) => {
+ const lo = Math.max(0, a), hi = Math.min(L.length, b); let e = 0;
+ for (let i = lo; i < hi; i++) e += L[i] * L[i] + R[i] * R[i];
+ return 10 * Math.log10(Math.max(e / (2 * Math.max(1, pad ? b - a : hi - lo)), 1e-20));
+};
+const peakOf = (L: Float32Array, R: Float32Array, a: number, b: number) => {
+ let peak = 0, at = Math.max(0, a);
+ for (let i = Math.max(0, a); i < Math.min(L.length, b); i++) { const v = Math.max(Math.abs(L[i]), Math.abs(R[i])); if (v > peak) { peak = v; at = i; } }
+ return { db: 20 * Math.log10(Math.max(peak, 1e-12)), at };
+};
+
+/** Pre-master cue harshness vs the ducked score. Score windows match sfxAudibility's 100 ms
+ * minimum. Silence-relative measurements are null below -70 dBFS; levels have a -200 dB RMS /
+ * -240 dB peak numeric floor. The body starts one sample AFTER the first largest window peak. */
+export const sfxHarshness = (placed: PlacedCue[], music: SfxStereo, sr: number, p: Pick<SfxPlan, "minDb" | "harsh">): SfxHarshness[] => {
+ if (!placed.length) return [];
+ const mL = presence(music[0], sr), mR = presence(music[1], sr), minWin = secs(sr, 0.1);
+ return placed.map((pc) => {
+ const s = pc.sound, [wa, wb] = s.window, cueBandDb = rmsDb(presence(s.L, sr), presence(s.R, sr), wa, wb), cueRmsDb = rmsDb(s.L, s.R, wa, wb);
+ let [a, b] = pc.window; if (b - a < minWin) { const c = (a + b) >> 1; a = c - (minWin >> 1); b = a + minWin; }
+ const musicBandDb = rmsDb(mL, mR, a, b), peak = peakOf(s.L, s.R, wa, wb), musicPeakDb = peakOf(music[0], music[1], a, b).db;
+ const bodyDb = rmsDb(s.L, s.R, peak.at + 1, peak.at + 1 + secs(sr, 0.15), true);
+ const o = pc.cue.harsh, mode = o?.mode ?? p.harsh?.mode ?? "report", maxLiftDb = o?.maxLiftDb ?? p.harsh?.maxLiftDb ?? SFX_HARSH_CAPS.maxLiftDb,
+ maxTiltDb = o?.maxTiltDb ?? p.harsh?.maxTiltDb ?? SFX_HARSH_CAPS.maxTiltDb, maxPeakDb = o?.maxPeakDb ?? p.harsh?.maxPeakDb ?? SFX_HARSH_CAPS.maxPeakDb;
+ const liftDb = musicBandDb < -70 ? null : cueBandDb - musicBandDb, tiltDb = cueBandDb - cueRmsDb, violations: SfxHarshness["violations"] = [];
+ for (const [metric, valueDb, capDb] of [["liftDb", liftDb, maxLiftDb], ["tiltDb", tiltDb, maxTiltDb], ["peakDb", peak.db, maxPeakDb]] as const)
+ if (valueDb !== null && valueDb > capDb) violations.push({ metric, valueDb, capDb, excessDb: valueDb - capDb });
+ return { i: pc.i, kind: pc.cue.kind, variant: s.variant, label: pc.cue.label ?? "", atS: pc.hitS,
+ cueBandDb, musicBandDb, liftDb, cueRmsDb, tiltDb,
+ peakDb: peak.db, musicPeakDb, peakMarginDb: musicPeakDb < -70 ? null : peak.db - musicPeakDb, peakAtS: (pc.start + peak.at) / sr, bodyDb, crestDb: peak.db - bodyDb,
+ mode, maxLiftDb, maxTiltDb, maxPeakDb, violations, ok: !violations.length, reductionDb: 0, conflict: null };
+ });
+};
+
/**
* The whole film's sound: score (any length; padded or cut to the film) ducked under the cues,
* effects added, one true-peak ceiling. `music` null = effects only. Does not throw on an inaudible
@@ -149,17 +218,38 @@ export const sfxAudibility = (placed: PlacedCue[], music: SfxStereo, sr: number,
*/
export const mixSfx = (music: SfxStereo | null, p: SfxPlan, sr = 48000): SfxMix => {
const n = Math.round((p.frames / p.fps) * sr), placed = placeSfx(p, sr);
- const fxL = new Float32Array(n), fxR = new Float32Array(n);
- for (const pc of placed) { const { L, R } = pc.sound; for (let i = 0; i < L.length && pc.start + i < n; i++) { fxL[pc.start + i] += L[i]; fxR[pc.start + i] += R[i]; } }
const duck = sfxDuck(placed, n, sr, p.duck), mL = new Float32Array(n), mR = new Float32Array(n);
if (music) { const m = Math.min(n, music[0].length); for (let i = 0; i < m; i++) { mL[i] = music[0][i] * duck[i]; mR[i] = music[1][i] * duck[i]; } }
+ let harshness = sfxHarshness(placed, [mL, mR], sr, p);
+ const changes = new Map<number, { reductionDb: number; conflict: SfxHarshness["conflict"] }>();
+ if (harshness.some((h) => h.mode === "tame" && !h.ok)) {
+ const aud = sfxAudibility(placed, [mL, mR], sr, p);
+ for (let i = 0; i < placed.length; i++) {
+ const h = harshness[i]; if (h.mode !== "tame" || h.ok) continue;
+ // Gain cannot change spectral tilt. Leave this cue untouched, even if another cap broke.
+ if (h.violations.some((v) => v.metric === "tiltDb")) { changes.set(h.i, { reductionDb: 0, conflict: "tilt cannot be fixed by gain" }); continue; }
+ const a = aud[i], excess = Math.max(...h.violations.map((v) => v.excessDb)), room = a.musicLufs < -70 ? Infinity : Math.max(0, a.marginDb - a.minDb - 1e-5);
+ // Float32 scaling can move a measurement by a few ulps: stay just inside both boundaries.
+ const down = a.ok ? Math.min(excess + 1e-5, room) : 0, pc = placed[i], g = db(-down);
+ if (down > 0) {
+ for (let j = 0; j < pc.sound.L.length; j++) { pc.sound.L[j] *= g; pc.sound.R[j] *= g; }
+ pc.sound.lufs -= down; pc.cue = { ...pc.cue, gainDb: (pc.cue.gainDb ?? 0) - down };
+ }
+ changes.set(h.i, { reductionDb: down, conflict: down < excess ? "audibility floor" : null });
+ }
+ harshness = sfxHarshness(placed, [mL, mR], sr, p).map((h) => ({ ...h, ...changes.get(h.i) }));
+ }
+ const bad = harshness.filter((h) => h.mode === "throw" && !h.ok);
+ if (bad.length) throw new Error(`sfx: ${bad.length} harsh cue(s):\n` + bad.map((h) => ` #${h.i} ${h.kind}:${h.variant}${h.label ? ` "${h.label}"` : ""} @ ${h.atS.toFixed(2)} s: ` + h.violations.map((v) => `${v.metric} ${v.valueDb.toFixed(2)} dB (cap ${v.capDb} dB, excess ${v.excessDb.toFixed(2)} dB)`).join(", ")).join("\n"));
+ const fxL = new Float32Array(n), fxR = new Float32Array(n);
+ for (const pc of placed) { const { L, R } = pc.sound; for (let i = 0; i < L.length && pc.start + i < n; i++) { fxL[pc.start + i] += L[i]; fxR[pc.start + i] += R[i]; } }
const L = new Float32Array(n), R = new Float32Array(n);
for (let i = 0; i < n; i++) { L[i] = mL[i] + fxL[i]; R[i] = mR[i] + fxR[i]; }
const limiterDb = ceiling(L, R, sr, db((p.ceilingDb ?? -1) - 0.3));
const fade = Math.min(n, secs(sr, 0.015)); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }
const audibility = sfxAudibility(placed, [mL, mR], sr, p);
const lu = n >= secs(sr, 0.4) ? loudness([L, R], sr).integrated : NaN;
- return { L, R, sfx: [fxL, fxR], music: [mL, mR], duck, placed, audibility, ok: audibility.every((a) => a.ok), lufs: lu, dbtp: truePeak([L, R]).dbtp, limiterDb };
+ return { L, R, sfx: [fxL, fxR], music: [mL, mR], duck, placed, audibility, harshness, ok: audibility.every((a) => a.ok), lufs: lu, dbtp: truePeak([L, R]).dbtp, limiterDb };
};
export const assertSfxAudible = (m: SfxMix) => {
diff --git a/skills/anidoodle/engine/src/canvas-core/transitions.ts b/skills/anidoodle/engine/src/canvas-core/transitions.ts
new file mode 100644
index 0000000..5bdf4a3
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/transitions.ts
@@ -0,0 +1,135 @@
+// TRANSITIONS. Three seams every film used to hand-roll, as reusable calls: a brush wipe, an iris,
+// and a flash on a cut. Each takes the two scenes as draw functions and a progress, at any frame
+// size, and is a pure function of its arguments (the brush's bristles come from rng(seed), never
+// from the clock). A gentle move stays the default seam (references/workflows/launch-video.md,
+// Motion); which of these fits a seam, and when none does, is references/motion-grammar.md.
+//
+// const p = seam(local, 120, 22); progress 0..1 over frames 120-142
+// brushWipe(ctx, env, p, drawA, drawB, { angle: -0.2, ink: "#1d1a16" });
+// iris(ctx, env, p, drawA, drawB, { center: [1400, 300] }); opens on B from a point
+// iris(ctx, env, p, drawA, drawB, { close: true }); closes on A, B is behind it
+// flashCut(ctx, env, local, 240, drawA, drawB); A until 240, B from 240
+// checkFlashes([240, 400], fps); throws if they could strobe
+//
+// A scene is drawn in its own coordinates: it sets its transform itself, as every film's shots do.
+// The incoming scene is already complete under the seam on every frame, so there is never an empty
+// frame between two scenes. At p <= 0 only the outgoing scene is drawn, at p >= 1 only the incoming.
+import { rng, type Ctx, type Env, type P } from "./core";
+import { blot, clamp, inOut, lerp, pathOf, ramp, selfLayer } from "./launchKit";
+
+export type Scene = (ctx: Ctx) => void;
+/** Progress of a seam that starts at frame `at` and lasts `len` frames. */
+export const seam = (local: number, at: number, len: number) => (len > 0 ? ramp(local, at, at + len) : local >= at ? 1 : 0);
+
+// the incoming scene on its own full-frame surface, then set down through a clip in logical units
+const through = (ctx: Ctx, env: Env, key: string, scene: Scene, clip: () => void, rim?: () => void) => {
+ const L = selfLayer(env, `seam:${key}`, Math.round(env.W * env.scale), Math.round(env.H * env.scale));
+ const lc = L.ctx as Ctx & { reset?: () => void }; // a clean context every frame: nothing a scene left behind may reach the next one
+ if (typeof lc.reset === "function") lc.reset(); else { lc.globalAlpha = 1; lc.globalCompositeOperation = "source-over"; lc.setLineDash([]); lc.shadowBlur = 0; }
+ scene(L.ctx);
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
+ ctx.save(); rim?.(); clip(); ctx.clip();
+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(L.canvas, 0, 0); ctx.restore();
+};
+
+// ---------------------------------------------------------------- brush wipe
+// A loaded flat brush pulled across the frame. Two edges, both the brush's own: the incoming
+// picture's edge, and ahead of it the front of the wet ink the brush carries (`ink`; leave it out
+// for a clean edge). Each is a row of fine bristles of uneven width following a slow curve, each
+// bristle a little ahead of or behind its neighbour. A few bristles are loaded and streak well
+// ahead of the ink; a few drag, and leave a thread of ink over the new picture for a moment. The
+// two edges have different profiles, so the ink between them is thick here and thin there, as a
+// stroke is. The bristles splay in the middle of the stroke and close up where it starts and lands.
+export type WipeOpts = {
+ angle?: number; // direction of travel in radians: 0 left to right, PI/2 top to bottom
+ seed?: number;
+ bristles?: number; // how many across the stroke (default 96)
+ ragged?: number; // how far the bristle tips vary, in logical px (default 5% of the frame's diagonal)
+ stray?: number; // share of bristles that streak ahead (ink) or drag behind (picture) (default 0.1)
+ ink?: string; band?: number; // the wet ink's colour and its mean width (default 1.1 x ragged)
+ ease?: (t: number) => number;
+};
+const STRAY = 2.4; // a stray bristle runs up to this many times `ragged` from the edge
+const smooth = (t: number) => t * t * (3 - 2 * t);
+/** One edge of the stroke as the polygon of everything behind it, in logical px (pure): the incoming picture's, or the ink's. */
+export const wipeFront = (p: number, W: number, H: number, o: WipeOpts = {}, edge: "picture" | "ink" = "picture"): P[] => {
+ const a = o.angle ?? 0, dx = Math.cos(a), dy = Math.sin(a), n = Math.max(1, Math.round(o.bristles ?? 96)), rag = o.ragged ?? Math.hypot(W, H) * 0.05, band = o.ink ? o.band ?? rag * 1.1 : 0, ink = edge === "ink";
+ const cs: P[] = [[0, 0], [W, 0], [W, H], [0, H]], S = cs.map(([x, y]) => x * dx + y * dy), T = cs.map(([x, y]) => -x * dy + y * dx);
+ const s0 = Math.min(...S), s1 = Math.max(...S), t0 = Math.min(...T) - 4, t1 = Math.max(...T) + 4, back = s0 - 8;
+ const e = clamp((o.ease ?? smooth)(clamp(p))), splay = 0.4 + 0.6 * Math.sin(Math.PI * e), base = lerp(s0 - band - rag * (0.4 * (1 + STRAY) + 0.1), s1 + rag * STRAY, e);
+ const r = rng((o.seed ?? 31) + (ink ? 101 : 0)), ph = [r() * 6.28, r() * 6.28, r() * 6.28], stray = o.stray ?? 0.1;
+ // bristle widths and reaches, fixed for the whole stroke: the profile of one brush
+ const br = Array.from({ length: n }, (_, i) => {
+ const u = i / n, body = clamp(0.5 + 0.3 * Math.sin(u * 5.1 + ph[0]) + 0.16 * Math.sin(u * 13.7 + ph[1]) + 0.07 * Math.sin(u * 41 + ph[2]) + (r() - 0.5) * 0.16), st = r() < stray, far = 0.5 + r() * (STRAY - 0.5);
+ return { w: st ? 0.35 + r() * 0.3 : 0.6 + r() * 0.8, reach: st ? (ink ? body + far : body - far) : body };
+ });
+ const tot = br.reduce((s, b) => s + b.w, 0), at = (s: number, t: number): P => [s * dx - t * dy, s * dy + t * dx];
+ const pts: P[] = [at(back, t0)];
+ let t = t0;
+ for (const b of br) { const w = (b.w / tot) * (t1 - t0), f = Math.max(back, base + b.reach * rag * splay + (ink ? band : 0)); pts.push(at(f, t), at(f, t + w)); t += w; } // square-ended: bristle marks
+ pts.push(at(back, t1));
+ return pts;
+};
+export const brushWipe = (ctx: Ctx, env: Env, p: number, from: Scene, to: Scene, o: WipeOpts = {}) => {
+ if (p >= 1) { to(ctx); return; }
+ from(ctx);
+ if (!(p > 0)) return; // before the seam, or not a number: the outgoing scene, whole
+ const W = env.W, H = env.H;
+ through(ctx, env, "wipe", to, () => pathOf(ctx, wipeFront(p, W, H, o)), o.ink ? () => { pathOf(ctx, wipeFront(p, W, H, o, "ink")); ctx.fillStyle = o.ink!; ctx.fill(); } : undefined);
+};
+
+// ---------------------------------------------------------------- iris
+// A round opening that grows from a point until the incoming scene fills the frame, or (`close`)
+// shrinks to a point on the outgoing one. Open it from the thing the next scene is about, close it
+// on the thing this scene was about: an iris centred on nothing is only a shape. "blot" gives the
+// ink bloom's wobbling rim instead of a clean circle; `rim` is the edge's width in `ink`.
+export type IrisOpts = { center?: P; close?: boolean; shape?: "circle" | "blot"; rim?: number; ink?: string; seed?: number; ease?: (t: number) => number };
+/** The opening's radius in logical px (pure): 0 at p = 0, past the farthest corner at p = 1 (the reverse with `close`). */
+export const irisRadius = (p: number, W: number, H: number, o: IrisOpts = {}) => {
+ const [cx, cy] = o.center ?? [W / 2, H / 2], far = Math.max(Math.hypot(cx, cy), Math.hypot(W - cx, cy), Math.hypot(cx, H - cy), Math.hypot(W - cx, H - cy));
+ const e = clamp((o.ease ?? inOut)(clamp(p))), full = (far + (o.rim ?? 0) + 2) / (o.shape === "blot" ? 0.86 : 1); // a blot's rim dips to 0.9 R
+ return full * (o.close ? 1 - e : e);
+};
+/** The ink rim's width at an opening of radius R (pure): it grows with the opening, so it never appears or vanishes in one frame. */
+export const irisRim = (R: number, o: IrisOpts = {}) => (o.rim ?? (o.shape === "blot" ? 22 : 0)) * clamp(R / 70);
+export const iris = (ctx: Ctx, env: Env, p: number, from: Scene, to: Scene, o: IrisOpts = {}) => {
+ if (p >= 1) { to(ctx); return; }
+ if (!(p > 0)) { from(ctx); return; }
+ const W = env.W, H = env.H, c: P = o.center ?? [W / 2, H / 2], R = irisRadius(p, W, H, o), rim = irisRim(R, o);
+ const edge = (r: number) => { if (o.shape === "blot") pathOf(ctx, blot(c, Math.max(0, r), o.seed ?? 88)); else { ctx.beginPath(); ctx.arc(c[0], c[1], Math.max(0, r), 0, Math.PI * 2); } };
+ // opening: B grows inside the hole over A. closing: A shrinks inside the hole over B.
+ const [outer, inner] = o.close ? [to, from] : [from, to];
+ outer(ctx);
+ if (R < 1) return;
+ through(ctx, env, "iris", inner, () => edge(R - (rim > 0 ? 3 : 0)), rim > 0 ? () => { edge(R + rim); ctx.fillStyle = o.ink ?? "#1d1a16"; ctx.fill(); } : undefined);
+};
+
+// ---------------------------------------------------------------- flash
+// A cut hidden under a burst of light: the frame lifts toward `color` over `inF` frames, the scene
+// changes on the brightest frame, and the light falls away over `outF`. It is a hard cut, so the
+// hard cut's conditions apply (a strong beat, in a piece whose energy asks for it), and it is the
+// one seam here that can hurt: a flash is never a single frame, never full white by default, and
+// never repeated quickly: two flashes are at least half a second apart, which also keeps a film
+// well under three a second. checkFlashes holds a film to that.
+export type FlashOpts = { color?: string; peak?: number; inF?: number; outF?: number };
+const FLASH = { color: "#fff8ea", peak: 0.86, inF: 2, outF: 9 };
+/** The light's opacity at a frame (pure): `peak` on the cut frame, 0 outside [cut - inF, cut + outF). */
+export const flashAlpha = (local: number, cut: number, o: FlashOpts = {}) => {
+ const peak = o.peak ?? FLASH.peak, inF = o.inF ?? FLASH.inF, outF = o.outF ?? FLASH.outF;
+ if (inF < 1 || outF < 3) throw new Error(`flash: inF ${inF}, outF ${outF}: the light must rise over at least 1 frame and fall over at least 3 (a one-frame flash is a fault, not a transition)`);
+ if (local <= cut - inF - 1 || local >= cut + outF) return 0;
+ const k = local < cut ? (local - (cut - inF - 1)) / (inF + 1) : Math.pow(1 - (local - cut) / outF, 2);
+ return clamp(peak) * clamp(k);
+};
+/** The light alone, over whatever is already drawn (when the film switches the scene itself). */
+export const flash = (ctx: Ctx, env: Env, local: number, cut: number, o: FlashOpts = {}) => {
+ const a = flashAlpha(local, cut, o); if (a <= 0) return;
+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.globalCompositeOperation = "source-over"; ctx.globalAlpha = a; ctx.fillStyle = o.color ?? FLASH.color; ctx.fillRect(0, 0, env.W, env.H); ctx.globalAlpha = 1;
+};
+export const flashCut = (ctx: Ctx, env: Env, local: number, cut: number, from: Scene, to: Scene, o: FlashOpts = {}) => { (local < cut ? from : to)(ctx); flash(ctx, env, local, cut, o); };
+/** Throws when a film's flashes could strobe: any two closer than half a second. */
+export const checkFlashes = (cuts: number[], fps: number) => {
+ const c = [...cuts].sort((a, b) => a - b);
+ for (let i = 1; i < c.length; i++) if (c[i] - c[i - 1] < fps / 2) throw new Error(`flash: frames ${c[i - 1]} and ${c[i]} are ${((c[i] - c[i - 1]) / fps).toFixed(2)} s apart: leave at least half a second between flashes`);
+ return cuts;
+};
diff --git a/skills/anidoodle/engine/src/canvas-core/transitionsDemo.ts b/skills/anidoodle/engine/src/canvas-core/transitionsDemo.ts
new file mode 100644
index 0000000..be44397
--- /dev/null
+++ b/skills/anidoodle/engine/src/canvas-core/transitionsDemo.ts
@@ -0,0 +1,39 @@
+// TRANSITIONS DEMO. The three seams of transitions.ts, each once, between four finished plates
+// (120 bpm: a beat is 15 frames). Every plate creeps in a little while it is held, so nothing sits still.
+// 0-30 the lighthouse
+// 26-56 BRUSH WIPE, a loaded ink brush pulled across and slightly down, onto the fox
+// 100-126 IRIS, an ink blot opening from the fox's eye onto the koi
+// 170-194 IRIS closing to a clean round point on the koi's eye; the balloon is behind it
+// 240 FLASH on the cut back to the lighthouse; frame 299 hands over to frame 0
+import type { Ctx, Env, P } from "./core";
+import type { Film } from "./film";
+import { plateLayer } from "./launchKit";
+import { brushWipe, checkFlashes, flashCut, iris, seam, type Scene } from "./transitions";
+import { lighthouse } from "./lighthouse";
+import { fox } from "./fox";
+import { koi } from "./koi";
+import { balloon } from "./balloon";
+
+const W = 1080, H = 1080, N = 300, INK = "#1d1a16";
+const FOX_EYE: P = [596, 466], KOI_EYE: P = [690, 420];
+checkFlashes([240], 30);
+
+// a plate, held: it fills the frame and creeps in by 4% from frame `a` to frame `b`
+const plate = (env: Env, key: string, film: Film, f: number, a: number, b: number): Scene => (c: Ctx) => {
+ const L = plateLayer(env, `seamdemo:${key}`, film, 0, Math.round(W * env.scale), true).canvas, z = 1 + 0.04 * Math.max(0, Math.min(1, (f - a) / (b - a))), s = W * env.scale;
+ c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.drawImage(L, (s - s * z) / 2, (s - s * z) / 2, s * z, s * z);
+};
+
+const draw = (ctx: Ctx, f: number, env: Env) => {
+ const light = plate(env, "light", lighthouse, f < 150 ? f : f - 300, -60, 56), foxS = plate(env, "fox", fox, f, 30, 126), koiS = plate(env, "koi", koi, f, 100, 194), bal = plate(env, "balloon", balloon, f, 170, 240);
+ if (f < 56) brushWipe(ctx, env, seam(f, 26, 30), light, foxS, { angle: 0.22, ink: INK, seed: 31 });
+ else if (f < 126) iris(ctx, env, seam(f, 100, 26), foxS, koiS, { center: FOX_EYE, shape: "blot", ink: INK });
+ else if (f < 194) iris(ctx, env, seam(f, 170, 24), koiS, bal, { center: KOI_EYE, close: true, rim: 10, ink: INK });
+ else flashCut(ctx, env, f, 240, bal, light);
+};
+
+export const transitionsDemo: Film = {
+ meta: { title: "transitions · brush wipe, iris, flash", W, H, fps: 30, bpm: 120, durationFrames: N, raster: "cpu" },
+ assets: { images: {} },
+ shots: [{ id: "seams", start: 0, end: N, draw }],
+};
diff --git a/skills/anidoodle/engine/src/hosts/page-calloutDemo.ts b/skills/anidoodle/engine/src/hosts/page-calloutDemo.ts
new file mode 100644
index 0000000..5d14c3e
--- /dev/null
+++ b/skills/anidoodle/engine/src/hosts/page-calloutDemo.ts
@@ -0,0 +1,4 @@
+import { calloutDemo } from "../canvas-core/calloutDemo";
+import { mountFilm } from "./page";
+
+mountFilm(calloutDemo);
diff --git a/skills/anidoodle/engine/src/hosts/page-cheetahDusk.ts b/skills/anidoodle/engine/src/hosts/page-cheetahDusk.ts
new file mode 100644
index 0000000..e34f643
--- /dev/null
+++ b/skills/anidoodle/engine/src/hosts/page-cheetahDusk.ts
@@ -0,0 +1,4 @@
+import { cheetahDusk } from "../canvas-core/cheetahDusk";
+import { mountFilm } from "./page";
+
+mountFilm(cheetahDusk);
diff --git a/skills/anidoodle/engine/src/hosts/page-morphDemo.ts b/skills/anidoodle/engine/src/hosts/page-morphDemo.ts
new file mode 100644
index 0000000..b25a3d4
--- /dev/null
+++ b/skills/anidoodle/engine/src/hosts/page-morphDemo.ts
@@ -0,0 +1,4 @@
+import { morphDemo } from "../canvas-core/morphDemo";
+import { mountFilm } from "./page";
+
+mountFilm(morphDemo);
diff --git a/skills/anidoodle/engine/src/hosts/page-transitionsDemo.ts b/skills/anidoodle/engine/src/hosts/page-transitionsDemo.ts
new file mode 100644
index 0000000..ac31725
--- /dev/null
+++ b/skills/anidoodle/engine/src/hosts/page-transitionsDemo.ts
@@ -0,0 +1,4 @@
+import { transitionsDemo } from "../canvas-core/transitionsDemo";
+import { mountFilm } from "./page";
+
+mountFilm(transitionsDemo);
diff --git a/skills/anidoodle/engine/test/callout.test.ts b/skills/anidoodle/engine/test/callout.test.ts
new file mode 100644
index 0000000..9142425
--- /dev/null
+++ b/skills/anidoodle/engine/test/callout.test.ts
@@ -0,0 +1,82 @@
+// CALLOUT TESTS. calloutPose, calloutReady, leaderPath and checkHandoff in
+// src/canvas-core/callout.ts are pure and are held to numbers here. drawCallout and drawLabel
+// draw through kinetic.ts (writeOn / setType) and are not covered. node tools/test.mjs
+import { CALLOUT_T, calloutPose, calloutReady, checkHandoff, leaderPath, type Callout, type LabelPose } from "../src/canvas-core/callout";
+import type { P } from "../src/canvas-core/core";
+
+export const name = "callout";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
+ const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
+ const dist = (a: P, b: P) => Math.hypot(a[0] - b[0], a[1] - b[1]);
+ const anchor = (): P => [500, 600];
+ const base: Callout = { text: "LIVE PREVIEW", anchor, label: { p: [1000, 300], size: 40 }, t0: 60 };
+ const same = (a: LabelPose | null, b: LabelPose) => !!a && near(a.p[0], b.p[0]) && near(a.p[1], b.p[1]) && near(a.size, b.size);
+
+ // 1. calloutPose: null before t0, the label's own pose until a handoff leaves, exactly the
+ // destination pose on `at`
+ ok(calloutPose(base, 0) === null && calloutPose(base, 59) === null, "calloutPose is null before t0");
+ ok(same(calloutPose(base, 60), base.label) && same(calloutPose({ ...base, out: 100 }, 500), base.label), "without a handoff the pose is the label's, leaving included");
+ const hc: Callout = { ...base, handoff: { leave: 120, at: 150, pose: { p: [200, 800], size: 80 }, arc: 60 } };
+ ok(same(calloutPose(hc, 120), base.label), "until leave the pose is still the label's");
+ const landed = calloutPose(hc, 150)!;
+ ok(near(landed.p[0], 200) && near(landed.p[1], 800) && near(landed.size, 80), "on the handoff frame the pose is exactly the next scene's heading");
+ const mid = calloutPose(hc, 135)!; // u = 0.5 -> e = 0.5
+ ok(near(mid.p[0], 600) && near(mid.p[1], 550 - 60, 1e-6), "mid-handoff the label sits on the eased midpoint, lifted by the arc");
+ ok(near(mid.size, Math.sqrt(40 * 80)), `size is eased as a ratio (${mid.size.toFixed(1)} = the geometric mean, not 60)`);
+
+ // 2. calloutReady: the frame the label is fully written
+ ok(calloutReady(base) === 60 + CALLOUT_T.text[1] && calloutReady(base) === 90, "calloutReady is t0 + the text's write-on time");
+
+ // 3. leaderPath, both registers, label to the right and to the left of the anchor
+ const pose: LabelPose = { p: [1000, 300], size: 40 }, w = 300, dot = pose.size * 0.16;
+ const drawn = leaderPath(anchor(), pose, w, "drawn");
+ ok(drawn.length === 25, "a drawn leader is a 25-point bowed stroke");
+ ok(near(dist(drawn[0], anchor()), dot * 2.2), "the drawn line starts off the anchor by the dot gap");
+ ok(near(drawn[24][0], 1000 - 40 * 0.35) && near(drawn[24][1], 300 - 40 * 0.42), "the drawn line ends at the label");
+ const chord: P = [(drawn[0][0] + drawn[24][0]) / 2, (drawn[0][1] + drawn[24][1]) / 2];
+ ok(dist(chord, drawn[12]) > 2, `the drawn line bows off its chord (${dist(chord, drawn[12]).toFixed(1)} px)`);
+ const drawnL = leaderPath([1500, 600], pose, w, "drawn");
+ ok(near(drawnL[24][0], 1000 + w + 40 * 0.35), "label left of the thing: the drawn line lands on its right edge");
+
+ const clean = leaderPath(anchor(), pose, w, "clean");
+ ok(clean.length === 3, "a clean leader is an elbow and an underline");
+ ok(near(dist(clean[0], anchor()), dot * 2), "the clean line starts off the anchor by the dot gap");
+ ok(clean[1][1] === clean[2][1] && near(clean[1][1], 300 + 40 * 0.34), "the underline is horizontal, just under the baseline");
+ ok(clean[1][0] <= 1000 && clean[2][0] >= 1300, "the underline spans the label's whole width");
+ const cleanL = leaderPath([1500, 600], pose, w, "clean");
+ ok(near(cleanL[1][0], 1000 + w + 40 * 0.1) && near(cleanL[2][0], 1000 - 40 * 0.1), "label left of the thing: the elbow meets its right edge and the underline runs left");
+
+ // 4. checkHandoff: a matching pose passes; a 5 px miss, an early leave, or a backwards
+ // window all throw
+ ok(checkHandoff(hc, hc.handoff!.pose).every((g) => g.dp < 1e-6 && g.dr < 1e-6), "a matching pose passes within tolerance");
+ ok(throws(() => checkHandoff(hc, { p: [205, 800], size: 80 })), "a 5 px miss throws");
+ ok(throws(() => checkHandoff(hc, { p: [200, 800], size: 84 })), "a 4 px size miss throws");
+ const early: Callout = { ...base, handoff: { leave: 80, at: 150, pose: { p: [200, 800], size: 80 } } };
+ ok(throws(() => checkHandoff(early, { p: [200, 800], size: 80 })), "leaving at 80, before the label is readable at 90, throws");
+ const back: Callout = { ...base, handoff: { leave: 160, at: 150, pose: { p: [200, 800], size: 80 } } };
+ ok(throws(() => checkHandoff(back, { p: [200, 800], size: 80 })), "landing before it leaves throws");
+ ok(throws(() => checkHandoff(base, { p: [0, 0], size: 10 })), "a callout with no handoff has nothing to check: throws");
+
+ // 5. checkHandoff needs the dot and line's CALLOUT_T.leave frames to retract: a shorter
+ // trip throws even when the pose matches, exactly CALLOUT_T.leave frames is legal
+ const tight: Callout = { ...base, handoff: { leave: 130, at: 141, pose: { p: [200, 800], size: 80 } } };
+ ok(throws(() => checkHandoff(tight, { p: [200, 800], size: 80 })), `a handoff trip under ${CALLOUT_T.leave} frames throws even with a matching pose`);
+ const just: Callout = { ...base, handoff: { leave: 130, at: 130 + CALLOUT_T.leave, pose: { p: [200, 800], size: 80 } } };
+ ok(!throws(() => checkHandoff(just, { p: [200, 800], size: 80 })), `a trip of exactly ${CALLOUT_T.leave} frames is legal`);
+
+ // 6. calloutPose with a size of 0 on either side falls back to a linear ease: finite numbers
+ const zeroA: Callout = { ...base, label: { p: [1000, 300], size: 0 }, handoff: { leave: 120, at: 150, pose: { p: [200, 800], size: 80 } } };
+ const zeroB: Callout = { ...base, handoff: { leave: 120, at: 150, pose: { p: [200, 800], size: 0 } } };
+ for (const c of [zeroA, zeroB]) for (const f of [120, 135, 149, 150]) {
+ const p = calloutPose(c, f)!;
+ ok(Number.isFinite(p.p[0]) && Number.isFinite(p.p[1]) && Number.isFinite(p.size), `a size of 0 gives finite numbers through the handoff (f=${f})`);
+ }
+ ok(near(calloutPose(zeroA, 135)!.size, 40), "0 -> 80 eases linearly through 40 at the midpoint");
+
+ // 7. leaderPath's `side` pins which edge the line meets, wherever the anchor sits
+ ok(near(leaderPath([500, 600], pose, w, "drawn", undefined, false)[24][0], 1000 + w + 40 * 0.35), "side=false: the drawn line meets the label's right edge though the anchor is left of it");
+ ok(near(leaderPath([1500, 600], pose, w, "drawn", undefined, true)[24][0], 1000 - 40 * 0.35), "side=true: the drawn line meets the label's left edge though the anchor is right of it");
+ const pinned = leaderPath([500, 600], pose, w, "clean", undefined, false);
+ ok(near(pinned[1][0], 1000 + w + 40 * 0.1) && near(pinned[2][0], 1000 - 40 * 0.1), "side=false pins the clean elbow and underline the same way");
+};
diff --git a/skills/anidoodle/engine/test/morph.test.ts b/skills/anidoodle/engine/test/morph.test.ts
new file mode 100644
index 0000000..0df43cf
--- /dev/null
+++ b/skills/anidoodle/engine/test/morph.test.ts
@@ -0,0 +1,96 @@
+// MORPH TESTS. resample, centreOf, handoff, coverShape, shapeGap and checkShapes in
+// src/canvas-core/morph.ts are pure and are held to numbers here. pathShape / fillShape get a
+// tiny recording ctx; nothing else draws. node tools/test.mjs
+import { blotShape, centreOf, checkShapes, circleShape, coverShape, fillShape, handoff, pathShape, rectShape, resample, shapeGap, type Shape } from "../src/canvas-core/morph";
+import type { Ctx, Env, P } from "../src/canvas-core/core";
+
+export const name = "morph";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
+ const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
+ const inside = (p: P, s: Shape) => { let c = false; for (let i = 0, j = s.length - 1; i < s.length; j = i++) { const a = s[i], b = s[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0]) c = !c; } return c; };
+ const area = (s: Shape) => s.reduce((a, p, i) => { const q = s[(i + 1) % s.length]; return a + p[0] * q[1] - q[0] * p[1]; }, 0) / 2;
+ const centred = (s: Shape, c: P): Shape => { const m = centreOf(s); return s.map(([x, y]): P => [x - m[0] + c[0], y - m[1] + c[1]]); };
+ const sq = rectShape(0, 0, 100, 50);
+
+ // 1. resample: exactly n points, clockwise on screen whatever the input winding, evenly
+ // spaced along the outline; degenerate shapes are refused
+ const r60 = resample(sq, 60);
+ ok(r60.length === 60 && resample(sq, 160).length === 160, "resample returns exactly n points");
+ ok(area(r60) > 0 && area(resample([...sq].reverse(), 60)) > 0, "resampled outlines run clockwise on screen, either input winding");
+ const circ = resample(circleShape([0, 0], 30, 72), 60), step = (2 * Math.PI * 30) / 60;
+ const gaps = circ.map((p, i) => Math.hypot(p[0] - circ[(i + 59) % 60][0], p[1] - circ[(i + 59) % 60][1]));
+ ok(gaps.every((g) => g > step * 0.98 && g <= step * 1.000001), `resample spaces points evenly along the outline (step ${step.toFixed(2)} px)`);
+ ok(JSON.stringify(resample(sq, 60)) === JSON.stringify(r60), "resample is deterministic");
+ ok(throws(() => resample([[0, 0], [1, 1]], 60)) && throws(() => resample([[5, 5], [5, 5], [5, 5]], 60)), "resample refuses fewer than 3 points or a zero-size shape");
+
+ // 2. the shape builders and centreOf
+ ok(circleShape([10, 20], 5).every((p) => near(Math.hypot(p[0] - 10, p[1] - 20), 5)), "circleShape's points sit on the circle");
+ ok(JSON.stringify(rectShape(0, 0, 100, 50)) === JSON.stringify([[100, 0], [100, 50], [0, 50], [0, 0]]), "a sharp rect is its four corners, clockwise");
+ const rr = rectShape(0, 0, 100, 50, 10, 4);
+ ok(rr.length === 20 && rr.every(([x, y]) => x >= -1e-9 && x <= 100 + 1e-9 && y >= -1e-9 && y <= 50 + 1e-9), "a rounded rect is perCorner points a corner, inside the box");
+ ok(blotShape([0, 0], 40, 7).every((p) => { const d = Math.hypot(p[0], p[1]); return d >= 40 * 0.9 - 1e-9 && d <= 40 * 1.12 + 1e-9; }), "blotShape's rim wobbles inside [0.9, 1.12] R");
+ ok(centreOf(sq)[0] === 50 && centreOf(sq)[1] === 25, "centreOf is the middle of the bounding box");
+ ok(centreOf([[0, 0], [10, 0], [0, 40]])[0] === 5 && centreOf([[0, 0], [10, 0], [0, 40]])[1] === 20, "centreOf uses the box, not the centroid");
+
+ // 3. handoff: exact at both ends, the centre rides the arc, stretch is zero at the ends
+ ok(throws(() => handoff({ from: circleShape([0, 0], 10), to: circleShape([100, 0], 10), t0: 50, t1: 50 })) && throws(() => handoff({ from: sq, to: sq, t0: 50, t1: 40 })), "t1 <= t0 throws");
+ const from = circleShape([820, 300], 16), to = rectShape(240, 420, 600, 380, 28);
+ const h = handoff({ from, to, t0: 45, t1: 80, arc: 90 });
+ ok(h.at(0) === from && h.at(45) === from && h.at(80) === to && h.at(200) === to, "handoff returns exactly the source until t0 and exactly the target from t1");
+ const ca = centreOf(resample(from, 160)), cb = centreOf(resample(to, 160));
+ ok(near(h.centre(45)[0], ca[0]) && near(h.centre(45)[1], ca[1]) && near(h.centre(80)[0], cb[0], 1e-6) && near(h.centre(80)[1], cb[1], 1e-6), "the centre starts and lands on the two shapes' centres");
+ const cm = h.centre(62.5); // u = 0.5 -> e = 0.5
+ ok(near(cm[0], (ca[0] + cb[0]) / 2, 1e-6) && near(cm[1], (ca[1] + cb[1]) / 2 - 90, 1e-6), "mid-flight the centre is the eased midpoint, lifted by the arc");
+ const long = handoff({ from, to, t0: 0, t1: 200, arc: 90 });
+ ok(shapeGap(long.at(1), centred(resample(from, 160), long.centre(1))) < 0.5, "just after t0 the outline is the un-stretched source at its centre");
+ ok(shapeGap(long.at(199), centred(resample(to, 160), long.centre(199))) < 0.5, "just before t1 the outline is the un-stretched target at its centre");
+ const spec = { from, to, t0: 45, t1: 80, arc: 90 };
+ ok(JSON.stringify(handoff(spec).at(60)) === JSON.stringify(h.at(60)), "a handoff is a pure function of its spec");
+
+ // 4. coverShape: a uniform scale about the frame's centre until every corner is inside
+ for (const s of [circleShape([820, 300], 16), sq, blotShape([500, 300], 40, 3)]) {
+ const cov = coverShape(s, 1920, 1080, 24), cs: P[] = [[-24, -24], [1944, -24], [1944, 1104], [-24, 1104]];
+ ok(cs.every((q) => inside(q, cov)), "coverShape puts every padded frame corner inside");
+ }
+ const wide = rectShape(300, 300, 100, 40), cov = coverShape(wide, 1920, 1080, 24);
+ const box = (s: Shape) => { const xs = s.map((p) => p[0]), ys = s.map((p) => p[1]); return [Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)]; };
+ const [w0, h0] = box(wide), [w1, h1] = box(cov);
+ ok(near(w1 / h1, w0 / h0), `coverShape keeps the shape's proportions (aspect ${(w1 / h1).toFixed(3)} = the source's)`);
+ ok(near(centreOf(cov)[0], 960, 1e-6) && near(centreOf(cov)[1], 540, 1e-6), "the shape's centre lands on the frame's centre");
+ // a shape whose bounding-box centre sits in its own hole can never cover the frame
+ const ring: Shape = [];
+ for (let i = 0; i <= 40; i++) { const a = -2.97 + (i * 5.94) / 40; ring.push([400 + Math.cos(a) * 60, 300 + Math.sin(a) * 60]); }
+ for (let i = 40; i >= 0; i--) { const a = -2.97 + (i * 5.94) / 40; ring.push([400 + Math.cos(a) * 40, 300 + Math.sin(a) * 40]); }
+ ok(!inside(centreOf(ring), ring), "the test ring's centre is in its hole");
+ ok(throws(() => coverShape(ring, 1920, 1080)), "coverShape throws when no scale can cover");
+
+ // 5. shapeGap and checkShapes: 0 for identical outlines, a real offset measured, tol enforced
+ const selfGap = shapeGap(sq, sq);
+ ok(selfGap < 1e-9, `a shape has zero gap to itself (${selfGap.toExponential(1)} of resample noise)`);
+ const c0 = circleShape([0, 0], 30), drift: Shape = c0.map(([x, y]): P => [x + 10, y]);
+ const g = shapeGap(c0, drift);
+ ok(Math.abs(g - 10) <= 0.5, `a 10 px offset is measured as ${g.toFixed(2)} px`);
+ ok(near(shapeGap(drift, c0), g), "shapeGap is symmetric");
+ ok(near(checkShapes(sq, sq), selfGap) && !throws(() => checkShapes(sq, sq, "self")), "checkShapes passes on a matching outline");
+ ok(throws(() => checkShapes(c0, drift, "probe", 2)), "checkShapes throws past tol");
+ ok(near(checkShapes(c0, drift, "probe", 20), g), "checkShapes returns the measured gap inside tol");
+
+ // 6. pathShape / fillShape on a recording ctx
+ const calls: string[] = [];
+ const fx = { beginPath() { calls.push("begin"); }, moveTo() { calls.push("m"); }, lineTo() { calls.push("l"); }, closePath() { calls.push("close"); }, setTransform(...a: number[]) { calls.push(`t${a.join("/")}`); }, fill() { calls.push("fill"); }, fillStyle: "", globalAlpha: 0 };
+ pathShape(fx as unknown as Ctx, sq);
+ ok(calls.join(",") === "begin,m,l,l,l,close", "pathShape traces the outline and closes it");
+ calls.length = 0;
+ fillShape(fx as unknown as Ctx, { scale: 2 } as unknown as Env, sq, "#123456");
+ ok(calls.includes("fill") && fx.fillStyle === "#123456" && calls.includes("t2/0/0/2/0/0"), "fillShape fills the outline in the film's scale");
+
+ // 7. the checks refuse bad input: NaN in a shape, a turn that ends where it starts, a NaN
+ // landing frame; a points: 2 ask still gets a usable outline (the floor is 8)
+ const nanShape: Shape = [[NaN, 0], [0, 10], [10, 0]];
+ ok(throws(() => checkShapes(nanShape, sq, "nan-out")) && throws(() => checkShapes(sq, nanShape, "nan-into")), "checkShapes throws when a shape contains NaN");
+ ok(throws(() => handoff({ from, to, t0: 45, t1: 80, turn: [0.5, 0.5] })) && throws(() => handoff({ from, to, t0: 45, t1: 80, turn: [1, 0.2] })), "a turn that does not end after it starts throws");
+ ok(throws(() => handoff({ from, to, t0: 45, t1: NaN })) && throws(() => handoff({ from, to, t0: NaN, t1: 80 })), "a NaN t0 or t1 throws");
+ const coarse = handoff({ from, to, t0: 45, t1: 80, points: 2 }).at(60);
+ ok(coarse.length === 8 && coarse.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y)), "points: 2 still yields a valid outline (8 finite points)");
+};
diff --git a/skills/anidoodle/engine/test/sfxFrozenPlans.ts b/skills/anidoodle/engine/test/sfxFrozenPlans.ts
new file mode 100644
index 0000000..552b9d1
--- /dev/null
+++ b/skills/anidoodle/engine/test/sfxFrozenPlans.ts
@@ -0,0 +1,26 @@
+// Launch-template cue sequences (launchTemplate.ts): typing, Generate/drop/card, reveal.
+import { launchLofi3 } from "../src/canvas-core/music/index";
+import { renderPiece } from "../src/canvas-core/music/render";
+import type { SfxPlan } from "../src/canvas-core/music/sfxMix";
+export const frozenPlans = (sr: number) => {
+ const piece = launchLofi3(), r = renderPiece(piece, sr), music: [Float32Array, Float32Array] = [r.L, r.R];
+ const base = { fps: 30, frames: 240, seed: 7, score: { piece } };
+ const plans: SfxPlan[] = [
+ { ...base, cues: [
+ { frame: 12, kind: "tick", variant: "key", gainDb: 1.5, label: 'key "m"' },
+ { frame: 16, kind: "tick", variant: "key" }, { frame: 19, kind: "tick", variant: "space" },
+ { frame: 24, kind: "tick", variant: "key" }, { frame: 28, kind: "tick", variant: "key" },
+ ] },
+ { ...base, cues: [
+ { frame: 30, kind: "press", variant: "thock", label: "Generate" },
+ { frame: 37, kind: "ink", variant: "plip", label: "the drop lifts" },
+ { frame: 48, kind: "ink", variant: "bloom", label: "it blooms into the card" },
+ { frame: 54, kind: "pop", variant: "cork", label: "the card lands (spring)" },
+ ] },
+ { ...base, cues: [
+ { frame: 120, kind: "riser", variant: "soft", beats: 4, label: "into the reveal" },
+ { frame: 120, kind: "impact", variant: "bloom", label: "the reveal" },
+ ] },
+ ];
+ return { plans, music };
+};
diff --git a/skills/anidoodle/engine/test/sfxHarsh.test.ts b/skills/anidoodle/engine/test/sfxHarsh.test.ts
new file mode 100644
index 0000000..624cfb8
--- /dev/null
+++ b/skills/anidoodle/engine/test/sfxHarsh.test.ts
@@ -0,0 +1,68 @@
+import { mixSfx, filmSfx, sfxHarshness, type PlacedCue, type SfxPlan, type SfxHarshOptions } from "../src/canvas-core/music/sfxMix";
+import { frozenPlans } from "./sfxFrozenPlans";
+import { survey } from "./sfxKitSurvey";
+const cryptoModule = "node:crypto", { createHash } = await import(cryptoModule);
+const hash = (L: Float32Array, R: Float32Array) => createHash("sha256").update(new Uint8Array(L.buffer)).update(new Uint8Array(R.buffer)).digest("hex");
+export const name = "sfx harshness";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const sr = 48000, n = sr * 2;
+ const music: [Float32Array, Float32Array] = [Float32Array.from({ length: n }, (_, i) => 0.04 * Math.sin(2 * Math.PI * 220 * i / sr) + 0.006 * Math.sin(2 * Math.PI * 4000 * i / sr)), new Float32Array(n)];
+ music[1].set(music[0]);
+ const synth = (f: number): PlacedCue => {
+ const L = Float32Array.from({ length: sr / 4 }, (_, i) => i < sr * 0.02 ? 0.5 * Math.sin(2 * Math.PI * f * i / sr) : 0), R = L.slice();
+ return { i: 0, cue: { frame: 15, kind: "tick", label: `${f} Hz` }, sound: { L, R, sr, kind: "tick", variant: "ui", seed: 1, hit: 0, window: [0, sr * 0.02], lufs: 0 }, hitS: 0.5, snappedFromS: 0.5, start: sr / 2, window: [sr / 2, sr * 0.52] };
+ };
+ const piercing = synth(4000), dull = synth(100), before = hash(piercing.sound.L, piercing.sound.R);
+ const high = sfxHarshness([piercing], music, sr, {})[0], low = sfxHarshness([dull], music, sr, {})[0];
+ ok(!high.ok && high.violations?.some((v) => v.metric === "liftDb"), "a loud 4 kHz burst exceeds the default lift cap");
+ ok(low.ok && Math.abs(low.cueRmsDb - high.cueRmsDb) < 1e-6, "a 100 Hz thump at the same RMS passes");
+ ok(high.peakDb > high.bodyDb + 10 && high.crestDb === high.peakDb - high.bodyDb, "a short peak with little following body has a large peak-body gap");
+ ok(hash(piercing.sound.L, piercing.sound.R) === before, "measurement never changes the cue samples");
+ const silence: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)], silent = sfxHarshness([piercing], silence, sr, {})[0];
+ ok(silent.liftDb === null && silent.peakMarginDb === null && silent.violations.every((v) => v.metric !== "liftDb"), "silence-relative fields are null and lift is skipped");
+ const click = synth(4000); click.sound.L.fill(0); click.sound.R.fill(0); click.sound.L[0] = click.sound.R[0] = 0.5;
+ const impulse = sfxHarshness([click], silence, sr, {})[0];
+ ok(impulse.bodyDb === -200 && impulse.peakAtS === 0.5 && Math.abs(impulse.peakDb + 6.020599913) < 1e-8, "body starts after the first peak: a single sample has no body");
+ const tail = synth(4000); tail.sound.L.fill(0); tail.sound.R.fill(0); tail.sound.L[0] = tail.sound.R[0] = 0.5;
+ tail.sound.L.fill(0.1, 1, 1 + sr * 0.15); tail.sound.R.set(tail.sound.L);
+ const body = sfxHarshness([tail], silence, sr, {})[0];
+ ok(Math.abs(body.bodyDb + 20) < 1e-6, "the 150 ms body uses stereo mean-power RMS without a +3 dB boost");
+ const plan: SfxPlan = { fps: 30, frames: 60, cues: [{ frame: 15, kind: "tick", variant: "ui", label: "piercing key" }] };
+ const report = mixSfx(music, plan, sr), cap = report.harshness[0].peakDb - 3, options: SfxHarshOptions = { maxPeakDb: cap, maxTiltDb: 0, maxLiftDb: 100 };
+ const explicit = mixSfx(music, { ...plan, harsh: { ...options, mode: "report" } }, sr);
+ ok(hash(report.L, report.R) === hash(explicit.L, explicit.R) && explicit.ok && !explicit.harshness[0].ok, "report flags a peak breach and keeps samples and audibility verdict unchanged");
+ let message = "";
+ try { mixSfx(music, { ...plan, harsh: { ...options, mode: "throw" } }, sr); } catch (e) { message = (e as Error).message; }
+ ok(/piercing key/.test(message) && /peakDb/.test(message) && /cap/.test(message), `throw names the cue, metric, measured value and cap: ${message.replace(/\n/g, " ")}`);
+ const tame = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame" } }, sr), tameAgain = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame" } }, sr);
+ ok(tame.harshness[0].ok && tame.harshness[0].peakDb <= cap && tame.ok && tame.harshness[0].reductionDb >= 3, "tame lowers the peak under the cap and keeps the cue audible");
+ ok(hash(tame.L, tame.R) === hash(tameAgain.L, tameAgain.R) && plan.cues[0].gainDb === undefined, "tame is deterministic and leaves the caller's plan alone");
+ const liftCap = report.harshness[0].liftDb! - 2, lifted = mixSfx(music, { ...plan, harsh: { mode: "tame", maxLiftDb: liftCap, maxTiltDb: 0 } }, sr);
+ ok(lifted.harshness[0].ok && lifted.harshness[0].liftDb! <= liftCap && lifted.ok, "tame lowers a lift breach under the cap while audible");
+ const conflict = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame", maxPeakDb: cap - 60 } }, sr);
+ ok(!conflict.harshness[0].ok && conflict.harshness[0].conflict === "audibility floor" && conflict.ok && conflict.audibility[0].marginDb >= conflict.audibility[0].minDb, "an impossible cap reports an audibility conflict and stays audible");
+ const tiltCap = report.harshness[0].tiltDb - 1, tilt = mixSfx(music, { ...plan, harsh: { mode: "tame", maxTiltDb: tiltCap, maxPeakDb: cap } }, sr);
+ ok(hash(tilt.L, tilt.R) === hash(report.L, report.R) && tilt.harshness[0].conflict === "tilt cannot be fixed by gain" && tilt.harshness[0].reductionDb === 0, "a tilt breach leaves the cue unchanged and explains that gain cannot fix it");
+ message = ""; try { mixSfx(null, { ...plan, harsh: { mode: "throw", maxTiltDb: tiltCap } }, sr); } catch (e) { message = (e as Error).message; }
+ ok(/tiltDb/.test(message) && /piercing key/.test(message), "throw still rejects a tilt breach over silence");
+ const override = mixSfx(music, { ...plan, harsh: { ...options, mode: "throw" }, cues: [{ ...plan.cues[0], harsh: { maxPeakDb: 0 } }] }, sr);
+ ok(override.harshness[0].ok, "a per-cue cap overrides the plan cap");
+ const floor = mixSfx(music, { ...plan, harsh: { ...options, mode: "tame", maxPeakDb: cap - 60 }, cues: [{ ...plan.cues[0], minDb: 0 }] }, sr);
+ ok(floor.ok && floor.audibility[0].marginDb >= 0, "tame respects the per-cue audibility floor");
+ const buriedPlan: SfxPlan = { ...plan, cues: [{ ...plan.cues[0], gainDb: -40 }], harsh: { mode: "tame", maxPeakDb: -100 } }, buried = mixSfx(music, buriedPlan, sr);
+ ok(!buried.ok && buried.harshness[0].conflict === "audibility floor" && buried.harshness[0].reductionDb === 0, "tame never lowers an already buried cue");
+ const overSilence = mixSfx(null, { ...plan, harsh: { ...options, mode: "tame" } }, sr);
+ ok(overSilence.ok && overSilence.harshness[0].ok && overSilence.harshness[0].liftDb === null, "over silence, tame still enforces the absolute peak cap");
+ for (const harsh of [{ mode: "unknown" }, { maxLiftDb: NaN }, { maxTiltDb: Infinity }, { maxPeakDb: "hot" }]) {
+ message = ""; try { mixSfx(null, { ...plan, harsh: harsh as SfxHarshOptions }, sr); } catch (e) { message = (e as Error).message; }
+ ok(/harsh\./.test(message), `invalid harsh option rejected: ${JSON.stringify(harsh)}`);
+ }
+ // Captured from production sources at c1beddfe4264a34d12531dbe931acef611fb0a02,
+ // loaded by git show and bundled with these fixtures before the mixer was edited.
+ const hashes = ["5db7c646b1e61b0016c5dd8a114e875f6cedbaed17f6b702a225ba2dcc187a85", "3064c924f76acb857c509a5c294cf043380451d544fda0b5372ce06d33ef133a", "3a42c3f453a9a1a0285bd2287bc9874e6e330fc3bd6baa263587e10443eaa94e"];
+ const frozen = frozenPlans(sr);
+ frozen.plans.forEach((p, i) => { const m = mixSfx(frozen.music, p, sr), f = filmSfx(() => frozen.music, p)(sr);
+ ok(hash(m.L, m.R) === hashes[i] && hash(...f) === hashes[i], `launch cue plan ${i}: mixSfx and filmSfx match base SHA-256 ${hashes[i]}`);
+ });
+ for (const row of survey()) ok(row.ok, `${row.kind}:${row.variant} over ${row.context}: default gain passes the measured default caps`);
+};
diff --git a/skills/anidoodle/engine/test/sfxKitSurvey.ts b/skills/anidoodle/engine/test/sfxKitSurvey.ts
new file mode 100644
index 0000000..af4fe38
--- /dev/null
+++ b/skills/anidoodle/engine/test/sfxKitSurvey.ts
@@ -0,0 +1,14 @@
+// Fixed calibration context: default gain, C major / 90 bpm, seed 1, 48 kHz.
+// A steady -22.36 dBFS score (220 Hz + 440 Hz + a quiet 4 kHz partial), no modulation.
+import { SFX_KINDS, sfxVariants, renderSfx } from "../src/canvas-core/music/sfxKit";
+import { sfxDuck, sfxHarshness, type PlacedCue } from "../src/canvas-core/music/sfxMix";
+export const survey = () => {
+ const sr = 48000, n = sr * 12, L = Float32Array.from({ length: n }, (_, i) => 0.1 * Math.sin(2 * Math.PI * 220 * i / sr) + 0.035 * Math.sin(2 * Math.PI * 440 * i / sr) + 0.02 * Math.sin(2 * Math.PI * 4000 * i / sr));
+ const silence: [Float32Array, Float32Array] = [new Float32Array(n), new Float32Array(n)];
+ return SFX_KINDS.flatMap((kind) => sfxVariants(kind).flatMap((variant) => {
+ const sound = renderSfx(kind, { variant, key: "C", bpm: 90 }, sr), start = 4 * sr - sound.hit;
+ const pc: PlacedCue = { i: 0, cue: { kind, variant, frame: 120 }, sound, hitS: 4, snappedFromS: 4, start, window: [start + sound.window[0], start + sound.window[1]] };
+ const duck = sfxDuck([pc], n, sr), bed = Float32Array.from(L, (x, i) => x * duck[i]);
+ return ([["silence", silence], ["score", [bed, bed]]] as [string, [Float32Array, Float32Array]][]).map(([context, music]) => ({ context, ...sfxHarshness([pc], music, sr, {})[0] }));
+ }));
+};
diff --git a/skills/anidoodle/engine/test/transitions.test.ts b/skills/anidoodle/engine/test/transitions.test.ts
new file mode 100644
index 0000000..d081895
--- /dev/null
+++ b/skills/anidoodle/engine/test/transitions.test.ts
@@ -0,0 +1,98 @@
+// TRANSITION TESTS. The seam math in src/canvas-core/transitions.ts is pure (wipeFront,
+// irisRadius, flashAlpha, checkFlashes, seam), so it is held to numbers here with no browser.
+// brushWipe / iris / flashCut draw through layers and are not covered; flash gets a tiny
+// recording ctx. node tools/test.mjs
+import { checkFlashes, flash, flashAlpha, irisRadius, irisRim, seam, wipeFront } from "../src/canvas-core/transitions";
+import { blot } from "../src/canvas-core/launchKit";
+import type { Ctx, Env, P } from "../src/canvas-core/core";
+
+export const name = "transitions";
+export const run = (ok: (cond: boolean, label: string) => void) => {
+ const near = (a: number, b: number, eps = 1e-9) => Math.abs(a - b) <= eps;
+ const throws = (fn: () => unknown) => { try { fn(); return false; } catch { return true; } };
+ // the same point-in-polygon ray cast morph.ts uses (it is private there)
+ const inside = (p: P, s: P[]) => { let c = false; for (let i = 0, j = s.length - 1; i < s.length; j = i++) { const a = s[i], b = s[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0]) c = !c; } return c; };
+ const W = 1920, H = 1080, corners: P[] = [[0, 0], [W, 0], [W, H], [0, H]];
+
+ // 1. seam: a clamped ramp over [at, at + len]
+ ok(seam(100, 120, 22) === 0 && seam(119.9, 120, 22) === 0, "seam is 0 before its window");
+ ok(seam(131, 120, 22) === 0.5 && seam(142, 120, 22) === 1 && seam(500, 120, 22) === 1, "seam is 0.5 mid-window and 1 from at+len on");
+
+ // 2. wipeFront: at p = 0 nothing of the frame is inside the picture polygon, at p = 1 all
+ // four corners are - for a straight, a diagonal, a vertical and a backwards stroke
+ const mid: P[] = [[W / 2, H / 2], [W * 0.25, H * 0.75], [W * 0.8, H * 0.2]];
+ for (const angle of [0, 0.22, Math.PI / 2, Math.PI]) for (const ink of [undefined, "#1d1a16"] as (string | undefined)[]) {
+ const o = { angle, ink, seed: 11 };
+ ok([...corners, ...mid].every((c) => !inside(c, wipeFront(0, W, H, o))), `wipeFront p=0 angle ${angle.toFixed(2)} ink ${!!ink}: nothing of the frame is inside`);
+ ok(corners.every((c) => inside(c, wipeFront(1, W, H, o))), `wipeFront p=1 angle ${angle.toFixed(2)} ink ${!!ink}: all four corners are inside`);
+ }
+
+ // 3. the ink edge never trails the picture edge: a point inside the picture polygon is
+ // inside the ink polygon too, at any progress and any angle
+ for (const angle of [0, 0.22, Math.PI / 2, Math.PI]) for (const p of [0.15, 0.5, 0.85]) {
+ const pic = wipeFront(p, W, H, { angle, ink: "#1d1a16", seed: 5 }), inked = wipeFront(p, W, H, { angle, ink: "#1d1a16", seed: 5 }, "ink");
+ let lead = true;
+ for (let y = 0; y <= 20 && lead; y++) for (let x = 0; x <= 36 && lead; x++) { const q: P = [(x * W) / 36, (y * H) / 20]; if (inside(q, pic) && !inside(q, inked)) lead = false; }
+ ok(lead, `wipeFront angle ${angle.toFixed(2)} p ${p}: the ink edge is ahead of or equal to the picture edge`);
+ }
+
+ // 4. the stroke is a pure function of its arguments: same seed, same points
+ const w1 = wipeFront(0.5, W, H, { angle: 0.3, seed: 7 });
+ ok(JSON.stringify(w1) === JSON.stringify(wipeFront(0.5, W, H, { angle: 0.3, seed: 7 })), "wipeFront: same seed gives identical points");
+ ok(JSON.stringify(w1) !== JSON.stringify(wipeFront(0.5, W, H, { angle: 0.3, seed: 8 })), "wipeFront: a different seed is a different brush");
+
+ // 5. irisRadius: 0 at p = 0, past the farthest corner at p = 1 even off-centre, reversed
+ // with close; a blot's wobbling rim needs more radius than a clean circle
+ ok(irisRadius(0, W, H) === 0, "irisRadius is 0 at p = 0");
+ const c: P = [120, 90], far = Math.max(...corners.map(([x, y]) => Math.hypot(x - c[0], y - c[1])));
+ ok(irisRadius(1, W, H, { center: c }) >= far, `irisRadius at p = 1 covers the farthest corner (${far.toFixed(0)} px from an off-centre centre)`);
+ ok(irisRadius(0, W, H, { center: c, close: true }) >= far && near(irisRadius(1, W, H, { close: true }), 0), "close: full radius at p = 0, 0 at p = 1");
+ const rb = irisRadius(1, W, H, { shape: "blot", center: [300, 200] }), rc = irisRadius(1, W, H, { center: [300, 200] });
+ ok(rb > rc, `a blot needs more radius than a circle (${rb.toFixed(0)} > ${rc.toFixed(0)})`);
+ ok([1, 42, 99].every((seed) => corners.every((q) => inside(q, blot([300, 200], rb, seed)))), "the blot's deepest rim dip still covers every corner at p = 1");
+
+ // 6. flashAlpha: peak on the cut frame, 0 outside [cut - inF, cut + outF), and the legal
+ // minimum still lights four frames - a one-frame flash cannot be built
+ ok(near(flashAlpha(100, 100), 0.86), "flashAlpha peaks on the cut frame");
+ const lit = Array.from({ length: 30 }, (_, i) => i + 90).filter((f) => flashAlpha(f, 100) > 0);
+ ok(lit.length === 11 && lit[0] === 98 && lit[10] === 108, `flashAlpha is > 0 on exactly the inF + outF frames around the cut (${lit.length})`);
+ ok(flashAlpha(97, 100) === 0 && flashAlpha(109, 100) === 0, "flashAlpha is 0 outside its window");
+ ok(flashAlpha(98, 100) < flashAlpha(99, 100) && flashAlpha(99, 100) < flashAlpha(100, 100), "the light rises into the cut");
+ ok(Array.from({ length: 10 }, (_, i) => i + 95).filter((f) => flashAlpha(f, 100, { inF: 1, outF: 3 }) > 0).length === 4, "the tightest legal flash lights 4 frames: never a one-frame flash");
+ ok(throws(() => flashAlpha(50, 100, { outF: 2 })) && throws(() => flashAlpha(50, 100, { inF: 0 })), "flashAlpha throws for outF < 3 or inF < 1");
+
+ // 7. checkFlashes: one rule - any two flashes closer than half a second throw; the
+ // boundary is strict, and however many flashes there are, only the nearest pair matters
+ ok(throws(() => checkFlashes([0, 14], 30)), "two flashes 0.47 s apart throw");
+ ok(!throws(() => checkFlashes([0, 15], 30)), "two flashes exactly 0.5 s apart pass");
+ ok(!throws(() => checkFlashes([0, 15, 30, 45], 30)), "four flashes, all at least half a second apart, pass: the only rule is the pair rule");
+ ok(throws(() => checkFlashes([0, 29, 14], 30)), "a close pair throws however the cuts were listed");
+ const cuts = [400, 240];
+ ok(checkFlashes(cuts, 30) === cuts, "checkFlashes sorts a copy and returns the argument");
+
+ // 8. flash() on a recording ctx: one full-frame fill at the computed alpha
+ let seen: { a: number; r: number[] } | undefined;
+ const rec = { setTransform() {}, globalCompositeOperation: "", globalAlpha: 0, fillStyle: "", fillRect: (...r: number[]) => { seen = { a: rec.globalAlpha, r }; } };
+ flash(rec as unknown as Ctx, { W, H, scale: 2 } as unknown as Env, 100, 100);
+ ok(near(seen?.a ?? -1, 0.86) && JSON.stringify(seen?.r) === JSON.stringify([0, 0, W, H]), "flash paints the whole frame at the computed alpha");
+
+ // 9. seam with len 0 is a hard cut that still answers 0 or 1, never NaN
+ ok(seam(119.9, 120, 0) === 0 && seam(120, 120, 0) === 1 && seam(500, 120, 0) === 1, "seam(local, at, 0): 0 before at, 1 from at");
+ ok(seam(119.9, 120, -3) === 0 && seam(120, 120, -3) === 1, "a negative len behaves the same");
+ ok([seam(NaN, 120, 0), seam(-1e9, 120, 0), seam(1e9, 120, 0)].every((v) => v === 0 || v === 1), "seam is never NaN");
+
+ // 10. irisRim: 0 at R = 0, grows without a step bigger than rim/20 per px, full width by
+ // R = 70 - so the ink rim never appears or vanishes in one frame
+ for (const [o, rim] of [[{ shape: "blot" }, 22], [{ rim: 10 }, 10]] as const) {
+ ok(irisRim(0, o) === 0 && irisRim(70, o) === rim && irisRim(200, o) === rim, `irisRim (rim ${rim}): 0 at R = 0, full ${rim} px from R = 70`);
+ let prev = 0, stepOk = true;
+ for (let R = 0.5; R <= 100; R += 0.5) { const v = irisRim(R, o); if (v - prev > rim / 20 + 1e-12 || v < prev - 1e-12) stepOk = false; prev = v; }
+ ok(stepOk, `irisRim (rim ${rim}) grows continuously, no step over ${(rim / 20).toFixed(2)} px`);
+ }
+ ok(irisRim(50, {}) === 0 && irisRim(50, { shape: "circle" }) === 0, "a clean circle has no rim");
+
+ // 11. wipeFront stays finite on degenerate input: no bristles, an ease that overshoots
+ const finite = (s: P[]) => s.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y));
+ ok(finite(wipeFront(0.5, W, H, { bristles: 0 })), "wipeFront with bristles: 0 still gives finite points");
+ ok(finite(wipeFront(0.5, W, H, { ease: () => 1.7 })) && finite(wipeFront(0.5, W, H, { ease: () => -0.4 })), "wipeFront with an ease returning 1.7 or -0.4 still gives finite points");
+};
diff --git a/skills/anidoodle/engine/tools/motion.mjs b/skills/anidoodle/engine/tools/motion.mjs
index 873453a..7b4b7e5 100644
--- a/skills/anidoodle/engine/tools/motion.mjs
+++ b/skills/anidoodle/engine/tools/motion.mjs
@@ -22,3 +22,32 @@ export const changedArea = async (file, width, height, threshold = 4, stride = 1
if (pending.length) throw new Error(`incomplete decoded frame: ${pending.length} bytes`);
return changed;
};
+
+// The frames themselves, one at a time, same small grey decode as changedArea: a Buffer of
+// width*height luma bytes per frame. Tools that need pixel neighbourhoods (popscan's triple
+// diff) rather than a pairwise summary consume this stream. `frames` caps the decode; a
+// consumer that stops early kills the encoder instead of buffering the rest of the film.
+export const greyFrames = async function* (file, width, height, frames = Infinity) {
+ const px = width * height;
+ const args = ["-v", "error", "-i", file, "-vf", `scale=${width}:${height}`];
+ if (Number.isFinite(frames)) args.push("-frames:v", String(frames));
+ args.push("-pix_fmt", "gray", "-f", "rawvideo", "-");
+ const ff = spawn("ffmpeg", args);
+ let pending = Buffer.alloc(0), error = "";
+ ff.stderr.on("data", (chunk) => { error += chunk.toString(); });
+ const closed = new Promise((resolve, reject) => { ff.on("error", reject); ff.on("close", (code) => code ? reject(new Error(error || `ffmpeg exited ${code}`)) : resolve()); });
+ closed.catch(() => {}); // a consumer that breaks early leaves ffmpeg to the kill below, not an unhandled rejection
+ try {
+ for await (const chunk of ff.stdout) {
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
+ while (pending.length >= px) {
+ yield Buffer.from(pending.subarray(0, px));
+ pending = pending.subarray(px);
+ }
+ }
+ await closed;
+ if (pending.length) throw new Error(`incomplete decoded frame: ${pending.length} bytes`);
+ } finally {
+ if (ff.exitCode === null) ff.kill("SIGKILL");
+ }
+};
diff --git a/skills/anidoodle/engine/tools/popscan-unit.mjs b/skills/anidoodle/engine/tools/popscan-unit.mjs
new file mode 100644
index 0000000..b14f38a
--- /dev/null
+++ b/skills/anidoodle/engine/tools/popscan-unit.mjs
@@ -0,0 +1,200 @@
+#!/usr/bin/env node
+// Unit + end-to-end tests for tools/popscan.mjs. The detector (scanPops) is pure, so the unit
+// half feeds it synthetic greyscale frames - no video needed. The e2e half builds two tiny
+// MP4s with ffmpeg lavfi (no assets) under a temp dir inside out/: one with a known one-frame
+// pop at a known frame and place, one clean clip holding a hard cut and continuous motion.
+// popscan must report exactly the known pop and nothing else. Temp dir removed afterwards.
+// Boundary rule under test: the first and last frames can never be pops - a pop needs a
+// neighbour on both sides.
+// node tools/popscan-unit.mjs
+import { execFileSync } from "node:child_process";
+import { strict as assert } from "node:assert";
+import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { scanPops } from "./popscan.mjs";
+
+const TOOLS = import.meta.dirname;
+const ENGINE = resolve(TOOLS, "..");
+const root = join(ENGINE, "out", ".popscan-unit");
+rmSync(root, { recursive: true, force: true });
+mkdirSync(root, { recursive: true });
+let pass = 0;
+const ok = (name) => console.log(`PASS ${++pass} ${name}`);
+
+// ---------------------------------------------------------------- synthetic frames: 48x48, grid 4 -> 12px tiles
+const W = 48, H = 48;
+const OPTS = { width: W, height: H, grid: 4, min: 0.01, ratio: 0.35, thresh: 4 }; // min is a fraction here (1% of a tile)
+const flat = (v = 30) => new Uint8Array(W * H).fill(v);
+const rect = (f, x0, y0, x1, y1, v) => { for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) f[y * W + x] = v; return f; };
+const tex = (seed) => { const f = flat(30); let s = seed; for (let y = 14; y < 24; y++) for (let x = 14; x < 24; x++) { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; f[y * W + x] = 40 + (s >>> 0) % 180; } return f; };
+
+// a one-frame APPEAR: a bright block exists on frame 2 only (inside tile (1,1): x12-23, y12-23)
+{
+ const fs = [flat(), flat(), rect(flat(), 14, 14, 24, 24, 220), flat(), flat()];
+ const r = await scanPops(fs, OPTS);
+ assert.equal(r.length, 1, "one finding");
+ assert.equal(r[0].frame, 2);
+ assert.deepEqual(r[0].box.map((v) => +v.toFixed(4)), [0.25, 0.25, 0.5, 0.5], "box is tile (1,1)");
+ assert.equal(r[0].kind, "appears");
+}
+ok("one-frame appear: found at frame 2 with the tile's box, kind appears");
+
+// a one-frame VANISH: the block exists on every frame except 2
+{
+ const block = () => rect(flat(), 14, 14, 24, 24, 220);
+ const r = await scanPops([block(), block(), flat(), block(), block()], OPTS);
+ assert.equal(r.length, 1);
+ assert.equal(r[0].frame, 2);
+ assert.equal(r[0].kind, "vanishes");
+}
+ok("one-frame vanish: found at frame 2, kind vanishes");
+
+// a JUMP: same texture, shifted inside the region for one frame (texture kept -> not appears/vanishes)
+{
+ const base = () => tex(7);
+ const jumped = () => { const f = flat(), t = tex(7); for (let y = 14; y < 24; y++) for (let x = 14; x < 24; x++) f[y * W + x + 3] = t[y * W + x]; return f; };
+ const r = await scanPops([base(), base(), jumped(), base(), base()], OPTS);
+ assert.equal(r.length, 1);
+ assert.equal(r[0].kind, "jumps");
+}
+ok("one-frame rearrange: found, kind jumps (texture preserved)");
+
+// a HARD CUT is not a pop: after the cut, f and f+1 agree
+{
+ const r = await scanPops([flat(30), flat(30), flat(200), flat(200), flat(200)], OPTS);
+ assert.equal(r.length, 0, "hard cut produces no finding");
+}
+ok("hard cut: no finding");
+
+// FAST CONTINUOUS MOTION is not a pop: f-1 and f+1 differ too
+{
+ const moved = (x) => rect(flat(), x, 14, x + 10, 24, 220);
+ const r = await scanPops([moved(2), moved(6), moved(10), moved(14), moved(18)], OPTS);
+ assert.equal(r.length, 0, "a sliding block never pops");
+}
+ok("smooth fast motion: no finding");
+
+// a SMALL POP in one tile of an otherwise moving frame: the busy top row moves every frame
+// (whole-frame change is high everywhere it matters), the quiet tile still gets caught
+{
+ const busy = (x, pop) => { const f = flat(24); rect(f, x, 2, x + 12, 8, 200); if (pop) rect(f, 38, 26, 46, 34, 210); return f; };
+ const fs = [busy(2), busy(5), busy(8, true), busy(11), busy(14)];
+ const r = await scanPops(fs, OPTS);
+ assert.equal(r.length, 1, "only the quiet-tile pop is found");
+ assert.equal(r[0].frame, 2);
+ assert.deepEqual(r[0].box.map((v) => +v.toFixed(4)), [0.75, 0.5, 1, 0.75], "box is tile (3,2) only");
+}
+ok("small pop in a busy frame: found, box is the one tile");
+
+// TWO POPS on different frames -> two findings
+{
+ const fs = [flat(), flat(), rect(flat(), 2, 2, 10, 10, 220), flat(), flat(), rect(flat(), 40, 40, 47, 47, 220), flat()];
+ const r = await scanPops(fs, OPTS);
+ assert.equal(r.length, 2);
+ assert.deepEqual(r.map((x) => x.frame), [2, 5]);
+}
+ok("two pops on different frames: two findings");
+
+// BOUNDARY: a pop on the first or last frame is never reported - both neighbours are required
+{
+ const first = await scanPops([rect(flat(), 14, 14, 24, 24, 220), flat(), flat(), flat(), flat()], OPTS);
+ const last = await scanPops([flat(), flat(), flat(), flat(), rect(flat(), 14, 14, 24, 24, 220)], OPTS);
+ assert.equal(first.length, 0, "frame 0 has no f-1, cannot pop");
+ assert.equal(last.length, 0, "last frame has no f+1, cannot pop");
+}
+ok("first/last frame can never be a pop");
+
+// ADJACENT popping tiles merge into ONE finding; DISJOINT regions are two findings
+{
+ const merged = await scanPops([flat(), flat(), rect(flat(), 18, 14, 30, 24, 220), flat(), flat()], OPTS);
+ assert.equal(merged.length, 1, "a block spanning tiles (1,1)+(2,1) is one finding");
+ assert.deepEqual(merged[0].box.map((v) => +v.toFixed(4)), [0.25, 0.25, 0.75, 0.5], "merged box covers both tiles");
+ assert.equal(merged[0].tiles, 2);
+ const two = await scanPops([flat(), flat(), rect(rect(flat(), 2, 2, 10, 10, 220), 40, 40, 47, 47, 220), flat(), flat()], OPTS);
+ assert.equal(two.length, 2, "two separated pops on one frame are two findings");
+}
+ok("adjacent tiles merge to one finding; disjoint regions stay separate");
+
+// --min gates: a 2x2 px blip under the floor is not a pop; --from/--to bound eligibility
+{
+ const fs = [flat(), flat(), rect(flat(), 14, 14, 16, 16, 220), flat(), flat()];
+ assert.equal((await scanPops(fs, { ...OPTS, min: 0.05 })).length, 0, "blip under --min is ignored");
+ const pop = [flat(), flat(), rect(flat(), 14, 14, 24, 24, 220), flat(), flat()];
+ assert.equal((await scanPops(pop, { ...OPTS, to: 1 })).length, 0, "--to 1 excludes frame 2");
+ assert.equal((await scanPops(pop, { ...OPTS, from: 3 })).length, 0, "--from 3 excludes frame 2");
+ assert.equal((await scanPops(pop, { ...OPTS, from: 2, to: 2 })).length, 1, "--from 2 --to 2 keeps it");
+}
+ok("--min floor and --from/--to bounds respected");
+
+// ---------------------------------------------------------------- end to end, real MP4s via lavfi
+const popMp4 = join(root, "pop.mp4"), cleanMp4 = join(root, "clean.mp4");
+try {
+ // a 36x24 white box on frame 15 only: x60-96 of 160 (37.5-60%), y48-72 of 120 (40-60%)
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x202830:s=160x120:r=30:d=1,drawbox=x=60:y=48:w=36:h=24:c=0xf0f0f0:t=fill:enable='eq(n,15)'", "-pix_fmt", "yuv420p", popMp4]);
+ // two 30-frame halves, each with a box in continuous motion, concatenated -> a hard cut at 30
+ execFileSync("ffmpeg", ["-v", "error", "-y",
+ "-f", "lavfi", "-i", "color=c=0x182028:s=160x120:r=30:d=1",
+ "-f", "lavfi", "-i", "color=c=0xe8e8e8:s=20x20:r=30:d=1",
+ "-f", "lavfi", "-i", "color=c=0x3a2020:s=160x120:r=30:d=1",
+ "-f", "lavfi", "-i", "color=c=0x30c0b0:s=16x16:r=30:d=1",
+ "-filter_complex", "[0:v][1:v]overlay=x='4+4*n':y=30[a];[2:v][3:v]overlay=x='140-4*n':y=70[b];[a][b]concat=n=2:v=1[out]",
+ "-map", "[out]", "-pix_fmt", "yuv420p", "-r", "30", cleanMp4]);
+ ok("lavfi fixtures built: pop.mp4 (pop at frame 15), clean.mp4 (cut + motion)");
+
+ const run = (args) => JSON.parse(execFileSync("node", [join(TOOLS, "popscan.mjs"), ...args, "--json"], { cwd: ENGINE, encoding: "utf8" }));
+ const pops = run([popMp4]);
+ assert.equal(pops.length, 1, `expected exactly one finding, got ${pops.length}`);
+ assert.equal(pops[0].frame, 15, "the known pop frame");
+ assert(pops[0].box[0] <= 48.75 && pops[0].box[2] >= 48.75 && pops[0].box[1] <= 50 && pops[0].box[3] >= 50, `box ${pops[0].box} contains the drawn box centre`);
+ assert.equal(pops[0].kind, "appears");
+ assert(pops[0].strip.includes("eq(n,15)") && pops[0].strip.includes("tile=5x1"), "review strip command embedded");
+ ok("e2e pop clip: exactly the known pop at frame 15, box covers it, strip command given");
+
+ const clean = run([cleanMp4]);
+ assert.equal(clean.length, 0, `the clean clip reports nothing, got ${JSON.stringify(clean)}`);
+ ok("e2e clean clip: hard cut and motion report zero findings");
+
+ try { execFileSync("node", [join(TOOLS, "popscan.mjs"), "definitely-not-a-film"], { cwd: ENGINE, encoding: "utf8" }); assert.fail("missing file must exit 2"); }
+ catch (e) { assert.equal(e.status, 2, "unreadable/missing file exits 2"); }
+ const okExit = execFileSync("node", [join(TOOLS, "popscan.mjs"), cleanMp4], { cwd: ENGINE, encoding: "utf8" });
+ assert(okExit.includes("POPSCAN: clean"), "a film never fails: clean scan exits 0 and says so");
+ ok("exit codes: 0 always after a scan, 2 for a file that cannot be read");
+
+ // the printed strip command is POSIX-paste-safe for any filename: the metacharacters below
+ // must arrive at ffmpeg as literal bytes, so an injected command never runs
+ {
+ const nasty = join(root, `pop 'q' $(touch INJECTED-A) \`touch INJECTED-B\` "dq".mp4`);
+ copyFileSync(popMp4, nasty);
+ const r = run([nasty]);
+ assert.equal(r.length, 1, "a shell-hostile name still scans");
+ const cmd = r[0].strip;
+ assert(cmd.includes("-fps_mode passthrough") && !cmd.includes("-vsync"), "the strip uses -fps_mode passthrough, not the deprecated -vsync");
+ assert(cmd.includes(`'\\''`), "a single quote in the name is '\\\\''-escaped");
+ const outDir = join(ENGINE, "out"), pngsBefore = readdirSync(outDir);
+ execFileSync("sh", ["-c", cmd], { cwd: ENGINE }); // really paste it: a quoting slip makes ffmpeg fail or runs the injection
+ assert(!existsSync(join(ENGINE, "INJECTED-A")) && !existsSync(join(ENGINE, "INJECTED-B")), "no injected command ran");
+ const png = readdirSync(outDir).filter((f) => f.startsWith("popscan-") && f.endsWith("-f15.png") && !pngsBefore.includes(f));
+ assert.equal(png.length, 1, `the strip rendered its review PNG (${png[0]})`);
+ rmSync(join(outDir, png[0]));
+ }
+ ok("strip command: paste-safe under shell metacharacters, -fps_mode passthrough, renders the PNG");
+
+ // a missing or failing ffprobe/ffmpeg is one clear line and exit 2, not a stack trace
+ {
+ const oneLine = (e) => { assert.equal(e.status, 2, "exit 2"); const err = (e.stderr || "").trim(); assert.equal(err.split("\n").length, 1, `one line on stderr, got: ${err.slice(0, 120)}`); assert(err.startsWith("popscan:"), `the line names the tool: ${err}`); };
+ writeFileSync(join(root, "not-video.mp4"), "this is not a video");
+ try { execFileSync("node", [join(TOOLS, "popscan.mjs"), join(root, "not-video.mp4")], { cwd: ENGINE, encoding: "utf8" }); assert.fail("a non-video must exit 2"); }
+ catch (e) { oneLine(e); }
+ try { execFileSync(process.execPath, [join(TOOLS, "popscan.mjs"), cleanMp4], { cwd: ENGINE, encoding: "utf8", env: { PATH: "/nonexistent-dir" } }); assert.fail("missing ffprobe must exit 2"); }
+ catch (e) { oneLine(e); }
+ const stub = join(root, "stub-bin"); mkdirSync(stub); // ffprobe answers, ffmpeg is gone
+ writeFileSync(join(stub, "ffprobe"), `#!/bin/sh\necho '{"streams":[{"width":160,"height":120,"avg_frame_rate":"30/1"}]}'\n`);
+ chmodSync(join(stub, "ffprobe"), 0o755);
+ try { execFileSync(process.execPath, [join(TOOLS, "popscan.mjs"), cleanMp4], { cwd: ENGINE, encoding: "utf8", env: { PATH: stub } }); assert.fail("missing ffmpeg must exit 2"); }
+ catch (e) { oneLine(e); }
+ }
+ ok("tool failures: unprobeable file, missing ffprobe, missing ffmpeg -> one clear line, exit 2");
+} finally {
+ rmSync(root, { recursive: true, force: true });
+}
+console.log(`\nPOPSCAN-UNIT: PASS ${pass} checks`);
diff --git a/skills/anidoodle/engine/tools/popscan.mjs b/skills/anidoodle/engine/tools/popscan.mjs
new file mode 100644
index 0000000..529f704
--- /dev/null
+++ b/skills/anidoodle/engine/tools/popscan.mjs
@@ -0,0 +1,120 @@
+// node tools/popscan.mjs <film|path.mp4> [--from F] [--to T] [--grid 12] [--min 0.4] [--ratio 0.35] [--json]
+// POPSCAN. Finds the one-frame pop: a frame that differs from BOTH neighbours while the
+// neighbours agree with each other (a flashed element, a vanished element, a one-frame jump).
+// A hard cut is not a pop (after it, f and f+1 agree); fast continuous motion is not a pop
+// (f-1 and f+1 differ too); an intentional one-frame flash IS listed - a human reviews, the
+// tool never fails a film. The first and last frames cannot pop: a pop needs both neighbours.
+//
+// Measured per TILE, not per frame: a small pop inside a busy frame vanishes in a whole-frame
+// number. Decoded small and grey like deadair, split into a grid x grid of tiles, three
+// differences per tile: in = d(f-1,f), out = d(f,f+1), across = d(f-1,f+1). A tile pops when
+// in and out are both at least --min percent of the tile and across is at most --ratio of the
+// smaller of the two. Adjacent (diagonals count) popping tiles on one frame are ONE finding
+// with a bounding box. `kind` is a cheap guess from texture in the box: appears/vanishes
+// add/remove it, jumps rearrange it. --from/--to bound which frames may be findings; the
+// decode still runs from 0 so frame numbers stay absolute (a --to stops it early).
+import { execFileSync } from "node:child_process";
+import { existsSync, mkdirSync } from "node:fs";
+import { basename, resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import { greyFrames } from "./motion.mjs";
+
+// The detector: pure, frames in -> findings out, no I/O. `frames` is any (sync or async)
+// iterable of width*height greyscale bytes. Findings: { frame, box [x0,y0,x1,y1] as frame
+// fractions, in, out, across as changed shares 0..1, tiles, kind }.
+export const scanPops = async (frames, { width: W, height: H, grid = 12, min = 0.004, ratio = 0.35, thresh = 4, from = 1, to = Infinity } = {}) => {
+ const g2 = grid * grid, px = W * H;
+ const tileOf = new Uint16Array(px), size = new Uint32Array(g2);
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { const t = Math.floor((y * grid) / H) * grid + Math.floor((x * grid) / W); tileOf[y * W + x] = t; size[t]++; }
+ const diff = (a, b) => { const c = new Uint32Array(g2); for (let i = 0; i < px; i++) if (Math.abs(a[i] - b[i]) > thresh) c[tileOf[i]]++; return Float64Array.from(c, (v, t) => v / size[t]); };
+ const std = (f, x0, y0, x1, y1) => { let s = 0, s2 = 0; for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const v = f[y * W + x]; s += v; s2 += v * v; } const n = (x1 - x0) * (y1 - y0), m = s / n; return Math.sqrt(Math.max(0, s2 / n - m * m)); };
+ const findings = [];
+ let index = -1, p2 = null, p1 = null, dIn = null;
+ for await (const cur of frames) {
+ index++;
+ if (p1 === null) { p1 = cur; continue; }
+ const dOut = diff(p1, cur), f = index - 1;
+ const dAcross = dIn && p2 && f >= from && f <= to ? diff(p2, cur) : null; // skip the third diff on ineligible frames
+ if (dAcross) {
+ const hit = new Uint8Array(g2);
+ for (let t = 0; t < g2; t++) if (dIn[t] >= min && dOut[t] >= min && dAcross[t] <= ratio * Math.min(dIn[t], dOut[t])) hit[t] = 1;
+ const seen = new Uint8Array(g2);
+ for (let t = 0; t < g2; t++) {
+ if (!hit[t] || seen[t]) continue;
+ const stack = [t], tiles = []; seen[t] = 1;
+ let tx0 = grid, ty0 = grid, tx1 = -1, ty1 = -1;
+ while (stack.length) {
+ const u = stack.pop(); tiles.push(u);
+ const uy = Math.floor(u / grid), ux = u % grid;
+ tx0 = Math.min(tx0, ux); ty0 = Math.min(ty0, uy); tx1 = Math.max(tx1, ux); ty1 = Math.max(ty1, uy);
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
+ if (!dx && !dy) continue;
+ const vy = uy + dy, vx = ux + dx;
+ if (vx < 0 || vy < 0 || vx >= grid || vy >= grid) continue;
+ const v = vy * grid + vx;
+ if (hit[v] && !seen[v]) { seen[v] = 1; stack.push(v); }
+ }
+ }
+ let iN = Infinity, oU = Infinity, aC = 0;
+ for (const t of tiles) { iN = Math.min(iN, dIn[t]); oU = Math.min(oU, dOut[t]); aC = Math.max(aC, dAcross[t]); }
+ const px0 = Math.floor((tx0 * W) / grid), py0 = Math.floor((ty0 * H) / grid), px1 = Math.floor(((tx1 + 1) * W) / grid), py1 = Math.floor(((ty1 + 1) * H) / grid);
+ const dStd = std(p1, px0, py0, px1, py1) - (std(p2, px0, py0, px1, py1) + std(cur, px0, py0, px1, py1)) / 2;
+ findings.push({ frame: f, tiles: tiles.length, box: [px0 / W, py0 / H, px1 / W, py1 / H], in: iN, out: oU, across: aC, kind: dStd > 3 ? "appears" : dStd < -3 ? "vanishes" : "jumps" });
+ }
+ }
+ p2 = p1; p1 = cur; dIn = dOut;
+ }
+ return findings;
+};
+
+const MAIN = process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
+if (MAIN) {
+ const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d; };
+ const die = (m) => { console.error(`popscan: ${m}`); process.exit(2); };
+ const a0 = process.argv[2];
+ if (!a0 || a0.startsWith("--")) { console.error("usage: node tools/popscan.mjs <film|path.mp4> [--from F] [--to T] [--grid 12] [--min 0.4] [--ratio 0.35] [--json]"); process.exit(2); }
+ const file = resolve(a0.endsWith(".mp4") ? a0 : `out/${a0}.mp4`);
+ if (!existsSync(file)) die(`no such file: ${file}`);
+ let probe;
+ try { probe = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,avg_frame_rate", "-of", "json", file], { stdio: ["pipe", "pipe", "pipe"] })); }
+ catch (e) { die(`ffprobe cannot read ${file}: ${String(e.stderr || e.message).trim().split("\n")[0] || "failed"}`); }
+ const stream = probe.streams?.[0];
+ if (!stream) die(`ffprobe finds no video stream in ${file}`);
+ const [fpsNum, fpsDen] = stream.avg_frame_rate.split("/").map(Number);
+ const fps = fpsNum / fpsDen || 30;
+ const GRID = Number(arg("grid", 12)), MIN = Number(arg("min", 0.4)) / 100, RATIO = Number(arg("ratio", 0.35)), THRESH = Number(arg("thresh", 4)), SIZE = Number(arg("size", 270));
+ const FROM = Number(arg("from", 1)), TO = arg("to") === undefined ? Infinity : Number(arg("to"));
+ if ([GRID, MIN, RATIO, THRESH, SIZE, FROM].some((v) => !Number.isFinite(v)) || Number.isNaN(TO)) die("a numeric option is not a number");
+ if (!Number.isInteger(GRID) || GRID < 2 || GRID > 64) die("--grid wants an integer in [2, 64]");
+ if (!(MIN > 0 && MIN < 1) || !(RATIO > 0)) die("--min wants a percent in (0, 100), --ratio a positive number");
+ const W = SIZE, H = Math.max(2, Math.round((SIZE * stream.height) / stream.width));
+ if (Math.floor(W / GRID) < 2 || Math.floor(H / GRID) < 2) die(`--grid ${GRID} leaves tiles under 2px at ${W}x${H}`);
+ const OUT = resolve("out"); mkdirSync(OUT, { recursive: true });
+ const stem = basename(file).replace(/\.[^.]*$/, "").replace(/[^\w.-]+/g, "-");
+ let n = 0;
+ const counted = (async function* () { for await (const fr of greyFrames(file, W, H, TO === Infinity ? Infinity : TO + 2)) { n++; yield fr; } })();
+ let findings;
+ try { findings = await scanPops(counted, { width: W, height: H, grid: GRID, min: MIN, ratio: RATIO, thresh: THRESH, from: FROM, to: TO }); }
+ catch (e) { die(String(e.message || e).trim().split("\n")[0]); }
+ if (!n) die("decoded 0 frames");
+ const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`; // POSIX single-quote: the strip is safe to paste whatever the film is named
+ const strip = (f) => {
+ const lo = Math.max(0, f - 2), hi = Math.min(n - 1, f + 2), sel = [];
+ for (let i = lo; i <= hi; i++) sel.push(`eq(n,${i})`);
+ const png = resolve(OUT, `popscan-${stem}-f${f}.png`);
+ return `ffmpeg -v error -y -i ${shq(file)} -vf "select='${sel.join("+")}',scale=384:-2,tile=${hi - lo + 1}x1" -fps_mode passthrough -frames:v 1 ${shq(png)}`;
+ };
+ const pct = (v) => +(v * 100).toFixed(2);
+ if (process.argv.includes("--json")) {
+ console.log(JSON.stringify(findings.map((r) => ({ frame: r.frame, t: +(r.frame / fps).toFixed(3), box: r.box.map(pct), in: pct(r.in), out: pct(r.out), across: pct(r.across), tiles: r.tiles, kind: r.kind, strip: strip(r.frame) })), null, 2));
+ } else {
+ console.log(`${file}\n ${n} frames decoded at ${W}x${H} grey, ${GRID}x${GRID} tiles, threshold ${THRESH}/255`);
+ for (const r of findings) {
+ console.log(` POP frame ${r.frame} t=${(r.frame / fps).toFixed(3)}s box ${r.box.map((v) => (v * 100).toFixed(1)).join(",")}% in ${pct(r.in)}% out ${pct(r.out)}% across ${pct(r.across)}% ${r.kind} (${r.tiles} tile${r.tiles > 1 ? "s" : ""})`);
+ console.log(` strip: ${strip(r.frame)}`);
+ }
+ console.log(findings.length ? ` POPSCAN: ${findings.length} finding(s) to review (a flag, never a fail)` : " POPSCAN: clean, no one-frame pops");
+ }
+ // exitCode, not process.exit: a big --json write to a pipe would otherwise truncate at 64k
+ process.exitCode = 0;
+}
diff --git a/skills/anidoodle/engine/tools/sfx.mjs b/skills/anidoodle/engine/tools/sfx.mjs
index 1fb4e2f..e84c4cd 100644
--- a/skills/anidoodle/engine/tools/sfx.mjs
+++ b/skills/anidoodle/engine/tools/sfx.mjs
@@ -39,6 +39,13 @@ const hfShare = (M, L) => {
return 10 * Math.log10(Math.max(hi, 1e-30) / Math.max(tot, 1e-30));
};
const dcOf = (L) => { let s = 0; for (const x of L) s += x; return s / L.length; };
+const harshColumns = (h) => {
+ const f = (v) => v === null ? "n/a" : v.toFixed(2);
+ return `band cue/score ${f(h.cueBandDb)}/${f(h.musicBandDb)} lift ${f(h.liftDb)} full ${f(h.cueRmsDb)} tilt ${f(h.tiltDb)} peak/score ${f(h.peakDb)}/${f(h.musicPeakDb)} peak over score ${f(h.peakMarginDb)} body(150ms) ${f(h.bodyDb)} peak-body ${f(h.crestDb)} dB harsh ${h.ok ? "PASS" : "FAIL"}${h.mode === "tame" ? ` tame -${f(h.reductionDb)} dB` : ""}${h.conflict ? " conflict: " + h.conflict : ""}`;
+};
+const printAudibility = (mix) => {
+ for (const a of mix.audibility) console.log(` ${a.atS.toFixed(2).padStart(6)} s ${(a.kind + ":" + a.variant).padEnd(16)} ${a.label.padEnd(22)} margin ${a.marginDb.toFixed(1).padStart(5)} dB (peak ${a.peakMarginDb.toFixed(1)} dB) ${harshColumns(mix.harshness.find((h) => h.i === a.i))}`);
+};
/** Three varied hits of one variant, back to back, so the ear hears the variation. */
const reel = (M, kind, variant, opts = {}) => {
@@ -116,14 +123,14 @@ const kit = async (outdir) => {
writeAudio(join(dir, "demo-sfx-only.mp3"), mix.sfx[0], mix.sfx[1]);
writeAudio(join(dir, "demo-music-only.mp3"), music[0], music[1]);
execFileSync("ffmpeg", ["-v", "error", "-y", "-i", join(dir, "demo.mp3"), "-lavfi", "showspectrumpic=s=900x220:legend=0:scale=log", join(dir, "spectra", "demo.png")]);
- meters.demo = { ok: mix.ok, lufs: +mix.lufs.toFixed(1), dbtp: +mix.dbtp.toFixed(2), limiterDb: +mix.limiterDb.toFixed(2), cues: mix.audibility.map((a) => ({ kind: `${a.kind}:${a.variant}`, label: a.label, atS: +a.atS.toFixed(2), marginDb: +a.marginDb.toFixed(1), peakMarginDb: +a.peakMarginDb.toFixed(1) })) };
+ meters.demo = { ok: mix.ok, lufs: +mix.lufs.toFixed(1), dbtp: +mix.dbtp.toFixed(2), limiterDb: +mix.limiterDb.toFixed(2), cues: mix.audibility.map((a) => ({ kind: `${a.kind}:${a.variant}`, label: a.label, atS: +a.atS.toFixed(2), marginDb: +a.marginDb.toFixed(1), peakMarginDb: +a.peakMarginDb.toFixed(1), harshness: mix.harshness.find((h) => h.i === a.i) })) };
writeFileSync(join(dir, "meters.json"), JSON.stringify(meters, null, 1));
const demo = [["demo.mp3", "demo: score + kit", `15 s, ${plan.cues.length} cues, ${mix.lufs.toFixed(1)} LUFS, ${mix.dbtp.toFixed(1)} dBTP, every cue audible: ${mix.ok}`], ["demo-sfx-only.mp3", "demo: kit only", "the same cues without the score"], ["demo-music-only.mp3", "demo: score only", "launchLofi3, first 15 s, undipped"],
...Object.keys(meters.baseline).map((k) => [`baseline-${k}.mp3`, `baseline: launch3 ${k}`, "the launch film's current effect, for A/B"])];
writeFileSync(join(dir, "index.html"), page(rows, demo));
console.log(`wrote ${dir}: ${rows.reduce((a, r) => a + r[2].length, 0)} variant reels, 3 demo files, ${Object.keys(meters.baseline).length} baselines, index.html, meters.json, spectra/`);
console.log(`demo: ${mix.lufs.toFixed(1)} LUFS, ${mix.dbtp.toFixed(2)} dBTP, limiter ${mix.limiterDb.toFixed(2)} dB, all audible: ${mix.ok}`);
- for (const a of mix.audibility) console.log(` ${a.atS.toFixed(2).padStart(6)} s ${(a.kind + ":" + a.variant).padEnd(16)} ${a.label.padEnd(22)} margin ${a.marginDb.toFixed(1).padStart(5)} dB (peak ${a.peakMarginDb.toFixed(1)} dB)`);
+ printAudibility(mix);
};
const test = async () => {
@@ -181,6 +188,7 @@ const test = async () => {
ok(m1.L.length === Math.round((DEMO_FRAMES / FPS) * SR), "demo mix is exactly the film length");
ok(m1.dbtp <= -0.9, `demo true peak <= -1 dBTP (got ${m1.dbtp.toFixed(2)})`);
ok(m1.ok && m1.audibility.every((a) => a.marginDb >= -6), `demo: every cue within 6 dB of the score (worst ${Math.min(...m1.audibility.map((a) => a.marginDb)).toFixed(1)} dB)`);
+ printAudibility(m1);
const g = m1.placed.find((p) => p.cue.label === "Generate"); ok(g && Math.abs(g.hitS - 160 / 30) < 1e-9, `snap to beat: frame 157 -> 160 (got ${g && (g.hitS * 30).toFixed(2)})`);
const imp = m1.placed.find((p) => p.cue.kind === "impact"); ok(imp && Math.min(...Array.from(m1.duck.subarray(imp.window[0], imp.window[1]))) < 0.55, "score ducks >= 5 dB under the impact");
// a buried cue must FAIL
diff --git a/skills/anidoodle/references/craft-bar.md b/skills/anidoodle/references/craft-bar.md
index 865127c..ce7b1e6 100644
--- a/skills/anidoodle/references/craft-bar.md
+++ b/skills/anidoodle/references/craft-bar.md
@@ -19,9 +19,9 @@ The test: would a proud human illustrator ship this, or is it mechanical shape-a
| The same character drawn differently shot to shot | One character module; shots pose it, never redraw it (`workflows/character-consistency.md`) |
| A silhouette filled with texture, no mouth line, no toes | Interior contours: mouth, eyelids, nostrils, toes, joins between forms (the detail pass below) |
| A drawing film where the finished picture fades in | Marks made in the medium's order; the last frames are the still (`workflows/drawing-process.md`) |
-| Words laid over the art or the UI | Type gets its own frame; corner marks step aside when the camera brings UI under them |
+| Words laid over busy art, a face or the UI | Type gets its own frame by default; over the picture only as a composed label or kinetic line on a calm area (`workflows/launch-video.md`, Type) |
| A loop playing in place and called "alive" | Real travel through a world that changes as the subject moves |
-| A hard cut or a sharp swoosh between scenes | A gentle move: a bloom, a flip, a push, the card grows into the frame |
+| An unmatched hard cut or a sharp swoosh between scenes | A gentle move (a bloom, a flip, a push, the card grows into the frame), or a cut matched on shape, position or beat |
**No dead air** in anything that moves: something visibly changes in every second, from frame 0.
Check it with the tool AND by eye: a creeping camera changes every pixel and satisfies the tool
diff --git a/skills/anidoodle/references/motion-grammar.md b/skills/anidoodle/references/motion-grammar.md
new file mode 100644
index 0000000..dfb74c4
--- /dev/null
+++ b/skills/anidoodle/references/motion-grammar.md
@@ -0,0 +1,163 @@
+# Motion grammar: six ways to get from one picture to the next
+
+A film that shows one good thing, then another unrelated good thing, reads as a slideshow however
+well each is animated. These six mechanisms are ways to make the next picture come OUT of the
+current one. They are a grammar to compose from, never presets: pick the one the story is already
+asking for, and build it for that film's subject and medium.
+
+**The default does not change.** A gentle move (a bloom, a flip, a push) is still the standard
+seam (`workflows/launch-video.md`, Motion). Each mechanism below is a judgement with conditions.
+If its "use it when" does not clearly hold, use the gentle move.
+
+Three things hold for all six:
+
+- **The destination is in place before the move starts.** The next scene is already drawn under
+ or behind the move, so there is never an empty frame between scenes.
+- **Something is carried across**: a shape, a position, a direction of travel. That is what
+ separates a designed seam from a transition laid over a join.
+- **One or two mechanisms a film, each used for the seams that matter.** All six in 30 seconds is
+ a demo reel of moves, not a story.
+
+## 1. Foreground as transition
+
+Something already in the scene (a word, a mark, a shape) grows or sweeps until it covers the
+frame, and when it clears the next scene is there.
+
+- **Use it when** the covering thing is part of the story (the brand's ink, the product's mark,
+ the claim itself) and the two scenes share nothing else to carry across.
+- **Not when** the cover would be an arbitrary shape brought in only to hide the join, or when it
+ would happen on every seam: the third time, it reads as a wipe preset.
+- **Ours**: the type frames of the launch film (`launch3.ts`, `typeFrame` in `launchCut.ts`). Ink
+ blooms open from a point over the picture, the word letters itself on the page inside the
+ bloom, and the ink closes to a point on the NEXT picture. The bloom takes the content frame it
+ opens over and the one it closes onto as data (`type(lines, len, before, after)`), so the next
+ scene is always waiting under it.
+
+## 2. Persistent actor
+
+One object keeps its identity through the whole film while the scenes change around it.
+
+- **Use it when** the story already owns such an object (a cursor, the product's dot, a
+ character, a line being drawn) and it has a reason to be in every scene it visits.
+- **Not when** it has to be invented for the purpose, or dragged through scenes where it does
+ nothing: a mascot that only watches is decoration.
+- **Ours**: the ink drop in the launch template (`launchTemplate.ts`). Every press of Generate
+ sends a drop into the thread, where it blooms into the answer card; at the end it lifts off
+ Generate one last time, lands as the dot of the end card's mark, and the end card opens from
+ it. `motif.ts` holds it to the rule: same screen position and size on both sides of the seam,
+ within 2 px, or `checkRelay` throws.
+
+- **The general move**: `engine/src/canvas-core/morph.ts`. `handoff({ from, to, t0, t1 })` carries
+ one outline from a source shape to a target shape: it travels, stretches a little while it is
+ moving, and becomes the target in the second half of the trip, landing on it exactly.
+ `coverShape` grows a shape until it is the whole page. Keep the object's colour and edge the
+ same on both sides, and hold the seam with `checkShapes` (2 px). `morphDemo.ts`: a full stop
+ becomes a card, the card becomes the page.
+
+## 3. Selection to expansion
+
+One item in a set is picked, and it grows until it IS the next scene.
+
+- **Use it when** the story moves from many to one: a wall of options, then the one being used;
+ a list, then the item opened. The viewer sees where the next scene came from.
+- **Not when** the set was only there to be left (build the set because the story needs range,
+ not as a launch pad), or when the item's small and full-frame versions do not match: frame the
+ full scene's first frame exactly like the card it grew from.
+- **Ours**: the style wall (`launchGallery.ts`, used in `launch2.ts`). The camera punches into
+ cards and comes back out; the last punch does not come back, the card fills the frame and
+ becomes the scene. The koi does the same from a still: `koiWorld.ts` frames its first frame
+ exactly like the koi plate, so the card hands over to the swimming world with no seam.
+
+## 4. Registered decomposition
+
+A whole stays recognisable while its parts move into groups, each part traceable from where it
+was to where it lands.
+
+- **Use it when** the point is that the product sorts, extracts or reorganises something the
+ viewer has just seen: a crowded week becoming a plan, a document becoming fields.
+- **Not when** the parts cannot be followed. Past about seven moving at once, or with parts that
+ cross paths, the viewer loses the map; stagger them, or move groups rather than items.
+- **Ours**: `productUI.ts` (a `kind: "ui"` ask in the launch template). The interface is drawn
+ from data in two states. One press of the product's action and every item, matched by id,
+ springs from its place in the before state to its place in the after: rows travel to their new
+ slots, values count to their new numbers, new items arrive, old ones leave.
+
+## 5. Continuous canvas
+
+All the scenes live in one layout bigger than the frame, and the camera travels between them
+instead of cutting.
+
+- **Use it when** the places are really related in space (sections of one page, rooms of one
+ building, steps along one path) and the route between them tells the viewer how.
+- **Not when** the places are unrelated (the travel then invents a relationship that is not
+ there), or when the journey between two stops is long and empty: every second must change
+ (`craft-bar.md`, no dead air). One camera for every plane (`camera.md`).
+- **Ours**: `webTour.ts`. Three sections on one long page, a visible cursor, and a camera that
+ shows the whole page, then pushes in on every click and every field. `koiWorld.ts` is the
+ drawn version: a pond much bigger than the frame, with the scenery placed in the world so it
+ changes as the fish travels.
+
+## 6. Exploded layers
+
+One object separates into its layers along its depth, holds so each can be read, then closes
+back into the object.
+
+- **Use it when** what is inside is the point: how a thing is built, what a stack is made of.
+ The layers must be real parts of the subject, in their real order.
+- **Not when** the subject has no true layers and they would be invented for the effect, or when
+ the pieces are not held long enough apart to be read. If it never closes again, it is a
+ diagram, which may be what the film wants; decide which.
+- **Ours, in one direction only**: `paperCraft.ts`, the toy theatre. The scene is built from the
+ back, flat by flat, with real gaps between the flats: each piece travels held above the stack,
+ its shadow wide and far, and the shadow closes as it lands. That is the closing half. No film
+ of ours yet starts whole and separates; treat the opening half as unproven until one does.
+
+## Three ready-made seams
+
+For a plain change of scene that still wants a made mark, `engine/src/canvas-core/transitions.ts`
+has three calls. Each takes the two scenes as draw functions and a progress, at any frame size,
+with the incoming scene already complete underneath. `transitionsDemo.ts` shows each once.
+
+- **`brushWipe`**: a loaded brush pulled across; with `ink`, a band of wet ink ahead of the new
+ picture (without it, a clean bristled edge).
+ For the drawn register, in the direction the story is already moving. Not in the clean
+ register, and not more than once or twice a film.
+- **`iris`**: a round opening from a point, or closing to one. Open it from the thing the next
+ scene is about, close it on the thing this one was about; centred on nothing it is only a
+ shape. `shape: "blot"` for ink, the plain circle for the clean register.
+- **`flashCut`**: a hard cut under a short burst of light, so the hard cut's conditions apply
+ (a strong beat, in a piece whose energy asks for it). Never one frame, never full white by
+ default, never repeated quickly: declare a film's flashes to `checkFlashes`, which throws on
+ any two within half a second.
+
+## Callouts and the label handoff
+
+`engine/src/canvas-core/callout.ts` names one thing in the picture: a dot lands on it, a leader
+line is drawn out, a label is written at the end. The dot follows the thing as the camera moves
+(pin it with `cam.toScreen`, `camera.md`); the label holds still so it can be read. It is type
+over the picture, so that judgement applies in full (`workflows/launch-video.md`, Type): a calm
+area, a label that names what it points at, one or two on screen at a time. Where the picture is
+busy, give the label a `backing` or leave the callout out.
+
+The label can also be the persistent actor across a seam. With `handoff`, the dot and line
+retract and the label travels to where the next scene starts, landing as its heading on that
+scene's first frame; the next scene draws it from there with `drawLabel` at the same pose.
+`checkHandoff` holds the two sides to within 2 px and throws if the seam jumps.
+`calloutDemo.ts` shows both.
+
+## Choosing
+
+Ask what the seam has to tell the viewer, then take the mechanism that says it:
+
+| The seam says | Mechanism |
+|---|---|
+| "and now this", with nothing shared but the brand | Foreground as transition |
+| "the same thing, further along" | Persistent actor |
+| "this one, out of all of those" | Selection to expansion |
+| "the same things, put in order" | Registered decomposition |
+| "next to that, over here" | Continuous canvas |
+| "and this is what is inside" | Exploded layers |
+
+If none of these is what the seam says, it is a plain change of scene: use the gentle move, or
+a matched hard cut where its conditions hold. Review every designed seam as a before/after pair
+of stills, and as a strip of the frames between them, before the film is rendered in full.
diff --git a/skills/anidoodle/references/music/sound-design.md b/skills/anidoodle/references/music/sound-design.md
index b4754a1..5cdf9b6 100644
--- a/skills/anidoodle/references/music/sound-design.md
+++ b/skills/anidoodle/references/music/sound-design.md
@@ -112,8 +112,8 @@ music, and its test only checked that they existed.)
makes it land.
- **One signature riser, one impact per film.** They mark the big reveal. A second riser halves
both.
-- Transitions are gentle moves, so their sound is gentle: `whoosh:soft` and `swish:soft`. Never a
- sharp swoosh.
+- Transitions are gentle moves by default, so their sound is gentle: `whoosh:soft` and
+ `swish:soft`. A matched hard cut takes a short hit on the beat or nothing. Never a sharp swoosh.
- Typing is one `tick` per character at the typing cadence, with `space` on spaces. Its level sits
above the intro and under the groove.
- Put at most two cues in any 100 ms. A thock on the kick merges into the kick, which is lovely
diff --git a/skills/anidoodle/references/workflows/launch-video.md b/skills/anidoodle/references/workflows/launch-video.md
index d0651c7..7510821 100644
--- a/skills/anidoodle/references/workflows/launch-video.md
+++ b/skills/anidoodle/references/workflows/launch-video.md
@@ -50,12 +50,19 @@ pieces are examples of the craft, never material for someone else's film.
## Type
-- **Words NEVER sit over the art or the UI.** A word gets its own full frame: an ink bloom
+- **Words get their own space by default.** A word gets its own full frame: an ink bloom
opens, a brush writes the word, the bloom closes on the next scene (`typeFrame`). Or, for a
feature beat, its own COLUMN: words on the left, the live UI on the right (words above, UI
below on a phone), each in its own area of the layout (`split`), faster than a full word page.
Corner marks step aside when the camera brings UI under them, and sit in their own strip on a
phone frame.
+- **Type over the picture is a judgement, and the answer is usually still no.** It earns its
+ place only when all of these hold: the picture under the word is calm there (flat or quiet,
+ and not moving through the letters); the word belongs to the scene (a label on the thing it
+ names, a callout, a kinetic line composed with the picture, not a caption dropped on top);
+ the frame would pass as a poster; and it reads with the sound off. Never over a face, a
+ product's UI, the detail the shot is about, or busy texture. Check it in a review still at
+ the smallest delivery size. In doubt, the word gets its own frame.
- **3-7 words a frame, few frames.** Collapse word cards into one claim then proof ("JUST CODE."
then "31 STYLES"); fewer cards leave more time for the proof.
- **Hold each settled word 0.5 s or more**, longer for the claim.
@@ -64,8 +71,14 @@ pieces are examples of the craft, never material for someone else's film.
## Motion
-- **Every transition is a gentle move**: bloom, card flip, push, the card GROWS into the frame.
- Never a hard cut, never a sharp swoosh. Ease in and out; the camera is `references/camera.md`.
+- **A gentle move is the default transition**: bloom, card flip, push, the card GROWS into the
+ frame. Ease in and out; the camera is `references/camera.md`.
+- **A hard cut is a judgement.** It works when it is matched: the same shape, position or
+ direction of travel on both sides, or a cut on a strong beat in a piece whose energy asks for
+ it. A cut with nothing carried across it, and any sharp swoosh, still reads as a slideshow.
+- **A designed seam is a judgement too.** Six ways to make the next picture come out of the
+ current one, each with when it fits and when it does not: `references/motion-grammar.md`.
+ Use one where its conditions clearly hold; otherwise the gentle move.
- **Drawings play 3-6x faster than real time**; a loop is held long enough to see it loop.
- **Alive means real motion**: the koi swims through a scrolling world, not an in-place GIF
(`start-here.md`, "Alive means real motion").
diff --git a/skills/anidoodle/references/workflows/long-film.md b/skills/anidoodle/references/workflows/long-film.md
index 6be565d..cbb813c 100644
--- a/skills/anidoodle/references/workflows/long-film.md
+++ b/skills/anidoodle/references/workflows/long-film.md
@@ -24,7 +24,8 @@ A long film is a sequence of chapters, each with its own small arc, joined by on
section moods. Chapters import it; nobody changes it privately.
4. **Transitions carry the story**: each chapter hands over with a match cut, a covered switch
(a shape passing, a page turning, a fog at full density) or a shared token. A hard cut to
- black between every chapter is a slideshow.
+ black between every chapter is a slideshow. The six mechanisms, with when each fits, are
+ in `references/motion-grammar.md`.
5. **Music follows the chapters**: one theme, varied per chapter mood (see
`references/music/`), with the transitions scored (pre-lap, pivot chord, texture handoff).
6. **Review per chapter, then once whole**: a contact sheet per chapter at one tile per beat,