Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/changelog.d/221.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add GL context lock for server mode
85 changes: 85 additions & 0 deletions src/ansys/visor/viewer/renderer/gl_context_lock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""
GlContextLock
=============
Scene lock for a scene whose render window is drawn on another thread.

An OpenGL context is current on at most one thread. VTK makes a window's
context current on the calling thread whenever it frees or builds graphics
resources (removing an actor, turning a widget off) and leaves it current.
A frame drawn later on another thread then cannot make the context current,
and draws nothing or aborts the process.

:class:`GlContextLock` is the re-entrant scene lock that every VTK touch of
such a window holds. When the outermost hold ends, it releases the window's
context if the holding thread has it current, so the next holder, on any
thread, can make it current.
"""

from __future__ import annotations

import threading
from typing import TYPE_CHECKING, Protocol

if TYPE_CHECKING:
from vtkmodules.vtkRenderingCore import vtkRenderWindow


class SceneLock(Protocol):
"""The lock operations a scene and its streaming window use."""

def acquire(self, blocking: bool = True) -> bool:
"""Acquire; non-blocking returns False when held elsewhere."""

def release(self) -> None:
"""Release one level."""

def __enter__(self) -> object:
"""Acquire, blocking."""

def __exit__(self, *exc: object) -> None:
"""Release one level."""


class GlContextLock:
"""Re-entrant lock; when the outermost hold ends, the render window's GL context is current on no thread."""

_render_window: vtkRenderWindow
_lock: threading.RLock
_depth: int

def __init__(self, render_window: vtkRenderWindow) -> None:
"""Wrap a new RLock around *render_window*."""
self._render_window = render_window
self._lock = threading.RLock()
self._depth = 0

@property
def depth(self) -> int:
"""Holds taken and not yet released by the holding thread; 0 when free."""
return self._depth

def acquire(self, blocking: bool = True) -> bool:
"""Acquire the RLock; on success increment the hold depth."""
if not self._lock.acquire(blocking):
return False
self._depth += 1
return True

def release(self) -> None:
"""Decrement the depth; at depth 0 release the context if current here, then release the RLock."""
self._depth -= 1
try:
# Released before the RLock, so no other thread can acquire in between.
if self._depth == 0 and self._render_window.IsCurrent():
self._render_window.ReleaseCurrent()
finally:
self._lock.release()

def __enter__(self) -> GlContextLock:
"""Acquire, blocking."""
self.acquire()
return self

def __exit__(self, *exc: object) -> None:
"""Release one level."""
self.release()
14 changes: 2 additions & 12 deletions src/ansys/visor/viewer/renderer/server_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@

from __future__ import annotations

from typing import Callable, Protocol
from typing import Callable

import numpy as np
from numpy.typing import NDArray
from trame_rca.rca.protocol import RemoteControlledAreaProtocol

from ansys.visor.viewer.renderer.gl_context_lock import SceneLock
from ansys.visor.viewer.renderer.server_renderer import INITIAL_WINDOW_SIZE, ServerRenderer

GESTURE_END_EVENT_TYPES: frozenset[str] = frozenset(
Expand All @@ -36,16 +37,6 @@
"""


class SceneLock(Protocol):
"""The two lock operations the window uses."""

def acquire(self, blocking: bool = True) -> bool:
"""Acquire; non-blocking returns False when held elsewhere."""

def release(self) -> None:
"""Release one level."""


class VisorRcaWindow:
"""trame-rca area over a ServerRenderer that touches VTK only while holding the scene lock."""

Expand Down Expand Up @@ -103,7 +94,6 @@ def img_cols_rows(self) -> tuple[NDArray, int, int]:
self._last_frame = frame
return frame
finally:
self._renderer.render_window.ReleaseCurrent()
self._vtk_lock.release()

def process_resize_event(self, width: int, height: int) -> None:
Expand Down
14 changes: 9 additions & 5 deletions src/ansys/visor/viewer/vtk/scene/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import json
import math
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List
Expand All @@ -29,6 +28,7 @@
from ansys.visor.viewer.models.runtime.scene.runtime_view_state import RuntimeViewState
from ansys.visor.viewer.models.runtime.visor_scene_details import VisorSceneDetails
from ansys.visor.viewer.renderer.base import IRenderer
from ansys.visor.viewer.renderer.gl_context_lock import SceneLock
from ansys.visor.viewer.vtk.datasets.visor_dataset import VisorDataset
from ansys.visor.viewer.vtk.datasets.visor_dataset_registry import VisorDatasetRegistry
from ansys.visor.viewer.vtk.scene.scene_graph_state_builder import SceneGraphStateBuilder
Expand Down Expand Up @@ -111,9 +111,11 @@ def __init__(
self,
server: Server,
dark_mode: bool = False,
renderer: IRenderer | None = None
renderer: IRenderer | None = None,
*,
vtk_lock: SceneLock,
):
"""Initialize the scene coordinator around the injected *renderer*."""
"""Initialize the scene coordinator around the injected *renderer* and scene lock *vtk_lock*."""
logger.debug("Initializing %s", type(self).__name__)

# The server's UI record, held as a model like the camera record.
Expand Down Expand Up @@ -172,8 +174,10 @@ def __init__(
# mutated from the caller's (notebook/main) thread. Re-entrant because
# the locked paths nest: finalize_scene -> populate_scene ->
# update_widgets, finalize_scene -> render, and the per-part
# coordinator methods -> apply -> flush.
self._vtk_lock = threading.RLock()
# coordinator methods -> apply -> flush. Injected because a scene
# whose window is drawn on another thread needs a lock that also
# releases the GL context (GlContextLock).
self._vtk_lock = vtk_lock

self._dataset_registry = self._initialize_dataset_registry()

Expand Down
3 changes: 2 additions & 1 deletion src/ansys/visor/viewer/vtk/scene/local_scene.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import threading
from typing import TYPE_CHECKING

from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger
Expand Down Expand Up @@ -38,7 +39,7 @@ def __init__(self, server: Server, dark_mode: bool = False):

try:
vtk_renderer = VisorLocalRenderer(server)
super().__init__(server, dark_mode, renderer=vtk_renderer)
super().__init__(server, dark_mode, renderer=vtk_renderer, vtk_lock=threading.RLock())
self._frontend_bridge = VisorFrontendBridge(server, self._renderer.frontend_ref_name)
except RuntimeError as e:
msg = f"Failed to initialize VTK pipeline: {e}"
Expand Down
10 changes: 8 additions & 2 deletions src/ansys/visor/viewer/vtk/scene/server_scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from trame_rca.rca import VtkRemoteControlledArea
from trame_server import Server

from ansys.visor.viewer.renderer.gl_context_lock import GlContextLock
from ansys.visor.viewer.renderer.server_renderer import ServerRenderer
from ansys.visor.viewer.renderer.server_window import VisorRcaWindow
from ansys.visor.viewer.vtk.scene.base import VisorSceneBase
Expand Down Expand Up @@ -50,9 +51,14 @@ def __init__(
bridge: ServerLoopBridge,
view_record_publisher: ViewRecordPublisher,
) -> None:
"""Build the ServerRenderer and the RCA window over this scene's lock."""
"""Build the ServerRenderer, a GlContextLock over its window as the scene lock, and the RCA window over that lock."""
renderer = ServerRenderer(BACKGROUND_RGB[dark_mode], bridge, view_record_publisher)
super().__init__(server, dark_mode, renderer=renderer)
super().__init__(
server,
dark_mode,
renderer=renderer,
vtk_lock=GlContextLock(renderer.render_window),
)
self._rca_window = VisorRcaWindow(
VtkRemoteControlledArea(renderer.render_window),
renderer,
Expand Down
93 changes: 93 additions & 0 deletions tests/integration/test_server_scene_gl_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""
Integration tests: a scene write on another thread leaves the next frame drawable.

Builds a real VisorServerScene, so its GlContextLock over a real off-screen
window, and draws every frame on the test's own thread through the scene's
RCA window. The first frame is drawn on that thread too: the window's hidden
native window belongs to the thread that first draws it, and a thread that
exits takes it with it. The writes under test run on a second thread, as a
REST call does. Needs an OpenGL context; runs unmarked in the gates.
"""

from __future__ import annotations

import threading
from types import SimpleNamespace
from unittest.mock import MagicMock

import pytest
from vtkmodules.vtkFiltersSources import vtkSphereSource

from ansys.visor.viewer.models.common.visor_camera_state import VisorCameraState
from ansys.visor.viewer.vtk.scene.server_scene import VisorServerScene


class _NullBridge:
"""Accepts frame requests and retries."""

def request_frame(self) -> None:
pass

def retry_frame(self) -> None:
pass


def _run_on_other_thread(target, *args) -> None:
thread = threading.Thread(target=target, args=args)
thread.start()
thread.join()


def _centre_pixel(scene: VisorServerScene) -> tuple[int, int, int]:
image, _, _ = scene.rca_window.img_cols_rows
return tuple(int(c) for c in image[150, 150])


def _look_at_origin_from_z(scene: VisorServerScene) -> None:
"""Point the camera down -z at the origin from z = 9; caller holds the lock."""
scene._renderer.sync_camera(
VisorCameraState(
position=[0.0, 0.0, 9.0],
focal_point=[0.0, 0.0, 0.0],
view_up=[0.0, 1.0, 0.0],
clipping_range=[1.0, 20.0],
parallel_projection=False,
view_angle=30.0,
parallel_scale=3.0,
)
)


@pytest.fixture
def scene() -> VisorServerScene:
"""A light-theme scene with no datasets and one frame drawn."""
s = VisorServerScene(MagicMock(name="server"), False, _NullBridge(), MagicMock(name="publisher"))
s.rca_window.img_cols_rows
return s


def test_frame_after_cross_section_off_on_another_thread_is_background(scene):
"""Turning the plane widget off makes the context current on its thread; the next frame still draws."""
with scene._vtk_lock:
scene._renderer.update_bounds([-0.5, 0.5, -0.5, 0.5, -0.5, 0.5])
_look_at_origin_from_z(scene)
scene.set_cross_section_visibility(True)
scene.rca_window.img_cols_rows

_run_on_other_thread(scene.set_cross_section_visibility, False)

assert _centre_pixel(scene) == (247, 247, 247)


def test_frame_after_clear_on_another_thread_is_background(scene):
"""Removing a part makes the context current on its thread; the next frame still draws."""
source = vtkSphereSource()
source.Update()
with scene._vtk_lock:
scene._renderer.register_node(SimpleNamespace(id=7), source.GetOutput())
_look_at_origin_from_z(scene)
scene.rca_window.img_cols_rows

_run_on_other_thread(scene.clear)

assert _centre_pixel(scene) == (247, 247, 247)
1 change: 0 additions & 1 deletion tests/unit/app/test_server_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,6 @@ class _SizeRecordingRenderer:

def __init__(self) -> None:
self.sizes: list[tuple[int, int]] = []
self.render_window = MagicMock(name="render_window")
self.pixel_scales: list[float] = []

def set_viewport_size(self, width: int, height: int) -> None:
Expand Down
Loading
Loading