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
SKILL.md: music line composes, never presets; resync mirror
Alex Greenshpun65042bd9fbd1
diff --git a/plugins/anidoodle/skills/anidoodle/SKILL.md b/plugins/anidoodle/skills/anidoodle/SKILL.mdindex 6a2b937..57fa00d 100644--- a/plugins/anidoodle/skills/anidoodle/SKILL.md+++ b/plugins/anidoodle/skills/anidoodle/SKILL.md@@ -35,13 +35,17 @@ say why in one line. Write the answers into a short brief before drawing.| 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` || An explainer or an infographic | `references/workflows/explainer.md` |-| A launch or product video (their screenshots welcome) | `references/workflows/launch-video.md` |+| A launch or product video (their screenshots welcome) | `references/workflows/launch-video.md`; build it on `references/workflows/launch-video-kit.md` || An interactive web animation that reacts to the UI | `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` |+- Music: pick a style vocabulary and mood, compose your own harmony, motif and form (references/music/compose.md), then node tools/music.mjs check <score.ts#export> 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.+- Launch films: `launchTemplate.ts` renders a product's launch from data: prompts, plates drawn for it, a score composed for it, words, install lines; habits that save tokens are in `references/working-method.md`.+## The seven laws1. **Every piece has a point.** A still: one idea, one focal subject, one light. A film: one@@ -74,7 +78,7 @@ on the moving file.****Film.** (1) **The story in three sentences** (setup, transformation, payoff) and the token; forlonger films, a spine plus one line per chapter. If you cannot write it, stop. (2) **The grid**:-at 120 bpm and 30 fps a beat is 15 frames; one cue table holds every frame number and a checker+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) **Review once** from the@@ -119,6 +123,7 @@ node tools/emit.mjs intro --out out/intro.html # one self-co| `docs-check.mjs` | fails when any doc's style count, length or path disagrees with the code || `verify-export.mjs` | opt-in QA on the rendered file: frame count, duration, first-frame colour, loop seam || `music.mjs` | renders and meters a score (loudness, range, onsets, brightness) |+| `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`diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch2.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch2.tsindex ca7cda9..ede7a6e 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch2.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch2.ts@@ -10,8 +10,8 @@import type { Ctx, Env, P } from "./core";import type { Film } from "./film";import {- C, GEN, HOME, INPUT, MONO, REPLY, SANS, TEXT, blot, camLerp, caretAt, clamp, drawChatFrame, expo, inOut, lerp, lerpP,- out3, pathOf, plateLayer, pointer, press, ramp, rr, selfLayer, softShadow, useCam, type Cam,+ C, GEN, HOME, INPUT, MONO, REPLY, SANS, TEXT, blot, camLerp, caretAt, charTimes, clamp, drawChatFrame, expo, inkDrop, inOut, lerp, lerpP,+ out3, pathOf, plateLayer, pointer, press, ramp, rr, selfLayer, softShadow, typedAt, useCam, type Cam,} from "./launchKit";import { koiDraw } from "./koiDraw";import { koi } from "./koi";@@ -36,8 +36,6 @@ export const T2 = {const N = T2.end[1];// ---------------------------------------------------------------- small helpers-const charTimes = (text: string, t0: number, rate: number, seed: number) => { const out: number[] = []; let t = t0; for (let i = 0; i < text.length; i++) { const h = Math.sin((i + 1) * 12.9898 + seed * 78.233) * 43758.5453, j = h - Math.floor(h); t += rate * (0.55 + j * 0.9) + (text[i] === " " ? 0.6 * rate : 0); out.push(t); } return out; };-const typedAt = (text: string, f: number, times: number[]) => text.slice(0, times.filter((t) => f >= t).length);const screen = (ctx: Ctx, env: Env) => ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);const GEN_C: P = [GEN.x + GEN.w / 2, GEN.y + GEN.h / 2];// a whip: the outgoing frame smeared along the move (drawn several times, fading), the incoming following it in@@ -100,13 +98,7 @@ const drawCard = (ctx: Ctx, env: Env, it: Extract<Item, { kind: "card" }>, x: nuctx.restore(); ctx.restore();};// the drop in flight from Generate to where the new card will land-const drawDrop = (ctx: Ctx, f: number, d: { t0: number; land: number }, to: P) => {- 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 = C.ink; ctx.beginPath(); ctx.arc(GEN_C[0], GEN.y + 6 - w * 22, 30 * (0.3 + 0.7 * w), 0, Math.PI * 2); ctx.fill(); return; }- const at = (g: number): P => { const u = ramp(g, d.t0, d.land), e = inOut(u); return [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16, to[1], e) - Math.sin(Math.PI * u) * 150]; };- for (let k = 24; k >= 0; k--) { const p = at(f - k * 0.1); ctx.fillStyle = C.ink; ctx.globalAlpha = k === 0 ? 1 : 0.22 * (1 - k / 25); ctx.beginPath(); ctx.arc(p[0], p[1], 30 * (1 - k * 0.022), 0, Math.PI * 2); ctx.fill(); }- ctx.globalAlpha = 1;-};+const drawDrop = (ctx: Ctx, f: number, d: { t0: number; land: number }, to: P) => inkDrop(ctx, f, d, to);type ChatO = { typed: string; caret: boolean; press: number; hot: number; flip?: number; hideCard?: number };const drawChat = (ctx: Ctx, env: Env, f: number, o: ChatO) => {drawChatFrame(ctx, { typed: o.typed, caret: o.caret, placeholder: "Describe what you want drawn…", genPress: o.press, genHot: o.hot });diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch3.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch3.tsindex 25ac91e..f2ed02c 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch3.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launch3.ts@@ -5,18 +5,17 @@// off to reveal the next scene. (Chosen: the ink bloom, and every word in ink.) 29 bars of the score (launchLofi3), 77 s.import type { Ctx, Env } from "./core";import type { Film } from "./film";-import { C, blot, expo, pathOf, ramp, selfLayer } from "./launchKit";+import { C } from "./launchKit";import { content2, SFX2, T2, WEB_SKIP } from "./launch2";-import { logoBug, measure, writeOn, type KStyle } from "./kinetic";+import { logoBug } from "./kinetic";+import { beatGrid, makeCut, pic, type, typeFrame, type Seg, type TypeSeg } from "./launchCut";import { launchLofi3 } from "./music/pieces/launch";import { renderPiece } from "./music/render";import { rng } from "./core";const W = 1920, H = 1080, FPS = 30;-type Line = { text: string; style: KStyle; color: string };-type Seg = { kind: "pic"; from: number; to: number; len: number } | { kind: "type"; lines: Line[]; len: number; before: number; after: number };-const pic = (from: number, to: number, len = to - from): Seg => ({ kind: "pic", from, to, len });-const type = (lines: Line[], len: number, before: number, after = before): Seg => ({ kind: "type", lines, len, before, after });+// The cut is data (launchCut.ts): pic(from, to, len) plays a span of content2, type(...) is a full-frame+// word page. Re-timing the film is an edit to HEAD, never to scene code.// Alex on cut 3: gentler pacing; ANIMATIONS before the swim request; the koi-and-code beat much// shorter; the embroidery long enough to see; the site from Bit's hero on. The film beat's length is// solved so "All in pure code." (content T2.words[0] + 140) lands on bar 26, the score's home chord.@@ -38,35 +37,21 @@ const HEAD: Seg[] = [pic(WEB_FROM, WEB_FROM + WEB_LEN),type([{ text: "FILMS", style: "ink", color: C.ink }], 60, WEB_FROM + WEB_LEN - 1, T2.film[0]),];-const headLen = HEAD.reduce((a, s) => a + s.len, 0), CLAIM = 26 * 80, FILM_LEN = CLAIM - 140 - headLen;-if (FILM_LEN < 90) throw new Error(`launch3: the film beat would be ${FILM_LEN} frames; the cut before it is too long for the claim to land on bar 26`);+// the claim lands on bar 26 (the score's home chord): the film beat takes whatever is left+const headLen = HEAD.reduce((a, s) => a + s.len, 0), FILM_LEN = beatGrid(90, FPS).solve(26, 140 + headLen, 90);const SEGS: Seg[] = [...HEAD, pic(T2.film[0], T2.film[1], FILM_LEN), pic(T2.words[0], T2.words[1]), pic(T2.end[0], T2.end[1]), pic(T2.end[1] - 1, T2.end[1], 60)];-const STARTS = (() => { let t = 0; return SEGS.map((s) => { const a = t; t += s.len; return a; }); })();-export const N3 = STARTS[STARTS.length - 1] + SEGS[SEGS.length - 1].len;-const at = (F: number) => { let i = SEGS.length - 1; while (i > 0 && STARTS[i] > F) i--; return { s: SEGS[i], local: F - STARTS[i] }; };-const contentOf = (s: Extract<Seg, { kind: "pic" }>, local: number) => s.from + ((s.to - s.from) * local) / s.len;+const CUT = makeCut(SEGS), { STARTS, at, contentOf } = CUT;+export const N3 = CUT.N;// a content frame, mapped to the cut (for the sound events); events inside a cut-away go to its start-export const cutOf = (c: number) => { for (let i = 0; i < SEGS.length; i++) { const s = SEGS[i]; if (s.kind === "pic" && c >= s.from && c < s.to) return STARTS[i] + ((c - s.from) * s.len) / (s.to - s.from); } return -1; };+export const cutOf = CUT.cutOf;// ---------------------------------------------------------------- a type frameconst IN = 14, OUT = 14; // gentle: the bloom opens and closes over half a second// Alex's pick: B, the ink bloom. The Generate drop's own ink blooms from the centre over the picture,// the page is inside the bloom, the word is written on it in ink by the pointed pen, and the ink// shrinks back to a point to show the next scene.-const drawType = (ctx: Ctx, env: Env, s: Extract<Seg, { kind: "type" }>, local: number, F: number) => {- const u = expo(ramp(local, 0, IN + 2)), v = expo(ramp(local, s.len - OUT, s.len)), R = 1250 * (v > 0 ? 1 - v : u);- content2(ctx, env, local < s.len / 2 ? s.before : s.after);- if (R < 2) return;- const L = selfLayer(env, "sheet", Math.round(W * env.scale), Math.round(H * env.scale)), c = L.ctx;- c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = C.bg; c.fillRect(0, 0, W, H);- const n = s.lines.length, size = Math.min(n === 1 ? 190 : 130, ...s.lines.map((l) => (1560 / measure(l.text, 100)) * 100)), gap = size * 1.45, y0 = H / 2 - ((n - 1) * gap) / 2 + size * 0.5;- s.lines.forEach((l, i) => writeOn(c, env, l.text, W / 2, y0 + i * gap, size, ramp(local, IN - 2 + i * 20, IN + 16 + i * 20), l.style, { color: l.color, align: "center", seed: 7 + i }));- logoBug(c, env, F, 1700, 1040, 0.9, { t0: -100, fps: FPS });- const ctr: [number, number] = [W / 2, H / 2];- ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.save();- pathOf(ctx, blot(ctr, R + 26, 88)); ctx.fillStyle = C.ink; ctx.fill(); pathOf(ctx, blot(ctr, Math.max(0, R - 4), 88)); ctx.clip();- ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(L.canvas, 0, 0); ctx.restore();-};+const drawType = (ctx: Ctx, env: Env, s: TypeSeg, local: number, F: number) =>+ typeFrame(ctx, env, s.lines, local, s.len, (first) => content2(ctx, env, first ? s.before : s.after), (c) => logoBug(c, env, F, 1700, 1040, 0.9, { t0: -100, fps: FPS }), { inF: IN, outF: OUT });// ---------------------------------------------------------------- the soundconst audio3 = (sr: number): [Float32Array, Float32Array] => {diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCut.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCut.tsnew file mode 100644index 0000000..ad01e07--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchCut.ts@@ -0,0 +1,89 @@+// LAUNCH CUT. A launch film is two things: the CONTENT (a continuous timeline of pictures, the chat,+// the plates) and the CUT, a list of data segments that picks spans of that content, re-times them,+// and splices full-frame TYPE FRAMES between them. Re-timing a film is then an edit to a list, never+// to scene code. launch3.ts is the worked example; launchTemplate.ts builds your own film on it.+//+// const cut = makeCut([pic(0, 200), type(lines, 64, 199, 200), pic(200, 360, 90), ...]);+// cut.N the cut's length in frames+// cut.at(F) which segment frame F is in, and the local frame inside it+// cut.contentOf(s,l) the content frame a picture segment shows at local frame l+// cut.cutOf(c) where content frame c lands in the cut (for sound events), -1 if cut away+//+// Type frames are an ink bloom: ink opens from the centre over the picture, a page is inside the+// bloom, the words letter themselves on it, and the ink closes to a point on the next picture.+// Words never sit over the art.+import type { Ctx, Env, P } from "./core";+import { C, blot, expo, pathOf, ramp, selfLayer } from "./launchKit";+import { measure, writeOn, type KStyle } from "./kinetic";++export type TypeLine = { text: string; style: KStyle; color: string };+export type PicSeg = { kind: "pic"; from: number; to: number; len: number };+export type TypeSeg = { kind: "type"; lines: TypeLine[]; len: number; before: number; after: number };+export type Seg = PicSeg | TypeSeg;+// a span of content [from, to) played over `len` frames (len < to - from plays it faster)+export const pic = (from: number, to: number, len = to - from): Seg => ({ kind: "pic", from, to, len });+// a type frame of `len` frames; the bloom opens over content frame `before`, closes onto `after`+export const type = (lines: TypeLine[], len: number, before: number, after = before): Seg => ({ kind: "type", lines, len, before, after });++export const makeCut = (SEGS: Seg[]) => {+ const STARTS = (() => { let t = 0; return SEGS.map((s) => { const a = t; t += s.len; return a; }); })();+ const N = STARTS[STARTS.length - 1] + SEGS[SEGS.length - 1].len;+ const at = (F: number) => { let i = SEGS.length - 1; while (i > 0 && STARTS[i] > F) i--; return { s: SEGS[i], local: F - STARTS[i] }; };+ const contentOf = (s: PicSeg, local: number) => s.from + ((s.to - s.from) * local) / s.len;+ const cutOf = (c: number) => { for (let i = 0; i < SEGS.length; i++) { const s = SEGS[i]; if (s.kind === "pic" && c >= s.from && c < s.to) return STARTS[i] + ((c - s.from) * s.len) / (s.to - s.from); } return -1; };+ return { SEGS, STARTS, N, at, contentOf, cutOf };+};++// The beat grid: at `bpm` and `fps`, how many frames a beat and a bar (4 beats) last. Cut on+// downbeats (bar starts), land the claim on a chosen bar, and solve one flexible segment's length+// so it does: `solve(bar, fixedFrames)` = frames left for the flexible segment, or throw.+export const beatGrid = (bpm: number, fps: number) => {+ const beat = (60 / bpm) * fps, bar = beat * 4;+ return {+ beat, bar,+ frameOf: (barNo: number, beatNo = 0) => Math.round(barNo * bar + beatNo * beat),+ solve: (barNo: number, fixed: number, min = 60) => {+ const left = Math.round(barNo * bar) - fixed;+ if (left < min) throw new Error(`beatGrid: only ${left} frames left to land on bar ${barNo}; shorten the cut before it or pick a later bar`);+ return left;+ },+ };+};++// ---------------------------------------------------------------- the bloom+export type BloomOpts = { inF?: number; outF?: number; close?: boolean; radius?: number; seed?: number; bg?: string; ink?: string; W?: number; H?: 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));+ 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);+ 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;+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.fillStyle = o.bg ?? C.bg; c.fillRect(0, 0, W, H);+ page(c);+ const ctr: P = [W / 2, H / 2], seed = o.seed ?? 88;+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); ctx.save();+ pathOf(ctx, blot(ctr, R + 26, seed)); ctx.fillStyle = o.ink ?? C.ink; ctx.fill(); pathOf(ctx, blot(ctr, Math.max(0, R - 4), seed)); ctx.clip();+ ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(L.canvas, 0, 0); ctx.restore();+};++// A type frame: one to three lines, each written on by its own tool, 20 frames apart, sized to fit.+// `bug` draws a corner brand mark on the page (the logo recurs on every frame of the film).+// `lead`: when the first line starts, relative to the bloom being open (default -2); `stagger`: frames+// between lines (default 20); a line takes 18 frames to write.+export type TypeOpts = BloomOpts & { maxW?: number; lead?: number; stagger?: number };+export const typeFrame = (ctx: Ctx, env: Env, lines: TypeLine[], local: number, len: number, under: (first: boolean) => void, bug?: (c: Ctx) => void, o: TypeOpts = {}) => {+ const IN = o.inF ?? 14, W = o.W ?? 1920, H = o.H ?? 1080, maxW = o.maxW ?? 1560, lead = o.lead ?? -2, st = o.stagger ?? 20;+ bloomFrame(ctx, env, local, len, under, (c) => {+ const n = lines.length, size = Math.min(n === 1 ? 190 : 130, ...lines.map((l) => (maxW / measure(l.text, 100)) * 100)), gap = size * 1.45, y0 = H / 2 - ((n - 1) * gap) / 2 + size * 0.5;+ lines.forEach((l, i) => writeOn(c, env, l.text, W / 2, y0 + i * gap, size, ramp(local, IN + lead + i * st, IN + lead + 18 + i * st), l.style, { color: l.color, align: "center", seed: 7 + i }));+ bug?.(c);+ }, o);+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExample.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExample.tsnew file mode 100644index 0000000..8921124--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchExample.ts@@ -0,0 +1,28 @@+// 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+import { C } from "./launchKit";+import { makeLaunchFilm } from "./launchTemplate";+import { lighthouseDraw } from "./lighthouseDraw";+import { foxDraw } from "./foxDraw";++export const launchExample = makeLaunchFilm({+ title: "Your Product",+ subtitle: "the one line it lives by",+ placeholder: "Ask for anything…",+ asks: [+ { prompt: "a lighthouse at sunset, as a print", plate: lighthouseDraw, label: "print · drawn in code" },+ { prompt: "now a fox at dusk", plate: foxDraw, label: "a second answer, same thread" },+ ],+ words: [[{ text: "IDEA IN.", style: "ink", color: C.ink }, { text: "ART OUT.", style: "ink", color: C.accent }]],+ 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+});diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.tsindex da01741..d9c2a4b 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchKit.ts@@ -122,6 +122,8 @@ export type ChatState = {attach?: { img: CanvasImageSource; label: string } | null;genPress?: number; genHot?: number; // the button: press depth 0..1, hover glow 0..1label?: string; labelAlpha?: number; // the reply's byline+ // your product: the thread's name and subline, the button's word, the accent (defaults: anidoodle's own)+ title?: string; subtitle?: string; genLabel?: string; accent?: string;};export const drawChatFrame = (ctx: Ctx, s: ChatState) => {@@ -130,8 +132,9 @@ export const drawChatFrame = (ctx: Ctx, s: ChatState) => {ctx.fillStyle = C.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 elsectx.fillStyle = C.ink; ctx.beginPath(); ctx.arc(CHAT.x + 58, CHAT.y + 52, 9, 0, Math.PI * 2); ctx.fill();- ctx.font = SANS(600, 22); ctx.fillStyle = C.ink; ctx.textBaseline = "middle"; ctx.fillText("anidoodle", CHAT.x + 80, CHAT.y + 53);- ctx.font = SANS(500, 18); ctx.fillStyle = C.mute; ctx.fillText("drawn in code", CHAT.x + 196, CHAT.y + 54);+ ctx.font = SANS(600, 22); ctx.fillStyle = C.ink; ctx.textBaseline = "middle"; ctx.fillText(s.title ?? "anidoodle", CHAT.x + 80, CHAT.y + 53);+ const subX = s.title === undefined ? CHAT.x + 196 : CHAT.x + 80 + ctx.measureText(s.title).width + 16;+ ctx.font = SANS(500, 18); ctx.fillStyle = C.mute; ctx.fillText(s.subtitle ?? "drawn in code", subX, CHAT.y + 54);ctx.fillStyle = C.line; ctx.fillRect(CHAT.x + 32, CHAT.y + 98, CHAT.w - 64, 1.5);// the sent message, right alignedif (s.sent) {@@ -150,15 +153,17 @@ export const drawChatFrame = (ctx: Ctx, s: ChatState) => {ctx.font = SANS(500, TEXT.px); ctx.textBaseline = "alphabetic";if (!s.typed && s.placeholder) { ctx.fillStyle = C.mute; ctx.fillText(s.placeholder, TEXT.x, TEXT.base); }ctx.fillStyle = C.ink; ctx.fillText(s.typed, TEXT.x, TEXT.base);- if (s.caret) { const x = TEXT.x + ctx.measureText(s.typed).width + 3; ctx.fillStyle = C.accent; ctx.fillRect(x, TEXT.base - 32, 3, 40); }+ const acc = s.accent ?? C.accent;+ if (s.caret) { const x = TEXT.x + ctx.measureText(s.typed).width + 3; ctx.fillStyle = acc; ctx.fillRect(x, TEXT.base - 32, 3, 40); }// Generateconst pr = s.genPress ?? 0, hot = s.genHot ?? 0, k = 1 - 0.07 * pr, gx = GEN.x + (GEN.w * (1 - k)) / 2, gy = GEN.y + (GEN.h * (1 - k)) / 2;- ctx.fillStyle = hot > 0 ? mixHex(C.accent, C.accentDeep, 0.35 * hot + 0.4 * pr) : C.accent; rr(ctx, gx, gy, GEN.w * k, GEN.h * k, GEN.r * k); ctx.fill();- ctx.fillStyle = "#fff"; ctx.font = SANS(600, 24 * k); ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.fillText("Generate", GEN.x + GEN.w / 2, GEN.y + GEN.h / 2 + 1); ctx.textAlign = "left";+ ctx.fillStyle = hot > 0 ? mixHex(acc, s.accent ? deepen(acc) : C.accentDeep, 0.35 * hot + 0.4 * pr) : acc; rr(ctx, gx, gy, GEN.w * k, GEN.h * k, GEN.r * k); ctx.fill();+ ctx.fillStyle = "#fff"; ctx.font = SANS(600, 24 * k); ctx.textBaseline = "middle"; ctx.textAlign = "center"; ctx.fillText(s.genLabel ?? "Generate", GEN.x + GEN.w / 2, GEN.y + GEN.h / 2 + 1); ctx.textAlign = "left";};export const caretAt = (ctx: Ctx, typed: string): P => { ctx.font = SANS(500, TEXT.px); return [TEXT.x + ctx.measureText(typed).width, TEXT.base - 12]; };const hx = (h: string) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));+const deepen = (h: string) => "#" + hx(h).map((v) => Math.round(v * 0.78).toString(16).padStart(2, "0")).join("");export const mixHex = (a: string, b: string, t: number) => { const x = hx(a), y = hx(b); return `rgb(${x.map((v, i) => Math.round(lerp(v, y[i], clamp(t)))).join(",")})`; };// the art card: paper, a hairline, and whatever layer is inside, clipped to the rounded square@@ -169,3 +174,31 @@ export const artCard = (ctx: Ctx, x: number, y: number, s: number, L: Layer | nuctx.restore();ctx.lineWidth = 1.5; ctx.strokeStyle = "rgba(0,0,0,0.08)"; rr(ctx, x, y, s, s, r); ctx.stroke();};++// ---------------------------------------------------------------- typing, the drop, the answer card+// Human typing: the time each character lands, uneven and seeded, spaces a little slower.+export const charTimes = (text: string, t0: number, rate: number, seed: number) => { const out: number[] = []; let t = t0; for (let i = 0; i < text.length; i++) { const h = Math.sin((i + 1) * 12.9898 + seed * 78.233) * 43758.5453, j = h - Math.floor(h); t += rate * (0.55 + j * 0.9) + (text[i] === " " ? 0.6 * rate : 0); out.push(t); } return out; };+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 };+export const inkDrop = (ctx: Ctx, f: number, d: { t0: number; land: number }, to: P) => {+ const 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 = C.ink; ctx.beginPath(); ctx.arc(GEN_C[0], GEN.y + 6 - w * 22, 30 * (0.3 + 0.7 * w), 0, Math.PI * 2); ctx.fill(); return; }+ const at = (g: number): P => { const u = ramp(g, d.t0, d.land), e = inOut(u); return [lerp(GEN_C[0], to[0], e), lerp(GEN.y - 16, to[1], e) - Math.sin(Math.PI * u) * 150]; };+ for (let k = 24; k >= 0; k--) { const p = at(f - k * 0.1); ctx.fillStyle = C.ink; ctx.globalAlpha = k === 0 ? 1 : 0.22 * (1 - k / 25); ctx.beginPath(); ctx.arc(p[0], p[1], 30 * (1 - k * 0.022), 0, Math.PI * 2); ctx.fill(); }+ ctx.globalAlpha = 1;+};+// 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.+export const inkCard = (ctx: Ctx, x: number, y: number, s: number, f: number, d: Drop, art: Layer, label: string, crop?: [number, number, number, number]) => {+ ctx.fillStyle = C.ink; ctx.globalAlpha = ramp(f, d.land, d.land + 10); ctx.beginPath(); ctx.arc(x + 9, y - 16, 7, 0, Math.PI * 2); ctx.fill();+ ctx.font = SANS(600, 20); ctx.textBaseline = "middle"; ctx.fillText(label, x + 26, y - 15); ctx.globalAlpha = 1;+ const grow = out3(ramp(f, d.land, d.full)), c: P = [x + s / 2, y + s / 2];+ softShadow(ctx, x, y, s, s, 20, grow * 1.3);+ ctx.save(); rr(ctx, x, y, s, s, 20); ctx.clip();+ if (grow < 1) { pathOf(ctx, blot(c, lerp(16, s * 0.8, grow) + 28 * (1 - grow), 77)); ctx.fillStyle = C.ink; ctx.fill(); pathOf(ctx, blot(c, Math.max(0, lerp(16, s * 0.8, grow) - 5), 77)); ctx.clip(); }+ ctx.fillStyle = C.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();+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.tsnew file mode 100644index 0000000..04f2bad--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchTemplate.ts@@ -0,0 +1,220 @@+// LAUNCH TEMPLATE. Your product's launch film from data: a product name, the prompts a user would+// type, the plates that answer them, the words for the type frames, and the exact install lines.+// It is the launch film's grammar (references/workflows/launch-video-kit.md) with nothing of+// anidoodle's own left in it:+//+// ask: the prompt is already being typed at frame 0 (a silent-readable hook), the camera eases+// out from the composer, the pointer presses Generate, an ink drop arcs into the thread and+// blooms open into a card where the plate draws itself, live. Earlier answers stay and the+// thread scrolls. The camera then leans in on the new card.+// type: a full-frame word page inside an ink bloom (launchCut.ts). Words never sit on the art.+// end: the bloom opens onto the end card and stays: the name written on, one line, the install+// lines in a dark panel, held for `endBeats` (3 s or more).+//+// Everything is timed on a beat grid (bpm from the brief, fps). With `claimBar`, the last ask's length is solved so+// the end card lands on that bar's downbeat, or the build throws.+//+// export const myLaunch = makeLaunchFilm({ title: "Tally", asks: [...], words: [...], ... });+// (then a host page, src/hosts/page-myLaunch.ts, and: node tools/render.mjs myLaunch)+import type { Ctx, Env, P } from "./core";+import type { Film } from "./film";+import {+ C, GEN, HOME, INPUT, REPLY, SANS, MONO, TEXT, camLerp, caretAt, charTimes, clamp, drawChatFrame, expo, inOut, inkCard, inkDrop,+ lerp, lerpP, out3, plateLayer, pointer, press, ramp, rr, typedAt, useCam, type Cam, type Drop,+} from "./launchKit";+import { beatGrid, bloomFrame, bloomRadius, makeCut, pic, type, typeFrame, type Seg, type TypeLine } from "./launchCut";+import { measure, writeOn } from "./kinetic";+import { renderPiece } from "./music/render";+import { loudness, truePeak } from "./music/meter";+import * as families from "./music/pieces/families";+import * as launchPieces from "./music/pieces/launch";+import * as nocturnePieces from "./music/pieces/nocturne";+import * as samplers from "./music/pieces/samplers";+import type { Piece } from "./music/plan";++export type LaunchAsk = {+ prompt: string; // what the user types, in their words+ plate: Film; // the answer: any film of this engine, drawn live into the card+ label: string; // the card's byline ("marker comic", "your dashboard, redrawn")+ from?: number; to?: number; // the plate frames to play while the card is up (default: all of it)+ crop?: [number, number, number, number]; // a source rectangle of the plate, in plate pixels at 1080 across+};+export type LaunchSpec = {+ title: string; // the product name: the thread's name, the end card, the corner mark+ subtitle?: string; // the thread's subline+ placeholder?: string; // the empty composer+ genLabel?: string; // the button's word (default "Generate")+ accent?: string; // the button and caret colour, hex+ asks: LaunchAsk[]; // 1 to 3 prompt-to-result beats+ words?: TypeLine[][]; // words[i] is a type frame after asks[i], for i < asks.length - 1+ tagline: string; // the one line under the name on the end card+ install: string[]; // the exact lines a viewer copies; held on screen for the whole end card+ footer?: string; // small print under the panel (where it runs, the repo)+ bpm: number; fps?: number; // the beat grid: bpm comes from the brief (the score composed for it); a beat is 60 * fps / bpm frames+ askBeats?: number; typeBeats?: number; endBeats?: number; // default 6, 4, 8+ claimBar?: number; // land the end card on this bar's downbeat (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+ // refused: every user's film gets its own music, never ours.+ score: (() => Piece) | null;+ audio?: Film["audio"]; // or your own finished mix; wins over score+};++const W = 1920, H = 1080;+// anidoodle's own pieces (the demos and our launch score) are examples of the composer, never a+// user's soundtrack. Refused by identity and by title, so a thin wrapper does not slip through.+const OURS: (() => Piece)[] = [...Object.values(families), ...Object.values(launchPieces), ...Object.values(nocturnePieces), ...Object.values(samplers)].filter((v): v is () => Piece => typeof v === "function");+const refuseOurs = (score: () => Piece) => {+ const ours = () => new Set(OURS.map((f) => { try { return f().title; } catch { return null; } }).filter(Boolean));+ if (OURS.includes(score) || ours().has(score().title)) throw new Error(`launchTemplate: "${score().title}" is one of anidoodle's own pieces; 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 TOP = 170, VIEW_BOTTOM = INPUT.y - 26, BUBBLE = 58, CARD = 460;+const GEN_C: P = [GEN.x + GEN.w / 2, GEN.y + GEN.h / 2];++// the timing inside one ask beat, from its prompt and its length+const askTiming = (prompt: string, i: number, ASK: number) => {+ const raw = charTimes(prompt, 0, 1, 7 + i * 4), last = raw[raw.length - 1] || 1;+ const b = Math.round(ASK * 0.25), a = i === 0 ? -Math.round(b * 1.2) : 4; // the first prompt is under way at frame 0+ const 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 };+ return { times, b, down, up, drop };+};++export const makeLaunchFilm = (spec: LaunchSpec): Film & { cut: ReturnType<typeof makeCut> } => {+ const fps = spec.fps ?? 30, n = spec.asks.length;+ 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 (spec.score) refuseOurs(spec.score);+ const grid = beatGrid(spec.bpm, fps);+ const ASK = Math.round((spec.askBeats ?? 6) * grid.beat), TYPE = Math.round((spec.typeBeats ?? 4) * grid.beat), END = Math.round((spec.endBeats ?? 8) * grid.beat);+ if (n < 1 || n > 3) throw new Error("launchTemplate: 1 to 3 asks; more is a feature list, not a story");+ if (ASK < 100) throw new Error(`launchTemplate: an ask beat needs 100 frames or more (it has ${ASK}); raise askBeats`);+ if (END < 3 * fps + 40) throw new Error("launchTemplate: the end card must hold the install lines 3 s or more; raise endBeats");+ const T = spec.asks.map((a, i) => ({ ...askTiming(a.prompt, i, ASK), base: i * ASK }));+ const END0 = n * ASK; // content frame where the end card starts++ // ---------------------------------------------------------------- the thread+ type Item = { at: number; h: number; user?: string; card?: number };+ const items: Item[] = [];+ T.forEach((t, i) => { items.push({ at: t.base + t.up, h: BUBBLE, user: spec.asks[i].prompt }); items.push({ at: t.base + t.drop.land, h: CARD + 34, card: i }); });+ const ys = (() => { let y = TOP; return items.map((it) => { const r = y; y += it.h + 26; 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; };+ const cardY = (i: number, f: number) => ys[items.findIndex((it) => it.card === i)] + 34 - scrollAt(f);+ const plateFrame = (i: number, f: number) => { const a = spec.asks[i], 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 + ASK - 8)); };++ const bug = (c: Ctx, env: Env) => writeOn(c, env, spec.title, W - 40, H - 34, 24, 1, "ink", { color: C.soft, align: "right", seed: 3 });+ const chat = (ctx: Ctx, env: Env, f: number, typed: string, caret: boolean, pr: number, hot: number) => {+ 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: spec.accent });+ const sc = scrollAt(f);+ ctx.save(); ctx.beginPath(); ctx.rect(300, 158, 1320, VIEW_BOTTOM - 158); ctx.clip();+ items.forEach((it, k) => {+ if (f < it.at) return;+ const y = ys[k] - sc; if (y > VIEW_BOTTOM || y + it.h < 100) return;+ if (it.user !== undefined) {+ ctx.globalAlpha = ramp(f, it.at, it.at + 8); ctx.font = SANS(500, 26);+ const bw = ctx.measureText(it.user).width + 52; ctx.fillStyle = C.chip; rr(ctx, 1560 - bw, y, bw, BUBBLE - 2, 22); ctx.fill();+ ctx.fillStyle = C.ink; ctx.textBaseline = "middle"; ctx.fillText(it.user, 1560 - bw + 26, y + 29); ctx.globalAlpha = 1;+ } else {+ const i = it.card!, a = spec.asks[i];+ const d = T[i].drop, b = T[i].base;+ inkCard(ctx, REPLY.x, y + 34, 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);+ }+ });+ ctx.restore();+ T.forEach((t, i) => inkDrop(ctx, f, { t0: t.base + t.drop.t0, land: t.base + t.drop.land }, [REPLY.x + CARD / 2, cardY(i, t.base + t.drop.land) + CARD / 2]));+ };+ // the camera: macro on the composer while typing, out to the room for the press, then a lean in on the new card+ const leanOn = (i: number): Cam => ({ c: lerpP(HOME.c, [REPLY.x + CARD / 2, cardY(i, T[i].base + ASK) + CARD / 2], 0.55), z: 1.18 });+ // `lean` (0..1) is how far the camera leans in; the corner mark steps aside while it does, since+ // the lean carries the composer under the corner and type never sits over the UI or the art+ const camAt = (ctx: Ctx, f: number, i: number): { cam: Cam; lean: number } => {+ const t = T[i], l = f - t.base, typed = typedAt(spec.asks[i].prompt, l, t.times), [cx] = caretAt(ctx, typed);+ // the macro creeps in while the words arrive: the frame is never a still+ const macro: Cam = { c: [Math.max(TEXT.x + 330, cx - 110), 934], z: 2.4 + 0.25 * inOut(ramp(l, t.times[0] - 8, t.b)) };+ if (i > 0 && l < 16) { const k = inOut(ramp(l, 0, 16)); return { cam: camLerp(leanOn(i - 1), macro, k), lean: 1 - k }; }+ if (l > t.drop.full - 10) { const k = inOut(ramp(l, t.drop.full - 10, ASK)); return { cam: camLerp(HOME, leanOn(i), k), lean: k }; }+ return { cam: l < t.b - 4 ? macro : camLerp(macro, HOME, expo(ramp(l, t.b - 4, t.down))), lean: 0 };+ };+ const askScene = (ctx: Ctx, env: Env, f: number) => {+ const i = Math.min(n - 1, Math.floor(f / ASK)), t = T[i], l = f - t.base;+ const { cam, lean } = camAt(ctx, f, i);+ useCam(ctx, env, cam);+ const typed = typedAt(spec.asks[i].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));+ // the pointer comes in for the press and glides back out; it never pops+ const off: P = [1780, 1140], on: P = [GEN_C[0] + 18, GEN_C[1] + 6];+ 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);+ // 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) : i > 0 && l < 24 ? ramp(l, 16, 24) : 1;+ if (show > 0) { ctx.globalAlpha = show; bug(ctx, env); ctx.globalAlpha = 1; }+ };+ // ---------------------------------------------------------------- the end card+ const endPage = (c: Ctx, env: Env, e: number) => {+ const cx = W / 2, size = Math.min(150, (1300 / measure(spec.title, 100)) * 100);+ writeOn(c, env, spec.title, cx, 400, size, ramp(e, 10, 44), "ink", { color: C.ink, align: "center", seed: 11 });+ c.setTransform(env.scale, 0, 0, env.scale, 0, 0); c.textAlign = "center"; c.textBaseline = "middle";+ c.globalAlpha = ramp(e, 34, 46); c.fillStyle = C.soft; c.font = SANS(500, 30); c.fillText(spec.tagline, cx, 520);+ c.globalAlpha = ramp(e, 40, 52); c.font = MONO(30);+ const pw = Math.max(...spec.install.map((s) => c.measureText(s).width)) + 120, ph = 60 * spec.install.length + 50, py = 590;+ c.fillStyle = "#1f1c18"; rr(c, cx - pw / 2, py, pw, ph, 22); c.fill();+ c.fillStyle = "#ece4d6"; spec.install.forEach((s, k) => c.fillText(s, cx, py + 55 + k * 60));+ // a terminal caret blinks after the last line: the hold reads as live, never as a freeze+ const lastW = c.measureText(spec.install[spec.install.length - 1]).width;+ if (Math.floor((e - 40) / 15) % 2 === 0) c.fillRect(cx + lastW / 2 + 8, py + 55 + (spec.install.length - 1) * 60 - 17, 16, 34);+ if (spec.footer) { c.fillStyle = C.soft; c.font = SANS(500, 24); c.fillText(spec.footer, cx, py + ph + 60); }+ c.globalAlpha = 1; c.textAlign = "left";+ };+ const content = (ctx: Ctx, env: Env, f: number) => {+ const g = clamp(Math.round(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), (c) => endPage(c, env, e), { close: false, inF: 16 });+ };++ // ---------------------------------------------------------------- the cut, as data+ const words = spec.words ?? [];+ const segs: Seg[] = [];+ spec.asks.forEach((_, i) => {+ const last = i === n - 1, fixed = segs.reduce((s, x) => s + x.len, 0);+ segs.push(last && spec.claimBar !== undefined ? pic(i * ASK, (i + 1) * ASK, grid.solve(spec.claimBar, fixed, 60)) : pic(i * ASK, (i + 1) * ASK));+ if (!last && words[i]?.length) segs.push(type(words[i], TYPE, (i + 1) * ASK - 1, (i + 1) * ASK));+ });+ segs.push(pic(END0, END0 + END));+ const cut = makeCut(segs);+ const draw = (ctx: Ctx, F: number, env: Env) => {+ const { s, local } = cut.at(F);+ if (s.kind === "pic") content(ctx, env, cut.contentOf(s, local));+ // offset by 2 frames at each end so the bloom is already moving on the first and last frame+ else typeFrame(ctx, env, s.lines, local + 2, s.len + 4, (first) => content(ctx, env, first ? s.before : s.after), (c) => bug(c, env), TYPE_O);+ };+ // declared holds: the words' reading time on each type frame, and the end card once it is all on+ 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) * TYPE_O.stagger - 2; // local frame the last line is done+ let open = s.len - 1; while (open > written && bloomRadius(open + 2, s.len + 4) < 1110) open--; // last fully covered frame+ holds.push([cut.STARTS[k] + written + 1, cut.STARTS[k] + open + 1]);+ });+ holds.push([cut.N - END + 53, cut.N]); // the end card, all on: read it, screenshot it+ return {+ meta: { title: `${spec.title} · launch`, W, H, fps, bpm: spec.bpm, durationFrames: cut.N, raster: "cpu", kind: "launch", holds },+ assets: { images: {} },+ shots: [{ id: "cut", start: 0, end: cut.N, draw }],+ audio: spec.audio ?? (spec.score ? musicBed(spec.score, cut.N, fps) : undefined),+ cut,+ };+};++// A music bed: the first `frames` of a composed piece, faded out over the last 1.2 s, then set to+// `lufs` integrated (default -14, the one published cross-platform target) with the true peak held+// at or under -1 dBTP. Compose the piece for this film, at the film's bpm, so the cuts sit on its downbeats.+export const musicBed = (piece: () => Piece, frames: number, fps = 30, lufs = -14) => (sr: number): [Float32Array, Float32Array] => {+ const n = Math.round((frames / fps) * sr), L = new Float32Array(n), R = new Float32Array(n), m = renderPiece(piece(), sr);+ for (let i = 0; i < n && i < m.L.length; i++) { L[i] = m.L[i]; R[i] = m.R[i]; }+ const fade = Math.round(1.2 * sr); for (let i = 0; i < fade && i < n; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }+ const now = loudness([L, R], sr).integrated, peak = truePeak([L, R]).dbtp;+ const gainDb = Math.min(lufs - now, -1 - peak), g = Math.pow(10, gainDb / 20); // loudness first, never past -1 dBTP+ for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; }+ return [L, R];+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/calibration.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/calibration.tsnew file mode 100644index 0000000..45183e2--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/calibration.ts@@ -0,0 +1,21 @@+// A neutral TEST SIGNAL per style: scale-degree triads, a stepwise line, arpeggios. It is not music+// and never a score: `tools/music.mjs calibrate` uses it to set palette levels against stem targets,+// and the unit test uses it to prove every vocabulary composes, renders and meters.+import { beatsPerBar, isCompound } from "./plan";+import { MODES, nameOf, type ModeId } from "./theory";+import type { Material } from "./compose";+import type { StyleVocab } from "./vocab";++export const testMaterial = (v: StyleVocab, o: { loop?: boolean; bars?: number; key?: string; tonic?: number; mode?: ModeId } = {}): Material => {+ const mode = o.mode ?? v.harmony.modes.find((x) => MODES[x].intervals.length === 7) ?? "major", iv = MODES[mode].intervals, meter = v.meters[0], bpb = beatsPerBar(meter), comp = isCompound(meter), bars = o.bars ?? 8;+ const deg = (d: number, oct: number) => 12 * (oct + 1) + (o.tonic ?? 0) + iv[((d % 7) + 7) % 7] + 12 * Math.floor(d / 7), unit = comp ? "1/3" : ".5", count = Math.round(bpb * (comp ? 3 : 2));+ const degs = [0, 3, 4, 5], chords: Material["chords"] = {};+ degs.forEach((d, i) => { chords[`c${i}`] = { voicing: `[${[0, 2, 4].map((k) => nameOf(deg(d + k, 4))).join(" ")}]`, bass: `${nameOf(deg(d, 2))}:${bpb}` }; });+ const bar = (fn: (d: number, j: number) => number) => Array.from({ length: bars }, (_, b) => Array.from({ length: count }, (_, j) => `${nameOf(fn(degs[b % 4], j))}:${unit}`).join(" "));+ const half = bpb / 2;+ return { style: v.id, title: `test signal: ${v.id}`, seed: 1, mood: v.moods[0], bpm: Math.round((v.tempo[0] + v.tempo[1]) / 2), key: o.key ?? "C", mode, meter, chords, loop: o.loop,+ grooves: v.grooves.length ? { main: { family: v.grooves[0], density: 0.5, variation: 0.35 } } : {},+ sections: [{ kind: "hook", bars, harmony: ["c0", "c1", "c2", "c3"], groove: v.grooves.length ? "main" : null,+ lead: bar((d, j) => deg(d + (j % 5), 5)), ...(v.palette.arp ? { arp: bar((d, j) => deg(d + [0, 2, 4, 2][j % 4], 4)) } : {}),+ ...(v.palette.counter ? { counter: Array.from({ length: bars }, (_, b) => `${nameOf(deg(degs[b % 4] + 4, 6))}:${half} ${nameOf(deg(degs[b % 4] + 2, 6))}:${half}`) } : {}) }] };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/compose.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/compose.tsnew file mode 100644index 0000000..07b0612--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/compose.ts@@ -0,0 +1,176 @@+// COMPOSE: the composer's material + a style vocabulary -> a Piece. The composer (the model) writes+// every note: the chord voicings and bass lines, the motifs and lines, the form. The style supplies+// only sound (voices, levels, fx), groove grammars, and the arrangement grammar (which layers a+// section kind lets sound). Nothing is filled in: missing material is an error that says what to+// compose. Workflow and craft: references/music/compose.md. Vocabularies: vocab.ts.+import { line, beatsPerBar, type Note, type Piece, type Part, type Role, type Meter } from "./plan";+import type { ModeId } from "./theory";+import type { MoodId, StyleId, MelodyType } from "./tables";+import { pcOf } from "./theory";+import { perform } from "./perform";+import { drumBar, type Groove, type Lane } from "./grooves";+import { VOCAB_TRIM, VOCAB_TARGET_FIX } from "./vocabTrim";+import { VOCAB, KINDS, BASE_SLOTS, resolveVoice, moodVoice, moodFx, fullMood, type Slot, type Voice, type SectionKind, type MoodControls } from "./vocab";++/** One chord of YOUR harmony: its voicing (a notation chord) and a one-bar bass line you wrote for it. */+export type ComposedChord = { voicing: string; bass?: string };+/** A line = notation bars, or names of your motifs, joined in order from the section's first bar. */+export type LineSpec = string | string[];+export type ComposedSection = {+ id?: string; kind: SectionKind; bars: number;+ /** chord names per bar (keys of `chords`), cycled to fill the section; a bar may hold two: "Dm9 G13" splits it */+ harmony: string[];+ /** lines play ONCE from the section's first bar (harmony cycles, lines do not); a shorter line leaves rests, unless `loopLines` */+ lead?: LineSpec; counter?: LineSpec; arp?: LineSpec;+ /** repeat each line to fill the section (a 2-bar motif in an 8-bar section plays 4 times) */ loopLines?: boolean;+ /** modulate: this section's key and mode (default the piece's); the key check reads each key region separately */ key?: string; mode?: ModeId;+ /** override the chords' bass lines for this section (one bar of notation, or one per bar) */ bass?: string | string[];+ /** a key of `grooves`, or null for no drums; default by kind (main / half / build / none) */ groove?: string | null;+ /** chord velocity scale (0..1.2), e.g. 0.8 for a softer intro */ chordVel?: number;+ /** 0..1 (0.5 = as written): the section's dynamics for EVERY part (velocity x 0.55..1.45, about -5..+3 dB) and the density of generated grooves */ energy?: number;+ /** play the section this many times (refit changes it for the stretch section) */ repeat?: number; stretch?: boolean;+};+export type Material = {+ style: StyleId; title: string; seed: number; mood: MoodId; bpm: number; key: string; mode: ModeId; meter?: Meter;+ chords: Record<string, ComposedChord>; motifs?: Record<string, string>; grooves?: Record<string, Groove>;+ sections: ComposedSection[];+ /** swap a slot's voice for one of the style's alternates by name, or give your own Voice */ voices?: Partial<Record<Slot, string | Voice>>;+ /** dB OFFSET per slot, added to the voice's calibrated gain (after trims and mood): +2 = two dB louder. Set from the stem meter. */ levels?: Partial<Record<Slot, number>>;+ moodControls?: MoodControls;+ /** 0.5 straight .. 0.67 hard swing (default the style's lower bound) */ swing?: number;+ /** the piece's dynamic level [start, end] 0..1, ramped over the whole piece (default [0.62, 0.66]); section `energy` shapes it locally */ dyn?: [number, number];+ /** seconds of ring-out after the last onset (default 3.2) */ tail?: number; loop?: boolean;+};++const need = (ok: unknown, msg: string) => { if (!ok) throw new Error(`compose: ${msg} The style supplies sound, never notes: compose it yourself (references/music/compose.md).`); };+const fmt = (x: number) => String(+x.toFixed(4));+const lanes: Lane[] = ["kick", "snare", "ghost", "hat", "perc"];++/** Expand repeats: the sections as played, with their first bar. */+export const layout = (sections: ComposedSection[]) => {+ const out: { s: ComposedSection; id: string; from: number; to: number; pass: number }[] = []; let b = 0;+ sections.forEach((s, i) => { for (let k = 0; k < (s.repeat ?? 1); k++) { out.push({ s, id: s.id ?? `${s.kind}${i}`, from: b, to: b + s.bars, pass: k }); b += s.bars; } });+ return out;+};++export const composePiece = (m: Material): Piece => {+ const V = VOCAB[m.style]; need(V, `no vocabulary for style "${m.style}" (have: ${Object.keys(VOCAB).join(", ")}).`);+ const vocab = V!, meter = m.meter ?? vocab.meters[0], bpb = beatsPerBar(meter);+ need(m.title && Number.isFinite(m.seed) && m.mood, "a piece needs its own title, seed and mood.");+ need(m.sections?.length, "no form: write the sections (kind, bars, harmony, lines).");+ need(m.chords && Object.keys(m.chords).length, "no harmony: write your chords (voicing + bass line per chord).");+ const lay = layout(m.sections), B = lay[lay.length - 1].to;+ need(m.sections.some((s) => s.lead), "no melody: at least one section needs a lead line (your own motif).");+ const motif = (x: string) => m.motifs?.[x] ?? x;+ const lineOf = (spec: LineSpec) => (Array.isArray(spec) ? spec : [spec]).map(motif).join(" | ");++ // ---- harmony per bar (a bar may split into chords: "A B" = two halves)+ const chordAt: string[][] = [];+ for (const x of lay) {+ need(x.s.harmony?.length, `section "${x.id}" has no harmony: write the chord names for its bars.`);+ for (let i = 0; i < x.s.bars; i++) { const names = x.s.harmony[i % x.s.harmony.length].trim().split(/\s+/); for (const n of names) need(m.chords[n], `chord "${n}" (section "${x.id}") has no voicing: add chords["${n}"] = { voicing: "[...]", bass: "..." }.`); chordAt.push(names); }+ }+ const harmony = chordAt.flatMap((names, b) => names.map((name, j) => ({ t: b * bpb + (j * bpb) / names.length, name })));+ const at = (b: number) => lay.find((x) => b >= x.from && b < x.to)!;++ // ---- notes+ const notes: Partial<Record<Slot, Note[]>> = {};+ const push = (slot: Slot, ns: Note[]) => { (notes[slot] ??= []).push(...ns); };+ const vel: Record<Slot, number> = { chords: 0.62, lead: 0.72, counter: 0.5, bass: 0.85, arp: 0.55, kick: 0.85, snare: 0.7, ghost: 0.5, hat: 0.5, perc: 0.45 };+ const role = (slot: Slot): Role => (slot === "chords" || slot === "arp" ? "accomp" : slot === "lead" ? "melody" : slot === "counter" ? "color" : slot === "bass" ? "bass" : "drum");+ for (let b = 0; b < B; b++) {+ const x = at(b), cv = x.s.chordVel, names = chordAt[b], d = bpb / names.length;+ const src = names.map((n) => `${m.chords[n].voicing}:${fmt(d)}${cv !== undefined ? `@${fmt(cv)}` : ""}`).join(" ");+ push("chords", line(b * bpb, src, { role: "accomp", v: vel.chords, bpb, roll: 0.03 }));+ if (KINDS[x.s.kind].bass) {+ const ov = x.s.bass, bl = ov !== undefined ? (Array.isArray(ov) ? ov[(b - x.from) % ov.length] : ov) : names.length === 1 ? m.chords[names[0]].bass : undefined;+ need(bl !== undefined, names.length > 1 ? `bar ${b} splits into ${names.join(" + ")}: give section "${x.id}" a bass override for it.` : `chord "${names[0]}" (section "${x.id}") has no bass line: add chords["${names[0]}"].bass (one bar), or a section bass override.`);+ if (bl) push("bass", line(b * bpb, bl, { role: "bass", v: vel.bass, bpb }));+ }+ // drums+ const def = KINDS[x.s.kind].drums, gname = x.s.groove === undefined ? def : x.s.groove;+ if (gname) {+ const g = m.grooves?.[gname];+ need(g, `section "${x.id}" (${x.s.kind}) needs a groove "${gname}": add grooves["${gname}"] = { family: one of ${vocab.grooves.join(", ")}, density, variation } or write it (kick/snare/ghost/hat bars), or set groove: null.`);+ const bar = drumBar(g!, meter, m.seed, b, b - x.from, x.s.bars, x.s.energy ?? 0.5);+ for (const ln of lanes) if (bar[ln]) push(ln, line(b * bpb, bar[ln]!, { role: "drum", v: vel[ln], bpb }));+ }+ }+ const warnings: string[] = [];+ for (const x of lay) for (const slot of ["lead", "counter", "arp"] as Slot[]) {+ const spec = x.s[slot as "lead" | "counter" | "arp"]; if (!spec) continue;+ let src = lineOf(spec); const barsOf = (t: string) => t.split("|").filter((z) => z.trim()).length, lb = barsOf(src);+ if (lb < x.s.bars) {+ if (x.s.loopLines) { const reps = Math.ceil(x.s.bars / lb), all = Array.from({ length: reps }, () => src).join(" | ").split("|").map((z) => z.trim()).filter(Boolean); src = all.slice(0, x.s.bars).join(" | "); }+ else if (x.pass === 0) warnings.push(`section "${x.id}": the ${slot} is ${lb} bar(s) in a ${x.s.bars}-bar section; it plays once, then rests (set loopLines: true to repeat it)`);+ }+ const ns = line(x.from * bpb, src, { role: role(slot), v: vel[slot], bpb });+ need(ns.every((n) => n.t < x.to * bpb - 1e-9), `the ${slot} line of section "${x.id}" is longer than its ${x.s.bars} bars.`);+ push(slot, ns);+ }++ // ---- section energy: dynamics for every part (0.5 = as written, exactly)+ for (const x of lay) { const en = x.s.energy; if (en === undefined || en === 0.5) continue; const f = 0.55 + 0.9 * en, a = x.from * bpb, z = x.to * bpb;+ for (const ns of Object.values(notes)) for (const n of ns!) if (n.t >= a - 1e-9 && n.t < z - 1e-9) n.v *= f; }+ // ---- parts from the palette (+ alternates, levels, mood)+ const mood = m.moodControls ? fullMood(m.moodControls) : null, targets: Record<string, number> = {};+ const slots = [...BASE_SLOTS, ...(["arp", "perc"] as Slot[]).filter((s) => notes[s]?.length)];+ const parts: Part[] = [];+ for (const slot of slots) {+ const pick = m.voices?.[slot];+ const FALLBACK: Partial<Record<Slot, Slot>> = { perc: "hat", ghost: "snare", snare: "ghost", hat: "perc" }; // a drum lane without its own voice borrows its neighbour's+ let v = typeof pick === "object" ? pick : typeof pick === "string" ? vocab.alternates[slot]?.[pick] : vocab.palette[slot] ?? (notes[slot]?.length && FALLBACK[slot] ? vocab.palette[FALLBACK[slot]!] : undefined);+ need(typeof pick !== "string" || v, `style ${vocab.id} has no "${pick}" voice for ${slot} (have: ${Object.keys(vocab.alternates[slot] ?? {}).join(", ") || "none"}).`);+ if (!v) { if (slot === "chords") continue; /* a style without a chord voice (chiptune): the harmony still labels bars and feeds the bass */ need(!notes[slot]?.length, `style ${vocab.id} has no ${slot} voice, but your ${slot} has notes: pick a groove family or slot this style has.`); continue; }+ v = resolveVoice(v, m.bpm);+ let dGain = 0; if (mood) { const r = moodVoice(slot, v, mood); v = r.voice; dGain = r.dGain; }+ const lv = m.levels?.[slot];+ const trim = pick !== undefined ? 0 : VOCAB_TRIM[vocab.id]?.[slot] ?? 0; let gainDb = trim ? v.gainDb + trim : v.gainDb; if (lv) gainDb += lv;+ // a timpani (or any pitched drum voice) playing a drum lane is tuned to the key: the tonic in its low register+ if (v.inst === "timpani" && role(slot) === "drum" && typeof pick !== "object") { const tp = pcOf(m.key.replace(/m$/, "")), lo = typeof v.opts?.pitch === "number" ? (v.opts.pitch as number) - 5 : slot === "kick" ? 31 : 38; /* the tonic nearest the voice's own register */ v = { ...v, opts: { ...(v.opts ?? {}), pitch: lo + ((tp - (lo % 12) + 12) % 12) } }; }+ if (vocab.stemTargets[slot] !== undefined) targets[slot] = vocab.stemTargets[slot] + dGain + (pick === undefined ? VOCAB_TARGET_FIX[vocab.id]?.[slot] ?? 0 : 0); // a mood that lifts the hats lifts their target too+ const p: Part = { id: slot, inst: v.inst, role: v.role, notes: notes[slot] ?? [], gainDb };+ if (v.opts) p.opts = v.opts; if (v.send !== undefined) p.send = v.send; if (v.pan !== undefined) p.pan = v.pan;+ parts.push(p);+ }+ const e = mood ? mood.energy - 0.5 : 0, dyn0 = m.dyn ?? [0.62, 0.66], dyn: [number, number] = mood ? [dyn0[0] + e * 0.2, dyn0[1] + e * 0.2] : dyn0;+ // key regions: one plan section per run of sections in the same key and mode (a single one when the piece never modulates)+ const keyOf = (x: (typeof lay)[number]) => `${x.s.key ?? m.key}|${x.s.mode ?? m.mode}`, regions: { from: number; to: number; key: string; mode: ModeId }[] = [];+ for (const x of lay) { const r = regions[regions.length - 1]; if (r && `${r.key}|${r.mode}` === keyOf(x)) r.to = x.to; else regions.push({ from: x.from, to: x.to, key: x.s.key ?? m.key, mode: x.s.mode ?? m.mode }); }+ const lvl = (b: number) => dyn[0] + ((dyn[1] - dyn[0]) * b) / B;+ const planSections = regions.length === 1 ? [{ id: "a", bars: B, mood: m.mood, key: m.key, mode: m.mode, melody: ["stepwise", "hook"] as MelodyType[], dyn, ending: "tail" as const, repeatable: false }]+ : regions.map((r, i) => ({ id: `key${i}`, bars: r.to - r.from, mood: m.mood, key: r.key, mode: r.mode, melody: ["stepwise", "hook"] as MelodyType[], dyn: [lvl(r.from), lvl(r.to)] as [number, number], ending: "tail" as const, repeatable: false }));+ const piece: Piece = {+ title: m.title, seed: m.seed, tail: m.tail ?? 3.2, harmony, parts,+ plan: { style: m.style, tempo: m.bpm, meter, swing: m.swing ?? vocab.swing[0], ritard: m.loop ? 1 : 0.92, loop: m.loop,+ sections: planSections },+ fx: mood ? moodFx(vocab.fx, mood) : vocab.fx, stemTargets: targets,+ arrangement: lay.map((x) => ({ id: x.id, kind: x.s.kind, from: x.from, bars: x.s.bars })),+ warnings, refit: m.loop ? undefined : (seconds: number) => composePiece(refitMaterial(m, seconds)),+ };+ return piece;+};++/** lofiElectronic(material): composePiece in the lo-fi electronic vocabulary. */+export const lofiElectronic = (m: Omit<Material, "style">): Piece => composePiece({ ...m, style: "lofiElectronic" } as Material);++/**+ * The same composition for a film `seconds` long: the `stretch` section (default the longest+ * groove/hook/verse/drop) is played more or fewer times (0 = dropped), whichever puts the last+ * onset nearest `seconds - tail` at the written tempo. fitToDuration then trims the tempo.+ */+export const refitMaterial = (m: Material, seconds: number): Material => {+ const secs = m.sections, want = seconds - (m.tail ?? 3.2);+ let si = secs.findIndex((s) => s.stretch);+ if (si < 0) secs.forEach((s, i) => { if (["groove", "hook", "verse", "drop"].includes(s.kind) && (si < 0 || s.bars * (s.repeat ?? 1) > secs[si].bars * (secs[si].repeat ?? 1))) si = i; });+ if (si < 0 || want <= 0) return m;+ let best: { m: Material; cost: number } | null = null;+ for (let r = 0; r <= 64; r++) {+ const m2: Material = { ...m, sections: secs.map((s, i) => (i === si ? { ...s, repeat: r } : s)).filter((s) => (s.repeat ?? 1) > 0) };+ if (!m2.sections.some((s) => s.lead)) continue;+ const t = perform(composePiece(m2), m.bpm, { expressive: true }).lastOnset, tempo = m.bpm * (t / want), cost = Math.abs(Math.log(tempo / m.bpm));+ if (!best || cost < best.cost) best = { m: m2, cost };+ if (tempo > m.bpm * 1.3) break;+ }+ return best ? best.m : m;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/grooves.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/grooves.tsnew file mode 100644index 0000000..c6b5ff9--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/grooves.ts@@ -0,0 +1,186 @@+// GROOVE FAMILIES: drum grammars, not drum patterns. A family says where the weight of a bar+// goes (kick anchors, backbeat, ghost slots, hat feel); `density`, `variation`, `fill` and the+// piece's seed decide the actual hits, bar by bar, so two pieces on the same family never share+// one loop. Pure: the same (family, params, seed, bar) always gives the same bar.+//+// Lanes: kick, snare, ghost (rim/soft snare), hat (closed), perc (open hat, shaker: the style's+// perc voice). Output is line() notation for one bar per lane (null = the lane rests).+import { rng as mkRng } from "../core";+import type { Meter } from "./plan";+import { beatsPerBar, isCompound } from "./plan";++export type GrooveFamily = "bounce" | "fourFloor" | "halfTime" | "broken" | "shuffle" | "pulse" | "brushes" | "build" | "tension" | "skip" | "trap" | "epic" | "hand" | "rock" | "swing";+/** A generated groove: the composer picks the family and its knobs. */+export type GrooveChoice = { family: GrooveFamily; density?: number; variation?: number; fill?: boolean; accent?: number };+/** A written groove: one or more bars of notation per lane, cycled by the absolute bar number. */+/** A written groove: one or more bars of notation per lane. Bars cycle from each section's first bar (`cycle: "piece"` cycles on the piece's bar count instead).+ * The written pitch is ignored by unpitched drums (kick, snare, hat, noise): write C4. A pitched voice in a drum lane (timpani) is tuned to the key. */+export type LiteralGroove = { kick?: string[]; snare?: string[]; ghost?: string[]; hat?: string[]; perc?: string[]; cycle?: "section" | "piece" };+export type Groove = GrooveChoice | LiteralGroove;+export type Lane = "kick" | "snare" | "ghost" | "hat" | "perc";+export type DrumBar = Partial<Record<Lane, string | null>>;++export const GROOVE_FAMILIES: Record<GrooveFamily, string> = {+ bounce: "lo-fi / hip-hop bounce: kick on 1 plus syncopated pickups, backbeat on 2 and 4, ghost notes, 8th or 16th hats with accents",+ fourFloor: "house / drive: kick on every beat, clap on 2 and 4, off-beat open hats, 16ths when dense",+ halfTime: "half-time: kick on 1 (and a pickup), snare on 3; the same tempo feels twice as slow (a breath, a scene change)",+ broken: "broken beat / garage: kicks displaced off the grid, backbeat kept, ghosted 16ths; restless, modern",+ shuffle: "shuffle: triplet grid, swung hats, kick on 1 and 3 with a skip; playful, bouncy",+ pulse: "pulse: a soft heartbeat kick, no backbeat, sparse shaker; ambient and cinematic under-scoring",+ brushes: "brushes: soft rim on 2 and 4, shaker swishes, a gentle kick; tender, acoustic",+ build: "build: snare 8ths then 16ths rising in velocity across the section, kick on quarters; ends on the next downbeat",+ tension: "tension: 3-3-2 kick ostinato, accent on 4, quiet 16th hats; cinematic urgency, chases",+ skip: "skip: kick on 1 and the and-of-2, clap on 2 and 4, a skipping 16th perc; playful, light",+ trap: "trap: sparse syncopated kicks (the 808 bass follows them), clap on 3, 16th hats with velocity ramps and bursts, an open hat now and then",+ epic: "epic: big low hits (kick / timpani in perc) in a 3-3-2 or 1-and-3 figure, a snare accent on 4; orchestral and trailer weight",+ hand: "hand percussion: dum (low) on each group start, tek (rim) inside, ka (perc) fills; groups follow the meter (7/8 = 2+2+3, 9/8 = 2+2+2+3, 5/4 = 3+2)",+ rock: "rock: kick on 1 and 3 with an 8th pickup, snare backbeat, 8th hats, a crash (perc) on section starts",+ swing: "jazz swing: ride on the beats and the swung skip of 2 and 4, foot hi-hat (perc) on 2 and 4, feathered kick, snare comping ghosts",+};++/** Step grid for a meter: 16ths in simple meters, triplet 8ths in compound ones. */+const grid = (meter: Meter, triplet: boolean) => {+ const bpb = beatsPerBar(meter), compound = isCompound(meter) || (triplet && Number.isInteger(bpb)), per = compound ? 3 : 4;+ return { steps: Math.round(bpb * per), stepBeats: 1 / per, per, bpb: Math.ceil(bpb) };+};+const round = (x: number) => +x.toFixed(3);+/** Hits (step -> velocity multiplier) to one bar of notation. */+export const stepsToLine = (hits: Map<number, number>, steps: number, per: number): string | null => {+ const at = [...hits.keys()].filter((s) => s >= 0 && s < steps).sort((a, b) => a - b); if (!at.length) return null;+ const d = (n: number) => (per === 3 ? `${n}/3` : String(n / per)); // exact: fractions for triplets, decimals for 16ths+ const toks: string[] = []; if (at[0] > 0) toks.push(`r:${d(at[0])}`);+ at.forEach((s, i) => { const nx = i + 1 < at.length ? at[i + 1] : steps; toks.push(`C4:${d(nx - s)}@${round(Math.min(1, Math.max(0.05, hits.get(s)!)))}`); });+ return toks.join(" ");+};++/**+ * One bar of a generated groove. `pos` = bar index inside its section, `len` = section bars,+ * `abs` = absolute bar (the seed's per-bar variation), `energy` 0..1 scales density.+ */+export const grooveBar = (g: GrooveChoice, meter: Meter, seed: number, abs: number, pos: number, len: number, energy = 0.5): DrumBar => {+ const trip = g.family === "shuffle" || g.family === "swing", G = grid(meter, trip), { steps, per, bpb } = G;+ const d = Math.min(1, Math.max(0, (g.density ?? 0.5) + (energy - 0.5) * 0.6)), v = g.variation ?? 0.35, acc = g.accent ?? 1;+ const r = mkRng(seed * 7919 + abs * 131 + 17), maybe = (p: number) => r() < p;+ const K = new Map<number, number>(), S = new Map<number, number>(), Gh = new Map<number, number>(), H = new Map<number, number>(), P = new Map<number, number>();+ const beat = (b: number, sub = 0) => b * per + sub; // step of beat b (0-based) plus a subdivision+ const back = bpb >= 4 ? [beat(1), beat(3)] : bpb === 3 ? [beat(1), beat(2)] : [beat(1)];+ const hats = (every: number, lo: number, hi: number, jitter = 0.08) => { for (let s = 0; s < steps; s += every) H.set(s, (s % per === 0 ? hi : lo) * (1 + (r() - 0.5) * jitter * 2)); };+ switch (g.family) {+ case "bounce": {+ K.set(0, 1); K.set(beat(2, 2), 0.9 * acc);+ for (const s of [beat(1, 3), beat(2), beat(2, 3), beat(3, 2)]) if (s < steps && maybe(0.15 + 0.35 * d * v)) K.set(s, 0.6 + 0.2 * r());+ for (const s of back) S.set(s, 1);+ if (d > 0.35) { const slots = [beat(1, 3), beat(3, 3), beat(0, 3), beat(2, 1)].filter((s) => s < steps); Gh.set(slots[Math.floor(r() * slots.length)], 0.45 + 0.1 * r()); }+ if (d > 0.55) { const pat = [0.85, 0.35, 0.6, 0.4]; for (let s = 0; s < steps; s++) H.set(s, pat[s % 4] * (1 + (r() - 0.5) * 0.12)); } else hats(2, 0.45, 0.8);+ break;+ }+ case "fourFloor": {+ for (let b = 0; b < bpb; b++) K.set(beat(b), b === 0 ? 1 : 0.92);+ for (const s of back) S.set(s, 0.95);+ for (let b = 0; b < bpb; b++) P.set(beat(b, 2), 0.7);+ if (d > 0.6) for (let s = 0; s < steps; s++) if (s % 2 === 1) H.set(s, 0.35 + 0.15 * r());+ if (v > 0.5 && maybe(0.3)) K.set(beat(bpb - 1, 3), 0.55);+ break;+ }+ case "halfTime": {+ K.set(0, 1); if (d > 0.4) K.set(beat(Math.min(2, bpb - 1) - 1, 2) + (maybe(v) ? 1 : 0), 0.7);+ S.set(beat(Math.floor(bpb / 2)), 1);+ hats(d > 0.6 ? 2 : per, 0.35, 0.6);+ break;+ }+ case "broken": {+ K.set(0, 1); for (const s of [beat(1, 2), beat(2, 1), beat(2, 3), beat(3, 1)]) if (s < steps && maybe(0.25 + 0.45 * v)) K.set(s, 0.75 + 0.15 * r());+ for (const s of back) S.set(s, 1);+ for (let s = 0; s < steps; s++) if (s % 2 === 1 && maybe(0.2 + 0.3 * d) && !K.has(s)) Gh.set(s, 0.35 + 0.15 * r());+ for (let s = 0; s < steps; s++) if (maybe(0.45 + 0.4 * d)) H.set(s, s % 2 ? 0.35 : 0.7);+ break;+ }+ case "shuffle": {+ K.set(0, 1); if (bpb >= 3) K.set(beat(2), 0.85); if (maybe(0.4 + 0.4 * v)) K.set(beat(1, 2), 0.6);+ for (const s of back) S.set(s, 0.95);+ for (let b = 0; b < bpb; b++) { H.set(beat(b), 0.75); if (d > 0.3) H.set(beat(b, 2), 0.45 + 0.1 * r()); }+ if (d > 0.6) Gh.set(beat(bpb - 1, 2), 0.4);+ break;+ }+ case "pulse": {+ K.set(0, 0.9); if (d > 0.5 && bpb >= 3) K.set(beat(Math.floor(bpb / 2)), 0.7); if (d > 0.75) K.set(beat(Math.floor(bpb / 2) - 1, 2), 0.5);+ if (d > 0.3) for (let b = 0; b < bpb; b++) P.set(beat(b, per / 2 >= 1 ? Math.floor(per / 2) : 0), 0.35 + 0.1 * r());+ if (v > 0.5 && maybe(0.4)) Gh.set(beat(bpb - 1), 0.35);+ break;+ }+ case "brushes": {+ K.set(0, 0.7); if (d > 0.5 && bpb >= 3) K.set(beat(bpb >= 4 ? 2 : 1), 0.55);+ for (const s of back) Gh.set(s, 0.6);+ for (let s = 0; s < steps; s += per === 3 ? 1 : 2) P.set(s, (s % per === 0 ? 0.55 : 0.3) * (1 + (r() - 0.5) * 0.3));+ break;+ }+ case "build": {+ const x = len > 1 ? pos / (len - 1) : 1, every = x < 0.5 ? 2 : 1;+ for (let b = 0; b < bpb; b++) K.set(beat(b), 0.9);+ for (let s = 0; s < steps; s += every) S.set(s, 0.35 + 0.6 * ((pos + s / steps) / len));+ hats(2, 0.4, 0.6);+ break;+ }+ case "tension": {+ for (const s of [0, 3, 6, 8, 11, 14].map((q) => Math.round((q / 16) * steps))) K.set(s, s === 0 ? 1 : 0.75);+ S.set(beat(bpb - 1), 0.9 * acc);+ for (let s = 0; s < steps; s++) H.set(s, (s % per === 0 ? 0.4 : 0.22) * (0.6 + 0.8 * d));+ if (v > 0.4 && maybe(0.5)) Gh.set(beat(bpb - 1, per - 1), 0.5);+ break;+ }+ case "skip": {+ K.set(0, 1); K.set(beat(1, 2), 0.8); if (maybe(0.3 + 0.4 * v)) K.set(beat(3, 1) < steps ? beat(3, 1) : beat(bpb - 1), 0.6);+ for (const s of back) S.set(s, 0.9);+ for (let s = 0; s < steps; s++) if (s % 4 === 1 || s % 4 === 3 || maybe(0.3 * d)) P.set(s, 0.3 + 0.25 * r());+ hats(2, 0.4, 0.65);+ break;+ }+ case "trap": {+ K.set(0, 1); for (const s of [beat(0, 3), beat(1, 2), beat(2, 3), beat(3, 1), beat(3, 2)]) if (s < steps && maybe(0.2 + 0.4 * v)) K.set(s, 0.8 + 0.15 * r());+ S.set(beat(Math.min(2, bpb - 1)), 1);+ for (let s = 0; s < steps; s++) H.set(s, (s % 2 ? 0.35 : 0.6) * (1 + (r() - 0.5) * 0.2));+ if (d > 0.5) { const b0 = Math.floor(r() * bpb); for (let j = 0; j < per; j++) H.set(beat(b0, j), 0.3 + (0.5 * j) / per); }+ if (maybe(0.25 * d)) P.set(beat(bpb - 1, 2), 0.5);+ break;+ }+ case "epic": {+ const fig = v > 0.5 ? [0, 3, 6, 8, 11, 14] : [0, 8, 10];+ for (const q of fig) { const s = Math.round((q / 16) * steps); K.set(s, q === 0 ? 1 : 0.8); if (d > 0.4) P.set(s, 0.7); }+ S.set(beat(bpb - 1), 0.9);+ if (d > 0.6) for (let s = 0; s < steps; s += 2) H.set(s, 0.3);+ break;+ }+ case "hand": {+ const eighths = Math.round(steps / (per === 3 ? 1 : 2)), unit = per === 3 ? 1 : 2;+ const groups = meter === "7/8" ? [2, 2, 3] : meter === "9/8" ? [2, 2, 2, 3] : meter === "5/4" ? [3, 3, 2, 2] : Array.from({ length: Math.max(1, Math.round(eighths / 2)) }, () => 2);+ let e8 = 0; groups.forEach((gsz, gi) => { const s0 = e8 * unit; K.set(s0, gi === 0 ? 1 : 0.8); for (let j = 1; j < gsz; j++) Gh.set((e8 + j) * unit, 0.5 + 0.2 * r()); if (d > 0.5 && maybe(0.5)) P.set((e8 + gsz) * unit - 1, 0.4); e8 += gsz; });+ if (per === 3 && meter !== "9/8") { /* compound: groups of 3 eighths */ K.clear(); Gh.clear(); for (let b = 0; b < bpb; b++) { K.set(beat(b), b === 0 ? 1 : 0.75); Gh.set(beat(b, 1), 0.45); Gh.set(beat(b, 2), 0.55); } }+ break;+ }+ case "rock": {+ K.set(0, 1); if (bpb >= 3) K.set(beat(2), 0.9); if (maybe(0.3 + 0.5 * v)) K.set(beat(Math.min(2, bpb - 1), 2), 0.75);+ for (const s of back) S.set(s, 1);+ hats(2, 0.55, 0.8);+ if (pos === 0) P.set(0, 0.9);+ break;+ }+ case "swing": {+ for (let b = 0; b < bpb; b++) { H.set(beat(b), 0.7); K.set(beat(b), 0.25); }+ for (const s of back) { H.set(s + 2, 0.5); P.set(s, 0.5); }+ for (let b = 0; b < bpb; b++) if (maybe(0.2 + 0.35 * d)) Gh.set(beat(b, 2), 0.3 + 0.2 * r());+ break;+ }+ }+ if (g.fill && pos === len - 1) { const f0 = steps - per; for (let s = f0; s < steps; s++) S.set(s, 0.45 + 0.5 * ((s - f0) / per)); }+ const out: DrumBar = {};+ for (const [lane, m] of [["kick", K], ["snare", S], ["ghost", Gh], ["hat", H], ["perc", P]] as [Lane, Map<number, number>][]) out[lane] = stepsToLine(m, steps, per);+ return out;+};++export const isLiteral = (g: Groove): g is LiteralGroove => !("family" in g);+/** One bar of any groove (literal lanes cycle on the absolute bar). */+export const drumBar = (g: Groove, meter: Meter, seed: number, abs: number, pos: number, len: number, energy?: number): DrumBar => {+ if (!isLiteral(g)) return grooveBar(g, meter, seed, abs, pos, len, energy);+ const k = g.cycle === "piece" ? abs : pos, pick = (xs?: string[]) => (xs && xs.length ? xs[k % xs.length] || null : null);+ return { kick: pick(g.kick), snare: pick(g.snare), ghost: pick(g.ghost), hat: pick(g.hat), perc: pick(g.perc) };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.tsindex a34ffeb..be75780 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/guards.ts@@ -13,7 +13,7 @@import { onsets, mono, loudness } from "./meter";import { renderPiece, type Rendered } from "./render";import { pcOf } from "./theory";-import type { Piece, Role } from "./plan";+import { beatsPerBar, type Piece, type Role } from "./plan";export const GHOST = { maxOnsetsPerBeat: 1.0, minSustainedShare: 0.6, reverbWithinDb: -12, windowBars: 4, fallbackWindowS: 8 };@@ -61,7 +61,7 @@ export const cadenceTimes = (r: Rendered) => {/** Reverb-to-dry per bar (dB). Pass: every sounding bar >= 10 dB under. */export const reverbCheck = (r: Rendered, sr: number) => {- const bpb = r.piece.plan.meter === "3/4" ? 3 : r.piece.plan.meter === "6/8" ? 2 : 4, total = r.piece.plan.sections.reduce((a, s) => a + s.bars * bpb, 0), bars: number[] = [];+ const bpb = beatsPerBar(r.piece.plan.meter), total = r.piece.plan.sections.reduce((a, s) => a + s.bars * bpb, 0), bars: number[] = [];for (let b = 0; b < total; b += bpb) {const a = Math.round(r.perf.sec(b) * sr), e = Math.min(r.L.length, Math.round(r.perf.sec(b + bpb) * sr)); let ew = 0, ed = 0;for (let c = 0; c < 2; c++) for (let i = a; i < e; i++) { ew += r.wet[c][i] ** 2; ed += r.dry[c][i] ** 2; }@@ -87,7 +87,7 @@ export const maskingCheck = (piece: Piece, sr: number, o: { seconds?: number; teconst only = (r: Role) => ({ ...piece, parts: piece.parts.map((p) => ({ ...p, notes: p.notes.filter((n) => n.role === r) })) });const base = { seconds: o.seconds, tempo: o.tempo, master: "none" as const };const mel = renderPiece(only("melody"), sr, base);- const bpb = piece.plan.meter === "3/4" ? 3 : piece.plan.meter === "6/8" ? 2 : 4, total = piece.plan.sections.reduce((a, s) => a + s.bars * bpb, 0);+ const bpb = beatsPerBar(piece.plan.meter), total = piece.plan.sections.reduce((a, s) => a + s.bars * bpb, 0);const spans: [number, number][] = []; for (let b = 0; b < total; b += bpb) spans.push([mel.perf.sec(b), mel.perf.sec(b + bpb)]);const melNotes = piece.parts.flatMap((p) => p.notes.filter((n) => n.role === "melody"));const sounding = spans.map((_, i) => melNotes.some((n) => n.t < (i + 1) * bpb && n.t + n.d > i * bpb));@@ -100,7 +100,7 @@ export const maskingCheck = (piece: Piece, sr: number, o: { seconds?: number; te/** Everything at once for a rendered piece. */export const guardReport = (r: Rendered, sr: number, seconds: number, o: { masking?: boolean } = {}) => {- const bpb = r.piece.plan.meter === "3/4" ? 3 : r.piece.plan.meter === "6/8" ? 2 : 4;+ const bpb = beatsPerBar(r.piece.plan.meter);const ghost = ghostCheck([r.L, r.R], sr, { bpm: r.tempo, beatsPerBar: bpb, wet: r.wet, dry: r.dry, cadences: cadenceTimes(r) });return { ghost: { pass: ghost.pass, failures: ghost.failures, windows: ghost.windows.length, minOnsetsPerBeat: Math.min(...ghost.windows.map((w) => w.onsetsPerBeat)), maxSustainedShare: Math.max(...ghost.windows.map((w) => w.sustainedShare)) }, reverb: reverbCheck(r, sr), masking: o.masking === false ? null : maskingCheck(r.piece, sr, { seconds, tempo: r.tempo }), lufs: loudness([r.L, r.R], sr).integrated };};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.tsindex b3a437a..d8bfe6e 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/index.ts@@ -8,12 +8,29 @@ export * from "./render";export * from "./meter";export * from "./guards";export * from "./score-text";+export * from "./grooves";+export * from "./vocab";+export * from "./vocabTrim";+export * from "./compose";+export * from "./novelty";+export * from "./calibration";export * as instruments from "./instruments";+export * from "./sfx";+export * as orchestra from "./orchestra";import { nocturne, pianoPhrase8 } from "./pieces/nocturne";-import { launchLofi, launchLofi2, launchLofi3 } from "./pieces/launch";+import { launchLofi, launchLofi2, launchLofi3, launchLofi3Material } from "./pieces/launch";import { musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic } from "./pieces/samplers";import { marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm } from "./pieces/families";import { ghostFixture } from "./pieces/fixtures";-export { launchLofi, launchLofi2, launchLofi3, nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm, ghostFixture };-/** Named pieces a film (or the tool) can ask for. ghostFixture is a test fixture, never a score. */-export const PIECES = { launchLofi, launchLofi2, launchLofi3, nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm, ghostFixture };+import { daylightCopy, daylightCopyMaterial } from "./pieces/copyFixture";+export { launchLofi, launchLofi2, launchLofi3, launchLofi3Material, nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm, ghostFixture, daylightCopy, daylightCopyMaterial };+/**+ * SHIPPED MUSIC: the demos (one per style/mood, written to prove the synth and the meters) and our own+ * film's scores. They are listening references and the novelty corpus, NEVER a film's score: a new+ * film composes its own (references/music/compose.md) and `novelty` fails it if it sounds like these.+ */+export const DEMOS = { launchLofi, launchLofi2, launchLofi3, nocturne, pianoPhrase8, musicBoxJoy, minorPianoMelancholy, cinematicAwe, chiptunePlayful, lofiNostalgic, marimbaCurious, harpTender, guitarWistful, celestaWonder, bellsHopeful, driveElectronic, folkCalm };+/** Families: cuts of one score (compared to each other they are the same music, by design). */+export const DEMO_FAMILIES: Record<string, string[]> = { launch: ["launchLofi", "launchLofi2", "launchLofi3"], nocturne: ["nocturne", "pianoPhrase8"] };+/** Test fixtures, never scores: the ghost (must fail the ghost guard), the copy (must fail novelty). */+export const FIXTURES = { ghostFixture, daylightCopy };diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/meter.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/meter.tsindex f70647c..9581955 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/meter.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/meter.ts@@ -103,3 +103,18 @@ export const measure = (chans: Float32Array[], sr: number): Meters => {const l = loudness(chans, sr), tp = truePeak(chans), on = onsets(chans, sr), c = centroid(chans, sr), dur = chans[0].length / sr;return { durationS: dur, lufs: l.integrated, lra: l.lra, shortMax: l.shortMax, dbtp: tp.dbtp, samplePeakDb: tp.samplePeakDb, onsetsPerS: on.length / dur, onsetCount: on.length, centroidHz: c.mean, centroidEnergyHz: c.energyWeighted, lastOnsetS: on.length ? on[on.length - 1] : 0, shortTerm: l.shortTerm };};++/** RMS of a stem over its active samples (|x| > 1e-4), left channel, dBFS: the level a part plays at when it plays. */+export const stemRms = (x: Float32Array, floor = 1e-4) => { let s = 0, c = 0; for (let i = 0; i < x.length; i++) { const v = x[i]; if (Math.abs(v) > floor) { s += v * v; c++; } } return c ? 10 * Math.log10(s / c + 1e-12) : -Infinity; };+export type StemRow = { id: string; rmsDb: number; targetDb: number | null; offDb: number | null; ok: boolean };+/**+ * Stem balance: each part's active RMS against its target; a part more than `tolDb` off is flagged.+ * LESSON (the launch score): integrated LUFS of the mix looked right while the sub sat 7-10 dB too hot.+ * Loudness says how loud the whole is, never which part is wrong. Meter the stems.+ */+/** Guards win over stem targets: the melody must clear the masking guard, so the lead may sit up to `LEAD_HEADROOM_DB` above its target before it is flagged. */+export const LEAD_HEADROOM_DB = 3;+export const stemBalance = (stems: Record<string, [Float32Array, Float32Array]>, targets: Record<string, number>, tolDb = 3, headroom: Record<string, number> = { lead: LEAD_HEADROOM_DB }) => {+ const rows: StemRow[] = Object.entries(stems).map(([id, [L]]) => { const rmsDb = stemRms(L), t = targets[id] ?? null, off = t === null ? null : rmsDb - t; return { id, rmsDb, targetDb: t, offDb: off, ok: off === null || (off >= -tolDb && off <= tolDb + (headroom[id] ?? 0)) }; });+ return { rows, pass: rows.every((r) => r.ok), tolDb, headroom };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/novelty.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/novelty.tsnew file mode 100644index 0000000..611d8b9--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/novelty.ts@@ -0,0 +1,72 @@+// NOVELTY: does a new score sound like one we already shipped? Alex heard "Daylight" as "almost the+// same as our launch track" although its key, chords and pitches were new: every layer kept the+// launch's RHYTHMS, the same contour, the same chord colours and the same form. So the fingerprint+// is mostly rhythm and shape, not pitch:+// melody rhythm (onset positions per bar, inter-onset n-grams), melody contour (up/down n-grams),+// melody intervals (transposition-free n-grams), other lines' rhythm (counter, bass), drum bars,+// chord function (root vs key + quality) n-grams, chord-quality n-grams, section-kind sequence.+// Each feature is a bag of n-grams; similarity is the cosine of the bags; the score is a weighted+// mean. `demoReuse` is the stricter gate: any 6-note melody fragment (intervals + durations) taken+// from a demo fails outright, transposed or not.+import type { Piece, Note } from "./plan";+import { beatsPerBar } from "./plan";+import { pcOf } from "./theory";++type Bag = Map<string, number>;+export type Fingerprint = Record<Feature, Bag>;+export type Feature = "melodyRhythm" | "melodyContour" | "melodyIntervals" | "lineRhythm" | "drums" | "chords" | "qualities" | "form";+export const NOVELTY_WEIGHTS: Record<Feature, number> = { melodyRhythm: 0.2, melodyContour: 0.15, melodyIntervals: 0.1, lineRhythm: 0.15, drums: 0.15, chords: 0.1, qualities: 0.07, form: 0.08 };+/** Above this a piece is too close to a shipped one. Calibrated: the copy fixture scores far above it, unrelated demos far below (tools/music-unit.mjs). */+export const NOVELTY_THRESHOLD = 0.5;++const add = (b: Bag, k: string, w = 1) => b.set(k, (b.get(k) ?? 0) + w);+const q = (x: number) => Math.round(x * 12); // 1/12 beat: 16ths and triplets both land+const grams = <T>(xs: T[], n: number, f: (g: T[]) => string, b: Bag, prefix = "") => { for (let i = 0; i + n <= xs.length; i++) add(b, prefix + f(xs.slice(i, i + n))); };+/** One voice per role: the top note of each onset (bass: the bottom). */+const voice = (notes: Note[], low = false) => { const by = new Map<number, Note>(); for (const n of notes) { const k = Math.round(n.t * 96), o = by.get(k); if (!o || (low ? n.p < o.p : n.p > o.p)) by.set(k, n); } return [...by.values()].sort((a, b) => a.t - b.t); };+const quality = (name: string) => { const s = name.replace(/^[A-G][#b]?/, "").split("/")[0]; return /^(maj|M|Δ)/.test(s) ? "maj7" : /^(m|min|-)(?!aj)/.test(s) ? (/b5|ø/.test(s) ? "hdim" : "min") : /dim|°/.test(s) ? "dim" : /aug|\+/.test(s) ? "aug" : /sus/.test(s) ? "sus" : /\d/.test(s) ? "dom" : "maj"; };++export const fingerprint = (p: Piece): Fingerprint => {+ const bpb = beatsPerBar(p.plan.meter), F = Object.fromEntries(Object.keys(NOVELTY_WEIGHTS).map((k) => [k, new Map()])) as Fingerprint;+ const role = (r: string) => p.parts.flatMap((pt) => pt.notes.filter((n) => n.role === r));+ const rhythm = (ns: Note[], b: Bag, pre: string) => {+ const bars = new Map<number, number[]>(); for (const n of ns) { const bar = Math.floor(n.t / bpb + 1e-9); (bars.get(bar) ?? bars.set(bar, []).get(bar)!).push(q(n.t - bar * bpb)); }+ for (const pos of bars.values()) add(b, `${pre}bar:${pos.join(",")}`);+ const ioi = ns.slice(1).map((n, i) => q(n.t - ns[i].t)); grams(ioi, 3, (g) => g.join(","), b, `${pre}ioi:`);+ };+ const mel = voice(role("melody"));+ rhythm(mel, F.melodyRhythm, "");+ const iv = mel.slice(1).map((n, i) => n.p - mel[i].p);+ grams(iv.map((x) => (x > 0 ? "u" : x < 0 ? "d" : "s")), 4, (g) => g.join(""), F.melodyContour);+ grams(iv, 3, (g) => g.join(","), F.melodyIntervals);+ rhythm(voice(role("color")), F.lineRhythm, "color:"); rhythm(voice(role("bass"), true), F.lineRhythm, "bass:");+ for (const pt of p.parts) if (pt.role === "drum") { const bars = new Map<number, number[]>(); for (const n of pt.notes) { const bar = Math.floor(n.t / bpb + 1e-9); (bars.get(bar) ?? bars.set(bar, []).get(bar)!).push(q(n.t - bar * bpb)); } for (const pos of bars.values()) add(F.drums, `${pt.inst}${pt.opts?.rim ? "rim" : ""}:${[...new Set(pos)].sort((a, b) => a - b).join(",")}`); }+ const tonic = pcOf(p.plan.sections[0].key.replace(/m$/, "")), seq: string[] = [], qs: string[] = [];+ for (const c of p.harmony.slice().sort((a, b) => a.t - b.t)) { const m = /^([A-G][#b]?)/.exec(c.name); if (!m) continue; const f = `${(pcOf(m[1]) - tonic + 12) % 12}${quality(c.name)}`; if (seq[seq.length - 1] !== f) { seq.push(f); qs.push(quality(c.name)); } }+ grams(seq, 3, (g) => g.join(" "), F.chords); grams(qs, 3, (g) => g.join(" "), F.qualities);+ const kinds = (p.arrangement ?? []).map((a) => a.kind); grams(kinds, 2, (g) => g.join(">"), F.form);+ return F;+};++const cosine = (a: Bag, b: Bag) => { let d = 0, na = 0, nb = 0; for (const [k, v] of a) { na += v * v; const w = b.get(k); if (w) d += v * w; } for (const v of b.values()) nb += v * v; return na && nb ? d / Math.sqrt(na * nb) : 0; };+/** 0 = nothing in common, 1 = the same music. Features empty in both pieces are left out of the mean. */+export const similarity = (a: Fingerprint, b: Fingerprint) => {+ let s = 0, w = 0; const by: Partial<Record<Feature, number>> = {};+ for (const f of Object.keys(NOVELTY_WEIGHTS) as Feature[]) { if (!a[f].size && !b[f].size) continue; const c = cosine(a[f], b[f]); by[f] = +c.toFixed(3); s += c * NOVELTY_WEIGHTS[f]; w += NOVELTY_WEIGHTS[f]; }+ return { score: w ? s / w : 0, by };+};++/** Every melody 6-note fragment as (interval, duration) pairs: transposition-free. */+const fragments = (p: Piece) => { const mel = voice(p.parts.flatMap((pt) => pt.notes.filter((n) => n.role === "melody" || n.role === "color"))); const out = new Set<string>(); for (let i = 0; i + 6 <= mel.length; i++) { const g = mel.slice(i, i + 6); out.add(g.slice(1).map((n, j) => `${n.p - g[j].p}/${q(n.t - g[j].t)}`).join(" ")); } return out; };++/** Score a piece against a corpus. `family` names the pieces that ARE this piece (its own cuts) and are skipped. */+export const novelty = (p: Piece, corpus: Record<string, () => Piece>, skip: string[] = [], threshold = NOVELTY_THRESHOLD) => {+ const fp = fingerprint(p), mine = fragments(p);+ const rows = Object.entries(corpus).filter(([name]) => !skip.includes(name)).map(([name, mk]) => {+ const other = mk(), sim = similarity(fp, fingerprint(other)), theirs = fragments(other);+ let reused = 0; for (const f of mine) if (theirs.has(f)) reused++;+ return { name, score: +sim.score.toFixed(3), by: sim.by, reusedFragments: reused };+ }).sort((a, b) => b.score - a.score);+ const worst = rows[0];+ return { rows, threshold, pass: rows.every((r) => r.score <= threshold && r.reusedFragments === 0), worst };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/orchestra.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/orchestra.tsnew file mode 100644index 0000000..1dd887b--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/orchestra.ts@@ -0,0 +1,110 @@+// ORCHESTRA AND BAND VOICES, added for breadth (orchestral, choral, suspense, rock, synthwave,+// world). Procedural approximations, deterministic, pure in (keys, sr, n, opts, rng). Acoustic+// timbres made this way are approximations: a human listens before one carries a film (spec 08+// DECISION B). Each voice states the physics it borrows.+import { type Rng, TAU, clamp, pan, SVF, blep, gauss } from "./dsp";+import type { Played } from "./perform";++type Out = { L: Float32Array; R: Float32Array };+type Opts = Record<string, number | boolean | string>;+const num = (o: Opts, k: string, d: number) => (typeof o[k] === "number" ? (o[k] as number) : d);+const f0 = (m: number) => 440 * Math.pow(2, (m - 69) / 12);+const out0 = (n: number): Out => ({ L: new Float32Array(n), R: new Float32Array(n) });+const byPitch = (p: number, w: number) => pan(clamp((p - 60) / 30, -1, 1) * w);+/** attack / sustain / release envelope for a held key */+const asr = (t: number, dur: number, atk: number, rel: number) => (t < dur ? Math.min(1, t / atk) : Math.min(1, dur / atk) * Math.exp(-(t - dur) / (rel / 4)));++/** Pipe organ: drawbar ranks (harmonics 1 2 3 4 6 8) summed per pipe, two detuned copies (chorus), a slow tremulant. `bright` weights the upper ranks. */+export const organ = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = out0(n), bright = num(o, "bright", 1), trem = num(o, "trem", 5.5), ranks = [[1, 1], [2, 0.7], [3, 0.35 * bright], [4, 0.35 * bright], [6, 0.18 * bright], [8, 0.12 * bright]];+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.15) * sr)), [gl, gr] = byPitch(k.p, 0.5);+ for (let i = 0; i < len; i++) { const t = i / sr, e = asr(t, dur, 0.015, 0.08) * k.v * 0.09 * (1 + 0.06 * Math.sin(TAU * trem * t));+ let s = 0; for (const [h, a] of ranks) if (f * h < sr / 2.2) s += a * (Math.sin(TAU * f * h * t) + Math.sin(TAU * f * h * 1.0012 * t + 1.3)) * 0.5;+ out.L[i0 + i] += s * e * gl; out.R[i0 + i] += s * e * gr; }+ }+ return out;+};++/** Brass: a PolyBLEP saw whose low-pass opens with loudness (the brass "bite"), the pitch rising ~25 cents into the note, vibrato delayed. `attack`, `bright`. */+export const brass = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = out0(n), atk = num(o, "attack", 0.06), bright = num(o, "bright", 1), w = num(o, "width", 0.5);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.3) * sr)), lp = new SVF(sr, 800, 0.8), [gl, gr] = byPitch(k.p, w); let ph = 0;+ for (let i = 0; i < len; i++) { const t = i / sr, e = asr(t, dur, atk, 0.25), cents = -25 * Math.exp(-t / 0.05) + (t > 0.25 ? 12 * Math.sin(TAU * 5.2 * t) * Math.min(1, (t - 0.25) / 0.3) : 0), inc = (f * Math.pow(2, cents / 1200)) / sr;+ ph += inc; if (ph >= 1) ph -= 1; if ((i & 15) === 0) lp.set(clamp(f * (1.5 + 7 * e * k.v * bright), 200, 12000), 0.8);+ const y = lp.tick(2 * ph - 1 - blep(ph, inc)) * e * k.v * 0.22; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; }+ }+ return out;+};++/** Woodwind: flute (sine + weak 2nd/3rd + breath noise at the pitch) or `reed: true` clarinet (odd harmonics, darker). Delayed vibrato. */+export const woodwind = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {+ const out = out0(n), reed = o.reed === true, breath = num(o, "breath", reed ? 0.02 : 0.08), w = num(o, "width", 0.3);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.2) * sr)), bp = new SVF(sr, f, 4), [gl, gr] = byPitch(k.p, w); let ph = 0;+ for (let i = 0; i < len; i++) { const t = i / sr, e = asr(t, dur, reed ? 0.04 : 0.07, 0.15), vib = t > 0.2 ? 1 + 0.004 * Math.sin(TAU * 5 * t) * Math.min(1, (t - 0.2) / 0.3) : 1;+ ph += (f * vib) / sr; if (ph >= 1) ph -= 1; const x = TAU * ph;+ const tone = reed ? Math.sin(x) + 0.33 * Math.sin(3 * x) + 0.18 * Math.sin(5 * x) + 0.08 * Math.sin(7 * x) : Math.sin(x) + 0.12 * Math.sin(2 * x) + 0.05 * Math.sin(3 * x);+ bp.tick(gauss(r)); const y = (tone * 0.8 + bp.bp * breath * 6) * e * k.v * 0.16; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; }+ }+ return out;+};++const VOWELS: Record<string, [number, number, number]> = { a: [700, 1220, 2600], o: [450, 800, 2830], u: [325, 700, 2530], e: [530, 1840, 2480], i: [300, 2200, 3000] };+/** Choir: three detuned saws per note through the formants of a vowel (`vowel`: a o u e i), slow attack. Texture and pads; never a lead. */+export const choir = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {+ const out = out0(n), fm = VOWELS[String(o.vowel ?? "a")] ?? VOWELS.a, atk = num(o, "attack", 0.35), w = num(o, "width", 0.8);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.8) * sr));+ const dets = [-9, 0, 8], phs = dets.map(() => r()), vr = dets.map(() => 4.5 + r()), pans = dets.map((_, j) => pan((j - 1) * w));+ const fl = [0, 1].map(() => fm.map((q, j) => new SVF(sr, q, [9, 11, 13][j])));+ for (let i = 0; i < len; i++) { const t = i / sr, e = asr(t, dur, atk, 0.7) * k.v * 0.14; let sl = 0, sR = 0;+ for (let v = 0; v < 3; v++) { const inc = (f * Math.pow(2, (dets[v] + 10 * Math.sin(TAU * vr[v] * t)) / 1200)) / sr; let ph = phs[v] + inc; if (ph >= 1) ph -= 1; phs[v] = ph; const s = 2 * ph - 1 - blep(ph, inc); sl += s * pans[v][0]; sR += s * pans[v][1]; }+ let yl = 0, yr = 0; for (let j = 0; j < 3; j++) { fl[0][j].tick(sl); fl[1][j].tick(sR); yl += fl[0][j].bp * [1, 0.6, 0.3][j]; yr += fl[1][j].bp * [1, 0.6, 0.3][j]; }+ out.L[i0 + i] += yl * e; out.R[i0 + i] += yr * e; }+ }+ return out;+};++/** Timpani (`pitch`: a MIDI note to tune it when it plays a drum lane): a tuned membrane (modal partials 1, 1.5, 1.99, 2.44, 2.97 with their own decays), a small downward pitch settle, a felt-mallet thump. Pitched on the note. */+export const timpani = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {+ const out = out0(n), dec = num(o, "decay", 1.6), P = [[1, 1, 1], [1.5, 0.5, 0.7], [1.99, 0.35, 0.5], [2.44, 0.2, 0.35], [2.97, 0.12, 0.25]];+ for (const k of keys) {+ const f = f0(typeof o.pitch === "number" ? (o.pitch as number) : k.p), i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil(dec * 4 * sr)), lp = new SVF(sr, 400, 0.7);+ for (let i = 0; i < len; i++) { const t = i / sr, bend = 1 + 0.03 * Math.exp(-t / 0.08); let s = 0;+ for (const [h, a, d] of P) s += a * Math.sin(TAU * f * h * bend * t) * Math.exp(-t / (dec * d));+ lp.tick(gauss(r)); const y = (s + lp.lp * Math.exp(-t / 0.012) * 3) * k.v * 0.3; out.L[i0 + i] += y; out.R[i0 + i] += y * 0.97; }+ }+ return out;+};++/** Lead synth: monophonic saw + square, portamento `glide` s between touching notes, a filter envelope re-struck each note, vibrato blooming on long notes (spec 06 lead). */+export const leadSynth = (keys: Played[], sr: number, n: number, o: Opts): Out => {+ const out = out0(n), glide = num(o, "glide", 0.03), cut = num(o, "cut", 1700), envAmt = num(o, "env", 4500), sq = num(o, "square", 0.4), [gl, gr] = pan(num(o, "pan", 0));+ const ks = keys.slice().sort((a, b) => a.t - b.t); let prevF = 0, prevOff = -1, ph = 0, ph2 = 0; const lp = new SVF(sr, cut, 1.2);+ ks.forEach((k, idx) => {+ const f = f0(k.p), i0 = Math.round(k.t * sr), nextT = idx + 1 < ks.length ? ks[idx + 1].t : Infinity, dur = Math.min(k.off, nextT) - k.t, tail = nextT < k.off + 0.12 ? nextT - k.t : dur + 0.12;+ const len = Math.min(n - i0, Math.ceil(Math.max(0.01, tail) * sr)), from = prevF && k.t - prevOff < 0.05 ? prevF : f;+ for (let i = 0; i < len; i++) { const t = i / sr, fr = from + (f - from) * Math.min(1, t / Math.max(1e-4, glide)), vib = t > 0.3 ? 1 + 0.006 * Math.sin(TAU * 5.5 * t) * Math.min(1, (t - 0.3) / 0.4) : 1, inc = (fr * vib) / sr;+ ph += inc; if (ph >= 1) ph -= 1; ph2 += inc; if (ph2 >= 1) ph2 -= 1;+ const e = Math.min(1, t / 0.006) * (t < dur ? 1 : Math.exp(-(t - dur) / 0.03));+ if ((i & 15) === 0) lp.set(clamp(cut + envAmt * k.v * Math.exp(-t / 0.18), 150, 14000), 1.2);+ const y = lp.tick((2 * ph - 1 - blep(ph, inc)) + sq * (ph2 < 0.5 ? 1 : -1)) * e * k.v * 0.18; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; }+ prevF = f; prevOff = k.t + dur;+ });+ return out;+};++/** Bowed solo (violin / cello): one saw with delayed vibrato and bow noise through body resonances (~280, 450, 2800 Hz), a bowed attack. */+export const bowedSolo = (keys: Played[], sr: number, n: number, o: Opts, r: Rng): Out => {+ const out = out0(n), atk = num(o, "attack", 0.09), vibC = num(o, "vibrato", 22), [gl, gr] = pan(num(o, "pan", -0.1));+ const body = o.cello === true ? [140, 300, 1600] : [280, 450, 2800];+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.35) * sr)), bs = body.map((q) => new SVF(sr, q, 2.2)), lp = new SVF(sr, 5000, 0.7); let ph = 0;+ for (let i = 0; i < len; i++) { const t = i / sr, e = asr(t, dur, atk, 0.3), vib = t > 0.15 ? vibC * Math.sin(TAU * 5.6 * t) * Math.min(1, (t - 0.15) / 0.35) : 0, inc = (f * Math.pow(2, vib / 1200)) / sr;+ ph += inc; if (ph >= 1) ph -= 1; const x = 2 * ph - 1 - blep(ph, inc) + gauss(r) * 0.06;+ let y = lp.tick(x) * 0.35; for (const b of bs) { b.tick(x); y += b.bp * 0.5; } y *= e * k.v * 0.16; out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; }+ }+ return out;+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/perform.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/perform.tsindex 56783c9..3b0aa62 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/perform.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/perform.ts@@ -64,7 +64,7 @@ export const perform = (p: Piece, tempo: number, o: PerformOpts): Performance =>const hi = n.role === "melody" ? 1 + 0.06 * ((n.p - 72) / 12) : 1;// written v 0.7 = mezzo; section level 0..1 maps to 0.25..0.85 of full velocityv = (n.v / 0.7) * (0.25 + 0.6 * lv) * (0.92 + 0.16 * arch(x)) * (grid ? 1 : metric * hi) * (isPiano ? RoleGain[n.role] : 1 / (0.25 + 0.6 * 0.75)) + vDev;- if (n.t > ritFrom) v *= 1 - 0.18 * clamp((n.t - ritFrom) / ritBeats, 0, 1); // the cadence relaxes+ if (n.t > ritFrom && !plan.loop) v *= 1 - 0.18 * clamp((n.t - ritFrom) / ritBeats, 0, 1); // the cadence relaxest += tDev;if (n.role === "melody" && isPiano) { const ld = 0.012 + 0.016 * clamp(v, 0, 1); t -= ld; leadSum += ld; leadN++; }if (n.roll !== undefined) t += chordIdx * n.roll; else if (chordIdx > 0 && !grid) t += chordIdx * 0.004;diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/copyFixture.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/copyFixture.tsnew file mode 100644index 0000000..258b9ff--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/copyFixture.ts@@ -0,0 +1,34 @@+// COPY FIXTURE (a test fixture, never a score). "Daylight" was offered as a lo-fi electronic example+// and Alex heard it at once: "almost the same as our launch track". It changed the key (D), the+// chords (I-vi-IV-V) and the pitches, but kept the launch's rhythms in every layer (hook cell per+// chord, sparkle answer, sub root + walk, the same drum bars) and its arrangement. The novelty gate+// (novelty.ts) must score it as a copy of launchLofi3: that is the proof the gate hears what she heard.+import type { Piece } from "../plan";+import { composePiece, type Material } from "../compose";++const HATS = Array.from({ length: 16 }, (_, i) => `C4:.25@${[0.85, 0.35, 0.6, 0.4][i % 4]}`).join(" ");+export const daylightCopyMaterial = (): Material => ({+ style: "lofiElectronic", title: "Daylight (copy fixture)", seed: 96, mood: "joy", bpm: 96, key: "D", mode: "major", swing: 0.54,+ chords: {+ Dmaj9: { voicing: "[F#3 A3 C#4 E4]", bass: "D2:3 r:.5 A1:.5" }, Bm9: { voicing: "[F#3 A3 C#4 D4]", bass: "B1:3 r:.5 F#1:.5" },+ Gmaj9: { voicing: "[F#3 A3 B3 D4]", bass: "G1:3 r:.5 D2:.5" }, A13: { voicing: "[G3 B3 C#4 F#4]", bass: "A1:3 r:.5 E2:.5" },+ },+ motifs: {+ h0: "r:.5 F#4:.5 A4:.5 D5:1 C#5:.5 A4:1", h1: "r:.5 F#4:.5 B4:.5 C#5:.5 D5:1 B4:1", h2: "r:.5 D5:.5 E5:.5 F#5:1 E5:.5 D5:1", h3: "C#5:1.5 B4:.5 A4:1 r:1",+ s0: "r:1 A5:.5 C#6:.5 E6:2", s1: "r:1 F#5:.5 A5:.5 C#6:2", s2: "r:1 F#6:.5 D6:.5 B5:2", s3: "C#6:1 B5:1 A5:2",+ },+ grooves: {+ main: { kick: ["C4:1.5 C4:[email protected] C4:[email protected]", "C4:1.5 C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]"], snare: ["r:1 C4:2 C4:1"], ghost: ["r:3.75 C4:[email protected]", "r:1.75 C4:[email protected] r:2"], hat: [HATS], cycle: "piece" },+ half: { kick: ["C4:2 r:2"], snare: ["r:2 C4:2"], hat: ["C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]"], cycle: "piece" },+ },+ sections: [+ { kind: "intro", bars: 2, harmony: ["Gmaj9", "A13"], chordVel: 0.8 },+ { kind: "hook", bars: 4, harmony: ["Dmaj9", "Bm9", "Gmaj9", "A13"], lead: ["h0", "h1", "h2", "h3"] },+ { kind: "hook", bars: 4, harmony: ["Dmaj9", "Bm9", "Gmaj9", "A13"], lead: ["h0", "h1", "h2", "h3"], counter: ["s0", "s1", "s2", "s3"] },+ { kind: "half", bars: 2, harmony: ["Dmaj9", "Bm9"], counter: ["s0", "s1"] },+ { kind: "breakdown", bars: 2, harmony: ["Gmaj9", "A13"] },+ { kind: "drop", bars: 1, harmony: ["Dmaj9"], lead: ["h0"] },+ { kind: "outro", bars: 2, harmony: ["Dmaj9"], chordVel: 0.75, bass: "D2:4", lead: ["r:4", "D5:4"] },+ ],+});+export const daylightCopy = (): Piece => composePiece(daylightCopyMaterial());diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.tsindex 7168799..d393837 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts@@ -14,6 +14,7 @@// [the live page] · 30-33 hook + sparkle [the film] · 34-35 breakdown, drums out [the reveal] ·// 36 everything back [All in pure code.] · 37-38 outro, Cmaj9 held [the end card].import { line, type Note, type Piece, type Role } from "../plan";+import { composePiece, type Material } from "../compose";export const LAUNCH_BPM = 90, LAUNCH_BARS = 39;const L = (t: number, s: string, role: Role, v = 0.7, extra: { roll?: number } = {}) => line(t, s, { role, v, bpb: 4, ...extra });@@ -66,24 +67,39 @@ export const launchLofi2 = (): Piece => {// 11-13 hook [bricks] · 14-15 half-time [Van Gogh] · 16 sparkle [LOOPS] · 17-21 groove, hook from// 19 [INTERACTIVE, the site] · 22-23 sparkle [FILMS, the film] · 24-25 breakdown [the five words] ·// 26 everything back [All in pure code.] · 27-28 home [the end card].+// Written as composed material on the lo-fi electronic vocabulary (compose.ts); its audio is+// bit-identical to the hand-written v6 (md5 of renderPiece at 48 kHz d20789f2344e6fff0d2a380c7c7825d2,+// guarded by tools/music-unit.mjs). This is OUR film's score: a demo, never a template (the novelty+// gate fails any film that reuses it).export const LAUNCH3_BARS = 29;-export const launchLofi3 = (): Piece => {- const B = LAUNCH3_BARS, last = B - 1, ci = (b: number) => (b < 2 ? -1 : b % 4);- const bars = (fn: (b: number, c: number) => string | null, role: Role, v: number, extra: { roll?: number } = {}): Note[] => { const out: Note[] = []; for (let b = 0; b < B; b++) { const x = fn(b, ci(b)); if (x) out.push(...L(b * 4, x, role, v, extra)); } return out; };- const full: [number, number][] = [[2, 13], [16, 23], [26, 26]], half: [number, number][] = [[14, 15]];- const pad = bars((b, c) => (b >= 27 ? `${PAD[2]}:[email protected]` : c < 0 ? `${PAD_INTRO[b]}:[email protected]` : `${PAD[c]}:4`), "accomp", 0.62, { roll: 0.03 });- const sub = bars((b, c) => (c < 0 || inRanges(b, [[24, 25]]) ? null : b >= 27 ? "C2:4" : SUB[c]), "bass", 0.85);- const kick = bars((b) => (inRanges(b, full) ? KICK[b % 2] : inRanges(b, half) ? "C4:2 r:2" : null), "drum", 0.85);- const snare = bars((b) => (inRanges(b, full) ? "r:1 C4:2 C4:1" : inRanges(b, half) ? "r:2 C4:2" : null), "drum", 0.7);- const ghost = bars((b) => (inRanges(b, full) ? (b % 2 ? "r:1.75 C4:[email protected] r:2" : "r:3.75 C4:[email protected]") : null), "drum", 0.5);- const hats = bars((b) => (inRanges(b, full) ? HATS : inRanges(b, half) ? "C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]" : null), "drum", 0.5);- const lead = bars((b, c) => (inRanges(b, [[6, 13], [19, 21], [26, 26]]) ? HOOK[c] : b === last ? "C5:4" : null), "melody", 0.72);- const sparkle = bars((b, c) => (inRanges(b, [[8, 10], [16, 16], [22, 25]]) ? SPARK[c] : null), "color", 0.5);- const harmony = Array.from({ length: B }, (_, b) => ({ t: b * 4, name: b < 2 ? ["Cmaj9", "Am9"][b] : b >= 27 ? "Cmaj9" : ["Dm9", "G13", "Cmaj9", "Am9"][b % 4] }));- const base = launchLofi();- return { ...base, title: "anidoodle launch, cut 3", harmony, plan: { ...base.plan, sections: [{ ...base.plan.sections[0], bars: B }] },- parts: base.parts.map((pt) => ({ ...pt, notes: ({ pad, lead, sparkle, sub, kick, snare, ghost, hat: hats } as Record<string, Note[]>)[pt.id] })) };+export const launchLofi3Material = (): Material => {+ const hk = (i: number) => `hook${i}`, sp = (i: number) => `spark${i}`;+ return {+ style: "lofiElectronic", title: "anidoodle launch, cut 3", seed: 2027, mood: "calm", bpm: LAUNCH_BPM, key: "C", mode: "major", swing: 0.54, tail: 3.2,+ chords: { Dm9: { voicing: PAD[0], bass: SUB[0] }, G13: { voicing: PAD[1], bass: SUB[1] }, Cmaj9: { voicing: PAD[2], bass: SUB[2] }, Am9: { voicing: PAD[3], bass: SUB[3] } },+ motifs: Object.fromEntries([...HOOK.map((h, i) => [hk(i), h]), ...SPARK.map((x, i) => [sp(i), x])]),+ grooves: {+ main: { kick: [KICK[0], KICK[1]], snare: ["r:1 C4:2 C4:1"], ghost: ["r:3.75 C4:[email protected]", "r:1.75 C4:[email protected] r:2"], hat: [HATS], cycle: "piece" },+ half: { kick: ["C4:2 r:2"], snare: ["r:2 C4:2"], hat: ["C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]"], cycle: "piece" },+ },+ sections: [+ { kind: "intro", bars: 2, harmony: ["Cmaj9", "Am9"], chordVel: 0.8 },+ { kind: "groove", bars: 4, harmony: ["Cmaj9", "Am9", "Dm9", "G13"] },+ { kind: "hook", bars: 2, harmony: ["Cmaj9", "Am9"], lead: [hk(2), hk(3)] },+ { kind: "hook", bars: 3, harmony: ["Dm9", "G13", "Cmaj9"], lead: [hk(0), hk(1), hk(2)], counter: [sp(0), sp(1), sp(2)] },+ { kind: "hook", bars: 3, harmony: ["Am9", "Dm9", "G13"], lead: [hk(3), hk(0), hk(1)] },+ { kind: "half", bars: 2, harmony: ["Cmaj9", "Am9"] },+ { kind: "groove", bars: 1, harmony: ["Dm9"], counter: [sp(0)] },+ { kind: "groove", bars: 2, harmony: ["G13", "Cmaj9"] },+ { kind: "hook", bars: 3, harmony: ["Am9", "Dm9", "G13"], lead: [hk(3), hk(0), hk(1)] },+ { kind: "groove", bars: 2, harmony: ["Cmaj9", "Am9"], counter: [sp(2), sp(3)] },+ { kind: "breakdown", bars: 2, harmony: ["Dm9", "G13"], counter: [sp(0), sp(1)] },+ { kind: "drop", bars: 1, id: "claim", harmony: ["Cmaj9"], lead: [hk(2)] },+ { kind: "outro", bars: 2, harmony: ["Cmaj9"], chordVel: 0.75, bass: "C2:4", lead: ["r:4", "C5:4"] },+ ],+ };};+export const launchLofi3 = (): Piece => composePiece(launchLofi3Material());export const launchLofi = (): Piece => {const full: [number, number][] = [[2, 18], [23, 33], [36, 36]], half: [number, number][] = [[19, 22]], last = LAUNCH_BARS - 1;diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.tsindex a1148a6..6b911a0 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/plan.ts@@ -1,16 +1,18 @@// MusicPlan and notes as data (spec 08 section 2), a small bar-checked notation so a composer// writes real lines instead of arrays of numbers, the plan validator, and `arrange`, which fits// a piece to ANY film duration (tempo inside the style's range, then repeat or drop sections).-import { midi, type ModeId, MODES, detectMode, pcOf } from "./theory";+import { midi, type ModeId, MODES, detectMode, pcOf, modeFit } from "./theory";import { MOODS, STYLES, REFUSED_BLENDS, type MoodId, type StyleId, type MelodyType } from "./tables";-export type Meter = "3/4" | "4/4" | "6/8" | "12/8";-export const beatsPerBar = (m: Meter) => (m === "3/4" ? 3 : m === "4/4" ? 4 : m === "6/8" ? 2 : 4);+export type Meter = "2/4" | "3/4" | "4/4" | "5/4" | "6/8" | "7/8" | "9/8" | "12/8";+/** Beats per bar. Simple meters count quarters (7/8 = 3.5 quarters, write eighths as .5); compound meters (6/8, 9/8, 12/8) count dotted quarters (write eighths as 1/3). */+export const beatsPerBar = (m: Meter) => ({ "2/4": 2, "3/4": 3, "4/4": 4, "5/4": 5, "6/8": 2, "7/8": 3.5, "9/8": 3, "12/8": 4 })[m];+export const isCompound = (m: Meter) => m === "6/8" || m === "9/8" || m === "12/8";export type Role = "melody" | "inner" | "bass" | "accomp" | "color" | "drum";/** t, d in beats from the piece start; p = MIDI; v = written velocity 0..1 (performance shapes it). */export type Note = { t: number; d: number; p: number; v: number; role: Role; roll?: number; kind?: string };-export type InstId = "piano" | "musicBox" | "bell" | "celesta" | "marimba" | "vibes" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "pulse" | "triangle" | "noiseDrum" | "kick" | "snare" | "hat" | "bass" | "vinyl" | "warmPad" | "softPluck" | "sub";+export type InstId = "piano" | "musicBox" | "bell" | "celesta" | "marimba" | "vibes" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "pulse" | "triangle" | "noiseDrum" | "kick" | "snare" | "hat" | "bass" | "vinyl" | "warmPad" | "softPluck" | "sub" | "organ" | "brass" | "woodwind" | "choir" | "timpani" | "leadSynth" | "bowedSolo";export type Part = { id: string; inst: InstId; role: Role; notes: Note[]; gainDb?: number; pan?: number; opts?: Record<string, number | boolean | string>; send?: number };export type Section = {id: string; bars: number; mood: MoodId | [MoodId, MoodId, number]; key: string; mode: ModeId; melody: MelodyType[];@@ -21,12 +23,17 @@ export type Section = {};export type MusicPlan = { style: StyleId; tempo: number; meter: Meter; sections: Section[]; pickupBeats?: number; swing?: number; phraseBars?: number; sync?: string[];/** tempo-arch depth per phrase (1 = +-2.5 %); final ritard end-tempo ratio (1 = none) */ rubato?: number; ritard?: number;+ /** a seamless loop (renderLoop): the end must not relax into a cadence */ loop?: boolean;/** room override (the guards' bad fixture uses it; films normally take the style's room) */ space?: { er?: number; late?: number; rt60?: number; hp?: number } };export type Chord = { t: number; name: string };/** Bus moves (lofiKit): `duck` pumps the named parts on every onset of the `by` part; `tape` wobbles and saturates the master. */export type PieceFx = { clean?: boolean /* skip the lo-fi master tone (low-pass, shelf, saturation) */; duck?: { by: string; parts: string[]; depth?: number; release?: number }; tape?: { wowCents?: number; wowHz?: number; flutterCents?: number; flutterHz?: number; drive?: number } };export type Piece = { title: string; plan: MusicPlan; parts: Part[]; harmony: Chord[]; tail: number; seed: number; fx?: PieceFx;- /** a shorter complete form of the same music, chosen automatically when the film is too short for this one */ shortForm?: () => Piece };+ /** a shorter complete form of the same music, chosen automatically when the film is too short for this one */ shortForm?: () => Piece;+ /** rebuild the same music for a film `seconds` long so it still ends on its phrase (lofiElectronic: loop cycles added or removed); `fitScore` calls it before fitToDuration */ refit?: (seconds: number) => Piece;+ /** composer-facing notes from compose (a line shorter than its section, ...): printed by tools/music.mjs check */ warnings?: string[];+ /** mix targets: RMS dBFS of each part's stem, measured over its active samples (`stemBalance`) */ stemTargets?: Record<string, number>;+ /** the arrangement as bar ranges, for the score and the docs (the plan may keep a single dynamics section) */ arrangement?: { id: string; kind: string; from: number; bars: number }[] };// ---------------------------------------------------------------- notation// "Eb4:1 | C5:2 Bb4:.5 Ab4:.5 | [Ab2 Eb3]:1 r:2 | G5:1/[email protected] ..." ; a token is NOTE:DUR[@VEL] or@@ -68,8 +75,11 @@ export const planProblems = (p: Piece): string[] => {if (notes.length) {const top = detectMode(notes, [s.mode, "major", "aeolian", "dorian", "mixolydian", "lydian"]);const want = pcOf(s.key.replace(/m$/, ""));- const hit = top.slice(0, 2).some((c) => pcOf(c.tonic) === want && c.mode === s.mode) || top.slice(0, 2).some((c) => c.mode === s.mode);- if (!hit) probs.push(`${s.id}: declared ${s.key} ${s.mode}, notes measure ${top.map((c) => `${c.tonic} ${c.mode}`).join(" / ")}`);+ const hit = top.slice(0, 2).some((c) => pcOf(c.tonic) === want && c.mode === s.mode);+ // a mode shares its notes with its relatives (D dorian = C major): accept the declared tonic when its scale explains the notes+ // as well as the winner does and the tonic is heard (>= 8 % of note time). Otherwise the tonic is not dominant enough.+ const fit = modeFit(notes, want, s.mode), best = modeFit(notes, pcOf(top[0].tonic), top[0].mode);+ if (!hit && !(fit.inScale >= best.inScale - 0.02 && fit.tonicShare >= 0.08)) probs.push(`${s.id}: declared ${s.key} ${s.mode}, notes measure ${top.map((c) => `${c.tonic} ${c.mode}`).join(" / ")} (tonic ${s.key} is ${Math.round(fit.tonicShare * 100)} % of note time, ${Math.round(fit.inScale * 100)} % in scale): make the tonic heard (bass on it at section starts and cadences) and state the mode's colour note`);}b0 = hi;}diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.tsindex 20a9b6e..d14a4fb 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/render.ts@@ -6,9 +6,10 @@ import { type Piece, type Part, resequence, beatsPerBar } from "./plan";import { perform, type Performance, type Played } from "./perform";import { renderPiano, PIANO_REAL, type PianoOpts } from "./piano";import * as I from "./instruments";+import * as O from "./orchestra";import { room, Biquad, db } from "./dsp";import { warmPad, softPluck, sub, duckCurve, tape } from "./lofiKit";-import { loudness, truePeak } from "./meter";+import { loudness, truePeak, stemBalance } from "./meter";import { STYLES } from "./tables";import { rng as mkRng } from "../core";@@ -40,6 +41,13 @@ const voice = (pt: Part, keys: Played[], sr: number, n: number, seed: number) =>case "warmPad": return warmPad(keys, sr, n, o, r);case "softPluck": return softPluck(keys, sr, n, o);case "sub": return sub(keys, sr, n, o);+ case "organ": return O.organ(keys, sr, n, o);+ case "brass": return O.brass(keys, sr, n, o);+ case "woodwind": return O.woodwind(keys, sr, n, o, r);+ case "choir": return O.choir(keys, sr, n, o, r);+ case "timpani": return O.timpani(keys, sr, n, o, r);+ case "leadSynth": return O.leadSynth(keys, sr, n, o);+ case "bowedSolo": return O.bowedSolo(keys, sr, n, o, r);default: throw new Error(`no instrument ${pt.inst}`);}};@@ -86,19 +94,51 @@ export const renderPiece = (piece: Piece, sr: number, o: RenderOpts = {}): Rendeif (style.id === "lofi" && !piece.fx?.clean) { for (const c of [L, R]) { Biquad.make(sr, "lp", 8500, 0.6).run(c); Biquad.make(sr, "highshelf", 5000, 0.7, -3).run(c); for (let i = 0; i < n; i++) c[i] = Math.tanh(c[i] * 1.2) / 1.2; } }if (piece.fx?.tape) tape(L, R, sr, piece.fx.tape);const fade = Math.min(n, Math.round(0.25 * sr)); for (let i = 0; i < fade; i++) { const g = 0.5 - 0.5 * Math.cos((Math.PI * i) / fade); L[n - 1 - i] *= g; R[n - 1 - i] *= g; }- let gainDb = 0, masterMode = o.master ?? "auto";+ let masterMode = o.master ?? "auto";if (masterMode === "auto") masterMode = style.master;- if (masterMode !== "none") {- const target = masterMode === "dense" ? -14 : -16;- gainDb = target - loudness([L, R], sr).integrated;- for (let i = 0; i < n; i++) { L[i] *= db(gainDb); R[i] *= db(gainDb); }- const tp = truePeak([L, R]).dbtp;- if (tp > -1) {- if (masterMode === "gentle") { const cut = tp + 1.05; gainDb -= cut; for (let i = 0; i < n; i++) { L[i] *= db(-cut); R[i] *= db(-cut); } }- else { limiter(L, R, sr, db(-1.3)); const again = target - loudness([L, R], sr).integrated; if (again > 0) { const g = db(Math.min(again, 1)); for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; } limiter(L, R, sr, db(-1.3)); } }+ const gainDb = masterMode === "none" ? 0 : master(L, R, sr, masterMode as "gentle" | "dense");+ return { L, R, perf, tempo, gainDb, masterMode, stems, piece, dry, wet };+};++/** The master stage, in place. Gentle: one static gain to -16 LUFS, pulled down if the true peak passes -1 dBTP. Dense: -14 LUFS through the look-ahead limiter. Returns the gain in dB. */+export const master = (L: Float32Array, R: Float32Array, sr: number, masterMode: "gentle" | "dense"): number => {+ const n = L.length, target = masterMode === "dense" ? -14 : -16;+ let gainDb = target - loudness([L, R], sr).integrated;+ for (let i = 0; i < n; i++) { L[i] *= db(gainDb); R[i] *= db(gainDb); }+ const tp = truePeak([L, R]).dbtp;+ if (tp > -1) {+ if (masterMode === "gentle") { const cut = tp + 1.05; gainDb -= cut; for (let i = 0; i < n; i++) { L[i] *= db(-cut); R[i] *= db(-cut); } }+ else {+ limiter(L, R, sr, db(-1.3)); const again = target - loudness([L, R], sr).integrated; if (again > 0) { const g = db(Math.min(again, 1)); for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; } limiter(L, R, sr, db(-1.3)); }+ const tp2 = truePeak([L, R]).dbtp; // harsh waveforms (pulses) can still overshoot between samples: a last static trim+ if (tp2 > -1) { const cut = tp2 + 1.05; gainDb -= cut; for (let i = 0; i < n; i++) { L[i] *= db(-cut); R[i] *= db(-cut); } }}}- return { L, R, perf, tempo, gainDb, masterMode, stems, piece, dry, wet };+ return gainDb;+};++/**+ * A seamless loop of a `plan.loop` piece: rendered unmastered with its tail, the tail (reverb, delay+ * repeats, pad release) folded back onto the start, then mastered once. Tape wow and flutter are+ * snapped to a whole number of cycles per loop so the pitch drift meets itself at the seam.+ */+export const renderLoop = (piece: Piece, sr: number): Rendered & { loopS: number } => {+ const beats = piece.plan.sections.reduce((a, s) => a + s.bars * beatsPerBar(piece.plan.meter), 0), loopS = (beats * 60) / piece.plan.tempo;+ const snap = (hz: number) => Math.max(1, Math.round(hz * loopS)) / loopS, tp = piece.fx?.tape;+ const p: Piece = { ...piece, plan: { ...piece.plan, loop: true, ritard: 1 }, fx: piece.fx && { ...piece.fx, tape: tp && { ...tp, wowHz: snap(tp.wowHz ?? 0.45), flutterHz: snap(tp.flutterHz ?? 6.2) } } };+ const r = renderPiece(p, sr, { seconds: loopS + piece.tail, master: "none" }), n = Math.round(loopS * sr), L = r.L.slice(0, n), R = r.R.slice(0, n);+ for (let i = n; i < r.L.length; i++) { L[i - n] += r.L[i]; R[i - n] += r.R[i]; }+ const mode = STYLES[piece.plan.style].master, gainDb = master(L, R, sr, mode);+ return { ...r, L, R, gainDb, masterMode: mode, loopS };+};++/** The score for a film `seconds` long: the piece's own `refit` first (so it still ends on a phrase), then fitToDuration for the tempo. */+export const fitScore = (piece: Piece, seconds: number) => fitToDuration(piece.refit ? piece.refit(seconds) : piece, seconds);++/** Each part's stem level against the piece's targets (unmastered, pre-room: the mix as the parts were set). */+export const measureStems = (piece: Piece, sr: number, o: RenderOpts = {}, tolDb = 3) => {+ const r = renderPiece(piece, sr, { ...o, stems: true, master: "none" });+ return stemBalance(r.stems, piece.stemTargets ?? {}, tolDb);};/** Look-ahead peak limiter (1.5 ms look-ahead, 120 ms release), used by dense styles only. */@@ -150,6 +190,6 @@ export const fitToDuration = (piece: Piece, seconds: number): { piece: Piece; te/** What a Film's `audio(sampleRate)` returns: [L, R] at exactly the film's length. */export const filmAudio = (piece: Piece, seconds: number) => (sr: number): [Float32Array, Float32Array] => {- const fit = fitToDuration(piece, seconds), r = renderPiece(fit.piece, sr, { seconds, tempo: fit.tempo });+ const fit = fitScore(piece, seconds), r = renderPiece(fit.piece, sr, { seconds, tempo: fit.tempo });return [r.L, r.R];};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.tsnew file mode 100644index 0000000..15a3d41--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfx.ts@@ -0,0 +1,5 @@+// anidoodle sound effects: the kit (sfxKit), its building blocks (sfxCore) and film placement (sfxMix).+// Docs: references/music/sound-design.md. Tool: engine/tools/sfx.mjs.+export { SFX, SFX_KINDS, sfxVariants, sfxInfo, renderSfx, validateSfx, sfxNeeds, parseKey, type SfxKind, type SfxOpts, type SfxSound } from "./sfxKit";+export { placeSfx, sfxDuck, sfxAudibility, mixSfx, assertSfxAudible, filmSfx, validateSfxPlan, resolveSfxPlan, type SfxCue, type SfxPlan, type SfxSnap, type PlacedCue, type SfxAudibility, type SfxMix } from "./sfxMix";+export { type SfxStereo } from "./sfxCore";diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxCore.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxCore.tsnew file mode 100644index 0000000..b176594--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxCore.ts@@ -0,0 +1,166 @@+// Sound-effect building blocks. Every effect is built from LAYERS (a transient, a body, a tail),+// each a pure function of (sampleRate, rng). Nothing here reads a clock or Math.random, so the+// same seed always renders the same samples.+import { Biquad, SVF, pan as panGains, room, TAU, clamp, type Rng } from "./dsp";++export type SfxStereo = [Float32Array, Float32Array];+export const buf = (n: number) => new Float64Array(Math.max(0, Math.round(n)));+export const secs = (sr: number, s: number) => Math.max(0, Math.round(s * sr));++/** 32-bit integer hash of two values: per-cue seeds that stay put when other cues move. */+export const mixSeed = (a: number, b: number) => {+ let h = (Math.imul(a | 0, 0x9e3779b1) ^ Math.imul(b | 0, 0x85ebca6b)) >>> 0;+ h = Math.imul(h ^ (h >>> 16), 0x7feb352d) >>> 0; h = Math.imul(h ^ (h >>> 15), 0x846ca68b) >>> 0;+ return (h ^ (h >>> 16)) >>> 0;+};+export const strSeed = (s: string) => { let h = 2166136261; for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return h >>> 0; };++/** A stereo bus. Mono layers are placed with a pan (constant, or per sample) and an optional Haas offset (ms, + delays R). */+export class Bus {+ L: Float64Array; R: Float64Array;+ constructor(readonly sr: number, readonly n: number) { this.L = buf(n); this.R = buf(n); }+ add(sig: ArrayLike<number>, at = 0, g = 1, p: number | ((i: number) => number) = 0, haasMs = 0) {+ const d = Math.round((Math.abs(haasMs) * this.sr) / 1000), dL = haasMs < 0 ? d : 0, dR = haasMs > 0 ? d : 0;+ const fixed = typeof p === "number" ? panGains(p) : null;+ for (let i = 0; i < sig.length; i++) {+ const v = sig[i] * g; if (v === 0) continue;+ const [gl, gr] = fixed ?? panGains((p as (i: number) => number)(i));+ const a = at + i + dL, b = at + i + dR;+ if (a >= 0 && a < this.n) this.L[a] += v * gl;+ if (b >= 0 && b < this.n) this.R[b] += v * gr;+ }+ }+ /** Add an already-stereo pair (for decorrelated layers). */+ add2(l: ArrayLike<number>, r: ArrayLike<number>, at = 0, g = 1) {+ for (let i = 0; i < l.length; i++) { const k = at + i; if (k < 0 || k >= this.n) continue; this.L[k] += l[i] * g; this.R[k] += r[i] * g; }+ }+}++// ---- sources+export const white = (r: Rng, n: number) => { const o = buf(n); for (let i = 0; i < o.length; i++) o[i] = r() * 2 - 1; return o; };+/** Pink noise (Paul Kellet's refined filter), ~unit RMS-ish. */+export const pink = (r: Rng, n: number) => {+ const o = buf(n); let b0 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0, b6 = 0;+ for (let i = 0; i < o.length; i++) {+ const w = r() * 2 - 1;+ b0 = 0.99886 * b0 + w * 0.0555179; b1 = 0.99332 * b1 + w * 0.0750759; b2 = 0.969 * b2 + w * 0.153852;+ b3 = 0.8665 * b3 + w * 0.3104856; b4 = 0.55 * b4 + w * 0.5329522; b5 = -0.7616 * b5 - w * 0.016898;+ o[i] = (b0 + b1 + b2 + b3 + b4 + b5 + b6 + w * 0.5362) * 0.11; b6 = w * 0.115926;+ }+ return o;+};++/** One mode of a struck object: a damped sinusoid, optionally gliding (bubbles rise, bodies drop). */+export type Mode = { f: number; tau: number; a: number; t0?: number; att?: number; ph?: number; glide?: number; glideTau?: number; rise?: number };+/**+ * Modal synthesis: sum of damped sinusoids. f(t) = f * (1 + glide*(1 - e^(-t/glideTau))) * (1 + rise*t), the+ * rise frozen once the mode is 60 dB down. Frequencies are held under 0.45*sr (no aliasing); a mode+ * stops once it has decayed 100 dB.+ */+export const modal = (sr: number, n: number, modes: Mode[]) => {+ const o = buf(n), ny = 0.45 * sr;+ for (const m of modes) {+ if (!(m.f > 0) || m.f > ny) continue;+ const i0 = secs(sr, m.t0 ?? 0), att = m.att ?? 0.00006, end = Math.min(o.length, i0 + Math.ceil(m.tau * 11.5 * sr)), riseEnd = m.tau * 6.9;+ let ph = m.ph ?? 0;+ for (let i = i0; i < end; i++) {+ const t = (i - i0) / sr, f = m.f * (1 + (m.glide ?? 0) * (1 - Math.exp(-t / (m.glideTau ?? 0.01)))) * (1 + (m.rise ?? 0) * Math.min(t, riseEnd));+ o[i] += Math.sin(ph) * m.a * (1 - Math.exp(-t / att)) * Math.exp(-t / m.tau);+ ph += (TAU * Math.min(f, ny)) / sr;+ }+ }+ return o;+};+/** Raised-cosine fade over the last `s` seconds of a layer: a layer cut while still sounding would click. */+export const endFade = (o: Float64Array, sr: number, s = 0.008) => { const f = Math.min(o.length, secs(sr, s)); for (let i = 0; i < f; i++) o[o.length - 1 - i] *= 0.5 - 0.5 * Math.cos((Math.PI * i) / f); return o; };+/** A sine whose frequency and amplitude are functions of time (phase-accumulated, so glides never click). */+export const chirp = (sr: number, n: number, f: (t: number) => number, env: (t: number) => number, ph0 = 0) => {+ const o = buf(n); let ph = ph0;+ for (let i = 0; i < o.length; i++) { const t = i / sr, e = env(t); o[i] = Math.sin(ph) * e; ph += (TAU * Math.min(f(t), sr * 0.45)) / sr; }+ return endFade(o, sr, 0.03);+};+/** Enveloped noise burst, optionally band-limited: the contact transient of almost every hit. */+export const burst = (sr: number, r: Rng, len: number, tau: number, o: { hp?: number; lp?: number; bp?: number; q?: number; pink?: boolean } = {}) => {+ const n = secs(sr, len), s = o.pink ? pink(r, n) : white(r, n);+ for (let i = 0; i < n; i++) s[i] *= Math.exp(-i / sr / tau) * Math.min(1, i / (sr * 0.00008) + 0.35);+ filt(s, sr, o); return endFade(s, sr, 0.008);+};+export const filt = (s: Float64Array, sr: number, o: { hp?: number; lp?: number; bp?: number; q?: number }) => {+ const run = (bq: Biquad) => { for (let i = 0; i < s.length; i++) s[i] = bq.tick(s[i]); };+ if (o.hp) run(Biquad.make(sr, "hp", o.hp, 0.707));+ if (o.lp) run(Biquad.make(sr, "lp", o.lp, 0.707));+ if (o.bp) run(Biquad.make(sr, "bp", o.bp, o.q ?? 1));+ return s;+};+/** Time-varying state-variable filter (a sweep): f(t) in Hz, returns the chosen output. */+export const sweep = (s: Float64Array, sr: number, f: (t: number) => number, q: number | ((t: number) => number), mode: "lp" | "bp" | "hp") => {+ const sv = new SVF(sr, f(0), typeof q === "number" ? q : q(0));+ for (let i = 0; i < s.length; i++) {+ if ((i & 15) === 0) { const t = i / sr; sv.set(clamp(f(t), 20, sr * 0.45), typeof q === "number" ? q : q(t)); }+ sv.tick(s[i]); s[i] = mode === "lp" ? sv.lp : mode === "bp" ? sv.bp : sv.hp;+ }+ return s;+};+export const shape = (s: Float64Array, sr: number, env: (t: number) => number) => { for (let i = 0; i < s.length; i++) s[i] *= env(i / sr); return s; };+/** Attack-decay envelope: raised-cosine attack of `a` seconds, exponential decay of time constant `tau`. */+export const ad = (a: number, tau: number) => (t: number) => (t < a ? 0.5 - 0.5 * Math.cos((Math.PI * t) / a) : Math.exp(-(t - a) / tau));+export const smooth = (u: number) => { const x = clamp(u, 0, 1); return x * x * (3 - 2 * x); };++/** Put the bus in a small space: dsp.room's wet signal, mixed in. Stereo width comes from here. */+export const space = (b: Bus, r: Rng, o: { rt60: number; mix: number; er?: number; predelay?: number; hp?: number; lp?: number }) => {+ const L = Float32Array.from(b.L), R = Float32Array.from(b.R);+ const [wL, wR] = room(L, R, b.sr, { er: o.er ?? 0.5, late: 0.6, rt60: o.rt60, predelay: o.predelay ?? 0.012, hp: o.hp ?? 250, lp: o.lp ?? 7000, seed: 0, rng: r });+ for (let i = 0; i < b.n; i++) { b.L[i] += wL[i] * o.mix; b.R[i] += wR[i] * o.mix; }+};++/** DC block (2nd-order 22 Hz high-pass), air roll-off (4th-order 16.5 kHz: no fizz for the encoder), NaN guard, trailing silence trimmed, 4 ms end fade. */+export const finish = (b: Bus, keep: number): SfxStereo => {+ const sr = b.sr;+ const top = Math.min(16500, sr * 0.4);+ for (const c of [b.L, b.R]) {+ const h = Biquad.make(sr, "hp", 22, 0.707), l1 = Biquad.make(sr, "lp", top, 0.5412), l2 = Biquad.make(sr, "lp", top, 1.3066);+ for (let i = 0; i < c.length; i++) { const v = l2.tick(l1.tick(h.tick(c[i]))); c[i] = Number.isFinite(v) ? v : 0; }+ }+ let peak = 0; for (let i = 0; i < b.n; i++) peak = Math.max(peak, Math.abs(b.L[i]), Math.abs(b.R[i]));+ let end = b.n; const floor = peak * 1e-4; // -80 dB under the peak+ while (end > keep + 1 && Math.abs(b.L[end - 1]) < floor && Math.abs(b.R[end - 1]) < floor) end--;+ const rang = end === b.n; // still ringing at the buffer's end: a long fade instead of a cut+ end = Math.min(b.n, end + secs(sr, 0.004));+ const L = new Float32Array(end), R = new Float32Array(end), fade = Math.min(end, rang ? Math.min(secs(sr, 0.4), Math.round(end * 0.2)) : secs(sr, 0.004));+ for (let i = 0; i < end; i++) { const g = i >= end - fade ? 0.5 - 0.5 * Math.cos((Math.PI * (end - 1 - i)) / fade) : 1; L[i] = b.L[i] * g; R[i] = b.R[i] * g; }+ return [L, R];+};++// ---- measurement: K-weighted (BS.1770) power over a window, the same yardstick for levels and audibility+export const kWeight = (x: ArrayLike<number>, sr: number) => {+ const out = new Float64Array(x.length);+ { const G = 3.999843853973347, Q = 0.7071752369554196, fc = 1681.974450955533, K = Math.tan((Math.PI * fc) / sr), Vh = Math.pow(10, G / 20), Vb = Math.pow(Vh, 0.4996667741545416);+ const a0 = 1 + K / Q + K * K, b0 = (Vh + (Vb * K) / Q + K * K) / a0, b1 = (2 * (K * K - Vh)) / a0, b2 = (Vh - (Vb * K) / Q + K * K) / a0, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let i = 0; i < x.length; i++) { const y = b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x[i]; y2 = y1; y1 = y; out[i] = y; } }+ { const fc = 38.13547087602444, Q = 0.5003270373238773, K = Math.tan((Math.PI * fc) / sr), a0 = 1 + K / Q + K * K, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let i = 0; i < out.length; i++) { const xi = out[i], y = xi - 2 * x1 + x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = xi; y2 = y1; y1 = y; out[i] = y; } }+ return out;+};+/** Loudness (LUFS-scaled, ungated) of K-weighted channels over samples [a, b). */+export const winLufs = (kL: Float64Array, kR: Float64Array, a: number, b: number) => {+ let s = 0; const lo = Math.max(0, a), hi = Math.min(kL.length, b), len = Math.max(1, hi - lo);+ for (let i = lo; i < hi; i++) s += kL[i] * kL[i] + kR[i] * kR[i];+ return -0.691 + 10 * Math.log10(Math.max(s / len, 1e-20));+};+/**+ * The window where a sound actually speaks: the 10 ms frames within 10 dB of its loudest frame,+ * grown to the contiguous run around that frame, clamped to 15..500 ms. Returns [a, b) in samples.+ */+export const speakingWindow = (kL: Float64Array, kR: Float64Array, sr: number): [number, number] => {+ const hop = Math.max(1, secs(sr, 0.01)), nf = Math.ceil(kL.length / hop), e = new Float64Array(nf);+ for (let f = 0; f < nf; f++) { let s = 0; for (let i = f * hop; i < Math.min(kL.length, (f + 1) * hop); i++) s += kL[i] * kL[i] + kR[i] * kR[i]; e[f] = s; }+ let mx = 0, at = 0; for (let f = 0; f < nf; f++) if (e[f] > mx) { mx = e[f]; at = f; }+ let a = at, b = at; const th = mx * 0.1;+ while (a > 0 && e[a - 1] >= th) a--;+ while (b < nf - 1 && e[b + 1] >= th) b++;+ let s0 = a * hop, s1 = Math.min(kL.length, (b + 1) * hop);+ const min = secs(sr, 0.015), max = secs(sr, 0.5);+ if (s1 - s0 > max) { const c = at * hop + hop / 2; s0 = Math.max(s0, Math.round(c - max / 2)); s1 = Math.min(s1, s0 + max); }+ if (s1 - s0 < min) s1 = Math.min(kL.length, s0 + min);+ return [s0, s1];+};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.tsnew file mode 100644index 0000000..78b48c1--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts@@ -0,0 +1,514 @@+// anidoodle's sound-effects kit: every sound designed in layers (transient + body + tail), placed+// in stereo, and varied per hit from its seed so a repeated cue never sounds like a loop.+// Levels are set in K-weighted loudness over the sound's own "speaking window" (sfxCore), the+// same yardstick the audibility check uses, so a kind's level means the same thing everywhere.+import { rng as mkRng } from "../core";+import { pcOf } from "./theory";+import { clamp, db, type Rng } from "./dsp";+import { Bus, modal, chirp, burst, white, pink, filt, sweep, shape, ad, smooth, space, finish, secs, buf, kWeight, winLufs, speakingWindow, type Mode, type SfxStereo } from "./sfxCore";++export type SfxOpts = {+ /** per-hit variation: same seed, same samples; a different seed, a different (but same-family) hit. */+ seed?: number; variant?: string;+ /** transpose in semitones (-24..24). */+ pitch?: number;+ /** length for sustained kinds (scratch, riser, whoosh, paper, thread); riser may use beats instead. */+ lengthS?: number; beats?: number; bpm?: number;+ /** tonal kinds (chime, riser, impact "bloom", press "confirm") are tuned to this key: "C", "Eb", "F#m" (m = minor). */+ key?: string;+ /** direction of travel for moving sounds: +1 left-to-right, -1 right-to-left. */+ dir?: 1 | -1;+ /** extra gain in dB on top of the kind's calibrated level. */+ gainDb?: number;+};+export type SfxSound = { L: Float32Array; R: Float32Array; sr: number; kind: SfxKind; variant: string; seed: number;+ /** sample index of the sync point (the hit, the pass-by, the end of a riser): this lands on the cue frame. */+ hit: number;+ /** [a, b) samples where the sound speaks (used for ducking and the audibility check). */+ window: [number, number]; lufs: number };++type Ctx = { sr: number; r: Rng; P: number; o: SfxOpts; dir: number; key: { pc: number; minor: boolean } | null; bpm: number;+ /** x jittered by +-amt (relative). */ j: (x: number, amt: number) => number };+type Made = { bus: Bus; hit: number };+type Def = { variants: readonly string[]; level: number; duckDb: number; use: string; make: (c: Ctx, v: string) => Made };++const keyHz = (c: Ctx, octave: number, semis = 0) => 440 * Math.pow(2, (c.key!.pc + semis + 12 * (octave + 1) - 69) / 12);+const PENTA = { major: [0, 2, 4, 7, 9], minor: [0, 3, 5, 7, 10] };+/** Glockenspiel-bar partials: a bright tuned strike that sits above a lo-fi mix. */+const glock = (f: number, tau: number, a: number, t0 = 0): Mode[] => [+ { f, tau, a, t0 }, { f: f * 2.756, tau: tau * 0.42, a: a * 0.32, t0 }, { f: f * 5.404, tau: tau * 0.18, a: a * 0.14, t0 }, { f: f * 8.933, tau: tau * 0.09, a: a * 0.06, t0 },+];++// ---------------------------------------------------------------------------------------------+const tick: Def = {+ variants: ["key", "soft", "ui", "space"], level: -20.5, duckDb: 0,+ use: "typing (one per character: key), a laptop key (soft), an interface tick (ui), the space bar (space)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, 0.22), b = new Bus(sr, n), p0 = (r() - 0.5) * 0.5;+ if (v === "ui") {+ const f = c.j(4300, 0.05) * P;+ b.add(modal(sr, n, [{ f, tau: 0.0017, a: 1 }, { f: f * 2.03, tau: 0.0009, a: 0.3 }, { f: f * 0.51, tau: 0.004, a: 0.25 }]), 0, 0.8, p0);+ b.add(burst(sr, r, 0.002, 0.00028, { hp: 5500 }), 0, 0.45, p0);+ space(b, r, { rt60: 0.18, mix: 0.05, hp: 1500 });+ return { bus: b, hit: 0 };+ }+ const soft = v === "soft", spc = v === "space";+ const f1 = c.j(soft ? 1550 : spc ? 1900 : 3150, 0.07) * P;+ // 1 the key's plastic click (three stiff modes), 2 the contact transient, 3 bottom-out into the plate+ b.add(burst(sr, r, 0.0016, 0.00035, { hp: soft ? 1200 : 2800 }), 0, soft ? 0.3 : 0.55, p0);+ b.add(modal(sr, n, [{ f: f1, tau: soft ? 0.0024 : 0.0031, a: 1 }, { f: f1 * c.j(1.63, 0.03), tau: 0.002, a: 0.5 }, { f: f1 * c.j(2.41, 0.03), tau: 0.0014, a: 0.3 }]), 0, soft ? 0.45 : 0.65, p0, 0.12);+ b.add(modal(sr, n, [{ f: c.j(spc ? 145 : soft ? 205 : 265, 0.1) * P, tau: spc ? 0.02 : 0.009, a: 1, t0: c.j(0.0028, 0.3), att: 0.0004 }, { f: c.j(spc ? 520 : 780, 0.1) * P, tau: 0.004, a: 0.35, t0: 0.003 }]), 0, spc ? 0.9 : 0.55, p0);+ if (spc) b.add(modal(sr, n, [{ f: c.j(2500, 0.1) * P, tau: 0.004, a: 1 }, { f: c.j(4100, 0.1) * P, tau: 0.002, a: 0.5 }]), secs(sr, c.j(0.0065, 0.25)), 0.28, p0 + 0.15); // stabiliser wire+ if (!soft) { // the upstroke, a quieter higher click as the key returns+ const up = secs(sr, c.j(spc ? 0.12 : 0.085, 0.25));+ b.add(modal(sr, n, [{ f: f1 * 1.18, tau: 0.0017, a: 1 }, { f: f1 * 1.9, tau: 0.001, a: 0.4 }]), up, 0.17, p0);+ b.add(burst(sr, r, 0.001, 0.00025, { hp: 4000 }), up, 0.1, p0);+ }+ if (soft) for (const ch of [b.L, b.R]) filt(ch, sr, { lp: 6000 });+ space(b, r, { rt60: 0.22, mix: 0.06, hp: 600 });+ return { bus: b, hit: 0 };+ },+};++const press: Def = {+ variants: ["thock", "soft", "confirm"], level: -13, duckDb: 2,+ use: "a button press, the Generate thock (thock), a gentle toggle (soft), a press that succeeds, tuned to the key (confirm)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, v === "confirm" ? 2.8 : 1.2), b = new Bus(sr, n), soft = v === "soft";+ // body: a pitch-dropping sine, the "th" of thock+ const lo = c.j(soft ? 70 : 84, 0.05) * P, drop = c.j(soft ? 105 : 150, 0.1) * P, tau = c.j(soft ? 0.065 : 0.052, 0.1);+ const body = chirp(sr, secs(sr, 0.5), (t) => lo + drop * Math.exp(-t / 0.017), ad(0.0006, tau));+ b.add(body.map((x) => Math.tanh(x * 1.5) / Math.tanh(1.5)), 0, 1, 0);+ // transient+ b.add(burst(sr, r, 0.004, soft ? 0.001 : 0.0006, { lp: soft ? 2500 : 7000, hp: 500 }), 0, soft ? 0.3 : 0.5, 0);+ if (!soft) {+ // the plastic cap: three modes, a hair to the side+ b.add(modal(sr, n, [{ f: c.j(1060, 0.05) * P, tau: 0.007, a: 1 }, { f: c.j(1790, 0.05) * P, tau: 0.005, a: 0.6 }, { f: c.j(2870, 0.05) * P, tau: 0.0035, a: 0.4 }]), 0, 0.42, 0.08, 0.3);+ const up = secs(sr, c.j(0.14, 0.2)); // release: the button coming back up+ b.add(modal(sr, n, [{ f: c.j(1420, 0.05) * P, tau: 0.003, a: 1 }, { f: c.j(2330, 0.05) * P, tau: 0.002, a: 0.5 }]), up, 0.13, 0.05);+ b.add(chirp(sr, secs(sr, 0.1), () => lo * 1.6, ad(0.0005, 0.012)), up, 0.12, 0);+ }+ if (v === "confirm") { // a glassy tuned answer 12 ms after the press+ const f = keyHz(c, 6);+ b.add(modal(sr, n, glock(f, 0.35, 1, 0.012)), 0, 0.18, -0.25);+ b.add(modal(sr, n, glock(f * 1.5, 0.28, 1, 0.07)), 0, 0.12, 0.3);+ }+ space(b, r, { rt60: v === "confirm" ? 0.9 : 0.4, mix: v === "confirm" ? 0.16 : 0.1, hp: 220 });+ return { bus: b, hit: 0 };+ },+};++const pop: Def = {+ variants: ["pop", "cork", "tiny"], level: -16, duckDb: 1,+ use: "something appears (pop), a cap coming off / a card landing (cork), a small dot or badge appearing (tiny)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, 0.5), b = new Bus(sr, n), p0 = (r() - 0.5) * 0.3;+ const [f0, rise, tau, nz] = v === "cork" ? [260, 0.9, 0.032, 0.7] : v === "tiny" ? [920, 1.1, 0.012, 0.3] : [420, 1.6, 0.022, 0.45];+ const f = c.j(f0, 0.1) * P, tt = c.j(tau, 0.15);+ b.add(chirp(sr, n, (t) => f * (1 + rise * (1 - Math.exp(-t / 0.005))), ad(0.0004, tt)), 0, 1, p0);+ b.add(burst(sr, r, 0.005, v === "cork" ? 0.0014 : 0.0008, { bp: v === "tiny" ? 3200 : v === "cork" ? 900 : 1400, q: 1.4 }), 0, nz * 2.2, p0);+ if (v !== "tiny") b.add(modal(sr, n, [{ f: c.j(v === "cork" ? 110 : 140, 0.1) * P, tau: 0.01, a: 1, att: 0.0005 }]), 0, 0.3, 0);+ if (v === "cork") b.add(shape(filt(pink(r, secs(sr, 0.12)), sr, { hp: 1800 }), sr, ad(0.004, 0.025)), secs(sr, 0.004), 0.25, p0); // the rush of air+ space(b, r, { rt60: 0.35, mix: 0.1 });+ return { bus: b, hit: 0 };+ },+};++const drop = (c: Ctx, b: Bus, at: number, f0: number, tau: number, g: number, p: number) => {+ const { sr, r } = c;+ b.add(burst(sr, r, 0.001, 0.00025, { hp: 2500 }), at, 0.35 * g, p); // the surface tick+ // the plink: a bubble of air trapped by the drop rings with a RISING pitch (van den Doel)+ b.add(modal(sr, b.n, [{ f: f0, tau, a: 1, t0: 0.0015, att: 0.0012, rise: 0.4 / tau }, { f: f0 * 2.01, tau: tau * 0.3, a: 0.08, t0: 0.0015, att: 0.0012, rise: 0.4 / tau }]), at, g, p);+};+const ink: Def = {+ variants: ["plip", "double", "bloom"], level: -15, duckDb: 2,+ use: "an ink drop landing (plip), a drop and its smaller echo (double), the drop that opens an ink bloom (bloom)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, 3), b = new Bus(sr, n), p0 = (r() - 0.5) * 0.3, f0 = c.j(1150, 0.12) * P, tau = c.j(0.04, 0.15);+ drop(c, b, 0, f0, tau, 1, p0);+ if (v === "double") drop(c, b, secs(sr, c.j(0.085, 0.2)), f0 * c.j(1.35, 0.06), tau * 0.7, 0.42, p0 + 0.25);+ if (v === "bloom") { // the ink spreads: a soft wet swell and a low round note under it+ const sw = shape(filt(pink(r, secs(sr, 1.5)), sr, { lp: 750, hp: 120 }), sr, ad(0.09, 0.45));+ const sw2 = shape(filt(pink(r, secs(sr, 1.5)), sr, { lp: 750, hp: 120 }), sr, ad(0.11, 0.45));+ b.add2(sw, sw2, secs(sr, 0.02), 0.5);+ b.add(chirp(sr, secs(sr, 2.2), (t) => c.j(98, 0.04) * P * (1 - 0.06 * smooth(t / 0.6)), ad(0.05, 0.34)), secs(sr, 0.01), 0.22, 0);+ }+ space(b, r, { rt60: v === "bloom" ? 1.1 : 0.6, mix: v === "bloom" ? 0.22 : 0.14, hp: 300 });+ return { bus: b, hit: 0 };+ },+};++/** Stroke velocity for writing: strokes of 60-200 ms, small lifts between, one-pole smoothed. */+const strokes = (c: Ctx, n: number, meanS: number) => {+ const { sr, r } = c, v = buf(n); let i = 0;+ while (i < n) {+ const d = secs(sr, c.j(meanS, 0.5)), peak = 0.55 + 0.45 * r();+ for (let k = 0; k < d && i + k < n; k++) v[i + k] = peak * Math.pow(Math.sin((Math.PI * k) / d), 0.7);+ i += d + (r() < 0.3 ? secs(sr, c.j(0.05, 0.5)) : secs(sr, c.j(0.012, 0.5)));+ }+ const k = 1 - Math.exp((-2 * Math.PI * 60) / sr); let z = 0;+ for (let q = 0; q < n; q++) { z += k * (v[q] - z); v[q] = z; }+ return v;+};+const scratch: Def = {+ variants: ["nib", "pencil", "marker"], level: -18.5, duckDb: 1.5,+ use: "lettering being written: a metal pen nib (nib), graphite (pencil), a felt marker (marker). lengthS = how long the writing lasts",+ make(c, v) {+ const { sr, r, P } = c, len = c.o.lengthS ?? 1.0, n = secs(sr, len + 0.15), b = new Bus(sr, n), N = secs(sr, len);+ const cfg = v === "pencil" ? { base: 1400, span: 1800, q: 1.1, rate: 500, crack: 0.35, fric: 0.7, body: 0.3, mean: 0.13 }+ : v === "marker" ? { base: 850, span: 900, q: 1.6, rate: 70, crack: 0.1, fric: 0.8, body: 0.35, mean: 0.16 }+ : { base: 2700, span: 2600, q: 2.2, rate: 950, crack: 0.55, fric: 0.55, body: 0.14, mean: 0.1 };+ const vel = strokes(c, N, cfg.mean), panAt = (i: number) => clamp(c.dir * (-0.3 + (0.6 * i) / Math.max(1, N)) + 0.05 * Math.sin(i / sr * 7), -1, 1);+ // 1 friction: noise through a band that brightens with pen speed+ const fr = white(r, N), fOf = (t: number) => (cfg.base + cfg.span * vel[Math.min(N - 1, Math.round(t * sr))]) * P; sweep(fr, sr, fOf, cfg.q, "bp"); sweep(fr, sr, fOf, cfg.q * 0.7, "bp");+ for (let i = 0; i < N; i++) fr[i] *= vel[i] * vel[i];+ b.add(fr, 0, cfg.fric * 3.2, panAt);+ // 2 the paper's tooth: sparse micro-clicks, denser when the pen moves fast+ const cr = buf(N);+ for (let i = 0; i < N; i++) if (r() < (cfg.rate * vel[i]) / sr) { const a = (r() - 0.5) * 2 * (0.4 + 0.6 * r()); for (let k = 0; k < secs(sr, 0.0012) && i + k < N; k++) cr[i + k] += a * Math.exp(-k / (sr * 0.00015)); }+ filt(cr, sr, { hp: 2500 }); b.add(cr, 0, cfg.crack, panAt);+ // 3 the hand and the sheet under it: low rustle following the stroke+ const bd = filt(pink(r, N), sr, { lp: 700, hp: 150 }); for (let i = 0; i < N; i++) bd[i] *= vel[i];+ b.add(bd, 0, cfg.body, panAt);+ if (v === "marker") { const f = c.j(1300, 0.1) * P; b.add(chirp(sr, N, (t) => f * (1 + 0.15 * vel[Math.min(N - 1, Math.round(t * sr))]), (t) => Math.pow(vel[Math.min(N - 1, Math.round(t * sr))], 3)), 0, 0.05, panAt); }+ const fade = secs(sr, 0.008); for (let i = 0; i < fade; i++) { const g = i / fade; b.L[i] *= g; b.R[i] *= g; }+ space(b, r, { rt60: 0.3, mix: 0.08, hp: 400 });+ return { bus: b, hit: 0 };+ },+};++const paper: Def = {+ variants: ["slide", "flip", "rustle"], level: -18, duckDb: 1.5,+ use: "a sheet sliding in and landing (slide, hit = the landing), a page turn (flip, hit = the snap), handling paper (rustle)",+ make(c, v) {+ const { sr, r, P } = c;+ if (v === "flip") {+ const len = c.o.lengthS ?? c.j(0.32, 0.1), N = secs(sr, len), b = new Bus(sr, N + secs(sr, 0.6));+ let ph = 0; const am = buf(N); for (let i = 0; i < N; i++) { const u = i / N; ph += (2 * Math.PI * (55 - 30 * u)) / sr; am[i] = 1 - 0.55 * (0.5 + 0.5 * Math.sin(ph)); }+ const env = (t: number) => { const u = t / len; return smooth(u / 0.55) * (u < 0.55 ? 1 : 1 - smooth((u - 0.55) / 0.45) * 0.85); };+ for (const [side, amt] of [[0, 1], [1, 1]] as const) {+ const s = white(r, N); sweep(s, sr, (t) => (1500 + 2700 * Math.sin(Math.PI * Math.min(1, t / len))) * P, 0.9, "bp");+ for (let i = 0; i < N; i++) s[i] *= am[i] * env(i / sr);+ b.add(s, 0, 1.1 * amt, side ? 0.2 * c.dir : -0.2 * c.dir);+ }+ const snap = N - secs(sr, 0.01);+ b.add(burst(sr, r, 0.006, 0.0009, { hp: 1500 }), snap, 0.55, 0.25 * c.dir);+ b.add(modal(sr, b.n, [{ f: c.j(880, 0.1) * P, tau: 0.005, a: 1 }, { f: c.j(190, 0.1) * P, tau: 0.012, a: 0.6, att: 0.0005 }]), snap, 0.3, 0.2 * c.dir);+ space(b, r, { rt60: 0.4, mix: 0.1 });+ return { bus: b, hit: snap };+ }+ if (v === "rustle") {+ const len = c.o.lengthS ?? c.j(0.5, 0.15), N = secs(sr, len), b = new Bus(sr, N + secs(sr, 0.5)), k = 28 + Math.floor(r() * 24);+ for (let g = 0; g < k; g++) {+ const t = len * Math.pow(r(), 1.3), gl = c.j(0.008, 0.6), f = (1500 + 4500 * r()) * P;+ b.add(burst(sr, r, gl, gl * 0.35, { bp: f, q: 1.3 }), secs(sr, t), (0.4 + r()) * 1.2 * Math.sin(Math.PI * Math.min(1, t / len + 0.05)), (r() - 0.5) * 0.8);+ }+ const bed = shape(filt(pink(r, N), sr, { lp: 3200, hp: 500 }), sr, (t) => Math.sin(Math.PI * Math.min(1, t / len)));+ b.add(bed, 0, 0.35, 0);+ space(b, r, { rt60: 0.35, mix: 0.08 });+ return { bus: b, hit: 0 };+ }+ // slide: the sheet travels, speeding then braking, then lands+ const len = c.o.lengthS ?? c.j(0.45, 0.12), N = secs(sr, len), land = secs(sr, len * 0.86), b = new Bus(sr, N + secs(sr, 0.6));+ const sp = (t: number) => { const u = t / (len * 0.86); return u < 1 ? smooth(u / 0.3) * (1 - 0.4 * u) : 0.15 * Math.exp(-(t - len * 0.86) / 0.02); };+ const pan = (i: number) => c.dir * (-0.3 + 0.55 * Math.min(1, i / land));+ for (const side of [0, 1]) {+ const s = pink(r, N); sweep(s, sr, (t) => (1000 + 1700 * sp(t)) * P, 0.8, "bp"); for (let i = 0; i < N; i++) s[i] *= sp(i / sr);+ b.add(s, 0, 1.3, (i) => pan(i) + (side ? 0.15 : -0.15));+ }+ const fib = buf(N); for (let i = 0; i < N; i++) if (r() < (180 * sp(i / sr)) / sr) fib[i] = (r() - 0.5) * 2;+ b.add(filt(fib, sr, { hp: 3000 }), 0, 0.35, pan);+ b.add(modal(sr, b.n, [{ f: c.j(150, 0.1) * P, tau: 0.02, a: 1, att: 0.0008 }, { f: c.j(620, 0.1) * P, tau: 0.006, a: 0.3 }]), land, 0.45, pan(land));+ b.add(burst(sr, r, 0.008, 0.0015, { lp: 3000, pink: true }), land, 0.5, pan(land));+ space(b, r, { rt60: 0.4, mix: 0.1 });+ return { bus: b, hit: land };+ },+};++/**+ * A pass-by: the source moves along a line past the listener. Distance sets level and air+ * absorption, the radial velocity sets the doppler glide (high approaching, low leaving) and the+ * angle sets the pan. hit = the closest point.+ */+const passBy = (c: Ctx, b: Bus, len: number, o: { air: number; tone: number; toneQ: number; body: number; toneAmt: number; bodyAmt: number; dop: number; spread: number }) => {+ const { sr, r, P } = c, N = secs(sr, len), tc = len * 0.56, w = len * 0.2;+ const geo = (t: number) => { const x = (t - tc) / w, d = Math.sqrt(1 + x * x); return { x, d, D: 1 / (1 + o.dop * (x / d)) }; };+ const edge = (t: number) => Math.min(1, t / 0.03, (len - t) / 0.03);+ const amp = (t: number) => { const { d } = geo(t); return Math.pow(d, -1.7) * Math.max(0, edge(t)); };+ const panAt = (i: number) => { const { x, d } = geo(i / sr); return clamp(c.dir * o.spread * (x / d), -1, 1); };+ const air = [pink(r, N), pink(r, N)];+ for (const s of air) { sweep(s, sr, (t) => { const g = geo(t); return o.air * P * g.D * (0.55 + 0.45 / g.d); }, 0.7, "bp"); for (let i = 0; i < N; i++) s[i] *= amp(i / sr); }+ // mostly panned (the source moves), partly decorrelated (the air around it)+ const mono = air[0].map((x, i) => x * 0.75 + air[1][i] * 0.25);+ b.add(mono, 0, 3.2, panAt);+ b.add2(air[1], air[0], 0, 0.9);+ if (o.toneAmt > 0) { const t = white(r, N); sweep(t, sr, (tt) => o.tone * P * geo(tt).D, o.toneQ, "bp"); for (let i = 0; i < N; i++) t[i] *= amp(i / sr); b.add(t, 0, o.toneAmt, panAt); }+ if (o.bodyAmt > 0) { const s = pink(r, N); sweep(s, sr, (t) => o.body * geo(t).D, 0.8, "lp"); for (let i = 0; i < N; i++) s[i] *= amp(i / sr); b.add(s, 0, o.bodyAmt, (i) => panAt(i) * 0.4); }+ return secs(sr, tc);+};+const whoosh: Def = {+ variants: ["soft", "air", "fast", "deep"], level: -16, duckDb: 2,+ use: "something travels past camera: a gentle transition (soft, the default), a card flying (air), a quick flick (fast), a big heavy move (deep). hit = the pass-by",+ make(c, v) {+ const cfg = { soft: { len: 0.9, air: 620, tone: 1050, toneQ: 5, body: 180, toneAmt: 0.35, bodyAmt: 0.25, dop: 0.14, spread: 0.6 },+ air: { len: 0.7, air: 950, tone: 1750, toneQ: 7, body: 220, toneAmt: 0.5, bodyAmt: 0.3, dop: 0.22, spread: 0.8 },+ fast: { len: 0.38, air: 1400, tone: 2600, toneQ: 8, body: 260, toneAmt: 0.55, bodyAmt: 0.15, dop: 0.32, spread: 0.85 },+ deep: { len: 1.05, air: 460, tone: 780, toneQ: 5, body: 150, toneAmt: 0.3, bodyAmt: 0.9, dop: 0.2, spread: 0.7 } }[v]!;+ const len = c.o.lengthS ?? c.j(cfg.len, 0.08), b = new Bus(c.sr, secs(c.sr, len + 0.8));+ const hit = passBy(c, b, len, { ...cfg, air: c.j(cfg.air, 0.1), tone: c.j(cfg.tone, 0.1) });+ space(b, c.r, { rt60: v === "deep" ? 1.2 : 0.7, mix: 0.12, hp: 300 });+ return { bus: b, hit };+ },+};++const swish: Def = {+ variants: ["in", "out", "soft"], level: -17, duckDb: 1,+ use: "a UI panel or card sliding (in = rising, out = falling), a subtle nudge (soft). Short, never sharp",+ make(c, v) {+ const { sr, r, P } = c, len = c.o.lengthS ?? c.j(v === "soft" ? 0.28 : 0.2, 0.1), N = secs(sr, len), b = new Bus(sr, secs(sr, len + 0.5));+ const [f1, f2] = v === "out" ? [3400, 1300] : v === "soft" ? [900, 1900] : [1300, 3400], pk = 0.35;+ const f = (t: number) => f1 * Math.pow(f2 / f1, smooth(t / len)) * P;+ const env = (t: number) => { const u = t / len; return u < pk ? 0.5 - 0.5 * Math.cos((Math.PI * u) / pk) : Math.exp(-(u - pk) * 4.5) * (1 - smooth((u - 0.85) / 0.15)); };+ const pan = (i: number) => c.dir * (-0.35 + (0.7 * i) / N);+ for (const side of [0, 1]) { const s = pink(r, N); sweep(s, sr, f, v === "soft" ? 0.9 : 1.3, "bp"); sweep(s, sr, f, 0.8, "bp"); shape(s, sr, env); b.add(s, 0, 1.4, (i) => pan(i) + (side ? 0.2 : -0.2)); }+ const t = white(r, N); sweep(t, sr, f, 6, "bp"); shape(t, sr, env); b.add(t, 0, v === "soft" ? 0.1 : 0.2, pan);+ space(b, r, { rt60: 0.35, mix: 0.08 });+ return { bus: b, hit: secs(sr, len * pk) };+ },+};++const riser: Def = {+ variants: ["soft", "air", "tonal"], level: -15, duckDb: 2,+ use: "the ONE build into the big reveal: soft (the signature: air + a tuned chord), air (noise only), tonal (more chord). Tempo-synced: beats + bpm; hit = its end, on the downbeat",+ make(c, v) {+ const { sr, r } = c, len = c.o.lengthS ?? ((c.o.beats ?? 4) * 60) / c.bpm, N = secs(sr, len), b = new Bus(sr, N + secs(sr, 0.03));+ const [nz, tn] = v === "air" ? [1, 0] : v === "tonal" ? [0.45, 1] : [0.8, 0.55];+ const cut = (t: number) => Math.min(1, (len - t) / 0.02); // it stops ON the downbeat+ // 1 air: noise through a resonant low-pass opening 250 Hz -> 10 kHz, growing wider+ for (const side of [0, 1]) {+ const s = pink(r, N); sweep(s, sr, (t) => 250 * Math.pow(40, Math.pow(t / len, 1.4)), (t) => 1.2 + 1.6 * (t / len), "lp"); filt(s, sr, { hp: 160 });+ shape(s, sr, (t) => Math.pow(t / len, 2.2) * cut(t));+ b.add(s, 0, nz * 1.6, (i) => (side ? 1 : -1) * (0.15 + 0.6 * (i / N)));+ }+ // 2 a tuned chord (root, fifth, octave, the octave above fading in) pulsing in tempo: 8ths -> 16ths -> 32nds+ if (tn > 0) {+ const beat = c.bpm / 60, voices: [number, number, number][] = [[keyHz(c, 3), -0.5, 0], [keyHz(c, 3, 7), 0.5, 0.5], [keyHz(c, 4), 0, 0.25], [keyHz(c, 5), 0, 0.75]];+ voices.forEach(([f, p, phase], vi) => {+ const s = buf(N); let ph = 0, tp = phase;+ for (let i = 0; i < N; i++) {+ const t = i / sr, u = t / len, rate = beat * (u < 0.5 ? 2 : u < 0.8 ? 4 : 8), I = 0.2 + 1.6 * u;+ tp += rate / sr; ph += (2 * Math.PI * f * c.P) / sr;+ const trem = 1 - (0.25 + 0.45 * u) * (0.5 + 0.5 * Math.cos(2 * Math.PI * tp));+ const fadeIn = vi === 3 ? smooth((u - 0.55) / 0.35) : 1;+ s[i] = Math.sin(ph + I * Math.sin(2 * ph)) * trem * Math.pow(u, 1.8) * fadeIn * cut(t);+ }+ b.add(s, 0, tn * 0.22, p);+ });+ }+ for (const ch of [b.L, b.R]) for (let i = 0; i < ch.length; i++) ch[i] = Math.tanh(ch[i] * 1.3) / 1.3;+ return { bus: b, hit: N };+ },+};++const impact: Def = {+ variants: ["boom", "soft", "bloom"], level: -9, duckDb: 6,+ use: "the ONE big reveal (boom), a smaller landing (soft), the reveal with a tuned shimmer and a breath in before it (bloom)",+ make(c, v) {+ const { sr, r, P } = c, soft = v === "soft", pre = v === "bloom" ? secs(sr, 0.28) : 0, n = pre + secs(sr, soft ? 3.5 : 5.5), b = new Bus(sr, n);+ // 1 sub drop, saturated so small speakers still hear its harmonics+ const lo = c.j(soft ? 40 : 44, 0.04) * P, subTau = c.j(soft ? 0.32 : 0.6, 0.1), sub = chirp(sr, secs(sr, subTau * 8), (t) => lo + (soft ? 55 : 72) * P * Math.exp(-t / 0.07), ad(0.002, subTau));+ b.add(sub.map((x) => Math.tanh(x * 1.8) / Math.tanh(1.8)), pre, 1, 0);+ // 2 punch: dark noise + two chest modes, a hair wide+ b.add(burst(sr, r, 0.35, soft ? 0.05 : 0.07, { lp: soft ? 500 : 950, pink: true }), pre, soft ? 0.9 : 1.3, -0.1, 0.4);+ b.add(burst(sr, r, 0.35, soft ? 0.05 : 0.07, { lp: soft ? 500 : 950, pink: true }), pre, soft ? 0.9 : 1.3, 0.1, -0.4);+ b.add(modal(sr, n, [{ f: c.j(170, 0.06) * P, tau: 0.09, a: 1, att: 0.001 }, { f: c.j(96, 0.06) * P, tau: 0.15, a: 0.8, att: 0.001 }]), pre, soft ? 0.25 : 0.4, 0);+ if (!soft) b.add(burst(sr, r, 0.004, 0.0007, { hp: 1500 }), pre, 0.35, 0); // 3 the crack on top+ if (v === "bloom") {+ // a breath in before it: a reversed swell that stops on the hit+ for (const side of [0, 1]) { const s = pink(r, pre); sweep(s, sr, (t) => 400 * Math.pow(8, t / 0.28), 1, "lp"); shape(s, sr, (t) => Math.pow(t / 0.28, 3)); b.add(s, 0, 0.8, side ? 0.4 : -0.4); }+ // and a tuned shimmer on the key: root, 3rd, 5th, 9th in the upper octaves, spread across the field+ const third = c.key!.minor ? 3 : 4;+ [[keyHz(c, 5), -0.6], [keyHz(c, 5, third), 0.6], [keyHz(c, 5, 7), -0.3], [keyHz(c, 6, 2), 0.3], [keyHz(c, 6), 0]].forEach(([f, p], k) => {+ const ms = glock(f * c.P, 1.5, 1, 0.02 + k * 0.012).map((m) => ({ ...m, att: 0.03 }));+ b.add(modal(sr, n, ms), pre, 0.09, p);+ });+ }+ space(b, r, { rt60: soft ? 1.2 : 2.4, mix: soft ? 0.2 : 0.34, hp: 120, lp: 3500, predelay: 0.02, er: 0.35 });+ return { bus: b, hit: pre };+ },+};++const chime: Def = {+ variants: ["sparkle", "bell", "glint"], level: -17, duckDb: 1.5,+ use: "magic / success, tuned to the film's key: a rising pentatonic sparkle (sparkle), one bell (bell), a tiny glint on a highlight (glint)",+ make(c, v) {+ const { sr, r } = c, n = secs(sr, v === "bell" ? 6 : v === "glint" ? 2 : 4), b = new Bus(sr, n), scale = PENTA[c.key!.minor ? "minor" : "major"];+ if (v === "bell") {+ b.add(modal(sr, n, glock(keyHz(c, 5) * c.P, 1.4, 1)), 0, 1, -0.1);+ b.add(modal(sr, n, glock(keyHz(c, 6, 7) * c.P, 0.9, 1, 0.004)), 0, 0.3, 0.3);+ b.add(burst(sr, r, 0.003, 0.0005, { hp: 5000 }), 0, 0.2, 0);+ space(b, r, { rt60: 1.6, mix: 0.25, hp: 400 });+ return { bus: b, hit: 0 };+ }+ const count = v === "glint" ? 2 : 4 + Math.floor(r() * 3), oct = v === "glint" ? 7 : 6, start = Math.floor(r() * 3);+ let t = 0;+ for (let k = 0; k < count; k++) {+ const d = start + k, f = keyHz(c, oct + Math.floor(d / 5), scale[d % 5]) * c.P, g = 0.6 + (0.4 * k) / count;+ const p = c.dir * (-0.55 + (1.1 * k) / Math.max(1, count - 1)) * (k % 2 ? 1 : 0.8);+ b.add(modal(sr, n, glock(f, v === "glint" ? 0.14 : c.j(0.5, 0.15), 1)), secs(sr, t), g, p);+ t += c.j(v === "glint" ? 0.04 : 0.055, 0.15);+ }+ if (v === "sparkle") { const s = [white(r, secs(sr, 1)), white(r, secs(sr, 1))]; for (const x of s) { filt(x, sr, { hp: 7500 }); shape(x, sr, ad(0.06, 0.3)); } b.add2(s[0], s[1], 0, 0.035); }+ space(b, r, { rt60: v === "glint" ? 0.8 : 1.8, mix: v === "glint" ? 0.15 : 0.3, hp: 400, predelay: 0.015 });+ return { bus: b, hit: 0 };+ },+};++const bubbleAt = (c: Ctx, b: Bus, at: number, f0: number, tau: number, g: number, p: number) =>+ b.add(modal(c.sr, b.n, [{ f: f0, tau, a: 1, att: 0.001, rise: 0.45 / tau }, { f: f0 * 2.02, tau: tau * 0.25, a: 0.06, att: 0.001, rise: 0.45 / tau }]), at, g, p);+const bubble: Def = {+ variants: ["bubbles", "splash", "gloop"], level: -16.5, duckDb: 1.5,+ use: "water life (the koi): a few rising bubbles (bubbles), a tail flick at the surface (splash), one big lazy bubble (gloop)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, 1.6), b = new Bus(sr, n);+ if (v === "gloop") {+ bubbleAt(c, b, 0, c.j(270, 0.1) * P, c.j(0.075, 0.15), 1, (r() - 0.5) * 0.4);+ bubbleAt(c, b, secs(sr, c.j(0.09, 0.2)), c.j(390, 0.1) * P, 0.05, 0.5, (r() - 0.5) * 0.6);+ for (const ch of [b.L, b.R]) filt(ch, sr, { lp: 2800 });+ } else {+ let t = 0;+ if (v === "splash") {+ for (const side of [0, 1]) b.add(burst(sr, r, 0.3, 0.06, { bp: 1200, q: 0.7, pink: true }), 0, 1.5, side ? 0.35 : -0.35);+ b.add(burst(sr, r, 0.12, 0.028, { hp: 3000 }), 0, 0.35, 0);+ const k = 4 + Math.floor(r() * 4); for (let q = 0; q < k; q++) { const f = (1800 + 1700 * r()) * P; b.add(modal(sr, n, [{ f, tau: 0.008 + 0.012 * r(), a: 1, rise: 30 }]), secs(sr, 0.04 + 0.22 * r()), 0.22, (r() - 0.5) * 0.9); }+ t = 0.05;+ }+ const k = v === "splash" ? 2 : 4 + Math.floor(r() * 5);+ for (let q = 0; q < k; q++) {+ const f0 = (350 + 1100 * Math.pow(r(), 1.5)) * P, tau = 0.012 + 12 / f0;+ bubbleAt(c, b, secs(sr, t), f0, tau, 0.5 + 0.5 * r(), (r() - 0.5) * 1.0);+ t += c.j(0.07, 0.8) * (1 - q / (k + 2));+ }+ for (const ch of [b.L, b.R]) filt(ch, sr, { lp: 5000 });+ }+ space(b, r, { rt60: 0.55, mix: 0.12, hp: 300 });+ return { bus: b, hit: 0 };+ },+};++const BRICK: [number, number, number][] = [[1850, 0.02, 1], [2720, 0.013, 0.7], [3990, 0.009, 0.55], [5240, 0.006, 0.4], [7380, 0.004, 0.25]];+const clack = (c: Ctx, b: Bus, at: number, g: number, p: number, face: number) => {+ const { sr, r, P } = c;+ b.add(modal(sr, b.n, [...BRICK.map(([f, tau, a]) => ({ f: f * c.j(1, 0.035) * P * face, tau: tau * c.j(1, 0.2), a: a * c.j(1, 0.25) })), { f: c.j(720, 0.08) * P * face, tau: 0.016, a: 0.45 }]), at, g, p);+ b.add(burst(sr, r, 0.0008, 0.00015, { hp: 4000 }), at, 0.5 * g, p);+};+const brick: Def = {+ variants: ["clack", "snap", "tumble"], level: -15, duckDb: 1.5,+ use: "toy bricks: two bricks tapping (clack), a brick pressed onto studs (snap), a brick dropped onto a pile (tumble)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, 1.2), b = new Bus(sr, n), p0 = (r() - 0.5) * 0.5;+ if (v === "snap") {+ clack(c, b, 0, 0.45, p0, 1.08);+ const at = secs(sr, c.j(0.024, 0.2)); clack(c, b, at, 1, p0, 0.94);+ b.add(modal(sr, n, [{ f: c.j(380, 0.08) * P, tau: 0.012, a: 1, att: 0.0003 }]), at, 0.5, p0);+ space(b, r, { rt60: 0.35, mix: 0.08 });+ return { bus: b, hit: at };+ }+ if (v === "tumble") {+ let t = 0, gap = c.j(0.11, 0.2), g = 1; const k = 3 + Math.floor(r() * 3);+ for (let q = 0; q < k; q++) { clack(c, b, secs(sr, t), g, clamp(p0 + (r() - 0.5) * 0.4, -1, 1), 0.9 + 0.2 * r()); t += gap; gap *= c.j(0.62, 0.1); g *= c.j(0.6, 0.15); }+ } else clack(c, b, 0, 1, p0, 1);+ space(b, r, { rt60: 0.35, mix: 0.08 });+ return { bus: b, hit: 0 };+ },+};++const thread: Def = {+ variants: ["pull", "pierce", "stitch"], level: -17.5, duckDb: 1.5,+ use: "embroidery: thread drawn through cloth (pull, hit = the tug), the needle going through (pierce), both (stitch)",+ make(c, v) {+ const { sr, r, P } = c, b = new Bus(sr, secs(sr, 1.6)), p0 = (r() - 0.5) * 0.3;+ const pierce = (at: number) => {+ const k = 3 + Math.floor(r() * 3); for (let q = 0; q < k; q++) b.add(burst(sr, r, 0.0006, 0.00012, { hp: 3500 }), at + secs(sr, q * 0.006 + r() * 0.003), 0.15 + 0.15 * r(), p0);+ const pop = at + secs(sr, c.j(0.03, 0.2));+ b.add(modal(sr, b.n, [{ f: c.j(3600, 0.06) * P, tau: 0.002, a: 1 }, { f: c.j(5900, 0.06) * P, tau: 0.0012, a: 0.4 }]), pop, 0.5, p0);+ b.add(burst(sr, r, 0.001, 0.0002, { hp: 2500 }), pop, 0.5, p0);+ b.add(burst(sr, r, 0.06, 0.015, { bp: 2400, q: 2 }), pop, 0.6, p0);+ return pop;+ };+ const pull = (at: number) => {+ const len = c.o.lengthS ?? c.j(0.45, 0.15), N = secs(sr, len), s = white(r, N), sp = (t: number) => Math.pow(Math.sin(Math.PI * Math.pow(Math.min(1, t / len), 0.8)), 1.2);+ sweep(s, sr, (t) => (1500 + 1800 * sp(t)) * P, 3, "bp"); sweep(s, sr, (t) => (1500 + 1800 * sp(t)) * P, 2, "bp");+ let ph = 0; for (let i = 0; i < N; i++) { const t = i / sr; ph += (2 * Math.PI * (70 + 110 * sp(t))) / sr; s[i] *= sp(t) * (1 - 0.5 * (0.5 + 0.5 * Math.sin(ph))); }+ b.add(s, at, 2.2, (i) => p0 + c.dir * (-0.1 + (0.3 * i) / N));+ const hiss = filt(white(r, N), sr, { hp: 5000 }); for (let i = 0; i < N; i++) hiss[i] *= sp(i / sr);+ b.add(hiss, at, 0.08, p0);+ const tug = at + N - secs(sr, 0.004);+ b.add(modal(sr, b.n, [{ f: c.j(230, 0.1) * P, tau: 0.012, a: 1, att: 0.0005 }]), tug, 0.4, p0);+ b.add(burst(sr, r, 0.001, 0.0002, { hp: 3000 }), tug, 0.18, p0);+ return tug;+ };+ let hit = 0;+ if (v === "pierce") hit = pierce(0);+ else if (v === "stitch") { hit = pierce(0); pull(hit + secs(sr, 0.1)); }+ else hit = pull(0);+ space(b, r, { rt60: 0.3, mix: 0.07, hp: 400 });+ return { bus: b, hit };+ },+};++export const SFX = { tick, press, pop, ink, scratch, paper, whoosh, swish, riser, impact, chime, bubble, brick, thread } as const;+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;+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) => {+ const m = /^([A-G](?:#|b)?)(m|min|minor)?$/.exec(key.trim());+ if (!m) throw new Error(`sfx: bad key "${key}" (use e.g. "C", "Eb", "F#m")`);+ return { pc: pcOf(m[1]), minor: !!m[2] };+};+const checkSeed = (seed: unknown) => { if (!Number.isSafeInteger(seed) || (seed as number) < 0 || (seed as number) > 0xffffffff) throw new Error(`sfx: seed must be an integer 0..4294967295, got ${String(seed)}`); };+const checkRange = (name: string, x: unknown, lo: number, hi: number) => { if (x !== undefined && (typeof x !== "number" || !Number.isFinite(x) || x < lo || x > hi)) throw new Error(`sfx: ${name} must be a number ${lo}..${hi}, got ${String(x)}`); };++export const validateSfx = (kind: string, o: SfxOpts = {}) => {+ if (!(kind in SFX)) throw new Error(`sfx: unknown kind "${kind}" (kinds: ${SFX_KINDS.join(", ")})`);+ const d = SFX[kind as SfxKind];+ if (o.variant !== undefined && !d.variants.includes(o.variant)) throw new Error(`sfx: ${kind} has no variant "${o.variant}" (variants: ${d.variants.join(", ")})`);+ if (o.seed !== undefined) checkSeed(o.seed);+ checkRange("pitch", o.pitch, -24, 24); checkRange("lengthS", o.lengthS, 0.05, 30); checkRange("beats", o.beats, 0.25, 64); checkRange("bpm", o.bpm, 20, 300); checkRange("gainDb", o.gainDb, -60, 24);+ if (o.dir !== undefined && o.dir !== 1 && o.dir !== -1) throw new Error(`sfx: dir must be 1 or -1, got ${String(o.dir)}`);+ if (o.key !== undefined) parseKey(o.key);+};++/**+ * What a sound needs from the film: a key (tuned kinds) and a bpm (tempo-synced kinds). Never+ * defaulted: an effect tuned to a key the score isn't in, or pulsing at a tempo it isn't at, is wrong.+ */+export const sfxNeeds = (kind: SfxKind, variant: string, o: SfxOpts = {}) => ({+ key: kind === "chime" || (kind === "riser" && variant !== "air") || (kind === "press" && variant === "confirm") || (kind === "impact" && variant === "bloom"),+ bpm: kind === "riser" && !(variant === "air" && o.lengthS !== undefined),+});+/**+ * Render one sound. Pure in (kind, opts, sr). The level is calibrated: the kind's target loudness+ * over its speaking window, +-1 dB of per-seed variation, + opts.gainDb; sample peak capped at -1 dBFS.+ */+export const renderSfx = (kind: SfxKind, o: SfxOpts = {}, sr = 48000): SfxSound => {+ validateSfx(kind, o);+ if (!Number.isSafeInteger(sr) || sr < 22050 || sr > 192000) throw new Error(`sfx: sample rate must be an integer 22050..192000, got ${sr}`);+ const d = SFX[kind], variant = o.variant ?? d.variants[0], seed = o.seed ?? 1, r = mkRng((seed ^ 0x5f3759df) >>> 0);+ const need = sfxNeeds(kind, variant, o);+ if (need.key && o.key === undefined) throw new Error(`sfx: ${kind}:${variant} is tuned and needs a key (opts.key, or in a plan: plan.key or plan.score = the film's piece); there is no default key`);+ if (need.bpm && o.bpm === undefined) throw new Error(`sfx: ${kind}:${variant} is tempo-synced and needs a bpm (opts.bpm, or in a plan: plan.bpm or plan.score); there is no default tempo`);+ const c: Ctx = { sr, r, P: Math.pow(2, (o.pitch ?? 0) / 12), 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 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; }+ return { L, R, sr, kind, variant, seed, hit: Math.min(made.hit, L.length - 1), window, lufs: now + g };+};++export type { SfxStereo };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.tsnew file mode 100644index 0000000..aa75d4a--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts@@ -0,0 +1,173 @@+// Placing the kit in a film: cues addressed by FILM FRAME, optionally snapped to the beat, the score+// 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 { kWeight, winLufs, mixSeed, strSeed, secs, type SfxStereo } from "./sfxCore";+import { db } from "./dsp";+import { MODES } from "./theory";+import type { Piece } from "./plan";+import { loudness, truePeak } from "./meter";++export type SfxSnap = "none" | "bar" | "beat" | "8th" | "16th";+export type SfxCue = SfxOpts & {+ /** the frame the sound's sync point lands on (the hit; the pass-by of a whoosh; the END of a riser). */+ frame: number; kind: SfxKind; label?: string;+ /** snap the sync point to the beat grid (needs plan.bpm). Default: plan.snap ?? "none". */+ snap?: SfxSnap;+ /** how far the score dips under this cue (dB); default = the kind's own (impact 6, tick 0...). */+ duckDb?: number;+ /** audibility floor for this cue (dB vs the score); default plan.minDb ?? -6. */+ minDb?: number;+};+export type SfxPlan = {+ fps: number; frames: number; cues: SfxCue[];+ /** seeds every cue that has no seed of its own; per-cue seeds depend on (kind, frame), not on list order. */+ seed?: number;+ /** tempo grid: bpm, the time of beat 1 in seconds (beatZeroS), beats per bar. */+ bpm?: number; beatZeroS?: number; beatsPerBar?: number; snap?: SfxSnap;+ /** key for the tuned kinds ("C", "Eb", "Am"). No default: set it, or pass `score`. */+ key?: string;+ /** the film's score: key (first section), bpm (tempo, or the fitted tempo) and beats per bar come from it unless set above. */+ score?: { piece: Piece; tempo?: number };+ duck?: { attackS?: number; releaseS?: number; maxDb?: number };+ /** audibility floor in dB (cue loudness minus score loudness over the cue's window). Default -6. */+ minDb?: number;+ /** final true-peak ceiling in dBTP. Default -1. */+ ceilingDb?: number;+};+export type PlacedCue = { i: number; cue: SfxCue; sound: SfxSound; hitS: number; snappedFromS: number; start: number; window: [number, number] };+export type SfxAudibility = { i: number; kind: SfxKind; variant: string; label: string; atS: number; cueLufs: number; musicLufs: number; marginDb: number; peakMarginDb: number; minDb: number; ok: boolean };+export type SfxMix = { L: Float32Array; R: Float32Array; sfx: SfxStereo; music: SfxStereo; duck: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; ok: boolean; lufs: number; dbtp: number; limiterDb: number };++const GRID: Record<Exclude<SfxSnap, "none">, number> = { bar: 0, beat: 1, "8th": 0.5, "16th": 0.25 };+const name = (c: SfxCue, i: number) => `cue #${i} (${c.kind}${c.variant ? ":" + c.variant : ""}${c.label ? ` "${c.label}"` : ""} @ frame ${c.frame})`;++/** A plan with key / bpm / beatsPerBar filled in from its score (explicit plan values win). */+export const resolveSfxPlan = (p: SfxPlan): SfxPlan => {+ if (!p.score) return p;+ const pl = p.score.piece?.plan, sec = pl?.sections?.[0];+ if (!pl || !sec) throw new Error("sfx plan: score.piece has no plan/sections to take the key and tempo from");+ const minor = (MODES[sec.mode]?.intervals ?? []).includes(3);+ return { ...p, key: p.key ?? `${sec.key}${minor ? "m" : ""}`, bpm: p.bpm ?? p.score.tempo ?? pl.tempo, beatsPerBar: p.beatsPerBar ?? Number(String(pl.meter).split("/")[0]) };+};++export const validateSfxPlan = (plan: SfxPlan) => {+ const p = resolveSfxPlan(plan);+ if (!Number.isSafeInteger(p.fps) || p.fps <= 0) throw new Error(`sfx plan: fps must be a positive integer, got ${String(p.fps)}`);+ if (!Number.isSafeInteger(p.frames) || p.frames <= 0) throw new Error(`sfx plan: frames must be a positive integer, got ${String(p.frames)}`);+ if (p.seed !== undefined && (!Number.isSafeInteger(p.seed) || p.seed < 0 || p.seed > 0xffffffff)) throw new Error(`sfx plan: seed must be an integer 0..4294967295, got ${String(p.seed)}`);+ if (p.bpm !== undefined && (!Number.isFinite(p.bpm) || p.bpm < 20 || p.bpm > 300)) throw new Error(`sfx plan: bpm must be 20..300, got ${String(p.bpm)}`);+ if (p.minDb !== undefined && !Number.isFinite(p.minDb)) throw new Error("sfx plan: minDb must be a finite number");+ if (!Array.isArray(p.cues)) throw new Error("sfx plan: cues must be an array");+ p.cues.forEach((c, i) => {+ if (!c || typeof c !== "object") throw new Error(`sfx plan: cue #${i} is not an object`);+ if (!(c.kind in SFX)) throw new Error(`sfx plan: cue #${i} has unknown kind "${String(c.kind)}" (kinds: ${SFX_KINDS.join(", ")})`);+ if (typeof c.frame !== "number" || !Number.isFinite(c.frame) || c.frame < 0 || c.frame >= p.frames) throw new Error(`sfx plan: ${name(c, i)}: frame must be 0..${p.frames - 1}`);+ const snap = c.snap ?? p.snap ?? "none";+ if (!(snap === "none" || snap in GRID)) throw new Error(`sfx plan: ${name(c, i)}: snap must be none|bar|beat|8th|16th`);+ if ((snap !== "none" || c.beats !== undefined) && p.bpm === undefined && c.bpm === undefined) throw new Error(`sfx plan: ${name(c, i)}: snap/beats need a bpm (plan.bpm)`);+ if (c.duckDb !== undefined && (!Number.isFinite(c.duckDb) || c.duckDb < 0 || c.duckDb > 18)) throw new Error(`sfx plan: ${name(c, i)}: duckDb must be 0..18`);+ try { validateSfx(c.kind, optsOf(p, c, 0)); } catch (e) { throw new Error(`sfx plan: ${name(c, i)}: ${(e as Error).message}`); }+ const o = optsOf(p, c, 0), need = sfxNeeds(c.kind, c.variant ?? SFX[c.kind].variants[0], o);+ if (need.key && o.key === undefined) throw new Error(`sfx plan: ${name(c, i)} is tuned: set plan.key, cue.key, or plan.score (the film's piece); there is no default key`);+ if (need.bpm && o.bpm === undefined) throw new Error(`sfx plan: ${name(c, i)} is tempo-synced: set plan.bpm, cue.bpm, or plan.score (the film's piece); there is no default tempo`);+ });+};+const optsOf = (p: SfxPlan, c: SfxCue, seed: number): SfxOpts => ({ seed: c.seed ?? seed, variant: c.variant, pitch: c.pitch, lengthS: c.lengthS, beats: c.beats, bpm: c.bpm ?? p.bpm, key: c.key ?? p.key, dir: c.dir, gainDb: c.gainDb });++/** Render and place every cue. Throws if a cue's pre-roll (whoosh approach, riser build) would start before 0. */+export const placeSfx = (plan: SfxPlan, sr: number): PlacedCue[] => {+ validateSfxPlan(plan);+ const p = resolveSfxPlan(plan);+ const seen = new Map<string, number>(), filmS = p.frames / p.fps;+ return p.cues.map((cue, i) => {+ const k = `${cue.kind}@${cue.frame}`, occ = seen.get(k) ?? 0; seen.set(k, occ + 1);+ const seed = mixSeed(p.seed ?? 0, (strSeed(cue.kind) ^ Math.round(cue.frame * 1000) ^ (occ * 7919)) >>> 0);+ const t0 = cue.frame / p.fps, snap = cue.snap ?? p.snap ?? "none";+ let hitS = t0;+ if (snap !== "none") {+ const bpm = cue.bpm ?? p.bpm!, beat = 60 / bpm, g = snap === "bar" ? beat * (p.beatsPerBar ?? 4) : beat * GRID[snap], z = p.beatZeroS ?? 0;+ hitS = z + Math.round((t0 - z) / g) * g;+ if (hitS >= filmS) hitS -= g;+ if (hitS < 0) hitS += g;+ }+ const sound = renderSfx(cue.kind, optsOf(p, cue, seed), sr), start = Math.round(hitS * sr) - sound.hit;+ if (start < 0) {+ const pre = sound.hit / sr, need = Math.ceil(pre * p.fps);+ throw new Error(`sfx plan: ${name(cue, i)}: its ${pre.toFixed(2)} s pre-roll starts before frame 0; move it to frame >= ${need} or shorten it (lengthS/beats)`);+ }+ return { i, cue, sound, hitS, snappedFromS: t0, start, window: [start + sound.window[0], start + sound.window[1]] as [number, number] };+ });+};++/** The score's gain under the cues: raised-cosine dip before each cue's window, held, released. */+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 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);+ const v = 1 - (1 - lo) * s; if (v < g[i]) g[i] = v;+ }+ }+ return g;+};++/** Look-ahead true-peak ceiling (2 ms look-ahead, 80 ms release, 1.12 inter-sample margin). Returns the deepest gain reduction in dB. */+const ceiling = (L: Float32Array, R: Float32Array, sr: number, ceil: number) => {+ const n = L.length, la = secs(sr, 0.002), rel = Math.exp(-1 / (0.08 * sr)), need = new Float32Array(n), g = new Float32Array(n);+ for (let i = 0; i < n; i++) { const a = Math.max(Math.abs(L[i]), Math.abs(R[i])) * 1.12; need[i] = a > ceil ? ceil / a : 1; }+ // running minimum over the look-ahead window, then a smooth ramp INTO each reduction+ for (let i = n - 1; i >= 0; i--) { let m = 1; for (let j = i; j < Math.min(n, i + la); j++) if (need[j] < m) m = need[j]; g[i] = m; }+ let cur = 1, deepest = 1;+ for (let i = 0; i < n; i++) { cur = g[i] < cur ? g[i] : 1 - (1 - cur) * rel; if (cur > g[i]) cur = g[i]; L[i] *= cur; R[i] *= cur; if (cur < deepest) deepest = cur; }+ return 20 * Math.log10(deepest);+};++/** Audibility of each placed cue vs the (ducked) score over the cue's speaking window (the score's window is at least 100 ms). */+export const sfxAudibility = (placed: PlacedCue[], music: SfxStereo, sr: number, p: Pick<SfxPlan, "minDb">): SfxAudibility[] => {+ const mL = kWeight(music[0], sr), mR = kWeight(music[1], sr), minWin = secs(sr, 0.1);+ return placed.map((pc) => {+ const s = pc.sound, kL = kWeight(s.L, sr), kR = kWeight(s.R, sr), [wa, wb] = s.window, cueLufs = winLufs(kL, kR, wa, wb);+ let [a, b] = pc.window; if (b - a < minWin) { const c = (a + b) >> 1; a = c - (minWin >> 1); b = a + minWin; }+ const musicLufs = winLufs(mL, mR, a, b);+ let cp = 0, mp = 0; for (let i = wa; i < wb; i++) cp = Math.max(cp, Math.abs(s.L[i]), Math.abs(s.R[i]));+ for (let i = Math.max(0, a); i < Math.min(music[0].length, b); i++) mp = Math.max(mp, Math.abs(music[0][i]), Math.abs(music[1][i]));+ const silent = musicLufs < -70, marginDb = silent ? 99 : cueLufs - musicLufs, peakMarginDb = mp < 1e-6 ? 99 : 20 * Math.log10(cp / mp);+ const minDb = pc.cue.minDb ?? p.minDb ?? -6;+ return { i: pc.i, kind: pc.cue.kind, variant: s.variant, label: pc.cue.label ?? "", atS: pc.hitS, cueLufs, musicLufs, marginDb, peakMarginDb, minDb, ok: marginDb >= minDb };+ });+};++/**+ * The whole film's sound: score (any length; padded or cut to the film) ducked under the cues,+ * effects added, one true-peak ceiling. `music` null = effects only. Does not throw on an inaudible+ * cue: read `ok` / `audibility`, or call assertSfxAudible (filmSfx does).+ */+export const mixSfx = (music: SfxStereo | null, p: SfxPlan, sr = 48000): SfxMix => {+ const n = Math.round((p.frames / p.fps) * sr), placed = placeSfx(p, sr);+ const fxL = new Float32Array(n), fxR = new Float32Array(n);+ for (const pc of placed) { const { L, R } = pc.sound; for (let i = 0; i < L.length && pc.start + i < n; i++) { fxL[pc.start + i] += L[i]; fxR[pc.start + i] += R[i]; } }+ const duck = sfxDuck(placed, n, sr, p.duck), mL = new Float32Array(n), mR = new Float32Array(n);+ if (music) { const m = Math.min(n, music[0].length); for (let i = 0; i < m; i++) { mL[i] = music[0][i] * duck[i]; mR[i] = music[1][i] * duck[i]; } }+ const L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = mL[i] + fxL[i]; R[i] = mR[i] + fxR[i]; }+ const limiterDb = ceiling(L, R, sr, db((p.ceilingDb ?? -1) - 0.3));+ const fade = Math.min(n, secs(sr, 0.015)); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }+ const audibility = sfxAudibility(placed, [mL, mR], sr, p);+ const lu = n >= secs(sr, 0.4) ? loudness([L, R], sr).integrated : NaN;+ return { L, R, sfx: [fxL, fxR], music: [mL, mR], duck, placed, audibility, ok: audibility.every((a) => a.ok), lufs: lu, dbtp: truePeak([L, R]).dbtp, limiterDb };+};++export const assertSfxAudible = (m: SfxMix) => {+ const bad = m.audibility.filter((a) => !a.ok);+ if (bad.length) throw new Error(`sfx: ${bad.length} cue(s) buried under the score:\n` + bad.map((a) => ` #${a.i} ${a.kind}:${a.variant}${a.label ? ` "${a.label}"` : ""} @ ${a.atS.toFixed(2)} s is ${a.marginDb.toFixed(1)} dB vs the score (floor ${a.minDb} dB): raise its gainDb or its duckDb`).join("\n"));+ return m;+};++/** What a Film's `audio(sampleRate)` returns: score + effects at exactly the film's length. Throws on a buried cue. */+export const filmSfx = (music: ((sr: number) => SfxStereo) | null, p: SfxPlan) => (sr: number): SfxStereo => {+ const m = assertSfxAudible(mixSfx(music ? music(sr) : null, p, sr)); return [m.L, m.R];+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/tables.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/tables.tsindex d86db96..2e2ddc4 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/tables.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/tables.ts@@ -4,14 +4,14 @@import type { ModeId } from "./theory";export type MelodyType = "arpeggio" | "stepwise" | "hook" | "ostinato" | "drone" | "callResponse" | "counterMelody" | "sequence" | "themeTransformation";-export type Family = "piano" | "musicBox" | "celesta" | "mallets" | "pluck" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "chip" | "drums" | "organ" | "bass";+export type Family = "piano" | "musicBox" | "celesta" | "mallets" | "pluck" | "harp" | "guitar" | "strings" | "fmBell" | "ePiano" | "chip" | "drums" | "organ" | "bass" | "pad" | "brass" | "woodwind" | "choir" | "orchPerc" | "synthLead" | "bowed";export type Range = [number, number];export type Mood = {id: MoodId; modes: ModeId[]; tempo: Range; meters: string[]; harmonicRhythmBars: Range; register: Range;onsetsPerBeat: Range; attackMs: Range; lra: Range; centroidHz: Range | null; families: Family[]; melody: MelodyType[];master: "gentle" | "dense"; confirmedBy?: { date: string; words: string };};-export type MoodId = "joy" | "playful" | "tender" | "wistful" | "melancholy" | "hopeful" | "curious" | "tension" | "dread" | "awe" | "triumph" | "drive" | "calm" | "nostalgic" | "romantic";+export type MoodId = "joy" | "playful" | "tender" | "wistful" | "melancholy" | "hopeful" | "curious" | "tension" | "dread" | "awe" | "triumph" | "drive" | "calm" | "nostalgic" | "romantic" | "anger" | "eerie" | "mischief" | "heroic" | "sensual" | "grief";// centroid null = report only (spec 08 drive row; ADVISORY 4.1: piano brightness is never gated).export const MOODS: Record<MoodId, Mood> = {@@ -29,6 +29,12 @@ export const MOODS: Record<MoodId, Mood> = {drive: { id: "drive", modes: ["aeolian", "dorian", "mixolydian"], tempo: [110, 140], meters: ["4/4"], harmonicRhythmBars: [1, 1], register: [60, 86], onsetsPerBeat: [4, 8], attackMs: [1, 5], lra: [4, 8], centroidHz: null, families: ["drums", "bass", "pluck"], melody: ["hook", "arpeggio", "ostinato"], master: "dense" },calm: { id: "calm", modes: ["mixolydian", "majorPentatonic", "major"], tempo: [60, 90], meters: ["6/8", "3/4"], harmonicRhythmBars: [2, 2], register: [60, 84], onsetsPerBeat: [1, 2], attackMs: [5, 30], lra: [4, 8], centroidHz: [1000, 2000], families: ["guitar", "fmBell"], melody: ["stepwise", "drone"], master: "gentle" },nostalgic: { id: "nostalgic", modes: ["major"], tempo: [70, 95], meters: ["4/4"], harmonicRhythmBars: [0.5, 1], register: [60, 84], onsetsPerBeat: [1.5, 3], attackMs: [5, 20], lra: [6, 10], centroidHz: [900, 1600], families: ["ePiano", "drums", "bass"], melody: ["stepwise", "hook"], master: "dense" },+ anger: { id: "anger", modes: ["phrygian", "aeolian", "harmonicMinor"], tempo: [120, 170], meters: ["4/4", "7/8"], harmonicRhythmBars: [1, 2], register: [40, 72], onsetsPerBeat: [3, 8], attackMs: [1, 5], lra: [4, 8], centroidHz: [1200, 5000], families: ["drums", "bass", "brass", "synthLead"], melody: ["ostinato", "hook"], master: "dense" },+ eerie: { id: "eerie", modes: ["wholeTone", "locrian", "phrygian", "harmonicMinor"], tempo: [50, 90], meters: ["4/4", "3/4", "5/4"], harmonicRhythmBars: [2, 4], register: [48, 96], onsetsPerBeat: [0.25, 1], attackMs: [50, 400], lra: [10, 18], centroidHz: null, families: ["bowed", "choir", "celesta", "fmBell"], melody: ["drone", "sequence"], master: "gentle" },+ mischief: { id: "mischief", modes: ["blues", "dorian", "mixolydian", "wholeTone"], tempo: [100, 150], meters: ["4/4", "2/4", "6/8"], harmonicRhythmBars: [0.5, 1], register: [55, 90], onsetsPerBeat: [1.5, 3], attackMs: [2, 8], lra: [6, 12], centroidHz: [1200, 4000], families: ["woodwind", "pluck", "mallets", "bass"], melody: ["callResponse", "hook"], master: "gentle" },+ heroic: { id: "heroic", modes: ["major", "mixolydian", "dorian"], tempo: [90, 130], meters: ["4/4", "3/4"], harmonicRhythmBars: [1, 2], register: [55, 84], onsetsPerBeat: [1, 3], attackMs: [10, 60], lra: [8, 14], centroidHz: null, families: ["brass", "strings", "orchPerc", "choir"], melody: ["hook", "themeTransformation"], master: "gentle" },+ sensual: { id: "sensual", modes: ["dorian", "aeolian", "mixolydian"], tempo: [65, 95], meters: ["4/4", "12/8"], harmonicRhythmBars: [1, 2], register: [55, 80], onsetsPerBeat: [0.75, 2], attackMs: [10, 60], lra: [6, 10], centroidHz: [800, 2000], families: ["ePiano", "bass", "woodwind", "drums"], melody: ["stepwise", "counterMelody"], master: "dense" },+ grief: { id: "grief", modes: ["aeolian", "harmonicMinor"], tempo: [40, 62], meters: ["3/4", "4/4"], harmonicRhythmBars: [2, 4], register: [48, 76], onsetsPerBeat: [0.5, 1], attackMs: [40, 200], lra: [10, 16], centroidHz: null, families: ["bowed", "piano", "strings", "choir"], melody: ["stepwise", "themeTransformation"], master: "gentle" },romantic: { id: "romantic", modes: ["major", "aeolian"], tempo: [60, 85], meters: ["3/4", "4/4"], harmonicRhythmBars: [1, 1], register: [60, 88], onsetsPerBeat: [1, 2.5], attackMs: [10, 60], lra: [8, 14], centroidHz: [1000, 2000], families: ["piano", "strings"], melody: ["stepwise", "counterMelody"], master: "gentle" },};@@ -36,7 +42,7 @@ export const MOODS: Record<MoodId, Mood> = {export const REFUSED_BLENDS: [MoodId, MoodId][] = [["joy", "dread"], ["playful", "melancholy"], ["calm", "tension"]];export const ARCS: Record<string, MoodId[]> = { rise: ["melancholy", "hopeful", "triumph"], turn: ["joy", "tension", "joy"], fallAndReturn: ["tender", "melancholy", "tender"], wonder: ["curious", "awe"], comic: ["playful", "tension", "playful"] };-export type StyleId = "musicBox" | "nocturne" | "drive" | "cinematic" | "chiptune" | "lofi" | "folk" | "minimalist" | "jazz" | "lullaby" | "ambient";+export type StyleId = "musicBox" | "nocturne" | "drive" | "cinematic" | "chiptune" | "lofi" | "lofiElectronic" | "folk" | "minimalist" | "jazz" | "lullaby" | "ambient" | "playful" | "orchestral" | "suspense" | "rock" | "hipHop" | "house" | "synthwave" | "world" | "choral";export type Style = { id: StyleId; tempo: Range; meters: string[]; families: Family[]; moods: MoodId[]; master: "gentle" | "dense"; arrangement: string; guards: string[]; reverb: "none" | "room" | "hall"; swing?: Range };export const STYLES: Record<StyleId, Style> = {musicBox: { id: "musicBox", tempo: [110, 130], meters: ["12/8"], families: ["musicBox", "fmBell"], moods: ["joy", "curious", "tender", "playful", "wistful"], master: "gentle", reverb: "room", arrangement: "melody -> +bass -> +arp -> +octave sparkle -> bell", guards: ["pluck-only instruments", "more notes, never longer notes"] },@@ -45,6 +51,16 @@ export const STYLES: Record<StyleId, Style> = {cinematic: { id: "cinematic", tempo: [60, 120], meters: ["4/4", "3/4"], families: ["strings", "piano", "harp", "fmBell", "drums"], moods: ["awe", "triumph", "melancholy", "tension", "hopeful"], master: "gentle", reverb: "hall", arrangement: "layered by register slot; crescendos over 4-8 bars", guards: ["max 4 families at once outside climaxes"] },chiptune: { id: "chiptune", tempo: [120, 160], meters: ["4/4"], families: ["chip"], moods: ["joy", "playful", "drive", "tension"], master: "dense", reverb: "none", arrangement: "2 pulses, triangle bass, noise drums; fast arpeggios fake chords", guards: ["<= 4 voices", "no reverb", "PolyBLEP pulses"] },lofi: { id: "lofi", tempo: [70, 90], meters: ["4/4"], families: ["ePiano", "drums", "bass"], moods: ["nostalgic", "calm", "wistful"], master: "dense", reverb: "room", swing: [0.55, 0.62], arrangement: "4 or 8 bar loop with small variations", guards: ["no 2 consecutive identical 8-bar blocks", "master low-pass <= 9 kHz allowed"] },+ lofiElectronic: { id: "lofiElectronic", tempo: [80, 100], meters: ["4/4"], families: ["pad", "pluck", "bass", "drums"], moods: ["calm", "joy", "hopeful", "nostalgic"], master: "dense", reverb: "room", swing: [0.52, 0.56], arrangement: "4-bar chord loop; sections add and remove layers (intro, groove, hook, half-time, breakdown, drop, outro); a chosen bar lands on the home chord", guards: ["no ePiano, no vinyl, no bit-crush: clean", "balance by stem RMS vs targets, not LUFS alone"] },+ playful: { id: "playful", tempo: [100, 150], meters: ["4/4", "6/8", "2/4"], families: ["mallets", "pluck", "bass", "drums"], moods: ["playful", "joy", "curious", "mischief"], master: "gentle", reverb: "room", swing: [0.5, 0.6], arrangement: "short sections, stop-time, call and response", guards: ["a button ending"] },+ orchestral: { id: "orchestral", tempo: [70, 140], meters: ["4/4", "3/4", "6/8"], families: ["strings", "brass", "choir", "orchPerc", "woodwind", "harp"], moods: ["heroic", "triumph", "awe", "tension", "grief"], master: "gentle", reverb: "hall", arrangement: "theme in brass or strings, ostinato engine, build to a tutti climax", guards: ["max 4 families at once outside the climax"] },+ suspense: { id: "suspense", tempo: [50, 110], meters: ["4/4", "5/4", "3/4"], families: ["bowed", "strings", "choir", "orchPerc", "bass"], moods: ["tension", "dread", "eerie"], master: "gentle", reverb: "hall", arrangement: "drone + pulse, stingers on picture hits, withheld resolution", guards: ["ghost guard: a pulse or a motif at least every 4 bars"] },+ rock: { id: "rock", tempo: [90, 160], meters: ["4/4", "6/8"], families: ["guitar", "bass", "drums", "organ"], moods: ["drive", "anger", "triumph", "joy"], master: "dense", reverb: "room", arrangement: "riff intro, verse, chorus, bridge, chorus; tight kit", guards: ["the riff returns"] },+ hipHop: { id: "hipHop", tempo: [70, 100], meters: ["4/4"], families: ["drums", "bass", "piano", "strings", "pluck"], moods: ["drive", "calm", "nostalgic", "sensual", "anger"], master: "dense", reverb: "room", swing: [0.52, 0.6], arrangement: "4 or 8 bar loop, drops and switch-ups every 8 bars", guards: ["808 carries content above 500 Hz"] },+ house: { id: "house", tempo: [118, 128], meters: ["4/4"], families: ["drums", "bass", "pad", "pluck", "organ"], moods: ["joy", "drive", "sensual", "hopeful"], master: "dense", reverb: "room", arrangement: "16-bar blocks, filter builds, breakdown, drop", guards: ["kick on every beat in the groove sections"] },+ synthwave: { id: "synthwave", tempo: [80, 118], meters: ["4/4"], families: ["synthLead", "pad", "bass", "drums"], moods: ["nostalgic", "drive", "heroic", "romantic"], master: "dense", reverb: "hall", arrangement: "intro pad, arpeggiated bass, big gated snare, lead hook", guards: ["one lead at a time"] },+ world: { id: "world", tempo: [60, 140], meters: ["7/8", "9/8", "12/8", "6/8", "4/4", "5/4"], families: ["pluck", "woodwind", "drums", "mallets"], moods: ["calm", "joy", "curious", "mischief", "awe"], master: "gentle", reverb: "room", arrangement: "drone + modal melody + hand percussion cycle; odd meters welcome", guards: ["name the tradition you draw on, write your own melody"] },+ choral: { id: "choral", tempo: [50, 90], meters: ["4/4", "3/4"], families: ["choir", "organ", "strings", "fmBell"], moods: ["awe", "grief", "hopeful", "tender", "heroic"], master: "gentle", reverb: "hall", arrangement: "voices in 4 parts, chorale phrases with cadences, a swell to the last chord", guards: ["choir is harmony and texture; the line on top must still move"] },folk: { id: "folk", tempo: [80, 120], meters: ["6/8", "3/4", "4/4"], families: ["guitar", "harp", "fmBell"], moods: ["calm", "wistful", "joy", "nostalgic"], master: "gentle", reverb: "room", arrangement: "fingerpicked pattern + lead", guards: ["strum spread 10-30 ms low to high"] },minimalist: { id: "minimalist", tempo: [100, 140], meters: ["4/4", "12/8"], families: ["mallets", "piano"], moods: ["curious", "tension", "awe"], master: "gentle", reverb: "room", arrangement: "interlocking ostinatos; one change every 8-16 bars", guards: ["a change at least every 16 bars"] },jazz: { id: "jazz", tempo: [90, 180], meters: ["4/4"], families: ["piano", "bass", "drums"], moods: ["playful", "nostalgic", "romantic", "curious"], master: "gentle", reverb: "room", swing: [0.6, 0.67], arrangement: "walking bass on quarters, comping off the beat", guards: ["7th chords required"] },diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/theory.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/theory.tsindex f20e846..801378e 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/theory.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/theory.ts@@ -7,7 +7,7 @@ export type Mode = { id: ModeId; intervals: number[]; color: string; use: string// Intervals are semitones above the tonic. `color` is the degree that makes the mode read as itself.export const MODES: Record<ModeId, Mode> = {- major: { id: "major", intervals: [0, 2, 4, 5, 7, 9, 11], color: "3, 7", use: "joy, arrival, sunlight; the music-box default", guard: "section 7 only" },+ major: { id: "major", intervals: [0, 2, 4, 5, 7, 9, 11], color: "3, 7", use: "joy, arrival, sunlight", guard: "section 7 only" },aeolian: { id: "aeolian", intervals: [0, 2, 3, 5, 7, 8, 10], color: "b3, b6", use: "sadness, longing, gravity, night", guard: "tonic clarity" },harmonicMinor: { id: "harmonicMinor", intervals: [0, 2, 3, 5, 7, 8, 11], color: "raised 7 over V", use: "drama, fate, cadences inside minor", guard: "augmented step b6-7 only as a passing figure, max 2 per phrase" },melodicMinor: { id: "melodicMinor", intervals: [0, 2, 3, 5, 7, 9, 11], color: "raised 6 and 7", use: "hopeful minor, yearning lines that climb", guard: "rising lines only; falling lines revert to aeolian" },@@ -63,3 +63,11 @@ export const detectMode = (notes: { p: number; d: number }[], modes: ModeId[] =}return res.sort((a, b) => b.score - a.score).slice(0, 3);};++/** How well a declared tonic + mode explains some notes: the share of note time inside the scale, and the tonic's own share (its dominance). */+export const modeFit = (notes: { p: number; d: number }[], tonicPc: number, mode: ModeId) => {+ const h = new Array(12).fill(0); for (const n of notes) h[((n.p % 12) + 12) % 12] += n.d;+ const tot = h.reduce((a, b) => a + b, 0) || 1, iv = new Set(MODES[mode].intervals.map((x) => (x + tonicPc) % 12));+ let inS = 0; for (let k = 0; k < 12; k++) if (iv.has(k)) inS += h[k];+ return { inScale: inS / tot, tonicShare: h[((tonicPc % 12) + 12) % 12] / tot };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocab.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocab.tsnew file mode 100644index 0000000..21563ab--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocab.ts@@ -0,0 +1,247 @@+// STYLE VOCABULARIES. A style is a vocabulary, never notes: the sound palette (a voice per slot,+// with levels and stem targets), the groove families that fit it, its harmony language, its melody+// rules, its arrangement grammar, and how five MOOD controls turn into real parameters. The composer+// (the model) writes every note: harmony, bass lines, motifs, form (compose.ts, references/music/compose.md).+// Nothing here is a melody, a progression or a riff, and nothing here should ever become one.+import type { InstId, Role, PieceFx, Meter } from "./plan";+import type { ModeId } from "./theory";+import type { MoodId, StyleId } from "./tables";+import type { GrooveFamily } from "./grooves";+import { VOCAB_MORE } from "./vocabMore";++/** Voice slots. Line slots (the composer writes them): chords, bass, lead, counter, arp. Drum slots are filled by a groove. */+export type Slot = "chords" | "lead" | "counter" | "bass" | "kick" | "snare" | "ghost" | "hat" | "arp" | "perc";+export const BASE_SLOTS: Slot[] = ["chords", "lead", "counter", "bass", "kick", "snare", "ghost", "hat"];+export const EXTRA_SLOTS: Slot[] = ["arp", "perc"];+/** opts values "beats:x" are resolved to x beats in seconds at the piece's tempo (delay times). */+export type Voice = { inst: InstId; role: Role; gainDb: number; opts?: Record<string, number | boolean | string>; send?: number; pan?: number };+/** Five mood controls, each 0..1, 0.5 = the calibrated palette unchanged. */+export type MoodControls = { energy?: number; warmth?: number; brightness?: number; tension?: number; space?: number };++export type SectionKind = "intro" | "verse" | "groove" | "hook" | "build" | "half" | "breakdown" | "drop" | "bridge" | "swell" | "breath" | "outro";+/** Arrangement grammar: which layers a section kind lets sound, and the groove it asks for by default. Lines sound only where written. */+export const KINDS: Record<SectionKind, { drums: "main" | "half" | "build" | null; bass: boolean; what: string }> = {+ intro: { drums: null, bass: false, what: "chords (and any line you write) without drums or bass: set the colour, state the key" },+ verse: { drums: "main", bass: true, what: "the groove under a lighter line: room for picture and words" },+ groove: { drums: "main", bass: true, what: "chords, bass, drums: the bed, no lead unless you write one" },+ hook: { drums: "main", bass: true, what: "full groove under the motif: the memorable part" },+ build: { drums: "build", bass: true, what: "rising density (snare 8ths to 16ths), rising line, lands on the next downbeat" },+ half: { drums: "half", bass: true, what: "half-time drums: the same tempo feels slower (a scene change, a breath with pulse)" },+ breakdown: { drums: null, bass: false, what: "drums and bass out, chords and a thin line: the held breath before a landing" },+ drop: { drums: "main", bass: true, what: "everything back on a strong chord: the landing, put it on the picture's key beat" },+ bridge: { drums: "main", bass: true, what: "new harmony away from home (a borrowed or relative area) before the return" },+ swell: { drums: null, bass: true, what: "long notes crescendo over 2-8 bars (orchestral swell), peaks on the downbeat after" },+ breath: { drums: null, bass: false, what: "near silence: one held chord or nothing, authored (max 2 bars)" },+ outro: { drums: null, bass: true, what: "home chord held, the motif's last word, then the tail" },+};++export type StyleVocab = {+ id: StyleId; name: string; atmosphere: string; tempo: [number, number]; meters: Meter[]; swing: [number, number];+ palette: Partial<Record<Slot, Voice>>; alternates: Partial<Record<Slot, Record<string, Voice>>>;+ fx: PieceFx; stemTargets: Record<string, number>; calibrated: boolean;+ grooves: GrooveFamily[]; moods: MoodId[];+ harmony: { modes: ModeId[]; qualities: string; tendencies: string; rhythm: string; voicing: string; tension: string };+ melody: { range: string; contour: string; density: string; motif: string };+ arrangement: { shape: string; transitions: string; endings: string };+ avoid: string;+};++const bassDelay = (x: number) => `beats:${x}`;+export const VOCAB: Partial<Record<StyleId, StyleVocab>> = {+ lofiElectronic: {+ id: "lofiElectronic", name: "lo-fi electronic", atmosphere: "warm, chill but upbeat, clean: a breathing pad, a plucked hook through ping-pong echoes, a round sub, a bouncy kit",+ tempo: [80, 100], meters: ["4/4"], swing: [0.52, 0.56],+ palette: {+ chords: { inst: "warmPad", role: "accomp", gainDb: -3, opts: { cut: 2600, attack: 0.5, release: 1.4, spread: 0.55 }, send: 0.35 },+ lead: { inst: "softPluck", role: "melody", gainDb: 6, opts: { decay: 0.42, bright: 6000, delay: bassDelay(0.75), feedback: 0.28, delayMix: 0.24 }, send: 0.25 },+ counter: { inst: "softPluck", role: "color", gainDb: 8, opts: { decay: 0.35, bright: 5200, pan: 0.35, delay: bassDelay(0.75), feedback: 0.3, delayMix: 0.35 }, send: 0.6 },+ bass: { inst: "sub", role: "bass", gainDb: -6, opts: { cut: 150 } },+ kick: { inst: "kick", role: "drum", gainDb: 0.5, send: 0.1 },+ snare: { inst: "snare", role: "drum", gainDb: 8, send: 0.3 },+ ghost: { inst: "snare", role: "drum", gainDb: 4, opts: { rim: true }, send: 0.2 },+ hat: { inst: "hat", role: "drum", gainDb: 20, opts: { pan: 0.25 }, send: 0.1 },+ arp: { inst: "softPluck", role: "accomp", gainDb: 4, opts: { decay: 0.22, bright: 3800, pan: -0.3, delay: bassDelay(0.5), feedback: 0.2, delayMix: 0.2 }, send: 0.3 },+ perc: { inst: "hat", role: "drum", gainDb: 14, opts: { pan: -0.3 }, send: 0.2 },+ },+ alternates: {+ lead: { bell: { inst: "fmBell", role: "melody", gainDb: 0, opts: { ratio: 3.5 }, send: 0.3 }, mallet: { inst: "marimba", role: "melody", gainDb: 2, send: 0.25 }, guitar: { inst: "guitar", role: "melody", gainDb: 2, send: 0.25 } },+ chords: { strings: { inst: "strings", role: "accomp", gainDb: -6, opts: { attack: 0.35, release: 1.0, bright: 0.8 }, send: 0.35 }, piano: { inst: "piano", role: "accomp", gainDb: -4, send: 0.3 } },+ bass: { warm: { inst: "bass", role: "bass", gainDb: -2, opts: { drive: 1.4 } } },+ },+ fx: { clean: true, duck: { by: "kick", parts: ["chords", "counter"], depth: 0.38, release: 0.24 }, tape: { wowCents: 2.5, wowHz: 0.4, flutterCents: 0, flutterHz: 6, drive: 1.02 } },+ stemTargets: { kick: -14, snare: -20, hat: -28, bass: -18, chords: -21, lead: -16.5, counter: -24 }, calibrated: true,+ grooves: ["bounce", "halfTime", "broken", "skip", "pulse", "build"], moods: ["calm", "joy", "hopeful", "nostalgic", "wistful", "curious"],+ harmony: { modes: ["major", "dorian", "lydian", "aeolian", "mixolydian"], qualities: "7ths, 9ths, 11ths and 13ths; add9; sus2/sus4 for air; avoid bare triads except on the landing",+ tendencies: "loops of 2, 4 or 8 bars; ii-V motion, IV-iii-vi drifts, modal vamps (i-IV in dorian, I-II in lydian), borrowed iv or bVII for a wistful turn; the home chord arrives on a structural beat",+ rhythm: "one chord per bar or two per bar; the change can anticipate the bar by an eighth", voicing: "rootless 3-4 note voicings between E3 and E4 moving by step (common tones held); the bass owns the root",+ tension: "sus4 and 13ths lean, maj7#11 floats, a dominant 7b9 or a borrowed iv aches; release by resolving the lean voice down a step" },+ melody: { range: "C4-A5 for the lead, the octave above for counter lines", contour: "short arches; the high point in the second half of a phrase; answer phrases end lower", density: "1-3 notes per beat; leave rests so the echo answers",+ motif: "a 2-5 note cell with its own rhythm; repeat it, then vary it (shift it up a step, invert the last interval, displace it by an eighth); call and response between lead and counter" },+ arrangement: { shape: "intro -> groove -> hook -> (half-time or breakdown) -> drop on home -> outro; add or remove one layer at a time", transitions: "a fill bar, a half-time bar, drums out for a breakdown, then everything back on a downbeat", endings: "home chord held with the motif's last note, or a clean button on 1" },+ avoid: "synth ePiano, vinyl crackle, bit-crush, a dark master low-pass: that is dusty lo-fi hip-hop, not clean electronic",+ },+ drive: {+ id: "drive", name: "driving electronic", atmosphere: "forward, bright, confident: four-on-the-floor, a pumping supersaw bed, a gritty bass line, a plucked arp",+ tempo: [110, 140], meters: ["4/4"], swing: [0.5, 0.52],+ palette: {+ chords: { inst: "strings", role: "accomp", gainDb: -8, opts: { attack: 0.25, release: 0.5, bright: 1.3, width: 0.95, grid: true }, send: 0.3 },+ lead: { inst: "strings", role: "melody", gainDb: -2, opts: { attack: 0.012, release: 0.15, bright: 1.8, width: 0.4, grid: true }, send: 0.25 },+ counter: { inst: "fmBell", role: "color", gainDb: -6, opts: { ratio: 3.5 }, send: 0.4 },+ bass: { inst: "bass", role: "bass", gainDb: -3, opts: { drive: 2.4, grid: true } },+ kick: { inst: "kick", role: "drum", gainDb: 2, opts: { soft: 0.3, grid: true }, send: 0 },+ snare: { inst: "snare", role: "drum", gainDb: 2, opts: { grid: true }, send: 0.4 },+ ghost: { inst: "snare", role: "drum", gainDb: -2, opts: { rim: true, grid: true }, send: 0.2 },+ hat: { inst: "hat", role: "drum", gainDb: 12, opts: { pan: 0.2, grid: true }, send: 0.1 },+ arp: { inst: "softPluck", role: "accomp", gainDb: 3, opts: { decay: 0.2, bright: 5000, delay: bassDelay(0.75), feedback: 0.3, delayMix: 0.25, grid: true }, send: 0.25 },+ perc: { inst: "hat", role: "drum", gainDb: 10, opts: { pan: -0.2, grid: true }, send: 0.15 },+ },+ alternates: { lead: { pluck: { inst: "softPluck", role: "melody", gainDb: 5, opts: { decay: 0.3, bright: 7000, delay: bassDelay(0.75), feedback: 0.3, delayMix: 0.25 }, send: 0.25 } }, bass: { sub: { inst: "sub", role: "bass", gainDb: -5, opts: { cut: 160 } } } },+ fx: { clean: true, duck: { by: "kick", parts: ["chords", "arp", "counter"], depth: 0.55, release: 0.2 } },+ stemTargets: { kick: -12, snare: -18, hat: -26, perc: -27, bass: -16, chords: -22, lead: -16, arp: -21, counter: -24 }, calibrated: false,+ grooves: ["fourFloor", "broken", "build", "halfTime", "tension"], moods: ["drive", "triumph", "tension", "joy", "awe"],+ harmony: { modes: ["aeolian", "dorian", "mixolydian", "major"], qualities: "triads and power voicings, sus2, add9; minor with a major IV (dorian) for lift", tendencies: "i-VI-III-VII, i-v-VI-IV, bVI-bVII-i climbs; long pedal tones under changing chords; a key lift of a step for the last chorus",+ rhythm: "one chord per bar or per two bars; stabs on off-beats", voicing: "wide: root-fifth-octave low, tight triads above C4; the bass line is 8ths or offbeat", tension: "a pedal under a moving chord, a build that withholds the kick, a riser into a drop; release on the downbeat with everything" },+ melody: { range: "A3-E6", contour: "repeated cells climbing by step; big leaps at the drop", density: "8ths and 16ths; arps in 3-note cells across 4/4 (hemiola)", motif: "a rhythmic riff of 3-6 notes, repeated with the last note changed; sequence it up the scale in the build" },+ arrangement: { shape: "intro (filtered) -> build -> drop -> breakdown -> build -> bigger drop -> outro", transitions: "builds of 4-8 bars, a one-beat breath before the drop", endings: "a button on 1 or a filtered fade of the groove" },+ avoid: "swing, soft attacks on the lead, more than 4 layers in the breakdown",+ },+ cinematic: {+ id: "cinematic", name: "cinematic / orchestral", atmosphere: "wide and emotional: string swells, low ostinatos for tension, harp and bell colour, a low boom on the arrival",+ tempo: [60, 120], meters: ["4/4", "3/4", "6/8"], swing: [0.5, 0.5],+ palette: {+ chords: { inst: "strings", role: "accomp", gainDb: -4, opts: { attack: 1.1, release: 1.6, bright: 0.9 }, send: 0.5 },+ lead: { inst: "strings", role: "melody", gainDb: 0, opts: { attack: 0.18, release: 0.9, bright: 1.1, width: 0.4 }, send: 0.45 },+ counter: { inst: "harp", role: "color", gainDb: 0, send: 0.5 },+ bass: { inst: "strings", role: "bass", gainDb: -3, opts: { attack: 0.6, release: 1.4, bass: true, bright: 0.6 }, send: 0.35 },+ arp: { inst: "strings", role: "accomp", gainDb: -4, opts: { attack: 0.01, release: 0.12, bright: 1.2, width: 0.6 }, send: 0.3 },+ kick: { inst: "kick", role: "drum", gainDb: 2, opts: { soft: 1 }, send: 0.6 },+ snare: { inst: "snare", role: "drum", gainDb: -2, send: 0.6 },+ ghost: { inst: "snare", role: "drum", gainDb: -4, opts: { rim: true }, send: 0.5 },+ hat: { inst: "hat", role: "drum", gainDb: 6, send: 0.4 },+ perc: { inst: "fmBell", role: "color", gainDb: -8, opts: { ratio: 2.4 }, send: 0.6 },+ },+ alternates: { lead: { piano: { inst: "piano", role: "melody", gainDb: 0, send: 0.4 }, bell: { inst: "fmBell", role: "melody", gainDb: -4, send: 0.5 }, celesta: { inst: "celesta", role: "melody", gainDb: 0, send: 0.5 } }, counter: { piano: { inst: "piano", role: "color", gainDb: -3, send: 0.4 } } },+ fx: {},+ stemTargets: { chords: -18, bass: -19, lead: -17, counter: -22, arp: -21, kick: -16, snare: -24, hat: -32 }, calibrated: false,+ grooves: ["pulse", "tension", "build", "halfTime"], moods: ["awe", "triumph", "tension", "melancholy", "hopeful", "dread"],+ harmony: { modes: ["aeolian", "harmonicMinor", "lydian", "major", "phrygian", "dorian"], qualities: "open fifths, add9, sus2/sus4, minor with a major IV; chromatic mediants (C to E, C to Ab) for awe",+ tendencies: "slow harmonic rhythm (1-2 bars per chord); i-bVI-bVII-i for epic, i-iv-V for drama, lydian II for wonder, a pedal bass under moving chords for tension; big arrivals on chromatic mediants",+ rhythm: "one chord per 1-2 bars; tension sections hold one chord over an ostinato", voicing: "spread wide: bass octaves below C3, open fifths, the melody doubled an octave on the climax (stagger the bass to keep peaks musical)",+ tension: "minor seconds against a pedal, a b6 leaning to 5, suspended 4ths held long, harmonic minor's raised 7th; release to a major chord or a picardy third" },+ melody: { range: "G3-C6 (strings), harp and bell above", contour: "long arcs over 4-8 bars, a big leap (6th, octave) then stepwise fall", density: "0.5-2 notes per beat; tension ostinatos 2-4 per beat", motif: "a 3-4 note idea that returns transformed: augmented (slower) at the climax, in the bass for menace, in the harp for tenderness" },+ arrangement: { shape: "intro (a colour, a drone) -> theme -> swell/build -> climax on the key picture beat -> release -> quiet coda", transitions: "crescendo over 4-8 bars; a breath of silence before the arrival; a low boom on the downbeat", endings: "a held chord ringing into the tail, or a hard-out on the cut" },+ avoid: "more than four families at once outside the climax; fast drums under a tender theme",+ },+ ambient: {+ id: "ambient", name: "airy ambient", atmosphere: "floating, spacious, luminous: long pads, bells and plucks with space around them, a soft heartbeat at most",+ tempo: [50, 80], meters: ["4/4", "3/4"], swing: [0.5, 0.5],+ palette: {+ chords: { inst: "warmPad", role: "accomp", gainDb: -1, opts: { cut: 3400, attack: 1.6, release: 3.0, spread: 1.0, width: 1 }, send: 0.7 },+ lead: { inst: "fmBell", role: "melody", gainDb: 0, opts: { ratio: 3.5, width: 0.6 }, send: 0.7 },+ counter: { inst: "softPluck", role: "color", gainDb: 6, opts: { decay: 0.6, bright: 4200, pan: -0.35, delay: bassDelay(1.5), feedback: 0.4, delayMix: 0.4 }, send: 0.8 },+ bass: { inst: "sub", role: "bass", gainDb: -8, opts: { cut: 120 } },+ arp: { inst: "celesta", role: "accomp", gainDb: -4, send: 0.7 },+ kick: { inst: "kick", role: "drum", gainDb: -4, opts: { soft: 1 }, send: 0.3 },+ ghost: { inst: "snare", role: "drum", gainDb: -6, opts: { rim: true }, send: 0.6 },+ hat: { inst: "hat", role: "drum", gainDb: 6, send: 0.5 },+ perc: { inst: "hat", role: "drum", gainDb: 4, opts: { pan: -0.4 }, send: 0.6 },+ },+ alternates: { lead: { pluck: { inst: "softPluck", role: "melody", gainDb: 5, opts: { decay: 0.8, bright: 3800, delay: bassDelay(1.5), feedback: 0.4, delayMix: 0.4 }, send: 0.7 }, vibes: { inst: "vibes", role: "melody", gainDb: 0, send: 0.6 } } },+ fx: { clean: true, tape: { wowCents: 4, wowHz: 0.25, flutterCents: 0, flutterHz: 6, drive: 1.0 } },+ stemTargets: { chords: -19, bass: -22, lead: -20, counter: -25, arp: -24, kick: -20, hat: -32 }, calibrated: false,+ grooves: ["pulse", "brushes"], moods: ["awe", "calm", "hopeful", "tender", "dread"],+ harmony: { modes: ["lydian", "major", "dorian", "majorPentatonic", "aeolian"], qualities: "maj7, add9, maj7#11, sus2, quartal stacks (4ths)", tendencies: "two-chord oscillations (I-II lydian, i-IV dorian), planing (the same shape moved by step), a pedal note held through changes",+ rhythm: "slow: one chord per 2-4 bars", voicing: "wide and open, high register, no thirds low; let voices ring", tension: "a #11 or a 9 against the root; release by the melody settling on the fifth or the root" },+ melody: { range: "C5-C7 bells, pluck echoes above", contour: "sparse, falling phrases of 2-5 notes; rests as long as the notes", density: "0.25-1 note per beat, but a motif at least every 8 bars (the ghost guard)", motif: "a 3-note bell figure that returns, echoed by the pluck at a new register" },+ arrangement: { shape: "slow evolution: add one layer every 4-8 bars, take one away before the end", transitions: "crossfades; a pad change on a bar line", endings: "the motif once more, alone, into the tail" },+ avoid: "formlessness: sustained pads with no onsets and no cadence (the ghost failure); run the guards",+ },+ folk: {+ id: "folk", name: "tender acoustic", atmosphere: "intimate and warm: fingerpicked guitar, soft piano, a harp or celesta line, brushes",+ tempo: [60, 110], meters: ["6/8", "3/4", "4/4"], swing: [0.5, 0.54],+ palette: {+ chords: { inst: "piano", role: "accomp", gainDb: -5, send: 0.35 },+ arp: { inst: "guitar", role: "accomp", gainDb: -4, send: 0.3 },+ lead: { inst: "harp", role: "melody", gainDb: 2, send: 0.35 },+ counter: { inst: "celesta", role: "color", gainDb: -3, send: 0.4 },+ bass: { inst: "bass", role: "bass", gainDb: -6, opts: { drive: 1.1 } },+ kick: { inst: "kick", role: "drum", gainDb: -4, opts: { soft: 1 }, send: 0.2 },+ snare: { inst: "snare", role: "drum", gainDb: -6, opts: { rim: true }, send: 0.4 },+ ghost: { inst: "snare", role: "drum", gainDb: -6, opts: { rim: true }, send: 0.4 },+ hat: { inst: "hat", role: "drum", gainDb: 2, send: 0.3 },+ perc: { inst: "hat", role: "drum", gainDb: 2, opts: { pan: -0.3 }, send: 0.3 },+ },+ alternates: { lead: { piano: { inst: "piano", role: "melody", gainDb: 0, send: 0.3 }, guitar: { inst: "guitar", role: "melody", gainDb: 2, send: 0.3 }, strings: { inst: "strings", role: "melody", gainDb: -2, opts: { attack: 0.2, release: 0.8 }, send: 0.4 } }, chords: { strings: { inst: "strings", role: "accomp", gainDb: -8, opts: { attack: 0.8, release: 1.2, bright: 0.7 }, send: 0.4 } } },+ fx: {},+ stemTargets: { chords: -20, arp: -21, lead: -16, counter: -24, bass: -21, kick: -20, snare: -26, ghost: -28, hat: -30, perc: -30 }, calibrated: false,+ grooves: ["brushes", "pulse", "shuffle"], moods: ["tender", "calm", "wistful", "nostalgic", "hopeful", "romantic"],+ harmony: { modes: ["major", "mixolydian", "dorian", "majorPentatonic", "aeolian"], qualities: "triads, add9, sus2, slash chords with a walking bass (I - V/7 - vi)", tendencies: "I-V/7-vi-IV descents, bVII-IV-I (mixolydian), plagal IV-I endings, a relative minor detour",+ rhythm: "one chord per bar in 6/8 or 3/4; two per bar in 4/4", voicing: "guitar-shaped: root-fifth-tenth, open strings ringing; piano in the middle, melody on top", tension: "a suspended 4th resolving, a IV minor (iv) borrowed for the ache; release plagal (IV-I)" },+ melody: { range: "D4-G5, singable (a 10th at most)", contour: "stepwise with one leap per phrase, rising question, falling answer", density: "1-2 notes per beat, a held note at each phrase end", motif: "a singable 4-bar phrase; the answer repeats its start and changes its end" },+ arrangement: { shape: "guitar alone -> + melody -> + piano and bass -> + counter line -> thin to guitar and melody for the end", transitions: "a pickup note into each phrase; a bar of guitar alone between verses", endings: "plagal cadence, a rolled final chord" },+ avoid: "four-on-the-floor, heavy drums, synth pads, fast arpeggios that bury the melody",+ },+ playful: {+ id: "playful", name: "playful / bouncy", atmosphere: "light, cheeky, springy: marimba and pizzicato-like plucks, a bouncy bass, a skipping kit",+ tempo: [100, 150], meters: ["4/4", "6/8"], swing: [0.5, 0.6],+ palette: {+ lead: { inst: "marimba", role: "melody", gainDb: 2, send: 0.25 },+ chords: { inst: "vibes", role: "accomp", gainDb: -6, opts: { trem: 4.5 }, send: 0.3 },+ arp: { inst: "harp", role: "accomp", gainDb: -4, send: 0.25 },+ counter: { inst: "celesta", role: "color", gainDb: -2, send: 0.35 },+ bass: { inst: "bass", role: "bass", gainDb: -3, opts: { drive: 1.8 } },+ kick: { inst: "kick", role: "drum", gainDb: 0, opts: { soft: 0.6 }, send: 0.1 },+ snare: { inst: "snare", role: "drum", gainDb: 3, send: 0.25 },+ ghost: { inst: "snare", role: "drum", gainDb: 0, opts: { rim: true }, send: 0.2 },+ hat: { inst: "hat", role: "drum", gainDb: 12, send: 0.1 },+ perc: { inst: "hat", role: "drum", gainDb: 10, opts: { pan: -0.35 }, send: 0.15 },+ },+ alternates: { lead: { chip: { inst: "pulse", role: "melody", gainDb: -4, opts: { duty: 0.25 } }, pluck: { inst: "softPluck", role: "melody", gainDb: 5, opts: { decay: 0.2, bright: 6000 } }, bell: { inst: "fmBell", role: "melody", gainDb: -2 } }, bass: { tuba: { inst: "sub", role: "bass", gainDb: -4, opts: { cut: 220 } } } },+ fx: { clean: true },+ stemTargets: { lead: -16, chords: -22, arp: -21, counter: -23, bass: -18, kick: -15, snare: -21, ghost: -26, hat: -28, perc: -29 }, calibrated: false,+ grooves: ["skip", "shuffle", "bounce", "fourFloor"], moods: ["playful", "joy", "curious"],+ harmony: { modes: ["major", "mixolydian", "majorPentatonic", "lydian", "blues"], qualities: "triads and 6ths, dominant 7ths, chromatic passing chords (a diminished between I and ii)", tendencies: "fast harmonic rhythm (2 chords a bar), I-vi-ii-V turnarounds, secondary dominants (V/V), a surprise bVI",+ rhythm: "two chords per bar, on-beat stabs", voicing: "close, mid-high; the bass bounces root-fifth (oom-pah) or walks", tension: "a chromatic approach note, a held dominant with a pause; release with a cheeky button" },+ melody: { range: "C4-C7 (mallets love the top)", contour: "leaps and staccato repeated notes; zig-zags; grace-note slides", density: "2-4 notes per beat, with sudden rests (comic timing)", motif: "a 3-note staccato cell with a leap; answer it lower, then sequence it" },+ arrangement: { shape: "short sections (4-8 bars), stop-time breaks, call and response between lead and counter", transitions: "a stop (all out for a beat), a drum fill, a key lift", endings: "a button: a short tutti hit on 1, sometimes after a comic pause" },+ avoid: "long pads, slow tempo, minor-key sustained melodies",+ },+};++/** Resolve a voice: "beats:x" opts to seconds at this tempo. */+export const resolveVoice = (v: Voice, bpm: number): Voice => {+ if (!v.opts) return v;+ const o: Record<string, number | boolean | string> = {};+ for (const [k, x] of Object.entries(v.opts)) o[k] = typeof x === "string" && x.startsWith("beats:") ? (60 / bpm) * Number(x.slice(6)) : x;+ return { ...v, opts: o };+};++/**+ * The mood controls as real parameters. 0.5 on every control = the palette as calibrated (exactly).+ * energy groove density, drum level, duck depth, section dynamics+ * warmth filters darker, tape drive and wow up, bass up a little+ * brightness filters and pluck brightness open, hats up+ * tension pad detune wider, strings attack shorter, lead decay shorter (the harmony is yours to tense)+ * space reverb sends, delay mix and pad release longer+ */+export const moodVoice = (slot: Slot, v: Voice, m: Required<MoodControls>): { voice: Voice; dGain: number } => {+ const o = { ...(v.opts ?? {}) }, e = m.energy - 0.5, w = m.warmth - 0.5, b = m.brightness - 0.5, t = m.tension - 0.5, s = m.space - 0.5;+ const tone = Math.pow(2, b * 1.2 - w * 0.8);+ const mul = (k: string, f: number) => { if (typeof o[k] === "number") o[k] = (o[k] as number) * f; };+ mul("cut", tone); mul("bright", tone); mul("spread", 1 + t * 1.2); mul("release", 1 + s * 0.8); mul("delayMix", 1 + s * 0.8);+ if (v.inst === "strings") mul("attack", 1 - t * 0.8);+ if (slot === "lead" || slot === "counter") mul("decay", 1 - t * 0.5);+ let dGain = 0;+ if (["kick", "snare", "ghost", "hat", "perc"].includes(slot)) dGain += e * 4;+ if (slot === "hat" || slot === "perc") dGain += b * 4;+ if (slot === "bass") dGain += w * 2;+ const send = v.send === undefined ? undefined : Math.min(1.2, v.send * Math.pow(2, s * 2));+ return { voice: { ...v, opts: o, send, gainDb: v.gainDb + dGain }, dGain };+};+export const moodFx = (fx: PieceFx, m: Required<MoodControls>): PieceFx => {+ const e = m.energy - 0.5, w = m.warmth - 0.5, t = m.tension - 0.5;+ return { ...fx, duck: fx.duck && { ...fx.duck, depth: Math.min(0.8, (fx.duck.depth ?? 0.4) * (1 + e * 0.6)) }, tape: fx.tape ? { ...fx.tape, drive: (fx.tape.drive ?? 1.25) + w * 0.3, wowCents: (fx.tape.wowCents ?? 7) * (1 + w + t * 0.5) } : undefined };+};+export const fullMood = (m: MoodControls): Required<MoodControls> => ({ energy: m.energy ?? 0.5, warmth: m.warmth ?? 0.5, brightness: m.brightness ?? 0.5, tension: m.tension ?? 0.5, space: m.space ?? 0.5 });++for (const v of VOCAB_MORE) VOCAB[v.id] = v;diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabMore.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabMore.tsnew file mode 100644index 0000000..0fd49af--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabMore.ts@@ -0,0 +1,121 @@+// The rest of the style vocabularies (vocab.ts has the type, the mood mapping and the first six).+// Same rule: sound, grooves, harmony language, melody rules, arrangement grammar. Never notes.+import type { StyleVocab, Voice, Slot } from "./vocab";++const V = (inst: Voice["inst"], role: Voice["role"], gainDb: number, opts?: Voice["opts"], send?: number): Voice => ({ inst, role, gainDb, ...(opts ? { opts } : {}), ...(send !== undefined ? { send } : {}) });+/** a drum kit at a level offset: soft (acoustic), tight (band), hard (electronic) */+const kit = (o: number, soft: number, extra: Partial<Record<Slot, Voice>> = {}): Partial<Record<Slot, Voice>> => ({+ kick: V("kick", "drum", 0 + o, { soft }, 0.15), snare: V("snare", "drum", 3 + o, undefined, 0.3), ghost: V("snare", "drum", 0 + o, { rim: true }, 0.25),+ hat: V("hat", "drum", 12 + o, { pan: 0.25 }, 0.1), perc: V("hat", "drum", 10 + o, { pan: -0.3 }, 0.15), ...extra,+});+const T = (x: Partial<Record<string, number>>) => x as Record<string, number>;+const std = T({ kick: -14, snare: -20, ghost: -26, hat: -28, perc: -29, bass: -18, chords: -21, lead: -16.5, counter: -23, arp: -22 });++export const VOCAB_MORE: StyleVocab[] = [+ { id: "musicBox", name: "music box", atmosphere: "small, bright, clockwork, innocent; plucked and never sustained", tempo: [100, 132], meters: ["12/8", "3/4", "6/8"], swing: [0.5, 0.5],+ palette: { lead: V("musicBox", "melody", 0, { grid: true }), arp: V("musicBox", "accomp", -9, { grid: true }), bass: V("musicBox", "bass", -8, { grid: true }), counter: V("bell", "color", -4), chords: V("celesta", "accomp", -10) },+ alternates: { lead: { celesta: V("celesta", "melody", 0), bell: V("fmBell", "melody", -4) } }, fx: {},+ stemTargets: T({ lead: -16, arp: -26, bass: -24, counter: -22, chords: -27 }), calibrated: false, grooves: [], moods: ["joy", "curious", "tender", "playful", "wistful", "eerie"],+ harmony: { modes: ["major", "lydian", "dorian", "aeolian", "majorPentatonic"], qualities: "triads and sus2; a minor music box is a real (and uncanny) sound", tendencies: "any functional progression you write; plagal and deceptive turns read well; a whole-step lift for the payoff", rhythm: "one chord per bar", voicing: "melody C5-C7, bass C3-G3, arpeggio figures in between (you choose the figure)", tension: "an unresolved 4th or a borrowed iv; release on a clean tonic" },+ melody: { range: "C5-C7", contour: "hooky, skipping", density: "more notes, never longer notes (no sustain)", motif: "a 3-5 note hook with a distinctive rhythm; restate it, answer it" },+ arrangement: { shape: "melody -> +bass -> +arpeggio -> +octave sparkle -> bell on the final downbeat", transitions: "add a layer each phrase", endings: "a bell or a single plucked tonic" },+ avoid: "sustained pads, long reverb tails, slow attacks (the ghost failure); see styles/music-box.md for the old recipe's numbers" },+ { id: "nocturne", name: "nocturne / solo piano", atmosphere: "intimate, expressive, late-night: one piano, rubato, pedal", tempo: [50, 76], meters: ["3/4", "6/8", "4/4"], swing: [0.5, 0.5],+ palette: { lead: V("piano", "melody", 0), chords: V("piano", "accomp", 0), bass: V("piano", "bass", 0), counter: V("strings", "color", -10, { attack: 0.9, release: 1.4 }) },+ alternates: {}, fx: {}, stemTargets: T({ lead: -17, chords: -24, bass: -23, counter: -30 }), calibrated: false, grooves: [], moods: ["tender", "melancholy", "wistful", "romantic", "grief"],+ harmony: { modes: ["major", "aeolian", "harmonicMinor", "dorian"], qualities: "triads, 7ths, secondary dominants, borrowed iv, Neapolitan for grief", tendencies: "descending bass lines, circle-of-fifths sequences, deceptive V-vi before the last cadence", rhythm: "one chord per bar, two at cadences", voicing: "left hand broken chords spanning a 10th, no close thirds below C3", tension: "suspensions (4-3, 9-8), appoggiaturas on strong beats" },+ melody: { range: "C4-C6", contour: "arch per phrase, peak about 2/3 through", density: "0.5-2 notes per beat", motif: "a leap then stepwise return; transform it (octave up, in the bass) at the climax" },+ arrangement: { shape: "intro -> theme (question, answer) -> build -> hush -> coda", transitions: "a breath (caesura) before a sudden hush", endings: "a rolled tonic into the pedal" },+ avoid: "octaves in both hands on one downbeat (peaks); a compressor" },+ { id: "minimalist", name: "minimalist / pulse", atmosphere: "hypnotic, curious, clean: interlocking ostinatos that change slowly", tempo: [96, 144], meters: ["4/4", "12/8", "5/4", "7/8"], swing: [0.5, 0.5],+ palette: { arp: V("marimba", "accomp", -3), lead: V("marimba", "melody", 1), bass: V("marimba", "bass", -1), counter: V("vibes", "color", -8, { trem: 4.5 }), chords: V("piano", "accomp", -8), kick: V("kick", "drum", -6, { soft: 1 }, 0.2), ghost: V("snare", "drum", -6, { rim: true }, 0.2), perc: V("hat", "drum", 0, undefined, 0.2) },+ alternates: { arp: { piano: V("piano", "accomp", -4), pluck: V("softPluck", "accomp", 3, { decay: 0.2, bright: 4000 }) } }, fx: {},+ stemTargets: T({ arp: -20, lead: -17, bass: -21, counter: -27, chords: -26 }), calibrated: false, grooves: ["pulse"], moods: ["curious", "tension", "awe", "calm"],+ harmony: { modes: ["dorian", "lydian", "aeolian", "major", "mixolydian"], qualities: "open 5ths, add9, quartal stacks", tendencies: "a two-chord cycle for 8-16 bars, then one note changes", rhythm: "slow; the ostinato is the rhythm", voicing: "mid-register, interlocking; no doubled roots", tension: "phase shifts, added beats, a new bass note under the same pattern" },+ melody: { range: "C4-C6", contour: "cells, not tunes", density: "2-4 onsets per beat in the ostinato", motif: "a 5-8 note cell; change ONE thing every 8-16 bars (add, drop, rotate)" },+ arrangement: { shape: "additive: one layer at a time", transitions: "a change at least every 16 bars", endings: "subtractive, or a hard stop" }, avoid: "a big climax; a change more often than every 4 bars" },+ { id: "jazz", name: "jazz / swing", atmosphere: "loose, warm, clever: swing ride, walking bass, comping piano", tempo: [80, 200], meters: ["4/4", "3/4"], swing: [0.6, 0.67],+ palette: { chords: V("piano", "accomp", -4), lead: V("vibes", "melody", 0, { trem: 4 }), bass: V("bass", "bass", -2, { drive: 1.1 }), counter: V("woodwind", "color", -2, { reed: true }), ...kit(-3, 1) },+ alternates: { lead: { piano: V("piano", "melody", 0), clarinet: V("woodwind", "melody", 0, { reed: true }), flute: V("woodwind", "melody", 0), brass: V("brass", "melody", -3, { bright: 0.8 }) } }, fx: {},+ stemTargets: T({ ...std, chords: -22, lead: -16, counter: -21, bass: -18, kick: -24, snare: -26, ghost: -28, hat: -26, perc: -30 }), calibrated: false, grooves: ["swing", "brushes", "shuffle"], moods: ["playful", "nostalgic", "romantic", "curious", "sensual", "mischief"],+ harmony: { modes: ["major", "dorian", "mixolydian", "melodicMinor", "blues"], qualities: "7ths required; 9ths, 13ths, altered dominants (7b9, 7#11)", tendencies: "ii-V-I, iii-VI-ii-V turnarounds, tritone substitutions, backdoor bVII7-I", rhythm: "two chords a bar at turnarounds", voicing: "rootless shell voicings (3-7, 7-3) in the middle; the walking bass owns roots", tension: "altered dominants, chromatic approach chords; release on a 6/9 or maj7" },+ melody: { range: "A3-C6", contour: "bebop lines: chord tones on beats, approach notes between", density: "swung 8ths with rests", motif: "a riff restated over changing chords (the chords change under it)" },+ arrangement: { shape: "head (theme) -> solos -> head out", transitions: "a 2-bar break, trading 4s", endings: "a tag (the last 2 bars three times) or a ritard on a 6/9" }, avoid: "straight 8ths, triads only" },+ { id: "lullaby", name: "lullaby", atmosphere: "soft, rocking, safe", tempo: [56, 78], meters: ["3/4", "6/8"], swing: [0.5, 0.5],+ palette: { lead: V("celesta", "melody", 0), arp: V("harp", "accomp", -8), bass: V("harp", "bass", -6), counter: V("musicBox", "color", -8), chords: V("strings", "accomp", -12, { attack: 1.0, release: 1.4, bright: 0.6 }) },+ alternates: { lead: { musicBox: V("musicBox", "melody", 0), piano: V("piano", "melody", 0), flute: V("woodwind", "melody", -2) } }, fx: {},+ stemTargets: T({ lead: -17, arp: -24, bass: -25, counter: -27, chords: -28 }), calibrated: false, grooves: [], moods: ["tender", "calm"],+ harmony: { modes: ["major", "majorPentatonic", "mixolydian"], qualities: "triads, add9, sus2", tendencies: "I-IV-I rocking, plagal cadences, a gentle ii", rhythm: "one chord per bar", voicing: "close, mid-high", tension: "almost none; a minor lullaby is flagged for the human check (tips into eerie)" },+ melody: { range: "C4-C6", contour: "rocking stepwise, falling phrase ends", density: "1-2 notes per beat", motif: "a 2-bar rocking figure repeated with a changed ending" },+ arrangement: { shape: "melody + gentle arpeggio, nothing percussive", transitions: "none needed", endings: "the tonic, soft, rolled" }, avoid: "drums, surprise, bright highs" },+ { id: "chiptune", name: "chiptune", atmosphere: "8-bit, bright, game-like: two pulses, a triangle, noise drums", tempo: [110, 170], meters: ["4/4", "6/8"], swing: [0.5, 0.56],+ palette: { lead: V("pulse", "melody", 0, { duty: 0.25, grid: true }), arp: V("pulse", "accomp", -5, { duty: 0.125, pan: 0.25, grid: true }), bass: V("triangle", "bass", 1, { grid: true }), kick: V("noiseDrum", "drum", -2, { grid: true }), snare: V("noiseDrum", "drum", -4, { grid: true }), hat: V("noiseDrum", "drum", -10, { grid: true }) },+ alternates: { lead: { square: V("pulse", "melody", -2, { duty: 0.5, grid: true }) } }, fx: {},+ stemTargets: T({ lead: -16, arp: -22, bass: -18, kick: -18, snare: -20, hat: -28 }), calibrated: false, grooves: ["fourFloor", "bounce", "shuffle", "skip"], moods: ["joy", "playful", "drive", "tension", "mischief"],+ harmony: { modes: ["major", "aeolian", "dorian", "mixolydian"], qualities: "triads; chords are faked by fast arpeggios", tendencies: "I-vi-IV-V, i-bVI-bVII, key changes up a step", rhythm: "one chord per bar", voicing: "arpeggio 16ths across an octave", tension: "a held dominant arpeggio, a pitch-bend-free chromatic climb" },+ melody: { range: "C4-C7", contour: "hooky, leaping", density: "8ths and 16ths", motif: "a 1-bar hook, answered, sequenced" },+ arrangement: { shape: "4 voices max: lead, arp, triangle bass, noise", transitions: "a drum fill, a key change", endings: "a fanfare button" }, avoid: "reverb, more than 4 voices, pads" },+ { id: "lofi", name: "dusty lo-fi hip-hop", atmosphere: "hazy, nostalgic, crackly: FM e-piano, vinyl, a lazy swung beat (the dusty cousin of lo-fi electronic)", tempo: [68, 90], meters: ["4/4"], swing: [0.55, 0.62],+ palette: { chords: V("ePiano", "accomp", -5, { detune: 5 }), lead: V("ePiano", "melody", 4, { detune: 6, width: 0.2 }), bass: V("bass", "bass", -2), counter: V("fmBell", "color", -8), ...kit(-6, 1, { hat: V("hat", "drum", -8, { pan: 0.25 }, 0.2) }) },+ alternates: { lead: { guitar: V("guitar", "melody", 2), flute: V("woodwind", "melody", -2) } }, fx: {},+ stemTargets: T({ ...std, chords: -20, lead: -17, bass: -19, kick: -17, snare: -22, hat: -30 }), calibrated: false, grooves: ["bounce", "halfTime", "shuffle"], moods: ["nostalgic", "calm", "wistful", "sensual"],+ harmony: { modes: ["major", "dorian", "aeolian"], qualities: "maj9, m9, 13, m11", tendencies: "2-4 chord loops, ii-V drifts", rhythm: "1-2 chords a bar", voicing: "e-piano 4-note voicings", tension: "a borrowed iv" },+ melody: { range: "C4-C6", contour: "lazy, behind the beat", density: "sparse", motif: "a 2-bar sampled-sounding phrase" },+ arrangement: { shape: "4 or 8 bar loop with variations", transitions: "a filter or a drop-out", endings: "fade or tape stop" }, avoid: "using it when the brief says clean or upbeat (then use lofiElectronic)" },+ { id: "orchestral", name: "orchestral / epic", atmosphere: "big and heroic: brass theme, string ostinato engine, choir, timpani", tempo: [70, 140], meters: ["4/4", "3/4", "6/8"], swing: [0.5, 0.5],+ palette: { lead: V("brass", "melody", 0, { attack: 0.06 }, 0.45), chords: V("strings", "accomp", -4, { attack: 0.5, release: 1.2 }, 0.5), arp: V("strings", "accomp", -3, { attack: 0.01, release: 0.1, bright: 1.2 }, 0.35), bass: V("strings", "bass", -2, { attack: 0.2, release: 0.8, bass: true, bright: 0.6 }, 0.35), counter: V("choir", "color", -2, { vowel: "a" }, 0.6), perc: V("timpani", "drum", 0, { pitch: 38 }, 0.5), kick: V("kick", "drum", 0, { soft: 1 }, 0.5), snare: V("snare", "drum", -3, undefined, 0.6), hat: V("hat", "drum", 4, undefined, 0.4) },+ alternates: { lead: { strings: V("strings", "melody", 0, { attack: 0.15, release: 0.9, width: 0.4 }, 0.45), horn: V("brass", "melody", -2, { attack: 0.1, bright: 0.6 }, 0.5), flute: V("woodwind", "melody", -2, undefined, 0.5) }, counter: { flute: V("woodwind", "color", -3, undefined, 0.5), harp: V("harp", "color", 0, undefined, 0.5) } }, fx: {},+ stemTargets: T({ lead: -16, chords: -19, arp: -20, bass: -19, counter: -22, perc: -17, kick: -17, snare: -24, hat: -32 }), calibrated: false, grooves: ["epic", "build", "tension", "pulse"], moods: ["heroic", "triumph", "awe", "tension", "grief"],+ harmony: { modes: ["major", "aeolian", "dorian", "mixolydian", "harmonicMinor"], qualities: "triads and power 5ths, sus4 resolving, major IV in minor", tendencies: "i-bVI-bIII-bVII, I-bVII-IV-I (mixolydian heroism), chromatic mediants for arrivals, a pedal under the build", rhythm: "one chord per 1-2 bars, faster into cadences", voicing: "brass in the middle in 3rds and 5ths, strings octaves above, bass in octaves", tension: "a long dominant pedal with the ostinato rising, sus4 held; release to the tonic major with everything" },+ melody: { range: "brass G3-C5 (heroic), strings up to A6", contour: "a rising 4th or 5th then steps; big arcs", density: "long notes over a busy ostinato", motif: "a fanfare cell (rising 4th/5th + rhythm) developed: fragment it in the build, augment it at the climax" },+ arrangement: { shape: "intro (ostinato alone) -> theme (strings) -> theme (brass) -> build -> tutti climax -> quiet coda", transitions: "timpani roll or snare build into downbeats; a bar of silence before the last statement", endings: "a big held chord with timpani, or a hard cut" }, avoid: "all families at once all the time; a brass lead above C6" },+ { id: "suspense", name: "suspense / horror", atmosphere: "unsettling, cold, withheld: low drones, heartbeat pulse, high bowed harmonics, stingers", tempo: [50, 110], meters: ["4/4", "5/4", "3/4"], swing: [0.5, 0.5],+ palette: { chords: V("strings", "accomp", -6, { attack: 2.0, release: 2.5, bright: 0.5 }, 0.6), bass: V("sub", "bass", -6, { cut: 110 }), lead: V("bowedSolo", "melody", 0, { vibrato: 8 }, 0.6), counter: V("celesta", "color", -4, undefined, 0.7), arp: V("strings", "accomp", -6, { attack: 0.005, release: 0.08, bright: 0.8 }, 0.3), kick: V("kick", "drum", 0, { soft: 1 }, 0.4), ghost: V("snare", "drum", -4, { rim: true }, 0.5), perc: V("timpani", "drum", -2, { pitch: 33 }, 0.6), hat: V("hat", "drum", 0, undefined, 0.5) },+ alternates: { counter: { choir: V("choir", "color", -4, { vowel: "u" }, 0.7), bell: V("fmBell", "color", -8, { ratio: 1.41 }, 0.7) }, lead: { choir: V("choir", "melody", -2, { vowel: "o" }, 0.6), cello: V("bowedSolo", "melody", 0, { cello: true, vibrato: 12 }, 0.5) } }, fx: {},+ stemTargets: T({ chords: -21, bass: -20, lead: -19, counter: -24, arp: -22, kick: -17, ghost: -27, perc: -18, hat: -32 }), calibrated: false, grooves: ["pulse", "tension", "epic"], moods: ["tension", "dread", "eerie"],+ harmony: { modes: ["phrygian", "locrian", "harmonicMinor", "wholeTone", "aeolian"], qualities: "clusters, minor 2nds, tritones, minor-major 7th, augmented triads", tendencies: "a pedal that never resolves, chromatic crawl up or down by semitone, i-bII (phrygian), sudden major chord a tritone away", rhythm: "static: one sound for 4-8 bars, then a jolt", voicing: "very low and very high with an empty middle", tension: "withhold resolution; a stinger (all voices, one hit) on the scare; silence right before it" },+ melody: { range: "extremes: below C3 or above C6", contour: "a 2-3 note cell, often a semitone", density: "sparse, irregular", motif: "a semitone sigh or a tritone leap, repeated slower each time" },+ arrangement: { shape: "drone -> pulse enters -> rising ostinato -> stinger on the hit -> silence -> aftermath drone", transitions: "cut to silence; a slow crescendo that stops short", endings: "unresolved: a held cluster, or a single low hit" }, avoid: "a major cadence, melody in the middle register, busy drums" },+ { id: "rock", name: "rock / band", atmosphere: "live-band energy: driven guitars, bass locked to the kick, a tight kit, maybe organ", tempo: [90, 160], meters: ["4/4", "6/8"], swing: [0.5, 0.52],+ palette: { chords: V("strings", "accomp", -6, { attack: 0.005, release: 0.08, bright: 2.0, width: 0.9, grid: true }, 0.2), lead: V("leadSynth", "melody", -2, { cut: 1400, env: 3000, square: 0.8, glide: 0.02 }, 0.25), bass: V("bass", "bass", -2, { drive: 2.2 }), counter: V("organ", "color", -6, { bright: 1.2 }, 0.3), ...kit(0, 0.5) },+ alternates: { chords: { organ: V("organ", "accomp", -4, { bright: 1.3 }, 0.25), piano: V("piano", "accomp", -3, undefined, 0.2) }, lead: { guitar: V("guitar", "melody", 2, undefined, 0.2) } }, fx: {},+ stemTargets: T({ ...std, chords: -19, lead: -16, bass: -17, counter: -23, kick: -13, snare: -17, hat: -27, perc: -26 }), calibrated: false, grooves: ["rock", "halfTime", "shuffle", "fourFloor"], moods: ["drive", "anger", "triumph", "joy", "heroic"],+ harmony: { modes: ["mixolydian", "aeolian", "major", "blues", "dorian"], qualities: "power chords (root-5th-octave), triads, sus4", tendencies: "I-bVII-IV, i-bVI-bVII, riffs on the pentatonic, a chorus a 4th up", rhythm: "one chord per bar in verses, two in choruses", voicing: "power chords low (E2-E4), the bass doubling the root in 8ths", tension: "a riff held on the V, a stop before the chorus" },+ melody: { range: "E3-A5", contour: "riff-based, pentatonic, strong beats", density: "8ths", motif: "a 1-2 bar riff that IS the song; the vocal-like lead answers it" },+ arrangement: { shape: "riff intro -> verse -> pre -> chorus -> verse -> chorus -> bridge -> chorus x2", transitions: "a drum fill and a crash into every section", endings: "a big held last chord with a fill, or a stop on 1" }, avoid: "swing, soft attacks, long pads; the guitar tone here is an approximation: say so" },+ { id: "hipHop", name: "hip-hop / trap", atmosphere: "head-nod or dark trap: heavy 808, crisp clap, rolling hats, a moody loop on top", tempo: [70, 100], meters: ["4/4"], swing: [0.52, 0.6],+ palette: { bass: V("sub", "bass", -4, { cut: 180 }), chords: V("piano", "accomp", -6, undefined, 0.3), lead: V("softPluck", "melody", 4, { decay: 0.5, bright: 3000, delay: "beats:0.75", feedback: 0.25, delayMix: 0.2 }, 0.3), counter: V("strings", "color", -8, { attack: 0.6, release: 1.0, bright: 0.7 }, 0.4), ...kit(0, 0.4, { hat: V("hat", "drum", 14, { pan: 0.15 }, 0.05) }) },+ alternates: { lead: { bell: V("fmBell", "melody", -2, undefined, 0.3), flute: V("woodwind", "melody", -2, undefined, 0.3), choir: V("choir", "melody", -4, { vowel: "o" }, 0.5) }, chords: { pad: V("warmPad", "accomp", -3, { cut: 2000, attack: 0.4, release: 1.2 }, 0.3) } }, fx: { clean: true, duck: { by: "kick", parts: ["chords", "counter"], depth: 0.3, release: 0.2 } },+ stemTargets: T({ ...std, bass: -15, kick: -13, snare: -18, hat: -26, chords: -22, lead: -18, counter: -25 }), calibrated: false, grooves: ["trap", "bounce", "halfTime", "broken"], moods: ["drive", "calm", "nostalgic", "sensual", "anger", "tension"],+ harmony: { modes: ["aeolian", "phrygian", "harmonicMinor", "dorian"], qualities: "minor triads, m7, dim, a single dark chord for 2 bars", tendencies: "2-chord minor loops, i-bVI, i-bII (phrygian menace), a melody over one chord", rhythm: "one chord per 1-2 bars", voicing: "piano or bells high, the 808 low with nothing between", tension: "the 808 sliding or dropping out; a switch-up after 8 bars" },+ melody: { range: "C4-C6", contour: "short repeated figures", density: "sparse over busy hats", motif: "a 1-2 bar loop that repeats (the loop is the hook); vary it every 8 bars" },+ arrangement: { shape: "intro (loop alone) -> 8-bar blocks with drops, switch-ups -> outro loop", transitions: "drop the drums for a bar, a hat roll into the downbeat", endings: "the loop alone, or a cut" }, avoid: "an 808 that owns everything below 150 Hz with no harmonics (phones): check stems" },+ { id: "house", name: "house / EDM", atmosphere: "euphoric, dancing, bright: four-on-the-floor, offbeat bass, stabs, a big pad", tempo: [118, 128], meters: ["4/4"], swing: [0.5, 0.54],+ palette: { chords: V("organ", "accomp", -6, { bright: 1.4, trem: 0 }, 0.3), bass: V("bass", "bass", -3, { drive: 2.0, grid: true }), lead: V("softPluck", "melody", 5, { decay: 0.25, bright: 7000, delay: "beats:0.75", feedback: 0.3, delayMix: 0.25, grid: true }, 0.25), counter: V("warmPad", "color", -4, { cut: 4000, attack: 0.3, release: 1.0 }, 0.4), arp: V("softPluck", "accomp", 3, { decay: 0.15, bright: 5000, grid: true }, 0.2), ...kit(1, 0.3, { hat: V("hat", "drum", 12, { pan: 0.2, grid: true }, 0.1) }) },+ alternates: { chords: { pad: V("warmPad", "accomp", -3, { cut: 3000, attack: 0.2, release: 0.8 }, 0.35), piano: V("piano", "accomp", -3, undefined, 0.25) }, lead: { synth: V("leadSynth", "melody", -2, { cut: 2000, env: 5000 }, 0.3) } }, fx: { clean: true, duck: { by: "kick", parts: ["chords", "counter", "arp"], depth: 0.6, release: 0.18 } },+ stemTargets: T({ ...std, kick: -12, snare: -18, hat: -26, perc: -27, bass: -16, chords: -21, lead: -17, counter: -23, arp: -22 }), calibrated: false, grooves: ["fourFloor", "build", "broken"], moods: ["joy", "drive", "sensual", "hopeful"],+ harmony: { modes: ["aeolian", "dorian", "major", "mixolydian"], qualities: "m7, m9, maj7 stabs; piano house triads", tendencies: "i-VI-III-VII, vi-IV-I-V, 2-chord dorian vamps; a long pedal in the build", rhythm: "one chord per bar or per 2 bars; stabs on offbeats", voicing: "stabs mid-register, the bass on the offbeat 8th", tension: "filter build + snare build + one beat of silence; release = the drop" },+ melody: { range: "C4-C6", contour: "repetitive riffs", density: "8ths and 16ths", motif: "a 1-bar riff repeated 4-8 times with one change" },+ arrangement: { shape: "intro (kick + hats) -> groove -> breakdown (pad + motif) -> build -> drop -> outro (kick)", transitions: "16- or 32-bar blocks; builds of 8", endings: "DJ-friendly: strip back to kick and hats" }, avoid: "swing, busy harmony, a quiet drop" },+ { id: "synthwave", name: "synthwave / retro", atmosphere: "neon-nostalgic, cinematic 80s: big gated snare, pulsing 8th bass, lush pads, a soaring lead", tempo: [80, 118], meters: ["4/4"], swing: [0.5, 0.5],+ palette: { chords: V("strings", "accomp", -6, { attack: 0.4, release: 1.4, bright: 1.1, width: 1 }, 0.5), bass: V("bass", "bass", -3, { drive: 1.8, grid: true }), lead: V("leadSynth", "melody", 0, { glide: 0.06, cut: 2200, env: 4000, square: 0.3 }, 0.4), arp: V("softPluck", "accomp", 3, { decay: 0.18, bright: 4500, delay: "beats:0.75", feedback: 0.35, delayMix: 0.3, grid: true }, 0.3), counter: V("fmBell", "color", -8, undefined, 0.5), ...kit(0, 0.5, { snare: V("snare", "drum", 5, undefined, 0.7) }) },+ alternates: { chords: { pad: V("warmPad", "accomp", -2, { cut: 3200, attack: 0.6, release: 1.6, spread: 0.9 }, 0.5) }, lead: { brass: V("brass", "melody", -2, { bright: 1.3 }, 0.4) } }, fx: { clean: true, duck: { by: "kick", parts: ["chords", "arp"], depth: 0.35, release: 0.25 } },+ stemTargets: T({ ...std, kick: -13, snare: -17, hat: -28, bass: -17, chords: -21, lead: -16, arp: -22, counter: -25 }), calibrated: false, grooves: ["fourFloor", "halfTime", "rock", "build"], moods: ["nostalgic", "drive", "heroic", "romantic", "tension"],+ harmony: { modes: ["aeolian", "dorian", "major", "lydian"], qualities: "minor triads, add9, maj7, sus2", tendencies: "i-bVI-bIII-bVII, vi-IV-I-V, a lydian II for the neon lift", rhythm: "one chord per bar", voicing: "wide pads, bass in driving 8ths on the root", tension: "a long build on the V with the arp rising; release with the gated snare" },+ melody: { range: "A3-E6", contour: "soaring, long notes with glide", density: "long lead notes over a busy arp", motif: "a 2-bar singable lead phrase, stated then lifted an octave" },+ arrangement: { shape: "pad intro -> bass + drums -> lead theme -> breakdown -> lead an octave up -> outro pad", transitions: "a tom-like fill (build), a drop-out bar", endings: "the pad alone, long tail" }, avoid: "trap hats, acoustic instruments, a dry mix" },+ { id: "world", name: "world / modal folk", atmosphere: "rooted, spacious, rhythmic: a drone, a modal melody on plucked strings or a flute, hand percussion cycles (write your own melody; name the tradition you draw on)", tempo: [60, 150], meters: ["7/8", "9/8", "12/8", "6/8", "4/4", "5/4"], swing: [0.5, 0.56],+ palette: { lead: V("woodwind", "melody", 0, { breath: 0.1 }, 0.4), counter: V("harp", "color", -2, undefined, 0.35), arp: V("guitar", "accomp", -4, undefined, 0.3), chords: V("warmPad", "accomp", -8, { cut: 1600, attack: 1.2, release: 2.0, spread: 0.4 }, 0.4), bass: V("sub", "bass", -8, { cut: 180 }), kick: V("timpani", "drum", -2, { pitch: 43, decay: 0.5 }, 0.2), ghost: V("snare", "drum", -2, { rim: true }, 0.25), perc: V("hat", "drum", 8, { pan: -0.3 }, 0.2), hat: V("hat", "drum", 6, { pan: 0.3 }, 0.15) },+ alternates: { lead: { pluck: V("guitar", "melody", 2, undefined, 0.3), marimba: V("marimba", "melody", 1, undefined, 0.3), reed: V("woodwind", "melody", 0, { reed: true }, 0.4), bowed: V("bowedSolo", "melody", 0, undefined, 0.4) } }, fx: {},+ stemTargets: T({ lead: -16, counter: -21, arp: -21, chords: -25, bass: -22, kick: -17, ghost: -24, perc: -28, hat: -30 }), calibrated: false, grooves: ["hand", "pulse", "brushes"], moods: ["calm", "joy", "curious", "mischief", "awe", "sensual"],+ harmony: { modes: ["dorian", "phrygian", "mixolydian", "aeolian", "majorPentatonic", "minorPentatonic", "harmonicMinor"], qualities: "a drone (tonic + 5th) more than chords; modal colour chords sparingly", tendencies: "modal: stay on the tonic drone, move the melody through the mode; a second drone a step away for contrast", rhythm: "the percussion cycle carries it; harmony changes rarely", voicing: "open 5ths, the drone low and wide", tension: "the mode's colour note held against the drone; release on the tonic" },+ melody: { range: "a 10th around the drone", contour: "ornamented steps (grace notes, turns), phrases that return to the drone note", density: "flowing 8ths and 16ths with long held notes", motif: "a modal phrase that grows by adding ornaments on repeats" },+ arrangement: { shape: "drone alone -> melody free -> percussion enters -> faster, denser -> return to the drone", transitions: "an accelerando, a percussion break", endings: "the melody alone on the tonic over the drone" }, avoid: "copying a traditional melody; Western functional cadences everywhere" },+ { id: "choral", name: "choral / sacred", atmosphere: "vast, human, reverent: voices in parts, organ, bells, a slow swell", tempo: [50, 90], meters: ["4/4", "3/4"], swing: [0.5, 0.5],+ palette: { chords: V("choir", "accomp", -2, { vowel: "a", attack: 0.5 }, 0.7), lead: V("choir", "melody", 0, { vowel: "o", attack: 0.25, width: 0.3 }, 0.6), bass: V("organ", "bass", -4, { bright: 0.5 }, 0.5), counter: V("fmBell", "color", -8, undefined, 0.7), arp: V("harp", "accomp", -6, undefined, 0.6), perc: V("timpani", "drum", -4, { pitch: 38 }, 0.6), kick: V("timpani", "drum", -6, { pitch: 31, decay: 1.2 }, 0.6) },+ alternates: { chords: { organ: V("organ", "accomp", -4, { bright: 0.9 }, 0.6), strings: V("strings", "accomp", -4, { attack: 0.8, release: 1.6 }, 0.6) }, lead: { bowed: V("bowedSolo", "melody", 0, undefined, 0.6), flute: V("woodwind", "melody", -2, undefined, 0.6) } }, fx: {},+ stemTargets: T({ chords: -19, lead: -17, bass: -21, counter: -26, arp: -24, perc: -20 }), calibrated: false, grooves: ["pulse"], moods: ["awe", "grief", "hopeful", "tender", "heroic"],+ harmony: { modes: ["major", "aeolian", "dorian", "lydian"], qualities: "triads in 4 parts, suspensions, the picardy third", tendencies: "chorale motion: I-IV-V-I, vi-IV-I-V, plagal amen (IV-I), deceptive V-vi before the final cadence", rhythm: "one chord per beat or per half bar (chorale), slower in swells", voicing: "SATB spacing: no gaps wider than an octave between upper voices, bass free; avoid parallel 5ths", tension: "4-3 suspensions, a held dominant; release on a plagal amen" },+ melody: { range: "C4-G5 (singable)", contour: "stepwise, phrase-shaped like breath", density: "1 note per beat or slower", motif: "a hymn-like phrase whose cadence changes each time" },+ arrangement: { shape: "a single voice -> full parts -> a swell -> a hush -> the final chord", transitions: "a fermata (breath) between phrases", endings: "a plagal amen or a picardy third, long tail" }, avoid: "fast rhythms, drums, choir as a lead above G5" },+];diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabTrim.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabTrim.tsnew file mode 100644index 0000000..d207919--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/vocabTrim.ts@@ -0,0 +1,247 @@+// GENERATED by `node tools/music.mjs calibrate`: per style, the gain trim (dB) that brings each palette+// voice's stem to its target on a neutral test phrase. Calibrated styles (listened) are never trimmed.+import type { Slot } from "./vocab";+export const VOCAB_TRIM: Record<string, Partial<Record<Slot, number>>> = {+ drive: {+ chords: 5.3,+ lead: 7.4,+ counter: 12,+ bass: 3.1,+ kick: 0.5,+ snare: 8.5,+ arp: 1.2,+ perc: 8.3+ },+ cinematic: {+ chords: 5.2,+ lead: 4.5,+ counter: 12,+ bass: 4.3,+ kick: -4.4,+ arp: 7.4+ },+ ambient: {+ chords: 2.5,+ lead: 1.3,+ counter: 0.8,+ bass: -0.3,+ kick: -2.4,+ arp: 3.1+ },+ folk: {+ chords: 12,+ lead: 12,+ counter: 11.2,+ bass: 1.6,+ kick: -0.5,+ ghost: 9.4,+ arp: 12,+ perc: 12+ },+ playful: {+ chords: 1.7,+ lead: 2.1,+ counter: 12,+ bass: 1.4,+ kick: 0.3,+ snare: 5.1,+ hat: 10.2,+ arp: 12,+ perc: 9.7+ },+ musicBox: {+ chords: 4.7,+ lead: 3.5,+ counter: 4.3,+ bass: 5,+ arp: 3+ },+ nocturne: {+ chords: 12,+ lead: 12,+ counter: 12,+ bass: 6.3+ },+ minimalist: {+ chords: 12,+ lead: 2.1,+ counter: 11.7,+ bass: -3.9,+ arp: 2.5+ },+ jazz: {+ chords: 12,+ lead: 3.8,+ counter: 10.5,+ bass: 0.7,+ kick: 2.8,+ ghost: 10.5,+ hat: 12,+ perc: 11+ },+ lullaby: {+ chords: 3.5,+ lead: 5.3,+ counter: 12,+ bass: 12,+ arp: 12+ },+ chiptune: {+ lead: 7.4,+ bass: -0.8,+ kick: 9.6,+ snare: 10.7,+ arp: 12+ },+ lofi: {+ chords: 10.2,+ lead: 3.5,+ counter: 12,+ bass: -0.1,+ kick: 3.4,+ snare: 9.2,+ ghost: 12,+ hat: 12+ },+ orchestral: {+ chords: 3.6,+ lead: 9.2,+ counter: 0.3,+ bass: 2.9,+ kick: -3.3,+ snare: 8.2,+ arp: 7.4,+ perc: 4.2+ },+ suspense: {+ chords: 5.2,+ lead: 7.3,+ counter: 12,+ bass: -0.1,+ kick: -3.4,+ arp: 8.7,+ perc: 10.4+ },+ rock: {+ chords: 5.1,+ lead: 11.9,+ counter: 12,+ bass: 1.2,+ kick: 1.2,+ snare: 8.2,+ hat: 8.6,+ perc: 7+ },+ hipHop: {+ chords: 12,+ lead: -1.3,+ counter: 12,+ bass: 1.5,+ kick: 1.4,+ snare: 7.2,+ hat: 9.6,+ perc: 9.9+ },+ house: {+ chords: 11.2,+ lead: -0.7,+ counter: 10.9,+ bass: 3.3,+ kick: 1.6,+ snare: 6.7,+ arp: 1.5,+ perc: 7.3+ },+ synthwave: {+ chords: 3.9,+ lead: 11.7,+ counter: 12,+ bass: 2.7,+ kick: 1.4,+ snare: 6.7,+ arp: 1.1,+ perc: 6.2+ },+ world: {+ chords: 4.9,+ lead: 8.7,+ counter: 12,+ bass: -1.6,+ kick: 2.3,+ ghost: 11.5,+ arp: 12+ },+ choral: {+ chords: -7.9,+ lead: -3.1,+ counter: 12,+ bass: 12,+ arp: 12,+ perc: 9.5+ }+};+/** Where a 12 dB trim could not reach the target (long-decaying plucks read low as active RMS), the target moves to where the voice sits. */+export const VOCAB_TARGET_FIX: Record<string, Partial<Record<Slot, number>>> = {+ drive: {+ counter: -3.3+ },+ cinematic: {+ counter: -14.7+ },+ ambient: {},+ folk: {+ chords: -13,+ lead: -2.8,+ arp: -1.9,+ perc: -5.8+ },+ playful: {+ arp: -1.4+ },+ musicBox: {},+ nocturne: {+ chords: -6.3+ },+ minimalist: {+ chords: -11.1+ },+ jazz: {+ chords: -10.5+ },+ lullaby: {+ counter: -4.7,+ bass: -1,+ arp: -4.3+ },+ chiptune: {+ arp: -1.1+ },+ lofi: {+ counter: -7.1,+ ghost: -1.1,+ hat: -13+ },+ orchestral: {},+ suspense: {+ counter: -3+ },+ rock: {+ counter: -7.4+ },+ hipHop: {+ chords: -14.8,+ counter: -4.2+ },+ house: {},+ synthwave: {+ counter: -4.1+ },+ world: {+ counter: -17.1,+ arp: -3.2+ },+ choral: {+ counter: -4.5,+ arp: -2.3+ }+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/score.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/score.tsindex 4560b20..8284a4d 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/score.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/score.ts@@ -1,39 +1,27 @@-// The scaffold score: a two-section MusicPlan on the music module, so every new film starts with the-// breadth visible (spec 08 section 12). Section A: music box, JOY, C major, I-IV-V-I. Section B: the-// same box turns WISTFUL in D dorian (same notes, new home; the B natural is the colour). Notes are-// data; the plan fits ANY film length (tempo, then repeats); pure in (frames, sampleRate).+// The scaffold score: an EMPTY composition. A new film starts with no notes at all, only the shape+// of what you will write: the style vocabulary, the mood, the tempo and key you choose, your own+// chords, motifs and form. Nothing here plays until you compose it (composePiece throws on missing+// material). Workflow: references/music/compose.md. Vocabularies: music/vocab.ts.//-// CHANGE NOTE: until the music module landed, this file was 14 lines of sine plucks on a fixed-// C-major arpeggio plus a bell. Nothing imported it, so no shipped film changes sound. The worked-// butterfly film keeps its own score (example/.../alive/score.ts), untouched: it sounds the same.-import { line, type Piece } from "./music/plan";+// CHANGE NOTE: this file used to hold a full C-major music-box piece. Films copied it, so it has been+// removed. No shipped film imported it. The butterfly film keeps its own score (example/.../alive/score.ts).+import type { Material } from "./music/compose";+import { composePiece } from "./music/compose";import { filmAudio } from "./music/render";-const B = 4; // 12/8: four dotted-quarter beats a bar, triplet subdivisions-const arp = (r: string, f: string, t: string) => Array.from({ length: 12 }, (_, i) => `${[r, f, t, f][i % 4]}:1/3`).join(" ");--export const fixturesPiece = (bpm = 120): Piece => ({- title: "Fixtures: joy, then wistful", seed: 3, tail: 1.6,- harmony: [[0, "C"], [4, "F"], [8, "G"], [12, "C"], [16, "Dm"], [20, "G/D"], [24, "Dm"], [28, "Dm"]].map(([t, name]) => ({ t: t as number, name: name as string })),- plan: {- style: "musicBox", tempo: bpm, meter: "12/8", ritard: 0.85,- sections: [- { id: "joy", bars: 4, mood: "joy", key: "C", mode: "major", melody: ["hook", "arpeggio"], dyn: [0.75, 0.8], repeatable: true },- { id: "wistful", bars: 4, mood: "wistful", key: "D", mode: "dorian", melody: ["themeTransformation"], dyn: [0.7, 0.6], ending: "button", repeatable: true, optional: true },- ],- },- parts: [- // the hook (E-G-A-G), answered; then the same hook re-seated on D dorian- { id: "melody", inst: "musicBox", role: "melody", opts: { grid: true }, notes: line(0, [- "E5:1 G5:2/3 A5:1/3 G5:1 E5:1", "A5:1 C6:2/3 A5:1/3 F5:2", "G5:1 A5:2/3 G5:1/3 D5:1 B5:1", "C6:4",- "F5:1 A5:2/3 B5:1/3 A5:1 F5:1", "B5:1 D6:2/3 B5:1/3 G5:2", "A5:1 B5:2/3 A5:1/3 E5:1 F5:1", "D5:4"].join(" | "), { role: "melody", v: 0.75, bpb: B }) },- { id: "arp", inst: "musicBox", role: "accomp", gainDb: -7, opts: { grid: true }, notes: line(0, [- arp("C5", "G5", "E5"), arp("C5", "A5", "F5"), arp("B4", "G5", "D5"), arp("C5", "G5", "E5"),- arp("D5", "A5", "F5"), arp("D5", "B5", "G5"), arp("D5", "A5", "F5"), "D5:1/3 A5:1/3 F5:1/3"].join(" | "), { role: "accomp", v: 0.5, bpb: B }) },- { id: "bass", inst: "musicBox", role: "bass", gainDb: -8, opts: { grid: true }, notes: line(0, "C3:2 G3:2 | F3:2 C3:2 | G3:2 D3:2 | C3:4 | D3:2 A3:2 | G3:2 D3:2 | D3:2 A3:2 | D3:1", { role: "bass", v: 0.62, bpb: B }) },- { id: "bell", inst: "bell", role: "color", notes: line(28, "D6:1", { role: "color", v: 0.7, bpb: B }) },- ],+/** Fill every field for THIS film. Placeholders are written as <angle brackets> and are rejected. */+export const scoreSkeleton = (): Material => ({+ style: "lofiElectronic", // a key of VOCAB, chosen from the brief (node tools/music.mjs vocab)+ title: "<this film's score>", seed: 0, mood: "calm", // your seed; a mood row that matches the brief+ bpm: 0, key: "<tonic>", mode: "major",+ chords: {}, // "<name>": { voicing: "[<notes>]", bass: "<one bar>" }+ motifs: {}, // "<motif>": "<bars of notation>"+ grooves: {}, // main: { family: "<one of the style's grooves>", density: 0.5, variation: 0.4 }+ sections: [], // { kind, bars, harmony: [...], lead: [...] } ... land the home chord on the picture's key beat});-/** A film's `audio`: exactly the film's length at any sample rate. The same signature as before. */-export const fixturesScore = (fps: number, bpm: number, frames: number) => filmAudio(fixturesPiece(bpm), frames / fps);+/** A film's `audio`: your composition, fitted to exactly the film's length (it ends on its phrase). */+export const filmScore = (m: Material, fps: number, frames: number) => {+ if (!m.bpm || /<|>/.test(JSON.stringify(m))) throw new Error("score.ts: the score is still a skeleton. Compose it (references/music/compose.md).");+ return filmAudio(composePiece(m), frames / fps);+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchExample.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchExample.tsnew file mode 100644index 0000000..015f1fa--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-launchExample.ts@@ -0,0 +1,4 @@+import { launchExample } from "../canvas-core/launchExample";+import { mountFilm } from "./page";++mountFilm(launchExample);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjsnew file mode 100644index 0000000..516e47c--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/music-unit.mjs@@ -0,0 +1,133 @@+#!/usr/bin/env node+// Music unit test: styles are vocabularies, the composer writes the notes.+// node tools/music-unit.mjs+// Asserts: the approved launch score is bit-identical as composed material (md5); neutral mood is the+// calibrated palette exactly; missing material is an error, never a default; every groove family+// parses in every meter and varies with the seed; every style vocabulary composes, renders (true peak+// <= -1 dBTP, loudness at its master target) and meets its stem targets; the stem meter catches a sub+// 9 dB hot that LUFS alone passes; a seamless loop; a film fit that ends on its phrase; the score+// scaffold is empty; and the novelty gate hears the copy Alex heard (Daylight vs the launch score).+import { strict as assert } from "node:assert";+import { createHash } from "node:crypto";+import { build } from "esbuild";+import { join } from "node:path";++const src = join(import.meta.dirname, "../src/canvas-core/music/index.ts");+const js = (await build({ entryPoints: [src], bundle: true, write: false, platform: "neutral", format: "esm", logLevel: "error" })).outputFiles[0].text;+const M = await import("data:text/javascript;base64," + Buffer.from(js).toString("base64"));+const md5 = (r) => { const h = createHash("md5"); h.update(Buffer.from(r.L.buffer, r.L.byteOffset, r.L.byteLength)); h.update(Buffer.from(r.R.buffer, r.R.byteOffset, r.R.byteLength)); return h.digest("hex"); };+const ok = []; const t0 = Date.now();+const pass = (s) => { ok.push(s); console.log(` ok ${s}`); };++// 1. The approved launch score, now composed material on the lo-fi electronic vocabulary: bit-identical.+const LAUNCH3_MD5_48K = "d20789f2344e6fff0d2a380c7c7825d2";+const launch = M.renderPiece(M.launchLofi3(), 48000);+assert.equal(md5(launch), LAUNCH3_MD5_48K, "launchLofi3 audio changed");+{ const tp = M.truePeak([launch.L, launch.R]).dbtp, lu = M.loudness([launch.L, launch.R], 48000).integrated; assert(tp <= -1 && Math.abs(lu + 14) <= 1);+ pass(`launchLofi3 md5 ${LAUNCH3_MD5_48K} (48 kHz), ${lu.toFixed(2)} LUFS, ${tp.toFixed(2)} dBTP`); }++// 2. Mood controls: all at 0.5 = the calibrated palette exactly; moved, the sound changes.+const SR = 24000, launchMd5_24 = md5(M.renderPiece(M.launchLofi3(), SR));+assert.equal(md5(M.renderPiece(M.composePiece({ ...M.launchLofi3Material(), moodControls: { energy: 0.5, warmth: 0.5, brightness: 0.5, tension: 0.5, space: 0.5 } }), SR)), launchMd5_24, "neutral mood must be identity");+assert.notEqual(md5(M.renderPiece(M.composePiece({ ...M.launchLofi3Material(), moodControls: { warmth: 0.9, space: 0.8 } }), SR)), launchMd5_24);+pass("mood controls: 0.5 on all five = identical audio; warmth/space moved = different audio");++// 3. No defaults: missing material is an error that says what to compose.+const base = M.launchLofi3Material();+for (const [what, m] of [+ ["harmony", { ...base, sections: base.sections.map((s, i) => (i === 1 ? { ...s, harmony: [] } : s)) }],+ ["melody", { ...base, sections: base.sections.map((s) => ({ ...s, lead: undefined })) }],+ ["chord voicing", { ...base, chords: { Dm9: base.chords.Dm9 } }],+ ["groove", { ...base, grooves: {} }],+ ["form", { ...base, sections: [] }],+ ["seed/mood", { ...base, mood: undefined }],+]) assert.throws(() => M.composePiece(m), /compose/, `missing ${what} must throw`);+{ const sjs = (await build({ entryPoints: [join(import.meta.dirname, "../src/canvas-core/score.ts")], bundle: true, write: false, platform: "neutral", format: "esm", logLevel: "error" })).outputFiles[0].text;+ const S = await import("data:text/javascript;base64," + Buffer.from(sjs).toString("base64")); assert.throws(() => S.filmScore(S.scoreSkeleton(), 30, 300), /skeleton/); }+pass("missing harmony, melody, voicing, groove, form, mood: each throws; the score scaffold is empty and refuses to play");++// 4. Groove families: every family parses in every meter, deterministic, and the seed varies the bars.+{ const meters = ["2/4", "3/4", "4/4", "5/4", "6/8", "7/8", "9/8", "12/8"]; let n = 0;+ for (const family of Object.keys(M.GROOVE_FAMILIES)) for (const meter of meters) for (let b = 0; b < 4; b++) {+ const g = { family, density: 0.8, variation: 0.8, fill: true }, bar = M.grooveBar(g, meter, 7, b, b, 4), again = M.grooveBar(g, meter, 7, b, b, 4);+ assert.deepEqual(bar, again); for (const x of Object.values(bar)) if (x) { M.line(0, x, { role: "drum", bpb: M.beatsPerBar(meter) }); n++; }+ }+ const bars = (seed) => Array.from({ length: 8 }, (_, b) => JSON.stringify(M.grooveBar({ family: "bounce", density: 0.7, variation: 0.8 }, "4/4", seed, b, b, 8)));+ assert.notDeepEqual(bars(1), bars(2)); assert(new Set(bars(1)).size > 1);+ pass(`${Object.keys(M.GROOVE_FAMILIES).length} groove families x ${meters.length} meters: ${n} bars parse, deterministic, seed-varied`); }++// 5. Every style vocabulary: a neutral test signal composes, renders, masters and meets its stem targets.+for (const v of Object.values(M.VOCAB)) {+ const p = M.composePiece(M.testMaterial(v, { bars: 4 })), r = M.renderPiece(p, SR), tp = M.truePeak([r.L, r.R]).dbtp, lu = M.loudness([r.L, r.R], SR).integrated;+ const target = M.STYLES[v.id].master === "dense" ? -14 : -16, b = M.measureStems(p, SR);+ assert(tp <= -1, `${v.id}: ${tp} dBTP`); assert(lu <= target + 1 && lu >= target - 6, `${v.id}: ${lu} LUFS vs ${target}`);+ if (!v.calibrated) assert(b.pass, `${v.id}: stems ${b.rows.filter((x) => !x.ok).map((x) => `${x.id} ${x.offDb.toFixed(1)}`).join(", ")}`);+ assert(!p.parts.some((x) => ["ePiano", "vinyl"].includes(x.inst)) || v.id === "lofi", `${v.id}: ePiano/vinyl only in the dusty lofi style`);+}+pass(`${Object.keys(M.VOCAB).length} style vocabularies compose, render (true peak <= -1 dBTP), master; uncalibrated palettes meet their stem targets on the test signal`);++{ const b = M.measureStems(M.launchLofi3(), SR); assert(b.pass); const w = b.rows.filter((x) => x.offDb !== null).reduce((a, x) => (Math.abs(x.offDb) > Math.abs(a.offDb) ? x : a));+ pass(`lofiElectronic (calibrated on the listened launch score): stems within +-3 dB, worst ${w.id} ${w.offDb.toFixed(1)} dB`); }++// 6. The lesson: a sub 9 dB hot still masters to -14 LUFS; only the stem meter sees it.+{ const hot = M.composePiece({ ...base, levels: { bass: 9 } }), r = M.renderPiece(hot, SR), lu = M.loudness([r.L, r.R], SR).integrated, b = M.measureStems(hot, SR), sub = b.rows.find((x) => x.id === "bass");+ assert(Math.abs(lu + 14) <= 1 && !b.pass && sub.offDb > 7, "the stem meter must flag a hot sub that LUFS passes");+ pass(`hot sub: mix ${lu.toFixed(1)} LUFS (passes), stem meter flags bass +${sub.offDb.toFixed(1)} dB`); }++// 7. A seamless loop (composer's material, loop: true): the seam is an ordinary sample step.+{ const lp = M.renderLoop(M.composePiece(M.testMaterial(M.VOCAB.lofiElectronic, { loop: true })), SR), n = lp.L.length, steps = [];+ for (let i = 1; i < n; i += 3) steps.push(Math.abs(lp.L[i] - lp.L[i - 1])); steps.sort((a, b) => a - b);+ const p999 = steps[Math.floor(steps.length * 0.999)], seam = Math.max(Math.abs(lp.L[0] - lp.L[n - 1]), Math.abs(lp.R[0] - lp.R[n - 1]));+ assert(seam <= p999, `seam ${seam} > ${p999}`); assert.equal(md5(lp), md5(M.renderLoop(M.composePiece(M.testMaterial(M.VOCAB.lofiElectronic, { loop: true })), SR)));+ pass(`loop: seam step ${seam.toFixed(4)} <= p99.9 ${p999.toFixed(4)}, deterministic`); }++// 8. Film fit: the composition is re-formed (stretch section repeated or dropped) and ends on its phrase.+for (const secs of [70, 90, 110]) {+ const f = M.fitScore(M.launchLofi3(), secs), perf = M.perform(f.piece, f.tempo, { expressive: true }), p = f.piece;+ assert.equal(p.harmony[p.harmony.length - 1].name, "Cmaj9"); assert.equal(f.form, "full");+ assert(Math.abs(perf.lastOnset - (secs - p.tail)) < 0.05); assert(f.tempo >= 90 * 0.88 && f.tempo <= 90 * 1.12);+ pass(`fit ${secs} s: ${p.plan.sections[0].bars} bars at ${f.tempo.toFixed(1)} bpm, last onset ${perf.lastOnset.toFixed(2)} s on Cmaj9`);+}+{ const a = M.filmAudio(M.launchLofi3(), 40)(16000); assert.equal(a[0].length, 40 * 16000); pass("filmAudio: exactly the film's length"); }++// 9. Composer-facing fixes (from the blind composer's report).+{ const t = M.testMaterial(M.VOCAB.playful, { bars: 4 }), sec = t.sections[0];+ const once = M.composePiece({ ...t, sections: [{ ...sec, lead: sec.lead.slice(0, 2) }] });+ assert(once.warnings.some((w) => /plays once/.test(w)), "a short line must warn");+ const looped = M.composePiece({ ...t, sections: [{ ...sec, lead: sec.lead.slice(0, 2), loopLines: true }] });+ assert.equal(looped.warnings.length, 0); assert.equal(looped.parts.find((p) => p.id === "lead").notes.length, 2 * once.parts.find((p) => p.id === "lead").notes.length);+ pass("lines: a short line warns; loopLines repeats it to fill the section");+ const lv = (x) => M.composePiece({ ...t, levels: x }).parts.find((p) => p.id === "lead").gainDb;+ assert(Math.abs(lv({ lead: 2 }) - lv({}) - 2) < 1e-9); pass("levels: a dB offset on top of the calibrated gain");+ const vsum = (en) => M.composePiece({ ...t, sections: [{ ...sec, energy: en }] }).parts.flatMap((p) => p.notes).reduce((a, n) => a + n.v, 0);+ assert(vsum(0.2) < vsum(0.5) && vsum(0.8) > vsum(0.5)); pass("section energy scales the dynamics of every part");+ const lit = { main: { kick: ["C4:4", "r:2 C4:2"] } }, mk = (from) => M.composePiece({ ...t, grooves: lit, sections: [{ kind: "hook", bars: from, harmony: ["c0"], lead: sec.lead.slice(0, from) }, { kind: "hook", bars: 2, harmony: ["c0"], lead: sec.lead.slice(0, 2) }] });+ const kicks = (p, bar) => p.parts.find((x) => x.id === "kick").notes.filter((n) => n.t >= bar * 4 && n.t < bar * 4 + 4).map((n) => n.t - bar * 4);+ assert.deepEqual(kicks(mk(1), 1), [0]); assert.deepEqual(kicks(mk(2), 2), [0]); pass("written grooves cycle from each section's first bar");+ const orch = (key, tonic) => M.composePiece(M.testMaterial(M.VOCAB.orchestral, { bars: 2, key, tonic })).parts.find((p) => p.id === "perc").opts.pitch % 12;+ assert.equal(orch("C", 0), 0); assert.equal(orch("D", 2), 2); pass("timpani in a drum lane is tuned to the key");+ const mod = M.composePiece({ ...t, sections: [sec, { ...sec, key: "D" }] }); assert.deepEqual(mod.plan.sections.map((x) => x.key), ["C", "D"]); pass("per-section key: the key check reads each key region");+ // the blind composer's case: Db lydian whose notes lean on Ab (the same pitch set as Ab major), tonic ~12 % of note time+ const lp = (key, mode, src) => ({ title: "k", seed: 1, tail: 1, harmony: [], plan: { style: "ambient", tempo: 70, meter: "4/4", sections: [{ id: "a", bars: 5, mood: "awe", key, mode, melody: ["stepwise"], dyn: [0.5, 0.5] }] }, parts: [{ id: "m", inst: "fmBell", role: "melody", notes: M.line(0, src, { role: "melody", bpb: 4 }) }] });+ const src = "Db4:2 Ab4:2 | Ab4:2 Eb4:2 | Eb4:1 F4:2 G4:1 | G4:1 Bb4:2 C5:1 | C5:1 Eb5:1 r:2";+ assert(M.detectMode(M.line(0, src, { role: "melody", bpb: 4 }), ["lydian", "major", "aeolian", "dorian", "mixolydian"])[0].tonic !== "Db", "fixture must fool the raw detector");+ assert.deepEqual(M.planProblems(lp("Db", "lydian", src)), []); assert(M.planProblems(lp("E", "major", src)).length > 0);+ pass("Db lydian leaning on Ab is accepted (scale fits, tonic heard); a wrong key is still flagged");+ const st = { lead: [new Float32Array([0.3 * 10 ** ((-16.5 + 5) / 20) / 0.3]), new Float32Array(1)] };+ assert(M.stemBalance(st, { lead: -16.5 }).pass); assert(!M.stemBalance({ lead: [new Float32Array([10 ** ((-16.5 + 7) / 20)]), new Float32Array(1)] }, { lead: -16.5 }).pass); pass("stems: the lead may sit +3 dB over tolerance (guards win), not more");+ const w = M.composePiece(M.testMaterial(M.VOCAB.world, { bars: 4 })), wr = M.renderPiece(w, SR), g = M.guardReport(wr, SR, wr.L.length / SR);+ assert(Number.isFinite(g.lufs) && g.ghost.windows > 0); pass(`guards run on a 7/8 score (${g.ghost.windows} windows)`); }++// 10. Novelty: the copy Alex heard scores as a copy; the shipped demos stay apart; a reused fragment fails.+{ const d = M.novelty(M.daylightCopy(), M.DEMOS);+ assert(!d.pass && d.worst.name.startsWith("launchLofi") && d.worst.score > 0.6, `daylight copy scored ${d.worst.score} vs ${d.worst.name}`);+ pass(`novelty: Daylight vs ${d.worst.name} = ${d.worst.score} (threshold ${d.threshold}): FAIL, as Alex heard it`);+ let worst = { score: 0 };+ for (const n of Object.keys(M.DEMOS)) { const fam = Object.values(M.DEMO_FAMILIES).find((f) => f.includes(n)) ?? [n], v = M.novelty(M.DEMOS[n](), M.DEMOS, fam); assert(v.pass, `${n} vs ${v.worst.name} ${v.worst.score}`); if (v.worst.score > worst.score) worst = { ...v.worst, of: n }; }+ pass(`novelty: every demo vs every other demo passes (closest: ${worst.of} vs ${worst.name} ${worst.score})`);+ const quoted = M.composePiece({ ...M.testMaterial(M.VOCAB.playful, { bars: 4 }), sections: [{ kind: "hook", bars: 2, harmony: ["c0"], groove: null, lead: ["G5:1 B5:.5 C6:.5 B5:1 G5:1", "E5:1 G5:.5 A5:.5 G5:1 E5:1"] }] });+ const src = M.composePiece({ ...M.testMaterial(M.VOCAB.playful, { bars: 4 }), sections: [{ kind: "hook", bars: 2, harmony: ["c0"], groove: null, lead: ["D5:1 F#5:.5 G5:.5 F#5:1 D5:1", "B4:1 D5:.5 E5:.5 D5:1 B4:1"] }] });+ const r = M.novelty(quoted, { src: () => src }); assert(!r.pass && r.rows[0].reusedFragments > 0, "a transposed quote must be caught");+ pass(`novelty: a transposed 6-note quote of a shipped line fails (${r.rows[0].reusedFragments} reused fragments)`); }++console.log(`music unit: ${ok.length} checks PASS in ${((Date.now() - t0) / 1000).toFixed(0)} s`);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjsindex 3df8715..c0c6bce 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/music.mjs@@ -3,8 +3,18 @@// clipping on the way) and meters the DECODED file: integrated LUFS (BS.1770-4), LRA (EBU 3342),// true peak (4x), onsets/s (spectral flux), spectral centroid; plus note-data numbers.//-// node tools/music.mjs list-// node tools/music.mjs render <piece> <out.wav> [--seconds 45] [--flat] [--tempo 66] [--fit]+// <piece> is YOUR score, a module: path/to/score.ts#exportName (a Material, a Piece, or a function+// returning either); or the name of a shipped demo (listening references, never a film's score).+//+// node tools/music.mjs vocab [style] # the style vocabularies: palette, grooves, harmony, melody, arrangement+// node tools/music.mjs check <piece> [--fit --seconds N] # everything: key/mode, warnings, master, ghost/reverb/masking guards, stems, novelty+// node tools/music.mjs novelty <piece> [more ...] # vs every shipped piece (and pairwise when several); FAILS above the threshold or on a reused fragment+// node tools/music.mjs list # shipped demos and fixtures+// node tools/music.mjs render <piece> <out.wav|out.mp3> [--seconds 45] [--flat] [--tempo 66] [--fit] [--loop] [--stems]+// node tools/music.mjs stems <piece> [--seconds 45] [--fit] # each part's stem RMS vs its target, flags > 3 dB off+// (--fit uses fitScore: the piece's refit, e.g. lofiElectronic adds loop cycles so it still ends on its outro;+// --loop renders a seamless loop, automatic for a plan.loop piece. LUFS alone once hid a sub 7-10 dB too hot:+// balance a mix by its stems, then master.)// node tools/music.mjs meter <file.wav|file.mp4> [more files]// node tools/music.mjs samples <outdir> # the whole deliverable set + meters.json + .m4a// node tools/music.mjs score <piece> # the text score, bar by bar@@ -22,6 +32,23 @@ const load = async () => {return import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));};+/** A piece by demo name, or from a module: "path.ts#export" (default export if no #). Material is composed. */+const getPiece = async (M, ref) => {+ if (!ref) throw new Error("name a piece: path/to/score.ts#export, or a demo (node tools/music.mjs list)");+ const fromDemo = M.DEMOS[ref] ?? M.FIXTURES[ref];+ let v;+ if (fromDemo) v = fromDemo;+ else {+ const [file, exp = "default"] = ref.split("#");+ if (!existsSync(resolve(file))) throw new Error(`no demo or module "${ref}" (demos: node tools/music.mjs list)`);+ const r = await build({ entryPoints: [resolve(file)], bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });+ const mod = await import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));+ v = mod[exp]; if (v === undefined) throw new Error(`${file} has no export "${exp}" (exports: ${Object.keys(mod).join(", ")})`);+ }+ const make = () => { const x = typeof v === "function" ? v() : v; return x && x.sections && x.chords ? M.composePiece(x) : x; };+ return { make, name: ref, demo: Boolean(fromDemo) };+};+export const writeWavFloat = (path, L, R, sr = SR) => {const n = L.length, data = Buffer.alloc(n * 8), h = Buffer.alloc(58);for (let i = 0; i < n; i++) { data.writeFloatLE(L[i], i * 8); data.writeFloatLE(R[i], i * 8 + 4); }@@ -57,15 +84,16 @@ const onsetsFromData = (rendered) => {};const renderOne = (M, spec) => {- let piece = M.PIECES[spec.piece]();+ let piece = spec.make ? spec.make() : (M.DEMOS[spec.piece] ?? M.FIXTURES[spec.piece])();let tempo = spec.tempo ?? piece.plan.tempo;let form;- if (spec.fit) { const f = M.fitToDuration(piece, spec.seconds); piece = f.piece; tempo = f.tempo; form = `${f.form}: ${f.piece.plan.sections.map((x) => x.id).join(", ")}`; }+ if (spec.fit) { const f = M.fitScore(piece, spec.seconds); piece = f.piece; tempo = f.tempo; form = `${f.form}: ${f.piece.plan.sections.map((x) => x.id).join(", ")}`; }const opts = { seconds: spec.seconds, tempo };if (spec.flat) Object.assign(opts, { expressive: false, piano: M.PIANO_FLAT, flatVelocity: 0.6 });- const t0 = Date.now(), r = M.renderPiece(piece, SR, opts), ms = Date.now() - t0;+ const loop = spec.loop || piece.plan.loop, go = () => (loop ? M.renderLoop(piece, SR) : M.renderPiece(piece, SR, opts));+ const t0 = Date.now(), r = go(), ms = Date.now() - t0;// determinism: a second render must be bit-identical- const r2 = M.renderPiece(piece, SR, opts); let same = true; for (let i = 0; i < r.L.length; i += 7) if (r.L[i] !== r2.L[i] || r.R[i] !== r2.R[i]) { same = false; break; }+ const r2 = go(); let same = true; for (let i = 0; i < r.L.length; i += 7) if (r.L[i] !== r2.L[i] || r.R[i] !== r2.R[i]) { same = false; break; }return { r, piece, tempo, ms, deterministic: same, form };};@@ -87,14 +115,49 @@ const main = async () => {const [cmd, ...args] = process.argv.slice(2);const M = await load();const flag = (k) => args.includes(k), val = (k, d) => { const i = args.indexOf(k); return i >= 0 ? Number(args[i + 1]) : d; };- if (cmd === "list") { console.log(Object.keys(M.PIECES).join("\n")); return; }+ if (cmd === "list") { console.log("demos (listening references and the novelty corpus, never a film's score):\n " + Object.keys(M.DEMOS).join("\n ") + "\nfixtures (tests):\n " + Object.keys(M.FIXTURES).join("\n ")); return; }+ if (cmd === "vocab") { if (args[0] === "--md") vocabMarkdown(M); else printVocab(M, args[0]); return; }+ if (cmd === "calibrate") { calibrate(M); return; }+ if (cmd === "novelty") {+ const refs = args.filter((a) => !a.startsWith("--") && !/^[\d.]+$/.test(a)), pcs = [];+ for (const ref of refs) pcs.push(await getPiece(M, ref));+ let fail = false;+ for (const pc of pcs) { const fam = Object.values(M.DEMO_FAMILIES).find((f) => f.includes(pc.name)) ?? [pc.name]; fail = !printNovelty(M, pc.name, M.novelty(pc.make(), M.DEMOS, fam, val("--threshold", undefined)), "shipped pieces") || fail; }+ if (pcs.length > 1) { // pairwise: scores meant for different products must not be siblings either+ const corpus = Object.fromEntries(pcs.map((p) => [p.name, p.make]));+ for (const pc of pcs) fail = !printNovelty(M, pc.name, M.novelty(pc.make(), corpus, [pc.name], val("--threshold", undefined)), "each other") || fail;+ }+ if (fail) process.exitCode = 1; return;+ }+ if (cmd === "check") {+ const pc = await getPiece(M, args[0]); let piece = pc.make(), tempo = piece.plan.tempo, seconds = val("--seconds", undefined);+ if (flag("--fit")) { const f = M.fitScore(piece, seconds); piece = f.piece; tempo = f.tempo; }+ const r = piece.plan.loop ? M.renderLoop(piece, SR) : M.renderPiece(piece, SR, { seconds, tempo });+ const ok = [report(M, r, piece), printStems(M, piece, tempo, seconds)?.ok !== false];+ if (!pc.demo) { const fam = [args[0]]; ok.push(printNovelty(M, args[0], M.novelty(piece, M.DEMOS, fam), "shipped pieces")); }+ console.log(ok.every(Boolean) ? "CHECK PASS: now a human listens (an mp3 or wav on a page)" : "CHECK FAIL: fix the items above, then run check again");+ if (!ok.every(Boolean)) process.exitCode = 1; return;+ }if (cmd === "render") {- const [name, out] = args; const { r, tempo, ms, deterministic, piece } = renderOne(M, { piece: name, seconds: val("--seconds", undefined), tempo: val("--tempo", undefined), flat: flag("--flat"), fit: flag("--fit") });- writeWavFloat(out, r.L, r.R); const m = M.measure(decode(out), SR);- console.log(JSON.stringify({ file: out, tempo, renderMs: ms, deterministic, gainDb: r.gainDb, problems: M.planProblems(piece), ...m, shortTerm: undefined }, null, 1)); return;+ const [name, out] = args, pc = await getPiece(M, name); const { r, tempo, ms, deterministic, piece } = renderOne(M, { make: pc.make, seconds: val("--seconds", undefined), tempo: val("--tempo", undefined), flat: flag("--flat"), fit: flag("--fit") });+ const mp3 = out.endsWith(".mp3"), wav = mp3 ? out.replace(/\.mp3$/, ".wav") : out;+ if (mp3 && (piece.plan.loop || flag("--loop"))) console.log("NOTE: mp3 is not gapless (encoder padding clicks at the loop point). Ship loops as .wav (or ogg/m4a with gapless metadata).");+ writeWavFloat(wav, r.L, r.R);+ if (mp3) { execFileSync("ffmpeg", ["-v", "error", "-y", "-i", wav, "-c:a", "libmp3lame", "-b:a", "256k", out]); unlinkSync(wav); }+ const m = M.measure(decode(out), SR);+ console.log(JSON.stringify({ file: out, tempo, renderMs: ms, deterministic, gainDb: r.gainDb, loopS: r.loopS, ...m, shortTerm: undefined }, null, 1));+ let good = report(M, r, piece);+ if (flag("--stems")) good = printStems(M, piece, tempo, val("--seconds", undefined)).ok && good;+ if (!good) process.exitCode = 1;+ return;+ }+ if (cmd === "stems") {+ const [name] = args; let piece = (await getPiece(M, name)).make(), tempo = piece.plan.tempo, seconds = val("--seconds", undefined);+ if (flag("--fit")) { const f = M.fitScore(piece, seconds); piece = f.piece; tempo = f.tempo; }+ printStems(M, piece, tempo, seconds); return;}if (cmd === "meter") { for (const f of args) { const m = M.measure(decode(f), SR), ff = ffmpegEbu(f); console.log(basename(f), `LUFS ${fmt(m.lufs)} (ffmpeg ${fmt(ff.I)}) LRA ${fmt(m.lra)} (ffmpeg ${fmt(ff.LRA)}) TP ${fmt(m.dbtp)} dBTP (ffmpeg ${fmt(ff.TP)}) onsets/s ${fmt(m.onsetsPerS, 2)} centroid ${fmt(m.centroidHz, 0)} Hz (energy-wtd ${fmt(m.centroidEnergyHz, 0)}) dur ${fmt(m.durationS, 2)} lastOnset ${fmt(m.lastOnsetS, 2)}`); } return; }- if (cmd === "score") { console.log(M.scoreText(M.PIECES[args[0]]())); return; }+ if (cmd === "score") { console.log(M.scoreText((await getPiece(M, args[0])).make())); return; }if (cmd === "probe") { console.log(JSON.stringify(probe(M), null, 1)); return; }if (cmd === "samples") {const dir = resolve(args[0]);@@ -148,6 +211,97 @@ const main = async () => {}};+const calibrate = (M) => {+ const trim = {}, fix = {};+ for (const v of Object.values(M.VOCAB)) {+ if (v.calibrated) continue; trim[v.id] = {}; fix[v.id] = {}; M.VOCAB_TARGET_FIX[v.id] = {};+ for (let pass = 0; pass < 3; pass++) {+ M.VOCAB_TRIM[v.id] = trim[v.id];+ const b = M.measureStems(M.composePiece(M.testMaterial(v)), STEM_SR);+ for (const r of b.rows) if (r.offDb !== null && Number.isFinite(r.offDb)) trim[v.id][r.id] = +Math.max(-12, Math.min(12, (trim[v.id][r.id] ?? 0) - r.offDb)).toFixed(1); // capped: past 12 dB the gain is not the problem+ if (pass === 2) { for (const r of b.rows) if (r.offDb !== null && Math.abs(r.offDb) > 1) fix[v.id][r.id] = +r.offDb.toFixed(1);+ console.log(v.id.padEnd(14), b.rows.filter((r) => r.offDb !== null).map((r) => `${r.id} ${r.offDb >= 0 ? "+" : ""}${r.offDb.toFixed(1)}`).join(" ")); }+ }+ }+ const file = join(here, "../src/canvas-core/music/vocabTrim.ts"), head = readFileSync(file, "utf8").split("export const VOCAB_TRIM")[0], j = (x) => JSON.stringify(x, null, 1).replace(/"(\w+)":/g, "$1:");+ writeFileSync(file, `${head}export const VOCAB_TRIM: Record<string, Partial<Record<Slot, number>>> = ${j(trim)};\n/** Where a 12 dB trim could not reach the target (long-decaying plucks read low as active RMS), the target moves to where the voice sits. */\nexport const VOCAB_TARGET_FIX: Record<string, Partial<Record<Slot, number>>> = ${j(fix)};\n`);+ console.log(`wrote ${file}`);+};++const printVocab = (M, id) => {+ if (!id) { for (const v of Object.values(M.VOCAB)) console.log(`${v.id.padEnd(15)} ${v.name}: ${v.atmosphere}\n${"".padEnd(16)}grooves: ${v.grooves.join(", ") || "none (no drums)"} | moods: ${v.moods.join(", ")} | ${v.tempo.join("-")} bpm ${v.meters.join(" ")}`);+ console.log("\ngroove families:"); for (const [k, d] of Object.entries(M.GROOVE_FAMILIES)) console.log(` ${k.padEnd(10)} ${d}`);+ console.log("\nsection kinds:"); for (const [k, d] of Object.entries(M.KINDS)) console.log(` ${k.padEnd(10)} ${d.what}`); return; }+ const v = M.VOCAB[id]; if (!v) throw new Error(`no style "${id}" (have: ${Object.keys(M.VOCAB).join(", ")})`);+ console.log(`${v.name} (${v.id}): ${v.atmosphere}\ntempo ${v.tempo.join("-")} bpm, meters ${v.meters.join(" ")}, swing ${v.swing.join("-")}, moods ${v.moods.join(", ")}`);+ const eff = (slot, x) => +(x.gainDb + (M.VOCAB_TRIM[v.id]?.[slot] ?? 0)).toFixed(1), tgt = (slot) => (v.stemTargets[slot] === undefined ? "-" : +(v.stemTargets[slot] + (M.VOCAB_TARGET_FIX[v.id]?.[slot] ?? 0)).toFixed(1));+ console.log("palette (slot: instrument, gain dB, stem target dB):"); for (const [slot, x] of Object.entries(v.palette)) console.log(` ${slot.padEnd(8)} ${x.inst.padEnd(10)} ${String(eff(slot, x)).padStart(5)} ${tgt(slot)} dB${Object.keys(v.alternates[slot] ?? {}).length ? ` alternates: ${Object.entries(v.alternates[slot]).map(([n, a]) => `${n} (${a.inst}, ${a.gainDb} dB)`).join(", ")}` : ""}`);+ for (const [slot, alts] of Object.entries(v.alternates)) if (!v.palette[slot]) console.log(` ${slot.padEnd(8)} (no default) alternates: ${Object.entries(alts).map(([n, a]) => `${n} (${a.inst}, ${a.gainDb} dB)`).join(", ")}`);+ console.log(`stem targets ${v.calibrated ? "calibrated on a listened score" : "are starting numbers (uncalibrated: flags are advisory until a human listens)"}`);+ console.log(`grooves: ${v.grooves.map((g) => `${g} (${M.GROOVE_FAMILIES[g]})`).join("\n ") || "none"}`);+ for (const [k, x] of Object.entries(v.harmony)) console.log(`harmony.${k}: ${Array.isArray(x) ? x.join(", ") : x}`);+ for (const [k, x] of Object.entries(v.melody)) console.log(`melody.${k}: ${x}`);+ for (const [k, x] of Object.entries(v.arrangement)) console.log(`arrangement.${k}: ${x}`);+ console.log(`avoid: ${v.avoid}`);+};++/** references/music/styles/vocabularies.md, generated from the data so the page never drifts from the code. */+const vocabMarkdown = (M) => {+ const o = ["# Style vocabularies", "", "> 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)).", "",+ "| Style | Atmosphere | Tempo, meters | Moods | Grooves |", "|---|---|---|---|---|"];+ for (const v of Object.values(M.VOCAB)) o.push(`| \`${v.id}\` | ${v.atmosphere} | ${v.tempo.join("-")} bpm; ${v.meters.join(", ")} | ${v.moods.join(", ")} | ${v.grooves.join(", ") || "none (no drums)"} |`);+ o.push("", "## Groove families", "", "Pick a family and its knobs (`density`, `variation`, `fill`, `accent`); the seed varies every bar. Or write the drum bars yourself.", "");+ for (const [k, d] of Object.entries(M.GROOVE_FAMILIES)) o.push(`- \`${k}\`: ${d}`);+ o.push("", "## Section kinds (the arrangement grammar)", "", "A kind decides which layers may sound; your lines sound only where you write them.", "");+ for (const [k, d] of Object.entries(M.KINDS)) o.push(`- \`${k}\` (drums: ${d.drums ?? "none"}, bass: ${d.bass ? "yes" : "no"}): ${d.what}`);+ for (const v of Object.values(M.VOCAB)) {+ o.push("", `## \`${v.id}\`: ${v.name}`, "", `${v.atmosphere}. Tempo ${v.tempo.join("-")} bpm, meters ${v.meters.join(", ")}, swing ${v.swing.join("-")}.`, "", "| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |", "|---|---|---|---|---|");+ for (const [slot, x] of Object.entries(v.palette)) o.push(`| ${slot} | \`${x.inst}\` | ${+(x.gainDb + (M.VOCAB_TRIM[v.id]?.[slot] ?? 0)).toFixed(1)} | ${v.stemTargets[slot] === undefined ? "-" : +(v.stemTargets[slot] + (M.VOCAB_TARGET_FIX[v.id]?.[slot] ?? 0)).toFixed(1)} | ${Object.entries(v.alternates[slot] ?? {}).map(([n, a]) => `${n} (\`${a.inst}\`, ${a.gainDb} dB)`).join(", ") || "-"} |`);+ o.push("", `Stem targets: ${v.calibrated ? "calibrated on a listened score." : "starting numbers from a neutral test signal (advisory until a human listens)."}`, "");+ o.push(`- **Harmony language.** Modes: ${v.harmony.modes.join(", ")}. Qualities: ${v.harmony.qualities}. Tendencies: ${v.harmony.tendencies}. Harmonic rhythm: ${v.harmony.rhythm}. Voicing: ${v.harmony.voicing}. Tension and release: ${v.harmony.tension}.`);+ o.push(`- **Melody.** Range ${v.melody.range}. Contour: ${v.melody.contour}. Density: ${v.melody.density}. Motif: ${v.melody.motif}.`);+ o.push(`- **Arrangement.** ${v.arrangement.shape}. Transitions: ${v.arrangement.transitions}. Endings: ${v.arrangement.endings}.`);+ o.push(`- **Grooves:** ${v.grooves.join(", ") || "none"}. **Avoid:** ${v.avoid}.`);+ }+ console.log(o.join("\n"));+};++/** Key/mode problems, composer warnings, the master (did the peak cap stop it short?), and the guards. Returns pass. */+const report = (M, r, piece) => {+ let ok = true; const probs = M.planProblems(piece), warn = piece.warnings ?? [];+ for (const p of probs) console.log(`PROBLEM ${p}`); ok = ok && !probs.length;+ for (const w of warn) console.log(`WARNING ${w}`);+ const lu = M.loudness([r.L, r.R], SR).integrated, tp = M.truePeak([r.L, r.R]).dbtp, target = r.masterMode === "dense" ? -14 : r.masterMode === "gentle" ? -16 : NaN;+ console.log(`master ${r.masterMode}: ${fmt(lu)} LUFS (target ${fmt(target)}), true peak ${fmt(tp, 2)} dBTP`);+ if (lu < target - 0.5) console.log(`NOTE the master stopped ${fmt(target - lu)} dB short of its target: the true-peak ceiling (-1 dBTP) capped the gain. Peaks are a composing problem: stagger the bass under the loudest downbeat, roll the big chord, don't double the climax note, soften the one loudest hit.`);+ const g = M.guardReport(r, SR, r.L.length / SR);+ console.log(`guards ghost ${g.ghost.pass ? "PASS" : "FAIL"} (${g.ghost.failures}/${g.ghost.windows} windows formless) | reverb ${g.reverb.pass ? "PASS" : "FAIL"} (worst tail ${fmt(g.reverb.worstDb)} dB vs dry) | masking ${g.masking ? `${g.masking.pass ? "PASS" : "FAIL"} (melody clear in ${Math.round(g.masking.shareOfBarsClear * 100)} % of bars, worst ${fmt(g.masking.worstMarginDb)} dB)` : "n/a (no melody)"}`);+ if (g.masking && !g.masking.pass) console.log(`FIX masking: the melody must beat every other part in 500 Hz-4 kHz by 3 dB in 80 % of its bars. Guards win over stem targets: raise the lead (levels.lead, up to +${M.LEAD_HEADROOM_DB} dB over its target is allowed), thin or lower what sits in its register, or move it.`);+ if (!g.ghost.pass) console.log("FIX ghost: sustained sound with too few onsets and no cadence. Add a rhythmic layer or motif, shorten tails, cadence.");+ if (!g.reverb.pass) console.log("FIX reverb: the late tail sits too close to the dry sound. Lower sends (voices' send) or the space mood control.");+ return ok && g.ghost.pass && g.reverb.pass && (!g.masking || g.masking.pass);+};+const printNovelty = (M, name, v, what) => {+ console.log(`novelty: ${name} vs ${v.rows.length} ${what} (fail above ${v.threshold}, or on any reused 6-note melody fragment)`);+ for (const r of v.rows.slice(0, 5)) console.log(` ${r.name.padEnd(22)} ${r.score.toFixed(3)} ${r.reusedFragments ? `REUSED ${r.reusedFragments} fragment(s) ` : ""}${Object.entries(r.by).map(([k, x]) => `${k} ${x}`).join(" ")}`);+ console.log(v.pass ? "novelty PASS" : `novelty FAIL: too close to ${v.worst.name}. Change what the numbers point at (the lead's rhythm, the contour, the groove, the chord colours, the form), not just the key.`);+ console.log(" (idioms are fine: a ii-V-I, a plagal cadence, a two-chord vamp are vocabulary. What fails is the same music: a multi-bar progression WITH its rhythm, groove, contour and form, or a quoted melody.)");+ return v.pass;+};++/** Stem balance: each part's unmastered stem RMS (active samples) vs piece.stemTargets. Measured at 24 kHz, as the targets were. */+const STEM_SR = 24000;+const printStems = (M, piece, tempo, seconds) => {+ const b = M.measureStems(piece, STEM_SR, { tempo, seconds });+ console.log(`stem balance: ${piece.title} (unmastered stem RMS over active samples vs target, +-${b.tolDb} dB; the lead may sit up to +${b.headroom.lead ?? 0} dB more for the masking guard; targets already include your mood controls' shifts)`);+ for (const r of b.rows) console.log(` ${r.id.padEnd(9)} ${fmt(r.rmsDb).padStart(6)} dB ${r.targetDb === null ? "(no target)" : `target ${fmt(r.targetDb).padStart(6)} off ${(r.offDb >= 0 ? "+" : "") + fmt(r.offDb)} ${r.ok ? "ok" : `FLAG: ${r.offDb > 0 ? "too hot" : "too quiet"}`}`}`);+ if (!Object.keys(piece.stemTargets ?? {}).length) console.log(" (this piece declares no stemTargets)");+ const cal = M.VOCAB[piece.plan.style]?.calibrated !== false;+ console.log(b.pass ? "stems PASS" : `stems ${cal ? "FAIL" : "OFF TARGET (advisory: this style's targets are uncalibrated starting numbers)"}: fix the part gains (Material.levels), then master. LUFS alone once hid a sub 7-10 dB too hot.`);+ if (!b.pass && cal) process.exitCode = 1;+ return { ...b, ok: b.pass || !cal };+};+/** Piano realism probes (ADVISORY 4.1): single notes, matched loudness where it matters. */const probe = (M) => {const note = (p, v, opts, dur = 3) => { const keys = [{ t: 0.05, off: dur, p, v }]; const { L, R } = M.renderPiano(keys, [], SR, Math.round((dur + 0.5) * SR), opts, 1); return [L, R]; };diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/sfx.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/sfx.mjsnew file mode 100644index 0000000..719d44e--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/sfx.mjs@@ -0,0 +1,218 @@+#!/usr/bin/env node+// The sound-effects kit, rendered and checked.+//+// node tools/sfx.mjs list # kinds, variants, levels, when to use each+// node tools/sfx.mjs one <kind> [variant] [seed] <out.wav|out.mp3>+// node tools/sfx.mjs kit <outdir> # every kind x variant, 3 varied hits each, + demo + page + meters.json+// node tools/sfx.mjs test # determinism, hygiene, audibility, validation (exit 1 on failure)+import { build } from "esbuild";+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { writeFileSync, mkdirSync, unlinkSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const here = dirname(fileURLToPath(import.meta.url)), SR = 48000;+/** 32-bit float stereo WAV (no clipping on the way to the encoder). */+const writeWavFloat = (path, L, R, 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);+ writeFileSync(path, Buffer.concat([h, data]));+};+const load = async () => {+ const r = await build({ entryPoints: [join(here, "../src/canvas-core/music/index.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"));+};+const md5 = (...chans) => { const h = createHash("md5"); for (const c of chans) h.update(Buffer.from(c.buffer, c.byteOffset, c.byteLength)); return h.digest("hex"); };+const dB = (x) => 20 * Math.log10(Math.max(x, 1e-12));+const peakOf = (L, R) => { let p = 0; for (let i = 0; i < L.length; i++) p = Math.max(p, Math.abs(L[i]), Math.abs(R[i])); return p; };+const toMp3 = (wav, mp3) => { execFileSync("ffmpeg", ["-v", "error", "-y", "-i", wav, "-codec:a", "libmp3lame", "-b:a", "192k", mp3]); unlinkSync(wav); };+const writeAudio = (path, L, R) => { if (path.endsWith(".mp3")) { const w = path + ".wav"; writeWavFloat(w, L, R, SR); toMp3(w, path); } else writeWavFloat(path, L, R, SR); };+/** Share of energy above 20 kHz (aliasing / fizz) in dB relative to the total, via one big FFT. */+const hfShare = (M, L) => {+ let N = 1; while (N < L.length) N <<= 1; N = Math.min(N, 1 << 18);+ const re = new Float64Array(N), im = new Float64Array(N); for (let i = 0; i < Math.min(N, L.length); i++) re[i] = L[i];+ M.fft(re, im); let tot = 0, hi = 0; const k20 = Math.round((20000 / SR) * N);+ for (let k = 1; k < N / 2; k++) { const e = re[k] * re[k] + im[k] * im[k]; tot += e; if (k >= k20) hi += e; }+ return 10 * Math.log10(Math.max(hi, 1e-30) / Math.max(tot, 1e-30));+};+const dcOf = (L) => { let s = 0; for (const x of L) s += x; return s / L.length; };++/** Three varied hits of one variant, back to back, so the ear hears the variation. */+const reel = (M, kind, variant, opts = {}) => {+ const hits = [1, 2, 3].map((seed) => M.renderSfx(kind, { variant, seed, key: "C", bpm: 90, ...opts }, SR));+ const gap = Math.round(0.35 * SR), lead = Math.round(0.15 * SR), pre = Math.max(...hits.map((h) => h.hit)), n = lead + hits.reduce((a, h) => a + h.L.length + gap, 0) + pre;+ const L = new Float32Array(n), R = new Float32Array(n); let at = lead;+ for (const h of hits) { L.set(h.L, at); R.set(h.R, at); at += h.L.length + gap; }+ return { L, R, hits };+};++// The launch-film baseline (launch3.ts audio3), rebuilt verbatim so the kit can be A/B'd against it.+const baseline = (M) => {+ const out = {}, r = (() => { let a = 4242 >>> 0; return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; })();+ const mk = (len, fn, gain, pan = 0) => { const n = Math.round(len * SR), L = new Float32Array(n), R = new Float32Array(n); for (let i = 0; i < n; i++) { const v = fn(i / SR) * gain; L[i] = v * (1 - Math.max(0, pan)); R[i] = v * (1 + Math.min(0, pan)); } return [L, R]; };+ out.click = (() => { const f0 = 2600 + r() * 1400, ph = r() * 6; return mk(0.03, (s) => Math.sin(2 * Math.PI * f0 * s + ph) * Math.exp(-s / 0.004) + (r() - 0.5) * Math.exp(-s / 0.002) * 0.6, 0.05); })();+ out.thock = mk(0.14, (s) => Math.sin(2 * Math.PI * (70 + 90 * Math.exp(-s / 0.02)) * s) * Math.exp(-s / 0.05), 0.2);+ out.plip = mk(0.16, (s) => Math.sin(2 * Math.PI * (320 + 700 * Math.exp(-s / 0.03)) * s) * Math.exp(-s / 0.06), 0.12);+ out.whoosh = (() => { let z = 0; return mk(0.32, (s) => { z += 0.14 * ((r() - 0.5) - z); return z * Math.sin((Math.PI * s) / 0.32) ** 2; }, 0.55); })();+ out.scratch = (() => { let z = 0; return mk(0.6, (s) => { z += 0.5 * ((r() - 0.5) - z); return z * (0.6 + 0.4 * Math.sin(s * 70)) * Math.min(1, s * 20) * Math.min(1, (0.6 - s) * 20); }, 0.07); })();+ return out;+};++// The demo: 15 s of the launch score's first bars with the kit on top, the story of the film's opening.+const FPS = 30, DEMO_FRAMES = 450;+export const demoPlan = (M) => {+ const cues = [];+ // typing "make a koi that swims" at a human cadence+ const text = "make a koi that swims"; let f = 12;+ for (let i = 0; i < text.length; i++) { cues.push({ frame: f, kind: "tick", variant: text[i] === " " ? "space" : "key", label: i === 0 ? "typing" : undefined }); f += 2.4 + ((i * 7) % 5) * 0.55 + (text[i] === " " ? 1.5 : 0); }+ cues.push(+ { frame: 157, kind: "press", variant: "thock", snap: "beat", label: "Generate" },+ { frame: 170, kind: "ink", variant: "bloom", label: "the drawing opens" },+ { frame: 182, kind: "scratch", variant: "nib", lengthS: 1.4, label: "lettering writes" },+ { frame: 232, kind: "whoosh", variant: "soft", label: "scene move" },+ { frame: 250, kind: "swish", variant: "in", label: "code panel slides in" },+ { frame: 268, kind: "bubble", variant: "bubbles", label: "the koi" },+ { frame: 290, kind: "brick", variant: "snap", label: "brick" },+ { frame: 300, kind: "brick", variant: "clack" },+ { frame: 312, kind: "thread", variant: "stitch", label: "embroidery" },+ { frame: 322, kind: "chime", variant: "sparkle", snap: "beat", label: "sparkle" },+ { frame: 400, kind: "riser", variant: "soft", beats: 4, label: "the build" },+ { frame: 400, kind: "impact", variant: "bloom", snap: "bar", label: "the reveal" },+ );+ return { fps: FPS, frames: DEMO_FRAMES, score: { piece: M.launchLofi3() }, beatZeroS: 0, seed: 7, cues }; // key, bpm, bar length come from the score+};+const demoMusic = (M) => { const r = M.renderPiece(M.launchLofi3(), SR); return [r.L.slice(0, Math.round((DEMO_FRAMES / FPS) * SR)), r.R.slice(0, Math.round((DEMO_FRAMES / FPS) * SR))]; };++const page = (rows, demo) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>anidoodle sfx kit</title>+<style>:root{--bg:#F0EEE6;--ink:#1d1b16;--mute:#6b665b;--line:#d8d3c4;--acc:#ca4901}@media (prefers-color-scheme:dark){:root{--bg:#1b1a17;--ink:#eeeae0;--mute:#a39e92;--line:#34322c}}+body{background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,sans-serif;margin:0;padding:24px 16px;max-width:980px;margin:auto}h1{font-size:26px;margin:0 0 4px}h2{font-size:17px;margin:28px 0 8px;color:var(--acc)}p{color:var(--mute);margin:4px 0 12px}+.g{display:grid;grid-template-columns:repeat(auto-fill,minmax(290px,1fr));gap:10px}.c{border:1px solid var(--line);border-radius:10px;padding:10px 12px}.c b{font-size:14px}.m{font:12px ui-monospace,monospace;color:var(--mute)}audio{width:100%;height:34px;margin-top:6px}</style></head><body>+<h1>anidoodle sound-effects kit</h1><p>Every sound is code: layered (transient + body + tail), stereo, and varied per seed. Each player holds 3 hits of the same variant with different seeds, so you hear the variation.</p>+<h2>In context: the launch score's first bars with the kit on top</h2><div class="g">${demo.map(([f, t, d]) => `<div class="c"><b>${t}</b><div class="m">${d}</div><audio controls preload="none" src="${f}"></audio></div>`).join("")}</div>+${rows.map(([kind, use, vs]) => `<h2>${kind}</h2><p>${use}</p><div class="g">${vs.map((v) => `<div class="c"><b>${kind} · ${v.variant}</b><div class="m">${v.meta}</div><audio controls preload="none" src="${v.file}"></audio></div>`).join("")}</div>`).join("\n")}+</body></html>`;++const kit = async (outdir) => {+ const M = await load(), dir = resolve(outdir); mkdirSync(join(dir, "spectra"), { recursive: true });+ const rows = [], meters = { kinds: {}, baseline: {}, demo: null };+ for (const kind of M.SFX_KINDS) {+ const info = M.sfxInfo(kind), vs = [];+ for (const variant of info.variants) {+ const { L, R, hits } = reel(M, kind, variant), file = `${kind}-${variant}.mp3`;+ writeAudio(join(dir, file), L, R);+ const c = M.centroid([L, R], SR), m = { peakDb: dB(peakOf(L, R)), windowLufs: hits.map((h) => +h.lufs.toFixed(1)), centroidHz: Math.round(c.energyWeighted), lengthsS: hits.map((h) => +(h.L.length / SR).toFixed(2)), hfShareDb: +hfShare(M, L).toFixed(1), dc: +dcOf(L).toExponential(1) };+ meters.kinds[`${kind}:${variant}`] = m;+ vs.push({ variant, file, meta: `peak ${m.peakDb.toFixed(1)} dBFS · ${m.windowLufs.join(" / ")} LUFS(win) · centroid ${m.centroidHz} Hz` });+ }+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", join(dir, `${kind}-${info.variants[0]}.mp3`), "-lavfi", "showspectrumpic=s=480x160:legend=0:scale=log", join(dir, "spectra", `${kind}.png`)]);+ rows.push([kind, info.use, vs]);+ }+ for (const [k, [L, R]] of Object.entries(baseline(M))) { writeAudio(join(dir, `baseline-${k}.mp3`), L, R); meters.baseline[k] = { peakDb: +dB(peakOf(L, R)).toFixed(1), centroidHz: Math.round(M.centroid([L, R], SR).energyWeighted), lengthS: +(L.length / SR).toFixed(2) }; }+ const plan = demoPlan(M), music = demoMusic(M), mix = M.mixSfx(music, plan, SR);+ writeAudio(join(dir, "demo.mp3"), mix.L, mix.R);+ writeAudio(join(dir, "demo-sfx-only.mp3"), mix.sfx[0], mix.sfx[1]);+ writeAudio(join(dir, "demo-music-only.mp3"), music[0], music[1]);+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", join(dir, "demo.mp3"), "-lavfi", "showspectrumpic=s=900x220:legend=0:scale=log", join(dir, "spectra", "demo.png")]);+ meters.demo = { ok: mix.ok, lufs: +mix.lufs.toFixed(1), dbtp: +mix.dbtp.toFixed(2), limiterDb: +mix.limiterDb.toFixed(2), cues: mix.audibility.map((a) => ({ kind: `${a.kind}:${a.variant}`, label: a.label, atS: +a.atS.toFixed(2), marginDb: +a.marginDb.toFixed(1), peakMarginDb: +a.peakMarginDb.toFixed(1) })) };+ writeFileSync(join(dir, "meters.json"), JSON.stringify(meters, null, 1));+ const demo = [["demo.mp3", "demo: score + kit", `15 s, ${plan.cues.length} cues, ${mix.lufs.toFixed(1)} LUFS, ${mix.dbtp.toFixed(1)} dBTP, every cue audible: ${mix.ok}`], ["demo-sfx-only.mp3", "demo: kit only", "the same cues without the score"], ["demo-music-only.mp3", "demo: score only", "launchLofi3, first 15 s, undipped"],+ ...Object.keys(meters.baseline).map((k) => [`baseline-${k}.mp3`, `baseline: launch3 ${k}`, "the launch film's current effect, for A/B"])];+ writeFileSync(join(dir, "index.html"), page(rows, demo));+ console.log(`wrote ${dir}: ${rows.reduce((a, r) => a + r[2].length, 0)} variant reels, 3 demo files, ${Object.keys(meters.baseline).length} baselines, index.html, meters.json, spectra/`);+ console.log(`demo: ${mix.lufs.toFixed(1)} LUFS, ${mix.dbtp.toFixed(2)} dBTP, limiter ${mix.limiterDb.toFixed(2)} dB, all audible: ${mix.ok}`);+ for (const a of mix.audibility) console.log(` ${a.atS.toFixed(2).padStart(6)} s ${(a.kind + ":" + a.variant).padEnd(16)} ${a.label.padEnd(22)} margin ${a.marginDb.toFixed(1).padStart(5)} dB (peak ${a.peakMarginDb.toFixed(1)} dB)`);+};++const test = async () => {+ const M = await load(); let pass = 0, fail = 0;+ const ok = (c, msg) => { if (c) pass++; else { fail++; console.log("FAIL " + msg); } };+ const throws = (fn, re, msg) => { try { fn(); ok(false, `${msg}: did not throw`); } catch (e) { ok(re.test(e.message), `${msg}: wrong message "${e.message}"`); } };+ const all = M.SFX_KINDS.flatMap((k) => M.sfxVariants(k).map((v) => [k, v]));+ ok(M.SFX_KINDS.length >= 14, `>= 14 kinds (got ${M.SFX_KINDS.length})`);+ for (const [k, v] of all) {+ const a = M.renderSfx(k, { variant: v, seed: 11, key: "C", bpm: 90 }, SR), b = M.renderSfx(k, { variant: v, seed: 11, key: "C", bpm: 90 }, SR), c = M.renderSfx(k, { variant: v, seed: 12, key: "C", bpm: 90 }, SR), tag = `${k}:${v}`;+ ok(md5(a.L, a.R) === md5(b.L, b.R), `${tag} deterministic`);+ ok(md5(a.L, a.R) !== md5(c.L, c.R), `${tag} varies with seed`);+ let finite = true; for (let i = 0; i < a.L.length; i++) if (!Number.isFinite(a.L[i]) || !Number.isFinite(a.R[i])) { finite = false; break; }+ ok(finite, `${tag} no NaN/Inf`);+ const pk = peakOf(a.L, a.R);+ ok(pk > 0.01, `${tag} non-silent (peak ${dB(pk).toFixed(1)} dBFS)`);+ ok(dB(pk) <= -0.99, `${tag} peak <= -1 dBFS (got ${dB(pk).toFixed(2)})`);+ ok(Math.abs(dcOf(a.L)) < 1e-3 * Math.max(pk, 1e-9) * 10 && Math.abs(dcOf(a.R)) < 1e-2 * pk, `${tag} no DC offset (${dcOf(a.L).toExponential(1)})`);+ ok(a.lufs > -40, `${tag} speaks (window ${a.lufs.toFixed(1)} LUFS)`);+ ok(Math.abs(a.lufs - c.lufs) < 3.5, `${tag} level stable across seeds (${a.lufs.toFixed(1)} vs ${c.lufs.toFixed(1)})`);+ ok(Math.abs(a.L[a.L.length - 1]) < 1e-3 && Math.abs(a.R[a.R.length - 1]) < 1e-3, `${tag} ends at zero (no end click)`);+ ok(hfShare(M, a.L) < -30, `${tag} no fizz above 20 kHz (${hfShare(M, a.L).toFixed(1)} dB)`);+ }+ // motion: a whoosh approaches bright from the left and leaves darker to the right (doppler + pan)+ const w = M.renderSfx("whoosh", { variant: "air", seed: 5, dir: 1 }, SR), half = (a, b) => [w.L.slice(a, b), w.R.slice(a, b)];+ const pre = half(Math.max(0, w.hit - SR * 0.25), w.hit), post = half(w.hit, w.hit + SR * 0.25), e = (x) => x.reduce((a, v) => a + v * v, 0);+ const cPre = M.centroid(pre, SR).energyWeighted, cPost = M.centroid(post, SR).energyWeighted;+ ok(cPre > cPost * 1.1, `whoosh doppler: approach brighter than exit (${cPre.toFixed(0)} vs ${cPost.toFixed(0)} Hz)`);+ ok(e(pre[0]) > e(pre[1]) && e(post[1]) > e(post[0]), "whoosh travels left -> right (dir 1)");+ // tuning: a bell in A rings on A5 = 880 Hz+ const bell = M.renderSfx("chime", { variant: "bell", key: "A", seed: 2 }, SR), N = 1 << 16, re = new Float64Array(N), im = new Float64Array(N);+ for (let i = 0; i < N; i++) re[i] = bell.L[i] + bell.R[i];+ M.fft(re, im); let best = 0, bk = 0; for (let k = 10; k < N / 2; k++) { const m = re[k] * re[k] + im[k] * im[k]; if (m > best) { best = m; bk = k; } }+ ok(Math.abs((bk * SR) / N - 880) < 3, `chime in A rings on 880 Hz (got ${((bk * SR) / N).toFixed(1)})`);+ // no silent defaults: tuned / tempo-synced kinds need a key / bpm, from the plan or the film's score+ throws(() => M.renderSfx("chime"), /tuned and needs a key.*no default key/, "chime without a key");+ throws(() => M.renderSfx("press", { variant: "confirm" }), /needs a key/, "press:confirm without a key");+ throws(() => M.renderSfx("impact", { variant: "bloom" }), /needs a key/, "impact:bloom without a key");+ throws(() => M.renderSfx("riser", { key: "C" }), /needs a bpm.*no default tempo/, "riser without a bpm");+ ok(M.renderSfx("press", {}).L.length > 0 && M.renderSfx("riser", { variant: "air", lengthS: 2 }).L.length > 0, "untuned kinds render without key/bpm");+ throws(() => M.mixSfx(null, { fps: 30, frames: 300, cues: [{ frame: 10, kind: "chime" }] }, SR), /cue #0 \(chime.*is tuned: set plan.key/, "plan cue: chime without a key names the cue");+ const noct = M.nocturne(), fromScore = M.placeSfx({ fps: 30, frames: 300, score: { piece: noct }, cues: [{ frame: 10, kind: "chime", variant: "bell" }, { frame: 200, kind: "riser", beats: 2 }] }, SR);+ const rp = M.resolveSfxPlan({ fps: 30, frames: 300, score: { piece: noct }, cues: [] });+ ok(rp.key === "Ab" && rp.bpm === noct.plan.tempo && rp.beatsPerBar === 3, `plan.score gives key/bpm/bar (got ${rp.key} ${rp.bpm} ${rp.beatsPerBar})`);+ ok(Math.abs(fromScore[1].sound.hit / SR - 2 * 60 / noct.plan.tempo) < 0.002, "a riser in a scored plan takes the score's tempo");+ { const b2 = fromScore[0].sound, N2 = 1 << 16, re2 = new Float64Array(N2), im2 = new Float64Array(N2); for (let i = 0; i < N2; i++) re2[i] = b2.L[i] + b2.R[i]; M.fft(re2, im2); let bb = 0, kk = 0; for (let k = 10; k < N2 / 2; k++) { const m = re2[k] * re2[k] + im2[k] * im2[k]; if (m > bb) { bb = m; kk = k; } }+ ok(Math.abs((kk * SR) / N2 - 830.6) < 3, `a bell under the Ab nocturne rings on Ab5 (got ${((kk * SR) / N2).toFixed(1)})`); }+ ok(M.resolveSfxPlan({ fps: 30, frames: 300, key: "D", score: { piece: noct }, cues: [] }).key === "D", "an explicit plan.key beats the score's");+ // tempo sync: a 4-beat riser at 120 bpm lasts 2 s and its hit is its end+ const rz = M.renderSfx("riser", { beats: 4, bpm: 120, key: "G", seed: 3 }, SR); ok(Math.abs(rz.hit / SR - 2) < 0.002, `riser 4 beats @120 = 2 s (got ${(rz.hit / SR).toFixed(3)})`);+ // the demo: deterministic, clean, every cue audible+ const plan = demoPlan(M), music = demoMusic(M), m1 = M.mixSfx(music, plan, SR), m2 = M.mixSfx(music, plan, SR);+ ok(md5(m1.L, m1.R) === md5(m2.L, m2.R), "demo mix deterministic");+ ok(m1.L.length === Math.round((DEMO_FRAMES / FPS) * SR), "demo mix is exactly the film length");+ ok(m1.dbtp <= -0.9, `demo true peak <= -1 dBTP (got ${m1.dbtp.toFixed(2)})`);+ ok(m1.ok && m1.audibility.every((a) => a.marginDb >= -6), `demo: every cue within 6 dB of the score (worst ${Math.min(...m1.audibility.map((a) => a.marginDb)).toFixed(1)} dB)`);+ const g = m1.placed.find((p) => p.cue.label === "Generate"); ok(g && Math.abs(g.hitS - 160 / 30) < 1e-9, `snap to beat: frame 157 -> 160 (got ${g && (g.hitS * 30).toFixed(2)})`);+ const imp = m1.placed.find((p) => p.cue.kind === "impact"); ok(imp && Math.min(...Array.from(m1.duck.subarray(imp.window[0], imp.window[1]))) < 0.55, "score ducks >= 5 dB under the impact");+ // a buried cue must FAIL+ const quiet = { ...plan, cues: [{ frame: 200, kind: "tick", gainDb: -30, label: "buried" }] }, mq = M.mixSfx(music, quiet, SR);+ ok(!mq.ok && mq.audibility[0].marginDb < -6, `buried cue detected (margin ${mq.audibility[0].marginDb.toFixed(1)} dB)`);+ throws(() => M.assertSfxAudible(mq), /buried under the score/, "assertSfxAudible throws on a buried cue");+ throws(() => M.filmSfx(() => music, quiet)(SR), /buried/, "filmSfx refuses a buried cue");+ // validation+ const base = { fps: 30, frames: 300, cues: [] };+ throws(() => M.renderSfx("kazoo"), /unknown kind "kazoo".*kinds: tick/, "unknown kind");+ throws(() => M.renderSfx("tick", { variant: "loud" }), /no variant "loud"/, "unknown variant");+ throws(() => M.mixSfx(null, { ...base, cues: [{ frame: 1, kind: "kazoo" }] }, SR), /unknown kind/, "unknown kind in a plan");+ throws(() => M.mixSfx(null, { ...base, cues: [{ frame: 2, kind: "whoosh" }] }, SR), /pre-roll starts before frame 0; move it to frame >= \d+/, "whoosh pre-roll before 0");+ throws(() => M.mixSfx(null, { ...base, bpm: 90, key: "C", cues: [{ frame: 30, kind: "riser", beats: 8 }] }, SR), /pre-roll/, "riser pre-roll before 0");+ for (const s of [-1, 1.5, 2 ** 33, NaN, "7"]) throws(() => M.renderSfx("pop", { seed: s }), /seed must be an integer/, `bad seed ${String(s)}`);+ throws(() => M.mixSfx(null, { ...base, seed: -3, cues: [] }, SR), /seed must be an integer/, "bad plan seed");+ throws(() => M.mixSfx(null, { ...base, cues: [{ frame: 300, kind: "pop" }] }, SR), /frame must be 0\.\.299/, "cue after the film");+ throws(() => M.mixSfx(null, { ...base, cues: [{ frame: -1, kind: "pop" }] }, SR), /frame must be/, "cue before 0");+ throws(() => M.mixSfx(null, { ...base, cues: [{ frame: 10, kind: "pop", snap: "beat" }] }, SR), /need a bpm/, "snap without bpm");+ throws(() => M.renderSfx("chime", { key: "H" }), /bad key/, "bad key");+ throws(() => M.renderSfx("pop", { pitch: 99 }), /pitch must be/, "pitch out of range");+ // placement is stable: inserting an unrelated cue earlier does not change another cue's sound+ const p1 = M.placeSfx({ ...base, cues: [{ frame: 100, kind: "pop" }] }, SR), p2 = M.placeSfx({ ...base, cues: [{ frame: 50, kind: "brick" }, { frame: 100, kind: "pop" }] }, SR);+ ok(md5(p1[0].sound.L) === md5(p2[1].sound.L), "a cue's sound does not depend on the cues before it");+ const p3 = M.placeSfx({ ...base, cues: [{ frame: 100, kind: "tick" }, { frame: 110, kind: "tick" }] }, SR);+ ok(md5(p3[0].sound.L) !== md5(p3[1].sound.L), "two ticks never render identically");+ console.log(`sfx: ${pass} passed, ${fail} failed`);+ process.exit(fail ? 1 : 0);+};++const [cmd, ...args] = process.argv.slice(2);+if (cmd === "list") { const M = await load(); for (const k of M.SFX_KINDS) { const i = M.sfxInfo(k); console.log(`${k.padEnd(8)} [${i.variants.join(", ")}] level ${i.levelLufs} LUFS(win), duck ${i.duckDb} dB\n ${i.use}`); } }+else if (cmd === "one") { const M = await load(), out = args.pop(), [kind, variant, seed] = args; const s = M.renderSfx(kind, { variant, seed: seed ? Number(seed) : undefined, key: process.env.KEY, bpm: process.env.BPM ? Number(process.env.BPM) : undefined }, SR); writeAudio(out, s.L, s.R); console.log(`${kind}:${s.variant} seed ${s.seed}: ${(s.L.length / SR).toFixed(2)} s, hit @ ${(s.hit / SR).toFixed(3)} s, ${s.lufs.toFixed(1)} LUFS(win)`); }+else if (cmd === "kit" && args[0]) await kit(args[0]);+else if (cmd === "test") await test();+else { console.log("usage: node tools/sfx.mjs list | one <kind> [variant] [seed] <out> | kit <outdir> | test"); process.exit(cmd ? 1 : 0); }diff --git a/plugins/anidoodle/skills/anidoodle/references/craft-bar.md b/plugins/anidoodle/skills/anidoodle/references/craft-bar.mdindex 583ffa7..865127c 100644--- a/plugins/anidoodle/skills/anidoodle/references/craft-bar.md+++ b/plugins/anidoodle/skills/anidoodle/references/craft-bar.md@@ -19,12 +19,23 @@ The test: would a proud human illustrator ship this, or is it mechanical shape-a| The same character drawn differently shot to shot | One character module; shots pose it, never redraw it (`workflows/character-consistency.md`) || A silhouette filled with texture, no mouth line, no toes | Interior contours: mouth, eyelids, nostrils, toes, joins between forms (the detail pass below) || A drawing film where the finished picture fades in | Marks made in the medium's order; the last frames are the still (`workflows/drawing-process.md`) |+| Words laid over the art or the UI | Type gets its own frame; corner marks step aside when the camera brings UI under them |+| A loop playing in place and called "alive" | Real travel through a world that changes as the subject moves |+| A hard cut or a sharp swoosh between scenes | A gentle move: a bloom, a flip, a push, the card grows into the frame |**No dead air** in anything that moves: something visibly changes in every second, from frame 0.Check it with the tool AND by eye: a creeping camera changes every pixel and satisfies the toolwhile the eye sees a still.+**Judge the design, not only the collisions.** A review still can have nothing overlapping and+still fail: no hierarchy, cramped spacing, a frame that would not pass as a poster. Look at each+review frame as a designer first, a checker second.++**Preview options before full renders.** When a choice is open (a transition, a lettering+medium, a palette), show a cheap still sheet of the options side by side and let the person+pick. A full render per option spends the most expensive resource on the cheapest question.+## The detail pass (run it on every piece before showing it)A silhouette filled with texture is not a drawing. Before any still, recreation or character isdiff --git a/plugins/anidoodle/skills/anidoodle/references/music/README.md b/plugins/anidoodle/skills/anidoodle/references/music/README.mdindex 7811b5f..7ff0b0a 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/README.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/README.md@@ -5,8 +5,25 @@ and synthesizes them in code. No samples, no recordings, no licensed audio, everwhat you make, so every choice is a number, every number is measured, and a human hears 8 secondsbefore anything ships.-Code: `engine/src/canvas-core/music/`. Tool: `engine/tools/music.mjs`. The old music-box recipe-lives on, verbatim, as the default style preset: [`styles/music-box.md`](styles/music-box.md).+Code: `engine/src/canvas-core/music/`. Tool: `engine/tools/music.mjs`.++**Start here: [`compose.md`](compose.md).** It takes you from a brief to an original score. A style+is a vocabulary: sound, grooves, harmony language, melody rules, arrangement grammar. It is never+notes. You compose every note, and nothing is filled in for you. There is no default style.++Pages:+- [`compose.md`](compose.md): the workflow, the material format, craft, and the never-reuse rule.+- [`styles/vocabularies.md`](styles/vocabularies.md): all 21 style vocabularies, the 15 groove+ families and the section kinds. It is generated from the code.+- [`styles/lofi-electronic.md`](styles/lofi-electronic.md): the lo-fi electronic vocabulary in+ depth, and the stem balance meter.+- [`styles/music-box.md`](styles/music-box.md): the original music-box recipe's sound numbers and+ the scar story behind the guards.++**Demos are not scores.** The pieces in `pieces/` (samplers, families, nocturne, our launch scores)+were written to prove the synth and the meters, and one of them is our own film's score. They are+listening references and the novelty corpus (`node tools/music.mjs list`). A film never plays them:+`node tools/music.mjs novelty` fails a score that sounds like them or quotes them.## The pipeline@@ -19,16 +36,16 @@ MusicPlan + notes (you write) -> perform -> instruments (one stem per part)harmony list.- The plan names:- one **style**;- - a tempo and a meter (3/4, 4/4, 6/8, 12/8);+ - a tempo and a meter (2/4, 3/4, 4/4, 5/4, 6/8, 7/8, 9/8, 12/8);- **sections**, each with a mood (or a blend `[a, b, w]`), a key and mode, the melody types,a dynamic level `[start, end]` 0..1, and an ending;- `repeatable` / `optional` / `pickup` / `variations` flags, which let it fit any length.- Notes are written in a bar-checked notation. A bar that doesn't add up to the meter throws:```ts- line(3, "C5:2 Bb4:.5 Ab4:.5 | Bb4:2 Eb4:1 | [Ab1 Eb2 Ab2]:[email protected]", { role: "melody", bpb: 3 })+ line(<start beat>, "<NOTE>:<beats> <NOTE>:<beats> | [<NOTE> <NOTE>]:<beats>@<vel> | r:<beats>", { role, bpb })```- Roles: `melody`, `inner`, `bass`, `accomp`, `color`, `drum`.- - Generators may draft. **You compose**:+ - Nothing generates notes. **You compose** (compose.md):- real harmony and voice-leading;- a memorable motif and phrases that ask and answer;- cadences.@@ -55,6 +72,16 @@ MusicPlan + notes (you write) -> perform -> instruments (one stem per part)| `fmBell`, `ePiano` | 2-operator FM || `pulse`, `triangle`, `noiseDrum` | NES-style chip voices || `kick`, `snare`, `hat`, `bass`, `vinyl` | Drums, bass and texture |+ | `warmPad`, `softPluck`, `sub` | The lo-fi electronic kit (`lofiKit.ts`): detuned-saw pad, filtered pluck with ping-pong delay, sine sub |+ | `organ` | Drawbar ranks (harmonics 1 2 3 4 6 8), chorus, tremulant |+ | `brass` | PolyBLEP saw, a low-pass that opens with loudness, a pitch scoop, delayed vibrato |+ | `woodwind` | Flute (sine + breath noise) or `reed: true` clarinet (odd harmonics) |+ | `choir` | Detuned saws through vowel formants (`vowel`: a o u e i). Texture, never a lead |+ | `timpani` | Tuned membrane modes, a pitch settle, a mallet thump (`pitch` tunes it in a drum lane) |+ | `leadSynth` | Mono saw + square, portamento, a filter envelope, blooming vibrato |+ | `bowedSolo` | One bowed voice (violin, or `cello: true`): vibrato, bow noise, body resonances |++ The acoustic voices are procedural approximations. A human listens before one carries a film.4. **Room.** The style chooses it:- music box: one reflection, no tail;- nocturne and lullaby: a small room;@@ -63,13 +90,20 @@ MusicPlan + notes (you write) -> perform -> instruments (one stem per part)5. **Master.**- **Gentle styles:** one static gain to **-16 LUFS**, true peak <= -1 dBTP, never a compressor.If the peak blocks the gain, the loudness goes down. The cure is musical (see "Peaks" below).- - **Dense styles** (chiptune, lo-fi, drive): **-14 LUFS** through a look-ahead true-peak limiter.+ - **Dense styles** (lofiElectronic, lofi, drive, house, synthwave, hipHop, rock, chiptune): **-14 LUFS** through a look-ahead true-peak limiter, then a static trim if an inter-sample peak still passes -1 dBTP.A film's `audio` is `filmAudio(piece, seconds)`, which returns `(sampleRate) => [L, R]` at exactly-the film's length. `engine/src/canvas-core/score.ts` is the scaffold example.+the film's length. It fits the score first (`fitScore`, below), so the music ends on its phrase at+the last frame and is never chopped. Any film mix that renders a score (sound effects included) must+fit it the same way. `engine/src/canvas-core/score.ts` is an empty skeleton: `filmScore(material,+fps, frames)` composes your material and fits it.## Any length, never hard-coded+`fitScore(piece, seconds)` first calls the piece's own `refit(seconds)` if it has one. A composed+piece repeats or drops its `stretch` section, so it still lands on its outro. Then it runs+`fitToDuration`.+`fitToDuration(piece, seconds)` tries every form:- with some `optional` sections dropped (dropping music costs more than nudging the tempo);- with the `repeatable` group restated 0..n times, as "A B A B" or "A A B" (restatements take the@@ -80,34 +114,42 @@ It picks the form whose tempo is closest to the written one. If no full form fitthe piece's `shortForm`. A section's `pickup` travels with it: wherever a section lands, its ownupbeat leads into it.-Example: the nocturne "Window Light" gives-- the short form (the 8-second phrase, restated) at 15 s;-- the full piece at 45 s;-- intro, theme, theme (in octaves), build, coda at 60 s;-- six theme/climax cycles with rotating variations at 180 s.+A hand-written piece with a short form, repeatable sections and optional sections can fit anything+from a quarter of its length to many times it, and it still ends on its cadence.-## Styles (11) and moods (15)+## Styles (21) and moods (21)-Both are rows of numbers in `tables.ts`. A brief names rows, never adjectives. Each row stays-`unconfirmed` until a human has listened to 8 seconds of it; the listener's words then go into-`confirmedBy`.+Both are rows of numbers in `tables.ts`. The vocabularies are in `vocab.ts` and `vocabMore.ts`, and+[`styles/vocabularies.md`](styles/vocabularies.md) is generated from them. A brief names rows,+never adjectives. Each row stays `unconfirmed` until a human has listened to 8 seconds of it; the+listener's words then go into `confirmedBy`.-| Style | Tempo, meter | Natural moods | Master |-|---|---|---|---|-| musicBox (default) | 110-130, 12/8 | joy, curious, tender, playful, wistful | gentle |-| nocturne (piano) | 50-72, 3/4 or 6/8 | tender, melancholy, wistful, romantic | gentle |-| cinematic | 60-120 | awe, triumph, melancholy, tension, hopeful | gentle |-| lullaby | 60-75, 3/4 or 6/8 | tender, calm | gentle |-| folk | 80-120, 6/8, 3/4, 4/4 | calm, wistful, joy, nostalgic | gentle |-| minimalist | 100-140 | curious, tension, awe | gentle |-| jazz | 90-180, swing | playful, nostalgic, romantic, curious | gentle |-| ambient | 50-80 | awe, calm, dread (highest ghost risk) | gentle |-| chiptune | 120-160 | joy, playful, drive, tension | dense |-| lofi | 70-90, swing 55-62 % | nostalgic, calm, wistful | dense |-| drive | 110-140 | drive, triumph, tension, awe | dense |+| Style | Atmosphere | Master |+|---|---|---|+| lofiElectronic | chill, upbeat, clean electronic | dense |+| lofi | dusty lo-fi hip-hop (e-piano, vinyl) | dense |+| drive | driving electronic, four-on-the-floor | dense |+| house | euphoric house / EDM | dense |+| synthwave | neon-retro, gated snare, soaring lead | dense |+| hipHop | head-nod or dark trap, heavy 808 | dense |+| rock | band energy, driven guitars, tight kit | dense |+| chiptune | 8-bit, two pulses, triangle, noise | dense |+| cinematic | string swells, ostinatos, harp and bell colour | gentle |+| orchestral | heroic/epic: brass theme, string engine, choir, timpani | gentle |+| suspense | drones, heartbeat pulse, bowed harmonics, stingers | gentle |+| ambient | airy, spacious, bells and pads | gentle |+| choral | voices in parts, organ, bells | gentle |+| folk | tender acoustic: guitar, piano, harp, brushes | gentle |+| world | drone, modal melody, hand percussion, odd meters | gentle |+| playful | bouncy mallets, skipping kit | gentle |+| jazz | swing ride, walking bass, comping | gentle |+| nocturne | solo piano, rubato | gentle |+| minimalist | interlocking ostinatos | gentle |+| lullaby | soft, rocking, nothing percussive | gentle |+| musicBox | clockwork plucks, no sustain | gentle |Moods: joy, playful, tender, wistful, melancholy, hopeful, curious, tension, dread, awe, triumph,-drive, calm, nostalgic, romantic.+drive, calm, nostalgic, romantic, anger, eerie, mischief, heroic, sensual, grief.- Each row has columns for:- modes and tempo;- harmonic rhythm and lead register;@@ -132,24 +174,18 @@ per-mode guards are in `theory.ts`.Melody types (9): arpeggio, stepwise, hook, ostinato, drone, call and response, counter-melody,sequence, theme transformation.-## How to plan a score--1. **Spot the film.** Find its 3-5 true sync points, and an arc per section (for example tender, then- swelling, then a sudden hush at about 2/3, then a soft close).-2. **Pick one style.** Give each section a mood, a key and a mode.-3. **Write the motif first.** A 2-5 note cell with its own rhythm. Then build the harmony under it,- with voice-leading by step. Then the phrases:- - the question ends off the tonic;- - the answer ends on it, straight away;- - the high point falls in the second half of the phrase.-4. **Arrange.** Add density, not length (more notes, never longer notes). Let the motif return:- transformed, at the climax, and at the close.-5. **Print the score and meter it:**- ```- node tools/music.mjs score <piece>- node tools/music.mjs render <piece> out.wav --seconds 45 --fit- ```-6. **8 seconds to a human.** Include the most important mood change.+## How to write a score++Follow [`compose.md`](compose.md). In short:+1. brief -> numbers (length, picture beats, feeling);+2. one style + one mood + five mood controls;+3. compose YOUR harmony, bass lines, motif(s), groove choice and form as `Material`;+4. `node tools/music.mjs check <file>.ts#<export>` must PASS (key, master, ghost/reverb/masking guards, stems, novelty);+5. `node tools/music.mjs render <file>.ts#<export> out.wav` (use wav for loops: mp3 is not gapless);+6. 8 seconds (then the whole piece) to a human, as an mp3 on a page.++Hand-written `Piece`s (the nocturne, the samplers) are still valid for styles without a vocabulary+builder. Write them with `line()` and render them with `renderPiece`.**Peaks are a composing problem.** Octaves in both hands landing on one downbeat make a true peakthat caps a gentle master. Fix it in the notes:diff --git a/plugins/anidoodle/skills/anidoodle/references/music/compose.md b/plugins/anidoodle/skills/anidoodle/references/music/compose.mdnew file mode 100644index 0000000..611007c--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/music/compose.md@@ -0,0 +1,235 @@+# Compose: from a brief to an original score++A style is a **vocabulary**. It gives you:+- sound: voices, levels and fx;+- groove families;+- a harmony language;+- melody rules;+- an arrangement grammar.++It never gives you notes. **You write every note**:+- the chords and their voicings;+- the bass lines;+- the motifs and lines;+- the form.++The engine refuses to fill gaps. Missing harmony, melody, grooves or form is an error that tells you+what to compose. The engine then performs, synthesizes, mixes and masters, deterministically, in code.++> **Never reuse shipped material.** The demos (`node tools/music.mjs list`) and our own film scores+> are listening references and the novelty corpus. They are never a film's score or a template. Don't+> copy them, transpose them or re-rhythm them. `node tools/music.mjs novelty` fails a score that+> sounds like any shipped piece, or that quotes a 6-note fragment of one (transposed or not).+>+> **Idioms are fine.** A ii-V-I, a plagal amen, a two-chord vamp, a I-bVII-IV are vocabulary. The+> style pages name them so you can use them. What is not fine is reusing the same music: a+> multi-bar progression together with its rhythm, groove, contour and form, or a quoted melody.+>+> Why this rule exists: a "new" example once changed the key, chords and pitches of the launch+> score but kept its rhythms, contour, drums and form. It was heard at once as the same song. The+> novelty fingerprint weighs exactly those things.++## The workflow++1. **Read the brief as numbers.** Write down:+ - the use case (launch film, explainer, loop for a site, game, ad);+ - the length in seconds, and whether it must loop;+ - 3-5 picture beats with their times (the reveal, the claim, the cut to the end card);+ - the words the person used for the feeling.+2. **Pick one style and one mood.** Styles:+ ```+ node tools/music.mjs vocab+ node tools/music.mjs vocab <style>+ ```+ For the details, see [styles/vocabularies.md](styles/vocabularies.md). The mood is a row in+ `tables.ts` (see the README's mood list). Then set the five **mood controls**, each 0..1, where+ 0.5 = the calibrated palette:++ | Control | What it moves |+ |---|---|+ | `energy` | groove density, drum level, sidechain depth, dynamics |+ | `warmth` | filters darker, tape drive and wow, a little more bass |+ | `brightness` | filters and pluck brightness open, hats up |+ | `tension` | pad detune wider, string attacks shorter, lead decays shorter |+ | `space` | reverb sends, delay mix, pad release |++ Controls change the sound only. Harmonic tension is yours to write (step 3).+3. **Compose the harmony.** Work inside the style's harmony language: its modes, chord qualities,+ tendencies and voicing rule. Decide the key and mode from the mood, not from habit.+ - Write a progression **for this brief**. Choose its length (2, 3, 4, 5, 6 or 8 bars) and its+ harmonic rhythm (one chord per bar, two per bar, or one per two bars) on purpose.+ - Voice each chord yourself. Move the voices by step and hold common tones. The bass owns the+ root.+ - Write each chord's bass line (one bar) in the style's bass idiom: held root, root and fifth,+ walking, offbeat 8ths, a syncopated 808 figure. Make the rhythm YOURS.+ - **Tension and release as a curve.** Stable (tonic), moving away (subdominant, relative,+ borrowed), leaning (dominant, suspension, pedal), home. Put home on the picture's key beat.+4. **Compose the motif(s).** A motif is 2-5 notes with its own rhythm. Invent the rhythm first:+ - Which beats does it avoid?+ - Does it start on an upbeat?+ - Where is the long note?++ Then the pitches: the contour, one leap, then steps back.++ Develop the motif. Don't photocopy it:+ - **repeat**, then **vary**: change the last interval, displace it by an eighth, extend it;+ - **sequence**: the same shape a step or a third higher;+ - **call and response**: the question ends off the tonic, the answer lands on it, or another+ instrument answers;+ - **fragment** it in a build, **augment** it (slower, longer notes) at the climax;+ - put it in the bass for menace, or high and quiet at the close.++ The phrase's high point goes in its second half. A phrase is 2 or 4 bars; a period is two phrases+ (question, answer). The line must respect the style's range and density.+5. **Choose or write the groove.** Pick a family from the style's list (`bounce`, `trap`,+ `brushes`, `hand`, ...). Set `density` 0..1, `variation` 0..1 and `fill` (a fill on a section's+ last bar). The seed varies every bar, so no two pieces share a loop. You can also write the drum+ bars yourself as notation, one or more bars per lane: `kick`, `snare`, `ghost`, `hat`, `perc`.+ Use a second groove for contrast (`half`, `build`).+6. **Write the form.** Sections are `{ kind, bars, harmony, lead, counter, arp, groove, bass,+ chordVel, energy, repeat, stretch }`.+ - The **kind** sets which layers may sound: intro, verse, groove, hook, build, half, breakdown,+ drop, bridge, swell, breath, outro. See the arrangement grammar in vocabularies.md.+ - Lines sound only where you write them.+ - Land each section change on a picture beat. At `bpm`, a bar lasts `beatsPerBar x 60 / bpm`+ seconds, and at 30 fps a beat is `1800 / bpm` frames.+ - Mark one section `stretch: true`: a film fit repeats or drops it to reach the exact length and+ still end on your outro.+7. **Check, render, listen:**+ ```+ node tools/music.mjs check <file>.ts#<export> [--fit --seconds 62] # EVERYTHING, must PASS (below)+ node tools/music.mjs render <file>.ts#<export> out.mp3 --stems # the file, plus the same report+ node tools/music.mjs novelty <a>.ts#x <b>.ts#y # several scores: vs shipped AND pairwise+ node tools/music.mjs score <file>.ts#<export> # the text score, bar by bar+ ```+ `check` runs everything:+ - key/mode problems and composer warnings (for example, a line shorter than its section);+ - the master: loudness vs target, true peak, and a note when the -1 dBTP ceiling stopped the+ gain short;+ - the **ghost, reverb and masking guards**;+ - the stems;+ - novelty.++ It exits non-zero on any failure. `render` prints the same report (stems with `--stems`), except+ novelty.+ - **Stems:** fix any part flagged more than 3 dB off with `levels`. `levels` is a **dB offset** per+ slot (+2 = two dB louder), added on top of the calibrated gain, the trims and the mood controls'+ shifts. LUFS alone once hid a sub 7-10 dB too hot.+ - **When the guards and the stems disagree, the guards win.** If masking fails (the melody isn't+ heard), raise the lead. The stem meter lets the lead sit up to +3 dB above its tolerance for+ this. You can also lower or thin what sits in the melody's register. Mood controls shift the+ stem targets with the sound (for example, brightness lifts the hats and their target); the+ printed targets already include that.+ - **Master short of target:** a gentle master (-16 LUFS) never compresses. If one peak blocks the+ gain, the whole piece stays quieter, and `check` says by how much. Fix it in the notes: stagger+ the bass under the loudest downbeat, roll the big chord, don't double the climax note.+ - **Novelty:** if it fails, change what the numbers point at. The per-feature scores name it:+ the lead's rhythm, the contour, the groove, the chord colours, the form. Changing the key fixes+ nothing.+ - **Listen:** the person hears it before it is used. Meters prove you aren't obviously wrong.+ Only an ear says right. For a **loop**, deliver a `.wav`: mp3 adds encoder padding, so it clicks+ or gaps at the loop point.++## The material format++Write the score in the film's own file, e.g. `engine/src/canvas-core/<film>Score.ts`, and export it:++```ts+import type { Material } from "./music";+export const score = (): Material => ({+ style: "<style id>", title: "<this film's score>", seed: <any integer>, mood: "<mood id>",+ bpm: <tempo in the style's range>, key: "<tonic>", mode: "<mode id>", meter: "<meter>",+ moodControls: { energy: <0..1>, warmth: <0..1>, brightness: <0..1>, tension: <0..1>, space: <0..1> },+ swing: <0.5 straight .. 0.67 hard>, dyn: [<start 0..1>, <end 0..1>], tail: <seconds of ring-out>,+ chords: { "<name>": { voicing: "[<note> <note> <note>]", bass: "<one bar of notation>" }, /* ... */ },+ motifs: { "<motif>": "<one or more bars of notation>", /* your variations are motifs too */ },+ grooves: { main: { family: "<family>", density: <0..1>, variation: <0..1> }, half: { family: "<family>" } },+ sections: [+ { kind: "intro", bars: <n>, harmony: ["<chord>", /* per bar, cycled */], chordVel: <0..1> },+ { kind: "hook", bars: <n>, harmony: [/* ... */], lead: ["<motif>", "<motif variant>", "r:<beats>"], stretch: true, energy: <0..1> },+ { kind: "groove", bars: <n>, harmony: [/* ... */], lead: ["<2-bar motif>"], loopLines: true },+ { kind: "bridge", bars: <n>, key: "<new tonic>", mode: "<mode>", harmony: [/* in the new key */], lead: [/* ... */] },+ /* ... */+ { kind: "outro", bars: <n>, harmony: ["<home chord>"], lead: ["<the motif's last word>"] },+ ],+});+```++A film plays it with `filmScore(score(), fps, frames)` from `canvas-core/score.ts`. That fits your+form to the exact length. `score.ts` is an empty skeleton to copy.++- **Voices:** `voices: { lead: "<alternate name>" }` swaps a slot for one of the style's+ alternates. Or give your own `{ inst, role, gainDb, opts }` (instruments: README table).+- **Loops:** `loop: true`, and the form length is the loop. `render` makes it seamless.+- **Split bars:** `harmony: ["<chord> <chord>"]` splits a bar in two. Give that section a `bass`+ override for it.+- **Lines play once.** `lead`, `counter` and `arp` start at the section's first bar and play ONCE,+ even though `harmony` cycles. A shorter line leaves rests, and `check` warns. Set+ `loopLines: true` to repeat the line until the section is full. `repeat: n` replays the whole+ section, lines included.+- **Section `energy`** (0..1, 0.5 = as written) sets the section's dynamics for every part,+ hand-written lines included. It scales velocity from 0.55x to 1.45x, roughly -5 to +3 dB. It+ also sets the density of generated grooves.+- **`dyn`** is the whole piece's dynamic level `[start, end]`, ramped (default `[0.62, 0.66]`).+ `swing` and `tail` default to the style's lower swing bound and 3.2 s.+- **Modulation:** give a section its own `key` and `mode`. The key check then reads each key region+ on its own. A lift of a step for the last chorus is fine when that section declares the new key.+- **The key check weighs the tonic.** It accepts your declared tonic and mode when the mode's scale+ explains the notes as well as any other reading, and the tonic is heard (at least 8 % of note+ time). A lydian or dorian passage whose notes lean on another degree gets read as that degree's+ major. Put the bass on the tonic at section starts and cadences, and state the mode's colour note.+- **Written drums:**+ - A `LiteralGroove` gives notation bars per lane (`kick`, `snare`, `ghost`, `hat`, `perc`).+ - The bars cycle from each section's first bar; `cycle: "piece"` cycles on the piece's bar count+ instead.+ - Unpitched drums ignore the written pitch: write `C4`.+ - A timpani in a drum lane (orchestral, choral, suspense, world) is tuned to the tonic of `key`,+ generated grooves included (`epic`).++**Notation** (bar-checked; a bar that doesn't add up throws):+- A token is `NOTE:DUR[@VEL]` (a pitch name with an octave, e.g. `F#4`), `[NOTE NOTE ...]:DUR` (a+ chord) or `r:DUR` (a rest).+- Bars are separated by `|`, or given as array items.+- Durations are in beats. In 6/8, 9/8 and 12/8 a beat is a dotted quarter, so an eighth is `1/3`.+ In 7/8 a beat is a quarter, so an eighth is `.5` and a bar is 3.5.+- `@VEL` scales the line's velocity (0..1).++## Craft notes (what makes it good, not just valid)++- **One idea, developed.** Most memorable scores have one motif, heard 6-12 times, never the same+ way twice. Two motifs at most; the second answers or contrasts the first.+- **Contrast by section:**+ - change the density (layers in and out);+ - change the register (the motif up an octave);+ - change the harmonic rhythm (twice as fast into a cadence);+ - change the groove (half-time).++ A section that only repeats the previous one is dead air.+- **Cadences on picture beats.** The strongest arrival (home chord, full layers, the motif's peak)+ goes on the most important frame. The claim, the reveal and the logo each get a structural+ downbeat. Use a breakdown or a breath (drums out, one bar of silence) right before it.+- **Tension curve.** Plan energy 0..1 per section before writing notes: rise, a dip before the peak,+ then release. Match it with density, register and harmony (leaning chords before home).+- **Endings.** End on a phrase, never on the last frame by accident:+ - a held home chord with the motif's last word;+ - a button (a short tutti hit);+ - an unresolved hold (suspense only).+- **Mood fit.** Match the mode, tempo and brightness to the words. If the listener names a different+ emotion from the one you declared, the choice was wrong, not the listener.+- **Breadth.** Across projects, vary the meter, the harmonic rhythm, the groove family and the form+ length. Two scores for two products should not be siblings.++## What checks what++| Check | Runs in | Fails when |+|---|---|---|+| key/mode (`planProblems`) | `check`, `render` | a key region's notes don't support its declared tonic and mode |+| composer warnings | `check`, `render` | (warns only) a line is shorter than its section, ... |+| master | `check`, `render` | (notes only) the peak ceiling stopped the gain short of the target |+| ghost guard | `check`, `render` | 4-bar windows are formless (few onsets, sustained, wet, no cadence) |+| reverb guard | `check`, `render` | the late tail sits within 10 dB of the dry sound |+| masking guard | `check`, `render` | the melody doesn't clear the other parts in 500 Hz-4 kHz |+| stems | `check`, `render --stems`, `stems` | a part is more than 3 dB off target (lead: up to +6 dB allowed); advisory for uncalibrated styles |+| novelty | `check`, `novelty` | similarity above 0.5 to a shipped piece (or to each other), or a reused 6-note melody fragment |++`tools/music-unit.mjs` keeps the engine honest: determinism, no defaults, every vocabulary renders.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.mdnew file mode 100644index 0000000..dae09c8--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md@@ -0,0 +1,145 @@+# Sound design: the effects kit, placed by frame, heard over the score++anidoodle makes its sound effects the way it makes its music: **in code, from nothing**. No samples+or recordings. Every effect is deterministic: the same cue and seed give identical samples.++Code: `engine/src/canvas-core/music/sfxKit.ts` (the kit), `sfxMix.ts` (placement), `sfxCore.ts`+(building blocks). Tool: `engine/tools/sfx.mjs`.++## What makes an effect sound designed, not generated++- **Layers.** Every sound has a transient (the contact: a 1-4 ms filtered noise burst), a body+ (modes of the struck object, a pitch-dropping sine, a friction band) and a tail (a small room from+ `dsp.room`). A single noise burst is not an effect. It is a click.+- **Physics, cheaply.** Plastic, bricks and bells are *modal*: a few damped sines at inharmonic+ ratios. Drops and bubbles ring with a *rising* pitch. A whoosh is a *pass-by*: distance sets+ level and air, radial speed sets the doppler glide (bright coming, darker going), angle sets pan.+ A pen's friction band brightens with stroke speed.+- **Stereo that moves.** Moving sounds travel across the field (`dir: 1` = left to right).+ Hits sit a little off-centre with a Haas offset. Tails are decorrelated.+- **No two hits alike.** Pitch, decay, pan, mode tuning and level (±1 dB) vary per seed. Twenty+ key ticks are twenty different ticks. `mixSfx` gives each cue its own seed from (kind, frame), so+ inserting a cue never changes the others.+- **Tuned where it is tonal.** chime, riser, `press:confirm` and `impact:bloom` follow the film's+ key. A sparkle in the wrong key sounds like a mistake, so there is **no default key or tempo**.+ Pass `plan.score: { piece, tempo? }` (key, bpm and bar come from the film's piece) or set+ `plan.key` / `plan.bpm`. A tuned kind with no key, or a riser with no bpm, throws.++## The kit++`node tools/sfx.mjs list` prints this live. The level is the target loudness over the sound's own+speaking window (K-weighted, see below). Duck is how far the score dips under it.++| kind | variants (first = default) | use it for | level | duck |+|---|---|---|---|---|+| tick | key, soft, ui, space | typing, one per character; a UI tick | -20.5 | 0 |+| press | thock, soft, confirm | the Generate button; `confirm` adds a tuned answer | -13 | 2 |+| pop | pop, cork, tiny | something appears; a card lands; a badge | -16 | 1 |+| ink | plip, double, bloom | an ink drop; `bloom` opens an ink-bloom frame | -15 | 2 |+| scratch | nib, pencil, marker | lettering being written (`lengthS` = writing time) | -18.5 | 1.5 |+| paper | slide, flip, rustle | a sheet lands (hit = landing), a page turn (hit = snap) | -18 | 1.5 |+| whoosh | soft, air, fast, deep | something passes the camera (hit = the pass-by) | -16 | 2 |+| swish | in, out, soft | a UI panel or card slides | -17 | 1 |+| riser | soft, air, tonal | THE build into the reveal (hit = its end) | -15 | 2 |+| impact | boom, soft, bloom | THE reveal; `bloom` breathes in first and shimmers in key | -9 | 6 |+| chime | sparkle, bell, glint | magic / success, tuned to the key | -17 | 1.5 |+| bubble | bubbles, splash, gloop | water life, the koi | -16.5 | 1.5 |+| 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 |++## Placing effects in a film++Cues are addressed by **film frame**. The frame is where the sound's sync point lands: the hit;+the pass-by of a whoosh; the landing of a paper slide; the END of a riser. Pre-roll (a whoosh's+approach, a riser's build) is rendered before the frame. If it would start before frame 0,+the plan throws and names the earliest legal frame.++```ts+import { filmSfx, launchLofi3, filmAudio, type SfxPlan } from "./music";+const plan: SfxPlan = {+ fps: 30, frames: 450, score: { piece: launchLofi3() }, beatZeroS: 0, seed: 7, // key, bpm, bar from the score+ cues: [+ { frame: 12, kind: "tick" }, // ...one per typed character+ { frame: 157, kind: "press", variant: "thock", snap: "beat", label: "Generate" },+ { frame: 182, kind: "scratch", variant: "nib", lengthS: 1.4 },+ { frame: 232, kind: "whoosh", variant: "soft", dir: 1 },+ { frame: 400, kind: "riser", beats: 4 }, // ends ON bar 5+ { frame: 400, kind: "impact", variant: "bloom", snap: "bar" },+ ],+};+export const audio = filmSfx(filmAudio(launchLofi3(), 15), plan); // Film.audio: score + effects+```++- `snap: "bar" | "beat" | "8th" | "16th"` moves the sync point to the tempo grid (`bpm`,+ `beatZeroS`, `beatsPerBar`). Snap musical moments: the reveal on the bar, a sparkle on the beat.+ Keep UI sounds (typing, clicks) on the picture.+- `beats` sizes a riser in tempo. Its chord pulses in 8ths, then 16ths, then 32nds, and it stops+ on the downbeat.+- Per cue: `variant`, `seed`, `pitch` (semitones), `gainDb`, `dir`, `lengthS`, `duckDb`, `minDb`,+ `label`.+- `mixSfx(music, plan)` returns the mix, the stems (`sfx`, ducked `music`), the duck curve, every+ placed cue and the audibility table. `filmSfx` wraps it for `Film.audio` and **throws on a+ buried cue**.+- One master at the very end: a look-ahead true-peak ceiling at -1 dBTP (`ceilingDb`). The score+ arrives already mastered, so nothing is renormalised.++## Levels and the audibility rule++A cue nobody hears is a bug, not a subtle choice. (The first effects PR sat 13-19 dB under its+music, and its test only checked that they existed.)++- Every cue is measured against the ducked score **at its own moment**. The yardstick is+ K-weighted (BS.1770) loudness over the cue's *speaking window*: the 10 ms frames within 10 dB of+ its loudest, 15-500 ms long. The score is measured over the same window, at least 100 ms.+- **margin = cue - score.** The mix fails if any cue is more than `minDb` under (default **-6+ dB**). Short transients cut through at -3 to -6. Sustained textures (scratch, thread) want -3+ or better.+- To fix a failing cue, raise its `gainDb` first. Raise its `duckDb` only for the moments that+ matter.+- Ducking: the score dips before the cue's window (40 ms raised-cosine attack), holds, and comes+ back over 280 ms (1.2 s after an impact). Typing does not duck. The reveal ducks 6 dB.+- Measured on the demo (launchLofi3, first 15 s, 33 cues): -15.5 LUFS, -1.9 dBTP, every cue audible.+ Margins: typing +3 to +8 dB over the intro pad; groove cues -3.5 to +5 dB; the reveal +10.7 dB.++## Taste: when to use effects++- **Effects only on real direction changes.** A press, an appearance, a scene move, a landing.+ Never under every motion, and never a constant bed of whooshes. Silence around a cue is what+ makes it land.+- **One signature riser, one impact per film.** They mark the big reveal. A second riser halves+ both.+- Transitions are gentle moves, so their sound is gentle: `whoosh:soft` and `swish:soft`. Never a+ sharp swoosh.+- Typing is one `tick` per character at the typing cadence, with `space` on spaces. Its level sits+ above the intro and under the groove.+- Put at most two cues in any 100 ms. A thock on the kick merges into the kick, which is lovely+ when it starts the groove and mud anywhere else.+- Hear it in context before it ships. Render the kit page (`node tools/sfx.mjs kit <dir>`) and a+ demo over the real score, and check the audibility table.++## Tools and checks++```+node tools/sfx.mjs list # kinds, variants, levels, uses+node tools/sfx.mjs one whoosh soft 3 out.mp3 # one sound+node tools/sfx.mjs kit <dir> # every variant x3 + demo + page + meters.json + spectra/+node tools/sfx.mjs test # the gate+```++The test checks every kind and variant for:++- determinism (md5 of two renders) and seed variation;+- no NaN, no DC, a peak of -1 dBFS or lower, an end at zero, and no fizz above 20 kHz (a+ 16.5 kHz air roll-off is built in);+- a non-silent sound whose level stays stable across seeds.++It also checks:++- the whoosh's doppler and pan travel;+- a chime tuned to its key;+- a riser synced to tempo, and snap-to-beat;+- the demo: deterministic, at film length, true peak within ceiling, every cue audible, the score+ ducked under the impact;+- that a buried cue fails;+- that validation throws clearly on an unknown kind or variant, a pre-roll before frame 0, a bad+ seed, a frame outside the film, a snap without bpm, a bad key, or a pitch out of range.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.md b/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.mdnew file mode 100644index 0000000..a51503e--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/music/styles/lofi-electronic.md@@ -0,0 +1,108 @@+# Style: lo-fi electronic (chill, upbeat, clean)++> 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`). That+> score is ours and is in the novelty corpus. Never reuse its progression, hook, rhythms, drums or+> form.++## The sound++Chill but **upbeat**, **clear**, **not noisy**:+- a warm pad that breathes with the kick;+- a plucked lead through a dotted-eighth ping-pong delay;+- a high counter-line;+- a round sine sub;+- a bouncy, clean kit.++**Never:**+- synth electric piano;+- vinyl crackle;+- bit-crush;+- a dark master low-pass;+- heavy tape.++Those read as dusty lo-fi hip-hop (the `lofi` style), not clean electronic.++| Slot | Voice | How it's made | Stem RMS target |+|---|---|---|---|+| chords | `warmPad` | 7 PolyBLEP saws, spread 0.55 x +-14 cents, slow per-voice drift, 12 dB low-pass at 2.6 kHz, 0.5 s attack, 1.4 s release | -21 dB |+| lead | `softPluck` | triangle + square an octave down, filter snaps open, 0.42 s decay, dotted-eighth ping-pong (feedback 0.28, mix 0.24) | -16.5 dB |+| counter | `softPluck` | brighter, panned 0.35, more delay and room | -24 dB |+| bass | `sub` | sine + a whisper of the 2nd harmonic, low-passed at 150 Hz | -18 dB |+| kick / snare / ghost / hat | kit | a bouncy kick, a snare, rim ghosts about 11 dB under, 16th hats | -14 / -20 / - / -28 dB |+| arp, perc | `softPluck`, `hat` | optional extra layers | - |++Alternates:+- lead: `bell`, `mallet`, `guitar`;+- chords: `strings`, `piano`;+- bass: `warm`.++Bus:+- the kick ducks the chords and the counter (depth 0.38, release 0.24 s);+- tape is barely there (2.5 cents of wow);+- clean master at **-14 LUFS**, true peak **<= -1 dBTP**.++The stem targets were calibrated on a listened score, and they are the only calibrated targets.++## Grooves++`bounce`, `halfTime`, `broken`, `skip`, `pulse`, `build`. Pick one per section role (`main`,+`half`, `build`) and set `density` and `variation`. The seed varies every bar. Swing 0.52-0.56.++## Harmony language (write your own progression)++- **Modes:** major, dorian, lydian, aeolian, mixolydian.+- **Qualities:** 7ths, 9ths, 11ths, 13ths, add9, sus2 and sus4. Keep bare triads for the landing.+- **Tendencies:**+ - loops of 2, 4 or 8 bars;+ - ii-V motion;+ - drifting IV-iii-vi motion;+ - modal vamps (i-IV in dorian, I-II in lydian);+ - a borrowed iv or bVII for a wistful turn.+- **Harmonic rhythm:** one chord per bar or two. A change may anticipate the bar by an eighth.+- **Voicing:** rootless 3-4 note voicings between about E3 and E4, moving by step. The sub owns the+ root.+- **Tension:** sus4 and 13ths lean, maj7#11 floats, 7b9 or a borrowed iv aches. Release by stepping+ the leaning voice down.++## Melody rules (write your own motif)++- Lead in C4-A5, counter an octave above.+- Short arches, with the high point late in the phrase.+- 1-3 notes per beat, with rests so the echo can answer.+- A 2-5 note cell with its own rhythm: repeat it, then vary it (a step up, the last interval+ inverted, displaced by an eighth).+- Call and response between the lead and the counter.++## Arrangement grammar++A typical shape: intro -> groove -> hook -> (half-time or breakdown) -> drop on home -> outro. Add+or remove one layer at a time. Put the drop (everything back, home chord) on the picture's strongest+beat.++**Transitions:**+- a fill bar;+- a half-time bar;+- drums out for a breakdown.++**Endings:**+- the home chord held, with the motif's last note;+- a clean button.++## Mixing: balance by stem RMS, then master++```+node tools/music.mjs stems <file>.ts#<export>+node tools/music.mjs render <file>.ts#<export> out.mp3 --stems+```++A stem is a part's own signal:+- unmastered, pre-room, after its gain and the duck;+- measured as RMS over its **active** samples (|x| > 1e-4), left channel, at 24 kHz.++Fix a flagged part with `levels`, never with the master.++**The lesson:** integrated LUFS only says how loud the whole mix is. On the launch score the mix read+a healthy -14 LUFS while the sub sat **7-10 dB too hot**. `tools/music-unit.mjs` keeps this as a+regression: a sub 9 dB hot still masters to -14.0 LUFS, and only the stem meter flags it.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/styles/music-box.md b/plugins/anidoodle/skills/anidoodle/references/music/styles/music-box.mdindex 8bfba70..cfe571f 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/styles/music-box.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/styles/music-box.md@@ -1,10 +1,11 @@-# Style preset: music-box (the default)+# Style: music box-> The original anidoodle music recipe, kept **verbatim** below as one style preset among the eleven-> in `engine/src/canvas-core/music/tables.ts` (`STYLES.musicBox`). Its numbers are what the-> `musicBox` and `bell` instruments implement. Its ban list is now the rule for THIS preset only;-> for every other style the bans became measured guards (see `../README.md`, "Guards"). The scar-> story is kept because it is why the guards exist.+> The original anidoodle music recipe, kept below for its SOUND numbers (the `musicBox` and `bell`+> instruments implement them) and its scar story (why the guards exist). It is one style among the+> vocabularies in `engine/src/canvas-core/music/vocab.ts` (`VOCAB.musicBox`), not a default: there is+> no default style. Its fixed composing choices (one progression, one scale, one accompaniment+> figure) were rewritten below as ranges: the composer writes the notes ([../compose.md](../compose.md)).+> Its ban list is the rule for THIS style only; for other styles the bans became measured guards.---@@ -27,11 +28,11 @@- bass: same pluck one to two octaves down with only the first two partials, gain 0.5. It is still a pluck. It never sustains.- "room": ONE early reflection, 30 ms late, 14 dB down. No tail.-**Key, register, harmony.** C, G or D major. Melody between C5 and C7, bass C3 to G3. One chord per bar, **I, IV, V, I**, and nothing cleverer. If you want a lift for the payoff, go up a whole step and play the same thing.+**Key, register, harmony.** Any major, lydian, dorian or minor key you choose for the mood (a minor music box is a real, uncanny sound). Melody between C5 and C7, bass C3 to G3. Harmonic rhythm one chord per bar; the progression is yours (plagal and deceptive turns read well; the original film used the plainest possible one and said "nothing cleverer", which is a choice, not a rule). For a lift at the payoff, move the key up a step.-**Melody.** Chord tones and the major pentatonic (1 2 3 5 6). Mostly steps, leaps only onto chord tones. Four-bar phrases in pairs: the QUESTION ends on the 5th over V, the ANSWER ends on the root over I, **and the answer follows immediately.** The story may hold its resolution back for a minute; the tune may not. What you hold back is the ARRANGEMENT: the octave doubling, the full arpeggio and the bell arrive with the payoff.+**Melody.** Chord tones plus the mode's scale, mostly steps, leaps onto chord tones. Four-bar phrases in pairs: the QUESTION ends off the tonic, the ANSWER lands on it, **and the answer follows immediately.** Your own motif, with its own rhythm.-**Rhythm.** At 120 bpm and 30 fps a beat is 15 frames and a straight eighth is 7.5 frames, which does not exist. Use triplet eighths, 5 frames: 12/8, which is what a music box plays anyway. Accompaniment is a rolling 1-5-3-5 arpeggio on the triplets; melody mostly on beats. Every onset is a row in a cue table with its FRAME, and the module asserts at load that each sample index equals `round(frame / fps * sampleRate)`.+**Rhythm.** At 120 bpm and 30 fps a beat is 15 frames and a straight eighth is 7.5 frames, which does not exist. Use triplet eighths, 5 frames: 12/8, which is what a music box plays anyway. Accompaniment is an arpeggio figure you design on the triplets (choose its order of chord tones and its cycle length; a 4-note cell over 3-note groups makes a gentle hemiola); melody mostly on beats. Every onset is a row in a cue table with its FRAME, and the module asserts at load that each sample index equals `round(frame / fps * sampleRate)`.**Sound events ride on top, quietly:** a tick is a 2 ms noise burst through a band-pass at 3 kHz, the tock at 2 kHz, 20 dB under the melody. A landing is one soft pluck on its beat. The DING is a bell on the tonic (partials 1, 2, 3, 4.2, tau 1.2 s, doubled an octave down) on the final downbeat, with at least four beats of film after it.diff --git a/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md b/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.mdnew file mode 100644index 0000000..6f24f48--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/music/styles/vocabularies.md@@ -0,0 +1,537 @@+# Style vocabularies++> 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)).++| Style | Atmosphere | Tempo, meters | Moods | Grooves |+|---|---|---|---|---|+| `lofiElectronic` | warm, chill but upbeat, clean: a breathing pad, a plucked hook through ping-pong echoes, a round sub, a bouncy kit | 80-100 bpm; 4/4 | calm, joy, hopeful, nostalgic, wistful, curious | bounce, halfTime, broken, skip, pulse, build |+| `drive` | forward, bright, confident: four-on-the-floor, a pumping supersaw bed, a gritty bass line, a plucked arp | 110-140 bpm; 4/4 | drive, triumph, tension, joy, awe | fourFloor, broken, build, halfTime, tension |+| `cinematic` | wide and emotional: string swells, low ostinatos for tension, harp and bell colour, a low boom on the arrival | 60-120 bpm; 4/4, 3/4, 6/8 | awe, triumph, tension, melancholy, hopeful, dread | pulse, tension, build, halfTime |+| `ambient` | floating, spacious, luminous: long pads, bells and plucks with space around them, a soft heartbeat at most | 50-80 bpm; 4/4, 3/4 | awe, calm, hopeful, tender, dread | pulse, brushes |+| `folk` | intimate and warm: fingerpicked guitar, soft piano, a harp or celesta line, brushes | 60-110 bpm; 6/8, 3/4, 4/4 | tender, calm, wistful, nostalgic, hopeful, romantic | brushes, pulse, shuffle |+| `playful` | light, cheeky, springy: marimba and pizzicato-like plucks, a bouncy bass, a skipping kit | 100-150 bpm; 4/4, 6/8 | playful, joy, curious | skip, shuffle, bounce, fourFloor |+| `musicBox` | small, bright, clockwork, innocent; plucked and never sustained | 100-132 bpm; 12/8, 3/4, 6/8 | joy, curious, tender, playful, wistful, eerie | none (no drums) |+| `nocturne` | intimate, expressive, late-night: one piano, rubato, pedal | 50-76 bpm; 3/4, 6/8, 4/4 | tender, melancholy, wistful, romantic, grief | none (no drums) |+| `minimalist` | hypnotic, curious, clean: interlocking ostinatos that change slowly | 96-144 bpm; 4/4, 12/8, 5/4, 7/8 | curious, tension, awe, calm | pulse |+| `jazz` | loose, warm, clever: swing ride, walking bass, comping piano | 80-200 bpm; 4/4, 3/4 | playful, nostalgic, romantic, curious, sensual, mischief | swing, brushes, shuffle |+| `lullaby` | soft, rocking, safe | 56-78 bpm; 3/4, 6/8 | tender, calm | none (no drums) |+| `chiptune` | 8-bit, bright, game-like: two pulses, a triangle, noise drums | 110-170 bpm; 4/4, 6/8 | joy, playful, drive, tension, mischief | fourFloor, bounce, shuffle, skip |+| `lofi` | hazy, nostalgic, crackly: FM e-piano, vinyl, a lazy swung beat (the dusty cousin of lo-fi electronic) | 68-90 bpm; 4/4 | nostalgic, calm, wistful, sensual | bounce, halfTime, shuffle |+| `orchestral` | big and heroic: brass theme, string ostinato engine, choir, timpani | 70-140 bpm; 4/4, 3/4, 6/8 | heroic, triumph, awe, tension, grief | epic, build, tension, pulse |+| `suspense` | unsettling, cold, withheld: low drones, heartbeat pulse, high bowed harmonics, stingers | 50-110 bpm; 4/4, 5/4, 3/4 | tension, dread, eerie | pulse, tension, epic |+| `rock` | live-band energy: driven guitars, bass locked to the kick, a tight kit, maybe organ | 90-160 bpm; 4/4, 6/8 | drive, anger, triumph, joy, heroic | rock, halfTime, shuffle, fourFloor |+| `hipHop` | head-nod or dark trap: heavy 808, crisp clap, rolling hats, a moody loop on top | 70-100 bpm; 4/4 | drive, calm, nostalgic, sensual, anger, tension | trap, bounce, halfTime, broken |+| `house` | euphoric, dancing, bright: four-on-the-floor, offbeat bass, stabs, a big pad | 118-128 bpm; 4/4 | joy, drive, sensual, hopeful | fourFloor, build, broken |+| `synthwave` | neon-nostalgic, cinematic 80s: big gated snare, pulsing 8th bass, lush pads, a soaring lead | 80-118 bpm; 4/4 | nostalgic, drive, heroic, romantic, tension | fourFloor, halfTime, rock, build |+| `world` | rooted, spacious, rhythmic: a drone, a modal melody on plucked strings or a flute, hand percussion cycles (write your own melody; name the tradition you draw on) | 60-150 bpm; 7/8, 9/8, 12/8, 6/8, 4/4, 5/4 | calm, joy, curious, mischief, awe, sensual | hand, pulse, brushes |+| `choral` | vast, human, reverent: voices in parts, organ, bells, a slow swell | 50-90 bpm; 4/4, 3/4 | awe, grief, hopeful, tender, heroic | pulse |++## Groove families++Pick a family and its knobs (`density`, `variation`, `fill`, `accent`); the seed varies every bar. Or write the drum bars yourself.++- `bounce`: lo-fi / hip-hop bounce: kick on 1 plus syncopated pickups, backbeat on 2 and 4, ghost notes, 8th or 16th hats with accents+- `fourFloor`: house / drive: kick on every beat, clap on 2 and 4, off-beat open hats, 16ths when dense+- `halfTime`: half-time: kick on 1 (and a pickup), snare on 3; the same tempo feels twice as slow (a breath, a scene change)+- `broken`: broken beat / garage: kicks displaced off the grid, backbeat kept, ghosted 16ths; restless, modern+- `shuffle`: shuffle: triplet grid, swung hats, kick on 1 and 3 with a skip; playful, bouncy+- `pulse`: pulse: a soft heartbeat kick, no backbeat, sparse shaker; ambient and cinematic under-scoring+- `brushes`: brushes: soft rim on 2 and 4, shaker swishes, a gentle kick; tender, acoustic+- `build`: build: snare 8ths then 16ths rising in velocity across the section, kick on quarters; ends on the next downbeat+- `tension`: tension: 3-3-2 kick ostinato, accent on 4, quiet 16th hats; cinematic urgency, chases+- `skip`: skip: kick on 1 and the and-of-2, clap on 2 and 4, a skipping 16th perc; playful, light+- `trap`: trap: sparse syncopated kicks (the 808 bass follows them), clap on 3, 16th hats with velocity ramps and bursts, an open hat now and then+- `epic`: epic: big low hits (kick / timpani in perc) in a 3-3-2 or 1-and-3 figure, a snare accent on 4; orchestral and trailer weight+- `hand`: hand percussion: dum (low) on each group start, tek (rim) inside, ka (perc) fills; groups follow the meter (7/8 = 2+2+3, 9/8 = 2+2+2+3, 5/4 = 3+2)+- `rock`: rock: kick on 1 and 3 with an 8th pickup, snare backbeat, 8th hats, a crash (perc) on section starts+- `swing`: jazz swing: ride on the beats and the swung skip of 2 and 4, foot hi-hat (perc) on 2 and 4, feathered kick, snare comping ghosts++## Section kinds (the arrangement grammar)++A kind decides which layers may sound; your lines sound only where you write them.++- `intro` (drums: none, bass: no): chords (and any line you write) without drums or bass: set the colour, state the key+- `verse` (drums: main, bass: yes): the groove under a lighter line: room for picture and words+- `groove` (drums: main, bass: yes): chords, bass, drums: the bed, no lead unless you write one+- `hook` (drums: main, bass: yes): full groove under the motif: the memorable part+- `build` (drums: build, bass: yes): rising density (snare 8ths to 16ths), rising line, lands on the next downbeat+- `half` (drums: half, bass: yes): half-time drums: the same tempo feels slower (a scene change, a breath with pulse)+- `breakdown` (drums: none, bass: no): drums and bass out, chords and a thin line: the held breath before a landing+- `drop` (drums: main, bass: yes): everything back on a strong chord: the landing, put it on the picture's key beat+- `bridge` (drums: main, bass: yes): new harmony away from home (a borrowed or relative area) before the return+- `swell` (drums: none, bass: yes): long notes crescendo over 2-8 bars (orchestral swell), peaks on the downbeat after+- `breath` (drums: none, bass: no): near silence: one held chord or nothing, authored (max 2 bars)+- `outro` (drums: none, bass: yes): home chord held, the motif's last word, then the tail++## `lofiElectronic`: lo-fi electronic++warm, chill but upbeat, clean: a breathing pad, a plucked hook through ping-pong echoes, a round sub, a bouncy kit. Tempo 80-100 bpm, meters 4/4, swing 0.52-0.56.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `warmPad` | -3 | -21 | strings (`strings`, -6 dB), piano (`piano`, -4 dB) |+| lead | `softPluck` | 6 | -16.5 | bell (`fmBell`, 0 dB), mallet (`marimba`, 2 dB), guitar (`guitar`, 2 dB) |+| counter | `softPluck` | 8 | -24 | - |+| bass | `sub` | -6 | -18 | warm (`bass`, -2 dB) |+| kick | `kick` | 0.5 | -14 | - |+| snare | `snare` | 8 | -20 | - |+| ghost | `snare` | 4 | - | - |+| hat | `hat` | 20 | -28 | - |+| arp | `softPluck` | 4 | - | - |+| perc | `hat` | 14 | - | - |++Stem targets: calibrated on a listened score.++- **Harmony language.** Modes: major, dorian, lydian, aeolian, mixolydian. Qualities: 7ths, 9ths, 11ths and 13ths; add9; sus2/sus4 for air; avoid bare triads except on the landing. Tendencies: loops of 2, 4 or 8 bars; ii-V motion, IV-iii-vi drifts, modal vamps (i-IV in dorian, I-II in lydian), borrowed iv or bVII for a wistful turn; the home chord arrives on a structural beat. Harmonic rhythm: one chord per bar or two per bar; the change can anticipate the bar by an eighth. Voicing: rootless 3-4 note voicings between E3 and E4 moving by step (common tones held); the bass owns the root. Tension and release: sus4 and 13ths lean, maj7#11 floats, a dominant 7b9 or a borrowed iv aches; release by resolving the lean voice down a step.+- **Melody.** Range C4-A5 for the lead, the octave above for counter lines. Contour: short arches; the high point in the second half of a phrase; answer phrases end lower. Density: 1-3 notes per beat; leave rests so the echo answers. Motif: a 2-5 note cell with its own rhythm; repeat it, then vary it (shift it up a step, invert the last interval, displace it by an eighth); call and response between lead and counter.+- **Arrangement.** intro -> groove -> hook -> (half-time or breakdown) -> drop on home -> outro; add or remove one layer at a time. Transitions: a fill bar, a half-time bar, drums out for a breakdown, then everything back on a downbeat. Endings: home chord held with the motif's last note, or a clean button on 1.+- **Grooves:** bounce, halfTime, broken, skip, pulse, build. **Avoid:** synth ePiano, vinyl crackle, bit-crush, a dark master low-pass: that is dusty lo-fi hip-hop, not clean electronic.++## `drive`: driving electronic++forward, bright, confident: four-on-the-floor, a pumping supersaw bed, a gritty bass line, a plucked arp. Tempo 110-140 bpm, meters 4/4, swing 0.5-0.52.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `strings` | -2.7 | -22 | - |+| lead | `strings` | 5.4 | -16 | pluck (`softPluck`, 5 dB) |+| counter | `fmBell` | 6 | -27.3 | - |+| bass | `bass` | 0.1 | -16 | sub (`sub`, -5 dB) |+| kick | `kick` | 2.5 | -12 | - |+| snare | `snare` | 10.5 | -18 | - |+| ghost | `snare` | -2 | - | - |+| hat | `hat` | 12 | -26 | - |+| arp | `softPluck` | 4.2 | -21 | - |+| perc | `hat` | 18.3 | -27 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: aeolian, dorian, mixolydian, major. Qualities: triads and power voicings, sus2, add9; minor with a major IV (dorian) for lift. Tendencies: i-VI-III-VII, i-v-VI-IV, bVI-bVII-i climbs; long pedal tones under changing chords; a key lift of a step for the last chorus. Harmonic rhythm: one chord per bar or per two bars; stabs on off-beats. Voicing: wide: root-fifth-octave low, tight triads above C4; the bass line is 8ths or offbeat. Tension and release: a pedal under a moving chord, a build that withholds the kick, a riser into a drop; release on the downbeat with everything.+- **Melody.** Range A3-E6. Contour: repeated cells climbing by step; big leaps at the drop. Density: 8ths and 16ths; arps in 3-note cells across 4/4 (hemiola). Motif: a rhythmic riff of 3-6 notes, repeated with the last note changed; sequence it up the scale in the build.+- **Arrangement.** intro (filtered) -> build -> drop -> breakdown -> build -> bigger drop -> outro. Transitions: builds of 4-8 bars, a one-beat breath before the drop. Endings: a button on 1 or a filtered fade of the groove.+- **Grooves:** fourFloor, broken, build, halfTime, tension. **Avoid:** swing, soft attacks on the lead, more than 4 layers in the breakdown.++## `cinematic`: cinematic / orchestral++wide and emotional: string swells, low ostinatos for tension, harp and bell colour, a low boom on the arrival. Tempo 60-120 bpm, meters 4/4, 3/4, 6/8, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `strings` | 1.2 | -18 | - |+| lead | `strings` | 4.5 | -17 | piano (`piano`, 0 dB), bell (`fmBell`, -4 dB), celesta (`celesta`, 0 dB) |+| counter | `harp` | 12 | -36.7 | piano (`piano`, -3 dB) |+| bass | `strings` | 1.3 | -19 | - |+| arp | `strings` | 3.4 | -21 | - |+| kick | `kick` | -2.4 | -16 | - |+| snare | `snare` | -2 | -24 | - |+| ghost | `snare` | -4 | - | - |+| hat | `hat` | 6 | -32 | - |+| perc | `fmBell` | -8 | - | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: aeolian, harmonicMinor, lydian, major, phrygian, dorian. Qualities: open fifths, add9, sus2/sus4, minor with a major IV; chromatic mediants (C to E, C to Ab) for awe. Tendencies: slow harmonic rhythm (1-2 bars per chord); i-bVI-bVII-i for epic, i-iv-V for drama, lydian II for wonder, a pedal bass under moving chords for tension; big arrivals on chromatic mediants. Harmonic rhythm: one chord per 1-2 bars; tension sections hold one chord over an ostinato. Voicing: spread wide: bass octaves below C3, open fifths, the melody doubled an octave on the climax (stagger the bass to keep peaks musical). Tension and release: minor seconds against a pedal, a b6 leaning to 5, suspended 4ths held long, harmonic minor's raised 7th; release to a major chord or a picardy third.+- **Melody.** Range G3-C6 (strings), harp and bell above. Contour: long arcs over 4-8 bars, a big leap (6th, octave) then stepwise fall. Density: 0.5-2 notes per beat; tension ostinatos 2-4 per beat. Motif: a 3-4 note idea that returns transformed: augmented (slower) at the climax, in the bass for menace, in the harp for tenderness.+- **Arrangement.** intro (a colour, a drone) -> theme -> swell/build -> climax on the key picture beat -> release -> quiet coda. Transitions: crescendo over 4-8 bars; a breath of silence before the arrival; a low boom on the downbeat. Endings: a held chord ringing into the tail, or a hard-out on the cut.+- **Grooves:** pulse, tension, build, halfTime. **Avoid:** more than four families at once outside the climax; fast drums under a tender theme.++## `ambient`: airy ambient++floating, spacious, luminous: long pads, bells and plucks with space around them, a soft heartbeat at most. Tempo 50-80 bpm, meters 4/4, 3/4, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `warmPad` | 1.5 | -19 | - |+| lead | `fmBell` | 1.3 | -20 | pluck (`softPluck`, 5 dB), vibes (`vibes`, 0 dB) |+| counter | `softPluck` | 6.8 | -25 | - |+| bass | `sub` | -8.3 | -22 | - |+| arp | `celesta` | -0.9 | -24 | - |+| kick | `kick` | -6.4 | -20 | - |+| ghost | `snare` | -6 | - | - |+| hat | `hat` | 6 | -32 | - |+| perc | `hat` | 4 | - | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: lydian, major, dorian, majorPentatonic, aeolian. Qualities: maj7, add9, maj7#11, sus2, quartal stacks (4ths). Tendencies: two-chord oscillations (I-II lydian, i-IV dorian), planing (the same shape moved by step), a pedal note held through changes. Harmonic rhythm: slow: one chord per 2-4 bars. Voicing: wide and open, high register, no thirds low; let voices ring. Tension and release: a #11 or a 9 against the root; release by the melody settling on the fifth or the root.+- **Melody.** Range C5-C7 bells, pluck echoes above. Contour: sparse, falling phrases of 2-5 notes; rests as long as the notes. Density: 0.25-1 note per beat, but a motif at least every 8 bars (the ghost guard). Motif: a 3-note bell figure that returns, echoed by the pluck at a new register.+- **Arrangement.** slow evolution: add one layer every 4-8 bars, take one away before the end. Transitions: crossfades; a pad change on a bar line. Endings: the motif once more, alone, into the tail.+- **Grooves:** pulse, brushes. **Avoid:** formlessness: sustained pads with no onsets and no cadence (the ghost failure); run the guards.++## `folk`: tender acoustic++intimate and warm: fingerpicked guitar, soft piano, a harp or celesta line, brushes. Tempo 60-110 bpm, meters 6/8, 3/4, 4/4, swing 0.5-0.54.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `piano` | 7 | -33 | strings (`strings`, -8 dB) |+| arp | `guitar` | 8 | -22.9 | - |+| lead | `harp` | 14 | -18.8 | piano (`piano`, 0 dB), guitar (`guitar`, 2 dB), strings (`strings`, -2 dB) |+| counter | `celesta` | 8.2 | -24 | - |+| bass | `bass` | -4.4 | -21 | - |+| kick | `kick` | -4.5 | -20 | - |+| snare | `snare` | -6 | -26 | - |+| ghost | `snare` | 3.4 | -28 | - |+| hat | `hat` | 2 | -30 | - |+| perc | `hat` | 14 | -35.8 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, mixolydian, dorian, majorPentatonic, aeolian. Qualities: triads, add9, sus2, slash chords with a walking bass (I - V/7 - vi). Tendencies: I-V/7-vi-IV descents, bVII-IV-I (mixolydian), plagal IV-I endings, a relative minor detour. Harmonic rhythm: one chord per bar in 6/8 or 3/4; two per bar in 4/4. Voicing: guitar-shaped: root-fifth-tenth, open strings ringing; piano in the middle, melody on top. Tension and release: a suspended 4th resolving, a IV minor (iv) borrowed for the ache; release plagal (IV-I).+- **Melody.** Range D4-G5, singable (a 10th at most). Contour: stepwise with one leap per phrase, rising question, falling answer. Density: 1-2 notes per beat, a held note at each phrase end. Motif: a singable 4-bar phrase; the answer repeats its start and changes its end.+- **Arrangement.** guitar alone -> + melody -> + piano and bass -> + counter line -> thin to guitar and melody for the end. Transitions: a pickup note into each phrase; a bar of guitar alone between verses. Endings: plagal cadence, a rolled final chord.+- **Grooves:** brushes, pulse, shuffle. **Avoid:** four-on-the-floor, heavy drums, synth pads, fast arpeggios that bury the melody.++## `playful`: playful / bouncy++light, cheeky, springy: marimba and pizzicato-like plucks, a bouncy bass, a skipping kit. Tempo 100-150 bpm, meters 4/4, 6/8, swing 0.5-0.6.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| lead | `marimba` | 4.1 | -16 | chip (`pulse`, -4 dB), pluck (`softPluck`, 5 dB), bell (`fmBell`, -2 dB) |+| chords | `vibes` | -4.3 | -22 | - |+| arp | `harp` | 8 | -22.4 | - |+| counter | `celesta` | 10 | -23 | - |+| bass | `bass` | -1.6 | -18 | tuba (`sub`, -4 dB) |+| kick | `kick` | 0.3 | -15 | - |+| snare | `snare` | 8.1 | -21 | - |+| ghost | `snare` | 0 | -26 | - |+| hat | `hat` | 22.2 | -28 | - |+| perc | `hat` | 19.7 | -29 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, mixolydian, majorPentatonic, lydian, blues. Qualities: triads and 6ths, dominant 7ths, chromatic passing chords (a diminished between I and ii). Tendencies: fast harmonic rhythm (2 chords a bar), I-vi-ii-V turnarounds, secondary dominants (V/V), a surprise bVI. Harmonic rhythm: two chords per bar, on-beat stabs. Voicing: close, mid-high; the bass bounces root-fifth (oom-pah) or walks. Tension and release: a chromatic approach note, a held dominant with a pause; release with a cheeky button.+- **Melody.** Range C4-C7 (mallets love the top). Contour: leaps and staccato repeated notes; zig-zags; grace-note slides. Density: 2-4 notes per beat, with sudden rests (comic timing). Motif: a 3-note staccato cell with a leap; answer it lower, then sequence it.+- **Arrangement.** short sections (4-8 bars), stop-time breaks, call and response between lead and counter. Transitions: a stop (all out for a beat), a drum fill, a key lift. Endings: a button: a short tutti hit on 1, sometimes after a comic pause.+- **Grooves:** skip, shuffle, bounce, fourFloor. **Avoid:** long pads, slow tempo, minor-key sustained melodies.++## `musicBox`: music box++small, bright, clockwork, innocent; plucked and never sustained. Tempo 100-132 bpm, meters 12/8, 3/4, 6/8, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| lead | `musicBox` | 3.5 | -16 | celesta (`celesta`, 0 dB), bell (`fmBell`, -4 dB) |+| arp | `musicBox` | -6 | -26 | - |+| bass | `musicBox` | -3 | -24 | - |+| counter | `bell` | 0.3 | -22 | - |+| chords | `celesta` | -5.3 | -27 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, lydian, dorian, aeolian, majorPentatonic. Qualities: triads and sus2; a minor music box is a real (and uncanny) sound. Tendencies: any functional progression you write; plagal and deceptive turns read well; a whole-step lift for the payoff. Harmonic rhythm: one chord per bar. Voicing: melody C5-C7, bass C3-G3, arpeggio figures in between (you choose the figure). Tension and release: an unresolved 4th or a borrowed iv; release on a clean tonic.+- **Melody.** Range C5-C7. Contour: hooky, skipping. Density: more notes, never longer notes (no sustain). Motif: a 3-5 note hook with a distinctive rhythm; restate it, answer it.+- **Arrangement.** melody -> +bass -> +arpeggio -> +octave sparkle -> bell on the final downbeat. Transitions: add a layer each phrase. Endings: a bell or a single plucked tonic.+- **Grooves:** none. **Avoid:** sustained pads, long reverb tails, slow attacks (the ghost failure); see styles/music-box.md for the old recipe's numbers.++## `nocturne`: nocturne / solo piano++intimate, expressive, late-night: one piano, rubato, pedal. Tempo 50-76 bpm, meters 3/4, 6/8, 4/4, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| lead | `piano` | 12 | -17 | - |+| chords | `piano` | 12 | -30.3 | - |+| bass | `piano` | 6.3 | -23 | - |+| counter | `strings` | 2 | -30 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, aeolian, harmonicMinor, dorian. Qualities: triads, 7ths, secondary dominants, borrowed iv, Neapolitan for grief. Tendencies: descending bass lines, circle-of-fifths sequences, deceptive V-vi before the last cadence. Harmonic rhythm: one chord per bar, two at cadences. Voicing: left hand broken chords spanning a 10th, no close thirds below C3. Tension and release: suspensions (4-3, 9-8), appoggiaturas on strong beats.+- **Melody.** Range C4-C6. Contour: arch per phrase, peak about 2/3 through. Density: 0.5-2 notes per beat. Motif: a leap then stepwise return; transform it (octave up, in the bass) at the climax.+- **Arrangement.** intro -> theme (question, answer) -> build -> hush -> coda. Transitions: a breath (caesura) before a sudden hush. Endings: a rolled tonic into the pedal.+- **Grooves:** none. **Avoid:** octaves in both hands on one downbeat (peaks); a compressor.++## `minimalist`: minimalist / pulse++hypnotic, curious, clean: interlocking ostinatos that change slowly. Tempo 96-144 bpm, meters 4/4, 12/8, 5/4, 7/8, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| arp | `marimba` | -0.5 | -20 | piano (`piano`, -4 dB), pluck (`softPluck`, 3 dB) |+| lead | `marimba` | 3.1 | -17 | - |+| bass | `marimba` | -4.9 | -21 | - |+| counter | `vibes` | 3.7 | -27 | - |+| chords | `piano` | 4 | -37.1 | - |+| kick | `kick` | -6 | - | - |+| ghost | `snare` | -6 | - | - |+| perc | `hat` | 0 | - | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: dorian, lydian, aeolian, major, mixolydian. Qualities: open 5ths, add9, quartal stacks. Tendencies: a two-chord cycle for 8-16 bars, then one note changes. Harmonic rhythm: slow; the ostinato is the rhythm. Voicing: mid-register, interlocking; no doubled roots. Tension and release: phase shifts, added beats, a new bass note under the same pattern.+- **Melody.** Range C4-C6. Contour: cells, not tunes. Density: 2-4 onsets per beat in the ostinato. Motif: a 5-8 note cell; change ONE thing every 8-16 bars (add, drop, rotate).+- **Arrangement.** additive: one layer at a time. Transitions: a change at least every 16 bars. Endings: subtractive, or a hard stop.+- **Grooves:** pulse. **Avoid:** a big climax; a change more often than every 4 bars.++## `jazz`: jazz / swing++loose, warm, clever: swing ride, walking bass, comping piano. Tempo 80-200 bpm, meters 4/4, 3/4, swing 0.6-0.67.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `piano` | 8 | -32.5 | - |+| lead | `vibes` | 3.8 | -16 | piano (`piano`, 0 dB), clarinet (`woodwind`, 0 dB), flute (`woodwind`, 0 dB), brass (`brass`, -3 dB) |+| bass | `bass` | -1.3 | -18 | - |+| counter | `woodwind` | 8.5 | -21 | - |+| kick | `kick` | -0.2 | -24 | - |+| snare | `snare` | 0 | -26 | - |+| ghost | `snare` | 7.5 | -28 | - |+| hat | `hat` | 21 | -26 | - |+| perc | `hat` | 18 | -30 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, dorian, mixolydian, melodicMinor, blues. Qualities: 7ths required; 9ths, 13ths, altered dominants (7b9, 7#11). Tendencies: ii-V-I, iii-VI-ii-V turnarounds, tritone substitutions, backdoor bVII7-I. Harmonic rhythm: two chords a bar at turnarounds. Voicing: rootless shell voicings (3-7, 7-3) in the middle; the walking bass owns roots. Tension and release: altered dominants, chromatic approach chords; release on a 6/9 or maj7.+- **Melody.** Range A3-C6. Contour: bebop lines: chord tones on beats, approach notes between. Density: swung 8ths with rests. Motif: a riff restated over changing chords (the chords change under it).+- **Arrangement.** head (theme) -> solos -> head out. Transitions: a 2-bar break, trading 4s. Endings: a tag (the last 2 bars three times) or a ritard on a 6/9.+- **Grooves:** swing, brushes, shuffle. **Avoid:** straight 8ths, triads only.++## `lullaby`: lullaby++soft, rocking, safe. Tempo 56-78 bpm, meters 3/4, 6/8, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| lead | `celesta` | 5.3 | -17 | musicBox (`musicBox`, 0 dB), piano (`piano`, 0 dB), flute (`woodwind`, -2 dB) |+| arp | `harp` | 4 | -28.3 | - |+| bass | `harp` | 6 | -26 | - |+| counter | `musicBox` | 4 | -31.7 | - |+| chords | `strings` | -8.5 | -28 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, majorPentatonic, mixolydian. Qualities: triads, add9, sus2. Tendencies: I-IV-I rocking, plagal cadences, a gentle ii. Harmonic rhythm: one chord per bar. Voicing: close, mid-high. Tension and release: almost none; a minor lullaby is flagged for the human check (tips into eerie).+- **Melody.** Range C4-C6. Contour: rocking stepwise, falling phrase ends. Density: 1-2 notes per beat. Motif: a 2-bar rocking figure repeated with a changed ending.+- **Arrangement.** melody + gentle arpeggio, nothing percussive. Transitions: none needed. Endings: the tonic, soft, rolled.+- **Grooves:** none. **Avoid:** drums, surprise, bright highs.++## `chiptune`: chiptune++8-bit, bright, game-like: two pulses, a triangle, noise drums. Tempo 110-170 bpm, meters 4/4, 6/8, swing 0.5-0.56.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| lead | `pulse` | 7.4 | -16 | square (`pulse`, -2 dB) |+| arp | `pulse` | 7 | -23.1 | - |+| bass | `triangle` | 0.2 | -18 | - |+| kick | `noiseDrum` | 7.6 | -18 | - |+| snare | `noiseDrum` | 6.7 | -20 | - |+| hat | `noiseDrum` | -10 | -28 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, aeolian, dorian, mixolydian. Qualities: triads; chords are faked by fast arpeggios. Tendencies: I-vi-IV-V, i-bVI-bVII, key changes up a step. Harmonic rhythm: one chord per bar. Voicing: arpeggio 16ths across an octave. Tension and release: a held dominant arpeggio, a pitch-bend-free chromatic climb.+- **Melody.** Range C4-C7. Contour: hooky, leaping. Density: 8ths and 16ths. Motif: a 1-bar hook, answered, sequenced.+- **Arrangement.** 4 voices max: lead, arp, triangle bass, noise. Transitions: a drum fill, a key change. Endings: a fanfare button.+- **Grooves:** fourFloor, bounce, shuffle, skip. **Avoid:** reverb, more than 4 voices, pads.++## `lofi`: dusty lo-fi hip-hop++hazy, nostalgic, crackly: FM e-piano, vinyl, a lazy swung beat (the dusty cousin of lo-fi electronic). Tempo 68-90 bpm, meters 4/4, swing 0.55-0.62.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `ePiano` | 5.2 | -20 | - |+| lead | `ePiano` | 7.5 | -17 | guitar (`guitar`, 2 dB), flute (`woodwind`, -2 dB) |+| bass | `bass` | -2.1 | -19 | - |+| counter | `fmBell` | 4 | -30.1 | - |+| kick | `kick` | -2.6 | -17 | - |+| snare | `snare` | 6.2 | -22 | - |+| ghost | `snare` | 6 | -27.1 | - |+| hat | `hat` | 4 | -43 | - |+| perc | `hat` | 4 | -29 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, dorian, aeolian. Qualities: maj9, m9, 13, m11. Tendencies: 2-4 chord loops, ii-V drifts. Harmonic rhythm: 1-2 chords a bar. Voicing: e-piano 4-note voicings. Tension and release: a borrowed iv.+- **Melody.** Range C4-C6. Contour: lazy, behind the beat. Density: sparse. Motif: a 2-bar sampled-sounding phrase.+- **Arrangement.** 4 or 8 bar loop with variations. Transitions: a filter or a drop-out. Endings: fade or tape stop.+- **Grooves:** bounce, halfTime, shuffle. **Avoid:** using it when the brief says clean or upbeat (then use lofiElectronic).++## `orchestral`: orchestral / epic++big and heroic: brass theme, string ostinato engine, choir, timpani. Tempo 70-140 bpm, meters 4/4, 3/4, 6/8, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| lead | `brass` | 9.2 | -16 | strings (`strings`, 0 dB), horn (`brass`, -2 dB), flute (`woodwind`, -2 dB) |+| chords | `strings` | -0.4 | -19 | - |+| arp | `strings` | 4.4 | -20 | - |+| bass | `strings` | 0.9 | -19 | - |+| counter | `choir` | -1.7 | -22 | flute (`woodwind`, -3 dB), harp (`harp`, 0 dB) |+| perc | `timpani` | 4.2 | -17 | - |+| kick | `kick` | -3.3 | -17 | - |+| snare | `snare` | 5.2 | -24 | - |+| hat | `hat` | 4 | -32 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, aeolian, dorian, mixolydian, harmonicMinor. Qualities: triads and power 5ths, sus4 resolving, major IV in minor. Tendencies: i-bVI-bIII-bVII, I-bVII-IV-I (mixolydian heroism), chromatic mediants for arrivals, a pedal under the build. Harmonic rhythm: one chord per 1-2 bars, faster into cadences. Voicing: brass in the middle in 3rds and 5ths, strings octaves above, bass in octaves. Tension and release: a long dominant pedal with the ostinato rising, sus4 held; release to the tonic major with everything.+- **Melody.** Range brass G3-C5 (heroic), strings up to A6. Contour: a rising 4th or 5th then steps; big arcs. Density: long notes over a busy ostinato. Motif: a fanfare cell (rising 4th/5th + rhythm) developed: fragment it in the build, augment it at the climax.+- **Arrangement.** intro (ostinato alone) -> theme (strings) -> theme (brass) -> build -> tutti climax -> quiet coda. Transitions: timpani roll or snare build into downbeats; a bar of silence before the last statement. Endings: a big held chord with timpani, or a hard cut.+- **Grooves:** epic, build, tension, pulse. **Avoid:** all families at once all the time; a brass lead above C6.++## `suspense`: suspense / horror++unsettling, cold, withheld: low drones, heartbeat pulse, high bowed harmonics, stingers. Tempo 50-110 bpm, meters 4/4, 5/4, 3/4, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `strings` | -0.8 | -21 | - |+| bass | `sub` | -6.1 | -20 | - |+| lead | `bowedSolo` | 7.3 | -19 | choir (`choir`, -2 dB), cello (`bowedSolo`, 0 dB) |+| counter | `celesta` | 8 | -27 | choir (`choir`, -4 dB), bell (`fmBell`, -8 dB) |+| arp | `strings` | 2.7 | -22 | - |+| kick | `kick` | -3.4 | -17 | - |+| ghost | `snare` | -4 | -27 | - |+| perc | `timpani` | 8.4 | -18 | - |+| hat | `hat` | 0 | -32 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: phrygian, locrian, harmonicMinor, wholeTone, aeolian. Qualities: clusters, minor 2nds, tritones, minor-major 7th, augmented triads. Tendencies: a pedal that never resolves, chromatic crawl up or down by semitone, i-bII (phrygian), sudden major chord a tritone away. Harmonic rhythm: static: one sound for 4-8 bars, then a jolt. Voicing: very low and very high with an empty middle. Tension and release: withhold resolution; a stinger (all voices, one hit) on the scare; silence right before it.+- **Melody.** Range extremes: below C3 or above C6. Contour: a 2-3 note cell, often a semitone. Density: sparse, irregular. Motif: a semitone sigh or a tritone leap, repeated slower each time.+- **Arrangement.** drone -> pulse enters -> rising ostinato -> stinger on the hit -> silence -> aftermath drone. Transitions: cut to silence; a slow crescendo that stops short. Endings: unresolved: a held cluster, or a single low hit.+- **Grooves:** pulse, tension, epic. **Avoid:** a major cadence, melody in the middle register, busy drums.++## `rock`: rock / band++live-band energy: driven guitars, bass locked to the kick, a tight kit, maybe organ. Tempo 90-160 bpm, meters 4/4, 6/8, swing 0.5-0.52.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `strings` | -0.9 | -19 | organ (`organ`, -4 dB), piano (`piano`, -3 dB) |+| lead | `leadSynth` | 9.9 | -16 | guitar (`guitar`, 2 dB) |+| bass | `bass` | -0.8 | -17 | - |+| counter | `organ` | 6 | -30.4 | - |+| kick | `kick` | 1.2 | -13 | - |+| snare | `snare` | 11.2 | -17 | - |+| ghost | `snare` | 0 | -26 | - |+| hat | `hat` | 20.6 | -27 | - |+| perc | `hat` | 17 | -26 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: mixolydian, aeolian, major, blues, dorian. Qualities: power chords (root-5th-octave), triads, sus4. Tendencies: I-bVII-IV, i-bVI-bVII, riffs on the pentatonic, a chorus a 4th up. Harmonic rhythm: one chord per bar in verses, two in choruses. Voicing: power chords low (E2-E4), the bass doubling the root in 8ths. Tension and release: a riff held on the V, a stop before the chorus.+- **Melody.** Range E3-A5. Contour: riff-based, pentatonic, strong beats. Density: 8ths. Motif: a 1-2 bar riff that IS the song; the vocal-like lead answers it.+- **Arrangement.** riff intro -> verse -> pre -> chorus -> verse -> chorus -> bridge -> chorus x2. Transitions: a drum fill and a crash into every section. Endings: a big held last chord with a fill, or a stop on 1.+- **Grooves:** rock, halfTime, shuffle, fourFloor. **Avoid:** swing, soft attacks, long pads; the guitar tone here is an approximation: say so.++## `hipHop`: hip-hop / trap++head-nod or dark trap: heavy 808, crisp clap, rolling hats, a moody loop on top. Tempo 70-100 bpm, meters 4/4, swing 0.52-0.6.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| bass | `sub` | -2.5 | -15 | - |+| chords | `piano` | 6 | -36.8 | pad (`warmPad`, -3 dB) |+| lead | `softPluck` | 2.7 | -18 | bell (`fmBell`, -2 dB), flute (`woodwind`, -2 dB), choir (`choir`, -4 dB) |+| counter | `strings` | 4 | -29.2 | - |+| kick | `kick` | 1.4 | -13 | - |+| snare | `snare` | 10.2 | -18 | - |+| ghost | `snare` | 0 | -26 | - |+| hat | `hat` | 23.6 | -26 | - |+| perc | `hat` | 19.9 | -29 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: aeolian, phrygian, harmonicMinor, dorian. Qualities: minor triads, m7, dim, a single dark chord for 2 bars. Tendencies: 2-chord minor loops, i-bVI, i-bII (phrygian menace), a melody over one chord. Harmonic rhythm: one chord per 1-2 bars. Voicing: piano or bells high, the 808 low with nothing between. Tension and release: the 808 sliding or dropping out; a switch-up after 8 bars.+- **Melody.** Range C4-C6. Contour: short repeated figures. Density: sparse over busy hats. Motif: a 1-2 bar loop that repeats (the loop is the hook); vary it every 8 bars.+- **Arrangement.** intro (loop alone) -> 8-bar blocks with drops, switch-ups -> outro loop. Transitions: drop the drums for a bar, a hat roll into the downbeat. Endings: the loop alone, or a cut.+- **Grooves:** trap, bounce, halfTime, broken. **Avoid:** an 808 that owns everything below 150 Hz with no harmonics (phones): check stems.++## `house`: house / EDM++euphoric, dancing, bright: four-on-the-floor, offbeat bass, stabs, a big pad. Tempo 118-128 bpm, meters 4/4, swing 0.5-0.54.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `organ` | 5.2 | -21 | pad (`warmPad`, -3 dB), piano (`piano`, -3 dB) |+| bass | `bass` | 0.3 | -16 | - |+| lead | `softPluck` | 4.3 | -17 | synth (`leadSynth`, -2 dB) |+| counter | `warmPad` | 6.9 | -23 | - |+| arp | `softPluck` | 4.5 | -22 | - |+| kick | `kick` | 2.6 | -12 | - |+| snare | `snare` | 10.7 | -18 | - |+| ghost | `snare` | 1 | -26 | - |+| hat | `hat` | 12 | -26 | - |+| perc | `hat` | 18.3 | -27 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: aeolian, dorian, major, mixolydian. Qualities: m7, m9, maj7 stabs; piano house triads. Tendencies: i-VI-III-VII, vi-IV-I-V, 2-chord dorian vamps; a long pedal in the build. Harmonic rhythm: one chord per bar or per 2 bars; stabs on offbeats. Voicing: stabs mid-register, the bass on the offbeat 8th. Tension and release: filter build + snare build + one beat of silence; release = the drop.+- **Melody.** Range C4-C6. Contour: repetitive riffs. Density: 8ths and 16ths. Motif: a 1-bar riff repeated 4-8 times with one change.+- **Arrangement.** intro (kick + hats) -> groove -> breakdown (pad + motif) -> build -> drop -> outro (kick). Transitions: 16- or 32-bar blocks; builds of 8. Endings: DJ-friendly: strip back to kick and hats.+- **Grooves:** fourFloor, build, broken. **Avoid:** swing, busy harmony, a quiet drop.++## `synthwave`: synthwave / retro++neon-nostalgic, cinematic 80s: big gated snare, pulsing 8th bass, lush pads, a soaring lead. Tempo 80-118 bpm, meters 4/4, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `strings` | -2.1 | -21 | pad (`warmPad`, -2 dB) |+| bass | `bass` | -0.3 | -17 | - |+| lead | `leadSynth` | 11.7 | -16 | brass (`brass`, -2 dB) |+| arp | `softPluck` | 4.1 | -22 | - |+| counter | `fmBell` | 4 | -29.1 | - |+| kick | `kick` | 1.4 | -13 | - |+| snare | `snare` | 11.7 | -17 | - |+| ghost | `snare` | 0 | -26 | - |+| hat | `hat` | 12 | -28 | - |+| perc | `hat` | 16.2 | -29 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: aeolian, dorian, major, lydian. Qualities: minor triads, add9, maj7, sus2. Tendencies: i-bVI-bIII-bVII, vi-IV-I-V, a lydian II for the neon lift. Harmonic rhythm: one chord per bar. Voicing: wide pads, bass in driving 8ths on the root. Tension and release: a long build on the V with the arp rising; release with the gated snare.+- **Melody.** Range A3-E6. Contour: soaring, long notes with glide. Density: long lead notes over a busy arp. Motif: a 2-bar singable lead phrase, stated then lifted an octave.+- **Arrangement.** pad intro -> bass + drums -> lead theme -> breakdown -> lead an octave up -> outro pad. Transitions: a tom-like fill (build), a drop-out bar. Endings: the pad alone, long tail.+- **Grooves:** fourFloor, halfTime, rock, build. **Avoid:** trap hats, acoustic instruments, a dry mix.++## `world`: world / modal folk++rooted, spacious, rhythmic: a drone, a modal melody on plucked strings or a flute, hand percussion cycles (write your own melody; name the tradition you draw on). Tempo 60-150 bpm, meters 7/8, 9/8, 12/8, 6/8, 4/4, 5/4, swing 0.5-0.56.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| lead | `woodwind` | 8.7 | -16 | pluck (`guitar`, 2 dB), marimba (`marimba`, 1 dB), reed (`woodwind`, 0 dB), bowed (`bowedSolo`, 0 dB) |+| counter | `harp` | 10 | -38.1 | - |+| arp | `guitar` | 8 | -24.2 | - |+| chords | `warmPad` | -3.1 | -25 | - |+| bass | `sub` | -9.6 | -22 | - |+| kick | `timpani` | 0.3 | -17 | - |+| ghost | `snare` | 9.5 | -24 | - |+| perc | `hat` | 8 | -28 | - |+| hat | `hat` | 6 | -30 | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: dorian, phrygian, mixolydian, aeolian, majorPentatonic, minorPentatonic, harmonicMinor. Qualities: a drone (tonic + 5th) more than chords; modal colour chords sparingly. Tendencies: modal: stay on the tonic drone, move the melody through the mode; a second drone a step away for contrast. Harmonic rhythm: the percussion cycle carries it; harmony changes rarely. Voicing: open 5ths, the drone low and wide. Tension and release: the mode's colour note held against the drone; release on the tonic.+- **Melody.** Range a 10th around the drone. Contour: ornamented steps (grace notes, turns), phrases that return to the drone note. Density: flowing 8ths and 16ths with long held notes. Motif: a modal phrase that grows by adding ornaments on repeats.+- **Arrangement.** drone alone -> melody free -> percussion enters -> faster, denser -> return to the drone. Transitions: an accelerando, a percussion break. Endings: the melody alone on the tonic over the drone.+- **Grooves:** hand, pulse, brushes. **Avoid:** copying a traditional melody; Western functional cadences everywhere.++## `choral`: choral / sacred++vast, human, reverent: voices in parts, organ, bells, a slow swell. Tempo 50-90 bpm, meters 4/4, 3/4, swing 0.5-0.5.++| Slot | Voice | Gain dB | Stem target dB | Alternates (voice, gain dB, uncalibrated) |+|---|---|---|---|---|+| chords | `choir` | -9.9 | -19 | organ (`organ`, -4 dB), strings (`strings`, -4 dB) |+| lead | `choir` | -3.1 | -17 | bowed (`bowedSolo`, 0 dB), flute (`woodwind`, -2 dB) |+| bass | `organ` | 8 | -21 | - |+| counter | `fmBell` | 4 | -30.5 | - |+| arp | `harp` | 6 | -26.3 | - |+| perc | `timpani` | 5.5 | -20 | - |+| kick | `timpani` | -6 | - | - |++Stem targets: starting numbers from a neutral test signal (advisory until a human listens).++- **Harmony language.** Modes: major, aeolian, dorian, lydian. Qualities: triads in 4 parts, suspensions, the picardy third. Tendencies: chorale motion: I-IV-V-I, vi-IV-I-V, plagal amen (IV-I), deceptive V-vi before the final cadence. Harmonic rhythm: one chord per beat or per half bar (chorale), slower in swells. Voicing: SATB spacing: no gaps wider than an octave between upper voices, bass free; avoid parallel 5ths. Tension and release: 4-3 suspensions, a held dominant; release on a plagal amen.+- **Melody.** Range C4-G5 (singable). Contour: stepwise, phrase-shaped like breath. Density: 1 note per beat or slower. Motif: a hymn-like phrase whose cadence changes each time.+- **Arrangement.** a single voice -> full parts -> a swell -> a hush -> the final chord. Transitions: a fermata (breath) between phrases. Endings: a plagal amen or a picardy third, long tail.+- **Grooves:** pulse. **Avoid:** fast rhythms, drums, choir as a lead above G5.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/adapt-a-style.md b/plugins/anidoodle/skills/anidoodle/references/workflows/adapt-a-style.mdindex b584ceb..469cedc 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/adapt-a-style.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/adapt-a-style.md@@ -60,3 +60,22 @@ both times: charcoal and broken-colour for a watercolour, wren for a scrapbook.)|---|---|---|---|| a pastel watercolour backdrop (terminal UI excluded) | jagged-coast puddles, pooled rims, bare-paper rests, spatter, gouache sparkles | `adaptAquarelle.ts`, a moon jellyfish | `styles/house/pastel-blotch.json` || an explainer frame (Ritwika, f_10) | tidy torn pastel cards with soft shadows, typewriter, thin pen diagrams, one engraving | `adaptScrapbook.ts`, why sourdough rises | `styles/house/quiet-scrapbook.json` |+| Van Gogh, *Almond Blossom* (1890, public domain) | short loaded oil strokes in turning patches, a broken blue-green contour laid last, thick ridged whites | `adaptAlmond.ts`, the launch film's koi in its pond | `styles/house/almond-blossom.json` |++## A MEDIUM RECIPE, filled in (the almond proof)++The analyzer's nearest plates were charcoal and storybook; by eye it was `paintedOil`, so the+plate reuses the painted-oil kit and changes the mark. The recipe, as written in the plate's+header before any code:++- **MARK**: opaque oil, a loaded bristle brush, strokes about a finger long. The ground is laid in+ small patches of strokes sharing a direction, the patches turning against each other. Forms are+ painted along their length. Lights are thick and ridged.+- **EDGE**: hard. A dark blue-green contour laid last with a small round brush, broken, heavier on+ the shadow side. Nothing blended across an edge.+- **ORDER**: the ground everywhere; forms in their mid tone; lights; the contour; the last whites.+- **PAPER**: primed linen, the weave showing through the thinner ground strokes.+- **PALETTE**: a narrow, high-key turquoise ground; sage for forms; cream and lead white; one+ vermilion; no black anywhere (the darkest note is the contour).+- **NOT**: `paintedOil` models form in depth; this hand keeps the ground flat and decorative with+ one step of shadow. The subject is the film's own koi, never the painting's branch.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video-kit.md b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video-kit.mdnew file mode 100644index 0000000..ed79ce4--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video-kit.md@@ -0,0 +1,115 @@+# The launch kit: build your product's launch film++The pieces anidoodle's own launch film is made of, in `engine/src/canvas-core/`, usable for any+product. The rules they serve are in `launch-video.md`.++## Start from the template (16 s, one file)++`launchTemplate.ts` turns data into a film: two or three prompts answered by plates drawing+themselves in a chat thread, a type frame between them, and an end card with your install lines.+`launchExample.ts` is a complete one for a made-up product. Copy its shape, not its contents:+the plates and the score are the product's own, made for its brief.++```ts+import { C } from "./launchKit";+import { makeLaunchFilm } from "./launchTemplate";+import { dashboardSketch, onboardingSketch } from "./myProductPlates"; // drawn for YOUR subject+import { myProductScore } from "./myProductScore"; // composed for YOUR brief++export const myLaunch = makeLaunchFilm({+ title: "Your Product", subtitle: "the one line it lives by",+ asks: [+ { prompt: "sketch my dashboard, as a print", plate: dashboardSketch, label: "print · drawn in code" },+ { prompt: "now the onboarding screen", plate: onboardingSketch, label: "a second answer, same thread" },+ ],+ words: [[{ text: "IDEA IN.", style: "ink", color: C.ink }, { text: "ART OUT.", style: "ink", color: C.accent }]],+ tagline: "One sentence that says what it is",+ install: ["npm install your-product", "your-product init"],+ bpm: 96, // the tempo of the score you composed; the brief sets it, there is no default+ askBeats: 6, typeBeats: 4, endBeats: 8, claimBar: 4,+ score: myProductScore, // or null for a silent film+});+```++Add `src/hosts/page-myLaunch.ts` (three lines, copy `page-launchExample.ts`), then:++```bash+node tools/still.mjs myLaunch --frame 0 --out out/poster.png # the first frame is the thumbnail+node tools/render.mjs myLaunch+node tools/gate.mjs myLaunch+node tools/verify-export.mjs myLaunch --file out/myLaunch.mp4+```++What you get: the first prompt already being typed at frame 0 in a close-up (a hook that reads+muted), the camera easing out for the press, an ink drop arcing from Generate into the thread+and blooming open into a card where the plate draws itself live, the thread keeping earlier+answers and scrolling, a gentle lean onto each new card, full-frame word pages between asks,+and the end card blooming open and holding. The corner mark (your name, hand-lettered) steps+aside before any lean. Real holds are declared, so the gate passes; the score is set to -14+LUFS with the true peak at or under -1 dBTP (`musicBed`; a very dynamic piece stops at the+peak ceiling first).++**The plates and the score are made for this product, every time.** A style is a recipe applied+to the user's subject (`references/styles.md`): draw their dashboard, their mascot, their+product's world in the chosen hand, as a still plus its `*Draw` film. anidoodle's own plates+(the lighthouse and fox in `launchExample.ts`) are placeholders, never a user's film. The score+is composed for the brief's style, mood and length (`references/music/compose.md`); `score` is+required (`null` means silent), `bpm` has no default, and the template refuses anidoodle's own+pieces, by identity and by title.++| Spec field | Meaning |+|---|---|+| `title`, `subtitle`, `placeholder`, `genLabel`, `accent` | the chat's name, subline, empty text, button word, button colour |+| `asks[]` | 1-3 of `{ prompt, plate, label, from?, to?, crop? }` |+| `words[i]` | the type frame after `asks[i]` (not after the last ask; it flows into the end card) |+| `tagline`, `install[]`, `footer` | the end card; install lines are shown exactly as given |+| `bpm` (required), `fps`, `askBeats`, `typeBeats`, `endBeats` | the beat grid (a beat is 60 x fps / bpm frames) and each part's length in beats |+| `claimBar` | land the end card on this bar's downbeat; throws if it cannot |+| `score` (required) or `audio` | a piece composed for this product, as a bed; `null` for silence; or your own finished mix |++The template refuses a feature list (more than 3 asks) and an end card too short to read.++## The parts, for a film of your own shape++**`launchKit.ts`**: timing and UI.+- Easing: `ramp`, `inOut`, `out3`, `in3`, `expo`, a closed-form `spring`, `press` (a button+ press that dips and springs back). Camera: `Cam`, `camLerp` (zoom travels in log space),+ `useCam`, `toScreen`. For longer camera work use `references/camera.md`.+- `plateLayer(env, key, film, frame, px)`: draw ANY film of this engine into an offscreen layer+ at any frame. This is composition without recordings: every plate in a launch film is the real+ plate drawn live by its own code. `selfLayer` is a scratch surface for a scene inside a scene.+- The chat: `drawChatFrame(ctx, state)` (window, composer, Generate; `title`, `subtitle`,+ `genLabel`, `accent` are yours), `charTimes`/`typedAt` (human typing), `caretAt`, `pointer`,+ `inkDrop` (the drop from the button to the card), `inkCard` (the answer card that blooms+ open), `artCard`, `softShadow`, `rr`.+- The ink: `blot(c, R, seed)` and `pathOf`, a seeded wobbling rim for blooms and drops.++**`kinetic.ts`**: lettering that is written, never set.+- `writeOn(ctx, env, text, x, y, size, p, style, opts)`: a line written stroke by stroke by a+ visible tool, in `ink`, `crayon`, `thread`, `chalk`, `brick` or `marker`. `measure` sizes it.+- `sentence` (one medium per word, one word per beat), `caption` (a small callout with an+ underline or arrow), `logo`/`logoCentred` and `logoBug` (anidoodle's own wordmark and corner+ mark; for your product, write your name with `writeOn` as the template does).++**`launchCut.ts`**: the cut as data.+- `pic(from, to, len)` plays a span of your content timeline over `len` frames; `type(lines,+ len, before, after)` is a word page. `makeCut(segs)` gives `N`, `at(F)`, `contentOf`, `cutOf`+ (map content-frame sound events onto the cut).+- `beatGrid(bpm, fps)`: `beat`, `bar`, `frameOf(bar, beat)`, and `solve(bar, fixed)`, the frames+ left for one flexible segment so the claim lands on a bar (launch3 lands on bar 26).+- `bloomFrame` (a page inside an ink bloom; `close: false` keeps it open for an end card),+ `typeFrame` (one to three lines written on it; `lead`, `stagger`), `bloomRadius` (for holds).++**`launchGallery.ts`**: `drawWall` and `wallCam`, a rolling wall of style cards where the+focus card GROWS toward the viewer instead of the camera zooming. The proof-of-range beat.++**`webTour.ts`**: a website drawn in code and toured: the whole page first, then the camera+zooms to each click, with the pointer and input log driving the page's own state.++## Worked example++`launch2.ts` is anidoodle's content timeline (chat, koi with its code streaming, the wall, the+brick balloon, the almond hand, the embroidery loop, the web tour, the butterfly film, the end+card); `launch3.ts` is the cut: data segments spliced with type frames, 77 s on the score's 29+bars. Study them for pacing, then build yours on the template with your own pictures and your+own music; anidoodle's launch is one example of the grammar, not a skin to reuse.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.mdindex 10b8335..3e7f46f 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/launch-video.md@@ -1,59 +1,126 @@# Launch and product videosA launch video makes one promise about a product and shows it being kept. It is a short film-with a job: the viewer should know what the thing is, why it matters to them, and where to get-it, in that order.+with a job: in the first seconds the viewer knows what the thing is, by the end they know where+to get it. Every rule below was paid for on anidoodle's own 77 s launch film (four cuts) and+checked against published launch-video craft. The reusable pieces are in `launch-video-kit.md`;+a template film renders a 16 s launch for any product from data.## Inputs the person brings-Product screenshots, a logo, UI captures, a repo link, a feature list. Images they bring may be-embedded (pinned by sha256, provenance recorded in the film's manifest); everything around them-is drawn in code. Never generate or fetch images.+Product screenshots, a logo, UI captures, a repo link, a feature list, the exact install or+sign-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.## Ground it in the real product firstBefore any storyboarding, write a short sourced brief and get ONE approval on it. A launch film-that invents its subject draws a mascot of a product, not the product. Keep it light: one brief,-one look approval, then build.--1. **Read the real thing.** Open what exists: the screenshots and captures they brought, the- repo's README and UI components, the live page. Note the two or three REAL features a viewer- should recognise on screen, the exact product name and mark, and the brand colours as hex.-2. **Collect approved claims.** The one-line promise and any numbers come from the person's own- materials (site copy, release notes, the README), each with its source written next to it.- Anything you cannot source becomes a question, not a line in the film. Write the claims the- film must NOT make while you are at it.-3. **Ask the grounding questions**, one message: which real features to show (pick from the- list you found, recommend your three), which shapes to ship (`9x16`, `16x9`, `1x1`), text- treatment (drawn kinetic type, their UI captures, or both), and where it will run.-4. **Write the brief** where the film's files will live: product and promise, the chosen- features with their sources, brand colours mapped onto the style's palette roles, the- approved claims and the banned ones, the shapes. The storyboard and every caption then quote- the brief, never memory.--The film still opens with a drawn hook, not a feature list: the brief decides WHAT the film may-claim and show, never how it moves.--## Shape of the film--1. **Hook in the first two seconds**: the problem, drawn being made (a tangle, a pile, a clock),- never a fade from black.-2. **The turn**: the product arrives. A screenshot slides in on a drawn device frame, or the- UI is redrawn in the chosen hand.-3. **Three proofs at most**: each feature shown doing something, one per beat group, with a short- drawn caption.-4. **The payoff and the call**: the product name drawn on, the one-line promise, where to get it.- Hold it long enough to read twice.--Length follows the content: 15 s for a social teaser, 30-60 s for a launch post, longer for a-walkthrough (then use chapters, `long-film.md`). Ship the shapes where it will run: `9x16` for-Reels/Shorts, `16x9` for YouTube and the site, `1x1` for feeds.--## Craft notes--- **Kinetic type is lettering**, stroke-drawn in the chosen hand, timed to the beat grid.-- **Screenshots are content, not decoration**: large enough to read on a phone, framed, with the- part that matters called out by a drawn circle or arrow in the style's hand.-- **Music**: a style that matches the brand (drive/electronic for energy, minimalist mallets for- calm confidence, lo-fi for friendly), with the product reveal on a true sync point.-- **Brand colours** map onto the style's palette roles; the style's hand stays intact.+that invents its subject draws a mascot of a product, not the product.++1. **Read the real thing.** The screenshots and captures they brought, the repo's README and UI+ components, the live page. Note the two or three REAL features a viewer should recognise on+ screen, the exact product name and mark, the brand colours as hex.+2. **Collect approved claims.** The one-line promise and any numbers come from their own+ materials (site copy, release notes, README), each with its source next to it. Anything you+ cannot source becomes a question, not a line in the film. List the claims the film must NOT make.+3. **Ask the grounding questions**, one message: which features to show (recommend your three),+ which shapes to ship, where it will run, the exact CTA lines.+4. **Write the brief** where the film's files live: product and promise, features with sources,+ brand colours mapped onto palette roles, approved and banned claims, shapes, platforms. The+ storyboard and every word on screen quote the brief, never memory.++## Made for this product, every frame and every note++The film's pictures are drawn for this product's subject in the style recipe the brief picked+(`references/styles.md`); its score is composed for this brief. anidoodle's own plates and+pieces are examples of the craft, never material for someone else's film.++## The story++- **One sentence the film proves**, written before anything else. anidoodle's: "you can create+ images, illustrations, loops, animations and films in pure code." Every beat serves it. A row+ of features is a spec sheet, not a story.+- **Told from the user's point of view**: they type, press the button, the result appears. The+ viewer should picture themselves doing it.+- **Say what it is in the first five seconds** (anidoodle: "no image model, just code" by 10 s at+ the latest). The hook lands inside 2-3 s and reads with the sound OFF: feeds autoplay muted.+- **Arc**: hook, one core interaction, a fast proof of range (a wall, never a slow tour), the+ brand 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.++## Type++- **Words NEVER sit over the art or the UI.** A word gets its own full frame: an ink bloom+ opens, a brush writes the word, the bloom closes on the next scene (`typeFrame`). Corner marks+ step aside when the camera brings UI under them.+- **3-7 words a frame, few frames.** Collapse word cards into one claim then proof ("JUST CODE."+ then "31 STYLES"); fewer cards leave more time for the proof.+- **Hold each settled word 0.5 s or more**, longer for the claim.+- **Judge DESIGN in review stills, not only collisions**: hierarchy, spacing, whether the frame+ would pass as a poster. A frame with nothing overlapping can still be ugly.++## Motion++- **Every transition is a gentle move**: bloom, card flip, push, the card GROWS into the frame.+ Never a hard cut, never a sharp swoosh. Ease in and out; the camera is `references/camera.md`.+- **Drawings play 3-6x faster than real time**; a loop is held long enough to see it loop.+- **Alive means real motion**: the koi swims through a scrolling world, not an in-place GIF+ (`start-here.md`, "Alive means real motion").+- **Chat is a real thread**: the request appears BEFORE its result, earlier answers stay, the+ thread scrolls, a follow-up animates in the existing card instead of popping a new one.+- **Web**: show the whole site first, then zoom to each click; the site's copy describes what+ the viewer is seeing.+- Banned defaults: a centred title on a gradient, everything fading in, bouncy easing, particle+ bursts, glow on UI chrome, dead time, text scaled into blur.++## Brand and the end card++- **The logo recurs**: a small corner mark on every frame (`logoBug`), not once at the start.+- **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:+ `/plugin marketplace add alexgreensh/anidoodle` and+ `/plugin install anidoodle@alexgreensh-anidoodle`. One primary call; the link smaller below.++## Sound++- **Music first, heard as an mp3 by a human** before it scores anything (you cannot hear it).+ Compose 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 own+ launch chose chill lo-fi electronic, one example (`references/music/styles/lofi-electronic.md`);+ never reuse our score or a stock piece.+- **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.+- **Sound effects only on real direction changes**: one riser into the big reveal, one impact,+ never a whoosh on every cut (`references/music/sound-design.md`).+- **Master to -14 LUFS integrated, true peak -1 dBTP or lower**, then listen on a phone speaker.++## 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).+- **Shapes**: `16x9` for YouTube and the site, `1x1` or `4x5` for feeds, `9x16` for Reels and+ Shorts. Reframe per shape from one timeline; never crop a wide render.+- **The first frame is the thumbnail.** Platforms and players show frame 1 before play. Make+ it legible and on brand (anidoodle's is the wall of styles; the template's is the prompt, big,+ mid-sentence); never a blank, a fade from black, or a whole chat window too small to read.++## 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.+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.+5. **Music as an mp3 on a page**, heard by a human. ✋ Approval.+6. **Cut as data**: content scenes on one timeline, the cut as `pic`/`type` segments on the+ beat grid (`launchCut.ts`). Re-timing edits the list, never scene code.+7. **Review from the render**: contact sheets per beat, cuts as before/after pairs, DESIGN+ first (type over art, spacing, hierarchy), then timing. Render only the changed range+ (`render.mjs --from F --to F`). Give notes in camera words ("slow this zoom to 0.7x",+ "hold the word 10 frames longer"), never "make it better".+8. **QA**: `gate.mjs <film>` (determinism, contract, dead air; declare real holds in+ `meta.holds`) and `verify-export.mjs <film> --file <mp4> --first-frame #rrggbb` for EVERY+ shape shipped; meter the mix. Keep the review page updated as work lands.+9. ✋ **Final approval** on the finished file.diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.md b/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.mdindex 26ba806..cf0e5bd 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/start-here.md@@ -47,3 +47,27 @@ Stop asking the moment you can build. Two questions answered well beat six askedOne short brief file in the project: kind, style (and why), shape(s), length, sound (style +moods), characters, the one-sentence idea. Everything the person said goes in their words.Everything you decided is marked as yours so they can veto it in one line.++## Before the first full render++- **Show options as one still sheet** when a choice is open (a transition, a lettering medium,+ a palette): three to six variants side by side, picked in one message. Then render.+- **Review stills for design**, not only for things overlapping (`references/craft-bar.md`).++## Alive means real motion++When someone asks for a subject to be "alive", "swimming" or "moving", an in-place loop reads as+a GIF. The subject travels through a world that changes as it moves, and the camera follows.+The worked example is the koi: `koi.ts` takes an optional `KoiLive` (time, amplitude, a pose on+a path) and `koiWorld.ts` swims it through a pond much bigger than the frame, sliding under pads+that are placed in the world, its wake spreading from its nose.++The pattern:+1. **Add motion as an optional input** to the subject's drawing function (`live?: KoiLive`).+ With it absent, the code path is the still, untouched.+2. **Guard the still**: render the still plate before and after with `still.mjs` and compare+ the md5 it prints. The still must stay pixel-identical; if it moves, the refactor leaked.+3. **Place the world in world units**, not screen units, so the scenery changes as the subject+ moves; let the camera follow (`references/camera.md`).+4. **Frame 0 of the living version equals the still** (same pose, same framing), so a film can+ hand over from the still card to the living one without a seam.diff --git a/plugins/anidoodle/skills/anidoodle/references/working-method.md b/plugins/anidoodle/skills/anidoodle/references/working-method.mdindex c551219..48c7c8d 100644--- a/plugins/anidoodle/skills/anidoodle/references/working-method.md+++ b/plugins/anidoodle/skills/anidoodle/references/working-method.md@@ -40,3 +40,30 @@ Do not push through. Reset:4. **The fresh session verifies before it trusts.** Read the files, check the disk, say what disagrees with the briefing. (Ours found that the "already built" camera was not in the source, in the first five minutes.)A reset cost us about ten minutes because the state was in files. It would have cost the project if the state had been in the conversation. And when a message arrives truncated, look for the full text in the session transcript before you guess; twice the missing half changed the job.++---++## Spend tokens and time where they buy something++The launch film cost 188M tokens, about 99% of them cache re-reads of one 750k-token context.+None of that was drawing. These habits cut it by an order of magnitude:++- **One session per cut, with a handover file.** When a cut is done, write the state (what+ exists, the rules the person gave, what is open, where files live) and start the next cut in a+ fresh session that reads it. A long session re-reads its whole history on every turn.+- **Briefed helpers, never context-inheriting forks.** A helper gets a short written brief and+ the few files it needs. A fork inherits the whole conversation and pays for it on every call.+- **Contact sheets at 0.3-0.5 scale** for review (`ffmpeg -vf "fps=1,scale=576:-1,tile=4x4"`),+ full size only for the crop a sheet raised a doubt about. Never re-read a big image you have+ already judged.+- **Options sheet before any full render.** Transitions, type styles, palettes: one still+ sheet with three to six variants side by side, picked in one message.+- **Timelines as data.** Scenes on one content timeline, the cut as a list of segments+ (`launchCut.ts`). Re-timing edits the list; scene code and its reviews stay valid.+- **Range renders.** `render.mjs <film> --from F --to F` renders only the passage you changed+ (it writes `out/<film>.<from>-<to>.mp4`, never over the finished film).+<!-- TODO(A): confirm the still.mjs multi-frame flag and the plate cache name/location once they land on integ/launch-kit -->+- **Many stills, one browser.** `still.mjs <film> --frames a,b,c` draws several frames in one+ page; one browser per still costs seconds each.+- **Plate cache.** Baked plates are cached on disk, so a wall of 31 live plates stops+ re-baking (about 60 s) on every still.diff --git a/skills/anidoodle/SKILL.md b/skills/anidoodle/SKILL.mdindex d1cd2a4..57fa00d 100644--- a/skills/anidoodle/SKILL.md+++ b/skills/anidoodle/SKILL.md@@ -42,8 +42,7 @@ say why in one line. Write the answers into a short brief before drawing.| A style matched from their image | `references/workflows/adapt-a-style.md` || A score or soundtrack | `references/music/README.md` |-<!-- KITS: one line each from the music (B) and sound (C) tracks; keep this block short -->-- Music, lo-fi electronic (chill, upbeat, clean; no ePiano): lofiElectronic() in engine/src/canvas-core/music; balance with node tools/music.mjs stems <piece> before mastering. See references/music/styles/lofi-electronic.md.+- Music: pick a style vocabulary and mood, compose your own harmony, motif and form (references/music/compose.md), then node tools/music.mjs check <score.ts#export> 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.- Launch films: `launchTemplate.ts` renders a product's launch from data: prompts, plates drawn for it, a score composed for it, words, install lines; habits that save tokens are in `references/working-method.md`.