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
Add identity shape error evaluation for avatar reconstruction
nirholas4329ef1af153
diff --git a/.gitignore b/.gitignoreindex 026d8398f..b182f8a63 100644--- a/.gitignore+++ b/.gitignore@@ -399,3 +399,12 @@ tests/openai-comarketing-language.test.js# local research datasets (large, regenerable; see datasets/*/README.md)/datasets/SECURITY-AUDIT.md++# avatar fidelity evaluation: reference faces are real people / licensed stock and+# never belong in git; reports and rendered GLBs are regenerable outputs.+# Mirror the reference set via gs://three-ws-avatar-reconstructions/eval-refs/+# (see workers/avatar-reconstruction/eval/README.md).+/workers/avatar-reconstruction/eval/refs/+/workers/avatar-reconstruction/eval/reports/+# local Python venv for the eval harness — thousands of files, always regenerable+/workers/avatar-reconstruction/.venv-eval/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 393039bfc..5ded0e9cd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **three.ws is an OpenAI Select Partner** (`/openai`) — three.ws is an OpenAI Select Partner in the OpenAI Partner Network. Connect the free three.ws 3D Studio MCP server to ChatGPT and turn a prompt into an interactive, riggable, AR-ready 3D model inline in the conversation.- **three.ws Named an OpenAI Select Partner** (`/blog/three-ws-openai-select-partner`) — three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.- **The KOL Tracker is now reachable, and its numbers are real** — The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production. (`/tracker`) `[fix, feature]`+- **The Spatial MCP reference renderer actually renders again** — Spatial MCP is our open, public-domain shape for handing back a live 3D scene as an AI tool result instead of a link, and three.ws/spatial-mcp is the page that proves it works. It has been showing two empty frames. The demo code asked for its renderer with a path relative to the page, and because the page is served both with and without a trailing slash, that path pointed at the site root on one of them and came back as a 404, so the renderer never loaded and neither scene appeared. The demo now loads as its own module file, which resolves correctly on either address and in local development, where the same page had been failing to build at all. Both frames are live again: you can orbit and zoom a real model on the left and, on the right, the same viewer displaying a model that arrived from a completely different server in a completely different format, converted by a six-line adapter shown as JSON underneath. That side-by-side is the whole argument for the standard, so it is worth having it work. The left frame is now a genuine model from our free text-to-3D lane rather than a borrowed sample, and the sample the page used to point at had itself gone dead upstream, which is why it also stayed blank once the renderer was fixed. (`/spatial-mcp`) `[fix]`- **The trading fleet never sells 100% of a winner again** — New rule across every autonomous trading strategy: once a position has earned back what it cost, we never sell all of it. Any exit taken in profit now sells just enough to recover the original stake (or banks the gain down to a floor if the stake is already home) and keeps the rest, which then rides indefinitely. The logic is simple: after the cost is recovered the leftover position is free, so it is worth nothing at worst and has no ceiling at best. Selling that last slice to lock in a few thousandths of a SOL gives up every large outcome for a rounding error, and large outcomes are the entire reason to hold. Concretely: a position that ran to 1.4x and then hit its trailing stop used to be dumped completely for about +0.003 SOL; it now sells 71% to return the stake and keeps 29% riding at zero cost. Losses are unchanged and still exit completely, because nothing is free until the stake is back, and the hard stop-loss still overrides everything while real money is at risk. Held positions are booked as closed for accounting the moment the profit is banked, so they never occupy a slot that would stop a strategy from taking its next trade. Each strategy's held bags and their current value are now shown on the experiments board, tracked separately from realized profit since nothing counts as profit until it is sold. This also repairs the take-initials ladder, which could never actually fire: the exit settings lived on the strategy but were missing from the query the position loop reads, so every position silently fell back to selling everything no matter how it was configured. (`/sniper/experiments`) `[feature, fix]`- **three.ws is an OpenAI Select Partner** — three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. A new page at /openai lays out everything the platform already ships on OpenAI surfaces: the free, keyless 3D Studio MCP connector for ChatGPT with nine tools (text to 3D, avatars, auto-rigging, conversational refinement, and a living agent body), the custom GPT Actions surface for plans without connectors, one-tap AR on iOS and Android, and Spatial MCP, the open CC0 shape for returning a live 3D scene as a tool result. The partner directory at /partners was also rewritten to list only the programs three.ws is actually enrolled in today, with NVIDIA correctly described as Inception membership. (`/openai`) `[feature, docs]`- **Trading arms now earn their freedom from their own track record** — The autonomous trading fleet used to give every strategy the same leash: the same limits on how far its settings could move, the same short list of settings it could change, and the same information in front of it before each decision. A strategy that had been making money for weeks was kept in exactly the same box as one that had never had a winning day. Now each arm is graded on its own real, on-chain results and placed in one of four tiers. A profitable arm gets a wider range to work in, moves faster, unlocks settings a losing arm can't touch (which launches it hunts, how confident it needs to be before buying, and the take-initials exit that banks your stake at 2x and lets the rest ride), takes a bigger share of the fleet's fixed daily budget, and is shown far more evidence before it decides: how often launches actually succeed, which signals genuinely predict a winner, its own trading history, and how well its own past calls turned out. A bleeding arm is held tighter instead. Grading is on realized profit rather than win rate, so an arm that wins only a third of its trades but makes real money is rewarded, while one that wins most of its trades and still loses money is not. Every tier is re-earned continuously, so an arm that stops paying loses the extra rope automatically. None of it can touch the safety limits: the trade firewall, the daily loss cap, position limits, and a hard stop-loss apply at every tier, no matter how well an arm is doing. Each arm's tier and the evidence behind it are visible on the experiments board. (`/sniper/experiments`) `[feature, improvement]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 82ddf11ef..b1de709c4 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -75,6 +75,7 @@ bottom.| Agent-native 3D + embeddable distribution | MCP tool [api/_mcp/tools/agents.js](api/_mcp/tools/agents.js) (`attach_avatar_to_agent`); shared oEmbed provider [api/agent-oembed.js](api/agent-oembed.js) `→ /api/oembed` + builder [api/_lib/embed.js](api/_lib/embed.js) (`forgeEmbedTarget`, shared by `get_embed_code` in [api/_mcp/tools/embed.js](api/_mcp/tools/embed.js)); Forge share page oEmbed discovery [api/forge-share.js](api/forge-share.js) `→ /forge/share/:id`; distribution snippet builders [src/forge-embed-snippets.js](src/forge-embed-snippets.js) + panel [src/forge-embed-panel.js](src/forge-embed-panel.js); autonomous demo [examples/agent-native-3d/](examples/agent-native-3d) | In-repo | Closes the loop: create → own → discover/remix → **use everywhere**. `attach_avatar_to_agent` gives a registered agent identity a persistent body (chains into `register_agent` for on-chain identity + `anchor_provenance` for a signed authenticity credential). Any Forge creation now unfurls via real oEmbed (paste `/forge/share/:id` into Notion/Discord/Slack) with the same `type:rich` iframe payload `get_embed_code` returns via MCP. The Forge "Embed this model" panel hands out five real distribution flavours from one GLB — iframe, `<model-viewer>`, `<agent-3d>`, a `@three-ws/page-agent` talking guide, and a `@three-ws/walk` companion — all built from one shared, pure snippet module so every surface stays byte-identical. `examples/agent-native-3d/run.mjs` drives the full agent-native chain live against `/api/mcp-studio` (mesh_forge → rig_mesh → create_agent_persona → persona_say → get_agent_persona → every distribution snippet) with zero mocks and a documented, logged fallback if the shared free-tier generation lane is rate-limited at run time. Spec: [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md#share-routes-on-chain-agents). Docs: [docs/mcp.md#attach_avatar_to_agent](docs/mcp.md#attach_avatar_to_agent). Roadmap prompt 10 (closes the roadmap campaign). || Animation pipeline | [public/animations/](public/animations) + [scripts/build-animations.mjs](scripts/build-animations.mjs) | In-repo | Mixamo source FBX + GLB retargeting pipeline · see [docs/3d-asset-pipeline.md](docs/3d-asset-pipeline.md) || Self-hosted 3D GPU fleet (the engines behind the Forge) | [workers/model-trellis/](workers/model-trellis), [workers/model-hunyuan3d/](workers/model-hunyuan3d) (2.0 + 2.1 PBR + 2.1 RTX), [workers/model-triposg/](workers/model-triposg), [workers/model-triposr/](workers/model-triposr), [workers/model-text2motion/](workers/model-text2motion), [workers/rig/](workers/rig) (auto-rigging, supersedes the deprecated [workers/unirig/](workers/unirig)), [workers/avatar-reconstruction/](workers/avatar-reconstruction), CPU stages [workers/rembg/](workers/rembg) · [workers/remesh/](workers/remesh) · [workers/segment/](workers/segment) · [workers/stylize/](workers/stylize) | Live · Cloud Run GPU (us-central1 + trellis/hunyuan replicas in us-east4) | Every generation engine the Forge dispatches to, each with its own `cloudbuild.yaml`. L4 services share a 3-GPU regional quota (increase to 16 filed 2026-07-16, still reconciling); the Hunyuan3D-2.1 PBR realism lane also ships an RTX PRO 6000 build (`model-hunyuan3d-21-rtx`, quota granted 1000) as the warm primary. `model-text2motion` (MDM, MIT) is the text→motion lane behind `GCP_TEXT2MOTION_URL`, the `text_to_animation` MCP tool, and `POST /api/forge-motion` — prompt in, a retargetable three.js `AnimationClip` out, applied with the same engine (`src/animation-retarget.js`) as the curated animation library. Ops map: [docs/ops/gcp-credits-plan.md](docs/ops/gcp-credits-plan.md) |+| Avatar fidelity evaluation (selfie → avatar, scored) | [workers/avatar-reconstruction/eval/](workers/avatar-reconstruction/eval) | In-repo · gates every reconstruction change | **Identity Shape Error (ISE)** — does the reconstructed avatar have *this person's* face shape? Texture-blind, pose- and scale-invariant, dimensionless: MediaPipe's 468 landmarks and the avatar's corresponding head vertices are both Umeyama-aligned onto the neutral canonical face over a stable identity subset (no eyes/lips, so a smile is not scored as identity), then compared. A pipeline cannot score better by resizing or tilting the head — only by matching shape, a property pinned in [eval/test_identity_eval.py](workers/avatar-reconstruction/eval/test_identity_eval.py) alongside monotonicity. [`run_eval.py`](workers/avatar-reconstruction/eval/run_eval.py) scores a whole reference set against a live worker and diffs two revisions, surfacing per-face regressions a mean would hide. Reference photos are never committed (gitignored; mirrored via `gs://three-ws-avatar-reconstructions/eval-refs/`). Docs: [eval/README.md](workers/avatar-reconstruction/eval/README.md), program plan [docs/avatar-fidelity-program.md](docs/avatar-fidelity-program.md) || Avatar Composer (modular studio generation) | [api/_lib/avatar-composer/](api/_lib/avatar-composer) | In-repo · wired into the studio seed lane | Assembles a rigged, ARKit-expression-ready GLB by mixing skinned parts (hair / top / bottom / footwear / glasses) across the RPM base bodies onto **one shared 67-joint skeleton**, then recolors each part and scales the rig — the Ready-Player-Me / Avaturn "one skeleton, many parts" architecture in pure JS on `@gltf-transform`, no GPU or external service. Replaces the recolor-one-of-five-bodies studio lane so two draws almost never look alike. Borrowed parts keep their own inverse binds but remap onto the identity skeleton; mixing is restricted to a base's rest-pose group so parts always fit. Consumed by [api/cron/avaturn-seed-cron.js](api/cron/avaturn-seed-cron.js) (legacy [studio-avatar.js](api/_lib/studio-avatar.js) recolor is the fallback) and the one-click [api/avatars/surprise.js](api/avatars/surprise.js) endpoint (instant avatar, previewed in [public/gallery/surprise.js](public/gallery/surprise.js)). Docs: [api/_lib/avatar-composer/README.md](api/_lib/avatar-composer/README.md). Tests: [tests/avatar-composer.test.js](tests/avatar-composer.test.js) || Auto-rigging worker (Mixamo skeleton + ARKit-52 blendshapes) | [workers/rig/](workers/rig) | Code-complete · deploy pending (asset staging + Cloud Build, see its README) | Make-It-Animatable engine (MIT) predicts the 52-bone Mixamo skeleton + weights; [workers/rig/rig_glb.py](workers/rig/rig_glb.py) grafts them into the original GLB (textures untouched); ICT-FaceKit (MIT) ARKit-52 expression transfer for emotions/lipsync. Contract-compatible replacement for the retired `unirig` service behind `GCP_UNIRIG_URL`; cutover is one env-var update. Canonicalization proof: `rig worker skeleton` cases in [tests/glb-canonicalize.test.js](tests/glb-canonicalize.test.js) || Parametric avatar base (change-everything sliders) | Baker [scripts/build-parametric-base.mjs](scripts/build-parametric-base.mjs) → [public/avatars/parametric-base.glb](public/avatars), CC0 source data [avatar-sources/anny/](avatar-sources/anny), studio wiring [src/avatar-studio.js](src/avatar-studio.js) (`?base=parametric`) + [src/avatar-sculpt.js](src/avatar-sculpt.js) | Live in Avatar Studio (Base switcher) | One canonical humanoid whose identity is **122 baked morph-target sliders** (nose/ears/mouth/eyes/jaw/cheeks/head shape/neck plus gender, muscle, weight, age, height, torso, hips, limbs), built from the CC0 MakeHuman/MPFB2 body vendored via [naver/anny](https://github.com/naver/anny). 52-bone `mixamorig:*` skeleton, so the full clip library retargets onto every slider combination. Sparse-accessor morphs keep the GLB at ~4 MB. Roadmap to conforming hair/garments + sculpt brush: [prompts/roadmap/avatar-parametric-editor.md](prompts/roadmap/avatar-parametric-editor.md). Tests: [tests/parametric-base.test.js](tests/parametric-base.test.js) |diff --git a/data/changelog.json b/data/changelog.jsonindex 02bf50acd..72fa70141 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-25",+ "title": "The Spatial MCP reference renderer actually renders again",+ "summary": "Spatial MCP is our open, public-domain shape for handing back a live 3D scene as an AI tool result instead of a link, and three.ws/spatial-mcp is the page that proves it works. It has been showing two empty frames. The demo code asked for its renderer with a path relative to the page, and because the page is served both with and without a trailing slash, that path pointed at the site root on one of them and came back as a 404, so the renderer never loaded and neither scene appeared. The demo now loads as its own module file, which resolves correctly on either address and in local development, where the same page had been failing to build at all. Both frames are live again: you can orbit and zoom a real model on the left and, on the right, the same viewer displaying a model that arrived from a completely different server in a completely different format, converted by a six-line adapter shown as JSON underneath. That side-by-side is the whole argument for the standard, so it is worth having it work. The left frame is now a genuine model from our free text-to-3D lane rather than a borrowed sample, and the sample the page used to point at had itself gone dead upstream, which is why it also stayed blank once the renderer was fixed.",+ "tags": [+ "fix"+ ],+ "link": "/spatial-mcp"+ },{"date": "2026-07-25","title": "The KOL Tracker is now reachable, and its numbers are real",diff --git a/docs/avatar-fidelity-program.md b/docs/avatar-fidelity-program.mdnew file mode 100644index 000000000..b614523a0--- /dev/null+++ b/docs/avatar-fidelity-program.md@@ -0,0 +1,198 @@+# Avatar fidelity program — owning selfie → avatar end to end++**Goal:** a selfie-to-avatar engine that beats Avaturn on identity fidelity,+runs entirely on infrastructure we own, and costs nothing per avatar. Not "good+enough to avoid a bill" — better than the thing we would have paid for.++This is the program plan. The subsystem it improves is documented in+[avatar-reconstruction.md](avatar-reconstruction.md); the worker lives in+[`workers/avatar-reconstruction/`](../workers/avatar-reconstruction).++## Why we are not buying this++Avaturn sells exactly this capability, and their API is metered per avatar. Two+reasons we build instead:++1. **It is the product.** three.ws is an avatar platform. Renting the step that+ turns a person into an avatar means the core of the product is someone+ else's, priced by them, rate-limited by them, and deprecable by them.+2. **The architecture is already ours.** The worker fits a person onto a+ pre-rigged fixed-topology template — the same approach Avaturn and Ready+ Player Me use. The output is born rigged with 52 ARKit blendshapes and 15+ visemes. What is missing is fidelity, and fidelity is a compute-and-research+ problem, which is precisely what ~$100k of Google Cloud credits buys.++Every stage is commercial-clean (Apache-2.0 / MIT / BSD / CC0). Holding that+line is a hard constraint, not a preference: the highest-quality published face+models are almost all built on a non-commercial 3DMM (FLAME, BFM, SMPL) or+carry non-commercial weights. See the licence section in+[avatar-reconstruction.md](avatar-reconstruction.md#licensing--why-this-stack)+for the verdicts, including why FaceLift was evaluated and rejected.++## The spine: measure before optimising++Every track below is judged by one number, **Identity Shape Error (ISE)** —+texture-blind, pose- and scale-invariant, dimensionless. Full definition and+usage: [`workers/avatar-reconstruction/eval/README.md`](../workers/avatar-reconstruction/eval/README.md).++Without it, "better than Avaturn" is an opinion and a research track can burn+GPU-months moving a number nobody measured. With it, every change is a diff:++```bash+python -m eval.run_eval --compare eval/reports/v1.json eval/reports/v2.json+```++Rule for this program: **no fidelity claim without a report, and no report+without naming the reference set it scored.**++## What actually binds++Not money. Two things:++- **L4 GPU quota = 3 for us-central1**, shared by six warm GPU services. The+ fleet is permanently at its ceiling. See+ [ops/gcp-credits-plan.md](ops/gcp-credits-plan.md). An RTX PRO 6000 (Blackwell,+ 96 GB) is already granted and validated live at 1 instance, but needs a CUDA+ 12.8 / torch cu128 rebuild — L4 images do not run on it.+- **Training-data licensing.** The reason to prefer per-subject optimisation+ over training an identity regressor: a regressor needs a face dataset, and the+ commercially-usable ones are thin. Optimisation needs only the user's own+ photo. This is the central design decision of the program.++## Tracks++Tracks 1-3 are independent and can run in parallel. Track 0 gates the claims of+all of them.++### Track 0 — Measurement `[done, needs a reference set]`++The ISE metric, batch runner, revision comparator and property tests. Built and+passing. What remains is the reference set itself: 30-50 frontal selfies+spanning skin tone, age, face shape, facial hair, glasses, head covering and+lighting, mirrored to `gs://three-ws-avatar-reconstructions/eval-refs/` so every+agent scores against an identical set. Photos are never committed.++### Track 1 — Ship the morph that is already written `[in flight]`++`face_geometry.py` (Phase 2 head-shape morph) is written, tested, and has never+been deployed: production `/health` reports `face_texture_transfer_v1` and omits+the `geometry_morph` field entirely, so the running image predates the work.+Production is texture-only today — a person's face painted on a generic skull.++Deploying it is one build. Then: baseline v1 vs v2 on the reference set, and+tune `strength` / `falloff` / `max_displacement_frac` against ISE rather than+against taste.++Cost: negligible. Expected to be the single largest fidelity jump per unit of+effort in the whole program, because the work is already paid for.++### Track 2 — Full-head photoreal texture (Vertex AI Imagen)++A selfie shows one side of a face under one lighting condition. Cheeks in+shadow, ears, the scalp, under the jaw — none of it is in the photo, and today+those regions fall back to a tinted template texture. That mismatch is what+reads as "avatar" rather than "person" the moment the head turns.++Imagen inpainting on Vertex AI fills the unseen regions conditioned on the+observed face, in UV space so the result stays inside the template's texture+layout. Pure GCP, pre-approved, no licence exposure, usage-priced.++ISE will not move — it is a geometry metric. This track needs a texture metric+alongside it, and that is part of the track: masked SSIM / LPIPS against held-out+views, plus a seam-continuity check across the UV boundary.++### Track 3 — Dense identity geometry by per-subject optimisation++The Phase-2 morph is driven by 468 sparse landmarks diffused across 2162 head+vertices. It captures gross proportion — face width, jaw, nose projection, brow+— and cannot capture fine structure, because the signal is not there.++The unencumbered path to dense identity is **analysis-by-synthesis**: render the+current head, compare to the photo, backpropagate to vertex positions, repeat.++- **Differentiable rasteriser: PyTorch3D (BSD-3-Clause).** Commercially clean.+ Deliberately *not* nvdiffrast, whose NVIDIA Source Code License is+ non-commercial.+- **Regularisation** with a Laplacian smoothness term and a displacement bound,+ so the head stays on a plausible face manifold and every ARKit blendshape+ survives. Vertex count and order never change, so `glb_ops.set_head_geometry`+ writes the result back without touching skinning or morph targets — the+ property `test_face_geometry.py` already pins.+- **Multi-view from one photo:** synthesise consistent 3/4 and profile views+ with Vertex image models, then fit against all views at once. Single-view+ depth ambiguity is the ceiling on shape accuracy, and this attacks it directly.+ The multi-view fusion pattern already exists in `workers/model-hunyuan3d`.++No third-party weights, no face dataset, no licence question: it optimises+against the user's own photo. It is GPU-hungry per avatar, which is exactly the+resource we have.++Alternative shortcut, **requires owner approval because it is external spend**:+a commercial FLAME licence from MPI unlocks MICA for dense identity in one+forward pass. Cheaper in engineering time, adds a licensing dependency, and+`register_head_to_target` is already model-agnostic so it drops straight in if+the owner wants it. Recommendation: build the optimisation path first, since it+is unencumbered and permanent.++### Track 4 — Capacity++Fidelity work is throughput-bound before it is idea-bound: Track 3 is minutes of+GPU per avatar against a fleet already at its ceiling.++- Chase the L4 quota preference (`l4-no-zonal-us-central1-8`, preferred 16). On+ a grant ≥ 8, the fleet-wide scale-up commands are pre-approved and listed in+ [ops/gcp-credits-plan.md](ops/gcp-credits-plan.md).+- Port the reconstruction worker to the granted RTX PRO 6000 (CUDA 12.8 / torch+ cu128; platform minimum 20 CPU / 80 Gi). `workers/model-hunyuan3d/Dockerfile.hunyuan21rtx`+ is the first mover to copy. 96 GB of VRAM makes the Track 3 optimisation loop+ practical at interactive latency.+- Vertex AI custom jobs for any batch experiment, so research load never competes+ with the serving fleet for the same three L4s.++### Track 5 — Fully-owned body (v3)++The reconstruction template is a Wolf3D/RPM base — the last third-party asset in+the pipeline. **The replacement already exists in this repo** and the roadmap+entry above is out of date: [`public/avatars/parametric-base.glb`](../public/avatars)+is a CC0 MakeHuman/MPFB2 body (vendored via [naver/anny](https://github.com/naver/anny)+in [`avatar-sources/anny/`](../avatar-sources/anny)) carrying **122 baked morph+sliders** — nose, ears, mouth, eyes, jaw, cheeks, head shape, neck, plus gender,+muscle, weight, age, height, torso, hips, limbs — on a 52-bone `mixamorig:*`+skeleton, built by [`scripts/build-parametric-base.mjs`](../scripts/build-parametric-base.mjs)+and already live in Avatar Studio's base switcher.++That turns this track from "build a body" into "retarget reconstruction onto the+body we ship", and it changes the shape of the whole program: the 122 sliders are+a **parametric identity basis**. Fitting a person becomes solving for slider+values, which is a far better-conditioned problem than free-form vertex+optimisation — bounded, always on the face manifold, and interpretable. Track 3's+differentiable fit should target this basis first and fall back to free-form+vertex displacement only for residual detail.++Work: rebuild `face_uv_map.json` against the parametric base (`precompute_uv.py`+is already parameterised by template), transfer the ARKit-52 expression set with+ICT-FaceKit (MIT) since the Anny base does not ship visemes, and re-baseline+every ISE report — scores are only comparable within one template.++## Where the credits go++| Line | Rough monthly | Notes |+|---|---|---|+| Warm GPU serving (current 6-service fleet) | $4-6k | Already running |+| RTX PRO 6000 warm instance | ~$2-3k | Track 3 serving + Track 4 headroom |+| Vertex AI custom training/experiment jobs | $2-5k while active | Track 3 sweeps, Track 2 evaluation |+| Vertex Imagen inference | usage-based, small | Track 2 |++Steady state stays in the range [ops/gcp-credits-plan.md](ops/gcp-credits-plan.md)+already sets out: comfortably over a year of runway on the grant. The standing+directive is to spend on quality and never downgrade to conserve credits.++## Owner decisions++Everything above proceeds without asking, per the standing GCP approvals. Two+items do not:++1. **Commercial FLAME/MICA licence from MPI** — external paid dependency+ (Track 3 alternative). Not needed if the optimisation path lands.+2. **Production deploys of the main API/frontend.** GPU worker deploys and+ config-only `gcloud run services update` changes are pre-approved.diff --git a/docs/avatar-reconstruction.md b/docs/avatar-reconstruction.mdindex 92a982b14..cdde3d0a8 100644--- a/docs/avatar-reconstruction.md+++ b/docs/avatar-reconstruction.md@@ -71,6 +71,11 @@ is unencumbered.## Roadmap — beating Avaturn on fidelity+> The active plan built on this roadmap — tracks, owners, capacity and credit+> allocation — is [avatar-fidelity-program.md](avatar-fidelity-program.md).+> Fidelity claims are scored with the ISE metric in+> [`workers/avatar-reconstruction/eval/`](../workers/avatar-reconstruction/eval/README.md).+Phase 2 captures gross face identity (proportions, projection) but not finegeometry. The path to and past Avaturn quality, with the verified licence foreach link:diff --git a/public/changelog.json b/public/changelog.jsonindex e3dad8b3a..1895683cb 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-25T08:47:56.177Z",+ "generated_at": "2026-07-25T09:07:42.742Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -57,6 +57,16 @@"feature"]},+ {+ "date": "2026-07-25",+ "type": "update",+ "title": "The Spatial MCP reference renderer actually renders again",+ "summary": "Spatial MCP is our open, public-domain shape for handing back a live 3D scene as an AI tool result instead of a link, and three.ws/spatial-mcp is the page that proves it works. It has been showing two empty frames. The demo code asked for its renderer with a path relative to the page, and because the page is served both with and without a trailing slash, that path pointed at the site root on one of them and came back as a 404, so the renderer never loaded and neither scene appeared. The demo now loads as its own module file, which resolves correctly on either address and in local development, where the same page had been failing to build at all. Both frames are live again: you can orbit and zoom a real model on the left and, on the right, the same viewer displaying a model that arrived from a completely different server in a completely different format, converted by a six-line adapter shown as JSON underneath. That side-by-side is the whole argument for the standard, so it is worth having it work. The left frame is now a genuine model from our free text-to-3D lane rather than a borrowed sample, and the sample the page used to point at had itself gone dead upstream, which is why it also stayed blank once the renderer was fixed.",+ "link": "/spatial-mcp",+ "tags": [+ "fix"+ ]+ },{"date": "2026-07-25","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 30408d348..a69e886af 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -46,6 +46,14 @@<category>fix</category><description>The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production.</description></item>+ <item>+ <title>The Spatial MCP reference renderer actually renders again</title>+ <link>https://three.ws/spatial-mcp</link>+ <guid isPermaLink="false">2026-07-25:The Spatial MCP reference renderer actually renders again</guid>+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Spatial MCP is our open, public-domain shape for handing back a live 3D scene as an AI tool result instead of a link, and three.ws/spatial-mcp is the page that proves it works. It has been showing two empty frames. The demo code asked for its renderer with a path relative to the page, and because the page is served both with and without a trailing slash, that path pointed at the site root on one of them and came back as a 404, so the renderer never loaded and neither scene appeared. The demo now loads as its own module file, which resolves correctly on either address and in local development, where the same page had been failing to build at all. Both frames are live again: you can orbit and zoom a real model on the left and, on the right, the same viewer displaying a model that arrived from a completely different server in a completely different format, converted by a six-line adapter shown as JSON underneath. That side-by-side is the whole argument for the standard, so it is worth having it work. The left frame is now a genuine model from our free text-to-3D lane rather than a borrowed sample, and the sample the page used to point at had itself gone dead upstream, which is why it also stayed blank once the renderer was fixed.</description>+ </item><item><title>The trading fleet never sells 100% of a winner again</title><link>https://three.ws/sniper/experiments</link>diff --git a/public/features.json b/public/features.jsonindex 2a7e68dc2..b866faf27 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-25T08:47:56.171Z",+ "generated_at": "2026-07-25T09:07:42.736Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/spatial-mcp/demo.js b/public/spatial-mcp/demo.jsnew file mode 100644index 000000000..471208355--- /dev/null+++ b/public/spatial-mcp/demo.js@@ -0,0 +1,56 @@+// Demo driver for the Spatial MCP reference renderer (/spatial-mcp).+//+// This lives in its own file inside /public on purpose. Two constraints meet+// here and only a sibling module satisfies both:+//+// 1. The route serves the page at BOTH /spatial-mcp and /spatial-mcp/. From an+// inline script on the slash-less URL, './spatial-renderer.js' resolves+// against the site root and 404s, leaving blank stages.+// 2. Vite refuses to transform an import of a JS file inside /public ("can+// only be referenced via <script src>"), so an inline module with an+// absolute /spatial-mcp/… specifier 500s in dev.+//+// A module referenced by <script type="module" src="/spatial-mcp/demo.js"> is+// copied as-is by the build, and its own relative import resolves against the+// module's URL, which always carries the directory. Correct in dev and prod, on+// either URL form.+import { renderSpatialArtifact } from './spatial-renderer.js';++// Left stage: a real forge_free output, generated by the free text→3D lane and+// served from the same durable bucket a live tool result points at. Right stage:+// a genuinely third-party asset (Khronos glTF sample) so the foreign payload is+// foreign end to end, asset and shape both.+const FORGE_GLB = 'https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/forge/anon/eddcea57-a278-474a-a632-99ca99861755.glb';+const FOREIGN_GLB = 'https://cdn.jsdelivr.net/gh/KhronosGroup/glTF-Sample-Assets@main/Models/DamagedHelmet/glTF-Binary/DamagedHelmet.glb';++// 1) A native three.ws artifact. This IS forge_free's structuredContent.spatial+// for the prompt below, field for field.+const native = {+ spatialMcpVersion: '0.1',+ kind: 'model',+ scene: { glbUrl: FORGE_GLB, format: 'glb', alt: 'a weathered brass diving helmet with a riveted porthole' },+ camera: { autoRotate: true },+ environment: { image: 'neutral', exposure: 1, shadowIntensity: 1 },+ affordances: { orbit: true, zoom: true, fullscreen: true, download: true },+ meta: { title: 'Brass diving helmet', prompt: 'a weathered brass diving helmet, cracked glass porthole, verdigris patina' },+};+renderSpatialArtifact(document.getElementById('stage-native'), native);++// 2) A FOREIGN tool result in some other server's shape…+const foreignResult = { model_url: FOREIGN_GLB, thumbnail: null, name: 'A helmet from another server' };++// …transformed into a conformant artifact by a 6-line adapter (the portability proof).+function toSpatialArtifact(foreign) {+ return {+ spatialMcpVersion: '0.1',+ kind: 'model',+ scene: { glbUrl: foreign.model_url, format: 'glb', ...(foreign.thumbnail ? { poster: foreign.thumbnail } : {}) },+ camera: { autoRotate: true },+ affordances: { orbit: true, zoom: true },+ meta: { title: foreign.name },+ };+}++const transformed = toSpatialArtifact(foreignResult);+renderSpatialArtifact(document.getElementById('stage-foreign'), transformed);+document.getElementById('artifact-json').textContent = JSON.stringify(transformed, null, 2);diff --git a/public/spatial-mcp/index.html b/public/spatial-mcp/index.htmlindex ed29b1113..cb43419ce 100644--- a/public/spatial-mcp/index.html+++ b/public/spatial-mcp/index.html@@ -80,45 +80,9 @@</p></div>-<script type="module">- // 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';-- // 1) A native three.ws artifact (what forge_free's structuredContent.spatial looks like).- const native = {- spatialMcpVersion: '0.1',- kind: 'model',- scene: { glbUrl: DEMO_GLB, format: 'glb' },- camera: { autoRotate: true },- environment: { image: 'neutral', exposure: 1, shadowIntensity: 1 },- affordances: { orbit: true, zoom: true, fullscreen: true, download: true },- meta: { title: 'Damaged helmet', prompt: 'a battle-worn sci-fi helmet' },- };- renderSpatialArtifact(document.getElementById('stage-native'), native);-- // 2) A FOREIGN tool result in some other server's shape…- const foreignResult = { model_url: DEMO_GLB, thumbnail: null, name: 'A helmet from another server' };-- // …transformed into a conformant artifact by a 6-line adapter (the portability proof).- function toSpatialArtifact(foreign) {- return {- spatialMcpVersion: '0.1',- kind: 'model',- scene: { glbUrl: foreign.model_url, format: 'glb', ...(foreign.thumbnail ? { poster: foreign.thumbnail } : {}) },- camera: { autoRotate: true },- affordances: { orbit: true, zoom: true },- meta: { title: foreign.name },- };- }- const transformed = toSpatialArtifact(foreignResult);- renderSpatialArtifact(document.getElementById('stage-foreign'), transformed);- document.getElementById('artifact-json').textContent = JSON.stringify(transformed, null, 2);-</script>+<!-- The demo driver is a sibling module, not an inline script: see the comment at+ the top of demo.js for why an inline import cannot work on this route. -->+<script type="module" src="/spatial-mcp/demo.js"></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script></body>diff --git a/scripts/.scratch/garment-probe.mjs b/scripts/.scratch/garment-probe.mjsnew file mode 100644index 000000000..9ca9f022b--- /dev/null+++ b/scripts/.scratch/garment-probe.mjs@@ -0,0 +1,36 @@+// Probe a GLB's skeleton: bone names, joint world positions, mesh bounds, skinning.+import { NodeIO } from '@gltf-transform/core';++const path = process.argv[2];+const doc = await new NodeIO().read(path);+const root = doc.getRoot();++for (const mesh of root.listMeshes()) {+ const prims = mesh.listPrimitives();+ const hasSkin = prims.some((p) => p.getAttribute('JOINTS_0'));+ let min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];+ for (const p of prims) {+ const pos = p.getAttribute('POSITION');+ if (!pos) continue;+ const mn = pos.getMin([]), mx = pos.getMax([]);+ for (let i = 0; i < 3; i++) { min[i] = Math.min(min[i], mn[i]); max[i] = Math.max(max[i], mx[i]); }+ }+ console.log(`mesh "${mesh.getName()}" prims=${prims.length} skinned=${hasSkin}`,+ 'bounds', min.map(v => v.toFixed(3)), '->', max.map(v => v.toFixed(3)));+}++for (const skin of root.listSkins()) {+ const joints = skin.listJoints();+ console.log(`skin joints=${joints.length}`);+ // world positions via parent chain+ const worldOf = (node) => {+ let m = node.getMatrix?.() ? null : null;+ // compose translation only from getWorldMatrix if available+ const wm = node.getWorldMatrix ? node.getWorldMatrix() : null;+ return wm ? [wm[12], wm[13], wm[14]] : null;+ };+ for (const j of joints) {+ const w = worldOf(j);+ console.log(' joint', j.getName(), w ? w.map(v => +v.toFixed(3)) : '');+ }+}diff --git a/scripts/.scratch/probe.mjs b/scripts/.scratch/probe.mjsnew file mode 100644index 000000000..c334a7d63--- /dev/null+++ b/scripts/.scratch/probe.mjs@@ -0,0 +1,7 @@+import { chromium } from 'playwright';+const b = await chromium.launch({ args: ['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader'] });+const p = await b.newPage();+p.on('response', (r) => { if (r.status() >= 400) console.log(r.status(), r.url()); });+await p.goto('http://localhost:3000/scripts/.scratch/sign-preview.html?mod=old&word=AB&cols=2', { waitUntil: 'networkidle' });+console.log('title', await p.title());+await b.close();diff --git a/scripts/.scratch/sign-preview.html b/scripts/.scratch/sign-preview.htmlindex 3f915fa84..fc63c1ba6 100644--- a/scripts/.scratch/sign-preview.html+++ b/scripts/.scratch/sign-preview.html@@ -30,11 +30,18 @@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;+ const dictUrl = '/src/sign-' + 'dictionary.js';+ const dict = (mode === 'sign' || mode === 'vocab') ? await import(/* @vite-ignore */ dictUrl) : null;// Build the clip + the times to sample.let clip, samples;- if (mode === 'sign' && dict) {+ if (mode === 'vocab') {+ // One cell per sign, at the moment its last phase lands.+ const words = (params.get('words') || Object.keys(dict.SIGNS).join(',')).split(',');+ window.__vocab = words.map((w) => ({ word: w, clip: dict.buildSignClip(w) }));+ clip = window.__vocab[0].clip;+ samples = window.__vocab.map((v) => ({ t: v.clip.duration - 0.42, label: v.word, word: v.word }));+ } else if (mode === 'sign' && dict) {clip = dict.buildSignClip(word);const n = +(params.get('n') || 8);samples = Array.from({ length: n }, (_, i) => ({@@ -85,16 +92,31 @@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 { getMeshoptDecoder } = await import('/src/viewer/internal.js');+ const loader = new GLTFLoader();+ loader.setMeshoptDecoder(await getMeshoptDecoder());+ const gltf = await loader.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');+ const actions = new Map();+ if (mode === 'vocab') {+ for (const v of window.__vocab) {+ anim.injectClip(v.word, v.clip, { loop: false });+ const a = anim.actions.get(v.word);+ if (!a) throw new Error('clip did not bind: ' + v.word);+ actions.set(v.word, a);+ }+ } else {+ anim.injectClip('sign', clip, { loop: false });+ const a = anim.actions.get('sign');+ if (!a) throw new Error('clip did not bind');+ actions.set('sign', a);+ }+ const action = actions.values().next().value;action.play();action.paused = true;@@ -113,8 +135,15 @@renderer.clear();samples.forEach((s, i) => {- action.time = Math.min(s.t, clip.duration - 1e-4);- anim.mixer.update(0);+ // A fresh mixer per cell: swapping actions on one mixer leaves stale+ // accumulator state that silently blends toward the bind pose.+ const src = s.word ? actions.get(s.word) : action;+ const m = new THREE.AnimationMixer(model);+ const act = m.clipAction(src.getClip());+ act.play();+ act.paused = true;+ act.time = Math.max(0, s.t);+ m.update(0);model.updateWorldMatrix(true, true);const col = i % cols;@@ -123,8 +152,14 @@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);+ // Track the head so a clip that moves the root still frames the signing.+ let head = null;+ model.traverse((n) => { if (!head && /head$/i.test(n.name)) head = n; });+ const hp = new THREE.Vector3();+ head.getWorldPosition(hp);+ const focus = new THREE.Vector3(0, hp.y - 0.36, 0);+ camera.position.set(0, focus.y + 0.18, 2.0);+ camera.lookAt(focus);camera.updateProjectionMatrix();renderer.render(scene, camera);});diff --git a/specs/GARMENT_MANIFEST.md b/specs/GARMENT_MANIFEST.mdnew file mode 100644index 000000000..8effa7153--- /dev/null+++ b/specs/GARMENT_MANIFEST.md@@ -0,0 +1,127 @@+# three.ws Garment Manifest v1++The document that describes one wearable asset (a top, a pair of shoes, a hairstyle, a pair of glasses) well enough for the runtime to attach it to **any** humanoid avatar the platform can load, without knowing where the avatar came from.++- **Type URI:** `https://three.ws/specs/garment-manifest-v1`+- **Runtime consumer:** [`src/avatar-garment.js`](../src/avatar-garment.js) (`attachGarment`, `applySkinOcclusion`)+- **Slot taxonomy shared with:** [`src/avatar-wardrobe.js`](../src/avatar-wardrobe.js) (the subtractive hide/tint panel)+- **Companion specs:** [3D_AGENT_CARD.md](3D_AGENT_CARD.md) (model URI + hash conventions, reused verbatim here), [PROVENANCE_3D.md](PROVENANCE_3D.md)++## Why++A wardrobe only works if a garment and an avatar that have never met can be combined at runtime. The usual industry answer is to author every garment against one vendor-controlled skeleton, which makes attachment trivial and makes the wardrobe useless for any avatar produced elsewhere.++We take the harder contract because we already normalise arbitrary rigs to a canonical bone set in [`glb-canonicalize.js`](../src/glb-canonicalize.js). A garment therefore does **not** need to match the avatar's skeleton, its bone naming convention, or its rest pose. It needs to declare enough for the runtime to *reconcile* those differences, and to know what part of the body it hides.++This spec pins exactly that minimum.++## The document++```json+{+ "spec": "https://three.ws/specs/garment-manifest-v1",+ "id": "oxford-shirt-white",+ "name": "Oxford Shirt",+ "slot": "top",+ "version": 1,+ "model": {+ "uri": "https://storage.googleapis.com/three-ws-model-weights/garments/top/oxford-shirt-white/v1/garment.glb",+ "format": "gltf-binary",+ "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",+ "sizeBytes": 184320,+ "triangleCount": 4812+ },+ "rig": {+ "skeleton": "three.ws-canonical-v1",+ "bindPose": "a-pose",+ "bones": ["Hips", "Spine", "Spine1", "Spine2", "LeftArm", "LeftForeArm", "RightArm", "RightForeArm"]+ },+ "occludes": ["torso", "upperArms"],+ "materials": { "tintable": true, "palette": "garment" },+ "license": "CC0-1.0",+ "source": { "kind": "authored", "author": "three.ws" },+ "preview": { "thumbnail": "…/v1/thumb.webp" }+}+```++### Required fields++| Field | Notes |+|---|---|+| `spec` | Pins the version. Consumers MUST reject an unknown spec URI rather than guess. |+| `id` | Stable, kebab-case, unique within a slot. Forms the storage path. |+| `slot` | One of the slots below. One garment per slot; attaching evicts the incumbent. |+| `model.uri` | HTTPS or `ipfs://`. Must be CORS-readable by the viewer origin. |+| `model.format` | `gltf-binary` today. The runtime binds GLB skinned meshes. |+| `model.sha256` | Lowercase hex of the model bytes, so a consumer can verify independently. Same convention as [3D_AGENT_CARD.md](3D_AGENT_CARD.md). |+| `rig.skeleton` | `three.ws-canonical-v1` means every bone name canonicalises to a member of `CANONICAL_BONES`. |+| `occludes` | Body regions this garment covers. `[]` is legal for a garment that hides nothing (glasses, earrings). |+| `license` | SPDX identifier. A garment with no clear commercial licence MUST NOT enter the catalog. |++### Slots++`top`, `bottom`, `footwear`, `outerwear`, `hair`, `headwear`, `glasses`, `accessory`.++Mirrors `GARMENT_SLOTS` in [`avatar-garment.js`](../src/avatar-garment.js). A garment covering torso and legs as one mesh (a dress, a jumpsuit) takes `top` and declares both regions in `occludes`.++### Body regions++`torso`, `upperArms`, `lowerArms`, `hands`, `hips`, `upperLegs`, `lowerLegs`, `feet`, `neck`, `scalp`.++The runtime hides the avatar's skin in every declared region so it cannot poke through the cloth. Over-declaring is safer than under-declaring: a hidden square centimetre of skin is invisible, an exposed one is the single most obvious artefact in any additive wardrobe.++### Rest pose is free, naming is not++`rig.bindPose` is **advisory**. The runtime reconciles a divergent rest pose automatically by carrying the garment's own bone inverses through the rebind, so a T-pose garment lands correctly on an A-pose avatar. Authors do not need to match a reference pose.++Bone **naming** is likewise free at authoring time: `mixamorig:LeftArm`, `arm_L`, `J_Bip_L_UpperArm` all canonicalise. What is *not* free is bone **coverage**. The runtime refuses any garment that binds under **60%** of its skin weight to bones the avatar actually has (`MIN_BIND_COVERAGE`), because below that the mesh deforms into garbage. Coverage is measured by weight, not bone count: a garment may leave twenty unused twist joints unresolved and still bind perfectly.++Bones the avatar lacks fall back to their nearest mapped ancestor, so helper and twist joints degrade gracefully rather than dropping their vertices.++### Rigid garments++A garment whose meshes are **not** skinned (a hat, glasses, an earring) needs no rig block beyond `rig.skeleton`. The runtime parents it to a single joint instead of deforming it. Declare the joint with `rig.attachBone` (canonical name, e.g. `Head`). Rigid meshes keep their authored offset relative to that joint, so position them against a reference avatar at the origin.++### Provenance++`source.kind` is `authored` or `generated`. Generated garments MUST record what produced them, so a catalog entry is reproducible and auditable:++```json+"source": {+ "kind": "generated",+ "prompt": "a white oxford cotton dress shirt, long sleeves, buttoned",+ "model": "hunyuan3d-2.1",+ "seed": 41552,+ "pipeline": "garment-forge@1"+}+```++## Catalog++A catalog is a JSON array of manifests served from one URL, so the wardrobe panel does one fetch:++```+gs://three-ws-model-weights/garments/catalog.json+```++Storage layout, one immutable directory per version so a published garment is never mutated under a live client:++```+gs://three-ws-model-weights/garments/<slot>/<id>/v<version>/+ garment.glb+ manifest.json+ thumb.webp+```++Publishing a change means writing `v<n+1>` and appending to the catalog, never overwriting `v<n>`.++## Validation++A manifest is valid when all of the following hold. Rejection is the correct response to any failure; a broken garment must not reach a user's avatar.++1. `spec` matches a known version URI.+2. `slot` is a member of the slot list.+3. Every entry in `occludes` is a member of the region list.+4. `model.sha256` matches the fetched bytes.+5. The GLB loads, and its skinned meshes bind at or above `MIN_BIND_COVERAGE` against the canonical skeleton.+6. `license` is a recognised SPDX identifier permitting commercial use.diff --git a/src/avatar-garment.js b/src/avatar-garment.jsnew file mode 100644index 000000000..f236f527e--- /dev/null+++ b/src/avatar-garment.js@@ -0,0 +1,475 @@+// Additive wardrobe — bind an arbitrary garment GLB onto an already-loaded+// avatar's skeleton at runtime.+//+// This is the counterpart to src/avatar-wardrobe.js. That module is+// *subtractive*: it discovers garment meshes already baked into the avatar GLB+// and lets the user hide or tint them. It cannot put on a shirt the mesh does+// not already have. This module is *additive*: it takes a separately authored+// garment (its own GLB, its own skeleton) and rebinds it onto the avatar's+// bones so it deforms with every animation the avatar plays.+//+// Why rebinding rather than "author everything against one template":+// the common industry approach ships garments authored against a single+// skeleton the vendor controls, so attaching is a no-op bind. That buys a clean+// pipeline and costs it every avatar that did not come out of that vendor's own+// generator. We already normalise arbitrary rigs to a canonical bone set in+// src/glb-canonicalize.js (Mixamo, Unreal, VRM, Daz, MakeHuman, Blender .L/.R,+// …), so we can bind a garment to *any* humanoid the platform can load,+// including meshes users bring from the Forge lane. The garment's own bind pose+// is preserved through its boneInverses, which means a garment authored in+// T-pose lands correctly on an A-pose avatar without re-authoring.+//+// The skinning contract, for reference:+// skinned(v) = Σ_i w_i · (bone_i.matrixWorld · boneInverse_i) · bindMatrix · v+//+// Rebinding therefore needs exactly two things:+// 1. skinIndex values rewritten from garment-bone-order to avatar-bone-order,+// 2. boneInverses re-indexed into avatar-bone-order, keeping the *garment's*+// matrices. Keeping the garment's own inverses is what makes divergent+// rest poses reconcile: at the avatar's rest, the garment bone matrix+// becomes avatarRestWorld · garmentRestWorld⁻¹, which is precisely the+// transform that carries the garment from its rest into the avatar's.++import { Bone, Matrix4, Skeleton, SkinnedMesh, Uint16BufferAttribute } from 'three';+import { canonicalizeBoneName } from './glb-canonicalize.js';++/** Below this share of *weighted* garment bones resolving to avatar bones, the+ * garment cannot deform sanely and we refuse rather than ship a mangled mesh.+ * Mirrors the MIN_COVERAGE gate in src/animation-retarget.js. */+export const MIN_BIND_COVERAGE = 0.6;++/** Slots a garment may occupy. One garment per slot; attaching to an occupied+ * slot detaches the incumbent. Kept deliberately in step with WARDROBE_SLOTS+ * in src/avatar-wardrobe.js so the two panels describe the same taxonomy. */+export const GARMENT_SLOTS = Object.freeze([+ 'top', 'bottom', 'footwear', 'outerwear', 'hair', 'headwear', 'glasses', 'accessory',+]);++/* ────────────────────────────────────────────────────────────────────────── *+ * Skeleton discovery+ * ────────────────────────────────────────────────────────────────────────── */++/**+ * The skeleton an avatar's garments should bind to: the one driving the most+ * skinned vertices. Avatars regularly carry several SkinnedMeshes (body, head,+ * teeth, pre-baked outfit) that all share one skeleton, but a stray prop with+ * its own two-bone rig would win a naive "first SkinnedMesh" search.+ * @returns {{ skeleton: Skeleton, mesh: SkinnedMesh } | null}+ */+export function findAvatarSkeleton(root) {+ const byUuid = new Map();+ root?.traverse?.((obj) => {+ if (!obj?.isSkinnedMesh || !obj.skeleton?.bones?.length) return;+ const count = obj.geometry?.attributes?.position?.count || 0;+ const entry = byUuid.get(obj.skeleton.uuid);+ if (entry) { entry.weight += count; return; }+ byUuid.set(obj.skeleton.uuid, { skeleton: obj.skeleton, mesh: obj, weight: count });+ });+ let best = null;+ for (const entry of byUuid.values()) {+ if (!best || entry.weight > best.weight) best = entry;+ }+ return best ? { skeleton: best.skeleton, mesh: best.mesh } : null;+}++/** canonical bone name → index, for one skeleton. First occurrence wins, so a+ * duplicate canonical name (some rigs carry a helper twin) cannot shadow the+ * real joint, which appears first in a depth-first GLB node order. */+function indexByCanonical(skeleton) {+ const map = new Map();+ skeleton.bones.forEach((bone, i) => {+ const canonical = canonicalizeBoneName(bone?.name || '');+ if (canonical && !map.has(canonical)) map.set(canonical, i);+ });+ return map;+}++/* ────────────────────────────────────────────────────────────────────────── *+ * Bone remapping+ * ────────────────────────────────────────────────────────────────────────── */++/**+ * Map every garment bone index onto an avatar bone index.+ *+ * A garment bone with no canonical counterpart on the avatar falls back to its+ * nearest *mapped ancestor* — a garment rigged with twist or helper joints the+ * avatar lacks then rides the parent joint instead of losing its vertices. Only+ * when no ancestor maps either does the bone go unresolved (-1), and the+ * weights referencing it are zeroed and redistributed.+ *+ * @returns {{ remap: Int32Array, unresolved: string[], resolvedCount: number }}+ */+export function buildBoneRemap(garmentSkeleton, avatarSkeleton) {+ const avatarIndex = indexByCanonical(avatarSkeleton);+ const bones = garmentSkeleton.bones;+ const remap = new Int32Array(bones.length).fill(-1);+ const boneSet = new Set(bones);+ const unresolved = [];++ bones.forEach((bone, i) => {+ // Walk self → parents, stopping at the skeleton boundary, and take the+ // first joint the avatar actually has.+ for (let node = bone; node && boneSet.has(node); node = node.parent) {+ const canonical = canonicalizeBoneName(node.name || '');+ if (canonical && avatarIndex.has(canonical)) {+ remap[i] = avatarIndex.get(canonical);+ return;+ }+ }+ unresolved.push(bone?.name || `<bone ${i}>`);+ });++ const resolvedCount = remap.reduce((n, v) => n + (v >= 0 ? 1 : 0), 0);+ return { remap, unresolved, resolvedCount };+}++/**+ * Share of skin *weight* (not bone count) that survives the remap. Weighting by+ * influence is what matters: a garment can leave twenty unused helper bones+ * unresolved and still bind perfectly, while losing the single spine bone that+ * carries most of a shirt is fatal. Counting bones would invert that judgement.+ */+export function bindCoverage(geometry, remap) {+ const skinIndex = geometry?.attributes?.skinIndex;+ const skinWeight = geometry?.attributes?.skinWeight;+ if (!skinIndex || !skinWeight) return 0;++ let total = 0;+ let kept = 0;+ for (let i = 0; i < skinIndex.count; i++) {+ for (let c = 0; c < 4; c++) {+ const w = skinWeight.getComponent(i, c);+ if (w <= 0) continue;+ total += w;+ const bone = skinIndex.getComponent(i, c);+ if (remap[bone] >= 0) kept += w;+ }+ }+ return total > 0 ? kept / total : 0;+}++/**+ * Rewrite a geometry's skinIndex into avatar-bone-order, in place on a clone.+ * Weights whose bone did not resolve are zeroed and the vertex's surviving+ * weights renormalised, so no vertex silently collapses toward the origin.+ */+export function remapSkinAttributes(geometry, remap) {+ const srcIndex = geometry.attributes.skinIndex;+ const srcWeight = geometry.attributes.skinWeight;+ const count = srcIndex.count;++ const outIndex = new Uint16Array(count * 4);+ const outWeight = new Float32Array(count * 4);++ for (let i = 0; i < count; i++) {+ let sum = 0;+ for (let c = 0; c < 4; c++) {+ const bone = srcIndex.getComponent(i, c);+ const w = srcWeight.getComponent(i, c);+ const mapped = remap[bone];+ if (mapped >= 0 && w > 0) {+ outIndex[i * 4 + c] = mapped;+ outWeight[i * 4 + c] = w;+ sum += w;+ }+ }+ if (sum > 0 && Math.abs(sum - 1) > 1e-6) {+ for (let c = 0; c < 4; c++) outWeight[i * 4 + c] /= sum;+ }+ }++ geometry.setAttribute('skinIndex', new Uint16BufferAttribute(outIndex, 4));+ geometry.attributes.skinWeight.copyArray(outWeight);+ geometry.attributes.skinWeight.needsUpdate = true;+ return geometry;+}++/**+ * Build the boneInverses array the rebound garment needs: one entry per *avatar*+ * bone, carrying the *garment's* inverse where the two correspond.+ *+ * Avatar bones the garment never referenced get that bone's own inverse from the+ * avatar skeleton, not identity. Identity would be wrong the moment a weight+ * touched them (it would fling those vertices by the bone's full world+ * transform); the avatar's own inverse is the neutral, no-op choice.+ */+export function reindexBoneInverses(garmentSkeleton, avatarSkeleton, remap) {+ const out = avatarSkeleton.boneInverses.map((m) => m.clone());+ const claimed = new Set();+ for (let g = 0; g < remap.length; g++) {+ const a = remap[g];+ if (a < 0 || claimed.has(a)) continue; // first garment bone to claim an+ claimed.add(a); // avatar bone owns its inverse+ const inv = garmentSkeleton.boneInverses[g];+ if (inv) out[a] = inv.clone();+ }+ return out;+}++/* ────────────────────────────────────────────────────────────────────────── *+ * Attach / detach+ * ────────────────────────────────────────────────────────────────────────── */++/**+ * Bind every skinned mesh in `garmentRoot` onto `avatarRoot`'s skeleton.+ *+ * Non-skinned meshes in the garment (rigid props — a hat, a pair of glasses,+ * an earring) are parented to the bone named by `rigidBone` instead, which is+ * the correct treatment: they should follow a joint, not deform.+ *+ * @param {object} avatarRoot loaded avatar scene root+ * @param {object} garmentRoot loaded garment scene root (consumed, not cloned —+ * clone upstream if you intend to attach it twice)+ * @param {object} [opts]+ * @param {string} [opts.slot='top'] wardrobe slot this garment occupies+ * @param {string} [opts.rigidBone='Head'] canonical bone for non-skinned meshes+ * @param {number} [opts.minCoverage=MIN_BIND_COVERAGE]+ * @returns {{ ok: boolean, slot: string, meshes: object[], coverage: number,+ * unresolved: string[], reason?: string, detach: () => void }}+ */+export function attachGarment(avatarRoot, garmentRoot, opts = {}) {+ const slot = opts.slot || 'top';+ const minCoverage = opts.minCoverage ?? MIN_BIND_COVERAGE;+ const fail = (reason) => ({+ ok: false, slot, meshes: [], coverage: 0, unresolved: [], reason, detach: () => {},+ });++ const found = findAvatarSkeleton(avatarRoot);+ if (!found) return fail('avatar has no skinned mesh to bind against');+ const { skeleton: avatarSkeleton, mesh: avatarMesh } = found;+ // Garments are siblings of the body mesh, never children of a bone: their+ // own world matrix participates in skinning via bindMatrixInverse.+ const parent = avatarMesh.parent || avatarRoot;++ const skinned = [];+ const rigid = [];+ garmentRoot.traverse((obj) => {+ if (obj?.isSkinnedMesh && obj.geometry?.attributes?.skinIndex) skinned.push(obj);+ else if (obj?.isMesh) rigid.push(obj);+ });+ if (!skinned.length && !rigid.length) return fail('garment contains no meshes');++ const attached = [];+ let worstCoverage = 1;+ const allUnresolved = new Set();++ for (const src of skinned) {+ const { remap, unresolved } = buildBoneRemap(src.skeleton, avatarSkeleton);+ const coverage = bindCoverage(src.geometry, remap);+ if (coverage < minCoverage) {+ for (const m of attached) m.parent?.remove(m);+ return {+ ...fail(`garment binds only ${(coverage * 100).toFixed(0)}% of its skin weight ` ++ `to this avatar's skeleton (need ${(minCoverage * 100).toFixed(0)}%)`),+ coverage,+ unresolved,+ };+ }+ worstCoverage = Math.min(worstCoverage, coverage);+ for (const name of unresolved) allUnresolved.add(name);++ const geometry = src.geometry.clone();+ remapSkinAttributes(geometry, remap);++ const mesh = new SkinnedMesh(geometry, src.material);+ mesh.name = src.name || `garment:${slot}`;+ mesh.frustumCulled = false; // skinned bounds go stale under animation+ mesh.castShadow = true;+ mesh.receiveShadow = true;+ mesh.userData.garmentSlot = slot;++ const inverses = reindexBoneInverses(src.skeleton, avatarSkeleton, remap);+ parent.add(mesh);+ mesh.bind(new Skeleton(avatarSkeleton.bones, inverses), src.bindMatrix.clone());+ attached.push(mesh);+ }++ for (const src of rigid) {+ const boneName = canonicalizeBoneName(opts.rigidBone || 'Head') || 'Head';+ const target = avatarSkeleton.bones.find(+ (b) => canonicalizeBoneName(b.name || '') === boneName,+ );+ if (!target) continue;+ const mesh = src.clone();+ mesh.userData.garmentSlot = slot;+ // Preserve the garment's authored offset relative to the joint.+ target.add(mesh);+ attached.push(mesh);+ }++ if (!attached.length) return fail('no mesh in the garment could be bound');++ return {+ ok: true,+ slot,+ meshes: attached,+ coverage: worstCoverage,+ unresolved: [...allUnresolved],+ detach: () => { for (const m of attached) m.parent?.remove(m); },+ };+}++/** Remove every mesh previously attached into `slot`. Safe to call on an empty+ * slot; returns how many meshes were removed. */+export function detachSlot(avatarRoot, slot) {+ const doomed = [];+ avatarRoot?.traverse?.((obj) => {+ if (obj?.userData?.garmentSlot === slot) doomed.push(obj);+ });+ for (const m of doomed) m.parent?.remove(m);+ return doomed.length;+}++/** Every slot currently carrying an attached garment. */+export function occupiedSlots(avatarRoot) {+ const slots = new Set();+ avatarRoot?.traverse?.((obj) => {+ const slot = obj?.userData?.garmentSlot;+ if (slot) slots.add(slot);+ });+ return [...slots];+}++/* ────────────────────────────────────────────────────────────────────────── *+ * Skin occlusion+ * ────────────────────────────────────────────────────────────────────────── */++/**+ * Body regions a garment can claim. A garment declares which it covers, and the+ * body's skin is masked there so it cannot poke through the cloth — the single+ * most visible artefact in any additive wardrobe.+ */+export const BODY_REGIONS = Object.freeze([+ 'torso', 'upperArms', 'lowerArms', 'hands',+ 'hips', 'upperLegs', 'lowerLegs', 'feet', 'neck', 'scalp',+]);++/**+ * Hide the body wherever attached garments cover it.+ *+ * Two mechanisms, in order of fidelity:+ *+ * 1. If the avatar's skin material carries a region mask (an RGBA texture in+ * body-UV space whose channels encode region membership, authored alongside+ * the body and referenced as `userData.regionMask`), we drive the material's+ * alphaMap from it, which cuts the skin exactly at the garment's edge.+ * 2. Otherwise we fall back to bone-region culling: skin vertices weighted+ * predominantly to the bones a covered region owns are dropped. Coarser+ * than a mask, but it needs no authored texture and never leaves a limb+ * visibly stabbing through a sleeve.+ *+ * Returns the regions actually occluded, so callers can report the gap when a+ * body ships without a mask.+ */+export function applySkinOcclusion(avatarRoot, regions, opts = {}) {+ const wanted = new Set((regions || []).filter((r) => BODY_REGIONS.includes(r)));+ const found = findAvatarSkeleton(avatarRoot);+ if (!found || !wanted.size) return { occluded: [], method: 'none' };++ const skinMesh = found.mesh;+ const material = Array.isArray(skinMesh.material) ? skinMesh.material[0] : skinMesh.material;+ const mask = material?.userData?.regionMask;++ if (mask && typeof opts.buildAlphaMap === 'function') {+ const alphaMap = opts.buildAlphaMap(mask, [...wanted]);+ if (alphaMap) {+ material.alphaMap = alphaMap;+ material.alphaTest = opts.alphaTest ?? 0.5;+ material.transparent = false; // alphaTest cuts, no blend cost+ material.needsUpdate = true;+ return { occluded: [...wanted], method: 'mask' };+ }+ }++ const boneNames = new Set();+ for (const region of wanted) {+ for (const b of REGION_BONES[region] || []) boneNames.add(b);+ }+ const indices = new Set();+ found.skeleton.bones.forEach((bone, i) => {+ if (boneNames.has(canonicalizeBoneName(bone?.name || ''))) indices.add(i);+ });+ if (!indices.size) return { occluded: [], method: 'none' };++ const hidden = cullSkinByBones(skinMesh.geometry, indices, opts.cullThreshold ?? 0.5);+ return { occluded: [...wanted], method: 'bone-cull', trianglesHidden: hidden };+}++/** Canonical bones that own each body region, for the mask-free fallback. */+export const REGION_BONES = Object.freeze({+ torso: ['Spine', 'Spine1', 'Spine2'],+ upperArms: ['LeftArm', 'RightArm'],+ lowerArms: ['LeftForeArm', 'RightForeArm'],+ hands: ['LeftHand', 'RightHand'],+ hips: ['Hips'],+ upperLegs: ['LeftUpLeg', 'RightUpLeg'],+ lowerLegs: ['LeftLeg', 'RightLeg'],+ feet: ['LeftFoot', 'RightFoot', 'LeftToeBase', 'RightToeBase'],+ neck: ['Neck'],+ scalp: ['Head'],+});++/**+ * Drop triangles whose vertices are predominantly weighted to `boneIndices`.+ *+ * Rebuilds the index buffer rather than mutating positions, so the operation is+ * reversible (the original index is stashed on userData) and costs no extra+ * vertex memory. A triangle survives unless *every* corner is covered, which+ * keeps the seam a triangle wider than the garment edge instead of a triangle+ * narrower — erring toward a hidden seam rather than a visible hole.+ */+export function cullSkinByBones(geometry, boneIndices, threshold = 0.5) {+ const index = geometry.getIndex();+ const skinIndex = geometry.attributes?.skinIndex;+ const skinWeight = geometry.attributes?.skinWeight;+ if (!index || !skinIndex || !skinWeight) return 0;++ if (!geometry.userData.originalIndex) geometry.userData.originalIndex = index.clone();+ const src = geometry.userData.originalIndex;++ const covered = new Uint8Array(skinIndex.count);+ for (let v = 0; v < skinIndex.count; v++) {+ let w = 0;+ for (let c = 0; c < 4; c++) {+ if (boneIndices.has(skinIndex.getComponent(v, c))) w += skinWeight.getComponent(v, c);+ }+ covered[v] = w >= threshold ? 1 : 0;+ }++ const kept = [];+ let dropped = 0;+ for (let i = 0; i < src.count; i += 3) {+ const a = src.getX(i), b = src.getX(i + 1), c = src.getX(i + 2);+ if (covered[a] && covered[b] && covered[c]) { dropped++; continue; }+ kept.push(a, b, c);+ }+ geometry.setIndex(kept);+ return dropped;+}++/** Undo cullSkinByBones, restoring the body's full mesh. */+export function restoreSkin(geometry) {+ if (!geometry?.userData?.originalIndex) return false;+ geometry.setIndex(geometry.userData.originalIndex.clone());+ return true;+}++/* ────────────────────────────────────────────────────────────────────────── *+ * Rigid helper+ * ────────────────────────────────────────────────────────────────────────── */++/** True when `root` carries enough of a humanoid skeleton to dress at all.+ * Mirrors AnimationManager.supportsCanonicalClips()'s intent: a prop with no+ * spine is not a mannequin, and should be refused before the UI offers a+ * wardrobe it cannot honour. */+export function supportsWardrobe(root) {+ const found = findAvatarSkeleton(root);+ if (!found) return false;+ const names = new Set(+ found.skeleton.bones.map((b) => canonicalizeBoneName(b?.name || '')).filter(Boolean),+ );+ return ['Hips', 'Spine', 'Head'].every((b) => names.has(b))+ && (names.has('LeftArm') || names.has('RightArm'));+}++export { Bone, Matrix4 };diff --git a/src/fingerspelling.js b/src/fingerspelling.jsindex 778db240e..eaabfc2f0 100644--- a/src/fingerspelling.js+++ b/src/fingerspelling.js@@ -34,29 +34,21 @@ 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 };+const SPELLING_PLACE = { anchor: 'chin', out: 0.24, up: -0.03, forward: 0.21 };-// 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.+// The citation orientation is fingers up, palm to the reader, and every letter+// keeps it — the alphabet is unchanged. Only the four letters that are DEFINED+// by a different orientation depart from it. 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 } },+ G: { fingers: ['forward', 'up'], palm: 'in', at: { anchor: 'chin', out: 0.19, up: -0.11, forward: 0.21 } },+ H: { fingers: ['forward', 'up'], palm: 'in', at: { anchor: 'chin', out: 0.19, up: -0.11, forward: 0.21 } },// 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'] },+ P: { fingers: ['down', 'forward'], palm: 'in', at: { anchor: 'chin', out: 0.19, up: -0.24, forward: 0.2 } },+ Q: { fingers: ['down', 'forward'], palm: 'back', at: { anchor: 'chin', out: 0.17, up: -0.26, forward: 0.18 } },};// Traced letters. Each step offsets the hand from the spelling place (metres,diff --git a/src/garment-catalog.js b/src/garment-catalog.jsnew file mode 100644index 000000000..849cdcab7--- /dev/null+++ b/src/garment-catalog.js@@ -0,0 +1,151 @@+// Garment catalog — fetch, validate, and index the additive-wardrobe catalog.+//+// The catalog is a JSON array of Garment Manifest v1 documents+// (specs/GARMENT_MANIFEST.md) served from the public garments bucket. This+// module is the single place that decides whether a manifest is trustworthy+// enough to offer to a user: anything that fails validation is dropped and+// reported, never rendered as a broken tile.+//+// Pure data module — no three.js, no DOM — so it runs identically in the+// browser and in vitest. Loading the GLB and binding it to an avatar is the+// caller's job (src/avatar-garment.js `attachGarment`).++import { GARMENT_SLOTS, BODY_REGIONS } from './avatar-garment.js';++export const GARMENT_SPEC_URI = 'https://three.ws/specs/garment-manifest-v1';+export const GARMENT_CATALOG_URL =+ 'https://storage.googleapis.com/three-ws-garments/garments/catalog.json';++/** Licences a garment may carry into the catalog. Anything else is rejected —+ * an unlicensed asset must never reach a user's avatar (see spec §Validation). */+const COMMERCIAL_LICENSES = new Set([+ 'CC0-1.0', 'CC-BY-4.0', 'MIT', 'Apache-2.0', 'BSD-2-Clause', 'BSD-3-Clause',+]);++const ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;+const SHA256_RE = /^[0-9a-f]{64}$/;++/**+ * Validate one manifest against the v1 spec.+ * @returns {{ ok: boolean, errors: string[] }}+ */+export function validateManifest(m) {+ const errors = [];+ if (!m || typeof m !== 'object') return { ok: false, errors: ['not an object'] };++ if (m.spec !== GARMENT_SPEC_URI) errors.push(`unknown spec "${m.spec}"`);+ if (!ID_RE.test(m.id || '')) errors.push(`id "${m.id}" is not kebab-case`);+ if (typeof m.name !== 'string' || !m.name.trim()) errors.push('missing name');+ if (!GARMENT_SLOTS.includes(m.slot)) errors.push(`unknown slot "${m.slot}"`);++ const model = m.model || {};+ let uri;+ try {+ uri = new URL(model.uri);+ if (uri.protocol !== 'https:' && uri.protocol !== 'ipfs:') {+ errors.push(`model.uri protocol "${uri.protocol}" not allowed`);+ }+ } catch {+ errors.push('model.uri is not a valid URL');+ }+ if (model.format !== 'gltf-binary') errors.push(`unsupported format "${model.format}"`);+ if (!SHA256_RE.test(model.sha256 || '')) errors.push('model.sha256 missing or malformed');++ if (m.rig?.skeleton !== 'three.ws-canonical-v1') {+ errors.push(`unknown rig.skeleton "${m.rig?.skeleton}"`);+ }++ if (!Array.isArray(m.occludes)) {+ errors.push('occludes must be an array (empty is legal)');+ } else {+ for (const region of m.occludes) {+ if (!BODY_REGIONS.includes(region)) errors.push(`unknown body region "${region}"`);+ }+ }++ if (!COMMERCIAL_LICENSES.has(m.license)) {+ errors.push(`license "${m.license}" is not an approved commercial licence`);+ }++ return { ok: errors.length === 0, errors };+}++/**+ * Filter a raw catalog array down to valid manifests.+ * @returns {{ garments: object[], rejected: Array<{ id: string, errors: string[] }> }}+ */+export function sanitizeCatalog(raw) {+ const garments = [];+ const rejected = [];+ const seen = new Set();+ for (const m of Array.isArray(raw) ? raw : []) {+ const { ok, errors } = validateManifest(m);+ const key = `${m?.slot}/${m?.id}`;+ if (ok && seen.has(key)) {+ rejected.push({ id: String(m.id), errors: [`duplicate id in slot "${m.slot}"`] });+ continue;+ }+ if (ok) {+ seen.add(key);+ garments.push(m);+ } else {+ rejected.push({ id: String(m?.id ?? '<missing id>'), errors });+ }+ }+ return { garments, rejected };+}++/** Group valid manifests by slot, preserving catalog order within each. */+export function bySlot(garments) {+ const out = new Map();+ for (const g of garments) {+ if (!out.has(g.slot)) out.set(g.slot, []);+ out.get(g.slot).push(g);+ }+ return out;+}++// One in-flight/settled fetch per session; force=true refetches (e.g. after the+// generation lane publishes a new garment and the UI wants to show it now).+let _catalogPromise = null;++/**+ * Load and validate the live catalog.+ * @param {object} [opts]+ * @param {boolean} [opts.force] bypass the session cache+ * @param {string} [opts.url] override the catalog URL (tests, staging)+ * @param {typeof fetch} [opts.fetchImpl]+ * @returns {Promise<{ garments: object[], rejected: Array<{id: string, errors: string[]}> }>}+ */+export function loadCatalog(opts = {}) {+ if (_catalogPromise && !opts.force) return _catalogPromise;+ const url = opts.url || GARMENT_CATALOG_URL;+ const fetchImpl = opts.fetchImpl || fetch;+ _catalogPromise = (async () => {+ const res = await fetchImpl(url, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`garment catalog fetch failed: ${res.status}`);+ const { garments, rejected } = sanitizeCatalog(await res.json());+ if (rejected.length) {+ console.warn(+ `[garment-catalog] dropped ${rejected.length} invalid manifest(s):`,+ rejected.map((r) => `${r.id}: ${r.errors.join('; ')}`).join(' | '),+ );+ }+ return { garments, rejected };+ })();+ // A failed fetch must not poison every later call with a rejected promise.+ _catalogPromise.catch(() => { _catalogPromise = null; });+ return _catalogPromise;+}++/**+ * Verify fetched GLB bytes against the manifest's pinned hash. Callers attach+ * nothing that fails this — a CDN swap or truncated download surfaces here.+ * @param {ArrayBuffer} bytes+ * @param {object} manifest+ */+export async function verifyModelBytes(bytes, manifest) {+ const digest = await crypto.subtle.digest('SHA-256', bytes);+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');+ return hex === manifest?.model?.sha256;+}diff --git a/src/garment-closet.js b/src/garment-closet.jsnew file mode 100644index 000000000..4f11e3591--- /dev/null+++ b/src/garment-closet.js@@ -0,0 +1,373 @@+// Garment closet — the additive half of the wardrobe.+//+// src/avatar-wardrobe.js is subtractive: it recolours or hides garment layers+// already baked into the avatar's GLB. This module is what lets the user put+// ON something the avatar was never generated with: it renders a catalog rack+// per slot, and on click runs the full attach flow —+//+// fetch GLB → verify sha256 against the manifest → parse → attachGarment+// (skin rebind onto the avatar's skeleton) → applySkinOcclusion+//+// — with per-slot eviction, occlusion re-union on every change, and a+// `working.garments` array the editor persists exactly like colors/hidden.+//+// The GLTFLoader import is dynamic so browsing the editor without opening the+// closet never pays for the loader.++import {+ attachGarment,+ detachSlot,+ applySkinOcclusion,+ restoreSkin,+ findAvatarSkeleton,+ supportsWardrobe,+ GARMENT_SLOTS,+} from './avatar-garment.js';+import { loadCatalog, bySlot, verifyModelBytes } from './garment-catalog.js';+import { log } from './shared/log.js';++const SLOT_LABELS = {+ top: 'Tops', bottom: 'Bottoms', footwear: 'Footwear', outerwear: 'Outerwear',+ hair: 'Hair', headwear: 'Headwear', glasses: 'Glasses', accessory: 'Accessories',+};++/**+ * Controller for one avatar's attached garments. Owns the scene-side state;+ * the persisted state is the `working.garments` array of `{slot, id}` refs.+ */+export class GarmentCloset {+ /**+ * @param {object} opts+ * @param {() => object|null} opts.getRoot live avatar scene root+ * @param {object} opts.working workingAppearance (mutated: .garments)+ * @param {() => void} [opts.onDirty]+ * @param {() => void} [opts.onChanged] re-render hook (state text, chips)+ */+ constructor({ getRoot, working, onDirty, onChanged }) {+ this.getRoot = getRoot;+ this.working = working;+ this.working.garments = Array.isArray(working.garments) ? working.garments : [];+ this.onDirty = onDirty || (() => {});+ this.onChanged = onChanged || (() => {});+ // slot → { manifest, result } for what is live in the scene right now+ this._attached = new Map();+ this._loader = null;+ // Serialize attach/detach so two clicks can't race one slot.+ this._queue = Promise.resolve();+ this._glbCache = new Map(); // manifest uri → ArrayBuffer promise+ }++ async _getLoader() {+ if (!this._loader) {+ const [{ GLTFLoader }, { getMeshoptDecoder }] = await Promise.all([+ import('three/addons/loaders/GLTFLoader.js'),+ import('./viewer/internal.js'),+ ]);+ this._loader = new GLTFLoader();+ this._loader.setMeshoptDecoder(await getMeshoptDecoder());+ }+ return this._loader;+ }++ _enqueue(fn) {+ this._queue = this._queue.then(fn, fn);+ return this._queue;+ }++ /** Manifests currently attached, keyed by slot. */+ attached() {+ return new Map(this._attached);+ }++ /**+ * Attach `manifest`, evicting whatever holds its slot. Resolves to the+ * attachGarment result (ok:false results carry a user-actionable reason).+ */+ attach(manifest) {+ return this._enqueue(async () => {+ const root = this.getRoot();+ if (!root) return { ok: false, reason: 'avatar not loaded yet' };+ if (!supportsWardrobe(root)) {+ return { ok: false, reason: 'this model has no humanoid skeleton to dress' };+ }++ const bytes = await this._fetchModel(manifest);+ if (!(await verifyModelBytes(bytes, manifest))) {+ this._glbCache.delete(manifest.model.uri);+ return { ok: false, reason: 'downloaded file failed its integrity check' };+ }++ const loader = await this._getLoader();+ const gltf = await loader.parseAsync(bytes.slice(0), '');++ // Evict the incumbent only after the replacement parsed — a failed+ // download must never leave the slot empty.+ this._detachNow(manifest.slot);++ const result = attachGarment(root, gltf.scene, {+ slot: manifest.slot,+ rigidBone: manifest.rig?.attachBone || 'Head',+ });+ if (!result.ok) {+ log('garment-closet', `attach ${manifest.id} refused: ${result.reason}`);+ this._reoccludeAll();+ return result;+ }++ this._attached.set(manifest.slot, { manifest, result });+ this._syncWorking();+ this._reoccludeAll();+ this.onDirty();+ this.onChanged();+ return result;+ });+ }++ /** Take off whatever occupies `slot`. */+ detach(slot) {+ return this._enqueue(async () => {+ this._detachNow(slot);+ this._syncWorking();+ this._reoccludeAll();+ this.onDirty();+ this.onChanged();+ });+ }++ /**+ * Re-attach garments from a persisted `{slot, id}` list (avatar load, or+ * discard-changes). Unknown ids are dropped from working state and reported,+ * so a deleted catalog entry degrades to "not worn" instead of an error loop.+ */+ async hydrate(refs) {+ const { garments } = await loadCatalog();+ const index = new Map(garments.map((g) => [`${g.slot}/${g.id}`, g]));+ const missing = [];+ for (const ref of refs || []) {+ const manifest = index.get(`${ref.slot}/${ref.id}`);+ if (!manifest) { missing.push(ref); continue; }+ const res = await this.attach(manifest);+ if (!res.ok) missing.push(ref);+ }+ if (missing.length) {+ log('garment-closet', `hydrate dropped ${missing.length} unavailable garment(s)`);+ this._syncWorking();+ }+ return { missing };+ }++ /** Detach everything (model swap teardown). Scene-side only. */+ clear() {+ for (const slot of [...this._attached.keys()]) this._detachNow(slot);+ this._reoccludeAll();+ }++ _detachNow(slot) {+ const root = this.getRoot();+ if (root) detachSlot(root, slot);+ this._attached.delete(slot);+ }++ _syncWorking() {+ this.working.garments = [...this._attached.values()].map(({ manifest }) => ({+ slot: manifest.slot,+ id: manifest.id,+ }));+ }++ /** Recompute skin occlusion as the union of every attached garment. */+ _reoccludeAll() {+ const root = this.getRoot();+ if (!root) return;+ const body = findAvatarSkeleton(root);+ if (body?.mesh?.geometry) restoreSkin(body.mesh.geometry);+ const regions = new Set();+ for (const { manifest } of this._attached.values()) {+ for (const r of manifest.occludes || []) regions.add(r);+ }+ if (regions.size) applySkinOcclusion(root, [...regions]);+ }++ async _fetchModel(manifest) {+ const uri = manifest.model.uri;+ if (!this._glbCache.has(uri)) {+ const p = fetch(uri).then(async (res) => {+ if (!res.ok) throw new Error(`garment download failed: ${res.status}`);+ return res.arrayBuffer();+ });+ p.catch(() => this._glbCache.delete(uri));+ this._glbCache.set(uri, p);+ }+ return this._glbCache.get(uri);+ }+}++/* ────────────────────────────────────────────────────────────────────────── *+ * Panel section+ * ────────────────────────────────────────────────────────────────────────── */++/**+ * Render the closet rack into `container` and wire it to `closet`.+ * Designed to sit directly under renderWardrobePanel's output.+ */+export async function renderClosetSection({ container, closet }) {+ injectCss();+ container.innerHTML = `<div class="gc-loading">Loading closet…</div>`;++ let catalog;+ try {+ catalog = await loadCatalog();+ } catch (err) {+ container.innerHTML = `+ <div class="gc-error" role="alert">+ Couldn't reach the closet.+ <button class="gc-retry" type="button">Retry</button>+ </div>`;+ container.querySelector('.gc-retry').addEventListener('click', async () => {+ try { await loadCatalog({ force: true }); } catch { /* rendered below */ }+ renderClosetSection({ container, closet });+ });+ log('garment-closet', `catalog load failed: ${err?.message || err}`);+ return;+ }++ const grouped = bySlot(catalog.garments);+ if (!catalog.garments.length) {+ container.innerHTML = `+ <div class="gc-empty">+ The closet is empty right now — new pieces land here as they're+ published. Generate your own on <a href="/forge">/forge</a>.+ </div>`;+ return;+ }++ const worn = closet.attached();+ container.innerHTML = `+ <h3 class="gc-title">Closet</h3>+ <p class="gc-note">Put on catalog pieces — they bind to this avatar's skeleton and move with every animation.</p>+ ${GARMENT_SLOTS.filter((s) => grouped.has(s)).map((slot) => `+ <div class="gc-rack" data-rack="${slot}">+ <div class="gc-rack-head">+ <span class="gc-rack-name">${SLOT_LABELS[slot] || slot}</span>+ <button class="gc-takeoff" type="button" data-slot="${slot}"+ ${worn.has(slot) ? '' : 'hidden'}>Take off</button>+ </div>+ <div class="gc-tiles" role="group" aria-label="${SLOT_LABELS[slot] || slot}">+ ${grouped.get(slot).map((g) => tileHtml(g, worn.get(g.slot)?.manifest?.id === g.id)).join('')}+ </div>+ </div>+ `).join('')}+ <div class="gc-status" role="status" aria-live="polite"></div>+ `;++ wireSection(container, closet, catalog);+}++function tileHtml(g, isWorn) {+ const thumb = g.preview?.thumbnail+ ? `<img src="${escAttr(g.preview.thumbnail)}" alt="" loading="lazy" />`+ : `<span class="gc-tile-fallback" aria-hidden="true">◆</span>`;+ return `+ <button class="gc-tile${isWorn ? ' worn' : ''}" type="button"+ data-garment="${escAttr(g.id)}" data-slot="${escAttr(g.slot)}"+ aria-pressed="${isWorn}" title="${escAttr(g.name)}">+ ${thumb}+ <span class="gc-tile-name">${escHtml(g.name)}</span>+ </button>+ `;+}++function wireSection(container, closet, catalog) {+ const byKey = new Map(catalog.garments.map((g) => [`${g.slot}/${g.id}`, g]));+ const status = container.querySelector('.gc-status');+ const setStatus = (msg) => { if (status) status.textContent = msg || ''; };++ const refresh = () => {+ const worn = closet.attached();+ container.querySelectorAll('.gc-tile').forEach((tile) => {+ const isWorn = worn.get(tile.dataset.slot)?.manifest?.id === tile.dataset.garment;+ tile.classList.toggle('worn', isWorn);+ tile.setAttribute('aria-pressed', String(isWorn));+ });+ container.querySelectorAll('.gc-takeoff').forEach((btn) => {+ btn.hidden = !worn.has(btn.dataset.slot);+ });+ };++ container.querySelectorAll('.gc-tile').forEach((tile) => {+ tile.addEventListener('click', async () => {+ const manifest = byKey.get(`${tile.dataset.slot}/${tile.dataset.garment}`);+ if (!manifest) return;+ const worn = closet.attached().get(manifest.slot)?.manifest?.id === manifest.id;+ tile.classList.add('busy');+ setStatus(worn ? `Taking off ${manifest.name}…` : `Putting on ${manifest.name}…`);+ try {+ if (worn) {+ await closet.detach(manifest.slot);+ setStatus('');+ } else {+ const res = await closet.attach(manifest);+ setStatus(res.ok ? '' : `Couldn't wear ${manifest.name}: ${res.reason}`);+ }+ } finally {+ tile.classList.remove('busy');+ refresh();+ }+ });+ });++ container.querySelectorAll('.gc-takeoff').forEach((btn) => {+ btn.addEventListener('click', async () => {+ await closet.detach(btn.dataset.slot);+ setStatus('');+ refresh();+ });+ });+}++/* ── styles ──────────────────────────────────────────────────────────────── */++let cssInjected = false;+function injectCss() {+ if (cssInjected || typeof document === 'undefined') return;+ cssInjected = true;+ const style = document.createElement('style');+ style.textContent = `+ .gc-title { margin: 18px 0 4px; font-size: 14px; font-weight: 600; }+ .gc-note { margin: 0 0 10px; font-size: 12px; opacity: 0.65; }+ .gc-rack { margin-bottom: 14px; }+ .gc-rack-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; }+ .gc-rack-name { font-size: 12px; font-weight: 600; opacity: 0.8; }+ .gc-takeoff { font-size: 11px; padding: 3px 8px; border-radius: 6px; border: 1px solid rgba(255,255,255,0.18);+ background: transparent; color: inherit; cursor: pointer; transition: background 0.15s ease; }+ .gc-takeoff:hover { background: rgba(255,255,255,0.08); }+ .gc-takeoff:focus-visible { outline: 2px solid #d4ed3a; outline-offset: 1px; }+ .gc-tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); gap: 8px; }+ .gc-tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: 6px;+ padding: 8px 6px; border-radius: 10px; border: 1px solid rgba(255,255,255,0.12);+ background: rgba(255,255,255,0.04); color: inherit; cursor: pointer;+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.15s ease; }+ .gc-tile:hover { background: rgba(255,255,255,0.09); transform: translateY(-1px); }+ .gc-tile:focus-visible { outline: 2px solid #d4ed3a; outline-offset: 1px; }+ .gc-tile.worn { border-color: #d4ed3a; background: rgba(212,237,58,0.10); }+ .gc-tile.busy { opacity: 0.55; pointer-events: none; }+ .gc-tile img { width: 56px; height: 56px; border-radius: 8px; object-fit: cover; }+ .gc-tile-fallback { width: 56px; height: 56px; border-radius: 8px; display: grid; place-items: center;+ background: rgba(255,255,255,0.06); font-size: 20px; opacity: 0.5; }+ .gc-tile-name { font-size: 11px; line-height: 1.2; text-align: center;+ overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }+ .gc-loading, .gc-empty, .gc-error { padding: 12px; font-size: 12px; opacity: 0.7; }+ .gc-error { color: #ff9d9d; opacity: 1; }+ .gc-retry { margin-left: 8px; font-size: 11px; padding: 3px 10px; border-radius: 6px;+ border: 1px solid currentColor; background: transparent; color: inherit; cursor: pointer; }+ .gc-status { min-height: 16px; font-size: 11px; opacity: 0.75; margin-top: 4px; }+ `;+ document.head.appendChild(style);+}++function escHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => (+ { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]+ ));+}+function escAttr(s) { return escHtml(s); }diff --git a/src/sign-clip.js b/src/sign-clip.jsindex d4012db42..3d597bc48 100644--- a/src/sign-clip.js+++ b/src/sign-clip.js@@ -155,20 +155,24 @@ export function poseHand(pose, side, spec) {* Build a whole-body pose for one phase of a sign.** @param {{+ * both?: object,* 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.+ * }} spec degrees for head/torso; `right`/`left` are {@link poseHand} specs and+ * `both` applies one spec to each hand — which works because directions and+ * places are body-relative, so a symmetric two-handed sign is written once.* @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()];+ const own = spec[side.toLowerCase()];+ const hand = own === 'rest' ? REST_ARM : spec.both ? { ...spec.both, ...(own ?? {}) } : own;if (!hand) continue;- poseHand(pose, side, hand === 'rest' ? REST_ARM : hand);+ poseHand(pose, side, hand);}const { head, torso } = spec;if (torso) {diff --git a/src/sign-dictionary.js b/src/sign-dictionary.jsnew file mode 100644index 000000000..250fb24ec--- /dev/null+++ b/src/sign-dictionary.js@@ -0,0 +1,401 @@+// Lexical ASL signs — the vocabulary an avatar signs instead of spelling.+//+// Fingerspelling is a fallback, not a language: a signer spells names and+// loanwords and SIGNS everything else. This module holds the signs themselves,+// written the way ASL is actually described — a handshape, a place on or in+// front of the body, the direction the palm and fingers face, and a movement+// through those places. Both hands are first-class: two-handed signs are the+// normal case in ASL, and writing one is a single `both:` block because places+// and directions are body-relative (src/sign-clip.js), so the non-dominant hand+// mirrors for free.+//+// Every sign compiles through the same solver the alphabet uses: the wrist goes+// to a POINT in signing space and src/sign-rig.js's two-bone IK finds the+// shoulder, elbow, and wrist that put it there. Nothing is hand-tuned in joint+// angles, so a sign holds up on any rigged avatar the retargeter can drive.+//+// Coverage is deliberately a core vocabulary, not a claim to fluency. Words with+// no entry here fingerspell (src/sign-speech.js decides), and this file is meant+// to grow: add an entry, add a test asserting where the hands end up, done.+//+// Grammar note: these are citation-form signs strung together in English word+// order. That is "signed English", not ASL grammar (which reorders, inflects+// verbs spatially, and carries meaning in the face). The page says so plainly —+// we are not pretending otherwise.++import { SignTimeline, posePhase, restingPose } from './sign-clip.js';++// Where the non-dominant hand waits when it is a surface for the other hand to+// act on (FALL, HELP, GOOD, STOP): flat, palm up, in front of the chest.+const BASE_PALM = {+ shape: 'FLAT',+ at: { anchor: 'sternum', out: 0.06, up: -0.09, forward: 0.24 },+ fingers: ['forward', 'in'],+ palm: 'up',+};++// Neutral signing space in front of the chest, where most two-handed signs live.+const NEUTRAL = { anchor: 'sternum', out: 0.13, up: -0.02, forward: 0.26 };++/**+ * The vocabulary. Each sign is a list of phases; `t` is the seconds spent moving+ * INTO that phase and `hold` the seconds spent in it. `both` poses both hands+ * from one description, `right`/`left` override or act alone.+ *+ * @type {Record<string, { gloss: string, phases: object[] }>}+ */+export const SIGNS = Object.freeze({+ HELLO: {+ gloss: 'Flat hand salutes out from the temple.',+ phases: [+ { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'forehead', out: 0.11, up: -0.03, forward: 0.1 }, fingers: ['up', 'in'], palm: ['forward', 'down'] }, head: { nod: 2 }, hold: 0.1 },+ { t: 0.32, right: { shape: 'FLAT', at: { anchor: 'forehead', out: 0.21, up: -0.07, forward: 0.18 }, fingers: ['up', 'out'], palm: 'forward' }, head: { nod: -2 }, hold: 0.18 },+ ],+ },+ THANK: {+ gloss: 'Flat hand moves out and down from the chin.',+ phases: [+ { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.03, up: -0.03, forward: 0.12 }, fingers: ['up', 'in'], palm: 'back' }, head: { nod: 3 }, hold: 0.12 },+ { t: 0.34, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.08, up: -0.16, forward: 0.28 }, fingers: ['forward', 'up'], palm: 'up' }, head: { nod: 6 }, hold: 0.16 },+ ],+ },+ PLEASE: {+ gloss: 'Flat hand circles on the chest.',+ phases: [+ { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.02, up: 0.03, forward: 0.13 }, fingers: ['up', 'in'], palm: 'back' } },+ { t: 0.26, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.09, up: -0.02, forward: 0.13 }, fingers: ['up', 'in'], palm: 'back' } },+ { t: 0.26, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.02, up: -0.07, forward: 0.13 }, fingers: ['up', 'in'], palm: 'back' } },+ { t: 0.26, right: { shape: 'FLAT', at: { anchor: 'sternum', out: -0.04, up: -0.02, forward: 0.13 }, fingers: ['up', 'in'], palm: 'back' } },+ { t: 0.26, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.02, up: 0.03, forward: 0.13 }, fingers: ['up', 'in'], palm: 'back' }, hold: 0.1 },+ ],+ },+ SORRY: {+ gloss: 'A-hand circles over the heart.',+ phases: [+ { t: 0.3, right: { shape: 'A', at: { anchor: 'sternum', out: 0.03, up: 0.02, forward: 0.14 }, fingers: 'up', palm: 'back' }, head: { nod: 5, tilt: 3 } },+ { t: 0.26, right: { shape: 'A', at: { anchor: 'sternum', out: 0.1, up: -0.04, forward: 0.14 }, fingers: 'up', palm: 'back' }, head: { nod: 5, tilt: 3 } },+ { t: 0.26, right: { shape: 'A', at: { anchor: 'sternum', out: 0.03, up: -0.09, forward: 0.14 }, fingers: 'up', palm: 'back' }, head: { nod: 5, tilt: 3 } },+ { t: 0.26, right: { shape: 'A', at: { anchor: 'sternum', out: 0.03, up: 0.02, forward: 0.14 }, fingers: 'up', palm: 'back' }, head: { nod: 5, tilt: 3 }, hold: 0.12 },+ ],+ },+ YES: {+ gloss: 'S-hand nods at the wrist, like a head saying yes.',+ phases: [+ { t: 0.28, right: { shape: 'S', at: NEUTRAL, fingers: 'up', palm: 'forward' }, head: { nod: 3 } },+ { t: 0.18, right: { shape: 'S', at: NEUTRAL, fingers: ['forward', 'down'], palm: ['forward', 'down'] }, head: { nod: 7 } },+ { t: 0.18, right: { shape: 'S', at: NEUTRAL, fingers: 'up', palm: 'forward' }, head: { nod: 2 } },+ { t: 0.18, right: { shape: 'S', at: NEUTRAL, fingers: ['forward', 'down'], palm: ['forward', 'down'] }, head: { nod: 7 }, hold: 0.12 },+ ],+ },+ NO: {+ gloss: 'Index and middle finger snap shut against the thumb.',+ phases: [+ { t: 0.28, right: { shape: 'U', at: { anchor: 'chin', out: 0.14, up: -0.1, forward: 0.24 }, fingers: ['forward', 'up'], palm: ['down', 'forward'] }, head: { turn: 4 } },+ { t: 0.2, right: { shape: 'FLAT_O', at: { anchor: 'chin', out: 0.14, up: -0.1, forward: 0.24 }, fingers: ['forward', 'up'], palm: ['down', 'forward'] }, head: { turn: -4 }, hold: 0.16 },+ ],+ },+ HAPPY: {+ gloss: 'Both flat hands brush up the chest in circles.',+ phases: [+ { t: 0.3, both: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.14, up: -0.13, forward: 0.16 }, fingers: ['up', 'in'], palm: 'back' }, head: { nod: -2 } },+ { t: 0.24, both: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.16, up: 0.01, forward: 0.19 }, fingers: ['up', 'in'], palm: ['back', 'down'] }, head: { nod: -4 } },+ { t: 0.24, both: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.14, up: -0.13, forward: 0.16 }, fingers: ['up', 'in'], palm: 'back' }, head: { nod: -2 } },+ { t: 0.24, both: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.16, up: 0.01, forward: 0.19 }, fingers: ['up', 'in'], palm: ['back', 'down'] }, head: { nod: -4 }, hold: 0.14 },+ ],+ },+ FALL: {+ gloss: 'Two legs stand on the flat palm, then tip over onto their back.',+ phases: [+ { t: 0.32, left: BASE_PALM, right: { shape: 'V', at: { anchor: 'sternum', out: 0.02, up: 0.0, forward: 0.26 }, fingers: 'down', palm: 'back' }, hold: 0.16 },+ { t: 0.3, left: BASE_PALM, right: { shape: 'V', at: { anchor: 'sternum', out: 0.16, up: -0.07, forward: 0.27 }, fingers: ['out', 'forward'], palm: 'up' }, head: { turn: -4, tilt: 4 }, hold: 0.2 },+ ],+ },+ YALL: {+ gloss: 'Flat palm-up hand sweeps an arc across the group.',+ phases: [+ { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'sternum', out: -0.08, up: -0.06, forward: 0.28 }, fingers: ['forward', 'in'], palm: 'up' }, head: { turn: 5 } },+ { t: 0.42, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.26, up: -0.04, forward: 0.24 }, fingers: ['forward', 'out'], palm: 'up' }, head: { turn: -6 }, hold: 0.16 },+ ],+ },+ YOU: {+ gloss: 'Index finger points at the person addressed.',+ phases: [+ { t: 0.28, right: { shape: '1', at: { anchor: 'sternum', out: 0.06, up: 0.04, forward: 0.3 }, fingers: 'forward', palm: 'down' }, head: { nod: 2 }, hold: 0.22 },+ ],+ },+ ME: {+ gloss: 'Index finger points to the signer’s own chest.',+ phases: [+ { t: 0.28, right: { shape: '1', at: { anchor: 'sternum', out: 0.05, up: -0.02, forward: 0.14 }, fingers: ['in', 'back'], palm: 'down' }, hold: 0.22 },+ ],+ },+ NAME: {+ gloss: 'Two H-hands tap across each other.',+ phases: [+ { t: 0.3, left: { shape: 'H', at: { anchor: 'sternum', out: 0.05, up: -0.02, forward: 0.25 }, fingers: ['forward', 'in'], palm: ['in', 'down'] }, right: { shape: 'H', at: { anchor: 'sternum', out: 0.05, up: 0.05, forward: 0.25 }, fingers: ['forward', 'in'], palm: 'down' } },+ { t: 0.16, left: { shape: 'H', at: { anchor: 'sternum', out: 0.05, up: -0.02, forward: 0.25 }, fingers: ['forward', 'in'], palm: ['in', 'down'] }, right: { shape: 'H', at: { anchor: 'sternum', out: 0.05, up: 0.005, forward: 0.25 }, fingers: ['forward', 'in'], palm: 'down' } },+ { t: 0.16, left: { shape: 'H', at: { anchor: 'sternum', out: 0.05, up: -0.02, forward: 0.25 }, fingers: ['forward', 'in'], palm: ['in', 'down'] }, right: { shape: 'H', at: { anchor: 'sternum', out: 0.05, up: 0.05, forward: 0.25 }, fingers: ['forward', 'in'], palm: 'down' } },+ { t: 0.16, left: { shape: 'H', at: { anchor: 'sternum', out: 0.05, up: -0.02, forward: 0.25 }, fingers: ['forward', 'in'], palm: ['in', 'down'] }, right: { shape: 'H', at: { anchor: 'sternum', out: 0.05, up: 0.005, forward: 0.25 }, fingers: ['forward', 'in'], palm: 'down' }, hold: 0.14 },+ ],+ },+ HELP: {+ gloss: 'A-hand rides the flat palm upward.',+ phases: [+ { t: 0.32, left: BASE_PALM, right: { shape: 'A', at: { anchor: 'sternum', out: 0.03, up: -0.06, forward: 0.26 }, fingers: 'up', palm: 'in' } },+ { t: 0.28, left: { ...BASE_PALM, at: { anchor: 'sternum', out: 0.06, up: 0.02, forward: 0.26 } }, right: { shape: 'A', at: { anchor: 'sternum', out: 0.03, up: 0.05, forward: 0.28 }, fingers: 'up', palm: 'in' }, hold: 0.16 },+ ],+ },+ GOOD: {+ gloss: 'Flat hand comes down from the chin onto the other palm.',+ phases: [+ { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.03, up: -0.02, forward: 0.13 }, fingers: ['up', 'in'], palm: 'back' }, left: BASE_PALM, head: { nod: 3 } },+ { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.05, up: -0.02, forward: 0.25 }, fingers: ['forward', 'in'], palm: 'up' }, left: BASE_PALM, head: { nod: 5 }, hold: 0.18 },+ ],+ },+ BAD: {+ gloss: 'Flat hand leaves the chin and turns palm-down.',+ phases: [+ { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.03, up: -0.02, forward: 0.13 }, fingers: ['up', 'in'], palm: 'back' }, head: { nod: 2 } },+ { t: 0.3, right: { shape: 'FLAT', at: { anchor: 'chin', out: 0.14, up: -0.2, forward: 0.24 }, fingers: ['forward', 'out'], palm: 'down' }, head: { nod: -3, turn: -5 }, hold: 0.16 },+ ],+ },+ LOVE: {+ gloss: 'Both arms cross over the heart.',+ phases: [+ { t: 0.36, left: { shape: 'S', at: { anchor: 'sternum', out: -0.07, up: 0.02, forward: 0.15 }, fingers: ['up', 'in'], palm: 'back' }, right: { shape: 'S', at: { anchor: 'sternum', out: -0.07, up: -0.05, forward: 0.17 }, fingers: ['up', 'in'], palm: 'back' }, head: { nod: 4, tilt: 3 }, hold: 0.3 },+ ],+ },+ LEARN: {+ gloss: 'Fingers lift knowledge off the palm to the forehead.',+ phases: [+ { t: 0.32, left: BASE_PALM, right: { shape: 'CLAW', at: { anchor: 'sternum', out: 0.04, up: -0.04, forward: 0.27 }, fingers: 'down', palm: 'down' } },+ { t: 0.2, left: BASE_PALM, right: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.04, up: 0.02, forward: 0.26 }, fingers: 'down', palm: 'back' } },+ { t: 0.32, left: BASE_PALM, right: { shape: 'FLAT_O', at: { anchor: 'forehead', out: 0.05, up: -0.05, forward: 0.1 }, fingers: ['up', 'back'], palm: 'down' }, hold: 0.16 },+ ],+ },+ KNOW: {+ gloss: 'Fingertips tap the forehead.',+ phases: [+ { t: 0.3, right: { shape: 'BENT_B', at: { anchor: 'forehead', out: 0.1, up: -0.06, forward: 0.07 }, fingers: ['up', 'in'], palm: 'back' } },+ { t: 0.16, right: { shape: 'BENT_B', at: { anchor: 'forehead', out: 0.08, up: -0.06, forward: 0.04 }, fingers: ['up', 'in'], palm: 'back' }, hold: 0.14 },+ ],+ },+ THINK: {+ gloss: 'Index finger touches the temple.',+ phases: [+ { t: 0.3, right: { shape: '1', at: { anchor: 'forehead', out: 0.09, up: -0.06, forward: 0.06 }, fingers: ['in', 'up'], palm: 'down' }, head: { tilt: 3 }, hold: 0.24 },+ ],+ },+ SEE: {+ gloss: 'V-hand moves out from the eyes.',+ phases: [+ { t: 0.3, right: { shape: 'V', at: { anchor: 'nose', out: 0.08, up: 0.02, forward: 0.1 }, fingers: ['up', 'forward'], palm: 'back' } },+ { t: 0.3, right: { shape: 'V', at: { anchor: 'nose', out: 0.11, up: -0.02, forward: 0.26 }, fingers: 'forward', palm: 'down' }, hold: 0.16 },+ ],+ },+ WANT: {+ gloss: 'Both claw hands draw in toward the body.',+ phases: [+ { t: 0.32, both: { shape: 'CLAW', at: { anchor: 'sternum', out: 0.11, up: -0.04, forward: 0.32 }, fingers: 'forward', palm: 'up' } },+ { t: 0.3, both: { shape: 'CLAW', at: { anchor: 'sternum', out: 0.11, up: -0.08, forward: 0.19 }, fingers: ['forward', 'up'], palm: 'up' }, head: { nod: 3 }, hold: 0.16 },+ ],+ },+ MORE: {+ gloss: 'Both flat-O hands tap fingertips together.',+ phases: [+ { t: 0.3, both: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.11, up: 0.0, forward: 0.26 }, fingers: 'in', palm: 'down' } },+ { t: 0.18, both: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.05, up: 0.0, forward: 0.26 }, fingers: 'in', palm: 'down' } },+ { t: 0.18, both: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.11, up: 0.0, forward: 0.26 }, fingers: 'in', palm: 'down' } },+ { t: 0.18, both: { shape: 'FLAT_O', at: { anchor: 'sternum', out: 0.05, up: 0.0, forward: 0.26 }, fingers: 'in', palm: 'down' }, hold: 0.14 },+ ],+ },+ STOP: {+ gloss: 'Flat hand chops down onto the other palm.',+ phases: [+ { t: 0.3, left: { ...BASE_PALM, at: { anchor: 'sternum', out: 0.04, up: -0.06, forward: 0.26 } }, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.04, up: 0.09, forward: 0.26 }, fingers: ['forward', 'up'], palm: 'in' } },+ { t: 0.2, left: { ...BASE_PALM, at: { anchor: 'sternum', out: 0.04, up: -0.06, forward: 0.26 } }, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.04, up: -0.03, forward: 0.26 }, fingers: 'forward', palm: 'in' }, head: { nod: 3 }, hold: 0.2 },+ ],+ },+ WORK: {+ gloss: 'One fist taps the back of the other wrist twice.',+ phases: [+ { t: 0.32, left: { shape: 'S', at: { anchor: 'sternum', out: 0.02, up: -0.08, forward: 0.26 }, fingers: ['forward', 'in'], palm: 'down' }, right: { shape: 'S', at: { anchor: 'sternum', out: 0.03, up: 0.02, forward: 0.24 }, fingers: ['forward', 'in'], palm: 'down' } },+ { t: 0.16, left: { shape: 'S', at: { anchor: 'sternum', out: 0.02, up: -0.08, forward: 0.26 }, fingers: ['forward', 'in'], palm: 'down' }, right: { shape: 'S', at: { anchor: 'sternum', out: 0.03, up: -0.03, forward: 0.24 }, fingers: ['forward', 'in'], palm: 'down' } },+ { t: 0.16, left: { shape: 'S', at: { anchor: 'sternum', out: 0.02, up: -0.08, forward: 0.26 }, fingers: ['forward', 'in'], palm: 'down' }, right: { shape: 'S', at: { anchor: 'sternum', out: 0.03, up: 0.02, forward: 0.24 }, fingers: ['forward', 'in'], palm: 'down' } },+ { t: 0.16, left: { shape: 'S', at: { anchor: 'sternum', out: 0.02, up: -0.08, forward: 0.26 }, fingers: ['forward', 'in'], palm: 'down' }, right: { shape: 'S', at: { anchor: 'sternum', out: 0.03, up: -0.03, forward: 0.24 }, fingers: ['forward', 'in'], palm: 'down' }, hold: 0.14 },+ ],+ },+ FRIEND: {+ gloss: 'Hooked index fingers link, then swap.',+ phases: [+ { t: 0.32, left: { shape: 'X', at: { anchor: 'sternum', out: 0.05, up: -0.03, forward: 0.26 }, fingers: ['forward', 'in', 'up'], palm: 'up' }, right: { shape: 'X', at: { anchor: 'sternum', out: 0.05, up: 0.03, forward: 0.26 }, fingers: ['forward', 'in', 'down'], palm: 'down' }, hold: 0.14 },+ { t: 0.26, left: { shape: 'X', at: { anchor: 'sternum', out: 0.05, up: 0.03, forward: 0.26 }, fingers: ['forward', 'in', 'down'], palm: 'down' }, right: { shape: 'X', at: { anchor: 'sternum', out: 0.05, up: -0.03, forward: 0.26 }, fingers: ['forward', 'in', 'up'], palm: 'up' }, hold: 0.16 },+ ],+ },+ MEET: {+ gloss: 'Two upright index fingers come together.',+ phases: [+ { t: 0.3, both: { shape: '1', at: { anchor: 'sternum', out: 0.17, up: 0.02, forward: 0.26 }, fingers: 'up', palm: 'in' } },+ { t: 0.28, both: { shape: '1', at: { anchor: 'sternum', out: 0.04, up: 0.02, forward: 0.26 }, fingers: 'up', palm: 'in' }, head: { nod: 3 }, hold: 0.18 },+ ],+ },+ NICE: {+ gloss: 'Flat hand slides cleanly across the other palm.',+ phases: [+ { t: 0.32, left: { ...BASE_PALM, fingers: ['forward', 'out'] }, right: { shape: 'FLAT', at: { anchor: 'sternum', out: -0.04, up: -0.05, forward: 0.24 }, fingers: ['forward', 'out'], palm: 'down' } },+ { t: 0.32, left: { ...BASE_PALM, fingers: ['forward', 'out'] }, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.19, up: -0.05, forward: 0.26 }, fingers: ['forward', 'out'], palm: 'down' }, hold: 0.16 },+ ],+ },+ WELCOME: {+ gloss: 'Open palm sweeps in toward the body, inviting.',+ phases: [+ { t: 0.32, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.22, up: -0.04, forward: 0.3 }, fingers: ['forward', 'out'], palm: 'up' }, head: { turn: -4 } },+ { t: 0.34, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.02, up: -0.06, forward: 0.22 }, fingers: ['forward', 'in'], palm: 'up' }, head: { nod: 4 }, hold: 0.18 },+ ],+ },+ WHAT: {+ gloss: 'Both palms turn up and shake, with a questioning brow.',+ phases: [+ { t: 0.3, both: { shape: '5', at: { anchor: 'sternum', out: 0.15, up: -0.08, forward: 0.26 }, fingers: ['forward', 'out'], palm: 'up' }, head: { tilt: 3, nod: -3 } },+ { t: 0.16, both: { shape: '5', at: { anchor: 'sternum', out: 0.18, up: -0.06, forward: 0.26 }, fingers: ['forward', 'out'], palm: 'up' }, head: { tilt: 3, nod: -3 } },+ { t: 0.16, both: { shape: '5', at: { anchor: 'sternum', out: 0.15, up: -0.08, forward: 0.26 }, fingers: ['forward', 'out'], palm: 'up' }, head: { tilt: 3, nod: -3 }, hold: 0.16 },+ ],+ },+ FINISH: {+ gloss: 'Both open hands flick out and down — done.',+ phases: [+ { t: 0.3, both: { shape: '5', at: { anchor: 'sternum', out: 0.1, up: 0.04, forward: 0.24 }, fingers: 'up', palm: 'back' } },+ { t: 0.24, both: { shape: '5', at: { anchor: 'sternum', out: 0.2, up: -0.08, forward: 0.26 }, fingers: ['forward', 'out'], palm: 'down' }, head: { nod: 4 }, hold: 0.18 },+ ],+ },+ AGAIN: {+ gloss: 'Bent hand arcs over and taps into the flat palm.',+ phases: [+ { t: 0.32, left: BASE_PALM, right: { shape: 'BENT_B', at: { anchor: 'sternum', out: 0.2, up: 0.02, forward: 0.24 }, fingers: ['up', 'out'], palm: 'up' } },+ { t: 0.3, left: BASE_PALM, right: { shape: 'BENT_B', at: { anchor: 'sternum', out: 0.06, up: -0.05, forward: 0.26 }, fingers: ['down', 'in'], palm: 'down' }, hold: 0.16 },+ ],+ },+ THREE: {+ gloss: 'The number three, held up clearly.',+ phases: [+ { t: 0.3, right: { shape: '3', at: { anchor: 'chin', out: 0.2, up: -0.06, forward: 0.22 }, fingers: 'up', palm: 'forward' }, hold: 0.26 },+ ],+ },+});++// Everyday words that map onto a sign already in the table. Kept separate so the+// vocabulary itself stays one entry per sign.+const ALIASES = Object.freeze({+ HI: 'HELLO',+ HEY: 'HELLO',+ THANKS: 'THANK',+ THANKYOU: 'THANK',+ YEAH: 'YES',+ YEP: 'YES',+ OK: 'YES',+ NOPE: 'NO',+ GLAD: 'HAPPY',+ FELL: 'FALL',+ FALLS: 'FALL',+ YOURE: 'YOU',+ MY: 'ME',+ MINE: 'ME',+ I: 'ME',+ IM: 'ME',+ NEED: 'WANT',+ WANTS: 'WANT',+ LIKE: 'GOOD',+ GREAT: 'GOOD',+ NICELY: 'NICE',+ KNOWS: 'KNOW',+ THINKS: 'THINK',+ LOOK: 'SEE',+ WATCH: 'SEE',+ MEETS: 'MEET',+ WORKS: 'WORK',+ WORKING: 'WORK',+ DONE: 'FINISH',+ FINISHED: 'FINISH',+ AGAIN: 'AGAIN',+ REPEAT: 'AGAIN',+ FRIENDS: 'FRIEND',+ HELPS: 'HELP',+ HELPING: 'HELP',+ LEARNING: 'LEARN',+ NAMED: 'NAME',+ EVERYONE: 'YALL',+ EVERYBODY: 'YALL',+ YALL: 'YALL',+ SORRYY: 'SORRY',+});++/** Every word this dictionary can sign, including aliases. */+export const SIGNABLE_WORDS = Object.freeze([...Object.keys(SIGNS), ...Object.keys(ALIASES)].sort());++/**+ * Resolve a normalized word to its sign entry, or null when it must be spelled.+ * @param {string} word already uppercased/normalized+ * @returns {{ name: string, sign: object }|null}+ */+export function lookupSign(word) {+ const key = String(word ?? '').toUpperCase();+ const name = SIGNS[key] ? key : ALIASES[key];+ return name && SIGNS[name] ? { name, sign: SIGNS[name] } : null;+}++export const DEFAULT_SIGN_TIMING = Object.freeze({+ leadSeconds: 0.3,+ tailSeconds: 0.38,+ /** Scales every authored phase duration — the tempo control for chat. */+ rate: 1,+});++/**+ * Build the AnimationClip document for one lexical sign.+ *+ * @param {string} word+ * @param {{ name?: string, base?: import('./sign-rig.js').Pose, settle?: boolean, rate?: number }} [opts]+ * @returns {object|null} clip document, or null when the word has no sign+ */+export function buildSignClip(word, opts = {}) {+ const found = lookupSign(word);+ if (!found) return null;+ const timing = { ...DEFAULT_SIGN_TIMING, ...opts };+ const rate = timing.rate > 0 ? timing.rate : 1;+ const base = opts.base ?? restingPose();+ const tl = new SignTimeline({ base });++ found.sign.phases.forEach((phase, i) => {+ const seconds = ((phase.t ?? 0.3) + (i === 0 ? timing.leadSeconds : 0)) / rate;+ tl.to(posePhase(phase, base), seconds, { ease: phase.ease ?? (i === 0 ? 'out' : 'smooth') });+ if (phase.hold) tl.hold(phase.hold / rate);+ });++ if (opts.settle === false) tl.hold(timing.tailSeconds / rate);+ else tl.settle(timing.tailSeconds / rate);++ return tl.build({+ name: opts.name ?? `sign-${found.name.toLowerCase()}`,+ seed: `sign:${found.name}:${rate}`,+ });+}++/**+ * A lookup function shaped for {@link import('./sign-speech.js').compileUtterance}:+ * pass it as `signs` and every word with an entry is SIGNED, the rest spelled.+ *+ * @param {{ base?: import('./sign-rig.js').Pose, rate?: number }} [opts]+ * @returns {(word: string) => object|null}+ */+export function signLookup(opts = {}) {+ const cache = new Map();+ return (word) => {+ if (!cache.has(word)) cache.set(word, buildSignClip(word, { ...opts, settle: false }));+ return cache.get(word);+ };+}++/** Human-readable description of a sign, for the vocabulary UI. */+export function signGloss(word) {+ return lookupSign(word)?.sign.gloss ?? null;+}diff --git a/src/sign-handshapes.js b/src/sign-handshapes.jsindex e590946ea..f41d01cb2 100644--- a/src/sign-handshapes.js+++ b/src/sign-handshapes.js@@ -1,19 +1,21 @@-// ASL handshapes — the finger configurations both lanes of the signing stack-// share: the manual alphabet (fingerspelling) and the lexical sign dictionary.+// ASL handshapes — the finger configurations the signing stack shares between+// the manual alphabet (src/fingerspelling.js) and the lexical sign dictionary+// (src/sign-dictionary.js).//-// 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.+// A handshape is described the way a signer describes it — how far each finger+// curls, how the fingers spread, where the thumb sits — and compiled to local+// rotations on the canonical finger bones. This is the ORIGINAL, hand-tuned+// handshape model, moved here unchanged so both lanes can share it: the letter+// table, the curl weights, the thumb presets, and the axes they are tuned+// against are exactly what the alphabet already spelled with. Nothing in this+// file changes the shape of a letter.//// 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`).+// `FLAT_O`, `BENT_B`, `OPEN_8`), which the lexical signs need and the alphabet+// never used.-import { adductAxis, curlAxis, qAxisAngle, qMul, qNorm, splayAxis } from './sign-rig.js';+import { qAxisAngle, qMul, qNorm, vNorm } from './sign-rig.js';export const FINGERS = ['Index', 'Middle', 'Ring', 'Pinky'];export const FINGER_JOINTS = [1, 2, 3];@@ -23,86 +25,88 @@ 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];+// Per-joint shares of a full curl (proximal knuckles carry most of it).+const CURL_WEIGHTS = [85, 100, 65];-// Thumb positions, as adduction (toward the fingers, across the palm) plus a-// per-joint curl. Every ASL handshape uses one of these five.+// 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 = {- /** 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 },+ // 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] },+ // barely engaged — the hand between letters and at rest+ neutral: { adduct: 0, curl: [4, 4, 4] },};/*** 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.+ * degrees), `splay` is degrees toward the thumb, `knuckle` adds bend at the+ * proximal joint only, and `thumb` names a preset.+ *+ * A–Z and 0–9 are the manual alphabet, unchanged.*/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' },+ 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' },- H: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: 2, Middle: -2 }, thumb: 'side' },+ H: { curl: { Ring: 1, Pinky: 1 }, 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' },+ 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.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' },+ 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' },Q: { curl: { Middle: 1, Ring: 1, Pinky: 1 }, thumb: 'side' },- R: { curl: { Ring: 1, Pinky: 1 }, splay: { Index: -7, Middle: 9 }, thumb: 'across' },+ 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.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' },+ 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' },- // 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' },+ // 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: 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' },+ 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' },- // 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' },+ // ── shapes with no letter of their own, used by the lexical signs ────────+ /** The hand between letters and at rest: barely engaged, not a pose. */+ RELAXED: { curl: { Index: [12, 12, 12], Middle: [12, 12, 12], Ring: [12, 12, 12], Pinky: [12, 12, 12] }, thumb: 'neutral' },/** 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' },+ FLAT: { curl: {}, thumb: 'side' },+ /** Flat hand bent at the knuckles — HAPPY, YOUR, the release of THANK-YOU. */+ BENT_B: { curl: {}, knuckle: 50, thumb: 'across' },+ /** Spread and curved, like holding a ball. */+ 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' },/** 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' },+ FLAT_O: { curl: { Index: 0.6, Middle: 0.6, Ring: 0.6, Pinky: 0.6 }, knuckle: 20, 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' },});@@ -110,14 +114,14 @@ export const HANDSHAPES = Object.freeze({/** Names of every handshape, for docs and tooling. */export const HANDSHAPE_NAMES = Object.freeze(Object.keys(HANDSHAPES));-function jointDegrees(spec) {+function fingerJointDegrees(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.+ * Compile one handshape into finger-bone local quats for one side.** @param {string} name a HANDSHAPES key (letter, digit, or named shape)* @param {'Left'|'Right'} [side]@@ -125,33 +129,29 @@ function jointDegrees(spec) {*/export function handshapeLocals(name, side = 'Right') {const shape = HANDSHAPES[name];- if (!shape) throw new Error(`no handshape "${name}"`);+ if (!shape) throw new Error(`no handshape for letter "${name}"`);+ 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 curl = jointDegrees(shape.curl?.[finger] ?? 0);+ const deg = fingerJointDegrees(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);+ for (let j = 0; j < 3; j++) {+ let q = qAxisAngle(curlAxis, deg[j] + (j === 0 ? (shape.knuckle ?? 0) : 0));+ if (j === 0 && splay) q = qMul(q, qAxisAngle(splayAxis, splay * -s));+ locals[`${side}Hand${finger}${j + 1}`] = 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);+ 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;}diff --git a/src/sign-rig.js b/src/sign-rig.jsindex 36aee19a4..f8013d550 100644--- a/src/sign-rig.js+++ b/src/sign-rig.js@@ -266,7 +266,7 @@ const _axisCache = new Map();/*** The bone's own axis: the LOCAL direction that points at its child. ~[0,1,0]- * on Mixamo/Avaturn rigs, but measured rather than assumed.+ * on most canonical humanoid rigs, but measured rather than assumed.* @param {string} bone* @returns {number[]}*/@@ -385,8 +385,12 @@ export const ANCHORS = (() => {chin: [0, chinY, head[2] + 0.03],mouth: [0, chinY + 0.04, head[2] + 0.04],nose: [0, head[1] + 0.02, head[2] + 0.05],- /** Upper chest, where most two-handed signs live. */- sternum: [0, chest[1] + 0.06, chest[2] + 0.02],+ /**+ * Upper chest, where most two-handed signs live. Measured up from the+ * chest bone toward the neck rather than from the bone itself, which sits+ * at mid-torso — anchoring signs there hangs them at belly height.+ */+ sternum: [0, chest[1] + (neck[1] - chest[1]) * 0.6, chest[2] + 0.02],/** Mid torso — the low end of neutral signing space. */belly: [0, (chest[1] + hips[1]) / 2, chest[2]],});diff --git a/src/sign-speech.js b/src/sign-speech.jsindex f138fb86a..88fafd3c8 100644--- a/src/sign-speech.js+++ b/src/sign-speech.js@@ -14,6 +14,7 @@// a standalone package.import { DEFAULT_TIMING, buildFingerspellingClip, normalizeWord } from './fingerspelling.js';+import { lookupSign, signLookup } from './sign-dictionary.js';// Chat replies favour pace over ceremony: quicker holds and transitions than// the studio default, so a sentence stays watchable.@@ -37,19 +38,24 @@ export function utteranceWords(text) {return normalizeWord(text).split(' ').filter(Boolean);}+// A lexical sign runs about this long in citation form — used only by the+// estimator, which decides how much text is worth signing before anything is+// compiled.+const SIGN_SECONDS = 1.1;+/*** Rough signing duration in seconds for `text` under `timing`, before- * compiling anything — used to cap chat replies to a watchable length.+ * compiling anything — used to cap chat replies to a watchable length. Words+ * with a dictionary sign count as one sign; the rest are counted per letter.*/-export function estimateDuration(text, timing = CHAT_TIMING) {+export function estimateDuration(text, timing = CHAT_TIMING, { signed = true } = {}) {const words = utteranceWords(text);- const letters = words.reduce((n, w) => n + w.length, 0);- return (- timing.leadSeconds +- timing.tailSeconds +- letters * (timing.holdSeconds + timing.transitionSeconds) +- Math.max(0, words.length - 1) * WORD_GAP_SECONDS- );+ let seconds = timing.leadSeconds + timing.tailSeconds;+ for (const word of words) {+ if (signed && lookupSign(word)) seconds += SIGN_SECONDS;+ else seconds += word.length * (timing.holdSeconds + timing.transitionSeconds);+ }+ return seconds + Math.max(0, words.length - 1) * WORD_GAP_SECONDS;}// Append `clip`'s tracks to the merged timeline starting at `offset`. Bones@@ -134,12 +140,14 @@ export function compileUtterance(text, opts = {}) {(sign ? signed : spelled).push(word);}+ // Rotation lanes only. A signed utterance is upper-body: it must never write+ // the root's translation, which on a rig whose hips rest a metre off the+ // floor would drop the whole avatar through it.const tracks = [];for (const [name, lane] of merged) {- if (name === 'Hips.position') continue; // re-added as a single origin key+ if (name.endsWith('.position') || name.endsWith('.scale')) continue;tracks.push({ type: lane.type, name, times: lane.times, values: lane.values });}- tracks.push({ type: 'vector', name: 'Hips.position', times: [0], values: [0, 0, 0] });return {clip: {@@ -167,10 +175,13 @@ export function compileUtterance(text, opts = {}) {* `signs` (optional) is the lexical dictionary passed through to the compiler.*/export class SignSpeaker {- constructor({ manager, signs = null, timing = null, maxSeconds = 45 } = {}) {+ constructor({ manager, signs = undefined, timing = null, maxSeconds = 45 } = {}) {if (!manager) throw new Error('SignSpeaker needs a manager');this.manager = manager;- this.signs = signs;+ // Default to the built-in vocabulary: a signer signs the words they have+ // signs for and only spells the rest. Pass `signs: null` for spelling-only,+ // or your own lookup to override.+ this.signs = signs === undefined ? signLookup() : signs;this.timing = timing;this.maxSeconds = maxSeconds;this._counter = 0;diff --git a/tests/avatar-garment.test.js b/tests/avatar-garment.test.jsnew file mode 100644index 000000000..bc5a26b39--- /dev/null+++ b/tests/avatar-garment.test.js@@ -0,0 +1,360 @@+/**+ * Additive wardrobe — unit tests for src/avatar-garment.js.+ *+ * Builds synthetic avatars and garments in-memory (no GLB fixtures), so the+ * suite is fast and deterministic. The contract under test is that a garment+ * authored against its *own* skeleton, with its own naming convention and its+ * own rest pose, deforms identically to the avatar's body once rebound:+ *+ * - garment bone indices rewritten into avatar bone order,+ * - vendor-prefixed / foreign naming still resolves (mixamorig:, VRM, .L/.R),+ * - helper joints the avatar lacks fall back to their nearest mapped ancestor,+ * - unresolvable weights are zeroed and the vertex renormalised,+ * - a divergent rest pose is reconciled, not baked in as an offset,+ * - a garment that cannot bind is refused rather than attached mangled,+ * - skin under a garment is culled and the cull is reversible.+ */++import { describe, it, expect } from 'vitest';+import {+ Bone,+ BufferGeometry,+ Float32BufferAttribute,+ Group,+ Matrix4,+ MeshStandardMaterial,+ Skeleton,+ SkinnedMesh,+ Uint16BufferAttribute,+ Vector3,+} from 'three';+import {+ MIN_BIND_COVERAGE,+ attachGarment,+ bindCoverage,+ buildBoneRemap,+ cullSkinByBones,+ detachSlot,+ findAvatarSkeleton,+ occupiedSlots,+ reindexBoneInverses,+ remapSkinAttributes,+ restoreSkin,+ supportsWardrobe,+} from '../src/avatar-garment.js';++/* ── helpers ─────────────────────────────────────────────────────────────── */++/**+ * A minimal humanoid chain: Hips → Spine → Head, plus LeftArm off the spine.+ * `names` lets a caller rename every joint to test foreign conventions, and+ * `spineY` moves the rest pose so divergent-bind-pose cases are expressible.+ */+function buildRig({ prefix = '', spineY = 2, extraBones = [] } = {}) {+ const mk = (n) => { const b = new Bone(); b.name = prefix + n; return b; };+ const hips = mk('Hips');+ const spine = mk('Spine');+ const head = mk('Head');+ const leftArm = mk('LeftArm');++ spine.position.set(0, spineY, 0);+ head.position.set(0, 1, 0);+ leftArm.position.set(0.5, 0.5, 0);++ hips.add(spine);+ spine.add(head);+ spine.add(leftArm);++ const bones = [hips, spine, head, leftArm];+ for (const { name, parent, position } of extraBones) {+ const b = mk(name);+ b.position.copy(position || new Vector3(0, 0.1, 0));+ (bones.find((x) => x.name === prefix + parent) || spine).add(b);+ bones.push(b);+ }++ hips.updateMatrixWorld(true);+ return { bones, hips, spine, head, leftArm, skeleton: new Skeleton(bones) };+}++/** One-vertex-per-entry skinned mesh, each vertex fully weighted to one bone. */+function buildSkinnedMesh(skeleton, verts) {+ const geometry = new BufferGeometry();+ const positions = [];+ const skinIndices = [];+ const skinWeights = [];+ for (const { pos, bone, weights } of verts) {+ positions.push(pos.x, pos.y, pos.z);+ if (weights) {+ skinIndices.push(...weights.map((w) => w[0]), ...Array(4 - weights.length).fill(0));+ skinWeights.push(...weights.map((w) => w[1]), ...Array(4 - weights.length).fill(0));+ } else {+ skinIndices.push(bone, 0, 0, 0);+ skinWeights.push(1, 0, 0, 0);+ }+ }+ geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));+ geometry.setAttribute('skinIndex', new Uint16BufferAttribute(skinIndices, 4));+ geometry.setAttribute('skinWeight', new Float32BufferAttribute(skinWeights, 4));++ const mesh = new SkinnedMesh(geometry, new MeshStandardMaterial());+ mesh.add(skeleton.bones[0]);+ mesh.bind(skeleton);+ mesh.updateMatrixWorld(true);+ return mesh;+}++function buildAvatar({ spineY = 2, prefix = '' } = {}) {+ const rig = buildRig({ prefix, spineY });+ const mesh = buildSkinnedMesh(rig.skeleton, [+ { pos: new Vector3(0, spineY + 0.5, 0), bone: 1 }, // torso vertex on Spine+ { pos: new Vector3(0, spineY + 1.0, 0), bone: 2 }, // head vertex+ ]);+ const root = new Group();+ root.add(mesh);+ root.updateMatrixWorld(true);+ return { root, mesh, ...rig };+}++/* ── bone remapping ──────────────────────────────────────────────────────── */++describe('buildBoneRemap', () => {+ it('maps identically-named skeletons one-to-one', () => {+ const avatar = buildRig();+ const garment = buildRig();+ const { remap, unresolved } = buildBoneRemap(garment.skeleton, avatar.skeleton);+ expect([...remap]).toEqual([0, 1, 2, 3]);+ expect(unresolved).toEqual([]);+ });++ it('resolves a mixamo-prefixed garment onto a plain avatar', () => {+ const avatar = buildRig();+ const garment = buildRig({ prefix: 'mixamorig:' });+ const { remap, unresolved } = buildBoneRemap(garment.skeleton, avatar.skeleton);+ expect([...remap]).toEqual([0, 1, 2, 3]);+ expect(unresolved).toEqual([]);+ });++ it('falls back to the nearest mapped ancestor for helper joints', () => {+ const avatar = buildRig();+ const garment = buildRig({+ extraBones: [{ name: 'SpineTwist_A', parent: 'Spine' }],+ });+ const { remap, unresolved } = buildBoneRemap(garment.skeleton, avatar.skeleton);+ // The twist joint is unknown to the avatar, so it rides Spine (index 1).+ expect(remap[4]).toBe(1);+ expect(unresolved).toEqual([]);+ });++ it('reports a bone with no mapped ancestor as unresolved', () => {+ const avatar = buildRig();+ const garment = buildRig();+ // An orphan bone parented outside the chain resolves to nothing.+ const orphan = new Bone();+ orphan.name = 'PropHandle';+ const skeleton = new Skeleton([...garment.bones, orphan]);+ const { remap, unresolved } = buildBoneRemap(skeleton, avatar.skeleton);+ expect(remap[4]).toBe(-1);+ expect(unresolved).toEqual(['PropHandle']);+ });+});++describe('bindCoverage', () => {+ it('weights coverage by influence, not by bone count', () => {+ const avatar = buildRig();+ const garment = buildRig();+ const skeleton = new Skeleton([...garment.bones, Object.assign(new Bone(), { name: 'X' })]);+ // One vertex: 90% on Spine (maps), 10% on the orphan (does not).+ const mesh = buildSkinnedMesh(skeleton, [+ { pos: new Vector3(0, 2, 0), weights: [[1, 0.9], [4, 0.1]] },+ ]);+ const { remap } = buildBoneRemap(skeleton, avatar.skeleton);+ expect(bindCoverage(mesh.geometry, remap)).toBeCloseTo(0.9, 5);+ });+});++describe('remapSkinAttributes', () => {+ it('renormalises a vertex after an unresolved weight is dropped', () => {+ const avatar = buildRig();+ const garment = buildRig();+ const skeleton = new Skeleton([...garment.bones, Object.assign(new Bone(), { name: 'X' })]);+ const mesh = buildSkinnedMesh(skeleton, [+ { pos: new Vector3(0, 2, 0), weights: [[1, 0.5], [4, 0.5]] },+ ]);+ const { remap } = buildBoneRemap(skeleton, avatar.skeleton);+ remapSkinAttributes(mesh.geometry, remap);++ const w = mesh.geometry.attributes.skinWeight;+ expect(w.getComponent(0, 0)).toBeCloseTo(1, 5); // surviving weight scaled to 1+ expect(w.getComponent(0, 1)).toBe(0);+ });+});++describe('reindexBoneInverses', () => {+ it("keeps the garment's own inverse for bones it referenced", () => {+ const avatar = buildRig({ spineY: 3 });+ const garment = buildRig({ spineY: 2 });+ const { remap } = buildBoneRemap(garment.skeleton, avatar.skeleton);+ const out = reindexBoneInverses(garment.skeleton, avatar.skeleton, remap);+ // Avatar Spine sits at y=3, garment Spine at y=2; the reindexed inverse+ // must be the garment's (translate -2), not the avatar's (translate -3).+ expect(out[1].elements[13]).toBeCloseTo(-2, 5);+ });+});++/* ── attach ──────────────────────────────────────────────────────────────── */++describe('attachGarment', () => {+ it('binds a foreign-named garment so it deforms with the avatar', () => {+ const avatar = buildAvatar({ spineY: 2 });+ const garment = buildRig({ prefix: 'mixamorig:', spineY: 2 });+ const garmentMesh = buildSkinnedMesh(garment.skeleton, [+ { pos: new Vector3(0, 2.5, 0), bone: 1 }, // shirt vertex over the spine+ ]);+ const garmentRoot = new Group();+ garmentRoot.add(garmentMesh);+ garmentRoot.updateMatrixWorld(true);++ const res = attachGarment(avatar.root, garmentRoot, { slot: 'top' });+ expect(res.ok).toBe(true);+ expect(res.coverage).toBeCloseTo(1, 5);++ // Rotate the avatar's spine; body and garment must land together.+ avatar.spine.rotation.z = Math.PI / 4;+ avatar.root.updateMatrixWorld(true);+ res.meshes[0].skeleton.update();+ avatar.mesh.skeleton.update();++ const bodyPoint = avatar.mesh.applyBoneTransform(0, new Vector3().fromBufferAttribute(+ avatar.mesh.geometry.attributes.position, 0));+ const garmentPoint = res.meshes[0].applyBoneTransform(0, new Vector3().fromBufferAttribute(+ res.meshes[0].geometry.attributes.position, 0));++ expect(garmentPoint.x).toBeCloseTo(bodyPoint.x, 5);+ expect(garmentPoint.y).toBeCloseTo(bodyPoint.y, 5);+ expect(garmentPoint.z).toBeCloseTo(bodyPoint.z, 5);+ });++ it('reconciles a divergent rest pose instead of baking in an offset', () => {+ // Garment authored on a rig whose spine sits at y=2; avatar's is at y=3.+ // The vertex sat 0.5 above its own spine and must still sit 0.5 above the+ // avatar's, i.e. y=3.5 — not y=2.5 (offset ignored) and not y=4.5 (double).+ const avatar = buildAvatar({ spineY: 3 });+ const garment = buildRig({ spineY: 2 });+ const garmentMesh = buildSkinnedMesh(garment.skeleton, [+ { pos: new Vector3(0, 2.5, 0), bone: 1 },+ ]);+ const garmentRoot = new Group();+ garmentRoot.add(garmentMesh);+ garmentRoot.updateMatrixWorld(true);++ const res = attachGarment(avatar.root, garmentRoot, { slot: 'top' });+ expect(res.ok).toBe(true);++ avatar.root.updateMatrixWorld(true);+ res.meshes[0].skeleton.update();+ const p = res.meshes[0].applyBoneTransform(0, new Vector3().fromBufferAttribute(+ res.meshes[0].geometry.attributes.position, 0));+ expect(p.y).toBeCloseTo(3.5, 5);+ });++ it('refuses a garment whose skin cannot reach the avatar skeleton', () => {+ const avatar = buildAvatar();+ const alien = new Skeleton([+ Object.assign(new Bone(), { name: 'tentacle_root' }),+ Object.assign(new Bone(), { name: 'tentacle_tip' }),+ ]);+ const garmentMesh = buildSkinnedMesh(alien, [+ { pos: new Vector3(0, 1, 0), bone: 0 },+ ]);+ const garmentRoot = new Group();+ garmentRoot.add(garmentMesh);++ const res = attachGarment(avatar.root, garmentRoot, { slot: 'top' });+ expect(res.ok).toBe(false);+ expect(res.coverage).toBeLessThan(MIN_BIND_COVERAGE);+ expect(res.reason).toMatch(/binds only/);+ // Nothing was left behind in the scene.+ expect(occupiedSlots(avatar.root)).toEqual([]);+ });++ it('tracks slot occupancy and detaches cleanly', () => {+ const avatar = buildAvatar();+ const garment = buildRig();+ const garmentRoot = new Group();+ garmentRoot.add(buildSkinnedMesh(garment.skeleton, [+ { pos: new Vector3(0, 2.5, 0), bone: 1 },+ ]));++ const res = attachGarment(avatar.root, garmentRoot, { slot: 'top' });+ expect(res.ok).toBe(true);+ expect(occupiedSlots(avatar.root)).toEqual(['top']);++ expect(detachSlot(avatar.root, 'top')).toBe(1);+ expect(occupiedSlots(avatar.root)).toEqual([]);+ });++ it('rejects an avatar with no skinned mesh', () => {+ const res = attachGarment(new Group(), new Group(), { slot: 'top' });+ expect(res.ok).toBe(false);+ expect(res.reason).toMatch(/no skinned mesh/);+ });+});++/* ── occlusion ───────────────────────────────────────────────────────────── */++describe('cullSkinByBones', () => {+ it('drops triangles fully covered by the garment and restores them', () => {+ const rig = buildRig();+ const mesh = buildSkinnedMesh(rig.skeleton, [+ { pos: new Vector3(0, 2, 0), bone: 1 }, // spine+ { pos: new Vector3(1, 2, 0), bone: 1 }, // spine+ { pos: new Vector3(0, 3, 0), bone: 1 }, // spine → triangle 0 covered+ { pos: new Vector3(0, 3, 1), bone: 2 }, // head → triangle 1 survives+ ]);+ mesh.geometry.setIndex([0, 1, 2, 0, 1, 3]);++ const dropped = cullSkinByBones(mesh.geometry, new Set([1]), 0.5);+ expect(dropped).toBe(1);+ expect(mesh.geometry.getIndex().count).toBe(3);++ expect(restoreSkin(mesh.geometry)).toBe(true);+ expect(mesh.geometry.getIndex().count).toBe(6);+ });+});++/* ── gating ──────────────────────────────────────────────────────────────── */++describe('supportsWardrobe', () => {+ it('accepts a humanoid rig', () => {+ expect(supportsWardrobe(buildAvatar().root)).toBe(true);+ });++ it('accepts a foreign-named humanoid rig', () => {+ expect(supportsWardrobe(buildAvatar({ prefix: 'mixamorig:' }).root)).toBe(true);+ });++ it('rejects a non-humanoid prop', () => {+ const bone = Object.assign(new Bone(), { name: 'root' });+ const skeleton = new Skeleton([bone]);+ const mesh = buildSkinnedMesh(skeleton, [{ pos: new Vector3(0, 0, 0), bone: 0 }]);+ const root = new Group();+ root.add(mesh);+ expect(supportsWardrobe(root)).toBe(false);+ });+});++describe('findAvatarSkeleton', () => {+ it('picks the skeleton driving the most vertices, not the first found', () => {+ const root = new Group();+ const prop = buildRig({ prefix: 'prop_' });+ root.add(buildSkinnedMesh(prop.skeleton, [{ pos: new Vector3(0, 0, 0), bone: 0 }]));+ const body = buildRig();+ const bodyMesh = buildSkinnedMesh(body.skeleton, Array.from({ length: 10 }, () => (+ { pos: new Vector3(0, 2, 0), bone: 1 }+ )));+ root.add(bodyMesh);++ expect(findAvatarSkeleton(root).mesh).toBe(bodyMesh);+ });+});diff --git a/tests/fingerspelling.test.js b/tests/fingerspelling.test.jsindex cc0953ca9..83c8bba6b 100644--- a/tests/fingerspelling.test.js+++ b/tests/fingerspelling.test.js@@ -7,6 +7,19 @@ import {handshapeLocals,normalizeWord,} from '../src/fingerspelling.js';+import { ANCHORS, Pose } from '../src/sign-rig.js';++/** Replay a compiled clip's own tracks into a pose, for forward kinematics. */+function poseAtTime(clip, time) {+ const pose = new Pose();+ for (const track of clip.tracks) {+ if (track.type !== 'quaternion') continue;+ let i = 0;+ while (i + 1 < track.times.length && track.times[i + 1] <= time) i++;+ pose.setLocal(track.name.split('.')[0], track.values.slice(i * 4, i * 4 + 4));+ }+ return pose;+}const FINGER_BONES = ['Thumb', 'Index', 'Middle', 'Ring', 'Pinky'].flatMap((f) =>[1, 2, 3].map((j) => `RightHand${f}${j}`),@@ -97,10 +110,15 @@ describe('buildFingerspellingClip', () => {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']) {+ for (const bone of ['RightArm', 'RightForeArm', 'RightHand', 'LeftArm', 'LeftForeArm', 'Spine', 'Neck']) {expect(names).toContain(`${bone}.quaternion`);}- expect(names).toContain('Hips.position');+ // Signing is upper-body: it must not drive the root at all. A Hips+ // translation track authored around the origin sank the whole avatar+ // through the floor on any rig whose hips rest a metre up.+ expect(names).not.toContain('Hips.position');+ expect(names).not.toContain('Hips.quaternion');+ expect(names.every((n) => n.endsWith('.quaternion'))).toBe(true);});it('tracks have ascending times, matching lengths, and unit quaternions', () => {@@ -138,13 +156,19 @@ describe('buildFingerspellingClip', () => {expect(unique.size).toBeGreaterThanOrEqual(3);});- it('static letters hold the wrist steady during the hold', () => {+ it('static letters hold the wrist steady through the hold', () => {+ const t = DEFAULT_TIMING;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));+ const hand = clip.tracks.find((t2) => t2.name === 'RightHand.quaternion');+ // The letter is reached after lead + transition and held from there.+ const holdStart = t.leadSeconds + t.transitionSeconds - 1e-6;+ const holdEnd = t.leadSeconds + t.transitionSeconds + t.holdSeconds + 1e-6;+ const inHold = hand.times+ .map((time, i) => ({ time, q: hand.values.slice(i * 4, i * 4 + 4) }))+ .filter((k) => k.time >= holdStart && k.time <= holdEnd);+ expect(inHold.length).toBeGreaterThanOrEqual(2);+ const first = inHold[0].q.map((v) => v.toFixed(6)).join(',');+ for (const k of inHold) expect(k.q.map((v) => v.toFixed(6)).join(',')).toBe(first);});it('duration follows the timing model', () => {@@ -154,6 +178,41 @@ describe('buildFingerspellingClip', () => {expect(clip.duration).toBeCloseTo(expected, 6);});+ it('the hand ends up in front of the body, at signing height', () => {+ // Guards the arm regression end-to-end: sample the compiled clip's own+ // tracks back through forward kinematics and check where the hand is.+ const clip = buildFingerspellingClip('a');+ const pose = poseAtTime(clip, DEFAULT_TIMING.leadSeconds + DEFAULT_TIMING.transitionSeconds + 0.2);+ const wrist = pose.worldPos('RightHand');+ expect(wrist[2]).toBeGreaterThan(0.1); // in front of the chest+ expect(wrist[0]).toBeLessThan(0); // on the signing (right) side+ expect(wrist[1]).toBeGreaterThan(ANCHORS.sternum[1]); // up at jaw height+ expect(wrist[1]).toBeLessThan(ANCHORS.forehead[1]);+ // Elbow hangs; it is never lifted behind or above the shoulder.+ const elbow = pose.worldPos('RightForeArm');+ expect(elbow[1]).toBeLessThan(pose.worldPos('RightArm')[1]);+ expect(elbow[2]).toBeGreaterThan(-0.05);+ });++ it('rests both arms down at the start and end of a word', () => {+ const clip = buildFingerspellingClip('hi');+ for (const t of [0, clip.duration]) {+ const pose = poseAtTime(clip, t);+ for (const side of ['Left', 'Right']) {+ const wrist = pose.worldPos(`${side}Hand`);+ expect(wrist[1], `${side}@${t}`).toBeLessThan(ANCHORS.belly[1]);+ }+ }+ });++ it('never leaves the non-dominant arm crossing the body', () => {+ const clip = buildFingerspellingClip('xyz');+ for (let t = 0; t <= clip.duration; t += 0.1) {+ const left = poseAtTime(clip, t).worldPos('LeftHand');+ expect(left[0], `t=${t.toFixed(2)}`).toBeGreaterThan(0);+ }+ });+it('rejects unspellable input', () => {expect(() => buildFingerspellingClip('...')).toThrow();expect(() => buildFingerspellingClip('')).toThrow();diff --git a/tests/garment-catalog.test.js b/tests/garment-catalog.test.jsnew file mode 100644index 000000000..e36975ed3--- /dev/null+++ b/tests/garment-catalog.test.js@@ -0,0 +1,145 @@+/**+ * Garment catalog — validation and loading, per specs/GARMENT_MANIFEST.md.+ *+ * The catalog is the trust boundary between generated/authored assets and a+ * user's avatar: everything that renders as a wardrobe tile passed through+ * validateManifest. These tests pin the rejection rules — especially the ones+ * that protect users (licence gate, hash shape, unknown regions) — and the+ * cache semantics of loadCatalog.+ */++import { describe, it, expect } from 'vitest';+import {+ GARMENT_SPEC_URI,+ bySlot,+ loadCatalog,+ sanitizeCatalog,+ validateManifest,+ verifyModelBytes,+} from '../src/garment-catalog.js';++function validManifest(overrides = {}) {+ return {+ spec: GARMENT_SPEC_URI,+ id: 'oxford-shirt-white',+ name: 'Oxford Shirt',+ slot: 'top',+ version: 1,+ model: {+ uri: 'https://storage.googleapis.com/three-ws-garments/garments/top/oxford-shirt-white/v1/garment.glb',+ format: 'gltf-binary',+ sha256: 'a'.repeat(64),+ },+ rig: { skeleton: 'three.ws-canonical-v1' },+ occludes: ['torso', 'upperArms'],+ license: 'CC0-1.0',+ ...overrides,+ };+}++describe('validateManifest', () => {+ it('accepts a spec-complete manifest', () => {+ expect(validateManifest(validManifest())).toEqual({ ok: true, errors: [] });+ });++ it('accepts empty occludes (glasses, earrings)', () => {+ expect(validateManifest(validManifest({ occludes: [] })).ok).toBe(true);+ });++ it.each([+ ['unknown spec', { spec: 'https://three.ws/specs/garment-manifest-v2' }, /unknown spec/],+ ['non-kebab id', { id: 'Oxford_Shirt' }, /kebab-case/],+ ['unknown slot', { slot: 'cape' }, /unknown slot/],+ ['http model uri', { model: { uri: 'http://x.test/g.glb', format: 'gltf-binary', sha256: 'a'.repeat(64) } }, /protocol/],+ ['bad hash', { model: { uri: 'https://x.test/g.glb', format: 'gltf-binary', sha256: 'zz' } }, /sha256/],+ ['foreign skeleton', { rig: { skeleton: 'mixamo-v1' } }, /rig\.skeleton/],+ ['unknown region', { occludes: ['tail'] }, /unknown body region/],+ ['no licence', { license: undefined }, /licence/],+ ['non-commercial licence', { license: 'CC-BY-NC-4.0' }, /licence/],+ ])('rejects %s', (_label, overrides, msg) => {+ const { ok, errors } = validateManifest(validManifest(overrides));+ expect(ok).toBe(false);+ expect(errors.join(' | ')).toMatch(msg);+ });+});++describe('sanitizeCatalog', () => {+ it('keeps valid entries, drops and reports broken ones', () => {+ const { garments, rejected } = sanitizeCatalog([+ validManifest(),+ validManifest({ id: 'denim-jacket', slot: 'outerwear' }),+ validManifest({ id: 'bad-hash', model: { uri: 'https://x.test/g.glb', format: 'gltf-binary', sha256: 'nope' } }),+ ]);+ expect(garments.map((g) => g.id)).toEqual(['oxford-shirt-white', 'denim-jacket']);+ expect(rejected).toHaveLength(1);+ expect(rejected[0].id).toBe('bad-hash');+ });++ it('rejects a duplicate id within a slot', () => {+ const { garments, rejected } = sanitizeCatalog([validManifest(), validManifest()]);+ expect(garments).toHaveLength(1);+ expect(rejected[0].errors.join()).toMatch(/duplicate/);+ });++ it('tolerates a non-array payload', () => {+ expect(sanitizeCatalog({ oops: true })).toEqual({ garments: [], rejected: [] });+ });+});++describe('bySlot', () => {+ it('groups by slot preserving order', () => {+ const grouped = bySlot([+ validManifest(),+ validManifest({ id: 'tee-black' }),+ validManifest({ id: 'denim-jacket', slot: 'outerwear' }),+ ]);+ expect(grouped.get('top').map((g) => g.id)).toEqual(['oxford-shirt-white', 'tee-black']);+ expect(grouped.get('outerwear')).toHaveLength(1);+ });+});++describe('loadCatalog', () => {+ const okFetch = (payload) => async () => ({ ok: true, json: async () => payload });++ it('fetches, validates, and caches per session', async () => {+ let calls = 0;+ const fetchImpl = async () => { calls++; return { ok: true, json: async () => [validManifest()] }; };+ const a = await loadCatalog({ force: true, url: 'https://t.test/c.json', fetchImpl });+ const b = await loadCatalog({ url: 'https://t.test/c.json', fetchImpl });+ expect(a.garments).toHaveLength(1);+ expect(b).toBe(a);+ expect(calls).toBe(1);+ });++ it('force refetches', async () => {+ let calls = 0;+ const fetchImpl = async () => { calls++; return { ok: true, json: async () => [] }; };+ await loadCatalog({ force: true, url: 'https://t.test/c.json', fetchImpl });+ await loadCatalog({ force: true, url: 'https://t.test/c.json', fetchImpl });+ expect(calls).toBe(2);+ });++ it('does not cache a failed fetch', async () => {+ let calls = 0;+ const failing = async () => { calls++; throw new Error('offline'); };+ await expect(loadCatalog({ force: true, url: 'https://t.test/c.json', fetchImpl: failing }))+ .rejects.toThrow('offline');+ const ok = await loadCatalog({ url: 'https://t.test/c.json', fetchImpl: okFetch([validManifest()]) });+ expect(ok.garments).toHaveLength(1);+ expect(calls).toBe(1);+ });+});++describe('verifyModelBytes', () => {+ it('accepts matching bytes and rejects tampered ones', async () => {+ const bytes = new TextEncoder().encode('glTF-bytes').buffer;+ const digest = await crypto.subtle.digest('SHA-256', bytes);+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');++ const manifest = validManifest({ model: { uri: 'https://x.test/g.glb', format: 'gltf-binary', sha256: hex } });+ expect(await verifyModelBytes(bytes, manifest)).toBe(true);++ const tampered = new TextEncoder().encode('glTF-bytes!').buffer;+ expect(await verifyModelBytes(tampered, manifest)).toBe(false);+ });+});diff --git a/tests/sign-dictionary.test.js b/tests/sign-dictionary.test.jsnew file mode 100644index 000000000..4c9990a93--- /dev/null+++ b/tests/sign-dictionary.test.js@@ -0,0 +1,214 @@+/**+ * Lexical sign dictionary — unit tests.+ *+ * Signs are authored as places in signing space, so they can be checked the same+ * way a signer would check them: replay the compiled clip through forward+ * kinematics and assert where the hands actually are. Model space is +Z forward+ * (the way the avatar faces), +Y up, −X the right side of the body.+ */++import { describe, expect, it } from 'vitest';++import {+ SIGNABLE_WORDS,+ SIGNS,+ buildSignClip,+ lookupSign,+ signGloss,+ signLookup,+} from '../src/sign-dictionary.js';+import { ANCHORS, Pose } from '../src/sign-rig.js';+import { compileUtterance } from '../src/sign-speech.js';++function poseAtTime(clip, time) {+ const pose = new Pose();+ for (const track of clip.tracks) {+ if (track.type !== 'quaternion') continue;+ let i = 0;+ while (i + 1 < track.times.length && track.times[i + 1] <= time) i++;+ pose.setLocal(track.name.split('.')[0], track.values.slice(i * 4, i * 4 + 4));+ }+ return pose;+}++/** The pose while the sign's final phase is held, before it settles. */+function peakPose(clip) {+ return poseAtTime(clip, clip.duration - 0.4);+}++const WORDS = Object.keys(SIGNS);++describe('vocabulary', () => {+ it('every sign has a plain-language gloss', () => {+ for (const word of WORDS) {+ expect(SIGNS[word].gloss, word).toBeTruthy();+ expect(signGloss(word), word).toBe(SIGNS[word].gloss);+ }+ });++ it('resolves aliases to real signs', () => {+ expect(lookupSign('hi').name).toBe('HELLO');+ expect(lookupSign('THANKS').name).toBe('THANK');+ expect(lookupSign('everyone').name).toBe('YALL');+ expect(lookupSign('zzzz')).toBeNull();+ });++ it('lists every signable word, aliases included', () => {+ expect(SIGNABLE_WORDS).toContain('HAPPY');+ expect(SIGNABLE_WORDS).toContain('HI');+ expect(SIGNABLE_WORDS.length).toBeGreaterThan(WORDS.length);+ for (const word of SIGNABLE_WORDS) expect(lookupSign(word), word).toBeTruthy();+ });+});++describe('compiled clips', () => {+ it('every sign compiles to a valid, monotonic, unit-quaternion clip', () => {+ for (const word of WORDS) {+ const clip = buildSignClip(word);+ expect(clip, word).toBeTruthy();+ expect(clip.duration, word).toBeGreaterThan(0.5);+ for (const track of clip.tracks) {+ expect(track.type, `${word}:${track.name}`).toBe('quaternion');+ expect(track.values.length).toBe(track.times.length * 4);+ for (let i = 1; i < track.times.length; i++) {+ expect(track.times[i], `${word}:${track.name}`).toBeGreaterThan(track.times[i - 1]);+ }+ for (let i = 0; i < track.values.length; i += 4) {+ expect(Math.hypot(...track.values.slice(i, i + 4))).toBeCloseTo(1, 6);+ }+ }+ }+ });++ it('never drives the root, so the avatar cannot sink through the floor', () => {+ for (const word of WORDS) {+ const names = buildSignClip(word).tracks.map((t) => t.name);+ expect(names.some((n) => n.startsWith('Hips')), word).toBe(false);+ expect(names.every((n) => n.endsWith('.quaternion')), word).toBe(true);+ }+ });++ it('is deterministic', () => {+ expect(buildSignClip('HAPPY')).toEqual(buildSignClip('HAPPY'));+ });++ it('returns null for a word with no sign', () => {+ expect(buildSignClip('QWERTY')).toBeNull();+ });++ it('rate scales the tempo without changing the shape', () => {+ const normal = buildSignClip('HELLO');+ const fast = buildSignClip('HELLO', { rate: 2 });+ expect(fast.duration).toBeLessThan(normal.duration);+ expect(fast.tracks.length).toBe(normal.tracks.length);+ });+});++describe('where the hands actually go', () => {+ it('keeps every hand in front of the body for the whole sign', () => {+ for (const word of WORDS) {+ const clip = buildSignClip(word);+ for (let t = 0.35; t < clip.duration - 0.35; t += 0.12) {+ const pose = poseAtTime(clip, t);+ for (const side of ['Left', 'Right']) {+ const hand = pose.worldPos(`${side}Hand`);+ // −0.05 allows a hand resting beside the hip; the failure this+ // guards is a hand swung round BEHIND the torso.+ expect(hand[2], `${word} ${side} @${t.toFixed(2)}`).toBeGreaterThan(-0.06);+ }+ }+ }+ });++ it('never lifts an elbow above its own shoulder', () => {+ for (const word of WORDS) {+ const clip = buildSignClip(word);+ for (let t = 0; t <= clip.duration; t += 0.15) {+ const pose = poseAtTime(clip, t);+ for (const side of ['Left', 'Right']) {+ const elbow = pose.worldPos(`${side}ForeArm`)[1];+ const shoulder = pose.worldPos(`${side}Arm`)[1];+ expect(elbow, `${word} ${side} @${t.toFixed(2)}`).toBeLessThan(shoulder + 0.02);+ }+ }+ }+ });++ it('starts and ends every sign with the arms at rest', () => {+ for (const word of WORDS) {+ const clip = buildSignClip(word);+ for (const t of [0, clip.duration]) {+ const pose = poseAtTime(clip, t);+ for (const side of ['Left', 'Right']) {+ expect(pose.worldPos(`${side}Hand`)[1], `${word} ${side}`).toBeLessThan(ANCHORS.belly[1]);+ }+ }+ }+ });++ it('signs the two-handed ones with BOTH hands, symmetrically', () => {+ for (const word of ['HAPPY', 'WANT', 'MORE', 'MEET', 'WHAT', 'FINISH']) {+ const pose = peakPose(buildSignClip(word));+ const r = pose.worldPos('RightHand');+ const l = pose.worldPos('LeftHand');+ expect(r[1], `${word} right`).toBeGreaterThan(ANCHORS.belly[1]);+ expect(l[1], `${word} left`).toBeGreaterThan(ANCHORS.belly[1]);+ expect(Math.abs(r[1] - l[1]), `${word} height`).toBeLessThan(0.05);+ expect(r[0]).toBeLessThan(0);+ expect(l[0]).toBeGreaterThan(0);+ }+ });++ it('places the signs that are defined by their location', () => {+ const at = (word) => peakPose(buildSignClip(word)).worldPos('RightHand');+ // KNOW and THINK are head signs; HAPPY and LOVE are chest signs.+ expect(at('KNOW')[1]).toBeGreaterThan(ANCHORS.chin[1]);+ expect(at('THINK')[1]).toBeGreaterThan(ANCHORS.chin[1]);+ expect(at('HAPPY')[1]).toBeLessThan(ANCHORS.chin[1]);+ expect(at('HAPPY')[1]).toBeGreaterThan(ANCHORS.belly[1]);+ // LOVE crosses the arms, so the right hand ends up on the LEFT of centre.+ expect(at('LOVE')[0]).toBeGreaterThan(0);+ });++ it('HAPPY brushes upward, the way the sign moves', () => {+ const clip = buildSignClip('HAPPY');+ const low = poseAtTime(clip, 0.62).worldPos('RightHand')[1];+ const high = poseAtTime(clip, 0.9).worldPos('RightHand')[1];+ expect(high).toBeGreaterThan(low);+ });++ it('YALL sweeps across the group', () => {+ const clip = buildSignClip('YALL');+ const start = poseAtTime(clip, 0.62).worldPos('RightHand')[0];+ const end = peakPose(clip).worldPos('RightHand')[0];+ expect(end).toBeLessThan(start - 0.15); // travels outward, to −X+ });++ it('FALL stands the legs on the palm, then tips them over', () => {+ const clip = buildSignClip('FALL');+ const standing = poseAtTime(clip, 0.7);+ const fallen = peakPose(clip);+ // Fingers point down while standing, then swing away from down.+ expect(standing.worldDir('RightHand')[1]).toBeLessThan(-0.6);+ expect(fallen.worldDir('RightHand')[1]).toBeGreaterThan(standing.worldDir('RightHand')[1] + 0.5);+ });+});++describe('signLookup', () => {+ it('feeds compileUtterance so known words sign and the rest spell', () => {+ const out = compileUtterance('hello brixton happy', { signs: signLookup() });+ expect(out.signed).toEqual(['HELLO', 'HAPPY']);+ expect(out.spelled).toEqual(['BRIXTON']);+ expect(out.clip.duration).toBeGreaterThan(0);+ for (const track of out.clip.tracks) {+ for (let i = 1; i < track.times.length; i++) {+ expect(track.times[i], track.name).toBeGreaterThan(track.times[i - 1]);+ }+ }+ });++ it('caches so a repeated word is compiled once', () => {+ const lookup = signLookup();+ expect(lookup('HAPPY')).toBe(lookup('HAPPY'));+ });+});diff --git a/tests/sign-rig.test.js b/tests/sign-rig.test.jsnew file mode 100644index 000000000..73258bdd6--- /dev/null+++ b/tests/sign-rig.test.js@@ -0,0 +1,197 @@+/**+ * Sign-rig kinematics — unit tests.+ *+ * These guard the bug that made the signing avatar unusable: the arm was posed+ * with rotations authored against a skeleton convention the reference rig does+ * not use, which swung the signing hand BEHIND the body. The fix was to solve+ * the arm against the rig's measured bind pose, so the assertions here are+ * about where the hand physically ends up, in model space:+ *+ * forward is +Z (the direction the avatar faces), up is +Y, and the right+ * side of the body is −X.+ */++import { describe, expect, it } from 'vitest';++import {+ ANCHORS,+ Pose,+ boneAxis,+ boneLength,+ orientQuat,+ palmAxis,+ qRotate,+ restPalmWorld,+ restRadialWorld,+ signPoint,+ solveArm,+ vDot,+ vLen,+ vNorm,+ vSub,+} from '../src/sign-rig.js';++const near = (a, b, tol = 1e-6) => Math.abs(a - b) <= tol;++describe('measured rig frames', () => {+ it('measures bone axes from the rig instead of assuming them', () => {+ // cz.glb (Avaturn/Mixamo convention) aims bones down local +Y. The point+ // is that this is READ, not hardcoded — so assert it matches the rig.+ for (const bone of ['RightArm', 'RightForeArm', 'LeftArm', 'RightHandIndex1']) {+ const axis = boneAxis(bone);+ expect(vLen(axis)).toBeCloseTo(1, 6);+ expect(axis[1]).toBeGreaterThan(0.9);+ }+ });++ it('finds each arm segment’s real length', () => {+ expect(boneLength('RightArm')).toBeGreaterThan(0.15);+ expect(boneLength('RightArm')).toBeCloseTo(boneLength('LeftArm'), 3);+ expect(boneLength('RightForeArm')).toBeCloseTo(boneLength('LeftForeArm'), 3);+ });++ it('derives palms-down, thumbs-forward hand frames on both hands', () => {+ for (const side of ['Left', 'Right']) {+ // Palm faces the floor at rest…+ expect(restPalmWorld(side)[1]).toBeLessThan(-0.9);+ // …and the thumb side of the hand points where the body faces.+ expect(restRadialWorld(side)[2]).toBeGreaterThan(0.9);+ }+ });++ it('places anatomical anchors where they belong on the body', () => {+ expect(ANCHORS.forehead[1]).toBeGreaterThan(ANCHORS.chin[1]);+ expect(ANCHORS.chin[1]).toBeGreaterThan(ANCHORS.sternum[1]);+ expect(ANCHORS.sternum[1]).toBeGreaterThan(ANCHORS.belly[1]);+ // The sternum is upper chest: above the shoulder line is wrong, mid-belly+ // is wrong; it sits between the chest bone and the neck.+ expect(ANCHORS.sternum[1]).toBeLessThan(ANCHORS.shoulder.Right[1]);+ expect(ANCHORS.sternum[1]).toBeGreaterThan(ANCHORS.belly[1] + 0.1);+ expect(ANCHORS.shoulder.Right[0]).toBeLessThan(0); // right side is −X+ expect(ANCHORS.shoulder.Left[0]).toBeGreaterThan(0);+ });++ it('offsets sign points outward per hand', () => {+ const right = signPoint('sternum', { out: 0.2, side: 'Right' });+ const left = signPoint('sternum', { out: 0.2, side: 'Left' });+ expect(right[0]).toBeCloseTo(-0.2, 6);+ expect(left[0]).toBeCloseTo(0.2, 6);+ });+});++describe('orientQuat', () => {+ it('carries the local frame exactly onto the world frame', () => {+ const q = orientQuat([0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0]);+ const axis = qRotate(q, [0, 1, 0]);+ expect(axis[0]).toBeCloseTo(1, 6);+ expect(near(vLen(axis), 1)).toBe(true);+ const ref = qRotate(q, [0, 0, 1]);+ expect(ref[1]).toBeCloseTo(1, 6);+ });++ it('still resolves when the reference is parallel to the axis', () => {+ const q = orientQuat([0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1]);+ expect(qRotate(q, [0, 1, 0])[2]).toBeCloseTo(1, 6);+ });+});++describe('solveArm', () => {+ const spellingTarget = signPoint('chin', { out: 0.24, up: -0.03, forward: 0.21, side: 'Right' });++ it('puts the wrist exactly on a reachable target', () => {+ const pose = new Pose();+ solveArm(pose, 'Right', { wrist: spellingTarget, fingers: [0, 1, 0], palm: [0, 0, 1] });+ expect(vLen(vSub(pose.worldPos('RightHand'), spellingTarget))).toBeLessThan(1e-3);+ });++ it('keeps the signing hand IN FRONT of the body, never behind it', () => {+ // The regression this whole module exists for: the old pose put the hand+ // at negative Z, i.e. behind the avatar's back.+ const pose = new Pose();+ solveArm(pose, 'Right', { wrist: spellingTarget, fingers: [0, 1, 0], palm: [0, 0, 1] });+ for (const bone of ['RightForeArm', 'RightHand', 'RightHandMiddle3']) {+ expect(pose.worldPos(bone)[2], bone).toBeGreaterThan(0);+ }+ });++ it('aims the fingers and palm where asked', () => {+ const pose = new Pose();+ solveArm(pose, 'Right', { wrist: spellingTarget, fingers: [0, 1, 0], palm: [0, 0, 1] });+ const fingers = pose.worldDir('RightHand');+ expect(fingers[1]).toBeGreaterThan(0.98); // straight up+ const palm = vNorm(qRotate(pose.worldQuat('RightHand'), palmAxis('RightHand')));+ expect(palm[2]).toBeGreaterThan(0.98); // toward the reader+ });++ it('drops the elbow below the wrist and outside the torso', () => {+ const pose = new Pose();+ solveArm(pose, 'Right', { wrist: spellingTarget, fingers: [0, 1, 0], palm: [0, 0, 1] });+ const elbow = pose.worldPos('RightForeArm');+ const wrist = pose.worldPos('RightHand');+ const shoulder = pose.worldPos('RightArm');+ expect(elbow[1]).toBeLessThan(wrist[1]);+ expect(elbow[1]).toBeLessThan(shoulder[1]);+ // Elbow stays on the signing side of the body, not tucked across it.+ expect(elbow[0]).toBeLessThan(0);+ });++ it('preserves the rig’s own bone lengths (no stretching to reach)', () => {+ const pose = new Pose();+ solveArm(pose, 'Right', { wrist: spellingTarget, fingers: [0, 1, 0], palm: [0, 0, 1] });+ const upper = vLen(vSub(pose.worldPos('RightForeArm'), pose.worldPos('RightArm')));+ const lower = vLen(vSub(pose.worldPos('RightHand'), pose.worldPos('RightForeArm')));+ expect(upper).toBeCloseTo(boneLength('RightArm'), 5);+ expect(lower).toBeCloseTo(boneLength('RightForeArm'), 5);+ });++ it('clamps an out-of-reach target instead of tearing the arm apart', () => {+ const pose = new Pose();+ const far = [-3, 1.5, 3];+ solveArm(pose, 'Right', { wrist: far, fingers: [0, 1, 0], palm: [0, 0, 1] });+ const reach = vLen(vSub(pose.worldPos('RightHand'), pose.worldPos('RightArm')));+ expect(reach).toBeLessThanOrEqual(boneLength('RightArm') + boneLength('RightForeArm'));+ // Still pointing AT the target, just short of it.+ const dir = vNorm(vSub(pose.worldPos('RightHand'), pose.worldPos('RightArm')));+ expect(vDot(dir, vNorm(vSub(far, pose.worldPos('RightArm'))))).toBeGreaterThan(0.99);+ });++ it('mirrors: the same body-relative target reaches the same place on either hand', () => {+ const rightTarget = signPoint('sternum', { out: 0.18, up: 0, forward: 0.25, side: 'Right' });+ const leftTarget = signPoint('sternum', { out: 0.18, up: 0, forward: 0.25, side: 'Left' });+ const pose = new Pose();+ solveArm(pose, 'Right', { wrist: rightTarget, fingers: [0, 1, 0], palm: [0, 0, 1] });+ solveArm(pose, 'Left', { wrist: leftTarget, fingers: [0, 1, 0], palm: [0, 0, 1] });+ const r = pose.worldPos('RightHand');+ const l = pose.worldPos('LeftHand');+ expect(r[0]).toBeCloseTo(-l[0], 3);+ expect(r[1]).toBeCloseTo(l[1], 3);+ expect(r[2]).toBeCloseTo(l[2], 3);+ });+});++describe('Pose', () => {+ it('round-trips a world rotation through the local it stores', () => {+ const pose = new Pose();+ const q = orientQuat(boneAxis('RightArm'), [1, 0, 0], [0, -1, 0], [0, 0, 1]);+ pose.setWorldQuat('RightArm', q);+ const back = pose.worldQuat('RightArm');+ for (let i = 0; i < 4; i++) expect(Math.abs(back[i])).toBeCloseTo(Math.abs(q[i]), 6);+ });++ it('moves child bones when a parent rotates (real forward kinematics)', () => {+ const pose = new Pose();+ const before = pose.worldPos('RightHand');+ pose.aim('RightArm', [0, 1, 0]);+ const after = pose.worldPos('RightHand');+ expect(vLen(vSub(before, after))).toBeGreaterThan(0.3);+ });++ it('clones without aliasing', () => {+ const a = new Pose();+ a.aim('RightArm', [0, 1, 0]);+ const b = a.clone();+ b.aim('RightArm', [0, -1, 0]);+ expect(a.worldDir('RightArm')[1]).toBeGreaterThan(0.9);+ expect(b.worldDir('RightArm')[1]).toBeLessThan(-0.9);+ });+});diff --git a/tests/sign-speech.test.js b/tests/sign-speech.test.jsindex f59d506a0..2c524d0cf 100644--- a/tests/sign-speech.test.js+++ b/tests/sign-speech.test.js@@ -77,11 +77,19 @@ describe('compileUtterance', () => {describe('estimateDuration', () => {it('tracks compiled duration closely for plain fingerspelling', () => {+ // `signed: false` matches compileUtterance with no dictionary — both spell+ // every word.const text = 'hello world';- const est = estimateDuration(text, CHAT_TIMING);+ const est = estimateDuration(text, CHAT_TIMING, { signed: false });const real = compileUtterance(text).clip.duration;expect(Math.abs(est - real)).toBeLessThan(1.0);});++ it('counts a dictionary word as one sign, not as its letters', () => {+ expect(estimateDuration('welcome', CHAT_TIMING)).toBeLessThan(+ estimateDuration('welcome', CHAT_TIMING, { signed: false }),+ );+ });});describe('SignSpeaker', () => {diff --git a/workers/avatar-reconstruction/eval/README.md b/workers/avatar-reconstruction/eval/README.mdnew file mode 100644index 000000000..ed925d86b--- /dev/null+++ b/workers/avatar-reconstruction/eval/README.md@@ -0,0 +1,116 @@+# Reconstruction fidelity evaluation++Measures whether a reconstructed avatar actually has **this person's face+shape**, so pipeline changes can be judged on a number instead of on whether a+screenshot looks nice.++The pipeline paints a selfie onto a template head. That flatters a visual check:+from the front, the render already looks like the person while the underlying+skull is still the template's. Turn the head 30 degrees and the illusion breaks.+The metric here ignores texture completely and scores geometry.++## The metric: Identity Shape Error (ISE)++For one (selfie, avatar GLB) pair:++1. MediaPipe detects the selfie's 468 face landmarks.+2. `face_uv_map.json` maps each landmark to a head vertex, so the same 468+ points can be read off the avatar's mesh.+3. Both point sets are Umeyama-aligned onto MediaPipe's neutral canonical face,+ using only the **stable identity landmarks** (face oval, nose, cheeks, brow,+ jaw). Eyes and lips are excluded so a smile or a blink in the selfie is not+ scored as identity.+4. **ISE** = mean distance between the aligned sets, over the stable subset,+ divided by canonical interocular distance.++Dimensionless and comparable across faces, image sizes and body types. **Lower+is better.** Because step 3 quotients out similarity transforms, a pipeline+cannot score better by scaling or tilting the head — only by matching shape.+`eval/test_identity_eval.py` pins that invariance, along with monotonicity+(interpolating a head toward the person must lower the score at every step).++Two numbers give it meaning:++- **template floor** — the same measurement against the unmorphed template. This+ is what a texture-only pipeline scores, and the number to beat.+- **improvement** — the fraction of that floor a run closes. The Phase-2 morph+ moves `strength` (default 0.75) of the way toward the person, so ~0.75 is the+ current implementation's ceiling, not 1.0.++A region breakdown (oval / nose / cheeks / brow / jaw) says *where* the shape is+wrong, which is what decides where the next fidelity push goes.++## Score one reconstruction++```bash+python -m eval.identity_eval --selfie refs/ana.jpg --glb out/ana.glb+```++```+ana.jpg → ana.glb+ ISE 0.0412 (lower is better)+ worst point 0.0980+ template floor 0.0733+ improvement +43.8%+ by region:+ jaw 0.0561+ oval 0.0487+ nose 0.0402+ cheeks 0.0331+ brow 0.0298+```++## Score a deployment++```bash+export RECON_KEY=$(gcloud secrets versions access latest \+ --secret=avatar-reconstruction-key --project=aerial-vehicle-466722-p5)++python -m eval.run_eval \+ --photos eval/refs \+ --url https://avatar-reconstruction-lp642k3kpa-uc.a.run.app \+ --out eval/reports/v2.json --keep-glb+```++Submits every photo in the directory, waits for each job, scores the result and+writes a report with per-sample and aggregate numbers.++## Compare two revisions++```bash+python -m eval.run_eval --compare eval/reports/v1.json eval/reports/v2.json+```++Prints the aggregate move, the per-region move, and — importantly — **every+individual face that got worse**. A change can improve the mean while wrecking a+subset of faces; the mean alone hides exactly the regression that matters. Exits+non-zero when the mean did not improve, so it works as a gate.++## The reference set++`--photos` is a directory of frontal selfies, one file per sample. Choose faces+that span what the pipeline must handle: skin tone, age, face shape, facial+hair, glasses, head covering, lighting, camera quality. A mean over a narrow set+hides the failures that matter most.++Reference photos are **not committed** — they are either real people's faces or+licensed stock, and neither belongs in git. Keep them in+`eval/refs/` (gitignored) and mirror the set to+`gs://three-ws-avatar-reconstructions/eval-refs/` so every agent and every CI run+scores against an identical set:++```bash+gsutil -m rsync -r gs://three-ws-avatar-reconstructions/eval-refs eval/refs+```++A score is only comparable to another score taken on the same reference set.+Record which set a report used before quoting its number.++## Running the tests++```bash+python -m pytest eval/test_identity_eval.py -q+```++Scoring is pure geometry, so the tests need only numpy — no mediapipe, no cv2,+no GPU. The detector is imported lazily, and only when a selfie is actually read.diff --git a/workers/avatar-reconstruction/eval/identity_eval.py b/workers/avatar-reconstruction/eval/identity_eval.pynew file mode 100644index 000000000..748a52151--- /dev/null+++ b/workers/avatar-reconstruction/eval/identity_eval.py@@ -0,0 +1,223 @@+"""+Identity Shape Error (ISE) — does the reconstructed avatar's face actually have+*this person's* shape?++The texture-transfer pipeline paints a selfie onto a template head, so a purely+visual check flatters it: the render looks like the person from the front while+the underlying skull is still the template's. ISE ignores texture entirely and+measures geometry, which is the quantity the Phase-2 morph moves.++Method+------+1. MediaPipe gives 468 landmarks for the selfie: the person's face shape, in+ image space with unknown pose and scale.+2. `face_uv_map.json` gives, for each of those 468 landmarks, the head vertex it+ corresponds to. Reading those vertices out of a GLB yields the *avatar's*+ version of the same 468 points.+3. Both point sets are Umeyama-aligned onto MediaPipe's neutral canonical face+ using only the stable identity landmarks (face oval, nose, cheeks, brow, jaw+ — no eyes or lips, so a smile or a blink cannot register as identity).+ Alignment removes pose and scale; what remains is shape.+4. ISE = mean euclidean distance between the two aligned sets over the stable+ subset, divided by canonical interocular distance.++Dimensionless, so it compares across faces, image sizes and body types. Lower is+better. Because step 3 quotients out similarity transforms, a pipeline cannot+score well by making the head bigger or tilting it — only by matching shape.++Reference points for reading a score:+ • the *template floor* — the same measurement against the unmorphed template+ head — is what a texture-only pipeline scores. It is the number to beat.+ • `improvement` is the fraction of that floor the morph closes. The Phase-2+ morph applies `strength` (default 0.75) toward the person's shape, so the+ theoretical ceiling for the current implementation is ~0.75.++Usage+-----+ python -m eval.identity_eval --selfie a.jpg --glb out.glb+ python -m eval.identity_eval --selfie a.jpg --glb out.glb --json++Runs on the worker's existing dependencies (mediapipe, pygltflib, numpy) — no+GPU and no render, so it is cheap enough to gate every pipeline change.+"""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++import numpy as np+from PIL import Image++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++import face_geometry # noqa: E402+import glb_ops # noqa: E402++# `face_pipeline` drags in mediapipe, cv2 and rembg. Scoring is pure geometry and+# needs none of that, so the detector is imported only when a selfie is actually+# read — the metric stays runnable (and testable) outside the GPU image.++# MediaPipe outer eye corners — the interocular span that normalises the score.+_EYE_L, _EYE_R = 33, 263++# Landmark groups, so a score can say *where* the shape is wrong. These are the+# same anatomical bands `face_geometry._STABLE_IDENTITY_INDICES` is built from;+# a region-level breakdown is what tells us whether the next fidelity push+# belongs in the nose, the jaw or the silhouette.+_REGIONS = {+ "oval": [+ 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,+ 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,+ 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,+ ],+ "nose": [6, 197, 195, 5, 4, 1, 19, 94, 2, 98, 327, 129, 358],+ "cheeks": [50, 280, 116, 345, 117, 346, 118, 347, 205, 425],+ "brow": [107, 336, 66, 296, 105, 334, 63, 293],+ "jaw": [32, 262, 211, 431, 170, 395, 208, 428],+}+++class EvalError(RuntimeError):+ """Raised when a sample cannot be scored (no face, no geometry map, …)."""+++def _align_to_canonical(points: np.ndarray, canonical: np.ndarray, stable: np.ndarray) -> np.ndarray:+ """Similarity-align `points` onto the canonical face using the stable subset."""+ s, R, t = face_geometry.umeyama(points[stable], canonical[stable])+ return (s * (R @ points.T)).T + t+++def selfie_landmarks(image_path: Path) -> np.ndarray:+ """Detect the 468 face landmarks for a selfie, as an (N,3) array."""+ import face_pipeline++ img = Image.open(image_path).convert("RGB")+ landmarks = face_pipeline._get_landmarks(img)+ if landmarks is None:+ landmarks = face_pipeline._get_landmarks_small_face(img)+ if landmarks is None:+ raise EvalError(f"no face detected in {image_path.name}")+ return face_geometry.landmarks_to_array(landmarks)+++def head_landmark_points(glb_path: Path, face_map: face_geometry.FaceMap) -> np.ndarray:+ """Read the avatar's own version of the 468 landmark points out of a GLB."""+ glb = glb_ops.load_glb(glb_path.read_bytes())+ positions, _, _ = glb_ops.get_head_mesh_data(glb)+ idx = face_map.landmark_vtx+ if idx.max() >= positions.shape[0]:+ raise EvalError(+ f"{glb_path.name}: landmark map indexes vertex {int(idx.max())} but the head "+ f"has only {positions.shape[0]} — the GLB is not the template this map was built for"+ )+ return positions[idx].astype(np.float64)+++def score(+ selfie_pts: np.ndarray,+ head_pts: np.ndarray,+ face_map: face_geometry.FaceMap,+) -> dict:+ """+ Compute ISE between a person's landmarks and an avatar head's landmark+ vertices. Both are aligned onto the canonical face first, so the result+ depends on shape alone.+ """+ canon = face_map.canonical_norm+ stable = face_map.stable_indices+ n = canon.shape[0]++ person = _align_to_canonical(np.asarray(selfie_pts, dtype=np.float64)[:n], canon, stable)+ avatar = _align_to_canonical(np.asarray(head_pts, dtype=np.float64)[:n], canon, stable)++ # Normalise by the canonical interocular span so the score is dimensionless+ # and comparable across faces.+ interocular = float(np.linalg.norm(canon[_EYE_L] - canon[_EYE_R]))+ if interocular <= 0:+ raise EvalError("canonical face has degenerate interocular distance")++ per_point = np.linalg.norm(person - avatar, axis=1) / interocular++ regions = {}+ for name, indices in _REGIONS.items():+ sel = [i for i in indices if i < n]+ if sel:+ regions[name] = float(per_point[sel].mean())++ return {+ "ise": float(per_point[stable].mean()),+ "ise_max": float(per_point[stable].max()),+ "regions": regions,+ }+++def evaluate(selfie: Path, glb: Path, template: Path | None = None) -> dict:+ """+ Score one reconstruction, and (when a template is given) the texture-only+ floor it has to beat.+ """+ face_map = face_geometry.FaceMap.load()+ if face_map is None:+ raise EvalError(+ "face_uv_map.json has no geometry fields — rebuild it with precompute_uv.py "+ "(this is also the condition that silently disables the Phase-2 morph)"+ )++ selfie_pts = selfie_landmarks(selfie)+ result = {+ "selfie": selfie.name,+ "glb": glb.name,+ **score(selfie_pts, head_landmark_points(glb, face_map), face_map),+ }++ if template is not None:+ floor = score(selfie_pts, head_landmark_points(template, face_map), face_map)+ result["template_floor"] = floor["ise"]+ result["improvement"] = (+ (floor["ise"] - result["ise"]) / floor["ise"] if floor["ise"] > 0 else 0.0+ )++ return result+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--selfie", type=Path, required=True, help="source photo")+ ap.add_argument("--glb", type=Path, required=True, help="reconstructed avatar GLB")+ ap.add_argument(+ "--template",+ type=Path,+ default=Path(__file__).resolve().parent.parent / "templates" / "default.glb",+ help="unmorphed template GLB — the texture-only floor to beat",+ )+ ap.add_argument("--json", action="store_true", help="emit JSON only")+ args = ap.parse_args()++ template = args.template if args.template and args.template.exists() else None+ try:+ result = evaluate(args.selfie, args.glb, template)+ except EvalError as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 1++ if args.json:+ print(json.dumps(result, indent=2))+ return 0++ print(f"{result['selfie']} → {result['glb']}")+ print(f" ISE {result['ise']:.4f} (lower is better)")+ print(f" worst point {result['ise_max']:.4f}")+ if "template_floor" in result:+ print(f" template floor {result['template_floor']:.4f}")+ print(f" improvement {result['improvement'] * 100:+.1f}%")+ print(" by region:")+ for name, value in sorted(result["regions"].items(), key=lambda kv: -kv[1]):+ print(f" {name:8s} {value:.4f}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/workers/avatar-reconstruction/eval/run_eval.py b/workers/avatar-reconstruction/eval/run_eval.pynew file mode 100644index 000000000..8cb00e61b--- /dev/null+++ b/workers/avatar-reconstruction/eval/run_eval.py@@ -0,0 +1,212 @@+"""+Batch identity evaluation — score a whole reference set against a live+reconstruction worker, and compare two revisions head to head.++This is the regression gate for the reconstruction pipeline. Point it at a+directory of reference selfies and a deployed worker; it submits every photo,+waits for the GLBs, scores each with `identity_eval`, and writes a report. Run+it against two service URLs (or the same service before and after a change) to+get a defensible answer to "did that actually improve fidelity?" instead of+comparing screenshots.++Usage+-----+ export RECON_KEY=$(gcloud secrets versions access latest \+ --secret=avatar-reconstruction-key --project=aerial-vehicle-466722-p5)++ # score one deployment+ python -m eval.run_eval --photos eval/refs --url https://<service>.run.app \+ --out eval/reports/v2.json++ # compare a report against an earlier one+ python -m eval.run_eval --compare eval/reports/v1.json eval/reports/v2.json++Reference set+-------------+`--photos` is a directory of frontal selfies. Use faces that span the axes the+pipeline is expected to handle — skin tone, age, face shape, facial hair,+glasses, lighting — because a mean over a narrow set hides exactly the failures+that matter. Each file is one sample; sub-directories are ignored.+"""++from __future__ import annotations++import argparse+import base64+import json+import os+import statistics+import sys+import time+from pathlib import Path++import httpx++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++from eval.identity_eval import EvalError, evaluate # noqa: E402++POLL_INTERVAL_S = 3.0+JOB_TIMEOUT_S = 300.0+SUBMIT_TIMEOUT_S = 60.0+PHOTO_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp"}+++def _data_url(path: Path) -> str:+ mime = "image/png" if path.suffix.lower() == ".png" else "image/jpeg"+ return f"data:{mime};base64,{base64.b64encode(path.read_bytes()).decode()}"+++def reconstruct(client: httpx.Client, url: str, key: str, photo: Path, body_type: str) -> bytes:+ """Submit one photo, wait for the job, return the finished GLB bytes."""+ headers = {"authorization": f"Bearer {key}"}+ submit = client.post(+ f"{url}/reconstruct",+ headers=headers,+ json={"images": [_data_url(photo)], "body_type": body_type},+ timeout=SUBMIT_TIMEOUT_S,+ )+ submit.raise_for_status()+ job_id = submit.json()["job_id"]++ deadline = time.monotonic() + JOB_TIMEOUT_S+ while time.monotonic() < deadline:+ time.sleep(POLL_INTERVAL_S)+ job = client.get(f"{url}/jobs/{job_id}", headers=headers, timeout=SUBMIT_TIMEOUT_S).json()+ status = job.get("status")+ if status == "done":+ glb_url = job.get("glb_url")+ if not glb_url:+ raise EvalError(f"{photo.name}: job finished without a glb_url")+ glb = client.get(glb_url, timeout=120.0)+ glb.raise_for_status()+ return glb.content+ if status == "failed":+ detail = (job.get("error") or "unknown").strip().splitlines()[-1]+ raise EvalError(f"{photo.name}: {detail}")++ raise EvalError(f"{photo.name}: job {job_id} did not finish within {JOB_TIMEOUT_S:.0f}s")+++def run(photos: Path, url: str, key: str, out: Path, body_type: str, keep_glb: bool) -> dict:+ samples = sorted(p for p in photos.iterdir() if p.suffix.lower() in PHOTO_SUFFIXES)+ if not samples:+ raise EvalError(f"no photos in {photos} (looked for {', '.join(sorted(PHOTO_SUFFIXES))})")++ glb_dir = out.parent / f"{out.stem}-glb"+ if keep_glb:+ glb_dir.mkdir(parents=True, exist_ok=True)++ results: list[dict] = []+ failures: list[dict] = []++ with httpx.Client(follow_redirects=True) as client:+ health = client.get(f"{url}/health", timeout=30.0).json()+ print(f"worker: {health.get('pipeline')} geometry_morph={health.get('geometry_morph')}")++ for i, photo in enumerate(samples, 1):+ print(f"[{i}/{len(samples)}] {photo.name} … ", end="", flush=True)+ try:+ glb_bytes = reconstruct(client, url, key, photo, body_type)+ glb_path = (glb_dir if keep_glb else out.parent) / f"{photo.stem}.glb"+ glb_path.parent.mkdir(parents=True, exist_ok=True)+ glb_path.write_bytes(glb_bytes)+ result = evaluate(photo, glb_path)+ if not keep_glb:+ glb_path.unlink()+ results.append(result)+ print(f"ISE {result['ise']:.4f}")+ except (EvalError, httpx.HTTPError) as exc:+ failures.append({"selfie": photo.name, "error": str(exc)})+ print(f"FAILED — {exc}")++ if not results:+ raise EvalError("every sample failed — nothing to summarise")++ scores = [r["ise"] for r in results]+ regions = sorted({name for r in results for name in r["regions"]})+ report = {+ "url": url,+ "pipeline": health.get("pipeline"),+ "geometry_morph": health.get("geometry_morph"),+ "samples": len(results),+ "failed": len(failures),+ "ise_mean": statistics.fmean(scores),+ "ise_median": statistics.median(scores),+ "ise_worst": max(scores),+ "region_mean": {+ name: statistics.fmean([r["regions"][name] for r in results if name in r["regions"]])+ for name in regions+ },+ "results": results,+ "failures": failures,+ }++ out.parent.mkdir(parents=True, exist_ok=True)+ out.write_text(json.dumps(report, indent=2))+ print(f"\n{report['samples']} scored, {report['failed']} failed")+ print(f" ISE mean {report['ise_mean']:.4f}")+ print(f" ISE median {report['ise_median']:.4f}")+ print(f" ISE worst {report['ise_worst']:.4f}")+ print(f" report → {out}")+ return report+++def compare(before: Path, after: Path) -> int:+ a, b = json.loads(before.read_text()), json.loads(after.read_text())+ delta = b["ise_mean"] - a["ise_mean"]+ pct = (-delta / a["ise_mean"] * 100) if a["ise_mean"] else 0.0++ print(f"{before.name} ({a.get('pipeline')}) ISE {a['ise_mean']:.4f} n={a['samples']}")+ print(f"{after.name} ({b.get('pipeline')}) ISE {b['ise_mean']:.4f} n={b['samples']}")+ print(f"\n{'IMPROVED' if delta < 0 else 'REGRESSED'} {abs(pct):.1f}%")++ print("\nby region:")+ for name in sorted(set(a["region_mean"]) & set(b["region_mean"])):+ av, bv = a["region_mean"][name], b["region_mean"][name]+ arrow = "↓" if bv < av else "↑"+ print(f" {name:8s} {av:.4f} → {bv:.4f} {arrow}{abs(bv - av) / av * 100:5.1f}%")++ # Per-face movement catches a change that improves the mean while making+ # some faces materially worse — the failure mode a mean alone hides.+ by_name = {r["selfie"]: r["ise"] for r in a["results"]}+ regressions = [+ (r["selfie"], by_name[r["selfie"]], r["ise"])+ for r in b["results"]+ if r["selfie"] in by_name and r["ise"] > by_name[r["selfie"]] * 1.02+ ]+ if regressions:+ print(f"\n{len(regressions)} face(s) got worse:")+ for name, av, bv in sorted(regressions, key=lambda t: t[1] - t[2]):+ print(f" {name:30s} {av:.4f} → {bv:.4f}")++ return 0 if delta < 0 else 1+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--photos", type=Path, help="directory of reference selfies")+ ap.add_argument("--url", help="worker base URL")+ ap.add_argument("--key", default=os.environ.get("RECON_KEY"), help="worker API key (or $RECON_KEY)")+ ap.add_argument("--out", type=Path, default=Path("eval/reports/latest.json"))+ ap.add_argument("--body-type", default="neutral", choices=["male", "female", "neutral"])+ ap.add_argument("--keep-glb", action="store_true", help="keep the GLBs for visual inspection")+ ap.add_argument("--compare", nargs=2, type=Path, metavar=("BEFORE", "AFTER"))+ args = ap.parse_args()++ if args.compare:+ return compare(*args.compare)++ if not (args.photos and args.url and args.key):+ ap.error("--photos, --url and --key (or $RECON_KEY) are required unless --compare is used")++ try:+ run(args.photos, args.url.rstrip("/"), args.key, args.out, args.body_type, args.keep_glb)+ except EvalError as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/workers/avatar-reconstruction/eval/test_identity_eval.py b/workers/avatar-reconstruction/eval/test_identity_eval.pynew file mode 100644index 000000000..b654ad895--- /dev/null+++ b/workers/avatar-reconstruction/eval/test_identity_eval.py@@ -0,0 +1,108 @@+"""+Properties the ISE metric must hold, or its numbers cannot be trusted to gate a+pipeline change.++Run: python -m pytest eval/test_identity_eval.py -q+"""++from __future__ import annotations++import sys+from pathlib import Path++import numpy as np+import pytest++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++import face_geometry # noqa: E402+from eval.identity_eval import score # noqa: E402++RNG = np.random.default_rng(20260725)+N_LANDMARKS = 468+++def _face_map() -> face_geometry.FaceMap:+ """A synthetic but structurally faithful canonical face + correspondence."""+ canonical = RNG.normal(scale=0.25, size=(N_LANDMARKS, 3))+ return face_geometry.FaceMap({+ "canonical_norm": canonical.tolist(),+ "landmark_vtx": list(range(N_LANDMARKS)),+ "head_face_scale": 0.18,+ })+++def _similarity(points: np.ndarray, *, scale: float, seed: int) -> np.ndarray:+ """Apply a random rotation + the given scale + a random translation."""+ rng = np.random.default_rng(seed)+ q, _ = np.linalg.qr(rng.normal(size=(3, 3)))+ if np.linalg.det(q) < 0:+ q[:, 0] *= -1 # keep it a proper rotation, not a reflection+ return scale * (q @ points.T).T + rng.normal(scale=2.0, size=3)+++def test_identical_shape_scores_zero():+ """An avatar whose landmark points *are* the person's scores ~0."""+ fm = _face_map()+ person = fm.canonical_norm + RNG.normal(scale=0.02, size=(N_LANDMARKS, 3))+ assert score(person, person.copy(), fm)["ise"] == pytest.approx(0.0, abs=1e-9)+++def test_score_is_invariant_to_pose_and_scale():+ """+ The metric must measure shape only. A head that is twice as large, rotated+ and translated is the same face and must score the same — otherwise a+ pipeline could 'improve' by resizing the head.+ """+ fm = _face_map()+ person = fm.canonical_norm + RNG.normal(scale=0.03, size=(N_LANDMARKS, 3))+ head = fm.canonical_norm + RNG.normal(scale=0.05, size=(N_LANDMARKS, 3))++ baseline = score(person, head, fm)["ise"]+ for scale, seed in ((2.0, 1), (0.5, 2), (1.0, 3)):+ moved = score(person, _similarity(head, scale=scale, seed=seed), fm)["ise"]+ assert moved == pytest.approx(baseline, rel=1e-6)+++def test_moving_toward_the_person_lowers_the_score():+ """+ Monotonicity: interpolating the template head toward the person's shape must+ reduce ISE at every step. This is the property that makes the score usable+ as an objective — it has to reward the thing the morph actually does.+ """+ fm = _face_map()+ person = fm.canonical_norm + RNG.normal(scale=0.06, size=(N_LANDMARKS, 3))+ template = fm.canonical_norm + RNG.normal(scale=0.06, size=(N_LANDMARKS, 3))++ scores = [+ score(person, template + t * (person - template), fm)["ise"]+ for t in (0.0, 0.25, 0.5, 0.75, 1.0)+ ]+ assert scores == sorted(scores, reverse=True), scores+ assert scores[-1] == pytest.approx(0.0, abs=1e-9)+ assert scores[0] > 0.0+++def test_regions_are_reported_and_bounded_by_the_extremes():+ """Every region reports, and each mean sits inside the global min/max."""+ fm = _face_map()+ person = fm.canonical_norm + RNG.normal(scale=0.04, size=(N_LANDMARKS, 3))+ head = fm.canonical_norm + RNG.normal(scale=0.04, size=(N_LANDMARKS, 3))++ result = score(person, head, fm)+ assert set(result["regions"]) == {"oval", "nose", "cheeks", "brow", "jaw"}+ for value in result["regions"].values():+ assert 0.0 < value <= result["ise_max"]+++def test_extra_iris_landmarks_are_ignored():+ """+ MediaPipe returns 478 points when iris refinement is on. The extra 10 must+ not shift the score — irises are expression/gaze, not identity.+ """+ fm = _face_map()+ person = fm.canonical_norm + RNG.normal(scale=0.03, size=(N_LANDMARKS, 3))+ head = fm.canonical_norm + RNG.normal(scale=0.05, size=(N_LANDMARKS, 3))++ with_irises = np.vstack([person, RNG.normal(scale=5.0, size=(10, 3))])+ assert score(with_irises, head, fm)["ise"] == pytest.approx(score(person, head, fm)["ise"])