v2d / simulation /scripts /fetch_inspire_hand.py
hk239's picture
Upload v2d project (excluding data and .venv) (part 18)
3f4bb1d verified
Raw History Blame Contribute Delete
8.01 kB
#!/usr/bin/env python3
"""Fetch the G1 Inspire 5-finger USD and make it spawnable as a floating base.
Isaac Lab's ``g1_29dof_inspire_hand.usd`` is authored for a *fixed-base*
manipulation setup and needs two independent fixes before SONIC can use it. Both
faults report the same unhelpful symptom -- ``Pattern '/World/Robot/root_joint'
did not match any articulations`` -- because each one prevents PhysX from
creating the articulation at all.
1. **Mimic joints.** The Inspire finger linkages are ``physxMimicJoint:*``
properties (gearing -1.0 on the four fingers, -1.6 and -2.4 on the thumb).
This PhysX build cannot resolve them and logs ``failed to find internal joint
object for PhysxMimicJointAPI``. We strip all 60 properties, which leaves the
six coupled joints per hand independently actuated.
2. **Fixed base.** ``PhysicsArticulationRootAPI`` is applied to ``root_joint``,
a ``PhysicsFixedJoint`` anchoring the pelvis to the world. Spawning with
``fix_root_link=False`` disables that joint and takes the articulation root
with it. Stock ``g1.usd`` instead puts the root API on ``/g1/pelvis`` with no
root joint, so we match that: move the API and the ``physxArticulation:*``
solver settings onto the pelvis and drop the fixed joint.
The asset is a thin variant wrapper over four ``configuration/`` layers and
everything we touch lives in the 19 KB physics layer, so the 39 MB mesh layer is
mirrored untouched.
python scripts/fetch_inspire_hand.py [--force]
"""
from __future__ import annotations
import argparse
import urllib.request
from pathlib import Path
_ROOT = Path(__file__).resolve().parents[1]
_DEST = _ROOT / "assets" / "g1"
_BASE_URL = (
"https://omniverse-content-production.s3-us-west-2.amazonaws.com"
"/Assets/Isaac/6.0/Isaac/IsaacLab/Robots/Unitree/G1"
)
_WRAPPER = "g1_29dof_inspire_hand.usd"
_STEM = "g1_29dof_rev_1_0_with_inspire_hand_retarget_inspire_white"
_LAYERS = [f"{_STEM}_{k}.usd" for k in ("base", "physics", "robot", "sensor")]
_PHYSICS = f"{_STEM}_physics.usd"
_MARKER = "v2d_patch_version"
#: Bump when patch() changes, so an already-mirrored asset is re-patched.
_PATCH_VERSION = 2
_PRIM = "/g1_29dof_rev_1_0"
def _download(rel: str, dst: Path, force: bool) -> None:
if dst.is_file() and not force:
print(f" have {rel} ({dst.stat().st_size:,} B)")
return
dst.parent.mkdir(parents=True, exist_ok=True)
url = f"{_BASE_URL}/{rel}"
with urllib.request.urlopen(url) as r, open(dst, "wb") as f: # noqa: S310
f.write(r.read())
print(f" fetched {rel} ({dst.stat().st_size:,} B)")
def _drop_api_schema(spec, name: str) -> bool:
"""Remove one applied API schema from a prim spec, preserving the list-op kind."""
from pxr import Sdf
if not spec.HasInfo("apiSchemas"):
return False
op = spec.GetInfo("apiSchemas")
fields = ("explicitItems",) if op.isExplicit else ("prependedItems", "appendedItems", "addedItems")
new = Sdf.TokenListOp()
changed = False
for field in fields:
items = list(getattr(op, field))
kept = [t for t in items if name not in t]
changed |= len(kept) != len(items)
setattr(new, field, kept)
if changed:
spec.SetInfo("apiSchemas", new)
return changed
def _strip_mimic(layer) -> tuple[int, int]:
"""Drop the mimic properties *and* the now-orphaned API schema.
Removing only the properties leaves ``PhysxMimicJointAPI`` applied with no
``referenceJoint``, so PhysX logs an error per joint per articulation on
every run -- 48 lines for four environments -- which buries real errors.
The joints end up independently actuated either way.
"""
doomed: list = []
prims: list = []
def walk(spec) -> None:
for prop in spec.properties:
if "physxMimicJoint" in prop.name:
doomed.append(prop.path)
prims.append(spec)
for child in spec.nameChildren:
walk(child)
for root in layer.rootPrims:
walk(root)
for path in doomed:
del layer.GetPrimAtPath(path.GetPrimPath()).properties[path.name]
n_api = sum(_drop_api_schema(spec, "PhysxMimicJointAPI") for spec in prims)
return len(doomed), n_api
def _float_base(layer) -> bool:
"""Move the articulation root off the world-anchoring fixed joint."""
from pxr import Sdf
root_joint = layer.GetPrimAtPath(f"{_PRIM}/root_joint")
pelvis = layer.GetPrimAtPath(f"{_PRIM}/pelvis")
if root_joint is None or pelvis is None:
return False
for name in list(root_joint.properties.keys()):
if name.startswith("physxArticulation:"):
src = root_joint.properties[name]
dst = Sdf.AttributeSpec(pelvis, name, src.typeName)
dst.default = src.default
existing = pelvis.GetInfo("apiSchemas").prependedItems if pelvis.HasInfo("apiSchemas") else []
schemas = Sdf.TokenListOp()
schemas.prependedItems = list(existing) + ["PhysicsArticulationRootAPI"]
pelvis.SetInfo("apiSchemas", schemas)
del layer.GetPrimAtPath(_PRIM).nameChildren["root_joint"]
return True
def patch(layer_path: Path) -> tuple[int, int, bool]:
"""Strip mimic joints and float the base, in place. Idempotent."""
from pxr import Sdf
layer = Sdf.Layer.FindOrOpen(str(layer_path))
if layer is None:
raise SystemExit(f"cannot open {layer_path}")
if layer.customLayerData.get(_MARKER, 0) >= _PATCH_VERSION:
print(f" physics layer already patched (v{_PATCH_VERSION})")
return 0, 0, False
n_prop, n_api = _strip_mimic(layer)
floated = _float_base(layer)
data = dict(layer.customLayerData)
data[_MARKER] = _PATCH_VERSION
layer.customLayerData = data
layer.Save()
return n_prop, n_api, floated
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--force", action="store_true", help="re-download even if present")
args = ap.parse_args()
print(f"mirroring Inspire hand USD into {_DEST}")
_download(_WRAPPER, _DEST / _WRAPPER, args.force)
for name in _LAYERS:
_download(f"configuration/{name}", _DEST / "configuration" / name, args.force)
n_prop, n_api, floated = patch(_DEST / "configuration" / _PHYSICS)
if n_prop:
print(f" stripped {n_prop} mimic properties")
if n_api:
print(f" removed PhysxMimicJointAPI from {n_api} prims")
if floated:
print(" moved articulation root onto pelvis, removed root_joint")
from pxr import Usd
stage = Usd.Stage.Open(str(_DEST / _WRAPPER))
left = [
p.GetPath().pathString
for p in stage.Traverse()
if any("physxMimicJoint" in a.GetName() for a in p.GetAttributes())
]
# An applied-but-empty API is what makes PhysX log an error per joint.
left_api = [
p.GetPath().pathString
for p in stage.Traverse()
if any("PhysxMimicJointAPI" in s for s in p.GetAppliedSchemas())
]
fingers = [
p.GetName()
for p in stage.Traverse()
if p.GetName().startswith(("L_", "R_")) and p.GetName().endswith("_joint")
]
roots = [
(p.GetPath().pathString, str(p.GetTypeName()))
for p in stage.Traverse()
if "PhysicsArticulationRootAPI" in p.GetAppliedSchemas()
]
print()
print(f" mimic properties remaining : {len(left)} (want 0)")
print(f" mimic API still applied : {len(left_api)} (want 0)")
print(f" finger joints : {len(fingers)} (want 24)")
print(f" articulation root : {roots}")
print(f" root_joint present : {bool(stage.GetPrimAtPath(_PRIM + '/root_joint'))} (want False)")
ok = (
not left
and not left_api
and len(fingers) == 24
and len(roots) == 1
and roots[0][1] == "Xform"
)
print(f"\n{'OK' if ok else 'NOT OK'}: {_DEST / _WRAPPER}")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())