diff --git a/.github/workflows/build_wheels.yaml b/.github/workflows/build_wheels.yaml index 4099ed200..327e7165c 100644 --- a/.github/workflows/build_wheels.yaml +++ b/.github/workflows/build_wheels.yaml @@ -14,7 +14,7 @@ jobs: matrix: os: - ubuntu-latest - - macos-14 + - macos-15 steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index eb6bea24c..5ecb53f85 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -43,7 +43,7 @@ jobs: run: xvfb-run make pytest pythonpackage-macos: - runs-on: macos-14 + runs-on: macos-15 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} steps: diff --git a/CMakeLists.txt b/CMakeLists.txt index fe288a399..335f0fa27 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,15 +49,6 @@ FetchContent_Declare(Eigen3 URL https://gitlab.com/libeigen/eigen/-/archive/3.4.1/eigen-3.4.1.tar.gz EXCLUDE_FROM_ALL ) -FetchContent_Declare( - egl_headers - GIT_REPOSITORY https://github.com/KhronosGroup/EGL-Registry.git - GIT_TAG main - GIT_SHALLOW TRUE -) - -FetchContent_MakeAvailable(pybind11 Eigen3 egl_headers) -# egl headers -include_directories(${egl_headers_SOURCE_DIR}/api) +FetchContent_MakeAvailable(pybind11 Eigen3) add_subdirectory(src) diff --git a/docker/Dockerfile b/docker/Dockerfile index d40dace23..161e0cc8f 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -48,7 +48,7 @@ RUN chmod +x /usr/local/bin/link-editable-source \ pybind11 \ cmake \ ninja \ - "mujoco==3.2.6" \ + "mujoco==4.0.1" \ "pin==3.7.0" \ && uv pip install /opt/rcs-src \ && uv pip install --no-build-isolation /opt/rcs-src/extensions/rcs_fr3 \ diff --git a/docs/getting_started/index.md b/docs/getting_started/index.md index 16ac8644b..575d5418b 100644 --- a/docs/getting_started/index.md +++ b/docs/getting_started/index.md @@ -63,7 +63,6 @@ Here is a simple example of direct robot control using the low-level API: ```python import rcs from rcs import sim -from rcs._core.sim import CameraType from rcs.camera.sim import SimCameraConfig, SimCameraSet from time import sleep import numpy as np diff --git a/docs/user_guide/scene_configuration.md b/docs/user_guide/scene_configuration.md index aeddac885..5c7d443f5 100644 --- a/docs/user_guide/scene_configuration.md +++ b/docs/user_guide/scene_configuration.md @@ -100,7 +100,7 @@ This is the main top-level config for the scene API. | `task_cfg` | Optional task-specific config | Add pick/place or other task logic | | `scene` | Base scene XML path or scene key | Usually from `SCENE_PATHS[...]` | | `gripper_cfgs` | Optional gripper config per robot | Add one gripper per robot | -| `camera_cfgs` | Optional camera config dictionary | Define resolution, type, and frame rate for named cameras | +| `camera_cfgs` | Optional camera config dictionary | Define the model camera, resolution and frame rate for named cameras | | `max_relative_movement` | Relative action limit | Limit per-step Cartesian delta | | `relative_to` | Relative action reference | Usually `RelativeTo.LAST_STEP` or `RelativeTo.NONE` | | `robot_to_shared_base_frame` | Per-robot offset relative to the shared base frame | Multi-robot layouts | @@ -149,8 +149,8 @@ Each gripper entry usually defines: Each camera entry usually defines: -- camera identifier -- camera type +- camera identifier, the name of the camera in the MuJoCo model. Cameras attached to a body or with a + tracking `mode` in MJCF move with the simulation, e.g. for videos. - resolution - frame rate @@ -299,6 +299,58 @@ Example: - `depth[y, x] == 1500` means the point is about **1.5 m** away from the camera +## Camera timing + +Simulation cameras render in Python (`rcs.camera.sim.SimCameraSet`) and show one of two simulation states: + +- `render_on_demand=True` (default): the state at the moment the frames are requested, e.g. after the + last env step. +- `render_on_demand=False`: the state at the last *exposure* of each camera, like a real camera that + records at its `frame_rate`. While the simulation steps, it captures its state at each camera frame + rate (the state only, no rendering, about a microsecond per capture); frames are rendered from the + latest captured state when they are requested. With a 30 Hz camera and a 10 Hz env, an observation + therefore shows the scene up to 33 ms before the end of the env step, as a real camera would. + +```python +camera_set = SimCameraSet(simulation, camera_cfgs, physical_units=True, render_on_demand=False) +``` + +Captures follow a fixed schedule of simulation time (`k / frame_rate`, no drift) and happen at the +physics step closest to each capture time. Frame time stamps are the simulation time of the rendered +state, and `get_timestamp_frames(ts)` renders the latest exposure at or before `ts` (the last +`max_buffer_frames` captured states are kept). Cameras with different frame rates are captured +independently. + +## Rendering backend (Filament) + +By default, simulation cameras and the GUI use MuJoCo's classic OpenGL renderer. MuJoCo >= 4.0 also +ships the physically based [Filament](https://github.com/google/filament) renderer and the new +MuJoCo Studio viewer. Switch to them with the `renderer` flag of `SimConfig`: + +```python +from rcs.sim import RendererBackend, SimConfig + +sim_cfg = SimConfig(async_control=False, realtime=False, renderer=RendererBackend.FILAMENT) +``` + +With this flag + +- `SimCameraSet(...)` returns a `FilamentSimCameraSet`: color and depth images are rendered with Filament + instead of the classic renderer (both timing modes below are supported). Depth images always use the + metric units described above. The depth pass is a second Filament render per camera, so + it is skipped when `CameraSetWrapper(include_depth=False)` (or `FilamentSimCameraSet(render_depth=False)`) + is used. +- `open_gui()` launches MuJoCo Studio instead of the passive `mujoco.viewer`. Studio runs in the GUI + subprocess under a regular `python` interpreter (not `mjpython`, also on macOS). + +Environment variables for fine tuning: + +- `RCS_FILAMENT_GRAPHICS_API=opengl|vulkan` graphics API of the camera renderer (default `opengl`, or `vulkan` + on Linux without an X display, where Filament's OpenGL backend does not work) +- `RCS_FILAMENT_SOFTWARE_RENDERING=1` force software rendering for the cameras +- `RCS_FILAMENT_GFX=opengl|vulkan|web|...` Studio graphics mode; `web` serves the viewer over http instead + of opening a window + ### Camera placement #### Fixed scene camera diff --git a/examples/fr3/fr3_direct_control.py b/examples/fr3/fr3_direct_control.py index 342f1dec9..e16a33c74 100644 --- a/examples/fr3/fr3_direct_control.py +++ b/examples/fr3/fr3_direct_control.py @@ -2,7 +2,7 @@ import numpy as np from rcs._core.common import RobotPlatform -from rcs._core.sim import CameraType, SimConfig +from rcs._core.sim import SimConfig from rcs.camera.sim import SimCameraConfig, SimCameraSet from rcs.envs.configs import EmptyWorldFR3 from rcs_fr3._core import hw @@ -86,18 +86,10 @@ def main(): gripper_cfg = cfg.gripper_cfgs[fr3] # type: ignore gripper = sim.SimGripper(simulation, gripper_cfg) - # add camera to have a rendering gui + # render the wrist camera of the model cameras = { - "default_free": sim.SimCameraConfig( - identifier="", - type=CameraType.default_free, - resolution_width=1280, - resolution_height=720, - frame_rate=20, - ), "wrist": SimCameraConfig( identifier="wrist_0", - type=CameraType.fixed, resolution_width=640, resolution_height=480, frame_rate=30, diff --git a/examples/fr3/fr3_env_cartesian_control.py b/examples/fr3/fr3_env_cartesian_control.py index 982292fc5..ad2401b73 100644 --- a/examples/fr3/fr3_env_cartesian_control.py +++ b/examples/fr3/fr3_env_cartesian_control.py @@ -2,7 +2,7 @@ import gymnasium as gym from rcs._core.common import RobotPlatform -from rcs._core.sim import SimConfig +from rcs._core.sim import RendererBackend, SimConfig from rcs.camera.sim import SimCameraSet from rcs.envs.base import ( CameraSetWrapper, @@ -50,6 +50,7 @@ def main(): sim_cfg = SimConfig( realtime=False, async_control=False, + renderer=RendererBackend.FILAMENT, ) mjmodel = scene.create_model(cfg) diff --git a/include/rcs/utils.h b/include/rcs/utils.h index f12cb85a1..75ecf41f9 100644 --- a/include/rcs/utils.h +++ b/include/rcs/utils.h @@ -40,10 +40,6 @@ Eigen::Matrix array2eigen( Eigen::Matrix matrix(array.data()); return matrix; } -void bootstrap_egl_context(std::uintptr_t fn_addr, std::uintptr_t display, - std::uintptr_t context); -void bootstrap_gl_context(); -void ensure_current(); /*** * @brief thread safe holder for a single value, e.g. to hand data from a diff --git a/pyproject.toml b/pyproject.toml index 240522195..9af1e7f8b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,7 @@ requires = [ "pybind11", "cmake", "ninja", - "mujoco==3.10.0", + "mujoco==4.0.1", "pin==3.7.0", ] build-backend = "scikit_build_core.build" @@ -36,7 +36,7 @@ dependencies = [ "rpyc~=6.0.2", "pyarrow", "simplejpeg", - "mujoco==3.10.0", + "mujoco==4.0.1", "pin==3.7.0", # pin 3.7.0 currently resolves against older urdfdom/tinyxml SONAMEs at runtime "cmeel-urdfdom<5", @@ -76,7 +76,7 @@ dev = [ "twine~=6.0", ] build_deps = [ - "mujoco==3.10.0", + "mujoco==4.0.1", "pin==3.7.0", "cmeel-urdfdom<5", "cmeel-tinyxml2<11", @@ -93,7 +93,7 @@ environment = { SKBUILD_BUILD_DIR = "/tmp/rcs-build/{wheel_tag}" } archs = ["x86_64"] manylinux-x86_64-image = "manylinux_2_28" before-all = "yum install -y epel-release && yum install -y libXi-devel libXcursor-devel libXinerama-devel libXrandr-devel glfw-devel" -repair-wheel-command = "auditwheel repair -w {dest_dir} {wheel} --exclude libmujoco.so.3.10.0 --exclude libpinocchio_default.so.3.7.0 --exclude libpinocchio_parsers.so.3.7.0" +repair-wheel-command = "auditwheel repair -w {dest_dir} {wheel} --exclude libmujoco.so.4.0.1 --exclude libpinocchio_default.so.3.7.0 --exclude libpinocchio_parsers.so.3.7.0" [tool.cibuildwheel.macos] archs = ["arm64"] diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index a9c2380ef..b9d0385cf 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -351,8 +351,6 @@ def FrankaHandTCPOffset() -> numpy.ndarray[tuple[typing.Literal[4], typing.Liter def IdentityRotMatrix() -> numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]]: ... def IdentityRotQuatVec() -> numpy.ndarray[tuple[typing.Literal[4]], numpy.dtype[numpy.float64]]: ... def IdentityTranslation() -> numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]]: ... -def _bootstrap_egl_context(fn_addr: int, display: int, context: int) -> None: ... -def _bootstrap_gl_context() -> None: ... HARDWARE: RobotPlatform # value = LATERAL_GRASP: GraspType # value = diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index 7f6a21d23..ca800634e 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -8,16 +8,18 @@ import typing import numpy import rcs._core.common +from rcs._core.common import BaseCameraConfig as SimCameraConfig __all__: list[str] = [ - "CameraType", + "CLASSIC", + "CapturedState", "DynamicJointSchema", "DynamicJointState", - "FrameSet", + "FILAMENT", "GuiClient", + "RendererBackend", "Sim", "SimCameraConfig", - "SimCameraSet", "SimConfig", "SimGripper", "SimGripperConfig", @@ -28,33 +30,47 @@ __all__: list[str] = [ "SimTilburgHand", "SimTilburgHandConfig", "SimTilburgHandState", - "default_free", - "fixed", - "free", - "tracking", ] M = typing.TypeVar("M", bound=int) -class CameraType: - """ - Members: +class CapturedState: + @property + def state(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... + @property + def timestamp(self) -> float: ... - free +class DynamicJointSchema: + joint_names: list[str] + joint_types: list[int] + qpos_sizes: list[int] + qvel_sizes: list[int] + def __init__(self) -> None: ... - tracking +class DynamicJointState(typing.Generic[M]): + qpos: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + qvel: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] + def __init__(self) -> None: ... - fixed +class GuiClient: + def __init__(self, id: str) -> None: ... + def get_model_bytes(self) -> bytes: ... + def set_model_and_data(self, arg0: int, arg1: int) -> None: ... + def sync(self) -> None: ... + +class RendererBackend: + """ + Members: + + CLASSIC - default_free + FILAMENT """ + CLASSIC: typing.ClassVar[RendererBackend] # value = + FILAMENT: typing.ClassVar[RendererBackend] # value = __members__: typing.ClassVar[ - dict[str, CameraType] - ] # value = {'free': , 'tracking': , 'fixed': , 'default_free': } - default_free: typing.ClassVar[CameraType] # value = - fixed: typing.ClassVar[CameraType] # value = - free: typing.ClassVar[CameraType] # value = - tracking: typing.ClassVar[CameraType] # value = + dict[str, RendererBackend] + ] # value = {'CLASSIC': , 'FILAMENT': } def __eq__(self, other: typing.Any) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... @@ -70,46 +86,18 @@ class CameraType: @property def value(self) -> int: ... -class DynamicJointSchema: - joint_names: list[str] - joint_types: list[int] - qpos_sizes: list[int] - qvel_sizes: list[int] - def __init__(self) -> None: ... - -class DynamicJointState(typing.Generic[M]): - qpos: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] - qvel: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] - def __init__(self) -> None: ... - -class FrameSet: - def __init__( - self, - color_frames: dict[str, numpy.ndarray[tuple[M], numpy.dtype[numpy.uint8]]], - depth_frames: dict[str, numpy.ndarray[tuple[M], numpy.dtype[numpy.float32]]], - timestamp: float, - ) -> None: ... - @property - def color_frames(self) -> dict[str, numpy.ndarray[tuple[M], numpy.dtype[numpy.uint8]]]: ... - @property - def depth_frames(self) -> dict[str, numpy.ndarray[tuple[M], numpy.dtype[numpy.float32]]]: ... - @property - def timestamp(self) -> float: ... - -class GuiClient: - def __init__(self, id: str) -> None: ... - def get_model_bytes(self) -> bytes: ... - def set_model_and_data(self, arg0: int, arg1: int) -> None: ... - def sync(self) -> None: ... - class Sim: def __init__(self, mjmdl: int, mjdata: int) -> None: ... def _start_gui_server(self, id: str) -> None: ... def _stop_gui_server(self) -> None: ... + def captured_state_count(self, id: int) -> int: ... + def clear_captured_states(self, id: int) -> None: ... + def get_captured_state(self, id: int, max_timestamp: float = ...) -> CapturedState | None: ... def get_config(self) -> SimConfig: ... def get_dynamic_joint_schema(self) -> DynamicJointSchema: ... def get_dynamic_joint_state(self) -> DynamicJointState: ... def is_converged(self) -> bool: ... + def register_state_capture(self, frame_rate: float, buffer_size: int, state_spec: int) -> int: ... def reset(self) -> None: ... def set_config(self, cfg: SimConfig) -> bool: ... def set_dynamic_joint_state(self, schema: DynamicJointSchema, state: DynamicJointState) -> None: ... @@ -117,31 +105,13 @@ class Sim: def step_until_convergence(self) -> None: ... def sync_gui(self) -> None: ... -class SimCameraConfig(rcs._core.common.BaseCameraConfig): - type: CameraType - def __copy__(self) -> SimCameraConfig: ... - def __deepcopy__(self, arg0: dict) -> SimCameraConfig: ... - def __init__( - self, identifier: str, frame_rate: int, resolution_width: int, resolution_height: int, type: CameraType = ... - ) -> None: ... - -class SimCameraSet: - def __init__( - self, sim: Sim, cameras: dict[str, SimCameraConfig], render_on_demand: bool = True, max_buffer_frames: int = 100 - ) -> None: ... - def buffer_size(self) -> int: ... - def clear_buffer(self) -> None: ... - def get_latest_frameset(self) -> FrameSet | None: ... - def get_timestamp_frameset(self, ts: float) -> FrameSet | None: ... - @property - def _sim(self) -> Sim: ... - class SimConfig: async_control: bool frequency: float max_convergence_steps: int memory: int realtime: bool + renderer: RendererBackend def __copy__(self) -> SimConfig: ... def __deepcopy__(self, arg0: dict) -> SimConfig: ... def __init__( @@ -151,6 +121,7 @@ class SimConfig: frequency: float = 30.0, max_convergence_steps: int = 500, memory: int = -1, + renderer: RendererBackend = ..., ) -> None: ... class SimGripper(rcs._core.common.Gripper): @@ -383,7 +354,5 @@ class SimTilburgHandState(rcs._core.common.HandState): @property def last_qpos(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... -default_free: CameraType # value = -fixed: CameraType # value = -free: CameraType # value = -tracking: CameraType # value = +CLASSIC: RendererBackend # value = +FILAMENT: RendererBackend # value = diff --git a/python/rcs/camera/hw.py b/python/rcs/camera/hw.py index da8dc8d93..799e5dacd 100644 --- a/python/rcs/camera/hw.py +++ b/python/rcs/camera/hw.py @@ -250,7 +250,7 @@ def polling_thread(self, warm_up: bool = True): with self._buffer_lock: self._buffer[self._next_ring_index] = frame_set self._next_ring_index = (self._next_ring_index + 1) % self.max_buffer_frames - self._buffer_len = max(self._buffer_len + 1, self.max_buffer_frames) + self._buffer_len = min(self._buffer_len + 1, self.max_buffer_frames) # video recording for camera_key, writer in self.writer.items(): if frame_set is not None: diff --git a/python/rcs/camera/sim.py b/python/rcs/camera/sim.py index 12af75b47..39a2e2065 100644 --- a/python/rcs/camera/sim.py +++ b/python/rcs/camera/sim.py @@ -1,120 +1,337 @@ +""" +Simulation cameras. + +Images are rendered in Python, either with MuJoCo's classic OpenGL renderer or with Filament +(``SimConfig(renderer=RendererBackend.FILAMENT)``). They show one of two simulation states: + +- ``render_on_demand=True`` (default): the state at the time the frames are requested. +- ``render_on_demand=False``: the state at the last exposure of each camera, like a real camera that + records at its ``frame_rate``. The simulation captures its state at each camera's frame rate while + it steps (``Sim.register_state_capture``, cheap: no rendering), and frames are rendered from the + captured states when they are requested. + +In both cases the state is loaded into a separate render-only ``MjData`` and its kinematics are +recomputed, so the image, its time stamp and the camera extrinsics always belong together. +""" + import logging +import math +from collections import deque from datetime import datetime from typing import Literal +import cv2 import mujoco import numpy as np - -# from rcs._core.common import BaseCameraConfig from rcs._core import common -from rcs._core.sim import FrameSet as _FrameSet -from rcs._core.sim import SimCameraConfig -from rcs._core.sim import SimCameraSet as _SimCameraSet +from rcs._core.sim import RendererBackend, SimCameraConfig from rcs.camera.interface import BaseCameraSet, CameraFrame, DataFrame, Frame, FrameSet -from rcs.sim import render_context_bootstrap +from rcs.sim import filament, render_context_bootstrap from rcs import sim +logger = logging.getLogger(__name__) + +# state that is captured and restored for rendering +STATE_SPEC = mujoco.mjtState.mjSTATE_INTEGRATION + + +def _camera_id(model: mujoco.MjModel, cfg: SimCameraConfig) -> int: + cam_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_CAMERA, cfg.identifier) + if cam_id < 0: + msg = f"camera {cfg.identifier!r} does not exist in the model" + raise ValueError(msg) + return cam_id + + +def _intrinsics( + model: mujoco.MjModel, cfg: SimCameraConfig +) -> np.ndarray[tuple[Literal[3], Literal[4]], np.dtype[np.float64]]: + fovy = model.cam_fovy[_camera_id(model, cfg)] + fx = fy = 0.5 * cfg.resolution_height / np.tan(fovy * np.pi / 360) + return np.array( + [ + [fx, 0, (cfg.resolution_width - 1) / 2, 0], + [0, fy, (cfg.resolution_height - 1) / 2, 0], + [0, 0, 1, 0], + ] + ) + + +def _extrinsics( + model: mujoco.MjModel, data: mujoco.MjData, cfg: SimCameraConfig +) -> np.ndarray[tuple[Literal[4], Literal[4]], np.dtype[np.float64]]: + cam_id = _camera_id(model, cfg) + xpos = data.cam_xpos[cam_id] + xmat = data.cam_xmat[cam_id].reshape(3, 3) + + cam = common.Pose(rotation=xmat, translation=xpos) + # put z axis infront + rotation_p = common.Pose(rpy_vector=np.array([np.pi, 0, 0]), translation=np.array([0, 0, 0])) # type: ignore + cam = cam * rotation_p + + return cam.inverse().pose_matrix() + + +class _ClassicRenderer: + """MuJoCo's classic OpenGL renderer, offscreen, one context per resolution. + + Unlike ``mujoco.Renderer`` this is not limited by the model's ``offwidth``/``offheight``. + """ + + def __init__(self, model: mujoco.MjModel, physical_units: bool): + render_context_bootstrap.require("simulation camera rendering") + render_context_bootstrap.make_current() + self._model = model + self._physical_units = physical_units + self._scene = mujoco.MjvScene(model, maxgeom=2000) + self._opt = mujoco.MjvOption() + self._contexts: dict[tuple[int, int], tuple[mujoco.MjrContext, mujoco.MjrRect, np.ndarray, np.ndarray]] = {} + extent = model.stat.extent + self._near = model.vis.map.znear * extent + self._far = model.vis.map.zfar * extent + + def _context(self, width: int, height: int): + key = (width, height) + if key not in self._contexts: + ctx = mujoco.MjrContext(self._model, mujoco.mjtFontScale.mjFONTSCALE_150) + mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, ctx) + mujoco.mjr_resizeOffscreen(width, height, ctx) + rgb = np.empty((height, width, 3), dtype=np.uint8) + depth = np.empty((height, width), dtype=np.float32) + self._contexts[key] = (ctx, mujoco.MjrRect(0, 0, width, height), rgb, depth) + return self._contexts[key] + + def update(self, data: mujoco.MjData): + pass + + def render( + self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int, depth: bool + ) -> tuple[np.ndarray, np.ndarray | None]: + """Returns (H, W, 3) uint8 RGB and, if requested, (H, W) float32 depth, both top row first. + + Depth is in meters with ``physical_units``, otherwise the raw [0, 1] OpenGL depth buffer. + """ + render_context_bootstrap.make_current() + ctx, viewport, rgb_buffer, depth_buffer = self._context(width, height) + mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, ctx) + # The scene is shared by all cameras and mjv_updateScene positions infinite planes (e.g. the + # floor) from scene.camera *before* it updates the camera, i.e. from the previously rendered + # camera. Update the camera first so that images do not depend on the render order. + mujoco.mjv_updateCamera(self._model, data, camera, self._scene) + mujoco.mjv_updateScene(self._model, data, self._opt, None, camera, mujoco.mjtCatBit.mjCAT_ALL, self._scene) + mujoco.mjr_render(viewport, self._scene, ctx) + mujoco.mjr_readPixels(rgb_buffer, depth_buffer if depth else None, viewport, ctx) + # OpenGL reads bottom-up + rgb = cv2.flip(rgb_buffer, 0) + if not depth: + return rgb, None + depth_image = cv2.flip(depth_buffer, 0) + if self._physical_units: + # Convert from [0 1] to depth in meters, see links below: + # http://stackoverflow.com/a/6657284/1461210 + # https://www.khronos.org/opengl/wiki/Depth_Buffer_Precision + depth_image = self._near / (1 - depth_image * (1 - self._near / self._far)) + return rgb, depth_image + + def close(self): + if not self._contexts: + return + render_context_bootstrap.make_current() + for ctx, *_ in self._contexts.values(): + ctx.free() + self._contexts.clear() + + +class _FilamentRenderer: + """Adapter of :class:`rcs.sim.filament.FilamentRenderer` (depth is always metric).""" + + def __init__(self, model: mujoco.MjModel): + self._renderer = filament.FilamentRenderer(model) + + def update(self, data: mujoco.MjData): + self._renderer.update(data) + + def render( + self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int, depth: bool + ) -> tuple[np.ndarray, np.ndarray | None]: + rgb = self._renderer.render(data, camera, width, height) + return rgb, self._renderer.render_depth(data, camera, width, height) if depth else None + + def close(self): + self._renderer.close() + + +class SimCameraSet: + """Set of cameras in a MuJoCo simulation, implements BaseCameraSet. -class SimCameraSet(_SimCameraSet): - """Represents a set of cameras in a mujoco simulation. - Implements BaseCameraSet + Rendering uses MuJoCo's classic OpenGL renderer, or Filament if the simulation was configured with + ``SimConfig(renderer=RendererBackend.FILAMENT)`` (constructing this class then returns a + :class:`FilamentSimCameraSet`). + + Args: + simulation: the simulation to render. + cameras: camera configurations by name. Each renders the camera of the model named by its + ``identifier``; cameras attached to bodies or with a tracking ``mode`` in MJCF move with the + simulation. + physical_units: depth in meters (scaled by ``BaseCameraSet.DEPTH_SCALE``); otherwise the raw + [0, 1] depth buffer of the classic renderer is scaled. + render_on_demand: if True, frames show the simulation state at the time they are requested. + If False, they show the state at the last exposure of each camera according to its + ``frame_rate``, which the simulation captures while it steps, see module docstring. + max_buffer_frames: number of rendered framesets (``render_on_demand=True``) or captured states + per frame rate (``render_on_demand=False``) that are kept for ``get_timestamp_frames``. + render_depth: render depth images; frames have ``depth=None`` otherwise. Set automatically by + ``CameraSetWrapper(include_depth=...)``. """ + DEPTH_SCALE: int = BaseCameraSet.DEPTH_SCALE + + def __new__(cls, simulation: sim.Sim, *_args, **_kwargs): + if cls is SimCameraSet and simulation.get_config().renderer == RendererBackend.FILAMENT: + return super().__new__(FilamentSimCameraSet) + return super().__new__(cls) + def __init__( self, simulation: sim.Sim, cameras: dict[str, SimCameraConfig], physical_units: bool = False, render_on_demand: bool = True, + max_buffer_frames: int = 100, + render_depth: bool = True, ): - self._logger = logging.getLogger(__name__) + if max_buffer_frames <= 0: + msg = "max_buffer_frames must be positive" + raise ValueError(msg) + self._sim = simulation self.cameras = cameras self.physical_units = physical_units + self.render_on_demand = render_on_demand + self.render_depth = render_depth + self._max_buffer_frames = max_buffer_frames + self._renderer = self._create_renderer() - render_context_bootstrap.require("simulation camera rendering") - super().__init__(simulation, cameras, render_on_demand=render_on_demand) - self._sim: sim.Sim + model = self._sim.model + self._render_data = mujoco.MjData(model) + self._state = np.empty(mujoco.mj_stateSize(model, STATE_SPEC)) + self._mj_cameras: dict[str, mujoco.MjvCamera] = {} + for name, cfg in cameras.items(): + cam = mujoco.MjvCamera() + cam.type = mujoco.mjtCamera.mjCAMERA_FIXED + cam.fixedcamid = _camera_id(model, cfg) + self._mj_cameras[name] = cam - def get_latest_frames(self) -> FrameSet | None: - """Should return the latest frame from the camera with the given name.""" - return self._cpp_to_python_frames(super().get_latest_frameset()) + # render_on_demand=True: rendered framesets, newest last + self._buffer: deque[FrameSet] = deque(maxlen=max_buffer_frames) + self._buffer_states: deque[np.ndarray] = deque(maxlen=max_buffer_frames) + # render_on_demand=False: one state capture per frame rate and the cameras using it + self._captures: dict[int, list[str]] = {} + # rendered frames of captured states by (capture id, time stamp) + self._capture_frames: dict[tuple[int, float], dict[str, Frame]] = {} + if not render_on_demand: + by_rate: dict[int, list[str]] = {} + for name, cfg in cameras.items(): + by_rate.setdefault(cfg.frame_rate, []).append(name) + for frame_rate, names in by_rate.items(): + capture_id = self._sim.register_state_capture(frame_rate, max_buffer_frames, int(STATE_SPEC)) + self._captures[capture_id] = names - def get_timestamp_frames(self, ts: datetime) -> FrameSet | None: - """Should return the frame from the camera with the given name and closest to the given timestamp.""" - return self._cpp_to_python_frames(super().get_timestamp_frameset(ts.timestamp())) + def _create_renderer(self) -> _ClassicRenderer | _FilamentRenderer: + return _ClassicRenderer(self._sim.model, self.physical_units) - def _cpp_to_python_frames(self, cpp_frameset: _FrameSet | None) -> FrameSet | None: - if cpp_frameset is None: - return None + def _load_state(self, state: np.ndarray): + """Loads a state into the render data and computes what rendering needs from it.""" + model, data = self._sim.model, self._render_data + mujoco.mj_setState(model, data, state, STATE_SPEC) + mujoco.mj_kinematics(model, data) + mujoco.mj_camlight(model, data) + if model.ntendon: + mujoco.mj_tendon(model, data) + if model.nflex: + mujoco.mj_flex(model, data) + self._renderer.update(data) + + def _render(self, names: list[str]) -> dict[str, Frame]: + """Renders the given cameras from the render data.""" + model, data = self._sim.model, self._render_data + timestamp = data.time frames: dict[str, Frame] = {} - c_frames_iter = cpp_frameset.color_frames.items() - d_frames_iter = cpp_frameset.depth_frames.items() - for (color_name, color_frame), (depth_name, depth_frame) in zip(c_frames_iter, d_frames_iter, strict=True): - assert color_name == depth_name - color_np_frame = np.copy(color_frame).reshape( - self.cameras[color_name].resolution_height, self.cameras[color_name].resolution_width, 3 - )[ - # convert from column-major (c++ eigen) to row-major (python numpy) - ::-1 - ] - depth_np_frame = np.copy(depth_frame).reshape( - self.cameras[depth_name].resolution_height, self.cameras[depth_name].resolution_width, 1 - )[ - # convert from column-major (c++ eigen) to row-major (python numpy) - ::-1 - ] - if self.physical_units: - # Convert from [0 1] to depth in meters, see links below: - # http://stackoverflow.com/a/6657284/1461210 - # https://www.khronos.org/opengl/wiki/Depth_Buffer_Precision - # https://github.com/htung0101/table_dome/blob/master/table_dome_calib/utils.py#L160 - extent = self._sim.model.stat.extent - near = self._sim.model.vis.map.znear * extent - far = self._sim.model.vis.map.zfar * extent - depth_np_frame = near / (1 - depth_np_frame * (1 - near / far)) - - cameraframe = CameraFrame( - color=DataFrame( - data=color_np_frame, - timestamp=cpp_frameset.timestamp, - intrinsics=self._intrinsics(color_name), - extrinsics=self._extrinsics(color_name), - ), - depth=DataFrame( - data=(depth_np_frame * BaseCameraSet.DEPTH_SCALE).astype(np.uint16), - timestamp=cpp_frameset.timestamp, - intrinsics=self._intrinsics(depth_name), - extrinsics=self._extrinsics(depth_name), + for name in names: + cfg = self.cameras[name] + color, depth = self._renderer.render( + data, self._mj_cameras[name], cfg.resolution_width, cfg.resolution_height, self.render_depth + ) + intrinsics = _intrinsics(model, cfg) + extrinsics = _extrinsics(model, data, cfg) + depth_frame = None + if depth is not None: + depth_frame = DataFrame( + data=(depth[..., np.newaxis] * BaseCameraSet.DEPTH_SCALE).astype(np.uint16), + timestamp=timestamp, + intrinsics=intrinsics, + extrinsics=extrinsics, + ) + frames[name] = Frame( + camera=CameraFrame( + color=DataFrame(data=color, timestamp=timestamp, intrinsics=intrinsics, extrinsics=extrinsics), + depth=depth_frame, ), + avg_timestamp=timestamp, ) - frame = Frame(camera=cameraframe, avg_timestamp=cpp_frameset.timestamp) - frames[color_name] = frame - return FrameSet(frames=frames, avg_timestamp=cpp_frameset.timestamp) - - def _intrinsics(self, camera_name) -> np.ndarray[tuple[Literal[3], Literal[4]], np.dtype[np.float64]]: - cam_id = mujoco.mj_name2id(self._sim.model, mujoco.mjtObj.mjOBJ_CAMERA, self.cameras[camera_name].identifier) - fovy = self._sim.model.cam_fovy[cam_id] - fx = fy = 0.5 * self.cameras[camera_name].resolution_height / np.tan(fovy * np.pi / 360) - return np.array( - [ - [fx, 0, (self.cameras[camera_name].resolution_width - 1) / 2, 0], - [0, fy, (self.cameras[camera_name].resolution_height - 1) / 2, 0], - [0, 0, 1, 0], - ] - ) - - def _extrinsics(self, camera_name) -> np.ndarray[tuple[Literal[4], Literal[4]], np.dtype[np.float64]]: - cam_id = mujoco.mj_name2id(self._sim.model, mujoco.mjtObj.mjOBJ_CAMERA, self.cameras[camera_name].identifier) - xpos = self._sim.data.cam_xpos[cam_id] - xmat = self._sim.data.cam_xmat[cam_id].reshape(3, 3) - - cam = common.Pose(rotation=xmat, translation=xpos) - # put z axis infront - rotation_p = common.Pose(rpy_vector=np.array([np.pi, 0, 0]), translation=np.array([0, 0, 0])) # type: ignore - cam = cam * rotation_p - - return cam.inverse().pose_matrix() + return frames + + def _captured_frames(self, max_timestamp: float) -> FrameSet | None: + frames: dict[str, Frame] = {} + for capture_id, names in self._captures.items(): + captured = self._sim.get_captured_state(capture_id, max_timestamp) + if captured is None: + return None + key = (capture_id, captured.timestamp) + if key not in self._capture_frames: + self._load_state(captured.state) + self._capture_frames[key] = self._render(names) + # keep as many rendered frames as captured states + while len(self._capture_frames) > self._max_buffer_frames * len(self._captures): + del self._capture_frames[next(iter(self._capture_frames))] + frames.update(self._capture_frames[key]) + timestamps = [frame.avg_timestamp for frame in frames.values() if frame.avg_timestamp is not None] + return FrameSet(frames=frames, avg_timestamp=float(np.mean(timestamps)) if timestamps else None) + + def get_latest_frames(self) -> FrameSet | None: + """Frames of the current simulation state, or of the last exposures (``render_on_demand=False``).""" + if not self.render_on_demand: + return self._captured_frames(math.inf) + mujoco.mj_getState(self._sim.model, self._sim.data, self._state, STATE_SPEC) + if self._buffer_states and np.array_equal(self._buffer_states[-1], self._state): + return self._buffer[-1] + self._load_state(self._state) + frames = self._render(list(self.cameras)) + frameset = FrameSet(frames=frames, avg_timestamp=self._render_data.time) + self._buffer.append(frameset) + self._buffer_states.append(self._state.copy()) + return frameset + + def get_timestamp_frames(self, ts: datetime) -> FrameSet | None: + """Most recent frames with a simulation time <= ts.""" + if not self.render_on_demand: + return self._captured_frames(ts.timestamp()) + for frameset in reversed(self._buffer): + if frameset.avg_timestamp is not None and frameset.avg_timestamp <= ts.timestamp(): + return frameset + return None + + def buffer_size(self) -> int: + if not self.render_on_demand: + return min(self._sim.captured_state_count(capture_id) for capture_id in self._captures) + return len(self._buffer) + + def clear_buffer(self): + self._buffer.clear() + self._buffer_states.clear() + self._capture_frames.clear() + for capture_id in self._captures: + self._sim.clear_captured_states(capture_id) def calibrate(self) -> bool: return True @@ -124,8 +341,8 @@ def config(self, camera_name: str) -> SimCameraConfig: return self.cameras[camera_name] def close(self): - # TODO: this could deregister camera callbacks in simulation - pass + # the state captures keep running in the simulation, they are cheap (no rendering) + self._renderer.close() @property def camera_names(self) -> list[str]: @@ -135,3 +352,30 @@ def camera_names(self) -> list[str]: @property def name_to_identifier(self) -> dict[str, str]: return {name: cfg.identifier for name, cfg in self.cameras.items()} + + +class FilamentSimCameraSet(SimCameraSet): + """Set of simulation cameras rendered with MuJoCo's Filament renderer (MuJoCo >= 4.0). + + Same as :class:`SimCameraSet`, except that depth images are always metric (scaled by + ``BaseCameraSet.DEPTH_SCALE``), regardless of ``physical_units``. The depth pass is a second + Filament render per camera, set ``render_depth=False`` (done automatically by + ``CameraSetWrapper(include_depth=False)``) to skip it. + """ + + def __init__( + self, + simulation: sim.Sim, + cameras: dict[str, SimCameraConfig], + physical_units: bool = True, + render_on_demand: bool = True, + max_buffer_frames: int = 100, + render_depth: bool = True, + ): + filament.require("FilamentSimCameraSet") + if not physical_units: + logger.warning("FilamentSimCameraSet always returns metric depth; physical_units=False is ignored.") + super().__init__(simulation, cameras, True, render_on_demand, max_buffer_frames, render_depth) + + def _create_renderer(self) -> _ClassicRenderer | _FilamentRenderer: + return _FilamentRenderer(self._sim.model) diff --git a/python/rcs/envs/base.py b/python/rcs/envs/base.py index 0d1b62615..f82a812b7 100644 --- a/python/rcs/envs/base.py +++ b/python/rcs/envs/base.py @@ -961,6 +961,9 @@ def __init__(self, env, camera_set: BaseCameraSet, include_depth: bool = False): super().__init__(env) self.camera_set = camera_set self.include_depth = include_depth + # camera sets that render depth separately (e.g. FilamentSimCameraSet) can skip it if not requested + if hasattr(camera_set, "render_depth"): + camera_set.render_depth = include_depth self.observation_space: gym.spaces.Dict # rgb is always included diff --git a/python/rcs/envs/configs.py b/python/rcs/envs/configs.py index d9e79f752..7a49b78ea 100644 --- a/python/rcs/envs/configs.py +++ b/python/rcs/envs/configs.py @@ -5,13 +5,7 @@ import gymnasium as gym import numpy as np from rcs._core.common import GripperType, RobotType -from rcs._core.sim import ( - CameraType, - SimCameraConfig, - SimConfig, - SimGripperConfig, - SimRobotConfig, -) +from rcs._core.sim import SimCameraConfig, SimConfig, SimGripperConfig, SimRobotConfig from rcs.envs.base import ControlMode, RelativeTo from rcs.envs.scenes import ( CameraAdderConfig, @@ -105,14 +99,12 @@ def config(self) -> SimEnvCreatorConfig: camera_cfgs: dict[str, SimCameraConfig] | None = { "bird_eye": SimCameraConfig( identifier="bird_eye", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "wrist": SimCameraConfig( identifier="wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -251,28 +243,24 @@ def config(self) -> SimEnvCreatorConfig: cfg.camera_cfgs = { "over_shoulder_left": SimCameraConfig( identifier="over_shoulder_left", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "over_shoulder_right": SimCameraConfig( identifier="over_shoulder_right", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "front": SimCameraConfig( identifier="front", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "wrist": SimCameraConfig( identifier="wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -357,21 +345,18 @@ def config(self) -> SimEnvCreatorConfig: camera_cfgs: dict[str, SimCameraConfig] | None = { "head": SimCameraConfig( identifier="head", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "left_wrist": SimCameraConfig( identifier="left_wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "right_wrist": SimCameraConfig( identifier="right_wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -673,7 +658,6 @@ def config(self) -> SimEnvCreatorConfig: cfg.camera_cfgs = { "wrist": SimCameraConfig( identifier="wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -712,7 +696,6 @@ def config(self) -> SimEnvCreatorConfig: camera_cfgs: dict[str, SimCameraConfig] | None = { name: SimCameraConfig( identifier=name, - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -809,7 +792,6 @@ def config(self) -> SimEnvCreatorConfig: camera_cfgs = { f"{name}_wrist": SimCameraConfig( identifier=f"{name}_wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, diff --git a/python/rcs/envs/utils.py b/python/rcs/envs/utils.py index 7a33c0492..4319b059c 100644 --- a/python/rcs/envs/utils.py +++ b/python/rcs/envs/utils.py @@ -5,7 +5,6 @@ from rcs._core.sim import SimCameraConfig from rcs.camera.digit_cam import DigitCam -import rcs from rcs import sim logger = logging.getLogger(__name__) @@ -37,14 +36,6 @@ def default_mujoco_cameraset_cfg() -> dict[str, SimCameraConfig]: return { "wrist": SimCameraConfig( identifier="wrist_0", - type=rcs._core.sim.CameraType.fixed, - frame_rate=10, - resolution_width=256, - resolution_height=256, - ), - "default_free": SimCameraConfig( - identifier="", - type=rcs._core.sim.CameraType.default_free, frame_rate=10, resolution_width=256, resolution_height=256, diff --git a/python/rcs/sim/__init__.py b/python/rcs/sim/__init__.py index dab8c835d..58a7b550a 100644 --- a/python/rcs/sim/__init__.py +++ b/python/rcs/sim/__init__.py @@ -1,4 +1,5 @@ from rcs._core.sim import ( + RendererBackend, SimCameraConfig, SimConfig, SimGripper, @@ -27,4 +28,5 @@ "gui_loop", "SimCameraConfig", "SimConfig", + "RendererBackend", ] diff --git a/python/rcs/sim/filament.py b/python/rcs/sim/filament.py new file mode 100644 index 000000000..3346d811c --- /dev/null +++ b/python/rcs/sim/filament.py @@ -0,0 +1,302 @@ +""" +Filament rendering backend (MuJoCo >= 4.0). + +MuJoCo ships its Filament-based renderer only inside the ``mujoco-studio`` Python package +(``mujoco.mjrf`` and ``mujoco.studio``); ``libmujoco`` does not export the ``mjrf_*`` C API. +Everything Filament related therefore lives on the Python side of RCS: + +- :class:`FilamentRenderer` renders RGB images and metric depth of fixed/free MuJoCo cameras + offscreen. Depth comes from Filament's depth draw mode read back into a float target. +- :func:`gui_loop` runs MuJoCo Studio (the Filament viewer) in the RCS GUI subprocess. + Studio must own the main thread of its process and, unlike ``mujoco.viewer``, must *not* + run under ``mjpython`` on macOS. + +Enable it via ``SimConfig(renderer=RendererBackend.FILAMENT)``. + +Environment variables: + +- ``RCS_FILAMENT_GRAPHICS_API``: ``opengl`` or ``vulkan`` (default: opengl, vulkan on Linux without an + X display: Filament's OpenGL backend needs X and hangs without it) +- ``RCS_FILAMENT_SOFTWARE_RENDERING=1``: force software rendering for offscreen cameras +- ``RCS_FILAMENT_GFX``: Studio graphics mode for the GUI, e.g. ``opengl``, ``vulkan``, ``web`` + (``web`` serves the viewer over http instead of opening a native window) +""" + +import atexit +import ctypes +import os +import sys +import threading +from logging import getLogger +from tempfile import NamedTemporaryFile + +import cv2 +import mujoco +import numpy as np +from rcs._core.sim import GuiClient as _GuiClient +from rcs.utils import SimpleFrameRate + +logger = getLogger(__name__) + +# Target frames per second of the GUI loop +FPS = 60 + + +def _import_error() -> str | None: + try: + import mujoco.studio # noqa: F401 + from mujoco import mjrf # noqa: F401 + except ImportError as exc: + return repr(exc) + return None + + +def is_available() -> bool: + return _import_error() is None + + +def require(feature: str = "Filament rendering"): + error = _import_error() + if error is None: + return + msg = ( + f"{feature} requires the Filament renderer, which is shipped with the MuJoCo Python package " + f"(mujoco-studio) since version 4.0 (installed: {mujoco.__version__}). Import failed with: {error}" + ) + raise RuntimeError(msg) + + +def _graphics_api(mjrf): + """Graphics API for offscreen Filament contexts, see ``RCS_FILAMENT_GRAPHICS_API``.""" + api = os.environ.get("RCS_FILAMENT_GRAPHICS_API", "").lower() + if api not in ("", "opengl", "vulkan"): + logger.warning("Unknown RCS_FILAMENT_GRAPHICS_API=%r, using the default", api) + api = "" + # Filament's OpenGL backend on Linux uses GLX: without an X display it prints "Failed to open X + # display. (exiting)" and then hangs instead of exiting, so headless Linux has to use Vulkan + headless_linux = sys.platform.startswith("linux") and not os.environ.get("DISPLAY") + if api == "opengl" and headless_linux: + msg = ( + "RCS_FILAMENT_GRAPHICS_API=opengl requires an X display on Linux, but DISPLAY is not set. " + "Use RCS_FILAMENT_GRAPHICS_API=vulkan (the default without a display) or run under an X server." + ) + raise RuntimeError(msg) + if api == "vulkan" or (api == "" and headless_linux): + return mjrf.GraphicsApi.GRAPHICS_API_VULKAN + # OpenGL like MuJoCo's own samples; the platform default resolves to Vulkan on some systems + # (e.g. macOS) where it is not usable + return mjrf.GraphicsApi.GRAPHICS_API_OPENGL + + +# Filament contexts that are not in use, per (thread, graphics API, software rendering). +# Contexts are reused instead of destroyed: destroying a Vulkan context on NVIDIA drivers calls +# eglTerminate() on the process' default EGL display (from libGLX_nvidia on Filament's engine thread), +# which kills the EGL context of the classic renderer (eglMakeCurrent then fails with +# EGL_NOT_INITIALIZED). They are keyed by thread as Filament requires all calls of a context to come +# from the thread that created it. +_free_contexts: dict[tuple[int, object, bool], list] = {} +_free_contexts_lock = threading.Lock() + + +def _acquire_context(mjrf): + software = os.environ.get("RCS_FILAMENT_SOFTWARE_RENDERING", "") == "1" + key = (threading.get_ident(), _graphics_api(mjrf), software) + with _free_contexts_lock: + free = _free_contexts.setdefault(key, []) + ctx = free.pop() if free else None + if ctx is None: + cfg = mjrf.ContextConfig() + cfg.graphics_api = key[1] + cfg.software_rendering = software + ctx = mjrf.Context(cfg) + ctx.set_clear_color(np.zeros(3, dtype=np.float32)) + return key, ctx + + +def _release_context(key, ctx): + with _free_contexts_lock: + _free_contexts.setdefault(key, []).append(ctx) + + +@atexit.register +def _leak_free_contexts(): + # Pooled contexts would otherwise be destroyed during interpreter shutdown on the main thread, + # which aborts the process for contexts created by other threads ("Engine::shutdown() called from + # the wrong thread!"). Keep them alive instead; the OS frees them when the process exits. + with _free_contexts_lock: + for contexts in _free_contexts.values(): + for ctx in contexts: + ctypes.pythonapi.Py_IncRef(ctypes.py_object(ctx)) + + +class FilamentRenderer: + """Offscreen RGB renderer for a MuJoCo model based on Filament. + + All methods must be called from the thread that created the renderer: Filament asserts + thread affinity when its engine is destroyed. The Filament context is borrowed from a per-thread + pool and returned on :meth:`close` (a context can only serve one model at a time). + """ + + def __init__(self, model: mujoco.MjModel): + require("FilamentRenderer") + from mujoco import mjrf + + self._mjrf = mjrf + self.model = model + self._ctx_key, self._ctx = _acquire_context(mjrf) + self._objects = mjrf.ModelResources(self._ctx, model) + self._scene = self._ctx.create_scene(mjrf.SceneParams()) + self._scene.configure_from_model(model) + self._lights = mjrf.ModelLights(self._scene, self._objects) + self._renderables = mjrf.ModelRenderables(self._scene, self._objects) + # one render target per (resolution, kind), created lazily + self._targets: dict[tuple[int, int, str], tuple[object, object, np.ndarray]] = {} + extent = model.stat.extent + self._near = model.vis.map.znear * extent + self._far = model.vis.map.zfar * extent + self._closed = False + + def set_options(self, opt: mujoco.MjvOption): + self._renderables.set_options(opt) + + def update(self, data: mujoco.MjData): + """Syncs lights and renderables with the current simulation state.""" + self._lights.update(data) + self._renderables.update(data) + + def _target(self, width: int, height: int, kind: str = "rgb"): + key = (width, height, kind) + if key not in self._targets: + mjrf = self._mjrf + if kind == "rgb": + # RGBA8 instead of RGB8: GPUs generally do not support 3 channel 8 bit render targets + # (e.g. Vulkan's R8G8B8_UNORM has no image features on NVIDIA), so Filament emulates + # RGB8 with a slow readback path (about 2x slower on Vulkan); alpha is dropped in render() + fmt, buffer = mjrf.PixelFormat.PIXEL_FORMAT_RGBA8, np.empty((height, width, 4), dtype=np.uint8) + else: + fmt, buffer = mjrf.PixelFormat.PIXEL_FORMAT_R32F, np.empty((height, width), dtype=np.float32) + target = self._ctx.create_render_target(mjrf.RenderTargetConfig(color_format=fmt)) + target.resize(width, height) + read = mjrf.ReadRequest(target=target) + read.set_buffer(buffer) + self._targets[key] = (target, read, buffer) + return self._targets[key] + + def render(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int) -> np.ndarray: + """Renders the given camera and returns an (H, W, 3) uint8 RGB image (top row first). + + Call :meth:`update` first whenever ``data`` changed. + """ + # cv2 drops the alpha channel ~100x faster than a numpy slice copy + return cv2.cvtColor(self._render(data, camera, width, height, "rgb"), cv2.COLOR_RGBA2RGB) + + def render_depth(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int) -> np.ndarray: + """Renders the given camera and returns metric depth in meters as (H, W) float32 (top row first). + + Call :meth:`update` first whenever ``data`` changed. + """ + depth = self._render(data, camera, width, height, "depth") + # Filament's depth draw mode writes reversed-z (1 at znear, 0 at zfar) without post processing + # (MuJoCo >= 4.0); convert like the classic renderer's [0, 1] depth buffer + return self._near / (1 - (1 - depth) * (1 - self._near / self._far)) + + def _render(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int, kind: str): + mjrf = self._mjrf + target, read, buffer = self._target(width, height, kind) + glcam = mujoco.mjv_camera2GLCamera(self.model, data, camera) + request = mjrf.RenderRequest( + camera=mjrf.Camera( + pos=glcam.pos, + forward=glcam.forward, + up=glcam.up, + frustum_bottom=glcam.frustum_bottom, + frustum_top=glcam.frustum_top, + frustum_near=glcam.frustum_near, + frustum_far=glcam.frustum_far, + ), + draw_mode=mjrf.DrawMode.DRAW_MODE_DEFAULT if kind == "rgb" else mjrf.DrawMode.DRAW_MODE_DEPTH, + ) + request.scene = self._scene + request.target = target + request.viewport.left = 0 + request.viewport.bottom = 0 + request.viewport.width = width + request.viewport.height = height + # the bindings still support only a single read request per render call (MuJoCo 4.0.1) + frame = self._ctx.render([request], [read]) + self._ctx.wait_for_frame(frame) + return buffer + + def close(self): + if self._closed: + return + self._closed = True + # destroy in reverse creation order; the context must outlive everything it created + self._targets.clear() + del self._renderables, self._lights, self._scene, self._objects + # the context is not destroyed but reused, see _free_contexts + _release_context(self._ctx_key, self._ctx) + del self._ctx + + +def gui_executable() -> str: + """Python executable for the Filament GUI subprocess (never mjpython, see module docstring).""" + return sys.executable + + +def gui_loop(gui_uuid: str, close_event): + """Runs MuJoCo Studio for the simulation identified by ``gui_uuid``. + + Mirrors :func:`rcs.sim.sim.gui_loop`: the GUI process holds its own copy of the model and data + and synchronizes the state through the GuiClient. The viewer runs on the main thread of this + process, stepping/syncing happens on a background thread. + """ + require("The Filament GUI") + from mujoco.studio import app as studio_app + from mujoco.studio import ( + launch_native, + launch_thread, + viewer_handle, + viewer_protocol, + ) + + gui_client = _GuiClient(gui_uuid) + model_bytes = gui_client.get_model_bytes() + with NamedTemporaryFile(mode="wb") as f: + f.write(model_bytes) + f.flush() + model = mujoco.MjModel.from_binary_path(f.name) + data = mujoco.MjData(model) + gui_client.set_model_and_data(model._address, data._address) + mujoco.mj_step(model, data) + + viewer_endpoint, sim_endpoint = launch_thread.make_thread_endpoints() + handle = viewer_handle.ViewerHandle(sim_endpoint) + viewer_closed = threading.Event() + + def sim_loop(): + frame_rate = SimpleFrameRate(FPS, "gui_loop") + try: + while not close_event.is_set() and not viewer_closed.is_set() and handle.is_running(): + mujoco.mj_step(model, data) + # the viewer may hand back a new model (e.g. drag and drop); we keep ours as the + # GuiClient owns the pointers to model and data + handle.sync(model, data) + gui_client.sync() + frame_rate() + finally: + handle.close() + + sim_thread = threading.Thread(target=sim_loop, daemon=True) + sim_thread.start() + try: + config = viewer_protocol.ViewerConfig(title="RCS", gfx=os.environ.get("RCS_FILAMENT_GFX", "")) + # App provides the interactive Studio GUI (camera selection, visualization options, + # dragging bodies, ...); without it only the bare scene is rendered. The camera selection + # lives in the toolbar, which Studio hides by default ([ and ] cycle cameras regardless). + # Studio's SIM_PLUGINS (step control, history) are not used: sim_loop steps and paces itself. + app = studio_app.App(studio_app.Config(show_toolbar=True)) + launch_native.run_native_viewer(config, viewer_endpoint, plugins=[app]) + finally: + viewer_closed.set() + sim_thread.join(timeout=5) diff --git a/python/rcs/sim/render_context_bootstrap.py b/python/rcs/sim/render_context_bootstrap.py index e27f2411b..b706b40e1 100644 --- a/python/rcs/sim/render_context_bootstrap.py +++ b/python/rcs/sim/render_context_bootstrap.py @@ -1,23 +1,16 @@ """ -Bootstrap an offscreen GL render context and register it with the C++ backend. +Bootstrap the offscreen GL render context used by the classic renderer (python/rcs/camera/sim.py). Two backends are supported, selected by platform: -- Linux: load libEGL via ctypes, create a persistent MuJoCo EGL ``GLContext``, - and hand its ``eglMakeCurrent`` / display / context to C++ (the ``egl`` - backend). -- macOS: there is no libEGL. Create a persistent MuJoCo ``GLContext`` and make - it current on this thread; C++ then treats ``ensure_current()`` as a no-op - (the ``current_context`` backend). +- Linux: create a persistent MuJoCo EGL ``GLContext`` (headless). +- macOS: there is no libEGL. Create a persistent MuJoCo ``GLContext``. -The initialized state is held in a module-level ``_state`` (references keep the -library and context from being garbage-collected). Call ``bootstrap()`` to -complete initialization. +Rendering code calls ``make_current()`` before using the context. The initialized state is held in a +module-level ``_state`` (references keep the context from being garbage-collected). """ -import ctypes import ctypes.util -import os import sys from dataclasses import dataclass from typing import Any @@ -28,12 +21,8 @@ class _RenderBackend: backend: str = "none" # "none" | "egl" | "current_context" available: bool = False error: str | None = None - # references kept so the GL context / EGL library are not garbage-collected + # reference kept so the GL context is not garbage-collected gl_context: Any = None - egl_lib: Any = None - addr_make_current: int | None = None - egl_display: int | None = None - egl_context: int | None = None def _init_current_context() -> _RenderBackend: @@ -48,26 +37,14 @@ def _init_current_context() -> _RenderBackend: def _init_egl() -> _RenderBackend: - """Linux/other: load libEGL and create a persistent MuJoCo EGL GLContext.""" - name = ctypes.util.find_library("EGL") - if name is None: + """Linux/other: create a persistent MuJoCo EGL GLContext.""" + if ctypes.util.find_library("EGL") is None: return _RenderBackend(error="Could not find libEGL via ctypes.util.find_library('EGL').") try: - import mujoco.egl from mujoco.egl import GLContext - egl_lib = ctypes.CDLL(name, mode=os.RTLD_LOCAL | os.RTLD_NOW) - addr_make_current = ctypes.cast(egl_lib.eglMakeCurrent, ctypes.c_void_p).value ctx = GLContext(max_width=3840, max_height=2160) - return _RenderBackend( - backend="egl", - available=True, - gl_context=ctx, - egl_lib=egl_lib, - addr_make_current=addr_make_current, - egl_display=int(mujoco.egl.EGL_DISPLAY.address), - egl_context=int(ctx._context.address), - ) + return _RenderBackend(backend="egl", available=True, gl_context=ctx) except Exception as exc: return _RenderBackend(error=f"Failed to initialize MuJoCo EGL context: {exc!r}") @@ -95,17 +72,8 @@ def require(feature: str = "offscreen rendering"): raise RuntimeError(message) -def bootstrap(): - if not _state.available: - return - import rcs._core as _cxx - - if _state.backend == "current_context": - assert _state.gl_context is not None - _state.gl_context.make_current() - _cxx.common._bootstrap_gl_context() - elif _state.backend == "egl": - assert _state.addr_make_current is not None - assert _state.egl_display is not None - assert _state.egl_context is not None - _cxx.common._bootstrap_egl_context(_state.addr_make_current, _state.egl_display, _state.egl_context) +def make_current(): + """Makes the bootstrapped GL context current on the calling thread (for rendering from Python).""" + require() + assert _state.gl_context is not None + _state.gl_context.make_current() diff --git a/python/rcs/sim/sim.py b/python/rcs/sim/sim.py index 86df66ac5..4612b5b34 100644 --- a/python/rcs/sim/sim.py +++ b/python/rcs/sim/sim.py @@ -19,11 +19,10 @@ from rcs._core.sim import DynamicJointSchema, DynamicJointState from rcs._core.sim import GuiClient as _GuiClient from rcs._core.sim import Sim as _Sim -from rcs.sim import SimConfig, render_context_bootstrap +from rcs.sim import RendererBackend, SimConfig, filament from rcs.sim.composer import ModelComposer from rcs.utils import SimpleFrameRate -render_context_bootstrap.bootstrap() logger = getLogger(__name__) @@ -33,9 +32,19 @@ ROOT_RELATIVE_FREE_STATE_ENCODING = "root_relative_free" -def configure_viewer_mp_context(ctx: "mp.context.SpawnContext") -> None: - """On macOS the passive MuJoCo viewer must run under ``mjpython``.""" +def configure_viewer_mp_context( + ctx: "mp.context.SpawnContext", renderer: RendererBackend = RendererBackend.CLASSIC +) -> None: + """Selects the interpreter of the GUI subprocess. + + On macOS the passive MuJoCo viewer must run under ``mjpython``, whereas MuJoCo Studio (Filament) must + run under a regular ``python`` as it owns the main thread itself. + """ + if renderer == RendererBackend.FILAMENT: + ctx.set_executable(filament.gui_executable()) + return if sys.platform != "darwin": + ctx.set_executable(sys.executable) return mjpython = shutil.which("mjpython") if mjpython is None: @@ -82,7 +91,6 @@ def __init__(self, mjmdl: str | PathLike | ModelComposer, cfg: SimConfig | None self.data = mj.MjData(self.model) super().__init__(self.model._address, self.data._address) self._mp_context = mp.get_context("spawn") - configure_viewer_mp_context(self._mp_context) self._gui_uuid: Optional[str] = None self._gui_client: Optional[_GuiClient] = None self._gui_process: Optional[mp.context.SpawnProcess] = None @@ -253,13 +261,22 @@ def close_gui(self): self._gui_atexit_registered = False def open_gui(self): + """Opens the viewer in a subprocess. + + Uses the passive ``mujoco.viewer`` or, with ``SimConfig(renderer=RendererBackend.FILAMENT)``, + MuJoCo Studio (Filament). + """ + renderer = self.get_config().renderer + if renderer == RendererBackend.FILAMENT: + filament.require("The Filament GUI") if self._gui_uuid is None: self._gui_uuid = "rcs_" + str(uuid.uuid4()) self._start_gui_server(self._gui_uuid) if self._gui_process is None or not self._gui_process.is_alive(): + configure_viewer_mp_context(self._mp_context, renderer) self._stop_event = self._mp_context.Event() self._gui_process = self._mp_context.Process( - target=gui_loop, + target=filament.gui_loop if renderer == RendererBackend.FILAMENT else gui_loop, args=(self._gui_uuid, self._stop_event), daemon=True, ) diff --git a/python/tests/test_filament.py b/python/tests/test_filament.py new file mode 100644 index 000000000..52a028195 --- /dev/null +++ b/python/tests/test_filament.py @@ -0,0 +1,141 @@ +import sys + +import gymnasium as gym +import mujoco +import numpy as np +import pytest +from rcs.camera.sim import FilamentSimCameraSet, SimCameraSet +from rcs.envs.base import CameraSetWrapper +from rcs.envs.configs import EmptyWorldFR3 +from rcs.sim import RendererBackend, SimConfig, filament + +from rcs import sim + +# Filament ships with mujoco >= 4.0 (mujoco-studio). Only skip on older versions: if the import breaks on +# a supported version (e.g. a moved module), the tests must fail instead of being skipped silently. +pytestmark = pytest.mark.skipif( + int(mujoco.__version__.split(".")[0]) < 4, reason="Filament renderer requires mujoco >= 4.0" +) + + +def test_filament_is_available(): + assert filament.is_available(), filament._import_error() + + +@pytest.fixture() +def fr3_sim(): + scene = EmptyWorldFR3() + cfg = scene.prefixed_cfg(scene.config()) + simulation = sim.Sim(scene.create_model(cfg), SimConfig(renderer=RendererBackend.FILAMENT)) + return simulation, cfg + + +def test_sim_camera_set_dispatches_to_filament(fr3_sim): + simulation, cfg = fr3_sim + camera_set = SimCameraSet(simulation, cfg.camera_cfgs, physical_units=True) + assert isinstance(camera_set, FilamentSimCameraSet) + assert camera_set.camera_names == list(cfg.camera_cfgs.keys()) + camera_set.close() + + +def test_filament_camera_set_renders_rgb_and_metric_depth(fr3_sim): + simulation, cfg = fr3_sim + camera_set = FilamentSimCameraSet(simulation, cfg.camera_cfgs) + try: + simulation.step(1) + frameset = camera_set.get_latest_frames() + assert frameset is not None + assert frameset.frames.keys() == cfg.camera_cfgs.keys() + for name, frame in frameset.frames.items(): + cam_cfg = cfg.camera_cfgs[name] + assert frame.camera.depth is not None + color = frame.camera.color.data + depth = frame.camera.depth.data + assert color.shape == (cam_cfg.resolution_height, cam_cfg.resolution_width, 3) + assert color.dtype == np.uint8 + # the scene is lit and textured, so the image must not be uniform + assert color.std() > 1 + assert depth.shape == (cam_cfg.resolution_height, cam_cfg.resolution_width, 1) + assert depth.dtype == np.uint16 + # metric depth in millimeters: the cameras look at the robot/floor within a few meters + assert 10 < np.median(depth) < 10_000 + assert frame.camera.color.intrinsics is not None + assert frame.camera.color.extrinsics is not None + assert frame.camera.color.intrinsics.shape == (3, 4) + assert frame.camera.color.extrinsics.shape == (4, 4) + + # the same simulation time returns the buffered frames, a new step renders again + assert camera_set.get_latest_frames() is frameset + simulation.step(1) + assert camera_set.get_latest_frames() is not frameset + assert camera_set.buffer_size() == 2 + finally: + camera_set.close() + + +def test_filament_camera_set_skips_depth_when_not_requested(fr3_sim): + simulation, cfg = fr3_sim + camera_set = FilamentSimCameraSet(simulation, cfg.camera_cfgs, render_depth=False) + try: + simulation.step(1) + frameset = camera_set.get_latest_frames() + assert frameset is not None + assert all(frame.camera.depth is None for frame in frameset.frames.values()) + assert all(frame.camera.color.data.dtype == np.uint8 for frame in frameset.frames.values()) + finally: + camera_set.close() + + +class _EmptyObsEnv(gym.Env): + observation_space = gym.spaces.Dict({}) + action_space = gym.spaces.Dict({}) + + +def test_camera_set_wrapper_configures_depth_rendering(fr3_sim): + simulation, cfg = fr3_sim + camera_set = FilamentSimCameraSet(simulation, cfg.camera_cfgs) + try: + CameraSetWrapper(_EmptyObsEnv(), camera_set, include_depth=False) + assert camera_set.render_depth is False + CameraSetWrapper(_EmptyObsEnv(), camera_set, include_depth=True) + assert camera_set.render_depth is True + finally: + camera_set.close() + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="X display detection is Linux specific") +def test_graphics_api_without_x_display(monkeypatch): + from mujoco import mjrf + + monkeypatch.delenv("DISPLAY", raising=False) + monkeypatch.delenv("RCS_FILAMENT_GRAPHICS_API", raising=False) + # Filament's OpenGL backend hangs without X, so headless Linux defaults to Vulkan ... + assert filament._graphics_api(mjrf) == mjrf.GraphicsApi.GRAPHICS_API_VULKAN + # ... and an explicit OpenGL request fails instead of hanging + monkeypatch.setenv("RCS_FILAMENT_GRAPHICS_API", "opengl") + with pytest.raises(RuntimeError, match="X display"): + filament._graphics_api(mjrf) + + +def test_filament_contexts_are_reused(fr3_sim): + simulation, _ = fr3_sim + first = filament.FilamentRenderer(simulation.model) + ctx = first._ctx + first.close() + second = filament.FilamentRenderer(simulation.model) + try: + assert second._ctx is ctx + finally: + second.close() + + +def test_classic_rendering_after_filament_close(fr3_sim): + # destroying a Filament (Vulkan) context used to terminate the EGL display of the classic renderer + simulation, cfg = fr3_sim + FilamentSimCameraSet(simulation, cfg.camera_cfgs).close() + classic = sim.Sim(EmptyWorldFR3().create_model(cfg), SimConfig()) + camera_set = SimCameraSet(classic, cfg.camera_cfgs, physical_units=True) + classic.step(1) + frameset = camera_set.get_latest_frames() + assert frameset is not None + assert all(frame.camera.color.data.std() > 1 for frame in frameset.frames.values()) diff --git a/python/tests/test_hw_camera.py b/python/tests/test_hw_camera.py new file mode 100644 index 000000000..31c5a2914 --- /dev/null +++ b/python/tests/test_hw_camera.py @@ -0,0 +1,43 @@ +import time +from datetime import datetime + +import numpy as np +from rcs._core.common import BaseCameraConfig +from rcs.camera.hw import HardwareCameraSet +from rcs.camera.interface import CameraFrame, DataFrame, Frame + + +class _FakeCamera: + @property + def camera_names(self) -> list[str]: + return ["cam"] + + def open(self): + pass + + def close(self): + pass + + def config(self, camera_name: str) -> BaseCameraConfig: + return BaseCameraConfig(identifier=camera_name, frame_rate=100, resolution_width=4, resolution_height=3) + + def poll_frame(self, camera_name: str) -> Frame: + ts = time.time() + color = DataFrame(data=np.zeros((3, 4, 3), dtype=np.uint8), timestamp=ts) + return Frame(camera=CameraFrame(color=color), avg_timestamp=ts) + + def calibrate(self) -> bool: + return True + + +def test_timestamp_lookup_before_the_buffer_is_full(): + cameras = HardwareCameraSet([_FakeCamera()], warm_up_disposal_frames=0, max_buffer_frames=1000) + cameras.start(warm_up=False) + try: + cameras.wait_for_frames() + finally: + cameras.stop() + assert 0 < cameras.buffer_size() < cameras.max_buffer_frames + # only the filled slots are searched + assert cameras.get_timestamp_frames(datetime.fromtimestamp(0)) is None + assert cameras.get_timestamp_frames(datetime.now()) is cameras.get_latest_frames() diff --git a/python/tests/test_sim_camera.py b/python/tests/test_sim_camera.py new file mode 100644 index 000000000..eb72d22dc --- /dev/null +++ b/python/tests/test_sim_camera.py @@ -0,0 +1,158 @@ +import math + +import mujoco +import numpy as np +import pytest +from rcs.camera.sim import STATE_SPEC, SimCameraSet +from rcs.envs.configs import EmptyWorldDroid +from rcs.sim import SimConfig + +from rcs import sim + + +def _render(camera_cfgs) -> dict[str, np.ndarray]: + scene = EmptyWorldDroid() + cfg = scene.prefixed_cfg(scene.config()) + assert cfg.camera_cfgs is not None + simulation = sim.Sim(scene.create_model(cfg), SimConfig()) + simulation.step(10) + camera_set = SimCameraSet(simulation, {name: cfg.camera_cfgs[name] for name in camera_cfgs}, physical_units=True) + frames = [] + for _ in range(2): + frameset = camera_set.get_latest_frames() + assert frameset is not None + frames.append({name: frame.camera.color.data.astype(int) for name, frame in frameset.frames.items()}) + # rendering the same state twice gives the same images + for name in frames[0]: + assert np.abs(frames[0][name] - frames[1][name]).max() <= 1, name + return frames[1] + + +def test_camera_images_do_not_depend_on_other_cameras(): + # The cameras share one mjvScene and mjv_updateScene places infinite planes (the floor) relative to + # the scene's previous camera, which made images depend on which camera was rendered before. + scene = EmptyWorldDroid() + camera_cfgs = scene.prefixed_cfg(scene.config()).camera_cfgs + assert camera_cfgs is not None + names = list(camera_cfgs) + assert len(names) > 1 + together = _render(names) + for name in names: + alone = _render([name])[name] + assert np.abs(together[name] - alone).max() <= 1, name + + +def _droid_sim(): + scene = EmptyWorldDroid() + cfg = scene.prefixed_cfg(scene.config()) + assert cfg.camera_cfgs is not None + return sim.Sim(scene.create_model(cfg), SimConfig()), cfg.camera_cfgs + + +def test_state_capture_follows_fixed_schedule(): + simulation, _ = _droid_sim() + dt = simulation.model.opt.timestep + frame_rate = 30 + capture = simulation.register_state_capture(frame_rate, 1000, int(STATE_SPEC)) + # the current state is captured right away + assert simulation.captured_state_count(capture) == 1 + first = simulation.get_captured_state(capture) + assert first is not None + assert first.timestamp == 0 + assert len(first.state) == mujoco.mj_stateSize(simulation.model, STATE_SPEC) + + simulation.step(round(2.0 / dt)) + timestamps: list[float] = [] + for _ in range(simulation.captured_state_count(capture)): + captured = simulation.get_captured_state(capture, timestamps[-1] - dt / 2 if timestamps else math.inf) + assert captured is not None + timestamps.append(captured.timestamp) + timestamps.reverse() + # one capture per frame at the physics step closest to k / frame_rate, i.e. no drift over time + assert len(timestamps) == 2 * frame_rate + 1 + expected = np.arange(len(timestamps)) / frame_rate + assert np.abs(np.array(timestamps) - expected).max() <= dt / 2 + 1e-9 + + +def test_state_capture_restarts_on_reset(): + simulation, _ = _droid_sim() + capture = simulation.register_state_capture(30, 100, int(STATE_SPEC)) + simulation.step(100) + assert simulation.captured_state_count(capture) > 1 + simulation.reset() + assert simulation.captured_state_count(capture) == 1 + captured = simulation.get_captured_state(capture) + assert captured is not None + assert captured.timestamp == 0 + + +def test_state_capture_restarts_when_time_goes_backwards(): + simulation, _ = _droid_sim() + dt = simulation.model.opt.timestep + capture = simulation.register_state_capture(30, 100, int(STATE_SPEC)) + simulation.step(100) + assert simulation.captured_state_count(capture) > 1 + # set the time back without reset, e.g. when a recorded state is restored + simulation.data.time = 0 + simulation.step(1) + assert simulation.captured_state_count(capture) == 1 + captured = simulation.get_captured_state(capture) + assert captured is not None + assert captured.timestamp == pytest.approx(dt) + # and the fixed schedule continues from there + simulation.step(round(1 / 30 / dt)) + assert simulation.captured_state_count(capture) == 2 + + +def test_frames_show_last_exposure(): + simulation, camera_cfgs = _droid_sim() + dt = simulation.model.opt.timestep + name = next(iter(camera_cfgs)) + cfg = camera_cfgs[name] + period = 1 / cfg.frame_rate + exposed = SimCameraSet(simulation, {name: cfg}, physical_units=True, render_on_demand=False) + live = SimCameraSet(simulation, {name: cfg}, physical_units=True) + simulation.data.ctrl[:] = 0.5 + + # step to just after an exposure: the exposure is the live state at that time + simulation.step(round(3 * period / dt)) + live_at_exposure = live.get_latest_frames() + exposed_frames = exposed.get_latest_frames() + assert live_at_exposure is not None + assert exposed_frames is not None + assert exposed_frames.avg_timestamp == pytest.approx(live_at_exposure.avg_timestamp) + exposure = exposed_frames.frames[name].camera + live_frame = live_at_exposure.frames[name].camera + assert np.abs(exposure.color.data.astype(int) - live_frame.color.data.astype(int)).max() <= 1 + assert exposure.depth is not None + assert live_frame.depth is not None + assert np.array_equal(exposure.depth.data, live_frame.depth.data) + assert exposure.color.extrinsics is not None + assert np.allclose(exposure.color.extrinsics, live_frame.color.extrinsics) # type: ignore[arg-type] + + # until the next exposure, the frames do not change while the live state does + simulation.step(round(0.5 * period / dt)) + later = exposed.get_latest_frames() + assert later is not None + assert later.avg_timestamp == exposed_frames.avg_timestamp + assert later.frames[name] is exposed_frames.frames[name] + later_live = live.get_latest_frames() + assert later_live is not None + assert later_live.avg_timestamp is not None + assert later.avg_timestamp is not None + assert later_live.avg_timestamp > later.avg_timestamp + + # after the next exposure, new frames are rendered + simulation.step(round(0.6 * period / dt)) + newer = exposed.get_latest_frames() + assert newer is not None + assert newer.avg_timestamp == pytest.approx(4 * period, abs=dt) + exposed.close() + live.close() + + +def test_unknown_camera_raises(): + simulation, _ = _droid_sim() + cfg = sim.SimCameraConfig(identifier="missing", frame_rate=30, resolution_width=64, resolution_height=48) + with pytest.raises(ValueError, match="missing"): + SimCameraSet(simulation, {"missing": cfg}) diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 767c83a1b..0ebd39b9c 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -6,12 +6,13 @@ #include #include #include -#include #include #include +#include #include +#include "rcs/Camera.h" #include "rcs/Kinematics.h" #include "rcs/Pose.h" #include "rcs/Robot.h" @@ -256,9 +257,6 @@ PYBIND11_MODULE(_core, m) { // COMMON MODULE auto common = m.def_submodule("common", "common module"); - common.def("_bootstrap_egl_context", &rcs::common::bootstrap_egl_context, - py::arg("fn_addr"), py::arg("display"), py::arg("context")); - common.def("_bootstrap_gl_context", &rcs::common::bootstrap_gl_context); common.def("IdentityTranslation", &rcs::common::IdentityTranslation); common.def("IdentityRotMatrix", &rcs::common::IdentityRotMatrix); common.def("IdentityRotQuatVec", &rcs::common::IdentityRotQuatVec); @@ -748,16 +746,23 @@ PYBIND11_MODULE(_core, m) { .def_readonly("last_width", &rcs::sim::SimGripperState::last_width) .def_readonly("collision", &rcs::sim::SimGripperState::collision); + py::enum_(sim, "RendererBackend") + .value("CLASSIC", rcs::sim::RendererBackend::CLASSIC) + .value("FILAMENT", rcs::sim::RendererBackend::FILAMENT) + .export_values(); + rcs::sim::SimConfig default_sim_cfg = rcs::sim::SimConfig(); py::class_(sim, "SimConfig") .def(py::init([](bool async_control, bool realtime, double frequency, - int max_convergence_steps, long long memory) { + int max_convergence_steps, long long memory, + rcs::sim::RendererBackend renderer) { rcs::sim::SimConfig config; config.async_control = async_control; config.realtime = realtime; config.frequency = frequency; config.max_convergence_steps = max_convergence_steps; config.memory = memory; + config.renderer = renderer; return config; }), py::arg("async_control") = default_sim_cfg.async_control, @@ -765,13 +770,15 @@ PYBIND11_MODULE(_core, m) { py::arg("frequency") = default_sim_cfg.frequency, py::arg("max_convergence_steps") = default_sim_cfg.max_convergence_steps, - py::arg("memory") = default_sim_cfg.memory) + py::arg("memory") = default_sim_cfg.memory, + py::arg("renderer") = default_sim_cfg.renderer) .def_readwrite("async_control", &rcs::sim::SimConfig::async_control) .def_readwrite("realtime", &rcs::sim::SimConfig::realtime) .def_readwrite("frequency", &rcs::sim::SimConfig::frequency) .def_readwrite("max_convergence_steps", &rcs::sim::SimConfig::max_convergence_steps) .def_readwrite("memory", &rcs::sim::SimConfig::memory) + .def_readwrite("renderer", &rcs::sim::SimConfig::renderer) .def("__copy__", [](const rcs::sim::SimConfig& self) { return rcs::sim::SimConfig(self); @@ -792,6 +799,9 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("qpos", &rcs::sim::DynamicJointState::qpos) .def_readwrite("qvel", &rcs::sim::DynamicJointState::qvel); + py::class_(sim, "CapturedState") + .def_readonly("timestamp", &rcs::sim::CapturedState::timestamp) + .def_readonly("state", &rcs::sim::CapturedState::state); py::class_>(sim, "Sim") .def(py::init([](long m, long d) { return std::make_shared((mjModel*)m, (mjData*)d); @@ -809,6 +819,15 @@ PYBIND11_MODULE(_core, m) { .def("get_dynamic_joint_state", &rcs::sim::Sim::get_dynamic_joint_state) .def("set_dynamic_joint_state", &rcs::sim::Sim::set_dynamic_joint_state, py::arg("schema"), py::arg("state")) + .def("register_state_capture", &rcs::sim::Sim::register_state_capture, + py::arg("frame_rate"), py::arg("buffer_size"), py::arg("state_spec")) + .def("get_captured_state", &rcs::sim::Sim::get_captured_state, + py::arg("id"), + py::arg("max_timestamp") = std::numeric_limits::infinity()) + .def("captured_state_count", &rcs::sim::Sim::captured_state_count, + py::arg("id")) + .def("clear_captured_states", &rcs::sim::Sim::clear_captured_states, + py::arg("id")) .def("_start_gui_server", &rcs::sim::Sim::start_gui_server, py::arg("id")) .def("_stop_gui_server", &rcs::sim::Sim::stop_gui_server); @@ -920,67 +939,8 @@ PYBIND11_MODULE(_core, m) { .def("get_state", &rcs::sim::SimTilburgHand::get_state) .def("set_config", &rcs::sim::SimTilburgHand::set_config, py::arg("cfg")); - py::enum_(sim, "CameraType") - .value("free", rcs::sim::CameraType::free) - .value("tracking", rcs::sim::CameraType::tracking) - .value("fixed", rcs::sim::CameraType::fixed) - .value("default_free", rcs::sim::CameraType::default_free) - .export_values(); - py::class_( - sim, "SimCameraConfig") - .def(py::init([](const std::string& identifier, int frame_rate, - int resolution_width, int resolution_height, - rcs::sim::CameraType type) { - rcs::sim::SimCameraConfig config; - config.identifier = identifier; - config.frame_rate = frame_rate; - config.resolution_width = resolution_width; - config.resolution_height = resolution_height; - config.type = type; - return config; - }), - py::arg("identifier"), py::arg("frame_rate"), - py::arg("resolution_width"), py::arg("resolution_height"), - py::arg("type") = rcs::sim::CameraType::fixed) - .def_readwrite("type", &rcs::sim::SimCameraConfig::type) - .def("__copy__", - [](const rcs::sim::SimCameraConfig& self) { - return rcs::sim::SimCameraConfig(self); - }) - .def("__deepcopy__", [](const rcs::sim::SimCameraConfig& self, py::dict) { - return rcs::sim::SimCameraConfig(self); - }); - py::class_(sim, "FrameSet") - .def(py::init( - [](const std::unordered_map& - color_frames, - const std::unordered_map& - depth_frames, - double timestamp) { - rcs::sim::FrameSet fs; - fs.color_frames = color_frames; - fs.depth_frames = depth_frames; - fs.timestamp = timestamp; - return fs; - }), - py::arg("color_frames"), py::arg("depth_frames"), - py::arg("timestamp")) - .def_readonly("color_frames", &rcs::sim::FrameSet::color_frames) - .def_readonly("depth_frames", &rcs::sim::FrameSet::depth_frames) - .def_readonly("timestamp", &rcs::sim::FrameSet::timestamp); - py::class_(sim, "SimCameraSet") - .def(py::init, - std::unordered_map, - bool, int>(), - py::arg("sim"), py::arg("cameras"), - py::arg("render_on_demand") = true, - py::arg("max_buffer_frames") = 100) - .def("buffer_size", &rcs::sim::SimCameraSet::buffer_size) - .def("clear_buffer", &rcs::sim::SimCameraSet::clear_buffer) - .def("get_latest_frameset", &rcs::sim::SimCameraSet::get_latest_frameset) - .def_property_readonly("_sim", &rcs::sim::SimCameraSet::get_sim) - .def("get_timestamp_frameset", - &rcs::sim::SimCameraSet::get_timestamp_frameset, py::arg("ts")); + // simulated cameras render the camera of the model named by identifier + sim.attr("SimCameraConfig") = common.attr("BaseCameraConfig"); py::class_(sim, "GuiClient") .def(py::init(), py::arg("id")) .def("get_model_bytes", diff --git a/src/rcs/CMakeLists.txt b/src/rcs/CMakeLists.txt index 56391f749..bd1eb07b1 100644 --- a/src/rcs/CMakeLists.txt +++ b/src/rcs/CMakeLists.txt @@ -6,7 +6,7 @@ endif() add_library(rcs SHARED) target_include_directories(rcs PUBLIC ${CMAKE_SOURCE_DIR}/include) -target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp utils.cpp) +target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp) target_link_libraries(rcs PUBLIC Eigen3::Eigen pinocchio::all) set_target_properties(rcs PROPERTIES INSTALL_RPATH "${_rpath_origin};${_rpath_origin}/../cmeel.prefix/lib" diff --git a/src/rcs/utils.cpp b/src/rcs/utils.cpp deleted file mode 100644 index 630d850fa..000000000 --- a/src/rcs/utils.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "rcs/utils.h" - -#include - -#include - -namespace rcs { -namespace common { -enum class RenderBackend { none, egl, current_context }; - -static RenderBackend g_backend = RenderBackend::none; -static PFNEGLMAKECURRENTPROC g_makeCurrent = nullptr; -static EGLDisplay g_display = EGL_NO_DISPLAY; -static EGLSurface g_surface = EGL_NO_SURFACE; -static EGLContext g_context = EGL_NO_CONTEXT; - -void bootstrap_egl_context(uintptr_t fn_addr, uintptr_t dpy, uintptr_t ctx) { - g_makeCurrent = reinterpret_cast(fn_addr); - g_display = reinterpret_cast(dpy); - g_context = reinterpret_cast(ctx); - g_backend = RenderBackend::egl; -} - -void bootstrap_gl_context() { g_backend = RenderBackend::current_context; } - -void ensure_current() { - switch (g_backend) { - case RenderBackend::current_context: - return; - case RenderBackend::egl: - if (!g_makeCurrent(g_display, g_surface, g_surface, g_context)) - throw std::runtime_error("eglMakeCurrent failed"); - return; - case RenderBackend::none: - default: - throw std::runtime_error( - "Rendering was requested, but no render backend was bootstrapped. " - "This usually means libEGL or the MuJoCo GL context is unavailable. " - "Run without cameras/viewers if you do not need rendering, or " - "install " - "the required system EGL/OpenGL runtime libraries."); - } -} -} // namespace common -} // namespace rcs diff --git a/src/sim/CMakeLists.txt b/src/sim/CMakeLists.txt index 5c57a61c9..48ac27199 100644 --- a/src/sim/CMakeLists.txt +++ b/src/sim/CMakeLists.txt @@ -1,6 +1,6 @@ add_library(sim) target_sources(sim - PRIVATE sim.cpp SimRobot.cpp renderer.cpp camera.cpp SimGripper.cpp SimTilburgHand.cpp gui_server.cpp gui_client.cpp + PRIVATE sim.cpp SimRobot.cpp SimGripper.cpp SimTilburgHand.cpp gui_server.cpp gui_client.cpp ) target_link_libraries(sim PUBLIC rcs MuJoCo::MuJoCo) diff --git a/src/sim/camera.cpp b/src/sim/camera.cpp deleted file mode 100644 index eadbae5b3..000000000 --- a/src/sim/camera.cpp +++ /dev/null @@ -1,157 +0,0 @@ - -#include "sim/camera.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "mujoco/mjdata.h" -#include "mujoco/mjmodel.h" -#include "mujoco/mujoco.h" -#include "rcs/Robot.h" - -namespace rcs { -namespace sim { - -SimCameraSet::SimCameraSet( - std::shared_ptr sim, - std::unordered_map cameras_cfg, - bool render_on_demand, int max_buffer_frames) - : sim{sim}, - cameras_cfg{cameras_cfg}, - buffer{}, - buffer_lock{}, - cameras{}, - render_on_demand{render_on_demand}, - max_buffer_frames{max_buffer_frames} { - if (this->max_buffer_frames <= 0) { - throw std::invalid_argument("max_buffer_frames must be positive"); - } - buffer.resize(this->max_buffer_frames); - for (auto const& [id, cam] : cameras_cfg) { - this->sim->register_rendering_callback( - [this](const std::string& id, mjrContext& ctx, mjvScene& scene, - mjvOption& opt) { this->frame_callback(id, ctx, scene, opt); }, - id, cam.frame_rate, cam.resolution_width, cam.resolution_height); - - mjvCamera mjcam; - mjv_defaultCamera(&mjcam); - - if (cam.type == CameraType::default_free) { - mjv_defaultFreeCamera(this->sim->m, &mjcam); - } else { - mjcam.type = cam.type; - mjcam.fixedcamid = - mj_name2id(this->sim->m, mjOBJ_CAMERA, cam.identifier.c_str()); - } - cameras[id] = mjcam; - } -} - -SimCameraSet::~SimCameraSet() {} -int SimCameraSet::buffer_size() { - std::lock_guard lock(buffer_lock); - return buffer_len; -} -void SimCameraSet::clear_buffer() { - std::lock_guard lock(buffer_lock); - // when we clear the buffer, there is no last image timestep - this->last_ts = 0; - this->next_ring_index = 0; - this->buffer_len = 0; - std::fill(buffer.begin(), buffer.end(), std::nullopt); -} - -std::optional SimCameraSet::get_latest_frameset() { - if (this->render_on_demand) { - this->render_all(); - } - std::lock_guard lock(buffer_lock); - if (buffer_len == 0) { - return std::nullopt; - } - int idx = (next_ring_index - 1 + max_buffer_frames) % max_buffer_frames; - return buffer[idx]; -} -std::optional SimCameraSet::get_timestamp_frameset(float ts) { - std::lock_guard lock(buffer_lock); - for (int i = 0; i < buffer_len; ++i) { - int idx = (next_ring_index - i - 1 + max_buffer_frames) % max_buffer_frames; - if (buffer[idx].has_value() && buffer[idx]->timestamp <= ts) { - return buffer[idx]; - } - } - return std::nullopt; -} - -void SimCameraSet::render_all() { - for (auto const& [id, cam] : this->cameras_cfg) { - mjrContext* ctx = this->sim->renderer.get_context(id); - this->render_single(id, *ctx, this->sim->renderer.scene, - this->sim->renderer.opt); - } -} - -void SimCameraSet::frame_callback(const std::string& id, mjrContext& ctx, - mjvScene& scene, mjvOption& opt) { - if (!this->render_on_demand) { - this->render_single(id, ctx, scene, opt); - } -} - -void SimCameraSet::render_single(const std::string& id, mjrContext& ctx, - mjvScene& scene, mjvOption& opt) { - mjrRect viewport = mjr_maxViewport(&ctx); - int W = viewport.width; - int H = viewport.height; - - // allocate rgb and depth buffers - ColorFrame frame = ColorFrame::Zero(3 * W * H); - DepthFrame depth = DepthFrame::Zero(1 * W * H); - // update abstract scene - // TODO: we might be able to call this once for all cameras - // there is also a mjv_updateCamera function - mjv_updateScene(this->sim->m, this->sim->d, &opt, NULL, &this->cameras[id], - mjCAT_ALL, &scene); - // mjv_updateCamera(this->sim->m, this->sim->d, &this->cameras[id], &scene); - - // render scene in offscreen buffer - mjr_render(viewport, &scene, &ctx); - - // read rgb and depth buffers - // depth documentation can be found here: - // https://registry.khronos.org/OpenGL-Refpages/gl4/html/glReadPixels.xhtml - mjr_readPixels(frame.data(), depth.data(), viewport, &ctx); - - auto ts = this->sim->d->time; - std::lock_guard lock(buffer_lock); - // The following code assumes that all render callbacks for a timestep - // happen directly after each other - if (this->last_ts == ts && this->buffer_len > 0) { - int latest_idx = (this->next_ring_index - 1 + this->max_buffer_frames) % - this->max_buffer_frames; - buffer[latest_idx]->color_frames[id] = frame; - buffer[latest_idx]->depth_frames[id] = depth; - } else { - FrameSet fs; - fs.timestamp = ts; - fs.color_frames[id] = frame; - fs.depth_frames[id] = depth; - buffer[this->next_ring_index] = std::move(fs); - this->next_ring_index = - (this->next_ring_index + 1) % this->max_buffer_frames; - this->buffer_len = std::min(this->buffer_len + 1, this->max_buffer_frames); - this->last_ts = ts; - } -} - -} // namespace sim -} // namespace rcs diff --git a/src/sim/camera.h b/src/sim/camera.h deleted file mode 100644 index 3750c86da..000000000 --- a/src/sim/camera.h +++ /dev/null @@ -1,76 +0,0 @@ -#ifndef RCS_CAMSIM_H -#define RCS_CAMSIM_H -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "rcs/Camera.h" -#include "sim/sim.h" - -namespace rcs { -namespace sim { - -enum CameraType { - free = mjCAMERA_FREE, - tracking = mjCAMERA_TRACKING, - fixed = mjCAMERA_FIXED, - default_free -}; - -struct SimCameraConfig : common::BaseCameraConfig { - CameraType type; -}; - -// (H,W,3) -typedef Eigen::Matrix ColorFrame; -typedef Eigen::Matrix DepthFrame; - -struct FrameSet { - std::unordered_map color_frames; - std::unordered_map depth_frames; - mjtNum timestamp; -}; - -class SimCameraSet { - public: - SimCameraSet(std::shared_ptr sim, - std::unordered_map cameras, - bool render_on_demand = true, int max_buffer_frames = 100); - ~SimCameraSet(); - - int buffer_size(); - void clear_buffer(); - - std::optional get_latest_frameset(); - std::optional get_timestamp_frameset(float ts); - - void frame_callback(const std::string& id, mjrContext& ctx, mjvScene& scene, - mjvOption& opt); - - std::shared_ptr get_sim() { return sim; } - bool render_on_demand; - - private: - std::shared_ptr sim; - std::unordered_map cameras_cfg; - std::vector> buffer; - std::unordered_map cameras; - std::mutex buffer_lock; - int max_buffer_frames; - int next_ring_index = 0; - int buffer_len = 0; - mjtNum last_ts = 0; - void render_all(); - void render_single(const std::string& id, mjrContext& ctx, mjvScene& scene, - mjvOption& opt); -}; -} // namespace sim -} // namespace rcs -#endif // RCS_CAMSIM_H diff --git a/src/sim/renderer.cpp b/src/sim/renderer.cpp deleted file mode 100644 index 9e5e87a43..000000000 --- a/src/sim/renderer.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include -#include - -#include -#include - -#include "rcs/utils.h" -#include "sim/sim.h" -namespace rcs { -namespace sim { - -Renderer::Renderer(mjModel* m) : m{m} { - mjv_defaultOption(&this->opt); - mjv_defaultScene(&this->scene); - size_t max_geoms = 2000; - mjv_makeScene(this->m, &this->scene, max_geoms); - this->ctxs = std::unordered_map(); -} - -Renderer::~Renderer() { - for (auto const& [id, ctx] : this->ctxs) { - mjr_freeContext(ctx); - } - mjv_freeScene(&this->scene); -} - -void Renderer::register_context(const std::string& id, size_t width, - size_t height) { - common::ensure_current(); - mjrContext* ctx = new mjrContext(); - mjr_defaultContext(ctx); - mjr_makeContext(this->m, ctx, 200); - mjr_setBuffer(mjFB_OFFSCREEN, ctx); - mjr_resizeOffscreen(width, height, ctx); - if (ctx->currentBuffer != mjFB_OFFSCREEN) { - std::cout << "Warning: offscreen rendering not supported, using " - "default/window framebuffer" - << std::endl; - } - this->ctxs[id] = ctx; -} - -mjrContext* Renderer::get_context(const std::string& id) { - common::ensure_current(); - mjr_setBuffer(mjFB_OFFSCREEN, this->ctxs[id]); - return this->ctxs[id]; -} -} // namespace sim -} // namespace rcs diff --git a/src/sim/sim.cpp b/src/sim/sim.cpp index 2cbafbb36..a55221fd9 100644 --- a/src/sim/sim.cpp +++ b/src/sim/sim.cpp @@ -2,6 +2,7 @@ #include +#include #include #include #include @@ -13,17 +14,6 @@ namespace rcs { namespace sim { -void process_condition_callbacks(std::vector& cbs, - mjtNum time) { - for (int i = 0; i < std::size(cbs); ++i) { - mjtNum dt = time - cbs[i].last_call_timestamp; - if (dt > cbs[i].seconds_between_calls) { - cbs[i].last_return_value = cbs[i].cb(); - cbs[i].last_call_timestamp = time; - } - } -} - bool get_last_return_value(ConditionCallback cb) { return cb.last_return_value; } @@ -84,7 +74,7 @@ void Sim::init_dynamic_joint_specs() { } } -Sim::Sim(mjModel* m, mjData* d) : m(m), d(d), renderer(m) { +Sim::Sim(mjModel* m, mjData* d) : m(m), d(d) { this->init_dynamic_joint_specs(); }; @@ -95,20 +85,72 @@ bool Sim::set_config(const SimConfig& cfg) { SimConfig Sim::get_config() { return this->cfg; } +Sim::Due Sim::poll(CallbackSchedule& schedule) { + mjtNum time = this->d->time; + if (time < schedule.last_check_time) { + // simulation time went backwards (e.g. the state was set externally) + return Due::restarted; + } + schedule.last_check_time = time; + // call at the physics step closest to the scheduled time + mjtNum half_step = 0.5 * this->m->opt.timestep; + if (time + half_step < schedule.next_call_time) { + return Due::no; + } + if (schedule.period <= 0) { + schedule.next_call_time = time; + } else { + // advance on the fixed schedule, skipping call times that fell into this + // step (rates above the physics rate) + while (schedule.next_call_time <= time + half_step) { + schedule.next_call_time += schedule.period; + } + } + return Due::yes; +} + +void Sim::restart(CallbackSchedule& schedule) { + schedule.next_call_time = this->d->time + schedule.period; + schedule.last_check_time = this->d->time; +} + +void Sim::restart(Callback& callback) { + this->restart(callback.schedule); + if (callback.on_restart) { + callback.on_restart(); + } +} + void Sim::invoke_callbacks() { - for (int i = 0; i < std::size(this->callbacks); ++i) { - Callback& cb = this->callbacks[i]; - mjtNum dt = this->d->time - cb.last_call_timestamp; - if (dt > cb.seconds_between_calls) { - cb.cb(); - cb.last_call_timestamp = this->d->time; + for (size_t i = 0; i < std::size(this->callbacks); ++i) { + switch (this->poll(this->callbacks[i].schedule)) { + case Due::yes: + this->callbacks[i].cb(); + break; + case Due::restarted: + this->restart(this->callbacks[i]); + break; + case Due::no: + break; } } } bool Sim::invoke_condition_callbacks() { - process_condition_callbacks(this->any_callbacks, this->d->time); - process_condition_callbacks(this->all_callbacks, this->d->time); + for (auto* cbs : {&this->any_callbacks, &this->all_callbacks}) { + for (ConditionCallback& cb : *cbs) { + switch (this->poll(cb.schedule)) { + case Due::yes: + cb.last_return_value = cb.cb(); + break; + case Due::restarted: + this->restart(cb.schedule); + break; + case Due::no: + break; + } + } + } if (std::any_of(this->any_callbacks.begin(), this->any_callbacks.end(), get_last_return_value)) { return true; @@ -120,24 +162,14 @@ bool Sim::invoke_condition_callbacks() { return false; } -void Sim::invoke_rendering_callbacks() { - // bool scene_updated = false; - for (size_t i = 0; i < std::size(this->rendering_callbacks); ++i) { - RenderingCallback& cb = this->rendering_callbacks[i]; - mjtNum dt = this->d->time - cb.last_call_timestamp; - if (dt > cb.seconds_between_calls) { - // if (!scene_updated) { - // // update scene once for all cameras - // mjv_updateScene(this->m, this->d, &this->renderer.opt, NULL, NULL, - // mjCAT_ALL, - // &this->renderer.scene); - // scene_updated = true; - // } - mjrContext* ctx = this->renderer.get_context(cb.id); - cb.cb(cb.id, *ctx, this->renderer.scene, this->renderer.opt); - cb.last_call_timestamp = this->d->time; - } - } +void Sim::capture_state(size_t id) { + StateCapture& capture = this->state_captures[id]; + mj_getState(this->m, this->d, + capture.states.data() + capture.next_index * capture.state_size, + capture.state_spec); + capture.timestamps[capture.next_index] = this->d->time; + capture.next_index = (capture.next_index + 1) % capture.capacity; + capture.size = std::min(capture.size + 1, capture.capacity); } bool Sim::is_converged() { return this->converged; } @@ -167,10 +199,10 @@ void Sim::step_until_convergence() { void Sim::step(size_t k) { for (size_t i = 0; i < k; ++i) { - mj_step1(this->m, this->d); + mj_step(this->m, this->d); + // after integration, so that callbacks see a state consistent with its + // time stamp this->invoke_callbacks(); - mj_step2(this->m, this->d); - this->invoke_rendering_callbacks(); } } @@ -309,55 +341,96 @@ void Sim::set_dynamic_joint_state(const DynamicJointSchema& schema, void Sim::reset_callbacks() { for (size_t i = 0; i < std::size(this->callbacks); ++i) { - this->callbacks[i].last_call_timestamp = 0; + this->restart(this->callbacks[i]); } - for (size_t i = 0; i < std::size(this->any_callbacks); ++i) { - this->any_callbacks[i].last_call_timestamp = 0; - } - for (size_t i = 0; i < std::size(this->all_callbacks); ++i) { - this->all_callbacks[i].last_call_timestamp = 0; + for (auto* cbs : {&this->any_callbacks, &this->all_callbacks}) { + for (ConditionCallback& cb : *cbs) { + this->restart(cb.schedule); + } } - for (size_t i = 0; i < std::size(this->rendering_callbacks); ++i) { - // this is negative so that we will directly render the cameras - // in the first step - this->rendering_callbacks[i].last_call_timestamp = - -this->rendering_callbacks[i].seconds_between_calls; +} + +static CallbackSchedule make_schedule(mjtNum seconds_between_calls) { + if (seconds_between_calls < 0) { + throw std::invalid_argument("seconds_between_calls must not be negative"); } + return CallbackSchedule{.period = seconds_between_calls}; } -void Sim::register_cb(std::function cb, - mjtNum seconds_between_calls) { - this->callbacks.push_back(Callback{cb, seconds_between_calls, 0.0}); +size_t Sim::register_cb(std::function cb, + mjtNum seconds_between_calls, + std::function on_restart) { + this->callbacks.push_back( + Callback{.cb = std::move(cb), + .on_restart = std::move(on_restart), + .schedule = make_schedule(seconds_between_calls)}); + this->restart(this->callbacks.back()); + return this->callbacks.size() - 1; } void Sim::register_any_cb(std::function cb, mjtNum seconds_between_calls) { - this->any_callbacks.push_back( - ConditionCallback{cb, seconds_between_calls, 0.0, false}); + this->any_callbacks.push_back(ConditionCallback{ + .cb = std::move(cb), .schedule = make_schedule(seconds_between_calls)}); + this->restart(this->any_callbacks.back().schedule); } void Sim::register_all_cb(std::function cb, mjtNum seconds_between_calls) { - this->all_callbacks.push_back( - ConditionCallback{cb, seconds_between_calls, 0.0, false}); + this->all_callbacks.push_back(ConditionCallback{ + .cb = std::move(cb), .schedule = make_schedule(seconds_between_calls)}); + this->restart(this->all_callbacks.back().schedule); } -void Sim::register_rendering_callback( - std::function - cb, - const std::string& id, int frame_rate, size_t width, size_t height) { - this->renderer.register_context(id, width, height); - // in case frame_rate is zero, rendering needs to be triggered - // manually - if (frame_rate != 0) { - this->rendering_callbacks.push_back( - RenderingCallback{.cb = cb, - .id = id, - .seconds_between_calls = 1.0 / frame_rate, - // this is negative so that we will directly render - // the cameras in the first step - .last_call_timestamp = -1.0 / frame_rate}); +size_t Sim::register_state_capture(double frame_rate, size_t buffer_size, + int state_spec) { + if (frame_rate <= 0) { + throw std::invalid_argument("frame_rate must be positive"); + } + if (buffer_size == 0) { + throw std::invalid_argument("buffer_size must be positive"); } + StateCapture capture; + capture.state_spec = state_spec; + capture.state_size = mj_stateSize(this->m, state_spec); + capture.capacity = buffer_size; + capture.states.resize(buffer_size * capture.state_size); + capture.timestamps.resize(buffer_size); + this->state_captures.push_back(std::move(capture)); + size_t id = this->state_captures.size() - 1; + // on (re)start: clear the buffer and capture the current state right away + this->state_captures[id].callback_id = this->register_cb( + [this, id]() { this->capture_state(id); }, 1.0 / frame_rate, + [this, id]() { + this->state_captures[id].next_index = 0; + this->state_captures[id].size = 0; + this->capture_state(id); + }); + return id; +} + +std::optional Sim::get_captured_state( + size_t id, mjtNum max_timestamp) const { + const StateCapture& capture = this->state_captures.at(id); + for (size_t i = 0; i < capture.size; ++i) { + size_t idx = + (capture.next_index + capture.capacity - 1 - i) % capture.capacity; + if (capture.timestamps[idx] <= max_timestamp) { + return CapturedState{capture.timestamps[idx], + Eigen::Map( + capture.states.data() + idx * capture.state_size, + capture.state_size)}; + } + } + return std::nullopt; +} + +size_t Sim::captured_state_count(size_t id) const { + return this->state_captures.at(id).size; +} + +void Sim::clear_captured_states(size_t id) { + this->restart(this->callbacks.at(this->state_captures.at(id).callback_id)); } void Sim::start_gui_server(const std::string& id) { diff --git a/src/sim/sim.h b/src/sim/sim.h index 9bebea9b0..60c503226 100644 --- a/src/sim/sim.h +++ b/src/sim/sim.h @@ -15,19 +15,8 @@ namespace rcs { namespace sim { -class Renderer { - public: - Renderer(mjModel* m); - ~Renderer(); - void register_context(const std::string& id, size_t width, size_t height); - mjrContext* get_context(const std::string& id); - mjvScene scene; - mjvOption opt; - - private: - mjModel* m; - std::unordered_map ctxs; -}; +// Both renderers are implemented in python, see python/rcs/camera/sim.py +enum class RendererBackend { CLASSIC, FILAMENT }; struct SimConfig { bool async_control = false; @@ -39,28 +28,51 @@ struct SimConfig { // MuJoCo's automatic sizing, which can be too small for scenes with many // contacts ("mj_stackAlloc: insufficient memory"). long long memory = -1; + RendererBackend renderer = RendererBackend::CLASSIC; +}; + +/* Fixed schedule of a callback in simulation time: the k-th call is due at + * start + k * period and happens at the physics step closest to that time, so + * that the calls do not drift. The schedule restarts on reset and whenever + * the simulation time goes backwards. */ +struct CallbackSchedule { + mjtNum period; // in seconds, 0 calls the callback every step + mjtNum next_call_time = 0; // in seconds of simulation time + mjtNum last_check_time = 0; // to detect the simulation time going backwards }; struct Callback { - const std::function cb; - mjtNum seconds_between_calls; // in seconds - mjtNum last_call_timestamp; + std::function cb; + // called when the schedule (re)starts: at registration, on reset and when + // the simulation time goes backwards, may be empty + std::function on_restart; + CallbackSchedule schedule; }; struct ConditionCallback { - const std::function cb; - mjtNum seconds_between_calls; // in seconds - mjtNum last_call_timestamp; // in seconds - bool last_return_value; + std::function cb; + CallbackSchedule schedule; + bool last_return_value = false; +}; + +/* Simulation states captured at a fixed rate of simulation time, e.g. at the + * exposure times of a camera, so that they can be rendered later. Kept in a + * ring buffer of the most recent states. The captures are taken by a + * callback. */ +struct StateCapture { + size_t callback_id; + int state_spec; // mjtState bit mask passed to mj_getState + int state_size; + size_t capacity; + std::vector states; // capacity x state_size, row major + std::vector timestamps; // capacity + size_t next_index = 0; + size_t size = 0; }; -struct RenderingCallback { - const std::function - cb; - const std::string id; // rendering context id in renderer class - mjtNum seconds_between_calls; // in seconds - mjtNum last_call_timestamp; // in seconds +struct CapturedState { + mjtNum timestamp; + rcs::common::VectorXd state; }; struct DynamicJointSchema { @@ -90,12 +102,16 @@ class Sim { std::vector callbacks; std::vector any_callbacks; std::vector all_callbacks; - std::vector rendering_callbacks; + std::vector state_captures; std::vector dynamic_joint_specs; std::unordered_map dynamic_joint_name_to_index; + enum class Due { no, yes, restarted }; + Due poll(CallbackSchedule& schedule); + void restart(CallbackSchedule& schedule); + void restart(Callback& callback); void invoke_callbacks(); bool invoke_condition_callbacks(); - void invoke_rendering_callbacks(); + void capture_state(size_t id); void init_dynamic_joint_specs(); static int get_joint_qpos_size(int joint_type); static int get_joint_qvel_size(int joint_type); @@ -106,7 +122,6 @@ class Sim { public: // TODO: hide m & d, pass as parameter to callback (easier refactoring) - rcs::sim::Renderer renderer; mjModel* m; mjData* d; Sim(mjModel* m, mjData* d); @@ -121,23 +136,33 @@ class Sim { DynamicJointState get_dynamic_joint_state() const; void set_dynamic_joint_state(const DynamicJointSchema& schema, const DynamicJointState& state); - /* NOTE: IMPORTANT, the callback is not necessarily called at exactly the - * the requested interval. We invoke a callback if the elapsed simulation time - * since the last call of the callback is greater than the requested time. - * The exact interval at which they are called depends on the models timestep - * option (cf. - * https://mujoco.readthedocs.io/en/stable/programming/simulation.html#simulation-loop - */ - void register_cb(std::function cb, mjtNum seconds_between_calls); + /* Callbacks are called after each physics step that is closest to their + * fixed schedule of start + k * seconds_between_calls in simulation time, + * i.e. the actual calls jitter by up to half a timestep but do not drift. + * The schedule starts at registration and restarts on reset and whenever + * the simulation time goes backwards. seconds_between_calls = 0 calls the + * callback after every step. Condition callbacks are only evaluated in + * step_until_convergence. */ + size_t register_cb(std::function cb, mjtNum seconds_between_calls, + std::function on_restart = nullptr); void register_any_cb(std::function cb, mjtNum seconds_between_calls); void register_all_cb(std::function cb, mjtNum seconds_between_calls); - void register_rendering_callback( - std::function - cb, - const std::string& id, int frame_rate, size_t width, size_t height); + /* Captures the simulation state (mj_getState with state_spec) frame_rate + * times per second of simulation time and keeps the latest buffer_size + * states. The current state is captured right away. The captures are taken + * by a callback, i.e. they follow its fixed schedule and happen after + * integration so that the state is consistent with its time stamp. Returns + * the id of the capture. */ + size_t register_state_capture(double frame_rate, size_t buffer_size, + int state_spec); + /* Latest captured state with a time stamp <= max_timestamp */ + std::optional get_captured_state(size_t id, + mjtNum max_timestamp) const; + size_t captured_state_count(size_t id) const; + /* Clears the buffer and restarts the capture schedule at the current state */ + void clear_captured_states(size_t id); void start_gui_server(const std::string& id); void stop_gui_server(); void sync_gui();