File size: 9,440 Bytes
58771fe
eb0ddd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Play OneHundredStyle-G1 clips on the Unitree G1 with MuJoCo.

    python scripts/visualize.py                                # browse all 810 clips
    python scripts/visualize.py --style Zombie                 # all takes of one style
    python scripts/visualize.py --take FW                      # forward walks of every style
    python scripts/visualize.py --clip Zombie_FW Chicken_FR    # chosen clips
    python scripts/visualize.py --clip Zombie_FW --mirror      # its left-right mirror image
    python scripts/visualize.py --clip Zombie_FW --seconds 6 --record zombie.mp4   # offscreen video

Keys:  SPACE pause | RIGHT/N next clip | LEFT/B previous clip | R restart
       UP/DOWN playback speed | close the window to quit
"""
from __future__ import annotations

import argparse
import time
from pathlib import Path

import mujoco
import numpy as np

from style100 import FPS, JOINT_NAMES, ROOT, TAKES, load_clip, load_metadata

KEY_SPACE, KEY_RIGHT, KEY_LEFT, KEY_DOWN, KEY_UP = 32, 262, 263, 264, 265  # GLFW key codes
END_PAUSE_S = 0.5  # hold on the last frame before a clip loops


class Player:
    """Holds the playlist and writes one frame of the current clip into ``data``."""

    def __init__(self, model, data, clips, root: Path, mirrored: bool = False):
        self.model, self.data, self.clips, self.root, self.mirrored = model, data, clips, root, mirrored
        self.qadr = [model.joint(name).qposadr[0] for name in JOINT_NAMES]
        self.index = self.frame = 0
        self.paused, self.speed = False, 1.0
        self.keys: list[int] = []
        self._hold_until = 0.0
        self.load(0)

    def load(self, index: int):
        self.index = index % len(self.clips)
        self.row = self.clips[self.index]
        clip = load_clip(self.root / self.row["file"], mirrored=self.mirrored)
        self.qpos = np.zeros((len(clip), self.model.nq))
        self.qpos[:, 0:3], self.qpos[:, 3:7], self.qpos[:, self.qadr] = clip.root_pos, clip.root_quat, clip.joint_pos
        w, x, y, z = clip.root_quat[0]
        self.yaw_deg = float(np.degrees(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))))
        self.frame, self._hold_until = 0, 0.0
        self.apply()
        print(f"[{self.index + 1}/{len(self.clips)}] {self.row['id']}{' (mirrored)' if self.mirrored else ''}  "
              f"{self.row['motion']}  {self.row['n_frames']} frames ({self.row['duration_s']} s)  "
              f"{self.row['description']}")

    def apply(self):
        self.data.qpos[:] = self.qpos[self.frame]
        mujoco.mj_forward(self.model, self.data)

    def step(self):
        """Advance one frame; loop the clip after a short hold on its last frame."""
        now = time.monotonic()
        if self.paused or now < self._hold_until:
            return
        self.frame += 1
        if self.frame >= len(self.qpos):
            self.frame, self._hold_until = 0, now + END_PAUSE_S

    def label(self) -> tuple[str, str]:
        r = self.row
        return (f"{r['id']}{' (mirrored)' if self.mirrored else ''}  {r['motion']}\nframe {self.frame} / {r['n_frames'] - 1}",
                f"{self.index + 1} of {len(self.clips)}\nx{self.speed:.2f}")

    def handle_keys(self) -> bool:
        """Apply queued key presses; returns True when the clip changed."""
        before = self.index
        while self.keys:
            key = self.keys.pop(0)
            if key == KEY_SPACE:
                self.paused = not self.paused
            elif key in (KEY_RIGHT, ord("N")):
                self.load(self.index + 1)
            elif key in (KEY_LEFT, ord("B")):
                self.load(self.index - 1)
            elif key == ord("R"):
                self.frame = 0
            elif key == KEY_UP:
                self.speed = min(self.speed * 1.5, 8.0)
            elif key == KEY_DOWN:
                self.speed = max(self.speed / 1.5, 0.125)
        return self.index != before


def aim(cam, model, player: Player, args):
    """Track the pelvis from a fixed angle relative to the robot's heading in the first frame."""
    cam.type = mujoco.mjtCamera.mjCAMERA_TRACKING
    cam.trackbodyid = model.body("pelvis").id
    cam.distance, cam.elevation = args.distance, args.elevation
    cam.azimuth = player.yaw_deg + args.azimuth


def play(model, data, player: Player, args):
    import mujoco.viewer

    player.speed = args.speed
    with mujoco.viewer.launch_passive(model, data, key_callback=player.keys.append,
                                      show_left_ui=False, show_right_ui=False) as viewer:
        aim(viewer.cam, model, player, args)
        while viewer.is_running():
            tic = time.perf_counter()
            with viewer.lock():
                if player.handle_keys():
                    aim(viewer.cam, model, player, args)
                player.step()
                player.apply()
            if hasattr(viewer, "set_texts"):  # mujoco >= 3.2
                viewer.set_texts((None, None, *player.label()))
            viewer.sync()
            time.sleep(max(0.0, 1.0 / (FPS * player.speed) - (time.perf_counter() - tic)))


def record(model, data, player: Player, args):
    """Render the playlist offscreen; ``--speed`` only changes the output frame rate."""
    import imageio

    model.vis.global_.offwidth = max(model.vis.global_.offwidth, args.width)
    model.vis.global_.offheight = max(model.vis.global_.offheight, args.height)
    fps = FPS * args.speed / args.every
    is_gif = args.record.suffix.lower() == ".gif"
    options = {"duration": 1000.0 / fps, "loop": 0} if is_gif else {"fps": fps, "quality": 8}
    cam = mujoco.MjvCamera()
    with mujoco.Renderer(model, args.height, args.width) as renderer, \
            imageio.get_writer(args.record, **options) as writer:
        for index in range(len(player.clips)):
            player.load(index)
            aim(cam, model, player, args)
            first = min(int(round(args.start * FPS)), len(player.qpos) - 1)
            last = len(player.qpos) if args.seconds is None else min(len(player.qpos), first + int(round(args.seconds * FPS)))
            for frame in range(first, last, args.every):
                player.frame = frame
                player.apply()
                renderer.update_scene(data, cam)
                writer.append_data(renderer.render())
    print(f"wrote {args.record} ({len(player.clips)} clips, {fps:g} fps)")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--root", type=Path, default=ROOT, help="dataset folder (default: the one this script is in)")
    ap.add_argument("--scene", type=Path, default=None, help="MuJoCo XML (default: robot/scene.xml)")
    ap.add_argument("--clip", nargs="+", metavar="ID", help="play only these clips, e.g. Zombie_FW")
    ap.add_argument("--style", nargs="+", metavar="STYLE", help="play only these styles, e.g. Zombie Chicken")
    ap.add_argument("--take", nargs="+", choices=list(TAKES), help="play only these takes, e.g. FW FR")
    ap.add_argument("--mirror", action="store_true", help="play the left-right mirror image of every clip")
    ap.add_argument("--speed", type=float, default=1.0, help="playback speed factor (default 1.0)")
    ap.add_argument("--azimuth", type=float, default=135.0, help="camera yaw relative to the initial heading [deg]")
    ap.add_argument("--elevation", type=float, default=-15.0, help="camera elevation [deg]")
    ap.add_argument("--distance", type=float, default=3.2, help="camera distance to the pelvis [m]")
    ap.add_argument("--record", type=Path, metavar="FILE", help="render to FILE (.mp4 or .gif) instead of opening a window")
    ap.add_argument("--start", type=float, default=0.0, help="when recording, start this many seconds into each clip")
    ap.add_argument("--seconds", type=float, default=None, help="when recording, length to render per clip (default: all)")
    ap.add_argument("--every", type=int, default=1, help="when recording, keep every N-th frame (default 1)")
    ap.add_argument("--width", type=int, default=1280, help="recording width [px]")
    ap.add_argument("--height", type=int, default=720, help="recording height [px]")
    args = ap.parse_args()

    clips = load_metadata(args.root)
    if args.style:
        known = {c["style"] for c in clips}
        missing = [s for s in args.style if s not in known]
        if missing:
            raise SystemExit(f"no such style: {', '.join(missing)}")
        clips = [c for c in clips if c["style"] in args.style]
    if args.take:
        clips = [c for c in clips if c["take"] in args.take]
    if args.clip:
        by_id = {c["id"]: c for c in clips}
        missing = [i for i in args.clip if i not in by_id]
        if missing:
            raise SystemExit(f"no such clip in the selection: {', '.join(missing)}")
        clips = [by_id[i] for i in args.clip]
    if not clips:
        raise SystemExit("the selection is empty")
    if args.record and not (args.clip or args.style):
        raise SystemExit("--record needs the clips to render, e.g. --clip Zombie_FW")

    scene = args.scene or args.root / "robot" / "scene.xml"
    model = mujoco.MjModel.from_xml_path(str(scene))
    data = mujoco.MjData(model)
    player = Player(model, data, clips, args.root, mirrored=args.mirror)
    (record if args.record else play)(model, data, player, args)


if __name__ == "__main__":
    main()