the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Review fixes for the realism pass: continuous rhotic transitions, no contact gate, safe homographs
Jameson Hodgec401da5c38b6
diff --git a/src/engine/anatomy/geom.ts b/src/engine/anatomy/geom.tsindex b6e2226..6a26a91 100644--- a/src/engine/anatomy/geom.ts+++ b/src/engine/anatomy/geom.ts@@ -76,6 +76,30 @@ export function rayPolyline(ox: number, oy: number, dx: number, dy: number, pl:return n;}+/**+ * Like rayPolyline, also telling for each crossing whether the ray leaves the tissue (the+ * polyline's right-hand side, along its direction) for the air: `exit[i]` is 1 then, else 0.+ */+export function rayCrossings(ox: number, oy: number, dx: number, dy: number, pl: Polyline, tMin: number, tMax: number, outT: number[], exit: Uint8Array): number {+ let n = 0;+ const xs = pl.xs, ys = pl.ys;+ for (let i = 0; i < xs.length - 1; i++) {+ const ax = xs[i], ay = ys[i];+ const ex = xs[i + 1] - ax, ey = ys[i + 1] - ay;+ const den = dx * ey - dy * ex;+ if (Math.abs(den) < 1e-12) continue;+ const wx = ax - ox, wy = ay - oy;+ const t = (wx * ey - wy * ex) / den;+ const u = (wx * dy - wy * dx) / den;+ if (u >= 0 && u < 1 && t >= tMin && t <= tMax && n < outT.length) {+ outT[n] = t;+ exit[n] = den < 0 ? 1 : 0;+ n++;+ }+ }+ return n;+}+/** Sample a cubic Bézier into `count` points (including both ends). */export function bezier3(p0: Vec, p1: Vec, p2: Vec, p3: Vec, count: number): Vec[] {const pts: Vec[] = [];diff --git a/src/engine/anatomy/human.ts b/src/engine/anatomy/human.tsindex 3364e7a..80ae3ac 100644--- a/src/engine/anatomy/human.ts+++ b/src/engine/anatomy/human.ts@@ -12,7 +12,7 @@* midsagittal distance d gives area A = α·d^β per region (lips: elliptical slit d·w·π/4).* The epilarynx is a short parametric tube above the glottis.*/-import { type Vec, v, add, sub, scale, lerpV, polar, rotateAbout, Polyline, rayPolyline, bezier3, bezier2, arc, catmullRom, tangentAngle, dist, norm } from "./geom.ts";+import { type Vec, v, add, sub, scale, lerpV, polar, rotateAbout, Polyline, rayPolyline, rayCrossings, bezier3, bezier2, arc, catmullRom, tangentAngle, dist, norm } from "./geom.ts";import { clamp, lerp, smoothstep } from "../util/math.ts";export interface HumanArtic {@@ -166,6 +166,8 @@ export class HumanVocalTract {private readonly polarC: Vec;private readonly polarC2: Vec;private readonly tmpT: number[] = new Array(64);+ private readonly crossT: number[] = new Array(64);+ private readonly crossExit = new Uint8Array(64);/** signed closest approach (cm) of tongue tip / dorsum to the oral roof in the last frame */contactTip = 1;contactBody = 1;@@ -385,6 +387,48 @@ export class HumanVocalTract {const yEpiTop = glottis.y + 2.4 * k * this.body.pharynx;const yPharTop = this.polarC.y;const nPh = 12;+ // A fan ray's inner surface. The ray starts in the tongue: the gap begins where it leaves it+ // (or, if the tongue has moved off the origin, at the surface behind it: a fixed fallback+ // gap jumped as the surface crossed the origin). The gap is the air along the ray up to the+ // roof: tissue the ray passes through on the way (a curled tip with air beneath it) is taken+ // out by its thickness, so a layer that vanishes as the ray grazes it changes nothing ("the+ // last crossing before the roof" jumped deep into the mouth whenever a ray slipped past the+ // tip, as on the way into a rhotic).+ const crossT = this.crossT, crossExit = this.crossExit;+ const fanInner = (o: Vec, dir: Vec, tOut: number): number => {+ const n = rayCrossings(o.x, o.y, dir.x, dir.y, inner, 0, tOut + 1.5 * k, crossT, crossExit);+ // sort the crossings along the ray (there are only a few)+ for (let i = 1; i < n; i++) {+ const t = crossT[i], e = crossExit[i];+ let j = i - 1;+ while (j >= 0 && crossT[j] > t) {+ crossT[j + 1] = crossT[j];+ crossExit[j + 1] = crossExit[j];+ j--;+ }+ crossT[j + 1] = t;+ crossExit[j + 1] = e;+ }+ let tIn: number, i = 0;+ if (n > 0 && crossExit[0] === 1) {+ tIn = crossT[0];+ i = 1;+ } else {+ const back = 2.5 * k;+ const nBack = rayPolyline(o.x, o.y, -dir.x, -dir.y, inner, 0, back, tmp);+ let tb = back;+ for (let q = 0; q < nBack; q++) tb = Math.min(tb, tmp[q]);+ tIn = -tb;+ }+ let tissue = 0;+ for (; i < n && crossT[i] < tOut; i++) {+ if (crossExit[i] === 1) continue; // a surface without its entry: nothing to take out+ const b = i + 1 < n ? crossT[i + 1] : tOut + 1.5 * k;+ tissue += Math.min(b, tOut) - crossT[i];+ i++; // skip the layer's exit+ }+ return tIn + tissue;+ };// `fan`: a ray of the oral fan, whose origin the tongue can move off (the others start below// or in front of all tissue they measure)const measure = (o: Vec, dir: Vec, maxLen: number, fan = false): { inner: Vec; outer: Vec; d: number } | null => {@@ -393,18 +437,13 @@ export class HumanVocalTract {if (nOut === 0) return null;let tOut = Infinity;for (let i = 0; i < nOut; i++) tOut = Math.min(tOut, tmp[i]);- const nIn = rayPolyline(o.x, o.y, dir.x, dir.y, inner, 0, tOut + 1.5 * k, tmp);- let tIn = -Infinity;- for (let i = 0; i < nIn; i++) if (tmp[i] > tIn && tmp[i] < tOut + 1.5 * k) tIn = tmp[i];- if (tIn === -Infinity && !fan) tIn = Math.max(0, tOut - 3.5 * k);- else if (tIn === -Infinity) {- // the tongue has moved off the ray's origin: its surface is behind it (a fixed fallback- // gap here jumped as the surface crossed the origin)- const back = 2.5 * k;- const nBack = rayPolyline(o.x, o.y, -dir.x, -dir.y, inner, 0, back, tmp);- let tb = back;- for (let i = 0; i < nBack; i++) tb = Math.min(tb, tmp[i]);- tIn = -tb;+ let tIn: number;+ if (fan) tIn = fanInner(o, dir, tOut);+ else {+ const nIn = rayPolyline(o.x, o.y, dir.x, dir.y, inner, 0, tOut + 1.5 * k, tmp);+ tIn = -Infinity;+ for (let i = 0; i < nIn; i++) if (tmp[i] > tIn && tmp[i] < tOut + 1.5 * k) tIn = tmp[i];+ if (tIn === -Infinity) tIn = Math.max(0, tOut - 3.5 * k);}// if the tongue crosses the wall, the outermost inner crossing lies beyond tOut → closedconst d = Math.max(0, tOut - tIn);@@ -464,15 +503,14 @@ export class HumanVocalTract {this.contactBody = bodyC.d;this.contactTipN = tipC.n;this.contactBodyN = bodyC.n;- if (tipC.d < 0.6 * k || bodyC.d < 0.6 * k) {+ // No outer gate: each ray's own weight fades the contact in. A gate on the sampled+ // tongue-to-roof distance could open with the per-ray correction already part-way on.+ {// the whole tongue outline, closed: distance to its surface, signed by whether the roof// point is inside it (so the sign only changes where the distance is zero)const outl: Vec[] = [...root, ...arcPts.slice(1), ...blade.slice(1), ...under.slice(1), ...floor.slice(1), root[0]];const tongueOutline = { xs: outl.map((q) => q.x), ys: outl.map((q) => q.y) };- const tongueGap = (x: number, y: number) => {- const gap = distToPolyline(tongueOutline, x, y);- return insidePolygon(tongueOutline, x, y) ? -gap : gap;- };+ const tongueGap = (x: number, y: number) => signedGap(tongueOutline, x, y);// Each roof ray takes the narrowest gap along its own stretch of roof: ±1 mm, so the rays// near a contact seal together and open together (a sharp burst), widening to ±2 mm while// the tongue is pressed in, because the tip's contact on the alveolar ridge is narrower@@ -700,30 +738,26 @@ function pointAlong(pl: { xs: number[]; ys: number[] }, cum: Float64Array, s: nureturn { x: pl.xs[i] + (pl.xs[i + 1] - pl.xs[i]) * u, y: pl.ys[i] + (pl.ys[i + 1] - pl.ys[i]) * u };}-/** Shortest distance from a point to a polyline. */-function distToPolyline(pl: { xs: number[]; ys: number[] }, px: number, py: number): number {- let best = Infinity;+/**+ * Distance from a point to a closed polygon's boundary (its last point repeats its first),+ * negative inside (even-odd rule), in one pass over the edges.+ */+function signedGap(pl: { xs: number[]; ys: number[] }, px: number, py: number): number {+ let best = Infinity, inside = false;const xs = pl.xs, ys = pl.ys;for (let i = 0; i < xs.length - 1; i++) {- const ax = xs[i], ay = ys[i], ex = xs[i + 1] - ax, ey = ys[i + 1] - ay;+ const ax = xs[i], ay = ys[i], bx = xs[i + 1], by = ys[i + 1];+ const ex = bx - ax, ey = by - ay;const L2 = ex * ex + ey * ey;let t = L2 > 1e-12 ? ((px - ax) * ex + (py - ay) * ey) / L2 : 0;t = t < 0 ? 0 : t > 1 ? 1 : t;const dx = px - ax - ex * t, dy = py - ay - ey * t;const d2 = dx * dx + dy * dy;if (d2 < best) best = d2;+ if (ay > py !== by > py && px < ax + ((py - ay) * ex) / ey) inside = !inside;}- return Math.sqrt(best);-}--/** Even-odd point-in-polygon test (the polygon's last point repeats its first). */-function insidePolygon(pl: { xs: number[]; ys: number[] }, px: number, py: number): boolean {- let inside = false;- for (let i = 0; i < pl.xs.length - 1; i++) {- const xa = pl.xs[i], ya = pl.ys[i], xb = pl.xs[i + 1], yb = pl.ys[i + 1];- if (ya > py !== yb > py && px < xa + ((py - ya) * (xb - xa)) / (yb - ya)) inside = !inside;- }- return inside;+ const d = Math.sqrt(best);+ return inside ? -d : d;}/** Closest approach of a set of tissue points to the roof: signed gap δ (negative = pressed in) and the roof normal there. */diff --git a/src/engine/phonetics/english.ts b/src/engine/phonetics/english.tsindex 0f52aa6..400831e 100644--- a/src/engine/phonetics/english.ts+++ b/src/engine/phonetics/english.ts@@ -14,14 +14,14 @@ const VOWELS = new Set(["ɑ", "æ", "ʌ", "ə", "ɔ", "aʊ", "aɪ", "ɛ", "ɝ",* The dictionary keeps one pronunciation per word; for these homographs it kept the rarer one* (the verb "wind", past-tense "read"). Telling them apart needs grammar; the common reading wins.*/-const HOMOGRAPHS: Record<string, string> = {- wind: "W IH1 N D",- read: "R IY1 D",- live: "L IH1 V",- lead: "L IY1 D",- close: "K L OW1 Z",- wound: "W UW1 N D",-};+const HOMOGRAPHS = new Map<string, string>([+ ["wind", "W IH1 N D"],+ ["read", "R IY1 D"],+ ["live", "L IH1 V"],+ ["lead", "L IY1 D"],+ ["close", "K L OW1 Z"],+ ["wound", "W UW1 N D"],+]);/** monosyllabic function words are unstressed in running speech (and reduce) */const FUNCTION_WORDS = new Set("a an the of to in on at by for from with as and or but nor so if is am are was were be been do does did has have had will would can could should shall may might must it its i you he she we they me him her us them my your his our their this that than then there not no".split(" "));@@ -109,7 +109,7 @@ export class EnglishG2P {/** One word → segments with lexical stress. `reduce`: weak forms of function words (speech). */word(w: string, reduce = true): Segment[] {const clean = w.toLowerCase().replace(/^'+|'+$/g, "");- const entry = HOMOGRAPHS[clean] ?? this.dict?.get(clean);+ const entry = HOMOGRAPHS.get(clean) ?? this.dict?.get(clean);if (entry) {const segs = arpabetToSegments(entry);if (reduce && FUNCTION_WORDS.has(clean)) {diff --git a/src/engine/phonetics/planner.ts b/src/engine/phonetics/planner.tsindex 003ff8c..fedea17 100644--- a/src/engine/phonetics/planner.ts+++ b/src/engine/phonetics/planner.ts@@ -89,6 +89,12 @@ export function vowelArtic(ipa: string, body: string): Partial<HumanArtic> | nulif (!v) return null;const out: Partial<HumanArtic> = {};for (const k of VOWEL_KEYS) if (v.artic[k] !== undefined) out[k] = v.artic[k] as number;+ // a rhotic's tip is raised and curled back, not resting behind the teeth: without its+ // calibrated position the tip stayed down and /ɝ/'s F3 sat ~15–20 % high (weakly rhotic)+ if ((v.artic.ttCurl ?? 0) > 0.05) {+ if (v.artic.ttX !== undefined) out.ttX = v.artic.ttX;+ if (v.artic.ttY !== undefined) out.ttY = v.artic.ttY;+ }return out;}diff --git a/src/engine/phonetics/vowelTargets.generated.json b/src/engine/phonetics/vowelTargets.generated.jsonindex 855ee3b..4e032e8 100644--- a/src/engine/phonetics/vowelTargets.generated.json+++ b/src/engine/phonetics/vowelTargets.generated.json@@ -467,23 +467,23 @@},"ɝ": {"artic": {- "tbX": 2.804,- "tbY": 7.242,- "jaw": 0.905,- "lipAp": 0.64,- "lipProt": 0.598,- "lipWidth": 0.348,+ "tbX": 2.733,+ "tbY": 7.236,+ "jaw": 0.762,+ "lipAp": 0.645,+ "lipProt": 0.596,+ "lipWidth": 0.336,"root": -0.9,- "larynx": -0.891,- "ttX": 5.694,- "ttY": 8.678,+ "larynx": -0.886,+ "ttX": 5.73,+ "ttY": 8.802,"ttCurl": 1},"formants": [- 465,- 1359,- 1820,- 3033+ 466,+ 1362,+ 1819,+ 3075],"target": [474,@@ -491,9 +491,9 @@1710],"err": [- -1.8,- -1.5,- 6.5+ -1.7,+ -1.2,+ 6.4]},"y": {@@ -1148,23 +1148,23 @@},"ɝ": {"artic": {- "tbX": 2.85,- "tbY": 7.334,- "jaw": 0.824,- "lipAp": 0.645,- "lipProt": 0.592,- "lipWidth": 0.35,- "root": -0.898,- "larynx": -0.829,- "ttX": 5.741,- "ttY": 8.777,- "ttCurl": 0.998+ "tbX": 2.683,+ "tbY": 7.314,+ "jaw": 0.664,+ "lipAp": 0.651,+ "lipProt": 0.587,+ "lipWidth": 0.345,+ "root": -0.9,+ "larynx": -0.815,+ "ttX": 5.752,+ "ttY": 8.916,+ "ttCurl": 1},"formants": [- 508,- 1567,- 2173,- 3414+ 513,+ 1568,+ 2171,+ 3435],"target": [523,@@ -1172,9 +1172,9 @@1929],"err": [- -2.8,- -1.4,- 12.6+ -1.9,+ -1.3,+ 12.5]},"y": {@@ -1823,7 +1823,7 @@"lipProt": 1.4,"lipWidth": 0.341,"root": -0.9,- "larynx": -1.014,+ "larynx": -1.013,"ttX": 5.736,"ttY": 9.324,"ttCurl": 1diff --git a/tests/english.test.ts b/tests/english.test.tsindex e4a6d19..75b41a3 100644--- a/tests/english.test.ts+++ b/tests/english.test.ts@@ -27,3 +27,11 @@ test("numbers are spelled out and unknown words fall back to rules", () => {expect(p.words).toEqual(["forty", "two"]);expect(ipa(letterToSound("zorblat")).length).toBeGreaterThan(4);});++test("words that are also object property names do not break the front end", () => {+ for (const w of ["constructor", "toString", "valueOf", "hasOwnProperty", "__proto__", "prototype"]) {+ const [p] = g2p.toPhrases(`The ${w} is ready.`);+ expect(p.segments.length).toBeGreaterThan(5);+ }+ expect(new EnglishG2P().toPhrases("constructor")[0].segments.length).toBeGreaterThan(3); // no dictionary+});diff --git a/tests/geometry-continuity.test.ts b/tests/geometry-continuity.test.tsindex 884e831..62291cf 100644--- a/tests/geometry-continuity.test.ts+++ b/tests/geometry-continuity.test.ts@@ -4,8 +4,31 @@* several vowel postures and flags any step far above its neighbours.*/import { describe, expect, test } from "bun:test";-import { HumanVocalTract, NEUTRAL, BODY_MALE, restTip, type HumanArtic } from "../src/engine/anatomy/human.ts";+import { HumanVocalTract, NEUTRAL, BODY_MALE, BODY_FEMALE, BODY_CHILD, restTip, type HumanArtic } from "../src/engine/anatomy/human.ts";import { vowelArtic } from "../src/engine/phonetics/planner.ts";+import TARGETS from "../src/engine/phonetics/vowelTargets.generated.json";+++/**+ * Max area change across [u − h, u] for a path through postures; a true discontinuity keeps its+ * size as h shrinks, a steep but continuous ramp does not.+ */+function jumpSize(areas: (u: number) => number[], u0: number, u1: number): number {+ // bisect towards the largest change inside the coarse step, down to a millionth of it+ let lo = u0, hi = u1;+ const diff = (a: number, b: number) => {+ const x = areas(a), y = areas(b);+ let m = 0;+ for (let j = 0; j < x.length; j++) m = Math.max(m, Math.abs(x[j] - y[j]));+ return m;+ };+ for (let it = 0; it < 20; it++) {+ const mid = (lo + hi) / 2;+ if (diff(lo, mid) >= diff(mid, hi)) hi = mid;+ else lo = mid;+ }+ return diff(lo, hi);+}const SWEEPS: [keyof HumanArtic, number, number][] = [["tbY", 5.5, 8.5],@@ -45,7 +68,47 @@ describe("tract geometry continuity", () => {steps.forEach((s, i) => {const nb = steps.slice(Math.max(0, i - 8), i + 9).filter((_, k) => k !== Math.min(8, i)).sort((a, b) => a - b);const med = nb[Math.floor(nb.length / 2)] ?? 0;- if (s > 0.25 && s > 6 * Math.max(med, 0.01)) jumps.push(`${vw} ${key}=${(lo + ((hi - lo) * (i + 1)) / N).toFixed(3)}: ${s.toFixed(2)} cm²`);+ if (!(s > 0.25 && s > 6 * Math.max(med, 0.01))) return;+ const f = (u: number) => areas({ ...base, [key]: lo + (hi - lo) * u });+ const j = jumpSize(f, i / N, (i + 1) / N);+ if (j > 0.05) jumps.push(`${vw} ${key}=${(lo + ((hi - lo) * (i + 1)) / N).toFixed(3)}: ${j.toFixed(2)} cm²`);+ });+ }+ }+ expect(jumps).toEqual([]);+ });++ test("no area jumps on the way between calibrated vowels (all articulators at once, every body)", () => {+ const PAIRS = [["o", "ɝ"], ["i", "ɝ"], ["ɑ", "ɝ"], ["ə", "ɝ"], ["ɑ", "i"], ["u", "i"], ["æ", "u"], ["ʊ", "e"]];+ const jumps: string[] = [];+ const N = 300;+ for (const [bodyName, body] of [["male", BODY_MALE], ["female", BODY_FEMALE], ["child", BODY_CHILD]] as const) {+ const tract = new HumanVocalTract(body);+ const ph = new Float64Array(20), or = new Float64Array(24);+ const areas = (a: HumanArtic) => {+ tract.resample(a, tract.compute(a), 20, 24, ph, or);+ return [...ph, ...or];+ };+ // the full calibrated posture, tongue tip included (the rhotic's raised, curled tip)+ const posture = (vw: string): HumanArtic => ({ ...NEUTRAL, ...(TARGETS as Record<string, Record<string, { artic: Partial<HumanArtic> }>>)[bodyName][vw].artic }) as HumanArtic;+ for (const [x, y] of PAIRS) {+ const a = posture(x), b = posture(y);+ const at = (u: number) => Object.fromEntries(Object.keys(a).map((k) => [k, (a as unknown as Record<string, number>)[k] + ((b as unknown as Record<string, number>)[k] - (a as unknown as Record<string, number>)[k]) * u])) as unknown as HumanArtic;+ const steps: number[] = [];+ let prev = areas(at(0));+ for (let i = 1; i <= N; i++) {+ const cur = areas(at(i / N));+ let m = 0;+ for (let j = 0; j < cur.length; j++) m = Math.max(m, Math.abs(cur[j] - prev[j]));+ steps.push(m);+ prev = cur;+ }+ steps.forEach((s, i) => {+ const nb = steps.slice(Math.max(0, i - 8), i + 9).filter((_, k) => k !== Math.min(8, i)).sort((p, q) => p - q);+ const med = nb[Math.floor(nb.length / 2)] ?? 0;+ if (!(s > 0.2 && s > 6 * Math.max(med, 0.01))) return;+ const j = jumpSize((u) => areas(at(u)), i / N, (i + 1) / N);+ if (j > 0.05) jumps.push(`${bodyName} ${x}→${y} at ${((i + 1) / N).toFixed(3)}: ${j.toFixed(2)} cm²`);});}}