File size: 10,394 Bytes
390e994
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Play FiveHundredShots clips on the G1 + racket model with MuJoCo.

    python scripts/visualize.py                              # browse all 500 shots
    python scripts/visualize.py --stroke backhand            # only backhands
    python scripts/visualize.py --shot shot_0042 shot_0107   # chosen shots
    python scripts/visualize.py --shot shot_0042 --record shot_0042.mp4   # offscreen video

Markers:  yellow = racket sweet spot now | red = sweet spot at ball contact | green = hit direction
Keys:     SPACE pause | RIGHT/N next shot | LEFT/B previous shot | R restart | H jump to contact
          V markers on/off | 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 fivehundredshots import FPS, JOINT_NAMES, ROOT, 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 shot loops

YELLOW, RED, GREEN = (0.95, 0.85, 0.20, 1.0), (0.95, 0.25, 0.25, 1.0), (0.20, 0.80, 0.30, 1.0)


def rotation_z_to(direction) -> np.ndarray:
    """Rotation matrix taking +z onto ``direction`` (MuJoCo arrows point along their z axis)."""
    d = np.asarray(direction, float) / np.linalg.norm(direction)
    v, c = np.cross([0.0, 0.0, 1.0], d), d[2]
    if np.linalg.norm(v) < 1e-9:
        return np.eye(3) if c > 0 else np.diag([1.0, -1.0, -1.0])
    vx = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
    return np.eye(3) + vx + vx @ vx / (1.0 + c)


def add_geom(scene, geom_type, size, pos, mat, rgba):
    if scene.ngeom < scene.maxgeom:
        mujoco.mjv_initGeom(scene.geoms[scene.ngeom], geom_type, np.asarray(size, float), np.asarray(pos, float),
                            np.asarray(mat, float).flatten(), np.asarray(rgba, np.float32))
        scene.ngeom += 1


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

    def __init__(self, model, data, shots, root: Path):
        self.model, self.data, self.shots, self.root = model, data, shots, root
        self.qadr = [model.joint(name).qposadr[0] for name in JOINT_NAMES]
        self.site = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, "racket_sweetspot")
        self.index = self.frame = 0
        self.paused, self.speed, self.show_markers = False, 1.0, True
        self.keys: list[int] = []
        self._hold_until = 0.0
        self.load(0)

    def load(self, index: int):
        self.index = index % len(self.shots)
        self.shot = self.shots[self.index]
        clip = load_clip(self.root / self.shot["file"])
        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
        self.frame, self._hold_until = 0, 0.0
        self.apply()
        print(f"[{self.index + 1}/{len(self.shots)}] {self.shot['id']}  {self.shot['stroke']}  "
              f"{self.shot['n_frames']} frames, contact at frame {self.shot['hit_frame']}")

    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 shot 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 hit_yaw_deg(self) -> float:
        d = self.shot["hit_direction_world"]
        return float(np.degrees(np.arctan2(d[1], d[0])))

    def label(self) -> tuple[str, str]:
        s = self.shot
        return (f"{s['id']}  {s['stroke']}\nframe {self.frame} / {s['n_frames'] - 1}",
                f"{self.index + 1} of {len(self.shots)}\ncontact at {s['hit_frame']}   x{self.speed:.2f}")

    def draw_markers(self, scene):
        """Append the sweet-spot spheres and the hit-direction arrow to an ``MjvScene``."""
        if not self.show_markers:
            return
        hit, direction = self.shot["sweetspot_hit_world"], self.shot["hit_direction_world"]
        if self.site >= 0:
            add_geom(scene, mujoco.mjtGeom.mjGEOM_SPHERE, [0.022] * 3, self.data.site_xpos[self.site], np.eye(3), YELLOW)
        add_geom(scene, mujoco.mjtGeom.mjGEOM_SPHERE, [0.030] * 3, hit, np.eye(3), RED)
        add_geom(scene, mujoco.mjtGeom.mjGEOM_ARROW, [0.012, 0.012, 0.42], hit, rotation_z_to(direction), GREEN)

    def handle_keys(self) -> bool:
        """Apply queued key presses; returns True when the shot 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 == ord("H"):
                self.frame, self.paused = self.shot["hit_frame"], True
            elif key == ord("V"):
                self.show_markers = not self.show_markers
            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 shot's hit direction."""
    cam.type = mujoco.mjtCamera.mjCAMERA_TRACKING
    cam.trackbodyid = model.body("pelvis").id
    cam.distance, cam.elevation = args.distance, args.elevation
    cam.azimuth = player.hit_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()
                viewer.user_scn.ngeom = 0
                player.draw_markers(viewer.user_scn)
            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 every frame of 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.shots)):
            player.load(index)
            aim(cam, model, player, args)
            for frame in range(0, len(player.qpos), args.every):
                player.frame = frame
                player.apply()
                renderer.update_scene(data, cam)
                player.draw_markers(renderer.scene)
                writer.append_data(renderer.render())
    print(f"wrote {args.record} ({len(player.shots)} shots, {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_tennis.xml)")
    ap.add_argument("--shot", nargs="+", metavar="ID", help="play only these shots, e.g. shot_0042")
    ap.add_argument("--stroke", choices=("forehand", "backhand"), help="play only this stroke type")
    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 hit direction [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("--no-markers", action="store_true", help="hide the sweet-spot markers and hit arrow")
    ap.add_argument("--record", type=Path, metavar="FILE", help="render to FILE (.mp4 or .gif) instead of opening a window")
    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()

    shots = load_metadata(args.root)
    if args.stroke:
        shots = [s for s in shots if s["stroke"] == args.stroke]
    if args.shot:
        by_id = {s["id"]: s for s in shots}
        missing = [i for i in args.shot if i not in by_id]
        if missing:
            raise SystemExit(f"no such shot{' with stroke ' + args.stroke if args.stroke else ''}: {', '.join(missing)}")
        shots = [by_id[i] for i in args.shot]
    if args.record and not args.shot:
        raise SystemExit("--record needs the shots to render, e.g. --shot shot_0000 shot_0007")

    scene = args.scene or args.root / "robot" / "scene_tennis.xml"
    model = mujoco.MjModel.from_xml_path(str(scene))
    data = mujoco.MjData(model)
    player = Player(model, data, shots, args.root)
    player.show_markers = not args.no_markers
    (record if args.record else play)(model, data, player, args)


if __name__ == "__main__":
    main()