Skip to content

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

Rust

Face: cheeks puff with the air held behind the lips; brows, blinks and a nodding head

Jameson Hodgeee19ed036a02
diff --git a/src/ui/render/anatomy.ts b/src/ui/render/anatomy.ts
index 7a77a16..5199b79 100644
--- a/src/ui/render/anatomy.ts
+++ b/src/ui/render/anatomy.ts
@@ -17,6 +17,7 @@ import { V, heat, pressureLevel } from "../colors.ts";
import { beam, beamPts, chaikin, dot, handle, label, ring, seg, type Pt } from "./vector.ts";
import { buildProfile, Gaze, jawFn, VIEW, type Profile } from "./profile.ts";
import { drawReadouts, type Slot } from "./readouts.ts";
+import { Expression } from "./expression.ts";
export type { Slot } from "./readouts.ts";
@@ -80,6 +81,62 @@ const ECHO_AGES = [0.09, 0.06, 0.03];
/** top of the cranium in body cm (profile.ts's skin outline peaks at 22.9), with a little air */
const CROWN = 23.4;
+const smoothstep = (a: number, b: number, x: number): number => {
+ const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
+ return t * t * (3 - 2 * t);
+};
+
+/**
+ * The side view's brow and eyelids (body cm): the brow rides up with the pitch and knits on low
+ * notes; the lids, two arcs over the front of the eyeball, meet when the eye blinks or closes on a
+ * long note, and open wide on a high one.
+ */
+export function eyeFeatures(c: Vec, k: number, e: Expression): { pts: Vec[]; w: number; alpha: number }[] {
+ const rx = 1.22 * k, ry = 1.08 * k;
+ const arc = (a0: number, a1: number): Vec[] => {
+ const o: Vec[] = [];
+ for (let i = 0; i <= 14; i++) {
+ const an = a0 + ((a1 - a0) * i) / 14;
+ o.push({ x: c.x + rx * Math.cos(an), y: c.y + ry * Math.sin(an) });
+ }
+ return o;
+ };
+ const deg = Math.PI / 180;
+ const wide = Math.max(0, e.brow);
+ // the upper lid comes down to meet the lower
+ const upEnd = 30 * deg + 14 * deg * wide, lo = -32 * deg;
+ const up = upEnd + (lo - upEnd) * e.lid;
+ const brow: Vec[] = [];
+ const raise = 0.42 * k * e.brow, knit = 0.3 * k * Math.max(0, -e.brow);
+ for (let i = 0; i <= 12; i++) {
+ const u = -1 + i / 6; // −1 back, +1 front
+ const front = (1 + u) / 2;
+ brow.push({ x: c.x + 0.1 * k + 0.9 * k * u, y: c.y + 1.4 * k + 0.2 * k * (1 - u * u) + raise - knit * front });
+ }
+ return [
+ { pts: arc(100 * deg, up), w: 1.15, alpha: 0.9 },
+ { pts: arc(-78 * deg, lo), w: 1.0, alpha: 0.75 },
+ { pts: brow, w: 1.4, alpha: 0.85 },
+ ];
+}
+
+/**
+ * Puffed cheeks in the side view: the face's outline above and below the lips swells forward (the
+ * air held in the mouth pushes the skin round the lips out). The lips' meeting edge, where their
+ * handle sits, stays put. Returns the map for body points, or null at rest.
+ */
+export function puffProfile(f: HumanFrame, k: number, puff: number): ((p: Vec) => Vec) | null {
+ if (Math.abs(puff) < 0.01) return null;
+ const L = { x: (f.upperLip[6].x + f.lowerLip[6].x) / 2, y: (f.upperLip[6].y + f.lowerLip[6].y) / 2 };
+ const out = 0.6 * k * puff;
+ return (p) => {
+ const dy = Math.abs(p.y - L.y) / (2.6 * k);
+ if (dy >= 1) return p;
+ const w = (1 - dy * dy) ** 2 * smoothstep(0.03, 0.45, dy) * smoothstep(L.x - 1.2 * k, L.x - 0.5 * k, p.x);
+ return w ? { x: p.x + out * w, y: p.y } : p;
+ };
+}
+
export class AnatomyRenderer {
private particles: Particle[] = [];
private scale = 20;
@@ -96,6 +153,8 @@ export class AnatomyRenderer {
private lastEcho = -1;
/** where the eye looks */
private gaze = new Gaze();
+ /** brows, lids and cheeks, from the voice */
+ readonly face = new Expression();
constructor() {
for (let i = 0; i < 170; i++) this.particles.push({ s: Math.random() * 17, u: Math.random() * 2 - 1, life: Math.random(), px: NaN, py: NaN });
@@ -159,7 +218,8 @@ export class AnatomyRenderer {
const g = this.gaze;
g.update(this.clock, dt);
const off = 0.85 * k * Math.cos(g.yaw);
- const cp = Math.cos(g.pitch), sp = Math.sin(g.pitch);
+ const pitch = g.pitch + this.face.lookUp;
+ const cp = Math.cos(pitch), sp = Math.sin(pitch);
const lc = { x: c.x + off * cp, y: c.y + off * sp };
const rx = (0.18 + 0.2 * Math.abs(Math.sin(g.yaw))) * k, ry = 0.42 * k;
const o: Vec[] = [];
@@ -182,6 +242,7 @@ export class AnatomyRenderer {
opts: { hover: HandleId | null; drag: HandleId | null; dt: number; formants: number[]; slots: Slot[]; info: string[] },
): void {
this.clock += opts.dt;
+ this.face.update(tele, opts.dt);
const G = this.geometry(model, f, a);
const pts = (v: Vec[]) => v.map((p) => this.P(p));
const line = (v: Vec[], color: string, w: number, o: { alpha?: number; hot?: boolean; close?: boolean } = {}) => beamPts(ctx, pts(v), color, w, o);
@@ -192,7 +253,11 @@ export class AnatomyRenderer {
line(G.brain, V.blueMid, 1.1, { close: true });
line(G.sulcus, V.blueDim, 0.9);
line(G.eye, V.blueMid, 1.1);
- line(this.lens(G.eyeC, model.tract.scale, opts.dt), V.blueDim, 0.9);
+ const k = model.tract.scale;
+ const bulge = puffProfile(f, k, this.face.puff);
+ const puffed = (v: Vec[]) => (bulge ? v.map(bulge) : v);
+ line(this.lens(G.eyeC, k, opts.dt), V.blueDim, 0.9, { alpha: 1 - smoothstep(0.45, 0.9, this.face.lid) });
+ for (const l of eyeFeatures(G.eyeC, k, this.face)) line(l.pts, V.blue, l.w, { alpha: l.alpha });
for (const v of G.vertebrae) line(v, V.blueDim, 1);
line(G.cords[0], V.blueDim, 0.8, { alpha: 0.8 });
line(G.cords[1], V.blueDim, 0.8, { alpha: 0.6 });
@@ -213,7 +278,7 @@ export class AnatomyRenderer {
// afterglow: where the tongue, jaw and lips were a moment ago
if (tele && this.clock - this.lastEcho >= 0.028) {
this.lastEcho = this.clock;
- this.echoes.push({ t: this.clock, tongue: f.tongue.slice(), jaw: G.jawLower, upperLip: chaikin(f.upperLip.map((p) => [p.x, p.y] as Pt)), lowerLip: chaikin(f.lowerLip.map((p) => [p.x, p.y] as Pt)) });
+ this.echoes.push({ t: this.clock, tongue: f.tongue.slice(), jaw: G.jawLower, upperLip: chaikin(puffed(f.upperLip).map((p) => [p.x, p.y] as Pt)), lowerLip: chaikin(puffed(f.lowerLip).map((p) => [p.x, p.y] as Pt)) });
while (this.echoes.length && this.clock - this.echoes[0].t > 0.12) this.echoes.shift();
}
if (tele) {
@@ -230,8 +295,8 @@ export class AnatomyRenderer {
}
// skin, airway walls, teeth, folds
- line(G.skinLower, V.blue, 1.7, { hot: true });
- line(G.skinUpper, V.blue, 1.7, { hot: true });
+ line(puffed(G.skinLower), V.blue, 1.7, { hot: true });
+ line(puffed(G.skinUpper), V.blue, 1.7, { hot: true });
line(G.outerWall, V.blue, 1.4, { hot: true });
line(f.inner, V.blue, 1.3, { alpha: 0.9 });
line(G.glottisWall, V.blue, 1.2, { alpha: 0.8 });
@@ -254,8 +319,8 @@ export class AnatomyRenderer {
line(G.jawLower, V.red, 1.5, { hot: true });
line(G.jawUpper, V.red, 1, { alpha: 0.45 });
const soft = (v: Vec[], it: number) => chaikin(v.map((p) => this.P(p)), it);
- beamPts(ctx, soft(f.upperLip, 2), V.pink, 1.5, { hot: true });
- beamPts(ctx, soft(f.lowerLip, 2), V.pink, 1.5, { hot: true });
+ beamPts(ctx, soft(puffed(f.upperLip), 2), V.pink, 1.5, { hot: true });
+ beamPts(ctx, soft(puffed(f.lowerLip), 2), V.pink, 1.5, { hot: true });
beamPts(ctx, soft(f.velum, 3), V.white, 1.25, { alpha: 0.92 });
if (tele) this.drawTurbulence(ctx, model, f, tele);
diff --git a/src/ui/render/anatomy3d.ts b/src/ui/render/anatomy3d.ts
index 187f540..109636e 100644
--- a/src/ui/render/anatomy3d.ts
+++ b/src/ui/render/anatomy3d.ts
@@ -26,6 +26,7 @@ import { chaikin, type Pt } from "./vector.ts";
import { Beams, Poly } from "./beams3d.ts";
import { bodyPoint, buildProfile, Gaze, jawAngle, wallX } from "./profile.ts";
import { faceHandles, type FaceView, type ViewFlags } from "./anatomy.ts";
+import { Expression } from "./expression.ts";
type Table = readonly (readonly [number, number])[];
type V3 = [number, number, number];
@@ -195,10 +196,11 @@ interface Group {
hot?: boolean;
}
-/** a polyline whose points the jaw carries by weight w (the lower face's skin) */
+/** a polyline whose points the jaw carries by weight w (the lower face's skin), and the cheeks' puff by c */
interface Skinned {
a: Float32Array;
w: Float32Array;
+ c: Float32Array;
}
/** everything that only depends on the body, in the rest pose (jaw closed) */
@@ -231,6 +233,28 @@ function jawWeight(k: number, ph: number, x: number, y: number): number {
return wv * wl * wb;
}
+/** how far the cheeks push out at full puff (template cm): to the side, and a little forward */
+const PUFF_OUT = 1.7, PUFF_FWD = 0.55;
+
+/**
+ * How much of the cheeks' puff a point of the face's skin takes (rest pose, body cm): a mound
+ * behind the mouth's corners, over the buccinators, fading out before the lips, the nose and
+ * the jaw's lower border; the midline itself only comes forward.
+ */
+function cheekWeight(k: number, ph: number, x: number, y: number): number {
+ const X = x / k, Yb = y / k;
+ const Y = Yb >= 7 ? Yb : 7 - (7 - Yb) / ph;
+ const r2 = ((X - 5.2) / 2.3) ** 2 + ((Y - 8.3) / 2.4) ** 2;
+ return r2 < 1 ? (1 - r2) ** 2 : 0;
+}
+
+/** the cheeks' push at a point (rest pose): [dx, dz] for its weight c, side of the face z and the puff */
+function puffAt(k: number, c: number, z: number, puff: number): [number, number] {
+ if (c === 0 || puff === 0) return [0, 0];
+ const m = c * puff * k;
+ return [PUFF_FWD * m, Math.sign(z) * PUFF_OUT * m * smooth(0.4 * k, 2.6 * k, Math.abs(z))];
+}
+
/** split a polyline (flat xyz) into the runs whose points are kept */
function keptRuns(pts: number[], keep: boolean[], closed: boolean): number[][] {
const n = keep.length;
@@ -314,9 +338,12 @@ function buildRest(model: VoiceModel): Rest {
const addShell = (pts: number[], keep: boolean[], closed: boolean) => {
for (const run of keptRuns(pts, keep, closed)) {
const n = run.length / 3;
- const w = new Float32Array(n);
- for (let i = 0; i < n; i++) w[i] = jawWeight(k, ph, run[3 * i], run[3 * i + 1]);
- shell.push({ a: new Float32Array(run), w });
+ const w = new Float32Array(n), c = new Float32Array(n);
+ for (let i = 0; i < n; i++) {
+ w[i] = jawWeight(k, ph, run[3 * i], run[3 * i + 1]);
+ c[i] = cheekWeight(k, ph, run[3 * i], run[3 * i + 1]);
+ }
+ shell.push({ a: new Float32Array(run), w, c });
}
};
const half: number[] = [];
@@ -614,6 +641,12 @@ export class Anatomy3D {
compact = false;
private clock = 0;
private readonly gaze = new Gaze();
+ /** brows, lids, cheeks and the head's nods, from the voice */
+ readonly face = new Expression();
+ /** the camera in the head's own frame (the head nods and sways under it) */
+ private readonly eye = new THREE.Vector3();
+ private readonly turn = new THREE.Quaternion();
+ private readonly euler = new THREE.Euler();
private strobe = 0;
private readonly tmp = new Poly();
private readonly particles: Particle[] = [];
@@ -673,7 +706,7 @@ export class Anatomy3D {
/** body point → CSS px on the canvas */
project(x: number, y: number, z: number): [number, number] {
- const v = this.v3.set(x, y, z).project(this.camera);
+ const v = this.v3.set(x, y, z).applyMatrix4(this.beams.group.matrixWorld).project(this.camera);
return [((v.x + 1) / 2) * this.w, ((1 - v.y) / 2) * this.h];
}
@@ -701,6 +734,9 @@ export class Anatomy3D {
this.clock += dt;
const rest = this.restFor(model);
const k = model.tract.scale;
+ const face = this.face;
+ face.update(tele, dt);
+ this.headPose(rest, k);
const phi = jawAngle(model, a.jaw);
const C = rest.condyle;
const B = this.beams;
@@ -723,7 +759,7 @@ export class Anatomy3D {
// The midsagittal section is the 2D view's drawing: full on from the side, but seen edge-on (from
// the front, back or above) its lines pile into one bright bar down the middle, so it fades as
// the head turns and the 3D shapes take over; the articulators' outlines fade less.
- const toCam = this.v3.copy(this.camera.position).sub(rest.center).normalize();
+ const toCam = this.v3.copy(this.eye).sub(rest.center).normalize();
const side = smooth(0.25, 0.8, Math.abs(toCam.z));
const cut = 0.22 + 0.78 * side, artCut = 0.45 + 0.55 * side;
const line = (pts: Vec[], color: string, w: number, o: { alpha?: number; hot?: boolean; close?: boolean } = {}, fade = cut) => B.line(flat(pts), pts.length, color, w, { ...o, alpha: (o.alpha ?? 1) * fade });
@@ -745,8 +781,10 @@ export class Anatomy3D {
for (const sk of rest.shell) {
const P = this.tmp.reset();
for (let i = 0; i < sk.w.length; i++) {
- const [x, y] = rot(sk.a[3 * i], sk.a[3 * i + 1], phi * sk.w[i]);
- P.p(x, y, sk.a[3 * i + 2]);
+ const z = sk.a[3 * i + 2];
+ const [dx, dz] = puffAt(k, sk.c[i], z, face.puff);
+ const [x, y] = rot(sk.a[3 * i] + dx, sk.a[3 * i + 1], phi * sk.w[i]);
+ P.p(x, y, z + dz);
}
B.poly(P, V.blueDim, 0.85, { alpha: 0.42 });
}
@@ -826,19 +864,39 @@ export class Anatomy3D {
return best;
}
+ /**
+ * The head nods (chin up on high notes, down on the beat) and sways (on a long note, and with
+ * the vibrato) about the top of the neck. Everything is drawn in the head's frame, so this
+ * turns the beams' group; the camera's position in that frame is kept for what faces it.
+ */
+ private headPose(rest: Rest, k: number): void {
+ const g = this.beams.group;
+ const pivot = this.v3.set(-2.4 * k, rest.head.y0 + 0.42 * (rest.condyle.y - rest.head.y0), 0);
+ this.turn.setFromEuler(this.euler.set(this.face.tilt, 0, this.face.nod));
+ g.quaternion.copy(this.turn);
+ g.position.copy(pivot).sub(pivot.applyQuaternion(this.turn));
+ g.updateMatrixWorld(true);
+ this.eye.copy(this.camera.position);
+ g.worldToLocal(this.eye);
+ }
+
// ------------------------------------------------------------------ eyes
private eyes(rest: Rest, dt: number): void {
- const g = this.gaze;
+ const g = this.gaze, e = this.face;
g.update(this.clock, dt);
const r = rest.eyeR;
// where they look: forward, turned by the gaze (yaw towards +z, pitch up)
- const d: V3 = [Math.cos(g.pitch) * Math.cos(g.yaw), Math.sin(g.pitch), Math.cos(g.pitch) * Math.sin(g.yaw)];
+ const pitch = g.pitch + 1.3 * e.lookUp;
+ const d: V3 = [Math.cos(pitch) * Math.cos(g.yaw), Math.sin(pitch), Math.cos(pitch) * Math.sin(g.yaw)];
const basis = (n: V3): [V3, V3] => {
const up: V3 = Math.abs(n[1]) > 0.9 ? [1, 0, 0] : [0, 1, 0];
const u = norm3(cross(up, n));
return [u, cross(n, u)];
};
- const cam = this.camera.position;
+ const cam = this.eye;
+ // the iris shows less as the lids close
+ const seen = 1 - smooth(0.4, 0.9, e.lid);
+ const wide = Math.max(0, e.brow);
for (const c of rest.eyes) {
// a sphere's outline is the circle facing the camera
const toCam = norm3([cam.x - c[0], cam.y - c[1], cam.z - c[2]]);
@@ -850,24 +908,31 @@ export class Anatomy3D {
L.ellipse(ic, scale3(iu, r * 0.5), scale3(iv, r * 0.5), 24);
const pc: V3 = [c[0] + d[0] * r * 0.97, c[1] + d[1] * r * 0.97, c[2] + d[2] * r * 0.97];
L.ellipse(pc, scale3(iu, r * 0.2), scale3(iv, r * 0.2), 14);
- // the lids: an almond over the front of the eyeball, inner corner towards the nose
+ // the lids: an almond over the front of the eyeball, inner corner towards the nose; the
+ // upper one opens wide on a high note and comes down onto the lower one to shut
const out = Math.sign(c[2]);
- const lid = (open: number) => {
+ const lidAt = (open: number, sv: number, sgn: number) => open * (1 - sv * sv) + 0.06 * sv * out * sgn;
+ const lid = (upper: boolean) => {
for (let i = 0; i <= 16; i++) {
- const sv = -1 + i / 8, al = out * sv * 0.95, be = open * (1 - sv * sv) + 0.06 * sv * out * Math.sign(open);
+ const sv = -1 + i / 8, al = out * sv * 0.95;
+ const lo = lidAt(-0.36, sv, -1);
+ const be = upper ? lidAt(0.5 + 0.2 * wide, sv, 1) * (1 - e.lid) + (lo + 0.03) * e.lid : lo;
L.p(c[0] + 1.04 * r * Math.cos(be) * Math.cos(al), c[1] + 1.04 * r * Math.sin(be), c[2] + 1.04 * r * Math.cos(be) * Math.sin(al));
}
L.end();
};
- lid(0.5);
- lid(-0.36);
- // the brow above it
+ lid(true);
+ lid(false);
+ // the brow above it: up with the pitch, knit (inner end down) on a low note, and on a long
+ // high note with the eyes shut, the inner end up (the singer feeling it)
+ const lift = 0.3 * e.brow, knit = 0.28 * Math.max(0, -e.brow), feel = 0.22 * e.lid * wide;
for (let i = 0; i <= 12; i++) {
- const sv = -1 + i / 6, al = out * (0.15 + sv * 0.62), be = 0.82 + 0.12 * (1 - sv * sv) - 0.06 * sv;
+ const sv = -1 + i / 6, al = out * (0.15 + sv * 0.62), inner = (1 - sv) / 2;
+ const be = 0.82 + 0.12 * (1 - sv * sv) - 0.06 * sv + lift + (feel - knit) * inner;
L.p(c[0] + 1.32 * r * Math.cos(be) * Math.cos(al), c[1] + 1.32 * r * Math.sin(be), c[2] + 1.32 * r * Math.cos(be) * Math.sin(al));
}
L.end();
- const style = [[V.blueMid, 1.0, 0.35], [V.blue, 1.0, 0.9], [V.blue, 1.0, 0.7], [V.blue, 1.25, 0.95], [V.blue, 1.05, 0.75], [V.blueMid, 1.3, 0.8]] as const;
+ const style = [[V.blueMid, 1.0, 0.35], [V.blue, 1.0, 0.9 * seen], [V.blue, 1.0, 0.7 * seen], [V.blue, 1.25, 0.95], [V.blue, 1.05, 0.75], [V.blueMid, 1.3, 0.8]] as const;
L.lines.forEach((l, i) => this.beams.line(l, l.length / 3, style[i][0], style[i][1], { alpha: style[i][2] }));
}
}
@@ -910,8 +975,10 @@ export class Anatomy3D {
const x = base(y, z) + bulge * g;
const natural = upper ? 0.5 * (1 - sz) * (1 - t) : 0.5 * (1 + sz) + 0.5 * (1 - sz) * t;
const w = natural + (jawWeight(k, ph, x, y) - natural) * smooth(Wm, Wl, Math.abs(z));
- const [rx, ry] = w ? rotXY(x, y, C, phi * w) : [x, y];
- return [rx, ry, z];
+ // the cheeks' puff, as the shell beside the patch takes it
+ const [dx, dz] = puffAt(k, cheekWeight(k, ph, x, y), z, this.face.puff);
+ const [rx, ry] = w ? rotXY(x + dx, y, C, phi * w) : [x + dx, y];
+ return [rx, ry, z + dz];
};
const row = (upper: boolean, t: (z: number) => number, z0: number, z1: number, n: number): Poly => {
P.reset();
@@ -1022,7 +1089,7 @@ export class Anatomy3D {
R.b[j] = s.d > 0.01 ? Math.min(3.5 * k, (2 * s.area) / (Math.PI * s.d)) : 0;
}
const P = this.tmp;
- const cam = this.camera.position;
+ const cam = this.eye;
for (let j = 0; j < R.n; j += 2) {
P.reset();
for (let i = 0; i <= 24; i++) {
@@ -1257,6 +1324,8 @@ export class Anatomy3D {
let maxA = 0.02;
for (let i = 0; i < area.length; i++) maxA = Math.max(maxA, area[i]);
open = Math.min(0.45 * k, (area[Math.floor(this.strobe * area.length) % area.length] / (1.3 * k)) * 2.2);
+ // the scope's samples can be missing for a moment (lips held shut, the voice stopped)
+ if (!Number.isFinite(open)) open = 0;
}
const F = new Lines();
for (const s of [1, -1]) {
diff --git a/src/ui/render/expression.ts b/src/ui/render/expression.ts
new file mode 100644
index 0000000..3541fac
--- /dev/null
+++ b/src/ui/render/expression.ts
@@ -0,0 +1,130 @@
+/**
+ * The face's expression, from what the voice is doing: the cheeks puff with the air pressure held
+ * behind closed lips, the brows follow the pitch, the eyes blink now and then and close on a long
+ * held note, and (for the 3D head, which has no handles to keep still) the head nods, sways and
+ * wobbles with the vibrato.
+ *
+ * Both face views keep one each and update it every frame from the latest telemetry; without
+ * telemetry (the engine not started) the face still blinks and everything else settles to rest.
+ */
+import type { TelemetryMessage } from "../../worklet/protocol.ts";
+
+/** dyn/cm² in one cmH₂O (the engine's pressures are in dyn/cm²) */
+const CM_H2O = 980.665;
+const smooth = (a: number, b: number, x: number): number => {
+ const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
+ return t * t * (3 - 2 * t);
+};
+const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
+/** one step of x towards target with time constant tau (s) */
+const follow = (x: number, target: number, tau: number, dt: number) => x + (target - x) * (1 - Math.exp(-dt / tau));
+
+/** A damped spring: it overshoots a little, which is what makes cheeks and heads jiggle. */
+class Spring {
+ x = 0;
+ v = 0;
+ constructor(private readonly hz: number, private readonly damping: number) {}
+ step(target: number, dt: number): number {
+ const w = 2 * Math.PI * this.hz;
+ // a few substeps keep it stable at a low frame rate
+ const n = Math.max(1, Math.ceil(dt / 0.008)), h = dt / n;
+ for (let i = 0; i < n; i++) {
+ this.v += (w * w * (target - this.x) - 2 * this.damping * w * this.v) * h;
+ this.x += this.v * h;
+ }
+ return this.x;
+ }
+}
+
+/**
+ * The air pressure (cmH₂O) in the mouth just behind the lips: a node about a centimetre in from
+ * the lips' end of the oral tube. Lips shut with the soft palate up (p, b) hold it near the lungs'
+ * pressure; m lets it out through the nose, and t, k and vowels leave it near nothing.
+ */
+export function mouthPressure(tele: TelemetryMessage): number {
+ const p = tele.t.pressureRms;
+ const i = tele.nPh + tele.nOr - 3;
+ return i >= tele.nPh && i < p.length ? p[i] / CM_H2O : 0;
+}
+
+export class Expression {
+ /** cheeks: 0 at rest, 1 fully puffed (a spring: it overshoots a little either way on release) */
+ puff = 0;
+ /** brows: +1 raised high, −1 lowered and knit */
+ brow = 0;
+ /** eyelids: 0 open, 1 shut */
+ lid = 0;
+ /** extra gaze pitch (radians, up): the eyes roll up on high notes */
+ lookUp = 0;
+ /** 3D head: chin up (+) or down, radians */
+ nod = 0;
+ /** 3D head: tilted towards its right shoulder (+), radians */
+ tilt = 0;
+
+ private clock = 0;
+ private readonly cheeks = new Spring(6.5, 0.32);
+ private readonly nodSpring = new Spring(2.4, 0.42);
+ private readonly tiltSpring = new Spring(3.2, 0.3);
+ /** the pitch's long-run level (log2 Hz) and its last fraction of a second, while voiced */
+ private ref = NaN;
+ private fast = NaN;
+ /** how long the pitch has held steady (s) */
+ private held = 0;
+ private hold = 0;
+ private nextBlink = 1.5 + Math.random() * 2;
+ private blinkAt = -1;
+ private secondBlink = false;
+ private lastStep = -1;
+
+ update(tele: TelemetryMessage | null, dt: number): void {
+ this.clock += dt;
+ const t = tele?.t;
+ const voiced = !!t && t.voicing > 0.45 && t.gate > 0.3 && t.f0 > 30 && t.outRms > 0.004;
+
+ // ---- cheeks
+ const puffTo = tele ? smooth(1.5, 7.0, mouthPressure(tele)) : 0;
+ this.puff = clamp(this.cheeks.step(puffTo, dt), -0.35, 1.25);
+
+ // ---- pitch: brows follow the pitch above or below where it has been lately
+ let dev = 0, wobble = 0;
+ if (voiced) {
+ const l = Math.log2(t!.f0);
+ // the first note, or a new body an octave away, starts from where it is
+ if (!Number.isFinite(this.ref) || Math.abs(12 * (l - this.ref)) > 14) this.ref = this.fast = l;
+ this.ref = follow(this.ref, l, 5, dt);
+ // a new note (a step well past any vibrato) starts the held time again
+ if (Math.abs(12 * (l - this.fast)) > 2.5) {
+ this.fast = l;
+ this.held = 0;
+ }
+ this.fast = follow(this.fast, l, 0.35, dt);
+ this.held += dt;
+ dev = 12 * (l - this.ref);
+ wobble = 12 * (l - this.fast);
+ } else this.held = 0;
+ const browTo = voiced ? clamp(dev / 6, -0.7, 1) : 0;
+ this.brow = follow(this.brow, browTo, voiced ? 0.12 : 0.45, dt);
+ this.lookUp = 0.32 * Math.max(0, this.brow);
+
+ // ---- eyes: a long high note closes them (not a long note at the voice's usual pitch: Play's
+ // held breath is one); blinks in between
+ const holdTo = voiced ? 0.92 * smooth(0.9, 1.9, this.held) * smooth(0.15, 0.55, this.brow) : 0;
+ this.hold = follow(this.hold, holdTo, holdTo > this.hold ? 0.35 : 0.08, dt);
+ if (this.clock >= this.nextBlink && this.hold < 0.2) {
+ this.blinkAt = this.clock;
+ this.secondBlink = !this.secondBlink && Math.random() < 0.18;
+ this.nextBlink = this.clock + (this.secondBlink ? 0.28 : 2 + Math.random() * 4.5);
+ }
+ const b = (this.clock - this.blinkAt) / 0.17;
+ const blink = this.blinkAt >= 0 && b < 1 ? Math.sin(Math.PI * b) ** 0.7 : 0;
+ this.lid = Math.max(blink, this.hold);
+
+ // ---- the 3D head: chin up for high notes, a nod on the beat, a sway on a long note, the vibrato's wobble
+ const step = tele?.beatStep ?? -1;
+ if (step !== this.lastStep && step >= 0 && step % 4 === 0) this.nodSpring.v -= step % 16 === 0 ? 1.3 : 0.8;
+ this.lastStep = step;
+ this.nod = this.nodSpring.step(0.13 * this.brow, dt);
+ const sway = smooth(0.6, 2, this.held) * 0.07 * Math.sin(this.clock * 1.7);
+ this.tilt = this.tiltSpring.step(sway + 0.05 * clamp(wobble, -1.5, 1.5), dt);
+ }
+}
diff --git a/tests/expression.test.ts b/tests/expression.test.ts
new file mode 100644
index 0000000..1aa04b1
--- /dev/null
+++ b/tests/expression.test.ts
@@ -0,0 +1,75 @@
+/**
+ * The face's expression from the real engine: the cheeks puff on p and b (lips shut, the air held
+ * behind them) but not on m (out through the nose), t or k (shut further back), and the brows
+ * rise on a high note.
+ */
+import { describe, expect, test } from "bun:test";
+import { initEngine, WasmVoice } from "./harness.ts";
+import type { TelemetryMessage } from "../src/worklet/protocol.ts";
+import { Expression } from "../src/ui/render/expression.ts";
+
+await initEngine();
+const { planUtterance } = await import("../src/wasm/engine.ts");
+const MALE = { female: 0, child: 0 };
+const FS = 48000;
+
+/** the telemetry block (as src/worklet/processor.ts reads it), with what Expression uses */
+function telemetry(v: WasmVoice): TelemetryMessage {
+ const { x, h } = v as unknown as { x: { memory: WebAssembly.Memory; engine_telemetry: (h: number) => number }; h: number };
+ const p = x.engine_telemetry(h);
+ const [phLen, orLen, velumPort, f0, voicing, pLung, outRms, noiseLevel, noiseNode, gate, clock, nArtic, nPh, nOr] = new Float64Array(x.memory.buffer, p, 16);
+ const all = new Float64Array(x.memory.buffer, p, 16 + nArtic + 3 * (nPh + nOr));
+ const o = 16 + nArtic + nPh + nOr;
+ const pressureRms = Float32Array.from(all.subarray(o, o + nPh + nOr));
+ const none = new Float32Array(0);
+ return { type: "telemetry", t: { artic: none, phAreas: none, orAreas: none, phLen, orLen, pressureRms, flow: none, velumPort, glottalArea: none, glottalFlow: none, f0, voicing, pLung, outRms, noiseLevel, noiseNode, gate, clock, active: [] }, load: 0, body: MALE, nPh, nOr, beatStep: -1 };
+}
+
+/** say a run of segments, stepping an Expression at 100 frames a second; the largest of each value by segment */
+function run(ipa: string[], f0 = 110, dur = (s: string) => ("aiu".includes(s) ? 0.3 : 0.12)) {
+ const v = new WasmVoice(FS);
+ const plan = planUtterance(ipa.map((s) => ({ ipa: s, dur: dur(s) })), { body: MALE, t0: 0.05, rate: 1, f0, intonation: "flat" });
+ v.schedule(plan.gestures, 0, true);
+ const e = new Expression();
+ const peak = new Map<string, { puff: number; brow: number; lid: number }>();
+ for (let i = 0; i < FS * (plan.end + 0.3); i += 480) {
+ v.render(480);
+ const tele = telemetry(v);
+ e.update(tele, 0.01);
+ // the cheeks lag the pressure a little: credit each moment to the segment of 40 ms before
+ const seg = plan.segments.find((s) => s.t0 <= tele.t.clock - 0.04 && tele.t.clock - 0.04 < s.t1)?.ipa;
+ if (!seg) continue;
+ const pk = peak.get(seg) ?? { puff: 0, brow: -1, lid: 0 };
+ peak.set(seg, { puff: Math.max(pk.puff, e.puff), brow: Math.max(pk.brow, e.brow), lid: Math.max(pk.lid, e.lid) });
+ }
+ return peak;
+}
+
+describe("expression", () => {
+ test("cheeks puff behind shut lips, not for m, t or k", () => {
+ const pk = run(["a", "p", "a", "t", "a", "m", "a", "b", "a", "k", "a"]);
+ expect(pk.get("p")!.puff).toBeGreaterThan(0.6);
+ expect(pk.get("b")!.puff).toBeGreaterThan(0.6);
+ for (const s of ["m", "t", "k"]) expect(pk.get(s)!.puff).toBeLessThan(0.15);
+ });
+
+ test("brows rise on a note well above the recent pitch, and a long note closes the eyes", () => {
+ // a voiced frame at a pitch (only what Expression reads differs from silence)
+ const v = new WasmVoice(FS);
+ v.render(480);
+ const base = telemetry(v);
+ const at = (f0: number): TelemetryMessage => ({ ...base, t: { ...base.t, f0, voicing: 1, gate: 1, outRms: 0.1 } });
+ const e = new Expression();
+ const brows: number[] = [], lids: number[] = [];
+ for (let i = 0; i < 400; i++) {
+ // two seconds around 110 Hz, then two an octave up
+ e.update(at(i < 200 ? 110 * 2 ** (0.08 * Math.sin(i / 3)) : 220), 0.01);
+ brows.push(e.brow);
+ lids.push(e.lid);
+ }
+ expect(Math.max(...brows.slice(50, 200))).toBeLessThan(0.3);
+ expect(Math.max(...brows.slice(220, 260))).toBeGreaterThan(0.6);
+ // the octave note held for two seconds: eyes nearly shut by its end
+ expect(lids[399]).toBeGreaterThan(0.6);
+ });
+});