Update xiaozhao geometry, base axes, TCPs, neck joints and actuators. Add mesh generation tools, simplified visuals, screen and hand tags, and hand/head camera attachments. Configure both arms and enable the right-arm visual touch workflow with updated calibration, a camera-visible initial pose and higher-resolution external perception. Keep touch tests distance-limited with ZeroSimTouch. Release MuJoCo joint state control on torqueOff, latch the disabled state until torqueOn, and add regression coverage for actuator and fallback modes. Validation: isolated device/task initialization, camera acquisition and AprilTag pose checks passed. Full visual-servo motion was not validated.
239 lines
10 KiB
Python
239 lines
10 KiB
Python
"""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", "<f4", (3,)), ("vertices", "<f4", (3, 3)), ("attribute", "<u2")
|
|
])
|
|
|
|
|
|
def read_stl(path):
|
|
with path.open("rb") as stream:
|
|
header = stream.read(84)
|
|
count = struct.unpack("<I", header[80:84])[0]
|
|
assert path.stat().st_size == 84 + 50 * count, path
|
|
triangles = np.fromfile(stream, dtype=STL_DTYPE, count=count)["vertices"]
|
|
vertices, indices = np.unique(triangles.reshape(-1, 3), axis=0, return_inverse=True)
|
|
return vertices, indices.reshape(-1, 3)
|
|
|
|
|
|
def read_obj(path):
|
|
"""Read the triangle-only, lossless collision OBJ exported from CAD STL."""
|
|
vertices, faces = [], []
|
|
with path.open() as stream:
|
|
for line in stream:
|
|
fields = line.split()
|
|
if not fields:
|
|
continue
|
|
if fields[0] == "v":
|
|
vertices.append([float(x) for x in fields[1:4]])
|
|
elif fields[0] == "f":
|
|
if len(fields) != 4:
|
|
raise ValueError(f"Expected triangles in {path}")
|
|
faces.append([int(x.split('/')[0]) - 1 for x in fields[1:]])
|
|
return np.asarray(vertices, dtype=np.float32), np.asarray(faces, dtype=np.int32)
|
|
|
|
|
|
def atomic_write(path, data):
|
|
mode = stat.S_IMODE(path.stat().st_mode) if path.exists() else 0o644
|
|
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
|
|
temporary = Path(stream.name)
|
|
stream.write(data)
|
|
try:
|
|
temporary.chmod(mode)
|
|
os.replace(temporary, path)
|
|
finally:
|
|
temporary.unlink(missing_ok=True)
|
|
|
|
|
|
def write_stl(path, vertices, faces):
|
|
triangles = vertices[faces].astype(np.float32)
|
|
precise = triangles.astype(np.float64)
|
|
normal = np.cross(precise[:, 1] - precise[:, 0], precise[:, 2] - precise[:, 0])
|
|
length = np.linalg.norm(normal, axis=1)
|
|
assert np.all(length > 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("<I", len(faces)) + records.tobytes())
|
|
|
|
|
|
def sample_points(vertices, faces, count=SAMPLES_PER_KIND):
|
|
rng = np.random.default_rng(17)
|
|
vi = rng.choice(len(vertices), min(count, len(vertices)), replace=False)
|
|
fi = rng.choice(len(faces), min(count, len(faces)), replace=False)
|
|
return np.concatenate((vertices[vi], vertices[faces[fi]].mean(axis=1)))
|
|
|
|
|
|
def surface_tree(vertices, faces):
|
|
return BVHTree.FromPolygons(vertices.tolist(), faces.tolist(), all_triangles=True)
|
|
|
|
|
|
def distances(points, tree):
|
|
return np.array([tree.find_nearest(point)[3] for point in points])
|
|
|
|
|
|
def simplify(path, *, output_name=None, target_ratio=TARGET_RATIO,
|
|
max_error=MAX_SAMPLED_ERROR, samples_per_kind=SAMPLES_PER_KIND):
|
|
vertices, faces = read_obj(path) if path.suffix.lower() == ".obj" else read_stl(path)
|
|
original_tree = surface_tree(vertices, faces)
|
|
original_samples = sample_points(vertices, faces, samples_per_kind)
|
|
mesh = bpy.data.meshes.new(path.stem + "_source")
|
|
mesh.from_pydata(vertices.tolist(), [], faces.tolist())
|
|
mesh.update()
|
|
obj = bpy.data.objects.new(path.stem + "_simplify", mesh)
|
|
bpy.context.scene.collection.objects.link(obj)
|
|
modifier = obj.modifiers.new("Visual simplification", "DECIMATE")
|
|
modifier.decimate_type = "COLLAPSE"
|
|
modifier.use_collapse_triangulate = True
|
|
ratio = min(1., max(target_ratio, MIN_FACES / len(faces)))
|
|
try:
|
|
while True:
|
|
modifier.ratio = ratio
|
|
bpy.context.view_layer.update()
|
|
evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
|
|
result = evaluated.to_mesh()
|
|
try:
|
|
result.calc_loop_triangles()
|
|
out_vertices = np.empty((len(result.vertices), 3), dtype=np.float32)
|
|
out_faces = np.empty((len(result.loop_triangles), 3), dtype=np.int32)
|
|
result.vertices.foreach_get("co", out_vertices.ravel())
|
|
result.loop_triangles.foreach_get("vertices", out_faces.ravel())
|
|
finally:
|
|
evaluated.to_mesh_clear()
|
|
# Discard zero-area faces produced by CAD tessellation/collapse.
|
|
precise = out_vertices[out_faces].astype(np.float64)
|
|
areas = np.linalg.norm(np.cross(
|
|
precise[:, 1] - precise[:, 0], precise[:, 2] - precise[:, 0]
|
|
), axis=1)
|
|
out_faces = out_faces[areas > 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()
|