File size: 14,340 Bytes
0aefd10
 
 
 
 
 
 
 
 
 
 
96ebbc7
 
 
f5c939d
 
 
 
0aefd10
 
 
 
 
 
f5c939d
96ebbc7
0aefd10
 
 
 
96ebbc7
0aefd10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3522659
0aefd10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96ebbc7
 
 
 
 
 
 
 
 
0aefd10
96ebbc7
0aefd10
 
 
 
 
 
 
96ebbc7
 
 
 
 
 
 
 
f5c939d
0aefd10
 
 
 
 
 
 
 
 
 
 
 
 
f5c939d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aefd10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96ebbc7
f5c939d
96ebbc7
 
 
 
 
f5c939d
 
 
 
 
96ebbc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aefd10
 
 
 
 
 
 
 
 
96ebbc7
0aefd10
 
 
 
 
 
 
 
 
3522659
0aefd10
 
 
 
96ebbc7
 
 
 
0aefd10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# requires-python = ">=3.10"
# dependencies = ["usd-core"]
# ///
"""Make the 3D previews the Space's viewer loads: previews/<asset>.glb + previews/<asset>.json.

For each package in projectsim/simready-assets (read-only; nothing is written to the
dataset) this downloads simready_usd/ (without thumbnails) to a temporary folder, converts
the USD to a small Draco GLB with Blender (tools/blender_glb.py), and writes the rig: one
entry per hinge or slider joint with its parent and child part, pivot, axis and range,
in the GLB's Y-up metres. Parts are matched to GLB nodes by USD prim name.
A joint that follows another one in Isaac (a PhysX mimic joint, as on scissor and
accordion linkages) gets "mimic": {ref, gearing, offset} in the viewer's units
(degrees, metres): its position is -(gearing * ref + offset), as PhysX defines it.
A joint that another one drives through the package's OmniGraph coupling (the sidecar
simready_usd/<asset>.json, physics.articulation.joint_couplings: a linear map from the
source joint's range to the target's, e.g. a pedal bin's pedal opening its lid) gets the
same "mimic" with "one_way": true: in Isaac the driven joint can still be moved on its own.

Previews are cached in tools/preview_cache.json by package id, so a rerun only converts
new or changed packages.

Run from the Space folder:  HF_TOKEN=$(hf auth token) uv run tools/make_previews.py [asset ...]
(the token only raises Hugging Face's download rate limit; nothing is uploaded)
--rig-only rewrites just the .json files from each package's root USD layer and sidecar (no Blender,
the GLBs stay as they are), for when only the joint data changes.
"""

import argparse
import json
import math
import os
import re
import struct
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor

from pxr import Gf, Usd, UsdGeom, UsdPhysics

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from build_catalog import HF, get_json, hidden_assets, list_files  # noqa: E402

BLENDER = "/Applications/Blender.app/Contents/MacOS/Blender"
AXES = {"X": Gf.Vec3d(1, 0, 0), "Y": Gf.Vec3d(0, 1, 0), "Z": Gf.Vec3d(0, 0, 1)}


def rig(usd_path):
    """Hinge and slider joints with pivot and axis in GLB space (Y-up metres)."""
    stage = Usd.Stage.Open(usd_path)
    mpu = UsdGeom.GetStageMetersPerUnit(stage) or 1.0
    zup = UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z
    to_gltf = (lambda v: [v[0], v[2], -v[1]]) if zup else (lambda v: [v[0], v[1], v[2]])
    cache = UsdGeom.XformCache()
    joints = []
    for prim in stage.Traverse(Usd.TraverseInstanceProxies()):
        if prim.IsA(UsdPhysics.RevoluteJoint):
            kind, typed = "hinge", UsdPhysics.RevoluteJoint(prim)
        elif prim.IsA(UsdPhysics.PrismaticJoint):
            kind, typed = "slider", UsdPhysics.PrismaticJoint(prim)
        else:
            continue
        j = UsdPhysics.Joint(prim)
        b0 = j.GetBody0Rel().GetTargets()
        b1 = j.GetBody1Rel().GetTargets()
        if not b1:
            continue
        world0 = cache.GetLocalToWorldTransform(stage.GetPrimAtPath(b0[0])) if b0 else Gf.Matrix4d(1)
        pos = Gf.Vec3d(j.GetLocalPos0Attr().Get() or Gf.Vec3f(0))
        rot = j.GetLocalRot0Attr().Get() or Gf.Quatf(1)
        axis_local = Gf.Rotation(Gf.Quatd(rot)).TransformDir(AXES.get(typed.GetAxisAttr().Get(), AXES["X"]))
        pivot = world0.Transform(pos) * mpu
        axis = world0.TransformDir(axis_local).GetNormalized()
        lo, hi = typed.GetLowerLimitAttr().Get(), typed.GetUpperLimitAttr().Get()
        limited = lo is not None and hi is not None and abs(hi - lo) < 1e6
        scale = 1.0 if kind == "hinge" else mpu
        mimic = None   # PhysxMimicJointAPI:<axis>: this joint follows another one
        for attr in prim.GetAttributes():
            m = re.fullmatch(r"physxMimicJoint:(\w+):gearing", attr.GetName())
            ref = prim.GetRelationship(f"physxMimicJoint:{m.group(1)}:referenceJoint") if m else None
            if ref and ref.GetTargets() and attr.Get() is not None:
                off = prim.GetAttribute(f"physxMimicJoint:{m.group(1)}:offset")
                mimic = {"ref": ref.GetTargets()[0].name, "gearing": float(attr.Get()),
                         "offset": float((off.Get() if off else 0) or 0)}
                break
        joints.append({
            "_mimic": mimic,
            "name": prim.GetName(), "type": kind,
            "parent": b0[0].name if b0 else None, "child": b1[0].name,
            "pivot": [round(x, 6) for x in to_gltf(pivot)],
            "axis": [round(x, 6) for x in to_gltf(axis)],
            "lower": round(lo * scale, 6) if limited else None,
            "upper": round(hi * scale, 6) if limited else None,
        })
    # mimic links in the viewer's units: PhysX positions are radians (hinge) or stage units (slider)
    kinds = {jt["name"]: jt["type"] for jt in joints}
    native = lambda kind: math.pi / 180 if kind == "hinge" else 1 / mpu   # viewer value -> PhysX position
    for jt in joints:
        m = jt.pop("_mimic")
        if m and m["ref"] in kinds and m["ref"] != jt["name"]:
            kr, kf = native(kinds[m["ref"]]), native(jt["type"])
            jt["mimic"] = {"ref": m["ref"], "gearing": round(m["gearing"] * kr / kf, 6), "offset": round(m["offset"] / kf, 6)}
    couple(stage, os.path.splitext(usd_path)[0] + ".json", joints)
    # parents before children, so the viewer can chain joints in one pass
    order, placed = [], set()
    while len(order) < len(joints):
        before = len(order)
        for jt in joints:
            if jt["name"] not in placed and (jt["parent"] is None or jt["parent"] not in {k["child"] for k in joints if k["name"] not in placed}):
                order.append(jt); placed.add(jt["name"])
        if len(order) == before:  # a loop: keep the rest as they are
            order += [jt for jt in joints if jt["name"] not in placed]
            break
    return order


def couple(stage, sidecar, joints):
    """One-way links from the sidecar's joint_couplings, in the viewer's units.

    Each coupling maps source_range linearly onto target_range (radians for hinges, metres
    for sliders). Couplings Isaac runs as PhysX mimic joints are already read from the USD.
    """
    if not os.path.exists(sidecar):
        return
    try:
        couplings = json.load(open(sidecar))["physics"]["articulation"].get("joint_couplings") or []
    except (ValueError, KeyError, TypeError):
        return
    by_name = {jt["name"]: jt for jt in joints}
    unit = lambda jt: 180 / math.pi if jt["type"] == "hinge" else 1.0   # PhysX position -> viewer value
    root = stage.GetDefaultPrim()
    for c in couplings:
        src, dst = by_name.get(c.get("source_joint")), by_name.get(c.get("target_joint"))
        if c.get("runtime") == "physx_mimic" or not src or not dst or src is dst or "mimic" in dst:
            continue
        enabled = root.GetAttribute(c["enabled_attribute"]) if root and c.get("enabled_attribute") else None
        if enabled and enabled.Get() is False:
            continue
        (s0, s1), (t0, t1) = ([x * unit(jt) for x in c[k]] for jt, k in ((src, "source_range"), (dst, "target_range")))
        if s1 == s0:
            continue
        k = (t1 - t0) / (s1 - s0)   # target = t0 + k * (source - s0) = -(gearing * source + offset)
        # significant figures, not decimals: a screw's metres per degree is ~1e-5
        dst["mimic"] = {"ref": src["name"], "gearing": float(f"{-k:.6g}"), "offset": float(f"{k * s0 - t0:.6g}") + 0.0,
                        "one_way": True}


def download(url, dest, tries=6):
    """GET with an optional HF_TOKEN (higher rate limits) and backoff on 429/5xx."""
    headers = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"} if os.environ.get("HF_TOKEN") else {}
    for attempt in range(tries):
        try:
            with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=300) as r, open(dest, "wb") as f:
                while chunk := r.read(1 << 20):
                    f.write(chunk)
            return
        except urllib.error.HTTPError as e:
            if e.code not in (429, 500, 502, 503, 504) or attempt == tries - 1:
                raise
            wait = int(e.headers.get("Retry-After") or 0) or 15 * (attempt + 1)
            time.sleep(min(wait, 300))


def glb_node_names(path):
    data = open(path, "rb").read()
    n = struct.unpack_from("<I", data, 12)[0]
    return {node.get("name") for node in json.loads(data[20:20 + n]).get("nodes", [])}


def make_one(dataset, sha, asset, paths, out_dir, blender, max_px):
    with tempfile.TemporaryDirectory() as tmp:
        for p in paths:
            if "/simready_usd/" not in p or "/.thumbs/" in p:
                continue
            dest = os.path.join(tmp, p)
            os.makedirs(os.path.dirname(dest), exist_ok=True)
            download(f"{HF}/datasets/{dataset}/resolve/{sha}/{urllib.parse.quote(p)}", dest)
        usd = os.path.join(tmp, asset, "simready_usd", f"{asset}.usd")
        glb = os.path.join(out_dir, f"{asset}.glb")
        run = subprocess.run([blender, "-b", "--factory-startup", "--python",
                              os.path.join(os.path.dirname(os.path.abspath(__file__)), "blender_glb.py"),
                              "--", usd, glb, str(max_px)], capture_output=True, text=True)
        if "PREVIEW_OK" not in run.stdout or not os.path.exists(glb):
            raise RuntimeError(f"Blender failed: {(run.stdout + run.stderr)[-600:]}")
        joints = rig(usd)
    names = glb_node_names(glb)
    missing = sorted({j["child"] for j in joints if j["child"] not in names})
    json.dump({"joints": joints}, open(os.path.join(out_dir, f"{asset}.json"), "w"), separators=(",", ":"))
    return {"bytes": os.path.getsize(glb), "joints": len(joints), "missing_parts": missing}


def rig_only(args, sha, assets):
    """Rewrite previews/<asset>.json from the root USD layer and sidecar alone; report linked joints."""
    def work(a):
        try:
            with tempfile.TemporaryDirectory() as tmp:
                usd = os.path.join(tmp, f"{a}.usd")
                download(f"{HF}/datasets/{args.dataset}/resolve/{sha}/{a}/simready_usd/{a}.usd", usd)
                try:   # the sidecar, for one-way couplings (older packages may not have one)
                    download(f"{HF}/datasets/{args.dataset}/resolve/{sha}/{a}/simready_usd/{a}.json", usd[:-4] + ".json")
                except urllib.error.HTTPError as e:
                    if e.code != 404:
                        raise
                joints = rig(usd)
            json.dump({"joints": joints}, open(os.path.join(args.out, f"{a}.json"), "w"), separators=(",", ":"))
            return a, sum("mimic" in j for j in joints), None
        except Exception as e:  # keep going; report at the end
            return a, None, str(e)

    print(f"{len(assets)} joint files to rewrite", file=sys.stderr)
    with ThreadPoolExecutor(args.workers) as pool:
        results = list(pool.map(work, assets))
    for a, n, err in results:
        if err:
            print(f"  FAILED {a}: {err[:300]}", file=sys.stderr)
        elif n:
            print(f"  {a}: {n} linked joint(s)", file=sys.stderr)
    print(f"done: {sum(1 for r in results if not r[2])} rewritten, {sum(1 for r in results if r[1])} with linked joints",
          file=sys.stderr)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("assets", nargs="*", help="only these assets (default: all that need a preview)")
    ap.add_argument("--dataset", default="projectsim/simready-assets")
    ap.add_argument("--out", default="previews")
    ap.add_argument("--cache", default="tools/preview_cache.json")
    ap.add_argument("--blender", default=BLENDER)
    ap.add_argument("--max-texture", type=int, default=1024)
    ap.add_argument("--workers", type=int, default=4)
    ap.add_argument("--rig-only", action="store_true", help="only rewrite the .json joint files (no Blender)")
    args = ap.parse_args()

    os.makedirs(args.out, exist_ok=True)
    cache = json.load(open(args.cache)) if os.path.exists(args.cache) else {}
    sha, files = list_files(args.dataset)
    by_asset = {}
    for f in files:
        if "/" in f["path"]:
            by_asset.setdefault(f["path"].split("/")[0], []).append(f["path"])
    wanted = args.assets or sorted(set(by_asset) - hidden_assets())

    def package_id(a):
        return get_json(f"{HF}/datasets/{args.dataset}/resolve/{sha}/{a}/com.nvidia.simready.packaging.json")["package_id"]

    if args.rig_only:
        rig_only(args, sha, [a for a in wanted if args.assets or os.path.exists(os.path.join(args.out, f"{a}.glb"))])
        return

    with ThreadPoolExecutor(args.workers) as pool:
        ids = dict(zip(wanted, pool.map(package_id, wanted)))
        todo = [a for a in wanted if args.assets or ids[a] not in cache
                or not os.path.exists(os.path.join(args.out, f"{a}.glb"))]
        print(f"{len(wanted)} packages, {len(todo)} previews to make", file=sys.stderr)

        def work(a):
            try:
                return a, make_one(args.dataset, sha, a, by_asset[a], args.out, args.blender, args.max_texture), None
            except Exception as e:  # keep going; report at the end
                return a, None, str(e)

        failed = {}
        for i, (a, info, err) in enumerate(pool.map(work, todo), 1):
            if err:
                failed[a] = err
            else:
                cache[ids[a]] = {"asset": a, **info}
                if info["missing_parts"]:
                    print(f"  {a}: parts not found in GLB: {info['missing_parts']}", file=sys.stderr)
            if i % 20 == 0 or i == len(todo):
                print(f"  {i}/{len(todo)}", file=sys.stderr)
                json.dump(cache, open(args.cache, "w"), indent=0, sort_keys=True)

    total = sum(os.path.getsize(os.path.join(args.out, f)) for f in os.listdir(args.out) if f.endswith(".glb"))
    print(f"done: {len(todo) - len(failed)} made, {len(failed)} failed, previews total {total / 1e6:.0f} MB", file=sys.stderr)
    for a, e in failed.items():
        print(f"  FAILED {a}: {e[:300]}", file=sys.stderr)


if __name__ == "__main__":
    main()