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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
pose studio: fingerspell any word in ASL on the avatar's right hand
nirholaseecd8490f074
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 37e8a6510..e60f280d1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Graduated-coin prices now match PumpSwap exactly** — PumpSwap changed how pool prices are calculated: a pool can now hold quote-side liquidity that is not sitting in its vault, and prices have to count it. Every place we price a graduated coin has been updated to match, so quotes, price impact, market caps, and agent trade fills line up with what actually executes on-chain. Coins that have not graduated are unaffected, and the change is exact rather than approximate: where a pool carries none of this liquidity, prices are identical to before. `[fix, infra]`- **One page for every policy, and a clear way to report something** — three.ws had six legal documents and no index, so /legal itself went nowhere. It is now a real page: every policy listed with a plain-language summary and its effective date, plus which address actually reaches the right desk (copyright, abuse, privacy, general, support). Publishers who think we are showing too much of their work get a direct answer and a direct address instead of a search. (`/legal`) `[improvement, docs]`- **Swap quotes now show the reserves they were priced from** — The pump.fun MCP swap-quote tool used to hand back a price and nothing else, so there was no way to check it. It now also returns the pool reserves the quote was computed from, including the virtual quote reserves PumpSwap added last week, so an agent or a person can reproduce the number instead of trusting it. The tool descriptions were also rewritten to keep the bonding curve and the PumpSwap pool apart: both now have a field called virtual_quote_reserves, they mean different things, and conflating them was an easy way to read a coin's price as zero. (`/docs/mcp`) `[improvement, sdk]`+- **The live economy now paces itself instead of going quiet** — The agent economy used to run at a fixed rate until its treasury ran dry, then fall silent for hours until someone refilled it by hand. It now measures what it can afford each minute and paces itself: when funds are lean it keeps trials, reviews, and marketplace listings flowing while pausing the actions that spend, then automatically speeds back up as revenue comes in. The result is a Money Pulse that stays alive continuously rather than running in bursts. (`/pulse`) `[improvement, infra]`+- **Your avatar can fingerspell in American Sign Language** — The Animation Studio at /pose has a new Spell box: type any word and your avatar spells it letter by letter in ASL on its right hand, with all 26 handshapes, the traced J and Z motions, and the little bounce signers use for double letters. Spelling is built instantly on your device (no network round-trip), plays on any rigged avatar, and exports as an animated GLB like any other clip. This is the first step toward signing avatars for deaf and hard-of-hearing users, alongside the new hand-and-finger motion capture in Motion Swap. (`/pose`) `[feature]`## 2026-07-19diff --git a/data/changelog.json b/data/changelog.jsonindex 567280b41..31fb4b699 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -15038,6 +15038,15 @@"docs"],"link": "/legal"+ },+ {+ "date": "2026-07-20",+ "title": "Your avatar can fingerspell in American Sign Language",+ "summary": "The Animation Studio at /pose has a new Spell box: type any word and your avatar spells it letter by letter in ASL on its right hand, with all 26 handshapes, the traced J and Z motions, and the little bounce signers use for double letters. Spelling is built instantly on your device (no network round-trip), plays on any rigged avatar, and exports as an animated GLB like any other clip. This is the first step toward signing avatars for deaf and hard-of-hearing users, alongside the new hand-and-finger motion capture in Motion Swap.",+ "tags": [+ "feature"+ ],+ "link": "/pose"}]}diff --git a/pages/pose.html b/pages/pose.htmlindex 52f69eb72..b3ecec5eb 100644--- a/pages/pose.html+++ b/pages/pose.html@@ -631,6 +631,26 @@.al-gen[data-busy='true'] .al-gen-input {opacity: 0.6;}+ .al-spell .al-gen-input {+ background: rgba(167, 139, 250, 0.06);+ border-color: rgba(167, 139, 250, 0.4);+ }+ .al-spell .al-gen-input:focus {+ border-color: rgba(167, 139, 250, 0.75);+ }+ .al-spell .al-gen-btn {+ border-color: rgba(167, 139, 250, 0.4);+ background: rgba(167, 139, 250, 0.14);+ color: #ede9fe;+ }+ .al-spell .al-gen-btn:hover:not(:disabled) {+ background: rgba(167, 139, 250, 0.24);+ border-color: rgba(167, 139, 250, 0.7);+ }+ .al-spell .al-gen-btn:focus-visible {+ border-color: rgba(167, 139, 250, 0.85);+ box-shadow: 0 0 0 2px rgba(167, 139, 250, 0.3);+ }.al-search {width: 100%;box-sizing: border-box;diff --git a/public/changelog.json b/public/changelog.jsonindex ca2adbac5..6c24a742b 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-20T20:59:16.189Z",+ "generated_at": "2026-07-20T21:07:31.566Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -90,6 +90,27 @@"sdk"]},+ {+ "date": "2026-07-20",+ "type": "update",+ "title": "The live economy now paces itself instead of going quiet",+ "summary": "The agent economy used to run at a fixed rate until its treasury ran dry, then fall silent for hours until someone refilled it by hand. It now measures what it can afford each minute and paces itself: when funds are lean it keeps trials, reviews, and marketplace listings flowing while pausing the actions that spend, then automatically speeds back up as revenue comes in. The result is a Money Pulse that stays alive continuously rather than running in bursts.",+ "link": "/pulse",+ "tags": [+ "improvement",+ "infra"+ ]+ },+ {+ "date": "2026-07-20",+ "type": "update",+ "title": "Your avatar can fingerspell in American Sign Language",+ "summary": "The Animation Studio at /pose has a new Spell box: type any word and your avatar spells it letter by letter in ASL on its right hand, with all 26 handshapes, the traced J and Z motions, and the little bounce signers use for double letters. Spelling is built instantly on your device (no network round-trip), plays on any rigged avatar, and exports as an animated GLB like any other clip. This is the first step toward signing avatars for deaf and hard-of-hearing users, alongside the new hand-and-finger motion capture in Motion Swap.",+ "link": "/pose",+ "tags": [+ "feature"+ ]+ },{"date": "2026-07-19","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex c0e50eb66..ed72d76db 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -70,6 +70,22 @@<category>improvement</category><description>The pump.fun MCP swap-quote tool used to hand back a price and nothing else, so there was no way to check it. It now also returns the pool reserves the quote was computed from, including the virtual quote reserves PumpSwap added last week, so an agent or a person can reproduce the number instead of trusting it. The tool descriptions were also rewritten to keep the bonding curve and the PumpSwap pool apart: both now have a field called virtual_quote_reserves, they mean different things, and conflating them was an easy way to read a coin's price as zero.</description></item>+ <item>+ <title>The live economy now paces itself instead of going quiet</title>+ <link>https://three.ws/pulse</link>+ <guid isPermaLink="false">2026-07-20:The live economy now paces itself instead of going quiet</guid>+ <pubDate>Mon, 20 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The agent economy used to run at a fixed rate until its treasury ran dry, then fall silent for hours until someone refilled it by hand. It now measures what it can afford each minute and paces itself: when funds are lean it keeps trials, reviews, and marketplace listings flowing while pausing the actions that spend, then automatically speeds back up as revenue comes in. The result is a Money Pulse that stays alive continuously rather than running in bursts.</description>+ </item>+ <item>+ <title>Your avatar can fingerspell in American Sign Language</title>+ <link>https://three.ws/pose</link>+ <guid isPermaLink="false">2026-07-20:Your avatar can fingerspell in American Sign Language</guid>+ <pubDate>Mon, 20 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The Animation Studio at /pose has a new Spell box: type any word and your avatar spells it letter by letter in ASL on its right hand, with all 26 handshapes, the traced J and Z motions, and the little bounce signers use for double letters. Spelling is built instantly on your device (no network round-trip), plays on any rigged avatar, and exports as an animated GLB like any other clip. This is the first step toward signing avatars for deaf and hard-of-hearing users, alongside the new hand-and-finger motion capture in Motion Swap.</description>+ </item><item><title>Agent Sniper: Autonomous On-Chain Trading</title><link>https://three.ws/docs/agent-sniper</link>diff --git a/public/features.json b/public/features.jsonindex 2b80824a7..f1b251a41 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-20T20:59:16.156Z",+ "generated_at": "2026-07-20T21:07:31.547Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/animation-library.js b/src/animation-library.jsindex 64d9ce05c..77d6e2a99 100644--- a/src/animation-library.js+++ b/src/animation-library.js@@ -16,6 +16,7 @@ import { AnimationMixer, LoopOnce, LoopRepeat } from 'three';import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';import { curate } from './animation-presets.js';+import { buildFingerspellingClip, normalizeWord } from './fingerspelling.js';import {retargetClipToRig,scaleClipSpeed,@@ -281,6 +282,32 @@ export class AnimationLibrary {});const gen = el('div', { class: 'al-gen' }, [genInput, genBtn]);+ // Fingerspell: spell any word in ASL on the avatar's right hand. Built+ // locally and deterministically (src/fingerspelling.js) — no network,+ // instant, and the result exports like any other clip.+ const spellInput = el('input', {+ type: 'text',+ class: 'al-gen-input',+ placeholder: 'Fingerspell in ASL — try your name',+ 'aria-label': 'Fingerspell a word in American Sign Language',+ autocomplete: 'off',+ maxlength: '40',+ });+ const spellBtn = el(+ 'button',+ { class: 'al-gen-btn', type: 'button', title: 'Spell the word letter by letter in American Sign Language' },+ ['🤟 Spell'],+ );+ const submitSpell = () => this.spellWord(spellInput.value);+ spellBtn.addEventListener('click', submitSpell);+ spellInput.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ submitSpell();+ }+ });+ const spell = el('div', { class: 'al-gen al-spell' }, [spellInput, spellBtn]);+const search = el('input', {type: 'search',class: 'al-search',@@ -303,11 +330,12 @@ export class AnimationLibrary {// Shell refs first; _renderTransport() merges its own sub-refs (label,// speed, export button) into this._refs, so it must run after this assign.- this._refs = { gen, genInput, genBtn, search, chips, grid, empty };+ this._refs = { gen, genInput, genBtn, spell, spellInput, spellBtn, search, chips, grid, empty };const transport = this._renderTransport();this._refs.transport = transport;this.host.appendChild(gen);+ this.host.appendChild(spell);this.host.appendChild(search);// Now-playing transport sits directly under the search so it's visible the// moment a clip plays (hidden until then) — not buried below the card grid.@@ -319,9 +347,10 @@ export class AnimationLibrary {_setState(state) {this._state = state;- const { gen, search, chips, grid, empty, transport } = this._refs;+ const { gen, spell, search, chips, grid, empty, transport } = this._refs;const ready = state === 'ready';if (gen) gen.style.display = ready ? '' : 'none';+ if (spell) spell.style.display = ready ? '' : 'none';search.style.display = ready ? '' : 'none';chips.style.display = ready ? '' : 'none';grid.style.display = ready ? '' : 'none';@@ -662,6 +691,43 @@ export class AnimationLibrary {throw new Error('Generation timed out. Try a shorter prompt.');}+ // ── Fingerspell ─────────────────────────────────────────────────────────+ /**+ * Spell a word in American Sign Language on the rig's right hand. The clip+ * is built locally and deterministically (src/fingerspelling.js) and plays+ * through the same retarget/transport path as a preset, so speed, scrub,+ * and animated-GLB export all work on a spelled word. Returns true on play.+ */+ spellWord(word) {+ const letters = normalizeWord(word);+ if (!letters) {+ this.setStatus('Type a word to fingerspell — letters A–Z.', 'error');+ return false;+ }+ const rig = this.getRig();+ if (!rig || rig.kind === 'mannequin') {+ this.setStatus('Load a rigged avatar to fingerspell.', 'error');+ return false;+ }+ let clip;+ try {+ const json = buildFingerspellingClip(letters);+ clip = parseClipJSON(json, json.name);+ this._clipCache.set(json.name, clip);+ } catch (err) {+ this.setStatus(`Couldn’t build the spelling: ${err.message}`, 'error');+ return false;+ }+ const def = {+ name: clip.name,+ label: `Fingerspell “${letters}”`,+ icon: '🤟',+ loop: false,+ spelled: true,+ };+ return this._playClip(clip, def);+ }+_stopGenTimer() {if (this._genTimer) {clearInterval(this._genTimer);diff --git a/src/fingerspelling.js b/src/fingerspelling.jsnew file mode 100644index 000000000..add50cf4a--- /dev/null+++ b/src/fingerspelling.js@@ -0,0 +1,398 @@+// 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,+ };+}++// 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.3, -0.85, 0.3]), vNorm([0.1, 0.8, 0.45]), [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', wrist: { yaw: -45 } },+ 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: { pitch: -80, roll: -90 } },+ H: { curl: { Ring: 1, Pinky: 1 }, thumb: 'side', wrist: { pitch: -80, roll: -90 } },+ 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: { pitch: -110 } },+ Q: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side', wrist: { pitch: -110 } },+ 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' },+};++// Wrist paths for the traced letters, keyed 0..1 across the letter window.+const MOTIONS = {+ J: [+ { at: 0.0, wrist: { pitch: 0, yaw: 0, roll: 0 } },+ { at: 0.45, wrist: { pitch: -35, yaw: 0, roll: -30 } },+ { at: 1.0, wrist: { pitch: -20, yaw: 15, roll: -80 } },+ ],+ Z: [+ { at: 0.0, wrist: { pitch: 0, yaw: 18, roll: 0 } },+ { at: 0.3, wrist: { pitch: 0, yaw: -18, roll: 0 } },+ { at: 0.7, wrist: { pitch: -25, yaw: 18, roll: 0 } },+ { at: 1.0, wrist: { pitch: -25, yaw: -18, roll: 0 } },+ ],+};++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;+}++function wristOffsetQuat(off, s = -1) {+ // pitch: tip the fingers forward/back; yaw: turn the palm; roll: rotate+ // about the finger axis. Expressed in the raised-hand frame (fingers +Y,+ // palm +Z), applied as a local pre-rotation on the hand bone.+ const pitch = qAxisAngle([-s, 0, 0], off.pitch ?? 0);+ const yaw = qAxisAngle([0, -s, 0], off.yaw ?? 0);+ const roll = qAxisAngle([0, 0, 1], (off.roll ?? 0) * -s);+ return qMul(yaw, qMul(pitch, roll));+}++// ── 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-Z ]+/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. Only A–Z 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)');++ const pose = signingPose();+ const restHand = pose.RightHand;+ 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, wristOff) => {+ const locals = { ...fingers };+ locals.RightHand = wristOff ? qNorm(qMul(restHand, wristOffsetQuat(wristOff))) : 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.+ const bounce = { ...fingers };+ pushKey(t + timing.transitionSeconds * 0.6, bounce, { yaw: -14 });+ 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]) {+ const w = { ...(wristBase ?? {}) };+ for (const k of ['pitch', 'yaw', 'roll']) w[k] = (w[k] ?? 0) + (step.wrist[k] ?? 0);+ pushKey(start + step.at * timing.motionSeconds, fingers, w);+ }+ 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/tests/fingerspelling.test.js b/tests/fingerspelling.test.jsnew file mode 100644index 000000000..6a8f76225--- /dev/null+++ b/tests/fingerspelling.test.js@@ -0,0 +1,153 @@+import { describe, expect, it } from 'vitest';++import {+ DEFAULT_TIMING,+ LETTER_SHAPES,+ buildFingerspellingClip,+ handshapeLocals,+ normalizeWord,+} from '../src/fingerspelling.js';++const FINGER_BONES = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky'].flatMap((f) =>+ [1, 2, 3].map((j) => `RightHand${f}${j}`),+);++function quatAngleDeg(q) {+ return (2 * Math.acos(Math.min(1, Math.abs(q[3])))) * (180 / Math.PI);+}++describe('letter shapes', () => {+ it('defines all 26 letters', () => {+ for (let c = 65; c <= 90; c++) {+ expect(LETTER_SHAPES[String.fromCharCode(c)], String.fromCharCode(c)).toBeTruthy();+ }+ });++ it('produces unit quaternions for every finger bone of every letter', () => {+ for (const letter of Object.keys(LETTER_SHAPES)) {+ const locals = handshapeLocals(letter, 'Right');+ for (const bone of FINGER_BONES) {+ const q = locals[bone];+ expect(q, `${letter}:${bone}`).toBeTruthy();+ expect(Math.hypot(...q)).toBeCloseTo(1, 6);+ }+ }+ });++ it('distinct letters produce distinct handshapes', () => {+ const flat = (letter) =>+ FINGER_BONES.flatMap((b) => handshapeLocals(letter, 'Right')[b])+ .map((v) => v.toFixed(4))+ .join(',');+ const seen = new Map();+ for (const letter of Object.keys(LETTER_SHAPES)) {+ const key = flat(letter);+ // Some letters share a base handshape by design and differ only by+ // wrist orientation or motion, which live in the clip: I/J, K/P,+ // and the G/Q/Z family.+ const clash = seen.get(key);+ if (clash) {+ expect(['I:J', 'G:Q', 'Q:Z', 'K:P'].includes(`${clash}:${letter}`), `${clash} vs ${letter}`).toBe(true);+ }+ seen.set(key, letter);+ }+ });++ it('a fist letter curls the index far more than an open letter', () => {+ const fist = handshapeLocals('S', 'Right');+ const open = handshapeLocals('B', 'Right');+ expect(quatAngleDeg(fist.RightHandIndex2)).toBeGreaterThan(60);+ expect(quatAngleDeg(open.RightHandIndex2)).toBeLessThan(5);+ });++ it('mirrors cleanly to the left hand', () => {+ const right = handshapeLocals('V', 'Right');+ const left = handshapeLocals('V', 'Left');+ expect(quatAngleDeg(left.LeftHandIndex1)).toBeCloseTo(quatAngleDeg(right.RightHandIndex1), 5);+ // Curl hinge is mirrored: z components flip sign.+ expect(left.LeftHandRing2[2]).toBeCloseTo(-right.RightHandRing2[2], 6);+ });++ it('rejects unknown letters', () => {+ expect(() => handshapeLocals('7', 'Right')).toThrow();+ });+});++describe('normalizeWord', () => {+ it('uppercases, strips non-letters, collapses spaces', () => {+ expect(normalizeWord(' héllo, world! ')).toBe('HLLO WORLD');+ expect(normalizeWord('three.ws')).toBe('THREEWS');+ expect(normalizeWord('$$$')).toBe('');+ });+});++describe('buildFingerspellingClip', () => {+ it('emits a library-shaped clip document', () => {+ const clip = buildFingerspellingClip('hi');+ expect(clip.blendMode).toBe(2500);+ expect(clip.uuid).toMatch(/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/);+ expect(clip.duration).toBeGreaterThan(0);+ const names = clip.tracks.map((t) => t.name);+ for (const bone of FINGER_BONES) expect(names).toContain(`${bone}.quaternion`);+ for (const bone of ['RightArm', 'RightForeArm', 'RightHand', 'LeftArm', 'LeftForeArm', 'Hips']) {+ expect(names).toContain(`${bone}.quaternion`);+ }+ expect(names).toContain('Hips.position');+ });++ it('tracks have ascending times, matching lengths, and unit quaternions', () => {+ const clip = buildFingerspellingClip('lazy dog');+ for (const track of clip.tracks) {+ for (let i = 1; i < track.times.length; i++) {+ expect(track.times[i]).toBeGreaterThan(track.times[i - 1]);+ }+ if (track.type !== 'quaternion') continue;+ expect(track.values.length).toBe(track.times.length * 4);+ for (let i = 0; i < track.values.length; i += 4) {+ expect(Math.hypot(...track.values.slice(i, i + 4))).toBeCloseTo(1, 6);+ }+ expect(track.times[track.times.length - 1]).toBeLessThanOrEqual(clip.duration + 1e-9);+ }+ });++ it('is deterministic', () => {+ expect(buildFingerspellingClip('avatar')).toEqual(buildFingerspellingClip('avatar'));+ });++ it('double letters take longer than distinct ones', () => {+ const double = buildFingerspellingClip('aa');+ const single = buildFingerspellingClip('ab');+ expect(double.duration).toBeGreaterThan(single.duration - 1e-9);+ });++ it('traced letters (J, Z) animate the wrist inside the letter window', () => {+ const clip = buildFingerspellingClip('j');+ const hand = clip.tracks.find((t) => t.name === 'RightHand.quaternion');+ const unique = new Set();+ for (let i = 0; i < hand.values.length; i += 4) {+ unique.add(hand.values.slice(i, i + 4).map((v) => v.toFixed(4)).join(','));+ }+ expect(unique.size).toBeGreaterThanOrEqual(3);+ });++ it('static letters hold the wrist steady during the hold', () => {+ const clip = buildFingerspellingClip('b');+ const hand = clip.tracks.find((t) => t.name === 'RightHand.quaternion');+ // lead key + letter-in + letter-hold + tail = 4 keys, middle two equal.+ const k = (i) => hand.values.slice(i * 4, i * 4 + 4).join(',');+ expect(hand.times.length).toBe(4);+ expect(k(1)).toBe(k(2));+ });++ it('duration follows the timing model', () => {+ const t = DEFAULT_TIMING;+ const clip = buildFingerspellingClip('ab');+ const expected = t.leadSeconds + 2 * (t.transitionSeconds + t.holdSeconds) + t.tailSeconds;+ expect(clip.duration).toBeCloseTo(expected, 6);+ });++ it('rejects unspellable input', () => {+ expect(() => buildFingerspellingClip('123')).toThrow();+ expect(() => buildFingerspellingClip('')).toThrow();+ });+});