DragMesh-3-Scene / test_cam2.py
Neptune-T's picture
Add files using upload-large-folder tool
327ef01 verified
Raw History Blame Contribute Delete
3.83 kB
#!/usr/bin/env python3
"""Test improved camera: elevation ~0 (camera at part mid-height, not floor),
azimuth along (bbox_center - body_origin) horizontal projection, closer dist.
Measures diff(t0, t15) for several joints of a scene."""
import json
import sys
import mujoco
import numpy as np
SC = sys.argv[1] if len(sys.argv) > 1 else "home_01_kitchen"
MODEL = f"/home/zhanghao/scene/scenesmith_full/outputs/mujoco_scene_{SC}/scene.xml"
TRAJ = f"/home/zhanghao/scene/trajectories/{SC}/scene_trajectories.json"
W, H = 400, 300
def qrot(q, v):
tt = 2.0 * np.cross(q[1:], v)
return v + q[0] * tt + np.cross(q[1:], tt)
def body_bbox(m, d, bid, children, visual_only=True):
mins, maxs = [], []
stack = [bid]
while stack:
b = stack.pop()
for g in range(m.ngeom):
if m.geom_bodyid[g] == b and m.geom(g).type == mujoco.mjtGeom.mjGEOM_MESH:
gn = m.geom(g).name or ""
if visual_only and ("collision" in gn or gn.endswith("_com")):
continue
mid = m.geom_dataid[g]
va, vn = m.mesh_vertadr[mid], m.mesh_vertnum[mid]
verts = m.mesh_vert[va: va + vn].reshape(-1, 3)
w = qrot(m.geom_quat[g], verts) + m.geom_pos[g]
w = d.xpos[b] + w @ d.xmat[b].reshape(3, 3).T
mins.append(w.min(0)); maxs.append(w.max(0))
stack.extend(children.get(b, []))
return (np.min(mins, 0), np.max(maxs, 0)) if mins else None
def make_camera(m, d, bid, children):
bbox = body_bbox(m, d, bid, children)
if bbox is None:
bbox = body_bbox(m, d, bid, children, visual_only=False)
if bbox is None:
pos = d.body(bid).xpos
bbox = (pos - 0.5, pos + 0.5)
lo, hi = bbox
center = (lo + hi) / 2
size = max((hi - lo).max(), 0.4)
cam = mujoco.MjvCamera()
cam.lookat = center
cam.distance = size * 1.8
# face the part from its opening/extension side (away from body origin)
bpos = d.body(bid).xpos
dxy = center[:2] - bpos[:2]
if np.linalg.norm(dxy) < 0.05:
az = 45.0
else:
az = float(np.degrees(np.arctan2(dxy[1], dxy[0])))
cam.azimuth = az
cam.elevation = 0.0 # camera at part mid-height; avoids floor-level views
return cam, center, size
m = mujoco.MjModel.from_xml_path(MODEL)
d = mujoco.MjData(m)
mujoco.mj_forward(m, d)
m.vis.global_.offwidth = W
m.vis.global_.offheight = H
tj = json.load(open(TRAJ))
joints = [(j, e, np.asarray(e["traj_abs"], float))
for j, e in tj.get("joints", {}).items()
if np.abs(np.asarray(e.get("traj_abs", []), float)).max() > 1e-9]
children = {}
for b in range(m.nbody):
children.setdefault(m.body_parentid[b], []).append(b)
rend = mujoco.Renderer(m, H, W)
n_vis = 0
for idx, (jname, entry, t) in enumerate(joints[:8]):
jid = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_JOINT, jname)
if jid < 0:
continue
bid = m.jnt_bodyid[jid]
addr = m.jnt_qposadr[jid]
lo, hi = entry["range"]
t0 = float(np.clip(t[0], lo, hi))
d.qpos[addr] = t0
mujoco.mj_forward(m, d)
cam, center, size = make_camera(m, d, bid, children)
rend.update_scene(d, camera=cam)
f0 = rend.render()
d.qpos[addr] = float(np.clip(t[15], lo, hi))
mujoco.mj_forward(m, d)
rend.update_scene(d, camera=cam)
f15 = rend.render()
dm = np.abs(f15.astype(np.int16) - f0.astype(np.int16)).max(axis=2)
pct = 100 * (dm > 30).mean()
camz = center[2] - cam.distance * np.sin(np.radians(25)) if False else None
print(f"joint_{idx:02d} {jname.split('_E_')[-1][:40]:42s} az={cam.azimuth:6.1f} "
f"dist={cam.distance:.2f} lookat_z={center[2]:.2f} diff={pct:.1f}%")
if pct > 0.5:
n_vis += 1
rend.close()
print(f"VISIBLE: {n_vis}/{min(len(joints), 8)}")