File size: 10,118 Bytes
75db9a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import json

from isaaclab.app import AppLauncher

# CLI args
parser = argparse.ArgumentParser(description="Load many GLB objects from a JSON file.")
parser.add_argument("--json_path", type=str, default="layouts/desk_4.json",
                    help="Path to object list JSON file.")
parser.add_argument("--num_envs", type=int, default=1)
AppLauncher.add_app_launcher_args(parser)
args_cli = parser.parse_args()

# Launch Isaac Lab
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app

import torch
import isaaclab.sim as sim_utils
from isaaclab.scene import InteractiveScene, InteractiveSceneCfg
from isaaclab.assets import AssetBaseCfg
from isaaclab.utils.math import quat_from_euler_xyz

# USD / Omni imports
import omni.usd
from pxr import Usd, UsdGeom, Gf


# ==========================================================
# Scene configuration
# ==========================================================
class SimpleSceneCfg(InteractiveSceneCfg):
    ground = AssetBaseCfg(
        prim_path="/World/defaultGroundPlane",
        spawn=sim_utils.GroundPlaneCfg(),
    )
    dome_light = AssetBaseCfg(
        prim_path="/World/Light",
        spawn=sim_utils.DomeLightCfg(intensity=3000.0),
    )


# ==========================================================
# Helper: bbox computation  (world space, but此时父节点是 identity)
# ==========================================================
def compute_bbox_center_and_size(prim_path: str):
    """
    计算 prim_path 对应 prim(及其所有子节点)的整体包围盒几何中心和尺寸。
    注意:这里用的是 WorldBound,但如果父节点是 identity,那么 world/local 一致。
    """
    ctx = omni.usd.get_context()
    stage = ctx.get_stage()
    prim = stage.GetPrimAtPath(prim_path)

    if not prim.IsValid():
        raise RuntimeError(f"[compute_bbox_center_and_size] Invalid prim path: {prim_path}")

    bbox_cache = UsdGeom.BBoxCache(
        Usd.TimeCode.Default(),
        includedPurposes=[
            UsdGeom.Tokens.default_,
            UsdGeom.Tokens.render,
            UsdGeom.Tokens.proxy,
        ],
        useExtentsHint=False,
    )

    world_bbox = bbox_cache.ComputeWorldBound(prim)
    aligned_range = world_bbox.ComputeAlignedRange()
    mn = aligned_range.GetMin()
    mx = aligned_range.GetMax()

    size = mx - mn           # (sx, sy, sz)
    center = (mn + mx) * 0.5 # 几何中心
    return center, size



def print_final_bbox(prim_path: str, app, label=""):
    """
    计算 prim_path 对应的完整物体(含所有子 Mesh)在世界坐标系下的最终包围盒尺寸。
    """
    # 多次 update,确保 transform 已应用
    app.update()
    app.update()

    stage = omni.usd.get_context().get_stage()
    prim = stage.GetPrimAtPath(prim_path)
    if not prim.IsValid():
        print(f"[WARN] invalid prim for bbox: {prim_path}")
        return

    bbox_cache = UsdGeom.BBoxCache(
        Usd.TimeCode.Default(),
        includedPurposes=[
            UsdGeom.Tokens.default_,
            UsdGeom.Tokens.render,
            UsdGeom.Tokens.proxy,
        ],
        useExtentsHint=False,
    )

    world_bbox = bbox_cache.ComputeWorldBound(prim)
    aligned = world_bbox.ComputeAlignedRange()

    mn = aligned.GetMin()
    mx = aligned.GetMax()
    size = mx - mn

    print(f"\n====== Final BBox for {label or prim_path} ======")
    print(f"  Min  = ({mn[0]:.4f}, {mn[1]:.4f}, {mn[2]:.4f})")
    print(f"  Max  = ({mx[0]:.4f}, {mx[1]:.4f}, {mx[2]:.4f})")
    print(f"  Size = ({size[0]:.4f}, {size[1]:.4f}, {size[2]:.4f})")
    print("==========================================\n")



# ==========================================================
# 核心:让 /World/obj_name 的原点 = GLB 几何的 bbox “中心”或“底面中心”
#   - pivot_mode="bottom": JSON.position = bbox 底面中心在世界坐标的位置(你当前的语义)
#   - pivot_mode="center": JSON.position = bbox 几何中心在世界坐标的位置
# ==========================================================
def spawn_glb_from_dict(obj: dict, app, pivot_mode: str = "bottom"):
    """
    期望 JSON 字段:
      - object_name: str
      - glb_path: str
      - position: [x, y, z]
          * pivot_mode="bottom":  表示 bbox 底面中心的世界坐标
          * pivot_mode="center":  表示 bbox 几何中心的世界坐标
      - rotation_deg: [rx, ry, rz] (绕“pivot 点”的欧拉角, XYZ, 度)
      - size: [sx, sy, sz]         (目标 bbox 尺寸, 世界单位)
    """
    if pivot_mode not in ("bottom", "center"):
        raise ValueError(f"Unsupported pivot_mode: {pivot_mode}. Use 'bottom' or 'center'.")

    obj_name = obj["object_name"]
    glb_path = obj["glb_path"]
    pos = obj.get("position", [0.0, 0.0, 0.0])
    rot_deg = obj.get("rotation_deg", [0.0, 0.0, 0.0])
    target_size = obj.get("size", None)
    if target_size is None:
        raise RuntimeError(f"[{obj_name}] `size` must be provided because position is defined on bbox.")

    pos = [float(pos[0]), float(pos[1]), float(pos[2])]
    target_size = [float(target_size[0]), float(target_size[1]), float(target_size[2])]

    stage = omni.usd.get_context().get_stage()

    # parent = /World/obj_name, child = /World/obj_name/Mesh
    parent_path = f"/World/{obj_name}"
    child_path = f"{parent_path}/Mesh"

    # 确保 parent 存在(Xform)
    stage.DefinePrim(parent_path, "Xform")

    # 1) 以 identity transform 载入 GLB 到 child_path
    glb_cfg = sim_utils.UsdFileCfg(
        usd_path=glb_path,
        scale=[1.0, 1.0, 1.0],
    )
    glb_cfg.func(
        prim_path=child_path,
        cfg=glb_cfg,
        translation=None,
        orientation=None,
    )

    # 等 USD/PhysX 真正把 mesh load 完成(多次 update 防止 bbox 还没更新)
    app.update()
    app.update()

    # 2) 在 child (Mesh) 上计算原始整体 bbox(多个子 mesh 会自动合在一起)
    orig_center, orig_size = compute_bbox_center_and_size(child_path)

    eps = 1e-6
    sx = target_size[0] / (orig_size[0] if abs(orig_size[0]) > eps else 1.0)
    sy = target_size[1] / (orig_size[1] if abs(orig_size[1]) > eps else 1.0)
    sz = target_size[2] / (orig_size[2] if abs(orig_size[2]) > eps else 1.0)
    scale_vec = Gf.Vec3d(sx, sy, sz)

    # -------- 关键:确定“pivot”在原始 bbox 中的位置 --------
    if pivot_mode == "center":
        # 几何中心
        pivot_local_before_scale = Gf.Vec3d(
            float(orig_center[0]),
            float(orig_center[1]),
            float(orig_center[2]),
        )
    else:
        # bbox 底面中心: (cx, cy, cz - height/2)
        pivot_local_before_scale = Gf.Vec3d(
            float(orig_center[0]),
            float(orig_center[1]),
            float(orig_center[2] - orig_size[2] * 0.5),
        )

    # 缩放后,pivot 相对原点的向量也要按 scale 缩放
    pivot_local_after_scale = Gf.Vec3d(
        pivot_local_before_scale[0] * sx,
        pivot_local_before_scale[1] * sy,
        pivot_local_before_scale[2] * sz,
    )

    # 3) 在 child (Mesh) 上:
    #    先 scale 再 translate(-pivot_local_after_scale),
    #    让「缩放后的 bbox pivot(几何中心或底面中心)」变成 (0,0,0)
    child_prim = stage.GetPrimAtPath(child_path)
    child_xform = UsdGeom.Xformable(child_prim)
    child_xform.ClearXformOpOrder()
    s_child = child_xform.AddScaleOp()
    s_child.Set(scale_vec)
    t_child = child_xform.AddTranslateOp()
    t_child.Set(-pivot_local_after_scale)

    # 4) parent (/World/obj_name) 上:
    #    只做绕原点的旋转 + 平移到世界坐标的 position(对应 pivot 在世界的位置)
    rot_deg_t = torch.tensor(rot_deg, dtype=torch.float32)
    rot_rad = torch.deg2rad(rot_deg_t)
    quat = quat_from_euler_xyz(
        rot_rad[0:1],
        rot_rad[1:2],
        rot_rad[2:3],
    )[0].tolist()  # (w, x, y, z)

    w, x, y, z = quat
    parent_prim = stage.GetPrimAtPath(parent_path)
    parent_xform = UsdGeom.Xformable(parent_prim)
    parent_xform.ClearXformOpOrder()

    # o_op = parent_xform.AddOrientOp()
    # o_op.Set(Gf.Quatf(float(w), Gf.Vec3f(float(x), float(y), float(z))))

    t_op = parent_xform.AddTranslateOp()
    t_op.Set(Gf.Vec3d(pos[0], pos[1], pos[2]))

    # 打印信息方便你 debug
    mode_desc = "bbox center" if pivot_mode == "center" else "bbox bottom-center"
    print(f"[Spawned] {obj_name}")
    print(f"  glb_path      = {glb_path}")
    print(f"  pivot_mode    = {pivot_mode} ({mode_desc})")
    print(f"  json position = {pos}  (pivot in world)")
    print(f"  orig_size     = ({orig_size[0]:.4f}, {orig_size[1]:.4f}, {orig_size[2]:.4f})")
    print(f"  target_size   = ({target_size[0]:.4f}, {target_size[1]:.4f}, {target_size[2]:.4f})")
    print(f"  scale_vec     = ({sx:.4f}, {sy:.4f}, {sz:.4f})")

    print_final_bbox(parent_path, app, label=obj_name)
    # import ipdb; ipdb.set_trace()

    print("\n")



# ==========================================================
# Main
# ==========================================================
def main():
    # Load JSON file
    with open(args_cli.json_path, "r") as f:
        objects = json.load(f)

    print(f"Loaded {len(objects)} objects from JSON.")

    # Simulation context
    sim_cfg = sim_utils.SimulationCfg(device=args_cli.device)
    sim = sim_utils.SimulationContext(sim_cfg)
    sim.set_camera_view([2.5, 2.5, 3.0], [0.0, 0.0, 0.0])

    # 先 spawn GLB,再建地面和光
    for obj in objects:
        # 如果你想按“几何中心”对齐,把下面这一行改成:
        # spawn_glb_from_dict(obj, simulation_app, pivot_mode="center")
        spawn_glb_from_dict(obj, simulation_app, pivot_mode="bottom")

    scene_cfg = SimpleSceneCfg(args_cli.num_envs, env_spacing=2.0)
    scene = InteractiveScene(scene_cfg)

    sim.reset()
    print("[INFO] Simulation started...")

    sim_dt = sim.get_physics_dt()
    while simulation_app.is_running():
        sim.step()
        scene.update(sim_dt)


if __name__ == "__main__":
    main()
    simulation_app.close()