File size: 6,630 Bytes
327ef01 | 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 | #!/usr/bin/env python3
"""Render demo assets for every exported scene with DragMesh trajectories.
Runs on the server host (dragmesh_env, mujoco EGL offscreen):
python render_all.py [scene-substring-filter]
Outputs to outputs/demo/<scene>/... (grid pngs + per-scene mp4 + report)
"""
import json
import os
import sys
from pathlib import Path
import imageio.v2 as imageio
import mujoco
import numpy as np
FRAMES = (0, 4, 8, 12, 15)
W, H = 400, 300
FPS = 8
ANIM_FRAMES = 16
OUT_ROOT = Path("/home/zhanghao/scene/scenesmith_full/outputs/demo")
TRAJ_ROOT = Path("/home/zhanghao/scene/trajectories")
def qpos_addr(model, name):
jid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT, name)
if jid < 0:
return None
return model.jnt_qposadr[jid]
def children_map(model):
ch = {}
for b in range(model.nbody):
ch.setdefault(model.body_parentid[b], []).append(b)
return ch
def body_bbox(model, data, bid, children):
mins, maxs = [], []
stack = [bid]
while stack:
b = stack.pop()
for g in range(model.ngeom):
if model.geom_bodyid[g] == b and model.geom(g).type == mujoco.mjtGeom.mjGEOM_MESH:
gname = model.geom(g).name or ""
if "_visual_visual_mesh" not in gname and "visual_mesh" not in gname:
continue
mesh = model.mesh(model.geom_dataid[g])
verts = mesh.vert.reshape(-1, 3)
world = data.xpos[b] + verts @ data.xmat[b].reshape(3, 3).T
mins.append(world.min(0))
maxs.append(world.max(0))
stack.extend(children.get(b, []))
if not mins:
return None
return np.min(mins, 0), np.max(maxs, 0)
def make_camera(model, data, bname, children):
bid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, bname)
bbox = body_bbox(model, data, bid, children)
if bbox is None:
pos = data.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 * 2.0
cam.azimuth = 0.0
cam.elevation = -25.0
return cam, size
def render_frames(model, data, rend, cam, addr, traj, lo, hi, frames):
imgs = []
for f in frames:
v = float(np.clip(traj[f], lo, hi))
data.qpos[addr] = v
mujoco.mj_forward(model, data)
rend.update_scene(data, camera=cam)
imgs.append(rend.render())
return imgs
def collect_joints(traj_json):
out = []
for jname, entry in traj_json.get("joints", {}).items():
t = entry.get("traj_abs")
if not t:
continue
t = np.asarray(t, float)
if float(np.abs(t).max()) < 1e-9:
continue
out.append((jname, entry, t))
return out
def main():
filt = sys.argv[1] if len(sys.argv) > 1 else None
base = Path("/home/zhanghao/scene/scenesmith_full/outputs")
scenes = sorted(base.glob("mujoco_scene_home_*"))
if not scenes:
scenes = sorted(base.glob("mujoco_scene_*"))
if filt:
scenes = [s for s in scenes if filt in s.name]
print(f"{len(scenes)} scenes: {[s.name for s in scenes]}")
OUT_ROOT.mkdir(parents=True, exist_ok=True)
report = []
for sc in scenes:
sname = sc.name.replace("mujoco_scene_", "")
traj_dir = TRAJ_ROOT / sname / "scene_trajectories.json"
if not traj_dir.exists():
print(f"[{sname}] no trajectories, skip")
continue
with open(traj_dir) as f:
traj_json = json.load(f)
joints = collect_joints(traj_json)
if not joints:
print(f"[{sname}] no moving joints")
continue
model = mujoco.MjModel.from_xml_path(str(sc / "scene.xml"))
data = mujoco.MjData(model)
mujoco.mj_forward(model, data)
children = children_map(model)
s_out = OUT_ROOT / sname
s_out.mkdir(parents=True, exist_ok=True)
# offscreen EGL renderer (MUJOCO_GL=egl), strip of 5 frames wide
canvas_w = W * 5
model.vis.global_.offwidth = canvas_w
model.vis.global_.offheight = H
rend = mujoco.Renderer(model, H, canvas_w)
joint_meta = []
for idx, (jname, entry, t) in enumerate(joints[:6]):
addr = qpos_addr(model, jname)
if addr is None:
continue
jid = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT, jname)
bname = model.body(model.jnt_bodyid[jid]).name
cam, size = make_camera(model, data, bname, children)
lo, hi = entry.get("range", [-size * 2, size * 2])
imgs = render_frames(model, data, rend, cam, addr, t, lo, hi, FRAMES)
row = np.concatenate(imgs, axis=1)
imageio.imwrite(str(s_out / f"joint_{idx:02d}.png"), row)
joint_meta.append({
"joint": jname, "body": bname,
"range": [float(lo), float(hi)],
"max_abs": float(np.abs(t).max()),
"type": entry.get("joint_type", entry.get("type", "?")),
})
# movie: 16 frames, camera orbits slightly
frames = list(range(ANIM_FRAMES))
vid_imgs = []
cam0, size0 = make_camera(model, data, model.body(model.jnt_bodyid[
mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT, joints[0][0])]).name, children)
base_az = cam0.azimuth
for f in frames:
cam = mujoco.MjvCamera()
cam.lookat = cam0.lookat
cam.distance = cam0.distance
cam.azimuth = base_az + (f / (ANIM_FRAMES - 1)) * 60.0
cam.elevation = cam0.elevation
addr = qpos_addr(model, joints[0][0])
lo, hi = joints[0][1].get("range", [-size0 * 2, size0 * 2])
imgs = render_frames(model, data, rend, cam, addr, joints[0][2], lo, hi, [f])
vid_imgs.append(imgs[0])
mp4 = str(s_out / f"{sname}.mp4")
imageio.mimsave(mp4, vid_imgs, fps=FPS)
rend.close()
report.append({
"scene": sname,
"n_joints": len(joint_meta),
"joints": joint_meta,
"mp4": f"demo/{sname}/{sname}.mp4",
"stills": [f"demo/{sname}/joint_{i:02d}.png" for i in range(len(joint_meta))],
})
print(f"[{sname}] {len(joint_meta)} joints, mp4 done")
with open(OUT_ROOT / "report.json", "w") as f:
json.dump(report, f, indent=2)
print("ALL_RENDER_DONE", len(report))
if __name__ == "__main__":
main()
|