Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.
TypeScript agent-skillsanimationcanvasclaude-codeclaude-pluginclaude-skillscodex-plugincreative-codecreative-codingcreative-toolsdeterministicgenerative-arthand-drawnillustrationlaunch-videomotion-designmotion-graphicspluginprocedural-generationskill
sync plugin folder for 0.10.0
Alex Greenshpunc8f4f161a966
diff --git a/plugins/anidoodle/.claude-plugin/plugin.json b/plugins/anidoodle/.claude-plugin/plugin.jsonindex 97f371c..2f9601c 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 32 styles, with scores composed in code.",- "version": "0.9.6",+ "version": "0.10.0","icon": "./assets/icon.png","author": {"name": "Alex Greenshpun",diff --git a/plugins/anidoodle/.codex-plugin/plugin.json b/plugins/anidoodle/.codex-plugin/plugin.jsonindex e17cc11..4fd7a56 100644--- a/plugins/anidoodle/.codex-plugin/plugin.json+++ b/plugins/anidoodle/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "anidoodle",- "version": "0.9.6",+ "version": "0.10.0","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.","skills": "./skills/","interface": {diff --git a/plugins/anidoodle/skills/anidoodle/SKILL.md b/plugins/anidoodle/skills/anidoodle/SKILL.mdindex 76f893f..1442e9a 100644--- a/plugins/anidoodle/skills/anidoodle/SKILL.md+++ b/plugins/anidoodle/skills/anidoodle/SKILL.md@@ -1,6 +1,6 @@---name: anidoodle-description: Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with composed scores. Matches a reference style, keeps characters consistent, teaches drawing. Deterministic, no generated assets.+description: Code-drawn stills, films, 3D motion graphics, explainers and web animations in 32 styles, with scores, narration and subtitles. Use when asked for an illustration, animation, video or drawing lesson.metadata:created_by: Alex Greenshpun (10x Company)license: Apache-2.0@@ -8,24 +8,23 @@ metadata:# anidoodle-Pictures, films and interactive pieces drawn entirely in code. One pure function paints every-frame; another composes the score and plays it. The same source rebuilds the same pixels and the-same sound on any machine, at any size, at any length. Eight acoustic instruments can play recordings-of real ones from an optional download. ASK the user before any score work; never download unasked.+Pictures, films and interactive pieces drawn entirely in code, in 2D or in 3D. One pure function+paints every frame; another composes the score and plays it. The same source rebuilds the same+pixels and the same sound on any machine, at any size, at any length. Eight acoustic instruments can+play recordings of real ones from an optional download. ASK the user before any score work; never download unasked.-The engine is the easy half. Work gets thrown away because it had no point, because the subject-was an icon of itself, because a style was only a palette swap, because the music had no form,-or because the person spent their patience approving fragments. This skill carries the craft-that prevents each of those.+The engine is the easy half. Work gets thrown away because it had no point, the subject was an+icon of itself, a style was only a palette swap, the music had no form, or the person spent their+patience approving fragments. This skill carries the craft that prevents each of those.## Start by asking, then buildRead `references/workflows/start-here.md` and run its intake: one question at a time, onlywhat the request leaves open, your recommendation first. **What** are they making, in **which-style** (show the gallery sheet, https://github.com/alexgreensh/anidoodle/blob/main/skills/anidoodle/assets/styles.jpg; the list is `references/styles/INDEX.md`), what-**shape** (1x1, 9x16, 16x9, 4x5 or any W x H), how **long** (any length; never cap it), what-**sound** (silent or a music style and mood), which **characters**. "You pick" means pick and-say why in one line. Write the answers into a short brief before drawing.+style** (show the gallery sheet, https://github.com/alexgreensh/anidoodle/blob/main/skills/anidoodle/assets/styles.jpg; the list is `references/styles/INDEX.md`)+or in 3D (one medium per film), what **shape** (1x1, 9x16, 16x9, 4x5 or any W x H), how **long**+(any length; never cap it), what **sound** (silent, a music style and mood, narration), which+**characters**. "You pick" means pick and say why in one line. Write the answers into a short brief before drawing.## What are you making?@@ -35,16 +34,19 @@ say why in one line. Write the answers into a short brief before drawing.| A picture that draws itself (timelapse, making-of) | `references/workflows/drawing-process.md` || A loop, sticker, animated logo, ambient header | Loop workflow below, `references/formats.md` || A story film, any length | Film workflow below, `references/workflows/long-film.md` |+| A 3D film or 3D motion graphics: extruded type, objects, puppets, a camera through space | `references/workflows/three-d.md` || An explainer or infographic; a machine that comes apart to explain an idea, in any style | `references/workflows/explainer.md`, `references/workflows/machines.md` |-| A launch or product video (their screenshots welcome) | `references/workflows/launch-video.md`; build it on `references/workflows/launch-video-kit.md`; its claims: `references/workflows/facts.md` |+| A launch or product video, or 2D motion graphics (their screenshots welcome) | `references/workflows/launch-video.md`; one world, one camera: `references/workflows/motion-film.md`; the kit: `references/workflows/launch-video-kit.md`; claims: `references/workflows/facts.md` |+| A film in someone else's brand: their exact elements, logos, fonts, sponsors, an event program | `references/workflows/brand-film.md` (imported and signed off before the first board) || Art for a site (hero by a headline, tiles, spots, share card) on its page colour and brand; or a web animation that reacts to the UI | `references/workflows/site-art.md`; `references/workflows/interactive.md` || A drawing lesson, or "how do I draw this?" | `references/workflows/teach-drawing.md` || A character kept identical in any style (woodcut to toy brick) | `references/workflows/character-consistency.md`, `references/anatomy.md` || A style matched from their image | `references/workflows/adapt-a-style.md` |-| A score or soundtrack | `references/music/README.md` |+| A score or soundtrack; or a generated or licensed track cut to the film | `references/music/README.md`; `references/music/generated-tracks.md` |+| Narration, a voice-over, word timing or subtitles | `references/workflows/narration.md` |-- Music: pick a style vocabulary and mood, sketch the tension arc and motif, compose your own harmony, motif and form (references/music/compose.md, craft in references/music/theory/), revise until node tools/music.mjs craft shows only findings you chose, then check must PASS before a human listens. Styles give sound, never notes.-- Sound effects: references/music/sound-design.md. 14 layered, seeded effects cued by film frame (filmSfx); the score ducks, and every cue must be within 6 dB of it. Effects only on real direction changes, one riser + one impact per film.+- Music: pick a style vocabulary (`references/music/styles/vocabularies.md`; deep dives `references/music/styles/music-box.md`, `references/music/styles/lofi-electronic.md`) and mood, sketch the tension arc and motif, compose your own harmony, motif and form (references/music/compose.md, craft in references/music/theory/), revise until node tools/music.mjs craft shows only findings you chose, then check must PASS before a human listens. Styles give sound, never notes.+- Sound effects: references/music/sound-design.md. 14 layered, seeded effects cued by film frame (filmSfx); the score ducks, and every cue must be within 6 dB of it. Effects only on real direction changes, one riser + one impact per film. Under someone else's music, unpitched `tap` effects only.- Launch films: `launchTemplate.ts` renders a product's launch from data (prompts, plates or its own UI, a score composed for it, words, install lines) in every shape from one timeline; `launch.mjs new|ship`. Habits that save tokens: `references/working-method.md`.## The seven laws@@ -58,8 +60,10 @@ say why in one line. Write the answers into a short brief before drawing.4. **Prove the look on ONE still, then build end to end.** After that, gates cost more than theysave. → `references/working-method.md`5. **The contract is absolute.** Pure in `(frame, env)` (and the input log, for interactive- pieces), `rng(seed)` only, no clock, no `ctx.filter`. Nothing generated; images they bring may be- embedded by hash, and the sound pack is a separate, hash-pinned download. → `references/determinism-and-contract.md`+ pieces), `rng(seed)` only, no clock, no `ctx.filter`. Nothing generated, with one exception the+ person opts into: narration, in the voice they chose, each take cached by hash and baked into+ the film. Images they bring may be embedded by hash; the sound pack is a separate, hash-pinned+ download. → `references/determinism-and-contract.md`, `references/workflows/narration.md`6. **Music gets a plan, never an adjective.** A style, a mood per section, the notes as data, thenmeasurements. You cannot hear it, so one human listens before it ships. → `references/music/`7. **One directs, one builds, both write everything down.** When a session degrades, reset; the@@ -74,26 +78,23 @@ header first. (4) Draw in that medium's order. (5) Render with `still.mjs` at fusize and shape asked for from the same source, and say `reproducible` was printed.**Loop.** As a still, plus: every motion is periodic over the loop, the subject never stops,-something moves every second. Check the seam (last frame against frame 0). ✋ **One approval,-on the moving file.**+something moves every second. Check the seam (last frame against frame 0). ✋ **One approval, on the moving file.****Film.** (1) **The story in three sentences** (setup, transformation, payoff) and the token; for-longer films, a spine plus one line per chapter. If you cannot write it, stop. (2) **The grid**:+longer films, a spine plus one line per chapter; a launch or brand film adds a `board.json` that `board.mjs` passes. If you cannot write it, stop. (2) **The grid**:a beat is 60 x fps / bpm frames, the bpm from the brief's score; one cue table holds every frame number and a checkerruns at load. (3) **Real reference** for anything that exists. (4) **ONE look still**, the hardestframe, critiqued in writing. ✋ **Approval.** (5) **ONE 8-second music sample.** ✋ **Approval.**-(6) **Build the whole film**; mechanical checks run continuously. (7) **A fresh critic reviews, never you**+(6) **Build the whole film**; mechanical checks run continuously, and `ship.mjs` passes on the exact file before anyone sees a version. (7) **A fresh critic reviews, never you**(`references/workflows/review.md`): after the storyboard, each scene and the full render, a new subagent that saw none of the building returns ranked, timestamped problems and a verdict. Fix the biggest, a NEW critic rechecks; 3 rounds at most, logged in `ledger.md`.-(8) ✋ **Final approval.** Say what you verified and what you cannot.--Three approval gates at most. Approval is a budget; spend it where being wrong is expensive.+(8) ✋ **Final approval.** Say what you verified and what you cannot. Three approval gates at most. Approval is a budget; spend it where being wrong is expensive.## The craft barThe test: would a proud human illustrator ship this, or is it mechanical shape-assembly? The-full table of tells is `references/craft-bar.md`. The ones that sink most work: subjects built-from ellipses, one style recoloured into another, things that fade in instead of being drawn,-people with rubber joints, and a character drawn differently from shot to shot.+full table of tells is `references/craft-bar.md` (3D tells: `references/workflows/three-d.md`).+The ones that sink most work: subjects built from ellipses, one style recoloured into another,+things that fade in instead of being drawn, people with rubber joints, and a character drawn differently from shot to shot.**No dead air** in anything that moves: something visibly changes every second. A film thatdraws itself declares `kind: "drawing"` and is judged on a finer floor; a freeze still fails.@@ -101,7 +102,8 @@ draws itself declares `kind: "drawing"` and is judged on a finer floor; a freeze## The engine`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`.+about the DOM or any backend. `W`, `H`, `fps` and `durationFrames` come from the film's `meta`. Four backends, one art core → `references/backends-and-adapters.md`.+3D: `engine/src/three-core` renders three.js onto the same frame, so every tool below works on 3D films (three.js 0.170.0, hash-pinned, `engine/vendor/three/PROVENANCE.md`; type face `engine/assets/fonts/PROVENANCE.md`).Camera moves (pans, dollies, lens and dolly zooms, parallax, shake) and slow motion or freeze frames: `engine/src/canvas-core/camera.ts`, `engine/src/canvas-core/timeRemap.ts`, `references/camera.md`.Seams between scenes: `references/motion-grammar.md` (cuts that carry motion: `seams.ts`; `tools/deck.mjs deal` deals each film different moves; `deck.mjs find "<name>"` turns a move's everyday name into its card). `render.mjs --blur auto` renders with motion blur (subframes per framefrom its measured on-screen speed, averaged in linear light, `--shutter 180`); the default path is untouched.@@ -120,31 +122,26 @@ node <skill>/engine/tools/soundfetch.mjs get piano rooms # on their yes (piano| Tool | What it does ||---|---|| `scaffold.mjs` | a project with a still and/or film; `--duration`, `--format` or `--size`, `--fps`, `--bpm` |-| `still.mjs` / `render.mjs` | frames drawn twice with hashes (`--frames a,b,c --sheet` in one browser) / the piece in any format (`--from/--to`, `--poster-frame`, `--hashes`) |-| `gate.mjs` | determinism, contract, dead air, artifact; `--self-test` proves it can fail |-| `registry.mjs` / `gallery.mjs` | the style list from the plates themselves / the gallery sheet |-| `docs-check.mjs` | fails when any doc's style count, length or path disagrees with the code |+| `still.mjs` / `render.mjs` | frames drawn twice with hashes (`--frames a,b,c --sheet <file>` in one browser) / the piece in any format (`--from/--to`, `--poster-frame`, `--hashes`) |+| `gate.mjs` | determinism, contract, dead air, artifact, 3D checks; `--self-test` proves it can fail |+| `registry.mjs` / `gallery.mjs` / `docs-check.mjs` | the style list from the plates / the gallery sheet / fails when a doc's style count, length or path disagrees with the code || `verify-export.mjs` | QA on the rendered file: frames, duration, score, A/V sync, true peak after the encode; opt-in first frame, loop seam, `--delivery` |-| `launch.mjs` | a launch film: `new <name>` scaffolds the spec; `ship <name> --shapes 16x9,9x16` renders, posters, captions, verifies and framechecks each (`framecheck.mjs`: text whole, up long enough to read, clear of the 9:16 phone zones) and checks `facts.json` (`facts.mjs`) |+| `launch.mjs` | a launch film: `new <name>` scaffolds the spec (its `look` wears the product's own fonts, palette, shapes and logo: launch-video-kit.md, Looks); `ship <name> --shapes 16x9,9x16` renders, posters, captions, verifies and framechecks each (`framecheck.mjs`: text whole, up long enough to read, clear of the 9:16 phone zones) and checks `facts.json` (`facts.mjs`) || `test.mjs` (`npm test`) | unit suites in `engine/test/`, no browser || `music.mjs` | `vocab` prints a style's vocabulary; `check` gates your composed score (key, master, guards, stems, novelty, which parts played recordings) and prints its shape (ARC); `render`, `meter` |-| `soundfetch.mjs` | the sound pack: `list`, `get <id...\|all>`, `where`, `verify`, `remove <id>` |-| `sfx.mjs` | the sound-effects kit: `list`, `one`, `kit <dir>`, `test` |--Four backends, one art core: `playwright`, `html-player`, `remotion`, `hyperframes`.-→ `references/backends-and-adapters.md`+| `narrate.mjs` | narration: `say` (takes, cached), `time`, `check` (hears every word back; exit 1 on a dropped word), `bake`, `all`, `providers` |+| `soundfetch.mjs` / `sfx.mjs` | the sound pack: `list`, `get <id...\|all>`, `where`, `verify`, `remove <id>` / the effects kit: `list`, `one`, `kit <dir>`, `test` |+| `ship.mjs` | every check on the exact delivered file (framecheck on all drawn text, verify-export, gate, motion and layer scans, locks, sound, cues, facts, review ledger, length), one table and a critic sheet; a check that cannot look FAILS |+| `board.mjs` / `brand.mjs` | the brief and storyboard checked before drawing / a brand imported exactly: `import --sheet`, `inventory`, `find`, `check`, `logos`, `logo` |+| `motionscan.mjs` / `layerscan.mjs` / `lock.mjs` / `worldfilm.mjs` | slide cuts, carousels, dissolves, temperament on the MP4 / text residue, fast type, shapes over faces, translucent brand colour / approved shots frozen / a film started as one world |+| `track.mjs` / `cues.mjs` | an outside track: `analyze`, `cut` by bars, `mix`, `master`, `check`, `listen`, `prompt` (never sent) / the film's own event times for sound and sync |## Worked examples-- **The style plates** in `engine/src/canvas-core/`: every hand has a still and a film of it being- drawn, with the recipe in the header and `references/styles/<id>.md`.-- **MECHANICAL LEPIDOPTERA** in `example/`: a 47 s scored film. `scaffold.mjs ~/study --example`.--**Study them. Do not copy them.** The craft bar is not satisfied by inheritance.+The style plates in `engine/src/canvas-core/` (a still and a film of each being drawn, recipe in the header and `references/styles/<id>.md`) and **MECHANICAL LEPIDOPTERA** in `example/`, a 47 s scored film (`scaffold.mjs ~/study --example`). **Study them. Do not copy them.** The craft bar is not satisfied by inheritance.## Honest limits-You cannot hear the score, watch the film move, or use the interactive piece. Every claim about-them comes from a measurement or from a human; say which. A green checkmark is a claim until you-re-run it. Render one frame at `--scale 2` before trusting a still: a layer blitted through the+You cannot hear the score or the voice, watch the film move, or use the interactive piece. Every claim about them comes from a measurement or from a human; say which.+A green checkmark is a claim until you re-run it. Render one frame at `--scale 2` before trusting a still: a layer blitted through thewrong transform looks right at 1x and breaks at 2x.diff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/brand/lantern/brand.json b/plugins/anidoodle/skills/anidoodle/engine/assets/brand/lantern/brand.jsonnew file mode 100644index 0000000..808c816--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/assets/brand/lantern/brand.json@@ -0,0 +1,114 @@+{+ "version": 1,+ "elements": {+ "lanternMark": {+ "w": 120,+ "h": 120,+ "parts": [+ {+ "d": "M60 2 A13 13 0 1 1 59.99 2 Z M60 9 A6 6 0 1 0 60.01 9 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "evenodd",+ "op": 1,+ "bb": [+ 47,+ 2,+ 26,+ 26+ ]+ },+ {+ "d": "M40 24 H80 L92 38 H28 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "nonzero",+ "op": 1,+ "bb": [+ 28,+ 24,+ 64,+ 14+ ]+ },+ {+ "d": "M32 40 H88 V98 H32 Z M42 48 V90 H78 V48 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "evenodd",+ "op": 1,+ "bb": [+ 32,+ 40,+ 56,+ 58+ ]+ },+ {+ "d": "M60 52 C70 64 73 74 68 82 C65 87 55 87 52 82 C47 74 50 64 60 52 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "nonzero",+ "op": 1,+ "bb": [+ 49.63,+ 52,+ 20.75,+ 33.75+ ]+ },+ {+ "d": "M24 100 H96 Q100 100 100 104 V108 Q100 112 96 112 H24 Q20 112 20 108 V104 Q20 100 24 100 Z",+ "fill": {+ "type": "solid",+ "c": "#f2b544"+ },+ "rule": "nonzero",+ "op": 1,+ "bb": [+ 20,+ 100,+ 80,+ 12+ ]+ }+ ]+ }+ },+ "report": {+ "lanternMark": {+ "parts": 5,+ "size": "120x120",+ "symmetry": {+ "rotational": 1,+ "mirrorX": true,+ "mirrorY": false+ },+ "repeats": [],+ "warnings": [],+ "fonts": []+ }+ },+ "sources": {+ "lanternMark": {+ "file": "lanternMark.svg",+ "sha256": "7b0f3e4589478e0e437abf992684e26cae3b77a1e624e7ed4ebc83543efe5eaa"+ }+ },+ "fonts": [],+ "palette": [+ {+ "hex": "#f2b544",+ "share": 1+ }+ ],+ "motion": {}+}\ No newline at end of filediff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/brand/lantern/brand.ts b/plugins/anidoodle/skills/anidoodle/engine/assets/brand/lantern/brand.tsnew file mode 100644index 0000000..1a54543--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/assets/brand/lantern/brand.ts@@ -0,0 +1,10 @@+// Written by tools/brand.mjs import from 1 source file(s); never edit by hand, re-import instead.+// These are the brand's exact paths: move, rotate, scale evenly, clip and layer them (brandKit.ts), never redraw them.+import type { BrandElement } from "../../../src/canvas-core/brandKit";++export const BRAND: { elements: Record<string, BrandElement>; palette: { hex: string; share: number }[]; fonts: string[]; motion: Record<string, any> } = {"elements":{"lanternMark":{"w":120,"h":120,"parts":[{"d":"M60 2 A13 13 0 1 1 59.99 2 Z M60 9 A6 6 0 1 0 60.01 9 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"evenodd","op":1,"bb":[47,2,26,26]},{"d":"M40 24 H80 L92 38 H28 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"nonzero","op":1,"bb":[28,24,64,14]},{"d":"M32 40 H88 V98 H32 Z M42 48 V90 H78 V48 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"evenodd","op":1,"bb":[32,40,56,58]},{"d":"M60 52 C70 64 73 74 68 82 C65 87 55 87 52 82 C47 74 50 64 60 52 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"nonzero","op":1,"bb":[49.63,52,20.75,33.75]},{"d":"M24 100 H96 Q100 100 100 104 V108 Q100 112 96 112 H24 Q20 112 20 108 V104 Q20 100 24 100 Z","fill":{"type":"solid","c":"#f2b544"},"rule":"nonzero","op":1,"bb":[20,100,80,12]}]}},"palette":[{"hex":"#f2b544","share":1}],"fonts":[],"motion":{}};++/** For the film's meta.brand: the brand's colours (never drawn translucent outside a declared exception) and its element names. */+export const brandMeta = {"colors":["#f2b544"],"elements":["lanternMark"]};+/** For the film's meta.motion: layerscan fails a brand colour filled half-transparent. Spread it: meta.motion = { ...brandMotion, temperament: "calm" }. */+export const brandMotion = {"brandColors":["#f2b544"]};diff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/brand/lantern/lanternMark.svg b/plugins/anidoodle/skills/anidoodle/engine/assets/brand/lantern/lanternMark.svgnew file mode 100644index 0000000..6896f14--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/assets/brand/lantern/lanternMark.svg@@ -0,0 +1,8 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120" width="120" height="120">+ <!-- Lantern, an invented brand for anidoodle's worked example of a custom launch look. Drawn for it; no one else's mark. -->+ <path fill-rule="evenodd" d="M60 2 A13 13 0 1 1 59.99 2 Z M60 9 A6 6 0 1 0 60.01 9 Z" fill="#f2b544"/>+ <path d="M40 24 H80 L92 38 H28 Z" fill="#f2b544"/>+ <path fill-rule="evenodd" d="M32 40 H88 V98 H32 Z M42 48 V90 H78 V48 Z" fill="#f2b544"/>+ <path d="M60 52 C70 64 73 74 68 82 C65 87 55 87 52 82 C47 74 50 64 60 52 Z" fill="#f2b544"/>+ <path d="M24 100 H96 Q100 100 100 104 V108 Q100 112 96 112 H24 Q20 112 20 108 V104 Q20 100 24 100 Z" fill="#f2b544"/>+</svg>diff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/InstrumentSans-Bold.ttf b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/InstrumentSans-Bold.ttfnew file mode 100644index 0000000..f602dceBinary files /dev/null and b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/InstrumentSans-Bold.ttf differdiff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/InstrumentSans-OFL.txt b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/InstrumentSans-OFL.txtnew file mode 100644index 0000000..4bb9914--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/InstrumentSans-OFL.txt@@ -0,0 +1,93 @@+Copyright 2022 The Instrument Sans Project Authors (https://github.com/Instrument/instrument-sans)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/InstrumentSans-Regular.ttf b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/InstrumentSans-Regular.ttfnew file mode 100644index 0000000..14c6113Binary files /dev/null and b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/InstrumentSans-Regular.ttf differdiff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Lora-Bold.ttf b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Lora-Bold.ttfnew file mode 100644index 0000000..edae21eBinary files /dev/null and b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Lora-Bold.ttf differdiff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Lora-OFL.txt b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Lora-OFL.txtnew file mode 100644index 0000000..4cf1b95--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Lora-OFL.txt@@ -0,0 +1,93 @@+Copyright 2011 The Lora Project Authors (https://github.com/cyrealtype/Lora-Cyrillic), with Reserved Font Name "Lora".++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+https://openfontlicense.org+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/PROVENANCE.md b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/PROVENANCE.mdnew file mode 100644index 0000000..c0bcad5--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/PROVENANCE.md@@ -0,0 +1,37 @@+# Fonts bundled with the engine++## Poppins Bold (the default 3D type face)++- File: `Poppins-Bold.ttf`, TrueType outlines (glyf), 155996 bytes+- sha256: `983676516167748b74de6f4771fb384c664fd913acb8b471122ecacf5da5ea6c`+- Version: Poppins 4.003, Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins)+- Licence: SIL Open Font License 1.1, full text in `Poppins-OFL.txt` (sha256 `6be04893d770899a015649c7aa3b582f871b272f8747a92b78b17c3e5c8b2573`). The font's own name table says the same (nameID 13/14), and test/threeType.test.ts checks it.+- Source: `https://github.com/google/fonts/raw/main/ofl/poppins/Poppins-Bold.ttf` and `.../OFL.txt`, fetched 2026-10-28.+- Why this face: a geometric bold sans that reads well extruded, and the face Alex's own sites use.+- Note: Poppins carries no kerning (no `kern` table, no GPOS `kern` feature, in every release). The parser reads both when a font has them; with Poppins, letter spacing is the only spacing control.++`poppinsBold.ts` is the same bytes as a base64 string module, which is how films carry the font+(no file is read and nothing is fetched at draw time). Regenerate it after replacing the .ttf with:++```+node -e 'const fs=require("fs"),b=fs.readFileSync("assets/fonts/Poppins-Bold.ttf");let h=0x811c9dc5;for(const x of b){h^=x;h=Math.imul(h,0x01000193)}h=(h>>>0).toString(16);const sha=require("crypto").createHash("sha256").update(b).digest("hex");fs.writeFileSync("assets/fonts/poppinsBold.ts",`// POPPINS BOLD as base64 (see PROVENANCE.md). sha256 ${sha}\nexport const POPPINS_BOLD_FNV = 0x${h};\nexport const POPPINS_BOLD_BYTES = ${b.length};\nexport const POPPINS_BOLD = "${b.toString("base64")}";\n`)'+```++The OFL allows bundling and redistribution with software; the font may not be sold on its own, and+a modified version may not use the reserved name. We ship it unmodified.++## Lora Bold and Instrument Sans Regular and Bold (the launch template's look example, launchExampleBrand)++- `Lora-Bold.ttf`, 133828 bytes, sha256 `7d74015e950c2fb66519c7295b8155621d22200ae2ca2a4c6b43ce3c490cac87`.+ Copyright 2011 The Lora Project Authors, SIL Open Font License 1.1, full text in `Lora-OFL.txt`+ (sha256 `62e37a82d3f1ef2a70712885fa8b3144b65fd144d8e748d6196b690a354d792c`). Reserved Font Name "Lora".+- `InstrumentSans-Regular.ttf`, 68028 bytes, sha256 `a22cb26e48fd79bcb01bf2fc92d36785474dce36d9c544ab0a8868c2657c4a87`.+ Copyright 2022 The Instrument Sans Project Authors, SIL Open Font License 1.1, full text in+ `InstrumentSans-OFL.txt` (sha256 `bf4dc6d13a8cccd4807133c77a1ee9619a16b92cb23322258725ab6731c2f6e5`).+- `InstrumentSans-Bold.ttf`, 68084 bytes, sha256 `444f85bf1c4b0e1ce1ca624f6be54bcd832207714ccaf4ea99ee531341683bdf`.+ Same family, copyright and licence as the Regular above.+- Source: copied unmodified from a local copy of Anthropic's canvas-design skill font folder (the same+ Google Fonts releases), 2026-10-29; nothing fetched.+- Why: a serif display face and a plain text face for the worked example of a custom look, so the template+ is proven on fonts that are not ours. A film imports them by path (`import f from ".../Lora-Bold.ttf"`);+ tools/overlay.mjs inlines the bytes, so the page carries them and nothing is read or fetched at draw time.diff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Poppins-Bold.ttf b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Poppins-Bold.ttfnew file mode 100644index 0000000..1982f38Binary files /dev/null and b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Poppins-Bold.ttf differdiff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Poppins-OFL.txt b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Poppins-OFL.txtnew file mode 100644index 0000000..76df3b5--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/Poppins-OFL.txt@@ -0,0 +1,93 @@+Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/poppinsBold.ts b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/poppinsBold.tsnew file mode 100644index 0000000..2e36fe7--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/assets/fonts/poppinsBold.ts@@ -0,0 +1,8 @@+// POPPINS BOLD as base64, so a film carries its font inside the page: no file read, no network+// at draw time (the build plan, rule 2). Generated from assets/fonts/Poppins-Bold.ttf, never edited by hand.+// Poppins 4.003, Copyright 2020 The Poppins Project Authors, SIL Open Font License 1.1 (Poppins-OFL.txt).+// sha256 983676516167748b74de6f4771fb384c664fd913acb8b471122ecacf5da5ea6c 155996 bytes fnv1a32 97b44eae+// Regenerate: see PROVENANCE.md beside this file.+export const POPPINS_BOLD_FNV = 0x97b44eae;+export const POPPINS_B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AAAToAAAE6AAABOgCPASYBLAEyATgBPgFEAUoBUAFWAVwBYgFoAW4BdAF6AYABhgGMAZIBmAGeAaQBqgGwAVYBtgG8AcIByAHOAdQB2gHgAeYB7AHyAfIB+AH+AgQCCgIQAhYCHAIiAigCLgI0AjoCQAJGAkwCUgJYAl4CZAJqAnACdgJ8AoICiAKOApQCmgKgAqYCrAKyArgCvgLEAsoC0ALKAtYC3ALiAugC7gL0AvoDAAMGAwwDEgMYAxgDHgMkAyoDMAM2AzwDQgNIA04DVANaA2ADZgNsA3IDeAN+A4QDigOQA5YDnAOiA6gDrgO0A7oDwAK4A8YDzAPSA9gD3gPkA+oD2AKgAqYD8AP2A/wEAgQIBA4EFAQaBCAEJgQsBDIEOAQ+BEQESgAB/68AAAABAjYAAAABAYr/iwABAe3/sgABAa3/swABAaf/vQABAYz/igABAcv/lgABAiT/3wABAkMAAAABAuP/wQABAY//NAABAwL/2AABAjb/WgABAYz+sgABAcv+vwABAkP/uAABAjb/zgABAYr/LQABAe3/VgABAa3/XwABAaf/WgABAYz/LQABAcv/OQABAiT/wgABAuP+/AABAY//FAABAwL/ewABAoMAAAABApcAAAABBOwAAAABBOz/WgABBGL/swABAqcAAAABBNr/3wABBN0AAAABBN7/uAABBZj/wQABBmD/swABBkv/igABCO7/wQABBBb/3wABBNX/wQABA5//sgABBDP+oAABBGIAAAABA9b/swABA6D/igABBE7/3wABA/7/sgABAbD+mAABAbH+mQABAjj+1QABAaf+mQABAjn+4AABAYz+YQABAYz+ZgABAfn+ugABAcD+aAABAjH+ugABA93/swABA+L/vQABA8T/igABBAX/lgABA7MAAAABA7P/zgABBaj/wQABA6cAAAABBF//wQABAl3/AAABAl3+xwABA1L/3wABAgz/qAABAiP+7AABAiP+yAABAw3+sgABAhn++wABBDkAAAABBAH/sgABA6r/swABA4P/igABBCL/3wABBCL/wgABBA7++wABBDcAAAABBbv/swABA4L/NAABAxv/swABAxj/vQABA7YAAAABBEb/wQABBH3/swABBPIAAAABBPL/wAABBan/wQABA7r/3wABBGT/wQABBP//wQABBDv/3wABBPj/wQABA5H/NAABAnb/NAABBL8AAAABBDX/swABBDD/vQABA/b/igABBFP/lgABBKr/3wABBKr/wgABBKoAAAABBWz/wQABBlv/igABA93/NAABAtH/NAABBFcAAAABBFf/WgABAvn/ogABBC//sgABA9v/swABBQD/wQABAyb/swABAyb/XwABA6n+1QABAyL/vQABAyL/VwABA7QAAAABBDwAAAABBDz/zgABA7T/swABBCn/3wABBE4AAAABBOb/wQABAdT+vAABAy7/ZAABAeD+vAABAb3+vAABBvQF0gABAAwAEgABAAABJgCPASYBLAEyATgBPgFEAUoBUAFWAVwBYgFoASYBbgF0AVYBJgF6AYABhgGMAZIBmAFQAVYBngGkAaoBsAG2AbwBvAHCAcgBzgHUAdQB2gHgAeYB7AHyAfgB/gIEAgoCEAIWAhwCIgIoAi4CNAI6AkACRgJMAlICWAJeAmQCagJwAnYCfAKCAoICiAKOApQCmgKaAqACpgKgAqwCrAKyArgCvgLEAsoC0ALWAtYC3ALiAuIC6ALuAvQC+gMAAwYDDAMSAxIDGAMeAyQDKgMwAzYDPANCA0gDTgNUA1oDYANmA2YDbANyA3gDfgKUA4QDigOKA5ADlgOcA6IDkAKCAoIDqAOuA7QDugPAA8YDzAPMA9ID2APeA+QD6gPwA/YD/AAB/68AAAABAjYAAAABAYD/7AABAeMAFAABAaMAFAABAZ0AHgABAYL/7AABAcH/9wABAiT/3wABAkMAAAABAtYAHgABAYP/kAABAvQANQABAYL/EwABAcH/HwABAYD/jgABAeP/uAABAaP/wQABAZ3/uwABAYL/jwABAcH/mgABAtb/WQABAYP/cQABAvT/2AABAoMAAAABApcAAAABBOwAAAABBFcAFAABAqcAAAABBNr/3wABBN0AAAABBN4AAAABBYsAHgABBlYAFAABBkD/7AABCOEAHgABBBb/3wABBMcAHgABA5UAFAABBDP+oAABBGIAAAABA8sAFAABA5X/7AABBE7/3wABA/QAFAABAaX++QABAab++gABAjj+1QABAZ3++gABAjn+4AABAYL+wwABAYL+xwABAfn+ugABAbX+yQABAjH+ugABA9IAFAABA9cAHgABA7n/7AABA/r/9wABA7MAAAABBZsAHgABA6cAAAABBFIAHgABAl3/AAABA1L/3wABAgz/qAABAiP+7AABAw3+sgABAhn++wABBDkAAAABA/YAFAABA58AFAABA3f/7AABBCL/3wABBA7++wABBDcAAAABBbEAFAABA3T/kAABAxAAFAABAw0AHgABA7YAAAABBDgAHgABBHMAFAABBPIAAAABBZwAHgABA7r/3wABBFcAHgABBPIAHgABBDv/3wABBOsAHgABA4X/kAABAmn/kAABBL8AAAABBCsAFAABBCUAHgABA+z/7AABBEn/9wABBKr/3wABBKoAAAABBV8AHgABBlD/7AABA9H/kAABAsT/kAABBFcAAAABAvn/9wABBCQAFAABA9AAFAABBPQAHgABAxsAFAABAxv/wQABA6n+1QABAxcAHgABAxf/uQABA7QAAAABBDwAAAABA6oAFAABBCn/3wABBE4AAAABBNkAHgABAcf/GgABAy7/ZAABAdP/GgABAbD/GQABAA4AHgAfACIAeQB6AJICXAJnAmgCaQJqAmsCbAJzAAEAsgAGAAgACQAKAAsADAANAA4ADwAQABEAEgATABQAJAAoACoALgAvADAAMQA1ADkAPgA/AEQARQBIAEwATQBOAE8AVABaAFsAXABdAGEAagBwAJUAmQCbAJ8AoAChAKIApgCqAK8AtAC1ALYAugC/AMUAxgDHAMgAzADVANoA4QDiAOYA6ADuAPIA8wD0APkBAgEDAQYBGAEkASsBLAEyAToBOwE9AUgBSwFMAU4BTwFRAVIBUwFVAVYBWAFZAVoBWwFcAWEBYwFwAXEBdgF/AYABgQGCAYMBhQGGAYgBigGQAZMBlAGVAZ0BngGfAagBqQGyAbUBtgG3AbwBvwHEAckBygHMAdQB3AHkAecB9AH4AfwB/QIDAgQCBQIGAgoCCwINAhICFQIXAhoCHAIdAh4CIAIhAiYCKQIqAisCLQIuAi8CMQI2AjwCPQJBAkgCTAJRAlQCWAJZAnUCdgJ3AngCeQJ7AAIAAQJdAl8AAAACAAUAJABPAAAAlQC6AC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AEAFAAAgB9AAEABABRAAIAfQABAAQAUgACAH0AAQAEAFMAAgB9AAEABABUAAIAfQABAAQAVQACAH0AAQAEAFYAAgB9AAEABABXAAIAfQABAAQAWAACAH0AAQAEAFkAAgB9AAEABABaAAIAfQABAAQAWwACAH0AAQAEAFwAAgB9AAEABABdAAIAfQABAAQAXgACAH0AAQAEAF8AAgB9AAEABABgAAIAfQABAAQAYQACAH0AAQAEAGIAAgB9AAEABABjAAIAfQABAAQAZAACAH0AAQAEAGUAAgB9AAEABABmAAIAfQABAAQAZwACAH0AAQAEAGgAAgB9AAEABABpAAIAfQABAAQAkwACAH0AAQAEAGsAAgB9AAEABABsAAIAfQABAAQAbQACAH0AAQAEAG4AAgB9AAEABABvAAIAfQABAAQAcAACAH0AAQAEAHEAAgB9AAEABAByAAIAfQABAAQAcwACAH0AAQAEAHQAAgB9AAEABAB1AAIAfQABAAQAdgACAH0AAQAEAHcAAgB9AAEABAB4AAIAfQABAAQAkwACAH0AARgWACYAUgBcAGYAcAB6AIQAjgCYAKIArAC2AMAAygDUAN4A6ADyAPwBBgEQARoBJAEuATgBQgFMAVYBYAFqAXQBfgGIAZIBnAGmAbABugHEAAEABAC7AAIAfQABAAQAvAACAH0AAQAEAL0AAgB9AAEABAC+AAIAfQABAAQAvwACAH0AAQAEAMAAAgB9AAEABADBAAIAfQABAAQAwgACAH0AAQAEAMMAAgB9AAEABADEAAIAfQABAAQAxQACAH0AAQAEAMYAAgB9AAEABADHAAIAfQABAAQAyAACAH0AAQAEAMkAAgB9AAEABADKAAIAfQABAAQAywACAH0AAQAEAMwAAgB9AAEABADNAAIAfQABAAQAzgACAH0AAQAEAM8AAgB9AAEABADQAAIAfQABAAQA0QACAH0AAQAEANIAAgB9AAEABADTAAIAfQABAAQA1AACAH0AAQAEANUAAgB9AAEABADWAAIAfQABAAQA1wACAH0AAQAEANgAAgB9AAEABADZAAIAfQABAAQA2gACAH0AAQAEANsAAgB9AAEABADcAAIAfQABAAQA3QACAH0AAQAEAN4AAgB9AAEABADfAAIAfQABAAQA4AACAH0AARZSAEwAngCoALIAvADGANAA2gDkAO4A+AECAQwBFgEgASoBNAE+AUgBUgFcAWYBcAF6AYQBjgGYAaIBrAG2AcABygHUAd4B6AHyAfwCBgIQAhoCJAIuAjgCQgJMAlYCYAJqAnQCfgKIApICnAKmArACugLEAs4C2ALiAuwC9gMAAwoDFAMeAygDMgM8A0YDUANaA2QDbgN4A4IDjAABAAQAlQACAJQAAQAEAJYAAgCUAAEABACXAAIAlAABAAQAmAACAJQAAQAEAJkAAgCUAAEABACaAAIAlAABAAQAmwACAJQAAQAEAJwAAgCUAAEABACdAAIAlAABAAQAngACAJQAAQAEAJ8AAgCUAAEABACgAAIAlAABAAQAoQACAJQAAQAEAKIAAgCUAAEABACjAAIAlAABAAQApAACAJQAAQAEAKUAAgCUAAEABACmAAIAlAABAAQApwACAJQAAQAEAKgAAgCUAAEABACpAAIAlAABAAQAqgACAJQAAQAEAKsAAgCUAAEABACsAAIAlAABAAQArQACAJQAAQAEAK4AAgCUAAEABACvAAIAlAABAAQAsAACAJQAAQAEALEAAgCUAAEABACyAAIAlAABAAQAswACAJQAAQAEALQAAgCUAAEABAC1AAIAlAABAAQAtgACAJQAAQAEALcAAgCUAAEABAC4AAIAlAABAAQAuQACAJQAAQAEALoAAgCUAAEABAC7AAIAlAABAAQAvAACAJQAAQAEAL0AAgCUAAEABAC+AAIAlAABAAQAvwACAJQAAQAEAMAAAgCUAAEABADBAAIAlAABAAQAwgACAJQAAQAEAMMAAgCUAAEABADEAAIAlAABAAQAxQACAJQAAQAEAMYAAgCUAAEABADHAAIAlAABAAQAyAACAJQAAQAEAMkAAgCUAAEABADKAAIAlAABAAQAywACAJQAAQAEAMwAAgCUAAEABADNAAIAlAABAAQAzgACAJQAAQAEAM8AAgCUAAEABADQAAIAlAABAAQA0QACAJQAAQAEANIAAgCUAAEABADTAAIAlAABAAQA1AACAJQAAQAEANUAAgCUAAEABADWAAIAlAABAAQA1wACAJQAAQAEANgAAgCUAAEABADZAAIAlAABAAQA2gACAJQAAQAEANsAAgCUAAEABADcAAIAlAABAAQA3QACAJQAAQAEAN4AAgCUAAEABADfAAIAlAABAAQA4AACAJQAARLqACsAXAFQAYoCJAI+AnICfAL6AxQDNgNYA3IDlAOuA/AE1gTwBVIFfgbQBzQHfggWCDgI2AjqCcwJ9gpYCvwLyAv6DAQMKAwyDGQMlgyoDMoM8Az6DQQNDgAcADoARABMAFQAXABkAGwAdAB8AIIAiACOAJQAmgCgAKYArACyALgAvgDEAMoA0ADWANwA4gDoAO4BBgAEAG8AZAA/AOoAAwBfAD0A7AADAF8AQAD7AAMAbAA9AQIAAwBvAC4BAwADAG8AMAEEAAMAbwAzAQUAAwBvAKkA4QACACQA4wACACUA5AACACkA5QACACsA5gACAC4A5wACADIA6AACADMA7QACADQA7gACADUA7wACADcA8AACADgA8gACADkA9gACADwA+AACAD0A+QACAD8A+gACAEAA/AACAEEBAQACAEMA6wACAKQA8QACAKkABwAQABYAHAAiACgALgA0AQcAAgAlAQgAAgAzAQoAAgA3AQsAAgA8AQ0AAgA9AQ8AAgBAAREAAgBBABIAJgAuADYAPgBGAEwAUgBYAF4AZABqAHAAdgB8AIIAiACOAJQBGgADAGIAPQEbAAMAYgBAAR0AAwBjAD0BIAADAGcAPQEUAAIAJgEVAAIAJwEWAAIAKwEXAAIAMgEYAAIANQEZAAIANgEcAAIANwEeAAIAOgEfAAIAOwEhAAIAPAEiAAIAPQEkAAIAPwElAAIAQAEmAAIAQwADAAgADgAUAScAAgA3ASgAAgA8ASkAAgA9AAYADgAWABwAIgAoAC4BLAADAFYAQAEqAAIAKQErAAIAKgEtAAIANwEuAAIAPAEvAAIAPQABAAQBMAACAD0ADwAgACgAMAA2ADwAQgBIAE4AVABaAGAAZgBsAHIAeAE2AAMAVwA9ATcAAwBXAEABMgACACQBMwACACsBOAACACwBOgACAC4BOwACADABPAACADMBPQACADUBPgACADcBPwACADoBQAACADwBQQACAD0BQwACAEABNQACAEcAAwAIAA4AFAFEAAIANwFFAAIAPAFGAAIAPQAEAAoAEAAWABwBRwACACkBSAACACoBSQACACsBSgACAEEABAAKABAAFgAcAUsAAgAuAUwAAgAvAU0AAgA9AU4AAgBAAAMACAAOABQBTwACAC8BUAACAD0BUQACAEAABAAKABAAFgAcAVIAAgAwAVMAAgAxAVQAAgA9AVUAAgBAAAMACAAOABQBVgACADEBVwACAD0BWAACAEAACAASABgAHgAkACoAMAA2ADwBWQACAC4BWgACAC8BWwACADABXAACADEBXQACADIBXgACADwBXwACAD0BYAACAEAAGgA2AD4ARgBOAFYAXgBmAG4AdgB+AIYAjACSAJgAngCkAKoAsAC2ALwAwgDIAM4A1ADaAOABYgADAFAAPQFkAAMAUABAAWkAAwBfAD0BagADAF8AQAFtAAMAYwA9AXAAAwBkAD8BcwADAGgAPQF5AAMAbwA3AXoAAwBvAD0BewADAG8AQAFhAAIAJAFmAAIAJQFoAAIAMwFrAAIANAFsAAIANwFuAAIAOAFxAAIAOQFyAAIAPAF0AAIAPQF2AAIAPwF3AAIAQAF4AAIAQwFlAAIARgFjAAIAlQFnAAIAlgFvAAIAqQADAAgADgAUAXwAAgA3AX0AAgA9AX4AAgBAAAwAGgAgACYALAAyADgAPgBEAEoAUABWAFwBfwACACYBgQACACcBggACADUBgwACADYBhAACADcBhQACADoBhwACADsBiAACADwBiQACAD0BigACAEABgAACAJcBhgACAKsABQAMABQAGgAgACYBjAADAGMAPQGLAAIANwGNAAIAPAGOAAIAPQGPAAIAQAAmAE4AWABgAGgAcAB4AIAAiACQAJgAoACoALAAuADAAMgAzgDUANoA4ADmAOwA8gD4AP4BBAEKARABFgEcASIBKAEuATQBOgFAAUYBTAGzAAQAbwBoAD0BkQADAFAAQwGXAAMAXwA9AZkAAwBfAEMBmwADAGAAPQGcAAMAYABAAZ8AAwBhAEABoQADAGIAPQGjAAMAYgBAAaUAAwBjAD0BqwADAGcAPQGsAAMAZwBAAa4AAwBoAD0BsgADAG8ALgG0AAMAbwA9AZ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AAMAAgdgB1YAAQd2AAAAAQAAADMAAQdsAAQADgAYACoANAABAAQCeQACABoAAgAGAAwCdQACABgCdgACABkAAQAEAnoAAgAaAAMACAAOABQCdwACABgCeAACABkCewACABoAAwABByoAAQdyAAAAAQAAADMAAQdsAA8AJAAuADgAQgBMAFYAYABqAHQAfgCIAJIAnACmALAAAQAEAFQAAgB9AAEABABaAAIAfQABAAQAWwACAH0AAQAEAFwAAgB9AAEABABdAAIAfQABAAQAYQACAH0AAQAEAGoAAgB9AAEABABwAAIAfQABAAQAvwACAH0AAQAEAMUAAgB9AAEABADGAAIAfQABAAQAxwACAH0AAQAEAMgAAgB9AAEABADMAAIAfQABAAQA2gACAH0AAAEAAAIG0AAPBAUEBgQHBAgECQQKBAsEDAQNBA4EEAQRBBIEEwQUAAABAQACBsoACgQVBBoEFgQYBB4EGQQdBBsEFwQcAAABAgABBsQBhgAAAQMAAgbAAAQEIAQhBCIEIwABAOQAAQAIAAEABACTAAIAfQABAYICZgABAXwCZwABAXYCaAABAXACaQABAWoCagABAWQCawABAV4CbAABAVgCbQABAVICbgABAUwCbwABAUYCcAABAUACcQABAToCcgABATQCcwABAS4CdAABASgCdQABASICdgABARwCdwABARYCeAABARACeQABAQoCegABAQQCewABAP4CfAACBiIAAgKTAAoAAQA+/80AAQA4/84AAgYUAAgCWwANAl0CXgJfAmQCZQJmAAEACAAkACUAJgArADAAMQA5AD4AAQACACQAKwABAAEAPgABAAEAfQABAAEAkAACAAQAJAA9AAAAPwBFABoASABLACEATgBOACUAAgACACQASwAAAE4ATwAoAAIAAQCVALoAAAACAAcAJAA9AAAAPwBFABoASABLACEATgBOACUAUABpACYAawBxAEAAdAB4AEcAAgAJAFAAUwAAAFUAaQAEAGsAdQAZAHcAeAAkAJMAkwAmAL0AvQAnAMEAwQAoAMoAygApANIA0gAqAAEAAQAWAAEAGAAoAC4ALwAwAD4ARABMAE8AmQCfAKAAoQC0AUsBTAFOAU8BUQFSAVMBVQFWAVgBggABAAgAMQA1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sBowHCAcMBzQH/AkUAAQAGAOMBBwFtAZcBsgJDAAEACwEaAXMBegGcAaEB0QHsAiwCMAIzAjgAAQANAOwBAgEDAR0BIAFkAXkBjAGZAZsBrAHxAkcAAQAMAOoA+wE3AWIBpQGrAa4BtAHdAe8CFQJPAAEACQD+AQQBBQE2AZEB/gIJAhMCPgABAAEAGgABAAEAGwABAAEAHAABAAEAHQACAAEAGgAdAAAAAQAJAAcAFwAeAB8AIAAhACIAIwCSAAIAAQJ8ApMAAAACAAMAJABPAAAAlQC6ACwA4QJaAFIAAQADAHkAkgJcAAEABAA1AD4AQQBEAAEAIgAkADkASABOAJUAqgC2ALoA4QDiAOgA8gDzAPQBMgFhAWMBcQGQAagBqQG8AckBygH9Ag0CHQIeAikCKgI2AjwCPQJMAAEABAAXAmECYgJjAAEADwAoAC4ALwAwADEANQA+AEQAmQCfAKAAoQCiAKYAtAABAA8ClAKfAqECrQKuArIC8wMJAxEDSQPfA+AD4gPjA+gAAQAKAtQDMgMzAzQDNQM2AzcDUwNVA1cAAQABApkAAQAEAqUCpgKpAqwAAQACABYAPgABAAgAFwA+AHkAkgJcAmECYgJjAAAAAQAAAAA=";diff --git a/plugins/anidoodle/skills/anidoodle/engine/facts/launchClip.json b/plugins/anidoodle/skills/anidoodle/engine/facts/launchClip.jsonnew file mode 100644index 0000000..fe3dcbb--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/facts/launchClip.json@@ -0,0 +1,8 @@+{+ "version": 1,+ "about": "The ledger of launchClip, anidoodle's own 4 second motion test (the Generate press, the ink drop and the bloom) cut from the launch film. Its prompt is a user's request and the rest of its text is the chat's own interface; the two lines below are the ones that claim something.",+ "claims": [+ { "claim": "drawn in code", "where": "on-screen", "source": { "sentence": "Pictures, films and interactive pieces drawn entirely in code, in 2D or in 3D.", "file": "skills/anidoodle/SKILL.md" } },+ { "claim": "marker comic", "where": "on-screen", "source": { "sentence": "| 2 | Marker comic | `koi.ts` | flat cel fills with a hard shadow edge, one heavy contour that thickens away from the light |", "file": "skills/anidoodle/references/styles.md" } }+ ]+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleBrand.json b/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleBrand.jsonnew file mode 100644index 0000000..ba97e7a--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleBrand.json@@ -0,0 +1,11 @@+{+ "version": 1,+ "about": "The ledger of launchExampleBrand, a demo launch film for an invented product ('Lantern', no real company) in a custom look: anidoodle's worked example of the look layer. Its words describe the mock product shown on screen, written for the template, labelled generated. The source map and the library rows are made-up sample data in mock screens, not claims.",+ "claims": [+ { "claim": "READ LESS.", "where": "on-screen", "generated": true, "note": "demo slogan for an invented product, states no fact" },+ { "claim": "KNOW MORE.", "where": "on-screen", "generated": true, "note": "demo slogan for an invented product, states no fact" },+ { "claim": "Then it cites", "where": "on-screen", "generated": true, "note": "describes the mock library screen beside it; the product is invented" },+ { "claim": "every page.", "where": "on-screen", "generated": true, "note": "second line of 'Then it cites every page.', describes the mock library screen beside it; the product is invented" },+ { "claim": "A reading desk that keeps your sources straight", "where": "on-screen", "generated": true, "note": "demo tagline for an invented product, states no fact" }+ ]+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleClean.json b/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleClean.jsonindex 75b6d29..ca08799 100644--- a/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleClean.json+++ b/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleClean.json@@ -4,8 +4,8 @@"claims": [{ "claim": "ASK ONCE.", "where": "on-screen", "generated": true, "note": "demo slogan for a made-up product, states no fact" },{ "claim": "DONE.", "where": "on-screen", "generated": true, "note": "demo slogan for a made-up product, states no fact" },- { "claim": "Books close", "where": "on-screen", "generated": true, "note": "describes the mock UI on screen beside it (its rows reaching their after state); the product is made up" },- { "claim": "themselves.", "where": "on-screen", "generated": true, "note": "second line of 'Books close themselves.', describes the mock UI beside it; the product is made up" },+ { "claim": "Month end,", "where": "on-screen", "generated": true, "note": "describes the mock month-close screen beside it; the product is made up" },+ { "claim": "one click.", "where": "on-screen", "generated": true, "note": "second line of 'Month end, one click.', describes the one press on the mock screen beside it; the product is made up" },{ "claim": "And it shows", "where": "on-screen", "generated": true, "note": "describes the mock reports screen beside it; the product is made up" },{ "claim": "you where.", "where": "on-screen", "generated": true, "note": "second line of 'And it shows you where.', describes the mock reports screen beside it; the product is made up" },{ "claim": "Bookkeeping that does itself", "where": "on-screen", "generated": true, "note": "demo tagline for a made-up product, states no fact" }diff --git a/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleCleanChat.json b/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleCleanChat.jsonnew file mode 100644index 0000000..9d2300d--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/facts/launchExampleCleanChat.json@@ -0,0 +1,11 @@+{+ "version": 1,+ "about": "The ledger of launchExampleCleanChat, a demo launch film for a made-up product ('Tally') in the clean look with a chat ask. Its words describe the mock product shown on screen, written for the template, labelled generated. The chart and the UI's figures are made-up sample data in mock screens, not claims.",+ "claims": [+ { "claim": "ASK IT.", "where": "on-screen", "generated": true, "note": "demo slogan for a made-up product, states no fact" },+ { "claim": "SEE WHY.", "where": "on-screen", "generated": true, "note": "demo slogan for a made-up product: the chart answering the chat ask is mock data" },+ { "claim": "Then it fixes", "where": "on-screen", "generated": true, "note": "describes the mock inbox screen beside it; the product is made up" },+ { "claim": "the books.", "where": "on-screen", "generated": true, "note": "second line of 'Then it fixes the books.', describes the mock inbox screen beside it; the product is made up" },+ { "claim": "Bookkeeping that does itself", "where": "on-screen", "generated": true, "note": "demo tagline for a made-up product, states no fact" }+ ]+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/package.json b/plugins/anidoodle/skills/anidoodle/engine/package.jsonindex 046ca43..b28d952 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.9.6",+ "version": "0.10.0","private": true,"type": "module","description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",@@ -12,7 +12,8 @@"test": "node tools/test.mjs"},"dependencies": {- "esbuild": "0.25.12"+ "esbuild": "0.25.12",+ "three": "0.170.0"},"devDependencies": {"playwright-core": "1.63.0",@@ -22,6 +23,7 @@"@remotion/bundler": "4.0.522","@remotion/renderer": "4.0.522","react": "19.3.0",+ "react-dom": "19.3.0","remotion": "4.0.522"}}diff --git a/plugins/anidoodle/skills/anidoodle/engine/reviews/launchClip.json b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchClip.jsonnew file mode 100644index 0000000..ef64e47--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchClip.json@@ -0,0 +1,61 @@+{+ "about": "anidoodle's own review record for launchClip, written by a fresh critic (an agent), not a person's review. launchClip is a frozen cut of the published launch film: every finding is kept here so it is seen, and closed as wontfix because the film is not re-cut.",+ "findings": [+ {+ "id": "c1-1",+ "p": "P1",+ "status": "wontfix",+ "note": "0.00-1.10 s (f1-33): the first second does nothing. The text is already typed and the cursor is already on Generate, and only the caret blinks. That is 27% of a 4 s test spent idle, so the hook arrives late. Fix: start about 0.3 s before the press, or hold the full sentence no longer than 0.3 s before the click.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-2",+ "p": "P1",+ "status": "wontfix",+ "note": "~1.03-1.10 s (f31-35): the press itself barely reads. The Generate button never visibly moves down (no scale or shade change), and the drop is already sitting on top of the button before the click, so it reads as a dot that was there, not ink the click squeezes out. Fix: a 2-3 frame press-down on the button (scale ~0.94, darker), with the drop swelling out of it only after the click.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-3",+ "p": "P1",+ "status": "wontfix",+ "note": "1.6-2.2 s (f49-66): the bloom is a heavy, solid black wobbly ring (donut) about 25 px thick at 1080p. It is the darkest, biggest shape in a pale UI and reads as a hole or stain more than ink blooming open. While the card squares off (f57-66) the ring gets clipped by the card's rectangle, leaving four black triangles in the corners that shrink away. That reads as a mask artifact, not ink. Fix: bloom as a soft spreading wash that thins as it grows and fades into the card edge, or round the clip to match the ring so no hard black corners show.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-4",+ "p": "P1",+ "status": "wontfix",+ "note": "2.2-4.0 s (f66-120, last frame): the style promised is 'marker comic' but the koi is thin, pale blue pencil construction lines. The last frame shows a faint sketch with two flat orange blobs and a half-laid cream fill: no bold marker outline, no comic ink. The test ends on what looks like a draft that is still loading, so it does not pay off the request it ends beside. Fix: bring in a bold dark marker outline pass by about 3.0 s so the final frame holds a recognisable marker-comic koi (outline plus the main orange patches) for the last ~0.4 s.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-5",+ "p": "P2",+ "status": "wontfix",+ "note": "1.30-1.60 s (f40-48): the drop's trail is a soft grey gradient smear, like a CSS motion blur, not ink. It also flies down-left to empty space, away from the thread bubble at top right. Fix: draw the trail as tapering ink droplets or a brush flick, and arc it so it reads as landing in the reply slot below the user bubble.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-6",+ "p": "P2",+ "status": "wontfix",+ "note": "2.70-2.95 s (f81-88): the header, the 'marker comic' label, the input, the button and the cursor all fade out together, while the window grows slightly (a camera push). The brief says the small print fades IN, but on screen it fades OUT. That leaves an empty top band, and the input disappears mid-fade, so the window reads as unfinished. Fix: decide the direction on purpose. If the goal is to end on card plus request, keep the push and crop the frame to them, so no empty chrome band remains.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ },+ {+ "id": "c1-7",+ "p": "P2",+ "status": "wontfix",+ "note": "Whole clip: the 'turning' in the request never happens. The koi stays still, so nothing in the drawing moves except strokes and fills arriving. Fix: a slight body curve or tail flick in the last 0.5 s would make the answer match the request.",+ "by": "fresh critic r1 (an agent)",+ "why": "Not re-cut: launchClip is a frozen cut of the published launch film, its look already approved."+ }+ ]+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExample.json b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExample.jsonnew file mode 100644index 0000000..5ffca3c--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExample.json@@ -0,0 +1,76 @@+{+ "about": "anidoodle's own review record for launchExample, the drawn worked example of the launch template. Written by fresh critics (agents), not a person's review. A film made from the template gets its own record, written for that film (references/workflows/review.md).",+ "verdict": "ship (critic r4, an agent): no open P0 or P1; 1 open optional P2",+ "findings": [+ {+ "id": "d1-1",+ "p": "P1",+ "status": "fixed",+ "note": "Frames 120 to 140 (9:16): the answer card's byline words vanished under the thread's top while its dot stayed behind. The dot now goes with its words (inkCard), and a byline nearing the window's top fades out whole.",+ "by": "fresh critic r1, an agent; r2 (an agent) found d1-1 still open on 9:16 (the zone fade withheld the words, not the dot); fixed again and confirmed by fresh critic r3, an agent"+ },+ {+ "id": "d1-2",+ "p": "P1",+ "status": "fixed",+ "note": "The corner mark touched the chat window's bottom right corner (16:9 frames 0 and 345, 9:16 frames 0 and 270). It now sits clear of the window: beside it on 16:9 (the room creeps about that corner), under it on 9:16 with room for the hook's creep.",+ "by": "fresh critic r1, an agent; confirmed fixed by fresh critics r2 and r3 (agents)"+ },+ {+ "id": "d1-3",+ "p": "P1",+ "status": "fixed",+ "note": "The end card's install lines were each centred, so they started at different places. Every line now starts at the panel's left padding, as a terminal sets them.",+ "by": "fresh critic r1, an agent; confirmed fixed by fresh critics r2 and r3 (agents)"+ },+ {+ "id": "d2-1",+ "p": "P2",+ "status": "fixed",+ "note": "9:16 frames 110 to 120: the corner mark hid behind the leaned card, then popped back on top at 120. It now fades back over the travel's second half (r3: frames 142 to 148).",+ "by": "fresh critic r2, an agent; confirmed fixed by r3"+ },+ {+ "id": "d2-2",+ "p": "P2",+ "status": "fixed",+ "note": "9:16 frames 128 to 132: the cursor vanished in one frame during the lean. It now fades with the lean (r3: 106 to 114).",+ "by": "fresh critic r2, an agent; confirmed fixed by r3"+ },+ {+ "id": "d2-3",+ "p": "P2",+ "status": "fixed",+ "note": "9:16: the corner mark's right end sat on the right-hand zone's edge. It now sits 20 px inside the window's right edge, about 29 px clear of the zone.",+ "by": "fresh critic r2, an agent; confirmed fixed by r3"+ },+ {+ "id": "d3-1",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (round 2): a carried string fades over the band before a zone (9:16) or the frame's top and bottom edges (16:9, drawn look), measured from where it rests; the byline's dot fades with its words (critic r4 saw the dot pop on 9:16; fixed after, checked on the re-render: 16:9 fades over frames 126 to 129, 9:16 dot and words fade together 130 to 133).",+ "by": "fresh critic r3, an agent; checked by fresh critic r4, an agent"+ },+ {+ "id": "d3-2",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (round 2): the chat header recedes with the lean, fully faded before the travel carries it off (critic r4: fades from 108, gone by 116).",+ "by": "fresh critic r3, an agent; checked by fresh critic r4, an agent"+ },+ {+ "id": "d3-3",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (round 2): the 9:16 end card centres on the frame, x 540, inside the right-hand zone's edge (critic r4 measured centres 528 to 532, rightmost text at 889 of 929).",+ "by": "fresh critic r3, an agent; checked by fresh critic r4, an agent"+ },+ {+ "id": "d4-1",+ "p": "P2",+ "status": "fixed",+ "note": "End card sits 8 to 20 px left of centre on both shapes, consistent across lines: likely the headline glyphs' side bearing. Optional polish; centring by ink bounds instead of advance width would fix it. Fixed (template round 3): the cause was the end card's settle, a 3 % lean about the dot at the name's right end, which carried every line left by 3 % of the dot's distance from the axis. The settle now zooms about the card's axis, and the name with its dot is centred by its ink (kinetic.inkSpan). Measured on the render: every line within 1.5 px of the centre on 16:9 and 9:16 (test endCardCentre).",+ "by": "fresh critic r4, an agent"+ }+ ]+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExampleBrand.json b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExampleBrand.jsonnew file mode 100644index 0000000..cc723f5--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExampleBrand.json@@ -0,0 +1,97 @@+{+ "about": "anidoodle's own review record for launchExampleBrand, the worked example of a brand's own look. Written by a fresh critic (an agent), not a person's review.",+ "verdict": "fix: no P0, but six P1 open. The type, palette and end card read as Lantern's own, but the declared shapes are not honoured (pill composer and pill button), the 9:16 cut is off centre and top heavy, both transitions out of the answer have dead or colliding frames, the logo is a 20 px glyph that never reaches the end card, and the answer map says nothing a viewer can read (fresh critic r1, an agent). What works: Lora and Instrument Sans read crisply on the dark ground, the amber is used sparingly, the answer iris reads at speed, and the end card is centred and readable on both shapes",+ "findings": [+ {+ "id": "br1-1",+ "p": "P1",+ "status": "open",+ "note": "The brand's declared shapes are not what renders, so it reads as the clean template with a dark palette. The source declares shape { bubble: square, composer: bar, button: square }. Bubbles are square (good), but the composer is a fully rounded pill with a thin outline on both shapes (16:9 full frames 1.6 s and 4.4 s, 9:16 1.0 s and 3.6 s), and the library's 'Check all' button is a full pill (16:9 and 9:16, 11 to 16 s), while the composer's Ask button is a near square. Three corner languages in one film. Fix: make the composer a flat bar (square or the 14 px radius) and 'Check all' the same square button as Ask.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-2",+ "p": "P1",+ "status": "open",+ "note": "9:16 layout is off centre and top heavy through the chat and library beats. Full frame 1.0 s and 3.6 s (540 px wide sample): the window runs from x 9 to 15 on the left to x 466 to 471, so the left margin is about 2 to 3 percent of width and the right about 13 percent; everything sits in the top 72 percent with the bottom 28 percent empty dark ground. Library beat (12.5 s): card from x 36 to 444, right margin more than double the left, bottom third empty. On a phone this reads as a 16:9 layout squeezed into a corner. Fix: centre the window and library horizontally and use the full height (or centre the block vertically).",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-3",+ "p": "P1",+ "status": "open",+ "note": "The exit from the answer to the word page has dead frames on both shapes. 16:9, 4.8 to 6.4 s (10 fps strip): the composer fades, then the whole window slides slowly up off frame for about 1.3 s; from 5.8 to 6.3 s the screen is mostly an empty grey slab (the bottom of the window) with nothing to read before READ rises in. 9:16, 4.4 to 6.4 s: the window zooms in slowly for about 1.5 s (header and bubble fade), then is pushed right; the full frame at 6.0 s is the left 40 percent bare ground and a grey slab with the map card cut by the right edge, and at 6.1 to 6.3 s 'AD LESS.' is clipped against the slab's edge. The two shapes also use different transitions (vertical lift vs horizontal push). Fix: one quick, matched push (about 0.5 s) that carries the map card out as the words come in, with no empty slab frames.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-4",+ "p": "P1",+ "status": "open",+ "note": "The iris from the library to the end card collides on 9:16. 15.9 to 16.6 s (15 fps strip, full frame 16.1 s): the iris opens from the drop at the upper right, so the end card is revealed lopsided: for about 0.5 s the wordmark reads 'ern.', 'tern.', 'antern.' while the tagline and the npm pill are drawn over the still visible library card (the 'Field notes' and 'Interview' rows sit under 'npm install lantern' at 16.3 to 16.5 s, and a tagline fragment 'es' pokes out of the ring at 16.1 s). 16:9 is cleaner but shows a faint dark ring edge over the end card at about 16.2 s and the wordmark settles about 20 px sideways after the reveal (16.4 to 16.5 s). Fix: hide or fade the library inside the iris, centre the iris on the frame (or the wordmark), and land the end card without the post reveal drift.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-5",+ "p": "P1",+ "status": "open",+ "note": "The logo is not doing a logo's job. The brand has its own lantern mark (assets/brand/lantern/lanternMark.svg), but in the film it appears only as a roughly 20 by 30 px glyph in the window header (16:9 crop at 1.6 s), where it reads as a battery or jar, with a large gap before the 'Lantern' title so it looks detached. It never appears on the end card (19 s, both shapes), which uses the type wordmark plus an amber dot. A brand film should close on its mark. Fix: put the lantern mark on the end card beside or above the wordmark at a size where the lantern shape reads, and tighten the header gap.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-6",+ "p": "P1",+ "status": "open",+ "note": "The answer does not answer the question. 'which sources disagree?' is answered by six unlabelled dots, two ringed in amber (16:9 4.4 s, 9:16 6.0 s). A viewer cannot tell which sources these are or that the rings mean 'these two disagree'; the label is only 'Your sources, mapped'. On 16:9 the card is about 410 px wide on the left of a 1380 px window and the right 60 percent of the window is empty, so the payoff is small as well as mute. On 9:16 it is about a quarter of the frame width. Fix: label the two ringed nodes (for example 'Field notes, 2019' and 'Survey, spring', which the library beat then reuses), a short 'these two disagree' line, and a bigger card.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-7",+ "p": "P2",+ "status": "open",+ "note": "The corner 'Lantern' stamp is small grey type and on 9:16 it is not in a corner. 16:9: bottom right, about 18 px tall, grey, 0 to 16 s. 9:16: it hangs at about two thirds height just under the window and the library card (full frames 1.0, 3.6, 12.5, 16.1 s), so it reads as a stray caption. The header subtitle 'your reading desk' and the 'Ask Lantern...' placeholder are also grey. The person has rejected grey and tiny text before. Fix: drop the stamp (the header already says Lantern) or put it in the real corner at a readable size.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-8",+ "p": "P2",+ "status": "open",+ "note": "The second drop is born on top of the library nav. 15.3 to 15.6 s on both shapes: the amber dot appears over the 'Map' tab (covering its label) and next to 'Check all' before lifting. It reads as a glitch on the tab, not a drop leaving the product. Fix: emit it from the highlighted 'Field notes' row or from 'Check all' itself.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-9",+ "p": "P2",+ "status": "open",+ "note": "The cursor idles above the library. After 'Check all' is pressed (cue 11.27 s) the cursor sits in empty ground above the card, outside the UI, until about 16 s on both shapes (16:9 full frame 12.5 s at x 1680, y 295). Fix: let it rest on the button or leave the frame after the click.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-10",+ "p": "P2",+ "status": "open",+ "note": "Copy mismatch in the library beat: the headline says 'Then it cites every page.' but the button pressed is 'Check all' and the tags say 'cited' while the values are page counts (12 p., 40 p., 8 p.). 'every page' plus a page count suggests the whole document was cited. Minor, but a launch film's one claim should match its UI word for word. Fix: a button like 'Cite all', or show a page reference such as 'p. 4' in the tag.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-11",+ "p": "P2",+ "status": "open",+ "note": "The word page holds still for about 2.5 s. 16:9 and 9:16, about 6.9 to 9.4 s: READ LESS. / KNOW MORE. lands and nothing moves (6 fps strip shows identical frames). For a 'lively' temperament that is a freeze. On 16:9 the block also sits left (x 160 to 1310) with the right third empty, which is fine as editorial type but makes the hold feel emptier. Fix: shorten the hold to about 1.5 s or give it a small live move (the amber line drawing under, a slow drift).",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-12",+ "p": "P2",+ "status": "open",+ "note": "9:16 hook: the question breaks into three short lines ('which / sources / disagree?') inside a narrow composer, with the Ask button vertically off the text block (full frame 1.0 s). It reads cramped next to the one line 16:9 hook. Fix: a wider composer (see br1-2) so it fits on two lines, Ask aligned to the text's last line or centre.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "br1-13",+ "p": "P2",+ "status": "open",+ "note": "Sound, measured only (not listened to): integrated about -14.1 LUFS, true peak -1.4 dBTP, LRA 4.8 LU, which is fine for social. The first 2 s average about -30 dB (key ticks only), so the hook is near silent on a phone. The film also reuses the clean example's score (tallyScore), so the brand example does not have its own sound. Fix: a soft bed under the typing, and a short Lantern cue rather than the Tally score.",+ "by": "fresh critic r1, an agent"+ }+ ]+}\ No newline at end of filediff --git a/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExampleClean.json b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExampleClean.jsonnew file mode 100644index 0000000..a208be1--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExampleClean.json@@ -0,0 +1,90 @@+{+ "about": "anidoodle's own review record for launchExampleClean, the worked example of the launch template. Written by fresh critics (agents) over two rounds, not a person's review. A film made from the template gets its own record, written for that film (references/workflows/review.md).",+ "verdict": "ship (builder agent, template r3): no open P0 or P1; every P2 from critics r1 and r2 fixed and the film re-shipped PASS on 16:9 and 9:16",+ "findings": [+ {+ "id": "c1-1",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): the end card no longer holds still. As its last part lands the page settles in 3 % about the dot on an out-cubic, and the install line is fully on for more than 3 s of it.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-2",+ "p": "P1",+ "status": "fixed",+ "note": "Words sink at frames 910 to 935, and the headline is fully gone before the dot travels and the bloom opens at 960 to 984. Nothing is cut mid-word.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "c1-3",+ "p": "P1",+ "status": "fixed",+ "note": "Copy now reads 'Month end, one click.' (frames 560 to 700), and the cursor click on Close month at 596 agrees with the words.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "c1-4",+ "p": "P1",+ "status": "fixed",+ "note": "The bloom is now the loudest moment: momentary -10.5 LUFS at 16.3 s against a body of about -12.5, true peak -1.4 dBFS. Slim margin; a short dip before the drop would sell it. Measured only: a person must listen.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "c1-5",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): the grid card's footer stamp is set inline, one gap after the text block (endCard stamp: \"inline\"), and a lockup with a descender declares it (descent 0.3), so the line under 'Tally' keeps its air.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-6",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): on 16:9 the travels alternate, down then up then down; no two in a row arrive from the same side.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-7",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): on 9:16 the corner mark sits flush with the content's right edge, at the bottom of the safe rectangle (the platforms' bottom 25 % holds no text, so that is the frame's usable corner), clear of the window.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-8",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): in a tall frame the product's rows are tall touch rows, so the panel fills the safe rectangle above the corner mark. The bottom 25 % stays empty by design: it is the platforms' caption zone.",+ "by": "fresh critic r1, rechecked by r2 (agents); fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c1-9",+ "p": "P2",+ "status": "fixed",+ "note": "Counter steps 14 to 3 to 0 across frames 110 to 140, and rows flip to 'matched' one by one.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "c2-1",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): the drop swells left of Explain and clear of its word on both shapes (launchGrammar checks it at any push).",+ "by": "fresh critic r2, an agent; fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c2-2",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): frame 0 shows the prompt typed to a whole word ('match every').",+ "by": "fresh critic r2, an agent; fixed in template r3, checked by the builder agent"+ },+ {+ "id": "c2-3",+ "p": "P2",+ "status": "fixed",+ "note": "Fixed (template r3): after each click the pointer rests just above the product window, never on a row's figure (on 9:16 it had settled on '$1,208' at frame 935).",+ "by": "fresh critic r2, an agent; fixed in template r3, checked by the builder agent"+ }+ ]+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExampleCleanChat.json b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExampleCleanChat.jsonnew file mode 100644index 0000000..e182a48--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/reviews/launchExampleCleanChat.json@@ -0,0 +1,97 @@+{+ "about": "anidoodle's own review record for launchExampleCleanChat, the worked example of the clean look with a chat ask. Written by a fresh critic (an agent), not a person's review. A film made from the template gets its own record (references/workflows/review.md).",+ "verdict": "fix: no P0 or P1 open (cc1-3 iris and cc2-1 16:9 thread are fixed); after round 3 these P2s remain: grey tiny type (cc1-4), orphan end card pill on 16:9 (cc1-5), handover frames (cc1-6), near silent hook, measured only (cc1-7), 9:16 layout and small answer card (cc2-2, cc2-3), new small 16:9 answer card (cc3-1) and iris ring corner fragments (cc3-2) (fresh critic r3, an agent)",+ "findings": [+ {+ "id": "cc1-1",+ "p": "P1",+ "status": "fixed",+ "note": "The composer does not travel as one object. 16:9, 1.1 to 2.2 s (10 fps strip): it slides down at full size (it even grows a little from 1.3 to 1.7 s). Its vertical travel is almost done by 1.8 s (about 20 px left of 1080), and then it shrinks to about 55 % width from 1.8 to 2.1 s, nearly in place. That reads as a second move after the landing. 9:16 does the same at 1.8 to 2.4 s, ending as a narrow box with the question broken over three small lines. Scale should run on the same curve as the travel and finish with it. Checked r2: 16:9 at 0.8 to 2.6 s (10 fps strip) and 9:16 at the same span: the composer slides from mid window to the bottom between about 1.3 and 1.9 s at one constant size and stays that size after it lands; no shrink while moving or after. The question keeps two or three large lines on 9:16. Fixed on both shapes.",+ "by": "fresh critic r1, an agent; checked fixed by fresh critic r2, an agent"+ },+ {+ "id": "cc1-2",+ "p": "P1",+ "status": "fixed",+ "note": "The inbox reorder glitches instead of sliding. 16:9, 11.5 to 11.8 s (8 fps strip): at 11.5 s the 'Team lunch' row is half see-through on top of the slot below it. At 11.6 s only 'Cloud hosting' is left, with one empty ghost row and a blank lower half in the panel. At 11.75 s a faded 'Design tool' row overlaps 'Team lunch'. That breaks the opaque rule, and on a normal viewing the rows look like they vanish and collide. Same beat on 9:16 at about 11.5 s. Rows should keep full opacity and visibly swap places. Checked r2: 16:9 and 9:16 at 10.4 to 12.8 s (8 fps strips) and a full frame at 12.5 s: there is no reorder any more; the three rows stay fully opaque in place, no ghost row, no overlap, and they tick to matched in turn at about 11.6 to 11.8 s. Fixed on both shapes.",+ "by": "fresh critic r1, an agent; checked fixed by fresh critic r2, an agent"+ },+ {+ "id": "cc1-3",+ "p": "P1",+ "status": "fixed",+ "note": "The answer's iris does not read, and it is the payoff. 16:9, 2.6 to 3.6 s: the blue drop flying from Ask to the chart spot reads well, but it vanishes and the iris that follows is a cream disc opening on a cream card on a white window (at 3.1 s it is a faint 40 px circle you can barely see). At speed it looks like the chart fading in, not an iris opening. Same on 9:16 at 3.0 to 3.5 s. Give the iris edge contrast (an ink or blue rim, or open it onto the canvas colour) so the circle shape is seen. Still stands r2, half fixed: the iris is now a pale blue disc instead of cream. On 16:9 (full frame 3.55 s, strip 3.3 to 4.0 s) it is a 245 px disc and the circle shape reads in a still, though it has no rim and is low contrast (pale blue on a pale pink card on white). On 9:16 (full frame 3.5 s) the whole chart card is only about 265 px wide, the disc is about 85 px and very faint on a near white card, so at speed it still reads as a fade, not an iris. Needs an edge (ink or accent rim) and, on 9:16, a bigger answer card (see cc2-3). Checked r3: 16:9 strip 3.0 to 4.1 s (10 fps) and 9:16 the same span: the drop lands at about 3.4 s, then a thin solid accent blue ring opens from about 40 px to past the card edge by 3.9 s, with the chart showing inside it. The circle is clearly an iris at speed on both shapes, not a fade. Small leftover logged as cc3-2.",+ "by": "fresh critic r1, an agent; checked fixed by fresh critic r3, an agent"+ },+ {+ "id": "cc1-4",+ "p": "P2",+ "status": "open",+ "note": "Tiny grey text that does not earn its place. A corner 'Tally' stamp, about 10 px tall on 1080, sits bottom right in every shot from 0 to about 15 s on both shapes. You cannot read it at a phone glance, and it repeats the wordmark. The window header subtitle 'your books, answered' (0 to 5 s) and the grey 'matched' chips on the secondary rows (11.7 to 15 s) are also small grey type. The person has rejected grey and tiny text before. Still stands r2: the corner 'Tally' stamp (grey, about 18 px on 1080) is still bottom right from 0 to about 16 s on both shapes; the grey 'your books, answered' subtitle (0 to 5 s) and grey 'matched' chips on the two secondary rows (11.7 to 16 s, full frame 12.5 s) are unchanged. Still stands r3: full frames 0.5 s and 2.8 s: grey corner \"Tally\" stamp (about 20 px) still bottom right on both shapes, grey \"your books, answered\" subtitle unchanged; grey \"matched\" chips on the two lower inbox rows from about 11.7 s unchanged.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "cc1-5",+ "p": "P2",+ "status": "open",+ "note": "End card hierarchy, 16:9 from 15.5 s: the 'tally.example' pill floats on its own at x 1193 to 1591, 190 px past the end of the tagline, and lines up with no edge of the block above. It reads as an orphan, and the solid blue pill is the second-loudest thing on the card, louder than the tagline. The tagline also sits tight on the npm line (about 40 px) but far from the wordmark (about 90 px), so the two lower lines read as one clump. On 9:16 the pill stacks under the block and sits better. Still stands r2: 16:9 end card at 17 s, the 'tally.example' pill still floats alone at x 1185 to 1575, 70 px past the tagline, aligned to nothing, and stays the second loudest object; tagline still sits tight on the npm line and far from the wordmark. 9:16 stacks it and is fine. Still stands r3: 16:9 full frame 17 s: the \"tally.example\" pill still floats alone at x 1185 to 1575, about 70 px past the tagline, aligned to nothing, the second loudest thing on the card. 9:16 stacks it under the block and is fine.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "cc1-6",+ "p": "P2",+ "status": "open",+ "note": "The handover from the chart to the word page leaves poster-bad frames. 16:9, 5.4 to 6.2 s: the window is zoomed and cropped, with two white slabs (window, then a second copy of the chart card's foot) sliding up off the frame while 'ASK' rises from the bottom edge. 9:16, 5.9 to 6.4 s: a vertical wipe cuts through the words, so 'SK IT.' shows with the A still hidden behind the white window. Start the words after the wipe has passed their left edge. Still stands r2: 16:9 at 5.4 to 5.8 s still shows two or three stacked copies of the window and chart card sliding up while 'ASK' rises from the bottom edge. 9:16 at 6.0 to 6.4 s the vertical wipe still cuts the words ('K IT.', 'SK IT.') beside a half hidden chart card. Still stands r3: 16:9 strip 5.3 to 6.4 s: at 5.3 s two copies of the chart card show in two stacked white slabs, then the slabs slide up while \"ASK\" rises cut by the bottom edge (5.5 to 5.7 s). 9:16 strip same span: the vertical wipe still slices the words (\"IT\", \"K IT.\", \"SK IT.\") beside a half hidden chart card at 5.9 to 6.3 s.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "cc1-7",+ "p": "P2",+ "status": "open",+ "note": "Sound, measured only, so a person must listen: integrated -14.1 LUFS, true peak -1.4 dBFS, the same on both shapes. The loudest momentary is -11.6 LUFS at 7.5 s on the 'ASK IT. SEE WHY.' page. The answer opening (3 s, -16.5) and the end card's arrival (15.5 s, -12.4) are not the loudest moments. The first 2 s sit at -25 to -30 LUFS momentary, so the hook is nearly silent while the question types. Still stands r2: measured again, integrated -14.1 LUFS on both shapes; momentary is -25 to -28.5 LUFS from 0.5 to 2.1 s (the hook is near silent) and the loudest moments (-11.5) are at 7.6 s and 16.1 s, not the answer opening at 3 s (-15.6). A person must listen. Still stands r3: measured again (cannot hear): integrated -14.1 LUFS, true peak -1.2 (16:9) and -1.4 dBFS (9:16); momentary -24 to -30 LUFS from 0.5 to 2.1 s; loudest moments -11.7 at 7.5 s and -12.2 at 9.0 s, while the answer opening is -13.3 at 3.4 s. A person must listen.",+ "by": "fresh critic r1, an agent"+ },+ {+ "id": "cc1-8",+ "p": "P2",+ "status": "fixed",+ "note": "The thread bubble 'why did hosting go up?' and the chart label 'Cloud hosting, by month' are about 14 px type on 16:9 (2.5 to 5.5 s). A phone viewing a landscape film shows them at roughly 5 px. They are context the viewer already saw typed large, so it is not fatal, but the answer's label is the only words that say what the chart shows. Checked r2: on 16:9 the chart label 'Cloud hosting, by month' is now about 22 px (full frame 4.5 s) and the chart card is about 490 px wide, readable. The thread bubble no longer shows long enough to matter on 16:9 (see cc2-1). On 9:16 the bubble and label are about 30 px, readable. The legibility point is fixed; the thread problem is new and logged as cc2-1.",+ "by": "fresh critic r1, an agent; checked fixed by fresh critic r2, an agent"+ },+ {+ "id": "cc2-1",+ "p": "P1",+ "status": "fixed",+ "note": "New since the composer now stays big: on 16:9 the thread has no room for the question. The user bubble 'why did hosting go up?' appears at the top of the thread at about 2.5 s and scrolls straight up under the header rule: at 2.8 s (full frame) it is cut in half by the header line, and by 3.3 s it is gone, so the answer chart opens with no question above it. The chart card's bottom is also cut flat by the thread's clip just above the composer (3.55 s and 4.5 s, square bottom corners, shadow cut). 9:16 keeps the bubble and is fine. Give the thread the height it needs (shorter composer after the send, or a taller window) so question and answer are seen together. Checked r3: 16:9 full frames 2.8 s and 4.5 s and strip 3.0 to 4.1 s: the question bubble sits right under the header rule, whole, from about 2.6 s through 5 s, and the chart card below it has round bottom corners and its full shadow, about 200 px clear of the composer. Question and answer are seen together. The cost is a smaller card, logged as cc3-1.",+ "by": "fresh critic r2, an agent; checked fixed by fresh critic r3, an agent"+ },+ {+ "id": "cc2-2",+ "p": "P2",+ "status": "open",+ "note": "9:16 composition: from 0 to about 5 s the app window sits in the top 72 % of the frame and off centre (about 18 px margin left, 137 px right at 1080 wide; full frames 0.5 s and 3.5 s), leaving a 540 px empty band of canvas at the bottom. Reads as a misplaced layout, not as intent. Centre it and use the height. Still stands r3: 9:16 full frame 0.5 s: window still x 33 to 928 (33 px margin left, 152 right) and y 268 to 1364, with about 556 px of empty canvas below it, up to about 5 s.",+ "by": "fresh critic r2, an agent"+ },+ {+ "id": "cc2-3",+ "p": "P2",+ "status": "open",+ "note": "9:16 answer card is too small for the payoff: the chart card is about 265 px wide on a 1080 frame (full frames 3.5 s and 4.5 s), with the label, the bubble and a lot of empty white window below it. The film's key image is a thumbnail until the zoom at about 5 s. Still stands r3: 9:16 full frame 4.5 s (zoom already starting): chart card about 280 px wide on 1080, the rest of the window empty white below it; the key image is still a thumbnail until the zoom.",+ "by": "fresh critic r2, an agent"+ },+ {+ "id": "cc3-1",+ "p": "P2",+ "status": "fixed",+ "note": "16:9: the cc2-1 fix shrank the answer card. Full frame 4.5 s: the chart card is about 280 px wide (x 402 to 684) on a 1920 frame, under 15 % of the width, with the right two thirds of the thread empty between the bubble and the composer. The payoff image now reads as a thumbnail on 16:9 too (same as cc2-3 on 9:16). The room is there: a wider card, or a slightly shorter composer after the send, would let it be about twice the size. Fixed after r3 (builder agent): the clean hook, which is also the dock, is now set at the hook's smallest size (56 px on 16:9, 64 px on 9:16), so the docked composer is 171 px tall on 16:9 instead of 296 and the answer card is 393 px instead of 280 (checked on the render at 3.8 to 4.5 s). Not rechecked by a fourth critic: review.md stops at round 3.",+ "by": "fresh critic r3, an agent; fixed by the builder agent after r3"+ },+ {+ "id": "cc3-2",+ "p": "P2",+ "status": "fixed",+ "note": "Iris end, 16:9 strip 3.8 to 3.9 s and 9:16 the same: the accent ring grows past the card, so for two or three frames it shows only as four blue arc fragments at the card corners before it vanishes. Seen only on pause; fading the ring as it reaches the card edge would close it cleanly. Fixed after r3 (builder agent): the rim is drawn only while the whole ring is inside the card (test irisRim), so no arcs are left in the corners (checked at 3.77 to 3.97 s on both shapes). Not rechecked by a fourth critic.",+ "by": "fresh critic r3, an agent; fixed by the builder agent after r3"+ }+ ]+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/brandKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/brandKit.tsnew file mode 100644index 0000000..e31f4e7--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/brandKit.ts@@ -0,0 +1,144 @@+// BRAND KIT. Draws a brand's own elements exactly as `tools/brand.mjs import` exported them, and only+// ever moves them. A brand mark redrawn by eye, morphed through a blur or squashed into an ellipse is a+// different mark to its owner: a launch film lost four rounds of notes to a goo "mitosis" of a logo and+// to brand dots squashed out of round. So the rule lives in the code, not only in the docs:+// - parts are filled from their exported paths, never rebuilt;+// - an element may be translated, rotated, uniformly scaled, clipped and layered;+// - drawEl throws on a non-uniform scale or a skew in the current transform, unless the caller names the+// gag the squash serves ({ allowSquash: "the dot is crushed by the falling chat window" });+// - the caller's globalAlpha and transform are kept (a helper that resets alpha breaks every fade);+// - each drawn element reports its on-screen box to the frame probe ("brand:<name>"), so the shape scans see it.+//+// import { BRAND } from "./myBrand"; // written by brand.mjs import+// ctx.save(); ctx.translate(x, y); ctx.rotate(a); ctx.scale(s, s);+// drawEl(ctx, BRAND.elements.mark); ctx.restore();+// riseIn(ctx, BRAND.elements.lockup.parts[3], k); // one letter rises from behind its own baseline+import { probeRect, type Ctx, type Env, type ProbeRec } from "./core";++export type BrandStop = [offset: number, colour: string, alpha: number];+export type BrandPaint =+ | { type: "solid"; c: string }+ | { type: "lin"; x1: number; y1: number; x2: number; y2: number; stops: BrandStop[]; m?: number[] }+ | { type: "rad"; cx: number; cy: number; r: number; fx: number; fy: number; stops: BrandStop[]; m?: number[] }+ | { type: "none" };+export type BrandPart = {+ d: string; fill: BrandPaint; rule: string; op: number; bb: number[]; m?: number[];+ stroke?: { paint: BrandPaint; w: number; cap: string; join: string; op: number };+ clip?: { paths: { d: string; m: number[] }[] };+};+export type BrandElement = { w: number; h: number; parts: BrandPart[] };++const P2 = new Map<string, Path2D>();+/** One Path2D per path string, built once (it never changes, so caching it keeps the draw pure). */+const path = (d: string) => { let p = P2.get(d); if (!p) { p = new Path2D(d); P2.set(d, p); } return p; };+const hexA = (h: string, a: number) => { if (a >= 1 || !/^#[0-9a-f]{6}$/i.test(h)) return h; const n = parseInt(h.slice(1), 16); return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`; };++const gradient = (ctx: Ctx, f: BrandPaint): CanvasGradient | string => {+ if (f.type === "solid") return f.c;+ if (f.type === "none") return "rgba(0,0,0,0)";+ const g = f.type === "lin" ? ctx.createLinearGradient(f.x1, f.y1, f.x2, f.y2) : ctx.createRadialGradient(f.fx, f.fy, 0, f.cx, f.cy, f.r);+ for (const [o, c, a] of f.stops) g.addColorStop(Math.max(0, Math.min(1, o)), hexA(c, a));+ return g;+};+/** Fill a path with a paint. A gradient with its own matrix is drawn in gradient space under a clip, which is exact for any affine. */+const fillWith = (ctx: Ctx, p: Path2D, rule: CanvasFillRule, f: BrandPaint, bb: number[]) => {+ if (f.type === "none") return;+ const m = f.type !== "solid" ? f.m : undefined;+ if (!m) { ctx.fillStyle = gradient(ctx, f); ctx.fill(p, rule); return; }+ ctx.save(); ctx.clip(p, rule); ctx.transform(m[0], m[1], m[2], m[3], m[4], m[5]); ctx.fillStyle = gradient(ctx, f);+ const det = m[0] * m[3] - m[1] * m[2] || 1, inv = [m[3] / det, -m[1] / det, -m[2] / det, m[0] / det, (m[2] * m[5] - m[3] * m[4]) / det, (m[1] * m[4] - m[0] * m[5]) / det];+ const pad = 2, corners = [[bb[0] - pad, bb[1] - pad], [bb[0] + bb[2] + pad, bb[1] - pad], [bb[0] - pad, bb[1] + bb[3] + pad], [bb[0] + bb[2] + pad, bb[1] + bb[3] + pad]].map(([x, y]) => [inv[0] * x + inv[2] * y + inv[4], inv[1] * x + inv[3] * y + inv[5]]);+ const xs = corners.map((c) => c[0]), ys = corners.map((c) => c[1]);+ ctx.fillRect(Math.min(...xs), Math.min(...ys), Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));+ ctx.restore();+};++/** Draw one exported part as it is, times the caller's alpha. */+export function drawPart(ctx: Ctx, p: BrandPart, alpha = 1) {+ const g = ctx.globalAlpha;+ ctx.save();+ if (p.clip) clipIn(ctx, p);+ if (p.m) ctx.transform(p.m[0], p.m[1], p.m[2], p.m[3], p.m[4], p.m[5]);+ ctx.globalAlpha = g * alpha * (p.op ?? 1);+ // bb is in element space; the gradient fill wants it in the part's own space, so map it back through m+ fillWith(ctx, path(p.d), (p.rule === "evenodd" ? "evenodd" : "nonzero") as CanvasFillRule, p.fill, p.m ? localBox(p) : p.bb);+ if (p.stroke) {+ ctx.globalAlpha = g * alpha * (p.stroke.op ?? 1); ctx.lineWidth = p.stroke.w; ctx.lineCap = p.stroke.cap as CanvasLineCap; ctx.lineJoin = p.stroke.join as CanvasLineJoin;+ ctx.strokeStyle = gradient(ctx, p.stroke.paint); ctx.stroke(path(p.d));+ }+ ctx.restore();+ ctx.globalAlpha = g; // keeps any fade the caller set+}+/** Clip to the part's clip-path: its shapes (a union) carry their own matrices in element space. */+function clipIn(ctx: Ctx, p: BrandPart) {+ const c = new Path2D();+ for (const q of p.clip!.paths) c.addPath(path(q.d), { a: q.m[0], b: q.m[1], c: q.m[2], d: q.m[3], e: q.m[4], f: q.m[5] });+ ctx.clip(c);+}+const localBox = (p: BrandPart) => {+ const m = p.m!, det = m[0] * m[3] - m[1] * m[2] || 1, inv = [m[3] / det, -m[1] / det, -m[2] / det, m[0] / det, (m[2] * m[5] - m[3] * m[4]) / det, (m[1] * m[4] - m[0] * m[5]) / det];+ const [x, y, w, h] = p.bb, pts = [[x, y], [x + w, y], [x, y + h], [x + w, y + h]].map(([a, b]) => [inv[0] * a + inv[2] * b + inv[4], inv[1] * a + inv[3] * b + inv[5]]);+ const xs = pts.map((q) => q[0]), ys = pts.map((q) => q[1]);+ return [Math.min(...xs), Math.min(...ys), Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys)];+};++/**+ * How the current transform distorts a shape: the x and y scales and the skew (cosine of the angle between the axes).+ * A uniform scale with a rotation has sx = sy and skew 0.+ */+export const distortion = (m: { a: number; b: number; c: number; d: number }) => {+ const sx = Math.hypot(m.a, m.b), sy = Math.hypot(m.c, m.d), skew = sx && sy ? (m.a * m.c + m.b * m.d) / (sx * sy) : 0;+ return { sx, sy, skew, squash: Math.max(sx, sy) ? Math.abs(sx - sy) / Math.max(sx, sy) : 0 };+};+export type DrawElOpts = { alpha?: number; name?: string; allowSquash?: string; env?: Env; probe?: boolean };+/** The element's ink box in element space: the union of its parts' boxes. */+export const inkBox = (el: BrandElement) => {+ if (!el.parts.length) return [0, 0, el.w, el.h];+ const x0 = Math.min(...el.parts.map((p) => p.bb[0])), y0 = Math.min(...el.parts.map((p) => p.bb[1]));+ return [x0, y0, Math.max(...el.parts.map((p) => p.bb[0] + p.bb[2])) - x0, Math.max(...el.parts.map((p) => p.bb[1] + p.bb[3])) - y0];+};+/**+ * Tell the frame probe where a brand element landed (device pixels, kind "box", label "brand:<name>"), so the+ * scans that look for shapes (layerscan's shape-over-a-face check, framecheck's edge cuts) see brand marks too.+ * With the film's env it goes through probeRect (which reports only on the frame's own canvas); without one it+ * reports straight to the probe, which suits the usual case of a mark drawn on the frame. Off when no probe is installed.+ */+const reportBox = (ctx: Ctx, el: BrandElement, opts: DrawElOpts) => {+ if (opts.probe === false || (opts.alpha ?? 1) * ctx.globalAlpha < 0.1) return;+ const [x, y, w, h] = inkBox(el), label = `brand:${opts.name ?? "element"}`;+ if (opts.env) { probeRect(ctx, opts.env, x, y, w, h, label, "box"); return; }+ const p = (globalThis as { __ANIDOODLE_PROBE__?: (r: ProbeRec) => void }).__ANIDOODLE_PROBE__;+ if (!p || typeof ctx.getTransform !== "function") return;+ const m = ctx.getTransform(), pts = [[x, y], [x + w, y], [x, y + h], [x + w, y + h]].map(([a, b]) => [m.a * a + m.c * b + m.e, m.b * a + m.d * b + m.f]);+ p({ kind: "box", label, x0: Math.min(...pts.map((q) => q[0])), y0: Math.min(...pts.map((q) => q[1])), x1: Math.max(...pts.map((q) => q[0])), y1: Math.max(...pts.map((q) => q[1])) });+};+/** Draw a whole brand element. Throws on a squash or skew of more than 1% unless `allowSquash` names the gag. */+export function drawEl(ctx: Ctx, el: BrandElement, opts: DrawElOpts = {}) {+ if (!opts.allowSquash && typeof ctx.getTransform === "function") {+ const t = distortion(ctx.getTransform());+ if (t.squash > 0.01 || Math.abs(t.skew) > 0.01) throw new Error(`brand: element ${opts.name ? `'${opts.name}' ` : ""}drawn with a non-uniform scale or skew (x ${t.sx.toFixed(3)}, y ${t.sy.toFixed(3)}, skew ${t.skew.toFixed(3)}). A brand mark is only moved, rotated, scaled evenly, clipped or layered; an ellipse of a brand circle is a redraw. If the squash IS the joke, pass { allowSquash: "<the gag it serves>" }.`);+ }+ for (const p of el.parts) drawPart(ctx, p, opts.alpha ?? 1);+ reportBox(ctx, el, opts);+}+/** Place an element by its box: centre at (x, y), height h (or width w), rotated by `rot` radians. Uniform by construction. */+export function placeEl(ctx: Ctx, el: BrandElement, at: { x: number; y: number; h?: number; w?: number; rot?: number; alpha?: number; name?: string; env?: Env }) {+ const s = at.h != null ? at.h / el.h : at.w != null ? at.w / el.w : 1;+ ctx.save(); ctx.translate(at.x, at.y); if (at.rot) ctx.rotate(at.rot); ctx.scale(s, s); ctx.translate(-el.w / 2, -el.h / 2);+ try { drawEl(ctx, el, { alpha: at.alpha, name: at.name, env: at.env }); } finally { ctx.restore(); }+}+/** A part rises into place from behind its own baseline (the clip is the line it sits on); k 0..1. */+export function riseIn(ctx: Ctx, p: BrandPart, k: number) {+ if (k <= 0) return; if (k >= 1) { drawPart(ctx, p); return; }+ const [x, y, w, h] = p.bb;+ ctx.save(); ctx.beginPath(); ctx.rect(x - w, y - h * 4, w * 3, h * 4 + h + 1.5); ctx.clip();+ ctx.translate(0, (1 - k) * h * 1.08); drawPart(ctx, p); ctx.restore();+}+/** Centre of a part's box, in element space. */+export const centreOf = (p: BrandPart): [number, number] => [p.bb[0] + p.bb[2] / 2, p.bb[1] + p.bb[3] / 2];+/** Tile an element along x every `period` units (a frieze whose repeat brand.mjs measured), across [0, span]. */+export function tileX(ctx: Ctx, el: BrandElement, period: number, offset: number, span: number) {+ if (period <= 0) throw new Error("brand: tileX needs the element's measured period (brand.mjs import prints it)");+ const start = Math.floor(-offset / period) - 1;+ for (let i = start; i * period + offset < span + period; i++) { ctx.save(); ctx.translate(i * period + offset, 0); drawEl(ctx, el, { name: "tile" }); ctx.restore(); }+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/core.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/core.tsindex 33b8ac1..300b86c 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/core.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/core.ts@@ -11,6 +11,9 @@ export type Layer = { canvas: CanvasImageSource & { width: number; height: numbeexport type Env = {W: number; H: number; scale: number; // logical size, device pixels per logical pixelcanvas(w: number, h: number): Layer; // the ONLY way the core obtains an offscreen surface+ // OPTIONAL, host-provided: a WebGL-capable surface for 3D shots (three-core/stage.ts asks for it+ // once and keeps it). The core never creates canvases itself; a host without WebGL leaves it out.+ webgl?(w: number, h: number): OffscreenCanvas | HTMLCanvasElement;image?(name: string): CanvasImageSource | undefined; // assets are decoded by the ADAPTER before frame 0cache: Map<string, unknown>;// OPTIONAL, host-provided: a store of finished plate frames that outlives the page (the adaptersdiff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/cues.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/cues.tsnew file mode 100644index 0000000..cc8e5b7--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/cues.ts@@ -0,0 +1,108 @@+// CUE SHEET. The film says when its events happen, once, in its own source, and every tool reads+// that: the sound mix, the sync check, the duration budget. A brand launch film kept a second copy of+// its timing in a Python file (a hand-kept timing script) that re-implemented the film's time maps by hand; it drifted+// twice (one section left at real time after a 25 % slowdown, logo keys set in the wrong units), and+// its effects landed at chance level (49 % of 97 visual events had a sound, 71 % by chance alone).+//+// export const myFilm = withCues(film, [+// { name: "x-lock", at: { scene: 22.0, through: [master] } }, // a scene time, through the film's time maps+// { name: "fall", at: { scene: 11.94, through: [slowMo, master] } }, // innermost map first, as they are applied+// { name: "card", at: { film: 84.2 }, sync: true }, // a film time, also a verify-export sync marker+// { name: "tap", at: { frame: 512 }, sound: "tap:tock -4" }, // a whole frame, with its sound+// ]);+// node tools/cues.mjs myFilm -> out/myFilm.cues.json, which tools/track.mjs mix reads+//+// Times say their units: a bare number throws, because "4.4" in scene seconds and "4.4" in film seconds+// are different frames once a time map runs (the logo-keys bug). Pure: arithmetic over the maps.+import type { Film } from "./film";+import type { TimeRemap } from "./timeRemap";++export type CueAt = { frame: number } | { film: number } | { scene: number; through?: TimeRemap[] };+export type CueDef = { name: string; at: CueAt; sound?: string; sync?: boolean; note?: string };+export type FilmCue = { name: string; frame: number; t: number; sound?: string; sync?: boolean; note?: string };+export type CuedFilm = Film & { cues: FilmCue[] };++/** The film frame (fractional) that shows scene frame `t` under one map: the inverse of map.at, by bisection. */+export const invertRemap = (map: TimeRemap, t: number) => {+ const whole = map.filmFrameOf(t); // the first whole frame at or past t+ let lo = whole - 1, hi = whole;+ if (map.at(lo) >= t) return lo;+ for (let k = 0; k < 40; k++) { const mid = (lo + hi) / 2; if (map.at(mid) >= t) hi = mid; else lo = mid; }+ return hi;+};++/** One cue's film frame, fractional: a scene time is carried out through each map in turn. */+export const cueFrame = (at: CueAt, fps: number): number => {+ if (typeof at !== "object" || at === null) throw new Error(`cue time ${String(at)} has no units: write { scene: s }, { film: s } or { frame: n }`);+ if ("frame" in at) { if (!Number.isFinite(at.frame)) throw new Error(`cue frame must be a number, got ${String(at.frame)}`); return at.frame; }+ if ("film" in at) { if (!Number.isFinite(at.film)) throw new Error(`cue film time must be a number of seconds, got ${String(at.film)}`); return at.film * fps; }+ if ("scene" in at) {+ if (!Number.isFinite(at.scene)) throw new Error(`cue scene time must be a number of seconds, got ${String(at.scene)}`);+ let f = at.scene * fps; for (const m of at.through ?? []) f = invertRemap(m, f); return f;+ }+ throw new Error(`cue time ${JSON.stringify(at)} has no units: write { scene: s }, { film: s } or { frame: n }`);+};++/**+ * The film's cue sheet: each cue on the first whole frame that shows it (a sound cued a frame early+ * reads as a lead, a frame late as a lag), with its exact time in seconds. Names are unique, cues sit+ * inside the film, and the list is sorted by frame.+ */+export const cueSheet = (meta: Pick<Film["meta"], "fps" | "durationFrames">, defs: CueDef[]): FilmCue[] => {+ const seen = new Set<string>();+ const out = defs.map((d, i) => {+ if (!d || typeof d.name !== "string" || !d.name.trim()) throw new Error(`cue #${i} needs a name (what happens: "x-lock", "card-lands")`);+ if (seen.has(d.name)) throw new Error(`cue "${d.name}" is declared twice; give each event its own name ("land-1", "land-2")`);+ seen.add(d.name);+ const f = cueFrame(d.at, meta.fps), frame = Math.ceil(f - 1e-6);+ if (frame < 0 || frame >= meta.durationFrames) throw new Error(`cue "${d.name}" lands on frame ${frame}, outside the film (0..${meta.durationFrames - 1})`);+ return { name: d.name, frame, t: +(f / meta.fps).toFixed(4), ...(d.sound ? { sound: d.sound } : {}), ...(d.sync ? { sync: true } : {}), ...(d.note ? { note: d.note } : {}) };+ });+ return out.sort((a, b) => a.frame - b.frame || a.name.localeCompare(b.name));+};++/** The film with its cue sheet attached, and the cues marked sync added to meta.sync (verify-export's markers). */+export const withCues = (film: Film, defs: CueDef[]): CuedFilm => {+ const cues = cueSheet(film.meta, defs), sync = cues.filter((c) => c.sync).map((c) => ({ frame: c.frame, label: c.name }));+ const meta = sync.length ? { ...film.meta, sync: [...(film.meta.sync ?? []), ...sync] } : film.meta;+ return { ...film, meta, cues };+};++/** What changed between two cue sheets (a mix built from an old sheet is out of date): moved, added, removed. */+export const diffCues = (was: FilmCue[], now: FilmCue[], tolFrames = 0) => {+ const a = new Map(was.map((c) => [c.name, c])), b = new Map(now.map((c) => [c.name, c])), out: string[] = [];+ for (const [n, c] of b) {+ const o = a.get(n); if (!o) { out.push(`added "${n}" at frame ${c.frame}`); continue; }+ if (Math.abs(o.frame - c.frame) > tolFrames) out.push(`moved "${n}" from frame ${o.frame} to ${c.frame} (${((c.frame - o.frame) / 1).toFixed(0)} frames)`);+ // the mix plays the cue's sound, and verify-export reads its sync mark: a change to either is a stale mix too+ if ((o.sound ?? "") !== (c.sound ?? "")) out.push(`"${n}" changed its sound from ${o.sound ?? "none"} to ${c.sound ?? "none"}`);+ if (!!o.sync !== !!c.sync) out.push(`"${n}" ${c.sync ? "gained" : "lost"} its sync mark`);+ }+ for (const n of a.keys()) if (!b.has(n)) out.push(`removed "${n}"`);+ return out;+};++/**+ * Any film's cues as sheet cues: { name, frame, t } each. A withCues sheet passes through unchanged. A+ * launch template film carries its sound cues as film.cues ({ frame, kind, variant, label }, no name and+ * no time): each gets t = frame / fps, its label (or its kind) as the name, numbered in frame order when+ * the label repeats (every key of a typed prompt), and kind:variant as its sound, so --check can tell+ * one moved cue from another.+ */+export const sheetCues = (cues: readonly ({ frame: number; name?: string; t?: number; label?: string; kind?: string; variant?: string; sound?: string; sync?: boolean; note?: string })[], fps: number): FilmCue[] => {+ const seen = new Map<string, number>();+ return [...cues].sort((a, b) => a.frame - b.frame).map((c) => {+ if (typeof c.name === "string" && c.name && typeof c.t === "number") return c as FilmCue;+ const base = c.name || c.label || c.kind || "cue", k = (seen.get(base) ?? 0) + 1; seen.set(base, k);+ const sound = c.sound ?? (c.kind ? (c.variant ? `${c.kind}:${c.variant}` : c.kind) : undefined);+ return { name: k === 1 ? base : `${base} #${k}`, frame: c.frame, t: c.frame / fps, ...(sound ? { sound } : {}), ...(c.sync ? { sync: true } : {}), ...(c.note ? { note: c.note } : {}) };+ });+};++/** What changed between a written cue sheet and the film's sheet now: frame rate, length, then every cue. */+export const diffSheets = (was: { fps?: number; durationFrames?: number; cues?: FilmCue[] }, now: { fps: number; durationFrames: number; cues: FilmCue[] }) => {+ const out: string[] = [];+ if (was.fps !== now.fps) out.push(`the film runs at ${now.fps} fps now, ${was.fps ?? "no"} fps when the sheet was written`);+ if (was.durationFrames !== now.durationFrames) out.push(`the film is ${now.durationFrames} frames now, ${was.durationFrames ?? "no"} when the sheet was written`);+ return [...out, ...diffCues(was.cues ?? [], now.cues)];+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/endCard.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/endCard.tsnew file mode 100644index 0000000..6c64474--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/endCard.ts@@ -0,0 +1,90 @@+// END CARD. One card, one frame, an asymmetric grid: the layout the director approved on a brand launch film+// after rejecting a centred stack ("who is gonna read this overload of info?"), a shrunken card under a+// stinger and a split into extra frames ("too many slides now"). Built from the approved v12 card:+// lockup top-left at the margin; the event lines (date, venue) under it; the call to action as a+// stamp on the right, sitting on the venue's baseline; a hairline; a sponsor band along the foot,+// its label large enough not to be swallowed (38 px, weight 800 at 1080) and each sponsor switchable.+// Variants for 16x9, 1x1, 4x5 and 9x16 come from the frame's own shape (on 9:16 everything stays out of+// the platforms' bands and the right button column). The card reports itself to the frame probe as+// "end card", so framecheck fails a film whose card lands twice (card, stinger, card).+// endCardLayout(W, H, spec, measure) pure: every rectangle and size, for tests and for the draw+// drawEndCard(ctx, env, spec, p) draws it; p 0..1 is the arrival (staggered rise, no fade)+import { probeRect, type Ctx, type Env } from "./core";++export type Rect = { x: number; y: number; w: number; h: number };+export type Sponsor = { name: string; aspect: number; on?: boolean; draw: (ctx: Ctx, box: Rect) => void };+export type EndCardSpec = {+ // the exact brand lockup (brand import), drawn into its box; descent: how far its drawing hangs below+ // the box, as a share of the box's height (a name set on the box's foot as its baseline: its descenders)+ lockup: { aspect: number; draw: (ctx: Ctx, box: Rect) => void; descent?: number };+ date: string; venue: string;+ cta: string;+ sponsors?: { label?: string; list: Sponsor[] };+ colors: { ink: string; accent: string; ctaInk: string; hair?: string };+ font?: (weight: number, px: number) => string;+ // where a wide card's stamp sits on the venue's baseline: "edge", at the right margin (the approved card,+ // over its sponsor band), or "inline", one gap after the text block (a card with no band, where a stamp+ // at the edge floats far from everything it belongs to)+ stamp?: "edge" | "inline";+};+const FONT = (w: number, px: number) => `${w} ${px}px "Avenir Next", "Helvetica Neue", Helvetica, Arial, sans-serif`;+export type Measure = (text: string, font: string) => number;+export type EndCardLayout = { margin: number; lockup: Rect; date: Rect & { px: number }; venue: Rect & { px: number }; cta: Rect & { px: number }; hairY: number; label: Rect & { px: number } | null; logos: (Rect & { name: string })[]; shape: "wide" | "square" | "tall" };++/** Every rectangle of the card for a W x H frame. `measure` gives a text's width in a font (ctx.measureText in the draw). */+export const endCardLayout = (W: number, H: number, spec: EndCardSpec, measure: Measure): EndCardLayout => {+ const font = spec.font ?? FONT, u = Math.min(W, H) / 1080, shape = W / H > 1.2 ? "wide" : W / H < 0.7 ? "tall" : "square";+ const air = Math.ceil(0.035 * H); // the smallest gap between two parts: over framecheck's 3 % of the height+ const margin = shape === "wide" ? Math.round(W * 0.078) : Math.round(W * 0.09);+ const fit = (text: string, w: number, maxPx: number, minPx: number, weight: number) => { let px = maxPx; while (px > minPx && measure(text, font(weight, px)) > w) px -= 1; return px; };+ const top = shape === "tall" ? Math.round(H * 0.17) : margin; // 9:16: under the platforms' top band+ const textW = shape === "tall" ? Math.floor(W * 0.86) - margin - 8 : W - 2 * margin; // 9:16: lines end left of the platforms' right button column (14 %)+ const lockW = shape === "wide" ? W * 0.36 : W * (shape === "tall" ? 0.7 : 0.55), lockup = { x: margin, y: top, w: lockW, h: lockW / spec.lockup.aspect };+ const datePx = fit(spec.date, textW, Math.round(64 * u), Math.round(40 * u), 800), venuePx = fit(spec.venue, shape === "wide" ? W * 0.5 : textW, Math.round(44 * u), Math.round(32 * u), 600);+ const date = { x: margin, y: lockup.y + lockup.h * (1 + (spec.lockup.descent ?? 0)) + Math.max(Math.round(56 * u), air), w: measure(spec.date, font(800, datePx)), h: datePx, px: datePx };+ const venue = { x: margin, y: date.y + date.h + Math.round(18 * u), w: measure(spec.venue, font(600, venuePx)), h: venuePx, px: venuePx };+ const ctaPx = fit(spec.cta, shape === "wide" ? W * 0.3 : textW - 80 * u, Math.round(44 * u), Math.round(32 * u), 800), padX = Math.round(36 * u), padY = Math.round(22 * u);+ const ctaW = measure(spec.cta, font(800, ctaPx)) + 2 * padX, ctaH = ctaPx + 2 * padY;+ // the stamp sits on the venue's baseline, on the right (wide); under the event lines, still left-aligned, elsewhere: never centred+ const inlineX = margin + Math.max(date.w, venue.w) + Math.round(72 * u);+ const cta = shape === "wide" ? { x: spec.stamp === "inline" ? Math.min(inlineX, W - margin - ctaW) : W - margin - ctaW, y: venue.y + venue.h - ctaH + padY, w: ctaW, h: ctaH, px: ctaPx } : { x: margin, y: venue.y + venue.h + Math.round(48 * u), w: ctaW, h: ctaH, px: ctaPx };+ const on = (spec.sponsors?.list ?? []).filter((s) => s.on !== false);+ const bottom = shape === "tall" ? Math.round(H * 0.74) : H - margin; // 9:16: above the platforms' bottom band+ let label: EndCardLayout["label"] = null, logos: EndCardLayout["logos"] = [], hairY = bottom;+ if (on.length) {+ const labelPx = Math.round(38 * u), logoH = Math.round((shape === "wide" ? 0.062 : 0.05) * H * 1.3) /* v12: logos 1.3x after the designer's pass */, gap = Math.max(Math.round(56 * u), air), text = spec.sponsors?.label ?? "Sponsors";+ const perRow = shape === "wide" ? on.length : Math.min(on.length, 3), rows = Math.ceil(on.length / perRow), bandH = labelPx + air + rows * logoH + (rows - 1) * air;+ hairY = bottom - bandH - Math.round(36 * u);+ label = { x: margin, y: hairY + Math.round(36 * u), w: measure(text, font(800, labelPx)), h: labelPx, px: labelPx };+ const avail = W - 2 * margin, y0 = label.y + labelPx + air;+ for (let r = 0; r < rows; r++) {+ const row = on.slice(r * perRow, (r + 1) * perRow); let h = logoH, ws = row.map((s) => s.aspect * h), tot = ws.reduce((a, b) => a + b, 0) + gap * (row.length - 1);+ if (tot > avail) { const k = (avail - gap * (row.length - 1)) / (tot - gap * (row.length - 1)); h *= k; ws = ws.map((w) => w * k); }+ let x = margin; row.forEach((s, i) => { logos.push({ name: s.name, x, y: y0 + r * (logoH + air) + (logoH - h) / 2, w: ws[i], h }); x += ws[i] + gap; });+ }+ }+ return { margin, lockup, date, venue, cta, hairY, label, logos, shape };+};++/** Draw the end card; p 0..1 is its arrival (each part rises into place in turn, no fade). */+export const drawEndCard = (ctx: Ctx, env: Env, spec: EndCardSpec, p = 1) => {+ const font = spec.font ?? FONT, L = endCardLayout(env.W, env.H, spec, (t, f) => { ctx.font = f; return ctx.measureText(t).width; });+ const parts = 4 + (L.label ? 1 : 0), part = (i: number) => { const q = Math.max(0, Math.min(1, p * (1 + 0.25 * (parts - 1)) - 0.25 * i)); return 1 - Math.pow(1 - q, 3); };+ const rise = (i: number, r: Rect, draw: () => void) => { const e = part(i); if (e <= 0) return; ctx.save(); ctx.beginPath(); ctx.rect(r.x - 4, r.y - r.h * 0.3, r.w + 8, r.h * 1.6); ctx.clip(); ctx.translate(0, (1 - e) * r.h * 1.2); draw(); ctx.restore(); };+ if (p >= 1) probeRect(ctx, env, L.margin * 0.5, L.margin * 0.5, env.W - L.margin, env.H - L.margin, "end card");+ rise(0, L.lockup, () => spec.lockup.draw(ctx, L.lockup));+ ctx.textBaseline = "top"; ctx.textAlign = "left";+ rise(1, L.date, () => { ctx.fillStyle = spec.colors.ink; ctx.font = font(800, L.date.px); ctx.fillText(spec.date, L.date.x, L.date.y); });+ rise(2, L.venue, () => { ctx.fillStyle = spec.colors.ink; ctx.font = font(600, L.venue.px); ctx.fillText(spec.venue, L.venue.x, L.venue.y); });+ rise(3, L.cta, () => {+ const r = L.cta, rad = r.h * 0.22; ctx.fillStyle = spec.colors.accent; ctx.beginPath(); ctx.roundRect(r.x, r.y, r.w, r.h, rad); ctx.fill();+ ctx.fillStyle = spec.colors.ctaInk; ctx.font = font(800, r.px); ctx.textBaseline = "middle"; ctx.fillText(spec.cta, r.x + (r.w - ctx.measureText(spec.cta).width) / 2, r.y + r.h / 2); ctx.textBaseline = "top";+ });+ if (L.label) {+ const e = part(4); if (e > 0) { ctx.save(); ctx.strokeStyle = spec.colors.hair ?? spec.colors.ink; ctx.globalAlpha *= 0.35; ctx.lineWidth = Math.max(1, env.H / 1080); ctx.beginPath(); ctx.moveTo(L.margin, L.hairY); ctx.lineTo(L.margin + (env.W - 2 * L.margin) * e, L.hairY); ctx.stroke(); ctx.restore(); }+ rise(4, L.label, () => { ctx.fillStyle = spec.colors.ink; ctx.font = font(800, L.label!.px); ctx.fillText(spec.sponsors?.label ?? "Sponsors", L.label!.x, L.label!.y); });+ const on = (spec.sponsors?.list ?? []).filter((s) => s.on !== false);+ L.logos.forEach((b, i) => rise(4, b, () => { on[i].draw(ctx, b); probeRect(ctx, env, b.x, b.y, b.w, b.h, `sponsor:${b.name}`); }));+ }+ return L;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.tsindex 0e3f804..8c21478 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts@@ -34,6 +34,10 @@ export type Film = { meta: {captions?: { from: number; to: number; text: string }[];// a legible frame for the poster image and the thumbnail (render --poster-frame, launch.mjs ship)poster?: number;+ // what the film tells the ship checks about itself (shipMeta.ts: layout exemptions, length budget, brand fonts)+ checks?: import("./shipMeta").ShipMeta;+ // what the film tells the motion scans (motionMeta.ts: brand colours, temperament, approved shots, exceptions)+ motion?: import("./motionMeta").MotionMeta;}; assets: Assets; shots: Shot[]; audio?: FilmAudio;// the same film composed for another frame shape (launch template films); hosts/page.ts calls it for <film>-<shape>reshape?: (shape: string) => Film };diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kinetic.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kinetic.tsindex 21dedf0..612c6c1 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kinetic.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kinetic.ts@@ -14,9 +14,12 @@import { fractal, probeRect, rng, sample, type Ctx, type Env, type Layer, type P } from "./core";import { G, type Glyph } from "./drafting";import { DOT, TAIL, WORD, inkStroke, outlineOf, type Nib } from "./lettering";+import { typeExit } from "./motionKit";export type KStyle = "ink" | "crayon" | "thread" | "chalk" | "brick" | "marker";-export type WriteOpts = { color?: string; align?: "left" | "center" | "right"; slant?: number; track?: number; seed?: number; tool?: boolean; weight?: number; pop?: number };+// `out` 0..1 is a written line's exit, as setType's: the line sinks behind its own baseline on the same+// ease-in (motionKit.typeExit, 1.3x its size) and stops reporting itself to the frame probe while it leaves+export type WriteOpts = { color?: string; align?: "left" | "center" | "right"; slant?: number; track?: number; seed?: number; tool?: boolean; weight?: number; pop?: number; out?: number };const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));const lerp = (a: number, b: number, t: number) => a + (b - a) * t;@@ -89,6 +92,17 @@ const layout = (env: Env, text: string, x: number, y: number, size: number, o: Wconst total = strokes.reduce((a, k2) => a + k2.L + GAP, 0);const L: Layout = { strokes, boxes, W, total }; env.cache.set(key, L); return L;};+/** Where a line written in the ink style starts and ends, in px from its left-aligned origin: [left, right]. measure()+ * is the advance width, which starts at the first letter's origin, not its first stroke, so a line centred+ * by measure() sits a side bearing off its axis (the end card's name, a fresh critic's d4-1). */+export const inkSpan = (text: string, size: number, o: WriteOpts = {}): [number, number] => {+ const lay = layout({ cache: new Map() } as unknown as Env, text, 0, size, size, { ...o, align: "left" });+ // (the strokes are the nib's centre line; the ink style's nib is up to 0.115 of the size wide, so its edge+ // reaches half that past them: drawInk's `sh`)+ const pen = size * (o.weight ?? 1) * 0.115 / 2;+ let lo = Infinity, hi = -Infinity; for (const k of lay.strokes) for (const [x] of k.pts) { lo = Math.min(lo, x); hi = Math.max(hi, x); }+ return lo <= hi ? [lo - pen, hi + pen] : [0, lay.W];+};// how much of each stroke is laid at progress p (a constant-speed hand, pen lifts between)const reach = (lay: Layout, p: number) => { let d = clamp(p) * lay.total; return lay.strokes.map((k) => { const u = clamp(d / k.L); d -= k.L + GAP; return u; }); };const cut = (k: KStroke, u: number): P[] => { if (u >= 1) return k.pts; const want = u * k.L, out: P[] = [k.pts[0]]; for (let i = 1; i < k.pts.length; i++) { if (k.len[i] <= want) out.push(k.pts[i]); else { const f = (want - k.len[i - 1]) / (k.len[i] - k.len[i - 1] || 1); out.push([k.pts[i - 1][0] + (k.pts[i][0] - k.pts[i - 1][0]) * f, k.pts[i - 1][1] + (k.pts[i][1] - k.pts[i - 1][1]) * f]); break; } } return out.length > 1 ? out : [k.pts[0], k.pts[0]]; };@@ -291,19 +305,25 @@ const drawBricks = (c: Ctx, env: Env, lay: Layout, p: number, size: number, key:// ---------------------------------------------------------------- writeOnexport const writeOn = (ctx: Ctx, env: Env, text: string, x: number, y: number, size: number, p: number, style: KStyle, o: WriteOpts = {}) => {- if (p <= 0) return;+ const out = Math.max(0, Math.min(1, o.out ?? 0));+ if (p <= 0 || out >= 1) return;screen(ctx, env);if (style === "brick" && o.track === undefined) o = { ...o, track: 2.6, slant: o.slant ?? 0 };- const lay = layout(env, text, x, y, size, o), us = reach(lay, p), color = o.color ?? PALETTE[style], popK = o.pop ?? 1, seed = o.seed ?? 1;- if (env.root && lay.boxes.length) { const bx = lay.boxes; probeRect(ctx, env, Math.min(...bx.map((b) => b.c[0] - b.w / 2)), y - size * 1.05, Math.max(...bx.map((b) => b.c[0] + b.w / 2)) - Math.min(...bx.map((b) => b.c[0] - b.w / 2)), size * 1.3, text, "text"); }+ // a leaving line is laid out lower by its sink and drawn inside its own window (cap height plus the+ // ink's reach under the baseline), so every style, textured ones included, sinks out of it the same way+ const sink = out > 0 ? typeExit(out) * size * 1.4 : 0;+ const lay = layout(env, text, x, y + sink, size, o), us = reach(lay, p), color = o.color ?? PALETTE[style], popK = o.pop ?? 1, seed = o.seed ?? 1;+ if (out > 0) { const xs = lay.boxes.map((b) => b.c[0]), x0 = Math.min(...xs) - size, x1 = Math.max(...xs) + size; ctx.save(); ctx.beginPath(); ctx.rect(x0, y - size * 1.15, x1 - x0, size * 1.4); ctx.clip(); }+ if (out <= 0 && env.root && lay.boxes.length) { const bx = lay.boxes; probeRect(ctx, env, Math.min(...bx.map((b) => b.c[0] - b.w / 2)), y - size * 1.05, Math.max(...bx.map((b) => b.c[0] + b.w / 2)) - Math.min(...bx.map((b) => b.c[0] - b.w / 2)), size * 1.3, text, "text"); }ctx.save();if (style === "ink") drawInk(ctx, lay, us, size * (o.weight ?? 1), color, p, popK);else if (style === "marker") drawMarker(ctx, lay, us, size * (o.weight ?? 1), color, p, popK);else if (style === "crayon") textured(ctx, env, "crayon", waxHoles(env), 1, (c) => drawCrayon(c, lay, us, size * (o.weight ?? 1), color, p, popK, seed));else if (style === "chalk") textured(ctx, env, "chalk", chalkHoles(env), 1, (c) => drawChalk(c, lay, us, size * (o.weight ?? 1), color, p, popK, seed));else if (style === "thread") drawThread(ctx, lay, us, size * (o.weight ?? 1), color, p, popK);- else if (style === "brick") drawBricks(ctx, env, lay, p, size, `${text}|${x}|${y}|${size}|${o.seed}|${o.align}|${o.track}`, o.color);+ else if (style === "brick") drawBricks(ctx, env, lay, p, size, `${text}|${x}|${y + sink}|${size}|${o.seed}|${o.align}|${o.track}`, o.color);ctx.restore();+ if (out > 0) { ctx.restore(); return; } // the line's window; a leaving line has no tool// the tool, while the hand is still writingif (o.tool === false || p >= 1 || style === "brick") return;const tp = tipOf(lay, us); if (!tp) return;@@ -422,13 +442,21 @@ export const caption = (ctx: Ctx, env: Env, text: string, x: number, y: number,// Type as the design: a line SET in a heavy sans, not written. Each word rises into place from// behind its own baseline (a mask the size of the line), one after another, on an out-cubic: a// gentle move with no bounce and no fade-in. `p` 0..1 is the line's progress. Screen space.-export type SetOpts = { color?: string; align?: "left" | "center" | "right"; weight?: number; font?: (w: number, px: number) => string; track?: number };+// `out` 0..1 is its exit: the words sink back behind the baseline, last word first, on an EASE-IN over+// 1.3x the size (motionKit.typeExit), so they accelerate away and clear the clip whole. The ease-out,+// 1.0x exit left letter tops at the clip edge for half a second on a brand launch film.+// `space: "world"` draws in the CURRENT transform (inside a camera, a world region) instead of+// resetting to the screen: x, y and size are then world units.+export type SetOpts = { color?: string; align?: "left" | "center" | "right"; weight?: number; font?: (w: number, px: number) => string; track?: number; out?: number; space?: "screen" | "world" };const SET_FONT = (w: number, px: number) => `${w} ${px}px "Avenir Next", "Helvetica Neue", Helvetica, Arial, sans-serif`;export const setWidth = (ctx: Ctx, text: string, size: number, o: SetOpts = {}) => { ctx.font = (o.font ?? SET_FONT)(o.weight ?? 700, size); return ctx.measureText(text).width + Math.max(0, text.length - 1) * (o.track ?? -0.02) * size; };export const setType = (ctx: Ctx, env: Env, text: string, x: number, y: number, size: number, p: number, o: SetOpts = {}) => {- if (p <= 0) return;- screen(ctx, env);- { const w = setWidth(ctx, text, size, o), x0 = o.align === "center" ? x - w / 2 : o.align === "right" ? x - w : x; probeRect(ctx, env, x0, y - size * 0.8, w, size, text, "text"); }+ const out = Math.max(0, Math.min(1, o.out ?? 0));+ if (p <= 0 || out >= 1) return;+ if (o.space !== "world") screen(ctx, env);+ // a standing line reports its box to the frame probe; a line on its way out does not, because its+ // glyphs speak for what is still showing (the whole-line box let a one-frame "read" through on the exit)+ if (out <= 0) { const w = setWidth(ctx, text, size, o), x0 = o.align === "center" ? x - w / 2 : o.align === "right" ? x - w : x; probeRect(ctx, env, x0, y - size * 0.8, w, size, text, "text"); }ctx.save();ctx.font = (o.font ?? SET_FONT)(o.weight ?? 700, size); ctx.textBaseline = "alphabetic"; ctx.fillStyle = o.color ?? "#111214";const tr = (o.track ?? -0.02) * size, words = text.split(" "), space = ctx.measureText(" ").width;@@ -437,7 +465,8 @@ export const setType = (ctx: Ctx, env: Env, text: string, x: number, y: number,ctx.beginPath(); ctx.rect(cx - size, y - size * 1.05, total + 2 * size, size * 1.35); ctx.clip(); // the line's own window: words rise into itwords.forEach((w, i) => {const q = Math.max(0, Math.min(1, p * (1 + 0.35 * (words.length - 1)) - 0.35 * i)), e = 1 - Math.pow(1 - q, 3);- if (q > 0) { const dy = (1 - e) * size * 0.9; let wx = cx; for (const ch of w) { ctx.fillText(ch, wx, y + dy); wx += ctx.measureText(ch).width + tr; } }+ const qo = Math.max(0, Math.min(1, out * (1 + 0.3 * (words.length - 1)) - 0.3 * (words.length - 1 - i))), sink = typeExit(qo) * size; // last word leaves first+ if (q > 0 && qo < 1) { const dy = (1 - e) * size * 0.9 + sink; let wx = cx; for (const ch of w) { ctx.fillText(ch, wx, y + dy); wx += ctx.measureText(ch).width + tr; } }cx += wOf(w) + space;});ctx.restore();diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kineticDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kineticDemo.tsindex 68abe1e..eac87ab 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kineticDemo.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/kineticDemo.ts@@ -10,10 +10,14 @@ const W = 1920, H = 1080, PAPER = "#f4efe6";const ground = (ctx: Ctx, env: Env) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAPER; ctx.fillRect(0, 0, W, H); };const ease = (t: number) => { const c = Math.max(0, Math.min(1, t)); return c * c * (3 - 2 * c); };const bug = (ctx: Ctx, env: Env, f: number) => logoBug(ctx, env, f, 1640, 1030, 1, { t0: 40 });+// a slow, constant push-in about the frame centre, drawn as vector (positions and sizes scale, no raster+// resample): once a shot's words are down the camera keeps leaning in, so the frame never goes still.+// The corner bug is screen furniture and stays put.+const push = (f: number, len: number, amt: number) => { const z = 1 + (amt * f) / len; return { z, x: (x: number) => W / 2 + (x - W / 2) * z, y: (y: number) => H / 2 + (y - H / 2) * z }; };const opening = (ctx: Ctx, f: number, env: Env) => {ground(ctx, env);- logoCentred(ctx, env, W / 2, H / 2, 150, ease(f / 44));+ logoCentred(ctx, env, W / 2, H / 2, 150 * push(f, 60, 0.04).z, ease(f / 44));bug(ctx, env, f);};// two rows of three, each row laid out by measured width and centred@@ -21,15 +25,17 @@ const SZ = 100, ROWS: [string, KStyle][][] = [[["INK", "ink"], ["CRAYON", "crayoconst WORDS: [string, KStyle, number, number][] = ROWS.flatMap((row, r) => { const gap = 90, tot = row.reduce((a, [t]) => a + measure(t, SZ), 0) + gap * (row.length - 1); let x = W / 2 - tot / 2; return row.map(([t, st]) => { const o: [string, KStyle, number, number] = [t, st, x, r ? 700 : 360]; x += measure(t, SZ, st === "brick" ? { track: 2.6, slant: 0 } : {}) + gap; return o; }); });const styles = (ctx: Ctx, f: number, env: Env) => {ground(ctx, env);- const [, , cx, cy] = WORDS[3], cw = measure("CHALK", SZ); // the chalkboard behind the chalk word- ctx.fillStyle = "#2c3a33"; ctx.fillRect(cx - 50, cy - SZ - 55, cw + 100, SZ + 110); ctx.strokeStyle = "#6b4a2b"; ctx.lineWidth = 14; ctx.strokeRect(cx - 50, cy - SZ - 55, cw + 100, SZ + 110);- WORDS.forEach(([t, st, x, y], i) => writeOn(ctx, env, t, x, y, SZ, ease((f - i * 10) / 38), st, { seed: 3 + i }));- caption(ctx, env, "drawn live, no fonts", W / 2 + 180, 960, 40, ease((f - 60) / 30), "arrow", { to: [WORDS[5][2] + 60, 790] });+ const P = push(f, 100, 0.02), z = P.z, sz = SZ * z, [, , cx, cy] = WORDS[3], cw = measure("CHALK", sz); // the chalkboard behind the chalk word+ const bx = P.x(cx - 50), by = P.y(cy - SZ - 55);+ ctx.fillStyle = "#2c3a33"; ctx.fillRect(bx, by, cw + 100 * z, sz + 110 * z); ctx.strokeStyle = "#6b4a2b"; ctx.lineWidth = 14 * z; ctx.strokeRect(bx, by, cw + 100 * z, sz + 110 * z);+ WORDS.forEach(([t, st, x, y], i) => writeOn(ctx, env, t, P.x(x), P.y(y), sz, ease((f - i * 10) / 38), st, { seed: 3 + i }));+ caption(ctx, env, "drawn live, no fonts", P.x(W / 2 + 180), P.y(960), 40 * z, ease((f - 60) / 30), "arrow", { to: [P.x(WORDS[5][2] + 60), P.y(790)] });bug(ctx, env, f + 60);};const finale = (ctx: Ctx, f: number, env: Env) => {ground(ctx, env);- sentence(ctx, env, ["Images", "Illustrations", "Loops", "Animations", "Films"], f, 0, { beat: 14 });+ const P = push(f, 120, 0.03);+ sentence(ctx, env, ["Images", "Illustrations", "Loops", "Animations", "Films"], f, 0, { beat: 14, size: 74 * P.z, claimSize: 118 * P.z, top: P.y(H * 0.3) });bug(ctx, env, f + 160);};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCut.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCut.tsindex 9576c66..e4fc04c 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCut.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCut.ts@@ -55,18 +55,19 @@ export type BloomOpts = { inF?: number; outF?: number; close?: boolean; radius?:// where the bloom opens from (default the frame's centre): a match cut opens it from the motif (motif.ts)center?: P;// "circle": a clean round iris instead of the ink blot (the clean preset); rim: the ink edge's width (default 26)- shape?: "blot" | "circle"; rim?: number };+ shape?: "blot" | "circle"; rim?: number;+ // the opening's ease, 0..1 over inF + 2 frames (default expo: shut, then most of the frame in four frames)+ ease?: (t: number) => number };// A full-frame page inside an ink bloom. `under` draws the picture the bloom opens over (and closes// onto); `page` draws the page, in screen coordinates, on an offscreen sheet. With close: false the// bloom stays open (an end card).// the bloom's radius at a local frame: a page is fully covered while it is 1110 or more (1920x1080)export const bloomRadius = (local: number, len: number, o: BloomOpts = {}) => {- const IN = o.inF ?? 14, OUT = o.outF ?? 14, u = expo(ramp(local, 0, IN + 2)), v = o.close === false ? 0 : expo(ramp(local, len - OUT, len));+ const IN = o.inF ?? 14, OUT = o.outF ?? 14, u = (o.ease ?? expo)(ramp(local, 0, IN + 2)), v = o.close === false ? 0 : expo(ramp(local, len - OUT, len));return (o.radius ?? 1250) * (v > 0 ? 1 - v : u);};export const bloomFrame = (ctx: Ctx, env: Env, local: number, len: number, under: (first: boolean) => void, page: (c: Ctx) => void, o: BloomOpts = {}) => {- const IN = o.inF ?? 14, OUT = o.outF ?? 14, W = o.W ?? 1920, H = o.H ?? 1080;- const u = expo(ramp(local, 0, IN + 2)), v = o.close === false ? 0 : expo(ramp(local, len - OUT, len)), R = (o.radius ?? 1250) * (v > 0 ? 1 - v : u);+ const W = o.W ?? 1920, H = o.H ?? 1080, R = bloomRadius(local, len, o);under(local < len / 2);if (R < 2) return;const L = selfLayer(env, "sheet", Math.round(W * env.scale), Math.round(H * env.scale)), c = L.ctx;diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExample.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExample.tsindex 8921124..0990cdb 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExample.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExample.ts@@ -1,15 +1,15 @@-// LAUNCH EXAMPLE. A 16-second launch film for a made-up product, built only from the template: two-// prompts answered by two plates drawing themselves, one type frame, the end card on bar 4.-// Copying it: everything here is a PLACEHOLDER. The lighthouse and fox are stock style plates-// standing in; your film's plates are drawn fresh for YOUR product's subject, in the style recipe-// the brief chose (references/styles.md). The film is silent because a score is composed per-// product (references/music/compose.md); pass that piece as `score`. bpm comes from the brief.-// node tools/still.mjs launchExample --frame 0 the first frame is the thumbnail: check it-// node tools/render.mjs launchExample+// LAUNCH EXAMPLE. A launch film for a made-up product, built only from the template (preset "drawn", the+// default): two prompts answered by two plates drawing themselves, one word page, the end card on bar 5.+// Copying it: everything here is a PLACEHOLDER. The lighthouse and fox are stock style plates standing in;+// your film's plates are drawn fresh for YOUR product's subject, in the style recipe the brief chose+// (references/styles.md). Its score is composed for this made-up product (launchExampleScore.ts); a real+// film composes its own (references/music/compose.md). bpm comes from the brief.+// node tools/launch.mjs ship launchExample --shapes 16x9,9x16import { C } from "./launchKit";import { makeLaunchFilm } from "./launchTemplate";import { lighthouseDraw } from "./lighthouseDraw";import { foxDraw } from "./foxDraw";+import { sketchScore } from "./launchExampleScore";export const launchExample = makeLaunchFilm({title: "Your Product",@@ -23,6 +23,31 @@ export const launchExample = makeLaunchFilm({tagline: "One sentence that says what it is",install: ["npm install your-product", "your-product init"],footer: "yourproduct.example",- bpm: 90, askBeats: 6, typeBeats: 4, endBeats: 8, claimBar: 4,- score: null, // silent: compose this product's own score and pass it here+ // THE DECLARATIONS ship reads (node tools/ship.mjs). A check with nothing declared cannot look, and a+ // check that cannot look fails, so every film fills these from its brief. This example's are filled for+ // its made-up product, as a worked example: replace each with your own.+ motion: {+ // how the brand moves, from the brief: "calm", "lively" or "snappy" (motionKit.ts TEMPERAMENTS). A warm+ // drawing tool: alive, never violent. The end card's bloom is paced by it too.+ temperament: "lively",+ // the brand's own colours, #rrggbb: layerscan fails a fill in them at a see-through alpha (olive mud).+ // This made-up product owns its orange; the near-black ink is the drawn look's pen, the neutral every+ // line is written in (a drop's trail of ink ghosts, a byline easing in), so it is not listed here.+ // A brand whose colour IS a dark ink lists it, and the drawn look's ghosts then fail, as they should.+ brandColors: [C.accent],+ },+ // every claim beyond the words and the tagline (which are claims already), each listed in the facts+ // ledger with its source (facts/launchExample.json here; facts.json beside your project). The plates'+ // labels are bylines of placeholder art and claim nothing; a real product's real numbers ARE claims.+ claims: [],+ checks: {+ // the length budget in seconds: over max fails ship, over target flags it+ length: { target: 19, max: 22 },+ // the critic's record is reviews/launchExample.json: this example's own, written by a fresh critic for+ // anidoodle, never a person's review of your film. Your film gets its own (review.md).+ },+ bpm: 90, askBeats: 6, typeBeats: 6, endBeats: 8, claimBar: 5,+ // the example's own score, composed for this made-up product's brief (launchExampleScore.ts); a real+ // film composes its own product's score (references/music/compose.md), never this one+ score: sketchScore,});diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleBrand.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleBrand.tsnew file mode 100644index 0000000..635f91d--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleBrand.ts@@ -0,0 +1,110 @@+// LAUNCH EXAMPLE, A BRAND'S OWN LOOK. The template dressed as somebody else's product, to prove a launch film+// can look like YOUR product and still pass ship: "Lantern", an INVENTED reading desk (no real company), on+// a dark ground, its own serif display face (Lora Bold) and text face (Instrument Sans Bold), square+// bubbles, a square composer, its own logo (assets/brand/lantern/lanternMark.svg, drawn for it and imported with+// `node tools/brand.mjs import`), a chat ask and a product ask:+// 1 a chat ask: the question typed as the hook, Ask pressed, the answer opening as an iris on a map of+// sources drawing itself (the two that disagree lit in the accent, a clash mark between them);+// 2 a word page;+// 3 the product's own library from data, its words beside it.+// Everything here is a PLACEHOLDER for a made-up product; your film's look comes from YOUR product (its+// brand.json, its fonts, its colours), its answer plate is drawn for it and its score composed for its brief.+// node tools/launch.mjs ship launchExampleBrand --shapes 16x9,9x16+import type { Film } from "./film";+import { makeLaunchFilm } from "./launchTemplate";+import type { ProductUI } from "./productUI";+import { tallyScore } from "./launchExampleCleanScore";+import lora from "../../assets/fonts/Lora-Bold.ttf";+import instrument from "../../assets/fonts/InstrumentSans-Bold.ttf";+import lanternBrand from "../../assets/brand/lantern/brand.json";++// the brand's colours, as its own design file would name them (a dark reading desk, one lamp-light accent)+// (the window a clear step lighter than the ground and the answer's ground lighter again: on a dark page a+// window one shade off its ground changed too few pixels as the room crept, and read as a freeze to the gate)+const LANTERN = { bg: "#0f1113", card: "#1f2228", ink: "#f3ede0", soft: "#b8b0a2", mute: "#8f897e", line: "#3a3f48", chip: "#30343c", accent: "#f2b544", accentDeep: "#c98f22", paper: "#272b32" };++// the answer: six sources laid out as pages, each drawing itself (a page, its heading bar, its lines), joined+// where they cite each other; then the two that DISAGREE light up in the lamp's amber, joined by a bold+// amber line with a clash mark on it. No words inside: the card's byline says what it is.+const PAGES: [number, number][] = [[200, 230], [560, 170], [840, 260], [260, 640], [610, 560], [860, 760]];+const LINKS: [number, number][] = [[0, 1], [1, 2], [0, 3], [3, 4], [1, 4], [4, 5], [2, 5]];+const PW = 190, PH = 230, CLASH: [number, number] = [1, 3];+const sources: Film = {+ meta: { title: "Lantern answer: which sources disagree", W: 1080, H: 1080, fps: 30, bpm: 90, durationFrames: 150 },+ assets: { images: {} },+ shots: [{ id: "map", start: 0, end: 150, draw: (ctx, f, env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ // (a ground a step off the card's, so the iris that opens onto it is seen)+ ctx.fillStyle = "#353a43"; ctx.fillRect(0, 0, 1080, 1080);+ const q = (t0: number, len: number) => { const u = Math.min(1, Math.max(0, (f - t0) / len)); return 1 - (1 - u) ** 3; };+ const ctr = (i: number): [number, number] => [PAGES[i][0] + PW / 2, PAGES[i][1] + PH / 2];+ // the links first, under the pages+ ctx.lineWidth = 7; ctx.strokeStyle = "#5a6070"; ctx.lineCap = "round";+ LINKS.forEach(([a, b], i) => { const e = q(16 + i * 6, 18); if (e <= 0) return; const [x0, y0] = ctr(a), [x1, y1] = ctr(b); ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + (x1 - x0) * e, y0 + (y1 - y0) * e); ctx.stroke(); });+ const hot = q(78, 18); // the two that disagree light up+ PAGES.forEach(([x, y], i) => {+ const e = q(4 + i * 6, 16); if (e <= 0) return;+ const h = PH * e, lit = CLASH.includes(i) ? hot : 0;+ ctx.fillStyle = "#f3ede0"; ctx.fillRect(x, y + PH - h, PW, h);+ if (lit > 0) { ctx.lineWidth = 12; ctx.strokeStyle = "#f2b544"; ctx.strokeRect(x - 10 * lit, y + PH - h - 10 * lit, PW + 20 * lit, h + 20 * lit); }+ // the page's heading bar and its lines, written as the page rises+ ctx.fillStyle = lit > 0.5 ? "#c98f22" : "#4a505c"; if (e > 0.6) ctx.fillRect(x + 22, y + 26, (PW - 70) * q(10 + i * 6, 14), 22);+ ctx.fillStyle = "#9aa0ab"; for (let r = 0; r < 5; r++) { const w = q(14 + i * 6 + r * 2, 12); if (w > 0) ctx.fillRect(x + 22, y + 72 + r * 30, (PW - 44 - (r % 2) * 40) * w, 12); }+ });+ // the clash: a bold amber line between the two, and a mark where it crosses+ if (hot > 0) {+ const [x0, y0] = ctr(CLASH[0]), [x1, y1] = ctr(CLASH[1]), e = q(88, 16), mx = (x0 + x1) / 2, my = (y0 + y1) / 2;+ ctx.strokeStyle = "#f2b544"; ctx.lineWidth = 14; ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + (x1 - x0) * e, y0 + (y1 - y0) * e); ctx.stroke();+ const b = q(100, 14); if (b > 0) { ctx.fillStyle = "#f2b544"; ctx.beginPath(); ctx.arc(mx, my, 46 * b, 0, Math.PI * 2); ctx.fill(); ctx.strokeStyle = "#0f1113"; ctx.lineWidth = 10; ctx.beginPath(); ctx.moveTo(mx - 20 * b, my - 20 * b); ctx.lineTo(mx + 20 * b, my + 20 * b); ctx.moveTo(mx + 20 * b, my - 20 * b); ctx.lineTo(mx - 20 * b, my + 20 * b); ctx.stroke(); }+ }+ } }],+};++const library: ProductUI = {+ title: "Lantern", nav: ["Library", "Notes", "Map"], action: "Check all",+ // (rows keep their places and gain their tag as they are checked: no crossing rows)+ before: { items: [+ { id: "a", label: "Field notes, 2019", value: "12 p." },+ { id: "b", label: "Survey, spring", value: "40 p." },+ { id: "c", label: "Interview, May", value: "8 p." },+ ] },+ after: { items: [+ { id: "a", label: "Field notes, 2019", value: "12 p.", tag: "cited", done: true, accent: true },+ { id: "b", label: "Survey, spring", value: "40 p.", tag: "cited", done: true },+ { id: "c", label: "Interview, May", value: "8 p.", tag: "cited", done: true },+ ] },+};++export const launchExampleBrand = makeLaunchFilm({+ title: "Lantern", subtitle: "your reading desk", placeholder: "Ask Lantern…", fps: 60,+ // THE LOOK: the brand's own, field by field (launch-video-kit.md, Looks). `from` fills the palette and the+ // logo from the brand file; the explicit palette wins over it; the fonts are the brand's files.+ look: {+ base: "clean",+ from: lanternBrand,+ palette: LANTERN,+ fonts: { display: { family: "Lora", file: lora }, text: { family: "Instrument Sans", file: instrument } },+ shape: { radius: 14, bubble: "square", composer: "box", button: "square", buttonLabel: "Ask" },+ chat: { title: "Lantern", subtitle: "your reading desk", bubble: { fill: "#353a43", ink: "#f3ede0" }, reply: { fill: "#272b32", ink: "#f3ede0" } },+ },+ asks: [+ { prompt: "which sources disagree?", plate: sources, label: "Your sources, mapped" },+ { kind: "ui", ui: library, split: [{ text: "Then it cites", style: "ink", color: LANTERN.ink }, { text: "every page.", style: "ink", color: LANTERN.accent }] },+ ],+ words: [[{ text: "READ LESS.", style: "ink", color: LANTERN.ink }, { text: "KNOW MORE.", style: "ink", color: LANTERN.accent }]],+ tagline: "A reading desk that keeps your sources straight",+ install: ["npm install lantern"],+ footer: "lantern.example",+ // THE DECLARATIONS ship reads (node tools/ship.mjs), filled for this made-up product as a worked example+ motion: { temperament: "lively", brandColors: [LANTERN.accent, LANTERN.ink] },+ claims: [],+ checks: {+ length: { target: 22, max: 25 },+ // the split beat IS the product's own library beside its two words: its rows are what the viewer came to see+ layoutExempt: [[560, 960, "the library beat: the product's own rows beside its two words"]],+ // the critic's record is reviews/launchExampleBrand.json, this example's own+ },+ bpm: 90, askBeats: 8, typeBeats: 6, endBeats: 8, claimBar: 6,+ // the clean example's score (a made-up product and brief); a real film composes its own+ score: tallyScore,+});diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleClean.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleClean.tsindex 116e98e..b0fb2cb 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleClean.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleClean.ts@@ -10,6 +10,7 @@// node tools/launch.mjs ship launchExampleClean --shapes 16x9,9x16import { makeLaunchFilm } from "./launchTemplate";import type { ProductUI } from "./productUI";+import { tallyScore } from "./launchExampleCleanScore";const inbox: ProductUI = {title: "Tally", nav: ["Inbox", "Books", "Reports"], action: "Match all", command: "Ask Tally…",@@ -18,8 +19,8 @@ const inbox: ProductUI = {items: [{ id: "a", label: "Design tool, Sep", value: "$144", tag: "no receipt" },{ id: "b", label: "Cloud hosting, Sep", value: "$1,208", tag: "no receipt" },- { id: "c", label: "Team lunch, Thu", value: "$86", tag: "no receipt" },- { id: "d", label: "Train to Leeds", value: "$42", tag: "no receipt" },+ { id: "c", label: "Team lunch, Sep", value: "$86", tag: "no receipt" },+ { id: "d", label: "Train fare, Sep", value: "$42", tag: "no receipt" },],},after: {@@ -27,8 +28,8 @@ const inbox: ProductUI = {items: [{ id: "b", label: "Cloud hosting, Sep", value: "$1,208", tag: "matched", done: true, accent: true },{ id: "a", label: "Design tool, Sep", value: "$144", tag: "matched", done: true },- { id: "c", label: "Team lunch, Thu", value: "$86", tag: "matched", done: true },- { id: "d", label: "Train to Leeds", value: "$42", tag: "matched", done: true },+ { id: "c", label: "Team lunch, Sep", value: "$86", tag: "matched", done: true },+ { id: "d", label: "Train fare, Sep", value: "$42", tag: "matched", done: true },],},};@@ -60,13 +61,47 @@ export const launchExampleClean = makeLaunchFilm({title: "Tally", preset: "clean", fps: 60,asks: [{ kind: "ui", ui: inbox, prompt: "match every receipt from September" },- { kind: "ui", ui: books, split: [{ text: "Books close", style: "ink", color: "#15161a" }, { text: "themselves.", style: "ink", color: "#2f54eb" }] },+ { kind: "ui", ui: books, split: [{ text: "Month end,", style: "ink", color: "#15161a" }, { text: "one click.", style: "ink", color: "#2f54eb" }] }, // the words say what the picture shows: one press closes the month{ kind: "ui", ui: reports, split: [{ text: "And it shows", style: "ink", color: "#15161a" }, { text: "you where.", style: "ink", color: "#2f54eb" }] },],words: [[{ text: "ASK ONCE.", style: "ink", color: "#15161a" }, { text: "DONE.", style: "ink", color: "#2f54eb" }]],tagline: "Bookkeeping that does itself",install: ["npm install tally", "tally init"],footer: "tally.example",- bpm: 90, askBeats: 6, typeBeats: 4, endBeats: 8, claimBar: 6,- score: null, // silent here: compose this product's own score and pass it+ // the end card on endCard.ts's asymmetric grid: the name top-left with the drop as its full stop,+ // the line and the install line under it, the footer as a stamp on the right (never a centred stack)+ endCard: "grid",+ // THE DECLARATIONS ship reads (node tools/ship.mjs). A check with nothing declared cannot look, and a+ // check that cannot look fails, so every film fills these from its brief. This example's are filled+ // for its made-up product, as a worked example: replace each with your own.+ motion: {+ // how the brand moves, from the brief: "calm", "lively" or "snappy" (motionKit.ts TEMPERAMENTS).+ // A UI product with quick arrivals; motionscan fails any stretch faster than this allows.+ temperament: "snappy",+ // the brand's own colours, #rrggbb: layerscan fails a fill in them at a see-through alpha (olive mud)+ brandColors: ["#2f54eb", "#15161a"],+ },+ // every claim beyond the words, split words and tagline (which are claims already), each listed in the+ // facts ledger with its source (facts/launchExampleClean.json here; facts.json beside your project).+ // The UI's figures are made-up sample data in a mock screen and claim nothing; a real product's real+ // numbers on screen ARE claims: list each one here with its source.+ claims: [],+ checks: {+ // the length budget in seconds: over max fails ship, over target flags it+ length: { target: 22, max: 25 },+ // each ask IS the product's own screen: its title, nav, command bar, stats and rows are the UI the+ // viewer came to see, so their density is the point, not a layout fault. Only those beats (60 fps+ // frames, the travels into and out of them included); the word page and the end card are still judged.+ layoutExempt: [+ [0, 330, "the first ask shows the product's whole inbox: dense UI is the subject"],+ [440, 680, "the books beat: the product's own cards beside its two words"],+ [680, 960, "the reports beat: the product's own report rows beside its two words"],+ ],+ // the critic's record is reviews/launchExampleClean.json: this example's own, written by a fresh+ // critic for anidoodle, never a person's review of your film. Your film gets its own (review.md).+ },+ bpm: 90, askBeats: 6, typeBeats: 6, endBeats: 8, claimBar: 6,+ // the example's own score, composed for this made-up product's brief (launchExampleCleanScore.ts);+ // a real film composes its own product's score (references/music/compose.md), never this one+ score: tallyScore,});diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleCleanChat.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleCleanChat.tsnew file mode 100644index 0000000..33f1e90--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleCleanChat.ts@@ -0,0 +1,83 @@+// LAUNCH EXAMPLE, CLEAN, WITH A CHAT ASK. The clean look (preset "clean": a quiet canvas, one accent,+// type as the design) on a product people ask in a chat, at 60 fps:+// 1 a chat ask: the question typed as the hook, Generate pressed, and the answer card opening as an+// iris on a chart drawing itself (the answer is any film of this engine, here a small bar chart);+// 2 a word page;+// 3 the product's own screen from data, with its words beside it.+// Everything here is a PLACEHOLDER for a made-up product; your film's answer is drawn for YOUR product,+// its UI data comes from its real screens, and its score is composed for its brief.+// node tools/launch.mjs ship launchExampleCleanChat --shapes 16x9,9x16+import type { Film } from "./film";+import { CLEAN, makeLaunchFilm } from "./launchTemplate";+import type { ProductUI } from "./productUI";+import { tallyScore } from "./launchExampleCleanScore";++// the answer: four months of a spend line as bars, rising one after another, the last in the accent.+// No words inside it: the card's byline says what it is, at a size the frame checks can read.+const BARS = [0.42, 0.47, 0.45, 0.78];+const chart: Film = {+ meta: { title: "Tally answer: hosting by month", W: 1080, H: 1080, fps: 30, bpm: 90, durationFrames: 150 },+ assets: { images: {} },+ shots: [{ id: "chart", start: 0, end: 150, draw: (ctx, f, env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ // (a cool tint, not the card's paper: the answer opens as an iris, and paper on paper hid it, cc1-3)+ ctx.fillStyle = "#e8ecf6"; ctx.fillRect(0, 0, 1080, 1080);+ ctx.fillStyle = CLEAN.line; for (let j = 1; j <= 4; j++) ctx.fillRect(120, 900 - j * 170, 840, 3);+ ctx.fillStyle = CLEAN.ink; ctx.fillRect(120, 900, 840, 5);+ BARS.forEach((v, i) => {+ // each bar rises on an out-cubic, 12 frames after the one before; the accent bar last and tallest+ const q = Math.min(1, Math.max(0, (f - 6 - i * 12) / 30)), e = 1 - (1 - q) ** 3, h = 700 * v * e;+ ctx.fillStyle = i === BARS.length - 1 ? CLEAN.accent : "#b9bfcc";+ ctx.fillRect(170 + i * 205, 900 - h, 150, h);+ });+ } }],+};++const inbox: ProductUI = {+ title: "Tally", nav: ["Inbox", "Books", "Reports"], action: "Match all",+ // (the rows keep their places and gain their tag as they match, the hosting row the chat asked about in+ // the accent: rows that traded places passed through each other, and a fresh critic read the crossing as+ // rows going see-through and vanishing, cc1-2. The words beside them are read through the press, a+ // declared hold, so the in-place change is never dead air)+ before: { items: [+ { id: "a", label: "Cloud hosting, Sep", value: "$1,208" },+ { id: "b", label: "Design tool, Sep", value: "$144" },+ { id: "c", label: "Team lunch, Sep", value: "$86" },+ ] },+ after: { items: [+ { id: "a", label: "Cloud hosting, Sep", value: "$1,208", tag: "matched", done: true, accent: true },+ { id: "b", label: "Design tool, Sep", value: "$144", tag: "matched", done: true },+ { id: "c", label: "Team lunch, Sep", value: "$86", tag: "matched", done: true },+ ] },+};++export const launchExampleCleanChat = makeLaunchFilm({+ title: "Tally", subtitle: "your books, answered", placeholder: "Ask Tally…", genLabel: "Ask", preset: "clean", fps: 60,+ asks: [+ { prompt: "why did hosting go up?", plate: chart, label: "Cloud hosting, by month" },+ { kind: "ui", ui: inbox, split: [{ text: "Then it fixes", style: "ink", color: "#15161a" }, { text: "the books.", style: "ink", color: "#2f54eb" }] },+ ],+ words: [[{ text: "ASK IT.", style: "ink", color: "#15161a" }, { text: "SEE WHY.", style: "ink", color: "#2f54eb" }]],+ tagline: "Bookkeeping that does itself",+ install: ["npm install tally", "tally init"],+ footer: "tally.example",+ // the end card on endCard.ts's asymmetric grid: with two install lines a centred stack is five blocks on one+ // axis, the centred stack framecheck rejects+ endCard: "grid",+ // THE DECLARATIONS ship reads (node tools/ship.mjs). Filled for this made-up product as a worked example:+ // replace each with your own (launchExampleClean.ts explains each one)+ motion: { temperament: "snappy", brandColors: ["#2f54eb", "#15161a"] },+ claims: [],+ checks: {+ length: { target: 22, max: 25 },+ // the split beat IS the product's own inbox beside its words: its rows are what the viewer came to see+ // (60 fps frames, the travel into it included); the chat, the word page and the end card are still judged+ layoutExempt: [[560, 960, "the inbox beat: the product's own rows beside its two words"]],+ // the critic's record is reviews/launchExampleCleanChat.json, this example's own+ },+ // (askBeats 8: the chart answering the chat ask has time to be seen; claimBar 6 lands the end card on bar 6,+ // so the score leaves it a 5.3 s hold, as the other examples have)+ bpm: 90, askBeats: 8, typeBeats: 6, endBeats: 8, claimBar: 6,+ // the clean example's own score (the same made-up product and brief); a real film composes its own+ score: tallyScore,+});diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleCleanScore.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleCleanScore.tsnew file mode 100644index 0000000..6a0b983--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleCleanScore.ts@@ -0,0 +1,52 @@+// THE EXAMPLE'S SCORE. Composed for the clean launch example's made-up product (a calm, confident+// bookkeeping app) the way a user composes one for their own brief (references/music/compose.md). It is+// a worked example of the format, never a score to reuse: your film's music is written for YOUR brief.+//+// The brief as numbers: a 21 s launch film at 90 bpm in 4/4 (a bar is 2.67 s), cut on the template's+// beat grid. Picture beats: the ask typed from frame 0, the word page at 4.0 s, the books screen at+// 6.7 s, the reports screen on bar 4 (10.7 s), the end card on bar 6 (16.0 s, claimBar 6).+// The arc: a quiet start under the typing, the groove as the screens work, a breath on bar 5, the+// home chord and the motif's last word on the end card, then a short ring. Loudness stays even (a+// product film is watched with the sound low), so the energy moves by layers more than by level.+// The motif: an upbeat start, a third up, then steps home; answered a step lower, sequenced up,+// lifted to its peak on the reports screen, fragmented in the breath, augmented at the end.+import type { Material } from "./music";++export const tallyScore = (): Material => ({+ style: "lofiElectronic", title: "Tally, balanced", seed: 41, mood: "hopeful",+ bpm: 90, key: "A", mode: "major", meter: "4/4",+ moodControls: { energy: 0.45, warmth: 0.55, brightness: 0.7, tension: 0.35, space: 0.85 },+ swing: 0.53, dyn: [0.6, 0.64], tail: 0, // no ring bar: the held home chord is the ring, released inside the film+ // the warm bass, not the round sub: a bed under a voice-free film needs body, not rumble+ voices: { bass: "warm", lead: "bell" },+ levels: { lead: 2, counter: -6, chords: -3, kick: -2 }, // the answering line sits under the tune, never over it+ chords: {+ A: { voicing: "[G#3 B3 C#4 E4]", bass: "A2:1.5 E3:.5 A2:1 C#3:1" },+ Fsm: { voicing: "[E3 A3 C#4 G#4]", bass: "F#2:1.5 C#3:.5 F#2:.5 r:.5 A2:1" },+ D: { voicing: "[F#3 A3 C#4 E4]", bass: "D3:1.5 A2:.5 D3:1 E3:1" },+ E: { voicing: "[E3 A3 B3 D4]", bass: "E3:1.5 B2:.5 E3:1 r:1" },+ Bm: { voicing: "[E3 A3 C#4 D4]", bass: "B2:1.5 F#3:.5 B2:2" },+ Esus: { voicing: "[E3 A3 B3 D4]", bass: "E3:4" },+ Home: { voicing: "[E3 G#3 C#4 E4]", bass: "A2:4" },+ },+ motifs: {+ state: "r:.5 C#5:.5 E5:1 D5:.5 C#5:.5 B4:1",+ answer: "r:.5 B4:.5 D5:1 C#5:.5 B4:.5 A4:1",+ rise: "r:.5 D5:.5 F#5:1 E5:.5 D5:.5 C#5:1",+ peak: "r:.5 E5:.5 A5:1.5 G#5:.5 E5:1",+ lean: "r:.5 C#5:.5 E5:.5 F#5:.5 E5:2",+ breath: "r:.5 C#5:.5 E5:1 r:.5 D5:.5 B4:1",+ last: "C#5:1 E5:1 A4:2",+ rest: "r:4",+ },+ grooves: { main: { family: "bounce", density: 0.35, variation: 0.3 }, half: { family: "halfTime", density: 0.3 } },+ sections: [+ { kind: "intro", bars: 1, harmony: ["A"], chordVel: 0.55, energy: 0.45 },+ { kind: "groove", bars: 2, harmony: ["Fsm", "D"], lead: ["state", "answer"], groove: "main", energy: 0.5 },+ { kind: "hook", bars: 2, harmony: ["A", "E"], lead: ["peak", "lean"], counter: ["rise", "rest"], groove: "main", energy: 0.58 },+ { kind: "half", bars: 1, harmony: ["Bm Esus"], lead: ["breath"], bass: ["B2:1.5 F#3:.5 E3:1.5 r:.5"], groove: "half", energy: 0.5 },+ { kind: "outro", bars: 2, harmony: ["Home", "~"], lead: ["last", "rest"], comp: ["x:4", "~:2 r:2"], energy: 0.6 },+ // the stretch: one more held bar of home, played 0 or more times so the film is whole bars of the score+ { kind: "outro", bars: 1, harmony: ["~"], lead: ["rest"], stretch: true, energy: 0.5 },+ ],+});diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleScore.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleScore.tsnew file mode 100644index 0000000..eaa7033--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExampleScore.ts@@ -0,0 +1,55 @@+// THE DRAWN EXAMPLE'S SCORE. Composed for the drawn launch example's made-up product (a warm, lively tool+// that turns a sentence into a hand-drawn picture) the way a user composes one for their own brief+// (references/music/compose.md). It is a worked example of the format, never a score to reuse: your film's+// music is written for YOUR brief.+//+// The brief as numbers: a 16 to 19 s launch film at 90 bpm in 4/4 (a bar is 2.67 s), cut on the template's+// beat grid. Picture beats: the first prompt typed from frame 0 and Generate pressed at 1.8 s, the word+// page at 4.0 s, the second prompt at 8.0 s and its press at 10.5 s, the end card on bar 5 (13.3 s,+// claimBar 5). The arc: a fingerpicked start under the typing, the tune on the word page, the lift as the+// second answer draws itself, the home chord and the tune's last word on the end card, then a short ring.+// Loudness stays even (a product film is watched with the sound low): the energy moves by layers.+// The motif: a rising sixth and a step back, a sketch of a line being drawn; answered lower, lifted on the+// second answer, and set down whole on the end card.+import type { Material } from "./music";++export const sketchScore = (): Material => ({+ style: "folk", title: "Your Product, sketched", seed: 23, mood: "hopeful",+ bpm: 90, key: "D", mode: "major", meter: "4/4",+ moodControls: { energy: 0.5, warmth: 0.7, brightness: 0.6, tension: 0.3, space: 0.75 },+ swing: 0.52, dyn: [0.6, 0.66], tail: 0, // the held home chord is the ring, released inside the film+ // (the lead is set 2 dB under where it was: the harp's soft layer is recorded about 12 dB hot against its+ // model and the sample loader trims at most 9 dB, so its D5 to A5 tune sat 3 dB hot in the 300 Hz to+ // 1.2 kHz body and crowded it, the sound check's one warning)+ levels: { lead: 0, counter: -6, chords: -2 },+ chords: {+ D: { voicing: "[D3 A3 D4 F#4]", bass: "D2:1.5 A2:.5 D2:1 F#2:1" },+ Bm: { voicing: "[B2 F#3 B3 D4]", bass: "B1:1.5 F#2:.5 B1:1 D2:1" },+ G: { voicing: "[G2 D3 G3 B3]", bass: "G2:1.5 D2:.5 G2:1 B2:1" },+ A: { voicing: "[A2 E3 A3 C#4]", bass: "A2:1.5 E2:.5 A2:1 C#3:1" },+ Em: { voicing: "[E3 G3 B3 D4]", bass: "E2:1.5 B2:.5 E2:2" },+ Asus: { voicing: "[A2 D3 E3 A3]", bass: "A2:4" },+ Home: { voicing: "[D3 A3 D4 F#4 A4]", bass: "D2:4" },+ },+ motifs: {+ open: "r:1 D5:.5 E5:.5 F#5:1 A4:1",+ sketch: "r:.5 A4:.5 F#5:1 E5:.5 D5:.5 B4:1",+ reply: "r:.5 F#4:.5 D5:1 C#5:.5 B4:.5 A4:1",+ lift: "r:.5 B4:.5 G5:1 F#5:.5 E5:.5 D5:1",+ crest: "r:.5 C#5:.5 A5:1.5 G5:.5 E5:1",+ lean: "r:.5 D5:.5 E5:.5 F#5:.5 E5:2",+ last: "A4:1 F#5:1 D5:2",+ ring: "r:1 F#4:1 A4:1 D5:1", // the last bar keeps sounding under the held card: a held chord alone sagged 16 LU (sound check)+ rest: "r:4",+ },+ // brushes under the picking: a light kit that moves without pushing (a drawing tool, not a dance floor)+ grooves: { main: { family: "brushes", density: 0.3, variation: 0.3 } },+ sections: [+ { kind: "intro", bars: 1, harmony: ["D"], lead: ["open"], chordVel: 0.6, energy: 0.5 }, // the tune's first notes under the typing: no hole before the press+ { kind: "verse", bars: 2, harmony: ["Bm", "G"], lead: ["sketch", "reply"], groove: "main", energy: 0.55 },+ { kind: "hook", bars: 2, harmony: ["G A", "Em Asus"], lead: ["lift", "crest"], counter: ["rest", "lean"], bass: ["G2:1.5 D2:.5 A2:1.5 E2:.5", "E2:1.5 B2:.5 A2:2"], groove: "main", energy: 0.6 },+ { kind: "outro", bars: 2, harmony: ["Home", "Home"], lead: ["last", "ring"], groove: "main", energy: 0.6 },+ // the stretch: one more held bar of home, played 0 or more times so the film is whole bars of the score+ { kind: "outro", bars: 1, harmony: ["~"], lead: ["rest"], stretch: true, energy: 0.5 },+ ],+});diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.tsindex 3d92c4c..1c055e6 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.ts@@ -5,8 +5,18 @@// plate drawn live by its own code, never a recording of it.import { fractal, type Ctx, type Env, type Layer, type P } from "./core";import { renderFrame, type Film } from "./film";+import { drawEl, type BrandElement } from "./brandKit";// ---------------------------------------------------------------- palette and type+// THE FROZEN LAUNCH FILMS. launch, launch2 and launch3 are the source of anidoodle's published launch film+// (README). They were made before the 0.10 checks and are kept as they were published: never re-cut to+// meet a later check, and never a template to copy (references/workflows/launch-video-kit.md). Each declares+// the ship rows that cannot look, and the dead-air gate rows it fails, in meta.checks.none with this reason.+export const FROZEN = "frozen source of the published launch film; made before the 0.10 checks";+/** meta.checks.none for a frozen launch film: the ship rows with nothing declared to judge against, plus the named gate rows. */+export const frozenNone = (gateRows: ("gate:identical" | "gate:still")[] = []): Record<string, string> =>+ Object.fromEntries([...["motion:temperament", "layers:translucent", "facts", "review", "length"].map((k) => [k, FROZEN]), ...gateRows.map((k) => [k, `${FROZEN}: its still beats are the pace it was published with, and declaring them as holds one by one would be a re-cut on paper`])]);+export const C = {bg: "#ece6da", card: "#fffdf8", ink: "#1d1a16", soft: "#6f675c", mute: "#a39a8c", line: "#e0d8c8",chip: "#f3ede1", accent: "#d4622b", accentDeep: "#a9471a", paper: "#fbf9f3", shadow: "rgba(60,40,20,0.10)",@@ -99,12 +109,13 @@ export const blot = (c: P, R: number, seed: number, n = 96): P[] => {export const pathOf = (ctx: Ctx, pts: P[]) => { ctx.beginPath(); pts.forEach(([x, y], i) => (i ? ctx.lineTo(x, y) : ctx.moveTo(x, y))); ctx.closePath(); };// ---------------------------------------------------------------- pointer-export const pointer = (ctx: Ctx, p: P, down = 0, s = 1.35) => {+// (`tone`: its fill and edge; a dark look passes a light arrow, which a black one on a dark page is not seen)+export const pointer = (ctx: Ctx, p: P, down = 0, s = 1.35, tone: { fill: string; edge: string } = { fill: "#111", edge: "#fff" }) => {const k = s * (1 - 0.12 * down);const shape: P[] = [[0, 0], [0, 25], [6.4, 19.2], [10.6, 29], [14.8, 27.2], [10.8, 17.8], [19, 17.8]];ctx.save(); ctx.translate(p[0], p[1]); ctx.scale(k, k);ctx.fillStyle = "rgba(0,0,0,0.18)"; pathOf(ctx, shape.map(([x, y]) => [x + 1.2, y + 2] as P)); ctx.fill();- pathOf(ctx, shape); ctx.fillStyle = "#111"; ctx.fill(); ctx.lineWidth = 1.6; ctx.strokeStyle = "#fff"; ctx.lineJoin = "round"; ctx.stroke();+ pathOf(ctx, shape); ctx.fillStyle = tone.fill; ctx.fill(); ctx.lineWidth = 1.6; ctx.strokeStyle = tone.edge; ctx.lineJoin = "round"; ctx.stroke();ctx.restore();};@@ -118,6 +129,7 @@ export const TEXT = { x: 404, base: 948, px: 34 };export type ChatState = {typed: string; caret: boolean; placeholder?: string;+ full?: string; // the whole prompt being typed: a wrapping composer breaks where it will (composerLines)sent?: string; sentAlpha?: number; // the user's message once it has gone upattach?: { img: CanvasImageSource; label: string } | null;genPress?: number; genHot?: number; // the button: press depth 0..1, hover glow 0..1@@ -143,7 +155,17 @@ export type ChatGeom = {theme?: Partial<typeof C>;drop?: string; // the ink drop's colour (default the ink): the clean preset's drop is its one accentiris?: boolean; // the answer card opens as a clean round iris instead of an ink bloom (the clean preset)+ wrapAs?: { px: number; maxW: number }; // wrap the typed words as at this type size and width (a composer easing between two sizes keeps one set of line breaks), drawn at TEXT.px+ look?: ChatLook; // a custom look (launchLook.ts): its text face, shapes, header and label colour; absent, the stock chat+};+/** What the chat takes from a custom look (launchLook.ts resolves it): its faces, its shapes and its window. */+export type ChatLook = {+ fonts: { text: (w: number, px: number) => string };+ shape: { bubble: "rounded" | "square" | "none"; composer: "box" | "bar"; button: "pill" | "square"; radius?: number; buttonLabel?: string };+ chat: { header?: boolean; title?: string; subtitle?: string; logo?: BrandElement; bubble?: { fill: string; ink: string }; reply?: { fill: string; ink: string } };+ onAccent: string;};+const FT = (g: ChatGeom) => g.look?.fonts.text ?? SANS;export const CHAT_GEOM: ChatGeom = { CHAT, INPUT, GEN, REPLY, TEXT, k: 1, px: { head: 22, sub: 18, bubble: 26, label: 20, gen: 24 }, wrap: 0, lineH: 44 };// the same component at any size: derived from the window's rectangle, a length scale and the type// sizes. chatGeom(CHAT, 1, CHAT_GEOM.px, TEXT.px, 0) IS CHAT_GEOM (a test holds it to that).@@ -157,9 +179,16 @@ export const chatGeom = (chat: Rect & { r?: number }, k: number, px: ChatGeom["pconst pal = (g: ChatGeom) => (g.theme ? { ...C, ...g.theme } : C);// the typed words as they sit in a wrapping composer: whole words per line, a word longer than the// line broken where it must. Measured with the real font, so the lines are what the viewer sees.-export const composerLines = (ctx: Ctx, typed: string, g: ChatGeom): string[] => {- const maxW = g.GEN.x - 20 * g.k - g.TEXT.x;- ctx.font = SANS(500, g.TEXT.px);+// `full`: the whole prompt being typed. Given it, the words break where the finished prompt breaks, so a word+// starts on the line it will end on (a half-typed word that fit jumped a line as it grew, its line read 0.15 s)+export const composerLines = (ctx: Ctx, typed: string, g: ChatGeom, full?: string): string[] => {+ if (full !== undefined && full !== typed && full.startsWith(typed)) {+ const all = composerLines(ctx, full, g), out: string[] = []; let left = typed.length;+ for (const l of all) { if (left <= 0 && out.length) break; out.push(l.slice(0, Math.max(0, left))); left -= l.length; }+ return out;+ }+ const maxW = g.wrapAs ? g.wrapAs.maxW : g.GEN.x - 20 * g.k - g.TEXT.x;+ ctx.font = FT(g)(500, g.wrapAs ? g.wrapAs.px : g.TEXT.px);const out: string[] = []; let line = "";for (const tok of typed.split(/(?<= )/)) {if (ctx.measureText(line + tok).width <= maxW || !line) line += tok; else { out.push(line); line = tok; }@@ -173,18 +202,30 @@ export const drawChatFrame = (ctx: Ctx, s: ChatState, g: ChatGeom = CHAT_GEOM) =const { CHAT, INPUT, GEN, REPLY, TEXT, k, px } = g, P = pal(g);ctx.fillStyle = P.bg; ctx.fillRect(-2000, -2000, 6000, 6000);softShadow(ctx, CHAT.x, CHAT.y, CHAT.w, CHAT.h, CHAT.r, 1.2);- ctx.fillStyle = P.card; rr(ctx, CHAT.x, CHAT.y, CHAT.w, CHAT.h, CHAT.r); ctx.fill();- // the thread's head: a small ink dot and a name, nothing that belongs to anyone else+ const LO = g.look, F = FT(g), winR = LO?.shape.radius !== undefined ? LO.shape.radius * k : CHAT.r;+ ctx.fillStyle = P.card; rr(ctx, CHAT.x, CHAT.y, CHAT.w, CHAT.h, winR); ctx.fill();+ // the thread's head: a small ink dot and a name, nothing that belongs to anyone else (a custom look: the+ // product's own logo in the dot's place, or no header at all)+ if (LO?.chat.header !== false) {if (s.head !== undefined) ctx.globalAlpha = s.head;- ctx.fillStyle = P.ink; ctx.beginPath(); ctx.arc(CHAT.x + 58 * k, CHAT.y + 52 * k, 9 * k, 0, Math.PI * 2); ctx.fill();- ctx.font = SANS(600, px.head); ctx.fillStyle = P.ink; ctx.textBaseline = "middle"; ctx.fillText(s.title ?? "anidoodle", CHAT.x + 80 * k, CHAT.y + 53 * k);- const subX = s.title === undefined ? CHAT.x + 196 * k : CHAT.x + 80 * k + ctx.measureText(s.title).width + 16 * k;- ctx.font = SANS(500, px.sub); ctx.fillStyle = P.mute; ctx.fillText(s.subtitle ?? "drawn in code", subX, CHAT.y + 54 * k);+ // (the clean look's ink is never see-through, layerscan translucent: its dot is cut in or out whole, at half)+ { const a = ctx.globalAlpha; if (g.iris) ctx.globalAlpha = a >= 0.5 ? 1 : 0;+ const logo = LO?.chat.logo;+ if (logo) { const sc = (26 * k) / Math.max(logo.w, logo.h); ctx.save(); ctx.translate(CHAT.x + 58 * k - (logo.w * sc) / 2, CHAT.y + 52 * k - (logo.h * sc) / 2); ctx.scale(sc, sc); drawEl(ctx, logo, { name: "logo" }); ctx.restore(); }+ else { ctx.fillStyle = P.ink; ctx.beginPath(); ctx.arc(CHAT.x + 58 * k, CHAT.y + 52 * k, 9 * k, 0, Math.PI * 2); ctx.fill(); }+ ctx.globalAlpha = a; }+ const title = LO?.chat.title ?? s.title, sub = LO?.chat.subtitle ?? s.subtitle;+ // (with a logo the words stand 34 px or more clear of it: framecheck's gap between a brand element and text)+ const tx = LO?.chat.logo ? CHAT.x + 71 * k + Math.max(34, 36 * k) : CHAT.x + 80 * k;+ ctx.font = F(600, px.head); ctx.fillStyle = P.ink; ctx.textBaseline = "middle"; ctx.fillText(title ?? "anidoodle", tx, CHAT.y + 53 * k);+ const subX = title === undefined ? tx + 116 * k : tx + ctx.measureText(title).width + 16 * k;+ ctx.font = F(500, px.sub); ctx.fillStyle = P.mute; ctx.fillText(sub ?? "drawn in code", subX, CHAT.y + 54 * k);ctx.fillStyle = P.line; ctx.fillRect(CHAT.x + 32 * k, CHAT.y + 98 * k, CHAT.w - 64 * k, 1.5 * k);if (s.head !== undefined) ctx.globalAlpha = 1;+ }// the sent message, right alignedif (s.sent) {- ctx.globalAlpha = s.sentAlpha ?? 1; ctx.font = SANS(500, px.bubble);+ ctx.globalAlpha = s.sentAlpha ?? 1; ctx.font = F(500, px.bubble);const tw = ctx.measureText(s.sent).width, pad = 26 * k, bw = tw + pad * 2, bx = CHAT.x + CHAT.w - 60 * k - bw, by = CHAT.y + 124 * k;let ay = by;if (s.attach) { const iw = 240 * k, ih = 150 * k; ay = by; ctx.save(); rr(ctx, CHAT.x + CHAT.w - 60 * k - iw, ay, iw, ih, 16 * k); ctx.clip(); ctx.drawImage(s.attach.img, CHAT.x + CHAT.w - 60 * k - iw, ay, iw, ih); ctx.restore(); ay += ih + 10 * k; }@@ -192,17 +233,19 @@ export const drawChatFrame = (ctx: Ctx, s: ChatState, g: ChatGeom = CHAT_GEOM) =ctx.fillStyle = P.ink; ctx.textBaseline = "middle"; ctx.fillText(s.sent, bx + pad, ay + 29 * k);ctx.globalAlpha = 1;}- if (s.label) { ctx.globalAlpha = s.labelAlpha ?? 1; ctx.fillStyle = P.ink; ctx.beginPath(); ctx.arc(REPLY.x + 9 * k, REPLY.y - 26 * k, 7 * k, 0, Math.PI * 2); ctx.fill(); ctx.font = SANS(600, px.label); ctx.textBaseline = "middle"; ctx.fillText(s.label, REPLY.x + 26 * k, REPLY.y - 25 * k); ctx.globalAlpha = 1; }+ if (s.label) { ctx.globalAlpha = s.labelAlpha ?? 1; ctx.fillStyle = P.ink; ctx.beginPath(); ctx.arc(REPLY.x + 9 * k, REPLY.y - 26 * k, 7 * k, 0, Math.PI * 2); ctx.fill(); ctx.font = F(600, px.label); ctx.textBaseline = "middle"; ctx.fillText(s.label, REPLY.x + 26 * k, REPLY.y - 25 * k); ctx.globalAlpha = 1; }// the composer{ const g2 = s.composerGeom ?? g, { INPUT, GEN, TEXT, k, px } = g2;if (s.composer !== undefined) ctx.globalAlpha = s.composer;- ctx.fillStyle = P.paper; rr(ctx, INPUT.x, INPUT.y, INPUT.w, INPUT.h, INPUT.r); ctx.fill();+ // (a bar: round ends at one line's height; a composer grown to three lines keeps those ends, never an oval)+ const inR = LO ? (LO.shape.composer === "bar" ? Math.min(INPUT.h / 2, 52 * k) : LO.shape.radius !== undefined ? LO.shape.radius * k : INPUT.r) : INPUT.r;+ ctx.fillStyle = P.paper; rr(ctx, INPUT.x, INPUT.y, INPUT.w, INPUT.h, inR); ctx.fill();ctx.lineWidth = 2 * k; ctx.strokeStyle = P.line; ctx.stroke();- ctx.font = SANS(500, TEXT.px); ctx.textBaseline = "alphabetic";+ ctx.font = F(500, TEXT.px); ctx.textBaseline = "alphabetic";if (!s.typed && s.placeholder) { ctx.fillStyle = P.mute; ctx.fillText(s.placeholder, TEXT.x, TEXT.base); }const acc = s.accent ?? P.accent;if (g2.wrap > 0) {- const lines = composerLines(ctx, s.typed, g2); ctx.font = SANS(500, TEXT.px); ctx.fillStyle = P.ink;+ const lines = composerLines(ctx, s.typed, g2, s.full); ctx.font = F(500, TEXT.px); ctx.fillStyle = P.ink;lines.forEach((l, i) => ctx.fillText(l, TEXT.x, TEXT.base + i * g2.lineH));if (s.caret) { const i = lines.length - 1, x = TEXT.x + ctx.measureText(lines[i]).width + 3 * k; ctx.fillStyle = acc; ctx.fillRect(x, TEXT.base + i * g2.lineH - 0.94 * TEXT.px, 3 * k, 1.18 * TEXT.px); }} else {@@ -211,14 +254,16 @@ export const drawChatFrame = (ctx: Ctx, s: ChatState, g: ChatGeom = CHAT_GEOM) =}// Generateconst pr = s.genPress ?? 0, hot = s.genHot ?? 0, q = 1 - 0.07 * pr, gx = GEN.x + (GEN.w * (1 - q)) / 2, gy = GEN.y + (GEN.h * (1 - q)) / 2;- ctx.fillStyle = hot > 0 ? mixHex(acc, s.accent ? deepen(acc) : P.accentDeep, 0.35 * hot + 0.4 * pr) : acc; rr(ctx, gx, gy, GEN.w * q, GEN.h * q, GEN.r * q); ctx.fill();- ctx.fillStyle = "#fff"; ctx.font = SANS(600, px.gen * q); ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.fillText(s.genLabel ?? "Generate", GEN.x + GEN.w / 2, GEN.y + GEN.h / 2 + 1 * k); ctx.textAlign = "left";+ { const a = ctx.globalAlpha; if (g.iris) ctx.globalAlpha = a >= 0.5 ? 1 : 0; // (the clean look's accent button, cut whole, as its dot)+ const genR = LO?.shape.button === "square" ? Math.min(GEN.r, 8 * k) : GEN.r;+ ctx.fillStyle = hot > 0 ? mixHex(acc, s.accent ? deepen(acc) : P.accentDeep, 0.35 * hot + 0.4 * pr) : acc; rr(ctx, gx, gy, GEN.w * q, GEN.h * q, genR * q); ctx.fill(); ctx.globalAlpha = a; }+ ctx.fillStyle = LO?.onAccent ?? "#fff"; ctx.font = F(600, px.gen * q); ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.fillText(s.genLabel ?? "Generate", GEN.x + GEN.w / 2, GEN.y + GEN.h / 2 + 1 * k); ctx.textAlign = "left";if (s.composer !== undefined) ctx.globalAlpha = 1; }};// where the caret is: the end of the typed words (on their last line in a wrapping composer)-export const caretAt = (ctx: Ctx, typed: string, g: ChatGeom = CHAT_GEOM): P => {- if (g.wrap > 0) { const lines = composerLines(ctx, typed, g), i = lines.length - 1; ctx.font = SANS(500, g.TEXT.px); return [g.TEXT.x + ctx.measureText(lines[i]).width, g.TEXT.base + i * g.lineH - 0.35 * g.TEXT.px]; }- ctx.font = SANS(500, g.TEXT.px); return [g.TEXT.x + ctx.measureText(typed).width, g.TEXT.base - 12];+export const caretAt = (ctx: Ctx, typed: string, g: ChatGeom = CHAT_GEOM, full?: string): P => {+ if (g.wrap > 0) { const lines = composerLines(ctx, typed, g, full), i = lines.length - 1; ctx.font = FT(g)(500, g.TEXT.px); return [g.TEXT.x + ctx.measureText(lines[i]).width, g.TEXT.base + i * g.lineH - 0.35 * g.TEXT.px]; }+ ctx.font = FT(g)(500, g.TEXT.px); return [g.TEXT.x + ctx.measureText(typed).width, g.TEXT.base - 12];};const hx = (h: string) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));@@ -240,12 +285,21 @@ export const charTimes = (text: string, t0: number, rate: number, seed: number)export const typedAt = (text: string, f: number, times: number[]) => text.slice(0, times.filter((t) => f >= t).length);// The drop: a bead of ink lifts off Generate and arcs to where the answer card will land.export type Drop = { t0: number; land: number; full: number };+// the drop's progress along its path: the drawn look's in-out; the clean look's keeps 60 % of a steady pace, so+// it lands still moving, a hit the iris takes over (an in-out's slow last third crawled for half a second on a+// lively brand's longer flight: dead air to the gate)+const dropEase = (u: number, g: ChatGeom) => (g.iris ? 0.4 * inOut(u) + 0.6 * u : inOut(u));+// (and it flies straight: the 150 px arc, falling again as the drop rose to a card above the button, cancelled+// its climb near the end on a phone frame, where the path is mostly upward, and the drop hung there)+const dropArc = (g: ChatGeom) => (g.iris ? 0 : 150);export const inkDrop = (ctx: Ctx, f: number, d: { t0: number; land: number }, to: P, g: ChatGeom = CHAT_GEOM) => {const { GEN, k } = g, ink = g.drop ?? pal(g).ink, GEN_C: P = [GEN.x + GEN.w / 2, GEN.y + GEN.h / 2];if (f < d.t0 - 6 || f >= d.land) return;if (f < d.t0) { const w = out3(ramp(f, d.t0 - 6, d.t0)); ctx.fillStyle = ink; ctx.beginPath(); ctx.arc(GEN_C[0], GEN.y + 6 * k - w * 22 * k, 30 * k * (0.3 + 0.7 * w), 0, Math.PI * 2); ctx.fill(); return; }- const at = (t: number): P => { const u = ramp(t, d.t0, d.land), e = inOut(u); return [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16 * k, to[1], e) - Math.sin(Math.PI * u) * 150 * k]; };- for (let j = 24; j >= 0; j--) { const p = at(f - j * 0.1); ctx.fillStyle = ink; ctx.globalAlpha = j === 0 ? 1 : 0.22 * (1 - j / 25); ctx.beginPath(); ctx.arc(p[0], p[1], 30 * k * (1 - j * 0.022), 0, Math.PI * 2); ctx.fill(); }+ const at = (t: number): P => { const u = ramp(t, d.t0, d.land), e = dropEase(u, g); return [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16 * k, to[1], e) - Math.sin(Math.PI * u) * dropArc(g) * k]; };+ // the drawn look trails ghosts of ink; the clean look's drop (its one accent, never see-through) stretches+ // into one solid, tapering streak along its path instead, as the motif's drop does+ for (let j = 24; j >= 0; j--) { const p = at(f - j * 0.1); ctx.fillStyle = ink; ctx.globalAlpha = g.iris || j === 0 ? 1 : 0.22 * (1 - j / 25); ctx.beginPath(); ctx.arc(p[0], p[1], 30 * k * (g.iris ? 1 - j * 0.034 : 1 - j * 0.022), 0, Math.PI * 2); ctx.fill(); }ctx.globalAlpha = 1;};// where the drop is at frame f (null when it is not in flight): the motif's position for a match cut@@ -253,23 +307,44 @@ export const inkDropAt = (f: number, d: { t0: number; land: number }, to: P, g:const { GEN, k } = g, GEN_C: P = [GEN.x + GEN.w / 2, GEN.y + GEN.h / 2];if (f < d.t0 - 6 || f >= d.land) return null;if (f < d.t0) { const w = out3(ramp(f, d.t0 - 6, d.t0)); return { p: [GEN_C[0], GEN.y + 6 * k - w * 22 * k], r: 30 * k * (0.3 + 0.7 * w) }; }- const u = ramp(f, d.t0, d.land), e = inOut(u);- return { p: [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16 * k, to[1], e) - Math.sin(Math.PI * u) * 150 * k], r: 30 * k };+ const u = ramp(f, d.t0, d.land), e = dropEase(u, g);+ return { p: [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16 * k, to[1], e) - Math.sin(Math.PI * u) * dropArc(g) * k], r: 30 * k };};// The answer card in the thread: a byline, then the art, revealed by the landed drop blooming open.// `art` is any layer (plateLayer gives a live plate); `crop` picks a source rectangle.// `grow` (default an out-cubic from land to full) is how open the card is at frame f: the template// passes a spring, so the card lands on the spring's first arrival and its sound cue can sit there-export const inkCard = (ctx: Ctx, x: number, y: number, s: number, f: number, d: Drop, art: Layer, label: string, crop?: [number, number, number, number], g: ChatGeom = CHAT_GEOM, growAt?: (f: number) => number) => {+/** Set by a surface that faded or withheld the last fillText to the share of it drawn, 0..1 (launchTemplate's placed(), fading a line before a zone), so a mark that belongs to the line fades and leaves with it. */+export const TEXT_SHOWN = Symbol.for("anidoodle.textShown");+export const inkCard = (ctx: Ctx, x: number, y: number, s: number, f: number, d: Drop, art: Layer, label: string, crop?: [number, number, number, number], g: ChatGeom = CHAT_GEOM, growAt?: (f: number) => number, labelA = 1) => {const k = g.k, P = pal(g), A = ctx.globalAlpha; // a card drawn under a focus pull keeps the caller's opacity- ctx.fillStyle = P.ink; ctx.globalAlpha = A * ramp(f, d.land, d.land + 10); ctx.beginPath(); ctx.arc(x + 9 * k, y - 16 * k, 7 * k, 0, Math.PI * 2); ctx.fill();- ctx.font = SANS(600, g.px.label); ctx.textBaseline = "middle"; ctx.fillText(label, x + 26 * k, y - 15 * k); ctx.globalAlpha = A;+ // the byline: a dot and its words, drawn together or not at all (a dot left alone reads as a stray mark)+ const LA = A * ramp(f, d.land, d.land + 10) * Math.max(0, Math.min(1, labelA));+ if (label && LA > 0.001) {+ // the words first: a surface that fades or withholds a line (a travel's zone fade) says how much of it+ // it drew through TEXT_SHOWN, and the dot is drawn at that much too, fading and leaving with its words+ ctx.fillStyle = g.look?.chat.reply?.ink ?? P.ink; ctx.globalAlpha = LA; ctx.font = FT(g)(600, g.px.label); ctx.textBaseline = "middle";+ const c = ctx as Ctx & { [TEXT_SHOWN]?: number }; c[TEXT_SHOWN] = 1; ctx.fillText(label, x + 26 * k, y - 15 * k);+ const shown = Math.max(0, Math.min(1, Number(c[TEXT_SHOWN] ?? 1)));+ // (the clean look's dot is its ink, never see-through: it grows in and shrinks out with its words instead)+ if (shown > 0) { ctx.globalAlpha = g.iris ? 1 : LA * shown; ctx.beginPath(); ctx.arc(x + 9 * k, y - 16 * k, 7 * k * (g.iris ? LA * shown : 1), 0, Math.PI * 2); ctx.fill(); }+ }+ ctx.globalAlpha = A;const grow = growAt ? growAt(f) : out3(ramp(f, d.land, d.full)), c: P = [x + s / 2, y + s / 2];softShadow(ctx, x, y, s, s, 20 * k, Math.min(1, grow) * 1.3);ctx.save(); rr(ctx, x, y, s, s, 20 * k); ctx.clip();if (grow < 1 && g.iris) { ctx.beginPath(); ctx.arc(c[0], c[1], Math.max(0, lerp(18 * k, s * 0.72, grow)), 0, Math.PI * 2); ctx.clip(); }else if (grow < 1) { pathOf(ctx, blot(c, lerp(16 * k, s * 0.8, grow) + 28 * k * (1 - grow), 77)); ctx.fillStyle = g.drop ?? P.ink; ctx.fill(); pathOf(ctx, blot(c, Math.max(0, lerp(16 * k, s * 0.8, grow) - 5 * k), 77)); ctx.clip(); }- ctx.fillStyle = P.paper; ctx.fillRect(x, y, s, s);+ ctx.fillStyle = g.look?.chat.reply?.fill ?? P.paper; ctx.fillRect(x, y, s, s);if (crop) ctx.drawImage(art.canvas, ...crop, x, y, s, s); else ctx.drawImage(art.canvas, x, y, s, s);ctx.restore();+ // the clean iris's edge while it opens: a solid ring in the drop's colour, so the landed drop visibly opens+ // into it (a pale disc on a cream card read as the answer fading in, a fresh critic's cc1-3)+ // (only while the whole ring is inside the card: wider, it showed as four arcs in the corners, cc3-2)+ const rimR = Math.max(0, lerp(18 * k, s * 0.72, grow));+ if (grow < 1 && g.iris && rimR < s / 2 - 2 * k) {+ ctx.save(); rr(ctx, x, y, s, s, 20 * k); ctx.clip();+ ctx.beginPath(); ctx.arc(c[0], c[1], rimR, 0, Math.PI * 2);+ ctx.strokeStyle = g.drop ?? P.accent; ctx.lineWidth = 4 * k; ctx.stroke(); ctx.restore();+ }};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchLayout.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchLayout.tsindex d7b1f48..2f88a41 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchLayout.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchLayout.ts@@ -44,6 +44,8 @@ const ZONE_GAP = 8;// phone-safe minimums, px at the delivered size: `read` = a line the viewer must read (a prompt, a// label, the words, the install lines); `chrome` = the UI around them (a header, a button's word)+// the footer is where the film says the product lives: it is on screen in the last second, so it meets+// framecheck's last-second floor (28 px at 1080, tools/framerules.mjs RULES.endPx), not the chrome floorexport const MIN_PX = { phone: { read: 32, chrome: 24, type: 64 }, desk: { read: 18, chrome: 16, type: 80 } };// A build-time estimate of a sans line's width, deliberately a little wide: layout decisions (how@@ -104,7 +106,7 @@ export type LaunchLayout = {safe: Rect; zones: boolean;roles: Role[];};-export type LayoutContent = { prompts: string[]; install: string[]; tagline: string; title?: string; band?: boolean };+export type LayoutContent = { prompts: string[]; install: string[]; tagline: string; title?: string; band?: boolean; wrap?: (text: string, px: number, maxW: number) => string[] }; // wrap: the look's text face (default the stock estimate)// the desktop composition: the exact numbers of the 1920x1080 filmconst desk = (c: LayoutContent): LaunchLayout => {@@ -113,9 +115,10 @@ const desk = (c: LayoutContent): LaunchLayout => {shape: "16x9", W, H, k: 1, phone: false, chat: g,thread: { top: 170, viewBottom: VIEW_BOTTOM, clip: [300, 158, 1320, VIEW_BOTTOM - 158], bubbleH: 58, bubbleLineH: 34, bubblePad: 26, bubbleR: 1560, bubbleMaxW: 1080, bubbleRad: 22, gap: 26, card: 460, cardX: g.REPLY.x, cardDy: 34, bubbles: c.prompts.map((p) => [p]) },cam: { home: { c: [960, 540], z: 1 }, macroZ: 2.4, macroCreep: 0.25, macroX0: 330, macroY: 934, follow: true, leanZ: 1.18, pointerOff: [1780, 1140], pointerS: 1.35, pointerOn: [g.GEN.x + g.GEN.w / 2 + 18, g.GEN.y + g.GEN.h / 2 + 6] },- bug: { x: W - 40, y: H - 34, px: 24 },+ // the corner mark sits in the gutter right of the window, clear of its corner (24 px at the old 24 px size touched it)+ bug: { x: W - 36, y: H - 30, px: 22 },type: { maxW: 1560, cap1: 190, capN: 130, minPx: MIN_PX.desk.type, cover: 1110 },- end: { cx: W / 2, titleY: 400, titleMax: 150, titleW: 1300, tagline: [c.tagline], taglineY: 520, taglinePx: 30, taglineLH: 40, panelY: py, monoPx: 30, rows: c.install.map((text) => ({ text, indent: 0 })), wrapped: false, rowH: 60, padX: 60, lineY0: py + 55, footerPx: 24, footerY: py + ph + 60, caret: [16, 34] },+ end: { cx: W / 2, titleY: 400, titleMax: 150, titleW: 1300, tagline: [c.tagline], taglineY: 520, taglinePx: 30, taglineLH: 40, panelY: py, monoPx: 30, rows: c.install.map((text) => ({ text, indent: 0 })), wrapped: false, rowH: 60, padX: 60, lineY0: py + 55, footerPx: 28, footerY: py + ph + 60, caret: [16, 34] },// a two-column grid on the frame's centre line: words 40 %, a 100 px gutter, the live UI 46 %, equal marginssplit: { words: { x: 150, y: 150, w: 720, h: 780 }, ui: { x: 970, y: 120, w: 800, h: 840 }, vertical: false, wordsPx: 96 },stage: { x: 0, y: 0, w: W, h: H }, band: null,@@ -135,27 +138,31 @@ const phone = (shape: Exclude<Shape, "16x9">, c: LayoutContent, H0: number, S: Rconst E = zones ? { x0: 0, y0: S.y - (m - ZONE_GAP), x1: S.x + S.w + (m - ZONE_GAP), y1: Math.min(S.y + S.h, H) } : { x0: 0, y0: 0, x1: W, y1: H };const Ew = E.x1 - E.x0, Eh = E.y1 - E.y0;const px = { head: Math.max(22 * k, min.chrome), sub: Math.max(18 * k, min.chrome), bubble: Math.max(26 * k, min.read), label: Math.max(20 * k, min.read), gen: Math.max(24 * k, min.chrome) };- // the window stops above the corner mark's own strip: the mark never sits on the UI- const bugPx = Math.max(24 * k, min.chrome), bugStrip = Math.round(bugPx + 34);+ // the window stops above the corner mark's own strip: the mark never sits on the UI, and its letters stay+ // clear of the window's corner while the hook's camera creeps 2 % about the window's centre+ const bugPx = Math.max(24 * k, min.chrome), bugStrip = Math.round(bugPx + 56), bugY = zones ? E.y1 - 0.3 * bugPx - 2 : E.y1 - 20;const promptPx = Math.max(34 * k, min.read), chatR = { x: E.x0 + m, y: E.y0 + m, w: Ew - 2 * m, h: Eh - m - bugStrip, r: 34 * k };// the composer holds the longest prompt; the button sits on its last lineconst base = chatGeom(chatR, k, px, promptPx, 1), textW = base.GEN.x - 20 * k - base.TEXT.x;- const lines = Math.min(3, Math.max(1, ...c.prompts.map((p) => wrapEst(p, promptPx, textW).length)));+ const lines = Math.min(3, Math.max(1, ...c.prompts.map((p) => (c.wrap ?? wrapEst)(p, promptPx, textW).length)));const g = chatGeom(chatR, k, px, promptPx, lines);const top = g.CHAT.y + 114 * k, viewBottom = g.INPUT.y - 26 * k, bubbleMaxW = g.INPUT.w * 0.86, bubbleLineH = Math.round(px.bubble * 1.3);- const bubbles = c.prompts.map((p) => wrapEst(p, px.bubble, bubbleMaxW - 52 * k));+ const bubbles = c.prompts.map((p) => (c.wrap ?? wrapEst)(p, px.bubble, bubbleMaxW - 52 * k));// the answer card: as wide as the thread allows, and short enough that a card and the prompt above it both fit the viewconst card = Math.round(Math.min(g.INPUT.w, viewBottom - top - 58 * k - 2 * bubbleLineH - 60 * k));const cardX = g.CHAT.x + (g.CHAT.w - card) / 2;- // the end card, stacked and centred in E- const inst = installRows(c.install, Ew - 2 * 32 - 2 * 36, min.read, 30 * k), mono = inst.px;- const taglinePx = Math.max(30 * k, min.read), tagline = wrapEst(c.tagline, taglinePx, Ew - 2 * m - 60), tLH = Math.round(taglinePx * 1.3);+ // the end card, stacked and centred. On 9x16 it centres on the frame itself, the column a viewer sees+ // (centred on the safe rectangle it sat 60 px left of the middle, and read off-centre outside a feed), and+ // stays as narrow as the room between the middle and the right-hand zone allows+ const endCol = zones ? { cx: W / 2, w: 2 * (S.x + S.w + (m - ZONE_GAP) - W / 2) } : { cx: E.x0 + Ew / 2, w: Ew };+ const inst = installRows(c.install, endCol.w - 2 * 32 - 2 * 36, min.read, 30 * k), mono = inst.px;+ const taglinePx = Math.max(30 * k, min.read), tagline = (c.wrap ?? wrapEst)(c.tagline, taglinePx, endCol.w - 2 * m - 60), tLH = Math.round(taglinePx * 1.3);const titleMax = 150 * k, rowH = Math.round(mono * 2), ph = rowH * inst.rows.length + 50 * k;const block = titleMax + 60 + tagline.length * tLH + 60 + ph + 80, y0 = E.y0 + (Eh - block) / 2 - 20;const titleY = y0 + titleMax * 0.62, taglineY = y0 + titleMax + 60 + tLH / 2, panelY = taglineY + (tagline.length - 0.5) * tLH + 50;// the split beat, stacked: the words on top, the live UI under them. On 9x16 both sit in the window's// rectangle, and the UI is inset so its push (12 % at most) never carries its text past that rectangle.- const PUSH = 1.12, R = { x: chatR.x, y: chatR.y, w: chatR.w, h: chatR.h };+ const PUSH = 1.12, R = { x: chatR.x, y: chatR.y, w: chatR.w, h: chatR.h + 22 }; // (+22: a product's panel keeps the room the corner mark's wider strip took from the chat window; it never creeps as the hook does)const wordsH = Math.round(R.h * 0.32), uiTop = R.y + wordsH + 30, uiW = Math.floor(R.w / PUSH), uiH = Math.floor((R.y + R.h - uiTop) / PUSH);const split = zones? { words: { x: R.x + 20, y: R.y + 10, w: R.w - 40, h: wordsH }, ui: { x: Math.round(R.x + (R.w - uiW) / 2), y: Math.round(uiTop + (R.y + R.h - uiTop - uiH) / 2), w: uiW, h: uiH }, vertical: true, wordsPx: 96 }@@ -171,9 +178,9 @@ const phone = (shape: Exclude<Shape, "16x9">, c: LayoutContent, H0: number, S: Rthread: { top, viewBottom, clip: [g.CHAT.x, g.CHAT.y + 102 * k, g.CHAT.w, viewBottom - (g.CHAT.y + 102 * k)], bubbleH: 58 * k + (px.bubble - 26 * k) * 1.2, bubbleLineH, bubblePad: 26 * k, bubbleR: g.INPUT.x + g.INPUT.w, bubbleMaxW, bubbleRad: 22 * k, gap: 26 * k, card, cardX, cardDy: 34 * k + (px.label - 20 * k), bubbles },// on 9x16 the lean on a new card goes further: the card is smaller there, and the rest of the window fades as it leaves the safe areacam: { home: { c: [W / 2, H / 2], z: 1 }, macroZ, macroCreep: macroZ * 0.08, macroX0: W / 2 / macroZ - 60 * k, macroY: g.INPUT.y + g.INPUT.h / 2, follow: true, leanZ: zones ? 1.5 : 1.1, pointerOff: [W - 110, H + 70], pointerS: 1.35 * k, pointerOn: [g.GEN.x + g.GEN.w / 2 + 18 * k, g.GEN.y + g.GEN.h / 2 + 6 * k] },- bug: { x: E.x1 - m - 10, y: E.y1 - bugStrip / 2 + bugPx * 0.1, px: bugPx },+ bug: { x: chatR.x + chatR.w - 20, y: bugY, px: bugPx }, // under the window's right edge, 20 px in: aligned to the content, with room before the right-hand zonetype: { maxW: Ew - 2 * 90, cap1: 190, capN: 150, minPx: min.type, cover: zones ? Math.ceil(Math.max(...[[0, 0], [W, 0], [0, H], [W, H]].map(([x, y]) => Math.hypot(x - typeAt[0], y - typeAt[1])))) + 9 : Math.ceil(Math.hypot(W, H) / 2) + 9, ...(zones ? { at: typeAt } : {}) }, // cover: the bloom's reach to the farthest corner from where it opens- end: { cx: E.x0 + Ew / 2, titleY, titleMax, titleW: Ew - 2 * m - 80, tagline, taglineY, taglinePx, taglineLH: tLH, panelY, monoPx: mono, rows: inst.rows, wrapped: inst.wrapped, rowH, padX: 36, lineY0: panelY + 25 * k + rowH / 2, footerPx: Math.max(24 * k, min.read), footerY: panelY + ph + 60, caret: [Math.round(mono * 0.53), Math.round(mono * 1.13)] },+ end: { cx: endCol.cx, titleY, titleMax, titleW: endCol.w - 2 * m - 80, tagline, taglineY, taglinePx, taglineLH: tLH, panelY, monoPx: mono, rows: inst.rows, wrapped: inst.wrapped, rowH, padX: 36, lineY0: panelY + 25 * k + rowH / 2, footerPx: Math.max(28 * k, min.read), footerY: panelY + ph + 60, caret: [Math.round(mono * 0.53), Math.round(mono * 1.13)] },split, stage: { x: 0, y: 0, w: W, h: H }, band: null, uiFull, safe: S, zones,roles: [],};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchLook.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchLook.tsnew file mode 100644index 0000000..1a6cea2--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchLook.ts@@ -0,0 +1,211 @@+// THE LOOK. A launch film has to look like the product it launches, not like us. The template draws every+// colour, typeface and shape through one resolved look, built here from the spec's `look` block:+//+// look.base "drawn" | "clean" | any look registered with registerLook(): the starting point (ink and+// blooms with hand lettering, or a quiet canvas with set type), never the only option.+// `preset` is the old shorthand for look.base and keeps working.+// look.from a brand file from `tools/brand.mjs import` (import brand from "<dir>/brand.json"): its+// colours fill the palette and its logo the chat header. Explicit fields always win.+// look.palette any of bg, card, ink, soft, mute, line, chip, accent, accentDeep, paper, over the base.+// look.fonts { display, text, mono }: each a family name and a local font file, imported by path+// (import serif from "../../assets/fonts/MySerif-Bold.ttf"). The file travels inside the+// film (no network), is registered as a FontFace before the first frame, and every measure,+// wrap and reading time is taken from its own glyph advances, never from another face.+// look.shape corner radius, the user bubble (rounded, square, none), the composer (box or bar), the+// button's shape and label.+// look.chat the chat window as the product draws its own: header on or off, title and subtitle, a+// logo (a brand element) in place of the dot, the user bubble's and the answer's colours.+// A product with no chat: use `kind: "ui"` asks, its own screen with its command bar.+//+// A custom colour can never make an unreadable film: resolveLook checks every pair the film sets text in+// (WCAG AA: 4.5:1 for body text, 3:1 for large type and the hint text) wherever a pair has a colour the look+// changed, and throws naming the token and the pair.+import { C, SANS, MONO } from "./launchKit";+import { estWidth, monoWidth } from "./launchLayout";+import { parseTTF, type Font } from "../three-core/ttf";+import type { BrandElement } from "./brandKit";++/** A font file as the build carries it: imported by path, its bytes inside the film (tools/overlay.mjs). */+export type FontFile = { path: string; format: "ttf" | "otf" | "woff2"; data: string };+export type LookFont = { family: string; file: FontFile };+export type PaletteKey = "bg" | "card" | "ink" | "soft" | "mute" | "line" | "chip" | "accent" | "accentDeep" | "paper";+export type Palette = Record<PaletteKey, string> & { shadow: string };+export type LookShape = {+ radius?: number; // corner radius of the window, the composer and the cards, in layout px (default: the base's)+ bubble?: "rounded" | "square" | "none"; // the user's sent message: a rounded chip, a square one, or plain words+ composer?: "box" | "bar"; // the input: a box with the button inside, or one rounded bar+ button?: "pill" | "square"; // the send button's shape+ buttonLabel?: string; // its word ("Generate", "Ask", "Send")+};+export type LookChat = {+ header?: boolean; // the window's header (dot or logo, title, subtitle, rule); false hides it+ title?: string; subtitle?: string; // the header's words (default: the film's title and subtitle)+ logo?: BrandElement; // the product's mark, drawn in place of the dot (a brand.mjs import element)+ bubble?: { fill: string; ink: string }; // the user's sent message+ reply?: { fill: string; ink: string }; // the answer: its card's frame and its byline+};+/** What `tools/brand.mjs import` writes as brand.json (only what a look reads). */+export type BrandFile = { elements: Record<string, { w: number; h: number; parts: readonly unknown[] }>; palette: { hex: string; share: number }[]; fonts?: string[] }; // (as a JSON import types it: parts are brandKit's BrandPart)+export type LaunchLook = {+ base?: string;+ from?: BrandFile;+ palette?: Partial<Record<PaletteKey, string>>;+ fonts?: { display?: LookFont; text?: LookFont; mono?: LookFont };+ shape?: LookShape;+ chat?: LookChat;+};+export type FontFn = (weight: number, px: number) => string;+export type ResolvedLook = {+ base: string;+ clean: boolean; // the base's grammar: set type, travels and an iris (clean), or ink (drawn)+ palette: Palette;+ onAccent: string; // the label colour on the accent (white unless the accent is pale)+ custom: boolean; // anything beyond the base and the legacy accent+ fonts: { display: FontFn; text: FontFn; mono: (px: number) => string };+ /** widths at px, from the chosen face: custom fonts by their own advances, the stock ones by the template's estimates */+ measure: { text: (t: string, px: number) => number; display: (t: string, px: number) => number; mono: (t: string, px: number) => number };+ wrap: (text: string, px: number, maxW: number) => string[];+ wrapDisplay: (text: string, px: number, maxW: number) => string[]; // the same, by the display face (set words)+ customDisplay: boolean; // the display face is a font file (measured from it), not the stock set sans+ /** the width of text set in a CSS font string the look made: a custom face by its own advances, else the stock estimate */+ measureFont: (t: string, font: string) => number;+ shape: Required<Omit<LookShape, "radius" | "buttonLabel">> & { radius?: number; buttonLabel?: string };+ chat: LookChat;+ faces: { family: string; file: FontFile }[]; // the font files to register before the first frame+ /** the pointer's colours: the stock black arrow with a white edge, a light arrow with a dark edge on a dark ground */+ pointer: { fill: string; edge: string };+};++// the clean base: a quiet canvas, one accent, type as the design. Our own palette, drawn for it.+export const CLEAN: Palette = { bg: "#f3f2ef", card: "#ffffff", ink: "#15161a", soft: "#5b5f68", mute: "#9da1a9", line: "#e4e4e1", chip: "#efefec", accent: "#2f54eb", accentDeep: "#2442bf", paper: "#fbfbf9", shadow: "rgba(20,24,30,0.08)" };+type LookDef = { clean: boolean; palette: Palette };+const LOOKS = new Map<string, LookDef>([["drawn", { clean: false, palette: C as Palette }], ["clean", { clean: true, palette: CLEAN }]]);+/** A new starting point: a name, the grammar it draws with (clean or drawn), and its palette. */+export const registerLook = (name: string, def: { clean: boolean; palette: Palette }) => { LOOKS.set(name, def); };+export const lookNames = () => [...LOOKS.keys()];++// ---------------------------------------------------------------- colour and contrast (WCAG 2)+const rgb = (hex: string): [number, number, number] => {+ const m = /^#([0-9a-f]{6})$/i.exec(hex.trim()); if (!m) throw new Error(`look: colour '${hex}' is not #rrggbb`);+ const v = parseInt(m[1], 16); return [(v >> 16) & 255, (v >> 8) & 255, v & 255];+};+const lum = (hex: string) => { const [r, g, b] = rgb(hex).map((c) => { const s = c / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; }); return 0.2126 * r + 0.7152 * g + 0.0722 * b; };+/** The contrast ratio of two colours, 1 to 21. */+export const contrast = (a: string, b: string) => { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); };+const sat = (hex: string) => { const [r, g, b] = rgb(hex), mx = Math.max(r, g, b), mn = Math.min(r, g, b); return mx === 0 ? 0 : (mx - mn) / mx; };+/** Every pair the template sets text in: [text token, ground token, the bar, what it is]. */+export const TEXT_PAIRS: [PaletteKey, PaletteKey, number, string][] = [+ ["ink", "card", 4.5, "the chat's words and the product's rows"],+ ["ink", "bg", 4.5, "the word pages and the end card"],+ ["ink", "paper", 4.5, "the typed prompt"],+ ["ink", "chip", 4.5, "the sent message"],+ ["soft", "bg", 4.5, "the tagline and the footer"],+ ["soft", "card", 4.5, "the product's secondary words"],+ ["mute", "paper", 3, "the composer's placeholder (hint text, large-type bar)"],+ ["mute", "card", 3, "the header's subtitle (hint text, large-type bar)"],+ ["accent", "bg", 3, "accent words on the page (large type)"],+];+/** Throws naming the token when a pair the look changed falls under its bar. `changed`: the tokens the look set. */+export const checkContrast = (p: Palette, changed: Set<string>, extra: [string, string, number, string][] = []) => {+ const bad: string[] = [];+ for (const [t, g, bar, what] of TEXT_PAIRS) {+ if (!changed.has(t) && !changed.has(g)) continue;+ const fg = p[t], r = contrast(fg, p[g]);+ if (r < bar) bad.push(`'${t}' ${fg} on '${g}' ${p[g]} is ${r.toFixed(2)}:1, under ${bar}:1 (${what})`);+ }+ for (const [fg, bg, bar, what] of extra) { const r = contrast(fg, bg); if (r < bar) bad.push(`${what}: ${fg} on ${bg} is ${r.toFixed(2)}:1, under ${bar}:1`); }+ if (bad.length) throw new Error(`look: unreadable colours. ${bad.join("; ")}. Change the token named first (a darker ink or a lighter ground) until each pair reaches its bar (WCAG AA)`);+};++/** A brand file's colours as palette tokens: the most saturated as the accent; when the brand has a dark and a+ * light colour, the darkest as ink and the lightest as the ground (or the other way round for a dark brand,+ * whose most-used colour is dark). Only what the brand file says; the rest stays the base's. */+export const paletteFromBrand = (b: BrandFile): Partial<Record<PaletteKey, string>> => {+ const cols = b.palette.map((p) => p.hex.toLowerCase()).filter((h) => /^#[0-9a-f]{6}$/.test(h));+ if (!cols.length) return {};+ const out: Partial<Record<PaletteKey, string>> = {};+ const accent = [...cols].sort((x, y) => sat(y) - sat(x))[0]; if (sat(accent) > 0.35) out.accent = accent;+ const byL = [...cols].sort((x, y) => lum(x) - lum(y)), dark = byL[0], light = byL[byL.length - 1];+ if (contrast(dark, light) >= 7) { if (lum(cols[0]) < 0.2) { out.bg = dark; out.ink = light; } else { out.ink = dark; } }+ return out;+};+/** The brand file's logo: an element named like a logo or a mark, else its first. */+export const logoFromBrand = (b: BrandFile): BrandElement | undefined => { const names = Object.keys(b.elements); const n = names.find((x) => /logo|mark|symbol|icon/i.test(x)) ?? names[0]; return n ? (b.elements[n] as unknown as BrandElement) : undefined; };++// ---------------------------------------------------------------- fonts+const FONT_CACHE = new Map<string, Font>();+const fontOf = (f: LookFont, role: string): Font => {+ if (!f || typeof f.family !== "string" || !f.family) throw new Error(`look.fonts.${role}: give { family, file } (a family name and the imported font file)`);+ if (!f.file || typeof f.file.data !== "string") throw new Error(`look.fonts.${role}: '${f.family}' has no font file. Import it by path: import f from "../../assets/fonts/<file>.ttf", then { family: "${f.family}", file: f }`);+ if (f.file.format !== "ttf") throw new Error(`look.fonts.${role}: ${f.file.path} is a .${f.file.format}; the film measures every line from the font's own glyphs, which needs the TrueType .ttf of the face (convert it, or use the .ttf the family ships)`);+ const key = `${f.file.path}#${f.file.data.length}`;+ if (!FONT_CACHE.has(key)) FONT_CACHE.set(key, parseTTF(f.file.data));+ return FONT_CACHE.get(key)!;+};+/** Width of text at px in a parsed face: the glyphs' own advances and pair kerning, as a canvas sets them. */+export const fontWidth = (font: Font, text: string, px: number) => {+ let w = 0, prev = -1; const s = px / font.unitsPerEm;+ for (const ch of text) { const g = font.glyphIndex(ch.codePointAt(0)!); if (prev >= 0) w += font.kerning(prev, g); w += font.glyph(g).advance; prev = g; }+ return w * s;+};+const css = (family: string, fallback: string) => (w: number, px: number) => `${w} ${px}px "${family}", ${fallback}`;+const SANS_FALLBACK = `"Avenir Next", "Helvetica Neue", Helvetica, Arial, sans-serif`;++/** Registers the look's font files as FontFaces (in a page; in node it does nothing), once per family. */+const registered = new Set<string>();+export const registerFaces = (faces: ResolvedLook["faces"]) => {+ const g = globalThis as unknown as { FontFace?: new (f: string, s: ArrayBuffer, d?: Record<string, string>) => { load(): Promise<unknown> }; document?: { fonts: { add(f: unknown): void } } };+ if (!g.FontFace || !g.document) return;+ for (const { family, file } of faces) {+ if (registered.has(family)) continue; registered.add(family);+ const bin = atob(file.data), u8 = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);+ // (one face for every weight: the film is measured from this face's own advances, so the browser must not+ // swap in a synthesized bold that is wider than the measure)+ const face = new g.FontFace(family, u8.buffer, { weight: "1 1000", style: "normal" }); g.document.fonts.add(face); void face.load();+ }+};++// ---------------------------------------------------------------- resolve+export type LookSpec = { preset?: string; accent?: string; look?: LaunchLook };+export const resolveLook = (spec: LookSpec): ResolvedLook => {+ const L = spec.look ?? {}, base = L.base ?? spec.preset ?? "drawn";+ if (spec.preset !== undefined && L.base !== undefined && spec.preset !== L.base) throw new Error(`look: preset '${spec.preset}' and look.base '${L.base}' disagree; keep one (preset is the shorthand for look.base)`);+ const def = LOOKS.get(base); if (!def) throw new Error(`look: base '${base}' is not a registered look (${lookNames().join(", ")}); registerLook() adds one`);+ const fromP = L.from ? paletteFromBrand(L.from) : {}, own = L.palette ?? {};+ for (const [k, v] of Object.entries(own)) { if (!(k in CLEAN)) throw new Error(`look.palette: '${k}' is not a token (${Object.keys(CLEAN).filter((x) => x !== "shadow").join(", ")})`); rgb(String(v)); }+ const legacy = spec.accent ? { accent: spec.accent } : {};+ const palette: Palette = { ...def.palette, ...(def.clean ? legacy : {}), ...fromP, ...own } as Palette;+ const changed = new Set([...Object.keys(fromP), ...Object.keys(own)]);+ const chat: LookChat = { ...(L.from ? { logo: logoFromBrand(L.from) } : {}), ...(L.chat ?? {}) };+ const extra: [string, string, number, string][] = [];+ if (chat.bubble) extra.push([chat.bubble.ink, chat.bubble.fill, 4.5, "look.chat.bubble (ink on fill)"]);+ if (chat.reply) extra.push([chat.reply.ink, palette.card, 4.5, "look.chat.reply.ink on the card"]);+ // the label on the accent (the button, the product's action): white, or on a pale accent the darker of ink+ // and ground; whichever it is, it must reach the large-type bar+ const onAccent = contrast("#ffffff", palette.accent) >= 3 ? "#ffffff" : contrast(palette.ink, palette.accent) >= contrast(palette.bg, palette.accent) ? palette.ink : palette.bg;+ if (changed.has("accent") || changed.has("ink") || changed.has("bg")) extra.push([onAccent, palette.accent, 3, `the button's label on 'accent' ${palette.accent}`]);+ checkContrast(palette, changed, extra);+ const F = L.fonts ?? {}, faces: ResolvedLook["faces"] = [];+ const pick = (role: "display" | "text" | "mono") => { const f = F[role]; if (!f) return null; const font = fontOf(f, role); faces.push({ family: f.family, file: f.file }); return { f, font }; };+ const d = pick("display"), t = pick("text"), mo = pick("mono");+ const textFn: FontFn = t ? css(t.f.family, SANS_FALLBACK) : SANS;+ const displayFn: FontFn = d ? css(d.f.family, SANS_FALLBACK) : t ? textFn : SANS;+ const monoFn = mo ? (px: number) => `${px}px "${mo.f.family}", "SF Mono", Menlo, monospace` : MONO;+ const textW = t ? (s: string, px: number) => fontWidth(t.font, s, px) : estWidth;+ const measure = {+ text: textW,+ // (the stock display face is the heavy set sans, wider than the body estimate: the template's 1.12)+ display: d ? (s: string, px: number) => fontWidth(d.font, s, px) : t ? textW : (s: string, px: number) => estWidth(s, px) * 1.12,+ mono: mo ? (s: string, px: number) => fontWidth(mo.font, s, px) : monoWidth,+ };+ const wrapBy = (m: (s: string, px: number) => number) => (text: string, px: number, maxW: number) => { const out: string[] = []; let line = ""; for (const w of text.split(" ")) { const s = line ? `${line} ${w}` : w; if (!line || m(s, px) <= maxW) line = s; else { out.push(line); line = w; } } out.push(line); return out; };+ const wrap = wrapBy(measure.text), wrapDisplay = d ? wrapBy(measure.display) : wrap;+ const byFamily = [d, t, mo].filter((x): x is { f: LookFont; font: Font } => !!x);+ const measureFont = (s: string, fontStr: string) => { const px = Number(/([\d.]+)px/.exec(fontStr)?.[1] ?? 40), hit = byFamily.find((x) => fontStr.includes(`"${x.f.family}"`)); return hit ? fontWidth(hit.font, s, px) : estWidth(s, px); };+ const S = L.shape ?? {};+ if (S.bubble && !["rounded", "square", "none"].includes(S.bubble)) throw new Error(`look.shape.bubble: '${S.bubble}' is not rounded, square or none`);+ if (S.composer && !["box", "bar"].includes(S.composer)) throw new Error(`look.shape.composer: '${S.composer}' is not box or bar`);+ if (S.button && !["pill", "square"].includes(S.button)) throw new Error(`look.shape.button: '${S.button}' is not pill or square`);+ const custom = changed.size > 0 || faces.length > 0 || Object.keys(S).length > 0 || Object.keys(chat).length > 0;+ return { base, clean: def.clean, palette, onAccent, custom, fonts: { display: displayFn, text: textFn, mono: monoFn }, measure, wrap, wrapDisplay, customDisplay: !!d, measureFont, pointer: contrast("#111111", palette.bg) >= 3 ? { fill: "#111", edge: "#fff" } : { fill: contrast("#ffffff", palette.bg) >= contrast(palette.ink, palette.bg) ? "#fff" : palette.ink, edge: "#111" }, shape: { bubble: S.bubble ?? "rounded", composer: S.composer ?? "box", button: S.button ?? "pill", radius: S.radius, buttonLabel: S.buttonLabel }, chat, faces };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.tsindex 13ff45f..cd5c1f2 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts@@ -25,14 +25,15 @@import { probeRect, type Ctx, type Env, type P } from "./core";import type { Film } from "./film";import {- C, SANS, MONO, camLerp, caretAt, charTimes, clamp, drawChatFrame, expo, inOut, inkCard, inkDrop,+ C, TEXT_SHOWN, camLerp, caretAt, charTimes, clamp, drawChatFrame, expo, inOut, inkCard, inkDrop,lerp, lerpP, out3, plateLayer, pointer, press, ramp, rr, spring, toScreen, typedAt, useCam, type Cam, type Drop, type ChatGeom, type Rect,} from "./launchKit";-import { launchLayout, estWidth, installRows, wrapEst, SHAPES, type LaunchLayout, type Shape } from "./launchLayout";-import { chatGeom } from "./launchKit";-import { beatGrid, bloomFrame, bloomRadius, makeCut, pic, type, typeFrame, type Seg, type TypeLine } from "./launchCut";-import { measure, writeOn, setType } from "./kinetic";-import { drawProductUI, springLand, uiActionAt, uiCommandAt, uiSettles, uiWindow, type ProductUI, type UiTheme } from "./productUI";+import { launchLayout, estWidth, installRows, SHAPES, type LaunchLayout, type Shape } from "./launchLayout";+import { resolveLook, registerFaces, CLEAN as LOOK_CLEAN, type LaunchLook } from "./launchLook";+import { chatGeom, inkDropAt } from "./launchKit";+import { beatGrid, bloomFrame, bloomRadius, makeCut, pic, type, type Seg, type TypeLine } from "./launchCut";+import { inkSpan, measure, writeOn, setType } from "./kinetic";+import { drawProductUI, springLand, uiActionAt, uiActionRect, uiCommandAt, uiSettles, uiWindow, type ProductUI, type UiTheme } from "./productUI";import { relay, checkRelay, type MotifPose, type Seam } from "./motif";import { launchAudio, type LaunchCue } from "./launchSound";import { fitScore, limiter, renderPiece } from "./music/render";@@ -46,6 +47,13 @@ import { composePiece, stretchIndex, withStretch, type Material } from "./music/import { perform } from "./music/perform";import { beatsPerBar } from "./music/plan";import { novelty } from "./music/novelty";+import { drawEndCard, endCardLayout, type EndCardSpec } from "./endCard";+import { drawEl } from "./brandKit";+import type { ShipMeta } from "./shipMeta";+import type { MotionMeta } from "./motionMeta";+import { readS } from "./readable";+import { TEMPERAMENTS } from "./motionKit";+import { speedCeiling } from "./seams";/** chat -> Generate -> a plate drawing itself in the answer card (the default kind) */export type PlateAsk = {@@ -72,9 +80,15 @@ export type LaunchSpec = {tagline: string; // the one line under the name on the end cardinstall: string[]; // the exact lines a viewer copies; held on screen for the whole end cardfooter?: string; // small print under the panel (where it runs, the repo)+ // the clean end card's layout: "stack" (default) centres name, line, install panel and footer on one+ // axis; "grid" lays them on endCard.ts's asymmetric grid: the name top-left with the drop as its full+ // stop, the line and the install lines under it, the footer as a stamp on the right. Clean preset only.+ endCard?: "stack" | "grid";+ checks?: ShipMeta; // what the film tells the ship checks (shipMeta.ts): its length budget { target, max } in seconds, layoutExempt for a deliberately dense UI beat, and in `none` only a check with truly nothing to look at+ motion?: MotionMeta; // what the film tells the motion scans (motionMeta.ts): the brand's temperament ("calm", "lively", "snappy") and its colours (#rrggbb), both from the briefbpm: number; // the beat grid: bpm comes from the brief (the score composed for it)fps?: 30 | 60; // 60 for UI-heavy films (smoother scrolls and springs); the timing is the same- askBeats?: number; typeBeats?: number; endBeats?: number; // default 6, 4, 8+ askBeats?: number; typeBeats?: number; endBeats?: number; // default 6, 6 (a word page has a travel in, the words' own arrival, their read and their sink), 8claimBar?: number; // land the end card on this bar's downbeat, counting from bar 0 (solves the last ask)// The score: a piece COMPOSED for this product's brief (references/music/compose.md), or null for// a silent film. Required, so no film inherits a score by default. anidoodle's own pieces are@@ -84,7 +98,8 @@ export type LaunchSpec = {audio?: Film["audio"]; // or your own finished mix; wins over score and sfxlimit?: boolean; // let a look-ahead limiter take the score's last peaks so it reaches -14 LUFS (default off: the peak ceiling wins)shape?: Shape; // the frame: 16x9 (default), 1x1, 4x5, 9x16. Every shape is re-composed by launchLayout, never cropped; film.reshape(s) gives the same film in another shape- preset?: "drawn" | "clean"; // the look: ink, blooms and hand lettering (default), or a quiet canvas, one accent and set type+ preset?: string; // the shorthand for look.base: "drawn" (ink, blooms and hand lettering, default) or "clean" (a quiet canvas, one accent and set type)+ look?: LaunchLook; // how the film looks like YOUR product: base, palette, fonts, shape, chat, from (launchLook.ts; references/workflows/launch-video-kit.md, Looks)sfx?: boolean; // sound cues from the picture's timing (default true; false = the score alone)motif?: boolean; // the relay into the end card (default true): the drop becomes the mark's dotcaptions?: "sidecar" | "burn"; // .srt/.vtt only (default), or also burned into their own band (phone shapes)@@ -92,7 +107,8 @@ export type LaunchSpec = {};// the clean preset: a quiet canvas, one accent, type as the design. Our own palette, drawn for it.-export const CLEAN = { bg: "#f3f2ef", card: "#ffffff", ink: "#15161a", soft: "#5b5f68", mute: "#9da1a9", line: "#e4e4e1", chip: "#efefec", accent: "#2f54eb", accentDeep: "#2442bf", paper: "#fbfbf9", shadow: "rgba(20,24,30,0.08)" };+// (it lives in launchLook.ts with the other looks)+export const CLEAN = LOOK_CLEAN;// anidoodle's own pieces (the demos and our launch score) are examples of the composer, never a// user's soundtrack. Refused by identity, by title and by content (the novelty gate), so a thin or@@ -108,25 +124,115 @@ const refuseOurs = (score: () => Piece | Material) => {const v = novelty(asPiece(score)(), corpus);if (!v.pass) throw new Error(`launchTemplate: "${score().title}" is too close to anidoodle's own "${v.worst.name.replace(/ #\d+$/, "")}" (similarity ${v.worst.score}, ${v.worst.reusedFragments} reused 6-note fragments); compose a score for this product's brief (references/music/compose.md) or pass score: null`);};-const TYPE_O = { lead: -4, stagger: 18 }; // the word starts as the bloom closes over the frame; lines run on without a gap-const TR = 16; // a bloom-in: frames it takes to open over the previous scene (a seam between kinds, with no word page)-const DL = 14; // the motif relay: the drop's flight into the end card, in frames (it lands ON the end card's first frame)+// THE CLEAN PRESET'S SEAMS TRAVEL (references/motion-grammar.md, 5. Continuous canvas). Its asks and its+// word pages are places on one canvas, each the size of the frame, and the camera travels from one to the+// next: the next place is in the world before the move starts, nothing is swapped in place, so no seam+// reads as a slide (motionscan slidecut) and no text is left in slivers by an iris crawling over it+// (layerscan exits). The drawn preset keeps its ink blooms. TRV is how long a travel takes, in frames at+// 30 fps: type may never move faster than half the speed ceiling (layerscan fasttext: 0.5 x 2.5 frame+// widths a second), and a travel of one frame width on a sine ease peaks at pi/2 x its mean speed, so+// with a tenth in hand it takes (pi/2) / (0.9 x 1.25) s = 1.4 s. It is the same in every shape, so the+// cut and the sound never change with the shape. (The glide below peaks lower, at 1.11 x its mean, so+// the bound is generous.)+const TRV = Math.ceil((Math.PI / 2 / (0.9 * 0.5 * 2.5)) * 30);+/**+ * The travel's ease, a GLIDE: its speed rises in a straight line over the first tenth, cruises, and falls+ * over the last tenth (no step at either end, peak 1.11 x the mean). A sine ease crept under a pixel a+ * frame for its first and last frames, and a dense screen of type shifted that slowly reads as swapped,+ * not moved (motionscan slidecut cannot tell the camera is travelling).+ */+const GLIDE = 0.1;+const glide = (q: number) => { const c = clamp(q), r = GLIDE, v = 1 / (1 - r); return c < r ? (v * c * c) / (2 * r) : c > 1 - r ? 1 - (v * (1 - c) * (1 - c)) / (2 * r) : v * (c - r / 2); };+/**+ * A scene drawn at another place in the one world. Every transform the scene sets is scaled by z about+ * (cx, cy) and moved by (dx, dy) first, so a scene that sets its own camera (setTransform) can sit beside+ * another on one canvas, or creep closer as a whole. With `fade`, each line of text gets an opacity from+ * where it lands (logical px), so a phone shape's travel fades text before it reaches a platform zone.+ */+const placed = (ctx: Ctx, env: Env, o: { z?: number; c?: P; d?: P; fade?: (x0: number, y0: number, x1: number, y1: number, d: P) => number }): Ctx => {+ const z = o.z ?? 1, S = env.scale, [cx, cy] = o.c ?? [0, 0], [dx, dy] = o.d ?? [0, 0], ox = (cx * (1 - z) + dx) * S, oy = (cy * (1 - z) + dy) * S, fade = o.fade;+ if (z === 1 && !ox && !oy && !fade) return ctx;+ const setT = (a: number, b: number, c: number, d: number, e: number, f: number) => ctx.setTransform(z * a, z * b, z * c, z * d, z * e + ox, z * f + oy);+ return new Proxy(ctx, {+ get(t, k) {+ if (k === "setTransform") return (...a: unknown[]) => { if (typeof a[0] === "object" && a[0]) { const m = a[0] as DOMMatrix2DInit; return setT(m.a ?? 1, m.b ?? 0, m.c ?? 0, m.d ?? 1, m.e ?? 0, m.f ?? 0); } return setT(...(a as [number, number, number, number, number, number])); };+ if (k === "resetTransform") return () => setT(1, 0, 0, 1, 0, 0);+ if (k === "fillText" && fade) return (s: string, x: number, y: number, mw?: number) => {+ const m = t.getTransform(), q = t.measureText(s), x0 = x - q.actualBoundingBoxLeft, x1 = x + q.actualBoundingBoxRight, y0 = y - q.actualBoundingBoxAscent, y1 = y + q.actualBoundingBoxDescent;+ const xs = [m.a * x0 + m.c * y0 + m.e, m.a * x1 + m.c * y1 + m.e], ys = [m.b * x0 + m.d * y0 + m.f, m.b * x1 + m.d * y1 + m.f];+ const k = fade(Math.min(...xs) / S, Math.min(...ys) / S, Math.max(...xs) / S, Math.max(...ys) / S, [dx, dy]), was = t.globalAlpha;+ (t as unknown as Record<symbol, number>)[TEXT_SHOWN] = Math.max(0, k); // (inkCard fades a byline's dot with its words)+ if (k <= 0) return; t.globalAlpha = was * k; if (mw === undefined) t.fillText(s, x, y); else t.fillText(s, x, y, mw); t.globalAlpha = was;+ };+ const v = Reflect.get(t, k); return typeof v === "function" ? v.bind(t) : v;+ },+ set(t, k, v) { return Reflect.set(t, k, v); },+ });+};+// THE DRAWN LOOK'S WORDS WRITE THEMSELVES, with no pen in the frame. A hand-lettering pen crosses a line in+// 18 frames, at up to 90 px a frame on a phone frame: nearly twice what a lively brand allows (motionscan+// temperament), and the eye follows the pen, not the word. The ink still goes down stroke by stroke.+const PEN = false;+const DL0 = 14; // the motif relay: the drop's flight into the end card, in frames (it lands ON the end card's first frame); DL in the filmconst LIFT = 6; // ...after a bead of ink swells on its source for this many framesconst isChat = (a: LaunchAsk): a is PlateAsk => !a.kind || a.kind === "plate";-// the timing inside one chat ask, from its prompt and its length (`a0` delays the typing past a bloom-in)-const askTiming = (prompt: string, i: number, ASK: number, a0 = 0) => {+// the timing inside one chat ask, from its prompt and its length (`a0` delays the typing: after a travel+// in, typing starts halfway through it, as the composer arrives, the way a split beat's words rise)+// SETTLE: once the prompt is typed, the hook's composer docks (or the close-up eases out to the room) over+// this many frames, and Generate is pressed only once it has landed: a button is never pressed on the move.+// An in-out over a second keeps type under half the speed ceiling on every shape (layerscan fasttext); the+// expo ease it replaced moved the docking prompt at 118 px a frame on a phone frame.+const SETTLE = 30;+/**+ * THE CLEAN HOOK'S DOCK travels as one object and stays that object: the big composer glides down whole (its+ * own size, its own line breaks) to the foot of the window in MOVE frames, and that is the dock. It never+ * shrinks: a composer that shrank as it moved, its words rewrapping halfway, replaced 64 % of a clean frame in+ * 0.1 s (a slide cut to motionscan), and one that scaled down once it had landed read to a fresh critic as a+ * second move (cc1-1). MOVE is short enough that the glide reads to motionscan as a move (over 10 px a frame+ * at 60 fps on 16:9) and long enough that its type stays under half the speed ceiling on a phone frame+ * (layerscan fasttext). (`shrink` stays in the record, at 0 frames, for the grammar's dock window.)+ */+// REST: once landed it rests 15 frames before Ask is pressed (the room's creep still moving), the time the+// scale used to take: the typed question is read whole before it is sent (framecheck reading time, 1.5 s).+const CLEAN_DOCK = { at: -2, move: 14, shrink: 0, rest: 15 };+/**+ * The first prompt is already being typed at frame 0 (a silent-readable hook), so frame 0, the thumbnail,+ * shows what is typed so far. It must end on a whole word ("a lighthouse at", never "a lighthouse at s":+ * a fresh critic read the broken word as a broken frame). Typing runs from `a` to `b`, keeping each key's+ * share of the line (`raw`); this returns the start nearest `want` at which frame 0 falls between the last+ * key of a word and the space after it.+ */+export const wholeWordStart = (prompt: string, raw: number[], b: number, want: number) => {+ const last = raw[raw.length - 1] || 1, r = (j: number) => raw[j] / last;+ let best = want, gap = Infinity;+ for (let e = 1; e < prompt.length; e++) {+ if (prompt[e] !== " " || prompt[e - 1] === " ") continue;+ // key e-1 (the word's last) at or before frame 0, key e (the space) after it+ const hi = (-r(e - 1) * b) / (1 - r(e - 1)), lo = (-r(e) * b) / (1 - r(e)) + 0.25;+ if (lo > hi) continue;+ const a = clamp(want, lo, hi), d = Math.abs(a - want); if (d < gap) { gap = d; best = a; }+ }+ return best;+};+// `dock`: where the composer's settle starts against the last key, and how long it takes (the clean hook's+// dock, CLEAN_DOCK, is its own); `fly`: the ink drop's flight to the answer card, in frames (14, or the clean+// look's, from its distance)+const askTiming = (prompt: string, i: number, ASK: number, a0 = 0, dock: { at: number; len: number } = { at: -8, len: SETTLE }, fly = 14) => {const raw = charTimes(prompt, 0, 1, 7 + i * 4), last = raw[raw.length - 1] || 1;- const b = Math.round(ASK * 0.25) + a0, a = i === 0 ? -Math.round(b * 1.2) : 4 + a0; // the first prompt is under way at frame 0+ const b = Math.round(ASK * 0.25) + a0, a = i === 0 ? wholeWordStart(prompt, raw, b, -Math.round(b * 1.2)) : 4 + a0; // the first prompt is under way at frame 0, on a whole wordconst times = raw.map((t) => a + (t / last) * (b - a));- const down = b + 16, up = down + 5, drop: Drop = { t0: up + 5, land: up + 19, full: up + 40 };+ const down = b + dock.at + dock.len + 2, up = down + 5, drop: Drop = { t0: up + 5, land: up + 5 + fly, full: up + 26 + fly };return { times, b, down, up, drop };};// a UI ask: the ask typed into the product's command bar (if it has a prompt), then its action pressed-const uiTiming = (prompt: string | undefined, i: number, ASK: number, a0: number, split = false) => {- const b = Math.round(ASK * (prompt ? 0.3 : split ? 0.13 : 0.2)) + a0; // a split beat's words are the wait: its press follows them+const uiTiming = (prompt: string | undefined, i: number, ASK: number, a0: number, split = false, travelled = false) => {+ // a split beat's words are the wait: its press follows them. After a travel (clean) they rose on the way+ // in and are read as it lands, so the press comes 2 frames after: the after state then has the rest of+ // the beat to be read (a row's new tag needs its own reading time before the next seam)+ const b = split && travelled ? a0 + 2 : Math.round(ASK * (prompt ? 0.3 : split ? 0.13 : 0.2)) + a0;let times: number[] = [];- if (prompt) { const raw = charTimes(prompt, 0, 1, 11 + i * 4), last = raw[raw.length - 1] || 1, a = i === 0 ? -Math.round(b * 0.8) : 6 + a0; times = raw.map((t) => a + (t / last) * (b - a)); }+ if (prompt) { const raw = charTimes(prompt, 0, 1, 11 + i * 4), last = raw[raw.length - 1] || 1, a = i === 0 ? wholeWordStart(prompt, raw, b, -Math.round(b * 0.8)) : 6 + a0; times = raw.map((t) => a + (t / last) * (b - a)); }const down = b + 14, up = down + 5;return { times, b, down, up, drop: { t0: up + 2, land: up + 2, full: up + 2 } as Drop };};@@ -139,34 +245,165 @@ export type LaunchFilm = Omit<Film, "reshape"> & {timing: { base: number; len: number; tin: number; b: number; down: number; up: number; drop: Drop; times: number[] }[]; // each ask's own timing, content frames at 30 fpscaptions: { from: number; to: number; text: string }[]; // = meta.captionsclaims: string[]; // every claim the film makes, each to be listed in facts.json with its source (tools/facts.mjs)+ // the moves the film is built from, as data (content frames at 30 fps, world px), for tests and critics:+ // each chat ask's thread scroll, every travel's direction, each word page's sink, the end card's bloom,+ // and where the motif's drop swells before it flies+ grammar: {+ scrolls: { i: number; d: number; from: number; len: number }[];+ travels: { seam: string; ax: P }[];+ pages: { i: number; set: number; out: number }[];+ endBloom: { frames: number; radius: number };+ lift: P;+ endCard: { creep: P; cx: number; group: [number, number]; logo: Rect | null; tagline: string[]; taglineW: number[]; room: [number, number] }; // + the clean card's tagline lines, their measured widths, and the x span they may use (inside the phone-safe rectangle) // the point the end card's settle zooms about, the card's axis, and its name-and-dot group's ink, left and right+ rests: { i: number; tip: P; win: Rect; s: number }[];+ splits: { i: number; lines: string[]; size: number; tall: number; room: Rect }[];+ // the clean hook's dock (null without one): the frames it glides whole and the frames it then scales in, the+ // hook's and the dock's prompt size, the docked composer, the chat window, and where the thread's view ends+ dock: { move: [number, number]; shrink: [number, number]; creep: number; heroPx: number; dockPx: number; composer: Rect; window: Rect; viewBottom: number } | null; // each split beat's words as set: their lines, size, the height they take, and their column+ // the drawn hook's dock (null without one): its frames (30 fps units) and its fastest point on screen, px a+ // 30 fps frame, read off the composer's corners, its button and its type as the camera sees them+ heroDock: { frames: [number, number]; peak: number; wraps: number } | null;+ // the last ask's words with the motif (null without): the content frame they have sunk by, and the frames the+ // drop flies over (it leaves its bead at the first, lands as the end card's dot at the second)+ lastWords: { gone: number; flight: [number, number] } | null;+ // each chat ask's ink drop: its flight (content frames) and its fastest point on screen, px a 30 fps frame+ drops: { i: number; flight: [number, number]; peak: number; landing: number }[];+ };};+/** A travelled string's opacity on a phone shape (its box x0..x1, y0..y1 on screen, its place moved by d):+ * none inside a zone (the top band, the bottom band, the right-hand column; the left side has none), and a+ * fade over `band` px before one, measured from where it rests, so it leaves in some five frames of the+ * travel, never in one, and a string resting near a safe edge does not dim the moment a travel starts. */+export const zoneFadeOf = (S: { x: number; y: number; w: number; h: number }, band = 120) => {+ const dist = (y0: number, x1: number, y1: number) => Math.min(S.x + S.w - x1, y0 - S.y, S.y + S.h - y1);+ return (_x0: number, y0: number, x1: number, y1: number, d: P) => {+ const now = dist(y0, x1, y1); if (now < 0) return 0;+ const rest = dist(y0 - d[1], x1 - d[0], y1 - d[1]);+ return clamp(now / Math.max(1e-6, rest > 0 ? Math.min(band, rest) : band));+ };+};+/** How far line j of nL has sunk (0..1) at q (0..1) of a page's sink: the last line leaves first, and each+ * next one starts while the one below is 40 % from gone, so some line is always moving. Back to back, each+ * line's ease-in start left still frames between two lines (identical frames at 60 fps, the gate). */+export const sinkOf = (q: number, j: number, nL: number) => { const D = 1 / (1 + (nL - 1) * 0.6), start = (nL - 1 - j) * 0.6 * D; return clamp((q - start) / D); };export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {- const fps = spec.fps ?? 30, m = fps / 30, n = spec.asks.length, shape = spec.shape ?? "16x9", clean = spec.preset === "clean";+ const fps = spec.fps ?? 30, m = fps / 30, n = spec.asks.length, shape = spec.shape ?? "16x9", LK = resolveLook(spec), clean = LK.clean;if (fps !== 30 && fps !== 60) throw new Error(`launchTemplate: fps ${fps}; a launch film runs at 30, or 60 for a UI-heavy film`);if (!(shape in SHAPES)) throw new Error(`launchTemplate: shape '${shape}' is not one of ${Object.keys(SHAPES).join(", ")}`);- if (spec.preset !== undefined && spec.preset !== "drawn" && spec.preset !== "clean") throw new Error(`launchTemplate: preset '${spec.preset}' is not "drawn" or "clean"`);if (!(spec.bpm > 0)) throw new Error("launchTemplate: set bpm from the brief (the tempo of the score composed for this film)");if (spec.score === undefined && !spec.audio) throw new Error("launchTemplate: `score` is required: a piece composed for this product (references/music/compose.md), or null for silence");if (n < 1 || n > 3) throw new Error("launchTemplate: 1 to 3 asks; more is a feature list, not a story");if (spec.score) refuseOurs(spec.score);+ if (spec.endCard !== undefined && spec.endCard !== "stack" && spec.endCard !== "grid") throw new Error(`launchTemplate: endCard '${spec.endCard}' is not "stack" or "grid"`);+ if (spec.endCard === "grid" && !clean) throw new Error('launchTemplate: endCard "grid" is the clean preset\'s card; the drawn look keeps its written name');const chatIdx = spec.asks.map((a, i) => (isChat(a) ? i : -1)).filter((i) => i >= 0), chatOrd = (i: number) => chatIdx.indexOf(i);const burn = spec.captions === "burn" && shape !== "16x9";- const L = launchLayout(shape, { prompts: chatIdx.map((i) => (spec.asks[i] as PlateAsk).prompt), install: spec.install, tagline: spec.tagline, title: spec.title, band: burn });- const PAL = clean ? { ...CLEAN, ...(spec.accent ? { accent: spec.accent } : {}) } : C;- const ACC = spec.accent ?? (clean ? CLEAN.accent : undefined), INK = clean ? PAL.accent : PAL.ink; // the drop, the motif: ink, or the one accent- const G: ChatGeom = clean ? { ...L.chat, theme: CLEAN, drop: INK, iris: true } : L.chat;- const W = L.W, H = L.stage.h, TH = L.thread, CAM = L.cam, CARD = TH.card, VIEW_BOTTOM = TH.viewBottom, k = G.k, minPx = L.phone ? 32 : 18;- const GEN_C: P = [G.GEN.x + G.GEN.w / 2, G.GEN.y + G.GEN.h / 2];+ const L = launchLayout(shape, { prompts: chatIdx.map((i) => (spec.asks[i] as PlateAsk).prompt), install: spec.install, tagline: spec.tagline, title: spec.title, band: burn, wrap: LK.wrap });+ // THE LOOK (launchLook.ts): the stock looks draw exactly as before; a custom one brings its palette, faces,+ // shapes and chat. Its font files are registered as FontFaces before the first frame (in a page).+ registerFaces(LK.faces);+ const PAL = clean || LK.custom ? LK.palette : C;+ const ACC = clean || LK.custom ? PAL.accent : spec.accent, INK = clean ? PAL.accent : PAL.ink; // the drop, the motif: ink, or the one accent+ const G0: ChatGeom = clean ? { ...L.chat, theme: PAL, drop: INK, iris: true, look: LK.custom ? LK : undefined } : LK.custom ? { ...L.chat, theme: PAL, look: LK } : L.chat;+ const W = L.W, H = L.stage.h, CAM = L.cam, k = G0.k, minPx = L.phone ? 32 : 18;const UI_FULL: Rect = L.uiFull;+ const CALM = (spec.motion?.temperament ?? "lively") === "calm" || (typeof spec.motion?.temperament === "object" && spec.motion.temperament.maxSpeed <= TEMPERAMENTS.calm.maxSpeed);+ const DL = DL0;// 9x16: text stays inside the platforms' safe rectangle SAFE (launchLayout.PHONE_SAFE). The camera's// close-ups zoom about a point that stays put, and whatever a move carries toward a zone fades first.const ZONES = L.zones, SAFE = L.safe, SC: P = [SAFE.x + SAFE.w / 2, SAFE.y + SAFE.h / 2];+ // the empty state: on a phone the first ask's composer starts in the middle of the empty thread (the+ // way a chat app opens) and docks at the bottom as Generate is pressed; the hook is the prompt, centred+ // THE HOOK: the first prompt is the hero. It is typed in a big composer in the middle of the frame+ // (at least 64 px type on a phone frame, 56 px on 16x9, wrapping to 2-3 lines, never clipped),+ // which shrinks and docks at the bottom of the chat as Generate is pressed.+ // (clean: it holds as many lines as the longest prompt needs at its size, since the dock is this same+ // composer scaled down, and a later prompt is typed into it)+ // (clean, on 9x16: 40 px narrower, since the hook's composer is also the dock, and docked at the window's+ // foot under the hook's 4 % creep its right edge reached the phone's right-hand zone, where seen() faded+ // it: its accent caret and button see-through, layerscan translucent)+ const HERO = (() => {+ if (!isChat(spec.asks[0])) return null;+ const prompt = spec.asks[0].prompt, min = L.phone ? 64 : 56, inW = ZONES ? G0.CHAT.w - (clean ? 64 : 24) : Math.min(L.phone ? W * 0.9 : W * 0.72, G0.CHAT.w - 60 * k); // most of the width, inside the chat window (on 9x16 all of it: the window is narrower there)+ // (clean: from the smallest size, since this composer is the dock all film long; larger, it left the answer+ // card a thumbnail on 16:9, cc3-1)+ for (let px = clean ? min : L.phone ? 76 : 68; px >= min; px -= 2) {+ const kh = px / 34, genW = 166 * kh, textW = inW - 44 * kh - genW - 44 * kh, lines = LK.wrap(prompt, px, textW).length;+ if (lines > 3 && px > min) continue;+ if (lines > 3) throw new Error(`launchTemplate ${shape}: the first prompt "${prompt}" needs ${lines} lines at the hook's ${min} px; shorten it (the hook must read muted in the first 2 s)`);+ const rows = clean ? Math.min(3, Math.max(lines, ...chatIdx.map((j) => LK.wrap((spec.asks[j] as PlateAsk).prompt, px, textW).length))) : lines;+ // centred in the frame, or on 9x16 in the chat window (which is centred in the safe rectangle)+ const h = 104 * kh + (rows - 1) * Math.round(px * 1.3), fake = ZONES+ ? { x: G0.CHAT.x + (G0.CHAT.w - inW) / 2 - 60 * kh, y: G0.CHAT.y + G0.CHAT.h / 2 - H * 0.5, w: inW + 120 * kh, h: H * 0.5 + h / 2 + 36 * kh }+ : { x: (W - inW) / 2 - 60 * kh, y: 0, w: inW + 120 * kh, h: H * 0.5 + h / 2 + 36 * kh };+ const g = chatGeom(fake, kh, { ...G0.px, gen: 24 * kh }, px, rows, genW);+ return { ...g, CHAT: G0.CHAT, theme: G0.theme, drop: G0.drop, iris: G0.iris } as ChatGeom;+ }+ return null;+ })();+ // the hook's composer, its foot (the middle of its bottom edge) moved to `to` and scaled by s about it: every+ // part of it at once, its type size and its line breaks with it (the clean look's dock)+ const footOf = (g: ChatGeom): P => [g.INPUT.x + g.INPUT.w / 2, g.INPUT.y + g.INPUT.h];+ const scaledComposer = (g: ChatGeom, s: number, to: P): ChatGeom => {+ const [fx, fy] = footOf(g), X = (x: number) => to[0] + (x - fx) * s, Y = (y: number) => to[1] + (y - fy) * s;+ const R = (r: Rect & { r: number }) => ({ x: X(r.x), y: Y(r.y), w: r.w * s, h: r.h * s, r: r.r * s });+ return { ...g, INPUT: R(g.INPUT), GEN: R(g.GEN), TEXT: { x: X(g.TEXT.x), base: Y(g.TEXT.base), px: g.TEXT.px * s }, k: g.k * s, px: { ...g.px, gen: g.px.gen * s }, lineH: g.lineH * s };+ };+ // THE CLEAN DOCK is the hook's composer itself, at its own size, standing on the laid-out composer's foot:+ // one composer all film long, so the dock is one move of one object, never a re-layout or a rescale+ const DOCK_S = 1;+ const G: ChatGeom = clean && HERO ? (() => { const d = scaledComposer(HERO, DOCK_S, footOf(G0)); return { ...G0, INPUT: d.INPUT, GEN: d.GEN, TEXT: d.TEXT, wrap: d.wrap, lineH: d.lineH, px: { ...G0.px, gen: d.px.gen } }; })() : G0;+ // (the thread's view ends above the dock: on a phone the dock can stand taller than the laid-out composer,+ // and the answer card then shrinks, on every shape, to keep a card and the prompt above it in view together)+ const TH = (() => {+ const T0 = L.thread, vb = Math.min(T0.viewBottom, G.INPUT.y - 26 * k), d = T0.viewBottom - vb; if (d <= 0) return T0;+ // (on every shape: on 16:9 a card kept at its size made the thread scroll the question off, cc2-1)+ const card = Math.round(T0.card - d);+ return { ...T0, viewBottom: vb, clip: [T0.clip[0], T0.clip[1], T0.clip[2], T0.clip[3] - d] as [number, number, number, number], card, cardX: L.phone ? G.CHAT.x + (G.CHAT.w - card) / 2 : T0.cardX };+ })();+ const CARD = TH.card, VIEW_BOTTOM = TH.viewBottom;+ // THE CLEAN DROP'S FLIGHT follows its distance: 14 frames, or more when the streak (one solid, coherent thing+ // to motionscan, unlike the drawn look's fading trail) would top out past nine tenths of what the brand's+ // temperament allows, flown to where the thread's first card sits (later ones scroll in to sit lower; a+ // flight sized to the top of the view instead was so slow that a phone frame stood still: the gate's dead+ // air). With the hook's+ // composer docked at its own size+ // on a phone frame, the 14-frame flight moved at 45 px a frame against snappy's 36.+ const FLY = (() => {+ if (!clean || !TH.bubbles.length) return 14; // (no chat ask, no drop)+ const t = spec.motion?.temperament ?? "lively", share = typeof t === "string" ? (TEMPERAMENTS[t] ?? TEMPERAMENTS.lively).maxSpeed : t.maxSpeed, cap = 0.85 * share * speedCeiling(W, 30); // (0.85: the room creeps in a few per cent around it)+ // (the drop's own path, inkDropAt's, flown at each length until its fastest step is under the cap)+ const to: P = [TH.cardX + CARD / 2, TH.top + TH.bubbleH + (TH.bubbles[0].length - 1) * TH.bubbleLineH + TH.gap + TH.cardDy + CARD / 2], d0 = { t0: 0, land: 14 };+ for (let N = 14; N < 60; N++) {+ d0.land = N; let peak = 0;+ for (let c = 0; c < N - 0.5; c += 0.5) { const a = inkDropAt(c, d0, to, G), b = inkDropAt(c + 0.5, d0, to, G); if (a && b) peak = Math.max(peak, 2 * Math.hypot(b.p[0] - a.p[0], b.p[1] - a.p[1])); }+ if (peak <= cap) return N;+ }+ return 60;+ })();+ // THE DRAWN DOCK'S LENGTH follows the distance it covers: an in-out over SETTLE frames, or longer when the+ // hook's composer travels far enough that its fastest point would pass nine tenths of what the brand's+ // temperament allows (or of half the speed ceiling, the type's own limit). A calm brand's hook on a phone+ // frame docked at 44 px a frame against calm's 31 (motionscan temperament, layerscan fasttext on the+ // drawn scaffold); a lively one keeps its second on a wide frame. (The cubic in-out tops out at 3 times its average.)+ const DOCK_SHARE = (() => { const t = spec.motion?.temperament ?? "lively"; return Math.min(0.5, typeof t === "string" ? (TEMPERAMENTS[t] ?? TEMPERAMENTS.lively).maxSpeed : t.maxSpeed); })();+ const DOCK_LEN = (() => {+ if (!HERO || clean) return SETTLE;+ const pts = (g: ChatGeom): P[] => [[g.INPUT.x, g.INPUT.y], [g.INPUT.x + g.INPUT.w, g.INPUT.y], [g.INPUT.x, g.INPUT.y + g.INPUT.h], [g.INPUT.x + g.INPUT.w, g.INPUT.y + g.INPUT.h], [g.GEN.x, g.GEN.y], [g.TEXT.x, g.TEXT.base]];+ const a = pts(HERO), b = pts(G), D = Math.max(...a.map((p, j) => Math.hypot(p[0] - b[j][0], p[1] - b[j][1]))) * (ZONES ? 1.04 : 1.02); // (at the hook's creep zoom)+ return Math.max(SETTLE, Math.ceil((3 * D) / (0.9 * DOCK_SHARE * speedCeiling(W, 30))));+ })();+ // (a longer dock starts its extra frames sooner, over the prompt's last words, and lands when a one-second+ // dock would: everything after it keeps its time. Landing later squeezed the lean onto the answer card+ // into fewer frames, 55 px a frame on the calm scaffold's phone frame)+ const DOCK_AT = -8 - (DOCK_LEN - SETTLE);+ const GEN_C: P = [G.GEN.x + G.GEN.w / 2, G.GEN.y + G.GEN.h / 2];const about = (p: P, z: number): P => [p[0] - (p[0] - W / 2) / z, p[1] - (p[1] - H / 2) / z]; // a camera at zoom z that leaves world point p where it is on screen- const THEME: UiTheme = { bg: PAL.bg, card: PAL.card, ink: PAL.ink, soft: PAL.soft, mute: PAL.mute, line: PAL.line, chip: PAL.chip, accent: ACC ?? PAL.accent, paper: PAL.paper };+ const THEME: UiTheme = { bg: PAL.bg, card: PAL.card, ink: PAL.ink, soft: PAL.soft, mute: PAL.mute, line: PAL.line, chip: PAL.chip, accent: ACC ?? PAL.accent, paper: PAL.paper, ...(LK.custom ? { font: LK.fonts.text, onAccent: LK.onAccent, radius: LK.shape.radius, button: LK.shape.button } : {}) };// ---------------------------------------------------------------- the beat grid and the asks' lengths (30 fps units; 60 fps draws between them)const grid = beatGrid(spec.bpm, 30);- const ASK = Math.round((spec.askBeats ?? 6) * grid.beat), TYPE = Math.round((spec.typeBeats ?? 4) * grid.beat), END0_HOLD = Math.round((spec.endBeats ?? 8) * grid.beat);+ const ASK = Math.round((spec.askBeats ?? 6) * grid.beat), TYPE = Math.round((spec.typeBeats ?? 6) * grid.beat), END0_HOLD = Math.round((spec.endBeats ?? 8) * grid.beat);let END = END0_HOLD; // the end card is a hold: a scored film sets it so the film is whole bars of its scoreif (ASK < 100) throw new Error(`launchTemplate: an ask beat needs 100 frames or more (it has ${ASK}); raise askBeats`);if (END < MIN_END(30)) throw new Error("launchTemplate: the end card must hold the install lines 3 s or more; raise endBeats");@@ -178,8 +415,10 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const LEN = spec.asks.map((_, i) => (i === n - 1 ? Math.max(ASK, SOLVED) : ASK)); // content frames per askconst BASE = LEN.map((_, i) => LEN.slice(0, i).reduce((a, b) => a + b, 0));// a seam between two kinds (or into a UI or a film) with no word page on it opens with a bloom-in- const TIN = spec.asks.map((a, i) => (i > 0 && !(isChat(a) && isChat(spec.asks[i - 1])) && !words[i - 1]?.length ? TR : 0));- const T = spec.asks.map((a, i) => ({ ...(isChat(a) ? askTiming(a.prompt, i, ASK, TIN[i]) : a.kind === "ui" ? uiTiming(a.prompt, i, ASK, TIN[i], !!a.split?.length) : { times: [], b: 0, down: 0, up: 0, drop: { t0: 0, land: 0, full: 0 } }), base: BASE[i], len: LEN[i], tin: TIN[i] }));+ // (clean: every seam into an ask is a travel, from the word page before it or from the ask before it;+ // chat to chat with no word page stays in the one thread, with no seam at all)+ const TIN = spec.asks.map((a, i) => (i === 0 ? 0 : words[i - 1]?.length || !(isChat(a) && isChat(spec.asks[i - 1])) ? TRV : 0));+ const T = spec.asks.map((a, i) => ({ ...(isChat(a) ? askTiming(a.prompt, i, ASK, Math.round(TIN[i] / 2), HERO && i === 0 ? (clean ? { at: CLEAN_DOCK.at, len: CLEAN_DOCK.move + CLEAN_DOCK.shrink + CLEAN_DOCK.rest } : { at: DOCK_AT, len: DOCK_LEN }) : undefined, FLY) : a.kind === "ui" ? uiTiming(a.prompt, i, ASK, TIN[i], !!a.split?.length, TIN[i] > 0) : { times: [], b: 0, down: 0, up: 0, drop: { t0: 0, land: 0, full: 0 } }), base: BASE[i], len: LEN[i], tin: TIN[i] }));const END0 = BASE[n - 1] + LEN[n - 1]; // content frame where the end card startsconst askOf = (f: number) => { let i = n - 1; while (i > 0 && T[i].base > f) i--; return i; };@@ -188,22 +427,34 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const items: Item[] = [];chatIdx.forEach((i) => { const t = T[i], o = chatOrd(i); items.push({ at: t.base + t.up, h: TH.bubbleH + (TH.bubbles[o].length - 1) * TH.bubbleLineH, user: (spec.asks[i] as PlateAsk).prompt, lines: TH.bubbles[o] }); items.push({ at: t.base + t.drop.land, h: CARD + TH.cardDy, card: i }); });const ys = (() => { let y = TH.top; return items.map((it) => { const r = y; y += it.h + TH.gap; return r; }); })();- const scrollAt = (f: number) => { let s = 0; items.forEach((it, k) => { const want = Math.max(0, ys[k] + it.h - VIEW_BOTTOM); if (want > s) s += (want - s) * expo(ramp(f, it.at - 2, it.at + 16)); }); return s; };+ // THE THREAD SCROLLS ONCE PER ASK, as Generate is pressed: one move makes room for the sent prompt and+ // its answer card together (two overlapping scrolls added up). It is a glide (peak 1.11 times its mean)+ // whose length follows the distance, so the thread's type moves at three quarters of half the speed+ // ceiling at most (layerscan fasttext; the rest is the sent prompt's own rise, which rides on it), never+ // in under a second (an expo here moved the thread at 150 px a frame on a phone frame), and the camera+ // leans onto the card only once it has settled (cardSettled): a scroll and a lean at once carried the+ // thread's type past the ceiling on a phone frame.+ const scrolls = (() => { let done = 0; return chatIdx.map((i) => { const want = Math.max(0, ...items.map((it, k) => (it.card === i || it.user === (spec.asks[i] as PlateAsk).prompt && items[k + 1]?.card === i ? ys[k] + it.h - VIEW_BOTTOM : 0))), d = Math.max(0, want - done); done = Math.max(done, want);+ return { i, d, from: T[i].base + T[i].down - 2, len: Math.max(30, Math.ceil((1.12 * d) / (0.75 * 0.5 * speedCeiling(W, 30)))) }; }); })();+ const scrollAt = (f: number) => scrolls.reduce((s, q) => s + q.d * glide(ramp(f, q.from, q.from + q.len)), 0);+ const cardSettled = (i: number) => { const q = scrolls.find((x) => x.i === i)!; return q.from + q.len - T[i].base; }; // local frame its scroll landsconst cardY = (i: number, f: number) => ys[items.findIndex((it) => it.card === i)] + TH.cardDy - scrollAt(f);const plateFrame = (i: number, f: number) => { const a = spec.asks[i] as PlateAsk, t = T[i], from = a.from ?? 0, to = a.to ?? a.plate.meta.durationFrames - 1; return lerp(from, to, ramp(f, t.base + t.drop.land, t.base + t.len - 8)); };// the card opens on a spring and lands on its first arrival (its sound sits on that frame)const OMEGA = 4.163 / 21, ZETA = 0.8, arrive = (i: number) => springLand(T[i].base + T[i].drop.land, OMEGA, ZETA);const growAt = (i: number) => (f: number) => (f >= arrive(i) ? 1 : spring(f, T[i].base + T[i].drop.land, OMEGA, ZETA));+ let quietBug = false; // while a travel draws two places, the corner mark is drawn once, where it sits on the screenconst bug = (c: Ctx, env: Env) => {- if (clean) { c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.font = SANS(600, L.bug.px * 0.8); c.fillStyle = PAL.soft; c.textAlign = "right"; c.textBaseline = "alphabetic"; c.fillText(spec.title, L.bug.x, L.bug.y); c.textAlign = "left"; return; }+ if (quietBug) return;+ if (clean) { c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.font = LK.fonts.text(600, L.bug.px * 0.8); c.fillStyle = PAL.soft; c.textAlign = "right"; c.textBaseline = "alphabetic"; c.fillText(spec.title, L.bug.x, L.bug.y); c.textAlign = "left"; return; }writeOn(c, env, spec.title, L.bug.x, L.bug.y, L.bug.px, 1, "ink", { color: C.soft, align: "right", seed: 3 });};// focus: while the camera is close on the composer the thread recedes (it would be cut by the frame's// edge), and while it leans on a card everything but that card does; nothing is ever half off-frame// And whatever the camera's edge is about to cut fades before it does: an element's opacity is how// far inside the view it sits (full at 24 px in, none at the edge), so nothing shows half off-frame.- type Focus = { macro: number; lean: number; keep: number; cam: Cam };+ type Focus = { lean: number; keep: number; cam: Cam };// (on 9x16 the edge that counts is the safe rectangle's, so text fades before it reaches a zone; the fade// is short, ZONE_FADE px, because the hook's composer spans the window and a zone's line is not a visible edge)const ZONE_FADE = 8;@@ -211,27 +462,40 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const seen = ZONES ? seenSafe : (cam: Cam, x0: number, y0: number, x1: number, y1: number) => { const hw = W / 2 / cam.z, hh = H / 2 / cam.z, d = Math.min(x0 - (cam.c[0] - hw), cam.c[0] + hw - x1, y0 - (cam.c[1] - hh), cam.c[1] + hh - y1) * cam.z; return clamp(d / (24 * k)); };// (on a phone the close-up is nearly the whole window, so the header and thread stay, cut only by `seen`)// a card's width with its byline, which can run past the card (an estimate that errs wide)- const cardSpan = (i: number) => Math.max(CARD, 26 * k + estWidth((spec.asks[i] as PlateAsk).label, G.px.label));- const chat = (ctx: Ctx, env: Env, f: number, typed: string, caret: boolean, pr: number, hot: number, fo: Focus = { macro: 0, lean: 0, keep: -1, cam: CAM.home }, Gc: ChatGeom = G) => {- const C0 = G.CHAT, mf = L.phone || Gc !== G ? 0 : fo.macro, headA = Math.min(1 - mf, seen(fo.cam, C0.x + 40 * k, C0.y + 30 * k, C0.x + C0.w - 40 * k, C0.y + 76 * k)), compA = seen(fo.cam, Gc.INPUT.x, Gc.INPUT.y, Gc.INPUT.x + Gc.INPUT.w, Gc.INPUT.y + Gc.INPUT.h);- drawChatFrame(ctx, { typed, caret, placeholder: spec.placeholder ?? "Describe what you want…", genPress: pr, genHot: hot, title: spec.title, subtitle: spec.subtitle ?? "", genLabel: spec.genLabel, accent: ACC, head: headA, composer: compA, composerGeom: Gc === G ? undefined : Gc }, G);- const sc = scrollAt(f), rest = (1 - mf) * (1 - fo.lean), [, cyT, , chH] = TH.clip;+ const cardSpan = (i: number) => Math.max(CARD, 26 * k + LK.measure.text((spec.asks[i] as PlateAsk).label, G.px.label));+ const chat = (ctx: Ctx, env: Env, f: number, typed: string, caret: boolean, pr: number, hot: number, fo: Focus = { lean: 0, keep: -1, cam: CAM.home }, Gc: ChatGeom = G) => {+ // (the thread stays drawn under the composer's close-up: it used to fade out there and back in as the+ // camera eased out, and a thread fading in while the camera moves is content swapped, not carried: a+ // slide cut to motionscan. What the close-up's edge would cut, seen() fades as the camera reaches it.)+ // (the header recedes with the rest of the window while the camera leans on a card, as the thread does:+ // left at 60 %, the travel that follows carried it off the frame's top edge in a frame, a cut)+ // (clean: the window stays whole and opaque while the camera leans on a card, the lean a pure camera move;+ // the header and the thread receding in brand ink were see-through fills to layerscan and, with the move,+ // most of a sparse frame replaced in 0.1 s: a slide cut to motionscan)+ const recede = clean ? 0 : fo.lean;+ const C0 = G.CHAT, headA = (1 - recede) * seen(fo.cam, C0.x + 40 * k, C0.y + 30 * k, C0.x + C0.w - 40 * k, C0.y + 76 * k), compA = seen(fo.cam, Gc.INPUT.x, Gc.INPUT.y, Gc.INPUT.x + Gc.INPUT.w, Gc.INPUT.y + Gc.INPUT.h);+ drawChatFrame(ctx, { typed, full: ((a) => (isChat(a) ? a.prompt : undefined))(spec.asks[askOf(f)]), caret, placeholder: spec.placeholder ?? "Describe what you want…", genPress: pr, genHot: hot, title: spec.title, subtitle: spec.subtitle ?? "", genLabel: LK.shape.buttonLabel ?? spec.genLabel, accent: ACC, head: headA, composer: compA, composerGeom: Gc === G ? undefined : Gc }, G);+ const sc = scrollAt(f), rest = 1 - recede, [, cyT, , chH] = TH.clip;ctx.save(); ctx.beginPath(); ctx.rect(...TH.clip); ctx.clip();items.forEach((it, k) => {if (f < it.at) return;const y = ys[k] - sc; if (y > VIEW_BOTTOM || y + it.h < (ZONES ? cyT : 100)) return; // (on 9x16 an item scrolled wholly under the window's top is not drawn)// what of it the thread's window shows, and whether the camera shows all of thatconst vy0 = Math.max(y, cyT), vy1 = Math.min(y + it.h, cyT + chH), x0 = it.card !== undefined ? TH.cardX : TH.bubbleR - TH.bubbleMaxW, x1 = it.card !== undefined ? TH.cardX + (ZONES ? cardSpan(it.card) : CARD) : TH.bubbleR;- const A = (it.card === fo.keep ? 1 - mf : rest) * (vy1 > vy0 ? seen(fo.cam, x0, vy0, x1, vy1) : 1); if (A < 0.01) return;+ const A = (it.card === fo.keep ? 1 : rest) * (vy1 > vy0 ? seen(fo.cam, x0, vy0, x1, vy1) : 1); if (A < 0.01) return;if (it.user !== undefined) {- ctx.globalAlpha = A * ramp(f, it.at, it.at + 8); ctx.font = SANS(500, G.px.bubble);- const bw = Math.max(...it.lines!.map((l) => ctx.measureText(l).width)) + 2 * TH.bubblePad; ctx.fillStyle = PAL.chip; rr(ctx, TH.bubbleR - bw, y, bw, it.h - 2, TH.bubbleRad); ctx.fill();- ctx.fillStyle = PAL.ink; ctx.textBaseline = "middle"; it.lines!.forEach((l, j) => ctx.fillText(l, TH.bubbleR - bw + TH.bubblePad, y + TH.bubbleH / 2 + j * TH.bubbleLineH)); ctx.globalAlpha = 1;+ // the sent prompt rises into the thread from the composer it left (a bubble that only faded in was a dissolve to motionscan)+ const by = y + (1 - out3(ramp(f, it.at, it.at + 14))) * it.h * 0.3;+ ctx.globalAlpha = A * ramp(f, it.at, it.at + 3); ctx.font = LK.fonts.text(500, G.px.bubble);+ // (a custom look's bubble: its colours, square corners, or no bubble at all, the words alone)+ const bw = Math.max(...it.lines!.map((l) => ctx.measureText(l).width)) + 2 * TH.bubblePad, BS = LK.custom ? LK.shape.bubble : "rounded";+ if (BS !== "none") { ctx.fillStyle = LK.chat.bubble?.fill ?? PAL.chip; rr(ctx, TH.bubbleR - bw, by, bw, it.h - 2, BS === "square" ? 4 * k : TH.bubbleRad); ctx.fill(); }+ ctx.fillStyle = LK.chat.bubble?.ink ?? PAL.ink; ctx.textBaseline = "middle"; it.lines!.forEach((l, j) => ctx.fillText(l, TH.bubbleR - bw + TH.bubblePad, by + TH.bubbleH / 2 + j * TH.bubbleLineH)); ctx.globalAlpha = 1;} else {const i = it.card!, a = spec.asks[i] as PlateAsk;const d = T[i].drop, b = T[i].base;{ const py0 = Math.max(y + TH.cardDy, cyT), py1 = Math.min(y + TH.cardDy + CARD, cyT + chH); ctx.globalAlpha = A; if (py1 > py0) probeRect(ctx, env, TH.cardX, py0, CARD, py1 - py0, `answer card ${i}`); } // the part the thread's window shows- inkCard(ctx, TH.cardX, y + TH.cardDy, CARD, f, { t0: b + d.t0, land: b + d.land, full: b + d.full }, plateLayer(env, `ask${i}`, a.plate, plateFrame(i, f), 1080), y + TH.cardDy - 30 * k > cyT ? a.label : "", a.crop, G, growAt(i)); // a byline scrolled under the window's top is not drawn at all+ inkCard(ctx, TH.cardX, y + TH.cardDy, CARD, f, { t0: b + d.t0, land: b + d.land, full: b + d.full }, plateLayer(env, `ask${i}`, a.plate, plateFrame(i, f), 1080), a.label, a.crop, G, growAt(i), clamp((y + TH.cardDy - 30 * k - cyT) / (14 * k))); // a byline nearing the window's top fades out, dot and words togetherctx.globalAlpha = 1;}});@@ -243,8 +507,11 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {// with a margin on every sideconst HOME = CAM.home;const inView = (c: P, z: number): P => { const hw = W / 2 / z, hh = H / 2 / z; return [clamp(c[0], Math.min(hw, W - hw), Math.max(hw, W - hw)), clamp(c[1], Math.min(hh, H - hh), Math.max(hh, H - hh))]; };- // (a phone composer is nearly the frame's width, so there the close-up IS the window: the empty state, creeping 3 %)- const MZ = L.phone ? 1 : Math.max(1, Math.min(CAM.macroZ, (0.9 * W) / (G.INPUT.w + 48 * k), (0.8 * H) / (G.INPUT.h + 48 * k)) / 1.03);+ // A later ask is typed with the whole room in view, the camera creeping 3 % toward its composer (as it+ // always was on a phone, where the composer is nearly the frame's width). A close-up on the composer had+ // to ease back out before the press, and the thread above it could only arrive whole: each earlier card+ // stayed hidden until the move had brought it wholly inside the view, then appeared in two frames (a+ // slide cut to motionscan, and a pop to the eye).const leanOn = (i: number): Cam => {const cy = cardY(i, T[i].base + T[i].len), lab = 44 * k, box = { x: TH.cardX, y: cy - lab, w: ZONES ? cardSpan(i) : CARD, h: CARD + lab }, m = 36 * k;if (ZONES) {@@ -258,68 +525,78 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {return { c: [clamp(c[0], box.x + box.w + m - hw, box.x - m + hw), clamp(c[1], box.y + box.h + m - hh, box.y - m + hh)], z };};type CaretFn = (typed: string) => P;+ // the hook's creep: 2 % on a wide frame, 4 % on 9x16, 5 % there in the clean look (its composer, the dock+ // too, is narrower, so its typing changed too little of the tall frame: dead air to the gate, frames 13 to 46)+ const HOOK_CREEP = 1 + (ZONES ? (clean ? 0.05 : 0.04) : 0.02);+const prevChat = (i: number) => i > 0 && isChat(spec.asks[i - 1]) && T[i].tin === 0;- // the empty state: on a phone the first ask's composer starts in the middle of the empty thread (the- // way a chat app opens) and docks at the bottom as Generate is pressed; the hook is the prompt, centred- // THE HOOK: the first prompt is the hero. It is typed in a big composer in the middle of the frame- // (at least 64 px type on a phone frame, 56 px on 16x9, wrapping to 2-3 lines, never clipped),- // which shrinks and docks at the bottom of the chat as Generate is pressed.- const HERO = (() => {- if (!isChat(spec.asks[0])) return null;- const prompt = spec.asks[0].prompt, min = L.phone ? 64 : 56, inW = ZONES ? G.CHAT.w - 24 : Math.min(L.phone ? W * 0.9 : W * 0.72, G.CHAT.w - 60 * k); // most of the width, inside the chat window (on 9x16 all of it: the window is narrower there)- for (let px = L.phone ? 76 : 68; px >= min; px -= 2) {- const kh = px / 34, genW = 166 * kh, textW = inW - 44 * kh - genW - 44 * kh, lines = wrapEst(prompt, px, textW).length;- if (lines > 3 && px > min) continue;- if (lines > 3) throw new Error(`launchTemplate ${shape}: the first prompt "${prompt}" needs ${lines} lines at the hook's ${min} px; shorten it (the hook must read muted in the first 2 s)`);- // centred in the frame, or on 9x16 in the chat window (which is centred in the safe rectangle)- const h = 104 * kh + (lines - 1) * Math.round(px * 1.3), fake = ZONES- ? { x: G.CHAT.x + (G.CHAT.w - inW) / 2 - 60 * kh, y: G.CHAT.y + G.CHAT.h / 2 - H * 0.5, w: inW + 120 * kh, h: H * 0.5 + h / 2 + 36 * kh }- : { x: (W - inW) / 2 - 60 * kh, y: 0, w: inW + 120 * kh, h: H * 0.5 + h / 2 + 36 * kh };- const g = chatGeom(fake, kh, { ...G.px, gen: 24 * kh }, px, lines, genW);- return { ...g, CHAT: G.CHAT, theme: G.theme, drop: G.drop, iris: G.iris } as ChatGeom;- }- return null;- })();+ // (the drawn dock's two sets of line breaks: the hook's, then halfway, as its rows change, the dock's own, kept+ // to the landing; a one-line dock never wraps)+ const HERO_WRAP = HERO ? { px: HERO.TEXT.px, maxW: HERO.GEN.x - 20 * HERO.k - HERO.TEXT.x } : undefined;+ const DOCK_WRAP = { px: G.TEXT.px, maxW: G.wrap > 0 ? G.GEN.x - 20 * G.k - G.TEXT.x : Infinity };const heroAt = (i: number, l: number): ChatGeom => {if (!HERO || i !== 0) return G;- const u = expo(ramp(l, T[i].b - 4, T[i].down)); if (u >= 1) return G;+ if (clean) { // the clean dock: a glide down whole, at its own size (CLEAN_DOCK)+ const a0 = T[i].b + CLEAN_DOCK.at, q1 = glide(ramp(l, a0, a0 + CLEAN_DOCK.move));+ if (q1 >= 1) return G;+ return scaledComposer(HERO, DOCK_S, lerpP(footOf(HERO), footOf(G), q1));+ }+ const u = inOut(ramp(l, T[i].b + DOCK_AT, T[i].b + DOCK_AT + DOCK_LEN)); if (u >= 1) return G;const mix = (a: number, b: number) => a + (b - a) * u, R = <T extends Record<string, number>>(a: T, b: T) => Object.fromEntries(Object.keys(a).map((key) => [key, mix(a[key], b[key])])) as T;+ // (wrapped as the hook, then as the dock, never afresh at each eased width: words jumped between lines three+ // times on the move; now the breaks change once, halfway, with the composer's rows)const dockLines = Math.max(1, G.wrap);- return { ...G, INPUT: R(HERO.INPUT, G.INPUT), GEN: R(HERO.GEN, G.GEN), TEXT: R(HERO.TEXT, G.TEXT), k: mix(HERO.k, G.k), px: R(HERO.px, G.px), lineH: mix(HERO.lineH, G.lineH), wrap: u < 0.5 ? HERO.wrap : dockLines };+ return { ...G, INPUT: R(HERO.INPUT, G.INPUT), GEN: R(HERO.GEN, G.GEN), TEXT: R(HERO.TEXT, G.TEXT), k: mix(HERO.k, G.k), px: R(HERO.px, G.px), lineH: mix(HERO.lineH, G.lineH), wrap: u < 0.5 ? HERO.wrap : dockLines, wrapAs: u < 0.5 ? HERO_WRAP : DOCK_WRAP };};- // `lean` (0..1) is how far the camera leans in, `macro` how close it is on the composer; the corner- // mark steps aside while it leans, since the lean carries the composer under the corner- const camAt = (_caret: CaretFn, f: number, i: number): { cam: Cam; lean: number; macro: number; keep: number } => {+ // `lean` (0..1) is how far the camera leans in; the corner mark steps aside while it leans, since the+ // lean carries the composer under the corner+ const camAt = (_caret: CaretFn, f: number, i: number): { cam: Cam; lean: number; keep: number } => {const t = T[i], l = f - t.base;- // the close-up creeps in while the words arrive: the frame is never a still- // (the hero hook is its own close-up: the camera holds the whole frame, creeping 2 %)- const hero = !!HERO && i === 0, mz = hero ? 1 + 0.02 * ramp(l, -20, t.b) : MZ * (1 + 0.03 * ramp(l, -20, t.b));- // (9x16: the creep is about the window's centre for the hook, the composer's otherwise, so neither moves toward a zone)- const macro: Cam = ZONES ? { c: inView(about(hero ? [G.CHAT.x + G.CHAT.w / 2, G.CHAT.y + G.CHAT.h / 2] : [G.INPUT.x + G.INPUT.w / 2, G.INPUT.y + G.INPUT.h / 2], mz), mz), z: mz } : { c: inView(hero ? HOME.c : [G.INPUT.x + G.INPUT.w / 2, G.INPUT.y + G.INPUT.h / 2], mz), z: mz };- if (prevChat(i) && l < 16) { const q = inOut(ramp(l, 0, 16)); return { cam: camLerp(leanOn(i - 1), macro, q), lean: 1 - q, macro: q, keep: i - 1 }; }- if (l > t.drop.full - 10) { const q = inOut(ramp(l, t.drop.full - 10, t.len)); return { cam: camLerp(HOME, leanOn(i), q), lean: q, macro: 0, keep: i }; }- const w = l < t.b - 4 ? 1 : 1 - expo(ramp(l, t.b - 4, t.down));- return { cam: l < t.b - 4 ? macro : camLerp(macro, HOME, expo(ramp(l, t.b - 4, t.down))), lean: 0, macro: w, keep: -1 };+ // the room, creeping in while the words arrive and on through the press: the frame is never a still (a+ // camera that stopped as the pointer arrived left two identical frames before Generate went down, a+ // freeze to the gate). The hook creeps 2 % on the whole frame (4 % on 9x16, where typing alone changes too+ // little of a tall frame to read as motion), a later ask 3 % toward its composer.+ const hero = !!HERO && i === 0, mz = hero ? 1 + (HOOK_CREEP - 1) * ramp(l, -20, t.up + 10) : 1 + 0.03 * ramp(l, -20, t.up + 10);+ // (9x16: the creep is about the window's centre for the hook, the composer's otherwise, so neither moves toward a zone;+ // on a wide frame it is about the window's bottom right corner, so the window never grows into the corner mark beside it)+ const room: Cam = ZONES ? { c: inView(about(hero ? [G.CHAT.x + G.CHAT.w / 2, G.CHAT.y + G.CHAT.h / 2] : [G.INPUT.x + G.INPUT.w / 2, G.INPUT.y + G.INPUT.h / 2], mz), mz), z: mz } : { c: inView(about([G.CHAT.x + G.CHAT.w, G.CHAT.y + G.CHAT.h], mz), mz), z: mz };+ // (from the card before to this composer: in-out until the settle begins, never a 16-frame whip)+ if (prevChat(i) && l < t.b - 8) { const q = inOut(ramp(l, 0, t.b - 8)); return { cam: camLerp(leanOn(i - 1), room, q), lean: 1 - q, keep: i - 1 }; }+ const lean0 = Math.max(t.drop.full - 10, cardSettled(i));+ // (clean: when a travel or the end card follows, the lean is still moving as the ask ends, so the camera+ // never crawls to rest on a sparse frame before it moves again: its last slow frames, a near-still camera+ // over thin type, replaced most of the frame in 0.1 s with too little move to explain it, a slide cut)+ const leanEnd = clean && !(i < n - 1 && T[i + 1].tin === 0) ? t.len + 12 : t.len;+ if (l > lean0) { const q = inOut(ramp(l, lean0, leanEnd)); return { cam: camLerp(room, leanOn(i), q), lean: q, keep: i }; }+ return { cam: room, lean: 0, keep: -1 };};// the same camera without a canvas (for the sound's pan): the caret from the build-time width estimateconst caretEst: CaretFn = (typed) => {- if (G.wrap > 0) { const ls = wrapEst(typed, G.TEXT.px, G.GEN.x - 20 * k - G.TEXT.x); return [G.TEXT.x + estWidth(ls[ls.length - 1], G.TEXT.px), G.TEXT.base + (ls.length - 1) * G.lineH - 0.35 * G.TEXT.px]; }- return [G.TEXT.x + estWidth(typed, G.TEXT.px), G.TEXT.base - 12];+ if (G.wrap > 0) { const ls = LK.wrap(typed, G.TEXT.px, G.GEN.x - 20 * k - G.TEXT.x); return [G.TEXT.x + LK.measure.text(ls[ls.length - 1], G.TEXT.px), G.TEXT.base + (ls.length - 1) * G.lineH - 0.35 * G.TEXT.px]; }+ return [G.TEXT.x + LK.measure.text(typed, G.TEXT.px), G.TEXT.base - 12];};- const pointerPath = (ctx: Ctx, l: number, t: { b: number; down: number; up: number }, on: P, pr: number) => {- const off: P = CAM.pointerOff;- if (l >= t.b - 4 && l < t.up + 24) pointer(ctx, l < t.up + 4 ? lerpP(off, on, out3(ramp(l, t.b - 4, t.down))) : lerpP(on, off, inOut(ramp(l, t.up + 4, t.up + 24))), pr * 0.8, CAM.pointerS);+ // THE POINTER comes in for the press (from `from`, off the frame), and once the press is up it eases a+ // step aside, off the button's word, and rests there for the rest of the ask: a hand that clicked and let+ // go. It used to glide back out of frame and read as drifting into empty space after every click.+ const pointerPath = (ctx: Ctx, l: number, t: { b: number; down: number; up: number }, on: P, pr: number, from: P = CAM.pointerOff, restAt?: P) => {+ if (l < t.b - 4) return;+ const rest: P = restAt ?? [on[0] + 26 * k, on[1] + 30 * k];+ // (it arrives still moving a little, and the press stops it: an out-cubic came to rest a frame early and+ // left two identical frames before the press at 60 fps)+ const arrive = (q: number) => 0.85 * out3(q) + 0.15 * q;+ pointer(ctx, l < t.up + 4 ? lerpP(from, on, arrive(ramp(l, t.b - 4, t.down))) : lerpP(on, rest, inOut(ramp(l, t.up + 4, t.up + 22))), pr * 0.8, CAM.pointerS, LK.pointer);};const chatScene = (ctx: Ctx, env: Env, f: number, i: number) => {- const t = T[i], l = f - t.base, Gc = heroAt(i, l), caret: CaretFn = (s) => caretAt(ctx, s, Gc);- const { cam, lean, macro, keep } = camAt(caret, f, i);+ const t = T[i], l = f - t.base, Gc = heroAt(i, l), caret: CaretFn = (s) => caretAt(ctx, s, Gc, (spec.asks[i] as PlateAsk).prompt);+ const { cam, lean, keep } = camAt(caret, f, i);useCam(ctx, env, cam);const typed = typedAt((spec.asks[i] as PlateAsk).prompt, l, t.times), pr = press(l, t.down, t.up);- chat(ctx, env, f, l < t.up ? typed : "", l < t.up, pr, ramp(l, t.down - 10, t.down - 2), { macro, lean, keep, cam }, Gc);- // the pointer comes in for the press and glides back out; it never pops- pointerPath(ctx, l, t, [Gc.GEN.x + Gc.GEN.w / 2 + 18 * Gc.k, Gc.GEN.y + Gc.GEN.h / 2 + 6 * Gc.k], pr);+ chat(ctx, env, f, l < t.up ? typed : "", l < t.up, pr, ramp(l, t.down - 10, t.down - 2), { lean, keep, cam }, Gc);+ // the pointer comes in for the press and glides back out; it never pops (it fades as the camera leans on+ // the new card, so the travel that follows starts without it instead of dropping it in one frame)+ { const pa = keep === i ? 1 - lean : 1; if (pa > 0.01) { ctx.globalAlpha = pa; pointerPath(ctx, l, t, [Gc.GEN.x + Gc.GEN.w / 2 + 18 * Gc.k, Gc.GEN.y + Gc.GEN.h / 2 + 6 * Gc.k], pr); ctx.globalAlpha = 1; } }// the mark is gone BEFORE the lean moves the composer under it, and back only once the camera has left- const show = lean > 0 && l > ASK / 2 ? 1 - ramp(l, t.drop.full - 18, t.drop.full - 10) : prevChat(i) && l < 24 ? ramp(l, 16, 24) : 1;+ const show = lean > 0 && l > ASK / 2 ? 0 : l > ASK / 2 && l > t.drop.full - 18 ? 1 - ramp(l, t.drop.full - 18, t.drop.full - 10) : prevChat(i) && l < t.b ? ramp(l, t.b - 8, t.b) : 1;if (show > 0) { ctx.globalAlpha = show; bug(ctx, env); ctx.globalAlpha = 1; }};// ---------------------------------------------------------------- the product UI, a film in a card, and a split beat's words@@ -338,20 +615,55 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const fit = ZONES ? Math.max(1, Math.min((0.94 * SAFE.w) / win.w, (0.92 * SAFE.h) / win.h)) : Math.max(1, Math.min((0.94 * W) / win.w, (0.92 * H) / win.h));const toward = (z: number): Cam => (ZONES ? { c: inView(about(wc, z), z), z } : { c: inView(lerpP(HOME.c, wc, clamp((z - 1) / (fit - 1 || 1))), z), z });if (l >= t.down) return toward(1 + (fit - 1) * 0.9 * inOut(ramp(l, t.down, t.len + 40))); // from the press on, never resting; still moving when the ask ends- const open = toward(1 + (fit - 1) * 0.5 * ramp(l, -20, t.b)); // already creeping on frame 0- return camLerp(open, HOME, expo(ramp(l, t.b - 4, t.down)));+ // (on 9x16 a window that already fills the safe rectangle has little fit left to creep into, and the+ // typing alone changed too little of a tall frame: dead air to the gate. There it creeps 6 % at least+ // while the words arrive, about its centre: fitted to 94 % of the safe rectangle, it stays inside it+ // with its padding, and eases back to the whole window for the press)+ const open = toward(1 + (ZONES ? Math.max((fit - 1) * 0.35, 0.06) : (fit - 1) * 0.35) * ramp(l, -20, t.b)); // already creeping on frame 0+ // the ease back for the press is one long in-out, never a snap: an expo here took most of the zoom in+ // 3 frames, and a text-dense window zoomed that fast is replaced pixel for pixel (a slide cut to+ // motionscan). Kept this gentle, typing, ease-back and press read as ONE beat of one screen, not+ // three stills of the same layout (motionscan repeat: the carousel)+ return camLerp(open, HOME, inOut(ramp(l, t.b - 24, t.down)));+ };+ let quietGround = false; // inside a travel the ground is already laid, once, under both places+ const ground = (ctx: Ctx, env: Env) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); if (quietGround) return; ctx.fillStyle = PAL.bg; ctx.fillRect(0, 0, W, H); };+ // where the pointer rests after a product's click: up off the window, just above its header, so it never+ // settles on a row's figure (down and right of the button, as the chat's rest, it sat on "$1,208" on 9:16)+ const uiRest = (i: number) => {+ const a = spec.asks[i] as UiAsk, r = panelOf(i), [ax, ay] = uiActionAt(r, a.ui, minPx), on: P = [ax + 14 * k, ay + 8 * k], win = uiWindow(r, a.ui, minPx);+ return { i, tip: [on[0] + 20 * k, win.y - 29 * CAM.pointerS - 10 * k] as P, win, s: CAM.pointerS };};- const ground = (ctx: Ctx, env: Env) => { ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = PAL.bg; ctx.fillRect(0, 0, W, H); };const uiScene = (ctx: Ctx, env: Env, f: number, i: number) => {const a = spec.asks[i] as UiAsk, t = T[i], l = f - t.base, r = panelOf(i), pr = press(l, t.down, t.up);ground(ctx, env); if (a.split?.length) push(ctx, env, r, l, t.len, t.drop.t0); else useCam(ctx, env, uiCam(i, l));const typed = a.prompt ? typedAt(a.prompt, l, t.times) : "";{ const w = uiWindow(r, a.ui, minPx); probeRect(ctx, env, w.x, w.y, w.w, w.h, "product window"); }drawProductUI(ctx, r, a.ui, { f: l, t0: t.drop.t0 }, THEME, { minPx, typed, caret: !!a.prompt && l < t.down, press: pr, hot: ramp(l, t.down - 10, t.down - 2), accent: ACC });- pointerPath(ctx, l, t, (([x, y]) => [x + 14 * k, y + 8 * k] as P)(uiActionAt(r, a.ui, minPx)), pr);- if (a.split?.length) splitWords(ctx, env, a.split, l, t.tin);+ // (into a product's action from the right, along its header: a path up from the corner crossed the rows and paused on a figure)+ { const [ax, ay] = uiActionAt(r, a.ui, minPx), q = uiRest(i); pointerPath(ctx, l, t, [ax + 14 * k, ay + 8 * k], pr, [ax + 0.5 * W, ay - 20 * k], q.tip); }+ if (a.split?.length) splitWords(ctx, env, a.split, l, wordsAt(t.tin), wordsOut(i, l));bug(ctx, env);};+ // TYPE ARRIVES WITH ITS PLACE AND LEAVES IN PLACE (clean). A split beat's words rise halfway through the+ // travel in (a word rising while the camera is still is a slide to motionscan; carried by the move it is+ // part of the move), and sink out (setType's out: typeExit, ease-in, 1.3x their size), bottom line first,+ // in the last SINK frames before the camera leaves, so no line is carried across a platform zone or+ // sliced by the frame's edge (framecheck zones, layerscan exits). The last ask's words stay: the end card+ // blooms over them.+ const SINK = 18; // 0.6 s: type leaves in 0.5 to 0.7 s (motion-grammar.md)+ const wordsAt = (tin: number) => Math.round(tin / 2);+ // 0..1 over the sink, staggered per line by sunk(). The last ask's words sink too, before the motif's+ // drop starts to swell, so the drop flies and the end card blooms over clear canvas, never over a word+ // (a fresh critic saw the drop land on the headline's last letter and the bloom eat it mid-word)+ // (the last ask's words finish sinking halfway through the drop's flight, still gone before it lands and the+ // end card blooms; they sink while the bead swells beside the product's action and the drop leaves it, away+ // from them. Gone before the swell, and then before the flight, they left a phone frame its small product+ // window alone for over half a second: "6 text blocks packed into 25 % of the frame")+ const sinkAt = (i: number) => (i < n - 1 ? T[i].len - SINK - 1 : MOTIF ? T[i].len - Math.floor(DL / 2) - SINK - 1 : T[i].len);+ const wordsOut = (i: number, l: number) => (i < n - 1 || MOTIF ? (l - sinkAt(i)) / SINK : 0);+ /** Line j of nL leaving at sink progress q: the bottom line first, each in its own share of the sink with no overlap, so a sinking line never drops into the band of a line still leaving (a reader sees the two run together as one line). */+ const sunk = sinkOf;const filmCard = (i: number): Rect => { const a = spec.asks[i] as FilmAsk, r = panelOf(i), s = Math.min(r.w / a.film.meta.W, r.h / a.film.meta.H), w = a.film.meta.W * s, h = a.film.meta.H * s; return { x: r.x + (r.w - w) / 2, y: r.y + (r.h - h) / 2, w, h }; };const filmScene = (ctx: Ctx, env: Env, f: number, i: number) => {const a = spec.asks[i] as FilmAsk, t = T[i], l = f - t.base, c = filmCard(i), from = a.from ?? 0, to = a.to ?? a.film.meta.durationFrames - 1;@@ -360,20 +672,33 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {ctx.save(); rr(ctx, c.x, c.y, c.w, c.h, 22 * k); ctx.clip();ctx.drawImage(plateLayer(env, `film${i}`, a.film, lerp(from, to, ramp(l, 0, t.len - 1)), Math.round(c.w * env.scale)).canvas, c.x, c.y, c.w, c.h);ctx.restore();- if (a.split?.length) splitWords(ctx, env, a.split, l, t.tin);+ if (a.split?.length) splitWords(ctx, env, a.split, l, wordsAt(t.tin), wordsOut(i, l));bug(ctx, env);};// words in their own column beside the live UI (stacked above it on a phone): sized to the column, written or set on// the words are the design of the beat: as large as their column allows (set type is wider than it is tall, so its cap is higher)- const wordsCap = clean ? L.split.wordsPx * 1.6 : L.split.wordsPx, wOf = (t: string, sz: number) => (clean ? estWidth(t, sz) * 1.12 : measure(t, sz));- const splitLines = (lines: TypeLine[]) => { const col = L.split.words, out: TypeLine[] = []; for (const ln of lines) { const size = Math.min(wordsCap, (col.w / wOf(ln.text, 100)) * 100); if (size >= wordsCap * 0.62 || !ln.text.includes(" ")) out.push(ln); else wrapEst(ln.text, wordsCap, col.w * 1.05).forEach((t) => out.push({ ...ln, text: t })); } return out; };- const splitWords = (ctx: Ctx, env: Env, lines0: TypeLine[], l: number, tin: number) => {- const col = L.split.words, lines = splitLines(lines0), size = Math.min(wordsCap, ...lines.map((x) => (col.w / wOf(x.text, 100)) * 100)), gap = size * (clean ? 1.08 : 1.3);+ const wordsCap = clean ? L.split.wordsPx * 1.6 : L.split.wordsPx, wOf = (t: string, sz: number) => (clean ? LK.measure.display(t, sz) : measure(t, sz));+ const splitLines = (lines: TypeLine[]) => { const col = L.split.words, out: TypeLine[] = []; for (const ln of lines) { const size = Math.min(wordsCap, (col.w / wOf(ln.text, 100)) * 100); if (size >= wordsCap * 0.62 || !ln.text.includes(" ")) out.push(ln); else LK.wrapDisplay(ln.text, wordsCap, col.w * 1.05).forEach((t) => out.push({ ...ln, text: t })); } return out; };+ // ...and as tall as their column allows: on a phone the column is a third of the window, and the+ // scaffold's stand-in words, wrapped to four lines at the width's size, ran down over the product window+ // (framecheck: text over text, text over the window's edge). Words too tall for it are set smaller and+ // wrapped again at that size until they fit; under the phone-safe size it is an error+ const splitFit = (lines0: TypeLine[]): { lines: TypeLine[]; size: number } => {+ const col = L.split.words, gk = clean ? 1.08 : 1.3, tall = (nL: number, sz: number) => (L.split.vertical ? sz * 1.25 : sz * 1.05) + (nL - 1) * sz * gk;+ const at = (cap: number) => { const ls: TypeLine[] = []; for (const ln of lines0) { if ((col.w / wOf(ln.text, 100)) * 100 >= cap * 0.62 || !ln.text.includes(" ")) ls.push(ln); else LK.wrapDisplay(ln.text, cap, col.w * 1.05).forEach((t) => ls.push({ ...ln, text: t })); } return { lines: ls, size: Math.min(cap, ...ls.map((x) => (col.w / wOf(x.text, 100)) * 100)) }; };+ const first = { lines: splitLines(lines0), size: 0 }; first.size = Math.min(wordsCap, ...first.lines.map((x) => (col.w / wOf(x.text, 100)) * 100));+ if (tall(first.lines.length, first.size) <= col.h) return first;+ for (let cap = wordsCap * 0.95; cap >= L.split.wordsPx * 0.5; cap *= 0.95) { const f = at(cap); if (tall(f.lines.length, f.size) <= col.h && f.size >= minWords) return f; }+ throw new Error(`launchTemplate ${shape}: the split words "${lines0.map((x) => x.text).join(" ")}" do not fit their column (${Math.round(col.w)} x ${Math.round(col.h)} px) at the phone-safe size; use fewer words`);+ };+ const minWords = L.type.minPx * 0.75;+ const splitWords = (ctx: Ctx, env: Env, lines0: TypeLine[], l: number, tin: number, out = 0) => {+ const col = L.split.words, { lines, size } = splitFit(lines0), gap = size * (clean ? 1.08 : 1.3);const y0 = L.split.vertical ? col.y + size : col.y + col.h / 2 - ((lines.length - 1) * gap) / 2 + size * 0.35;lines.forEach((x, j) => {const p = ramp(l, tin + j * 12, tin + 18 + j * 12);- if (clean) setType(ctx, env, x.text, col.x, y0 + j * gap, size, p, { color: x.color === C.accent ? THEME.accent : x.color ?? PAL.ink, weight: 800 });- else writeOn(ctx, env, x.text, col.x, y0 + j * gap, size, p, x.style, { color: x.color, align: "left", seed: 21 + j });+ if (clean) { if (lineShown(ctx, env, x.text, col.x, y0 + j * gap, size)) setType(ctx, env, x.text, col.x, y0 + j * gap, size, p, { font: LK.fonts.display, color: x.color === C.accent ? THEME.accent : x.color ?? PAL.ink, weight: 800, out: sunk(out, j, lines.length) }); }+ else if (lineShown(ctx, env, x.text, col.x, y0 + j * gap, size, measure(x.text, size))) writeOn(ctx, env, x.text, col.x, y0 + j * gap, size, p, x.style, { color: x.color, align: "left", seed: 21 + j, out: sunk(out, j, lines.length), tool: PEN });});};// where a UI ask's world point is on screen at content frame f (its camera, or the split panel's push)@@ -382,30 +707,198 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const bloomOpts = clean ? { shape: "circle" as const, rim: 0, bg: PAL.bg } : {};const CLEAN_ST = 12; // a clean word page's lines follow each other closer: set type settles sooner than a brush+ // ---------------------------------------------------------------- the clean preset's travels and word pages+ // where the next place is: below on a wide frame; on a tall one to the left, the one side of a phone+ // frame with no platform zone, so everything ARRIVES clear of the zones (strings that arrived through the+ // right-hand column popped in on the last frame). Tall places sit one safe width apart, not one frame+ // width: they overlap only in the right-hand column, which holds nothing at rest, so the next place's+ // content is in view from the first frame of the move and no frame between two places is empty. Either+ // way no travel is longer than one frame width, so TRV holds for every shape.+ // (a wide or square frame alternates between travels: down, then up, then down, in the order the seams come.+ // Every travel going down read as one move repeated: "two travels from below", a fresh critic. Sideways+ // was tried: a wide place a frame width away is wholly out of view until the move brings it in, so the+ // frame emptied and then filled, a slide cut to motionscan)+ const SEAMS: string[] = []; spec.asks.forEach((_, i) => { if (i > 0 && TIN[i] > 0) SEAMS.push(`ask:${i}`); if (i < n - 1 && words[i]?.length) SEAMS.push(`page:${i}`); });+ const axOf = (seam: string): P => (W < H ? [-(SAFE.x + SAFE.w), 0] : SEAMS.indexOf(seam) % 2 ? [0, -H] : [0, H]);+ // on a phone shape the UI's own strings (its labels and figures) that the travel carries through a+ // platform zone (the top band, the bottom band, the right-hand column) are not drawn there: each fades,+ // whole, as it reaches one, as the chat's seen() does. The left side has no zone; there the frame's edge+ // is a clean cut while the camera moves. Set words never travel (wordsOut, the page's sink).+ // (a string fades over the ZONE_BAND px before it reaches a zone, so it leaves in about five frames of the+ // travel, never in one. The band is measured from where the string rests (the place at its own spot, d = 0):+ // one that rests nearer the zone than the band fades from its rest distance, so nothing near a safe edge+ // dims the moment a travel starts or snaps back when it ends. Inside a zone it is never drawn.)+ const inSafe = (y0: number, x1: number, y1: number) => x1 <= SAFE.x + SAFE.w && y0 >= SAFE.y && y1 <= SAFE.y + SAFE.h;+ // (on a frame with no zones the drawn look fades a carried string the same way before the frame's own+ // top and bottom edges, so a byline never leaves in one frame there either; the clean look's strings are+ // its brand ink, which never goes see-through, so they stay cut by the edge as the camera carries them)+ const zoneFade = ZONES ? zoneFadeOf(SAFE) : clean ? undefined : zoneFadeOf({ x: 0, y: 0, w: W, h: H });+ /** A set line inside a travel on a phone shape: drawn whole only while it is wholly inside the safe area (else not at all, so no line is ever half in a zone). */+ const lineShown = (c: Ctx, env: Env, text: string, x: number, y: number, size: number, width = LK.measure.display(text, size)) => {+ if (!ZONES || !quietGround) return true;+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); const m = c.getTransform(), S = env.scale, w = width;+ const xs = [x, x + w].map((v) => (m.a * v + m.e) / S), ys = [y - size * 0.8, y + size * 0.25].map((v) => (m.d * v + m.f) / S);+ return inSafe(Math.min(...ys), Math.max(...xs), Math.max(...ys));+ };+ /** The camera travels from one place to the next over q 0..1: both drawn where they sit in the world, each inside its own frame-sized place. */+ // (the ground is laid once under both places, so where two places overlap neither paints over the other)+ // (`hidden`: the place it leaves ended with the corner mark stepped aside, as a chat ask's lean does; the+ // mark then comes back over the travel's second half, never popping in on its first frame)+ // (callers sample a travel at mid-frame, (l + 0.5) / length: its first frame then already moves off the+ // place's last frame, which a place held still (a chat ask's lean) drew identically, a frozen pair to the gate)+ const travel = (ctx: Ctx, env: Env, q: number, from: (c: Ctx) => void, to: (c: Ctx) => void, AX: P, hidden = false) => {+ const u = glide(q), side = (k: number, draw: (c: Ctx) => void) => {+ const d: P = [AX[0] * k, AX[1] * k]; if (Math.abs(d[0]) >= W || Math.abs(d[1]) >= H) return;+ ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.beginPath(); ctx.rect(d[0], d[1], W, H); ctx.clip();+ draw(placed(ctx, env, { d, fade: zoneFade })); ctx.restore();+ };+ ground(ctx, env);+ quietBug = quietGround = true; try { side(-u, from); side(1 - u, to); } finally { quietBug = quietGround = false; }+ const a = hidden ? ramp(q, 0.5, 0.9) : 1; if (a > 0) { ctx.globalAlpha = a; bug(ctx, env); ctx.globalAlpha = 1; }+ };+ // a word page as a place: the camera comes in to it as its lines rise into place at the margin, they are read, and+ // sink out (typeExit) as the camera starts to leave; the page creeps closer (6 %) all the time it is on+ const PAGE_ON = Math.round(TRV / 2); // local frame the first line starts to rise: halfway, at the travel's top speed, so the rise is part of the move+ // local frame the lines start to sink: on a frame with no zones as the travel out starts, so they sink as+ // the camera carries them off; on a phone so the last line is gone at the last frame before the move+ // could carry the widest line (the page's full measure, crept 3 %) into the right-hand column+ // (a phone's word page sets its lines to three quarters of the measure, from the same left margin: the+ // room it leaves before the right-hand column lets the lines sink while the camera already moves)+ const PAGE_MEASURE = ZONES ? 0.75 : 1;+ // A sideways travel (a tall frame) carries the page right, and two edges then cross its lines: the right-hand+ // column (or the frame's right edge) ahead of them, and behind them the left edge of the page's own place,+ // which the next place is uncovering. The lines are gone before the move reaches either: a line sliced by+ // the edge of its place reads as a cut, not a move (a fresh look at the drawn example's 9:16 page found+ // "IDEA IN." still standing, its first letter shaved off, as the chat came in from the left).+ const pageRoom = () => {+ const at = L.type.at, cx = at ? at[0] : W / 2, x0 = at ? at[0] - L.type.maxW / 2 : (W - L.type.maxW) / 2, right = cx + (x0 + L.type.maxW * PAGE_MEASURE - cx) * 1.03, left = cx + (x0 - cx) * 1.03;+ return Math.min((ZONES ? SAFE.x + SAFE.w : W) - right, left) - 2;+ };+ const pageOut = (i: number) => { // (word page i: the travel that leaves it is the one into ask i + 1)+ const AX = axOf(`ask:${i + 1}`);+ // a travel down: the lines sink as it starts, carried off with the camera. A calm brand's lines do not+ // sink: the camera carries them off whole. Sinking while carried they moved at the travel's pace plus+ // their own, past what calm allows on a wide frame (motionscan temperament, 30 px a frame against 28),+ // and sunk before the travel they left its first frames a blank page moving (identical frames to the gate)+ if (!AX[0]) return CALM ? TYPE + TRV : TYPE;+ const room = pageRoom();+ let l = 0; while (l < TRV && glide((l + 1) / TRV) * Math.abs(AX[0]) <= room) l++;+ return TYPE + l - SINK;+ };+ // (the drawn look's lines are written in ink, left on the same margin: a hand line is narrower than its+ // set width estimate, so it is measured by its own glyphs. Each takes 12 frames, 10 after the one before,+ // so the page is written by the time the travel lands: ink alone changes too little of a phone frame to+ // read as motion (the gate's dead air), and the page must be done moving before it holds to be read)+ const ST = clean ? CLEAN_ST : 10, WR = clean ? 18 : 12, lineW = (t: string, size: number) => (clean ? LK.measure.display(t, size) : measure(t, size));+ const pageFit = (lines: TypeLine[]) => {+ const nL = lines.length, at = L.type.at, x0 = at ? at[0] - L.type.maxW / 2 : (W - L.type.maxW) / 2, maxW = L.type.maxW * PAGE_MEASURE;+ const size = Math.min(nL === 1 ? 220 : 170, ...lines.map((l) => (maxW / lineW(l.text, 100)) * 100)), gap = size * (clean ? 1.12 : 1.3), y0 = (at ? at[1] : H / 2) - ((nL - 1) * gap) / 2 + size * 0.36;+ return { x0, y0, size, gap, c: (at ?? [W / 2, H / 2]) as P };+ };+ const pageSet = (n: number) => PAGE_ON + WR + (n - 1) * ST - (clean ? 9 : 0); // local frame the last line is set (set type's out-cubic settles to the pixel 9 frames early; a pen line is done when its last stroke is)+ const pageScene = (ctx: Ctx, env: Env, lines: TypeLine[], local: number, k: number) => {+ const PAGE_OUT = pageOut(k);+ ground(ctx, env);+ const g = pageFit(lines), c = placed(ctx, env, { z: 1 + 0.06 * ramp(local, 0, TYPE + TRV), c: g.c });+ lines.forEach((l, i) => {+ const y = g.y0 + i * g.gap, p = ramp(local, PAGE_ON + i * ST, PAGE_ON + WR + i * ST), out = sunk((local - PAGE_OUT) / SINK, i, lines.length);+ if (!lineShown(c, env, l.text, g.x0, y, g.size, lineW(l.text, g.size))) return;+ if (clean) setType(c, env, l.text, g.x0, y, g.size, p, { font: LK.fonts.display, color: l.color === C.accent ? THEME.accent : l.color ?? PAL.ink, weight: 800, out });+ else writeOn(c, env, l.text, g.x0, y, g.size, p, l.style, { color: l.color, align: "left", seed: 7 + i, out, tool: PEN });+ });+ bug(ctx, env);+ };+ // the place a travel into ask i leaves: the word page before it (still creeping), or the ask before it, on its last frame+ const fitted = words.map((w) => (w?.length ? fitWords(w, L) : null));+ // a word page is read from the frame its last line is set until its lines start to sink: that must be+ // the reading rule's time (readable.ts readS), or the beat is too short for its words+ fitted.forEach((wl, i) => {+ if (!wl || i >= n - 1) return;+ const need = Math.ceil(readS(wl.map((x) => x.text).join(" ")) * 30), have = Math.min(TYPE, pageOut(i)) - pageSet(wl.length); // (read until the sink, or until the travel carries the page off)+ if (have < need) throw new Error(`launchTemplate: the word page "${wl.map((x) => x.text).join(" ")}" is up ${(have / 30).toFixed(2)} s once set and needs ${(need / 30).toFixed(2)} s to be read (readS), after ${(TRV / 30).toFixed(1)} s of travel in and before its 0.6 s sink; raise typeBeats or use fewer words`);+ });+ const prevPlace = (c: Ctx, env: Env, i: number, l: number) => { const wl = fitted[i - 1]; if (wl) pageScene(c, env, wl, TYPE + l, i - 1); else sceneOf(c, env, T[i].base - 1, i - 1); };+// ---------------------------------------------------------------- the motif: the drop that becomes the mark's dotconst MOTIF = spec.motif !== false;- const titleSize = clean ? Math.min(L.end.titleMax * 1.6, (L.end.titleW / (estWidth(spec.title, 100) * 1.1)) * 100) : Math.min(L.end.titleMax, (L.end.titleW / measure(spec.title, 100)) * 100);+ // a split beat's words are read too: from the frame the last line is set until they have sunk (the frame+ // check reads a line until it leaves; a beat shorter than its words' reading time is an error here, early)+ spec.asks.forEach((a, i) => {+ if (isChat(a) || !a.split?.length) return;+ const lines = splitFit(a.split).lines, set = wordsAt(TIN[i]) + 18 + (lines.length - 1) * 12, sink = sinkAt(i);+ const text = a.split.map((x) => x.text).join(" "), need = Math.ceil(readS(text) * 30), have = sink + SINK - set;+ if (have < need) throw new Error(`launchTemplate: the split words "${text}" of ask ${i} are up ${(have / 30).toFixed(2)} s once set, to the end of their sink, and need ${(need / 30).toFixed(2)} s to be read (readS); raise ${i === n - 1 && spec.claimBar !== undefined ? "claimBar (a later bar for the end card)" : "askBeats"} or use fewer words`);+ });+ // THE LOGO SIGNS THE CLEAN END CARD (a look with a logo, the stacked card): it stands before the name on its+ // baseline, LOGO_H of the name's size tall, and the group (logo, name, dot) shares the name's width budget+ const END_LOGO = clean && spec.endCard !== "grid" ? LK.chat.logo : undefined, LOGO_H = 0.86, LOGO_GAP = 0.24;+ const logoW1 = END_LOGO ? (LOGO_H * END_LOGO.w) / END_LOGO.h + LOGO_GAP : 0; // per unit of the name's size+ const titleSize = clean ? Math.min(L.end.titleMax * 1.6, (L.end.titleW / ((LK.customDisplay ? LK.measure.display(spec.title, 100) : estWidth(spec.title, 100) * 1.1) + 100 * logoW1)) * 100) : Math.min(L.end.titleMax, (L.end.titleW / measure(spec.title, 100)) * 100);// the clean end card is ONE centred group with presence: the wordmark large, the line under it,// the install block, the footer, stacked and centred in the frame (the drawn one keeps its layout)const END_L = (() => {if (!clean) return L.end;// (9x16: measured on the safe rectangle's width and centred on its height)- const AW = ZONES ? SAFE.w - 24 : W, E = L.end, tp = E.taglinePx * 1.5, tl = wrapEst(spec.tagline, tp, AW * (ZONES ? 0.9 : 0.8)), tLH = Math.round(tp * 1.3);- const inst = installRows(spec.install, AW * 0.86 - 2 * E.padX, minPx, E.monoPx * 1.35), mono = inst.px, rowH = Math.round(mono * 2), ph = rowH * inst.rows.length + 50 * k;+ // (on a phone the card is centred on the frame's axis, which sits left of the safe rectangle's: each line+ // gets the width the axis leaves it inside that rectangle, 10 px clear on each side, never 90 % of the+ // whole safe width: a line set in a real face ran into the button column)+ const AW = ZONES ? SAFE.w - 24 : W, E = L.end, axisW = ZONES ? 2 * Math.min(SAFE.x + SAFE.w - E.cx, E.cx - SAFE.x) - 20 : Infinity;+ const tp = E.taglinePx * 1.5, tl = LK.wrap(spec.tagline, tp, Math.min(axisW, AW * (ZONES ? 0.9 : 0.8))), tLH = Math.round(tp * 1.3);+ const inst = installRows(spec.install, Math.min(axisW, AW * 0.86) - 2 * E.padX, minPx, E.monoPx * 1.35), mono = inst.px, rowH = Math.round(mono * 2), ph = rowH * inst.rows.length + 50 * k;if (mono < minPx - 1e-9) throw new Error(`launchTemplate ${shape}: the install lines would be ${mono.toFixed(1)} px on the clean end card (phone-safe minimum ${minPx} px). Shorten the install line, or ship this shape without it`);const g1 = titleSize * 0.42, g2 = tLH * 0.9, g3 = spec.footer ? 44 * k : 0, block = titleSize * 0.74 + g1 + tl.length * tLH + g2 + ph + g3 + (spec.footer ? E.footerPx : 0);const titleY = (ZONES ? SAFE.y * 2 + SAFE.h - block : H - block) / 2 + titleSize * 0.74, taglineY = titleY + g1 + tLH / 2, panelY = taglineY + (tl.length - 0.5) * tLH + g2;return { ...E, titleY, tagline: tl, taglinePx: tp, taglineLH: tLH, taglineY, panelY, monoPx: mono, rows: inst.rows, wrapped: inst.wrapped, rowH, lineY0: panelY + 25 * k + rowH / 2, footerY: panelY + ph + g3 + E.footerPx / 2, caret: [Math.round(mono * 0.53), Math.round(mono * 1.13)] as [number, number] };})();- const titleW = clean ? estWidth(spec.title, titleSize) * 1.08 : measure(spec.title, titleSize);- const dotR = titleSize * (clean ? 0.1 : 0.085), dotGap = titleSize * 0.1;- const P1: P = [END_L.cx + titleW / 2 - (dotGap + 2 * dotR) / 2 + dotGap + dotR, END_L.titleY - dotR * 1.05];+ const titleW = clean ? (LK.customDisplay ? LK.measure.display(spec.title, titleSize) : estWidth(spec.title, titleSize) * 1.08) : measure(spec.title, titleSize);+ // the grid end card (endCard.ts): its lockup is the name set right up to the drop, which sits on the+ // baseline as the name's full stop. The lockup's box is fixed by its aspect, so the dot's place is+ // known here, before anything is drawn, and the motif's drop can fly to it.+ const GRID = spec.endCard === "grid", GRID_ON = 30, LOCK = { cap: 0.74, dot: 0.1, gap: 0.1 }; // per unit of the name's type size+ const CARD_SPEC: EndCardSpec | null = GRID ? {+ // (the name sits on the box's foot: a descender hangs about 0.3 of the box below it, and the line under+ // it keeps its air under the letters: a fresh critic saw the y's tail 15 px over the tagline)+ lockup: { aspect: ((LK.customDisplay ? LK.measure.display(spec.title, 100) : estWidth(spec.title, 100)) + 100 * (LOCK.gap + 2 * LOCK.dot)) / (100 * LOCK.cap), descent: /[gjpqy,;]/.test(spec.title) ? 0.3 : 0, draw: (c, b) => {+ const size = b.h / LOCK.cap, room = b.w - size * (LOCK.gap + 2 * LOCK.dot); // the dot is drawn by the end page: it is where the drop lands+ // the box comes from an estimate of the name's width: the real face is scaled to fill it exactly, so+ // the name starts on the card's margin and ends one gap before the dot (within 25 % either way)+ c.font = LK.fonts.display(800, size); const k = clamp(room / c.measureText(spec.title).width, 0.75, 1.25);+ c.font = LK.fonts.display(800, size * k); c.fillStyle = PAL.ink; c.textAlign = "right"; c.textBaseline = "alphabetic"; c.fillText(spec.title, b.x + room, b.y + b.h); c.textAlign = "left";+ } },+ date: spec.tagline, venue: spec.install.join(" · "), cta: spec.footer ?? `Get ${spec.title}`,+ // no sponsor band under this card: the stamp sits one gap after the text block, not at the far edge+ stamp: "inline",+ // the install line is set in mono, as a viewer would type it: it sits in the card's venue slot, its only 600-weight line+ colors: { ink: PAL.ink, accent: ACC ?? PAL.accent, ctaInk: LK.custom ? LK.onAccent : "#ffffff" }, font: (w, px) => (w === 600 ? LK.fonts.mono(px) : w >= 800 ? LK.fonts.display(w, px) : LK.fonts.text(w, px)),+ } : null;+ const CARD_L = CARD_SPEC ? endCardLayout(W, L.H, CARD_SPEC, (t, font) => LK.measureFont(t, font)) : null, LOCKUP = CARD_L?.lockup ?? null;+ // with no sponsor band at its foot the card's group is centred on the height (9:16: on the platforms'+ // safe band), so it does not hang from the top margin over an empty lower half+ const CARD_DY = CARD_L ? (() => { const top = CARD_L.lockup.y, bottom = Math.max(CARD_L.venue.y + CARD_L.venue.h, CARD_L.cta.y + CARD_L.cta.h), [lo, hi] = CARD_L.shape === "tall" ? [L.H * 0.17, L.H * 0.74] : [0, L.H]; return CARD_L.logos.length ? 0 : Math.round((lo + hi - (bottom - top)) / 2 - top); })() : 0;+ const dotR = LOCKUP ? (LOCKUP.h / LOCK.cap) * LOCK.dot : titleSize * (clean ? 0.1 : 0.085), dotGap = titleSize * 0.1;+ // the name and its dot are centred on the card's axis by their INK: a written name's first stroke starts a+ // side bearing after its advance width does, and centred by the advance it sat that far right of the axis+ const titleInkL = clean ? 0 : inkSpan(spec.title, titleSize, { seed: 11 })[0];+ const LOGO_W = logoW1 * titleSize; // the logo and its gap, in px+ const P1: P = LOCKUP ? [LOCKUP.x + LOCKUP.w - dotR, LOCKUP.y + CARD_DY + LOCKUP.h - dotR * 1.05] : [END_L.cx + (titleW + dotGap - titleInkL + LOGO_W) / 2, END_L.titleY - dotR * 1.05];+ // the logo's box: its left edge opens the group, its foot on the name's baseline+ const LOGO_BOX = END_LOGO ? (() => { const h = LOGO_H * titleSize, w = (h * END_LOGO.w) / END_LOGO.h, right = MOTIF ? P1[0] - dotR - dotGap - titleW - LOGO_GAP * titleSize : END_L.cx + (titleW + LOGO_W) / 2 - titleW - LOGO_GAP * titleSize; return { x: right - w, y: END_L.titleY - h, w, h }; })() : null;const coverFrom = (p: P) => Math.max(...[[0, 0], [W, 0], [0, H], [W, H]].map(([x, y]) => Math.hypot(x - p[0], y - p[1])));- const RAD = coverFrom(P1) * 1.14, R0 = bloomRadius(2, 1e6, { inF: 16, close: false, radius: RAD }), RIM = Math.max(1, dotR - R0);+ // THE END CARD'S BLOOM opens at an even pace, its rim never faster than nine tenths of the brand's+ // temperament allows (motionKit.TEMPERAMENTS; lively when the brief names none), so the frames it takes+ // follow the distance it covers: about 30 on a wide frame, 43 on a phone one. The expo it had took most+ // of the frame in four, then the name's first strokes on the bare page were a second swap: two slide+ // cuts in a row on a phone frame (motionscan), and its rim swept past at 200 px a frame.+ const RAD = coverFrom(P1) * 1.14, TEMPER = spec.motion?.temperament ?? "lively", RIM_PACE = 0.9 * (typeof TEMPER === "string" ? TEMPERAMENTS[TEMPER] ?? TEMPERAMENTS.lively : TEMPER).maxSpeed * speedCeiling(W, 30);+ // (the page is drawn from local frame 2, so the even opening starts there, from nothing: the landed drop is+ // its first size, never a disc already 150 px across that the drop had to swell into on its way)+ const BLOOM_N = Math.ceil(RAD / RIM_PACE), END_BLOOM = { inF: BLOOM_N, ease: (t: number) => clamp((t * (BLOOM_N + 2) - 2) / BLOOM_N), close: false };+ const R0 = bloomRadius(2, 1e6, { ...END_BLOOM, radius: RAD }), RIM = Math.max(1, dotR - R0);// where the drop lifts off: Generate as the viewer sees it on the last chat ask (the card's centre if the lean hid it), the product's action, or the film's cardconst liftAt = (f: number): P => {const i = n - 1, a = spec.asks[i];- if (!isChat(a)) return a.kind === "ui" ? uiScreen(i, f, uiActionAt(panelOf(i), a.ui, minPx)) : ((c) => [c.x + c.w / 2, c.y + c.h / 2] as P)(filmCard(i));+ // (a product's drop swells beside its action, to the left on the header, never on the button's word)+ if (!isChat(a)) return a.kind === "ui" ? uiScreen(i, f, (({ x, y, h }) => [x - 56 * k, y + h / 2] as P)(uiActionRect(panelOf(i), a.ui, minPx))) : ((c) => [c.x + c.w / 2, c.y + c.h / 2] as P)(filmCard(i));const cam = camAt(caretEst, f, i).cam, g = toScreen(cam, GEN_C, W, H), inFrame = g[0] > 60 && g[0] < W - 60 && g[1] > 60 && g[1] < H - 60;return inFrame ? g : toScreen(cam, [TH.cardX + CARD / 2, cardY(i, f) + CARD / 2], W, H);};@@ -415,7 +908,10 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {if (!MOTIF || f < END0 - DL - LIFT || f >= END0) return;ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.fillStyle = INK;if (f < END0 - DL) { const w = out3(ramp(f, END0 - DL - LIFT, END0 - DL)); ctx.beginPath(); ctx.arc(S0[0], S0[1], 30 * k * camZ * (0.2 + 0.8 * w), 0, Math.PI * 2); ctx.fill(); return; }- for (let j = 24; j >= 0; j--) { const q = path(Math.max(END0 - DL, f - j * 0.1)); if (!q) continue; ctx.globalAlpha = j === 0 ? 1 : 0.22 * (1 - j / 25); ctx.beginPath(); ctx.arc(q.p[0], q.p[1], q.r * (1 - j * 0.02), 0, Math.PI * 2); ctx.fill(); }+ // the drawn look trails ghosts of ink; the clean look's one accent is never see-through (layerscan+ // translucent: a brand colour at a part alpha reads as mud), so its drop stretches into one solid,+ // tapering streak along its path instead+ for (let j = 24; j >= 0; j--) { const q = path(Math.max(END0 - DL, f - j * 0.1)); if (!q) continue; ctx.globalAlpha = clean || j === 0 ? 1 : 0.22 * (1 - j / 25); ctx.beginPath(); ctx.arc(q.p[0], q.p[1], q.r * (clean ? 1 - j * 0.034 : 1 - j * 0.02), 0, Math.PI * 2); ctx.fill(); }ctx.globalAlpha = 1;};// the seam, checked: the drop's pose as it lands (the ask's side) is the ink the end card blooms from@@ -426,42 +922,69 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const i = askOf(f), t = T[i], l = f - t.base;// a seam between kinds: the new scene blooms open over the last frame of the one before// (+4: a bloom's first frames open by less than a pixel)- if (t.tin && l < t.tin) bloomFrame(ctx, env, l + 4, 1e6, () => sceneOf(ctx, env, t.base - 1, i - 1), (c) => sceneOf(c, env, f, i), { close: false, inF: 14, W, H, ...bloomOpts });+ if (t.tin && l < t.tin) travel(ctx, env, (l + 0.5) / t.tin, (c) => prevPlace(c, env, i, l), (c) => sceneOf(c, env, f, i), axOf(`ask:${i}`), !fitted[i - 1] && isChat(spec.asks[i - 1]));else sceneOf(ctx, env, f, i);if (withDrop) motifDrop(ctx, env, f);};// ---------------------------------------------------------------- the end card+ // the stacked card's name: end-card frames it writes (or sets) over; with the motif it starts as the page+ // opens from the dot, without it a little later. NAME_ON is the frame it is all on (set type's out-cubic+ // settles to the pixel 9 frames early; an ink line is done when its last stroke is). The drawn name is+ // written in 24 frames, as the bloom opens: written slower, its last strokes on the open page were too+ // small a change to read as motion and too early to be the hold (the gate's dead air)+ const NAME_W: [number, number] = clean ? (MOTIF ? [4, 26] : [8, 30]) : MOTIF ? [4, 28] : [10, 34], NAME_ON = NAME_W[1] - (clean ? 9 : 0) + 1;const endPage = (c: Ctx, env: Env, e: number) => {- const E = END_L, cx = E.cx, size = titleSize;+ if (CARD_SPEC) { // the grid card: its parts rise into place in turn beside the landed drop+ // once it is all on, the card settles (endZ) and then rests: the frame people read and screenshot+ const k = c;+ k.setTransform(env.scale, 0, 0, env.scale, 0, env.scale * CARD_DY); drawEndCard(k, env, CARD_SPEC, ramp(e, 4, GRID_ON));+ k.setTransform(env.scale, 0, 0, env.scale, 0, 0); k.fillStyle = INK; k.beginPath(); k.arc(P1[0], P1[1], dotR, 0, Math.PI * 2); k.fill();+ c.textAlign = "left"; c.textBaseline = "alphabetic"; return;+ }+ const E = END_L, cx = E.cx, size = titleSize, [n0, n1] = NAME_W;// (with the motif the page blooms from the dot, wider and sooner: the name starts as it opens, so no frame waits)- if (MOTIF) { const tx = P1[0] - dotR - dotGap; if (clean) setType(c, env, spec.title, tx, E.titleY, size, ramp(e, 4, 26), { align: "right", color: PAL.ink, weight: 800 }); else writeOn(c, env, spec.title, tx, E.titleY, size, ramp(e, 4, 40), "ink", { color: C.ink, align: "right", seed: 11 }); c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = INK; c.beginPath(); c.arc(P1[0], P1[1], dotR, 0, Math.PI * 2); c.fill(); }- else if (clean) setType(c, env, spec.title, cx, E.titleY, size, ramp(e, 8, 30), { align: "center", color: PAL.ink, weight: 800 });- else writeOn(c, env, spec.title, cx, E.titleY, size, ramp(e, 10, 44), "ink", { color: C.ink, align: "center", seed: 11 });+ if (MOTIF) { const tx = P1[0] - dotR - dotGap; if (clean) setType(c, env, spec.title, tx, E.titleY, size, ramp(e, n0, n1), { font: LK.fonts.display, align: "right", color: PAL.ink, weight: 800 }); else writeOn(c, env, spec.title, tx, E.titleY, size, ramp(e, n0, n1), "ink", { color: C.ink, align: "right", seed: 11, tool: PEN }); c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = INK; c.beginPath(); c.arc(P1[0], P1[1], dotR, 0, Math.PI * 2); c.fill(); }+ else if (clean) setType(c, env, spec.title, cx + LOGO_W / 2, E.titleY, size, ramp(e, n0, n1), { font: LK.fonts.display, align: "center", color: PAL.ink, weight: 800 });+ else writeOn(c, env, spec.title, cx, E.titleY, size, ramp(e, n0, n1), "ink", { color: C.ink, align: "center", seed: 11, tool: PEN });+ // the logo grows in about its own foot with the name (whole, never see-through: a brand element is opaque)+ if (END_LOGO && LOGO_BOX) { const g = out3(ramp(e, n0, n0 + 12)); if (g > 0.01) { const B = LOGO_BOX, sc = (B.h / END_LOGO.h) * g; c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.save(); c.translate(B.x + B.w / 2, B.y + B.h); c.scale(sc, sc); c.translate(-END_LOGO.w / 2, -END_LOGO.h); drawEl(c, END_LOGO, { name: "logo" }); c.restore(); } }c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.textAlign = "center"; c.textBaseline = "middle";- const Q = clean && MOTIF ? -14 : 0; // the clean name is set in 22 frames, not written in 36: the rest follows it closer- // the clean look's lines rise into place as they appear, like its type (the drawn look's fade in under the written name)- const rise = (a: number) => (clean ? (1 - out3(ramp(e, a, a + 12))) * 22 * L.k : 0);- c.globalAlpha = ramp(e, 34 + Q, 46 + Q); c.fillStyle = PAL.soft; c.font = SANS(500, E.taglinePx); E.tagline.forEach((t, j) => c.fillText(t, cx, E.taglineY + j * E.taglineLH + rise(34 + Q)));- c.translate(0, rise(40 + Q));- c.globalAlpha = ramp(e, 40 + Q, 52 + Q); c.font = MONO(E.monoPx);- // one row per install line, centred; a wrapped line's rows are set left in the panel, its continuation indented+ // THE LINE, THE INSTALL PANEL AND THE FOOTER OPEN WITH THE PAGE: the bloom reveals them whole, and only the+ // name writes itself. Each used to fade in after the name (a dissolve to motionscan), and a big dark panel+ // arriving on an empty page in a few frames was a second slide cut after the bloom's. Open from the+ // first frame, the install lines are on screen for the whole end card.+ c.fillStyle = PAL.soft; c.font = LK.fonts.text(500, E.taglinePx); E.tagline.forEach((t, j) => c.fillText(t, cx, E.taglineY + j * E.taglineLH));+ c.font = LK.fonts.mono(E.monoPx);+ // one row per install line, every row set left in the panel as a terminal sets them (centred rows started+ // at different places and read as a caption); a wrapped line's continuation is indentedconst rows = E.rows, nI = rows.length, cw = c.measureText("0").width, rowW = (r: { text: string; indent: number }) => c.measureText(r.text).width + r.indent * cw;const pw = (E.wrapped ? Math.max(...rows.map(rowW)) : Math.max(...spec.install.map((s) => c.measureText(s).width))) + 2 * E.padX, ph = E.rowH * nI + 2 * (E.lineY0 - E.panelY) - E.rowH, py = E.panelY, x0 = cx - pw / 2 + E.padX;c.fillStyle = clean ? PAL.ink : "#1f1c18"; rr(c, cx - pw / 2, py, pw, ph, 22 * L.k); c.fill();- c.fillStyle = clean ? "#ffffff" : "#ece4d6";- if (E.wrapped) { c.textAlign = "left"; rows.forEach((r, j) => c.fillText(r.text, x0 + r.indent * cw, E.lineY0 + j * E.rowH)); c.textAlign = "center"; }- else spec.install.forEach((s, j) => c.fillText(s, cx, E.lineY0 + j * E.rowH));+ // (a custom look's panel is its ink with its ground's colour for the words: a light ink took white words)+ c.fillStyle = clean ? (LK.custom ? PAL.bg : "#ffffff") : "#ece4d6";+ c.textAlign = "left"; rows.forEach((r, j) => c.fillText(r.text, x0 + r.indent * cw, E.lineY0 + j * E.rowH)); c.textAlign = "center";// a terminal caret blinks after the last row: the hold reads as live, never as a freeze- const lastW = c.measureText(rows[nI - 1].text).width, caretX = E.wrapped ? x0 + rowW(rows[nI - 1]) + 8 * (E.monoPx / 30) : cx + lastW / 2 + 8 * (E.monoPx / 30);- if (Math.floor((e - 40 - Q) / 15) % 2 === 0) { if (clean) c.fillStyle = THEME.accent; c.fillRect(caretX, E.lineY0 + (nI - 1) * E.rowH - E.caret[1] / 2, E.caret[0], E.caret[1]); }- if (spec.footer) { c.fillStyle = PAL.soft; c.font = SANS(500, E.footerPx); c.fillText(spec.footer, cx, E.footerY); }+ const lastW = c.measureText(rows[nI - 1].text).width, caretX = x0 + rowW(rows[nI - 1]) + 8 * (E.monoPx / 30);+ if (Math.floor((e - NAME_ON) / 15) % 2 === 0) { if (clean) c.fillStyle = THEME.accent; c.fillRect(caretX, E.lineY0 + (nI - 1) * E.rowH - E.caret[1] / 2, E.caret[0], E.caret[1]); }+ if (spec.footer) { c.fillStyle = PAL.soft; c.font = LK.fonts.text(500, E.footerPx); c.fillText(spec.footer, cx, E.footerY); }c.globalAlpha = 1; c.textAlign = "left"; c.setTransform(env.scale, 0, 0, env.scale, 0, 0);};+ // THE END CARD SETTLES, never a dead hold: as its last part lands the page leans in 3 % (END_CREEP),+ // easing out to rest a second before the end (the frame people screenshot). A fresh critic read four+ // seconds of a still card as the film stopping. The install lines stay put to the eye: at its fastest the+ // lean moves a line's end by under a pixel a frame. It starts while the parts still land and only slows+ // from there: a creep that started from still (linear, or an in-out) left still stretches on both sides of+ // its move, and motionscan read them on 9x16 as one layout settling three times in a row.+ // (the stacked card leans in about a point on its own axis, level with the dot: about the dot itself, which+ // sits at the name's right end, the lean carried every line of the card left by 3 % of the dot's distance+ // from the axis, 20 px on 16:9, a fresh critic's d4-1. The grid card is not centred: it leans about its dot)+ const END_CREEP: P = GRID ? P1 : [END_L.cx, P1[1]];+ const ALL_ON = GRID ? GRID_ON : NAME_ON, endZ = (e: number) => 1 + 0.03 * out3(ramp(e, ALL_ON - 10, END - 30));const content = (ctx: Ctx, env: Env, f: number, exact: boolean) => {const g = clamp(exact ? Math.round(f) : f, 0, END0 + END - 1);if (g < END0) return askScene(ctx, env, g);const e = g - END0;- bloomFrame(ctx, env, e + 2, END + 2, () => askScene(ctx, env, END0 - 1, false), (c) => endPage(c, env, e), { close: false, inF: 16, W, H, ...bloomOpts, ...(MOTIF ? { center: P1, radius: RAD, rim: lerp(RIM, clean ? 0 : 26, out3(ramp(e, 0, 7))), ink: INK } : {}) });+ bloomFrame(ctx, env, e + 2, END + 2, () => askScene(ctx, env, END0 - 1, false), (c) => endPage(placed(c, env, { z: endZ(e), c: END_CREEP }), env, e), { ...END_BLOOM, W, H, ...bloomOpts, ...(MOTIF ? { center: P1, radius: RAD, rim: lerp(RIM, clean ? 0 : 26, out3(ramp(e, 0, 7))), ink: INK } : {}) });};// ---------------------------------------------------------------- the cut, as data@@ -470,7 +993,7 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const last = i === n - 1;const b = BASE[i], e = b + LEN[i];segs.push(last && spec.claimBar !== undefined ? pic(b, e, SOLVED) : pic(b, e)); // SOLVED < ASK plays the ask faster; never slower- if (!last && words[i]?.length) segs.push(type(fitWords(words[i], L), TYPE, e - 1, e));+ if (!last && words[i]?.length) segs.push(type(fitted[i]!, TYPE, e - 1, e)); // (the fitted lines themselves: a page knows its index by them)});// the score plays at the film's bpm, exactly: the cuts sit on this grid. Sync wins over length, so// the end-card hold (not the tempo) takes up the difference: the film becomes whole bars of the score.@@ -478,24 +1001,12 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {if (bed) END = bed.end;segs.push(pic(END0, END0 + END));const cut = makeCut(segs);- // a clean word page: a round iris, the lines SET (heavy sans, left-aligned at the margin, each rising into place)- const cleanType = (ctx: Ctx, env: Env, lines: TypeLine[], local: number, len: number, under: (first: boolean) => void) => bloomFrame(ctx, env, local, len, under, (c) => {- const nL = lines.length, maxW = L.type.maxW, at = L.type.at, x0 = at ? at[0] - maxW / 2 : (W - maxW) / 2;- const size = Math.min(nL === 1 ? 220 : 170, ...lines.map((l) => (maxW / (estWidth(l.text, 100) * 1.12)) * 100)), gap = size * 1.12, y0 = (at ? at[1] : H / 2) - ((nL - 1) * gap) / 2 + size * 0.36;- lines.forEach((l, i) => setType(c, env, l.text, x0, y0 + i * gap, size, ramp(local, 14 + TYPE_O.lead + i * CLEAN_ST, 14 + TYPE_O.lead + 18 + i * CLEAN_ST), { color: l.color === C.accent ? THEME.accent : l.color ?? PAL.ink, weight: 800 }));- bug(c, env);- }, { W, H, ...bloomOpts, rim: 4, ink: THEME.accent, radius: TYPE_R, ...(L.type.at ? { center: L.type.at } : {}) });- // a word page's bloom is sized to the frame it covers (the desktop's 1250 px over a 1110 px cover):- // on a smaller frame a fixed bloom would cover it before the words start, and two frames would match- const TYPE_R = L.shape === "16x9" ? undefined : Math.round((1250 * L.type.cover) / 1110);- // (9x16: the page blooms from the words' centre, so its first drop lands where the words will be)- const TYPE_OPTS = L.shape === "16x9" ? TYPE_O : { ...TYPE_O, W, H, maxW: L.type.maxW, radius: TYPE_R, ...(L.type.at ? { text: L.type.at, center: L.type.at } : {}) };const drawStage = (ctx: Ctx, env: Env, t: number) => {const { s, local } = cut.at(t), exact = Number.isInteger(t);if (s.kind === "pic") content(ctx, env, cut.contentOf(s, local), exact);// offset by 2 frames at each end so the bloom is already moving on the first and last frame- else if (clean) cleanType(ctx, env, s.lines, local + 2, s.len + 4, (first) => content(ctx, env, first ? s.before : s.after, true));- else typeFrame(ctx, env, s.lines, local + 2, s.len + 4, (first) => content(ctx, env, first ? s.before : s.after, true), (c) => bug(c, env), TYPE_OPTS);+ // (clean: the camera travels from the ask to the word page; it travels on to the next ask in that ask's own first frames)+ else { const k = fitted.indexOf(s.lines); if (local < TRV) travel(ctx, env, (local + 0.5) / TRV, (c) => content(c, env, s.before, true), (c) => pageScene(c, env, s.lines, local, k), axOf(`page:${k}`), isChat(spec.asks[k])); else pageScene(ctx, env, s.lines, local, k); }};// ---------------------------------------------------------------- captions: the words a viewer reads, in cut frames@@ -505,7 +1016,7 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const t = T[i], lo = cut.STARTS[cut.SEGS.findIndex((sg) => sg.kind === "pic" && sg.from === t.base)] ?? 0;if (isChat(a) || (a.kind === "ui" && a.prompt)) { const from = Math.max(lo, cutAt(t.base + Math.max(t.tin, t.times[0] ?? 0))), to = cutAt(t.base + Math.min(t.len - 1, isChat(a) ? t.drop.full : t.drop.t0 + 24)); if (from >= 0 && to > from) caps.push({ from, to, text: isChat(a) ? a.prompt : a.prompt! }); }const split = !isChat(a) ? a.split : undefined;- if (split?.length) { const from = cutAt(t.base + t.tin + 4), to = cutAt(t.base + t.len - 1) + 1; caps.push({ from, to, text: split.map((x) => x.text).join(" ") }); }+ if (split?.length) { const from = cutAt(t.base + wordsAt(t.tin) + 4), to = cutAt(t.base + t.len - 1) + 1; caps.push({ from, to, text: split.map((x) => x.text).join(" ") }); }});cut.SEGS.forEach((sg, k) => { if (sg.kind === "type") caps.push({ from: cut.STARTS[k] + 12, to: cut.STARTS[k] + sg.len, text: sg.lines.map((x) => x.text).join(" ") }); });const endAt = cut.STARTS[cut.SEGS.length - 1];@@ -519,8 +1030,8 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {ctx.fillStyle = PAL.card; ctx.fillRect(B.x, B.y, B.w, B.h); ctx.fillStyle = PAL.line; ctx.fillRect(B.x, B.y, B.w, 2);const c = capAt(t); if (!c) return;const TX = ZONES ? { x: SAFE.x, w: SAFE.w } : B; // the caption's own column: on 9x16 clear of the right-hand buttons- const px = Math.max(36, Math.round(B.h * 0.2)), lines = wrapEst(c.text, px, TX.w - 120).slice(0, 2), a = Math.min(ramp(t, c.from, c.from + 6), 1 - ramp(t, c.to - 6, c.to));- ctx.globalAlpha = a; ctx.fillStyle = PAL.ink; ctx.font = SANS(600, px); ctx.textAlign = "center"; ctx.textBaseline = "middle";+ const px = Math.max(36, Math.round(B.h * 0.2)), lines = LK.wrap(c.text, px, TX.w - 120).slice(0, 2), a = Math.min(ramp(t, c.from, c.from + 6), 1 - ramp(t, c.to - 6, c.to));+ ctx.globalAlpha = a; ctx.fillStyle = PAL.ink; ctx.font = LK.fonts.text(600, px); ctx.textAlign = "center"; ctx.textBaseline = "middle";lines.forEach((l, j) => ctx.fillText(l, TX.x + TX.w / 2, B.y + B.h / 2 + (j - (lines.length - 1) / 2) * px * 1.25)); ctx.globalAlpha = 1; ctx.textAlign = "left";};const draw = (ctx: Ctx, F: number, env: Env) => {@@ -534,19 +1045,29 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const holds: [number, number][] = [];cut.SEGS.forEach((s, k) => {if (s.kind !== "type") return;- const written = 14 + TYPE_O.lead + 18 + (s.lines.length - 1) * (clean ? CLEAN_ST : TYPE_O.stagger) - (clean ? 9 : 2); // local frame the last line is done (set type's out-cubic settles to the pixel sooner)- // last frame the page still fills the frame (a round iris only clips the corners for its first closing frames: still a still)- const cover = clean ? (L.type.at ? (L.type.cover - 9) * 0.9 : Math.hypot(W, H) / 2 * 0.9) : L.type.cover;- let open = s.len - 1; while (open > written && bloomRadius(open + 2, s.len + 4, { radius: TYPE_R }) < cover) open--;- holds.push([cut.STARTS[k] + written + 1, cut.STARTS[k] + open + 1]);+ // the page is fully set (or written) from pageSet until its lines sink; it creeps, but slowly enough to read as a hold+ holds.push([cut.STARTS[k] + pageSet(s.lines.length), cut.STARTS[k] + Math.min(TYPE, pageOut(fitted.indexOf(s.lines))) + 6]); // (+6: a sink's first frames are an ease-in, still to the eye)});// a solved ask longer than the grid's: the finished card rests on screen until the end card blooms// (with the motif the drop is in flight over those frames, so they are not a hold)if (LEN[n - 1] > ASK && isChat(spec.asks[n - 1]) && !MOTIF) { const S = cut.STARTS[cut.SEGS.length - 2]; holds.push([S + LEN[n - 1] - 18, S + LEN[n - 1] + 6]); }- holds.push([cut.N - END + (clean && MOTIF ? 39 : 53), cut.N]); // the end card, all on: read it, screenshot it+ holds.push([cut.N - END + (GRID ? GRID_ON - 2 : NAME_ON), cut.N]); // the end card, all on: read it, screenshot it (the grid card's out-cubic rise settles to the pixel 2 frames before GRID_ON)// a UI ask's action button bottoms out: the press lands before the items move (a stationary point by// design, one or two frames; at 60 fps and in small shapes the gate reads it as a still)spec.asks.forEach((a, i) => { if (isChat(a) || a.kind !== "ui") return; const F = cut.cutOf(T[i].base + T[i].up); if (F > 0) holds.push([F - 1, F + 2]); });+ // a split beat's words, once they are set and the product beside them has landed, are read until they+ // sink, as a word page's are: the panel creeps, but over a sparse product screen (a scaffold's stand-in,+ // two rows) the creep alone changes too little of the frame to be told from a freeze (the gate's dead air)+ spec.asks.forEach((a, i) => {+ if (isChat(a) || !a.split?.length) return;+ // (set type's out-cubic settles to the pixel 9 frames before its rise ends, as pageSet counts it; an item+ // has landed at its spring's first arrival, its overshoot after it under what the eye reads as moving)+ const t = T[i], set = wordsAt(t.tin) + 18 + (splitFit(a.split).lines.length - 1) * 12 - (clean ? 9 : 0), landed = a.kind === "ui" ? Math.max(t.drop.t0, ...uiSettles(a.ui, { t0: t.drop.t0 }).map((q) => q.frame)) : 0;+ // (reached by a travel, the words are set before the press and read while the product rests in its before+ // state: the hold starts with them, or that rest is dead air to the gate; otherwise once both have landed)+ const sink = sinkAt(i), from = cut.cutOf(t.base + (t.tin > 0 && t.drop.t0 > set ? set : Math.max(set, landed))), to = cut.cutOf(t.base + sink) + 6;+ if (from >= 0 && to > from) holds.push([from, to]);+ });// ---------------------------------------------------------------- sound: the picture's own cuesconst cues: LaunchCue[] = [];@@ -558,8 +1079,8 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {const t = T[i], b = t.base;const prompt = isChat(a) ? a.prompt : a.kind === "ui" ? a.prompt : undefined;// a key for every character typed, a word's first key a touch firmer, the space bar its own sound- if (prompt) t.times.forEach((tm, j) => { if (tm < Math.max(0, t.tin)) return; const ch = prompt[j], first = j === 0 || prompt[j - 1] === " ";- const x = isChat(a) ? screenX(i, b + tm, caretEst(prompt.slice(0, j + 1))) : ((r) => (r ? r.x + 26 * k + estWidth(prompt.slice(0, j + 1), 26) : W / 2))(uiCommandAt(panelOf(i), (a as UiAsk).ui, minPx));+ if (prompt) t.times.forEach((tm, j) => { if (tm < 0) return; /* a key typed before frame 0 is not heard; one typed as the composer travels in is */ const ch = prompt[j], first = j === 0 || prompt[j - 1] === " ";+ const x = isChat(a) ? screenX(i, b + tm, caretEst(prompt.slice(0, j + 1))) : ((r) => (r ? r.x + 26 * k + LK.measure.text(prompt.slice(0, j + 1), 26) : W / 2))(uiCommandAt(panelOf(i), (a as UiAsk).ui, minPx));add(b + tm, { kind: "tick", variant: ch === " " ? "space" : "key", gainDb: first && ch !== " " ? 1.5 : 0, x, role: "key", label: `key ${JSON.stringify(ch)}` }); });if (isChat(a)) {const card = (c: number): P => [TH.cardX + CARD / 2, cardY(i, c) + CARD / 2];@@ -588,11 +1109,23 @@ export const makeLaunchFilm = (spec: LaunchSpec): LaunchFilm => {let memo: Map<string, LaunchFilm> | null = null;const self: LaunchFilm = {meta: { title: `${spec.title} · launch${shape === "16x9" ? "" : ` · ${shape}`}`, W, H: L.H, fps, bpm: spec.bpm, durationFrames: cut.N * m, raster: "cpu", kind: "launch", holds: holds.map(([a, b]) => [a * m - (m - 1), b * m] as [number, number]), ...(bed ? { score: { tempo: spec.bpm, form: bed.form, grid: true } } : {}),- sync, captions: caps.map((c) => ({ from: Math.round(c.from * m), to: Math.round(c.to * m), text: c.text })), poster: Math.round((cut.N - END + 60) * m) },+ sync, captions: caps.map((c) => ({ from: Math.round(c.from * m), to: Math.round(c.to * m), text: c.text })), poster: Math.round((cut.N - END + 60) * m), ...(spec.checks ? { checks: spec.checks } : {}), ...(spec.motion ? { motion: spec.motion } : {}) },assets: { images: {} },shots: [{ id: "cut", start: 0, end: cut.N * m, draw }],audio,claims: [...new Set([...words.flat().map((x) => x.text), ...spec.asks.flatMap((a) => (isChat(a) ? [] : (a.split ?? []).map((x) => x.text))), spec.tagline, ...(spec.claims ?? [])].map((x) => x.trim()).filter(Boolean))],+ grammar: { scrolls, travels: SEAMS.map((seam) => ({ seam, ax: axOf(seam) })), pages: fitted.flatMap((wl, i) => (wl ? [{ i, set: pageSet(wl.length), out: pageOut(i) }] : [])), endBloom: { frames: BLOOM_N, radius: RAD }, lift: S0, endCard: { creep: END_CREEP, cx: END_L.cx, group: [LOGO_BOX ? LOGO_BOX.x : P1[0] - dotR - dotGap - titleW + titleInkL, P1[0] + dotR], logo: LOGO_BOX, tagline: END_L.tagline, taglineW: END_L.tagline.map((t) => LK.measure.text(t, END_L.taglinePx)), room: ZONES ? [SAFE.x, SAFE.x + SAFE.w] : [0, W] }, rests: spec.asks.flatMap((a, i) => (isChat(a) || a.kind !== "ui" ? [] : [uiRest(i)])), dock: clean && HERO ? (() => { const a0 = T[0].b + CLEAN_DOCK.at; return { move: [a0, a0 + CLEAN_DOCK.move] as [number, number], shrink: [a0 + CLEAN_DOCK.move, a0 + CLEAN_DOCK.move + CLEAN_DOCK.shrink] as [number, number], creep: HOOK_CREEP, heroPx: HERO.TEXT.px, dockPx: G.TEXT.px, composer: { x: G.INPUT.x, y: G.INPUT.y, w: G.INPUT.w, h: G.INPUT.h }, window: { x: G.CHAT.x, y: G.CHAT.y, w: G.CHAT.w, h: G.CHAT.h }, viewBottom: VIEW_BOTTOM }; })() : null, drops: chatIdx.map((i) => {+ const t = T[i], d = { t0: t.base + t.drop.t0, land: t.base + t.drop.land }, to: P = [TH.cardX + CARD / 2, cardY(i, t.base + t.drop.land) + CARD / 2];+ const at = (c: number) => { const q = inkDropAt(c, d, to, G); return q ? toScreen(camAt(caretEst, c, i).cam, q.p, W, H) : null; };+ // (`landing`: the slowest it moves over the last 30 % of the flight, where an in-out crawled)+ let peak = 0, landing = Infinity; for (let c = d.t0; c < d.land - 1; c += 0.5) { const a = at(c), b = at(c + 0.5); if (!a || !b) continue; const v = 2 * Math.hypot(b[0] - a[0], b[1] - a[1]); peak = Math.max(peak, v); if (c >= d.land - 0.3 * (d.land - d.t0)) landing = Math.min(landing, v); }+ return { i, flight: [d.t0, d.land] as [number, number], peak, landing };+ }), lastWords: MOTIF && !isChat(spec.asks[n - 1]) && (spec.asks[n - 1] as UiAsk | FilmAsk).split?.length ? { gone: T[n - 1].base + sinkAt(n - 1) + SINK, flight: [END0 - DL, END0] } : null, heroDock: HERO && !clean ? (() => {+ const a0 = T[0].b + DOCK_AT, pts = (l: number): P[] => { const g = heroAt(0, l), cam = camAt(caretEst, T[0].base + l, 0).cam; return ([[g.INPUT.x, g.INPUT.y], [g.INPUT.x + g.INPUT.w, g.INPUT.y], [g.INPUT.x, g.INPUT.y + g.INPUT.h], [g.INPUT.x + g.INPUT.w, g.INPUT.y + g.INPUT.h], [g.GEN.x, g.GEN.y], [g.TEXT.x, g.TEXT.base]] as P[]).map((p) => toScreen(cam, p, W, H)); };+ let peak = 0; for (let l = a0; l < a0 + DOCK_LEN + 1; l++) { const p = pts(l), q = pts(l + 1); peak = Math.max(peak, ...p.map((x, j) => Math.hypot(q[j][0] - x[0], q[j][1] - x[1]))); }+ const seen = new Set<string>(); for (let l = a0; l < a0 + DOCK_LEN; l++) { const g = heroAt(0, l); seen.add(g.wrapAs ? `${g.wrapAs.px}/${g.wrapAs.maxW}` : `fresh ${l}`); }+ return { frames: [a0, a0 + DOCK_LEN] as [number, number], peak, wraps: seen.size };+ })() : null, splits: spec.asks.flatMap((a, i) => (isChat(a) || !a.split?.length ? [] : [(({ lines, size }) => ({ i, lines: lines.map((x) => x.text), size, tall: (L.split.vertical ? size * 1.25 : size * 1.05) + (lines.length - 1) * size * (clean ? 1.08 : 1.3), room: L.split.words }))(splitFit(a.split))])) },cut, layout: L, cues, seams, heroPx: HERO ? HERO.TEXT.px : null, timing: T, captions: caps.map((c) => ({ from: Math.round(c.from * m), to: Math.round(c.to * m), text: c.text })),// the same film composed for another frame shape (one timeline: the cut, the timing and the sound do not change)reshape: (s: string) => { if (s === shape) return self; memo ??= new Map(); let f = memo.get(s); if (!f) { f = makeLaunchFilm({ ...spec, shape: s as Shape }); memo.set(s, f); } return f; },diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/motionKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/motionKit.tsnew file mode 100644index 0000000..2922f96--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/motionKit.ts@@ -0,0 +1,123 @@+// MOTION KIT. Small helpers that keep a motion-graphics film from turning into a slide deck. Each one+// exists because a brand launch film needed it and wrote it by hand (or got it wrong):+//+// alternate(i, ["left", "right"]) side, direction or entry for the i-th item of a list, never the same twice running+// entryFrom(i) a different entry direction for each item: no carousel+// chatScroll(f, steps, o) a chat column that scrolls over 18-24 frames on an ease-out, never a snap+// temperament(name | spec) the brand's motion temperament as numbers: top speed, settle time, overshoot+// cubicBezier(x1, y1, x2, y2) a CSS / Figma easing curve as a function (brand motion tokens)+// motionTokens(tokens) a brand's exported motion tokens as named eases and durations+// typeExit(q) how far a line of type has sunk on its way out (ease-in, 1.3x its size)+//+// Every function is pure arithmetic over its arguments: no clock, no state, any frame order.+import { speedCeiling } from "./seams";++const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));++/**+ * The i-th choice of a list that never repeats twice running: alternate(i, ["left", "right"]) gives+ * left, right, left. With three or more choices it walks a fixed shuffle so a list of eight items does+ * not read as a strict ping-pong either. The designer's note on the speakers: "each time pop up from a+ * different place".+ */+export const alternate = <T>(i: number, choices: readonly T[]): T => {+ if (!Number.isInteger(i) || i < 0) throw new Error(`alternate: i is a whole index from 0 (got ${i})`);+ if (choices.length < 2) throw new Error("alternate: give at least two choices; one choice repeated is the carousel this helper exists to stop");+ if (choices.length === 2) return choices[i % 2];+ // a stride coprime with the length visits every choice before repeating and never lands on the same one twice in a row+ const n = choices.length; let s = 2; while (gcd(s, n) !== 1) s++;+ return choices[(i * s) % n];+};+const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a);++export type Entry = "left" | "right" | "below" | "above";+/** A different entry for each item: from the left, then the right, then below, then above, in the alternate() walk. */+export const entryFrom = (i: number, from: readonly Entry[] = ["left", "right", "below", "above"]): Entry => alternate(i, from);++/** Where a chat column sits at frame f: each step is { f, by } (start frame, pixels to scroll). Ease-out over `frames` (18-24). */+export const chatScroll = (f: number, steps: readonly { f: number; by: number }[], o: { frames?: number } = {}) => {+ const n = o.frames ?? 20;+ if (!(n >= 18 && n <= 24)) throw new Error(`chatScroll: a scroll takes 18 to 24 frames (got ${n}); fewer is the 100 px-a-frame snap that ghosts the text`);+ let y = 0;+ for (const s of steps) { const u = clamp((f - s.f) / n); y += s.by * (1 - Math.pow(1 - u, 3)); }+ return y;+};++// ---------------------------------------------------------------- temperament+/**+ * A brand's motion temperament, set in the brief before any motion is made. A brand launch film was+ * first "violent" and then "flat": nobody had written down how fast, how soft, and whether things+ * overshoot. maxSpeed is a share of speedCeiling (2.5 frame widths a second), settle is how long an+ * arrival takes in seconds, overshoot says whether arrivals may pass their mark and come back.+ */+export type Temperament = { name: string; maxSpeed: number; settle: [number, number]; overshoot: boolean };+export const TEMPERAMENTS: Record<string, Temperament> = {+ // poured liquid: long, soft, no bounce (a brand launch film, Apple "Intention")+ calm: { name: "calm", maxSpeed: 0.35, settle: [0.5, 1.0], overshoot: false },+ // alive but never violent: small landings, short settles+ lively: { name: "lively", maxSpeed: 0.55, settle: [0.3, 0.7], overshoot: true },+ // snappy product UI: quick arrivals, still under the ceiling+ snappy: { name: "snappy", maxSpeed: 0.8, settle: [0.2, 0.45], overshoot: true },+};+export const temperament = (t: string | Temperament): Temperament & { pxPerFrame: (W: number, fps: number) => number; settleFrames: (fps: number) => [number, number]; arrive: (u: number) => number } => {+ const spec = typeof t === "string" ? TEMPERAMENTS[t] : t;+ if (!spec) throw new Error(`temperament: '${t}' is not one of ${Object.keys(TEMPERAMENTS).join(", ")}; or pass { maxSpeed, settle, overshoot }`);+ if (!(spec.maxSpeed > 0 && spec.maxSpeed <= 1)) throw new Error(`temperament: maxSpeed is a share of speedCeiling, in (0, 1] (got ${spec.maxSpeed})`);+ if (!(spec.settle[0] > 0 && spec.settle[1] >= spec.settle[0])) throw new Error(`temperament: settle is [shortest, longest] seconds (got ${spec.settle})`);+ // an arrival curve that matches: with overshoot a small back-ease (passes by about 4 %), without it a quintic out+ const arrive = spec.overshoot ? (u: number) => { const c = clamp(u), s = 1.2; return 1 + (s + 1) * Math.pow(c - 1, 3) + s * Math.pow(c - 1, 2); } : (u: number) => 1 - Math.pow(1 - clamp(u), 5);+ return { ...spec, arrive, pxPerFrame: (W, fps) => spec.maxSpeed * speedCeiling(W, fps), settleFrames: (fps) => [Math.round(spec.settle[0] * fps), Math.round(spec.settle[1] * fps)] };+};++// ---------------------------------------------------------------- brand motion tokens+/** cubic-bezier(x1, y1, x2, y2) as an easing function of u in [0, 1]: the curve a designer types in Figma or CSS. */+export const cubicBezier = (x1: number, y1: number, x2: number, y2: number) => {+ if (![x1, x2].every((x) => x >= 0 && x <= 1)) throw new Error(`cubicBezier: x1 and x2 must lie in [0, 1] (got ${x1}, ${x2})`);+ const bx = (t: number) => 3 * x1 * t * (1 - t) ** 2 + 3 * x2 * t * t * (1 - t) + t ** 3;+ const by = (t: number) => 3 * y1 * t * (1 - t) ** 2 + 3 * y2 * t * t * (1 - t) + t ** 3;+ return (u: number) => {+ const x = clamp(u); if (x === 0 || x === 1) return x;+ let lo = 0, hi = 1; for (let i = 0; i < 40; i++) { const m = (lo + hi) / 2; if (bx(m) < x) lo = m; else hi = m; } // bisection: exact enough, and never fails to converge+ return by((lo + hi) / 2);+ };+};+/** A brand's motion tokens (brand.mjs import writes brand.motion from Figma's prototype timings). */+export type MotionToken = { ease: [number, number, number, number] | "linear"; ms: number; distance?: number };+/** Named eases and frame counts from the tokens: motionTokens(brand.motion, 60).turn.ease(u), .turn.frames. */+export const motionTokens = (tokens: Record<string, MotionToken>, fps: number) => Object.fromEntries(Object.entries(tokens).map(([k, t]) => {+ if (!(t.ms > 0)) throw new Error(`motionTokens: token "${k}" has no duration (ms ${t.ms})`);+ return [k, { ease: t.ease === "linear" ? (u: number) => clamp(u) : cubicBezier(...t.ease), frames: Math.max(1, Math.round((t.ms / 1000) * fps)), distance: t.distance }];+})) as Record<string, { ease: (u: number) => number; frames: number; distance?: number }>;++// ---------------------------------------------------------------- type exits+/** How far type travels when it sinks out, as a share of its font size: 1.3 clears ascenders and i-dots past the clip. */+export const TYPE_EXIT_TRAVEL = 1.3;+/**+ * A line of type leaving: q 0..1 is its exit progress, the result is how far it has sunk in font sizes.+ * EASE-IN, so it accelerates away and nothing lingers at the clip edge. The ease-out exit (1.0x) on+ * a brand launch film left letter tops visible for about half a second: the director saw them.+ */+export const typeExit = (q: number) => TYPE_EXIT_TRAVEL * Math.pow(clamp(q), 3);++// ---------------------------------------------------------------- the blur mask+/**+ * Draw something that must stay sharp under render --blur (a logo lockup, a UI card with small type):+ * the renderer leaves it out of the blurred subframes and lays the sharp frame's pixels over them.+ * Text and photos are kept sharp automatically; this is for anything else that reads as type.+ */+export const sharp = (draw: () => void) => { if ((globalThis as { __ANIDOODLE_SHARP__?: string }).__ANIDOODLE_SHARP__ === "skip") return; draw(); };++// ---------------------------------------------------------------- landings+/**+ * Squash and stretch for a landing, volume kept: [sx, sy] at frame t for a body landing at frame+ * `land`. Stretched into the ground, squashed for a few frames on contact, round again after (the+ * proof-3 grammar the director called "better than before"). A brand mark keeps its shape: pass brand: true+ * and this refuses unless `gag` names why the squash is the joke (brandKit.drawEl asks the same).+ */+export const landSquash = (t: number, land: number, o: { amount?: number; frames?: number; brand?: boolean; gag?: string } = {}): [number, number] => {+ if (o.brand && !o.gag?.trim()) throw new Error("landSquash: a brand mark keeps its shape (an ellipse of a brand circle is a redraw); pass { gag: \"<why the squash is the joke>\" } or squash a shape that is not the brand's");+ const amt = o.amount ?? 0.25, n = o.frames ?? 6, u = t - land;+ if (u < -n || u > n) return [1, 1];+ const sy = u < 0 ? 1 + amt * 0.6 * (1 + u / n) : 1 - amt * (1 - u / n) ** 2; // fullest squash on the contact frame (the classic contact pose), round again n frames later+ return [1 / Math.sqrt(sy), sy];+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/motionMeta.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/motionMeta.tsnew file mode 100644index 0000000..0658537--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/motionMeta.ts@@ -0,0 +1,14 @@+// MOTION META. What a film tells the motion scans about itself (Film.meta.motion). Plain data, so it+// survives the page boundary; every field is read by a tool (motionscan.mjs, layerscan.mjs, lock.mjs).+import type { Temperament } from "./motionKit";++export type MotionMeta = {+ /** The brand's colours (#rrggbb). layerscan fails any fill in them at an alpha between 5 % and 95 % (olive mud). */+ brandColors?: string[];+ /** The brand's motion temperament, by name ("calm", "lively", "snappy") or as numbers. motionscan fails stretches past its top speed. */+ temperament?: string | Temperament;+ /** Approved shots, frozen: [shot id, sha from `lock.mjs <film> --shot <id>`, who approved it and when]. lock.mjs fails if the shot's frames change. */+ approved?: [shot: string, sha: string, note: string][];+ /** Deliberate exceptions, [fromFrame, toFrame, reason]: a hard cut on a beat (slide cut), a dissolve the story needs, a declared brand fade. */+ allow?: { slideCut?: [number, number, string][]; dissolve?: [number, number, string][]; translucent?: [number, number, string][] };+};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.tsindex be694fe..cb24977 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 { SFX, SFX_KINDS, sfxVariants, sfxInfo, sfxDuckDb, renderSfx, validateSfx, sfxNeeds, parseKey, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";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/sfxKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.tsindex d1cad69..b62e963 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts@@ -495,11 +495,55 @@ const thread: Def = {},};-export const SFX = { tick, press, pop, ink, scratch, paper, whoosh, swish, riser, impact, chime, bubble, brick, thread } as const;+// The unpitched family, for films whose music the engine does not control (a generated or supplied+// track). Every layer is filtered noise or a falling sweep under 150 Hz, and the contact lasts a few+// milliseconds, so nothing carries a note that could clash with the track's key: a brand launch+// note was "the sound effects cannot be melodic, it makes disharmonious interruptions to the music".+// Modelled on that film's approved kit (strikes cut to 10-25 ms from their peak). tools/track.mjs kit+// prints each variant's pitch salience; trackMix refuses anything over 0.5 under an external track.+const tap: Def = {+ variants: ["tick", "tickHi", "tock", "thump", "impact"], level: -19, duckDb: 0,+ use: "under someone else's music: a small landing or a typed line (tick), a sparkle-sized touch (tickHi), a card or button (tock), a stage or block landing (thump), the one big lock-in (impact). No pitch, so no clash with the track's key",+ make(c, v) {+ const { sr, r } = c, p0 = (r() - 0.5) * 0.3;+ if (v === "tick" || v === "tickHi") {+ const hi = v === "tickHi", b = new Bus(sr, secs(sr, 0.05));+ b.add(burst(sr, r, hi ? 0.01 : 0.016, c.j(hi ? 0.0007 : 0.0013, 0.1), { hp: hi ? 3200 : 1800, lp: hi ? 14000 : 9000 }), 0, 1, p0);+ b.add(burst(sr, r, 0.004, 0.0004, { hp: hi ? 6000 : 4000 }), 0, 0.5, p0);+ punch(b, 0.3);+ return { bus: b, hit: 0 };+ }+ if (v === "tock") {+ const b = new Bus(sr, secs(sr, 0.08));+ b.add(burst(sr, r, 0.03, c.j(0.0045, 0.1), { hp: 450, lp: 5500 }), 0, 1, p0);+ b.add(burst(sr, r, 0.004, 0.0005, { hp: 2500 }), 0, 0.45, p0);+ punch(b, 0.35);+ return { bus: b, hit: 0 };+ }+ const big = v === "impact", n = secs(sr, big ? 1.8 : 0.16), b = new Bus(sr, n);+ // weight: a sweep that falls from about 110 to 45 Hz, under the 150 Hz line where a sound reads as a note+ const lo = c.j(big ? 42 : 48, 0.04), tau = big ? 0.42 : 0.045;+ b.add(chirp(sr, secs(sr, big ? 1.7 : 0.15), (t) => lo + 65 * Math.exp(-t / 0.018), ad(0.0015, tau)).map((x) => Math.tanh(x * 1.6) / Math.tanh(1.6)), 0, 1, 0);+ // body: low noise (lowpassed twice, as the approved kit was) and a dull contact so phones hear the hit+ const body = burst(sr, r, big ? 1.6 : 0.12, c.j(big ? 0.35 : 0.03, 0.1), { lp: big ? 500 : 160 }); filt(body, sr, { lp: big ? 500 : 160 });+ b.add(body, 0, big ? 1.6 : 1.2, p0 * 0.5);+ b.add(burst(sr, r, 0.006, 0.0009, { hp: 1200, lp: 6000 }), 0, big ? 0.22 : 0.3, p0);+ if (big) space(b, r, { rt60: 0.9, mix: 0.12, hp: 120, lp: 3000 });+ punch(b, 0.3);+ return { bus: b, hit: 0 };+ },+};++export const SFX = { tick, press, pop, ink, scratch, paper, whoosh, swish, riser, impact, chime, bubble, brick, thread, tap } as const;+/** Per-variant level (LUFS over the speaking window) where a kind's variants differ a lot in weight. */+const VARIANT_LEVEL: Partial<Record<string, number>> = { "tap:tickHi": -22, "tap:tock": -18, "tap:thump": -14, "tap:impact": -10 };+const VARIANT_DUCK: Partial<Record<string, number>> = { "tap:thump": 1.5, "tap:impact": 6 };export type SfxKind = keyof typeof SFX;export const SFX_KINDS = Object.keys(SFX) as SfxKind[];/** kind -> its variants (the first is the default). */export const sfxVariants = (k: SfxKind) => SFX[k].variants;+/** How far the score dips under one variant (dB): the kind's own, or the variant's where weights differ. */+export const sfxDuckDb = (k: SfxKind, variant?: string) => VARIANT_DUCK[`${k}:${variant ?? SFX[k].variants[0]}`] ?? SFX[k].duckDb;export const sfxInfo = (k: SfxKind) => ({ variants: SFX[k].variants, levelLufs: SFX[k].level, duckDb: SFX[k].duckDb, use: SFX[k].use });export const parseKey = (key: string) => {@@ -543,7 +587,7 @@ export const renderSfx = (kind: SfxKind, o: SfxOpts = {}, sr = 48000): SfxSoundconst c: Ctx = { sr, r, P: Math.pow(2, (o.pitch ?? 0) / 12) * wobble, o, dir: o.dir ?? 1, key: o.key === undefined ? null : parseKey(o.key), bpm: o.bpm ?? NaN, j: (x, amt) => x * (1 + (r() * 2 - 1) * amt) };const made = d.make(c, variant), [L, R] = finish(made.bus, made.hit);const kL = kWeight(L, sr), kR = kWeight(R, sr), window = speakingWindow(kL, kR, sr), now = winLufs(kL, kR, window[0], window[1]);- let g = d.level + (r() * 2 - 1) + (o.gainDb ?? 0) - now;+ let g = (VARIANT_LEVEL[`${kind}:${variant}`] ?? d.level) + (r() * 2 - 1) + (o.gainDb ?? 0) - now;let peak = 0; for (let i = 0; i < L.length; i++) peak = Math.max(peak, Math.abs(L[i]), Math.abs(R[i]));g = Math.min(g, -1 - 20 * Math.log10(Math.max(peak, 1e-9)));const G = db(g); for (let i = 0; i < L.length; i++) { L[i] *= G; R[i] *= G; }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.tsindex 6e4160b..5270ab2 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@@ -2,7 +2,7 @@// ducked under the cues that matter, one final master (a look-ahead true-peak ceiling), and an// audibility guarantee: every cue is measured against the ducked score at its own moment and the// 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 { renderSfx, validateSfx, sfxNeeds, sfxDuckDb, SFX, SFX_KINDS, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";import { kWeight, winLufs, mixSeed, strSeed, secs, type SfxStereo } from "./sfxCore";import { Biquad, db } from "./dsp";import { MODES } from "./theory";@@ -137,7 +137,7 @@ export const placeSfx = (plan: SfxPlan, sr: number): PlacedCue[] => {export const sfxDuck = (placed: PlacedCue[], n: number, sr: number, o: SfxPlan["duck"] = {}) => {const g = new Float32Array(n).fill(1), att = secs(sr, o.attackS ?? 0.04), maxDb = o.maxDb ?? 9;for (const pc of placed) {- const depth = Math.min(maxDb, pc.cue.duckDb ?? SFX[pc.cue.kind].duckDb); if (depth <= 0) continue;+ const depth = Math.min(maxDb, pc.cue.duckDb ?? sfxDuckDb(pc.cue.kind, pc.sound.variant)); if (depth <= 0) continue;const rel = secs(sr, pc.cue.kind === "impact" ? 1.2 : o.releaseS ?? 0.28), lo = db(-depth), [a, b] = pc.window;for (let i = Math.max(0, a - att); i < Math.min(n, b + rel); i++) {const s = i < a ? 0.5 - 0.5 * Math.cos((Math.PI * (i - (a - att))) / att) : i < b ? 1 : 0.5 + 0.5 * Math.cos((Math.PI * (i - b)) / rel);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/track.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/track.tsnew file mode 100644index 0000000..7950cac--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/track.ts@@ -0,0 +1,327 @@+// EXTERNAL TRACKS. A supplied or generated piece of music (a Lyria take, a licensed track, a client's+// jingle) measured and cut to a film by numbers, so nobody does it by hand per version again.+// analyzeTrack tempo, beat phase, downbeats, the bar grid with each bar's level, sections, key, the+// real last-note time and any designed stops. A generative model ignores exact+// timestamps in its prompt, so the picture is fitted to what the track really does.+// parseSegs a cut list from text, robust to the shapes people write ("0 6\n8 36", "0:6, 8:36",+// no final newline: a brand launch film's mix silently lost its last segment to a shell+// `while read` loop on a file with no trailing newline).+// planCut checks a cut before it is rendered: joins on downbeats, the outro keeps the track's+// own ending, no silence after the last note, and the music never ends before the picture.+// renderCut the edit, with short centred crossfades so the length is exactly the sum of the segments.+// trackGrid the edit's downbeats as a grid that solves holds, so a picture event lands on a bar.+// pitchSalience how much a short sound carries a note. Under someone else's music, effects must be+// transients, never notes (a brand launch "disharmonious" note).+// Pure functions of sample arrays: no files, no clock. The command line is tools/track.mjs.+import { fft } from "./meter";++export type Stereo = [Float32Array, Float32Array];+export type Bar = { i: number; t: number; rmsDb: number };+export type Section = { fromBar: number; toBar: number; fromS: number; toS: number; level: "silent" | "quiet" | "mid" | "full"; rmsDb: number };+export type TrackAnalysis = {+ sr: number; durationS: number;+ bpm: number; beatS: number; beatsPerBar: number; barS: number;+ /** the strongest tempo peaks with their comb score relative to the winner (1 = the winner); empty when bpm was pinned */+ tempoCandidates: { bpm: number; rel: number }[];+ /** time of the first downbeat at or after 0 (s); earlier material is a pickup */+ downbeatS: number;+ bars: Bar[]; sections: Section[];+ key: { name: string; confidence: number; runnerUp: string };+ /** the median level of the bars that play (dB), the yardstick for everything below */+ bodyDb: number;+ /** when the last note has decayed into silence (s): the track's real end, whatever the file length says */+ lastSoundS: number;+ /** silence in the file after the last note (s) */+ tailS: number;+ /** stretches inside the track that drop out (a designed hard stop), at least 0.2 s long */+ stops: { atS: number; lenS: number }[];+};++const dB = (x: number) => 10 * Math.log10(x + 1e-20);+export const monoOf = (L: Float32Array, R: Float32Array = L) => { const m = new Float32Array(L.length); for (let i = 0; i < L.length; i++) m[i] = 0.5 * (L[i] + R[i]); return m; };++/** Mean power per block of `hop` samples, as dB. */+const levels = (x: Float32Array, hop: number) => {+ const n = Math.floor(x.length / hop), out = new Float64Array(n);+ for (let b = 0; b < n; b++) { let s = 0; for (let i = b * hop; i < (b + 1) * hop; i++) s += x[i] * x[i]; out[b] = dB(s / hop); }+ return out;+};+const median = (a: number[]) => { if (!a.length) return -Infinity; const s = [...a].sort((p, q) => p - q); return s[s.length >> 1]; };++/** Onset strength at a 5 ms hop: the rise of log energy (full band) and of the low band (the kick), mean removed. */+const onsetCurves = (x: Float32Array, sr: number) => {+ const hop = Math.max(1, Math.round(sr * 0.005)), n = Math.floor(x.length / hop), full = new Float64Array(n), low = new Float64Array(n);+ const k = 1 - Math.exp((-2 * Math.PI * 120) / sr); let lp = 0;+ for (let b = 0; b < n; b++) {+ let s = 0, sl = 0;+ for (let i = b * hop; i < (b + 1) * hop; i++) { lp += k * (x[i] - lp); s += x[i] * x[i]; sl += lp * lp; }+ full[b] = Math.log(1e-9 + s / hop); low[b] = Math.log(1e-9 + sl / hop);+ }+ const flux = (e: Float64Array) => { const o = new Float64Array(n); for (let b = 1; b < n; b++) o[b] = Math.max(0, e[b] - e[b - 1]); let m = 0; for (const v of o) m += v; m /= n || 1; for (let b = 0; b < n; b++) o[b] -= m; return o; };+ return { hopS: hop / sr, full: flux(full), low: flux(low) };+};+/** Mean onset strength on a beat comb of period P hops starting at phase ph (fractional positions, linear read). */+const combAt = (O: Float64Array, P: number, ph: number) => {+ let s = 0, c = 0;+ for (let t = ph; t < O.length - 1; t += P) { const i = Math.floor(t), f = t - i; s += O[i] * (1 - f) + O[i + 1] * f; c++; }+ return c ? s / c : -Infinity;+};+const bestPhase = (O: Float64Array, P: number, step = 1) => { let best = -Infinity, ph = 0; for (let p = 0; p < P; p += step) { const v = combAt(O, P, p); if (v > best) { best = v; ph = p; } } return { ph, score: best }; };++// Krumhansl-Kessler key profiles (major, minor), index 0 = the tonic.+const KK_MAJOR = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88];+const KK_MINOR = [6.33, 2.68, 3.52, 5.38, 2.6, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17];+const NAMES = ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];+const corr = (a: number[], b: number[]) => { const ma = a.reduce((p, q) => p + q, 0) / a.length, mb = b.reduce((p, q) => p + q, 0) / b.length; let s = 0, da = 0, db = 0; for (let i = 0; i < a.length; i++) { s += (a[i] - ma) * (b[i] - mb); da += (a[i] - ma) ** 2; db += (b[i] - mb) ** 2; } return da && db ? s / Math.sqrt(da * db) : 0; };++/**+ * Pitch-class energy from 55 Hz to 2 kHz: frames of 16384 samples (3 Hz bins at 48 kHz, finer than a+ * semitone at 55 Hz), power of spectral PEAKS only, so a tone's window lobe does not leak into its+ * neighbours (a 4096 frame smeared A into G# and Bb). At most 200 frames, spread over the track.+ */+export const chroma = (x: Float32Array, sr: number) => {+ const N = 16384, out = new Array(12).fill(0), frames = Math.max(1, Math.floor((x.length - N) / (N / 2))), stride = Math.max(1, Math.floor(frames / 200));+ const re = new Float64Array(N), im = new Float64Array(N), win = Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N)), pw = new Float64Array(N / 2);+ for (let f = 0; f < frames; f += stride) {+ const a = f * (N / 2); if (a + N > x.length) break;+ for (let i = 0; i < N; i++) { re[i] = x[a + i] * win[i]; im[i] = 0; }+ fft(re, im);+ for (let k = 0; k < N / 2; k++) pw[k] = re[k] * re[k] + im[k] * im[k];+ for (let k = Math.max(1, Math.ceil((55 * N) / sr)); k <= Math.floor((2000 * N) / sr); k++) {+ if (!(pw[k] > pw[k - 1] && pw[k] >= pw[k + 1])) continue;+ const d = (0.5 * (pw[k - 1] - pw[k + 1])) / (pw[k - 1] - 2 * pw[k] + pw[k + 1] || 1), hz = ((k + d) * sr) / N; // parabolic peak+ out[((Math.round(12 * Math.log2(hz / 440)) % 12) + 12 + 9) % 12] += Math.sqrt(pw[k]);+ }+ }+ return out as number[];+};+/** The best of the 24 major and minor keys for a chroma vector, with the margin over the runner-up as confidence. */+export const keyOf = (ch: number[]) => {+ const all: { name: string; r: number }[] = [];+ for (let t = 0; t < 12; t++) {+ const rot = (p: number[]) => ch.map((_, i) => p[(i - t + 12) % 12]);+ all.push({ name: NAMES[t], r: corr(ch, rot(KK_MAJOR)) }, { name: NAMES[t] + "m", r: corr(ch, rot(KK_MINOR)) });+ }+ all.sort((a, b) => b.r - a.r);+ return { name: all[0].name, confidence: +(all[0].r - all[1].r).toFixed(3), runnerUp: all[1].name };+};++/**+ * Measure a track. `bpm` pins the tempo when you know it (the prompt asked for 120 and the take obeyed);+ * otherwise it is found between bpmRange by a comb over the onset curve and refined to 0.01 bpm.+ * `downbeatS` pins the bar phase when the ear disagrees with the kick-drum guess.+ */+export const analyzeTrack = (L: Float32Array, R: Float32Array, sr: number, o: { bpm?: number; bpmRange?: [number, number]; beatsPerBar?: number; downbeatS?: number } = {}): TrackAnalysis => {+ if (!Number.isSafeInteger(sr) || sr < 4000) throw new Error(`analyzeTrack: sample rate must be an integer of at least 4000, got ${sr}`);+ if (L.length < sr * 2) throw new Error(`analyzeTrack: the track is ${(L.length / sr).toFixed(2)} s; at least 2 s are needed to find a tempo`);+ const x = monoOf(L, R), durationS = x.length / sr, beatsPerBar = o.beatsPerBar ?? 4, [lo, hi] = o.bpmRange ?? [70, 180];+ if (o.bpm !== undefined && !(o.bpm >= 20 && o.bpm <= 300)) throw new Error(`analyzeTrack: bpm must be 20..300, got ${o.bpm}`);+ const { hopS, full, low } = onsetCurves(x, sr);+ let bpm = o.bpm ?? 0; const coarse: [number, number][] = [];+ if (!bpm) {+ // coarse: every 0.5 bpm, the best phase per tempo; then fine: 0.01 bpm around the winner+ let best = -Infinity;+ for (let b = lo; b <= hi + 1e-9; b += 0.5) { const P = 60 / b / hopS, s = bestPhase(full, P, 2).score; coarse.push([b, s]); if (s > best) { best = s; bpm = b; } }+ let fineBest = -Infinity, fine = bpm;+ for (let b = bpm - 0.6; b <= bpm + 0.6 + 1e-9; b += 0.01) { const P = 60 / b / hopS, s = bestPhase(full, P, 1).score; if (s > fineBest) { fineBest = s; fine = b; } }+ bpm = Math.round(fine * 100) / 100;+ }+ const beatS = 60 / bpm, P = beatS / hopS, barS = beatS * beatsPerBar;+ const beatPh = bestPhase(full, P, 0.25).ph * hopS; // first beat time in [0, beatS)+ let downbeatS = o.downbeatS;+ if (downbeatS === undefined) {+ // the bar's phase: of the beatsPerBar candidate beats, the one where the low band (kick) rises hardest+ let best = -Infinity; downbeatS = beatPh;+ for (let k = 0; k < beatsPerBar; k++) { const t = beatPh + k * beatS, s = combAt(low, barS / hopS, t / hopS) + 0.5 * combAt(full, barS / hopS, t / hopS); if (s > best) { best = s; downbeatS = t; } }+ }+ downbeatS = ((downbeatS % barS) + barS) % barS;+ // bars and their levels+ const bars: Bar[] = [];+ for (let i = 0, t = downbeatS; t < durationS - 1e-6; i++, t = downbeatS + i * barS) {+ const a = Math.floor(t * sr), b = Math.min(x.length, Math.floor((t + barS) * sr)); let s = 0; for (let j = a; j < b; j++) s += x[j] * x[j];+ bars.push({ i, t: +t.toFixed(4), rmsDb: +dB(s / Math.max(1, b - a)).toFixed(1) });+ }+ const bodyDb = median(bars.filter((b) => b.rmsDb > -70).map((b) => b.rmsDb));+ const cls = (v: number): Section["level"] => (v < bodyDb - 30 ? "silent" : v < bodyDb - 9 ? "quiet" : v < bodyDb - 3 ? "mid" : "full");+ const sections: Section[] = [];+ for (const b of bars) {+ const c = cls(b.rmsDb), last = sections[sections.length - 1];+ if (last && last.level === c) { last.toBar = b.i + 1; last.toS = +Math.min(durationS, b.t + barS).toFixed(3); last.rmsDb = Math.max(last.rmsDb, b.rmsDb); }+ else sections.push({ fromBar: b.i, toBar: b.i + 1, fromS: b.t, toS: +Math.min(durationS, b.t + barS).toFixed(3), level: c, rmsDb: b.rmsDb });+ }+ // the real end and the stops, on 50 ms blocks against the body level+ const blk = Math.round(sr * 0.05), lv = levels(x, blk), body50 = median([...lv].filter((v) => v > -70));+ let last = lv.length - 1; while (last >= 0 && lv[last] < body50 - 40) last--;+ const lastSoundS = +(((last + 1) * blk) / sr).toFixed(3), stops: TrackAnalysis["stops"] = [];+ let first = 0; while (first < lv.length && lv[first] < body50 - 40) first++;+ for (let b = first; b <= last; ) { if (lv[b] >= body50 - 30) { b++; continue; } const a = b; while (b <= last && lv[b] < body50 - 30) b++; const len = ((b - a) * blk) / sr; if (len >= 0.2) stops.push({ atS: +((a * blk) / sr).toFixed(2), lenS: +len.toFixed(2) }); }+ const peaks = coarse.filter(([, v], i) => v > (coarse[i - 1]?.[1] ?? -Infinity) && v >= (coarse[i + 1]?.[1] ?? -Infinity)).sort((p, q) => q[1] - p[1]).slice(0, 4);+ const tempoCandidates = peaks.map(([b, v]) => ({ bpm: b, rel: +(v / (peaks[0][1] || 1)).toFixed(3) }));+ return { sr, durationS: +durationS.toFixed(3), bpm, tempoCandidates, beatS: +beatS.toFixed(5), beatsPerBar, barS: +barS.toFixed(5), downbeatS: +downbeatS.toFixed(4), bars, sections, key: keyOf(chroma(x, sr)), bodyDb: +bodyDb.toFixed(1), lastSoundS, tailS: +Math.max(0, durationS - lastSoundS).toFixed(3), stops };+};++// ------------------------------------------------------------------------------------------- cutting+export type Seg = { from: number; to: number };+/**+ * A cut list from text. Accepts one segment per line ("8 36"), comma lists ("0:6, 8:36", "0-6"),+ * comments after #, CRLF, and no final newline. Bars ("bars 0-2, 4-17": whole bars, end exclusive)+ * need the analysis. Anything else throws with the line it could not read.+ */+export const parseSegs = (text: string, a?: Pick<TrackAnalysis, "downbeatS" | "barS">): Seg[] => {+ const body = text.replace(/#.*$/gm, "").trim();+ if (!body) throw new Error("cut: the segment list is empty");+ const bars = /^bars\b/i.test(body), parts = body.replace(/^bars\b/i, "").split(/[\n,;]+/).map((s) => s.trim()).filter(Boolean);+ if (bars && !a) throw new Error("cut: a bar list needs the track's analysis (tempo and downbeat)");+ return parts.map((p) => {+ const m = /^(-?\d+(?:\.\d+)?)\s*(?:[\s:\-]|to)\s*(-?\d+(?:\.\d+)?)$/.exec(p.replace(/\s+/g, " "));+ if (!m) throw new Error(`cut: cannot read segment "${p}" (write "from to" in seconds, or "bars a-b")`);+ const x = Number(m[1]), y = Number(m[2]);+ return bars ? { from: +(a!.downbeatS + x * a!.barS).toFixed(4), to: +(a!.downbeatS + y * a!.barS).toFixed(4) } : { from: x, to: y };+ });+};++export type CutPlan = {+ segs: Seg[]; lengthS: number;+ /** each join: where it falls in the edit, and how far each side is from a downbeat (ms) */+ joins: { atS: number; fromOffMs: number; toOffMs: number }[];+ /** the edit's downbeats (s), for trackGrid */+ downbeats: number[];+ /** the track's designed stops as they fall in the edit (s): declared silences, so the shape check does not call them holes */+ quiet: { fromS: number; toS: number; reason: string }[];+ errors: string[]; warnings: string[];+};+const offBar = (a: Pick<TrackAnalysis, "downbeatS" | "barS">, t: number) => { const k = Math.round((t - a.downbeatS) / a.barS); return { ms: (t - (a.downbeatS + k * a.barS)) * 1000, bar: k, at: a.downbeatS + k * a.barS }; };+/**+ * Check a cut against the track before rendering it. Errors (refuse): a segment outside the file, a join+ * off a downbeat by more than `barTolMs`, an outro that stops before the track's last note (unless the+ * film fades it on purpose with `fadeOutS`), a segment that carries silence from after the last note,+ * and an edit shorter than the picture. Warnings: an edit that runs past the picture (the mux cuts it).+ */+export const planCut = (a: TrackAnalysis, segs: Seg[], o: { filmS?: number; barTolMs?: number; fadeOutS?: number; endTolS?: number } = {}): CutPlan => {+ const errors: string[] = [], warnings: string[] = [], tol = o.barTolMs ?? 30, endTol = o.endTolS ?? 0.5; // the same half second filmshape allows at the end; a shipped brand-launch v12 ended 0.72 s past the last note and fails it+ if (!segs.length) errors.push("the cut has no segments");+ segs.forEach((s, i) => {+ const where = `segment ${i + 1} (${s.from}-${s.to} s)`;+ if (!(Number.isFinite(s.from) && Number.isFinite(s.to)) || s.to <= s.from) errors.push(`${where} has no length`);+ if (s.from < 0 || s.to > a.durationS + 1e-6) errors.push(`${where} lies outside the track (0-${a.durationS} s)`);+ // the first segment may start at 0 (a pickup), the last may end at the track's own end; every join sits on a bar+ if (i > 0 || s.from > 0.05) { const b = offBar(a, s.from); if (Math.abs(b.ms) > tol) errors.push(`${where} starts ${b.ms.toFixed(0)} ms off a downbeat: start at bar ${b.bar} (${b.at.toFixed(3)} s)`); }+ if (i < segs.length - 1) { const b = offBar(a, s.to); if (Math.abs(b.ms) > tol) errors.push(`${where} ends ${b.ms.toFixed(0)} ms off a downbeat: end at bar ${b.bar} (${b.at.toFixed(3)} s)`); }+ if (s.to > a.lastSoundS + endTol) errors.push(`${where} runs ${(s.to - a.lastSoundS).toFixed(2)} s past the track's last note at ${a.lastSoundS} s, so the edit carries silence; end it at ${a.lastSoundS} s (a brand launch film went silent 4 s early this way)`);+ });+ const lastSeg = segs[segs.length - 1];+ if (lastSeg && lastSeg.to < a.lastSoundS - 0.05 && !(o.fadeOutS && o.fadeOutS > 0)) errors.push(`the outro stops at ${lastSeg.to} s, before the track's last note at ${a.lastSoundS} s: end the last segment on the track's own ending (cut whole bars earlier instead), or fade it on purpose with fadeOutS`);+ const lengthS = segs.reduce((p, s) => p + (s.to - s.from), 0);+ if (o.filmS !== undefined) {+ // where the music is last heard in the edit: the last segment's own end, or the track's last note if that comes first+ const soundEnd = lastSeg ? lengthS - (lastSeg.to - Math.min(lastSeg.to, Math.max(lastSeg.from, a.lastSoundS))) : 0;+ if (soundEnd < o.filmS - 0.5) errors.push(`the music is last heard at ${soundEnd.toFixed(2)} s of the edit and the picture runs to ${o.filmS.toFixed(2)} s: ${(o.filmS - soundEnd).toFixed(2)} s of silence at the end; add ${Math.ceil((o.filmS - soundEnd) / a.barS)} bar(s) before the outro, or end the picture with the music`);+ else if (soundEnd > o.filmS + 0.5) { const over = soundEnd - o.filmS, bars = Math.floor(over / a.barS); warnings.push(`the music plays ${over.toFixed(2)} s past the picture; the mux would cut its ending mid-note: ${bars ? `drop ${bars} bar(s) before the outro, or ` : ""}extend the last shot by ${over.toFixed(2)} s`); }+ }+ const joins: CutPlan["joins"] = [], downbeats: number[] = [], quiet: CutPlan["quiet"] = [];+ let at = 0;+ segs.forEach((s, i) => {+ if (i > 0) joins.push({ atS: +at.toFixed(4), fromOffMs: +offBar(a, segs[i - 1].to).ms.toFixed(1), toOffMs: +offBar(a, s.from).ms.toFixed(1) });+ for (const b of a.bars) if (b.t >= s.from - 1e-6 && b.t < s.to - 1e-6) downbeats.push(+(at + b.t - s.from).toFixed(4));+ for (const st of a.stops) { const x = Math.max(st.atS, s.from), y = Math.min(st.atS + st.lenS, s.to); if (y > x) quiet.push({ fromS: +Math.max(0, at + x - s.from - 0.1).toFixed(3), toS: +(at + y - s.from + 0.1).toFixed(3), reason: `the track's own stop at ${st.atS} s` }); }+ at += s.to - s.from;+ });+ return { segs, lengthS: +lengthS.toFixed(4), joins, downbeats, quiet, errors, warnings };+};++/**+ * Render a cut. Each join is a centred equal-power crossfade of `xfadeMs` (default 12): the outgoing+ * segment runs half a fade past its end and the incoming one starts half a fade early, so the edit is+ * exactly the sum of the segments and every bar stays where planCut said it is. `fadeOutS` fades the end.+ */+export const renderCut = (L: Float32Array, R: Float32Array, sr: number, segs: Seg[], o: { xfadeMs?: number; fadeOutS?: number } = {}): Stereo => {+ const h = Math.round(((o.xfadeMs ?? 12) / 1000) * sr / 2), total = segs.reduce((p, s) => p + Math.round(s.to * sr) - Math.round(s.from * sr), 0);+ const oL = new Float32Array(total), oR = new Float32Array(total);+ let at = 0;+ segs.forEach((s, i) => {+ const a = Math.round(s.from * sr), b = Math.round(s.to * sr), pre = i > 0 ? h : 0, post = i < segs.length - 1 ? h : 0;+ for (let j = -pre; j < b - a + post; j++) {+ const src = a + j, dst = at + j; if (src < 0 || src >= L.length || dst < 0 || dst >= total) continue;+ let g = 1;+ if (j < pre) g = Math.sin((Math.PI / 2) * ((j + pre) / (2 * pre || 1))); // fade in across the join+ if (j >= b - a - post) g *= Math.cos((Math.PI / 2) * ((j - (b - a - post)) / (2 * post || 1))); // fade out across the next join+ oL[dst] += L[src] * g; oR[dst] += R[src] * g;+ }+ at += b - a;+ });+ if (o.fadeOutS && o.fadeOutS > 0) { const n = Math.min(total, Math.round(o.fadeOutS * sr)); for (let i = 0; i < n; i++) { const g = Math.sin((Math.PI / 2) * (i / n)); oL[total - 1 - i] *= g; oR[total - 1 - i] *= g; } }+ return [oL, oR];+};++// ------------------------------------------------------------------------------------------- the grid+/**+ * The edit's bar grid, to fit flexible holds to the music (a brand launch film's holds were solved by hand+ * bisection per version). holdTo(startS, minS) is the shortest hold of at least minS whose end lands+ * on a downbeat; landOn(t) is the downbeat nearest t.+ */+export const trackGrid = (downbeats: number[], fps?: number) => {+ if (!downbeats.length) throw new Error("trackGrid: no downbeats (analyse the track, or plan the cut first)");+ const sorted = [...downbeats].sort((a, b) => a - b);+ const next = (t: number) => sorted.find((d) => d >= t - 1e-9);+ return {+ downbeats: sorted,+ landOn: (t: number) => sorted.reduce((p, d) => (Math.abs(d - t) < Math.abs(p - t) ? d : p), sorted[0]),+ holdTo: (startS: number, minS: number) => {+ const d = next(startS + minS);+ if (d === undefined) throw new Error(`trackGrid: no downbeat after ${(startS + minS).toFixed(2)} s; the music ends at bar ${sorted.length}`);+ return { holdS: +(d - startS).toFixed(4), landS: d, bar: sorted.indexOf(d), frame: fps ? Math.round(d * fps) : undefined };+ },+ };+};++// ------------------------------------------------------------------------------------------- pitch+/**+ * How much a short sound carries a note, 0..1: the normalised autocorrelation's highest peak between+ * 90 Hz and 2 kHz (past the first zero crossing, so the broad lobe of noise does not count), scaled by+ * how long the sound rings within 20 dB of its peak, against 60 ms. Calibrated on real sounds: the+ * a brand launch kit the director approved (strikes cut to 8-22 ms, a 174 ms boom) measures 0.07 to 0.45; full+ * notes from the sound pack (marimba, glockenspiel, harp, tubular bell, 150 ms and longer) measure 0.77+ * to 0.98. Below 90 Hz a boom reads as weight, not a note. Over 0.5 under someone else's music fails.+ */+export const pitchSalience = (x: Float32Array, sr: number, o: { fMin?: number; fMax?: number; ringMs?: number } = {}) => {+ let pk = 0, at = 0; for (let i = 0; i < x.length; i++) if (Math.abs(x[i]) > pk) { pk = Math.abs(x[i]); at = i; }+ if (pk < 1e-6) return { salience: 0, hz: NaN, ringMs: 0, raw: 0 };+ // ring: how long the 2 ms envelope stays within 20 dB of the peak, from the peak on+ const w = Math.max(1, Math.round(sr * 0.002)), floor = pk * 0.1; let end = at;+ for (let i = at; i < x.length; i += w) { let m = 0; for (let j = i; j < Math.min(x.length, i + w); j++) m = Math.max(m, Math.abs(x[j])); if (m >= floor) end = i + w; else break; }+ const ringMs = ((end - at) / sr) * 1000;+ // autocorrelation over the ringing part (at most 120 ms)+ const a = Math.max(0, at - Math.round(sr * 0.002)), b = Math.min(x.length, Math.max(end, a + Math.round(sr * 0.01)), a + Math.round(sr * 0.12)), n = b - a;+ const lagMin = Math.max(1, Math.floor(sr / (o.fMax ?? 2000))), lagMax = Math.min(n - 1, Math.ceil(sr / (o.fMin ?? 90)));+ let r0 = 0; for (let i = a; i < b; i++) r0 += x[i] * x[i];+ if (r0 <= 0 || lagMax <= lagMin) return { salience: 0, hz: NaN, ringMs, raw: 0 };+ const r = (lag: number) => { let s = 0; for (let i = a; i + lag < b; i++) s += x[i] * x[i + lag]; return s / r0; };+ let lag = 1; while (lag < lagMax && r(lag) > 0) lag++; // past the main lobe+ let raw = 0, best = NaN;+ for (let L = Math.max(lag, lagMin); L <= lagMax; L++) { const v = r(L); if (v > raw) { raw = v; best = L; } }+ const salience = raw * Math.min(1, ringMs / (o.ringMs ?? 60));+ return { salience: +salience.toFixed(3), hz: Number.isFinite(best) ? +(sr / best).toFixed(1) : NaN, ringMs: +ringMs.toFixed(1), raw: +raw.toFixed(3) };+};+export const PITCHED = 0.5;++/** When the music in a mix stops being audible (s), on 50 ms blocks against its own body level. */+export const lastSoundOf = (L: Float32Array, R: Float32Array, sr: number, belowBodyDb = 40) => {+ const blk = Math.round(sr * 0.05), lv = levels(monoOf(L, R), blk), body = median([...lv].filter((v) => v > -70));+ if (!Number.isFinite(body)) return 0;+ let last = lv.length - 1; while (last >= 0 && lv[last] < body - belowBodyDb) last--;+ return ((last + 1) * blk) / sr;+};++/**+ * Each effect in an effects stem (silent between cues) with its pitch salience: an effect starts where+ * the 2 ms peak envelope rises out of silence (2 % of the stem's peak) after at least 20 ms below it,+ * and is measured up to the next effect or 400 ms. For soundcheck --sfx on a film over an external track.+ */+export const stemCues = (L: Float32Array, R: Float32Array, sr: number) => {+ const x = monoOf(L, R), hop = Math.max(1, Math.round(sr * 0.002)), n = Math.floor(x.length / hop), env = new Float64Array(n);+ let peak = 0;+ for (let b = 0; b < n; b++) { let m = 0; for (let i = b * hop; i < (b + 1) * hop; i++) m = Math.max(m, Math.abs(x[i])); env[b] = m; peak = Math.max(peak, m); }+ const thr = peak * 0.02, on: number[] = []; let below = 10;+ for (let b = 0; b < n; b++) { if (env[b] <= thr) { below++; continue; } if (below >= 10) on.push(b); below = 0; }+ return on.map((b, k) => { const a = b * hop, e = Math.min(x.length, (on[k + 1] ?? n) * hop, a + Math.round(sr * 0.4)); return { atS: +(a / sr).toFixed(3), ...pitchSalience(x.subarray(a, e), sr) }; });+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/trackMix.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/trackMix.tsnew file mode 100644index 0000000..a3168b0--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/trackMix.ts@@ -0,0 +1,87 @@+// A FILM'S EFFECTS OVER SOMEONE ELSE'S MUSIC. The engine's mix (launchSound.mixLaunch: panned cues,+// the score ducked under the ones that matter, every cue measured against the music at its own moment+// and raised until it is heard, the dense delivery master) applied to a generated or supplied track,+// plus the three rules a brand launch film learned by ear:+// 1. Effects are transients, never notes. A tuned kind (a chime, a tuned riser, impact:bloom,+// press:confirm) is refused, and every placed sound's pitch salience must stay under 0.5.+// A cue may carry a note only when `pitched` says why in words.+// 2. Every cue is heard: the buried-cue guard measures the track's local loudness at each cue (the+// film's effects stem once sat 29 dB under the music and nobody could tell without listening).+// 3. The music never ends before the picture: the track's last audible moment must reach the film's end.+// Pure: arrays in, arrays out. tools/track.mjs mix reads the files.+import { mixLaunch, type LaunchCue } from "../launchSound";+import { sfxNeeds, SFX, SFX_KINDS, type SfxKind } from "./sfxKit";+import type { SfxCue, SfxPlan, PlacedCue, SfxAudibility } from "./sfxMix";+import type { Delivered } from "./delivery";+import { pitchSalience, lastSoundOf, monoOf, PITCHED, type Stereo } from "./track";++export type TrackCue = SfxCue & {+ /** stereo position -1 (left) .. 1 (right) */+ pan?: number;+ /** why this cue may carry a note under the track (a deliberate musical button). Without it, a pitched cue fails. */+ pitched?: string;+};+export type TrackPlan = Omit<SfxPlan, "cues" | "score" | "key"> & { cues: TrackCue[] };+export type TrackMix = {+ L: Float32Array; R: Float32Array; sfx: Stereo; placed: PlacedCue[]; audibility: SfxAudibility[];+ raised: { i: number; db: number }[];+ pitch: { i: number; label: string; kind: string; salience: number; hz: number; ringMs: number; allowed?: string; ok: boolean }[];+ ending: { musicEndS: number; filmS: number; ok: boolean; msg?: string };+ lufs: number; dbtp: number; delivered?: Delivered; ok: boolean; problems: string[];+};++/** "tap:thump -9 pan=0.3" -> { kind, variant, gainDb, pan }. Gain is optional, in dB on top of the kind's level. */+export const parseSoundSpec = (spec: string): Omit<TrackCue, "frame"> => {+ const parts = String(spec).trim().split(/\s+/), [kind, variant] = parts[0].split(":");+ if (!(kind in SFX)) throw new Error(`sound "${spec}": unknown kind "${kind}" (kinds: ${SFX_KINDS.join(", ")})`);+ const k = kind as SfxKind;+ if (variant !== undefined && !SFX[k].variants.includes(variant)) throw new Error(`sound "${spec}": ${kind} has no variant "${variant}" (variants: ${SFX[k].variants.join(", ")})`);+ const out: Omit<TrackCue, "frame"> = { kind: k, variant };+ for (const p of parts.slice(1)) {+ const m = /^(pan|duck|snap)=(.+)$/.exec(p);+ if (m) { if (m[1] === "pan") out.pan = Number(m[2]); else if (m[1] === "duck") out.duckDb = Number(m[2]); else out.snap = m[2] as TrackCue["snap"]; continue; }+ if (/^[+-]?\d+(\.\d+)?$/.test(p)) { out.gainDb = Number(p); continue; }+ throw new Error(`sound "${spec}": cannot read "${p}" (write e.g. "tap:thump -9 pan=0.3")`);+ }+ if (out.pan !== undefined && !(out.pan >= -1 && out.pan <= 1)) throw new Error(`sound "${spec}": pan must be -1..1`);+ return out;+};++/** Refuse tuned kinds under a track the engine does not control, unless the cue says why. */+export const checkTrackCues = (plan: TrackPlan) => {+ plan.cues.forEach((c, i) => {+ const v = c.variant ?? SFX[c.kind]?.variants[0];+ if (c.kind in SFX && sfxNeeds(c.kind, v, c).key && !c.pitched?.trim())+ throw new Error(`track mix: cue #${i} ${c.kind}:${v}${c.label ? ` "${c.label}"` : ""} is tuned to a key, and the music here is a track the engine did not write: under someone else's music, effects are transients, never notes. Use tap:${c.kind === "impact" ? "impact" : "tock"} (or another tap variant), or set pitched: "<why this note belongs>"`);+ });+};++export const mixOverTrack = (music: Stereo | null, plan: TrackPlan, sr = 48000, o: { maxRaiseDb?: number } = {}): TrackMix => {+ checkTrackCues(plan);+ const filmS = plan.frames / plan.fps, n = Math.round(filmS * sr), problems: string[] = [];+ const cues: LaunchCue[] = plan.cues.map((c) => ({ ...c, role: "land", x: c.pan === undefined ? undefined : (c.pan + 1) / 2 }));+ const m = mixLaunch(music, { ...plan, cues, W: 1, spread: 1, master: plan.master ?? "dense" }, sr, o.maxRaiseDb ?? 8);+ // the effects stem, rebuilt from the placed (panned, raised) sounds+ const fx: Stereo = [new Float32Array(n), new Float32Array(n)];+ for (const pc of m.placed) for (let i = 0; i < pc.sound.L.length && pc.start + i < n; i++) { fx[0][pc.start + i] += pc.sound.L[i]; fx[1][pc.start + i] += pc.sound.R[i]; }+ const pitch = m.placed.map((pc) => {+ const c = plan.cues[pc.i], p = pitchSalience(monoOf(pc.sound.L, pc.sound.R), sr), allowed = c.pitched?.trim() || undefined;+ return { i: pc.i, label: c.label ?? `${c.kind}:${pc.sound.variant}`, kind: `${c.kind}:${pc.sound.variant}`, salience: p.salience, hz: p.hz, ringMs: p.ringMs, allowed, ok: !!allowed || p.salience <= PITCHED };+ });+ for (const p of pitch) if (!p.ok) problems.push(`cue #${p.i} "${p.label}" (${p.kind}) carries a note (pitch salience ${p.salience.toFixed(2)} at ${p.hz} Hz, rings ${p.ringMs} ms): use a tap variant, or set pitched with the reason`);+ for (const a of m.audibility) if (!a.ok) problems.push(`cue #${a.i} "${a.label}" is buried ${a.marginDb.toFixed(1)} dB under the track at ${a.atS.toFixed(2)} s even after raising it 8 dB: give it a bigger kind (tock, thump) or a duck`);+ const musicEndS = music ? Math.min(lastSoundOf(music[0], music[1], sr), music[0].length / sr) : 0;+ const ending = { musicEndS: +musicEndS.toFixed(3), filmS: +filmS.toFixed(3), ok: !music || musicEndS >= filmS - 0.3, msg: undefined as string | undefined };+ if (!ending.ok) { ending.msg = `the music ends at ${musicEndS.toFixed(2)} s and the picture at ${filmS.toFixed(2)} s: ${(filmS - musicEndS).toFixed(2)} s of silence at the end. Extend the outro by whole bars (track.mjs cut --film-s ${filmS.toFixed(2)}) or end the picture with the music`; problems.push(ending.msg); }+ return { L: m.L, R: m.R, sfx: fx, placed: m.placed, audibility: m.audibility, raised: m.raised.map(({ i, db }) => ({ i, db })), pitch, ending, lufs: m.lufs, dbtp: m.dbtp, delivered: m.delivered, ok: !problems.length, problems };+};++/** The mix as a table a person reads: each cue's margin over the track, any raise, its pitch salience; then the problems. */+export const trackMixReport = (m: TrackMix) => {+ const o = [`MIX OVER TRACK ${m.placed.length} cues, ${m.lufs.toFixed(1)} LUFS, ${m.dbtp.toFixed(2)} dBTP; music ends ${m.ending.musicEndS} s, picture ${m.ending.filmS} s`];+ o.push(` ${"at s".padStart(7)} ${"cue".padEnd(26)} ${"kind".padEnd(13)} ${"margin".padStart(7)} ${"raised".padStart(7)} ${"pitch".padStart(6)}`);+ const raised = new Map(m.raised.map((r) => [r.i, r.db]));+ m.audibility.forEach((a, k) => { const p = m.pitch[k]; o.push(` ${a.atS.toFixed(2).padStart(7)} ${String(a.label || p.label).slice(0, 26).padEnd(26)} ${p.kind.padEnd(13)} ${a.marginDb.toFixed(1).padStart(6)} ${(raised.has(a.i) ? "+" + raised.get(a.i)!.toFixed(1) : "").padStart(7)} ${p.salience.toFixed(2).padStart(6)}${a.ok && p.ok ? "" : " <-"}`); });+ for (const p of m.problems) o.push(` FAIL ${p}`);+ return o.join("\n");+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/people.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/people.tsnew file mode 100644index 0000000..c07d4aa--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/people.ts@@ -0,0 +1,80 @@+// PEOPLE. Real people in a film, placed by the size of their HEAD, not the size of their photo.+// On a brand launch film three speaker cut-outs were placed by photo size and their heads came out+// 370, 270 and 190 px; the director: "ines's image looks bigger than tomas and priya... check proportions".+// headOf(alpha, w, h) the head box of a head-and-shoulders cut-out, from its alpha alone+// placePerson(head, o) the scale and offset that put that head at headPx tall, crown at crownY+// drawPerson(ctx, env, o) draws the cut-out so, and reports "head:<group>/<name>" to the frame+// probe: framecheck fails a group whose heads differ by more than 10 %+// popOut(ctx, circle, draw) a person on a disc: the body clipped by the circle, the head free above it+// A per-asset head box from the manifest (o.head) always wins over the detected one.+import { probeRect, type Ctx, type Env } from "./core";++export type Box = { x0: number; y0: number; x1: number; y1: number };++/**+ * The head box of a cut-out from its alpha channel (one byte per pixel, row-major, or RGBA when+ * `stride` is 4). The head is the part above the neck, and the neck is the narrowest row between 12 %+ * and 50 % of the figure's height under its crown that is clearly narrower than both the head above+ * and the shoulders below. With no such row (a head-only crop, an oval portrait) the whole figure is+ * the head. Returns null for an empty image.+ */+export const headOf = (alpha: ArrayLike<number>, w: number, h: number, stride = 1, threshold = 32): Box | null => {+ const left = new Array<number>(h).fill(-1), right = new Array<number>(h).fill(-1);+ let top = -1, bottom = -1;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (alpha[(y * w + x) * stride + (stride - 1)] > threshold) { if (left[y] < 0) left[y] = x; right[y] = x; if (top < 0) top = y; bottom = y; }+ if (top < 0) return null;+ const bh = bottom - top + 1, from = top + Math.max(1, Math.floor(0.12 * bh)), to = Math.min(bottom, top + Math.floor(0.5 * bh));+ const wdOf = (y: number) => (left[y] < 0 ? 0 : right[y] - left[y] + 1);+ // the widest row from each row down (the shoulders a neck must sit on)+ const below = new Array<number>(h + 1).fill(0); for (let y = bottom; y >= top; y--) below[y] = Math.max(below[y + 1], wdOf(y));+ // A neck is a row clearly narrower than the head above it AND the shoulders below it. The top of+ // an oval cut-out or a head-only crop is narrow too, but nothing above it is wider: no neck there.+ let neck = -1, best = Infinity, above = 0;+ for (let y = top; y < from; y++) above = Math.max(above, wdOf(y));+ for (let y = from; y <= to; y++) { const wd = wdOf(y); if (wd > 0 && wd < best && above >= wd * 1.15 && below[y + 1] >= wd * 1.15) { best = wd; neck = y; } above = Math.max(above, wd); }+ // no neck: the whole figure is the head (scaling it by a sliver of its top made the person ~8x too big)+ const end = neck < 0 ? bottom + 1 : neck;+ let x0 = w, x1 = 0; for (let y = top; y < end; y++) if (left[y] >= 0) { x0 = Math.min(x0, left[y]); x1 = Math.max(x1, right[y]); }+ return { x0, y0: top, x1: x1 + 1, y1: end };+};++/** Scale and top-left that draw an image whose head is `head` (image px) at headPx tall, crown at (cx, crownY). */+export const placePerson = (head: Box, o: { cx: number; crownY: number; headPx: number }) => {+ const s = o.headPx / Math.max(1, head.y1 - head.y0);+ return { s, x: o.cx - ((head.x0 + head.x1) / 2) * s, y: o.crownY - head.y0 * s };+};++const headCache = (env: Env, name: string, img: CanvasImageSource & { width: number; height: number }) => {+ const k = `people:head:${name}`; let b = env.cache.get(k) as Box | null | undefined;+ if (b === undefined) { const L = env.canvas(img.width, img.height); L.ctx.drawImage(img, 0, 0); b = headOf(L.ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4); env.cache.set(k, b); }+ return b;+};++/**+ * Draw the cut-out asset `name` with its head `headPx` tall, centred on cx, crown at crownY (film px),+ * and report the head box to the frame probe as head:<group>/<name>. Returns the placement and the head+ * box on screen. People shown as one sequence share a group and a headPx.+ */+export const drawPerson = (ctx: Ctx, env: Env, o: { name: string; group: string; cx: number; crownY: number; headPx: number; head?: Box; alpha?: number }) => {+ const img = env.image?.(o.name) as (CanvasImageSource & { width: number; height: number }) | undefined;+ if (!img) throw new Error(`drawPerson: no image asset '${o.name}'`);+ const head = o.head ?? headCache(env, o.name, img); if (!head) throw new Error(`drawPerson: '${o.name}' has no opaque pixels (a cut-out needs alpha)`);+ const p = placePerson(head, o);+ ctx.save(); if (o.alpha !== undefined) ctx.globalAlpha *= o.alpha;+ ctx.drawImage(img, p.x, p.y, img.width * p.s, img.height * p.s);+ probeRect(ctx, env, p.x + head.x0 * p.s, p.y + head.y0 * p.s, (head.x1 - head.x0) * p.s, (head.y1 - head.y0) * p.s, `head:${o.group}/${o.name}`);+ ctx.restore();+ return { ...p, head: { x0: p.x + head.x0 * p.s, y0: p.y + head.y0 * p.s, x1: p.x + head.x1 * p.s, y1: p.y + head.y1 * p.s } };+};++/**+ * A person on a disc (the hosts card): `draw` is clipped to the circle below its centre line and free+ * above it, so the body sits in the circle and the head pops out over the rim. The disc itself is the+ * caller's (a coded circle stays a perfect circle).+ */+export const popOut = (ctx: Ctx, c: { cx: number; cy: number; r: number }, draw: () => void) => {+ ctx.save(); ctx.beginPath();+ ctx.arc(c.cx, c.cy, c.r, 0, Math.PI * 2);+ ctx.rect(c.cx - c.r, c.cy - c.r * 4, c.r * 2, c.r * 4); // the band above the centre line, as wide as the disc (same winding: one region)+ ctx.clip(); draw(); ctx.restore();+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/productUI.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/productUI.tsindex 9a609ad..f63f2c1 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/productUI.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/productUI.ts@@ -27,7 +27,7 @@ export type ProductUI = {layout?: "list" | "cards";before: UiState; after: UiState;};-export type UiTheme = { bg: string; card: string; ink: string; soft: string; mute: string; line: string; chip: string; accent: string; paper: string };+export type UiTheme = { bg: string; card: string; ink: string; soft: string; mute: string; line: string; chip: string; accent: string; paper: string; font?: (w: number, px: number) => string; onAccent?: string; radius?: number; button?: "pill" | "square" }; // font, onAccent: a custom look's text face and the label colour on its accent; radius: every corner's ceiling at 1x; button: its action's shape// the move: t0 is the press; items leave one after another, `stagger` frames apart, each on a springexport type UiMorph = { f: number; t0: number; stagger?: number; omega?: number; zeta?: number };export type UiOpts = { minPx?: number; typed?: string; caret?: boolean; press?: number; hot?: number; accent?: string };@@ -51,7 +51,9 @@ const geo = (r0: Rect, ui: ProductUI, minPx: number): Geo => { // sized to own iconst top = headH + 18 * u + (ui.command !== undefined ? cmdH + 18 * u : 0) + (nStats ? statH + 18 * u : 0);const n = Math.max(ui.before.items.length, ui.after.items.length, 1), cards = ui.layout === "cards", rows = cards ? Math.ceil(n / 2) : n;const bodyW = r0.w - 2 * pad, room = r0.h - top - pad;- const row = cards ? Math.min(room / rows, (bodyW / 2) * 0.62) : clamp(room / rows, px.row * 2.3, px.row * 3.2);+ // (in a tall rectangle, a phone frame's, a list's rows are tall touch rows and the window fills its+ // rectangle; capped at a desktop height there, it left the lower third of a 9:16 frame empty)+ const row = cards ? Math.min(room / rows, (bodyW / 2) * 0.62) : clamp(room / rows, px.row * 2.3, px.row * (r0.h > r0.w * 1.05 ? 4.5 : 3.2));const h = Math.min(r0.h, top + rows * row + pad), r = { x: r0.x, y: r0.y + (r0.h - h) / 2, w: r0.w, h };const head = { x: r.x, y: r.y, w: r.w, h: headH };const aw = Math.min(r.w * 0.42, px.row * 0.62 * ui.action.length + 64 * u), ah = Math.max(52 * u, px.row * 1.9);@@ -70,6 +72,8 @@ const slot = (g: Geo, ui: ProductUI, i: number): Rect => {export const uiWindow = (r: Rect, ui: ProductUI, minPx = 0): Rect => geo(r, ui, minPx).win;/** Where the action button is (its centre), for the pointer and the sound's pan. */export const uiActionAt = (r: Rect, ui: ProductUI, minPx = 0): P => { const a = geo(r, ui, minPx).action; return [a.x + a.w / 2, a.y + a.h / 2]; };+/** The action button's rectangle (where a drop can sit beside it, clear of its word). */+export const uiActionRect = (r: Rect, ui: ProductUI, minPx = 0): Rect => geo(r, ui, minPx).action;/** Where the command bar's caret starts (its left text edge and centre line), when the UI has one. */export const uiCommandAt = (r: Rect, ui: ProductUI, minPx = 0): Rect | null => geo(r, ui, minPx).command;@@ -102,25 +106,27 @@ const num = (a: number | string | undefined, b: number | string | undefined, p:// ---------------------------------------------------------------- drawingexport const drawProductUI = (ctx: Ctx, r0: Rect, ui: ProductUI, m: UiMorph, T: UiTheme, o: UiOpts = {}) => {const g = geo(r0, ui, o.minPx ?? 0), u = g.u, acc = o.accent ?? T.accent, r = g.win;+ // (a look's radius caps every corner, so a square brand's product is square too; a square button is square)+ const RAD = (x: number) => (T.radius !== undefined ? Math.min(x, T.radius * u) : x);// the window- for (let i = 5; i >= 1; i--) { ctx.fillStyle = "rgba(20,24,30,0.022)"; rr(ctx, r.x - i * 2, r.y + i * 3, r.w + i * 4, r.h + i * 3, 24 * u + i * 2); ctx.fill(); }- ctx.fillStyle = T.card; rr(ctx, r.x, r.y, r.w, r.h, 24 * u); ctx.fill();+ for (let i = 5; i >= 1; i--) { ctx.fillStyle = "rgba(20,24,30,0.022)"; rr(ctx, r.x - i * 2, r.y + i * 3, r.w + i * 4, r.h + i * 3, RAD(24 * u + i * 2)); ctx.fill(); }+ ctx.fillStyle = T.card; rr(ctx, r.x, r.y, r.w, r.h, RAD(24 * u)); ctx.fill();ctx.lineWidth = 1.5 * u; ctx.strokeStyle = T.line; ctx.stroke();// the head: the product's name, its sections, the action- ctx.textBaseline = "middle"; ctx.font = SANS(700, g.px.title); ctx.fillStyle = T.ink;+ ctx.textBaseline = "middle"; ctx.font = (T.font ?? SANS)(700, g.px.title); ctx.fillStyle = T.ink;ctx.fillText(ui.title, r.x + 28 * u, g.head.y + g.head.h / 2);let nx = r.x + 28 * u + ctx.measureText(ui.title).width + 26 * u;- ctx.font = SANS(500, g.px.nav);- (ui.nav ?? []).forEach((t, i) => { const w = ctx.measureText(t).width; if (nx + w > g.action.x - 20 * u) return; if (i === 0) { ctx.fillStyle = T.chip; rr(ctx, nx - 12 * u, g.head.y + g.head.h / 2 - g.px.nav * 0.95, w + 24 * u, g.px.nav * 1.9, g.px.nav); ctx.fill(); } ctx.fillStyle = i === 0 ? T.ink : T.mute; ctx.fillText(t, nx, g.head.y + g.head.h / 2); nx += w + 36 * u; });+ ctx.font = (T.font ?? SANS)(500, g.px.nav);+ (ui.nav ?? []).forEach((t, i) => { const w = ctx.measureText(t).width; if (nx + w > g.action.x - 20 * u) return; if (i === 0) { ctx.fillStyle = T.chip; rr(ctx, nx - 12 * u, g.head.y + g.head.h / 2 - g.px.nav * 0.95, w + 24 * u, g.px.nav * 1.9, RAD(g.px.nav)); ctx.fill(); } ctx.fillStyle = i === 0 ? T.ink : T.mute; ctx.fillText(t, nx, g.head.y + g.head.h / 2); nx += w + 36 * u; });const pr = o.press ?? 0, q = 1 - 0.06 * pr, a = g.action;const hot = Math.max(o.hot ?? 0, pr); ctx.fillStyle = hot > 0 ? shade(acc, 1 - 0.18 * hot) : acc;- rr(ctx, a.x + (a.w * (1 - q)) / 2, a.y + (a.h * (1 - q)) / 2, a.w * q, a.h * q, (a.h * q) / 2); ctx.fill();- ctx.fillStyle = "#fff"; ctx.font = SANS(600, g.px.row * 0.8 * q); ctx.textAlign = "center"; ctx.fillText(ui.action, a.x + a.w / 2, a.y + a.h / 2 + 1); ctx.textAlign = "left";+ rr(ctx, a.x + (a.w * (1 - q)) / 2, a.y + (a.h * (1 - q)) / 2, a.w * q, a.h * q, RAD(T.button === "square" ? Math.min(8 * u, (a.h * q) / 2) : (a.h * q) / 2)); ctx.fill();+ ctx.fillStyle = T.onAccent ?? "#fff"; ctx.font = (T.font ?? SANS)(600, g.px.row * 0.8 * q); ctx.textAlign = "center"; ctx.fillText(ui.action, a.x + a.w / 2, a.y + a.h / 2 + 1); ctx.textAlign = "left";ctx.fillStyle = T.line; ctx.fillRect(r.x, g.head.y + g.head.h, r.w, 1.5 * u);// the command barif (g.command) {- const c = g.command; ctx.fillStyle = T.paper; rr(ctx, c.x, c.y, c.w, c.h, c.h / 2); ctx.fill(); ctx.strokeStyle = T.line; ctx.lineWidth = 1.5 * u; ctx.stroke();- ctx.font = SANS(500, g.px.row); ctx.textBaseline = "middle"; const tx = c.x + 26 * u;+ const c = g.command; ctx.fillStyle = T.paper; rr(ctx, c.x, c.y, c.w, c.h, RAD(c.h / 2)); ctx.fill(); ctx.strokeStyle = T.line; ctx.lineWidth = 1.5 * u; ctx.stroke();+ ctx.font = (T.font ?? SANS)(500, g.px.row); ctx.textBaseline = "middle"; const tx = c.x + 26 * u;if (o.typed) { ctx.fillStyle = T.ink; ctx.fillText(fitTail(ctx, o.typed, c.w - 60 * u), tx, c.y + c.h / 2); } else { ctx.fillStyle = T.mute; ctx.fillText(ui.command!, tx, c.y + c.h / 2); }if (o.caret) { const w = o.typed ? ctx.measureText(fitTail(ctx, o.typed, c.w - 60 * u)).width : 0; ctx.fillStyle = acc; ctx.fillRect(tx + w + 3 * u, c.y + c.h / 2 - g.px.row * 0.6, 3 * u, g.px.row * 1.2); }}@@ -129,35 +135,46 @@ export const drawProductUI = (ctx: Ctx, r0: Rect, ui: ProductUI, m: UiMorph, T:const bs = ui.before.stats ?? [], as = ui.after.stats ?? [], n = Math.max(bs.length, as.length), w = g.stats.w / n, p = spring(m.f, m.t0, m.omega ?? DEF.omega, m.zeta ?? DEF.zeta);for (let i = 0; i < n; i++) {const b = bs[i], x = as[i] ?? b, sx = g.stats.x + i * w;- ctx.font = SANS(500, g.px.small); ctx.fillStyle = T.soft; ctx.fillText((x ?? b).label, sx, g.stats.y + g.px.small * 0.7);- ctx.font = SANS(700, g.px.stat); ctx.fillStyle = T.ink; ctx.fillText(num(b?.value, x?.value, p, x?.unit ?? b?.unit ?? ""), sx, g.stats.y + g.px.small * 1.6 + g.px.stat * 0.62);+ ctx.font = (T.font ?? SANS)(500, g.px.small); ctx.fillStyle = T.soft; ctx.fillText((x ?? b).label, sx, g.stats.y + g.px.small * 0.7);+ ctx.font = (T.font ?? SANS)(700, g.px.stat); ctx.fillStyle = T.ink; counted(ctx, num(b?.value, x?.value, p, x?.unit ?? b?.unit ?? ""), sx, g.stats.y + g.px.small * 1.6 + g.px.stat * 0.62, "left", counting(b?.value, x?.value, p));}}// the items, each on its own spring- ctx.save(); rr(ctx, g.body.x - 8 * u, g.body.y - 8 * u, g.body.w + 16 * u, g.body.h + 16 * u, 12 * u); ctx.clip();- for (const s of poses(g, ui, m).sort((x, y) => (x.to ? 1 : 0) - (y.to ? 1 : 0))) {- const p = s.p, e = clamp(p), alpha = !s.from ? e : !s.to ? 1 - e : 1, k = !s.from ? 0.94 + 0.06 * out3(e) : 1;+ ctx.save(); rr(ctx, g.body.x - 8 * u, g.body.y - 8 * u, g.body.w + 16 * u, g.body.h + 16 * u, RAD(12 * u)); ctx.clip();+ // draw order: leaving items first, then the ones at rest, then the movers, the one rising last (it+ // lifts over the others). Two rows that trade places pass through each other; the one passed over+ // RECEDES: its words dim as the rising row comes within two lines of it and return as it clears, so the+ // two rows' words never stand a line apart reading as one ("$1,208 $144"). Rows at rest are never dimmed.+ const all = poses(g, ui, m).map((s) => { const p = s.p, e = clamp(p), moving = !!(s.from && s.to && (s.a.y !== s.b.y || s.a.x !== s.b.x)); return { s, e, moving, box: { x: lerp(s.a.x, s.b.x, p), y: lerp(s.a.y, s.b.y, p) + (!s.from ? (1 - e) * 14 * u : 0), w: s.a.w, h: s.a.h } as Rect }; });+ const z = (q: (typeof all)[number]) => (!q.s.to ? 0 : !q.moving ? 1 : q.s.b.y < q.s.a.y || (q.s.b.y === q.s.a.y && q.s.b.x < q.s.a.x) ? 3 : 2);+ all.sort((x, y) => z(x) - z(y) || x.s.order - y.s.order);+ const near = 2.15 * g.px.row, R = Math.max(g.row, near + 0.3 * g.px.row);+ const crosses = (x: Pose, y: Pose) => x.from && x.to && y.from && y.to && Math.sign(x.a.y - y.a.y || x.a.x - y.a.x) !== Math.sign(x.b.y - y.b.y || x.b.x - y.b.x);+ for (let i = 0; i < all.length; i++) {+ const { s, e, box } = all[i], p = s.p, alpha = !s.from ? e : !s.to ? 1 - e : 1, k = !s.from ? 0.94 + 0.06 * out3(e) : 1;if (alpha <= 0.002) continue;- const box: Rect = { x: lerp(s.a.x, s.b.x, p), y: lerp(s.a.y, s.b.y, p) + (!s.from ? (1 - e) * 14 * u : 0), w: s.a.w, h: s.a.h };- const it = e < 0.5 ? s.from ?? s.item : s.to ?? s.item, lift = s.from && s.to && (s.a.y !== s.b.y || s.a.x !== s.b.x) ? Math.sin(Math.PI * e) : 0;+ let words = 1;+ for (let j = i + 1; j < all.length; j++) { const o = all[j]; if (!o.moving || !crosses(s, o.s) || Math.abs(o.box.x - box.x) > box.w / 2) continue; words = Math.min(words, clamp((Math.abs(o.box.y - box.y) - near) / (R - near))); }+ const it = e < 0.5 ? s.from ?? s.item : s.to ?? s.item, lift = all[i].moving ? Math.sin(Math.PI * e) : 0;ctx.save(); ctx.globalAlpha = alpha; ctx.translate(box.x + box.w / 2, box.y + box.h / 2); ctx.scale(k, k); ctx.translate(-box.w / 2, -box.h / 2);- if (lift > 0) { ctx.fillStyle = `rgba(20,24,30,${0.07 * lift})`; rr(ctx, -4 * u, 6 * u, box.w + 8 * u, box.h + 4 * u, 14 * u); ctx.fill(); }- ctx.fillStyle = it.accent ? mixA(acc, T.card, 0.9) : ui.layout === "cards" ? T.paper : T.card; rr(ctx, 0, 0, box.w, box.h, 14 * u); ctx.fill();+ if (lift > 0) { ctx.fillStyle = `rgba(20,24,30,${0.07 * lift})`; rr(ctx, -4 * u, 6 * u, box.w + 8 * u, box.h + 4 * u, RAD(14 * u)); ctx.fill(); }+ ctx.fillStyle = it.accent ? mixA(acc, T.card, 0.9) : ui.layout === "cards" ? T.paper : T.card; rr(ctx, 0, 0, box.w, box.h, RAD(14 * u)); ctx.fill();ctx.strokeStyle = it.accent ? mixA(acc, T.card, 0.6) : T.line; ctx.lineWidth = 1.5 * u; ctx.stroke();const cy = ui.layout === "cards" ? g.px.row * 1.1 : box.h / 2 - (it.bar !== undefined ? 7 * u : 0), lx = 22 * u + g.px.row * 0.9;// a status mark: a ring, a filled accent dot, or a tick when doneconst done = s.from && s.to ? (e < 0.5 ? !!s.from.done : !!s.to.done) : !!it.done, mr = g.px.row * 0.3, mx = 22 * u + mr;ctx.lineWidth = 2.2 * u; ctx.strokeStyle = it.accent || done ? acc : T.mute; ctx.beginPath(); ctx.arc(mx, cy, mr, 0, Math.PI * 2);- if (done) { ctx.fillStyle = acc; ctx.fill(); ctx.strokeStyle = "#fff"; ctx.beginPath(); ctx.moveTo(mx - mr * 0.45, cy); ctx.lineTo(mx - mr * 0.1, cy + mr * 0.38); ctx.lineTo(mx + mr * 0.5, cy - mr * 0.35); ctx.stroke(); } else ctx.stroke();- ctx.font = SANS(600, g.px.row); ctx.fillStyle = T.ink; ctx.textBaseline = "middle";+ if (done) { ctx.fillStyle = acc; ctx.fill(); ctx.strokeStyle = T.onAccent ?? "#fff"; ctx.beginPath(); ctx.moveTo(mx - mr * 0.45, cy); ctx.lineTo(mx - mr * 0.1, cy + mr * 0.38); ctx.lineTo(mx + mr * 0.5, cy - mr * 0.35); ctx.stroke(); } else ctx.stroke();+ ctx.font = (T.font ?? SANS)(600, g.px.row); ctx.fillStyle = T.ink; ctx.textBaseline = "middle";const val = num(s.from?.value, s.to?.value ?? s.from?.value, s.from && s.to ? p : 1, it.unit ?? "");- ctx.font = SANS(700, g.px.value); const vw = val ? ctx.measureText(val).width : 0;- ctx.font = SANS(600, g.px.row); ctx.fillText(fitTail(ctx, it.label, box.w - lx - vw - 60 * u, true), lx, cy);- if (it.tag) { ctx.font = SANS(600, g.px.small); const tw = ctx.measureText(it.tag).width, tx = ui.layout === "cards" ? lx : Math.min(lx + ctx.measureText(it.label).width * (g.px.row / g.px.small) + 18 * u, box.w - vw - tw - 60 * u); if (tx > lx + 40 * u || ui.layout === "cards") { const ty = ui.layout === "cards" ? cy + g.px.row * 1.25 : cy; ctx.fillStyle = it.accent ? acc : T.chip; rr(ctx, tx - 10 * u, ty - g.px.small * 0.75, tw + 20 * u, g.px.small * 1.5, g.px.small * 0.75); ctx.fill(); ctx.fillStyle = it.accent ? "#fff" : T.soft; ctx.fillText(it.tag, tx, ty); } }- if (val) { ctx.font = SANS(700, g.px.value); ctx.fillStyle = it.accent ? acc : T.ink; ctx.textAlign = "right"; ctx.fillText(val, box.w - 22 * u, ui.layout === "cards" ? box.h - g.px.value : cy); ctx.textAlign = "left"; }+ ctx.font = (T.font ?? SANS)(700, g.px.value); const vw = val ? ctx.measureText(val).width : 0;+ const said = (draw: () => void) => { if (words <= 0) return; ctx.globalAlpha = alpha * words; draw(); ctx.globalAlpha = alpha; };+ ctx.font = (T.font ?? SANS)(600, g.px.row); said(() => ctx.fillText(fitTail(ctx, it.label, box.w - lx - vw - 60 * u, true), lx, cy));+ if (it.tag) { ctx.font = (T.font ?? SANS)(600, g.px.small); const tw = ctx.measureText(it.tag).width, tx = ui.layout === "cards" ? lx : Math.min(lx + ctx.measureText(it.label).width * (g.px.row / g.px.small) + 18 * u, box.w - vw - tw - 60 * u); if (tx > lx + 40 * u || ui.layout === "cards") { const ty = ui.layout === "cards" ? cy + g.px.row * 1.25 : cy; ctx.fillStyle = it.accent ? acc : T.chip; rr(ctx, tx - 10 * u, ty - g.px.small * 0.75, tw + 20 * u, g.px.small * 1.5, RAD(g.px.small * 0.75)); ctx.fill(); ctx.fillStyle = it.accent ? T.onAccent ?? "#fff" : T.soft; said(() => ctx.fillText(it.tag!, tx, ty)); } }+ if (val) { ctx.font = (T.font ?? SANS)(700, g.px.value); ctx.fillStyle = it.accent ? acc : T.ink; said(() => counted(ctx, val, box.w - 22 * u, ui.layout === "cards" ? box.h - g.px.value : cy, "right", !!(s.from && s.to) && counting(s.from.value, s.to.value, p))); ctx.textAlign = "left"; }if (it.bar !== undefined || s.from?.bar !== undefined) {const b0 = s.from?.bar ?? 0, b1 = s.to?.bar ?? b0, bv = clamp(s.from && s.to ? lerp(b0, b1, p) : b1, 0, 1.02), by = ui.layout === "cards" ? box.h - 16 * u : cy + g.px.row * 0.75, bw = box.w - lx - (ui.layout === "cards" ? 22 * u : vw + 60 * u);- ctx.fillStyle = T.chip; rr(ctx, lx, by, bw, 6 * u, 3 * u); ctx.fill(); ctx.fillStyle = it.accent ? acc : T.ink; rr(ctx, lx, by, Math.max(6 * u, bw * bv), 6 * u, 3 * u); ctx.fill();+ ctx.fillStyle = T.chip; rr(ctx, lx, by, bw, 6 * u, RAD(3 * u)); ctx.fill(); ctx.fillStyle = it.accent ? acc : T.ink; rr(ctx, lx, by, Math.max(6 * u, bw * bv), 6 * u, RAD(3 * u)); ctx.fill();}ctx.restore();}@@ -165,6 +182,16 @@ export const drawProductUI = (ctx: Ctx, r0: Rect, ui: ProductUI, m: UiMorph, T:ctx.globalAlpha = 1; ctx.textBaseline = "alphabetic";};+// A number on its way from one value to another is set digit by digit on a tabular grid: the figures+// do not jitter sideways as they count, and no passing value is drawn as one word (a "70%" counting+// through one card is not the "70%" resting in the next). At rest it is one word again.+const counting = (a: number | string | undefined, b: number | string | undefined, p: number) => typeof a === "number" && typeof b === "number" && a !== b && Math.abs(p - 1) > 0.002 && p > 0.002;+const counted = (ctx: Ctx, s: string, x: number, y: number, align: "left" | "right", tabular: boolean) => {+ if (!tabular) { ctx.textAlign = align; ctx.fillText(s, x, y); ctx.textAlign = "left"; return; }+ const fig = ctx.measureText("0").width, adv = (ch: string) => (/[0-9]/.test(ch) ? fig : ctx.measureText(ch).width), w = [...s].reduce((a, ch) => a + adv(ch), 0);+ let cx = align === "right" ? x - w : x; ctx.textAlign = "left";+ for (const ch of s) { ctx.fillText(ch, cx + (adv(ch) - ctx.measureText(ch).width) / 2, y); cx += adv(ch); }+};// the end of a line when it overflows (a command bar scrolls), or its start with an ellipsis (a label)const fitTail = (ctx: Ctx, s: string, w: number, head = false) => {if (ctx.measureText(s).width <= w) return s;diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/readable.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/readable.tsnew file mode 100644index 0000000..5a400dd--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/readable.ts@@ -0,0 +1,55 @@+// READABLE. Holds and type sizes from the reading rule, so a film's timing comes from its words, not+// from feel. A brand launch film typed its AI replies at 52 chars/s and held them a fixed 0.9 s after+// the last character; an 11-word reply was up about 2.5 s where the rule wants 3.3 s, and viewers said+// "too fast" twice, even after a 25 % slowdown. These helpers make the rule the default.+// readS(text) seconds a text needs: max(0.7 s, 0.3 s per word) (the same rule framecheck checks)+// chatHold(text, o) a typed reply: think + typing + reading AFTER the last character, times pace+// paced(s, pace, part) one pace scalar (or one per section) that every hold multiplies: "20 % slower" is pace 1.2+// texture(ctx, draw) text drawn inside is texture, not meant to be read ("blah blah"): framecheck skips it+// fitText(ctx, text, maxW, o) the largest size from maxPx down to minPx at which a line fits maxW+import type { Ctx } from "./core";++export const MIN_READ_S = 0.7, READ_S_PER_WORD = 0.3; // must equal tools/textrules.mjs (test/readable.test.ts holds them together)+const words = (t: string) => t.trim().split(/\s+/).filter(Boolean).length;++/** Seconds a viewer needs to read `text`. */+export const readS = (text: string) => Math.max(MIN_READ_S, READ_S_PER_WORD * words(text));++/** A pace: one number for the whole film, or one per named section (`default` for the rest). 1 = the rule; 1.25 = 25 % longer holds. */+export type Pace = number | ({ default?: number } & Record<string, number>);+export const paceOf = (pace: Pace = 1, section?: string) => (typeof pace === "number" ? pace : (section !== undefined && pace[section] !== undefined ? pace[section] : pace.default ?? 1));+/** Seconds times the pace for a section. Every hold of a film goes through this, so length changes are one number. */+export const paced = (s: number, pace: Pace = 1, section?: string) => s * paceOf(pace, section);++/**+ * A typed reply's timeline in seconds: a think beat, the typing, then the full reading time after the+ * last character (a reader cannot start before the sentence exists). `cps` is characters per second.+ * Pace stretches the think and the read, never the typing speed (typing speed is a character trait).+ */+export const chatHold = (text: string, o: { cps?: number; think?: number; pace?: Pace; section?: string } = {}) => {+ const k = paceOf(o.pace ?? 1, o.section), think = (o.think ?? 0.6) * k, typing = text.length / (o.cps ?? 52), read = readS(text) * k;+ return { think, typing, read, total: think + typing + read };+};+/** chatHold in whole frames (rounded up, so the hold never lands a frame short of the rule). */+export const chatHoldFrames = (text: string, fps: number, o: Parameters<typeof chatHold>[1] = {}) => { const h = chatHold(text, o); return { think: Math.ceil(h.think * fps), typing: Math.ceil(h.typing * fps), read: Math.ceil(h.read * fps), total: Math.ceil(h.think * fps) + Math.ceil(h.typing * fps) + Math.ceil(h.read * fps) }; };++/** Draw words meant as texture, not reading (fast "blah" behind a joke): framecheck's reading time and layout rules skip them. */+export const texture = (ctx: Ctx, draw: () => void) => {+ const c = ctx as Ctx & { __texture?: boolean }, was = c.__texture;+ c.__texture = true;+ try { draw(); } finally { c.__texture = was; }+};++/**+ * The largest whole px size, from maxPx down to minPx, at which `text` fits `maxW` in this font; sets+ * ctx.font to it. `fits` is false when even minPx overflows (shorten the copy: never let it clip).+ */+export const fitText = (ctx: Ctx, text: string, maxW: number, o: { maxPx: number; minPx: number; font: (px: number) => string }) => {+ let lo = Math.ceil(o.minPx), hi = Math.floor(o.maxPx);+ const w = (px: number) => { ctx.font = o.font(px); return ctx.measureText(text).width; };+ if (w(hi) <= maxW) return { px: hi, fits: true };+ if (w(lo) > maxW) return { px: lo, fits: false };+ while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (w(mid) <= maxW) lo = mid; else hi = mid; }+ ctx.font = o.font(lo);+ return { px: lo, fits: true };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/shipMeta.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/shipMeta.tsnew file mode 100644index 0000000..60d3ca4--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/shipMeta.ts@@ -0,0 +1,23 @@+// SHIP META. What a film tells the ship checks about itself (Film.meta.checks). Every field is+// optional and every one is read by a tool: framecheck.mjs, ship.mjs. Plain data, so it survives the+// page boundary as it is.+export type ShipMeta = {+ /** [fromFrame, toFrame, reason]: frames where the layout rules (density, gaps, centred stack, text over+ * text or over a box edge) are not judged. A deliberate wall of words or a collision that is the joke. */+ layoutExempt?: [from: number, to: number, reason: string][];+ /** The length budget in seconds (D1). ship prints the film's length and its shots against it; over max fails. */+ length?: { target: number; max: number };+ /** The brand's own font families (T8). Text set in any other family is listed for review. */+ fonts?: string[];+ /** Brand face -> the family standing in for it while the font file is missing (T8): every line set in a stand-in is listed. */+ standIns?: Record<string, string>;+ /** Music that is a supplied or generated track, not a score the page composes (X3). `track` is the take's+ * manifest from `track.mjs import` (<take>.track.json). verify-export then expects an audio stream, checks the+ * delivered mix came from that take, and ship runs track.mjs check and soundcheck --sfx on the file. */+ music?: { track: string };+ /** Checks with truly nothing to look at, by ship row name, each with its reason: { "review": "a test fixture+ * nobody is shown", "layers:translucent": "the brand has no colour of its own" }. A check that cannot look+ * FAILS in ship.mjs; a row named here is NONE instead, with the reason printed in the table. Gate check 5+ * reads "3d" the same way (a 3D film that registers no grip or rig to check). */+ none?: Record<string, string>;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/subtitles.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/subtitles.tsnew file mode 100644index 0000000..cc53d7b--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/subtitles.ts@@ -0,0 +1,263 @@+// SUBTITLES. A narrated film's words on screen, as short phrases that land on what is said.+// What the ghost film learned (lesson 36): a whole verse line in a lower band is too much to read;+// 2-6 word phrases, one at a time, each appearing as its first word is spoken, read fine. Pure: the+// timing comes in as data (tools/narrate.mjs writes voice-timing.json, `bake` puts it in the film).+//+// phrases(timing, opts) each line split into short phrases, timed in frames+// phrasePlan(timing, opts) the same, plus the problems (TOO TIGHT, a forced bad break)+// eventProblems(events, fps, opts) the caption rules, checked on any events (red fixtures in the tests)+// toCaptions(events, fps) -> meta.captions (tools/captions.mjs writes .srt/.vtt from it); refuses bad events+// drawSubtitles(ctx, env, frame, events, style) burned in: one phrase, a high-contrast plate, inside the safe area+// cue(timing, "line3:context") the frame a word is spoken on, so a shot can land on it (cueEnd: its last frame)+import { probeRect, type Ctx, type Env } from "./core";++export type TimedWord = { w: string; say?: string; from: number; to: number; t0?: number; t1?: number; est?: boolean }; // frames; t0/t1 seconds inside the take+export type TimedLine = { id: string; text: string; display?: string; start: number; end: number; durationS?: number; hash?: string; words: TimedWord[] };+/** voice-timing.json: every line and word in frames of the film (tools/narrate.mjs time) */+export type VoiceTiming = { version: number; fps: number; totalFrames: number; lines: TimedLine[]; provider?: string; sampleRate?: number };+export type CaptionEvent = { from: number; to: number; text: string; line: string; words: TimedWord[] };+export type Shape = "16x9" | "9x16" | "1x1";+export type PhraseOpts = {+ shape?: Shape;+ maxChars?: number; // per screen line; default 32 (16x9, 1x1) or 22 (9x16)+ minWords?: number; // 2+ maxWords?: number; // 6+ minHold?: number; // frames; default 20 at 24 fps, scaled by fps+ maxHoldS?: number; // 7+ gap?: number; // frames between two phrases, 2+ lead?: number; // frames a phrase appears before its first word, 2+ slip?: number; // frames a phrase may start after its first word when the one before needs its reading time, default 0.25 s+ early?: number; // frames a phrase may start before its first word to leave later phrases their reading time, default 0.5 s+ keep?: string[]; // extra names never split ("Total Recall", "Claude Code")+};++// the reading rule framecheck holds every cue to (tools/textrules.mjs: max(0.7 s, 0.3 s per word));+// kept equal here so a phrase this module makes can never fail it. A unit test pins the two together.+export const MIN_READ_S = 0.7, READ_S_PER_WORD = 0.3;+export const readingFrames = (text: string, fps: number) => Math.ceil(Math.max(MIN_READ_S, READ_S_PER_WORD * text.trim().split(/\s+/).filter(Boolean).length) * fps - 1e-9);++// ---------------------------------------------------------------- where a phrase may break+const ARTICLES = new Set(["a", "an", "the", "this", "these", "those", "my", "your", "his", "her", "its", "our", "their", "every", "each", "some", "no", "any"]);+const WEAK_END = new Set(["to", "of", "in", "on", "at", "for", "with", "from", "by", "and", "or", "but", "as", "into", "onto", "than", "very", "so", "is", "are", "was", "were"]);+const CLAUSE = new Set(["and", "but", "or", "so", "because", "which", "that", "when", "where", "while", "who", "if", "then", "until", "before", "after", "though", "although", "like", "with"]);+const UNITS = new Set(["%", "percent", "dollars", "dollar", "cents", "pounds", "euros", "ms", "s", "sec", "secs", "seconds", "second", "minutes", "minute", "min", "hours", "hour", "h", "days", "day", "weeks", "years", "frames", "frame", "fps", "px", "kb", "mb", "gb", "tb", "k", "m", "km", "kg", "g", "x", "times", "bpm", "hz", "khz", "db", "lufs", "am", "pm", "a.m.", "p.m.", "degrees", "points", "tokens", "words", "users", "people", "steps", "lines", "files"]);+const NUMWORD = /^(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million|billion|trillion|half|dozen)$/;+const bare = (w: string) => w.toLowerCase().replace(/^[^\w$£€%]+|[^\w%.]+$/g, "").replace(/\.$/, "");+const isNumber = (w: string) => /^[$£€]?\d/.test(bare(w)) || NUMWORD.test(bare(w));+const strongEnd = (w: string) => /[.!?;:]["'”’)\]]*$/.test(w);+const weakEnd = (w: string) => /[,—–]["'”’)\]]*$/.test(w) || /["”’)]$/.test(w);+const capital = (w: string) => /^["'“‘(]?[A-Z][a-z]/.test(w) || /^["'“‘(]?[A-Z]{2,}/.test(w);++/** Why the break between words a and b (a then b) is forbidden, or null when it is allowed. */+export const forbiddenBreak = (a: string, b: string, keep: string[] = []): string | null => {+ const A = bare(a), B = bare(b);+ if (strongEnd(a) || weakEnd(a)) return null; // punctuation always allows a break+ if (ARTICLES.has(A)) return `an article from its noun ("${a} | ${b}")`;+ if (isNumber(a) && (UNITS.has(B) || isNumber(b) || /^%/.test(b))) return `a number from its unit ("${a} | ${b}")`;+ if (/^[$£€]$/.test(A)) return `a currency sign from its amount ("${a} | ${b}")`;+ if (capital(a) && capital(b) && A !== "i" && B !== "i") return `a name ("${a} | ${b}")`;+ for (const k of keep) { const ws = k.split(/\s+/).map(bare); for (let i = 0; i < ws.length - 1; i++) if (ws[i] === A && ws[i + 1] === B) return `a kept name ("${k}")`; }+ return null;+};+// the cost of ending a phrase after word a (when b follows): punctuation is free, a clause word next is+// cheap, a dangling "and"/"to" is dear+const breakCost = (a: string, b: string) => strongEnd(a) ? 0 : weakEnd(a) ? 1 : (CLAUSE.has(bare(b)) ? 2 : 4) + (WEAK_END.has(bare(a)) ? 4 : 0);++/** Two screen lines at most, as even as the words allow, each within maxChars when it can be. */+export const wrapPhrase = (text: string, maxChars: number): string[] => {+ if (text.length <= maxChars) return [text];+ const ws = text.split(" ");+ let best: string[] = [text], bestCost = Infinity;+ for (let i = 1; i < ws.length; i++) {+ const a = ws.slice(0, i).join(" "), b = ws.slice(i).join(" "), over = Math.max(0, a.length - maxChars) + Math.max(0, b.length - maxChars), c = over * 100 + Math.abs(a.length - b.length);+ if (c < bestCost) { bestCost = c; best = [a, b]; }+ }+ return best;+};++const defaults = (fps: number, o: PhraseOpts) => ({+ maxChars: o.maxChars ?? (o.shape === "9x16" ? 22 : 32), minWords: o.minWords ?? 2, maxWords: o.maxWords ?? 6,+ minHold: o.minHold ?? Math.round((20 * fps) / 24), maxHold: Math.round((o.maxHoldS ?? 7) * fps), gap: o.gap ?? 2, lead: o.lead ?? 2,+ slip: o.slip ?? Math.round(0.25 * fps), early: o.early ?? Math.round(0.5 * fps), keep: o.keep ?? [],+});++// split one line's words into phrases by dynamic programming over the break points: every phrase within+// the word and character limits, no forbidden break, the cheapest set of breaks overall+const splitLine = (words: string[], d: ReturnType<typeof defaults>, problems: string[], lineId: string): number[][] => {+ const n = words.length;+ if (n <= d.minWords) return [words.map((_, i) => i)];+ const solve = (minW: number, allowForbidden: boolean) => {+ const best = new Array<number>(n + 1).fill(Infinity), from = new Array<number>(n + 1).fill(-1);+ best[0] = 0;+ for (let j = 1; j <= n; j++) for (let i = Math.max(0, j - d.maxWords); i <= j - 1; i++) {+ if (best[i] === Infinity) continue;+ const k = j - i, text = words.slice(i, j).join(" ");+ if (k < minW) continue;+ let c = best[i];+ // over one screen line it wraps to two: allowed, but dear (a single long word costs nothing: it cannot split)+ if (text.length > d.maxChars && k > 1) c += 40 + (text.length - d.maxChars) * 4;+ // a phrase that runs across a sentence end reads as two thoughts+ for (let q = i; q < j - 1; q++) if (strongEnd(words[q])) c += 6;+ // inside the phrase: no cost; at its end, the break's own cost (none at the line's end)+ if (j < n) { const why = forbiddenBreak(words[j - 1], words[j], d.keep); if (why) { if (!allowForbidden) continue; c += 100; } c += breakCost(words[j - 1], words[j]); }+ c += Math.pow(text.length - d.maxChars * 0.62, 2) / 120;+ if (c < best[j]) { best[j] = c; from[j] = i; }+ }+ if (best[n] === Infinity) return null;+ const out: number[][] = []; for (let j = n; j > 0; j = from[j]) out.unshift(Array.from({ length: j - from[j] }, (_, q) => from[j] + q));+ return out;+ };+ const sol = solve(d.minWords, false) ?? solve(1, false) ?? solve(1, true);+ if (!sol) return [words.map((_, i) => i)];+ for (let p = 0; p < sol.length - 1; p++) { const a = words[sol[p][sol[p].length - 1]], b = words[sol[p + 1][0]], why = forbiddenBreak(a, b, d.keep); if (why) problems.push(`${lineId}: forced to split ${why}: shorten the line or allow more words per phrase`); }+ return sol;+};++/**+ * Each line of the timing split into short phrases (2-6 words; punctuation first, then clause words, then+ * length; never a name, a number and its unit, or an article and its noun apart), each timed on the words+ * it holds: it appears `lead` frames before its first word and stays for its reading time (min hold, max+ * 7 s, 2-frame gap). A phrase whose reading time would push the next one more than `slip` frames off+ * its first word is TOO TIGHT: reported, never squeezed.+ */+export const phrasePlan = (timing: VoiceTiming, o: PhraseOpts = {}) => {+ const fps = timing.fps, d = defaults(fps, o), problems: string[] = [], events: CaptionEvent[] = [];+ const raw: { line: string; words: TimedWord[] }[] = [];+ for (const ln of timing.lines) {+ // a line with nothing to show (its display text was "") has no phrase to time: say which, then go on+ if (!ln.words?.length) { problems.push(`${ln.id}: no words to caption (is its display text empty?)`); continue; }+ for (const ix of splitLine(ln.words.map((w) => w.w), d, problems, ln.id)) raw.push({ line: ln.id, words: ix.map((i) => ln.words[i]) });+ }+ // Speech runs at about the reading rule's own pace (0.3 s a word), so phrases placed greedily drift+ // late. Two passes keep them on their words: backward, the latest each phrase may appear and still+ // leave every later phrase its reading time; forward, each appears at its ideal frame (lead before its+ // first word), earlier only when a later phrase needs the room, never more than `early` before it.+ const R = raw.map((r) => { const text = r.words.map((w) => w.w).join(" "); return { ...r, text, first: r.words[0].from, last: r.words[r.words.length - 1].to, need: Math.max(d.minHold, readingFrames(text, fps)) }; });+ const latest = new Array<number>(R.length);+ for (let k = R.length - 1; k >= 0; k--) latest[k] = Math.min(R[k].first + d.slip, k + 1 < R.length ? latest[k + 1] - d.gap - R[k].need : Infinity);+ const froms: number[] = [];+ for (let k = 0; k < R.length; k++) {+ const r = R[k], ideal = Math.max(0, r.first - d.lead), floor = k ? froms[k - 1] + R[k - 1].need + d.gap : 0;+ const from = Math.max(floor, Math.min(ideal, latest[k]));+ if (from > r.first + d.slip) problems.push(`TOO TIGHT: "${r.text}" (${r.line}) would appear ${from - r.first} frames after its first word is spoken (limit ${d.slip}): the phrases before it need their reading time. Give the line more time (pauseAfter), fewer words, or slow the voice`);+ else if (r.first - from > d.early) problems.push(`TOO TIGHT: "${r.text}" (${r.line}) would appear ${r.first - from} frames before its first word is spoken (limit ${d.early}) to leave the next phrases their reading time. Give the line more time (pauseAfter), fewer words, or slow the voice`);+ froms.push(from);+ }+ for (let k = 0; k < R.length; k++) {+ const r = R[k], from = froms[k], next = k + 1 < R.length ? froms[k + 1] : Infinity;+ let to = Math.min(Math.max(r.last + Math.round(0.25 * fps), from + r.need), next - d.gap);+ // a short hole before the next phrase is bridged, so the words don't blink off and on+ if (next - d.gap - to <= Math.round(0.5 * fps) && next - d.gap > to) to = next - d.gap;+ if (to - from > d.maxHold) { to = from + d.maxHold; if (to < r.last) problems.push(`"${r.text}" is spoken over more than ${d.maxHold / fps} s: split the line`); }+ events.push({ from, to: Math.max(to, from + 1), text: r.text, line: r.line, words: r.words });+ }+ return { events, problems: [...problems, ...eventProblems(events, fps, o)] };+};+/** The phrases of phrasePlan; throws on any problem, so a film can never ship a squeezed caption. */+export const phrases = (timing: VoiceTiming, o: PhraseOpts = {}): CaptionEvent[] => {+ const p = phrasePlan(timing, o);+ if (p.problems.length) throw new Error(`subtitles: ${p.problems.length} problem(s):\n ${p.problems.join("\n ")}`);+ return p.events;+};++/** The caption rules on any list of events (each a red fixture in test/subtitles.test.ts). */+export const eventProblems = (events: { from: number; to: number; text: string; line?: string }[], fps: number, o: PhraseOpts = {}) => {+ const d = defaults(fps, o), p: string[] = [];+ events.forEach((e, i) => {+ const hold = e.to - e.from, need = Math.max(d.minHold, readingFrames(e.text, fps));+ if (!Number.isInteger(e.from) || !Number.isInteger(e.to)) p.push(`"${e.text}": from/to must be whole frames`);+ if (hold < need) p.push(`"${e.text}" is up ${hold} frame(s); it needs ${need} (min hold ${d.minHold}, reading time ${readingFrames(e.text, fps)})`);+ if (hold > d.maxHold) p.push(`"${e.text}" is up ${(hold / fps).toFixed(1)} s, over ${d.maxHold / fps} s`);+ const lines = wrapPhrase(e.text, d.maxChars);+ if (lines.some((l) => l.length > d.maxChars) && e.text.includes(" ")) p.push(`"${e.text}" does not fit two lines of ${d.maxChars} characters`);+ const prev = events[i - 1];+ if (prev) {+ if (e.from < prev.to + d.gap) p.push(`"${e.text}" starts ${e.from - prev.to} frame(s) after "${prev.text}" ends (gap ${d.gap})`);+ if (prev.line === undefined || prev.line === e.line) { const a = prev.text.split(" ").pop()!, b = e.text.split(" ")[0], why = forbiddenBreak(a, b, d.keep); if (why) p.push(`split ${why} across two captions`); }+ }+ });+ return p;+};++/** Events -> meta.captions ({ from, to, text } in frames). Refuses events that break the rules (a 1-frame caption, an overlap). */+export const toCaptions = (events: { from: number; to: number; text: string; line?: string }[], fps: number, o: PhraseOpts = {}) => {+ const p = eventProblems(events, fps, o);+ if (p.length) throw new Error(`toCaptions: refused, ${p.length} problem(s):\n ${p.join("\n ")}`);+ return events.map(({ from, to, text }) => ({ from, to, text }));+};++// ---------------------------------------------------------------- cues: land a shot on a spoken word+const lineOf = (t: VoiceTiming, id: string) => { const l = t.lines.find((x) => x.id === id); if (!l) throw new Error(`cue: no line '${id}' (lines: ${t.lines.map((x) => x.id).join(", ")})`); return l; };+const findWord = (t: VoiceTiming, key: string) => {+ const [id, rest] = key.split(":"), l = lineOf(t, id);+ if (rest === undefined) return { l, w: null };+ const m = rest.match(/^(.*?)(?:#(\d+))?$/)!, want = bare(m[1]), nth = Number(m[2] ?? 1);+ const hits = l.words.filter((w) => bare(w.w) === want || bare(w.say ?? "") === want);+ if (hits.length < nth) throw new Error(`cue: '${key}': line ${id} says ${l.words.map((w) => w.w).join(" ")}`);+ return { l, w: hits[nth - 1] };+};+/** The frame a line starts ("line3") or a word starts ("line3:context", "line3:the#2" for the second "the"). */+export const cue = (t: VoiceTiming, key: string) => { const { l, w } = findWord(t, key); return w ? w.from : l.start; };+/** The frame after a line or word ends. */+export const cueEnd = (t: VoiceTiming, key: string) => { const { l, w } = findWord(t, key); return w ? w.to : l.end; };++// ---------------------------------------------------------------- burned in+export type SubtitleStyle = {+ /** where the phrase sits: centre x and centre y as shares of the frame, fixed or per frame (one home per shot, it moves only on a cut) */+ home?: [number, number] | ((frame: number) => [number, number]);+ size?: number; // logical px of the type; default 5 % of the short side... see below+ font?: (px: number) => string;+ color?: string; // the words: white, never grey+ accent?: string; // the word being spoken, when highlight is on+ plate?: string; // the plate behind the words+ highlight?: boolean; // light the word being spoken+ maxChars?: number; // wrap width in characters (default by shape, as phrases)+ margin?: number; // safe margin, share of the frame (default 0.05)+};+const SANS = (px: number) => `700 ${px}px "Avenir Next", "Helvetica Neue", Helvetica, Arial, sans-serif`;+const isTall = (W: number, H: number) => Math.abs(W / H - 9 / 16) < 0.02;+// the phone app chrome a 9:16 frame keeps clear of (tools/textrules.mjs SAFE_ZONES): top 14 %, bottom 25 %, right 14 %+const ZONES = { top: 0.14, bottom: 0.25, right: 0.14 };+const sm = (x: number) => { const t = Math.min(1, Math.max(0, x)); return t * t * (3 - 2 * t); };++/** The phrase box for an event (logical px), already clamped into the safe area. Exported for tests and placement checks. */+export const subtitleBox = (ctx: Ctx, env: Env, e: CaptionEvent, frame: number, style: SubtitleStyle = {}) => {+ const { W, H } = env, tall = isTall(W, H), size = style.size ?? Math.round(tall ? W * 0.06 : H * 0.05), font = (style.font ?? SANS)(size);+ ctx.font = font;+ const lines = wrapPhrase(e.text, style.maxChars ?? (tall ? 22 : 32)), lh = size * 1.22, padX = size * 0.55, padY = size * 0.32;+ const w = Math.max(...lines.map((l) => ctx.measureText(l).width)) + padX * 2, h = lines.length * lh + padY * 2;+ const home = typeof style.home === "function" ? style.home(frame) : style.home ?? (tall ? [0.43, 0.68] : [0.5, 0.86]);+ const m = style.margin ?? 0.05, x0min = W * m, x1max = tall ? W * (1 - ZONES.right) - W * 0.01 : W * (1 - m), y0min = tall ? H * ZONES.top + H * 0.01 : H * m, y1max = tall ? H * (1 - ZONES.bottom) - H * 0.01 : H * (1 - m);+ const x = Math.min(Math.max(home[0] * W - w / 2, x0min), x1max - w), y = Math.min(Math.max(home[1] * H - h / 2, y0min), y1max - h);+ return { x, y, w, h, lines, size, lh, padX, padY, font };+};++/** The phrase on screen at this frame, burned in: a soft pop in, a fade out, one phrase at a time. */+export const drawSubtitles = (ctx: Ctx, env: Env, frame: number, events: CaptionEvent[], style: SubtitleStyle = {}) => {+ const e = [...events].reverse().find((x) => frame >= x.from && frame < x.to); // phrases never overlap; the newest wins if they do+ if (!e) return;+ const t = frame - e.from, alpha = sm((t + 1) / 3) * sm((e.to - frame) / 3);+ if (alpha <= 0.01) return;+ ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);+ const b = subtitleBox(ctx, env, e, frame, style), pop = t < 4 ? 0.94 + 0.06 * sm(t / 4) : 1;+ const cx = b.x + b.w / 2, cy = b.y + b.h / 2;+ ctx.translate(cx, cy); ctx.scale(pop, pop); ctx.translate(-cx, -cy);+ ctx.globalAlpha = alpha;+ ctx.fillStyle = style.plate ?? "rgba(10,10,14,0.82)";+ const r = b.size * 0.35; ctx.beginPath(); ctx.roundRect(b.x, b.y, b.w, b.h, r); ctx.fill();+ probeRect(ctx, env, b.x, b.y, b.w, b.h, e.text, "text");+ ctx.font = b.font; ctx.textBaseline = "middle"; ctx.textAlign = "left"; ctx.lineJoin = "round";+ // the spoken word lights only when the timing says which one it is: each screen word is matched to its timed word in order+ let wi = 0;+ b.lines.forEach((line, li) => {+ const lw = ctx.measureText(line).width, y = b.y + b.padY + b.lh * (li + 0.5);+ let x = b.x + (b.w - lw) / 2;+ for (const word of line.split(" ")) {+ const tw = e.words[wi++], on = style.highlight && tw && frame >= tw.from && frame < tw.to;+ ctx.lineWidth = b.size * 0.12; ctx.strokeStyle = "rgba(0,0,0,0.55)"; ctx.strokeText(word, x, y);+ ctx.fillStyle = on ? style.accent ?? "#FFD84D" : style.color ?? "#FFFFFF"; ctx.fillText(word, x, y);+ x += ctx.measureText(word + " ").width;+ }+ });+ ctx.restore();+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeHello.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeHello.tsnew file mode 100644index 0000000..6a556fa--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeHello.ts@@ -0,0 +1,38 @@+// THREE HELLO. The smallest 3D film: a bevelled star turning under a key light. It proves the+// stage bridge (WebGL -> the frame), purity (every value set from the frame) and the gate.+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import * as THREE from "three";+import { draw3d, memo } from "../three-core/stage";++const W = 1280, H = 720, FPS = 24, N = 96;+const build = () => {+ const scene = new THREE.Scene();+ const shape = new THREE.Shape();+ for (let i = 0; i < 10; i++) { const a = (i / 10) * Math.PI * 2 + Math.PI / 2, r = i % 2 ? 0.45 : 1; const x = Math.cos(a) * r, y = Math.sin(a) * r; if (i) shape.lineTo(x, y); else shape.moveTo(x, y); }+ const geo = new THREE.ExtrudeGeometry(shape, { depth: 0.35, bevelEnabled: true, bevelThickness: 0.08, bevelSize: 0.06, bevelSegments: 4 });+ geo.center();+ const star = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: "#ffde59", roughness: 0.45, metalness: 0.1 }));+ scene.add(star);+ const floor = new THREE.Mesh(new THREE.CircleGeometry(3, 64), new THREE.MeshStandardMaterial({ color: "#1d1a2b", roughness: 1 }));+ floor.rotation.x = -Math.PI / 2; floor.position.y = -1.3; scene.add(floor);+ const key = new THREE.DirectionalLight("#fff2e0", 2.6); key.position.set(3, 4, 5); scene.add(key);+ scene.add(new THREE.HemisphereLight("#b9c8ff", "#2a2033", 0.9));+ const cam = new THREE.PerspectiveCamera(35, W / H, 0.1, 100);+ return { scene, star, cam };+};+const turn = (ctx: Ctx, f: number, env: Env) => {+ const { scene, star, cam } = memo(env, "threeHello", build);+ const t = f / N;+ star.rotation.set(0.25 * Math.sin(t * Math.PI * 2), t * Math.PI * 2, 0);+ star.position.y = 0.15 * Math.sin(t * Math.PI * 4);+ cam.position.set(Math.sin(t * Math.PI * 2) * 0.8, 0.6, 5.2); cam.lookAt(0, 0, 0);+ draw3d(ctx, env, scene, cam, { clear: "#0f0d1a" });+};+export const threeHello: Film = {+ meta: { title: "three hello", W, H, fps: FPS, bpm: 120, durationFrames: N, kind: "loop",+ // gate check 5 FAILS a 3D film that registers nothing; this one has nothing physical to go wrong+ checks: { none: { "3d": "one star turning alone in the middle of the frame: no character, nothing held, nothing for it to pass through" } } },+ assets: { images: {} },+ shots: [{ id: "turn", start: 0, end: N, draw: turn }],+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.tsnew file mode 100644index 0000000..931f973--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeMotionDemo.ts@@ -0,0 +1,162 @@+// THREE MOTION DEMO. A 9.5 s tour of the 3D motion kit (three-core/timeline, camera, mograph) on+// simple bevelled shapes in one studio: four stations along x, one shot each, cuts on the beat.+// grid a 5x5 field of bevelled tiles pops in from the centre, then a wave rolls across it;+// push-in with a light handheld+// write a ribbon writes itself through the air with a glowing bead riding its tip; pillars rise+// from the floor; the camera dollies past on a constant-speed path+// morph a ring draws on, its beads pop in, and the ring morphs into a star while the camera+// orbits; a whip pan (held frames, no smear) carries us to the next station+// explode a 3x3x3 block flashes, blows apart and reassembles under a crane up with a dutch roll+// Everything moving is set from the frame: the scene is built once (memo) and every draw re-poses it.+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import * as THREE from "three";+import { draw3d, memo } from "../three-core/stage";+import { checking, registerPath, registerSize, runChecks } from "../three-core/checks3d";+import { ease, seg, tween } from "../three-core/time";+import { crane, dolly, dutch, handheld, hash01, look, orbit, path, place, pushIn, then, whipPan, withMods, type CamState, type Move, type V3 } from "../three-core/camera";+import { assemble, dropIn, explode, grid, indicate, lagged, morph, moveAlongPath, popIn, riseFromFloor, wave, writeOn, writeTube } from "../three-core/mograph";++const W = 1920, H = 1080, FPS = 24, BEAT = 12, N = 19 * BEAT; // 228 frames, 9.5 s+const BG = "#15122a", FLOOR = "#221d3d";+const PAL = { coral: "#ff6b5b", sun: "#ffc53d", teal: "#2ec4b6", lilac: "#8c7dff", cream: "#f3ece0" };+const CUT = { write: 4 * BEAT, morph: 9 * BEAT, explode: 14 * BEAT };+const ST = { grid: [0, 0, 0] as V3, write: [17, 0, 0] as V3, morph: [34, 0, 0] as V3, explode: [51, 0, 0] as V3 };++const mat = (color: string, o: { emissive?: string; ei?: number; rough?: number } = {}) =>+ new THREE.MeshPhysicalMaterial({ color, roughness: o.rough ?? 0.42, metalness: 0, clearcoat: 0.5, clearcoatRoughness: 0.35, emissive: o.emissive ?? "#000000", emissiveIntensity: o.ei ?? 1 });+// a rounded rectangle extruded with a soft bevel: the "designed object" look, never a raw box+const slab = (w: number, d: number, depth: number, r: number, bevel = 0.06) => {+ const s = new THREE.Shape(), x = -w / 2, y = -d / 2;+ s.moveTo(x + r, y); s.lineTo(x + w - r, y); s.quadraticCurveTo(x + w, y, x + w, y + r); s.lineTo(x + w, y + d - r); s.quadraticCurveTo(x + w, y + d, x + w - r, y + d);+ s.lineTo(x + r, y + d); s.quadraticCurveTo(x, y + d, x, y + d - r); s.lineTo(x, y + r); s.quadraticCurveTo(x, y, x + r, y);+ const g = new THREE.ExtrudeGeometry(s, { depth, bevelEnabled: true, bevelThickness: bevel, bevelSize: bevel, bevelSegments: 4, curveSegments: 6 });+ return g;+};+const shadowy = (m: THREE.Object3D) => { m.traverse((c) => { c.castShadow = true; c.receiveShadow = true; }); return m; };++const build = () => {+ const scene = new THREE.Scene();+ scene.background = new THREE.Color(BG);+ scene.fog = new THREE.Fog(BG, 22, 48);+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(400, 400), new THREE.MeshStandardMaterial({ color: FLOOR, roughness: 0.95 }));+ floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);+ const key = new THREE.DirectionalLight("#fff1dc", 2.4); key.castShadow = true;+ key.shadow.mapSize.set(2048, 2048); key.shadow.bias = -0.0004; key.shadow.normalBias = 0.02; key.shadow.radius = 4;+ Object.assign(key.shadow.camera, { left: -8, right: 8, top: 8, bottom: -8, near: 1, far: 40 });+ scene.add(key, key.target);+ const rim = new THREE.DirectionalLight("#9fb4ff", 1.2); scene.add(rim, rim.target);+ scene.add(new THREE.HemisphereLight("#c9d2ff", "#2a2240", 0.85));++ // grid: 5x5 tiles in three heights, in a palette that walks the colours diagonally+ const tiles = new THREE.Group(), heights = [0.25, 0.5, 0.8].map((h) => { const g = slab(0.8, 0.8, h, 0.16, 0.05); g.rotateX(-Math.PI / 2); g.translate(0, 0.05, 0); return g; });+ const tileCols = [PAL.coral, PAL.sun, PAL.teal, PAL.lilac, PAL.cream].map((c) => mat(c));+ for (let i = 0; i < 5; i++) for (let j = 0; j < 5; j++) {+ const h = Math.floor(hash01(11, i * 5 + j) * 3), m = new THREE.Mesh(heights[h], tileCols[(i + j) % 5]);+ m.position.set((i - 2) * 1.02, 0, (j - 2) * 1.02); tiles.add(m);+ }+ tiles.position.set(...ST.grid); scene.add(shadowy(tiles));++ // write: a ribbon swooping through the air, a bead at its tip, pillars around it+ const swoop = path([[-4, 0.4, 2.2], [-2.6, 1.8, 0.4], [-0.6, 3.0, -1.4], [1.6, 2.4, -0.6], [1.2, 1.0, 1.4], [-0.4, 1.4, 0.8], [0.4, 2.6, -0.2], [2.6, 3.2, 0.2], [4.2, 1.6, 1.6]].map((p) => [p[0] + ST.write[0], p[1], p[2]] as V3));+ const ribbon = new THREE.Mesh(new THREE.TubeGeometry(swoop, 480, 0.13, 20), mat(PAL.coral, { rough: 0.3 }));+ const bead = new THREE.Mesh(new THREE.SphereGeometry(0.24, 32, 20), mat(PAL.sun, { emissive: PAL.sun, ei: 0.9 }));+ const pillars = new THREE.Group();+ [[-3.0, -2.0, 1.6, PAL.lilac], [3.4, -2.4, 2.4, PAL.teal], [-0.8, -3.4, 1.1, PAL.cream], [4.6, 0.2, 0.8, PAL.sun]].forEach(([x, z, h, c]) => {+ const g = new THREE.CylinderGeometry(0.42, 0.42, h as number, 40); g.translate(0, (h as number) / 2, 0);+ const m = new THREE.Mesh(g, mat(c as string)); m.position.set(ST.write[0] + (x as number), 0, z as number); pillars.add(m);+ });+ bead.position.copy(swoop.getPointAt(0));+ scene.add(shadowy(ribbon), shadowy(bead), shadowy(pillars));++ // morph: a ring of beads and a tube laid through them, standing up; a circle becoming a star+ const M = 64, cy = 2.3, ringR = 1.9;+ const circle: V3[] = Array.from({ length: M }, (_, i) => { const a = (i / M) * Math.PI * 2 + Math.PI / 2; return [ST.morph[0] + Math.cos(a) * ringR, cy + Math.sin(a) * ringR, 0]; });+ const star: V3[] = Array.from({ length: 10 }, (_, i) => { const a = (i / 10) * Math.PI * 2 + Math.PI / 2, r = i % 2 ? 0.95 : 2.25; return [ST.morph[0] + Math.cos(a) * r, cy + Math.sin(a) * r, 0]; });+ const ringTube = new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(circle.map((p) => new THREE.Vector3(...p)), true), 256, 0.07, 12, true), mat(PAL.teal, { rough: 0.3 }));+ const beads = new THREE.Group(), beadGeo = new THREE.SphereGeometry(0.15, 24, 16), beadMat = mat(PAL.sun, { emissive: "#ff9a1f", ei: 0.35 });+ for (let i = 0; i < 20; i++) beads.add(new THREE.Mesh(beadGeo, beadMat));+ const plinth = new THREE.Mesh(slab(5.6, 1.4, 0.3, 0.3, 0.06).rotateX(-Math.PI / 2), mat(PAL.lilac)); plinth.position.set(ST.morph[0], 0.06, 0);+ scene.add(shadowy(ringTube), shadowy(beads), shadowy(plinth));++ // explode: a 3x3x3 block of soft cubes, sun on the corners, coral on the edges, cream elsewhere+ const block = new THREE.Group(), cubeGeo = slab(0.52, 0.52, 0.52, 0.12, 0.05); cubeGeo.center();+ const cubeMat = { sun: mat(PAL.sun), coral: mat(PAL.coral), cream: mat(PAL.cream) };+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) for (let k = 0; k < 3; k++) {+ const ends = [i, j, k].filter((v) => v !== 1).length, m = new THREE.Mesh(cubeGeo, ends === 3 ? cubeMat.sun : ends === 2 ? cubeMat.coral : cubeMat.cream);+ m.position.set((i - 1) * 0.68, 0.34 + j * 0.68, (k - 1) * 0.68); block.add(m);+ }+ const blockWrap = new THREE.Group(); blockWrap.add(block); blockWrap.position.set(...ST.explode);+ scene.add(shadowy(blockWrap));++ const cam = new THREE.PerspectiveCamera(35, W / H, 0.1, 200);+ return { scene, key, rim, tiles, swoop, ribbon, bead, pillars, circle, star, ringTube, beads, block, blockWrap, cam };+};++// ---- camera, one move per shot, in film frames+const shot1 = withMods(pushIn(look([3.6, 4.4, 7.2], [0, 0.1, 0.2], 36), 0.22, 0, CUT.write, ease.inOutSine), handheld(2, 0.6));+const shot2 = withMods(dolly(path([[ST.write[0] - 5.5, 1.3, 7.6], [ST.write[0] - 2.5, 2.3, 7.8], [ST.write[0] + 1.5, 2.8, 8.0], [ST.write[0] + 4.5, 2.1, 8.4]]), CUT.write, CUT.morph, { target: [ST.write[0], 1.7, 0], fov: 38, ease: ease.inOutSine }), handheld(3, 0.4));+const D0: CamState = look([ST.explode[0] + 4.6, 2.4, 6.6], [ST.explode[0], 1.0, 0], 36);+const WHIP = CUT.explode - BEAT;+const orbitC = orbit([ST.morph[0], 1.9, 0], -38, 22, 10.6, 0.8, CUT.morph, WHIP + 2, { fov: 36, ease: ease.inOutSine });+const shot3: Move = then(orbitC, WHIP, whipPan(orbitC(WHIP), D0, WHIP, CUT.explode, { hold: 2 }));+const shot4 = withMods(crane(D0, 2.2, CUT.explode, N, { follow: 0.25, ease: ease.inOutSine }), dutch((f) => -7 * tween(f, CUT.explode, N, ease.inOutSine)), handheld(5, 0.5));+const camAt = (f: number) => (f < CUT.write ? shot1(f) : f < CUT.morph ? shot2(f) : f < CUT.explode ? shot3(f) : shot4(f));++const draw = (ctx: Ctx, f: number, env: Env) => {+ const s = memo(env, "threeMotionDemo", build);++ // grid: pops from the centre outwards (begun just before frame 0 so the film opens on motion), then a wave+ grid(s.tiles, f, -14, 3, (c, ff, at) => popIn(c, ff, at, 12));+ wave(s.tiles, f, 20, 26, { height: 0.45, width: 4 });++ // write: pillars rise on the beat, the ribbon writes on with the bead on its tip+ lagged(s.pillars, f, CUT.write - 6, 6, (c, ff, at) => riseFromFloor(c, ff, at, 14, 2.6));+ const w0 = CUT.write + 2, w1 = CUT.morph - 10, wt = ease.inOutSine(seg(f, w0, w1));+ writeOn(s.ribbon, f, w0, w1 - w0, ease.inOutSine);+ // the bead drops onto the ribbon's start (its rest pose), then rides the tip; dropIn's squash rings on+ dropIn(s.bead, f, w0 - 10, 14, { height: 2.5 });+ if (f >= w0) moveAlongPath(s.bead, s.swoop, wt);++ // morph: ring draws on, beads pop in around it, circle becomes star, star pulses+ const m0 = CUT.morph, mt = ease.inOutCubic(seg(f, m0 + 14, m0 + 34));+ const shape = morph(s.circle, s.star, mt, { n: 120, closed: true });+ writeTube(s.ringTube.geometry as THREE.TubeGeometry, shape, true);+ writeOn(s.ringTube, f, m0 - 4, 14, ease.outCubic);+ const ring20 = morph(s.circle, s.star, mt, { n: 20, closed: true });+ // popIn owns scale and visibility only, so the beads ride the morph through position freely+ lagged(s.beads, f, m0 + 2, 1, (b, ff, at, i) => { b.position.set(...ring20[i]); popIn(b, ff, at, 10); });+ indicate(s.beads, f, m0 + 36, 12, { scale: 1.0, color: "#ffffff", strength: 0.5 });++ // explode: flash in the whip's tail, blow apart on the beat, home again two beats later+ indicate(s.blockWrap, f, CUT.explode - 6, 12, { scale: 1.08, color: "#ffe9b0", strength: 0.45 });+ if (f < CUT.explode + 24) explode(s.block, f, CUT.explode + 6, 18, { seed: 9, distance: 1.9, spin: 0.35, upward: true });+ else assemble(s.block, f, CUT.explode + 26, 22, { seed: 9, distance: 1.9, spin: 0.35, upward: true, ease: ease.inOutCubic });++ // lights follow the station the camera is at, so one 16-unit shadow map covers every shot+ const c = camAt(f), at = c.target;+ s.key.position.set(at[0] + 5, 9, at[2] + 6); s.key.target.position.set(at[0], 0, at[2]);+ s.rim.position.set(at[0] - 4, 5, at[2] - 8); s.rim.target.position.set(at[0], 1, at[2]);+ place(s.cam, c, env);+ draw3d(ctx, env, s.scene, s.cam, { clear: BG, shadows: true });+ // what each station must keep true (checks3d, gate check 5): its subject big enough to read, and the bead+ // riding the ribbon never passes through a pillar (an upright cylinder the bead's size around its centre)+ if (checking()) {+ if (f < CUT.write) registerSize(s.tiles, 40);+ else if (f < CUT.morph) {+ registerSize(s.pillars, 40);+ if (f >= w0) registerPath({ at: (ff) => s.swoop.getPointAt(ease.inOutSine(seg(ff, w0, w1))).clone().setY(s.swoop.getPointAt(ease.inOutSine(seg(ff, w0, w1))).y - 0.24), from: f, to: f, radius: 0.24, height: 0.48, name: "bead" }, s.pillars.children.map((c, i) => ({ name: `pillar ${i + 1}`, box: c })));+ } else if (f < WHIP) registerSize(s.ringTube, 40);+ else if (f >= CUT.explode) registerSize(s.blockWrap, 40);+ runChecks(f, s.cam, env);+ }+};++const shot = (id: string, start: number, end: number) => ({ id, start, end, draw: (ctx: Ctx, local: number, env: Env) => draw(ctx, start + local, env) });+export const threeMotionDemo: Film = {+ meta: { title: "three motion demo", W, H, fps: FPS, bpm: 120, durationFrames: N, kind: "explainer", poster: 130,+ // the whip pan opens on posed held frames (no smear, lesson 46); the star has finished, so they are truly still+ holds: [[WHIP, WHIP + 3, "whip pan: held pose before the whip"]] },+ assets: { images: {} },+ shots: [shot("grid", 0, CUT.write), shot("write", CUT.write, CUT.morph), shot("morph", CUT.morph, CUT.explode), shot("explode", CUT.explode, N)],+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeRigDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeRigDemo.tsnew file mode 100644index 0000000..e55abb0--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeRigDemo.ts@@ -0,0 +1,252 @@+// THREE RIG DEMO. Nib, a little lamp-lighter robot built from primitives with three-core/rig.ts,+// walks in (arms counter-swinging, body bobbing), stops (antenna and body follow through), winds up,+// reaches for a lantern on a crate with two-bone IK, takes the handle in its jaws, lifts it (the+// lantern lags, then swings through), turns to the camera and waves. Every frame is posed from the+// frame number alone, and every frame passes checks3d (grip, proximity, self, path, screen size):+// test/threeChecks.test.ts runs them on all 192 frames, and on two broken variants that must fail.+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import * as THREE from "three";+import { draw3d, memo } from "../three-core/stage";+import { ease, lerp, seg, spring, tween } from "../three-core/time";+import { anticipate, bodyMatrix, flag, followThrough, grip, handle, head, limb, makeRig, part, pose, walkCycle, type Limb, type LimbPose } from "../three-core/rig";+import { checking, registerGrip, registerPath, registerRig, registerSize, resetChecks, runChecks } from "../three-core/checks3d";++const W = 1920, H = 1080, FPS = 24, N = 192;+type V3 = THREE.Vector3;+const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);++// ---------------------------------------------------------------- the beats (frames)+export const BEATS = { stop: 84, windup: 92, reach: 100, approach: 114, onBar: 121, closed: 126, lift: 128, lifted: 146, turn: 140, wave: 156, giggle: 160 };+const STRIDE = 0.56, CYCLES = 3.55; // the walk ends at phase .55: both feet planted (stance 0.6), so the stop never freezes a foot mid-air+const STOP_X = 0.05;+// the carry: the lantern lags AWAY from the arm as it rises, and the wrist bends over it so the+// forearm stays clear of the lid (an upright wrist put the forearm through the lid: checks3d found it)+const LAG = 0.1, WR = -0.4;+export type Variant = "clean" | "offset" | "path";++// ---------------------------------------------------------------- materials and parts+const std = (color: string, o: THREE.MeshStandardMaterialParameters = {}) => new THREE.MeshStandardMaterial({ color, roughness: 0.5, ...o });+const glow = (color: string, k = 1.6) => new THREE.MeshStandardMaterial({ color: "#000000", emissive: color, emissiveIntensity: k, roughness: 1 });++// Nib's hand: a palm and two jaws hinged at the back of a ring. Closed, the jaws make a ring whose+// hole runs along the hand's x axis: a handle passes THROUGH it (lesson 37), never through the palm.+const RING_R = 0.035, RING_T = 0.0125, GRIP_Y = 0.074;+const makeHand = (jaws: Record<string, THREE.Group[]>, name: string, cream: THREE.Material, coral: THREE.Material) => () => {+ const g = new THREE.Group();+ const palm = new THREE.Mesh(new THREE.SphereGeometry(0.038, 20, 14), cream); palm.scale.set(1.15, 1, 1); g.add(palm);+ const hingeY = GRIP_Y - RING_R, list: THREE.Group[] = [];+ // the ring lies in the hand's y-z plane; a point at angle a: centre + R (cos a y + sin a z)+ const basis = new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(v3(0, 1, 0), v3(0, 0, 1), v3(1, 0, 0)));+ for (const s of [1, -1]) {+ const hinge = new THREE.Group(); hinge.position.set(0, hingeY, 0);+ const a0 = s > 0 ? 0.035 * Math.PI : -Math.PI + 0.06, len = 0.93 * Math.PI;+ const m = new THREE.Mesh(new THREE.TorusGeometry(RING_R, RING_T, 10, 28, len), coral);+ m.position.set(0, RING_R, 0); m.quaternion.copy(basis).multiply(new THREE.Quaternion().setFromAxisAngle(v3(0, 0, 1), a0));+ m.userData.part = `${name}.jaw`; hinge.add(m); hinge.userData.side = s; list.push(hinge); g.add(hinge);+ }+ jaws[name] = list;+ return g;+};++const build = () => {+ const scene = new THREE.Scene();+ const cream = std("#f4eee3", { roughness: 0.42 }), coral = std("#ff7656", { roughness: 0.45 }), slate = std("#5c6a80", { roughness: 0.5, metalness: 0.15 });+ const visorM = std("#18202f", { roughness: 0.16, metalness: 0.35 }), eyeM = glow("#8ff4ff", 2.2), cheekM = glow("#ff8f80", 0.9);++ // ---- Nib+ const nib = makeRig("nib", { hipHeight: 0.515 });+ const torso = part(nib, nib.body, "torso", new THREE.Mesh(new THREE.CapsuleGeometry(0.2, 0.2, 10, 32), cream)); torso.position.y = 0.25; torso.scale.set(1.05, 1, 0.92);+ const bib = part(nib, nib.body, "bib", new THREE.Mesh(new THREE.CylinderGeometry(0.203, 0.203, 0.15, 32, 1, true, -0.5, 1.0), coral)); bib.position.y = 0.22; bib.scale.set(1.05, 1, 0.92);+ const button = part(nib, nib.body, "button", new THREE.Mesh(new THREE.SphereGeometry(0.024, 16, 12), std("#ffd25e", { emissive: "#ffb000", emissiveIntensity: 0.35 }))); button.position.set(0, 0.235, 0.19);+ const neck = new THREE.Group(); nib.hips.add(neck); nib.anchors.push({ obj: neck, base: v3(0, 0.56, 0) });+ part(nib, neck, "neck", new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.06, 0.09, 20), slate)).position.y = 0.03;+ const hd = head(nib, "head", { at: [0, 0.6, 0], max: [1.15, 0.55] });+ const skull = part(nib, hd.pivot, "head", new THREE.Mesh(new THREE.SphereGeometry(0.2, 40, 28), cream)); skull.position.y = 0.17; skull.scale.set(1.12, 0.92, 1);+ const visor = part(nib, skull, "visor", new THREE.Mesh(new THREE.SphereGeometry(0.204, 40, 20, Math.PI / 2 - 0.95, 1.9, 1.0, 1.05), visorM)); void visor;+ const eyes: THREE.Mesh[] = [];+ for (const s of [-1, 1]) {+ const e = part(nib, hd.pivot, "eye", new THREE.Mesh(new THREE.CapsuleGeometry(0.021, 0.028, 6, 14), eyeM)); e.position.set(0.064 * s, 0.195, 0.196); e.rotation.x = -0.12; eyes.push(e);+ const c = part(nib, hd.pivot, "cheek", new THREE.Mesh(new THREE.CircleGeometry(0.017, 20), cheekM)); c.position.set(0.112 * s, 0.14, 0.186); c.rotation.set(-0.15, 0.5 * s, 0);+ const ear = part(nib, hd.pivot, "ear", new THREE.Mesh(new THREE.CylinderGeometry(0.052, 0.052, 0.045, 24), coral)); ear.rotation.z = Math.PI / 2; ear.position.set(0.222 * s, 0.17, 0);+ }+ const mouth = part(nib, hd.pivot, "mouth", new THREE.Mesh(new THREE.TorusGeometry(0.026, 0.0055, 8, 24, Math.PI), eyeM)); mouth.position.set(0, 0.142, 0.203); mouth.rotation.set(-0.2, 0, Math.PI);+ const antenna = new THREE.Group(); antenna.position.set(0, 0.352, -0.01); hd.pivot.add(antenna);+ part(nib, antenna, "antenna", new THREE.Mesh(new THREE.CylinderGeometry(0.008, 0.01, 0.12, 10), slate)).position.y = 0.06;+ part(nib, antenna, "antenna.tip", new THREE.Mesh(new THREE.SphereGeometry(0.03, 18, 12), std("#ff7656", { emissive: "#ff5a36", emissiveIntensity: 0.5 }))).position.y = 0.14;++ const jaws: Record<string, THREE.Group[]> = {};+ const arm = (side: "left" | "right", s: number) => limb(nib, `arms.${side}`, { at: [0.235 * s, 0.4, 0], lengths: [0.19, 0.19], radius: [0.032, 0.029], rest: [0.05 * s, -0.34, 0.04], pole: [0.3 * s, -0.1, -1], material: slate, jointMaterial: coral, end: makeHand(jaws, `arms.${side}`, cream, coral), gripPoint: [0, GRIP_Y, 0], gripAxis: [1, 0, 0] });+ const leg = (side: "left" | "right", s: number) => limb(nib, `legs.${side}`, { at: [0.1 * s, -0.02, 0], lengths: [0.23, 0.23], radius: [0.042, 0.038], rest: [0, -0.42, 0.02], pole: [0, 0, 1], material: slate, jointMaterial: coral, endMode: "level",+ end: () => { const f = new THREE.Mesh(new THREE.CapsuleGeometry(0.052, 0.09, 6, 18), coral); f.rotation.x = Math.PI / 2; f.position.set(0, -0.002, 0.035); f.scale.set(1.05, 1, 0.8); return f; } });+ // left is +x in Nib's own space (it faces +z), right is -x+ arm("left", 1); arm("right", -1); leg("left", 1); leg("right", -1);+ flag(nib, "blink", (_r, val) => eyes.forEach((e) => e.scale.set(1, Math.max(0.08, 1 - 0.92 * val), 1)));+ flag(nib, "antenna", (_r, val) => antenna.rotation.set(val, 0, 0));+ for (const n of ["arms.left", "arms.right"]) flag(nib, `jaws.${n.slice(5)}`, (_r, val) => jaws[n].forEach((h) => h.rotation.set(h.userData.side * 0.62 * val, 0, 0)));+ scene.add(nib.root);++ // ---- the crate and the lantern+ const crate = new THREE.Group(); crate.name = "crate"; crate.position.set(0.56, 0, -0.2);+ const wood = std("#c9935c", { roughness: 0.8 }), woodDark = std("#9a6a3e", { roughness: 0.85 });+ const box = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.34, 0.4), wood); box.position.y = 0.17; crate.add(box);+ for (const y of [0.012, 0.115, 0.225, 0.328]) { const b = new THREE.Mesh(new THREE.BoxGeometry(0.408, 0.022, 0.408), woodDark); b.position.y = y; crate.add(b); }+ crate.traverse((o) => { o.castShadow = o.receiveShadow = true; o.userData.part ??= "crate"; });+ scene.add(crate);++ const lantern = new THREE.Group(); lantern.name = "lantern";+ const iron = std("#3a4150", { roughness: 0.45, metalness: 0.5 }), glass = new THREE.MeshStandardMaterial({ color: "#ffe6b0", emissive: "#ffae45", emissiveIntensity: 1.25, roughness: 0.3 });+ const add = (m: THREE.Mesh, y: number, nm: string) => { m.position.y = y; m.userData.part = nm; m.castShadow = true; lantern.add(m); return m; };+ add(new THREE.Mesh(new THREE.CylinderGeometry(0.072, 0.076, 0.03, 28), iron), 0.015, "lantern.base");+ add(new THREE.Mesh(new THREE.CylinderGeometry(0.058, 0.058, 0.13, 28), glass), 0.095, "lantern.glass").castShadow = false;+ for (let k = 0; k < 4; k++) { const a = Math.PI / 4 + (k * Math.PI) / 2, p = add(new THREE.Mesh(new THREE.CylinderGeometry(0.007, 0.007, 0.13, 8), iron), 0.095, "lantern.post"); p.position.x = Math.cos(a) * 0.062; p.position.z = Math.sin(a) * 0.062; }+ add(new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.074, 0.024, 28), iron), 0.172, "lantern.lid");+ add(new THREE.Mesh(new THREE.ConeGeometry(0.056, 0.036, 28), iron), 0.202, "lantern.roof");+ // the bail: a wire arc from rim to rim with a wooden grip across its top. The grip is the handle+ const bail = new THREE.Group(); bail.userData.handlePart = true; lantern.add(bail);+ const arc = new THREE.Mesh(new THREE.TorusGeometry(0.074, 0.0055, 8, 32, Math.PI), iron); arc.position.y = 0.176; arc.userData.part = "lantern.bail"; arc.userData.handlePart = true; bail.add(arc);+ const gripM = new THREE.Mesh(new THREE.CylinderGeometry(0.012, 0.012, 0.07, 16), std("#6b4428", { roughness: 0.7 })); gripM.rotation.z = Math.PI / 2; gripM.position.y = 0.25; gripM.userData.part = "lantern.handle"; gripM.userData.handlePart = true; bail.add(gripM);+ handle(lantern, [-0.035, 0.25, 0], [0.035, 0.25, 0], 0.012);+ const flame = new THREE.PointLight("#ffb35c", 0.5, 3, 2); flame.position.y = 0.1; lantern.add(flame);+ scene.add(lantern);++ // ---- the set: a photo-studio sweep (floor curving up into a wall) turned to face the lens+ const prof: [number, number][] = []; // (z, y): floor from the front to the cove, a quarter circle, the wall+ for (let i = 0; i <= 12; i++) prof.push([8 - (i / 12) * 10, 0]);+ for (let i = 1; i <= 16; i++) { const a = (i / 16) * (Math.PI / 2); prof.push([-2 - Math.sin(a) * 2, 2 - Math.cos(a) * 2]); }+ for (let i = 1; i <= 6; i++) prof.push([-4, 2 + i]);+ const pos: number[] = [], idx: number[] = [], XS = [-12, -4, 4, 12];+ prof.forEach(([z, y]) => XS.forEach((x) => pos.push(x, y, z)));+ for (let i = 0; i < prof.length - 1; i++) for (let j = 0; j < XS.length - 1; j++) { const a = i * XS.length + j, b = a + 1, c = a + XS.length, d = c + 1; idx.push(a, c, b, b, c, d); }+ const sg = new THREE.BufferGeometry(); sg.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3)); sg.setIndex(idx); sg.computeVertexNormals();+ const sweep = new THREE.Mesh(sg, std("#efe6d8", { roughness: 0.95, side: THREE.DoubleSide })); sweep.receiveShadow = true; sweep.rotation.y = 0.5; sweep.position.set(-0.4, 0, 0.3);+ scene.add(sweep);++ // ---- light: a warm key with soft shadows, a cool sky, a cool rim from behind+ scene.add(new THREE.HemisphereLight("#e8efff", "#d6c6ae", 1.1));+ const fill = new THREE.DirectionalLight("#fff6ea", 0.75); fill.position.set(2.2, 1.6, 4.5); scene.add(fill);+ const key = new THREE.DirectionalLight("#fff0da", 2.5); key.castShadow = true; key.shadow.mapSize.set(2048, 2048); key.shadow.bias = -0.0004; key.shadow.normalBias = 0.02; key.shadow.radius = 5;+ const sc = key.shadow.camera as THREE.OrthographicCamera; sc.left = -2.4; sc.right = 2.4; sc.top = 2.4; sc.bottom = -2.4; sc.near = 0.5; sc.far = 14;+ key.target.position.set(-0.8, 0, 0.1); key.position.set(-0.8 - 1.6, 4.2, 0.1 + 3.2); scene.add(key, key.target);+ const rim = new THREE.DirectionalLight("#cfe0ff", 1.3); rim.position.set(-2.5, 2.6, -2.8); scene.add(rim);++ const cam = new THREE.PerspectiveCamera(30, W / H, 0.05, 60);+ return { scene, nib, crate, lantern, cam, jaws };+};+type Built = ReturnType<typeof build>;++// ---------------------------------------------------------------- the motion, from the frame alone+const distAt = (f: number) => {+ const D = STRIDE * CYCLES, f1 = 66, T = BEATS.stop - f1, v = D / (f1 + T / 2);+ if (f <= f1) return v * f;+ if (f < BEATS.stop) { const t = f - f1; return v * f1 + v * (t - (t * t) / (2 * T)); }+ return D;+};+const rootAt = (f: number, variant: Variant) => v3(STOP_X + (variant === "path" ? 0.18 : 0) - STRIDE * CYCLES + distAt(f), 0, 0);+const BLINKS = [36, 140, 183];+const blinkAt = (f: number) => { for (const b of BLINKS) if (f >= b && f < b + 4) return [0.6, 1, 1, 0.5][f - b]; return 0; };++/** Pose the whole scene for frame f (no rendering): what the draw and the checks both use. */+export const rigDemoFrame = (env: Env, f: number, variant: Variant = "clean") => {+ const B = memo(env, "threeRigDemo", build) as Built, { nib, lantern, cam } = B;+ resetChecks();+ const at = rootAt(f, variant), yaw = Math.PI / 2;++ // the walk: phase from distance, so planted feet never slide through the ease-out+ const wk = walkCycle(f, { distance: distAt(f), stride: STRIDE, bob: 0.022, lift: 0.07, sway: 0.012, armSwing: 1 });+ const S = BEATS;+ // body: walk lean that rocks through the stop, the wind-up and the reach, then straightens for the lift+ const reachP = anticipate(f, { at: S.reach, dur: S.approach - S.reach, lead: S.reach - S.windup, amount: 0.25 });+ const settle = followThrough(f, FPS, [{ at: S.stop, amp: 0.07, held: 1, freq: 1.4, damping: 0.32 }]);+ const lean = settle + 0.2 * Math.max(-0.25, reachP) * (1 - tween(f, S.lift, S.lifted)) + 0.02 * tween(f, S.lift, S.lifted);+ const giggle = f >= S.giggle ? 0.04 * Math.sin((2 * Math.PI * (f - S.giggle)) / 8) * (1 - seg(f, S.giggle, S.giggle + 22)) : 0;+ const lift = wk.bob - 0.05 * Math.max(0, reachP) * (1 - tween(f, S.lift, S.lifted)) + giggle * 0.4;+ const twist = f < S.stop ? wk.twist * 0.12 : -0.22 * tween(f, S.turn + 6, S.turn + 24);++ // feet: planted in the world from the walk; toes lift a little as a foot swings+ const bm = bodyMatrix(nib, { at, yaw });+ const feet: Record<string, LimbPose> = {};+ (["left", "right"] as const).forEach((side, i) => { const ft = wk.feet[i], s = side === "left" ? 1 : -1; feet[side] = { target: v3(0.1 * s, 0.052 + ft.lift, ft.fwd).applyMatrix4(bm.root), wrist: [-4.5 * ft.lift, 0] }; });++ // arms: counter-swing that dies into the stop and springs through it+ const mvA = 1 - 0.6 * seg(f, 66, S.stop);+ const swing = (i: number) => f < S.stop ? wk.arms[i] * mvA : walkCycle(S.stop, { distance: distAt(S.stop), stride: STRIDE }).arms[i] * 0.4 * spring(f, S.stop, FPS, 1.6, 0.3);+ const armSwing = (i: number): LimbPose => ({ offset: [0, 0.025 * Math.abs(swing(i)), 0.13 * swing(i)] });++ // the reach: rest > a point just short of the handle (jaws opening) > onto the handle > lift to show it+ const hb = lantern.userData.handle as { a: V3; b: V3 };+ const onCrate = () => { lantern.position.set(0.42, 0.34, -0.2); lantern.rotation.set(0, Math.PI / 2, 0); lantern.updateWorldMatrix(true, true); };+ onCrate();+ const bar = lantern.localToWorld(hb.a.clone().lerp(hb.b, 0.5)), axis = v3(0, 0, 1);+ const approachPt = bar.clone().add(v3(-0.08, 0.1, 0)), showPt = v3(STOP_X + 0.35, 0.95, -0.24);+ let carry: LimbPose = armSwing(0), jawsC = 0;+ if (f >= S.reach && f < S.lift) {+ if (f < S.approach) carry = { grip: { point: approachPt, axis }, weight: ease.inOutCubic(seg(f, S.reach, S.approach)) };+ else carry = { grip: { point: approachPt.clone().lerp(bar, ease.inOutSine(seg(f, S.approach, S.onBar))), axis } };+ jawsC = seg(f, S.reach + 4, S.approach) - seg(f, S.onBar, S.closed);+ } else if (f >= S.lift) {+ const u = ease.inOutCubic(seg(f, S.lift, S.lifted)), p = bar.clone().lerp(showPt, u); p.y += 0.06 * Math.sin(Math.PI * u);+ carry = { grip: { point: p, axis }, wrist: [WR * Math.min(1, 2 * u + seg(f, S.closed, S.lift)), 0] };+ }+ if (f >= S.reach - 6 && f < S.reach) carry = { offset: [0, 0.03 * -reachP, -0.08 * -reachP / 0.25] }; // the wind-up: the hand draws back first+ // the free hand (the lens side) balances during the reach, then waves at the lens+ let free: LimbPose = armSwing(1), jawsF = 0;+ if (f >= S.windup && f < S.wave) { const b = Math.max(0, reachP) * (1 - seg(f, S.lift, S.lifted)); free = { offset: [-0.06 * b, 0.05 * b, -0.1 * b] }; }+ if (f >= S.wave) { const w = ease.inOutCubic(seg(f, S.wave, S.wave + 10)), osc = Math.sin((2 * Math.PI * (f - S.wave - 10)) / 11) * seg(f, S.wave + 8, S.wave + 14); free = { offset: [-0.07 * w - 0.045 * osc, 0.62 * w, 0.06 * w], wrist: [0, -0.35 * osc] }; jawsF = 0.6 * w; }++ // the head: ahead, then the lantern, then the lens+ const ahead = at.clone().add(v3(1.6, 0.55, 0));+ const lanternC = v3(); // the lantern, wherever it is this frame (set after the grip below, read by the look)+ const camPos = cameraAt(f, B);+ const lookFor = (lc: V3) => { const t1 = ease.inOutSine(seg(f, 44, 64)), t2 = ease.inOutCubic(seg(f, S.turn + 4, S.turn + 18)); return ahead.clone().lerp(lc, t1).lerp(camPos, t2); };++ // antenna: trails while walking, swings through at the stop, the lift and the giggle+ const ant = -0.2 * (f < S.stop ? 1 : 0) * Math.min(1, f / 6) + 0.05 * Math.sin(4 * Math.PI * wk.phase) * (f < S.stop ? 1 : 0)+ + followThrough(f, FPS, [{ at: S.stop, amp: -0.2, freq: 1.8, damping: 0.22 }, { at: S.lifted, amp: 0.14, freq: 1.8, damping: 0.25 }, { at: S.giggle + 4, amp: -0.12, freq: 2.2, damping: 0.25 }]);++ // pose once with the look on the lantern's resting place, grip, then re-aim the look (cheap: head only)+ const p = { at, yaw, lift, lean, twist, squash: giggle, look: { target: lookFor(bar) }, arms: { left: carry, right: free }, legs: feet,+ flags: { blink: blinkAt(f), antenna: ant, "jaws.left": jawsC, "jaws.right": jawsF } };+ pose(nib, p);++ // the lantern: on the crate until the jaws close on it, then hanging from them, lagging and swinging+ const hand = nib.limbs["arms.left"] as Limb;+ if (f >= S.closed) {+ const lag = f < S.lifted ? LAG * ease.inOutSine(seg(f, S.lift, S.lift + 9)) : LAG * spring(f, S.lifted, FPS, 1.3, 0.18);+ grip(hand, lantern, 0.5, { hang: true, swing: lag });+ if (variant === "offset") { const back = v3(0, -0.05, 0).transformDirection(hand.end.matrixWorld).multiplyScalar(0.05); lantern.position.add(back); lantern.updateWorldMatrix(false, true); }+ }+ lantern.getWorldPosition(lanternC).add(v3(0, 0.12, 0));+ if (f >= S.lift) pose(nib, { ...p, look: { target: lookFor(lanternC) } });++ // the camera follows Nib in, then pushes in for the look+ cam.position.copy(camPos); cam.lookAt(camTarget(f)); cam.updateMatrixWorld();++ // what this frame must keep true (checks3d): nothing through anything, the grip held and seen+ registerRig("nib", nib); registerRig("crate", B.crate); registerRig("lantern", lantern);+ if (f >= S.approach - 2) registerGrip(nib, hand, lantern, { closing: f < S.closed });+ if (f >= S.approach && f < S.lifted + 12) registerSize(hand.end, 40);+ registerPath({ name: "nib", at: (g) => rootAt(g, variant), from: f, to: f, radius: 0.22, height: 1.4 }, [{ name: "crate", box: B.crate }]);+ return { ...B, hand };+};+// the camera keeps Nib a little left of centre while walking, then settles on the reach and pushes in+const camTarget = (f: number) => v3(lerp(rootAt(f, "clean").x + 0.3, 0.2, tween(f, 64, 118)), lerp(0.72, 0.68, tween(f, 70, 110)) + 0.04 * tween(f, 120, 170), lerp(0.05, -0.02, tween(f, 64, 118)));+// a side-on three-quarter for the walk, an arc round toward Nib's front for the reach (so its face reads+// while it looks at the lantern on its far side), then a push in for the look and the wave+const CAM_A = v3(1.45, 0.5, 3.3), CAM_B = v3(3.1, 0.6, 2.3), CAM_C = v3(2.85, 0.5, 2.45);+const cameraAt = (f: number, _b?: Built) => { const t = camTarget(f), a = ease.inOutSine(seg(f, 46, 134)), b = ease.inOutCubic(seg(f, 128, 176)); return t.add(CAM_A.clone().lerp(CAM_B, a).lerp(CAM_C, b)); };++// ---------------------------------------------------------------- the film+const shotFor = (variant: Variant) => (ctx: Ctx, f: number, env: Env) => {+ const s = rigDemoFrame(env, f, variant);+ if (checking()) runChecks(f, s.cam, env); else resetChecks();+ draw3d(ctx, env, s.scene, s.cam, { clear: "#e9e1d4", shadows: true });+};+const filmOf = (title: string, variant: Variant): Film => ({+ meta: { title, W, H, fps: FPS, bpm: 120, durationFrames: N, kind: "story", poster: 150 },+ assets: { images: {} },+ shots: [{ id: "nib", start: 0, end: N, draw: shotFor(variant) }],+});+export const threeRigDemo = filmOf("three rig demo", "clean");+/** TEST FIXTURE, not a film: the demo with the lantern shifted through Nib's jaws. The gate's 3D CHECKS must FAIL it. */+export const fixtureRigBrokenGrip = filmOf("fixture: broken grip", "offset");diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeTypeDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeTypeDemo.tsnew file mode 100644index 0000000..49af520--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/threeTypeDemo.ts@@ -0,0 +1,166 @@+// THREE TYPE DEMO. Extruded type as motion graphics, eight seconds, three looks and two+// transitions: "anidoodle" drops onto a warm studio cove (satin, studio light, contact shadows),+// an ink-blot wipe opens on "now in 3D" in toon shading with an ink outline, and the camera flies+// through it onto the end card (the wordmark and the repo URL as flat type in 3D space). Grain and+// a vignette finish every frame. It exercises type3d.ts, look.ts and transitions.ts together.+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import * as THREE from "three";+import { draw3d, memo, probe3d } from "../three-core/stage";+import { checking, registerSize, runChecks } from "../three-core/checks3d";+import { ease, lerp, seg, spring, tween } from "../three-core/time";+import { defaultFont, text3d, textPlane, type Letter } from "../three-core/type3d";+import { contactShadow, grain, matte, outline, satin, studio, toon, vignette } from "../three-core/look";+import { noiseWipe, transition, zoomThrough } from "../three-core/transitions";++const W = 1920, H = 1080, FPS = 24, N = 192;+// cuts on the 12-frame beat (120 bpm at 24 fps)+const WIPE = [72, 96] as const, ZOOM = [144, 168] as const;++// A photographer's cove: a floor that curves up into the back wall, so there is no horizon line+// and the light falls off smoothly behind the type (the "infinite white" of a product shot).+const cove = (color: THREE.ColorRepresentation, mat?: THREE.Material) => {+ const geo = new THREE.PlaneGeometry(40, 1, 1, 96), pos = geo.getAttribute("position");+ const floorLen = 40, r = 4, wall = 16, total = floorLen + (Math.PI / 2) * r + wall;+ for (let i = 0; i < pos.count; i++) {+ const s = (pos.getY(i) + 0.5) * total; let y: number, z: number;+ if (s < floorLen) { y = 0; z = 30 - s; }+ else if (s < floorLen + (Math.PI / 2) * r) { const a = (s - floorLen) / r; y = r - r * Math.cos(a); z = 30 - floorLen - r * Math.sin(a); }+ else { y = r + (s - floorLen - (Math.PI / 2) * r); z = 30 - floorLen - r; }+ pos.setXYZ(i, pos.getX(i), y, z);+ }+ geo.computeVertexNormals();+ return new THREE.Mesh(geo, mat ?? matte(color));+};++const font = () => defaultFont();+const SIZE = 1.25, BASE = -0.3525 * SIZE; // Poppins caps are 0.705 em; type3d centres them on y 0++// ---------------------------------------------------------------- scene A: "anidoodle" drops in+const buildA = (env: Env) => {+ const scene = new THREE.Scene();+ const floor = cove("#f6ecdd"); floor.position.y = BASE; scene.add(floor);+ const word = text3d(env, font(), "anidoodle", { size: SIZE, depth: 0.32, bevel: 0.022, letterSpacing: 0.01, material: satin("#f0642f") });+ scene.add(word);+ const shadows = word.userData.letters.map((l) => { const s = contactShadow(0.95 * SIZE * 0.62, 0.6, { aspect: 1.4, color: "#5a3426" }); s.position.set(l.userData.home.x, BASE + 0.002, 0); scene.add(s); return s; });+ scene.add(studio({ at: { x: 0, y: 0, z: 0 } }).group);+ const cam = new THREE.PerspectiveCamera(30, W / H, 0.1, 100);+ return { scene, letters: word.userData.letters, shadows, cam };+};+// a letter dropped at frame `at`: falls 2.6 units in 11 frames, lands with a squash that springs back+const drop = (l: Letter, f: number, at: number, i: number, sh: THREE.Mesh) => {+ const p = seg(f, at, at + 11), h = l.userData.home, fall = 2.6 * (1 - p * p), land = spring(f, at + 11, FPS, 2.6, 0.3);+ // a hop that ripples along the word once everything has landed: the type stays alive+ const hop = Math.max(0, Math.sin(Math.PI * seg(f, 46 + i * 2.2, 58 + i * 2.2))) * 0.32;+ l.visible = f >= at - 1;+ l.position.set(h.x, h.y + fall + hop, h.z);+ l.rotation.set(0, 0, (1 - ease.outCubic(p)) * (i % 2 ? 0.5 : -0.45));+ const sq = f >= at + 11 ? land * 0.22 : 0;+ // squash about the letter's foot, not its centre: shift down by what the scale removes+ l.scale.set(1 + sq * 0.5, 1 - sq, 1 + sq * 0.5);+ l.position.y -= (sq * SIZE * 0.705) / 2;+ const up = fall + hop, near = 1 - Math.min(1, up / 2.6);+ sh.visible = l.visible;+ sh.scale.setScalar(lerp(1.7, 1, near));+ (sh.material as THREE.MeshBasicMaterial).opacity = lerp(0.12, 1, near * near);+};+const sceneA = (ctx: Ctx, env: Env, f: number) => {+ const { scene, letters, shadows, cam } = memo(env, "typeDemo:A", buildA);+ letters.forEach((l, i) => drop(l, f, -6 + i * 3.2, i, shadows[i]));+ const t = tween(f, 0, 96, ease.outCubic);+ cam.position.set(lerp(-0.7, 0.5, t), lerp(2.9, 2.2, t), lerp(12.6, 11.2, t)); cam.lookAt(0, -0.05, 0);+ draw3d(ctx, env, scene, cam, { clear: "#efe3d2" }); if (f >= 48) { probe3d(ctx, env, letters[0].parent!, cam, "anidoodle"); sizeCheck(f, letters[0].parent!, cam, env); } /* the letters drop in from above the frame on purpose; the word must read whole once it has landed */+};++// what the type must keep true (checks3d, gate check 5): the word, once it has landed, is big enough to read+const sizeCheck = (f: number, word: THREE.Object3D, cam: THREE.Camera, env: Env) => { if (!checking()) return; registerSize(word, 60); runChecks(f, cam, env); };++// ---------------------------------------------------------------- scene B: "now in 3D", toon and ink+const buildB = (env: Env) => {+ const scene = new THREE.Scene();+ const floor = cove("#3a52c4"); floor.position.y = BASE; scene.add(floor);+ const cream = toon("#fff3dc", 3), yellow = toon("#ffd23f", 3);+ const word = text3d(env, font(), "now in 3D", { size: SIZE, depth: 0.42, bevel: 0.015, letterSpacing: 0.02, material: [cream, cream, cream, cream, cream, yellow, yellow] });+ scene.add(word);+ // ink outline 4.5 px at 1080 on every letter, whatever the camera distance (screen width, lesson 27)+ word.userData.letters.forEach((l) => outline(l, 4.5, "#14112a", { screen: true, frameH: H }));+ const shadows = word.userData.letters.map((l) => { const s = contactShadow(SIZE * 0.62, 0.5, { aspect: 1.5, color: "#0e1440", opacity: 0.6 }); s.position.set(l.userData.home.x, BASE + 0.002, 0); scene.add(s); return s; });+ scene.add(studio({ intensity: 1.1 }).group);+ const cam = new THREE.PerspectiveCamera(30, W / H, 0.1, 100);+ return { scene, word, letters: word.userData.letters, shadows, cam };+};+const sceneB = (ctx: Ctx, env: Env, f: number) => {+ const { scene, word, letters, shadows, cam } = memo(env, "typeDemo:B", buildB);+ letters.forEach((l, i) => {+ // pop up from the floor: scale from nothing with an overshoot, staggered two frames a letter+ const at = 2 + i * 2.5, p = seg(f, at, at + 12), s = ease.outBack(p), h = l.userData.home;+ l.visible = p > 0;+ l.scale.setScalar(Math.max(0.0001, s));+ l.position.set(h.x, h.y - (1 - s) * SIZE * 0.35, h.z);+ // "3D" spins round once on its own axis to show it has a back+ const spin = i >= 5 ? tween(f, 40 + (i - 5) * 3, 62 + (i - 5) * 3, ease.inOutCubic) * Math.PI * 2 : 0;+ l.rotation.set(0, spin + (1 - ease.outCubic(p)) * -0.9, 0);+ shadows[i].visible = l.visible; shadows[i].scale.setScalar(Math.max(0.0001, s));+ });+ word.rotation.y = lerp(-0.22, 0.16, tween(f, 0, 96, ease.inOutSine));+ const t = tween(f, 0, 96, ease.inOutSine);+ cam.position.set(lerp(0.8, -0.4, t), lerp(2.8, 2.1, t), lerp(12.2, 11.0, t)); cam.lookAt(0, -0.1, 0);+ draw3d(ctx, env, scene, cam, { clear: "#2d3f8f" }); probe3d(ctx, env, word, cam, "now in 3D");+ if (f >= 2 + (letters.length - 1) * 2.5 + 12) sizeCheck(f, word, cam, env); // every letter has popped up+};++// ---------------------------------------------------------------- scene C: the end card+const buildC = (env: Env) => {+ const scene = new THREE.Scene();+ const base = -0.3525 * 1.0;+ const floor = cove("#efe3d2"); floor.position.y = base; scene.add(floor);+ const word = text3d(env, font(), "anidoodle", { size: 1.0, depth: 0.3, bevel: 0.022, letterSpacing: 0.01, material: satin("#f0642f") });+ word.position.y = 0.42; scene.add(word);+ const url = textPlane(env, "github.com/alexgreensh/anidoodle", { size: 0.16, color: "#3a2b2a", letterSpacing: 0.01 });+ url.position.set(0, -0.16, 1.0); scene.add(url);+ const made = textPlane(env, "3D type, drawn in code", { size: 0.17, color: "#8a5a3c" });+ made.position.set(0, 1.3, 0.3); scene.add(made);+ const sh = contactShadow(6.4, 0.75, { aspect: 1, color: "#5a3426", opacity: 0.35 }); sh.scale.set(1, 0.3, 1); sh.position.set(0, base + 0.002, 0); scene.add(sh);+ scene.add(studio().group);+ const cam = new THREE.PerspectiveCamera(30, W / H, 0.1, 100);+ return { scene, letters: word.userData.letters, url, made, cam };+};+const sceneC = (ctx: Ctx, env: Env, f: number) => {+ const { scene, letters, url, made, cam } = memo(env, "typeDemo:C", buildC);+ // a slow wave through the wordmark: each letter floats a little, one after the other+ letters.forEach((l, i) => { const h = l.userData.home; l.position.set(h.x, h.y + 0.06 * Math.sin((f / FPS) * Math.PI * 1.2 - i * 0.55), h.z); l.rotation.set(0, 0.08 * Math.sin((f / FPS) * Math.PI * 0.8 - i * 0.4), 0); });+ const pu = tween(f, 6, 22, ease.outCubic), pm = tween(f, 12, 28, ease.outCubic);+ (url.material as THREE.MeshBasicMaterial).opacity = pu; url.position.y = -0.16 - (1 - pu) * 0.1;+ (made.material as THREE.MeshBasicMaterial).opacity = pm; made.position.y = 1.3 + (1 - pm) * 0.12;+ const t = tween(f, 0, 48, ease.outCubic);+ cam.position.set(0, lerp(0.7, 0.55, t), lerp(9.2, 8.6, t)); cam.lookAt(0, 0.2, 0);+ draw3d(ctx, env, scene, cam, { clear: "#efe3d2" }); probe3d(ctx, env, letters[0].parent!, cam, "anidoodle"); sizeCheck(f, letters[0].parent!, cam, env);+};++// ---------------------------------------------------------------- finish and shots+const finish = (ctx: Ctx, env: Env, f: number, dark = false) => { vignette(ctx, env, dark ? 0.32 : 0.22, dark ? "#0b0f2a" : "#3a2420"); grain(ctx, env, f); };+const shotA = (ctx: Ctx, f: number, env: Env) => { sceneA(ctx, env, f); finish(ctx, env, f); };+const shotWipe = (ctx: Ctx, f: number, env: Env) => {+ const F = WIPE[0] + f;+ transition(ctx, env, seg(F, WIPE[0], WIPE[1]), noiseWipe(11, { scale: 420, ink: "#14112a" }), (c, e) => sceneA(c, e, F), (c, e) => sceneB(c, e, F - WIPE[0]));+ finish(ctx, env, F, seg(F, WIPE[0], WIPE[1]) > 0.5);+};+const shotB = (ctx: Ctx, f: number, env: Env) => { const F = WIPE[1] + f; sceneB(ctx, env, F - WIPE[0]); finish(ctx, env, F, true); };+const shotZoom = (ctx: Ctx, f: number, env: Env) => {+ const F = ZOOM[0] + f;+ transition(ctx, env, seg(F, ZOOM[0], ZOOM[1]), zoomThrough(), (c, e) => sceneB(c, e, F - WIPE[0]), (c, e) => sceneC(c, e, F - ZOOM[0]));+ finish(ctx, env, F, seg(F, ZOOM[0], ZOOM[1]) < 0.5);+};+const shotC = (ctx: Ctx, f: number, env: Env) => { const F = ZOOM[1] + f; sceneC(ctx, env, F - ZOOM[0]); finish(ctx, env, F); };++export const threeTypeDemo: Film = {+ meta: { title: "three type demo", W, H, fps: FPS, bpm: 120, durationFrames: N, kind: "explainer", poster: 48 },+ assets: { images: {} },+ shots: [+ { id: "drop", start: 0, end: WIPE[0], draw: shotA },+ { id: "inkWipe", start: WIPE[0], end: WIPE[1], draw: shotWipe },+ { id: "toon", start: WIPE[1], end: ZOOM[0], draw: shotB },+ { id: "zoomThrough", start: ZOOM[0], end: ZOOM[1], draw: shotZoom },+ { id: "endCard", start: ZOOM[1], end: N, draw: shotC },+ ],+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/timeRemap.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/timeRemap.tsindex 54e8d8c..d54a4a8 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/timeRemap.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/timeRemap.ts@@ -26,8 +26,14 @@// filmFrameOf(sceneFrame). A slowed world under a score at its own tempo is the effect.// Every function here is arithmetic over (frame, keys): no clock, no state, any order.+// WHERE A KEY SITS, IN NAMED UNITS. `f` is a film frame. `film: s` is film time in seconds and `scene:+// s` is SCENE time in seconds (the key lands on the first film frame that shows that scene moment);+// both need timeRemap(keys, { fps }). Exactly one of the three, never a bare number: a brand launch+// logo keys were typed in scene seconds where film seconds were meant, and nothing complained.export type TimeKey = {- f: number; // the film frame this speed starts from (whole, increasing)+ f?: number; // the film frame this speed starts from (whole, increasing)+ film?: number; // or: film time in seconds (needs fps)+ scene?: number; // or: scene time in seconds, resolved through the keys before this one (needs fps)speed: number; // scene frames per film frame from here on: 1 real time, 0.25 slow motion, 0 a freeze, 2 fast (0 or at least MIN_SPEED)ramp?: number; // frames over which the speed glides from the old value to this one (default 0, a hard change)curve?: "smooth" | "linear"; // the glide's shape: smoothstep (default; no kick at either end) or a straight line@@ -56,7 +62,8 @@ export const MIN_SPEED = 0.01;type Seg = { f: number; from: number; to: number; ramp: number; curve: (typeof CURVES)["smooth"]; t0: number };-export const timeRemap = (keys: readonly TimeKey[]): TimeRemap => {+export const timeRemap = (input: readonly TimeKey[], opts: { fps?: number } = {}): TimeRemap => {+ const keys = resolveKeys(input, opts.fps);let last = -1, prevSpeed = 1;const segs: Seg[] = [], freezes: Freeze[] = [];// the frames first, all of them, so a later check never reports a symptom of keys out of order@@ -110,3 +117,24 @@ const sceneAt = (s: Seg, f: number): number => {if (s.ramp > 0 && x < s.ramp) return s.t0 + s.ramp * (s.from * (x / s.ramp) + (s.to - s.from) * s.curve.area(x / s.ramp));return s.t0 + s.ramp * (s.from + (s.to - s.from) * s.curve.area(1)) + s.to * (x - s.ramp);};++// Every key's place in film frames, from whichever unit it names. A scene-time key is found on the+// remap built from the keys before it, so "the logo starts at scene 30 s" means what it says even+// after a slowdown earlier in the film.+type Resolved = TimeKey & { f: number };+const resolveKeys = (keys: readonly TimeKey[], fps?: number): Resolved[] => {+ const out: Resolved[] = [];+ for (const [i, k] of keys.entries()) {+ if (typeof k !== "object" || k === null) throw new Error(`timeRemap: key ${i} is ${JSON.stringify(k)}; a key is an object that names its unit: { f: frame }, { film: seconds } or { scene: seconds }, plus speed`);+ const named = (["f", "film", "scene"] as const).filter((u) => k[u] !== undefined);+ if (named.length !== 1) throw new Error(`timeRemap: key ${i} ${named.length ? `names ${named.join(" and ")}` : "names no time"}; give exactly one of f (film frame), film (film seconds) or scene (scene seconds)`);+ const u = named[0], v = k[u]!;+ if (!Number.isFinite(v)) throw new Error(`timeRemap: key ${i} has ${u} = ${v}; it must be a number`);+ if (u === "f") { out.push({ ...k, f: v }); continue; }+ if (!(fps && fps > 0)) throw new Error(`timeRemap: key ${i} is in ${u} seconds; pass timeRemap(keys, { fps }) so seconds can become frames`);+ if (u === "film") { out.push({ ...k, f: Math.round(v * fps) }); continue; }+ const before = timeRemap(out.map(({ f, speed, ramp, curve, keepsMoving }) => ({ f, speed, ramp, curve, keepsMoving })));+ out.push({ ...k, f: before.filmFrameOf(v * fps) });+ }+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/voice.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/voice.tsnew file mode 100644index 0000000..4440ba3--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/voice.ts@@ -0,0 +1,121 @@+// VOICE. Narration in the film's own mix. The takes arrive baked into the film's bundle+// (tools/narrate.mjs bake writes a module: the timing plus each line as 16-bit PCM in base64), so the+// page never loads a file or touches the network, and a code-built score and the voice are mixed in+// the same place the rest of the film's sound is: Film.audio(sampleRate).+//+// narrationAudio({ voice, music, ... }) a Film.audio: score ducked under the voice, the voice on its frames, one delivery master+// mixNarration(music, voice, sr, opts) the same mix as plain arrays, with the duck curve and the numbers (tests, reports)+// duckEnvelope(voice, sr, opts) the music's gain under speech: -9 dB, 40 ms down, 450 ms back up (the ghost film's sidechain)+// voiceTrack(baked, sr, frames) every line's take placed at its start frame, as one mono track+// syncMarks(timing) a verify-export sync marker on each line's first word+//+// The ducking dips BEFORE a line starts (a look-ahead the length of the attack), so the first syllable+// never lands on full-level music. Ramps are linear in dB, so the curve is exactly what the numbers say.+import type { FilmAudio } from "./film";+import type { VoiceTiming } from "./subtitles";+import { Biquad, db } from "./music/dsp";+import { deliver, type Delivered, type MasterMode } from "./music/delivery";+import { loudness } from "./music/meter";++/** What `narrate.mjs bake` writes: the timing and each line's take (16-bit little-endian mono PCM, base64). */+export type BakedVoice = { timing: VoiceTiming; sampleRate: number; pcm: Record<string, string> };+export type DuckOpts = { depthDb?: number; attackMs?: number; releaseMs?: number; holdMs?: number; thresholdDb?: number };+export type NarrationOpts = DuckOpts & { musicDb?: number; voiceDb?: number; master?: MasterMode; ceilingDb?: number };+type Stereo = [Float32Array, Float32Array];++/** base64 16-bit little-endian PCM -> Float32 in [-1, 1). */+export const decodePcm16 = (b64: string) => {+ const s = atob(b64), n = s.length >> 1, out = new Float32Array(n);+ for (let i = 0; i < n; i++) { let v = s.charCodeAt(2 * i) | (s.charCodeAt(2 * i + 1) << 8); if (v >= 32768) v -= 65536; out[i] = v / 32768; }+ return out;+};+/** Resample by cubic (Catmull-Rom) interpolation; a low-pass first when going down, so nothing folds back. */+export const resample = (x: Float32Array, from: number, to: number) => {+ if (from === to) return x;+ const src = Float32Array.from(x);+ if (to < from) for (const q of [0.5412, 1.3066]) Biquad.make(from, "lp", to * 0.45, q).run(src);+ const n = Math.round((x.length * to) / from), out = new Float32Array(n), at = (i: number) => src[Math.max(0, Math.min(src.length - 1, i))];+ for (let i = 0; i < n; i++) {+ const p = (i * from) / to, j = Math.floor(p), f = p - j, y0 = at(j - 1), y1 = at(j), y2 = at(j + 1), y3 = at(j + 2);+ out[i] = y1 + 0.5 * f * (y2 - y0 + f * (2 * y0 - 5 * y1 + 4 * y2 - y3 + f * (3 * (y1 - y2) + y3 - y0)));+ }+ return out;+};++// Decoded takes, keyed on the take's own base64 text and then on (source rate, target rate). Keying on the+// exact text means two voices that share a line id and a take length can never be served each other's take.+const decoded = new Map<string, Map<string, Float32Array>>();+/** Every line's take on one mono track of `frames` film frames, each starting exactly on its start frame. */+export const voiceTrack = (v: BakedVoice, sr: number, frames = v.timing.totalFrames) => {+ const fps = v.timing.fps, out = new Float32Array(Math.round((frames / fps) * sr));+ for (const ln of v.timing.lines) {+ const b64 = v.pcm[ln.id]; if (!b64) throw new Error(`voice: no take for line '${ln.id}' (re-run narrate.mjs bake)`);+ let rates = decoded.get(b64); if (!rates) { rates = new Map(); decoded.set(b64, rates); }+ const key = `${v.sampleRate}>${sr}`;+ let x = rates.get(key); if (!x) { x = resample(decodePcm16(b64), v.sampleRate, sr); rates.set(key, x); }+ const at = Math.round((ln.start / fps) * sr);+ for (let i = 0; i < x.length && at + i < out.length; i++) out[at + i] += x[i];+ }+ return out;+};++/**+ * The music's gain (linear, one value per sample) under a voice track: depthDb while the voice speaks+ * (RMS over 5 ms above thresholdDb, held holdMs across the small gaps between words), reached in+ * attackMs and given back over releaseMs, both as straight lines in dB. The dip starts attackMs+ * before the voice, so speech never starts over full-level music.+ */+export const duckEnvelope = (voice: Float32Array, sr: number, o: DuckOpts = {}) => {+ const depth = o.depthDb ?? -9, att = Math.max(1, ((o.attackMs ?? 40) / 1000) * sr), rel = Math.max(1, ((o.releaseMs ?? 450) / 1000) * sr);+ const hold = Math.round(((o.holdMs ?? 120) / 1000) * sr), thr = db(o.thresholdDb ?? -42), hop = Math.max(1, Math.round(0.005 * sr)), n = voice.length;+ const speaking = new Uint8Array(n);+ let lastOn = -Infinity;+ for (let i = 0; i < n; i += hop) {+ let s = 0; const e = Math.min(n, i + hop); for (let k = i; k < e; k++) s += voice[k] * voice[k];+ const on = Math.sqrt(s / (e - i)) > thr; if (on) lastOn = e;+ if (on || i < lastOn + hold) for (let k = i; k < e; k++) speaking[k] = 1;+ }+ // look ahead by the attack: the target falls `att` samples before the voice does+ const ahead = Math.round(att), target = new Float32Array(n);+ for (let i = 0; i < n; i++) target[i] = speaking[Math.min(n - 1, i + ahead)] || speaking[i] ? depth : 0;+ const g = new Float32Array(n), down = -depth / att, up = -depth / rel;+ let cur = 0;+ for (let i = 0; i < n; i++) { const t = target[i]; cur = t < cur ? Math.max(t, cur - down) : Math.min(t, cur + up); g[i] = db(cur); }+ return g;+};++/**+ * Score + voice -> one delivered stereo mix. music may be null (a voice-only piece). The score is set+ * musicDb under its own level, ducked under the voice, the voice laid in the middle, and the whole mix+ * goes through the delivery master (-16 LUFS gentle, -1 dBTP ceiling) that verify-export --delivery accepts.+ */+export const mixNarration = (music: Stereo | null, voice: Float32Array, sr: number, o: NarrationOpts = {}) => {+ const n = voice.length, duck = duckEnvelope(voice, sr, o), mg = db(o.musicDb ?? -6), vg = db(o.voiceDb ?? 0);+ const L = new Float32Array(n), R = new Float32Array(n), mL = new Float32Array(n), mR = new Float32Array(n);+ if (music) for (let i = 0; i < n && i < music[0].length; i++) { mL[i] = music[0][i] * mg * duck[i]; mR[i] = music[1][i] * mg * duck[i]; }+ for (let i = 0; i < n; i++) { const v = voice[i] * vg; L[i] = mL[i] + v; R[i] = mR[i] + v; }+ // speech over music, measured where the voice speaks, before the master (the master moves both alike)+ const margin = speechOverMusic(voice, vg, [mL, mR], duck, sr);+ const delivered: Delivered = deliver(L, R, sr, o.master ?? "gentle", { ceilingDb: (o.ceilingDb ?? -1) - 0.3 });+ const fade = Math.min(n, Math.round(0.015 * sr)); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }+ return { L, R, duck, delivered, speechOverMusicDb: margin };+};+// K-weighted loudness of the voice and of the ducked music over the samples where the duck is fully down+const speechOverMusic = (voice: Float32Array, vg: number, music: Stereo, duck: Float32Array, sr: number) => {+ let lo = 1; for (let i = 0; i < duck.length; i++) if (duck[i] < lo) lo = duck[i];+ const floor = lo * 1.01, ix: number[] = []; for (let i = 0; i < duck.length; i++) if (duck[i] <= floor) ix.push(i);+ if (ix.length < sr * 0.4) return NaN;+ const v = new Float32Array(ix.length), a = new Float32Array(ix.length), b = new Float32Array(ix.length);+ ix.forEach((k, j) => { v[j] = voice[k] * vg; a[j] = music[0][k]; b[j] = music[1][k]; });+ return loudness([v, v], sr).integrated - loudness([a, b], sr).integrated;+};++/** A Film.audio with narration: `music` is the film's score (filmAudio(piece, s) keeps its .scores for the hosts). */+export const narrationAudio = (p: { voice: BakedVoice; music?: FilmAudio | ((sr: number) => Stereo) | null; frames?: number } & NarrationOpts): FilmAudio => {+ const frames = p.frames ?? p.voice.timing.totalFrames;+ const fn = (sr: number): Stereo => { const m = mixNarration(p.music ? p.music(sr) : null, voiceTrack(p.voice, sr, frames), sr, p); return [m.L, m.R]; };+ return Object.assign(fn, { scores: (p.music as FilmAudio | undefined)?.scores });+};++/** One verify-export sync marker per line, on its first word (the onset check then measures the voice's attack). */+export const syncMarks = (t: VoiceTiming) => t.lines.map((l) => ({ frame: l.words[0]?.from ?? l.start, label: `voice ${l.id}` }));diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/world.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/world.tsnew file mode 100644index 0000000..4c9b62c--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/world.ts@@ -0,0 +1,99 @@+// ONE WORLD. The default architecture for a motion-graphics film: every beat is a REGION placed on+// one canvas in world coordinates, and a single camera travels between them. Nothing is rebuilt per+// scene, so nothing can cut like a slide. This is the fix for "DUDE YOUR VIDEO IS A LITERAL SLIDE+// DECK" on a brand launch film: it cut from screen to screen instead of being one moving world.+//+// const w = world({ W: 1920, H: 1080, regions: [+// { id: "chat", rect: [0, 0, 1600, 900] },+// { id: "crowd", rect: [1900, 200, 2400, 1350] },+// ], stops: [+// { f: 0, at: "chat", hold: 90 },+// { f: 150, at: "crowd", hold: 60 }, // the camera travels chat -> crowd over frames 90..150+// ], alive: { amp: 3, seed: 7 } });+// w.begin(ctx, env, f); // the camera's transform: draw in world units now+// w.region(ctx, "chat", () => drawChat(ctx)); // clipped to its own rect by default (no leaking edges)+// w.depth(ctx, env, f, 0.33, () => frieze(ctx)); // a layer of brand shapes at a third of camera speed+// w.end(ctx);+//+// CRAFT, and why it works this way:+// - REGIONS ARE THE STORYBOARD. A row of the board is a place in the world plus the camera move into+// it, so a board with two rows and no move between them cannot be built here.+// - A STOP FRAMES A REGION. Its zoom fits the region's rect inside the frame with `pad` around it, so a+// region can be any size and the camera works out the dolly. Several regions may share a stop.+// - REGIONS CLIP BY DEFAULT. A speaker's pink panel edge leaked into the next question on a brand launch film;+// a region draws only inside its own rect unless it says clip: false.+// - THE CAMERA BREATHES. `alive` adds a slow handheld drift in screen px (never per-frame noise): a parked+// camera reads as a slide even when the world is one.+// - ONE LAYOUT PER SHAPE. `regions` may be a function of the frame shape, so a 9:16 cut re-composes the+// same world (a chat card that fills the phone) instead of cropping it.+// Every function is pure in the frame number; the camera is camera.ts's, so seams.ts's numbers apply.+import { Camera, heroScale, type Cam, type CamKey, type EaseName } from "./camera";+import { fractal, type Ctx, type Env, type P } from "./core";++export type Rect = [x: number, y: number, w: number, h: number];+export type Region = { id: string; rect: Rect; clip?: boolean };+export type Stop = { f: number; at: string | { look: P; zoom: number }; hold?: number; pad?: number; ease?: EaseName };+export type Shape = { W: number; H: number; name?: string };+export type WorldSpec = { W: number; H: number; regions: Region[] | ((shape: Shape) => Region[]); stops: Stop[]; alive?: { amp: number; seed: number; freq?: number }; shape?: string };++/** The zoom that fits rect inside a W x H frame with `pad` (a share of the rect) around it. */+export const fitZoom = (rect: Rect, W: number, H: number, pad = 0.08) => Math.min(W / (rect[2] * (1 + 2 * pad)), H / (rect[3] * (1 + 2 * pad)));+export const centreOf = (r: Rect): P => [r[0] + r[2] / 2, r[1] + r[3] / 2];+/** The fewest frames a camera move of `distPx` screen px may take so its peak stays under `maxPxPerFrame` (an in-out cubic peaks at 3x its mean). Use with temperament(...).pxPerFrame(W, fps). */+export const minTravel = (distPx: number, maxPxPerFrame: number) => { if (!(maxPxPerFrame > 0)) throw new Error(`minTravel: the speed limit must be above 0 (got ${maxPxPerFrame})`); return Math.max(2, Math.ceil((3 * Math.abs(distPx)) / maxPxPerFrame)); };++export const world = (spec: WorldSpec) => {+ const { W, H } = spec, regions = typeof spec.regions === "function" ? spec.regions({ W, H, name: spec.shape }) : spec.regions;+ if (!spec.stops.length) throw new Error("world: give at least one stop: where the camera starts");+ const byId = new Map<string, Region>();+ for (const r of regions) {+ if (byId.has(r.id)) throw new Error(`world: two regions are called "${r.id}"`);+ if (!(r.rect[2] > 0 && r.rect[3] > 0)) throw new Error(`world: region "${r.id}" has no size (${r.rect})`);+ byId.set(r.id, r);+ }+ const frame = (s: Stop): { look: P; zoom: number } => {+ if (typeof s.at !== "string") return s.at;+ const r = byId.get(s.at); if (!r) throw new Error(`world: stop at frame ${s.f} goes to "${s.at}", which is not a region (${[...byId.keys()].join(", ")})`);+ return { look: centreOf(r.rect), zoom: fitZoom(r.rect, W, H, s.pad) };+ };+ // each stop is an arrival key and, with a hold, a departure key: the camera travels between them+ const keys: CamKey[] = [];+ let last = -1;+ for (const s of spec.stops) {+ if (!Number.isInteger(s.f) || s.f <= last) throw new Error(`world: stops sit on whole, increasing frames (${last} then ${s.f}); a stop's hold must end before the next stop, and a move takes at least one frame (a jump between regions is the slide cut this scaffold exists to stop)`);+ const c = frame(s); keys.push({ f: s.f, ...c, ease: s.hold ? "linear" : s.ease ?? "inout" });+ if (s.hold) { if (!(Number.isInteger(s.hold) && s.hold > 0)) throw new Error(`world: hold at frame ${s.f} is a whole number of frames (got ${s.hold})`); keys.push({ f: s.f + s.hold, ...c, ease: s.ease ?? "inout" }); last = s.f + s.hold; } else last = s.f;+ }+ const camera = new Camera([W / 2, H / 2], keys);+ // handheld breathing: smooth gradient noise in screen px, the same at every zoom+ const breath = (f: number): P => {+ const a = spec.alive; if (!a || !(a.amp > 0)) return [0, 0];+ const q = a.freq ?? 0.02; return [a.amp * (fractal(a.seed, f * q, 0, 1, 1, 2) * 2 - 1), a.amp * (fractal(a.seed + 31, f * q, 0, 1, 1, 2) * 2 - 1)];+ };+ /** The camera at frame f, breathing included: look in world units, zoom in screen px per world unit. */+ const cam = (f: number): Cam => { const c = camera.at(f), [bx, by] = breath(f), k = heroScale(c); return { ...c, look: [c.look[0] - bx / k, c.look[1] - by / k] }; };+ /** Set the context to draw in world units at frame f (env.scale included). Pair with end(). */+ const begin = (ctx: Ctx, env: Env, f: number) => {+ const c = cam(f), k = heroScale(c);+ ctx.save(); ctx.setTransform(env.scale * k, 0, 0, env.scale * k, env.scale * (W / 2 - k * c.look[0]), env.scale * (H / 2 - k * c.look[1]));+ };+ const end = (ctx: Ctx) => ctx.restore();+ /** Draw a region: clipped to its rect unless it says clip: false. Call inside begin()/end(). */+ const region = (ctx: Ctx, id: string, draw: (r: Region) => void) => {+ const r = byId.get(id); if (!r) throw new Error(`world: no region "${id}"`);+ ctx.save(); if (r.clip !== false) { ctx.beginPath(); ctx.rect(...r.rect); ctx.clip(); } draw(r); ctx.restore();+ };+ /** A depth layer that travels at `speed` x the camera (0.33: a third as fast, far behind). Its own transform; do not nest in begin(). */+ const depth = (ctx: Ctx, env: Env, f: number, speed: number, draw: () => void) => {+ if (!(speed > 0)) throw new Error(`world.depth: speed is a share of the camera's, above 0 (got ${speed})`);+ const c = cam(f), k = heroScale(c);+ ctx.save(); ctx.setTransform(env.scale * k, 0, 0, env.scale * k, env.scale * (W / 2 - k * c.look[0] * speed), env.scale * (H / 2 - k * c.look[1] * speed)); draw(); ctx.restore();+ };+ /** Where a world point lands on screen at frame f (logical px). */+ const toScreen = (p: P, f: number): P => { const c = cam(f), k = heroScale(c); return [W / 2 + k * (p[0] - c.look[0]), H / 2 + k * (p[1] - c.look[1])]; };+ /** The region the camera frames at f (its centre nearest the look point), for captions and checks. */+ const regionAt = (f: number): Region | undefined => { const c = cam(f); let best: Region | undefined, d = Infinity; for (const r of regions) { const [x, y] = centreOf(r.rect), e = Math.hypot(x - c.look[0], y - c.look[1]); if (e < d) { d = e; best = r; } } return best; };+ /** The camera's moves between stops, [from, to] frames: the seams of the film, every one a move. */+ const moves = () => { const out: { from: number; to: number; into: string }[] = []; for (let i = 1; i < spec.stops.length; i++) { const p = spec.stops[i - 1], s = spec.stops[i]; out.push({ from: p.f + (p.hold ?? 0), to: s.f, into: typeof s.at === "string" ? s.at : "point" }); } return out; };+ return { camera, cam, begin, end, region, depth, toScreen, regionAt, moves, regions: byId };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/fonts.d.ts b/plugins/anidoodle/skills/anidoodle/engine/src/fonts.d.tsnew file mode 100644index 0000000..42ab140--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/fonts.d.ts@@ -0,0 +1,4 @@+// A font file imported by path (tools/overlay.mjs inlines it): import serif from "../../assets/fonts/X.ttf"+declare module "*.ttf" { const f: { path: string; format: "ttf" | "otf" | "woff2"; data: string }; export default f; }+declare module "*.otf" { const f: { path: string; format: "ttf" | "otf" | "woff2"; data: string }; export default f; }+declare module "*.woff2" { const f: { path: string; format: "ttf" | "otf" | "woff2"; data: string }; export default f; }diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/instrument.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/instrument.tsnew file mode 100644index 0000000..f8f79a9--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/instrument.ts@@ -0,0 +1,147 @@+// LAYER INSTRUMENTS (hosts only; the art core never sees them). Two jobs, both by watching what a+// frame DRAWS rather than guessing from its pixels:+//+// 1. THE BLUR MASK (render --blur). Motion blur is for the world and the camera. Type and photos are+// drawn sharp: on a brand launch film, blurred whips on type and faces read as the violent motion+// the director rejected (critic round 2). While the subframes are drawn, every line of text, every photo+// (a film asset drawn with drawImage) and everything inside sharp() is left out; the frame is then+// drawn twice more, whole and without them, and the pixels that differ are taken from the whole+// sharp frame. What remains is a blurred world under sharp type.+// 2. THE LAYER PROBE (tools/layerscan.mjs). Per frame: every line of text, every photo, every probeRect+// box (brand elements report themselves through drawEl), in draw order; the fills made in a brand+// colour at a translucent alpha; and, on request, how much ink one line of text puts on screen+// (the frame drawn with and without it). layerscan turns these into its findings.+// Only the frame's own context and full-frame sheets (__frame) count: a cached plate is drawn once+// and reused, so leaving text out of it would leave it out forever.+// THE BLUR MASK'S LIMIT. So type drawn into an offscreen layer (a sheet, a bake() sprite, a plate) and+// composited later is NOT kept sharp: it blurs with the world. Neither is 3D type (three-core text3d), which+// is drawn by WebGL, not fillText. sharpLayers counts the layers holding type that a frame composites+// (layerType), so the render can say how much type it could not keep sharp instead of claiming all of it.+import type { Ctx } from "../canvas-core/core";++type Proto = Record<string, (...a: unknown[]) => unknown>;+// src: "fill" a fillText call (setType draws one per character), "probe" a whole line or box the art reported (probeRect, drawEl)+type Rec = { kind: "text" | "box" | "photo"; src: "fill" | "probe" | "image"; label: string; x0: number; y0: number; x1: number; y1: number; alpha: number; order: number };+const protos = (): Proto[] => [CanvasRenderingContext2D.prototype, ...(typeof OffscreenCanvasRenderingContext2D !== "undefined" ? [OffscreenCanvasRenderingContext2D.prototype] : [])] as unknown as Proto[];+const G = globalThis as { __ANIDOODLE_SHARP__?: "skip"; __ANIDOODLE_PROBE__?: (r: { kind: "text" | "box"; label: string; x0: number; y0: number; x1: number; y1: number }) => void };++const boxOf = (c: Ctx, pts: number[][]) => { const T = c.getTransform(), q = pts.map(([u, v]) => [T.a * u + T.c * v + T.e, T.b * u + T.d * v + T.f]); return { x0: Math.min(...q.map((p) => p[0])), y0: Math.min(...q.map((p) => p[1])), x1: Math.max(...q.map((p) => p[0])), y1: Math.max(...q.map((p) => p[1])) }; };+const textBox = (c: Ctx, t: string, x: number, y: number) => {+ const m = c.measureText(t), a = c.textAlign, dx = a === "center" ? -m.width / 2 : a === "right" || a === "end" ? -m.width : 0;+ return boxOf(c, [[x + dx, y - m.actualBoundingBoxAscent], [x + dx + m.width, y - m.actualBoundingBoxAscent], [x + dx, y + m.actualBoundingBoxDescent], [x + dx + m.width, y + m.actualBoundingBoxDescent]]);+};+// drawImage(img, dx, dy), (img, dx, dy, dw, dh) or (img, sx, sy, sw, sh, dx, dy, dw, dh): the destination box+const imageBox = (c: Ctx, img: { width?: number; height?: number }, a: number[]) => {+ const [dx, dy, dw, dh] = a.length >= 8 ? [a[4], a[5], a[6], a[7]] : a.length >= 4 ? a : [a[0], a[1], Number(img.width), Number(img.height)];+ return boxOf(c, [[dx, dy], [dx + dw, dy], [dx, dy + dh], [dx + dw, dy + dh]]);+};+const hex = (s: string) => s.trim().toLowerCase();+const two = (n: number) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, "0");+/**+ * A declared brand colour as the #rrggbb a canvas reports for its fills, or null when it is not one this+ * can read. #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba() and hsl()/hsla() are read (alpha is ignored:+ * the colour is the brand's, the alpha is what the scan measures). A short "#c41" or an hsl() used to be+ * compared as written, never matched a fill, and the translucent check passed without looking.+ */+export const brandHex = (c: unknown): string | null => {+ if (typeof c !== "string") return null;+ const s = c.trim().toLowerCase();+ let m = /^#([0-9a-f]{3,4})$/.exec(s); if (m) return "#" + [...m[1].slice(0, 3)].map((d) => d + d).join("");+ m = /^#([0-9a-f]{6})([0-9a-f]{2})?$/.exec(s); if (m) return "#" + m[1];+ m = /^rgba?\(\s*([\d.]+)\s*[, ]\s*([\d.]+)\s*[, ]\s*([\d.]+)\s*(?:[,/]\s*[\d.]+%?\s*)?\)$/.exec(s); if (m) return "#" + [m[1], m[2], m[3]].map((v) => two(Number(v))).join("");+ m = /^hsla?\(\s*([\d.]+)(?:deg)?\s*[, ]\s*([\d.]+)%\s*[, ]\s*([\d.]+)%\s*(?:[,/]\s*[\d.]+%?\s*)?\)$/.exec(s);+ if (m) {+ const h = ((Number(m[1]) % 360) + 360) % 360, sat = Number(m[2]) / 100, l = Number(m[3]) / 100, k = (n: number) => (n + h / 30) % 12, a = sat * Math.min(l, 1 - l);+ const f = (n: number) => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));+ return "#" + [f(0), f(8), f(4)].map((v) => two(v * 255)).join("");+ }+ return null;+};+const colourAlpha = (fill: unknown): { c: string; a: number } | null => {+ if (typeof fill !== "string") return null;+ const m = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/.exec(fill.replace(/\s+/g, " ").trim());+ if (m) return { c: "#" + [m[1], m[2], m[3]].map((v) => Number(v).toString(16).padStart(2, "0")).join(""), a: m[4] === undefined ? 1 : Number(m[4]) };+ return /^#[0-9a-f]{6}$/i.test(fill) ? { c: hex(fill), a: 1 } : null;+};++export const instruments = (o: { ctx: () => Ctx; images: () => Set<unknown>; draw: (frame: number) => void; read: () => Uint8ClampedArray; clearCache?: () => void }) => {+ const own = (c: Ctx & { __frame?: boolean }) => c === o.ctx() || !!c.__frame; // ctx is a getter: the page mounts its context after building the instruments+ // TYPED LAYERS (the blur mask's limit, above). From the first blurred frame on, every surface that is not+ // the frame's own and gets text (or a typed surface drawn into it) is marked, and each frame counts how+ // many marked surfaces it composites. Installed only when a blur runs, so a shipped player is untouched;+ // the film's layer memo is emptied once then so the layers already built are rebuilt and marked.+ const typed = new WeakSet<object>(); let counting = false, layerType = 0, marking = false;+ const mark = () => {+ if (marking) return; marking = true;+ protos().forEach((p) => {+ const ft = p.fillText, st = p.strokeText, di = p.drawImage;+ p.fillText = function (this: Ctx, ...a: unknown[]) { if (!own(this) && String(a[0]).trim()) typed.add(this.canvas); return ft.apply(this, a); };+ p.strokeText = function (this: Ctx, ...a: unknown[]) { if (!own(this) && String(a[0]).trim()) typed.add(this.canvas); return st.apply(this, a); };+ p.drawImage = function (this: Ctx, ...a: unknown[]) { if (typed.has(a[0] as object)) { if (own(this)) { if (counting) layerType++; } else typed.add(this.canvas); } return di.apply(this, a); };+ });+ o.clearCache?.();+ };+ // hide: leave text / photos out of the frame's own drawing while fn runs. Restores the prototypes even on a throw.+ const hiding = <T>(what: { text?: boolean | string; photo?: boolean }, fn: () => T): T => {+ const ps = protos(), saved = ps.map((p) => ({ fillText: p.fillText, strokeText: p.strokeText, drawImage: p.drawImage })), imgs = o.images();+ const skipText = (t: unknown) => what.text === true || (typeof what.text === "string" && String(t) === what.text);+ ps.forEach((p, i) => {+ for (const k of ["fillText", "strokeText"] as const) { const f = saved[i][k]; p[k] = function (this: Ctx, ...a: unknown[]) { if (own(this) && skipText(a[0])) return; return f.apply(this, a); }; }+ const d = saved[i].drawImage; p.drawImage = function (this: Ctx, ...a: unknown[]) { if (what.photo && own(this) && imgs.has(a[0])) return; return d.apply(this, a); };+ });+ const prev = G.__ANIDOODLE_SHARP__; if (what.text === true || what.photo) G.__ANIDOODLE_SHARP__ = "skip";+ try { return fn(); } finally { ps.forEach((p, i) => Object.assign(p, saved[i])); G.__ANIDOODLE_SHARP__ = prev; }+ };++ /**+ * The sharp layers of frame n: [mask of pixels the type/photos/sharp() own, the whole sharp frame], or null+ * when the frame has none. layerType: how many layers holding type the frame composites (those blur).+ */+ const sharpLayers = (n: number) => {+ mark(); layerType = 0; counting = true;+ try { o.draw(n); } finally { counting = false; }+ const whole = o.read().slice(), lt = layerType;+ hiding({ text: true, photo: true }, () => o.draw(n)); const bare = o.read();+ const mask = new Uint8Array(whole.length / 4); let any = 0;+ for (let i = 0, p = 0; p < whole.length; i++, p += 4) if (whole[p] !== bare[p] || whole[p + 1] !== bare[p + 1] || whole[p + 2] !== bare[p + 2] || whole[p + 3] !== bare[p + 3]) { mask[i] = 1; any++; }+ return any || lt ? { mask, whole, count: any, layerType: lt } : null;+ };+ /** Run fn (the subframe loop) with the sharp layers left out. */+ const withoutSharp = <T>(fn: () => T) => hiding({ text: true, photo: true }, fn);++ /** Layer records for each frame asked, in draw order, plus brand-colour fills at a translucent alpha. */+ const layers = (frames: number[], brand: string[] = []) => {+ // declared colours are read as #rrggbb (brandHex); one that cannot be read is returned in `unread`, and+ // layerscan fails the translucent check on it rather than comparing a colour no fill can match+ const unread = brand.filter((c) => !brandHex(c)), brandSet = new Set(brand.map(brandHex).filter((c): c is string => !!c));+ const out: { frame: number; recs: Rec[]; translucent: { colour: string; alpha: number }[]; unread?: string[] }[] = [], ps = protos(), imgs = o.images();+ const saved = ps.map((p) => ({ fillText: p.fillText, drawImage: p.drawImage, fill: p.fill, fillRect: p.fillRect, stroke: p.stroke }));+ let recs: Rec[] = [], tr: { colour: string; alpha: number }[] = [], order = 0;+ const brandFill = (c: Ctx, style: unknown) => { if (!brandSet.size || !own(c)) return; const ca = colourAlpha(style); if (!ca || !brandSet.has(ca.c)) return; const a = c.globalAlpha * ca.a; if (a > 0.05 && a < 0.95) tr.push({ colour: ca.c, alpha: +a.toFixed(3) }); };+ ps.forEach((p, i) => {+ const s = saved[i];+ p.fillText = function (this: Ctx, ...a: unknown[]) { if (own(this) && this.globalAlpha >= 0.1 && String(a[0]).trim()) recs.push({ kind: "text", src: "fill", label: String(a[0]), ...textBox(this, String(a[0]), Number(a[1]), Number(a[2])), alpha: this.globalAlpha, order: order++ }); return s.fillText.apply(this, a); };+ p.drawImage = function (this: Ctx, ...a: unknown[]) { if (own(this) && imgs.has(a[0])) recs.push({ kind: "photo", src: "image", label: String((a[0] as { __name?: string }).__name ?? "image"), ...imageBox(this, a[0] as { width?: number; height?: number }, a.slice(1).map(Number)), alpha: this.globalAlpha, order: order++ }); return s.drawImage.apply(this, a); };+ p.fill = function (this: Ctx, ...a: unknown[]) { brandFill(this, this.fillStyle); return s.fill.apply(this, a); };+ p.fillRect = function (this: Ctx, ...a: unknown[]) { brandFill(this, this.fillStyle); return s.fillRect.apply(this, a); };+ p.stroke = function (this: Ctx, ...a: unknown[]) { brandFill(this, this.strokeStyle); return s.stroke.apply(this, a); };+ });+ const prevProbe = G.__ANIDOODLE_PROBE__;+ G.__ANIDOODLE_PROBE__ = (r) => { recs.push({ ...r, src: "probe", alpha: 1, order: order++ }); };+ try { for (const f of frames) { recs = []; tr = []; order = 0; o.draw(f); out.push({ frame: f, recs, translucent: tr, ...(unread.length ? { unread } : {}) }); } }+ finally { ps.forEach((p, i) => Object.assign(p, saved[i])); G.__ANIDOODLE_PROBE__ = prevProbe; }+ return out;+ };++ /** Visible ink of the text inside each box on frame n: pixels that change when ALL text is left out, counted per box (device px). */+ const ink = (n: number, boxes: { x0: number; y0: number; x1: number; y1: number }[], width: number) => {+ o.draw(n); const whole = o.read().slice();+ hiding({ text: true }, () => o.draw(n)); const bare = o.read(), height = whole.length / 4 / width;+ return boxes.map((b) => {+ let k = 0; const x0 = Math.max(0, Math.floor(b.x0)), x1 = Math.min(width, Math.ceil(b.x1)), y0 = Math.max(0, Math.floor(b.y0)), y1 = Math.min(height, Math.ceil(b.y1));+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const p = (y * width + x) * 4; if (Math.abs(whole[p] - bare[p]) + Math.abs(whole[p + 1] - bare[p + 1]) + Math.abs(whole[p + 2] - bare[p + 2]) > 24) k++; }+ return k;+ });+ };+ return { sharpLayers, withoutSharp, layers, ink };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/interactive.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/interactive.tsindex 4f8ddcc..3816329 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/interactive.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/interactive.ts@@ -46,7 +46,8 @@ const surfaceFor = (cpu: boolean) => (w: number, h: number): Layer => {return { canvas: c, ctx: c.getContext("2d", cpu ? { willReadFrequently: true } : undefined) as unknown as Ctx } as Layer;};let surface = surfaceFor(false);-const newEnv = (piece: Piece, scale: number): Env => ({ W: piece.meta.W, H: piece.meta.H, scale, cache: new Map(), canvas: surface });+const glSurface = (w: number, h: number) => typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(w, h) : Object.assign(document.createElement("canvas"), { width: w, height: h });+const newEnv = (piece: Piece, scale: number): Env => ({ W: piece.meta.W, H: piece.meta.H, scale, cache: new Map(), canvas: surface, webgl: glSurface });const q = (v: number, step: number) => Math.round(v / step) * step;const fnv = (d: Uint8ClampedArray) => { let h = 0x811c9dc5; for (let i = 0; i < d.length; i++) { h ^= d[i]; h = Math.imul(h, 0x01000193); } return (h >>> 0).toString(16).padStart(8, "0"); };const pct = (a: number[], p: number) => { if (!a.length) return 0; const s = [...a].sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptAlmond.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptAlmond.tsdeleted file mode 100644index d4c3719..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptAlmond.ts+++ /dev/null@@ -1,4 +0,0 @@-import { adaptAlmond } from "../canvas-core/adaptAlmond";-import { mountFilm } from "./page";--mountFilm(adaptAlmond);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptAquarelle.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptAquarelle.tsdeleted file mode 100644index 569a6ca..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptAquarelle.ts+++ /dev/null@@ -1,4 +0,0 @@-import { adaptAquarelle } from "../canvas-core/adaptAquarelle";-import { mountFilm } from "./page";--mountFilm(adaptAquarelle);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptScrapbook.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptScrapbook.tsdeleted file mode 100644index e5c5c84..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-adaptScrapbook.ts+++ /dev/null@@ -1,4 +0,0 @@-import { adaptScrapbook } from "../canvas-core/adaptScrapbook";-import { mountFilm } from "./page";--mountFilm(adaptScrapbook);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-bakerSheet.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-bakerSheet.tsdeleted file mode 100644index 93783e5..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-bakerSheet.ts+++ /dev/null@@ -1,4 +0,0 @@-import { bakerSheet } from "../canvas-core/bakerSheet";-import { mountFilm } from "./page";--mountFilm(bakerSheet);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-balloon.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-balloon.tsdeleted file mode 100644index ccd44b1..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-balloon.ts+++ /dev/null@@ -1,4 +0,0 @@-import { balloon } from "../canvas-core/balloon";-import { mountFilm } from "./page";--mountFilm(balloon);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-balloonDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-balloonDraw.tsdeleted file mode 100644index dbc1bd5..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-balloonDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { balloonDraw } from "../canvas-core/balloonDraw";-import { mountFilm } from "./page";--mountFilm(balloonDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-banner.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-banner.tsdeleted file mode 100644index 54bb509..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-banner.ts+++ /dev/null@@ -1,4 +0,0 @@-import { banner } from "../canvas-core/banner";-import { mountFilm } from "./page";--mountFilm(banner);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-blueprint.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-blueprint.tsdeleted file mode 100644index c1def27..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-blueprint.ts+++ /dev/null@@ -1,4 +0,0 @@-import { blueprint } from "../canvas-core/blueprint";-import { mountFilm } from "./page";--mountFilm(blueprint);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-brickBalloon.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-brickBalloon.tsdeleted file mode 100644index 695fb2b..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-brickBalloon.ts+++ /dev/null@@ -1,4 +0,0 @@-import { brickBalloon } from "../canvas-core/brickBalloon";-import { mountFilm } from "./page";--mountFilm(brickBalloon);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-brokenColour.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-brokenColour.tsdeleted file mode 100644index 0ff2ed4..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-brokenColour.ts+++ /dev/null@@ -1,4 +0,0 @@-import { brokenColour } from "../canvas-core/brokenColour";-import { mountFilm } from "./page";--mountFilm(brokenColour);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-calloutDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-calloutDemo.tsdeleted file mode 100644index 5d14c3e..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-calloutDemo.ts+++ /dev/null@@ -1,4 +0,0 @@-import { calloutDemo } from "../canvas-core/calloutDemo";-import { mountFilm } from "./page";--mountFilm(calloutDemo);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-charcoalErasure.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-charcoalErasure.tsdeleted file mode 100644index 9e5e5fc..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-charcoalErasure.ts+++ /dev/null@@ -1,4 +0,0 @@-import { charcoalErasure } from "../canvas-core/charcoalErasure";-import { mountFilm } from "./page";--mountFilm(charcoalErasure);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-colouredPencil.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-colouredPencil.tsdeleted file mode 100644index 501cbd2..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-colouredPencil.ts+++ /dev/null@@ -1,4 +0,0 @@-import { colouredPencil } from "../canvas-core/colouredPencil";-import { mountFilm } from "./page";--mountFilm(colouredPencil);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-dreamGlaze.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-dreamGlaze.tsdeleted file mode 100644index c60244e..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-dreamGlaze.ts+++ /dev/null@@ -1,4 +0,0 @@-import { dreamGlaze } from "../canvas-core/dreamGlaze";-import { mountFilm } from "./page";--mountFilm(dreamGlaze);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-dreamGlazeDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-dreamGlazeDraw.tsdeleted file mode 100644index f37b418..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-dreamGlazeDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { dreamGlazeDraw } from "../canvas-core/dreamGlazeDraw";-import { mountFilm } from "./page";--mountFilm(dreamGlazeDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-embroidery.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-embroidery.tsdeleted file mode 100644index 83a497f..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-embroidery.ts+++ /dev/null@@ -1,4 +0,0 @@-import { embroidery } from "../canvas-core/embroidery";-import { mountFilm } from "./page";--mountFilm(embroidery);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-embroideryAlive.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-embroideryAlive.tsdeleted file mode 100644index cf6de0a..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-embroideryAlive.ts+++ /dev/null@@ -1,4 +0,0 @@-import { embroideryAlive } from "../canvas-core/embroideryAlive";-import { mountFilm } from "./page";--mountFilm(embroideryAlive);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-figureSheet.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-figureSheet.tsdeleted file mode 100644index c4cc0d9..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-figureSheet.ts+++ /dev/null@@ -1,4 +0,0 @@-import { figureSheet } from "../canvas-core/figureSheet";-import { mountFilm } from "./page";--mountFilm(figureSheet);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-flatVector.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-flatVector.tsdeleted file mode 100644index 008632a..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-flatVector.ts+++ /dev/null@@ -1,4 +0,0 @@-import { flatVector } from "../canvas-core/flatVector";-import { mountFilm } from "./page";--mountFilm(flatVector);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-folkTale.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-folkTale.tsdeleted file mode 100644index 32ede8c..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-folkTale.ts+++ /dev/null@@ -1,4 +0,0 @@-import { folkTale } from "../canvas-core/folkTale";-import { mountFilm } from "./page";--mountFilm(folkTale);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-fox.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-fox.tsdeleted file mode 100644index e2a07e8..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-fox.ts+++ /dev/null@@ -1,4 +0,0 @@-import { fox } from "../canvas-core/fox";-import { mountFilm } from "./page";--mountFilm(fox);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-foxDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-foxDraw.tsdeleted file mode 100644index f4ba359..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-foxDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { foxDraw } from "../canvas-core/foxDraw";-import { mountFilm } from "./page";--mountFilm(foxDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-halftone.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-halftone.tsdeleted file mode 100644index 2db22ea..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-halftone.ts+++ /dev/null@@ -1,4 +0,0 @@-import { halftone } from "../canvas-core/halftone";-import { mountFilm } from "./page";--mountFilm(halftone);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-isometric.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-isometric.tsdeleted file mode 100644index 3ed4dba..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-isometric.ts+++ /dev/null@@ -1,4 +0,0 @@-import { isometric } from "../canvas-core/isometric";-import { mountFilm } from "./page";--mountFilm(isometric);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-kineticDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-kineticDemo.tsdeleted file mode 100644index a63e3a0..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-kineticDemo.ts+++ /dev/null@@ -1,4 +0,0 @@-import { kineticDemo } from "../canvas-core/kineticDemo";-import { mountFilm } from "./page";--mountFilm(kineticDemo);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koi.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koi.tsdeleted file mode 100644index 292e7ab..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koi.ts+++ /dev/null@@ -1,4 +0,0 @@-import { koi } from "../canvas-core/koi";-import { mountFilm } from "./page";--mountFilm(koi);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiAlive.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiAlive.tsdeleted file mode 100644index 3a707ef..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiAlive.ts+++ /dev/null@@ -1,4 +0,0 @@-import { koiAlive } from "../canvas-core/koiAlive";-import { mountFilm } from "./page";--mountFilm(koiAlive);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiDraw.tsdeleted file mode 100644index cb60660..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { koiDraw } from "../canvas-core/koiDraw";-import { mountFilm } from "./page";--mountFilm(koiDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiWorld.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiWorld.tsdeleted file mode 100644index f1bd8ee..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-koiWorld.ts+++ /dev/null@@ -1,4 +0,0 @@-import { koiWorld } from "../canvas-core/koiWorld";-import { mountFilm } from "./page";--mountFilm(koiWorld);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchExample.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchExample.tsdeleted file mode 100644index 015f1fa..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchExample.ts+++ /dev/null@@ -1,4 +0,0 @@-import { launchExample } from "../canvas-core/launchExample";-import { mountFilm } from "./page";--mountFilm(launchExample);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchExampleClean.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchExampleClean.tsdeleted file mode 100644index d4bc013..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchExampleClean.ts+++ /dev/null@@ -1,4 +0,0 @@-import { launchExampleClean } from "../canvas-core/launchExampleClean";-import { mountFilm } from "./page";--mountFilm(launchExampleClean);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonCat.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonCat.tsdeleted file mode 100644index c2ef020..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonCat.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lessonCat } from "../canvas-core/lessonCat";-import { mountFilm } from "./page";--mountFilm(lessonCat);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonCatFinal.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonCatFinal.tsdeleted file mode 100644index c505f23..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonCatFinal.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lessonCatFinal } from "../canvas-core/lessonCatFinal";-import { mountFilm } from "./page";--mountFilm(lessonCatFinal);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonCatSheet.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonCatSheet.tsdeleted file mode 100644index 0156900..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonCatSheet.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lessonCatSheet } from "../canvas-core/lessonCatSheet";-import { mountFilm } from "./page";--mountFilm(lessonCatSheet);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwl.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwl.tsdeleted file mode 100644index e7a0727..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwl.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lessonOwl } from "../canvas-core/lessonOwl";-import { mountFilm } from "./page";--mountFilm(lessonOwl);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwlFinal.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwlFinal.tsdeleted file mode 100644index 035ece8..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwlFinal.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lessonOwlFinal } from "../canvas-core/lessonOwlFinal";-import { mountFilm } from "./page";--mountFilm(lessonOwlFinal);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwlSheet.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwlSheet.tsdeleted file mode 100644index d04a868..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwlSheet.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lessonOwlSheet } from "../canvas-core/lessonOwlSheet";-import { mountFilm } from "./page";--mountFilm(lessonOwlSheet);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwlSocial.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwlSocial.tsdeleted file mode 100644index 3fcd9aa..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lessonOwlSocial.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lessonOwlSocial } from "../canvas-core/lessonOwlSocial";-import { mountFilm } from "./page";--mountFilm(lessonOwlSocial);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lighthouse.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lighthouse.tsdeleted file mode 100644index 2b5046a..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lighthouse.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lighthouse } from "../canvas-core/lighthouse";-import { mountFilm } from "./page";--mountFilm(lighthouse);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lighthouseDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lighthouseDraw.tsdeleted file mode 100644index 9ee13e7..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lighthouseDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lighthouseDraw } from "../canvas-core/lighthouseDraw";-import { mountFilm } from "./page";--mountFilm(lighthouseDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lowPoly.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lowPoly.tsdeleted file mode 100644index eecef4e..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-lowPoly.ts+++ /dev/null@@ -1,4 +0,0 @@-import { lowPoly } from "../canvas-core/lowPoly";-import { mountFilm } from "./page";--mountFilm(lowPoly);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanism.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanism.tsdeleted file mode 100644index 1c8c577..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanism.ts+++ /dev/null@@ -1,4 +0,0 @@-import { mechanism } from "../canvas-core/mechanism";-import { mountFilm } from "./page";--mountFilm(mechanism);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismBlueprint.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismBlueprint.tsdeleted file mode 100644index f4abd46..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismBlueprint.ts+++ /dev/null@@ -1,4 +0,0 @@-import { mechanismBlueprint } from "../canvas-core/mechanismBlueprint";-import { mountFilm } from "./page";--mountFilm(mechanismBlueprint);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismDraw.tsdeleted file mode 100644index 3891e08..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { mechanismDraw } from "../canvas-core/mechanismDraw";-import { mountFilm } from "./page";--mountFilm(mechanismDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismPencil.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismPencil.tsdeleted file mode 100644index 1f42662..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismPencil.ts+++ /dev/null@@ -1,4 +0,0 @@-import { mechanismPencil } from "../canvas-core/mechanismPencil";-import { mountFilm } from "./page";--mountFilm(mechanismPencil);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismStipple.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismStipple.tsdeleted file mode 100644index 1d60455..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mechanismStipple.ts+++ /dev/null@@ -1,4 +0,0 @@-import { mechanismStipple } from "../canvas-core/mechanismStipple";-import { mountFilm } from "./page";--mountFilm(mechanismStipple);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mellan.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mellan.tsdeleted file mode 100644index 87e898a..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mellan.ts+++ /dev/null@@ -1,4 +0,0 @@-import { mellan } from "../canvas-core/mellan";-import { mountFilm } from "./page";--mountFilm(mellan);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mellanUnspool.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mellanUnspool.tsdeleted file mode 100644index e8b2693..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-mellanUnspool.ts+++ /dev/null@@ -1,4 +0,0 @@-import { mellanUnspool } from "../canvas-core/mellanUnspool";-import { mountFilm } from "./page";--mountFilm(mellanUnspool);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-midCentury.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-midCentury.tsdeleted file mode 100644index 95674a8..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-midCentury.ts+++ /dev/null@@ -1,4 +0,0 @@-import { midCentury } from "../canvas-core/midCentury";-import { mountFilm } from "./page";--mountFilm(midCentury);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraComic.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraComic.tsdeleted file mode 100644index f7bb4ca..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraComic.ts+++ /dev/null@@ -1,4 +0,0 @@-import { miraComic } from "../canvas-core/miraComic";-import { mountFilm } from "./page";--mountFilm(miraComic);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraEveryHand.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraEveryHand.tsdeleted file mode 100644index 0639641..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraEveryHand.ts+++ /dev/null@@ -1,4 +0,0 @@-import { miraEveryHand } from "../canvas-core/miraEveryHand";-import { mountFilm } from "./page";--mountFilm(miraEveryHand);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraRiso.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraRiso.tsdeleted file mode 100644index 24bf8a6..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraRiso.ts+++ /dev/null@@ -1,4 +0,0 @@-import { miraRiso } from "../canvas-core/miraRiso";-import { mountFilm } from "./page";--mountFilm(miraRiso);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraSheet.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraSheet.tsdeleted file mode 100644index e2a16cf..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraSheet.ts+++ /dev/null@@ -1,4 +0,0 @@-import { miraSheet } from "../canvas-core/miraSheet";-import { mountFilm } from "./page";--mountFilm(miraSheet);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraTile.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraTile.tsdeleted file mode 100644index b573f0e..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraTile.ts+++ /dev/null@@ -1,4 +0,0 @@-import { miraTile } from "../canvas-core/miraTile";-import { mountFilm } from "./page";--mountFilm(miraTile);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraTriptych.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraTriptych.tsdeleted file mode 100644index 7641a83..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraTriptych.ts+++ /dev/null@@ -1,4 +0,0 @@-import { miraTriptych } from "../canvas-core/miraTriptych";-import { mountFilm } from "./page";--mountFilm(miraTriptych);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraWalk.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraWalk.tsdeleted file mode 100644index 7901614..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-miraWalk.ts+++ /dev/null@@ -1,4 +0,0 @@-import { miraWalk } from "../canvas-core/miraWalk";-import { mountFilm } from "./page";--mountFilm(miraWalk);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-moonPhases.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-moonPhases.tsdeleted file mode 100644index 7a4417b..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-moonPhases.ts+++ /dev/null@@ -1,4 +0,0 @@-import { moonPhases } from "../canvas-core/moonPhases";-import { mountFilm } from "./page";--mountFilm(moonPhases);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-moonPhasesDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-moonPhasesDraw.tsdeleted file mode 100644index 9e31f00..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-moonPhasesDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { moonPhasesDraw } from "../canvas-core/moonPhasesDraw";-import { mountFilm } from "./page";--mountFilm(moonPhasesDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-morphDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-morphDemo.tsdeleted file mode 100644index b25a3d4..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-morphDemo.ts+++ /dev/null@@ -1,4 +0,0 @@-import { morphDemo } from "../canvas-core/morphDemo";-import { mountFilm } from "./page";--mountFilm(morphDemo);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-paintedOil.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-paintedOil.tsdeleted file mode 100644index 0968070..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-paintedOil.ts+++ /dev/null@@ -1,4 +0,0 @@-import { paintedOil } from "../canvas-core/paintedOil";-import { mountFilm } from "./page";--mountFilm(paintedOil);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-paperCraft.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-paperCraft.tsdeleted file mode 100644index 30bc8ab..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-paperCraft.ts+++ /dev/null@@ -1,4 +0,0 @@-import { paperCraft } from "../canvas-core/paperCraft";-import { mountFilm } from "./page";--mountFilm(paperCraft);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-pixelArt.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-pixelArt.tsdeleted file mode 100644index ba61908..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-pixelArt.ts+++ /dev/null@@ -1,4 +0,0 @@-import { pixelArt } from "../canvas-core/pixelArt";-import { mountFilm } from "./page";--mountFilm(pixelArt);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-pocketWatch.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-pocketWatch.tsdeleted file mode 100644index e433965..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-pocketWatch.ts+++ /dev/null@@ -1,4 +0,0 @@-import { pocketWatch } from "../canvas-core/pocketWatch";-import { mountFilm } from "./page";--mountFilm(pocketWatch);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-pocketWatchDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-pocketWatchDraw.tsdeleted file mode 100644index 31f5a9e..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-pocketWatchDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { pocketWatchDraw } from "../canvas-core/pocketWatchDraw";-import { mountFilm } from "./page";--mountFilm(pocketWatchDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-ranunculus.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-ranunculus.tsdeleted file mode 100644index dd9c661..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-ranunculus.ts+++ /dev/null@@ -1,4 +0,0 @@-import { ranunculus } from "../canvas-core/ranunculus";-import { mountFilm } from "./page";--mountFilm(ranunculus);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-ranunculusDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-ranunculusDraw.tsdeleted file mode 100644index 7d29f88..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-ranunculusDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { ranunculusDraw } from "../canvas-core/ranunculusDraw";-import { mountFilm } from "./page";--mountFilm(ranunculusDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-rubberHose.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-rubberHose.tsdeleted file mode 100644index 42ef590..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-rubberHose.ts+++ /dev/null@@ -1,4 +0,0 @@-import { rubberHose } from "../canvas-core/rubberHose";-import { mountFilm } from "./page";--mountFilm(rubberHose);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-scrapbook.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-scrapbook.tsdeleted file mode 100644index e3fccc6..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-scrapbook.ts+++ /dev/null@@ -1,4 +0,0 @@-import { scrapbook } from "../canvas-core/scrapbook";-import { mountFilm } from "./page";--mountFilm(scrapbook);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-scratchboard.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-scratchboard.tsdeleted file mode 100644index 42574a6..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-scratchboard.ts+++ /dev/null@@ -1,4 +0,0 @@-import { scratchboard } from "../canvas-core/scratchboard";-import { mountFilm } from "./page";--mountFilm(scratchboard);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHero.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHero.tsdeleted file mode 100644index a186064..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHero.ts+++ /dev/null@@ -1,4 +0,0 @@-import { siteHero } from "../canvas-core/siteHero";-import { mountFilm } from "./page";--mountFilm(siteHero);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHeroDark.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHeroDark.tsdeleted file mode 100644index 327b2f6..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHeroDark.ts+++ /dev/null@@ -1,4 +0,0 @@-import { siteHeroDark } from "../canvas-core/siteHeroDark";-import { mountFilm } from "./page";--mountFilm(siteHeroDark);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-stipple.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-stipple.tsdeleted file mode 100644index 64957da..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-stipple.ts+++ /dev/null@@ -1,4 +0,0 @@-import { stipple } from "../canvas-core/stipple";-import { mountFilm } from "./page";--mountFilm(stipple);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-storybookDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-storybookDraw.tsdeleted file mode 100644index 7eafde2..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-storybookDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { storybookDraw } from "../canvas-core/storybookDraw";-import { mountFilm } from "./page";--mountFilm(storybookDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-styleGallery.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-styleGallery.tsdeleted file mode 100644index abb2f7d..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-styleGallery.ts+++ /dev/null@@ -1,4 +0,0 @@-import { styleGallery } from "../canvas-core/styleGallery";-import { mountFilm } from "./page";--mountFilm(styleGallery);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-styleWall.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-styleWall.tsdeleted file mode 100644index 9beba4b..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-styleWall.ts+++ /dev/null@@ -1,4 +0,0 @@-import { styleWall } from "../canvas-core/styleWall";-import { mountFilm } from "./page";--mountFilm(styleWall);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-sumiE.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-sumiE.tsdeleted file mode 100644index df3ef9b..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-sumiE.ts+++ /dev/null@@ -1,4 +0,0 @@-import { sumiE } from "../canvas-core/sumiE";-import { mountFilm } from "./page";--mountFilm(sumiE);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-toyBrick.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-toyBrick.tsdeleted file mode 100644index 1ea1187..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-toyBrick.ts+++ /dev/null@@ -1,4 +0,0 @@-import { toyBrick } from "../canvas-core/toyBrick";-import { mountFilm } from "./page";--mountFilm(toyBrick);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-transitionsDemo.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-transitionsDemo.tsdeleted file mode 100644index ac31725..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-transitionsDemo.ts+++ /dev/null@@ -1,4 +0,0 @@-import { transitionsDemo } from "../canvas-core/transitionsDemo";-import { mountFilm } from "./page";--mountFilm(transitionsDemo);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-webTour.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-webTour.tsdeleted file mode 100644index f834909..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-webTour.ts+++ /dev/null@@ -1,4 +0,0 @@-import { webTour } from "../canvas-core/webTour";-import { mountFilm } from "./page";--mountFilm(webTour);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-woodcut.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-woodcut.tsdeleted file mode 100644index 9766791..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-woodcut.ts+++ /dev/null@@ -1,4 +0,0 @@-import { woodcut } from "../canvas-core/woodcut";-import { mountFilm } from "./page";--mountFilm(woodcut);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-wren.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-wren.tsdeleted file mode 100644index 3ed6104..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-wren.ts+++ /dev/null@@ -1,4 +0,0 @@-import { wren } from "../canvas-core/wren";-import { mountFilm } from "./page";--mountFilm(wren);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-wrenDraw.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-wrenDraw.tsdeleted file mode 100644index fbf531a..0000000--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-wrenDraw.ts+++ /dev/null@@ -1,4 +0,0 @@-import { wrenDraw } from "../canvas-core/wrenDraw";-import { mountFilm } from "./page";--mountFilm(wrenDraw);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.tsindex a1853e4..bd7635d 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page.ts@@ -1,9 +1,11 @@// THE ONE GENERATED PAGE. Playwright, the HTML player and (Phase 5) Hyperframes all drive this// same page through window.FILM. Everything host-specific (DOM, clocks, asset decoding, Web// Audio) lives HERE; the art core never sees it.-import type { Ctx, Env, Layer, ProbeRec } from "../canvas-core/core";+import type { Ctx, Env, Layer } from "../canvas-core/core";import { Film, renderFrame, validate } from "../canvas-core/film";import { embeddedAudio, type AudioPayload } from './audio';+import { instruments } from "./instrument";+import { frameProbe } from "./probe";declare global { interface Window { FILM: unknown; __ASSETS__?: Record<string, string>; __BAKE_SRC__?: Record<string, string>; __ANIDOODLE_SRC__?: WeakMap<object, string>; __SHAPE__?: string; __AUDIO__?: AudioPayload } }@@ -42,11 +44,16 @@ export const mountFilm = (film: Film) => {const opts = film.meta.raster === "cpu" ? { willReadFrequently: true } : undefined; // see Film.meta.rasterconst surface = (w: number, h: number): Layer => { const c = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(w, h) : Object.assign(document.createElement("canvas"), { width: w, height: h }); return { canvas: c, ctx: c.getContext("2d", opts) as unknown as Ctx } as Layer; };const bakes = bakeStore(surface);- const mount = (scale = 1) => { canvas.width = Math.round(film.meta.W * scale); canvas.height = Math.round(film.meta.H * scale); ctx = canvas.getContext("2d", opts) as CanvasRenderingContext2D; env = { W: film.meta.W, H: film.meta.H, scale, cache: new Map(), canvas: surface, image: (n) => images.get(n), bake: bakes.bake, root: true }; return film.meta; };+ // 3D shots draw through WebGL (three-core/stage.ts). OffscreenCanvas when the browser has it, a detached <canvas> otherwise.+ const glSurface = (w: number, h: number) => typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(w, h) : Object.assign(document.createElement("canvas"), { width: w, height: h });+ const mount = (scale = 1) => { canvas.width = Math.round(film.meta.W * scale); canvas.height = Math.round(film.meta.H * scale); ctx = canvas.getContext("2d", opts) as CanvasRenderingContext2D; env = { W: film.meta.W, H: film.meta.H, scale, cache: new Map(), canvas: surface, webgl: glSurface, image: (n) => images.get(n), bake: bakes.bake, root: true }; return film.meta; };// contract rule 4: every asset is loaded AND decoded before frame 0, or the film refuses to startconst ready = (async () => {const problems = validate(film); if (problems.length) throw new Error("timeline: " + problems.join("; "));- await Promise.all(Object.entries(film.assets.images).map(async ([name, url]) => { const img = new Image(); img.src = window.__ASSETS__?.[name] ?? url; await img.decode(); images.set(name, img); }));+ await Promise.all(Object.entries(film.assets.images).map(async ([name, url]) => { const img = new Image(); img.src = window.__ASSETS__?.[name] ?? url; await img.decode(); (img as unknown as { __name: string }).__name = name; images.set(name, img); }));+ // a launch look's own font files (launchLook.registerFaces) are loaded before frame 0, so no frame is set+ // in a fallback face; a film that added none waits for nothing+ if ((document.fonts as unknown as { size: number }).size) await document.fonts.ready;mount(1); return film.meta;})();const seek = (frame: number) => { const t0 = performance.now(); const shot = renderFrame(film, ctx, frame, env); ctx.getImageData(0, 0, 1, 1); current = frame; return { shot, ms: performance.now() - t0 }; }; // getImageData forces the deferred raster so the timing is real@@ -72,7 +79,9 @@ export const mountFilm = (film: Film) => {// divided by `px` (default 3: subframes at most 3 px apart), is the count, 1 on a still frame (the// sharp frame itself, untouched), at most `max` (default 32). Pure pixels in, a number out:// deterministic like the frames it measures.- type BlurSpec = { samples?: number; shutter?: number; max?: number; px?: number };+ // sharp: true (the default) keeps type, photos and sharp() out of the blur (hosts/instrument.ts); false blurs everything.+ type BlurSpec = { samples?: number; shutter?: number; max?: number; px?: number; sharp?: boolean };+ const inst = instruments({ ctx: () => ctx, images: () => new Set(images.values()), draw: (f) => { renderFrame(film, ctx, f, env); }, read: () => ctx.getImageData(0, 0, canvas.width, canvas.height).data, clearCache: () => env.cache.clear() });const lumaGrid = (f: number, cell: number) => {renderFrame(film, ctx, f, env); const w = canvas.width, h = canvas.height, d = ctx.getImageData(0, 0, w, h).data, gw = Math.floor(w / cell), gh = Math.floor(h / cell), g = new Float32Array(gw * gh);for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) { let s = 0; for (let yy = 0; yy < cell; yy += 2) for (let xx = 0; xx < cell; xx += 2) { const p = ((y * cell + yy) * w + x * cell + xx) * 4, a = d[p + 3] / 255; s += (0.2126 * d[p] + 0.7152 * d[p + 1] + 0.0722 * d[p + 2]) * a; } g[y * gw + x] = s / ((cell * cell) / 4); }@@ -111,47 +120,35 @@ export const mountFilm = (film: Film) => {if (shot && !stepped && samples === 0) { speed = speedOf(win(n - sh / 2), win(n + sh / 2)); samples = Math.max(1, Math.min(o.max ?? 32, Math.ceil(speed / (o.px ?? 3)))); }if (!shot || samples < 2 || stepped) { const r = seek(n); return { shot: r.shot, ms: r.ms, samples: 1, speed }; }const t0 = performance.now(), w = canvas.width, h = canvas.height, acc = new Float64Array(w * h * 4);- for (let i = 0; i < samples; i++) {+ const keep = o.sharp === false ? null : inst.sharpLayers(n); // the frame's type and photos, drawn sharp+ const sub = () => { for (let i = 0; i < samples; i++) {const t = win(n + ((i + 0.5) / samples - 0.5) * sh);renderFrame(film, ctx, t, env);const d = ctx.getImageData(0, 0, w, h).data;for (let p = 0; p < d.length; p += 4) { const a = d[p + 3], k = a / 255; acc[p] += toLin[d[p]] * k; acc[p + 1] += toLin[d[p + 1]] * k; acc[p + 2] += toLin[d[p + 2]] * k; acc[p + 3] += a; }- }+ } };+ if (keep) inst.withoutSharp(sub); else sub();const img = ctx.createImageData(w, h), out = img.data, inv = 1 / samples, full = 255 * samples;for (let p = 0; p < out.length; p += 4) {const A = acc[p + 3]; if (A === 0) continue; // nothing was ever drawn here: stays transparent blackconst c = A === full ? inv : 255 / A; // premultiplied average, un-premultiplied by the mean alphaout[p] = fromLin(acc[p] * c); out[p + 1] = fromLin(acc[p + 1] * c); out[p + 2] = fromLin(acc[p + 2] * c); out[p + 3] = Math.round(A * inv);}+ if (keep) for (let i = 0, p = 0; i < keep.mask.length; i++, p += 4) if (keep.mask[i]) { out[p] = keep.whole[p]; out[p + 1] = keep.whole[p + 1]; out[p + 2] = keep.whole[p + 2]; out[p + 3] = keep.whole[p + 3]; }ctx.putImageData(img, 0, 0); current = n;- return { shot: shot.id, ms: performance.now() - t0, samples, speed };+ return { shot: shot.id, ms: performance.now() - t0, samples, speed, sharpPx: keep?.count ?? 0, typeInLayers: keep?.layerType ?? 0 }; // typeInLayers: layers holding type that blurred (instrument.ts)};- // THE FRAME PROBE (tools/framecheck.mjs). For each frame asked, every line of text (fillText on the- // frame or a full-frame sheet, writeOn, setType) and every content box the art core reports- // (probeRect: a card, a window) is collected in device pixels; a box the frame's edge cuts through- // is returned. Whatever lies wholly outside the frame, or wholly inside it, is fine. With `all`, every- // visible line of text is returned too (cut: false when whole), for the checks that judge where- // text sits (the 9:16 safe zones, textrules.mjs).- const probe = (frames: number[], all = false) => {- const out: (ProbeRec & { frame: number; cut?: boolean })[] = [], g = globalThis as { __ANIDOODLE_PROBE__?: (r: ProbeRec) => void };- const protos = [CanvasRenderingContext2D.prototype, ...(typeof OffscreenCanvasRenderingContext2D !== "undefined" ? [OffscreenCanvasRenderingContext2D.prototype] : [])] as unknown as { fillText: (t: string, x: number, y: number, w?: number) => void }[];- const orig = protos.map((p) => p.fillText);- let frame = 0, recs: ProbeRec[] = [];- protos.forEach((p, i) => { p.fillText = function (this: Ctx & { __frame?: boolean }, t: string, x: number, y: number, w?: number) {- if ((this === ctx || this.__frame) && this.globalAlpha >= 0.1 && String(t).trim()) {- const m = this.measureText(t), a = this.textAlign, dx = a === "center" ? -m.width / 2 : a === "right" || a === "end" ? -m.width : 0, T = this.getTransform();- const bx = [[x + dx, y - m.actualBoundingBoxAscent], [x + dx + m.width, y - m.actualBoundingBoxAscent], [x + dx, y + m.actualBoundingBoxDescent], [x + dx + m.width, y + m.actualBoundingBoxDescent]].map(([u, v]) => [T.a * u + T.c * v + T.e, T.b * u + T.d * v + T.f]);- recs.push({ kind: "text", label: String(t), x0: Math.min(...bx.map((q) => q[0])), y0: Math.min(...bx.map((q) => q[1])), x1: Math.max(...bx.map((q) => q[0])), y1: Math.max(...bx.map((q) => q[1])) });- }- return (orig[i] as (t: string, x: number, y: number, w?: number) => void).call(this, t, x, y, w);- }; });- g.__ANIDOODLE_PROBE__ = (r) => recs.push(r);- try {- for (frame of frames) {- recs = []; seek(frame); const W = canvas.width, H = canvas.height, tol = 1.5;- for (const r of recs) { const inter = r.x1 > 0 && r.x0 < W && r.y1 > 0 && r.y0 < H, inside = r.x0 >= -tol && r.y0 >= -tol && r.x1 <= W + tol && r.y1 <= H + tol; if (inter && !inside) out.push({ ...r, frame }); else if (all && inter && r.kind === "text") out.push({ ...r, frame, cut: false }); }- }- } finally { protos.forEach((p, i) => (p.fillText = orig[i] as never)); delete g.__ANIDOODLE_PROBE__; }+ // THE FRAME PROBE (tools/framecheck.mjs): hosts/probe.ts. Every call rebuilds the film's layer memo under+ // its hooks, so text in a reused layer (a bake() sprite, a held plate) is seen in every batch.+ const probe = frameProbe({ canvas: () => canvas, ctx: () => ctx, seek: (f) => { seek(f); }, clearCache: () => env.cache.clear() });+ // 3D CHECKS (tools/gate.mjs, still.mjs --grips). Turns three-core/checks3d.ts on, draws each frame asked+ // and returns what every frame's runChecks found, plus where its grips sit on screen (logical px).+ // A frame whose film never calls runChecks returns no record. Off by default: no hook, no cost.+ type Check3D = { frame: number; findings: { frame: number; kind: string; where: string; detail: string }[]; grips: { name: string; x: number; y: number }[] };+ const checks3d = (frames: number[]) => {+ const out: Check3D[] = [], g = globalThis as { __ANIDOODLE_CHECK3D__?: (frame: number, findings: Check3D["findings"], info?: { grips: Check3D["grips"] }) => void };+ g.__ANIDOODLE_CHECK3D__ = (frame, findings, info) => { out.push({ frame, findings, grips: info?.grips ?? [] }); };+ try { for (const f of frames) seek(f); } finally { delete g.__ANIDOODLE_CHECK3D__; }return out;};const audio = (sr: number) => { if (!filmSound) return null; const [L, R] = filmSound(sr); if (L.length !== R.length) throw new Error("audio channels have different lengths"); const pcm = new Float32Array(L.length * 2); for (let i = 0; i < L.length; i++) { pcm[i * 2] = L[i]; pcm[i * 2 + 1] = R[i]; } return { sampleRate: sr, frames: L.length, float32: b64(new Uint8Array(pcm.buffer)) }; };@@ -175,7 +172,11 @@ export const mountFilm = (film: Film) => {if (u > 0 && posterOf) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = Math.min(1, u); ctx.globalCompositeOperation = "source-over"; if (u >= 1) ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(posterOf.img, 0, 0); ctx.restore(); }current = n; return r;};- window.FILM = { probe, meta: { ...film.meta, hasAudio: typeof film.audio === "function", shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, blur, poster, bakes: { load: bakes.load, take: bakes.take, hashes: bakes.hashes, stats: () => bakes.stats }, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };+ // THE LAYER PROBE (tools/layerscan.mjs): per frame, text, photos and reported boxes in draw order, and+ // translucent fills in the brand's colours; ink(): how much each text box shows on a frame.+ const layers = (frames: number[], brand: string[] = []) => { const r = inst.layers(frames, brand); current = frames[frames.length - 1] ?? current; return r; };+ const ink = (frame: number, boxes: { x0: number; y0: number; x1: number; y1: number }[]) => inst.ink(frame, boxes, canvas.width);+ window.FILM = { probe, checks3d, layers, ink, meta: { ...film.meta, placeholders: (window as unknown as { __PLACEHOLDERS__?: string[] }).__PLACEHOLDERS__ ?? [], hasAudio: typeof film.audio === "function", shots: film.shots.map(({ id, start, end }) => ({ id, start, end })) }, ready, mount, seek, hash, audio, warm, blur, poster, bakes: { load: bakes.load, take: bakes.take, hashes: bakes.hashes, stats: () => bakes.stats }, png: () => canvas.toDataURL("image/png").slice(22), frame: () => current };// ---- the player: click or space to play, arrows to step, ?frame=N to open on a frameready.then(() => {diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/probe.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/probe.tsnew file mode 100644index 0000000..622167a--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/probe.ts@@ -0,0 +1,124 @@+// THE FRAME PROBE (tools/framecheck.mjs), host side. For each frame asked, every line of text (fillText on+// the frame or a full-frame sheet, writeOn, setType) and every content box the art core reports+// (probeRect: a card, a window) is collected in device pixels; a box the frame's edge cuts through+// is returned. Whatever lies wholly outside the frame, or wholly inside it, is fine. With `all`, every+// visible line of text is returned too (cut: false when whole), for the checks that judge where+// text sits (the 9:16 safe zones, textrules.mjs).+// Text is followed through offscreen layers: every fillText/strokeText on ANY surface is recorded in+// that surface's own pixels, and a drawImage of a surface carries its text onto the surface it is+// drawn into (through the source rectangle, the destination rectangle and the current transform).+// So text a film sets on a sheet and composites later is seen exactly like text on the frame+// (the reading-time check was blind to it before). A full clearRect, or an opaque full fillRect,+// forgets a surface's text. Each text record also carries its alpha, its type size in device px,+// its font family and the texture mark (texture(): words not meant to be read).+//+// It lives in its own module (page.ts mounts it) so the unit tests can drive it with a stand-in+// canvas in node: test/probe.test.ts.+import type { Ctx, ProbeRec } from "../canvas-core/core";++type TextRec = ProbeRec & { alpha: number; px: number; family: string; texture?: boolean };+type B = { x0: number; y0: number; x1: number; y1: number };+export type ProbeOut = (ProbeRec | TextRec) & { frame: number; cut?: boolean };++/**+ * canvas/ctx are getters (the page mounts a new context at each scale). seek draws one frame.+ * clearCache empties the film's layer memo (env.cache): a pure memo, so emptying it changes no pixel.+ */+export const frameProbe = (o: { canvas: () => { width: number; height: number }; ctx: () => Ctx; seek: (frame: number) => void; clearCache: () => void }) => (frames: number[], all = false) => {+ const canvas = o.canvas(), ctx = o.ctx();+ const out: ProbeOut[] = [], g = globalThis as { __ANIDOODLE_PROBE__?: (r: ProbeRec) => void };+ type Proto = Record<string, (...a: unknown[]) => void>;+ const protos = [CanvasRenderingContext2D.prototype, ...(typeof OffscreenCanvasRenderingContext2D !== "undefined" ? [OffscreenCanvasRenderingContext2D.prototype] : [])] as unknown as Proto[];+ const names = ["fillText", "strokeText", "drawImage", "clearRect", "fillRect", "beginPath", "rect", "roundRect", "arc", "arcTo", "ellipse", "moveTo", "lineTo", "bezierCurveTo", "quadraticCurveTo", "clip", "save", "restore", "reset"] as const, orig = protos.map((p) => Object.fromEntries(names.map((n) => [n, p[n]])) as Proto);+ const texts = new WeakMap<object, TextRec[]>(), of = (c: object) => { let l = texts.get(c); if (!l) texts.set(c, (l = [])); return l; };+ const box = (T: DOMMatrix, pts: number[][]) => { const q = pts.map(([u, v]) => [T.a * u + T.c * v + T.e, T.b * u + T.d * v + T.f]); return { x0: Math.min(...q.map((p) => p[0])), y0: Math.min(...q.map((p) => p[1])), x1: Math.max(...q.map((p) => p[0])), y1: Math.max(...q.map((p) => p[1])) }; };+ const zoom = (T: DOMMatrix) => Math.sqrt(Math.abs(T.a * T.d - T.b * T.c));+ // CLIPS. A text drawn under a clip (an input field that scrolls its text, a mask a line rises through)+ // is seen only inside it. The probe keeps each context's clip as the bounding box of the path it was+ // made from (rect, roundRect, arc, arcTo, ellipse, lines and curves, in device px), intersected down the+ // save/restore stack, and cuts every text box to it; a text wholly outside its clip is not drawn.+ // A clip the probe cannot measure (a Path2D, or a path with no area it could read) is treated as no+ // clip: the text stays in view of the checks. Reading an unknown clip as "clips everything" made every+ // line under it vanish, and the checks then passed on text they never saw.+ const clipOf = new WeakMap<object, { box: B | null; stack: (B | null)[]; path: B | null }>(), cs = (c: object) => { let v = clipOf.get(c); if (!v) clipOf.set(c, (v = { box: null, stack: [], path: null })); return v; };+ const meet = (a: B | null, b: B | null): B | null => (!a ? b : !b ? a : { x0: Math.max(a.x0, b.x0), y0: Math.max(a.y0, b.y0), x1: Math.min(a.x1, b.x1), y1: Math.min(a.y1, b.y1) });+ const grow = (c: Ctx, pts: number[][]) => { const st = cs(c), r = box(c.getTransform(), pts); st.path = st.path ? { x0: Math.min(st.path.x0, r.x0), y0: Math.min(st.path.y0, r.y0), x1: Math.max(st.path.x1, r.x1), y1: Math.max(st.path.y1, r.y1) } : r; };+ const clipped = <T extends B>(c: Ctx, t: T): T | null => { const k = clipOf.get(c)?.box; if (!k) return t; const m = meet(t, k)!; return m.x1 - m.x0 <= 0.5 || m.y1 - m.y0 <= 0.5 ? null : { ...t, ...m }; };+ const text = function (this: Ctx & { __texture?: boolean }, t: string, x: number, y: number) {+ if (!String(t).trim() || this.globalAlpha < 0.01) return;+ const m = this.measureText(t), a = this.textAlign, dx = a === "center" ? -m.width / 2 : a === "right" || a === "end" ? -m.width : 0, T = this.getTransform();+ const fm = /(\d+(?:\.\d+)?)px\s*(.*)$/.exec(this.font), px = (fm ? Number(fm[1]) : 10) * zoom(T), family = (fm?.[2] ?? "").split(",")[0].trim().replace(/^["']|["']$/g, "");+ const rec = clipped(this, { kind: "text" as const, label: String(t), ...box(T, [[x + dx, y - m.actualBoundingBoxAscent], [x + dx + m.width, y - m.actualBoundingBoxAscent], [x + dx, y + m.actualBoundingBoxDescent], [x + dx + m.width, y + m.actualBoundingBoxDescent]]), alpha: this.globalAlpha, px, family, texture: this.__texture || undefined });+ if (rec) of(this.canvas).push(rec);+ };+ const opaque = new WeakSet<object>(); // surfaces whose last full-size fill was opaque: drawn at alpha 1 they cover what is under them+ const solid = (c: Ctx) => c.globalAlpha >= 1 && c.globalCompositeOperation === "source-over" && typeof c.fillStyle === "string" && !/rgba|hsla|transparent|#[0-9a-f]{4}$|#[0-9a-f]{8}$/i.test(c.fillStyle);+ const full = (c: Ctx, x: number, y: number, w: number, h: number) => { const r = box(c.getTransform(), [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]); return r.x0 <= 0 && r.y0 <= 0 && r.x1 >= c.canvas.width && r.y1 >= c.canvas.height; };+ const forget = (c: Ctx, x: number, y: number, w: number, h: number) => {+ const l = texts.get(c.canvas); if (!l?.length) return;+ const r = box(c.getTransform(), [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]), cw = c.canvas.width, ch = c.canvas.height;+ if (r.x0 <= 0 && r.y0 <= 0 && r.x1 >= cw && r.y1 >= ch) { l.length = 0; return; }+ // what lies wholly under an opaque fill is covered: the viewer cannot see it, so it is no longer drawn text+ texts.set(c.canvas, l.filter((t) => !(t.x0 >= r.x0 && t.y0 >= r.y0 && t.x1 <= r.x1 && t.y1 <= r.y1)));+ };+ const isPath2D = (v: unknown) => typeof Path2D !== "undefined" && v instanceof Path2D;+ protos.forEach((p, i) => {+ p.fillText = function (this: Ctx, ...a: unknown[]) { text.call(this, a[0] as string, a[1] as number, a[2] as number); return orig[i].fillText.apply(this, a); };+ p.strokeText = function (this: Ctx, ...a: unknown[]) { text.call(this, a[0] as string, a[1] as number, a[2] as number); return orig[i].strokeText.apply(this, a); };+ p.clearRect = function (this: Ctx, ...a: unknown[]) { const q = a as [number, number, number, number]; forget(this, ...q); if (full(this, ...q)) opaque.delete(this.canvas); return orig[i].clearRect.apply(this, a); };+ p.fillRect = function (this: Ctx, ...a: unknown[]) { const q = a as [number, number, number, number]; if (solid(this)) { forget(this, ...q); if (full(this, ...q)) opaque.add(this.canvas); } return orig[i].fillRect.apply(this, a); };+ p.drawImage = function (this: Ctx, ...a: unknown[]) {+ const src = texts.get(a[0] as object), s = a[0] as { width: number; height: number }, n = a.length;+ const [sx, sy, sw, sh, dx, dy, dw, dh] = (n >= 9 ? a.slice(1, 9) : n >= 5 ? [0, 0, s.width, s.height, ...a.slice(1, 5)] : [0, 0, s.width, s.height, a[1], a[2], s.width, s.height]) as number[];+ if (opaque.has(a[0] as object) && this.globalAlpha >= 1 && this.globalCompositeOperation === "source-over") forget(this, dx, dy, dw, dh); // an opaque sheet covers what was under it+ if (src?.length && this.globalAlpha >= 0.01) {+ const kx = dw / sw, ky = dh / sh, T = this.getTransform(), z = zoom(T) * Math.sqrt(Math.abs(kx * ky)), dst = of(this.canvas);+ for (const t of src) {+ if (t.x1 <= sx || t.x0 >= sx + sw || t.y1 <= sy || t.y0 >= sy + sh) continue; // outside the source rectangle: not drawn+ const u0 = dx + (t.x0 - sx) * kx, v0 = dy + (t.y0 - sy) * ky, u1 = dx + (t.x1 - sx) * kx, v1 = dy + (t.y1 - sy) * ky;+ const rec = clipped(this, { ...t, ...box(T, [[u0, v0], [u1, v0], [u0, v1], [u1, v1]]), alpha: t.alpha * this.globalAlpha, px: t.px * z }); if (rec) dst.push(rec);+ }+ }+ return orig[i].drawImage.apply(this, a);+ };+ const num = (a: unknown[]) => a as number[];+ p.beginPath = function (this: Ctx, ...a: unknown[]) { cs(this).path = null; return orig[i].beginPath.apply(this, a); };+ p.rect = function (this: Ctx, ...a: unknown[]) { const [x, y, w, h] = num(a); grow(this, [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]); return orig[i].rect.apply(this, a); };+ if (orig[i].roundRect) p.roundRect = function (this: Ctx, ...a: unknown[]) { const [x, y, w, h] = num(a); grow(this, [[x, y], [x + w, y], [x, y + h], [x + w, y + h]]); return orig[i].roundRect.apply(this, a); };+ p.arc = function (this: Ctx, ...a: unknown[]) { const [x, y, r] = num(a); grow(this, [[x - r, y - r], [x + r, y - r], [x - r, y + r], [x + r, y + r]]); return orig[i].arc.apply(this, a); };+ // arcTo (rounded rects built by hand, launchKit rr()): the arc lies inside the triangle of the pen, the+ // corner and the far point, so the two control points bound it with the pen already in the box+ if (orig[i].arcTo) p.arcTo = function (this: Ctx, ...a: unknown[]) { const q = num(a); grow(this, [[q[0], q[1]], [q[2], q[3]]]); return orig[i].arcTo.apply(this, a); };+ p.ellipse = function (this: Ctx, ...a: unknown[]) { const [x, y, rx, ry] = num(a), r = Math.max(rx, ry); grow(this, [[x - r, y - r], [x + r, y - r], [x - r, y + r], [x + r, y + r]]); return orig[i].ellipse.apply(this, a); };+ p.moveTo = function (this: Ctx, ...a: unknown[]) { const [x, y] = num(a); grow(this, [[x, y]]); return orig[i].moveTo.apply(this, a); };+ p.lineTo = function (this: Ctx, ...a: unknown[]) { const [x, y] = num(a); grow(this, [[x, y]]); return orig[i].lineTo.apply(this, a); };+ p.bezierCurveTo = function (this: Ctx, ...a: unknown[]) { const q = num(a); grow(this, [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]]]); return orig[i].bezierCurveTo.apply(this, a); };+ p.quadraticCurveTo = function (this: Ctx, ...a: unknown[]) { const q = num(a); grow(this, [[q[0], q[1]], [q[2], q[3]]]); return orig[i].quadraticCurveTo.apply(this, a); };+ p.clip = function (this: Ctx, ...a: unknown[]) {+ const st = cs(this), b = st.path;+ // only a clip with a measured area narrows what the checks see; anything else is an unknown clip (see CLIPS)+ if (!isPath2D(a[0]) && b && b.x1 - b.x0 > 0.5 && b.y1 - b.y0 > 0.5) st.box = meet(st.box, b);+ return orig[i].clip.apply(this, a);+ };+ p.save = function (this: Ctx, ...a: unknown[]) { const st = cs(this); st.stack.push(st.box); return orig[i].save.apply(this, a); };+ p.restore = function (this: Ctx, ...a: unknown[]) { const st = cs(this); st.box = st.stack.length ? st.stack.pop()! : null; return orig[i].restore.apply(this, a); };+ if (orig[i].reset) p.reset = function (this: Ctx, ...a: unknown[]) { clipOf.delete(this); return orig[i].reset.apply(this, a); };+ });+ let frame = 0;+ // boxes the art reports (probeRect) join the frame's own list, so an opaque fill drawn over them covers them too+ g.__ANIDOODLE_PROBE__ = (r) => { of(canvas).push({ ...r, alpha: 1, px: undefined as unknown as number, family: "" }); };+ try {+ // Text records live only as long as this call (the hooks come off at the end). A layer the film built+ // once and reuses (a bake() sprite, a plate that skips its redraw) carries records only if it is drawn+ // under these hooks, so EVERY call starts by emptying the film's layer memo and each layer is rebuilt+ // here. Emptying it only on the first call left reused layers without records from the second batch+ // on (framecheck asks 40 frames at a time), and every text check then passed on text it never saw.+ // Plate frames from the bake store are the one blind spot left: framecheck opens the page with the bake cache off.+ o.clearCache();+ for (frame of frames) {+ of(canvas).length = 0; clipOf.delete(ctx); o.seek(frame); const W = canvas.width, H = canvas.height, tol = 1.5;+ for (const r of of(canvas).filter((t) => t.alpha >= 0.1)) { const inter = r.x1 > 0 && r.x0 < W && r.y1 > 0 && r.y0 < H, inside = r.x0 >= -tol && r.y0 >= -tol && r.x1 <= W + tol && r.y1 <= H + tol; if (inter && !inside) out.push({ ...r, frame }); else if (all && inter) out.push({ ...r, frame, cut: false }); }+ }+ } finally { protos.forEach((p, i) => names.forEach((n) => { if (orig[i][n]) p[n] = orig[i][n]; })); delete g.__ANIDOODLE_PROBE__; }+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/camera.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/camera.tsnew file mode 100644index 0000000..8c4e7f6--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/camera.ts@@ -0,0 +1,202 @@+// CAMERA (3D). Named moves a director would call, each a pure function of the frame that returns a+// whole camera state: where it stands, what it looks at, the lens and the roll. place() writes a+// state onto a THREE.PerspectiveCamera. Nothing is stepped, so any frame can be drawn first.+//+// const base = look([0, 1.2, 8], [0, 0.6, 0], 35);+// const move = withMods(pushIn(base, 0.3, 0, 48), handheld(7, 0.6));+// place(cam, move(f), env);+//+// Same vocabulary as the 2D camera (canvas-core/camera.ts) and the same craft:+// - A PUSH IS EASED IN log(distance). Halving the distance twice should take twice as long as+// halving it once; easing the distance itself sprints at the near end.+// - A DOLLY ALONG A PATH RUNS AT CONSTANT SPEED BY ARC LENGTH (getPointAt), then the ease shapes+// it. Curve parameter u bunches up wherever the control points do, which reads as a stutter.+// - HANDHELD IS SMOOTH SEEDED NOISE, MOSTLY ROTATION. Per-frame random reads as static; a slow+// aim wander and a little roll is what sells an operator. Never Math.random.+// - A WHIP PAN HOLDS POSED FRAMES ON BOTH ENDS AND HAS NO SMEAR (lesson 46): sharp drawings at each+// end and a fast move between make the cut without a motion-blur bible break.+// - A MATCH CUT KEEPS SCREEN SIZE: on-screen size is worldSize * H / (2 * D * tan(fov / 2)), so+// across a lens change keep D * tan(fov / 2) fixed (matchDistance) and the subject holds its size.+// - LEGIBILITY IS MEASURED IN PIXELS (lessons 25, 27): a contact beat needs ~40 px at 1080p, a+// story-critical line ~2 px. screenSize() and worldForPx() turn a camera into those numbers.+import * as THREE from "three";+import { ease as E, seg, type Ease } from "./time";++export type V3 = [number, number, number];+/** a whole camera: position, the point it looks at, vertical fov in degrees, roll in degrees */+export type CamState = { pos: V3; target: V3; fov: number; roll: number };+/** a camera move: frame in, camera out */+export type Move = (f: number) => CamState;+/** something layered on top of a move (handheld, dutch): state and frame in, new state out */+export type Mod = (s: CamState, f: number) => CamState;+type Size = { W: number; H: number };++const D2R = Math.PI / 180;+const v = (a: V3) => new THREE.Vector3(a[0], a[1], a[2]);+const arr = (p: THREE.Vector3): V3 => [p.x, p.y, p.z];+const lerp3 = (a: V3, b: V3, t: number): V3 => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];+const p = (f: number, f0: number, f1: number, e: Ease) => e(seg(f, f0, f1));++/** a camera state from where it stands and what it looks at */+export const look = (pos: V3, target: V3, fov = 35, roll = 0): CamState => ({ pos: [...pos], target: [...target], fov, roll });+/** a move that never moves (a locked-off shot; add handheld to keep it alive) */+export const hold = (s: CamState): Move => () => ({ ...s, pos: [...s.pos], target: [...s.target] });+/** layer modifiers over a move, in order */+export const withMods = (move: Move, ...mods: Mod[]): Move => (f) => mods.reduce((s, m) => m(s, f), move(f));+/** run one move until frame `at`, then another (a move that hands over without a cut) */+export const then = (a: Move, at: number, b: Move): Move => (f) => (f < at ? a(f) : b(f));++/** write a state onto a three camera: position, lookAt, roll about the view axis, fov (and aspect from env) */+export const place = (cam: THREE.PerspectiveCamera, s: CamState, env?: Size) => {+ cam.position.set(s.pos[0], s.pos[1], s.pos[2]);+ cam.up.set(0, 1, 0);+ cam.lookAt(s.target[0], s.target[1], s.target[2]);+ if (s.roll) cam.rotateZ(s.roll * D2R);+ cam.fov = s.fov;+ if (env) cam.aspect = env.W / env.H;+ cam.updateProjectionMatrix();+ cam.updateMatrixWorld(true);+ return cam;+};++// distance moved in log space: equal time per halving+const pushTo = (base: CamState, factor: number, f: number, f0: number, f1: number, e: Ease): CamState => {+ const k = Math.exp(Math.log(factor) * p(f, f0, f1, e)), t = base.target;+ return { ...base, pos: [t[0] + (base.pos[0] - t[0]) * k, t[1] + (base.pos[1] - t[1]) * k, t[2] + (base.pos[2] - t[2]) * k], target: [...t] };+};+/** move toward the target: amount 0.3 ends 30% closer */+export const pushIn = (base: CamState, amount: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => (f) => pushTo(base, 1 - amount, f, f0, f1, e);+/** move away from the target: amount 0.3 ends 30% farther */+export const pullBack = (base: CamState, amount: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => (f) => pushTo(base, 1 + amount, f, f0, f1, e);++/** a path for the camera through points (centripetal Catmull-Rom: no loops or overshoot at tight keys) */+export const path = (points: V3[], closed = false) => new THREE.CatmullRomCurve3(points.map(v), closed, "centripetal");+/** travel along a curve at constant speed by arc length; aim at a fixed point, along a second curve, or ahead along the path */+export const dolly = (curve: THREE.Curve<THREE.Vector3>, f0: number, f1: number, o: { target?: V3 | THREE.Curve<THREE.Vector3> | "ahead"; fov?: number; ease?: Ease; lead?: number } = {}): Move => {+ // arc-length table built once here, not on the first draw: getPointAt caches it on the curve+ curve.getLengths();+ return (f) => {+ const t = p(f, f0, f1, o.ease ?? E.inOutSine), pos = arr(curve.getPointAt(t));+ let target: V3;+ // "ahead": look along the travel direction, `lead` units out (the tangent, so it never stalls at the end)+ if (o.target === undefined || o.target === "ahead") target = arr(curve.getPointAt(t).add(curve.getTangentAt(t).multiplyScalar(o.lead ?? 3)));+ else if (Array.isArray(o.target)) target = [...o.target];+ else target = arr(o.target.getPointAt(t));+ return { pos, target, fov: o.fov ?? 35, roll: 0 };+ };+};+/** circle a point at a radius and height above it, fromDeg to toDeg (0 deg = on +z, looking toward -z) */+export const orbit = (center: V3, fromDeg: number, toDeg: number, radius: number, height: number, f0: number, f1: number, o: { fov?: number; ease?: Ease } = {}): Move => (f) => {+ const a = (fromDeg + (toDeg - fromDeg) * p(f, f0, f1, o.ease ?? E.inOutSine)) * D2R;+ return { pos: [center[0] + Math.sin(a) * radius, center[1] + height, center[2] + Math.cos(a) * radius], target: [...center], fov: o.fov ?? 35, roll: 0 };+};+/** rise (or sink, negative) by `rise`; follow 0 keeps the aim point (the camera tilts), 1 lifts it too */+export const crane = (base: CamState, rise: number, f0: number, f1: number, o: { follow?: number; ease?: Ease } = {}): Move => (f) => {+ const d = rise * p(f, f0, f1, o.ease ?? E.inOutCubic);+ return { ...base, pos: [base.pos[0], base.pos[1] + d, base.pos[2]], target: [base.target[0], base.target[1] + d * (o.follow ?? 0), base.target[2]] };+};+// the camera's right and up axes for a state (world up is +y)+const axes = (s: CamState) => {+ const fwd = v(s.target).sub(v(s.pos)).normalize(), right = new THREE.Vector3().crossVectors(fwd, new THREE.Vector3(0, 1, 0)).normalize();+ return { fwd, right, up: new THREE.Vector3().crossVectors(right, fwd) };+};+/** slide sideways (positive = camera right), aim point and all */+export const truck = (base: CamState, dx: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => {+ const r = arr(axes(base).right);+ return (f) => { const d = dx * p(f, f0, f1, e); return { ...base, pos: lerp3(base.pos, [base.pos[0] + r[0], base.pos[1] + r[1], base.pos[2] + r[2]], d), target: lerp3(base.target, [base.target[0] + r[0], base.target[1] + r[1], base.target[2] + r[2]], d) }; };+};+const turnAim = (s: CamState, axis: THREE.Vector3, deg: number): V3 => arr(v(s.target).sub(v(s.pos)).applyAxisAngle(axis, deg * D2R).add(v(s.pos)));+/** turn the camera on its head left or right (positive = left) */+export const pan = (base: CamState, deg: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => (f) => ({ ...base, pos: [...base.pos], target: turnAim(base, new THREE.Vector3(0, 1, 0), deg * p(f, f0, f1, e)) });+/** nod the camera up or down (positive = up) */+export const tilt = (base: CamState, deg: number, f0: number, f1: number, e: Ease = E.inOutCubic): Move => { const r = axes(base).right; return (f) => ({ ...base, pos: [...base.pos], target: turnAim(base, r, deg * p(f, f0, f1, e)) }); };+/**+ * A fast pan from one aim to another: the first `hold` frames sit on `from`, the last `hold` on `to`,+ * the move between is an expo in-out with no smear. Both states may differ in position too.+ */+export const whipPan = (from: CamState, to: CamState, f0: number, f1: number, o: { hold?: number } = {}): Move => {+ const h = o.hold ?? 2;+ if (f1 - f0 < 2 * h + 2) throw new Error(`whipPan: ${f1 - f0} frames is too short for ${h} held frames each end plus a move`);+ // aim swings on a sphere around the moving position, so the pan reads as a turn, not a slide+ return (f) => {+ const t = E.inOutExpo(seg(f, f0 + h, f1 - h)), pos = lerp3(from.pos, to.pos, t);+ const da = v(from.target).sub(v(from.pos)), db = v(to.target).sub(v(to.pos)), la = da.length(), lb = db.length();+ const q = new THREE.Quaternion().setFromUnitVectors(da.clone().normalize(), db.clone().normalize()), dir = da.clone().normalize().applyQuaternion(new THREE.Quaternion().slerp(q, t));+ return { pos, target: arr(dir.multiplyScalar(la + (lb - la) * t).add(v(pos))), fov: from.fov + (to.fov - from.fov) * t, roll: from.roll + (to.roll - from.roll) * t };+ };+};+/** roll the frame: a fixed angle, or a function of the frame for an eased dutch */+export const dutch = (roll: number | ((f: number) => number)): Mod => (s, f) => ({ ...s, roll: s.roll + (typeof roll === "number" ? roll : roll(f)) });+/** change the lens over time (deg): a zoom, which unlike a push keeps every depth's proportion */+export const zoom = (fromFov: number, toFov: number, f0: number, f1: number, e: Ease = E.inOutCubic): Mod => (s, f) => ({ ...s, fov: fromFov + (toFov - fromFov) * p(f, f0, f1, e) });++// ---- seeded smooth noise+/** a pure hash of (seed, i) to [0, 1): no sequence, so any i can be asked first */+export const hash01 = (seed: number, i: number) => {+ let h = Math.imul((seed | 0) ^ 0x9e3779b9, 0x85ebca6b) ^ Math.imul(i | 0, 0xc2b2ae35);+ h ^= h >>> 16; h = Math.imul(h, 0x7feb352d); h ^= h >>> 15; h = Math.imul(h, 0x846ca68b); h ^= h >>> 16;+ return (h >>> 0) / 4294967296;+};+/** smooth 1D value noise in [-1, 1]: quintic between seeded lattice values one unit apart */+export const noise1 = (seed: number, x: number) => {+ const i = Math.floor(x), t = x - i, s = t * t * t * (t * (t * 6 - 15) + 10);+ const a = hash01(seed, i) * 2 - 1, b = hash01(seed, i + 1) * 2 - 1;+ return a + (b - a) * s;+};+/**+ * An operator holding the camera: aim wander, roll and a little sway, all seeded smooth noise.+ * amount 1 = about 0.5 deg of aim wander; freq in wobbles per second at 24 fps (default 0.6).+ */+export const handheld = (seed: number, amount = 1, o: { freq?: number; fps?: number } = {}): Mod => (s, f) => {+ const x = (f / (o.fps ?? 24)) * (o.freq ?? 0.6), n = (k: number) => noise1(seed * 31 + k, x + k * 0.37) * 0.7 + noise1(seed * 31 + k + 9, x * 2.3) * 0.3;+ const { right, up } = axes(s), dist = v(s.target).sub(v(s.pos)).length(), aim = Math.tan(0.5 * amount * D2R) * dist, sway = 0.004 * amount * dist;+ const dt = right.clone().multiplyScalar(n(1) * aim).add(up.clone().multiplyScalar(n(2) * aim));+ const dp = right.clone().multiplyScalar(n(3) * sway).add(up.clone().multiplyScalar(n(4) * sway));+ return { pos: arr(v(s.pos).add(dp)), target: arr(v(s.target).add(dt).add(dp)), fov: s.fov, roll: s.roll + n(5) * 0.35 * amount };+};++// ---- framing and legibility+/**+ * Frame a box (or an object's bounds): look from `dir` (pointing from the subject toward the+ * camera) at the box centre, at the distance where the box's furthest corner sits `padding` in+ * from the frame edge (padding 1.15 = 15% margin). Solved by bisection on the projected corners,+ * so it is exact for this aspect, not the loose bounding-sphere fit.+ */+export const fitTo = (subject: THREE.Box3 | THREE.Object3D, o: { padding?: number; dir?: V3; fov?: number; aspect?: number } = {}): CamState => {+ const box = (subject as THREE.Box3).isBox3 ? (subject as THREE.Box3) : new THREE.Box3().setFromObject(subject as THREE.Object3D);+ if (box.isEmpty()) throw new Error("fitTo: the subject has no bounds");+ const c = box.getCenter(new THREE.Vector3()), dir = v(o.dir ?? [0, 0.25, 1]).normalize(), fov = o.fov ?? 35, aspect = o.aspect ?? 16 / 9, pad = o.padding ?? 1.15;+ const cam = new THREE.PerspectiveCamera(fov, aspect, 0.01, 1e5);+ const corners = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => new THREE.Vector3(i & 1 ? box.max.x : box.min.x, i & 2 ? box.max.y : box.min.y, i & 4 ? box.max.z : box.min.z));+ const reach = (d: number) => {+ cam.position.copy(c).addScaledVector(dir, d); cam.lookAt(c); cam.updateMatrixWorld(true); cam.updateProjectionMatrix();+ let m = 0; for (const k of corners) { const q = k.clone().applyMatrix4(cam.matrixWorldInverse); if (-q.z <= cam.near) return Infinity; const n = k.clone().project(cam); m = Math.max(m, Math.abs(n.x), Math.abs(n.y)); }+ return m;+ };+ let lo = 1e-3, hi = Math.max(1, box.getSize(new THREE.Vector3()).length()) * 2;+ while (reach(hi) > 1 / pad) hi *= 2;+ for (let i = 0; i < 60; i++) { const mid = (lo + hi) / 2; if (reach(mid) > 1 / pad) lo = mid; else hi = mid; }+ return { pos: arr(c.clone().addScaledVector(dir, hi)), target: arr(c), fov, roll: 0 };+};+/** a focus distance racked from one subject distance to another, eased in dioptres (1/d): how a real focus ring moves */+export const rackFocus = (f: number, f0: number, f1: number, fromDist: number, toDist: number, e: Ease = E.inOutCubic) => 1 / (1 / fromDist + (1 / toDist - 1 / fromDist) * p(f, f0, f1, e));+/** pixels an object worldSize tall covers at `distance` from the camera, at the film's height */+export const screenSize = (cam: { fov: number }, worldSize: number, distance: number, env: Size) => (worldSize * env.H) / (2 * distance * Math.tan((cam.fov * D2R) / 2));+/** the world size that covers `px` pixels at `distance`: size a thin story line by its screen width (lesson 27) */+export const worldForPx = (cam: { fov: number }, px: number, distance: number, env: Size) => (px * 2 * distance * Math.tan((cam.fov * D2R) / 2)) / env.H;+/** the camera distance that shows a subject worldSize tall at `px` pixels through this fov (D = K / tan(fov/2)) */+export const matchCut = (worldSize: number, px: number, fovDeg: number, env: Size) => (worldSize * env.H) / (2 * px * Math.tan((fovDeg * D2R) / 2));+/** the distance through fovB that keeps the size a subject had at distance dA through fovA */+export const matchDistance = (dA: number, fovA: number, fovB: number) => (dA * Math.tan((fovA * D2R) / 2)) / Math.tan((fovB * D2R) / 2);+/** a state through a new lens with the subject at its target holding its screen size (the camera slides along its view axis) */+export const matchLens = (s: CamState, fov: number): CamState => {+ const d = v(s.pos).sub(v(s.target)), k = matchDistance(d.length(), s.fov, fov) / d.length();+ return { ...s, fov, pos: arr(v(s.target).add(d.multiplyScalar(k))), target: [...s.target] };+};+/** where a world point lands on the film, in film pixels [x, y] (call place() first); z > 1 means behind the camera */+export const screenPx = (cam: THREE.PerspectiveCamera, world: V3 | THREE.Vector3, env: Size): [number, number, number] => {+ const q = (Array.isArray(world) ? v(world) : world.clone()).project(cam);+ return [((q.x + 1) / 2) * env.W, ((1 - q.y) / 2) * env.H, q.z];+};+/** distance from the camera to a world point along its view axis (what screenSize wants) */+export const depthOf = (cam: THREE.Camera, world: V3) => -v(world).applyMatrix4(cam.matrixWorldInverse).z;diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/checks3d.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/checks3d.tsnew file mode 100644index 0000000..26b367b--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/checks3d.ts@@ -0,0 +1,376 @@+// CHECKS 3D. What a director runs on a frame of a 3D shot, from inside its draw, to catch the faults+// Alex caught by eye on the last 3D film: a prop through the hand meant to hold it (lesson 37), a+// claw holding nothing on screen (48), two characters clipping (38), a walk through a closed gate+// (22), a label covered by a claw (42), a contact beat too small to read (25).+//+// Every check is a plain function returning { ok, findings }. For a whole shot, register what the+// frame holds as it is posed, then runChecks() once the camera is set:+//+// resetChecks(); // first thing in the draw: nothing carries over from another frame+// pose(robot, ...); grip(hand, lantern, 0.5, { hang: true });+// registerRig("robot", robot); registerGrip(robot, robot.limbs["arms.right"], lantern);+// if (checking()) runChecks(f, camera, env); // the collector (a host, a test) gets the findings+//+// Checks sample real surfaces, not bounding boxes: boxes of curved tubes are mostly air and flagged+// thousands of points while rigs stood metres apart (lesson 38). Hidden objects never count (a+// carried jar that is switched off is not a collision).+//+// PERSISTENT VISUAL CHECK (a practice, not code): run the full check pass after EVERY batch of shot+// changes, not once at the end. On the last film a new jar swing broke a catch that had been clean,+// and only the re-run found it (lesson 48). Pair it with a 2x crop of each grip (still --scale 2):+// a green check with a prop through a hand is a failed gate, so look.+import * as THREE from "three";+import { gripFrame, handleOf, isLimb, meshesOf, type Limb, type Rig } from "./rig";++type V3 = THREE.Vector3;+const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);+export type Finding = { frame: number; kind: string; where: string; detail: string };+export type CheckResult = { ok: boolean; findings: Finding[] };+const result = (findings: Finding[]): CheckResult => ({ ok: findings.length === 0, findings });+const fmt = (p: V3) => p.toArray().map((x) => x.toFixed(2)).join(", ");+type Obj = THREE.Object3D;+const objOf = (x: Rig | Obj): Obj => ("hips" in x && "limbs" in x ? (x as Rig).root : (x as Obj));+const within = (o: Obj, anc: Obj) => { let n: Obj | null = o; while (n) { if (n === anc) return true; n = n.parent; } return false; };+// visible itself and every ancestor visible: what the renderer would actually draw+const shown = (o: Obj) => { let n: Obj | null = o; while (n) { if (!n.visible) return false; n = n.parent; } return true; };+const partName = (m: THREE.Mesh) => String(m.userData.part ?? (m.name || m.geometry.type));++// ---------------------------------------------------------------- surface sampling+// Points spread over every triangle at `spacing` (vertices alone miss a big flat face pushed through+// a small part). Cached per geometry in its own space: geometry never changes per frame, so the cache+// cannot carry frame state; the world positions are recomputed from the mesh's matrix every call.+const sampleCache = new WeakMap<THREE.BufferGeometry, Map<number, Float32Array>>();+const MAX_PTS = 6000;+const localSamples = (g: THREE.BufferGeometry, spacing: number): Float32Array => {+ let byS = sampleCache.get(g); if (!byS) sampleCache.set(g, (byS = new Map()));+ const hit = byS.get(spacing); if (hit) return hit;+ const pos = g.attributes.position, idx = g.index, n = idx ? idx.count : pos.count, tri = (i: number) => (idx ? idx.getX(i) : i);+ const A = v3(), B = v3(), C = v3();+ // The longest edge of each triangle, once. Then COUNT the points a spacing would make before making+ // any: a rig built in centimetres, or a prop scaled to almost nothing, asks for millions of points+ // at the spacing it was given. The spacing grows by 1.6x until the count fits the cap (or only the+ // vertices are left), so a tiny or non-finite spacing can never stall or overflow an array.+ const edge: number[] = [];+ for (let t = 0; t + 2 < n; t += 3) {+ A.fromBufferAttribute(pos, tri(t)); B.fromBufferAttribute(pos, tri(t + 1)); C.fromBufferAttribute(pos, tri(t + 2));+ edge.push(Math.max(A.distanceTo(B), B.distanceTo(C), C.distanceTo(A)));+ }+ const extra = (s: number) => { let c = 0; for (const e of edge) { const k = Math.ceil(e / s); if (k >= 2) c += ((k + 1) * (k + 2)) / 2 - 3; } return c; };+ const longest = edge.reduce((m, e) => Math.max(m, e), 0);+ let sp = Number.isFinite(spacing) && spacing > 0 ? spacing : longest || 1;+ for (let c = extra(sp); c > 0 && pos.count + c > MAX_PTS; c = extra(sp)) sp *= 1.6;+ // every vertex once, then extra points only inside triangles bigger than the spacing (a dense+ // sphere needs no more than its vertices; a two-triangle wall needs a grid)+ const out: number[] = [];+ for (let i = 0; i < pos.count; i++) out.push(pos.getX(i), pos.getY(i), pos.getZ(i));+ for (let t = 0, e = 0; t + 2 < n; t += 3, e++) {+ const k = Math.ceil(edge[e] / sp);+ if (k < 2) continue;+ A.fromBufferAttribute(pos, tri(t)); B.fromBufferAttribute(pos, tri(t + 1)); C.fromBufferAttribute(pos, tri(t + 2));+ for (let i = 0; i <= k; i++) for (let j = 0; j <= k - i; j++) { if ((i === 0 && j === 0) || (i === k && j === 0) || (i === 0 && j === k)) continue; const a = i / k, b = j / k, c = 1 - a - b; out.push(A.x * c + B.x * a + C.x * b, A.y * c + B.y * a + C.y * b, A.z * c + B.z * a + C.z * b); }+ }+ const arr = new Float32Array(out); byS.set(spacing, arr); return arr;+};+/** World-space surface points of a mesh, about `spacing` apart. */+export const surfacePoints = (m: THREE.Mesh, spacing: number): V3[] => { const w = worldPts(m, spacing), out: V3[] = []; for (let i = 0; i < w.length; i += 3) out.push(v3(w[i], w[i + 1], w[i + 2])); return out; };+// the same as a flat array (the checks' hot path: no object per point)+const worldPts = (m: THREE.Mesh, spacing: number): Float32Array => {+ m.updateWorldMatrix(true, false);+ const s = localSamples(m.geometry, spacing), e = m.matrixWorld.elements, out = new Float32Array(s.length);+ for (let i = 0; i < s.length; i += 3) { const x = s[i], y = s[i + 1], z = s[i + 2]; out[i] = e[0] * x + e[4] * y + e[8] * z + e[12]; out[i + 1] = e[1] * x + e[5] * y + e[9] * z + e[13]; out[i + 2] = e[2] * x + e[6] * y + e[10] * z + e[14]; }+ return out;+};+const segDist = (p: V3, a: V3, b: V3) => segDistXYZ(p.x, p.y, p.z, a, b);+const segDistXYZ = (px: number, py: number, pz: number, a: V3, b: V3) => {+ const abx = b.x - a.x, aby = b.y - a.y, abz = b.z - a.z, L = abx * abx + aby * aby + abz * abz;+ let t = L > 0 ? ((px - a.x) * abx + (py - a.y) * aby + (pz - a.z) * abz) / L : 0; t = t < 0 ? 0 : t > 1 ? 1 : t;+ const dx = px - a.x - abx * t, dy = py - a.y - aby * t, dz = pz - a.z - abz * t; return Math.sqrt(dx * dx + dy * dy + dz * dz);+};++// Is a point INSIDE a closed mesh? Ray parity in the mesh's own space, both faces counted. A hand+// sunk wholly into a body touches no surface point, so surface distance alone misses it.+const CLOSED = new Set(["SphereGeometry", "CapsuleGeometry", "BoxGeometry", "IcosahedronGeometry", "OctahedronGeometry", "DodecahedronGeometry", "TetrahedronGeometry", "ExtrudeGeometry"]);+const isClosed = (m: THREE.Mesh) => {+ if (m.userData.closed !== undefined) return !!m.userData.closed;+ const g = m.geometry as THREE.BufferGeometry & { parameters?: Record<string, number | boolean> }, t = g.type, p = g.parameters ?? {};+ if (t === "CylinderGeometry") return !p.openEnded && (p.thetaLength === undefined || (p.thetaLength as number) >= Math.PI * 2 - 1e-6);+ if (t === "TorusGeometry") return (p.arc as number) >= Math.PI * 2 - 1e-6;+ if (t === "SphereGeometry") return (p.phiLength as number) >= Math.PI * 2 - 1e-6 && (p.thetaLength as number) >= Math.PI - 1e-6;+ return CLOSED.has(t);+};+// triangles of a geometry as one flat array, cached (geometry is static; the frame never is)+const triCache = new WeakMap<THREE.BufferGeometry, Float32Array>();+const trisOf = (g: THREE.BufferGeometry) => {+ let t = triCache.get(g); if (t) return t;+ const pos = g.attributes.position, idx = g.index, n = idx ? idx.count : pos.count; t = new Float32Array(Math.floor(n / 3) * 9);+ for (let i = 0, k = 0; i + 2 < n; i += 3) for (let j = 0; j < 3; j++) { const q = idx ? idx.getX(i + j) : i + j; t[k++] = pos.getX(q); t[k++] = pos.getY(q); t[k++] = pos.getZ(q); }+ triCache.set(g, t); return t;+};+const DX = 1, DY = 0.000713, DZ = 0.000419; // a skewed ray so it never runs exactly along an edge+type Solid = { box: THREE.Box3; lbox: THREE.Box3; inv: number[]; tris: Float32Array; name: string };+const solidOf = (m: THREE.Mesh): Solid => { m.updateWorldMatrix(true, false); const g = m.geometry; g.boundingBox ?? g.computeBoundingBox(); return { box: new THREE.Box3().copy(g.boundingBox!).applyMatrix4(m.matrixWorld), lbox: g.boundingBox!, inv: m.matrixWorld.clone().invert().elements, tris: trisOf(g), name: partName(m) }; };+const insideSolid = (s: Solid, x: number, y: number, z: number) => {+ if (x < s.box.min.x || x > s.box.max.x || y < s.box.min.y || y > s.box.max.y || z < s.box.min.z || z > s.box.max.z) return false;+ const e = s.inv, px = e[0] * x + e[4] * y + e[8] * z + e[12], py = e[1] * x + e[5] * y + e[9] * z + e[13], pz = e[2] * x + e[6] * y + e[10] * z + e[14];+ const lb = s.lbox; if (px < lb.min.x || px > lb.max.x || py < lb.min.y || py > lb.max.y || pz < lb.min.z || pz > lb.max.z) return false;+ const t = s.tris; let k = 0;+ for (let i = 0; i < t.length; i += 9) { // Moller-Trumbore, both faces+ const ax = t[i], ay = t[i + 1], az = t[i + 2], e1x = t[i + 3] - ax, e1y = t[i + 4] - ay, e1z = t[i + 5] - az, e2x = t[i + 6] - ax, e2y = t[i + 7] - ay, e2z = t[i + 8] - az;+ const hx = DY * e2z - DZ * e2y, hy = DZ * e2x - DX * e2z, hz = DX * e2y - DY * e2x, det = e1x * hx + e1y * hy + e1z * hz;+ if (det > -1e-12 && det < 1e-12) continue;+ const f = 1 / det, sx = px - ax, sy = py - ay, sz = pz - az, u = f * (sx * hx + sy * hy + sz * hz); if (u < 0 || u > 1) continue;+ const qx = sy * e1z - sz * e1y, qy = sz * e1x - sx * e1z, qz = sx * e1y - sy * e1x, v = f * (DX * qx + DY * qy + DZ * qz); if (v < 0 || u + v > 1) continue;+ if (f * (e2x * qx + e2y * qy + e2z * qz) > 0) k++;+ }+ return (k & 1) === 1;+};++// ---------------------------------------------------------------- proximity (two rigs clipping)+export type ProximityOpts = { frame?: number; tol?: number; minPoints?: number; spacing?: number; exempt?: Obj[]; deep?: boolean; kind?: string };+/**+ * Do two things touch or pass through each other? A spatial hash of A's surface points; B's surface+ * points within `tol` of one are counted, and (deep) B's points sunk inside A's closed parts. A+ * finding names the hit centre and the parts on both sides. `exempt` subtrees (a held prop, the+ * holding hand) are skipped on either side. Default tol: 2% of the larger one's height.+ */+export const proximity = (rigA: Rig | Obj, rigB: Rig | Obj, exempt: Obj[] = [], o: ProximityOpts = {}): CheckResult => {+ const A = objOf(rigA), B = objOf(rigB), ex = [...exempt, ...(o.exempt ?? [])], skip = (m: THREE.Mesh) => ex.some((e) => within(m, e));+ A.updateWorldMatrix(true, true); B.updateWorldMatrix(true, true);+ let ma = meshesOf(A, skip).filter((m) => !within(m, B)), mb = meshesOf(B, skip).filter((m) => !within(m, A));+ if (!ma.length || !mb.length) return result([]);+ const boxOf = (ms: THREE.Mesh[]) => { const b = new THREE.Box3(); ms.forEach((m) => b.expandByObject(m)); return b; };+ const bA = boxOf(ma), bB = boxOf(mb);+ const tol = o.tol ?? 0.02 * Math.max(bA.getSize(v3()).y, bB.getSize(v3()).y), sp = o.spacing ?? tol * 0.75, minN = o.minPoints ?? 12;+ // boxes only PRUNE (a part whose box is nowhere near the other side cannot touch it); they never decide a hit+ bA.expandByScalar(tol); bB.expandByScalar(tol);+ ma = ma.filter((m) => new THREE.Box3().setFromObject(m).intersectsBox(bB)); mb = mb.filter((m) => new THREE.Box3().setFromObject(m).intersectsBox(bA));+ if (!ma.length || !mb.length) return result([]);+ const cell = new Map<number, number[]>(), c = (u: number) => Math.floor(u / tol), key = (x: number, y: number, z: number) => ((x * 73856093) ^ (y * 19349663) ^ (z * 83492791)) | 0;+ const AP: number[] = [], AN: string[] = [];+ for (const m of ma) { const w = worldPts(m, sp), nm = partName(m); for (let i = 0; i < w.length; i += 3) { const id = AP.length / 3; AP.push(w[i], w[i + 1], w[i + 2]); AN.push(nm); const k = key(c(w[i]), c(w[i + 1]), c(w[i + 2])); let l = cell.get(k); if (!l) cell.set(k, (l = [])); l.push(id); } }+ let n = 0; const hitC = v3(), partsA: Record<string, number> = {}, partsB: Record<string, number> = {}, t2 = tol * tol;+ const solids = o.deep === false ? [] : ma.filter(isClosed).map(solidOf);+ for (const m of mb) {+ const w = worldPts(m, sp), pb = partName(m);+ for (let i = 0; i < w.length; i += 3) {+ const x = w[i], y = w[i + 1], z = w[i + 2], X = c(x), Y = c(y), Z = c(z); let near: string | null = null;+ for (let a = -1; a <= 1 && !near; a++) for (let b = -1; b <= 1 && !near; b++) for (let d = -1; d <= 1 && !near; d++) for (const id of cell.get(key(X + a, Y + b, Z + d)) ?? []) { const dx = AP[id * 3] - x, dy = AP[id * 3 + 1] - y, dz = AP[id * 3 + 2] - z; if (dx * dx + dy * dy + dz * dz < t2) { near = AN[id]; break; } }+ if (!near) for (const sd of solids) if (insideSolid(sd, x, y, z)) { near = sd.name + " (inside)"; break; }+ if (near) { n++; hitC.x += x; hitC.y += y; hitC.z += z; partsA[near] = (partsA[near] ?? 0) + 1; partsB[pb] = (partsB[pb] ?? 0) + 1; }+ }+ }+ if (n < minN) return result([]);+ const top = (r: Record<string, number>) => Object.entries(r).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([k, x]) => `${k} ${x}`).join(", ");+ return result([{ frame: o.frame ?? 0, kind: o.kind ?? "proximity", where: `${A.name || "A"} / ${B.name || "B"} at ${fmt(hitC.divideScalar(n))}`, detail: `${n} surface points within ${tol.toFixed(3)} (A: ${top(partsA)}; B: ${top(partsB)})` }]);+};++/** A rig's own limbs through its own body (an arm swung through the belly): lower bones and ends against the torso. */+export const selfClear = (rig: Rig, o: { frame?: number; tol?: number; minPoints?: number } = {}): CheckResult => {+ const f: Finding[] = [];+ for (const L of Object.values(rig.limbs)) {+ // the far half only: the upper bone and the root joint sit in the shoulder by design+ const meshes = [L.lower, ...meshesOf(L.end)];+ const r = proximityMeshes(meshes, meshesOf(rig.body), { tol: o.tol ?? 0.004, minPoints: o.minPoints ?? 6, frame: o.frame ?? 0, where: `${rig.name}: ${L.name} into its own body` });+ f.push(...r);+ }+ return result(f);+};+const proximityMeshes = (mb: THREE.Mesh[], ma: THREE.Mesh[], o: { tol: number; minPoints: number; frame: number; where: string }): Finding[] => {+ let n = 0; const at = v3(), parts: Record<string, number> = {}, solids = ma.filter(isClosed).map(solidOf);+ for (const m of mb) { const w = worldPts(m, o.tol * 3); for (let i = 0; i < w.length; i += 3) for (const sd of solids) if (insideSolid(sd, w[i], w[i + 1], w[i + 2])) { n++; at.x += w[i]; at.y += w[i + 1]; at.z += w[i + 2]; parts[sd.name] = (parts[sd.name] ?? 0) + 1; break; } }+ return n >= o.minPoints ? [{ frame: o.frame, kind: "self", where: `${o.where} at ${fmt(at.divideScalar(n))}`, detail: `${n} points inside ${Object.keys(parts).join(", ")}` }] : [];+};++// ---------------------------------------------------------------- grips+export type GripOpts = { tol?: number; contact?: number; minTouch?: number; closing?: boolean; others?: Obj[] };+const onScreen = (p: V3, cam: THREE.Camera, m = 0.98) => { const q = p.clone().project(cam); return q.z < 1 && q.z > -1 && Math.abs(q.x) < m && Math.abs(q.y) < m; };+const handPart = (prop: Obj, m: THREE.Mesh) => !!m.userData.handlePart || (within(m, prop) && !!(m.parent && m.parent.userData.handlePart));+/**+ * Is the prop really held? (1) the hand's grip point is on the handle (within tol); (2) the hand is+ * closed on it: enough of its surface just outside the handle; (3) the handle does not run through+ * the hand (points inside the handle's core) or (4) through the holder's own body; (5) the prop's+ * body is not pushed into the holder; and with a camera, (6) the grip is in frame when the prop is,+ * and (7) not hidden behind the holder, the prop or another rig. `closing`: the hand is still on its+ * way, so only "through the hand" and "through the holder" apply.+ */+export const checkGrip = (holder: Rig | Obj, hand: Limb | Obj, prop: Obj, frame = 0, camera?: THREE.Camera, o: GripOpts = {}): CheckResult => {+ const H = objOf(holder), end = isLimb(hand) ? hand.end : hand, F: Finding[] = [], where = `${H.name || "holder"} holding ${prop.name || "prop"}`;+ H.updateWorldMatrix(true, true); prop.updateWorldMatrix(true, true);+ // Hidden objects never count: a prop switched off, inside a hidden group, or still scaled to almost+ // nothing (popIn starts at 2.2e-16) is not held yet, so there is nothing to judge.+ const sc = prop.getWorldScale(v3()).x;+ if (!shown(prop) || !(Math.abs(sc) >= 1e-3 * Math.abs(H.getWorldScale(v3()).x))) return result([]);+ const h = handleOf(prop), a = prop.localToWorld(h.a.clone()), b = prop.localToWorld(h.b.clone()), r = h.r * sc;+ const { point: gp } = gripFrame(hand);+ const handMeshes = meshesOf(end), handPts = handMeshes.flatMap((m) => surfacePoints(m, r * 0.6));+ const handR = handPts.reduce((mx, p) => Math.max(mx, p.distanceTo(gp)), 0);+ const tol = o.tol ?? Math.max(r * 3, handR * 0.25);+ const gap = segDist(gp, a, b);+ let inside = 0, touch = 0;+ for (const p of handPts) { const d = segDist(p, a, b); if (d < r * 0.5) inside++; else if (d < r + (o.contact ?? Math.max(r * 2.5, handR * 0.6))) touch++; }+ if (!o.closing && gap > tol) F.push({ frame, kind: "grip-gap", where, detail: `the grip point is ${gap.toFixed(3)} from the handle (tolerance ${tol.toFixed(3)}): the prop floats off the hand` });+ if (!o.closing && touch < (o.minTouch ?? 8)) F.push({ frame, kind: "grip-open", where, detail: `only ${touch} hand points close on the handle: it reads as not held` });+ if (inside > 6) F.push({ frame, kind: "grip-through-hand", where, detail: `${inside} hand points inside the handle: the handle passes through the hand` });+ // the handle through the holder: body points on the handle's line, away from the hand+ const body = meshesOf(H, (m) => within(m, end) || within(m, prop));+ let thru = 0; const thruParts: Record<string, number> = {}, reachBox = new THREE.Box3().setFromPoints([a, b]).expandByScalar(r * 1.2);+ // along the handle: samples sunk inside a closed part of the holder (a body's big flat faces are+ // sampled sparsely, so this side of the test is the one that never misses a pole through a torso)+ const solids = body.filter((m) => isClosed(m) && new THREE.Box3().setFromObject(m).intersectsBox(reachBox)).map(solidOf), L = a.distanceTo(b), nS = Math.max(2, Math.ceil(L / r));+ for (let i = 0; i <= nS; i++) { const p = a.clone().lerp(b, i / nS); if (p.distanceTo(gp) <= handR) continue; for (const sd of solids) if (insideSolid(sd, p.x, p.y, p.z)) { thru++; thruParts[sd.name] = (thruParts[sd.name] ?? 0) + 1; break; } }+ for (const m of body) { if (!new THREE.Box3().setFromObject(m).intersectsBox(reachBox)) continue; const w = worldPts(m, r); for (let i = 0; i < w.length; i += 3) { const dx = w[i] - gp.x, dy = w[i + 1] - gp.y, dz = w[i + 2] - gp.z; if (dx * dx + dy * dy + dz * dz > handR * handR && segDistXYZ(w[i], w[i + 1], w[i + 2], a, b) < r * 1.2) { thru++; thruParts[partName(m)] = (thruParts[partName(m)] ?? 0) + 1; } } }+ if (thru > 3) F.push({ frame, kind: "grip-through-holder", where, detail: `the handle runs through the holder (${Object.entries(thruParts).map(([k, x]) => `${k} ${x}`).join(", ")})` });+ // the prop's body pushed into the holder (a lantern in the belly)+ const pr = proximity(H, prop, [end, ...meshesOf(prop).filter((m) => handPart(prop, m))], { frame, minPoints: 6, kind: "grip-prop-in-holder" });+ F.push(...pr.findings);+ if (camera) {+ camera.updateMatrixWorld();+ const eye = camera.getWorldPosition(v3());+ if (!o.closing && onScreen(new THREE.Box3().setFromObject(prop).getCenter(v3()), camera) && !onScreen(gp, camera)) F.push({ frame, kind: "grip-offscreen", where, detail: "the prop is in frame but the hand holding it is not: it reads as dropped" });+ if (onScreen(gp, camera)) {+ const occ = [...body, ...meshesOf(prop, (m) => handPart(prop, m)), ...(o.others ?? []).flatMap((x) => meshesOf(x))];+ const ax = b.clone().sub(a).normalize(); let hid = 0, centre = false, what = "";+ for (const t of [-1, -0.5, 0, 0.5, 1]) {+ const pt = gp.clone().addScaledVector(ax, t * handR * 0.8), dir = pt.clone().sub(eye), L = dir.length();+ const hit = new THREE.Raycaster(eye, dir.normalize(), 0, L - handR * 0.6).intersectObjects(occ, false)[0];+ if (hit) { hid++; if (t === 0) centre = true; what = partName(hit.object as THREE.Mesh); }+ }+ if (centre || hid >= 3) F.push({ frame, kind: "grip-hidden", where, detail: `the grip is hidden behind ${what} (${hid}/5 points along the hold)` });+ }+ }+ return result(F);+};++// ---------------------------------------------------------------- paths through set props+export type PathSpec = { at: (f: number) => V3; from: number; to: number; step?: number; radius: number; height?: number; name?: string };+export type PropBox = { name: string; box: THREE.Box3 | Obj; open?: boolean };+/**+ * Does a character walk through a set prop (a closed gate, a crate)? The character is an upright+ * cylinder of `radius` and `height` standing on path.at(f); props are boxes (or objects, boxed).+ * An `open` prop (a gate swung open) is skipped. One finding per run of colliding frames.+ */+export const pathClear = (path: PathSpec, props: PropBox[]): CheckResult => {+ const F: Finding[] = [], hgt = path.height ?? 1, st = path.step ?? 1;+ const boxes = props.filter((p) => !p.open).map((p) => ({ name: p.name, b: (p.box as THREE.Box3).isBox3 ? (p.box as THREE.Box3) : new THREE.Box3().setFromObject(p.box as Obj) }));+ for (const { name, b } of boxes) {+ let run: number[] = [], worst = 0;+ const flush = () => { if (run.length) F.push({ frame: run[0], kind: "path", where: `${path.name ?? "character"} through ${name}`, detail: `frames ${run[0]}-${run[run.length - 1]}: ${worst.toFixed(3)} into it` }); run = []; worst = 0; };+ for (let f = path.from; f <= path.to; f += st) {+ const p = path.at(f), dx = Math.max(b.min.x - p.x, 0, p.x - b.max.x), dz = Math.max(b.min.z - p.z, 0, p.z - b.max.z), d = Math.hypot(dx, dz);+ const yHit = p.y < b.max.y && p.y + hgt > b.min.y;+ if (yHit && d < path.radius) { run.push(f); worst = Math.max(worst, path.radius - d); } else flush();+ }+ flush();+ }+ return result(F);+};++// ---------------------------------------------------------------- labels+export type Label = { obj: Obj; w: number; h: number; name: string };+const LABEL_PTS: [number, number][] = [[0, 0], [-0.42, 0.38], [0.42, 0.38], [-0.42, -0.38], [0.42, -0.38], [-0.42, 0], [0.42, 0], [0, 0.38], [0, -0.38]];+/**+ * Can the label be read? Nine points on it (its local xy plane, w x h, facing +z) are raycast from+ * the camera past `occluders`; any hidden point, a label turned more than ~70 degrees from the lens,+ * or one out of frame is a finding.+ */+export const labelVisible = (label: Label, camera: THREE.Camera, occluders: Obj[], frame = 0): CheckResult => {+ const F: Finding[] = [], occ = occluders.flatMap((o) => meshesOf(o, (m) => within(m, label.obj)));+ label.obj.updateWorldMatrix(true, true); camera.updateMatrixWorld();+ const eye = camera.getWorldPosition(v3()); let hid = 0, off = 0; const what = new Set<string>();+ for (const [x, y] of LABEL_PTS) {+ const pt = label.obj.localToWorld(v3(x * label.w, y * label.h, 0.001)), dir = pt.clone().sub(eye), L = dir.length();+ if (!onScreen(pt, camera, 1)) { off++; continue; }+ const hit = new THREE.Raycaster(eye, dir.normalize(), 0, L - 1e-3).intersectObjects(occ, false)[0];+ if (hit) { hid++; what.add(partName(hit.object as THREE.Mesh)); }+ }+ const nrm = v3(0, 0, 1).transformDirection(label.obj.matrixWorld), toEye = eye.clone().sub(label.obj.getWorldPosition(v3())).normalize();+ if (off) F.push({ frame, kind: "label-offscreen", where: label.name, detail: `${off}/9 points of the label out of frame` });+ if (hid) F.push({ frame, kind: "label-hidden", where: label.name, detail: `${hid}/9 points hidden behind ${[...what].join(", ")}` });+ if (nrm.dot(toEye) < 0.35) F.push({ frame, kind: "label-turned", where: label.name, detail: `the label faces ${(Math.acos(Math.max(-1, Math.min(1, nrm.dot(toEye)))) * 180 / Math.PI).toFixed(0)} degrees from the lens` });+ return result(F);+};+/** Turn a label about its parent's up so its face points at the camera (a tag on a string, a sign). */+export const faceCamera = (obj: Obj, camera: THREE.Camera) => {+ obj.updateWorldMatrix(true, false); camera.updateMatrixWorld();+ const par = obj.parent, eye = camera.getWorldPosition(v3()), at = par ? par.worldToLocal(eye.clone()) : eye.clone();+ obj.rotation.set(0, Math.atan2(at.x - obj.position.x, at.z - obj.position.z), 0);+ obj.updateWorldMatrix(false, true);+};+/**+ * AFTER THE CAMERA: place a label where it reads. Each try sets the label's transform from scratch+ * (slide along a handle, swing round, shorten the string); the first that passes labelVisible wins.+ * If none passes, the last try stays and its findings are returned. Run it after the frame's camera+ * is set, never before (lesson 42: a tag reading "/co act" because a claw covered two letters).+ */+export const placeLabel = (label: Label, camera: THREE.Camera, occluders: Obj[], tries: ((obj: Obj, k: number) => void)[], frame = 0) => {+ let last = result([]);+ for (let k = 0; k < tries.length; k++) { tries[k](label.obj, k); label.obj.updateWorldMatrix(true, true); last = labelVisible(label, camera, occluders, frame); if (last.ok) return { ...last, pick: k }; }+ return { ...last, pick: -1 };+};++// ---------------------------------------------------------------- screen size+/**+ * Is it big enough to read? The object's box projected through the camera, its larger side in+ * pixels at 1080p (a 4K or 720p film is scaled to 1080 lines). A contact beat (a hand on a handle)+ * needs about 40 px, or the acting reads as nothing (lesson 25).+ */+export const screenSizeOk = (object: Obj, camera: THREE.Camera, env: { W: number; H: number }, minPx = 40, frame = 0): CheckResult & { px: number } => {+ object.updateWorldMatrix(true, true); camera.updateMatrixWorld();+ const pts = meshesOf(object).flatMap((m) => surfacePoints(m, 1e9));+ if (!pts.length) return { ...result([{ frame, kind: "screen-size", where: object.name || "object", detail: "nothing visible to measure" }]), px: 0 };+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;+ for (const p of pts) { const q = p.clone().project(camera); const x = ((q.x + 1) / 2) * env.W, y = ((1 - q.y) / 2) * env.H; x0 = Math.min(x0, x); x1 = Math.max(x1, x); y0 = Math.min(y0, y); y1 = Math.max(y1, y); }+ const px = (Math.max(x1 - x0, y1 - y0) * 1080) / env.H;+ return { ...result(px >= minPx ? [] : [{ frame, kind: "screen-size", where: object.name || "object", detail: `${px.toFixed(0)} px at 1080p, under ${minPx}: the action will not read` }]), px };+};++// ---------------------------------------------------------------- the per-frame registry+// A draw registers what this frame holds; runChecks reads it and clears it. Module state, but reset+// at the start of every draw (resetChecks) and at the end of every run, so no frame sees another's.+type Reg = { rigs: { name: string; obj: Obj; rig?: Rig }[]; grips: { holder: Rig | Obj; hand: Limb | Obj; prop: Obj; o: GripOpts }[]; labels: Label[]; sizes: { obj: Obj; minPx: number }[]; paths: { path: PathSpec; props: PropBox[] }[] };+let REG: Reg = { rigs: [], grips: [], labels: [], sizes: [], paths: [] };+/** What a host learns besides the findings: each registered grip's point on screen (logical px), for crop boards and for sampling contact windows. */+export type CheckInfo = { grips: { name: string; x: number; y: number }[] };+const G = globalThis as { __ANIDOODLE_CHECK3D__?: (frame: number, findings: Finding[], info: CheckInfo) => void };+/** True while a host or a test is collecting 3D findings. Draws skip the checks otherwise: no cost. */+export const checking = () => typeof G.__ANIDOODLE_CHECK3D__ === "function";+export const resetChecks = () => { REG = { rigs: [], grips: [], labels: [], sizes: [], paths: [] }; };+/** A character (or any object) the proximity check pairs with every other registered one. */+export const registerRig = (name: string, rig: Rig | Obj) => { const obj = objOf(rig); obj.name ||= name; REG.rigs.push({ name, obj, rig: "limbs" in rig ? (rig as Rig) : undefined }); };+/** A held prop: checked by checkGrip, and exempt (with its hand) from proximity between holder and prop. */+export const registerGrip = (holder: Rig | Obj, hand: Limb | Obj, prop: Obj, o: GripOpts = {}) => { REG.grips.push({ holder, hand, prop, o }); };+export const registerLabel = (label: Label) => { REG.labels.push(label); };+export const registerSize = (obj: Obj, minPx = 40) => { REG.sizes.push({ obj, minPx }); };+export const registerPath = (path: PathSpec, props: PropBox[]) => { REG.paths.push({ path, props }); };+/**+ * Run every registered check on this frame and hand the findings to the collector (when one is+ * listening). Proximity runs for every pair of registered rigs, with held props and their hands+ * exempt between holder and prop; selfClear runs for every registered rig.+ */+export const runChecks = (frame: number, camera: THREE.Camera, env: { W: number; H: number }, o: { proximity?: ProximityOpts } = {}): CheckResult => {+ const F: Finding[] = [];+ const others = (h: Obj) => REG.rigs.map((r) => r.obj).filter((x) => x !== h && !REG.grips.some((g) => g.prop === x));+ for (const g of REG.grips) F.push(...checkGrip(g.holder, g.hand, g.prop, frame, camera, { others: others(objOf(g.holder)), ...g.o }).findings);+ for (let i = 0; i < REG.rigs.length; i++) for (let j = i + 1; j < REG.rigs.length; j++) {+ // two set props touching (a lantern standing on a crate) is staging; a pair needs a character in it+ if (!REG.rigs[i].rig && !REG.rigs[j].rig) continue;+ const A = REG.rigs[i].obj, B = REG.rigs[j].obj, ex: Obj[] = [];+ for (const g of REG.grips) { const H = objOf(g.holder); if ((H === A && g.prop === B) || (H === B && g.prop === A)) ex.push(isLimb(g.hand) ? g.hand.end : g.hand, ...meshesOf(g.prop).filter((m) => handPart(g.prop, m))); }+ F.push(...proximity(A, B, ex, { ...o.proximity, frame }).findings);+ }+ for (const r of REG.rigs) if (r.rig) F.push(...selfClear(r.rig, { frame }).findings);+ for (const l of REG.labels) F.push(...labelVisible(l, camera, REG.rigs.map((r) => r.obj), frame).findings);+ for (const s of REG.sizes) F.push(...screenSizeOk(s.obj, camera, env, s.minPx, frame).findings);+ for (const p of REG.paths) F.push(...pathClear({ ...p.path, from: frame, to: frame }, p.props).findings.map((x) => ({ ...x, frame })));+ const info: CheckInfo = { grips: REG.grips.map((g) => { const q = gripFrame(g.hand).point.project(camera); return { name: `${objOf(g.holder).name || "holder"}/${g.prop.name || "prop"}`, x: ((q.x + 1) / 2) * env.W, y: ((1 - q.y) / 2) * env.H }; }) };+ resetChecks();+ if (checking()) G.__ANIDOODLE_CHECK3D__!(frame, F, info);+ return result(F);+};+/** Collect the findings of everything `run` draws (a test, a host's check pass). */+export const collectChecks = (run: () => void): Finding[] => {+ const out: Finding[] = [], prev = G.__ANIDOODLE_CHECK3D__;+ G.__ANIDOODLE_CHECK3D__ = (_f, fs) => { out.push(...fs); };+ try { run(); } finally { if (prev) G.__ANIDOODLE_CHECK3D__ = prev; else delete G.__ANIDOODLE_CHECK3D__; }+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/look.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/look.tsnew file mode 100644index 0000000..032e323--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/look.ts@@ -0,0 +1,271 @@+// LOOK. Light rigs, materials and finishing passes that read as DESIGNED, not as default CG. Every+// default here answers one of the "cheap 3D" tells (lessons 8, 35, 45, 47 in the Clawd film notes):+//+// shadow acne -> contactShadow() (a soft blob, no shadow map at all), and softShadows()+// with a bias worked out from the shadow map's texel size when a shot wants+// real cast shadows+// harsh self-shadow -> rigs are three lights + a sky fill, so no side of a form drops to black+// plastic shine -> matte/satin keep specular low and wide; nothing defaults to a mirror+// jaggies -> draw3d supersamples (stage ss 2); outlines are hulls, not 1 px GL lines+// black crush -> every rig carries a hemisphere fill, toon ramps start at 0.38, the+// vignette darkens toward a tinted colour, never to pure black+//+// lights: studio() night() interior() sunset() -> a LightRig; scene.add(rig.group)+// materials: matte(c) satin(c) toon(c, steps) glass(o) emissiveGlow(c, k)+// ink: outline(mesh, width, color, o) -> inverted hull, animatable width+// ground: contactShadow(size, softness, o) -> a soft shadow plane, no shadow map+// shadows: softShadows(light, o) -> acne-free cast shadows when wanted+// post (2D): grain(ctx, env, frame, amount, seed, cell) vignette(ctx, env, amount) after draw3d+import * as THREE from "three";+import type { Ctx, Env, Layer } from "../canvas-core/core";+import { rand } from "./stage";++// ---------------------------------------------------------------- light rigs+export type LightRig = { group: THREE.Group; key: THREE.Light; fill: THREE.Light; rim: THREE.Light; sky: THREE.HemisphereLight; practical?: THREE.PointLight };+export type RigOpts = { /** multiplies every light. Default 1 */ intensity?: number; /** where the directional lights aim. Default the origin */ at?: THREE.Vector3Like };++const dir = (g: THREE.Group, name: string, color: THREE.ColorRepresentation, k: number, p: [number, number, number], at: THREE.Vector3Like) => {+ const l = new THREE.DirectionalLight(color, k); l.name = name; l.position.set(p[0] + at.x, p[1] + at.y, p[2] + at.z);+ l.target.position.set(at.x, at.y, at.z); g.add(l, l.target); return l;+};+const rig = (name: string, o: RigOpts, build: (g: THREE.Group, k: number, at: THREE.Vector3Like) => Omit<LightRig, "group">): LightRig => {+ const g = new THREE.Group(); g.name = `rig:${name}`;+ const parts = build(g, o.intensity ?? 1, o.at ?? { x: 0, y: 0, z: 0 });+ return { group: g, ...parts };+};++/** Product-shot light: a warm key high and to the right, a cool fill from the left, a rim from behind that separates the form from the backdrop, and a soft sky so the shadow side keeps its colour. */+export const studio = (o: RigOpts = {}): LightRig => rig("studio", o, (g, k, at) => {+ const key = dir(g, "key", "#fff1de", 2.4 * k, [4, 6, 6], at);+ const fill = dir(g, "fill", "#dfe8ff", 0.75 * k, [-6, 2, 4], at);+ const rim = dir(g, "rim", "#ffffff", 1.9 * k, [-1.5, 4, -7], at);+ const sky = new THREE.HemisphereLight("#f3f1ff", "#6b5a52", 0.85 * k); sky.name = "sky"; g.add(sky);+ return { key, fill, rim, sky };+});+/** Night exterior: a cool, low moon key, a blue sky fill that keeps shadows readable (blue, not black), and a warm rim like a street lamp behind. */+export const night = (o: RigOpts = {}): LightRig => rig("night", o, (g, k, at) => {+ const key = dir(g, "moon", "#b8c8ff", 1.3 * k, [-5, 7, 4], at);+ const fill = dir(g, "fill", "#5a6aa8", 0.5 * k, [6, 1, 3], at);+ const rim = dir(g, "lamp", "#ffc27a", 1.6 * k, [3, 3, -6], at);+ const sky = new THREE.HemisphereLight("#33407a", "#1d1a2b", 0.9 * k); sky.name = "sky"; g.add(sky);+ return { key, fill, rim, sky };+});+/** Interior (lesson 35): the key comes DOWN from a ceiling, a warm practical (a lamp) sits near the subject, and a warm hemisphere fill lifts the room. An outdoor rig left inside reads muddy. */+export const interior = (o: RigOpts = {}): LightRig => rig("interior", o, (g, k, at) => {+ const key = dir(g, "ceiling", "#fff4e6", 1.8 * k, [0.5, 8, 2], at);+ const fill = dir(g, "window", "#e4ecff", 0.6 * k, [-6, 3, 3], at);+ const rim = dir(g, "rim", "#ffe2bf", 1.1 * k, [2, 3, -6], at);+ const sky = new THREE.HemisphereLight("#ffe9d2", "#5a4337", 0.9 * k); sky.name = "sky"; g.add(sky);+ // decay 2 is physical: the lamp's pool falls off like a real lamp's; distance 0 = no hard cut-off+ const practical = new THREE.PointLight("#ffb86b", 6 * k, 0, 2); practical.name = "practical"; practical.position.set(at.x + 1.6, at.y + 1.4, at.z + 1.2); g.add(practical);+ return { key, fill, rim, sky, practical };+});+/** Golden hour: a low orange key from the side, a lilac sky fill, and a hot rim that outlines the form. */+export const sunset = (o: RigOpts = {}): LightRig => rig("sunset", o, (g, k, at) => {+ const key = dir(g, "sun", "#ffb070", 2.6 * k, [7, 1.6, 3], at);+ const fill = dir(g, "fill", "#b9a3ff", 0.7 * k, [-6, 3, 4], at);+ const rim = dir(g, "rim", "#ffd29a", 2.2 * k, [-3, 2.5, -7], at);+ const sky = new THREE.HemisphereLight("#ffd6c2", "#4a3550", 0.8 * k); sky.name = "sky"; g.add(sky);+ return { key, fill, rim, sky };+});++// ---------------------------------------------------------------- materials+/** chalky, no highlight to speak of: paper, clay, felt-ish props, floors */+export const matte = (color: THREE.ColorRepresentation) => new THREE.MeshStandardMaterial({ color, roughness: 0.92, metalness: 0 });+/** a soft, wide sheen that catches a rim light without the hard white dot of plastic */+export const satin = (color: THREE.ColorRepresentation) => {+ const c = new THREE.Color(color);+ return new THREE.MeshPhysicalMaterial({ color: c, roughness: 0.5, metalness: 0, specularIntensity: 0.35, sheen: 0.35, sheenRoughness: 0.55, sheenColor: c.clone().lerp(new THREE.Color("#ffffff"), 0.5) });+};+/**+ * The toon ramp as numbers: `steps` flat bands of light from `floor` (the shadow side, kept well+ * above black so it never crushes) up to full light. Pure, so the test can hold it.+ */+export const toonRamp = (steps: number, floor = 0.38): number[] => {+ const n = Math.max(2, Math.round(steps));+ return Array.from({ length: n }, (_, i) => floor + ((1 - floor) * i) / (n - 1));+};+/** cel shading in `steps` flat bands (2 = graphic, 3 = classic cartoon, 4-5 = soft) */+export const toon = (color: THREE.ColorRepresentation, steps = 3, floor = 0.38) => {+ const ramp = toonRamp(steps, floor), data = new Uint8Array(ramp.length * 4);+ ramp.forEach((v, i) => data.set([Math.round(v * 255), Math.round(v * 255), Math.round(v * 255), 255], i * 4));+ const tex = new THREE.DataTexture(data, ramp.length, 1, THREE.RGBAFormat);+ // Nearest, no mipmaps: the bands must stay hard-edged; linear filtering blends them into a gradient+ tex.minFilter = THREE.NearestFilter; tex.magFilter = THREE.NearestFilter; tex.generateMipmaps = false; tex.needsUpdate = true;+ return new THREE.MeshToonMaterial({ color, gradientMap: tex });+};+export type GlassOpts = { tint?: THREE.ColorRepresentation; ior?: number; thickness?: number; roughness?: number };+/**+ * Glass that reads as glass (lesson 47): ONE front-facing refracting surface, thin, low IOR. A+ * double-sided thick transmission draws the back wall as a second, offset outline.+ */+export const glass = (o: GlassOpts = {}) => new THREE.MeshPhysicalMaterial({+ color: "#ffffff", metalness: 0, roughness: o.roughness ?? 0.04, transmission: 1, thickness: o.thickness ?? 0.06, ior: o.ior ?? 1.15,+ attenuationColor: new THREE.Color(o.tint ?? "#eaf4ff"), attenuationDistance: 1.5, specularIntensity: 1, side: THREE.FrontSide,+});+/** a light that IS its colour (a firefly, a screen, a lamp bulb): unlit, outside tone mapping, and never fogged (lesson 45: far glows told by size, not by greying) */+export const emissiveGlow = (color: THREE.ColorRepresentation, intensity = 1) =>+ new THREE.MeshBasicMaterial({ color: new THREE.Color(color).multiplyScalar(intensity), fog: false, toneMapped: false });++// ---------------------------------------------------------------- outline (inverted hull)+/**+ * Averaged normals per POSITION, so the hull is pushed out as one closed skin. With the geometry's+ * own split normals (every extruded letter, every box) the hull tears open at hard edges.+ */+export const hullNormals = (geo: THREE.BufferGeometry): THREE.BufferAttribute => {+ const have = geo.getAttribute("outlineNormal") as THREE.BufferAttribute | undefined; if (have) return have;+ const pos = geo.getAttribute("position"), idx = geo.getIndex(), n = pos.count, sum = new Map<string, THREE.Vector3>();+ const key = (i: number) => `${Math.round(pos.getX(i) * 1e4)},${Math.round(pos.getY(i) * 1e4)},${Math.round(pos.getZ(i) * 1e4)}`;+ const tri = idx ? idx.count / 3 : n / 3, a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();+ for (let t = 0; t < tri; t++) {+ const i0 = idx ? idx.getX(t * 3) : t * 3, i1 = idx ? idx.getX(t * 3 + 1) : t * 3 + 1, i2 = idx ? idx.getX(t * 3 + 2) : t * 3 + 2;+ a.fromBufferAttribute(pos, i0); b.fromBufferAttribute(pos, i1); c.fromBufferAttribute(pos, i2);+ // ANGLE-weighted: each face counts by the corner angle it makes at the vertex, so a box corner+ // points along the true diagonal however its faces were cut into triangles (area weighting does not)+ const f = new THREE.Vector3().subVectors(c, b).cross(new THREE.Vector3().subVectors(a, b));+ if (f.lengthSq() === 0) continue;+ f.normalize();+ const corner = [[a, b, c], [b, c, a], [c, a, b]] as const;+ [i0, i1, i2].forEach((i, n2) => { const [p, q, r] = corner[n2]; const ang = new THREE.Vector3().subVectors(q, p).angleTo(new THREE.Vector3().subVectors(r, p)); const w = f.clone().multiplyScalar(ang), k = key(i), s = sum.get(k); if (s) s.add(w); else sum.set(k, w); });+ }+ const out = new Float32Array(n * 3);+ for (let i = 0; i < n; i++) { const s = (sum.get(key(i)) ?? new THREE.Vector3()).clone(); if (s.lengthSq() === 0) s.set(0, 0, 1); s.normalize(); out.set([s.x, s.y, s.z], i * 3); }+ const attr = new THREE.BufferAttribute(out, 3); geo.setAttribute("outlineNormal", attr); return attr;+};+export type OutlineOpts = {+ /** width in FRAME PIXELS (of a frameH-tall frame) instead of world units: stays the same on screen near and far (lesson 27) */+ screen?: boolean;+ /** the film's logical height for screen widths. Default 1080 */+ frameH?: number;+};+export type Outline = THREE.Mesh & { userData: { width: { value: number } } };+/**+ * An ink line around a mesh's silhouette: a slightly larger copy, back faces only, flat colour. It+ * is pushed out in VIEW space after the model transform, so a scaled letter keeps the same line+ * (no fat outline on a popped-up letter). Set `hull.userData.width.value` per frame to animate it+ * (outlinePulse). Added as a child of the mesh, so it follows every move.+ */+export const outline = (mesh: THREE.Mesh, width = 0.02, color: THREE.ColorRepresentation = "#1b1622", o: OutlineOpts = {}): Outline => {+ hullNormals(mesh.geometry);+ const uWidth = { value: width }, uScreen = { value: o.screen ? 1 : 0 }, uFrameH = { value: o.frameH ?? 1080 };+ const mat = new THREE.MeshBasicMaterial({ color, side: THREE.BackSide, toneMapped: false, fog: false });+ mat.onBeforeCompile = (sh) => {+ sh.uniforms.outlineWidth = uWidth; sh.uniforms.outlineScreen = uScreen; sh.uniforms.outlineFrameH = uFrameH;+ sh.vertexShader = "attribute vec3 outlineNormal;\nuniform float outlineWidth;\nuniform float outlineScreen;\nuniform float outlineFrameH;\n" + sh.vertexShader.replace("#include <project_vertex>", `+ vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );+ vec3 hullN = normalize( normalMatrix * outlineNormal );+ // screen mode: a pixel at depth -z spans 2 * z / (P[1][1] * frameH) world units+ float hullW = outlineScreen > 0.5 ? outlineWidth * 2.0 * max( -mvPosition.z, 0.0 ) / ( projectionMatrix[1][1] * outlineFrameH ) : outlineWidth;+ mvPosition.xyz += hullN * hullW;+ // and push the whole hull AWAY from the camera by more than it grew: long thin cap triangles+ // (every extruded letter has them) flip when their corners move apart, and a flipped one+ // would draw in front of the face as a black crack. Behind the face it is hidden; at the+ // silhouette, where the hull is seen beside the mesh, the push only moves it in depth.+ mvPosition.xyz += normalize( mvPosition.xyz ) * hullW * 2.5;+ gl_Position = projectionMatrix * mvPosition;`);+ };+ mat.customProgramCacheKey = () => "anidoodle-outline";+ const hull = new THREE.Mesh(mesh.geometry, mat) as unknown as Outline;+ hull.name = "outline"; hull.userData = { width: uWidth }; hull.castShadow = false; hull.receiveShadow = false;+ hull.raycast = () => {}; // never picked: it is ink, not an object+ mesh.add(hull);+ return hull;+};++// ---------------------------------------------------------------- contact shadow+/**+ * The contact shadow's opacity at normalised radius r (0 centre, 1 rim). `softness` 0 gives a+ * dense core with a quick edge, 1 an all-falloff haze. Exactly 0 from r = 1 on: no square edge.+ */+export const shadowAlpha = (r: number, softness = 0.6) => {+ if (r >= 1) return 0;+ const inner = (1 - Math.min(1, Math.max(0, softness))) * 0.55, t = r <= inner ? 0 : (r - inner) / (1 - inner);+ const s = t * t * (3 - 2 * t);+ return (1 - s) ** 1.6;+};+export type ContactOpts = { color?: THREE.ColorRepresentation; opacity?: number; /** x stretch: 2 = an oval twice as wide as deep (a word, a car) */ aspect?: number; res?: number };+/**+ * A soft shadow pool under an object: a flat plane with a radial falloff, no shadow map, so no+ * acne and no hard edge. Warm-dark by default (lesson 8: a coloured shadow band reads as designed;+ * grey-black reads as CG). Lay it a hair above the floor; it never writes depth.+ */+export const contactShadow = (size = 1, softness = 0.6, o: ContactOpts = {}): THREE.Mesh => {+ const res = o.res ?? 64, data = new Uint8Array(res * res * 4), c = new THREE.Color(o.color ?? "#3a2a35"), op = o.opacity ?? 0.55;+ for (let y = 0; y < res; y++) for (let x = 0; x < res; x++) {+ const u = ((x + 0.5) / res) * 2 - 1, v = ((y + 0.5) / res) * 2 - 1, a = shadowAlpha(Math.hypot(u, v), softness) * op;+ data.set([Math.round(c.r * 255), Math.round(c.g * 255), Math.round(c.b * 255), Math.round(a * 255)], (y * res + x) * 4);+ }+ const tex = new THREE.DataTexture(data, res, res, THREE.RGBAFormat);+ tex.magFilter = THREE.LinearFilter; tex.minFilter = THREE.LinearFilter; tex.needsUpdate = true;+ const mat = new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false, toneMapped: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 });+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(size * (o.aspect ?? 1), size), mat);+ mesh.rotation.x = -Math.PI / 2; mesh.name = "contactShadow"; mesh.renderOrder = 1;+ return mesh;+};++// ---------------------------------------------------------------- real shadows, acne-free+export type SoftShadowOpts = { /** half-width of the area the shadow covers, world units. Default 6 */ size?: number; mapSize?: number; near?: number; far?: number };+/**+ * Turn on cast shadows for a directional or spot light with values that do not acne. The biases+ * come from the shadow map's texel size (world units per texel = 2 * size / mapSize):+ * normalBias = 1.5 texels moves each lookup off the surface along its normal; this is what+ * kills acne on curved and grazing surfaces without detaching shadows+ * bias = -0.0002 a tiny depth offset for flat floors facing the light+ * Also draw3d(..., { shadows: true }), receiveShadow on floors, and (lesson 8) NOT on characters+ * or type, whose self-shadow creases read as cheap: give them contactShadow() instead.+ */+export const softShadows = (light: THREE.DirectionalLight | THREE.SpotLight, o: SoftShadowOpts = {}) => {+ const size = o.size ?? 6, map = o.mapSize ?? 2048, texel = (2 * size) / map;+ light.castShadow = true;+ light.shadow.mapSize.set(map, map);+ light.shadow.bias = -0.0002;+ light.shadow.normalBias = 1.5 * texel;+ light.shadow.radius = 3; // used by PCFShadowMap; PCFSoft (the stage default) softens on its own+ const cam = light.shadow.camera as THREE.OrthographicCamera;+ if ((cam as THREE.OrthographicCamera).isOrthographicCamera) { cam.left = -size; cam.right = size; cam.top = size; cam.bottom = -size; }+ cam.near = o.near ?? 0.5; cam.far = o.far ?? 40; cam.updateProjectionMatrix();+ return { texel, bias: light.shadow.bias, normalBias: light.shadow.normalBias };+};++// ---------------------------------------------------------------- 2D post on the finished frame+/**+ * The grain tile for one frame, as RGBA bytes: grey around 128 (no change under "overlay"), with a+ * triangular spread (two uniforms summed) that looks like film rather than TV static. Pure: the+ * same (seed, frame) always gives the same bytes; the next frame gives different ones.+ */+export const grainTile = (seed: number, frame: number, size = 256): Uint8ClampedArray => {+ const r = rand((seed * 2654435761 + Math.round(frame) * 40503) >>> 0), out = new Uint8ClampedArray(size * size * 4);+ for (let i = 0; i < out.length; i += 4) { const v = 128 + (r() + r() - 1) * 127; out[i] = out[i + 1] = out[i + 2] = v; out[i + 3] = 255; }+ return out;+};+/**+ * Film grain over the whole frame, new every frame, seeded by the frame (so frame 40 drawn first+ * or last is the same). amount 0-1: 0.03-0.06 is felt, not seen. Call after draw3d and any 2D+ * layers; overlay blending keeps mid-tones and leaves pure black and white alone.+ * cell: logical pixels per grain value (default 2). The tile is stretched with smoothing, so each+ * grain is a soft clump rather than a one-pixel speck: it still reads as film at 1x, and the encoder+ * no longer spends its bits on per-pixel noise (an 8 s 1080p film went from 69 MB to well under 25).+ */+export const grain = (ctx: Ctx, env: Env, frame: number, amount = 0.035, seed = 7, cell = 2) => {+ if (amount <= 0) return;+ const T = 256, key = `three:grain:${T}`, k = Math.max(1, cell);+ let layer = env.cache.get(key) as Layer | undefined;+ if (!layer) { layer = env.canvas(T, T); env.cache.set(key, layer); }+ const img = layer.ctx.createImageData(T, T); img.data.set(grainTile(seed, frame, T)); layer.ctx.putImageData(img, 0, 0);+ const pat = ctx.createPattern(layer.canvas as CanvasImageSource, "repeat"); if (!pat) return;+ ctx.save(); ctx.setTransform(env.scale * k, 0, 0, env.scale * k, 0, 0);+ ctx.globalCompositeOperation = "overlay"; ctx.globalAlpha = Math.min(1, amount * 3); ctx.imageSmoothingEnabled = true;+ ctx.fillStyle = pat; ctx.fillRect(0, 0, env.W / k, env.H / k);+ ctx.restore();+};+/** darken the corners toward a tinted dark (not black: lesson 8, black crush). amount 0-1, 0.3 is gentle */+export const vignette = (ctx: Ctx, env: Env, amount = 0.3, color = "#160f1e") => {+ if (amount <= 0) return;+ const c = new THREE.Color(color), rgb = `${Math.round(c.r * 255)},${Math.round(c.g * 255)},${Math.round(c.b * 255)}`;+ const cx = env.W / 2, cy = env.H / 2, R = Math.hypot(cx, cy);+ ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.globalCompositeOperation = "source-over"; ctx.globalAlpha = 1;+ const g = ctx.createRadialGradient(cx, cy, R * 0.45, cx, cy, R);+ g.addColorStop(0, `rgba(${rgb},0)`); g.addColorStop(0.6, `rgba(${rgb},${(amount * 0.45).toFixed(3)})`); g.addColorStop(1, `rgba(${rgb},${amount.toFixed(3)})`);+ ctx.fillStyle = g; ctx.fillRect(0, 0, env.W, env.H);+ ctx.restore();+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/mograph.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/mograph.tsnew file mode 100644index 0000000..861bd67--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/mograph.ts@@ -0,0 +1,243 @@+// MOGRAPH. Motion-graphics verbs for three objects, each a pure function of the frame:+// popIn(mesh, f, 24, 12) // at frame 24, over 12 frames+// A verb SETS the channels it owns from the object's rest pose every time it is called: before its+// start it writes the "before" state (usually hidden), after its end the exact rest ("after")+// state, so a frame never inherits anything from the frame drawn before it.+//+// - REST POSE. The pose an object was built in (position, rotation, scale, material opacity and+// emissive) is recorded the first time any verb touches it (or call keepRest() in the build).+// Verbs compute from that, never from the current values, so nothing accumulates.+// - ONE VERB PER CHANNEL. Two verbs that both write scale on one object: the later call wins. To+// layer a pop with an indicate, nest the mesh in a Group and give each its own object.+// - Seeds, never Math.random: explode, wiggle and the noise draw from a pure hash of (seed, index).+import * as THREE from "three";+import { ease as E, seg, spring, type Ease } from "./time";+import { hash01, noise1 } from "./camera";++type V3 = [number, number, number];+type Rest = { position: THREE.Vector3; quaternion: THREE.Quaternion; scale: THREE.Vector3; visible: boolean };+type MatRest = { opacity: number; transparent: boolean; emissive?: THREE.Color };+const REST = "anidoodleRest";++/** record an object's pose as its rest pose now (verbs do this on first touch; call it in a build that moves things later) */+export const keepRest = (o: THREE.Object3D): Rest => {+ if (!o.userData[REST]) o.userData[REST] = { position: o.position.clone(), quaternion: o.quaternion.clone(), scale: o.scale.clone(), visible: o.visible } as Rest;+ return o.userData[REST] as Rest;+};+const rest = keepRest;+const mats = (o: THREE.Object3D): THREE.Material[] => {+ const out: THREE.Material[] = [];+ o.traverse((c) => { const m = (c as THREE.Mesh).material; if (m) for (const x of Array.isArray(m) ? m : [m]) if (!out.includes(x)) out.push(x); });+ return out;+};+const matRest = (m: THREE.Material): MatRest => {+ if (!m.userData[REST]) { const em = (m as THREE.MeshStandardMaterial).emissive; m.userData[REST] = { opacity: m.opacity, transparent: m.transparent, emissive: em ? em.clone() : undefined } as MatRest; }+ return m.userData[REST] as MatRest;+};+const t01 = (f: number, at: number, len: number) => seg(f, at, at + len);+// a scale of exactly 0 gives singular normal matrices; hide instead+const showScaled = (o: THREE.Object3D, r: Rest, k: number, kz = k) => { o.visible = r.visible && k > 1e-4 && kz > 1e-4; o.scale.set(r.scale.x * k, r.scale.y * k, r.scale.z * kz); };++/** scale up from nothing with an overshoot that lands: the default entrance */+export const popIn = (o: THREE.Object3D, f: number, at: number, len = 12, e: Ease = E.outBack) => { const r = rest(o), t = t01(f, at, len); showScaled(o, r, t >= 1 ? 1 : Math.max(0, e(t))); };+/** scale down to nothing (anticipation first) */+export const popOut = (o: THREE.Object3D, f: number, at: number, len = 10) => { const r = rest(o), t = t01(f, at, len); showScaled(o, r, t <= 0 ? 1 : Math.max(0, 1 - E.inBack(t))); };+/**+ * Fall from `height` above rest, land at 40% of len, then squash and settle on a closed-form+ * spring (so it is seekable). Hidden before it starts.+ */+export const dropIn = (o: THREE.Object3D, f: number, at: number, len = 18, o2: { height?: number; squash?: number; fps?: number } = {}) => {+ const r = rest(o), land = at + Math.max(1, Math.round(len * 0.4)), h = o2.height ?? 3, sq = o2.squash ?? 0.28;+ o.position.copy(r.position);+ o.position.y += h * (1 - E.inQuad(seg(f, at, land)));+ // the spring rings from the landing; fade it to exactly 0 by the end so "after" is the rest pose+ const s = f >= at + len ? 0 : spring(f, land, o2.fps ?? 24, 3, 0.35) * sq * (1 - seg(f, land, at + len));+ o.scale.set(r.scale.x * (1 + s * 0.5), r.scale.y * (1 - s), r.scale.z * (1 + s * 0.5));+ o.visible = r.visible && f >= at;+};+/** rise out of the floor from `depth` below rest (hidden before it starts) */+export const riseFromFloor = (o: THREE.Object3D, f: number, at: number, len = 14, depth = 1, e: Ease = E.outCubic) => {+ const r = rest(o); o.position.copy(r.position); o.position.y -= depth * (1 - e(t01(f, at, len))); o.visible = r.visible && f >= at;+};+/** grow out of a point (in the parent's space): travel from it while scaling up */+export const growFrom = (o: THREE.Object3D, f: number, at: number, len: number, point: V3, e: Ease = E.outCubic) => {+ const r = rest(o), k = e(t01(f, at, len)); o.position.set(point[0], point[1], point[2]).lerp(r.position, k); showScaled(o, r, k);+};+const setOpacity = (o: THREE.Object3D, k: number) => {+ for (const m of mats(o)) {+ const mr = matRest(m);+ m.opacity = mr.opacity * k;+ // back to opaque when fully in, or sorting artefacts linger on a finished object+ const tr = k < 1 || mr.transparent;+ if (m.transparent !== tr) { m.transparent = tr; m.needsUpdate = true; }+ }+ o.visible = rest(o).visible && k > 0;+};+/** fade materials in (every material of every mesh below, arrays too) */+export const fadeIn = (o: THREE.Object3D, f: number, at: number, len = 12, e: Ease = E.inOutSine) => setOpacity(o, e(t01(f, at, len)));+/** fade materials out */+export const fadeOut = (o: THREE.Object3D, f: number, at: number, len = 12, e: Ease = E.inOutSine) => setOpacity(o, 1 - e(t01(f, at, len)));+/** type or a shape gaining its depth: scale z from a sliver to rest (real bevel-last extrusion is type3d's job) */+export const extrudeIn = (o: THREE.Object3D, f: number, at: number, len = 12, e: Ease = E.outCubic) => { const r = rest(o), t = t01(f, at, len); showScaled(o, r, t > 0 ? 1 : 0, 0.02 + 0.98 * e(t)); };++/**+ * Draw a path on from 0 to t (a fraction) with setDrawRange. A TubeGeometry draws whole tubular+ * segments (radialSegments * 6 indices each); a Line or Points draws whole vertices.+ */+export const drawTo = (mesh: THREE.Mesh | THREE.Line | THREE.Points, t: number) => {+ const g = mesh.geometry as THREE.BufferGeometry & { parameters?: { tubularSegments?: number; radialSegments?: number } };+ const k = Math.max(0, Math.min(1, t));+ if (g.parameters?.tubularSegments && g.parameters.radialSegments && g.index) g.setDrawRange(0, Math.round(k * g.parameters.tubularSegments) * g.parameters.radialSegments * 6);+ else g.setDrawRange(0, Math.round(k * (g.index ? g.index.count : g.attributes.position.count)));+ mesh.visible = k > 0;+};+/** write a path on over len frames */+export const writeOn = (mesh: THREE.Mesh | THREE.Line | THREE.Points, f: number, at: number, len: number, e: Ease = E.inOutCubic) => drawTo(mesh, e(t01(f, at, len)));+/** put an object at fraction t along a curve (constant speed by arc length); orient turns its +z along the travel */+export const moveAlongPath = (o: THREE.Object3D, curve: THREE.Curve<THREE.Vector3>, t: number, orient = false) => {+ const k = Math.max(0, Math.min(1, t));+ o.position.copy(curve.getPointAt(k));+ if (orient) o.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), curve.getTangentAt(k).normalize());+};++// ---- morphs+/** n points spaced evenly by arc length along a polyline (closed adds the edge back to the start) */+export const resample = (pts: V3[], n: number, closed = false): V3[] => {+ if (!pts.length) throw new Error("resample: the shape has no points");+ // a single point (a dot that grows into a line) has no length to walk: it is that point n times+ if (pts.length === 1) return Array.from({ length: Math.max(0, n) }, () => [...pts[0]] as V3);+ const P = closed ? [...pts, pts[0]] : pts, cum = [0];+ for (let i = 1; i < P.length; i++) cum.push(cum[i - 1] + Math.hypot(P[i][0] - P[i - 1][0], P[i][1] - P[i - 1][1], P[i][2] - P[i - 1][2]));+ const L = cum[cum.length - 1], out: V3[] = [], m = closed ? n : n - 1;+ let j = 0;+ for (let i = 0; i < n; i++) {+ const d = m > 0 ? (L * i) / m : 0;+ while (j < P.length - 2 && cum[j + 1] < d) j++;+ const span = cum[j + 1] - cum[j], u = span > 0 ? (d - cum[j]) / span : 0;+ out.push([0, 1, 2].map((k) => P[j][k] + (P[j + 1][k] - P[j][k]) * u) as V3);+ }+ return out;+};+/** one shape becoming another: both resampled to the same count by arc length, then mixed at t */+export const morph = (a: V3[], b: V3[], t: number, o: { n?: number; closed?: boolean } = {}): V3[] => {+ const n = o.n ?? Math.max(a.length, b.length), A = resample(a, n, o.closed), B = resample(b, n, o.closed);+ return A.map((p, i) => [p[0] + (B[i][0] - p[0]) * t, p[1] + (B[i][1] - p[1]) * t, p[2] + (B[i][2] - p[2]) * t] as V3);+};+/** write points into a Line/Points geometry's position attribute (same count every frame) */+export const writePoints = (g: THREE.BufferGeometry, pts: V3[]) => {+ const a = g.attributes.position as THREE.BufferAttribute;+ if (a.count !== pts.length) throw new Error(`writePoints: geometry holds ${a.count} points, got ${pts.length}`);+ pts.forEach((p, i) => a.setXYZ(i, p[0], p[1], p[2]));+ a.needsUpdate = true; g.computeBoundingSphere();+};+/** rebuild a TubeGeometry in place along new points (same segment counts, so the buffers keep their size) */+export const writeTube = (g: THREE.TubeGeometry, pts: V3[], closed = false) => {+ const { tubularSegments, radius, radialSegments } = g.parameters;+ const fresh = new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts.map((p) => new THREE.Vector3(...p)), closed, "centripetal"), tubularSegments, radius, radialSegments, closed);+ for (const k of ["position", "normal"] as const) { (g.attributes[k] as THREE.BufferAttribute).copyArray(fresh.attributes[k].array as Float32Array); g.attributes[k].needsUpdate = true; }+ g.computeBoundingSphere(); fresh.dispose();+};++// ---- groups+const kids = (g: THREE.Object3D | THREE.Object3D[]) => (Array.isArray(g) ? g : g.children);+const unit = (seed: number, i: number) => { const z = hash01(seed, i * 3) * 2 - 1, a = hash01(seed, i * 3 + 1) * Math.PI * 2, r = Math.sqrt(1 - z * z); return new THREE.Vector3(r * Math.cos(a), z, r * Math.sin(a)); };+/**+ * Fly children apart (k 0 = assembled, 1 = exploded): each shard leaves along its direction from+ * the group's centre plus a seeded spread, and tumbles by up to `spin` turns.+ */+export const shatter = (g: THREE.Object3D | THREE.Object3D[], k: number, o: { seed?: number; distance?: number; spin?: number; upward?: boolean } = {}) => {+ const cs = kids(g), seed = o.seed ?? 1, centre = new THREE.Vector3();+ cs.forEach((c) => centre.add(rest(c).position)); centre.divideScalar(Math.max(1, cs.length));+ cs.forEach((c, i) => {+ const r = rest(c), out = r.position.clone().sub(centre);+ const dir = (out.lengthSq() > 1e-9 ? out.normalize() : new THREE.Vector3(0, 1, 0)).add(unit(seed, i).multiplyScalar(0.6)).normalize();+ // upward: a block on the floor must not throw shards through it+ if (o.upward) { dir.y = Math.abs(dir.y) + 0.2; dir.normalize(); }+ const d = (o.distance ?? 3) * (0.6 + 0.8 * hash01(seed, i * 3 + 2));+ c.position.copy(r.position).addScaledVector(dir, d * k);+ c.quaternion.copy(r.quaternion).multiply(new THREE.Quaternion().setFromAxisAngle(unit(seed + 7, i), (o.spin ?? 0.5) * Math.PI * 2 * k * (0.5 + hash01(seed + 3, i))));+ c.scale.copy(r.scale);+ });+};+/** blow the children apart from frame `at` (assembled before, exploded after) */+export const explode = (g: THREE.Object3D | THREE.Object3D[], f: number, at: number, len = 18, o: { seed?: number; distance?: number; spin?: number; upward?: boolean; ease?: Ease } = {}) => shatter(g, (o.ease ?? E.outCubic)(t01(f, at, len)), o);+/** bring scattered children home (exploded before, assembled after) */+export const assemble = (g: THREE.Object3D | THREE.Object3D[], f: number, at: number, len = 18, o: { seed?: number; distance?: number; spin?: number; upward?: boolean; ease?: Ease } = {}) => shatter(g, 1 - (o.ease ?? E.inOutCubic)(t01(f, at, len)), o);+/** call attention: a scale pulse and an emissive flash that peak mid-way and return exactly to rest */+export const indicate = (o: THREE.Object3D, f: number, at: number, len = 12, o2: { scale?: number; color?: string; strength?: number } = {}) => {+ const r = rest(o), t = t01(f, at, len), b = t > 0 && t < 1 ? Math.sin(Math.PI * t) : 0, flash = new THREE.Color(o2.color ?? "#ffffff");+ showScaled(o, r, 1 + ((o2.scale ?? 1.15) - 1) * b);+ for (const m of mats(o)) { const mr = matRest(m), em = (m as THREE.MeshStandardMaterial).emissive; if (em && mr.emissive) em.copy(mr.emissive).lerp(flash, b * (o2.strength ?? 0.6)); }+};+/** a seeded wobble about z that swells and dies within [at, at + len] */+export const wiggle = (o: THREE.Object3D, f: number, at: number, len = 18, o2: { seed?: number; deg?: number; freq?: number } = {}) => {+ const r = rest(o), t = t01(f, at, len), env = t > 0 && t < 1 ? Math.sin(Math.PI * t) : 0;+ const a = env * (o2.deg ?? 10) * (Math.PI / 180) * noise1(o2.seed ?? 1, (f - at) * (o2.freq ?? 0.5));+ o.quaternion.copy(r.quaternion).multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), a));+};+/** a bump that travels across the children in order, lifting each by `height` as it passes */+export const wave = (g: THREE.Object3D | THREE.Object3D[], f: number, at: number, len = 24, o: { height?: number; width?: number; axis?: V3 } = {}) => {+ const cs = kids(g), n = cs.length, w = o.width ?? 2, ax = new THREE.Vector3(...(o.axis ?? [0, 1, 0]));+ const head = t01(f, at, len) * (n - 1 + 2 * w) - w;+ cs.forEach((c, i) => { const r = rest(c), d = (i - head) / w, b = Math.abs(d) < 1 ? 0.5 + 0.5 * Math.cos(Math.PI * d) : 0; c.position.copy(r.position).addScaledVector(ax, (o.height ?? 0.4) * b); });+};++/**+ * Give each object its own copy of any material it shares with another one in the list. text3d puts+ * one material on every letter, so fading letter by letter wrote all of them, and the last letter's+ * opacity won (the whole word hid). The copy starts from the shared material's REST state, so it does+ * not matter which frame is drawn first. Done once per object; the material passed in is never changed.+ */+const OWN = "anidoodleOwnMaterials";+const ownMaterials = (objs: THREE.Object3D[]) => {+ if (objs.every((o) => o.userData[OWN])) return;+ const users = new Map<THREE.Material, Set<THREE.Object3D>>();+ for (const o of objs) for (const m of mats(o)) { let u = users.get(m); if (!u) users.set(m, (u = new Set())); u.add(o); }+ for (const o of objs) {+ if (o.userData[OWN]) continue;+ o.userData[OWN] = true;+ const copies = new Map<THREE.Material, THREE.Material>();+ const own = (m: THREE.Material) => {+ if ((users.get(m)?.size ?? 0) < 2) return m;+ let c = copies.get(m);+ if (!c) {+ const r = matRest(m); c = m.clone();+ c.opacity = r.opacity; c.transparent = r.transparent;+ const em = (c as THREE.MeshStandardMaterial).emissive; if (em && r.emissive) em.copy(r.emissive);+ c.userData[REST] = { opacity: r.opacity, transparent: r.transparent, emissive: r.emissive?.clone() } as MatRest;+ copies.set(m, c);+ }+ return c;+ };+ o.traverse((n) => { const mesh = n as THREE.Mesh; if (mesh.material) mesh.material = Array.isArray(mesh.material) ? mesh.material.map(own) : own(mesh.material); });+ }+};++/** a verb as lagged() and grid() call it: one child, the frame, its own start frame, its index */+export type Verb = (o: THREE.Object3D, f: number, at: number, i: number) => void;+/** start a verb on each child `stagger` frames after the one before (Manim's LaggedStart) */+export const lagged = (g: THREE.Object3D | THREE.Object3D[], f: number, start: number, stagger: number, verb: Verb) => kids(g).forEach((c, i) => verb(c, f, start + i * stagger, i));+/**+ * Stagger a verb across a layout by distance: rings of children equally far from the centre (or+ * from the outside in, with from "edge") start together, `stagger` frames per ring.+ */+export const grid = (g: THREE.Object3D | THREE.Object3D[], f: number, start: number, stagger: number, verb: Verb, o: { from?: "center" | "edge" | V3 } = {}) => {+ const cs = kids(g), c = new THREE.Vector3();+ if (Array.isArray(o.from)) c.set(...o.from); else { cs.forEach((x) => c.add(rest(x).position)); c.divideScalar(Math.max(1, cs.length)); }+ const d = cs.map((x) => Math.round(rest(x).position.distanceTo(c) * 1000) / 1000), rings = [...new Set(d)].sort((a, b) => a - b);+ cs.forEach((x, i) => { const ring = rings.indexOf(d[i]); verb(x, f, start + stagger * (o.from === "edge" ? rings.length - 1 - ring : ring), i); });+};+/**+ * Per-letter type motion for a group whose children are letters in reading order (type3d builds+ * them): each letter enters `stagger` frames after the last, by rise, pop, drop or spin.+ */+export const kinetic = (letters: THREE.Object3D, f: number, start: number, stagger = 2, o: { style?: "rise" | "pop" | "drop" | "spin"; len?: number } = {}) => {+ const len = o.len ?? 12, style = o.style ?? "rise";+ if (style === "rise") ownMaterials(kids(letters));+ lagged(letters, f, start, stagger, (c, ff, at) => {+ if (style === "pop") popIn(c, ff, at, len);+ else if (style === "drop") dropIn(c, ff, at, len, { height: 1 });+ else if (style === "spin") { const r = rest(c), t = t01(ff, at, len); c.quaternion.copy(r.quaternion).multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), (1 - E.outCubic(t)) * Math.PI)); c.visible = r.visible && t > 0; }+ else { const r = rest(c), t = E.outCubic(t01(ff, at, len)); c.position.copy(r.position); c.position.y -= 0.5 * (1 - t); setOpacity(c, t); }+ });+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/rig.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/rig.tsnew file mode 100644index 0000000..51f613f--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/rig.ts@@ -0,0 +1,440 @@+// RIG. Posable characters from primitives: a biped, a quadruped, a crab, a mascot. A rig is a tree+// of groups built ONCE (memo it), and pose(rig, p) sets every joint from the pose alone, so any frame+// can be posed first. Nothing here reads a clock or keeps a value from the pose before.+//+// makeRig(name) root (placed in the world) > hips (bob, lean) > body (the squashable torso)+// part(rig, parent, name, m) add a mesh with a part name (the checks report hits by part name)+// limb(rig, name, opts) a two-bone chain (arm, leg, claw) with its own end (hand, foot), posable at once+// head(rig, name, opts) a head that can turn to look at things+// flag(rig, name, apply) a custom pose flag (blink, antenna) that THIS rig supports+// handle(prop, a, b, r) declare the segment of a prop a hand can hold (grip and the checks read it)+// pose(rig, p) put the whole character in a pose; unknown limbs or flags THROW+//+// Why limbs are the default: a rig whose arms are fixed geometry plays every shot with frozen hands,+// and retrofitting an arm rig after shots are rendered costs a reshoot (lessons 10 and 23). Why+// unknown flags throw: a flag built into one variant of a rig silently did nothing on the other+// variant, and only a render showed it (lesson 32).+//+// Verbs for the director: solveTwoBone (the IK), grip (a prop held along the hand's axis through+// the grip), bodyMatrix (where the body will be, without posing meshes), lookAt, followThrough,+// squashStretch, walkCycle, anticipate.+import * as THREE from "three";+import { clamp01, ease, lerp, seg, spring, type Ease } from "./time";++type V3 = THREE.Vector3;+export type Vec = [number, number, number];+const v3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);+const vec = (a: Vec | V3) => (Array.isArray(a) ? v3(a[0], a[1], a[2]) : a.clone());+const UP = v3(0, 1, 0);++// ---------------------------------------------------------------- two-bone IK+export type TwoBone = { mid: V3; end: V3; reached: boolean; bend: number };+/**+ * Analytic two-bone IK (law of cosines). root, mid, end give the bone lengths; the answer puts the+ * end on the target when it can, and the middle joint on the side of the pole point. A target out+ * of reach gives a straight limb pointing at it; one too close folds the limb as far as it goes.+ * Deterministic and exact: no iterations, so no frame ever depends on the frame before.+ */+export const solveTwoBone = (root: V3, mid: V3, end: V3, target: V3, pole: V3): TwoBone => {+ const L1 = root.distanceTo(mid), L2 = mid.distanceTo(end);+ const d = target.clone().sub(root);+ let D = d.length();+ const dir = D > 1e-9 ? d.divideScalar(D) : end.clone().sub(root).normalize();+ const maxD = L1 + L2, minD = Math.abs(L1 - L2);+ const reached = D <= maxD + 1e-9 && D >= minD - 1e-9;+ D = Math.min(maxD, Math.max(minD + 1e-9, D));+ const a = (L1 * L1 - L2 * L2 + D * D) / (2 * D), h = Math.sqrt(Math.max(0, L1 * L1 - a * a));+ // the bend plane: the pole's offset from the root, minus its part along the limb+ const p = pole.clone().sub(root), perp = p.sub(dir.clone().multiplyScalar(p.dot(dir)));+ if (perp.lengthSq() < 1e-12) perp.copy(v3().crossVectors(dir, Math.abs(dir.y) < 0.9 ? UP : v3(1, 0, 0)));+ perp.normalize();+ const m = root.clone().addScaledVector(dir, a).addScaledVector(perp, h), e = root.clone().addScaledVector(dir, D);+ const bend = m.clone().sub(root).angleTo(e.clone().sub(m)); // 0 = straight+ return { mid: m, end: e, reached, bend };+};++// ---------------------------------------------------------------- the rig+export type LimbPose = {+ /** where the end goes, in WORLD space (a hand on a bar, a foot on a step) */+ target?: V3;+ /** an offset from the rest end, in the limb's parent space (a swing, a wave) */+ offset?: Vec | V3;+ /** 0..1 blend from the rest (or offset) end to `target`: ease a reach in and out with it */+ weight?: number;+ /** a different bend direction for this pose, in the parent's space (a world point is NOT expected) */+ pole?: Vec | V3;+ /** put the hand's grip point on `point` with its grip axis along `axis` (world): reachFor a handle */+ grip?: { point: V3; axis: V3 };+ /** wrist: pitch and twist of the end in radians, after it is aimed (a flick, a toe lift) */+ wrist?: [pitch: number, twist: number];+};+export type Limb = {+ name: string; rig: Rig;+ root: THREE.Group; upper: THREE.Mesh; lower: THREE.Mesh; joints: THREE.Mesh[]; end: THREE.Group;+ L1: number; L2: number; base: V3; rest: V3; pole: V3; endMode: "forearm" | "level";+ gripPoint: V3; gripAxis: V3;+ /** the last solve (read it to know whether the target was reached) */+ solved: TwoBone;+};+export type Head = { name: string; pivot: THREE.Group; max: [yaw: number, pitch: number] };+export type Rig = {+ name: string; root: THREE.Group; hips: THREE.Group; body: THREE.Group;+ hipHeight: number;+ limbs: Record<string, Limb>; heads: Record<string, Head>;+ flags: Record<string, (rig: Rig, value: number, p: Pose) => void>;+ /** groups whose rest position rides the squash of the body (shoulders, the neck) */+ anchors: { obj: THREE.Object3D; base: V3 }[];+};+export type Pose = {+ at?: Vec | V3; yaw?: number;+ /** hip height offset (a bob, a crouch); legs solved to world feet stay planted */+ lift?: number;+ /** forward pitch of the hips (radians), side tilt, and twist about the spine */+ lean?: number; tilt?: number; twist?: number;+ /** volume-preserving squash (negative) or stretch (positive) of the body */+ squash?: number;+ /** turn a head to a world point: amount 0..1 blends from straight ahead */+ look?: { target: V3; amount?: number; head?: string };+ /** limbs by full name ("arms.left", "claws.big") */+ limbs?: Record<string, LimbPose>;+ /** sugar: arms.left is limbs["arms.left"], legs.right is limbs["legs.right"] */+ arms?: Record<string, LimbPose>; legs?: Record<string, LimbPose>;+ /** this rig's own flags (registered with flag()); a flag it does not have throws */+ flags?: Record<string, number | boolean>;+};++/** A new empty character: root > hips (at hipHeight) > body. Add parts, limbs and heads to it. */+export const makeRig = (name: string, opts: { hipHeight?: number } = {}): Rig => {+ const root = new THREE.Group(), hips = new THREE.Group(), body = new THREE.Group();+ root.name = `${name}`; hips.name = `${name}.hips`; body.name = `${name}.body`;+ root.add(hips); hips.add(body);+ const hipHeight = opts.hipHeight ?? 0;+ hips.position.y = hipHeight;+ hips.rotation.order = "YXZ";+ const r: Rig = { name, root, hips, body, hipHeight, limbs: {}, heads: {}, flags: {}, anchors: [] };+ root.userData.rig = r;+ return r;+};++/** Add a mesh under `parent` with a part name the checks will print ("visor", "arms.left.hand"). */+export const part = <T extends THREE.Object3D>(rig: Rig, parent: THREE.Object3D, name: string, obj: T): T => {+ obj.traverse((o) => { if ((o as THREE.Mesh).isMesh) { o.userData.part ??= name; o.castShadow = true; o.receiveShadow = true; } });+ obj.name ||= name;+ parent.add(obj);+ void rig;+ return obj;+};++/** Make a group ride the body's squash: its rest position scales with the torso (shoulders, the neck). */+export const anchor = (rig: Rig, obj: THREE.Object3D, at: Vec | V3) => { const b = vec(at); obj.position.copy(b); rig.anchors.push({ obj, base: b }); return obj; };++export type LimbOpts = {+ /** what the limb hangs from (default: the hips). Its root rides the squash when it hangs from the hips */+ parent?: THREE.Object3D;+ /** the root joint (shoulder, hip) in the parent's space */+ at: Vec;+ /** upper and lower bone lengths */+ lengths: [number, number];+ /** bone radius (one number, or [upper, lower]) */+ radius?: number | [number, number];+ /** where the end rests, relative to the root joint, in the parent's space */+ rest: Vec;+ /** which way the middle joint bends at rest (elbows back, knees forward): a direction in the parent's space */+ pole: Vec;+ material: THREE.Material;+ jointMaterial?: THREE.Material;+ /** the end (a hand, a foot, a claw), built in its own frame: +y runs along the forearm out of the wrist */+ end?: (limb: Limb) => THREE.Object3D;+ /** the point a handle passes through, and the axis it runs along, in the end's frame (default: 1.6 radii out, along x) */+ gripPoint?: Vec; gripAxis?: Vec;+ /** "forearm": the end follows the lower bone (hands). "level": it stays level with the parent (feet) */+ endMode?: "forearm" | "level";+ /** smoothness of the bones */+ segments?: number;+};+/** Add a two-bone limb. It is posable at once: pose(rig, { limbs: { [name]: { target } } }). */+export const limb = (rig: Rig, name: string, o: LimbOpts): Limb => {+ if (rig.limbs[name]) throw new Error(`limb: ${rig.name} already has a limb called "${name}"`);+ const [L1, L2] = o.lengths, [r1, r2] = typeof o.radius === "number" ? [o.radius, o.radius * 0.9] : o.radius ?? [0.1 * L1, 0.09 * L2];+ const parent = o.parent ?? rig.hips, seg = o.segments ?? 12;+ const root = new THREE.Group(); root.name = `${name}.root`; parent.add(root);+ if (parent === rig.hips) anchor(rig, root, o.at); else root.position.set(...o.at);+ const bone = (r: number, L: number, nm: string) => { const m = new THREE.Mesh(new THREE.CapsuleGeometry(r, Math.max(1e-4, L - r * 0.2), 4, seg), o.material); m.userData.part = nm; m.castShadow = m.receiveShadow = true; root.add(m); return m; };+ const upper = bone(r1, L1, `${name}.upper`), lower = bone(r2, L2, `${name}.lower`);+ const jm = o.jointMaterial ?? o.material;+ const joints = [r1 * 1.15, r2 * 1.15].map((r, i) => { const m = new THREE.Mesh(new THREE.SphereGeometry(r, seg, Math.max(6, seg >> 1)), jm); m.userData.part = `${name}.${i ? "mid" : "root"}joint`; m.castShadow = m.receiveShadow = true; root.add(m); return m; });+ const end = new THREE.Group(); end.name = `${name}.end`; root.add(end);+ const rest = vec(o.rest), pole = vec(o.pole).normalize();+ const L: Limb = { name, rig, root, upper, lower, joints, end, L1, L2, base: vec(o.at), rest, pole, endMode: o.endMode ?? "forearm",+ gripPoint: o.gripPoint ? vec(o.gripPoint) : v3(0, r2 * 1.6, 0), gripAxis: (o.gripAxis ? vec(o.gripAxis) : v3(1, 0, 0)).normalize(), solved: { mid: v3(), end: rest.clone(), reached: true, bend: 0 } };+ if (o.end) { const e = o.end(L); e.traverse((n) => { if ((n as THREE.Mesh).isMesh) { n.userData.part ??= `${name}.end`; n.castShadow = n.receiveShadow = true; } }); end.add(e); }+ rig.limbs[name] = L;+ setLimb(L, rest);+ return L;+};++const Q = new THREE.Quaternion();+const restMid = (L: Limb) => { const d = L.rest.clone(), n = d.length() || 1; return d.clone().multiplyScalar(L.L1 / (L.L1 + L.L2)).addScaledVector(L.pole, 0.3 * n); };+/** Solve a limb so its end sits at `endLocal` (in the limb root's space) and place its meshes. */+const setLimb = (L: Limb, endLocal: V3, lp: LimbPose = {}, axisLocal?: V3, endQ?: THREE.Quaternion) => {+ const root = v3(), mid0 = restMid(L).setLength(L.L1), end0 = mid0.clone().add(L.rest.clone().sub(mid0).setLength(L.L2));+ const pole = lp.pole ? vec(lp.pole).normalize() : L.pole;+ const s = solveTwoBone(root, mid0, end0, endLocal, pole.clone().multiplyScalar(L.L1 + L.L2));+ L.solved = s;+ const put = (m: THREE.Mesh, a: V3, b: V3) => { m.position.copy(a).add(b).multiplyScalar(0.5); m.quaternion.setFromUnitVectors(UP, b.clone().sub(a).normalize()); };+ put(L.upper, root, s.mid); put(L.lower, s.mid, s.end);+ L.joints[0].position.copy(root); L.joints[1].position.copy(s.mid);+ L.end.position.copy(s.end);+ L.end.quaternion.copy(endQ ?? endFrame(L, s, pole, axisLocal));+ if (lp.wrist) L.end.quaternion.multiply(Q.setFromEuler(new THREE.Euler(lp.wrist[0], lp.wrist[1], 0, "YXZ")));+};+// The end's frame. A hand: +y along the forearm; its grip axis across it, on the side away from the+// bend (so a fist's handle runs across the knuckles), or turned to a requested axis. A foot: level.+const endFrame = (L: Limb, s: TwoBone, pole: V3, axisLocal?: V3) => {+ if (L.endMode === "level") return new THREE.Quaternion();+ let y = s.end.clone().sub(s.mid).normalize(), x: V3;+ if (axisLocal && axisLocal.lengthSq() > 1e-10) {+ // a grip: the axis is honoured exactly and the wrist bends (a handle off the jaw axis clips the jaw)+ x = axisLocal.clone().normalize(); const yy = y.clone().sub(x.clone().multiplyScalar(y.dot(x)));+ y = yy.lengthSq() > 1e-10 ? yy.normalize() : v3().crossVectors(x, Math.abs(x.z) < 0.9 ? v3(0, 0, 1) : v3(1, 0, 0)).normalize();+ } else {+ x = v3().crossVectors(y, pole);+ if (x.lengthSq() < 1e-10) x = v3().crossVectors(y, Math.abs(y.z) < 0.9 ? v3(0, 0, 1) : v3(1, 0, 0));+ x.normalize();+ }+ // the declared grip axis sits along end-local gripAxis; build the basis so gripAxis maps to x+ const z = v3().crossVectors(x, y).normalize(), basis = new THREE.Matrix4().makeBasis(x, y, z), q = new THREE.Quaternion().setFromRotationMatrix(basis);+ const toAxis = new THREE.Quaternion().setFromUnitVectors(v3(1, 0, 0), L.gripAxis);+ return q.multiply(toAxis.invert());+};++// the hand's turn for a grip: grip axis along the handle, fingers pointing from the root joint to it+const gripTurn = (L: Limb, ptLocal: V3, axisLocal: V3) => {+ const x = axisLocal.clone().normalize(); let y = ptLocal.clone().sub(x.clone().multiplyScalar(ptLocal.dot(x)));+ if (y.lengthSq() < 1e-10) y = L.rest.clone().sub(x.clone().multiplyScalar(L.rest.dot(x)));+ if (y.lengthSq() < 1e-10) y = v3().crossVectors(x, Math.abs(x.z) < 0.9 ? v3(0, 0, 1) : v3(1, 0, 0));+ y.normalize();+ const z = v3().crossVectors(x, y).normalize(), q = new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(x, y, z));+ return q.multiply(new THREE.Quaternion().setFromUnitVectors(v3(1, 0, 0), L.gripAxis).invert());+};++/** A head: a pivot at `at` (in the parent's space, riding the squash) that lookAt and pose.look turn. */+export const head = (rig: Rig, name: string, o: { parent?: THREE.Object3D; at: Vec; max?: [number, number] }): Head => {+ const pivot = new THREE.Group(); pivot.name = name; pivot.rotation.order = "YXZ";+ const parent = o.parent ?? rig.hips; parent.add(pivot);+ if (parent === rig.hips) anchor(rig, pivot, o.at); else pivot.position.set(...o.at);+ const h: Head = { name, pivot, max: o.max ?? [1.2, 0.6] };+ rig.heads[name] = h;+ return h;+};++/** Register a pose flag this rig supports. pose() calls apply(rig, value) and throws on any other flag. */+export const flag = (rig: Rig, name: string, apply: (rig: Rig, value: number, p: Pose) => void) => { rig.flags[name] = apply; };++const HIPS_EULER = new THREE.Euler(0, 0, 0, "YXZ");+/**+ * Where the body goes for a pose, as matrices, WITHOUT touching a mesh: root and hips in world+ * space, and toWorld() for any point in hips space (a shoulder, the chest). Plan a reach or a camera+ * from it before posing anything (lesson 24: a world-space grip used to cost a whole extra build).+ */+export const bodyMatrix = (rig: Rig, p: Pose = {}) => {+ const root = new THREE.Matrix4().compose(p.at ? vec(p.at) : v3(), new THREE.Quaternion().setFromAxisAngle(UP, p.yaw ?? 0), v3(1, 1, 1));+ if (rig.root.parent) { rig.root.parent.updateWorldMatrix(true, false); root.premultiply(rig.root.parent.matrixWorld); }+ HIPS_EULER.set(p.lean ?? 0, p.twist ?? 0, p.tilt ?? 0, "YXZ");+ const hips = root.clone().multiply(new THREE.Matrix4().compose(v3(0, rig.hipHeight + (p.lift ?? 0), 0), new THREE.Quaternion().setFromEuler(HIPS_EULER), v3(1, 1, 1)));+ const sq = squashStretch(p.squash ?? 0);+ return { root, hips, squash: sq, toWorld: (local: Vec | V3, rides = true) => { const q = vec(local); if (rides) q.multiply(sq); return q.applyMatrix4(hips); } };+};++const LIMB_KEYS = new Set(["target", "offset", "weight", "pole", "grip", "wrist"]);+const POSE_KEYS = new Set(["at", "yaw", "lift", "lean", "tilt", "twist", "squash", "look", "limbs", "arms", "legs", "flags"]);+/**+ * Put the rig in a pose. Every joint is SET (limbs not named go to rest), so the pose depends on+ * nothing but `p`. Unknown keys, limbs, heads and flags throw: a pose a rig cannot show must say so.+ */+export const pose = (rig: Rig, p: Pose = {}) => {+ for (const k of Object.keys(p)) if (!POSE_KEYS.has(k)) throw new Error(`pose: unknown pose key "${k}" for ${rig.name}`);+ const limbs: Record<string, LimbPose> = { ...(p.limbs ?? {}) };+ for (const [grp, m] of [["arms", p.arms], ["legs", p.legs]] as const) for (const [side, lp] of Object.entries(m ?? {})) limbs[`${grp}.${side}`] = lp;+ for (const [n, lp] of Object.entries(limbs)) {+ if (!rig.limbs[n]) throw new Error(`pose: ${rig.name} has no limb "${n}" (it has: ${Object.keys(rig.limbs).join(", ") || "none"})`);+ for (const k of Object.keys(lp)) if (!LIMB_KEYS.has(k)) throw new Error(`pose: unknown limb key "${k}" on ${n}`);+ }+ for (const n of Object.keys(p.flags ?? {})) if (!rig.flags[n]) throw new Error(`pose: ${rig.name} has no flag "${n}" (it has: ${Object.keys(rig.flags).join(", ") || "none"}). Build the flag into every variant or leave it out of the pose.`);+ if (p.look && !Object.keys(rig.heads).length) throw new Error(`pose: ${rig.name} has no head to look with`);+ if (p.look?.head && !rig.heads[p.look.head]) throw new Error(`pose: ${rig.name} has no head "${p.look.head}"`);++ // the body+ rig.root.position.copy(p.at ? vec(p.at) : v3()); rig.root.rotation.set(0, p.yaw ?? 0, 0);+ rig.hips.position.set(0, rig.hipHeight + (p.lift ?? 0), 0); rig.hips.rotation.set(p.lean ?? 0, p.twist ?? 0, p.tilt ?? 0, "YXZ");+ const sq = squashStretch(p.squash ?? 0); rig.body.scale.copy(sq);+ for (const a of rig.anchors) a.obj.position.copy(a.base).multiply(sq);+ for (const h of Object.values(rig.heads)) h.pivot.rotation.set(0, 0, 0);+ rig.root.updateWorldMatrix(true, true);++ // flags (blink, antenna...) before the look, so a flag may move a head's parent+ for (const [n, val] of Object.entries(p.flags ?? {})) rig.flags[n](rig, typeof val === "boolean" ? (val ? 1 : 0) : val, p);+ if (p.look) { const h = rig.heads[p.look.head ?? Object.keys(rig.heads)[0]]; lookAt(h, p.look.target, 0, { weight: p.look.amount ?? 1 }); }++ // limbs, every one of them: rest unless posed+ for (const L of Object.values(rig.limbs)) {+ const lp = limbs[L.name] ?? {};+ L.root.updateWorldMatrix(true, false);+ const inv = L.root.matrixWorld.clone().invert(), rotInv = new THREE.Quaternion().setFromRotationMatrix(L.root.matrixWorld).invert();+ const from = L.rest.clone().add(lp.offset ? vec(lp.offset) : v3());+ let to = from, axisLocal: V3 | undefined, endQ: THREE.Quaternion | undefined;+ if (lp.grip) {+ // reachFor: the hand is aimed from the shoulder toward the handle (known BEFORE the solve), so+ // the wrist is exactly the handle point minus the turned grip offset: one solve, no iteration+ const pt = lp.grip.point.clone().applyMatrix4(inv); axisLocal = lp.grip.axis.clone().applyQuaternion(rotInv).normalize();+ endQ = gripTurn(L, pt, axisLocal);+ if (lp.wrist) endQ.multiply(Q.setFromEuler(new THREE.Euler(lp.wrist[0], lp.wrist[1], 0, "YXZ")));+ to = pt.clone().sub(L.gripPoint.clone().applyQuaternion(endQ));+ } else if (lp.target) to = lp.target.clone().applyMatrix4(inv);+ const w = lp.weight ?? 1;+ // endQ already carries the wrist; a partial reach turns the hand from the forearm and bends the wrist after+ setLimb(L, w >= 1 ? to : from.clone().lerp(to, clamp01(w)), endQ && w >= 1 ? { ...lp, wrist: undefined } : lp, axisLocal, endQ && w >= 1 ? endQ : undefined);+ }+ rig.root.updateWorldMatrix(true, true);+ return rig;+};++/** Every mesh of a rig (or of any object), visible ones only: what the checks sample. */+export const meshesOf = (o: THREE.Object3D, skip?: (m: THREE.Mesh) => boolean) => { const out: THREE.Mesh[] = []; o.traverseVisible((n) => { const m = n as THREE.Mesh; if (m.isMesh && m.geometry?.attributes?.position && !(skip && skip(m))) out.push(m); }); return out; };++// ---------------------------------------------------------------- holding props+/** Declare a prop's handle: a segment a..b of radius r in the prop's own space. grip() and the checks read it. */+export const handle = (prop: THREE.Object3D, a: Vec, b: Vec, r: number) => { prop.userData.handle = { a: vec(a), b: vec(b), r }; return prop; };+export type Handle = { a: V3; b: V3; r: number };+export const handleOf = (prop: THREE.Object3D): Handle => { const h = prop.userData.handle as Handle | undefined; if (!h) throw new Error(`grip: prop "${prop.name || prop.type}" has no handle (call handle(prop, a, b, r) when you build it)`); return h; };+/** The hand's grip point and axis in world space (for a limb, or any object carrying userData.gripPoint/gripAxis). */+export const gripFrame = (hand: Limb | THREE.Object3D) => {+ const end = isLimb(hand) ? hand.end : hand, gp = isLimb(hand) ? hand.gripPoint : vec(end.userData.gripPoint ?? [0, 0, 0]), ga = isLimb(hand) ? hand.gripAxis : vec(end.userData.gripAxis ?? [1, 0, 0]);+ end.updateWorldMatrix(true, false);+ return { point: end.localToWorld(gp.clone()), axis: ga.clone().transformDirection(end.matrixWorld).normalize(), end };+};+export const isLimb = (x: unknown): x is Limb => !!x && typeof x === "object" && "L1" in (x as object) && "end" in (x as object);+/**+ * Hold a prop: its handle, at `at` (0..1 along it), sits on the hand's grip point and runs along the+ * hand's grip axis, through the grip (lesson 37: a handle glued to a palm passes through the hand).+ * hang: the prop turns about the handle so its +y points up (a lantern, a bucket), then swings by+ * `swing` radians. Without hang it turns with the hand (a mug, a sword), rolled by `roll`.+ * Sets the prop's transform in its parent's space; the prop stays wherever it lives in the scene.+ */+export const grip = (hand: Limb | THREE.Object3D, prop: THREE.Object3D, at = 0.5, o: { hang?: boolean; swing?: number; roll?: number } = {}) => {+ const h = handleOf(prop), { point, axis, end } = gripFrame(hand);+ const ha = h.b.clone().sub(h.a).normalize(), hp = h.a.clone().lerp(h.b, at);+ let q: THREE.Quaternion;+ if (o.hang) {+ q = new THREE.Quaternion().setFromUnitVectors(ha, axis);+ // roll about the handle until the prop's up is as close to world up as it can get+ const up = UP.clone().applyQuaternion(q), want = UP.clone().sub(axis.clone().multiplyScalar(UP.dot(axis)));+ if (want.lengthSq() > 1e-8) { want.normalize(); const cur = up.sub(axis.clone().multiplyScalar(up.dot(axis))).normalize(); const ang = Math.atan2(v3().crossVectors(cur, want).dot(axis), cur.dot(want)); q.premultiply(new THREE.Quaternion().setFromAxisAngle(axis, ang)); }+ if (o.swing) q.premultiply(new THREE.Quaternion().setFromAxisAngle(axis, o.swing));+ } else {+ const eq = end.getWorldQuaternion(new THREE.Quaternion()), ga = isLimb(hand) ? hand.gripAxis : vec(end.userData.gripAxis ?? [1, 0, 0]);+ q = eq.multiply(new THREE.Quaternion().setFromUnitVectors(ha, ga.clone().normalize()));+ if (o.roll) q.premultiply(new THREE.Quaternion().setFromAxisAngle(axis, o.roll));+ }+ const pos = point.clone().sub(hp.clone().multiply(prop.getWorldScale(v3())).applyQuaternion(q));+ const par = prop.parent;+ if (par) { par.updateWorldMatrix(true, false); const pq = par.getWorldQuaternion(new THREE.Quaternion()).invert(); prop.quaternion.copy(pq.multiply(q)); prop.position.copy(par.worldToLocal(pos)); }+ else { prop.quaternion.copy(q); prop.position.copy(pos); }+ prop.updateWorldMatrix(false, true);+ return { a: prop.localToWorld(h.a.clone()), b: prop.localToWorld(h.b.clone()), point };+};++// ---------------------------------------------------------------- motion verbs (all closed form)+/**+ * Turn a head (or any object whose +z is its face) toward a world point, eased: weight from+ * tween(f, at, at + dur) when `at` is given, else opts.weight (default 1). Clamped to the head's+ * max yaw and pitch, so a target behind the character gives a shoulder check, not an owl.+ */+export const lookAt = (h: Head | THREE.Object3D, target: V3, f: number, o: { at?: number; dur?: number; ease?: Ease; weight?: number; from?: [number, number]; max?: [number, number] } = {}) => {+ const obj = "pivot" in h ? h.pivot : h, max = o.max ?? ("pivot" in h ? h.max : [1.2, 0.6]);+ const par = obj.parent; if (par) par.updateWorldMatrix(true, false);+ const t = par ? par.worldToLocal(target.clone()) : target.clone(); t.sub(obj.position);+ let yaw = Math.atan2(t.x, t.z), pitch = -Math.atan2(t.y, Math.hypot(t.x, t.z));+ yaw = Math.max(-max[0], Math.min(max[0], yaw)); pitch = Math.max(-max[1], Math.min(max[1], pitch));+ const w = o.at !== undefined ? (o.ease ?? ease.inOutCubic)(seg(f, o.at, o.at + (o.dur ?? 12))) : clamp01(o.weight ?? 1);+ const [y0, p0] = o.from ?? [0, 0];+ obj.rotation.order = "YXZ"; obj.rotation.set(lerp(p0, pitch, w), lerp(y0, yaw, w), 0);+ obj.updateWorldMatrix(false, true);+ return { yaw: lerp(y0, yaw, w), pitch: lerp(p0, pitch, w), weight: w };+};++export type Kick = { at: number; amp: number; freq?: number; damping?: number; held?: number };+/**+ * Secondary motion: the sum of springs kicked at each event (a stop, a lift, a hop). Before its kick+ * an event contributes amp x held (a lag held while moving, 0 by default); from the kick on it rings+ * down from amp to 0. Closed form (time.ts spring): frame 300 never needs frames 0-299.+ */+export const followThrough = (f: number, fps: number, kicks: Kick[]) => {+ let s = 0;+ for (const k of kicks) s += k.amp * (f < k.at ? (k.held ?? 0) : spring(f, k.at, fps, k.freq, k.damping));+ return s;+};++/** Volume-preserving squash (s < 0) or stretch (s > 0) as a scale: y = 1 + s, x = z = 1 / sqrt(1 + s). */+export const squashStretch = (s: number) => { const y = 1 + Math.max(-0.9, s), xz = 1 / Math.sqrt(y); return v3(xz, y, xz); };++/**+ * Anticipation: a move from `at` to `at + dur` that first goes the other way. Returns progress in+ * [-amount, 1]: easing down to -amount over the `lead` frames before `at`, then over to 1. Multiply+ * a move vector by it (a wind-up before a reach, a crouch before a hop).+ */+export const anticipate = (f: number, o: { at: number; dur: number; lead?: number; amount?: number; ease?: Ease }) => {+ const lead = o.lead ?? Math.max(1, Math.round(o.dur * 0.5)), amt = o.amount ?? 0.15;+ if (f < o.at) return -amt * ease.inOutSine(seg(f, o.at - lead, o.at));+ return lerp(-amt, 1, (o.ease ?? ease.inOutCubic)(seg(f, o.at, o.at + o.dur)));+};++export type WalkOpts = {+ fps?: number;+ /** full cycles (two steps for a biped) per second, when the walk runs on the frame */+ cadence?: number;+ /** distance travelled: when given, the phase is distance / stride, so planted feet never slide at any speed, eases and stops included */+ distance?: number;+ /** distance the body travels in one full cycle */+ stride?: number;+ /** body bob: the hips dip this far at each contact */+ bob?: number;+ /** fraction of the cycle a foot is planted (0.6 walks, under 0.5 runs) */+ stance?: number;+ /** how high a swinging foot lifts */+ lift?: number;+ /** side sway of the hips over the planted foot */+ sway?: number;+ /** arm counter-swing amplitude (the arms[] values are -1..1 times this) */+ armSwing?: number;+ /** phase offset of each foot (biped [0, 0.5]; a quadruped walk [0, 0.5, 0.25, 0.75]) */+ offsets?: number[];+ /** 0..1: blends every output toward standing still (a start or a stop) */+ moving?: number;+};+export type WalkFoot = { u: number; stance: boolean; fwd: number; lift: number };+export type Walk = { phase: number; feet: WalkFoot[]; bob: number; sway: number; twist: number; arms: number[] };+/**+ * A walk, as numbers: per foot its place along the travel relative to the hips (fwd) and its lift,+ * the hip bob, sway and twist, and each foot's arm counter-swing (arms[i] swings against foot i:+ * forward while that foot is back). Periodic in the phase. Feet are planted for `stance` of the cycle+ * and travel back under the body exactly as fast as the body moves, so with `distance` they stick.+ */+export const walkCycle = (f: number, o: WalkOpts = {}): Walk => {+ const stride = o.stride ?? 1, S = o.stance ?? 0.6, mv = clamp01(o.moving ?? 1), offs = o.offsets ?? [0, 0.5];+ const phase = o.distance !== undefined ? o.distance / stride : (f / (o.fps ?? 24)) * (o.cadence ?? 1);+ const frac = (x: number) => x - Math.floor(x);+ const feet = offs.map((off): WalkFoot => {+ const u = frac(phase + off);+ if (u < S) return { u, stance: true, fwd: mv * stride * (S / 2 - u), lift: 0 };+ const s = (u - S) / (1 - S), e = s * s * (3 - 2 * s);+ return { u, stance: false, fwd: mv * stride * lerp(-S / 2, S / 2, e), lift: mv * (o.lift ?? 0.1 * stride) * Math.sin(Math.PI * s) };+ });+ const arms = feet.map((ft) => { const u = ft.u, a = u < S ? -Math.cos((Math.PI * u) / S) : Math.cos(Math.PI * ((u - S) / (1 - S))); return mv * (o.armSwing ?? 1) * a; });+ // hips: lowest at each contact (u = 0 of a foot), highest as the other leg passes (mid stance)+ const k = offs.length > 2 ? 2 : offs.length;+ const bob = -mv * (o.bob ?? 0) * (0.5 - 0.5 * Math.cos(2 * Math.PI * k * (phase - S / 2)));+ const sway = mv * (o.sway ?? 0) * Math.cos(2 * Math.PI * (phase - S / 2));+ const twist = mv * 0.5 * (feet[0].fwd - (feet[1]?.fwd ?? 0)) / Math.max(1e-6, stride);+ return { phase, feet, bob, sway, twist, arms };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/stage.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/stage.tsnew file mode 100644index 0000000..e10046c--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/stage.ts@@ -0,0 +1,124 @@+// STAGE. The bridge between three.js and the film contract. A 3D shot is an ordinary shot: its+// draw(ctx, local, env) builds or updates a scene from the frame number alone, then calls+// draw3d(), which renders through WebGL and copies the pixels onto the frame's 2D canvas. So+// render, still, gate, captions, the player and the score all work on 3D films unchanged, and+// 2D layers (titles, subtitles, grain) can sit on top in the same draw.+//+// Purity is the whole game. The renderer is kept between frames (building one costs ~100 ms),+// and so may the scene graph (memo below), but every value that moves must be SET from the frame+// on every draw: a position left over from the frame drawn before makes frame N depend on the+// order frames were asked for, and parallel renders then disagree. gate.mjs seeks out of order+// and catches it. Never read a clock: AnimationMixer.setTime(f / fps), never mixer.update(dt).+// Import three as `import * as THREE from "three"` in each file and never re-export the namespace:+// esbuild then drops the parts a film never uses (the file loaders that could fetch, among them).+import * as THREE from "three";+import type { Ctx, Env } from "../canvas-core/core";+import { probeRect } from "../canvas-core/core";++// Hosts see this string in the page bundle and start Chrome with WebGL on (adapters/playwright.mjs).+export const WEBGL_MARKER = "__ANIDOODLE_WEBGL__";+(globalThis as Record<string, unknown>)[WEBGL_MARKER] = true;++export type StageOpts = {+ /** render at ss x the device size and scale down: smooth edges that never depend on MSAA support. 1 to 3, default 2 */+ ss?: number;+ /** soft shadow maps (PCFSoft). Off by default: a shadow is a choice, and acne is the first "cheap 3D" tell */+ shadows?: boolean;+ toneMapping?: THREE.ToneMapping;+ exposure?: number;+};+export type Stage = { renderer: THREE.WebGLRenderer; w: number; h: number; ss: number };++const KEY = "three:stage";+/** The film's one WebGL renderer, sized to the frame at env.scale (x ss). Built on first use, then kept. draw3d sets its tone mapping and exposure on every call. */+export const stage = (env: Env, opts: StageOpts = {}): Stage => {+ const ss = Math.max(1, Math.min(3, Math.round(opts.ss ?? 2)));+ const w = Math.round(env.W * env.scale * ss), h = Math.round(env.H * env.scale * ss);+ const key = `${KEY}:${w}x${h}:${opts.shadows ? 1 : 0}`;+ const hit = env.cache.get(key) as Stage | undefined;+ if (hit) return hit;+ if (!env.webgl) throw new Error("stage: this host has no WebGL surface (env.webgl). 3D shots need the page host or the interactive host.");+ const canvas = env.webgl(w, h);+ const renderer = new THREE.WebGLRenderer({ canvas: canvas as HTMLCanvasElement, antialias: false, alpha: true, preserveDrawingBuffer: true, powerPreference: "high-performance" });+ renderer.setPixelRatio(1);+ renderer.setSize(w, h, false);+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = opts.toneMapping ?? THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = opts.exposure ?? 1;+ renderer.shadowMap.enabled = !!opts.shadows;+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;+ // shadow maps re-render only when asked; a frame-pure film asks every frame (draw3d sets needsUpdate)+ renderer.shadowMap.autoUpdate = false;+ const s: Stage = { renderer, w, h, ss };+ env.cache.set(key, s);+ return s;+};++/**+ * Build something once per page and keep it: geometry, materials, a whole scene graph. The+ * builder gets env and must not read the frame. Everything that changes over time is set by the+ * shot's draw on every frame, never left to persist.+ */+export const memo = <T>(env: Env, key: string, build: (env: Env) => T): T => {+ const k = `three:memo:${key}`;+ if (!env.cache.has(k)) env.cache.set(k, build(env));+ return env.cache.get(k) as T;+};++/**+ * Render scene through camera and copy the result onto the frame. The camera's aspect is set from+ * the film here, so a reshaped film (9x16, 1x1) keeps its proportions. `clear` paints the frame+ * first (pass null to composite over what the shot already drew, e.g. a painted 2D background).+ */+export const draw3d = (ctx: Ctx, env: Env, scene: THREE.Scene, camera: THREE.Camera, opts: StageOpts & { clear?: string | null } = {}) => {+ const st = stage(env, opts), { renderer } = st;+ // the renderer is shared by every shot of this size, but its look belongs to THIS shot: set it on+ // every call, or a shot inherits the exposure of whichever shot happened to build the renderer+ renderer.toneMapping = opts.toneMapping ?? THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = opts.exposure ?? 1;+ if ((camera as THREE.PerspectiveCamera).isPerspectiveCamera) { const c = camera as THREE.PerspectiveCamera; c.aspect = env.W / env.H; c.updateProjectionMatrix(); }+ scene.updateMatrixWorld(true);+ if (renderer.shadowMap.enabled) renderer.shadowMap.needsUpdate = true;+ renderer.setClearColor(0x000000, 0);+ renderer.render(scene, camera);+ const gl = renderer.getContext();+ if (gl.isContextLost()) throw new Error("draw3d: WebGL context lost. The frame was NOT drawn; re-render it in a fresh page.");+ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ const W = Math.round(env.W * env.scale), H = Math.round(env.H * env.scale);+ if (opts.clear !== null) { ctx.fillStyle = opts.clear ?? "#000"; ctx.fillRect(0, 0, W, H); }+ ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high";+ ctx.drawImage(renderer.domElement as CanvasImageSource, 0, 0, st.w, st.h, 0, 0, W, H);+ ctx.restore();+};++/** Seeded random for anything 3D: the same numbers on every machine. Never Math.random. */+export const rand = (seed: number) => {+ let a = seed >>> 0;+ return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };+};++/**+ * Report a 3D object's on-screen box to the frame probe, so framecheck.mjs catches 3D type or a+ * hero object cut by the frame edge (the 2D drawing code reports its boxes the same way). Call it+ * after positioning the camera, for anything the viewer must see whole. No cost unless framecheck+ * is running. The box is the projected corners of the object's world bounding box.+ */+const _box = new THREE.Box3(), _v = new THREE.Vector3();+export const probe3d = (ctx: Ctx, env: Env, object: THREE.Object3D, camera: THREE.Camera, label: string, kind: "text" | "box" = "text") => {+ if (!(globalThis as { __ANIDOODLE_PROBE__?: unknown }).__ANIDOODLE_PROBE__) return;+ if ((camera as THREE.PerspectiveCamera).isPerspectiveCamera) { const c = camera as THREE.PerspectiveCamera; c.aspect = env.W / env.H; c.updateProjectionMatrix(); }+ object.updateWorldMatrix(true, true); camera.updateMatrixWorld();+ _box.setFromObject(object); if (_box.isEmpty()) return;+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;+ for (let i = 0; i < 8; i++) {+ _v.set(i & 1 ? _box.max.x : _box.min.x, i & 2 ? _box.max.y : _box.min.y, i & 4 ? _box.max.z : _box.min.z).project(camera);+ if (_v.z > 1) continue; // behind the camera: not on screen+ const x = ((_v.x + 1) / 2) * env.W, y = ((1 - _v.y) / 2) * env.H;+ x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y);+ }+ if (!Number.isFinite(x0)) return;+ ctx.save(); ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.globalAlpha = 1;+ probeRect(ctx, env, x0, y0, x1 - x0, y1 - y0, label, kind);+ ctx.restore();+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/time.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/time.tsnew file mode 100644index 0000000..94f5d80--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/time.ts@@ -0,0 +1,79 @@+// TIME. The shared vocabulary every 3D module speaks. A frame number goes in, a number comes out;+// nothing here keeps state, so any frame can be drawn first.+//+// seg(f, a, b) 0 before frame a, 1 after frame b, linear between (the workhorse)+// ease.* shaping curves on [0, 1]+// spring(f, at, ...) a damped spring that was kicked at frame `at`, in closed form: follow-through+// and settle WITHOUT simulating from frame 0, so it stays seekable+// storyClock(...) maps the film's real frames onto the frames the shots were written in, so a+// narrator that stretches the film is a table edit, not 100 hand-moved numbers++export const clamp01 = (x: number) => (x < 0 ? 0 : x > 1 ? 1 : x);+export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;+/** progress of frame f through [a, b]: 0 before, 1 after */+export const seg = (f: number, a: number, b: number) => (b <= a ? (f >= a ? 1 : 0) : clamp01((f - a) / (b - a)));++export type Ease = (t: number) => number;+const back = 1.70158;+export const ease = {+ linear: ((t) => t) as Ease,+ inQuad: ((t) => t * t) as Ease,+ outQuad: ((t) => 1 - (1 - t) * (1 - t)) as Ease,+ inOutQuad: ((t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2)) as Ease,+ inCubic: ((t) => t * t * t) as Ease,+ outCubic: ((t) => 1 - (1 - t) ** 3) as Ease,+ inOutCubic: ((t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2)) as Ease,+ outQuint: ((t) => 1 - (1 - t) ** 5) as Ease,+ inOutSine: ((t) => -(Math.cos(Math.PI * t) - 1) / 2) as Ease,+ outExpo: ((t) => (t >= 1 ? 1 : 1 - 2 ** (-10 * t))) as Ease,+ inOutExpo: ((t) => (t <= 0 ? 0 : t >= 1 ? 1 : t < 0.5 ? 2 ** (20 * t - 10) / 2 : (2 - 2 ** (-20 * t + 10)) / 2)) as Ease,+ /** overshoots then lands: pops, drops, arrivals */+ outBack: ((t) => 1 + (back + 1) * (t - 1) ** 3 + back * (t - 1) ** 2) as Ease,+ /** pulls back first: anticipation before a move */+ inBack: ((t) => (back + 1) * t * t * t - back * t * t) as Ease,+ outElastic: ((t) => (t <= 0 ? 0 : t >= 1 ? 1 : 2 ** (-10 * t) * Math.sin((t * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1)) as Ease,+ outBounce: ((t) => { const n = 7.5625, d = 2.75; if (t < 1 / d) return n * t * t; if (t < 2 / d) return n * (t -= 1.5 / d) * t + 0.75; if (t < 2.5 / d) return n * (t -= 2.25 / d) * t + 0.9375; return n * (t -= 2.625 / d) * t + 0.984375; }) as Ease,+ /** smoothstep: soft in and out, the default for camera moves */+ smooth: ((t) => t * t * (3 - 2 * t)) as Ease,+};+/** eased progress of frame f through [a, b] */+export const tween = (f: number, a: number, b: number, e: Ease = ease.inOutCubic) => e(seg(f, a, b));++/**+ * A damped spring kicked at frame `at`: returns the displacement (starting at 1, ringing down to 0)+ * at frame f. Multiply by an amplitude for follow-through (an antenna after a stop, a jar swinging+ * after a turn). Closed form, so frame 300 never needs frames 0-299. freq in Hz, damping 0-1.+ */+export const spring = (f: number, at: number, fps: number, freq = 2.2, damping = 0.28) => {+ // a 0 fps or a 0 Hz spring has no time to ring in: it would return NaN, and a NaN position draws nothing+ if (!(fps > 0) || !Number.isFinite(fps)) throw new Error(`spring: fps must be a positive number of frames per second (got ${fps})`);+ if (!(freq > 0) || !Number.isFinite(freq)) throw new Error(`spring: freq must be a positive number of Hz (got ${freq})`);+ if (f < at) return 0;+ const t = (f - at) / fps, w = 2 * Math.PI * freq, z = Math.min(0.999, Math.max(0, damping)), wd = w * Math.sqrt(1 - z * z);+ return Math.exp(-z * w * t) * (Math.cos(wd * t) + ((z * w) / wd) * Math.sin(wd * t));+};++/** frames per beat at a tempo; integer when the film's grid is valid (validate() enforces it) */+export const beatFrames = (bpm: number, fps: number) => (60 * fps) / bpm;++/**+ * STORY CLOCK. Shots are written against story frames (the grid they were planned on). When the+ * narration or the score stretches the film, give the real frame of each story anchor and every+ * shot follows: between anchors, time maps linearly. Anchors must increase in both columns.+ * const clock = storyClock([[0, 0], [240, 300], [480, 590]]); // [storyFrame, realFrame]+ * draw: (ctx, local, env) => shot(clock.story(start + local) - storyStart)+ * real(f) goes the other way. For cyclic motion that must keep its real speed (a walk, flicker),+ * use the real frame directly.+ */+export const storyClock = (anchors: [story: number, real: number][]) => {+ if (!anchors.length) throw new Error("storyClock: give at least one [storyFrame, realFrame] anchor");+ const a = [...anchors].sort((x, y) => x[0] - y[0]);+ for (let i = 1; i < a.length; i++) if (!(a[i][0] > a[i - 1][0] && a[i][1] > a[i - 1][1])) throw new Error(`storyClock: anchors must increase in both columns (at ${a[i - 1]} -> ${a[i]})`);+ const map = (x: number, from: 0 | 1, to: 0 | 1) => {+ if (a.length === 1) return x - a[0][from] + a[0][to];+ let i = 0; while (i < a.length - 2 && x > a[i + 1][from]) i++;+ const [p, q] = [a[i], a[i + 1]];+ return p[to] + ((x - p[from]) * (q[to] - p[to])) / (q[from] - p[from]);+ };+ return { story: (real: number) => map(real, 1, 0), real: (story: number) => map(story, 0, 1) };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/timeline.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/timeline.tsnew file mode 100644index 0000000..e1ba964--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/timeline.ts@@ -0,0 +1,174 @@+// TIMELINE. Author motion the way a director talks ("these three pop in one after another, then the+// title slides up on the word 'three'"), compile it to a flat list of timed tweens, and read any+// track at any frame. Nothing is played: tl.value(name, f) is a pure lookup, so frame 300 never needs+// frames 0-299 and parallel renders agree.+//+// const tl = timeline(24, { labels: { drop: 48 }, words: [{ text: "three", frame: 96 }] });+// tl.at(0, set("x", 0), set("tint", "#ff6b5b"));+// tl.at("drop", chain(to("x", 2, 12, ease.outBack), wait(6), to("x", 0, 12)));+// tl.at({ word: "three" }, sequence(3, to("a", 1, 8), to("b", 1, 8), to("c", 1, 8)));+// draw: mesh.position.x = tl.num("x", f);+//+// Rules that keep it honest:+// - A clip is placed RELATIVE to where its parent puts it; only tl.at() names absolute frames (a+// number, a label, or a spoken word), so beats can come from narration timing later.+// - A tween with no `from` starts from whatever the track holds when it starts (the previous+// tween's end), resolved once at compile time. A track with nothing before it must be set() or+// use fromTo(), or compile throws: a silent 0 is how a prop teleports on frame 1.+// - Before the first key a track holds its first value; after the last it holds its last.+// - Colours mix in LINEAR light: sRGB midpoints read muddy and dark (red to green through brown).+// - check() names two tweens writing one track at once (the later-starting one wins, which is+// rarely what was meant) and cues off the beat grid.+import { ease as E, type Ease } from "./time";++export type Vec3 = [number, number, number];+/** a track's value: a number, an [x, y, z] vector, or a "#rrggbb" colour */+export type Value = number | Vec3 | string;+export type Tween = { track: string; start: number; end: number; from?: Value; to: Value; ease: Ease; src: string };+/** a piece of motion that does not know where it sits yet: emit() writes its tweens from `start` and returns its length */+export type Clip = { len: number; emit: (start: number, out: Tween[]) => void };+export type When = number | string | { label: string; offset?: number } | { word: string; nth?: number; offset?: number };++// ---- values+const hex = (s: string): Vec3 => {+ const m = /^#?([0-9a-f]{6})$/i.exec(s.trim()) ?? /^#?([0-9a-f]{3})$/i.exec(s.trim());+ if (!m) throw new Error(`timeline: '${s}' is not a #rrggbb colour`);+ const h = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1];+ return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) / 255) as Vec3;+};+const toLin = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);+const toSrgb = (c: number) => (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055);+const byte = (c: number) => Math.max(0, Math.min(255, Math.round(c * 255))).toString(16).padStart(2, "0");+/** a #rrggbb colour as linear-light rgb in [0, 1] (what three's Color holds internally) */+export const linear = (s: string): Vec3 => hex(s).map(toLin) as Vec3;+/** mix two values at t: numbers and vectors linearly, colours in linear light (returned as #rrggbb) */+export const mix = (a: Value, b: Value, t: number): Value => {+ if (typeof a === "number" && typeof b === "number") return a + (b - a) * t;+ if (typeof a === "string" && typeof b === "string") { const p = linear(a), q = linear(b); return "#" + p.map((x, i) => byte(toSrgb(x + (q[i] - x) * t))).join(""); }+ if (Array.isArray(a) && Array.isArray(b) && a.length === 3 && b.length === 3) return [0, 1, 2].map((i) => a[i] + (b[i] - a[i]) * t) as Vec3;+ throw new Error(`timeline: cannot mix ${JSON.stringify(a)} with ${JSON.stringify(b)} (one track, one kind of value)`);+};++// ---- clips (relative time)+const whole = (n: number, what: string) => { if (!Number.isFinite(n) || n < 0) throw new Error(`timeline: ${what} must be a frame count >= 0, got ${n}`); return n; };+/** move a track to `value` over `frames`, starting from wherever it is */+export const to = (track: string, value: Value, frames: number, e: Ease = E.inOutCubic): Clip => ({ len: whole(frames, "to() length"), emit: (s, o) => o.push({ track, start: s, end: s + frames, to: value, ease: e, src: `to(${track})` }) });+/** move a track from `a` to `b` over `frames` (jumps to `a` when it starts) */+export const fromTo = (track: string, a: Value, b: Value, frames: number, e: Ease = E.inOutCubic): Clip => ({ len: whole(frames, "fromTo() length"), emit: (s, o) => o.push({ track, start: s, end: s + frames, from: a, to: b, ease: e, src: `fromTo(${track})` }) });+/** jump a track to `value` with no motion */+export const set = (track: string, value: Value): Clip => ({ len: 0, emit: (s, o) => o.push({ track, start: s, end: s, from: value, to: value, ease: E.linear, src: `set(${track})` }) });+/** nothing for n frames (a held breath inside a chain) */+export const wait = (n: number): Clip => ({ len: whole(n, "wait()"), emit: () => {} });+/** play clips together; lasts as long as the longest */+export const all = (...clips: Clip[]): Clip => ({ len: Math.max(0, ...clips.map((c) => c.len)), emit: (s, o) => clips.forEach((c) => c.emit(s, o)) });+/** play clips one after another */+export const chain = (...clips: Clip[]): Clip => ({ len: clips.reduce((n, c) => n + c.len, 0), emit: (s, o) => { let t = s; for (const c of clips) { c.emit(t, o); t += c.len; } } });+/** start each clip `stagger` frames after the one before (Manim's LaggedStart) */+export const sequence = (stagger: number, ...clips: Clip[]): Clip => ({ len: Math.max(0, ...clips.map((c, i) => i * stagger + c.len)), emit: (s, o) => clips.forEach((c, i) => c.emit(s + i * whole(stagger, "sequence() stagger"), o)) });+/** start a clip n frames late */+export const delay = (n: number, ...clips: Clip[]): Clip => chain(wait(n), all(...clips));+/** play a clip n times back to back; pass a function of the pass index to vary each pass */+export const loop = (n: number, clip: Clip | ((i: number) => Clip)): Clip => chain(...Array.from({ length: whole(n, "loop() count") }, (_, i) => (typeof clip === "function" ? clip(i) : clip)));++export type TimelineOpts = { labels?: Record<string, number>; words?: { text: string; frame: number }[]; beat?: number };+export type Issue = { track?: string; frame: number; msg: string };++/** a seekable timeline at `fps`; labels and spoken-word cues may be passed in from narration timing */+export const timeline = (fps: number, opts: TimelineOpts = {}) => {+ const labels: Record<string, number> = { ...(opts.labels ?? {}) };+ const placed: { at: number; src: string; tweens: Tween[] }[] = [];+ let compiled: Map<string, (Tween & { from: Value })[]> | null = null;++ const resolve = (w: When): number => {+ if (typeof w === "number") return w;+ if (typeof w === "string") { if (!(w in labels)) throw new Error(`timeline: no label '${w}' (have: ${Object.keys(labels).join(", ") || "none"})`); return labels[w]; }+ if ("label" in w) return resolve(w.label) + (w.offset ?? 0);+ const hits = (opts.words ?? []).filter((x) => x.text.toLowerCase().replace(/[^\p{L}\p{N}']/gu, "") === w.word.toLowerCase());+ const hit = hits[w.nth ?? 0];+ if (!hit) throw new Error(`timeline: the word '${w.word}'${w.nth ? ` (#${w.nth})` : ""} is not in the narration timing`);+ return hit.frame + (w.offset ?? 0);+ };++ const compile = () => {+ if (compiled) return compiled;+ const by = new Map<string, Tween[]>();+ for (const p of placed) for (const t of p.tweens) { if (!by.has(t.track)) by.set(t.track, []); by.get(t.track)!.push(t); }+ compiled = new Map();+ for (const [track, list] of by) {+ // stable sort: same start keeps authored order, so a set() then a to() at one frame reads right+ const ts = list.map((t, i) => ({ t, i })).sort((a, b) => a.t.start - b.t.start || a.i - b.i).map((x) => x.t);+ const out: (Tween & { from: Value })[] = [];+ for (const t of ts) {+ let from = t.from;+ if (from === undefined) {+ if (!out.length) throw new Error(`timeline: track '${track}' moves at frame ${t.start} with no starting value: set() it first or use fromTo()`);+ from = evalTrack(out, t.start);+ }+ out.push({ ...t, from });+ }+ compiled.set(track, out);+ }+ return compiled;+ };++ // the track's value at frame f: the latest tween that has started wins; before any, the first value+ const evalTrack = (ts: (Tween & { from: Value })[], f: number): Value => {+ if (f < ts[0].start) return ts[0].from;+ let k = 0;+ for (let i = 0; i < ts.length; i++) if (ts[i].start <= f) k = i;+ const t = ts[k];+ if (f >= t.end) return t.to;+ return mix(t.from, t.to, t.ease((f - t.start) / (t.end - t.start)));+ };++ const tl = {+ fps,+ labels,+ /** name a cue frame so clips can be placed on it */+ label(name: string, frame: number) { labels[name] = frame; return tl; },+ /** frame of a label, a word cue or a number */+ frame: resolve,+ /** place clips (played together) at an absolute frame, label or spoken word */+ at(w: When, ...clips: Clip[]) {+ const at = resolve(w), tweens: Tween[] = [];+ all(...clips).emit(at, tweens);+ placed.push({ at, src: typeof w === "object" ? JSON.stringify(w) : String(w), tweens });+ compiled = null;+ return tl;+ },+ /** last frame any tween reaches */+ get end() { return Math.max(0, ...placed.flatMap((p) => p.tweens.map((t) => t.end))); },+ tracks: () => [...compile().keys()],+ /** every compiled tween, in time order per track (for tests and debugging) */+ tweens: (track?: string) => (track ? compile().get(track) ?? [] : [...compile().values()].flat()),+ /** a track's value at frame f */+ value(track: string, f: number): Value {+ const ts = compile().get(track);+ if (!ts) throw new Error(`timeline: no track '${track}'`);+ return evalTrack(ts, f);+ },+ num: (track: string, f: number) => { const v = tl.value(track, f); if (typeof v !== "number") throw new Error(`timeline: track '${track}' is not a number`); return v; },+ vec: (track: string, f: number) => { const v = tl.value(track, f); if (!Array.isArray(v)) throw new Error(`timeline: track '${track}' is not a vector`); return v; },+ color: (track: string, f: number) => { const v = tl.value(track, f); if (typeof v !== "string") throw new Error(`timeline: track '${track}' is not a colour`); return v; },+ /** every track's value at frame f */+ sample(f: number): Record<string, Value> { const o: Record<string, Value> = {}; for (const [k, ts] of compile()) o[k] = evalTrack(ts, f); return o; },+ /** tweens fighting over one track, and cues (tl.at placements) off the beat grid */+ check(grid: { beat?: number; subdiv?: number } = {}): Issue[] {+ const issues: Issue[] = [];+ for (const [track, ts] of compile()) {+ for (let i = 0; i < ts.length; i++) for (let j = i + 1; j < ts.length; j++) {+ const a = ts[i], b = ts[j];+ if (b.start < a.end && a.end > a.start && b.end > b.start) issues.push({ track, frame: b.start, msg: `track '${track}': ${b.src} ${b.start}-${b.end} starts while ${a.src} ${a.start}-${a.end} is still moving (they fight; the later one wins)` });+ }+ }+ const beat = grid.beat ?? opts.beat;+ if (beat) {+ const step = beat / (grid.subdiv ?? 1);+ for (const p of placed) if (Math.abs(p.at / step - Math.round(p.at / step)) > 1e-9) issues.push({ frame: p.at, msg: `cue ${p.src} at frame ${p.at} is off the beat grid (every ${step} frames)` });+ }+ return issues;+ },+ };+ return tl;+};+export type Timeline = ReturnType<typeof timeline>;diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/transitions.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/transitions.tsnew file mode 100644index 0000000..27494f9--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/transitions.ts@@ -0,0 +1,194 @@+// TRANSITIONS between two shots, pure in the frame. Each side draws a whole frame into its own+// offscreen layer (env.canvas), then the two are combined on the frame. Works with draw3d: draw3d+// targets whatever ctx it is handed, so a 3D shot renders into a layer like into the frame.+//+// transition(ctx, env, t, crossfade(), (c) => shotA(c, fA), (c) => shotB(c, fB))+//+// crossfade() dissolve+// wipe("right") a soft straight edge travelling right (B enters from the left)+// radialWipe({ x, y }) an iris opening from a point (0-1 of the frame), B inside it+// noiseWipe(seed) an ink-blot dissolve: B spreads in blots of seeded noise, with an ink rim+// slide("left") B pushes A out of frame, both moving left+// zoomThrough() the camera flies through A, which grows and fades, onto B settling in+//+// t is the transition's own progress, 0 to 1 (use time.ts seg(f, a, b)). Each kind eases it. At+// t <= 0 only A is drawn, straight onto the frame; at t >= 1 only B. So the frames either side of+// a transition are exactly the shots' own frames, bit for bit, never "almost".+// The mask maths (wipeAlpha, radialAlpha, noiseMask) are pure functions, held to numbers in+// test/threeTransitions.test.ts.+import type { Ctx, Env, Layer } from "../canvas-core/core";+import { fractal } from "../canvas-core/core";+import * as THREE from "three";+import { ease, type Ease } from "./time";++export type DrawInto = (ctx: Ctx, env: Env) => void;+export type Dir = "left" | "right" | "up" | "down";+type Base = { ease?: Ease };+export type TransitionKind =+ | (Base & { kind: "crossfade" })+ | (Base & { kind: "wipe"; dir: Dir; feather: number })+ | (Base & { kind: "radial"; x: number; y: number; feather: number })+ | (Base & { kind: "noise"; seed: number; scale: number; soft: number; ink: string | null; inkWidth: number })+ | (Base & { kind: "slide"; dir: Dir })+ | (Base & { kind: "zoom"; amount: number });++/** a plain dissolve */+export const crossfade = (o: Base = {}): TransitionKind => ({ kind: "crossfade", ...o });+/** a straight soft edge that travels in `dir`; feather in frame pixels */+export const wipe = (dir: Dir = "right", o: Base & { feather?: number } = {}): TransitionKind => ({ kind: "wipe", dir, feather: o.feather ?? 60, ease: o.ease });+/** an iris opening from (x, y), given as 0-1 of the frame; feather in frame pixels */+export const radialWipe = (o: Base & { x?: number; y?: number; feather?: number } = {}): TransitionKind => ({ kind: "radial", x: o.x ?? 0.5, y: o.y ?? 0.5, feather: o.feather ?? 80, ease: o.ease });+/** an ink-blot dissolve from seeded noise; scale = blot size in frame pixels; ink = rim colour (null for none) */+export const noiseWipe = (seed = 1, o: Base & { scale?: number; soft?: number; ink?: string | null; inkWidth?: number } = {}): TransitionKind => {+ const ink = o.ink === undefined ? "#1b1622" : o.ink;+ if (ink) inkRGB(ink); // a bad colour fails here, where the wipe is written, not mid-render+ return { kind: "noise", seed, scale: o.scale ?? 360, soft: o.soft ?? 0.02, ink, inkWidth: o.inkWidth ?? 0.014, ease: o.ease ?? ease.inOutSine };+};+/** B pushes A out: both move in `dir` */+export const slide = (dir: Dir = "left", o: Base = {}): TransitionKind => ({ kind: "slide", dir, ease: o.ease });+/** fly through A onto B; amount = how far A grows (4 = to four times its size); A is gone by 52 % so the middle never reads as a double exposure */+export const zoomThrough = (o: Base & { amount?: number } = {}): TransitionKind => ({ kind: "zoom", amount: o.amount ?? 4, ease: o.ease ?? ease.inOutCubic });++const clamp01 = (x: number) => (x < 0 ? 0 : x > 1 ? 1 : x);++// ---------------------------------------------------------------- pure mask maths+/**+ * B's opacity at (x, y) for a straight wipe at eased progress e. The edge runs from one feather+ * BEFORE the frame to one feather PAST it, so e = 0 shows none of B and e = 1 all of it.+ */+export const wipeAlpha = (x: number, y: number, w: number, h: number, e: number, dir: Dir, feather: number) => {+ const along = dir === "right" ? x : dir === "left" ? w - x : dir === "down" ? y : h - y, L = dir === "left" || dir === "right" ? w : h;+ const f = Math.max(1e-6, feather), edge = -f + (L + 2 * f) * e;+ return clamp01((edge - along) / f);+};+/** B's opacity at (x, y) for an iris from (cx, cy): the radius grows from 0 to the farthest corner plus one feather */+export const radialAlpha = (x: number, y: number, w: number, h: number, e: number, cx: number, cy: number, feather: number) => {+ const f = Math.max(1e-6, feather), far = Math.max(Math.hypot(cx, cy), Math.hypot(w - cx, cy), Math.hypot(cx, h - cy), Math.hypot(w - cx, h - cy));+ const r = (far + f) * e;+ return clamp01((r - Math.hypot(x - cx, y - cy)) / f);+};+/**+ * The ink-blot mask on a w x h grid (one cell per few frame pixels; the caller scales it up+ * smoothly, which softens the edge). Noise in [0, 1] per cell; B shows where the noise sits under+ * a threshold that sweeps from below 0 to above 1, so e = 0 is exactly none and e = 1 exactly all.+ * `ink` is a thin band riding the edge, like wet ink spreading.+ */+export const noiseMask = (seed: number, e: number, w: number, h: number, o: { cell?: number; scale?: number; soft?: number; inkWidth?: number; ink?: boolean } = {}) => {+ const cell = o.cell ?? 4, scale = o.scale ?? 360, soft = o.soft ?? 0.035, iw = o.ink === false ? 0 : (o.inkWidth ?? 0.03);+ const reach = soft + iw, thr = -reach + (1 + 2 * reach) * e;+ const alpha = new Uint8ClampedArray(w * h), ink = iw > 0 ? new Uint8ClampedArray(w * h) : null;+ const field = blotField(seed, w, h, cell / scale);+ for (let p = 0; p < w * h; p++) {+ const n = field[p], a = clamp01((thr - n) / soft + 0.5);+ alpha[p] = Math.round(a * 255);+ if (ink) { const d = n - thr; ink[p] = d > -iw && d < iw ? Math.round((1 - Math.abs(d) / iw) * 255) : 0; }+ }+ return { alpha, ink };+};+// The blot field: three octaves of gradient noise, then RANK-equalised to 0-1, so the share of+// the frame that has turned to B tracks the transition's progress evenly (raw noise bunches in the+// middle: the dissolve would stall, then rush). Kept per (seed, size): it does not depend on time.+const fields = new Map<string, Float32Array>();+const blotField = (seed: number, w: number, h: number, k: number) => {+ const key = `${seed}:${w}x${h}:${k}`, hit = fields.get(key); if (hit) return hit;+ const raw = new Float32Array(w * h);+ for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) raw[j * w + i] = fractal(seed, i * k, j * k, 1, 1, 3);+ const order = Array.from(raw.keys()).sort((a, b) => raw[a] - raw[b] || a - b), out = new Float32Array(w * h), last = Math.max(1, order.length - 1);+ order.forEach((p, r) => (out[p] = r / last));+ if (fields.size > 8) fields.delete(fields.keys().next().value!);+ fields.set(key, out); return out;+};+/** where each layer sits for a slide at eased e: offsets in frame pixels for A and B */+export const slideOffsets = (e: number, dir: Dir, w: number, h: number) => {+ const [dx, dy] = dir === "left" ? [-w, 0] : dir === "right" ? [w, 0] : dir === "up" ? [0, -h] : [0, h];+ return { a: [dx * e, dy * e] as [number, number], b: [dx * (e - 1), dy * (e - 1)] as [number, number] };+};++// ---------------------------------------------------------------- layers+let depth = 0; // a transition inside a transition gets its own layers (only during one call: no frame state)+const layer = (env: Env, slot: string, w: number, h: number): Layer => {+ const key = `three:tx:${depth}:${slot}:${w}x${h}`;+ let l = env.cache.get(key) as Layer | undefined;+ if (!l) { l = env.canvas(w, h); env.cache.set(key, l); }+ const c = l.ctx as Ctx & { reset?: () => void };+ if (typeof c.reset === "function") c.reset(); else { c.setTransform(1, 0, 0, 1, 0, 0); c.globalAlpha = 1; c.globalCompositeOperation = "source-over"; }+ c.clearRect(0, 0, w, h);+ return l;+};+const putMask = (env: Env, slot: string, w: number, h: number, a: Uint8ClampedArray, rgb: [number, number, number] = [0, 0, 0]) => {+ const l = layer(env, slot, w, h), img = l.ctx.createImageData(w, h);+ for (let p = 0; p < a.length; p++) { const q = p * 4; img.data[q] = rgb[0]; img.data[q + 1] = rgb[1]; img.data[q + 2] = rgb[2]; img.data[q + 3] = a[p]; }+ l.ctx.putImageData(img, 0, 0); return l;+};+/**+ * The rim colour as 0-255 sRGB. Hex is read exactly; any other CSS colour (a name, rgb(), hsl()) goes+ * through three's own CSS parser. Anything else throws: a hex-only parser read "red" as a dark teal+ * and drew it without a word.+ */+export const inkRGB = (s: string): [number, number, number] => {+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(s.trim());+ if (m) { const v = m[1].length === 3 ? m[1].split("").map((c) => c + c).join("") : m[1]; return [0, 2, 4].map((i) => parseInt(v.slice(i, i + 2), 16)) as [number, number, number]; }+ const c = new THREE.Color(); c.r = -1; // three leaves an unknown colour untouched, so -1 marks "not parsed"+ const t = typeof s === "string" ? s.trim() : "";+ // only a CSS name, rgb() or hsl() reaches three's parser (so it never prints its own warning)+ if (/^(rgb|hsl)a?\(/i.test(t) || Object.hasOwn(THREE.Color.NAMES, t.toLowerCase())) c.setStyle(t);+ if (c.r === -1) throw new Error(`noiseWipe: ink "${s}" is not a colour (use hex like "#1b1622", a CSS name, rgb() or hsl())`);+ const h = c.getHex(); return [(h >> 16) & 255, (h >> 8) & 255, h & 255];+};++/**+ * Draw the frame of a transition at progress t (0-1) from what drawA and drawB paint. Each draw+ * gets a clean, full-size, untransformed context, exactly like a shot's draw gets the frame.+ */+export const transition = (ctx: Ctx, env: Env, t: number, kind: TransitionKind, drawA: DrawInto, drawB: DrawInto) => {+ if (t <= 0) { drawA(ctx, env); return; }+ if (t >= 1) { drawB(ctx, env); return; }+ const e = (kind.ease ?? ease.inOutCubic)(t), W = Math.round(env.W * env.scale), H = Math.round(env.H * env.scale), s = env.scale;+ depth++;+ try {+ const A = layer(env, "a", W, H); drawA(A.ctx, env);+ const B = layer(env, "b", W, H); drawB(B.ctx, env);+ ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high";+ ctx.clearRect(0, 0, W, H);+ const src = (l: Layer) => l.canvas as CanvasImageSource;+ switch (kind.kind) {+ case "crossfade": ctx.drawImage(src(A), 0, 0); ctx.globalAlpha = e; ctx.drawImage(src(B), 0, 0); break;+ case "slide": { const o = slideOffsets(e, kind.dir, W, H); ctx.drawImage(src(A), o.a[0], o.a[1]); ctx.drawImage(src(B), o.b[0], o.b[1]); break; }+ case "zoom": {+ // B settles from a little large to its own size underneath; A grows past the camera and fades+ const sb = 1 + 0.25 * (1 - e), sa = 1 + (kind.amount - 1) * e * e, fade = 1 - clamp01((e - 0.12) / 0.4);+ const at = (l: Layer, k: number) => ctx.drawImage(src(l), (W - W * k) / 2, (H - H * k) / 2, W * k, H * k);+ at(B, sb); ctx.globalAlpha = fade; at(A, sa); break;+ }+ case "wipe": case "radial": {+ // B keeps only what the mask lets through, then lands on A+ const g = kind.kind === "wipe" ? linearMask(B.ctx, W, H, e, kind.dir, kind.feather * s) : radialMask(B.ctx, W, H, e, kind.x * W, kind.y * H, kind.feather * s);+ B.ctx.save(); B.ctx.globalCompositeOperation = "destination-in"; B.ctx.fillStyle = g; B.ctx.fillRect(0, 0, W, H); B.ctx.restore();+ ctx.drawImage(src(A), 0, 0); ctx.drawImage(src(B), 0, 0); break;+ }+ case "noise": {+ const cell = 2 * s, mw = Math.ceil(W / cell), mh = Math.ceil(H / cell);+ const m = noiseMask(kind.seed, e, mw, mh, { cell: 2, scale: kind.scale, soft: kind.soft, inkWidth: kind.inkWidth, ink: !!kind.ink });+ const M = putMask(env, "m", mw, mh, m.alpha);+ B.ctx.save(); B.ctx.globalCompositeOperation = "destination-in"; B.ctx.imageSmoothingEnabled = true; B.ctx.imageSmoothingQuality = "high"; B.ctx.drawImage(src(M), 0, 0, mw * cell, mh * cell); B.ctx.restore();+ ctx.drawImage(src(A), 0, 0); ctx.drawImage(src(B), 0, 0);+ if (m.ink && kind.ink) { const I = putMask(env, "i", mw, mh, m.ink, inkRGB(kind.ink)); ctx.drawImage(src(I), 0, 0, mw * cell, mh * cell); }+ break;+ }+ }+ ctx.restore();+ } finally { depth--; }+};+// gradients that match wipeAlpha / radialAlpha exactly (alpha 1 behind the edge, 0 one feather ahead)+const linearMask = (c: Ctx, W: number, H: number, e: number, dir: Dir, f: number) => {+ const L = dir === "left" || dir === "right" ? W : H, edge = -f + (L + 2 * f) * e, a = edge - f, b = edge;+ const pt = (v: number): [number, number] => (dir === "right" ? [v, 0] : dir === "left" ? [W - v, 0] : dir === "down" ? [0, v] : [0, H - v]);+ const [x0, y0] = pt(a), [x1, y1] = pt(b), g = c.createLinearGradient(x0, y0, x1, y1);+ g.addColorStop(0, "rgba(0,0,0,1)"); g.addColorStop(1, "rgba(0,0,0,0)"); return g;+};+const radialMask = (c: Ctx, W: number, H: number, e: number, cx: number, cy: number, f: number) => {+ const far = Math.max(Math.hypot(cx, cy), Math.hypot(W - cx, cy), Math.hypot(cx, H - cy), Math.hypot(W - cx, H - cy)), r = (far + f) * e;+ const g = c.createRadialGradient(cx, cy, Math.max(0, r - f), cx, cy, Math.max(1e-3, r));+ // while r < f even the centre is only part-way in+ g.addColorStop(0, `rgba(0,0,0,${Math.min(1, r / f).toFixed(4)})`); g.addColorStop(1, "rgba(0,0,0,0)"); return g;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/ttf.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/ttf.tsnew file mode 100644index 0000000..7f00926--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/ttf.ts@@ -0,0 +1,275 @@+// TTF. A small TrueType reader with no library behind it, so 3D type needs nothing fetched and+// nothing new vendored: the font arrives as bytes inside the film (a base64 string module) and is+// parsed here, the same on every machine. It reads only what extruded and flat type need:+//+// cmap character -> glyph (format 4 for the BMP, format 12 for the rest)+// head/maxp units per em, how loca is stored, glyph count+// loca/glyf outlines: simple glyphs (quadratic curves, implied on-curve points) and composites+// hhea/hmtx advance widths+// kern / GPOS pair kerning (kern format 0; GPOS lookup type 2, formats 1 and 2, via extensions too)+// OS/2, name cap height, and the family / licence strings so a test can check what was bundled+//+// Outlines come out in FONT UNITS, y up, as contours of quadratic segments. CFF fonts (.otf with+// PostScript outlines) are refused by name: they hold cubic curves in a different program format.+//+// const font = parseTTF(bytes) bytes: Uint8Array | ArrayBuffer | base64 string+// font.glyphIndex("A".codePointAt(0)!) -> glyph id (0 = .notdef, the font has no such letter)+// font.glyph(id) -> { contours, advance, lsb, bbox }+// font.kerning(left, right) -> font units to add between two glyph ids++export type Seg = ["M", number, number] | ["L", number, number] | ["Q", number, number, number, number];+/** one closed outline: an "M" then L/Q segments, ending back at the start */+export type Contour = Seg[];+export type GlyphOutline = { id: number; contours: Contour[]; advance: number; lsb: number; bbox: [xMin: number, yMin: number, xMax: number, yMax: number] };+export type Font = {+ /** a short stable id (family, style, byte length, checksum): the cache key for anything built from it */+ id: string;+ family: string; style: string; copyright: string; license: string; licenseUrl: string;+ unitsPerEm: number; ascender: number; descender: number; lineGap: number; capHeight: number; xHeight: number;+ numGlyphs: number;+ glyphIndex(codePoint: number): number;+ glyph(id: number): GlyphOutline;+ kerning(left: number, right: number): number;+};++const fail = (msg: string): never => { throw new Error(`ttf: ${msg}`); };++/** bytes from a Uint8Array, an ArrayBuffer or a base64 string (how films carry the font) */+export const fontBytes = (src: Uint8Array | ArrayBuffer | string): Uint8Array => {+ if (src instanceof Uint8Array) return src;+ if (src instanceof ArrayBuffer) return new Uint8Array(src);+ const bin = atob(src.replace(/\s+/g, "")), u8 = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i);+ return u8;+};++export const parseTTF = (src: Uint8Array | ArrayBuffer | string): Font => {+ const u8 = fontBytes(src);+ if (u8.length < 12) fail(`only ${u8.length} bytes: this is not a font file (truncated?)`);+ const dv = new DataView(u8.buffer, u8.byteOffset, u8.byteLength);+ const tag = (o: number) => String.fromCharCode(u8[o], u8[o + 1], u8[o + 2], u8[o + 3]);+ const sig = tag(0);+ if (sig === "OTTO") fail("this font has CFF outlines; use a TrueType .ttf");+ if (sig === "ttcf") fail("this is a font collection (.ttc); export the one face you want as a .ttf");+ if (sig === "wOFF" || sig === "wOF2") fail(`this is a ${sig === "wOFF" ? "WOFF" : "WOFF2"} web font (compressed); use the TrueType .ttf it was made from`);+ if (dv.getUint32(0) !== 0x00010000 && sig !== "true") fail(`unknown font signature '${sig}'; use a TrueType .ttf`);++ // ---- table directory. Every read below is bounds-checked by DataView, but a truncated file+ // would throw a bare RangeError: check each table fits first and say which one is cut short.+ const tables = new Map<string, { off: number; len: number }>();+ const n = dv.getUint16(4);+ if (12 + n * 16 > u8.length) fail(`the table directory is cut short (${n} tables, ${u8.length} bytes): truncated file`);+ for (let i = 0; i < n; i++) {+ const o = 12 + i * 16, t = tag(o), off = dv.getUint32(o + 8), len = dv.getUint32(o + 12);+ if (off + len > u8.length) fail(`table '${t}' runs past the end of the file (needs ${off + len} bytes, has ${u8.length}): truncated file`);+ tables.set(t, { off, len });+ }+ if (tables.has("CFF ") || tables.has("CFF2")) fail("this font has CFF outlines; use a TrueType .ttf");+ const need = (t: string) => tables.get(t) ?? fail(`missing required table '${t}'`);+ const u16 = (o: number) => dv.getUint16(o), i16 = (o: number) => dv.getInt16(o), u32 = (o: number) => dv.getUint32(o);++ const head = need("head").off, maxp = need("maxp").off, hhea = need("hhea").off, hmtx = need("hmtx").off;+ const loca = need("loca").off, glyf = need("glyf"), cmapT = need("cmap").off;+ const unitsPerEm = u16(head + 18), longLoca = i16(head + 50) === 1, numGlyphs = u16(maxp + 4);+ const ascender = i16(hhea + 4), descender = i16(hhea + 6), lineGap = i16(hhea + 8), nHM = u16(hhea + 34);++ // ---- name: family, style, copyright, licence (Windows Unicode first, then Mac Roman)+ const names: Record<number, string> = {};+ const nameT = tables.get("name");+ if (nameT) {+ const base = nameT.off, count = u16(base + 2), strs = base + u16(base + 4);+ for (let i = 0; i < count; i++) {+ const r = base + 6 + i * 12, plat = u16(r), enc = u16(r + 2), id = u16(r + 6), len = u16(r + 8), off = strs + u16(r + 10);+ if (off + len > u8.length) continue;+ if (plat === 3 && (enc === 1 || enc === 10)) { let s = ""; for (let k = 0; k < len; k += 2) s += String.fromCharCode(u16(off + k)); names[id] = s; }+ else if (plat === 1 && enc === 0 && names[id] === undefined) { let s = ""; for (let k = 0; k < len; k++) s += String.fromCharCode(u8[off + k]); names[id] = s; }+ }+ }++ // ---- glyph locations and outlines+ const glyphRange = (id: number): [number, number] => {+ if (id < 0 || id >= numGlyphs) return [0, 0];+ const a = longLoca ? u32(loca + id * 4) : u16(loca + id * 2) * 2, b = longLoca ? u32(loca + id * 4 + 4) : u16(loca + id * 2 + 2) * 2;+ if (b < a || a > glyf.len) fail(`loca entry for glyph ${id} is out of order or past glyf: damaged file`);+ return [glyf.off + a, glyf.off + Math.min(b, glyf.len)];+ };+ const advanceOf = (id: number) => u16(hmtx + Math.min(id, nHM - 1) * 4);+ const lsbOf = (id: number) => (id < nHM ? i16(hmtx + id * 4 + 2) : i16(hmtx + nHM * 4 + (id - nHM) * 2));++ type Pt = { x: number; y: number; on: boolean };+ // raw points per contour, before curves are made; composites concatenate their parts' contours+ const points = (id: number, depth = 0): Pt[][] => {+ if (depth > 8) fail(`glyph ${id}: composite glyphs nest deeper than 8 (a loop?)`);+ const [a, b] = glyphRange(id);+ if (b - a < 10) return []; // an empty glyph (space): no outline at all+ const nc = i16(a);+ if (nc >= 0) {+ const ends: number[] = []; for (let i = 0; i < nc; i++) ends.push(u16(a + 10 + i * 2));+ const np = nc ? ends[nc - 1] + 1 : 0;+ let p = a + 10 + nc * 2; p += 2 + u16(p); // skip the hinting instructions+ const flags: number[] = [];+ while (flags.length < np) { const f = u8[p++]; flags.push(f); if (f & 8) { let r = u8[p++]; while (r-- > 0) flags.push(f); } }+ const xs: number[] = [], ys: number[] = [];+ let v = 0;+ for (const f of flags) { if (f & 2) { const d = u8[p++]; v += f & 16 ? d : -d; } else if (!(f & 16)) { v += i16(p); p += 2; } xs.push(v); }+ v = 0;+ for (const f of flags) { if (f & 4) { const d = u8[p++]; v += f & 32 ? d : -d; } else if (!(f & 32)) { v += i16(p); p += 2; } ys.push(v); }+ if (p > b + 3) fail(`glyph ${id}: outline data runs past its slot: damaged file`);+ const out: Pt[][] = []; let s = 0;+ for (const e of ends) { const c: Pt[] = []; for (let k = s; k <= e; k++) c.push({ x: xs[k], y: ys[k], on: !!(flags[k] & 1) }); out.push(c); s = e + 1; }+ return out;+ }+ // composite: each component is another glyph, moved (and maybe scaled) into place+ const out: Pt[][] = [];+ let p = a + 10, more = true;+ while (more) {+ const fl = u16(p), gid = u16(p + 2); p += 4;+ let dx: number, dy: number;+ if (fl & 1) { dx = i16(p); dy = i16(p + 2); p += 4; } else { dx = dv.getInt8(p); dy = dv.getInt8(p + 1); p += 2; }+ // ARGS_ARE_XY_VALUES unset means "match point numbers": rare in Latin fonts, placed at 0, 0+ if (!(fl & 2)) { dx = 0; dy = 0; }+ let m = [1, 0, 0, 1];+ const f2 = (o: number) => i16(o) / 16384;+ if (fl & 8) { const s = f2(p); m = [s, 0, 0, s]; p += 2; }+ else if (fl & 0x40) { m = [f2(p), 0, 0, f2(p + 2)]; p += 4; }+ else if (fl & 0x80) { m = [f2(p), f2(p + 2), f2(p + 4), f2(p + 6)]; p += 8; }+ for (const c of points(gid, depth + 1)) out.push(c.map((q) => ({ x: m[0] * q.x + m[2] * q.y + dx, y: m[1] * q.x + m[3] * q.y + dy, on: q.on })));+ more = !!(fl & 0x20);+ }+ return out;+ };++ const cache = new Map<number, GlyphOutline>();+ const glyph = (id: number): GlyphOutline => {+ const hit = cache.get(id); if (hit) return hit;+ const contours = points(id).filter((c) => c.length > 1).map(toQuads);+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;+ for (const c of contours) for (const s of c) for (let k = 1; k < s.length; k += 2) { const x = s[k] as number, y = s[k + 1] as number; if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }+ const g: GlyphOutline = { id, contours, advance: advanceOf(id), lsb: lsbOf(id), bbox: contours.length ? [x0, y0, x1, y1] : [0, 0, 0, 0] };+ cache.set(id, g); return g;+ };++ // ---- cmap: prefer the full-Unicode format 12 table, else format 4+ let sub4 = -1, sub12 = -1;+ for (let i = 0, nt = u16(cmapT + 2); i < nt; i++) {+ const r = cmapT + 4 + i * 8, plat = u16(r), enc = u16(r + 2), off = cmapT + u32(r + 4), fmt = u16(off);+ const unicode = plat === 0 || (plat === 3 && (enc === 1 || enc === 10));+ if (!unicode) continue;+ if (fmt === 12 && sub12 < 0) sub12 = off;+ if (fmt === 4 && sub4 < 0) sub4 = off;+ }+ if (sub4 < 0 && sub12 < 0) fail("no Unicode character map (cmap format 4 or 12)");+ const cmapCache = new Map<number, number>();+ const glyphIndex = (cp: number): number => {+ const hit = cmapCache.get(cp); if (hit !== undefined) return hit;+ let g = 0;+ if (sub12 >= 0) {+ for (let i = 0, ng = u32(sub12 + 12); i < ng; i++) { const r = sub12 + 16 + i * 12, s = u32(r), e = u32(r + 4); if (cp >= s && cp <= e) { g = u32(r + 8) + cp - s; break; } }+ } else if (cp <= 0xffff) {+ const segX2 = u16(sub4 + 6), ends = sub4 + 14, starts = ends + segX2 + 2, deltas = starts + segX2, ranges = deltas + segX2;+ for (let i = 0; i < segX2 / 2; i++) {+ if (cp > u16(ends + i * 2)) continue;+ const s = u16(starts + i * 2); if (cp < s) break;+ const delta = u16(deltas + i * 2), ro = u16(ranges + i * 2);+ if (ro === 0) g = (cp + delta) & 0xffff;+ else { const at = ranges + i * 2 + ro + (cp - s) * 2, v = u16(at); g = v ? (v + delta) & 0xffff : 0; }+ break;+ }+ }+ if (g >= numGlyphs) g = 0;+ cmapCache.set(cp, g); return g;+ };++ // ---- kerning: kern format 0 pairs, then GPOS pair adjustments for the 'kern' feature+ const kern = new Map<number, number>();+ const kernT = tables.get("kern");+ if (kernT && u16(kernT.off) === 0) {+ let p = kernT.off + 4;+ for (let t = 0, nt = u16(kernT.off + 2); t < nt; t++) {+ const len = u16(p + 2), cov = u16(p + 4);+ if (cov >> 8 === 0 && cov & 1) for (let i = 0, np = u16(p + 6); i < np; i++) { const r = p + 14 + i * 6; kern.set((u16(r) << 16) | u16(r + 2), i16(r + 4)); }+ p += len;+ }+ }+ type Pair = (l: number, r: number) => number | undefined;+ const gposPairs: Pair[] = [];+ const gposT = tables.get("GPOS");+ if (gposT && kern.size === 0) {+ const G = gposT.off, featList = G + u16(G + 6), lookList = G + u16(G + 8);+ const lookups = new Set<number>();+ for (let i = 0, nf = u16(featList); i < nf; i++) { const r = featList + 2 + i * 6; if (tag(r) !== "kern") continue; const f = featList + u16(r + 4); for (let k = 0, nl = u16(f + 2); k < nl; k++) lookups.add(u16(f + 4 + k * 2)); }+ // coverage: glyph -> index in the table, or -1+ const coverage = (c: number) => { const fmt = u16(c), m = new Map<number, number>(); if (fmt === 1) for (let i = 0, n2 = u16(c + 2); i < n2; i++) m.set(u16(c + 4 + i * 2), i); else for (let i = 0, n2 = u16(c + 2); i < n2; i++) { const r = c + 4 + i * 6, s = u16(r), e = u16(r + 2), si = u16(r + 4); for (let gq = s; gq <= e; gq++) m.set(gq, si + gq - s); } return m; };+ const classDef = (c: number) => { const fmt = u16(c), m = new Map<number, number>(); if (fmt === 1) { const s = u16(c + 2); for (let i = 0, n2 = u16(c + 4); i < n2; i++) m.set(s + i, u16(c + 6 + i * 2)); } else for (let i = 0, n2 = u16(c + 2); i < n2; i++) { const r = c + 4 + i * 6; for (let gq = u16(r); gq <= u16(r + 2); gq++) m.set(gq, u16(r + 4)); } return m; };+ // ValueRecord: only XAdvance matters for horizontal kerning; the other fields are skipped by size+ const vSize = (f: number) => { let s = 0; for (let b = 0; b < 8; b++) if (f & (1 << b)) s += 2; return s; };+ const xAdv = (o: number, f: number) => { if (!(f & 4)) return 0; let p = o; if (f & 1) p += 2; if (f & 2) p += 2; return i16(p); };+ const pairSub = (st: number) => {+ const fmt = u16(st), cov = coverage(st + u16(st + 2)), vf1 = u16(st + 4), vf2 = u16(st + 6), rec = vSize(vf1) + vSize(vf2);+ if (fmt === 1) {+ gposPairs.push((l, r) => { const ci = cov.get(l); if (ci === undefined) return undefined; const set = st + u16(st + 10 + ci * 2); for (let i = 0, nv = u16(set); i < nv; i++) { const pr = set + 2 + i * (2 + rec); if (u16(pr) === r) return xAdv(pr + 2, vf1); } return undefined; });+ } else if (fmt === 2) {+ const c1 = classDef(st + u16(st + 8)), c2 = classDef(st + u16(st + 10)), n1 = u16(st + 12), n2 = u16(st + 14);+ gposPairs.push((l, r) => { if (!cov.has(l)) return undefined; const a = c1.get(l) ?? 0, b2 = c2.get(r) ?? 0; if (a >= n1 || b2 >= n2) return undefined; return xAdv(st + 16 + (a * n2 + b2) * rec, vf1); });+ }+ };+ for (const li of [...lookups].sort((a, b) => a - b)) {+ const L = lookList + u16(lookList + 2 + li * 2), type = u16(L);+ for (let s = 0, ns = u16(L + 4); s < ns; s++) {+ let st = L + u16(L + 6 + s * 2);+ if (type === 9) { if (u16(st + 2) !== 2) continue; st = st + u32(st + 4); } // extension wrapping a pair lookup+ else if (type !== 2) continue;+ pairSub(st);+ }+ }+ }+ const kernCache = new Map<number, number>();+ const kerning = (l: number, r: number) => {+ const k = (l << 16) | r, hit = kern.get(k) ?? kernCache.get(k); if (hit !== undefined) return hit;+ let v = 0; for (const f of gposPairs) { const x = f(l, r); if (x !== undefined) { v = x; break; } }+ kernCache.set(k, v); return v;+ };++ // ---- OS/2 cap and x height (version 2+), else measured from H and x+ const os2 = tables.get("OS/2");+ const yMaxOf = (ch: string) => glyph(glyphIndex(ch.codePointAt(0)!)).bbox[3];+ const capHeight = os2 && u16(os2.off) >= 2 && os2.len >= 90 ? i16(os2.off + 88) : yMaxOf("H");+ const xHeight = os2 && u16(os2.off) >= 2 && os2.len >= 88 ? i16(os2.off + 86) : yMaxOf("x");++ let sum = 0; for (let i = 0; i < u8.length; i += 97) sum = (Math.imul(sum, 31) + u8[i]) >>> 0;+ const family = names[16] ?? names[1] ?? "unnamed", style = names[17] ?? names[2] ?? "";+ return {+ id: `${family}-${style}-${u8.length}-${sum.toString(36)}`.replace(/\s+/g, ""),+ family, style, copyright: names[0] ?? "", license: names[13] ?? "", licenseUrl: names[14] ?? "",+ unitsPerEm, ascender, descender, lineGap, capHeight: capHeight || unitsPerEm * 0.7, xHeight: xHeight || unitsPerEm * 0.5,+ numGlyphs, glyphIndex, glyph, kerning,+ };+};++/**+ * TrueType points -> quadratic segments. Two off-curve points in a row imply an on-curve point+ * halfway between them; a contour may even start off-curve (then it starts at such a midpoint,+ * or at the first on-curve point found further on).+ */+export const toQuads = (pts: { x: number; y: number; on: boolean }[]): Contour => {+ const n = pts.length;+ let start = pts.findIndex((p) => p.on);+ let sx: number, sy: number;+ if (start < 0) { start = 0; sx = (pts[0].x + pts[1 % n].x) / 2; sy = (pts[0].y + pts[1 % n].y) / 2; }+ else { sx = pts[start].x; sy = pts[start].y; }+ const out: Contour = [["M", sx, sy]];+ // walk every point once after the start; an all-off contour starts at the midpoint of its first+ // two points, so its first point comes round again at k = n as the closing control+ let ctrl: { x: number; y: number } | null = null;+ for (let k = 1; k <= n; k++) {+ const p = pts[(start + k) % n];+ if (p.on) { if (ctrl) out.push(["Q", ctrl.x, ctrl.y, p.x, p.y]); else out.push(["L", p.x, p.y]); ctrl = null; }+ else if (ctrl) { const mx = (ctrl.x + p.x) / 2, my = (ctrl.y + p.y) / 2; out.push(["Q", ctrl.x, ctrl.y, mx, my]); ctrl = { x: p.x, y: p.y }; }+ else ctrl = { x: p.x, y: p.y };+ }+ if (ctrl) out.push(["Q", ctrl.x, ctrl.y, sx, sy]);+ // a closing "L" back onto the start adds a zero-length edge that triangulators dislike+ const last = out[out.length - 1];+ if (out.length > 2 && last[0] === "L" && last[1] === sx && last[2] === sy) out.pop();+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/three-core/type3d.ts b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/type3d.tsnew file mode 100644index 0000000..489aaa1--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/three-core/type3d.ts@@ -0,0 +1,241 @@+// TYPE 3D. Real letters in a 3D scene, from a TrueType font the film carries (ttf.ts), with no+// typeface JSON, no FontLoader and nothing fetched.+//+// text3d(env, font, "anidoodle", { size, depth, bevel }) extruded letters: a Group, ONE Mesh per+// visible glyph in reading order, so a verb can stagger them. Each letter's origin is its own+// centre (it pops and spins about itself) and its resting place is mesh.userData.home.+// textPlane(env, "made with anidoodle", { size, color }) flat, crisp type on a plane, drawn from+// the same outlines onto a 2D layer: labels, captions and URLs placed in 3D space.+// defaultFont() Poppins Bold (OFL), bundled.+// layoutText(font, text, opts) the pure layout both use (font units).+//+// Holes are found by CONTAINMENT, not by winding: a contour inside an odd number of others is a+// hole (the counter of "o", the bowl of "A"), whatever direction the font drew it. Winding alone+// fails on fonts that mix directions, and three's ShapePath.toShapes guesses from winding.+import * as THREE from "three";+import type { Env } from "../canvas-core/core";+import { memo } from "./stage";+import { parseTTF, type Contour, type Font } from "./ttf";+import { POPPINS_BOLD } from "../../assets/fonts/poppinsBold";++let poppins: Font | null = null;+/** Poppins Bold 4.003 (SIL OFL 1.1), parsed once. The same bytes on every machine. */+export const defaultFont = (): Font => (poppins ??= parseTTF(POPPINS_BOLD));++export type Align = "left" | "center" | "right";+export type LayoutOpts = { letterSpacing?: number; lineHeight?: number; align?: Align; kerning?: boolean };+export type Placed = { ch: string; gid: number; x: number; y: number; advance: number; line: number; index: number };+export type Layout = { glyphs: Placed[]; width: number; height: number; lines: number[] };++/**+ * Where every glyph goes, in FONT UNITS (y up, first baseline at 0). letterSpacing is in ems+ * (0.05 = a twentieth of the size between letters); lineHeight in ems. align shifts each line so+ * the block's x origin is its left edge, centre or right edge. Vertical: the cap-height middle of+ * the first line sits at y 0, so a word centres on its capitals, not on its descenders.+ */+export const layoutText = (font: Font, text: string, o: LayoutOpts = {}): Layout => {+ const em = font.unitsPerEm, track = (o.letterSpacing ?? 0) * em, lh = (o.lineHeight ?? 1.15) * em, align = o.align ?? "center";+ const glyphs: Placed[] = [], lines: number[] = [];+ const rows = text.split("\n");+ rows.forEach((row, li) => {+ const chars = [...row], start = glyphs.length;+ let x = 0, prev = -1;+ chars.forEach((ch, i) => {+ const gid = font.glyphIndex(ch.codePointAt(0)!), g = font.glyph(gid);+ if (prev >= 0 && o.kerning !== false) x += font.kerning(prev, gid);+ glyphs.push({ ch, gid, x, y: -li * lh, advance: g.advance, line: li, index: glyphs.length });+ x += g.advance + (i < chars.length - 1 ? track : 0);+ prev = gid;+ });+ const w = x, shift = align === "left" ? 0 : align === "right" ? -w : -w / 2;+ for (let k = start; k < glyphs.length; k++) glyphs[k].x += shift;+ lines.push(w);+ });+ const mid = font.capHeight / 2;+ for (const g of glyphs) g.y -= mid;+ return { glyphs, width: Math.max(0, ...lines), height: font.capHeight + (rows.length - 1) * lh, lines };+};++/** visible = has ink. Spaces and unmapped control characters make no mesh. */+export const visibleGlyphs = (font: Font, layout: Layout) => layout.glyphs.filter((g) => font.glyph(g.gid).contours.length > 0);++// ---- contours -> shapes with holes+const flatten = (c: Contour, steps = 4): [number, number][] => {+ const out: [number, number][] = []; let x = 0, y = 0;+ for (const s of c) {+ if (s[0] === "M" || s[0] === "L") { x = s[1]; y = s[2]; out.push([x, y]); }+ else { const [, cx, cy, ex, ey] = s; for (let k = 1; k <= steps; k++) { const t = k / steps, u = 1 - t; out.push([u * u * x + 2 * u * t * cx + t * t * ex, u * u * y + 2 * u * t * cy + t * t * ey]); } x = ex; y = ey; }+ }+ return out;+};+const area = (p: [number, number][]) => { let a = 0; for (let i = 0, j = p.length - 1; i < p.length; j = i++) a += (p[j][0] - p[i][0]) * (p[j][1] + p[i][1]); return a / 2; };+const inside = (pt: [number, number], poly: [number, number][]) => {+ let c = false;+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const a = poly[i], b = poly[j]; if ((a[1] > pt[1]) !== (b[1] > pt[1]) && pt[0] < ((b[0] - a[0]) * (pt[1] - a[1])) / (b[1] - a[1]) + a[0]) c = !c; }+ return c;+};+/**+ * Group a glyph's contours into outer outlines and their holes, by nesting depth. Returns indices:+ * [{ outer, holes }]. A contour's depth is how many others contain its test point; even depth is+ * ink, odd is a hole, and a hole belongs to the smallest contour one level up that contains it.+ */+export const nestContours = (contours: Contour[]): { outer: number; holes: number[] }[] => {+ const polys = contours.map((c) => flatten(c)), areas = polys.map((p) => Math.abs(area(p)));+ // test point: a vertex of the contour nudged a hair toward its own interior side is overkill for+ // fonts; a plain on-curve point is inside every true container and outside every sibling+ const probe = polys.map((p) => p[0]);+ const containers = polys.map((_, i) => polys.map((q, j) => (j !== i && areas[j] > areas[i] && inside(probe[i], q) ? j : -1)).filter((j) => j >= 0));+ const depth = containers.map((c) => c.length);+ const groups = new Map<number, { outer: number; holes: number[] }>();+ depth.forEach((d, i) => { if (d % 2 === 0) groups.set(i, { outer: i, holes: [] }); });+ depth.forEach((d, i) => {+ if (d % 2 === 0) return;+ const parent = containers[i].filter((j) => depth[j] === d - 1).sort((a, b) => areas[a] - areas[b])[0];+ if (parent !== undefined) groups.get(parent)!.holes.push(i);+ });+ return [...groups.values()];+};++const tracePath = (p: THREE.Path, c: Contour, k: number, dx: number, dy: number) => {+ for (const s of c) {+ if (s[0] === "M") p.moveTo(s[1] * k + dx, s[2] * k + dy);+ else if (s[0] === "L") p.lineTo(s[1] * k + dx, s[2] * k + dy);+ else p.quadraticCurveTo(s[1] * k + dx, s[2] * k + dy, s[3] * k + dx, s[4] * k + dy);+ }+};+/** a glyph's outline as THREE.Shapes in world units (k = world units per font unit), offset by dx, dy */+export const glyphShapes = (font: Font, gid: number, k: number, dx = 0, dy = 0): THREE.Shape[] => {+ const { contours } = font.glyph(gid);+ return nestContours(contours).map(({ outer, holes }) => {+ const s = new THREE.Shape(); tracePath(s, contours[outer], k, dx, dy);+ for (const h of holes) { const p = new THREE.Path(); tracePath(p, contours[h], k, dx, dy); s.holes.push(p); }+ return s;+ });+};++/**+ * Smooth normals across soft edges, keep them sharp across hard ones (the face and the side of a+ * letter). ExtrudeGeometry gives one flat normal per triangle, so the curved side of an "o" shows+ * every facet; averaging only the neighbours within `angle` of each other rounds it off.+ */+export const creaseNormals = (geo: THREE.BufferGeometry, angle = (35 * Math.PI) / 180) => {+ const pos = geo.getAttribute("position"), n = pos.count, faceN: THREE.Vector3[] = [], cos = Math.cos(angle);+ const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();+ for (let i = 0; i < n; i += 3) { a.fromBufferAttribute(pos, i); b.fromBufferAttribute(pos, i + 1); c.fromBufferAttribute(pos, i + 2); const f = new THREE.Vector3().subVectors(c, b).cross(new THREE.Vector3().subVectors(a, b)); const len = f.length(); faceN.push(len > 0 ? f.multiplyScalar(1 / len) : f.set(0, 0, 1)); }+ const key = (i: number) => `${Math.round(pos.getX(i) * 1e4)},${Math.round(pos.getY(i) * 1e4)},${Math.round(pos.getZ(i) * 1e4)}`;+ const at = new Map<string, number[]>();+ for (let i = 0; i < n; i++) { const k = key(i); const l = at.get(k); if (l) l.push(i); else at.set(k, [i]); }+ const out = new Float32Array(n * 3), s = new THREE.Vector3();+ for (let i = 0; i < n; i++) {+ const fi = faceN[(i / 3) | 0]; s.set(0, 0, 0);+ for (const j of at.get(key(i))!) { const fj = faceN[(j / 3) | 0]; if (fi.dot(fj) >= cos) s.add(fj); }+ if (s.lengthSq() === 0) s.copy(fi); s.normalize(); out.set([s.x, s.y, s.z], i * 3);+ }+ geo.setAttribute("normal", new THREE.BufferAttribute(out, 3));+ return geo;+};++export type Text3dOpts = LayoutOpts & {+ /** em size in world units (the height a capital "H" gets is about 0.7 of it). Default 1 */+ size?: number;+ /** extrusion depth, in ems. Default 0.22 */+ depth?: number;+ /** bevel size in ems (0 = a hard edge). Default 0.018: enough to catch a rim light */+ bevel?: number;+ bevelSegments?: number;+ /** segments per quadratic curve. Default 10: smooth at 1080p for letters up to half the frame */+ curveSegments?: number;+ /** one material for every letter, or a list cycled letter by letter. Default: satin warm white */+ material?: THREE.Material | THREE.Material[];+};+export type Letter = THREE.Mesh & { userData: { char: string; index: number; home: THREE.Vector3 } };++/**+ * Extruded 3D text: a Group of one Mesh per visible glyph, in reading order. Built once per+ * (font, text, options) and kept (stage.ts memo), so call it from a shot's draw freely; the same+ * call returns the same Group (clone() it for a second copy). Animate letters by SETTING their+ * transforms from the frame, starting from userData.home: never nudge what the last frame left.+ */+export const text3d = (env: Env, font: Font, text: string, o: Text3dOpts = {}): THREE.Group & { userData: { letters: Letter[]; width: number; height: number } } => {+ const mats = o.material === undefined ? [] : Array.isArray(o.material) ? o.material : [o.material];+ const key = `text3d:${font.id}:${JSON.stringify(text)}:${JSON.stringify({ ...o, material: mats.map((m) => m.uuid) })}`;+ return memo(env, key, () => {+ const size = o.size ?? 1, k = size / font.unitsPerEm, depth = (o.depth ?? 0.22) * size, bevel = (o.bevel ?? 0.018) * size;+ const layout = layoutText(font, text, o);+ const fallback = mats.length ? mats : [new THREE.MeshPhysicalMaterial({ color: "#f4efe6", roughness: 0.5, specularIntensity: 0.35, sheen: 0.25, sheenRoughness: 0.6 })];+ const group = new THREE.Group() as THREE.Group & { userData: { letters: Letter[]; width: number; height: number } };+ const letters: Letter[] = [];+ for (const p of visibleGlyphs(font, layout)) {+ const g = font.glyph(p.gid), cx = (g.advance / 2) * k; // the letter's own centre: half its advance, cap middle, mid depth+ const geo = memo(env, `text3d:glyph:${font.id}:${p.gid}:${size}:${depth}:${bevel}:${o.bevelSegments ?? 3}:${o.curveSegments ?? 10}`, () => {+ const ge = new THREE.ExtrudeGeometry(glyphShapes(font, p.gid, k, -cx, -(font.capHeight / 2) * k), {+ depth, curveSegments: o.curveSegments ?? 10, bevelEnabled: bevel > 0, bevelThickness: bevel, bevelSize: bevel,+ // pull the bevel INSIDE the outline: the letter keeps the font's exact footprint and thin parts never fatten into each other+ bevelOffset: -bevel, bevelSegments: o.bevelSegments ?? 3,+ });+ ge.translate(0, 0, -depth / 2);+ return creaseNormals(ge);+ });+ const m = new THREE.Mesh(geo, fallback[letters.length % fallback.length]) as unknown as Letter;+ // the geometry's origin is font y = capHeight / 2 above this glyph's baseline (p.y)+ const home = new THREE.Vector3(p.x * k + cx, (p.y + font.capHeight / 2) * k, 0);+ m.position.copy(home); m.name = `letter:${letters.length}:${p.ch}`;+ m.userData = { char: p.ch, index: letters.length, home };+ group.add(m); letters.push(m);+ }+ group.userData = { letters, width: layout.width * k, height: layout.height * k };+ return group;+ });+};++// ---- flat type: the same outlines filled on a 2D layer+export type PlaneStyle = LayoutOpts & {+ font?: Font;+ /** em size in world units. Default 0.3 */+ size?: number;+ color?: string;+ /** texture pixels per em: 160 keeps 1080p captions sharp when the plane fills a fifth of the frame */+ px?: number;+ opacity?: number;+};+/** draw a laid-out text's outlines onto a 2D context, em = pixels per em, baseline origin at (ox, oy) */+export const fillText2d = (ctx: CanvasRenderingContext2D, font: Font, layout: Layout, em: number, ox: number, oy: number) => {+ const k = em / font.unitsPerEm;+ ctx.beginPath();+ for (const p of layout.glyphs) for (const c of font.glyph(p.gid).contours) for (const s of c) {+ const X = (x: number) => ox + (p.x + x) * k, Y = (y: number) => oy - (p.y + y) * k;+ if (s[0] === "M") ctx.moveTo(X(s[1]), Y(s[2])); else if (s[0] === "L") ctx.lineTo(X(s[1]), Y(s[2])); else ctx.quadraticCurveTo(X(s[1]), Y(s[2]), X(s[3]), Y(s[4]));+ }+ ctx.fill("nonzero"); // TrueType outlines are drawn to the nonzero rule+};+/**+ * Flat, crisp text on a plane for labels, captions and URLs in 3D space. Unlit (it reads the same+ * under any light rig) and outside tone mapping (its colour is the colour asked for). Built once per+ * (text, style) and kept. The plane is centred per align like text3d.+ */+export const textPlane = (env: Env, text: string, style: PlaneStyle = {}): THREE.Mesh => {+ const font = style.font ?? defaultFont();+ const key = `textPlane:${font.id}:${JSON.stringify(text)}:${JSON.stringify({ ...style, font: undefined })}`;+ return memo(env, key, () => {+ const em = style.px ?? 160, size = style.size ?? 0.3, layout = layoutText(font, text, style);+ const asc = font.ascender / font.unitsPerEm, desc = -font.descender / font.unitsPerEm, pad = 0.08;+ const wEm = layout.width / font.unitsPerEm + 2 * pad, hEm = (layout.height - font.capHeight) / font.unitsPerEm + asc + desc + 2 * pad;+ const W = Math.ceil(wEm * em), H = Math.ceil(hEm * em), layer = env.canvas(W, H), ctx = layer.ctx;+ ctx.clearRect(0, 0, W, H); ctx.fillStyle = style.color ?? "#ffffff";+ // layoutText put the cap middle at y 0 and x 0 at the block's left edge, centre or right edge+ const align = style.align ?? "center", ink = layout.width / font.unitsPerEm;+ const ax = align === "left" ? 0 : align === "right" ? ink : ink / 2;+ fillText2d(ctx, font, layout, em, (pad + ax) * em, (pad + asc) * em - (font.capHeight / 2 / font.unitsPerEm) * em);+ const tex = new THREE.CanvasTexture(layer.canvas as unknown as HTMLCanvasElement);+ tex.colorSpace = THREE.SRGBColorSpace; tex.premultiplyAlpha = true; tex.anisotropy = 8;+ tex.minFilter = THREE.LinearMipmapLinearFilter; tex.generateMipmaps = true;+ const mat = new THREE.MeshBasicMaterial({ map: tex, transparent: true, premultipliedAlpha: true, depthWrite: false, toneMapped: false, opacity: style.opacity ?? 1 });+ const geo = new THREE.PlaneGeometry(wEm * size, hEm * size);+ // align: the plane's origin is the text block's left edge, centre or right edge, at cap middle+ const x0 = align === "left" ? -pad : align === "right" ? -ink - pad : -ink / 2 - pad;+ const capMidFromTop = pad + asc - font.capHeight / 2 / font.unitsPerEm;+ geo.translate((x0 + wEm / 2) * size, (capMidFromTop - hEm / 2) * size, 0);+ const mesh = new THREE.Mesh(geo, mat); mesh.name = `textPlane:${text}`;+ return mesh;+ });+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/html-player.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/html-player.mjsindex a6ec3d8..c421f27 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/html-player.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/html-player.mjs@@ -10,6 +10,7 @@import { readFileSync, statSync } from "node:fs";import { resolve } from "node:path";import { pathToFileURL } from "node:url";+import { glArgs } from "./playwright.mjs";import { buildPage } from "../build-page.mjs";import { detect } from "../detect.mjs";import { loadBakes, saveBakes } from "../bake-cache.mjs";@@ -32,7 +33,8 @@ export const pageChecks = (html, declared = []) => {const has = (re) => { const m = rest.match(re); return m ? m.length : 0; };let names = null; try { names = assets ? Object.keys(JSON.parse(assets[1])) : null; } catch { names = null; }return [- { ok: has(/https?:\/\//g) === 0, label: "no http(s) reference of any kind", detail: `${has(/https?:\/\//g)} found` },+ // an XML namespace name (three.js creates its canvas with createElementNS) is an identifier, never fetched+ { ok: has(/https?:\/\/(?!www\.w3\.org\/(1999\/xhtml|2000\/svg)")/g) === 0, label: "no http(s) reference of any kind", detail: `${has(/https?:\/\/(?!www\.w3\.org\/(1999\/xhtml|2000\/svg)")/g)} found (XML namespace names excepted)` },{ ok: has(/<(img|audio|video|source|link|iframe)\b/gi) === 0, label: "no external element (img, audio, video, link)", detail: `${has(/<(img|audio|video|source|link|iframe)\b/gi)} found` },{ ok: has(/@font-face/gi) === 0, label: "no web font", detail: `${has(/@font-face/gi)} found` },{ ok: has(/data:[a-z]+\/[a-z0-9.+-]+;base64/gi) === 0, label: "no embedded binary outside the asset manifest", detail: `${has(/data:[a-z]+\/[a-z0-9.+-]+;base64/gi)} found` },@@ -51,7 +53,7 @@ export const open = async (film, opts = {}) => {const built = await buildPage({ entry: `src/hosts/page-${film}.ts`, out, title: film });const html = readFileSync(out, "utf8");- const browser = await p.env.pw.lib.chromium.launch({ executablePath: p.env.browser.executablePath, args: ["--disable-background-timer-throttling"] });+ const browser = await p.env.pw.lib.chromium.launch({ executablePath: p.env.browser.executablePath, args: ["--disable-background-timer-throttling", ...glArgs(out)] });const context = await browser.newContext({ viewport: { width: 640, height: 640 }, deviceScaleFactor: 1 });const pages = [], bv = browser.version();for (let i = 0; i < workers; i++) {diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjsindex a0ea434..31ea003 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/adapters/playwright.mjs@@ -2,13 +2,25 @@// canvas pixels. Frame accuracy comes from the pull model (frame N is a pure function of N),// not from anything Playwright does.import { createHash } from "node:crypto";+import { readFileSync } from "node:fs";import { pathToFileURL } from "node:url";import { bakeCacheOn, loadBakes, saveBakes } from "../bake-cache.mjs";export const name = "playwright";+// WEBGL. Only a page whose bundle carries three-core's marker gets a GL backend, so 2D films keep+// exactly the browser they always had. Default: SwiftShader, a CPU renderer that draws the same+// pixels on any machine (slow, ~1-3 s a 1080p frame). ANIDOODLE_GL=gpu uses the machine's GPU+// (Metal on a Mac, about 10x faster), but its hashes only hold on that machine and driver.+export const glArgs = (pagePath) => {+ let three = false; try { three = readFileSync(pagePath, "utf8").includes("__ANIDOODLE_WEBGL__"); } catch { /* not a file: no GL */ }+ if (!three) return [];+ const gpu = process.env.ANIDOODLE_GL === "gpu";+ return gpu ? ["--use-angle=" + (process.platform === "darwin" ? "metal" : "default"), "--ignore-gpu-blocklist", "--enable-gpu-rasterization"]+ : ["--use-angle=swiftshader", "--use-gl=angle", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"];+};// bakeCache (default on): finished plate frames come from and go to .cache/bakes (see bake-cache.mjs)export const open = async ({ pw, browser: found }, pagePath, { scale = 1, workers = 1, bakeCache } = {}) => {- const browser = await pw.lib.chromium.launch({ executablePath: found.executablePath, args: ["--disable-background-timer-throttling"] });+ const browser = await pw.lib.chromium.launch({ executablePath: found.executablePath, args: ["--disable-background-timer-throttling", ...glArgs(pagePath)] });// the bake folder is keyed by the browser BINARY, not just its version: Chrome for Testing and// chrome-headless-shell report the same version and rasterise differently, so one must never// replay the other's plate frames@@ -26,7 +38,7 @@ export const open = async ({ pw, browser: found }, pagePath, { scale = 1, workerhash: (n, w = 0) => pick(w).evaluate((f) => { window.FILM.seek(f); return window.FILM.hash(); }, n),// motion-blurred frame: `samples` subframes averaged in the page (see hosts/page.ts blur)// `samples` is a count (a 360-degree shutter, as before) or a spec { samples: N | 0 (auto), shutter, max, px }- blur: async (n, samples, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, s]) => { const r = window.FILM.blur(f, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0, samples: r.samples, speed: r.speed }; },+ blur: async (n, samples, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, s]) => { const r = window.FILM.blur(f, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0, samples: r.samples, speed: r.speed, sharpPx: r.sharpPx ?? 0, typeInLayers: r.typeInLayers ?? 0 }; },// a frame of the poster dissolve (see hosts/page.ts poster): frame n with poster frame p over itposter: async (n, p, fade, samples = 1, w = n) => { const t0 = Date.now(); const r = await pick(w).evaluate(([f, pf, fd, s]) => { const r = window.FILM.poster(f, pf, fd, s); const t = performance.now(); const png = window.FILM.png(); return { ...r, png, enc: performance.now() - t }; }, [n, p, fade, samples]); return { png: Buffer.from(r.png, "base64"), shot: r.shot, drawMs: r.ms, encodeMs: r.enc, roundTripMs: Date.now() - t0 }; },posterHash: (n, p, fade, samples = 1, w = 0) => pick(w).evaluate(([f, pf, fd, s]) => { window.FILM.poster(f, pf, fd, s); return window.FILM.hash(); }, [n, p, fade, samples]),@@ -35,6 +47,10 @@ export const open = async ({ pw, browser: found }, pagePath, { scale = 1, workeraudio: (sr) => pages[0].evaluate((s) => window.FILM.audio(s), sr),// the frame probe (hosts/page.ts): text and content boxes the frame's edge cuts throughprobe: (frames, all = false) => pages[0].evaluate(([fs, a]) => window.FILM.probe(fs, a), [frames, all]),+ // the layer probe (hosts/instrument.ts, tools/layerscan.mjs): text, photos and boxes per frame in draw order, translucent brand fills+ layers: (frames, brand = []) => pages[0].evaluate(([fs, b]) => window.FILM.layers(fs, b), [frames, brand]),+ // visible ink of the text inside each box on one frame (device px)+ ink: (frame, boxes) => pages[0].evaluate(([f, bs]) => window.FILM.ink(f, bs), [frame, boxes]),// keeps the fresh bakes, then closes; returns how many plate frames were storedclose: async () => { let saved = 0; if (useBakes) for (const p of pages) saved += await saveBakes(p, bv).catch(() => 0); await browser.close(); return saved; },};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/board.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/board.mjsnew file mode 100644index 0000000..eb1b004--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/board.mjs@@ -0,0 +1,28 @@+// BOARD. Checks a brief and its storyboard (board.json) before anything is drawn, and prints the board+// with a CARRY column: what each beat takes in from the one before. A board whose rows carry nothing is a+// slide deck however well it is animated later. The rules and the file format: tools/boardrules.mjs.+// node tools/board.mjs board.json check it; exit 1 with each problem and its fix+// node tools/board.mjs init [board.json] write a starting board with every field (never overwrites)+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { resolve } from "node:path";+import { isMain } from "./is-main.mjs";+import { BOARD_TEMPLATE, checkBoard } from "./boardrules.mjs";++export const printBoard = (r) => {+ const out = [` ${"beat".padEnd(12)} ${"s".padStart(5)} ${"carry (in from the beat before)".padEnd(34)} action`];+ for (const t of r.table) out.push(` ${String(t.id).slice(0, 12).padEnd(12)} ${t.seconds.toFixed(1).padStart(5)} ${(t.carry || "-- nothing --").slice(0, 34).padEnd(34)} ${t.action.slice(0, 70)}`);+ out.push(` ${"total".padEnd(12)} ${r.seconds.toFixed(1).padStart(5)}`);+ return out.join("\n");+};++if (isMain(import.meta.url)) {+ const [cmd, arg] = process.argv.slice(2);+ if (cmd === "init") { const f = resolve(arg ?? "board.json"); if (existsSync(f)) { console.log(`board: ${f} already exists; left as it is`); process.exit(0); } writeFileSync(f, JSON.stringify(BOARD_TEMPLATE, null, 2) + "\n"); console.log(`board: wrote ${f}`); process.exit(0); }+ if (!cmd) { console.error("usage: node tools/board.mjs <board.json> | init [board.json]"); process.exit(2); }+ let board; try { board = JSON.parse(readFileSync(resolve(cmd), "utf8")); } catch (e) { console.error(`board: cannot read ${cmd}: ${e.message}`); process.exit(1); }+ const r = checkBoard(board);+ console.log(`BOARD ${cmd}\n${printBoard(r)}\n`);+ for (const p of r.problems) console.log(` FAIL ${p.where}: ${p.why}`);+ console.log(r.status === "PASS" ? `BOARD: PASS ${r.table.length} beats, each carrying the last; brief complete` : `BOARD: FAIL ${r.problems.length} problem(s)`);+ process.exit(r.status === "PASS" ? 0 : 1);+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/boardrules.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/boardrules.mjsnew file mode 100644index 0000000..8398fa3--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/boardrules.mjs@@ -0,0 +1,121 @@+// BOARD RULES. The pure half of board.mjs: what a brief and a storyboard must hold before anything is+// drawn. Every rule here was a round of notes on a brand launch film: a board of facts that played as a+// slide deck, a logo that arrived with no reason, a brand tagline nobody understood, jokes that were all+// the same shape (and one that made the audience's own tool look stupid), a count of dots read as a+// promise of six more speakers, an ending that ended twice, organisers and sponsors forgotten, filler+// text that viewers tried to read. A rule that can be a check is a check; each failure names its fix.+//+// board.json+// { "version": 1,+// "brief": { "story": "...", "message": "...", "premise": { "pain": "...", "stereotype": "..." } | "none: <why>",+// "promise": { "line": "...", "does": "<what the viewer does>", "leaves": "<what they leave with>" },+// "actor": "<the one object that carries the seams>", "kind": "event" | "product" | "story",+// "people": { "hosts": [...] | "excluded: <why, who decided>", "sponsors": ..., "partners": ..., "speakers": ... }, (events)+// "voices": { "<speaker>": "<how their lines look: dots then white type>" },+// "reference": { "film": "<a film chosen with the person>", "notes": "<its deconstruction>" } | "none: <why>",+// "length": { "target": 60, "max": 90 } },+// "rows": [ { "id": "hook", "seconds": 3, "action": "<what moves>", "carry": "<what comes in from the previous row>",+// "words": ["..."], "lines": [{ "speaker": "ai", "text": "..." }], "texture": ["blah blah"], "kind": "beat" | "card" | "stinger",+// "brand": true, "bridge": "<why the logo appears now, from what is on screen>", "builtFrom": "<the thing that just acted>",+// "counts": [{ "of": "dots", "from": 3, "to": 1, "why": "..." }], "answers": "<a stinger: what it answers, visible in the last 3 s>" } ],+// "jokes": [ { "line": "...", "device": "verbal|visual|interaction|physical|structural", "butt": "situation|habit|...", "who": "<who gets it and why>", "row": "hook" } ],+// "pitches": [ { "line": "...", "device": "...", "twist": "<the turn that makes it a joke>" } ],+// "program": [ { "name": "...", "role": "...", "company": "...", "logo": "..." } ], "programTitles": "on: <why>" (titles are off by default) }++export const DEVICES = ["verbal", "visual", "interaction", "physical", "structural"];+const ABSTRACT = /\b(intelligence|synerg\w*|unlock\w*|empower\w*|transform\w*|multipl\w*|next[- ]level|leverag\w*|revolution\w*|elevat\w*|supercharg\w*|reimagin\w*|amplif\w*|innovat\w*)\b/i;+const MYSTERY = /^(tba|tbd|\?+|mystery|secret|to be announced|surprise)( speaker)?$/i;+const GREEK = /\b(blah|lorem|ipsum|dolor|lipsum)\b|x{3,}|~{2,}|_{3,}/i;+const words = (s) => String(s ?? "").toLowerCase().match(/[a-z0-9']+/g) ?? [];+const set = (v) => (Array.isArray(v) ? v.length > 0 : typeof v === "string" && /^(excluded|none)\s*:\s*\S/.test(v.trim()));+const reasoned = (v) => typeof v === "string" && /^(excluded|none|on)\s*:\s*\S/.test(v.trim());+const norm = (s) => String(s ?? "").toLowerCase().replace(/\s+/g, " ").replace(/^[\s"'“”]+|[\s.!?:;"'“”]+$/g, "");+const STOP = new Set(["the", "a", "an", "of", "to", "and", "in", "on", "it", "its", "is", "into", "from", "that", "then", "with", "as", "at", "by", "for", "they", "their", "one", "two", "three"]);+const shares = (a, b) => { const A = new Set(words(a).filter((w) => !STOP.has(w))); return words(b).some((w) => !STOP.has(w) && (A.has(w) || A.has(w.replace(/s$/, "")) || A.has(`${w}s`))); };++/** -> { status: "PASS" | "FAIL", problems: [{ where, why }], table: [{ id, seconds, carry, action }] , seconds } */+export const checkBoard = (board) => {+ const P = [], add = (where, why) => P.push({ where, why });+ if (!board || typeof board !== "object") return { status: "FAIL", problems: [{ where: "board", why: "is not a board object" }], table: [], seconds: 0 };+ const b = board.brief ?? {}, rows = Array.isArray(board.rows) ? board.rows : [];+ const todo = (v, path) => { if (typeof v === "string" && /^todo\b/i.test(v.trim())) add(path, "is still a TODO"); else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) todo(x, `${path}.${k}`); };+ todo(board.brief, "brief"); todo(board.rows, "rows");+ // ---- the brief+ if (!String(b.story ?? "").trim()) add("brief.story", "is missing: one sentence the film proves, written before anything else");+ if (!String(b.message ?? "").trim()) add("brief.message", "is missing: the line the viewer should leave repeating (a film of information with no message is a deck)");+ if (!b.premise || (typeof b.premise === "string" ? !reasoned(b.premise) : !(String(b.premise.pain ?? "").trim() && String(b.premise.stereotype ?? "").trim()))) add("brief.premise", "needs the comic premise { pain: whose pain, stereotype: which habit }, or \"none: <why this film plays it straight>\"");+ const pr = b.promise;+ if (!pr || !String(pr.line ?? "").trim()) add("brief.promise", "is missing: the promise line, naming what the viewer DOES and LEAVES WITH");+ else {+ if (!String(pr.does ?? "").trim() || !String(pr.leaves ?? "").trim()) add("brief.promise", "needs `does` (what the viewer does) and `leaves` (what they leave with): an abstract claim nobody can picture is not a promise");+ if (ABSTRACT.test(pr.line) && !reasoned(pr.taglineApproved)) add("brief.promise", `"${pr.line}" leans on an abstract word (${pr.line.match(ABSTRACT)[0]}); say what the viewer does and leaves with, or set taglineApproved: "on: <who approved it and why it reads>"`);+ }+ if (!String(b.actor ?? "").trim()) add("brief.actor", "is missing: name the one object that carries the film across its seams (the motif)");+ if (b.kind === "event") for (const k of ["hosts", "sponsors", "partners", "speakers"]) if (!set(b.people?.[k])) add(`brief.people.${k}`, `is missing: an event film lists its ${k}, or says "excluded: <why, and who decided>"`);+ if (["event", "product"].includes(b.kind) && !(b.reference && (reasoned(b.reference) || (String(b.reference.film ?? "").trim() && String(b.reference.notes ?? "").trim())))) add("brief.reference", "is missing: one reference film chosen with the person and deconstructed (shot lengths, seams, camera, type entry and exit), or \"none: <why>\"");+ // ---- the rows+ if (!rows.length) add("rows", "the board has no rows (an empty board is never a pass)");+ const table = [], seen = new Map();+ let seconds = 0, lastCard = -1, stingerAfterCard = -1;+ rows.forEach((r, i) => {+ const id = r.id ?? `row ${i + 1}`, at = `rows.${id}`;+ seconds += Number(r.seconds) || 0;+ if (!String(r.action ?? "").trim()) add(at, "has no action: a row says what MOVES and what it becomes, never only what is shown (a fact on a frame is a slide)");+ if (i > 1 && !String(r.carry ?? "").trim() && !String(rows[i - 1].carry ?? "").trim()) add(at, `and ${rows[i - 1].id ?? `row ${i}`} carry nothing in from the row before: two cuts in a row with nothing carried play as a slide deck. Name what moves across (an object, a shape, the camera)`);+ if (i > 0 && String(r.carry ?? "").trim() && !shares(r.carry, `${rows[i - 1].kind ?? ""} ${rows[i - 1].action} ${rows[i - 1].carry ?? ""} ${(rows[i - 1].words ?? []).join(" ")}`)) add(at, `carries "${r.carry}", which the row before never shows: the carried thing must be on screen on both sides of the seam`);+ if (r.brand) {+ if (!String(r.bridge ?? "").trim()) add(at, "reveals the brand with no bridge: answer \"why does the logo appear now?\" in one sentence from what is on screen (the brand arrives as the answer, shown as an action)");+ if (!String(r.builtFrom ?? "").trim()) add(at, "reveals the brand without saying what it is built from: the mark should be built from the thing that just acted");+ else if (i > 0 && !shares(r.builtFrom, `${rows[i - 1].action} ${rows[i - 1].carry ?? ""} ${r.action}`)) add(at, `builds the brand from "${r.builtFrom}", which is not what just acted on screen`);+ }+ for (const c of r.counts ?? []) if (c.from !== c.to && !String(c.why ?? "").trim()) add(at, `changes the count of ${c.of ?? "an actor"} from ${c.from} to ${c.to} with no reason on screen: keep the count, or show why it changes`);+ for (const t of r.texture ?? []) if (!GREEK.test(t) && words(t).length >= 3) add(at, `texture text "${String(t).slice(0, 40)}" is real words: text that is not meant to be read must look unreadable (blah, greeked), or the eye tries to read it`);+ for (const l of r.lines ?? []) if (!b.voices?.[l.speaker]) add(at, `has a line by "${l.speaker}", who has no visual voice in brief.voices: a character's lines always look the same (same bubble, same type)`);+ for (const w of [...(r.words ?? []), ...(r.lines ?? []).map((l) => l.text)]) { const k = norm(w); if (!k) continue; if (seen.has(k)) add(at, `repeats "${String(w).slice(0, 40)}" (first in ${seen.get(k)}): say a line once`); else seen.set(k, id); }+ if (r.kind === "card") { if (stingerAfterCard >= 0 && stingerAfterCard > lastCard) add(at, "returns to the card after the stinger: the film ends twice. One landing: the card OR the stinger is the last thing on screen"); lastCard = i; }+ if (r.kind === "stinger") { if (lastCard >= 0) stingerAfterCard = i; if (!String(r.answers ?? "").trim()) add(at, "is a stinger with nothing to answer: it must answer something visible in the 3 s before it"); }+ table.push({ id, seconds: Number(r.seconds) || 0, carry: r.carry ?? "", action: r.action ?? "" });+ });+ // ---- jokes+ const jokes = Array.isArray(board.jokes) ? board.jokes : [];+ for (const [i, j] of jokes.entries()) {+ const at = `jokes.${i + 1}`;+ if (!DEVICES.includes(j.device)) add(at, `"${String(j.line ?? "").slice(0, 40)}" needs a device: ${DEVICES.join(", ")}`);+ if (!String(j.who ?? "").trim()) add(at, `"${String(j.line ?? "").slice(0, 40)}" needs who gets it and why, in one line; a gag that needs explaining to the client is cut or rewritten`);+ if (/\b(tool|product|person|people|audience|user|ai)\b/i.test(String(j.butt ?? "")) || !String(j.butt ?? "").trim()) add(at, `the butt of "${String(j.line ?? "").slice(0, 40)}" is ${j.butt ? `"${j.butt}"` : "unnamed"}: the joke is on a situation or a habit, never on the tool the audience relies on or a real person`);+ }+ if (jokes.length >= 3) { const top = Math.max(...DEVICES.map((d) => jokes.filter((j) => j.device === d).length)); if (top / jokes.length > 0.6) add("jokes", `${top} of ${jokes.length} jokes use one device: vary it (a visual pun, an interaction, physical comedy, structure), one format repeated stops being funny`); }+ const pitches = Array.isArray(board.pitches) ? board.pitches : [];+ if (pitches.length) {+ const devices = new Set(pitches.map((p) => p.device).filter((d) => DEVICES.includes(d)));+ if (devices.size < Math.min(4, pitches.length)) add("pitches", `the batch spans ${devices.size} comic device(s): a pitch batch spans at least four (${DEVICES.join(", ")})`);+ for (const [i, p] of pitches.entries()) if (!String(p.twist ?? "").trim()) add(`pitches.${i + 1}`, `"${String(p.line ?? "").slice(0, 40)}" has no twist: an observation (true, with no turn) is not a joke`);+ }+ // ---- the program (events)+ for (const [i, s] of (board.program ?? []).entries()) {+ const at = `program.${i + 1}`;+ if (MYSTERY.test(String(s.name ?? "").trim())) add(at, `"${s.name}" is a mystery speaker: list real people only; for more to come, one symbol (a single "?") never a count`);+ for (const k of ["name", "role", "company"]) if (!String(s[k] ?? "").trim()) add(at, `${s.name ?? "a speaker"} has no ${k}: the program shows name, role and company logo for every speaker`);+ if (s.title && !reasoned(board.programTitles)) add(at, `${s.name} shows a talk title: titles are off by default (too long to read in a film); set programTitles: "on: <why>" to keep them`);+ }+ // ---- length+ const L = b.length ?? {};+ if (L.max && seconds > L.max) add("length", `the rows add up to ${seconds} s, over the ${L.max} s maximum: cut whole beats (never speed up reading)`);+ return { status: P.length ? "FAIL" : "PASS", problems: P, table, seconds };+};++/** A starting board with every field, for `board.mjs init`. */+export const BOARD_TEMPLATE = {+ version: 1,+ brief: {+ story: "TODO one sentence the film proves", message: "TODO the line the viewer leaves repeating",+ premise: { pain: "TODO whose pain", stereotype: "TODO which habit" },+ promise: { line: "TODO", does: "TODO what the viewer does", leaves: "TODO what they leave with" },+ actor: "TODO the one object that carries the seams", kind: "product",+ voices: { ai: "TODO how its lines look" },+ reference: { film: "TODO a film chosen with the person", notes: "TODO path to its deconstruction" },+ length: { target: 60, max: 90 },+ },+ rows: [{ id: "hook", seconds: 3, action: "TODO what moves and what it becomes", carry: "", words: [] }],+ jokes: [],+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/brand-unit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/brand-unit.mjsnew file mode 100644index 0000000..81684a8--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/brand-unit.mjs@@ -0,0 +1,84 @@+#!/usr/bin/env node+// Unit + end-to-end tests for tools/brand.mjs that need node's own modules (zlib, files), so they run+// here rather than in the bundled test/brand.test.ts. Temp folder under out/, removed afterwards.+// node tools/brand-unit.mjs (add --browser to also run the contact-sheet red/green pair)+import { strict as assert } from "node:assert";+import { execFileSync, spawnSync } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { alphaBox, crop, decodePng, encodePng, inkOf, opaqueCorners, tint } from "./pngio.mjs";++const ENGINE = join(dirname(fileURLToPath(import.meta.url)), ".."), TOOL = join(ENGINE, "tools", "brand.mjs"), FIX = join(ENGINE, "test", "fixtures", "brand");+const root = join(ENGINE, "out", ".brand-unit"); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true });+let n = 0; const t = (label, fn) => { fn(); n++; console.log(` PASS ${label}`); };+const run = (...args) => spawnSync(process.execPath, [TOOL, ...args], { cwd: root, encoding: "utf8" });+try {+ // ---- PNG: written and read back, trimmed to ink, tinted+ const w = 40, h = 20, data = new Uint8Array(w * h * 4);+ for (let y = 5; y < 15; y++) for (let x = 10; x < 30; x++) { const i = (y * w + x) * 4; data.set([200, 30, 30, 255], i); }+ const back = decodePng(encodePng({ w, h, data }));+ t("a PNG written and read back is the same pixels", () => assert.deepEqual([...back.data], [...data]));+ t("the transparent margin is found and trimmed to 20x10 with 200 px of ink", () => { const b = alphaBox(back); assert.deepEqual(b, [10, 5, 20, 10]); assert.equal(inkOf(crop(back, b)), 200); });+ t("tinted white keeps alpha", () => { const x = tint(back, [255, 255, 255]); const i = (5 * w + 10) * 4; assert.deepEqual([...x.data.slice(i, i + 4)], [255, 255, 255, 255]); });+ t("RED: a logo on a solid background is caught", () => assert.ok(opaqueCorners({ w: 2, h: 2, data: new Uint8Array(16).fill(255) }) && !opaqueCorners(back)));+ t("NEGATIVE: not a PNG is refused", () => assert.throws(() => decodePng(Buffer.from([1, 2, 3])), /not a PNG/));+ const rgb = execFileSync("ffmpeg", ["-loglevel", "error", "-f", "lavfi", "-i", "color=c=red:s=8x4", "-frames:v", "1", "-pix_fmt", "rgb24", "-f", "image2pipe", "-vcodec", "png", "-"]);+ t("an RGB PNG from another encoder (ffmpeg, filtered rows) decodes", () => { const p = decodePng(rgb); assert.equal(p.w, 8); assert.ok(p.data[0] > 240 && p.data[1] < 12 && p.data[3] === 255, String([...p.data.slice(0, 4)])); });++ // ---- inventory -> find -> check, through the command line+ const figma = { document: { children: [{ name: "Social", children: [+ { id: "4:7", name: "Social Media partners", type: "FRAME", absoluteBoundingBox: { width: 1080, height: 1080 }, children: [{ type: "TEXT", characters: "Thank you to our sponsors" }] },+ { id: "4:8", name: "Story cover", type: "FRAME", absoluteBoundingBox: { width: 1080, height: 1920 }, children: [] }] }] } };+ writeFileSync(join(root, "file.json"), JSON.stringify(figma));+ t("inventory lists every frame", () => { const r = run("inventory", "--figma-json", "file.json"); assert.equal(r.status, 0, r.stderr); assert.match(r.stdout, /2 frames/); });+ t("find answers from the words on a frame", () => assert.match(run("find", "sponsors").stdout, /Social Media partners/));+ t("find says what it searched when nothing matches", () => assert.match(run("find", "speakers").stdout, /not in the names or words of the 2 frames/));+ t("RED: check fails while frames are unread", () => { const r = run("check"); assert.equal(r.status, 1); assert.match(r.stdout, /UNREAD/); });+ const md = join(root, "brand", "INVENTORY.md"); writeFileSync(md, readFileSync(md, "utf8").replace("| [ ] | Social | Social Media partners", "| [x] | Social | Social Media partners").replace("| [ ] | Social | Story cover", "| [-] same elements as the lockup | Social | Story cover"));+ t("check passes once every frame is read or skipped with a reason", () => assert.equal(run("check").status, 0));+ t("re-running inventory keeps the read marks", () => { run("inventory", "--figma-json", "file.json"); assert.equal(run("check").status, 0); });++ // ---- import and logos, through the command line+ t("import writes brand.json and a TS module, and reports the half-turn symmetry", () => { const r = run("import", join(FIX, "hourglass.svg"), "--ts", "src/canvas-core/demoBrand.ts"); assert.equal(r.status, 0, r.stderr); assert.match(r.stdout, /same after 1\/2 turn/); assert.ok(existsSync(join(root, "src/canvas-core/demoBrand.ts"))); });+ t("import names the mask it cannot draw", () => assert.match(run("import", join(FIX, "masked.svg"), "--out", "b2").stdout, /WARN .*mask/));+ mkdirSync(join(root, "logos")); writeFileSync(join(root, "logos", "wide.png"), encodePng({ w, h, data })); writeFileSync(join(root, "logos", "solid.png"), encodePng({ w: 2, h: 2, data: new Uint8Array(16).fill(255) }));+ writeFileSync(join(root, "logos", "shared.svg"), `<svg width="100" height="20" xmlns="http://www.w3.org/2000/svg"><rect width="60" height="20" fill="#123456"/><rect x="40" width="60" height="20" fill="#123456"/></svg>`);+ t("logos trims, skips a solid background, and flags shared outlines for the owner", () => { const r = run("logos", "logos", "--on", "dark"); assert.equal(r.status, 0, r.stderr); assert.match(r.stdout, /trimmed 40x20 -> 20x10/); assert.match(r.stdout, /SKIP\s+solid\.png has a solid background/); assert.match(r.stdout, /CHECK WITH OWNER/); assert.ok(existsSync(join(root, "brand/logos/shared-dark.svg"))); });++ // ---- M7: a flag that takes no value must not swallow the file after it; an unknown flag is refused+ t("RED (M7): an unknown flag is refused, never read as a value or a file", () => { const r = run("import", join(FIX, "hourglass.svg"), "--sheeet", join(FIX, "hardmask.svg"), "--out", "m7a"); assert.notEqual(r.status, 0); assert.match(r.stderr, /unknown flag --sheeet/); });++ t("RED: brand.json records each source relative to itself, never an absolute path", () => { const r = run("import", join(FIX, "hourglass.svg"), "--out", "relsrc"); assert.equal(r.status, 0, r.stdout + r.stderr); const j = JSON.parse(readFileSync(join(root, "relsrc", "brand.json"), "utf8")); for (const s of Object.values(j.sources)) { assert.ok(!s.file.startsWith("/") && !/^[A-Za-z]:/.test(s.file), `absolute path written: ${s.file}`); assert.ok(existsSync(join(root, "relsrc", s.file)), `relative path does not resolve: ${s.file}`); } });++ // ---- the test override can never send the Figma token off this machine+ await (async () => {+ const { figmaBase } = await import("./brand.mjs");+ t("RED: ANIDOODLE_FIGMA_API pointing at another host is refused", () => { assert.throws(() => figmaBase({ ANIDOODLE_FIGMA_API: "https://evil.example.com" }), /local test server/); assert.throws(() => figmaBase({ ANIDOODLE_FIGMA_API: "http://127.0.0.1.evil.example.com" }), /local test server/); });+ t("no override gives Figma itself; a localhost override is kept", () => { assert.equal(figmaBase({}), "https://api.figma.com"); assert.equal(figmaBase({ ANIDOODLE_FIGMA_API: "http://127.0.0.1:4010/" }), "http://127.0.0.1:4010"); });+ })();++ // ---- L10: a Figma image fetch that fails is an error, never an .svg holding the error page+ await (async () => {+ const { createServer } = await import("node:http"), { spawn } = await import("node:child_process");+ const srv = createServer((q, s) => {+ if (q.url.startsWith("/v1/files/")) { s.setHeader("content-type", "application/json"); s.end(JSON.stringify({ nodes: { "1:2": { document: { name: "Mark" } } } })); }+ else if (q.url.startsWith("/v1/images/")) { s.setHeader("content-type", "application/json"); s.end(JSON.stringify({ images: { "1:2": `http://127.0.0.1:${srv.address().port}/img.svg` } })); }+ else { s.statusCode = 403; s.end("<Error><Code>AccessDenied</Code></Error>"); }+ });+ await new Promise((ok) => srv.listen(0, "127.0.0.1", ok));+ const env = { ...process.env, FIGMA_TOKEN: "test-token", ANIDOODLE_FIGMA_API: `http://127.0.0.1:${srv.address().port}` };+ const r = await new Promise((ok) => { const c = spawn(process.execPath, [TOOL, "import", "--figma", "KEY", "--nodes", "1:2", "--out", "l10"], { cwd: root, env }); let out = "", err = ""; c.stdout.on("data", (d) => (out += d)); c.stderr.on("data", (d) => (err += d)); c.on("close", (status) => ok({ status, stdout: out, stderr: err })); });+ srv.close();+ t("RED (L10): a Figma image fetch that returns 403 fails the import and writes no .svg", () => { assert.notEqual(r.status, 0, r.stdout); assert.match(r.stderr, /403/); assert.ok(!existsSync(join(root, "l10", "src", "Mark.svg")), "the error page was saved as Mark.svg"); });+ })();++ if (process.argv.includes("--browser")) {+ t("RED (M7): a file after --sheet is imported too, not dropped as the flag's value", () => { const r = run("import", join(FIX, "hourglass.svg"), "--sheet", join(FIX, "hardmask.svg"), "--out", "m7"); assert.match(r.stdout, /2 file\(s\)/, r.stdout + r.stderr); assert.equal(Object.keys(JSON.parse(readFileSync(join(root, "m7", "brand.json"), "utf8")).report).length, 2); });+ t("the contact sheet passes an exact import", () => { const r = run("import", join(FIX, "hourglass.svg"), "--out", "g", "--sheet"); assert.equal(r.status, 0, r.stdout + r.stderr); assert.match(r.stdout, /BRAND: PASS/); });+ t("a hard white mask imports as a clip and passes the sheet", () => { const r = run("import", join(FIX, "hardmask.svg"), "--out", "h", "--sheet"); assert.equal(r.status, 0, r.stdout + r.stderr); });+ t("RED: the contact sheet fails the masked mark the import cannot draw", () => { const r = run("import", join(FIX, "masked.svg"), "--out", "r", "--sheet"); assert.equal(r.status, 1); assert.match(r.stdout, /BRAND: FAIL/); });+ }+ console.log(`\nBRAND-UNIT: PASS ${n} checks`);+} catch (e) { console.log(` FAIL ${e.message}`); console.log("\nBRAND-UNIT: FAIL"); process.exitCode = 1; }+finally { rmSync(root, { recursive: true, force: true }); }diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/brand.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/brand.mjsnew file mode 100644index 0000000..d517483--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/brand.mjs@@ -0,0 +1,233 @@+// BRAND. A brand film uses the brand's EXACT elements, logos and motion, imported and signed off before+// the first storyboard. Drawing them anew from screenshots cost a launch film four rounds of rejection+// ("use the right elements, exact ones from the design file, never invent or draw the official ones+// anew"). This tool turns the source into a brand file the film draws from, and makes the sign-off a check.+//+// node tools/brand.mjs import <file.svg|dir ...> [--out brand] [--ts src/canvas-core/myBrand.ts] [--sheet] [--on #111]+// exact paths per element (fills, gradients, transforms, <use>, clip-paths resolved) -> brand/brand.json and a TS+// module (BRAND + brandMeta for meta.brand); prints each element's parts, symmetry and repeat period.+// --sheet draws every element twice, from its source SVG and from the import, and fails past 1% different ink.+// node tools/brand.mjs import --figma <fileKey> --nodes <id,id> [...] route 1: the Figma REST API, read only,+// token in FIGMA_TOKEN; exports SVG with text outlined, then imports as above. Never writes to the file.+// node tools/brand.mjs inventory (--figma <fileKey> | --figma-json file.json | --dir <exports>) [--out brand]+// EVERY frame of the source -> brand/INVENTORY.md (a read box per frame) + inventory.json + the source's own+// transition timings as motion tokens (brand/motion.json, merged into brand.json on the next import).+// node tools/brand.mjs find <words> [--out brand] "is X in the file?" answered from the whole inventory+// node tools/brand.mjs check [--out brand] fails while any frame is unread, or skipped with no reason+// node tools/brand.mjs logos <dir> --on dark|light [--out brand/logos]+// each logo (SVG or PNG): trimmed to its ink, a one-colour version for the ground, ink measured, a size that+// makes every logo read equally, outlines that overlap flagged "check with the owner" (never auto-fixed);+// writes logos.json and strip.html (+ strip.png when a browser is installed).+// node tools/brand.mjs logo <film-render.svg|png> --ref <production-screenshot.png> [--out brand/logo-check.png]+// the production logo and the film's logo side by side at the same height, for a human to sign off first.+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";+import { basename, dirname, extname, join, relative, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { isMain } from "./is-main.mjs";+import { brandModule, coloursOf, equaliseLogos, importSvg, logoMetrics, monochrome, repeats, symmetry, toSvg } from "./brandsvg.mjs";+import { checkInventory, findInInventory, framesFromFigma, framesFromFiles, motionTokens, parseInventory, renderInventory } from "./brandinv.mjs";+import { alphaBox, crop, decodePng, encodePng, inkOf, opaqueCorners, tint } from "./pngio.mjs";++const ENGINE = join(dirname(fileURLToPath(import.meta.url)), "..");+const sha = (b) => createHash("sha256").update(b).digest("hex");+const ident = (s) => { const w = String(s).replace(/\.[^.]+$/, "").split(/[^A-Za-z0-9]+/).filter(Boolean); const id = w.map((x, i) => (i ? x[0].toUpperCase() + x.slice(1) : x[0].toLowerCase() + x.slice(1))).join(""); return /^[0-9]/.test(id) ? `el${id}` : id || "element"; };+const svgFiles = (paths) => paths.flatMap((p) => statSync(p).isDirectory() ? readdirSync(p).filter((f) => f.toLowerCase().endsWith(".svg")).sort().map((f) => join(p, f)) : [p]);++/** The import, pure apart from reading the files: -> { elements, report, palette, fonts, sources }. */+export const importFiles = (files) => {+ const elements = {}, report = {}, sources = {}, palette = new Map(), fonts = new Set();+ for (const f of files) {+ const text = readFileSync(f, "utf8"), name = ident(basename(f)), el = importSvg(text);+ if (elements[name]) throw new Error(`two sources map to the element name '${name}' (${sources[name].file} and ${f}); rename one`);+ elements[name] = { w: el.w, h: el.h, parts: el.parts }; sources[name] = { file: f, sha256: sha(text) };+ for (const [c, a] of coloursOf(el)) palette.set(c, (palette.get(c) ?? 0) + a);+ el.fonts.forEach((x) => fonts.add(x));+ report[name] = { parts: el.parts.length, size: `${el.w}x${el.h}`, symmetry: el.parts.length ? symmetry(el) : null, repeats: repeats(el), warnings: el.warnings, fonts: el.fonts };+ }+ const total = [...palette.values()].reduce((a, b) => a + b, 0) || 1;+ return { elements, report, sources, fonts: [...fonts], palette: [...palette].sort((a, b) => b[1] - a[1]).map(([hex, a]) => ({ hex, share: Math.round((a / total) * 1000) / 1000 })) };+};+const describe = (r) => [+ r.symmetry ? (r.symmetry.rotational > 1 ? `same after 1/${r.symmetry.rotational} turn (lands from a spin without a jump)` : "no rotational symmetry") + (r.symmetry.mirrorX ? ", mirror left-right" : "") + (r.symmetry.mirrorY ? ", mirror top-bottom" : "") : "empty",+ ...r.repeats.map((p) => `${p.what === "pattern" ? "colour pattern" : "shape"}: ${p.copies} copies every ${p.step[0] || p.step[1]} units ${p.step[0] ? "across" : "down"}${p.seamless ? ", tiles without a seam" : ""}`),+].join("; ");++// ------------------------------------------------------------------ browser pages (contact sheet, logo strip, side by side)+const kitBundle = async () => {+ const { build } = await import("esbuild");+ return (await build({ entryPoints: [join(ENGINE, "src", "canvas-core", "brandKit.ts")], bundle: true, write: false, format: "iife", globalName: "BK", logLevel: "error" })).outputFiles[0].text;+};+// JSON inside a <script> must not carry '<' (a '</script>' or '<!--' in an SVG comment ends or bends the script)+const safeJson = (v) => JSON.stringify(v).replace(/</g, "\\u003c");+/** Contact sheet: each element from its source SVG, from the import, and their difference in red. */+export const sheetHtml = (brand, svgTexts, kit, ground = "checker") => `<!doctype html><html><head><meta charset="utf-8"><style>+body{margin:0;padding:24px;font:14px/1.4 Poppins,Arial,sans-serif;background:#f4f2ec;color:#111}h1{font-size:20px;margin:0 0 16px}+.row{display:grid;grid-template-columns:200px repeat(3,360px);gap:16px;align-items:center;margin-bottom:18px}+.cell{width:360px;height:240px;display:flex;align-items:center;justify-content:center;${ground === "checker" ? "background:repeating-conic-gradient(#ddd 0 25%,#fff 0 50%) 0 0/16px 16px" : `background:${ground}`}}+img,canvas{max-width:340px;max-height:220px}.bad{color:#b3261e;font-weight:700}</style></head><body>+<h1>Brand contact sheet: source / import / difference</h1><div id="rows"></div>+<script>${kit}</script><script>+const B=${safeJson(brand.elements)}, S=${safeJson(svgTexts)}, out={};+(async()=>{for(const name of Object.keys(B)){const el=B[name], k=Math.min(1400/el.w,600/el.h), W=Math.max(1,Math.round(el.w*k)), H=Math.max(1,Math.round(el.h*k));+ const row=document.createElement('div');row.className='row';row.innerHTML='<div><b>'+name+'</b><br>'+el.parts.length+' parts<br><span id="r-'+name+'"></span></div>';+ const img=new Image();img.width=W;img.height=H;img.src='data:image/svg+xml;base64,'+btoa(unescape(encodeURIComponent(S[name])));const okImg=await img.decode().then(()=>true,()=>false);if(!okImg){out[name]={ink:0,diff:0,share:1,broken:true};row.innerHTML+='<div class=bad>the source SVG does not render in a browser (invalid XML?)</div>';document.getElementById('rows').appendChild(row);continue;}+ const a=document.createElement('canvas');a.width=W;a.height=H;const ca=a.getContext('2d');ca.drawImage(img,0,0,W,H);+ const b=document.createElement('canvas');b.width=W;b.height=H;const cb=b.getContext('2d');cb.scale(k,k);BK.drawEl(cb,el,{name});+ const d=document.createElement('canvas');d.width=W;d.height=H;const cd=d.getContext('2d');const A=ca.getImageData(0,0,W,H).data,Bd=cb.getImageData(0,0,W,H).data,D=cd.createImageData(W,H);+ let ink=0,diff=0;for(let i=0;i<A.length;i+=4){const on=A[i+3]>40||Bd[i+3]>40;if(on)ink++;const dd=Math.max(Math.abs(A[i]*A[i+3]-Bd[i]*Bd[i+3]),Math.abs(A[i+1]*A[i+3]-Bd[i+1]*Bd[i+3]),Math.abs(A[i+2]*A[i+3]-Bd[i+2]*Bd[i+3]),Math.abs(A[i+3]-Bd[i+3])*255)/255;+ // a difference a 1 px shift explains is antialiasing, not a different shape: count it only when no neighbour of the source matches+ let real=false;if(dd>64){real=true;const x=(i/4)%W,y=Math.floor(i/4/W);for(let oy=-1;oy<=1&ℜoy++)for(let ox=-1;ox<=1&ℜox++){const xx=x+ox,yy=y+oy;if(xx<0||yy<0||xx>=W||yy>=H)continue;const j=(yy*W+xx)*4;+ const e=Math.max(Math.abs(A[j]*A[j+3]-Bd[i]*Bd[i+3]),Math.abs(A[j+1]*A[j+3]-Bd[i+1]*Bd[i+3]),Math.abs(A[j+2]*A[j+3]-Bd[i+2]*Bd[i+3]),Math.abs(A[j+3]-Bd[i+3])*255)/255;if(e<=64)real=false}}+ if(real){diff++;D.data[i]=220;D.data[i+3]=255}else if(on){D.data[i]=D.data[i+1]=D.data[i+2]=180;D.data[i+3]=120}}+ cd.putImageData(D,0,0);const share=ink?diff/ink:0;out[name]={ink,diff,share};+ for(const c of [img,b,d]){const w=document.createElement('div');w.className='cell';w.appendChild(c);row.appendChild(w)}+ document.getElementById('rows').appendChild(row);const r=document.getElementById('r-'+name);r.textContent=(share*100).toFixed(2)+'% of ink differs';if(share>0.01)r.className='bad';}+ window.__results=out;document.body.dataset.done='1';})();+</script></body></html>`;+const shoot = async (html, out, width = 1400) => {+ const { detect } = await import("./detect.mjs"), env = detect();+ if (!env.pw.ok || !env.browser.ok) return { shot: false, why: `no browser (${env.report.playwright}; ${env.report.browser}); open the .html file instead` };+ const browser = await env.pw.lib.chromium.launch({ executablePath: env.browser.executablePath });+ try {+ const page = await browser.newPage({ viewport: { width, height: 800 }, deviceScaleFactor: 1 });+ const errors = []; page.on("pageerror", (e) => errors.push(e.message));+ await page.setContent(html); await page.waitForSelector("body[data-done]", { timeout: 30000 }).catch((e) => { throw new Error(`the page never finished${errors.length ? `: ${errors.join("; ")}` : ""} (${e.message.split("\n")[0]})`); });+ const results = await page.evaluate(() => window.__results ?? null);+ mkdirSync(dirname(out), { recursive: true }); await page.screenshot({ path: out, fullPage: true });+ return { shot: true, results };+ } finally { await browser.close(); }+};++// ------------------------------------------------------------------ logos+const logoStripHtml = (logos, ground) => `<!doctype html><html><head><meta charset="utf-8"><style>body{margin:0;padding:40px;background:${ground};font:13px Poppins,Arial,sans-serif;color:${ground === "#111111" ? "#eee" : "#111"}}+.strip{display:flex;gap:56px;align-items:center;flex-wrap:wrap}figure{margin:0;text-align:center}figcaption{margin-top:10px;opacity:.8}</style></head><body><div class="strip">+${logos.map((l) => `<figure><img style="height:${l.height}px" src="data:${l.mime};base64,${l.b64}"><figcaption>${l.name}${l.overlaps ? " · check with owner" : ""}</figcaption></figure>`).join("")}+</div><script>Promise.all([...document.images].map(i=>i.decode().catch(()=>{}))).then(()=>{document.body.dataset.done='1'})</script></body></html>`;++// ------------------------------------------------------------------ Figma REST (route 1). Read only.+// ANIDOODLE_FIGMA_API points the calls at a local stand-in for the unit tests. It is accepted only on+// this machine (localhost), so a stray environment variable can never send the token to another host.+export const figmaBase = (env = process.env) => {+ const v = env.ANIDOODLE_FIGMA_API; if (!v) return "https://api.figma.com";+ let u; try { u = new URL(v); } catch { throw new Error(`ANIDOODLE_FIGMA_API is not a URL: unset it to use Figma itself`); }+ if (u.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(u.hostname)) throw new Error(`ANIDOODLE_FIGMA_API must be a local test server (http://127.0.0.1:<port>), got ${u.host}: unset it to use Figma itself`);+ return v.replace(/\/$/, "");+};+const figma = async (path) => {+ const token = process.env.FIGMA_TOKEN; if (!token) throw new Error("FIGMA_TOKEN is not set: make a personal access token (Figma > Settings > Security, read-only file scope) and export FIGMA_TOKEN=..., or use route 4 (ask for an SVG export) in references/workflows/brand-film.md");+ const r = await fetch(`${figmaBase()}/v1/${path}`, { headers: { "X-Figma-Token": token } });+ if (!r.ok) throw new Error(`Figma API ${r.status} on ${path.split("?")[0]}: ${(await r.text()).slice(0, 200)}`);+ return r.json();+};++if (isMain(import.meta.url)) {+ const argv = process.argv.slice(2), cmd = argv[0], opt = (k, d) => { const i = argv.indexOf(k); return i >= 0 ? argv[i + 1] : d; }, has = (k) => argv.includes(k);+ // Only the flags that take a value skip the word after them; --sheet takes none, so a file after it is+ // still a file. An unknown flag is refused rather than guessed at.+ const VALUED = ["--out", "--ts", "--on", "--figma", "--nodes", "--figma-json", "--dir", "--ref"], BOOL = ["--sheet"];+ const bad = argv.slice(1).find((a) => a.startsWith("--") && !VALUED.includes(a) && !BOOL.includes(a));+ if (bad) { console.error(`brand: unknown flag ${bad} (flags: ${[...VALUED, ...BOOL].join(" ")})`); process.exit(2); }+ const pos = argv.slice(1).filter((a, i, all) => !a.startsWith("--") && !VALUED.includes(all[i - 1]));+ const OUT = resolve(opt("--out", "brand"));+ const die = (m) => { console.error(`brand: ${m}`); process.exit(1); };+ try {+ if (cmd === "import") {+ let files = pos.length ? svgFiles(pos.map((p) => resolve(p))) : [];+ if (opt("--figma")) {+ const key = opt("--figma"), ids = String(opt("--nodes", "")).split(",").filter(Boolean); if (!ids.length) die("--figma needs --nodes <id,id> (brand.mjs inventory lists every frame id)");+ const names = await figma(`files/${key}/nodes?ids=${encodeURIComponent(ids.join(","))}`), urls = await figma(`images/${key}?ids=${encodeURIComponent(ids.join(","))}&format=svg&svg_outline_text=true&svg_simplify_stroke=false`);+ mkdirSync(join(OUT, "src"), { recursive: true });+ for (const id of ids) { const u = urls.images?.[id]; if (!u) die(`Figma rendered nothing for node ${id}`); const res = await fetch(u); if (!res.ok) die(`Figma's image for node ${id} failed: HTTP ${res.status} (nothing written; the link may have expired, run the import again)`); const svg = await res.text(); if (!/<svg[\s>]/i.test(svg)) die(`Figma's image for node ${id} is not an SVG (nothing written)`); const f = join(OUT, "src", `${ident(names.nodes?.[id]?.document?.name ?? id)}.svg`); writeFileSync(f, svg); files.push(f); }+ }+ if (!files.length) die("nothing to import: give SVG files or folders, or --figma <fileKey> --nodes <ids>");+ const brand = importFiles(files), motionFile = join(OUT, "motion.json");+ brand.motion = existsSync(motionFile) ? JSON.parse(readFileSync(motionFile, "utf8")) : {};+ mkdirSync(OUT, { recursive: true });+ // source paths are written relative to brand.json, so the file never carries the person's folder names+ // (a brand.json is often committed or shared); the sheet below still reads the absolute paths in memory+ const relSources = Object.fromEntries(Object.entries(brand.sources).map(([n, s]) => [n, { ...s, file: relative(OUT, s.file).split("\\").join("/") }]));+ writeFileSync(join(OUT, "brand.json"), JSON.stringify({ version: 1, ...brand, sources: relSources }, null, 1));+ const tsOut = resolve(opt("--ts", join(OUT, "brand.ts"))), kit = [resolve("src/canvas-core/brandKit.ts"), join(ENGINE, "src/canvas-core/brandKit.ts")].find(existsSync);+ const kitImport = kit ? (relative(dirname(tsOut), kit).replace(/\\/g, "/").replace(/\.ts$/, "")) : null;+ mkdirSync(dirname(tsOut), { recursive: true }); writeFileSync(tsOut, brandModule(brand, kitImport && (kitImport.startsWith(".") ? kitImport : `./${kitImport}`)));+ console.log(`BRAND IMPORT ${files.length} file(s) -> ${relative(process.cwd(), join(OUT, "brand.json"))}, ${relative(process.cwd(), tsOut)}\n`);+ for (const [n, r] of Object.entries(brand.report)) { console.log(` ${n.padEnd(18)} ${String(r.parts).padStart(3)} parts ${r.size.padEnd(11)} ${describe(r)}`); for (const w of r.warnings) console.log(` ${"".padEnd(18)} WARN ${w}`); }+ console.log(`\n palette: ${brand.palette.slice(0, 10).map((p) => `${p.hex} ${(p.share * 100).toFixed(0)}%`).join(", ")}`);+ if (brand.fonts.length) console.log(` fonts (live text in the source): ${brand.fonts.join(", ")}. Ask once, early, for the font files (OTF/TTF/WOFF2), or re-export with text outlined. A stand-in face is recorded in the brief and flagged on the review page.`);+ const tokens = Object.entries(brand.motion).filter(([k]) => k !== "_springs");+ if (tokens.length) console.log(` motion tokens from the source (motionKit motionTokens(BRAND.motion, fps)): ${tokens.slice(0, 4).map(([k, m]) => `${k} ${m.ms} ms ${m.ease === "linear" ? "linear" : `cubic-bezier(${m.ease.join(", ")})`}`).join("; ")}`);+ if (brand.motion._springs) console.log(` ${brand.motion._springs.length} spring easing(s) have no bezier form; translate them with the person (motion.json _springs)`);+ if (has("--sheet")) {+ const texts = Object.fromEntries(Object.entries(brand.sources).map(([n, s]) => [n, readFileSync(s.file, "utf8")])), html = sheetHtml(brand, texts, await kitBundle(), opt("--on", "checker"));+ writeFileSync(join(OUT, "sheet.html"), html); const r = await shoot(html, join(OUT, "sheet.png"));+ if (!r.shot) { console.log(`\n SHEET ${relative(process.cwd(), join(OUT, "sheet.html"))} written; ${r.why}. The match is unmeasured until it renders.`); process.exit(1); }+ const bad = Object.entries(r.results).filter(([, v]) => v.share > 0.01);+ console.log(`\n SHEET ${relative(process.cwd(), join(OUT, "sheet.png"))}: ${Object.entries(r.results).map(([n, v]) => v.broken ? `${n} SOURCE DOES NOT RENDER` : `${n} ${(v.share * 100).toFixed(2)}%`).join(", ")}`);+ console.log(bad.length ? `BRAND: FAIL ${bad.map(([n]) => n).join(", ")} draw(s) more than 1% differently from the source; open sheet.png, fix the import (a mask, filter or pattern the warnings name), never redraw by eye` : "BRAND: PASS every element draws as its source. Show sheet.png to the person for sign-off before the first storyboard.");+ process.exit(bad.length ? 1 : 0);+ }+ console.log("\nNext: brand.mjs import ... --sheet, and show sheet.png for sign-off before the first storyboard.");+ } else if (cmd === "inventory") {+ let src, inv;+ if (opt("--figma")) { src = `figma ${opt("--figma")}`; inv = framesFromFigma(await figma(`files/${opt("--figma")}?depth=4`)); }+ else if (opt("--figma-json")) { src = basename(opt("--figma-json")); inv = framesFromFigma(JSON.parse(readFileSync(resolve(opt("--figma-json")), "utf8"))); }+ else if (opt("--dir")) { src = opt("--dir"); inv = { frames: framesFromFiles(readdirSync(resolve(opt("--dir")))), motion: [] }; }+ else die("inventory needs --figma <fileKey>, --figma-json <file.json> (the REST file JSON) or --dir <exports>");+ mkdirSync(OUT, { recursive: true });+ const mdFile = join(OUT, "INVENTORY.md"), prev = new Map(existsSync(mdFile) ? parseInventory(readFileSync(mdFile, "utf8")).map((r) => [r.id, r.mark]) : []);+ writeFileSync(mdFile, renderInventory(src, inv.frames, prev)); writeFileSync(join(OUT, "inventory.json"), JSON.stringify(inv.frames, null, 1));+ if (inv.motion.length) writeFileSync(join(OUT, "motion.json"), JSON.stringify(motionTokens(inv.motion), null, 1));+ console.log(`INVENTORY ${inv.frames.length} frames from ${src} -> ${relative(process.cwd(), mdFile)}${inv.motion.length ? `; ${inv.motion.length} motion token(s) -> motion.json` : ""}\nMark each frame [x] once read, or [-] <reason>. brand.mjs check holds it.`);+ } else if (cmd === "find") {+ const mdFile = join(OUT, "INVENTORY.md"); if (!existsSync(mdFile)) die(`no ${relative(process.cwd(), mdFile)}: run brand.mjs inventory first; without it, "not in the file" is a guess`);+ const rows = parseInventory(readFileSync(mdFile, "utf8")), q = pos.join(" "), hits = findInInventory(rows, q);+ if (hits.length) { console.log(`FIND "${q}": ${hits.length} frame(s)`); for (const h of hits) console.log(` ${h.page} / ${h.name} (${h.id})${h.words ? ` "${h.words.slice(0, 90)}"` : ""}`); }+ else console.log(`FIND "${q}": not in the names or words of the ${rows.length} frames in ${relative(process.cwd(), mdFile)}. Say exactly that, and ask; the person may know a frame by another name.`);+ } else if (cmd === "check") {+ const mdFile = join(OUT, "INVENTORY.md"), r = checkInventory(existsSync(mdFile) ? parseInventory(readFileSync(mdFile, "utf8")) : []);+ if (r.why) { console.log(`BRAND CHECK: FAIL ${r.why}`); process.exit(1); }+ for (const u of r.unread) console.log(` UNREAD ${u.page} / ${u.name} (${u.id})`);+ for (const u of r.bareSkips) console.log(` SKIPPED WITH NO REASON ${u.page} / ${u.name} (${u.id})`);+ console.log(r.status === "PASS" ? `BRAND CHECK: PASS all ${r.total} frames read or skipped with a reason` : `BRAND CHECK: FAIL ${r.unread.length + r.bareSkips.length} of ${r.total} frames not accounted for; open each, then mark it [x], or [-] <why it does not matter>`);+ process.exit(r.status === "PASS" ? 0 : 1);+ } else if (cmd === "logos") {+ const dir = pos[0] ? resolve(pos[0]) : die("logos needs a folder of logo files"), on = opt("--on", "dark"), out = resolve(opt("--out", join(OUT, "logos")));+ if (!["dark", "light"].includes(on)) die("--on is dark or light");+ const colour = on === "dark" ? "#ffffff" : "#111111", rgb = on === "dark" ? [255, 255, 255] : [17, 17, 17]; mkdirSync(out, { recursive: true });+ const logos = [];+ for (const f of readdirSync(dir).filter((x) => /\.(svg|png)$/i.test(x)).sort()) {+ const name = ident(f), p = join(dir, f);+ if (/\.svg$/i.test(f)) {+ const el = importSvg(readFileSync(p, "utf8")), m = logoMetrics(el), mono = toSvg(monochrome(el, colour), { tight: true });+ writeFileSync(join(out, `${name}.svg`), toSvg(el, { tight: true })); writeFileSync(join(out, `${name}-${on}.svg`), mono);+ logos.push({ name, file: f, kind: "svg", h: m.bbox[3], w: m.bbox[2], ink: m.ink, overlaps: m.overlaps, mime: "image/svg+xml", b64: Buffer.from(mono).toString("base64"), warnings: el.warnings });+ } else {+ const img = decodePng(readFileSync(p)), box = alphaBox(img);+ if (opaqueCorners(img)) { logos.push({ name, file: f, kind: "png", skipped: "has a solid background: ask for a transparent PNG or the SVG (a cut-out by eye is a redraw)" }); continue; }+ if (!box) { logos.push({ name, file: f, kind: "png", skipped: "is fully transparent" }); continue; }+ const trimmed = crop(img, box), mono = tint(trimmed, rgb), bytes = encodePng(mono);+ writeFileSync(join(out, `${name}.png`), encodePng(trimmed)); writeFileSync(join(out, `${name}-${on}.png`), bytes);+ logos.push({ name, file: f, kind: "png", w: box[2], h: box[3], ink: inkOf(trimmed), overlaps: 0, trimmed: `${img.w}x${img.h} -> ${box[2]}x${box[3]}`, mime: "image/png", b64: bytes.toString("base64") });+ }+ }+ const ok = equaliseLogos(logos.filter((l) => !l.skipped)), table = [...ok, ...logos.filter((l) => l.skipped)];+ writeFileSync(join(out, "logos.json"), JSON.stringify(table.map(({ b64, mime, ...l }) => l), null, 1));+ console.log(`LOGOS ${dir} on ${on} -> ${relative(process.cwd(), out)}\n`);+ for (const l of table) console.log(l.skipped ? ` SKIP ${l.file} ${l.skipped}` : ` ${l.name.padEnd(18)} ${l.kind} ${String(l.w).padStart(5)}x${String(l.h).padEnd(5)} ink density ${String(l.density).padEnd(6)} -> draw ${l.height} px tall${l.trimmed ? ` (trimmed ${l.trimmed})` : ""}${l.overlaps ? ` CHECK WITH OWNER: ${l.overlaps} outline(s) overlap; it may be their design, never fix it yourself` : ""}`);+ const html = logoStripHtml(ok, on === "dark" ? "#111111" : "#f4f2ec"); writeFileSync(join(out, "strip.html"), html);+ const r = await shoot(html, join(out, "strip.png")); console.log(r.shot ? `\n strip: ${relative(process.cwd(), join(out, "strip.png"))} (show it before use)` : `\n strip: ${relative(process.cwd(), join(out, "strip.html"))}; ${r.why}`);+ } else if (cmd === "logo") {+ const film = pos[0] ? resolve(pos[0]) : die("logo needs the film's logo (svg or png)"), ref = opt("--ref") ? resolve(opt("--ref")) : die("logo needs --ref <a screenshot of the logo where it is used in production>");+ const uri = (f) => `data:${/\.svg$/i.test(f) ? "image/svg+xml" : "image/png"};base64,${readFileSync(f).toString("base64")}`, out = resolve(opt("--out", join(OUT, "logo-check.png")));+ const html = `<!doctype html><html><body style="margin:0;padding:32px;background:#f4f2ec;font:14px Poppins,Arial,sans-serif"><div style="display:flex;gap:48px;align-items:flex-end">+<figure style="margin:0"><img style="height:160px" src="${uri(ref)}"><figcaption>production: ${basename(ref)}</figcaption></figure>+<figure style="margin:0;background:#111;padding:16px"><img style="height:128px" src="${uri(film)}"><figcaption style="color:#eee">film: ${basename(film)}</figcaption></figure></div>+<script>Promise.all([...document.images].map(i=>i.decode().catch(()=>{}))).then(()=>{document.body.dataset.done='1'})</script></body></html>`;+ writeFileSync(out.replace(/\.png$/, ".html"), html); const r = await shoot(html, out, 1200);+ console.log(r.shot ? `LOGO ${relative(process.cwd(), out)}: production left, film right. Compare order, colour and spacing of every part, and show it to the person before the logo is used.` : `LOGO ${out.replace(/\.png$/, ".html")}; ${r.why}`);+ } else {+ console.log(readFileSync(fileURLToPath(import.meta.url), "utf8").split("\n").filter((l) => l.startsWith("//")).slice(0, 26).map((l) => l.slice(3)).join("\n")); process.exit(cmd ? 2 : 0);+ }+ } catch (e) { die(e.message); }+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/brandinv.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/brandinv.mjsnew file mode 100644index 0000000..b468a2d--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/brandinv.mjs@@ -0,0 +1,87 @@+// BRAND INVENTORY. The pure half of `brand.mjs inventory | find | check` (no files, no network).+// A launch film once answered "the sponsors are not in the design file" after searching only its own+// exports, while the file had two frames named "Social Media partners". The fix is a class fix: on first+// access, list EVERY frame of the source (name, id, size, the words on it), keep that list beside the+// film, and answer any "is X in the file?" from a search of the whole list, never from memory.+// The list also carries a read mark per frame, and `check` fails while any frame is unmarked, so+// "I read the brand file" is a claim the tool can hold.++/** Figma REST file JSON (GET /v1/files/:key) -> { frames, motion }. Top-level children of each page are the frames. */+export const framesFromFigma = (file) => {+ const pages = file?.document?.children ?? [], frames = [], motion = new Map();+ const textOf = (n, out = []) => { if (n.type === "TEXT" && n.characters) out.push(n.characters); for (const k of n.children ?? []) textOf(k, out); return out; };+ const motionOf = (n) => {+ const add = (dur, easing, from) => { if (!dur) return; const key = `${Math.round(dur * 1000)}|${JSON.stringify(easing)}`; const m = motion.get(key) ?? { ms: Math.round(dur * 1000), easing, uses: 0, from: [] }; m.uses++; if (m.from.length < 5) m.from.push(from); motion.set(key, m); };+ for (const it of n.interactions ?? []) for (const a of it.actions ?? (it.action ? [it.action] : [])) { const t = a?.transition; if (t) add(t.duration, easingOf(t.easing), `${n.name} (${t.type ?? "transition"})`); }+ if (n.transitionDuration) add(n.transitionDuration / 1000, easingOf(n.transitionEasing), n.name);+ for (const k of n.children ?? []) motionOf(k);+ };+ for (const page of pages) for (const n of page.children ?? []) {+ const box = n.absoluteBoundingBox ?? {};+ frames.push({ page: page.name, name: n.name, id: n.id, type: n.type, w: Math.round(box.width ?? 0), h: Math.round(box.height ?? 0), text: textOf(n).join(" | ").slice(0, 4000) });+ motionOf(n);+ }+ return { frames, motion: [...motion.values()].sort((a, b) => b.uses - a.uses) };+};+const easingOf = (e) => {+ if (!e) return null; if (typeof e === "string") return e;+ const b = e.easingFunctionCubicBezier; if (b) return `cubic-bezier(${b.x1}, ${b.y1}, ${b.x2}, ${b.y2})`;+ const s = e.easingFunctionSpring; if (s) return `spring(mass ${s.mass}, stiffness ${s.stiffness}, damping ${s.damping})`;+ return e.type ?? null;+};+/** A folder of exports -> frames, one per file. */+export const framesFromFiles = (names) => names.filter((f) => !f.startsWith(".")).sort().map((f) => ({ page: "(files)", name: f.replace(/\.[^.]+$/, ""), id: f, type: f.split(".").pop().toUpperCase(), w: 0, h: 0, text: "" }));++const cell = (s) => String(s ?? "").replace(/\|/g, "/").replace(/\s+/g, " ").trim();+/** The inventory page: one row per frame, an unticked read box each. Existing marks are kept by id. */+export const renderInventory = (source, frames, prev = new Map()) => [+ `# Brand inventory: ${source}`,+ "",+ `${frames.length} frames. Mark each one when you have looked at it: \`[x]\` read, or \`[-] reason\` skipped on purpose.`,+ "Answer \"is X in the file?\" with `brand.mjs find X`, which searches every name and every word below, never from memory.",+ "",+ "| read | page | frame | id | size | words on it |",+ "|---|---|---|---|---|---|",+ ...frames.map((f) => `| ${prev.get(f.id) ?? "[ ]"} | ${cell(f.page)} | ${cell(f.name)} | ${cell(f.id)} | ${f.w && f.h ? `${f.w}x${f.h}` : "-"} | ${cell(f.text).slice(0, 160)} |`),+ "",+].join("\n");+/** INVENTORY.md -> rows { mark, page, name, id, words }. */+export const parseInventory = (md) => String(md).split("\n").filter((l) => /^\|\s*\[/.test(l)).map((l) => {+ const c = l.split("|").slice(1, -1).map((x) => x.trim());+ return { mark: c[0], page: c[1], name: c[2], id: c[3], size: c[4], words: c[5] ?? "" };+});+/** Every frame read or skipped with a reason. -> { status, total, unread: [rows], bareSkips: [rows] } */+export const checkInventory = (rows) => {+ if (!rows.length) return { status: "FAIL", total: 0, unread: [], bareSkips: [], why: "the inventory lists no frames: run brand.mjs inventory first (an empty list is never a pass)" };+ // Only two marks count: [x] (read) and "[-] reason" (skipped on purpose). Anything else, such as [], [ ]+ // or [?], was never read, so it fails rather than passing unseen.+ const read = (m) => /^\[[xX]\]/.test(m), skip = (m) => /^\[-\]\s+\S/.test(m), bare = (m) => /^\[-\]\s*$/.test(m);+ const unread = rows.filter((r) => !read(r.mark) && !skip(r.mark) && !bare(r.mark)), bareSkips = rows.filter((r) => bare(r.mark));+ return { status: unread.length || bareSkips.length ? "FAIL" : "PASS", total: rows.length, unread, bareSkips };+};+const fold = (s) => String(s).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();+/** Frames whose name or words contain every query word (or a close plural/singular of it). */+export const findInInventory = (rows, query) => {+ const words = fold(query).split(" ").filter(Boolean); if (!words.length) return [];+ const stem = (w) => w.replace(/(ies|es|s)$/, "");+ return rows.filter((r) => { const hay = ` ${fold(`${r.page} ${r.name} ${r.words}`)} `; return words.every((w) => hay.includes(` ${w}`) || hay.includes(` ${stem(w)}`)); });+};+/**+ * Motion tokens for the brand file, in the shape motionKit.ts motionTokens() reads:+ * { <name>: { ease: [x1, y1, x2, y2] | "linear", ms, uses, from } }, named after the first frame that uses each timing.+ * Spring easings have no cubic-bezier form; they are listed under `_springs` for a person to translate, never guessed.+ */+export const motionTokens = (motion) => {+ const out = {}, springs = [], NAMED = { EASE_IN: [0.42, 0, 1, 1], EASE_OUT: [0, 0, 0.58, 1], EASE_IN_AND_OUT: [0.42, 0, 0.58, 1], LINEAR: "linear", EASE_IN_BACK: [0.3, -0.05, 0.7, -0.5], EASE_OUT_BACK: [0.45, 1.45, 0.8, 1], EASE_IN_AND_OUT_BACK: [0.7, -0.4, 0.4, 1.4] };+ for (const m of motion) {+ const e = String(m.easing ?? "LINEAR"), bz = e.match(/^cubic-bezier\(([^)]*)\)$/);+ const ease = bz ? bz[1].split(",").map(Number) : NAMED[e] ?? null;+ if (!ease) { springs.push({ ms: m.ms, easing: e, from: m.from }); continue; }+ let name = String(m.from?.[0] ?? "motion").replace(/\s*\(.*\)$/, "").split(/[^A-Za-z0-9]+/).filter(Boolean).map((w, i) => (i ? w[0].toUpperCase() + w.slice(1).toLowerCase() : w.toLowerCase())).join("") || "motion";+ if (/^[0-9]/.test(name)) name = `m${name}`;+ let k = name, n = 2; while (out[k]) k = `${name}${n++}`;+ out[k] = { ease, ms: m.ms, uses: m.uses, from: m.from };+ }+ if (springs.length) out._springs = springs;+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/brandsvg.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/brandsvg.mjsnew file mode 100644index 0000000..1783dd8--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/brandsvg.mjs@@ -0,0 +1,362 @@+// BRAND SVG. The pure half of brand.mjs (no files, no browser), so it is unit-tested. It reads an SVG+// export (from Figma, a site or a brand pack) into the exact paths a film draws: every fill, gradient,+// transform and <use> resolved, each part with its bounding box. Nothing is redrawn or simplified,+// because a brand element approximated by eye is a different element in the owner's eyes.+// It also measures what the marks can do in motion: rotational and mirror symmetry (a mark that looks+// the same after a half turn can land from a spin without a jump) and repeat periods (a frieze that+// repeats every N units tiles without a seam).++// ------------------------------------------------------------------ XML, small and strict enough+const ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };+const unent = (s) => String(s).replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => e[0] === "#" ? String.fromCodePoint(e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)) : ENT[e] ?? m);+/** -> root node { tag, attrs, kids, text } of the first <svg>. Throws on input with no <svg>. */+export const parseXml = (src) => {+ const s = String(src).replace(/<!--[\s\S]*?-->/g, "").replace(/<\?[\s\S]*?\?>/g, "").replace(/<!DOCTYPE[\s\S]*?>/gi, "").replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, (_, t) => t.replace(/</g, "<"));+ const root = { tag: "#root", attrs: {}, kids: [], text: "" }, stack = [root], TAG = /<(\/?)([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g;+ for (const m of s.matchAll(TAG)) {+ const top = stack[stack.length - 1];+ if (m[5] !== undefined) { top.text += unent(m[5]); continue; }+ if (m[1]) { while (stack.length > 1 && stack.pop().tag !== m[2]); continue; }+ const attrs = {}; for (const a of m[3].matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) attrs[a[1]] = unent(a[2] ?? a[3]);+ const node = { tag: m[2].replace(/^svg:/, ""), attrs, kids: [], text: "", parent: top };+ top.kids.push(node); if (!m[4]) stack.push(node);+ }+ const find = (n) => n.tag === "svg" ? n : n.kids.map(find).find(Boolean);+ const svg = find(root); if (!svg) throw new Error("not an SVG: no <svg> element found");+ return svg;+};++// ------------------------------------------------------------------ affine matrices [a b c d e f]+export const I = [1, 0, 0, 1, 0, 0];+export const mul = (m, n) => [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1], m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3], m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]];+export const apply = (m, x, y) => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];+export const isIdentity = (m) => m.every((v, i) => Math.abs(v - I[i]) < 1e-9);+const nums = (s) => (String(s).match(/-?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/g) ?? []).map(Number);+/** SVG transform attribute -> one matrix. */+export const parseTransform = (t) => {+ let m = I;+ for (const [, fn, args] of String(t ?? "").matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g)) {+ const a = nums(args), r = (d) => (d * Math.PI) / 180;+ let n = I;+ if (fn === "matrix" && a.length === 6) n = a;+ else if (fn === "translate") n = [1, 0, 0, 1, a[0] ?? 0, a[1] ?? 0];+ else if (fn === "scale") n = [a[0] ?? 1, 0, 0, a[1] ?? a[0] ?? 1, 0, 0];+ else if (fn === "rotate") { const c = Math.cos(r(a[0] ?? 0)), s = Math.sin(r(a[0] ?? 0)), cx = a[1] ?? 0, cy = a[2] ?? 0; n = mul(mul([1, 0, 0, 1, cx, cy], [c, s, -s, c, 0, 0]), [1, 0, 0, 1, -cx, -cy]); }+ else if (fn === "skewX") n = [1, 0, Math.tan(r(a[0] ?? 0)), 1, 0, 0];+ else if (fn === "skewY") n = [1, Math.tan(r(a[0] ?? 0)), 0, 1, 0, 0];+ m = mul(m, n);+ }+ return m;+};++// ------------------------------------------------------------------ path data -> absolute commands -> points+/** d -> [[cmd, ...absolute numbers]] with M L C Q A Z only (H V S T and relatives resolved). */+export const parsePath = (d) => {+ const src = String(d ?? ""), out = []; let i = 0, cmd = "", x = 0, y = 0, sx = 0, sy = 0, lc = null, lq = null;+ const ws = () => { while (i < src.length && /[\s,]/.test(src[i])) i++; };+ const num = () => { ws(); const m = /^[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/.exec(src.slice(i)); if (!m) throw new Error(`bad path data near "${src.slice(i, i + 12)}"`); i += m[0].length; return Number(m[0]); };+ const flag = () => { ws(); const c = src[i++]; if (c !== "0" && c !== "1") throw new Error(`bad arc flag near "${src.slice(i - 1, i + 10)}"`); return c === "1" ? 1 : 0; };+ for (;;) {+ ws(); if (i >= src.length) break;+ if (/[a-zA-Z]/.test(src[i])) cmd = src[i++]; else if (!cmd) throw new Error("path data must start with a command");+ const rel = cmd === cmd.toLowerCase() && cmd !== "z" ? true : cmd === "z", C = cmd.toUpperCase(), ox = rel && C !== "Z" ? x : 0, oy = rel && C !== "Z" ? y : 0;+ if (C === "Z") { out.push(["Z"]); x = sx; y = sy; lc = lq = null; continue; }+ if (C === "M") { x = num() + ox; y = num() + oy; sx = x; sy = y; out.push(["M", x, y]); cmd = rel ? "l" : "L"; lc = lq = null; continue; }+ if (C === "L") { x = num() + ox; y = num() + oy; out.push(["L", x, y]); lc = lq = null; continue; }+ if (C === "H") { x = num() + ox; out.push(["L", x, y]); lc = lq = null; continue; }+ if (C === "V") { y = num() + oy; out.push(["L", x, y]); lc = lq = null; continue; }+ if (C === "C" || C === "S") {+ let x1, y1; if (C === "C") { x1 = num() + ox; y1 = num() + oy; } else [x1, y1] = lc ? [2 * x - lc[0], 2 * y - lc[1]] : [x, y];+ const x2 = num() + ox, y2 = num() + oy; x = num() + ox; y = num() + oy; out.push(["C", x1, y1, x2, y2, x, y]); lc = [x2, y2]; lq = null; continue;+ }+ if (C === "Q" || C === "T") {+ let x1, y1; if (C === "Q") { x1 = num() + ox; y1 = num() + oy; } else [x1, y1] = lq ? [2 * x - lq[0], 2 * y - lq[1]] : [x, y];+ x = num() + ox; y = num() + oy; out.push(["Q", x1, y1, x, y]); lq = [x1, y1]; lc = null; continue;+ }+ if (C === "A") { const rx = num(), ry = num(), rot = num(), la = flag(), sw = flag(); x = num() + ox; y = num() + oy; out.push(["A", rx, ry, rot, la, sw, x, y]); lc = lq = null; continue; }+ throw new Error(`unknown path command "${cmd}"`);+ }+ return out;+};++// endpoint arc -> centre form (SVG spec F.6.5), sampled+const arcPoints = (x0, y0, rx, ry, rotDeg, la, sw, x, y, n = 16) => {+ if (!rx || !ry) return [[x, y]];+ rx = Math.abs(rx); ry = Math.abs(ry); const phi = (rotDeg * Math.PI) / 180, c = Math.cos(phi), s = Math.sin(phi);+ const dx = (x0 - x) / 2, dy = (y0 - y) / 2, x1 = c * dx + s * dy, y1 = -s * dx + c * dy;+ const L = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry); if (L > 1) { rx *= Math.sqrt(L); ry *= Math.sqrt(L); }+ const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1, den = rx * rx * y1 * y1 + ry * ry * x1 * x1;+ const k = (la === sw ? -1 : 1) * Math.sqrt(Math.max(0, num / den)), cx1 = (k * rx * y1) / ry, cy1 = (-k * ry * x1) / rx;+ const cx = c * cx1 - s * cy1 + (x0 + x) / 2, cy = s * cx1 + c * cy1 + (y0 + y) / 2;+ const ang = (ux, uy, vx, vy) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);+ const t0 = ang(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry); let dt = ang((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry);+ if (!sw && dt > 0) dt -= 2 * Math.PI; else if (sw && dt < 0) dt += 2 * Math.PI;+ const pts = []; for (let j = 1; j <= n; j++) { const t = t0 + (dt * j) / n; pts.push([cx + rx * Math.cos(t) * c - ry * Math.sin(t) * s, cy + rx * Math.cos(t) * s + ry * Math.sin(t) * c]); }+ return pts;+};+/** d -> subpaths of points (curves sampled), each point through matrix m. */+export const flatten = (d, m = I, steps = 16) => {+ const subs = []; let cur = null, x = 0, y = 0, x0 = 0, y0 = 0;+ const put = (px, py) => cur.push(apply(m, px, py));+ for (const c of parsePath(d)) {+ if (c[0] === "M") { cur = []; subs.push(cur); x = x0 = c[1]; y = y0 = c[2]; put(x, y); continue; }+ if (!cur) { cur = []; subs.push(cur); put(x, y); }+ if (c[0] === "L") { x = c[1]; y = c[2]; put(x, y); }+ else if (c[0] === "C") { for (let j = 1; j <= steps; j++) { const t = j / steps, u = 1 - t; put(u * u * u * x + 3 * u * u * t * c[1] + 3 * u * t * t * c[3] + t * t * t * c[5], u * u * u * y + 3 * u * u * t * c[2] + 3 * u * t * t * c[4] + t * t * t * c[6]); } x = c[5]; y = c[6]; }+ else if (c[0] === "Q") { for (let j = 1; j <= steps; j++) { const t = j / steps, u = 1 - t; put(u * u * x + 2 * u * t * c[1] + t * t * c[3], u * u * y + 2 * u * t * c[2] + t * t * c[4]); } x = c[3]; y = c[4]; }+ else if (c[0] === "A") { for (const p of arcPoints(x, y, c[1], c[2], c[3], c[4], c[5], c[6], c[7], steps)) put(p[0], p[1]); x = c[6]; y = c[7]; }+ else if (c[0] === "Z") { if (cur.length) cur.push([cur[0][0], cur[0][1]]); x = x0; y = y0; cur = null; }+ }+ return subs.filter((s) => s.length > 1);+};+export const bboxOf = (subs) => {+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;+ for (const s of subs) for (const [x, y] of s) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; }+ return x0 === Infinity ? [0, 0, 0, 0] : [x0, y0, x1 - x0, y1 - y0];+};+/** Signed shoelace area per subpath, summed: an outline with counter-wound holes gives its ink area. */+export const signedArea = (sub) => { let a = 0; for (let i = 0; i < sub.length; i++) { const [x0, y0] = sub[i], [x1, y1] = sub[(i + 1) % sub.length]; a += x0 * y1 - x1 * y0; } return a / 2; };+/** Ink area of one part under its fill rule (holes subtract when wound the other way; evenodd: holes subtract when nested). */+export const inkArea = (subs, rule = "nonzero") => {+ if (rule !== "evenodd") return Math.abs(subs.reduce((s, p) => s + signedArea(p), 0));+ // even-odd: a subpath inside an odd number of others is a hole+ return subs.reduce((s, p, i) => { const depth = subs.filter((q, j) => j !== i && inside(p[0], q)).length; return s + (depth % 2 ? -1 : 1) * Math.abs(signedArea(p)); }, 0);+};+/** Ray-cast point-in-polygon. */+export const inside = ([x, y], poly) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) c = !c; } return c; };++// ------------------------------------------------------------------ shapes -> d+const n0 = (v, d = 0) => { const x = parseFloat(v); return Number.isFinite(x) ? x : d; };+export const shapeToD = (node) => {+ const a = node.attrs, t = node.tag;+ if (t === "path") return a.d ?? null;+ if (t === "rect") {+ const x = n0(a.x), y = n0(a.y), w = n0(a.width), h = n0(a.height); if (!w || !h) return null;+ let rx = a.rx != null ? n0(a.rx) : a.ry != null ? n0(a.ry) : 0, ry = a.ry != null ? n0(a.ry) : rx; rx = Math.min(rx, w / 2); ry = Math.min(ry, h / 2);+ if (!rx || !ry) return `M${x} ${y}H${x + w}V${y + h}H${x}Z`;+ return `M${x + rx} ${y}H${x + w - rx}A${rx} ${ry} 0 0 1 ${x + w} ${y + ry}V${y + h - ry}A${rx} ${ry} 0 0 1 ${x + w - rx} ${y + h}H${x + rx}A${rx} ${ry} 0 0 1 ${x} ${y + h - ry}V${y + ry}A${rx} ${ry} 0 0 1 ${x + rx} ${y}Z`;+ }+ if (t === "circle" || t === "ellipse") {+ const cx = n0(a.cx), cy = n0(a.cy), rx = t === "circle" ? n0(a.r) : n0(a.rx), ry = t === "circle" ? n0(a.r) : n0(a.ry); if (!rx || !ry) return null;+ return `M${cx - rx} ${cy}A${rx} ${ry} 0 1 0 ${cx + rx} ${cy}A${rx} ${ry} 0 1 0 ${cx - rx} ${cy}Z`;+ }+ if (t === "polygon" || t === "polyline") { const p = nums(a.points); if (p.length < 4) return null; let d = `M${p[0]} ${p[1]}`; for (let i = 2; i + 1 < p.length; i += 2) d += `L${p[i]} ${p[i + 1]}`; return t === "polygon" ? d + "Z" : d; }+ if (t === "line") return `M${n0(a.x1)} ${n0(a.y1)}L${n0(a.x2)} ${n0(a.y2)}`;+ return null;+};++// ------------------------------------------------------------------ styles: attributes, style="", <style> classes, inheritance+const NAMED = { white: "#ffffff", black: "#000000", red: "#ff0000", green: "#008000", lime: "#00ff00", blue: "#0000ff", yellow: "#ffff00", orange: "#ffa500", purple: "#800080", magenta: "#ff00ff", fuchsia: "#ff00ff", cyan: "#00ffff", aqua: "#00ffff", gray: "#808080", grey: "#808080", silver: "#c0c0c0", navy: "#000080", teal: "#008080", maroon: "#800000", olive: "#808000", pink: "#ffc0cb", none: "none", transparent: "none" };+export const normColor = (c) => {+ const s = String(c ?? "").trim().toLowerCase(); if (!s) return null;+ if (NAMED[s]) return NAMED[s];+ const h = s.match(/^#([0-9a-f]{3,8})$/); if (h) { const v = h[1]; return "#" + (v.length === 3 || v.length === 4 ? v.slice(0, 3).split("").map((ch) => ch + ch).join("") : v.slice(0, 6)); }+ const r = s.match(/^rgba?\(([^)]*)\)$/); if (r) { const [R, G, B] = r[1].split(/[\s,/]+/).map((v) => (v.endsWith("%") ? (parseFloat(v) * 255) / 100 : parseFloat(v))); return "#" + [R, G, B].map((v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, "0")).join(""); }+ return s;+};+const INHERIT = ["fill", "fill-rule", "fill-opacity", "stroke", "stroke-width", "stroke-opacity", "stroke-linecap", "stroke-linejoin", "font-family", "color"];+const styleOf = (node, classes) => {+ const st = {};+ for (const cls of String(node.attrs.class ?? "").split(/\s+/).filter(Boolean)) Object.assign(st, classes[cls] ?? {});+ for (const k of [...INHERIT, "opacity", "stop-color", "stop-opacity", "clip-path", "mask", "display", "visibility"]) if (node.attrs[k] != null) st[k] = node.attrs[k];+ for (const decl of String(node.attrs.style ?? "").split(";")) { const [k, ...v] = decl.split(":"); if (k && v.length) st[k.trim()] = v.join(":").trim(); }+ return st;+};+const parseClasses = (svg) => {+ const out = {}, walk = (n) => { if (n.tag === "style") for (const m of n.text.matchAll(/([^{}]+)\{([^}]*)\}/g)) { const decls = {}; for (const d of m[2].split(";")) { const [k, ...v] = d.split(":"); if (k && v.length) decls[k.trim()] = v.join(":").trim(); } for (const sel of m[1].split(",")) { const c = sel.trim().match(/^\.([\w-]+)$/); if (c) out[c[1]] = { ...(out[c[1]] ?? {}), ...decls }; } } n.kids.forEach(walk); };+ walk(svg); return out;+};++// ------------------------------------------------------------------ the import+const pct = (v, d) => (v == null ? d : String(v).trim().endsWith("%") ? parseFloat(v) / 100 : parseFloat(v));+const urlRef = (v) => String(v ?? "").match(/url\(\s*['"]?#([^'")\s]+)['"]?\s*\)/)?.[1];+const round = (v) => Math.round(v * 100) / 100;++/**+ * SVG text -> { w, h, parts, fonts, warnings }. Each part: { d, fill, rule, op, bb, m? , stroke?, clip? }.+ * fill: { type: "solid", c } | { type: "lin", x1, y1, x2, y2, stops, m? } | { type: "rad", cx, cy, r, fx, fy, stops, m? }.+ * m is the part's own matrix (transforms and the viewBox folded in); the path data is never rewritten.+ */+export const importSvg = (text) => {+ const svg = parseXml(text), classes = parseClasses(svg), byId = new Map(), warnings = new Set(), fonts = new Set();+ const index = (n) => { if (n.attrs.id) byId.set(n.attrs.id, n); n.kids.forEach(index); }; index(svg);+ const vb = nums(svg.attrs.viewBox ?? svg.attrs.viewbox ?? ""), w = n0(svg.attrs.width, vb[2] ?? 0), h = n0(svg.attrs.height, vb[3] ?? 0);+ let root = I; if (vb.length === 4 && vb[2] && vb[3]) { const s = Math.min(w / vb[2], h / vb[3]); root = [s, 0, 0, s, -vb[0] * s + (w - vb[2] * s) / 2, -vb[1] * s + (h - vb[3] * s) / 2]; }+ const stopsOf = (g, seen = new Set()) => {+ const own = g.kids.filter((k) => k.tag === "stop"); if (own.length || seen.has(g)) return own.map((s) => { const st = styleOf(s, classes); return [pct(s.attrs.offset, 0), normColor(st["stop-color"] ?? "#000"), pct(st["stop-opacity"], 1)]; });+ seen.add(g); const ref = byId.get(String(g.attrs["xlink:href"] ?? g.attrs.href ?? "").replace(/^#/, "")); return ref ? stopsOf(ref, seen) : [];+ };+ const paint = (v, bbLocal) => {+ if (v == null || v === "none") return null;+ const id = urlRef(v);+ if (!id) { const c = normColor(v === "currentColor" ? "#000" : v); return c === "none" ? null : { type: "solid", c }; }+ const g = byId.get(id); if (!g) { warnings.add(`a fill points at #${id}, which the file does not define; drawn black`); return { type: "solid", c: "#000000" }; }+ if (g.tag === "pattern") { warnings.add(`#${id} is a pattern fill (often an embedded image); not imported, check the contact sheet`); return null; }+ const stops = stopsOf(g), obb = (g.attrs.gradientUnits ?? "objectBoundingBox") === "objectBoundingBox";+ let gm = g.attrs.gradientTransform ? parseTransform(g.attrs.gradientTransform) : I;+ if (obb) gm = mul([bbLocal[2], 0, 0, bbLocal[3], bbLocal[0], bbLocal[1]], gm);+ const f = g.tag === "radialGradient"+ ? { type: "rad", cx: pct(g.attrs.cx, 0.5), cy: pct(g.attrs.cy, 0.5), r: pct(g.attrs.r, 0.5), fx: pct(g.attrs.fx ?? g.attrs.cx, 0.5), fy: pct(g.attrs.fy ?? g.attrs.cy, 0.5), stops }+ : { type: "lin", x1: pct(g.attrs.x1, 0), y1: pct(g.attrs.y1, 0), x2: pct(g.attrs.x2, 1), y2: pct(g.attrs.y2, 0), stops };+ if (!isIdentity(gm)) f.m = gm.map(round6);+ return f;+ };+ const parts = [];+ const visit = (node, m, inh, op, clipOuter) => {+ const t = node.tag; if (["defs", "symbol", "clipPath", "mask", "linearGradient", "radialGradient", "pattern", "style", "title", "desc", "metadata", "filter", "marker"].includes(t)) return;+ const own = styleOf(node, classes); if (own.display === "none" || own.visibility === "hidden") return;+ const st = { ...inh }; for (const k of INHERIT) if (own[k] != null) st[k] = own[k];+ let mm = node.attrs.transform ? mul(m, parseTransform(node.attrs.transform)) : m, o = op * pct(own.opacity, 1);+ let clipFromMask = null;+ if (own.mask) {+ // a mask made only of solid white shapes is a clip (Figma exports simple masks this way); a soft or grey mask is not+ const mk = byId.get(urlRef(own.mask)), shapes = mk ? mk.kids.filter((k) => shapeToD(k)) : [];+ const hard = mk && shapes.length && shapes.length === mk.kids.length && shapes.every((k) => { const ks = styleOf(k, classes); return ["#ffffff"].includes(normColor(ks.fill ?? "#000")) && pct(ks.opacity, 1) === 1 && pct(ks["fill-opacity"], 1) === 1; });+ if (hard) clipFromMask = { paths: shapes.map((k) => ({ d: shapeToD(k), m: (k.attrs.transform ? mul(mm, parseTransform(k.attrs.transform)) : mm).map(round6) })) };+ else warnings.add(`an element uses a soft or grey mask (${own.mask}); the import draws it unmasked, check the contact sheet`);+ }+ if (own.filter || node.attrs.filter) warnings.add("an element uses an SVG filter (blur, shadow); the import leaves it out, the film draws shadows itself");+ let clip = clipFromMask ?? clipOuter; const cid = urlRef(own["clip-path"]);+ if (cid) { const cp = byId.get(cid); const ds = cp ? cp.kids.map((k) => shapeToD(k) && { d: shapeToD(k), m: k.attrs.transform ? mul(mm, parseTransform(k.attrs.transform)) : mm }).filter(Boolean) : []; if (ds.length) clip = { paths: ds.map((x) => ({ d: x.d, m: x.m.map(round6) })) }; else warnings.add(`clip-path #${cid} could not be read; drawn unclipped`); }+ if (t === "text") { warnings.add("the file has live text: export with text outlined (Figma: svgOutlineText) or supply the font file, never set it in a stand-in face silently"); fonts.add(own["font-family"] ?? st["font-family"] ?? "(unnamed)"); return; }+ if (t === "image") { warnings.add("the file embeds a raster image; it is not a path, so it is not imported (bring it as an asset pinned by sha256)"); return; }+ if (t === "use") {+ const ref = byId.get(String(node.attrs["xlink:href"] ?? node.attrs.href ?? "").replace(/^#/, ""));+ if (!ref) { warnings.add(`a <use> points at a missing element`); return; }+ const um = mul(mm, [1, 0, 0, 1, n0(node.attrs.x), n0(node.attrs.y)]);+ if (ref.tag === "symbol") { ref.kids.forEach((k) => visit(k, um, st, o, clip)); return; }+ visit({ ...ref, attrs: { ...ref.attrs, id: undefined } }, um, st, o, clip); return;+ }+ if (t === "g" || t === "svg" || t === "a" || t === "switch") { node.kids.forEach((k) => visit(k, mm, st, o, clip)); return; }+ const d = shapeToD(node); if (!d) return;+ let local; try { local = bboxOf(flatten(d)); } catch (e) { warnings.add(`skipped a ${t} with unreadable path data (${e.message})`); return; }+ const isLine = t === "line" || t === "polyline";+ const fill = isLine ? null : paint(st.fill ?? "#000", local), stroke = paint(st.stroke, local);+ if (!fill && !stroke) return;+ const subs = flatten(d, mm), bb = bboxOf(subs), sw = n0(st["stroke-width"], 1) * Math.sqrt(Math.abs(mm[0] * mm[3] - mm[1] * mm[2]));+ const part = { d, fill: fill ?? { type: "none" }, rule: st["fill-rule"] === "evenodd" ? "evenodd" : "nonzero", op: round(o * pct(st["fill-opacity"], 1)), bb: (stroke ? [bb[0] - sw / 2, bb[1] - sw / 2, bb[2] + sw, bb[3] + sw] : bb).map(round) };+ if (!isIdentity(mm)) part.m = mm.map(round6);+ if (stroke) { part.stroke = { paint: stroke, w: n0(st["stroke-width"], 1), cap: st["stroke-linecap"] ?? "butt", join: st["stroke-linejoin"] ?? "miter", op: round(o * pct(st["stroke-opacity"], 1)) }; warnings.add("the file has strokes; they are drawn as strokes (export with outlined strokes for an exact match at every scale)"); }+ if (clip) part.clip = clip;+ parts.push(part);+ };+ svg.kids.forEach((k) => visit(k, root, {}, 1, null));+ return { w, h, parts, fonts: [...fonts], warnings: [...warnings] };+};+const round6 = (v) => Math.round(v * 1e6) / 1e6;++// ------------------------------------------------------------------ what the marks can do in motion+/** Outline points of a whole element, resampled so long curves and short lines weigh the same. */+export const outline = (el, spacing) => {+ const pts = [];+ for (const p of el.parts) for (const s of flatten(p.d, p.m ?? I)) for (let i = 1; i < s.length; i++) {+ const [x0, y0] = s[i - 1], [x1, y1] = s[i], L = Math.hypot(x1 - x0, y1 - y0), n = Math.max(1, Math.ceil(L / spacing));+ for (let j = 0; j < n; j++) pts.push([x0 + ((x1 - x0) * j) / n, y0 + ((y1 - y0) * j) / n]);+ }+ return pts;+};+const grid = (pts, cell) => { const g = new Map(); for (const p of pts) { const k = `${Math.floor(p[0] / cell)},${Math.floor(p[1] / cell)}`; (g.get(k) ?? g.set(k, []).get(k)).push(p); } return g; };+const nearest = (g, cell, [x, y]) => { let best = Infinity; const cx = Math.floor(x / cell), cy = Math.floor(y / cell); for (let i = -1; i <= 1; i++) for (let j = -1; j <= 1; j++) for (const q of g.get(`${cx + i},${cy + j}`) ?? []) best = Math.min(best, Math.hypot(q[0] - x, q[1] - y)); return best; };+/** Worst distance from the mapped outline back to the outline, as a share of the diagonal. */+const mismatch = (pts, map, tol) => { const g = grid(pts, tol); let worst = 0; for (const p of pts) { const d = nearest(g, tol, map(p)); if (d > worst) worst = d; if (worst === Infinity) break; } return worst; };+/**+ * Symmetry of an element about its bounding-box centre. -> { rotational: n (1 = none; 2 = same after a half turn), mirrorX, mirrorY }+ * A tolerance of 1% of the diagonal: exports carry rounding, a real asymmetry is far larger.+ */+export const symmetry = (el, tolShare = 0.01) => {+ const bb = bboxOf(el.parts.map((p) => flatten(p.d, p.m ?? I)).flat()), diag = Math.hypot(bb[2], bb[3]) || 1, tol = diag * tolShare;+ const pts = outline(el, tol / 2), cx = bb[0] + bb[2] / 2, cy = bb[1] + bb[3] / 2;+ const rot = (a) => ([x, y]) => [cx + (x - cx) * Math.cos(a) - (y - cy) * Math.sin(a), cy + (x - cx) * Math.sin(a) + (y - cy) * Math.cos(a)];+ const holds = (map) => mismatch(pts, map, tol) <= tol;+ let rotational = 1; for (const n of [6, 5, 4, 3, 2]) if (holds(rot((2 * Math.PI) / n))) { rotational = n; break; }+ return { rotational, mirrorX: holds(([x, y]) => [2 * cx - x, y]), mirrorY: holds(([x, y]) => [x, 2 * cy - y]) };+};+/**+ * Repeats inside an element: parts with the same shape (same size, fill and outline) placed at a constant step.+ * -> [{ copies, step: [dx, dy], seamless }]; seamless when copies x step spans the element's own width or height, so it tiles end to end.+ */+export const repeats = (el, tol = 0.5) => {+ // a gradient's coordinates move with each copy, so a copy is matched by its colours, not by its gradient vector+ const colours = (f) => (f.type === "solid" ? f.c : f.type === "none" ? "none" : JSON.stringify(f.stops));+ const shapeSig = (p) => `${Math.round(p.bb[2] / tol)}x${Math.round(p.bb[3] / tol)}|${parsePath(p.d).length}`;+ const out = [], seen = new Set();+ for (const [what, sig] of [["shape", shapeSig], ["pattern", (p) => `${shapeSig(p)}|${colours(p.fill)}`]]) {+ const groups = new Map(); for (const p of el.parts) { const k = sig(p); (groups.get(k) ?? groups.set(k, []).get(k)).push(p); }+ for (const g of groups.values()) {+ if (g.length < 2) continue;+ for (const axis of [0, 1]) {+ const pos = g.map((p) => p.bb[axis]).sort((a, b) => a - b), steps = pos.slice(1).map((v, i) => v - pos[i]);+ if (!steps.every((s) => s > tol && Math.abs(s - steps[0]) <= tol)) continue;+ const step = round(steps[0]), span = axis ? el.h : el.w, key = `${what}|${axis}|${step}`;+ if (seen.has(key) || (what === "pattern" && seen.has(`shape|${axis}|${step}`))) continue; seen.add(key);+ out.push({ what, copies: g.length, step: axis ? [0, step] : [step, 0], seamless: Math.abs(g.length * step - span) <= Math.max(1, span * 0.005) });+ }+ }+ }+ return out;+};++/** Every colour an element uses, from fills, strokes and gradient stops. */+export const coloursOf = (el) => {+ const out = new Map(), add = (c, area) => { if (!c || c === "none") return; out.set(c, (out.get(c) ?? 0) + area); };+ const fromPaint = (f, area) => { if (!f) return; if (f.type === "solid") add(f.c, area); else for (const s of f.stops ?? []) add(s[1], area / (f.stops.length || 1)); };+ for (const p of el.parts) { const area = p.bb[2] * p.bb[3]; fromPaint(p.fill, area); if (p.stroke) fromPaint(p.stroke.paint, area * 0.1); }+ return out;+};++/**+ * Logo metrics for sizing a strip of logos so they read equally: ink area (outline area under the fill rule),+ * ink bbox, and overlapping outlines between separate parts (flagged "check with the owner": shared strokes in a+ * wordmark may be the design, so they are never auto-fixed).+ */+export const logoMetrics = (el) => {+ const shapes = el.parts.map((p) => ({ subs: flatten(p.d, p.m ?? I), rule: p.rule, bb: p.bb }));+ const ink = shapes.reduce((s, x) => s + inkArea(x.subs, x.rule), 0), bb = bboxOf(shapes.map((x) => x.subs).flat());+ let overlaps = 0;+ for (let i = 0; i < shapes.length; i++) for (let j = i + 1; j < shapes.length; j++) {+ const a = shapes[i].bb, b = shapes[j].bb; if (a[0] > b[0] + b[2] || b[0] > a[0] + a[2] || a[1] > b[1] + b[3] || b[1] > a[1] + a[3]) continue;+ // a vertex of one outline strictly inside the other's outer ring means the shapes cross or share a stroke+ const outer = (s) => s.subs.reduce((m, p) => (Math.abs(signedArea(p)) > Math.abs(signedArea(m)) ? p : m), s.subs[0]);+ const A = outer(shapes[i]), B = outer(shapes[j]);+ if (A && B && (A.some((p) => inside(p, B)) || B.some((p) => inside(p, A)))) overlaps++;+ }+ return { ink: round(ink), bbox: bb.map(round), aspect: bb[3] ? round(bb[2] / bb[3]) : 0, overlaps };+};+/** Recolour every paint of an element to one colour (a logo for a dark or light ground). Gradients become the colour too. */+export const monochrome = (el, colour) => ({ ...el, parts: el.parts.map((p) => ({ ...p, fill: p.fill.type === "none" ? p.fill : { type: "solid", c: colour }, ...(p.stroke ? { stroke: { ...p.stroke, paint: { type: "solid", c: colour } } } : {}) })) });+/** Write an element back out as a standalone SVG (tight viewBox around its ink, for logos). */+export const toSvg = (el, { tight = false, pad = 0 } = {}) => {+ const bb = tight ? bboxOf(el.parts.map((p) => flatten(p.d, p.m ?? I)).flat()) : [0, 0, el.w, el.h];+ const vb = [bb[0] - pad, bb[1] - pad, bb[2] + 2 * pad, bb[3] + 2 * pad].map(round);+ const defs = [], paintAttr = (f) => {+ if (!f || f.type === "none") return "none"; if (f.type === "solid") return f.c;+ const id = `g${defs.length}`, stops = f.stops.map(([o, c, a]) => `<stop offset="${o}" stop-color="${c}" stop-opacity="${a}"/>`).join(""), gt = f.m ? ` gradientTransform="matrix(${f.m.join(" ")})"` : "";+ defs.push(f.type === "lin" ? `<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${f.x1}" y1="${f.y1}" x2="${f.x2}" y2="${f.y2}"${gt}>${stops}</linearGradient>` : `<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${f.cx}" cy="${f.cy}" r="${f.r}" fx="${f.fx}" fy="${f.fy}"${gt}>${stops}</radialGradient>`);+ return `url(#${id})`;+ };+ const body = el.parts.map((p) => `<path d="${p.d}" fill="${paintAttr(p.fill)}" fill-rule="${p.rule}"${p.op !== 1 ? ` opacity="${p.op}"` : ""}${p.m ? ` transform="matrix(${p.m.join(" ")})"` : ""}${p.stroke ? ` stroke="${paintAttr(p.stroke.paint)}" stroke-width="${p.stroke.w}"` : ""}/>`).join("");+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${vb[2]}" height="${vb[3]}" viewBox="${vb.join(" ")}">${defs.length ? `<defs>${defs.join("")}</defs>` : ""}${body}</svg>`;+};++// ------------------------------------------------------------------ outputs+/** The TS module a film imports. brandMeta goes into meta.brand so the gate knows the brand's colours and elements. */+export const brandModule = (brand, kitImport) => [+ `// Written by tools/brand.mjs import from ${Object.keys(brand.elements).length} source file(s); never edit by hand, re-import instead.`,+ "// These are the brand's exact paths: move, rotate, scale evenly, clip and layer them (brandKit.ts), never redraw them.",+ kitImport ? `import type { BrandElement } from "${kitImport}";` : "type BrandElement = { w: number; h: number; parts: any[] };",+ "",+ `export const BRAND: { elements: Record<string, BrandElement>; palette: { hex: string; share: number }[]; fonts: string[]; motion: Record<string, any> } = ${JSON.stringify({ elements: brand.elements, palette: brand.palette, fonts: brand.fonts, motion: brand.motion ?? {} })};`,+ "",+ `/** For the film's meta.brand: the brand's colours (never drawn translucent outside a declared exception) and its element names. */`,+ `export const brandMeta = ${JSON.stringify({ colors: brand.palette.map((p) => p.hex).filter((h) => /^#[0-9a-f]{6}$/.test(h)), elements: Object.keys(brand.elements) })};`,+ "/** For the film's meta.motion: layerscan fails a brand colour filled half-transparent. Spread it: meta.motion = { ...brandMotion, temperament: \"calm\" }. */",+ `export const brandMotion = ${JSON.stringify({ brandColors: brand.palette.map((p) => p.hex).filter((h) => /^#[0-9a-f]{6}$/.test(h)) })};`,+ "",+].join("\n");++/** Size every logo so its ink matches the median logo's ink at the strip height: equal visual weight, not equal boxes. */+export const equaliseLogos = (logos, height = 80) => {+ // ink per unit of height squared, so logos of different heights compare+ const dens = logos.map((l) => l.ink / (l.h * l.h)), sorted = [...dens].sort((a, b) => a - b), median = sorted[Math.floor(sorted.length / 2)] || 1;+ return logos.map((l, i) => ({ ...l, density: Math.round(dens[i] * 1000) / 1000, height: Math.round(height * Math.sqrt(median / (dens[i] || median))) }));+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjsindex 0fbcce2..bba23e2 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/build-page.mjs@@ -3,9 +3,9 @@import { build } from "esbuild";import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";import { createHash } from "node:crypto";-import { extname, join, relative, resolve } from "node:path";-import { overlay, resolveOverlay } from "./overlay.mjs";-import { requireFilm, splitShape } from "./names.mjs";+import { dirname, extname, join, relative, resolve } from "node:path";+import { enginePath, overlay, resolveOverlay } from "./overlay.mjs";+import { filmModule, requireFilm, splitShape, standardHost } from "./names.mjs";import { loadFilmModule, prepareFilmSounds, filmFloat32 } from './audio.mjs';import { isMain } from "./is-main.mjs";@@ -49,21 +49,30 @@ export const buildPage = async ({ entry, out, title, plugins: extra = [] }) => {const { base, shape } = splitShape(title);if (shape) { entry = entry.replace(`page-${title}.ts`, `page-${base}.ts`); title = base; }if (!existsSync(entry)) entry = resolveOverlay("./" + entry, process.cwd()) ?? entry; // e.g. the example's own host page- if (!existsSync(entry) && title) requireFilm(title, "build", "a film name: src/hosts/page-<film>.ts"); // a clear exit with the known films, not an esbuild trace- const main = await build({ absWorkingDir: process.cwd(), entryPoints: [resolve(entry)], bundle: true, format: "iife", target: "es2020", minify: true, write: false, legalComments: "none", metafile: true, plugins: [...plugins, tagFilms] });+ // no host page of its own: the standard one (names.mjs standardHost), built in memory next to the film's module+ const mod = !existsSync(entry) && title ? filmModule(title) : null;+ if (!existsSync(entry) && !mod && title) requireFilm(title, "build", "a film name: src/hosts/page-<film>.ts"); // a clear exit with the known films, not an esbuild trace+ const from = mod ? { stdin: { contents: standardHost(title), resolveDir: join(dirname(dirname(mod)), "hosts"), sourcefile: `page-${title}.ts`, loader: "ts" }, tsconfig: enginePath("tsconfig.json") } : { entryPoints: [resolve(entry)] };+ const main = await build({ absWorkingDir: process.cwd(), ...from, bundle: true, format: "iife", target: "es2020", minify: true, write: false, legalComments: "none", metafile: true, plugins: [...plugins, tagFilms] });const js = main.outputFiles[0].text;// read the manifest out of the film module itself, so the page and the film can never disagreeconst { film, music } = await loadFilmModule(shape ? `${title}-${shape}` : title, plugins);const recorded = prepareFilmSounds(film, music), audio = recorded ? filmFloat32(film) : null;- const assets = Object.fromEntries(Object.entries(film.assets.images).map(([name, file]) => { const mime = MIME[extname(file).toLowerCase()]; if (!mime) throw new Error(`asset '${name}': unsupported type ${file}`); return [name, `data:${mime};base64,${readFileSync(join(process.cwd(), file)).toString("base64")}`]; }));+ // PLACEHOLDERS (ANIDOODLE_PLACEHOLDERS=1, render/still/framecheck alike): a missing image asset becomes a+ // labelled grey box so the film can be worked on before every photo arrives. The page lists them in+ // FILM.meta.placeholders and verify-export --delivery (and ship) refuse such a file.+ const placeholders = [], PH = process.env.ANIDOODLE_PLACEHOLDERS === "1";+ const stand = (name) => { placeholders.push(name); const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="800"><rect width="800" height="800" fill="#9a9a9a"/><path d="M0 0L800 800M800 0L0 800" stroke="#7a7a7a" stroke-width="6"/><text x="400" y="410" font-family="sans-serif" font-size="44" text-anchor="middle" fill="#fff">MISSING: ${name.replace(/[<&>"]/g, "")}</text></svg>`; return [name, `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`]; };+ const assets = Object.fromEntries(Object.entries(film.assets.images).map(([name, file]) => { if (PH && !existsSync(join(process.cwd(), file))) return stand(name); const mime = MIME[extname(file).toLowerCase()]; if (!mime) throw new Error(`asset '${name}': unsupported type ${file}`); return [name, `data:${mime};base64,${readFileSync(join(process.cwd(), file)).toString("base64")}`]; }));// the renderer that draws every plate frame, and the assets any plate may read, salt every key- const salt = [BAKE_FORMAT, ...["src/canvas-core/film.ts", "src/canvas-core/core.ts"].map((f) => readFileSync(resolve(f), "utf8")), JSON.stringify(assets)].join("\0");+ const salt = [BAKE_FORMAT, ...["src/canvas-core/film.ts", "src/canvas-core/core.ts"].map((f) => readFileSync(enginePath(f), "utf8")), JSON.stringify(assets)].join("\0");const bakeSrc = bakeHashes(main.metafile, salt);const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${film.meta.title}</title><style>html,body{margin:0;height:100%;background:#1b1a1a;display:grid;place-items:center}canvas{max-width:100vw;max-height:100vh;aspect-ratio:${film.meta.W}/${film.meta.H};cursor:pointer;background:#fff}</style></head>-<body><canvas id="film"></canvas><script>window.__ASSETS__=${JSON.stringify(assets)};window.__BAKE_SRC__=${JSON.stringify(bakeSrc)};${audio ? `window.__AUDIO__=${JSON.stringify(audio)};` : ''}${shape ? `window.__SHAPE__=${JSON.stringify(shape)};` : ""}</script><script>${js.replace(/<\/script/g, "<\\/script")}</script></body></html>`;+<body><canvas id="film"></canvas><script>window.__ASSETS__=${JSON.stringify(assets)};window.__BAKE_SRC__=${JSON.stringify(bakeSrc)};${audio ? `window.__AUDIO__=${JSON.stringify(audio)};` : ''}${shape ? `window.__SHAPE__=${JSON.stringify(shape)};` : ""}${placeholders.length ? `window.__PLACEHOLDERS__=${JSON.stringify(placeholders)};` : ""}</script><script>${js.replace(/<\/script/g, "<\\/script")}</script></body></html>`;mkdirSync(join(out, ".."), { recursive: true }); writeFileSync(out, html);const meta = film.meta;- return { out, bytes: html.length, meta, assets: Object.keys(film.assets.images) };+ if (placeholders.length) console.warn(`build: ${placeholders.length} missing asset(s) drawn as placeholders: ${placeholders.join(", ")} (never for delivery)`);+ return { out, bytes: html.length, meta, assets: Object.keys(film.assets.images), placeholders };};if (isMain(import.meta.url)) { const title = requireFilm(process.argv[2], "build-page", "node tools/build-page.mjs <film>"); const r = await buildPage({ entry: `src/hosts/page-${title}.ts`, out: `dist/${title}.html`, title }); console.log(`built ${r.out} (${(r.bytes / 1024).toFixed(0)} KB, self-contained)`); }diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/cues.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/cues.mjsnew file mode 100644index 0000000..d78c73a--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/cues.mjs@@ -0,0 +1,44 @@+#!/usr/bin/env node+// CUES. Writes a film's cue sheet (src/canvas-core/cues.ts: withCues) as JSON from the film's own+// source and time maps, so the sound mix never reads a hand-copied timing file again.+// node tools/cues.mjs <film> [--out out/<film>.cues.json] [--check out/<film>.cues.json]+// --check: exit 1 when the film's cues moved since that sheet was written (the mix built from it is+// out of date: rebuild it). A film with no cue sheet exits 2 with how to declare one, never a quiet pass.+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { build } from "esbuild";+import { fileURLToPath } from "node:url";+import { isMain } from "./is-main.mjs";+import { loadFilmModule } from "./audio.mjs";++// fileURLToPath, never URL.pathname: a space in the path stays a space and a Windows drive stays C:\+export const loadCues = async () => { const r = await build({ stdin: { contents: `export * from "./src/canvas-core/cues";`, resolveDir: join(dirname(fileURLToPath(import.meta.url)), ".."), loader: "ts" }, bundle: true, write: false, format: "esm", platform: "neutral", logLevel: "error" }); return import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64")); };++/** The sheet as written to disk: the film, its frame rate and length, and every cue. */+export const exportCues = async (name) => {+ const { film } = await loadFilmModule(name);+ if (!Array.isArray(film.cues) || !film.cues.length) throw Object.assign(new Error(`${name} declares no cues. Wrap the film: export const ${name} = withCues(film, [{ name: "x-lock", at: { scene: 22, through: [master] } }, ...]) (src/canvas-core/cues.ts). Sound and sync are cued from these, never from a hand-copied timing file.`), { code: 2 });+ // a launch template film's cues are sound cues with no name and no time: sheetCues names and times them+ // (written raw, the print below crashed on c.t.toFixed and --check saw every cue as one)+ const { sheetCues } = await loadCues();+ return { film: name, fps: film.meta.fps, durationFrames: film.meta.durationFrames, durationS: +(film.meta.durationFrames / film.meta.fps).toFixed(4), cues: sheetCues(film.cues, film.meta.fps) };+};++if (isMain(import.meta.url)) {+ const argv = process.argv.slice(2), name = argv.find((a, i) => !a.startsWith("--") && !["--out", "--check"].includes(argv[i - 1]));+ const opt = (k) => { const i = argv.indexOf(k); return i >= 0 ? argv[i + 1] : undefined; };+ if (!name) { console.error("usage: node tools/cues.mjs <film> [--out out/<film>.cues.json] [--check old.cues.json]"); process.exit(2); }+ try {+ const sheet = await exportCues(name);+ if (opt("--check")) {+ const f = resolve(opt("--check")); if (!existsSync(f)) { console.error(`cues: no sheet at ${f}`); process.exit(2); }+ const { diffSheets } = await loadCues(), d = diffSheets(JSON.parse(readFileSync(f, "utf8")), sheet);+ if (d.length) { console.log(`CUES ${name}: the sheet ${opt("--check")} is out of date, so is any mix built from it:`); for (const x of d) console.log(` ${x}`); console.log(`fix: node tools/cues.mjs ${name} --out ${opt("--check")} and rebuild the mix (node tools/track.mjs mix ...)\nVERDICT: FAIL`); process.exit(1); }+ console.log(`CUES ${name}: ${sheet.cues.length} cues match ${opt("--check")}\nVERDICT: PASS`); process.exit(0);+ }+ const out = resolve(opt("--out") ?? `out/${name}.cues.json`); mkdirSync(dirname(out), { recursive: true });+ writeFileSync(out, JSON.stringify(sheet, null, 1) + "\n");+ console.log(`CUES ${name}: ${sheet.cues.length} cues over ${sheet.durationS} s -> ${out}`);+ for (const c of sheet.cues) console.log(` ${String(c.frame).padStart(6)} ${c.t.toFixed(3).padStart(8)} s ${c.name.padEnd(24)} ${c.sound ?? ""}${c.sync ? " (sync marker)" : ""}`);+ } catch (e) { console.error(`cues: ${e.message}`); process.exit(e.code === 2 ? 2 : 2); }+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjsindex 8cdc9a0..3019e51 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/emit.mjs@@ -22,6 +22,7 @@ import { pathToFileURL } from "node:url";import { buildPage } from "./build-page.mjs";import { requireFilm } from "./names.mjs";import { pageChecks, probe } from "./adapters/html-player.mjs";+import { glArgs } from "./adapters/playwright.mjs";const VAL = new Set(["out", "frames", "scale"]);const pos = [], opt = {};@@ -55,7 +56,7 @@ pageChecks(html, ship.assets).forEach((c) => say(c.ok, c.label, c.detail));say(statSync(out).size === ship.bytes, "the file on disk is the file that was built", `${statSync(out).size} bytes`);// ---------------------------------------------------------------- 2 & 3. run it-const browser = await p.env.pw.lib.chromium.launch({ executablePath: p.env.browser.executablePath, args: ["--disable-background-timer-throttling"] });+const browser = await p.env.pw.lib.chromium.launch({ executablePath: p.env.browser.executablePath, args: ["--disable-background-timer-throttling", ...glArgs(out)] });const context = await browser.newContext({ viewport: { width: 640, height: 640 }, deviceScaleFactor: 1 });const openPage = async (file) => {const page = await context.newPage(), errors = [], reached = [];diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/facts.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/facts.mjsindex daa4d19..248cdb5 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/facts.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/facts.mjs@@ -20,7 +20,9 @@// - a sourced entry has the exact sentence and a URL (http/https) or a file;// - a generated entry says what it is, and states no number (a number needs a source);// - every number in a sourced claim appears in its source sentence;-// - a TODO is not a claim yet.+// - a TODO is not a claim yet;+// - a fact is said once: the same line twice, or the same number in two entries, needs `reuse: "<reason>"`;+// - a site source ({ kind: "site", url, fetched: "YYYY-MM-DD" }) carries the day it was read.import { existsSync, readFileSync, writeFileSync } from "node:fs";import { resolve } from "node:path";import { isMain } from "./is-main.mjs";diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/factsrules.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/factsrules.mjsindex 1f347d7..c28b313 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/factsrules.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/factsrules.mjs@@ -16,6 +16,8 @@ export const entryProblems = (e) => {return out;}const src = e.source ?? {}, sentence = String(src.sentence ?? "").trim();+ // a live site changes: a site source carries the day it was read, so a viewer's "that's wrong now" can be dated+ if (src.kind === "site") { if (!src.url) out.push("is a site source with no url"); if (!/^\d{4}-\d{2}-\d{2}$/.test(String(src.fetched ?? ""))) out.push("is a site source with no fetched date (YYYY-MM-DD, the day the page was read)"); }if (!sentence) out.push("has no source.sentence (the exact sentence it comes from)");if (!String(src.url ?? "").trim() && !String(src.file ?? "").trim()) out.push("has no source.url or source.file");else if (src.url && !/^https?:\/\/\S+$/i.test(String(src.url).trim())) out.push(`source.url '${src.url}' is not an http(s) link`);@@ -28,7 +30,7 @@ export const entryProblems = (e) => {* -> { status: "PASS" | "FAIL" | "N/A", checked, problems: [{ claim, why }] }*/export const checkFacts = (claims, facts) => {- const declared = [...new Set((Array.isArray(claims) ? claims : []).map((c) => String(c).trim()).filter(Boolean))];+ const raw = (Array.isArray(claims) ? claims : []).map((c) => String(c).trim()).filter(Boolean), declared = [...new Set(raw)];if (!declared.length) return { status: "N/A", checked: 0, problems: [], reason: "the film declares no claims (film.claims), so nothing was checked" };if (!facts) return { status: "FAIL", checked: declared.length, problems: declared.map((c) => ({ claim: c, why: "has no facts.json to be listed in (node tools/facts.mjs init)" })) };const entries = Array.isArray(facts.claims) ? facts.claims : [], problems = [];@@ -40,6 +42,7 @@ export const checkFacts = (claims, facts) => {if (!e) { problems.push({ claim: c, why: "is on screen but not listed in facts.json" }); continue; }for (const why of entryProblems(e)) problems.push({ claim: c, why });}+ problems.push(...dupes(raw, entries));const declaredKeys = new Set(declared.map(normClaim));for (const e of entries) if (!declaredKeys.has(normClaim(e?.claim))) for (const why of entryProblems(e)) problems.push({ claim: String(e?.claim ?? "(no claim)"), why }); // narrated and other listed claims are held to the same shapereturn { status: problems.length ? "FAIL" : "PASS", checked: declared.length, problems };@@ -48,3 +51,23 @@ export const checkFacts = (claims, facts) => {/** The film's declared claims (a launch film: film.claims; any film may set film.claims or meta.claims). */export const claimsOf = (film) => film?.claims ?? film?.meta?.claims;++// A fact said twice is a beat wasted: a launch film said "about 400 of them" in the hook and "400+" on a+// numbers card, and the second one was cut late. Numbers worth repeating are rare enough to ask for a reason.+const FACT_NUMBER = /\d[\d.,]*\d[%+x]?|\d[%+x]|\d{2,}/g;+const factNumbers = (s) => [...new Set((String(s).match(FACT_NUMBER) ?? []).map((n) => n.replace(/[.,]+$/, "").replace(/[%+x]$/, "").replace(/,/g, "")).filter((n) => n.length >= 2 || /[%+x]/.test(n)))];+/**+ * Repeats across one film: the same line declared twice, or the same number stated by two entries.+ * The later entry may carry `reuse: "<why the repeat earns its place>"`. -> [{ claim, why }]+ */+export const dupes = (raw, entries = []) => {+ const out = [], seen = new Map();+ for (const c of raw ?? []) { const k = normClaim(c); if (seen.has(k)) { const e = entries.find((x) => normClaim(x?.claim) === k); if (!String(e?.reuse ?? "").trim()) out.push({ claim: c, why: "is on screen twice; cut one, or give its entry reuse: \"<why the repeat earns its place>\"" }); } seen.set(k, true); }+ const firstBy = new Map();+ for (const e of entries) for (const n of factNumbers(e?.claim)) {+ const first = firstBy.get(n);+ if (first === undefined) { firstBy.set(n, e); continue; }+ if (first !== e && !String(e.reuse ?? "").trim()) out.push({ claim: String(e.claim), why: `states ${n} again (first in "${String(first.claim).slice(0, 40)}"); say a fact once, or give this entry reuse: "<reason>"` });+ }+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/framecheck.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/framecheck.mjsindex f4079b8..95cd52e 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/framecheck.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/framecheck.mjs@@ -1,49 +1,91 @@-// FRAMECHECK. Design faults the determinism gate cannot see, found on the frames themselves.-// 1. Cut by the edge. Every line of text (fillText, writeOn, setType) and every content box the art-// reports (probeRect: an answer card, a product window, a film's card) must lie wholly inside the-// frame or wholly outside it, on every frame checked. A deliberate full-bleed is not reported as a box.-// 2. Reading time. Each declared text cue (meta.captions) stays up for max(0.7 s, 0.3 s per word).-// A film that declares no cues reports N/A, never a pass.-// 3. Phone safe zones, 9:16 frames only. No text inside the top band, the bottom band or the right-// button column the platforms cover with their own interface. Other shapes report N/A.-// The rules and their numbers are textrules.mjs.-// node tools/framecheck.mjs <film>[-<shape>] [--every 1] [--from F] [--to T] [--zones fail|warn]-// --zones warn lists safe-zone text as FLAG and does not fail the run (launch.mjs ship passes it on with-// its own --zones warn; by default safe-zone text fails). Reading time and the edge cut always fail.+// FRAMECHECK. Design faults the determinism gate cannot see, found on the frames themselves, from the+// text and boxes every frame actually draws (the frame probe in hosts/page.ts follows text through+// offscreen layers, so a sheet composited later counts like text on the frame).+// 1. Cut by the edge. No line of text and no content box the art reports (probeRect) SITS cut by the+// frame's edge: cut and unmoved on 3 checked frames in a row fails. Sliding across the edge while+// the camera travels (one world, a pan) is motion, and is listed, not failed.+// 2. Reading time. EVERY block of text the film draws is a cue, timed from the frame it is complete+// (a typed reply: after its last character) to the last frame it is up, and must stay up+// max(0.7 s, 0.3 s per word); meta.captions are checked too. A film that draws text can never be+// N/A: it was on a brand launch film, which shipped "text too fast" with this check printing N/A.+// Words meant as texture (readable.ts texture()) are skipped and counted.+// 3. Phone safe zones, 9:16 only: no text in the platforms' top band, bottom band or right column.+// 4. Layout: too many text blocks, blocks packed into a corner, a centred stack, a gap under 3 % of+// the height, text across the edge of a content box, text over text (framerules.mjs, held 0.5 s).+// 5. The last second: no text under 28 px at 1080. The end card lands once. Heads in one group+// within 10 %. Font families listed (brand faces, stand-ins: meta.checks.fonts / standIns).+// The rules and their numbers are textrules.mjs and framerules.mjs.+// node tools/framecheck.mjs <film>[-<shape>] [--every 1] [--from F] [--to T] [--zones fail|warn] [--json out.json]+// --zones warn lists safe-zone text as FLAG and does not fail the run. Everything else fails.+import { writeFileSync } from "node:fs";import { resolve } from "node:path";import { buildPage } from "./build-page.mjs";import { detect } from "./detect.mjs";import * as playwright from "./adapters/playwright.mjs";import { requireFilm } from "./names.mjs";import { isMain } from "./is-main.mjs";-import { SAFE_ZONES, isPortrait916, readingTime, safeZoneHits } from "./textrules.mjs";+import { SAFE_ZONES, isPortrait916, safeZoneHits } from "./textrules.mjs";+import { autoCues, checkedFrames, edgeCuts, endCardRuns, endSizeFindings, fontReport, framesOf, headSpread, layoutFindings, readingFloor, readingVerdict } from "./framerules.mjs";-const USAGE = "node tools/framecheck.mjs <film>[-<shape>] [--every 1] [--from F] [--to T] [--zones fail|warn]";+const USAGE = "node tools/framecheck.mjs <film>[-<shape>] [--every 1] [--from F] [--to T] [--zones fail|warn] [--json out.json]";export const frameCheck = async (film, { every = 1, from = 0, to } = {}) => {const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film });- const s = await playwright.open(detect(), page.out, { workers: 1 }), meta = await s.info(), N = to ?? meta.durationFrames, portrait = isPortrait916(meta.W, meta.H);- const frames = []; for (let f = from; f < N; f += every) frames.push(f);- const recs = []; for (let i = 0; i < frames.length; i += 40) recs.push(...(await s.probe(frames.slice(i, i + 40), portrait)));+ // the bake cache stays off: a plate frame read back from disk carries no text records+ const s = await playwright.open(detect(), page.out, { workers: 1, bakeCache: false }), meta = await s.info();+ let frames; try { frames = checkedFrames({ every, from, to }, meta.durationFrames); } catch (e) { await s.close(); throw new Error(`framecheck: ${e.message}`); }+ const recs = []; for (let i = 0; i < frames.length; i += 40) recs.push(...(await s.probe(frames.slice(i, i + 40), true)));await s.close();- return { meta, frames: frames.length, bad: recs.filter((r) => r.cut !== false), reading: readingTime(meta.captions, meta.fps), zones: safeZoneHits(recs, meta.W, meta.H) };+ const scale = 1, W = meta.W * scale, H = meta.H * scale, byFrame = framesOf(recs, frames), ck = meta.checks ?? {};+ const auto = autoCues(byFrame, frames, { first: 0, last: meta.durationFrames, fps: meta.fps });+ return {+ meta, frames: frames.length, every, // every > 1: a quick look (holds measured in steps of `every` frames), never a ship PASS+ bad: recs.filter((r) => r.cut !== false), cuts: edgeCuts(recs.filter((r) => r.cut !== false), frames),+ reading: readingVerdict(auto, meta.captions, meta.fps, frames.length), auto,+ floor: readingFloor(auto.cues, meta.fps),+ zones: safeZoneHits(recs.filter((r) => r.cut === false), W, H),+ layout: layoutFindings(byFrame, frames, { W, H, fps: meta.fps, exemptRanges: ck.layoutExempt }),+ endSize: endSizeFindings(byFrame, frames, { W, H, fps: meta.fps, durationFrames: meta.durationFrames, scale }),+ endCard: endCardRuns(byFrame, frames),+ heads: headSpread(byFrame, frames),+ fonts: fontReport(byFrame, frames, ck),+ };};++/** The verdict lines of a frameCheck result, and how many of them fail. Shared with ship.mjs. */+export const frameReport = (film, r, { warnZones = false } = {}) => {+ const lines = [], list = (fs) => `${fs.slice(0, 8).join(", ")}${fs.length > 8 ? " ..." : ""}`, out = (l) => lines.push(l);+ const cuts = r.cuts.filter((c) => c.fail), passing = r.cuts.length - cuts.length;+ out(`FRAMECHECK ${film} ${r.meta.W}x${r.meta.H}, ${r.frames} frames`);+ for (const c of cuts) out(` FAIL ${c.kind} "${String(c.label).slice(0, 48)}" cut by the frame's edge and held there ${c.held} frames (${c.frames.length} cut in all): ${list(c.frames)} box ${c.box.map((v) => Math.round(v)).join(",")}`);+ const rd = r.reading, zn = r.zones;+ for (const b of rd.bad) out(` FAIL text "${b.text.slice(0, 48)}" is up ${b.seconds} s from frame ${b.from}; reading it takes ${b.need} s (hold it longer: readable.ts chatHold/readS, or mark texture() if it is not meant to be read)`);+ for (const h of zn.hits ?? []) out(` ${warnZones ? "FLAG" : "FAIL"} text "${h.label.slice(0, 48)}" sits in the ${h.zone} on ${h.frames.length} frame(s): ${list(h.frames)}`);+ for (const x of r.layout) out(` FAIL ${x.msg} frames ${x.from}-${x.to} (declare a deliberate one in meta.checks.layoutExempt with a reason)`);+ for (const x of r.endSize) out(` FAIL ${x.msg}`);+ if (!r.endCard.ok) out(` FAIL ${r.endCard.msg}`);+ for (const g of r.heads) if (!g.ok) out(` FAIL heads in "${g.group}" differ by ${Math.round(g.spread * 100)}% (at most 10%): ${g.people.map((p) => `${p.name} ${p.h} px`).join(", ")}; place them with people.ts drawPerson and one headPx`);+ for (const f of r.fonts) if (f.standFor || f.offBrand) out(` FLAG ${f.lines} line(s) set in ${f.family}${f.standFor ? `, standing in for ${f.standFor} (the font file is missing: ask for it)` : ", not one of the brand's faces (meta.checks.fonts)"}`);+ const zp = (x) => Math.round(x * 100), a = r.auto;+ if (passing) out(` EDGE: ${passing} line(s) or box(es) crossed the edge while moving (a pan or a camera travel, not held there): not a fault`);+ out(` READING-TIME: ${rd.status}${rd.reason ? ` ${rd.reason}` : ` ${rd.checked} cue(s) (${a.cues.length} drawn, the rest meta.captions), each at least max(0.7 s, 0.3 s per word)`}${a.texture ? `; ${a.texture} texture block(s) skipped` : ""}${a.skipped.partial ? `; ${a.skipped.partial} cut off by the range` : ""}${a.skipped.seen ? `; ${a.skipped.seen} return(s) of text already read` : ""}${a.skipped.exit ? `; ${a.skipped.exit} exit step(s)` : ""}`);+ if (a.cues.length) out(` READING-FLOOR: text needs at least ${r.floor.floorS.toFixed(1)} s of the film's ${(r.meta.durationFrames / r.meta.fps).toFixed(1)} s; text stays up ${r.floor.spareS.toFixed(1)} s beyond its reading time in all (cut length from there, or from moves, never from reading)`);+ out(` SAFE-ZONES: ${zn.status === "FAIL" && warnZones ? "FLAG" : zn.status}${zn.status === "N/A" ? ` ${zn.reason}` : ` ${zn.hits.length ? `${zn.hits.length} text(s) inside` : "no text in"} the top ${zp(SAFE_ZONES.top)}%, bottom ${zp(SAFE_ZONES.bottom)}% or right ${zp(SAFE_ZONES.right)}% of the frame`}`);+ out(` LAYOUT: ${r.layout.length ? `FAIL ${r.layout.length} finding(s)` : "PASS density, gaps, stacks, overlaps"}; LAST SECOND ${r.endSize.length ? "FAIL" : "PASS"}; END CARD ${r.endCard.runs.length ? (r.endCard.ok ? "PASS (lands once)" : "FAIL") : "none reported"}; HEADS ${r.heads.length ? (r.heads.every((g) => g.ok) ? "PASS" : "FAIL") : "none reported"}`);+ const nz = zn.hits?.length ?? 0, readFail = rd.status === "FAIL" ? Math.max(1, rd.bad.length) : 0;+ const fails = cuts.length + readFail + (warnZones ? 0 : nz) + r.layout.length + r.endSize.length + (r.endCard.ok ? 0 : 1) + r.heads.filter((g) => !g.ok).length;+ out(fails ? `FRAMECHECK: FAIL ${fails} problem(s): ${cuts.length} cut by the frame's edge, ${readFail} reading time, ${warnZones ? 0 : nz} in a phone safe zone, ${r.layout.length} layout, ${r.endSize.length} too small at the end` : `FRAMECHECK: PASS no text or box cut by the edge; reading time ${rd.status}; layout clean; safe zones ${nz ? `FLAGGED (${nz} text(s))` : zn.status}`);+ return { lines, fails };+};+if (isMain(import.meta.url)) {const pos = [], opt = {};for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }const film = requireFilm(pos[0], "framecheck", USAGE), warnZones = opt.zones === "warn";if (opt.zones !== undefined && !["fail", "warn"].includes(opt.zones)) { console.error(`framecheck: --zones is fail or warn, got '${opt.zones}'\nusage: ${USAGE}`); process.exit(2); }- const r = await frameCheck(film, { every: Number(opt.every ?? 1), from: Number(opt.from ?? 0), to: opt.to === undefined ? undefined : Number(opt.to) });- const list = (fs) => `${fs.slice(0, 8).join(", ")}${fs.length > 8 ? " ..." : ""}`;- const groups = new Map(); for (const b of r.bad) { const k = `${b.kind} "${b.label.slice(0, 48)}"`; const g = groups.get(k) ?? []; g.push(b.frame); groups.set(k, g); }- console.log(`FRAMECHECK ${film} ${r.meta.W}x${r.meta.H}, ${r.frames} frames`);- for (const [k, fs] of groups) { const b = r.bad.find((x) => `${x.kind} "${x.label.slice(0, 48)}"` === k); console.log(` FAIL ${k} cut by the frame's edge on ${fs.length} frame(s): ${list(fs)} box ${[b.x0, b.y0, b.x1, b.y1].map((v) => Math.round(v)).join(",")}`); }- const rd = r.reading, zn = r.zones;- for (const b of rd.bad) console.log(` FAIL text "${b.text.slice(0, 48)}" is up ${b.seconds} s from frame ${b.from}; reading it takes ${b.need} s`);- for (const h of zn.hits ?? []) console.log(` ${warnZones ? "FLAG" : "FAIL"} text "${h.label.slice(0, 48)}" sits in the ${h.zone} on ${h.frames.length} frame(s): ${list(h.frames)}`);- const zp = (x) => Math.round(x * 100);- console.log(` READING-TIME: ${rd.status}${rd.status === "N/A" ? ` ${rd.reason}` : ` ${rd.checked} cue(s), each at least max(0.7 s, 0.3 s per word)`}`);- console.log(` SAFE-ZONES: ${zn.status === "FAIL" && warnZones ? "FLAG" : zn.status}${zn.status === "N/A" ? ` ${zn.reason}` : ` ${zn.hits.length ? `${zn.hits.length} text(s) inside` : "no text in"} the top ${zp(SAFE_ZONES.top)}%, bottom ${zp(SAFE_ZONES.bottom)}% or right ${zp(SAFE_ZONES.right)}% of the frame`}`);- const nz = zn.hits?.length ?? 0, fails = groups.size + rd.bad.length + (warnZones ? 0 : nz);- console.log(fails ? `FRAMECHECK: FAIL ${fails} problem(s): ${groups.size} cut by the frame's edge, ${rd.bad.length} read too briefly, ${warnZones ? 0 : nz} in a phone safe zone` : `FRAMECHECK: PASS no text or content box cut by the frame's edge; reading time ${rd.status}; safe zones ${nz ? `FLAGGED (${nz} text(s))` : zn.status}`);- process.exit(fails ? 1 : 0);+ let r; try { r = await frameCheck(film, { every: Number(opt.every ?? 1), from: Number(opt.from ?? 0), to: opt.to === undefined ? undefined : Number(opt.to) }); }+ catch (e) { if (!/^framecheck: --/.test(e.message)) throw e; console.error(`${e.message}\nusage: ${USAGE}`); process.exit(2); }+ const rep = frameReport(film, r, { warnZones });+ console.log(rep.lines.join("\n"));+ if (opt.json) writeFileSync(resolve(opt.json), JSON.stringify({ ...r, bad: r.bad.slice(0, 200) }, null, 1));+ process.exit(rep.fails ? 1 : 0);}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/framerules.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/framerules.mjsnew file mode 100644index 0000000..4a193a8--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/framerules.mjs@@ -0,0 +1,276 @@+// FRAME RULES. What framecheck judges on the text and boxes a film draws, as pure functions (records in,+// findings out, no browser) so every rule is unit-tested with a case that must fail.+// Records come from the frame probe (hosts/page.ts): { kind: "text"|"box", label, frame, x0, y0, x1, y1 }+// in device pixels, text also with { alpha, px, family, texture } and cut: false when wholly in frame.+// They exist because a brand launch film passed every check while its viewers said the text+// was too fast, its end card was a crowded corner and its CTA was 14 px tall. Each rule below names+// the note it answers.+import { readingNeed, readingTime, wordCount } from "./textrules.mjs";++export const RULES = {+ gapShare: 0.03, // C4: two things closer than 3 % of the frame's short side read as touching ("circles way too close")+ maxBlocks: 7, // C2: more than 7 separate text blocks on one frame is a wall of text (the ledger said 6; a+ // product-UI beat, header + bubbles + placeholder + button, is 7 and was never the complaint)+ clusterMin: 5, // C2: 5 or more blocks ...+ clusterShare: 0.3, // ... packed into under 30 % of the frame is "an insane amount of text in a small spot"+ stackMin: 5, // C1: 5 or more blocks centred on one axis is the centred stack the director rejected+ stackTol: 0.015, // centres within 1.5 % of the width count as one axis+ overlapShare: 0.2, // T9: two text blocks sharing 20 % of the smaller one collide+ endPx: 28, // T10: text in the last second smaller than 28 px at 1080 is unreadable on a phone+ endWindowS: 1,+ headSpread: 0.1, // C5: people shown as one sequence differ in head height by at most 10 %+ persistS: 0.5, // a layout finding counts when it holds this long (a passing move is not a layout)+ flashFrames: 3, // a text replaced in place within 3 frames at 30 fps (0.1 s, scaled to the film's rate) is an animation step (a counter), not a read+};+const CURSOR = /[\s|▍▌▎█_]+$/u;++const inter = (a, b) => Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0)) * Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0));+const area = (a) => Math.max(0, a.x1 - a.x0) * Math.max(0, a.y1 - a.y0);+const contains = (a, b, tol = 1) => b.x0 >= a.x0 - tol && b.y0 >= a.y0 - tol && b.x1 <= a.x1 + tol && b.y1 <= a.y1 + tol;+const centreIn = (r, b) => { const cx = (r.x0 + r.x1) / 2, cy = (r.y0 + r.y1) / 2; return cx >= b.x0 && cx <= b.x1 && cy >= b.y0 && cy <= b.y1; };+const union = (list) => list.reduce((u, r) => ({ x0: Math.min(u.x0, r.x0), y0: Math.min(u.y0, r.y0), x1: Math.max(u.x1, r.x1), y1: Math.max(u.y1, r.y1) }), { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity });+/** Edge-to-edge distance of two rectangles (0 when they touch or overlap). */+export const rectGap = (a, b) => { const dx = Math.max(0, a.x0 - b.x1, b.x0 - a.x1), dy = Math.max(0, a.y0 - b.y1, b.y0 - a.y1); return Math.hypot(dx, dy); };+const lineH = (r) => (r.px > 0 ? r.px : Math.max(1, r.y1 - r.y0));++/**+ * The text blocks of ONE frame: lines of text (single glyphs, words or whole lines, however the film+ * drew them) joined into the blocks a viewer reads as one thing. A probeRect text box with real glyphs+ * inside it gives way to the glyphs (they show what is actually drawn); one with none (writeOn draws+ * strokes) stands for its words. -> [{ key, words, x0, y0, x1, y1, px, texture, family }]+ */+export const blocksOf = (recs) => {+ const fill = recs.filter((r) => r.kind === "text" && r.px !== undefined), probes = recs.filter((r) => r.kind === "text" && r.px === undefined);+ const T = [...fill, ...probes.filter((p) => !fill.some((f) => centreIn(f, p)))];+ const parent = T.map((_, i) => i), find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));+ const sameLine = (a, b) => { const h = Math.min(lineH(a), lineH(b)), vo = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0); return vo > 0.4 * Math.min(a.y1 - a.y0, b.y1 - b.y0) && Math.max(a.x0 - b.x1, b.x0 - a.x1) < 1.0 * h; };+ const stacked = (a, b) => { const h = Math.min(lineH(a), lineH(b)); return Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0) > 0 && Math.max(a.y0 - b.y1, b.y0 - a.y1) < 0.75 * h; };+ for (let i = 0; i < T.length; i++) for (let j = i + 1; j < T.length; j++) if (sameLine(T[i], T[j]) || stacked(T[i], T[j])) parent[find(i)] = find(j);+ const groups = new Map(); T.forEach((r, i) => { const k = find(i); (groups.get(k) ?? groups.set(k, []).get(k)).push(r); });+ return [...groups.values()].map((g) => {+ // lines: by vertical overlap, top to bottom; inside a line left to right, a space where the ink gap is a word gap+ const lines = []; for (const r of [...g].sort((a, b) => a.y0 - b.y0)) { const l = lines.find((L) => Math.min(L.y1, r.y1) - Math.max(L.y0, r.y0) > 0.4 * Math.min(L.y1 - L.y0, r.y1 - r.y0)); if (l) { l.rs.push(r); l.y0 = Math.min(l.y0, r.y0); l.y1 = Math.max(l.y1, r.y1); } else lines.push({ y0: r.y0, y1: r.y1, rs: [r] }); }+ lines.sort((a, b) => a.y0 - b.y0);+ const key = lines.map((L) => { const rs = L.rs.sort((a, b) => a.x0 - b.x0); let s = ""; rs.forEach((r, i) => { const lbl = String(r.label).trim(); if (i && (r.x0 - rs[i - 1].x1 > 0.18 * lineH(r) || r.label.startsWith(" ") || rs[i - 1].label.endsWith(" "))) s += " "; s += lbl; }); return s; }).join(" ").replace(CURSOR, "").trim();+ const fam = new Map(); for (const r of g) if (r.family) fam.set(r.family, (fam.get(r.family) ?? 0) + 1);+ return { key, words: wordCount(key), ...union(g), px: Math.max(...g.map(lineH)), texture: g.every((r) => r.texture), family: [...fam.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? "" };+ });+};++/** Records grouped by frame, only what the viewer can see: in frame, not cut, alpha 0.1 and over. */+export const framesOf = (recs, frames) => {+ const m = new Map(frames.map((f) => [f, []]));+ for (const r of recs) if (r.cut === false && (r.alpha ?? 1) >= 0.1) m.get(r.frame)?.push(r);+ return m;+};++/**+ * READING TIME FROM WHAT IS DRAWN (T2). Every block of text the film shows becomes a cue, timed from the+ * first frame it is complete to the last frame it is up. Text still being typed or built (the next frame+ * shows a longer text containing it, in the same place) is not a cue yet: the read starts after the last+ * character, so a typed reply needs typing time PLUS reading time (T3). A text replaced in place within+ * RULES.flashFrames frames is an animation step (a count-up), not a read. What is left of a longer text as it+ * leaves (words sinking last-first) is an exit step, not a read. Texture text (texture()) is+ * words not meant to be read (S13). A cue cut off by the checked range is partial and not judged.+ * frames: the checked frame numbers, ascending. -> { cues, skipped: { typing, flash, partial }, texture, blocks }+ */+// what a sinking line leaves behind its clip, glyph by glyph: short letters drop out first, so "And"+// leaves "A d". True when each remnant piece is letters of one word of the longer text, in order, the+// pieces in the words' order ("A d" from "And it shows"); a new word that only shares letters ("dish")+// is not.+export const glyphsOf = (k, longer) => {+ if (longer.replace(/\s+/g, "").length <= k.replace(/\s+/g, "").length) return false; // fewer letters than were there+ const words = longer.split(/\s+/).filter(Boolean); let w = 0, c = 0;+ const inWord = (t, word, from) => { let i = from; for (const ch of t) { i = word.indexOf(ch, i); if (i < 0) return -1; i++; } return i; };+ for (const t of k.split(/\s+/).filter(Boolean)) {+ let at = -1; while (w < words.length && (at = inWord(t, words[w], c)) < 0) { w++; c = 0; }+ if (w >= words.length) return false; c = at;+ }+ return true;+};+export const autoCues = (byFrame, frames, { first = 0, last = Infinity, fps = 30 } = {}) => {+ const step = frames.length > 1 ? frames[1] - frames[0] : 1, B = new Map(frames.map((f) => [f, blocksOf(byFrame.get(f) ?? [])]));+ const cues = [], skipped = { typing: 0, flash: 0, partial: 0 }, open = new Map(); let texture = 0, blocks = 0;+ const close = (run, next) => {+ const nb = next === undefined ? [] : (B.get(next) ?? []).filter((b) => !b.texture), near = (b) => inter(b, run.box) > 0 || rectGap(b, run.box) < run.px;+ if (nb.some((b) => b.key.length > run.key.length && b.key.includes(run.key) && near(b))) { skipped.typing++; return; } // typed on, or joined by the next line of its block+ if (run.exiting) { skipped.exit = (skipped.exit ?? 0) + 1; return; }+ const span = run.last - run.first + step;+ // (flashFrames is 0.1 s at 30 fps: at 60 fps a counter's digit is up 6 frames, and was timed as a read)+ if (span <= RULES.flashFrames * Math.max(1, fps / 30) * step && nb.some((b) => b.key !== run.key && near(b))) { skipped.flash++; return; }+ if ((run.first === frames[0] && frames[0] > first) || (next === undefined && run.last === frames[frames.length - 1] && run.last + step < last)) { skipped.partial++; return; }+ cues.push({ from: run.first, to: run.last + step, text: run.key, box: run.box });+ };+ frames.forEach((f, i) => {+ const bs = B.get(f), seen = new Set();+ for (const b of bs) {+ blocks++; if (b.texture) { texture++; continue; } if (!b.key) continue;+ const k = b.key; if (seen.has(k)) continue; seen.add(k);+ const r = open.get(k);+ if (r && r.last === frames[i - 1]) { r.last = f; r.box = b; r.px = b.px; } else {+ if (r) close(r, frames[frames.indexOf(r.last) + 1]);+ // what is left of a longer text in the same place as it leaves (words sinking last-first) is an exit, not a new read+ const prev = i ? (B.get(frames[i - 1]) ?? []) : [], exiting = prev.some((p) => ((p.key.length > k.length && p.key.includes(k)) || glyphsOf(k, p.key)) && (inter(p, b) > 0 || rectGap(p, b) < b.px));+ open.set(k, { key: k, first: f, last: f, box: b, px: b.px, exiting });+ }+ }+ for (const [k, r] of open) if (!seen.has(k) && r.last === frames[i - 1]) { close(r, f); open.delete(k); }+ });+ for (const r of open.values()) close(r, undefined);+ // the same words gone for at most two checked frames and back (a sent message leaving the input for its+ // bubble, a cut between two framings of one card) are one read, not two+ cues.sort((a, b) => a.from - b.from);+ const joined = [];+ for (const c of cues) { const p = joined.findLast((q) => q.text === c.text); if (p && c.from - p.to <= 2 * step) p.to = Math.max(p.to, c.to); else joined.push({ ...c }); }+ // a text read once in full is not read again: when it comes back later (the chat's header in the next+ // shot, a placeholder after each send) a short return is not a reading fault+ const read = new Set(), out = [];+ for (const c of joined) { if (read.has(c.text)) { skipped.seen = (skipped.seen ?? 0) + 1; continue; } out.push(c); if (c.to - c.from >= Math.ceil(readingNeed(c.text) * fps - 1e-9)) read.add(c.text); }+ return { cues: out, skipped, texture, blocks };+};++/** The reading-time verdict on drawn text plus any declared captions. Never N/A while text is drawn. */+export const readingVerdict = (auto, captions, fps, framesChecked) => {+ const r = readingTime([...auto.cues, ...(Array.isArray(captions) ? captions : [])], fps);+ if (!framesChecked) return { ...r, status: "FAIL", reason: "no frame was checked: an empty run proves nothing" };+ if (r.status === "N/A") return auto.blocks ? { ...r, status: "FAIL", reason: `text was drawn (${auto.blocks} block(s)) but no cue could be timed: ${JSON.stringify(auto.skipped)}` } : { ...r, status: "NONE", reason: `no text was drawn on any of the ${framesChecked} frames checked` };+ return r;+};++/**+ * THE READING FLOOR (D2). The seconds the film cannot lose without cutting into reading time: the union+ * of every cue's [start, start + need]. Spare = how long text stays up beyond its need, summed: the only+ * place a cut for length may come from without making the text too fast.+ */+export const readingFloor = (cues, fps) => {+ const iv = cues.map((c) => [c.from, c.from + Math.ceil(readingNeed(c.text) * fps)]).sort((a, b) => a[0] - b[0]);+ let total = 0, end = -Infinity; for (const [a, b] of iv) { if (a > end) { total += b - a; end = b; } else if (b > end) { total += b - end; end = b; } }+ const spare = cues.reduce((s, c) => s + Math.max(0, c.to - c.from - Math.ceil(readingNeed(c.text) * fps)), 0);+ return { floorS: total / fps, spareS: spare / fps };+};++const exempt = (f, ranges) => (ranges ?? []).some(([a, b]) => f >= a && f < b);+/** Findings that hold at least RULES.persistS: [{ id, msg }] per frame -> [{ msg, from, to }] runs. */+const persist = (perFrame, frames, fps) => {+ const step = frames.length > 1 ? frames[1] - frames[0] : 1, need = Math.max(1, Math.round((RULES.persistS * fps) / step)), runs = new Map(), out = [];+ frames.forEach((f, i) => { for (const { id, msg } of perFrame.get(f) ?? []) { const r = runs.get(id); if (r && r.last === frames[i - 1]) { r.last = f; r.n++; } else { if (r && r.n >= need) out.push({ msg: r.msg, from: r.first, to: r.last + step }); runs.set(id, { msg, first: f, last: f, n: 1 }); } } });+ for (const r of runs.values()) if (r.n >= need) out.push({ msg: r.msg, from: r.first, to: r.last + step });+ // a run interrupted and resumed is reported once per stretch; collapse identical messages+ return out.sort((a, b) => a.from - b.from);+};++/**+ * LAYOUT (C1, C2, C4, T9). On every checked frame: too many text blocks, blocks packed into a corner, a+ * centred stack, two things nearly touching, text over the edge of a content box, text over text.+ * A finding counts when it holds RULES.persistS. meta.checks.layoutExempt [from, to, reason] ranges are+ * not judged (a deliberate wall of words, a gag that collides on purpose).+ * -> [{ rule, msg, from, to }]+ */+export const layoutFindings = (byFrame, frames, { W, H, fps, exemptRanges } = {}) => {+ const per = new Map();+ for (const f of frames) {+ if (exempt(f, exemptRanges)) continue;+ const recs = byFrame.get(f) ?? [], bl = blocksOf(recs).filter((b) => !b.texture && b.key), boxes = recs.filter((r) => r.kind === "box"), list = [];+ if (bl.length > RULES.maxBlocks) list.push({ id: "density", msg: `density: ${bl.length} text blocks on one frame (at most ${RULES.maxBlocks})` });+ if (bl.length >= RULES.clusterMin) { const u = union(bl), share = area(u) / (W * H); if (share < RULES.clusterShare) list.push({ id: "cluster", msg: `density: ${bl.length} text blocks packed into ${Math.round(share * 100)}% of the frame (spread them over at least ${RULES.clusterShare * 100}%)` }); }+ if (bl.length >= RULES.stackMin) { const cx = bl.map((b) => (b.x0 + b.x1) / 2).sort((a, b) => a - b), med = cx[cx.length >> 1], on = cx.filter((c) => Math.abs(c - med) <= RULES.stackTol * W).length; if (on >= RULES.stackMin) list.push({ id: "stack", msg: `centred stack: ${on} text blocks centred on one axis (compose an asymmetric grid: references/workflows/launch-video.md, end card)` }); }+ // collisions are judged on the lines themselves: two overlapping lines would otherwise merge into one block+ const lines = recs.filter((r) => r.kind === "text" && !r.texture && String(r.label).trim().length > 1);+ for (let i = 0; i < lines.length; i++) for (let j = i + 1; j < lines.length; j++) { const a = lines[i], b = lines[j]; if (a.label !== b.label && inter(a, b) > RULES.overlapShare * Math.min(area(a), area(b))) list.push({ id: `tt:${a.label}|${b.label}`, msg: `text over text: "${String(a.label).slice(0, 32)}" and "${String(b.label).slice(0, 32)}" overlap` }); }+ const items = [...bl.map((b) => ({ ...b, label: b.key, isText: true })), ...boxes.map((b) => ({ ...b, isText: false }))], floor = RULES.gapShare * Math.min(W, H); // of the short side: on 9:16 the height is not what the eye measures a gap against+ for (let i = 0; i < items.length; i++) for (let j = i + 1; j < items.length; j++) {+ const a = items[i], b = items[j]; if (a.label === b.label) continue;+ const ia = inter(a, b), q = (s) => `"${String(s).slice(0, 32)}"`;+ if (a.isText && b.isText) continue;+ if (ia > 0) { if (a.isText !== b.isText && !contains(a.isText ? b : a, a.isText ? a : b) && !contains(a.isText ? a : b, a.isText ? b : a)) list.push({ id: `edge:${a.label}|${b.label}`, msg: `text over an edge: ${q(a.isText ? a.label : b.label)} crosses the edge of ${q(a.isText ? b.label : a.label)}` }); continue; }+ const d = rectGap(a, b); if (d > 0 && d < floor) list.push({ id: `gap:${a.label}|${b.label}`, msg: `gap: ${q(a.label)} sits ${Math.round(d)} px from ${q(b.label)} (at least ${Math.round(floor)} px, ${RULES.gapShare * 100}% of the short side)` });+ }+ per.set(f, list);+ }+ return persist(per, frames, fps).map((x) => ({ rule: x.msg.split(":")[0], ...x }));+};++/** T10: text in the last second smaller than RULES.endPx at 1080. scale = device px per film px. */+export const endSizeFindings = (byFrame, frames, { W, H, fps, durationFrames, scale = 1 }) => {+ const from = durationFrames - Math.round(RULES.endWindowS * fps), small = new Map();+ for (const f of frames) if (f >= from) for (const b of blocksOf(byFrame.get(f) ?? [])) {+ if (b.texture || !b.key) continue; const at1080 = (b.px / scale) * (1080 / Math.min(W, H));+ if (at1080 < RULES.endPx) small.set(b.key, Math.min(small.get(b.key) ?? Infinity, at1080));+ }+ return [...small].map(([text, px]) => ({ text, px: Math.round(px), msg: `"${text.slice(0, 40)}" is ${Math.round(px)} px at 1080 in the last ${RULES.endWindowS} s (at least ${RULES.endPx}): grow it, or keep the card full size under the stinger` }));+};++export const END_CARD = "end card";+/** S9/C1: the end card lands once. Boxes labelled "end card" (endCard.ts probes it) seen in more than one run is card, something else, card. */+export const endCardRuns = (byFrame, frames) => {+ const runs = []; let on = false;+ for (const f of frames) { const vis = (byFrame.get(f) ?? []).some((r) => r.kind === "box" && r.label === END_CARD); if (vis && !on) runs.push([f, f]); if (vis) runs[runs.length - 1][1] = f; on = vis; }+ return { runs, ok: runs.length <= 1, msg: runs.length > 1 ? `the end card lands ${runs.length} times (${runs.map(([a, b]) => `${a}-${b}`).join(", ")}): one landing only, end on the card or on the stinger, never card-stinger-card` : "" };+};++/** C5: heads in one sequence match. Boxes labelled "head:<group>/<name>" (people.ts); each person's settled (largest) head height per group. */+export const headSpread = (byFrame, frames) => {+ const best = new Map();+ for (const f of frames) for (const r of byFrame.get(f) ?? []) { if (r.kind !== "box" || !String(r.label).startsWith("head:")) continue; const h = r.y1 - r.y0; if (h > (best.get(r.label) ?? 0)) best.set(r.label, h); }+ const groups = new Map(); for (const [label, h] of best) { const [g, name] = label.slice(5).split("/"); (groups.get(g) ?? groups.set(g, []).get(g)).push({ name: name ?? g, h: Math.round(h) }); }+ return [...groups].map(([group, people]) => { const hs = people.map((p) => p.h), spread = Math.min(...hs) > 0 ? (Math.max(...hs) - Math.min(...hs)) / Math.min(...hs) : 0; return { group, people, spread, ok: people.length < 2 || spread <= RULES.headSpread }; });+};++/** T8: which font families set the text, and the lines in a declared stand-in or outside the brand's faces. */+export const fontReport = (byFrame, frames, { fonts, standIns } = {}) => {+ const fam = new Map(); for (const f of frames) for (const r of byFrame.get(f) ?? []) if (r.kind === "text" && r.family && !r.texture) { const e = fam.get(r.family) ?? { family: r.family, lines: new Set() }; e.lines.add(r.label); fam.set(r.family, e); }+ const brand = new Set((fonts ?? []).map((s) => s.toLowerCase())), stand = Object.fromEntries(Object.entries(standIns ?? {}).map(([want, used]) => [String(used).toLowerCase(), want]));+ return [...fam.values()].map((e) => { const k = e.family.toLowerCase(), standFor = stand[k]; return { family: e.family, lines: e.lines.size, standFor, offBrand: brand.size > 0 && !brand.has(k) && !standFor }; });+};++/**+ * CUT BY THE EDGE, held (T7, M11). A line or box the frame's edge cuts through is a fault when it SITS+ * there: a sliced line left at the top edge for 196 frames, a name that overflows. Text sliding across+ * the edge while the camera travels in one world is a pan, not a fault. So a cut counts once the same+ * label is cut, unmoved (under half a pixel), on 3 checked frames in a row.+ * bad: the probe's cut records. -> [{ kind, label, frames, box, held }] with held = the longest still run.+ */+export const edgeCuts = (bad, frames, minHeld = 3) => {+ const idx = new Map(frames.map((f, i) => [f, i])), groups = new Map();+ for (const b of bad) { const k = `${b.kind}\u0000${b.label}`; (groups.get(k) ?? groups.set(k, []).get(k)).push(b); }+ const gap = (a, b) => Math.abs(a.x0 - b.x0) + Math.abs(a.y0 - b.y0) + Math.abs(a.x1 - b.x1) + Math.abs(a.y1 - b.y1);+ const out = [];+ for (const list of groups.values()) {+ // One label can be drawn more than once on a frame (two "Learn more" buttons, setType's fill per+ // character). Each record is followed as its own track: matched to the nearest record of the same+ // label on the checked frame before, nearest pairs first. Grouping by label alone compared the two+ // copies with each other, so a cut held for 6 frames read as never held.+ list.sort((a, b) => a.frame - b.frame);+ const byFrame = new Map(); for (const b of list) (byFrame.get(b.frame) ?? byFrame.set(b.frame, []).get(b.frame)).push(b);+ let live = [], prevIdx = null, held = 1, heldBox = list[0];+ for (const [f, recs] of byFrame) {+ const i = idx.get(f), cand = i !== undefined && prevIdx !== null && i === prevIdx + 1 ? live : [];+ const pairs = []; recs.forEach((r, ri) => cand.forEach((t, ti) => pairs.push([gap(r, t.last), ri, ti]))); pairs.sort((a, b) => a[0] - b[0]);+ const usedR = new Set(), usedT = new Set(), next = [];+ for (const [d, ri, ti] of pairs) {+ if (usedR.has(ri) || usedT.has(ti)) continue; usedR.add(ri); usedT.add(ti);+ const run = d < 0.5 ? cand[ti].run + 1 : 1; next.push({ last: recs[ri], run }); if (run > held) { held = run; heldBox = recs[ri]; }+ }+ recs.forEach((r, ri) => { if (!usedR.has(ri)) next.push({ last: r, run: 1 }); });+ live = next; prevIdx = i ?? null;+ }+ out.push({ kind: list[0].kind, label: list[0].label, frames: [...byFrame.keys()], box: [heldBox.x0, heldBox.y0, heldBox.x1, heldBox.y1], held, fail: held >= minHeld });+ }+ return out;+};++/**+ * THE FRAMES A CHECK LOOKS AT (framecheck, layerscan, ship): from `from` up to `to` (default: the whole film)+ * every `every` frames. A bad value is refused with the flag named, never quietly bent: --every abc used to+ * check frame 0 alone and print PASS, --every 0 looped until memory ran out, and a --from past the end+ * checked nothing and passed. Zero frames checked is refused too: an empty run proves nothing.+ */+export const checkedFrames = ({ every = 1, from = 0, to } = {}, N) => {+ const int = (v) => typeof v === "number" && Number.isInteger(v);+ if (!int(every) || every < 1) throw new Error(`--every wants a whole number of frames, 1 or more; got '${every}'`);+ if (!int(from) || from < 0 || from >= N) throw new Error(`--from wants a frame from 0 to ${N - 1}; got '${from}'`);+ const end = to === undefined ? N : to;+ if (!int(end) || end <= from) throw new Error(`--to wants a frame after --from (${from}); got '${to}'`);+ const out = []; for (let f = from; f < Math.min(end, N); f += every) out.push(f);+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjsindex d8f1149..03a9633 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/gate.mjs@@ -7,16 +7,27 @@// different orders. Byte-identical, or PSNR above 45 dB.// 2 CONTRACT a static scan of every module the film draws through.// 3 DEAD AIR no identical consecutive frames, no half-second window under 0.5 % changed per 1/30 s.+// 5 3D CHECKS 3D films only: three-core/checks3d.ts on sampled frames plus every frame of a+// grip's contact window. Any finding (a prop through a hand, rigs clipping) fails, and+// so does a 3D film that registers nothing to check (unless meta.checks.none["3d"] says why).+// A film made before a check existed (a frozen source of a published film) may declare a dead-air row,+// meta.checks.none["gate:identical"] or ["gate:still"], with its reason: listed with the reason, never counted.//// The gate NEVER writes to out/. It renders into .tmp/gate/ and it only ever READS the MP4 it is// pointed at, so running it can never damage a finished film.import { execFileSync, spawnSync } from "node:child_process";import { createHash } from "node:crypto";import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";-import { resolve } from "node:path";+import { join, resolve } from "node:path";+import { ROOTS } from "./overlay.mjs";+import { trackProvenance } from "./sidecar.mjs";import { readdirSync } from "node:fs";import { defaultOutput, requireFilm } from "./names.mjs";import { changedArea } from "./motion.mjs";+import { pathToFileURL } from "node:url";+import { glArgs } from "./adapters/playwright.mjs";+import { detect } from "./detect.mjs";+import { deadAirVerdict, threeDVerdict } from "./gaterules.mjs";const VAL = new Set(["adapter", "mp4", "samples", "scale", "workers"]);const pos = [], opt = {};@@ -64,7 +75,8 @@ const walk = (dir, out = []) => { for (const e of execFileSync("find", [dir, "-nconst contractScan = () => {head(2, "CONTRACT the art core cannot reach a clock, the network or a file");// the worked example is part of the same tree at build time (tools/overlay.mjs): scan it too- const files = [...walk("src/canvas-core"), ...(existsSync("../example/src/canvas-core") ? walk("../example/src/canvas-core") : []), `src/hosts/page-${film}.ts`].filter((f) => existsSync(f));+ // a linked project (scaffold --linked) draws through the engine's modules too: scan the whole tree the build sees+ const files = [...new Set(ROOTS.flatMap((r) => ["canvas-core", "three-core"].map((d) => join(r, d))).filter((d) => existsSync(d)).flatMap((d) => walk(d)))].concat(existsSync(`src/hosts/page-${film}.ts`) ? [`src/hosts/page-${film}.ts`] : []);const hits = [];for (const f of files) { const src = stripComments(readFileSync(f, "utf8")); FORBIDDEN.forEach(([re, label]) => { const m = src.match(new RegExp(re.source, "g")); if (m) hits.push(`${f}: ${label} x${m.length}`); }); }say(hits.length === 0, `no forbidden call in ${files.length} art-core modules`, hits.length ? hits.slice(0, 6).join(" | ") : "Math.random, Date, performance.now, ctx.filter, network, image/font loads: none");@@ -88,12 +100,44 @@ const deadAir = async (mp4, meta) => {const merged = []; win.forEach((f) => { const l = merged[merged.length - 1]; if (l && f <= l[1]) l[1] = f + windowSize; else merged.push([f, f + windowSize]); });for (const [from, to, reason] of meta.locked ?? []) console.log(` LOCKED ${from}-${to}: ${reason}; violations remain failures`);for (const [from, to, reason] of meta.holds ?? []) if (reason) console.log(` HOLD ${from}-${to}: ${reason}`);- say(still.length === 0, "no unexplained identical consecutive frames", still.length ? still.slice(0, 20).join(", ") : "none");- say(merged.length === 0, `no ${windowSize}-frame window under ${meta.kind === "drawing" ? "0.02" : "0.5"}% changed`, merged.map(([a, b]) => `${a}-${b}`).join(", ") || "none");+ // (a frozen film made before these checks may declare a row in meta.checks.none: listed with its reason, never counted as a pass)+ const row = (key, ok, label, detail) => { const v = deadAirVerdict(key, ok, detail, meta); if (v.counted) say(v.ok, label, v.detail); else note(`${label} (not judged)`, v.detail); };+ row("gate:identical", still.length === 0, "no unexplained identical consecutive frames", still.length ? still.slice(0, 20).join(", ") : "none");+ row("gate:still", merged.length === 0, `no ${windowSize}-frame window under ${meta.kind === "drawing" ? "0.02" : "0.5"}% changed`, merged.map(([a, b]) => `${a}-${b}`).join(", ") || "none");const mvt = changed.slice(1).sort((a, b) => a - b);console.log(` ${n} frames measured; median ${((mvt[mvt.length >> 1] ?? 0) * 100).toFixed(2)}% min ${((mvt[0] ?? 0) * 100).toFixed(2)}%`);};+// ---------------------------------------------------------------- 5. 3D checks, inside the page+// The film's own draws run three-core/checks3d.ts (runChecks) when a collector listens; the page+// returns every finding (hosts/page.ts FILM.checks3d). The pass mounts at a quarter scale: the checks+// read geometry and the camera, never pixels, so the frame size changes nothing they see and the+// WebGL draw costs a sixteenth. Lessons 37 and 48: a green gate with a prop through a hand is a failed gate.+const CHECK_SCALE = 0.25, CHECK_SAMPLES = 48;+const checks3d = async (pagePath, meta) => {+ head(5, "3D CHECKS grips held, nothing through anything (three-core/checks3d)");+ if (!readFileSync(pagePath, "utf8").includes("__ANIDOODLE_WEBGL__")) { note("a 2D film", "3D checks not applicable"); return; }+ const env = detect(), N = meta.durationFrames;+ const browser = await env.pw.lib.chromium.launch({ executablePath: env.browser.executablePath, args: ["--disable-background-timer-throttling", ...glArgs(pagePath)] });+ try {+ const page = await (await browser.newContext({ viewport: { width: 640, height: 640 } })).newPage(), errors = [];+ page.on("pageerror", (e) => errors.push(e.message));+ await page.goto(pathToFileURL(pagePath).href + "?adapter=gate-3d");+ await page.evaluate(async (s) => { await window.FILM.ready; window.FILM.mount(s); }, CHECK_SCALE);+ const ask = async (frames) => { const out = []; for (let i = 0; i < frames.length; i += 24) out.push(...(await page.evaluate((fs) => window.FILM.checks3d(fs), frames.slice(i, i + 24)))); return out; };+ // pass 1: every Nth frame. pass 2: every frame between two samples where either one holds a grip+ // (a contact window), because a hand can pass through a handle for three frames between samples+ const step = Math.max(1, Math.ceil(N / CHECK_SAMPLES)), sampled = [...new Set([...Array.from({ length: Math.ceil(N / step) }, (_, i) => i * step), N - 1])];+ const recs = await ask(sampled), byFrame = new Map(recs.map((r) => [r.frame, r]));+ const fill = []; for (let i = 0; i + 1 < sampled.length; i++) { const a = byFrame.get(sampled[i]), b = byFrame.get(sampled[i + 1]); if (a?.grips.length || b?.grips.length) for (let f = sampled[i] + 1; f < sampled[i + 1]; f++) fill.push(f); }+ recs.push(...(await ask(fill)));+ if (errors.length) { say(false, "the 3D check pass drew without errors", errors.slice(0, 3).join("; ")); return; }+ // nothing registered is a check that could not look: FAIL, unless the film declares why (gaterules.mjs)+ const v = threeDVerdict({ recs, sampled: sampled.length, fill: fill.length, meta });+ if (v.counted) say(v.ok, v.label, v.detail); else note(v.label, v.detail);+ } finally { await browser.close(); }+};+// ---------------------------------------------------------------- 1. determinism, two ways roundconst psnr = (a, b) => {const r = spawnSync("ffmpeg", ["-v", "error", "-i", a, "-i", b, "-lavfi", "psnr=stats_file=-", "-f", "null", "-"], { encoding: "utf8" });@@ -176,6 +220,15 @@ const run = async () => {console.log(` ${art.path} (${(art.bytes / 1024).toFixed(0)} KB, ${art.kind})`);art.checks.forEach((c) => say(c.ok, c.label, c.detail));}+ // EXTERNAL MUSIC (meta.checks.music.track). "Any score is synthesized in the page" holds for the page; a+ // film whose music is a supplied or generated track is mixed outside it (track.mjs), so the gate holds+ // the delivered file to the take its manifest pins instead of waving it through (X3).+ if (meta.checks?.music?.track) {+ head("4b", "EXTERNAL TRACK the music in the file is the pinned take");+ const mp4 = resolve(opt.mp4 ?? defaultOutput(film)), pv = trackProvenance(resolve(meta.checks.music.track), mp4);+ say(pv.ok, "the delivered mix comes from the take its manifest pins", pv.detail);+ }+ await checks3d(resolve(`dist/${film}.html`), meta);console.log(`\n${"=".repeat(58)}`);console.log(fails ? `GATE: FAIL ${fails} of ${checks} checks failed` : `GATE: PASS ${checks}/${checks} checks, ${nFiles} modules scanned`);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/gaterules.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/gaterules.mjsnew file mode 100644index 0000000..cecbd05--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/gaterules.mjs@@ -0,0 +1,43 @@+// GATE RULES. The decisions gate.mjs makes that can be made without a browser, as pure functions, so each+// is unit-tested with a case that must fail (test/gaterules.test.ts).++/**+ * CHECK 5, 3D: what the page's runChecks returned on the frames asked. A 3D film with no frame that registers+ * anything to check (no grip, no rig) did not look: that FAILS, unless the film declares why there is+ * nothing to check in meta.checks.none["3d"] (a turntable with no characters and nothing held). It used to+ * print a note, count nothing, and let the gate say PASS without one 3D check having run.+ * -> { counted, ok, label, detail }: counted false is a listed note with the film's reason.+ */+export const threeDVerdict = ({ recs, sampled, fill, meta }) => {+ if (!recs.length) {+ const why = meta?.checks?.none?.["3d"];+ if (typeof why === "string" && why.trim()) return { counted: false, ok: true, label: `no frame registers anything to check (${sampled} sampled)`, detail: `declared in meta.checks.none["3d"]: ${why.trim()}` };+ return { counted: true, ok: false, label: `a 3D film with no frame registering anything to check (${sampled} sampled): the 3D checks could not look`, detail: 'register its characters and held props (three-core/checks3d.ts runChecks, registerGrip), or declare meta.checks.none["3d"] = "<reason>" when there is truly nothing to check' };+ }+ const findings = recs.flatMap((r) => r.findings), withGrip = recs.filter((r) => r.grips.length).length;+ return { counted: true, ok: findings.length === 0, label: `${recs.length} frames checked (${sampled} sampled + ${fill} in grip windows), ${withGrip} with a grip`, detail: findings.length ? `${findings.length} finding(s): ` + findings.slice(0, 6).map((x) => `${x.frame} ${x.kind} ${x.where}: ${x.detail}`).join(" | ") : "no finding" };+};++/**+ * The findings that belong to one grip (still.mjs --grips labels each crop with them). A grip is named+ * "<holder>/<prop>"; checkGrip's findings say "<holder> holding <prop>" and its proximity finding+ * "<holder> / <prop> at ...". Every crop used to carry every grip finding on the frame.+ */+export const gripFindings = (grip, findings) => {+ const name = String(grip.name), heads = [];+ for (let i = name.indexOf("/"); i >= 0; i = name.indexOf("/", i + 1)) { const h = name.slice(0, i), p = name.slice(i + 1); heads.push(`${h} holding ${p}`, `${h} / ${p} `); }+ return findings.filter((x) => (x.kind.startsWith("grip") || x.kind === "proximity") && heads.some((h) => String(x.where).startsWith(h)));+};++/**+ * CHECK 3, DEAD AIR, one row ("gate:identical" identical consecutive frames, "gate:still" a still window).+ * A film made before the check existed (a frozen source of a published film, whose pace was approved)+ * may declare the row in meta.checks.none with its reason: the row is then listed with the reason and its+ * findings, and not counted. Undeclared, it is a PASS or a FAIL as it was.+ * -> { counted, ok, detail }+ */+export const deadAirVerdict = (key, ok, detail, meta) => {+ const why = meta?.checks?.none?.[key];+ if (!ok && typeof why === "string" && why.trim()) return { counted: false, ok: true, detail: `declared in meta.checks.none["${key}"]: ${why.trim()}; found: ${detail}` };+ return { counted: true, ok, detail };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/keys-compare.py b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-compare.pyindex 978e765..b5725c7 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/keys-compare.py+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-compare.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# Needs numpy (offline research tool, not used by renders): pip install numpy"""Spectral A/B of rendered piano notes vs the CC0 VCSL Steinway B (offline, numpy only).python3 tools/keys-compare.py <VCSL root> <probe dir> (probe dir holds old-<note>_vl<k>.wav / v2-<note>_vl<k>.wav)diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/keys-fit.py b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-fit.pyindex c2b7856..4080749 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/keys-fit.py+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-fit.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# Needs numpy (offline research tool, not used by renders): pip install numpy"""Offline "measured physics" fitter for the keys voices (piano, mallets, organ).python3 tools/keys-fit.py <VCSL root> [--json out.json]diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/keys-metrics.py b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-metrics.pyindex d4088a2..52b9d56 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/keys-metrics.py+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/keys-metrics.py@@ -1,4 +1,5 @@#!/usr/bin/env python3+# Needs numpy (offline research tool, not used by renders): pip install numpy"""Anti-MIDI metrics for the keys phrases (research sec. 9.2): per-band inter-channel correlation(< 0.9 above 500 Hz = real width; ~1 below 120 Hz = mono lows), click detector (sample steps far above thelocal signal), spectral flux in sustains (a static oscillator is ~flat). numpy only.diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/launch.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/launch.mjsindex 11003e2..a7ed65e 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/launch.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/launch.mjs@@ -51,8 +51,18 @@ export const ${n} = makeLaunchFilm({title: "TODO Product", // the exact product namesubtitle: "TODO the one line it lives by",placeholder: "Ask for anything…",+ // THE LOOK: your product's own, field by field (launch-video-kit.md, Looks). Uncomment what you need;+ // every field is optional and the base's value stands for the rest. launchExampleBrand.ts is a worked example.+ // look: {+ // base: "drawn", // a registered look: "drawn" or "clean" (or one you registerLook)+ // from: brandJson, // import brandJson from "../../brand/brand.json" (node tools/brand.mjs import): fills palette, logo+ // palette: { bg: "#rrggbb", card: "#rrggbb", ink: "#rrggbb", soft: "#rrggbb", mute: "#rrggbb", line: "#rrggbb", chip: "#rrggbb", accent: "#rrggbb", accentDeep: "#rrggbb", paper: "#rrggbb" }, // checked for contrast (WCAG AA)+ // fonts: { display: { family: "Your Serif", file: yourSerif }, text: { family: "Your Sans", file: yourSans } }, // import yourSans from "../../assets/fonts/YourSans.ttf" (a local .ttf, no network)+ // shape: { radius: 12, bubble: "rounded", composer: "box", button: "pill", buttonLabel: "Send" }, // bubble rounded|square|none, composer box|bar, button pill|square+ // chat: { header: true, title: "Product", subtitle: "its line", logo: undefined, bubble: { fill: "#rrggbb", ink: "#rrggbb" }, reply: { fill: "#rrggbb", ink: "#rrggbb" } },+ // },asks: [- { prompt: "TODO what a user types, in their words", plate: lighthouseDraw, label: "TODO the card's byline" },+ { prompt: "TODO what a user types", plate: lighthouseDraw, label: "TODO the card's byline" },{ prompt: "TODO the follow-up", plate: foxDraw, label: "TODO byline" },],words: [[{ text: "TODO CLAIM.", style: "ink", color: C.ink }, { text: "TODO PROOF.", style: "ink", color: C.accent }]],@@ -60,8 +70,18 @@ export const ${n} = makeLaunchFilm({install: ["TODO the exact install line"], // shown exactly as given, held 3 s or morefooter: "TODO where it lives",bpm: 90, // TODO the tempo of the score composed for this brief- askBeats: 6, typeBeats: 4, endBeats: 8, claimBar: 4,- score: null, // TODO the score composed for this product (references/music/compose.md)+ // THE DECLARATIONS ship reads (node tools/ship.mjs): a check with nothing declared cannot look, and+ // a check that cannot look fails. Fill each from the brief (launchExample.ts is a worked example).+ motion: {+ temperament: "calm", // TODO how the brand moves: "calm", "lively" or "snappy"+ brandColors: [C.accent], // TODO the brand's own colours, #rrggbb (no see-through fills in them; the drawn look's ink is its pen, not a brand colour unless yours is ink)+ },+ claims: [], // TODO every claim beyond the words and tagline (a real number on screen), each in facts.json+ checks: { length: { target: 30, max: 45 } }, // TODO the length budget in seconds: over max fails, over target flags+ // the review is yours: a fresh critic's findings go in reviews/${n}.json (references/workflows/review.md)+ askBeats: 6, typeBeats: 6, endBeats: 8, claimBar: 5,+ score: null, // TODO the score composed for this product (references/music/compose.md; launchExampleScore.ts is a worked example)+ sfx: false, // TODO true once the score is in: the sound cues ride the score, and alone they are clicks on silence (soundcheck fails their loudness)});`;const CLEAN = (n) => `// ${n}: a UI-first launch film on the template, in the clean preset (a quiet canvas, one accent,@@ -72,24 +92,54 @@ const CLEAN = (n) => `// ${n}: a UI-first launch film on the template, in the climport { makeLaunchFilm } from "./launchTemplate";import type { ProductUI } from "./productUI";+// (the stand-in is three plain rows on purpose, and the split beat shows it without its command bar: it renders+// and ships as it is. Your real screen will have more on it,+// its nav, its figures, its tags; a frame of it over 7 text blocks is dense, and framecheck says so: declare+// those beats in checks.layoutExempt below once you see them)const main: ProductUI = { // TODO your product's own UI, its before and after- title: "TODO", nav: ["TODO", "TODO"], action: "TODO action", command: "TODO Ask…",- before: { items: [{ id: "a", label: "TODO item", value: 3, tag: "TODO" }, { id: "b", label: "TODO item", value: 8 }] },- after: { items: [{ id: "b", label: "TODO item", value: 0, done: true, accent: true }, { id: "a", label: "TODO item", value: 0, done: true }] },+ title: "TODO", action: "TODO action",+ before: { items: [{ id: "a", label: "TODO first item", tag: "TODO" }, { id: "b", label: "TODO second item" }, { id: "c", label: "TODO third item" }] },+ after: { items: [{ id: "b", label: "TODO second item", done: true, accent: true }, { id: "a", label: "TODO first item", tag: "TODO", done: true }, { id: "c", label: "TODO third item", done: true }] },};export const ${n} = makeLaunchFilm({title: "TODO Product", preset: "clean", fps: 60,+ // THE LOOK: your product's own, field by field (launch-video-kit.md, Looks). Uncomment what you need;+ // every field is optional and the base's value stands for the rest. launchExampleBrand.ts is a worked example.+ // look: {+ // base: "clean", // a registered look (preset: "clean" above is its shorthand; keep one of the two)+ // from: brandJson, // import brandJson from "../../brand/brand.json" (node tools/brand.mjs import): fills palette, logo+ // palette: { bg: "#rrggbb", card: "#rrggbb", ink: "#rrggbb", soft: "#rrggbb", mute: "#rrggbb", line: "#rrggbb", chip: "#rrggbb", accent: "#rrggbb", accentDeep: "#rrggbb", paper: "#rrggbb" }, // checked for contrast (WCAG AA)+ // fonts: { display: { family: "Your Serif", file: yourSerif }, text: { family: "Your Sans", file: yourSans } }, // import yourSans from "../../assets/fonts/YourSans.ttf" (a local .ttf, no network)+ // shape: { radius: 12, bubble: "rounded", composer: "box", button: "pill", buttonLabel: "Send" }, // bubble rounded|square|none, composer box|bar, button pill|square+ // chat: { header: true, title: "Product", subtitle: "its line", logo: undefined, bubble: { fill: "#rrggbb", ink: "#rrggbb" }, reply: { fill: "#rrggbb", ink: "#rrggbb" } },+ // },asks: [- { kind: "ui", ui: main, prompt: "TODO what a user asks the product" },- { kind: "ui", ui: main, split: [{ text: "TODO the feature,", style: "ink", color: "#15161a" }, { text: "TODO in five words.", style: "ink", color: "#2f54eb" }] },+ { kind: "ui", ui: { ...main, command: "TODO Ask…" }, prompt: "TODO what a user asks the product" }, // the ask typed into its command bar+ { kind: "ui", ui: main, split: [{ text: "TODO the feature,", style: "ink", color: "#15161a" }, { text: "in five words.", style: "ink", color: "#2f54eb" }] }, // TODO the feature in about five words],words: [[{ text: "TODO CLAIM.", style: "ink", color: "#15161a" }]],tagline: "TODO one sentence that says what it is",install: ["TODO the exact install line"],footer: "TODO where it lives",- bpm: 90, askBeats: 6, typeBeats: 4, endBeats: 8, claimBar: 4,- score: null, // TODO the score composed for this product+ // THE DECLARATIONS ship reads (node tools/ship.mjs): a check with nothing declared cannot look, and+ // a check that cannot look fails. Fill each from the brief (launchExampleClean.ts is a worked example).+ motion: {+ temperament: "calm", // TODO how the brand moves: "calm", "lively" or "snappy"+ brandColors: ["#15161a", "#2f54eb"], // TODO the brand's own colours, #rrggbb (no see-through fills in them)+ },+ claims: [], // TODO every claim beyond the words and tagline (a real number on screen), each in facts.json+ checks: {+ length: { target: 30, max: 45 }, // TODO the length budget in seconds: over max fails, over target flags+ // a product screen dense with rows is the point of its beat, not a layout fault: once you see the beats,+ // declare each as [from, to, "why"] in film frames (ship's frame row names them; launchExampleClean.ts shows how)+ // layoutExempt: [[0, 330, "TODO the first ask shows the product's whole inbox: dense UI is the subject"]],+ },+ // the review is yours: a fresh critic's findings go in reviews/${n}.json (references/workflows/review.md)+ // (claimBar 6: the split beat's words need their reading time before the end card; the template says so if not)+ bpm: 90, askBeats: 6, typeBeats: 6, endBeats: 8, claimBar: 6,+ score: null, // TODO the score composed for this product (launchExampleCleanScore.ts is a worked example)+ sfx: false, // TODO true once the score is in: the sound cues ride the score, and alone they are clicks on silence (soundcheck fails their loudness)});`;diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/layerscan.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/layerscan.mjsnew file mode 100644index 0000000..68366b1--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/layerscan.mjs@@ -0,0 +1,75 @@+// node tools/layerscan.mjs <film> [--checks exits,fasttext,faces,translucent] [--every 1] [--from F] [--to T] [--json]+// LAYER SCAN. Watches what each frame DRAWS (hosts/instrument.ts: every line of text, every photo, every+// box the art reports, every fill in a brand colour) and fails the faults that pixels alone cannot pin+// on an element. Each one is a note from a brand launch film:+// exits a line of text leaves slivers behind at its clip edge for 0.2 s or more ("pixels are+// left for about half a second longer than they should... check each and every frame")+// fasttext type moving faster than half the speed ceiling: a whip that blurs ("violent exits")+// faces a moving shape drawn over a real person's face ("whack-a-mole", "swallowing the head")+// translucent a brand colour filled between 5 % and 95 % alpha ("olive mud"); needs meta.motion.brandColors+// Exceptions live in meta.motion.allow. Exit 0 pass, 1 fail, 2 usage. Detectors: motionscan-core.mjs.+import { resolve } from "node:path";+import { buildPage } from "./build-page.mjs";+import { detect } from "./detect.mjs";+import * as playwright from "./adapters/playwright.mjs";+import { requireFilm } from "./names.mjs";+import { isMain } from "./is-main.mjs";+import { checkedFrames } from "./framerules.mjs";+import { scanExits, scanFaceCover, scanFastText, scanTranslucent, textLines } from "./motionscan-core.mjs";++export const LAYER_CHECKS = ["exits", "fasttext", "faces", "translucent"];+const pad = (b, k = 0.45) => { const h = b.y1 - b.y0, w = b.x1 - b.x0; return { x0: b.x0 - w * 0.02, y0: b.y0 - h * k, x1: b.x1 + w * 0.02, y1: b.y1 + h * k }; };++export const layerScan = async (film, { checks = LAYER_CHECKS, every = 1, from = 0, to } = {}) => {+ const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film });+ const s = await playwright.open(detect(), page.out, { workers: 1 }), meta = await s.info(), motion = meta.motion ?? {}, allow = motion.allow ?? {};+ // a bad --every/--from/--to is refused (framerules.mjs checkedFrames): --every 0 looped forever, and zero frames checked passed+ let frames; try { frames = checkedFrames({ every, from, to }, meta.durationFrames); } catch (e) { await s.close(); throw new Error(`layerscan: ${e.message}`); }+ const N = Math.min(to ?? meta.durationFrames, meta.durationFrames);+ const layers = []; for (let i = 0; i < frames.length; i += 40) layers.push(...(await s.layers(frames.slice(i, i + 40), motion.brandColors ?? [])));+ const out = {};+ try {+ if (checks.includes("exits")) {+ // the ink each line shows over the last 2 s of its life, measured frame by frame (every frame, whatever --every says)+ const lines = textLines(layers), tailF = Math.round(2 * meta.fps), want = new Map();+ for (const [label, pts] of Object.entries(lines)) { const last = pts[pts.length - 1].frame, first = pts[0].frame; for (let f = Math.max(first, last - tailF); f <= Math.min(N - 1, last + every); f++) { const box = pts.filter((p) => p.frame <= f).pop() ?? pts[0]; (want.get(f) ?? want.set(f, []).get(f)).push({ label, box: pad(box) }); } }+ const series = {};+ // the box at each frame is the line's own box that frame when it was drawn, else its last one+ const detail = new Map(); for (const l of layers) detail.set(l.frame, l);+ for (const [f, items] of [...want].sort((a, b) => a[0] - b[0])) {+ const here = textLines(detail.has(f) ? [detail.get(f)] : (await s.layers([f], [])));+ const boxes = items.map((it) => (here[it.label] ? pad(here[it.label][0]) : it.box));+ const ink = await s.ink(f, boxes);+ items.forEach((it, i) => (series[it.label] ??= []).push({ frame: f, ink: here[it.label] ? ink[i] : 0 }));+ }+ const r = scanExits(series, { fps: meta.fps }); out.exits = { status: Object.keys(lines).length ? (r.fail ? "FAIL" : "PASS") : "NONE", lines: Object.keys(lines).length, ...r };+ if (!Object.keys(lines).length) out.exits.reason = "the film draws no lines of text: looked, none there";+ }+ if (checks.includes("fasttext")) { const r = scanFastText(layers, { W: meta.W, fps: meta.fps, scale: 1, step: every }); out.fasttext = { status: r.fail ? "FAIL" : "PASS", ...r }; }+ if (checks.includes("faces")) { const photos = layers.some((l) => l.recs.some((r) => r.kind === "photo")); const r = scanFaceCover(layers); out.faces = photos ? { status: r.fail ? "FAIL" : "PASS", ...r } : { status: "NONE", reason: "the film draws no photos (film assets): looked, none there", ...r }; }+ if (checks.includes("translucent")) { const r = scanTranslucent(layers, { allow: (allow.translucent ?? []).map(([a, b]) => [a, b]) }); out.translucent = layers[0]?.unread?.length ? { status: "FAIL", reason: `brand colour(s) ${layers[0].unread.join(", ")} in meta.motion.brandColors cannot be read: give #rrggbb, rgb() or hsl()`, ...r, findings: [], fail: true } : motion.brandColors?.length ? { status: r.fail ? "FAIL" : "PASS", ...r } : { status: "N/A", reason: "the film declares no brand colours (meta.motion.brandColors)", ...r }; }+ } finally { await s.close(); }+ return { film, meta, frames: frames.length, checks: out, fail: Object.values(out).some((c) => c.status === "FAIL") };+};++export const printLayers = (r) => {+ const c = r.checks, s = (f) => (f / r.meta.fps).toFixed(2), list = (fs) => `${fs.slice(0, 8).join(", ")}${fs.length > 8 ? " ..." : ""}`;+ console.log(`LAYERSCAN ${r.film} ${r.meta.W}x${r.meta.H}, ${r.frames} frames`);+ if (c.exits) { for (const e of c.exits.findings) console.log(` FAIL text "${e.label.slice(0, 48)}" leaves slivers for ${e.frames} frames (${e.seconds} s, frames ${e.from}-${e.to - 1}) as it exits: sink it with setType's out (ease-in, 1.3x its size) so it clears the clip`); console.log(` EXITS: ${c.exits.status}${c.exits.status === "NONE" ? ` ${c.exits.reason}` : ` ${c.exits.lines} line(s), residue limit ${c.exits.limit} frames`}`); }+ if (c.fasttext) { for (const t of c.fasttext.findings) console.log(` FAIL text "${t.label.slice(0, 48)}" moves at up to ${t.top} px a frame, frames ${t.from}-${t.to - 1} (${s(t.from)} s): type leaves over 0.5-0.7 s; the fast whip is for the camera`); console.log(` FAST-TEXT: ${c.fasttext.status} limit ${c.fasttext.cap} px a frame (half the speed ceiling)`); }+ if (c.faces) { for (const f of c.faces.findings) console.log(` FAIL "${f.shape}" moves across the face of "${f.photo}" on ${f.frames.length} frame(s): ${list(f.frames)}: a person enters and leaves with their stage; draw the shape behind them or move it with them`); console.log(` FACES: ${c.faces.status}${c.faces.status === "NONE" ? ` ${c.faces.reason}` : ""}`); }+ if (c.translucent) { if (c.translucent.status === "FAIL" && c.translucent.reason) console.log(` FAIL ${c.translucent.reason}`); for (const t of c.translucent.findings) console.log(` FAIL brand colour ${t.colour} filled at ${t.alphas.join(", ")} % alpha on ${t.frames.length} frame(s): ${list(t.frames)}: cut it in or out whole, or declare the fade in meta.motion.allow.translucent`); console.log(` TRANSLUCENT: ${c.translucent.status}${c.translucent.status === "N/A" || c.translucent.reason ? ` ${c.translucent.reason}` : ""}`); }+ console.log(`LAYERSCAN: ${r.fail ? "FAIL" : "PASS"}`);+};++if (isMain(import.meta.url)) {+ const pos = [], opt = {};+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a === "--json") opt.json = true; else if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }+ const usage = "node tools/layerscan.mjs <film> [--checks exits,fasttext,faces,translucent] [--every 1] [--from F] [--to T] [--json]";+ const film = requireFilm(pos[0], "layerscan", usage), checks = opt.checks ? String(opt.checks).split(",") : LAYER_CHECKS, bad = checks.filter((c) => !LAYER_CHECKS.includes(c));+ if (bad.length) { console.error(`layerscan: unknown check ${bad.join(", ")}; the checks are ${LAYER_CHECKS.join(", ")}\nusage: ${usage}`); process.exit(2); }+ let r; try { r = await layerScan(film, { checks, every: Number(opt.every ?? 1), from: Number(opt.from ?? 0), to: opt.to === undefined ? undefined : Number(opt.to) }); }+ catch (e) { if (!/^layerscan: --/.test(e.message)) throw e; console.error(`${e.message}\nusage: ${usage}`); process.exit(2); }+ if (opt.json) console.log(JSON.stringify(r, null, 1)); else printLayers(r);+ process.exit(r.fail ? 1 : 0);+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/lock.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/lock.mjsnew file mode 100644index 0000000..25c317a--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/lock.mjs@@ -0,0 +1,63 @@+// node tools/lock.mjs <film> --shot <id> print the approval sha of a shot (every frame hashed)+// node tools/lock.mjs <film> [--unlock a,b] check every approved shot (meta.motion.approved) still draws the same+// APPROVED SHOTS STAY APPROVED. On a brand launch film the logo shot the director approved ("the elements flying+// together, rotating. It was actually good") was replaced by a "better" idea while iterating, and had to+// be rebuilt exactly. Once a shot is approved its sha goes in the film:+// meta.motion.approved: [["logo", "<sha>", "director 2026-10-27 16:50"]]+// and any change to its frames fails here until it is unlocked on purpose (--unlock logo), which is the+// moment to ask the person again. The sha is over every frame's pixel hash, drawn sharp in the page.+// Exit 0 pass, 1 a locked shot changed (or is missing), 2 usage.+import { createHash } from "node:crypto";+import { resolve } from "node:path";+import { buildPage } from "./build-page.mjs";+import { detect } from "./detect.mjs";+import * as playwright from "./adapters/playwright.mjs";+import { requireFilm } from "./names.mjs";+import { isMain } from "./is-main.mjs";++/** The approval sha of each shot asked for: sha256 over the pixel hash of every frame, in order. */+export const shotShas = async (film, ids) => {+ const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film });+ const s = await playwright.open(detect(), page.out, { workers: 1, bakeCache: false }), meta = await s.info(), out = {};+ try {+ for (const id of ids) {+ const shot = meta.shots.find((x) => x.id === id); if (!shot) { out[id] = { missing: true, shots: meta.shots.map((x) => x.id) }; continue; }+ const h = createHash("sha256"); for (let f = shot.start; f < shot.end; f++) h.update(`${f - shot.start}:${await s.hash(f)}\n`);+ out[id] = { sha: h.digest("hex").slice(0, 16), frames: shot.end - shot.start };+ }+ } finally { await s.close(); }+ return { meta, shas: out };+};++/** Check every approved shot. Returns { checked: [{ shot, status: "same" | "changed" | "missing" | "unlocked", ... }], fail }. */+// `approved` overrides the film's own list (the self-test checks a live sha and a wrong one without editing a film)+export const checkLocks = async (film, { unlock = [], approved: given } = {}) => {+ let approved = given;+ if (!approved) { const page = await buildPage({ entry: `src/hosts/page-${film}.ts`, out: resolve(`dist/${film}.html`), title: film }); const s0 = await playwright.open(detect(), page.out, { workers: 1, bakeCache: false }); approved = (await s0.info()).motion?.approved ?? []; await s0.close(); }+ if (!approved.length) return { checked: [], fail: false, none: true };+ const { shas } = await shotShas(film, approved.map(([id]) => id)), checked = [];+ for (const [shot, sha, note] of approved) {+ const got = shas[shot];+ if (unlock.includes(shot)) checked.push({ shot, status: "unlocked", note, sha: got.sha });+ else if (got.missing) checked.push({ shot, status: "missing", note, shots: got.shots });+ else checked.push({ shot, status: got.sha === sha ? "same" : "changed", note, sha: got.sha, want: sha });+ }+ return { checked, fail: checked.some((c) => c.status === "changed" || c.status === "missing") };+};++if (isMain(import.meta.url)) {+ const pos = [], opt = {};+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }+ const usage = "node tools/lock.mjs <film> --shot <id> | node tools/lock.mjs <film> [--unlock a,b]";+ const film = requireFilm(pos[0], "lock", usage);+ if (opt.shot) {+ const { shas } = await shotShas(film, String(opt.shot).split(","));+ for (const [id, r] of Object.entries(shas)) { if (r.missing) { console.error(`lock: no shot "${id}"; this film's shots are ${r.shots.join(", ")}`); process.exit(2); } console.log(`${id}: ${r.sha} (${r.frames} frames)\n meta.motion.approved: [["${id}", "${r.sha}", "<who approved it, when>"]]`); }+ process.exit(0);+ }+ const r = await checkLocks(film, { unlock: opt.unlock ? String(opt.unlock).split(",") : [] });+ if (r.none) { console.log("LOCKS: N/A no approved shots (meta.motion.approved); lock one with --shot <id> once the person approves it"); process.exit(0); }+ for (const c of r.checked) console.log(` ${c.status === "same" ? "PASS" : c.status === "unlocked" ? "NOTE" : "FAIL"} ${c.shot} (${c.note}): ${c.status === "same" ? "unchanged" : c.status === "unlocked" ? `unlocked for this run, now ${c.sha}: show the person before re-approving` : c.status === "missing" ? `no such shot any more (shots: ${c.shots.join(", ")})` : `CHANGED (${c.sha}, approved ${c.want}): restore it, or ask the person and run with --unlock ${c.shot}`}`);+ console.log(`LOCKS: ${r.fail ? "FAIL" : "PASS"}`);+ process.exit(r.fail ? 1 : 0);+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/motionscan-core.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/motionscan-core.mjsnew file mode 100644index 0000000..29b4c4f--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/motionscan-core.mjs@@ -0,0 +1,318 @@+// MOTION SCAN DETECTORS. Pure: frames (or layer records) in, findings out, no I/O, so the unit tests+// feed them synthetic frames and the CLIs (motionscan.mjs, layerscan.mjs) feed them a real film.+// Each detector answers one note the director or a critic gave a brand launch film:+//+// scanSlideCuts "a LITERAL SLIDE DECK": most of the frame replaced within 6 frames with no camera move+// scanRepeats "moves like a carousel": three beats in a row settle into the same layout+// scanDissolves "olive mud" cross-dissolves: a region blends linearly from one picture to another+// speedProfile how fast the picture moves, frame by frame, for the brand's motion temperament+// scanTemperament stretches faster than the temperament allows ("violent")+// scanExits text that leaves pixels behind ("pixels left for about half a second")+// scanFastText type moving faster than half the speed ceiling (reads as a blurred whip)+// scanFaceCover a moving shape drawn over a real person's face ("whack-a-mole", "swallowing the head")+// scanTranslucent brand colours drawn half-transparent+//+// Frames are greyscale Uint8Arrays of width*height (motion.mjs greyFrames decodes them small).++const median = (xs) => { if (!xs.length) return 0; const s = [...xs].sort((a, b) => a - b); return s[s.length >> 1]; };++// ---------------------------------------------------------------- motion between two frames+/**+ * Block matching between two small grey frames. Returns the 98th-percentile displacement of the+ * coherent textured blocks (analysis px per frame pair), and `matched`: the share of textured blocks+ * that found their content somewhere nearby. A camera move: high matched, real speed. A cut or a slide+ * reset: low matched. A dissolve or a still: matched at speed 0.+ */+export const motionBetween = (A, Z, W, H, { B = 8, R = 8, subpixel = false } = {}) => {+ const vec = new Map(), frac = new Map(), cols = Math.floor((W - 2 * R - B) / B) + 1; let textured = 0, matched = 0;+ for (let by = R, row = 0; by + B + R <= H; by += B, row++) for (let bx = R, col = 0; bx + B + R <= W; bx += B, col++) {+ let mean = 0, v = 0; for (let y = 0; y < B; y++) for (let x = 0; x < B; x++) mean += A[(by + y) * W + bx + x]; mean /= B * B;+ for (let y = 0; y < B; y++) for (let x = 0; x < B; x++) v += (A[(by + y) * W + bx + x] - mean) ** 2;+ if (v / (B * B) < 12) continue; // flat: no motion can be read off it+ textured++;+ let best = Infinity, mx = 0, my = 0, md = Infinity; const cost = new Float64Array((2 * R + 1) ** 2);+ for (let dy = -R; dy <= R; dy++) for (let dx = -R; dx <= R; dx++) { let sad = 0; for (let y = 0; y < B; y++) for (let x = 0; x < B; x++) sad += Math.abs(A[(by + y) * W + bx + x] - Z[(by + y + dy) * W + bx + x + dx]); cost[(dy + R) * (2 * R + 1) + dx + R] = sad; if (sad < best) best = sad; }+ if (best / (B * B) > 6) continue; // its content went nowhere nearby: changed, not moved+ matched++;+ for (let dy = -R; dy <= R; dy++) for (let dx = -R; dx <= R; dx++) { const c = cost[(dy + R) * (2 * R + 1) + dx + R], d = Math.hypot(dx, dy); if (c <= best * 1.1 + B * B * 0.5 && d < md) { md = d; mx = dx; my = dy; } }+ // a match on content that was already there, unchanged, is not a move: the block was covered (a reveal+ // edge, a bloom's rim) and its look-alike beside it stood still. Text beside text matched a few letters+ // over and read as the fastest thing in the frame (a launch film's end bloom, 51 px a frame).+ if (mx || my) { let still = 0; for (let y = 0; y < B; y++) for (let x = 0; x < B; x++) { const i = (by + y + my) * W + bx + x + mx; still += Math.abs(A[i] - Z[i]); } if (still / (B * B) <= 6) continue; }+ vec.set(row * cols + col, [mx, my]);+ // asked for (`subpixel`, the speed profile), the move between whole pixels: a parabola through the block's+ // cost at its best whole shift and its two neighbours on each axis, about the cheapest shift found. One+ // analysis pixel is 8 to 15 px of the film, and word lines carried at 1.4 pixels a frame read 1 or 2 by+ // turns (and 2 failed a calm brand on a phone frame). Neighbour agreement still uses the whole shifts+ if (subpixel) {+ // (about the shift the block was given, the nearest of the near-best: on a repeating texture the cheapest+ // shift can be a period away, and a parabola there would measure the pattern, not the move)+ const bx0 = mx, by0 = my, at = (dx, dy) => cost[(dy + R) * (2 * R + 1) + dx + R], c0 = at(bx0, by0);+ const sub = (ea, e0, eb) => { const d = ea - 2 * e0 + eb; return d > 1e-9 ? Math.max(-0.5, Math.min(0.5, (ea - eb) / (2 * d))) : 0; };+ const fx = bx0 > -R && bx0 < R ? sub(at(bx0 - 1, by0), c0, at(bx0 + 1, by0)) : 0, fy = by0 > -R && by0 < R ? sub(at(bx0, by0 - 1), c0, at(bx0, by0 + 1)) : 0;+ frac.set(row * cols + col, Math.hypot(bx0 + fx, by0 + fy));+ }+ }+ const disp = [];+ for (const [key, [x, y]] of vec) { const r = Math.floor(key / cols), c = key % cols; let agree = 0; for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) { if (!dr && !dc) continue; const nb = vec.get((r + dr) * cols + c + dc); if (nb && c + dc >= 0 && c + dc < cols && Math.hypot(nb[0] - x, nb[1] - y) <= 1.5) agree++; } if (agree >= 2) disp.push(subpixel ? frac.get(key) : Math.hypot(x, y)); }+ disp.sort((a, b) => a - b);+ return { speed: disp.length ? disp[Math.min(disp.length - 1, Math.floor(disp.length * 0.98))] : 0, matched: textured ? matched / textured : 1, textured };+};++// ---------------------------------------------------------------- the camera's own move+const down = (f, W, H, k) => { const w = Math.floor(W / k), h = Math.floor(H / k), o = new Float32Array(w * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { let s = 0; for (let yy = 0; yy < k; yy++) for (let xx = 0; xx < k; xx++) s += f[(y * k + yy) * W + x * k + xx]; o[y * w + x] = s / (k * k); } return { o, w, h }; };+// mean absolute difference of A against Z seen through a zoom s about the centre and a shift (dx, dy), over the overlap+const warpErr = (A, Z, w, h, s, dx, dy) => { let e = 0, n = 0; const cx = w / 2, cy = h / 2; for (let y = 1; y < h - 1; y += 1) for (let x = 1; x < w - 1; x += 1) { const u = Math.round(cx + (x - cx) * s + dx), v = Math.round(cy + (y - cy) * s + dy); if (u < 0 || v < 0 || u >= w || v >= h) continue; e += Math.abs(A[y * w + x] - Z[v * w + u]); n++; } return n > (w * h) / 4 ? e / n : Infinity; };+/**+ * The camera's move between two frames as ONE zoom and shift for the whole picture (coarse to fine, up+ * to a third of the frame per step). `explained`: how much of the difference that move accounts for+ * (1 - err / err at rest). A pan, a push-in or a pull-out explains most of it; a cut or a swapped slide+ * explains none, whatever the texture: flat cards on a flat ground still move as one.+ */+export const globalMotion = (A, Z, W, H, { between = false, subpixel = false } = {}) => {+ const k = Math.max(1, Math.floor(W / 48)), a = down(A, W, H, k), z = down(Z, W, H, k), R = Math.ceil(a.w / 6);+ const e0 = warpErr(a.o, z.o, a.w, a.h, 1, 0, 0);+ let best = { e: e0, s: 1, dx: 0, dy: 0 };+ for (const sc of [1, 0.94, 0.97, 1.03, 1.06]) for (let dy = -R; dy <= R; dy++) for (let dx = -R; dx <= R; dx++) { const e = warpErr(a.o, z.o, a.w, a.h, sc, dx, dy); if (e < best.e - 1e-9) best = { e, s: sc, dx, dy }; }+ // refine the shift at full size within one coarse cell: a 3 px pan must read as 3, not as a whole cell+ const f0 = Float32Array.from(A), f1 = Float32Array.from(Z); let fine = { e: warpErr(f0, f1, W, H, best.s, best.dx * k, best.dy * k), dx: best.dx * k, dy: best.dy * k };+ for (let dy = -k; dy <= k; dy++) for (let dx = -k; dx <= k; dx++) { const e = warpErr(f0, f1, W, H, best.s, best.dx * k + dx, best.dy * k + dy); if (e < fine.e - 1e-9) fine = { e, dx: best.dx * k + dx, dy: best.dy * k + dy }; }+ // and, asked for (`between`), the zooms between the coarse steps, at full size and sub-pixel shifts: a camera+ // leaning in at about 1 % a frame matched neither 1 nor 1.03, so its push-in explained under half the+ // change and read as a slide cut (a clean chat's lean onto its answer card, thin type on a sparse frame,+ // where a shift off by half a pixel misses every stroke). Slide cuts ask for it on the few frames they judge.+ let sc = best.s;+ if (between) {+ // (both frames softened by a 3 x 3 box first: a stroke one pixel wide resampled half a pixel over is a+ // different set of pixels, and the fit would judge the sampling, not the move)+ const soft = (F) => { const o = new Float32Array(W * H); for (let y = 1; y < H - 1; y++) for (let x = 1; x < W - 1; x++) { let t = 0; for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) t += F[(y + j) * W + x + i]; o[y * W + x] = t / 9; } return o; };+ const s0 = soft(f0), s1 = soft(f1);+ const lin = (F, x, y) => { const x0 = Math.floor(x), y0 = Math.floor(y), fx = x - x0, fy = y - y0, i = y0 * W + x0; return (1 - fy) * ((1 - fx) * F[i] + fx * F[i + 1]) + fy * ((1 - fx) * F[i + W] + fx * F[i + W + 1]); };+ const err = (s2, dx, dy) => { let e = 0, n = 0; const cx = W / 2, cy = H / 2; for (let y = 3; y < H - 3; y++) for (let x = 3; x < W - 3; x++) { const u = cx + (x - cx) * s2 + dx, v = cy + (y - cy) * s2 + dy; if (u < 2 || v < 2 || u >= W - 3 || v >= H - 3) continue; e += Math.abs(s0[y * W + x] - lin(s1, u, v)); n++; } return n > (W * H) / 4 ? e / n : Infinity; };+ const rest2 = err(1, 0, 0);+ let b2 = { e: err(best.s, fine.dx, fine.dy), s: best.s, dx: fine.dx, dy: fine.dy };+ for (let ds = -0.02; ds <= 0.0201; ds += 0.0025) for (let dy = -1.5; dy <= 1.5; dy += 0.25) for (let dx = -1.5; dx <= 1.5; dx += 0.25) { const e = err(best.s + ds, fine.dx + dx, fine.dy + dy); if (e < b2.e - 1e-9) b2 = { e, s: best.s + ds, dx: fine.dx + dx, dy: fine.dy + dy }; }+ // judged on the softened frames, so both errors are: the share of the change the move explains+ // (its speed is the fastest point of the frame, a corner, under the zoom and the shift together: a lean that+ // pans as it zooms moves its corners by both, and neither alone says how far the picture moved)+ const corner = Math.max(...[[0, 0], [W, 0], [0, H], [W, H]].map(([x, y]) => Math.hypot((b2.s - 1) * (x - W / 2) + b2.dx, (b2.s - 1) * (y - H / 2) + b2.dy)));+ if (rest2 > 0 && 1 - b2.e / rest2 > 1 - fine.e / warpErr(f0, f1, W, H, 1, 0, 0)) return { speed: corner, explained: Math.max(0, 1 - b2.e / rest2), dx: b2.dx, dy: b2.dy, scale: +b2.s.toFixed(4), err: b2.e, rest: warpErr(f0, f1, W, H, 1, 0, 0) };+ }+ // the shift between whole pixels: a parabola through the error at the best whole shift and its two+ // neighbours, on each axis. One analysis pixel is 8 to 15 px of the film, and a travel at 1.46 pixels a frame+ // read as 1 or 2 by turns: its 2s failed a calm brand's limit on a phone frame, which the move never reached.+ // The speed profile asks for it (`subpixel`); slide cuts keep whole pixels, their "it moved" floor is one+ const sub = (ea, e0, eb) => { const d = ea - 2 * e0 + eb; return d > 1e-9 ? Math.max(-0.5, Math.min(0.5, (ea - eb) / (2 * d))) : 0; };+ const ox = subpixel ? sub(warpErr(f0, f1, W, H, sc, fine.dx - 1, fine.dy), fine.e, warpErr(f0, f1, W, H, sc, fine.dx + 1, fine.dy)) : 0;+ const oy = subpixel ? sub(warpErr(f0, f1, W, H, sc, fine.dx, fine.dy - 1), fine.e, warpErr(f0, f1, W, H, sc, fine.dx, fine.dy + 1)) : 0;+ const rest = warpErr(f0, f1, W, H, 1, 0, 0), shift = Math.hypot(fine.dx + ox, fine.dy + oy), zoom = Math.abs(sc - 1) * W / 2;+ return { speed: Math.max(shift, zoom), explained: rest > 0.05 ? Math.max(0, 1 - fine.e / rest) : 0, dx: fine.dx, dy: fine.dy, scale: sc, err: fine.e, rest };+};++const changedShare = (a, b, thresh) => { let n = 0; for (let i = 0; i < a.length; i++) if (Math.abs(a[i] - b[i]) > thresh) n++; return n / a.length; };+// the ground: the most common grey level (a dark or a paper background), read off a 32-level histogram+const groundOf = (f) => { const h = new Uint32Array(32); for (let i = 0; i < f.length; i += 3) h[f[i] >> 3]++; let b = 0; for (let k = 1; k < 32; k++) if (h[k] > h[b]) b = k; return b * 8 + 4; };+/**+ * Of the pixels that hold CONTENT in either frame (not the plain ground), the share that changed. A deck+ * on a dark ground keeps most pixels dark from slide to slide; what it replaces is the content.+ */+export const contentReplaced = (a, b, thresh = 16) => {+ const ga = groundOf(a), gb = groundOf(b); let content = 0, changed = 0;+ for (let i = 0; i < a.length; i++) { if (Math.abs(a[i] - ga) <= 12 && Math.abs(b[i] - gb) <= 12) continue; content++; if (Math.abs(a[i] - b[i]) > thresh) changed++; }+ return content < a.length * 0.01 ? 0 : changed / content;+};++// ---------------------------------------------------------------- slide cuts+/**+ * A slide cut: more than `replaced` of the frame's CONTENT pixels (contentReplaced: the plain ground+ * does not count) change within `win` frames while the camera is not travelling (the content did not+ * move there, it was swapped). Fades count: a dissolve between two layouts is the same deck transition, slower. Fails when any 60 s stretch holds more than+ * `perMinute` (2) of them. `allow`: [from, to] frame ranges that are deliberate (a hard cut on a beat).+ */+export const scanSlideCuts = (frames, { width: W, height: H, fps, win = 6, replaced = 0.6, thresh = 16, perMinute = 2, allow = [] } = {}) => {+ const n = frames.length, rep = new Float64Array(n);+ for (let f = win; f < n; f++) rep[f] = contentReplaced(frames[f - win], frames[f], thresh);+ const events = [];+ for (let f = win; f < n; f++) {+ if (rep[f] < replaced) continue;+ let peak = f; while (f + 1 < n && rep[f + 1] >= replaced) { f++; if (rep[f] > rep[peak]) peak = f; }+ const a = Math.max(1, peak - win), pairs = [];+ for (let g = a; g <= peak; g++) pairs.push(globalMotion(frames[g - 1], frames[g], W, H, { between: true }));+ // the camera carried it: on the pairs where the picture changed, one zoom and shift explains most of the change+ // (a change spread so thin that no single step shows it is a slow drift or a fade: dissolve's business, not a cut)+ const changing = pairs.filter((p) => p.rest > 0.05), travel = !changing.length || (median(changing.map((p) => p.explained)) >= 0.5 && median(changing.map((p) => p.speed)) >= 1);+ if (travel || allow.some(([x, y]) => peak >= x && peak < y)) continue;+ events.push({ frame: peak, from: a, replaced: +rep[peak].toFixed(3), explained: +median(changing.map((p) => p.explained)).toFixed(2) });+ }+ const span = Math.round(60 * fps), dense = [];+ for (let i = 0; i < events.length; i++) { const inWin = events.filter((e) => e.frame >= events[i].frame && e.frame < events[i].frame + span); if (inWin.length > perMinute) { dense.push(inWin.map((e) => e.frame)); } }+ return { events, fail: dense.length > 0, worst: dense.sort((a, b) => b.length - a.length)[0] ?? [], perMinute };+};++// ---------------------------------------------------------------- repeated layouts (the carousel)+const pool = (f, W, H, k) => { const w = Math.floor(W / k), h = Math.floor(H / k), o = new Float32Array(w * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { let s = 0; for (let yy = 0; yy < k; yy++) for (let xx = 0; xx < k; xx++) s += f[(y * k + yy) * W + x * k + xx]; o[y * w + x] = s / (k * k); } return { o, w, h }; };+/** Where a settled frame has content: a cols x rows grid of cells with edges in them (text, photos, shapes). */+export const layoutOf = (f, W, H, { cols = 32, rows = 18, edge = 10 } = {}) => {+ const occ = new Uint8Array(cols * rows), e = new Float64Array(cols * rows), cnt = new Uint32Array(cols * rows);+ for (let y = 1; y < H - 1; y++) for (let x = 1; x < W - 1; x++) { const g = Math.abs(f[y * W + x + 1] - f[y * W + x - 1]) + Math.abs(f[(y + 1) * W + x] - f[(y - 1) * W + x]); const c = Math.min(rows - 1, Math.floor((y * rows) / H)) * cols + Math.min(cols - 1, Math.floor((x * cols) / W)); e[c] += g; cnt[c]++; }+ for (let i = 0; i < occ.length; i++) occ[i] = cnt[i] && e[i] / cnt[i] > edge ? 1 : 0;+ return occ;+};+export const layoutIoU = (a, b) => { let i = 0, u = 0; for (let k = 0; k < a.length; k++) { if (a[k] && b[k]) i++; if (a[k] || b[k]) u++; } return u ? i / u : 1; };+/**+ * Beats that settle into the same layout with new content, three or more in a row: the template ran+ * again. A beat is a settled stretch (under `still` of the frame changing per frame, judged on a coarse+ * copy so a breathing camera still counts as settled) at least `hold` seconds long.+ */+export const scanRepeats = (frames, { width: W, height: H, fps, hold = 0.4, still = 0.01, same = 0.75, newContent = 0.05, run = 3 } = {}) => {+ const k = Math.max(1, Math.floor(W / 64)), small = frames.map((f) => pool(f, W, H, k)), sw = small[0]?.w ?? 0, sh = small[0]?.h ?? 0, minLen = Math.max(2, Math.round(hold * fps));+ const holds = []; let start = 0;+ const settledAt = (f) => { let n = 0; const a = small[f - 1].o, b = small[f].o; for (let i = 0; i < a.length; i++) if (Math.abs(a[i] - b[i]) > 6) n++; return n / a.length < still; };+ for (let f = 1; f <= frames.length; f++) { if (f < frames.length && settledAt(f)) continue; if (f - start >= minLen) holds.push([start, f]); start = f; }+ const beats = holds.map(([a, b]) => { const m = (a + b) >> 1; return { from: a, to: b, mid: m, layout: layoutOf(frames[m], W, H) }; });+ const links = []; // beat i and i+1 share a layout and show new content+ for (let i = 1; i < beats.length; i++) links.push(layoutIoU(beats[i - 1].layout, beats[i].layout) >= same && contentReplaced(frames[beats[i - 1].mid], frames[beats[i].mid]) >= newContent);+ const runs = []; let i = 0;+ while (i < links.length) { if (!links[i]) { i++; continue; } let j = i; while (j < links.length && links[j]) j++; if (j - i + 1 >= run) runs.push(beats.slice(i, j + 1).map((b) => [b.from, b.to])); i = j; }+ return { beats: beats.map(({ from, to }) => [from, to]), runs, fail: runs.length > 0, size: [sw, sh] };+};++// ---------------------------------------------------------------- dissolves+/**+ * A cross-dissolve or fade: inside a tile, frame t equals A + a(t) (B - A) for a rising a(t), over at+ * least `minFrames` frames, where A and B are the pictures before and after: pixels blending, nothing+ * moving. Findings are merged across tiles per stretch of frames, with `area` (share of the frame) and+ * `share` (of the tiles that changed at all in that stretch, how many blended). It FAILS when the blend+ * is how the stretch changes (share >= 0.5) over at least `minArea` of the frame: a dissolve seam, or a+ * card faded in instead of moved in (motion-grammar bans both). Small fades (a caption) are listed.+ */+export const scanDissolves = (frames, { width: W, height: H, grid = 8, minFrames = 6, minDelta = 10, fit = 0.25, minArea = 0.05, allow = [] } = {}) => {+ const n = frames.length, tiles = [];+ for (let ty = 0; ty < grid; ty++) for (let tx = 0; tx < grid; tx++) tiles.push([Math.floor((tx * W) / grid), Math.floor((ty * H) / grid), Math.floor(((tx + 1) * W) / grid), Math.floor(((ty + 1) * H) / grid)]);+ const tdiff = (a, b, [x0, y0, x1, y1]) => { let s = 0; for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) s += Math.abs(a[y * W + x] - b[y * W + x]); return s / ((x1 - x0) * (y1 - y0)); };+ const hits = [], diffs = [];+ tiles.forEach((t, ti) => {+ const d = new Float64Array(n); for (let f = 1; f < n; f++) d[f] = tdiff(frames[f - 1], frames[f], t); diffs.push(d);+ for (let f = 1; f < n; f++) {+ if (d[f] < 0.4) continue;+ const a = f; while (f + 1 < n && d[f + 1] >= 0.4) f++;+ const b = f; if (b - a + 1 < minFrames) continue;+ const A = frames[a - 1], Bf = frames[b], [x0, y0, x1, y1] = t;+ let dd = 0, cnt = 0; for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const q = Bf[y * W + x] - A[y * W + x]; dd += q * q; cnt++; }+ if (Math.sqrt(dd / cnt) < minDelta) continue;+ let ok = true, mid = 0, last = -Infinity;+ for (let g = a; g < b; g++) {+ let num = 0, res = 0; const F = frames[g];+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const i = y * W + x; num += (F[i] - A[i]) * (Bf[i] - A[i]); }+ const al = num / dd;+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const i = y * W + x, p = A[i] + al * (Bf[i] - A[i]); res += (F[i] - p) ** 2; }+ if (Math.sqrt(res / cnt) > fit * Math.sqrt(dd / cnt) || al < last - 0.05) { ok = false; break; }+ last = al; if (al > 0.1 && al < 0.9) mid++;+ }+ if (ok && mid >= Math.min(4, minFrames - 2)) hits.push({ tile: ti, from: a, to: b + 1 });+ }+ });+ // merge tiles whose stretches overlap into one finding per seam+ hits.sort((p, q) => p.from - q.from); const out = [];+ for (const h of hits) { const g = out.find((o) => h.from < o.to && h.to > o.from); if (g) { g.from = Math.min(g.from, h.from); g.to = Math.max(g.to, h.to); g.tiles.add(h.tile); } else out.push({ from: h.from, to: h.to, tiles: new Set([h.tile]) }); }+ const findings = out.map((o) => {+ let moving = 0; for (const d of diffs) { let any = false; for (let f = o.from; f < Math.min(n, o.to); f++) if (d[f] >= 0.4) { any = true; break; } if (any) moving++; }+ const area = +(o.tiles.size / tiles.length).toFixed(3), share = +(o.tiles.size / Math.max(1, moving)).toFixed(2);+ return { from: o.from, to: o.to, area, share, seam: area >= minArea && share >= 0.5, allowed: allow.some(([x, y]) => o.from < y && o.to > x) };+ });+ return { findings, fail: findings.some((f) => f.seam && !f.allowed), minArea };+};++// ---------------------------------------------------------------- speed and temperament+// the temperaments' top speeds as shares of speedCeiling, as motionKit.ts defines them (kept here so the+// tool needs no bundler); test/motionscan.test.ts holds the two equal+export const TEMPERAMENT_MAX = { calm: 0.35, lively: 0.55, snappy: 0.8 };+/** Per-frame on-screen speed in FULL-SIZE px per frame (scale = full width / analysis width). Frame 0 is 0. */+export const speedProfile = (frames, { width: W, height: H, scale = 1, R = 8 } = {}) => {+ const out = [0];+ for (let f = 1; f < frames.length; f++) { const g = globalMotion(frames[f - 1], frames[f], W, H, { subpixel: true }), cam = g.explained >= 0.5 ? g.speed : 0; out.push(Math.max(cam, motionBetween(frames[f - 1], frames[f], W, H, { R, subpixel: true }).speed) * scale); } // the camera's move, or the fastest coherent element+ return out;+};+/** Stretches of at least `min` frames moving faster than `maxPx` per frame: past the temperament ("violent"). */+export const scanTemperament = (speeds, { maxPx, min = 3 } = {}) => {+ const out = []; for (let f = 0; f < speeds.length; f++) { if (speeds[f] <= maxPx) continue; const a = f; let top = speeds[f]; while (f + 1 < speeds.length && speeds[f + 1] > maxPx) { f++; top = Math.max(top, speeds[f]); } if (f - a + 1 >= min) out.push({ from: a, to: f + 1, top: +top.toFixed(1) }); }+ return { stretches: out, fail: out.length > 0, maxPx };+};++// ---------------------------------------------------------------- layer-record detectors (layerscan)+const lineLabel = (r) => r.kind === "text" && (r.src === "probe" || r.label.trim().length > 1);+/**+ * Text that leaves pixels behind. `series`: per text line, [{ frame, ink }] (visible ink, px) over its+ * life. Its residue is the run at the END of its life where it shows ink but under `tail` (35 %) of its+ * peak: slivers of letters lingering at a clip edge. `max` seconds of that fails (0.2 s, 6 frames at 30+ * fps). An ease-in sink over 1.3x the size crosses that band in about 2 frames; the ease-out 1.0x sink+ * of a brand launch film sat in it for half its exit and left a fifth of the letters showing.+ */+export const scanExits = (series, { fps, tail = 0.35, max = 0.2 } = {}) => {+ const limit = Math.max(2, Math.round(max * fps)), out = [];+ for (const [label, pts] of Object.entries(series)) {+ const peak = Math.max(0, ...pts.map((p) => p.ink)); if (!peak) continue;+ let k = pts.length - 1; while (k >= 0 && pts[k].ink === 0) k--; // frames where it is drawn but fully clipped show nothing: not residue+ let n = 0; const end = k; while (k >= 0 && pts[k].ink > 0 && pts[k].ink <= tail * peak) { n++; k--; }+ if (n >= limit) out.push({ label, from: pts[k + 1].frame, to: pts[end].frame + 1, frames: n, seconds: +(n / fps).toFixed(2), peak, last: pts[end].ink });+ }+ return { findings: out, fail: out.length > 0, limit };+};+/** Each line of text's box per frame, keyed by label: { label: [{ frame, x0, y0, x1, y1 }] } (lines, not per-character fills). */+export const textLines = (layers) => { const out = {}; for (const { frame, recs } of layers) { const seen = new Set(); for (const r of recs) { if (!lineLabel(r) || seen.has(r.label)) continue; seen.add(r.label); (out[r.label] ??= []).push({ frame, x0: r.x0, y0: r.y0, x1: r.x1, y1: r.y1 }); } } return out; };+/**+ * Type moving faster than `ratio` x speedCeiling (2.5 frame widths a second) on consecutive checked frames:+ * a whip, not a read. `step`: the frames were sampled every `step` frames (layerscan --every), so two+ * checked frames `step` apart are neighbours and the move between them is shared over `step` frames.+ * Without it a sampled scan never saw two neighbours and could not fire.+ */+export const scanFastText = (layers, { W, fps, scale = 1, ratio = 0.5, min = 2, step = 1 } = {}) => {+ const cap = ((2.5 * W) / fps) * ratio * scale, lines = textLines(layers), out = [];+ for (const [label, pts] of Object.entries(lines)) {+ let run = [];+ const flush = () => { if (run.length >= min) out.push({ label, from: run[0].frame, to: run[run.length - 1].frame + 1, top: +Math.max(...run.map((r) => r.v)).toFixed(1) }); run = []; };+ for (let i = 1; i < pts.length; i++) {+ const a = pts[i - 1], b = pts[i]; if (b.frame !== a.frame + step) { flush(); continue; }+ const v = Math.hypot((b.x0 + b.x1 - a.x0 - a.x1) / 2, (b.y0 + b.y1 - a.y0 - a.y1) / 2) / step;+ if (v > cap) run.push({ frame: b.frame, v: v / scale }); else flush();+ }+ flush();+ }+ return { findings: out, fail: out.length > 0, cap: +(cap / scale).toFixed(1) };+};+const overlap = (a, b) => Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0)) * Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0));+/**+ * A real person's face covered by a moving shape. The face is the top `face` (30 %) of a photo's box+ * (cut-outs are framed head-first); a box drawn AFTER the photo that covers more than `min` of the+ * face, and moved against the photo since the frame before, is the "whack-a-mole" the critic named.+ * The person enters and leaves WITH their stage; nothing slides across them.+ */+export const scanFaceCover = (layers, { face = 0.3, min = 0.1 } = {}) => {+ const out = new Map(); let prev = null;+ for (const { frame, recs } of layers) {+ const photos = recs.filter((r) => r.kind === "photo"), boxes = recs.filter((r) => r.kind === "box");+ for (const p of photos) {+ const fb = { x0: p.x0, y0: p.y0, x1: p.x1, y1: p.y0 + (p.y1 - p.y0) * face }, area = (fb.x1 - fb.x0) * (fb.y1 - fb.y0); if (!(area > 0)) continue;+ for (const b of boxes) {+ if (b.order < p.order || overlap(fb, b) / area < min) continue;+ const pp = prev?.recs.find((r) => r.kind === "photo" && r.label === p.label), pb = prev?.recs.find((r) => r.kind === "box" && r.label === b.label);+ const moved = pp && pb ? Math.hypot((b.x0 - p.x0) - (pb.x0 - pp.x0), (b.y0 - p.y0) - (pb.y0 - pp.y0)) > 0.5 : false;+ if (!moved) continue;+ const k = `${p.label}|${b.label}`, e = out.get(k) ?? { photo: p.label, shape: b.label, frames: [] }; e.frames.push(frame); out.set(k, e);+ }+ }+ prev = { frame, recs };+ }+ const findings = [...out.values()];+ return { findings, fail: findings.length > 0 };+};+/** Frames where a brand colour was filled at a translucent alpha, outside the film's declared fades. */+export const scanTranslucent = (layers, { allow = [] } = {}) => {+ const out = new Map();+ for (const { frame, translucent } of layers) for (const t of translucent ?? []) { if (allow.some(([a, b]) => frame >= a && frame < b)) continue; const e = out.get(t.colour) ?? { colour: t.colour, frames: [], alphas: new Set() }; if (e.frames[e.frames.length - 1] !== frame) e.frames.push(frame); e.alphas.add(Math.round(t.alpha * 100)); out.set(t.colour, e); }+ const findings = [...out.values()].map((e) => ({ colour: e.colour, frames: e.frames, alphas: [...e.alphas].sort((a, b) => a - b) }));+ return { findings, fail: findings.length > 0 };+};++/** The file a motion scan reads: a path to any video file as given, else out/<film>.mp4 (a .mov or .m4v was rewritten to out/x.mov.mp4). */+export const scanTarget = (arg) => (/\.(mp4|mov|m4v|mkv|webm)$/i.test(String(arg)) ? String(arg) : `out/${arg}.mp4`);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/motionscan.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/motionscan.mjsnew file mode 100644index 0000000..6b8f2eb--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/motionscan.mjs@@ -0,0 +1,81 @@+// node tools/motionscan.mjs <film|path.mp4> [--checks slidecut,repeat,dissolve,temperament] [--temperament calm] [--json]+// MOTION SCAN. Reads the RENDERED film (any MP4, made by anidoodle or not) and fails the motion that+// made a brand launch film read as a slide deck:+// slidecut most of the frame replaced within 6 frames with no camera move; more than 2 in any minute fails+// repeat three or more beats in a row settle into the same layout with new content (a carousel)+// dissolve a cross-dissolve over a quarter of the frame or more (smaller element fades are listed)+// temperament stretches faster than the film's motion temperament allows (meta.motion.temperament or --temperament)+// The film's meta comes from the render's sidecar (<file>.film.json, written by render.mjs), so a+// renamed or versioned file still knows its exceptions (meta.motion.allow) and its temperament.+// Exit 0 pass, 1 fail, 2 usage. The detectors are motionscan-core.mjs (pure, unit-tested).+import { existsSync, readFileSync } from "node:fs";+import { execFileSync } from "node:child_process";+import { resolve } from "node:path";+import { greyFrames } from "./motion.mjs";+import { isMain } from "./is-main.mjs";+import { TEMPERAMENT_MAX, scanTarget, scanDissolves, scanRepeats, scanSlideCuts, scanTemperament, speedProfile } from "./motionscan-core.mjs";++export const CHECKS = ["slidecut", "repeat", "dissolve", "temperament"];+const ranges = (xs) => (xs ?? []).map(([a, b]) => [a, b]);++/** The sidecar render.mjs writes beside a delivered file, or null. */+export const sidecarOf = (file) => { const p = `${file}.film.json`; try { return existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : null; } catch { return null; } };++/** Run the motion checks on a rendered file. Returns { checks: { name: { status, ... } }, fail }. */+export const motionScan = async (file, { checks = CHECKS, temperament, size = 192, meta: given } = {}) => {+ const st = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,avg_frame_rate", "-of", "json", file])).streams[0];+ const [fn, fd] = st.avg_frame_rate.split("/").map(Number), fps = fn / fd, W = size, H = Math.max(24, Math.round((size * st.height) / st.width / 2) * 2);+ const meta = given ?? sidecarOf(file)?.meta ?? {}, motion = meta.motion ?? {}, allow = motion.allow ?? {};+ const frames = []; for await (const f of greyFrames(file, W, H)) frames.push(f);+ const out = {}, o = { width: W, height: H, fps };+ if (checks.includes("slidecut")) { const r = scanSlideCuts(frames, { ...o, allow: ranges(allow.slideCut) }); out.slidecut = { status: r.fail ? "FAIL" : "PASS", ...r }; }+ if (checks.includes("repeat")) { const r = scanRepeats(frames, o); out.repeat = { status: r.fail ? "FAIL" : "PASS", ...r }; }+ if (checks.includes("dissolve")) { const r = scanDissolves(frames, { ...o, allow: ranges(allow.dissolve) }); out.dissolve = { status: r.fail ? "FAIL" : "PASS", ...r }; }+ if (checks.includes("temperament")) {+ const t = temperament ?? motion.temperament, share = typeof t === "string" ? TEMPERAMENT_MAX[t] : t?.maxSpeed;+ if (t !== undefined && !share) throw new Error(`motionscan: temperament '${JSON.stringify(t)}' is not one of ${Object.keys(TEMPERAMENT_MAX).join(", ")} or { maxSpeed }`);+ if (!share) out.temperament = { status: "N/A", reason: "the film declares no motion temperament (meta.motion.temperament); pass --temperament calm|lively|snappy to judge it" };+ else {+ const sw = 128, sh = Math.max(24, Math.round((sw * st.height) / st.width / 2) * 2), small = []; for await (const f of greyFrames(file, sw, sh)) small.push(f);+ const maxPx = share * (2.5 * st.width) / fps, speeds = speedProfile(small, { width: sw, height: sh, scale: st.width / sw, R: 10 }), r = scanTemperament(speeds, { maxPx });+ out.temperament = { status: r.fail ? "FAIL" : "PASS", temperament: t, top: +Math.max(...speeds).toFixed(1), ...r };+ }+ }+ return { file, fps, frames: frames.length, checks: out, fail: Object.values(out).some((c) => c.status === "FAIL") };+};++export const printScan = (r) => {+ const s = (f) => (f / r.fps).toFixed(2), c = r.checks;+ console.log(`MOTIONSCAN ${r.file} ${r.frames} frames @ ${r.fps.toFixed(2)} fps`);+ if (c.slidecut) {+ for (const e of c.slidecut.events) console.log(` ${c.slidecut.fail ? "FAIL" : "NOTE"} slide cut at frame ${e.frame} (${s(e.frame)} s): ${Math.round(e.replaced * 100)} % of the frame replaced in 6 frames with no camera move`);+ console.log(` SLIDE-CUTS: ${c.slidecut.status} ${c.slidecut.events.length} found${c.slidecut.fail ? `, ${c.slidecut.worst.length} inside one minute (limit ${c.slidecut.perMinute}): carry the eye with a camera move into the next region (world.ts), or declare the cut in meta.motion.allow.slideCut` : ""}`);+ }+ if (c.repeat) {+ for (const run of c.repeat.runs) console.log(` FAIL ${run.length} beats in a row settle into the same layout: ${run.map(([a, b]) => `${s(a)}-${s(b)} s`).join(", ")}`);+ console.log(` REPEATS: ${c.repeat.status} ${c.repeat.beats.length} settled beats${c.repeat.fail ? ": give each beat its own layout and entry (motionKit alternate(i), entryFrom(i))" : ""}`);+ }+ if (c.dissolve) {+ for (const d of c.dissolve.findings) console.log(` ${d.seam && !d.allowed ? "FAIL" : "NOTE"} ${d.seam ? "dissolve or fade-in" : "small fade"} frames ${d.from}-${d.to - 1} (${s(d.from)}-${s(d.to)} s): ${Math.round(d.area * 100)} % of the frame blends, ${Math.round(d.share * 100)} % of what changes there${d.allowed ? " (declared)" : ""}`);+ console.log(` DISSOLVES: ${c.dissolve.status}${c.dissolve.fail ? " a fade is not a transition: move the camera, mask a wipe, or let the outgoing element leave" : ""}`);+ }+ if (c.temperament) {+ if (c.temperament.status === "N/A") console.log(` TEMPERAMENT: N/A ${c.temperament.reason}`);+ else { for (const t of c.temperament.stretches) console.log(` FAIL frames ${t.from}-${t.to} (${s(t.from)} s) move at up to ${t.top} px a frame; the ${JSON.stringify(c.temperament.temperament)} temperament allows ${c.temperament.maxPx.toFixed(0)}`); console.log(` TEMPERAMENT: ${c.temperament.status} fastest ${c.temperament.top} px a frame, limit ${c.temperament.maxPx.toFixed(0)}${c.temperament.fail ? ": lengthen the move or travel less" : ""}`); }+ }+ console.log(`MOTIONSCAN: ${r.fail ? "FAIL" : "PASS"}`);+};++if (isMain(import.meta.url)) {+ const pos = [], opt = {};+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a === "--json") opt.json = true; else if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }+ const usage = "usage: node tools/motionscan.mjs <film|path.mp4> [--checks slidecut,repeat,dissolve,temperament] [--temperament calm|lively|snappy] [--json]";+ if (!pos[0]) { console.error(usage); process.exit(2); }+ const file = resolve(scanTarget(pos[0]));+ if (!existsSync(file)) { console.error(`motionscan: no such file ${file}; render it first (node tools/render.mjs ${pos[0]}) or give the video file's path\n${usage}`); process.exit(2); }+ const checks = opt.checks ? String(opt.checks).split(",") : CHECKS, bad = checks.filter((c) => !CHECKS.includes(c));+ if (bad.length) { console.error(`motionscan: unknown check ${bad.join(", ")}; the checks are ${CHECKS.join(", ")}`); process.exit(2); }+ const r = await motionScan(file, { checks, temperament: opt.temperament });+ if (opt.json) console.log(JSON.stringify(r, (k, v) => (v instanceof Set ? [...v] : v), 1)); else printScan(r);+ process.exit(r.fail ? 1 : 0);+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/names.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/names.mjsindex 375402b..7e6afd3 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/names.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/names.mjs@@ -1,5 +1,5 @@// Names shared by the tools: where a film's MP4 lands by default, and which films exist.-import { existsSync, readdirSync } from "node:fs";+import { existsSync, readdirSync, readFileSync } from "node:fs";import { join } from "node:path";import { ROOTS } from "./overlay.mjs";@@ -10,9 +10,23 @@ export const defaultOutput = (film) => `out/${film}.mp4`;export const SHAPE_NAMES = ["16x9", "1x1", "4x5", "9x16"];export const splitShape = (film) => { const m = /^(.+)-(16x9|1x1|4x5|9x16)$/.exec(film ?? ""); return m ? { base: m[1], shape: m[2] } : { base: film, shape: null }; };-/** Every film this project can build: one host page, src/hosts/page-<film>.ts (the worked example's too). */-export const knownFilms = () => [...new Set([join(process.cwd(), "src"), ...ROOTS].flatMap((r) => { const d = join(r, "hosts"); return existsSync(d) ? readdirSync(d).filter((f) => /^page-.+\.ts$/.test(f)).map((f) => f.slice(5, -3)) : []; }))].sort();-const hostOf = (film) => [join(process.cwd(), "src"), ...ROOTS].map((r) => join(r, "hosts", `page-${splitShape(film).base}.ts`)).find((f) => existsSync(f));+// THE STANDARD HOST PAGE. Most films need nothing but "import the film, mount it". A film with no host page+// of its own gets exactly that page, built in memory (build-page.mjs): the installed plugin leaves those+// identical pages out to stay under the plugin directory's 512-file limit. A film that needs more (fixtures,+// a social card) keeps its own src/hosts/page-<film>.ts, which always wins.+export const standardHost = (name) => `import { ${name} } from "../canvas-core/${name}";\nimport { mountFilm } from "./page";\n\nmountFilm(${name});\n`;+const SRC_ROOTS = () => [join(process.cwd(), "src"), ...ROOTS];+const exportsFilm = (file, name) => new RegExp(`export\\s+const\\s+${name.replace(/\$/g, "\\$")}\\s*:\\s*Film\\b`).test(readFileSync(file, "utf8"));+/** The module that exports <film> as a Film under the same name (src/canvas-core/<film>.ts), or undefined. */+export const filmModule = (film) => { const b = splitShape(film).base; return SRC_ROOTS().map((r) => join(r, "canvas-core", `${b}.ts`)).find((f) => existsSync(f) && exportsFilm(f, b)); };+/** Every film this project can build: one with a host page src/hosts/page-<film>.ts, or a module that exports a Film under its own name. */+export const knownFilms = () => [...new Set(SRC_ROOTS().flatMap((r) => {+ const h = join(r, "hosts"), c = join(r, "canvas-core");+ const hosts = existsSync(h) ? readdirSync(h).filter((f) => /^page-.+\.ts$/.test(f)).map((f) => f.slice(5, -3)) : [];+ const mods = existsSync(c) ? readdirSync(c).filter((f) => /^[A-Za-z_$][\w$]*\.ts$/.test(f)).map((f) => f.slice(0, -3)).filter((n) => exportsFilm(join(c, `${n}.ts`), n)) : [];+ return [...hosts, ...mods];+}))].sort();+const hostOf = (film) => SRC_ROOTS().map((r) => join(r, "hosts", `page-${splitShape(film).base}.ts`)).find((f) => existsSync(f)) ?? filmModule(film);/** The film named on the command line, or a clear exit: the usage when none is given, the known films when it is not one. */export const requireFilm = (film, tool, usage) => {diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/narrate.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate.mjsnew file mode 100644index 0000000..88fc987--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate.mjs@@ -0,0 +1,249 @@+// NARRATE. A film's narration from a script: takes, word timing, a round-trip check, and a module the+// film imports. Every line is one take, cached by what makes its sound, so re-runs are free and the+// same script gives the same takes.+//+// node tools/narrate.mjs say <narration.json> make every take (cached in .cache/voice/)+// node tools/narrate.mjs time <narration.json> word timings by whisper.cpp, mapped onto the SCRIPT's words -> voice-timing.json+// node tools/narrate.mjs check <narration.json> the round trip: transcribe each take with no prompt, compare word by word,+// alignment and audio sanity, the phrase subtitles; exit 1 on any failure+// node tools/narrate.mjs bake <narration.json> time + write the film module (timing + takes as base64 PCM)+// node tools/narrate.mjs all <narration.json> check, then bake when it passes+// node tools/narrate.mjs providers which voices this machine can use+//+// --out DIR where voice-only stems and voice-timing.json go (default out/narration/<script name>/)+// --module FILE bake's module (default src/canvas-core/<script name>Voice.ts)+// --model FILE the whisper.cpp model (default: the best ggml-*.bin in ~/.cache/whisper)+// --shape S 16x9 (default), 9x16 or 1x1: the subtitle line length check uses it+// --max-wer X a take fails past this word error rate from extra words (default 0.03); any dropped+// or changed script word always fails+// --mix FILE check also: transcribe the finished mix (a .wav or the film's .mp4) and hold the whole script+// to the same word-for-word rule, so a score that buries a word fails too+// --force make the takes again, ignoring the cache+//+// CLOUD VOICES SEND YOUR TEXT TO THAT COMPANY: gemini (Google), openai (OpenAI), elevenlabs (ElevenLabs).+// A paid voice is only ever called when the script itself names it as its provider; keys are read from+// the environment and never printed. say (macOS), kokoro (local) and files (your own recordings) stay+// on this machine.+import { spawnSync } from "node:child_process";+import { enginePath } from "./overlay.mjs";+import { createHash } from "node:crypto";+import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { basename, dirname, join, relative, resolve } from "node:path";+import { build } from "esbuild";+import { isMain } from "./is-main.mjs";+import { audioProblems, alignmentProblems, mapDisplay, mapTimings, placeLines, roundTrip, scriptProblems, takeKey, whisperWords } from "./narrate/core.mjs";+import * as say from "./narrate/providers/say.mjs";+import * as gemini from "./narrate/providers/gemini.mjs";+import * as openai from "./narrate/providers/openai.mjs";+import * as elevenlabs from "./narrate/providers/elevenlabs.mjs";+import * as kokoro from "./narrate/providers/kokoro.mjs";+import * as files from "./narrate/providers/files.mjs";+import { which } from "./narrate/providers/util.mjs";++export const PROVIDERS = { say, gemini, openai, elevenlabs, kokoro, files };+const SR = 24000, CACHE = resolve(".cache/voice"), POST = "trim45-pad40-80-lufs20-pk3-v1"; // POST names the take processing: change it and every take is made again+const USAGE = "node tools/narrate.mjs say|time|check|bake|all <narration.json> [--out DIR] [--module FILE] [--model FILE] [--shape 16x9|9x16|1x1] [--max-wer 0.03] [--mix out/<film>.mp4] [--force]\n node tools/narrate.mjs providers";+const die = (m, code = 2) => { console.error(`narrate: ${m}`); process.exit(code); };+const sha = (s) => createHash("sha256").update(s).digest("hex");+const ff = (args) => { const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args], { encoding: "utf8", maxBuffer: 1 << 28 }); if (r.status !== 0) throw new Error(`ffmpeg: ${r.stderr.trim()}`); return r; };++// ---------------------------------------------------------------- the script+export const loadScript = (path) => {+ if (!path || !existsSync(path)) die(`no script '${path ?? ""}'\nusage: ${USAGE}`);+ let s; try { s = JSON.parse(readFileSync(path, "utf8")); } catch (e) { die(`${path} is not valid JSON: ${e.message}`); }+ const p = scriptProblems(s);+ if (p.length) die(`${path}:\n ${p.join("\n ")}`);+ if (!PROVIDERS[s.provider]) die(`${path}: unknown provider '${s.provider}' (say, gemini, openai, elevenlabs, kokoro, files)`);+ return { ...s, path: resolve(path), dir: dirname(resolve(path)), name: basename(path).replace(/\.json$/, "").replace(/[^A-Za-z0-9_]/g, "_") };+};+const voiceOf = (s, ln) => ({ ...(s.voice ?? {}), ...(ln.voice ?? {}) });++// ---------------------------------------------------------------- takes+// samples of a mono 24 kHz float WAV/any file, decoded by ffmpeg+export const readMono = (file, sr = SR) => { const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-f", "f32le", "-ac", "1", "-ar", String(sr), "-"], { maxBuffer: 1 << 30 }); if (r.status !== 0) throw new Error(`ffmpeg could not read ${file}: ${r.stderr}`); return new Float32Array(r.stdout.buffer.slice(r.stdout.byteOffset, r.stdout.byteOffset + r.stdout.byteLength)); };+const pcm16 = (x, gain) => { const b = Buffer.alloc(x.length * 2); for (let i = 0; i < x.length; i++) b.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(x[i] * gain * 32767))), i * 2); return b; };+const wavOf = (pcm) => { const h = Buffer.alloc(44); h.write("RIFF", 0); h.writeUInt32LE(36 + pcm.length, 4); h.write("WAVEfmt ", 8); h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22); h.writeUInt32LE(SR, 24); h.writeUInt32LE(SR * 2, 28); h.writeUInt16LE(2, 32); h.writeUInt16LE(16, 34); h.write("data", 36); h.writeUInt32LE(pcm.length, 40); return Buffer.concat([h, pcm]); };+// one provider take -> the house take: mono 24 kHz 16-bit, silence trimmed at -45 dB and padded+// (40 ms before, 80 ms after), set to -20 LUFS with its sample peak no higher than -3 dBFS+const finishTake = (raw, out) => {+ const tmp = out + ".trim.wav";+ ff(["-i", raw, "-af", "aformat=channel_layouts=mono,aresample=24000,silenceremove=start_periods=1:start_threshold=-45dB,areverse,silenceremove=start_periods=1:start_threshold=-45dB,areverse,adelay=40,apad=pad_dur=0.08", "-ar", String(SR), "-ac", "1", "-c:a", "pcm_f32le", tmp]);+ const r = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", tmp, "-af", "ebur128", "-f", "null", "-"], { encoding: "utf8" });+ const I = Number(((r.stdout + r.stderr).match(/Integrated loudness:\s*\n\s*I:\s*(-?[0-9.]+) LUFS/) ?? [])[1]);+ const x = readMono(tmp); let pk = 0; for (const v of x) pk = Math.max(pk, Math.abs(v));+ const gainDb = Math.min(Number.isFinite(I) ? -20 - I : 0, -3 - 20 * Math.log10(Math.max(pk, 1e-9)));+ writeFileSync(out, wavOf(pcm16(x, Math.pow(10, gainDb / 20)))); rmSync(tmp, { force: true });+};++/** Every line's take, from the cache or the provider. Returns [{ line, file, hash, cached }]. */+export const makeTakes = async (s, { force = false, log = console.log } = {}) => {+ // the provider (and its key) is needed only for a take that is not cached yet: checking, timing and+ // baking cached cloud takes never needs the key and never calls the company+ const P = PROVIDERS[s.provider];+ let ready = false;+ const need = () => {+ if (ready) return; ready = true;+ const av = P.available(); if (!av.ok) die(`provider '${s.provider}' is not available here: ${av.why}`);+ if (P.cloud) log(`narrate: ${s.provider} is a cloud voice: each line's text is sent to ${P.about.match(/goes to (\w+)/)?.[1] ?? "its company"}`);+ };+ if (s.provider === "files") need();+ mkdirSync(CACHE, { recursive: true });+ const out = [];+ for (const ln of s.lines) {+ const voice = voiceOf(s, ln);+ // a recording's own bytes are what make its sound: they go in the key instead of the text alone+ const src = s.provider === "files" ? await P.synth({ voice, lineId: ln.id, scriptDir: s.dir }) : null;+ const hash = sha(takeKey({ provider: s.provider, voice, text: ln.text, post: POST }) + (src ? sha(readFileSync(src)) : ""));+ const file = join(CACHE, `${hash}.wav`), cached = existsSync(file) && !force;+ if (!cached) {+ need();+ const raw = join(CACHE, `${hash}.raw`);+ const got = src ?? await P.synth({ text: ln.text, voice, raw, lineId: ln.id, scriptDir: s.dir });+ finishTake(got, file);+ if (!src) for (const f of readdirSync(CACHE)) if (f.startsWith(`${hash}.raw`)) rmSync(join(CACHE, f), { force: true });+ writeFileSync(join(CACHE, `${hash}.json`), JSON.stringify({ provider: s.provider, voice, text: ln.text, post: POST }, null, 1));+ }+ out.push({ line: ln, file, hash, cached });+ }+ return out;+};++// ---------------------------------------------------------------- whisper.cpp+const MODEL_ORDER = ["ggml-small.en.bin", "ggml-medium.en.bin", "ggml-base.en.bin", "ggml-large-v3-turbo.bin", "ggml-large-v3.bin", "ggml-small.bin", "ggml-base.bin", "ggml-tiny.en.bin"];+export const findModel = (flag) => {+ if (flag) { if (!existsSync(flag)) die(`no whisper model at ${flag}`); return resolve(flag); }+ if (process.env.NARRATE_WHISPER_MODEL && existsSync(process.env.NARRATE_WHISPER_MODEL)) return process.env.NARRATE_WHISPER_MODEL;+ const dir = join(homedir(), ".cache/whisper"), have = existsSync(dir) ? readdirSync(dir).filter((f) => /^ggml-.*\.bin$/.test(f) && !f.includes("for-tests")) : [];+ const pick = MODEL_ORDER.find((m) => have.includes(m)) ?? have[0];+ if (!pick) die(`no whisper.cpp model in ${dir}. Get one (MIT, about 148 MB):\n mkdir -p ~/.cache/whisper && curl -L -o ~/.cache/whisper/ggml-base.en.bin https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.en.bin\n(ggml-small.en.bin, about 488 MB, hears better)`);+ return join(dir, pick);+};+const whisperBin = () => { for (const c of ["whisper-cli", "whisper-cpp"]) { const f = which(c); if (f) return f; } die("whisper.cpp is not installed (brew install whisper-cpp gives whisper-cli)"); };+/** Transcribe a take with NO prompt (the check must hear what was said, not what was meant). Cached by take + model. */+export const transcribe = (file, model, lang = "en") => {+ const key = sha(readFileSync(file).toString("base64") + "\0" + basename(model) + "\0" + lang + "\0ml1-sow"), dir = join(CACHE, "asr"), hit = join(dir, `${key}.json`);+ mkdirSync(dir, { recursive: true });+ if (!existsSync(hit)) {+ const wav16 = join(dir, `${key}.16k.wav`), base = join(dir, key);+ ff(["-i", file, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wav16]);+ const r = spawnSync(whisperBin(), ["-m", model, "-f", wav16, "-l", lang, "-ml", "1", "-sow", "-ojf", "-of", base, "-np", "-bs", "5"], { encoding: "utf8", maxBuffer: 1 << 26 });+ rmSync(wav16, { force: true });+ if (r.status !== 0 || !existsSync(base + ".json")) throw new Error(`whisper-cli failed on ${file}: ${(r.stderr || r.stdout).trim().slice(-400)}`);+ }+ return whisperWords(JSON.parse(readFileSync(hit, "utf8")));+};++// ---------------------------------------------------------------- time+const outDir = (s, flag) => resolve(flag ?? join("out/narration", s.name));+export const timeScript = async (s, o = {}) => {+ const takes = await makeTakes(s, o), model = findModel(o.model), per = [];+ for (const t of takes) {+ const x = readMono(t.file), asr = transcribe(t.file, model, s.lang ?? "en"), m = mapTimings(t.line.text, asr, { aliases: s.aliases });+ const words = mapDisplay(t.line.display ?? t.line.text, m.tokens);+ per.push({ ...t, x, asr, mapped: m, take: { durationS: x.length / SR, words } });+ }+ const timing = { ...placeLines(s, per.map((p) => p.take)), provider: s.provider, sampleRate: SR };+ timing.lines.forEach((l, i) => { l.file = relative(process.cwd(), per[i].file); l.hash = per[i].hash; });+ const dir = outDir(s, o.out); mkdirSync(join(dir, "lines"), { recursive: true });+ // voice-only stems next to every mix (lesson 51): one line can be swapped without touching the rest+ for (const p of per) copyFileSync(p.file, join(dir, "lines", `${p.line.id}.wav`));+ writeFileSync(join(dir, "voice-timing.json"), JSON.stringify(timing, null, 1));+ return { timing, per, dir, model };+};++// ---------------------------------------------------------------- check+// the phrase subtitles, built by the film's own module, so the check and the film can never disagree+const loadSubtitles = async () => {+ const js = (await build({ entryPoints: [enginePath("src/canvas-core/subtitles.ts")], bundle: true, format: "esm", write: false, platform: "neutral", logLevel: "error" })).outputFiles[0].text;+ return import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));+};+const show = (p) => { const r = relative(process.cwd(), p); return r.startsWith("..") ? p : r; };+const pad = (s, n) => String(s).padEnd(n).slice(0, Math.max(n, String(s).length));+export const checkScript = async (s, o = {}) => {+ const { timing, per, model } = await timeScript(s, o), maxWer = Number(o.maxWer ?? 0.03), rows = [];+ for (const [i, p] of per.entries()) {+ const rt = roundTrip(p.line.text, p.asr, { aliases: s.aliases, maxWer }), al = alignmentProblems(p.mapped.tokens), au = audioProblems(p.x, SR, { words: rt.tokens.filter((t) => t.words.length).length });+ rows.push({ id: p.line.id, dur: p.take.durationS, frames: `${timing.lines[i].start}-${timing.lines[i].end}`, wer: rt.wer, heard: rt.heard, problems: [...rt.problems, ...al.map((x) => `ALIGN ${x}`), ...au.problems.map((x) => `AUDIO ${x}`)], peak: au.peakDb });+ }+ const sub = await loadSubtitles(), plan = sub.phrasePlan(timing, { shape: o.shape ?? "16x9" });+ console.log(`NARRATE CHECK ${show(s.path)} provider ${s.provider}, ${s.lines.length} line(s), ${timing.totalFrames} frames at ${timing.fps} fps ASR ${basename(model)} (no prompt)`);+ console.log(` ${pad("line", 10)} ${pad("frames", 11)} ${pad("dur", 6)} ${pad("WER", 6)} ${pad("peak", 7)} verdict`);+ for (const r of rows) {+ console.log(` ${pad(r.id, 10)} ${pad(r.frames, 11)} ${pad(r.dur.toFixed(2) + "s", 6)} ${pad((r.wer * 100).toFixed(1) + "%", 6)} ${pad(r.peak.toFixed(1), 7)} ${r.problems.length ? "FAIL" : "PASS"}`);+ for (const pr of r.problems) console.log(` ${pr}`);+ if (r.problems.length) console.log(` heard: "${r.heard}"`);+ }+ console.log(` SUBTITLES ${plan.events.length} phrase(s) for ${o.shape ?? "16x9"}${plan.problems.length ? "" : ": every phrase lands on its words and holds its reading time"}`);+ for (const pr of plan.problems) console.log(` ${pr}`);+ // after the mix: the voice must still be heard word for word over the score (research: run the round trip again on the final mix)+ let mixBad = 0;+ if (o.mix) {+ if (!existsSync(o.mix)) die(`--mix: no file ${o.mix}`);+ const all = s.lines.map((l) => l.text).join(" "), mrt = roundTrip(all, transcribe(resolve(o.mix), model, s.lang ?? "en"), { aliases: s.aliases, maxWer });+ mixBad = mrt.problems.length;+ console.log(` MIX ${show(resolve(o.mix))}: WER ${(mrt.wer * 100).toFixed(1)} % over the whole script ${mixBad ? "FAIL" : "PASS"}`);+ for (const pr of mrt.problems) console.log(` ${pr}`);+ if (mixBad) console.log(` heard: "${mrt.heard}"`);+ }+ // the film plays the BAKED takes: a module baked from other takes (or another timing) is a stale film+ const mod = resolve(o.module ?? `src/canvas-core/${s.name}Voice.ts`); let stale = false;+ if (existsSync(mod)) {+ stale = bakedStale(readFileSync(mod, "utf8"), timing, !!o.ignoreStale);+ console.log(` BAKED ${show(mod)}: ${stale ? "FAIL baked from other takes or timing: run narrate.mjs bake" : "matches these takes and this timing"}`);+ } else console.log(` BAKED ${show(mod)}: not baked yet (narrate.mjs bake writes it)`);+ const bad = rows.filter((r) => r.problems.length).length + (plan.problems.length ? 1 : 0) + (mixBad ? 1 : 0) + (stale ? 1 : 0);+ console.log(bad ? `NARRATE CHECK: FAIL ${rows.filter((r) => r.problems.length).length} line(s) failed${plan.problems.length ? `, ${plan.problems.length} subtitle problem(s)` : ""}${mixBad ? ", the mix lost words" : ""}${stale ? ", the baked module is stale" : ""}` : `NARRATE CHECK: PASS ${rows.length}/${rows.length} lines heard word for word, timed and clean`);+ return { ok: !bad, rows, timing, plan };+};++/**+ * Is a baked module out of date for these takes and this timing? It is when its take hashes or its+ * length differ. `all` passes ignoreStale, because re-baking a stale module is the job it exists to do:+ * the parentheses make that cover a changed length too, not only changed takes.+ */+export const bakedStale = (src, timing, ignoreStale = false) => {+ const hashes = [...src.matchAll(/"hash":"([0-9a-f]{64})"/g)].map((m) => m[1]), frames = Number((src.match(/"totalFrames":(\d+)/) ?? [])[1]);+ return !ignoreStale && (hashes.join() !== timing.lines.map((l) => l.hash).join() || frames !== timing.totalFrames);+};++// ---------------------------------------------------------------- bake+export const bakeScript = async (s, o = {}) => {+ const { timing, per } = await timeScript(s, o), mod = resolve(o.module ?? `src/canvas-core/${s.name}Voice.ts`), name = `${s.name}Voice`;+ const pcm = Object.fromEntries(per.map((p) => [p.line.id, readFileSync(p.file).subarray(44).toString("base64")]));+ const t = { ...timing, lines: timing.lines.map(({ file, ...l }) => l) }; // the local take path stays out of the film+ const src = `// GENERATED by tools/narrate.mjs bake from ${relative(dirname(mod), s.path)}: do not edit. Re-run the bake after changing the script.\n` ++ `// The narration's timing (frames at ${timing.fps} fps) and each line's take as 16-bit mono PCM at ${SR} Hz, base64, so the film needs no file and no network.\n` ++ `// Voice: ${s.provider}${s.provider === "say" ? " (macOS system voice: a draft; check its licence before publishing a film made with it)" : ""}.\n` ++ `import type { BakedVoice } from "./voice";\n\nexport const ${name}: BakedVoice = {\n timing: ${JSON.stringify(t)},\n sampleRate: ${SR},\n pcm: {\n${Object.entries(pcm).map(([k, v]) => ` ${JSON.stringify(k)}: "${v}",`).join("\n")}\n },\n};\n`;+ writeFileSync(mod, src);+ return { mod, bytes: src.length, timing };+};++// ---------------------------------------------------------------- the command line+if (isMain(import.meta.url)) {+ const [cmd, file, ...rest] = process.argv.slice(2), o = {};+ for (let i = 0; i < rest.length; i++) { const a = rest[i]; if (!a.startsWith("--")) die(`unexpected '${a}'\nusage: ${USAGE}`); const k = a.slice(2); if (k === "force") o.force = true; else o[{ "max-wer": "maxWer" }[k] ?? k] = rest[++i]; }+ if (o.shape && !["16x9", "9x16", "1x1"].includes(o.shape)) die(`--shape is 16x9, 9x16 or 1x1, got '${o.shape}'`);+ try {+ if (cmd === "providers") {+ for (const [k, P] of Object.entries(PROVIDERS)) { const a = P.available(); console.log(` ${pad(k, 11)} ${a.ok ? "ready " : "missing"} ${P.about}${a.ok ? "" : `: ${a.why}`}`); }+ console.log("Cloud voices send each line's text to that company. A script names its provider; nothing else is ever called.");+ } else if (cmd === "say") {+ const s = loadScript(file), t = await makeTakes(s, o);+ for (const x of t) console.log(` ${pad(x.line.id, 10)} ${x.cached ? "cached" : "made "} ${relative(process.cwd(), x.file)}`);+ console.log(`narrate say: ${t.length} take(s), ${t.filter((x) => !x.cached).length} new`);+ } else if (cmd === "time") {+ const s = loadScript(file), r = await timeScript(s, o);+ for (const l of r.timing.lines) console.log(` ${pad(l.id, 10)} frames ${l.start}-${l.end} ${l.words.map((w) => `${w.w}@${w.from}${w.est ? "?" : ""}`).join(" ")}`);+ console.log(`narrate time: ${r.timing.totalFrames} frames -> ${relative(process.cwd(), join(r.dir, "voice-timing.json"))}`);+ } else if (cmd === "check" || cmd === "all") {+ const s = loadScript(file), r = await checkScript(s, { ...o, ignoreStale: cmd === "all" });+ if (!r.ok) process.exit(1);+ if (cmd === "all") { const b = await bakeScript(s, o); console.log(`narrate bake: ${relative(process.cwd(), b.mod)} (${(b.bytes / 1024).toFixed(0)} KB)`); }+ } else if (cmd === "bake") {+ const s = loadScript(file), b = await bakeScript(s, o);+ console.log(`narrate bake: ${relative(process.cwd(), b.mod)} (${(b.bytes / 1024).toFixed(0)} KB), ${b.timing.totalFrames} frames. Run check before you ship it.`);+ } else die(`unknown command '${cmd ?? ""}'\nusage: ${USAGE}`);+ } catch (e) { die(e.message, 2); }+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/core.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/core.mjsnew file mode 100644index 0000000..bc454c0--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/core.mjs@@ -0,0 +1,322 @@+// NARRATE CORE. The pure half of tools/narrate.mjs: no ffmpeg, no files, no network, so every rule+// here is unit-tested (test/narrate.test.ts) on hand-made words and synthetic samples.+// normalise text -> the words a listener hears: lower case, no punctuation, numbers, money,+// percents, times and ordinals spelled out, so "$13.60" and "thirteen dollars sixty"+// compare equal and a script is never judged on how an ASR chose to print a number+// alignWords Levenshtein on words with a backtrace: which script word was heard, changed, dropped+// wer word error rate, (substitutions + deletions + insertions) / script words+// mapTimings ASR word times laid back onto the SCRIPT's words (never the ASR's text: lesson 51)+// placeLines line takes laid end to end on the film's frame grid -> voice-timing.json+// checks alignment sanity and audio sanity, each returning named problems++// ---------------------------------------------------------------- numbers to words+const ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];+const TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];+const SCALES = [[1e12, "trillion"], [1e9, "billion"], [1e6, "million"], [1e3, "thousand"]];+const under1000 = (n) => {+ const out = [];+ if (n >= 100) { out.push(ONES[Math.floor(n / 100)], "hundred"); n %= 100; }+ if (n >= 20) { out.push(TENS[Math.floor(n / 10)]); n %= 10; if (n) out.push(ONES[n]); }+ else if (n > 0 || !out.length) out.push(ONES[n]);+ return out;+};+/** A whole number as spoken words ("1984" stays a cardinal here; yearWords reads it as a year). */+export const cardinalWords = (n) => {+ if (!Number.isSafeInteger(n) || n < 0) return String(n).split("");+ if (n === 0) return ["zero"];+ const out = [];+ for (const [v, w] of SCALES) if (n >= v) { out.push(...under1000(Math.floor(n / v)), w); n %= v; }+ if (n) out.push(...under1000(n));+ return out;+};+// a bare four-digit number in running speech is usually a year: 1984 "nineteen eighty four", 2026+// "twenty twenty six", but 2005 "two thousand five" and 1900 "nineteen hundred"+export const yearWords = (n) => {+ if (n >= 2000 && n <= 2009) return cardinalWords(n);+ const hi = Math.floor(n / 100), lo = n % 100;+ return [...cardinalWords(hi), ...(lo === 0 ? ["hundred"] : lo < 10 ? ["oh", ONES[lo]] : cardinalWords(lo))];+};+const ORD = { one: "first", two: "second", three: "third", five: "fifth", eight: "eighth", nine: "ninth", twelve: "twelfth" };+const ordinalOf = (w) => ORD[w] ?? (w.endsWith("y") ? w.slice(0, -1) + "ieth" : w + "th");+const ordinalWords = (n) => { const c = cardinalWords(n); c[c.length - 1] = ordinalOf(c[c.length - 1]); return c; };+const digitsWords = (s) => [...s].map((d) => ONES[+d]);+const NUMBER_WORDS = new Set([...ONES, ...TENS.filter(Boolean), "hundred", "thousand", "million", "billion", "trillion", "point", "oh"]);+export const isNumberWord = (w) => NUMBER_WORDS.has(w) || /^\d/.test(w);++// one raw token (no spaces) -> the words it is heard as+const CURRENCY = { $: ["dollar", "dollars"], "£": ["pound", "pounds"], "€": ["euro", "euros"] };+const numberish = (core) => {+ // money: $13.60 -> thirteen dollars sixty; $5 -> five dollars; €1.5m is left to the digits path+ const money = core.match(/^([$£€])(\d[\d,]*)(?:\.(\d{1,2}))?$/);+ if (money) {+ const [, sym, whole, cents] = money, n = +whole.replace(/,/g, ""), [one, many] = CURRENCY[sym];+ const out = [...cardinalWords(n), n === 1 ? one : many];+ if (cents && +cents) out.push(...cardinalWords(+(cents.length === 1 ? cents + "0" : cents)));+ return out;+ }+ const pct = core.match(/^(\d[\d,]*(?:\.\d+)?)%$/);+ if (pct) return [...numberish(pct[1]), "percent"];+ const ord = core.match(/^(\d+)(st|nd|rd|th)$/i);+ if (ord) return ordinalWords(+ord[1]);+ const clock = core.match(/^(\d{1,2}):(\d{2})$/);+ if (clock) return [...cardinalWords(+clock[1]), ...(+clock[2] === 0 ? [] : +clock[2] < 10 ? ["oh", ONES[+clock[2]]] : cardinalWords(+clock[2]))];+ const dec = core.match(/^(\d[\d,]*)\.(\d+)$/);+ if (dec) return [...cardinalWords(+dec[1].replace(/,/g, "")), "point", ...digitsWords(dec[2])];+ if (/^\d{1,3}(,\d{3})+$/.test(core)) return cardinalWords(+core.replace(/,/g, ""));+ if (/^\d{4}$/.test(core) && +core >= 1100 && +core <= 2099) return yearWords(+core);+ if (/^\d+$/.test(core)) return core.length > 15 ? digitsWords(core) : cardinalWords(+core);+ // digits glued to letters: 2AM -> two am, 3D -> three d, 24fps -> twenty four fps+ const glued = core.match(/^(\d+)([a-z]+)$/i);+ if (glued) return [...numberish(glued[1]), glued[2].toLowerCase()];+ return null;+};++/** One raw token (a word as written, with its punctuation) -> the words a listener hears. */+export const tokenWords = (raw) => {+ let t = String(raw).trim();+ if (!t) return [];+ t = t.replace(/[‘’ʼ]/g, "'").replace(/[“”]/g, '"').replace(/[–—]/g, " ");+ if (/\s/.test(t)) return t.split(/\s+/).flatMap(tokenWords);+ // strip the punctuation around the word, keep what lives inside it ($, %, :, ., ')+ const core = t.replace(/^[^\w$£€]+/, "").replace(/[^\w%]+$/, "");+ if (!core) return t === "&" ? ["and"] : t === "+" ? ["plus"] : t === "@" ? ["at"] : [];+ const n = numberish(core);+ if (n) return n;+ if (core === "&") return ["and"];+ // dotted abbreviations collapse: a.m. -> am, U.S. -> us+ if (/^([a-z]\.)+[a-z]?$/i.test(core + (t.endsWith(".") ? "." : ""))) return [core.replace(/\./g, "").toLowerCase()];+ // hyphens and slashes join words that are each spoken+ if (/[-/]/.test(core)) return core.split(/[-/]+/).flatMap(tokenWords);+ return [core.toLowerCase().replace(/'/g, "").replace(/[^a-z0-9]/g, "")].filter(Boolean);+};++/** Raw tokens of a line, split on whitespace, each with the words it is heard as. */+export const tokenize = (text) => String(text ?? "").replace(/[–—]/g, " ").split(/\s+/).filter(Boolean).map((raw) => ({ raw, words: tokenWords(raw) }));++// "and" inside a number and "cents" after one are said by some voices and printed by no ASR+// (thirteen dollars AND sixty CENTS): they are dropped from both sides before any comparison+const softNumberGlue = (flat) => flat.filter((x, i) => {+ // only after a scale word or a currency ("two hundred and five", "dollars and sixty"): "2026 and 1984" keeps its and+ if (x.w === "and") return !(i > 0 && i < flat.length - 1 && /^(hundred|thousand|million|billion|trillion|dollars?|pounds?|euros?)$/.test(flat[i - 1].w) && isNumberWord(flat[i + 1].w));+ if (x.w === "cents" || x.w === "cent") return !(i > 0 && isNumberWord(flat[i - 1].w));+ return true;+});+/** Tokens -> the flat list of heard words, each remembering the token it came from. */+export const flatten = (tokens) => softNumberGlue(tokens.flatMap((t, ti) => t.words.map((w) => ({ w, ti }))));+/** Plain text -> normalised words (what WER is computed on). */+export const normalise = (text) => flatten(tokenize(text)).map((x) => x.w);++// ---------------------------------------------------------------- alignment and WER+/**+ * Levenshtein on words with a backtrace. ref and hyp are arrays of words; eq(a, b) decides a match+ * (aliases: a name the ASR always spells its own way). Returns ops in order:+ * { op: "ok" | "sub" | "del" | "ins", r: refIndex | -1, h: hypIndex | -1 }+ * Ties prefer a match, then a substitution, so a changed word reads as "changed", not drop + insert.+ */+export const alignWords = (ref, hyp, eq = (a, b) => a === b) => {+ const n = ref.length, m = hyp.length, D = Array.from({ length: n + 1 }, () => new Int32Array(m + 1));+ for (let i = 0; i <= n; i++) D[i][0] = i;+ for (let j = 0; j <= m; j++) D[0][j] = j;+ for (let i = 1; i <= n; i++) for (let j = 1; j <= m; j++) D[i][j] = Math.min(D[i - 1][j - 1] + (eq(ref[i - 1], hyp[j - 1]) ? 0 : 1), D[i - 1][j] + 1, D[i][j - 1] + 1);+ const ops = [];+ let i = n, j = m;+ while (i > 0 || j > 0) {+ if (i > 0 && j > 0 && eq(ref[i - 1], hyp[j - 1]) && D[i][j] === D[i - 1][j - 1]) { ops.push({ op: "ok", r: i - 1, h: j - 1 }); i--; j--; }+ else if (i > 0 && j > 0 && D[i][j] === D[i - 1][j - 1] + 1) { ops.push({ op: "sub", r: i - 1, h: j - 1 }); i--; j--; }+ else if (i > 0 && D[i][j] === D[i - 1][j] + 1) { ops.push({ op: "del", r: i - 1, h: -1 }); i--; }+ else { ops.push({ op: "ins", r: -1, h: j - 1 }); j--; }+ }+ return ops.reverse();+};+/** Word error rate of hyp against ref (both arrays of normalised words). */+export const wer = (ref, hyp, eq) => {+ const ops = alignWords(ref, hyp, eq), c = { sub: 0, del: 0, ins: 0, ok: 0 };+ for (const o of ops) c[o.op]++;+ return { wer: ref.length ? (c.sub + c.del + c.ins) / ref.length : hyp.length ? 1 : 0, ...c, n: ref.length, ops };+};+/** aliases: { "clawd": ["claude", "clod"] } -> an eq() that also accepts those spellings. */+export const aliasEq = (aliases = {}) => {+ const map = new Map();+ for (const [k, vs] of Object.entries(aliases)) for (const kw of normalise(k)) map.set(kw, new Set([kw, ...[].concat(vs).flatMap(normalise)]));+ return (a, b) => a === b || (map.get(a)?.has(b) ?? false);+};++// ---------------------------------------------------------------- ASR words back onto the script+/**+ * whisper.cpp JSON (-ml 1 -sow -ojf): one segment per word. -> [{ text, t0, t1 }] in seconds, the+ * [_BEG_]-style empty segments dropped.+ */+export const whisperWords = (json) => (json?.transcription ?? [])+ .map((s) => ({ text: String(s.text ?? "").trim(), t0: (s.offsets?.from ?? 0) / 1000, t1: (s.offsets?.to ?? 0) / 1000 }))+ .filter((w) => w.text && !/^\[.*\]$/.test(w.text) && tokenWords(w.text).length);++/**+ * Lay ASR word times onto the script's own tokens. asr: [{ text, t0, t1 }]. The ASR text is used ONLY+ * to find where each script word was said; the words the film shows always come from the script.+ * Returns { tokens: [{ raw, words, t0, t1, status, heard }], inserted: [heard words], ops } where status is+ * "ok" every heard word of the token matched+ * "changed" the token was said, but as something else (heard shows what)+ * "dropped" nothing in the take lines up with it: its time is ESTIMATED between its neighbours+ */+export const mapTimings = (scriptText, asr, { aliases } = {}) => {+ const tokens = tokenize(scriptText), ref = flatten(tokens);+ // each ASR word spreads its time over the words it normalises to (by letters: "thirteen" outlasts "a")+ const hyp = asr.flatMap((a) => {+ const ws = tokenWords(a.text), total = ws.reduce((s, w) => s + w.length + 1, 0);+ let at = a.t0;+ return ws.map((w) => { const d = ((a.t1 - a.t0) * (w.length + 1)) / total, o = { w, t0: at, t1: at + d }; at += d; return o; });+ });+ const ops = alignWords(ref.map((x) => x.w), hyp.map((x) => x.w), aliasEq(aliases));+ const per = tokens.map((t) => ({ ...t, t0: NaN, t1: NaN, status: t.words.length ? "ok" : "silent", heard: [] }));+ const inserted = [];+ for (const o of ops) {+ if (o.op === "ins") { inserted.push(hyp[o.h].w); continue; }+ const tk = per[ref[o.r].ti];+ if (o.op === "del") { tk.status = "dropped"; continue; }+ if (o.op === "sub" && tk.status !== "dropped") tk.status = "changed";+ tk.heard.push(hyp[o.h].w);+ tk.t0 = Number.isNaN(tk.t0) ? hyp[o.h].t0 : Math.min(tk.t0, hyp[o.h].t0);+ tk.t1 = Number.isNaN(tk.t1) ? hyp[o.h].t1 : Math.max(tk.t1, hyp[o.h].t1);+ }+ // a token partly dropped (one of its words missing) is "dropped" if nothing was heard, else "changed"+ for (const tk of per) if (tk.status === "dropped" && tk.heard.length) tk.status = "changed";+ estimateGaps(per);+ return { tokens: per, inserted, ops };+};+// dropped tokens (and punctuation-only ones) get a time between their timed neighbours, marked est+const estimateGaps = (per) => {+ for (let i = 0; i < per.length; i++) {+ if (!Number.isNaN(per[i].t0)) continue;+ let j = i; while (j < per.length && Number.isNaN(per[j].t0)) j++;+ const a = i > 0 ? per[i - 1].t1 : (per[j]?.t0 ?? 0), b = j < per.length ? per[j].t0 : a, k = j - i;+ for (let q = 0; q < k; q++) { per[i + q].t0 = a + ((b - a) * q) / k; per[i + q].t1 = a + ((b - a) * (q + 1)) / k; per[i + q].est = true; }+ i = j - 1;+ }+};++/**+ * Display tokens (what captions show: "$13.60") mapped onto the spoken tokens ("thirteen dollars sixty")+ * through their heard words, so each display token takes the time of what was said for it.+ * spoken: [{ raw, words, t0, t1, est? }]. Returns [{ w, say, t0, t1, est }].+ */+export const mapDisplay = (displayText, spoken) => {+ const disp = tokenize(displayText), dflat = flatten(disp), sflat = flatten(spoken);+ const ops = alignWords(dflat.map((x) => x.w), sflat.map((x) => x.w));+ const hit = disp.map(() => new Set());+ for (const o of ops) if (o.r >= 0 && o.h >= 0) hit[dflat[o.r].ti].add(sflat[o.h].ti);+ const out = disp.map((d, i) => {+ const ix = [...hit[i]].sort((a, b) => a - b), sp = ix.map((k) => spoken[k]);+ return sp.length ? { w: d.raw, say: sp.map((s) => s.raw).join(" "), t0: Math.min(...sp.map((s) => s.t0)), t1: Math.max(...sp.map((s) => s.t1)), est: sp.some((s) => s.est) } : { w: d.raw, say: "", t0: NaN, t1: NaN, est: true };+ });+ estimateGaps(out);+ return out;+};++// ---------------------------------------------------------------- placing lines on the film's frames+/**+ * script: { fps, lead?, tail?, pause?, lines: [{ id, at?, pauseAfter? }] }; takes: per line { durationS,+ * words: [{ w, say, t0, t1, est }] } (seconds inside the take). Lines play end to end: each starts on a+ * whole frame (so its first sample sits exactly on that frame), after the previous line's last frame+ * plus its pause, unless it names its own frame `at`. Returns the voice-timing object (frames).+ */+export const placeLines = (script, takes) => {+ const fps = script.fps, lead = script.lead ?? Math.round(fps / 2), tail = script.tail ?? fps, pause = script.pause ?? 0.35;+ if (!Number.isInteger(fps) || fps <= 0) throw new Error(`narration: fps must be a whole number, got ${fps}`);+ let free = lead, prevPause = 0;+ const lines = script.lines.map((ln, i) => {+ const tk = takes[i], natural = i === 0 ? lead : free + Math.round(prevPause * fps);+ if (ln.at !== undefined && (!Number.isInteger(ln.at) || ln.at < free)) throw new Error(`narration: line '${ln.id}' asks to start at frame ${ln.at}, but the line before it is still speaking until frame ${free}`);+ const start = ln.at ?? natural, end = start + Math.ceil(tk.durationS * fps - 1e-9);+ free = end; prevPause = ln.pauseAfter ?? pause;+ const words = tk.words.map((w) => {+ // an ASR end can overshoot the take's trailing pad: no word outlasts its own line+ const from = Math.min(end - 1, start + Math.round(w.t0 * fps)), to = Math.min(end, Math.max(from + 1, start + Math.round(w.t1 * fps)));+ return { w: w.w, say: w.say, from, to, t0: round3(w.t0), t1: round3(w.t1), ...(w.est ? { est: true } : {}) };+ });+ return { id: ln.id, text: ln.text, display: ln.display ?? ln.text, start, end, durationS: round3(tk.durationS), words };+ });+ return { version: 1, fps, totalFrames: free + tail, lines };+};+const round3 = (x) => Math.round(x * 1000) / 1000;++// ---------------------------------------------------------------- the checks+/** Sentence-ending punctuation on a raw token: no gap rule applies across it. */+export const endsSentence = (raw) => /[.!?;:]["')\]]*$/.test(raw);+/**+ * Alignment sanity on one take's mapped tokens: every word timed (not estimated), monotonic and+ * non-overlapping, each word 0.05-1.5 s long, no gap over maxGapS inside a sentence.+ */+export const alignmentProblems = (tokens, { maxGapS = 1.0, minWordS = 0.05, maxWordS = 1.5 } = {}) => {+ const p = [], timed = tokens.filter((t) => t.words.length);+ for (const t of timed) if (t.est) p.push(`"${t.raw}" has no timing of its own (estimated)`);+ for (let i = 0; i < timed.length; i++) {+ const t = timed[i], d = t.t1 - t.t0;+ if (!(d >= 0)) p.push(`"${t.raw}" ends before it starts`);+ else if (!t.est && (d < minWordS - 1e-9 || d > maxWordS + 1e-9)) p.push(`"${t.raw}" lasts ${d.toFixed(2)} s (sane: ${minWordS}-${maxWordS} s)`);+ if (i > 0) {+ const a = timed[i - 1];+ if (t.t0 < a.t0 - 1e-9 || t.t0 < a.t1 - 0.02) p.push(`"${t.raw}" starts before "${a.raw}" ends (not monotonic)`);+ else if (!endsSentence(a.raw) && t.t0 - a.t1 > maxGapS) p.push(`a ${(t.t0 - a.t1).toFixed(2)} s gap between "${a.raw}" and "${t.raw}" inside a sentence`);+ }+ }+ return p;+};++/**+ * Audio sanity on a mono take (Float32 samples at sr): not clipped (no sample at full scale), peak at or+ * under peakDb, leading silence and trailing silence inside their bounds, and a speaking rate that a+ * person could have produced (words per second). Silence = under -45 dBFS in 10 ms windows.+ */+export const audioProblems = (x, sr, { words = 0, peakDb = -1, maxLeadS = 0.3, maxTailS = 0.6, wps = [1.2, 4.5], floorDb = -45 } = {}) => {+ const p = [];+ let peak = 0, clipped = 0;+ for (let i = 0; i < x.length; i++) { const a = Math.abs(x[i]); if (a > peak) peak = a; if (a >= 0.999) clipped++; }+ const pkDb = 20 * Math.log10(Math.max(peak, 1e-12)), hop = Math.max(1, Math.round(0.01 * sr)), thr = Math.pow(10, floorDb / 20);+ let first = -1, last = -1;+ for (let i = 0; i + hop <= x.length; i += hop) { let s = 0; for (let k = i; k < i + hop; k++) s += x[k] * x[k]; if (Math.sqrt(s / hop) > thr) { if (first < 0) first = i; last = i + hop; } }+ const dur = x.length / sr, lead = first < 0 ? dur : first / sr, tail = first < 0 ? dur : dur - last / sr, speech = first < 0 ? 0 : (last - first) / sr;+ if (first < 0) p.push("the take is silent");+ if (clipped) p.push(`clipped: ${clipped} sample(s) at full scale`);+ else if (pkDb > peakDb) p.push(`peak ${pkDb.toFixed(1)} dBFS is over ${peakDb} dBFS`);+ if (first >= 0 && lead > maxLeadS) p.push(`${lead.toFixed(2)} s of silence before the first word (bound ${maxLeadS} s)`);+ if (first >= 0 && tail > maxTailS) p.push(`${tail.toFixed(2)} s of silence after the last word (bound ${maxTailS} s)`);+ if (words && speech > 0) { const r = words / speech; if (r < wps[0] || r > wps[1]) p.push(`${r.toFixed(1)} words per second (a voice says ${wps[0]}-${wps[1]})`); }+ return { problems: p, peakDb: pkDb, leadS: lead, tailS: tail, speechS: speech };+};++/**+ * The round-trip verdict for one line: the script against what a second model heard, with no prompt.+ * Any dropped or changed script word fails and is named (lesson 51: an all-caps CONTEXT vanished from a+ * take and only an ear caught it). Words the ASR heard that the script lacks fail past maxWer.+ */+export const roundTrip = (scriptText, asr, { aliases, maxWer = 0.03 } = {}) => {+ const m = mapTimings(scriptText, asr, { aliases }), ref = normalise(scriptText), hyp = asr.flatMap((a) => tokenWords(a.text));+ const w = wer(ref, hyp, aliasEq(aliases));+ const dropped = m.tokens.filter((t) => t.status === "dropped").map((t) => t.raw), changed = m.tokens.filter((t) => t.status === "changed").map((t) => `${t.raw} -> ${t.heard.join(" ")}`);+ const problems = [...dropped.map((d) => `DROPPED "${d}"`), ...changed.map((c) => `CHANGED "${c}"`)];+ if (w.wer > maxWer && !problems.length) problems.push(`WER ${(w.wer * 100).toFixed(1)} % over ${(maxWer * 100).toFixed(0)} % (heard extra: ${m.inserted.join(" ")})`);+ return { wer: w.wer, dropped, changed, inserted: m.inserted, heard: hyp.join(" "), problems, tokens: m.tokens };+};++/** The sha256 cache key input for one take: everything that changes the sound, nothing that doesn't. */+export const takeKey = ({ provider, voice, text, post }) => JSON.stringify({ provider, voice: sortKeys(voice ?? {}), text, post });+const sortKeys = (o) => (o && typeof o === "object" && !Array.isArray(o) ? Object.fromEntries(Object.keys(o).sort().map((k) => [k, sortKeys(o[k])])) : o);++/** Validate a narration.json object. Returns problems (empty = good). */+export const scriptProblems = (s) => {+ const p = [];+ if (!s || typeof s !== "object") return ["the script is not a JSON object"];+ if (!Number.isInteger(s.fps) || s.fps <= 0) p.push("fps must be a whole number of frames per second");+ if (typeof s.provider !== "string") p.push("provider is required: say, gemini, openai, elevenlabs, kokoro or files");+ if (!Array.isArray(s.lines) || !s.lines.length) p.push("lines must be a non-empty list");+ const ids = new Set();+ for (const [i, l] of (s.lines ?? []).entries()) {+ if (!l || typeof l.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(l.id)) p.push(`line ${i}: id must be letters, digits, - or _`);+ else if (ids.has(l.id)) p.push(`line ${i}: duplicate id '${l.id}'`); else ids.add(l.id);+ if (typeof l?.text !== "string" || !normalise(l.text).length) p.push(`line ${i}: text has no words`);+ if (l?.display !== undefined && typeof l.display !== "string") p.push(`line ${i}: display must be text`);+ if (l?.pauseAfter !== undefined && !(l.pauseAfter >= 0)) p.push(`line ${i}: pauseAfter is seconds >= 0`);+ if (l?.at !== undefined && !(Number.isInteger(l.at) && l.at >= 0)) p.push(`line ${i}: at is a frame number >= 0`);+ }+ return p;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/elevenlabs.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/elevenlabs.mjsnew file mode 100644index 0000000..00397ca--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/elevenlabs.mjs@@ -0,0 +1,16 @@+// ElevenLabs text to speech. CLOUD: the line's text is sent to ElevenLabs. Key: ELEVENLABS_API_KEY.+// voice: { id: "<voice_id>", model: "eleven_multilingual_v2", stability: 0.5, similarity: 0.75, seed: 7 }+import { writeFileSync } from "node:fs";+import { envKey, pcm16Wav, post } from "./util.mjs";++export const id = "elevenlabs", cloud = true;+export const about = "ElevenLabs (cloud: text goes to ElevenLabs)";+export const available = () => (envKey("ELEVENLABS_API_KEY") ? { ok: true } : { ok: false, why: "set ELEVENLABS_API_KEY in the environment" });+export const synth = async ({ text, voice = {}, raw }) => {+ const key = envKey("ELEVENLABS_API_KEY");+ if (!voice.id) throw new Error("elevenlabs: voice.id (a voice_id from your ElevenLabs voice library) is required");+ const body = { text, model_id: voice.model ?? "eleven_multilingual_v2", voice_settings: { stability: voice.stability ?? 0.5, similarity_boost: voice.similarity ?? 0.75 }, ...(voice.seed !== undefined ? { seed: voice.seed } : {}) };+ // pcm_24000: raw 16-bit mono, no codec in the way+ const pcm = await post(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice.id)}?output_format=pcm_24000`, { "Content-Type": "application/json", "xi-api-key": key.value }, body, "elevenlabs");+ const out = raw + ".wav"; writeFileSync(out, pcm16Wav(pcm, 24000)); return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/files.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/files.mjsnew file mode 100644index 0000000..df2167c--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/files.mjs@@ -0,0 +1,14 @@+// Bring your own recordings: one audio file per line id in voice.dir (relative to the script), named+// <id>.wav (or .aiff, .flac, .mp3, .m4a). Nothing is synthesised; the takes still go through trim,+// level, timing and the round-trip check like any other voice.+import { existsSync } from "node:fs";+import { join } from "node:path";++export const id = "files", cloud = false;+export const about = "your own recordings, one file per line id";+export const available = () => ({ ok: true });+export const synth = async ({ voice = {}, lineId, scriptDir }) => {+ const dir = join(scriptDir, voice.dir ?? "takes");+ for (const ext of ["wav", "aiff", "flac", "mp3", "m4a"]) { const f = join(dir, `${lineId}.${ext}`); if (existsSync(f)) return f; }+ throw new Error(`files: no recording for line '${lineId}' in ${dir} (want ${lineId}.wav)`);+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/gemini.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/gemini.mjsnew file mode 100644index 0000000..3a7613f--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/gemini.mjs@@ -0,0 +1,22 @@+// Google Gemini TTS over REST. CLOUD: the line's text is sent to Google. Key: GEMINI_API_KEY or GOOGLE_API_KEY.+// voice: { name: "Alnilam", style: "a warm storyteller...", model: "gemini-3.8-flash-tts" }+// The request is the one the ghost film recorded with (clawd-ghost-of-last-session/voice/tts.py). Lesson 51:+// this voice dropped an ALL-CAPS word without a sound; write such a word plain, in quotes, and let `check` prove it.+import { writeFileSync } from "node:fs";+import { envKey, pcm16Wav, post } from "./util.mjs";++export const id = "gemini", cloud = true;+export const about = "Google Gemini TTS (cloud: text goes to Google)";+export const available = () => (envKey("GEMINI_API_KEY", "GOOGLE_API_KEY") ? { ok: true } : { ok: false, why: "set GEMINI_API_KEY (or GOOGLE_API_KEY) in the environment" });+export const synth = async ({ text, voice = {}, raw }) => {+ const key = envKey("GEMINI_API_KEY", "GOOGLE_API_KEY"), model = voice.model ?? "gemini-3.8-flash-tts";+ const part = { text, ...(voice.style ? { speech_metadata: { style: voice.style } } : {}) };+ const body = { contents: [{ role: "user", parts: [part] }], generationConfig: { responseModalities: ["AUDIO"], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: voice.name ?? "Alnilam" } } } } };+ const res = JSON.parse((await post(`https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent`, { "Content-Type": "application/json", "x-goog-api-key": key.value }, body, "gemini")).toString("utf8"));+ const data = res?.candidates?.[0]?.content?.parts?.find((p) => p.inlineData)?.inlineData?.data;+ if (!data) throw new Error("gemini: the answer carried no audio");+ const audio = Buffer.from(data, "base64"), out = raw + ".wav";+ // Gemini answers raw 24 kHz 16-bit mono PCM (sometimes already a RIFF file)+ writeFileSync(out, audio.subarray(0, 4).toString() === "RIFF" ? audio : pcm16Wav(audio, 24000));+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/kokoro.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/kokoro.mjsnew file mode 100644index 0000000..928c5d3--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/kokoro.mjs@@ -0,0 +1,17 @@+// Kokoro (hexgrad/kokoro, Apache-2.0 code and weights), local and offline, only when a CLI is on PATH:+// `kokoro-tts` (pip install kokoro-tts; usage `kokoro-tts in.txt out.wav --voice af_heart --speed 1`).+// voice: { name: "af_heart", speed: 1, lang: "en-us" }+import { execFileSync } from "node:child_process";+import { writeFileSync } from "node:fs";+import { which } from "./util.mjs";++export const id = "kokoro", cloud = false;+export const about = "Kokoro (local, Apache-2.0)";+const cli = () => which("kokoro-tts") ?? which("kokoro");+export const available = () => (cli() ? { ok: true } : { ok: false, why: "no kokoro CLI on PATH. Get one with `pipx install kokoro-tts` (it downloads the Apache-2.0 Kokoro-82M model and voices on first run), then check `kokoro-tts --help`" });+export const synth = async ({ text, voice = {}, raw }) => {+ const txt = raw + ".txt", out = raw + ".wav";+ writeFileSync(txt, text);+ execFileSync(cli(), [txt, out, "--voice", String(voice.name ?? "af_heart"), "--speed", String(voice.speed ?? 1), ...(voice.lang ? ["--lang", String(voice.lang)] : [])], { stdio: ["ignore", "ignore", "pipe"] });+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/openai.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/openai.mjsnew file mode 100644index 0000000..e640f4a--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/openai.mjs@@ -0,0 +1,15 @@+// OpenAI speech endpoint. CLOUD: the line's text is sent to OpenAI. Key: OPENAI_API_KEY.+// voice: { name: "alloy", model: "gpt-4o-mini-tts", instructions: "calm, warm", speed: 1 }+import { writeFileSync } from "node:fs";+import { envKey, post } from "./util.mjs";++export const id = "openai", cloud = true;+export const about = "OpenAI speech (cloud: text goes to OpenAI)";+export const available = () => (envKey("OPENAI_API_KEY") ? { ok: true } : { ok: false, why: "set OPENAI_API_KEY in the environment" });+export const synth = async ({ text, voice = {}, raw }) => {+ const key = envKey("OPENAI_API_KEY");+ const body = { model: voice.model ?? "gpt-4o-mini-tts", voice: voice.name ?? "alloy", input: text, response_format: "wav", ...(voice.instructions ? { instructions: voice.instructions } : {}), ...(voice.speed ? { speed: voice.speed } : {}) };+ const out = raw + ".wav";+ writeFileSync(out, await post("https://api.openai.com/v1/audio/speech", { "Content-Type": "application/json", Authorization: `Bearer ${key.value}` }, body, "openai"));+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/say.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/say.mjsnew file mode 100644index 0000000..daec685--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/say.mjs@@ -0,0 +1,18 @@+// macOS built-in `say`: zero setup, offline, draft quality. Good for timing a cut before a real voice.+// DRAFTS ONLY: Apple's macOS licence allows the system voices for personal, non-commercial content.+// Never publish or commit a `say` take; re-voice with kokoro, files or a cloud provider before shipping.+// voice: { name: "Samantha", rate: 175 } (`say -v '?'` lists the voices on this Mac)+import { execFileSync } from "node:child_process";+import { which } from "./util.mjs";++export const id = "say", cloud = false;+export const about = "macOS `say` (offline, draft quality; Apple licenses the voices for personal, non-commercial use, so re-voice before publishing)";+export const available = () => (process.platform === "darwin" && which("say") ? { ok: true } : { ok: false, why: "`say` is macOS only; use kokoro, files or a cloud provider" });+export const synth = async ({ text, voice = {}, raw }) => {+ const out = raw + ".aiff", args = ["-o", out];+ if (voice.name) args.push("-v", String(voice.name));+ if (voice.rate) args.push("-r", String(voice.rate));+ // the text goes in on stdin (`-f -`), never as an argument: a line starting with "-" stays a line+ execFileSync("say", [...args, "-f", "-"], { input: text, stdio: ["pipe", "ignore", "pipe"] });+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/util.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/util.mjsnew file mode 100644index 0000000..137e474--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/narrate/providers/util.mjs@@ -0,0 +1,32 @@+// Shared bits for the providers: PATH lookup, a key read from the environment (never printed), and a+// POST that returns bytes and reports a failure WITHOUT echoing headers (the key lives there).+import { accessSync, constants, statSync } from "node:fs";+import { delimiter, join } from "node:path";++/**+ * A program's full path from the PATH, or null. Read in node rather than by running `which`, which+ * Windows does not have: there every PATHEXT ending (.EXE, .CMD, ...) is tried, and a folder with a space+ * is just a folder. `o` overrides the PATH, PATHEXT and platform (the tests use it).+ */+export const which = (cmd, o = {}) => {+ const win = o.win ?? process.platform === "win32", path = o.path ?? process.env.PATH ?? process.env.Path ?? "";+ const exts = win ? [...String(o.pathext ?? process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean)] : [""];+ for (const dir of path.split(delimiter).filter(Boolean)) for (const e of exts) {+ const f = join(dir.replace(/^"(.*)"$/, "$1"), cmd + e);+ try { if (!statSync(f).isFile()) continue; if (!win) accessSync(f, constants.X_OK); return f; } catch { /* not here */ }+ }+ return null;+};+export const envKey = (...names) => { for (const n of names) if (process.env[n]?.trim()) return { name: n, value: process.env[n].trim() }; return null; };+export const post = async (url, headers, body, what) => {+ const r = await fetch(url, { method: "POST", headers, body: typeof body === "string" ? body : JSON.stringify(body) });+ if (!r.ok) { const t = (await r.text()).slice(0, 400).replace(/[A-Za-z0-9_-]{32,}/g, "<redacted>"); throw new Error(`${what}: HTTP ${r.status} ${t}`); }+ return Buffer.from(await r.arrayBuffer());+};+// raw 16-bit little-endian mono PCM -> a WAV container ffmpeg can read+export const pcm16Wav = (pcm, sr, ch = 1) => {+ const h = Buffer.alloc(44);+ h.write("RIFF", 0); h.writeUInt32LE(36 + pcm.length, 4); h.write("WAVEfmt ", 8); h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(ch, 22);+ h.writeUInt32LE(sr, 24); h.writeUInt32LE(sr * 2 * ch, 28); h.writeUInt16LE(2 * ch, 32); h.writeUInt16LE(16, 34); h.write("data", 36); h.writeUInt32LE(pcm.length, 40);+ return Buffer.concat([h, pcm]);+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/overlay.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/overlay.mjsindex 14ba363..e75967c 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/overlay.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/overlay.mjs@@ -4,12 +4,23 @@// example keeps importing "../core"; a launch film can import "./mechanicalLepidoptera" and get// the committed example. Order matters: engine/src first, so the engine always wins a name clash.// tsconfig.json says the same thing to tsc with "rootDirs", so the checker and the bundler agree.-import { existsSync, statSync } from "node:fs";+import { createHash } from "node:crypto";+import { existsSync, readFileSync, statSync } from "node:fs";import { dirname, join, relative, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";const ENGINE = resolve(dirname(fileURLToPath(import.meta.url)), "..");-export const ROOTS = [join(ENGINE, "src"), resolve(ENGINE, "../example/src")];+// A LINKED PROJECT (scaffold.mjs --linked): a folder of its own films that runs the installed engine's+// tools from its own working directory. Its src/ joins the tree first, so a project film's "./core"+// resolves to the engine's and a project never needs a copy of the engine (a brand launch film was+// built in a forked engine for exactly this reason). When cwd is the engine itself nothing changes.+// A folder counts as a linked project only when it carries the marker scaffold --linked writes: any other+// repo run from (one with its own src/hosts/page.ts, say) must never replace the engine's files.+export const PROJECT_MARKER = "anidoodle-project.json";+const PROJECT = resolve(process.cwd(), "src"), LINKED = PROJECT !== join(ENGINE, "src") && existsSync(PROJECT) && existsSync(resolve(process.cwd(), PROJECT_MARKER));+export const ROOTS = [...(LINKED ? [PROJECT] : []), join(ENGINE, "src"), resolve(ENGINE, "../example/src")];+/** An engine file by its path inside the engine (src/canvas-core/film.ts): a linked project's copy if it has one, else the engine's. */+export const enginePath = (rel) => (LINKED && existsSync(resolve(rel)) ? resolve(rel) : join(ENGINE, rel));const EXT = ["", ".ts", ".tsx", ".js", ".mjs", "/index.ts", "/index.js"];const file = (p) => { for (const e of EXT) { const f = p + e; if (existsSync(f) && statSync(f).isFile()) return f; } return null; };const rootOf = (p) => ROOTS.find((r) => p === r || p.startsWith(r + sep));@@ -25,9 +36,39 @@ export const resolveOverlay = (spec, dir) => {return null;};+// THREE. A film imports "three" by its bare name and gets three.js 0.170.0, hash-pinned+// (vendor/three/PROVENANCE.md): the same bytes on every machine. The repository vendors the file; the+// installed plugin leaves it out (plugin directories refuse a file this size) and gets the same npm+// release from `npm install` (package.json pins three 0.170.0). Either way the hash must match.+export const THREE_SHA256 = "ce1fa418de16a19495a9f72495580e3015d7745c296d3ce0485897f902ddedfb";+export const threeCandidates = (engine = ENGINE, cwd = process.cwd()) => [...new Set([join(engine, "vendor/three/three.module.js"), join(engine, "node_modules/three/build/three.module.js"), join(cwd, "node_modules/three/build/three.module.js")])];+export const resolveThree = (engine = ENGINE, read = (f) => (existsSync(f) ? readFileSync(f) : null)) => {+ for (const f of threeCandidates(engine, engine === ENGINE ? process.cwd() : engine)) {+ const bytes = read(f); if (!bytes) continue;+ const got = createHash("sha256").update(bytes).digest("hex");+ if (got !== THREE_SHA256) throw new Error(`three.js at ${f} is not the pinned 0.170.0 build (sha256 ${got.slice(0, 12)}...): run npm install in the engine folder so package.json's exact version is used`);+ return f;+ }+ throw new Error(`three.js is not installed: run npm install in the engine folder (${engine}); it pins three 0.170.0`);+};+let threeModule = null;+export const THREE_MODULE_PATH = () => (threeModule ??= resolveThree());export const overlay = {name: "anidoodle-overlay",setup(b) {+ b.onResolve({ filter: /^three$/ }, () => { try { return { path: THREE_MODULE_PATH() }; } catch (e) { return { errors: [{ text: e.message }] }; } });+ // FONT FILES. A launch look imports its typefaces by path (import serif from "../../assets/fonts/X.ttf"):+ // the bytes are inlined as { path, format, data } so the film carries them and nothing is fetched. A path+ // that is not there is a build error that says where to put the file.+ b.onResolve({ filter: /\.(ttf|otf|woff2)$/i }, (a) => {+ const want = resolve(a.resolveDir, a.path), f = existsSync(want) ? want : resolveOverlay(a.path, a.resolveDir);+ if (!f) return { errors: [{ text: `font file not found: ${a.path} (looked for ${want}). Put the font file (.ttf) there, or fix the import's path; the engine's own fonts are in engine/assets/fonts` }] };+ return { path: f, namespace: "anidoodle-font" };+ });+ b.onLoad({ filter: /.*/, namespace: "anidoodle-font" }, (a) => {+ const format = a.path.toLowerCase().split(".").pop(), rel = relative(ENGINE, a.path).split(sep).join("/");+ return { contents: `export default ${JSON.stringify({ path: rel, format, data: readFileSync(a.path).toString("base64") })};`, loader: "js" };+ });b.onResolve({ filter: /^\.\.?\// }, (a) => {const f = resolveOverlay(a.path, a.resolveDir);return f ? { path: f } : undefined;diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/pngio.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/pngio.mjsnew file mode 100644index 0000000..df46993--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/pngio.mjs@@ -0,0 +1,63 @@+// PNG IO. Just enough PNG to trim a logo's transparent margins and measure its ink, with no+// dependency: 8-bit greyscale, grey+alpha, RGB, RGBA and palette images, not interlaced. Anything else+// gets a message naming the fix (re-export as 8-bit RGBA), never a wrong answer.+import { deflateSync, inflateSync } from "node:zlib";++const SIG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);+const CRC = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })();+const crc32 = (buf) => { let c = 0xffffffff; for (const b of buf) c = CRC[(c ^ b) & 255] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };++/** PNG bytes -> { w, h, data: RGBA Uint8Array }. */+export const decodePng = (buf) => {+ if (!Buffer.isBuffer(buf) || buf.length < 8 || !buf.subarray(0, 8).equals(SIG)) throw new Error("not a PNG file");+ let pos = 8, w = 0, h = 0, depth = 0, type = 0, interlace = 0, palette = null, trns = null; const idat = [];+ while (pos < buf.length) {+ const len = buf.readUInt32BE(pos), kind = buf.toString("latin1", pos + 4, pos + 8), body = buf.subarray(pos + 8, pos + 8 + len); pos += 12 + len;+ if (kind === "IHDR") { w = body.readUInt32BE(0); h = body.readUInt32BE(4); depth = body[8]; type = body[9]; interlace = body[12]; }+ else if (kind === "PLTE") palette = body; else if (kind === "tRNS") trns = body; else if (kind === "IDAT") idat.push(body); else if (kind === "IEND") break;+ }+ if (depth !== 8) throw new Error(`PNG bit depth ${depth} is not read here: re-export the logo as an 8-bit RGBA PNG (or bring the SVG)`);+ if (interlace) throw new Error("interlaced PNGs are not read here: re-export without interlacing (or bring the SVG)");+ const ch = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[type]; if (!ch) throw new Error(`PNG colour type ${type} is not supported`);+ const raw = inflateSync(Buffer.concat(idat)), stride = w * ch, px = new Uint8Array(stride * h);+ for (let y = 0; y < h; y++) {+ const f = raw[y * (stride + 1)], src = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)), row = y * stride;+ for (let x = 0; x < stride; x++) {+ const a = x >= ch ? px[row + x - ch] : 0, b = y ? px[row - stride + x] : 0, c = x >= ch && y ? px[row - stride + x - ch] : 0;+ let v = src[x];+ if (f === 1) v += a; else if (f === 2) v += b; else if (f === 3) v += (a + b) >> 1;+ else if (f === 4) { const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c); v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c; }+ px[row + x] = v & 255;+ }+ }+ const data = new Uint8Array(w * h * 4);+ for (let i = 0; i < w * h; i++) {+ const s = i * ch, d = i * 4;+ if (type === 6) { data[d] = px[s]; data[d + 1] = px[s + 1]; data[d + 2] = px[s + 2]; data[d + 3] = px[s + 3]; }+ else if (type === 2) { data[d] = px[s]; data[d + 1] = px[s + 1]; data[d + 2] = px[s + 2]; data[d + 3] = 255; }+ else if (type === 0) { data[d] = data[d + 1] = data[d + 2] = px[s]; data[d + 3] = 255; }+ else if (type === 4) { data[d] = data[d + 1] = data[d + 2] = px[s]; data[d + 3] = px[s + 1]; }+ else { const k = px[s]; data[d] = palette[k * 3]; data[d + 1] = palette[k * 3 + 1]; data[d + 2] = palette[k * 3 + 2]; data[d + 3] = trns && k < trns.length ? trns[k] : 255; }+ }+ return { w, h, data };+};+/** { w, h, data: RGBA } -> PNG bytes (filter 0, which is plenty for logos). */+export const encodePng = ({ w, h, data }) => {+ const raw = Buffer.alloc((w * 4 + 1) * h); for (let y = 0; y < h; y++) Buffer.from(data.buffer, data.byteOffset + y * w * 4, w * 4).copy(raw, y * (w * 4 + 1) + 1);+ const chunk = (kind, body) => { const len = Buffer.alloc(4); len.writeUInt32BE(body.length); const kb = Buffer.concat([Buffer.from(kind, "latin1"), body]), c = Buffer.alloc(4); c.writeUInt32BE(crc32(kb)); return Buffer.concat([len, kb, c]); };+ const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 6;+ return Buffer.concat([SIG, chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);+};+/** Box of pixels with alpha over `min` (a PNG's transparent margin removed). -> [x, y, w, h], or null when it is empty. */+export const alphaBox = ({ w, h, data }, min = 8) => {+ let x0 = w, y0 = h, x1 = -1, y1 = -1;+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (data[(y * w + x) * 4 + 3] > min) { if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }+ return x1 < 0 ? null : [x0, y0, x1 - x0 + 1, y1 - y0 + 1];+};+export const crop = (img, [x, y, w, h]) => { const data = new Uint8Array(w * h * 4); for (let r = 0; r < h; r++) data.set(img.data.subarray(((y + r) * img.w + x) * 4, ((y + r) * img.w + x + w) * 4), r * w * 4); return { w, h, data }; };+/** Ink: the summed alpha, in whole-pixel units (a half-transparent pixel counts half). */+export const inkOf = ({ data }) => { let s = 0; for (let i = 3; i < data.length; i += 4) s += data[i]; return s / 255; };+/** Paint every visible pixel one colour, keeping its alpha (a white logo for a dark ground). */+export const tint = (img, [r, g, b]) => { const data = new Uint8Array(img.data); for (let i = 0; i < data.length; i += 4) { data[i] = r; data[i + 1] = g; data[i + 2] = b; } return { ...img, data }; };+/** Does the image have a solid (non-transparent) background? Corner pixels all opaque means yes. */+export const opaqueCorners = ({ w, h, data }) => [0, w - 1, (h - 1) * w, h * w - 1].every((i) => data[i * 4 + 3] > 245);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjsindex 0a97fa2..55abc1c 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/render.mjs@@ -9,6 +9,9 @@// matching two sharp renders at the shutter's ends: subframes at most --blur-px apart// (default 3 px), 1 on a still frame (the sharp frame, untouched), at most --blur-max (32).// Deterministic: the count is a function of the frame's pixels.+// Type, photos and anything drawn inside sharp() are NEVER blurred (hosts/instrument.ts): they+// are left out of the subframes and laid over the result sharp. Blurred type and faces read+// as violent motion (a brand launch film, critic round 2). --blur-all blurs everything, as before.// --shutter DEG the shutter angle: 180 (default, film's standard: half the frame interval) to 360// (the whole interval, the old --blur behaviour). 180-240 reads as natural motion.// --from/--to render only frames [from, to): for checking a passage, not for shipping. A range@@ -28,6 +31,8 @@// whatever sits behind the page shows through// .apng animated PNG, alpha kept, loops forever, plays in every browser// --width only applies to the silent formats; the MP4 is always the film's own size.+// Every render also writes <out>.film.json beside the file: the film id, frame range, blur, sha256 and+// the film's meta, so the checks on a delivered file never infer the film from its name.// --shapes 16x9,1x1,4x5,9x16 a launch template film in several frame shapes from ONE timeline: each// shape is re-composed by its layout (launchLayout.ts), never cropped, and rendered as the// film <film>-<shape> to out/<film>-<shape>.mp4, one after another, with the other flags.@@ -35,8 +40,9 @@ import { spawn, spawnSync, execFileSync } from "node:child_process";import { createHash } from "node:crypto";import { mkdirSync, writeFileSync } from "node:fs";import { cpus } from "node:os";-import { join, resolve } from "node:path";+import { basename, join, resolve } from "node:path";import { buildPage } from "./build-page.mjs";+import { enginePath } from "./overlay.mjs";import { detect } from "./detect.mjs";import * as playwright from "./adapters/playwright.mjs";import { defaultOutput, requireFilm } from "./names.mjs";@@ -58,7 +64,8 @@ const BLUR = arg("blur", "1") === "auto" ? "auto" : Number(arg("blur", 1)), SHUTif (BLUR !== "auto" && (!Number.isInteger(BLUR) || BLUR < 1)) { console.error(`--blur wants a whole number of subframes >= 1 or 'auto', got '${arg("blur")}'`); process.exit(2); }if (!(SHUTTER > 0 && SHUTTER <= 360)) { console.error(`--shutter wants an angle in (0, 360] degrees, got '${arg("shutter")}'`); process.exit(2); }if (!Number.isInteger(BMAX) || BMAX < 2 || !(BPX > 0)) { console.error(`--blur-max wants a whole number >= 2 and --blur-px a number > 0`); process.exit(2); }-const BLURRED = BLUR === "auto" || BLUR > 1, BSPEC = BLUR === "auto" ? { samples: 0, shutter: SHUTTER, max: BMAX, px: BPX } : { samples: BLUR, shutter: SHUTTER };+const SHARP = !process.argv.includes("--blur-all"); // type and photos stay sharp under the blur unless asked otherwise+const BLURRED = BLUR === "auto" || BLUR > 1, BSPEC = BLUR === "auto" ? { samples: 0, shutter: SHUTTER, max: BMAX, px: BPX, sharp: SHARP } : { samples: BLUR, shutter: SHUTTER, sharp: SHARP };const scale = Number(arg("scale", 1)), fmt = (arg("out", "").match(/\.(gif|webm|apng)$/i)?.[1] ?? "mp4").toLowerCase(), workers = Number(arg("workers", Math.max(1, Math.min(4, Math.floor(cpus().length / 2)))));const HASHES = arg("hashes", null) ? new Map() : null;const RANGE_ASKED = process.argv.includes("--from") || process.argv.includes("--to");@@ -92,7 +99,7 @@ const drawAt = (n, w) => (posterAt(n) ? session.poster(n, POSTER, FADE, BLURRED// a film whose cuts sit on its beat grid (meta.score.grid) must hear its score at that grid's tempoif (meta.score?.grid && Math.abs(meta.score.tempo / meta.bpm - 1) > 0.005) { console.error(`render: the score plays at ${meta.score.tempo.toFixed(2)} bpm but this film's cuts sit on a ${meta.bpm} bpm grid (${((meta.score.tempo / meta.bpm - 1) * 100).toFixed(1)} %, limit 0.5 %): the cuts would drift off the downbeats. Play the score at the film's bpm and make the film whole bars of it (launchTemplate does), or compose a 1-bar stretch section`); process.exit(2); }console.log(`film: "${meta.title}" ${meta.W}x${meta.H} @ ${meta.fps} fps, ${N} frames, ${meta.bpm} bpm, scale ${scale}, ${session.workers} page(s)`);-if (BLURRED) console.log(`motion blur: ${BLUR === "auto" ? `adaptive (subframes <= ${BPX} px apart, max ${BMAX})` : `${BLUR} subframes per frame`}, ${SHUTTER}-degree shutter, linear light`);+if (BLURRED) console.log(`motion blur: ${BLUR === "auto" ? `adaptive (subframes <= ${BPX} px apart, max ${BMAX})` : `${BLUR} subframes per frame`}, ${SHUTTER}-degree shutter, linear light, ${SHARP ? "type and photos kept sharp" : "EVERYTHING blurred (--blur-all), type and photos too"}`);if (ranged) console.log(`range render: frames [${FROM}, ${TO}) of ${N}, silent by design`);// audio: the page returns its embedded recorded track or its code-built mix -> WAV here@@ -100,7 +107,8 @@ if (ranged) console.log(`range render: frames [${FROM}, ${TO}) of ${N}, silent bmkdirSync(resolve(".tmp"), { recursive: true }); const wav = resolve(`.tmp/${film}.wav`), a = ranged ? null : await session.audio(48000);if (a) writeFileSync(wav, float32Wav(a));if (a) { // the audio report: loudness and true peak, and the score's fit against the picture's grid- const { build } = await import("esbuild"), js = (await build({ entryPoints: [resolve("src/canvas-core/music/meter.ts")], bundle: true, write: false, format: "esm", platform: "neutral", logLevel: "error" })).outputFiles[0].text;+ // the meter is an engine file: a linked project (scaffold --linked) runs from its own folder and has no copy+ const { build } = await import("esbuild"), js = (await build({ entryPoints: [enginePath("src/canvas-core/music/meter.ts")], bundle: true, write: false, format: "esm", platform: "neutral", logLevel: "error" })).outputFiles[0].text;const { loudness, truePeak } = await import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));const pcm = new Float32Array(Uint8Array.from(Buffer.from(a.float32, "base64")).buffer), L = new Float32Array(a.frames), R = new Float32Array(a.frames);for (let i = 0; i < a.frames; i++) { L[i] = pcm[2 * i]; R[i] = pcm[2 * i + 1]; }@@ -129,7 +137,7 @@ const done = new Promise((res, rej) => ff.on("close", (c) => (c ? rej(new Error(const cost = [], pending = new Map(); let next, write;const pump = async () => { while (pending.has(write)) { const b = pending.get(write); pending.delete(write); if (!ff.stdin.write(b)) await new Promise((r) => ff.stdin.once("drain", r)); write++; } };next = FROM; write = FROM;-await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = await drawAt(n, w); if (HASHES) HASHES.set(n, createHash("md5").update(f.png).digest("hex")); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs, samples: f.samples ?? 1 }); pending.set(n, f.png); await pump(); } }));+await Promise.all(Array.from({ length: session.workers }, async (_, w) => { while (next < TO) { const n = next++; while (n - write > session.workers * 3) await new Promise((r) => setTimeout(r, 5)); const f = await drawAt(n, w); if (HASHES) HASHES.set(n, createHash("md5").update(f.png).digest("hex")); cost.push({ n, shot: f.shot, draw: f.drawMs, enc: f.encodeMs, rt: f.roundTripMs, samples: f.samples ?? 1, sharp: f.sharpPx ?? 0, typeInLayers: f.typeInLayers ?? 0 }); pending.set(n, f.png); await pump(); } }));await pump(); ff.stdin.end(); await done;const wall = (Date.now() - t0) / 1000;if (HASHES) { const hf = resolve(arg("hashes")); mkdirSync(join(hf, ".."), { recursive: true }); writeFileSync(hf, [...HASHES].sort((a, b) => a[0] - b[0]).map(([n, h]) => `${n} ${h}`).join("\n") + "\n"); console.log(`frame hashes -> ${hf}`); }@@ -151,6 +159,22 @@ for (const n of probe) fwd.push(await hashOf(n, 0)); for (const n of [...probe].const same = probe.filter((_, i) => fwd[i] === rev[i]).length;console.log(`\ndeterminism: ${same}/${probe.length} probe frames${BLURRED ? ` (blurred, ${BLUR === "auto" ? "adaptive" : `${BLUR} subframes`}, ${SHUTTER} degrees)` : ""} hash-identical (forward on page 0 vs reversed on page ${session.workers - 1})${same === probe.length ? "" : " -> fall back to PSNR > 45 dB in the Phase 2 gate"}`);await session.close();+// THE SIDECAR. <out>.film.json says which film and which frames this file is, so the checks that read a+// delivered file (verify-export, motionscan, soundcheck) never have to guess the film from its name: the+// A brand film's deliverables were called brandLaunch-v12.mp4 while the film was brandHook, and verify-export+// could not find them. The sha256 ties the sidecar to these exact bytes; a re-encode or a rename-and-+// replace is caught by comparing it. The file is named without its folder: the sidecar travels with the+// film, and an absolute path would carry the maker's home folder with it.+{+ const { readFileSync } = await import("node:fs"), sha = createHash("sha256").update(readFileSync(out)).digest("hex");+ const pick = ({ title, W, H, fps, bpm, durationFrames, kind, holds, quiet, sync, captions, poster, motion, checks, shots }) => ({ title, W, H, fps, bpm, durationFrames, kind, holds, quiet, sync, captions, poster, motion, checks, shots });+ writeFileSync(`${out}.film.json`, JSON.stringify({ film, file: basename(out), sha256: sha, frames: [FROM, TO], scale, blur: BLURRED ? { samples: BLUR, shutter: SHUTTER, sharp: SHARP } : null, poster: POSTER, meta: pick(meta) }, null, 1) + "\n");+}+const sharpFrames = cost.filter((c) => c.sharp > 0).length;+if (BLURRED && SHARP) console.log(`blur mask: type and photos kept sharp on ${sharpFrames} of ${cost.length} frames`);+// the mask only sees type drawn on the frame's own canvas: type composited from an offscreen layer blurs with it (instrument.ts)+const layerTypeFrames = cost.filter((c) => c.typeInLayers > 0).length;+if (BLURRED && SHARP && layerTypeFrames) console.log(` NOTE ${layerTypeFrames} frame(s) composited type from layers that blurred: that type is NOT kept sharp. Draw it on the frame's canvas, not in a layer, to keep it crisp`);const pr = execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,codec_name,width,height,nb_frames,duration", "-of", "csv=p=0", out]).toString().trim().split("\n");-console.log(`\noutput: ${out}`); pr.forEach((l) => console.log(` ${l}`));+console.log(`\noutput: ${out}\nsidecar: ${out}.film.json`); pr.forEach((l) => console.log(` ${l}`));if (fmt === "mp4" && !ranged) { const t = firstFrameBlank(out); if (t.blank) console.log(`\nWARNING frame 0 is near-blank (${t.detail}). Platforms use frame 0 as the thumbnail: re-render with --poster-frame N (a legible frame: the wall, the logo).`); }diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/scaffold.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/scaffold.mjsindex 1ce7de2..d647f19 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/scaffold.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/scaffold.mjs@@ -1,6 +1,8 @@// SCAFFOLD. Turn the skill's engine into a working project: a still, a film, or both.//// node <skill>/engine/tools/scaffold.mjs <dir> [--still myPicture] [--film myFilm] [--duration seconds] [--size WxH | --format 9x16] [--fps N] [--bpm N] [--example]+// node <skill>/engine/tools/scaffold.mjs <dir> --linked --film myFilm [--world] [...] a project that USES the engine, no copy;+// --world starts the film as one world under one camera (worldfilm.mjs), the default for launch films//// The engine ships as parts, not as a project: `engine/src` holds the portable art core and the// one page host, `example/src` holds the worked butterfly. A film needs them in ONE tree, because@@ -17,8 +19,9 @@// use; the launch KIT (launchKit, kinetic, launchCut, launchTemplate, launchExample)// always ships, because that is what your own launch film is built on.import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";-import { dirname, join, resolve, sep } from "node:path";+import { dirname, join, relative, resolve, sep } from "node:path";import { fileURLToPath } from "node:url";+import { PROJECT_MARKER } from "./overlay.mjs";const HERE = dirname(fileURLToPath(import.meta.url));const ENGINE = resolve(HERE, "..");@@ -63,12 +66,60 @@ const ownFilmFiles = () => {for (const f of files) if (!reach.has(f)) out.add(f);return out;};+// --linked: a project of the person's own, beside their brand files and photos, that USES the installed+// engine instead of copying it. Only the film, its host page, a tsconfig that sees the engine's modules+// and a package.json whose scripts call the engine's tools are written. The tools run from the project+// folder (cwd); overlay.mjs puts the project's src/ in front of the engine's, so "./core" resolves to the+// engine. An engine update reaches every linked project; nothing is forked (lesson X4 from a brand launch film).+if (opt.linked) {+ if (still || opt.example) die("--linked takes --film only (a still or the example need the full copy)");+ if (!film) die("--linked needs --film <name>");+ const mod = join(target, "src/canvas-core", `${film}.ts`), host = join(target, "src/hosts", `page-${film}.ts`);+ if (existsSync(mod) || existsSync(host)) die(`${film} already exists in ${target}; refusing to overwrite`);+ mkdirSync(join(target, "src/canvas-core"), { recursive: true }); mkdirSync(join(target, "src/hosts"), { recursive: true });+ const rel = (p) => relative(target, p).split(sep).join("/");+ if (opt.world) { const { worldFilmSource } = await import("./worldfilm.mjs"); writeFileSync(mod, worldFilmSource(film, { format: opt.format ?? "16x9", fps, ...(opt.bpm ? { bpm } : {}) })); } // the one-world starter (worldfilm.mjs): the default for a motion or launch film+ else writeFileSync(mod, `// ${film}: a film in a linked project. "./core", "./film" and every kit module come from the engine at+// ${rel(join(ENGINE, "src"))} (tools/overlay.mjs). Keep this folder for the film's own modules, assets and facts.+import { rng, type Ctx, type Env } from "./core";+import type { Film } from "./film";++const FPS = ${fps}, BPM = ${bpm}, DURATION = ${durationFrames};+const draw = (ctx: Ctx, local: number, env: Env) => {+ const W = env.W * env.scale, H = env.H * env.scale, r = rng(1), t = local / DURATION;+ ctx.fillStyle = "#12161c"; ctx.fillRect(0, 0, W, H);+ for (let i = 0; i < 90; i++) { const a = r() * Math.PI * 2, rad = (0.08 + r() * 0.36) * Math.min(W, H); ctx.globalAlpha = 0.25 + r() * 0.6; ctx.fillStyle = "#e8e3d2"; ctx.beginPath(); ctx.arc(W / 2 + Math.cos(a + t * Math.PI * 2) * rad, H / 2 + Math.sin(a + t * Math.PI * 2) * rad, (1 + r() * 2.5) * env.scale, 0, Math.PI * 2); ctx.fill(); }+ ctx.globalAlpha = 1;+};+export const ${film}: Film = {+ meta: { title: "${film}", W: ${size[0]}, H: ${size[1]}, fps: FPS, bpm: BPM, durationFrames: DURATION },+ assets: { images: {} },+ shots: [{ id: "one", start: 0, end: DURATION, draw }],+};+`);+ writeFileSync(host, `import { ${film} } from "../canvas-core/${film}";\nimport { mountFilm } from "./page";\nmountFilm(${film});\n`);+ const eng = rel(ENGINE);+ if (!existsSync(join(target, "tsconfig.json"))) writeFileSync(join(target, "tsconfig.json"), JSON.stringify({ compilerOptions: { target: "ES2022", module: "ESNext", moduleResolution: "bundler", strict: true, noEmit: true, skipLibCheck: true, lib: ["DOM", "ES2022"], rootDirs: ["src", `${eng}/src`], paths: { three: [`${eng}/vendor/three/types/Three.d.ts`, `${eng}/vendor/three/three-untyped.d.ts`] } }, include: ["src"] }, null, 2) + "\n");+ // npm runs a script through a shell (sh, or cmd.exe on Windows): the tool path is quoted so a folder+ // with a space stays one word. Single quotes on sh (nothing inside expands), double quotes on cmd.exe.+ const quote = (p) => (process.platform === "win32" ? `"${p}"` : `'${p.replace(/'/g, `'\\''`)}'`);+ const tool = (t) => `node ${quote(join(ENGINE, "tools", t))}`;+ // the marker that makes this folder a linked project: overlay.mjs puts its src/ in front of the engine's+ // only when this file is here, so another repo that happens to have a src/ never replaces engine files+ if (!existsSync(join(target, PROJECT_MARKER))) writeFileSync(join(target, PROJECT_MARKER), JSON.stringify({ linked: true, film, engine: ENGINE }, null, 2) + "\n");+ if (!existsSync(join(target, "package.json"))) writeFileSync(join(target, "package.json"), JSON.stringify({ name: film.toLowerCase(), private: true, type: "module", dependencies: { three: "0.170.0" }, scripts: { still: `${tool("still.mjs")} ${film}`, render: `${tool("render.mjs")} ${film}`, framecheck: `${tool("framecheck.mjs")} ${film}`, ship: `${tool("ship.mjs")} ${film}` } }, null, 2) + "\n");+ console.log(`linked project ${target}\n src/canvas-core/${film}.ts, src/hosts/page-${film}.ts, tsconfig.json, package.json, ${PROJECT_MARKER}\n engine: ${ENGINE}\nnext (from ${target}):\n ${tool("still.mjs")} ${film} --out out/look.png\n ${tool("render.mjs")} ${film}\n ${tool("ship.mjs")} ${film}`);+ process.exit(0);+}const skip = opt.example ? new Set() : ownFilmFiles();mkdirSync(target, { recursive: true });cpSync(join(ENGINE, "src"), join(target, "src"), { recursive: true, filter: (f) => !skip.has(f) });cpSync(join(ENGINE, "tools"), join(target, "tools"), { recursive: true });for (const f of ["package.json", "package-lock.json", "tsconfig.json"]) if (existsSync(join(ENGINE, f))) cpSync(join(ENGINE, f), join(target, f));+// three.js for 3D shots: the vendored, hash-pinned build and its types where the install has them; the+// plugin install has neither, and npm install brings the same pinned release (package.json, overlay.mjs)+if (existsSync(join(ENGINE, "vendor"))) cpSync(join(ENGINE, "vendor"), join(target, "vendor"), { recursive: true });if (opt.example) {const ex = join(SKILL, "example", "src");diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/ship.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/ship.mjsnew file mode 100644index 0000000..b092d7f--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/ship.mjs@@ -0,0 +1,181 @@+// SHIP. The one command a film passes before anyone is shown it, for ANY film (hand-built or template),+// on the exact file that will be delivered. On a brand launch film nine versions reached the director with no+// check at all, and the checks that did run passed while blind (reading time "N/A", verify-export unable+// to resolve a renamed file). Ship runs every check on the file, prints one table and writes a critic-+// ready sheet. Its rule: a check that cannot look is a FAIL, never a pass.+//+// node tools/ship.mjs <film|file.mp4> [--file out/x.mp4] [--shapes 16x9,9x16 [--file out/x-{shape}.mp4]]+// [--every 1] [--zones warn] [--quick] [--sfx stem.wav]+// [--review reviews/<film>.json] [--out <dir>]+//+// input the file exists, is not empty, decodes; its sidecar (render's <file>.film.json) names this+// film and covers the whole film (a range render never ships)+// frame framecheck: edges, reading time on every drawn text, safe zones, layout, the last second,+// the end card landing once, head sizes, fonts (framerules.mjs)+// verify verify-export --delivery on the file: size, frames, duration, score, sync, true peak,+// loudness, a legible frame 0, no placeholder assets+// gate determinism, the contract scan, dead air on the file (skipped only with --quick, and then+// the verdict is QUICK, never PASS)+// motion motionscan on the file (slide cuts, carousels, dissolves, temperament) and layerscan on the+// film (exit residue, fast type, shapes over faces, translucent brand colour), lock (approved+// shots unchanged): Lane MOTION's scanners, one row per check; a check that reports N/A did not look+// and FAILS, unless the film names why there is nothing to check in meta.checks.none (then NONE)+// sound the engine's score: soundcheck on the file. An external track (meta.checks.music.track):+// track.mjs check on the file (holes, the ending against the track's own last note) and+// soundcheck --sfx <stem> (effects carry no pitch under someone else's music); verify-export+// checks the mix came from the pinned take. cues --check whenever the film declares cues+// facts every claim the film declares is in its facts ledger with a source+// review reviews/<film>.json: an open P0 from a critic fails; open P1s are listed; the person's last+// three notes are printed to re-read against the new sheet+// length meta.checks.length: over max fails, over target flags, and the reading floor is printed+// sheet <file>.ship/sheet.jpg beside the file (a frame every 2 s, every shot start, the last frame),+// SHIP.md and ship.json: the table to attach whenever a version is shown+// A check that cannot look (no temperament, no brand colours, no review ledger, no length budget, text with+// no claims) FAILS; a film that truly has nothing there declares it, with a reason, in meta.checks.none+// { "<row>": "<reason>" }, and the row is NONE with the reason printed. --every above 1 is a QUICK run.+// Exit 0 PASS, 1 FAIL (or QUICK), 2 bad input.+import { spawnSync } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { basename, dirname, join, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { isMain } from "./is-main.mjs";+import { knownFilms, requireFilm, SHAPE_NAMES } from "./names.mjs";+import { filmOfFile, readSidecar } from "./sidecar.mjs";+import { frameCheck, frameReport } from "./framecheck.mjs";+import { blindRow, lengthRow, reviewRows, row, scannerRows, sheetFrames, shipEvery, verdict } from "./shiprules.mjs";++const TOOLS = dirname(fileURLToPath(import.meta.url));+const USAGE = "node tools/ship.mjs <film|file.mp4> [--file out/x.mp4] [--shapes 16x9,9x16] [--every 1] [--zones warn] [--quick] [--review reviews/<film>.json] [--out dir]";+++/** Run a tool, read its verdict from the exit code. A tool that could not run (exit 2, or missing) is a FAIL. */+export const runTool = (script, args, { label = script, none = /\bN\/A\b/ } = {}) => {+ const path = join(TOOLS, script);+ if (!existsSync(path)) return row(label, "FAIL", `tools/${script} is not installed: this check cannot look, so it fails`);+ const r = spawnSync(process.execPath, [path, ...args], { encoding: "utf8", maxBuffer: 1 << 27 });+ const out = `${r.stdout ?? ""}${r.stderr ?? ""}`, lines = out.split("\n"), verdict = [...lines].reverse().find((l) => /^[A-Z][A-Z-]+:\s/.test(l.trim())) ?? lines.filter(Boolean).pop() ?? "";+ const fails = lines.filter((l) => /^\s*FAIL\b/.test(l)).map((l) => l.trim());+ if (r.status === 0) return row(label, none.test(verdict) ? "NONE" : "PASS", verdict.trim());+ if (r.status === 1) return row(label, "FAIL", verdict.trim(), fails.length ? fails : lines.filter(Boolean).slice(-6));+ return row(label, "FAIL", `could not run (exit ${r.status}): ${out.trim().split("\n").slice(-2).join(" ")}`);+};++/**+ * A scanner from another lane, run in-process: one row per check it reports (shiprules.mjs scannerRows).+ * FAIL fails, PASS passes, NONE (looked, nothing there) is NONE, and N/A (did not look) FAILS unless the+ * film declares why there is nothing to check (meta.checks.none). A scanner that is missing or throws is a+ * FAIL row: a check that cannot look is not a pass.+ */+export const scanner = async (label, script, fn, printer, call, shape, meta = null) => {+ const path = join(TOOLS, script);+ if (!existsSync(path)) return [row(label, "FAIL", `tools/${script} is not installed: this check cannot look, so it fails`)];+ // a file URL, never a bare path: on Windows C:\\... is not a module specifier, and every scanner row failed there+ let mod, r; try { mod = await import(pathToFileURL(path).href); r = await call(mod[fn]); } catch (e) { return [row(label, "FAIL", `${script} could not run: ${String(e.message ?? e).split("\n")[0]}`)]; }+ if (shape) return shape(r);+ const printed = []; if (printer && mod[printer]) { const log = console.log; console.log = (...a) => printed.push(a.join(" ")); try { mod[printer](r); } finally { console.log = log; } }+ return scannerRows(label, r, meta, printed.filter((l) => /^\s*FAIL\b/.test(l)).map((l) => l.trim()));+};++const audioStreams = (file) => { const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "a", "-show_entries", "stream=index", "-of", "csv=p=0", file], { encoding: "utf8" }); return r.status === 0 ? r.stdout.split("\n").filter(Boolean).length : -1; };+const videoFrames = (file) => { const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=codec_name", "-of", "csv=p=0", file], { encoding: "utf8" }); return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null; };++/** Every check on one (film, file). -> { rows, meta } */+export const shipOne = async (film, file, o = {}) => {+ const rows = [];+ // ---- input: never judge an empty or wrong file+ if (!existsSync(file)) return { rows: [row("input", "FAIL", `${file} does not exist: render it first (node tools/render.mjs ${film})`)] };+ if (statSync(file).size === 0) return { rows: [row("input", "FAIL", `${file} is empty (0 bytes): an empty input is never a pass`)] };+ const codec = videoFrames(file); if (!codec) return { rows: [row("input", "FAIL", `${file} has no decodable video stream`)] };+ const sc = readSidecar(file);+ if (sc?.error) rows.push(row("input", "FAIL", sc.error));+ else if (sc && sc.film !== film) rows.push(row("input", "FAIL", `${basename(file)} was rendered from '${sc.film}' (its sidecar), not '${film}'`));+ else if (sc?.stale) rows.push(row("input", "FAIL", `${basename(file)} changed after render wrote its sidecar: re-render it`));+ else rows.push(row("input", "PASS", `${basename(file)} (${codec}, ${(statSync(file).size / 1e6).toFixed(1)} MB)${sc ? ", sidecar matches" : ", no sidecar (an older render): the film is the one named"}`));++ // ---- frame+ let fc; try { fc = await frameCheck(film, { every: o.every ?? 1 }); } catch (e) { rows.push(row("frame", "FAIL", `the film did not draw: ${String(e.message ?? e).split("\n")[0]}${/one shape/.test(String(e.message)) ? " (a hand-built film takes --shapes once it has film.reshape: compose each shape from one timeline, never a crop)" : ""}`)); return { rows }; }+ const meta = fc.meta, rep = frameReport(film, fc, { warnZones: o.zones === "warn" });+ if (sc?.frames && Array.isArray(sc.frames) && (sc.frames[0] !== 0 || sc.frames[1] !== meta.durationFrames)) rows.push(row("input", "FAIL", `a range render (frames ${sc.frames.join("-")} of ${meta.durationFrames}) cannot ship`));+ rows.push(row("frame", rep.fails ? "FAIL" : "PASS", rep.lines[rep.lines.length - 1].replace(/^FRAMECHECK:\s*/, ""), rep.lines.filter((l) => /^\s+(FAIL|FLAG)\b/.test(l)).map((l) => l.trim())));+ if (meta.placeholders?.length) rows.push(row("assets", "FAIL", `placeholder asset(s): ${meta.placeholders.join(", ")}`));++ // ---- the file+ rows.push(runTool("verify-export.mjs", [film, "--file", file, "--delivery"], { label: "verify" }));+ if (o.quick) rows.push(row("gate", "FLAG", "skipped (--quick): determinism, contract and dead air not run, so this run cannot pass"));+ else rows.push(runTool("gate.mjs", [film, "--mp4", file], { label: "gate" }));+ // Lane MOTION's scanners, one row per check: N/A comes back as FLAG with its reason (listed, never a pass)+ // the film's own meta goes to motionscan: a file with no sidecar (an older render, track.mjs master) used to+ // be scanned with no temperament and no meta.motion.allow, so declared cuts and fades failed falsely+ rows.push(...await scanner("motion", "motionscan.mjs", "motionScan", "printScan", (m) => m(file, { meta }), null, meta));+ rows.push(...await scanner("layers", "layerscan.mjs", "layerScan", "printLayers", (m) => m(film), null, meta));+ rows.push(...await scanner("locks", "lock.mjs", "checkLocks", null, (m) => m(film), (r) => (r.none ? [row("locks", "NONE", "no approved shots yet (meta.motion.approved): lock one with lock.mjs --shot <id> once the person approves it")] : [row("locks", r.fail ? "FAIL" : "PASS", `${r.checked.length} approved shot(s)`, r.checked.filter((c) => c.status !== "same").map((c) => `${c.status === "unlocked" ? "FLAG" : "FAIL"} ${c.shot} (${c.note}) ${c.status}`))])));+ // sound: the engine's own score, or an external track (meta.checks.music.track: Lane SOUND's route)+ const na = audioStreams(file), ext = meta.checks?.music?.track, base = film.replace(/-(16x9|1x1|4x5|9x16)$/, "");+ if (na < 0) rows.push(row("sound", "FAIL", "ffprobe could not read the audio streams"));+ else if (na === 0) rows.push(meta.hasAudio || ext ? row("sound", "FAIL", "the film has music but the file has no audio stream") : row("sound", "NONE", "no audio stream, and the film declares no score (verify checks the same)"));+ else if (ext) {+ rows.push(runTool("track.mjs", ["check", file], { label: "track" }));+ if (!o.sfx) rows.push(row("sfx", "FAIL", "an external track needs its effects stem measured for pitch: pass --sfx <stem.wav> (track.mjs mix --stem wrote it)"));+ else rows.push(runTool("soundcheck.mjs", [file, "--sfx", o.sfx], { label: "sound" }));+ } else rows.push(runTool("soundcheck.mjs", [file], { label: "sound" }));+ // cues: a film that declares cues must have its sheet exported and current (the mix reads it)+ let cuesDeclared = false; try { const { loadFilm } = await import("./captions.mjs"); cuesDeclared = ((await loadFilm(base)).cues ?? []).length > 0; } catch { /* the facts row below reports a film that will not load */ }+ const cueSheet = resolve(`out/${base}.cues.json`);+ if (existsSync(cueSheet)) rows.push(runTool("cues.mjs", [base, "--check", cueSheet], { label: "cues" }));+ else if (cuesDeclared || ext) rows.push(row("cues", "FAIL", `the film's cue sheet ${cueSheet} is missing: export it with node tools/cues.mjs ${base} (the mix and the sync are cued from it)`));++ // ---- the film's own records+ try {+ const { loadFilm } = await import("./captions.mjs"), { checkFacts, claimsOf } = await import("./factsrules.mjs"), { factsFile, readFacts } = await import("./facts.mjs");+ const fx = readFacts(factsFile(film)), res = fx.error ? { status: "FAIL", checked: 0, problems: [{ claim: "(facts.json)", why: fx.error }] } : checkFacts(claimsOf(await loadFilm(film)), fx.facts);+ const drawn = fc.auto.cues.length;+ rows.push(res.status === "N/A" ? (drawn ? blindRow(meta, "facts", `the film declares no claims (film.claims) but draws ${drawn} text cue(s): list every claim with its source (references/workflows/facts.md)`) : row("facts", "NONE", "the film declares no claims and draws no text")) : row("facts", res.status, `${res.checked} claim(s)`, res.problems.map((p) => `FAIL "${String(p.claim).slice(0, 60)}" ${p.why}`)));+ } catch (e) { rows.push(row("facts", "FAIL", `could not read the film's claims: ${e.message}`)); }+ { const rp = resolve(o.review ?? `reviews/${film.replace(/-(16x9|1x1|4x5|9x16)$/, "")}.json`); let j = null, err = null; if (existsSync(rp)) try { j = JSON.parse(readFileSync(rp, "utf8")); } catch (e) { err = e.message; } rows.push(...reviewRows(j, rp, err, meta)); }+ rows.push(lengthRow(meta, fc.auto.cues.length ? fc.floor : null));++ // ---- the critic sheet+ if (o.out) {+ mkdirSync(o.out, { recursive: true });+ const fr = sheetFrames(meta), sheet = join(o.out, "sheet.jpg");+ const st = spawnSync(process.execPath, [join(TOOLS, "still.mjs"), film, "--frames", fr.join(","), "--out", join(o.out, "frames", "f-{frame}.png"), "--sheet", sheet], { encoding: "utf8", maxBuffer: 1 << 26 });+ rows.push(row("sheet", st.status === 0 && existsSync(sheet) ? "PASS" : "FAIL", st.status === 0 ? `${sheet} (${fr.length} frames: every 2 s, every shot start, the last frame)` : `still.mjs failed: ${(st.stderr || st.stdout).trim().split("\n").pop()}`));+ }+ return { rows, meta, frame: rep.lines };+};++const table = (name, rows) => [`SHIP ${name}`, ...rows.flatMap((r) => [` ${r.step.padEnd(18)} ${r.status.padEnd(5)} ${r.detail}`, ...r.lines.slice(0, 12).map((l) => ` ${l}`), ...(r.lines.length > 12 ? [` ... ${r.lines.length - 12} more`] : [])])];++if (isMain(import.meta.url)) {+ const pos = [], opt = {}, FLAGS = new Set(["quick"]);+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) { const k = a.slice(2); opt[k] = FLAGS.has(k) ? true : process.argv[++i]; } else pos.push(a); }+ if (!pos[0]) { console.error(`usage: ${USAGE}`); process.exit(2); }+ let film = pos[0];+ if (/\.(mp4|mov|m4v)$/i.test(film)) { if (opt.file) { console.error("ship: give the file once"); process.exit(2); } opt.file = film; const who = filmOfFile(film, knownFilms()); if (!who.film) { console.error(`ship: ${who.why.replace("verify-export.mjs", "ship.mjs")}`); process.exit(2); } film = who.film; }+ requireFilm(film, "ship", USAGE);+ if (opt.zones !== undefined && !["fail", "warn"].includes(opt.zones)) { console.error(`ship: --zones is fail or warn, got '${opt.zones}'`); process.exit(2); }+ // --every: checked here, before any row (abc used to reach framecheck as NaN and check frame 0 alone); above 1 the run is QUICK+ let ev; try { ev = shipEvery(opt.every); } catch (e) { console.error(`ship: ${e.message}\nusage: ${USAGE}`); process.exit(2); }+ const quick = !!opt.quick || ev.quick;+ const shapes = opt.shapes ? String(opt.shapes).split(",").map((s) => s.trim()).filter(Boolean) : [null];+ const badShape = shapes.filter((s) => s && !SHAPE_NAMES.includes(s)); if (badShape.length) { console.error(`ship: --shapes wants ${SHAPE_NAMES.join(", ")}, got '${opt.shapes}'`); process.exit(2); }+ const results = [];+ for (const sh of shapes) {+ const f = sh ? `${film}-${sh}` : film, file = resolve(opt.file ? String(opt.file).replace("{shape}", sh ?? "") : `out/${f}.mp4`);+ if (sh && opt.file && !String(opt.file).includes("{shape}") && shapes.length > 1) { console.error("ship: with several --shapes, --file needs {shape} in it (out/x-{shape}.mp4)"); process.exit(2); }+ const out = resolve(opt.out ? String(opt.out).replace("{shape}", sh ?? "") + (sh && !String(opt.out).includes("{shape}") ? `-${sh}` : "") : join(dirname(file), `${basename(file).replace(/\.[^.]+$/, "")}.ship`));+ console.log(`\n==================== ${f} ${file}`);+ const r = await shipOne(f, file, { every: ev.every, zones: opt.zones, quick: !!opt.quick, review: opt.review, sfx: opt.sfx ? resolve(String(opt.sfx).replace("{shape}", sh ?? "")) : undefined, out });+ const v = verdict(r.rows, quick), t = table(f, r.rows);+ console.log(t.join("\n")); console.log(`SHIP ${f}: ${v}`);+ { mkdirSync(out, { recursive: true }); // the table is written even when the input was refused: that refusal is the record+ writeFileSync(join(out, "ship.json"), JSON.stringify({ film: f, file, verdict: v, rows: r.rows }, null, 1) + "\n");+ writeFileSync(join(out, "SHIP.md"), [`# Ship: ${f}`, "", `File: \`${file}\` `, `Verdict: **${v}**`, "", "| check | status | detail |", "|---|---|---|", ...r.rows.map((x) => `| ${x.step} | ${x.status} | ${x.detail.replace(/\|/g, "/")} |`), "", "## Findings", "", ...r.rows.flatMap((x) => x.lines.map((l) => `- ${x.step}: ${l}`)), "", "", ""].join("\n"));+ console.log(`critic sheet and table: ${join(out, "SHIP.md")}`);+ }+ results.push(v);+ }+ const all = results.every((v) => v === "PASS") ? "PASS" : results.includes("FAIL") ? "FAIL" : "QUICK";+ console.log(`\nSHIP: ${all}${all === "QUICK" ? ` (${opt.quick ? "--quick skips the gate" : `--every ${ev.every} checks every ${ev.every}th frame`}: run without it before showing anyone)` : ""}`);+ process.exit(all === "PASS" ? 0 : all === "FAIL" ? 1 : 1);+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/shiprules.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/shiprules.mjsnew file mode 100644index 0000000..7f9d898--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/shiprules.mjs@@ -0,0 +1,90 @@+// SHIP RULES. The parts of ship.mjs that decide, as pure functions (rows in, verdict out), so each is+// unit-tested with a case that must fail: the review ledger, the length budget, the critic sheet's+// frames and the verdict itself.+//+// reviews/<film>.json, the review ledger a critic writes and ship reads:+// { "findings": [{ "id": "r1-4", "p": "P0", "status": "open" | "fixed" | "wontfix", "note": "...", "by": "critic r1" }],+// "notes": [{ "at": "2026-10-27 21:36", "from": "the director", "text": "who is gonna read this overload of info?" }] }++/** One row of the table. status: PASS, FAIL, NONE (checked, nothing there, with the evidence), FLAG (looked, review it). */+export const row = (step, status, detail, lines = []) => ({ step, status, detail, lines });++// A CHECK THAT CANNOT LOOK FAILS. When a check has nothing to judge against (no temperament, no brand+// colours, no review ledger, no length budget) it did not look, and that is a FAIL, never a FLAG that+// passes: six such rows once added up to SHIP: PASS. A film that truly has nothing there says so, with a+// reason, in meta.checks.none: { "<row>": "<reason>" }, e.g. { "review": "a test fixture nobody is shown" }.+// That row is then NONE and the reason is printed in the table for the reader to judge.++/** The film's declared reason that a check has nothing to look at (meta.checks.none[step]), or null. */+export const waiver = (meta, step) => { const r = meta?.checks?.none?.[step]; return typeof r === "string" && r.trim() ? r.trim() : null; };+/** The row of a check that could not look: FAIL, or NONE with the film's declared reason. */+export const blindRow = (meta, step, why, lines = []) => {+ const r = waiver(meta, step);+ return r ? row(step, "NONE", `not checked, declared in meta.checks.none: ${r}`, lines) : row(step, "FAIL", `${why}: this check cannot look, so it fails (declare meta.checks.none["${step}"] = "<reason>" only when there is truly nothing to check)`, lines);+};+/**+ * A scanner's checks as rows (motionscan, layerscan): PASS and FAIL as they are, NONE (looked, nothing there)+ * as NONE, N/A (did not look) as a blind row. Any other status is a FAIL: it is not one ship knows.+ */+export const scannerRows = (label, r, meta, fails = []) => {+ let given = false;+ return Object.entries(r.checks ?? {}).map(([name, c]) => {+ const step = `${label}:${name}`, lines = c.status === "FAIL" && !given ? ((given = true), fails) : []; // the printer's findings go under the first failing check+ if (c.status === "N/A") return blindRow(meta, step, `did not look: ${c.reason}`);+ if (c.status === "NONE") return row(step, "NONE", c.reason ?? "nothing there to check");+ if (c.status === "PASS") return row(step, "PASS", "clean");+ if (c.status === "FAIL") return row(step, "FAIL", `${name} failed`, lines);+ return row(step, "FAIL", `unknown status '${c.status}' from the scanner`);+ });+};+/** ship --every: a whole number of frames, 1 or more. Above 1 it is a quick look (holds measured in steps), so the verdict is QUICK. */+export const shipEvery = (v) => {+ const n = v === undefined ? 1 : Number(v);+ if (!Number.isInteger(n) || n < 1) throw new Error(`--every wants a whole number of frames, 1 or more; got '${v}'`);+ return { every: n, quick: n > 1 };+};++/** The review ledger (R2/R3/R4): critic findings with a priority and a status, and the person's notes, verbatim. */+export const reviewRows = (j, path, err = null, meta = null) => {+ if (err) return [row("review", "FAIL", `${path} is not valid JSON: ${err}`)];+ if (!j) return [blindRow(meta, "review", `no ${path}: no critic findings recorded for this version (review.md: run a fresh critic and record its P0/P1 list there)`)];+ // the ledger's shape, before any of it is read: a wrong shape is a FAIL row, never a crash with no SHIP.md+ const shape = typeof j !== "object" || Array.isArray(j) ? "the ledger is not an object"+ : j.findings !== undefined && (!Array.isArray(j.findings) || j.findings.some((f) => !f || typeof f !== "object" || Array.isArray(f))) ? "findings is not a list of objects"+ : j.notes !== undefined && (!Array.isArray(j.notes) || j.notes.some((n) => !n || typeof n !== "object")) ? "notes is not a list of objects" : null;+ if (shape) return [row("review", "FAIL", `${path}: ${shape} ({ "findings": [{ "id", "p", "status", "note" }], "notes": [{ "at", "from", "text" }] })`)];+ const open = (j.findings ?? []).filter((f) => (f.status ?? "open") === "open"), p0 = open.filter((f) => f.p === "P0"), p1 = open.filter((f) => f.p === "P1");+ const out = [row("review", p0.length ? "FAIL" : p1.length ? "FLAG" : "PASS", `${(j.findings ?? []).length} finding(s) recorded, ${p0.length} open P0, ${p1.length} open P1`, [...p0, ...p1].map((f) => `${p0.includes(f) ? "FAIL" : "FLAG"} ${f.p} ${f.id ?? ""} ${f.note ?? ""}`.trim()))];+ const notes = (j.notes ?? []).slice(-3);+ if (notes.length) out.push(row("notes", "FLAG", `the person's last ${notes.length} note(s): re-read each against the new sheet before showing it`, notes.map((n) => `${n.at ?? ""} ${n.from ?? ""}: "${n.text}"`.trim())));+ return out;+};++/** Length against meta.checks.length (D1), seconds. */+export const lengthRow = (meta, floor) => {+ const s = meta.durationFrames / meta.fps, L = meta.checks?.length, f = floor ? `; reading needs ${floor.floorS.toFixed(1)} s of it, text holds ${floor.spareS.toFixed(1)} s beyond reading` : "";+ const shots = (meta.shots ?? []).map((x) => `${x.id} ${((x.end - x.start) / meta.fps).toFixed(1)} s`).join(", ");+ const sh = shots ? [`shots: ${shots}`] : [];+ if (!L) return blindRow(meta, "length", `${s.toFixed(1)} s, no length budget (meta.checks.length { target, max })${f}`, sh);+ // a budget needs a number to judge against: max, else the target stands in for it (a budget with no max never failed)+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0, max = num(L.max) ? L.max : num(L.target) ? L.target : null, target = num(L.target) ? L.target : max;+ if (max === null) return row("length", "FAIL", `${s.toFixed(1)} s, the length budget has no number to judge against: give meta.checks.length { target, max } in seconds${f}`, sh);+ return row("length", s > max ? "FAIL" : s > target ? "FLAG" : "PASS", `${s.toFixed(1)} s against target ${target} s, max ${max} s${num(L.max) ? "" : " (no max: the target is the limit)"}${f}`, sh);+};++/** The frames of the critic sheet: one every 2 s, every shot start, the last frame (at most 60). */+export const sheetFrames = (meta) => {+ const N = meta.durationFrames, step = Math.max(1, Math.round(2 * meta.fps)), set = new Set([0, N - 1]);+ for (let f = 0; f < N; f += step) set.add(f); for (const s of meta.shots ?? []) set.add(s.start);+ let fr = [...set].filter((f) => f >= 0 && f < N).sort((a, b) => a - b);+ if (fr.length > 60) { const k = fr.length / 60; fr = Array.from({ length: 60 }, (_, i) => fr[Math.floor(i * k)]); fr[59] = N - 1; }+ return fr;+};++/**+ * PASS only when every row is PASS, NONE (checked, absent, with evidence) or FLAG (looked, review it); a row+ * with any other status fails. QUICK when the run was a quick look (--quick, or --every above 1).+ */+const KNOWN = new Set(["PASS", "NONE", "FLAG"]);+export const verdict = (rows, quick) => (rows.some((r) => !KNOWN.has(r.status)) ? "FAIL" : quick ? "QUICK" : "PASS");+diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/sidecar.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/sidecar.mjsnew file mode 100644index 0000000..f99d3b5--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/sidecar.mjs@@ -0,0 +1,57 @@+// SIDECAR. A rendered file says which film it is in <file>.film.json beside it, so a file that has been+// renamed or versioned (out/brandLaunch-v12.mp4 from the film brandHook) still resolves. On a brand launch film verify-export inferred the film from the file name, failed with "unknown film+// 'brandFilm-v2-frozen'", and was never run again. Tools read the sidecar first, the name second.+// render.mjs writes it after the encode ({ film, file, sha256, frames: [from, to], scale, blur, poster, meta }).+// readSidecar(file) -> the record, or null when there is none+// filmOfFile(file, known) -> { film, how } | { film: null, why } (sidecar, then the name, then nothing)+import { createHash } from "node:crypto";+import { existsSync, readFileSync } from "node:fs";+import { basename } from "node:path";++export const sidecarPath = (file) => `${file}.film.json`;+const sha = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");++/** The sidecar beside `file`, with `stale: true` when the file changed after it was written. */+export const readSidecar = (file) => {+ const p = sidecarPath(file); if (!existsSync(p)) return null;+ try { const rec = JSON.parse(readFileSync(p, "utf8")); return { ...rec, stale: existsSync(file) && rec.sha256 ? rec.sha256 !== sha(file) : false }; } catch (e) { return { error: `unreadable sidecar ${p}: ${e.message}` }; }+};++/** Which film a file is: its sidecar, else its name (out/<film>[.<from>-<to>].<ext>). `known` lists the films that exist. */+export const filmOfFile = (file, known) => {+ const sc = readSidecar(file);+ if (sc?.film) return { film: sc.film, how: sc.stale ? "sidecar (STALE: the file changed after render wrote it)" : "sidecar", sidecar: sc };+ const byName = basename(file).split(".")[0];+ if (known.includes(byName)) return { film: byName, how: "file name" };+ return { film: null, why: `'${basename(file)}' has no sidecar (${basename(sidecarPath(file))}) and its name is not a film. Name the film: node tools/verify-export.mjs <film> --file ${file}` };+};++/**+ * EXTERNAL MUSIC PROVENANCE (X3). A film whose music is a supplied or generated track declares the+ * track's manifest (meta.checks.music.track: the <take>.track.json that `track.mjs import` writes, with+ * its sha256, provider, cost and licence). The delivered file's mix sidecar (<file>.mix.json, written by+ * `track.mjs mix` and copied by `master`) must have been made from that take: its music is the take+ * itself, or a bar cut whose <cut>.cut.json names the take's sha256 as its source. The mix must also+ * have been made from the cue sheet as it is now (cuesSha256), so the effects are on the current frames.+ * -> { ok, detail }+ */+export const trackProvenance = (trackJson, file) => {+ if (!existsSync(trackJson)) return { ok: false, detail: `no track manifest ${trackJson}: pin the take with node tools/track.mjs import <take> --provider ...` };+ let man, mix; try { man = JSON.parse(readFileSync(trackJson, "utf8")); } catch (e) { return { ok: false, detail: `unreadable ${trackJson}: ${e.message}` }; }+ if (!man.sha256 || !man.provider) return { ok: false, detail: `${trackJson} has no sha256 or provider` };+ const mixJson = `${file}.mix.json`;+ if (!existsSync(mixJson)) return { ok: false, detail: `no mix sidecar ${basename(mixJson)}: master the file with node tools/track.mjs master <picture> <mix.wav> -o ${basename(file)}` };+ try { mix = JSON.parse(readFileSync(mixJson, "utf8")); } catch (e) { return { ok: false, detail: `unreadable ${mixJson}: ${e.message}` }; }+ // The effects in the mix land on the cue sheet it was made from: a sheet changed since then (or a mix+ // record that never named its sheet) is a stale mix, whatever the music says.+ if (!mix.cuesSha256 || !mix.cues) return { ok: false, detail: `${basename(mixJson)} names no cue sheet, so the effects in the mix cannot be checked: re-mix with node tools/track.mjs mix --cues out/<film>.cues.json` };+ if (!existsSync(mix.cues)) return { ok: false, detail: `the cue sheet the mix was made from (${basename(String(mix.cues))}) is gone: export it (node tools/cues.mjs <film>) and re-mix` };+ if (sha(mix.cues) !== mix.cuesSha256) return { ok: false, detail: `the cue sheet ${basename(String(mix.cues))} changed after the mix was made, so its effects land on the old frames: re-mix (node tools/track.mjs mix ...) and master again` };+ if (mix.musicSha256 === man.sha256) return { ok: true, detail: `the mix plays the pinned take itself (${man.provider}${man.licence ? `, ${man.licence}` : ""})` };+ const cutJson = `${mix.music}.cut.json`;+ if (!existsSync(cutJson)) return { ok: false, detail: `the mix's music ${basename(String(mix.music))} is not the pinned take and has no cut record (${basename(cutJson)})` };+ const cut = JSON.parse(readFileSync(cutJson, "utf8"));+ if (cut.sourceSha256 !== man.sha256) return { ok: false, detail: `the mix was cut from a different take (sha ${String(cut.sourceSha256).slice(0, 12)}, the manifest pins ${man.sha256.slice(0, 12)})` };+ if (existsSync(mix.music) && sha(mix.music) !== mix.musicSha256) return { ok: false, detail: `the cut ${basename(mix.music)} changed after the mix was made: re-mix` };+ return { ok: true, detail: `the mix plays a bar cut of the pinned take (${man.provider}${man.licence ? `, ${man.licence}` : ""}${man.costUsd != null ? `, $${man.costUsd}` : ""})` };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/sound-unit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/sound-unit.mjsnew file mode 100644index 0000000..46c14b5--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/sound-unit.mjs@@ -0,0 +1,124 @@+#!/usr/bin/env node+// Unit + end-to-end tests for the sound and project tools that need node's own modules, ffmpeg and real+// files: track.mjs master and listen, the mix sidecar's provenance, cues.mjs and scaffold.mjs from a+// folder whose path has a space, narrate's baked-module staleness and its PATH lookup, and overlay's+// linked-project rule. Each test was written red first, against the bug it names. Temp folder under+// out/, removed afterwards. No paid API is ever called.+// node tools/sound-unit.mjs+import { strict as assert } from "node:assert";+import { execFileSync, spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { chmodSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { delimiter, dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const ENGINE = join(dirname(fileURLToPath(import.meta.url)), ".."), TOOLS = join(ENGINE, "tools");+const root = join(ENGINE, "out", ".sound-unit"); rmSync(root, { recursive: true, force: true }); mkdirSync(root, { recursive: true });+let n = 0, failed = 0;+const t = async (label, fn) => { try { await fn(); n++; console.log(` PASS ${label}`); } catch (e) { failed++; console.log(` FAIL ${label}\n ${String(e.message).split("\n").slice(0, 6).join("\n ")}`); } };+const node = (args, o = {}) => spawnSync(process.execPath, args, { encoding: "utf8", cwd: root, ...o });+const ff = (...a) => execFileSync("ffmpeg", ["-y", "-v", "error", ...a]);+const dur = (f) => Number(execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", f]).toString().trim());+const sha = (f) => createHash("sha256").update(readFileSync(f)).digest("hex");+const tone = (f, s) => ff("-f", "lavfi", "-i", `sine=frequency=330:sample_rate=48000:duration=${s}`, "-af", "volume=0.3", "-ac", "2", f);+const isWin = process.platform === "win32";++try {+ // ---------------------------------------------------------------- track.mjs master (H5, M10)+ const pic = join(root, "picture.mp4"); ff("-f", "lavfi", "-i", "color=c=gray:s=64x36:r=30:d=6", "-c:v", "mpeg4", pic);+ const short = join(root, "short.wav"), full = join(root, "full.wav"), long = join(root, "long.wav"); tone(short, 4); tone(full, 6); tone(long, 8);+ const master = (mix, out) => node([join(TOOLS, "track.mjs"), "master", pic, mix, "-o", out]);+ await t("RED (H5): a 4 s mix under a 6 s picture is refused, and no file shorter than the picture is written", () => {+ const out = join(root, "h5.mp4"), r = master(short, out);+ assert.notEqual(r.status, 0, r.stdout); assert.match(r.stdout + r.stderr, /shorter than the picture/);+ assert.ok(!existsSync(out) || dur(out) >= 5.9, `a ${existsSync(out) ? dur(out).toFixed(2) : "?"} s file was written for a 6 s picture`);+ });+ await t("GREEN (H5): a mix as long as the picture masters to the full 6 s", () => { const out = join(root, "h5ok.mp4"), r = master(full, out); assert.equal(r.status, 0, r.stdout + r.stderr); assert.ok(Math.abs(dur(out) - 6) < 0.15, `${dur(out)} s`); });+ await t("H5: a mix longer than the picture is trimmed to the picture, never the other way round", () => { const out = join(root, "h5long.mp4"), r = master(long, out); assert.equal(r.status, 0, r.stdout + r.stderr); assert.ok(Math.abs(dur(out) - 6) < 0.15, `${dur(out)} s`); });+ await t("RED (M10): mastering again from a mix with no sidecar removes the old <out>.mix.json", () => {+ const out = join(root, "m10.mp4"), a = join(root, "a.wav"), b = join(root, "b.wav"); cpSync(full, a); cpSync(full, b);+ writeFileSync(a + ".mix.json", JSON.stringify({ music: "x", musicSha256: "old", quiet: [] }));+ master(a, out); assert.ok(existsSync(out + ".mix.json"), "the first master did not copy the sidecar");+ const r = master(b, out); assert.ok(!existsSync(out + ".mix.json"), "the previous mix's record is still beside the new file"); assert.match(r.stdout, /no mix sidecar/);+ });+ await t("RED (M5): master carries the picture's film sidecar to the output, re-hashed, so ship scans with the film's settings", async () => {+ const { readSidecar } = await import(pathToFileURL(join(TOOLS, "sidecar.mjs")).href);+ const p2 = join(root, "m5pic.mp4"), out = join(root, "m5.mp4"); cpSync(pic, p2);+ writeFileSync(p2 + ".film.json", JSON.stringify({ film: "m5Film", file: "m5pic.mp4", sha256: sha(p2), frames: [0, 180], meta: { fps: 30, motion: { temperament: "calm" } } }));+ const r2 = node([join(TOOLS, "track.mjs"), "master", p2, full, "-o", out]);+ assert.equal(r2.status, 0, r2.stdout + r2.stderr);+ const sc = readSidecar(out); assert.ok(sc, "no <out>.film.json beside the mastered file");+ assert.equal(sc.film, "m5Film"); assert.equal(sc.meta.motion.temperament, "calm"); assert.equal(sc.stale, false, "the sidecar still carries the picture's hash"); assert.equal(sc.file, "m5.mp4");+ });+ await t("master leaves no .master.wav temp file behind", () => assert.deepEqual(readdirSync(root).filter((f) => f.endsWith(".master.wav")), []));++ // ---------------------------------------------------------------- the mix sidecar names its cue sheet (H6)+ const { trackProvenance } = await import(pathToFileURL(join(TOOLS, "sidecar.mjs")).href);+ const take = join(root, "take.wav"); cpSync(full, take);+ const man = join(root, "take.wav.track.json"); writeFileSync(man, JSON.stringify({ sha256: sha(take), provider: "test" }));+ const cues = join(root, "film.cues.json"), file = join(root, "film.mp4"); writeFileSync(file, "x");+ writeFileSync(cues, JSON.stringify({ film: "film", fps: 30, durationFrames: 180, cues: [{ name: "hit", frame: 30, t: 1, sound: "tap:tock" }] }));+ const mixRec = (extra) => writeFileSync(file + ".mix.json", JSON.stringify({ music: take, musicSha256: sha(take), cues, cuesSha256: sha(cues), quiet: [], ...extra }));+ await t("GREEN (H6): a mix made from the current cue sheet passes provenance", () => { mixRec(); const p = trackProvenance(man, file); assert.ok(p.ok, p.detail); });+ await t("RED (H6): the cue sheet changed after the mix was made, so the effects are stale and provenance fails", () => {+ mixRec(); writeFileSync(cues, JSON.stringify({ film: "film", fps: 30, durationFrames: 180, cues: [{ name: "hit", frame: 60, t: 2, sound: "tap:tock" }] }));+ const p = trackProvenance(man, file); assert.ok(!p.ok, p.detail); assert.match(p.detail, /cue sheet/);+ });+ await t("RED (H6): a mix record with no cue sheet hash cannot be checked, so it fails", () => { mixRec({ cuesSha256: undefined }); const p = trackProvenance(man, file); assert.ok(!p.ok, p.detail); });+ await t("RED (H6): a mix whose cue sheet is gone fails", () => { mixRec(); rmSync(cues); const p = trackProvenance(man, file); assert.ok(!p.ok, p.detail); });++ // ---------------------------------------------------------------- track.mjs listen without a shell rm (M11)+ await t("RED (M11): listen runs with no rm on the PATH (as on Windows) and leaves no temp WAVs", () => {+ const dir = join(root, "listen"), r = node([join(TOOLS, "track.mjs"), "listen", dir, "--mix", full, "--at", "0", "--len", "2"], { env: { ...process.env, PATH: dirname(execFileSync(isWin ? "where" : "which", ["ffmpeg"]).toString().split(/\r?\n/)[0]) } });+ assert.equal(r.status, 0, r.stderr); assert.deepEqual(readdirSync(dir).filter((f) => f.endsWith(".wav")), []);+ });++ // ---------------------------------------------------------------- narrate (M6, M11)+ const { bakedStale } = await import(pathToFileURL(join(TOOLS, "narrate.mjs")).href);+ const timing = { totalFrames: 120, lines: [{ hash: "a".repeat(64) }] }, mod = (frames, hash = "a".repeat(64)) => `export const v = {"timing":{"totalFrames":${frames},"lines":[{"hash":"${hash}"}]}}`;+ await t("RED (M6): narrate all may re-bake after the script's length changed (ignoreStale covers frames too)", () => assert.equal(bakedStale(mod(100), timing, true), false));+ await t("M6: check still calls a module baked at another length stale", () => assert.equal(bakedStale(mod(100), timing, false), true));+ await t("M6: check still calls a module baked from other takes stale", () => assert.equal(bakedStale(mod(120, "b".repeat(64)), timing, false), true));+ await t("M6: a module baked from these takes at this length is current", () => assert.equal(bakedStale(mod(120), timing, false), false));+ const { which } = await import(pathToFileURL(join(TOOLS, "narrate", "providers", "util.mjs")).href);+ const bin = join(root, "bin dir"); mkdirSync(bin); const exe = join(bin, isWin ? "kokoro-x.cmd" : "kokoro-x"); writeFileSync(exe, isWin ? "@echo off\r\n" : "#!/bin/sh\n"); chmodSync(exe, 0o755);+ await t("RED (M11): which finds a program on PATH with no /usr/bin/env or which (a folder with a space)", () => { const was = process.env.PATH; process.env.PATH = bin; try { assert.equal(which("kokoro-x"), exe); } finally { process.env.PATH = was; } });+ await t("M11: which reads Windows PATHEXT, so kokoro-x finds kokoro-x.CMD", () => {+ const win = join(root, "win"); mkdirSync(win); writeFileSync(join(win, "whisper-cli.CMD"), "");+ assert.equal(which("whisper-cli", { path: [join(root, "nope"), win].join(delimiter), pathext: ".EXE;.CMD", win: true }), join(win, "whisper-cli.CMD"));+ });+ await t("M11: which says null for a program that is not there", () => assert.equal(which("no-such-program-xyz", { path: bin }), null));++ // ---------------------------------------------------------------- a copy of the engine in a folder with a space (M11, L9, L11)+ const spaced = join(root, "my engine", "engine"); mkdirSync(spaced, { recursive: true });+ for (const d of ["tools", "src"]) cpSync(join(ENGINE, d), join(spaced, d), { recursive: true });+ cpSync(join(ENGINE, "package.json"), join(spaced, "package.json"));+ await t("RED (M11): cues.mjs builds its cue module from an engine whose path has a space", async () => {+ const { loadCues } = await import(pathToFileURL(join(spaced, "tools", "cues.mjs")).href);+ const m = await loadCues(); assert.equal(typeof m.diffSheets, "function");+ });+ const proj = join(root, "my film project");+ await t("RED (L9): scaffold --linked quotes the engine path in package.json, so the scripts survive a space", () => {+ const r = node([join(spaced, "tools", "scaffold.mjs"), proj, "--linked", "--film", "spaceFilm"]); assert.equal(r.status, 0, r.stdout + r.stderr);+ const scripts = JSON.parse(readFileSync(join(proj, "package.json"), "utf8")).scripts;+ for (const [k, cmd] of Object.entries(scripts)) {+ assert.match(cmd, /^node /, k);+ if (isWin) { assert.match(cmd, /^node "[^"]+" spaceFilm$/, cmd); continue; }+ // npm runs a script through sh: the first word after node must be the whole tool path+ const words = execFileSync("sh", ["-c", `printf '%s\\n' ${cmd.slice(5)}`]).toString().trim().split("\n");+ assert.equal(words[0], join(spaced, "tools", `${k}.mjs`), `${k}: sh split the path into ${JSON.stringify(words)}`);+ assert.equal(words[1], "spaceFilm");+ }+ });+ const overlayRoots = (cwd) => { const r = node(["--input-type=module", "-e", `const o = await import(${JSON.stringify(pathToFileURL(join(TOOLS, "overlay.mjs")).href)}); console.log(JSON.stringify({ roots: o.ROOTS, page: o.enginePath("src/hosts/page.ts") }));`], { cwd }); assert.equal(r.status, 0, r.stderr); return JSON.parse(r.stdout); };+ await t("RED (L11): another repo's src/hosts/page.ts never replaces the engine's (no linked-project marker)", () => {+ const other = join(root, "other repo"); mkdirSync(join(other, "src", "hosts"), { recursive: true }); writeFileSync(join(other, "src", "hosts", "page.ts"), "// not ours\n");+ const o = overlayRoots(other); assert.equal(o.page, join(ENGINE, "src", "hosts", "page.ts")); assert.ok(!o.roots.includes(join(other, "src")), JSON.stringify(o.roots));+ });+ await t("GREEN (L11): a project made by scaffold --linked joins the tree first", () => {+ assert.ok(existsSync(join(proj, "src")), "the L9 test did not scaffold the project");+ const o = overlayRoots(proj); assert.equal(o.roots[0], join(proj, "src"));+ });+} finally { rmSync(root, { recursive: true, force: true }); }+console.log(`\nSOUND-UNIT: ${failed ? "FAIL" : "PASS"} ${n} passed, ${failed} failed`);+process.exitCode = failed ? 1 : 0;diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/soundcheck.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/soundcheck.mjsindex dadf6b8..1a0799c 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/soundcheck.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/soundcheck.mjs@@ -2,7 +2,10 @@// it without any model, checks each value against a range, and lists the changes to make, most// important first, each tied to a moment in the film.// node tools/soundcheck.mjs <film|file.mp4|file.wav> [--profile references/music/sound-profile.json]-// [--allow 3.1:3.6,...] [--no-video] [--json] [--out f.json]+// [--allow 3.1:3.6,...] [--no-video] [--json] [--out f.json] [--sfx stem.wav]+// --sfx: the effects stem of a film whose music is an external track (track.mjs mix --stem). Every+// effect in it must be a transient, never a note: a cue with pitch salience over 0.5 FAILS, because a+// note the engine did not choose clashes with the track's key (a brand launch "disharmonious" note).// node tools/soundcheck.mjs profile <files...> -o references/music/sound-profile.json [--name "drawing film"]// Decodes what a player would (ffmpeg, stereo float at 48 kHz). The metrics are pure functions in// src/canvas-core/music/soundcheck.ts (unit-tested on synthetic signals); visual sync reuses@@ -43,7 +46,19 @@ export const loadProfile = (C, path) => {};/** Everything for one file: measures, curves, visual sync (when there is a picture and `video`), rows and the fix list. */-export const check = async (C, file, { profile, allow = [], video = "auto" } = {}) => {+let trackP = null;+const loadPitch = () => (trackP ??= build({ entryPoints: [join(here, "../src/canvas-core/music/track.ts")], bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" }).then((r) => import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"))));+/** One row per effect in an effects stem: its onset, and how much of a note it carries. */+export const pitchedCues = async (stemFile) => { const T = await loadPitch(), [L, R] = decode(stemFile); return T.stemCues(L, R, SR); };+export const pitchRows = (cues, threshold = 0.5) => {+ const bad = cues.filter((c) => c.salience > threshold), worst = [...cues].sort((a, b) => b.salience - a.salience)[0];+ const at = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(2).padStart(5, "0")}`;+ if (!cues.length) return [{ key: "sfxPitch", label: "effects pitch (external track)", value: null, text: "no effects found", status: "FAIL", fix: "the --sfx stem is silent: pass the stem track.mjs mix --stem wrote" }];+ return [{ key: "sfxPitch", label: "effects pitch (external track)", value: worst.salience, text: `${bad.length} of ${cues.length} carry a note`, status: bad.length ? "FAIL" : "PASS", range: { max: threshold }, at: bad[0]?.atS,+ fix: bad.length ? `effects carry notes under a track the engine did not write (${bad.slice(0, 4).map((c) => `${at(c.atS)} ${c.hz} Hz, salience ${c.salience}`).join("; ")}): use the tap kind (sfx.mjs list) or cut strikes under 25 ms (track.mjs kit --from-pack)` : undefined }];+};++export const check = async (C, file, { profile, allow = [], video = "auto", sfx = null } = {}) => {const p = probe(file);if (!p.audio) throw new Error(`${basename(file)} has no audio stream`);const [L, R] = decode(file), prof = profile ?? C.DEFAULT_PROFILE;@@ -55,6 +70,7 @@ export const check = async (C, file, { profile, allow = [], video = "auto" } = {sync = { ...C.visualSync(events, curves.onsets, measures.durationS), times: events, fps: p.video.fps };}const rows = C.evaluate(measures, prof);+ if (sfx) rows.push(...pitchRows(await pitchedCues(sfx)));return { file, profile: prof.name, measures, curves, sync, rows, fixes: C.startHere(rows), video: p.video, L, R };};@@ -87,7 +103,7 @@ export const asJson = (r) => ({ file: r.file, profile: r.profile, verdict: r.rowif (isMain(import.meta.url)) {const argv = process.argv.slice(2), flag = (k) => argv.includes(`--${k}`), opt = (...ks) => { for (const k of ks) { const i = argv.indexOf(k); if (i >= 0) return argv[i + 1]; } return undefined; };- const VAL = new Set(["--profile", "--out", "--allow", "-o", "--name"]), pos = argv.filter((a, i) => !a.startsWith("-") && !VAL.has(argv[i - 1]));+ const VAL = new Set(["--profile", "--out", "--allow", "-o", "--name", "--sfx"]), pos = argv.filter((a, i) => !a.startsWith("-") && !VAL.has(argv[i - 1]));const die = (msg, code = 2) => { console.error(msg); process.exit(code); };if (!pos.length) die("usage: node tools/soundcheck.mjs <film|file.mp4|file.wav> [--profile p.json] [--allow a:b] [--no-video] [--json] [--out f.json]\n node tools/soundcheck.mjs profile <files...> -o references/music/sound-profile.json [--name \"drawing film\"]");const C = await loadCheck();@@ -101,7 +117,7 @@ if (isMain(import.meta.url)) {console.log(`profile of ${sets.length} film(s) -> ${out}`); for (const [k, v] of Object.entries(p.metrics)) console.log(` ${pad(k, 12)} ${v.min} .. ${v.max} median ${v.median}`);process.exit(0);}- const file = resolveInput(pos[0]), r = await check(C, file, { profile: loadProfile(C, opt("--profile")), allow: parseAllow(opt("--allow")), video: flag("no-video") ? false : "auto" });+ const file = resolveInput(pos[0]), r = await check(C, file, { profile: loadProfile(C, opt("--profile")), allow: parseAllow(opt("--allow")), video: flag("no-video") ? false : "auto", sfx: opt("--sfx") ? resolveInput(opt("--sfx")) : null });const j = asJson(r);if (opt("--out")) { mkdirSync(dirname(resolve(opt("--out"))), { recursive: true }); writeFileSync(resolve(opt("--out")), JSON.stringify(j, null, 1) + "\n"); }console.log(flag("json") ? JSON.stringify(j, null, 1) : report(C, r));diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/still.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/still.mjsindex 6b4e67a..ae54b39 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/still.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/still.mjs@@ -9,10 +9,15 @@// plates baked once): the cheap way to review a cut. Ranges work: 0-300:50.// --sheet file also lay the frames out as one contact sheet at --sheet-scale (default 0.4)// --no-bake-cache draw every finished plate cold instead of reading .cache/bakes+// --grips 3D films: a 2x crop of every grip the film registers (three-core/checks3d) on each+// frame, plus one board of them all, each labelled PASS or with its findings. A green+// check with a prop through a hand is still a failure: look at the crops (lesson 37).// With no --frame/--frames, one still per shot, at the shot's first frame.+import { gripFindings } from "./gaterules.mjs";import { createHash } from "node:crypto";import { spawnSync } from "node:child_process";-import { mkdirSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { pathToFileURL } from "node:url";import { dirname, join, resolve } from "node:path";import { buildPage } from "./build-page.mjs";import { requireFilm } from "./names.mjs";@@ -90,3 +95,42 @@ if (opt.sheet) {if (r.status !== 0) die(`contact sheet failed: ${r.stderr.trim()}`);console.log(` contact sheet ${cols}x${rows} at ${k}x -> ${out}`);}++// GRIP CROP BOARD. A page of its own at 2x with the 3D checks listening (hosts/page.ts FILM.checks3d):+// each frame is drawn once, its registered grips come back as points on screen, and a crop around+// each one is cut from that same 2x frame. Never touches the stills above.+if (opt.grips) {+ if (!readFileSync(page.out, "utf8").includes("__ANIDOODLE_WEBGL__")) die("--grips is for 3D films (this page draws no WebGL, so nothing registers a grip)");+ const K = 2, CW = 240, CH = 170, dir = resolve(String(opt.out ?? "out/").endsWith("/") ? opt.out ?? "out/" : dirname(resolve(opt.out)), "grips");+ mkdirSync(dir, { recursive: true });+ const browser = await env.pw.lib.chromium.launch({ executablePath: env.browser.executablePath, args: ["--disable-background-timer-throttling", ...playwright.glArgs(page.out)] });+ const crops = [];+ try {+ const gp = await (await browser.newContext({ viewport: { width: 640, height: 640 } })).newPage();+ await gp.goto(pathToFileURL(page.out).href + "?adapter=still-grips");+ await gp.evaluate(async (k) => { await window.FILM.ready; window.FILM.mount(k); }, K);+ for (const [n] of jobs) {+ const r = await gp.evaluate((f) => { const rec = window.FILM.checks3d([f]); return { rec, png: window.FILM.png() }; }, n);+ const rec = r.rec[0]; if (!rec?.grips.length) { console.log(` grips frame ${String(n).padEnd(5)} none registered`); continue; }+ const full = resolve(dir, `.frame-${n}.png`); writeFileSync(full, Buffer.from(r.png, "base64"));+ rec.grips.forEach((g, i) => {+ const w = CW * K, h = CH * K, x = Math.max(0, Math.min(meta.W * K - w, Math.round(g.x * K - w / 2))), y = Math.max(0, Math.min(meta.H * K - h, Math.round(g.y * K - h / 2)));+ const out = resolve(dir, `${film}-${n}-grip${i}.png`), bad = gripFindings(g, rec.findings); // this grip's own findings, not every grip's on the frame+ const cr = spawnSync("ffmpeg", ["-v", "error", "-y", "-i", full, "-vf", `crop=${w}:${h}:${x}:${y}`, out], { encoding: "utf8" });+ if (cr.status !== 0) die(`grip crop failed: ${cr.stderr.trim()}`);+ crops.push(out);+ console.log(` grips frame ${String(n).padEnd(5)} ${g.name} ${bad.length ? "FINDINGS: " + bad.map((x) => x.kind).join(", ") : "PASS"} -> ${out}`);+ });+ rmSync(full, { force: true });+ }+ } finally { await browser.close(); }+ if (crops.length > 1) {+ const cols = Math.ceil(Math.sqrt(crops.length)), rows = Math.ceil(crops.length / cols), w = CW * K, h = CH * K, args = ["-v", "error", "-y"];+ crops.forEach((f) => args.push("-i", f));+ const pads = Array.from({ length: cols * rows - crops.length }, (_, i) => `color=c=white:s=${w}x${h}:d=1[p${i}]`), ids = [...crops.map((_, i) => `[${i}:v]`), ...pads.map((_, i) => `[p${i}]`)];+ const layout = ids.map((_, i) => `${(i % cols) * w}_${Math.floor(i / cols) * h}`).join("|"), board = resolve(dir, `${film}-grips.png`);+ const r = spawnSync("ffmpeg", [...args, "-filter_complex", [...pads, `${ids.join("")}xstack=inputs=${ids.length}:layout=${layout}:fill=white`].join(";"), "-frames:v", "1", board], { encoding: "utf8" });+ if (r.status !== 0) die(`grip board failed: ${r.stderr.trim()}`);+ console.log(` grip board ${cols}x${rows} -> ${board}`);+ }+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/track.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/track.mjsnew file mode 100644index 0000000..624368f--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/track.mjs@@ -0,0 +1,314 @@+#!/usr/bin/env node+// TRACK. Supplied or generated music (a Lyria take, a licensed track) as a first-class path: measured,+// cut by whole bars, mixed under the film's own cues with unpitched effects, mastered, and checked on+// the muxed file. A brand launch film did all of this by hand in Python and shell, and shipped a+// silent ending twice. Generation itself stays with the person's chosen provider: `prompt` writes the+// request and states the price, it never calls a paid API.+//+// node tools/track.mjs analyze <audio> [--bpm 120] [--downbeat 0.02] [--json] [--out a.json]+// node tools/track.mjs cut <audio> (--segs "0:6,8:36" | --segs-file f.txt | --bars "0-3,4-18")+// [--film <name> | --film-s 88.8] [--fade-out S] [--end-tol 0.5] [--xfade 12] [--bpm N] -o cut.wav+// node tools/track.mjs import <audio> --provider "lyria-3.5" [--cost 0.08] [--prompt p.txt] [--licence "..."]+// node tools/track.mjs prompt --len 70 --bpm 120 --style "..." [--key "A minor"] [--sections "0-11 Intro: ...; 11-12 Hard stop: ..."] [-o p.txt]+// node tools/track.mjs kit <outdir> [--from-pack]+// node tools/track.mjs mix --music cut.wav --cues out/<film>.cues.json [--sounds map.json] -o mix.wav [--stem sfx.wav]+// node tools/track.mjs master <picture.mp4> <mix.wav> -o out.mp4 [--tp -1] [--lufs -14]+// node tools/track.mjs check <file.mp4|wav> [--film-s S] [--fps 60] [--quiet-from cut.json|mix.json] [--json]+// node tools/track.mjs listen <outdir> --mix mix.wav [--at 20] [--len 10] [--takes a.wav,b.wav]+// Exit 1 on a failed check or a refused cut, 2 on bad input.+import { build } from "esbuild";+import { execFileSync, spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import { existsSync, readFileSync, writeFileSync, mkdirSync, copyFileSync, readdirSync, rmSync } from "node:fs";+import { basename, dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { homedir } from "node:os";+import { isMain } from "./is-main.mjs";+import { filmShape } from "./filmshape.mjs";++const here = dirname(fileURLToPath(import.meta.url)), SR = 48000;+let modP = null;+/** The pure modules (track analysis, the mix over a track, the effects kit, meters) in one bundle. */+export const loadTrack = () => (modP ??= (async () => {+ const src = `export * from "./src/canvas-core/music/track"; export * from "./src/canvas-core/music/trackMix"; export * from "./src/canvas-core/music/meter"; export { renderSfx, sfxInfo, sfxVariants } from "./src/canvas-core/music/sfxKit";`;+ const r = await build({ stdin: { contents: src, resolveDir: join(here, ".."), loader: "ts" }, bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });+ return import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));+})());++// ---------------------------------------------------------------- audio in and out+export const decode = (file, sr = SR) => {+ if (!existsSync(file)) throw new Error(`no such file: ${file}`);+ const b = execFileSync("ffmpeg", ["-v", "error", "-i", file, "-vn", "-f", "f32le", "-acodec", "pcm_f32le", "-ac", "2", "-ar", String(sr), "pipe:1"], { maxBuffer: 2 ** 31 });+ const f = new Float32Array(b.buffer, b.byteOffset, b.length / 4), n = f.length / 2, L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = f[2 * i]; R[i] = f[2 * i + 1]; }+ return [L, R];+};+/** 32-bit float stereo WAV: nothing clips on the way to the encoder. */+export const writeWav = (path, L, R, sr = SR) => {+ const n = L.length, data = Buffer.alloc(n * 8), h = Buffer.alloc(44);+ for (let i = 0; i < n; i++) { data.writeFloatLE(L[i], i * 8); data.writeFloatLE(R[i], i * 8 + 4); }+ h.write("RIFF", 0); h.writeUInt32LE(36 + data.length, 4); h.write("WAVEfmt ", 8); h.writeUInt32LE(16, 16); h.writeUInt16LE(3, 20); h.writeUInt16LE(2, 22);+ h.writeUInt32LE(sr, 24); h.writeUInt32LE(sr * 8, 28); h.writeUInt16LE(8, 32); h.writeUInt16LE(32, 34); h.write("data", 36); h.writeUInt32LE(data.length, 40);+ mkdirSync(dirname(resolve(path)), { recursive: true }); writeFileSync(path, Buffer.concat([h, data]));+};+const sha256 = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");+const probeDur = (file) => { const j = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,duration,avg_frame_rate:format=duration", "-of", "json", file]).toString()); const v = j.streams.find((s) => s.codec_type === "video"); const [a, b] = (v?.avg_frame_rate ?? "0/1").split("/").map(Number); return { video: v ? Number(v.duration ?? j.format.duration) : null, fps: b ? a / b : 0, duration: Number(j.format.duration), audio: j.streams.some((s) => s.codec_type === "audio") }; };+/** ffmpeg's own EBU R128 reading of a file: integrated loudness and true peak (what a platform measures). */+export const ebur = (file) => {+ const r = spawnSync("ffmpeg", ["-hide_banner", "-nostats", "-i", file, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"], { encoding: "utf8", maxBuffer: 1 << 26 });+ const s = r.stderr.slice(r.stderr.lastIndexOf("Summary:")), I = /I:\s+(-?[\d.]+|-inf) LUFS/.exec(s), P = /Peak:\s+(-?[\d.]+|-inf) dBFS/.exec(s);+ if (!I || !P) throw new Error(`could not meter ${file}: ${r.stderr.slice(-300)}`);+ return { lufs: Number(I[1]), tp: P[1] === "-inf" ? -Infinity : Number(P[1]) };+};+/** A film's length in seconds from its module (meta.durationFrames / meta.fps). */+const filmSeconds = async (name) => { const { loadFilmModule } = await import("./audio.mjs"); const { film } = await loadFilmModule(name); return { s: film.meta.durationFrames / film.meta.fps, fps: film.meta.fps }; };++// ---------------------------------------------------------------- arguments+const parseArgs = (argv) => {+ const pos = [], o = {};+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === "-o") { o.out = argv[++i]; continue; }+ if (a.startsWith("--")) { const k = a.slice(2), nx = argv[i + 1]; if (nx === undefined || nx.startsWith("--") || ["json", "from-pack"].includes(k)) o[k] = true; else { o[k] = nx; i++; } continue; }+ pos.push(a);+ }+ return { pos, o };+};+const num = (v, name) => { if (v === undefined) return undefined; const n = Number(v); if (!Number.isFinite(n)) throw new Error(`--${name} wants a number, got "${v}"`); return n; };++// ---------------------------------------------------------------- analyze+export const analyzeFile = async (file, o = {}) => { const T = await loadTrack(), [L, R] = decode(file); return T.analyzeTrack(L, R, SR, { bpm: o.bpm, downbeatS: o.downbeatS }); };+const fmtAnalysis = (a, file) => {+ const out = [`TRACK ${file}`, ` ${a.durationS} s, ${a.bpm} bpm (beat ${a.beatS} s, bar ${a.barS} s), first downbeat ${a.downbeatS} s`,+ ` tempo candidates: ${a.tempoCandidates.length ? a.tempoCandidates.map((c) => `${c.bpm} (${c.rel})`).join(", ") + " <- if your ear or the prompt says another, pin it with --bpm" : "pinned with --bpm"}`,+ ` key ${a.key.name}${a.key.confidence < 0.1 ? " (unclear: margin " + a.key.confidence + " over " + a.key.runnerUp + "; a generated take often ignores the key asked for)" : ` (margin ${a.key.confidence} over ${a.key.runnerUp})`}`,+ ` last note ends ${a.lastSoundS} s; ${a.tailS} s of silence after it${a.tailS > 0.5 ? " <- an edit must not reach past the last note" : ""}`,+ ` stops (designed drop-outs): ${a.stops.length ? a.stops.map((s) => `${s.atS} s for ${s.lenS} s`).join(", ") : "none"}`, "", " SECTIONS (by bar level against the body, " + a.bodyDb + " dB)"];+ for (const s of a.sections) out.push(` bars ${String(s.fromBar).padStart(3)}-${String(s.toBar).padEnd(4)} ${String(s.fromS).padStart(7)}-${String(s.toS).padEnd(8)} ${s.level.padEnd(6)} peak bar ${s.rmsDb} dB`);+ out.push("", " BARS (bar: start s, level dB)");+ for (let i = 0; i < a.bars.length; i += 6) out.push(" " + a.bars.slice(i, i + 6).map((b) => `${String(b.i).padStart(3)}: ${b.t.toFixed(2).padStart(6)} ${String(b.rmsDb).padStart(6)}`).join(" "));+ return out.join("\n");+};++// ---------------------------------------------------------------- cut+const readSegs = (T, o, a) => {+ const n = ["segs", "segs-file", "bars"].filter((k) => o[k] !== undefined);+ if (n.length !== 1) throw new Error("cut wants exactly one of --segs, --segs-file or --bars");+ const text = o["segs-file"] ? readFileSync(resolve(o["segs-file"]), "utf8") : o.bars ? `bars ${o.bars}` : String(o.segs);+ return T.parseSegs(text, a);+};+export const cutFile = async (file, o) => {+ const T = await loadTrack(), [L, R] = decode(file), a = T.analyzeTrack(L, R, SR, { bpm: num(o.bpm, "bpm"), downbeatS: num(o.downbeat, "downbeat") });+ const segs = readSegs(T, o, a), film = o.film ? await filmSeconds(o.film) : null, filmS = film?.s ?? num(o["film-s"], "film-s");+ const plan = T.planCut(a, segs, { filmS, fadeOutS: num(o["fade-out"], "fade-out"), endTolS: num(o["end-tol"], "end-tol") });+ return { a, plan, render: () => T.renderCut(L, R, SR, plan.segs, { xfadeMs: num(o.xfade, "xfade"), fadeOutS: num(o["fade-out"], "fade-out") }) };+};++// ---------------------------------------------------------------- prompt (never calls the provider)+export const PRICES = { "lyria-3.5": { usd: 0.08, unit: "song", checked: "2026-10-27", source: "https://ai.google.dev/gemini-api/docs/pricing" } };+export const promptText = (o) => {+ const len = num(o.len, "len"), bpm = num(o.bpm, "bpm");+ if (!len || !bpm) throw new Error("prompt wants --len <seconds> and --bpm <tempo>");+ const bar = (240 / bpm).toFixed(2), sections = String(o.sections ?? "").split(";").map((s) => s.trim()).filter(Boolean);+ const lines = [+ `Tempo is locked at exactly ${bpm} BPM (one beat every ${(60 / bpm).toFixed(2)} seconds, one bar every ${bar} seconds), steady metronomic tempo throughout, no tempo changes. Section boundaries fall exactly on bar lines.`, "",+ `${o.style ?? "Warm modern downtempo instrumental."}${o.key ? ` In ${o.key}.` : ""} Instrumental only, no vocals, no voices, no choir. Exactly ${bpm} BPM in 4/4, the first downbeat lands at 0:00 with no pickup or silence before it. Total length ${len} seconds, ending cleanly on one final button hit with under 2 seconds of tail and no long fade.`,+ ];+ if (sections.length) { lines.push(""); for (const s of sections) { const m = /^(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)\s+(.*)$/.exec(s); if (!m) throw new Error(`--sections: cannot read "${s}" (write "from-to Name: what happens")`); const t = (x) => `${Math.floor(x / 60)}:${String(Math.round(x % 60)).padStart(2, "0")}`; lines.push(`[${t(+m[1])} - ${t(+m[2])}] ${m[3]}`); } }+ return lines.join("\n");+};++// ---------------------------------------------------------------- kit+// The recorded route, ported from a brand launch film's hand-written kit script with its bug fixed by construction: every+// strike is cut from its own PEAK (the first cut trimmed leading silence and kept a -46 dB tick), then+// filtered, faded and normalised to -6 dBFS. Too short to carry a note under someone else's music.+export const PACK_KIT = [+ { name: "tick", pat: /^C7_l3_rr1.*\.flac$/, dir: "marimba", preMs: 1.5, lenMs: 16, af: "highpass=f=1800,afade=t=in:d=0.0008,afade=t=out:st=0.006:d=0.010" },+ { name: "tickHi", pat: /^C8_l2_rr1.*\.flac$/, dir: "glockenspiel", preMs: 1.0, lenMs: 10, af: "highpass=f=3000,afade=t=in:d=0.0006,afade=t=out:st=0.004:d=0.006" },+ { name: "tock", pat: /^C5_l3_rr1.*\.flac$/, dir: "marimba", preMs: 2.0, lenMs: 26, af: "highpass=f=500,lowpass=f=6000,afade=t=in:d=0.001,afade=t=out:st=0.010:d=0.016" },+ { name: "thump", pat: /^Timpani2A_l3_rr1.*\.flac$/, dir: "timpani", preMs: 3.0, lenMs: 110, af: "lowpass=f=150,lowpass=f=150,afade=t=in:d=0.002,afade=t=out:st=0.04:d=0.07" },+ { name: "impact", pat: /^Timpani3A_l3_rr1.*\.flac$/, dir: "timpani", preMs: 3.0, lenMs: 1600, af: "lowpass=f=500,afade=t=in:d=0.002,afade=t=out:st=0.6:d=1.0" },+];+/** Cut one transient from its peak: the sample index of the loudest sample, minus preMs. */+export const cutFromPeak = (x, sr, preMs, lenMs) => {+ let pk = 0, at = 0; for (let i = 0; i < x.length; i++) if (Math.abs(x[i]) > pk) { pk = Math.abs(x[i]); at = i; }+ const s = Math.max(0, at - Math.round((preMs * sr) / 1000)); return x.slice(s, s + Math.round((lenMs * sr) / 1000));+};++// ---------------------------------------------------------------- mix+/** A sounds map: cue name (or a prefix ending in *) -> "tap:thump -9 pan=0.3". The cue's own `sound` wins. */+const soundFor = (cue, map) => cue.sound ?? map[cue.name] ?? Object.entries(map).find(([k]) => k.endsWith("*") && cue.name.startsWith(k.slice(0, -1)))?.[1];++// ---------------------------------------------------------------- check (the muxed file)+/**+ * Everything a delivered external-track mix must pass, on the exact file: integrated loudness near the+ * target, true peak at or under the ceiling (AAC adds peak, so it is measured AFTER encoding), and the+ * film shape: the sound starts with the picture, has no hole, and does not stop before the picture does.+ */+export const checkFile = async (file, o = {}) => {+ const p = probeDur(file); if (!p.audio) throw new Error(`${basename(file)} has no audio stream`);+ const [L, R] = decode(file), m = ebur(file), rows = [], fps = num(o.fps, "fps") ?? (p.fps || 30);+ const lufsT = num(o.lufs, "lufs") ?? -14, tpT = num(o.tp, "tp") ?? -1;+ const picS = num(o["film-s"], "film-s") ?? p.video ?? p.duration, soundS = L.length / SR;+ const add = (ok, label, value, fix) => rows.push({ status: ok ? "PASS" : "FAIL", label, value, fix: ok ? undefined : fix });+ add(Math.abs(m.lufs - lufsT) <= 1, "integrated loudness", `${m.lufs} LUFS (target ${lufsT})`, `re-master to ${lufsT} LUFS: node tools/track.mjs master <picture> <mix.wav> -o <out>`);+ add(m.tp <= tpT, "true peak after encoding", `${m.tp} dBTP (ceiling ${tpT})`, "AAC adds about 3 dB of peak: master again (track.mjs master lowers the limiter until the ENCODED file passes)");+ const quiet = quietFrom(file, o).map(({ fromS, toS }) => [Math.floor(fromS * fps), Math.ceil(toS * fps)]);+ const shape = filmShape(L, R, SR, { fps, quiet });+ for (const pr of shape.problems) add(false, `sound shape: ${pr.kind}`, pr.msg, pr.kind === "dead end" ? "the music ends before the picture: extend the outro by whole bars (track.mjs cut --film-s), or end the picture on the music's last note" : "declare a designed silence in meta.quiet, or fill it");+ if (!shape.problems.length) add(true, "sound shape", `starts ${shape.firstS.toFixed(1)} s, longest hole ${shape.holeS.toFixed(1)} s, ends ${shape.endS.toFixed(1)} s before the picture`);+ if (p.video !== null || o["film-s"] !== undefined) add(soundS >= picS - 0.1, "sound covers the picture", `${soundS.toFixed(2)} s of sound for ${picS.toFixed(2)} s of picture`, "the audio stream is shorter than the picture: rebuild the mix at the film's length");+ return { file, rows, verdict: rows.some((r) => r.status === "FAIL") ? "FAIL" : "PASS", lufs: m.lufs, tp: m.tp };+};+/**+ * Designed silences in seconds: --quiet-from <cut.json|mix.json>, else the sidecars next to the file+ * (<out>.mix.json written by mix and copied by master), so a track's own hard stops are declared once,+ * by the analysis, and never reported as holes.+ */+const quietFrom = (file, o) => {+ const cands = [o["quiet-from"], `${file}.mix.json`, `${file}.cut.json`].filter(Boolean).map((f) => resolve(f));+ const f = cands.find((c) => existsSync(c)); if (o["quiet-from"] && !existsSync(resolve(o["quiet-from"]))) throw new Error(`--quiet-from: no such file ${o["quiet-from"]}`);+ return f ? JSON.parse(readFileSync(f, "utf8")).quiet ?? [] : [];+};+const printRows = (title, rows, verdict) => { console.log(title); for (const r of rows) console.log(` ${r.status.padEnd(5)} ${r.label.padEnd(28)} ${r.value}${r.fix ? `\n fix: ${r.fix}` : ""}`); console.log(`VERDICT: ${verdict}`); };++// ---------------------------------------------------------------- master+/**+ * The delivery chain a brand launch film ended on (loudnorm to the target, a limiter, AAC 256k), with+ * the step it did by hand made automatic: the true peak is read from the ENCODED file, and while it is+ * over the ceiling the limiter comes down by the excess and the file is encoded again (at most 5 times).+ */+export const master = (picture, mix, out, o = {}) => {+ const lufs = num(o.lufs, "lufs") ?? -14, ceil = num(o.tp, "tp") ?? -1;+ // The picture's length is measured on the SOURCE picture, never on the output: the film is never cut to+ // the mix. A mix shorter than the picture is refused before anything is written; a longer one is trimmed+ // to the picture.+ const pv = probeDur(picture), pictureS = pv.video ?? pv.duration, mixS = probeDur(mix).duration;+ if (!(pictureS > 0)) throw new Error(`${basename(picture)} has no picture to master onto`);+ if (mixS < pictureS - 0.05) return { out, ok: false, refused: `the mix ${basename(mix)} is ${mixS.toFixed(2)} s, shorter than the picture ${basename(picture)} (${pictureS.toFixed(2)} s): rebuild the mix at the film's length (track.mjs cut --film-s ${pictureS.toFixed(2)}). Nothing written.`, pictureS };+ let limitDb = ceil - 2.6, m = null; const tmp = out.replace(/\.[^.]+$/, "") + ".master.wav";+ try {+ for (let k = 0; k < 5; k++) {+ execFileSync("ffmpeg", ["-y", "-v", "error", "-i", mix, "-af", `loudnorm=I=${lufs}:TP=${ceil - 0.5}:LRA=11:linear=true,alimiter=limit=${Math.pow(10, limitDb / 20).toFixed(4)}:level=false:attack=3:release=60`, "-ar", String(SR), tmp]);+ execFileSync("ffmpeg", ["-y", "-v", "error", "-i", picture, "-t", pictureS.toFixed(4), "-i", tmp, "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-c:a", "aac", "-b:a", "256k", out]);+ m = ebur(out);+ if (m.tp <= ceil) break;+ limitDb -= m.tp - ceil + 0.3;+ }+ } finally { rmSync(tmp, { force: true }); }+ return { out, limitDb: +limitDb.toFixed(2), ...m, ok: m.tp <= ceil, pictureS };+};++// ---------------------------------------------------------------- listen+const listenPage = (title, items) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title>+<style>:root{--bg:#F0EEE6;--ink:#1d1b16;--line:#d8d3c4}@media (prefers-color-scheme:dark){:root{--bg:#1b1a17;--ink:#eeeae0;--line:#34322c}}body{background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,sans-serif;max-width:900px;margin:auto;padding:24px 16px}h1{font-size:24px}h2{font-size:17px;margin-top:24px}.g{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:10px}.c{border:1px solid var(--line);border-radius:10px;padding:10px 12px}audio{width:100%}</style></head><body>+<h1>${title}</h1><p>Listen before the full mix: the effects on their own, then ten seconds of the mix, then the takes. Your ears are the check the tools cannot make.</p>+${items.map(([h, list]) => `<h2>${h}</h2><div class="g">${list.map(([f, t, d]) => `<div class="c"><b>${t}</b><div>${d}</div><audio controls preload="none" src="${f}"></audio></div>`).join("")}</div>`).join("\n")}+</body></html>`;++// ---------------------------------------------------------------- command line+if (isMain(import.meta.url)) {+ const { pos, o } = parseArgs(process.argv.slice(2)), cmd = pos[0];+ const die = (msg, code = 2) => { console.error(`track: ${msg}`); process.exit(code); };+ try {+ if (cmd === "analyze") {+ if (!pos[1]) die("usage: node tools/track.mjs analyze <audio> [--bpm N] [--downbeat S] [--json] [--out a.json]");+ const a = await analyzeFile(resolve(pos[1]), { bpm: num(o.bpm, "bpm"), downbeatS: num(o.downbeat, "downbeat") });+ if (o.out) writeFileSync(resolve(o.out), JSON.stringify(a, null, 1) + "\n");+ console.log(o.json ? JSON.stringify(a, null, 1) : fmtAnalysis(a, pos[1]));+ } else if (cmd === "cut") {+ if (!pos[1] || !o.out) die("usage: node tools/track.mjs cut <audio> (--segs \"0:6,8:36\" | --segs-file f.txt | --bars \"0-3,4-18\") [--film <name> | --film-s S] [--fade-out S] -o cut.wav");+ const { a, plan, render } = await cutFile(resolve(pos[1]), o);+ console.log(`CUT ${pos[1]} (${a.bpm} bpm, bar ${a.barS} s, last note ${a.lastSoundS} s)`);+ plan.segs.forEach((s, i) => console.log(` ${String(i + 1).padStart(2)}. ${s.from}-${s.to} s (${(s.to - s.from).toFixed(2)} s, ${((s.to - s.from) / a.barS).toFixed(2)} bars)`));+ console.log(` edit length ${plan.lengthS} s; joins at ${plan.joins.map((j) => j.atS.toFixed(2)).join(", ") || "none"}`);+ for (const w of plan.warnings) console.log(` WARN ${w}`);+ for (const e of plan.errors) console.log(` FAIL ${e}`);+ if (plan.errors.length) { console.log("VERDICT: REFUSED (nothing written)"); process.exit(1); }+ const [L, R] = render(); writeWav(o.out, L, R);+ writeFileSync(o.out + ".cut.json", JSON.stringify({ source: resolve(pos[1]), sourceSha256: sha256(resolve(pos[1])), segs: plan.segs, lengthS: plan.lengthS, downbeats: plan.downbeats, quiet: plan.quiet, bpm: a.bpm }, null, 1) + "\n");+ console.log(`wrote ${o.out} (${(L.length / SR).toFixed(3)} s) and ${o.out}.cut.json (the edit's downbeats, for trackGrid)\nVERDICT: PASS`);+ } else if (cmd === "import") {+ if (!pos[1] || !o.provider) die("usage: node tools/track.mjs import <audio> --provider <model or source> [--cost USD] [--prompt p.txt] [--licence \"...\"]");+ const f = resolve(pos[1]), a = await analyzeFile(f, {});+ const man = { file: basename(f), sha256: sha256(f), provider: o.provider, costUsd: num(o.cost, "cost") ?? null, prompt: o.prompt ? readFileSync(resolve(o.prompt), "utf8") : null, licence: o.licence ?? null, importedAt: new Date().toISOString().slice(0, 10), analysis: { durationS: a.durationS, bpm: a.bpm, downbeatS: a.downbeatS, key: a.key.name, lastSoundS: a.lastSoundS, tailS: a.tailS, stops: a.stops } };+ writeFileSync(f + ".track.json", JSON.stringify(man, null, 1) + "\n");+ console.log(`pinned ${man.file} sha256 ${man.sha256.slice(0, 16)}... -> ${basename(f)}.track.json\n${fmtAnalysis(a, pos[1]).split("\n").slice(0, 4).join("\n")}`);+ } else if (cmd === "prompt") {+ const text = promptText(o), model = o.model ?? "lyria-3.5", price = PRICES[model];+ if (o.out) writeFileSync(resolve(o.out), text + "\n");+ console.log(text);+ console.log(`\n---\nNot sent. This tool never calls a paid API. ${price ? `${model} costs $${price.usd} per ${price.unit} (checked ${price.checked}, ${price.source}); check the page again before running.` : `No price on record for ${model}: look it up before running.`}\nState the cost to the person before generating, log every take in a COST.md ledger (date, model, result, cost), and ask for 3 to 4 takes: a model ignores exact timestamps, so the picture is fitted to the take with 'track.mjs analyze' and 'cut'.`);+ } else if (cmd === "kit") {+ if (!pos[1]) die("usage: node tools/track.mjs kit <outdir> [--from-pack]");+ const T = await loadTrack(), dir = resolve(pos[1]); mkdirSync(dir, { recursive: true });+ const rows = [];+ if (o["from-pack"]) {+ const pack = process.env.ANIDOODLE_SOUNDS || join(homedir(), ".anidoodle", "sounds");+ for (const k of PACK_KIT) {+ const d = join(pack, k.dir); if (!existsSync(d)) die(`the sound pack has no ${k.dir}/ (fetch it: node tools/soundfetch.mjs)`);+ const src = readdirSync(d).filter((f) => k.pat.test(f)).sort()[0]; if (!src) die(`no ${k.pat} in ${d}`);+ const [xl, xr] = decode(join(d, src)), seg = cutFromPeak(T.monoOf(xl, xr), SR, k.preMs, k.lenMs), raw = join(dir, `_${k.name}.wav`), out = join(dir, `${k.name}.wav`);+ writeWav(raw, seg, seg); execFileSync("ffmpeg", ["-y", "-v", "error", "-i", raw, "-af", k.af, "-c:a", "pcm_f32le", join(dir, `_${k.name}2.wav`)]);+ const [y] = decode(join(dir, `_${k.name}2.wav`)); let pk = 0; for (const v of y) pk = Math.max(pk, Math.abs(v)); const g = Math.pow(10, -6 / 20) / Math.max(pk, 1e-9); const z = y.map((v) => v * g);+ writeWav(out, z, z); for (const f of [raw, join(dir, `_${k.name}2.wav`)]) rmSync(f, { force: true });+ rows.push([k.name, T.pitchSalience(z, SR), `${src}`]);+ }+ } else {+ for (const v of T.sfxVariants("tap")) { const s = T.renderSfx("tap", { variant: v, seed: 1 }, SR); writeWav(join(dir, `${v}.wav`), s.L, s.R); rows.push([v, T.pitchSalience(T.monoOf(s.L, s.R), SR), "engine tap:" + v]); }+ }+ console.log(`KIT ${dir}`); for (const [n, p, src] of rows) console.log(` ${(p.salience > T.PITCHED ? "FAIL" : "PASS").padEnd(5)} ${n.padEnd(8)} pitch salience ${p.salience.toFixed(2)} (raw ${p.raw}, rings ${p.ringMs} ms${Number.isFinite(p.hz) ? `, ${p.hz} Hz` : ""}) ${src}`);+ if (rows.some(([, p]) => p.salience > T.PITCHED)) process.exit(1);+ } else if (cmd === "mix") {+ if (!o.music || !o.cues || !o.out) die("usage: node tools/track.mjs mix --music cut.wav --cues out/<film>.cues.json [--sounds map.json] -o mix.wav [--stem sfx.wav]");+ const T = await loadTrack(), cuesDoc = JSON.parse(readFileSync(resolve(o.cues), "utf8")), map = o.sounds ? JSON.parse(readFileSync(resolve(o.sounds), "utf8")) : {};+ if (!Array.isArray(cuesDoc.cues) || !cuesDoc.fps || !cuesDoc.durationFrames) die(`${o.cues} is not a cue sheet (write one with: node tools/cues.mjs <film>)`);+ const cues = []; const unsounded = [];+ for (const c of cuesDoc.cues) { const spec = soundFor(c, map); if (spec === undefined) { unsounded.push(c.name); continue; } if (spec === null || spec === "none") continue; cues.push({ ...T.parseSoundSpec(spec), frame: c.frame, label: c.name }); }+ if (unsounded.length) console.log(` note: ${unsounded.length} cue(s) have no sound (silent on purpose?): ${unsounded.slice(0, 8).join(", ")}${unsounded.length > 8 ? " ..." : ""}`);+ const music = decode(resolve(o.music)), m = T.mixOverTrack(music, { fps: cuesDoc.fps, frames: cuesDoc.durationFrames, cues, seed: 1 }, SR);+ console.log(T.trackMixReport(m));+ if (!m.ok) { console.log("VERDICT: FAIL (nothing written)"); process.exit(1); }+ writeWav(o.out, m.L, m.R); if (o.stem) writeWav(o.stem, m.sfx[0], m.sfx[1]);+ const cutJson = resolve(o.music) + ".cut.json", quiet = existsSync(cutJson) ? JSON.parse(readFileSync(cutJson, "utf8")).quiet ?? [] : [];+ writeFileSync(o.out + ".mix.json", JSON.stringify({ music: resolve(o.music), musicSha256: sha256(resolve(o.music)), cues: resolve(o.cues), cuesSha256: sha256(resolve(o.cues)), film: cuesDoc.film ?? null, lufs: m.lufs, dbtp: m.dbtp, quiet }, null, 1) + "\n");+ console.log(`wrote ${o.out}${o.stem ? ` and ${o.stem}` : ""}\nVERDICT: PASS`);+ } else if (cmd === "master") {+ if (!pos[1] || !pos[2] || !o.out) die("usage: node tools/track.mjs master <picture.mp4> <mix.wav> -o out.mp4 [--tp -1] [--lufs -14]");+ const r = master(resolve(pos[1]), resolve(pos[2]), resolve(o.out), o);+ if (r.refused) { console.log(`MASTER ${o.out}\n FAIL ${r.refused}\nVERDICT: FAIL`); process.exit(1); }+ // The sidecar beside the output always describes THIS mix: an older one is removed first, so+ // provenance never reads the previous mix's record.+ const side = resolve(o.out) + ".mix.json"; rmSync(side, { force: true });+ if (existsSync(resolve(pos[2]) + ".mix.json")) copyFileSync(resolve(pos[2]) + ".mix.json", side);+ else console.log(` note: no mix sidecar beside ${basename(pos[2])} (track.mjs mix writes one), so ${basename(side)} is not written and provenance will fail`);+ // The picture's film sidecar (<picture>.film.json, written by render) goes with it, re-hashed for the+ // mastered file, so ship and verify-export read the film's own settings from the delivered file. An+ // older one beside the output is removed first, as with the mix sidecar.+ const filmSide = resolve(o.out) + ".film.json", picSide = resolve(pos[1]) + ".film.json"; rmSync(filmSide, { force: true });+ if (existsSync(picSide)) { const rec = JSON.parse(readFileSync(picSide, "utf8")); writeFileSync(filmSide, JSON.stringify({ ...rec, file: basename(resolve(o.out)), sha256: sha256(resolve(o.out)), masteredFrom: basename(resolve(pos[1])) }, null, 1) + "\n"); }+ else console.log(` note: no film sidecar beside ${basename(pos[1])} (render writes one), so ${basename(filmSide)} is not written`);+ console.log(`MASTER ${o.out}: ${r.lufs} LUFS, ${r.tp} dBTP after AAC (limiter at ${r.limitDb} dB)`);+ // the picture length comes from the source picture, so the check can never measure a cut output against itself+ const c = await checkFile(resolve(o.out), { ...o, "film-s": o["film-s"] ?? r.pictureS }); printRows("CHECK (the muxed file)", c.rows, c.verdict);+ process.exit(r.ok && c.verdict === "PASS" ? 0 : 1);+ } else if (cmd === "check") {+ if (!pos[1]) die("usage: node tools/track.mjs check <file.mp4|wav> [--film-s S] [--fps N] [--lufs -14] [--tp -1] [--json]");+ const c = await checkFile(resolve(pos[1]), o);+ if (o.json) console.log(JSON.stringify(c, null, 1)); else printRows(`TRACK CHECK ${pos[1]}`, c.rows, c.verdict);+ process.exit(c.verdict === "PASS" ? 0 : 1);+ } else if (cmd === "listen") {+ if (!pos[1] || !o.mix) die("usage: node tools/track.mjs listen <outdir> --mix mix.wav [--at 20] [--len 10] [--takes a.wav,b.wav] [--kit dir]");+ const T = await loadTrack(), dir = resolve(pos[1]); mkdirSync(dir, { recursive: true });+ const mp3 = (src, out, extra = []) => execFileSync("ffmpeg", ["-y", "-v", "error", ...extra, "-i", src, "-codec:a", "libmp3lame", "-b:a", "256k", join(dir, out)]);+ const kitRows = [];+ if (o.kit) for (const f of readdirSync(resolve(o.kit)).filter((f) => f.endsWith(".wav")).sort()) { mp3(join(resolve(o.kit), f), `kit-${f.replace(/\.wav$/, ".mp3")}`); kitRows.push([`kit-${f.replace(/\.wav$/, ".mp3")}`, f.replace(/\.wav$/, ""), "recorded transient"]); }+ else for (const v of T.sfxVariants("tap")) { const s = T.renderSfx("tap", { variant: v, seed: 1 }, SR), w = join(dir, `_${v}.wav`); writeWav(w, s.L, s.R); mp3(w, `kit-${v}.mp3`); rmSync(w, { force: true }); kitRows.push([`kit-${v}.mp3`, `tap:${v}`, T.sfxInfo("tap").use]); }+ const at = num(o.at, "at") ?? 20, len = num(o.len, "len") ?? 10;+ mp3(resolve(o.mix), "mix-sample.mp3", ["-ss", String(at), "-t", String(len)]);+ const takes = String(o.takes ?? "").split(",").filter(Boolean).map((t, i) => { mp3(resolve(t), `take-${i + 1}.mp3`); return [`take-${i + 1}.mp3`, basename(t), ""]; });+ writeFileSync(join(dir, "index.html"), listenPage("Sound check by ear", [["The effects, alone", kitRows], [`The mix, ${len} s from ${at} s`, [["mix-sample.mp3", "mix sample", basename(o.mix)]]], ...(takes.length ? [["The takes", takes]] : [])]));+ console.log(`wrote ${join(dir, "index.html")}: ${kitRows.length} effects, a ${len} s mix sample${takes.length ? `, ${takes.length} takes` : ""}. Open it and listen before rendering the full mix.`);+ } else die("commands: analyze, cut, import, prompt, kit, mix, master, check, listen (see the header of tools/track.mjs)");+ } catch (e) { die(e.message, 2); }+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjsindex b7624df..f59090e 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs@@ -5,7 +5,9 @@// colour to assert, and a one-shot film has no seam to hide.//// node tools/verify-export.mjs <film> [--file out/x.mp4] [--adapter html-player]-// node tools/verify-export.mjs out/<film>.mp4 [...] the file itself: the film is its name (out/<film>[.<from>-<to>].<ext>)+// node tools/verify-export.mjs out/<file>.mp4 [...] the file itself: the film is its sidecar's (<file>.film.json,+// written by render), else its name (out/<film>[.<from>-<to>].<ext>); a renamed file+// with neither gets the --file form to run instead// [--width W] expected pixel width of a .gif/.webm/.apng made with render --width// (default: the film's own; height follows the aspect). Not for .mp4:// render always writes the MP4 at the film's size (x --scale), so@@ -33,7 +35,8 @@import { execFileSync, spawnSync } from "node:child_process";import { existsSync, mkdirSync, writeFileSync } from "node:fs";import { basename, resolve } from "node:path";-import { defaultOutput, requireFilm } from "./names.mjs";+import { defaultOutput, knownFilms, requireFilm } from "./names.mjs";+import { filmOfFile, readSidecar, trackProvenance } from "./sidecar.mjs";import { firstFrameBlank } from "./thumb.mjs";import { mono, onsetNear, xcorrOffset } from "./avsync.mjs";import { filmShape } from "./filmshape.mjs";@@ -46,7 +49,9 @@ const USAGE = "node tools/verify-export.mjs <film> [--file out/<film>.mp4] [--fiif (pos[0] && /\.(mp4|gif|webm|apng|png)$/i.test(pos[0])) {if (opt.file) { console.error(`verify-export: give the file once: '${pos[0]}' or --file ${opt.file}`); process.exit(2); }if (!existsSync(pos[0])) { console.error(`verify-export: no file '${pos[0]}'`); process.exit(2); }- opt.file = pos[0]; pos[0] = basename(pos[0]).split(".")[0];+ opt.file = pos[0]; const who = filmOfFile(pos[0], knownFilms());+ if (!who.film) { console.error(`verify-export: ${who.why}`); process.exit(2); }+ pos[0] = who.film; console.log(`film "${who.film}" from the ${who.how}`);}const film = requireFilm(pos[0], "verify-export", USAGE);const adapterName = opt.adapter ?? "html-player";@@ -80,6 +85,13 @@ const file = resolve(opt.file ?? defaultOutput(film));console.log(`VERIFY-EXPORT film "${meta.title}" file ${file}`);if (!existsSync(file)) die(`${file} not found`);const isMp4 = /\.(mp4|m4v|mov)$/i.test(file);+// the sidecar render wrote beside the file: it must name THIS film, and a placeholder render never ships+{ const sc = readSidecar(file);+ if (sc?.error) die(sc.error);+ if (sc?.film && sc.film !== film) die(`${basename(file)} was rendered from film '${sc.film}' (its sidecar), not '${film}'`);+ if (sc?.stale) note("the sidecar's hash does not match the file", "the file changed after render wrote it: re-render, or check what touched it");+ const ph = [...new Set([...(sc?.placeholders ?? []), ...(meta.placeholders ?? [])])];+ if (ph.length) (opt.delivery ? (l, d) => say(false, l, d) : note)(`rendered with ${ph.length} placeholder asset(s): ${ph.join(", ")}`, "a labelled grey box stands in for each; --delivery refuses it"); }if (opt.width && isMp4) die(`--width does not apply to an MP4: render writes it at the film's own size (x --scale); use --scale to check a scaled render`);const FRAME = opt.frame === undefined ? 0 : Number(opt.frame);if (!Number.isInteger(FRAME) || FRAME < 0 || FRAME >= N) die(`--frame wants a frame number in [0, ${N - 1}], got '${opt.frame}'`);@@ -100,7 +112,9 @@ say(Math.abs(dur - wantDur) <= slack, `duration ${dur.toFixed(3)} s`, `expectedif (isMp4) {head("1b", "SOUND the score is in the file, as long as the picture, and audible");const a = ffprobe(["-select_streams", "a", "-show_entries", "stream=codec_name,duration,sample_rate,channels", "-of", "csv=p=0", file]).split("\n").filter(Boolean);- const hasAudio = meta.hasAudio ?? Boolean(await s.audio?.(48000)); // older pages / other adapters: ask the score itself+ // a supplied or generated track (meta.checks.music.track) is mixed outside the page: the file must carry it+ const ext = meta.checks?.music?.track ? resolve(meta.checks.music.track) : null;+ const hasAudio = ext ? true : meta.hasAudio ?? Boolean(await s.audio?.(48000)); // older pages / other adapters: ask the score itselfif (!hasAudio) say(a.length === 0, "no audio stream (the film has no score)", a.length ? `found ${a.length}: ${a.join(" | ")}` : "");else if (!a.length) say(false, "an audio stream (the film has a score)", "none found: was it a range render?");else {@@ -111,6 +125,11 @@ if (isMp4) {const mx = Number(((vd.stdout + vd.stderr).match(/max_volume:\s*(-?[0-9.]+|-inf) dB/) ?? [])[1]);say(Number.isFinite(mx) && mx > -40 && mx <= 0, `audio peak ${Number.isFinite(mx) ? mx.toFixed(1) : "-inf"} dBFS`, "audible (> -40 dBFS) and not clipped past 0");+ if (ext) {+ head("1c", "TRACK the music is the pinned take (an external track, mixed by track.mjs)");+ const pv = trackProvenance(ext, file); say(pv.ok, "the delivered mix comes from the take its manifest pins", pv.detail);+ note("shape, holes and the ending of an external track", "track.mjs check measures them on this file against the track's declared stops (ship runs it)");+ } else {head("1c", "SYNC the delivered sound sits on the picture's frames");const SR = 48000, dec = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-map", "0:a:0", "-f", "f32le", "-ac", "2", "-ar", String(SR), "-"], { maxBuffer: 1 << 30 });if (dec.status !== 0) die(`ffmpeg could not decode the audio: ${dec.stderr.toString().trim()}`);@@ -138,6 +157,8 @@ if (isMp4) {}}+ }+head("1d", "PEAK the true peak of the file as delivered (after the encode)");const eb = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", file, "-map", "0:a:0", "-af", "ebur128=peak=true", "-f", "null", "-"], { encoding: "utf8", maxBuffer: 1 << 26 });const txt = eb.stdout + eb.stderr, tp = Number((txt.match(/True peak:\s*\n\s*Peak:\s*(-?[0-9.]+|-inf) dBFS/) ?? [])[1]), il = Number((txt.match(/Integrated loudness:\s*\n\s*I:\s*(-?[0-9.]+) LUFS/) ?? [])[1]);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/worldfilm.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/worldfilm.mjsnew file mode 100644index 0000000..973797e--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/worldfilm.mjs@@ -0,0 +1,75 @@+// node tools/worldfilm.mjs <name> [--dir .] [--beats 4] [--format 16x9|9x16|1x1|4x5] [--fps 30] [--temperament calm|lively|snappy]+// A NEW MOTION FILM, STARTED AS ONE WORLD. Writes src/canvas-core/<name>.ts and src/hosts/page-<name>.ts:+// every beat is a region of one canvas, one camera travels between them (world.ts), each beat's title+// enters and leaves with setType (exit on an ease-in, 1.3x), sides alternate (alternate(i)), the camera+// breathes, and meta.motion names the temperament and the brand colours for motionscan and layerscan.+// It is the default for a launch or motion-graphics film because a brand launch film was built scene+// by scene and read as "a LITERAL SLIDE DECK". Replace the titles and the cards; keep the structure.+// Refuses to overwrite. Prints the next commands.+import { existsSync, mkdirSync, writeFileSync } from "node:fs";+import { join, resolve } from "node:path";+import { isMain } from "./is-main.mjs";++const SHAPES = { "16x9": [1920, 1080], "9x16": [1080, 1920], "1x1": [1080, 1080], "4x5": [1080, 1350] };++/** The source of a one-world film module: `beats` regions, a hold and a camera move each, on the beat grid. */+export const worldFilmSource = (name, { beats = 4, format = "16x9", fps = 30, bpm = 120, temperament = "calm" } = {}) => {+ const [W, H] = SHAPES[format] ?? (() => { throw new Error(`worldfilm: format is one of ${Object.keys(SHAPES).join(", ")}`); })();+ if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(name)) throw new Error(`worldfilm: '${name}' must be a bare identifier (it becomes a module and an export name)`);+ if (!(Number.isInteger(beats) && beats >= 2 && beats <= 12)) throw new Error(`worldfilm: --beats is 2 to 12 (got ${beats})`);+ const beat = (60 / bpm) * fps; if (!Number.isInteger(beat)) throw new Error(`worldfilm: ${bpm} bpm at ${fps} fps is not a whole number of frames a beat`);+ const share = { calm: 0.35, lively: 0.55, snappy: 0.8 }[temperament]; if (!share) throw new Error(`worldfilm: temperament is calm, lively or snappy (got ${temperament})`);+ const portrait = H > W, zoom = 1 / 1.16, step = portrait ? Math.hypot(0.35 * W, 1.1 * H) : Math.hypot(1.1 * W, 0.35 * H);+ // the camera's move is long enough for the temperament: an in-out cubic peaks at 3x its mean speed (world.minTravel)+ const move = Math.ceil(Math.ceil((3 * step * zoom) / ((share * 2.5 * W) / fps)) / beat) * beat, hold = beat * 4, dur = beats * hold + (beats - 1) * move + beat * 2; // 4 beats on each region, then the move, 2 beats to land+ return `// ${name}: ONE WORLD. Every beat is a region of one canvas; one camera travels between them. Replace the+// titles and the card drawing; keep the structure: no beat is a slide, every seam is a camera move.+// Check it with: node tools/motionscan.mjs ${name} and node tools/layerscan.mjs ${name}+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import { setType } from "./kinetic";+import { alternate } from "./motionKit";+import { world, type Rect } from "./world";++const W = ${W}, H = ${H}, FPS = ${fps}, BPM = ${bpm}, HOLD = ${hold}, MOVE = ${move};+const INK = "#111214", PAPER = "#f4f1ea", ACCENT = "#ffde59"; // put the brand's own colours here (and in meta.motion.brandColors)+const TITLES = [${Array.from({ length: beats }, (_, i) => `"Beat ${i + 1}: one line that says it"`).join(", ")}];+const clamp = (v: number) => Math.max(0, Math.min(1, v));++// regions sit along a gentle path, ${portrait ? "stacked down the canvas for a phone frame" : "across the canvas"}; each is one frame big+const REGIONS = TITLES.map((_, i) => ({ id: \`b\${i}\`, rect: [${portrait ? "(i % 2) * W * 0.35, i * H * 1.1" : "i * W * 1.1, (i % 2) * H * 0.35"}, W, H] as Rect }));+const STOPS = TITLES.map((_, i) => ({ f: i * (HOLD + MOVE), at: \`b\${i}\`, hold: HOLD }));+const W0 = world({ W, H, regions: REGIONS, stops: STOPS, alive: { amp: 3, seed: 7 } });++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);+ W0.begin(ctx, env, f);+ TITLES.forEach((title, i) => W0.region(ctx, \`b\${i}\`, (r) => {+ const [x, y, w, h] = r.rect, left = alternate(i, [true, false]), t0 = i * (HOLD + MOVE);+ ctx.fillStyle = ACCENT; ctx.fillRect(left ? x + w * 0.06 : x + w * 0.54, y + h * 0.18, w * 0.4, h * 0.64); // the beat's card: opaque, moved by the camera, never faded+ const enter = clamp((f - t0 + MOVE * 0.4) / (FPS * 0.6)), leave = clamp((f - t0 - HOLD) / (FPS * 0.6));+ setType(ctx, env, title, left ? x + w * 0.52 : x + w * 0.06, y + h * 0.52, ${portrait ? 64 : 72}, enter, { color: INK, weight: 800, space: "world", out: i === TITLES.length - 1 ? 0 : leave });+ }));+ W0.end(ctx);+};++export const ${name}: Film = {+ meta: { title: "${name}", W, H, fps: FPS, bpm: BPM, durationFrames: ${dur}, motion: { temperament: "${temperament}", brandColors: [ACCENT] } },+ assets: { images: {} },+ shots: [{ id: "world", start: 0, end: ${dur}, draw }],+};+`;+};++if (isMain(import.meta.url)) {+ const pos = [], opt = {};+ for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = process.argv[++i]; else pos.push(a); }+ const name = pos[0], dir = resolve(opt.dir ?? ".");+ if (!name) { console.error("usage: node tools/worldfilm.mjs <name> [--dir .] [--beats 4] [--format 16x9|9x16|1x1|4x5] [--fps 30] [--temperament calm|lively|snappy]"); process.exit(2); }+ let src; try { src = worldFilmSource(name, { beats: Number(opt.beats ?? 4), format: opt.format ?? "16x9", fps: Number(opt.fps ?? 30), temperament: opt.temperament ?? "calm" }); } catch (e) { console.error(String(e.message ?? e)); process.exit(2); }+ const mod = join(dir, "src/canvas-core", `${name}.ts`), host = join(dir, "src/hosts", `page-${name}.ts`);+ if (existsSync(mod) || existsSync(host)) { console.error(`worldfilm: ${name} already exists in ${dir}; refusing to overwrite`); process.exit(2); }+ mkdirSync(join(dir, "src/canvas-core"), { recursive: true }); mkdirSync(join(dir, "src/hosts"), { recursive: true });+ writeFileSync(mod, src); writeFileSync(host, `import { ${name} } from "../canvas-core/${name}";\nimport { mountFilm } from "./page";\n\nmountFilm(${name});\n`);+ console.log(`one-world film ${name}\n ${mod}\n ${host}\nnext:\n node tools/still.mjs ${name} --frames 0,${Math.round(0.5 * 30 * 4)} --sheet out/${name}-sheet.jpg\n node tools/render.mjs ${name}\n node tools/motionscan.mjs ${name} node tools/layerscan.mjs ${name}`);+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tsconfig.json b/plugins/anidoodle/skills/anidoodle/engine/tsconfig.jsonindex 25da5d9..aabdbf3 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tsconfig.json+++ b/plugins/anidoodle/skills/anidoodle/engine/tsconfig.json@@ -1,8 +1,9 @@{"compilerOptions": {"target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "jsx": "react-jsx",- "strict": true, "noEmit": true, "skipLibCheck": true, "esModuleInterop": true, "lib": ["DOM", "ES2022"],- "rootDirs": ["src", "../example/src"]+ "strict": true, "noEmit": true, "skipLibCheck": true, "esModuleInterop": true, "resolveJsonModule": true, "lib": ["DOM", "ES2022"],+ "rootDirs": ["src", "../example/src"],+ "paths": { "three": ["./vendor/three/types/Three.d.ts", "./vendor/three/three-untyped.d.ts"] }},"include": ["src", "test", "../example/src"]}diff --git a/plugins/anidoodle/skills/anidoodle/engine/vendor/three/LICENSE b/plugins/anidoodle/skills/anidoodle/engine/vendor/three/LICENSEnew file mode 100644index 0000000..d33709f--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/vendor/three/LICENSE@@ -0,0 +1,21 @@+The MIT License++Copyright © 2010-2024 three.js authors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.diff --git a/plugins/anidoodle/skills/anidoodle/engine/vendor/three/PROVENANCE.md b/plugins/anidoodle/skills/anidoodle/engine/vendor/three/PROVENANCE.mdnew file mode 100644index 0000000..db2c5d5--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/vendor/three/PROVENANCE.md@@ -0,0 +1,8 @@+# three.js 0.170.0 (vendored)++- `three.module.js`: `build/three.module.js` from the npm tarball `[email protected]` (sha512 matched npm's published integrity). sha256 `ce1fa418de16a19495a9f72495580e3015d7745c296d3ce0485897f902ddedfb`.+- `types/`: `src/**/*.d.ts` from `@types/[email protected]` (sha512 `CUm2uckq...QFAyg==` matched). Type declarations only, no runtime code. sha256 of all .d.ts in path order: `0f922d42e410315f052b7360dc3ce60a24b13003c88aa41f82102659c3c98570`.+- Licence: MIT (`LICENSE`, three.js authors; @types/three is MIT too).+- Security: scanned with repo-forensics 2.14.19 (30 scanners, coverage COMPLETE) on 2026-10-28. 0 block, 0 critical. All 60 warnings adjudicated benign: 54 are doc comments ("Create a new instance of ..."), the rest are a GitHub URL and `////` rule lines read as base64, and `lists.get( scene )` read as an AWS key. No eval, no new Function. The loaders that fetch are never called: anidoodle pages have no network.+- The installed plugin leaves `three.module.js` and `types/` out (plugin directories hold files over 256 KiB and plugins over 512 files). There `package.json` pins `three` 0.170.0 exactly and `npm install` brings the same file; `tools/overlay.mjs` refuses any three.js whose sha256 is not the one above, and `three-untyped.d.ts` lets films type-check without the types.+- Nothing else from the package is used. Upgrading means a new scan and new hashes here and in `tools/overlay.mjs` (`THREE_SHA256`); `test/threePin.test.ts` checks it.diff --git a/plugins/anidoodle/skills/anidoodle/engine/vendor/three/three-untyped.d.ts b/plugins/anidoodle/skills/anidoodle/engine/vendor/three/three-untyped.d.tsnew file mode 100644index 0000000..85f4d68--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/vendor/three/three-untyped.d.ts@@ -0,0 +1,5 @@+// The installed plugin leaves out three.js's 500 type files (plugin directories cap a plugin at 512 files).+// tsconfig falls back to this file when vendor/three/types is absent: "three" type-checks as untyped there.+// The repository keeps the full types, so the engine's own code is always checked against them.+declare const THREE: any;+export = THREE;diff --git a/plugins/anidoodle/skills/anidoodle/references/camera.md b/plugins/anidoodle/skills/anidoodle/references/camera.mdindex 0d997ee..c687731 100644--- a/plugins/anidoodle/skills/anidoodle/references/camera.md+++ b/plugins/anidoodle/skills/anidoodle/references/camera.md@@ -1,5 +1,7 @@# The camera: one dolly and one lens, keyed on the frame grid+**Contents:** The move · Depth planes (parallax) · Lens and dolly · Time: speed ramps, slow motion, freeze frames · Shake · Line weight at close range · The two drawing paths+`engine/src/canvas-core/camera.ts` is the camera. A film either draws in world coordinatesinside `begin()`/`end()` (the transform path: dirty boxes stay right because the camera ridesthe `Gfx` transform stack), or asks `toScreen()` where a world point lands and draws there (the@@ -93,6 +95,10 @@ name(g, f); // the writing, on the film's own framecues.push({ frame: t.filmFrameOf(LANDING), kind: "paper" }); // a sound on a remapped event```+- **Every key names its unit**: `f` (a film frame), `film` (seconds of film time) or `scene` (seconds of+ scene time, resolved through the keys before it), exactly one. A bare number throws, because a+ speed key set in scene seconds when film seconds were meant once put a logo's speed-up in the wrong+ place.- **A ramp eases the speed**, on a smoothstep (or `curve: "linear"`), so it starts and ends withno kick. `ramp` defaults to 0, a deliberate hard change of speed; give it frames to glide. A slowed scene is asked for frames between its frames, so it mustdraw at fractional time (motion is a function of time, never of a frame counter).diff --git a/plugins/anidoodle/skills/anidoodle/references/determinism-and-contract.md b/plugins/anidoodle/skills/anidoodle/references/determinism-and-contract.mdindex ed0c934..772c646 100644--- a/plugins/anidoodle/skills/anidoodle/references/determinism-and-contract.md+++ b/plugins/anidoodle/skills/anidoodle/references/determinism-and-contract.md@@ -10,7 +10,10 @@1. `renderFrame(frame, env)` is PURE. No state carried between frames, no module-level mutable state that touches pixels. Audio is the same: samples are a pure function of the sample rate.2. Randomness only from `rng(seed)`. Never `Math.random`. Never `Date`, never `performance.now` in the core; timing belongs to hosts.3. A restricted canvas: paths, fill, stroke, clip, transforms, alpha, composite operations, patterns, gradients, `drawImage`, image data, `fillText` with a preloaded font. **No `ctx.filter` in any form.** No DOM, no `window`, no `new OffscreenCanvas` or `new Image`; surfaces come from `env.canvas()`.-4. **No assets.** No images, no fonts, no audio files in the repository. Lettering is pen strokes; texture is seeded noise; music is arithmetic. This is what makes the repo the whole film, with no licensing questions. The optional sound pack is the one thing fetched from outside, it is installed by hash, and a film renders without it.+4. **No assets, with three named exceptions.** No images, no fonts, no audio files in the repository. Lettering is pen strokes; texture is seeded noise; music is arithmetic. This is what makes the repo the whole film, with no licensing questions. The optional sound pack is the one thing fetched from outside, it is installed by hash, and a film renders without it. Three things are carried as data because code cannot make them, each pinned by hash so a build can never change under a film:+ - **three.js**, vendored at `engine/vendor/three/` (MIT, scanned and hash-pinned, `PROVENANCE.md` there). Films import it as `import * as THREE from "three"` in each file and never re-export the namespace: a re-export keeps three's file loaders, which can fetch, in the player, and the gate fails a player that can reach the network.+ - **One font for 3D type**, Poppins Bold (SIL OFL 1.1), carried as a base64 module (`engine/assets/fonts/poppinsBold.ts`, provenance in `engine/assets/fonts/PROVENANCE.md`), so no file is read and nothing is fetched at draw time. 2D lettering stays pen strokes.+ - **Baked narration takes**, the one generated input: only when the person asks for narration, in the voice they chose, each take cached by a hash of what made it and baked into the film as data by `tools/narrate.mjs bake` (`references/workflows/narration.md`). A take made with macOS `say` is a draft and is never committed.5. Caches are legal only when the value is a pure function of its key, and **the key names everything the pixels depend on**. We found two violations by machine, never by eye: an annotation layer whose key omitted the crank angle two of its leaders pointed at, and one that omitted the pose. A cached frame and a cold frame of the same number must be the same pixels.6. Never scale a bitmap up. Close shots are re-inked at that view; cached surfaces may only be downscaled, and only a little.diff --git a/plugins/anidoodle/skills/anidoodle/references/formats.md b/plugins/anidoodle/skills/anidoodle/references/formats.mdindex a619741..47240b5 100644--- a/plugins/anidoodle/skills/anidoodle/references/formats.md+++ b/plugins/anidoodle/skills/anidoodle/references/formats.md@@ -1,5 +1,7 @@# Formats: what you are making, and how each one ships+**Contents:** Stills: hero art, spots, covers, cards, diagrams · Motion without a story: loops, stickers, logos, ambient art · Films: the story ones · Delivering+Everything is a `Film`: meta, shots that tile `[0, duration)`, and optionally a score. A stillis a film one frame long, so every tool works on every format. Scaffold the kind you need:@@ -88,9 +90,21 @@ Render options that hold for every moving format:Words on screen, wherever the shape:-- **Reading time.** Each text stays up at least `max(0.7 s, 0.3 s per word)`. A launch film's cues- are `meta.captions`; `node tools/framecheck.mjs <name>` fails any cue held shorter and reports- `N/A` for a film that declares no cues (it cannot see words it was not told about).+- **Reading time.** Each text stays up at least `max(0.7 s, 0.3 s per word)`. `node tools/framecheck.mjs+ <name>` times every block of text the film DRAWS (glyphs joined into words and blocks, through+ layers and clips; typed text is timed from its last character) and fails any block held shorter.+ It is never N/A while text is drawn: a film that draws none says NONE with the evidence, and no+ frame checked is a FAIL. Text meant as texture is drawn inside `texture(ctx, draw)` and skipped.+ Build holds from the rule, not by feel: `readable.ts` `chatHold(text)` is think time (about 0.6 s)+ plus typing (about 52 characters a second) plus the full read AFTER the last character, times one+ `pace` scalar (`paced`, per section if needed). Worked example: an 11-word typed reply needs 3.3 s+ of reading after it finishes; a launch film held it 0.9 s, viewers said "too fast" twice, and even a+ 25% slowdown left it under the floor. "20% slower" is then one number, `pace: 1.2`.+- **Layout and the last second.** framecheck also fails more than 7 text blocks in a frame, 5 or more+ packed into under 30% of it, a centred stack of 5 or more, gaps under 3% of the short side, text+ over text or across a card's edge (held 0.5 s), any line under 28 px at 1080 in the last second,+ an end card that lands twice, and people in one sequence whose heads differ by more than 10%.+ A deliberate dense frame (a UI beat) is declared in `meta.checks.layoutExempt` with its reason.- **No text on a busy picture without a plate** (`craft-bar.md`).- **Phone safe zones, 9:16 only.** Reels, TikTok and Shorts lay their own name, caption, buttonsand progress bar over the frame. Keep text and key content out of the top 14 % and bottom 25 %@@ -116,6 +130,13 @@ frame `--fidelity-psnr` compares; default 0). All of it is opt-in beyond the conso transparent and non-uniform pieces pass cleanly. For a file that ships, add `--delivery`: anear-blank frame 0 then FAILS instead of warning; the fix is `render --poster-frame N`.+**Venue screens.** A film that will also loop on screens at an event: ask first what plays it (a+video player, a presentation app), make the loop seam clean (`gate` checks the last frame against+frame 0 for loops), and never depend on the sound, which venues often mute.++**Ship.** Before any version is shown to anyone, `node tools/ship.mjs <film> --file out/<file>.mp4`+runs every check on that exact file and writes a table and a critic sheet beside it (`workflows/review.md`).+A still needs a browser only (`npx playwright-core install chromium`). Anything that moves also needs`ffmpeg`. `gate.mjs` runs on all of them and marks the checks that do not apply to the piece,a silent loop's audio or a still's dead air, as `----` rather than passing them.diff --git a/plugins/anidoodle/skills/anidoodle/references/motion-grammar.md b/plugins/anidoodle/skills/anidoodle/references/motion-grammar.mdindex d252743..5a127a9 100644--- a/plugins/anidoodle/skills/anidoodle/references/motion-grammar.md+++ b/plugins/anidoodle/skills/anidoodle/references/motion-grammar.md@@ -1,5 +1,7 @@# Motion grammar: six ways to get from one picture to the next+**Contents:** 1. Foreground as transition · 2. Persistent actor · 3. Selection to expansion · 4. Registered decomposition · 5. Continuous canvas · 6. Exploded layers · Three ready-made seams · Cuts that carry motion · Dealing a hand · Names people use · Names we refuse · Callouts and the label handoff · Choosing+A film that shows one good thing, then another unrelated good thing, reads as a slideshow howeverwell each is animated. These six mechanisms are ways to make the next picture come OUT of thecurrent one. They are a grammar to compose from, never presets: pick the one the story is already@@ -144,6 +146,10 @@ roughest. The difference is arithmetic, and `engine/src/canvas-core/seams.ts` docamera look; the entry distance is worked out from the exit speed, so the two always agree.The incoming shot owns the cut frame: the outgoing shot's last frame on screen is the onebefore it, and that is its fastest.+ **This short, fast exit is for camera and world moves only.** Type and photos of people leave in+ 0.5 to 0.7 s, eased in (they accelerate away from rest), and are never motion-blurred: a launch+ film that whipped every speaker card out in 0.4 s with blur on type and faces was called violent,+ twice. A fast exit used as the seam for many cuts is a preset, however well each is timed.- **Through the cut, in depth.** `matchedZoom({ push, exitF, entryF })` does the same for acamera that flies into one shot and out in the next: a dolly push through the cut. A push is aratio, so both sides run in log space and grow at the same rate per frame across the cut. With the default push the@@ -152,7 +158,8 @@ roughest. The difference is arithmetic, and `engine/src/canvas-core/seams.ts` do- **There is a top speed.** Past about two and a half frame widths a second(`speedCeiling(W, fps)`), blur stops reading as motion and shows as a streak with steppedcopies. A move that needs more than that wants a shorter travel with the rest hidden behind- the cut, or a plain cut on the beat. Render fast seams with `--blur auto`.+ the cut, or a plain cut on the beat. Render fast seams with `--blur auto`, which leaves text+ and photo layers sharp.- **Match everything, once.** Whatever crosses the cut keeps its position, size, colour andedge; a property that flips on the cut frame pops. And the resting pose is shown once: if oneshot settles onto a pose and the next opens on it, the first shot's last frame is the move'sdiff --git a/plugins/anidoodle/skills/anidoodle/references/music/README.md b/plugins/anidoodle/skills/anidoodle/references/music/README.mdindex 13a56d5..ce0f049 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/README.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/README.md@@ -1,5 +1,7 @@# Music: composed as data, performed, measured, then heard once+**Contents:** The pipeline · Recorded instruments: the optional sound pack · Any length, never hard-coded · Styles (21) and moods (21) · Keys and modes (13) · How to write a score · The guards (guards.ts): sad is allowed, formless is not · The 8-second human listen+Every score in anidoodle is written as data and every voice is the engine's own: you write thenotes, the engine performs them. You cannot hear what you make, so every choice is a number, everynumber is measured, and a human hears 8 seconds before anything ships.@@ -19,6 +21,8 @@ notes. You compose every note, and nothing is filled in for you. There is no defPages:- [`compose.md`](compose.md): the workflow, the material format, craft, and the never-reuse rule.+- [`generated-tracks.md`](generated-tracks.md): when the person wants a music-model take or a licensed+ track instead: pinned and costed, cut by whole bars, unpitched effects, mastered and checked.- [`theory/`](theory/README.md): the craft behind it: melody, harmony, rhythm, mood mapping, form andorchestration, sound (psychoacoustics for voicing and mixing). Cited, and measured by`node tools/music.mjs craft`.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/compose.md b/plugins/anidoodle/skills/anidoodle/references/music/compose.mdindex 145a5b8..d6e6045 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/compose.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/compose.md@@ -1,5 +1,7 @@# Compose: from a brief to an original score+**Contents:** The workflow · Recorded instruments · The material format · What makes it beautiful (check before you call it done) · What checks what+A style is a **vocabulary**. It gives you:- sound: voices, levels and fx;- groove families;diff --git a/plugins/anidoodle/skills/anidoodle/references/music/generated-tracks.md b/plugins/anidoodle/skills/anidoodle/references/music/generated-tracks.mdnew file mode 100644index 0000000..5c01de3--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/music/generated-tracks.md@@ -0,0 +1,99 @@+# Generated or supplied music: someone else's track, cut to the film++**Contents:** When to take this path · The route · Prompting a music model · Cutting by bars · Effects under someone else's music · Mastering and the checks · What it cannot do++anidoodle composes its own scores (`compose.md`). Sometimes the person wants a track from a music+model (Lyria, through the Gemini API), or brings a licensed one. That is a first-class path with its+own tools: `engine/tools/track.mjs` (analyse, cut, mix, master, check) and `engine/tools/cues.mjs`+(the film's own event times). Every step below closes a failure from a brand launch film whose+music was made this way by hand: the music ended four seconds before the picture, twice, and the+effects were notes that clashed with the track.++## When to take this path++When the person asks for it, or when they have heard the composed score and want a register the+engine does not reach. Never as a shortcut around composing. The person chooses the provider and+pays for it; anidoodle never calls a paid API. Cost is stated before anything runs, and every take+is logged with its price in a `COST.md` beside the music.++## The route++1. **Agree** tempo, length, sections and style with the person.+2. **Prompt.** `track.mjs prompt --len 70 --bpm 120 --style "..." --sections "0-11 Intro: ...; 11-12 Hard stop: ..."`+ writes the request (a tempo-lock line, "Instrumental only", timestamped sections) and prints the+ price with its source and the date it was checked. It says the request was **not sent**.+3. **The person runs their provider.** For Lyria via the Gemini API: `POST+ https://generativelanguage.googleapis.com/v1beta/interactions` with+ `{"model": "lyria-3.5", "input": <prompt>, "response_format": {"type": "audio", "mime_type": "audio/wav"}}`+ and their key from their keychain ($0.08 per song on the paid tier, checked 2026-10-27; check+ again). Ask for 3 to 4 takes: the model ignores exact timestamps, so takes differ in where they land.+4. **Pin the take.** `track.mjs import <take.wav> --provider lyria-3.5 --cost 0.08 --prompt p.txt+ --licence "..."` writes `<take>.track.json` (sha256, provider, cost, prompt, licence). The film+ declares it as `meta.score = { external: "<take>.track.json" }`.+5. **Analyse.** `track.mjs analyze <take.wav>`: tempo (top candidates printed; pin `--bpm` when the+ ear disagrees, tempo octaves happen), first downbeat, bars with levels, sections, a key estimate+ (marked unclear when weak; takes often ignore the key asked for), the track's own stops, and the+ **real last note**.+6. **Fit the picture to the music.** `trackGrid(cut.downbeats, fps).holdTo(start, minHold)` gives the+ shortest hold that lands on a downbeat; land the logo lock, the card's arrival and other key hits+ on downbeats.+7. **Cut by whole bars.** `track.mjs cut <take.wav> --bars "0-3,4-18" --film <name> -o cut.wav`+ (below).+8. **Cues from the film itself.** Wrap the film with `withCues(film, [{ name, at: { scene: 22, through:+ [master] } }, ...])` and run `cues.mjs <film>`; the cue sheet comes from the film's own time maps, so+ a slowdown or a time-map change moves every cue with it. Never copy times into a second file:+ a hand-mirrored timing script drifted twice on the film this page comes from. `cues.mjs <film>+ --check` fails a sheet (or a mix) that is out of date.+9. **Listen first.** `track.mjs listen <dir> --mix mix.wav` makes a page with each effect alone, a+ 10 s sample of the mix and the takes. A human hears it before the full mix.+10. **Mix.** `track.mjs mix --music cut.wav --cues out/<film>.cues.json --sounds map.json -o mix.wav --stem sfx.wav`.+11. **Master and check.** `track.mjs master <picture.mp4> mix.wav -o film.mp4`, then `track.mjs check`+ and the ship command on the delivered file.++## Prompting a music model++- Say the tempo twice (in the tempo-lock line and in the style), the length, "Instrumental only",+ and the sections with times. A designed stop ("hard stop, one beat of silence") is worth asking for+ at the moment the picture holds its breath.+- Expect to fit the cut by bars afterwards: timestamps in the prompt are wishes.+- Keep the prompts and the takes; the person picks by ear ("take 2, love it").++## Cutting by bars++`track.mjs cut` joins whole bars with centred 12 ms crossfades, so the edit's length is exact and+every join sits on a downbeat. It refuses, and names the bars to add:++- a join more than a little off a downbeat;+- a segment that carries the silence after the last note;+- an outro that stops before the track's own ending (unless you ask for `--fade-out`);+- an edit whose last audible moment ends more than 0.5 s before the picture (`--end-tol`).++The edit's own downbeats are written beside it (`cut.wav.cut.json`) for `trackGrid`, and the track's+own stops become declared quiet ranges, so the dead-air and shape checks do not call them holes.+A segment list with no final newline is read whole (a shell loop once dropped the last segment).++## Effects under someone else's music++**Under a track the engine does not control, effects are transients, never notes.** A note that is+not in the track's key, or not on its chord, is a clash ("the sound effects cannot be melodic, they+make disharmonious interruptions"). Use the `tap` kind (`tick`, `tickHi`, `tock`, `thump`,+`impact`): short strikes too brief for the ear to name a pitch. Tuned kinds (chime, tuned riser,+`impact:bloom`, `press:confirm`) are refused under an external track unless the cue says why+(`pitched: "..."`). Every placed sound's pitch salience is measured in the mix, and `soundcheck.mjs+<file> --sfx sfx.wav` measures the rendered stem: a cue over 0.5 fails. The buried-cue guard runs+against the track too: a quiet cue is raised up to 8 dB against the track's local loudness, and fails+by name if it is still buried. `track.mjs kit --from-pack` cuts a transient kit from the sound pack,+each strike cut from its peak (cutting from the onset kept leading silence and lost the hit).++## Mastering and the checks++`track.mjs master` normalises to -14 LUFS, limits, encodes AAC 256k, then reads the true peak from the+**encoded** file and lowers the limiter until it is at or under -1 dBTP (AAC adds up to about 3 dB to+a peak). It then runs `check` on the muxed file: loudness, peak, the end of the music against the end+of the picture (filmshape), and the declared stops. The ship command runs `track.mjs check`,+`soundcheck --sfx` and `cues.mjs --check` for any film with an external track.++## What it cannot do++It cannot hear. Tempo, key and the last note are measurements; taste is the person's. A take's+own silent tail can still fail the end check by a fraction of a second: add the bars, or ask.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.mdindex d2955c0..c44bcd6 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md@@ -1,5 +1,7 @@# Sound design: the effects kit, placed by frame, heard over the score+**Contents:** What makes an effect sound designed, not generated · The kit · Placing effects in a film · Sound across a cut (J-cut and L-cut) · Levels and the audibility rule · Taste: when to use effects · The finished mix · Checking the finished film's sound · Tools and checks+Every anidoodle sound effect is **built in code, from nothing**: no samples, no recordings, ever.(The music's acoustic instruments can play recordings from the optional sound pack; effects neverdo.) Every effect is deterministic: the same cue and seed give identical samples.@@ -48,6 +50,11 @@ speaking window (K-weighted, see below). Duck is how far the score dips under it| brick | clack, snap, tumble | toy bricks: tap, press onto studs, drop on a pile | -15 | 1.5 || thread | pull, pierce, stitch | embroidery: thread through cloth (hit = the tug), the needle | -17.5 | 1.5 |+**Under someone else's music, effects are transients, never notes.** Use the unpitched `tap` kind+(tick, tickHi, tock, thump, impact); tuned kinds are refused unless the cue says why (`pitched`).+The impact's in-key shimmer applies only to scores the engine composes. The route for a generated or+supplied track: `generated-tracks.md`.+## Placing effects in a filmCues are addressed by **film frame**, a whole number (a fractional frame throws; to land a hitdiff --git a/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.md b/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.mdindex 3fde11d..2da504d 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.md@@ -1,5 +1,7 @@# Style: lo-fi electronic (chill, upbeat, clean)+**Contents:** The sound · Grooves · Harmony language (write your own progression) · Melody rules (write your own motif) · Arrangement grammar · Mixing: balance by stem RMS, then master+> A vocabulary, not a song. The data is `VOCAB.lofiElectronic` in `engine/src/canvas-core/music/vocab.ts`> (print it: `node tools/music.mjs vocab lofiElectronic`). You compose the notes with> [../compose.md](../compose.md). Our launch film was scored in this style (`launchLofi3`). Thatdiff --git a/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md b/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.mdindex f918db4..0d0c531 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md@@ -1,5 +1,7 @@# Style vocabularies+**Contents:** Groove families · Section kinds (the arrangement grammar) · lofiElectronic: lo-fi electronic · drive: driving electronic · cinematic: cinematic / orchestral · ambient: airy ambient · folk: tender acoustic · playful: playful / bouncy · musicBox: music box · nocturne: nocturne / solo piano · minimalist: minimalist / pulse · jazz: jazz / swing · lullaby: lullaby · chiptune: chiptune · lofi: dusty lo-fi hip-hop · orchestral: orchestral / epic · suspense: suspense / horror · rock: rock / band · hipHop: hip-hop / trap · house: house / EDM · synthwave: synthwave / retro · world: world / modal folk · choral: choral / sacred+> GENERATED by `node tools/music.mjs vocab --md` from `engine/src/canvas-core/music/vocab.ts` and `vocabMore.ts`. Do not edit by hand.> A style is a vocabulary: sound, grooves, harmony language, melody rules, arrangement grammar. It never> contains notes. You compose the notes ([../compose.md](../compose.md)).diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/form.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/form.mdindex 2726511..89f208b 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/theory/form.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/form.md@@ -1,5 +1,7 @@# Form, arrangement, orchestration, counterpoint+**Contents:** 1. Song forms (and the engine's section kinds) · 2. Film cue structure (scoring to picture) · 3. Builds and releases · 4. Orchestration: registers and frequency slots · 5. Counterpoint basics (a second line that helps)+## 1. Song forms (and the engine's section kinds)| Form | Shape | Engine kinds |diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.mdindex e687239..bc4d39f 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/harmony.md@@ -1,5 +1,7 @@# Harmony: function, voice leading, colour, tension+**Contents:** 1. Function: home, away, leaning, home · 2. Cadences: where a phrase breathes · 3. Voice leading · 4. Voicing and the low end · 5. Colour: modes, borrowed chords, extensions · 6. Secondary dominants, pedals, modulation · 7. Harmonic rhythm: pacing · 8. Tension curve+Roman numerals are relative to the key (`I ii iii IV V vi vii°` in major, `i ii° III iv v VI VII` inminor, `b` = borrowed or lowered). These are idioms, which are vocabulary. A multi-bar progressiontogether with its rhythm and groove is a piece, and novelty checks for that. `craft` measures this pagediff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/melody.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/melody.mdindex 55012e3..b964030 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/theory/melody.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/melody.md@@ -1,5 +1,7 @@# Melody: motif, contour, phrase+**Contents:** 1. Start from a motif, then develop it · 2. Phrase and period · 3. Contour and climax · 4. Steps, leaps and recovery · 5. Range and tessitura · 6. Rhythm and melody together · 7. Non-chord tones: where the feeling is · 8. Phrase endings · Checklist+Notation on this page: scale degrees (`1 2 3 ... 7`, `b3`, `#4`; `5,` = the octave below, `1'` = the octaveabove), durations in beats after a colon (`3:.5`). These are shapes to apply, never tunes to copy.`node tools/music.mjs craft <score>` measures every rule below (the **melody** line and `CRAFT melody:` findings).diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/rhythm.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/rhythm.mdindex d0bd286..63e8c00 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/theory/rhythm.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/rhythm.md@@ -1,5 +1,7 @@# Rhythm and groove+**Contents:** 1. Metric hierarchy · 2. Syncopation · 3. The backbeat and core patterns · 4. Swing and feel · 5. Polyrhythm and hemiola · 6. Fills and transitions · 7. Density arcs · 8. Rhythm in the melody · 9. Humanize or quantize+Positions are beats in the bar (`1`, `1&` = the eighth after it, `1e&a` = sixteenths). In 6/8 and 12/8 abeat is a dotted quarter. `craft` measures this page on the **rhythm** line.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/theory/sound.md b/plugins/anidoodle/skills/anidoodle/references/music/theory/sound.mdindex 635af1d..c2cf4cd 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/theory/sound.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/theory/sound.md@@ -1,5 +1,7 @@# Sound theory: psychoacoustics for composing and mixing+**Contents:** 1. Critical bands and roughness · 2. Masking: why the tune gets buried · 3. Equal loudness (Fletcher-Munson / ISO 226) · 4. Tonal balance by genre (long-term spectrum) · 5. Stereo and depth · 6. Reverb and delay timing · 7. Loudness and dynamics+You write notes, and the engine mixes. Most "muddy", "thin" or "buried" results are decided by thenotes: register, spacing, density and which parts overlap. This page is the physics behind thosechoices. The engine's guards and `craft` check the parts you can control from the score. The mixdiff --git a/plugins/anidoodle/skills/anidoodle/references/storytelling.md b/plugins/anidoodle/skills/anidoodle/references/storytelling.mdindex 19f6775..43e1cf5 100644--- a/plugins/anidoodle/skills/anidoodle/references/storytelling.md+++ b/plugins/anidoodle/skills/anidoodle/references/storytelling.md@@ -30,3 +30,66 @@**Tests before you build.** Say it in three sentences. Name the frame of the turn. Name the token and the two frames where it appears. For every shot ask "what changed for the character"; a shot where the answer is "the rendering style" is a shot to cut. And: every element in frame gets a one-line reason. In our meadow each flower colour, the footpath and the sun all had one. The oval bokeh blobs had none, and they were the first thing the eye caught as fake.**No dead air.** The first riso and watercolour acts were static for half their length and opened on three seconds of empty stock. The rule since: something visibly moves in every second, from frame 0, and a "hold" means the camera creeps while the subject keeps living. Check it with a tool (per-frame changed-pixel fraction, no identical consecutive frames, no 15-frame window under half a percent) and ALSO by eye: a creeping camera changes every pixel and satisfies the tool while the eye sees a still. We shipped a second of exactly that before I caught it on the contact sheet.++## Launch, brand and event films: a story, not a list++> Earned on a brand launch film that went through twelve versions. Its first board was nine facts,+> one per frame, and the note was "the whole thing literally looks like a deck". `tools/board.mjs`+> checks every rule below on the board, before anything is drawn.++- **A row is an action, never a fact.** Each storyboard row says what MOVES and what it becomes, and+ what it **carries** in from the row before (an object, a shape, the camera). Two rows in a row that+ carry nothing are two slide cuts. "You talk to AI all day" on its own frame is a slide; the AI's+ typing dots falling out of the chat into a crowd is a film.+- **A message, not just information.** Write the line the viewer should leave repeating ("AI is+ changing marketing. Nobody has a prompt for that.") beside the story sentence. A film that only+ informs plays as a promo deck.+- **The brand arrives as the answer.** After the problem line, the brand is shown as an action (the+ crowd wiring itself into a network) and the mark is **built from the thing that just acted** (the+ network's thread becomes the logo's neck). Test: "why does the logo appear now?" answered in one+ sentence from what is on screen. A thesis line followed by a logo, with no bridge, is a cut to an ad.+- **One actor carries the film.** Name it in the brief (the AI's three typing dots: its face, its+ fall, the crowd, the logo's dots, the last reply). It crosses every seam it can.+- **Counts change for a reason.** Three dots becoming two "for no reason" reads as noise. Keep the+ count, or show why it changes (one dot hops up and joins the network).+- **A count on screen is a claim.** Six "?" dots promise six more speakers. Use one symbol for "more+ to come", or source the number (`facts.md`).+- **The promise is what the viewer does and leaves with.** "Multiply your marketing intelligence"+ meant nothing to anyone; "Half a day with marketers who already figured it out. Leave with real+ systems that get real results." did. A brand tagline goes in only if it passes that test.+- **Say each thing once.** "About 400 of them" in the hook and "400+" on a numbers card is one fact+ told twice; cut one (`facts.mjs` fails a repeated number without a `reuse` reason).+- **One landing.** The last thing on screen is the end card OR the stinger, never card, stinger,+ card again. "Started with a conversation, end with a conversation." A stinger answers something+ visible in the three seconds before it.+- **Text that is not meant to be read must look unreadable.** Fast filler replies in real words make+ the eye try to read them; use "blah blah", greeked lines, or one real line then blah.+- **Events list their people.** Hosts and organisers, speakers (all of them, name, role and logo,+ no talk titles), sponsors and partners are brief fields, each present or excluded by the person.+ The hosts' own beat ("who's running this thing?") was the one viewers loved most.++## Comedy++> Same film. Its comedy scored 8 and 9 with critics, then most new jokes were "not funny, try harder",+> because every joke had one shape: the AI chimes in with a quip.++- **Pain first, then gags.** List the audience's lived pain points (the em-dash habit, "Great+ question!", "Compacting conversation...", "You've reached your limit, try again in 4 hours"), then+ write one gag per pain. Specific nouns beat generic AI jokes.+- **Punch at the situation or the habit, never at the tool the audience relies on, and never at a+ real person.** "Make it funnier without making AI look stupid": the AI became a witty wingman.+- **Pitch across devices.** A batch of pitches spans at least four: verbal, visual pun (an "I'm not a+ robot" box ticked beside "100% in person"), interaction (the user types "make no mistakes"),+ physical comedy, structural (self-editing copy, an empty chair). Each pitch names its device and+ where it lands. An observation (true, with no twist) is not a joke. Constraints you set yourself+ ("jokes only when the AI talks") are said out loud so the person can lift them.+- **Who gets it, in one line.** Every gag carries a note of who laughs and why. A gag that needs+ explaining to the client ("cameras can't be off"?) is cut or rewritten ("Nobody's on mute.").+- **A character keeps its visual voice.** A line spoken by the AI always looks like the AI's bubble+ (dots, then its type), even when it is the person's favourite joke dropped in late.+- **Self-aware hosts land.** "Three humans. I just take notes." The people behind the thing, laughing+ at their own role, beat any clever line about the product.++`board.mjs` holds the checkable half: each joke has a device, a "who gets it", and a butt that is a+situation or a habit; no device carries more than 60% of the jokes; pitches span four devices and+each has a twist; every speaking character has a registered visual voice.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/brand-film.md b/plugins/anidoodle/skills/anidoodle/references/workflows/brand-film.mdnew file mode 100644index 0000000..fdfc14e--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/brand-film.md@@ -0,0 +1,167 @@+# Brand films: someone else's brand, exactly++**Contents:** Why this page exists · Step 0: one reference film · Step 1: the inventory · Step 2: getting the files out (four routes) · Step 3: import and sign-off · Step 4: logos · Step 5: fonts and motion tokens · Step 6: people and their photos · Step 7: the brief and the board · Step 8: the hardest shot first · What a brand element may do · Data from the live site · Design critique before the first render++A brand film is a launch, event or campaign film made in a brand that already exists: a logo, a+shape language, colours, fonts, maybe motion. Everything in `launch-video.md` applies. This page adds+what a brand changes, and every rule on it was paid for on a brand launch film that took twelve+versions: wrong elements drawn from screenshots, a logo morphed through goo, the wrong company logo+three times, sponsors "not in the design file" when two frames held them, and a font never supplied.++## Why this page exists++To the brand's owner, a mark redrawn by eye is a different mark, even when it is close. So brand+elements are **imported, never drawn**, and the film only ever **moves** them. Nothing on this page+is a style choice; each step closes a door a past film walked through.++## Step 0: one reference film++Before the brief, pick ONE reference film with the person (a launch film they admire, a keynote+title sequence). Deconstruct it into notes beside the project: frames every 0.5 s, shot lengths,+seam types, camera moves, how type enters and leaves, how long text holds. Take its **grammar,+never its content**. A film started with no reference drifts toward slides, and "this is the level+of mastery I expect" arrives as a note in round five instead of a target in round one. The board+records it as `brief.reference` (`board.mjs` fails a brand film without one, or without a reasoned+"none: ...").++## Step 1: the inventory++On first access to the brand source, list **every** frame in it, not only the ones you plan to use:++```bash+node <skill>/engine/tools/brand.mjs inventory --figma <fileKey> # Figma REST (FIGMA_TOKEN)+node <skill>/engine/tools/brand.mjs inventory --figma-json file.json # a saved REST response+node <skill>/engine/tools/brand.mjs inventory --dir brand-pack/ # a folder of exports+```++It writes `brand/INVENTORY.md` (page, frame, id, size, the words on it, a read box per frame),+`inventory.json`, and the file's own transition timings as `motion.json`. Then:++- **"Is X in the file?"** is answered with `brand.mjs find X`, which searches every frame name and+ every word on every frame. "Not there" is only ever said with the count of frames searched.+- **Read every frame.** Mark each `[x]`, or `[-] <why it does not matter>`. `brand.mjs check` fails+ while any frame is unmarked or skipped with no reason. Partner, sponsor and speaker frames hide+ under names like "Social Media partners".++## Step 2: getting the files out (four routes)++Try them in this order; never modify the source file.++1. **Figma REST API, read only.** The person makes a personal access token (file read scope) and+ exports it as `FIGMA_TOKEN`. `brand.mjs import --figma <fileKey> --nodes <id,id>` renders each node+ as SVG with text outlined and imports it. The node ids come from the inventory.+2. **Figma's own MCP server**, if the person has it connected: export each node as SVG with text+ outlined, then import the files.+3. **The plugin API in a browser tab**, when the file is open in a browser the agent can drive:+ `node.exportAsync({ format: "SVG_STRING", svgOutlineText: true })`. Browser tools often truncate+ results near 1,000 characters, so stage the string on `window` and read it back in slices.+ Slow and fragile; use it only when 1 and 2 are closed.+4. **Ask for an export**: one zip of SVGs (text outlined), one file per element, named for what it+ is. Asking costs one message; guessing costs a round.++A brand pack, a site's own SVGs, or an Illustrator export are imported the same way.++## Step 3: import and sign-off++```bash+node <skill>/engine/tools/brand.mjs import brand/src/ --ts src/canvas-core/myBrand.ts --sheet --on '#111'+```++- Each SVG becomes one element: its exact path data, fills, gradients (linear and radial, in either+ unit system), transforms, `<use>` and `<symbol>`, CSS classes, clip-paths and hard white masks,+ each part with its box. Path data is never rewritten; transforms ride beside it as a matrix.+- It writes `brand/brand.json` and a TS module exporting `BRAND` (elements, palette, fonts, motion)+ and `brandMeta` (colours and element names). Put `brandMeta` in the film's `meta.brand` so the+ gate knows which colours are the brand's, and spread `brandMotion` into `meta.motion` so layerscan+ fails a brand colour drawn half-transparent.+- It prints what each mark can do in motion: **rotational symmetry** (a mark that is the same after+ a half turn can land from a spin without a jump) and **repeat periods** (a frieze whose shapes+ repeat every N units tiles without a seam when stepped by N). Plan moves around those numbers.+- It names what it cannot draw (a soft mask, a filter, a pattern fill, an embedded image, live text)+ instead of dropping it silently.+- `--sheet` draws every element twice, from its source SVG in the browser and from the import, and+ **fails past 1% different ink**. Show `brand/sheet.png` to the person and get the sign-off before+ the first storyboard. Every later frame is built from what they signed.++## Step 4: logos++Partner, sponsor and company logos are the same problem in miniature.++- **Copy where it is rendered in production first.** Screenshot the logo where the company uses it+ (its site header, its product), then rebuild from its SVG. `brand.mjs logo film-logo.svg --ref+ shot.png` puts the two side by side at one height; the person sees that still before the logo+ goes in. A company with a mark and a wordmark has an order, a colour per part and a spacing; none+ of it is guessed.+- **One strip, equal weight.** `brand.mjs logos sponsors/ --on dark` trims transparent margins+ (a PNG with a wide margin renders tiny), writes a one-colour version for the ground, measures each+ logo's ink and prints the height at which every logo reads equally heavy, with a strip still.+ A PNG on a solid background is refused: ask for a transparent export or the SVG.+- **Never fix a client's mark.** Overlapping outlines (letters that share a stroke) are flagged+ "check with the owner". It is usually their real design; ask, do not repair.++## Step 5: fonts and motion tokens++- **Fonts.** The import lists any live text's font. Ask ONCE, early, for the font files (OTF, TTF+ or WOFF2) or for exports with text outlined. If the font never arrives, the brief records the+ stand-in face, and the review page flags every line set in it. A stand-in that mixes with the+ brand face in one frame reads as a mistake.+- **Motion tokens.** If the source has prototype transitions (Figma interactions), the inventory+ saves their durations and easings (`motion.json`, merged into `BRAND.motion` as named tokens).+ `motionTokens(BRAND.motion, fps)` in `motionKit.ts` turns them into eases and frame counts. A+ brand's own turn (say a half-turn over 2 s on `cubic-bezier(0.5, 0, 0.5, 1)`) is the film's first+ easing choice. Spring easings have no bezier form and are set aside for the person, never guessed.+- **Temperament.** Set it before motion: how fast things may move (a share of `speedCeiling`),+ how long they settle, whether anything overshoots (`temperament()` in `motionKit.ts`). A brand that moves "like poured liquid" never+ springs; a playful one may. A film corrected first for "violent" and then for "flat" never had one.++## Step 6: people and their photos++- **Program data comes from the live site**, cited as a site source with its date (`facts.md`):+ name, role, company logo, slot. Every speaker is listed (no mystery speakers); talk titles are off+ by default because nobody reads them in a film (`board.mjs` program rules).+- **Hosts, organisers, sponsors and partners are brief fields** for an event: present, or excluded+ by the person with a reason. The people running the event are often the beat viewers like most.+- **Photo restoration and cut-outs.** When the person asks, a supplied photo may be restored or cut+ out by an image model they choose (through their own subscription tool). Show the original and the+ result side by side on the film's background before use; the original file stays untouched; record+ the model and date in the asset manifest. A model may change clothes or lighting: compare, then ask.+- **Faces are sized by head, not by photo.** Normalise people in one sequence by head height with+ crowns level; a photo cropped looser makes its person look smaller.+- **A real face is never covered, cut or swallowed by a moving shape.** The person enters and+ leaves with their stage.++## Step 7: the brief and the board++`board.mjs init` writes a board with every field; `board.mjs board.json` checks it before anything is+drawn (`storytelling.md` has the why for each rule). For a brand film it requires: the story sentence+and the message; the comic premise or "none: why"; a promise that says what the viewer DOES and+LEAVES WITH (a brand tagline is used only if it passes that test); the actor that carries the seams;+the people fields; the reference film; and for every row, what it carries in from the row before.+The brand's reveal row says why the logo appears now and what it is built from.++## Step 8: the hardest shot first++No second scene until the hardest shot (usually the logo reveal) is rendered, critiqued and approved.+Once approved, **lock it** (`lock.mjs <film> --shot <id>`, the sha into `meta.motion.approved`,+`motion-film.md`): an approved shot is restored exactly, never "improved" in passing.++## What a brand element may do++Translate, rotate, scale evenly, clip, mask, layer, tile by its measured period, and appear part by+part (`riseIn`). It may not be squashed, skewed, blurred, morphed or blended into another mark, and a+brand colour is never shown half-transparent (yellow at 50% over black reads olive). In code:+`brandKit.ts` `drawEl` throws on a non-uniform scale or a skew; a squash that IS the joke passes+`{ allowSquash: "<the gag it serves>" }`. `placeEl` positions by centre and height and is uniform by+construction. Draw helpers multiply the caller's alpha and keep its transform, and every drawn mark+reports its on-screen box to the frame probe, so the scans see brand shapes crossing a face.++## Data from the live site++Fetch site data with the web reader the session has, not with ad-hoc downloads (security hooks block+those, rightly). Save what you used with its URL and date as the facts source.++## Design critique before the first render++Before the first full render, run a design critique on the storyboard stills with whatever design+skills the person has installed (name them in the brief), and re-read the person's last notes against+the new sheet. Judge hierarchy, flow and brand temperament first; collisions second.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/facts.md b/plugins/anidoodle/skills/anidoodle/references/workflows/facts.mdindex 94c58cc..9b849e6 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/facts.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/facts.md@@ -15,6 +15,13 @@ research ledger (`explainer.md`) made general, and the launch film's list of appdata: `generated: true` with a note saying what it is. A generated entry states no number; anumber needs a source.- **A claim you cannot source is cut**, or shown plainly as a metaphor.+- **A count drawn on screen is a number.** Six "?" dots claim six more speakers; three seats claim+ three places left. List it with digits ("6 more speakers") so it needs a source, or draw one symbol.+- **Say each fact once.** The same line twice, or the same number on two cards ("about 400" and+ "400+"), fails; the later entry may carry `reuse: "<why the repeat earns its place>"` (a date on+ the hook and the end card, say). Single digits are counting words and never flagged.+- **A live site is a source with a date.** `"source": { "kind": "site", "url": "...", "fetched":+ "2026-10-27", "sentence": "..." }`: sites change, and the date says what was true when you read it.## The file@@ -42,7 +49,10 @@ and any `claims: [...]` in its spec; any other film sets `film.claims`. It fails- a sourced entry lacks the sentence, or a URL (http/https) or file;- a generated entry has no note, or states a number;- a number in a sourced claim is not in its source sentence;-- a claim is still a TODO.+- a claim is still a TODO;+- a line is declared twice, or two entries state the same number (10 or more, or with %, + or x),+ and the later one has no `reuse` reason;+- a `site` source has no URL or no `fetched` date.A film that declares no claims reports `N/A`, never a pass. The check is light on purpose: itcannot know a sentence is true. The critic does that by reading each source beside the filmdiff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/interactive.md b/plugins/anidoodle/skills/anidoodle/references/workflows/interactive.mdindex 10f74dd..c32083a 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/interactive.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/interactive.md@@ -1,5 +1,7 @@# Interactive web animation+**Contents:** The contract: a frame is a fact, given its input log · Making one · What the replay gate proves · Measured (headless Chromium 1140, this Mac, 1280x800 at DPR 2, September 2026) · Limits+Hand-drawn pieces that live on a web page and answer the person using it. They follow the pointer,react to hovered and focused buttons, draw themselves as you scroll, and read along with a form.None of this is a video or an embedded player: the piece is part of the page's UI.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video-kit.md b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video-kit.mdindex 8cd32c5..2303a26 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video-kit.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video-kit.md@@ -1,5 +1,7 @@# The launch kit: build your product's launch film+**Contents:** Start from the template (16 s, one file) · The parts, for a film of your own shape · Worked example+The pieces anidoodle's own launch film is made of, in `engine/src/canvas-core/`, usable for anyproduct. The rules they serve are in `launch-video.md`.@@ -8,7 +10,9 @@ product. The rules they serve are in `launch-video.md`.`launchTemplate.ts` turns data into a film: one to three asks, a type frame between them, and anend card with your install lines. `launchExample.ts` is a complete one for a made-up product (thedrawn look, chat asks); `launchExampleClean.ts` is the second look on a UI-first product (the-product's own UI in three screens, two of them split beats, 60 fps). Copy their shape, not their contents:+product's own UI in three screens, two of them split beats, 60 fps), and `launchExampleCleanChat.ts`+is the clean look with a chat ask (the hook, an answer card opening as an iris, a word page, then the+product's screen). Copy their shape, not their contents:the plates, the UI data and the score are the product's own, made for its brief.```bash@@ -77,11 +81,20 @@ What you get, from data:- **Chat asks** (`kind` omitted): the hook: the first prompt is the hero, already being typed atframe 0 in a big composer across most of the frame (at least 64 px type on 1x1/4x5/9x16, 56 px on16x9, wrapping to 2-3 lines, never clipped; a prompt too long for that is an error), which shrinks- and docks at the bottom of the chat as Generate is pressed. Later prompts are typed with the whole+ and docks at the bottom of the chat as Generate is pressed (over a second, or longer when the+ distance would take its fastest point past what the brand's motion temperament allows: a calm+ brand's hook on a phone frame docks over nearly two). Later prompts are typed with the wholecomposer in frame, the camera easing out for the press, an ink drop arcing from Generateinto the thread and blooming open into a card where the plate draws itself live (the card openson a spring), the thread keeping earlier answers and scrolling, a gentle lean onto each new card that keeps it whole with a margin (what the camera is about- to cut fades first).+ to cut fades first). The drawn dock keeps the hook's line breaks until it lands (no word jumps a+ line on the move) and re-wraps once, at rest. In the clean look the hook's composer glides down+ whole and IS the dock: it never shrinks, on the move or after it lands, and rests a moment before+ Ask is pressed (on 9x16 it is laid out a little narrower, to dock clear of the phone's right-hand+ zone). The drop flies as one solid streak of the accent, over as many frames as its distance needs+ to stay inside the brand's temperament, the answer card opens as an iris, and the window+ stays whole and opaque while the camera leans in (still moving as a travel takes over), so no+ brand colour is ever see-through.- **UI asks** (`kind: "ui"`): the product's interface drawn from data (`productUI.ts`) in its`before` state; the ask typed into its command bar if it has a `prompt`; the pointer presses its`action`; every item springs to its place in the `after` state (matched by `id`: rows move,@@ -89,9 +102,13 @@ What you get, from data:- **Film asks** (`kind: "film"`): any film of this engine (a `webTour`, a loop, a plate) in a card.- **Split feature beats**: a UI or film ask with `split: [lines]` puts its words in their owncolumn beside the live UI (above it on a phone), never over it: faster than a full word page.+ The words are sized to their column's width and height (set smaller and rewrapped when they would+ run down over the product); their read, once set and the product has landed, is a declared hold+ (after a travel in, from the moment they are set, through the press, until they sink).- **Seams**: chat to chat is one thread; a seam between kinds with no word page opens as a bloom.- **The motif**: an ink drop lifts off Generate (or the product's action, or the film's card) andlands as the dot of the end card's mark ("NAME."); the end card blooms open FROM it and stays.+ The last split beat's words finish sinking halfway through its flight, gone before it lands.- **Sound from the picture** (`launchSound.ts`): a key per character typed (the space bar itsown), the press on the frame Generate goes down, the drop and its bloom, each card landing on itsspring's first arrival, each UI item's landing; every cue panned to where it happens on screen;@@ -133,13 +150,38 @@ Every line a viewer must read is phone-safe on 1x1, 4x5 and 9x16: at least 32 px(about 11 pt on a phone) for prompts, bubbles, card labels, tagline and install lines, 64 px for aword page; the layout throws with the fix when one cannot be (an install line too long for 9x16).-### Two looks--`preset: "drawn"` (default): ink blooms, hand-lettered words (`writeOn`), a warm paper palette.-`preset: "clean"`: a quiet canvas, ONE accent colour (the button, the drop, the dot, the caret;-`accent` sets it), type as the design: word pages SET in a heavy sans (`setType`: each word rises-into place behind its own baseline), round iris seams instead of ink, the answer card opening as-an iris. Both are ours: the clean look is a register, not a copy of anyone's film.+### Looks: the film wears the product's own look++A look is a base grammar plus the product's own tokens. `look.base` picks the grammar; every other+field dresses it, and any field left out keeps the base's value. `preset: "clean"` is shorthand for+`look: { base: "clean" }` (a preset and a base that disagree are an error). With no look the film+draws exactly what it drew before (launch, launch2 and launch3 render byte-identical).++The two bases:+- `drawn` (default): ink blooms, hand-lettered words (`writeOn`), a warm paper palette.+- `clean`: a quiet canvas, ONE accent (the button, the drop, the dot, the caret), type as the design:+ word pages SET in the display face (`setType`), round iris seams, the answer card opening as an+ iris. It takes every kind of ask: chat asks (the hook's composer glides down whole and IS the dock;+ give the answer plate a ground other than the card's, or the iris opens unseen), product screens and+ films. `registerLook(name, { clean, palette })` adds a base of your own.++| Field | What it sets | Notes |+|---|---|---|+| `look.base` | the grammar: `"drawn"`, `"clean"`, or a registered look | `preset` is its shorthand |+| `look.palette` | any of `bg card ink soft mute line chip accent accentDeep paper` | merged over the base; checked for contrast (below) |+| `look.fonts` | `{ display, text, mono }`, each `{ family, file }` | `file` is a local `.ttf` imported into the film (`import f from "../../assets/fonts/X.ttf"`); registered before the first frame, no network; every measure, wrap and reading-time path uses its own glyph advances. A missing file or an `.otf`/`.woff2` is a clear error (convert to `.ttf`) |+| `look.shape` | `radius`, `bubble` (`rounded` `square` `none`), `composer` (`box` `bar`), `button` (`pill` `square`), `buttonLabel` | the radius caps every corner, the chat's and the product UI's alike |+| `look.chat` | `header` on/off, `title`, `subtitle`, `logo` (a brand element, drawn with brandKit `drawEl`), `bubble` and `reply` `{ fill, ink }` | a logo also opens the clean end card, before the name, on its baseline |+| `look.from` | a brand file from `node tools/brand.mjs import` | fills the palette (its saturated colour the accent; a dark-first file the ground and ink) and the logo; explicit fields win |++The product's own screen is a `kind: "ui"` ask (`productUI.ts`): it takes the look's face, label colour+and shape too. READABILITY: a custom palette is checked pair by pair (WCAG AA: 4.5:1 for body text,+3:1 for large type and the button's label), only on pairs that touch a token you changed, and the build+fails naming the token and both colours. On a dark ground the pointer turns light. `launchExampleBrand.ts`+is the worked example: an invented brand, dark ground, a serif display face, square shapes, its own logo,+a chat ask and a product ask; `node tools/launch.mjs new` scaffolds a commented `look` block.+With two or more install lines, use `endCard: "grid"`: the stacked card is then five blocks centred+on one axis, which framecheck fails as a centred stack.### Frame rate and motion blur@@ -157,7 +199,7 @@ many subframes as each frame's measured on-screen speed needs (1 on a still fram| `claims` | extra on-screen or narrated claims for `facts.json`; the words, split words and tagline are claims already || `claimBar` | land the end card on this bar's downbeat, counting from bar 0 (`claimBar: 4` = frame 4 x bar); throws if it cannot. A longer last ask is really longer, never slowed || `score` (required) or `audio` | the score composed for this product (the `Material` function compose.md writes, or a `Piece`), as a bed; `null` for silence; or your own finished mix (not checked; it replaces the cues too) |-| `shape`, `preset`, `sfx`, `motif`, `captions` | the frame (16x9 default); the look (drawn, clean); sound cues (default on); the relay into the end card (default on); `"sidecar"` (default) or `"burn"` |+| `shape`, `preset`, `sfx`, `motif`, `captions` | the frame (16x9 default); the look (drawn, clean); sound cues (default on; `launch.mjs new` writes `sfx: false` beside `score: null`, since cues alone are clicks on silence that soundcheck fails: turn them on with the score); the relay into the end card (default on); `"sidecar"` (default) or `"burn"` |The template refuses a feature list (more than 3 asks) and an end card too short to read.@@ -180,7 +222,9 @@ The template refuses a feature list (more than 3 asks) and an end card too short- `writeOn(ctx, env, text, x, y, size, p, style, opts)`: a line written stroke by stroke by avisible tool, in `ink`, `crayon`, `thread`, `chalk`, `brick` or `marker`. `measure` sizes it.- `setType(ctx, env, text, x, y, size, p, opts)`: a line SET in a heavy sans, each word rising- into place behind its baseline: the clean look's type. `setWidth` measures it.+ into place behind its baseline: the clean look's type. `setWidth` measures it. `{ out }` sinks it out+ last word first on an ease-in over 1.3x its size (no slivers at the clip edge); `{ space: "world" }`+ draws it inside a camera or a region (`motion-film.md`).- `sentence` (one medium per word, one word per beat), `caption` (a small callout with anunderline or arrow), `logo`/`logoCentred` and `logoBug` (anidoodle's own wordmark and cornermark; for your product, write your name with `writeOn` as the template does).@@ -230,3 +274,4 @@ scaffold leaves them out; `scaffold.mjs <dir> --example` brings them in (with thare built on) to study. Study them for pacing, then build yours onthe template with your own pictures and your own music; anidoodle's launch is one example of thegrammar, not a skin to reuse.+`launch.ts`, `launch2.ts` and `launch3.ts` are frozen reference builds of that published film, made before the 0.10 checks (their declarations say so, `FROZEN` in `launchKit.ts`): never templates; start from `launch.mjs new`, whose examples pass `ship.mjs`.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.mdindex 4e9847a..ebcbd97 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md@@ -1,5 +1,7 @@# Launch and product videos+**Contents:** Inputs the person brings · Ground it in the real product first · Made for this product, every frame and every note · The story · Type · Motion · The motif · Two registers · Brand and the end card · Sound · Delivery · The process+A launch video makes one promise about a product and shows it being kept. It is a short filmwith a job: in the first seconds the viewer knows what the thing is, by the end they know whereto get it. Every rule below was paid for on anidoodle's own 77 s launch film (four cuts) and@@ -10,7 +12,11 @@ a template film renders a 16 s launch for any product from data.Product screenshots, a logo, UI captures, a repo link, a feature list, the exact install orsign-up line. Images they bring may be embedded (pinned by sha256, provenance in the manifest);-everything around them is drawn in code. Never generate or fetch images.+everything around them is drawn in code. Never generate or fetch images on your own. One exception+the person opts into: a photo they supplied may be restored or cut out by an image model they choose,+shown beside the original on the film's background before use, with the original kept and the+model recorded in the manifest (`brand-film.md`, people). A film in someone else's brand starts with+`brand-film.md`: the brand's exact elements, logos and motion are imported and signed off first.## Ground it in the real product first@@ -48,6 +54,10 @@ pieces are examples of the craft, never material for someone else's film.- **Arc**: hook, one core interaction, a fast proof of range (a wall, never a slow tour), thebrand moment, the call. A visual payoff every 3-5 s; no dead waits.- **No footnotes, no eyebrow text, no terminal jargon on screen** unless the product is one.+- **A board row is an action, never a fact**, and names what it carries in from the row before; the+ brand arrives as the answer, built from the thing that just acted; one message line beside the+ story sentence; a promise that says what the viewer does and leaves with; one landing at the end.+ The why is `../storytelling.md` ("Launch, brand and event films", "Comedy"); `board.mjs` checks it.## Type@@ -67,11 +77,16 @@ pieces are examples of the craft, never material for someone else's film.- **3-7 words a frame, few frames.** Collapse word cards into one claim then proof ("JUST CODE."then "32 STYLES"); fewer cards leave more time for the proof.- **Hold each settled word 0.5 s or more**, longer for the claim.+- **Text meant as texture looks unreadable** ("blah blah", greeked lines). Real sentences that are+ up too briefly make viewers try, and fail, to read them.- **Judge DESIGN in review stills, not only collisions**: hierarchy, spacing, whether the framewould pass as a poster. A frame with nothing overlapping can still be ugly.## Motion+- **One world, one camera, by default.** Start with `worldfilm.mjs` and build on `world.ts`: every beat+ a region of one canvas, every seam a camera move. Built scene by scene, a film plays as slides however+ well each scene moves. `motionscan` and `layerscan` hold it (`motion-film.md`).- **A gentle move is the default transition**: bloom, card flip, push, the card GROWS into theframe. 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@@ -113,8 +128,19 @@ into place), round iris seams, the product's own UI. Pick one per film; never mi## Brand and the end card- **The logo recurs**: a small corner mark on every frame (`logoBug`), not once at the start.+- **One landing.** The last thing on screen is the card or the stinger, never card, stinger, card.+- **Event programs** show every speaker as name, role and company logo (from the live site, dated),+ no talk titles and no mystery speakers; the panel's title once. Hosts and sponsors are in the brief.+- **Logos of other companies** are copied from where they are rendered in production, sized to equal+ visual weight, never "fixed" (`brand-film.md`, logos).- **The end card is composed for the frame**: the name, one line, the exact install lines in a- panel, held **3 s or more** so a viewer can screenshot them. anidoodle's are both lines:+ panel, held **3 s or more** so a viewer can screenshot them. For an event or campaign, build it on+ `endCard.ts` (`endCardLayout`, `drawEndCard`): one card, one frame, an asymmetric grid with the+ lockup top-left, the event lines under it, the call as a stamp on the right on the venue's baseline,+ a hairline, then a sponsor band (label 38 px, weight 800 at 1080; each sponsor switchable), in every+ shape. Never a centred stack of five or more items, never extra slides for what did not fit.+- **People** (speakers, hosts) are placed by head height with crowns level (`people.ts` `drawPerson`);+ `popOut` puts a person on a disc with the head free above it. anidoodle's are both lines:`/plugin marketplace add alexgreensh/anidoodle` and`/plugin install anidoodle@alexgreensh-anidoodle`. One primary call; the link smaller below.@@ -124,7 +150,11 @@ into place), round iris seams, the product's own UI. Pick one per film; never miCompose it for THIS brand: pick the style and a mood per section from the brief (energy,audience, where it runs), then write the notes (`references/music/compose.md`). anidoodle's ownlaunch chose chill lo-fi electronic, one example (`references/music/styles/lofi-electronic.md`);- never reuse our score or a stock piece.+ never reuse our score or a stock piece. When the person asks for a generated or licensed track,+ it takes its own route (`references/music/generated-tracks.md`): pinned and costed, cut by whole+ bars, effects unpitched, the music never ending before the picture.+- **Effects and a 10 s mix sample are heard first**, on a listening page (`track.mjs listen`), before+ the full mix. You cannot hear; the person can.- **Balance by stem RMS, not only LUFS**: an integrated -14 LUFS hid a sub 7-10 dB too hot.- **Cut on downbeats, not every beat.** Land the claim on a chord (launch3's lands on bar 26,the home chord); `beatGrid().solve()` fits a flexible segment so it does.@@ -139,8 +169,13 @@ into place), round iris seams, the product's own UI. Pick one per film; never mi## Delivery- **Length**: about 60 s for a launch post (LinkedIn, YouTube, the README); 15-45 s for X; cut- a platform version rather than pushing one master everywhere. Cut whole beats; never speed- the whole film up (it breaks the beat grid and reads rushed).+ a platform version rather than pushing one master everywhere. Set `length.target` and+ `length.max` in the brief before the board (`board.mjs` fails a board over the max), and the same+ numbers in the film's `meta.checks.length` (ship fails a cut over the max and prints the reading+ floor: how short the film can get without cutting into reading time). Cut whole+ beats, and only from non-reading holds; never speed the film up to hit a length (it reads rushed).+ Slowing everything for reading through one master pace map is fine, if the key hits are re-solved+ onto their downbeats afterwards.- **Shapes**: `16x9` for YouTube and the site, `1x1` or `4x5` for feeds, `9x16` for Reels andShorts. Re-compose per shape from one timeline; never crop a wide render. The template does itthrough `launchLayout.ts` (`launch.mjs ship <film> --shapes 16x9,1x1,9x16`), with phone-safe type:@@ -162,8 +197,10 @@ into place), round iris seams, the product's own UI. Pick one per film; never mi## The process-1. **Story sentence** and the sourced brief. ✋ One approval.-2. **Storyboard**: one line per beat with its length in beats, the words, the transition.+1. **Story sentence** and the sourced brief (a brand film: `brand-film.md` steps 0 to 5 first). ✋ One approval.+2. **Storyboard**: one row per beat with its length, the action, what it carries in, the words, the+ transition, as `board.json`; `node tools/board.mjs board.json` must pass. The person sees it as a+ page of drawn stills with timing, never text only.3. **Options sheet**: transitions and type styles side by side as one cheap still sheet (e.g.three blooms, three lettering media). The person picks; nothing is rendered in full yet.4. **One still per scene**, at 0.3-0.5 scale on a contact sheet, reviewed for design:@@ -176,7 +213,9 @@ into place), round iris seams, the product's own UI. Pick one per film; never misheets, cuts as before/after pairs, DESIGN first (type over art, spacing, hierarchy), then timing. Render only the changed range(`render.mjs --from F --to T` writes `out/<film>.<F>-<T>.mp4`, silent). Give notes in camera words ("slow this zoom to 0.7x","hold the word 10 frames longer"), never "make it better".-8. **QA**: review every shape's contact sheet against the design checklist in+8. **Ship before showing**: `node tools/ship.mjs <film> --file out/<file>.mp4` on the exact file you+ will send, for every version, its table attached (`review.md`). For template films, also:+ **QA**: review every shape's contact sheet against the design checklist in`launch-video-kit.md` (no clipped type, no edge-cropped content, balanced per shape, coherentcontent). `launch.mjs ship <film> --shapes ... --gate` runs, for EVERY shape shipped, `framecheck`(text and cards whole on every frame; each text up long enough to read; on 9:16 nothing underdiff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/machines.md b/plugins/anidoodle/skills/anidoodle/references/workflows/machines.mdindex 24c7947..f7bf80e 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/machines.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/machines.md@@ -1,5 +1,7 @@# Machines: explain an idea by building it, in any style+**Contents:** 1. Turn the idea into a machine · 2. Parts list before geometry · 3. One model drives everything · 4. Build with the kit · 5. Draw it in a style: the hand · 6. Films and interactive pieces · 7. Check it+A machine is a subject, not a look. The kit (`engine/src/canvas-core/mechanismKit.ts`) builds realparts in 3D, sorts them, takes them apart and folds them back; a **hand** marks them in a style'sown medium. The same music box draws as cyanotype, coloured pencil, stipple or flat iso planes.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/motion-film.md b/plugins/anidoodle/skills/anidoodle/references/workflows/motion-film.mdnew file mode 100644index 0000000..ca1105b--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/motion-film.md@@ -0,0 +1,102 @@+# Motion films: one world, one camera++**Contents:** Why one world · Start a film as one world · The kit · Type that enters and leaves · Brand temperament · Approved shots stay approved · The scans · Exceptions, declared · Rendering with blur++A motion-graphics film (a launch, a promo, an explainer in a clean register) is judged first on+whether it moves like one piece. A brand launch film built scene by scene, each scene rebuilding its+own layout, was called "a literal slide deck" four times; both of its critics flagged the same+carousel in its middle. The cure is architectural, and the scans below hold it.++## Why one world++Every beat is a **region** placed on one canvas in world coordinates, and a single **camera** travels+between them. Nothing is rebuilt per scene, so nothing can cut like a slide: every seam is a camera+move, and the thing on screen at the end of one beat is still in the world at the start of the next.+Regions clip their own drawing by default, so one region never leaks an edge into its neighbour.++## Start a film as one world++```bash+node tools/worldfilm.mjs promo --beats 4 --format 16x9 --temperament calm # writes the film and its host page+node tools/motionscan.mjs promo && node tools/layerscan.mjs promo # the scaffold passes both as written+```++`engine/src/canvas-core/world.ts`:++```ts+const w = world({ W: 1920, H: 1080, regions: [{ id: "chat", rect: [0, 0, 1600, 900] }, { id: "crowd", rect: [1900, 200, 2400, 1350] }],+ stops: [{ f: 0, at: "chat", hold: 90 }, { f: 150, at: "crowd", hold: 60 }], alive: { amp: 3, seed: 7 } });+w.begin(ctx, env, f); // the camera's transform: draw in world units+w.region(ctx, "chat", () => drawChat(ctx)); // clipped to its rect+w.end(ctx);+w.depth(ctx, env, f, 0.33, () => frieze(ctx)); // a layer of brand shapes at a third of the camera's speed+```++A stop with no frames to travel is refused: that is the slide cut. `minTravel(px, maxPxPerFrame)`+gives the frames a move needs at the temperament's top speed. `regionAt(f)` and `moves()` list where+the camera is and every seam. Regions may be a function of the frame shape, so one world re-composes+for 9:16 from day one.++## The kit++`engine/src/canvas-core/motionKit.ts`, all pure arithmetic over the frame:++| Call | For |+|---|---|+| `alternate(i, ["left", "right"])`, `entryFrom(i)` | the i-th item of a list enters from a different side each time: a program never plays as a carousel |+| `chatScroll(f, steps)` | a chat column that scrolls over 18 to 24 frames on an ease-out; a snap is refused |+| `temperament("calm" \| "lively" \| "snappy" \| spec)` | the brand's motion as numbers: top speed, settle frames, overshoot or not, an arrival ease |+| `cubicBezier(x1, y1, x2, y2)`, `motionTokens(BRAND.motion, fps)` | a brand's own easings (from `brand.mjs`) as eases and frame counts |+| `typeExit(q)` | how far a line has sunk on its way out (ease-in, 1.3x its size) |+| `sharp(() => draw())` | marks a layer the motion blur must leave sharp |+| `landSquash(t, land, { brand, gag })` | squash on landing, volume kept; refused on a brand mark unless the gag is named |++`world({ alive })` gives the camera a slow breath; `w.depth` the parallax layer. People: `people.ts`+places cut-outs by head height (`drawPerson`, `popOut`). Brand marks: `brandKit.ts`.++## Type that enters and leaves++- `setType(ctx, env, text, x, y, size, p, { out })`: words rise in, and with `out` sink out last+ word first on an **ease-in** over 1.3x their size, so they clear the clip edge at speed. A sink that+ eased out decelerated into the mask and left slivers for half a second ("check each and every frame").+- `{ space: "world" }` draws inside the current transform (a camera, a region); the default resets to+ screen space.+- Type and photos leave in 0.5 to 0.7 s and are never blurred (`../motion-grammar.md`).+- Holds come from the words: `readable.ts` (`chatHold`, `readS`, `paced`, `texture`, `fitText`).++## Brand temperament++Set `meta.motion.temperament` before any motion is built. Too violent and too flat are both a+missing temperament. `motionscan` fails any stretch faster than its top speed.++## Approved shots stay approved++When the person approves a shot, freeze it: `node tools/lock.mjs <film> --shot logo` prints its sha;+put `["logo", "<sha>", "<who approved it, and when>"]` in `meta.motion.approved`. `lock.mjs <film>`+fails if its frames change; `--unlock logo` lets a deliberate change through, which is the moment to+ask the person again. A shot that was "improved" in passing had to be rebuilt exactly.++## The scans++| Tool | Reads | Fails |+|---|---|---|+| `motionscan.mjs <film\|file.mp4>` | the rendered file (any MP4) | **slidecut**: most of the content replaced within 6 frames with no camera move, more than 2 a minute; **repeat**: 3 beats in a row settle into one layout (a carousel); **dissolve**: a cross-dissolve or fade-in over a real share of the frame; **temperament**: faster than the film allows |+| `layerscan.mjs <film>` | what each frame draws | **exits**: text residue at its clip edge for 0.2 s or more; **fasttext**: type faster than half the speed ceiling; **faces**: a moving shape (any probe box, brand marks included) over the top 30% of a person's photo; **translucent**: a brand colour filled between 5% and 95% alpha |+| `lock.mjs <film>` | approved shots | a locked shot that changed or went missing |++A check with no input says N/A with its reason (no temperament declared, no photos, no brand+colours); the ship command lists those, never counts them as passes.++## Exceptions, declared++`meta.motion.allow = { slideCut: [[from, to, reason]], dissolve: [...], translucent: [...] }`: a hard+cut on a strong beat, a dissolve the story needs, a declared brand fade. Each has its reason.+`meta.motion.brandColors` comes from `brandMotion` in the module `brand.mjs import` writes.++## Rendering with blur++`render.mjs --blur auto` blurs fast moves by their real speed and keeps text, photos and anything in+`sharp()` crisp (the pixels they own come from the sharp frame); `--blur-all` blurs everything, the+old behaviour. Text baked into a cached plate is blurred with the plate: draw type on the frame. Every+render writes `<out>.film.json` (film id, frames, blur, sha256, meta), so a renamed or versioned file+is still checked as its film.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/narration.md b/plugins/anidoodle/skills/anidoodle/references/workflows/narration.mdnew file mode 100644index 0000000..9843f5e--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/narration.md@@ -0,0 +1,175 @@+# Narration, word timing and subtitles++**Contents:** The order of work · The script: narration.json · Choosing a voice · The commands · The round trip, and why it is not optional · Narration sets the clock · Phrase subtitles · Caption files · The mix++A narrated film is timed by its voice. The script is written first, each line becomes one take,+the takes are heard back word for word, and the picture is cut to the words. Everything here works+the same for 2D and 3D films.++Narration is the one generated input anidoodle allows, and only on the person's request: the voice+they chose, each take cached by a hash of what made it, then baked into the film so the film needs+no file and no network to play. Needs `ffmpeg` and whisper.cpp (`brew install whisper-cpp`; the+tool prints the one-line model download when no model is found).++## The order of work++1. Write the script and budget its time before setting the film's length: every phrase needs+ `max(0.7 s, 0.3 s per word)` on screen, and a voice says 1.2 to 4.5 words a second. A rhymed+ narration on the last film set the runtime to 119 s on its own.+2. Draft with a free voice, cut the picture to it, then make the final takes with the chosen voice.+3. `narrate.mjs check` until it passes, then `bake`.+4. Build the shots on the words (`cue`), the subtitles from the timing, the mix with the duck.+5. Render, then `check --mix` on the finished file, `framecheck`, `verify-export --delivery`.+ A human listens before it ships: you cannot hear the voice.++## The script: narration.json++```json+{+ "fps": 24,+ "provider": "kokoro",+ "voice": { "name": "af_heart", "speed": 1 },+ "lead": 12, "tail": 30, "pause": 0.4, "lang": "en",+ "aliases": { "Clawd": ["claude"] },+ "lines": [+ { "id": "open", "text": "Every film starts as a few plain words." },+ { "id": "code", "text": "It draws itself at twenty four frames a second.", "display": "It draws itself at 24 frames a second.", "pauseAfter": 0.6 },+ { "id": "end", "text": "Then the clock rang out \"Context!\" for him.", "at": 400 }+ ]+}+```++- `lead` and `tail` are frames of air before the first line and after the last; `pause` is seconds+ between lines, `pauseAfter` overrides it for one line, `at` pins a line to a frame (refused if the+ line before is still speaking).+- `text` is what the voice says; `display` is what the screen shows. Write numbers, money and+ symbols as spoken words in `text` and as figures in `display`: each screen word takes the frames+ of the words spoken for it ("24" gets the frames of "twenty four").+- A line's own `voice` overrides the script's. `aliases` accept a name the transcriber spells+ another way.+- Write an emphasised word in plain case inside quotes, never in capitals. A cloud voice read+ "the clock rang out CONTEXT for him" as "the clock rang out for him", silently; the quoted+ plain-case form passed three takes of three.++## Choosing a voice++Ask which voice the person wants. The script's `provider` is the only way a voice is chosen; the+command line has no override, so a paid voice is called only when the script names it.++| Provider | Runs | Licence and cost | Setup |+|---|---|---|---|+| `say` | this Mac, offline | Free. Apple licenses the system voices for personal, non-commercial use, so **drafts only**: re-voice before publishing, and never commit a `say` take or a module baked from one | macOS only. `voice: { name, rate }` |+| `kokoro` | this machine, offline | Free; code and weights Apache-2.0, so a clean choice for a film that ships | `pipx install kokoro-tts`. `voice: { name, speed, lang }` |+| `files` | your own recordings | Yours | one `<id>.wav` (or aiff, flac, mp3, m4a) per line in `voice.dir` (default `takes/` beside the script) |+| `gemini` | Google's servers | Paid per use; the text goes to Google; their terms govern the audio | `GEMINI_API_KEY` or `GOOGLE_API_KEY`. `voice: { name, style, model }` |+| `openai` | OpenAI's servers | Paid per use; the text goes to OpenAI | `OPENAI_API_KEY`. `voice: { name, model, instructions, speed }` |+| `elevenlabs` | ElevenLabs' servers | Paid per use; the text goes to ElevenLabs | `ELEVENLABS_API_KEY`. `voice: { id, model, stability, similarity, seed }` |++Before a cloud voice runs, tell the person that each line's text is sent to that company and that+it costs money per use, and get their yes. Never pick a paid voice for them. Keys come from the+environment only; the tool never prints them, and they never go into the script, a command you+show, or a file. `node tools/narrate.mjs providers` lists what this machine can use.+The kokoro, openai and elevenlabs modules have not yet been run against the real service: make one+line and `check` it before voicing a whole script.++## The commands++```bash+node tools/narrate.mjs providers # which voices this machine can use+node tools/narrate.mjs say <narration.json> # make every take (cached: .cache/voice/<sha256>.wav)+node tools/narrate.mjs time <narration.json> # word timings -> out/narration/<name>/voice-timing.json + lines/<id>.wav+node tools/narrate.mjs check <narration.json> # the round trip; exit 1 on any failure+node tools/narrate.mjs bake <narration.json> # write src/canvas-core/<name>Voice.ts (timing + takes)+node tools/narrate.mjs all <narration.json> # check, then bake when it passes+```++Flags: `--out DIR` (stems and timing), `--module FILE` (the baked module), `--model FILE` (a+whisper.cpp model; `ggml-small.en.bin` hears better than base), `--shape 16x9|9x16|1x1` (subtitle+line length), `--max-wer 0.03`, `--mix out/<film>.mp4` (check the finished mix too), `--force`+(make every take again).++A take is keyed by provider, voice settings, text and processing, so editing one line re-makes+only that line, and checking, timing or baking cached cloud takes never calls the company or needs+the key. `--force` re-makes, and re-pays for, every take. Each take is trimmed, padded and levelled+to -20 LUFS. `time` also writes a voice-only stem per line: keep them, so one line can be swapped+later without re-recording the takes people liked.++## The round trip, and why it is not optional++A voice model can drop or change a word without any error, and the take still sounds fluent. A+shipped film lost the word CONTEXT this way and only a human ear caught it. So `check` transcribes+every take with whisper.cpp, with no prompt (it must hear what was said, not what was meant),+and holds it to the script word by word, after normalising numbers, money and times on both sides.++It fails on: any dropped or changed script word, named; extra heard words past `--max-wer`; a+word with no timing of its own, out of order, under 0.05 s or over 1.5 s, or a gap over 1 s inside+a sentence; clipping, a peak over -1 dBFS, too much silence at either end, a silent take, a pace+outside 1.2 to 4.5 words a second; a subtitle phrase that cannot get its reading time (TOO TIGHT);+a baked module made from other takes or another timing. With `--mix` it transcribes the finished+film as well, so a score that buries a word fails too.++On a failure, fix the script (rewrite the word, spell the number, quote the emphasis), re-run+`check` (only the changed line is re-made), then `bake`. A film plays the baked module, so a take+changed after the bake is a stale film until it is baked again. Word times come from whisper's+segments, good to about 50 to 100 ms: right for phrases and for landing a beat on a word, too+coarse for lip sync. Normalising is English only; a year spoken as words can read as a change.++## Narration sets the clock++The audio is measured first and the picture follows it, never the reverse: a picture timed to a+guessed read drifted 30 to 40 frames from the voice on the last film.++```ts+import { myFilmVoice as VOICE } from "./myFilmVoice"; // written by narrate.mjs bake+import { cue, cueEnd, drawSubtitles, phrases, toCaptions } from "./subtitles";+import { narrationAudio, syncMarks } from "./voice";+const T = VOICE.timing, EVENTS = phrases(T, { shape: "16x9" });+const HIT = cue(T, "code:24"); // the frame "24" is spoken; "code" = line start, "end:the#2" = the second "the"+```++- The film's length comes from `T.totalFrames` (rounded up to the beat). Cuts land on line+ starts, reveals on the word that names them.+- In 3D, `timeline(fps, { words })` places clips on words by name; see `references/workflows/three-d.md`.+- When shots were written before the voice, map each story frame to its spoken cue with+ `storyClock` (`engine/src/three-core/time.ts`) instead of moving every constant by hand. Cyclic+ motion keeps the real frame.++## Phrase subtitles++`phrases(timing, opts)` cuts each line into 2 to 6 word phrases, one on screen at a time, and+`drawSubtitles(ctx, env, frame, events, style)` burns them in. A whole line in a lower band was+too much to read on the last film; short phrases, each landing on its own words, read without+pulling the eye off the picture. The rules, held in code:++- A phrase appears 2 frames before its first word is spoken and holds at least+ `max(0.7 s, 0.3 s per word)` and 20 frames, at most 7 s, with 2 frames between phrases.+- Breaks fall at punctuation, then clause words. Never between an article and its noun, a number+ and its unit, a currency sign and its amount, or inside a name (`keep: ["Total Recall"]`).+- When the speech is too fast to give a phrase its reading time, `phrases` throws TOO TIGHT+ instead of squeezing it. Slow the read, cut words, or add a pause.+- At most 32 characters a line for 16x9 and 1x1, 22 for 9x16; a long phrase wraps to two lines.+- `style.home` places the phrase: one home per shot, in calm negative space, never over a face, a+ hand at work or a joke, and it moves only on a cut (pass a function of the frame). White type+ on a dark plate, never grey; `highlight: true` lights the word being spoken. On 9:16 it stays+ out of the phone's interface zones.++## Caption files++`meta.captions = toCaptions(EVENTS, fps)` hands the same phrases to the sidecar files;+`toCaptions` refuses events that break the rules. `node tools/captions.mjs <film>` writes `.srt`+and `.vtt`, and `framecheck.mjs` holds every cue to its reading time and every burned phrase to+the frame.++## The mix++```ts+audio: narrationAudio({ voice: VOICE, music: filmAudio(score, N / FPS), frames: N, musicDb: -6, depthDb: -9 }), // filmAudio: ./music/render+meta: { ..., captions: toCaptions(EVENTS, FPS), sync: syncMarks(T) },+```++The score sits 6 dB under its own level and ducks a further 9 dB under the voice, measured from+the voice itself. The dip starts 40 ms before each line, so the first syllable never lands on+full music, holds across the gaps between words and comes back over 450 ms. One delivery master+brings the mix to -16 LUFS under -1 dBTP. `syncMarks` puts a marker on each line's first word, so+`verify-export.mjs --delivery` measures the voice landing on its frame. The baked takes cost+about 64 KB of page per second of speech, fine for a short film; a long one is a size to state.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/review.md b/plugins/anidoodle/skills/anidoodle/references/workflows/review.mdindex 995c897..c25f0c1 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/review.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/review.md@@ -1,5 +1,7 @@# The review: a fresh critic, three rounds at most+**Contents:** The loop · No version is shown without its ship table · Before any critic: the design pass · What the critic does · The four readings · Severity · The check before fixing · The scorecard · The gate · The fix ledger+The builder never judges its own work. A builder who has watched the film forty times sees whatthey meant, forgives the hand they know is hard, and grades the effort. So every review is done bya **fresh critic**: a new subagent (or a new session) that has seen none of the building.@@ -13,7 +15,11 @@ film), and after each **full render**. The loop is the same each time.the builder is already re-rendering.2. **Brief the critic.** Give it the frozen file (for a storyboard, the rows), the story in threesentences, the shapes and sound the film promised, and this page. Give it none of the build:- no conclusions, no chat history, no list of what you think is wrong.+ no conclusions, no chat history, no list of what you think is wrong. DO give it the person's+ own earlier rejections, verbatim, from the project ledger ("that end card is a mess... who is+ going to read this overload of info?"). Critics calibrate on collisions and counts; the person's+ words are the only record of their taste for density, hierarchy and humour. A critic that called+ an end card "generous" which the person had already rejected three times was judging the wrong film.3. **The critic reports** (below). It returns ranked problems with timestamps and a verdict.4. **Fix the biggest problem first.** Then the next, if they share a rebuild. Re-render.5. **A NEW critic rechecks.** Not the one who found the problems; it would see only what it expects.@@ -22,6 +28,35 @@ film), and after each **full render**. The loop is the same each time.finds new taste, not new faults. After round 3, report what remains, honestly, in the ledgerand to the person ("two P2 left: the brush wipe is used twice, the tail rings 0.4 s long").+## No version is shown without its ship table++`node tools/ship.mjs <film> --file out/<the file you will send>.mp4` runs every check on the exact+delivered file (framecheck, verify-export, the gate, motionscan, layerscan, the locks, the sound or+track checks, the cues, facts, the review ledger, the length budget) and writes `SHIP.md`, `ship.json`+and a critic sheet (a frame every 2 s, every shot start, the last frame) beside it. A check that+cannot look is a FAIL, never a pass; an N/A shows as a FLAG with its reason; `--quick` skips the gate+and can never say PASS. Nine versions of a launch film reached the person with no check at all, and+the checks that did run had passed while blind. Attach the table to every version you show.++The critic's findings and the person's own notes live in `reviews/<film>.json`, which ship reads:++```json+{ "findings": [{ "id": "r1-4", "p": "P0", "status": "open", "note": "the end card is crammed", "by": "critic r1" }],+ "notes": [{ "at": "2026-10-27 21:36", "from": "<the person>", "text": "who is going to read this overload of info?" }] }+```++An open P0 fails the ship, an open P1 flags it, and the person's last three notes are printed+verbatim in the table, to be re-read against the new sheet.++## Before any critic: the design pass++The builder checks bugs well and taste badly ("I checked my frames for bugs, not for design"). So+before a version is shown to anyone, the builder judges a still sheet of it **for design first**:+hierarchy, flow, whether each frame would pass as a poster, the brand's temperament; then bugs. It+re-reads the person's last three notes against the new sheet, one by one. Before the first full+render, run a design critique of the storyboard stills with whatever design skills the person has+installed (name them in the brief). Changed beats are shown as a still sheet before any re-render.+## What the critic does**Pulls its own frames.** It does not use the builder's stills. From the frozen file:@@ -123,8 +158,8 @@ The film ships when all of these hold:- every line is 3 or more, Finish is 5, and the average is 4 or more;- no P0 is open (a P0 still open after round 3 is a blocker the person is told about, never shipped quietly);-- `gate.mjs` and `verify-export.mjs` pass, and for a scored film `music.mjs check` passes and a- human has listened;+- `ship.mjs` passes on the delivered file (it runs the gate, verify-export and every scan), and for+ a scored film `music.mjs check` passes and a human has listened;- the last critic's verdict is `ship`, or three rounds are used and what remains is in the ledger.After the rebuild, the new critic goes down the earlier list item by item against the new file anddiff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.md b/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.mdindex b846746..5d524e1 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.md@@ -1,5 +1,7 @@# Start here: agree the piece with the person, then build+**Contents:** The intake · When they name a move · Defaults when they do not say · Write it down before you draw · Before the first full render · Alive means real motion+anidoodle makes many kinds of thing in many hands. Nothing about a piece is fixed in advance:not its length, its shape, its style or its sound. So the first job is to find out what thisperson wants, quickly, one question at a time, and to fill every gap with a stated default@@ -14,20 +16,29 @@ pick", pick, say what you picked and why in one line, and carry on.explainer, an infographic, a launch or product video, an interactive web piece, a drawinglesson, a character, or a style matched from their image. The table in `SKILL.md` routes eachone to its workflow file.-2. **Which style?** Show the gallery (https://github.com/alexgreensh/anidoodle/blob/main/skills/anidoodle/assets/styles.jpg, one tile per hand; the list with+2. **Drawn or 3D?** One medium for the whole film. Recommend one with a reason: 3D for solid+ things in light (extruded type, products, toys and puppets, a camera moving through space),+ drawn for anything where the marks are the point. A drawn world with a 3D puppet pasted on read+ as two films glued together on the last 3D film, so build a hybrid only when they ask for one.+ 3D goes to `references/workflows/three-d.md`; the style question below is for drawn pieces.+3. **Which style?** Show the gallery (https://github.com/alexgreensh/anidoodle/blob/main/skills/anidoodle/assets/styles.jpg, one tile per hand; the list witheach hand's medium is `references/styles/INDEX.md`). Recommend two or three hands that suit thesubject and the audience, with one reason each. Offer two other routes:- **"Match my image"**: they bring a picture and you adapt its hand (`adapt-a-style.md`).- **"A house style"**: they already picked one before; load it from `styles/house/`.-3. **What shape and where will it live?** Square `1x1`, vertical `9x16`, wide `16x9`, portrait+4. **What shape and where will it live?** Square `1x1`, vertical `9x16`, wide `16x9`, portrait`4x5`, or any W x H they name. One source can ship several shapes (`references/formats.md`).-4. **How long?** Any length. A three-second sticker, a ninety-second story, a five-minute+5. **How long?** Any length. A three-second sticker, a ninety-second story, a five-minuteexplainer, a twenty-minute lesson. Never cap it and never assume it. Long pieces get chapters(`long-film.md`).-5. **Sound?** Silent, or a score: name a music style and a mood per section- (`references/music/`). Their own voice-over or track is theirs to bring; anidoodle composes- and plays everything else.-6. **Characters?** A new one (build it once, `character-consistency.md`), one they already have+6. **Sound?** Silent, or a score: name a music style and a mood per section+ (`references/music/`). Their own track is theirs to bring; anidoodle composes and plays everything else.+7. **Narration?** None, their own recordings, or a generated voice they choose+ (`references/workflows/narration.md`). Say it plainly when you offer one: macOS `say` is free+ but for drafts only (Apple licenses its voices for personal, non-commercial use); Kokoro is free,+ local and licence-clean; a cloud voice (Gemini, OpenAI, ElevenLabs) sends the script's text to+ that company and costs money per use, so it runs only on their yes and with their own key.+8. **Characters?** A new one (build it once, `character-consistency.md`), one they already havein a module, or one from their image (reference, embedded only if they ask).Stop asking the moment you can build. Two questions answered well beat six asked.@@ -59,8 +70,8 @@ the reason in one line, record the alternative you will build, and let them veto## Write it down before you draw-One short brief file in the project: kind, style (and why), shape(s), length, sound (style +-moods), characters, the one-sentence idea, and any named moves as name, duration, strength and+One short brief file in the project: kind, medium (drawn or 3D), style (and why), shape(s), length, sound (style ++moods), narration (and whose voice), characters, the one-sentence idea, and any named moves as name, duration, strength andwhat moves (card defaults marked as such). Everything the person said goes in their words.Everything you decided is marked as yours so they can veto it in one line.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/three-d.md b/plugins/anidoodle/skills/anidoodle/references/workflows/three-d.mdnew file mode 100644index 0000000..93db68b--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/three-d.md@@ -0,0 +1,202 @@+# 3D films and 3D motion graphics++**Contents:** 3D or 2D: one medium per film · Benchmark before the look still · A 3D shot · The contract in 3D · The kit, by job · The craft bar in 3D · The checks, and what each catches · Rendering++A 3D shot is an ordinary shot. three.js renders into WebGL, `draw3d` copies the pixels onto the+frame's 2D canvas, and every tool (still, render, gate, framecheck, captions, emit, the score)+works on it unchanged. The Film workflow in `SKILL.md` still runs in full: three sentences, one+look still, one music sample, a fresh critic. This page adds what is different in 3D.++## 3D or 2D: one medium per film++Pick 3D when the subject is solid things in light: extruded type, products and objects, toys+and puppets, a camera that travels through space, stop-motion. Pick 2D when the marks are the+point: any of the drawn styles, a drawing that makes itself, ink and paint. The 2D style plates+have no 3D version, so a request for "watercolour, but 3D" is a question to ask, not a build.++Make the medium a brief question ("all drawn, or all 3D?") and keep one medium for the whole+film. The last 3D film rejected four mixed looks before the one that worked: code-painted 2D, pasted+reference pixels, a drawn world with a 3D puppet composited on top, a painted backdrop behind 3D.+Each read as two films glued together. Build a hybrid only when the person asks for one. Finish+layers drawn over the 3D frame (subtitles, grain, vignette, a plated title) are not a second medium.++## Benchmark before the look still++The kit makes it easy to put a lit, bevelled object on screen, and that is the trap: a capsule+robot, a box house and lollipop trees under default materials render cleanly, pass every check,+and still read as a beginner's three.js scene. It happened on this kit's first flagship still+(graded 7 by its builder, rejected on sight). Clean is the floor. The bar is designed 3D, and you+cannot hold a bar you have not looked at.++So before the look still, build a reference board:++1. **Find 6 to 12 real references** of excellent stylized 3D close to the brief: award-winning+ WebGL work, stylized 3D studios, stylized games and films (a paper world that comes alive+ points at Tearaway; a miniature town at Townscaper). Open them and look; do not work from memory.+2. **Write what makes each one work**: shape language and proportions (characters designed as+ shapes with a silhouette, never a stack of capsules), bevel softness, material recipe, light,+ palette, depth and atmosphere, lens and framing, how dense the small detail is.+3. **Pick ONE benchmark** and say which techniques you take from it. References are rebuilt in+ code; their pixels never ship.+4. **Critique the still side by side with the benchmark**, by a fresh critic+ (`references/workflows/review.md`), and grade against the benchmark, never against "it works".+ A still that would look out of place next to its benchmark is not done.++## A 3D shot++```ts+import * as THREE from "three"; // the vendored build, resolved by the bundler+import { draw3d, memo } from "../three-core/stage";+import { orbit, place } from "../three-core/camera";++const build = () => { /* scene, meshes, lights, camera: built once, never reads the frame */ };+const shot = (ctx: Ctx, f: number, env: Env) => {+ const s = memo(env, "myShot", build); // the same objects every frame+ s.star.rotation.y = (f / 96) * Math.PI * 2; // every moving value SET from f, every frame+ place(s.cam, orbit([0, 0, 0], 0, 40, 6, 1.5, 0, 96)(f), env); // camera first, then anything placed on screen+ draw3d(ctx, env, s.scene, s.cam, { clear: "#0f0d1a" });+ // 2D finish on top: subtitles, grain, vignette+};+```++`engine/src/canvas-core/threeHello.ts` is the smallest whole film. `threeMotionDemo.ts`,+`threeTypeDemo.ts` and `threeRigDemo.ts` beside it show the motion, type and character kits.++## The contract in 3D++Frames render in parallel chunks and out of order, so frame N has to be the same picture however+it is reached. 3D makes that easy to break, because a scene graph remembers.++- **Pure in the frame.** Build once with `memo`, then set every moving value (position, rotation,+ scale, opacity, colour, morph, camera) from the frame number on every draw. A value left over from+ the frame before is the classic 3D bug: on the last film a dropped broom vanished when a render+ chunk started after the drop, and a firefly was placed with the previous drawing's camera.+ When a shot needs a pose from an earlier beat, rebuild it at that fixed beat, read it, and throw+ it away. Never carry it in a `let`.+- **No clock.** No `Math.random`, `Date`, `performance.now`, `setAnimationLoop`, `THREE.Clock`,+ `mixer.update(dt)`. An `AnimationMixer` is driven with `mixer.setTime(f / fps)`. The gate's+ contract scan reads `src/three-core` as well as `src/canvas-core` and fails on these.+- **Seeded randomness**: `rand(seed)` from `three-core/stage.ts`, one seed per system, so adding+ one effect does not reshuffle another.+- **Import three as `import * as THREE from "three"` in each file, and never re-export the+ namespace.** Re-exporting stops the bundler dropping the unused parts, which drags three's file+ loaders (which can fetch) into the player, and the gate fails a player that can reach the network.+- **`ss` supersampling, default 2** (`draw3d(..., { ss })`, 1 to 3): rendered at 2x and scaled down,+ so edges are smooth and identical on every backend. MSAA varies by driver; do not turn it on.+- **Shadows are off by default** (`{ shadows: true }` turns on soft shadow maps). A shadow is a+ choice, and shadow acne is the first cheap-3D tell.+- Fonts arrive as data: `defaultFont()` is Poppins Bold, inlined from `engine/assets/fonts/`+ (OFL, provenance in `engine/assets/fonts/PROVENANCE.md`). three.js itself is vendored, scanned+ and hash-pinned: `engine/vendor/three/PROVENANCE.md`.++## The kit, by job++All in `engine/src/three-core/`. Every function takes the frame and returns or sets a value; none keeps state.++| Job | Module | What to reach for |+|---|---|---|+| Stage | `stage.ts` | `stage`, `draw3d` (render and copy to the frame), `memo`, `rand`, `probe3d` |+| Time | `time.ts` | `seg`, `tween`, `ease.*`, `spring` (closed form, seekable), `beatFrames`, `storyClock` |+| Timeline | `timeline.ts` | `timeline(fps, { labels, words, beat })` with `tl.at`, `tl.value`, `tl.check`; clips `to`, `fromTo`, `set`, `wait`, `all`, `chain`, `sequence`, `delay`, `loop`; `mix` (colours in linear light) |+| Camera | `camera.ts` | `look`, `place`, `hold`, `then`, `withMods`; `pushIn`, `pullBack`, `dolly` + `path`, `orbit`, `crane`, `truck`, `pan`, `tilt`, `whipPan`; mods `handheld`, `dutch`, `zoom`; `fitTo`, `rackFocus`; `matchCut`, `matchLens`, `screenPx`, `screenSize`, `worldForPx` |+| Motion graphics | `mograph.ts` | `popIn`/`popOut`, `dropIn`, `riseFromFloor`, `growFrom`, `fadeIn`/`fadeOut`, `extrudeIn`, `writeOn`/`drawTo`, `moveAlongPath`, `morph` + `writeTube`, `explode`/`assemble`, `indicate`, `wiggle`, `wave`; groups `lagged`, `grid`, `kinetic` (per letter) |+| Type | `type3d.ts`, `ttf.ts` | `text3d(env, font, text, opts)` (one mesh per letter, `userData.letters`), `textPlane` (flat crisp text in the scene), `defaultFont`, `parseTTF` for another TrueType face |+| Look | `look.ts` | rigs `studio`, `night`, `interior`, `sunset`; materials `matte`, `satin`, `toon`, `glass`, `emissiveGlow`; `outline` (`screen: true` for a width in pixels), `contactShadow`, `softShadows`, `grain`, `vignette` |+| Transitions | `transitions.ts` | `transition(ctx, env, t, kind, drawA, drawB)` with `crossfade`, `wipe`, `radialWipe`, `noiseWipe` (ink blot), `slide`, `zoomThrough`; t at 0 or 1 is exactly A or B |+| Characters | `rig.ts` | `makeRig`, `part`, `anchor`, `limb`, `head`, `flag`, `pose`, `bodyMatrix`, `solveTwoBone`; props `handle`, `grip`, `gripFrame`; motion `lookAt`, `anticipate`, `followThrough`, `squashStretch`, `walkCycle` |+| Checks | `checks3d.ts` | `checkGrip`, `proximity`, `selfClear`, `pathClear`, `labelVisible`, `placeLabel`, `screenSizeOk`; per frame: `resetChecks`, `register*`, `runChecks` |++Mograph verbs take `(object, f, at, len)` and set their channels from the object's rest pose:+before `at` the object is in its before-state, after `at + len` it is exactly at rest. A+`timeline` `to()` on a track that was never set throws instead of moving from a silent 0.++**Two clocks for narrated or rescored films.** Write shots against story frames and map the real+frame through `storyClock([[story, real], ...])`, so a narrator who stretches the film is a table+edit (the last film retimed about 100 beat constants this way). Cyclic motion (walks, flicker,+breathing) reads the real frame, or it plays in slow motion. Keep every story action as a named+frame constant at the top of the shot. Word cues come from narration: `references/workflows/narration.md`.++## The craft bar in 3D++The test from `references/craft-bar.md` holds: would a proud maker ship it? In 3D the question is whether it+reads as a designed miniature or as an untextured blockout.++| The cheap-3D tell | What passes |+|---|---|+| Shadow acne, self-shadow creases on a character | Shadows off unless chosen; `softShadows(light)` sets acne-free biases; characters get `receiveShadow = false` and a `contactShadow` under them |+| Plastic shine | `matte` or `satin` (sheen, low specular); metal only where the thing is metal |+| Jaggies, shimmering edges | `ss: 2`; check a 2x crop |+| Black crush in the shadows | Every rig has a sky fill; `vignette` darkens toward a tinted colour, never black |+| A muddy interior lit by the outdoor rig | `interior()`: a key from above, a warm practical, a warm fill |+| Far glows going grey in fog | `emissiveGlow` (fog off): distance reads by size |+| Glass with a second, offset outline | `glass()`: front side only, thin, low IOR |+| Boxes with a glowing plane for a window | Built like a model maker would: frames, sills, bevels, varied repeated pieces |+| A hook, a lamp or a sign floating | Every part held by something (a bracket, a string, the ground); look at the joins at 2x |+| One angle per shot, a locked camera | Each shot gets an angle, a move and a seam (`references/motion-grammar.md`, `deck.mjs deal`) |+| A whip pan with smear frames | `whipPan` holds posed frames at both ends; a match cut keeps size with `matchCut`/`matchLens` |+| Frozen arms on a walking character | Limbs that pose from the start: arm counter-swing (`walkCycle`), reach with `anticipate`, props that lag (`followThrough`) |++Five rules the last film paid for, each with its check:++- **Contact beats are framed close.** A grip, a push or a hand-off reads only when the contact+ point is at least about 40 px tall at 1080p. A gate push filmed from 17 units away showed a claw+ a few pixels wide and read as nothing. `registerSize(hand.end, 40)` holds it.+- **Thin lines are sized by screen, not world units.** A fixed-width thread vanishes in a wide+ shot. Size it with `worldForPx`, or use `outline(..., { screen: true })`.+- **Labels are placed after the camera.** A tag reading "/co act" because a claw covers two letters+ is a placement problem. Set the camera, then `placeLabel` tries positions until the label reads;+ `registerLabel` flags one still hidden or turned away.+- **Hands act.** Build every rig with posable limbs and grip points before any shot. A rig whose+ arms were fixed geometry played every shot with frozen claws, and retrofitting the arms cost+ two rendered shots. `pose` throws on a flag a rig variant does not have, so nothing silently+ does nothing.+- **Grips read.** A held handle runs along the hand's grip axis through the closed grip (`grip`),+ a lantern hangs from its bail (`hang: true`). A broom, a shovel and a jar went through the claws+ for a whole first cut and nobody saw it until a critic did. Check the rig's reach before blocking a+ hand-off: when the hands cannot meet, a toss, a drop or a set-down reads better and never clips.++## The checks, and what each catches++```bash+node tools/still.mjs <film> --frames 0,48,96,150 --out out/look/ --sheet out/look-sheet.png+node tools/still.mjs <film> --frame 126 --scale 2 --out out/grip-126.png # a 2x crop+node tools/framecheck.mjs <film>+node tools/gate.mjs <film>+```++- **Still sheets.** `--sheet` takes a file path. A bare `--sheet` swallows the next argument, so+ `--sheet --out x.png` writes the sheet to a file named `--out`.+ Then a 2x frame of every contact beat, face and join: the checks see geometry, a crop sees+ what the viewer sees.+- **framecheck** with `probe3d`: call `probe3d(ctx, env, object, camera, label)` after the camera+ is placed, for 3D type and any hero object that must be whole. framecheck then fails one cut by+ the frame edge, as it does for 2D type, and holds subtitle cues to their reading time.+- **gate**, five steps on a 3D film. DETERMINISM (the same sampled frames drawn cold and forward, then+ warm and reversed, identical) catches state carried between frames. CONTRACT catches a clock or the network.+ DEAD AIR catches stillness; declare a meant hold in `meta.holds` with its reason. ARTIFACT+ catches a player that can reach the network. **3D CHECKS** runs `checks3d` inside the page on+ about 48 sampled frames plus every frame of each grip's contact window, and fails on any finding:+ a gap or an open hand on a held prop, a prop through a hand or the holder's body, a hand off+ screen while its prop is on, a grip hidden from the lens, two rigs clipping, a walk through a+ closed prop, a label covered, a contact beat under its pixel size. For that, each draw starts with+ `resetChecks()`, registers what it holds (`registerRig`, `registerGrip`, `registerSize`,+ `registerLabel`, `registerPath`) and ends with `if (checking()) runChecks(f, camera, env)`+ (`threeRigDemo.ts`). A film that registers nothing gets a note, not a pass.+- **Rerun the whole check pass after every batch of shot changes.** A new jar swing broke a catch+ that had been clean, and only the re-run found it. A green gate with a prop through a hand is a+ failed gate, so look at the crops too.++## Rendering++- **Default: SwiftShader**, a CPU WebGL that draws the same pixels on any machine. About 1 s a+ 1080p frame at `ss: 2` with soft shadows. `render.mjs` then prints its 150 ms draw budget as OVER;+ that line is information, not a failure.+- **`ANIDOODLE_GL=gpu`** uses the machine's GPU (Metal on a Mac), about 12x faster. Its hashes+ hold only on the same machine and driver, so iterate and render long films with it, and say which+ backend a published hash came from. Any tool takes it:+ `ANIDOODLE_GL=gpu node tools/render.mjs <film>`.+- A lost WebGL context throws in `draw3d` instead of writing a broken frame; re-render in a fresh page.+- Grain changes every pixel every frame and defeats compression (69 MB for 8 s at the demo's+ amount). Keep `grain` around 0.03 for long films.+- Only pages whose bundle carries the 3D marker get WebGL flags, so 2D films keep the browser+ they always had.diff --git a/plugins/anidoodle/skills/anidoodle/references/working-method.md b/plugins/anidoodle/skills/anidoodle/references/working-method.mdindex 87e81df..17171c6 100644--- a/plugins/anidoodle/skills/anidoodle/references/working-method.md+++ b/plugins/anidoodle/skills/anidoodle/references/working-method.md@@ -82,5 +82,13 @@ None of that was drawing. These habits cut it by an order of magnitude:prints it and keeps failing, so the decision stays visible. If the owner accepts it as shipped,it becomes a hold with that reason as its third field (`[from, to, "approved as shipped: ..."]`),which the gate prints and passes (`launch3.ts`).+- **Dense strips around a seam** come from `still.mjs --frames 840-880:2 --sheet out/seam.jpg`, never a+ hand-written ffmpeg tiling script.+- **A film beside its own files.** `scaffold.mjs <dir> --linked --film promo [--world]` makes a project+ that USES the installed engine (its film, host page, brand files and photos live in the project), so+ no film needs a copy of the engine, and every tool (`music.mjs check`, `ship.mjs`) finds it.+- **A photo that has not arrived yet.** `ANIDOODLE_PLACEHOLDERS=1` draws a labelled grey box for a+ missing image asset and lists it in `meta.placeholders`; `verify-export --delivery` and `ship` refuse+ a file that still has one. Never drop a stand-in photo in under the real name.- **`npm test`** (in `engine/`) runs the unit suites in `engine/test/*.test.ts` without abrowser (camera moves today). Run it with the gate after any engine change.