Placement_Assets / scripts /run_convex_decomposition.py
yuchi233's picture
Upload scripts/run_convex_decomposition.py with huggingface_hub
3886356 verified
Raw
History Blame Contribute Delete
23.9 kB
#!/usr/bin/env python3
"""
Run convex decomposition for meshes in one raw asset and generate MuJoCo include files.
Outputs follow the repository derived-asset convention:
assets/<source>/derived/convex_decompositions/<category>/<asset_id>_<variant>/
The generated MJCF files are intentionally split:
- mjcf/convex_assets_include.xml: include at MJCF root/top level.
- mjcf/convex_geoms_include.xml: include inside the body that should receive collision geoms.
- mjcf/convex_collision_include.xml: standalone convenience include with a wrapper body.
"""
import argparse
import csv
import hashlib
import inspect
import json
import re
import sys
import xml.etree.ElementTree as ET
from datetime import date
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
MANIFEST = ROOT / "manifest" / "assets.jsonl"
def parse_simple_yaml(path: Path):
data = {}
current_key = None
for raw in path.read_text().splitlines():
if not raw.strip() or raw.lstrip().startswith("#"):
continue
if raw.startswith(" - ") and current_key:
data.setdefault(current_key, []).append(raw.strip()[2:].strip())
continue
if ":" in raw and not raw.startswith(" "):
key, value = raw.split(":", 1)
key = key.strip()
value = value.strip()
current_key = key
if value == "":
data[key] = []
elif value in {"[]", "{}"}:
data[key] = [] if value == "[]" else {}
else:
data[key] = value.strip('"').strip("'")
return data
def yaml_scalar(value):
if isinstance(value, bool):
return "true" if value else "false"
if value is None:
return "null"
if isinstance(value, (int, float)):
return str(value)
text = str(value)
if text == "":
return '""'
if any(ch in text for ch in [":", "#", "{", "}", "[", "]", ",", '"', "'", "\n"]) or text.startswith(" ") or text.endswith(" "):
return json.dumps(text, ensure_ascii=False)
return text
def dump_yaml(mapping, indent=0):
lines = []
pad = " " * indent
for key, value in mapping.items():
if isinstance(value, dict):
lines.append(f"{pad}{key}:")
lines.extend(dump_yaml(value, indent + 2))
elif isinstance(value, list):
if not value:
lines.append(f"{pad}{key}: []")
else:
lines.append(f"{pad}{key}:")
for item in value:
if isinstance(item, dict):
lines.append(f"{pad} -")
lines.extend(dump_yaml(item, indent + 4))
else:
lines.append(f"{pad} - {yaml_scalar(item)}")
else:
lines.append(f"{pad}{key}: {yaml_scalar(value)}")
return lines
def sha256_file(path: Path):
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def rounded_list(values, digits=8):
return [round(float(v), digits) for v in values]
def mesh_stats(mesh):
extents = rounded_list(mesh.bounding_box.extents)
center = rounded_list(mesh.bounding_box.centroid)
bbox_volume = float(extents[0] * extents[1] * extents[2])
volume = None
try:
volume = float(mesh.volume)
except Exception:
volume = None
area = None
try:
area = float(mesh.area)
except Exception:
area = None
return {
"bbox_extents": extents,
"bbox_center": center,
"bbox_volume": round(bbox_volume, 12),
"mesh_volume": round(volume, 12) if volume is not None else None,
"surface_area": round(area, 12) if area is not None else None,
"num_vertices": int(len(mesh.vertices)),
"num_faces": int(len(mesh.faces)),
}
def safe_name(text: str):
text = Path(text).stem if "/" in text else text
text = re.sub(r"[^0-9A-Za-z_]+", "_", text)
text = re.sub(r"_+", "_", text).strip("_")
if not text:
text = "mesh"
if text[0].isdigit():
text = f"m_{text}"
return text
def rel_to_root(path: Path):
return path.resolve().relative_to(ROOT).as_posix()
def require_raw_asset(raw_asset_dir: Path):
raw_asset_dir = raw_asset_dir.resolve()
try:
raw_rel = raw_asset_dir.relative_to(ROOT / "assets")
except ValueError as exc:
raise SystemExit("raw_asset_dir must be under this repository's assets/ directory") from exc
parts = raw_rel.parts
if len(parts) < 5 or parts[1] != "raw":
raise SystemExit("raw_asset_dir must be under assets/<source>/raw/<asset_type>/<category>/<asset_id>")
return raw_asset_dir, parts[0], parts[2], parts[3], parts[4]
def discover_meshes(raw_asset_dir: Path, patterns):
meshes = []
for pattern in patterns:
meshes.extend(raw_asset_dir.glob(pattern))
meshes = sorted({p.resolve() for p in meshes if p.is_file()})
return meshes
def resolve_mesh_args(raw_asset_dir: Path, mesh_args, patterns):
if mesh_args:
meshes = []
for item in mesh_args:
path = Path(item).expanduser()
if not path.is_absolute():
path = raw_asset_dir / path
if not path.exists():
raise SystemExit(f"mesh does not exist: {path}")
meshes.append(path.resolve())
return meshes
meshes = discover_meshes(raw_asset_dir, patterns)
if not meshes:
raise SystemExit(
"no mesh found. Pass --mesh relative/or/absolute/path.obj, "
"or adjust --mesh-glob. Default globs search visuals/ and meshes/."
)
return meshes
def import_deps():
try:
import coacd # type: ignore
import trimesh # type: ignore
except ModuleNotFoundError as exc:
missing = exc.name
raise SystemExit(
f"missing Python dependency: {missing}\n"
"Install before running real decomposition, for example:\n"
" pip install trimesh coacd\n"
) from exc
return coacd, trimesh
def coacd_version(coacd):
return getattr(coacd, "__version__", "unknown")
def filter_coacd_params(coacd, params):
try:
sig = inspect.signature(coacd.run_coacd)
except (TypeError, ValueError):
return {k: v for k, v in params.items() if v is not None}
valid = set(sig.parameters)
if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()):
return {k: v for k, v in params.items() if v is not None}
return {k: v for k, v in params.items() if v is not None and k in valid}
def run_coacd_for_mesh(mesh_path: Path, output_dir: Path, params):
coacd, trimesh = import_deps()
# Convex decomposition only needs geometry. Skipping materials avoids a
# Pillow dependency for textured OBJ files from sources such as RoboCasa.
loaded = trimesh.load(mesh_path, skip_materials=True)
if isinstance(loaded, trimesh.Scene):
meshes = []
for node_name in loaded.graph.nodes_geometry:
transform, geometry_name = loaded.graph[node_name]
geom = loaded.geometry[geometry_name].copy()
geom.visual = trimesh.visual.ColorVisuals(geom)
geom.apply_transform(transform)
meshes.append(geom)
if not meshes:
raise RuntimeError(f"no mesh geometry in scene: {mesh_path}")
mesh = trimesh.util.concatenate(meshes)
else:
mesh = loaded
mesh.visual = trimesh.visual.ColorVisuals(mesh)
if mesh.is_empty:
raise RuntimeError(f"empty mesh: {mesh_path}")
coacd_mesh = coacd.Mesh(mesh.vertices, mesh.faces)
kwargs = filter_coacd_params(coacd, params)
parts = coacd.run_coacd(coacd_mesh, **kwargs)
output_dir.mkdir(parents=True, exist_ok=True)
outputs = []
for i, part in enumerate(parts):
vertices, faces = part
part_mesh = trimesh.Trimesh(vertices, faces)
part_path = output_dir / f"part_{i:03d}.obj"
part_mesh.export(part_path)
outputs.append((part_path, mesh_stats(part_mesh)))
return outputs, coacd_version(coacd), kwargs
def xml_escape(value):
return (
str(value)
.replace("&", "&amp;")
.replace('"', "&quot;")
.replace("<", "&lt;")
.replace(">", "&gt;")
)
def write_xml_files(mjcf_dir: Path, asset_id: str, part_records, class_name: str, rgba: str, group: str, contype: str, conaffinity: str):
mjcf_dir.mkdir(parents=True, exist_ok=True)
asset_lines = [
"<!-- Include this file at MJCF root/top level so mesh assets are defined. -->",
"<mujocoinclude>",
" <asset>",
]
for rec in part_records:
asset_lines.append(f' <mesh name="{xml_escape(rec["mesh_name"])}" file="{xml_escape(rec["file_from_mjcf"])}"/>')
asset_lines.extend([" </asset>", "</mujocoinclude>", ""])
(mjcf_dir / "convex_assets_include.xml").write_text("\n".join(asset_lines))
geom_attrs = []
if class_name:
geom_attrs.append(f'class="{xml_escape(class_name)}"')
if rgba:
geom_attrs.append(f'rgba="{xml_escape(rgba)}"')
if group:
geom_attrs.append(f'group="{xml_escape(group)}"')
if contype:
geom_attrs.append(f'contype="{xml_escape(contype)}"')
if conaffinity:
geom_attrs.append(f'conaffinity="{xml_escape(conaffinity)}"')
common = " ".join(geom_attrs)
common = f" {common}" if common else ""
geom_lines = [
"<!-- Include this file inside the target body to add convex collision geoms. -->",
"<mujocoinclude>",
]
for rec in part_records:
geom_lines.append(f' <geom type="mesh" mesh="{xml_escape(rec["mesh_name"])}"{common}/>')
geom_lines.extend(["</mujocoinclude>", ""])
(mjcf_dir / "convex_geoms_include.xml").write_text("\n".join(geom_lines))
body_name = safe_name(f"{asset_id}_convex_collision")
combo_lines = [
"<!-- Convenience include for preview or standalone loading.",
" For integration into an existing object, include convex_assets_include.xml at root",
" and convex_geoms_include.xml inside the target body instead. -->",
"<mujocoinclude>",
' <include file="convex_assets_include.xml"/>',
" <worldbody>",
f' <body name="{xml_escape(body_name)}">',
' <include file="convex_geoms_include.xml"/>',
" </body>",
" </worldbody>",
"</mujocoinclude>",
"",
]
(mjcf_dir / "convex_collision_include.xml").write_text("\n".join(combo_lines))
def append_manifest(row):
MANIFEST.parent.mkdir(parents=True, exist_ok=True)
existing = []
if MANIFEST.exists():
existing = [line for line in MANIFEST.read_text().splitlines() if line.strip()]
path = row["path"]
for line in existing:
try:
old = json.loads(line)
except json.JSONDecodeError:
continue
if old.get("path") == path:
raise SystemExit(f"manifest already contains path: {path}")
with MANIFEST.open("a") as f:
f.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
def parse_args():
parser = argparse.ArgumentParser(
description="Run CoACD convex decomposition and generate MuJoCo include files."
)
parser.add_argument("raw_asset_dir", help="Raw asset directory under assets/<source>/raw/...")
parser.add_argument(
"--mesh",
action="append",
default=[],
help="Mesh path to decompose. Can be relative to raw_asset_dir or absolute. Repeatable.",
)
parser.add_argument(
"--mesh-glob",
action="append",
default=["visuals/*.obj", "visuals/*.stl", "meshes/*.obj", "meshes/*.stl"],
help="Glob relative to raw_asset_dir used when --mesh is omitted. Repeatable.",
)
parser.add_argument("--variant", default="coacd_v1", help="Derived asset suffix.")
parser.add_argument("--overwrite", action="store_true", help="Allow writing into an existing derived directory.")
parser.add_argument("--register-manifest", action="store_true", help="Append the derived asset to manifest/assets.jsonl.")
parser.add_argument("--class-name", default="convex_collision", help="MJCF geom class name. Empty string disables class attr.")
parser.add_argument("--rgba", default="0.8 0.2 0.2 0.35", help="MJCF geom rgba.")
parser.add_argument("--group", default="0", help="MJCF geom group. Empty string disables group attr.")
parser.add_argument("--contype", default="", help="MJCF geom contype. Empty string uses MuJoCo default.")
parser.add_argument("--conaffinity", default="", help="MJCF geom conaffinity. Empty string uses MuJoCo default.")
parser.add_argument("--threshold", type=float, default=0.05, help="CoACD concavity threshold.")
parser.add_argument("--max-convex-hull", type=int, default=-1, help="CoACD max convex hull count; -1 means CoACD default/unlimited.")
parser.add_argument("--preprocess-mode", default="auto", choices=["auto", "on", "off"], help="CoACD preprocess mode.")
parser.add_argument("--preprocess-resolution", type=int, default=50, help="CoACD preprocess resolution.")
parser.add_argument("--resolution", type=int, default=2000, help="CoACD sampling/resolution parameter.")
parser.add_argument("--mcts-nodes", type=int, default=20, help="CoACD MCTS node count.")
parser.add_argument("--mcts-iterations", type=int, default=150, help="CoACD MCTS iteration count.")
parser.add_argument("--mcts-max-depth", type=int, default=3, help="CoACD MCTS max depth. Higher values can create finer splits.")
parser.add_argument("--pca", action="store_true", help="Enable CoACD PCA mode.")
parser.add_argument("--no-merge", action="store_true", help="Disable CoACD merge step. This can keep more/smaller convex parts.")
parser.add_argument("--decimate", action="store_true", help="Enable CoACD decimation.")
parser.add_argument("--max-ch-vertex", type=int, default=256, help="Maximum vertices per convex hull.")
parser.add_argument("--extrude", action="store_true", help="Enable CoACD extrusion.")
parser.add_argument("--extrude-margin", type=float, default=0.01, help="CoACD extrusion margin.")
parser.add_argument("--apx-mode", default="ch", choices=["ch", "box"], help="CoACD approximation mode.")
parser.add_argument("--real-metric", action="store_true", help="Enable CoACD real_metric option if supported.")
parser.add_argument("--seed", type=int, default=0, help="CoACD random seed if supported.")
return parser.parse_args()
def main():
args = parse_args()
raw_asset_dir, source, _raw_asset_type, category, source_asset_id = require_raw_asset(Path(args.raw_asset_dir))
raw_meta_path = raw_asset_dir / "metadata.yaml"
raw_meta = parse_simple_yaml(raw_meta_path) if raw_meta_path.exists() else {}
meshes = resolve_mesh_args(raw_asset_dir, args.mesh, args.mesh_glob)
derived_asset_id = f"{source_asset_id}_{args.variant}"
derived_dir = ROOT / "assets" / source / "derived" / "convex_decompositions" / category / derived_asset_id
if derived_dir.exists() and not args.overwrite:
raise SystemExit(f"destination already exists: {derived_dir}. Use --overwrite only if you intend to replace files inside it.")
work_dir = derived_dir
if not args.overwrite:
work_dir = derived_dir.parent / f".{derived_dir.name}.tmp"
if work_dir.exists():
raise SystemExit(f"temporary output already exists from a previous failed run: {work_dir}")
# Fail before creating derived files if the real decomposition backend is unavailable.
import_deps()
(work_dir / "meshes").mkdir(parents=True, exist_ok=True)
(work_dir / "mjcf").mkdir(parents=True, exist_ok=True)
(work_dir / "logs").mkdir(parents=True, exist_ok=True)
coacd_params = {
"threshold": args.threshold,
"max_convex_hull": None if args.max_convex_hull < 0 else args.max_convex_hull,
"preprocess_mode": args.preprocess_mode,
"preprocess_resolution": args.preprocess_resolution,
"resolution": args.resolution,
"mcts_nodes": args.mcts_nodes,
"mcts_iterations": args.mcts_iterations,
"mcts_max_depth": args.mcts_max_depth,
"pca": args.pca,
"merge": not args.no_merge,
"decimate": args.decimate,
"max_ch_vertex": args.max_ch_vertex,
"extrude": args.extrude,
"extrude_margin": args.extrude_margin,
"apx_mode": args.apx_mode,
"seed": args.seed,
"real_metric": args.real_metric,
}
inputs_log = []
outputs_log = []
part_records = []
actual_tool_version = "unknown"
actual_params = {}
for mesh_path in meshes:
mesh_stem = safe_name(mesh_path.stem)
out_dir = work_dir / "meshes" / mesh_stem
part_outputs, actual_tool_version, actual_params = run_coacd_for_mesh(mesh_path, out_dir, coacd_params)
inputs_log.append({
"path": rel_to_root(mesh_path),
"sha256": sha256_file(mesh_path),
})
for part_path, part_stats in part_outputs:
part_rel = part_path.relative_to(work_dir).as_posix()
part_index = int(part_path.stem.split("_")[-1])
mesh_name = safe_name(f"{source}_{source_asset_id}_{mesh_stem}_convex_{part_index:03d}")
part_records.append({
"source_mesh": rel_to_root(mesh_path),
"path": part_rel,
"sha256": sha256_file(part_path),
"mesh_name": mesh_name,
"file_from_mjcf": f"../{part_rel}",
**part_stats,
})
outputs_log.append({
"path": part_rel,
"sha256": sha256_file(part_path),
"mesh_name": mesh_name,
**part_stats,
})
write_xml_files(
work_dir / "mjcf",
source_asset_id,
part_records,
args.class_name,
args.rgba,
args.group,
args.contype,
args.conaffinity,
)
license_name = raw_meta.get("license", "unknown")
origin_url = raw_meta.get("origin_url", "")
global_asset_id = f"{source}.convex_decompositions.{category}.{derived_asset_id}"
metadata = {
"asset_id": global_asset_id,
"source": source,
"source_asset_id": source_asset_id,
"asset_type": "convex_decompositions",
"category": category,
"format": "obj_mjcf_include",
"entry_file": "mjcf/convex_collision_include.xml",
"license": license_name,
"origin_url": origin_url,
"path": rel_to_root(derived_dir),
"storage_mode": "derived",
"derived_from": [rel_to_root(raw_asset_dir)],
"derivation_method": "convex_decomposition",
"decomposition_tool": "coacd",
"decomposition_version": actual_tool_version,
"decomposition_params_file": "logs/decomposition.json",
"validation_status": "generated",
"tags": [source, "convex_decomposition", "collision", "mujoco"],
}
if "readiness_level" in raw_meta:
metadata["readiness_level"] = raw_meta["readiness_level"]
if "source_commit" in raw_meta:
metadata["source_commit"] = raw_meta["source_commit"]
(work_dir / "metadata.yaml").write_text("\n".join(dump_yaml(metadata)) + "\n")
source_refs = {
"raw_asset": rel_to_root(raw_asset_dir),
"raw_entry_file": rel_to_root(raw_asset_dir / raw_meta.get("entry_file", "model.xml"))
if (raw_asset_dir / raw_meta.get("entry_file", "model.xml")).exists()
else "",
"raw_meshes": [rel_to_root(p) for p in meshes],
}
(work_dir / "source_refs.yaml").write_text("\n".join(dump_yaml(source_refs)) + "\n")
log = {
"tool": "coacd",
"tool_version": actual_tool_version,
"created_at": str(date.today()),
"raw_asset": rel_to_root(raw_asset_dir),
"derived_asset": rel_to_root(derived_dir),
"params": actual_params,
"inputs": inputs_log,
"outputs": outputs_log,
"mjcf": {
"root_level_asset_include": "mjcf/convex_assets_include.xml",
"body_level_geom_include": "mjcf/convex_geoms_include.xml",
"standalone_include": "mjcf/convex_collision_include.xml",
},
}
(work_dir / "logs" / "decomposition.json").write_text(json.dumps(log, indent=2, ensure_ascii=False) + "\n")
summary_path = work_dir / "logs" / "parts_summary.csv"
with summary_path.open("w", newline="") as f:
writer = csv.DictWriter(
f,
fieldnames=[
"source_mesh",
"part_path",
"mesh_name",
"bbox_x",
"bbox_y",
"bbox_z",
"bbox_center_x",
"bbox_center_y",
"bbox_center_z",
"bbox_volume",
"mesh_volume",
"surface_area",
"num_vertices",
"num_faces",
"sha256",
],
)
writer.writeheader()
for rec in part_records:
bbox = rec["bbox_extents"]
center = rec["bbox_center"]
writer.writerow({
"source_mesh": rec["source_mesh"],
"part_path": rec["path"],
"mesh_name": rec["mesh_name"],
"bbox_x": bbox[0],
"bbox_y": bbox[1],
"bbox_z": bbox[2],
"bbox_center_x": center[0],
"bbox_center_y": center[1],
"bbox_center_z": center[2],
"bbox_volume": rec["bbox_volume"],
"mesh_volume": rec["mesh_volume"],
"surface_area": rec["surface_area"],
"num_vertices": rec["num_vertices"],
"num_faces": rec["num_faces"],
"sha256": rec["sha256"],
})
readme = f"""# Convex decomposition: {source_asset_id}
Source asset:
```text
{rel_to_root(raw_asset_dir)}
```
Generated collision meshes:
```text
{rel_to_root(derived_dir / "meshes")}
```
MuJoCo integration:
1. Include `mjcf/convex_assets_include.xml` at MJCF root/top level.
2. Include `mjcf/convex_geoms_include.xml` inside the body that should receive these collision geoms.
3. Use `mjcf/convex_collision_include.xml` only for quick standalone preview/wrapper-body loading.
Do not edit the raw source asset in place.
"""
(work_dir / "README.md").write_text(readme)
if work_dir != derived_dir:
work_dir.rename(derived_dir)
if args.register_manifest:
row = {
"asset_id": global_asset_id,
"asset_type": "convex_decompositions",
"category": category,
"entry_file": "mjcf/convex_collision_include.xml",
"format": "obj_mjcf_include",
"license": license_name,
"origin_url": origin_url,
"path": rel_to_root(derived_dir),
"source": source,
"source_asset_id": source_asset_id,
"tags": [source, "convex_decomposition", "collision", "mujoco"],
}
append_manifest(row)
print(rel_to_root(derived_dir))
print(f"decomposed_meshes={len(meshes)} convex_parts={len(part_records)}")
if not args.register_manifest:
print("manifest_status=not_registered; rerun with --register-manifest when this derived asset should be indexed")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except ET.ParseError as exc:
print(f"XML error: {exc}", file=sys.stderr)
raise