File size: 11,885 Bytes
a3a1599
590da42
a3a1599
 
 
 
 
 
 
 
 
f4ed0b9
a3a1599
 
 
 
 
 
590da42
a3a1599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ed0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3a1599
f4ed0b9
 
 
a3a1599
f4ed0b9
a3a1599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ed0b9
 
 
 
 
 
 
 
 
 
a3a1599
f4ed0b9
 
 
 
 
 
a3a1599
 
f4ed0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3a1599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590da42
a3a1599
590da42
a3a1599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/env python3
"""Repair example_robot_data URDFs for self-contained simulation in tars-fleet.

Resolves `package://` mesh URIs to local relative `meshes/...` paths, repairs
zero/non-positive masses and non-SPD inertia tensors (Sylvester criterion),
and defines missing top-level `<material>` entries referenced by `<visual>`.
"""

from __future__ import annotations

import argparse
import math
import re
import shutil
import xml.etree.ElementTree as ET
from pathlib import Path

DEFAULT_SRC = Path("C:/projects/projects.rust.cg/cglibs/tars-rs/target/bench/example_robot_data/robots")
DEFAULT_DST = Path("C:/projects/projects.rust.cg/cglibs/tars-fleet/example_robot_data")

KNOWN_MATERIAL_RGBA = {
    "black": "0.1 0.1 0.1 1.0",
    "flatblack": "0.12 0.12 0.12 1.0",
    "dark_grey": "0.25 0.25 0.25 1.0",
    "grey": "0.5 0.5 0.5 1.0",
    "white": "0.9 0.9 0.9 1.0",
    "red": "0.8 0.1 0.1 1.0",
    "blue": "0.1 0.1 0.8 1.0",
}


def resolve_package_uri(uri: str, src_robots_dir: Path) -> Path | None:
    """Resolve a `package://<pkg>/<rel>` (or `package:///<pkg>/<rel>`) URI against example_robot_data layout."""
    m = re.match(r"^package://+([^/]+)/(.+)$", uri.strip())
    if not m:
        return None
    pkg, rel = m.group(1), m.group(2).lstrip("/")
    if pkg == "example-robot-data":
        cand = src_robots_dir.parent / rel
        return cand if cand.exists() else None
    for base in (src_robots_dir / pkg, src_robots_dir.parent / pkg):
        cand = base / rel
        if cand.exists():
            return cand
    return None


def symmetric_3x3_eigenvalues(
    ixx: float, iyy: float, izz: float, ixy: float, ixz: float, iyz: float
) -> tuple[float, float, float]:
    """Compute sorted eigenvalues (l0 <= l1 <= l2) of a symmetric 3x3 inertia tensor via Jacobi rotations."""
    a = [
        [ixx, ixy, ixz],
        [ixy, iyy, iyz],
        [ixz, iyz, izz],
    ]
    for _ in range(32):
        # Find largest off-diagonal element
        p, q, max_val = 0, 1, abs(a[0][1])
        for i, j in ((0, 2), (1, 2)):
            v = abs(a[i][j])
            if v > max_val:
                p, q, max_val = i, j, v
        if max_val <= 1e-18:
            break
        app, aqq, apq = a[p][p], a[q][q], a[p][q]
        tau = (aqq - app) / (2.0 * apq)
        t = (1.0 / (tau + math.sqrt(1.0 + tau * tau))) if tau >= 0.0 else (-1.0 / (-tau + math.sqrt(1.0 + tau * tau)))
        c = 1.0 / math.sqrt(1.0 + t * t)
        s = t * c
        a[p][p] = app - t * apq
        a[q][q] = aqq + t * apq
        a[p][q] = 0.0
        a[q][p] = 0.0
        for r in range(3):
            if r != p and r != q:
                arp, arq = a[r][p], a[r][q]
                a[r][p] = a[p][r] = c * arp - s * arq
                a[r][q] = a[q][r] = s * arp + c * arq
    vals = sorted((a[0][0], a[1][1], a[2][2]))
    return (vals[0], vals[1], vals[2])


def is_spd_inertia(ixx: float, iyy: float, izz: float, ixy: float, ixz: float, iyz: float) -> bool:
    """Return True iff the 3x3 inertia matrix is strictly positive definite and eigenvalues satisfy triangle inequalities."""
    l0, l1, l2 = symmetric_3x3_eigenvalues(ixx, iyy, izz, ixy, ixz, iyz)
    if l0 <= 1e-12:
        return False
    return (l0 + l1) > l2 * (1.0 + 1e-6)


def fallback_inertia_for_link(link: ET.Element, mass: float) -> tuple[float, float, float]:
    """Compute a conservative SPD diagonal inertia from link primitive geometry or a 5 cm sphere."""
    for tag in ("collision", "visual"):
        for holder in link.findall(tag):
            geom = holder.find("geometry")
            if geom is None:
                continue
            box = geom.find("box")
            if box is not None and "size" in box.attrib:
                sx, sy, sz = (max(abs(float(v)), 0.02) for v in box.attrib["size"].split()[:3])
                return (
                    mass * (sy * sy + sz * sz) / 12.0,
                    mass * (sx * sx + sz * sz) / 12.0,
                    mass * (sx * sx + sy * sy) / 12.0,
                )
            cyl = geom.find("cylinder")
            if cyl is not None:
                r = max(abs(float(cyl.attrib.get("radius", 0.05))), 0.01)
                h = max(abs(float(cyl.attrib.get("length", 0.1))), 0.02)
                ixx = mass * (3.0 * r * r + h * h) / 12.0
                izz = 0.5 * mass * r * r
                return (ixx, ixx, izz)
            sph = geom.find("sphere")
            if sph is not None:
                r = max(abs(float(sph.attrib.get("radius", 0.05))), 0.01)
                i = 0.4 * mass * r * r
                return (i, i, i)
    r = 0.05
    i = 0.4 * mass * r * r
    return (i, i, i)


def repair_urdf(
    urdf_path: Path,
    src_robots_dir: Path,
    dst_robots_dir: Path,
    dry_run: bool,
) -> dict[str, int]:
    """Repair a single URDF and copy its referenced meshes into `<dst>/<rel_dir>/meshes/`."""
    rel_urdf = urdf_path.relative_to(src_robots_dir)
    model_root_name = rel_urdf.parts[0]
    dst_urdf = dst_robots_dir / rel_urdf
    dst_model_dir = dst_robots_dir / model_root_name

    tree = ET.parse(urdf_path)
    root = tree.getroot()

    stats = {
        "meshes_rewritten": 0,
        "meshes_copied": 0,
        "meshes_missing": 0,
        "inertias_repaired": 0,
        "materials_added": 0,
    }

    # 1. Resolve and rewrite package:// mesh paths
    copied_pairs: set[tuple[Path, Path]] = set()
    for mesh_el in root.iter("mesh"):
        fn = mesh_el.attrib.get("filename", "")
        if not fn.startswith("package://"):
            continue
        src_mesh = resolve_package_uri(fn, src_robots_dir)
        if src_mesh is None:
            stats["meshes_missing"] += 1
            continue
        m = re.match(r"^package://+[^/]+/(.+)$", fn.strip())
        rel_inside_pkg = Path(m.group(1))
        # Normalize `robots/<model>/meshes/...` -> `meshes/...` when inside the same model
        parts = rel_inside_pkg.parts
        if len(parts) >= 2 and parts[0] == "robots" and parts[1] == model_root_name:
            mesh_rel = Path(*parts[2:])
        elif len(parts) >= 2 and parts[0] == "robots":
            mesh_rel = Path("_shared") / Path(*parts[1:])
        else:
            mesh_rel = rel_inside_pkg

        dst_mesh = dst_model_dir / mesh_rel
        rel_from_urdf = Path("..") / mesh_rel if len(rel_urdf.parts) >= 3 else mesh_rel
        mesh_el.attrib["filename"] = rel_from_urdf.as_posix()
        stats["meshes_rewritten"] += 1
        copied_pairs.add((src_mesh, dst_mesh))

    # 2. Repair missing <inertial> on moving/root links, zero/negative mass, and non-SPD inertia tensors
    moving_links = set()
    child_links = set()
    for j in root.findall("joint"):
        ch = j.find("child")
        if ch is not None and "link" in ch.attrib:
            cname = ch.attrib["link"]
            child_links.add(cname)
            if j.attrib.get("type", "fixed") != "fixed":
                moving_links.add(cname)
    for link in root.findall("link"):
        lname = link.attrib.get("name", "")
        if lname not in child_links and lname.lower() != "world":
            moving_links.add(lname)

    for link in root.findall("link"):
        link_name = link.attrib.get("name", "")
        iner = link.find("inertial")
        if iner is None:
            if link_name in moving_links and link.find("collision") is None:
                iner = ET.SubElement(link, "inertial")
                ET.SubElement(iner, "origin", {"xyz": "0 0 0", "rpy": "0 0 0"})
                ET.SubElement(iner, "mass", {"value": "0.001"})
                f_ixx, f_iyy, f_izz = fallback_inertia_for_link(link, 0.001)
                ET.SubElement(
                    iner,
                    "inertia",
                    {
                        "ixx": f"{f_ixx:.6e}",
                        "iyy": f"{f_iyy:.6e}",
                        "izz": f"{f_izz:.6e}",
                        "ixy": "0",
                        "ixz": "0",
                        "iyz": "0",
                    },
                )
                stats["inertias_repaired"] += 1
            continue
        mass_el = iner.find("mass")
        mass = float(mass_el.attrib.get("value", "0")) if mass_el is not None else 0.0
        i_el = iner.find("inertia")
        if i_el is None:
            continue
        ixx = float(i_el.attrib.get("ixx", "0"))
        iyy = float(i_el.attrib.get("iyy", "0"))
        izz = float(i_el.attrib.get("izz", "0"))
        ixy = float(i_el.attrib.get("ixy", "0"))
        ixz = float(i_el.attrib.get("ixz", "0"))
        iyz = float(i_el.attrib.get("iyz", "0"))

        needs_mass = mass <= 0.0
        needs_inertia = not is_spd_inertia(ixx, iyy, izz, ixy, ixz, iyz)
        if needs_mass or needs_inertia:
            has_geom = link.find("collision") is not None or link.find("visual") is not None
            fixed_mass = (0.1 if has_geom else 1e-3) if needs_mass else mass
            if mass_el is None:
                mass_el = ET.SubElement(iner, "mass")
            mass_el.attrib["value"] = f"{fixed_mass:.6g}"
            f_ixx, f_iyy, f_izz = fallback_inertia_for_link(link, fixed_mass)
            i_el.attrib["ixx"] = f"{f_ixx:.6e}"
            i_el.attrib["iyy"] = f"{f_iyy:.6e}"
            i_el.attrib["izz"] = f"{f_izz:.6e}"
            i_el.attrib["ixy"] = "0"
            i_el.attrib["ixz"] = "0"
            i_el.attrib["iyz"] = "0"
            stats["inertias_repaired"] += 1

    # 3. Ensure every referenced <visual><material name="..."/> exists at <robot> root
    defined_mats = {m.attrib["name"] for m in root.findall("material") if "name" in m.attrib}
    for link in root.findall("link"):
        for vis in link.findall("visual"):
            mat = vis.find("material")
            if mat is None or "name" not in mat.attrib:
                continue
            if mat.find("color") is not None or mat.find("texture") is not None:
                continue
            mat_name = mat.attrib["name"]
            if mat_name not in defined_mats:
                rgba = KNOWN_MATERIAL_RGBA.get(mat_name.lower(), "0.5 0.5 0.5 1.0")
                top_mat = ET.Element("material", {"name": mat_name})
                ET.SubElement(top_mat, "color", {"rgba": rgba})
                root.insert(0, top_mat)
                defined_mats.add(mat_name)
                stats["materials_added"] += 1

    if not dry_run:
        dst_urdf.parent.mkdir(parents=True, exist_ok=True)
        ET.indent(tree, space="  ")
        tree.write(dst_urdf, encoding="utf-8", xml_declaration=True)
        for src_mesh, dst_mesh in sorted(copied_pairs):
            dst_mesh.parent.mkdir(parents=True, exist_ok=True)
            if not dst_mesh.exists():
                shutil.copy2(src_mesh, dst_mesh)
                stats["meshes_copied"] += 1
    else:
        stats["meshes_copied"] = len(copied_pairs)

    return stats


def main() -> None:
    parser = argparse.ArgumentParser(description="Repair example_robot_data URDFs for tars-fleet.")
    parser.add_argument("--src", type=Path, default=DEFAULT_SRC, help="Source example_robot_data/robots directory")
    parser.add_argument("--dst", type=Path, default=DEFAULT_DST, help="Destination directory in tars-fleet")
    parser.add_argument("--dry-run", action="store_true", help="Inspect and report repairs without writing files")
    args = parser.parse_args()

    urdfs = sorted(args.src.rglob("*.urdf"))
    totals = {
        "urdfs": len(urdfs),
        "meshes_rewritten": 0,
        "meshes_copied": 0,
        "meshes_missing": 0,
        "inertias_repaired": 0,
        "materials_added": 0,
    }
    for u in urdfs:
        res = repair_urdf(u, args.src, args.dst, dry_run=args.dry_run)
        for k, v in res.items():
            totals[k] += v

    mode = "DRY-RUN" if args.dry_run else "WROTE"
    print(f"[{mode}] {totals}")


if __name__ == "__main__":
    main()