"""Generate MuJoCo visual meshes from the STL files referenced by the URDF. 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. All generated meshes and the manifest are written to meshes/visual. """ from pathlib import Path import argparse import hashlib import json import os import stat import struct import sys import tempfile import xml.etree.ElementTree as ET import bpy import numpy as np from mathutils.bvhtree import BVHTree MESHES = Path(__file__).resolve().parent / "meshes" URDF = MESHES.parent / "urdf" / "xiaozhao.urdf" 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 hand meshes. 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 / 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(): """Preserve the exact mirror relationship of the two URDF hand meshes.""" left_source, right_source = MESHES / "link7-left.STL", MESHES / "link7-right.STL" lv, lf = read_stl(left_source) rv, rf = read_stl(right_source) if not np.array_equal(rv[rf], lv[lf][:, [0, 2, 1], :] * [1, 1, -1]): raise ValueError("URDF hand STL files are not exact mirrors; review before simplifying") left = simplify(left_source, 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]]) right = dict(left, source=right_source.name, source_sha256=hashlib.sha256(right_source.read_bytes()).hexdigest(), output="visual/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 only the hand visuals from the URDF hand STL files") args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []) OUTPUT.mkdir(exist_ok=True) sources = {Path(mesh.attrib["filename"]).name for mesh in ET.parse(URDF).iterfind("link/visual/geometry/mesh")} if args.hands_only: previous = json.loads((OUTPUT / "manifest.json").read_text()) reports = [item for item in previous["meshes"] if Path(item["output"]).name in sources - HAND_NAMES] else: reports = [simplify(MESHES / name) for name in sorted(sources - 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()