Skip to content

Turn any video into a Mixamo-rig animation - GVHMR estimator, spec-driven retarget, FK apply in Blender via MCP. Works with any Mixamo character; built to be operated end-to-end by an AI agent.

Video -> Mixamo mocap pipeline: any Mixamo character, GVHMR, spec-driven, AI-operable

Sacha1d23ac7750f2
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..9564ff4
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,22 @@
+# Mixamo assets — Adobe's terms forbid redistribution. Download Y Bot
+# yourself and build the scene with pipeline/setup_rig.py (docs/INSTALL.md).
+ybot.fbx
+ybot_rest.blend
+*.blend1
+rig_profile.json
+
+# The author's plates and produced clips are demonstration material,
+# not part of the distributed pipeline. They stay local.
+plates/
+clips/
+
+# Local reference material not meant to ship (rig measurement dumps etc.)
+local/
+
+# External tools: GVHMR checkout, its venv, checkpoints and the
+# license-gated SMPL-X body model all live here. Never commit them.
+tools/
+
+# Python
+__pycache__/
+*.pyc
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..23c6f6d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,39 @@
+MIT License
+
+Copyright (c) 2026 squall01337 / mixamo-llm-mocap contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+----------------------------------------------------------------------------
+Third-party notes (not covered by this license)
+
+- Mixamo characters (Y Bot or any other): Adobe Mixamo terms. No
+ character FBX is included and none may be redistributed — download
+ your own from mixamo.com and build the scene with
+ pipeline/setup_rig.py.
+- GVHMR (zju3dv): separate license, cloned into tools/ by the user.
+ Its pretrained checkpoints carry their own terms.
+- SMPL-X body model (MPI): registration-gated license at
+ https://smpl-x.is.tue.mpg.de/ — never committed to this repo.
+- pytorch3d Windows wheels: community builds by MiroPsota
+ (torch_packages_builder), BSD-licensed pytorch3d (Meta).
+- Blender MCP add-on: Blender Lab, GPL-3.0-or-later (runs inside
+ Blender; this repo only talks to its socket).
+- The motion clips under clips/ and the generated plates under plates/
+ are original content released under the MIT license above.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..c556539
--- /dev/null
+++ b/README.md
@@ -0,0 +1,112 @@
+# Mixamo LLM Mocap
+
+**Turn any locked-camera video — filmed or AI-generated — into a clean
+FK animation on any Mixamo character. No mocap suit, no manual
+keyframing, and every stage scriptable enough that an AI agent can run
+the whole loop.**
+
+![license](https://img.shields.io/badge/license-MIT-green)
+![blender](https://img.shields.io/badge/Blender-5.1%2B-orange)
+![gpu](https://img.shields.io/badge/CUDA-~8GB%20VRAM-76b900)
+![agent](https://img.shields.io/badge/operable%20by-AI%20agents-blueviolet)
+
+![showcase](media/showcase.gif)
+
+*Left: AI-generated source video. Right: the automatic retarget on a
+Mixamo character in Blender — 10 seconds, nine punches, a slip under
+and a high side kick, straight through the pipeline.*
+
+## How it works
+
+```
+video plate (locked camera, T-pose bookends)
+ │
+ ├─ 1. estimate_pose_gvhmr.py GVHMR (SMPL-X mesh recovery) → 33 landmarks + pelvis height
+ ├─ 2. analyze_landmarks.py numeric beat detection → you write a beat sheet from NUMBERS
+ ├─ 3. action_specs/<name>.json the motion as data: support schedule, rest blends, fists
+ ├─ 4. lift_to_mixamo.py direction-preserving retarget onto YOUR rig's proportions
+ ├─ 5. apply_mixamo_fk.py FK aim + foot planting, inside live Blender (via Blender MCP)
+ └─ 6. qa_clip.py automated gate: no explosions, no pops, no foot skate
+```
+
+The estimator provides mesh-quality joints; the lift keeps its segment
+*directions* but rebuilds every position from your character's measured
+bone lengths; the apply plants feet by solving hip height (never IK —
+Mixamo rigs are FK-only); the spec contributes only what a video cannot
+know: which foot is the support in each phase (including `"none"` for
+airborne beats), when fists close, where the clip locks back to rest.
+
+## Why it's different
+
+- **Any Mixamo character.** `setup_rig.py` builds a clean scene from
+ your own Mixamo download and measures it into `rig_profile.json`
+ (rest pose, bone lengths, hip and ground heights). Every stage reads
+ that profile.
+- **Motions are data, not code.** A new motion is a small JSON spec —
+ the three `action_specs/` here (a kung-fu form, a combo with a jump,
+ a fight combination) are worked examples of the whole schema.
+- **Honest Mixamo FK.** Hips are the only translating bone, everything
+ else is quaternions at 30 fps — clips drop into any Mixamo-style
+ workflow without cleanup.
+- **Real ground contact.** Planted feet solve to ground height with
+ zero skate (the support ankle is pinned through each stance); jumps
+ integrate the estimator's real pelvis arc.
+- **A QA gate, not vibes.** Exploded bones, hip pops, foot skate,
+ drifting roots and broken rest poses are caught numerically before a
+ human ever looks.
+- **Written for agents.** Beat decisions come from
+ `analyze_landmarks.py` numbers (never from eyeballing frames), every
+ stage is a CLI or a socket call, and `docs/PITFALLS.md` encodes every
+ mistake so the next operator — human or AI — doesn't repeat them.
+
+## Quickstart
+
+1. **Install** — [docs/INSTALL.md](docs/INSTALL.md) walks through every
+ dependency (list below).
+2. **Build your rig scene**:
+
+ ```
+ blender --background --python pipeline\setup_rig.py -- --fbx ybot.fbx --out ybot_rest.blend
+ ```
+
+3. **Run a plate** (Blender open on the scene; plate rules in
+ [docs/PROMPTING.md](docs/PROMPTING.md)):
+
+ ```
+ tools\GVHMR\.venv\Scripts\python.exe pipeline\estimate_pose_gvhmr.py --video plates\<name>\<name>.mp4 --out plates\<name>\landmarks.json
+ tools\GVHMR\.venv\Scripts\python.exe pipeline\analyze_landmarks.py --landmarks plates\<name>\landmarks.json
+ # beat sheet → action_specs\<name>.json (schema: docs/PIPELINE.md)
+ tools\GVHMR\.venv\Scripts\python.exe pipeline\lift_to_mixamo.py --spec action_specs\<name>.json
+ # in Blender: import apply_mixamo_fk; apply_mixamo_fk.run("action_specs/<name>.json")
+ tools\GVHMR\.venv\Scripts\python.exe pipeline\qa_clip.py --spec action_specs\<name>.json
+ ```
+
+4. **Iterate** with [docs/PIPELINE.md](docs/PIPELINE.md) and
+ [docs/PITFALLS.md](docs/PITFALLS.md).
+
+## What you need to bring (and where to get it)
+
+| What | Where | Notes |
+|---|---|---|
+| **A Mixamo character — any model** | [mixamo.com](https://www.mixamo.com) → Characters → download FBX Binary, T-pose | Adobe's terms don't allow redistributing them; `setup_rig.py` builds and validates the scene from your download |
+| **Blender 5.1+** | [blender.org](https://www.blender.org/download/) | |
+| **Blender MCP add-on** (official, Blender Lab) | [blender.org/lab/mcp-server](https://www.blender.org/lab/mcp-server/) | enable *Allow Online Access*; the apply talks to its socket |
+| **GVHMR** (the pose estimator — **not in this repo**) | [github.com/zju3dv/GVHMR](https://github.com/zju3dv/GVHMR) | clone into `tools/GVHMR`; install per [docs/INSTALL.md](docs/INSTALL.md) — including a working Windows recipe (`docs/requirements_gvhmr_windows.txt` + prebuilt pytorch3d wheel) |
+| **GVHMR checkpoints** (~5 GB) | HuggingFace mirror | exact `curl` commands in [docs/INSTALL.md](docs/INSTALL.md) |
+| **SMPL-X body model** | [smpl-x.is.tue.mpg.de](https://smpl-x.is.tue.mpg.de/) | free research registration → download *SMPL-X v1.1*, place `SMPLX_NEUTRAL.npz` as shown in [docs/INSTALL.md](docs/INSTALL.md) |
+| **NVIDIA GPU** | ~8 GB VRAM | developed on an RTX 4080 |
+
+## Docs
+
+| Doc | What it covers |
+|---|---|
+| [docs/INSTALL.md](docs/INSTALL.md) | Every dependency, step by step, Windows-proven |
+| [docs/PIPELINE.md](docs/PIPELINE.md) | The operational loop + the action_spec schema, field by field |
+| [docs/RIG.md](docs/RIG.md) | Mixamo rig conventions: spaces, units, the rules that must never break |
+| [docs/PITFALLS.md](docs/PITFALLS.md) | Every mistake this pipeline's development paid for, so you don't pay twice |
+| [docs/PROMPTING.md](docs/PROMPTING.md) | Writing gen-video plate prompts that survive retargeting |
+
+## License
+
+MIT — see [LICENSE](LICENSE), including third-party notes (Mixamo,
+GVHMR, SMPL-X, Blender MCP).
diff --git a/action_specs/combo.json b/action_specs/combo.json
new file mode 100644
index 0000000..8673f69
--- /dev/null
+++ b/action_specs/combo.json
@@ -0,0 +1,27 @@
+{
+ "name": "combo",
+ "action_name": "YBot_ComboFromVideo",
+ "clip_dir": "clips/ybot_combo_from_video",
+ "landmarks": "plates/combo/landmarks.json",
+ "joints_out": "plates/combo/joints_mixamo.json",
+ "beatsheet": "plates/combo/BEATSHEET.md",
+ "estimator": "gvhmr_siga24",
+ "src_fps": 24,
+ "dst_fps": 30,
+
+ "rest_blend_start": { "full_src": 1, "release_src": 16 },
+ "rest_blend_end": { "start_src": 214, "full_src": 232 },
+
+ "fists": { "rise_src": [20, 28], "fall_src": [200, 212] },
+
+ "plant": [
+ { "src": [1, 129], "support": "both" },
+ { "src": [130, 154], "support": "left" },
+ { "src": [155, 158], "support": "right" },
+ { "src": [159, 168], "support": "none" },
+ { "src": [169, 177], "support": "left" },
+ { "src": [178, 241], "support": "both" }
+ ],
+
+ "qa_src_frames": [1, 30, 60, 68, 90, 109, 127, 139, 151, 163, 171, 190, 220, 241]
+}
diff --git a/action_specs/fight.json b/action_specs/fight.json
new file mode 100644
index 0000000..58f4437
--- /dev/null
+++ b/action_specs/fight.json
@@ -0,0 +1,24 @@
+{
+ "name": "fight",
+ "action_name": "YBot_FightFromVideo",
+ "clip_dir": "clips/ybot_fight_from_video",
+ "landmarks": "plates/fight/landmarks.json",
+ "joints_out": "plates/fight/joints_mixamo.json",
+ "beatsheet": "plates/fight/BEATSHEET.md",
+ "estimator": "gvhmr_siga24",
+ "src_fps": 24,
+ "dst_fps": 30,
+
+ "rest_blend_start": { "full_src": 44, "release_src": 58 },
+ "rest_blend_end": { "start_src": 206, "full_src": 224 },
+
+ "fists": { "rise_src": [56, 64], "fall_src": [196, 208] },
+
+ "plant": [
+ { "src": [1, 127], "support": "both" },
+ { "src": [128, 140], "support": "left" },
+ { "src": [141, 241], "support": "both" }
+ ],
+
+ "qa_src_frames": [1, 45, 71, 77, 92, 98, 109, 122, 132, 145, 153, 175, 215, 241]
+}
diff --git a/action_specs/kungfu_form.json b/action_specs/kungfu_form.json
new file mode 100644
index 0000000..dfd7b1a
--- /dev/null
+++ b/action_specs/kungfu_form.json
@@ -0,0 +1,34 @@
+{
+ "name": "kungfu_form",
+ "action_name": "YBot_KungFuFromVideo",
+ "clip_dir": "clips/ybot_kungfu_from_video",
+ "landmarks": "plates/kungfu/landmarks.json",
+ "joints_out": "plates/kungfu/joints_mixamo.json",
+ "beatsheet": "plates/kungfu/BEATSHEET.md",
+ "estimator": "gvhmr_siga24",
+ "src_fps": 24,
+ "dst_fps": 30,
+
+ "rest_blend_end": { "start_src": 208, "full_src": 230 },
+
+ "fists": { "rise_src": [58, 66], "fall_src": [183, 195] },
+
+ "arm_overrides": [
+ {
+ "side": "right",
+ "src": [76, 163],
+ "ramp_src": 6,
+ "comment": "Owner note on pass 1: after the right punch (dest ~91) the right arm pulls back close to the body, fist at chest level through the whole bow-hold pause. GVHMR mis-tracked the occluded arm as lateral-back.",
+ "wrist_local": [-0.17, -0.12, 0.33],
+ "elbow_local": [-0.25, 0.05, 0.12]
+ }
+ ],
+
+ "plant": [
+ { "src": [1, 45], "support": "both" },
+ { "src": [46, 69], "support": "left" },
+ { "src": [70, 241], "support": "both" }
+ ],
+
+ "qa_src_frames": [1, 25, 47, 55, 62, 73, 84, 95, 130, 180, 193, 210, 241]
+}
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
new file mode 100644
index 0000000..a6df571
--- /dev/null
+++ b/docs/INSTALL.md
@@ -0,0 +1,126 @@
+# Install
+
+Everything the pipeline needs, from a bare Windows machine to a first
+retarget. Developed and validated on: Windows 10, RTX 4080 (16 GB),
+Blender 5.1.2, Python 3.10 (GVHMR venv via `uv`). Linux works with the
+same steps minus the Windows-specific wheel notes.
+
+## 0. Prerequisites
+
+| Thing | Version | Notes |
+|---|---|---|
+| NVIDIA GPU + driver | ~8 GB VRAM min | CUDA 12.1 wheels are used |
+| Blender | **5.1+** | the Blender MCP add-on requires it |
+| Python | any (for `uv`) | the GVHMR venv is created as 3.10 |
+| [uv](https://docs.astral.sh/uv/) | recent | manages the 3.10 venv painlessly |
+| git, ffmpeg | recent | |
+
+## 1. Mixamo character (Adobe — bring your own)
+
+Any Mixamo character with the standard `mixamorig` skeleton works;
+Y Bot is the reference the pipeline was developed on.
+
+1. Log in at https://www.mixamo.com → Characters → pick a character.
+2. Download: Format **FBX Binary**, Pose **T-pose** (with skin).
+3. Save as `<repo>\ybot.fbx` (any name — pass it via `--fbx`).
+4. Build + validate the working scene — this also writes
+ `rig_profile.json`, the measured proportions every later stage uses:
+
+```
+"C:\Program Files\Blender Foundation\Blender 5.1\blender.exe" ^
+ --background --python pipeline\setup_rig.py -- --fbx ybot.fbx --out ybot_rest.blend
+```
+
+Expected output ends with `rig_profile.json written — hip ... ground ...`
+and `saved ... bones ... 30 fps`. If validation fails, the FBX is not a
+plain Mixamo T-pose character download.
+
+## 2. Blender MCP (official, Blender Lab)
+
+The FK apply runs inside a live Blender through the official add-on's
+bridge socket (`localhost:9876`).
+
+1. In Blender: **Edit → Preferences → System → Network → Allow Online
+ Access** (off by default — the server refuses to start without it).
+2. Install the add-on from https://www.blender.org/lab/mcp-server/ —
+ drag the install link into Blender **twice** (first adds the Blender
+ Lab extension repository, second installs), or download the zip and
+ use *Install from Disk*.
+3. The server autostarts ~1 s after Blender launches (check
+ Preferences → Add-ons → MCP: "Server is running").
+
+For an **agent driving Blender**: either register the MCP server with
+your client —
+
+```
+claude mcp add blender -s user -- uvx --from "git+https://projects.blender.org/lab/blender_mcp.git#subdirectory=mcp" --with "mcp[cli]<2" blender-mcp
+```
+
+(the `mcp[cli]<2` pin matters: the 2.x Python SDK removed
+`mcp.server.fastmcp`, which the server imports) — or skip MCP entirely
+and use `pipeline\blender_exec.py <script.py> [timeout]`, which speaks
+the add-on's socket protocol directly.
+
+## 3. GVHMR (the estimator)
+
+```
+git clone https://github.com/zju3dv/GVHMR tools/GVHMR
+uv python install 3.10
+uv venv --python 3.10 tools/GVHMR/.venv
+uv pip install --python tools/GVHMR/.venv/Scripts/python.exe -r docs/requirements_gvhmr_windows.txt
+uv pip install --python tools/GVHMR/.venv/Scripts/python.exe --no-deps -e tools/GVHMR
+uv pip install --python tools/GVHMR/.venv/Scripts/python.exe yacs
+```
+
+`docs/requirements_gvhmr_windows.txt` is GVHMR's requirements with
+Windows fixes baked in (pinned `pytorch3d` Linux wheel dropped,
+`chumpy`/`cython_bbox` dropped — see the file header). On Linux you can
+use GVHMR's own `requirements.txt` unchanged.
+
+**pytorch3d on Windows** (needed by GVHMR's core, not just its
+renderer): install a community wheel matching
+torch 2.3.0 + cu121 + cp310 + win_amd64 from
+https://miropsota.github.io/torch_packages_builder/pytorch3d/ :
+
+```
+uv pip install --python tools/GVHMR/.venv/Scripts/python.exe --no-deps "https://github.com/MiroPsota/torch_packages_builder/releases/download/pytorch3d-0.7.6/pytorch3d-0.7.6%2Bpt2.3.0cu121-cp310-cp310-win_amd64.whl"
+```
+
+**Checkpoints** (~5.3 GB). Google Drive blocks scripted downloads;
+the HuggingFace mirror works:
+
+```
+BASE=https://huggingface.co/camenduru/GVHMR/resolve/main
+CK=tools/GVHMR/inputs/checkpoints
+curl -L $BASE/gvhmr/gvhmr_siga24_release.ckpt -o $CK/gvhmr/gvhmr_siga24_release.ckpt --create-dirs
+curl -L $BASE/yolo/yolov8x.pt -o $CK/yolo/yolov8x.pt --create-dirs
+curl -L $BASE/vitpose/vitpose-h-multi-coco.pth -o $CK/vitpose/vitpose-h-multi-coco.pth --create-dirs
+curl -L "$BASE/hmr2/epoch%3D10-step%3D25000.ckpt" -o "$CK/hmr2/epoch=10-step=25000.ckpt" --create-dirs
+```
+
+(dpvo.pth is only needed for moving cameras; plates are locked.)
+
+**SMPL-X body model** (license-gated, free registration): register at
+https://smpl-x.is.tue.mpg.de/ , download **SMPL-X v1.1 (NPZ+PKL)** and
+copy `SMPLX_NEUTRAL.npz` to
+`tools/GVHMR/inputs/checkpoints/body_models/smplx/`. GVHMR's network
+asserts on this file at startup — nothing runs without it.
+
+**Smoke test** (must print your GPU and no tracebacks):
+
+```
+tools/GVHMR/.venv/Scripts/python.exe -c "import torch; print(torch.cuda.get_device_name(0)); from hmr4d.utils.smplx_utils import make_smplx; from hmr4d.model.gvhmr.gvhmr_pl_demo import DemoPL; from hmr4d.utils.preproc import Tracker; print('GVHMR import chain OK')"
+```
+
+If a different GVHMR root is preferred, set the env var `GVHMR_ROOT`.
+
+## 4. Verify end-to-end
+
+With Blender open on `ybot_rest.blend`, run your first plate through
+the five stages (README quickstart step 3 / docs/PIPELINE.md). Sanity
+reference values from the author's accepted clips:
+
+- estimator bind wrist span on a T-pose: ~1.25–1.44 m
+- QA gate: 0 world-bound violations, max hip Z step well under
+ 0.12 m/frame (accepted clips: 0.026–0.061), single-support foot
+ skate 0.000 m, end-frame rest hand error ~0.001 m, verdict PASS.
diff --git a/docs/PIPELINE.md b/docs/PIPELINE.md
new file mode 100644
index 0000000..2f937dd
--- /dev/null
+++ b/docs/PIPELINE.md
@@ -0,0 +1,178 @@
+# The pipeline, operationally
+
+How a video becomes a Y Bot clip, stage by stage, with the decision
+rules an operator (human or AI) needs. Everything here was validated on
+the two shipped clips.
+
+## 0. The plate (source video)
+
+Quality is won or lost here. Rules (see docs/PROMPTING.md for
+generating plates with AI video):
+
+- Locked camera, full body in frame the whole time, even light, 720p+.
+- **T-pose held ~1 s at the start AND the end**, facing the camera
+ square. The T-poses are the rest anchors; the pipeline blends into
+ exact Y Bot rest there.
+- One continuous take, on the spot. Every moving limb must stay
+ visible — an occluded limb cannot be tracked (it can be fixed with an
+ `arm_override`, but only because a human saw the video).
+- Facing changes are fine (the kungfu clip turns ±100°); occlusion is
+ the enemy, not rotation.
+
+Save as `plates/<name>/<clip>.mp4` with a short `SOURCE.md`.
+
+## 1. Estimate
+
+```
+tools\GVHMR\.venv\Scripts\python.exe pipeline\estimate_pose_gvhmr.py ^
+ --video plates\<name>\<clip>.mp4 --out plates\<name>\landmarks.json
+```
+
+Output: 33 landmarks/frame (MediaPipe-compatible convention: per-frame
+mid-hip origin, y down, z **negative toward camera**, meters) plus
+`pelvis_height` (absolute, above the estimator's ground plane).
+GVHMR caches its preprocessing under `tools/GVHMR/outputs/demo/<stem>/`
+— re-runs are fast.
+
+## 2. Numeric beat sheet — BEFORE any spec
+
+```
+tools\GVHMR\.venv\Scripts\python.exe pipeline\analyze_landmarks.py --landmarks plates\<name>\landmarks.json
+```
+
+Write `plates/<name>/BEATSHEET.md`: a table of beats with src frame
+windows, the acting limb, the support foot, and the *numeric evidence*
+(this tool's output). Hard rules:
+
+- **Take every limb decision from the numbers, never from stills.**
+ Facing the camera, viewer-left is the character's RIGHT; every
+ screen-read limb guess in this project's history was wrong at least
+ once. Gen-video also deviates from its prompt (a prompted left-knee
+ jump arrived as right-knee).
+- Punches: wrist z dips below −0.32 (toward camera). Kicks/knees: one
+ ankle height rises with the other grounded. Flight: both ankles
+ > 0.25 m. Ducks/jumps: `pelvis_height` dips/peaks.
+- Shoulder-line yaw swings ±40–60° during punches without the hips
+ turning — don't read those as facing changes.
+
+## 3. The action_spec (the motion as data)
+
+`action_specs/<motion>.json` — all frame numbers are **source** frames
+(the lift converts to 30 fps dest internally):
+
+```jsonc
+{
+ "name": "combo", // slug
+ "action_name": "YBot_ComboFromVideo", // Blender action name
+ "clip_dir": "clips/ybot_combo_from_video",// outputs (repo-relative)
+ "landmarks": "plates/combo/landmarks.json",
+ "joints_out": "plates/combo/joints_mixamo.json",
+ "estimator": "gvhmr_siga24",
+ "src_fps": 24, "dst_fps": 30,
+
+ // Blend into exact Y Bot rest. End is required; start is optional
+ // (use it when the plate opens on a clean T-pose).
+ "rest_blend_start": { "full_src": 1, "release_src": 16 },
+ "rest_blend_end": { "start_src": 214, "full_src": 232 },
+
+ // Fist amount 0->1->0, smooth edges.
+ "fists": { "rise_src": [20, 28], "fall_src": [200, 212] },
+
+ // Optional authored overrides for beats where the human's read of
+ // the video beats the estimator (occluded arm etc.). Targets are
+ // METERS in the hip basis (x=character left, y=back, z=up), ramped.
+ "arm_overrides": [
+ { "side": "right", "src": [76, 163], "ramp_src": 6,
+ "wrist_local": [-0.17, -0.12, 0.33],
+ "elbow_local": [-0.25, 0.05, 0.12] }
+ ],
+
+ // The support schedule — the heart of the spec. Windows must cover
+ // the clip. Supports: "both", "left", "right", "none" (airborne).
+ "plant": [
+ { "src": [1, 129], "support": "both" },
+ { "src": [130, 154], "support": "left" }, // right leg acts
+ { "src": [155, 158], "support": "right" },
+ { "src": [159, 168], "support": "none" }, // flight
+ { "src": [169, 177], "support": "left" }, // landing
+ { "src": [178, 241], "support": "both" }
+ ],
+
+ "qa_src_frames": [1, 30, 60, 109, 139, 163, 241] // beat frames for QA/stills
+}
+```
+
+What each support does in the FK apply:
+- `left`/`right`: hip height searched so that foot lands at 0.105 m;
+ the foot is flattened (Z-only, keeps estimator XZ and its own
+ heading); the lift also **pins the support ankle's XZ** for the whole
+ window (the pose translates so the planted foot never skates; the
+ correction decays over 10 frames after the window).
+- `both`: plant the lower foot, flatten both if near ground. Feet may
+ genuinely step inside a `both` window — that is fine.
+- `none`: no plant, no snapping; hip height integrates the estimator's
+ `pelvis_height` arc from the last planted frame (continuous takeoff,
+ ballistic flight). Landing pops are caught by QA's hip-step check.
+
+## 4. Lift
+
+```
+tools\GVHMR\.venv\Scripts\python.exe pipeline\lift_to_mixamo.py --spec action_specs\<motion>.json
+```
+
+Direction-preserving retarget: estimator segment directions × Mixamo
+bone lengths from the Mixamo sockets. No IK. Read the QA lines it
+prints (one per `qa_src_frames`): rest/fist amounts, plant, yaw, key
+positions. Sanity: rest frames print the exact Y Bot rest
+(`lw=[0.73777, 0.06171, 1.43572]`).
+
+## 5. Apply (inside live Blender)
+
+Blender must be open on `ybot_rest.blend` with the MCP add-on server
+running. Via MCP `execute_blender_code` or `pipeline\blender_exec.py`:
+
+```python
+import sys; sys.path.insert(0, r"<repo>\pipeline")
+import apply_mixamo_fk
+apply_mixamo_fk.run("action_specs/<motion>.json") # keys the action (~2-4 min / 300 frames; UI freezes — normal)
+apply_mixamo_fk.dump_curves("action_specs/<motion>.json") # curves.json (every bone, every frame)
+apply_mixamo_fk.run_stills_render("action_specs/<motion>.json", [1, 30, ...]) # front+side PNGs per beat
+```
+
+Stills use a temporary camera + Workbench render (window-independent);
+never use viewport screenshots — they capture black when the Blender
+window is occluded.
+
+## 6. QA
+
+```
+tools\GVHMR\.venv\Scripts\python.exe pipeline\qa_clip.py --spec action_specs\<motion>.json
+```
+
+| Check | Limit | Meaning |
+|---|---|---|
+| world bounds | \|x\|,\|y\| < 2, z ∈ (−0.5, 3) | exploded bones |
+| hip Z step | < 0.12 m/frame | pops (takeoff/landing included) |
+| in-place travel | end-to-end ≈ 0 | root discipline |
+| single-support | z-err ≈ 0, XZ wander ≈ 0 | plant + no skate |
+| airborne | lower-foot clearance > 0.12 m | the jump actually flies |
+| end frame | hand error < 0.03 vs rest | clean T-pose out |
+| frame-jumps | < 0.30 m per bone | teleporting limbs |
+
+`WARN` on a `both` window usually means a genuine step (weight shift,
+stance widening) — check the video before "fixing" it. **Numbers can
+pass while the motion is wrong: always look at the stills and play the
+clip. The human eye is the last word.**
+
+## 7. Iteration protocol (how 16 passes became 1–2)
+
+- Beat sheet before any spec. A wrong limb in the spec is a wasted pass.
+- Human notes come as frame ranges + a region ("frames 18–50, punching
+ side"). Map the range to the beat and to the spec field that owns it
+ BEFORE editing anything.
+- One constraint per pass. Never touch a region the human has signed
+ off to polish a different one.
+- Re-render stills after every apply; never argue from a stale image.
+- When the estimator and the human's read of the video disagree, the
+ human is right (occlusion, foreshortening) — encode the fix as an
+ `arm_override`, don't fight the estimator globally.
diff --git a/docs/PITFALLS.md b/docs/PITFALLS.md
new file mode 100644
index 0000000..d6d1a74
--- /dev/null
+++ b/docs/PITFALLS.md
@@ -0,0 +1,91 @@
+# Pitfalls
+
+Every one of these was paid for in real passes across three model
+generations working on this rig. If you are an AI operating this
+pipeline: read this file before your first pass and again before
+touching a clip a human has partially signed off.
+
+## Space and measurement
+
+1. **Blender IK explodes this rig.** `POSE_IK` on the legs sent feet to
+ −81 m. The skeleton is FK-only; plant feet via hip-height search +
+ Z-only flattening. If FK plant looks wrong, fix the spec or the
+ lift — never "just add IK for the landing".
+2. **World-space aim is 100× off.** Composing a pose matrix through
+ `arm.matrix_world` (scale 0.01) and assigning it sends hands to
+ z ≈ 10 m. Aim in armature centimeters (`aim_bone` does).
+3. **`pb.head` lies on a posed rig.** Only
+ `(arm.matrix_world @ pb.matrix).to_translation()` after a depsgraph
+ update is truth.
+4. **Stale location keys survive rewrites.** A failed pass that keyed
+ locations on non-hip bones will haunt a rotations-only rewrite.
+ `apply_mixamo_fk` deletes and rebuilds the action and re-keys zero
+ locations everywhere for this reason.
+
+## Reading the video
+
+5. **Never decide a limb from a still.** Facing the camera,
+ viewer-left = character-RIGHT. Three separate incidents: a kick
+ built on the wrong leg (full wasted pass), a "left knee" jump that
+ was numerically right-knee, a "chambered fist" that was a
+ foreshortened punch toward the camera. `analyze_landmarks.py` output
+ is the only admissible evidence for the beat sheet.
+6. **Gen-video does not follow its prompt.** Prompted left-knee jump →
+ right knee; prompted extended front kick → high-knee snap; prompted
+ A-pose → the model's own idea of one. Retarget what was filmed;
+ never author toward the prompt.
+7. **The estimator loses occluded limbs.** An arm behind the torso in
+ 3/4 view came back as garbage (lateral-back instead of chambered at
+ the chest). When a human's read of the video contradicts the
+ estimator, the human is right — encode it as a spec `arm_override`
+ with ramps, and leave the estimator's other limbs alone.
+
+## Feet and ground
+
+8. **Per-frame hip-centered landmarks make planted feet skate.** The
+ support foot wandered 0.30 m during a kick. Fix is structural (the
+ lift pins the support ankle's XZ and translates the whole pose;
+ pelvis sways over the foot, which is correct physics) — do not
+ patch it per-frame in the apply.
+9. **A degenerate aim target bends toes randomly.** Aiming ToeBase at
+ its own head position is a near-zero-length target. Toe aims need a
+ point several cm FORWARD along the foot's own heading.
+10. **Foot heading follows the foot/hips, never a world axis.**
+ "Straightening" toes toward world −Y on a yawed stance turns them
+ outward on screen. Keep estimator XZ; constrain heights only.
+11. **Never snap the acting limb to the floor.** A floor snap that kept
+ running while a kick lifted pinned the foot for one frame and made
+ the next frame pop. The plant schedule exists so ground logic
+ knows whose foot is acting.
+
+## Blender / tooling
+
+12. **Viewport screenshots capture black** when the Blender window is
+ occluded or minimized. Stills go through a temporary camera +
+ Workbench render (`run_stills_render`), always.
+13. **The long apply blocks Blender's UI.** 300 frames ≈ 2–4 minutes of
+ frozen window while the socket request executes. Normal; don't
+ kill it. Results are also written to disk (`apply_result.json`) so
+ a dropped socket loses nothing.
+14. **mcp SDK 2.x breaks the official Blender MCP server** (it imports
+ `mcp.server.fastmcp`, removed in 2.0). Pin `mcp[cli]<2` when
+ registering the server.
+15. **Stale stills burn passes.** After every re-key, delete and
+ re-render the stills before judging anything. An old PNG has
+ cost this project at least two decisions.
+
+## Process
+
+16. **Beat sheet before any spec.** The 16-pass punch and the 4-pass
+ kick differ by exactly this discipline; the two shipped clips took
+ 1–2 passes each.
+17. **One constraint per pass; signed-off regions are frozen.** The
+ single historical regression came from "improving" feet while
+ polishing something else after the upper body was approved.
+18. **Map human notes to the owning system before editing.** "Frames
+ 18–50, punching side" once meant the *guard*, not the punch — a
+ pass was wasted editing the wrong function. Convert the frame range
+ to src frames, find the beat, find the spec field; only then edit.
+19. **QA passing ≠ done.** Numbers catch explosions, pops, skate and
+ drift; they cannot see a wrong silhouette. Play the clip, read the
+ stills, ask the human.
diff --git a/docs/PROMPTING.md b/docs/PROMPTING.md
new file mode 100644
index 0000000..03157e0
--- /dev/null
+++ b/docs/PROMPTING.md
@@ -0,0 +1,55 @@
+# Prompting gen-video plates
+
+The pipeline retargets *any* locked-camera footage, but its cheapest
+source is AI video (the shipped plates came from Seedance and an
+earlier image-to-video tool). This is how to prompt so the result
+survives retargeting.
+
+## The contract a plate must honor
+
+1. **Camera locked**, full body in frame every frame, even light,
+ 1080p (720p minimum), 24–30 fps, ~10 s.
+2. **T-pose held ~1 s at the START and the END**, square to camera.
+ These bookends are the rest anchors (`rest_blend_start/_end`) and
+ the proof the identity didn't drift. If the start pose is dirty the
+ end T-pose alone is enough — but demand both anyway.
+3. **Chest and hips face the camera** unless a turn IS the motion.
+ Turns are retargetable; occlusion is not.
+4. **Every moving limb stays visible.** Kicks travel just to the
+ performer's side of the centerline so the leg never hides behind
+ the torso. No props, tight kit, bare feet.
+5. One continuous take, on the spot: no walking, no spinning, no
+ extra strikes. Name the exact moves and forbid the rest.
+6. Reuse the same first-frame still (image-to-video) across plates —
+ same performer, same studio, same grid. Identity drift between
+ plates breaks nothing technically but muddies comparison.
+
+## Template
+
+> Same man, same grey studio, same floor grid, camera locked, full body
+> in frame the whole time. He starts holding this exact T-pose,
+> perfectly still and facing the camera straight on, for a full second.
+> Then he [MOVE 1 in one clause]. He then [MOVE 2]. Next he [MOVE 3,
+> with visibility hints like "the kicking foot staying just to HIS
+> right of the centerline so the whole leg stays visible"]. Finally he
+> lowers his arms and spreads them straight out horizontally into a
+> T-pose, feet returning under his shoulders, and holds that T-pose
+> perfectly still, facing the camera, for the last full second. He
+> stays on the same spot the whole time. His chest and hips face the
+> camera the entire clip. No walking, no turning, no spinning, no
+> extra strikes. Even lighting, bare feet, tight athletic kit, no
+> props.
+
+Write a must-see beat checklist next to the prompt (time window → what
+must be visible) and regenerate the video if any beat fails — a hidden
+foot cannot be retargeted, and regeneration is cheaper than a wasted
+pass.
+
+## Expect the model to disobey
+
+Every plate so far deviated from its prompt somewhere: a left-knee jump
+delivered as right-knee, an extended kick delivered as a knee snap, an
+opening T-pose delivered as an A-pose. None of that matters IF you take
+the beats and limbs from `analyze_landmarks.py` instead of from the
+prompt (docs/PITFALLS.md #5–6). Prompt for what you want; retarget what
+you got.
diff --git a/docs/RIG.md b/docs/RIG.md
new file mode 100644
index 0000000..6542b98
--- /dev/null
+++ b/docs/RIG.md
@@ -0,0 +1,90 @@
+# Mixamo rig conventions
+
+The conventions below hold for every Mixamo character (same skeleton,
+same spaces, same channel rules). The concrete numbers are the **Y Bot
+reference measurements**; your own character's numbers are measured
+into `rig_profile.json` by `pipeline/setup_rig.py` and override them
+throughout the pipeline.
+
+Measured facts about the Mixamo Y Bot as imported by Blender from FBX.
+The pipeline's constants (`REST`/`LEN` in `pipeline/lift_to_mixamo.py`)
+come from these measurements. `pipeline/setup_rig.py` validates a fresh
+import against them.
+
+## Scene
+
+| Object | Role |
+|---|---|
+| `Armature` | only transform root — rotation X = 90°, scale 0.01 |
+| `Alpha_Surface` | body skin (17k verts, max 4 influences/vert) |
+| `Alpha_Joints` | decorative joint spheres (ignore for motion) |
+
+Nothing else. No cameras, no lights, no empties, no constraints.
+
+## Spaces and units (the part that breaks people)
+
+Mixamo FBX is **Y-up centimeters**; the import wraps it in the
+armature's X=90° rotation and 0.01 scale:
+
+| Space | Up | Character forward | Character left | Units |
+|---|---|---|---|---|
+| Bone/pose local (Mixamo) | +Y | +Z (bone aim) | +X | **cm** |
+| World after import | +Z | **−Y** | +X | m |
+| Estimator landmarks | −Y (y is down) | −Z (z<0 toward camera) | +X | m |
+
+Consequences the code lives by:
+
+- Animate **pose bones**, never the armature object.
+- **Hips is the only bone that translates.** Its `location` is
+ pose-local **centimeters**: `x → world X`, `y → world Z (height)`,
+ `z → world −Y (forward)`. A hip at world height h keys
+ `location.y = (h − 0.99792) * 100`.
+- Every other bone: `rotation_quaternion (w, x, y, z)` only; location
+ stays zero (keyed at zero every frame so stale channels can't leak).
+- 30 fps, integer frames, frame 1 = first pose, linear interpolation.
+- Measure world positions ONLY as
+ `(arm.matrix_world @ pose_bone.matrix).to_translation()` after
+ `view_layer.update()`. (`pb.head`, or composing pose matrices through
+ `matrix_world`, both give wrong answers on this rig.)
+- Aim bones in **armature space** (centimeters). Building a world-space
+ matrix (scale 0.01) and writing it onto a pose bone sends limbs 100×
+ away.
+- **No Blender IK, ever.** Constraint IK explodes this rig (feet at
+ −81 m historically). Feet are planted by searching the hip height
+ until the support foot reaches ground, plus Z-only foot flattening.
+- Blender 5.x slotted actions: fcurves live in
+ `action.layers[].strips[].channelbag(slot)` — old `action.fcurves`
+ is gone.
+
+## Bones (65, prefix `mixamorig:` — never rename)
+
+```
+Hips → Spine → Spine1 → Spine2 → {Neck → Head → HeadTop_End,
+ L/R Shoulder → Arm → ForeArm → Hand → 5×(1..4 fingers)}
+Hips → L/R UpLeg → Leg → Foot → ToeBase → Toe_End
+```
+
+Tip bones (`*4`, `HeadTop_End`, `*Toe_End`) carry no skin weights —
+leave them at rest (the pipeline skips keying them).
+
+## Key measurements (world meters, rest)
+
+| Landmark | Value |
+|---|---|
+| Hips | (0, 0, **0.998**) |
+| Head | (0, 0, 1.60) |
+| Hands | (±0.738, 0.062, 1.436) — wrist span 1.476 |
+| Feet (ankle) | (±0.091, 0.026, **0.105**) ← ground contact height |
+| Flat-foot ball / toe z | ~0.034 / ~0.031 |
+| Ball-plant (heel up) toe z | ~0.03, ankle ~0.11 |
+
+| Chain | Length (m) |
+|---|---|
+| Shoulder (clavicle) | 0.129 — you cannot "move the socket" more than this |
+| Upper arm / forearm / hand | 0.274 / 0.276 / 0.110 |
+| Thigh / shin / foot | 0.406 / 0.421 / 0.157 |
+| Spine1 / Spine2 / Neck / Head | 0.135 / 0.123 / 0.108 / 0.196 |
+
+Full-arm reach (arm+forearm) ≈ 0.55 m; with hand ≈ 0.66 m.
+A ~90° knee puts the ankle ≈ `sqrt(thigh² + shin²)` ≈ 0.58 m from the
+hip — closer than that folds the calf into the thigh.
diff --git a/docs/requirements_gvhmr_windows.txt b/docs/requirements_gvhmr_windows.txt
new file mode 100644
index 0000000..9504bb9
--- /dev/null
+++ b/docs/requirements_gvhmr_windows.txt
@@ -0,0 +1,47 @@
+# Windows-adjusted GVHMR requirements (C:\mixamo 4080 box).
+# Diff vs requirements.txt:
+# - pytorch3d: dropped (pinned wheel is linux-only; only needed for their
+# mesh renderer / visualization — the Mixamo adapter only needs joints)
+# - cython_bbox: dropped (no Windows wheel; bbox tracking extra we do not hit
+# with a single-person locked plate)
+# - chumpy: dropped (setup.py breaks under uv build isolation; only needed to
+# load legacy SMPL .pkl body models — the adapter uses SMPL-X .npz)
+# - jupyter / black / ipdb: dropped (dev-only)
+# Everything else identical, same pins.
+
+# PyTorch
+--extra-index-url https://download.pytorch.org/whl/cu121
+torch==2.3.0+cu121
+torchvision==0.18.0+cu121
+timm==0.9.12 # For HMR2.0a feature extraction
+
+# Lightning + Hydra
+lightning==2.3.0
+hydra-core==1.3
+hydra-zen
+hydra_colorlog
+rich
+
+# Common utilities
+numpy==1.23.5
+matplotlib
+setuptools>=68.0
+tensorboardX
+opencv-python
+ffmpeg-python
+scikit-image
+termcolor
+einops
+imageio==2.34.1
+av==13.0.0 # imageio[pyav], improved performance over imageio[ffmpeg]
+joblib
+
+# 3D-Vision
+trimesh
+smplx
+wis3d
+pycolmap
+
+# 2D-Pose
+ultralytics==8.2.42 # YOLO
+lapx
diff --git a/media/showcase.gif b/media/showcase.gif
new file mode 100644
index 0000000..775e59c
Binary files /dev/null and b/media/showcase.gif differ
diff --git a/pipeline/analyze_landmarks.py b/pipeline/analyze_landmarks.py
new file mode 100644
index 0000000..97939aa
--- /dev/null
+++ b/pipeline/analyze_landmarks.py
@@ -0,0 +1,97 @@
+"""Numeric beat detection over a landmarks.json — the tool that writes
+the beat sheet's evidence column. Run this BEFORE writing an action_spec
+and take every limb decision from these numbers, never from
+screen-reading stills (facing the camera, viewer-left is the
+character's RIGHT — every screen-read limb guess in this project's
+history was wrong at least once).
+
+Usage:
+ python pipeline\\analyze_landmarks.py --landmarks plates\\<plate>\\landmarks.json [--step 6]
+
+Prints a per-N-frame table plus detected events:
+ - pelvis baseline / dips (ducks, crouches) / peaks (jumps)
+ - windows where both feet are airborne (true flight)
+ - single-leg-up windows (kicks, knees) with the acting side
+ - punch windows per arm (wrist depth toward camera, z < -0.32)
+ - T-pose spans (wrist span > 1.22 m) — bind candidates
+ - shoulder-line yaw (facing wobble vs punch rotation)
+
+True joint heights need `pelvis_height` in the landmarks (the GVHMR
+estimator writes it); without it, heights fall back to hip-relative.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import numpy as np
+
+REPO = Path(__file__).resolve().parents[1]
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--landmarks", required=True, type=Path)
+ ap.add_argument("--step", type=int, default=6)
+ args = ap.parse_args()
+ lm = args.landmarks if args.landmarks.is_absolute() else REPO / args.landmarks
+ d = json.loads(lm.read_text(encoding="utf-8"))
+ F = d["frames"]
+ n = len(F)
+
+ def w(i, name):
+ l = F[i]["world"][name]
+ return np.array([l["x"], l["y"], l["z"]])
+
+ has_ph = "pelvis_height" in F[0]
+ ph = np.array([f.get("pelvis_height", 0.0) for f in F])
+
+ def height(i, name):
+ # y is down and per-frame mid-hip centered; pelvis_height restores ground.
+ return (ph[i] if has_ph else 0.0) - w(i, name)[1] - (0.0 if has_ph else 0.0)
+
+ la_h = np.array([height(i, "left_ankle") for i in range(n)])
+ ra_h = np.array([height(i, "right_ankle") for i in range(n)])
+ lk_h = np.array([height(i, "left_knee") for i in range(n)])
+ rk_h = np.array([height(i, "right_knee") for i in range(n)])
+ lw_z = np.array([w(i, "left_wrist")[2] for i in range(n)])
+ rw_z = np.array([w(i, "right_wrist")[2] for i in range(n)])
+ span = np.array([np.linalg.norm(w(i, "left_wrist")[[0, 2]] - w(i, "right_wrist")[[0, 2]]) for i in range(n)])
+ yaw = np.array([np.degrees(np.arctan2(-(w(i, "left_shoulder") - w(i, "right_shoulder"))[2],
+ (w(i, "left_shoulder") - w(i, "right_shoulder"))[0])) for i in range(n)])
+
+ print(" f | ph | laH raH | lkH rkH | lwZ rwZ | span yaw")
+ for i in range(0, n, max(1, args.step)):
+ print(f"{i+1:4d} | {ph[i]:.3f} | {la_h[i]:.2f} {ra_h[i]:.2f} | {lk_h[i]:.2f} {rk_h[i]:.2f} "
+ f"| {lw_z[i]:+.2f} {rw_z[i]:+.2f} | {span[i]:.2f} {yaw[i]:+4.0f}")
+
+ def segments(idx, gap=3):
+ return np.split(idx, np.where(np.diff(idx) > gap)[0] + 1) if len(idx) else []
+
+ if has_ph:
+ base = float(np.median(ph[: max(10, n // 12)]))
+ print(f"\npelvis baseline {base:.3f} | min {ph.min():.3f} @ f{ph.argmin()+1} | max {ph.max():.3f} @ f{ph.argmax()+1}")
+ air = np.where((la_h > 0.25) & (ra_h > 0.25))[0]
+ for s in segments(air):
+ print(f"both feet airborne (>0.25): f{s[0]+1}-f{s[-1]+1} "
+ f"(peak lower-ankle {np.minimum(la_h, ra_h)[s].max():.2f} m)")
+ for nm, up, other in (("left", la_h, ra_h), ("right", ra_h, la_h)):
+ leg = np.where((up > 0.30) & (other < 0.15))[0]
+ for s in segments(leg):
+ print(f"{nm} leg up on {('right' if nm == 'left' else 'left')} support: "
+ f"f{s[0]+1}-f{s[-1]+1} (ankle peak {up[s].max():.2f} @ f{s[up[s].argmax()]+1})")
+
+ for nm, z in (("left", lw_z), ("right", rw_z)):
+ for s in segments(np.where(z < -0.32)[0]):
+ print(f"{nm} wrist toward camera (z<-0.32): f{s[0]+1}-f{s[-1]+1} (min {z[s].min():+.2f} @ f{s[z[s].argmin()]+1})")
+
+ for s in segments(np.where(span > 1.22)[0], gap=4):
+ print(f"T-pose span (>1.22 m): f{s[0]+1}-f{s[-1]+1}")
+ print(f"shoulder-line yaw range: {yaw.min():+.0f}..{yaw.max():+.0f} deg "
+ "(punches rotate shoulders ±40-60 without turning the hips)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pipeline/apply_mixamo_fk.py b/pipeline/apply_mixamo_fk.py
new file mode 100644
index 0000000..edde8ce
--- /dev/null
+++ b/pipeline/apply_mixamo_fk.py
@@ -0,0 +1,493 @@
+"""Generic FK apply: lifted joints -> live Y Bot action. Runs inside
+Blender 5.1 (via the official Blender MCP, or pipeline/blender_exec.py).
+
+Per-frame the joints file carries the support foot ("plant": left /
+right / both / none), the fist amount, the rest-blend amount and the
+estimator's absolute pelvis height. This module aims each mixamorig
+bone at its lifted joint (armature space, FK only — no constraints, no
+IK), then resolves the hip height:
+
+ left/right binary-search hips Y so that foot lands at GROUND_Z,
+ then flatten it (Z-only, keeps estimator XZ + heading)
+ both plant the lower foot, flatten both if near ground
+ none airborne: integrate the estimator's pelvis arc from the
+ last applied height (continuous takeoff, ballistic flight)
+ rest>=0.65 exact rest height (start/end T-pose)
+
+Usage inside Blender:
+ import apply_mixamo_fk
+ result = apply_mixamo_fk.run("action_specs/<motion>.json")
+Then, separately (keeps the long keying pass in one socket request):
+ apply_mixamo_fk.dump_curves("action_specs/<motion>.json")
+ apply_mixamo_fk.run_stills_render("action_specs/<motion>.json", [1, ...])
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import bpy
+from mathutils import Quaternion, Vector
+
+REPO = Path(__file__).resolve().parents[1]
+GROUND_Z = 0.105 # Y Bot rest ankle height (flat-foot contact)
+HIP_HEIGHT = 0.99792 # Y Bot rest hip height
+FPS = 30
+
+# Character-specific overrides from rig_profile.json (setup_rig.py) —
+# any Mixamo character, not just Y Bot.
+_PROFILE = REPO / "rig_profile.json"
+if _PROFILE.exists():
+ try:
+ _p = json.loads(_PROFILE.read_text(encoding="utf-8"))
+ GROUND_Z = float(_p["ground_z"])
+ HIP_HEIGHT = float(_p["hip_height"])
+ except Exception:
+ pass
+
+AIM = [
+ ("mixamorig:Spine", "spine1"),
+ ("mixamorig:Spine1", "spine2"),
+ ("mixamorig:Spine2", "neck"),
+ ("mixamorig:Neck", "head"),
+ ("mixamorig:Head", "head"),
+ ("mixamorig:LeftShoulder", "l_arm"),
+ ("mixamorig:LeftArm", "l_elbow"),
+ ("mixamorig:LeftForeArm", "l_wrist"),
+ ("mixamorig:LeftHand", "l_hand"),
+ ("mixamorig:RightShoulder", "r_arm"),
+ ("mixamorig:RightArm", "r_elbow"),
+ ("mixamorig:RightForeArm", "r_wrist"),
+ ("mixamorig:RightHand", "r_hand"),
+ ("mixamorig:LeftUpLeg", "l_knee"),
+ ("mixamorig:LeftLeg", "l_ankle"),
+ ("mixamorig:LeftFoot", "l_foot"),
+ ("mixamorig:LeftToeBase", "l_toe"),
+ ("mixamorig:RightUpLeg", "r_knee"),
+ ("mixamorig:RightLeg", "r_ankle"),
+ ("mixamorig:RightFoot", "r_foot"),
+ ("mixamorig:RightToeBase", "r_toe"),
+]
+
+
+def _fist_quats() -> dict:
+ """Original procedural fist (no third-party motion data).
+
+ Finger curl on this rig is a positive rotation about the bone-local
+ X axis for both hands (80 deg base, 95 deg mid, 50 deg tip). Thumb
+ bones bend on a DIFFERENT axis mix: the fold that wraps the thumb
+ across the curled fingers is mostly negative-X plus a y/z opposition
+ component that mirrors between hands. Positive-X on a thumb
+ hyperextends it outward — the original bug this replaces. Values
+ validated visually on the rig (palm/top/front close-up renders).
+ """
+ seg1 = (0.766044, 0.642788, 0.0, 0.0) # 80 deg about X
+ seg2 = (0.67559, 0.737277, 0.0, 0.0) # 95 deg about X
+ seg3 = (0.906308, 0.422618, 0.0, 0.0) # 50 deg about X
+ out = {}
+ for side, zs in (("Left", -1.0), ("Right", 1.0)):
+ out[f"mixamorig:{side}HandThumb1"] = (0.961, 0.069, 0.165 * zs, 0.207 * zs)
+ out[f"mixamorig:{side}HandThumb2"] = (0.766, -0.399, 0.161 * zs, 0.476 * zs)
+ out[f"mixamorig:{side}HandThumb3"] = (0.940, -0.210, 0.136 * zs, 0.231 * zs)
+ for fn in ("Index", "Middle", "Ring", "Pinky"):
+ out[f"mixamorig:{side}Hand{fn}1"] = seg1
+ out[f"mixamorig:{side}Hand{fn}2"] = seg2
+ out[f"mixamorig:{side}Hand{fn}3"] = seg3
+ return out
+
+
+FIST = _fist_quats()
+
+
+def rpath(p) -> Path:
+ p = Path(p)
+ return p if p.is_absolute() else (REPO / p)
+
+
+def v(seq) -> Vector:
+ return Vector((float(seq[0]), float(seq[1]), float(seq[2])))
+
+
+def world_loc(arm, name: str) -> Vector:
+ pb = arm.pose.bones[name]
+ return (arm.matrix_world @ pb.matrix).to_translation()
+
+
+def reset_pose(arm) -> None:
+ for pb in arm.pose.bones:
+ pb.rotation_mode = "QUATERNION"
+ pb.rotation_quaternion = Quaternion((1.0, 0.0, 0.0, 0.0))
+ pb.location = Vector((0.0, 0.0, 0.0))
+ pb.scale = Vector((1.0, 1.0, 1.0))
+ bpy.context.view_layer.update()
+
+
+def to_arm(arm, world_m: Vector) -> Vector:
+ return arm.matrix_world.inverted() @ world_m
+
+
+def dir_to_arm(arm, world_dir: Vector) -> Vector:
+ return (arm.matrix_world.to_3x3().inverted() @ world_dir).normalized()
+
+
+def aim_bone(arm, name: str, target_world: Vector) -> None:
+ """Aim bone +Y at a world-meter target. All math in ARMATURE space
+ (centimeters) — never build pose matrices through matrix_world."""
+ pb = arm.pose.bones[name]
+ pb.rotation_mode = "QUATERNION"
+ pb.rotation_quaternion = Quaternion((1.0, 0.0, 0.0, 0.0))
+ if name != "mixamorig:Hips":
+ pb.location = Vector((0.0, 0.0, 0.0))
+ bpy.context.view_layer.update()
+ head = pb.matrix.to_translation()
+ target = to_arm(arm, target_world)
+ direction = target - head
+ if direction.length < 1e-5:
+ return
+ rot = pb.y_axis.normalized().rotation_difference(direction.normalized())
+ mat = rot.to_matrix().to_4x4() @ pb.matrix.to_3x3().to_4x4()
+ mat.translation = head
+ pb.matrix = mat
+ bpy.context.view_layer.update()
+ q = pb.rotation_quaternion.copy()
+ if name != "mixamorig:Hips":
+ pb.location = Vector((0.0, 0.0, 0.0))
+ pb.rotation_quaternion = q
+ bpy.context.view_layer.update()
+
+
+def set_hips(arm, basis_x, basis_y, basis_z, loc_world) -> None:
+ """Hips rotation from the lifted basis; location in Mixamo pose-cm
+ (x -> world X, y -> world Z height, z -> world -Y forward)."""
+ pb = arm.pose.bones["mixamorig:Hips"]
+ pb.rotation_mode = "QUATERNION"
+ pb.rotation_quaternion = Quaternion((1.0, 0.0, 0.0, 0.0))
+ pb.location = Vector((0.0, 0.0, 0.0))
+ bpy.context.view_layer.update()
+ up_arm = dir_to_arm(arm, basis_z)
+ left_arm = dir_to_arm(arm, basis_x)
+ rot_y = pb.y_axis.normalized().rotation_difference(up_arm)
+ mat = rot_y.to_matrix().to_4x4() @ pb.matrix.to_3x3().to_4x4()
+ mat.translation = pb.matrix.to_translation()
+ pb.matrix = mat
+ bpy.context.view_layer.update()
+ x_now = pb.x_axis.normalized()
+ left_flat = left_arm - up_arm * left_arm.dot(up_arm)
+ if left_flat.length > 1e-5:
+ twist = x_now.rotation_difference(left_flat.normalized())
+ axis, ang = twist.to_axis_angle()
+ if axis.dot(pb.y_axis) < 0.0:
+ ang = -ang
+ twist_y = Quaternion(pb.y_axis.normalized(), ang)
+ mat = twist_y.to_matrix().to_4x4() @ pb.matrix.to_3x3().to_4x4()
+ mat.translation = pb.matrix.to_translation()
+ pb.matrix = mat
+ bpy.context.view_layer.update()
+ q = pb.rotation_quaternion.copy()
+ pb.location = Vector(
+ (loc_world.x * 100.0, (loc_world.z - HIP_HEIGHT) * 100.0, -loc_world.y * 100.0)
+ )
+ pb.rotation_quaternion = q
+ bpy.context.view_layer.update()
+
+
+def plant_hips(arm, hint_y: float, loc_x: float, loc_z: float, foot: str) -> float:
+ """Binary-search hips.location.y (cm) until *foot* lands at GROUND_Z."""
+ hips = arm.pose.bones["mixamorig:Hips"]
+ lo, hi = hint_y - 55.0, hint_y + 40.0
+ best_y, best_err = hint_y, 1e9
+ for _ in range(15):
+ mid = 0.5 * (lo + hi)
+ hips.location = (loc_x, mid, loc_z)
+ bpy.context.view_layer.update()
+ zf = world_loc(arm, foot).z
+ err = abs(zf - GROUND_Z)
+ if err < best_err:
+ best_err, best_y = err, mid
+ if zf > GROUND_Z:
+ hi = mid
+ else:
+ lo = mid
+ hips.location = (loc_x, best_y, loc_z)
+ bpy.context.view_layer.update()
+ return best_y
+
+
+def flatten_foot(arm, side: str) -> None:
+ """Z-only ground snap for a near-ground foot. Keeps estimator XZ and
+ the foot's own heading (never a world axis).
+
+ The toe aim needs a target FORWARD of the ball along the foot
+ heading — aiming ToeBase at its own head position is degenerate and
+ bends the toes randomly.
+ """
+ foot_b = f"mixamorig:{side}Foot"
+ toe_b = f"mixamorig:{side}ToeBase"
+ ankle = world_loc(arm, foot_b)
+ ball = world_loc(arm, toe_b)
+ if ankle.z > 0.20:
+ return # genuinely lifted — leave it alone
+ heading = Vector((ball.x - ankle.x, ball.y - ankle.y, 0.0))
+ if heading.length < 0.02:
+ pb = arm.pose.bones[foot_b]
+ y_w = (arm.matrix_world.to_3x3() @ pb.y_axis)
+ heading = Vector((y_w.x, y_w.y, 0.0))
+ if heading.length < 1e-5:
+ return
+ heading.normalize()
+ aim_bone(arm, foot_b, Vector((ball.x, ball.y, 0.034)))
+ ball2 = world_loc(arm, toe_b)
+ aim_bone(arm, toe_b, Vector((ball2.x + heading.x * 0.06, ball2.y + heading.y * 0.06, 0.028)))
+
+
+def apply_fingers(arm, amount: float) -> None:
+ ident = Quaternion((1.0, 0.0, 0.0, 0.0))
+ for name, quat in FIST.items():
+ if name not in arm.pose.bones:
+ continue
+ pb = arm.pose.bones[name]
+ pb.rotation_mode = "QUATERNION"
+ fq = Quaternion(quat)
+ fq.normalize()
+ pb.rotation_quaternion = ident.slerp(fq, amount)
+ pb.location = Vector((0.0, 0.0, 0.0))
+
+
+def ensure_action(arm, name: str, end: int):
+ if arm.animation_data is None:
+ arm.animation_data_create()
+ if name in bpy.data.actions:
+ bpy.data.actions.remove(bpy.data.actions[name])
+ action = bpy.data.actions.new(name)
+ arm.animation_data.action = action
+ try:
+ slot = action.slots.new(id_type="OBJECT", name="Armature")
+ arm.animation_data.action_slot = slot
+ except Exception:
+ pass
+ scene = bpy.context.scene
+ scene.render.fps = FPS
+ scene.frame_start = 1
+ scene.frame_end = end
+ scene.frame_set(1)
+ return action
+
+
+def key_pose(arm, f: int) -> None:
+ for pb in arm.pose.bones:
+ if pb.name.endswith("_End") or pb.name.endswith("4"):
+ continue
+ pb.rotation_mode = "QUATERNION"
+ pb.keyframe_insert("rotation_quaternion", frame=f)
+ if pb.name == "mixamorig:Hips":
+ pb.keyframe_insert("location", frame=f)
+ else:
+ pb.location = Vector((0.0, 0.0, 0.0))
+ pb.keyframe_insert("location", frame=f)
+
+
+def set_linear(action) -> None:
+ """Blender 5.x slotted actions: write through the channelbag."""
+ try:
+ for layer in action.layers:
+ for strip in layer.strips:
+ for slot in action.slots:
+ bag = strip.channelbag(slot)
+ if not bag:
+ continue
+ for fc in bag.fcurves:
+ for kp in fc.keyframe_points:
+ kp.interpolation = "LINEAR"
+ except Exception:
+ if getattr(action, "fcurves", None):
+ for fc in action.fcurves:
+ for kp in fc.keyframe_points:
+ kp.interpolation = "LINEAR"
+
+
+def measure(arm, f: int) -> dict:
+ bpy.context.scene.frame_set(f)
+ bpy.context.view_layer.update()
+
+ def w(n):
+ p = world_loc(arm, n)
+ return [round(p.x, 4), round(p.y, 4), round(p.z, 4)]
+
+ return {
+ "frame": f,
+ "hips": w("mixamorig:Hips"),
+ "l_hand": w("mixamorig:LeftHand"),
+ "r_hand": w("mixamorig:RightHand"),
+ "l_foot": w("mixamorig:LeftFoot"),
+ "r_foot": w("mixamorig:RightFoot"),
+ "l_toe": w("mixamorig:LeftToeBase"),
+ "r_toe": w("mixamorig:RightToeBase"),
+ "head": w("mixamorig:Head"),
+ }
+
+
+def run(spec_path: str) -> dict:
+ spec = json.loads(rpath(spec_path).read_text(encoding="utf-8"))
+ payload = json.loads(rpath(spec["joints_out"]).read_text(encoding="utf-8"))
+ frames = payload["frames"]
+ end = len(frames)
+ src_fps = float(payload.get("src_fps", 24))
+ dst_fps = float(payload.get("dst_fps", 30))
+
+ arm = bpy.data.objects["Armature"]
+ bpy.context.view_layer.objects.active = arm
+ if bpy.context.mode != "POSE":
+ bpy.ops.object.mode_set(mode="POSE")
+ action = ensure_action(arm, spec["action_name"], end)
+
+ prev_hip_y = 0.0
+ prev_ph = None
+ for fr in frames:
+ f = int(fr["frame"])
+ rest = float(fr.get("rest_amount", 0.0))
+ fist = float(fr.get("fist_amount", 0.0))
+ plant = fr.get("plant", "both")
+ ph = float(fr.get("pelvis_height", 0.0))
+ if prev_ph is None:
+ prev_ph = ph
+ reset_pose(arm)
+ bx, by, bz = v(fr["basis_x"]), v(fr["basis_y"]), v(fr["basis_z"])
+ hips_w = v(fr["hips"])
+ set_hips(arm, bx, by, bz, hips_w)
+ loc_x = hips_w.x * 100.0
+ loc_z = -hips_w.y * 100.0
+ hint = (hips_w.z - HIP_HEIGHT) * 100.0
+ up = v(fr["basis_z"])
+ neck_p = v(fr["neck"])
+ head_flat = v(fr["head"]) - neck_p
+ head_flat.z = 0.0
+ for bone, key in AIM:
+ if bone == "mixamorig:Neck":
+ aim_bone(arm, bone, neck_p + up * 0.11 + head_flat * 0.25)
+ elif bone == "mixamorig:Head":
+ aim_bone(arm, bone, neck_p + up * 0.28 + head_flat * 0.15)
+ else:
+ aim_bone(arm, bone, v(fr[key]))
+ apply_fingers(arm, fist)
+
+ if rest >= 0.65:
+ hips = arm.pose.bones["mixamorig:Hips"]
+ hips.location = (loc_x, 0.0, loc_z)
+ bpy.context.view_layer.update()
+ elif plant == "none":
+ # Airborne: no plant, no snapping. Hip height integrates the
+ # estimator's real pelvis arc from the last applied height.
+ hips = arm.pose.bones["mixamorig:Hips"]
+ hips.location = (loc_x, prev_hip_y + (ph - prev_ph) * 100.0, loc_z)
+ bpy.context.view_layer.update()
+ elif plant in ("left", "right"):
+ foot = "mixamorig:LeftFoot" if plant == "left" else "mixamorig:RightFoot"
+ plant_hips(arm, hint, loc_x, loc_z, foot)
+ flatten_foot(arm, "Left" if plant == "left" else "Right")
+ else: # both
+ la = world_loc(arm, "mixamorig:LeftFoot").z
+ ra = world_loc(arm, "mixamorig:RightFoot").z
+ lower = "mixamorig:LeftFoot" if la <= ra else "mixamorig:RightFoot"
+ other = "Right" if la <= ra else "Left"
+ plant_hips(arm, hint, loc_x, loc_z, lower)
+ flatten_foot(arm, "Left" if lower.endswith("LeftFoot") else "Right")
+ flatten_foot(arm, other)
+ prev_hip_y = float(arm.pose.bones["mixamorig:Hips"].location[1])
+ prev_ph = ph
+ key_pose(arm, f)
+
+ set_linear(action)
+ bpy.context.scene.frame_set(1)
+ bpy.context.view_layer.update()
+
+ qa_dest = [max(1, min(end, int(round((sf - 1) * dst_fps / src_fps + 1)))) for sf in spec.get("qa_src_frames", [])]
+ samples = [measure(arm, f) for f in qa_dest]
+ clip_dir = rpath(spec["clip_dir"])
+ clip_dir.mkdir(parents=True, exist_ok=True)
+ (clip_dir / "retarget_samples.json").write_text(json.dumps(samples, indent=2), encoding="utf-8")
+ result = {
+ "action": spec["action_name"],
+ "frames": end,
+ "samples": samples,
+ "constraints": [c.name for pb in arm.pose.bones for c in pb.constraints],
+ }
+ (clip_dir / "apply_result.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
+ return result
+
+
+def run_stills_render(spec_path: str, dest_frames) -> dict:
+ """Front + side stills via a temporary camera + Workbench render.
+
+ Window-independent (viewport screenshots capture black when the
+ Blender window is occluded or minimized). The camera is removed
+ afterward so the scene stays Armature + meshes only.
+ """
+ import math
+
+ spec = json.loads(rpath(spec_path).read_text(encoding="utf-8"))
+ pose_dir = rpath(spec["clip_dir"]) / "poses"
+ pose_dir.mkdir(parents=True, exist_ok=True)
+ arm = bpy.data.objects["Armature"]
+ scene = bpy.context.scene
+
+ cam_data = bpy.data.cameras.new("QA_Camera")
+ cam = bpy.data.objects.new("QA_Camera", cam_data)
+ scene.collection.objects.link(cam)
+ old_cam = scene.camera
+ old_engine = scene.render.engine
+ old_res = (scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage)
+ old_path = scene.render.filepath
+ scene.camera = cam
+ scene.render.engine = "BLENDER_WORKBENCH"
+ scene.render.resolution_x, scene.render.resolution_y = 960, 720
+ scene.render.resolution_percentage = 100
+
+ written = []
+ try:
+ for f in dest_frames:
+ scene.frame_set(int(f))
+ bpy.context.view_layer.update()
+ hips = (arm.matrix_world @ arm.pose.bones["mixamorig:Hips"].matrix).to_translation()
+ views = {
+ "front": (Vector((hips.x, hips.y - 3.9, max(0.95, hips.z))), (math.radians(90), 0.0, 0.0)),
+ "side": (Vector((hips.x + 3.9, hips.y, max(0.95, hips.z))), (math.radians(90), 0.0, math.radians(90))),
+ }
+ for vn, (loc, rot) in views.items():
+ cam.location = loc
+ cam.rotation_euler = rot
+ dest = pose_dir / f"{vn}_{int(f):04d}.png"
+ scene.render.filepath = str(dest)
+ bpy.ops.render.render(write_still=True)
+ written.append(dest.name)
+ finally:
+ scene.camera = old_cam
+ scene.render.engine = old_engine
+ scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = old_res
+ scene.render.filepath = old_path
+ bpy.data.objects.remove(cam)
+ bpy.data.cameras.remove(cam_data)
+ return {"stills": written}
+
+
+def dump_curves(spec_path: str) -> dict:
+ """Every bone, every frame: pose channels + world location."""
+ spec = json.loads(rpath(spec_path).read_text(encoding="utf-8"))
+ arm = bpy.data.objects["Armature"]
+ end = bpy.context.scene.frame_end
+ out = []
+ for f in range(1, end + 1):
+ bpy.context.scene.frame_set(f)
+ bpy.context.view_layer.update()
+ bones = {}
+ for pb in arm.pose.bones:
+ wl = (arm.matrix_world @ pb.matrix).to_translation()
+ bones[pb.name] = {
+ "location": [round(v, 6) for v in pb.location],
+ "rotation_quaternion": [round(v, 6) for v in pb.rotation_quaternion],
+ "world_location": [round(wl.x, 6), round(wl.y, 6), round(wl.z, 6)],
+ }
+ out.append({"frame": f, "bones": bones})
+ clip_dir = rpath(spec["clip_dir"])
+ (clip_dir / "curves.json").write_text(json.dumps({"frames": out}), encoding="utf-8")
+ return {"curves_frames": len(out)}
diff --git a/pipeline/blender_exec.py b/pipeline/blender_exec.py
new file mode 100644
index 0000000..a7c733d
--- /dev/null
+++ b/pipeline/blender_exec.py
@@ -0,0 +1,55 @@
+"""Run a Python file inside the live Blender session, over the official
+Blender MCP add-on's bridge socket (localhost:9876).
+
+This is the direct path an agent (or a human) can use when the MCP
+client layer is not available — the add-on's protocol is null-delimited
+JSON: {"type": "execute", "code": "<python>", "strict_json": bool}.
+The executed code should set `result = {...}` for a structured reply;
+stdout/stderr are captured into the response.
+
+Usage:
+ python pipeline\\blender_exec.py <file.py> [timeout_seconds]
+
+Blender must be open with the MCP add-on's server running (it
+autostarts if "Allow Online Access" is enabled in Preferences >
+System > Network). A long apply pass blocks Blender's UI until it
+finishes — that is normal.
+"""
+
+from __future__ import annotations
+
+import json
+import socket
+import sys
+
+HOST, PORT = "localhost", 9876
+
+
+def execute_file(path: str, timeout: float = 120.0) -> dict:
+ code = open(path, encoding="utf-8").read()
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.settimeout(timeout)
+ s.connect((HOST, PORT))
+ s.sendall((json.dumps({"type": "execute", "code": code, "strict_json": False}) + "\0").encode())
+ buf = bytearray()
+ while b"\0" not in buf:
+ chunk = s.recv(65536)
+ if not chunk:
+ break
+ buf.extend(chunk)
+ s.close()
+ if b"\0" not in buf:
+ raise SystemExit("no complete response from Blender (is the add-on server running?)")
+ return json.loads(bytes(buf[: buf.index(b"\0")]).decode())
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ raise SystemExit(__doc__)
+ t = float(sys.argv[2]) if len(sys.argv) > 2 else 120.0
+ res = execute_file(sys.argv[1], t)
+ print(json.dumps(res, indent=1))
+ # Propagate Blender-side failures as a nonzero exit so shell chains
+ # (`&&`) cannot mistake an in-Blender traceback for success.
+ if res.get("status") != "ok":
+ sys.exit(1)
diff --git a/pipeline/estimate_pose_gvhmr.py b/pipeline/estimate_pose_gvhmr.py
new file mode 100644
index 0000000..fb03050
--- /dev/null
+++ b/pipeline/estimate_pose_gvhmr.py
@@ -0,0 +1,365 @@
+"""GVHMR estimator: video plate -> landmarks.json.
+
+The estimator step of the video -> Mixamo Y Bot pipeline (see
+docs/PIPELINE.md). Runs GVHMR (SMPL-X mesh regression) on a locked-
+camera plate and emits a 33-landmark landmarks.json in a MediaPipe-
+compatible convention, plus an absolute `pelvis_height` per frame:
+
+ world: per-frame mid-hip origin, y DOWN, z NEGATIVE toward camera,
+ meters (a punch toward the camera drives wrist z below -0.3)
+ image: normalized [0..1], x right, y down
+ pelvis_height: meters above the estimator's ground plane (y=0 in
+ GVHMR's gravity-aligned frame) — used by airborne windows
+
+Run with the GVHMR venv (see docs/INSTALL.md), from anywhere:
+
+ <repo>\\tools\\GVHMR\\.venv\\Scripts\\python.exe \\
+ pipeline\\estimate_pose_gvhmr.py \\
+ --video plates\\<plate>\\<clip>.mp4 \\
+ --out plates\\<plate>\\landmarks.json
+
+Joints come from the SMPL 24-joint regressor applied to the predicted
+mesh (same path as GVHMR's own render_global): SMPL-X verts ->
+smplx2smpl_sparse -> J_regressor. Landmarks MediaPipe has but SMPL does
+not (nose, heels, hand points, face) are synthesized from the torso
+basis — the lift only uses them for direction hints, not geometry.
+
+GVHMR gives real depth, plausible proportions and no per-frame Z
+spikes; it still does not know Mixamo bone lengths and will not plant
+feet. That stays the lift's job.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parents[1]
+GVHMR_ROOT = Path(os.environ.get("GVHMR_ROOT", REPO / "tools" / "GVHMR"))
+
+# hydra configs and every checkpoint path in GVHMR are relative to the
+# GVHMR repo root. chdir before importing hmr4d.
+os.chdir(GVHMR_ROOT)
+sys.path.insert(0, str(GVHMR_ROOT))
+
+import cv2 # noqa: E402
+import numpy as np # noqa: E402
+import torch # noqa: E402
+
+MP_NAMES = [
+ "nose",
+ "left_eye_inner", "left_eye", "left_eye_outer",
+ "right_eye_inner", "right_eye", "right_eye_outer",
+ "left_ear", "right_ear",
+ "mouth_left", "mouth_right",
+ "left_shoulder", "right_shoulder",
+ "left_elbow", "right_elbow",
+ "left_wrist", "right_wrist",
+ "left_pinky", "right_pinky",
+ "left_index", "right_index",
+ "left_thumb", "right_thumb",
+ "left_hip", "right_hip",
+ "left_knee", "right_knee",
+ "left_ankle", "right_ankle",
+ "left_heel", "right_heel",
+ "left_foot_index", "right_foot_index",
+]
+
+# SMPL 24-joint regressor indices.
+J = {
+ "pelvis": 0, "l_hip": 1, "r_hip": 2, "spine1": 3,
+ "l_knee": 4, "r_knee": 5, "spine2": 6, "l_ankle": 7, "r_ankle": 8,
+ "spine3": 9, "l_foot": 10, "r_foot": 11, "neck": 12,
+ "l_collar": 13, "r_collar": 14, "head": 15,
+ "l_shoulder": 16, "r_shoulder": 17, "l_elbow": 18, "r_elbow": 19,
+ "l_wrist": 20, "r_wrist": 21, "l_hand": 22, "r_hand": 23,
+}
+
+BODY_MODELS = GVHMR_ROOT / "inputs/checkpoints/body_models"
+CHECKPOINTS = {
+ "gvhmr": GVHMR_ROOT / "inputs/checkpoints/gvhmr/gvhmr_siga24_release.ckpt",
+ "hmr2": GVHMR_ROOT / "inputs/checkpoints/hmr2/epoch=10-step=25000.ckpt",
+ "vitpose": GVHMR_ROOT / "inputs/checkpoints/vitpose/vitpose-h-multi-coco.pth",
+ "yolo": GVHMR_ROOT / "inputs/checkpoints/yolo/yolov8x.pt",
+ # dpvo is only for moving cameras; plates are locked. Not required.
+ "smplx_neutral": BODY_MODELS / "smplx/SMPLX_NEUTRAL.npz",
+}
+
+
+def preflight() -> None:
+ missing = [f" {k}: {p}" for k, p in CHECKPOINTS.items() if not p.exists()]
+ if missing:
+ raise SystemExit(
+ "missing model files:\n" + "\n".join(missing) + "\n\n"
+ "smplx_neutral is license-gated: register at https://smpl-x.is.tue.mpg.de/ ,\n"
+ "download 'SMPL-X v1.1 (NPZ+PKL)' and copy SMPLX_NEUTRAL.npz to\n"
+ f" {BODY_MODELS / 'smplx'}\\\n"
+ "The rest are non-gated checkpoints (see docs/INSTALL.md)."
+ )
+
+
+def video_fps(path: Path) -> float:
+ cap = cv2.VideoCapture(str(path))
+ fps = cap.get(cv2.CAP_PROP_FPS) or 24.0
+ cap.release()
+ return float(fps)
+
+
+# ---------------------------------------------------------------------------
+# Stage 1 — GVHMR demo pipeline (preprocess + predict), no rendering.
+# Results are cached in <GVHMR_ROOT>/outputs/demo/<video_name>/.
+
+def run_gvhmr(video: Path) -> dict:
+ import hydra
+ from hydra import compose, initialize_config_module
+
+ from hmr4d.configs import register_store_gvhmr
+ from hmr4d.model.gvhmr.gvhmr_pl_demo import DemoPL
+ from hmr4d.utils.geo.hmr_cam import estimate_K, get_bbx_xys_from_xyxy
+ from hmr4d.utils.geo_transform import compute_cam_angvel
+ from hmr4d.utils.net_utils import detach_to_cpu
+ from hmr4d.utils.preproc import Extractor, Tracker, VitPoseExtractor
+ from hmr4d.utils.video_io_utils import get_video_lwh, get_video_reader, get_writer
+
+ with initialize_config_module(version_base="1.3", config_module="hmr4d.configs"):
+ register_store_gvhmr()
+ cfg = compose(
+ config_name="demo",
+ overrides=[f"video_name={video.stem}", "static_cam=True", "verbose=False", "use_dpvo=False"],
+ )
+ Path(cfg.output_dir).mkdir(parents=True, exist_ok=True)
+ Path(cfg.preprocess_dir).mkdir(parents=True, exist_ok=True)
+
+ # GVHMR restamps the working copy at 30 fps; frame count is unchanged
+ # and we keep our own source-fps clock for landmarks.json.
+ if not Path(cfg.video_path).exists() or get_video_lwh(video)[0] != get_video_lwh(cfg.video_path)[0]:
+ reader = get_video_reader(video)
+ writer = get_writer(cfg.video_path, fps=30, crf=23)
+ for img in reader:
+ writer.write_frame(img)
+ writer.close()
+ reader.close()
+
+ paths = cfg.paths
+ if not Path(paths.bbx).exists():
+ tracker = Tracker()
+ bbx_xyxy = tracker.get_one_track(cfg.video_path).float()
+ bbx_xys = get_bbx_xys_from_xyxy(bbx_xyxy, base_enlarge=1.2).float()
+ torch.save({"bbx_xyxy": bbx_xyxy, "bbx_xys": bbx_xys}, paths.bbx)
+ del tracker
+ bbx_xys = torch.load(paths.bbx)["bbx_xys"]
+
+ if not Path(paths.vitpose).exists():
+ vitpose_extractor = VitPoseExtractor()
+ torch.save(vitpose_extractor.extract(cfg.video_path, bbx_xys), paths.vitpose)
+ del vitpose_extractor
+
+ if not Path(paths.vit_features).exists():
+ extractor = Extractor()
+ torch.save(extractor.extract_video_features(cfg.video_path, bbx_xys), paths.vit_features)
+ del extractor
+
+ if not Path(paths.hmr4d_results).exists():
+ length, width, height = get_video_lwh(cfg.video_path)
+ K_fullimg = estimate_K(width, height).repeat(length, 1, 1)
+ data = {
+ "length": torch.tensor(length),
+ "bbx_xys": bbx_xys,
+ "kp2d": torch.load(paths.vitpose),
+ "K_fullimg": K_fullimg,
+ "cam_angvel": compute_cam_angvel(torch.eye(3).repeat(length, 1, 1)),
+ "f_imgseq": torch.load(paths.vit_features),
+ }
+ model: DemoPL = hydra.utils.instantiate(cfg.model, _recursive_=False)
+ model.load_pretrained_model(cfg.ckpt_path)
+ model = model.eval().cuda()
+ pred = detach_to_cpu(model.predict(data, static_cam=True))
+ pred.pop("net_outputs", None) # heavy intermediates, not needed
+ torch.save(pred, paths.hmr4d_results)
+
+ return {"pred": torch.load(paths.hmr4d_results), "cfg": cfg}
+
+
+# ---------------------------------------------------------------------------
+# Stage 2 — SMPL-X params -> SMPL 24 joints (global ay frame + incam).
+
+def smpl_joints(pred: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ from einops import einsum
+ from hmr4d.utils.geo_transform import apply_T_on_points, compute_T_ayfz2ay
+ from hmr4d.utils.net_utils import to_cuda
+ from hmr4d.utils.smplx_utils import make_smplx
+
+ smplx = make_smplx("supermotion").cuda()
+ smplx2smpl = torch.load(GVHMR_ROOT / "hmr4d/utils/body_model/smplx2smpl_sparse.pt").cuda()
+ J_regressor = torch.load(GVHMR_ROOT / "hmr4d/utils/body_model/smpl_neutral_J_regressor.pt").cuda()
+
+ def joints_of(params: dict) -> torch.Tensor:
+ with torch.no_grad():
+ verts = smplx(**to_cuda(params)).vertices # (L, Vx, 3)
+ verts = torch.stack([torch.matmul(smplx2smpl, v) for v in verts]) # (L, 6890, 3)
+ return einsum(J_regressor, verts, "j v, l v i -> l j i") # (L, 24, 3)
+
+ joints_ay = joints_of(pred["smpl_params_global"])
+
+ # Same normalization as GVHMR render_global: frame-0 pelvis to the
+ # origin (XZ), ground to y=0, then rotate so frame 0 faces +z.
+ offset = joints_ay[0, J["pelvis"]].clone()
+ offset[1] = joints_ay[:, :, 1].min()
+ joints_ay = joints_ay - offset
+ T_ay2ayfz = compute_T_ayfz2ay(joints_ay[[0]], inverse=True)
+ joints_ayfz = apply_T_on_points(joints_ay, T_ay2ayfz)
+
+ joints_incam = joints_of(pred["smpl_params_incam"])
+ K = pred["K_fullimg"][0].cpu().numpy()
+ return joints_ayfz.cpu().numpy(), joints_incam.cpu().numpy(), K
+
+
+# ---------------------------------------------------------------------------
+# Stage 3 — MediaPipe-33 synthesis.
+#
+# ayfz frame: y up, ground y=0, character faces +z at the bind frame.
+# Output world: per-frame mid-hip origin, y down, z toward camera is
+# NEGATIVE. ayfz -> output is the 180° rotation about x: (x,y,z) -> (x,-y,-z).
+
+def ayfz_to_mp(p: np.ndarray) -> np.ndarray:
+ out = p.copy()
+ out[..., 1] *= -1.0
+ out[..., 2] *= -1.0
+ return out
+
+
+def mp33_from_smpl(j: np.ndarray) -> dict[str, np.ndarray]:
+ """j: (24, 3) one frame, any right-handed y-down frame. Returns 33 pts."""
+
+ def g(name):
+ return j[J[name]]
+
+ ls, rs = g("l_shoulder"), g("r_shoulder")
+ pelvis, neck, head = g("pelvis"), g("neck"), g("head")
+
+ def unit(v):
+ n = np.linalg.norm(v)
+ return v / n if n > 1e-8 else np.zeros(3)
+
+ left = unit(ls - rs)
+ up = unit(neck - pelvis) # y-down frame: points toward smaller y
+ fwd = unit(np.cross(left, up)) # toward the camera
+
+ def hand_pts(wrist, elbow, side):
+ d = unit(wrist - elbow)
+ lat = left * (0.03 if side == "l" else -0.03)
+ return {
+ "index": wrist + d * 0.09 + lat * 0.3,
+ "pinky": wrist + d * 0.08 - lat,
+ "thumb": wrist + d * 0.04 + lat,
+ }
+
+ def heel_of(ankle, toe):
+ f = toe - ankle
+ f[1] = 0.0
+ f = unit(f)
+ heel = ankle - f * 0.06
+ heel[1] = ankle[1] + 0.04 # y-down: slightly below the ankle
+ return heel
+
+ lh = hand_pts(g("l_wrist"), g("l_elbow"), "l")
+ rh = hand_pts(g("r_wrist"), g("r_elbow"), "r")
+ l_heel = heel_of(g("l_ankle"), g("l_foot"))
+ r_heel = heel_of(g("r_ankle"), g("r_foot"))
+ nose = head + fwd * 0.09
+ eye_l = head + fwd * 0.07 + left * 0.03 - up * (-0.02)
+ eye_r = head + fwd * 0.07 - left * 0.03 - up * (-0.02)
+
+ return {
+ "nose": nose,
+ "left_eye_inner": eye_l - left * 0.01, "left_eye": eye_l, "left_eye_outer": eye_l + left * 0.01,
+ "right_eye_inner": eye_r + left * 0.01, "right_eye": eye_r, "right_eye_outer": eye_r - left * 0.01,
+ "left_ear": head + left * 0.07, "right_ear": head - left * 0.07,
+ "mouth_left": nose + left * 0.02 + up * (-0.03), "mouth_right": nose - left * 0.02 + up * (-0.03),
+ "left_shoulder": ls, "right_shoulder": rs,
+ "left_elbow": g("l_elbow"), "right_elbow": g("r_elbow"),
+ "left_wrist": g("l_wrist"), "right_wrist": g("r_wrist"),
+ "left_pinky": lh["pinky"], "right_pinky": rh["pinky"],
+ "left_index": lh["index"], "right_index": rh["index"],
+ "left_thumb": lh["thumb"], "right_thumb": rh["thumb"],
+ "left_hip": g("l_hip"), "right_hip": g("r_hip"),
+ "left_knee": g("l_knee"), "right_knee": g("r_knee"),
+ "left_ankle": g("l_ankle"), "right_ankle": g("r_ankle"),
+ "left_heel": l_heel, "right_heel": r_heel,
+ "left_foot_index": g("l_foot"), "right_foot_index": g("r_foot"),
+ }
+
+
+def project(p: np.ndarray, K: np.ndarray, wh: tuple[int, int]) -> np.ndarray:
+ z = max(float(p[2]), 1e-6)
+ u = (K[0, 0] * p[0] / z + K[0, 2]) / wh[0]
+ v = (K[1, 1] * p[1] / z + K[1, 2]) / wh[1]
+ return np.array([u, v, 0.0])
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description="GVHMR -> MediaPipe-style landmarks.json")
+ ap.add_argument("--video", required=True, type=Path)
+ ap.add_argument("--out", required=True, type=Path)
+ ap.add_argument("--fps", type=float, default=None, help="source fps for the t clock (default: probe the video)")
+ args = ap.parse_args()
+
+ def rp(p: Path) -> Path:
+ return p if p.is_absolute() else (REPO / p)
+
+ video = rp(args.video)
+ out_path = rp(args.out)
+ if not video.exists():
+ raise SystemExit(f"video not found: {video}")
+ preflight()
+ fps = args.fps or video_fps(video)
+
+ res = run_gvhmr(video)
+ pred = res["pred"]
+ joints_ayfz, joints_incam, K = smpl_joints(pred)
+ L = joints_ayfz.shape[0]
+
+ cap = cv2.VideoCapture(str(video))
+ wh = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1920, int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 1080)
+ cap.release()
+
+ frames = []
+ for i in range(L):
+ mp_world = mp33_from_smpl(ayfz_to_mp(joints_ayfz[i]))
+ hip_mid = 0.5 * (mp_world["left_hip"] + mp_world["right_hip"])
+ mp_img = mp33_from_smpl(joints_incam[i]) # camera frame is already y-down
+ rec = {"frame": i + 1, "t": i / fps, "ok": True,
+ "pelvis_height": round(float(-hip_mid[1]), 5),
+ "image": {}, "world": {}}
+ for n in MP_NAMES:
+ w = mp_world[n] - hip_mid # per-frame mid-hip centered
+ im = project(mp_img[n], K, wh)
+ rec["world"][n] = {"x": round(float(w[0]), 6), "y": round(float(w[1]), 6), "z": round(float(w[2]), 6),
+ "visibility": 1.0, "presence": 1.0}
+ rec["image"][n] = {"x": round(float(im[0]), 6), "y": round(float(im[1]), 6), "z": 0.0,
+ "visibility": 1.0, "presence": 1.0}
+ frames.append(rec)
+
+ payload = {
+ "source": "gvhmr_siga24",
+ "model": str(CHECKPOINTS["gvhmr"]),
+ "fps": fps,
+ "frame_count": L,
+ "ok_count": L,
+ "landmark_names": MP_NAMES,
+ "frames": frames,
+ }
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ out_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ b = frames[0]["world"]
+ span = float(np.hypot(b["left_wrist"]["x"] - b["right_wrist"]["x"], b["left_wrist"]["z"] - b["right_wrist"]["z"]))
+ print(f"wrote {out_path} frames={L} fps={fps:.3f} bind wrist span={span:.3f} m")
+ print("sanity: a T-pose bind span lands ~1.25-1.40 m with SMPL wrists; the lift needs no absolute scale.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pipeline/lift_to_mixamo.py b/pipeline/lift_to_mixamo.py
new file mode 100644
index 0000000..1158ecd
--- /dev/null
+++ b/pipeline/lift_to_mixamo.py
@@ -0,0 +1,453 @@
+"""Generic lift: estimator landmarks -> Mixamo-world joints, driven by an
+action_spec JSON (see docs/PIPELINE.md for the spec schema).
+
+Usage:
+ python pipeline\\lift_to_mixamo.py --spec action_specs\\<motion>.json
+
+This is a direction-preserving retarget: keep the estimator's segment
+DIRECTIONS, rebuild positions from the Mixamo sockets with Mixamo bone
+lengths. With mesh-quality input (GVHMR) no inverse kinematics, no
+authored limb targets and no action envelopes are needed. The spec
+contributes only what the estimator cannot know:
+
+ - where the clip blends into exact Y Bot rest (start and/or end)
+ - when fists close
+ - which foot is the support in each phase (left/right/both/none)
+ - authored arm overrides for beats where the owner's read of the
+ video beats the estimator (e.g. an occluded arm)
+ - the QA frames
+
+Two structural jobs happen here rather than in the FK apply:
+
+ - support-ankle pinning: the estimator world is per-frame hip-centered,
+ so a planted foot drifts while the body leans. During single-support
+ windows the WHOLE pose is translated so the support ankle stays where
+ it touched down (the pelvis then sways over the planted foot, which
+ is the correct physics). The correction decays over 10 frames after
+ the window.
+ - hips world Z stays at rest height; the FK apply searches the real
+ hip height per frame so the support foot plants at ground level —
+ that is what makes crouches and wide stances drop the pelvis. For
+ airborne windows the per-frame `pelvis_height` is passed through and
+ the apply integrates the arc instead.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import numpy as np
+from scipy.signal import savgol_filter
+
+REPO = Path(__file__).resolve().parents[1]
+
+# Y Bot rest joints, world meters (measured from the live rig; see docs/RIG.md).
+REST = {
+ "hips": np.array([0.0, 0.0, 0.99792]),
+ "spine": np.array([0.0, 0.01227, 1.09715]),
+ "spine1": np.array([0.0, 0.0265, 1.21361]),
+ "spine2": np.array([0.0, 0.04276, 1.34721]),
+ "neck": np.array([0.0, 0.03483, 1.49754]),
+ "head": np.array([0.0, 0.00341, 1.60075]),
+ "l_shoulder": np.array([0.06103, 0.03571, 1.43832]),
+ "l_arm": np.array([0.18758, 0.06171, 1.43567]),
+ "l_elbow": np.array([0.46163, 0.06171, 1.4357]),
+ "l_wrist": np.array([0.73777, 0.06171, 1.43572]),
+ "l_hand": np.array([0.84757, 0.06171, 1.43573]),
+ "r_shoulder": np.array([-0.06109, 0.03571, 1.43831]),
+ "r_arm": np.array([-0.18764, 0.06171, 1.43564]),
+ "r_elbow": np.array([-0.46168, 0.06171, 1.43562]),
+ "r_wrist": np.array([-0.73783, 0.06171, 1.43559]),
+ "r_hand": np.array([-0.84763, 0.06171, 1.43558]),
+ "l_upleg": np.array([0.09124, 0.00055, 0.93136]),
+ "l_knee": np.array([0.09369, 0.00571, 0.5254]),
+ "l_ankle": np.array([0.09124, 0.0263, 0.10492]),
+ "l_foot": np.array([0.09498, -0.11336, 0.03284]),
+ "l_toe": np.array([0.09356, -0.21334, 0.03108]),
+ "r_upleg": np.array([-0.09124, 0.00055, 0.93136]),
+ "r_knee": np.array([-0.09369, 0.0057, 0.5254]),
+ "r_ankle": np.array([-0.09124, 0.0263, 0.10492]),
+ "r_foot": np.array([-0.09498, -0.11336, 0.03284]),
+ "r_toe": np.array([-0.09356, -0.21334, 0.03109]),
+}
+
+# Mixamo bone lengths, meters.
+LEN = {
+ "spine1": 0.13459,
+ "spine2": 0.12344,
+ "neck": 0.10790,
+ "head": 0.19630,
+ "l_shoulder": 0.12922,
+ "l_arm": 0.27405,
+ "l_fore": 0.27614,
+ "l_hand": 0.10980,
+ "r_shoulder": 0.12922,
+ "r_arm": 0.27405,
+ "r_fore": 0.27614,
+ "r_hand": 0.10980,
+ "l_upleg": 0.40599,
+ "l_leg": 0.42099,
+ "l_foot": 0.15722,
+ "r_upleg": 0.40599,
+ "r_leg": 0.42099,
+ "r_foot": 0.15722,
+}
+
+# A character-specific rig_profile.json (written by pipeline/setup_rig.py
+# when you build the scene) overrides the built-in Y Bot measurements —
+# this is what makes the lift work with any Mixamo character's
+# proportions.
+_PROFILE = REPO / "rig_profile.json"
+if _PROFILE.exists():
+ _p = json.loads(_PROFILE.read_text(encoding="utf-8"))
+ REST = {k: np.array(v, dtype=float) for k, v in _p["rest"].items()}
+ LEN = {k: float(v) for k, v in _p["lengths"].items()}
+
+MP_USED = [
+ "nose",
+ "left_shoulder", "right_shoulder",
+ "left_elbow", "right_elbow",
+ "left_wrist", "right_wrist",
+ "left_index", "right_index",
+ "left_hip", "right_hip",
+ "left_knee", "right_knee",
+ "left_ankle", "right_ankle",
+ "left_heel", "right_heel",
+ "left_foot_index", "right_foot_index",
+]
+
+HIP_Z = float(REST["hips"][2])
+
+
+def rpath(p) -> Path:
+ p = Path(p)
+ return p if p.is_absolute() else (REPO / p)
+
+
+def unit(v):
+ n = np.linalg.norm(v)
+ return v / n if n > 1e-8 else np.zeros(3)
+
+
+def smoother(t):
+ t = float(np.clip(t, 0.0, 1.0))
+ return t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
+
+
+def lerp(a, b, t):
+ return a * (1.0 - t) + b * t
+
+
+def mp_to_mix(p):
+ """Estimator world (y down, z away-from-camera) -> Mixamo world
+ (z up, character faces -Y, left +X)."""
+ return np.array([p[0], p[2], -p[1] + HIP_Z], dtype=np.float64)
+
+
+def smooth_series(arr, window=7, poly=2):
+ n = arr.shape[0]
+ w = min(window, n if n % 2 == 1 else n - 1)
+ if w < 5:
+ return arr
+ out = np.empty_like(arr)
+ for c in range(arr.shape[1]):
+ out[:, c] = savgol_filter(arr[:, c], window_length=w, polyorder=poly, mode="interp")
+ return out
+
+
+def load_mp(path: Path):
+ data = json.loads(path.read_text(encoding="utf-8"))
+ frames = [f for f in data["frames"] if f.get("ok")]
+ world = {n: np.zeros((len(frames), 3)) for n in MP_USED}
+ times = np.zeros(len(frames))
+ pelvis_h = np.zeros(len(frames))
+ for i, f in enumerate(frames):
+ times[i] = f["t"]
+ pelvis_h[i] = float(f.get("pelvis_height", 0.0))
+ for n in MP_USED:
+ w = f["world"][n]
+ world[n][i] = (w["x"], w["y"], w["z"])
+ return data["fps"], times, world, pelvis_h
+
+
+def resample(times, series, dst_times):
+ out = {}
+ for k, arr in series.items():
+ sm = smooth_series(arr)
+ cols = [np.interp(dst_times, times, sm[:, c]) for c in range(arr.shape[1])]
+ out[k] = np.stack(cols, axis=1)
+ return out
+
+
+def place_chain(up, left):
+ z = unit(up)
+ x = unit(left - z * np.dot(left, z))
+ y = unit(np.cross(z, x))
+ x = unit(np.cross(y, z))
+ return x, y, z
+
+
+def rest_pose():
+ out = {k: v.copy() for k, v in REST.items()}
+ out["basis_x"] = np.array([1.0, 0.0, 0.0])
+ out["basis_y"] = np.array([0.0, 1.0, 0.0])
+ out["basis_z"] = np.array([0.0, 0.0, 1.0])
+ return out
+
+
+def blend_pose(a, b, t):
+ t = float(np.clip(t, 0.0, 1.0))
+ out = {}
+ for k in set(a) | set(b):
+ if k not in a:
+ out[k] = b[k]
+ elif k not in b:
+ out[k] = a[k]
+ else:
+ out[k] = lerp(np.asarray(a[k], float), np.asarray(b[k], float), t)
+ return out
+
+
+def seg(mp, i, a, b):
+ """Unit direction of estimator segment a->b at frame i."""
+ return unit(mp[b][i] - mp[a][i])
+
+
+def reconstruct(mp, i):
+ """Direction-preserving retarget of one frame onto Mixamo lengths."""
+ ls, rs = mp["left_shoulder"][i], mp["right_shoulder"][i]
+ lh, rh = mp["left_hip"][i], mp["right_hip"][i]
+ nose = mp["nose"][i]
+
+ hip_mid = 0.5 * (lh + rh)
+ sh_mid = 0.5 * (ls + rs)
+ up = unit(sh_mid - hip_mid)
+ if np.linalg.norm(up) < 0.2:
+ up = np.array([0.0, 0.0, 1.0])
+ left = unit((ls - rs) + (lh - rh) * 0.35)
+ x, y, z = place_chain(up, left)
+
+ hips = np.array([hip_mid[0], hip_mid[1], HIP_Z])
+
+ def in_basis(local_xyz):
+ return hips + x * local_xyz[0] + y * local_xyz[1] + z * local_xyz[2]
+
+ # Torso: the SMPL-derived landmarks carry no spine names, so the
+ # chest chain is built from the hip basis + shoulder line.
+ chest_dir = unit(0.65 * z + 0.35 * up)
+ spine = hips + chest_dir * np.linalg.norm(REST["spine"] - REST["hips"])
+ spine1 = spine + chest_dir * LEN["spine1"]
+ spine2 = spine1 + chest_dir * LEN["spine2"]
+ neck = spine2 + z * LEN["neck"]
+ head = neck + z * LEN["head"] * 0.85 + unit(np.array([nose[0], nose[1], 0.0])) * 0.02
+
+ # Sockets from the posed hip basis.
+ l_shoulder = in_basis(REST["l_shoulder"] - REST["hips"])
+ r_shoulder = in_basis(REST["r_shoulder"] - REST["hips"])
+ l_arm = l_shoulder + unit((ls - sh_mid) + x * 0.35) * LEN["l_shoulder"]
+ r_arm = r_shoulder + unit((rs - sh_mid) - x * 0.35) * LEN["r_shoulder"]
+ l_upleg = in_basis(REST["l_upleg"] - REST["hips"])
+ r_upleg = in_basis(REST["r_upleg"] - REST["hips"])
+
+ # Limbs: estimator directions, Mixamo lengths.
+ l_elbow = l_arm + seg(mp, i, "left_shoulder", "left_elbow") * LEN["l_arm"]
+ l_wrist = l_elbow + seg(mp, i, "left_elbow", "left_wrist") * LEN["l_fore"]
+ l_hand = l_wrist + seg(mp, i, "left_wrist", "left_index") * LEN["l_hand"]
+ r_elbow = r_arm + seg(mp, i, "right_shoulder", "right_elbow") * LEN["r_arm"]
+ r_wrist = r_elbow + seg(mp, i, "right_elbow", "right_wrist") * LEN["r_fore"]
+ r_hand = r_wrist + seg(mp, i, "right_wrist", "right_index") * LEN["r_hand"]
+
+ l_knee = l_upleg + seg(mp, i, "left_hip", "left_knee") * LEN["l_upleg"]
+ l_ankle = l_knee + seg(mp, i, "left_knee", "left_ankle") * LEN["l_leg"]
+ r_knee = r_upleg + seg(mp, i, "right_hip", "right_knee") * LEN["r_upleg"]
+ r_ankle = r_knee + seg(mp, i, "right_knee", "right_ankle") * LEN["r_leg"]
+
+ l_foot = l_ankle + seg(mp, i, "left_ankle", "left_foot_index") * LEN["l_foot"]
+ r_foot = r_ankle + seg(mp, i, "right_ankle", "right_foot_index") * LEN["r_foot"]
+ l_fwd = unit(np.array([*(mp["left_foot_index"][i] - mp["left_heel"][i])[:2], 0.0]))
+ r_fwd = unit(np.array([*(mp["right_foot_index"][i] - mp["right_heel"][i])[:2], 0.0]))
+ if np.linalg.norm(l_fwd) < 0.1:
+ l_fwd = -y
+ if np.linalg.norm(r_fwd) < 0.1:
+ r_fwd = -y
+ l_toe = l_foot + l_fwd * 0.10
+ r_toe = r_foot + r_fwd * 0.10
+
+ return {
+ "hips": hips, "spine": spine, "spine1": spine1, "spine2": spine2,
+ "neck": neck, "head": head,
+ "l_shoulder": l_shoulder, "l_arm": l_arm, "l_elbow": l_elbow,
+ "l_wrist": l_wrist, "l_hand": l_hand,
+ "r_shoulder": r_shoulder, "r_arm": r_arm, "r_elbow": r_elbow,
+ "r_wrist": r_wrist, "r_hand": r_hand,
+ "l_upleg": l_upleg, "l_knee": l_knee, "l_ankle": l_ankle,
+ "l_foot": l_foot, "l_toe": l_toe,
+ "r_upleg": r_upleg, "r_knee": r_knee, "r_ankle": r_ankle,
+ "r_foot": r_foot, "r_toe": r_toe,
+ "basis_x": x, "basis_y": y, "basis_z": z,
+ }
+
+
+def window_amount(dest_f, rise, fall, src2dest):
+ """1 inside [rise..fall] windows given in src frames, smooth edges."""
+ r0, r1 = src2dest(rise[0]), src2dest(rise[1])
+ f0, f1 = src2dest(fall[0]), src2dest(fall[1])
+ if dest_f <= r0 or dest_f >= f1:
+ return 0.0
+ if dest_f < r1:
+ return smoother((dest_f - r0) / max(1.0, r1 - r0))
+ if dest_f <= f0:
+ return 1.0
+ return 1.0 - smoother((dest_f - f0) / max(1.0, f1 - f0))
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--spec", required=True, type=Path)
+ args = ap.parse_args()
+ spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))
+
+ fps, times, world, pelvis_h = load_mp(rpath(spec["landmarks"]))
+ dst_fps = float(spec.get("dst_fps", 30))
+ duration = float(times[-1])
+ n_dst = int(round(duration * dst_fps)) + 1
+ dst_times = np.clip(np.arange(n_dst) / dst_fps, times[0], times[-1])
+
+ mp = {n: np.stack([mp_to_mix(p) for p in world[n]]) for n in world}
+ mp = resample(times, mp, dst_times)
+ if len(pelvis_h) >= 7:
+ pelvis_h = savgol_filter(pelvis_h, 7, 2, mode="interp")
+ pelvis_h = np.interp(dst_times, times, pelvis_h)
+
+ def src2dest(sf):
+ return (sf - 1) * dst_fps / fps + 1
+
+ rb = spec["rest_blend_end"]
+ rest = rest_pose()
+
+ plant_windows = [(w["src"][0], w["src"][1], w["support"]) for w in spec["plant"]]
+
+ def plant_at(sf):
+ for a, b, sup in plant_windows:
+ if a <= sf <= b:
+ return sup
+ return "both"
+
+ recs, extras = [], []
+ for i in range(n_dst):
+ f = i + 1
+ sf = 1 + (f - 1) * fps / dst_fps # dest -> src frame (float)
+ rec = reconstruct(mp, i)
+
+ # Authored arm overrides (spec): pull a whole arm chain to
+ # hip-local targets — for beats where the owner's read of the
+ # video beats the estimator (e.g. occluded arm chambered at the
+ # chest). Targets are meters in the hip basis, ramped in/out.
+ for ov in spec.get("arm_overrides", []):
+ amt = window_amount(
+ f,
+ [ov["src"][0], ov["src"][0] + ov.get("ramp_src", 6)],
+ [ov["src"][1] - ov.get("ramp_src", 6), ov["src"][1]],
+ src2dest,
+ )
+ if amt <= 1e-4:
+ continue
+ s = "l" if ov["side"] == "left" else "r"
+ bx, by, bz = rec["basis_x"], rec["basis_y"], rec["basis_z"]
+ hips_p = np.asarray(rec["hips"], float)
+
+ def hip_local(v3):
+ return hips_p + bx * v3[0] + by * v3[1] + bz * v3[2]
+
+ sock = np.asarray(rec[f"{s}_arm"], float)
+ e_t = sock + unit(hip_local(ov["elbow_local"]) - sock) * LEN[f"{s}_arm"]
+ w_t = e_t + unit(hip_local(ov["wrist_local"]) - e_t) * LEN[f"{s}_fore"]
+ e = lerp(np.asarray(rec[f"{s}_elbow"], float), e_t, amt)
+ w = lerp(np.asarray(rec[f"{s}_wrist"], float), w_t, amt)
+ e = sock + unit(e - sock) * LEN[f"{s}_arm"]
+ w = e + unit(w - e) * LEN[f"{s}_fore"]
+ rec[f"{s}_elbow"], rec[f"{s}_wrist"] = e, w
+ rec[f"{s}_hand"] = w + unit(w - e) * LEN[f"{s}_hand"]
+
+ rest_amt = smoother((sf - rb["start_src"]) / max(1.0, rb["full_src"] - rb["start_src"]))
+ rbs = spec.get("rest_blend_start")
+ if rbs:
+ start_amt = 1.0 - smoother(
+ (sf - rbs["full_src"]) / max(1.0, rbs["release_src"] - rbs["full_src"])
+ )
+ rest_amt = max(rest_amt, start_amt)
+ if rest_amt > 0.0:
+ rec = blend_pose(rec, rest, rest_amt)
+ for k in ("basis_x", "basis_y", "basis_z"):
+ rec[k] = unit(np.asarray(rec[k], float))
+
+ fist = window_amount(f, spec["fists"]["rise_src"], spec["fists"]["fall_src"], src2dest)
+ recs.append(rec)
+ extras.append({"frame": f, "t": float(dst_times[i]), "rest": rest_amt, "fist": fist,
+ "plant": plant_at(sf) if rest_amt < 0.65 else "both",
+ "pelvis_height": float(pelvis_h[i])})
+
+ # Support-ankle pinning (see module docstring).
+ RELEASE = 10
+ pos_keys = [k for k in recs[0] if not k.startswith("basis_")]
+ for a_src, b_src, sup in plant_windows:
+ if sup not in ("left", "right"):
+ continue
+ a = max(1, int(round(src2dest(a_src))))
+ b = min(n_dst, int(round(src2dest(b_src))))
+ ankle = "l_ankle" if sup == "left" else "r_ankle"
+ anchor = np.asarray(recs[a - 1][ankle], float)[:2].copy()
+ last_delta = np.zeros(2)
+ for f in range(a, b + 1):
+ delta = anchor - np.asarray(recs[f - 1][ankle], float)[:2]
+ for k in pos_keys:
+ recs[f - 1][k] = np.asarray(recs[f - 1][k], float)
+ recs[f - 1][k][:2] += delta
+ last_delta = delta
+ for j, f in enumerate(range(b + 1, min(n_dst, b + RELEASE) + 1)):
+ fade = last_delta * (1.0 - smoother((j + 1) / float(RELEASE)))
+ for k in pos_keys:
+ recs[f - 1][k] = np.asarray(recs[f - 1][k], float)
+ recs[f - 1][k][:2] += fade
+
+ joints = []
+ for rec, ex in zip(recs, extras):
+ out = {k: [round(float(v), 5) for v in np.asarray(val)] for k, val in rec.items()}
+ out["frame"] = ex["frame"]
+ out["t"] = ex["t"]
+ out["rest_amount"] = round(float(ex["rest"]), 4)
+ out["fist_amount"] = round(float(ex["fist"]), 4)
+ out["plant"] = ex["plant"]
+ out["pelvis_height"] = round(float(ex["pelvis_height"]), 5)
+ joints.append(out)
+
+ payload = {
+ "src_fps": fps,
+ "dst_fps": dst_fps,
+ "duration": duration,
+ "frame_count": n_dst,
+ "estimator": spec.get("estimator", "unknown"),
+ "action_spec": spec["name"],
+ "frames": joints,
+ }
+ out_path = rpath(spec["joints_out"])
+ out_path.write_text(json.dumps(payload), encoding="utf-8")
+ print("wrote", out_path, "frames", n_dst)
+
+ for sfq in spec.get("qa_src_frames", []):
+ f = int(round(src2dest(sfq)))
+ f = max(1, min(n_dst, f))
+ j = joints[f - 1]
+ bx = np.asarray(j["basis_x"], float)
+ yaw = np.degrees(np.arctan2(-bx[1], bx[0]))
+ print(
+ f"src{sfq:3d}/dest{f:3d} rest={j['rest_amount']:.2f} fist={j['fist_amount']:.2f} "
+ f"plant={j['plant']:5s} yaw={yaw:+4.0f} "
+ f"lw={j['l_wrist']} rw={j['r_wrist']} ra={j['r_ankle']}"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pipeline/qa_clip.py b/pipeline/qa_clip.py
new file mode 100644
index 0000000..db6fb9f
--- /dev/null
+++ b/pipeline/qa_clip.py
@@ -0,0 +1,121 @@
+"""Generic clip QA: numeric checks against a clip's dumped curves.json,
+driven by the action_spec.
+
+Usage:
+ python pipeline\\qa_clip.py --spec action_specs\\<motion>.json
+
+Numbers can pass while the motion is wrong — stills and a human eye are
+still the last word. This catches the classes of failure that burn
+passes: exploded bones, hip pops, foot skate on the support, a drifting
+in-place root, an end pose that is not rest, grounded "airborne" frames.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import numpy as np
+
+REPO = Path(__file__).resolve().parents[1]
+GROUND_Z = 0.105
+REST_LW = (0.7378, 1.4357)
+REST_RW = (-0.7378, 1.4356)
+_PROFILE = REPO / "rig_profile.json"
+if _PROFILE.exists():
+ _p = json.loads(_PROFILE.read_text(encoding="utf-8"))
+ GROUND_Z = float(_p["ground_z"])
+ REST_LW = (_p["rest"]["l_wrist"][0], _p["rest"]["l_wrist"][2])
+ REST_RW = (_p["rest"]["r_wrist"][0], _p["rest"]["r_wrist"][2])
+
+
+def rpath(p) -> Path:
+ p = Path(p)
+ return p if p.is_absolute() else (REPO / p)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--spec", required=True, type=Path)
+ args = ap.parse_args()
+ spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))
+ clip_dir = rpath(spec["clip_dir"])
+ curves = json.loads((clip_dir / "curves.json").read_text(encoding="utf-8"))
+ frames = curves["frames"]
+ n = len(frames)
+ src_fps = float(spec.get("src_fps", 24))
+ dst_fps = float(spec.get("dst_fps", 30))
+
+ def w(i, bone):
+ return np.array(frames[i]["bones"][bone]["world_location"], dtype=float)
+
+ names = list(frames[0]["bones"].keys())
+ ok = True
+
+ # 1. World bounds, all bones all frames.
+ bad = []
+ for i in range(n):
+ for b in names:
+ p = w(i, b)
+ if abs(p[0]) > 2 or abs(p[1]) > 2 or not (-0.5 < p[2] < 3):
+ bad.append((i + 1, b, p.round(2).tolist()))
+ print(f"[{'OK' if not bad else 'FAIL'}] world bounds: {len(bad)} violations" + (f" e.g. {bad[:3]}" if bad else ""))
+ ok &= not bad
+
+ # 2. Hip Z continuity.
+ hz = np.array([w(i, "mixamorig:Hips")[2] for i in range(n)])
+ steps = np.abs(np.diff(hz))
+ print(f"[{'OK' if steps.max() < 0.12 else 'FAIL'}] hip Z step: max {steps.max():.3f} m @ f{steps.argmax()+2} (limit 0.12) | range {hz.min():.3f}-{hz.max():.3f}")
+ ok &= steps.max() < 0.12
+
+ # 3. In-place root.
+ hx = np.array([w(i, "mixamorig:Hips")[0] for i in range(n)])
+ hy = np.array([w(i, "mixamorig:Hips")[1] for i in range(n)])
+ travel = float(np.hypot(hx[-1] - hx[0], hy[-1] - hy[0]))
+ drift = float(max(np.ptp(hx), np.ptp(hy)))
+ print(f"[{'OK' if travel < 0.05 else 'WARN'}] in-place: end-to-end hip XZ travel {travel:.4f} m, max drift {drift:.3f} m")
+
+ # 4. Support feet during plant windows.
+ for wnd in spec.get("plant", []):
+ a = int(round((wnd["src"][0] - 1) * dst_fps / src_fps + 1))
+ b = int(round((wnd["src"][1] - 1) * dst_fps / src_fps + 1))
+ b = min(b, n)
+ sup = wnd["support"]
+ if sup == "none":
+ zs = np.array([[w(i, "mixamorig:LeftFoot")[2], w(i, "mixamorig:RightFoot")[2]]
+ for i in range(a - 1, b)])
+ clear = zs.min(axis=1).max() # highest point of the lower foot
+ tag = "OK" if clear > 0.12 else "WARN"
+ print(f"[{tag}] airborne dest {a}-{b}: lower-foot peak clearance {clear:.3f} m (want > 0.12)")
+ continue
+ feet = ["mixamorig:LeftFoot", "mixamorig:RightFoot"] if sup == "both" else (
+ ["mixamorig:LeftFoot"] if sup == "left" else ["mixamorig:RightFoot"])
+ for foot in feet:
+ zs = np.array([w(i, foot)[2] for i in range(a - 1, b)])
+ xy = np.array([w(i, foot)[:2] for i in range(a - 1, b)])
+ # For "both", each foot may legitimately step; judge height only.
+ zerr = np.abs(zs - GROUND_Z).max()
+ skate = float(np.ptp(xy, axis=0).max()) if sup != "both" else float("nan")
+ tag = "OK" if zerr < 0.06 else "WARN"
+ extra = "" if sup == "both" else f", XZ wander {skate:.3f} m"
+ print(f"[{tag}] plant {sup:5s} dest {a}-{b} {foot.split(':')[1]}: |z-{GROUND_Z}| max {zerr:.3f}{extra}")
+
+ # 5. End pose == rest.
+ lh, rh = w(n - 1, "mixamorig:LeftHand"), w(n - 1, "mixamorig:RightHand")
+ rest_err = max(abs(lh[0] - REST_LW[0]) + abs(lh[2] - REST_LW[1]), abs(rh[0] - REST_RW[0]) + abs(rh[2] - REST_RW[1]))
+ print(f"[{'OK' if rest_err < 0.03 else 'FAIL'}] end frame is rest: hand error {rest_err:.4f} (hips z {hz[-1]:.4f})")
+ ok &= rest_err < 0.03
+
+ # 6. Fast-bone pops: largest single-frame world jump per key bone.
+ for b in ("mixamorig:LeftHand", "mixamorig:RightHand", "mixamorig:LeftFoot", "mixamorig:RightFoot", "mixamorig:Head"):
+ ps = np.array([w(i, b) for i in range(n)])
+ d = np.linalg.norm(np.diff(ps, axis=0), axis=1)
+ tag = "OK" if d.max() < 0.30 else "WARN"
+ print(f"[{tag}] max frame-jump {b.split(':')[1]}: {d.max():.3f} m @ f{int(d.argmax()) + 2}")
+
+ print("\nverdict:", "PASS (visual review still required)" if ok else "HARD FAILURES — fix before showing")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pipeline/setup_rig.py b/pipeline/setup_rig.py
new file mode 100644
index 0000000..f58e36f
--- /dev/null
+++ b/pipeline/setup_rig.py
@@ -0,0 +1,198 @@
+"""Build the clean rest scene from your own Mixamo character download —
+ANY Mixamo character with the standard mixamorig skeleton (Y Bot,
+X Bot, or any character from the Mixamo library).
+
+Mixamo characters cannot be redistributed (Adobe terms), so this repo
+ships no .fbx/.blend. Download a character yourself:
+
+ 1. Log in at https://www.mixamo.com , open the Characters tab,
+ pick any character (Y Bot is the reference this pipeline was
+ developed on).
+ 2. Download: Format "FBX Binary", Pose "T-pose", with skin.
+ 3. Save as <repo>\\ybot.fbx (any name; pass it via --fbx)
+
+Then build the scene (Blender 5.1+):
+
+ "C:\\Program Files\\Blender Foundation\\Blender 5.1\\blender.exe" ^
+ --background --python pipeline\\setup_rig.py -- ^
+ --fbx ybot.fbx --out ybot_rest.blend
+
+Validates the import against the conventions the pipeline relies on
+(docs/RIG.md): armature "Armature" rotated X=90deg scale 0.01,
+mixamorig: bones rooted at mixamorig:Hips — then saves the .blend the
+FK apply runs in AND writes `rig_profile.json` at the repo root: the
+character's measured rest-joint positions, bone lengths, hip height
+and ground height. The lift/apply/QA read that profile, which is what
+makes the pipeline work with any Mixamo character's proportions
+(without a profile they fall back to built-in Y Bot measurements).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+
+import bpy
+
+REPO = Path(__file__).resolve().parents[1]
+
+# Profile joint -> bone whose (posed-rest) head is that joint.
+PROFILE_JOINTS = {
+ "hips": "mixamorig:Hips", "spine": "mixamorig:Spine",
+ "spine1": "mixamorig:Spine1", "spine2": "mixamorig:Spine2",
+ "neck": "mixamorig:Neck", "head": "mixamorig:Head",
+ "l_shoulder": "mixamorig:LeftShoulder", "l_arm": "mixamorig:LeftArm",
+ "l_elbow": "mixamorig:LeftForeArm", "l_wrist": "mixamorig:LeftHand",
+ "l_hand": "mixamorig:LeftHandMiddle1",
+ "r_shoulder": "mixamorig:RightShoulder", "r_arm": "mixamorig:RightArm",
+ "r_elbow": "mixamorig:RightForeArm", "r_wrist": "mixamorig:RightHand",
+ "r_hand": "mixamorig:RightHandMiddle1",
+ "l_upleg": "mixamorig:LeftUpLeg", "l_knee": "mixamorig:LeftLeg",
+ "l_ankle": "mixamorig:LeftFoot", "l_foot": "mixamorig:LeftToeBase",
+ "l_toe": "mixamorig:LeftToe_End",
+ "r_upleg": "mixamorig:RightUpLeg", "r_knee": "mixamorig:RightLeg",
+ "r_ankle": "mixamorig:RightFoot", "r_foot": "mixamorig:RightToeBase",
+ "r_toe": "mixamorig:RightToe_End",
+}
+
+# LEN key (as the lift uses them) -> bone whose length it is.
+PROFILE_LENGTHS = {
+ "spine1": "mixamorig:Spine1", "spine2": "mixamorig:Spine2",
+ "neck": "mixamorig:Neck", "head": "mixamorig:Head",
+ "l_shoulder": "mixamorig:LeftShoulder", "l_arm": "mixamorig:LeftArm",
+ "l_fore": "mixamorig:LeftForeArm", "l_hand": "mixamorig:LeftHand",
+ "r_shoulder": "mixamorig:RightShoulder", "r_arm": "mixamorig:RightArm",
+ "r_fore": "mixamorig:RightForeArm", "r_hand": "mixamorig:RightHand",
+ "l_upleg": "mixamorig:LeftUpLeg", "l_leg": "mixamorig:LeftLeg",
+ "l_foot": "mixamorig:LeftFoot",
+ "r_upleg": "mixamorig:RightUpLeg", "r_leg": "mixamorig:RightLeg",
+ "r_foot": "mixamorig:RightFoot",
+}
+
+
+def dump_rig_profile(arm, out_path: Path) -> dict:
+ """Measure the character's rest geometry into rig_profile.json."""
+ bpy.context.view_layer.update()
+ scale = arm.scale[0]
+
+ def w(bone_name):
+ pb = arm.pose.bones.get(bone_name)
+ if pb is None:
+ return None
+ p = (arm.matrix_world @ pb.matrix).to_translation()
+ return [round(p.x, 5), round(p.y, 5), round(p.z, 5)]
+
+ rest = {}
+ for joint, bone in PROFILE_JOINTS.items():
+ p = w(bone)
+ if p is None and joint in ("l_hand", "r_hand"):
+ # No finger bones on this character: extrapolate the hand
+ # tip along the forearm direction.
+ wrist = rest.get(joint.replace("hand", "wrist"))
+ elbow = rest.get(joint.replace("hand", "elbow"))
+ if wrist and elbow:
+ d = [wrist[i] - elbow[i] for i in range(3)]
+ n = max(1e-6, sum(x * x for x in d) ** 0.5)
+ hand_len = arm.pose.bones[bone.replace("HandMiddle1", "Hand")].length * scale
+ p = [round(wrist[i] + d[i] / n * hand_len, 5) for i in range(3)]
+ if p is None:
+ raise SystemExit(f"cannot measure profile joint {joint} ({bone})")
+ rest[joint] = p
+
+ lengths = {}
+ for key, bone in PROFILE_LENGTHS.items():
+ pb = arm.pose.bones.get(bone)
+ if pb is None:
+ raise SystemExit(f"cannot measure bone length {key} ({bone})")
+ lengths[key] = round(pb.length * scale, 5)
+
+ profile = {
+ "character": [o.name for o in bpy.data.objects if o.type == "MESH"],
+ "hip_height": rest["hips"][2],
+ "ground_z": round(0.5 * (rest["l_ankle"][2] + rest["r_ankle"][2]), 5),
+ "rest": rest,
+ "lengths": lengths,
+ }
+ out_path.write_text(json.dumps(profile, indent=1), encoding="utf-8")
+ return profile
+
+
+def main() -> None:
+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--fbx", default="ybot.fbx")
+ ap.add_argument("--out", default="ybot_rest.blend")
+ args = ap.parse_args(argv)
+
+ fbx = Path(args.fbx)
+ fbx = fbx if fbx.is_absolute() else REPO / fbx
+ out = Path(args.out)
+ out = out if out.is_absolute() else REPO / out
+ if not fbx.exists():
+ raise SystemExit(f"ybot.fbx not found at {fbx} — download it from mixamo.com (see module docstring)")
+
+ # Empty scene, metric, 30 fps.
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ scene = bpy.context.scene
+ scene.render.fps = 30
+ scene.frame_start = 1
+
+ bpy.ops.import_scene.fbx(filepath=str(fbx))
+
+ arms = [o for o in bpy.data.objects if o.type == "ARMATURE"]
+ if len(arms) != 1:
+ raise SystemExit(f"expected exactly one armature in the FBX, found {len(arms)}")
+ arm = arms[0]
+ arm.name = "Armature"
+
+ # Validate the conventions the whole pipeline assumes.
+ errors = []
+ warnings = []
+ if abs(arm.rotation_euler[0] - math.pi / 2) > 1e-3:
+ errors.append(f"armature X rotation is {math.degrees(arm.rotation_euler[0]):.1f} deg, expected 90")
+ if abs(arm.scale[0] - 0.01) > 1e-5:
+ errors.append(f"armature scale is {arm.scale[0]}, expected 0.01 (cm -> m)")
+ bones = arm.pose.bones
+ if "mixamorig:Hips" not in bones:
+ errors.append("root bone mixamorig:Hips missing (do not strip the mixamorig: prefix)")
+ bad_names = [b.name for b in bones if not b.name.startswith("mixamorig:")]
+ if bad_names:
+ errors.append(f"non-mixamorig bones: {bad_names[:5]}")
+ if len(bones) != 65:
+ warnings.append(f"{len(bones)} pose bones (standard characters have 65 — "
+ "missing fingers are tolerated, fists are skipped for absent bones)")
+ mesh_names = sorted(o.name for o in bpy.data.objects if o.type == "MESH")
+ if not mesh_names:
+ errors.append("no mesh objects in the FBX")
+
+ bpy.context.view_layer.update()
+ if "mixamorig:Hips" in bones:
+ hip_z = (arm.matrix_world @ bones["mixamorig:Hips"].matrix).to_translation().z
+ if not (0.6 < hip_z < 1.4):
+ errors.append(f"rest hip world height {hip_z:.3f} m — not a human-scale Mixamo import")
+ else:
+ print(f"rest hip world height {hip_z:.4f} m")
+
+ if errors:
+ raise SystemExit("FBX does not match the expected Mixamo conventions:\n " + "\n ".join(errors))
+ for wmsg in warnings:
+ print("WARNING:", wmsg)
+
+ # No cameras/lights/extras: scene must be the armature + its meshes.
+ for o in list(bpy.data.objects):
+ if o.type not in ("ARMATURE", "MESH"):
+ bpy.data.objects.remove(o)
+
+ profile = dump_rig_profile(arm, REPO / "rig_profile.json")
+ print(f"rig_profile.json written — hip {profile['hip_height']} m, "
+ f"ground {profile['ground_z']} m, meshes {profile['character']}")
+
+ bpy.ops.wm.save_as_mainfile(filepath=str(out))
+ print(f"saved {out} — {len(bones)} bones, meshes {mesh_names}, 30 fps")
+
+
+if __name__ == "__main__":
+ main()