yuchi233 commited on
Commit
77db31c
·
verified ·
1 Parent(s): dd238b9

Upload scripts/run_convex_decomposition.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/run_convex_decomposition.py +497 -0
scripts/run_convex_decomposition.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Run convex decomposition for meshes in one raw asset and generate MuJoCo include files.
4
+
5
+ Outputs follow the repository derived-asset convention:
6
+
7
+ assets/<source>/derived/convex_decompositions/<category>/<asset_id>_<variant>/
8
+
9
+ The generated MJCF files are intentionally split:
10
+
11
+ - mjcf/convex_assets_include.xml: include at MJCF root/top level.
12
+ - mjcf/convex_geoms_include.xml: include inside the body that should receive collision geoms.
13
+ - mjcf/convex_collision_include.xml: standalone convenience include with a wrapper body.
14
+ """
15
+
16
+ import argparse
17
+ import hashlib
18
+ import inspect
19
+ import json
20
+ import re
21
+ import sys
22
+ import xml.etree.ElementTree as ET
23
+ from datetime import date
24
+ from pathlib import Path
25
+
26
+
27
+ ROOT = Path(__file__).resolve().parents[1]
28
+ MANIFEST = ROOT / "manifest" / "assets.jsonl"
29
+
30
+
31
+ def parse_simple_yaml(path: Path):
32
+ data = {}
33
+ current_key = None
34
+ for raw in path.read_text().splitlines():
35
+ if not raw.strip() or raw.lstrip().startswith("#"):
36
+ continue
37
+ if raw.startswith(" - ") and current_key:
38
+ data.setdefault(current_key, []).append(raw.strip()[2:].strip())
39
+ continue
40
+ if ":" in raw and not raw.startswith(" "):
41
+ key, value = raw.split(":", 1)
42
+ key = key.strip()
43
+ value = value.strip()
44
+ current_key = key
45
+ if value == "":
46
+ data[key] = []
47
+ elif value in {"[]", "{}"}:
48
+ data[key] = [] if value == "[]" else {}
49
+ else:
50
+ data[key] = value.strip('"').strip("'")
51
+ return data
52
+
53
+
54
+ def yaml_scalar(value):
55
+ if isinstance(value, bool):
56
+ return "true" if value else "false"
57
+ if value is None:
58
+ return "null"
59
+ if isinstance(value, (int, float)):
60
+ return str(value)
61
+ text = str(value)
62
+ if text == "":
63
+ return '""'
64
+ if any(ch in text for ch in [":", "#", "{", "}", "[", "]", ",", '"', "'", "\n"]) or text.startswith(" ") or text.endswith(" "):
65
+ return json.dumps(text, ensure_ascii=False)
66
+ return text
67
+
68
+
69
+ def dump_yaml(mapping, indent=0):
70
+ lines = []
71
+ pad = " " * indent
72
+ for key, value in mapping.items():
73
+ if isinstance(value, dict):
74
+ lines.append(f"{pad}{key}:")
75
+ lines.extend(dump_yaml(value, indent + 2))
76
+ elif isinstance(value, list):
77
+ if not value:
78
+ lines.append(f"{pad}{key}: []")
79
+ else:
80
+ lines.append(f"{pad}{key}:")
81
+ for item in value:
82
+ if isinstance(item, dict):
83
+ lines.append(f"{pad} -")
84
+ lines.extend(dump_yaml(item, indent + 4))
85
+ else:
86
+ lines.append(f"{pad} - {yaml_scalar(item)}")
87
+ else:
88
+ lines.append(f"{pad}{key}: {yaml_scalar(value)}")
89
+ return lines
90
+
91
+
92
+ def sha256_file(path: Path):
93
+ h = hashlib.sha256()
94
+ with path.open("rb") as f:
95
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
96
+ h.update(chunk)
97
+ return h.hexdigest()
98
+
99
+
100
+ def safe_name(text: str):
101
+ text = Path(text).stem if "/" in text else text
102
+ text = re.sub(r"[^0-9A-Za-z_]+", "_", text)
103
+ text = re.sub(r"_+", "_", text).strip("_")
104
+ if not text:
105
+ text = "mesh"
106
+ if text[0].isdigit():
107
+ text = f"m_{text}"
108
+ return text
109
+
110
+
111
+ def rel_to_root(path: Path):
112
+ return path.resolve().relative_to(ROOT).as_posix()
113
+
114
+
115
+ def require_raw_asset(raw_asset_dir: Path):
116
+ raw_asset_dir = raw_asset_dir.resolve()
117
+ try:
118
+ raw_rel = raw_asset_dir.relative_to(ROOT / "assets")
119
+ except ValueError as exc:
120
+ raise SystemExit("raw_asset_dir must be under this repository's assets/ directory") from exc
121
+
122
+ parts = raw_rel.parts
123
+ if len(parts) < 5 or parts[1] != "raw":
124
+ raise SystemExit("raw_asset_dir must be under assets/<source>/raw/<asset_type>/<category>/<asset_id>")
125
+ return raw_asset_dir, parts[0], parts[2], parts[3], parts[4]
126
+
127
+
128
+ def discover_meshes(raw_asset_dir: Path, patterns):
129
+ meshes = []
130
+ for pattern in patterns:
131
+ meshes.extend(raw_asset_dir.glob(pattern))
132
+ meshes = sorted({p.resolve() for p in meshes if p.is_file()})
133
+ return meshes
134
+
135
+
136
+ def resolve_mesh_args(raw_asset_dir: Path, mesh_args, patterns):
137
+ if mesh_args:
138
+ meshes = []
139
+ for item in mesh_args:
140
+ path = Path(item).expanduser()
141
+ if not path.is_absolute():
142
+ path = raw_asset_dir / path
143
+ if not path.exists():
144
+ raise SystemExit(f"mesh does not exist: {path}")
145
+ meshes.append(path.resolve())
146
+ return meshes
147
+ meshes = discover_meshes(raw_asset_dir, patterns)
148
+ if not meshes:
149
+ raise SystemExit(
150
+ "no mesh found. Pass --mesh relative/or/absolute/path.obj, "
151
+ "or adjust --mesh-glob. Default globs search visuals/ and meshes/."
152
+ )
153
+ return meshes
154
+
155
+
156
+ def import_deps():
157
+ try:
158
+ import coacd # type: ignore
159
+ import trimesh # type: ignore
160
+ except ModuleNotFoundError as exc:
161
+ missing = exc.name
162
+ raise SystemExit(
163
+ f"missing Python dependency: {missing}\n"
164
+ "Install before running real decomposition, for example:\n"
165
+ " pip install trimesh coacd\n"
166
+ ) from exc
167
+ return coacd, trimesh
168
+
169
+
170
+ def coacd_version(coacd):
171
+ return getattr(coacd, "__version__", "unknown")
172
+
173
+
174
+ def filter_coacd_params(coacd, params):
175
+ try:
176
+ sig = inspect.signature(coacd.run_coacd)
177
+ except (TypeError, ValueError):
178
+ return {k: v for k, v in params.items() if v is not None}
179
+ valid = set(sig.parameters)
180
+ if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()):
181
+ return {k: v for k, v in params.items() if v is not None}
182
+ return {k: v for k, v in params.items() if v is not None and k in valid}
183
+
184
+
185
+ def run_coacd_for_mesh(mesh_path: Path, output_dir: Path, params):
186
+ coacd, trimesh = import_deps()
187
+
188
+ mesh = trimesh.load(mesh_path, force="mesh")
189
+ if mesh.is_empty:
190
+ raise RuntimeError(f"empty mesh: {mesh_path}")
191
+
192
+ coacd_mesh = coacd.Mesh(mesh.vertices, mesh.faces)
193
+ kwargs = filter_coacd_params(coacd, params)
194
+ parts = coacd.run_coacd(coacd_mesh, **kwargs)
195
+
196
+ output_dir.mkdir(parents=True, exist_ok=True)
197
+ outputs = []
198
+ for i, part in enumerate(parts):
199
+ vertices, faces = part
200
+ part_mesh = trimesh.Trimesh(vertices, faces)
201
+ part_path = output_dir / f"part_{i:03d}.obj"
202
+ part_mesh.export(part_path)
203
+ outputs.append(part_path)
204
+
205
+ return outputs, coacd_version(coacd), kwargs
206
+
207
+
208
+ def xml_escape(value):
209
+ return (
210
+ str(value)
211
+ .replace("&", "&amp;")
212
+ .replace('"', "&quot;")
213
+ .replace("<", "&lt;")
214
+ .replace(">", "&gt;")
215
+ )
216
+
217
+
218
+ def write_xml_files(mjcf_dir: Path, asset_id: str, part_records, class_name: str, rgba: str, group: str, contype: str, conaffinity: str):
219
+ mjcf_dir.mkdir(parents=True, exist_ok=True)
220
+
221
+ asset_lines = [
222
+ "<!-- Include this file at MJCF root/top level so mesh assets are defined. -->",
223
+ "<mujocoinclude>",
224
+ " <asset>",
225
+ ]
226
+ for rec in part_records:
227
+ asset_lines.append(f' <mesh name="{xml_escape(rec["mesh_name"])}" file="{xml_escape(rec["file_from_mjcf"])}"/>')
228
+ asset_lines.extend([" </asset>", "</mujocoinclude>", ""])
229
+ (mjcf_dir / "convex_assets_include.xml").write_text("\n".join(asset_lines))
230
+
231
+ geom_attrs = []
232
+ if class_name:
233
+ geom_attrs.append(f'class="{xml_escape(class_name)}"')
234
+ if rgba:
235
+ geom_attrs.append(f'rgba="{xml_escape(rgba)}"')
236
+ if group:
237
+ geom_attrs.append(f'group="{xml_escape(group)}"')
238
+ if contype:
239
+ geom_attrs.append(f'contype="{xml_escape(contype)}"')
240
+ if conaffinity:
241
+ geom_attrs.append(f'conaffinity="{xml_escape(conaffinity)}"')
242
+ common = " ".join(geom_attrs)
243
+ common = f" {common}" if common else ""
244
+
245
+ geom_lines = [
246
+ "<!-- Include this file inside the target body to add convex collision geoms. -->",
247
+ "<mujocoinclude>",
248
+ ]
249
+ for rec in part_records:
250
+ geom_lines.append(f' <geom type="mesh" mesh="{xml_escape(rec["mesh_name"])}"{common}/>')
251
+ geom_lines.extend(["</mujocoinclude>", ""])
252
+ (mjcf_dir / "convex_geoms_include.xml").write_text("\n".join(geom_lines))
253
+
254
+ body_name = safe_name(f"{asset_id}_convex_collision")
255
+ combo_lines = [
256
+ "<!-- Convenience include for preview or standalone loading.",
257
+ " For integration into an existing object, include convex_assets_include.xml at root",
258
+ " and convex_geoms_include.xml inside the target body instead. -->",
259
+ "<mujocoinclude>",
260
+ ' <include file="convex_assets_include.xml"/>',
261
+ " <worldbody>",
262
+ f' <body name="{xml_escape(body_name)}">',
263
+ ' <include file="convex_geoms_include.xml"/>',
264
+ " </body>",
265
+ " </worldbody>",
266
+ "</mujocoinclude>",
267
+ "",
268
+ ]
269
+ (mjcf_dir / "convex_collision_include.xml").write_text("\n".join(combo_lines))
270
+
271
+
272
+ def append_manifest(row):
273
+ MANIFEST.parent.mkdir(parents=True, exist_ok=True)
274
+ existing = []
275
+ if MANIFEST.exists():
276
+ existing = [line for line in MANIFEST.read_text().splitlines() if line.strip()]
277
+ path = row["path"]
278
+ for line in existing:
279
+ try:
280
+ old = json.loads(line)
281
+ except json.JSONDecodeError:
282
+ continue
283
+ if old.get("path") == path:
284
+ raise SystemExit(f"manifest already contains path: {path}")
285
+ with MANIFEST.open("a") as f:
286
+ f.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
287
+
288
+
289
+ def parse_args():
290
+ parser = argparse.ArgumentParser(
291
+ description="Run CoACD convex decomposition and generate MuJoCo include files."
292
+ )
293
+ parser.add_argument("raw_asset_dir", help="Raw asset directory under assets/<source>/raw/...")
294
+ parser.add_argument(
295
+ "--mesh",
296
+ action="append",
297
+ default=[],
298
+ help="Mesh path to decompose. Can be relative to raw_asset_dir or absolute. Repeatable.",
299
+ )
300
+ parser.add_argument(
301
+ "--mesh-glob",
302
+ action="append",
303
+ default=["visuals/*.obj", "visuals/*.stl", "meshes/*.obj", "meshes/*.stl"],
304
+ help="Glob relative to raw_asset_dir used when --mesh is omitted. Repeatable.",
305
+ )
306
+ parser.add_argument("--variant", default="coacd_v1", help="Derived asset suffix.")
307
+ parser.add_argument("--overwrite", action="store_true", help="Allow writing into an existing derived directory.")
308
+ parser.add_argument("--register-manifest", action="store_true", help="Append the derived asset to manifest/assets.jsonl.")
309
+ parser.add_argument("--class-name", default="convex_collision", help="MJCF geom class name. Empty string disables class attr.")
310
+ parser.add_argument("--rgba", default="0.8 0.2 0.2 0.35", help="MJCF geom rgba.")
311
+ parser.add_argument("--group", default="0", help="MJCF geom group. Empty string disables group attr.")
312
+ parser.add_argument("--contype", default="", help="MJCF geom contype. Empty string uses MuJoCo default.")
313
+ parser.add_argument("--conaffinity", default="", help="MJCF geom conaffinity. Empty string uses MuJoCo default.")
314
+ parser.add_argument("--threshold", type=float, default=0.05, help="CoACD concavity threshold.")
315
+ parser.add_argument("--max-convex-hull", type=int, default=-1, help="CoACD max convex hull count; -1 means CoACD default/unlimited.")
316
+ parser.add_argument("--preprocess-resolution", type=int, default=50, help="CoACD preprocess resolution.")
317
+ parser.add_argument("--seed", type=int, default=0, help="CoACD random seed if supported.")
318
+ return parser.parse_args()
319
+
320
+
321
+ def main():
322
+ args = parse_args()
323
+ raw_asset_dir, source, _raw_asset_type, category, source_asset_id = require_raw_asset(Path(args.raw_asset_dir))
324
+ raw_meta_path = raw_asset_dir / "metadata.yaml"
325
+ raw_meta = parse_simple_yaml(raw_meta_path) if raw_meta_path.exists() else {}
326
+
327
+ meshes = resolve_mesh_args(raw_asset_dir, args.mesh, args.mesh_glob)
328
+ derived_asset_id = f"{source_asset_id}_{args.variant}"
329
+ derived_dir = ROOT / "assets" / source / "derived" / "convex_decompositions" / category / derived_asset_id
330
+
331
+ if derived_dir.exists() and not args.overwrite:
332
+ raise SystemExit(f"destination already exists: {derived_dir}. Use --overwrite only if you intend to replace files inside it.")
333
+
334
+ # Fail before creating derived files if the real decomposition backend is unavailable.
335
+ import_deps()
336
+
337
+ (derived_dir / "meshes").mkdir(parents=True, exist_ok=True)
338
+ (derived_dir / "mjcf").mkdir(parents=True, exist_ok=True)
339
+ (derived_dir / "logs").mkdir(parents=True, exist_ok=True)
340
+
341
+ coacd_params = {
342
+ "threshold": args.threshold,
343
+ "max_convex_hull": None if args.max_convex_hull < 0 else args.max_convex_hull,
344
+ "preprocess_resolution": args.preprocess_resolution,
345
+ "seed": args.seed,
346
+ }
347
+
348
+ inputs_log = []
349
+ outputs_log = []
350
+ part_records = []
351
+ actual_tool_version = "unknown"
352
+ actual_params = {}
353
+
354
+ for mesh_path in meshes:
355
+ mesh_stem = safe_name(mesh_path.stem)
356
+ out_dir = derived_dir / "meshes" / mesh_stem
357
+ part_paths, actual_tool_version, actual_params = run_coacd_for_mesh(mesh_path, out_dir, coacd_params)
358
+ inputs_log.append({
359
+ "path": rel_to_root(mesh_path),
360
+ "sha256": sha256_file(mesh_path),
361
+ })
362
+ for part_path in part_paths:
363
+ part_rel = part_path.relative_to(derived_dir).as_posix()
364
+ part_index = int(part_path.stem.split("_")[-1])
365
+ mesh_name = safe_name(f"{source}_{source_asset_id}_{mesh_stem}_convex_{part_index:03d}")
366
+ part_records.append({
367
+ "source_mesh": rel_to_root(mesh_path),
368
+ "path": part_rel,
369
+ "sha256": sha256_file(part_path),
370
+ "mesh_name": mesh_name,
371
+ "file_from_mjcf": f"../{part_rel}",
372
+ })
373
+ outputs_log.append({
374
+ "path": part_rel,
375
+ "sha256": sha256_file(part_path),
376
+ "mesh_name": mesh_name,
377
+ })
378
+
379
+ write_xml_files(
380
+ derived_dir / "mjcf",
381
+ source_asset_id,
382
+ part_records,
383
+ args.class_name,
384
+ args.rgba,
385
+ args.group,
386
+ args.contype,
387
+ args.conaffinity,
388
+ )
389
+
390
+ license_name = raw_meta.get("license", "unknown")
391
+ origin_url = raw_meta.get("origin_url", "")
392
+ global_asset_id = f"{source}.convex_decompositions.{category}.{derived_asset_id}"
393
+ metadata = {
394
+ "asset_id": global_asset_id,
395
+ "source": source,
396
+ "source_asset_id": source_asset_id,
397
+ "asset_type": "convex_decompositions",
398
+ "category": category,
399
+ "format": "obj_mjcf_include",
400
+ "entry_file": "mjcf/convex_collision_include.xml",
401
+ "license": license_name,
402
+ "origin_url": origin_url,
403
+ "path": rel_to_root(derived_dir),
404
+ "storage_mode": "derived",
405
+ "derived_from": [rel_to_root(raw_asset_dir)],
406
+ "derivation_method": "convex_decomposition",
407
+ "decomposition_tool": "coacd",
408
+ "decomposition_version": actual_tool_version,
409
+ "decomposition_params_file": "logs/decomposition.json",
410
+ "validation_status": "generated",
411
+ "tags": [source, "convex_decomposition", "collision", "mujoco"],
412
+ }
413
+ if "readiness_level" in raw_meta:
414
+ metadata["readiness_level"] = raw_meta["readiness_level"]
415
+ if "source_commit" in raw_meta:
416
+ metadata["source_commit"] = raw_meta["source_commit"]
417
+ (derived_dir / "metadata.yaml").write_text("\n".join(dump_yaml(metadata)) + "\n")
418
+
419
+ source_refs = {
420
+ "raw_asset": rel_to_root(raw_asset_dir),
421
+ "raw_entry_file": rel_to_root(raw_asset_dir / raw_meta.get("entry_file", "model.xml"))
422
+ if (raw_asset_dir / raw_meta.get("entry_file", "model.xml")).exists()
423
+ else "",
424
+ "raw_meshes": [rel_to_root(p) for p in meshes],
425
+ }
426
+ (derived_dir / "source_refs.yaml").write_text("\n".join(dump_yaml(source_refs)) + "\n")
427
+
428
+ log = {
429
+ "tool": "coacd",
430
+ "tool_version": actual_tool_version,
431
+ "created_at": str(date.today()),
432
+ "raw_asset": rel_to_root(raw_asset_dir),
433
+ "derived_asset": rel_to_root(derived_dir),
434
+ "params": actual_params,
435
+ "inputs": inputs_log,
436
+ "outputs": outputs_log,
437
+ "mjcf": {
438
+ "root_level_asset_include": "mjcf/convex_assets_include.xml",
439
+ "body_level_geom_include": "mjcf/convex_geoms_include.xml",
440
+ "standalone_include": "mjcf/convex_collision_include.xml",
441
+ },
442
+ }
443
+ (derived_dir / "logs" / "decomposition.json").write_text(json.dumps(log, indent=2, ensure_ascii=False) + "\n")
444
+
445
+ readme = f"""# Convex decomposition: {source_asset_id}
446
+
447
+ Source asset:
448
+
449
+ ```text
450
+ {rel_to_root(raw_asset_dir)}
451
+ ```
452
+
453
+ Generated collision meshes:
454
+
455
+ ```text
456
+ {rel_to_root(derived_dir / "meshes")}
457
+ ```
458
+
459
+ MuJoCo integration:
460
+
461
+ 1. Include `mjcf/convex_assets_include.xml` at MJCF root/top level.
462
+ 2. Include `mjcf/convex_geoms_include.xml` inside the body that should receive these collision geoms.
463
+ 3. Use `mjcf/convex_collision_include.xml` only for quick standalone preview/wrapper-body loading.
464
+
465
+ Do not edit the raw source asset in place.
466
+ """
467
+ (derived_dir / "README.md").write_text(readme)
468
+
469
+ if args.register_manifest:
470
+ row = {
471
+ "asset_id": global_asset_id,
472
+ "asset_type": "convex_decompositions",
473
+ "category": category,
474
+ "entry_file": "mjcf/convex_collision_include.xml",
475
+ "format": "obj_mjcf_include",
476
+ "license": license_name,
477
+ "origin_url": origin_url,
478
+ "path": rel_to_root(derived_dir),
479
+ "source": source,
480
+ "source_asset_id": source_asset_id,
481
+ "tags": [source, "convex_decomposition", "collision", "mujoco"],
482
+ }
483
+ append_manifest(row)
484
+
485
+ print(rel_to_root(derived_dir))
486
+ print(f"decomposed_meshes={len(meshes)} convex_parts={len(part_records)}")
487
+ if not args.register_manifest:
488
+ print("manifest_status=not_registered; rerun with --register-manifest when this derived asset should be indexed")
489
+ return 0
490
+
491
+
492
+ if __name__ == "__main__":
493
+ try:
494
+ raise SystemExit(main())
495
+ except ET.ParseError as exc:
496
+ print(f"XML error: {exc}", file=sys.stderr)
497
+ raise