Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

Bestiary mode: physical creature voices (songbird, Weddell seal, alligator, elephant)

Jameson Hodgea8ee6aa1972c
diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.ts
index c94267f..bcdd92b 100644
--- a/src/audio/AudioEngine.ts
+++ b/src/audio/AudioEngine.ts
@@ -3,7 +3,7 @@
* parameter messages (at most one per animation frame per kind) and telemetry fan-out.
*/
import workletUrl from "../worklet/processor.ts?worker&url";
-import type { ToWorklet, FromWorklet, TelemetryMessage, BodyName, PlannedMessage } from "../worklet/protocol.ts";
+import type { ToWorklet, FromWorklet, TelemetryMessage, BodyName, PlannedMessage, CreatureTelemetryMessage } from "../worklet/protocol.ts";
import type { HumanArtic } from "../engine/anatomy/human.ts";
import type { VoiceSource } from "../engine/voice/humanVoice.ts";
@@ -13,13 +13,21 @@ export class AudioEngine {
ctx: AudioContext | null = null;
private node: AudioWorkletNode | null = null;
analyser: AnalyserNode | null = null;
+ /** unsmoothed, short-window analyser for the spectrogram */
+ analyserFast: AnalyserNode | null = null;
+ /** long time-domain window for the waveform scope */
+ analyserScope: AnalyserNode | null = null;
private master: GainNode | null = null;
latest: TelemetryMessage | null = null;
+ latestCreature: CreatureTelemetryMessage | null = null;
+ /** load of the most recent telemetry of either kind */
+ load = 0;
sampleRate = 48000;
private listeners = new Set<Listener>();
private pendingArtic: Partial<HumanArtic> | null = null;
private pendingTipFree: boolean | undefined;
private pendingSource: Partial<VoiceSource> | null = null;
+ private pendingCParams: Record<string, number> | null = null;
private flushScheduled = false;
private readyListeners = new Set<() => void>();
private plannedListeners = new Set<(p: PlannedMessage) => void>();
@@ -50,14 +58,29 @@ export class AudioEngine {
analyser.fftSize = 4096;
analyser.smoothingTimeConstant = 0.6;
this.analyser = analyser;
+ const fast = ctx.createAnalyser();
+ fast.fftSize = 2048;
+ fast.smoothingTimeConstant = 0;
+ this.analyserFast = fast;
+ const scope = ctx.createAnalyser();
+ scope.fftSize = 16384;
+ this.analyserScope = scope;
node.connect(master);
master.connect(ctx.destination);
master.connect(analyser);
+ master.connect(fast);
+ master.connect(scope);
node.port.onmessage = (e: MessageEvent<FromWorklet>) => {
const m = e.data;
if (m.type === "telemetry") {
this.latest = m;
+ this.latestCreature = null;
+ this.load = m.load;
for (const l of this.listeners) l(m);
+ } else if (m.type === "ctelemetry") {
+ this.latestCreature = m;
+ this.latest = null;
+ this.load = m.load;
} else if (m.type === "planned") {
this.lastPlan = m;
for (const l of this.plannedListeners) l(m);
@@ -88,6 +111,26 @@ export class AudioEngine {
return id;
}
+ /** Switch voice ("human" or a creature id), starting the creature from the given settings. */
+ setCreature(id: string, params?: Record<string, number>): void {
+ // settings still waiting for the next frame belong to the previous creature
+ this.pendingCParams = null;
+ this.send({ type: "creature", id, params });
+ }
+
+ setCreatureParams(values: Record<string, number>): void {
+ this.pendingCParams = { ...(this.pendingCParams ?? {}), ...values };
+ this.scheduleFlush();
+ }
+
+ playCall(id: string, pitch?: number, amp?: number): void {
+ this.send({ type: "call", id, pitch, amp });
+ }
+
+ stopCall(): void {
+ this.send({ type: "stopCall" });
+ }
+
stopSpeech(): void {
this.send({ type: "stopSpeech" });
}
@@ -139,6 +182,10 @@ export class AudioEngine {
this.send({ type: "source", values: this.pendingSource });
this.pendingSource = null;
}
+ if (this.pendingCParams) {
+ this.send({ type: "cparams", values: this.pendingCParams });
+ this.pendingCParams = null;
+ }
};
if (typeof requestAnimationFrame === "function") requestAnimationFrame(flush);
else setTimeout(flush, 16);
diff --git a/src/engine/creatures/alligator.ts b/src/engine/creatures/alligator.ts
new file mode 100644
index 0000000..1c2d5ac
--- /dev/null
+++ b/src/engine/creatures/alligator.ts
@@ -0,0 +1,80 @@
+/**
+ * American alligator: bellows are noisy and chaotic with most power far below 100 Hz; the body
+ * vibrates the water into a "dance" before the audible roar. Chaotic laryngeal source, long tract,
+ * closed mouth (sound leaves through nostrils and skin).
+ */
+import type { CreatureDef, CreatureSim } from "./types.ts";
+import { mammalAirway, stepGlottis, mammalNoise } from "./mammal.ts";
+import { fillAreas, CMH2O } from "./build.ts";
+
+function create(fs: number): CreatureSim {
+ const a = mammalAirway(fs, { trachea: [30, 6], pharynx: [18, 7], oral: [24, 6], nasal: [26, 1.8], wallRadiation: 1.0, coarse: 1.3 });
+ const g = a.glottisSrc;
+ g.threshold = 1.5 * CMH2O;
+ return {
+ net: a.net,
+ tubes: { trachea: a.trachea, pharynx: a.pharynx, oral: a.oral, nasal: a.nasal! },
+ gain: 2.8e-7,
+ control(p, gate) {
+ a.net.setFixedPressure(a.lungs, p.pressure * CMH2O * gate);
+ g.params.f0 = p.pitch;
+ g.params.amplitude = 0.9 * (1 - p.hiss);
+ g.params.abduction = 0.02 + 0.8 * p.hiss;
+ g.params.openQuotient = 0.5;
+ g.params.closureSharpness = 0.8;
+ g.params.effort = 1;
+ g.params.chaos = p.chaos;
+ g.params.jitter = 0.01 + 0.05 * p.chaos;
+ g.params.shimmer = 0.05 + 0.25 * p.chaos;
+ g.params.drift = 8;
+ a.net.setTubeTargets(a.pharynx, fillAreas(a.pharynx, () => 7, a.pharArea));
+ const m = p.mouth;
+ a.net.setTubeTargets(a.oral, fillAreas(a.oral, (u) => (u > 0.85 ? 0.05 + 12 * m : 6), a.oralArea));
+ a.net.setPortTarget(a.velum, 0.4 + 1.6 * p.nostrils);
+ mammalNoise(a, { glottis: 6e-6, oral: 4e-6 });
+ },
+ sample() {
+ stepGlottis(a);
+ return a.net.step();
+ },
+ sourceState: () => ({ glottis: Math.min(1, g.area / 1) }),
+ };
+}
+
+export const ALLIGATOR: CreatureDef = {
+ id: "alligator",
+ name: "American alligator",
+ latin: "Alligator mississippiensis",
+ group: "reptile",
+ blurb: "A chaotic, very low laryngeal roar through a long, closed-mouthed tract; the whole body radiates.",
+ role: "Distorted sub drones, noise bass, impacts",
+ oversample: 2,
+ params: [
+ { key: "pitch", label: "Pitch", min: 12, max: 120, default: 28, unit: "Hz", log: true, smooth: 0.05, role: "pitch" },
+ { key: "chaos", label: "Bifurcation (period doubling → chaos)", min: 0, max: 1, default: 0.75, smooth: 0.05 },
+ { key: "pressure", label: "Breath pressure", min: 3, max: 40, default: 18, unit: "cmH₂O", smooth: 0.03 },
+ { key: "mouth", label: "Mouth opening", min: 0, max: 1, default: 0.02, smooth: 0.05 },
+ { key: "nostrils", label: "Nasal passage", min: 0, max: 1, default: 0.8, smooth: 0.05 },
+ { key: "hiss", label: "Hiss (open glottis)", min: 0, max: 1, default: 0, smooth: 0.04 },
+ ],
+ calls: [
+ { id: "bellow", name: "Bellow", hint: "Two seconds of chaotic roar, rising into full chaos", pitchRef: 28, keys: [{ t: 0, v: { gate: 0, chaos: 0.55, pitch: 30, hiss: 0, mouth: 0.02 } }, { t: 0.15, v: { gate: 1 } }, { t: 1.6, v: { gate: 1, chaos: 0.95, pitch: 24 } }, { t: 2.0, v: { gate: 0 } }] },
+ { id: "growl", name: "Growl", hint: "Short, rough warning", pitchRef: 45, keys: [{ t: 0, v: { gate: 1, chaos: 0.7, pitch: 45, mouth: 0.15 } }, { t: 0.5, v: { pitch: 38 } }, { t: 0.6, v: { gate: 0 } }] },
+ { id: "hiss", name: "Hiss", hint: "Open mouth, open glottis: pure turbulence", keys: [{ t: 0, v: { gate: 0, hiss: 1, mouth: 0.9 } }, { t: 0.1, v: { gate: 1 } }, { t: 1.2, v: { gate: 1 } }, { t: 1.3, v: { gate: 0, hiss: 0, mouth: 0.02 } }] },
+ { id: "dance", name: "Water dance", hint: "Steady subsonic throb that shakes the water", pitchRef: 18, keys: [{ t: 0, v: { gate: 1, chaos: 0, pitch: 18, mouth: 0 } }, { t: 1.6, v: { gate: 1 } }, { t: 1.7, v: { gate: 0, chaos: 0.75 } }] },
+ ],
+ visual: {
+ view: { x0: -120, x1: 120, y0: -40, y1: 40 },
+ silhouette: [[-118, 2], [-90, -4], [-60, -8], [-30, -14], [0, -16], [30, -14], [50, -10], [70, -8], [95, -5], [114, -3], [118, 0], [115, 3], [98, 5], [75, 7], [52, 9], [40, 12], [20, 14], [-10, 14], [-40, 11], [-70, 7], [-100, 4]],
+ parts: [{ shade: 0.15, pts: [[54, 9], [56, 11], [58, 9], [56, 8]] }],
+ tubes: [
+ { tube: "trachea", path: [[0, -6], [18, -5], [36, -4]], label: "Trachea" },
+ { tube: "pharynx", path: [[36, -4], [46, -2], [54, 0]], label: "Pharynx" },
+ { tube: "oral", path: [[54, 0], [80, -1], [112, -1]], label: "Mouth" },
+ { tube: "nasal", path: [[54, 2], [80, 4], [113, 2]], label: "Nostrils" },
+ ],
+ tubeScale: 1.05,
+ sources: [{ key: "glottis", at: [36, -4], label: "Larynx" }],
+ },
+ create,
+};
diff --git a/src/engine/creatures/build.ts b/src/engine/creatures/build.ts
new file mode 100644
index 0000000..c4bb999
--- /dev/null
+++ b/src/engine/creatures/build.ts
@@ -0,0 +1,32 @@
+/** Shared helpers for building creature airways. */
+import { AirwayNetwork, type Tube } from "../airway/network.ts";
+import { C_SOUND, RHO, type WallParams } from "../physics.ts";
+
+/** Smallest stable section length at this internal rate (CFL 0.93). */
+export const dxMin = (fs: number) => C_SOUND / fs / 0.93;
+
+/** Number of sections for a tube: as fine as stability allows, but at least `min`, at most `max`. */
+export function sections(fs: number, length: number, min = 3, max = 120, coarse = 1): number {
+ return Math.max(min, Math.min(max, Math.floor(length / (dxMin(fs) * coarse))));
+}
+
+export function tube(net: AirwayNetwork, name: string, fs: number, length: number, area: number | ((u: number) => number), opts: { wall?: WallParams | null; coarse?: number; min?: number; max?: number; perimeterFactor?: number; viscousFactor?: number; wallRadiation?: number } = {}): Tube {
+ const n = sections(fs, length, opts.min ?? 3, opts.max ?? 120, opts.coarse ?? 1);
+ const areas = typeof area === "number" ? area : Array.from({ length: n }, (_, i) => area((i + 0.5) / n));
+ return net.addTube({ name, n, length, area: areas, wall: opts.wall ?? null, perimeterFactor: opts.perimeterFactor, viscousFactor: opts.viscousFactor, wallRadiation: opts.wallRadiation });
+}
+
+/** Lungs/air-sac pressure node feeding a tube through a mildly resistive connection. */
+export function lungs(net: AirwayNetwork, into: number, area: number): number {
+ const node = net.addPressureNode("lungs");
+ net.addPort(node, into, { area, length: 1, kEntrance: 0, kExit: 0, extraResistance: (0.5 * RHO * C_SOUND) / area });
+ return node;
+}
+
+/** Fill a tube's areas from a function of position u ∈ (0,1). */
+export function fillAreas(t: Tube, f: (u: number) => number, out: Float64Array): Float64Array {
+ for (let i = 0; i < t.n; i++) out[i] = Math.max(0, f((i + 0.5) / t.n));
+ return out;
+}
+
+export const CMH2O = 980.665;
diff --git a/src/engine/creatures/elephant.ts b/src/engine/creatures/elephant.ts
new file mode 100644
index 0000000..5b81b92
--- /dev/null
+++ b/src/engine/creatures/elephant.ts
@@ -0,0 +1,102 @@
+/**
+ * African elephant: infrasonic rumbles from self-oscillating vocal folds, routed through the trunk
+ * or the mouth; trumpets from a valve at the trunk entrance that locks onto the trunk's resonances
+ * like a brass player's lips on a bugle; squeaks from tensed lips.
+ */
+import type { CreatureDef, CreatureSim } from "./types.ts";
+import { mammalAirway, stepGlottis, mammalNoise } from "./mammal.ts";
+import { fillAreas, tube, CMH2O } from "./build.ts";
+import { LipReed } from "../sources/valves.ts";
+import { WALL_NASAL } from "../physics.ts";
+import type { Tube } from "../airway/network.ts";
+
+function create(fs: number): CreatureSim {
+ let trunk: Tube | null = null;
+ let valve = -1;
+ const a = mammalAirway(fs, { trachea: [45, 14], pharynx: [32, 14], oral: [28, 10], nasal: [14, 6], wallRadiation: 0.6, coarse: 1.2, nasalRadiates: false }, (net, parts) => {
+ // the "nasal" tube is the trunk base; a lip-like valve leads into the long trunk
+ trunk = tube(net, "trunk", fs, 185, (u) => 4.2 - 3.0 * u, { wall: WALL_NASAL, coarse: 2.3, max: 110, perimeterFactor: 1.4 });
+ valve = net.addPort(parts.nasal!.lastNode, (trunk as Tube).firstNode, { area: 0, length: 0.6, kEntrance: 0.3, kExit: 1 });
+ net.addRadiation((trunk as Tube).lastNode);
+ });
+ const trunkTube = trunk as unknown as Tube;
+ const lips = new LipReed(fs);
+ const g = a.glottisSrc;
+ g.threshold = 1.5 * CMH2O;
+ let mode = 0;
+ return {
+ net: a.net,
+ tubes: { trachea: a.trachea, pharynx: a.pharynx, oral: a.oral, trunk: trunkTube },
+ gain: 1.8e-6,
+ control(p, gate) {
+ mode = p.mode;
+ a.net.setFixedPressure(a.lungs, p.pressure * CMH2O * gate);
+ // rumble: folds vibrate; trumpet: folds open, valve buzzes
+ g.params.f0 = p.pitch;
+ g.params.amplitude = 1.6 * (1 - mode);
+ g.params.abduction = 0.05 + 3.0 * mode; // trumpet: larynx wide open, silent
+ g.params.openQuotient = 0.6;
+ g.params.closureSharpness = 0.6;
+ g.params.effort = 0.9;
+ g.params.chaos = p.chaos * 0.6;
+ lips.f = p.lipPitch;
+ lips.zeta = 0.08;
+ lips.h0 = 0.003; // a slight rest gap: buzzing lips start from just apart
+ lips.width = 2.4;
+ lips.surfacePerMass = 40;
+ const toTrunk = p.trunk;
+ a.net.setPortTarget(a.velum, 0.1 + 6 * toTrunk);
+ a.net.setTubeTargets(a.pharynx, fillAreas(a.pharynx, () => 14, a.pharArea));
+ a.net.setTubeTargets(a.oral, fillAreas(a.oral, (u) => (u > 0.85 ? 0.05 + 10 * (1 - toTrunk) : 10), a.oralArea));
+ mammalNoise(a, { glottis: 4e-7 * (1 - mode) });
+ },
+ sample() {
+ stepGlottis(a);
+ if (mode > 0.02) {
+ const p = a.net.p;
+ const dp = p[a.nasal!.lastNode] - p[trunkTube.firstNode];
+ const open = lips.next(dp * mode);
+ a.net.setPortArea(valve, Math.max(open, 4.5 * (1 - mode)));
+ } else a.net.setPortArea(valve, 4.5);
+ return a.net.step();
+ },
+ sourceState: () => ({ glottis: Math.min(1, g.area / 1.6), lips: Math.min(1, lips.opening / 1.2) }),
+ };
+}
+
+export const ELEPHANT: CreatureDef = {
+ id: "elephant",
+ name: "African elephant",
+ latin: "Loxodonta africana",
+ group: "mammal",
+ blurb: "Infrasonic rumbles from huge vocal folds, routed through a two-metre trunk or the mouth; trumpets from a buzzing valve at the trunk entrance.",
+ role: "Sub-bass rumbles, distorted brass leads",
+ oversample: 1,
+ params: [
+ { key: "mode", label: "Rumble ↔ trumpet", min: 0, max: 1, default: 0, smooth: 0.03 },
+ { key: "pitch", label: "Rumble pitch", min: 8, max: 45, default: 14, unit: "Hz", log: true, smooth: 0.05, role: "pitch" },
+ { key: "lipPitch", label: "Trumpet valve pitch", min: 150, max: 900, default: 470, unit: "Hz", log: true, smooth: 0.02 },
+ { key: "pressure", label: "Breath pressure", min: 3, max: 45, default: 16, unit: "cmH₂O", smooth: 0.02 },
+ { key: "trunk", label: "Mouth ↔ trunk", min: 0, max: 1, default: 1, smooth: 0.04 },
+ { key: "chaos", label: "Chaos", min: 0, max: 1, default: 0.2, smooth: 0.05 },
+ ],
+ calls: [
+ { id: "rumble", name: "Rumble", hint: "Three seconds of infrasonic rumble through the trunk", pitchRef: 14, keys: [{ t: 0, v: { mode: 0, gate: 0, pitch: 15, trunk: 1 } }, { t: 0.3, v: { gate: 1 } }, { t: 2.7, v: { gate: 1, pitch: 12 } }, { t: 3.1, v: { gate: 0 } }] },
+ { id: "trumpet", name: "Trumpet", hint: "A brassy blast that bends up and breaks into chaos", pitchRef: 470, keys: [{ t: 0, v: { mode: 1, gate: 0, lipPitch: 380, pressure: 26, chaos: 0.1 } }, { t: 0.05, v: { gate: 1 } }, { t: 0.5, v: { lipPitch: 520 }, curve: "exp" }, { t: 1.1, v: { lipPitch: 470, chaos: 0.6, pressure: 34 }, curve: "exp" }, { t: 1.25, v: { gate: 0, mode: 0, pressure: 16 } }] },
+ { id: "squeak", name: "Squeak", hint: "Tensed, high valve buzz", pitchRef: 850, keys: [{ t: 0, v: { mode: 1, gate: 0, lipPitch: 820, pressure: 20 } }, { t: 0.04, v: { gate: 1 } }, { t: 0.45, v: { lipPitch: 880 } }, { t: 0.5, v: { gate: 0, mode: 0, pressure: 16 } }] },
+ ],
+ visual: {
+ view: { x0: -170, x1: 170, y0: -170, y1: 130 },
+ silhouette: [[-160, 20], [-150, 70], [-110, 105], [-40, 118], [30, 115], [70, 100], [95, 112], [120, 108], [140, 85], [148, 55], [146, 25], [140, 5], [132, -20], [128, -60], [122, -110], [118, -150], [108, -152], [112, -100], [110, -50], [104, -20], [96, -5], [80, 0], [70, -10], [66, -90], [40, -95], [44, -30], [-90, -30], [-95, -95], [-125, -95], [-122, -10], [-150, -5]],
+ parts: [{ shade: 0.15, pts: [[118, 62], [122, 66], [126, 62], [122, 58]] }, { shade: 0.62, pts: [[70, 100], [40, 60], [55, 25], [85, 40], [95, 80]] }],
+ tubes: [
+ { tube: "trachea", path: [[40, 20], [70, 30], [95, 38]], label: "Trachea" },
+ { tube: "pharynx", path: [[95, 38], [112, 50], [124, 58]], label: "Pharynx" },
+ { tube: "oral", path: [[124, 58], [130, 42], [134, 30]], label: "Mouth" },
+ { tube: "trunk", path: [[136, 70], [142, 40], [136, 0], [128, -50], [120, -100], [113, -148]], label: "Trunk" },
+ ],
+ tubeScale: 3,
+ sources: [{ key: "glottis", at: [95, 38], label: "Vocal folds" }, { key: "lips", at: [136, 70], label: "Trunk valve" }],
+ },
+ create,
+};
diff --git a/src/engine/creatures/index.ts b/src/engine/creatures/index.ts
new file mode 100644
index 0000000..93ceb6c
--- /dev/null
+++ b/src/engine/creatures/index.ts
@@ -0,0 +1,9 @@
+/** Creature registry. */
+import type { CreatureDef } from "./types.ts";
+import { SONGBIRD } from "./songbird.ts";
+import { SEAL } from "./seal.ts";
+import { ALLIGATOR } from "./alligator.ts";
+import { ELEPHANT } from "./elephant.ts";
+
+export const CREATURES: CreatureDef[] = [SONGBIRD, SEAL, ALLIGATOR, ELEPHANT];
+export const creatureById = (id: string) => CREATURES.find((c) => c.id === id);
diff --git a/src/engine/creatures/mammal.ts b/src/engine/creatures/mammal.ts
new file mode 100644
index 0000000..9d93126
--- /dev/null
+++ b/src/engine/creatures/mammal.ts
@@ -0,0 +1,81 @@
+/** Parametrised mammalian/reptilian airway: lungs → trachea → glottis → pharynx ─┬─ oral → mouth
+ * └─ velum → nasal → nostrils */
+import { AirwayNetwork, type Tube } from "../airway/network.ts";
+import { WALL_SOFT, WALL_TRACHEA, WALL_NASAL, type WallParams } from "../physics.ts";
+import { ParametricGlottis } from "../sources/glottis.ts";
+import { tube, lungs } from "./build.ts";
+
+export interface MammalSpec {
+ trachea: [length: number, area: number];
+ pharynx: [length: number, area: number];
+ oral: [length: number, area: number];
+ nasal?: [length: number, area: number];
+ wall?: WallParams;
+ /** fraction of wall motion that radiates (body/skin radiation) */
+ wallRadiation?: number;
+ /** coarse sections for very long tubes (×dxMin) */
+ coarse?: number;
+ /** the nasal tube ends in nostrils (default) or continues into something else (trunk) */
+ nasalRadiates?: boolean;
+}
+
+export interface MammalAirway {
+ net: AirwayNetwork;
+ trachea: Tube;
+ pharynx: Tube;
+ oral: Tube;
+ nasal: Tube | null;
+ lungs: number;
+ glottis: number;
+ velum: number;
+ glottisSrc: ParametricGlottis;
+ pharArea: Float64Array;
+ oralArea: Float64Array;
+}
+
+export function mammalAirway(fs: number, s: MammalSpec, extra?: (net: AirwayNetwork, a: Omit<MammalAirway, "glottisSrc" | "pharArea" | "oralArea" | "lungs" | "glottis" | "velum"> & { lungs?: number }) => void): MammalAirway {
+ const net = new AirwayNetwork(fs);
+ const wall = s.wall ?? WALL_SOFT;
+ const coarse = s.coarse ?? 1;
+ const trachea = tube(net, "trachea", fs, s.trachea[0], s.trachea[1], { wall: WALL_TRACHEA, coarse: Math.max(coarse, 1.6), max: 60 });
+ const pharynx = tube(net, "pharynx", fs, s.pharynx[0], s.pharynx[1], { wall, coarse, wallRadiation: s.wallRadiation ?? 0.25, perimeterFactor: 1.3 });
+ const oral = tube(net, "oral", fs, s.oral[0], s.oral[1], { wall, coarse, wallRadiation: s.wallRadiation ?? 0.25, perimeterFactor: 1.5 });
+ const nasal = s.nasal ? tube(net, "nasal", fs, s.nasal[0], s.nasal[1], { wall: WALL_NASAL, coarse, perimeterFactor: 2.6, viscousFactor: 2 }) : null;
+ const lungNode = lungs(net, trachea.firstNode, s.trachea[1]);
+ const glottis = net.addPort(trachea.lastNode, pharynx.firstNode, { area: 0, length: 0.4, kEntrance: 0.37, kExit: 1, slitWidth: Math.sqrt(s.trachea[1]) * 0.9 });
+ net.connect(pharynx.lastNode, oral.firstNode);
+ const velum = nasal ? net.addPort(pharynx.lastNode, nasal.firstNode, { area: 0, length: 1, kEntrance: 0.3, kExit: 0.8 }) : -1;
+ net.addRadiation(oral.lastNode);
+ if (nasal && s.nasalRadiates !== false) net.addRadiation(nasal.lastNode);
+ extra?.(net, { net, trachea, pharynx, oral, nasal });
+ net.finalize();
+ return { net, trachea, pharynx, oral, nasal, lungs: lungNode, glottis, velum, glottisSrc: new ParametricGlottis(fs), pharArea: new Float64Array(pharynx.n), oralArea: new Float64Array(oral.n) };
+}
+
+/**
+ * Register turbulence sources: aspiration at the glottis (hiss, breathiness) and the narrowest
+ * point of the oral tube (mouth/teeth hiss). Call at control rate.
+ */
+export function mammalNoise(a: MammalAirway, gains: { glottis: number; oral?: number }): void {
+ const list: { src: number; fwd: number; bwd: number; gain: number; lowpassHz?: number; highpassHz?: number }[] = [
+ { src: a.glottis, fwd: a.pharynx.branch(Math.min(1, a.pharynx.n - 2)), bwd: a.trachea.branch(a.trachea.n - 2), gain: gains.glottis, lowpassHz: 4000, highpassHz: 250 },
+ ];
+ if (gains.oral) {
+ let mi = 0, mv = Infinity;
+ for (let i = 0; i < a.oral.n - 1; i++) {
+ const v = a.oralArea[i];
+ if (v > 0 && v < mv) {
+ mv = v;
+ mi = i;
+ }
+ }
+ if (mv < 2) list.push({ src: a.oral.branch(mi), fwd: a.oral.branch(Math.min(a.oral.n - 2, mi + 1)), bwd: a.oral.branch(Math.max(0, mi - 1)), gain: gains.oral, lowpassHz: 5000, highpassHz: 600 });
+ }
+ a.net.setNoiseSources(list);
+}
+
+/** Drive the glottal port from its source for one sample. */
+export function stepGlottis(a: MammalAirway): void {
+ const p = a.net.p;
+ a.net.setPortArea(a.glottis, a.glottisSrc.next(p[a.trachea.lastNode] - p[a.pharynx.firstNode]));
+}
diff --git a/src/engine/creatures/seal.ts b/src/engine/creatures/seal.ts
new file mode 100644
index 0000000..84b1043
--- /dev/null
+++ b/src/engine/creatures/seal.ts
@@ -0,0 +1,86 @@
+/**
+ * Weddell seal: male trills sweep down over seconds from several kHz to below 100 Hz while their
+ * pulse rate also slows — researchers compared them to ARP synthesizers. Modelled as a laryngeal
+ * source with an extreme pitch range, a pulse (amplitude) oscillator, and a short tract.
+ */
+import type { CreatureDef, CreatureSim } from "./types.ts";
+import { mammalAirway, stepGlottis, mammalNoise } from "./mammal.ts";
+import { fillAreas, CMH2O } from "./build.ts";
+
+function create(fs: number): CreatureSim {
+ const a = mammalAirway(fs, { trachea: [24, 4], pharynx: [11, 3.2], oral: [12, 3.6], nasal: [12, 1.5], wallRadiation: 0.6 });
+ const g = a.glottisSrc;
+ g.params.jitter = 0.002;
+ g.params.shimmer = 0.01;
+ g.params.drift = 2;
+ let pulsePhase = 0;
+ let pulseGate = 1;
+ return {
+ net: a.net,
+ tubes: { trachea: a.trachea, pharynx: a.pharynx, oral: a.oral },
+ gain: 6.4e-8,
+ control(p, gate, dt) {
+ pulsePhase += p.pulseRate * dt;
+ pulsePhase -= Math.floor(pulsePhase);
+ const ph = pulsePhase < p.duty ? Math.sin((Math.PI * pulsePhase) / p.duty) : 0;
+ pulseGate = 1 - p.pulse + p.pulse * ph;
+ a.net.setFixedPressure(a.lungs, p.pressure * CMH2O * gate * pulseGate);
+ g.params.f0 = p.pitch;
+ g.params.amplitude = 0.22;
+ g.params.openQuotient = 0.55 - 0.25 * p.bright;
+ g.params.closureSharpness = 0.4 + 0.6 * p.bright;
+ g.params.effort = 0.5 + 0.5 * p.bright;
+ g.params.chink = 0.01;
+ g.params.chaos = p.rough;
+ const mouth = p.mouth;
+ a.net.setTubeTargets(a.pharynx, fillAreas(a.pharynx, () => 3.0, a.pharArea));
+ a.net.setTubeTargets(a.oral, fillAreas(a.oral, (u) => (u > 0.8 ? 0.3 + 4 * mouth : 3.6), a.oralArea));
+ mammalNoise(a, { glottis: 2e-6 });
+ },
+ sample() {
+ stepGlottis(a);
+ return a.net.step();
+ },
+ sourceState: () => ({ glottis: Math.min(1, g.area / 0.3) }),
+ };
+}
+
+export const SEAL: CreatureDef = {
+ id: "seal",
+ name: "Weddell seal",
+ latin: "Leptonychotes weddellii",
+ group: "marine",
+ blurb: "Laryngeal calls with an extreme range: trills glide down for seconds while their pulses slow.",
+ role: "Downlifters, laser zaps, acid-style sweeping leads",
+ oversample: 2,
+ gateTimes: { attack: 0.006, release: 0.03 },
+ params: [
+ { key: "pitch", label: "Pitch", min: 40, max: 6000, default: 900, unit: "Hz", log: true, smooth: 0.01, role: "pitch" },
+ { key: "pulseRate", label: "Pulse rate", min: 2, max: 60, default: 18, unit: "Hz", log: true, smooth: 0.02 },
+ { key: "pulse", label: "Pulsing depth", min: 0, max: 1, default: 0.6, smooth: 0.02 },
+ { key: "duty", label: "Pulse duty", min: 0.15, max: 1, default: 0.55, smooth: 0.02 },
+ { key: "bright", label: "Brightness", min: 0, max: 1, default: 0.6, smooth: 0.02 },
+ { key: "rough", label: "Roughness", min: 0, max: 0.8, default: 0.05, smooth: 0.05 },
+ { key: "pressure", label: "Breath pressure", min: 2, max: 25, default: 10, unit: "cmH₂O", smooth: 0.01 },
+ { key: "mouth", label: "Mouth opening", min: 0, max: 1, default: 0.35, smooth: 0.03 },
+ ],
+ calls: [
+ { id: "trill", name: "Descending trill", hint: "Several seconds falling from bright to subsonic, pulses slowing", pitchRef: 3600, keys: [{ t: 0, v: { gate: 1, pitch: 3600, pulseRate: 42, pulse: 0.9, duty: 0.5 } }, { t: 3.6, v: { gate: 1, pitch: 95, pulseRate: 6 }, curve: "exp" }, { t: 3.9, v: { gate: 0 } }] },
+ { id: "zap", name: "Laser chirp", hint: "A 150 ms downward zap", pitchRef: 6000, keys: [{ t: 0, v: { gate: 1, pitch: 6000, pulse: 0 } }, { t: 0.15, v: { pitch: 1100 }, curve: "exp" }, { t: 0.17, v: { gate: 0 } }] },
+ { id: "whistle", name: "U whistle", hint: "Dips and returns", pitchRef: 1700, keys: [{ t: 0, v: { gate: 1, pitch: 1700, pulse: 0.1 } }, { t: 0.45, v: { pitch: 620 }, curve: "exp" }, { t: 0.95, v: { pitch: 1500 }, curve: "exp" }, { t: 1.0, v: { gate: 0 } }] },
+ { id: "chug", name: "Chug", hint: "Low, pulsed grunt", pitchRef: 90, keys: [{ t: 0, v: { gate: 1, pitch: 90, pulseRate: 11, pulse: 1, duty: 0.35, rough: 0.3 } }, { t: 0.9, v: { gate: 1 } }, { t: 0.95, v: { gate: 0, rough: 0.05 } }] },
+ ],
+ visual: {
+ view: { x0: -60, x1: 60, y0: -30, y1: 30 },
+ silhouette: [[-58, -2], [-50, -8], [-30, -14], [-5, -16], [20, -14], [38, -10], [48, -6], [55, -3], [58, 1], [56, 5], [50, 8], [42, 10], [30, 11], [10, 13], [-15, 13], [-35, 10], [-50, 6], [-56, 3], [-62, 8], [-64, 4], [-60, 0], [-64, -4], [-62, -8]],
+ parts: [{ shade: 0.15, pts: [[47, 4], [48.5, 5], [50, 4], [48.5, 3]] }],
+ tubes: [
+ { tube: "trachea", path: [[8, -4], [20, -3], [30, -2]], label: "Trachea" },
+ { tube: "pharynx", path: [[30, -2], [38, 0], [44, 1.5]], label: "Pharynx" },
+ { tube: "oral", path: [[44, 1.5], [50, 0.5], [57, -0.5]], label: "Mouth" },
+ ],
+ tubeScale: 1.3,
+ sources: [{ key: "glottis", at: [30, -2], label: "Larynx" }],
+ },
+ create,
+};
diff --git a/src/engine/creatures/songbird.ts b/src/engine/creatures/songbird.ts
new file mode 100644
index 0000000..7579bf2
--- /dev/null
+++ b/src/engine/creatures/songbird.ts
@@ -0,0 +1,164 @@
+/**
+ * Two-voice songbird (thrush-sized). Each side of the syrinx has its own labial oscillator and
+ * pitch; both bronchi merge into the trachea → larynx → oropharyngeal–oesophageal cavity (OEC,
+ * a Helmholtz resonator whose volume can track f0 for pure tones) → beak (gape controls radiation).
+ */
+import { AirwayNetwork } from "../airway/network.ts";
+import { WALL_TRACHEA } from "../physics.ts";
+import { SyrinxLabia } from "../sources/syrinx.ts";
+import type { CreatureDef, CreatureSim, CallKey } from "./types.ts";
+import { tube, fillAreas } from "./build.ts";
+
+const OEC_NECK = 0.03; // cm² (larynx)
+const OEC_LEN = 0.35; // cm, with end corrections
+
+function create(fs: number): CreatureSim {
+ const net = new AirwayNetwork(fs);
+ const bronL = tube(net, "bronchusL", fs, 0.8, 0.02);
+ const bronR = tube(net, "bronchusR", fs, 0.8, 0.02);
+ const trachea = tube(net, "trachea", fs, 3.6, 0.045, { wall: WALL_TRACHEA });
+ const sac = net.addPressureNode("air sac");
+ net.addPort(sac, bronL.firstNode, { area: 0.05, length: 0.4 });
+ net.addPort(sac, bronR.firstNode, { area: 0.05, length: 0.4 });
+ const vL = net.addPort(bronL.lastNode, trachea.firstNode, { area: 0, length: 0.08, kEntrance: 0.5, kExit: 1 });
+ const vR = net.addPort(bronR.lastNode, trachea.firstNode, { area: 0, length: 0.08, kEntrance: 0.5, kExit: 1 });
+ const oec = net.addCavity("oec", 0.4);
+ net.addPort(trachea.lastNode, oec, { area: OEC_NECK, length: 0.25, kEntrance: 0.3, kExit: 0.8 });
+ const beak = tube(net, "beak", fs, 1.3, 0.08);
+ net.connect(oec, beak.firstNode);
+ net.addRadiation(beak.lastNode);
+ net.finalize();
+ const oecLen = Math.cbrt(0.4);
+ const labL = new SyrinxLabia(fs, 0);
+ const labR = new SyrinxLabia(fs, 1);
+ const beakAreas = new Float64Array(beak.n);
+ const AMAX = 0.03;
+ return {
+ net,
+ tubes: { trachea, beak, bronchusL: bronL, bronchusR: bronR },
+ gain: 4.8e-7,
+ control(p, gate) {
+ net.setFixedPressure(sac, p.pressure * 1000 * gate * 10); // kPa → dyn/cm² (×10 000)
+ labL.f0 = p.pitch;
+ labR.f0 = p.pitch * Math.pow(2, p.interval / 12);
+ labL.drive = labR.drive = p.drive;
+ labL.tension = labR.tension = p.tension;
+ // voices: 0 = left only, 0.5 = both, 1 = right only
+ labL.gate = p.voices <= 0.5 ? 1 : Math.max(0, 2 - 2 * p.voices);
+ labR.gate = p.voices >= 0.5 ? 1 : Math.max(0, 2 * p.voices);
+ // OEC tracks the (lower) fundamental for pure tones, or stays at its own size
+ const fT = Math.min(labL.f0, labR.f0);
+ const vTrack = OEC_NECK / (OEC_LEN * Math.pow(fT / 5570, 2));
+ const vol = Math.min(2.5, Math.max(0.04, p.purity * vTrack + (1 - p.purity) * p.oec));
+ net.setNodeAreaTarget(oec, vol / oecLen);
+ const gape = p.gape;
+ net.setTubeTargets(beak, fillAreas(beak, (u) => 0.012 + gape * (0.05 + 0.22 * u), beakAreas));
+ },
+ sample() {
+ net.setPortArea(vL, AMAX * labL.next());
+ net.setPortArea(vR, AMAX * labR.next());
+ return net.step();
+ },
+ sourceState: () => ({ left: labL.opening, right: labR.opening }),
+ };
+}
+
+// --- calls --------------------------------------------------------------------------------------
+function trill(f0: number, rate: number, n: number, sweep: number): CallKey[] {
+ const keys: CallKey[] = [];
+ const per = 1 / rate;
+ for (let i = 0; i < n; i++) {
+ const t = i * per;
+ keys.push({ t, v: { gate: 0, pitch: f0 * (1 - sweep / 2) } , curve: "step" });
+ keys.push({ t: t + per * 0.08, v: { gate: 1 } });
+ keys.push({ t: t + per * 0.62, v: { gate: 1, pitch: f0 * (1 + sweep / 2) }, curve: "exp" });
+ keys.push({ t: t + per * 0.75, v: { gate: 0 } });
+ }
+ return keys;
+}
+
+export const SONGBIRD: CreatureDef = {
+ id: "songbird",
+ name: "Songbird",
+ latin: "Hylocichla mustelina & kin",
+ group: "bird",
+ blurb: "Two independent labial pairs in the syrinx, one per bronchus, each with its own pitch; a throat cavity tracks the note.",
+ role: "Shimmering two-note leads, arpeggio trills, glitchy chirps",
+ oversample: 4,
+ gateTimes: { attack: 0.004, release: 0.012 },
+ params: [
+ { key: "pitch", label: "Pitch, left voice", min: 400, max: 9000, default: 2600, unit: "Hz", log: true, smooth: 0.008, role: "pitch" },
+ { key: "interval", label: "Right voice interval", min: -12, max: 12, default: 7, unit: "st", smooth: 0.02, digits: 1 },
+ { key: "voices", label: "Left ↔ both ↔ right", min: 0, max: 1, default: 0.5, smooth: 0.02 },
+ { key: "drive", label: "Drive (pure → raspy)", min: 0, max: 1, default: 0.35, smooth: 0.02 },
+ { key: "tension", label: "Labial tension", min: 0, max: 1, default: 0.4, smooth: 0.02 },
+ { key: "pressure", label: "Air-sac pressure", min: 0.1, max: 2, default: 0.9, unit: "kPa", smooth: 0.01, digits: 2 },
+ { key: "purity", label: "Throat tracks note", min: 0, max: 1, default: 0.8, smooth: 0.02 },
+ { key: "oec", label: "Throat cavity size", min: 0.05, max: 2, default: 0.4, unit: "cm³", log: true, smooth: 0.03, digits: 2 },
+ { key: "gape", label: "Beak gape", min: 0, max: 1, default: 0.55, smooth: 0.02 },
+ ],
+ calls: [
+ {
+ id: "flute",
+ name: "Flute phrase",
+ hint: "Wood-thrush style: three notes, then a two-voice shimmer",
+ pitchRef: 2600,
+ keys: [
+ { t: 0, v: { gate: 0, pitch: 2000, voices: 0.15, drive: 0.25, interval: 7 } },
+ { t: 0.02, v: { gate: 1 } },
+ { t: 0.2, v: { gate: 1, pitch: 2100 }, curve: "exp" },
+ { t: 0.23, v: { gate: 0 } },
+ { t: 0.3, v: { gate: 1, pitch: 2600 }, curve: "step" },
+ { t: 0.5, v: { pitch: 2500 }, curve: "exp" },
+ { t: 0.53, v: { gate: 0 } },
+ { t: 0.6, v: { gate: 1, pitch: 3300, voices: 0.5, interval: 4 }, curve: "step" },
+ { t: 1.1, v: { pitch: 3500, interval: 5 }, curve: "exp" },
+ { t: 1.2, v: { gate: 0 } },
+ ],
+ },
+ { id: "trill", name: "Canary trill", hint: "16 notes a second, each a quick upsweep", pitchRef: 3000, keys: [{ t: 0, v: { voices: 0.15, drive: 0.3 } }, ...trill(3000, 16, 18, 0.35)] },
+ {
+ id: "chirps",
+ name: "Chirp cascade",
+ hint: "Falling chirps, faster and faster",
+ pitchRef: 4500,
+ keys: [{ t: 0, v: { voices: 0.15, drive: 0.4 } }, ...Array.from({ length: 9 }, (_, i): CallKey[] => {
+ const t = i * (0.14 - i * 0.008);
+ return [
+ { t, v: { gate: 0, pitch: 7000 - i * 300 }, curve: "step" },
+ { t: t + 0.01, v: { gate: 1 } },
+ { t: t + 0.06, v: { gate: 1, pitch: 2400 - i * 80 }, curve: "exp" },
+ { t: t + 0.07, v: { gate: 0 } },
+ ];
+ }).flat()],
+ },
+ {
+ id: "buzz",
+ name: "Finch buzz",
+ hint: "Zebra-finch style: raspy, pulsed by mini-breaths",
+ pitchRef: 1200,
+ keys: [
+ { t: 0, v: { voices: 0.5, drive: 0.95, tension: 0.15, interval: 0.5, pitch: 1200, purity: 0.1, gate: 0 } },
+ ...Array.from({ length: 8 }, (_, i): CallKey[] => [
+ { t: 0.02 + i * 0.07, v: { gate: 1 } },
+ { t: 0.06 + i * 0.07, v: { gate: 0.35 } },
+ ]).flat(),
+ { t: 0.6, v: { gate: 0 } },
+ ],
+ },
+ ],
+ visual: {
+ view: { x0: -4, x1: 14, y0: -6, y1: 8 },
+ silhouette: [[-3.2, -1.2], [-1.6, -3.4], [1.6, -4.6], [5.2, -4.4], [7.8, -2.6], [9.0, -0.4], [9.6, 1.8], [10.4, 2.4], [12.8, 2.6], [10.6, 3.0], [9.8, 3.6], [9.2, 4.6], [7.6, 5.2], [6.0, 4.6], [4.2, 2.8], [2.0, 2.0], [-0.2, 1.6], [-3.6, 1.4], [-3.4, 0.2]],
+ parts: [{ shade: 0.2, pts: [[8.6, 4.0], [8.95, 4.3], [9.2, 4.0], [8.95, 3.7]] }],
+ tubes: [
+ { tube: "bronchusL", path: [[3.4, -1.9], [4.4, -1.4]], label: "Left bronchus", inView: false },
+ { tube: "bronchusR", path: [[3.4, -0.9], [4.4, -1.2]], label: "Right bronchus", inView: false },
+ { tube: "trachea", path: [[4.4, -1.3], [5.6, -0.4], [6.8, 0.8], [7.8, 1.9], [8.6, 2.5]], label: "Trachea" },
+ { tube: "beak", path: [[9.4, 2.75], [10.6, 2.75], [12.4, 2.7]], label: "Beak" },
+ ],
+ tubeScale: 1.6,
+ sources: [{ key: "left", at: [4.2, -1.6], label: "Left voice" }, { key: "right", at: [4.2, -1.0], label: "Right voice" }],
+ },
+ create,
+};
diff --git a/src/engine/creatures/types.ts b/src/engine/creatures/types.ts
new file mode 100644
index 0000000..f5119cc
--- /dev/null
+++ b/src/engine/creatures/types.ts
@@ -0,0 +1,87 @@
+/** Creature definitions: physics (airway + sources), playable parameters, calls, and drawing. */
+import type { AirwayNetwork, Tube } from "../airway/network.ts";
+
+export type CreatureGroup = "human" | "bird" | "mammal" | "marine" | "reptile" | "amphibian" | "insect" | "crustacean" | "fantasy";
+
+export interface ParamDef {
+ key: string;
+ label: string;
+ min: number;
+ max: number;
+ default: number;
+ unit?: string;
+ log?: boolean;
+ /** smoothing time constant (s) */
+ smooth?: number;
+ /** "pitch" params follow the keyboard */
+ role?: "pitch";
+ /** decimals for display */
+ digits?: number;
+}
+
+export interface CallKey {
+ t: number;
+ v: Record<string, number>;
+ /** interpolation from the previous key: linear (default), exponential (for frequencies), or step */
+ curve?: "lin" | "exp" | "step";
+}
+
+export interface CallDef {
+ id: string;
+ name: string;
+ hint: string;
+ keys: CallKey[];
+ /** pitch params in the call are scaled by playedPitch / pitchRef when triggered from the keys */
+ pitchRef?: number;
+}
+
+export interface CreatureVisual {
+ /** body outline in drawing units (≈ cm; y up) */
+ silhouette: [number, number][];
+ /** extra shapes drawn in tissue tones (shade 0 black … 1 white) */
+ parts?: { shade: number; pts: [number, number][]; stroke?: boolean }[];
+ /** airway centrelines per tube name (tube nodes are distributed along the path); inView: false
+ * keeps the label out of the cross-section (it still names the tube's lane) */
+ tubes: { tube: string; path: [number, number][]; label?: string; inView?: boolean }[];
+ /** how much wider than life to draw the airway (narrow tubes stay legible) */
+ tubeScale?: number;
+ /** drawing extents */
+ view: { x0: number; x1: number; y0: number; y1: number };
+ /** sound sources to draw, keyed into CreatureSim.sourceState() */
+ sources?: { key: string; at: [number, number]; label: string }[];
+}
+
+export interface CreatureSim {
+ readonly net: AirwayNetwork | null;
+ /** tubes exposed to telemetry/visuals, by name */
+ readonly tubes: Record<string, Tube>;
+ /** control-rate update with smoothed parameters; gate 0..1 is the breath */
+ control(p: Record<string, number>, gate: number, dt: number): void;
+ /** one internal sample → radiated output (arbitrary units) */
+ sample(): number;
+ /** fixed output normalisation */
+ readonly gain: number;
+ /** a few named source values for the source glyph (0..1) */
+ sourceState?(): Record<string, number>;
+ /** discrete events from calls (e.g. clicks, snaps) */
+ trigger?(name: string, amount: number): void;
+}
+
+export interface CreatureDef {
+ id: string;
+ name: string;
+ latin: string;
+ group: CreatureGroup;
+ /** how it makes sound, one sentence */
+ blurb: string;
+ /** musical role in a track */
+ role: string;
+ /** internal oversampling factor relative to the output rate */
+ oversample: number;
+ /** breath gate attack/release time constants (s) */
+ gateTimes?: { attack: number; release: number };
+ params: ParamDef[];
+ calls: CallDef[];
+ visual: CreatureVisual;
+ create(fs: number): CreatureSim;
+}
diff --git a/src/engine/creatures/voice.ts b/src/engine/creatures/voice.ts
new file mode 100644
index 0000000..98af225
--- /dev/null
+++ b/src/engine/creatures/voice.ts
@@ -0,0 +1,256 @@
+/**
+ * Generic runtime for non-human creatures: parameter smoothing, breath gate, call playback
+ * (keyframed automation), control-rate scheduling, oversampled simulation, decimation, DC block,
+ * limiter and fixed-size telemetry. Runs in the AudioWorklet and in Bun.
+ */
+import type { CreatureDef, CreatureSim, CallDef } from "./types.ts";
+import { Decimator } from "../airway/decimator.ts";
+
+export interface CreatureTelemetry {
+ kind: "creature";
+ id: string;
+ params: Record<string, number>;
+ gate: number;
+ outRms: number;
+ clock: number;
+ /** per tube: areas (cm²) and acoustic pressure RMS (dyn/cm², static pressure removed) per node */
+ tubes: Record<string, { areas: Float32Array; rms: Float32Array }>;
+ source: Record<string, number>;
+ call: string | null;
+}
+
+interface ActiveCall {
+ def: CallDef;
+ t0: number;
+ pitch: number;
+ amp: number;
+ fired: Set<number>;
+ /** params the call automates (restored to the performer's values when it ends) */
+ owns: Set<string>;
+}
+
+export class CreatureVoice {
+ readonly def: CreatureDef;
+ readonly fsOut: number;
+ readonly fs: number;
+ readonly M: number;
+ readonly sim: CreatureSim;
+ /** performer settings, targets (performer or call automation) and smoothed values */
+ readonly performer: Record<string, number> = {};
+ readonly target: Record<string, number> = {};
+ readonly value: Record<string, number> = {};
+ gate = 0;
+ private gateTarget = 0;
+ private callGate = 0;
+ clock = 0;
+ private call: ActiveCall | null = null;
+ private readonly dec: Decimator;
+ private readonly ctrlEvery: number;
+ private ctrlCounter = 0;
+ private dcX = 0;
+ private dcY = 0;
+ private readonly dcCoef: number;
+ private outAcc = 0;
+ private outCount = 0;
+ private readonly rmsAcc: Record<string, Float64Array> = {};
+ private readonly meanAcc: Record<string, Float64Array> = {};
+ private rmsCount = 0;
+ private sub = 0;
+ /** master trim (performer) */
+ level = 1;
+
+ constructor(def: CreatureDef, fsOut: number, initial?: Record<string, number>) {
+ this.def = def;
+ this.fsOut = fsOut;
+ this.M = Math.max(1, Math.round(def.oversample * (fsOut > 60000 ? 0.5 : 1)));
+ this.fs = fsOut * this.M;
+ this.sim = def.create(this.fs);
+ this.dec = new Decimator(this.M);
+ this.ctrlEvery = 64 * this.M;
+ this.dcCoef = Math.exp((-2 * Math.PI * 12) / fsOut);
+ for (const p of def.params) {
+ const x = initial?.[p.key];
+ this.performer[p.key] = this.target[p.key] = this.value[p.key] = x !== undefined && Number.isFinite(x) ? Math.min(p.max, Math.max(p.min, x)) : p.default;
+ }
+ for (const [name, t] of Object.entries(this.sim.tubes)) {
+ this.rmsAcc[name] = new Float64Array(t.n);
+ this.meanAcc[name] = new Float64Array(t.n);
+ }
+ this.sim.control(this.value, 0, this.ctrlEvery / this.fs);
+ this.sim.net?.snapToTargets();
+ }
+
+ setParams(v: Record<string, number>): void {
+ for (const [k, x] of Object.entries(v)) {
+ const d = this.def.params.find((p) => p.key === k);
+ if (!d || !Number.isFinite(x)) continue;
+ const v = Math.min(d.max, Math.max(d.min, x));
+ this.performer[k] = v;
+ if (!this.call?.owns.has(k)) this.target[k] = v;
+ }
+ }
+
+ setGate(level: number): void {
+ this.gateTarget = Math.max(0, Math.min(1.5, level));
+ }
+
+ /** Play a call; pitch scales the call's pitch params relative to its reference. */
+ playCall(id: string, pitch?: number, amp = 1): void {
+ const def = this.def.calls.find((c) => c.id === id);
+ if (!def) return;
+ const ref = def.pitchRef ?? 0;
+ this.endCall();
+ const owns = new Set<string>();
+ for (const k of def.keys) for (const n of Object.keys(k.v)) if (n !== "gate" && !n.startsWith("!")) owns.add(n);
+ this.call = { def, t0: this.clock, pitch: pitch && ref ? pitch / ref : 1, amp, fired: new Set(), owns };
+ }
+
+ stopCall(): void {
+ this.endCall();
+ }
+
+ /** End the active call and hand its parameters back to the performer. */
+ private endCall(): void {
+ if (this.call) for (const n of this.call.owns) this.target[n] = this.performer[n];
+ this.call = null;
+ this.callGate = 0;
+ }
+
+ get activeCall(): string | null {
+ return this.call?.def.id ?? null;
+ }
+
+ /** Evaluate the active call's automation at the current clock (writes into targets). */
+ private evalCall(): void {
+ const c = this.call;
+ if (!c) return;
+ const t = this.clock - c.t0;
+ const keys = c.def.keys;
+ const last = keys[keys.length - 1];
+ if (t > last.t + 0.05) {
+ this.endCall();
+ return;
+ }
+ // collect all params mentioned
+ const names = new Set<string>();
+ for (const k of keys) for (const n of Object.keys(k.v)) names.add(n);
+ for (const n of names) {
+ // find surrounding keys that define n
+ let prev: { t: number; x: number } | null = null, next: { t: number; x: number; curve?: string } | null = null;
+ for (const k of keys) {
+ if (!(n in k.v)) continue;
+ if (k.t <= t) prev = { t: k.t, x: k.v[n] };
+ else {
+ next = { t: k.t, x: k.v[n], curve: k.curve };
+ break;
+ }
+ }
+ if (!prev) continue;
+ let x = prev.x;
+ if (next && next.curve !== "step") {
+ const u = (t - prev.t) / Math.max(1e-6, next.t - prev.t);
+ if (next.curve === "exp" && prev.x > 0 && next.x > 0) x = prev.x * Math.pow(next.x / prev.x, u);
+ else x = prev.x + (next.x - prev.x) * u;
+ }
+ if (n === "gate") {
+ this.callGate = x * c.amp;
+ continue;
+ }
+ if (n.startsWith("!")) {
+ // events: "!click" etc. fire once when crossing the key time with value = amount
+ continue;
+ }
+ const d = this.def.params.find((p) => p.key === n);
+ if (!d) continue;
+ if (d.role === "pitch") x *= c.pitch;
+ this.target[n] = Math.min(d.max, Math.max(d.min, x));
+ }
+ // one-shot events
+ keys.forEach((k, i) => {
+ if (k.t > t || c.fired.has(i)) return;
+ for (const [n, amount] of Object.entries(k.v)) if (n.startsWith("!")) this.sim.trigger?.(n.slice(1), amount * c.amp);
+ c.fired.add(i);
+ });
+ }
+
+ private control(): void {
+ const dt = this.ctrlEvery / this.fs;
+ this.evalCall();
+ for (const p of this.def.params) {
+ const tau = p.smooth ?? 0.03;
+ const a = 1 - Math.exp(-dt / Math.max(0.001, tau));
+ const cur = this.value[p.key], tgt = this.target[p.key];
+ this.value[p.key] = p.log && cur > 0 && tgt > 0 ? cur * Math.pow(tgt / cur, a) : cur + (tgt - cur) * a;
+ }
+ const goal = Math.max(this.gateTarget, this.callGate);
+ const gt = this.def.gateTimes ?? { attack: 0.012, release: 0.06 };
+ const tau = goal > this.gate ? gt.attack : gt.release;
+ this.gate += (goal - this.gate) * (1 - Math.exp(-dt / tau));
+ this.sim.control(this.value, this.gate, dt);
+ this.sim.net?.beginBlock(this.ctrlEvery);
+ this.ctrlCounter = this.ctrlEvery;
+ this.clock += dt;
+ }
+
+ render(out: Float32Array, offset: number, n: number): void {
+ const M = this.M;
+ const gain = this.sim.gain * this.level;
+ const tubes = Object.entries(this.sim.tubes);
+ for (let i = 0; i < n; i++) {
+ for (let m = 0; m < M; m++) {
+ if (this.ctrlCounter <= 0) this.control();
+ this.ctrlCounter--;
+ const y = this.sim.sample();
+ if ((++this.sub & 7) === 0 && this.sim.net) {
+ const p = this.sim.net.p;
+ for (const [name, t] of tubes) {
+ const acc = this.rmsAcc[name], mean = this.meanAcc[name];
+ for (let k = 0; k < t.n; k++) {
+ const v = p[t.first + k];
+ acc[k] += v * v;
+ mean[k] += v;
+ }
+ }
+ this.rmsCount++;
+ }
+ if (this.dec.push(y)) {
+ let v = this.dec.value * gain;
+ const hp = v - this.dcX + this.dcCoef * this.dcY;
+ this.dcX = v;
+ this.dcY = hp;
+ v = hp;
+ const av = Math.abs(v);
+ if (av > 0.7) v = Math.sign(v) * (0.7 + 0.3 * Math.tanh((av - 0.7) / 0.3));
+ if (!Number.isFinite(v)) v = 0;
+ out[offset + i] = v;
+ this.outAcc += v * v;
+ this.outCount++;
+ }
+ }
+ }
+ }
+
+ telemetry(): CreatureTelemetry {
+ const tubes: CreatureTelemetry["tubes"] = {};
+ const c = Math.max(1, this.rmsCount);
+ for (const [name, t] of Object.entries(this.sim.tubes)) {
+ const areas = new Float32Array(t.n);
+ const rms = new Float32Array(t.n);
+ const net = this.sim.net!;
+ const acc = this.rmsAcc[name], mean = this.meanAcc[name];
+ for (let k = 0; k < t.n; k++) {
+ areas[k] = net.area[t.first + k];
+ const m = mean[k] / c;
+ rms[k] = Math.sqrt(Math.max(0, acc[k] / c - m * m));
+ }
+ acc.fill(0);
+ mean.fill(0);
+ tubes[name] = { areas, rms };
+ }
+ this.rmsCount = 0;
+ const outRms = Math.sqrt(this.outAcc / Math.max(1, this.outCount));
+ this.outAcc = 0;
+ this.outCount = 0;
+ return { kind: "creature", id: this.def.id, params: { ...this.value }, gate: this.gate, outRms, clock: this.clock, tubes, source: this.sim.sourceState?.() ?? {}, call: this.activeCall };
+ }
+}
diff --git a/src/engine/sources/glottis.ts b/src/engine/sources/glottis.ts
index 1b382a8..8fd3aba 100644
--- a/src/engine/sources/glottis.ts
+++ b/src/engine/sources/glottis.ts
@@ -43,6 +43,11 @@ export interface GlottisParams {
diplophonia: number;
/** extra glottal closure force 0..1 (glottal stop / ejective: holds the folds shut) */
closure: number;
+ /**
+ * bifurcation 0..1: a logistic map drives per-cycle period and amplitude. Rising values walk
+ * through period doubling (subharmonics, ~0.3), period four (~0.55) into deterministic chaos (>0.62).
+ */
+ chaos: number;
}
export const DEFAULT_GLOTTIS: GlottisParams = {
@@ -62,6 +67,7 @@ export const DEFAULT_GLOTTIS: GlottisParams = {
fry: 0,
diplophonia: 0,
closure: 0,
+ chaos: 0,
};
export class ParametricGlottis {
@@ -71,6 +77,7 @@ export class ParametricGlottis {
private cycleAmp = 1;
private cyclePeriodScale = 1;
private cycleIndex = 0;
+ private chaosX = 0.37;
private vibPhase = 0;
private readonly rng = new Rng(777);
private readonly drift: Drift;
@@ -147,9 +154,18 @@ export class ParametricGlottis {
this.phase -= 1;
this.cycleIndex++;
const alt = this.cycleIndex & 1 ? 1 : -1;
- this.cyclePeriodScale = 1 + P.jitter * this.rng.gauss() + P.diplophonia * 0.08 * alt;
- this.cyclePeriodScale = clamp(this.cyclePeriodScale, 0.7, 1.4);
- this.cycleAmp = Math.max(0.2, 1 + P.shimmer * this.rng.gauss() - P.diplophonia * 0.35 * (alt > 0 ? 1 : 0));
+ let chaosP = 0, chaosA = 0;
+ if (P.chaos > 0) {
+ const r = 2.9 + 1.1 * Math.min(1, P.chaos);
+ this.chaosX = r * this.chaosX * (1 - this.chaosX);
+ if (!(this.chaosX > 0 && this.chaosX < 1)) this.chaosX = 0.37;
+ const dev = this.chaosX - 0.5;
+ chaosP = 0.45 * P.chaos * dev;
+ chaosA = 1.1 * P.chaos * dev;
+ }
+ this.cyclePeriodScale = 1 + P.jitter * this.rng.gauss() + P.diplophonia * 0.08 * alt + chaosP;
+ this.cyclePeriodScale = clamp(this.cyclePeriodScale, 0.55, 1.8);
+ this.cycleAmp = Math.max(0.12, 1 + P.shimmer * this.rng.gauss() - P.diplophonia * 0.35 * (alt > 0 ? 1 : 0) + chaosA);
}
// pulse shape within the cycle
diff --git a/src/engine/sources/syrinx.ts b/src/engine/sources/syrinx.ts
new file mode 100644
index 0000000..df4ca29
--- /dev/null
+++ b/src/engine/sources/syrinx.ts
@@ -0,0 +1,105 @@
+/**
+ * Songbird syrinx: one labial pair modelled by the Gardner–Mindlin normal form
+ * X' = Y, Y' = −α − βX − X³ − X²Y + X² − XY (τ = γ·t)
+ * γ is a pure time scale for fixed (α, β), so pitch is exact: γ = f0·T(α, β), with the limit-cycle
+ * period T tabulated offline (tools/gen-syrinx-table.ts). α (drive ≈ air-sac pressure) moves the
+ * waveform from a near-sine (Hopf onset) to rich relaxation pulses; β (labial tension) shapes it.
+ * The labial displacement maps to the valve opening of its bronchus.
+ */
+import table from "./syrinxTable.generated.json";
+
+interface Table {
+ alphas: number[];
+ betas: number[];
+ T: (number | null)[][];
+ lo: number[][];
+ hi: number[][];
+}
+const TB = table as unknown as Table;
+
+// fill cells without a limit cycle from their neighbours
+for (let bi = 0; bi < TB.betas.length; bi++)
+ for (let ai = TB.alphas.length - 1; ai >= 0; ai--) {
+ const v = TB.T[bi][ai];
+ if (v === null || !Number.isFinite(v)) {
+ TB.T[bi][ai] = TB.T[bi][ai + 1] ?? TB.T[bi + 1]?.[ai] ?? 10;
+ TB.lo[bi][ai] = TB.lo[bi][ai + 1] ?? -1;
+ TB.hi[bi][ai] = TB.hi[bi][ai + 1] ?? 1;
+ }
+ }
+
+function bilinear(grid: (number | null)[][], a: number, b: number): number {
+ const as = TB.alphas, bs = TB.betas;
+ const fa = Math.max(0, Math.min(as.length - 1.0001, ((a - as[0]) / (as[as.length - 1] - as[0])) * (as.length - 1)));
+ const fb = Math.max(0, Math.min(bs.length - 1.0001, ((b - bs[0]) / (bs[bs.length - 1] - bs[0])) * (bs.length - 1)));
+ const ia = Math.floor(fa), ib = Math.floor(fb);
+ const u = fa - ia, w = fb - ib;
+ const g = (i: number, j: number) => grid[j][i] as number;
+ return (1 - w) * ((1 - u) * g(ia, ib) + u * g(ia + 1, ib)) + w * ((1 - u) * g(ia, ib + 1) + u * g(ia + 1, ib + 1));
+}
+
+export const ALPHA_RANGE: [number, number] = [0.09, 0.6];
+export const BETA_RANGE: [number, number] = [0.2, 1.3];
+
+export class SyrinxLabia {
+ private x = 0.2;
+ private y = 0;
+ /** drive 0..1 → α; tension 0..1 → β */
+ drive = 0.5;
+ tension = 0.4;
+ f0 = 3000;
+ /** 0..1 gate (syringeal muscle opening this side) */
+ gate = 1;
+ private readonly fs: number;
+ /** last opening 0..1 (telemetry) */
+ opening = 0;
+ private gateSm = 0;
+
+ constructor(fs: number, seed = 0) {
+ this.fs = fs;
+ this.x = 0.2 + 0.05 * seed;
+ }
+
+ private static rhs(x: number, y: number, a: number, b: number, out: Float64Array): void {
+ out[0] = y;
+ out[1] = -a - b * x - x * x * x - x * x * y + x * x - x * y;
+ }
+
+ private k = new Float64Array(8);
+
+ /** Advance one sample; returns the valve opening 0..1. */
+ next(): number {
+ const a = ALPHA_RANGE[0] + (ALPHA_RANGE[1] - ALPHA_RANGE[0]) * Math.max(0, Math.min(1, this.drive));
+ const b = BETA_RANGE[0] + (BETA_RANGE[1] - BETA_RANGE[0]) * Math.max(0, Math.min(1, this.tension));
+ const T = bilinear(TB.T, a, b);
+ const dtau = (T * this.f0) / this.fs;
+ const n = Math.max(1, Math.ceil(dtau / 0.06));
+ const h = dtau / n;
+ const k = this.k;
+ let x = this.x, y = this.y;
+ for (let i = 0; i < n; i++) {
+ // RK4 (allocation-free)
+ SyrinxLabia.rhs(x, y, a, b, k);
+ const k1x = k[0], k1y = k[1];
+ SyrinxLabia.rhs(x + 0.5 * h * k1x, y + 0.5 * h * k1y, a, b, k);
+ const k2x = k[0], k2y = k[1];
+ SyrinxLabia.rhs(x + 0.5 * h * k2x, y + 0.5 * h * k2y, a, b, k);
+ const k3x = k[0], k3y = k[1];
+ SyrinxLabia.rhs(x + h * k3x, y + h * k3y, a, b, k);
+ x += (h / 6) * (k1x + 2 * k2x + 2 * k3x + k[0]);
+ y += (h / 6) * (k1y + 2 * k2y + 2 * k3y + k[1]);
+ }
+ if (!Number.isFinite(x) || Math.abs(x) > 10) {
+ x = 0.2;
+ y = 0;
+ }
+ this.x = x;
+ this.y = y;
+ const lo = bilinear(TB.lo, a, b), hi = bilinear(TB.hi, a, b);
+ const u = Math.max(0, Math.min(1, (x - lo) / Math.max(1e-3, hi - lo)));
+ this.gateSm += (this.gate - this.gateSm) * 0.002;
+ const open = u * u * this.gateSm;
+ this.opening = open;
+ return open;
+ }
+}
diff --git a/src/engine/sources/syrinxTable.generated.json b/src/engine/sources/syrinxTable.generated.json
new file mode 100644
index 0000000..4e0efeb
--- /dev/null
+++ b/src/engine/sources/syrinxTable.generated.json
@@ -0,0 +1 @@
+{"alphas":[0.07,0.11416666666666667,0.15833333333333333,0.2025,0.24666666666666667,0.2908333333333334,0.335,0.3791666666666667,0.42333333333333334,0.4675,0.5116666666666667,0.5558333333333334,0.6000000000000001],"betas":[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.8999999999999999,0.9999999999999999,1.1,1.2,1.3],"T":[[null,17.204,12.545,10.62,9.463,8.66,8.055,7.577,7.184,6.853,6.568,6.319,6.098],[13.114,11.162,9.88,8.986,8.32,7.8,7.378,7.026,6.726,6.465,6.236,6.032,5.848],[10.239,9.332,8.611,8.041,7.582,7.202,6.881,6.605,6.364,6.151,5.961,5.788,5.632],[8.909,8.308,7.808,7.394,7.046,6.749,6.493,6.267,6.067,5.888,5.726,5.578,5.442],[8.059,7.61,7.23,6.907,6.629,6.387,6.175,5.985,5.815,5.661,5.521,5.392,5.272],[7.44,7.086,6.781,6.518,6.289,6.087,5.906,5.744,5.597,5.463,5.34,5.225,5.119],[6.958,6.668,6.417,6.197,6.003,5.83,5.675,5.534,5.405,5.286,5.177,5.075,4.98],[6.565,6.323,6.111,5.924,5.757,5.607,5.471,5.347,5.233,5.128,5.03,4.938,4.852],[6.235,6.03,5.849,5.687,5.542,5.41,5.29,5.18,5.078,4.983,4.895,4.812,4.734],[5.953,5.776,5.619,5.478,5.35,5.234,5.127,5.028,4.936,4.851,4.771,4.696,4.625],[5.707,5.553,5.416,5.291,5.178,5.074,4.978,4.889,4.806,4.729,4.656,4.588,4.523],[5.489,5.355,5.234,5.123,5.022,4.929,4.842,4.762,4.687,4.616,4.549,4.486,4.427],[5.296,5.177,5.069,4.971,4.88,4.796,4.717,4.644,4.575,4.511,4.45,4.392,4.337]],"lo":[[0.734,-0.616,-0.712,-0.79,-0.856,-0.914,-0.966,-1.012,-1.055,-1.094,-1.13,-1.163,-1.195],[-0.472,-0.596,-0.691,-0.769,-0.836,-0.894,-0.946,-0.992,-1.035,-1.074,-1.11,-1.144,-1.175],[-0.459,-0.579,-0.673,-0.75,-0.816,-0.874,-0.926,-0.973,-1.016,-1.055,-1.091,-1.125,-1.157],[-0.446,-0.564,-0.656,-0.733,-0.798,-0.856,-0.908,-0.954,-0.997,-1.036,-1.073,-1.107,-1.138],[-0.434,-0.55,-0.64,-0.716,-0.781,-0.839,-0.89,-0.937,-0.979,-1.019,-1.055,-1.089,-1.121],[-0.423,-0.536,-0.626,-0.7,-0.765,-0.822,-0.873,-0.92,-0.962,-1.001,-1.038,-1.072,-1.104],[-0.413,-0.524,-0.612,-0.685,-0.749,-0.806,-0.857,-0.903,-0.946,-0.985,-1.021,-1.055,-1.087],[-0.403,-0.512,-0.598,-0.671,-0.735,-0.791,-0.841,-0.887,-0.93,-0.969,-1.005,-1.039,-1.071],[-0.394,-0.501,-0.586,-0.658,-0.721,-0.776,-0.826,-0.872,-0.914,-0.953,-0.989,-1.023,-1.055],[-0.385,-0.49,-0.574,-0.645,-0.707,-0.762,-0.812,-0.857,-0.899,-0.938,-0.974,-1.008,-1.04],[-0.376,-0.48,-0.563,-0.633,-0.694,-0.749,-0.798,-0.843,-0.885,-0.924,-0.96,-0.994,-1.025],[-0.369,-0.47,-0.552,-0.621,-0.682,-0.736,-0.785,-0.83,-0.871,-0.91,-0.946,-0.979,-1.011],[-0.361,-0.461,-0.541,-0.61,-0.67,-0.723,-0.772,-0.817,-0.858,-0.896,-0.932,-0.965,-0.997]],"hi":[[0.734,0.622,0.653,0.679,0.697,0.711,0.72,0.726,0.729,0.729,0.728,0.724,0.719],[0.473,0.555,0.606,0.641,0.666,0.684,0.697,0.706,0.712,0.715,0.716,0.715,0.712],[0.433,0.519,0.574,0.613,0.641,0.662,0.678,0.689,0.697,0.702,0.705,0.706,0.704],[0.409,0.494,0.55,0.591,0.621,0.644,0.662,0.675,0.684,0.691,0.695,0.697,0.698],[0.392,0.475,0.531,0.573,0.604,0.628,0.647,0.662,0.672,0.68,0.686,0.689,0.691],[0.378,0.459,0.515,0.557,0.589,0.615,0.634,0.65,0.662,0.671,0.677,0.682,0.685],[0.366,0.445,0.501,0.544,0.576,0.602,0.622,0.639,0.652,0.662,0.669,0.675,0.678],[0.355,0.433,0.489,0.531,0.564,0.59,0.612,0.629,0.642,0.653,0.661,0.668,0.672],[0.346,0.423,0.478,0.52,0.553,0.58,0.601,0.619,0.633,0.645,0.654,0.661,0.667],[0.338,0.413,0.468,0.51,0.543,0.57,0.592,0.61,0.625,0.637,0.647,0.655,0.661],[0.33,0.404,0.458,0.5,0.534,0.561,0.583,0.602,0.617,0.63,0.64,0.648,0.655],[0.323,0.396,0.45,0.491,0.525,0.552,0.575,0.594,0.609,0.623,0.633,0.642,0.65],[0.316,0.388,0.441,0.483,0.516,0.544,0.567,0.586,0.602,0.616,0.627,0.636,0.644]]}
\ No newline at end of file
diff --git a/src/engine/sources/valves.ts b/src/engine/sources/valves.ts
new file mode 100644
index 0000000..128c675
--- /dev/null
+++ b/src/engine/sources/valves.ts
@@ -0,0 +1,230 @@
+/**
+ * Flow-induced and driven sources beyond the vocal folds.
+ * - LipReed: outward-striking "brass player's lips" valve (elephant trumpet, beatbox lip buzz)
+ * - Whistle: aerodynamic whistle at a narrow constriction (elk bugle), a van der Pol oscillator
+ * coupled to the local acoustic pressure so it pulls toward and locks onto tract resonances
+ * - ClickTrain: impulsive sources (sperm-whale phonic lips, cicada tymbal ribs)
+ * - Bubble: cavitation bubble (Rayleigh–Plesset) for the snapping shrimp
+ */
+
+/** Outward-striking lip valve: m·h'' + r·h' + k·(h − h0) = S·(p_up − p_down). Opening area = w·max(h, 0). */
+export class LipReed {
+ private h = 0;
+ private v = 0;
+ /** natural frequency (Hz) of the lip mass–spring */
+ f = 400;
+ /** damping ratio */
+ zeta = 0.12;
+ /** rest opening (cm): >0 leaks, <0 pressed together */
+ h0 = -0.01;
+ /** lip width (cm) */
+ width = 1.2;
+ /** effective pressure surface per unit mass (cm²/g) */
+ surfacePerMass = 0.08;
+ private readonly dt: number;
+ opening = 0;
+
+ constructor(fs: number) {
+ this.dt = 1 / fs;
+ }
+
+ /** Advance one sample with the pressure difference across the lips; returns the opening area (cm²). */
+ next(dp: number): number {
+ const w = 2 * Math.PI * this.f;
+ const acc = this.surfacePerMass * dp - 2 * this.zeta * w * this.v - w * w * (this.h - this.h0);
+ // semi-implicit Euler (stable for w·dt < 1 at the internal rate)
+ this.v += acc * this.dt;
+ this.h += this.v * this.dt;
+ // the lips cannot interpenetrate: inelastic collision at h = 0 with tissue compliance
+ if (this.h < -0.05) {
+ this.h = -0.05;
+ if (this.v < 0) this.v = 0;
+ }
+ if (this.h > 0.8) {
+ this.h = 0.8;
+ if (this.v > 0) this.v = 0;
+ }
+ const a = this.h > 0 ? this.h * this.width : 0;
+ this.opening = a;
+ return a;
+ }
+}
+
+/**
+ * Supraglottal whistle: van der Pol oscillator excited by the jet (flow through the constriction)
+ * and coupled to the local acoustic pressure, so its frequency is pulled toward the tract's
+ * resonances (the elk bugle's G0 hops between formants as the tract lengthens).
+ */
+export class Whistle {
+ private x = 0.01;
+ private v = 0;
+ /** target frequency (Hz) */
+ f = 2200;
+ /** coupling to the local pressure (frequency pulling) */
+ coupling = 0.6;
+ private readonly dt: number;
+ out = 0;
+
+ constructor(fs: number) {
+ this.dt = 1 / fs;
+ }
+
+ /** drive 0..1 (jet strength), pLocal = acoustic pressure at the whistle (dyn/cm²). Returns a pressure source (dyn/cm²). */
+ next(drive: number, pLocal: number, gain: number): number {
+ const w = 2 * Math.PI * this.f;
+ const mu = 0.15 * drive;
+ // x'' − μ w (1 − x²) x' + w² x = c·w²·p̂
+ const pn = Math.max(-1, Math.min(1, pLocal / 2000));
+ const acc = mu * w * (1 - this.x * this.x) * this.v - w * w * this.x + this.coupling * w * w * pn * drive;
+ this.v += acc * this.dt;
+ this.x += this.v * this.dt;
+ if (!Number.isFinite(this.x) || Math.abs(this.x) > 5) {
+ this.x = 0.01;
+ this.v = 0;
+ }
+ if (drive < 0.02) {
+ this.x *= 0.999;
+ this.v *= 0.999;
+ }
+ this.out = this.x * gain * drive;
+ return this.out;
+ }
+}
+
+/** Impulse source: smooth pulses (raised cosine) triggered by events, optionally ringing (tymbal ribs). */
+export class ClickTrain {
+ private readonly fs: number;
+ private pending: { at: number; amp: number }[] = [];
+ private t = 0;
+ /** click width (s) */
+ width = 0.0004;
+ /** ring frequency (Hz) and decay (s) for each click; ring = 0 → plain pulse */
+ ring = 0;
+ ringDecay = 0.002;
+ private active: { start: number; amp: number }[] = [];
+
+ constructor(fs: number) {
+ this.fs = fs;
+ }
+
+ /** Schedule a click after `delay` seconds. */
+ click(delay: number, amp = 1): void {
+ this.pending.push({ at: this.t + delay, amp });
+ }
+
+ clear(): void {
+ this.pending.length = 0;
+ this.active.length = 0;
+ }
+
+ /** Advance one sample; returns the source value (unit-ish). */
+ next(): number {
+ const t = this.t;
+ if (this.pending.length) {
+ for (let i = this.pending.length - 1; i >= 0; i--) {
+ if (this.pending[i].at <= t) {
+ this.active.push({ start: this.pending[i].at, amp: this.pending[i].amp });
+ this.pending.splice(i, 1);
+ }
+ }
+ }
+ let y = 0;
+ for (let i = this.active.length - 1; i >= 0; i--) {
+ const c = this.active[i];
+ const age = t - c.start;
+ const life = this.ring > 0 ? this.width + 6 * this.ringDecay : this.width;
+ if (age > life) {
+ this.active.splice(i, 1);
+ continue;
+ }
+ if (this.ring > 0) {
+ const env = age < this.width ? age / this.width : Math.exp(-(age - this.width) / this.ringDecay);
+ y += c.amp * env * Math.sin(2 * Math.PI * this.ring * age);
+ } else {
+ y += c.amp * 0.5 * (1 - Math.cos((2 * Math.PI * age) / this.width));
+ }
+ }
+ this.t += 1 / this.fs;
+ return y;
+ }
+}
+
+/**
+ * Cavitation bubble in water (Rayleigh–Plesset):
+ * R R'' + 1.5 R'² = (p_gas(R) − p∞(t) − 2σ/R − 4μ R'/R) / ρ
+ * A "snap" drops the ambient pressure (the claw's jet), the bubble grows, then collapses violently.
+ * Radiated pressure ∝ d²V/dt² = 4π(R²R'' + 2RR'²).
+ */
+export class Bubble {
+ private R: number;
+ private Rd = 0;
+ /** equilibrium radius (m) */
+ R0 = 0.0005;
+ private readonly dt: number;
+ private tension = 0.072;
+ private viscosity = 0.0015; // effective, includes thermal/acoustic damping
+ private rho = 1000;
+ private p0 = 101325;
+ private kappa = 1.33;
+ /** ambient pressure drop (Pa) while the jet passes, and its time course */
+ private dropUntil = 0;
+ private dropAmount = 0;
+ private t = 0;
+ out = 0;
+
+ constructor(fs: number) {
+ this.dt = 1 / fs;
+ this.R = this.R0;
+ }
+
+ /** Trigger a snap: the ambient pressure falls for `dur` seconds (larger drop → larger bubble). */
+ snap(strength: number, dur = 0.0012): void {
+ this.dropAmount = this.p0 * (0.9 + 0.09 * Math.max(0, Math.min(1, strength)));
+ this.dropUntil = this.t + dur;
+ this.R = Math.max(this.R, this.R0);
+ }
+
+ private acc(R: number, Rd: number, pinf: number): number {
+ const pg = (this.p0 + (2 * this.tension) / this.R0) * Math.pow(this.R0 / R, 3 * this.kappa);
+ return ((pg - pinf - (2 * this.tension) / R - (4 * this.viscosity * Rd) / R) / this.rho - 1.5 * Rd * Rd) / R;
+ }
+
+ /** Advance one audio sample (with adaptive sub-stepping for the collapse); returns radiated pressure (arb.). */
+ next(): number {
+ const pinf = this.t < this.dropUntil ? this.p0 - this.dropAmount : this.p0;
+ let R = this.R, Rd = this.Rd;
+ // sub-steps: the collapse is stiff
+ const speed = Math.abs(Rd) / Math.max(R, 1e-6);
+ const n = Math.min(64, Math.max(2, Math.ceil(speed * this.dt * 20)));
+ const h = this.dt / n;
+ let a = 0;
+ for (let i = 0; i < n; i++) {
+ // velocity-Verlet-like midpoint step
+ const a1 = this.acc(R, Rd, pinf);
+ const Rm = R + 0.5 * h * Rd;
+ const Rdm = Rd + 0.5 * h * a1;
+ a = this.acc(Math.max(Rm, this.R0 * 0.02), Rdm, pinf);
+ R += h * Rdm;
+ Rd += h * a;
+ if (R < this.R0 * 0.02) {
+ R = this.R0 * 0.02;
+ Rd = Math.abs(Rd) * 0.3; // lossy rebound
+ }
+ }
+ if (!Number.isFinite(R) || !Number.isFinite(Rd)) {
+ R = this.R0;
+ Rd = 0;
+ }
+ this.R = R;
+ this.Rd = Rd;
+ this.t += this.dt;
+ // d²V/dt² / 4π
+ const y = R * R * a + 2 * R * Rd * Rd;
+ this.out = y;
+ return y;
+ }
+
+ get radius(): number {
+ return this.R;
+ }
+}
diff --git a/src/main.tsx b/src/main.tsx
index cae418c..d55e15e 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -2,6 +2,10 @@ import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./ui/App.tsx";
import "./ui/styles.css";
+import { engine } from "./audio/AudioEngine.ts";
+
+// console/debug handle (used by the browser smoke test)
+(window as unknown as { __chimeraEngine: typeof engine }).__chimeraEngine = engine;
createRoot(document.getElementById("root")!).render(
<StrictMode>
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 7f55398..c015849 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -11,6 +11,12 @@ import { ArticPanel } from "./components/ArticPanel.tsx";
import { Keys } from "./components/Keys.tsx";
import { Segmented, Toggle } from "./components/Controls.tsx";
import { SpeakPanel } from "./components/SpeakPanel.tsx";
+import { BestiaryPanel } from "./components/BestiaryPanel.tsx";
+import { CreatureView } from "./components/CreatureView.tsx";
+import { Spectrogram } from "./components/Spectrogram.tsx";
+import { Scope } from "./components/Scope.tsx";
+import { CreatureTubes } from "./components/CreatureTubes.tsx";
+import { creatureById } from "../engine/creatures/index.ts";
import type { Mode } from "./store.ts";
import type { BodyName } from "../worklet/protocol.ts";
@@ -26,7 +32,7 @@ function TopBar() {
const setMode = useStore((s) => s.setMode);
const [load, setLoad] = useState(0);
useEffect(() => {
- const id = setInterval(() => setLoad(engine.latest?.load ?? 0), 500);
+ const id = setInterval(() => setLoad(engine.load), 500);
return () => clearInterval(id);
}, []);
return (
@@ -42,18 +48,21 @@ function TopBar() {
options={[
{ value: "play", label: "Play" },
{ value: "speak", label: "Speak" },
+ { value: "bestiary", label: "Bestiary" },
]}
/>
- <Segmented<BodyName>
- label="Body"
- value={body}
- onChange={setBody}
- options={[
- { value: "male", label: "Adult male" },
- { value: "female", label: "Adult female" },
- { value: "child", label: "Child" },
- ]}
- />
+ {mode !== "bestiary" && (
+ <Segmented<BodyName>
+ label="Body"
+ value={body}
+ onChange={setBody}
+ options={[
+ { value: "male", label: "Adult male" },
+ { value: "female", label: "Adult female" },
+ { value: "child", label: "Child" },
+ ]}
+ />
+ )}
<div className="topbar-right">
<label className="volume">
<span>Volume</span>
@@ -76,12 +85,13 @@ function TopBar() {
function ViewToggles() {
const view = useStore((s) => s.view);
const setView = useStore((s) => s.setView);
+ const bestiary = useStore((s) => s.mode === "bestiary");
return (
<div className="view-toggles">
<Toggle label="Sound pressure" checked={view.pressure} onChange={(v) => setView({ pressure: v })} />
- <Toggle label="Airflow" checked={view.particles} onChange={(v) => setView({ particles: v })} />
- <Toggle label="Measurements" checked={view.calipers} onChange={(v) => setView({ calipers: v })} />
- <Toggle label="Grid" checked={view.grid} onChange={(v) => setView({ grid: v })} />
+ {!bestiary && <Toggle label="Airflow" checked={view.particles} onChange={(v) => setView({ particles: v })} />}
+ <Toggle label={bestiary ? "Labels" : "Measurements"} checked={view.calipers} onChange={(v) => setView({ calipers: v })} />
+ {!bestiary && <Toggle label="Grid" checked={view.grid} onChange={(v) => setView({ grid: v })} />}
</div>
);
}
@@ -92,21 +102,30 @@ function StartPrompt() {
const err = useStore((s) => s.startError);
const start = useStore((s) => s.start);
const setHold = useStore((s) => s.setHold);
+ const bestiary = useStore((s) => s.mode === "bestiary");
+ const playCall = useStore((s) => s.playCall);
+ const creature = useStore((s) => s.creature);
if (started) return null;
return (
<div className="start-prompt">
- <p>Every sound here is produced by simulating air moving through a throat, mouth and nose.</p>
+ <p>{bestiary ? "Each animal's sound comes from a simulation of its own sound source and airway." : "Every sound here is produced by simulating air moving through a throat, mouth and nose."}</p>
<button
className="primary large"
disabled={starting}
onClick={async () => {
await start();
- setHold(true);
+ const first = creatureById(creature)?.calls[0];
+ if (bestiary && first) playCall(first.id);
+ else if (!bestiary) setHold(true);
}}
>
- {starting ? "Starting…" : "Breathe in and start"}
+ {starting ? "Starting…" : bestiary ? "Start and hear a call" : "Breathe in and start"}
</button>
- {err ? <p className="error">Audio could not start: {err}. Reload the page and try again.</p> : <p className="hint">Then drag the tongue, lips or jaw, or play the keys.</p>}
+ {err ? (
+ <p className="error">Audio could not start: {err}. Reload the page and try again.</p>
+ ) : (
+ <p className="hint">{bestiary ? "Then play its calls, or hold the keys to sustain it at a pitch." : "Then drag the tongue, lips or jaw, or play the keys."}</p>
+ )}
</div>
);
}
@@ -114,6 +133,7 @@ function StartPrompt() {
function Deck() {
const mode = useStore((s) => s.mode);
if (mode === "speak") return <SpeakPanel />;
+ if (mode === "bestiary") return <BestiaryPanel />;
return (
<>
<section className="deck">
@@ -131,30 +151,61 @@ function Deck() {
);
}
+function Instruments() {
+ const bestiary = useStore((s) => s.mode === "bestiary");
+ if (bestiary)
+ return (
+ <aside className="instruments">
+ <figure className="instrument">
+ <figcaption>Spectrogram</figcaption>
+ <Spectrogram />
+ </figure>
+ <figure className="instrument">
+ <figcaption>Waveform, three cycles</figcaption>
+ <Scope />
+ </figure>
+ <figure className="instrument">
+ <figcaption>Airway, each tube unrolled</figcaption>
+ <CreatureTubes />
+ </figure>
+ </aside>
+ );
+ return (
+ <aside className="instruments">
+ <figure className="instrument">
+ <figcaption>Tube, glottis to lips</figcaption>
+ <TubeView />
+ </figure>
+ <figure className="instrument">
+ <figcaption>Vocal folds, slowed down</figcaption>
+ <Stroboscope />
+ </figure>
+ <figure className="instrument">
+ <figcaption>Spectrum and resonances</figcaption>
+ <SpectrumView />
+ </figure>
+ </aside>
+ );
+}
+
+function Viewport() {
+ const bestiary = useStore((s) => s.mode === "bestiary");
+ return (
+ <section className="viewport" aria-label={bestiary ? "Live creature airway" : "Live vocal tract"}>
+ {bestiary ? <CreatureView /> : <AnatomyView />}
+ <StartPrompt />
+ <ViewToggles />
+ </section>
+ );
+}
+
export function App() {
return (
<div className="app">
<TopBar />
<main className="stage">
- <section className="viewport" aria-label="Live vocal tract">
- <AnatomyView />
- <StartPrompt />
- <ViewToggles />
- </section>
- <aside className="instruments">
- <figure className="instrument">
- <figcaption>Tube, glottis to lips</figcaption>
- <TubeView />
- </figure>
- <figure className="instrument">
- <figcaption>Vocal folds, slowed down</figcaption>
- <Stroboscope />
- </figure>
- <figure className="instrument">
- <figcaption>Spectrum and resonances</figcaption>
- <SpectrumView />
- </figure>
- </aside>
+ <Viewport />
+ <Instruments />
</main>
<Deck />
</div>
diff --git a/src/ui/components/BestiaryPanel.tsx b/src/ui/components/BestiaryPanel.tsx
new file mode 100644
index 0000000..1ad7fa2
--- /dev/null
+++ b/src/ui/components/BestiaryPanel.tsx
@@ -0,0 +1,123 @@
+import { memo } from "react";
+import { useStore } from "../store.ts";
+import { CREATURES, creatureById } from "../../engine/creatures/index.ts";
+import type { CreatureDef } from "../../engine/creatures/types.ts";
+import { useLiveCreature } from "../creatureLive.ts";
+import { Slider } from "./Controls.tsx";
+import { Keys } from "./Keys.tsx";
+
+/** Scout-image thumbnail: the creature's outline with its airway traced in black. */
+const Thumb = memo(function Thumb({ def }: { def: CreatureDef }) {
+ const v = def.visual;
+ const vw = v.view.x1 - v.view.x0, vh = v.view.y1 - v.view.y0;
+ const pad = Math.max(vw, vh) * 0.06;
+ const pts = (p: [number, number][]) => p.map(([x, y]) => `${x},${-y}`).join(" ");
+ return (
+ <svg className="thumb" viewBox={`${v.view.x0 - pad} ${-v.view.y1 - pad} ${vw + 2 * pad} ${vh + 2 * pad}`} preserveAspectRatio="xMidYMid meet" aria-hidden="true">
+ <polygon points={pts(v.silhouette)} fill="#8a8a8a" stroke="#bdbdbd" strokeWidth={Math.max(vw, vh) * 0.012} strokeLinejoin="round" />
+ {v.tubes.map((t) => (
+ <polyline key={t.tube} points={pts(t.path)} fill="none" stroke="#000" strokeWidth={Math.max(vw, vh) * 0.022} strokeLinecap="round" strokeLinejoin="round" />
+ ))}
+ </svg>
+ );
+});
+
+function Gallery() {
+ const creature = useStore((s) => s.creature);
+ const setCreature = useStore((s) => s.setCreature);
+ return (
+ <div className="panel gallery">
+ <h2>Creatures</h2>
+ <div className="specimens">
+ {CREATURES.map((c) => (
+ <button key={c.id} className={`specimen${c.id === creature ? " on" : ""}`} onClick={() => setCreature(c.id)} aria-pressed={c.id === creature}>
+ <Thumb def={c} />
+ <span className="specimen-name">{c.name}</span>
+ <span className="specimen-latin">{c.latin}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function Calls({ def }: { def: CreatureDef }) {
+ const playCall = useStore((s) => s.playCall);
+ const hold = useStore((s) => s.hold);
+ const setHold = useStore((s) => s.setHold);
+ const keyCall = useStore((s) => s.keyCall);
+ const setKeyCall = useStore((s) => s.setKeyCall);
+ const live = useLiveCreature(def.id);
+ return (
+ <div className="panel calls-panel">
+ <h2>Calls</h2>
+ <div className="calls">
+ {def.calls.map((c) => (
+ <button key={c.id} className={`call${live?.call === c.id ? " playing" : ""}`} onClick={() => playCall(c.id)}>
+ <span className="call-name">{c.name}</span>
+ <span className="call-hint">{c.hint}</span>
+ </button>
+ ))}
+ <button className={`call sustain${hold ? " on" : ""}`} onClick={() => setHold(!hold)} aria-pressed={hold}>
+ <span className="call-name">{hold ? "Stop sustaining" : "Sustain"}</span>
+ <span className="call-hint">Keep the breath on and shape the sound with the sliders</span>
+ </button>
+ </div>
+ <div className="keys-mode" role="radiogroup" aria-label="What the keys play">
+ <span className="dim">Keys play</span>
+ <button role="radio" aria-checked={keyCall === null} className={`chip${keyCall === null ? " on" : ""}`} onClick={() => setKeyCall(null)}>
+ Held voice
+ </button>
+ {def.calls.map((c) => (
+ <button key={c.id} role="radio" aria-checked={keyCall === c.id} className={`chip${keyCall === c.id ? " on" : ""}`} onClick={() => setKeyCall(c.id)}>
+ {c.name}
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function fmt(v: number, p: CreatureDef["params"][number]): string {
+ const digits = p.digits ?? (p.max - p.min <= 2 ? 2 : v < 100 && p.log ? 1 : 0);
+ return `${v.toFixed(digits)}${p.unit ? " " + p.unit : ""}`;
+}
+
+function Params({ def }: { def: CreatureDef }) {
+ const cparams = useStore((s) => s.cparams[def.id]);
+ const setCParam = useStore((s) => s.setCParam);
+ const live = useLiveCreature(def.id);
+ // while a call plays, the sliders follow its automation; afterwards they return to yours
+ const calling = !!live?.call;
+ return (
+ <div className="panel creature-params">
+ <h2>{def.name}</h2>
+ <p className="creature-role">{def.role}</p>
+ <p className="creature-blurb">{def.blurb}</p>
+ <div className="creature-sliders">
+ {def.params.map((p) => {
+ const mine = cparams?.[p.key] ?? p.default;
+ const value = calling ? (live!.params[p.key] ?? mine) : mine;
+ return <Slider key={p.key} label={p.label} value={value} min={p.min} max={p.max} log={p.log} onChange={(v) => setCParam(p.key, v)} format={(v) => fmt(v, p)} />;
+ })}
+ </div>
+ </div>
+ );
+}
+
+export function BestiaryPanel() {
+ const creature = useStore((s) => s.creature);
+ const def = creatureById(creature);
+ return (
+ <>
+ <section className="bestiary">
+ <Gallery />
+ {def && <Calls def={def} />}
+ {def && <Params def={def} />}
+ </section>
+ <footer className="keys-bar">
+ <Keys />
+ </footer>
+ </>
+ );
+}
diff --git a/src/ui/components/CreatureTubes.tsx b/src/ui/components/CreatureTubes.tsx
new file mode 100644
index 0000000..f04e1cf
--- /dev/null
+++ b/src/ui/components/CreatureTubes.tsx
@@ -0,0 +1,44 @@
+import { useCanvasLoop, font } from "../useCanvas.ts";
+import { useStore } from "../store.ts";
+import { creatureById } from "../../engine/creatures/index.ts";
+import { liveTelemetry, previewTelemetry } from "../creatureLive.ts";
+import { C, hot, pressureLevel } from "../colors.ts";
+
+const a2d = (A: number) => 2 * Math.sqrt(Math.max(0, A) / Math.PI);
+
+/** Each airway tube unrolled into a lane: diameter profile (shared scale) lit by acoustic pressure. */
+export function CreatureTubes() {
+ const ref = useCanvasLoop(({ ctx, w, h }) => {
+ const st = useStore.getState();
+ const def = creatureById(st.creature);
+ ctx.clearRect(0, 0, w, h);
+ if (!def) return;
+ const live = liveTelemetry(def.id);
+ const tele = live ?? previewTelemetry(def, st.cparams[def.id]);
+ const lanes = def.visual.tubes.filter((t) => tele.tubes[t.tube]);
+ if (!lanes.length) return;
+ let dMax = 0.01;
+ for (const l of lanes) for (const a of tele.tubes[l.tube].areas) dMax = Math.max(dMax, a2d(a));
+ const labelW = 92;
+ const laneH = (h - 2) / lanes.length;
+ ctx.font = font(11);
+ lanes.forEach((l, li) => {
+ const data = tele.tubes[l.tube];
+ const y = 1 + laneH * (li + 0.5);
+ ctx.fillStyle = C.textDim;
+ ctx.fillText(l.label ?? l.tube, 0, y + 4);
+ const n = data.areas.length;
+ const x0 = labelW, x1 = w - 2;
+ const dx = (x1 - x0) / n;
+ for (let k = 0; k < n; k++) {
+ const d = Math.max(1, (a2d(data.areas[k]) / dMax) * (laneH - 4));
+ if (live) {
+ const [r, g, b] = hot(0.08 + 0.92 * pressureLevel(data.rms[k] * 0.6));
+ ctx.fillStyle = `rgb(${r | 0},${g | 0},${b | 0})`;
+ } else ctx.fillStyle = "#5b6368";
+ ctx.fillRect(x0 + k * dx, y - d / 2, Math.max(1, dx - 0.6), d);
+ }
+ });
+ });
+ return <canvas ref={ref} className="instrument-canvas" aria-label="Airway tubes unrolled, lit by sound pressure" role="img" />;
+}
diff --git a/src/ui/components/CreatureView.tsx b/src/ui/components/CreatureView.tsx
new file mode 100644
index 0000000..d0e238a
--- /dev/null
+++ b/src/ui/components/CreatureView.tsx
@@ -0,0 +1,254 @@
+import { useRef } from "react";
+import { useCanvasLoop, font } from "../useCanvas.ts";
+import { useStore } from "../store.ts";
+import { creatureById } from "../../engine/creatures/index.ts";
+import type { CreatureDef } from "../../engine/creatures/types.ts";
+import { liveTelemetry, previewTelemetry } from "../creatureLive.ts";
+import { C, hot, pressureLevel } from "../colors.ts";
+
+type P = [number, number];
+
+/** Catmull-Rom through the points; closed shapes wrap around. */
+function smooth(pts: P[], per: number, closed: boolean): P[] {
+ const n = pts.length;
+ if (n < 3) return pts.slice();
+ const at = (i: number) => (closed ? pts[(i + n) % n] : pts[Math.max(0, Math.min(n - 1, i))]);
+ const out: P[] = [];
+ const segs = closed ? n : n - 1;
+ for (let i = 0; i < segs; i++) {
+ const p0 = at(i - 1), p1 = at(i), p2 = at(i + 1), p3 = at(i + 2);
+ for (let k = 0; k < per; k++) {
+ const t = k / per, t2 = t * t, t3 = t2 * t;
+ const f = (a: number, b: number, c: number, d: number) => 0.5 * (2 * b + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * t2 + (-a + 3 * b - 3 * c + d) * t3);
+ out.push([f(p0[0], p1[0], p2[0], p3[0]), f(p0[1], p1[1], p2[1], p3[1])]);
+ }
+ }
+ if (!closed) out.push(pts[n - 1]);
+ return out;
+}
+
+interface TubeGeom {
+ tube: string;
+ label?: string;
+ inView: boolean;
+ pts: P[];
+ cum: number[];
+ length: number;
+}
+
+interface Geom {
+ silhouette: P[];
+ parts: { shade: number; pts: P[] }[];
+ tubes: TubeGeom[];
+}
+
+const geoms = new Map<string, Geom>();
+function geometry(def: CreatureDef): Geom {
+ let g = geoms.get(def.id);
+ if (g) return g;
+ const v = def.visual;
+ g = {
+ silhouette: smooth(v.silhouette, 8, true),
+ parts: (v.parts ?? []).map((p) => ({ shade: p.shade, pts: smooth(p.pts, 6, true) })),
+ tubes: v.tubes.map((t) => {
+ const pts = smooth(t.path, 6, false);
+ const cum = [0];
+ for (let i = 1; i < pts.length; i++) cum.push(cum[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
+ return { tube: t.tube, label: t.label, inView: t.inView !== false, pts, cum, length: cum[cum.length - 1] };
+ }),
+ };
+ geoms.set(def.id, g);
+ return g;
+}
+
+function pointAt(t: TubeGeom, s: number): P {
+ let i = 1;
+ while (i < t.cum.length - 1 && t.cum[i] < s) i++;
+ const u = Math.max(0, Math.min(1, (s - t.cum[i - 1]) / Math.max(1e-9, t.cum[i] - t.cum[i - 1])));
+ return [t.pts[i - 1][0] + (t.pts[i][0] - t.pts[i - 1][0]) * u, t.pts[i - 1][1] + (t.pts[i][1] - t.pts[i - 1][1]) * u];
+}
+
+/**
+ * Creature cross-section in the same visual language as the human MRI view: tissue silhouette,
+ * black airway channels whose width follows the simulated cross-section, acoustic pressure in
+ * the hot scale, and source glyphs whose ripples follow the vibration.
+ */
+export function CreatureView() {
+ const grainRef = useRef<CanvasPattern | null>(null);
+ const glyph = useRef<{ peak: Record<string, number>; phase: Record<string, number> }>({ peak: {}, phase: {} });
+ const ref = useCanvasLoop(({ ctx, w, h, dt }) => {
+ const st = useStore.getState();
+ const def = creatureById(st.creature);
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, w, h);
+ if (!def) return;
+ const vis = def.visual;
+ const geo = geometry(def);
+ const live = liveTelemetry(def.id);
+ const tele = live ?? previewTelemetry(def, st.cparams[def.id]);
+ const vw = vis.view.x1 - vis.view.x0, vh = vis.view.y1 - vis.view.y0;
+ const sc = Math.min((w * 0.84) / vw, (h * 0.7) / vh);
+ const ox = w / 2 - ((vis.view.x0 + vis.view.x1) / 2) * sc;
+ const oy = h * 0.53 + ((vis.view.y0 + vis.view.y1) / 2) * sc;
+ const X = (x: number) => ox + x * sc;
+ const Y = (y: number) => oy - y * sc;
+ if (!grainRef.current) {
+ const g = document.createElement("canvas");
+ g.width = g.height = 160;
+ const gc = g.getContext("2d")!;
+ const img = gc.createImageData(160, 160);
+ for (let i = 0; i < img.data.length; i += 4) {
+ const v = 128 + (Math.random() + Math.random() + Math.random() - 1.5) * 90;
+ img.data[i] = img.data[i + 1] = img.data[i + 2] = v;
+ img.data[i + 3] = 255;
+ }
+ gc.putImageData(img, 0, 0);
+ grainRef.current = ctx.createPattern(g, "repeat");
+ }
+ const path = (pts: P[]) => {
+ ctx.beginPath();
+ pts.forEach(([x, y], i) => (i ? ctx.lineTo(X(x), Y(y)) : ctx.moveTo(X(x), Y(y))));
+ ctx.closePath();
+ };
+ // tissue: bright subcutaneous fat rim around darker muscle, T1-like
+ const span = Math.min(vw * sc, vh * sc * 2.5);
+ ctx.save();
+ path(geo.silhouette);
+ ctx.clip();
+ ctx.fillStyle = C.muscle;
+ ctx.fill();
+ ctx.lineJoin = "round";
+ ctx.strokeStyle = C.fat;
+ ctx.lineWidth = Math.max(5, span * 0.018);
+ ctx.stroke();
+ ctx.strokeStyle = C.skin;
+ ctx.lineWidth = Math.max(2, span * 0.006);
+ ctx.stroke();
+ for (const part of geo.parts) {
+ path(part.pts);
+ const v = Math.round(part.shade * 255);
+ ctx.fillStyle = `rgb(${v},${v},${v})`;
+ ctx.fill();
+ }
+ if (grainRef.current) {
+ ctx.globalCompositeOperation = "overlay";
+ ctx.globalAlpha = 0.2;
+ ctx.fillStyle = grainRef.current;
+ ctx.fillRect(0, 0, w, h);
+ ctx.globalAlpha = 1;
+ ctx.globalCompositeOperation = "source-over";
+ }
+ ctx.restore();
+ // airway channels: drawn wider than life so narrow tubes stay legible
+ const exaggerate = vis.tubeScale ?? 1.6;
+ ctx.lineCap = "round";
+ const labels: { text: string; x: number; y: number }[] = [];
+ for (const tg of geo.tubes) {
+ const data = tele.tubes[tg.tube];
+ if (!data) continue;
+ const n = data.areas.length;
+ const width = (k: number) => 2 * Math.sqrt(Math.max(0, data.areas[k]) / Math.PI) * exaggerate * sc;
+ // walls first (mucosa), then lumen, then pressure
+ for (let pass = 0; pass < 3; pass++) {
+ for (let k = 0; k < n; k++) {
+ const a = pointAt(tg, (k / n) * tg.length), b = pointAt(tg, ((k + 1) / n) * tg.length);
+ const d = width(k);
+ ctx.beginPath();
+ ctx.moveTo(X(a[0]), Y(a[1]));
+ ctx.lineTo(X(b[0]), Y(b[1]));
+ if (pass === 0) {
+ ctx.strokeStyle = C.mucosa;
+ ctx.lineWidth = d + 3;
+ } else if (pass === 1) {
+ ctx.strokeStyle = "#000";
+ ctx.lineWidth = Math.max(1.5, d);
+ } else {
+ if (!live || !st.view.pressure) break;
+ const lvl = pressureLevel(data.rms[k] * 0.6);
+ if (lvl < 0.02) continue;
+ const [r, g, bb] = hot(lvl);
+ ctx.strokeStyle = `rgba(${r | 0},${g | 0},${bb | 0},${0.5 + 0.5 * lvl})`;
+ ctx.lineWidth = Math.max(1.2, d - 1);
+ }
+ ctx.stroke();
+ }
+ }
+ if (tg.label && tg.inView) {
+ const m = pointAt(tg, tg.length * 0.5);
+ labels.push({ text: tg.label, x: X(m[0]) + 10, y: Y(m[1]) - 10 });
+ }
+ }
+ // source glyphs: a ring sized by the vibration envelope, ripples paced by the pitch
+ const pp = def.params.find((p) => p.role === "pitch");
+ const pitch = pp ? (live ? live.params[pp.key] : (st.cparams[def.id]?.[pp.key] ?? pp.default)) : 200;
+ const rate = 1.2 + 4.8 * Math.max(0, Math.min(1, Math.log(pitch / 10) / Math.log(900)));
+ for (const s of vis.sources ?? []) {
+ const raw = Math.max(0, Math.min(1, live?.source[s.key] ?? 0));
+ const pk = Math.max(raw, (glyph.current.peak[s.key] ?? 0) * Math.exp(-dt / 0.18));
+ glyph.current.peak[s.key] = pk;
+ const ph = ((glyph.current.phase[s.key] ?? 0) + dt * rate) % 1;
+ glyph.current.phase[s.key] = ph;
+ const x = X(s.at[0]), y = Y(s.at[1]);
+ const r0 = 3.5 + 6 * pk;
+ if (pk > 0.04) {
+ for (let j = 0; j < 3; j++) {
+ const u = (ph + j / 3) % 1;
+ ctx.beginPath();
+ ctx.arc(x, y, r0 + u * 24, 0, Math.PI * 2);
+ ctx.strokeStyle = `rgba(242,207,91,${(1 - u) * Math.min(1, pk * 1.3) * 0.7})`;
+ ctx.lineWidth = 1;
+ ctx.stroke();
+ }
+ }
+ ctx.beginPath();
+ ctx.arc(x, y, r0, 0, Math.PI * 2);
+ ctx.strokeStyle = C.caliper;
+ ctx.lineWidth = 1.5;
+ ctx.stroke();
+ ctx.beginPath();
+ ctx.arc(x, y, 1.8, 0, Math.PI * 2);
+ ctx.fillStyle = C.caliper;
+ ctx.fill();
+ labels.push({ text: s.label, x: x + 14, y: y + 18 });
+ }
+ if (st.view.calipers) {
+ // place labels, nudging down past any earlier label they would overlap
+ ctx.font = font(11.5);
+ const placed: { x0: number; x1: number; y0: number; y1: number }[] = [];
+ for (const l of labels) {
+ const tw = ctx.measureText(l.text).width;
+ const x = Math.min(w - tw - 6, l.x);
+ let y = l.y;
+ for (let guard = 0; guard < 8; guard++) {
+ const hit = placed.find((r) => x < r.x1 + 4 && x + tw > r.x0 - 4 && y - 11 < r.y1 && y + 2 > r.y0);
+ if (!hit) break;
+ y = hit.y1 + 12;
+ }
+ placed.push({ x0: x, x1: x + tw, y0: y - 11, y1: y + 2 });
+ const isSource = (vis.sources ?? []).some((s) => s.label === l.text);
+ ctx.lineJoin = "round";
+ ctx.lineWidth = 3.5;
+ ctx.strokeStyle = "rgba(0,0,0,0.85)";
+ ctx.strokeText(l.text, x, y);
+ ctx.fillStyle = isSource ? C.caliper : "rgba(232,234,235,0.82)";
+ ctx.fillText(l.text, x, y);
+ }
+ }
+ // corner overlays
+ ctx.font = font(14, 600, 112);
+ ctx.fillStyle = "rgba(232,234,235,0.9)";
+ ctx.fillText(def.name, 14, 26);
+ ctx.font = `italic ${font(12.5)}`;
+ ctx.fillStyle = C.textDim;
+ ctx.fillText(def.latin, 14, 44);
+ ctx.textAlign = "right";
+ ctx.font = font(12.5);
+ ctx.fillStyle = "rgba(232,234,235,0.85)";
+ if (pp) ctx.fillText(`${pitch.toFixed(pp.digits ?? (pitch < 100 ? 1 : 0))} ${pp.unit ?? ""}`.trim(), w - 14, 26);
+ const state = live ? (live.call ? (def.calls.find((c) => c.id === live.call)?.name ?? live.call) : live.gate > 0.05 ? "Sustaining" : "At rest") : "Not started";
+ ctx.fillStyle = C.textDim;
+ ctx.fillText(state, w - 14, 44);
+ ctx.textAlign = "left";
+ });
+ return <canvas ref={ref} className="creature-canvas" aria-label="Creature airway cross-section" role="img" />;
+}
diff --git a/src/ui/components/Scope.tsx b/src/ui/components/Scope.tsx
new file mode 100644
index 0000000..e5a151e
--- /dev/null
+++ b/src/ui/components/Scope.tsx
@@ -0,0 +1,68 @@
+import { useRef } from "react";
+import { useCanvasLoop, font } from "../useCanvas.ts";
+import { engine } from "../../audio/AudioEngine.ts";
+import { useStore } from "../store.ts";
+import { creatureById } from "../../engine/creatures/index.ts";
+import { liveTelemetry } from "../creatureLive.ts";
+import { C } from "../colors.ts";
+
+/** Output waveform, triggered on a rising zero crossing and spanning three cycles of the pitch. */
+export function Scope() {
+ const buf = useRef<Float32Array | null>(null);
+ const gainRef = useRef(1);
+ const ref = useCanvasLoop(({ ctx, w, h, dt }) => {
+ const st = useStore.getState();
+ ctx.clearRect(0, 0, w, h);
+ const mid = h / 2;
+ ctx.strokeStyle = "rgba(255,255,255,0.08)";
+ ctx.beginPath();
+ ctx.moveTo(0, mid);
+ ctx.lineTo(w, mid);
+ ctx.stroke();
+ const an = engine.analyserScope;
+ if (!an || !st.started) return;
+ if (!buf.current || buf.current.length !== an.fftSize) buf.current = new Float32Array(an.fftSize);
+ const b = buf.current;
+ an.getFloatTimeDomainData(b as Float32Array<ArrayBuffer>);
+ const sr = engine.sampleRate;
+ const def = creatureById(st.creature);
+ const pp = def?.params.find((p) => p.role === "pitch");
+ const tele = def ? liveTelemetry(def.id) : null;
+ const f0 = pp && tele ? tele.params[pp.key] : 200;
+ const win = Math.round(Math.min(b.length / 2, Math.max(0.004 * sr, Math.min(0.3 * sr, (3 * sr) / f0))));
+ // latest rising zero crossing that leaves a full window after it
+ let start = b.length - win;
+ for (let i = b.length - win; i > b.length - win - Math.min(b.length / 2, (2 * sr) / f0); i--) {
+ if (b[i - 1] < 0 && b[i] >= 0) {
+ start = i;
+ break;
+ }
+ }
+ let peak = 1e-4;
+ for (let i = start; i < start + win; i++) peak = Math.max(peak, Math.abs(b[i]));
+ // slow auto-gain so quiet calls stay visible without the trace jumping
+ const want = 0.42 / Math.max(peak, 0.01);
+ gainRef.current += (want - gainRef.current) * (1 - Math.exp(-dt / (want < gainRef.current ? 0.05 : 0.6)));
+ const g = gainRef.current * h;
+ ctx.beginPath();
+ for (let x = 0; x < w; x++) {
+ const i0 = start + Math.floor((x / w) * win), i1 = Math.max(i0 + 1, start + Math.floor(((x + 1) / w) * win));
+ let lo = Infinity, hi = -Infinity;
+ for (let i = i0; i < i1; i++) {
+ if (b[i] < lo) lo = b[i];
+ if (b[i] > hi) hi = b[i];
+ }
+ ctx.lineTo(x, mid - hi * g);
+ if (lo < hi) ctx.lineTo(x, mid - lo * g);
+ }
+ ctx.strokeStyle = "rgba(232,234,235,0.85)";
+ ctx.lineWidth = 1.25;
+ ctx.stroke();
+ ctx.font = font(10.5);
+ ctx.fillStyle = C.textDim;
+ const ms = (win / sr) * 1000;
+ const label = ms >= 10 ? `${ms.toFixed(0)} ms` : `${ms.toFixed(1)} ms`;
+ ctx.fillText(label, w - ctx.measureText(label).width - 2, h - 4);
+ });
+ return <canvas ref={ref} className="instrument-canvas" aria-label="Output waveform" role="img" />;
+}
diff --git a/src/ui/components/Spectrogram.tsx b/src/ui/components/Spectrogram.tsx
new file mode 100644
index 0000000..4ae49a8
--- /dev/null
+++ b/src/ui/components/Spectrogram.tsx
@@ -0,0 +1,84 @@
+import { useRef } from "react";
+import { useCanvasLoop, font } from "../useCanvas.ts";
+import { engine } from "../../audio/AudioEngine.ts";
+import { useStore } from "../store.ts";
+import { C, hot } from "../colors.ts";
+
+const FMIN = 15, FMAX = 16000;
+const SPEED = 64; // px per second
+const DB_LO = -100, DB_HI = -30;
+
+/** Scrolling spectrogram of the output on a log-frequency axis, energy in the hot scale. */
+export function Spectrogram() {
+ const st = useRef<{ off: HTMLCanvasElement | null; bins: Float32Array | null; rows: Int32Array | null; acc: number }>({ off: null, bins: null, rows: null, acc: 0 });
+ const ref = useCanvasLoop(({ ctx, w, h, dt }) => {
+ const s = st.current;
+ const axisW = 30;
+ const pw = Math.max(1, Math.floor(w - axisW)), ph = Math.max(1, Math.floor(h - 4));
+ if (!s.off || s.off.width !== pw || s.off.height !== ph) {
+ s.off = document.createElement("canvas");
+ s.off.width = pw;
+ s.off.height = ph;
+ const oc = s.off.getContext("2d")!;
+ oc.fillStyle = "#000";
+ oc.fillRect(0, 0, pw, ph);
+ s.rows = null;
+ }
+ const oc = s.off.getContext("2d")!;
+ const an = engine.analyserFast;
+ s.acc += dt * SPEED;
+ const cols = Math.min(pw, Math.floor(s.acc));
+ s.acc -= cols;
+ if (cols > 0) {
+ oc.drawImage(s.off, -cols, 0);
+ const img = oc.createImageData(cols, ph);
+ if (an && useStore.getState().started) {
+ const n = an.frequencyBinCount;
+ if (!s.bins || s.bins.length !== n) s.bins = new Float32Array(n);
+ an.getFloatFrequencyData(s.bins as Float32Array<ArrayBuffer>);
+ const binHz = engine.sampleRate / an.fftSize;
+ if (!s.rows || s.rows.length !== ph * 2) {
+ // bin range covered by each pixel row (top = high frequencies)
+ s.rows = new Int32Array(ph * 2);
+ for (let y = 0; y < ph; y++) {
+ const fHi = FMAX * Math.pow(FMIN / FMAX, y / ph), fLo = FMAX * Math.pow(FMIN / FMAX, (y + 1) / ph);
+ const k0 = Math.max(1, Math.floor(fLo / binHz)), k1 = Math.min(n - 1, Math.max(k0, Math.ceil(fHi / binHz)));
+ s.rows[2 * y] = k0;
+ s.rows[2 * y + 1] = k1;
+ }
+ }
+ const b = s.bins, rows = s.rows;
+ for (let y = 0; y < ph; y++) {
+ let db = -Infinity;
+ for (let k = rows[2 * y]; k <= rows[2 * y + 1]; k++) if (b[k] > db) db = b[k];
+ const u = (db - DB_LO) / (DB_HI - DB_LO);
+ const [r, g, bl] = hot(u > 0 ? Math.pow(u, 1.5) : 0);
+ for (let x = 0; x < cols; x++) {
+ const i = (y * cols + x) * 4;
+ img.data[i] = r;
+ img.data[i + 1] = g;
+ img.data[i + 2] = bl;
+ img.data[i + 3] = 255;
+ }
+ }
+ } else for (let i = 3; i < img.data.length; i += 4) img.data[i] = 255;
+ oc.putImageData(img, pw - cols, 0);
+ }
+ ctx.clearRect(0, 0, w, h);
+ ctx.drawImage(s.off, 0, 2);
+ // frequency axis
+ ctx.font = font(10.5);
+ ctx.fillStyle = C.textDim;
+ ctx.strokeStyle = "rgba(255,255,255,0.10)";
+ const fy = (f: number) => 2 + (Math.log(FMAX / f) / Math.log(FMAX / FMIN)) * ph;
+ for (const [f, label] of [[20, "20"], [100, "100"], [1000, "1k"], [10000, "10k"]] as const) {
+ const y = fy(f);
+ ctx.beginPath();
+ ctx.moveTo(0, y);
+ ctx.lineTo(pw, y);
+ ctx.stroke();
+ ctx.fillText(label, pw + 5, Math.min(h - 2, Math.max(10, y + 4)));
+ }
+ });
+ return <canvas ref={ref} className="instrument-canvas" aria-label="Spectrogram of the output" role="img" />;
+}
diff --git a/src/ui/creatureLive.ts b/src/ui/creatureLive.ts
new file mode 100644
index 0000000..e094991
--- /dev/null
+++ b/src/ui/creatureLive.ts
@@ -0,0 +1,46 @@
+import { useEffect, useState } from "react";
+import { engine } from "../audio/AudioEngine.ts";
+import { CreatureVoice, type CreatureTelemetry } from "../engine/creatures/voice.ts";
+import type { CreatureDef } from "../engine/creatures/types.ts";
+
+const previews = new Map<string, CreatureTelemetry>();
+
+/**
+ * A still frame of a creature's airway at the given settings, for drawing before audio starts:
+ * builds the simulation on the main thread (well under a millisecond) and reads its geometry.
+ */
+export function previewTelemetry(def: CreatureDef, params?: Record<string, number>): CreatureTelemetry {
+ const key = def.id + JSON.stringify(params ?? {});
+ let t = previews.get(key);
+ if (!t) {
+ t = new CreatureVoice(def, 48000, params).telemetry();
+ previews.set(key, t);
+ if (previews.size > 48) previews.delete(previews.keys().next().value!);
+ }
+ return t;
+}
+
+/** Live telemetry for this creature, or null when it is not the voice that is playing. */
+export function liveTelemetry(id: string): CreatureTelemetry | null {
+ const m = engine.latestCreature;
+ return m && m.t.id === id ? m.t : null;
+}
+
+/** Re-render at about 20 Hz with the latest telemetry of this creature. */
+export function useLiveCreature(id: string): CreatureTelemetry | null {
+ const [t, setT] = useState<CreatureTelemetry | null>(null);
+ useEffect(() => {
+ let raf = 0, last = 0;
+ const loop = (now: number) => {
+ if (now - last > 50) {
+ last = now;
+ const next = liveTelemetry(id);
+ setT((prev) => (prev === next ? prev : next));
+ }
+ raf = requestAnimationFrame(loop);
+ };
+ raf = requestAnimationFrame(loop);
+ return () => cancelAnimationFrame(raf);
+ }, [id]);
+ return t;
+}
diff --git a/src/ui/store.ts b/src/ui/store.ts
index 7c758c2..7b5a6bc 100644
--- a/src/ui/store.ts
+++ b/src/ui/store.ts
@@ -3,10 +3,12 @@ import { engine } from "../audio/AudioEngine.ts";
import { DEFAULT_SOURCE, type VoiceSource } from "../engine/voice/humanVoice.ts";
import { NEUTRAL, restTip, type HumanArtic } from "../engine/anatomy/human.ts";
import type { BodyName } from "../worklet/protocol.ts";
+import { creatureById } from "../engine/creatures/index.ts";
+import type { ParamDef } from "../engine/creatures/types.ts";
export const DEFAULT_F0: Record<BodyName, number> = { male: 110, female: 205, child: 260 };
-export type Mode = "play" | "speak";
+export type Mode = "play" | "speak" | "bestiary";
export interface ViewOptions {
pressure: boolean;
@@ -30,6 +32,15 @@ interface State {
view: ViewOptions;
mode: Mode;
setMode: (m: Mode) => void;
+ /** active non-human creature in the bestiary */
+ creature: string;
+ cparams: Record<string, Record<string, number>>;
+ setCreature: (id: string) => void;
+ setCParam: (key: string, v: number) => void;
+ playCall: (id: string, pitch?: number) => void;
+ /** what the keys do in the bestiary: hold the voice at a pitch (null) or trigger this call */
+ keyCall: string | null;
+ setKeyCall: (id: string | null) => void;
start: () => Promise<void>;
setBody: (b: BodyName) => void;
setSource: (v: Partial<VoiceSource>) => void;
@@ -43,10 +54,26 @@ interface State {
const midiToHz = (m: number) => 440 * Math.pow(2, (m - 69) / 12);
-function updateGate(s: { hold: boolean; heldNotes: number[] }) {
- engine.gate(s.hold || s.heldNotes.length > 0 ? 1 : 0);
+/**
+ * Map a key to a creature's pitch range: shift the whole keyboard by whole octaves so middle C
+ * lands near the middle of the range (adjacent octaves stay distinct), then fold stragglers in.
+ */
+export function creatureKeyHz(midi: number, p: Pick<ParamDef, "min" | "max">): number {
+ const shift = Math.round(Math.log2(Math.sqrt(p.min * p.max) / midiToHz(60)));
+ let f = midiToHz(midi) * Math.pow(2, shift);
+ while (f > p.max) f /= 2;
+ while (f < p.min) f *= 2;
+ return Math.min(p.max, f);
}
+function updateGate(s: { hold: boolean; heldNotes: number[]; mode: Mode; keyCall: string | null }) {
+ // keys that trigger calls leave the breath to the call
+ const keysBreathe = !(s.mode === "bestiary" && s.keyCall);
+ engine.gate(s.hold || (keysBreathe && s.heldNotes.length > 0) ? 1 : 0);
+}
+
+let startPromise: Promise<void> | null = null;
+
export const useStore = create<State>((set, get) => ({
started: false,
starting: false,
@@ -63,19 +90,67 @@ export const useStore = create<State>((set, get) => ({
heldNotes: [],
view: { pressure: true, particles: true, grid: false, calipers: true },
mode: "play",
- setMode: (m) => set({ mode: m }),
- start: async () => {
- if (get().started || get().starting) return;
- set({ starting: true, startError: null });
- try {
- await engine.start();
+ setMode: (m) => {
+ const prev = get().mode;
+ if (prev === m) return;
+ // notes held across the switch would keep breathing into the other voice
+ set({ mode: m, heldNotes: [] });
+ if ((prev === "bestiary") !== (m === "bestiary")) {
+ // a sustain belongs to the voice it was started on
+ set({ hold: false });
const s = get();
- engine.setSource(s.source);
- engine.setVolume(s.volume);
- set({ started: true, starting: false });
- } catch (e) {
- set({ starting: false, startError: e instanceof Error ? e.message : String(e) });
+ engine.setCreature(m === "bestiary" ? s.creature : "human", s.cparams[s.creature]);
}
+ updateGate(get());
+ },
+ creature: "songbird",
+ cparams: {},
+ keyCall: null,
+ setKeyCall: (id) => {
+ set({ keyCall: id, heldNotes: [] });
+ updateGate(get());
+ },
+ setCreature: (id) => {
+ if (id === get().creature) return;
+ set({ creature: id, keyCall: null, heldNotes: [] });
+ if (get().mode === "bestiary") engine.setCreature(id, get().cparams[id]);
+ updateGate(get());
+ },
+ setCParam: (key, v) => {
+ const id = get().creature;
+ set((s) => ({ cparams: { ...s.cparams, [id]: { ...(s.cparams[id] ?? {}), [key]: v } } }));
+ engine.setCreatureParams({ [key]: v });
+ },
+ playCall: (id, pitch) => {
+ void get()
+ .start()
+ .then(() => {
+ if (get().started) engine.playCall(id, pitch);
+ });
+ },
+ start: () => {
+ if (get().started) return Promise.resolve();
+ if (startPromise) return startPromise;
+ set({ starting: true, startError: null });
+ startPromise = (async () => {
+ try {
+ await engine.start();
+ // anything set before audio existed was not delivered: send the whole state now
+ const s = get();
+ engine.setVolume(s.volume);
+ if (s.body !== "male") engine.setBody(s.body);
+ engine.setSource(s.source);
+ engine.setArtic(s.artic, s.tipFree);
+ if (s.mode === "bestiary") engine.setCreature(s.creature, s.cparams[s.creature]);
+ updateGate(s);
+ set({ started: true, starting: false });
+ } catch (e) {
+ set({ starting: false, startError: e instanceof Error ? e.message : String(e) });
+ } finally {
+ startPromise = null;
+ }
+ })();
+ return startPromise;
},
setBody: (b) => {
const f0 = DEFAULT_F0[b];
@@ -96,19 +171,34 @@ export const useStore = create<State>((set, get) => ({
},
setHold: (h) => {
set({ hold: h });
- updateGate({ ...get(), hold: h });
+ updateGate(get());
},
noteOn: (midi) => {
const held = get().heldNotes.filter((n) => n !== midi).concat(midi);
set({ heldNotes: held });
- get().setSource({ f0: midiToHz(midi) });
- updateGate({ ...get(), heldNotes: held });
+ const s = get();
+ if (s.mode === "bestiary") {
+ const pp = creatureById(s.creature)?.params.find((p) => p.role === "pitch");
+ const f = pp ? creatureKeyHz(midi, pp) : undefined;
+ if (s.keyCall) s.playCall(s.keyCall, f);
+ else if (pp && f) s.setCParam(pp.key, f);
+ } else s.setSource({ f0: midiToHz(midi) });
+ updateGate(get());
},
noteOff: (midi) => {
const held = get().heldNotes.filter((n) => n !== midi);
set({ heldNotes: held });
- if (held.length) get().setSource({ f0: midiToHz(held[held.length - 1]) });
- updateGate({ ...get(), heldNotes: held });
+ const s = get();
+ if (held.length) {
+ // fall back to the most recent note still held (legato)
+ const last = held[held.length - 1];
+ if (s.mode !== "bestiary") s.setSource({ f0: midiToHz(last) });
+ else if (!s.keyCall) {
+ const pp = creatureById(s.creature)?.params.find((p) => p.role === "pitch");
+ if (pp) s.setCParam(pp.key, creatureKeyHz(last, pp));
+ }
+ }
+ updateGate(get());
},
setView: (v) => set((s) => ({ view: { ...s.view, ...v } })),
}));
diff --git a/src/ui/styles.css b/src/ui/styles.css
index d64415a..0e212a3 100644
--- a/src/ui/styles.css
+++ b/src/ui/styles.css
@@ -551,6 +551,182 @@ button.ghost {
display: block;
}
+/* ---------- bestiary */
+.creature-canvas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ display: block;
+}
+
+.bestiary {
+ display: grid;
+ grid-template-columns: minmax(250px, 0.9fr) minmax(280px, 1fr) minmax(300px, 1.1fr);
+ gap: 10px;
+}
+
+.specimens {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(118px, 1fr));
+ gap: 6px;
+ max-height: 300px;
+ overflow-y: auto;
+}
+
+.specimen {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ gap: 1px;
+ padding: 0 0 6px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-s);
+ background: transparent;
+ text-align: left;
+ cursor: pointer;
+ overflow: hidden;
+}
+
+.specimen:hover {
+ border-color: var(--text-dim);
+}
+
+.specimen.on {
+ border-color: var(--caliper);
+}
+
+.thumb {
+ display: block;
+ width: 100%;
+ aspect-ratio: 16 / 10;
+ background: var(--black);
+ margin-bottom: 5px;
+}
+
+.specimen-name,
+.specimen-latin {
+ padding: 0 8px;
+}
+
+.specimen-name {
+ font-size: 13.5px;
+ font-weight: 600;
+ line-height: 1.25;
+}
+
+.specimen.on .specimen-name {
+ color: var(--caliper);
+}
+
+.specimen-latin {
+ font-size: 12px;
+ font-style: italic;
+ font-stretch: 87%;
+ color: var(--text-dim);
+ line-height: 1.3;
+}
+
+.calls-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.calls {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 6px;
+}
+
+.call {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 8px 10px 9px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-s);
+ background: var(--black);
+ text-align: left;
+ cursor: pointer;
+}
+
+.call:hover {
+ border-color: var(--text-dim);
+}
+
+.call:active,
+.call.sustain.on {
+ background: var(--caliper);
+ border-color: var(--caliper);
+ color: #1d1a10;
+}
+
+.call.playing {
+ border-color: var(--caliper);
+}
+
+.call.playing .call-name {
+ color: var(--caliper);
+}
+
+.call.sustain {
+ grid-column: 1 / -1;
+}
+
+.call-name {
+ font-weight: 600;
+ font-size: 14px;
+}
+
+.call-hint {
+ font-size: 12.5px;
+ font-stretch: 87%;
+ color: var(--text-dim);
+ line-height: 1.3;
+}
+
+.call:active .call-hint,
+.call.sustain.on .call-hint {
+ color: #3d3620;
+}
+
+.keys-mode {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+}
+
+.keys-mode .dim {
+ margin-right: 2px;
+}
+
+.creature-params {
+ display: flex;
+ flex-direction: column;
+}
+
+.creature-role {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 550;
+}
+
+.creature-blurb {
+ margin: 4px 0 10px;
+ font-size: 13px;
+ color: var(--text-dim);
+ max-width: 62ch;
+}
+
+.creature-sliders {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ column-gap: 18px;
+ row-gap: 4px;
+}
+
/* ---------- keys */
.keys-bar {
background: var(--inset);
@@ -623,6 +799,12 @@ button.ghost {
.vowel-panel {
grid-column: 1 / -1;
}
+ .bestiary {
+ grid-template-columns: 1fr 1fr;
+ }
+ .creature-params {
+ grid-column: 1 / -1;
+ }
}
@media (max-width: 900px) {
@@ -632,10 +814,30 @@ button.ghost {
}
@media (max-width: 720px) {
+ /* on a phone the controls come straight after the picture; the instruments go last */
.app {
+ display: flex;
+ flex-direction: column;
padding: 8px;
gap: 8px;
}
+ .stage {
+ display: contents;
+ }
+ .viewport {
+ order: 1;
+ }
+ .deck,
+ .speak,
+ .bestiary {
+ order: 2;
+ }
+ .keys-bar {
+ order: 3;
+ }
+ .instruments {
+ order: 4;
+ }
.tagline {
display: none;
}
@@ -650,9 +852,16 @@ button.ghost {
grid-template-columns: 1fr;
}
.voice-panel,
- .artic-panel {
+ .artic-panel,
+ .creature-sliders {
+ grid-template-columns: 1fr;
+ }
+ .bestiary {
grid-template-columns: 1fr;
}
+ .specimens {
+ grid-template-columns: repeat(2, 1fr);
+ }
.view-toggles {
top: auto;
bottom: 8px;
diff --git a/src/worklet/processor.ts b/src/worklet/processor.ts
index 9124289..a1bcc61 100644
--- a/src/worklet/processor.ts
+++ b/src/worklet/processor.ts
@@ -5,6 +5,8 @@
import { HumanVoice } from "../engine/voice/humanVoice.ts";
import { BODY_MALE, BODY_FEMALE, BODY_CHILD, type HumanBody } from "../engine/anatomy/human.ts";
import type { ToWorklet, FromWorklet, BodyName } from "./protocol.ts";
+import { CreatureVoice } from "../engine/creatures/voice.ts";
+import { creatureById } from "../engine/creatures/index.ts";
// Minimal AudioWorkletGlobalScope typings
declare const sampleRate: number;
@@ -24,12 +26,18 @@ class ChimeraProcessor extends AudioWorkletProcessor {
private blocks = 0;
private load = 0;
private pendingBody: BodyName | null = null;
+ private creature: CreatureVoice | null = null;
+ private pendingCreature: string | null = null;
+ /** params and a call that arrived while a creature switch was pending */
+ private pendingCreatureParams: Record<string, number> = {};
+ private pendingCall: { id: string; pitch?: number; amp?: number } | null = null;
+ private gateLevel = 0;
constructor() {
super();
this.voice = this.makeVoice("male");
this.port.onmessage = (e: MessageEvent<ToWorklet>) => this.onMessage(e.data);
- this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr });
+ this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, creature: "human" });
}
private makeVoice(body: BodyName): HumanVoice {
@@ -54,7 +62,26 @@ class ChimeraProcessor extends AudioWorkletProcessor {
this.voice.setSource(m.values);
break;
case "gate":
+ this.gateLevel = m.level;
this.voice.setGate(m.level);
+ this.creature?.setGate(m.level);
+ break;
+ case "creature":
+ this.pendingCreature = m.id;
+ this.pendingCreatureParams = { ...(m.params ?? {}) };
+ this.pendingCall = null;
+ break;
+ case "cparams":
+ if (this.pendingCreature !== null) Object.assign(this.pendingCreatureParams, m.values);
+ else this.creature?.setParams(m.values);
+ break;
+ case "call":
+ if (this.pendingCreature !== null) this.pendingCall = { id: m.id, pitch: m.pitch, amp: m.amp };
+ else this.creature?.playCall(m.id, m.pitch, m.amp);
+ break;
+ case "stopCall":
+ if (this.pendingCreature !== null) this.pendingCall = null;
+ else this.creature?.stopCall();
break;
case "telemetry":
this.telemetryOn = m.enabled;
@@ -90,12 +117,29 @@ class ChimeraProcessor extends AudioWorkletProcessor {
this.voice.setSource({ ...prev.source, f0: DEFAULT_F0[this.body] });
this.voice.setArticulation({ ...prev.artic.target }, prev.artic.tipFree);
this.voice.setGate(prev.gate > 0.5 ? 1 : 0);
- this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr });
+ this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, creature: this.creature ? this.creature.def.id : "human" });
+ }
+ if (this.pendingCreature !== null) {
+ const id = this.pendingCreature;
+ this.pendingCreature = null;
+ if (id === "human") this.creature = null;
+ else {
+ const def = creatureById(id);
+ if (def) {
+ this.creature = new CreatureVoice(def, sampleRate, this.pendingCreatureParams);
+ this.creature.setGate(this.gateLevel);
+ if (this.pendingCall) this.creature.playCall(this.pendingCall.id, this.pendingCall.pitch, this.pendingCall.amp);
+ }
+ }
+ this.pendingCreatureParams = {};
+ this.pendingCall = null;
+ this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, creature: this.creature ? this.creature.def.id : "human" });
}
const ch0 = out[0];
const t0 = Date.now();
try {
- this.voice.render(ch0, 0, ch0.length);
+ if (this.creature) this.creature.render(ch0, 0, ch0.length);
+ else this.voice.render(ch0, 0, ch0.length);
} catch (err) {
ch0.fill(0);
this.post({ type: "error", message: String(err) });
@@ -105,7 +149,8 @@ class ChimeraProcessor extends AudioWorkletProcessor {
const budget = (ch0.length / sampleRate) * 1000;
this.load += 0.05 * (dt / budget - this.load);
if (this.telemetryOn && ++this.blocks % 6 === 0) {
- this.post({ type: "telemetry", t: this.voice.telemetry(), load: this.load, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr });
+ if (this.creature) this.post({ type: "ctelemetry", t: this.creature.telemetry(), load: this.load });
+ else this.post({ type: "telemetry", t: this.voice.telemetry(), load: this.load, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr });
}
return true;
}
diff --git a/src/worklet/protocol.ts b/src/worklet/protocol.ts
index 82f800e..ba8ce90 100644
--- a/src/worklet/protocol.ts
+++ b/src/worklet/protocol.ts
@@ -3,6 +3,7 @@ import type { HumanArtic } from "../engine/anatomy/human.ts";
import type { VoiceSource, VoiceTelemetry } from "../engine/voice/humanVoice.ts";
import type { Segment, PlannedSegment } from "../engine/phonetics/planner.ts";
import type { Gesture } from "../engine/control/score.ts";
+import type { CreatureTelemetry } from "../engine/creatures/voice.ts";
export interface PhraseMsg {
segments: Segment[];
@@ -20,7 +21,12 @@ export type ToWorklet =
| { type: "telemetry"; enabled: boolean }
/** gestures planned on the main thread with times relative to "now" (the worklet adds its clock) */
| { type: "schedule"; gestures: Gesture[]; segments: PlannedSegment[]; end: number; id: number; replace: boolean }
- | { type: "stopSpeech" };
+ | { type: "stopSpeech" }
+ /** switch the active voice: "human" or a creature id */
+ | { type: "creature"; id: string; params?: Record<string, number> }
+ | { type: "cparams"; values: Record<string, number> }
+ | { type: "call"; id: string; pitch?: number; amp?: number }
+ | { type: "stopCall" };
export interface TelemetryMessage {
type: "telemetry";
@@ -40,4 +46,15 @@ export interface PlannedMessage {
segments: PlannedSegment[];
}
-export type FromWorklet = { type: "ready"; sampleRate: number; body: BodyName; nPh: number; nOr: number } | TelemetryMessage | PlannedMessage | { type: "error"; message: string };
+export interface CreatureTelemetryMessage {
+ type: "ctelemetry";
+ t: CreatureTelemetry;
+ load: number;
+}
+
+export type FromWorklet =
+ | { type: "ready"; sampleRate: number; body: BodyName; nPh: number; nOr: number; creature: string }
+ | TelemetryMessage
+ | CreatureTelemetryMessage
+ | PlannedMessage
+ | { type: "error"; message: string };
diff --git a/tools/e2e.ts b/tools/e2e.ts
index 1a041fb..f4a738c 100644
--- a/tools/e2e.ts
+++ b/tools/e2e.ts
@@ -66,6 +66,43 @@ async function run(viewport: { width: number; height: number }, tag: string) {
await page.locator("button.ipa", { hasText: "ʃ" }).first().click();
await page.waitForTimeout(700);
await page.screenshot({ path: `${outDir}/${tag}-4-pad.png` });
+ // bestiary: every creature, its first call, a key in held-voice mode, and the sustain toggle
+ await page.getByRole("radio", { name: "Bestiary" }).click();
+ await page.waitForTimeout(300);
+ const names = await page.locator(".specimen-name").allTextContents();
+ for (const [i, name] of names.entries()) {
+ await page.locator(".specimen").nth(i).click();
+ await page.waitForTimeout(250);
+ await page.locator(".call").first().click();
+ await page.waitForTimeout(1300);
+ const slug = name.toLowerCase().replace(/[^a-z]+/g, "-");
+ if (tag === "desktop" || i === 0) await page.screenshot({ path: `${outDir}/${tag}-5-${slug}.png`, fullPage: tag !== "desktop" });
+ const state = await page.evaluate(() => {
+ // @ts-expect-error debug handle
+ const e = window.__chimeraEngine;
+ const t = e?.latestCreature?.t;
+ return t ? { id: t.id, rms: t.outRms, call: t.call, load: e.load } : null;
+ });
+ logs.push(`[${tag}] creature ${name}: ${JSON.stringify(state)}`);
+ }
+ await page.keyboard.down("g");
+ await page.waitForTimeout(600);
+ const held = await page.evaluate(() => {
+ // @ts-expect-error debug handle
+ const t = window.__chimeraEngine?.latestCreature?.t;
+ return t ? { gate: t.gate, rms: t.outRms } : null;
+ });
+ await page.keyboard.up("g");
+ logs.push(`[${tag}] held key: ${JSON.stringify(held)}`);
+ // back to the human voice
+ await page.getByRole("radio", { name: "Play" }).click();
+ await page.waitForTimeout(600);
+ const human = await page.evaluate(() => {
+ // @ts-expect-error debug handle
+ const e = window.__chimeraEngine;
+ return { human: !!e?.latest, creature: !!e?.latestCreature };
+ });
+ logs.push(`[${tag}] back to play: ${JSON.stringify(human)}`);
await page.close();
}
@@ -73,4 +110,4 @@ await run({ width: 1440, height: 980 }, "desktop");
await run({ width: 390, height: 844 }, "mobile");
await browser.close();
console.log("console errors:", errors.length ? "\n" + errors.join("\n") : "none");
-console.log(logs.filter((l) => /load|warn|transcription/i.test(l)).slice(0, 20).join("\n"));
+console.log(logs.filter((l) => /load|warn|transcription|creature|held|back to/i.test(l)).slice(0, 40).join("\n"));
diff --git a/tools/explore-syrinx.ts b/tools/explore-syrinx.ts
new file mode 100644
index 0000000..b1b2dfb
--- /dev/null
+++ b/tools/explore-syrinx.ts
@@ -0,0 +1,48 @@
+/**
+ * Explore the Gardner–Mindlin labial normal form in normalised time τ:
+ * X' = Y, Y' = −α − βX − X³ − X²Y + X² − XY
+ * For a grid of (α, β): does a limit cycle exist? period in τ, amplitude, harmonic richness.
+ * Usage: bun tools/explore-syrinx.ts
+ */
+function rhs(x: number, y: number, a: number, b: number): [number, number] {
+ return [y, -a - b * x - x * x * x - x * x * y + x * x - x * y];
+}
+function simulate(a: number, b: number) {
+ let x = 0.1, y = 0.0;
+ const h = 0.002;
+ const N = 400000;
+ const xs: number[] = [];
+ for (let i = 0; i < N; i++) {
+ const [k1x, k1y] = rhs(x, y, a, b);
+ const [k2x, k2y] = rhs(x + 0.5 * h * k1x, y + 0.5 * h * k1y, a, b);
+ const [k3x, k3y] = rhs(x + 0.5 * h * k2x, y + 0.5 * h * k2y, a, b);
+ const [k4x, k4y] = rhs(x + h * k3x, y + h * k3y, a, b);
+ x += (h / 6) * (k1x + 2 * k2x + 2 * k3x + k4x);
+ y += (h / 6) * (k1y + 2 * k2y + 2 * k3y + k4y);
+ if (!Number.isFinite(x) || Math.abs(x) > 50) return null;
+ if (i > N / 2) xs.push(x);
+ }
+ let mn = Infinity, mx = -Infinity, mean = 0;
+ for (const v of xs) { mn = Math.min(mn, v); mx = Math.max(mx, v); mean += v; }
+ mean /= xs.length;
+ if (mx - mn < 1e-3) return { osc: false, fix: mean };
+ // period from upward mean crossings
+ const cr: number[] = [];
+ for (let i = 1; i < xs.length; i++) if (xs[i - 1] < mean && xs[i] >= mean) cr.push(i);
+ if (cr.length < 3) return { osc: false, fix: mean };
+ const period = ((cr[cr.length - 1] - cr[0]) / (cr.length - 1)) * h;
+ // crude richness: ratio of time spent in the top 20% of the swing (spiky = rich)
+ let top = 0; for (const v of xs) if (v > mn + 0.8 * (mx - mn)) top++;
+ return { osc: true, period, amp: mx - mn, min: mn, max: mx, duty: top / xs.length };
+}
+const rows: string[] = [];
+for (const b of [0.1, 0.2, 0.3, 0.45, 0.6, 0.8, 1.0, 1.3]) {
+ const cells: string[] = [];
+ for (const a of [0.0, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.6]) {
+ const r = simulate(a, b);
+ cells.push(!r ? " diverge " : !r.osc ? " · " : `T${r.period!.toFixed(1).padStart(5)} A${r.amp!.toFixed(2)}`);
+ }
+ rows.push(`β=${b.toFixed(2).padStart(5)} | ${cells.join(" ")}`);
+}
+console.log("α = 0.00 0.05 0.10 0.15 0.20 0.30 0.40 0.60");
+console.log(rows.join("\n"));
diff --git a/tools/gen-syrinx-table.ts b/tools/gen-syrinx-table.ts
new file mode 100644
index 0000000..f665022
--- /dev/null
+++ b/tools/gen-syrinx-table.ts
@@ -0,0 +1,45 @@
+/**
+ * Tabulate the Gardner–Mindlin normal form's limit cycle over (α, β): period T (in τ), and the
+ * X range (for mapping labial displacement to valve opening). Output: src/engine/sources/syrinxTable.generated.json
+ */
+import { writeFileSync } from "node:fs";
+const rhs = (x: number, y: number, a: number, b: number): [number, number] => [y, -a - b * x - x * x * x - x * x * y + x * x - x * y];
+function cycle(a: number, b: number) {
+ let x = 0.3, y = 0;
+ const h = 0.002;
+ const N = 300000;
+ let mn = Infinity, mx = -Infinity, sum = 0, cnt = 0;
+ const cross: number[] = [];
+ let prev = x;
+ for (let i = 0; i < N; i++) {
+ const [k1x, k1y] = rhs(x, y, a, b);
+ const [k2x, k2y] = rhs(x + 0.5 * h * k1x, y + 0.5 * h * k1y, a, b);
+ const [k3x, k3y] = rhs(x + 0.5 * h * k2x, y + 0.5 * h * k2y, a, b);
+ const [k4x, k4y] = rhs(x + h * k3x, y + h * k3y, a, b);
+ x += (h / 6) * (k1x + 2 * k2x + 2 * k3x + k4x);
+ y += (h / 6) * (k1y + 2 * k2y + 2 * k3y + k4y);
+ if (i > N / 2) {
+ mn = Math.min(mn, x); mx = Math.max(mx, x); sum += x; cnt++;
+ }
+ if (i > N / 2 && prev < 0 && x >= 0) cross.push(i);
+ prev = x;
+ }
+ const mean = sum / cnt;
+ const T = cross.length > 2 ? ((cross[cross.length - 1] - cross[0]) / (cross.length - 1)) * h : NaN;
+ return { T, min: mn, max: mx, mean };
+}
+const alphas = Array.from({ length: 13 }, (_, i) => 0.07 + (i / 12) * 0.53);
+const betas = Array.from({ length: 13 }, (_, i) => 0.1 + (i / 12) * 1.2);
+const T: number[][] = [], lo: number[][] = [], hi: number[][] = [];
+for (const b of betas) {
+ const rT: number[] = [], rl: number[] = [], rh: number[] = [];
+ for (const a of alphas) {
+ const c = cycle(a, b);
+ rT.push(Math.round(c.T * 1000) / 1000);
+ rl.push(Math.round(c.min * 1000) / 1000);
+ rh.push(Math.round(c.max * 1000) / 1000);
+ }
+ T.push(rT); lo.push(rl); hi.push(rh);
+}
+writeFileSync("src/engine/sources/syrinxTable.generated.json", JSON.stringify({ alphas, betas, T, lo, hi }));
+console.log("T range", Math.min(...T.flat().filter(Number.isFinite)), Math.max(...T.flat()), "NaN cells", T.flat().filter((v) => !Number.isFinite(v)).length);
diff --git a/tools/render-creature.ts b/tools/render-creature.ts
new file mode 100644
index 0000000..ffe1a4b
--- /dev/null
+++ b/tools/render-creature.ts
@@ -0,0 +1,65 @@
+/**
+ * Render a creature's calls (and a sustained note) offline; report level, stability and pitch.
+ * Usage: bun tools/render-creature.ts <creatureId> [outdir]
+ */
+import { CreatureVoice } from "../src/engine/creatures/voice.ts";
+import { CREATURES } from "../src/engine/creatures/index.ts";
+import { yinPitch } from "../src/engine/analysis/pitch.ts";
+import { writeWav } from "./lib/wav.ts";
+import { renderSpectrogram } from "./lib/spectrogram.ts";
+
+const id = process.argv[2] ?? "songbird";
+const outDir = process.argv[3] ?? "out/creatures";
+const def = CREATURES.find((c) => c.id === id);
+if (!def) throw new Error(`unknown creature ${id}; have ${CREATURES.map((c) => c.id).join(", ")}`);
+const FS = 48000;
+const v = new CreatureVoice(def, FS);
+const segs: { t: number; label: string }[] = [];
+const chunks: Float32Array[] = [];
+let tCursor = 0;
+const t0 = performance.now();
+const renderFor = (sec: number) => {
+ const n = Math.round(sec * FS);
+ const buf = new Float32Array(n);
+ for (let i = 0; i < n; i += 128) v.render(buf, i, Math.min(128, n - i));
+ chunks.push(buf);
+ tCursor += sec;
+ return buf;
+};
+// sustained note at the default pitch
+const pitchParam = def.params.find((p) => p.role === "pitch");
+segs.push({ t: tCursor, label: "sustain" });
+if (def.params.some((p) => p.key === "voices")) v.setParams({ voices: 0 }); // single voice for the pitch check
+v.setGate(1);
+const sus = renderFor(1.2);
+v.setGate(0);
+renderFor(0.4);
+if (def.params.some((p) => p.key === "voices")) v.setParams({ voices: 0.5 });
+let pitchReport = "";
+if (pitchParam) {
+ const est = yinPitch(sus.subarray(Math.round(0.6 * FS), Math.round(0.6 * FS) + 4096), FS, { minF0: Math.max(20, pitchParam.min * 0.5), maxF0: Math.min(12000, pitchParam.max * 2) });
+ pitchReport = `target ${pitchParam.default} Hz, measured ${est.f0.toFixed(1)} Hz (aperiodicity ${est.aperiodicity.toFixed(2)})`;
+}
+for (const call of def.calls) {
+ segs.push({ t: tCursor, label: call.id });
+ v.playCall(call.id);
+ const dur = call.keys[call.keys.length - 1].t + 0.5;
+ renderFor(dur);
+}
+const ms = performance.now() - t0;
+const total = chunks.reduce((a, c) => a + c.length, 0);
+const out = new Float32Array(total);
+let o = 0;
+for (const c of chunks) {
+ out.set(c, o);
+ o += c.length;
+}
+let pk = 0, bad = 0;
+for (const x of out) {
+ if (!Number.isFinite(x)) bad++;
+ pk = Math.max(pk, Math.abs(x));
+}
+writeWav(`${outDir}/${id}.wav`, [out], FS);
+renderSpectrogram(`${outDir}/${id}.png`, out, FS, { title: `${def.name} (${def.latin})`.toUpperCase().replace(/[^\x20-\x7e]/g, "?"), maxFreq: id === "songbird" ? 12000 : 6000, windowMs: id === "songbird" ? 4 : 12, marks: segs });
+console.log(`${def.name}: ${(total / FS).toFixed(1)} s in ${ms.toFixed(0)} ms (${((ms / 1000 / (total / FS)) * 100).toFixed(1)}% RT, internal ${v.fs} Hz) peak ${pk.toFixed(3)} non-finite ${bad}`);
+console.log(` ${pitchReport}`);