packingbench-assets / scripts /package_simple_background.py
Hovessian's picture
Update package_simple_background.py (shell at identity, tuned lighting)
5f0371a verified
Raw
History Blame Contribute Delete
13.4 kB
"""
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()