robodojo-dev-suite / tools /robolab /convert_objects.py
vietnhat's picture
Add files using upload-large-folder tool
a84ddf8 verified
Raw History Blame Contribute Delete
9.82 kB
"""Convert RoboLab's objects into RoboDojo objects (PROD-116).
/data1/viet/venv/usdtools/bin/python dev_suite/robolab/convert_objects.py [--robolab /data1/viet/robolab] [--out $ROBOLAB_OBJECTS]
Needs `pxr` (pip install usd-core; Isaac Sim's own python also has it). Only the sets we may use commercially: ycb (MIT) and
vomp (CC BY 4.0); see dev_suite/robolab/README.md. For each object it writes, under --out (default $ROBOLAB_OBJECTS or
/data1/viet/robolab_objects):
RoboLabSrc/<set>/... the RoboLab files (USD + textures), copied once
Rigid/rl_<name>/00000/object.usd a wrapper: rigid body on the root, the model below it, scaled and moved so that its
Geometry/rl_<name>/00000/object.usd bbox centre is the origin (RoboDojo's convention); Geometry = the same without the
rigid body (a static fixture, e.g. a shelf)
.../00000/metadata.json, description.json
and dev_suite/robolab/objects.json (the manifest: set, licence, scale, size, mass, friction). scripts/install_into_robodojo.sh
links the folders into RoboDojo's Assets/Object/RoboDojo.
Scale: RoboDojo's checks read the unscaled bbox from metadata.json, so a scale is baked into the wrapper, never set per layout.
Objects larger than MAX_SIZE are shrunk to it (the vomp crates and shelves are full size, up to 1.8 m); SCALE overrides that.
Mass: RoboLab's when it gives one, otherwise the bbox volume times EFFECTIVE_DENSITY (hollow household things), within
[0.02, 0.5] kg (RoboDojo caps every rigid body at 0.5 kg anyway).
"""
from __future__ import annotations
import argparse
import json
import math
import os
import shutil
import uuid
from pathlib import Path
import numpy as np
import trimesh
from pxr import Gf, Usd, UsdGeom, UsdPhysics, UsdUtils
HERE = Path(__file__).resolve().parent
LICENCES = {"ycb": "MIT", "vomp": "CC-BY-4.0"} # the others (hope, handal, hot3d, ...) are non-commercial: not converted
MAX_SIZE = 0.5 # m, largest side of a table-top object
SCALE = { # where the default rule is not what the tasks need: mostly the scale RoboLab's scenes use; the shelves lower,
# about 30 cm tall, so that two short arms reach their top and they do not block the head camera
"rack_l04": 0.2, "wireshelving_a01": 0.35, "bulkstoragerack_a01": 0.16, "heavydutysteelshelving_a01": 0.3,
"container_f24": 0.3, "bin_a06": 0.7, "bin_b03": 1.4, "anza_medium": 0.4, "utilityjug_a03": 0.4,
}
EFFECTIVE_DENSITY = 150.0 # kg/m^3 of the bbox
def bbox(stage: Usd.Stage, prim: Usd.Prim) -> Gf.Range3d:
cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), [UsdGeom.Tokens.default_, UsdGeom.Tokens.render])
return cache.ComputeWorldBound(prim).ComputeAlignedRange()
def copy_sources(usd: Path, set_root: Path, out_src: Path) -> Path:
"""Copy the USD and the textures it uses, keeping their paths relative to the set's folder."""
layers, assets, _ = UsdUtils.ComputeAllDependencies(str(usd))
for f in [Path(layer.realPath) for layer in layers] + [Path(a) for a in assets]:
dst = out_src / f.relative_to(set_root)
if not dst.exists():
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(f, dst)
return out_src / usd.relative_to(set_root)
def wrapper(path: Path, source: Path, scale: float, rigid: bool) -> Gf.Range3d:
"""object.usd: /root (rigid body if `rigid`) / offset (scale, then centre the bbox) / model (the RoboLab USD)."""
path.parent.mkdir(parents=True, exist_ok=True)
path.unlink(missing_ok=True)
stage = Usd.Stage.CreateNew(str(path))
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(stage, 1.0)
root = UsdGeom.Xform.Define(stage, "/root")
stage.SetDefaultPrim(root.GetPrim())
if rigid:
UsdPhysics.RigidBodyAPI.Apply(root.GetPrim())
offset = UsdGeom.Xform.Define(stage, "/root/offset")
model = stage.DefinePrim("/root/offset/model")
model.GetReferences().AddReference(os.path.relpath(source, path.parent))
model.RemoveAPI(UsdPhysics.RigidBodyAPI) # one rigid body per object: the root's
model.RemoveAPI(UsdPhysics.MassAPI) # RoboDojo sets the mass on the root
translate = offset.AddTranslateOp()
offset.AddScaleOp().Set(Gf.Vec3f(scale))
centre = bbox(stage, root.GetPrim()).GetMidpoint()
translate.Set(Gf.Vec3d(-centre[0], -centre[1], -centre[2]))
stage.GetRootLayer().Save()
return bbox(stage, root.GetPrim())
def floor_height(path: Path, box: Gf.Range3d) -> float:
"""Height above the bottom of the first surface straight down through the middle: a container's inner floor (the
sampler drops what starts inside it there), a solid object's top."""
stage = Usd.Stage.Open(str(path))
xf = UsdGeom.XformCache()
verts, faces = [], []
for prim in stage.Traverse():
if not (prim.IsA(UsdGeom.Mesh) and prim.HasAPI(UsdPhysics.CollisionAPI)):
continue
mesh = UsdGeom.Mesh(prim)
pts = np.asarray(mesh.GetPointsAttr().Get(), dtype=float)
m = np.asarray(xf.GetLocalToWorldTransform(prim), dtype=float)
start = sum(len(v) for v in verts)
verts.append(pts @ m[:3, :3] + m[3, :3])
i = 0
idx = mesh.GetFaceVertexIndicesAttr().Get()
for n in mesh.GetFaceVertexCountsAttr().Get():
faces += [[start + idx[i], start + idx[i + k], start + idx[i + k + 1]] for k in range(1, n - 1)]
i += n
if not faces:
return 0.0
hits, _, _ = trimesh.Trimesh(np.concatenate(verts), np.asarray(faces), process=False).ray.intersects_location(
[[0.0, 0.0, box.GetMax()[2] + 0.1]], [[0.0, 0.0, -1.0]])
return float(hits[:, 2].max() - box.GetMin()[2]) if len(hits) else 0.0
def metadata(box: Gf.Range3d, mass: float, friction: float, record: dict) -> dict:
lo, hi = box.GetMin(), box.GetMax()
ext = [round(hi[i] - lo[i], 4) for i in range(3)]
corners = [[round(x, 4), round(y, 4), round(z, 4)] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]
half_diag = math.hypot(ext[0], ext[1]) / 2
ground = {"center": [0.0, 0.0, round(lo[2], 4), 1.0, 0.0, 0.0, 0.0], "radius": round(half_diag, 4)}
# lying on its side: turned +90 deg about x, so the asset's -y face is down
side = {"center": [0.0, round(lo[1], 4), 0.0, 1.0, 0.0, 0.0, 0.0], "radius": round(math.hypot(ext[0], ext[2]) / 2, 4)}
s = math.sqrt(0.5)
return {
"uuid": str(uuid.uuid5(uuid.NAMESPACE_URL, record["source"])),
"physics": {"mass": mass, "friction": friction, "size": ext},
"geometry": {
"aligned_bbox": {"vertices": corners, "extents": ext},
"oriented_bbox": {"vertices": corners, "extents": ext},
"bbox": ext, "center": [0.0, 0.0, 0.0], "radius": round(math.sqrt(sum(e * e for e in ext)) / 2, 4),
},
"active": {"place": {
"up": {"orientation": [1.0, 0.0, 0.0, 0.0], "projection_circle": ground, "contact_circle": ground},
"side": {"orientation": [s, s, 0.0, 0.0], "projection_circle": side, "contact_circle": side},
}},
"robolab": record,
}
def main() -> None:
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--robolab", type=Path, default=Path("/data1/viet/robolab"))
p.add_argument("--out", type=Path, default=Path(os.environ.get("ROBOLAB_OBJECTS", "/data1/viet/robolab_objects")))
args = p.parse_args()
catalog = json.loads((args.robolab / "assets/objects/object_catalog.json").read_text())
manifest = {}
for entry in catalog:
dataset = entry["dataset"]
if dataset not in LICENCES:
continue
usd = args.robolab / entry["usd_path"]
name = usd.stem # unique (the catalog's "name" is not: ycb has bowl.usd and bowl2.usd both named "bowl")
set_root = args.robolab / "assets/objects" / dataset
source = copy_sources(usd, set_root, args.out / "RoboLabSrc" / dataset)
size = max(entry["dims"])
scale = SCALE.get(name, min(1.0, MAX_SIZE / size))
category = f"rl_{name}"
record = {"name": entry["name"], "class": entry["class"], "description": entry["description"], "dataset": dataset,
"licence": LICENCES[dataset], "source": entry["usd_path"], "scale": round(scale, 4)}
box = wrapper(args.out / "Rigid" / category / "00000/object.usd", source, scale, rigid=True)
record["floor"] = round(floor_height(args.out / "Rigid" / category / "00000/object.usd", box), 4)
wrapper(args.out / "Geometry" / category / "00000/object.usd", source, scale, rigid=False)
ext = [box.GetMax()[i] - box.GetMin()[i] for i in range(3)]
mass = entry.get("mass") or EFFECTIVE_DENSITY * ext[0] * ext[1] * ext[2]
mass = round(min(max(mass, 0.02), 0.5), 3)
friction = round(entry.get("static_friction") or 1.0, 3)
meta = metadata(box, mass, friction, record)
desc = {"uuid": meta["uuid"], "description": [entry["description"]], "caption": {"name": [entry["name"].replace("_", " ")]}}
for section in ("Rigid", "Geometry"):
folder = args.out / section / category / "00000"
(folder / "metadata.json").write_text(json.dumps(meta, indent=1))
(folder / "description.json").write_text(json.dumps(desc, indent=1))
manifest[category] = record | {"size": [round(e, 3) for e in ext], "mass": mass, "friction": friction}
print(f"{category:34} {dataset:5} scale {scale:.3f} size {[round(e, 3) for e in ext]} mass {mass}")
(HERE / "objects.json").write_text(json.dumps(manifest, indent=1) + "\n")
print(f"{len(manifest)} objects -> {args.out}")
if __name__ == "__main__":
main()