Metadata-Version: 2.5
Name: robot-viewer-irsl
Version: 1.1.0
Summary: Real-time MuJoCo robot visualization over ZMQ with desktop, web, and headless renderers
Project-URL: Homepage, https://github.com/SeoWookHan/robot_viewer
Project-URL: Repository, https://github.com/SeoWookHan/robot_viewer
Project-URL: Issues, https://github.com/SeoWookHan/robot_viewer/issues
Requires-Python: <3.15,>=3.12
Requires-Dist: imageio-ffmpeg>=0.6.0
Requires-Dist: mjviser<0.1,>=0.0.14
Requires-Dist: mujoco==4.0.1
Requires-Dist: pillow>=10.0
Requires-Dist: pyzmq>=27.1.0
Requires-Dist: robot-msg-irsl==0.5.4
Requires-Dist: tyro>=1.0.8
Requires-Dist: usd-core>=25.5
Provides-Extra: ovrtx
Requires-Dist: ovrtx==0.6.0.1791947691; (python_version < '3.14' and (sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) and extra == 'ovrtx'
Requires-Dist: ovstage==0.3.0.1791986420; (python_version < '3.14' and (sys_platform == 'linux' or sys_platform == 'win32') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')) and extra == 'ovrtx'
Requires-Dist: pyglet<3,>=2.1; extra == 'ovrtx'
Description-Content-Type: text/markdown

# 🤖 Robot Viewer

A **MuJoCo-based robot visualizer** that receives real-time visualization commands (joint states, spheres, arrows, frames, etc.) over **ZMQ**. Choose the **MuJoCo Studio** desktop window (default), the [mjviser](https://github.com/mujocolab/mjviser) web renderer, the **NVIDIA OV RTX** desktop renderer, or **Blender Eevee**. MJCF remains the model input for every backend.

---

## ✨ Features

- 🔴 **Sphere** — render point clouds or markers
- ➡️ **Arrow / Arrow2** — visualize vectors or trajectories
- 🪢 **Frame** — display coordinate frames (XYZ axes)
- 🥚 **Ellipsoid** — render covariance or uncertainty regions
- 🦾 **RobotJoint** — update joint positions in real-time
- 📡 **ZMQ PUB/SUB** — decoupled, network-transparent messaging
- 📷 **Cycles Capture** — save the current Studio/mjviser/OV RTX view as PNG + JSON on demand
- 🎬 **Sequence recording** — record metadata, render Cycles frames later, and encode MP4 with progress and ETA
- 🐍 **Headless API** — send `robot_msg` directly, configure camera/palette/quality, and batch-render selected sequences without a display

---

## 📦 Installation

> Requires **Python 3.12–3.14**. Exactly **MuJoCo 4.0.1** is installed automatically.

### Install from PyPI

```bash
python -m pip install robot-viewer-irsl

# Launch with your own MJCF model
robot-viewer --model-path /path/to/scene.xml

# Browser renderer (no desktop display required)
robot-viewer --model-path /path/to/scene.xml --renderer mjviser

# Or receive the model and state from switch_controller
robot-viewer-switch --connect 127.0.0.1
```

The PyPI distribution is named `robot-viewer-irsl`; the Python import remains
`robot_viewer`, and the commands remain `robot-viewer`, `robot_viewer`,
`robot-viewer-switch`, and `robot-render-sequence`.

Example robot models are **not included** in the PyPI package. Pass
`--model-path` to your own MJCF file (with its meshes/assets), use
`robot-viewer-switch` to receive a controller's model, or clone the example
models as described below. The default relative model path only works from a
source checkout with its submodule initialized.

For the optional NVIDIA RTX backend (Python 3.12–3.13, Linux/Windows x86-64):

```bash
python -m pip install 'robot-viewer-irsl[ovrtx]'
```

The `mujoco==4.0.1` meta-package installs matching `mujoco-core` and
`mujoco-studio` packages, plus the Studio web assets.

### Install from source

Development uses [uv](https://docs.astral.sh/uv/). Use `uv sync` when upgrading
an existing checkout so the old monolithic MuJoCo wheel is replaced cleanly.

```bash
# Clone the repository
git clone https://github.com/SeoWookHan/robot_viewer.git
cd robot_viewer

# Initialize example robot models (messages are installed from PyPI)
git submodule update --init --recursive

# Install in editable mode (NVIDIA RTX is an optional extra)
uv sync
```

The `uv run ...` examples below assume a source checkout. After installing from
PyPI, run the same commands without the `uv run` prefix and supply your model
path where needed.

Blender uses the official **Blender 4.5 LTS** desktop application, not a `bpy`
wheel. On Linux x86-64, the first Cycles capture or `--renderer blender` launch automatically
downloads the official binary (~378 MB), verifies its SHA-256, and installs it
under `~/.local/share/robot-viewer`. No source build, root privileges, or extras
are needed. An existing `blender` on `PATH` is used first. On macOS/Windows,
install [Blender 4.5 or newer](https://www.blender.org/download/) and put its
executable on `PATH`; `/Applications/Blender.app` is also detected on macOS.
`BLENDER_PATH` can point to an existing executable in a custom location.

### Python interpreter and desktop Tk

The project uses **Python 3.12** by default (`.python-version`) and requires
3.12 or newer. MuJoCo Studio 4.0.1 imports `collections.abc.Buffer`, which is
not available on Python 3.11. Use the managed **CPython 3.12.12** distribution
with Tk for the existing desktop capture controls; this machine's system
Python 3.12.3 does not include `tkinter`.

```bash
uv python install 3.12.12
uv sync --python 3.12.12
uv run python -c "import tkinter; print(tkinter.TkVersion)"
```

Keep `uv.lock` when migrating an existing environment; this upgrade does not
require newer NumPy, USD, mjviser, or NVIDIA runtime versions.

### MuJoCo Studio desktop viewer (default)

The default renderer is **MuJoCo Studio** (`--renderer studio`). The classic
MuJoCo Simulate viewer (`native`/`classic`, `mujoco.viewer.launch_passive`) was
removed. In the Python API, `RobotViewer(..., renderer='native'|'classic')` and
`SwitchArgs(renderer=...)` raise
`ValueError: the classic MuJoCo viewer was removed; use 'studio' (default) or 'headless'`.
On the command line, `--renderer native|classic` is rejected by the argument
parser as an invalid choice, which lists the remaining backends.
Studio here is a **passive display** of externally owned state (protocol-2
messages or a switch_controller robot), not a simulator. It never steps physics,
and no UI action can change robot_viewer's model or data.

```bash
uv run robot-viewer                       # Studio, opengl_headless, 1200x800
uv run robot-viewer-switch --connect 127.0.0.1
# Software-display/CI option (still requires X11)
uv run robot-viewer --studio-gfx opengl_software --studio-width 1200 --studio-height 800
# History bounds (defaults: 1800 frames = 30 s at 60 Hz, 256 MiB; 0 frames disables)
uv run robot-viewer --studio-history-frames 3600 --studio-history-mb 512
```

Both commands accept `--studio-gfx`, `--studio-width`, `--studio-height`,
`--studio-history-frames`, and `--studio-history-mb`.

**Limits (default behavior):**

- **X display with GLX required.** Studio opens a desktop window and needs a
  working `DISPLAY` with the GLX extension, libX11, libGL and libEGL;
  **`opengl_headless` does not mean display-free**. Without X11/GLX use
  `--renderer headless` (no window) or `--renderer mjviser` (browser). A missing
  or unreachable display, or one without GLX, is rejected before any native
  Studio code runs.
- **`opengl_headless` (default) and `opengl_software` only.** In the shipped
  4.0.1 wheel, `opengl`, `vulkan` and `vulkan_software` fail with an unnamed
  render-target error and can abort during teardown, even on real NVIDIA X11.
  The actual GL driver depends on the display: NVIDIA on Xorg `:1` and llvmpipe
  under Xvfb in our tests.
- **~2000 overlay geoms.** Studio 4.0.1 has a 2000 total scene-geom budget that
  includes model-generated geoms. The adapter reports the remaining overlay
  capacity and drops excess markers with rate-limited warnings (also when
  visualization options shrink the budget). It never truncates silently.
- **Primitive overlays only.** Sphere/ellipsoid/box/capsule/cylinder/arrow/
  frame/line markers and model mesh colors are supported. Mesh/heightfield and
  non-finite overlay geoms are rejected. Mesh-robot ghost overlays need another
  backend.
- **One Studio window per process.** ImGui contexts are global. Controller
  model refresh reuses the live session instead of opening a second window.
- **Close before exit.** `close()` waits for Studio's native teardown (up to
  15 s). A Ctrl+C during that wait is deferred and re-raised once teardown has
  finished; the process-wide session is released only after a verified
  teardown (otherwise it stays poisoned and no second window can open). A
  renderer that is never closed is closed automatically at interpreter exit or
  garbage collection, because a live Studio thread at exit crashes the process.

#### Studio features in robot_viewer

| Studio feature | In robot_viewer |
|---|---|
| Menu bar: File → Quit, View (panel toggles, Save/Reset Config, theme), Help | Enabled |
| History menu, History section in Options, toolbar ⏮/Pause/Live/⏭ | Enabled: replaces Studio's Simulation menu and panel |
| Timeline scrubber, Space (pause/resume), Left/Right (previous/next frame) | Enabled: browses the viewer-side frame history (below) |
| Toolbar camera, label, and frame selectors; view gizmo; status bar | Enabled |
| Camera modes: tumble, free/fly (WASD), tracking (Ctrl+right double-click), fixed cameras (`[`/`]`, Esc), right double-click to set the look-at point | Enabled and validated before any native call |
| Rendering settings, visibility groups, visualization options, visualization hotkeys | Enabled, local to the viewer; visualization options are reported back to `viewer.viewer.opt` |
| Left double-click body selection | Enabled; highlights the body in the viewer only |
| Inspector: Sensors (plot), Watch | Enabled; show the displayed frame |
| Inspector: Joints, Controls, State | Read-only (greyed-out values of the displayed frame) |
| Options: Physics Settings | Read-only |
| Info (F2), Profiler (F3: solver counts and convergence from the viewer's `mj_forward` of the displayed frame), Console | Enabled |
| Reset (button, Backspace), keyframe load/save, physics single step, speed, noise, worker threads | Removed or ignored: they would mutate authoritative state or do not apply |
| Perturb (Ctrl+drag), model reload, file drop, model hot reload | Disabled; a dropped file is ignored with a warning |

As defense in depth, robot_viewer never calls the Studio handle's `sync()`, so
viewer-to-sim messages are never applied. A read-only guard also blocks
mutating messages.

#### History: pause, scrub, and return to live

Every frame that `RobotViewer.sync()` submits is recorded in a bounded ring
(`--studio-history-frames`, default 1800 = 30 s at 60 Hz, and
`--studio-history-mb`, default 256 MiB; the oldest frames are evicted first).
Each record is frame-atomic: integration state, overlay markers, and the
`geom_rgba`/`geom_matid`/`mat_rgba` visual arrays are kept together. Overlays
are stored compactly (one ~250-byte structured-array row per marker instead of
a ~1.3 kB `MjvGeom`) and rebuilt only when a past frame is shown or captured.
Unchanged visual arrays are shared between frames and counted once while any
recorded frame references them, so the MiB cap bounds actual allocations
(verified with `tracemalloc`; process RSS also includes allocator slack and the
live frame).

- **Pause** (Space, the toolbar, or the History menu) freezes the display on the
  frame currently shown. Incoming frames keep being recorded, and the display
  stays on the selected frame until you resume live.
- **Scrub** with Studio's own timeline scrubber in *Options → History* or step
  with Left/Right. A frame stays displayed even after the ring evicts it; the
  status bar then marks it as evicted.
- **Live** (Space, the toolbar, or the History menu) returns to the newest frame.
- Camera and visualization changes apply in both modes; they are view settings,
  not part of the recorded robot state.
- Loading a new model (e.g. controller model refresh) clears the history and
  returns to live.
- Scripts can use `viewer.viewer.history_pause()`, `history_seek(index)`
  (index ≤ 0), `history_step(delta)`, `history_live()`, `history_clear()` and
  `history_status()`. Pause/seek/step/live are applied asynchronously on the
  viewer thread; pass `wait=True` (optional `timeout`, default 2 s) to block
  until the viewer acknowledges the command and get its `HistoryStatus`, e.g.
  `history_seek(-30, wait=True)` before a capture guarantees the capture shows
  that frame. `history_clear()` is synchronous and only drops frames of the
  current model.
- If the pinned frame has been evicted, the scrubber shows it one slot before
  the oldest recorded frame; Right moves to the oldest recorded frame.

Studio's own `SimHistory` is a sim-side plugin: it records after each physics
step and loads frames into the sim's data. robot_viewer never steps physics and
must not write into authoritative data, and `SimHistory` stores physics state
only, without overlays or colors. The history is therefore implemented
viewer-side, but it drives Studio's native pause state, timeline scrubber, and
arrow-key handlers.

**Capture and sequence semantics:** a single **Cycles capture is WYSIWYG**.
While Studio shows a past frame, the capture renders that frame's state,
markers, and colors, and its metadata carries a `studio_history` marker.
**Sequence recording always follows the live stream**, even while you inspect
history, so recordings never freeze or duplicate frames. The status bar shows
`REC live` while recording. `sync()` publishes the frame without waiting for
pixels; intermediate submissions may be skipped by the display but are still
recorded in history. Capture uses the latest render-thread camera readback (or
a pending explicit camera edit). Cycles output is not a pixel-identical Studio
screenshot.

### Optional NVIDIA OV RTX backend

OV RTX requires **Python 3.12–3.13**, **Linux or Windows x86-64**, a supported
**NVIDIA RTX GPU/driver**, and a desktop display. Install its pinned standalone
runtime and desktop dependencies separately:

```bash
uv sync --python 3.12 --extra ovrtx
uv run --extra ovrtx robot-viewer --renderer ovrtx
```

The base installation and other renderers do not import or initialize the NVIDIA
runtime. Python 3.14 remains supported for those backends, but not OV RTX. See
[NVIDIA's driver requirements](https://nvidia-omniverse.github.io/ovrtx/driver_requirements.html)
for compatible GPUs, operating systems, and drivers. This backend has been tested
on Linux x86-64 with Python 3.12/3.13, an RTX 5060, and driver 595.84; Windows has not
been exercised here. Isaac Sim and Omniverse Kit are not required.

---

## 🚀 Usage

### View a running switch_controller

```bash
# Controller must have its opt-in --remote-viewer server enabled (Studio window by default).
uv run robot-viewer-switch --connect 192.168.0.10

# Same PC: --connect 127.0.0.1. Browser renderer:
uv run robot-viewer-switch --connect 192.168.0.10 --renderer mjviser

# Custom model port/cache; bounded no-window connectivity probe
uv run robot-viewer-switch --connect 192.168.0.10:30000 \
  --renderer headless --cache-dir /tmp/robot-viewer-models --max-frames 120
```

This **read-only** integration uses the published **robot-msg-irsl 0.5.4**
`ModelRequest`/`ModelDescriptor`/`ModelChunk` and `StateSnapshot` binary messages.
Simulation downloads the effective **MJB**, including composed hands, meshes and
textures, and applies **full native qpos/mocap/time**. Real backends serve an
immutable **MJCF + asset file table**; the viewer compiles it locally and maps
measured component positions by named scalar joints and declared units. No local
controller/model clone is needed. A verified content-addressed cache avoids
repeated downloads. No controls or `mj_step()` calls are sent/performed.

| Option | Default | Description |
|---|---|---|
| `--connect` | required | Controller IPv4/hostname, optionally `:model-port`; no `tcp://` prefix |
| `--renderer` | `studio` | `studio` (MuJoCo Studio; needs X11), `mjviser`, or `headless` |
| `--studio-gfx` / `--studio-width` / `--studio-height` | `opengl_headless` / `1200` / `800` | Studio window options (see above) |
| `--studio-history-frames` / `--studio-history-mb` | `1800` / `256` | Studio history bounds; `0` frames disables history |
| `--host` / `--port` | `127.0.0.1` / `8080` | mjviser HTTP bind address/port, not the controller address |
| `--hz` | `60` | Maximum render update rate; apply the newest valid whole snapshot |
| `--cache-dir` | `$XDG_CACHE_HOME/robot_viewer/switch` or `~/.cache/robot_viewer/switch` | Verified model file cache |
| `--timeout` | `2` | Absolute deadline for each complete model TCP request in seconds, with up to three bootstrap attempts |
| `--stale-after` | `2` | Silence threshold in seconds; report stale status and revalidate in the background |
| `--max-frames` | `0` | Exit after this many applied snapshots; `0` runs until closed/Ctrl+C |

The length-prefixed **TCP model port** defaults to **28430** (`ROBOT_MODEL`):
one connection carries one request and one response, each prefixed by a 4-byte
unsigned big-endian payload length. Requests are 1–4096 bytes, responses 1 byte–1
MiB, containing the unchanged canonical robot_msg binary payload. A single
absolute deadline covers connect/send/header/body, so partial progress does not
extend the request indefinitely. All resolved IPv4 connection attempts share that
budget. System hostname/DNS resolution itself is synchronous and cannot be
interrupted by the socket timeout; use a numeric IPv4 address when resolver delays
must be avoided. The descriptor supplies the **ZMQ snapshot PUB**
port, normally **28405** (`STATE_SNAPSHOT`), on the same user-provided host. Both
must be reachable. Existing `RobotState` port **28400**
and viewer marker port **28410** retain their original wire format. The private
JSON/raw-MJB experiment on 28420/28421 was not released and is not supported.
The legacy `robot-viewer` command/renderers are unchanged. Capture/recording,
custom markers, forces and dynamic-model reconstruction are outside this CLI.

**Measured state is not a command target.** Arm q/dq sizes are independent;
Shadow has 24 measured joints versus 20 drives. NERO real hand feedback can have
**zero measured joints** and one measured opening/force actuator (`m`/`N`): fixed
finger geometry stays static, never animated from invented joint feedback.
Non-scalar/unmapped component blocks fail closed; unmeasured moving model joints
require named **explicit JointDefault** entries, never implicit qpos0 padding.
Unavailable components retain their last pose and are logged separately from
transport freshness. `last_snapshot` preserves typed samples, source clocks and
software `enabled` flags; these flags do not mean physical power/readiness.

**Compatibility and integrity:** MJB requires the exact descriptor MuJoCo version
(**4.0.1**), matching this viewer and the upgraded controller. MJB files from
3.13.0 and 4.0.1 cannot be exchanged in either direction; use a matching older
viewer checkout for an older controller rather than overriding this pin.
MJCF `engine_version=any` remains accepted, but is only source compatibility,
not a guarantee that every engine release compiles it.

MuJoCo 4 stores resolved asset paths in compiled models, so identical source
models built on different hosts/checkouts can have different MJB hashes and
`model_id` values. Cache entries identify the exact served content, not a
portable robot identity: a different hash gets a separate verified cache entry.
Every file/hash, canonical
`model_content_id`, compiled dimensions and mappings are checked. Transfers use
at most **64 KiB** chunks and **256 MiB** aggregate file bytes; descriptor/state
admission is **1 MiB before decoding**. Source dependencies must stay within the
verified table; unsafe paths, external model/plugin references and XML
entities/cycles are rejected. Separate cube-texture face `file*` attributes and
external MJCF model attachments are currently unsupported and rejected before
compilation. Plugin libraries are never downloaded.

Invalid/old snapshots do not change pose or freshness. New session/model IDs
require descriptor confirmation; reconnect runs in the background while the last
pose stays visible. No physics extrapolation is performed. `--max-frames` counts
valid applied snapshots and can wait indefinitely on silence; use Ctrl+C to stop.

**Trusted LAN/VPN only.** The model TCP and state ZMQ channels have no
authentication/encryption; MuJoCo parses the native model. State admission bounds
apply before Python decoding but do **not** bound libzmq's native buffering of
unfinished multipart messages from a malicious publisher; trust the state server.
Hashes verify integrity, not peer trust. Do not
expose the ports publicly or connect to an untrusted controller. Cache files
remain on disk until removed.

### Run the viewer

```bash
uv run robot-viewer [OPTIONS]
```

#### Options

| Option | Default | Description |
|---|---|---|
| `--model-path` | `robot_description/qdd_dual_arm/mujoco_model/scene.xml` | MuJoCo XML model file path |
| `--renderer` | `studio` | `studio`: MuJoCo Studio desktop window (needs X11); `mjviser`: browser viewer; `ovrtx`: NVIDIA RTX desktop; `blender`: Blender Eevee; `headless`: scene state only |
| `--studio-gfx` | `opengl_headless` | Studio graphics mode: `opengl_headless` or `opengl_software` |
| `--studio-width` / `--studio-height` | `1200` / `800` | Studio window size |
| `--studio-history-frames` / `--studio-history-mb` | `1800` / `256` | Studio history bounds; `0` frames disables history |
| `--host` | `127.0.0.1` | mjviser HTTP bind address; `0.0.0.0` allows remote access |
| `--port` | `8080` | mjviser HTTP port |
| `--hz` | `60` | Viewer update rate (Hz) |
| `--addr` | `tcp://localhost:28410` | ZMQ subscriber address |
| `--t-out` | `1.0` | Legacy compatibility option; object lifetimes use message `lifetime` |

#### Examples

```bash
# Use default settings (MuJoCo Studio desktop window)
uv run robot-viewer

# Web viewer: open http://127.0.0.1:8080 in a browser
uv run robot-viewer --renderer mjviser

# NVIDIA RTX desktop viewer (requires the optional extra)
uv run --extra ovrtx robot-viewer --renderer ovrtx

# Blender desktop viewer with Eevee lighting, shadows, and reflections
uv run robot-viewer --renderer blender

# Web viewer on a remote machine
uv run robot-viewer --renderer mjviser --host 0.0.0.0 --port 8081

# Custom model and port
uv run robot-viewer --model-path /path/to/model.xml --addr tcp://localhost:28411 --hz 30
```

All renderers use the same `RobotViewer` API and ZMQ messages: all individual
markers, all batches, joint updates, geom/link colors, temporary color restoration,
ID replacement, visibility, lifetimes, and `Clear`. Publishers should use
`robot-msg-irsl==0.5.4` (protocol 2); existing 0.3.0 viewer messages remain compatible.
All are passive visualizers: they display incoming poses without
advancing physics automatically. The default Studio backend is a read-only
MuJoCo Studio window with history scrubbing. The web server keeps running when a browser disconnects; use Ctrl+C
or `close()` to stop it and the ZMQ subscriber.

```python
import time
from robot_viewer import RobotViewer

viewer = RobotViewer("path/to/scene.xml", renderer="mjviser", port=8080)
# Omit renderer (default "studio") for the MuJoCo Studio desktop window.
# Use renderer="ovrtx" for NVIDIA RTX (install the optional extra first).
# Use renderer="blender" for Blender Eevee.
try:
    viewer.start_subscriber("tcp://localhost:28410")
    while viewer.is_running:
        viewer.process_zmq()
        viewer.sync()
        time.sleep(1 / 60)
finally:
    viewer.close()
```

Rendering appearance and built-in UI controls differ between MuJoCo and mjviser.
Web color overrides use flat RGBA; restoring a color also restores its original
material/texture. Infinite planes have a 20 m extent in the web renderer. Native
mouse/body dragging and keyboard shortcuts are not reproduced by mjviser.

### NVIDIA OV RTX live view

```python
from robot_viewer import RobotViewer

viewer = RobotViewer("path/to/scene.xml", renderer="ovrtx")
```

MJCF is converted through MuJoCo's official USD exporter **once at startup**.
A persistent OV RTX stage then receives pose, visibility, color, marker, and
camera updates without writing per-frame USD assets or stepping physics. The
default is **Real-time Path Tracing** with **Blender pastel** appearance: uniform
Mint matte materials, soft studio lighting, shaded depth, and a white background
and floor. Opaque white planes receive contact shadows without darkening the
distant floor. This is lit RTX rendering, not unlit flat shading; shadow noise
can remain at low resolutions or before accumulated PT converges.

**Live RTX** controls appear in the right sidebar of the robot window, for both
the CLI and Python-created viewers. Keep calling `viewer.sync()` to process
input. Click choice fields to cycle through their values, edit numeric values
or `#RRGGBB` colors, and scroll the panel to reach the appearance controls.
Press **Apply** (or Enter in an input) to use changes on the next successful
frame, or **Reset defaults** to restore the defaults. Invalid inputs leave the
last valid settings in effect. Use **F1** or the top-right arrow to collapse or
reopen the sidebar. Panel input does not orbit, pan, or zoom the camera.

RTX mode does **not** automatically open the Blender/Cycles capture window or
start Blender. Offline PNG/video rendering remains available through the Python
API; call `viewer.enable_capture_ui()` explicitly if you also want its separate
Cycles capture controls.

| Live control | Default / choices | Tradeoff |
|---|---|---|
| Render mode | Real-time / Accumulated Path Tracing | Real-time suits motion; accumulated PT converges while still and restarts after scene/camera changes |
| Internal render scale | 100%, 75%, 50% | Lower resolution is enlarged to the window for speed; camera and offline capture dimensions stay unchanged |
| DLSS | Auto, Performance, Balanced, Quality, RTXAA | Real-time reconstruction / anti-aliasing quality |
| Direct light samples | 2 (1–16) | More samples cost time and can reduce lighting noise |
| Indirect diffuse / bounces | On / 2 (0–8) | Indirect illumination quality versus cost |
| Reflection bounces | 1 (0–8) | More reflection paths cost time |
| PT samples / iteration | 1 (1–16) | Work per accumulated render iteration |
| PT total sample limit | 512 (1–4096) | Convergence target, not samples per frame |
| PT max bounces / denoising | 4 (1–16) / On | Path depth and noise filtering |
| Exposure compensation | 0 EV (-4 to +4) | Adjusts live brightness |
| Appearance | Blender pastel / Original MJCF | Eight palettes or custom model/floor/background colors; Original restores source materials, textures, and active lights |

The status line reports the last successfully displayed settings, measured FPS,
robot viewport/internal render pixel sizes, and the runtime's PT progression and
convergence. The sidebar is excluded from the camera and offline capture or
recording dimensions. Internal render scale changes only the RTX pixels, not
those camera dimensions. These controls affect **only live RTX rendering**;
Cycles PNG/video settings remain independent.

- **Orbit:** left mouse drag.
- **Pan:** right/middle mouse drag, or Shift + drag.
- **Zoom:** mouse wheel.
- **Exit:** Escape or close the RTX window.

The window is resizable. Navigation updates `viewer.viewer.cam`; programmatic
edits to that MuJoCo camera are also supported. Geometry/site groups are
controlled through `viewer.viewer.opt`, initially matching MuJoCo's defaults.
Explicit message/direct RGBA overrides are local to each geom and take priority
over the pastel palette, including alpha and temporary-color lifetimes. When an
override expires or is cleared, the selected base appearance returns: pastel
material or original MJCF material/texture. Marker colors and geom/site group
visibility are preserved. Expired and cleared marker meshes are hidden and
reused. The resulting appearance differs from native OpenGL and offline Cycles.

This backend supports **rigid, static-topology geometry**. Deformables, runtime
mesh-topology changes, browser streaming, and native MuJoCo's built-in controls
or body dragging are not supported. `--hz` is a target, not a guaranteed frame
rate; scene complexity, resolution, GPU, readback, and presentation affect it.
The optional desktop Cycles panel captures/records the current RTX camera and
displayed state for offline Blender rendering; it does not save the live RTX
framebuffer. Its Render Style and Cycles samples affect those offline renders;
use the embedded Live RTX sidebar to change the live appearance and quality.

### Headless Python API: robot_msg → Cycles PNG / video

`RobotRenderer` needs **no desktop, browser, DISPLAY, Wayland, or OpenGL context**.
Constructing it and recording metadata only use MuJoCo CPU scene state. Blender
starts when you request PNG/video rendering, using the normal installation above.
The Studio, mjviser, and OV RTX capture panels call the **same `RenderAPI` implementation**
through `viewer.rendering`.

```python
import robot_msg as rm
from robot_msg.types import ColorRGBA, Vec3
from robot_viewer import RobotRenderer, Camera, RenderSettings, RenderStyle

with RobotRenderer(
    "robot_description/qdd_dual_arm/mujoco_model/scene.xml",
    camera=Camera.orbit(target=(0, 0, .5), distance=2.3, azimuth=160, elevation=-30),
    settings=RenderSettings(
        width=1280, height=720, samples=128,
        style=RenderStyle.pastel("Mint"),  # Transparent background, opaque model.
    ),
) as renderer:
    renderer.send(
        rm.RobotJointInput(qpos=renderer.model.qpos0.tolist()),
        rm.SphereInput(frame_id="world", position=Vec3(.2, 0., .6), radius=.04,
                       color=ColorRGBA(1., 0., 0., 1.)),
    )
    png = renderer.render("captures/headless.png")  # Waits; saves PNG + JSON.
    print(png)

    # Another camera, same frozen robot/markers, including single-frame objects.
    future = renderer.render_async(
        "captures/side.png",
        camera=Camera.look_at(position=(2., 0., 1.), target=(0., 0., .5)),
    )
    print(future.result())
```

`send()` accepts individual messages, lists/tuples, and `rm.MessageBatch` envelopes.
All normal joint, primitive, batch, color, ID, visibility, lifetime, and `Clear()`
messages use the live viewer's implementation. Joint poses must contain exactly
`renderer.model.nq` finite values. `render()` automatically calls `sync()` after
`send()`; subsequent camera renders reuse that frame. Call `sync()` explicitly
after directly changing `renderer.data` or to process timeout expiry without new
messages. Scenes are passive: use your simulation to advance physics.

Configuration is immutable; use `dataclasses.replace()` for a variant. Set
`renderer.camera`, `.settings`, or `.visibility` for persistent defaults, or pass
an override to a single `render()` / `render_async()` call:

| Setting | API |
|---|---|
| Orbit camera | `Camera.orbit(target=…, distance=…, azimuth=…, elevation=…)` — MuJoCo convention, degrees |
| Position and target | `Camera.look_at(position=…, target=…, up=(0, 0, 1), fov_y=45)` — metres, vertical FOV in degrees |
| Orthographic camera | `Camera.look_at(…, projection="orthographic", ortho_height=2)` |
| XML fixed camera | `Camera.named("camera_name")` — evaluated against the recorded robot pose |
| Clipping, roll, lens shift | `near`, `far`, `up` or explicit `rotation`, `shift_x`, `shift_y` on `Camera` |
| Size and quality | `RenderSettings(width=1920, height=1080, samples=256)`; omitted dimensions use the live/recorded viewport, headless default 1280×720 |
| Palette | `RenderStyle.pastel("Lavender")`; all eight GUI palettes are in `PASTEL_PALETTES` |
| Custom colors | `RenderStyle.pastel(robot_color="#B6A6D9", floor_color="#F4F4F4", background_color="#FFFFFF")` |
| Transparency | `RenderStyle.pastel(transparent_background=True, ignore_mesh_transparency=True)` |
| Original materials | `RenderStyle.studio(ignore_mesh_transparency=False)` |
| Model/site groups | `Visibility(geom_groups=(0, 1, 2), site_groups=(0, 1, 2))` |
| Video | `render_video(folder, fps=30, settings=…)`; batch: `render_videos([folder_a, folder_b], …)` |

Import `Visibility` and `PASTEL_PALETTES` from `robot_viewer` as needed. Recover
the exact camera (including browser roll) and rendering settings from a GUI PNG's
JSON using `Camera.from_metadata("captures/pose.json")` and
`RenderSettings.from_metadata("captures/pose.json")`. These restore configuration;
send the desired robot/object state separately. `RenderSettings.from_metadata()`
also accepts a video's `metadata/render.json`.

Record offline without sleeps, then render any selection:

```python
from datetime import datetime
from pathlib import Path
import time
import robot_msg as rm
from robot_viewer import RobotRenderer, RenderSettings
from robot_viewer.sequence import progress_label

root = Path("captures/sequences") / datetime.now().strftime("%Y%m%d_%H%M%S_%f")
with RobotRenderer("robot_description/qdd_dual_arm/mujoco_model/scene.xml",
                   settings=RenderSettings(width=640, height=480, samples=32)) as renderer:
    folders = []
    for name in ("take_a", "take_b"):
        folder = root / name
        with renderer.recording(folder, fps=30):
            for i in range(30):
                # Replace qpos with each pose from your simulation/controller.
                renderer.send(rm.RobotJointInput(qpos=renderer.model.qpos0.tolist()))
                renderer.record_frame()  # Timestamp i/30; no Blender work here.
        folders.append(folder)

    job = renderer.render_videos(folders, fps=30)
    while not job.done():
        state = job.progress()  # fraction, completed/total frames, overall ETA,
        print(progress_label(state))  # current sequence, per-folder states.
        time.sleep(.25)
    for video in job.result():
        print(video)  # Each sequence's video.mp4, directly inside its folder.
```

`record_frame(timestamp=seconds, camera=…)` supports irregular ordered timestamps
and a changing camera. Sequence duration ends one frame period after the last
timestamp. Manual timestamps control video timing; message `Lifetime("seconds", seconds)`
still uses the receiver's real monotonic time from receipt. For deterministic offline
drawings, send each frame's markers with `Lifetime("one_frame")` (the default),
or use persistent IDs and `Clear()`.

`start_recording(folder, fps=None)` records real-time `sync()` calls instead;
`stop_recording()` flushes metadata. `job.cancel()` stops the active video and
skips the remaining queue, preserving completed videos/PNGs. Batch failures are
reported per folder and later sequences continue; `result()` raises
`robot_viewer.sequence.BatchRenderError` with `.errors` and successful `.results`.
`job.results` always provides completed `{sequence_folder: video_path}` pairs.
Use `result(timeout=…)` to bound waiting. Normal viewer closure does not cancel
an active batch. Videos are saved directly in the sequence folder as `video.mp4`.
If that name already exists, the new video is named `video_<date_id>.mp4` alongside
it. PNGs and metadata stay in `renders/<date_id>/`; earlier output is preserved.
`render_video(..., output_dir=path)` uses that directory for videos and its
`renders/<date_id>/` subdirectory for PNGs/metadata.

For an existing `RobotViewer`, use `viewer.rendering.send(...)`, `.render_async(...)`,
`.start_recording(...)`, and `.render_videos(...)`. Its default camera is the current
Studio/browser/RTX view; pass `client=client_handle` with multiple browsers, or an
explicit `Camera`. Legacy `save_snapshot()` / `render_sequence()` remain available.

A runnable example with animated metadata sequences and a terminal progress bar:

```bash
uv run python examples/headless_render.py --frames 12 --fps 12 --samples 32
```

### Capture the current view with Cycles

Use the default Studio renderer, `--renderer mjviser`, or `--renderer ovrtx` (with its
optional extra). The Studio and mjviser CLIs automatically open **Cycles Capture**
controls; RTX opens only its live robot window by default:

- **Studio:** a separate (Tk) window with a PNG path field and capture button.
- **mjviser:** the **Cycles Capture** section at the top of the browser controls.
  Each browser captures its own current camera, including mouse orbit and zoom.
- **OV RTX:** call `viewer.enable_capture_ui()` explicitly to open the separate
  offline Cycles controls, or use the Python PNG/video APIs without that window.

Enter a path such as `captures/experiment_01.png` and click **Capture current
view**. It saves `experiment_01.png` and `experiment_01.json` next to each other.
Paths refer to the machine running the viewer, including when using a remote
browser. Parent directories are created, and existing images/metadata are never
overwritten. The panel shows rendering, completion, and errors. A new timestamped
path is suggested after each successful capture.

The capture freezes the latest displayed frame and the camera at the click (with
Studio paused on a past frame, that past frame; see *History* above):
single-frame drawings, retained markers, batches, visibility, temporary colors,
joint poses, and geom/site groups. Subsequent motion, timeouts, and `Clear()` do
not alter an in-progress capture. PNG dimensions match the current Studio/RTX
viewport or browser canvas; position, orientation, projection, and field of
view are transferred to Blender. **Cycles samples** in Render Style controls both
PNG and video quality (default 128), with denoising and GPU
rendering when available (OptiX on this machine). USD export and rendering run
in separate processes, with no live Blender window. Rendering still shares GPU
resources with the viewer. One capture runs at a time, and a requested capture
finishes even if the viewer closes.

JSON metadata contains:

- XML absolute path and SHA-256; named joint values, full `qpos`/`qvel`, control,
  mocap and MuJoCo integration state, and geom/material colors.
- Camera pose and projection, image size, source renderer and browser client.
- Displayed user objects with MuJoCo geometry type, position, rotation, size,
  and RGBA; exported model geometry and visualization group settings.
- Capture/request timestamps, MuJoCo/Blender versions, Cycles settings/device,
  render duration, final PNG path and SHA-256.

Geometry metadata records the resolved displayed shapes, not a replay of message
lifetimes. The referenced XML, includes, and assets must still be available for
reconstruction; they are not bundled in the JSON. Appearance uses Blender's
studio lighting and USD material conversion, so it differs from the live viewer.
Capture covers RobotViewer model geometry and drawing APIs, not arbitrary extra
objects created directly through Viser or Blender APIs.

For a custom Python loop, call `viewer.enable_capture_ui()` once to add the same
controls, or request a capture directly after `sync()`:

```python
viewer.sync()
job = viewer.save_snapshot("captures/pose.png", samples=128)
# Continue calling viewer.sync() while the capture runs.
if job.done():
    print(job.result())  # Saved PNG path, or a rendering exception.
```

With multiple mjviser clients, use the browser button or pass
`client=client_handle` to `save_snapshot()`. No additional CLI flags or extras
are required beyond the selected renderer's dependencies. Native and OV RTX
capture controls use Python's `tkinter` GUI module.

### Pastel colors, transparent backgrounds, and mesh opacity

**Render Style** appears above the capture controls in mjviser and in the desktop
(Studio/RTX) capture window. These settings apply to Cycles captures and sequence renders;
the live viewer keeps its own appearance. The GUI starts with **Pastel clay**:

- **Style:** choose `Pastel clay` for matte materials, neutral softbox lighting,
  soft shadows, and a solid floor without the XML's checker texture. `Studio`
  retains the original material/texture appearance and existing studio lighting.
- **Pastel palette:** eight color buttons: `Mint` (default), `Lavender`, `Peach`,
  `Sky Blue`, `Rose`, `Butter`, `Sage`, and `Apricot`. Each button shows its actual
  color, and a check mark identifies the selection. Every preset pairs its robot color with a white background
  (`#FFFFFF`) and a soft white floor (`#F4F4F4`). Selecting one applies all three
  colors and switches to Pastel clay, retaining both transparency checkboxes.
  Editing individual colors changes the palette label to `Custom`.
- **Robot / model**, **Floor**, **Background:** color pickers for the pastel
  palette. Markers retain their original hue distinctions (including XYZ axes),
  softened toward white. Robot/model recoloring deliberately overrides recorded
  mesh colors; `Studio` retains them. Background color also controls MP4 compositing.
- **Transparent background:** **on by default for Pastel**. It hides MuJoCo ground
  planes and save the robot/objects against alpha in RGBA PNG, with smooth edges.
  Existing hidden geometry stays hidden. No floor or floor shadow is baked in.
- **Ignore mesh transparency:** **on by default**. Visible model surfaces render
  opaque in either style. Uncheck to restore the original geom/material alpha.
  This is independent of background transparency; marker alpha, group visibility,
  and fully hidden geometry are preserved.

Choose settings before **Capture current view** or **Render video**. Each job
freezes its palette and opacity settings, stores them under `render.style` in
snapshot JSON or `style` in video `render.json`, and keeps them consistent across
video frames. A saved sequence can be rendered again with another palette.

Transparent sequence PNGs keep their alpha. **H.264 MP4 does not support alpha**,
so encoding composites those frames over the selected Background color. The PNG
sources remain transparent for later compositing in an editor.

```python
style = {
    "preset": "pastel",
    "robot_color": "#9BC9BE",       # sRGB hex
    "floor_color": "#F4F4F4",
    "background_color": "#FFFFFF",
    "transparent_background": True,
    "ignore_mesh_transparency": True,
}
viewer.save_snapshot("captures/mint.png", samples=128, style=style)
# Or: viewer.render_sequence(folder, fps=30, samples=128, style=style)
```

`RobotRenderer` / `RenderSettings` default to transparent Mint pastel, matching
the GUI. Legacy `save_snapshot()` / `render_sequence()` and the sequence CLI keep
their `studio` default with mesh transparency ignored. Their `style="pastel"`
selects the pastel palette; pass the dictionary above to enable alpha too.
For offline video:

```bash
uv run robot-render-sequence captures/sequences/run_01 --style pastel \
  --robot-color '#B6A6D9' --background-color '#FFFFFF' --transparent-background
# Add --use-mesh-transparency to retain original model alpha.
```

### Record a sequence, then render a video

The Studio/OV RTX capture window and mjviser **Sequence → Cycles Video** section provide:

1. **Sequence folder:** enter a new or empty folder, e.g. `captures/sequences/run_01`.
2. **Start recording:** continue moving the camera and sending normal robot/marker messages.
3. **Stop recording:** a row for the folder appears in **Sequences · render checked folders**,
   checked by default. Wait for buffered metadata to finish saving. The path field
   suggests a new date-based folder, so you can immediately record another take.
4. Repeat recording as needed, then uncheck the sequences you want to skip.
5. Set **Video FPS** (default 30) and the shared **Cycles samples** (default 128),
   then click the highlighted **Render video** button. All checked folders render
   in order, each saving its own video. Completed rows display the video path and
   stay in the list; uncheck them to skip a later render.

**Clear sequences** empties the sequence list, checkbox selections, and finished
progress in the desktop capture window and mjviser (including other connected browsers). Recorded
metadata, PNGs, and videos stay on disk; use **Add existing sequence** to restore
a folder to the list. Clearing is disabled during recording, metadata saving, or
video rendering. The same action is available as `viewer.rendering.clear_sequences()`.

The progress bar shows the current sequence/folder, aggregate completed/total
frames, elapsed time, and estimated remaining time for the entire selection.
Before the first frame completes, ETA shows “estimating”. Each sequence then
encodes its MP4. **Cancel render** stops after the current Cycles frame (or during
encoding) and skips queued sequences; metadata, completed videos, and PNGs remain.
A failed sequence displays its error while the rest continue. The live viewer remains usable,
and an already started render continues if you close the viewer/browser.

Recording only writes `sequence.json` and buffered `frames.jsonl` on a background
thread. Each displayed `sync()` records camera, integration state, joint positions,
colors, group visibility, and resolved marker geometry, including expiry/clear
results. No Blender process, mesh export, or PNG rendering runs during recording.
If the disk writer cannot keep up, recording stops with an error instead of
silently dropping states. Closing the viewer normally flushes the recording.

The browser that starts recording owns its camera track; disconnecting it stops
the recording with an error. To render an older recording, enter its existing
folder and click **Add existing sequence** to add a checked row. The list lasts
for this viewer session and survives browser reconnects; checkbox selection is
per browser. Rendering never replaces metadata.
Keep the original XML, includes, and mesh/texture assets available and unchanged:
metadata references these files instead of copying them. The root XML hash is
checked before rendering.

Video frames use wall-clock recording time, holding the most recently recorded
state between updates. A 10-second recording produces 300 frames at 30 FPS even
if the viewer update rate varies. Camera motion is reproduced with the first
recorded viewport's resolution/aspect ratio; studio lights remain fixed. Odd
image dimensions are padded by one pixel for H.264. One Blender process and one
USD import are reused for the entire video.

```text
captures/sequences/run_01/
├── video.mp4                # H.264, ready to play directly from this folder
├── sequence.json            # XML reference/hash, joint layout, duration, dimensions
├── frames.jsonl             # Timestamped state, camera, options, and objects
└── renders/<timestamp_id>/  # A new directory for each render
    ├── png/000000.png …     # Source images, alpha retained when requested
    └── metadata/
        ├── render.json     # FPS, samples, device, dimensions
        ├── rendered_frames.jsonl # Video frame → recorded state/camera mapping
        ├── progress.json
        ├── job.json
        └── render.log
```

Render later without opening a viewer:

```bash
uv run robot-render-sequence captures/sequences/run_01 --fps 30 --samples 128
```

This command also displays a terminal progress bar and ETA. FFmpeg is included
through the normal Python dependencies; an installed system FFmpeg is preferred.
The first video render installs Blender by the same process as a still capture.

Python API (continue the usual `sync()` loop between start and stop):

```python
viewer.sync()
viewer.start_recording("captures/sequences/run_01")  # client=... for multiple browsers
# ... update joints/markers and call viewer.sync() for each live frame ...
folder = viewer.stop_recording()  # Flush metadata; GUI uses wait=False
job = viewer.render_sequence(folder, fps=30, samples=128)
print(job.progress())  # phase, fraction (0–1), completed/total frames, elapsed, ETA
# Continue the live sync loop; job.cancel() requests cancellation.
video_path = job.result()  # Blocks until MP4 is ready, or raises the reported error
```

### Blender live view

Blender opens a rendered Eevee viewport with area lights, soft shadows, AgX
color management, and Eevee ray tracing enabled. Orbit with the middle mouse
button, pan with Shift + middle mouse, and zoom with the wheel. Programmatic
edits to `viewer.viewer.cam` update the camera; ordinary pose updates preserve
your mouse navigation. Closing the Blender window or pressing Ctrl+C in the
launcher stops the viewer.

The robot's mesh geometry, materials, and textures are exported through MuJoCo's
USD exporter **once**. Later `sync()` calls send only poses, colors, and marker
geometry over a private local connection. Blender reuses marker meshes and
objects. `sync()` waits for Blender to apply the snapshot, so `--hz` is a target
update rate; complex scenes can run slower. Physics remains in MuJoCo, and the
existing ZMQ publisher stays unchanged. Blender itself needs no extra Python
packages installed. A desktop display is required for the CLI viewer.

Geometry groups 0–2 are initially visible, matching native MuJoCo; the Python
adapter also exposes `viewer.viewer.opt.geomgroup`. Color overrides use flat
RGBA, and restoration reinstates the original material and texture. MuJoCo's
USD exporter determines model geometry/material conversion, so appearance may
differ from native OpenGL. Live updates support rigid robot geometry; changing
mesh topology or deformable objects is not supported. Native interaction
controls are not replicated.
The initial Blender integration is validated on Linux x86-64 with Blender 4.5;
macOS/Windows executable support has not been exercised here.

To keep a self-contained Blender file for further editing or Cycles rendering:

```python
viewer.sync()
viewer.viewer.save_scene("robot.blend")  # Includes packed textures.
```

Eevee's ray tracing improves real-time lighting/reflections; it is not Cycles
path tracing. You can switch to Cycles in Blender's Render Properties, but
interactive updates will generally be slower. Cycles starts with 32 viewport
samples and 128 final-render samples, with denoising enabled for both. Unchanged
sync snapshots leave Blender's scene untouched so a stationary view can finish
accumulating samples. Motion and camera navigation restart that accumulation.
No Cycles performance is assumed.

---

## 📡 Sending Messages (Client Side)

Install `robot-viewer` and `robot-msg-irsl==0.5.4` in your sender project and use
`ZMQPublisher` to send the generated protocol-2 messages. The Python import remains
`robot_msg`.

```python
from robot_viewer import ZMQPublisher
from robot_msg import (
    ports, SphereInput, ArrowInput, Arrow2Input, FrameInput,
    EllipsoidInput, RobotJointInput, MeshColorInput,
)
from robot_msg.types import ColorRGBA, Lifetime, Pose, Vec3

# Create a publisher and bind to the viewer's TCP port (HTTP stays on 8080).
pub = ZMQPublisher(addr=f"tcp://*:{ports.VIEWER}", bind=True)

pub.send(SphereInput(frame_id="world", position=Vec3(.3, 0., .5),
                     color=ColorRGBA(1., 0., 0., 1.), radius=.02))
pub.send(ArrowInput(frame_id="world", position=Vec3(0., 0., 0.),
                    direction=Vec3(.1, 0., .2), color=ColorRGBA(0., 1., 0., 1.)))
pub.send(Arrow2Input(frame_id="world", start=Vec3(0., 0., 0.), end=Vec3(.5, 0., .5)))
pub.send(FrameInput(frame_id="world", pose=Pose(Vec3(0., 0., .3))))
pub.send(EllipsoidInput(frame_id="world", pose=Pose(Vec3(.2, .1, .3)),
                        radii=Vec3(.05, .03, .08), color=ColorRGBA(.8, .2, .2, .7)))
pub.send(RobotJointInput(qpos=[0., -.5, 0., -1.5, 0., 1., 0.]))

# Temporary color; the default lifetime for mesh colors is persistent.
pub.send(MeshColorInput(link_name="panda_link4", color=ColorRGBA(1., 0., 0., 1.),
                        lifetime=Lifetime("seconds", .2)))
pub.send(MeshColorInput(geom_name="panda_hand_visual", color=ColorRGBA(.1, .8, .2, 1.)))

# A list is encoded as one ordered MessageBatch.
pub.send([
    SphereInput(frame_id="world", position=Vec3(.1, 0., .4), color=ColorRGBA(0., 0., 1., 1.)),
    SphereInput(frame_id="world", position=Vec3(.2, 0., .4), color=ColorRGBA(1., 1., 0., 1.)),
])
pub.close()
```

---

## 🗂️ Message Types

| Type | Fields | Description |
|---|---|---|
| `SphereInput` | `frame_id`, `position`, `color`, `radius` | Sphere marker |
| `ArrowInput` | `frame_id`, `position`, `direction`, `color`, `width` | Arrow from position along direction |
| `Arrow2Input` | `frame_id`, `start`, `end`, `color`, `width` | Arrow from start to end point |
| `FrameInput` | `frame_id`, `pose`, `width`, `length`, `alpha` | Coordinate frame (XYZ axes) |
| `BoxInput` | `frame_id`, `pose`, `half_extents`, `color` | Oriented box |
| `LineInput` | `frame_id`, `start`, `end`, `width`, `color` | Capsule segment; `width` is its radius |
| `EllipsoidInput` | `frame_id`, `pose`, `radii`, `color` | Oriented ellipsoid / uncertainty region |
| `RobotJointInput` | `qpos`, `max_queue_age` | Robot joint vector with optional queue freshness limit |
| `MeshColorInput` | `link_name` or `geom_name`, `color`, `lifetime` | Change robot mesh(geom) color temporarily or persistently |

Vectors, colors, and poses use `Vec3`, `ColorRGBA`, and `Pose` from `robot_msg.types`.
Pose orientation is a **unit XYZW** `Quaternion(x, y, z, w)`; it maps child coordinates
into the reference frame (`p_ref = R * p_child + position`). MuJoCo's WXYZ quaternion
and matrix conventions are converted at the viewer boundary. Use `frame_id="world"`
for world-space drawings.

The message definitions come from `robot_msg`. Every ZMQ frame uses the compact
binary envelope from `robot_msg.encode()`. A Python list is carried in the
canonical binary `common.message_batch` message so it remains one ZMQ frame.

### Bulk markers, lifetimes, and clearing

`BatchArrowInput`, `BatchArrow2Input`, `BatchBoxInput`, `BatchEllipsoidInput`,
`BatchFrameInput`, `BatchLineInput`, and `BatchSphereInput` render ordered `items`
with shared appearance. Arrow/line items hold typed endpoint/vector fields;
boxes, ellipsoids, and frames hold `Pose` items; spheres hold `Vec3` items.
`BatchMeshColorInput.items` groups typed color changes, and
`BatchRobotJointInput.items` applies its last `qpos` to the viewer's single robot.

```python
from robot_msg import BatchArrowInput, BatchArrowInputItemsItem, Clear
from robot_msg.types import ColorRGBA, Lifetime, Vec3

pub.send(BatchArrowInput(frame_id="world", items=[
    BatchArrowInputItemsItem(position=Vec3(.1, .2, .3), direction=Vec3(0., 0., .05)),
    BatchArrowInputItemsItem(position=Vec3(.2, .3, .4), direction=Vec3(.05, 0., 0.)),
], color=ColorRGBA(1., 0., 1., .7), id="particles", lifetime=Lifetime("seconds", 1 / 60)))
pub.send(Clear())
```

`Lifetime("one_frame")` is the default for markers and consumes them after one
rendered frame. `Lifetime("persistent")` retains markers until hidden, replaced,
or cleared, and is the default for mesh colors. `Lifetime("seconds", seconds)`
expires after a positive interval on the **receiver's monotonic clock starting
at receipt**, never a sender metadata timestamp. Expiration runs every frame,
even while the publisher is silent. Only the `seconds` mode accepts a seconds value.

Joint messages instead use `max_queue_age` (zero means no queue age limit) to
reject stale queued updates. An applied robot pose never expires or resets when
markers are cleared. Sequence recording timestamps do not alter these clocks.

Use a stable nonempty `id` to replace an object or entire batch and refresh its
deadline. `visible=False` or an empty batch removes that ID. Queued updates are
coalesced by ID before building geometry, so 12 updates of a 200-arrow batch draw
only the newest 200 arrows. Anonymous markers are independent and remain bounded
by the scene capacity. Oversize geometry is clipped to MuJoCo's scene limit.

`Clear()` removes all direct and message-created markers, deadlines and mesh
color effects, retaining the robot model and its last joint pose. Clear is
processed in delivery order, including inside a `MessageBatch`: objects after
the clear are displayed. The main loop syncs at `--hz` even without incoming
traffic; `--t-out` is accepted for compatibility but no longer delays expiry.

The installed `robot-msg-irsl==0.5.4` package supplies the protocol-2 wire types.
The 0.5.x protocol is additive: existing 0.3.0/0.4.0 viewer-message senders remain wire-compatible.
Legacy duplicate message types and protocol-1 payload fields are not supported;
upgrade protocol-1 senders alongside the viewer. No editable robot_msg submodule is required.

Tests use real MuJoCo/USD geometry, the mjviser server, and Blender datablocks/IPC:

```bash
uv run --with pytest python -m pytest
```

Blender integration tests run in background mode when Blender is installed;
they are skipped without downloading it otherwise. They cover the common
API/ZMQ contract, primitive dimensions, joint poses, camera placement, color and
texture restoration, marker reuse, expiry, saving, and process cleanup.
OV RTX CPU scene/contract tests run without the optional NVIDIA runtime. On a
supported RTX workstation, opt into actual GPU pixel tests:

```bash
ROBOT_VIEWER_TEST_OVRTX=1 uv run --extra ovrtx --with pytest python -m pytest tests/test_ovrtx_renderer.py
```

---

## 🏗️ Project Structure

```
robot_viewer/
├── pyproject.toml
├── README.md
└── src/
    └── robot_viewer/
        ├── __init__.py        # RobotViewer class
        ├── launch.py          # CLI entry point
        ├── renderers.py       # Backend selection (studio default)
        ├── studio_renderer.py # Read-only MuJoCo Studio window + frame history
        └── utils/
            ├── msg_type.py    # Compatibility exports for robot_msg types
            └── zmq_module.py  # robot_msg-based ZMQ send/recv helpers
```

---

## 🛠️ Dependencies

| Package | Purpose |
|---|---|
| [`mujoco`](https://mujoco.org/) | Physics simulation, passive viewer, and USD export (exactly 4.0.1) |
| [`mjviser`](https://github.com/mujocolab/mjviser) | Web rendering through Viser |
| `usd-core`, `pillow` | MuJoCo USD scene and texture export for Blender and OV RTX |
| `ovrtx`, `ovstage`, `pyglet` | Optional `ovrtx` extra: standalone NVIDIA RTX runtime, persistent stage, and desktop window |
| `imageio-ffmpeg` | FFmpeg binary fallback for H.264 sequence videos |
| [Blender](https://www.blender.org/) | Eevee desktop rendering; official binary, installed separately from Python wheels |
| [`pyzmq`](https://pyzmq.readthedocs.io/) | ZMQ messaging |
| `robot-msg-irsl==0.5.4` | Protocol-2 shared message definitions and codecs (`import robot_msg`) |
| [`tyro`](https://brentyi.github.io/tyro/) | CLI argument parsing |
