Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: add sign preview and screenshot functionality

nirholas07e329ad1555
diff --git a/public/spatial-mcp/index.html b/public/spatial-mcp/index.html
index 1cced10dc..ed29b1113 100644
--- a/public/spatial-mcp/index.html
+++ b/public/spatial-mcp/index.html
@@ -81,7 +81,10 @@
</div>
<script type="module">
- import { renderSpatialArtifact } from './spatial-renderer.js';
+ // Absolute, not './' — the route serves this page at BOTH /spatial-mcp and
+ // /spatial-mcp/, and on the slash-less URL a relative specifier resolves
+ // against the site root (/spatial-renderer.js → 404, blank stages).
+ import { renderSpatialArtifact } from '/spatial-mcp/spatial-renderer.js';
// A real, public demo GLB (three.js sample, https).
const DEMO_GLB = 'https://cdn.jsdelivr.net/npm/[email protected]/examples/models/gltf/DamagedHelmet/glTF-Binary/DamagedHelmet.glb';
diff --git a/scripts/.scratch/fingerspelling-old.js b/scripts/.scratch/fingerspelling-old.js
new file mode 100644
index 000000000..36b094823
--- /dev/null
+++ b/scripts/.scratch/fingerspelling-old.js
@@ -0,0 +1,418 @@
+// ASL fingerspelling clip builder — turn a word into a canonical-skeleton
+// animation clip that spells it letter by letter on the dominant (right) hand.
+//
+// Every handshape is defined parametrically (per-finger curl, splay, a thumb
+// preset, optional wrist orientation) and compiled to local joint rotations on
+// the canonical bones (RightHandIndex1 … RightHandThumb3 plus the right arm
+// chain), emitting the SAME AnimationClip JSON document the animation library
+// and the motion-capture lanes produce. That means a spelled word retargets
+// onto any rigged avatar through src/animation-retarget.js with zero new
+// playback machinery.
+//
+// Letters with movement (J traces from I, Z traces with the index) carry wrist
+// keyframes inside their letter window. Double letters get a small outward
+// bounce between the two holds, matching how signers disambiguate them.
+//
+// Scope note: fingerspelling is the receptive-friendly, deterministic subset
+// of sign language — it spells English words; it is not grammatical ASL.
+// Lexical sign clips come from the motion-capture lane (video2motion), not
+// from this module.
+
+// ── quaternion + vector helpers ([x, y, z, w], matching three.js) ──────────
+
+const IDENT = [0, 0, 0, 1];
+
+function qMul(a, b) {
+ const [ax, ay, az, aw] = a;
+ const [bx, by, bz, bw] = b;
+ return [
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw,
+ aw * bw - ax * bx - ay * by - az * bz,
+ ];
+}
+
+function qConj(q) {
+ return [-q[0], -q[1], -q[2], q[3]];
+}
+
+function qNorm(q) {
+ const n = Math.hypot(q[0], q[1], q[2], q[3]);
+ if (n < 1e-8) return [...IDENT];
+ return [q[0] / n, q[1] / n, q[2] / n, q[3] / n];
+}
+
+function qAxisAngle(axis, deg) {
+ const [x, y, z] = vNorm(axis);
+ const half = (deg * Math.PI) / 360;
+ const s = Math.sin(half);
+ return [x * s, y * s, z * s, Math.cos(half)];
+}
+
+function vNorm(v) {
+ const n = Math.hypot(v[0], v[1], v[2]);
+ if (n < 1e-8) return [0, 0, 0];
+ return [v[0] / n, v[1] / n, v[2] / n];
+}
+
+function vCross(a, b) {
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+}
+
+function vDot(a, b) {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+}
+
+function vRot(q, v) {
+ const p = qMul(qMul(q, [v[0], v[1], v[2], 0]), qConj(q));
+ return [p[0], p[1], p[2]];
+}
+
+function shortestArc(from, to) {
+ const f = vNorm(from);
+ const t = vNorm(to);
+ const d = vDot(f, t);
+ if (d > 1 - 1e-9) return [...IDENT];
+ if (d < -1 + 1e-9) {
+ let axis = vCross(f, [1, 0, 0]);
+ if (Math.hypot(...axis) < 1e-6) axis = vCross(f, [0, 1, 0]);
+ const [x, y, z] = vNorm(axis);
+ return [x, y, z, 0];
+ }
+ const axis = vCross(f, t);
+ return qNorm([axis[0], axis[1], axis[2], 1 + d]);
+}
+
+// Orientation carrying rest axes (restDir, restNormal) onto (dir, normal):
+// swing to the direction, then a pure twist about it to line up the normal.
+function frameQuat(dir, normal, restDir, restNormal) {
+ const swing = shortestArc(restDir, dir);
+ const d = vNorm(dir);
+ let n = vNorm(normal);
+ n = vNorm([n[0] - d[0] * vDot(n, d), n[1] - d[1] * vDot(n, d), n[2] - d[2] * vDot(n, d)]);
+ if (Math.hypot(...n) < 1e-5) return swing;
+ let carried = vRot(swing, restNormal);
+ carried = vNorm([
+ carried[0] - d[0] * vDot(carried, d),
+ carried[1] - d[1] * vDot(carried, d),
+ carried[2] - d[2] * vDot(carried, d),
+ ]);
+ if (Math.hypot(...carried) < 1e-5) return swing;
+ const twist = shortestArc(carried, n);
+ const a = vDot([twist[0], twist[1], twist[2]], d);
+ return qMul(qNorm([d[0] * a, d[1] * a, d[2] * a, twist[3]]), swing);
+}
+
+// ── the signing arm pose (right hand raised, palm out, left arm relaxed) ───
+//
+// Canonical rest is a T-pose (arms along ±X, palms down), so every arm bone
+// needs a pose even when "static": zero rotation would leave the avatar
+// signing from a T-pose. Locals are derived from target global directions the
+// same way the capture solver does it, so they read naturally on any rig.
+
+function chainLocals(side, upperDir, lowerDir, handDir, handNormal) {
+ const s = side === 'Left' ? 1 : -1;
+ const rest = [s, 0, 0];
+ const gUpper = shortestArc(rest, upperDir);
+ const lowerLocalDir = vRot(qConj(gUpper), lowerDir);
+ const lowerLocal = shortestArc(rest, lowerLocalDir);
+ const gLower = qMul(gUpper, lowerLocal);
+ const gHand = frameQuat(handDir, handNormal, rest, [0, 1, 0]);
+ const handLocal = qMul(qConj(gLower), gHand);
+ return {
+ [`${side}Arm`]: qNorm(gUpper),
+ [`${side}ForeArm`]: qNorm(lowerLocal),
+ [`${side}Hand`]: qNorm(handLocal),
+ [`__g${side}Hand`]: gHand,
+ [`__g${side}Lower`]: gLower,
+ };
+}
+
+// Right hand up in signing space beside the shoulder: fingers up, palm to the
+// viewer (+Z), elbow dropped. The left arm hangs relaxed at the side using
+// locals sampled from the baked idle clip's first frame (the library's own
+// convention), which reads naturally after the retargeter's bind correction
+// where a geometrically-derived "down" did not.
+function signingPose() {
+ const right = chainLocals('Right', vNorm([-0.25, -0.9, 0.3]), vNorm([-0.22, 0.38, 0.9]), [0, 1, 0], [0, 0, -1]);
+ return {
+ ...right,
+ LeftArm: qNorm([0.5402, 0.1202, -0.0234, 0.8326]),
+ LeftForeArm: qNorm([0.0199, 0.0244, 0.1378, 0.99]),
+ LeftHand: qNorm([-0.0098, -0.0091, -0.029, 0.9995]),
+ };
+}
+
+// ── handshape model ────────────────────────────────────────────────────────
+
+const FINGERS = ['Index', 'Middle', 'Ring', 'Pinky'];
+
+// Per-joint shares of a full curl (proximal knuckles carry most of it).
+const CURL_WEIGHTS = [85, 100, 65];
+
+// Thumb presets, as [joint1, joint2, joint3] rotations composed from curl
+// about the thumb hinge and swing toward/away from the palm. Tuned for the
+// right hand and mirrored for the left via axis sign.
+const THUMB_PRESETS = {
+ // resting against the index side, pointing along the fingers
+ side: { adduct: 22, curl: [8, 10, 5] },
+ // extended away from the palm (L / Y / thumbs-out shapes)
+ out: { adduct: -55, curl: [0, 0, 0] },
+ // folded across the palm, under or over the curled fingers
+ across: { adduct: 55, curl: [30, 45, 30] },
+ // opposing the fingertips (O / F / D circles)
+ oppose: { adduct: 40, curl: [18, 30, 22] },
+ // tip pinned between index and middle (T) / at the middle knuckle (K)
+ between: { adduct: 38, curl: [22, 30, 15] },
+};
+
+// A handshape: curl 0..1 per finger (or [j1,j2,j3] explicit degrees), splay
+// in degrees (+ toward the thumb), a thumb preset, an optional wrist offset
+// {pitch,yaw,roll} in degrees applied on top of the signing pose, and an
+// optional motion ('J' | 'Z') traced inside the letter's time window.
+export const LETTER_SHAPES = {
+ A: { curl: { Index: 1, Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
+ B: { curl: {}, thumb: 'across' },
+ C: { curl: { Index: 0.45, Middle: 0.45, Ring: 0.45, Pinky: 0.45 }, thumb: 'oppose' },
+ D: { curl: { Middle: 0.7, Ring: 0.7, Pinky: 0.7 }, thumb: 'oppose' },
+ E: { curl: { Index: 0.85, Middle: 0.85, Ring: 0.85, Pinky: 0.85 }, thumb: 'across' },
+ F: { curl: { Index: 0.55 }, splay: { Middle: 6, Ring: 0, Pinky: -8 }, thumb: 'oppose' },
+ G: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side', wrist: { local: [0, 1, 0], deg: 85 } },
+ H: { curl: { Ring: 1, Pinky: 1 }, thumb: 'side', wrist: { local: [0, 1, 0], deg: 85 } },
+ I: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'across' },
+ J: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'across', motion: 'J' },
+ K: { curl: { Middle: [40, 15, 10], Ring: 1, Pinky: 1 }, thumb: 'between' },
+ L: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'out' },
+ M: { curl: { Index: 0.75, Middle: 0.75, Ring: 0.75, Pinky: 0.95 }, thumb: 'across' },
+ N: { curl: { Index: 0.75, Middle: 0.75, Ring: 0.95, Pinky: 0.95 }, thumb: 'across' },
+ O: { curl: { Index: 0.55, Middle: 0.55, Ring: 0.55, Pinky: 0.55 }, thumb: 'oppose' },
+ P: { curl: { Middle: [40, 15, 10], Ring: 1, Pinky: 1 }, thumb: 'between', wrist: { dir: [0.15, -0.85, 0.5], normal: [0, 1, 0.2] } },
+ Q: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side', wrist: { dir: [0.15, -0.85, 0.5], normal: [0, 1, 0.2] } },
+ R: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: -6, Middle: 8 }, thumb: 'across' },
+ S: { curl: { Index: 1, Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'across' },
+ T: { curl: { Index: 0.9, Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'between' },
+ U: { curl: { Ring: 1, Pinky: 1 }, thumb: 'across' },
+ V: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 9, Middle: -9 }, thumb: 'across' },
+ W: { curl: { Pinky: 1 }, splay: { Index: 10, Middle: 0, Ring: -10 }, thumb: 'across' },
+ X: { curl: { Index: [15, 95, 80], Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
+ Y: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'out' },
+ Z: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side', motion: 'Z' },
+ // ASL number handshapes 0–9 (static). 6–9 touch the thumb to one
+ // fingertip; the touched finger half-curls to meet the opposing thumb.
+ 0: { curl: { Index: 0.55, Middle: 0.55, Ring: 0.55, Pinky: 0.55 }, thumb: 'oppose' },
+ 1: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'across' },
+ 2: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 9, Middle: -9 }, thumb: 'across' },
+ 3: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 9, Middle: -9 }, thumb: 'out' },
+ 4: { curl: {}, splay: { Index: 10, Middle: 3, Ring: -4, Pinky: -12 }, thumb: 'across' },
+ 5: { curl: {}, splay: { Index: 10, Middle: 3, Ring: -4, Pinky: -12 }, thumb: 'out' },
+ 6: { curl: { Pinky: 0.55 }, splay: { Index: 9, Middle: 0, Ring: -8 }, thumb: 'oppose' },
+ 7: { curl: { Ring: 0.55 }, splay: { Index: 9, Middle: 0, Pinky: -10 }, thumb: 'oppose' },
+ 8: { curl: { Middle: 0.55 }, splay: { Index: 9, Ring: -6, Pinky: -12 }, thumb: 'oppose' },
+ 9: { curl: { Index: 0.55 }, splay: { Middle: 4, Ring: -4, Pinky: -12 }, thumb: 'oppose' },
+};
+
+// Wrist paths for the traced letters, keyed 0..1 across the letter window —
+// absolute {dir, normal} orientations like every other wrist spec. J dips and
+// supinates so the pinky draws the hook; Z jabs the index through the zigzag.
+const MOTIONS = {
+ J: [
+ { at: 0.0, wrist: { dir: [0, 1, 0], normal: [0, 0, -1] } },
+ { at: 0.45, wrist: { dir: [0.15, 0.5, 0.85], normal: [0, -0.8, 0.2] } },
+ { at: 1.0, wrist: { dir: [0.55, 0.6, 0.55], normal: [-0.8, 0, 0.2] } },
+ ],
+ Z: [
+ { at: 0.0, wrist: { dir: [0.35, 1, 0.1], normal: [0, 0, -1] } },
+ { at: 0.3, wrist: { dir: [-0.35, 1, 0.1], normal: [0, 0, -1] } },
+ { at: 0.7, wrist: { dir: [0.45, 0.65, 0.45], normal: [0, 0, -1] } },
+ { at: 1.0, wrist: { dir: [-0.3, 0.6, 0.45], normal: [0, 0, -1] } },
+ ],
+};
+
+function fingerJointDegrees(spec) {
+ if (Array.isArray(spec)) return spec;
+ const amount = typeof spec === 'number' ? spec : 0;
+ return CURL_WEIGHTS.map((w) => w * amount);
+}
+
+// Compile one handshape into finger-bone local quats for one side.
+export function handshapeLocals(letter, side = 'Right') {
+ const shape = LETTER_SHAPES[letter];
+ if (!shape) throw new Error(`no handshape for letter "${letter}"`);
+ const s = side === 'Left' ? 1 : -1;
+ const curlAxis = [0, 0, -s]; // hinge toward the palm (palms-down rest)
+ const splayAxis = [0, 1, 0];
+ const locals = {};
+ for (const finger of FINGERS) {
+ const deg = fingerJointDegrees(shape.curl?.[finger] ?? 0);
+ const splay = shape.splay?.[finger] ?? 0;
+ for (let j = 0; j < 3; j++) {
+ let q = qAxisAngle(curlAxis, deg[j]);
+ if (j === 0 && splay) q = qMul(q, qAxisAngle(splayAxis, splay * -s));
+ locals[`${side}Hand${finger}${j + 1}`] = qNorm(q);
+ }
+ }
+ const preset = THUMB_PRESETS[shape.thumb ?? 'side'];
+ // Thumb rest points ~45° between the fingers and the palm-forward axis;
+ // adduction swings it about the palm normal (toward/away from the palm
+ // centre), curl bends its hinge toward the palm. Axes are side-mirrored.
+ const thumbHinge = vNorm([-s * 0.5, 0, -0.85]);
+ for (let j = 0; j < 3; j++) {
+ let q = qAxisAngle(thumbHinge, preset.curl[j]);
+ if (j === 0) q = qMul(qAxisAngle([0, 1, 0], preset.adduct * -s), q);
+ locals[`${side}HandThumb${j + 1}`] = qNorm(q);
+ }
+ return locals;
+}
+
+// Hand local for an ABSOLUTE authored orientation: fingers toward `dir`, back
+// of hand toward `normal`, in the same authoring frame as the signing pose
+// (avatar faces +Z, up +Y, the right side of the body toward -X). Relative
+// deltas on the base wrist do not survive the retargeter's per-rig bind
+// correction, but absolute orientations built like the base pose do — the base
+// pose itself is the proof.
+function wristLocal(spec, gLower, restHand) {
+ // Escape hatch for orientations that degenerate under absolute authoring
+ // (a target direction near the bone's rest axis collapses to a pure twist,
+ // which the bind correction scrambles): a plain local pre-rotation on the
+ // base wrist, tuned against the live renderer (G / H use it).
+ if (spec.local) return qNorm(qMul(restHand, qAxisAngle(spec.local, spec.deg)));
+ const gHand = frameQuat(vNorm(spec.dir), vNorm(spec.normal), [-1, 0, 0], [0, 1, 0]);
+ return qNorm(qMul(qConj(gLower), gHand));
+}
+
+// ── clip assembly ──────────────────────────────────────────────────────────
+
+export const DEFAULT_TIMING = Object.freeze({
+ holdSeconds: 0.5,
+ transitionSeconds: 0.22,
+ motionSeconds: 0.9,
+ leadSeconds: 0.35,
+ tailSeconds: 0.4,
+});
+
+export function normalizeWord(word) {
+ const cleaned = String(word ?? '')
+ .toUpperCase()
+ .replace(/[^A-Z0-9 ]+/g, '')
+ .replace(/ +/g, ' ')
+ .trim();
+ return cleaned;
+}
+
+const NORMAL_BLEND_MODE = 2500;
+
+function stableUuid(seed) {
+ // FNV-1a over the seed, expanded to uuid shape — deterministic like the
+ // capture lanes, so identical words produce identical documents.
+ let h1 = 0x811c9dc5;
+ let h2 = 0x01000193;
+ for (let i = 0; i < seed.length; i++) {
+ h1 = Math.imul(h1 ^ seed.charCodeAt(i), 0x01000193) >>> 0;
+ h2 = Math.imul((h2 + seed.charCodeAt(i)) ^ (h1 >>> 5), 0x85ebca6b) >>> 0;
+ }
+ const hex = (n) => n.toString(16).padStart(8, '0');
+ const full = hex(h1) + hex(h2) + hex((h1 ^ 0x9e3779b9) >>> 0) + hex((h2 ^ 0x7f4a7c15) >>> 0);
+ return `${full.slice(0, 8)}-${full.slice(8, 12)}-${full.slice(12, 16)}-${full.slice(16, 20)}-${full.slice(20, 32)}`.toUpperCase();
+}
+
+/**
+ * Build an AnimationClip JSON document that fingerspells `word` on the right
+ * hand. Letters A–Z, digits 0–9, and spaces survive normalization; anything
+ * else is dropped.
+ * Returns the same document shape the animation library serves, ready for
+ * THREE.AnimationClip.parse + the platform retarget engine.
+ */
+export function buildFingerspellingClip(word, opts = {}) {
+ const timing = { ...DEFAULT_TIMING, ...opts };
+ const letters = normalizeWord(word);
+ if (!letters) throw new Error('word has no spellable characters (A-Z, 0-9)');
+
+ const pose = signingPose();
+ const restHand = pose.RightHand;
+ const gLower = pose.__gRightLower;
+ const neutralFingers = {};
+ for (const finger of [...FINGERS, 'Thumb']) {
+ for (let j = 1; j <= 3; j++) neutralFingers[`RightHand${finger}${j}`] = qAxisAngle([0, 0, 1], finger === 'Thumb' ? 4 : 12);
+ }
+
+ // Build the keyframe timeline: {time, locals} snapshots. Every snapshot
+ // carries the full right-hand bone set so tracks stay aligned.
+ const keys = [];
+ const pushKey = (time, fingers, wristSpec) => {
+ const locals = { ...fingers };
+ locals.RightHand = wristSpec ? wristLocal(wristSpec, gLower, restHand) : restHand;
+ keys.push({ time, locals });
+ };
+
+ let t = 0;
+ pushKey(0, neutralFingers, null);
+ t = timing.leadSeconds;
+ let prevLetter = null;
+ for (const ch of letters) {
+ if (ch === ' ') {
+ pushKey(t + timing.transitionSeconds, neutralFingers, null);
+ t += timing.transitionSeconds + timing.holdSeconds * 0.6;
+ prevLetter = null;
+ continue;
+ }
+ const shape = LETTER_SHAPES[ch];
+ const fingers = handshapeLocals(ch, 'Right');
+ const isDouble = prevLetter === ch;
+ if (isDouble) {
+ // Small outward bounce between repeated letters.
+ pushKey(t + timing.transitionSeconds * 0.6, { ...fingers }, { dir: [-0.3, 1, 0.1], normal: [0, 0, -1] });
+ t += timing.transitionSeconds * 0.6;
+ }
+ const wristBase = shape.wrist ?? null;
+ if (shape.motion && MOTIONS[shape.motion]) {
+ const start = t + timing.transitionSeconds;
+ for (const step of MOTIONS[shape.motion]) {
+ pushKey(start + step.at * timing.motionSeconds, fingers, step.wrist);
+ }
+ t = start + timing.motionSeconds;
+ } else {
+ pushKey(t + timing.transitionSeconds, fingers, wristBase);
+ pushKey(t + timing.transitionSeconds + timing.holdSeconds, fingers, wristBase);
+ t += timing.transitionSeconds + timing.holdSeconds;
+ }
+ prevLetter = ch;
+ }
+ pushKey(t + timing.tailSeconds, neutralFingers, null);
+
+ // Static body pose: keep the whole figure composed while the hand spells.
+ const staticBones = {
+ RightArm: pose.RightArm,
+ RightForeArm: pose.RightForeArm,
+ LeftArm: pose.LeftArm,
+ LeftForeArm: pose.LeftForeArm,
+ LeftHand: pose.LeftHand,
+ Hips: [...IDENT],
+ Spine: qAxisAngle([1, 0, 0], 2),
+ Spine1: [...IDENT],
+ Spine2: [...IDENT],
+ Neck: qAxisAngle([1, 0, 0], -3),
+ Head: [...IDENT],
+ };
+
+ const duration = keys[keys.length - 1].time;
+ const trackBones = Object.keys(keys[0].locals);
+ const tracks = [];
+ for (const bone of trackBones) {
+ const times = keys.map((k) => k.time);
+ const values = keys.flatMap((k) => k.locals[bone] ?? [...IDENT]);
+ tracks.push({ type: 'quaternion', name: `${bone}.quaternion`, times, values });
+ }
+ for (const [bone, q] of Object.entries(staticBones)) {
+ tracks.push({ type: 'quaternion', name: `${bone}.quaternion`, times: [0, duration], values: [...q, ...q] });
+ }
+ tracks.push({ type: 'vector', name: 'Hips.position', times: [0], values: [0, 0, 0] });
+
+ return {
+ name: opts.name ?? `fingerspell-${letters.toLowerCase().replace(/ /g, '-')}`,
+ duration,
+ tracks,
+ uuid: stableUuid(`fingerspell:${letters}:${timing.holdSeconds}:${timing.transitionSeconds}`),
+ blendMode: NORMAL_BLEND_MODE,
+ };
+}
diff --git a/scripts/.scratch/shoot.mjs b/scripts/.scratch/shoot.mjs
new file mode 100644
index 000000000..a86cf19cd
--- /dev/null
+++ b/scripts/.scratch/shoot.mjs
@@ -0,0 +1,26 @@
+// Screenshot the sign-preview contact sheet.
+// usage: node scripts/.scratch/shoot.mjs "<query>" <outfile>
+import { chromium } from 'playwright';
+
+const query = process.argv[2] || '';
+const out = process.argv[3] || '/tmp/sign.png';
+const browser = await chromium.launch({
+ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
+});
+const page = await browser.newPage({ viewport: { width: 1400, height: 1200 } });
+const errors = [];
+page.on('console', (m) => errors.push(`[${m.type()}] ${m.text()}`));
+page.on('pageerror', (e) => errors.push(String(e)));
+await page.goto(`http://localhost:3000/scripts/.scratch/sign-preview.html?${query}`, { waitUntil: 'load' });
+try {
+ await page.waitForFunction(() => document.title === 'ready', null, { timeout: 45000 });
+} catch {
+ console.error('TIMEOUT waiting for render');
+}
+await page.waitForTimeout(400);
+const canvas = await page.$('canvas');
+const box = canvas ? await canvas.boundingBox() : null;
+await page.screenshot({ path: out, clip: box ? { x: 0, y: 0, width: box.width, height: box.height } : undefined });
+if (errors.length) console.error('page errors:\n' + errors.join('\n'));
+console.log('wrote', out);
+await browser.close();
diff --git a/scripts/.scratch/sign-preview.html b/scripts/.scratch/sign-preview.html
new file mode 100644
index 000000000..3f915fa84
--- /dev/null
+++ b/scripts/.scratch/sign-preview.html
@@ -0,0 +1,134 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <title>sign preview</title>
+ <style>
+ html, body { margin: 0; background: #2f5bb7; }
+ canvas { display: block; }
+ #labels { position: fixed; inset: 0; pointer-events: none; font: 700 22px system-ui; color: #ffe600; }
+ #labels div { position: absolute; }
+ </style>
+ </head>
+ <body>
+ <div id="labels"></div>
+ <script type="module">
+ import * as THREE from 'three';
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+ import { AnimationManager } from '/src/animation-manager.js';
+
+ const params = new URLSearchParams(location.search);
+ const which = params.get('mod') || 'new';
+ const word = params.get('word') || 'ABCDEFGHIJKL';
+ const cols = +(params.get('cols') || 4);
+ const cellW = +(params.get('w') || 300);
+ const cellH = +(params.get('h') || 340);
+ const mode = params.get('mode') || 'letters'; // letters | frames | sign
+ const camY = +(params.get('camy') || 0.62);
+
+ const mod = which === 'old'
+ ? await import('/scripts/.scratch/fingerspelling-old.js')
+ : await import('/src/fingerspelling.js');
+ const dict = mode === 'sign' ? await import('/src/sign-dictionary.js') : null;
+
+ // Build the clip + the times to sample.
+ let clip, samples;
+ if (mode === 'sign' && dict) {
+ clip = dict.buildSignClip(word);
+ const n = +(params.get('n') || 8);
+ samples = Array.from({ length: n }, (_, i) => ({
+ t: (clip.duration * (i + 0.5)) / n,
+ label: `${(clip.duration * (i + 0.5) / n).toFixed(2)}s`,
+ }));
+ } else if (mode === 'frames') {
+ clip = mod.buildFingerspellingClip(word);
+ const n = +(params.get('n') || 12);
+ samples = Array.from({ length: n }, (_, i) => ({ t: (clip.duration * i) / (n - 1), label: `${((clip.duration * i) / (n - 1)).toFixed(2)}s` }));
+ } else {
+ // One cell per letter, sampled in the middle of that letter's hold.
+ const letters = [...word.toUpperCase().replace(/[^A-Z0-9]/g, '')];
+ clip = mod.buildFingerspellingClip(letters.join(''));
+ const T = mod.DEFAULT_TIMING;
+ let t = T.leadSeconds;
+ samples = letters.map((ch) => {
+ if (ch === 'J' || ch === 'Z') {
+ const mid = t + T.transitionSeconds + T.motionSeconds * 0.85;
+ t = t + T.transitionSeconds + T.motionSeconds;
+ return { t: mid, label: ch };
+ }
+ const mid = t + T.transitionSeconds + T.holdSeconds * 0.6;
+ t = t + T.transitionSeconds + T.holdSeconds;
+ return { t: mid, label: ch };
+ });
+ }
+
+ const rows = Math.ceil(samples.length / cols);
+ const W = cols * cellW;
+ const H = rows * cellH;
+
+ const renderer = new THREE.WebGLRenderer({ antialias: true });
+ renderer.setPixelRatio(1);
+ renderer.setSize(W, H);
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.autoClear = false;
+ renderer.setScissorTest(true);
+ document.body.appendChild(renderer.domElement);
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(0x2f5bb7);
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ scene.add(new THREE.HemisphereLight(0xffffff, 0x39404d, 1.0));
+ const key = new THREE.DirectionalLight(0xffffff, 1.6);
+ key.position.set(1.5, 2.5, 3);
+ scene.add(key, new THREE.AmbientLight(0xffffff, 0.4));
+
+ const gltf = await new GLTFLoader().loadAsync('/avatars/cz.glb');
+ const model = gltf.scene;
+ model.traverse((n) => { if (n.isMesh) n.frustumCulled = false; });
+ scene.add(model);
+
+ const anim = new AnimationManager();
+ anim.attach(model);
+ anim.injectClip('sign', clip, { loop: false });
+ const action = anim.actions.get('sign');
+ if (!action) throw new Error('clip did not bind');
+ action.play();
+ action.paused = true;
+
+ const camera = new THREE.PerspectiveCamera(30, cellW / cellH, 0.05, 50);
+
+ const labels = document.getElementById('labels');
+ samples.forEach((s, i) => {
+ const col = i % cols;
+ const row = (i / cols) | 0;
+ const el = document.createElement('div');
+ el.textContent = s.label;
+ el.style.left = `${col * cellW + 12}px`;
+ el.style.top = `${row * cellH + 10}px`;
+ labels.appendChild(el);
+ });
+
+ renderer.clear();
+ samples.forEach((s, i) => {
+ action.time = Math.min(s.t, clip.duration - 1e-4);
+ anim.mixer.update(0);
+ model.updateWorldMatrix(true, true);
+
+ const col = i % cols;
+ const row = (i / cols) | 0;
+ const x = col * cellW;
+ const y = H - (row + 1) * cellH;
+ renderer.setViewport(x, y, cellW, cellH);
+ renderer.setScissor(x, y, cellW, cellH);
+ camera.position.set(0, 1.5 + camY * 0.0, 1.85);
+ camera.lookAt(0, 1.34, 0);
+ camera.updateProjectionMatrix();
+ renderer.render(scene, camera);
+ });
+ document.title = 'ready';
+ </script>
+ </body>
+</html>
diff --git a/src/fingerspelling.js b/src/fingerspelling.js
index 36b094823..778db240e 100644
--- a/src/fingerspelling.js
+++ b/src/fingerspelling.js
@@ -1,288 +1,82 @@
-// ASL fingerspelling clip builder — turn a word into a canonical-skeleton
-// animation clip that spells it letter by letter on the dominant (right) hand.
+// ASL fingerspelling — turn a word into a canonical-skeleton animation clip that
+// spells it letter by letter on the dominant hand.
//
-// Every handshape is defined parametrically (per-finger curl, splay, a thumb
-// preset, optional wrist orientation) and compiled to local joint rotations on
-// the canonical bones (RightHandIndex1 … RightHandThumb3 plus the right arm
-// chain), emitting the SAME AnimationClip JSON document the animation library
-// and the motion-capture lanes produce. That means a spelled word retargets
-// onto any rigged avatar through src/animation-retarget.js with zero new
-// playback machinery.
+// Fingerspelling has a real citation form and this module follows it: the hand
+// sits in front of the dominant shoulder at about jaw height, palm to the person
+// reading, elbow down and relaxed. Only the handshape changes between letters —
+// the hand itself stays put, which is exactly what makes fingerspelling readable
+// and what a signer would correct first in a bad avatar.
//
-// Letters with movement (J traces from I, Z traces with the index) carry wrist
-// keyframes inside their letter window. Double letters get a small outward
-// bounce between the two holds, matching how signers disambiguate them.
+// The pose is SOLVED, not authored: `src/sign-clip.js` places the wrist at a
+// point in signing space and `src/sign-rig.js` runs two-bone IK against the
+// reference skeleton's measured bind pose to find the shoulder, elbow, and wrist
+// rotations. Handshapes come from the shared catalogue in
+// `src/sign-handshapes.js`. The result is the SAME AnimationClip JSON document
+// the pre-baked library and the motion-capture lanes produce, so a spelled word
+// retargets onto any rigged avatar through `src/animation-retarget.js` with zero
+// new playback machinery.
//
-// Scope note: fingerspelling is the receptive-friendly, deterministic subset
-// of sign language — it spells English words; it is not grammatical ASL.
-// Lexical sign clips come from the motion-capture lane (video2motion), not
-// from this module.
-
-// ── quaternion + vector helpers ([x, y, z, w], matching three.js) ──────────
-
-const IDENT = [0, 0, 0, 1];
-
-function qMul(a, b) {
- const [ax, ay, az, aw] = a;
- const [bx, by, bz, bw] = b;
- return [
- aw * bx + ax * bw + ay * bz - az * by,
- aw * by - ax * bz + ay * bw + az * bx,
- aw * bz + ax * by - ay * bx + az * bw,
- aw * bw - ax * bx - ay * by - az * bz,
- ];
-}
-
-function qConj(q) {
- return [-q[0], -q[1], -q[2], q[3]];
-}
-
-function qNorm(q) {
- const n = Math.hypot(q[0], q[1], q[2], q[3]);
- if (n < 1e-8) return [...IDENT];
- return [q[0] / n, q[1] / n, q[2] / n, q[3] / n];
-}
-
-function qAxisAngle(axis, deg) {
- const [x, y, z] = vNorm(axis);
- const half = (deg * Math.PI) / 360;
- const s = Math.sin(half);
- return [x * s, y * s, z * s, Math.cos(half)];
-}
-
-function vNorm(v) {
- const n = Math.hypot(v[0], v[1], v[2]);
- if (n < 1e-8) return [0, 0, 0];
- return [v[0] / n, v[1] / n, v[2] / n];
-}
-
-function vCross(a, b) {
- return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
-}
-
-function vDot(a, b) {
- return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
-}
-
-function vRot(q, v) {
- const p = qMul(qMul(q, [v[0], v[1], v[2], 0]), qConj(q));
- return [p[0], p[1], p[2]];
-}
-
-function shortestArc(from, to) {
- const f = vNorm(from);
- const t = vNorm(to);
- const d = vDot(f, t);
- if (d > 1 - 1e-9) return [...IDENT];
- if (d < -1 + 1e-9) {
- let axis = vCross(f, [1, 0, 0]);
- if (Math.hypot(...axis) < 1e-6) axis = vCross(f, [0, 1, 0]);
- const [x, y, z] = vNorm(axis);
- return [x, y, z, 0];
- }
- const axis = vCross(f, t);
- return qNorm([axis[0], axis[1], axis[2], 1 + d]);
-}
-
-// Orientation carrying rest axes (restDir, restNormal) onto (dir, normal):
-// swing to the direction, then a pure twist about it to line up the normal.
-function frameQuat(dir, normal, restDir, restNormal) {
- const swing = shortestArc(restDir, dir);
- const d = vNorm(dir);
- let n = vNorm(normal);
- n = vNorm([n[0] - d[0] * vDot(n, d), n[1] - d[1] * vDot(n, d), n[2] - d[2] * vDot(n, d)]);
- if (Math.hypot(...n) < 1e-5) return swing;
- let carried = vRot(swing, restNormal);
- carried = vNorm([
- carried[0] - d[0] * vDot(carried, d),
- carried[1] - d[1] * vDot(carried, d),
- carried[2] - d[2] * vDot(carried, d),
- ]);
- if (Math.hypot(...carried) < 1e-5) return swing;
- const twist = shortestArc(carried, n);
- const a = vDot([twist[0], twist[1], twist[2]], d);
- return qMul(qNorm([d[0] * a, d[1] * a, d[2] * a, twist[3]]), swing);
-}
-
-// ── the signing arm pose (right hand raised, palm out, left arm relaxed) ───
+// Letters with movement carry it as real movement in space: J hooks the pinky
+// down and around, Z draws the zig-zag with the index. Double letters bounce
+// outward between the two holds, the way signers disambiguate them.
//
-// Canonical rest is a T-pose (arms along ±X, palms down), so every arm bone
-// needs a pose even when "static": zero rotation would leave the avatar
-// signing from a T-pose. Locals are derived from target global directions the
-// same way the capture solver does it, so they read naturally on any rig.
-
-function chainLocals(side, upperDir, lowerDir, handDir, handNormal) {
- const s = side === 'Left' ? 1 : -1;
- const rest = [s, 0, 0];
- const gUpper = shortestArc(rest, upperDir);
- const lowerLocalDir = vRot(qConj(gUpper), lowerDir);
- const lowerLocal = shortestArc(rest, lowerLocalDir);
- const gLower = qMul(gUpper, lowerLocal);
- const gHand = frameQuat(handDir, handNormal, rest, [0, 1, 0]);
- const handLocal = qMul(qConj(gLower), gHand);
- return {
- [`${side}Arm`]: qNorm(gUpper),
- [`${side}ForeArm`]: qNorm(lowerLocal),
- [`${side}Hand`]: qNorm(handLocal),
- [`__g${side}Hand`]: gHand,
- [`__g${side}Lower`]: gLower,
- };
-}
-
-// Right hand up in signing space beside the shoulder: fingers up, palm to the
-// viewer (+Z), elbow dropped. The left arm hangs relaxed at the side using
-// locals sampled from the baked idle clip's first frame (the library's own
-// convention), which reads naturally after the retargeter's bind correction
-// where a geometrically-derived "down" did not.
-function signingPose() {
- const right = chainLocals('Right', vNorm([-0.25, -0.9, 0.3]), vNorm([-0.22, 0.38, 0.9]), [0, 1, 0], [0, 0, -1]);
- return {
- ...right,
- LeftArm: qNorm([0.5402, 0.1202, -0.0234, 0.8326]),
- LeftForeArm: qNorm([0.0199, 0.0244, 0.1378, 0.99]),
- LeftHand: qNorm([-0.0098, -0.0091, -0.029, 0.9995]),
- };
-}
-
-// ── handshape model ────────────────────────────────────────────────────────
-
-const FINGERS = ['Index', 'Middle', 'Ring', 'Pinky'];
-
-// Per-joint shares of a full curl (proximal knuckles carry most of it).
-const CURL_WEIGHTS = [85, 100, 65];
-
-// Thumb presets, as [joint1, joint2, joint3] rotations composed from curl
-// about the thumb hinge and swing toward/away from the palm. Tuned for the
-// right hand and mirrored for the left via axis sign.
-const THUMB_PRESETS = {
- // resting against the index side, pointing along the fingers
- side: { adduct: 22, curl: [8, 10, 5] },
- // extended away from the palm (L / Y / thumbs-out shapes)
- out: { adduct: -55, curl: [0, 0, 0] },
- // folded across the palm, under or over the curled fingers
- across: { adduct: 55, curl: [30, 45, 30] },
- // opposing the fingertips (O / F / D circles)
- oppose: { adduct: 40, curl: [18, 30, 22] },
- // tip pinned between index and middle (T) / at the middle knuckle (K)
- between: { adduct: 38, curl: [22, 30, 15] },
+// Scope note: fingerspelling spells English words; it is not grammatical ASL.
+// Lexical signs live in `src/sign-dictionary.js`, and `src/sign-speech.js`
+// prefers them, falling back here for anything with no sign of its own.
+
+import { HANDSHAPES, handshapeLocals } from './sign-handshapes.js';
+import { SignTimeline, posePhase, restingPose } from './sign-clip.js';
+
+export { HANDSHAPES, handshapeLocals, restingPose };
+
+/** Back-compat alias: the letter/digit subset of the handshape catalogue. */
+export const LETTER_SHAPES = HANDSHAPES;
+
+// Where fingerspelling happens: in front of the dominant shoulder, jaw height,
+// far enough forward to clear the body and be read comfortably.
+const SPELLING_PLACE = { anchor: 'chin', out: 0.19, up: -0.06, forward: 0.17 };
+
+// Per-letter departures from the citation orientation (fingers up, palm to the
+// reader). Directions are body-relative: `out` is away from the signer's
+// midline, `in` toward it, `forward` toward the person reading.
+const LETTER_ORIENT = {
+ // G and H lie the hand over: fingers point at the reader, palm toward the
+ // signer's other side.
+ G: { fingers: ['forward', 'up'], palm: 'in', at: { anchor: 'chin', out: 0.17, up: -0.12, forward: 0.2 } },
+ H: { fingers: ['forward', 'up'], palm: 'in', at: { anchor: 'chin', out: 0.17, up: -0.12, forward: 0.2 } },
+ // P and Q are K and G turned down toward the floor, and sit lower.
+ P: { fingers: ['down', 'forward'], palm: 'in', at: { anchor: 'chin', out: 0.17, up: -0.24, forward: 0.19 } },
+ Q: { fingers: ['down', 'forward'], palm: 'back', at: { anchor: 'chin', out: 0.15, up: -0.26, forward: 0.17 } },
+ // The thumb-out shapes read best angled slightly inward.
+ L: { palm: ['forward', 'in'] },
+ Y: { palm: ['forward', 'in'] },
+ // The closed shapes turn a few degrees off square so the knuckles catch light.
+ A: { palm: ['forward', 'out'] },
+ S: { palm: ['forward', 'out'] },
+ T: { palm: ['forward', 'out'] },
+ M: { palm: ['forward', 'out'] },
+ N: { palm: ['forward', 'out'] },
+ E: { palm: ['forward', 'out'] },
};
-// A handshape: curl 0..1 per finger (or [j1,j2,j3] explicit degrees), splay
-// in degrees (+ toward the thumb), a thumb preset, an optional wrist offset
-// {pitch,yaw,roll} in degrees applied on top of the signing pose, and an
-// optional motion ('J' | 'Z') traced inside the letter's time window.
-export const LETTER_SHAPES = {
- A: { curl: { Index: 1, Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
- B: { curl: {}, thumb: 'across' },
- C: { curl: { Index: 0.45, Middle: 0.45, Ring: 0.45, Pinky: 0.45 }, thumb: 'oppose' },
- D: { curl: { Middle: 0.7, Ring: 0.7, Pinky: 0.7 }, thumb: 'oppose' },
- E: { curl: { Index: 0.85, Middle: 0.85, Ring: 0.85, Pinky: 0.85 }, thumb: 'across' },
- F: { curl: { Index: 0.55 }, splay: { Middle: 6, Ring: 0, Pinky: -8 }, thumb: 'oppose' },
- G: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side', wrist: { local: [0, 1, 0], deg: 85 } },
- H: { curl: { Ring: 1, Pinky: 1 }, thumb: 'side', wrist: { local: [0, 1, 0], deg: 85 } },
- I: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'across' },
- J: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'across', motion: 'J' },
- K: { curl: { Middle: [40, 15, 10], Ring: 1, Pinky: 1 }, thumb: 'between' },
- L: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'out' },
- M: { curl: { Index: 0.75, Middle: 0.75, Ring: 0.75, Pinky: 0.95 }, thumb: 'across' },
- N: { curl: { Index: 0.75, Middle: 0.75, Ring: 0.95, Pinky: 0.95 }, thumb: 'across' },
- O: { curl: { Index: 0.55, Middle: 0.55, Ring: 0.55, Pinky: 0.55 }, thumb: 'oppose' },
- P: { curl: { Middle: [40, 15, 10], Ring: 1, Pinky: 1 }, thumb: 'between', wrist: { dir: [0.15, -0.85, 0.5], normal: [0, 1, 0.2] } },
- Q: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side', wrist: { dir: [0.15, -0.85, 0.5], normal: [0, 1, 0.2] } },
- R: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: -6, Middle: 8 }, thumb: 'across' },
- S: { curl: { Index: 1, Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'across' },
- T: { curl: { Index: 0.9, Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'between' },
- U: { curl: { Ring: 1, Pinky: 1 }, thumb: 'across' },
- V: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 9, Middle: -9 }, thumb: 'across' },
- W: { curl: { Pinky: 1 }, splay: { Index: 10, Middle: 0, Ring: -10 }, thumb: 'across' },
- X: { curl: { Index: [15, 95, 80], Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
- Y: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'out' },
- Z: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side', motion: 'Z' },
- // ASL number handshapes 0–9 (static). 6–9 touch the thumb to one
- // fingertip; the touched finger half-curls to meet the opposing thumb.
- 0: { curl: { Index: 0.55, Middle: 0.55, Ring: 0.55, Pinky: 0.55 }, thumb: 'oppose' },
- 1: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'across' },
- 2: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 9, Middle: -9 }, thumb: 'across' },
- 3: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 9, Middle: -9 }, thumb: 'out' },
- 4: { curl: {}, splay: { Index: 10, Middle: 3, Ring: -4, Pinky: -12 }, thumb: 'across' },
- 5: { curl: {}, splay: { Index: 10, Middle: 3, Ring: -4, Pinky: -12 }, thumb: 'out' },
- 6: { curl: { Pinky: 0.55 }, splay: { Index: 9, Middle: 0, Ring: -8 }, thumb: 'oppose' },
- 7: { curl: { Ring: 0.55 }, splay: { Index: 9, Middle: 0, Pinky: -10 }, thumb: 'oppose' },
- 8: { curl: { Middle: 0.55 }, splay: { Index: 9, Ring: -6, Pinky: -12 }, thumb: 'oppose' },
- 9: { curl: { Index: 0.55 }, splay: { Middle: 4, Ring: -4, Pinky: -12 }, thumb: 'oppose' },
-};
-
-// Wrist paths for the traced letters, keyed 0..1 across the letter window —
-// absolute {dir, normal} orientations like every other wrist spec. J dips and
-// supinates so the pinky draws the hook; Z jabs the index through the zigzag.
-const MOTIONS = {
+// Traced letters. Each step offsets the hand from the spelling place (metres,
+// body-relative) and may re-aim the fingers and palm — J swings the pinky down
+// and hooks it back in, Z jabs the index through the three strokes.
+const LETTER_MOTION = {
J: [
- { at: 0.0, wrist: { dir: [0, 1, 0], normal: [0, 0, -1] } },
- { at: 0.45, wrist: { dir: [0.15, 0.5, 0.85], normal: [0, -0.8, 0.2] } },
- { at: 1.0, wrist: { dir: [0.55, 0.6, 0.55], normal: [-0.8, 0, 0.2] } },
+ { at: 0.0, offset: { up: 0.02 }, palm: ['forward', 'in'] },
+ { at: 0.45, offset: { up: -0.1, out: 0.02 }, palm: ['forward', 'in'] },
+ { at: 0.75, offset: { up: -0.14, out: -0.05 }, palm: ['up', 'forward'] },
+ { at: 1.0, offset: { up: -0.09, out: -0.08 }, palm: ['up', 'in'] },
],
Z: [
- { at: 0.0, wrist: { dir: [0.35, 1, 0.1], normal: [0, 0, -1] } },
- { at: 0.3, wrist: { dir: [-0.35, 1, 0.1], normal: [0, 0, -1] } },
- { at: 0.7, wrist: { dir: [0.45, 0.65, 0.45], normal: [0, 0, -1] } },
- { at: 1.0, wrist: { dir: [-0.3, 0.6, 0.45], normal: [0, 0, -1] } },
+ { at: 0.0, offset: { out: 0.05, up: 0.06 } },
+ { at: 0.33, offset: { out: -0.07, up: 0.06 } },
+ { at: 0.66, offset: { out: 0.05, up: -0.05 } },
+ { at: 1.0, offset: { out: -0.07, up: -0.05 } },
],
};
-function fingerJointDegrees(spec) {
- if (Array.isArray(spec)) return spec;
- const amount = typeof spec === 'number' ? spec : 0;
- return CURL_WEIGHTS.map((w) => w * amount);
-}
-
-// Compile one handshape into finger-bone local quats for one side.
-export function handshapeLocals(letter, side = 'Right') {
- const shape = LETTER_SHAPES[letter];
- if (!shape) throw new Error(`no handshape for letter "${letter}"`);
- const s = side === 'Left' ? 1 : -1;
- const curlAxis = [0, 0, -s]; // hinge toward the palm (palms-down rest)
- const splayAxis = [0, 1, 0];
- const locals = {};
- for (const finger of FINGERS) {
- const deg = fingerJointDegrees(shape.curl?.[finger] ?? 0);
- const splay = shape.splay?.[finger] ?? 0;
- for (let j = 0; j < 3; j++) {
- let q = qAxisAngle(curlAxis, deg[j]);
- if (j === 0 && splay) q = qMul(q, qAxisAngle(splayAxis, splay * -s));
- locals[`${side}Hand${finger}${j + 1}`] = qNorm(q);
- }
- }
- const preset = THUMB_PRESETS[shape.thumb ?? 'side'];
- // Thumb rest points ~45° between the fingers and the palm-forward axis;
- // adduction swings it about the palm normal (toward/away from the palm
- // centre), curl bends its hinge toward the palm. Axes are side-mirrored.
- const thumbHinge = vNorm([-s * 0.5, 0, -0.85]);
- for (let j = 0; j < 3; j++) {
- let q = qAxisAngle(thumbHinge, preset.curl[j]);
- if (j === 0) q = qMul(qAxisAngle([0, 1, 0], preset.adduct * -s), q);
- locals[`${side}HandThumb${j + 1}`] = qNorm(q);
- }
- return locals;
-}
-
-// Hand local for an ABSOLUTE authored orientation: fingers toward `dir`, back
-// of hand toward `normal`, in the same authoring frame as the signing pose
-// (avatar faces +Z, up +Y, the right side of the body toward -X). Relative
-// deltas on the base wrist do not survive the retargeter's per-rig bind
-// correction, but absolute orientations built like the base pose do — the base
-// pose itself is the proof.
-function wristLocal(spec, gLower, restHand) {
- // Escape hatch for orientations that degenerate under absolute authoring
- // (a target direction near the bone's rest axis collapses to a pure twist,
- // which the bind correction scrambles): a plain local pre-rotation on the
- // base wrist, tuned against the live renderer (G / H use it).
- if (spec.local) return qNorm(qMul(restHand, qAxisAngle(spec.local, spec.deg)));
- const gHand = frameQuat(vNorm(spec.dir), vNorm(spec.normal), [-1, 0, 0], [0, 1, 0]);
- return qNorm(qMul(qConj(gLower), gHand));
-}
-
-// ── clip assembly ──────────────────────────────────────────────────────────
-
export const DEFAULT_TIMING = Object.freeze({
holdSeconds: 0.5,
transitionSeconds: 0.22,
@@ -291,128 +85,131 @@ export const DEFAULT_TIMING = Object.freeze({
tailSeconds: 0.4,
});
+/**
+ * Uppercase, drop anything unspellable, collapse whitespace. A–Z, 0–9 and
+ * single spaces survive.
+ * @param {string} word
+ * @returns {string}
+ */
export function normalizeWord(word) {
- const cleaned = String(word ?? '')
+ return String(word ?? '')
.toUpperCase()
.replace(/[^A-Z0-9 ]+/g, '')
.replace(/ +/g, ' ')
.trim();
- return cleaned;
}
-const NORMAL_BLEND_MODE = 2500;
+const SIDE = 'Right';
-function stableUuid(seed) {
- // FNV-1a over the seed, expanded to uuid shape — deterministic like the
- // capture lanes, so identical words produce identical documents.
- let h1 = 0x811c9dc5;
- let h2 = 0x01000193;
- for (let i = 0; i < seed.length; i++) {
- h1 = Math.imul(h1 ^ seed.charCodeAt(i), 0x01000193) >>> 0;
- h2 = Math.imul((h2 + seed.charCodeAt(i)) ^ (h1 >>> 5), 0x85ebca6b) >>> 0;
+/** The letter's place in signing space, plus an optional metre offset. */
+function letterPlace(letter, offset) {
+ const spec = { ...SPELLING_PLACE, ...(LETTER_ORIENT[letter]?.at ?? {}) };
+ if (offset) {
+ spec.out = (spec.out ?? 0) + (offset.out ?? 0);
+ spec.up = (spec.up ?? 0) + (offset.up ?? 0);
+ spec.forward = (spec.forward ?? 0) + (offset.forward ?? 0);
}
- const hex = (n) => n.toString(16).padStart(8, '0');
- const full = hex(h1) + hex(h2) + hex((h1 ^ 0x9e3779b9) >>> 0) + hex((h2 ^ 0x7f4a7c15) >>> 0);
- return `${full.slice(0, 8)}-${full.slice(8, 12)}-${full.slice(12, 16)}-${full.slice(16, 20)}-${full.slice(20, 32)}`.toUpperCase();
+ return spec;
}
/**
- * Build an AnimationClip JSON document that fingerspells `word` on the right
- * hand. Letters A–Z, digits 0–9, and spaces survive normalization; anything
- * else is dropped.
- * Returns the same document shape the animation library serves, ready for
- * THREE.AnimationClip.parse + the platform retarget engine.
+ * Full-body pose for one letter, optionally displaced (double-letter bounce) or
+ * re-aimed (a step of a traced letter).
+ * @param {string} letter
+ * @param {{ offset?: object, fingers?: any, palm?: any }} [opts]
+ * @param {import('./sign-rig.js').Pose} [base]
+ */
+export function letterPose(letter, opts = {}, base = restingPose()) {
+ if (!HANDSHAPES[letter]) throw new Error(`no handshape for letter "${letter}"`);
+ const orient = LETTER_ORIENT[letter] ?? {};
+ return posePhase(
+ {
+ right: {
+ shape: letter,
+ at: letterPlace(letter, opts.offset),
+ fingers: opts.fingers ?? orient.fingers ?? 'up',
+ palm: opts.palm ?? orient.palm ?? 'forward',
+ },
+ // The reading eye follows the hand: a small turn and tilt toward the
+ // spelling hand is what a signer does and what makes this look alive.
+ head: { turn: -3, tilt: 1.5 },
+ torso: { turn: -2 },
+ },
+ base,
+ );
+}
+
+/** The neutral hand a word starts and ends from: same place, open and relaxed. */
+function readyPose(base) {
+ return posePhase(
+ {
+ right: { shape: 'RELAXED', at: letterPlace('A', { up: -0.03, forward: -0.03 }), fingers: 'up', palm: ['forward', 'in'] },
+ head: { turn: -3, tilt: 1.5 },
+ torso: { turn: -2 },
+ },
+ base,
+ );
+}
+
+/**
+ * Build an AnimationClip JSON document that fingerspells `word` on the dominant
+ * hand. Letters A–Z, digits 0–9, and spaces survive normalization; anything else
+ * is dropped.
+ *
+ * @param {string} word
+ * @param {Partial<typeof DEFAULT_TIMING> & { name?: string, base?: import('./sign-rig.js').Pose, settle?: boolean }} [opts]
+ * @returns {object} clip document, ready for THREE.AnimationClip.parse + retarget
*/
export function buildFingerspellingClip(word, opts = {}) {
const timing = { ...DEFAULT_TIMING, ...opts };
const letters = normalizeWord(word);
if (!letters) throw new Error('word has no spellable characters (A-Z, 0-9)');
- const pose = signingPose();
- const restHand = pose.RightHand;
- const gLower = pose.__gRightLower;
- const neutralFingers = {};
- for (const finger of [...FINGERS, 'Thumb']) {
- for (let j = 1; j <= 3; j++) neutralFingers[`RightHand${finger}${j}`] = qAxisAngle([0, 0, 1], finger === 'Thumb' ? 4 : 12);
- }
+ const base = opts.base ?? restingPose();
+ const tl = new SignTimeline({ base });
+ const ready = readyPose(base);
- // Build the keyframe timeline: {time, locals} snapshots. Every snapshot
- // carries the full right-hand bone set so tracks stay aligned.
- const keys = [];
- const pushKey = (time, fingers, wristSpec) => {
- const locals = { ...fingers };
- locals.RightHand = wristSpec ? wristLocal(wristSpec, gLower, restHand) : restHand;
- keys.push({ time, locals });
- };
+ // Lift into signing space, then spell.
+ tl.to(ready, timing.leadSeconds, { ease: 'out' });
- let t = 0;
- pushKey(0, neutralFingers, null);
- t = timing.leadSeconds;
- let prevLetter = null;
+ let prev = null;
for (const ch of letters) {
if (ch === ' ') {
- pushKey(t + timing.transitionSeconds, neutralFingers, null);
- t += timing.transitionSeconds + timing.holdSeconds * 0.6;
- prevLetter = null;
+ // A word break is a small drop and re-set of the hand, not a pause.
+ tl.to(readyPose(base), timing.transitionSeconds, { ease: 'smooth' });
+ tl.hold(timing.holdSeconds * 0.5);
+ prev = null;
continue;
}
- const shape = LETTER_SHAPES[ch];
- const fingers = handshapeLocals(ch, 'Right');
- const isDouble = prevLetter === ch;
- if (isDouble) {
- // Small outward bounce between repeated letters.
- pushKey(t + timing.transitionSeconds * 0.6, { ...fingers }, { dir: [-0.3, 1, 0.1], normal: [0, 0, -1] });
- t += timing.transitionSeconds * 0.6;
+ if (prev === ch) {
+ // Doubled letter: bounce outward and back rather than holding one shape
+ // twice, which would read as a single letter.
+ tl.to(letterPose(ch, { offset: { out: 0.045, forward: -0.01 } }, base), timing.transitionSeconds * 0.55, { ease: 'out' });
}
- const wristBase = shape.wrist ?? null;
- if (shape.motion && MOTIONS[shape.motion]) {
- const start = t + timing.transitionSeconds;
- for (const step of MOTIONS[shape.motion]) {
- pushKey(start + step.at * timing.motionSeconds, fingers, step.wrist);
+ const motion = LETTER_MOTION[ch];
+ if (motion) {
+ const step = (s) => letterPose(ch, { offset: s.offset, fingers: s.fingers, palm: s.palm }, base);
+ tl.to(step(motion[0]), timing.transitionSeconds, { ease: 'smooth' });
+ for (let i = 1; i < motion.length; i++) {
+ const span = (motion[i].at - motion[i - 1].at) * timing.motionSeconds;
+ tl.to(step(motion[i]), span, { ease: i === motion.length - 1 ? 'in' : 'linear' });
}
- t = start + timing.motionSeconds;
} else {
- pushKey(t + timing.transitionSeconds, fingers, wristBase);
- pushKey(t + timing.transitionSeconds + timing.holdSeconds, fingers, wristBase);
- t += timing.transitionSeconds + timing.holdSeconds;
+ tl.to(letterPose(ch, {}, base), timing.transitionSeconds, { ease: 'smooth' });
+ tl.hold(timing.holdSeconds);
}
- prevLetter = ch;
+ prev = ch;
}
- pushKey(t + timing.tailSeconds, neutralFingers, null);
-
- // Static body pose: keep the whole figure composed while the hand spells.
- const staticBones = {
- RightArm: pose.RightArm,
- RightForeArm: pose.RightForeArm,
- LeftArm: pose.LeftArm,
- LeftForeArm: pose.LeftForeArm,
- LeftHand: pose.LeftHand,
- Hips: [...IDENT],
- Spine: qAxisAngle([1, 0, 0], 2),
- Spine1: [...IDENT],
- Spine2: [...IDENT],
- Neck: qAxisAngle([1, 0, 0], -3),
- Head: [...IDENT],
- };
- const duration = keys[keys.length - 1].time;
- const trackBones = Object.keys(keys[0].locals);
- const tracks = [];
- for (const bone of trackBones) {
- const times = keys.map((k) => k.time);
- const values = keys.flatMap((k) => k.locals[bone] ?? [...IDENT]);
- tracks.push({ type: 'quaternion', name: `${bone}.quaternion`, times, values });
- }
- for (const [bone, q] of Object.entries(staticBones)) {
- tracks.push({ type: 'quaternion', name: `${bone}.quaternion`, times: [0, duration], values: [...q, ...q] });
- }
- tracks.push({ type: 'vector', name: 'Hips.position', times: [0], values: [0, 0, 0] });
+ // Drop the hand back to rest unless the caller is stitching more signing on.
+ if (opts.settle === false) tl.hold(timing.tailSeconds);
+ else tl.settle(timing.tailSeconds);
- return {
+ return tl.build({
name: opts.name ?? `fingerspell-${letters.toLowerCase().replace(/ /g, '-')}`,
- duration,
- tracks,
- uuid: stableUuid(`fingerspell:${letters}:${timing.holdSeconds}:${timing.transitionSeconds}`),
- blendMode: NORMAL_BLEND_MODE,
- };
+ seed: `fingerspell:${letters}:${timing.holdSeconds}:${timing.transitionSeconds}:${timing.leadSeconds}:${timing.tailSeconds}`,
+ });
}
+
+/** The citation place for fingerspelling, so other lanes can match it. */
+export { SPELLING_PLACE };
diff --git a/src/sign-clip.js b/src/sign-clip.js
new file mode 100644
index 000000000..d4012db42
--- /dev/null
+++ b/src/sign-clip.js
@@ -0,0 +1,368 @@
+// Sign clip assembly — the shared authoring layer under fingerspelling and the
+// lexical sign dictionary.
+//
+// It gives both lanes the same three things:
+// • a resting signer (arms down, hands relaxed, spine settled) to start and
+// end every utterance from, so signing enters and leaves naturally instead
+// of snapping out of a bind pose,
+// • `posePhase()`, which turns a readable sign description — "flat hand, palm
+// out, at the chin" — into a solved full-body pose via the rig's IK,
+// • `SignTimeline`, which strings those poses together with eased transitions
+// and emits the SAME AnimationClip JSON document the pre-baked clip library
+// serves, so a sign retargets onto any rigged avatar with zero new playback
+// machinery (src/animation-retarget.js).
+//
+// Signs never write joint angles. They name a handshape, a place in signing
+// space, and which way the fingers and palm face; everything else is solved.
+
+import { applyHandshape, fingerBones } from './sign-handshapes.js';
+import {
+ Pose,
+ qAxisAngle,
+ qMul,
+ qSlerp,
+ signPoint,
+ solveArm,
+ vAdd,
+ vNorm,
+ vScale,
+} from './sign-rig.js';
+
+/**
+ * The bones a signing clip drives. Legs and hips are deliberately absent: an
+ * utterance is upper-body, so the avatar keeps whatever stance the clip it
+ * blended out of left it in, and the root never moves.
+ */
+export const SIGNING_BONES = Object.freeze([
+ 'Spine',
+ 'Spine1',
+ 'Spine2',
+ 'Neck',
+ 'Head',
+ ...['Left', 'Right'].flatMap((side) => [
+ `${side}Shoulder`,
+ `${side}Arm`,
+ `${side}ForeArm`,
+ `${side}Hand`,
+ ...fingerBones(side),
+ ]),
+]);
+
+// ── readable directions ────────────────────────────────────────────────────
+
+const BASE_DIRECTIONS = {
+ up: [0, 1, 0],
+ down: [0, -1, 0],
+ /** Toward the person being signed to. */
+ forward: [0, 0, 1],
+ /** Toward the signer's own body. */
+ back: [0, 0, -1],
+};
+
+/**
+ * Resolve a direction written the way a sign is described — `'up'`,
+ * `['down', 'forward']`, `'in'` (toward the midline), `'out'` (away from it) —
+ * into a unit vector in model space. Explicit `[x,y,z]` passes through.
+ *
+ * @param {string|string[]|number[]} spec
+ * @param {'Left'|'Right'} side
+ * @returns {number[]}
+ */
+export function direction(spec, side = 'Right') {
+ if (!spec) return null;
+ if (Array.isArray(spec) && typeof spec[0] === 'number') return vNorm(spec);
+ const names = Array.isArray(spec) ? spec : String(spec).split(/[\s-]+/);
+ const outward = side === 'Right' ? -1 : 1;
+ let acc = [0, 0, 0];
+ for (const name of names) {
+ const base = BASE_DIRECTIONS[name];
+ if (base) acc = vAdd(acc, base);
+ else if (name === 'out') acc = vAdd(acc, [outward, 0, 0]);
+ else if (name === 'in') acc = vAdd(acc, [-outward, 0, 0]);
+ else throw new Error(`unknown direction "${name}"`);
+ }
+ return vNorm(acc);
+}
+
+/**
+ * Resolve a place in signing space: an anchor name with body-relative offsets,
+ * an explicit point, or a `[anchor, offsets]` pair.
+ * @param {string|object|number[]} spec
+ * @param {'Left'|'Right'} side
+ * @returns {number[]}
+ */
+export function place(spec, side = 'Right') {
+ if (Array.isArray(spec) && typeof spec[0] === 'number') return spec;
+ if (typeof spec === 'string') return signPoint(spec, { side });
+ const { anchor = 'sternum', ...offsets } = spec;
+ return signPoint(anchor, { ...offsets, side });
+}
+
+// ── the resting signer ─────────────────────────────────────────────────────
+
+/** Where a relaxed arm hangs: down the side, elbow soft, palm toward the thigh. */
+const REST_ARM = {
+ at: { anchor: 'shoulder', out: 0.055, up: -0.47, forward: 0.06 },
+ fingers: ['down', 'forward'],
+ palm: 'in',
+ shape: 'RELAXED',
+};
+
+/**
+ * A signer at rest: arms down, hands relaxed, chest open, head level. Every
+ * utterance starts and ends here so signing has somewhere to come from and go
+ * back to.
+ * @returns {Pose}
+ */
+export function restingPose() {
+ const pose = new Pose();
+ // A little life in the spine: signers stand tall, not ramrod straight.
+ pose.setLocal('Spine', qMul(pose.getLocal('Spine'), qAxisAngle([1, 0, 0], 1.5)));
+ pose.setLocal('Spine2', qMul(pose.getLocal('Spine2'), qAxisAngle([1, 0, 0], -1)));
+ pose.setLocal('Neck', qMul(pose.getLocal('Neck'), qAxisAngle([1, 0, 0], -2)));
+ for (const side of ['Left', 'Right']) poseHand(pose, side, REST_ARM);
+ return pose;
+}
+
+/**
+ * Put one hand somewhere in signing space: handshape, location, and the
+ * directions the fingers and palm face. The arm is solved by IK, so the elbow
+ * and shoulder follow anatomically instead of being posed by hand.
+ *
+ * @param {Pose} pose mutated in place
+ * @param {'Left'|'Right'} side
+ * @param {{
+ * shape?: string,
+ * at?: string|object|number[],
+ * fingers?: string|string[]|number[],
+ * palm?: string|string[]|number[],
+ * pole?: string|string[]|number[],
+ * }} spec
+ * @returns {Pose}
+ */
+export function poseHand(pose, side, spec) {
+ if (spec.shape) applyHandshape(pose, spec.shape, side);
+ solveArm(pose, side, {
+ wrist: place(spec.at ?? REST_ARM.at, side),
+ fingers: direction(spec.fingers ?? 'up', side),
+ palm: direction(spec.palm ?? 'forward', side),
+ pole: spec.pole ? direction(spec.pole, side) : undefined,
+ });
+ return pose;
+}
+
+/**
+ * Build a whole-body pose for one phase of a sign.
+ *
+ * @param {{
+ * right?: object|'rest',
+ * left?: object|'rest',
+ * head?: { nod?: number, tilt?: number, turn?: number },
+ * torso?: { lean?: number, turn?: number },
+ * }} spec degrees for head/torso; `right`/`left` are {@link poseHand} specs.
+ * @param {Pose} [base] pose to build on (defaults to the resting signer)
+ * @returns {Pose}
+ */
+export function posePhase(spec, base = restingPose()) {
+ const pose = base.clone();
+ for (const side of ['Left', 'Right']) {
+ const hand = spec[side.toLowerCase()];
+ if (!hand) continue;
+ poseHand(pose, side, hand === 'rest' ? REST_ARM : hand);
+ }
+ const { head, torso } = spec;
+ if (torso) {
+ // Spread the lean across the spine so the torso curves instead of hinging.
+ for (const [bone, share] of [['Spine', 0.4], ['Spine1', 0.35], ['Spine2', 0.25]]) {
+ pose.setLocal(
+ bone,
+ qMul(
+ pose.getLocal(bone),
+ qMul(qAxisAngle([1, 0, 0], (torso.lean ?? 0) * share), qAxisAngle([0, 1, 0], (torso.turn ?? 0) * share)),
+ ),
+ );
+ }
+ }
+ if (head) {
+ const q = qMul(
+ qMul(qAxisAngle([1, 0, 0], head.nod ?? 0), qAxisAngle([0, 1, 0], head.turn ?? 0)),
+ qAxisAngle([0, 0, 1], head.tilt ?? 0),
+ );
+ // Split between neck and head so the whole column moves, not just the skull.
+ pose.setLocal('Neck', qMul(pose.getLocal('Neck'), qSlerp([0, 0, 0, 1], q, 0.45)));
+ pose.setLocal('Head', qMul(pose.getLocal('Head'), qSlerp([0, 0, 0, 1], q, 0.55)));
+ }
+ return pose;
+}
+
+// ── timeline → clip document ───────────────────────────────────────────────
+
+const NORMAL_BLEND_MODE = 2500;
+
+/** Smoothstep — the default ease for a transition between two sign phases. */
+const EASES = {
+ linear: (u) => u,
+ smooth: (u) => u * u * (3 - 2 * u),
+ /** Fast out of the hold, soft into the next one: how a hand actually moves. */
+ out: (u) => 1 - (1 - u) * (1 - u),
+ in: (u) => u * u,
+};
+
+// Interpolated keys inside each transition. Quaternion tracks are slerped
+// linearly by the mixer, so easing has to be baked as extra samples.
+const EASE_SAMPLES = 3;
+
+// Longest gap between keys, so the idle breath below is sampled smoothly
+// through a long hold rather than aliasing into a twitch.
+const MAX_KEY_GAP = 0.28;
+
+// A signer is never perfectly still. Amplitudes in degrees; the period is a
+// slow breath cycle.
+const BREATH = { period: 4.4, chest: 0.9, neck: 0.5, sway: 0.35 };
+
+function stableUuid(seed) {
+ // FNV-1a over the seed expanded to uuid shape — deterministic, so the same
+ // word compiles to the same document every time.
+ let h1 = 0x811c9dc5;
+ let h2 = 0x01000193;
+ for (let i = 0; i < seed.length; i++) {
+ h1 = Math.imul(h1 ^ seed.charCodeAt(i), 0x01000193) >>> 0;
+ h2 = Math.imul((h2 + seed.charCodeAt(i)) ^ (h1 >>> 5), 0x85ebca6b) >>> 0;
+ }
+ const hex = (n) => n.toString(16).padStart(8, '0');
+ const full = hex(h1) + hex(h2) + hex((h1 ^ 0x9e3779b9) >>> 0) + hex((h2 ^ 0x7f4a7c15) >>> 0);
+ return `${full.slice(0, 8)}-${full.slice(8, 12)}-${full.slice(12, 16)}-${full.slice(16, 20)}-${full.slice(20, 32)}`.toUpperCase();
+}
+
+/**
+ * A sequence of poses on a clock, compiled to an AnimationClip document.
+ *
+ * const tl = new SignTimeline();
+ * tl.to(posePhase({ right: { shape: 'B', at: 'chin', palm: 'forward' } }), 0.3);
+ * tl.hold(0.4);
+ * tl.settle(0.35);
+ * const clip = tl.build({ name: 'sign-hello' });
+ */
+export class SignTimeline {
+ /** @param {{ base?: Pose, breathe?: boolean }} [opts] */
+ constructor({ base = restingPose(), breathe = true } = {}) {
+ this.base = base;
+ this.breathe = breathe;
+ /** @type {{time:number, pose:Pose}[]} */
+ this.keys = [{ time: 0, pose: base }];
+ this.time = 0;
+ }
+
+ /** The pose the timeline currently ends on. */
+ get current() {
+ return this.keys[this.keys.length - 1].pose;
+ }
+
+ /** Hold the current pose for `seconds`. */
+ hold(seconds) {
+ if (seconds > 0) {
+ this.time += seconds;
+ this.keys.push({ time: this.time, pose: this.current });
+ }
+ return this;
+ }
+
+ /**
+ * Move to `pose` over `seconds`, easing so the hand accelerates out of the
+ * previous phase and settles into this one.
+ * @param {Pose} pose
+ * @param {number} seconds
+ * @param {{ ease?: keyof EASES }} [opts]
+ */
+ to(pose, seconds, { ease = 'smooth' } = {}) {
+ const from = this.current;
+ const curve = EASES[ease] ?? EASES.smooth;
+ const start = this.time;
+ if (seconds > 0) {
+ for (let i = 1; i <= EASE_SAMPLES; i++) {
+ const u = i / (EASE_SAMPLES + 1);
+ this.keys.push({ time: start + seconds * u, pose: blend(from, pose, curve(u)) });
+ }
+ this.time = start + seconds;
+ }
+ this.keys.push({ time: this.time, pose });
+ return this;
+ }
+
+ /** Return to the resting signer over `seconds` — how every utterance ends. */
+ settle(seconds) {
+ return this.to(this.base, seconds, { ease: 'in' });
+ }
+
+ /**
+ * Compile to the clip JSON the animation library and retargeter consume.
+ * @param {{ name: string, uuid?: string, seed?: string }} opts
+ * @returns {object}
+ */
+ build({ name, uuid, seed }) {
+ const keys = densify(this.keys, MAX_KEY_GAP);
+ const driven = new Set();
+ for (const key of keys) for (const bone of key.pose.local.keys()) driven.add(bone);
+ // Always emit the full signing set, so merging two segments never leaves a
+ // bone stranded at whatever a previous sign left it holding.
+ for (const bone of SIGNING_BONES) driven.add(bone);
+
+ const times = keys.map((k) => k.time);
+ const tracks = [];
+ for (const bone of driven) {
+ const values = [];
+ for (const key of keys) {
+ let q = key.pose.getLocal(bone);
+ if (this.breathe) q = breathe(bone, q, key.time);
+ values.push(q[0], q[1], q[2], q[3]);
+ }
+ tracks.push({ type: 'quaternion', name: `${bone}.quaternion`, times: [...times], values });
+ }
+ return {
+ name,
+ duration: times[times.length - 1],
+ tracks,
+ uuid: uuid ?? stableUuid(seed ?? name),
+ blendMode: NORMAL_BLEND_MODE,
+ };
+ }
+}
+
+/** Per-bone slerp between two poses. */
+function blend(a, b, t) {
+ const out = new Pose(a);
+ const bones = new Set([...a.local.keys(), ...b.local.keys()]);
+ for (const bone of bones) out.setLocal(bone, qSlerp(a.getLocal(bone), b.getLocal(bone), t));
+ return out;
+}
+
+/** Insert interpolated keys so no gap exceeds `maxGap` seconds. */
+function densify(keys, maxGap) {
+ const out = [keys[0]];
+ for (let i = 1; i < keys.length; i++) {
+ const prev = keys[i - 1];
+ const next = keys[i];
+ const span = next.time - prev.time;
+ const steps = Math.ceil(span / maxGap);
+ for (let s = 1; s < steps; s++) {
+ const u = s / steps;
+ out.push({ time: prev.time + span * u, pose: blend(prev.pose, next.pose, u) });
+ }
+ out.push(next);
+ }
+ return out;
+}
+
+// Breathing + micro-sway, layered on top of the authored pose. Small enough to
+// read as life rather than motion, but the difference between a signing avatar
+// and a mannequin holding a shape.
+function breathe(bone, q, time) {
+ const phase = (time / BREATH.period) * Math.PI * 2;
+ if (bone === 'Spine1') return qMul(q, qAxisAngle([1, 0, 0], Math.sin(phase) * BREATH.chest));
+ if (bone === 'Spine2') return qMul(q, qAxisAngle([0, 1, 0], Math.sin(phase * 0.5) * BREATH.sway));
+ if (bone === 'Neck') return qMul(q, qAxisAngle([1, 0, 0], -Math.sin(phase) * BREATH.neck));
+ if (bone === 'Head') return qMul(q, qAxisAngle([0, 1, 0], Math.sin(phase * 0.37) * BREATH.sway));
+ return q;
+}
+
+export { stableUuid };
diff --git a/src/sign-handshapes.js b/src/sign-handshapes.js
new file mode 100644
index 000000000..e590946ea
--- /dev/null
+++ b/src/sign-handshapes.js
@@ -0,0 +1,168 @@
+// ASL handshapes — the finger configurations both lanes of the signing stack
+// share: the manual alphabet (fingerspelling) and the lexical sign dictionary.
+//
+// A handshape is described the way a signer would describe it — how far each
+// finger curls, how the fingers spread, where the thumb sits — never as raw
+// joint quaternions. The compiler turns that description into local rotations
+// about axes MEASURED from the reference skeleton (src/sign-rig.js), so the same
+// description drives either hand with no mirrored sign flipping, and a rig whose
+// finger bones rest at a different angle still curls its fingers into the palm
+// instead of sideways.
+//
+// Handshape names follow standard ASL naming: the letters and digits that double
+// as shapes (`B`, `S`, `1`, `5`, …) plus the named ones that don't (`CLAW`,
+// `FLAT_O`, `BENT_B`, `OPEN_8`).
+
+import { adductAxis, curlAxis, qAxisAngle, qMul, qNorm, splayAxis } from './sign-rig.js';
+
+export const FINGERS = ['Index', 'Middle', 'Ring', 'Pinky'];
+export const FINGER_JOINTS = [1, 2, 3];
+
+/** Every finger bone of one hand, in the order the clip tracks are emitted. */
+export function fingerBones(side) {
+ return [...FINGERS, 'Thumb'].flatMap((f) => FINGER_JOINTS.map((j) => `${side}Hand${f}${j}`));
+}
+
+// Share of a full curl carried by each joint. The proximal knuckle leads, the
+// middle joint closes hardest, the tip trails — the proportions a relaxed hand
+// actually closes with, which is what keeps a fist from reading as a claw.
+const CURL_WEIGHTS = [78, 100, 62];
+
+// Thumb positions, as adduction (toward the fingers, across the palm) plus a
+// per-joint curl. Every ASL handshape uses one of these five.
+const THUMB_PRESETS = {
+ /** Alongside the index, pointing with the fingers — A, G, L-less shapes. */
+ side: { adduct: 18, curl: [10, 12, 6], lift: 6 },
+ /** Extended clear of the palm — L, Y, 5, and the "thumb out" shapes. */
+ out: { adduct: -48, curl: [0, 0, 0], lift: 10 },
+ /** Folded across the closed fingers — B, S, E, M, N. */
+ across: { adduct: 52, curl: [26, 40, 26], lift: -4 },
+ /** Opposing the fingertips, as in O, C, F and the 6–9 digits. */
+ oppose: { adduct: 36, curl: [20, 32, 24], lift: 2 },
+ /** Tucked between fingers — T, K, P. */
+ between: { adduct: 34, curl: [24, 30, 16], lift: -2 },
+};
+
+/**
+ * The handshape catalogue. `curl` is 0–1 per finger (or explicit per-joint
+ * degrees), `splay` is degrees toward the thumb (negative = toward the pinky),
+ * `knuckle` bends only the proximal joint (the flat-then-bent shapes), and
+ * `thumb` names a preset.
+ */
+export const HANDSHAPES = Object.freeze({
+ A: { curl: { Index: 1, Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
+ B: { curl: {}, splay: { Index: 2, Middle: 1, Ring: -1, Pinky: -3 }, thumb: 'across' },
+ C: { curl: { Index: 0.42, Middle: 0.45, Ring: 0.48, Pinky: 0.5 }, thumb: 'oppose' },
+ D: { curl: { Middle: 0.72, Ring: 0.72, Pinky: 0.72 }, thumb: 'oppose' },
+ E: { curl: { Index: 0.82, Middle: 0.85, Ring: 0.85, Pinky: 0.82 }, thumb: 'across' },
+ F: { curl: { Index: 0.55 }, splay: { Middle: 7, Ring: 0, Pinky: -9 }, thumb: 'oppose' },
+ G: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
+ H: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 2, Middle: -2 }, thumb: 'side' },
+ I: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'across' },
+ J: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'across' },
+ K: { curl: { Middle: [42, 12, 8], Ring: 1, Pinky: 1 }, splay: { Index: 10, Middle: -6 }, thumb: 'between' },
+ L: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'out' },
+ M: { curl: { Index: 0.72, Middle: 0.74, Ring: 0.76, Pinky: 0.95 }, thumb: 'across' },
+ N: { curl: { Index: 0.72, Middle: 0.74, Ring: 0.95, Pinky: 0.95 }, thumb: 'across' },
+ O: { curl: { Index: 0.52, Middle: 0.55, Ring: 0.58, Pinky: 0.6 }, thumb: 'oppose' },
+ P: { curl: { Middle: [42, 12, 8], Ring: 1, Pinky: 1 }, splay: { Index: 10, Middle: -6 }, thumb: 'between' },
+ Q: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
+ R: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: -7, Middle: 9 }, thumb: 'across' },
+ S: { curl: { Index: 1, Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'across' },
+ T: { curl: { Index: 0.88, Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'between' },
+ U: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 1, Middle: -1 }, thumb: 'across' },
+ V: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 10, Middle: -10 }, thumb: 'across' },
+ W: { curl: { Pinky: 1 }, splay: { Index: 11, Middle: 0, Ring: -11 }, thumb: 'across' },
+ X: { curl: { Index: [18, 92, 78], Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
+ Y: { curl: { Index: 1, Middle: 1, Ring: 1 }, thumb: 'out' },
+ Z: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },
+
+ // ASL number handshapes. 6–9 touch the thumb to one fingertip, so the
+ // touched finger half-curls to meet the opposing thumb.
+ 0: { curl: { Index: 0.52, Middle: 0.55, Ring: 0.58, Pinky: 0.6 }, thumb: 'oppose' },
+ 1: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'across' },
+ 2: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 10, Middle: -10 }, thumb: 'across' },
+ 3: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 10, Middle: -10 }, thumb: 'out' },
+ 4: { curl: {}, splay: { Index: 11, Middle: 4, Ring: -5, Pinky: -13 }, thumb: 'across' },
+ 5: { curl: {}, splay: { Index: 12, Middle: 4, Ring: -5, Pinky: -14 }, thumb: 'out' },
+ 6: { curl: { Pinky: 0.55 }, splay: { Index: 9, Middle: 0, Ring: -9 }, thumb: 'oppose' },
+ 7: { curl: { Ring: 0.55 }, splay: { Index: 9, Middle: 0, Pinky: -11 }, thumb: 'oppose' },
+ 8: { curl: { Middle: 0.55 }, splay: { Index: 9, Ring: -7, Pinky: -13 }, thumb: 'oppose' },
+ 9: { curl: { Index: 0.55 }, splay: { Middle: 5, Ring: -5, Pinky: -13 }, thumb: 'oppose' },
+
+ // Shapes with no letter name of their own.
+ /** Spread and curved, like holding a ball — used by many "grab" signs. */
+ CLAW: { curl: { Index: 0.45, Middle: 0.45, Ring: 0.45, Pinky: 0.45 }, splay: { Index: 10, Middle: 3, Ring: -4, Pinky: -12 }, thumb: 'oppose' },
+ /** Flat hand, fingers together — the citation "flat B" used everywhere. */
+ FLAT: { curl: {}, splay: { Index: 2, Middle: 1, Ring: -1, Pinky: -3 }, thumb: 'side' },
+ /** Flat hand bent at the knuckles — HAPPY, THANK YOU's release, YOUR. */
+ BENT_B: { curl: {}, knuckle: 52, thumb: 'across' },
+ /** Fingers together pinched to the thumb — the closing shape of many signs. */
+ FLAT_O: { curl: { Index: 0.6, Middle: 0.62, Ring: 0.64, Pinky: 0.66 }, knuckle: 22, thumb: 'oppose' },
+ /** Open hand with the middle finger dropped to the palm — FEEL, SICK. */
+ OPEN_8: { curl: { Middle: 0.62 }, splay: { Index: 9, Ring: -6, Pinky: -12 }, thumb: 'out' },
+ /** Relaxed, slightly-curled hand: what a hand does when it isn't signing. */
+ RELAXED: { curl: { Index: 0.18, Middle: 0.22, Ring: 0.26, Pinky: 0.3 }, thumb: 'side' },
+ /** Index and pinky out — the ILY / "rock on" family. */
+ ILY: { curl: { Middle: 1, Ring: 1 }, splay: { Index: 6, Pinky: -6 }, thumb: 'out' },
+});
+
+/** Names of every handshape, for docs and tooling. */
+export const HANDSHAPE_NAMES = Object.freeze(Object.keys(HANDSHAPES));
+
+function jointDegrees(spec) {
+ if (Array.isArray(spec)) return spec;
+ const amount = typeof spec === 'number' ? spec : 0;
+ return CURL_WEIGHTS.map((w) => w * amount);
+}
+
+/**
+ * Compile a handshape into local rotations for one hand's finger bones.
+ *
+ * @param {string} name a HANDSHAPES key (letter, digit, or named shape)
+ * @param {'Left'|'Right'} [side]
+ * @returns {Record<string, number[]>} bone → [x,y,z,w]
+ */
+export function handshapeLocals(name, side = 'Right') {
+ const shape = HANDSHAPES[name];
+ if (!shape) throw new Error(`no handshape "${name}"`);
+ const locals = {};
+
+ for (const finger of FINGERS) {
+ const curl = jointDegrees(shape.curl?.[finger] ?? 0);
+ const splay = shape.splay?.[finger] ?? 0;
+ for (const j of FINGER_JOINTS) {
+ const bone = `${side}Hand${finger}${j}`;
+ const bend = curl[j - 1] + (j === 1 ? (shape.knuckle ?? 0) : 0);
+ let q = qAxisAngle(curlAxis(bone), bend);
+ // Spread happens at the knuckle only, and always outside the curl so
+ // a curled finger still fans from the same origin.
+ if (j === 1 && splay) q = qMul(qAxisAngle(splayAxis(bone), splay), q);
+ locals[bone] = qNorm(q);
+ }
+ }
+
+ const thumb = THUMB_PRESETS[shape.thumb ?? 'side'];
+ for (const j of FINGER_JOINTS) {
+ const bone = `${side}HandThumb${j}`;
+ let q = qAxisAngle(curlAxis(bone), thumb.curl[j - 1]);
+ if (j === 1) {
+ // The base joint also swings the thumb across the palm (adduction) and
+ // lifts it off the palm plane, which is what separates an A from an S.
+ q = qMul(qMul(qAxisAngle(adductAxis(bone), thumb.adduct), qAxisAngle(splayAxis(bone), thumb.lift ?? 0)), q);
+ }
+ locals[bone] = qNorm(q);
+ }
+ return locals;
+}
+
+/**
+ * Apply a handshape to a {@link import('./sign-rig.js').Pose} in place.
+ * @param {import('./sign-rig.js').Pose} pose
+ * @param {string} name
+ * @param {'Left'|'Right'} side
+ */
+export function applyHandshape(pose, name, side) {
+ for (const [bone, q] of Object.entries(handshapeLocals(name, side))) pose.setLocal(bone, q);
+ return pose;
+}
diff --git a/src/sign-rig.js b/src/sign-rig.js
index 8d69d6199..36aee19a4 100644
--- a/src/sign-rig.js
+++ b/src/sign-rig.js
@@ -338,6 +338,15 @@ export function splayAxis(bone) {
return vNorm(vCross(boneAxis(bone), radialAxis(bone)));
}
+/**
+ * LOCAL adduction axis of a thumb joint: a POSITIVE angle swings the thumb in
+ * toward the fingers (across the palm), a negative one out away from them.
+ */
+export function adductAxis(bone) {
+ const handDir = restDirWorld(`${sideOf(bone)}Hand`);
+ return vNorm(vCross(boneAxis(bone), qRotate(qConj(restWorld(bone)), handDir)));
+}
+
// ── the signing body: anchors and workspace ────────────────────────────────
/**
@@ -366,7 +375,12 @@ export const ANCHORS = (() => {
neck,
chest,
hips,
+ /** Side-aware anchors: `signPoint('shoulder', { side })` picks the right one. */
shoulder: { Left: shoulderL, Right: shoulderR },
+ hip: {
+ Left: [Math.abs(shoulderL[0]) * 0.55, hips[1], hips[2]],
+ Right: [-Math.abs(shoulderR[0]) * 0.55, hips[1], hips[2]],
+ },
forehead: [0, head[1] + 0.07, head[2]],
chin: [0, chinY, head[2] + 0.03],
mouth: [0, chinY + 0.04, head[2] + 0.04],
@@ -388,9 +402,11 @@ export const ANCHORS = (() => {
* @returns {number[]} model-space point
*/
export function signPoint(anchor, offset = {}) {
- const base = Array.isArray(anchor) ? anchor : ANCHORS[anchor];
- if (!base) throw new Error(`unknown sign anchor "${anchor}"`);
const side = offset.side ?? 'Right';
+ let base = Array.isArray(anchor) ? anchor : ANCHORS[anchor];
+ // Side-aware anchors (shoulder, hip) resolve against the acting hand.
+ if (base && !Array.isArray(base)) base = base[side];
+ if (!base) throw new Error(`unknown sign anchor "${anchor}"`);
const outSign = side === 'Right' ? -1 : 1; // the right hand's "out" is −X
return [
base[0] + outSign * (offset.out ?? 0),