Source code for joltsim.sdf

from __future__ import annotations

import math
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_pose(text: Optional[str]) -> Tuple[np.ndarray, np.ndarray]:
    if not text:
        return np.zeros(3, dtype=np.float64), np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
    vals = [float(x) for x in text.strip().split()]
    xyz = np.array(vals[:3] if len(vals) >= 3 else [0.0, 0.0, 0.0], dtype=np.float64)
    r, p, y = vals[3:6] if len(vals) >= 6 else (0.0, 0.0, 0.0)
    cr, sr = math.cos(0.5 * r), math.sin(0.5 * r)
    cp, sp = math.cos(0.5 * p), math.sin(0.5 * p)
    cy, sy = math.cos(0.5 * y), math.sin(0.5 * y)
    q = np.array([
        sr * cp * cy - cr * sp * sy,
        cr * sp * cy + sr * cp * sy,
        cr * cp * sy - sr * sp * cy,
        cr * cp * cy + sr * sp * sy,
    ], dtype=np.float64)
    n = np.linalg.norm(q)
    return xyz, (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
    q = 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)
    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_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)


[docs] @dataclass class SdfModel: name: str articulations: List[ArticulationDesc] = field(default_factory=list) bodies: List[BodyDesc] = field(default_factory=list)
def _parse_geometry(geom_elem: Optional[ET.Element]) -> Optional[ShapeDesc]: if geom_elem is None: return None s = ShapeDesc() box = geom_elem.find("box") if box is not None: size = [float(x) for x in (box.findtext("size") or "1 1 1").split()] s.type = ShapeType.Box s.half_extents = [0.5 * size[0], 0.5 * size[1], 0.5 * size[2]] return s sph = geom_elem.find("sphere") if sph is not None: s.type = ShapeType.Sphere s.radius = float(sph.findtext("radius") or 0.5) return s cyl = geom_elem.find("cylinder") if cyl is not None: s.type = ShapeType.Cylinder s.radius = float(cyl.findtext("radius") or 0.5) s.half_height = 0.5 * float(cyl.findtext("length") or 1.0) return s cap = geom_elem.find("capsule") if cap is not None: s.type = ShapeType.Capsule s.radius = float(cap.findtext("radius") or 0.5) s.half_height = 0.5 * float(cap.findtext("length") or 1.0) return s return None
[docs] def load_sdf(path: str | Path, default_kp: float = 100.0, default_kd: float = 10.0) -> SdfModel: """Parse an SDF (<sdf><model>...) file into JoltSim ArticulationDesc and BodyDesc objects.""" tree = ET.parse(str(path)) root = tree.getroot() world_elem = root.find("world") model_elems = world_elem.findall("model") if world_elem is not None else root.findall("model") out = SdfModel(name=Path(path).stem) for m_elem in model_elems: m_name = m_elem.attrib.get("name", "sdf_model") is_static = (m_elem.findtext("static") or "false").strip().lower() in ("true", "1") m_pos, m_quat = _parse_pose(m_elem.findtext("pose")) links: List[BodyDesc] = [] link_idx_by_name: Dict[str, int] = {} for l_elem in m_elem.findall("link"): l_name = l_elem.attrib.get("name", f"link_{len(links)}") lp, lq = _parse_pose(l_elem.findtext("pose")) bd = BodyDesc() bd.name = f"{m_name}/{l_name}" bd.is_static = is_static bd.pos = (m_pos + _quat_to_mat3(m_quat) @ lp).astype(np.float32).tolist() bd.quat = _quat_mul(m_quat, lq).astype(np.float32).tolist() inertial = l_elem.find("inertial") if inertial is not None: mass_txt = inertial.findtext("mass") if mass_txt: bd.mass = max(1e-4, float(mass_txt)) shapes: List[ShapeDesc] = [] for col in l_elem.findall("collision"): sd = _parse_geometry(col.find("geometry")) if sd is not None: cp, cq = _parse_pose(col.findtext("pose")) sd.local_pos = cp.astype(np.float32).tolist() sd.local_quat = cq.astype(np.float32).tolist() shapes.append(sd) bd.collision_shapes = shapes link_idx_by_name[l_name] = len(links) links.append(bd) joints: List[JointDesc] = [] for j_elem in m_elem.findall("joint"): j_type_str = j_elem.attrib.get("type", "fixed").lower() p_name = (j_elem.findtext("parent") or "").strip() c_name = (j_elem.findtext("child") or "").strip() if p_name not in link_idx_by_name or c_name not in link_idx_by_name: continue p_idx = link_idx_by_name[p_name] c_idx = link_idx_by_name[c_name] jd = JointDesc() jd.name = j_elem.attrib.get("name", f"joint_{len(joints)}") jd.parent_link_idx = p_idx jd.child_link_idx = c_idx if j_type_str == "revolute": jd.type = JointType.Revolute elif j_type_str == "continuous": jd.type = JointType.Continuous elif j_type_str == "prismatic": jd.type = JointType.Prismatic else: jd.type = JointType.Fixed c_pos = np.array(links[c_idx].pos, dtype=np.float64) c_rot = _quat_to_mat3(np.array(links[c_idx].quat, dtype=np.float64)) jp, jq = _parse_pose(j_elem.findtext("pose")) jd.anchor_world = (c_pos + c_rot @ jp).astype(np.float32).tolist() axis_elem = j_elem.find("axis") if axis_elem is not None: xyz = np.array([float(x) for x in (axis_elem.findtext("xyz") or "0 0 1").split()][:3], dtype=np.float64) j_world_rot = c_rot @ _quat_to_mat3(jq) jd.axis_world = (j_world_rot @ xyz).astype(np.float32).tolist() lim = axis_elem.find("limit") if lim is not None: if lim.findtext("lower"): jd.lower_limit = float(lim.findtext("lower")) if lim.findtext("upper"): jd.upper_limit = float(lim.findtext("upper")) mc = MotorConfig() mc.mode = MotorMode.Position if jd.type != JointType.Fixed else MotorMode.Off mc.kp = default_kp mc.kd = default_kd jd.motor = mc joints.append(jd) if len(links) == 1 and not joints: out.bodies.append(links[0]) elif links: art = ArticulationDesc() art.links = links art.joints = joints art.fixed_base = is_static out.articulations.append(art) return out