130 lines
5.9 KiB
Python
130 lines
5.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate xiaozhao collision envelopes using the shared primitive fitter.
|
|
|
|
Only temporary input mesh URIs are normalized. The original URDF, meshes,
|
|
MuJoCo model and shared generator are left untouched.
|
|
"""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import os
|
|
from pathlib import Path
|
|
import tempfile
|
|
import xml.etree.ElementTree as ET
|
|
|
|
from collision_pieces import fit_pieces, link_triangles, shared_fitter
|
|
from verify_collision import verify
|
|
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
MODEL = HERE.parent
|
|
SOURCE = MODEL / "urdf/xiaozhao.urdf"
|
|
|
|
|
|
def parse(path):
|
|
return ET.parse(path, parser=ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)))
|
|
|
|
|
|
def signature(element):
|
|
"""Compare XML contents independently of indentation."""
|
|
return (element.tag, sorted(element.attrib.items()), (element.text or "").strip(),
|
|
[signature(child) for child in element])
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--output", type=Path, default=HERE / "xiaozhao_collision.urdf")
|
|
parser.add_argument("--config", type=Path, default=HERE / "xiaozhao_collision.toml")
|
|
args = parser.parse_args()
|
|
output = args.output.resolve()
|
|
if output.suffix.lower() != ".urdf":
|
|
raise ValueError("output must be a .urdf file, not a mesh, configuration or MuJoCo XML")
|
|
if output == SOURCE.resolve():
|
|
raise ValueError("output must not overwrite the source URDF")
|
|
original = SOURCE.read_bytes()
|
|
tree = parse(SOURCE)
|
|
root = tree.getroot()
|
|
joints = [signature(joint) for joint in root.findall("joint")]
|
|
links = [link.get("name") for link in root.findall("link")]
|
|
mesh_paths = set()
|
|
for mesh in root.iter("mesh"):
|
|
# The package name in the CAD export is historical. Resolve each asset
|
|
# under this model explicitly, never through the generic package search.
|
|
asset = (MODEL / "meshes" / Path(mesh.get("filename", "")).name).resolve()
|
|
if not asset.is_file() or asset.parent != (MODEL / "meshes").resolve():
|
|
raise FileNotFoundError(f"xiaozhao mesh missing: {asset}")
|
|
mesh.set("filename", str(asset))
|
|
mesh_paths.add(asset)
|
|
|
|
fitter = shared_fitter()
|
|
config = fitter.load_config(args.config.resolve())
|
|
defaults = config.get("defaults", {})
|
|
unknown = set(config.get("links", {})) - set(links)
|
|
if unknown:
|
|
raise ValueError(f"configuration names unknown links: {sorted(unknown)}")
|
|
for link in root.findall("link"):
|
|
name = link.get("name")
|
|
settings = fitter.link_settings(config, name)
|
|
if not settings.get("enabled", True):
|
|
continue
|
|
if not link.findall("collision"):
|
|
raise ValueError(f"visual-only link must be explicitly disabled: {name}")
|
|
if "pieces" in settings:
|
|
fits = fit_pieces(link_triangles(link), settings)
|
|
else:
|
|
fit, count = fitter._fit_urdf_link(link, SOURCE, config, defaults,
|
|
list(fitter.PRIMITIVE_TYPES))
|
|
fits = [("envelope", fit, None)]
|
|
for collision in list(link.findall("collision")):
|
|
link.remove(collision)
|
|
for piece_name, fit, face_count in fits:
|
|
collision = fitter.create_urdf_collision(fit)
|
|
collision.set("name", "collision_" + piece_name)
|
|
link.append(collision)
|
|
print(f"FIT {name}/{piece_name}: {fit.kind}, "
|
|
f"triangles={face_count if face_count is not None else 'whole-link'}")
|
|
|
|
with tempfile.TemporaryDirectory(prefix="xiaozhao-collision-") as temporary:
|
|
work = Path(temporary)
|
|
result = work / "collision.urdf"
|
|
tree.write(result, encoding="utf-8", xml_declaration=True)
|
|
# Audit the retained STL faces and all non-collision fields before publishing.
|
|
report = verify(result, 0.001, config)
|
|
print(f"Coverage verified: {report['triangles_covered']} complete triangles at 1 mm, "
|
|
f"{report['triangles_below_margin_on_rim_cylinders']} below margin on rim cylinders, "
|
|
f"{report['triangles_excluded']} triangles in disabled pieces, "
|
|
f"{report['primitive_count']} pieces")
|
|
generated = parse(result)
|
|
generated_root = generated.getroot()
|
|
if joints != [signature(joint) for joint in generated_root.findall("joint")]:
|
|
raise RuntimeError("generated joint definitions differ from source")
|
|
if links != [link.get("name") for link in generated_root.findall("link")]:
|
|
raise RuntimeError("generated link structure differs from source")
|
|
for name in ("tcp-left", "tcp-right"):
|
|
link = generated_root.find(f"link[@name='{name}']")
|
|
if link is None or link.find("collision") is not None:
|
|
raise RuntimeError(f"TCP marker must remain collision-free: {name}")
|
|
for mesh in generated_root.iter("mesh"):
|
|
asset = Path(mesh.get("filename")).resolve()
|
|
if asset not in mesh_paths:
|
|
raise RuntimeError(f"unexpected generated mesh path: {asset}")
|
|
mesh.set("filename", Path(os.path.relpath(asset, output.parent)).as_posix())
|
|
if SOURCE.read_bytes() != original:
|
|
raise RuntimeError("source URDF changed during generation")
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
ET.indent(generated, space=" ")
|
|
pending = output.with_name(f".{output.name}.tmp")
|
|
generated.write(pending, encoding="utf-8", xml_declaration=True)
|
|
os.replace(pending, output)
|
|
|
|
print(f"Verified {len(mesh_paths)} current xiaozhao mesh assets")
|
|
print(f"Preserved {len(joints)} joints, including "
|
|
f"{sum(j.get('type') != 'fixed' for j in root.findall('joint'))} movable joints")
|
|
print(f"Source SHA256: {hashlib.sha256(original).hexdigest()}")
|
|
print(f"Output SHA256: {hashlib.sha256(output.read_bytes()).hexdigest()}")
|
|
print(f"Output: {output}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|