Skip to content

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

music: composer fixes from the blind run - loopLines + short-line warnings, levels as a dB offset, section energy shapes dynamics of every part, per-section key (modulation), key check accepts a heard tonic (and no longer accepts a wrong tonic), written grooves cycle per section, timpani tuned to the key, lead headroom in the stem meter, guards use the real meter

Alex Greenshpun46f5fc584829
diff --git a/skills/anidoodle/engine/src/canvas-core/music/calibration.ts b/skills/anidoodle/engine/src/canvas-core/music/calibration.ts
index 9189c89..45183e2 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/calibration.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/calibration.ts
@@ -2,18 +2,18 @@
// 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 } from "./theory";
+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 } = {}): Material => {
- const 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) + iv[((d % 7) + 7) % 7] + 12 * Math.floor(d / 7), unit = comp ? "1/3" : ".5", count = Math.round(bpb * (comp ? 3 : 2));
+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: "C", mode, meter, chords, loop: o.loop,
+ 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)) } : {}),
diff --git a/skills/anidoodle/engine/src/canvas-core/music/compose.ts b/skills/anidoodle/engine/src/canvas-core/music/compose.ts
index 6ba61fd..07b0612 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/compose.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/compose.ts
@@ -5,7 +5,8 @@
// 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 } from "./tables";
+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";
@@ -19,11 +20,14 @@ 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, scales generated groove density in this section */ energy?: 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 = {
@@ -31,8 +35,11 @@ export type Material = {
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>>;
- /** gainDb per slot, after measuring stems */ levels?: Partial<Record<Slot, number>>;
- moodControls?: MoodControls; swing?: number; dyn?: [number, number]; tail?: number; loop?: boolean;
+ /** 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).`); };
@@ -89,13 +96,22 @@ export const composePiece = (m: Material): Piece => {
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;
- const ns = line(x.from * bpb, lineOf(spec), { role: role(slot), v: vel[slot], bpb });
+ 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)];
@@ -109,20 +125,28 @@ export const composePiece = (m: Material): Piece => {
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, gainDb = lv !== undefined ? lv : trim ? v.gainDb + trim : v.gainDb;
+ 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, dyn = m.dyn ?? [0.62, 0.66];
+ 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: [{ id: "a", bars: B, mood: m.mood, key: m.key, mode: m.mode, melody: ["stepwise", "hook"], dyn: mood ? [dyn[0] + e * 0.2, dyn[1] + e * 0.2] : dyn, ending: "tail", repeatable: false }] },
+ 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 })),
- refit: m.loop ? undefined : (seconds: number) => composePiece(refitMaterial(m, seconds)),
+ warnings, refit: m.loop ? undefined : (seconds: number) => composePiece(refitMaterial(m, seconds)),
};
return piece;
};
diff --git a/skills/anidoodle/engine/src/canvas-core/music/grooves.ts b/skills/anidoodle/engine/src/canvas-core/music/grooves.ts
index 66b597a..c6b5ff9 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/grooves.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/grooves.ts
@@ -13,7 +13,9 @@ export type GrooveFamily = "bounce" | "fourFloor" | "halfTime" | "broken" | "shu
/** 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. */
-export type LiteralGroove = { kick?: string[]; snare?: string[]; ghost?: string[]; hat?: string[]; perc?: string[] };
+/** 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>>;
@@ -179,6 +181,6 @@ 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 pick = (xs?: string[]) => (xs && xs.length ? xs[abs % xs.length] || null : null);
+ 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/skills/anidoodle/engine/src/canvas-core/music/guards.ts b/skills/anidoodle/engine/src/canvas-core/music/guards.ts
index a34ffeb..be75780 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/guards.ts
+++ b/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; te
const 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/skills/anidoodle/engine/src/canvas-core/music/meter.ts b/skills/anidoodle/engine/src/canvas-core/music/meter.ts
index 69671e9..9581955 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/meter.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/meter.ts
@@ -112,7 +112,9 @@ export type StemRow = { id: string; rmsDb: number; targetDb: number | null; offD
* 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.
*/
-export const stemBalance = (stems: Record<string, [Float32Array, Float32Array]>, targets: Record<string, number>, tolDb = 3) => {
- 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 || Math.abs(off) <= tolDb }; });
- return { rows, pass: rows.every((r) => r.ok), tolDb };
+/** 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/skills/anidoodle/engine/src/canvas-core/music/pieces/copyFixture.ts b/skills/anidoodle/engine/src/canvas-core/music/pieces/copyFixture.ts
index 4f08574..258b9ff 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/pieces/copyFixture.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/pieces/copyFixture.ts
@@ -18,8 +18,8 @@ export const daylightCopyMaterial = (): Material => ({
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] },
- half: { kick: ["C4:2 r:2"], snare: ["r:2 C4:2"], hat: ["C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]"] },
+ 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 },
diff --git a/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts b/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
index acbacd5..d393837 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/pieces/launch.ts
@@ -79,8 +79,8 @@ export const launchLofi3Material = (): Material => {
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] },
- half: { kick: ["C4:2 r:2"], snare: ["r:2 C4:2"], hat: ["C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]"] },
+ 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 },
diff --git a/skills/anidoodle/engine/src/canvas-core/music/plan.ts b/skills/anidoodle/engine/src/canvas-core/music/plan.ts
index ba16107..6b911a0 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/plan.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/plan.ts
@@ -1,7 +1,7 @@
// 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 = "2/4" | "3/4" | "4/4" | "5/4" | "6/8" | "7/8" | "9/8" | "12/8";
@@ -31,6 +31,7 @@ export type PieceFx = { clean?: boolean /* skip the lo-fi master tone (low-pass,
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;
/** 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 }[] };
@@ -74,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/skills/anidoodle/engine/src/canvas-core/music/theory.ts b/skills/anidoodle/engine/src/canvas-core/music/theory.ts
index d380aa3..801378e 100644
--- a/skills/anidoodle/engine/src/canvas-core/music/theory.ts
+++ b/skills/anidoodle/engine/src/canvas-core/music/theory.ts
@@ -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 };
+};