Skip to content

Commit c95067c

Browse files
feat: Pick and highlight geometry through the server in client mode (#204)
Co-authored-by: pyansys-ci-bot <92810346+pyansys-ci-bot@users.noreply.github.com>
1 parent d393de3 commit c95067c

35 files changed

Lines changed: 805 additions & 546 deletions

‎doc/changelog.d/204.added.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Pick and highlight geometry through the server in client mode

‎src/ansys/visor/viewer/app/trame/local_app.py‎

Lines changed: 47 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,50 @@
11
from logging import Logger
2+
from typing import Callable, Protocol
23

34
from trame.app.core import Server
45
from trame.decorators import TrameApp, trigger
56
from vtk import vtkObject
67

7-
from ansys.visor.viewer.app.trame.scene_trigger_app import SceneMutationApi, SceneTriggerApp
8+
from ansys.visor.viewer.app.trame.scene_trigger_app import (
9+
SceneMutationApi,
10+
SceneTriggerApp,
11+
parse_payload,
12+
)
813
from ansys.visor.viewer.config import settings
914
from ansys.visor.viewer.core.visor_enums import RenderingMode
1015
from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger
16+
from ansys.visor.viewer.models.runtime.picking.geometry_pick import GeometryPick
17+
from ansys.visor.viewer.models.runtime.requests.geometry_pick_payloads import PickGeometryInViewPayload
18+
from ansys.visor.viewer.models.runtime.requests.pixel_scale_payload import SetPixelScalePayload
19+
from ansys.visor.viewer.vtk.picking.part_cell_hit import PickView
1120

1221
logger = VisorDefaultLogger(__name__)
1322

1423
# Disable VTK warning display
1524
vtkObject.GlobalWarningDisplayOff()
1625

1726

27+
class LocalSceneMutationApi(SceneMutationApi, Protocol):
28+
"""The scene surface LocalApp's triggers call: the shared one plus the client-only pixel scale."""
29+
30+
def set_pixel_scale(self, pixel_scale: float) -> None: ...
31+
32+
1833
@TrameApp()
1934
class LocalApp(SceneTriggerApp):
2035
"""
2136
LocalApp serves the scene triggers shared by every rendering mode, plus
22-
the local-only triggers for sub-geometry picking and client performance
23-
reporting, for client-side rendering via VTK-WASM in the browser.
37+
the local-only triggers for sub-geometry picking through the client's
38+
view and client performance reporting, for client-side rendering via
39+
VTK-WASM in the browser.
2440
2541
Attributes:
2642
server (Server): the Trame server instance
2743
Methods:
28-
pick_geometry: picks the geometry for rendering
44+
pick_geometry_in_view: picks the geometry feature under a pixel of the client's window
2945
perf_report_wasm: reports the performance of the wasm update cycle
3046
perf_report_server_update: reports the performance of the server update cycle
47+
set_pixel_scale: sets the device pixel ratio the geometry highlight is drawn at
3148
set_only_cookie: sets a cookie on the server (note: Trame server only allows a single cookie header)
3249
"""
3350
def __init__(
@@ -36,11 +53,11 @@ def __init__(
3653
get_scene_details_json: callable,
3754
standalone: bool = True,
3855
trame_logger: Logger | None = None,
39-
pick_geometry=None,
40-
scene_mutation_api: SceneMutationApi | None = None,
56+
scene_mutation_api: LocalSceneMutationApi | None = None,
57+
*,
58+
pick_geometry_in_view: Callable[[PickView, int, int, str], GeometryPick],
4159
):
42-
# Callable for sub-geometry picking (optional), local-only.
43-
self._pick_geometry = pick_geometry
60+
self._pick_geometry_in_view = pick_geometry_in_view
4461
super().__init__(
4562
server=server,
4663
get_scene_details_json=get_scene_details_json,
@@ -54,12 +71,28 @@ def rendering_mode(self) -> RenderingMode:
5471
"""This app serves client-side rendering via VTK-WASM in the browser."""
5572
return RenderingMode.CLIENT
5673

57-
@trigger("pick_geometry")
58-
def pick_geometry(self, actor_wasm_id, cell_id, mode: str, world_x: float, world_y: float, world_z: float):
59-
"""Frontend → Backend: perform sub-geometry picking given a WASM actor/cell ID and world-space point."""
60-
if self._pick_geometry is None:
61-
return {"found": False}
62-
return self._pick_geometry(actor_wasm_id, cell_id, mode, world_x, world_y, world_z)
74+
@trigger("pick_geometry_in_view")
75+
@parse_payload(PickGeometryInViewPayload)
76+
def pick_geometry_in_view(self, payload) -> dict:
77+
"""Frontend -> Backend: the geometry feature under a pixel of the client's window, dumped by alias.
78+
79+
Picked through the client's camera and window size; highlights nothing.
80+
"""
81+
view = PickView(camera_state=payload.camera, width=payload.width, height=payload.height)
82+
return self._pick_geometry_in_view(view, payload.x, payload.y, payload.mode).model_dump(by_alias=True)
83+
84+
@trigger("set_pixel_scale")
85+
@parse_payload(SetPixelScalePayload)
86+
def set_pixel_scale(self, payload) -> None:
87+
"""Frontend -> Backend: the client reports its device pixel ratio for the geometry highlight.
88+
89+
Server mode learns the same ratio from the remote-canvas size report,
90+
so only client mode registers this.
91+
"""
92+
api = self._mutation_api("set_pixel_scale", payload)
93+
if api is None:
94+
return
95+
api.set_pixel_scale(payload.scale)
6396

6497
@trigger("perf_report_wasm")
6598
def perf_report_wasm(self, payload: dict):

‎src/ansys/visor/viewer/app/visor_vtk_local.py‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -44,17 +44,11 @@ def _initialize_rendering(self, standalone: bool, trame_log_dir: str | None) ->
4444
lambda: self._scene.get_scene_details_json(),
4545
standalone,
4646
trame_logger=get_trame_logger(trame_log_dir),
47-
pick_geometry=lambda
48-
actor_wasm_id,
49-
cell_id,
50-
mode,
51-
world_x,
52-
world_y,
53-
world_z: self._scene.pick_geometry(actor_wasm_id, cell_id, mode, world_x, world_y, world_z),
54-
# The scene satisfies LocalApp's SceneMutationApi protocol
55-
# structurally: the six per-part coordinator methods carry exactly
56-
# the names and signatures the triggers call.
47+
# The scene satisfies LocalApp's LocalSceneMutationApi protocol
48+
# structurally: the coordinator methods carry exactly the names
49+
# and signatures the triggers call.
5750
scene_mutation_api=self._scene,
51+
pick_geometry_in_view=self._scene.pick_geometry_in_view,
5852
)
5953

6054
def _post_scene_change_hook(self) -> None:

‎src/ansys/visor/viewer/models/runtime/requests/geometry_pick_payloads.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
"""Models for the geometry-pick trigger payloads."""
22

3-
from pydantic import BaseModel
3+
from typing import Annotated
44

5+
from pydantic import BaseModel, Field
6+
7+
from ansys.visor.viewer.models.common.visor_camera_state import VisorCameraState
58
from ansys.visor.viewer.models.runtime.picking.geometry_pick import GeometryPick, GeometryPickMode
69

710

@@ -13,6 +16,17 @@ class PickGeometryAtPayload(BaseModel):
1316
mode: GeometryPickMode
1417

1518

19+
class PickGeometryInViewPayload(BaseModel):
20+
"""pick_geometry_in_view payload: a pixel of the client's window, origin bottom-left, the window's size, its camera record, and the mode."""
21+
22+
x: int
23+
y: int
24+
width: Annotated[int, Field(gt=0)]
25+
height: Annotated[int, Field(gt=0)]
26+
mode: GeometryPickMode
27+
camera: VisorCameraState
28+
29+
1630
class SetGeometryHighlightPayload(BaseModel):
1731
"""set_geometry_highlight payload: the pick whose feature to highlight; a not-found pick clears it."""
1832

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
"""Model for the ``set_pixel_scale`` trigger payload."""
2+
3+
from typing import Annotated
4+
5+
from pydantic import BaseModel, Field
6+
7+
8+
class SetPixelScalePayload(BaseModel):
9+
"""set_pixel_scale payload: the client's device pixels per CSS pixel, finite and positive."""
10+
11+
scale: Annotated[float, Field(gt=0, allow_inf_nan=False)]

‎src/ansys/visor/viewer/renderer/local_renderer.py‎

Lines changed: 1 addition & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,12 @@
2323
from ansys.visor.viewer.core.perf_timer import PerfTimer
2424
from ansys.visor.viewer.core.visor_colors import VisorColors
2525
from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger
26-
from ansys.visor.viewer.models.runtime.picking.geometry_pick import NoGeometryPick
2726
from ansys.visor.viewer.models.runtime.vtk.renderer_annotation import (
2827
WasmNodeHandles,
2928
WasmRendererAnnotation,
3029
WasmWidgetHandles,
3130
)
3231
from ansys.visor.viewer.renderer.pipeline_renderer import VtkPipelineRenderer
33-
from ansys.visor.viewer.vtk.picking.cell_feature_finder import CellFeatureFinder
3432
from ansys.visor.viewer.vtk.widgets.visor_bounding_box import VisorBoundingBox
3533
from ansys.visor.viewer.vtk.widgets.visor_cross_section import VisorCrossSectionWidget
3634
from ansys.visor.viewer.vtk.widgets.visor_orientation import VisorOrientationWidget
@@ -200,7 +198,7 @@ def _present_geometry_highlight(self) -> None:
200198
self.push_without_rebuild()
201199

202200
def _initial_highlight_pixel_scale(self) -> float:
203-
"""1.0: the client draws its own overlay here, so the actor's sizes are not shown."""
201+
"""1.0 until the client reports its device pixel ratio."""
204202
return 1.0
205203

206204
# ------------------------------------------------------------------
@@ -217,72 +215,6 @@ def set_cross_section_visibility(self, visible: bool) -> None:
217215
def set_bounding_box_visibility(self, visible: bool) -> None:
218216
"""No-op: the widget's enablement is driven client-side."""
219217

220-
# ------------------------------------------------------------------
221-
# Local-only: picking
222-
# ------------------------------------------------------------------
223-
224-
def pick_geometry(
225-
self,
226-
actor_wasm_id: int,
227-
cell_id: int,
228-
mode: str,
229-
world_pos: tuple[float, float, float],
230-
) -> dict:
231-
"""
232-
Resolve a client-initiated pick event to a sub-geometry payload.
233-
234-
The actor is found by matching each renderer actor's object-manager
235-
id against *actor_wasm_id*; the coordinator never performs that
236-
resolution.
237-
238-
Parameters
239-
----------
240-
actor_wasm_id:
241-
Client-supplied opaque actor identifier from the wasm-side picker.
242-
cell_id:
243-
Cell index within the picked actor's mapper dataset.
244-
mode:
245-
``"vertex" | "edge" | "face"``.
246-
world_pos:
247-
World-space pick position from the client picker, used to select
248-
the nearest vertex/edge for multi-vertex/edge cells.
249-
250-
Returns
251-
-------
252-
dict
253-
Backend-neutral pick result. Always contains ``"found": bool``.
254-
When ``found`` is ``True``, contains ``"mode"`` and mode-specific
255-
fields (``position`` / ``pointA``+``pointB``+``edgeLength`` /
256-
``points``+``area``).
257-
"""
258-
actor_wasm_id = int(actor_wasm_id)
259-
cell_id = int(cell_id)
260-
pick_pos = (float(world_pos[0]), float(world_pos[1]), float(world_pos[2]))
261-
262-
if actor_wasm_id < 0 or cell_id < 0:
263-
return NoGeometryPick().model_dump(by_alias=True)
264-
265-
# Locate the actor by iterating the renderer's actors and matching
266-
# WASM IDs (avoids depending on a GetObjectAtId reverse-lookup API).
267-
actor = None
268-
actors = self._vtk_renderer.GetActors()
269-
actors.InitTraversal()
270-
a = actors.GetNextActor()
271-
while a is not None:
272-
if self._object_manager.GetId(a) == actor_wasm_id:
273-
actor = a
274-
break
275-
a = actors.GetNextActor()
276-
277-
if actor is None:
278-
return NoGeometryPick().model_dump(by_alias=True)
279-
280-
finder = CellFeatureFinder.from_dataset(
281-
actor.GetMapper().GetInputDataObject(0, 0), cell_id, pick_pos
282-
)
283-
pick = finder.find(mode) if finder is not None else NoGeometryPick()
284-
return pick.model_dump(by_alias=True)
285-
286218
# ------------------------------------------------------------------
287219
# IRenderer: render
288220
# ------------------------------------------------------------------

‎src/ansys/visor/viewer/renderer/pipeline_renderer.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,14 @@ def show_geometry_highlight(self, pick: GeometryPick) -> None:
539539
pick.highlight_with(self._geometry_highlight)
540540
self._present_geometry_highlight()
541541

542+
def set_pixel_scale(self, pixel_scale: float) -> None:
543+
"""Rescale the geometry highlight to this many device pixels per CSS pixel; requests no frame and pushes nothing.
544+
545+
Server mode's resize path, which calls this, schedules its own frame.
546+
In client mode the next highlight shown carries the new size.
547+
"""
548+
self._geometry_highlight.set_pixel_scale(pixel_scale)
549+
542550
# ------------------------------------------------------------------
543551
# Internal init helpers
544552
# ------------------------------------------------------------------

‎src/ansys/visor/viewer/renderer/server_renderer.py‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -88,13 +88,6 @@ def set_viewport_size(self, width: int, height: int) -> None:
8888
self._render_window_interactor.UpdateSize(width, height)
8989
self._orientation_widget.fit_to_window(width, height)
9090

91-
def set_pixel_scale(self, pixel_scale: float) -> None:
92-
"""Rescale the geometry highlight to this many device pixels per CSS pixel.
93-
94-
Requests no frame: the resize path that calls this schedules its own.
95-
"""
96-
self._geometry_highlight.set_pixel_scale(pixel_scale)
97-
9891
def set_background_rgb(self, background_rgb: tuple[float, float, float]) -> None:
9992
"""Clear to this colour from the next frame.
10093

‎src/ansys/visor/viewer/vtk/node_pipeline.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,16 @@
3737
LOOKUP_TABLE_HUE_RANGE: tuple[float, float] = (0.667, 0.0)
3838
"""Blue (low) to red (high)."""
3939

40+
PART_POLYGON_OFFSET: tuple[float, float] = (0.0, 2.0)
41+
"""Relative coincident-topology polygon offset (factor, units) for every part.
42+
43+
Applied by VTK only while the part is drawn with edges on. Positive values push
44+
the part's faces away from the camera, so geometry drawn on faces without an offset
45+
(the geometry highlight) draws in front of the part's faces.
46+
47+
When part edges are on, With a zero polygon offset, the highlight is drawn behind the
48+
face and is invisible.
49+
"""
4050

4151
@dataclass
4252
class VtkNodePipeline:
@@ -80,6 +90,7 @@ def from_dataset(cls, dataset: vtkDataObject) -> "VtkNodePipeline":
8090
mapper.SetInputConnection(base_algorithm.GetOutputPort())
8191
lookup_table = cls._create_lookup_table()
8292
mapper.SetLookupTable(lookup_table)
93+
mapper.SetRelativeCoincidentTopologyPolygonOffsetParameters(*PART_POLYGON_OFFSET)
8394

8495
actor = vtkActor()
8596
actor.SetMapper(mapper)

‎src/ansys/visor/viewer/vtk/scene/local_scene.py‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,17 +66,16 @@ def _push_runtime_state(self, runtime_app_state: "RuntimeAppState") -> None:
6666
self._frontend_bridge.set_state(runtime_app_state)
6767

6868
# -------------------------------------------------------------------------
69-
# Picking — wasm: the client's picker reports a wasm actor id
69+
# Picking — through the client's view, on the server picker
7070
# -------------------------------------------------------------------------
7171

72-
def pick_geometry(self, actor_wasm_id, cell_id, mode, world_x, world_y, world_z) -> dict:
73-
"""
74-
Frontend-trigger entry point for cell picking. Packs the world-space
75-
pick position into a tuple and delegates to the renderer backend.
72+
def set_pixel_scale(self, pixel_scale: float) -> None:
73+
"""Draw the geometry highlight at this many device pixels per CSS pixel; no push, no notify.
74+
75+
The next highlight shown carries the new size to the client.
7676
"""
77-
return self._renderer.pick_geometry(
78-
actor_wasm_id, cell_id, mode, (world_x, world_y, world_z)
79-
)
77+
with self._vtk_lock:
78+
self._renderer.set_pixel_scale(pixel_scale)
8079

8180
def pick_geometry_in_view(self, view: "PickView", x: int, y: int, mode: str) -> "GeometryPick":
8281
"""Find the geometry feature under a pixel of a client's view, under the scene lock."""

0 commit comments

Comments
 (0)