Source code for joltsim.viewer.server

from __future__ import annotations

import asyncio
import json
import mimetypes
import struct
import threading
import time
import webbrowser
from http import HTTPStatus
from pathlib import Path
from typing import Any, Callable, Optional, Set

import numpy as np

_STATIC_DIR = Path(__file__).resolve().parent / "static"
_HEADER_FMT = "<4sIfffBB2xIIIIII"
_HEADER_MAGIC = b"JSV1"


def _ensure_websockets():
    try:
        import websockets  # noqa: F401
        from websockets.asyncio.server import serve  # noqa: F401
        return serve
    except ImportError as exc:
        raise ImportError(
            "joltsim.viewer requires 'websockets>=13.0'. "
            "Install with: pip install 'joltsim[ui]'"
        ) from exc


[docs] class ViewerServer: """Single-port HTTP + WebSocket server streaming World/VecWorld state at 60 FPS.""" def __init__( self, world: Any, host: str = "127.0.0.1", port: int = 8765, dt: float = 1.0 / 60.0, substeps: int = 4, title: str = "JoltSim Studio", ray_provider: Optional[Callable[[], tuple[np.ndarray, np.ndarray]]] = None, ) -> None: self.world = world self.host = host self.port = port self.dt = float(dt) self.substeps = int(substeps) self.title = title self.ray_provider = ray_provider self.is_vec = hasattr(world, "num_envs") self.num_envs = int(world.num_envs) if self.is_vec else 1 self.paused = False self.speed = 1.0 self.sim_time = 0.0 self.frame_id = 0 self.step_requested = False self.show_contacts = True self.show_rays = True self.show_soft_bodies = True self.view_mode = "grid" if (self.is_vec and self.num_envs > 1) else "single" self.selected_env = 0 self.max_grid_envs = 16 self._snapshot: Optional[Any] = None self._clients: Set[Any] = set() self._lock = threading.Lock() self._stop_event: Optional[asyncio.Event] = None self._loop: Optional[asyncio.AbstractEventLoop] = None self._thread: Optional[threading.Thread] = None self._actual_port = port self._last_sps_time = time.perf_counter() self._sps_steps = 0 self._current_sps = 0.0 self._step_accum = 0.0 self._pick_phase = 0 self._pick_phase_applied = 0 self._pick_timer = 0.0 self._pick_step_count = 0 self._pick_target = np.array([0.45, 0.0, 0.022], dtype=np.float32) self._pick_quat = np.array([0.9239, -0.3827, 0.0, 0.0], dtype=np.float32) self._debug_lines: dict[int, tuple[float, float, float, float, float, float, float, Optional[float]]] = {} self._next_debug_line_id = 0
[docs] def add_debug_line( self, line_from: tuple[float, float, float] | list[float] | np.ndarray, line_to: tuple[float, float, float] | list[float] | np.ndarray, color: tuple[float, float, float] = (1.0, 0.0, 0.0), width: float = 1.0, life_time: float = 0.0, replace_item_unique_id: int = -1, ) -> int: """Add or replace a 3D debug line segment rendered in JoltSim Studio.""" del color, width # Reserved for per-line styling in future protocol versions with self._lock: if replace_item_unique_id >= 0 and replace_item_unique_id in self._debug_lines: line_id = int(replace_item_unique_id) else: line_id = self._next_debug_line_id self._next_debug_line_id += 1 expires_at = (self.sim_time + float(life_time)) if life_time > 0.0 else None self._debug_lines[line_id] = ( float(line_from[0]), float(line_from[1]), float(line_from[2]), float(line_to[0]), float(line_to[1]), float(line_to[2]), -2.0, expires_at, ) return line_id
[docs] def remove_debug_line(self, line_id: int) -> None: """Remove a debug line by ID.""" with self._lock: self._debug_lines.pop(int(line_id), None)
[docs] def clear_debug_lines(self) -> None: """Remove all debug lines.""" with self._lock: self._debug_lines.clear()
@property def url(self) -> str: return f"http://{self.host}:{self._actual_port}" def _step_pick_demo(self) -> None: """Closed-loop 4-phase pick-and-lift animation using finger-midpoint IK servoing.""" self._pick_timer += self.dt self._pick_step_count += 1 meta = self.world.get_scene_metadata() art0_links = [b for b in meta["bodies"] if b["art_idx"] == 0] if len(art0_links) < 3: self._pick_phase = 0 return ee_link = art0_links[-3]["link_idx"] ee_body = art0_links[-3]["body_idx"] lf_body = art0_links[-2]["body_idx"] rf_body = art0_links[-1]["body_idx"] if self._pick_phase_applied != self._pick_phase: if self._pick_phase == 1: for b in meta["bodies"]: if b["art_idx"] < 0 and not b["is_static"]: self._pick_target = np.array(self.world.body_pos[b["body_idx"]], dtype=np.float32) break self._pick_quat = np.array(self.world.body_quat[ee_body], dtype=np.float32) self._pick_step_count = 0 self._pick_phase_applied = self._pick_phase if self._pick_phase in (1, 2, 4) and (self._pick_step_count % 2 == 0): if self._pick_phase == 1: goal_finger = self._pick_target + np.array([0.0, 0.0, 0.14], dtype=np.float32) self.world.ctrl[7:9] = 0.04 elif self._pick_phase == 2: goal_finger = self._pick_target + np.array([0.0, 0.0, 0.045], dtype=np.float32) self.world.ctrl[7:9] = 0.04 else: goal_finger = self._pick_target + np.array([0.0, 0.0, 0.28], dtype=np.float32) self.world.ctrl[7:9] = -0.02 f_mid = 0.5 * (self.world.body_pos[lf_body] + self.world.body_pos[rf_body]) err = goal_finger - f_mid l7_target = np.asarray(self.world.body_pos[ee_body], dtype=np.float32) + 1.8 * err q = np.asarray( self.world.calculate_ik(0, ee_link, l7_target, self._pick_quat), dtype=np.float32, ) self.world.ctrl[:7] = q[:7] elif self._pick_phase == 3: self.world.ctrl[7:9] = -0.02 if self._pick_phase == 1 and self._pick_timer >= 1.2: self._pick_phase = 2 self._pick_timer = 0.0 elif self._pick_phase == 2 and self._pick_timer >= 1.2: self._pick_phase = 3 self._pick_timer = 0.0 elif self._pick_phase == 3 and self._pick_timer >= 0.9: self._pick_phase = 4 self._pick_timer = 0.0 elif self._pick_phase == 4 and self._pick_timer >= 1.5: self._pick_phase = 0 def _get_metadata_json(self) -> str: meta = self.world.get_scene_metadata() payload = { "type": "scene_metadata", "title": self.title, "is_vec": self.is_vec, "num_envs": self.num_envs, "nb": int(self.world.num_bodies), "nq": int(self.world.nq), "nu": int(self.world.nu), "bodies": meta["bodies"], "joints": meta["joints"], "soft_bodies": meta["soft_bodies"], "sites": meta.get("sites", []), } return json.dumps(payload) def _pack_frame(self) -> bytes: with self._lock: nb = int(self.world.num_bodies) nu = int(self.world.nu) env_idx = min(max(0, self.selected_env), self.num_envs - 1) if self.is_vec: stream_envs = min(self.num_envs, self.max_grid_envs) if self.view_mode == "grid" else 1 if self.view_mode == "grid": bpos = np.ascontiguousarray(self.world.body_pos[:stream_envs], dtype=np.float32) bquat = np.ascontiguousarray(self.world.body_quat[:stream_envs], dtype=np.float32) else: bpos = np.ascontiguousarray(self.world.body_pos[env_idx : env_idx + 1], dtype=np.float32) bquat = np.ascontiguousarray(self.world.body_quat[env_idx : env_idx + 1], dtype=np.float32) qpos = np.ascontiguousarray(self.world.qpos[env_idx, :nu], dtype=np.float32) if nu > 0 else np.empty(0, np.float32) qfrc = np.ascontiguousarray(self.world.qfrc_motor[env_idx, :nu], dtype=np.float32) if nu > 0 else np.empty(0, np.float32) ctrl = np.ascontiguousarray(self.world.ctrl[env_idx, :nu], dtype=np.float32) if nu > 0 else np.empty(0, np.float32) jerr = self.world.joint_error[env_idx] else: stream_envs = 1 bpos = np.ascontiguousarray(self.world.body_pos, dtype=np.float32) bquat = np.ascontiguousarray(self.world.body_quat, dtype=np.float32) qpos = np.ascontiguousarray(self.world.qpos[:nu], dtype=np.float32) if nu > 0 else np.empty(0, np.float32) qfrc = np.ascontiguousarray(self.world.qfrc_motor[:nu], dtype=np.float32) if nu > 0 else np.empty(0, np.float32) ctrl = np.ascontiguousarray(self.world.ctrl[:nu], dtype=np.float32) if nu > 0 else np.empty(0, np.float32) jerr = self.world.joint_error max_err_mm = float(np.max(jerr) * 1000.0) if jerr.size > 0 else 0.0 contacts_arr = np.empty((0, 7), dtype=np.float32) if self.show_contacts: c = self.world.contacts if self.is_vec and c.shape[0] > 0: c = c[c["env_id"] == env_idx] if c.shape[0] > 0: contacts_arr = np.column_stack([ c["px"], c["py"], c["pz"], c["nx"], c["ny"], c["nz"], c["impulse"], ]).astype(np.float32, copy=False) rays_arr = np.empty((0, 7), dtype=np.float32) if self.show_rays: ray_parts = [] if self.ray_provider is not None and not self.is_vec: starts, dirs = self.ray_provider() if starts.shape[0] > 0: hits = self.world.raycast_batch(starts, dirs, 10.0) ray_parts.append(np.column_stack([ starts[:, 0], starts[:, 1], starts[:, 2], hits["px"], hits["py"], hits["pz"], hits["body_idx"].astype(np.float32), ]).astype(np.float32, copy=False)) if self._debug_lines: expired = [lid for lid, item in self._debug_lines.items() if item[7] is not None and self.sim_time >= item[7]] for lid in expired: del self._debug_lines[lid] if self._debug_lines: dbg = np.array([item[:7] for item in self._debug_lines.values()], dtype=np.float32) ray_parts.append(dbg) if ray_parts: rays_arr = np.vstack(ray_parts) if len(ray_parts) > 1 else ray_parts[0] soft_chunks = [] num_soft_verts = 0 if self.show_soft_bodies and not self.is_vec: n_sb = int(self.world.num_soft_bodies) for sb_idx in range(n_sb): v = np.ascontiguousarray(self.world.soft_body_vertices(sb_idx), dtype=np.float32) num_soft_verts += v.shape[0] soft_chunks.append(v.tobytes()) header = struct.pack( _HEADER_FMT, _HEADER_MAGIC, self.frame_id, float(self.sim_time), float(self._current_sps), float(max_err_mm), 1 if self.paused else 0, 1 if self.view_mode == "grid" else 0, stream_envs, nb, nu, int(contacts_arr.shape[0]), int(rays_arr.shape[0]), num_soft_verts, ) parts = [ header, bpos.tobytes(), bquat.tobytes(), qpos.tobytes(), qfrc.tobytes(), ctrl.tobytes(), np.ascontiguousarray(contacts_arr, dtype=np.float32).tobytes(), np.ascontiguousarray(rays_arr, dtype=np.float32).tobytes(), ] parts.extend(soft_chunks) return b"".join(parts) def _handle_command(self, msg: str) -> None: data = json.loads(msg) cmd = data.get("cmd") with self._lock: if cmd == "play": self.paused = False elif cmd == "pause": self.paused = True elif cmd == "step": self.paused = True self.step_requested = True elif cmd == "reset": if self.is_vec: self.world.reset_all() else: self.world.reset() self.sim_time = 0.0 elif cmd == "set_speed": self.speed = max(0.1, min(8.0, float(data.get("speed", 1.0)))) elif cmd == "save_snapshot": self._snapshot = self.world.save_state() elif cmd == "load_snapshot": if self._snapshot is not None: self.world.load_state(self._snapshot) elif cmd == "set_ctrl": idx = int(data["index"]) val = float(data["value"]) if self.is_vec: self.world.ctrl[:, idx] = val else: self.world.ctrl[idx] = val elif cmd == "set_ctrl_all": vals = np.asarray(data["values"], dtype=np.float32) if self.is_vec: self.world.ctrl[:, : vals.shape[0]] = vals else: self.world.ctrl[: vals.shape[0]] = vals elif cmd == "solve_ik": art_idx = int(data.get("art_idx", 0)) link_idx = int(data.get("link_idx", 0)) pos = np.asarray(data["pos"], dtype=np.float32) quat = data.get("quat") q_arr = np.asarray(quat, dtype=np.float32) if quat is not None else None if self.is_vec: q_sol = np.asarray( self.world.calculate_ik(self.selected_env, art_idx, link_idx, pos, q_arr), dtype=np.float32, ) n_u = min(q_sol.shape[0], int(self.world.nu)) self.world.ctrl[self.selected_env, :n_u] = q_sol[:n_u] else: q_sol = np.asarray( self.world.calculate_ik(art_idx, link_idx, pos, q_arr), dtype=np.float32, ) n_u = min(q_sol.shape[0], int(self.world.nu)) self.world.ctrl[:n_u] = q_sol[:n_u] elif cmd == "set_overlays": if "contacts" in data: self.show_contacts = bool(data["contacts"]) if "rays" in data: self.show_rays = bool(data["rays"]) if "soft_bodies" in data: self.show_soft_bodies = bool(data["soft_bodies"]) elif cmd == "set_view_mode": self.view_mode = str(data.get("mode", "single")) if "env_idx" in data: self.selected_env = int(data["env_idx"]) elif cmd == "apply_force": b_idx = int(data["body_idx"]) force = [float(x) for x in data["force"][:3]] pos = [float(x) for x in data["pos"][:3]] if "pos" in data and data["pos"] is not None else None if self.is_vec: self.world.apply_external_force(self.selected_env, b_idx, force, pos=pos) else: self.world.apply_external_force(b_idx, force, pos=pos) elif cmd == "pick_demo": self.paused = False self._pick_phase = 1 self._pick_phase_applied = 0 self._pick_timer = 0.0 async def _process_request(self, connection: Any, request: Any): upgrade = request.headers.get("Upgrade", "") if upgrade.lower() == "websocket": return None req_path = request.path.split("?", 1)[0] if req_path == "/" or req_path == "": req_path = "/index.html" rel = req_path.lstrip("/") file_path = (_STATIC_DIR / rel).resolve() if not str(file_path).startswith(str(_STATIC_DIR.resolve())) or not file_path.is_file(): return connection.respond(HTTPStatus.NOT_FOUND, "Not Found\n") from websockets.datastructures import Headers from websockets.http11 import Response mime, _ = mimetypes.guess_type(str(file_path)) hdrs = Headers([("Content-Type", mime or "application/octet-stream")]) return Response(HTTPStatus.OK, "OK", hdrs, file_path.read_bytes()) async def _ws_handler(self, websocket: Any) -> None: self._clients.add(websocket) try: await websocket.send(self._get_metadata_json()) async for message in websocket: if isinstance(message, str): self._handle_command(message) except Exception: pass finally: self._clients.discard(websocket) async def _sim_and_broadcast_loop(self) -> None: target_period = 1.0 / 60.0 while not self._stop_event.is_set(): t0 = time.perf_counter() steps_this_tick = 0 with self._lock: if self.step_requested: n_steps = 1 self.step_requested = False elif not self.paused: self._step_accum += self.speed n_steps = int(self._step_accum) self._step_accum -= n_steps else: n_steps = 0 for _ in range(n_steps): if self._pick_phase > 0 and not self.is_vec and int(self.world.nu) >= 9: self._step_pick_demo() self.world.step(self.dt, substeps=self.substeps) self.sim_time += self.dt steps_this_tick += 1 self._sps_steps += steps_this_tick * (self.num_envs if self.is_vec else 1) now = time.perf_counter() elapsed_sps = now - self._last_sps_time if elapsed_sps >= 0.5: self._current_sps = self._sps_steps / elapsed_sps self._sps_steps = 0 self._last_sps_time = now if self._clients: self.frame_id += 1 frame = self._pack_frame() dead = [] for ws in list(self._clients): try: await ws.send(frame) except Exception: dead.append(ws) for ws in dead: self._clients.discard(ws) dt_loop = time.perf_counter() - t0 await asyncio.sleep(max(0.001, target_period - dt_loop)) async def _run_async(self) -> None: serve = _ensure_websockets() self._stop_event = asyncio.Event() async with serve( self._ws_handler, self.host, self.port, process_request=self._process_request, ) as server: sock = server.sockets[0] self._actual_port = sock.getsockname()[1] await self._sim_and_broadcast_loop()
[docs] def start(self, block: bool = False, open_browser: bool = False) -> "ViewerServer": if block: if open_browser: threading.Timer(0.4, lambda: webbrowser.open(self.url)).start() asyncio.run(self._run_async()) return self ready = threading.Event() def _runner(): self._loop = asyncio.new_event_loop() asyncio.set_event_loop(self._loop) async def _main(): serve = _ensure_websockets() self._stop_event = asyncio.Event() async with serve( self._ws_handler, self.host, self.port, process_request=self._process_request, ) as server: self._actual_port = server.sockets[0].getsockname()[1] ready.set() await self._sim_and_broadcast_loop() try: self._loop.run_until_complete(_main()) finally: self._loop.close() self._thread = threading.Thread(target=_runner, daemon=True) self._thread.start() ready.wait(timeout=5.0) if open_browser: webbrowser.open(self.url) return self
[docs] def stop(self) -> None: if self._loop is not None and self._stop_event is not None: self._loop.call_soon_threadsafe(self._stop_event.set) if self._thread is not None: self._thread.join(timeout=2.0)
[docs] def launch( world: Any, host: str = "127.0.0.1", port: int = 8765, dt: float = 1.0 / 60.0, substeps: int = 4, open_browser: bool = True, block: bool = True, title: str = "JoltSim Studio", ray_provider: Optional[Callable[[], tuple[np.ndarray, np.ndarray]]] = None, ) -> ViewerServer: """Launch JoltSim Studio in the browser for a World or VecWorld.""" server = ViewerServer( world=world, host=host, port=port, dt=dt, substeps=substeps, title=title, ray_provider=ray_provider, ) print(f"JoltSim Studio listening on http://{host}:{port}") return server.start(block=block, open_browser=open_browser)