from __future__ import annotations
import math
import struct
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import numpy as np
from joltsim._core import (
ArticulationDesc,
BodyDesc,
JointDesc,
JointType,
MotorConfig,
MotorMode,
ShapeDesc,
ShapeType,
)
def _parse_floats(text: Optional[str], default: Tuple[float, ...]) -> Tuple[float, ...]:
if not text:
return default
return tuple(float(x) for x in text.strip().split())
def _rpy_to_quat(roll: float, pitch: float, yaw: float) -> np.ndarray:
"""Convert URDF intrinsic ZYX (extrinsic XYZ) RPY to (x, y, z, w) quaternion."""
cr, sr = math.cos(0.5 * roll), math.sin(0.5 * roll)
cp, sp = math.cos(0.5 * pitch), math.sin(0.5 * pitch)
cy, sy = math.cos(0.5 * yaw), math.sin(0.5 * yaw)
w = cr * cp * cy + sr * sp * sy
x = sr * cp * cy - cr * sp * sy
y = cr * sp * cy + sr * cp * sy
z = cr * cp * sy - sr * sp * cy
q = np.array([x, y, z, w], dtype=np.float64)
n = np.linalg.norm(q)
return q / n if n > 1e-12 else np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
def _quat_mul(q1: np.ndarray, q2: np.ndarray) -> np.ndarray:
x1, y1, z1, w1 = q1
x2, y2, z2, w2 = q2
return np.array([
w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2,
w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
], dtype=np.float64)
def _quat_to_mat3(q: np.ndarray) -> np.ndarray:
x, y, z, w = q
xx, yy, zz = x * x, y * y, z * z
xy, xz, yz = x * y, x * z, y * z
wx, wy, wz = w * x, w * y, w * z
return np.array([
[1.0 - 2.0 * (yy + zz), 2.0 * (xy - wz), 2.0 * (xz + wy)],
[2.0 * (xy + wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz - wx)],
[2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (xx + yy)],
], dtype=np.float64)
def _quat_rotate(q: np.ndarray, v: np.ndarray) -> np.ndarray:
return _quat_to_mat3(q) @ v
def _compose_tf(p1: np.ndarray, q1: np.ndarray, p2: np.ndarray, q2: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
return p1 + _quat_rotate(q1, p2), _quat_mul(q1, q2)
def _parse_origin(elem: Optional[ET.Element]) -> Tuple[np.ndarray, np.ndarray]:
if elem is None:
return np.zeros(3, dtype=np.float64), np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
xyz = np.array(_parse_floats(elem.attrib.get("xyz"), (0.0, 0.0, 0.0)), dtype=np.float64)
rpy = _parse_floats(elem.attrib.get("rpy"), (0.0, 0.0, 0.0))
return xyz, _rpy_to_quat(rpy[0], rpy[1], rpy[2])
def _resolve_mesh_path(filename: str, urdf_dir: Path) -> Path:
if filename.startswith("package://"):
rel = filename[len("package://"):]
cand = urdf_dir / rel
if cand.exists():
return cand
parts = Path(rel).parts
if len(parts) > 1:
cand2 = urdf_dir / Path(*parts[1:])
if cand2.exists():
return cand2
return cand
p = Path(filename)
return p if p.is_absolute() else (urdf_dir / p)
def _load_obj_vertices(path: Path) -> np.ndarray:
verts = []
with path.open("r", encoding="utf-8", errors="ignore") as f:
for line in f:
if line.startswith("v "):
parts = line.split()
if len(parts) >= 4:
verts.append((float(parts[1]), float(parts[2]), float(parts[3])))
if not verts:
raise ValueError(f"No vertices found in OBJ: {path}")
return np.asarray(verts, dtype=np.float64)
def _load_stl_vertices(path: Path) -> np.ndarray:
data = path.read_bytes()
if len(data) >= 84:
num_tris = struct.unpack_from("<I", data, 80)[0]
if 84 + num_tris * 50 == len(data):
verts = np.empty((num_tris * 3, 3), dtype=np.float64)
offset = 84
for i in range(num_tris):
# skip 12-byte normal
v = struct.unpack_from("<9f", data, offset + 12)
verts[i * 3 + 0] = v[0:3]
verts[i * 3 + 1] = v[3:6]
verts[i * 3 + 2] = v[6:9]
offset += 50
return verts
# ASCII STL fallback
verts = []
for line in data.decode("utf-8", errors="ignore").splitlines():
s = line.strip()
if s.startswith("vertex "):
parts = s.split()
if len(parts) >= 4:
verts.append((float(parts[1]), float(parts[2]), float(parts[3])))
if not verts:
raise ValueError(f"No vertices found in STL: {path}")
return np.asarray(verts, dtype=np.float64)
def _downsample_hull_points(pts: np.ndarray, max_points: int = 240) -> np.ndarray:
"""Ensure vertex count <= Jolt's ConvexHullShape::cMaxPointsInHull (256)."""
unique = np.unique(np.round(pts, decimals=6), axis=0)
if len(unique) <= max_points:
return unique
# Farthest-point sampling for good convex hull coverage
selected = np.empty((max_points, 3), dtype=np.float64)
center = unique.mean(axis=0)
d2 = np.sum((unique - center) ** 2, axis=1)
idx = int(np.argmax(d2))
selected[0] = unique[idx]
min_d2 = np.sum((unique - selected[0]) ** 2, axis=1)
for k in range(1, max_points):
idx = int(np.argmax(min_d2))
selected[k] = unique[idx]
new_d2 = np.sum((unique - selected[k]) ** 2, axis=1)
min_d2 = np.minimum(min_d2, new_d2)
return selected
def _parallel_axis_combine(
m1: float, c1: np.ndarray, i1: np.ndarray,
m2: float, c2: np.ndarray, i2: np.ndarray,
) -> Tuple[float, np.ndarray, np.ndarray]:
"""Combine two inertias around their new combined CoM via the parallel-axis theorem."""
m_tot = m1 + m2
if m_tot <= 1e-12:
return 0.0, np.zeros(3, dtype=np.float64), np.zeros((3, 3), dtype=np.float64)
c_new = (m1 * c1 + m2 * c2) / m_tot
d1 = c1 - c_new
d2 = c2 - c_new
eye = np.eye(3, dtype=np.float64)
i_new = (
i1 + m1 * (float(np.dot(d1, d1)) * eye - np.outer(d1, d1))
+ i2 + m2 * (float(np.dot(d2, d2)) * eye - np.outer(d2, d2))
)
return m_tot, c_new, i_new
@dataclass
class _RawLink:
name: str
mass: float = 0.0
com: np.ndarray = field(default_factory=lambda: np.zeros(3, dtype=np.float64))
inertia: np.ndarray = field(default_factory=lambda: np.zeros((3, 3), dtype=np.float64))
has_inertial: bool = False
shapes: List[ShapeDesc] = field(default_factory=list)
@dataclass
class _RawJoint:
name: str
joint_type: str
parent: str
child: str
xyz: np.ndarray
quat: np.ndarray
axis: np.ndarray
lower: float
upper: float
effort: float
velocity: float
damping: float
friction: float
mimic_joint: Optional[str] = None
mimic_multiplier: float = 1.0
mimic_offset: float = 0.0
[docs]
@dataclass
class UrdfModel:
desc: ArticulationDesc
link_names: List[str]
joint_names: List[str]
actuated_joint_names: List[str]
mimic_map: Dict[str, Tuple[str, float, float]]
[docs]
def load_urdf(
urdf_path: str | Path,
base_pos: Tuple[float, float, float] = (0.0, 0.0, 0.0),
base_quat: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0),
fixed_base: bool = False,
default_kp: float = 200.0,
default_kd: float = 20.0,
default_effort: float = 100.0,
inertia_scale: float = 1.0,
min_inertia_diag: float = 0.0,
link_friction: float = 0.5,
merge_fixed_links: bool = True,
) -> UrdfModel:
path = Path(urdf_path)
urdf_dir = path.parent
tree = ET.parse(path)
root = tree.getroot()
mesh_cache: Dict[Tuple[Path, Tuple[float, float, float]], List[float]] = {}
raw_links: Dict[str, _RawLink] = {}
for link_el in root.findall("link"):
name = link_el.attrib["name"]
rl = _RawLink(name=name)
inertial_el = link_el.find("inertial")
if inertial_el is not None:
rl.has_inertial = True
c_xyz, c_quat = _parse_origin(inertial_el.find("origin"))
mass_el = inertial_el.find("mass")
rl.mass = float(mass_el.attrib.get("value", "0.0")) if mass_el is not None else 0.0
in_el = inertial_el.find("inertia")
if in_el is not None:
ixx = float(in_el.attrib.get("ixx", "0"))
ixy = float(in_el.attrib.get("ixy", "0"))
ixz = float(in_el.attrib.get("ixz", "0"))
iyy = float(in_el.attrib.get("iyy", "0"))
iyz = float(in_el.attrib.get("iyz", "0"))
izz = float(in_el.attrib.get("izz", "0"))
i_local = np.array([
[ixx, ixy, ixz],
[ixy, iyy, iyz],
[ixz, iyz, izz],
], dtype=np.float64)
r_mat = _quat_to_mat3(c_quat)
rl.inertia = r_mat @ i_local @ r_mat.T
rl.com = c_xyz
for col_el in link_el.findall("collision"):
geom_el = col_el.find("geometry")
if geom_el is None:
continue
s_xyz, s_quat = _parse_origin(col_el.find("origin"))
sd = ShapeDesc()
sd.local_pos = [float(s_xyz[0]), float(s_xyz[1]), float(s_xyz[2])]
sd.local_quat = [float(s_quat[0]), float(s_quat[1]), float(s_quat[2]), float(s_quat[3])]
box_el = geom_el.find("box")
sphere_el = geom_el.find("sphere")
cyl_el = geom_el.find("cylinder")
cap_el = geom_el.find("capsule")
mesh_el = geom_el.find("mesh")
if box_el is not None:
size = _parse_floats(box_el.attrib.get("size"), (0.1, 0.1, 0.1))
sd.type = ShapeType.Box
sd.half_extents = [0.5 * size[0], 0.5 * size[1], 0.5 * size[2]]
rl.shapes.append(sd)
elif sphere_el is not None:
sd.type = ShapeType.Sphere
sd.radius = float(sphere_el.attrib.get("radius", "0.05"))
rl.shapes.append(sd)
elif cyl_el is not None:
sd.type = ShapeType.Cylinder
sd.radius = float(cyl_el.attrib.get("radius", "0.05"))
sd.half_height = 0.5 * float(cyl_el.attrib.get("length", "0.1"))
rl.shapes.append(sd)
elif cap_el is not None:
sd.type = ShapeType.Capsule
sd.radius = float(cap_el.attrib.get("radius", "0.05"))
sd.half_height = 0.5 * float(cap_el.attrib.get("length", "0.1"))
rl.shapes.append(sd)
elif mesh_el is not None:
mpath = _resolve_mesh_path(mesh_el.attrib["filename"], urdf_dir)
scale = _parse_floats(mesh_el.attrib.get("scale"), (1.0, 1.0, 1.0))
cache_key = (mpath, scale)
if cache_key not in mesh_cache:
ext = mpath.suffix.lower()
if ext == ".obj":
pts = _load_obj_vertices(mpath)
elif ext == ".stl":
pts = _load_stl_vertices(mpath)
else:
raise ValueError(f"Unsupported collision mesh format '{ext}' in {mpath}")
pts = pts * np.asarray(scale, dtype=np.float64)
pts = _downsample_hull_points(pts, max_points=240)
mesh_cache[cache_key] = pts.astype(np.float32).ravel().tolist()
sd.type = ShapeType.ConvexHull
sd.vertices = mesh_cache[cache_key]
sd.convex_radius = 0.005
rl.shapes.append(sd)
raw_links[name] = rl
raw_joints: List[_RawJoint] = []
children_of: Dict[str, List[_RawJoint]] = {k: [] for k in raw_links}
has_parent = set()
for j_el in root.findall("joint"):
jname = j_el.attrib["name"]
jtype = j_el.attrib["type"].lower()
parent = j_el.find("parent").attrib["link"]
child = j_el.find("child").attrib["link"]
xyz, quat = _parse_origin(j_el.find("origin"))
axis_el = j_el.find("axis")
axis = np.array(_parse_floats(axis_el.attrib.get("xyz") if axis_el is not None else None, (1.0, 0.0, 0.0)), dtype=np.float64)
an = np.linalg.norm(axis)
axis = axis / an if an > 1e-12 else np.array([1.0, 0.0, 0.0], dtype=np.float64)
lim_el = j_el.find("limit")
lower = float(lim_el.attrib.get("lower", "-3.14159265")) if lim_el is not None else -math.pi
upper = float(lim_el.attrib.get("upper", "3.14159265")) if lim_el is not None else math.pi
effort = float(lim_el.attrib.get("effort", str(default_effort))) if lim_el is not None else default_effort
velocity = float(lim_el.attrib.get("velocity", "10.0")) if lim_el is not None else 10.0
dyn_el = j_el.find("dynamics")
damping = float(dyn_el.attrib.get("damping", "0.0")) if dyn_el is not None else 0.0
friction = float(dyn_el.attrib.get("friction", "0.0")) if dyn_el is not None else 0.0
mimic_el = j_el.find("mimic")
mimic_joint = mimic_el.attrib.get("joint") if mimic_el is not None else None
mimic_mult = float(mimic_el.attrib.get("multiplier", "1.0")) if mimic_el is not None else 1.0
mimic_off = float(mimic_el.attrib.get("offset", "0.0")) if mimic_el is not None else 0.0
rj = _RawJoint(
name=jname,
joint_type=jtype,
parent=parent,
child=child,
xyz=xyz,
quat=quat,
axis=axis,
lower=lower,
upper=upper,
effort=effort,
velocity=velocity,
damping=damping,
friction=friction,
mimic_joint=mimic_joint,
mimic_multiplier=mimic_mult,
mimic_offset=mimic_off,
)
raw_joints.append(rj)
children_of[parent].append(rj)
has_parent.add(child)
roots = [n for n in raw_links if n not in has_parent]
if not roots:
raise ValueError(f"No root link found in URDF: {path}")
root_name = roots[0]
# Merge fixed-joint subtrees into their parent rigid body
merged_links: Dict[str, _RawLink] = {}
movable_joints: List[_RawJoint] = []
def _merge_fixed_into(
target: _RawLink,
cur_name: str,
rel_pos: np.ndarray,
rel_quat: np.ndarray,
) -> None:
cur = raw_links[cur_name]
if cur_name != target.name:
if cur.has_inertial and cur.mass > 0.0:
c_in_target = rel_pos + _quat_rotate(rel_quat, cur.com)
r_mat = _quat_to_mat3(rel_quat)
i_in_target = r_mat @ cur.inertia @ r_mat.T
m_new, c_new, i_new = _parallel_axis_combine(
target.mass, target.com, target.inertia,
cur.mass, c_in_target, i_in_target,
)
target.mass = m_new
target.com = c_new
target.inertia = i_new
target.has_inertial = True
for s in cur.shapes:
sp, sq = _compose_tf(
rel_pos,
rel_quat,
np.asarray(s.local_pos, dtype=np.float64),
np.asarray(s.local_quat, dtype=np.float64),
)
sc = ShapeDesc()
sc.type = s.type
sc.half_extents = list(s.half_extents)
sc.radius = s.radius
sc.half_height = s.half_height
sc.convex_radius = s.convex_radius
sc.local_pos = [float(sp[0]), float(sp[1]), float(sp[2])]
sc.local_quat = [float(sq[0]), float(sq[1]), float(sq[2]), float(sq[3])]
sc.vertices = list(s.vertices)
sc.indices = list(s.indices)
target.shapes.append(sc)
for cj in children_of.get(cur_name, []):
next_p, next_q = _compose_tf(rel_pos, rel_quat, cj.xyz, cj.quat)
if merge_fixed_links and cj.joint_type == "fixed":
_merge_fixed_into(target, cj.child, next_p, next_q)
else:
new_j = _RawJoint(
name=cj.name,
joint_type=cj.joint_type,
parent=target.name,
child=cj.child,
xyz=next_p,
quat=next_q,
axis=cj.axis,
lower=cj.lower,
upper=cj.upper,
effort=cj.effort,
velocity=cj.velocity,
damping=cj.damping,
friction=cj.friction,
mimic_joint=cj.mimic_joint,
mimic_multiplier=cj.mimic_multiplier,
mimic_offset=cj.mimic_offset,
)
movable_joints.append(new_j)
_build_merged_subtree(cj.child)
def _build_merged_subtree(link_name: str) -> None:
src = raw_links[link_name]
copy_link = _RawLink(
name=src.name,
mass=src.mass,
com=src.com.copy(),
inertia=src.inertia.copy(),
has_inertial=src.has_inertial,
shapes=list(src.shapes),
)
merged_links[link_name] = copy_link
_merge_fixed_into(copy_link, link_name, np.zeros(3), np.array([0.0, 0.0, 0.0, 1.0]))
_build_merged_subtree(root_name)
# Assemble world-space poses via forward kinematics at q = 0
world_pos: Dict[str, np.ndarray] = {root_name: np.asarray(base_pos, dtype=np.float64)}
world_quat: Dict[str, np.ndarray] = {root_name: np.asarray(base_quat, dtype=np.float64)}
ordered_links: List[str] = [root_name]
for j in movable_joints:
p_pos = world_pos[j.parent]
p_quat = world_quat[j.parent]
c_pos, c_quat = _compose_tf(p_pos, p_quat, j.xyz, j.quat)
world_pos[j.child] = c_pos
world_quat[j.child] = c_quat
ordered_links.append(j.child)
link_index = {n: i for i, n in enumerate(ordered_links)}
desc = ArticulationDesc()
desc.fixed_base = fixed_base
desc.disable_adjacent_collisions = True
links_list: List[BodyDesc] = []
for n in ordered_links:
rl = merged_links[n]
bd = BodyDesc()
bd.name = rl.name
wp = world_pos[n]
wq = world_quat[n]
bd.pos = [float(wp[0]), float(wp[1]), float(wp[2])]
bd.quat = [float(wq[0]), float(wq[1]), float(wq[2]), float(wq[3])]
bd.friction = link_friction
bd.restitution = 0.0
bd.collision_shapes = rl.shapes
if rl.has_inertial and rl.mass > 0.0:
bd.mass = float(rl.mass)
bd.has_explicit_inertia = True
bd.com_offset = [float(rl.com[0]), float(rl.com[1]), float(rl.com[2])]
bd.inertia_3x3 = [float(x) for x in rl.inertia.ravel()]
bd.inertia_scale = float(inertia_scale)
bd.min_inertia_diag = float(min_inertia_diag)
else:
bd.mass = 1.0
bd.has_explicit_inertia = False
bd.inertia_scale = float(inertia_scale)
links_list.append(bd)
desc.links = links_list
joint_names: List[str] = []
actuated_joint_names: List[str] = []
mimic_map: Dict[str, Tuple[str, float, float]] = {}
joints_list: List[JointDesc] = []
for j in movable_joints:
jd = JointDesc()
jd.name = j.name
jd.parent_link_idx = link_index[j.parent]
jd.child_link_idx = link_index[j.child]
c_pos = world_pos[j.child]
c_quat = world_quat[j.child]
axis_w = _quat_rotate(c_quat, j.axis)
jd.anchor_world = [float(c_pos[0]), float(c_pos[1]), float(c_pos[2])]
jd.axis_world = [float(axis_w[0]), float(axis_w[1]), float(axis_w[2])]
if j.joint_type == "revolute":
jd.type = JointType.Revolute
elif j.joint_type == "continuous":
jd.type = JointType.Continuous
elif j.joint_type == "prismatic":
jd.type = JointType.Prismatic
else:
jd.type = JointType.Fixed
jd.lower_limit = float(j.lower)
jd.upper_limit = float(j.upper)
mc = MotorConfig()
mc.mode = MotorMode.Off if jd.type == JointType.Fixed else MotorMode.Position
mc.kp = float(default_kp)
mc.kd = float(default_kd)
mc.max_effort = float(j.effort if j.effort > 0.0 else default_effort)
mc.max_friction = float(j.friction)
jd.motor = mc
joints_list.append(jd)
joint_names.append(j.name)
if jd.type != JointType.Fixed:
actuated_joint_names.append(j.name)
if j.mimic_joint is not None:
mimic_map[j.name] = (j.mimic_joint, j.mimic_multiplier, j.mimic_offset)
joint_idx_by_name = {name: i for i, name in enumerate(joint_names)}
for j, jd in zip(movable_joints, joints_list):
if j.mimic_joint is not None and j.mimic_joint in joint_idx_by_name:
jd.mimic_joint_idx = joint_idx_by_name[j.mimic_joint]
jd.mimic_multiplier = float(j.mimic_multiplier)
jd.mimic_offset = float(j.mimic_offset)
desc.joints = joints_list
return UrdfModel(
desc=desc,
link_names=ordered_links,
joint_names=joint_names,
actuated_joint_names=actuated_joint_names,
mimic_map=mimic_map,
)