File size: 13,448 Bytes
5f0371a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Package the task-9 packing-area scene as a SELF-CONTAINED background.

Takes the composition-based export (assets/task9_packing_area/
task9_packing_area.usd, see export_task9_scene_usd.py) and produces a fully
independent folder that can be copied anywhere (e.g. backend
storage/backgrounds/):

    assets/packing_area_background/
        scene.usd        flattened composed stage (only ACTIVE prims: the
                         warehouse shell, cleared bench, dressing props,
                         lights -- deactivated zones don't compose)
        resource/...     every texture/material file the scene references,
                         copied in and rewritten to package-relative paths

Texture slimming (the dataset ships 4K PNGs at 20-50 MB each): building-shell
textures are capped at 1K and prop textures at 2K -- the benchmark cameras
render at 640x480, and the shell is never closer than a few meters. Files are
deduplicated by content hash. <UDIM> patterns are expanded tile-by-tile.
Bare shader names (OmniPBR.mdl etc.) resolve from the Isaac install and are
left alone; unreachable omniverse:// paths are left as-is (benign warnings,
same as the source dataset).

Run phase 1 (needs pxr -- Isaac USD libs), which then invokes phase 2
(texture downscale, needs system python3 + PIL) automatically:

    USDLIBS=/opt/isaac-sim/extscache/omni.usd.libs-1.0.1+69cbf6ad.lx64.r.cp311
    PYTHONPATH=$USDLIBS LD_LIBRARY_PATH=$USDLIBS/bin \
        /opt/isaac-sim/kit/python/bin/python3 simready_warehouse_tasks/package_task9_background.py
"""

import hashlib
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys

SCRIPT_DIR = Path(__file__).resolve().parent
PROJECT_DIR = SCRIPT_DIR.parent
SRC = PROJECT_DIR / "assets" / "simple_packing_area" / "simple_packing_area.usd"
OUT_DIR = PROJECT_DIR / "assets" / "simple_packing_background"
SCENE = OUT_DIR / "scene.usd"
MANIFEST = OUT_DIR / "resource" / "textures_manifest.tsv"

SHELL_MAX_PX = 512  # building-shell textures: never seen closer than ~3 m
PROP_MAX_PX = 2048   # bench/rack/box textures: can fill a wrist-camera frame


# Keep emitting lights only near the packing area; the warehouse shell ships
# ~555 UsdLux fixtures across the whole building, which crushes RTX real-time
# rendering. Fixture geometry stays visible everywhere -- only distant light
# prims are deactivated. Bounds are generous around the table (origin) so the
# work area and everything the cameras face stays properly lit.
LIGHT_KEEP_X = (-16.0, 16.0)
LIGHT_KEEP_Y = (-12.0, 20.0)


def _prune_distant_lights(scene_path):
    from pxr import Usd, UsdGeom, UsdLux

    stage = Usd.Stage.Open(str(scene_path))
    cache = UsdGeom.XformCache()
    doomed = []
    kept = 0
    for prim in stage.Traverse(Usd.TraverseInstanceProxies()):
        if not (prim.IsA(UsdLux.BoundableLightBase) or prim.IsA(UsdLux.NonboundableLightBase)):
            continue
        if not prim.GetPath().pathString.startswith("/Root/Warehouse/"):
            continue  # never touch the baked dome/key lights
        pos = cache.GetLocalToWorldTransform(prim).ExtractTranslation()
        if LIGHT_KEEP_X[0] <= pos[0] <= LIGHT_KEEP_X[1] and LIGHT_KEEP_Y[0] <= pos[1] <= LIGHT_KEEP_Y[1]:
            kept += 1
            continue
        doomed.append(prim.GetPath())
    for path in doomed:
        prim = stage.GetPrimAtPath(path)
        if not prim:
            continue
        if prim.IsInstanceProxy():
            # Editing inside an instance requires de-instancing its root.
            anc = prim
            while anc and anc.IsInstanceProxy():
                anc = anc.GetParent()
            if anc and anc.IsInstance():
                anc.SetInstanceable(False)
            prim = stage.GetPrimAtPath(path)
        if prim and not prim.IsInstanceProxy():
            prim.SetActive(False)
    stage.GetRootLayer().Save()
    print(f"  lights: kept {kept} near the packing area, deactivated {len(doomed)} distant")


def main():
    from pxr import Sdf, Usd, UsdUtils

    if OUT_DIR.exists():
        shutil.rmtree(OUT_DIR)
    (OUT_DIR / "resource").mkdir(parents=True)

    print(f"[1/3] Flattening {SRC} (only active prims compose)...")
    stage = Usd.Stage.Open(str(SRC))
    stage.Export(str(SCENE))
    print(f"  scene.usd: {SCENE.stat().st_size / 1e6:.1f} MB")
    _prune_distant_lights(SCENE)

    print("[2/3] Collecting referenced assets (dedup by content hash)...")
    src_dir = SRC.parent
    layer = Sdf.Layer.FindOrOpen(str(SCENE))
    hash_to_rel = {}
    rel_class = {}  # rel path -> "prop" | "shell" (prop wins on dedup collisions)
    stats = {"copied": 0, "deduped": 0, "external": 0, "missing": []}

    def classify(abs_path):
        # Actual objects (bench, boxes, racks) live under Props/general and
        # Props/assembly; Props/materials and Props/skies hold the shared
        # building-shell materials despite the folder name.
        return "prop" if ("/Props/general/" in abs_path or "/Props/assembly/" in abs_path) else "shell"

    def copy_one(abs_path, dest_name_hint):
        digest = hashlib.sha1(Path(abs_path).read_bytes()).hexdigest()[:16]
        if digest in hash_to_rel:
            stats["deduped"] += 1
            rel = hash_to_rel[digest]
            if classify(abs_path) == "prop":
                rel_class[rel] = "prop"
            return rel
        rel = f"resource/{digest}_{dest_name_hint}"
        shutil.copy2(abs_path, OUT_DIR / rel)
        hash_to_rel[digest] = rel
        rel_class[rel] = classify(abs_path)
        stats["copied"] += 1
        return rel

    mdl_dirs = {}  # mdl content digest -> package-relative mdl path
    _tex_index = {}  # dataset-wide basename -> path index, built on first miss

    def find_texture_anywhere(basename):
        if not _tex_index:
            print("  building dataset-wide texture index (first fallback miss)...")
            for _root_dir in (PROJECT_DIR / "assets" / "physicalai_simready_warehouse_01",
                              PROJECT_DIR / "assets" / "isaac_sim_assets_51"):
              for dirpath, _dirs, files in os.walk(_root_dir):
                for f in files:
                    if f.lower().endswith((".png", ".jpg", ".jpeg", ".tga", ".hdr", ".exr")):
                        _tex_index.setdefault(f, os.path.join(dirpath, f))
        return _tex_index.get(basename)

    def copy_mdl(abs_path):
        """Copy a custom .mdl into its own package folder together with every
        texture it references internally (relative to the .mdl's location),
        preserving the relative layout so those internal references keep
        resolving. Built-in shader names (OmniPBR.mdl) never reach here."""
        digest = hashlib.sha1(Path(abs_path).read_bytes()).hexdigest()[:16]
        if digest in mdl_dirs:
            stats["deduped"] += 1
            return mdl_dirs[digest]
        mdl_name = os.path.basename(abs_path)
        dest_dir = OUT_DIR / f"resource/mdl_{digest}"
        dest_dir.mkdir(parents=True, exist_ok=True)
        shutil.copy2(abs_path, dest_dir / mdl_name)
        stats["copied"] += 1
        src_mdl_dir = os.path.dirname(abs_path)
        # MDLs may import sibling modules ("import .::OmniUe4Function") which
        # must live next to them or compilation fails (renders red). Copy the
        # whole import closure into the same folder.
        _pending = [abs_path]
        _seen_mods = {mdl_name}
        while _pending:
            _mdl_text = Path(_pending.pop()).read_text(errors="replace")
            for _mod in set(re.findall(r"(?:import|using)\s+\.::([A-Za-z0-9_]+)", _mdl_text)):
                _mod_file = f"{_mod}.mdl"
                if _mod_file in _seen_mods:
                    continue
                _seen_mods.add(_mod_file)
                _src_mod = os.path.join(src_mdl_dir, _mod_file)
                if os.path.exists(_src_mod):
                    shutil.copy2(_src_mod, dest_dir / _mod_file)
                    stats["copied"] += 1
                    _pending.append(_src_mod)
                else:
                    stats["missing"].append(f"{mdl_name}: module {_mod_file}")
        text = Path(abs_path).read_text(errors="replace")
        for ref in set(re.findall(r'"([^"]+\.(?:png|jpg|jpeg|tga|hdr|exr))"', text, re.IGNORECASE)):
            ref_norm = ref.lstrip("./")
            if ref_norm.startswith("..") or os.path.isabs(ref):
                print(f"  WARNING: mdl ref escapes its folder, skipped: {mdl_name}: {ref}")
                continue
            tiles = [ref_norm]
            if "<UDIM>" in ref_norm:
                pattern = os.path.basename(ref_norm).replace("<UDIM>", "[0-9][0-9][0-9][0-9]")
                folder = Path(src_mdl_dir) / os.path.dirname(ref_norm)
                tiles = [os.path.join(os.path.dirname(ref_norm), t.name) for t in sorted(folder.glob(pattern))]
            for tile in tiles:
                src_tex = os.path.normpath(os.path.join(src_mdl_dir, tile))
                if not os.path.exists(src_tex):
                    # The dataset's MDLs are sloppy about case/subfolders
                    # ("Textures/foo.png" vs "textures/Chrome_A/foo.png");
                    # Omniverse's MDL resolver tolerates it, so fall back to a
                    # by-name search under the MDL's own folder and copy the
                    # hit to the path the MDL actually references.
                    candidates = sorted(Path(src_mdl_dir).rglob(os.path.basename(tile)))
                    if candidates:
                        src_tex = str(candidates[0])
                    else:
                        # This MDL copy has no textures nearby at all; take
                        # the same-named file from anywhere in the dataset.
                        src_tex = find_texture_anywhere(os.path.basename(tile))
                        if src_tex is None:
                            stats["missing"].append(f"{mdl_name}: {tile}")
                            continue
                dst_tex = dest_dir / tile
                dst_tex.parent.mkdir(parents=True, exist_ok=True)
                if not dst_tex.exists():
                    shutil.copy2(src_tex, dst_tex)
                    rel_class[f"resource/mdl_{digest}/{tile}"] = classify(abs_path)
                    stats["copied"] += 1
        rel = f"resource/mdl_{digest}/{mdl_name}"
        mdl_dirs[digest] = rel
        return rel

    def rewrite(path):
        if not path:
            return path
        if path.startswith(("omniverse://", "http")) or "/" not in path:
            # unreachable server paths and bare shader names (OmniPBR.mdl):
            # leave as authored.
            stats["external"] += 1
            return path
        abs_path = path if os.path.isabs(path) else os.path.normpath(str(src_dir / path))
        if abs_path.endswith(".mdl"):
            if not os.path.exists(abs_path):
                stats["missing"].append(path)
                return path
            return "./" + copy_mdl(abs_path)
        name = os.path.basename(abs_path)
        if "<UDIM>" in name:
            # expand tiles: copy each 4-digit tile under a shared hint so the
            # rewritten pattern resolves to all of them.
            folder = Path(os.path.dirname(abs_path))
            tiles = sorted(folder.glob(name.replace("<UDIM>", "[0-9][0-9][0-9][0-9]")))
            if not tiles:
                stats["missing"].append(path)
                return path
            hint = name.replace("<UDIM>", "UDIM")
            digest = hashlib.sha1(("udim:" + abs_path).encode()).hexdigest()[:16]
            for tile in tiles:
                tile_no = tile.name[len(name.split("<UDIM>")[0]):][:4]
                tile_rel = f"resource/{digest}_{hint.replace('UDIM', tile_no)}"
                dst = OUT_DIR / tile_rel
                if not dst.exists():
                    shutil.copy2(tile, dst)
                    rel_class[tile_rel] = classify(str(tile))
                    stats["copied"] += 1
            return f"./resource/{digest}_{hint.replace('UDIM', '<UDIM>')}"
        if not os.path.exists(abs_path):
            stats["missing"].append(path)
            return path
        return "./" + copy_one(abs_path, name)

    UsdUtils.ModifyAssetPaths(layer, rewrite)
    layer.Save()
    print(f"  copied {stats['copied']} files ({stats['deduped']} duplicate refs), "
          f"{stats['external']} left external")
    if stats["missing"]:
        print(f"  WARNING missing: {stats['missing']}")

    # Classification for the downscale pass: a file is a PROP texture if ANY
    # of its source paths lived under /Props/, else building shell.
    with open(MANIFEST, "w") as mf:
        for rel, cls in sorted(rel_class.items()):
            mf.write(f"{rel}\t{cls}\n")

    print("[3/3] Downscaling textures with system python3 + PIL...")
    downscale = subprocess.run(
        [sys.executable if "isaac" not in sys.executable else "python3",
         str(SCRIPT_DIR / "_downscale_textures.py"), str(OUT_DIR),
         str(SHELL_MAX_PX), str(PROP_MAX_PX)],
        capture_output=True, text=True,
    )
    print(downscale.stdout)
    if downscale.returncode != 0:
        print(downscale.stderr)
        raise SystemExit("texture downscale failed")

    total = sum(f.stat().st_size for f in OUT_DIR.rglob("*") if f.is_file())
    print(f"DONE: package total {total / 1e6:.1f} MB at {OUT_DIR}")


if __name__ == "__main__":
    main()