File size: 24,484 Bytes
55c03f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
755a212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55c03f9
 
 
 
 
755a212
 
 
 
55c03f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329113a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a23e4
 
 
 
 
 
 
 
 
 
 
329113a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
"""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())
        # A joint may target a prim under its rigid body (a mesh): the body is the nearest ancestor
        # with RigidBodyAPI, and the joint frame is relative to the targeted prim.
        def owner(targets, local_frame):
            if not targets:
                return None, local_frame
            prim = stage.GetPrimAtPath(targets[0])
            body = prim
            while body and body.IsValid() and str(body.GetPath()) not in bodies:
                body = body.GetParent()
            if not body or not body.IsValid() or body.IsPseudoRoot():
                return str(targets[0]), local_frame
            offset = np.linalg.inv(bodies[str(body.GetPath())]) @ np_matrix(cache.GetLocalToWorldTransform(prim))
            return str(body.GetPath()), offset @ local_frame

        body0, J0 = owner(b0, _frame(j.GetLocalPos0Attr().Get(), j.GetLocalRot0Attr().Get()))
        body1, J1 = owner(b1, _frame(j.GetLocalPos1Attr().Get(), j.GetLocalRot1Attr().Get()))
        joints.append(
            {
                "name": p.GetName(),
                "path": str(p.GetPath()),
                "type": kind,
                "body0": body0,
                "body1": body1,
                "J0": J0,
                "J1": J1,
                "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}


# ---------------------------------------------------------------- URDF to USD


def read_stl(path):
    """Points and triangles of a binary STL."""
    data = open(path, "rb").read()
    n = int(np.frombuffer(data, np.uint32, 1, 80)[0])
    tris = np.frombuffer(data, np.dtype([("n", "<f4", 3), ("v", "<f4", (3, 3)), ("a", "<u2")]), n, 84)
    return tris["v"].reshape(-1, 3).astype(float), np.arange(3 * n).reshape(n, 3)


def srgb_to_linear(c):
    c = np.asarray(c, float)
    return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)


def _axis_frame(axis):
    """The USD axis token for a URDF axis along X, Y or Z, and the rotation turning that token into it."""
    a = np.asarray(axis, float)
    i = int(np.argmax(np.abs(a)))
    if not np.allclose(np.abs(a), np.eye(3)[i]):
        raise ValueError(f"axis {axis} is not along X, Y or Z")
    R = np.eye(4) if a[i] > 0 else _rot(np.eye(3)[(i + 1) % 3], math.pi)
    return "XYZ"[i], R


def _set_matrix(xformable, M):
    xformable.ClearXformOpOrder()
    xformable.AddTransformOp().Set(Gf.Matrix4d(M.T.tolist()))


def _pose(M):
    q = Gf.Matrix4d(M.T.tolist()).ExtractRotationQuat()
    im = q.GetImaginary()
    return Gf.Vec3f(*M[:3, 3]), Gf.Quatf(q.GetReal(), Gf.Vec3f(im[0], im[1], im[2]))


def from_urdf(urdf, name, colors=None):
    """A stage drawing the URDF's visual meshes, with a rigid body per link a moving joint drives.

    Links fixed to another are frames under its body, so every link keeps the URDF's name and frame;
    joints are UsdPhysics joints (limits in degrees), the root link at the origin. `colors` maps a
    link to an sRGB color replacing its URDF material.
    """
    from pxr import UsdShade

    root_el = ET.parse(urdf).getroot()
    mesh_dir = urdf.rsplit("/", 1)[0] if "/" in urdf else "."
    links, joints = urdf_joints(urdf)
    by_child = {j["child"]: j for j in joints}
    rest = urdf_fk(urdf, {})
    named_colors = {m.get("name"): [float(v) for v in m.find("color").get("rgba").split()[:3]] for m in root_el.findall("material") if m.find("color") is not None}

    stage = Usd.Stage.CreateInMemory()
    UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
    UsdGeom.SetStageMetersPerUnit(stage, 1.0)
    UsdPhysics.SetStageKilogramsPerUnit(stage, 1.0)
    robot = UsdGeom.Xform.Define(stage, f"/{name}")
    stage.SetDefaultPrim(robot.GetPrim())
    Usd.ModelAPI(robot.GetPrim()).SetKind("component")
    UsdGeom.Scope.Define(stage, f"/{name}/Materials")
    UsdGeom.Scope.Define(stage, f"/{name}/Geometry")
    UsdGeom.Scope.Define(stage, f"/{name}/Joints")

    materials = {}

    def material(rgb):
        key = tuple(round(c, 5) for c in rgb)
        if key not in materials:
            path = f"/{name}/Materials/material_{len(materials)}"
            mat = UsdShade.Material.Define(stage, path)
            shader = UsdShade.Shader.Define(stage, f"{path}/PreviewSurface")
            shader.CreateIdAttr("UsdPreviewSurface")
            shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*srgb_to_linear(rgb)))
            shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
            shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.5)
            mat.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
            materials[key] = path
        return materials[key]

    # A link is a body unless a fixed joint holds it to its parent.
    def body_of(link):
        j = by_child.get(link)
        return link if j is None or j["type"] != "fixed" else body_of(j["parent"])

    paths = {}
    for link in links:
        body = body_of(link)
        if body == link:
            paths[link] = f"/{name}/Geometry/{link}"
            x = UsdGeom.Xform.Define(stage, paths[link])
            _set_matrix(x, rest[link])
            UsdPhysics.RigidBodyAPI.Apply(x.GetPrim())
            if by_child.get(link) is None:
                UsdPhysics.ArticulationRootAPI.Apply(x.GetPrim())
    for link in links:
        body = body_of(link)
        if body != link:
            paths[link] = f"{paths[body]}/{link}"
            _set_matrix(UsdGeom.Xform.Define(stage, paths[link]), np.linalg.inv(rest[body]) @ rest[link])

    for el in root_el.findall("link"):
        link = el.get("name")
        inertial = el.find("inertial")
        if inertial is not None and body_of(link) == link:
            mass = UsdPhysics.MassAPI.Apply(stage.GetPrimAtPath(paths[link]))
            mass.CreateMassAttr(float(inertial.find("mass").get("value")))
            mass.CreateCenterOfMassAttr(Gf.Vec3f(*_origin(inertial.find("origin"))[:3, 3]))
        for k, visual in enumerate(el.findall("visual")):
            mesh_el = visual.find("geometry/mesh")
            if mesh_el is None:
                raise ValueError(f"{link}: only mesh visuals are supported")
            points, faces = read_stl(f"{mesh_dir}/{mesh_el.get('filename')}")
            scale = [float(v) for v in mesh_el.get("scale", "1 1 1").split()]
            T = _origin(visual.find("origin"))
            points = (T[:3, :3] @ (points * scale).T).T + T[:3, 3]
            points, faces = weld(points, faces)
            points, faces, normals = crease_normals(points, faces)
            mat_el = visual.find("material")
            rgb = (colors or {}).get(link)
            if rgb is None and mat_el is not None:
                color_el = mat_el.find("color")
                rgb = [float(v) for v in color_el.get("rgba").split()[:3]] if color_el is not None else named_colors[mat_el.get("name")]
            author_mesh(stage, f"{paths[link]}/visual" + (f"_{k}" if k else ""), points, faces, normals, material(rgb) if rgb else None)

    for j in joints:
        if j["type"] == "fixed":
            continue
        kind = {"revolute": UsdPhysics.RevoluteJoint, "continuous": UsdPhysics.RevoluteJoint, "prismatic": UsdPhysics.PrismaticJoint}[j["type"]]
        joint = kind.Define(stage, f"/{name}/Joints/{j['name']}")
        token, R = _axis_frame(j["axis"])
        parent = body_of(j["parent"])
        frame = rest[j["child"]] @ R
        pos0, rot0 = _pose(np.linalg.inv(rest[parent]) @ frame)
        pos1, rot1 = _pose(R)
        joint.CreateBody0Rel().SetTargets([paths[parent]])
        joint.CreateBody1Rel().SetTargets([paths[j["child"]]])
        joint.CreateLocalPos0Attr(pos0)
        joint.CreateLocalRot0Attr(rot0)
        joint.CreateLocalPos1Attr(pos1)
        joint.CreateLocalRot1Attr(rot1)
        joint.CreateAxisAttr(token)
        if j["type"] != "continuous" and j["limit"]:
            lo, hi = j["limit"]
            if j["type"] == "revolute":
                lo, hi = math.degrees(lo), math.degrees(hi)
            joint.CreateLowerLimitAttr(lo)
            joint.CreateUpperLimitAttr(hi)
        if j["mimic"]:
            # PhysX's mimic constraint, position + gearing * reference + offset = 0, so a `<mimic>` joint
            # still follows its joint without the URDF.
            reference, multiplier, offset = j["mimic"]
            if offset:
                raise NotImplementedError(f"{j['name']}: a mimic offset needs its units settled first")
            dof = ("trans" if j["type"] == "prismatic" else "rot") + token
            prim = joint.GetPrim()
            prim.AddAppliedSchema(f"PhysxMimicJointAPI:{dof}")
            prim.CreateRelationship(f"physxMimicJoint:{dof}:referenceJoint").SetTargets([f"/{name}/Joints/{reference}"])
            prim.CreateAttribute(f"physxMimicJoint:{dof}:gearing", Sdf.ValueTypeNames.Float).Set(-multiplier)
    return stage