Skip to content

Retarget human motion from video to an Adobe Mixamo-rigged 3D character.

Python

Pin planted feet on the ground and add floor markers to judge movement.

MaxLiu6dd26becf352
diff --git a/AGENTS.md b/AGENTS.md
index 3d90182..cc07c76 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -36,6 +36,7 @@ m2mr run --video assets/video/dance.mp4 --rig assets/mixamo/Vampire.fbx
m2mr run --image assets/image/pose.jpg --rig assets/mixamo/Y_Bot.fbx
m2mr run --skeleton outputs/<run>/skeleton_motion.npz --rig ... # reuse extraction, swap rig
m2mr run --output-dir DIR --progress-jsonl FILE --no-preview # Blender Extension / automation
+m2mr run --no-foot-lock ... # keep the raw retarget (planted feet are pinned by default)
m2mr diagnose outputs/<run> [--visualize] [--threshold-cm N] # re-check self-intersection -> diagnostics.json (+ .html)
```
@@ -85,7 +86,11 @@ When helping a user:
appears: disable, **quit Blender fully**, reopen, install again.
6. Jobs write `<project>/outputs/blender_jobs/<job-id>/`. After import, hide
**Icosphere** and the **armature** in the Outliner; leave the
- **skinned_mesh_…** objects (one per FBX geometry) visible. FPS must match the source clip duration (a 60 fps video tagged as
+ **skinned_mesh_…** objects (one per FBX geometry) visible. Import also
+ adds a **Floor Markers** mesh on Blender's floor (z=0): 0.5 m crosses
+ over the hips' travel, metre marks larger, origin green. The next import
+ into that collection replaces it. The result panel's **Floor Markers**
+ checkbox shows or hides that mesh. FPS must match the source clip duration (a 60 fps video tagged as
30 fps plays at half speed). The timeline runs 0..n-1, the frames
`diagnostics.json` uses; the **Diagnostics** box under Progress reads it
(frame bar, Previous / Next, **Open HTML Report** builds `diagnostics.html`
@@ -98,10 +103,10 @@ Smoke-test checklist: [`docs/blender-extension.md`](docs/blender-extension.md).
Each run writes `outputs/<YYYYMMDD_HHMMSS>_<source>/`:
- `run.json` — inputs, timings, output listing
-- `skeleton_motion.npz` — 3D human skeleton (24 SMPL joints, Y-up meters)
+- `skeleton_motion.npz` — 3D human skeleton (24 SMPL joints, Y-up meters) + `foot_contact` (F, 4: left ankle, left foot, right ankle, right foot static probability from GVHMR; older runs read it from `cache/*/hmr4d_results.pt`)
- `mixamo_rotations.npz` — per-bone animation rotations (quaternion wxyz; convention string inside)
- `mixamo_character.glb` — skinned character + clip (glTF 2.0; Blender: File → Import → glTF 2.0)
-- `diagnostics.json` — self-intersection report on the GLB (body-part pairs, frame ranges, depth in cm; frames counted from 0); summary also in `run.json`. Parts joined at a joint are not compared. No floor check. `m2mr diagnose <run> [--visualize] [--threshold-cm N]` re-checks a run; `--visualize` adds `diagnostics.html`.
+- `diagnostics.json` — self-intersection report on the GLB (body-part pairs, frame ranges, depth in cm; frames counted from 0); summary also in `run.json`. Parts joined at a joint are not compared. No floor check. `m2mr diagnose <run> [--visualize] [--threshold-cm N]` re-checks a run; `--visualize` adds `diagnostics.html`. The report's 3D view keeps fixed floor markers on y=0 (0.5 m crosses, larger metre marks, green origin) so movement can be judged against the floor.
- Video in: `videos/human_skeleton.mp4`, `videos/mixamo_skeleton.mp4`, `videos/mixamo_character.mp4`, `videos/compare.mp4` (2x2: original / mixamo skeleton / human skeleton / character)
- Photo in: the same four views as PNG under `images/`, plus `images/before_after_360_compare.mp4` (left original / right 10° orbit of the rig)
@@ -110,6 +115,8 @@ Each run writes `outputs/<YYYYMMDD_HHMMSS>_<source>/`:
- `motion2mixamorig/paths.py` — all filesystem locations
- `motion2mixamorig/extract.py` — video or still -> 3D human skeleton (GVHMR)
- `motion2mixamorig/mixamo/` — FBX parsing, FK, retargeting, skinning, rendering
+- `motion2mixamorig/mixamo/foot_lock.py` — pins planted feet (ball first, else heel) with two-bone leg IK, shifting the hips when a straight leg cannot reach; summary in `run.json` → `foot_lock`
+- `motion2mixamorig/mixamo/ground.py` — shifts the hips so the planted sole sits on y = 0; summary in `run.json` → `ground`
- `motion2mixamorig/diagnose.py` — self-intersection check on the GLB -> `diagnostics.json`
- `motion2mixamorig/diagnose_report.py` — `diagnostics.html` (`--visualize`)
- `motion2mixamorig/pipeline.py` — one run end to end
diff --git a/blender_extension/motion2mixamorig_blender/i18n.py b/blender_extension/motion2mixamorig_blender/i18n.py
index f69e0c0..f692180 100644
--- a/blender_extension/motion2mixamorig_blender/i18n.py
+++ b/blender_extension/motion2mixamorig_blender/i18n.py
@@ -298,6 +298,16 @@ _add(
ru="Импортировать персонажа",
ar="استيراد الشخصية المولَّدة",
)
+_add(
+ "show_floor_markers",
+ en="Floor Markers",
+ **{"zh-CN": "地面标记"},
+ ko="바닥 마커",
+ ja="床マーカー",
+ de="Bodenmarkierungen",
+ ru="Метки на полу",
+ ar="علامات الأرضية",
+)
_add(
"open_output",
en="Open Output Folder",
diff --git a/blender_extension/motion2mixamorig_blender/locales/zh_TW.py b/blender_extension/motion2mixamorig_blender/locales/zh_TW.py
index c4af8e9..977c6b1 100644
--- a/blender_extension/motion2mixamorig_blender/locales/zh_TW.py
+++ b/blender_extension/motion2mixamorig_blender/locales/zh_TW.py
@@ -33,6 +33,7 @@ STRINGS = {
"generation_import_failed": "產生成功,但自動匯入失敗",
"cancelled": "已取消",
"import_character": "匯入產生的角色",
+ "show_floor_markers": "地面標記",
"open_output": "開啟輸出資料夾",
"view_log": "檢視完整記錄",
"no_job_yet": "尚無工作",
diff --git a/blender_extension/motion2mixamorig_blender/operators/import_result.py b/blender_extension/motion2mixamorig_blender/operators/import_result.py
index b828439..f5b819e 100644
--- a/blender_extension/motion2mixamorig_blender/operators/import_result.py
+++ b/blender_extension/motion2mixamorig_blender/operators/import_result.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import math
from pathlib import Path
import bpy
@@ -117,6 +118,185 @@ def hide_joint_bubbles(armature, imported_objects) -> None:
obj.hide_viewport = True
+_MARKER_FLAG = "m2mr_floor_markers"
+_MARKER_STEP = 0.5
+_MARKER_PAD = 1.5
+
+
+def _marker_material(name: str, rgba: tuple[float, float, float, float]):
+ mat = bpy.data.materials.get(name)
+ if mat is None:
+ mat = bpy.data.materials.new(name)
+ mat.use_nodes = True
+ mat.diffuse_color = rgba
+ tree = mat.node_tree
+ bsdf = tree.nodes.get("Principled BSDF") if tree is not None else None
+ if bsdf is not None and "Base Color" in bsdf.inputs:
+ bsdf.inputs["Base Color"].default_value = rgba
+ if "Roughness" in bsdf.inputs:
+ bsdf.inputs["Roughness"].default_value = 1.0
+ return mat
+
+
+def _clear_floor_markers(collection) -> None:
+ for obj in list(collection.objects):
+ if not obj.get(_MARKER_FLAG):
+ continue
+ mesh = obj.data if obj.type == "MESH" else None
+ bpy.data.objects.remove(obj, do_unlink=True)
+ if mesh is not None and mesh.users == 0:
+ bpy.data.meshes.remove(mesh)
+
+
+def _hips_travel(context: Context, armature):
+ """World XY bounds of the hips across the timeline. Blender is Z-up."""
+ bone = None
+ if armature is not None and getattr(armature, "pose", None) is not None:
+ for candidate in armature.pose.bones:
+ if candidate.name.lower().endswith("hips"):
+ bone = candidate
+ break
+ if bone is None:
+ return None
+ scene = context.scene
+ span = max(0, int(scene.frame_end) - int(scene.frame_start))
+ stride = max(1, span // 120)
+ original = scene.frame_current
+ # A hidden armature drops out of the depsgraph, so the pose would stay
+ # on the rest hips and the markers would miss the travel.
+ was_hidden = False
+ was_viewport = bool(armature.hide_viewport)
+ try:
+ was_hidden = bool(armature.hide_get())
+ except Exception:
+ was_hidden = False
+ xs: list[float] = []
+ ys: list[float] = []
+ try:
+ armature.hide_viewport = False
+ try:
+ armature.hide_set(False)
+ except Exception:
+ pass
+ frame = int(scene.frame_start)
+ last = int(scene.frame_end)
+ while frame <= last:
+ scene.frame_set(frame)
+ context.view_layer.update()
+ co = armature.matrix_world @ bone.head
+ xs.append(float(co.x))
+ ys.append(float(co.y))
+ if frame == last:
+ break
+ frame = min(last, frame + stride)
+ finally:
+ scene.frame_set(original)
+ armature.hide_viewport = was_viewport
+ if was_hidden:
+ try:
+ armature.hide_set(True)
+ except Exception:
+ pass
+ if not xs:
+ return None
+ return min(xs), max(xs), min(ys), max(ys)
+
+
+def _add_floor_markers(context: Context, collection, armature) -> None:
+ """One mesh of floor crosses on Z=0, covering where the hips travel.
+
+ Replaced on the next import into the same collection. glTF Y-up lands on
+ Blender Z-up, so the grounded sole plane is z=0.
+ """
+ _clear_floor_markers(collection)
+ travel = _hips_travel(context, armature)
+ if travel is None:
+ min_x, max_x, min_y, max_y = -2.0, 2.0, -2.0, 2.0
+ else:
+ min_x, max_x, min_y, max_y = travel
+ min_x -= _MARKER_PAD
+ max_x += _MARKER_PAD
+ min_y -= _MARKER_PAD
+ max_y += _MARKER_PAD
+ step = _MARKER_STEP
+ x0, x1 = math.floor(min_x / step) * step, math.ceil(max_x / step) * step
+ y0, y1 = math.floor(min_y / step) * step, math.ceil(max_y / step) * step
+ nx = int(round((x1 - x0) / step))
+ ny = int(round((y1 - y0) / step))
+ if (nx + 1) * (ny + 1) > 2500:
+ step = 1.0
+ x0, x1 = math.floor(min_x), math.ceil(max_x)
+ y0, y1 = math.floor(min_y), math.ceil(max_y)
+ nx = int(round(x1 - x0))
+ ny = int(round(y1 - y0))
+
+ verts: list[tuple[float, float, float]] = []
+ faces: list[tuple[int, int, int, int]] = []
+ slots: list[int] = []
+ z = 0.002
+
+ def plus(x: float, y: float, arm: float, thick: float, slot: int) -> None:
+ bars = (
+ (x - arm, y - thick, x + arm, y - thick, x + arm, y + thick, x - arm, y + thick),
+ (x - thick, y - arm, x + thick, y - arm, x + thick, y + arm, x - thick, y + arm),
+ )
+ for b in bars:
+ o = len(verts)
+ verts.extend((
+ (b[0], b[1], z), (b[2], b[3], z), (b[4], b[5], z), (b[6], b[7], z),
+ ))
+ faces.append((o, o + 1, o + 2, o + 3))
+ slots.append(slot)
+
+ for ix in range(nx + 1):
+ for iy in range(ny + 1):
+ x = x0 + ix * step
+ y = y0 + iy * step
+ origin = abs(x) < 1e-3 and abs(y) < 1e-3
+ metre = abs(x - round(x)) < 1e-3 and abs(y - round(y)) < 1e-3
+ if origin:
+ plus(x, y, 0.16, 0.016, 2)
+ elif metre:
+ plus(x, y, 0.10, 0.012, 1)
+ else:
+ plus(x, y, 0.055, 0.010, 0)
+
+ mesh = bpy.data.meshes.new("Floor Markers")
+ mesh.from_pydata(verts, [], faces)
+ grey = _marker_material("M2MR Floor Marker", (0.54, 0.54, 0.54, 1.0))
+ metre_mat = _marker_material("M2MR Floor Marker Metre", (0.82, 0.82, 0.82, 1.0))
+ origin_mat = _marker_material("M2MR Floor Marker Origin", (0.463, 0.725, 0.0, 1.0))
+ mesh.materials.append(grey)
+ mesh.materials.append(metre_mat)
+ mesh.materials.append(origin_mat)
+ for poly, slot in zip(mesh.polygons, slots):
+ poly.material_index = slot
+ mesh.update()
+
+ obj = bpy.data.objects.new("Floor Markers", mesh)
+ obj[_MARKER_FLAG] = True
+ if hasattr(obj, "visible_shadow"):
+ obj.visible_shadow = False
+ collection.objects.link(obj)
+ visible = True
+ props = getattr(getattr(context, "scene", None), "m2mr", None)
+ if props is not None:
+ visible = bool(props.show_floor_markers)
+ apply_floor_marker_visibility(visible)
+
+
+def apply_floor_marker_visibility(visible: bool) -> None:
+ """Show or hide every floor-marker mesh. The result panel drives this."""
+ for obj in list(bpy.data.objects):
+ if not obj.get(_MARKER_FLAG):
+ continue
+ obj.hide_viewport = not visible
+ try:
+ obj.hide_set(not visible)
+ except Exception:
+ pass
+
+
def import_generated_character(
context: Context,
result: RunResult,
@@ -173,6 +353,11 @@ def import_generated_character(
new_objects[0].select_set(True)
view_layer.objects.active = new_objects[0]
+ try:
+ _add_floor_markers(context, collection, armature)
+ except Exception as exc:
+ print(f"Motion2MixamoRig floor markers skipped: {exc}")
+
class M2MR_OT_import_result(Operator):
bl_idname = "m2mr.import_result"
diff --git a/blender_extension/motion2mixamorig_blender/panels/main_panel.py b/blender_extension/motion2mixamorig_blender/panels/main_panel.py
index 57f9fda..5b862a7 100644
--- a/blender_extension/motion2mixamorig_blender/panels/main_panel.py
+++ b/blender_extension/motion2mixamorig_blender/panels/main_panel.py
@@ -166,6 +166,7 @@ class M2MR_PT_main(Panel):
box.label(text=t("glb_fmt", name=Path(props.job_glb_path).name))
row = box.row()
row.operator("m2mr.import_result", text=t("import_character"), icon="IMPORT")
+ box.prop(props, "show_floor_markers", text=t("show_floor_markers"))
row = box.row()
row.operator("m2mr.open_output", text=t("open_output"), icon="FILE_FOLDER")
row.operator("m2mr.view_log", text=t("view_log"), icon="TEXT")
diff --git a/blender_extension/motion2mixamorig_blender/properties.py b/blender_extension/motion2mixamorig_blender/properties.py
index f86460e..bbb70f7 100644
--- a/blender_extension/motion2mixamorig_blender/properties.py
+++ b/blender_extension/motion2mixamorig_blender/properties.py
@@ -24,6 +24,18 @@ def _source_type_items(self, context):
return _SOURCE_TYPE_ITEMS
+def _update_show_floor_markers(self, context) -> None:
+ from .operators.import_result import apply_floor_marker_visibility
+
+ apply_floor_marker_visibility(bool(self.show_floor_markers))
+ screen = getattr(context, "screen", None) if context is not None else None
+ if screen is None:
+ return
+ for area in screen.areas:
+ if area.type == "VIEW_3D":
+ area.tag_redraw()
+
+
def _device_items(self, context):
from .i18n import t
@@ -91,6 +103,12 @@ class M2MRProperties(PropertyGroup):
job_id: StringProperty(name="Job id", default="", maxlen=128)
job_source_name: StringProperty(name="Source name", default="", maxlen=128)
import_note: StringProperty(name="Import note", default="", maxlen=512)
+ show_floor_markers: BoolProperty(
+ name="Floor Markers",
+ description="Show or hide the floor markers",
+ default=True,
+ update=_update_show_floor_markers,
+ )
# First-run model download, filled in by the job poller.
dl_active: BoolProperty(name="Downloading models", default=False)
diff --git a/motion2mixamorig/cli.py b/motion2mixamorig/cli.py
index 3d541cf..693966f 100644
--- a/motion2mixamorig/cli.py
+++ b/motion2mixamorig/cli.py
@@ -292,6 +292,7 @@ def run(args: argparse.Namespace) -> int:
output_dir=output_dir,
progress=progress,
no_preview=bool(getattr(args, "no_preview", False)),
+ foot_lock=not bool(getattr(args, "no_foot_lock", False)),
)
except Exception:
import traceback
@@ -357,6 +358,11 @@ def build_parser() -> argparse.ArgumentParser:
action="store_true",
help="skip preview videos/images; still write NPZ, GLB, and run.json",
)
+ p_run.add_argument(
+ "--no-foot-lock",
+ action="store_true",
+ help="do not pin planted feet (keeps the raw retarget, feet may slide)",
+ )
p_diag = sub.add_parser(
"diagnose",
diff --git a/motion2mixamorig/diagnose_report.py b/motion2mixamorig/diagnose_report.py
index 766fe6c..e7e668a 100644
--- a/motion2mixamorig/diagnose_report.py
+++ b/motion2mixamorig/diagnose_report.py
@@ -244,7 +244,7 @@ _TEMPLATE = r"""<!doctype html>
<div class="body"></div>
</div>
<div class="vp" id="view">
- <div class="phead">Viewport <span class="sub">Character</span></div>
+ <div class="phead">Viewport <span class="sub" id="viewSub">Character</span></div>
<div class="body" id="viewBody">
<span class="hint">LMB orbit · Wheel zoom</span>
<div class="caption" id="caption"></div>
@@ -513,7 +513,7 @@ renderer.setPixelRatio(window.devicePixelRatio || 1);
renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
view.prepend(renderer.domElement);
-// Dark viewport: grey void, metre grid on the floor, soft contact shadow.
+// Dark viewport: grey void, fixed floor grid and crosses, soft contact shadow.
const BG = 0x2b2b2b;
const scene = new THREE.Scene();
scene.background = new THREE.Color(BG);
@@ -528,12 +528,74 @@ sun.shadow.mapSize.set(2048, 2048); sun.shadow.radius = 6;
Object.assign(sun.shadow.camera, { left: -2, right: 2, top: 2, bottom: -2, near: 0.5, far: 20 });
scene.add(sun); scene.add(sun.target);
const floor = new THREE.Group(); scene.add(floor);
-const minor = new THREE.GridHelper(40, 400, 0x353535, 0x353535), major = new THREE.GridHelper(40, 40, 0x4a4a4a, 0x4a4a4a);
+const minor = new THREE.GridHelper(40, 400, 0x555555, 0x555555), major = new THREE.GridHelper(40, 40, 0x8a8a8a, 0x8a8a8a);
minor.position.y = 0.0005; major.position.y = 0.001;
const ground = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), new THREE.ShadowMaterial({ opacity: 0.45 }));
ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true;
floor.add(minor, major, ground);
+// World-fixed crosses on y=0. Half-metre marks, larger metre marks, green origin.
+function addFloorMarkers(parent, gltf, sceneBox) {
+ let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
+ const clip = gltf.animations && gltf.animations[0];
+ if (clip) {
+ for (const track of clip.tracks) {
+ const name = track.name.toLowerCase();
+ if (!name.includes('hips') || (!name.endsWith('position') && !name.includes('translation'))) continue;
+ const v = track.values;
+ for (let i = 0; i + 2 < v.length; i += 3) {
+ minX = Math.min(minX, v[i]); maxX = Math.max(maxX, v[i]);
+ minZ = Math.min(minZ, v[i + 2]); maxZ = Math.max(maxZ, v[i + 2]);
+ }
+ }
+ }
+ if (!isFinite(minX)) {
+ minX = sceneBox.min.x; maxX = sceneBox.max.x; minZ = sceneBox.min.z; maxZ = sceneBox.max.z;
+ }
+ minX -= 1.5; maxX += 1.5; minZ -= 1.5; maxZ += 1.5;
+ let step = 0.5;
+ let x0 = Math.floor(minX / step) * step, x1 = Math.ceil(maxX / step) * step;
+ let z0 = Math.floor(minZ / step) * step, z1 = Math.ceil(maxZ / step) * step;
+ if ((Math.round((x1 - x0) / step) + 1) * (Math.round((z1 - z0) / step) + 1) > 2500) {
+ step = 1;
+ x0 = Math.floor(minX); x1 = Math.ceil(maxX); z0 = Math.floor(minZ); z1 = Math.ceil(maxZ);
+ }
+ const positions = [], colors = [], indices = [];
+ const y = 0.004;
+ const cOrigin = new THREE.Color(0x76b900), cMetre = new THREE.Color(0xd0d0d0), cHalf = new THREE.Color(0x8a8a8a);
+ function plus(x, z, arm, thick, color) {
+ const bars = [[-arm, -thick, arm, -thick, arm, thick, -arm, thick], [-thick, -arm, thick, -arm, thick, arm, -thick, arm]];
+ for (const b of bars) {
+ const o = positions.length / 3;
+ for (let k = 0; k < 8; k += 2) {
+ positions.push(x + b[k], y, z + b[k + 1]);
+ colors.push(color.r, color.g, color.b);
+ }
+ indices.push(o, o + 1, o + 2, o, o + 2, o + 3);
+ }
+ }
+ const nx = Math.round((x1 - x0) / step), nz = Math.round((z1 - z0) / step);
+ for (let ix = 0; ix <= nx; ix++) {
+ for (let iz = 0; iz <= nz; iz++) {
+ const x = x0 + ix * step, z = z0 + iz * step;
+ const origin = Math.abs(x) < 1e-3 && Math.abs(z) < 1e-3;
+ const metre = Math.abs(x - Math.round(x)) < 1e-3 && Math.abs(z - Math.round(z)) < 1e-3;
+ plus(x, z, origin ? 0.16 : metre ? 0.10 : 0.055, origin ? 0.016 : 0.010, origin ? cOrigin : metre ? cMetre : cHalf);
+ }
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
+ geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
+ geo.setIndex(indices);
+ const mesh = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({
+ vertexColors: true, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1,
+ }));
+ mesh.frustumCulled = false;
+ parent.add(mesh);
+ const sub = document.getElementById('viewSub');
+ if (sub) sub.textContent = 'floor markers ' + step + ' m';
+}
+
function size() { const w = view.clientWidth, h = view.clientHeight; renderer.setSize(w, h); camera.aspect = w / Math.max(1, h); camera.updateProjectionMatrix(); }
window.addEventListener('resize', size); size();
@@ -576,7 +638,8 @@ new GLTFLoader().parse(bytes.buffer, '', gltf => {
mixer.setTime(0); gltf.scene.updateMatrixWorld(true);
const box = new THREE.Box3().setFromObject(gltf.scene), c = box.getCenter(new THREE.Vector3()), sz = box.getSize(new THREE.Vector3());
- floor.position.y = box.min.y;
+ floor.position.y = 0;
+ addFloorMarkers(floor, gltf, box);
controls.target.copy(c);
camera.position.copy(c).add(new THREE.Vector3(sz.y * 0.7, sz.y * 0.75, Math.max(sz.y, sz.x) * 2.2));
controls.update();
@@ -587,7 +650,7 @@ new GLTFLoader().parse(bytes.buffer, '', gltf => {
window.diag.onFrame = (f, active) => {
mixer.setTime(f / FPS); paint(active);
if (hips) { gltf.scene.updateMatrixWorld(true); hips.getWorldPosition(follow); } else follow.copy(c);
- sun.target.position.set(follow.x, box.min.y, follow.z); sun.position.set(follow.x + 2.5, box.min.y + 6, follow.z + 3);
+ sun.target.position.set(follow.x, 0, follow.z); sun.position.set(follow.x + 2.5, 6, follow.z + 3);
};
window.diag.setFrame(+document.getElementById('frameField').value || 0);
renderer.setAnimationLoop(() => { controls.update(); renderer.render(scene, camera); });
diff --git a/motion2mixamorig/extract.py b/motion2mixamorig/extract.py
index dd2e564..f9cff9d 100644
--- a/motion2mixamorig/extract.py
+++ b/motion2mixamorig/extract.py
@@ -225,6 +225,22 @@ def joints_world_from_smplx(params, device: str = "cpu") -> np.ndarray:
return joints.cpu().numpy().astype(np.float32)
+def foot_contact_from_raw(raw) -> np.ndarray | None:
+ """(F, 4) static probability of left ankle, left foot, right ankle, right foot.
+
+ GVHMR's static_conf_logits channels are [L_ankle, L_foot, R_ankle, R_foot,
+ L_wrist, R_wrist]; only the feet are kept.
+ """
+ try:
+ logits = _to_numpy(raw["net_outputs"]["static_conf_logits"])
+ except (KeyError, TypeError):
+ return None
+ logits = np.asarray(logits, dtype=np.float64).reshape(-1, logits.shape[-1])
+ if logits.shape[-1] < 4:
+ return None
+ return (1.0 / (1.0 + np.exp(-logits[:, :4]))).astype(np.float32)
+
+
def _stabilize_pose_cache(pose_cache: Path) -> bool:
"""Stabilize GVHMR's 2D-pose cache in place. True if the file changed.
@@ -423,6 +439,9 @@ def extract_motion(
camera=np.array(result.camera),
video=np.array(str(video)),
)
+ contact = foot_contact_from_raw(getattr(result, "raw", None))
+ if contact is not None and len(contact) == len(joints_3d):
+ payload["foot_contact"] = contact
if source_image is not None:
payload["image"] = np.array(str(source_image))
_strip_cache_videos(output_dir)
diff --git a/motion2mixamorig/human_motion.py b/motion2mixamorig/human_motion.py
index 2e3a389..66241d9 100644
--- a/motion2mixamorig/human_motion.py
+++ b/motion2mixamorig/human_motion.py
@@ -20,6 +20,8 @@ class HumanMotion:
timestamps: np.ndarray
root_translation: np.ndarray | None
path: Path
+ # (F, 4) static probability: left ankle, left foot, right ankle, right foot.
+ foot_contact: np.ndarray | None = None
@property
def n_frames(self) -> int:
@@ -54,6 +56,10 @@ def load_human_motion(path: Path) -> HumanMotion:
if "root_translation" in data.files
else None
)
+ if "foot_contact" in data.files:
+ contact = np.asarray(data["foot_contact"], dtype=np.float64)
+ else:
+ contact = foot_contact_from_cache(path, len(joints))
return HumanMotion(
joints_3d=joints,
joint_names=names,
@@ -61,9 +67,32 @@ def load_human_motion(path: Path) -> HumanMotion:
timestamps=timestamps,
root_translation=root,
path=path,
+ foot_contact=contact,
)
+def foot_contact_from_cache(npz_path: Path, n_frames: int) -> np.ndarray | None:
+ """Foot contact for a skeleton_motion.npz written before it carried one.
+
+ Reads GVHMR's cached prediction in the run's cache/<clip>/hmr4d_results.pt.
+ """
+ candidates = sorted((Path(npz_path).parent / "cache").glob("*/hmr4d_results.pt"))
+ if not candidates:
+ return None
+ try:
+ import torch
+
+ from .extract import foot_contact_from_raw
+
+ for candidate in candidates:
+ contact = foot_contact_from_raw(torch.load(candidate, map_location="cpu", weights_only=False))
+ if contact is not None and len(contact) == n_frames:
+ return contact.astype(np.float64)
+ except Exception: # noqa: BLE001
+ return None
+ return None
+
+
def source_video_path(motion: HumanMotion) -> Path | None:
"""The input video recorded inside skeleton_motion.npz, if still on disk."""
npz = np.load(motion.path, allow_pickle=True)
diff --git a/motion2mixamorig/mixamo/animation.py b/motion2mixamorig/mixamo/animation.py
index 6ac158b..1f95d14 100644
--- a/motion2mixamorig/mixamo/animation.py
+++ b/motion2mixamorig/mixamo/animation.py
@@ -5,6 +5,10 @@
Mixamo Skeleton R_anim
| rest-relative transfer from the T-pose calibration
character rig R_anim -> FK -> linear blend skinning
+
+When the motion carries foot contact, planted feet are pinned on both the
+Mixamo Skeleton and the character rig (foot_lock.py) after the transfer, and
+the hips then shift vertically so the planted sole sits on y = 0 (ground.py).
"""
from __future__ import annotations
@@ -13,6 +17,8 @@ from dataclasses import dataclass, field
import numpy as np
+from .foot_lock import lock_feet
+from .ground import plant_soles
from .kinematics import forward_kinematics, world_positions_m
from .retarget import joint_mixamo, retarget_one_frame
from .skinned_mesh import YBotAsset, bone_palette, skin_mesh
@@ -32,6 +38,8 @@ class RetargetedAnimation:
human_pos: list[dict[str, np.ndarray]]
twist_events: list[dict] = field(default_factory=list)
sign_events: list[dict] = field(default_factory=list)
+ foot_lock: dict | None = None
+ ground: dict | None = None
@property
def n(self) -> int:
@@ -39,7 +47,13 @@ class RetargetedAnimation:
def build_animation(
- motion, mapping: YBotMapping, frames: list[int], *, verbose: bool = True
+ motion,
+ mapping: YBotMapping,
+ frames: list[int],
+ *,
+ verbose: bool = True,
+ foot_lock: bool = True,
+ asset: YBotAsset | None = None,
) -> RetargetedAnimation:
"""Retarget Human -> Mixamo, then carry the rest-relative motion onto the rig."""
skel = mapping.skeleton_rig
@@ -81,6 +95,41 @@ def build_animation(
r_prev, q_prev = result.r_anim_raw, result.q_anim
if verbose and (i == 0 or (i + 1) % 200 == 0 or i == len(frames) - 1):
print(f" retarget {i + 1}/{len(frames)}")
+
+ contact = getattr(motion, "foot_contact", None)
+ contact_frames = None if contact is None else np.asarray(contact)[list(frames)]
+ if foot_lock and contact_frames is not None and len(frames) > 1:
+ anim.r_anim_skeleton, _ = lock_feet(
+ skel, anim.r_anim_skeleton, anim.hips_cm_skeleton, contact_frames, anim.fps
+ )
+ anim.r_anim_rig, stats = lock_feet(
+ mapping.ybot_rig, anim.r_anim_rig, anim.hips_cm_rig, contact_frames, anim.fps
+ )
+ anim.mixamo_pos = [
+ world_positions_m(skel, forward_kinematics(skel, r, hips_translation_cm=h))
+ for r, h in zip(anim.r_anim_skeleton, anim.hips_cm_skeleton)
+ ]
+ anim.rig_pos = [mapping.ybot_positions_m(r, h) for r, h in zip(anim.r_anim_rig, anim.hips_cm_rig)]
+ anim.foot_lock = stats.as_dict()
+ if verbose:
+ print(
+ f" foot lock: mean correction {stats.mean_correction_cm:.1f} cm, "
+ f"max {stats.max_correction_cm:.1f} cm, "
+ f"hips shifted on {stats.hip_shift_frames} frames "
+ f"(mean {stats.mean_hip_shift_cm:.1f} cm, max {stats.max_hip_shift_cm:.1f} cm), "
+ f"out of reach {stats.unreachable_frames} frames"
+ )
+ elif verbose and foot_lock:
+ print(" foot lock: no foot contact in the skeleton; skipped")
+ if asset is not None and contact_frames is not None and len(frames) > 1:
+ anim.ground = plant_soles(anim, mapping, asset, contact_frames)
+ if verbose and anim.ground is not None:
+ sole = anim.ground["support_sole_cm"]
+ print(
+ f" ground: hips shifted median {anim.ground['median_shift_cm']:.1f} cm, "
+ f"max {anim.ground['max_shift_cm']:.1f} cm, "
+ f"support sole median {sole['median']} cm"
+ )
return anim
diff --git a/motion2mixamorig/mixamo/foot_lock.py b/motion2mixamorig/mixamo/foot_lock.py
new file mode 100644
index 0000000..ccd8c62
--- /dev/null
+++ b/motion2mixamorig/mixamo/foot_lock.py
@@ -0,0 +1,326 @@
+"""Keep planted feet still on a retargeted rig.
+
+GVHMR predicts, per frame, how confident it is that each of four foot joints
+is static: left/right ankle (heel side) and left/right foot (ball of the foot).
+Heel and ball are locked independently, so a flat foot, a heel raise pivoting
+on the ball, and a heel strike with the toes up each keep the part that is
+actually on the ground in place.
+
+Per contact segment the locked point is pinned at its mean position over the
+segment. The correction (pinned minus raw) fades out over a short window on
+both sides of the segment so the swing leg does not pop. Each frame then:
+
+ ankle target = raw ankle + ball correction while the ball is planted,
+ else + heel correction (heel strike, toes up)
+ UpLeg / Leg = analytic two-bone IK to the ankle target, knee kept in the
+ plane of the original bend
+
+The ball wins when both are planted: the two anchors come from different
+segments and are not a rigid foot length apart, so forcing both would twist
+the foot. The foot keeps its original world orientation, so a heel raise
+still pivots about the pinned ball.
+
+When a straight leg still cannot reach its anchor, the hips translate by the
+smallest move that brings every planted hip joint into reach. Both hip joints
+share that translation. Nothing is snapped to a floor here: only drift during
+contact is removed.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+from .kinematics import (
+ MixamoRig,
+ anim_from_world_rotation,
+ forward_kinematics,
+ normalize,
+ rotation_aligning,
+)
+
+# Column order of `foot_contact` in skeleton_motion.npz (GVHMR static_conf_logits[..., :4]).
+CONTACT_CHANNELS = ("left_ankle", "left_foot", "right_ankle", "right_foot")
+SIDES = (("Left", 0, 1), ("Right", 2, 3))
+
+ENTER_CONF = 0.8
+EXIT_CONF = 0.5
+MIN_CONTACT_S = 0.1
+BLEND_S = 0.15
+
+
+@dataclass
+class FootLockStats:
+ planted_fraction: dict[str, float]
+ segments: dict[str, int]
+ mean_correction_cm: float
+ max_correction_cm: float
+ unreachable_frames: int
+ hip_shift_frames: int
+ mean_hip_shift_cm: float
+ max_hip_shift_cm: float
+
+ def as_dict(self) -> dict:
+ return {
+ "planted_fraction": {k: round(v, 3) for k, v in self.planted_fraction.items()},
+ "segments": dict(self.segments),
+ "mean_correction_cm": round(self.mean_correction_cm, 2),
+ "max_correction_cm": round(self.max_correction_cm, 2),
+ "unreachable_frames": self.unreachable_frames,
+ "hip_shift_frames": self.hip_shift_frames,
+ "mean_hip_shift_cm": round(self.mean_hip_shift_cm, 2),
+ "max_hip_shift_cm": round(self.max_hip_shift_cm, 2),
+ }
+
+
+def contact_mask(conf: np.ndarray, fps: float) -> np.ndarray:
+ """Hysteresis on one confidence channel, then drop contacts shorter than MIN_CONTACT_S."""
+ conf = np.asarray(conf, dtype=np.float64)
+ mask = np.zeros(len(conf), dtype=bool)
+ on = False
+ for i, c in enumerate(conf):
+ on = c >= EXIT_CONF if on else c >= ENTER_CONF
+ mask[i] = on
+ min_len = max(2, int(round(MIN_CONTACT_S * fps)))
+ for s, e in segments(mask):
+ if e - s < min_len:
+ mask[s:e] = False
+ return mask
+
+
+def segments(mask: np.ndarray) -> list[tuple[int, int]]:
+ """[start, end) runs of True."""
+ padded = np.concatenate([[False], np.asarray(mask, dtype=bool), [False]])
+ edges = np.flatnonzero(padded[1:] != padded[:-1])
+ return [(int(s), int(e)) for s, e in zip(edges[::2], edges[1::2])]
+
+
+def _fade(distance: int, blend: int) -> float:
+ """1 next to a contact, 0 at `blend` frames away (smoothstep)."""
+ x = min(1.0, distance / float(blend))
+ return 1.0 - x * x * (3.0 - 2.0 * x)
+
+
+def correction_track(raw: np.ndarray, mask: np.ndarray, blend: int) -> tuple[np.ndarray, np.ndarray]:
+ """Per-frame offset that pins `raw` (F, 3) during contact, plus its weight in [0, 1]."""
+ n = len(raw)
+ offset = np.zeros((n, 3))
+ weight = np.zeros(n)
+ segs = segments(mask)
+ for s, e in segs:
+ offset[s:e] = raw[s:e].mean(axis=0) - raw[s:e]
+ weight[s:e] = 1.0
+ bounds = [(None, None)] + segs + [(None, None)]
+ for (_, prev_end), (next_start, _) in zip(bounds[:-1], bounds[1:]):
+ lo = 0 if prev_end is None else prev_end
+ hi = n if next_start is None else next_start
+ for t in range(lo, hi):
+ a = _fade(t - prev_end + 1, blend) if prev_end is not None else 0.0
+ b = _fade(next_start - t, blend) if next_start is not None else 0.0
+ if a + b > 1.0:
+ a, b = a / (a + b), b / (a + b)
+ if a == 0.0 and b == 0.0:
+ continue
+ o_prev = offset[prev_end - 1] if prev_end is not None else 0.0
+ o_next = offset[next_start] if next_start is not None else 0.0
+ offset[t] = a * o_prev + b * o_next
+ weight[t] = max(a, b)
+ return offset, weight
+
+
+def _project_ball(point: np.ndarray, center: np.ndarray, radius: float) -> np.ndarray:
+ """Closest point to `point` that lies inside the ball."""
+ delta = np.asarray(point, dtype=np.float64) - center
+ dist = float(np.linalg.norm(delta))
+ if dist <= radius or dist < 1e-12:
+ return np.asarray(point, dtype=np.float64).copy()
+ return center + delta * (radius / dist)
+
+
+def _equal_shortfall(center_a: np.ndarray, radius_a: float, center_b: np.ndarray, radius_b: float) -> np.ndarray:
+ """Where two non-overlapping balls meet once each radius grows by the same amount."""
+ span = center_b - center_a
+ dist = float(np.linalg.norm(span))
+ if dist < 1e-12:
+ return center_a.copy()
+ along = float(np.clip((dist + radius_a - radius_b) * 0.5, 0.0, dist))
+ return center_a + span * (along / dist)
+
+
+def hip_reach_delta(constraints: list[tuple[np.ndarray, float]]) -> np.ndarray:
+ """Smallest shared translation that puts every hip joint within reach of its target.
+
+ Each entry is `(target - hip_joint, reach)`. Both hip joints move by the same
+ vector, so the unknown is that translation and zero means the body stays put.
+ A target already in reach contributes a ball that contains the origin.
+ """
+ balls = [(np.asarray(center, dtype=np.float64), float(radius)) for center, radius in constraints if radius > 0.0]
+ if not balls:
+ return np.zeros(3)
+ if len(balls) == 1:
+ return _project_ball(np.zeros(3), balls[0][0], balls[0][1])
+
+ (center_a, radius_a), (center_b, radius_b) = balls[:2]
+ dist = float(np.linalg.norm(center_b - center_a))
+ if dist > radius_a + radius_b + 1e-6:
+ return _equal_shortfall(center_a, radius_a, center_b, radius_b)
+ if dist < abs(radius_a - radius_b) - 1e-6:
+ if radius_a <= radius_b:
+ return _project_ball(np.zeros(3), center_a, radius_a)
+ return _project_ball(np.zeros(3), center_b, radius_b)
+
+ # Dykstra: Euclidean projection of the origin onto the intersection.
+ point = np.zeros(3)
+ slack = [np.zeros(3), np.zeros(3)]
+ for _ in range(24):
+ for index, (center, radius) in enumerate(balls[:2]):
+ previous = point.copy()
+ point = _project_ball(previous + slack[index], center, radius)
+ slack[index] = previous + slack[index] - point
+ return point
+
+
+def two_bone_ik(
+ hip: np.ndarray,
+ knee: np.ndarray,
+ ankle: np.ndarray,
+ target: np.ndarray,
+ pole_hint: np.ndarray,
+) -> tuple[np.ndarray, np.ndarray, bool]:
+ """World-space swings for the thigh and shin that put the ankle on `target`.
+
+ The knee stays in the plane of the original bend (or of `pole_hint` when
+ the leg is straight). Out-of-reach targets are clamped to full extension.
+ """
+ l1 = float(np.linalg.norm(knee - hip))
+ l2 = float(np.linalg.norm(ankle - knee))
+ v = target - hip
+ dist = float(np.linalg.norm(v))
+ u = normalize(v, normalize(ankle - hip))
+ reach = (l1 + l2) * 0.9999
+ unreachable = dist > reach
+ dist = float(np.clip(dist, abs(l1 - l2) + 1e-6, reach))
+
+ pole = (knee - hip) - u * float((knee - hip) @ u)
+ if np.linalg.norm(pole) < 1e-3 * l1:
+ pole = pole_hint - u * float(pole_hint @ u)
+ pole = normalize(pole, np.array([0.0, 0.0, 1.0]))
+
+ cos_a = float(np.clip((l1 * l1 + dist * dist - l2 * l2) / (2.0 * l1 * dist), -1.0, 1.0))
+ sin_a = float(np.sqrt(max(0.0, 1.0 - cos_a * cos_a)))
+ knee_new = hip + l1 * (cos_a * u + sin_a * pole)
+ ankle_new = hip + dist * u
+
+ r_thigh = rotation_aligning(knee - hip, knee_new - hip)
+ r_shin = rotation_aligning(r_thigh @ (ankle - knee), ankle_new - knee_new)
+ return r_thigh, r_shin, unreachable
+
+
+def lock_feet(
+ rig: MixamoRig,
+ r_anims: list[dict[str, np.ndarray]],
+ hips_cm: list[np.ndarray],
+ contact: np.ndarray,
+ fps: float,
+) -> tuple[list[dict[str, np.ndarray]], FootLockStats]:
+ """Return new per-frame R_anim dicts with the planted feet pinned.
+
+ `contact` is (F, 4) in CONTACT_CHANNELS order, aligned with `r_anims`.
+ Leg rotations change, and `hips_cm` is shifted in place when a straight
+ leg cannot reach its anchor.
+ """
+ n = len(r_anims)
+ contact = np.asarray(contact, dtype=np.float64)
+ if contact.shape != (n, 4):
+ raise ValueError(f"foot contact must be ({n}, 4), got {contact.shape}")
+ blend = max(2, int(round(BLEND_S * fps)))
+
+ worlds = [forward_kinematics(rig, r_anims[i], hips_translation_cm=hips_cm[i]) for i in range(n)]
+
+ tracks = {}
+ planted: dict[str, float] = {}
+ seg_count: dict[str, int] = {}
+ for side, heel_ch, ball_ch in SIDES:
+ foot, toe = f"mixamorig:{side}Foot", f"mixamorig:{side}ToeBase"
+ ankle_raw = np.stack([w[foot][:3, 3] for w in worlds])
+ ball_raw = np.stack([w[toe][:3, 3] for w in worlds])
+ heel_mask = contact_mask(contact[:, heel_ch], fps)
+ ball_mask = contact_mask(contact[:, ball_ch], fps)
+ tracks[side] = (
+ correction_track(ankle_raw, heel_mask, blend),
+ correction_track(ball_raw, ball_mask, blend),
+ )
+ for label, mask in ((CONTACT_CHANNELS[heel_ch], heel_mask), (CONTACT_CHANNELS[ball_ch], ball_mask)):
+ planted[label] = float(mask.mean()) if n else 0.0
+ seg_count[label] = len(segments(mask))
+
+ out = [dict(r) for r in r_anims]
+ corrections: list[float] = []
+ hip_shifts: list[float] = []
+ unreachable = 0
+ # Stay just inside two_bone_ik's own reach clamp so the shifted hip counts as reachable.
+ reach_scale = 0.999
+ for i in range(n):
+ world = worlds[i]
+ planted_legs = []
+ for side, _, _ in SIDES:
+ (off_h, w_h), (off_b, w_b) = tracks[side]
+ if w_h[i] == 0.0 and w_b[i] == 0.0:
+ continue
+ up, leg, foot, toe = (f"mixamorig:{side}{b}" for b in ("UpLeg", "Leg", "Foot", "ToeBase"))
+ hip_p = world[up][:3, 3]
+ knee_p = world[leg][:3, 3]
+ ankle_p = world[foot][:3, 3]
+ ball_p = world[toe][:3, 3]
+ ankle_off = w_b[i] * off_b[i] + (1.0 - w_b[i]) * off_h[i]
+ reach = (float(np.linalg.norm(knee_p - hip_p)) + float(np.linalg.norm(ankle_p - knee_p))) * reach_scale
+ planted_legs.append(
+ {
+ "up": up,
+ "leg": leg,
+ "foot": foot,
+ "hip": hip_p,
+ "knee": knee_p,
+ "ankle": ankle_p,
+ "target": ankle_p + ankle_off,
+ "pole": ball_p - ankle_p,
+ "reach": reach,
+ "correction_cm": float(np.linalg.norm(ankle_off)) * rig.meters_per_unit * 100.0,
+ }
+ )
+ delta = hip_reach_delta([(leg["target"] - leg["hip"], leg["reach"]) for leg in planted_legs])
+ shift_cm = float(np.linalg.norm(delta)) * rig.meters_per_unit * 100.0
+ if shift_cm > 0.0:
+ hips_cm[i] = np.asarray(hips_cm[i], dtype=np.float64) + delta
+ if shift_cm > 0.01:
+ hip_shifts.append(shift_cm)
+ for leg in planted_legs:
+ r_thigh, r_shin, miss = two_bone_ik(
+ leg["hip"] + delta,
+ leg["knee"] + delta,
+ leg["ankle"] + delta,
+ leg["target"],
+ leg["pole"],
+ )
+ unreachable += int(miss)
+ corrections.append(leg["correction_cm"])
+ parent_r = world[rig.bones[leg["up"]].parent][:3, :3]
+ w_up = r_thigh @ world[leg["up"]][:3, :3]
+ w_leg = r_shin @ r_thigh @ world[leg["leg"]][:3, :3]
+ w_foot = world[leg["foot"]][:3, :3]
+ out[i][leg["up"]] = anim_from_world_rotation(rig.bones[leg["up"]], parent_r, w_up)
+ out[i][leg["leg"]] = anim_from_world_rotation(rig.bones[leg["leg"]], w_up, w_leg)
+ out[i][leg["foot"]] = anim_from_world_rotation(rig.bones[leg["foot"]], w_leg, w_foot)
+
+ stats = FootLockStats(
+ planted_fraction=planted,
+ segments=seg_count,
+ mean_correction_cm=float(np.mean(corrections)) if corrections else 0.0,
+ max_correction_cm=float(np.max(corrections)) if corrections else 0.0,
+ unreachable_frames=unreachable,
+ hip_shift_frames=len(hip_shifts),
+ mean_hip_shift_cm=float(np.mean(hip_shifts)) if hip_shifts else 0.0,
+ max_hip_shift_cm=float(np.max(hip_shifts)) if hip_shifts else 0.0,
+ )
+ return out, stats
diff --git a/motion2mixamorig/mixamo/ground.py b/motion2mixamorig/mixamo/ground.py
new file mode 100644
index 0000000..8f1e9ee
--- /dev/null
+++ b/motion2mixamorig/mixamo/ground.py
@@ -0,0 +1,173 @@
+"""Put the planted sole on y = 0.
+
+Foot lock pins a foot where it already was, and that height is the recovered
+skeleton's, not the floor. The character's sole sits a different distance
+below the foot bone than the skeleton joint does, and the recovered height
+drifts over a clip, so the mesh ends up floating or sunk in Blender.
+
+The sole is the lowest skinned vertex of the planted part: the heel (Foot)
+or the ball (ToeBase / Toe_End). On a planted frame the hips translate
+vertically so that vertex lands on y = 0. A plant holds the offset of its
+lowest frame, so the sole can lift during the step but does not sink.
+Airborne frames blend from the previous plant to the next, which keeps a
+jump's height and removes the slow drift between steps.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+
+from .foot_lock import contact_mask, segments
+from .kinematics import forward_kinematics, world_positions_m
+from .skinned_mesh import YBotAsset
+
+# Column order matches foot_contact: left heel, left ball, right heel, right ball.
+SOLE_BONES = (
+ ("mixamorig:LeftFoot",),
+ ("mixamorig:LeftToeBase", "mixamorig:LeftToe_End"),
+ ("mixamorig:RightFoot",),
+ ("mixamorig:RightToeBase", "mixamorig:RightToe_End"),
+)
+
+
+def _skin(vertices: np.ndarray, weights: np.ndarray, palette: np.ndarray) -> np.ndarray:
+ ones = np.ones((len(vertices), 1), dtype=np.float64)
+ posed = np.zeros((len(vertices), 4), dtype=np.float64)
+ homogeneous = np.concatenate([vertices, ones], axis=1)
+ for bone in range(palette.shape[0]):
+ weight = weights[:, bone]
+ if float(weight.max()) < 1e-12:
+ continue
+ posed += weight[:, None] * (homogeneous @ palette[bone].T)
+ return posed[:, :3]
+
+
+def _sole_vertices(asset: YBotAsset) -> list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]]:
+ """Per mesh: foot vertices, their weights, the inverse binds, and a group id per vertex.
+
+ Group ids are the SOLE_BONES columns. A vertex belongs to the foot bone that
+ owns most of its weight.
+ """
+ out = []
+ for mesh in asset.meshes:
+ group = np.full(len(mesh.vertices), -1, dtype=int)
+ dominant = mesh.weights.argmax(axis=1)
+ for column, bones in enumerate(SOLE_BONES):
+ owned = np.zeros(len(mesh.vertices), dtype=bool)
+ for bone in bones:
+ index = asset.bone_index.get(bone)
+ if index is None:
+ continue
+ owned |= (dominant == index) & (mesh.weights[:, index] > 0.5)
+ group[owned] = column
+ keep = group >= 0
+ if not np.any(keep):
+ continue
+ out.append((mesh.vertices[keep], mesh.weights[keep], mesh.ibm, group[keep]))
+ return out
+
+
+def sole_heights_m(
+ asset: YBotAsset,
+ r_anims: list[dict[str, np.ndarray]],
+ hips_cm: list[np.ndarray],
+ soles: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]] | None = None,
+) -> np.ndarray:
+ """(F, 4) world height of the lowest vertex of each sole group, in metres."""
+ if soles is None:
+ soles = _sole_vertices(asset)
+ n = len(r_anims)
+ heights = np.full((n, 4), np.nan)
+ scale = asset.rig.meters_per_unit
+ order = asset.rig.order
+ for i in range(n):
+ world = forward_kinematics(asset.rig, r_anims[i], hips_translation_cm=hips_cm[i])
+ for vertices, weights, ibm, group in soles:
+ palette = np.stack([world[name] for name in order], axis=0) @ ibm
+ posed = _skin(vertices, weights, palette)
+ for column in range(4):
+ picked = posed[group == column]
+ if len(picked) == 0:
+ continue
+ lowest = float(picked[:, 1].min()) * scale
+ if not np.isfinite(heights[i, column]) or lowest < heights[i, column]:
+ heights[i, column] = lowest
+ return heights
+
+
+def support_delta_m(heights_m: np.ndarray, contact: np.ndarray, fps: float) -> np.ndarray:
+ """Per-frame vertical hips shift, in metres, that lands the support sole on y = 0.
+
+Planted frames use the lowest planted sole. Each contact holds the shift
+that puts the lowest frame of that contact on the floor, so the sole can
+lift during the step but does not sink through it. Airborne frames blend
+from the previous plant to the next; the clip before the first plant and
+after the last holds still.
+ """
+ n = len(heights_m)
+ raw = np.full(n, np.nan)
+ supported = np.zeros(n, dtype=bool)
+ masks = [contact_mask(contact[:, channel], fps) for channel in range(4)]
+ for i in range(n):
+ planted = [heights_m[i, column] for column, mask in enumerate(masks) if mask[i] and np.isfinite(heights_m[i, column])]
+ if not planted:
+ continue
+ raw[i] = -min(planted)
+ supported[i] = True
+
+ delta = np.zeros(n)
+ segs = segments(supported)
+ if not segs:
+ return delta
+ for start, end in segs:
+ delta[start:end] = float(np.max(raw[start:end]))
+ delta[: segs[0][0]] = delta[segs[0][0]]
+ delta[segs[-1][1] :] = delta[segs[-1][1] - 1]
+ for (_, left_end), (right_start, _) in zip(segs, segs[1:]):
+ gap = np.arange(left_end, right_start)
+ if len(gap) == 0:
+ continue
+ span = right_start - (left_end - 1)
+ t = (gap - (left_end - 1)) / span
+ delta[gap] = (1.0 - t) * delta[left_end - 1] + t * delta[right_start]
+ return delta
+
+
+def plant_soles(anim, mapping, asset: YBotAsset, contact: np.ndarray) -> dict:
+ """Shift both hip tracks so the planted sole sits on y = 0. Rotations stay."""
+ soles = _sole_vertices(asset)
+ heights = sole_heights_m(asset, anim.r_anim_rig, anim.hips_cm_rig, soles)
+ delta_m = support_delta_m(heights, np.asarray(contact, dtype=np.float64), float(anim.fps))
+ delta_cm = delta_m / asset.rig.meters_per_unit
+ align = mapping.r_world_align
+ scale = mapping.translation_scale
+ for i, shift_cm in enumerate(delta_cm):
+ anim.hips_cm_rig[i] = np.asarray(anim.hips_cm_rig[i], dtype=np.float64) + np.array([0.0, shift_cm, 0.0])
+ skeleton_shift = align.T @ np.array([0.0, shift_cm, 0.0]) / scale
+ anim.hips_cm_skeleton[i] = np.asarray(anim.hips_cm_skeleton[i], dtype=np.float64) + skeleton_shift
+
+ skel = mapping.skeleton_rig
+ anim.mixamo_pos = [
+ world_positions_m(skel, forward_kinematics(skel, r, hips_translation_cm=h))
+ for r, h in zip(anim.r_anim_skeleton, anim.hips_cm_skeleton)
+ ]
+ anim.rig_pos = [mapping.ybot_positions_m(r, h) for r, h in zip(anim.r_anim_rig, anim.hips_cm_rig)]
+
+ grounded = sole_heights_m(asset, anim.r_anim_rig, anim.hips_cm_rig, soles)
+ supported = np.zeros(len(delta_m), dtype=bool)
+ masks = [contact_mask(contact[:, channel], anim.fps) for channel in range(4)]
+ residual = []
+ for i in range(len(delta_m)):
+ planted = [grounded[i, column] for column, mask in enumerate(masks) if mask[i] and np.isfinite(grounded[i, column])]
+ if planted:
+ supported[i] = True
+ residual.append(min(planted) * 100.0)
+ return {
+ "median_shift_cm": round(float(np.median(np.abs(delta_m)) * 100.0), 2),
+ "max_shift_cm": round(float(np.max(np.abs(delta_m)) * 100.0), 2),
+ "supported_fraction": round(float(supported.mean()), 3),
+ "support_sole_cm": {
+ "median": round(float(np.median(residual)), 2) if residual else None,
+ "p95_abs": round(float(np.percentile(np.abs(residual), 95)), 2) if residual else None,
+ },
+ }
diff --git a/motion2mixamorig/pipeline.py b/motion2mixamorig/pipeline.py
index d58dd00..c0900a6 100644
--- a/motion2mixamorig/pipeline.py
+++ b/motion2mixamorig/pipeline.py
@@ -23,7 +23,7 @@ import numpy as np
from . import paths
from .errors import classify_error
from .diagnose import DIAGNOSTICS_JSON, diagnose_run, summary_line
-from .human_motion import HumanMotion, load_human_motion
+from .human_motion import HumanMotion, foot_contact_from_cache, load_human_motion
from .mixamo.animation import build_animation
from .mixamo.gltf import write_glb
from .mixamo.kinematics import quat_wxyz
@@ -82,6 +82,7 @@ def run_pipeline(
progress: ProgressWriter | None = None,
progress_jsonl: Path | None = None,
no_preview: bool = False,
+ foot_lock: bool = True,
) -> Path:
"""Full pipeline for one video or still + one rig. Returns the run directory.
@@ -92,6 +93,7 @@ def run_pipeline(
`output_dir` writes this run into a caller-chosen folder (used by the
Blender extension). When omitted, a timestamped directory is created.
`no_preview` still writes the NPZ/GLB products but skips rendered previews.
+ `foot_lock` pins planted feet using GVHMR's foot contact (when available).
"""
if image is None and video is None:
raise ValueError("run_pipeline needs a video or an image")
@@ -148,6 +150,8 @@ def run_pipeline(
verbose=verbose,
)
motion: HumanMotion = load_human_motion(motion_npz)
+ if motion.foot_contact is None and skeleton_npz is not None:
+ motion.foot_contact = foot_contact_from_cache(Path(skeleton_npz), motion.n_frames)
print(f"human motion {motion.n_frames} frames @ {motion.fps:g} fps")
stage = "retarget"
@@ -163,7 +167,9 @@ def run_pipeline(
print("retargeting")
frames = list(range(motion.n_frames))
- anim = build_animation(motion, mapping, frames, verbose=verbose)
+ anim = build_animation(
+ motion, mapping, frames, verbose=verbose, foot_lock=foot_lock, asset=asset
+ )
rotations_npz = run_dir / "mixamo_rotations.npz"
save_mixamo_rotations(anim, mapping, rig, rotations_npz)
@@ -231,6 +237,8 @@ def run_pipeline(
"rest_skin_error_cm": skin_err,
"twist_events": len(anim.twist_events),
"quat_sign_flips": len(anim.sign_events),
+ "foot_lock": anim.foot_lock,
+ "ground": anim.ground,
"diagnostics": diagnostics,
"outputs": outputs,
}