feat: expand product exporters and FEM workflow
This commit is contained in:
@@ -48,7 +48,9 @@ DEFAULT_SOURCE_FILENAMES: tuple[str, ...] = (
|
||||
"inspect/brep/render.py",
|
||||
"inspect/brep/slices.py",
|
||||
"exporter/step.py",
|
||||
"exporter/obj.py",
|
||||
"exporter/stl.py",
|
||||
"exporter/mjcf.py",
|
||||
)
|
||||
|
||||
DEFAULT_STDLIB_SOURCE_FILENAMES: tuple[str, ...] = (
|
||||
@@ -90,7 +92,9 @@ EXPORTED_FUNCTION_MODULES = frozenset(
|
||||
"inspect/brep/render.py",
|
||||
"inspect/brep/slices.py",
|
||||
"exporter/step.py",
|
||||
"exporter/obj.py",
|
||||
"exporter/stl.py",
|
||||
"exporter/mjcf.py",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -324,6 +328,8 @@ class APIDocumentGenerator:
|
||||
module_name: str,
|
||||
exported_names: set[str],
|
||||
) -> bool:
|
||||
if name.startswith("_"):
|
||||
return False
|
||||
if module_name.startswith("exporter/"):
|
||||
return True
|
||||
if name.startswith("_"):
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
"""Product-package exporters for neutral CAD and mesh formats."""
|
||||
"""Product-package exporters for neutral CAD, mesh, and simulation formats."""
|
||||
|
||||
from .mjcf import ProductMJCFExportReport, export_product_package_to_mjcf
|
||||
from .obj import ProductOBJExportReport, export_product_package_to_obj
|
||||
from .step import ProductSTEPExportReport, export_product_package_to_step
|
||||
from .stl import ProductSTLExportReport, export_product_package_to_stl
|
||||
|
||||
__all__ = [
|
||||
"ProductMJCFExportReport",
|
||||
"ProductOBJExportReport",
|
||||
"ProductSTEPExportReport",
|
||||
"ProductSTLExportReport",
|
||||
"export_product_package_to_mjcf",
|
||||
"export_product_package_to_obj",
|
||||
"export_product_package_to_step",
|
||||
"export_product_package_to_stl",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Shared OpenCASCADE BREP tessellation for STL and OBJ exporters."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
from typing import Any, Sequence
|
||||
|
||||
import numpy as np
|
||||
from OCP.BRep import BRep_Tool
|
||||
from OCP.BRepMesh import BRepMesh_IncrementalMesh
|
||||
from OCP.BRepTools import BRepTools
|
||||
from OCP.TopAbs import TopAbs_FACE, TopAbs_REVERSED
|
||||
from OCP.TopExp import TopExp_Explorer
|
||||
from OCP.TopLoc import TopLoc_Location
|
||||
from OCP.TopoDS import TopoDS
|
||||
|
||||
from ..artifacts.assembly_io import materialize_definition
|
||||
from ..kernel.ocp_booleans import solids_of
|
||||
from ..operations import make_compound_from_assembly_rcompound
|
||||
from ..product import Assembly, Part
|
||||
from ..translator.package_units import (
|
||||
ProductPackageInput,
|
||||
read_product_package_translation_units,
|
||||
)
|
||||
|
||||
_TESSELLATION_BACKEND = "opencascade-brep-tessellation"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TessellatedSurfaceMesh:
|
||||
"""One triangle mesh produced directly from evaluated product BREP solids."""
|
||||
|
||||
vertices: np.ndarray
|
||||
triangles: np.ndarray
|
||||
root_definition_id: str
|
||||
solid_count: int
|
||||
definition_count: int
|
||||
linear_deflection: float
|
||||
angular_deflection_degrees: float
|
||||
relative: bool
|
||||
tessellation_backend: str = _TESSELLATION_BACKEND
|
||||
|
||||
@property
|
||||
def vertex_count(self) -> int:
|
||||
return int(self.vertices.shape[0])
|
||||
|
||||
@property
|
||||
def triangle_count(self) -> int:
|
||||
return int(self.triangles.shape[0])
|
||||
|
||||
|
||||
def _product_solids(value: Part | Assembly) -> tuple[Any, ...]:
|
||||
if isinstance(value, Part):
|
||||
return (value.body.wrapped,)
|
||||
projection = make_compound_from_assembly_rcompound(assembly=value)
|
||||
solids = tuple(solids_of(projection.wrapped))
|
||||
if not solids:
|
||||
raise ValueError("Product assembly produced no solids for mesh export")
|
||||
return solids
|
||||
|
||||
|
||||
def _vertex_key(point: Sequence[float], tolerance: float) -> tuple[int, int, int]:
|
||||
return tuple(int(round(float(value) / tolerance)) for value in point)
|
||||
|
||||
|
||||
def _is_collapsed_triangle(
|
||||
vertices: Sequence[tuple[float, float, float]],
|
||||
indices: tuple[int, int, int],
|
||||
) -> bool:
|
||||
points = np.asarray([vertices[index] for index in indices], dtype=np.float64)
|
||||
first = points[1] - points[0]
|
||||
second = points[2] - points[0]
|
||||
third = points[2] - points[1]
|
||||
max_edge_squared = max(
|
||||
float(np.dot(first, first)),
|
||||
float(np.dot(second, second)),
|
||||
float(np.dot(third, third)),
|
||||
)
|
||||
if max_edge_squared == 0.0:
|
||||
return True
|
||||
normal = np.cross(first, second)
|
||||
area_squared = float(np.dot(normal, normal))
|
||||
relative_floor = np.finfo(np.float64).eps ** 2 * max_edge_squared**2
|
||||
return area_squared <= relative_floor
|
||||
|
||||
|
||||
def _tessellate_solid(
|
||||
solid: Any,
|
||||
*,
|
||||
linear_deflection: float,
|
||||
angular_deflection_radians: float,
|
||||
relative: bool,
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
BRepTools.Clean_s(solid, False)
|
||||
mesher = BRepMesh_IncrementalMesh(
|
||||
solid,
|
||||
linear_deflection,
|
||||
relative,
|
||||
angular_deflection_radians,
|
||||
False,
|
||||
)
|
||||
mesher.Perform()
|
||||
if not mesher.IsDone():
|
||||
raise RuntimeError("OpenCASCADE failed to tessellate product geometry")
|
||||
|
||||
weld_tolerance = max(min(linear_deflection * 1.0e-7, 1.0e-7), 1.0e-9)
|
||||
vertices: list[tuple[float, float, float]] = []
|
||||
vertex_indices: dict[tuple[int, int, int], int] = {}
|
||||
triangles: list[tuple[int, int, int]] = []
|
||||
explorer = TopExp_Explorer(solid, TopAbs_FACE)
|
||||
while explorer.More():
|
||||
face = TopoDS.Face_s(explorer.Current())
|
||||
location = TopLoc_Location()
|
||||
triangulation = BRep_Tool.Triangulation_s(face, location, 0)
|
||||
if triangulation is None or triangulation.NbTriangles() == 0:
|
||||
raise RuntimeError("OpenCASCADE produced an empty face triangulation")
|
||||
transform = location.Transformation()
|
||||
local_indices: dict[int, int] = {}
|
||||
for node_index in range(1, triangulation.NbNodes() + 1):
|
||||
point = triangulation.Node(node_index).Transformed(transform)
|
||||
coordinates = (float(point.X()), float(point.Y()), float(point.Z()))
|
||||
if not all(math.isfinite(value) for value in coordinates):
|
||||
raise RuntimeError("OpenCASCADE produced a non-finite mesh vertex")
|
||||
key = _vertex_key(coordinates, weld_tolerance)
|
||||
global_index = vertex_indices.get(key)
|
||||
if global_index is None:
|
||||
global_index = len(vertices)
|
||||
vertex_indices[key] = global_index
|
||||
vertices.append(coordinates)
|
||||
local_indices[node_index] = global_index
|
||||
|
||||
reversed_face = face.Orientation() == TopAbs_REVERSED
|
||||
for triangle_index in range(1, triangulation.NbTriangles() + 1):
|
||||
a, b, c = triangulation.Triangle(triangle_index).Get()
|
||||
indices = (
|
||||
(local_indices[a], local_indices[c], local_indices[b])
|
||||
if reversed_face
|
||||
else (local_indices[a], local_indices[b], local_indices[c])
|
||||
)
|
||||
if len(set(indices)) == 3 and not _is_collapsed_triangle(vertices, indices):
|
||||
triangles.append(indices)
|
||||
explorer.Next()
|
||||
|
||||
if not vertices or not triangles:
|
||||
raise RuntimeError("OpenCASCADE produced no product surface triangles")
|
||||
return (
|
||||
np.asarray(vertices, dtype=np.float64).reshape((-1, 3)),
|
||||
np.asarray(triangles, dtype=np.int32).reshape((-1, 3)),
|
||||
)
|
||||
|
||||
|
||||
def tessellate_product_surface(
|
||||
data: ProductPackageInput,
|
||||
*,
|
||||
linear_deflection: float,
|
||||
angular_deflection_degrees: float,
|
||||
relative: bool,
|
||||
) -> TessellatedSurfaceMesh:
|
||||
"""Tessellate every evaluated product solid directly with OpenCASCADE."""
|
||||
|
||||
linear = float(linear_deflection)
|
||||
if not math.isfinite(linear) or linear <= 0.0:
|
||||
raise ValueError("linear_deflection must be a positive finite value")
|
||||
angular_degrees = float(angular_deflection_degrees)
|
||||
if (
|
||||
not math.isfinite(angular_degrees)
|
||||
or angular_degrees <= 0.0
|
||||
or angular_degrees > 180.0
|
||||
):
|
||||
raise ValueError("angular_deflection_degrees must be in (0, 180]")
|
||||
if not isinstance(relative, bool):
|
||||
raise TypeError("relative must be a bool")
|
||||
|
||||
package, units = read_product_package_translation_units(data)
|
||||
root = materialize_definition(package.root_definition)
|
||||
solids = _product_solids(root)
|
||||
vertex_blocks: list[np.ndarray] = []
|
||||
triangle_blocks: list[np.ndarray] = []
|
||||
vertex_offset = 0
|
||||
angular_radians = math.radians(angular_degrees)
|
||||
for solid in solids:
|
||||
vertices, triangles = _tessellate_solid(
|
||||
solid,
|
||||
linear_deflection=linear,
|
||||
angular_deflection_radians=angular_radians,
|
||||
relative=relative,
|
||||
)
|
||||
vertex_blocks.append(vertices)
|
||||
triangle_blocks.append(triangles + vertex_offset)
|
||||
vertex_offset += len(vertices)
|
||||
|
||||
return TessellatedSurfaceMesh(
|
||||
vertices=np.concatenate(vertex_blocks, axis=0),
|
||||
triangles=np.concatenate(triangle_blocks, axis=0),
|
||||
root_definition_id=package.root_definition.definition_id,
|
||||
solid_count=len(solids),
|
||||
definition_count=len(units),
|
||||
linear_deflection=linear,
|
||||
angular_deflection_degrees=angular_degrees,
|
||||
relative=relative,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["TessellatedSurfaceMesh", "tessellate_product_surface"]
|
||||
@@ -0,0 +1,931 @@
|
||||
"""MuJoCo MJCF export for validated SimpleCAD product packages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict, deque
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any, Mapping
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..artifacts.assembly_io import materialize_definition
|
||||
from ..artifacts.canonical import parse_canonical_json
|
||||
from ..artifacts.part_definition import PartDefinition
|
||||
from ..product import Assembly, Part, Placement, relative_placement
|
||||
from ..scene import read_scene_package
|
||||
from ..translator.package_units import (
|
||||
ProductPackageInput,
|
||||
read_product_package_translation_units,
|
||||
)
|
||||
from ._surface_mesh import _tessellate_solid
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProductMJCFExportReport:
|
||||
"""Observed facts and compiler decisions from one MJCF export."""
|
||||
|
||||
output_path: Path
|
||||
mapping_path: Path
|
||||
mesh_directory: Path
|
||||
root_definition_id: str
|
||||
mesh_count: int
|
||||
body_count: int
|
||||
joint_count: int
|
||||
equality_count: int
|
||||
grounded_group_count: int
|
||||
site_count: int
|
||||
default_density_count: int
|
||||
limitations: tuple[str, ...]
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"output_path": str(self.output_path),
|
||||
"mapping_path": str(self.mapping_path),
|
||||
"mesh_directory": str(self.mesh_directory),
|
||||
"root_definition_id": self.root_definition_id,
|
||||
"mesh_count": self.mesh_count,
|
||||
"body_count": self.body_count,
|
||||
"joint_count": self.joint_count,
|
||||
"equality_count": self.equality_count,
|
||||
"grounded_group_count": self.grounded_group_count,
|
||||
"site_count": self.site_count,
|
||||
"default_density_count": self.default_density_count,
|
||||
"limitations": list(self.limitations),
|
||||
}
|
||||
|
||||
|
||||
class _UnionFind:
|
||||
def __init__(self, values: list[str]) -> None:
|
||||
self.parent = {value: value for value in values}
|
||||
self.rank = {value: 0 for value in values}
|
||||
|
||||
def find(self, value: str) -> str:
|
||||
parent = self.parent[value]
|
||||
if parent != value:
|
||||
self.parent[value] = self.find(parent)
|
||||
return self.parent[value]
|
||||
|
||||
def union(self, first: str, second: str) -> None:
|
||||
left = self.find(first)
|
||||
right = self.find(second)
|
||||
if left == right:
|
||||
return
|
||||
if self.rank[left] < self.rank[right]:
|
||||
left, right = right, left
|
||||
self.parent[right] = left
|
||||
if self.rank[left] == self.rank[right]:
|
||||
self.rank[left] += 1
|
||||
|
||||
|
||||
def _safe_name(value: str, *, prefix: str = "item") -> str:
|
||||
rendered = re.sub(r"[^A-Za-z0-9_]", "_", str(value)).strip("_")
|
||||
if not rendered:
|
||||
rendered = prefix
|
||||
if not rendered[0].isalpha():
|
||||
rendered = f"{prefix}_{rendered}"
|
||||
if len(rendered) > 96:
|
||||
digest = hashlib.sha1(str(value).encode("utf-8")).hexdigest()[:12]
|
||||
rendered = f"{rendered[:80]}_{digest}"
|
||||
return rendered
|
||||
|
||||
|
||||
def _fmt(value: float) -> str:
|
||||
return f"{float(value):.12g}"
|
||||
|
||||
|
||||
def _fmt_vec(values: tuple[float, float, float] | list[float]) -> str:
|
||||
return " ".join(_fmt(float(value)) for value in values)
|
||||
|
||||
|
||||
def _placement(payload: Mapping[str, Any]) -> Placement:
|
||||
return Placement(
|
||||
origin=tuple(float(value) for value in payload["origin"]),
|
||||
x_axis=tuple(float(value) for value in payload["x_axis"]),
|
||||
y_axis=tuple(float(value) for value in payload["y_axis"]),
|
||||
z_axis=tuple(float(value) for value in payload["z_axis"]),
|
||||
)
|
||||
|
||||
|
||||
def _inverse_vector(
|
||||
frame: Placement,
|
||||
vector: tuple[float, float, float],
|
||||
) -> tuple[float, float, float]:
|
||||
return (
|
||||
sum(vector[index] * frame.x_axis[index] for index in range(3)),
|
||||
sum(vector[index] * frame.y_axis[index] for index in range(3)),
|
||||
sum(vector[index] * frame.z_axis[index] for index in range(3)),
|
||||
)
|
||||
|
||||
|
||||
def _add_scaled_terms(
|
||||
target: dict[str, float],
|
||||
source: Mapping[str, float],
|
||||
scale: float,
|
||||
) -> None:
|
||||
for name, coefficient in source.items():
|
||||
target[name] = target.get(name, 0.0) + scale * coefficient
|
||||
|
||||
|
||||
def _subtracted_terms(
|
||||
first: Mapping[str, float],
|
||||
second: Mapping[str, float],
|
||||
) -> dict[str, float]:
|
||||
result = dict(first)
|
||||
_add_scaled_terms(result, second, -1.0)
|
||||
return {name: value for name, value in result.items() if abs(value) > 1.0e-12}
|
||||
|
||||
|
||||
def _matrix_to_quat(frame: Placement) -> tuple[float, float, float, float]:
|
||||
"""Convert the frame's orthonormal columns to MuJoCo wxyz."""
|
||||
|
||||
m00, m01, m02 = frame.x_axis[0], frame.y_axis[0], frame.z_axis[0]
|
||||
m10, m11, m12 = frame.x_axis[1], frame.y_axis[1], frame.z_axis[1]
|
||||
m20, m21, m22 = frame.x_axis[2], frame.y_axis[2], frame.z_axis[2]
|
||||
trace = m00 + m11 + m22
|
||||
if trace > 0.0:
|
||||
scale = 2.0 * (trace + 1.0) ** 0.5
|
||||
return (
|
||||
0.25 * scale,
|
||||
(m21 - m12) / scale,
|
||||
(m02 - m20) / scale,
|
||||
(m10 - m01) / scale,
|
||||
)
|
||||
if m00 > m11 and m00 > m22:
|
||||
scale = 2.0 * (1.0 + m00 - m11 - m22) ** 0.5
|
||||
return (
|
||||
(m21 - m12) / scale,
|
||||
0.25 * scale,
|
||||
(m01 + m10) / scale,
|
||||
(m02 + m20) / scale,
|
||||
)
|
||||
if m11 > m22:
|
||||
scale = 2.0 * (1.0 + m11 - m00 - m22) ** 0.5
|
||||
return (
|
||||
(m02 - m20) / scale,
|
||||
(m01 + m10) / scale,
|
||||
0.25 * scale,
|
||||
(m12 + m21) / scale,
|
||||
)
|
||||
scale = 2.0 * (1.0 + m22 - m00 - m11) ** 0.5
|
||||
return (
|
||||
(m10 - m01) / scale,
|
||||
(m02 + m20) / scale,
|
||||
(m12 + m21) / scale,
|
||||
0.25 * scale,
|
||||
)
|
||||
|
||||
|
||||
def _placement_attributes(value: Placement, *, scale_length: bool) -> dict[str, str]:
|
||||
origin = tuple(component * 0.001 for component in value.origin) if scale_length else value.origin
|
||||
return {
|
||||
"pos": _fmt_vec(origin),
|
||||
"quat": _fmt_vec(_matrix_to_quat(value)),
|
||||
}
|
||||
|
||||
|
||||
def _write_obj(path: Path, solid: Any, *, linear_deflection: float) -> tuple[int, int]:
|
||||
vertices, triangles = _tessellate_solid(
|
||||
solid.wrapped,
|
||||
linear_deflection=linear_deflection,
|
||||
angular_deflection_radians=0.35,
|
||||
relative=False,
|
||||
)
|
||||
with path.open("w", encoding="ascii", newline="\n") as stream:
|
||||
stream.write("# SimpleCAD BREP tessellation for MuJoCo\n")
|
||||
for x, y, z in vertices:
|
||||
stream.write(f"v {_fmt(float(x))} {_fmt(float(y))} {_fmt(float(z))}\n")
|
||||
for a, b, c in triangles:
|
||||
stream.write(f"f {int(a) + 1} {int(b) + 1} {int(c) + 1}\n")
|
||||
return int(len(vertices)), int(len(triangles))
|
||||
|
||||
|
||||
def _density_kg_m3(
|
||||
material: Any,
|
||||
*,
|
||||
default_density_kg_m3: float | None,
|
||||
) -> tuple[float, bool]:
|
||||
density = getattr(material, "density", None) if material is not None else None
|
||||
unit = str(getattr(material, "density_unit", None) or "") if material is not None else ""
|
||||
if density is None:
|
||||
if default_density_kg_m3 is None:
|
||||
raise ValueError(
|
||||
"MJCF export requires material density for every Part; pass "
|
||||
"default_density_kg_m3 explicitly to opt into a fallback"
|
||||
)
|
||||
return float(default_density_kg_m3), True
|
||||
if unit == "kg/mm^3":
|
||||
return float(density) * 1.0e9, False
|
||||
if unit in {"kg/m^3", "kg/m3"}:
|
||||
return float(density), False
|
||||
raise ValueError(f"unsupported material density unit for MJCF: {unit!r}")
|
||||
|
||||
|
||||
def _world_placements(scene: Mapping[str, Any]) -> dict[str, Placement]:
|
||||
nodes = {str(item["node_id"]): item for item in scene["nodes"]}
|
||||
result: dict[str, Placement] = {}
|
||||
pending = set(nodes)
|
||||
while pending:
|
||||
progress = False
|
||||
for node_id in sorted(pending):
|
||||
node = nodes[node_id]
|
||||
parent_id = node["parent_node_id"]
|
||||
if parent_id is not None and parent_id not in result:
|
||||
continue
|
||||
local = _placement(node["transform"])
|
||||
result[node_id] = local if parent_id is None else result[parent_id].compose(local)
|
||||
pending.remove(node_id)
|
||||
progress = True
|
||||
break
|
||||
if not progress:
|
||||
raise ValueError("Scene node hierarchy contains an unresolved parent cycle")
|
||||
return result
|
||||
|
||||
|
||||
def _runtime_ground_edges(value: Assembly, root_node_id: str) -> list[tuple[str, str]]:
|
||||
edges: list[tuple[str, str]] = []
|
||||
|
||||
def visit(item: Part | Assembly, node_id: str) -> None:
|
||||
if not isinstance(item, Assembly):
|
||||
return
|
||||
for component in item.components:
|
||||
child_node_id = f"{node_id}/{component.component_id}"
|
||||
if component.component_id in item.grounded_component_ids:
|
||||
edges.append((node_id, child_node_id))
|
||||
visit(component.item, child_node_id)
|
||||
|
||||
visit(value, root_node_id)
|
||||
return edges
|
||||
|
||||
|
||||
def _entity_documents(
|
||||
scene_package: Any,
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
result: dict[str, dict[str, Any]] = {}
|
||||
for record in scene_package.manifest["entity_assets"]:
|
||||
document = parse_canonical_json(scene_package.blobs[record["uri"]])
|
||||
result[str(document["definition_id"])] = document
|
||||
return result
|
||||
|
||||
|
||||
def _part_materials(units: tuple[Any, ...]) -> dict[str, tuple[Part, float, bool]]:
|
||||
result: dict[str, tuple[Part, float, bool]] = {}
|
||||
for unit in units:
|
||||
if not isinstance(unit.definition, PartDefinition):
|
||||
continue
|
||||
runtime = materialize_definition(unit.definition)
|
||||
if not isinstance(runtime, Part):
|
||||
raise TypeError(f"definition {unit.definition_id!r} did not materialize as Part")
|
||||
result[unit.definition_id] = (runtime, 0.0, False)
|
||||
return result
|
||||
|
||||
|
||||
def export_product_package_to_mjcf(
|
||||
data: ProductPackageInput,
|
||||
output_path: str | Path,
|
||||
*,
|
||||
mesh_directory: str | Path | None = None,
|
||||
mapping_path: str | Path | None = None,
|
||||
linear_deflection: float = 0.15,
|
||||
default_density_kg_m3: float | None = None,
|
||||
) -> ProductMJCFExportReport:
|
||||
"""Compile a validated `.scadpkg` assembly into an MJCF model.
|
||||
|
||||
Fixed constraints and attachments through forwarded nested-assembly
|
||||
connectors create rigid groups. Revolute/prismatic edges form a
|
||||
deterministic spanning tree. Gear, belt, and rack-pinion relations become
|
||||
independent fixed-tendon equalities. Root assembly connectors and geometry
|
||||
names in the ``interface.*`` namespace become MJCF sites.
|
||||
"""
|
||||
|
||||
if linear_deflection <= 0.0:
|
||||
raise ValueError("linear_deflection must be positive")
|
||||
destination = Path(output_path).expanduser().resolve()
|
||||
if destination.suffix.lower() != ".xml":
|
||||
raise ValueError("output_path must end in .xml")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
mesh_root = (
|
||||
Path(mesh_directory).expanduser().resolve()
|
||||
if mesh_directory is not None
|
||||
else destination.parent / f"{destination.stem}_meshes"
|
||||
)
|
||||
mesh_root.mkdir(parents=True, exist_ok=True)
|
||||
decision_path = (
|
||||
Path(mapping_path).expanduser().resolve()
|
||||
if mapping_path is not None
|
||||
else destination.with_suffix(".mapping.json")
|
||||
)
|
||||
decision_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
package, units = read_product_package_translation_units(data)
|
||||
if (
|
||||
not hasattr(package.root_definition, "definition_kind")
|
||||
or package.root_definition.definition_kind != "assembly"
|
||||
):
|
||||
raise ValueError("MJCF export requires an assembly-rooted .scadpkg")
|
||||
root_runtime = materialize_definition(package.root_definition)
|
||||
if not isinstance(root_runtime, Assembly):
|
||||
raise TypeError("assembly package root did not materialize as Assembly")
|
||||
scene_package = read_scene_package(package.scene_bytes)
|
||||
scene = scene_package.manifest
|
||||
world = _world_placements(scene)
|
||||
nodes = {str(item["node_id"]): item for item in scene["nodes"]}
|
||||
root_node_id = str(scene["roots"][0])
|
||||
connector_records = list(scene["connectors"])
|
||||
connector_by_snapshot = {
|
||||
str(item["connector_snapshot_id"]): item for item in connector_records
|
||||
}
|
||||
connectors_by_node_and_id = {
|
||||
(str(item["node_id"]), str(item["connector_id"])): item
|
||||
for item in connector_records
|
||||
}
|
||||
|
||||
def leaf_connector(record: Mapping[str, Any]) -> Mapping[str, Any]:
|
||||
current = record
|
||||
seen: set[str] = set()
|
||||
while current.get("forwarded_from") is not None:
|
||||
snapshot_id = str(current["connector_snapshot_id"])
|
||||
if snapshot_id in seen:
|
||||
raise ValueError(f"forwarded connector cycle at {snapshot_id!r}")
|
||||
seen.add(snapshot_id)
|
||||
source = current["forwarded_from"]
|
||||
child_node_id = f"{current['node_id']}/{source['component_id']}"
|
||||
key = (child_node_id, str(source["connector_id"]))
|
||||
try:
|
||||
current = connectors_by_node_and_id[key]
|
||||
except KeyError as exc:
|
||||
raise ValueError(
|
||||
f"forwarded connector {snapshot_id!r} does not resolve to {key!r}"
|
||||
) from exc
|
||||
return current
|
||||
|
||||
uf = _UnionFind(sorted(nodes))
|
||||
rigid_edges: list[dict[str, str]] = []
|
||||
movable_edges: list[dict[str, Any]] = []
|
||||
equality_edges: list[dict[str, Any]] = []
|
||||
for first, second in _runtime_ground_edges(root_runtime, root_node_id):
|
||||
uf.union(first, second)
|
||||
rigid_edges.append({"kind": "ground", "a": first, "b": second})
|
||||
for joint in scene["joints"]:
|
||||
first_original = connector_by_snapshot[
|
||||
str(joint["connector_a"]["connector_snapshot_id"])
|
||||
]
|
||||
second_original = connector_by_snapshot[
|
||||
str(joint["connector_b"]["connector_snapshot_id"])
|
||||
]
|
||||
first_connector = leaf_connector(first_original)
|
||||
second_connector = leaf_connector(second_original)
|
||||
first = str(first_connector["node_id"])
|
||||
second = str(second_connector["node_id"])
|
||||
kind = str(joint["joint_type"])
|
||||
forwarded_attachment = kind in {"revolute", "prismatic"} and (
|
||||
first_original.get("forwarded_from") is not None
|
||||
or second_original.get("forwarded_from") is not None
|
||||
)
|
||||
if kind == "fixed" or forwarded_attachment:
|
||||
uf.union(first, second)
|
||||
rigid_edges.append(
|
||||
{
|
||||
"kind": "forwarded_attachment" if forwarded_attachment else kind,
|
||||
"a": first,
|
||||
"b": second,
|
||||
"joint_id": str(joint["joint_id"]),
|
||||
}
|
||||
)
|
||||
elif kind in {"revolute", "prismatic"}:
|
||||
movable_edges.append(
|
||||
{
|
||||
"joint": joint,
|
||||
"a": first,
|
||||
"b": second,
|
||||
"connector_a": first_connector,
|
||||
"connector_b": second_connector,
|
||||
}
|
||||
)
|
||||
elif kind in {"gear", "belt", "rack_pinion"}:
|
||||
equality_edges.append(
|
||||
{
|
||||
"joint": joint,
|
||||
"a": first,
|
||||
"b": second,
|
||||
"connector_a": first_connector,
|
||||
"connector_b": second_connector,
|
||||
}
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"MJCF exporter does not support joint type {kind!r}")
|
||||
|
||||
groups: dict[str, list[str]] = defaultdict(list)
|
||||
for node_id in sorted(nodes):
|
||||
groups[uf.find(node_id)].append(node_id)
|
||||
root_group = uf.find(root_node_id)
|
||||
group_for_node = {node_id: uf.find(node_id) for node_id in nodes}
|
||||
group_representative: dict[str, str] = {}
|
||||
for group_id, members in groups.items():
|
||||
geometric = [
|
||||
node_id
|
||||
for node_id in members
|
||||
if nodes[node_id]["node_kind"] == "part" and nodes[node_id]["entity_asset_id"] is not None
|
||||
]
|
||||
group_representative[group_id] = sorted(geometric or members)[0]
|
||||
|
||||
movable_edges.sort(
|
||||
key=lambda item: (
|
||||
str(item["joint"]["assembly_definition_id"])
|
||||
!= str(package.root_definition.definition_id),
|
||||
str(item["joint"]["joint_id"]),
|
||||
)
|
||||
)
|
||||
adjacency: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
for edge in movable_edges:
|
||||
first_group = group_for_node[edge["a"]]
|
||||
second_group = group_for_node[edge["b"]]
|
||||
if first_group == second_group:
|
||||
raise ValueError(
|
||||
f"movable joint {edge['joint']['joint_id']!r} collapsed inside a rigid grounding group"
|
||||
)
|
||||
edge["a_group"] = first_group
|
||||
edge["b_group"] = second_group
|
||||
adjacency[first_group].append(edge)
|
||||
adjacency[second_group].append(edge)
|
||||
|
||||
parent_group: dict[str, str | None] = {root_group: None}
|
||||
parent_edge: dict[str, dict[str, Any]] = {}
|
||||
queue: deque[str] = deque([root_group])
|
||||
while queue:
|
||||
current = queue.popleft()
|
||||
for edge in sorted(
|
||||
adjacency[current],
|
||||
key=lambda item: (
|
||||
str(item["joint"]["assembly_definition_id"])
|
||||
!= str(package.root_definition.definition_id),
|
||||
str(item["joint"]["joint_id"]),
|
||||
),
|
||||
):
|
||||
target = edge["b_group"] if edge["a_group"] == current else edge["a_group"]
|
||||
if target in parent_group:
|
||||
continue
|
||||
parent_group[target] = current
|
||||
parent_edge[target] = edge
|
||||
queue.append(target)
|
||||
unreachable = sorted(set(groups) - set(parent_group))
|
||||
if unreachable:
|
||||
raise ValueError(
|
||||
"MJCF kinematic graph is disconnected from grounding; unreachable groups: "
|
||||
+ ", ".join(unreachable)
|
||||
)
|
||||
|
||||
body_name_by_group: dict[str, str] = {}
|
||||
for group_id, edge in parent_edge.items():
|
||||
joint = edge["joint"]
|
||||
group_component_id = None
|
||||
for side in ("a", "b"):
|
||||
endpoint = joint[f"connector_{side}"]
|
||||
endpoint_snapshot = connector_by_snapshot[
|
||||
str(endpoint["connector_snapshot_id"])
|
||||
]
|
||||
if group_for_node[str(leaf_connector(endpoint_snapshot)["node_id"])] == group_id:
|
||||
group_component_id = str(endpoint["component_id"])
|
||||
break
|
||||
if group_component_id is None:
|
||||
raise ValueError(f"tree joint {joint['joint_id']!r} does not identify child group")
|
||||
body_name_by_group[group_id] = _safe_name(
|
||||
f"body_{group_component_id}", prefix="body"
|
||||
)
|
||||
tree_joint_name_by_group: dict[str, str] = {}
|
||||
for group_id, edge in parent_edge.items():
|
||||
tree_joint_name_by_group[group_id] = _safe_name(
|
||||
"joint_" + str(edge["joint"]["joint_id"]), prefix="joint"
|
||||
)
|
||||
|
||||
angle_terms_by_group: dict[str, dict[str, float]] = {root_group: {}}
|
||||
for group_id in parent_group:
|
||||
if group_id == root_group:
|
||||
continue
|
||||
parent = parent_group[group_id]
|
||||
if parent is None or parent not in angle_terms_by_group:
|
||||
raise ValueError(f"group {group_id!r} has no resolved parent angle expression")
|
||||
terms = dict(angle_terms_by_group[parent])
|
||||
terms[tree_joint_name_by_group[group_id]] = 1.0
|
||||
angle_terms_by_group[group_id] = terms
|
||||
|
||||
tree_edge_ids = {id(edge) for edge in parent_edge.values()}
|
||||
non_tree_movable_edges = [edge for edge in movable_edges if id(edge) not in tree_edge_ids]
|
||||
|
||||
def relative_angle_terms(edge: Mapping[str, Any]) -> dict[str, float]:
|
||||
return _subtracted_terms(
|
||||
angle_terms_by_group[str(edge["b_group"])],
|
||||
angle_terms_by_group[str(edge["a_group"])],
|
||||
)
|
||||
|
||||
def support_edge(connector_snapshot_id: str, group_id: str) -> dict[str, Any] | None:
|
||||
candidates = [
|
||||
edge
|
||||
for edge in movable_edges
|
||||
if connector_snapshot_id
|
||||
in {
|
||||
str(edge["connector_a"]["connector_snapshot_id"]),
|
||||
str(edge["connector_b"]["connector_snapshot_id"]),
|
||||
}
|
||||
]
|
||||
if not candidates:
|
||||
return None if group_id == root_group else None
|
||||
if len(candidates) != 1:
|
||||
raise ValueError(
|
||||
f"connector {connector_snapshot_id!r} has ambiguous movable supports: "
|
||||
+ ", ".join(str(edge["joint"]["joint_id"]) for edge in candidates)
|
||||
)
|
||||
return candidates[0]
|
||||
part_materials = _part_materials(units)
|
||||
mesh_by_definition: dict[str, str] = {}
|
||||
density_by_definition: dict[str, float] = {}
|
||||
default_density_count = 0
|
||||
for definition_id, (part, _unused_density, _unused_default) in sorted(part_materials.items()):
|
||||
density, used_default = _density_kg_m3(
|
||||
part.material,
|
||||
default_density_kg_m3=default_density_kg_m3,
|
||||
)
|
||||
density_by_definition[definition_id] = density
|
||||
default_density_count += int(used_default)
|
||||
mesh_name = _safe_name("mesh_" + definition_id, prefix="mesh")
|
||||
mesh_path = mesh_root / f"{mesh_name}.obj"
|
||||
_write_obj(mesh_path, part.body, linear_deflection=linear_deflection)
|
||||
mesh_by_definition[definition_id] = mesh_name
|
||||
|
||||
entity_documents = _entity_documents(scene_package)
|
||||
mesh_asset_elements: list[ET.Element] = []
|
||||
for definition_id, mesh_name in sorted(mesh_by_definition.items()):
|
||||
mesh_asset_elements.append(
|
||||
ET.Element(
|
||||
"mesh",
|
||||
{
|
||||
"name": mesh_name,
|
||||
"file": os.path.relpath(
|
||||
mesh_root / f"{mesh_name}.obj",
|
||||
start=destination.parent,
|
||||
),
|
||||
"scale": "0.001 0.001 0.001",
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
root_xml = ET.Element("mujoco", {"model": str(package.root_definition.definition_id)})
|
||||
ET.SubElement(root_xml, "compiler", {"angle": "radian", "coordinate": "local"})
|
||||
ET.SubElement(root_xml, "option", {"gravity": "0 0 -9.81"})
|
||||
asset_xml = ET.SubElement(root_xml, "asset")
|
||||
for element in mesh_asset_elements:
|
||||
asset_xml.append(element)
|
||||
world_xml = ET.SubElement(root_xml, "worldbody")
|
||||
|
||||
group_children: dict[str, list[str]] = defaultdict(list)
|
||||
for group_id, parent in parent_group.items():
|
||||
if parent is not None:
|
||||
group_children[parent].append(group_id)
|
||||
|
||||
group_body_frame: dict[str, Placement] = {
|
||||
root_group: Placement((0.0, 0.0, 0.0)),
|
||||
**{
|
||||
group_id: world[group_representative[group_id]]
|
||||
for group_id in groups
|
||||
if group_id != root_group
|
||||
},
|
||||
}
|
||||
body_nodes: dict[str, ET.Element] = {root_group: world_xml}
|
||||
|
||||
def relative_to_group(group_id: str, node_id: str) -> Placement:
|
||||
return relative_placement(group_body_frame[group_id], world[node_id])
|
||||
site_count = 0
|
||||
geom_count = 0
|
||||
site_records: list[dict[str, Any]] = []
|
||||
|
||||
def append_group_content(group_id: str, parent_xml: ET.Element) -> None:
|
||||
nonlocal site_count, geom_count
|
||||
body_frame = group_body_frame[group_id]
|
||||
for node_id in sorted(groups[group_id]):
|
||||
node = nodes[node_id]
|
||||
definition_id = str(node["definition_id"])
|
||||
mesh_name = mesh_by_definition.get(definition_id)
|
||||
if mesh_name is not None:
|
||||
local = relative_to_group(group_id, node_id)
|
||||
if node.get("parent_node_id") == root_node_id and node.get("component_id"):
|
||||
semantic_id = str(node["component_id"])
|
||||
else:
|
||||
semantic_id = f"geom_{node_id}"
|
||||
geom_name = _safe_name(semantic_id, prefix="geom")
|
||||
attrs = {
|
||||
"name": geom_name,
|
||||
"type": "mesh",
|
||||
"mesh": mesh_name,
|
||||
"density": _fmt(density_by_definition[definition_id]),
|
||||
"contype": "1",
|
||||
"conaffinity": "1",
|
||||
**_placement_attributes(local, scale_length=True),
|
||||
}
|
||||
ET.SubElement(parent_xml, "geom", attrs)
|
||||
geom_count += 1
|
||||
if node["entity_asset_id"] is None:
|
||||
continue
|
||||
document = entity_documents[definition_id]
|
||||
for entity in document["entities"]:
|
||||
tags = [
|
||||
str(tag)
|
||||
for tag in entity.get("tags", [])
|
||||
if str(tag).startswith("interface.")
|
||||
]
|
||||
if not tags:
|
||||
continue
|
||||
props = entity.get("properties", {})
|
||||
frame_payload = props.get("connector_frame")
|
||||
if frame_payload is None:
|
||||
origin = tuple(
|
||||
float(value)
|
||||
for value in props.get("centroid", [0.0, 0.0, 0.0])
|
||||
)
|
||||
entity_frame = Placement(origin)
|
||||
else:
|
||||
entity_frame = _placement(frame_payload)
|
||||
site_world = world[node_id].compose(entity_frame)
|
||||
local = relative_placement(body_frame, site_world)
|
||||
for tag in tags:
|
||||
site_name = _safe_name(f"site_{node_id}_{tag}", prefix="site")
|
||||
ET.SubElement(
|
||||
parent_xml,
|
||||
"site",
|
||||
{
|
||||
"name": site_name,
|
||||
"size": "0.0008",
|
||||
"type": "sphere",
|
||||
**_placement_attributes(local, scale_length=True),
|
||||
},
|
||||
)
|
||||
site_records.append(
|
||||
{
|
||||
"name": site_name,
|
||||
"tag": tag,
|
||||
"node_id": node_id,
|
||||
"entity_id": entity["entity_id"],
|
||||
"topo_id": entity["topo_id"],
|
||||
}
|
||||
)
|
||||
site_count += 1
|
||||
|
||||
def append_group_tree(group_id: str, parent_xml: ET.Element) -> None:
|
||||
for child_group in sorted(group_children[group_id], key=lambda item: body_name_by_group[item]):
|
||||
child_frame = group_body_frame[child_group]
|
||||
parent_frame = group_body_frame[group_id]
|
||||
local = relative_placement(parent_frame, child_frame)
|
||||
body_xml = ET.SubElement(
|
||||
parent_xml,
|
||||
"body",
|
||||
{"name": body_name_by_group[child_group], **_placement_attributes(local, scale_length=True)},
|
||||
)
|
||||
body_nodes[child_group] = body_xml
|
||||
edge = parent_edge[child_group]
|
||||
joint = edge["joint"]
|
||||
connector = edge["connector_a"]
|
||||
connector_frame = _placement(connector["local_frame"])
|
||||
joint_world = world[str(connector["node_id"])].compose(connector_frame)
|
||||
joint_local = relative_placement(child_frame, joint_world)
|
||||
joint_axis_world = world[str(connector["node_id"])].transform_vector(
|
||||
connector_frame.z_axis
|
||||
)
|
||||
axis = _inverse_vector(child_frame, joint_axis_world)
|
||||
joint_attrs = {
|
||||
"name": tree_joint_name_by_group[child_group],
|
||||
"type": "hinge" if joint["joint_type"] == "revolute" else "slide",
|
||||
"pos": _fmt_vec(tuple(value * 0.001 for value in joint_local.origin)),
|
||||
"axis": _fmt_vec(axis),
|
||||
}
|
||||
limits = joint.get("limits")
|
||||
if limits is not None:
|
||||
limit_key = (
|
||||
"angle_limit"
|
||||
if joint["joint_type"] == "revolute"
|
||||
else "distance_limit"
|
||||
)
|
||||
scalar_limit = limits.get(limit_key) or limits
|
||||
lower = float(scalar_limit.get("lower_value", 0.0))
|
||||
upper = float(scalar_limit.get("upper_value", 0.0))
|
||||
if joint["joint_type"] == "revolute":
|
||||
lower = lower * 3.141592653589793 / 180.0
|
||||
upper = upper * 3.141592653589793 / 180.0
|
||||
else:
|
||||
lower, upper = lower * 0.001, upper * 0.001
|
||||
joint_attrs.update(
|
||||
{"limited": "true", "range": f"{_fmt(lower)} {_fmt(upper)}"}
|
||||
)
|
||||
ET.SubElement(body_xml, "joint", joint_attrs)
|
||||
append_group_content(child_group, body_xml)
|
||||
append_group_tree(child_group, body_xml)
|
||||
|
||||
append_group_content(root_group, world_xml)
|
||||
append_group_tree(root_group, world_xml)
|
||||
|
||||
public_connectors = [
|
||||
connector
|
||||
for connector in connector_records
|
||||
if str(connector["node_id"]) == root_node_id
|
||||
]
|
||||
for connector in public_connectors:
|
||||
connector_id = str(connector["connector_id"])
|
||||
leaf = leaf_connector(connector)
|
||||
leaf_node_id = str(leaf["node_id"])
|
||||
group_id = group_for_node[leaf_node_id]
|
||||
frame_world = world[str(connector["node_id"])].compose(
|
||||
_placement(connector["local_frame"])
|
||||
)
|
||||
local = relative_placement(group_body_frame[group_id], frame_world)
|
||||
site_name = _safe_name(connector_id, prefix="site")
|
||||
ET.SubElement(
|
||||
body_nodes[group_id],
|
||||
"site",
|
||||
{
|
||||
"name": site_name,
|
||||
"size": "0.0012",
|
||||
"type": "sphere",
|
||||
**_placement_attributes(local, scale_length=True),
|
||||
},
|
||||
)
|
||||
site_records.append(
|
||||
{
|
||||
"name": site_name,
|
||||
"connector_id": connector_id,
|
||||
"connector_snapshot_id": connector["connector_snapshot_id"],
|
||||
"node_id": connector["node_id"],
|
||||
"attached_group": group_id,
|
||||
}
|
||||
)
|
||||
site_count += 1
|
||||
|
||||
joint_names = sorted(tree_joint_name_by_group.values())
|
||||
joint_index = {name: index for index, name in enumerate(joint_names)}
|
||||
candidate_equalities: list[dict[str, Any]] = []
|
||||
for edge in equality_edges:
|
||||
joint = edge["joint"]
|
||||
kind = str(joint["joint_type"])
|
||||
parameters = dict(joint.get("parameters") or {})
|
||||
endpoint_terms: list[dict[str, float]] = []
|
||||
for side in ("a", "b"):
|
||||
connector = edge[f"connector_{side}"]
|
||||
group_id = group_for_node[str(edge[side])]
|
||||
support = support_edge(str(connector["connector_snapshot_id"]), group_id)
|
||||
if support is None:
|
||||
if group_id != root_group:
|
||||
raise ValueError(
|
||||
f"coupling {joint['joint_id']!r} endpoint {side} has no movable support"
|
||||
)
|
||||
endpoint_terms.append({})
|
||||
else:
|
||||
endpoint_terms.append(relative_angle_terms(support))
|
||||
first_terms, second_terms = endpoint_terms
|
||||
coefficients: dict[str, float] = {}
|
||||
if kind == "gear":
|
||||
_add_scaled_terms(coefficients, first_terms, float(parameters["pitch_radius_a"]))
|
||||
_add_scaled_terms(coefficients, second_terms, float(parameters["pitch_radius_b"]))
|
||||
elif kind == "belt":
|
||||
_add_scaled_terms(coefficients, first_terms, float(parameters["pulley_radius_a"]))
|
||||
_add_scaled_terms(coefficients, second_terms, -float(parameters["pulley_radius_b"]))
|
||||
else:
|
||||
_add_scaled_terms(coefficients, first_terms, 1.0)
|
||||
_add_scaled_terms(
|
||||
coefficients,
|
||||
second_terms,
|
||||
float(parameters["pitch_radius"]) * 0.001,
|
||||
)
|
||||
coefficients = {
|
||||
name: value for name, value in coefficients.items() if abs(value) > 1.0e-12
|
||||
}
|
||||
if not coefficients:
|
||||
raise ValueError(f"coupling {joint['joint_id']!r} produced an empty equation")
|
||||
row = np.zeros(len(joint_names), dtype=float)
|
||||
for name, coefficient in coefficients.items():
|
||||
row[joint_index[name]] = coefficient
|
||||
candidate_equalities.append(
|
||||
{
|
||||
"joint": joint,
|
||||
"coefficients": coefficients,
|
||||
"row": row,
|
||||
"reference_phase": float(parameters.get("phase_offset", 0.0)),
|
||||
}
|
||||
)
|
||||
|
||||
independent_equalities: list[dict[str, Any]] = []
|
||||
current_rows = np.empty((0, len(joint_names)), dtype=float)
|
||||
current_rank = 0
|
||||
equality_records: list[dict[str, Any]] = []
|
||||
for candidate in candidate_equalities:
|
||||
trial = np.vstack((current_rows, candidate["row"]))
|
||||
trial_rank = int(np.linalg.matrix_rank(trial, tol=1.0e-10))
|
||||
independent = trial_rank > current_rank
|
||||
record = {
|
||||
"equality_id": str(candidate["joint"]["joint_id"]),
|
||||
"joint_type": str(candidate["joint"]["joint_type"]),
|
||||
"coefficients": dict(sorted(candidate["coefficients"].items())),
|
||||
"reference_phase_source_units": candidate["reference_phase"],
|
||||
"independent": independent,
|
||||
}
|
||||
equality_records.append(record)
|
||||
if independent:
|
||||
independent_equalities.append({**candidate, "record": record})
|
||||
current_rows = trial
|
||||
current_rank = trial_rank
|
||||
|
||||
tendon_xml = ET.SubElement(root_xml, "tendon")
|
||||
equality_xml = ET.SubElement(root_xml, "equality")
|
||||
for candidate in independent_equalities:
|
||||
joint = candidate["joint"]
|
||||
tendon_name = _safe_name("coupling_" + str(joint["joint_id"]), prefix="coupling")
|
||||
fixed_xml = ET.SubElement(tendon_xml, "fixed", {"name": tendon_name})
|
||||
for name, coefficient in sorted(candidate["coefficients"].items()):
|
||||
ET.SubElement(
|
||||
fixed_xml,
|
||||
"joint",
|
||||
{"joint": name, "coef": _fmt(coefficient)},
|
||||
)
|
||||
equality_name = _safe_name("equality_" + str(joint["joint_id"]), prefix="equality")
|
||||
ET.SubElement(
|
||||
equality_xml,
|
||||
"tendon",
|
||||
{
|
||||
"name": equality_name,
|
||||
"tendon1": tendon_name,
|
||||
"polycoef": "0 0 0 0 0",
|
||||
},
|
||||
)
|
||||
candidate["record"].update(
|
||||
{"name": equality_name, "tendon": tendon_name}
|
||||
)
|
||||
if not independent_equalities:
|
||||
root_xml.remove(tendon_xml)
|
||||
root_xml.remove(equality_xml)
|
||||
|
||||
ET.indent(root_xml, space=" ")
|
||||
tree = ET.ElementTree(root_xml)
|
||||
tree.write(destination, encoding="utf-8", xml_declaration=True)
|
||||
if destination.stat().st_size <= 0:
|
||||
raise RuntimeError("MJCF writer produced an empty XML file")
|
||||
|
||||
group_records = [
|
||||
{
|
||||
"group_id": group_id,
|
||||
"members": sorted(members),
|
||||
"grounded": group_id == root_group,
|
||||
"representative": group_representative[group_id],
|
||||
"body_name": None if group_id == root_group else body_name_by_group[group_id],
|
||||
"parent_group": parent_group[group_id],
|
||||
"tree_joint": None if group_id == root_group else tree_joint_name_by_group[group_id],
|
||||
}
|
||||
for group_id, members in sorted(groups.items())
|
||||
]
|
||||
mapping = {
|
||||
"schema_version": "1.0",
|
||||
"root_definition_id": package.root_definition.definition_id,
|
||||
"units": {"source": "mm", "mjcf_length": "m", "mjcf_angle": "radian"},
|
||||
"grounded_group_id": root_group,
|
||||
"groups": group_records,
|
||||
"rigid_edges": rigid_edges,
|
||||
"tree_joints": [
|
||||
{
|
||||
"joint_id": str(edge["joint"]["joint_id"]),
|
||||
"group": group_id,
|
||||
"parent_group": parent_group[group_id],
|
||||
"joint_name": tree_joint_name_by_group[group_id],
|
||||
}
|
||||
for group_id, edge in sorted(parent_edge.items())
|
||||
],
|
||||
"redundant_movable_joints": [
|
||||
str(edge["joint"]["joint_id"]) for edge in non_tree_movable_edges
|
||||
],
|
||||
"equalities": equality_records,
|
||||
"sites": site_records,
|
||||
"meshes": {definition_id: name for definition_id, name in sorted(mesh_by_definition.items())},
|
||||
"default_density_count": default_density_count,
|
||||
}
|
||||
decision_path.write_text(json.dumps(mapping, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
limitations = (
|
||||
"Mesh geoms are generated from BREP tessellation and scaled from mm to m.",
|
||||
"MuJoCo mesh collision uses its supported mesh collision representation; no convex decomposition is attempted.",
|
||||
"Revolute/prismatic attachments through forwarded nested-assembly connectors assign internal bearing geometry to the supported rigid group without adding another MJCF degree of freedom.",
|
||||
"Gear, belt, and rack-pinion relations constrain reference-pose increments through independent fixed tendons.",
|
||||
)
|
||||
return ProductMJCFExportReport(
|
||||
output_path=destination,
|
||||
mapping_path=decision_path,
|
||||
mesh_directory=mesh_root,
|
||||
root_definition_id=package.root_definition.definition_id,
|
||||
mesh_count=len(mesh_by_definition),
|
||||
body_count=len(body_name_by_group),
|
||||
joint_count=len(tree_joint_name_by_group),
|
||||
equality_count=len(independent_equalities),
|
||||
grounded_group_count=1,
|
||||
site_count=site_count,
|
||||
default_density_count=default_density_count,
|
||||
limitations=limitations,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["ProductMJCFExportReport", "export_product_package_to_mjcf"]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Direct OpenCASCADE BREP tessellation to triangle OBJ."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from ..translator.package_units import ProductPackageInput
|
||||
from ._surface_mesh import tessellate_product_surface
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProductOBJExportReport:
|
||||
"""Evidence from direct BREP tessellation and triangle OBJ export."""
|
||||
|
||||
output_path: Path
|
||||
root_definition_id: str
|
||||
solid_count: int
|
||||
definition_count: int
|
||||
vertex_count: int
|
||||
triangle_count: int
|
||||
linear_deflection: float
|
||||
angular_deflection_degrees: float
|
||||
relative: bool
|
||||
tessellation_backend: str = "opencascade-brep-tessellation"
|
||||
|
||||
|
||||
def export_product_package_to_obj(
|
||||
data: ProductPackageInput,
|
||||
output_path: str | Path,
|
||||
*,
|
||||
linear_deflection: float = 0.1,
|
||||
angular_deflection_degrees: float = 20.0,
|
||||
relative: bool = False,
|
||||
) -> ProductOBJExportReport:
|
||||
"""Export one `.scadpkg` directly from evaluated BREP as triangle OBJ.
|
||||
|
||||
`linear_deflection` is the maximum chordal deviation in product units.
|
||||
`angular_deflection_degrees` limits angular deviation on curved surfaces.
|
||||
No remeshing or topology reconstruction is performed.
|
||||
"""
|
||||
|
||||
destination = Path(output_path).expanduser().resolve()
|
||||
if destination.suffix.lower() != ".obj":
|
||||
raise ValueError("output_path must end in .obj")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
mesh = tessellate_product_surface(
|
||||
data=data,
|
||||
linear_deflection=linear_deflection,
|
||||
angular_deflection_degrees=angular_deflection_degrees,
|
||||
relative=relative,
|
||||
)
|
||||
with destination.open("w", encoding="ascii", newline="\n") as stream:
|
||||
stream.write("# SimpleCAD OpenCASCADE BREP tessellation\n")
|
||||
for x, y, z in mesh.vertices:
|
||||
stream.write(f"v {float(x):.17g} {float(y):.17g} {float(z):.17g}\n")
|
||||
for a, b, c in mesh.triangles:
|
||||
stream.write(f"f {int(a) + 1} {int(b) + 1} {int(c) + 1}\n")
|
||||
if destination.stat().st_size <= 0:
|
||||
raise RuntimeError("OBJ writer produced an empty file")
|
||||
return ProductOBJExportReport(
|
||||
output_path=destination,
|
||||
root_definition_id=mesh.root_definition_id,
|
||||
solid_count=mesh.solid_count,
|
||||
definition_count=mesh.definition_count,
|
||||
vertex_count=mesh.vertex_count,
|
||||
triangle_count=mesh.triangle_count,
|
||||
linear_deflection=mesh.linear_deflection,
|
||||
angular_deflection_degrees=mesh.angular_deflection_degrees,
|
||||
relative=mesh.relative,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["ProductOBJExportReport", "export_product_package_to_obj"]
|
||||
@@ -1,166 +1,93 @@
|
||||
"""Quad-dominant STL export for validated product packages."""
|
||||
"""Direct OpenCASCADE BREP tessellation to binary STL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import importlib
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
from typing import Any
|
||||
import struct
|
||||
|
||||
from OCP.BRepTools import BRepTools
|
||||
import numpy as np
|
||||
|
||||
from ..artifacts.assembly_io import materialize_definition
|
||||
from ..operations import make_compound_from_assembly_rcompound
|
||||
from ..product import Assembly, Part
|
||||
from ..translator.package_units import (
|
||||
ProductPackageInput,
|
||||
read_product_package_translation_units,
|
||||
)
|
||||
from ..translator.package_units import ProductPackageInput
|
||||
from ._surface_mesh import TessellatedSurfaceMesh, tessellate_product_surface
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProductSTLExportReport:
|
||||
"""Evidence from quad-dominant product-surface remeshing and STL export."""
|
||||
"""Evidence from direct BREP tessellation and binary STL export."""
|
||||
|
||||
output_path: Path
|
||||
root_definition_id: str
|
||||
solid_count: int
|
||||
definition_count: int
|
||||
quadrilateral_count: int
|
||||
residual_triangle_count: int
|
||||
stl_triangle_count: int
|
||||
quad_fraction: float
|
||||
mesh_size: float
|
||||
remesh_backend: str = "gmsh-quad-dominant"
|
||||
vertex_count: int
|
||||
triangle_count: int
|
||||
linear_deflection: float
|
||||
angular_deflection_degrees: float
|
||||
relative: bool
|
||||
tessellation_backend: str = "opencascade-brep-tessellation"
|
||||
|
||||
|
||||
def _load_gmsh() -> Any:
|
||||
try:
|
||||
return importlib.import_module("gmsh")
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(
|
||||
"Product STL export requires the 'gmsh' optional dependency; "
|
||||
"install simplecadapi[gmsh]"
|
||||
) from exc
|
||||
|
||||
|
||||
def _product_shape(value: Part | Assembly):
|
||||
if isinstance(value, Part):
|
||||
return value.body.wrapped, 1
|
||||
projection = make_compound_from_assembly_rcompound(assembly=value)
|
||||
solid_count = int(
|
||||
projection.get_metadata("assembly_projection", {}).get("solid_count", 0)
|
||||
)
|
||||
if solid_count <= 0:
|
||||
raise ValueError("Product assembly produced no solids for STL export")
|
||||
return projection.wrapped, solid_count
|
||||
|
||||
|
||||
def _surface_element_counts(gmsh: Any) -> tuple[int, int, int]:
|
||||
quadrilaterals = 0
|
||||
triangles = 0
|
||||
stl_triangles = 0
|
||||
element_types, element_tags, _node_tags = gmsh.model.mesh.getElements(2)
|
||||
for element_type, tags in zip(element_types, element_tags):
|
||||
name, dimension, _order, node_count, _coords, primary_node_count = (
|
||||
gmsh.model.mesh.getElementProperties(element_type)
|
||||
)
|
||||
if int(dimension) != 2:
|
||||
continue
|
||||
count = len(tags)
|
||||
if int(primary_node_count) == 4 and "Quadrilateral" in str(name):
|
||||
quadrilaterals += count
|
||||
stl_triangles += 2 * count
|
||||
elif int(primary_node_count) == 3 and "Triangle" in str(name):
|
||||
triangles += count
|
||||
stl_triangles += count
|
||||
else:
|
||||
raise RuntimeError(
|
||||
f"Gmsh produced unsupported STL surface element {name!r} "
|
||||
f"with {node_count} nodes"
|
||||
def _write_binary_stl(path: Path, mesh: TessellatedSurfaceMesh) -> None:
|
||||
header = b"SimpleCAD OpenCASCADE BREP tessellation".ljust(80, b"\0")
|
||||
with path.open("wb") as stream:
|
||||
stream.write(header)
|
||||
stream.write(struct.pack("<I", mesh.triangle_count))
|
||||
for a, b, c in mesh.triangles:
|
||||
points = mesh.vertices[[a, b, c]]
|
||||
normal = np.cross(points[1] - points[0], points[2] - points[0])
|
||||
length = float(np.linalg.norm(normal))
|
||||
if length == 0.0 or not np.isfinite(length):
|
||||
raise RuntimeError("STL tessellation contains a collapsed triangle")
|
||||
normal /= length
|
||||
stream.write(
|
||||
struct.pack(
|
||||
"<12fH",
|
||||
*normal.astype(np.float32),
|
||||
*points.astype(np.float32).reshape(-1),
|
||||
0,
|
||||
)
|
||||
)
|
||||
return quadrilaterals, triangles, stl_triangles
|
||||
|
||||
|
||||
def export_product_package_to_stl(
|
||||
data: ProductPackageInput,
|
||||
output_path: str | Path,
|
||||
*,
|
||||
mesh_size: float = 1.0,
|
||||
recombination_angle_degrees: float = 45.0,
|
||||
linear_deflection: float = 0.1,
|
||||
angular_deflection_degrees: float = 20.0,
|
||||
relative: bool = False,
|
||||
) -> ProductSTLExportReport:
|
||||
"""Export one validated `.scadpkg` as a quad-dominant remeshed STL.
|
||||
"""Export one `.scadpkg` directly from evaluated BREP as binary STL.
|
||||
|
||||
Gmsh recombines each CAD surface into quadrilaterals before its STL writer
|
||||
splits every quad into two triangles, as required by the STL file format.
|
||||
`linear_deflection` is the maximum chordal deviation in product units.
|
||||
`angular_deflection_degrees` limits angular deviation on curved surfaces.
|
||||
No remeshing or topology reconstruction is performed.
|
||||
"""
|
||||
|
||||
size = float(mesh_size)
|
||||
if size <= 0.0:
|
||||
raise ValueError("mesh_size must be greater than zero")
|
||||
angle = float(recombination_angle_degrees)
|
||||
if not 0.0 < angle <= 180.0:
|
||||
raise ValueError("recombination_angle_degrees must be in (0, 180]")
|
||||
|
||||
package, units = read_product_package_translation_units(data)
|
||||
root = materialize_definition(package.root_definition)
|
||||
shape, solid_count = _product_shape(root)
|
||||
destination = Path(output_path).expanduser().resolve()
|
||||
if destination.suffix.lower() != ".stl":
|
||||
raise ValueError("output_path must end in .stl")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
gmsh = _load_gmsh()
|
||||
initialized = False
|
||||
with tempfile.TemporaryDirectory(prefix="simplecad_product_stl_") as temp_dir:
|
||||
brep_path = Path(temp_dir) / "product.brep"
|
||||
if not BRepTools.Write_s(shape, str(brep_path)):
|
||||
raise RuntimeError(
|
||||
"OpenCASCADE failed to serialize product BREP for remeshing"
|
||||
)
|
||||
try:
|
||||
gmsh.initialize()
|
||||
initialized = True
|
||||
gmsh.option.setNumber("General.Terminal", 0)
|
||||
gmsh.model.add("SimpleCADProductSTL")
|
||||
imported = gmsh.model.occ.importShapes(
|
||||
str(brep_path), highestDimOnly=True, format="brep"
|
||||
)
|
||||
if not imported:
|
||||
raise RuntimeError("Gmsh imported no product geometry")
|
||||
gmsh.model.occ.synchronize()
|
||||
surfaces = gmsh.model.getEntities(2)
|
||||
if not surfaces:
|
||||
raise RuntimeError("Gmsh product geometry has no meshable surfaces")
|
||||
gmsh.option.setNumber("Mesh.Algorithm", 8)
|
||||
gmsh.option.setNumber("Mesh.RecombinationAlgorithm", 1)
|
||||
gmsh.option.setNumber("Mesh.MeshSizeMin", size)
|
||||
gmsh.option.setNumber("Mesh.MeshSizeMax", size)
|
||||
for _dimension, tag in surfaces:
|
||||
gmsh.model.mesh.setRecombine(2, tag, angle)
|
||||
gmsh.model.mesh.generate(2)
|
||||
quadrilaterals, triangles, stl_triangles = _surface_element_counts(gmsh)
|
||||
if quadrilaterals + triangles == 0:
|
||||
raise RuntimeError("Gmsh produced no surface elements")
|
||||
gmsh.write(str(destination))
|
||||
finally:
|
||||
if initialized:
|
||||
gmsh.finalize()
|
||||
|
||||
if not destination.is_file() or destination.stat().st_size <= 0:
|
||||
raise RuntimeError("Gmsh did not create a non-empty STL file")
|
||||
surface_count = quadrilaterals + triangles
|
||||
mesh = tessellate_product_surface(
|
||||
data=data,
|
||||
linear_deflection=linear_deflection,
|
||||
angular_deflection_degrees=angular_deflection_degrees,
|
||||
relative=relative,
|
||||
)
|
||||
_write_binary_stl(destination, mesh)
|
||||
if destination.stat().st_size != 84 + 50 * mesh.triangle_count:
|
||||
raise RuntimeError("STL writer produced an invalid binary length")
|
||||
return ProductSTLExportReport(
|
||||
output_path=destination,
|
||||
root_definition_id=package.root_definition.definition_id,
|
||||
solid_count=solid_count,
|
||||
definition_count=len(units),
|
||||
quadrilateral_count=quadrilaterals,
|
||||
residual_triangle_count=triangles,
|
||||
stl_triangle_count=stl_triangles,
|
||||
quad_fraction=quadrilaterals / surface_count,
|
||||
mesh_size=size,
|
||||
root_definition_id=mesh.root_definition_id,
|
||||
solid_count=mesh.solid_count,
|
||||
definition_count=mesh.definition_count,
|
||||
vertex_count=mesh.vertex_count,
|
||||
triangle_count=mesh.triangle_count,
|
||||
linear_deflection=mesh.linear_deflection,
|
||||
angular_deflection_degrees=mesh.angular_deflection_degrees,
|
||||
relative=mesh.relative,
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user