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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
"""Shared helpers to rebuild robot USDs whose joints and links match a URDF."""

import math
import xml.etree.ElementTree as ET

import numpy as np
from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics, Vt

# ---------------------------------------------------------------- URDF


def _origin(el):
    xyz = [float(v) for v in (el.get("xyz", "0 0 0") if el is not None else "0 0 0").split()]
    rpy = [float(v) for v in (el.get("rpy", "0 0 0") if el is not None else "0 0 0").split()]
    cr, sr = math.cos(rpy[0]), math.sin(rpy[0])
    cp, sp = math.cos(rpy[1]), math.sin(rpy[1])
    cy, sy = math.cos(rpy[2]), math.sin(rpy[2])
    T = np.eye(4)
    T[:3, :3] = [
        [cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
        [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
        [-sp, cp * sr, cp * cr],
    ]
    T[:3, 3] = xyz
    return T


def _rot(axis, angle):
    axis = np.asarray(axis, float)
    axis = axis / np.linalg.norm(axis)
    x, y, z = axis
    c, s, C = math.cos(angle), math.sin(angle), 1 - math.cos(angle)
    T = np.eye(4)
    T[:3, :3] = [
        [c + x * x * C, x * y * C - z * s, x * z * C + y * s],
        [y * x * C + z * s, c + y * y * C, y * z * C - x * s],
        [z * x * C - y * s, z * y * C + x * s, c + z * z * C],
    ]
    return T


def _trans(v):
    T = np.eye(4)
    T[:3, 3] = v
    return T


def urdf_joints(path):
    root = ET.parse(path).getroot()
    joints = []
    for j in root.findall("joint"):
        axis = j.find("axis")
        lim = j.find("limit")
        mimic = j.find("mimic")
        joints.append(
            {
                "name": j.get("name"),
                "type": j.get("type"),
                "parent": j.find("parent").get("link"),
                "child": j.find("child").get("link"),
                "origin": _origin(j.find("origin")),
                "axis": [float(v) for v in axis.get("xyz").split()] if axis is not None else [1, 0, 0],
                "limit": (float(lim.get("lower", 0)), float(lim.get("upper", 0))) if lim is not None else None,
                "mimic": (mimic.get("joint"), float(mimic.get("multiplier", 1)), float(mimic.get("offset", 0)))
                if mimic is not None
                else None,
            }
        )
    links = [l.get("name") for l in root.findall("link")]
    return links, joints


def urdf_fk(path, q):
    """World pose of every link for joint values `q` (radians / meters)."""
    links, joints = urdf_joints(path)
    by_child = {j["child"]: j for j in joints}
    out = {}

    def value(j):
        if j["mimic"]:
            name, mult, off = j["mimic"]
            return q.get(name, 0.0) * mult + off
        return q.get(j["name"], 0.0)

    def world(link):
        if link in out:
            return out[link]
        j = by_child.get(link)
        if j is None:
            out[link] = np.eye(4)
            return out[link]
        T = world(j["parent"]) @ j["origin"]
        if j["type"] in ("revolute", "continuous"):
            T = T @ _rot(j["axis"], value(j))
        elif j["type"] == "prismatic":
            T = T @ _trans(np.asarray(j["axis"], float) * value(j))
        out[link] = T
        return T

    for l in links:
        world(l)
    return out


# ---------------------------------------------------------------- USD kinematics


def np_matrix(m):
    """Gf (row vectors) to numpy (column vectors)."""
    return np.array(m, dtype=float).T


def _quat(q):
    im = q.GetImaginary()
    return Gf.Quatd(q.GetReal(), Gf.Vec3d(im[0], im[1], im[2]))


def _frame(pos, rot):
    T = np.eye(4)
    T[:3, :3] = np.array(Gf.Matrix3d(Gf.Rotation(_quat(rot))), dtype=float).T
    T[:3, 3] = [pos[0], pos[1], pos[2]]
    return T


AXES = {"X": [1, 0, 0], "Y": [0, 1, 0], "Z": [0, 0, 1]}


def usd_model(stage):
    cache = UsdGeom.XformCache()
    bodies, joints = {}, []
    for p in stage.Traverse():
        if p.HasAPI(UsdPhysics.RigidBodyAPI):
            bodies[str(p.GetPath())] = np_matrix(cache.GetLocalToWorldTransform(p))
    for p in stage.Traverse():
        if not p.IsA(UsdPhysics.Joint):
            continue
        j = UsdPhysics.Joint(p)
        b0 = j.GetBody0Rel().GetTargets()
        b1 = j.GetBody1Rel().GetTargets()
        kind = "fixed"
        axis, limit = None, None
        if p.IsA(UsdPhysics.RevoluteJoint):
            kind, s = "revolute", UsdPhysics.RevoluteJoint(p)
        elif p.IsA(UsdPhysics.PrismaticJoint):
            kind, s = "prismatic", UsdPhysics.PrismaticJoint(p)
        if kind != "fixed":
            axis = s.GetAxisAttr().Get()
            limit = (s.GetLowerLimitAttr().Get(), s.GetUpperLimitAttr().Get())
        joints.append(
            {
                "name": p.GetName(),
                "path": str(p.GetPath()),
                "type": kind,
                "body0": str(b0[0]) if b0 else None,
                "body1": str(b1[0]) if b1 else None,
                "J0": _frame(j.GetLocalPos0Attr().Get(), j.GetLocalRot0Attr().Get()),
                "J1": _frame(j.GetLocalPos1Attr().Get(), j.GetLocalRot1Attr().Get()),
                "axis": axis,
                "limit": limit,
            }
        )
    return bodies, joints


def usd_fk(model, q):
    """World pose of every body for joint values `q` (degrees / meters), keyed by body path."""
    bodies, joints = model
    # A joint to a prim that isn't a body (or to nothing) anchors its body at rest.
    by_body1 = {j["body1"]: j for j in joints if j["body0"] in bodies and j["body1"]}
    out = {}

    def world(b):
        if b in out:
            return out[b]
        j = by_body1.get(b)
        if j is None:
            out[b] = bodies[b]
            return out[b]
        M = np.eye(4)
        v = q.get(j["name"], 0.0)
        if j["type"] == "revolute":
            M = _rot(AXES[j["axis"]], math.radians(v))
        elif j["type"] == "prismatic":
            M = _trans(np.asarray(AXES[j["axis"]], float) * v)
        out[b] = world(j["body0"]) @ j["J0"] @ M @ np.linalg.inv(j["J1"])
        return out[b]

    for b in bodies:
        world(b)
    return out


def check_against_urdf(stage, urdf, samples=200, seed=0):
    """Pose USD and URDF with the same random joint values and compare every link.

    USD bodies are matched to URDF links by name. Each link may differ from the URDF by a constant
    offset at rest (a different frame convention); after that, motion must agree exactly.
    """
    model = usd_model(stage)
    bodies, joints = model
    links, ujoints = urdf_joints(urdf)
    name_of = {p.rsplit("/", 1)[1]: p for p in bodies}
    # Frames that aren't bodies (tips) ride on their nearest ancestor body.
    cache = UsdGeom.XformCache()
    riders = {}
    for p in stage.Traverse():
        if p.GetName() in links and p.GetName() not in name_of and p.IsA(UsdGeom.Xformable):
            anc = p.GetParent()
            while anc and str(anc.GetPath()) not in bodies:
                anc = anc.GetParent()
            if anc:
                b = str(anc.GetPath())
                riders[p.GetName()] = (b, np.linalg.inv(bodies[b]) @ np_matrix(cache.GetLocalToWorldTransform(p)))
    def fk_all(model, q):
        out = usd_fk(model, q)
        for name, (b, rel) in riders.items():
            out["rider:" + name] = out[b] @ rel
        return out

    name_of.update({n: "rider:" + n for n in riders})
    bodies = {**bodies, **{"rider:" + n: bodies[b] @ rel for n, (b, rel) in riders.items()}}
    shared = [l for l in links if l in name_of]
    movable = [j for j in ujoints if j["type"] in ("revolute", "prismatic", "continuous") and not j["mimic"]]
    mimics = [j for j in ujoints if j["mimic"]]
    rest_u = urdf_fk(urdf, {})
    rest_s = fk_all(model, {})
    ref = shared[0]
    A = rest_s[name_of[ref]] @ np.linalg.inv(rest_u[ref])
    D = {l: np.linalg.inv(A @ rest_u[l]) @ rest_s[name_of[l]] for l in shared}
    rest_err = max(np.abs(rest_s[p] - bodies[p]).max() for p in bodies)
    rng = np.random.default_rng(seed)
    worst_pos, worst_rot = 0.0, 0.0
    for _ in range(samples):
        qu = {}
        for j in movable:
            lo, hi = j["limit"] if j["limit"] else (-math.pi, math.pi)
            qu[j["name"]] = rng.uniform(lo, hi)
        for j in mimics:
            name, mult, off = j["mimic"]
            qu[j["name"]] = qu[name] * mult + off
        qs = {k: (math.degrees(v) if any(j["name"] == k and j["type"] != "prismatic" for j in ujoints) else v) for k, v in qu.items()}
        fu = urdf_fk(urdf, qu)
        fs = fk_all(model, qs)
        for l in shared:
            expected = A @ fu[l] @ D[l]
            got = fs[name_of[l]]
            worst_pos = max(worst_pos, np.linalg.norm(expected[:3, 3] - got[:3, 3]))
            R = expected[:3, :3].T @ got[:3, :3]
            worst_rot = max(worst_rot, math.degrees(math.acos(max(-1, min(1, (np.trace(R) - 1) / 2)))))
    frame_offsets = {
        l: (round(float(np.linalg.norm(D[l][:3, 3])) * 1000, 2), round(math.degrees(math.acos(max(-1, min(1, (np.trace(D[l][:3, :3]) - 1) / 2)))), 2))
        for l in shared
    }
    return {
        "links_missing": [l for l in links if l not in name_of],
        "joints_missing": [j["name"] for j in ujoints if j["type"] != "fixed" and j["name"] not in {k["name"] for k in joints}],
        "rest_consistency_m": float(rest_err),
        "worst_pos_mm": worst_pos * 1000,
        "worst_rot_deg": worst_rot,
        "frame_offsets_mm_deg": frame_offsets,
    }


# ---------------------------------------------------------------- composition and namespace edits


def flatten(path, variants=None):
    """One layer holding the composed stage, every instance turned into its own prims."""
    stage = Usd.Stage.Open(path)
    stage.SetEditTarget(stage.GetSessionLayer())
    for name, selection in (variants or {}).items():
        stage.GetDefaultPrim().GetVariantSet(name).SetVariantSelection(selection)
    while True:
        instances = [p for p in stage.Traverse() if p.IsInstance()]
        if not instances:
            break
        for p in instances:
            p.SetInstanceable(False)
    return stage.Flatten(addSourceFileComment=False)


def _remap_list(listop, fn):
    for field in ("explicitItems", "prependedItems", "appendedItems", "addedItems", "deletedItems", "orderedItems"):
        items = list(getattr(listop, field))
        mapped = [fn(i) for i in items]
        mapped = [m for m in mapped if m is not None]
        if mapped != items:
            setattr(listop, field, mapped)


def remap_targets(layer, fn):
    """Applies `fn(path) -> path | None` to every relationship target and attribute connection."""

    def visit(path):
        if not path.IsPropertyPath():
            return
        spec = layer.GetObjectAtPath(path)
        if isinstance(spec, Sdf.RelationshipSpec):
            _remap_list(spec.targetPathList, fn)
        elif isinstance(spec, Sdf.AttributeSpec):
            _remap_list(spec.connectionPathList, fn)

    layer.Traverse(Sdf.Path.absoluteRootPath, visit)


def rename(layer, path, new_name):
    old = Sdf.Path(path)
    new = old.ReplaceName(new_name)
    edit = Sdf.BatchNamespaceEdit()
    edit.Add(Sdf.NamespaceEdit.Rename(old, new_name))
    if not layer.Apply(edit):
        raise RuntimeError(f"rename {old} -> {new_name}")
    remap_targets(layer, lambda p: p.ReplacePrefix(old, new) if p.HasPrefix(old) else p)
    return str(new)


def remove(layer, path):
    path = Sdf.Path(path)
    edit = Sdf.BatchNamespaceEdit()
    edit.Add(Sdf.NamespaceEdit.Remove(path))
    if not layer.Apply(edit):
        raise RuntimeError(f"remove {path}")
    remap_targets(layer, lambda p: None if p.HasPrefix(path) else p)


def add_frame(stage, parent_path, name, world):
    """An Xform under `parent_path` placed at `world` (numpy, column vectors)."""
    parent = stage.GetPrimAtPath(parent_path)
    parent_world = np_matrix(UsdGeom.XformCache().GetLocalToWorldTransform(parent))
    local = np.linalg.inv(parent_world) @ world
    x = UsdGeom.Xform.Define(stage, f"{parent_path}/{name}")
    x.AddTransformOp().Set(Gf.Matrix4d(local.T.tolist()))
    return x


# ---------------------------------------------------------------- geometry


def crease_normals(points, faces, crease_deg=30.0):
    """Splits vertices along edges sharper than `crease_deg` and returns per-vertex normals."""
    a, b, c = (points[faces[:, k]] for k in range(3))
    fn = np.cross(b - a, c - a)
    area = np.linalg.norm(fn, axis=1)
    keep = area > 1e-20
    faces, fn, area = faces[keep], fn[keep], area[keep]
    unit = fn / area[:, None]
    m = len(faces)
    corner_vertex = faces.reshape(-1)
    corner_face = np.repeat(np.arange(m), 3)
    order = np.argsort(corner_vertex, kind="stable")
    sorted_v = corner_vertex[order]
    starts = np.flatnonzero(np.r_[True, sorted_v[1:] != sorted_v[:-1]])
    ends = np.r_[starts[1:], len(sorted_v)]
    cos_t = math.cos(math.radians(crease_deg))
    corner_normal = np.zeros((3 * m, 3))
    for s, e in zip(starts, ends):
        corners = order[s:e]
        fs = corner_face[corners]
        u = unit[fs]
        similar = (u @ u.T) > cos_t
        corner_normal[corners] = similar.astype(float) @ fn[fs]
    corner_normal /= np.maximum(np.linalg.norm(corner_normal, axis=1, keepdims=True), 1e-30)
    q = np.round(corner_normal * 1024).astype(np.int32)
    key = np.concatenate([corner_vertex[:, None], q], axis=1)
    unique, first, inverse = np.unique(key, axis=0, return_index=True, return_inverse=True)
    new_points = points[unique[:, 0]]
    new_normals = corner_normal[first]
    new_faces = inverse.reshape(-1).reshape(m, 3)
    return new_points, new_faces, new_normals


def weld(points, faces):
    unique, inverse = np.unique(points, axis=0, return_inverse=True)
    return unique, inverse.reshape(-1)[faces]


def author_mesh(stage, path, points, faces, normals, material=None):
    mesh = UsdGeom.Mesh.Define(stage, path)
    mesh.CreatePointsAttr(Vt.Vec3fArray.FromNumpy(points.astype(np.float32)))
    mesh.CreateFaceVertexCountsAttr(Vt.IntArray.FromNumpy(np.full(len(faces), 3, dtype=np.int32)))
    mesh.CreateFaceVertexIndicesAttr(Vt.IntArray.FromNumpy(faces.reshape(-1).astype(np.int32)))
    mesh.CreateNormalsAttr(Vt.Vec3fArray.FromNumpy(normals.astype(np.float32)))
    mesh.SetNormalsInterpolation(UsdGeom.Tokens.vertex)
    mesh.CreateSubdivisionSchemeAttr(UsdGeom.Tokens.none)
    mesh.CreateExtentAttr(Vt.Vec3fArray([Gf.Vec3f(*points.min(0)), Gf.Vec3f(*points.max(0))]))
    if material is not None:
        from pxr import UsdShade

        UsdShade.MaterialBindingAPI.Apply(mesh.GetPrim()).Bind(UsdShade.Material(stage.GetPrimAtPath(material)))
    return mesh


def compare_visual_bounds(source, out, renames=None):
    """Worst corner offset (mm) between each body's drawn geometry in `source` and in `out`."""
    renames = renames or {}

    def bounds(stage):
        cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ["default"], useExtentsHint=False)
        found = {}
        for p in stage.Traverse(Usd.TraverseInstanceProxies()):
            if p.HasAPI(UsdPhysics.RigidBodyAPI):
                # Only this body's own meshes, not those of bodies nested under it.
                lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
                it = iter(Usd.PrimRange(p, Usd.TraverseInstanceProxies()))
                for q in it:
                    if q != p and q.HasAPI(UsdPhysics.RigidBodyAPI):
                        it.PruneChildren()
                        continue
                    if q.IsA(UsdGeom.Mesh) and UsdGeom.Imageable(q).ComputePurpose() == "default":
                        r = cache.ComputeWorldBound(q).ComputeAlignedRange()
                        lo, hi = np.minimum(lo, r.GetMin()), np.maximum(hi, r.GetMax())
                if np.isfinite(lo).all():
                    found[renames.get(p.GetName(), p.GetName())] = (lo, hi)
        return found

    a, b = bounds(source), bounds(out)
    return {k: round(float(max(np.abs(a[k][0] - b[k][0]).max(), np.abs(a[k][1] - b[k][1]).max())) * 1000, 2) if k in b else "missing" for k in a}