File size: 9,143 Bytes
41aebeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) 2026, dishsim project.
#
# SPDX-License-Identifier: BSD-3-Clause

"""Kit-side extraction of the collision-world cache (``dump_cache``).

Verbatim from ``code/src/dishsim/geometry.py`` (moved here on 2026-10-21; the cache format and its readers stay in
the code repo's ``dishsim.geometry``). Only ``extract_geometry.py`` imports it, after Kit has booted.
"""

import json
import os

import numpy as np

from dishsim import config
from dishsim.geometry import MANIFEST, MESH_DIR, config_hash
from dishsim.quats import wxyz_to_xyzw

#: dishwasher rigid bodies to extract (body-frame meshes + world poses); machines with a
#: third rack extend this via :func:`dishwasher_bodies`
DISHWASHER_BODIES = ["E_body_5", "E_door_4", "E_shelf_03", "E_shelf_1_04"]


def dishwasher_bodies() -> list[str]:
    """The active machine's extractable rigid bodies (adds the third rack when present)."""
    return DISHWASHER_BODIES + (["E_shelf_third"] if config.HAS_THIRD_RACK else [])


# ---------------------------------------------------------------------------------------------
# Kit-side extraction
# ---------------------------------------------------------------------------------------------


#: Geom prim types the extractor understands (Isaac Lab 2.1 ships no ``utils.mesh`` — the
#: 3.0 helpers this replaces returned exactly these plus ``Mesh``).
_GEOM_TYPES = ("Cube", "Sphere", "Cylinder", "Capsule", "Cone")


def _mesh_prims_under(prim):
    import isaaclab.sim as sim_utils  # noqa: PLC0415

    return sim_utils.get_all_matching_child_prims(
        prim.GetPath(), lambda p: p.GetTypeName() in _GEOM_TYPES + ("Mesh",)
    )


def _trimesh_from_geom_prim(mesh_prim) -> "object":
    """A ``trimesh.Trimesh`` of one Mesh/primitive geom prim, in the prim's LOCAL frame."""
    import numpy as _np  # noqa: PLC0415
    import trimesh  # noqa: PLC0415
    from pxr import UsdGeom  # noqa: PLC0415

    t = mesh_prim.GetTypeName()
    if t == "Mesh":
        geom = UsdGeom.Mesh(mesh_prim)
        pts = _np.asarray(geom.GetPointsAttr().Get() or [], dtype=float)
        counts = _np.asarray(geom.GetFaceVertexCountsAttr().Get() or [], dtype=int)
        idx = _np.asarray(geom.GetFaceVertexIndicesAttr().Get() or [], dtype=int)
        if len(pts) == 0 or len(counts) == 0:
            return None
        faces, o = [], 0
        for c in counts:  # fan-triangulate n-gons
            for k in range(1, c - 1):
                faces.append((idx[o], idx[o + k], idx[o + k + 1]))
            o += c
        return trimesh.Trimesh(vertices=pts, faces=_np.asarray(faces, dtype=int), process=False)
    if t == "Cube":
        size = float(UsdGeom.Cube(mesh_prim).GetSizeAttr().Get())
        return trimesh.creation.box(extents=(size, size, size))
    axis_rot = {"X": [0.0, 1.0, 0.0, 90.0], "Y": [1.0, 0.0, 0.0, -90.0], "Z": None}
    if t == "Sphere":
        return trimesh.creation.icosphere(radius=float(UsdGeom.Sphere(mesh_prim).GetRadiusAttr().Get()))
    if t in ("Cylinder", "Capsule", "Cone"):
        geom = {"Cylinder": UsdGeom.Cylinder, "Capsule": UsdGeom.Capsule, "Cone": UsdGeom.Cone}[t](mesh_prim)
        r, h = float(geom.GetRadiusAttr().Get()), float(geom.GetHeightAttr().Get())
        if t == "Cylinder":
            m = trimesh.creation.cylinder(radius=r, height=h)
        elif t == "Capsule":
            m = trimesh.creation.capsule(radius=r, height=h)
        else:
            m = trimesh.creation.cone(radius=r, height=h)
            m.apply_translation((0.0, 0.0, -h / 2.0))  # USD cones are center-origin
        rot = axis_rot[str(geom.GetAxisAttr().Get() or "Z")]
        if rot is not None:
            m.apply_transform(trimesh.transformations.rotation_matrix(
                _np.radians(rot[3]), rot[:3]))
        return m
    return None


def extract_prim_mesh(body_prim, stage) -> "object":
    """Concatenate all meshes under a rigid-body prim into one trimesh in the BODY frame.

    Returns:
        A ``trimesh.Trimesh`` (body-frame vertices [m]) or None if no meshes found.
    """
    import trimesh  # noqa: PLC0415
    from pxr import Usd, UsdGeom  # noqa: PLC0415

    cache = UsdGeom.XformCache(Usd.TimeCode.Default())
    inv_body = cache.GetLocalToWorldTransform(body_prim).GetInverse()
    parts = []
    for mesh_prim in _mesh_prims_under(body_prim):
        mesh = _trimesh_from_geom_prim(mesh_prim)
        if mesh is None or len(mesh.vertices) == 0:
            continue
        # full mesh->body transform (scale included); Gf matrices are row-vector, transpose
        # to the column convention trimesh/make_T use
        rel = cache.GetLocalToWorldTransform(mesh_prim) * inv_body
        mesh.apply_transform(np.array(rel, dtype=float).T)
        parts.append(mesh)
    if not parts:
        return None
    return trimesh.util.concatenate(parts) if len(parts) > 1 else parts[0]


def dump_cache(scene, sim, cache_dir: str = config.CACHE_DIR) -> str:
    """Dump body-frame meshes + the scene_state.json manifest from the LIVE settled scene.

    Must run with ``use_fabric=False`` (stale-transform trap) after the scene has settled at
    the static state.

    Returns:
        Path to the manifest.
    """
    import trimesh  # noqa: PLC0415

    from dishsim.transforms import T_inv, make_T  # noqa: PLC0415

    stage = scene.stage
    mesh_dir = os.path.join(cache_dir, MESH_DIR)
    os.makedirs(mesh_dir, exist_ok=True)

    T_w_base = make_T(config.ROBOT_BASE_POS_W, config.ROBOT_BASE_QUAT_W)
    T_base_w = T_inv(T_w_base)
    manifest: dict = {
        "frame_convention": config.FRAME_CONVENTION,
        "config_hash": config_hash(),
        "object_name": config.OBJECT_NAME,
        "statics": {},
    }

    def body_pose_w(articulation, body_name):
        ids, _ = articulation.find_bodies(body_name)
        pos = articulation.data.body_link_pos_w[0, ids[0]].cpu().numpy()
        quat = wxyz_to_xyzw(articulation.data.body_link_quat_w[0, ids[0]].cpu().numpy())
        return make_T(pos, quat)

    def save_mesh(name, mesh):
        path = os.path.join(mesh_dir, f"{name}.obj")
        mesh.export(path)
        return f"{MESH_DIR}/{name}.obj"

    # -- dishwasher bodies (static in v0) ------------------------------------------------------
    dw = scene["dishwasher"]
    env_path = "/World/envs/env_0"
    for body in dishwasher_bodies():
        prim = None
        for cand in stage.Traverse():
            if cand.GetName() == body and str(cand.GetPath()).startswith(f"{env_path}/Dishwasher"):
                prim = cand
                break
        assert prim is not None, f"dishwasher body prim {body} not found"
        mesh = extract_prim_mesh(prim, stage)
        assert mesh is not None, f"no meshes under {body}"
        if body in config.RACK_GEN:
            # earliest Kit-stage guard against a scale/pre-compensation bug: the extracted
            # (USD-round-tripped) rack must match the generator's design-space geometry
            import rack_gen  # noqa: PLC0415  (this folder)

            ref = rack_gen.merged_mesh(rack_gen.build(config.RACK_GEN[body]))
            dev = np.abs(np.asarray(mesh.bounds) - np.asarray(ref.bounds)).max()
            assert dev < 2e-3, f"{body}: extracted bounds deviate {dev * 1e3:.2f} mm from rack_gen"
        T_base_body = T_base_w @ body_pose_w(dw, body)
        manifest["statics"][body] = {
            "mesh": save_mesh(body, mesh),
            "T_base_body": T_base_body.tolist(),
            "coacd": True,
        }

    # -- pedestal + ground (procedural boxes; base frame poses from config) -------------------
    ped = trimesh.creation.box(extents=config.PEDESTAL_SIZE)
    T_base_ped = T_base_w @ make_T(config.PEDESTAL_POS_W, (0, 0, 0, 1))
    manifest["statics"]["pedestal"] = {
        "mesh": save_mesh("pedestal", ped),
        "T_base_body": T_base_ped.tolist(),
        "coacd": False,
    }
    ground = trimesh.creation.box(extents=(4.0, 4.0, 0.02))
    T_base_ground = T_base_w @ make_T((0.4, 0.0, -0.01), (0, 0, 0, 1))
    manifest["statics"]["ground"] = {
        "mesh": save_mesh("ground", ground),
        "T_base_body": T_base_ground.tolist(),
        "coacd": False,
    }

    # -- object mesh (body frame, Kit-free source) ---------------------------------------------
    # every class ships a body-frame OBJ beside its physics USD (the same file
    # planning stack collides) — no live extraction needed for a free object
    obj_mesh = trimesh.load(
        os.path.join(config.ASSETS_DIR, "bosch_props", "meshes", f"{config.ACTIVE_OBJECT}.obj"),
        force="mesh")
    manifest["object"] = {
        "mesh": save_mesh("object", obj_mesh),
        "coacd": True,
    }

    # -- static machine state + scenario (recorded for review; not part of config_hash) -------
    from dishsim import scene as _s  # noqa: PLC0415

    manifest["statics_state"] = _s.statics_report(scene)
    manifest["scenario"] = config.SCENARIO_NAME

    path = os.path.join(cache_dir, MANIFEST)
    with open(path, "w") as f:
        json.dump(manifest, f, indent=2)
    print(f"[INFO] cache manifest written to {path} (hash {manifest['config_hash']})")
    return path