File size: 24,911 Bytes
767a9a2
5d43661
767a9a2
 
 
 
 
 
5d43661
767a9a2
5d43661
767a9a2
 
 
5d43661
 
 
 
 
 
 
 
 
 
 
 
 
 
767a9a2
 
5d43661
f42f559
 
5d43661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f42f559
 
5d43661
 
 
 
 
 
 
 
 
 
 
 
f42f559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d43661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767a9a2
5d43661
 
 
 
 
 
 
 
 
f42f559
 
 
 
5d43661
 
 
 
f42f559
 
5d43661
 
 
 
 
 
 
 
 
f42f559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767a9a2
f42f559
 
 
5d43661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f42f559
5d43661
 
 
f42f559
5d43661
 
f42f559
5d43661
f42f559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d43661
 
 
 
 
 
 
 
 
 
f42f559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d43661
 
 
 
 
 
 
 
 
 
f42f559
 
 
 
 
5d43661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f42f559
5d43661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767a9a2
5d43661
 
 
 
 
 
f42f559
5d43661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f42f559
 
 
 
 
 
 
 
 
 
 
 
 
767a9a2
 
f42f559
5d43661
 
 
f42f559
 
 
 
767a9a2
5d43661
 
 
 
 
 
 
 
 
 
 
 
 
767a9a2
 
5d43661
 
 
 
 
 
f42f559
5d43661
 
f42f559
 
 
 
 
 
 
 
5d43661
 
f42f559
5d43661
 
 
 
 
 
 
 
 
 
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
"""Add the original visual meshes to SimSure objects (ships on HF as scripts/).

SimSure shares collision shapes and physics, not the visual meshes. `visuals/<source>.jsonl.gz`
has one line per object: which original file to download (repo, path, checksum), which faces of
which mesh in it belong to which body, where they go, and a size check per piece. This script
downloads the file (or uses your copy), checks it is unchanged, places the meshes, checks every
piece, and writes `sim/fixed_main/model_visual.xml`: the same model plus visual-only meshes (no
contacts, no mass). GRScenes, SimReady and Palatial are USD: also `pip install usd-core`.

    python simsure_visuals.py --root <unpacked SimSure dir> --placements visuals/objaverse.jsonl.gz [--ids ids.txt]

Files are loaded raw (no vertex merging, no face cleanup), so face numbers follow the file whatever
the trimesh version; a failed check stops with an error, never a silently wrong mesh.
Needs numpy, trimesh, Pillow, huggingface_hub.
"""
from __future__ import annotations

import argparse
import gzip
import hashlib
import io
import json
import os
import xml.etree.ElementTree as ET
from pathlib import Path

import numpy as np

SCHEMA = "simsure_visual_placement/1"
_OLD_SCHEMAS = {"simsure_visual_recipe/1"}
LOADER = {"call": "trimesh.load(force='scene', process=False); pieces = scene graph node/geometry"}
LOADER_USD = {"call": "pxr: every UsdGeom.Mesh prim (instance proxies included) at the default time; "
                     "points x LocalToWorld; polygons fan-triangulated; key = prim path"}
FP_TOL_M = 1e-5
MIN_AREA_M2 = 1e-8          # below this MuJoCo rejects a mesh ("surface area is too small")


def runs_to_idx(runs: list[list[int]]) -> np.ndarray:
    return np.concatenate([np.arange(a, b) for a, b in runs]) if runs else np.zeros(0, int)


def fingerprint(n_faces: int, V: np.ndarray) -> dict:
    return {"faces": int(n_faces), "aabb": [V.min(0).round(7).tolist(), V.max(0).round(7).tolist()]}


def load_meshes(path: Path, loader: dict) -> dict:
    """{"<node>|<geometry>": (4x4 node->file frame, raw Trimesh)} for every mesh instance."""
    import trimesh
    if loader == LOADER_USD:
        return _load_usd(path)
    if loader != LOADER:
        raise ValueError(f"unknown loader {loader}")
    scene = trimesh.load(str(path), force="scene", process=False)
    out = {}
    for node in scene.graph.nodes_geometry:
        T, geom = scene.graph[node]
        m = scene.geometry[geom]
        if isinstance(m, trimesh.Trimesh):
            out[f"{_tok(node, path)}|{_tok(geom, path)}"] = (np.asarray(T, float), m)
    return out


def _load_usd(path: Path) -> dict:
    """{prim path: (4x4 local->world, Trimesh of the prim's points)}; needs `pip install usd-core`."""
    import trimesh
    from pxr import Usd, UsdGeom
    stage = Usd.Stage.Open(str(path))
    if stage is None:
        raise ValueError(f"USD could not open {path}")
    xc = UsdGeom.XformCache(Usd.TimeCode.Default())
    out = {}
    for prim in Usd.PrimRange(stage.GetPseudoRoot(), Usd.TraverseInstanceProxies()):
        if not prim.IsA(UsdGeom.Mesh):
            continue
        m = UsdGeom.Mesh(prim)
        pts, cnt, idx = (m.GetPointsAttr().Get(), m.GetFaceVertexCountsAttr().Get(),
                         m.GetFaceVertexIndicesAttr().Get())
        if not pts or not cnt or idx is None:
            continue
        cnt, idx = np.asarray(cnt, int), np.asarray(idx, int)
        start = np.concatenate([[0], np.cumsum(cnt)[:-1]])
        tri = [np.stack([np.full(c - 2, idx[s0]), idx[s0 + 1:s0 + c - 1], idx[s0 + 2:s0 + c]], 1)
               for s0, c in zip(start, cnt) if c >= 3]
        if not tri:
            continue
        T = np.asarray(xc.GetLocalToWorldTransform(prim), float).T      # USD is row-vector
        out[str(prim.GetPath())] = (T, trimesh.Trimesh(np.asarray(pts, float), np.vstack(tri), process=False))
    return out


def _tok(name: str, path: Path) -> str:
    """Loaders name file-level meshes after the file (OBJ): make keys independent of it."""
    for n in (path.name, path.stem):
        if name == n or name.startswith(n + "_"):
            return "@file" + name[len(n):]
    return name


def _sha_ok(p: Path, want: str) -> None:
    """sha256 of an upstream file, checked once per (size, mtime) (big archives are shared)."""
    st = p.stat()
    mark = p.with_name(p.name + f".sha256-{st.st_size}-{int(st.st_mtime)}")
    if mark.is_file() and mark.read_text() == want:
        return
    h = hashlib.sha256()
    with open(p, "rb") as fh:
        for blk in iter(lambda: fh.read(1 << 24), b""):
            h.update(blk)
    if h.hexdigest() != want:
        raise ValueError(f"{p}: sha256 {h.hexdigest()} != expected {want} (the original file changed)")
    try:
        mark.write_text(want)
    except OSError:
        pass


def fetch(upstream: dict, cache: Path, local: Path | None = None) -> list[Path]:
    """Local paths of the upstream file(s), sha256-checked. `local`: a copy you already have
    (a single file, or the dir holding a split archive's parts)."""
    if upstream.get("kind") == "zip_ranges":       # nothing to download whole; Upstream reads ranges
        return [local] if local is not None else []
    if upstream.get("kind") == "tar_gz" and local is None:   # streamed; files checked by sha256 one by one
        return []
    parts = upstream.get("parts") or [{"path": upstream["path"], "sha256": upstream["sha256"]}]
    out = []
    for q in parts:
        if local is not None:
            rel = q["path"] if upstream.get("kind") == "files" else Path(q["path"]).name
            p = local / rel if local.is_dir() else local
        else:
            from huggingface_hub import hf_hub_download
            p = Path(hf_hub_download(upstream["repo"], q["path"], repo_type=upstream.get("repo_type", "dataset"),
                                     revision=upstream.get("revision"), cache_dir=str(cache)))
        _sha_ok(p, q["sha256"])
        out.append(p)
    return out


def _ranges(spec: dict, start: int, n: int, local: Path | None) -> bytes:
    """Bytes [start, start+n) of a (split) zip, from the parts' HF URLs (range requests) or a local dir."""
    import time
    out, base = [], 0
    for path, size in spec["zip_parts"]:
        lo, hi = max(start, base), min(start + n, base + size)
        if lo < hi:
            if local is not None:
                with open(local / Path(path).name, "rb") as fh:
                    fh.seek(lo - base)
                    out.append(fh.read(hi - lo))
            else:
                from huggingface_hub import get_session, hf_hub_url
                from huggingface_hub.utils import build_hf_headers
                url = hf_hub_url(spec["repo"], path, repo_type=spec.get("repo_type", "dataset"),
                                 revision=spec.get("revision"))
                for k in range(9):
                    r = get_session().get(url, headers={**build_hf_headers(), "Range": f"bytes={lo - base}-{hi - base - 1}"},
                                          timeout=600)
                    if r.status_code != 429 or k == 8:
                        break
                    time.sleep(min(2.0 * 2 ** k, 300.0))        # HF rate limit: back off
                r.raise_for_status()
                out.append(r.content)
        base += size
    data = b"".join(out)
    if len(data) != n:
        raise ValueError(f"short read: {len(data)} of {n} bytes")
    return data


def zip_member(spec: dict, local: Path | None = None, m: dict | None = None) -> bytes:
    """One member of a zip read in place (local header + payload), checked by sha256 (or the zip's
    own CRC32). Handles PKWARE split archives (address = disk * part_size + offset) and byte splits."""
    import struct
    import zlib
    m = m or spec["member"]
    at = m.get("disk", 0) * spec.get("part_size", 0) + m["off"]
    hdr = _ranges(spec, at, 30, local)
    if hdr[:4] != b"PK\x03\x04":
        raise ValueError(f"{m['name']}: no zip local header at {at}")
    nlen, elen = struct.unpack_from("<HH", hdr, 26)
    raw = _ranges(spec, at + 30 + nlen + elen, m["csize"], local)
    data = raw if m["method"] == 0 else zlib.decompressobj(-15).decompress(raw)
    ok = hashlib.sha256(data).hexdigest() == m["sha256"] if "sha256" in m else zlib.crc32(data) == m["crc32"]
    if not ok:
        raise ValueError(f"{m['name']}: content differs from what we expect (the original file changed)")
    return data


class _Concat(io.RawIOBase):
    """Byte splits of one archive (`cat a b c`) read as one seekable file, without the copy."""

    def __init__(self, paths: list[Path]):
        self.fhs = [open(p, "rb") for p in paths]
        self.sizes = [p.stat().st_size for p in paths]
        self.total, self.pos = sum(self.sizes), 0

    def seekable(self):
        return True

    def readable(self):
        return True

    def tell(self):
        return self.pos

    def seek(self, off, whence=0):
        self.pos = {0: off, 1: self.pos + off, 2: self.total + off}[whence]
        return self.pos

    def readinto(self, b):
        n, start = 0, self.pos
        for fh, sz in zip(self.fhs, self.sizes):
            if start >= sz:
                start -= sz
                continue
            fh.seek(start)
            k = fh.readinto(memoryview(b)[n:n + min(len(b) - n, sz - start)])
            n += k
            start = 0
            if n >= len(b):
                break
        self.pos += n
        return n


def _texture_png(visual) -> tuple[bytes | None, list[float]]:
    mat = getattr(visual, "material", None)
    rgba, img = [1.0, 1.0, 1.0, 1.0], None
    if mat is not None:
        f = getattr(mat, "baseColorFactor", None)
        if f is not None:
            f = np.asarray(f, float).ravel()
            f = f / 255.0 if f.max() > 1.0 else f
            rgba = f.tolist()[:4] + [1.0] * (4 - len(f))
        img = getattr(mat, "baseColorTexture", None)
        if img is None:
            img = getattr(mat, "image", None)
    if img is None:
        return None, rgba
    buf = io.BytesIO()
    img.convert("RGBA").save(buf, format="PNG")
    return buf.getvalue(), rgba


def _obj(V: np.ndarray, F: np.ndarray, UV: np.ndarray | None) -> bytes:
    out = [f"v {x:.9g} {y:.9g} {z:.9g}" for x, y, z in V]
    if UV is not None:
        out += [f"vt {u:.9g} {v:.9g}" for u, v in UV]
        out += [f"f {a}/{a} {b}/{b} {c}/{c}" for a, b, c in F + 1]
    else:
        out += [f"f {a} {b} {c}" for a, b, c in F + 1]
    return ("\n".join(out) + "\n").encode()


class Upstream:
    """The fetched upstream: one file, or an archive (`kind` zip / split_zip / tar_gz) whose members are
    extracted on demand (a member's whole directory, plus the MTL/textures it names). Members
    are relative to the dir holding `entity_marker` when given, else to the archive root."""

    def __init__(self, paths: list[Path], spec: dict, loader: dict, work: Path, prefixes: set | None = None):
        self.spec, self.loader, self._cache = spec, loader, {}
        self.kind = spec.get("kind", "file")
        self.zf = None
        if self.kind == "file":
            self.single = paths[0]
            return
        if self.kind == "zip_ranges" and "members" in spec:   # this asset's files, read in place
            self.work = work / "zip_ranges" / hashlib.sha256(f"{spec['repo']}@{spec.get('revision')}".encode()).hexdigest()[:16]
            for name, m in spec["members"].items():
                dst = self.work / name
                if not dst.is_file():
                    dst.parent.mkdir(parents=True, exist_ok=True)
                    t = dst.with_name("." + dst.name + ".part")
                    t.write_bytes(zip_member(spec, paths[0] if paths else None, {"name": name, **m}))
                    os.replace(t, dst)
            self.kind = "members"
            return
        if self.kind == "zip_ranges":             # just this asset's file, read in place from the archive
            dst = work / "zip_ranges" / spec["member"]["sha256"][:16] / Path(spec["member"]["name"]).name
            if not dst.is_file():
                dst.parent.mkdir(parents=True, exist_ok=True)
                t = dst.with_name("." + dst.name + ".part")
                t.write_bytes(zip_member(spec, paths[0] if paths else None))
                os.replace(t, dst)
            self.single, self.kind = dst, "file"
            return
        if self.kind == "files":                  # a USD and the layers it references, as in the repo
            self.single = paths[[q["path"] for q in spec["parts"]].index(spec["root"])]
            self.kind = "file"
            return
        if self.kind == "tar_gz":                 # not seekable: one streaming pass for every asset asked
            self.work = work / spec["sha256"][:16]
            self._untar(paths[0] if paths else None, prefixes or set(), spec)
            return
        import zipfile
        raw = open(paths[0], "rb") if len(paths) == 1 else io.BufferedReader(_Concat(paths), 1 << 20)
        self.zf = zipfile.ZipFile(raw)
        self.names = set(self.zf.namelist())
        self.work = work / hashlib.sha256("".join(str(p) for p in paths).encode()).hexdigest()[:16]
        marker = spec.get("entity_marker")
        hits = sorted(n for n in self.names if n.endswith("/" + marker) or n == marker) if marker else []
        self.prefix = hits[0][: -len(marker)] if hits else ""

    def _untar(self, path: Path | None, prefixes: set, spec: dict) -> None:
        """Extract the members under `prefixes` (dirs, e.g. 'data/<id>/urdf_w_collider/'), once. With no
        local copy, streams the archive from HF (nothing big on disk) and stops after the last asset
        asked for: the archive is sorted by path, so only bytes up to that asset are read."""
        import tarfile
        todo = {q for q in prefixes if not (self.work / q / ".simsure_done").is_file()}
        if not todo:
            return
        depth = {q.count("/") for q in todo}
        last = max("/".join(q.split("/")[:-2]) for q in todo)        # asset dir of the last prefix
        root = self.work.resolve()
        if path is not None:
            fobj, label = open(path, "rb"), path.name
        else:
            import urllib.request
            from huggingface_hub import hf_hub_url
            from huggingface_hub.utils import build_hf_headers
            url = hf_hub_url(spec["repo"], spec["path"], repo_type=spec.get("repo_type", "dataset"),
                             revision=spec.get("revision"))
            # 401/403 here: request access on the dataset's HF page and `hf auth login` first
            fobj = urllib.request.urlopen(urllib.request.Request(url, headers=build_hf_headers()), timeout=600)
            label = spec["path"]
        print(f"reading {label} for {len(todo)} assets (streamed, stops after the last one) ...", flush=True)
        seen: set = set()
        with fobj, tarfile.open(fileobj=fobj, mode="r|gz") as tf:
            for m in tf:
                hit = next(("/".join(m.name.split("/")[:k]) + "/" for k in depth
                            if "/".join(m.name.split("/")[:k]) + "/" in todo), None)
                if hit is None:
                    if seen >= todo and m.name > last and not m.name.startswith(last + "/"):
                        break                        # sorted archive: past every asset asked for
                    continue
                seen.add(hit)
                if not m.isfile():
                    continue
                dst = (self.work / m.name).resolve()
                if root not in dst.parents:
                    raise ValueError(f"unsafe member path {m.name}")
                dst.parent.mkdir(parents=True, exist_ok=True)
                t = dst.with_name("." + dst.name + ".part")
                with tf.extractfile(m) as src, open(t, "wb") as out:
                    out.write(src.read())
                os.replace(t, dst)
        for q in todo:
            (self.work / q).mkdir(parents=True, exist_ok=True)
            (self.work / q / ".simsure_done").write_text("ok")

    def _extract(self, name: str) -> Path:
        dst = self.work / name
        if not dst.is_file():
            dst.parent.mkdir(parents=True, exist_ok=True)
            t = dst.with_name("." + dst.name + ".part")
            t.write_bytes(self.zf.read(name))
            os.replace(t, dst)
        return dst

    def path(self, member: str) -> Path:
        if self.kind in ("tar_gz", "members"):
            f = self.work / member
            if not f.is_file():
                raise ValueError(f"{member} not in the upstream archive")
            return f
        name = self.prefix + member
        if name not in self.names:
            raise ValueError(f"{member} not in the upstream archive")
        d = name.rsplit("/", 1)[0] + "/" if "/" in name else ""
        for n in self.names:
            if n.startswith(d) and not n.endswith("/") and "/" not in n[len(d):]:
                self._extract(n)
        f = self.work / name
        if f.suffix.lower() == ".obj":                       # MTL + textures it names, anywhere
            for line in f.read_text(errors="replace").splitlines():
                if line.startswith("mtllib "):
                    mtl = os.path.normpath(os.path.join(os.path.dirname(name), line.split(None, 1)[1].strip()))
                    if mtl in self.names:
                        m = self._extract(mtl)
                        for ml in m.read_text(errors="replace").splitlines():
                            t = ml.split()
                            if t and t[0].lower().startswith("map_") and len(t) > 1:
                                tex = os.path.normpath(os.path.join(os.path.dirname(mtl), t[-1]))
                                if tex in self.names:
                                    self._extract(tex)
        return f

    def meshes(self, member: str | None) -> dict:
        if member not in self._cache:
            f = self.single if self.kind == "file" else self.path(member)
            self._cache[member] = load_meshes(f, self.loader)
        return self._cache[member]


def build(asset: Path, recipe: dict, meshes, textures: bool = True) -> dict[str, bytes]:
    """{path relative to the asset: bytes}: visual meshes/textures + model_visual.xml.
    `meshes`: an Upstream, or the mesh dict of a single upstream file."""
    get = meshes.meshes if hasattr(meshes, "meshes") else (lambda member: meshes)
    fm = asset / "sim" / "fixed_main"
    root = ET.parse(fm / "model.xml").getroot()
    comp = root.find("compiler")
    meshdir = (comp.get("meshdir") if comp is not None else None) or ""
    if comp is not None and meshdir:
        comp.set("texturedir", meshdir)
    asset_el = root.find("asset")
    if asset_el is None:
        asset_el = ET.SubElement(root, "asset")
    bodies = {b.get("name"): b for b in root.iter("body")}
    files = {}
    for L, spec in recipe["links"].items():
        T = np.asarray(spec["T_body_from_source"], float)
        for k, piece in enumerate(spec["pieces"]):
            ms = get(piece.get("file"))
            if piece["mesh"] not in ms:
                raise ValueError(f"upstream mesh {piece['mesh']!r} in {piece.get('file')} not found (loader differs?)")
            T_node, m = ms[piece["mesh"]]
            F0 = np.asarray(m.faces)[runs_to_idx(piece["faces"])]
            used, F = np.unique(F0, return_inverse=True)
            F = F.reshape(-1, 3)
            A = T @ T_node
            V = np.asarray(m.vertices)[used] @ A[:3, :3].T + A[:3, 3]
            fp = fingerprint(len(F0), V)
            want = piece["fingerprint"]
            if fp["faces"] != want["faces"] or np.abs(np.asarray(fp["aabb"]) - np.asarray(want["aabb"])).max() > FP_TOL_M:
                raise ValueError(f"piece {piece['mesh']!r} of {L}: check failed: {fp} != expected {want}")
            area = 0.5 * np.linalg.norm(np.cross(V[F[:, 1]] - V[F[:, 0]], V[F[:, 2]] - V[F[:, 0]]), axis=1).sum()
            if len(V) < 4 or area < MIN_AREA_M2:
                continue                       # slivers MuJoCo refuses as a mesh; invisible anyway
            uv = getattr(m.visual, "uv", None)
            UV = np.asarray(uv)[used] if uv is not None and len(uv) == len(m.vertices) else None
            png, rgba = _texture_png(m.visual) if textures else (None, [1.0, 1.0, 1.0, 1.0])
            name = f"vis_{L}_{k}".replace("/", "_").replace("#", "_")
            files[os.path.join("sim/fixed_main", meshdir, f"{name}.obj")] = _obj(V, F, UV if png else None)
            ET.SubElement(asset_el, "mesh", {"name": name, "file": f"{name}.obj", "inertia": "shell"})
            mat = {"name": f"{name}_mat", "rgba": " ".join(f"{c:.4g}" for c in rgba)}
            if png and UV is not None:
                files[os.path.join("sim/fixed_main", meshdir, f"{name}.png")] = png
                ET.SubElement(asset_el, "texture", {"name": f"{name}_tex", "type": "2d", "file": f"{name}.png"})
                mat["texture"] = f"{name}_tex"
            ET.SubElement(asset_el, "material", mat)
            ET.SubElement(bodies[spec["body"]], "geom", {
                "name": name, "type": "mesh", "mesh": name, "material": f"{name}_mat", "contype": "0",
                "conaffinity": "0", "group": "2", "density": "0"})
    files["sim/fixed_main/model_visual.xml"] = ET.tostring(root)
    return files


_OPEN: dict = {}


def _ukey(r: dict) -> str:
    """One key per upstream archive (per-asset fields like member_depth left out)."""
    return json.dumps({k: v for k, v in r["upstream"].items() if k not in ("member_depth", "files_sha256")},
                      sort_keys=True)


def tar_prefixes(recipe: dict) -> set:
    """Archive dirs a recipe needs (for `tar_gz` upstreams): each piece file's asset dir."""
    k = int(recipe["upstream"].get("member_depth", 0))
    return {"/".join(pc["file"].split("/")[:k]) + "/" for L in recipe["links"].values() for pc in L["pieces"]} if k else set()


def apply(asset: Path, recipe: dict, cache: Path, local: Path | None = None, prefixes: set | None = None) -> list[str]:
    if recipe.get("schema") != SCHEMA and recipe.get("schema") not in _OLD_SCHEMAS:
        raise ValueError(f"unknown placement format {recipe.get('schema')}")
    key = _ukey(recipe)
    if key not in _OPEN:                                   # archives are shared by many assets
        _OPEN.clear()
        _OPEN[key] = Upstream(fetch(recipe["upstream"], cache, local), recipe["upstream"], recipe["loader"],
                              cache / "unpacked", prefixes if prefixes is not None else tar_prefixes(recipe))
    for member, want in (recipe["upstream"].get("files_sha256") or {}).items():   # streamed archives
        got = hashlib.sha256(_OPEN[key].path(member).read_bytes()).hexdigest()
        if got != want:
            raise ValueError(f"{member}: checksum differs from what we expect (the original file changed)")
    files = build(asset, recipe, _OPEN[key])
    for rel, data in files.items():
        p = asset / rel
        p.parent.mkdir(parents=True, exist_ok=True)
        t = p.with_name("." + p.name + ".tmp")
        t.write_bytes(data)
        os.replace(t, p)
    return sorted(files)


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--root", required=True, help="dir holding the extracted <source>/<id>/ asset dirs")
    ap.add_argument("--placements", "--recipes", dest="recipes", required=True, help="visuals/<source>.jsonl.gz")
    ap.add_argument("--ids", help="file with object ids to do (default: every object found under --root)")
    ap.add_argument("--local", help="upstream file you already have (with one id)")
    ap.add_argument("--cache", default=os.path.expanduser("~/.cache/simsure"))
    a = ap.parse_args(argv)
    want = set(Path(a.ids).read_text().split()) if a.ids else None
    op = gzip.open if a.recipes.endswith(".gz") else open
    ok = bad = 0
    todo = []
    for l in op(a.recipes, "rt"):
        r = json.loads(l)
        if (want is None or r["id"] in want) and (Path(a.root) / r["id"]).is_dir():
            todo.append(r)
    key = _ukey
    todo.sort(key=key)                                    # one archive open at a time
    need: dict = {}
    for r in todo:
        need.setdefault(key(r), set()).update(tar_prefixes(r))
    for r in todo:
        asset = Path(a.root) / r["id"]
        try:
            apply(asset, r, Path(a.cache), Path(a.local) if a.local else None, need[key(r)])
            ok += 1
        except Exception as e:                                        # noqa: BLE001 — reported per asset
            bad += 1
            print(f"ERR {r['id']}: {type(e).__name__}: {e}")
    print(f"placed {ok}, failed {bad}")
    return 1 if bad else 0


if __name__ == "__main__":
    raise SystemExit(main())