"""Flatten the Isaac URDF importer's layered output into one robot/robot.usd and dump its physics properties. Research and simulation project only. Do not install this device in a real vehicle or attempt to drive a vehicle with it. It has not been built or tested on any vehicle. Simulation-tested ยท Not built. Runs inside Isaac Lab's Python (queue: gpu), called by `uv run tasks.py usd`: isaaclab.bat -p usd_flatten_dump.py Adapted from the Raptor for Zmass project's tool of the same name. Additions for this kit: * prismatic joints (brake_slider_joint; limits in stage units, metres here) next to revolute joints (degrees); * fixed joints, the articulation root and the fixed root joint (the kit's base seat_frame is fixed); * the URDF couplings, which importer 3.0 writes as NewtonMimicAPI (newton:mimicJoint, newton:mimicCoef0/1); * each joint's axis expressed in body0, the rest-pose transform of body1 in body0 (to compare with the URDF joint origin), drive / friction / velocity-limit / effort attributes, the full inertia tensor rebuilt from the principal moments and principal axes, and the collision prims per body. The composed Physics variant at flatten time is recorded (the importer's default, "physics"). robot.usd holds ASCII (usda) content, with Flatten()'s instancing prototypes renamed in a canonical order (canonical_usda), so the file is byte-reproducible run to run and reviewable; USD reads either encoding from .usd. """ import json import math import re import sys sys.dont_write_bytecode = True # no .pyc next to the package files from pxr import Usd, UsdGeom, UsdPhysics # noqa: E402 def qmat(w, x, y, z): """Rotation matrix (column-vector convention) of a unit quaternion (w, x, y, z).""" n = math.sqrt(w * w + x * x + y * y + z * z) or 1.0 w, x, y, z = w / n, x / n, y / n, z / n return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]] def mv(R, v): return [sum(R[i][k] * v[k] for k in range(3)) for i in range(3)] def wxyz(q): return [float(q.GetReal()), *[float(c) for c in q.GetImaginary()]] def val(v): """JSON-friendly value of a USD attribute.""" if v is None: return None if isinstance(v, (bool, int, float, str)): return v if hasattr(v, "GetReal"): return wxyz(v) try: return [float(c) for c in v] except TypeError: return str(v) PROTO = re.compile(r"Flattened_Prototype_(\d+)\b") PROTO_NAME = re.compile(r"Flattened_Prototype_(\d+)") ROOT_PRIM = re.compile(r'^(def|over|class)\b[^"]*"([^"]+)"') NL = "\n" def canonical_usda(text: str) -> str: """Rename USD's Flattened_Prototype_ root prims by first use and sort them. Flatten() names the prototypes of instanceable prims in the order USD discovers them, which changes from run to run. Walking the non-prototype root prims (the robot) in file order and then each newly found prototype gives the same numbering every time; prototypes nothing refers to keep their relative order at the end. Only names change. """ lines = text.split(NL) starts = [i for i, ln in enumerate(lines) if ROOT_PRIM.match(ln)] if not starts: return text head, blocks = lines[:starts[0]], [] for k, i in enumerate(starts): j = starts[k + 1] if k + 1 < len(starts) else len(lines) blocks.append((ROOT_PRIM.match(lines[i]).group(2), lines[i:j])) protos = {int(m.group(1)): b for name, b in blocks if (m := PROTO_NAME.fullmatch(name))} others = [b for name, b in blocks if not PROTO_NAME.fullmatch(name)] order, queue = [], [NL.join(b) for b in others] while queue: for m in PROTO.finditer(queue.pop(0)): n = int(m.group(1)) if n in protos and n not in order: order.append(n) queue.append(NL.join(protos[n])) order += [n for n in sorted(protos) if n not in order] new = {old: k + 1 for k, old in enumerate(order)} body = [ln for n in order for ln in protos[n]] + [ln for b in others for ln in b] return PROTO.sub(lambda m: f"Flattened_Prototype_{new.get(int(m.group(1)), int(m.group(1)))}", NL.join(head + body)) def main() -> int: src, out_usd, out_json = sys.argv[1:4] stage = Usd.Stage.Open(src) dp = stage.GetDefaultPrim() vset = dp.GetVariantSets().GetVariantSet("Physics") if dp.GetVariantSets().HasVariantSet("Physics") else None variant = {"set": "Physics", "selection": vset.GetVariantSelection(), "choices": vset.GetVariantNames()} if vset else None # ASCII content in robot.usd (USD detects the format from the content), with the instancing prototypes renamed in # a canonical order (canonical_usda) so the file is byte-reproducible and diffs in review. flat = stage.Flatten() flat.documentation = ("Flattened from the Isaac Lab URDF converter output (robot/robot.urdf -> runs/usd_import) by " "simulation/isaac/tools/usd_flatten_dump.py. Simulation-tested - Not built.") with open(out_usd, "w", encoding="utf-8", newline=NL) as fh: fh.write(canonical_usda(flat.ExportToString())) st = Usd.Stage.Open(out_usd) xc = UsdGeom.XformCache(Usd.TimeCode.Default()) prims = list(Usd.PrimRange.Stage(st, Usd.TraverseInstanceProxies())) dump = {"generated_by": "simulation/isaac/tools/usd_flatten_dump.py (uv run tasks.py usd)", "source_layer": "runs/usd_import/robot/robot.usda (Isaac Lab UrdfConverter, layered)", "creator": st.GetRootLayer().customLayerData.get("creator"), "default_prim": st.GetDefaultPrim().GetName(), "physics_variant_at_flatten": variant, "meters_per_unit": UsdGeom.GetStageMetersPerUnit(st), "kilograms_per_unit": UsdPhysics.GetStageKilogramsPerUnit(st), "up_axis": str(UsdGeom.GetStageUpAxis(st)), "units": {"revolute_limits": "deg", "prismatic_limits": "stage units (m)", "revolute_velocity_limit": "deg/s", "inertia_frame": "principal axes"}, "articulation_roots": [], "links": {}, "joints": {}, "mimic": [], "counts": {}} body_world = {} for prim in prims: if prim.HasAPI(UsdPhysics.ArticulationRootAPI): dump["articulation_roots"].append(str(prim.GetPath())) if not prim.HasAPI(UsdPhysics.RigidBodyAPI): continue m = UsdPhysics.MassAPI(prim) com, di, pa = m.GetCenterOfMassAttr().Get(), m.GetDiagonalInertiaAttr().Get(), m.GetPrincipalAxesAttr().Get() rec = {"path": str(prim.GetPath()), "mass": m.GetMassAttr().Get(), "com": val(com), "diag_inertia": val(di), "principal_axes_wxyz": wxyz(pa) if pa is not None else None} if di is not None and pa is not None: R = qmat(*wxyz(pa)) d = [float(c) for c in di] rec["inertia_tensor"] = [[sum(R[i][k] * d[k] * R[j][k] for k in range(3)) for j in range(3)] for i in range(3)] T = xc.GetLocalToWorldTransform(prim) body_world[str(prim.GetPath())] = T rec["world_pos"] = [float(c) for c in T.ExtractTranslation()] rec["world_quat_wxyz"] = wxyz(T.ExtractRotationQuat()) cols = [p for p in Usd.PrimRange(prim, Usd.TraverseInstanceProxies()) if p.HasAPI(UsdPhysics.CollisionAPI) and p != prim and not (p.HasAPI(UsdPhysics.RigidBodyAPI))] # collision prims that belong to this body (not to a nested child body) own = [p for p in cols if next((a for a in _ancestors(p) if a.HasAPI(UsdPhysics.RigidBodyAPI)), None) == prim] rec["collision_prims"] = len(own) rec["collision_types"] = sorted({p.GetTypeName() for p in own}) dump["links"][prim.GetName()] = rec for prim in prims: if not prim.IsA(UsdPhysics.Joint): continue j = UsdPhysics.Joint(prim) b0 = [str(t) for t in j.GetBody0Rel().GetTargets()] b1 = [str(t) for t in j.GetBody1Rel().GetTargets()] r0, r1 = j.GetLocalRot0Attr().Get(), j.GetLocalRot1Attr().Get() p0, p1 = j.GetLocalPos0Attr().Get(), j.GetLocalPos1Attr().Get() rec = {"path": str(prim.GetPath()), "type": prim.GetTypeName(), "body0": b0, "body1": b1, "body0_name": b0[0].rsplit("/", 1)[-1] if b0 else None, "body1_name": b1[0].rsplit("/", 1)[-1] if b1 else None, "local_pos0": val(p0), "local_pos1": val(p1), "local_rot0_wxyz": val(r0), "local_rot1_wxyz": val(r1), "applied_schemas": list(prim.GetAppliedSchemas()), "attrs": {a.GetName(): val(a.Get()) for a in prim.GetAttributes() if a.HasAuthoredValue() and a.GetName().split(":")[0] in ("drive", "newton", "urdf", "physxJoint", "physxLimit", "mjc")}} if prim.IsA(UsdPhysics.RevoluteJoint) or prim.IsA(UsdPhysics.PrismaticJoint): jj = UsdPhysics.RevoluteJoint(prim) if prim.IsA(UsdPhysics.RevoluteJoint) else UsdPhysics.PrismaticJoint(prim) ax = str(jj.GetAxisAttr().Get()) rec.update(axis=ax, lower=jj.GetLowerLimitAttr().Get(), upper=jj.GetUpperLimitAttr().Get(), limit_units="deg" if prim.IsA(UsdPhysics.RevoluteJoint) else "m") e = {"X": [1.0, 0.0, 0.0], "Y": [0.0, 1.0, 0.0], "Z": [0.0, 0.0, 1.0]}[ax] rec["axis_in_body0"] = mv(qmat(*rec["local_rot0_wxyz"]), e) if prim.IsA(UsdPhysics.RevoluteJoint): rec["lower_deg"], rec["upper_deg"] = rec["lower"], rec["upper"] # rest-pose transform of body1 in body0 (row-vector Gf convention: T1_in_0 = T1 * inv(T0)) if b0 and b1 and b0[0] in body_world and b1[0] in body_world: T = body_world[b1[0]] * body_world[b0[0]].GetInverse() rec["body1_in_body0_pos"] = [float(c) for c in T.ExtractTranslation()] rec["body1_in_body0_quat_wxyz"] = wxyz(T.ExtractRotationQuat()) elif b1 and b1[0] in body_world: rec["body0_is_world"] = True if prim.HasAPI("NewtonMimicAPI") or any("mimic" in a.GetName().lower() for a in prim.GetAttributes()): tgt = prim.GetRelationship("newton:mimicJoint") mm = {"joint": prim.GetName(), "api": [s for s in prim.GetAppliedSchemas() if "imic" in s], "reference": [str(t) for t in tgt.GetTargets()] if tgt else [], "coef0_offset": val(prim.GetAttribute("newton:mimicCoef0").Get()) if prim.GetAttribute("newton:mimicCoef0") else None, "coef1_multiplier": val(prim.GetAttribute("newton:mimicCoef1").Get()) if prim.GetAttribute("newton:mimicCoef1") else None, "attrs": {a.GetName(): val(a.Get()) for a in prim.GetAttributes() if "mimic" in a.GetName().lower()}} mm["reference_name"] = mm["reference"][0].rsplit("/", 1)[-1] if mm["reference"] else None mm["physx_mimic_api"] = any(s.startswith("PhysxMimicJointAPI") for s in prim.GetAppliedSchemas()) rec["mimic"] = mm dump["mimic"].append(mm) dump["joints"][prim.GetName()] = rec types = {} for p in prims: types[p.GetTypeName() or "(typeless)"] = types.get(p.GetTypeName() or "(typeless)", 0) + 1 dump["counts"] = {"rigid_bodies": len(dump["links"]), "joints": len(dump["joints"]), "revolute": sum(1 for j in dump["joints"].values() if j["type"] == "PhysicsRevoluteJoint"), "prismatic": sum(1 for j in dump["joints"].values() if j["type"] == "PhysicsPrismaticJoint"), "fixed": sum(1 for j in dump["joints"].values() if j["type"] == "PhysicsFixedJoint"), "mimic": len(dump["mimic"]), "prim_types": dict(sorted(types.items()))} with open(out_json, "w", encoding="utf-8", newline="\n") as fh: json.dump(dump, fh, indent=1, sort_keys=False, default=str) fh.write("\n") c = dump["counts"] print(f"flattened -> {out_usd}; {c['rigid_bodies']} rigid bodies, {c['revolute']} revolute, {c['prismatic']} prismatic, " f"{c['fixed']} fixed joints, {c['mimic']} mimic couplings", flush=True) return 0 def _ancestors(p): q = p.GetParent() while q and q.IsValid() and not q.IsPseudoRoot(): yield q q = q.GetParent() if __name__ == "__main__": raise SystemExit(main())