"""Generate lightweight visuals, including the STL files used by URDF hands. Run with Blender 4.5 from any directory: blender --background --factory-startup --python simplify_visual_meshes.py blender --background --factory-startup --python simplify_visual_meshes.py -- --hands-only The sampled surface-distance check is a quality check, not a Hausdorff bound. Hand OBJ files retain the original geometry for MuJoCo collisions and repeated simplification. Other source meshes and URDF definitions are not edited here. """ from pathlib import Path import argparse import hashlib import json import os import stat import struct import sys import tempfile import bpy import numpy as np from mathutils.bvhtree import BVHTree MESHES = Path(__file__).resolve().parent / "meshes" OUTPUT = MESHES / "visual" TARGET_RATIO = 0.10 MIN_FACES = 2000 MAX_SAMPLED_ERROR = 0.0005 # metres; retain more faces if necessary SAMPLES_PER_KIND = 6000 HAND_TARGET_RATIO = 0.08 HAND_MAX_SAMPLED_ERROR = 0.0009 # Covers every vertex and triangle centre of the current 268,502-face source. HAND_SAMPLES_PER_KIND = 300000 HAND_NAMES = {"link7-left.STL", "link7-right.STL"} STL_DTYPE = np.dtype([ ("normal", " 0), f"Degenerate triangles in {path.name}" records = np.zeros(len(faces), dtype=STL_DTYPE) records["normal"] = normal / length[:, None] records["vertices"] = triangles atomic_write(path, b"xiaozhao visual mesh; original coordinates in metres".ljust(80, b"\0") + struct.pack(" 0] used, indices = np.unique(out_faces.ravel(), return_inverse=True) out_vertices = out_vertices[used] out_faces = indices.reshape(-1, 3).astype(np.int32) out_tree = surface_tree(out_vertices, out_faces) errors = np.concatenate(( distances(original_samples, out_tree), distances(sample_points(out_vertices, out_faces, samples_per_kind), original_tree), )) bounds_error = float(np.max(np.abs( np.array([vertices.min(axis=0), vertices.max(axis=0)]) - np.array([out_vertices.min(axis=0), out_vertices.max(axis=0)]) ))) if max(float(errors.max()), bounds_error) <= max_error: break if ratio >= 1.: raise ValueError(f"Surface check failed for {path.name}") ratio = min(1., ratio * 2) print(f"Retaining more detail in {path.name}: ratio={ratio:.3f}; " f"sampled error={errors.max() * 1000:.3f} mm", flush=True) output = OUTPUT / (output_name or path.name) write_stl(output, out_vertices, out_faces) report = { "source": path.name, "source_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "output": "visual/" + output.name, "source_faces": len(faces), "output_faces": len(out_faces), "sampled_surface_max_m": float(errors.max()), "sampled_surface_rms_m": float(np.sqrt(np.mean(errors ** 2))), "bounds_max_change_m": bounds_error, "target_ratio": target_ratio, "max_sampled_error_m": max_error, "samples_per_kind": samples_per_kind, } print(json.dumps(report), flush=True) return report finally: bpy.data.objects.remove(obj, do_unlink=True) bpy.data.meshes.remove(mesh) def simplify_hands(): """Always start from original OBJ, and preserve exact left/right mirroring.""" left_source, right_source = MESHES / "link7-left.obj", MESHES / "link7-right.obj" lv, lf = read_obj(left_source) rv, rf = read_obj(right_source) if not np.array_equal(rv[rf], lv[lf][:, [0, 2, 1], :] * [1, 1, -1]): raise ValueError("Hand collision OBJ files are not exact mirrors; review before simplifying") left = simplify(left_source, output_name="link7-left.STL", target_ratio=HAND_TARGET_RATIO, max_error=HAND_MAX_SAMPLED_ERROR, samples_per_kind=HAND_SAMPLES_PER_KIND) vertices, faces = read_stl(OUTPUT / "link7-left.STL") vertices[:, 2] *= -1 write_stl(OUTPUT / "link7-right.STL", vertices, faces[:, [0, 2, 1]]) for name in sorted(HAND_NAMES): atomic_write(MESHES / name, (OUTPUT / name).read_bytes()) left["urdf_stl"] = "link7-left.STL" right = dict(left, source=right_source.name, source_sha256=hashlib.sha256(right_source.read_bytes()).hexdigest(), output="visual/link7-right.STL", urdf_stl="link7-right.STL", mirror_of="visual/link7-left.STL", mirror_axis="z") return [left, right] def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--hands-only", action="store_true", help="Update hand STL/visual meshes from original collision OBJ only") args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []) OUTPUT.mkdir(exist_ok=True) if args.hands_only: previous = json.loads((OUTPUT / "manifest.json").read_text()) reports = [item for item in previous["meshes"] if Path(item["output"]).name not in HAND_NAMES] else: reports = [simplify(path) for path in sorted(MESHES.glob("*.STL")) if path.name not in HAND_NAMES] reports.extend(simplify_hands()) reports.sort(key=lambda item: item["output"]) report = { "blender_version": bpy.app.version_string, "target_ratio": TARGET_RATIO, "min_faces": MIN_FACES, "max_sampled_error_m": MAX_SAMPLED_ERROR, "samples_per_kind": SAMPLES_PER_KIND, "source_faces": sum(item["source_faces"] for item in reports), "output_faces": sum(item["output_faces"] for item in reports), "meshes": reports, } atomic_write(OUTPUT / "manifest.json", (json.dumps(report, indent=2) + "\n").encode()) print(f"TOTAL {report['source_faces']} -> {report['output_faces']} faces", flush=True) if __name__ == "__main__": main()