diff --git a/doc/changelog.d/237.fixed.md b/doc/changelog.d/237.fixed.md
new file mode 100644
index 00000000..ab562485
--- /dev/null
+++ b/doc/changelog.d/237.fixed.md
@@ -0,0 +1 @@
+Update_variables no longer rebuilds the frontend and add sim example notebook
diff --git a/examples/notebooks/warp_fluid_update_variables.ipynb b/examples/notebooks/warp_fluid_update_variables.ipynb
new file mode 100644
index 00000000..fac320fa
--- /dev/null
+++ b/examples/notebooks/warp_fluid_update_variables.ipynb
@@ -0,0 +1,345 @@
+{
+ "cells": [
+ {
+ "metadata": {},
+ "cell_type": "code",
+ "outputs": [],
+ "execution_count": null,
+ "source": [
+ "########################################################################\n",
+ "# Fluid Simulation Example - Update Variables\n",
+ "#\n",
+ "# Use Visor to visualize a fluid simulation, and update the\n",
+ "# variables in Visor as the simulation progresses.\n",
+ "#\n",
+ "# Dependency: This example requires the Warp library, which is not\n",
+ "# included in the Visor package.\n",
+ "# > pip install warp-lang[examples]\n",
+ "#\n",
+ "# We use the warp fluid simulation example:\n",
+ "# https://github.com/NVIDIA/warp/blob/main/warp/examples/core/example_fluid.py\n",
+ "#########################################################################\n",
+ "import asyncio\n",
+ "\n",
+ "import numpy as np\n",
+ "import warp as wp\n",
+ "from IPython.display import IFrame\n",
+ "from vtk import vtkHDFWriter, vtkPlaneSource, vtkPolyData\n",
+ "from vtk.util.numpy_support import numpy_to_vtk\n",
+ "from warp.examples.core import example_fluid\n",
+ "from warp.examples.core.example_fluid import Example\n",
+ "\n",
+ "from ansys.visor.viewer import Metadata, Visor\n",
+ "\n",
+ "wp.ScopedTimer.enabled = False\n",
+ "\n",
+ "w = example_fluid.grid_width\n",
+ "h = example_fluid.grid_height\n",
+ "VTKHDF_FILE_PATH = \"warp_fluid_sim.vtkhdf\""
+ ],
+ "id": "b355a718167c2bf0"
+ },
+ {
+ "metadata": {},
+ "cell_type": "code",
+ "outputs": [],
+ "execution_count": null,
+ "source": [
+ "########################################################################\n",
+ "# Sim data + VTK dataset configuration\n",
+ "########################################################################\n",
+ "\n",
+ "def point_arrays(sim):\n",
+ " \"\"\" Return a dict of the fluid fields from the warp simulation, ordered for VTK point arrays.\"\"\"\n",
+ " density = sim.rho0.numpy().T.ravel()\n",
+ " pressure = sim.p0.numpy().T.ravel()\n",
+ " velocity = sim.u0.numpy().transpose(1, 0, 2).reshape(-1, 2)\n",
+ " velocity3 = np.column_stack([velocity, np.zeros(len(velocity), np.float32)])\n",
+ " return {\"density\": density, \"pressure\": pressure, \"velocity\": velocity3}\n",
+ "\n",
+ "def create_grid():\n",
+ " \"\"\"Create a quad mesh, of size w x h with one point per fluid cell.\"\"\"\n",
+ " plane = vtkPlaneSource()\n",
+ " plane.SetOrigin(0, 0, 0)\n",
+ " plane.SetPoint1(w-1, 0, 0)\n",
+ " plane.SetPoint2(0, h-1, 0)\n",
+ " plane.SetResolution(w-1, h-1)\n",
+ " plane.Update()\n",
+ " polydata = vtkPolyData()\n",
+ " polydata.DeepCopy(plane.GetOutput())\n",
+ " # Remove the default arrays so we only have the simulation's variables\n",
+ " for name in (\"Normals\", \"TextureCoordinates\"):\n",
+ " polydata.GetPointData().RemoveArray(name)\n",
+ " return polydata\n",
+ "\n",
+ "def add_arrays_to_dataset(dataset, arrays):\n",
+ " \"\"\"Add point arrays on a VTK dataset\"\"\"\n",
+ " for name, values in arrays.items():\n",
+ " # Create a vtkDataArray from the numpy array\n",
+ " array = numpy_to_vtk(np.ascontiguousarray(values, dtype=np.float32), deep=True)\n",
+ " array.SetName(name)\n",
+ " dataset.GetPointData().AddArray(array)\n",
+ "\n",
+ "def write_vtkhdf(dataset, file_path):\n",
+ " \"\"\"Writes a VTK dataset to disk as VTKHDF.\"\"\"\n",
+ " writer = vtkHDFWriter()\n",
+ " writer.SetInputData(dataset)\n",
+ " writer.SetFileName(file_path)\n",
+ " if not writer.Write():\n",
+ " raise RuntimeError(f\"vtkHDFWriter failed for {file_path}\")\n",
+ "\n",
+ "def create_dataset_and_write_to_disk(sim):\n",
+ " \"\"\"Creates a VTK dataset, adds arrays from the sim, and writes the dataset to disk.\"\"\"\n",
+ " polydata = create_grid()\n",
+ " arrays = point_arrays(sim)\n",
+ " add_arrays_to_dataset(polydata, arrays)\n",
+ " write_vtkhdf(polydata, VTKHDF_FILE_PATH)\n",
+ "\n",
+ "########################################################################\n",
+ "# Visor configuration\n",
+ "########################################################################\n",
+ "\n",
+ "def set_up_metadata(variable_id=\"POINT::velocity::3\"):\n",
+ " \"\"\"Set up metadata for the dataset in Visor.\n",
+ " \n",
+ " This is optional; here, it automatically colors by the specified variable\n",
+ " instead of having to set it manually in the browser.\n",
+ "\n",
+ " Variables available here:\n",
+ " POINT::density::1\n",
+ " POINT::pressure::1\n",
+ " POINT::velocity::3\n",
+ " \"\"\"\n",
+ " metadata = Metadata(\n",
+ " name=\"fluid_simulation\",\n",
+ " unit=\"\",\n",
+ " state={\n",
+ " \"parts\": {\n",
+ " \"fluid_simulation\": {\n",
+ " \"selected\": \"true\", # selecting the part displays the legend by default\n",
+ " \"color_by\": variable_id, # POINT/CELL :: name :: num_components\n",
+ " \"color_by_component\": -1, # -1 is magnitude\n",
+ " }\n",
+ " }\n",
+ " }\n",
+ " )\n",
+ " return metadata\n",
+ "\n",
+ "def configure_visor(port, variable_to_display, mode=\"CLIENT\"):\n",
+ " \"\"\"Instantiate VISOR, start with the VTK dataset file path, and get the dataset's part variables.\"\"\"\n",
+ " visor = Visor(rendering_mode=mode, url=f\"http://localhost:{port}\")\n",
+ " metadata = set_up_metadata(variable_to_display)\n",
+ " dataset_id = visor.start(input=VTKHDF_FILE_PATH, metadata=metadata)\n",
+ " part_variables = visor.list_variables(dataset_id)[0]\n",
+ " return visor, dataset_id, part_variables\n",
+ "\n",
+ "def get_update_dict(dataset_id, variable, new_data):\n",
+ " \"\"\"Create a dictionary to pass to Visor's update_variables API.\"\"\"\n",
+ " update_dict = {\n",
+ " \"type\": variable.type,\n",
+ " \"name\": variable.name,\n",
+ " \"num_components\": variable.num_components,\n",
+ " \"data\": new_data\n",
+ " }\n",
+ " return update_dict\n",
+ "\n",
+ "def update_variables(visor, dataset_id, part_variables, arrays):\n",
+ " \"\"\"Update the Visor dataset to display the new variable data.\"\"\"\n",
+ " update_dicts = []\n",
+ " for variable in part_variables.variables:\n",
+ " update_dicts.append(get_update_dict(dataset_id, variable, arrays.get(variable.name)))\n",
+ " visor.update_variables(dataset_id, update_dicts)\n"
+ ],
+ "id": "7a9aa1fe1b996ae0"
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "fe1f8e393ff128e5",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Warp 1.19.0 initialized:\n",
+ " CUDA Toolkit 13.4, Driver 13.0\n",
+ " Devices:\n",
+ " \"cpu\" : \"Intel64 Family 6 Model 183 Stepping 1, GenuineIntel\"\n",
+ " \"cuda:0\" : \"NVIDIA RTX 5000 Ada Generation Laptop GPU\" (16 GiB, sm_89, mempool enabled)\n",
+ " Kernel cache:\n",
+ " \\\\?\\C:\\Users\\lkasian\\AppData\\Local\\NVIDIA\\warp\\Cache\\1.19.0\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Initialize the simulation, and run 60 steps, from which\n",
+ "# to create the VTK dataset and write to disk as VTKHDF.\n",
+ "sim = Example()\n",
+ "for _ in range(100):\n",
+ " sim.step()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "83f244d00271089f",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# Create a plane, add the data from the initial sim pass as data arrays, and save to disk as vtkhdf.\n",
+ "create_dataset_and_write_to_disk(sim)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "3bbbf65dea57f293",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Server starting...\n",
+ "Server started and ready on http://localhost:8081\n",
+ "Server starting...\n",
+ "Server started and ready on http://localhost:8082\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Instantiate VISOR, start it with the dataset, and get its variable info\n",
+ "# \n",
+ "# Optional: update more than one VISOR instance e.g. to view more than one variable at once.\n",
+ "# In this example: Visor instance 1 by default displays the density\n",
+ "# Visor instance 2 by default displays the pressure.\n",
+ "visor1, dataset_id1, variables1 = configure_visor(port=8081, variable_to_display=\"POINT::density::1\")\n",
+ "visor2, dataset_id2, variables2 = configure_visor(port=8082, variable_to_display=\"POINT::pressure::1\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "d331c5d1ed65e2aa",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "\n",
+ " \n",
+ " "
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "IFrame(src=\"http://localhost:8081\", width=800, height=400)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "ff7ba5d2ee222f0",
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "\n",
+ " \n",
+ " "
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "IFrame(src=\"http://localhost:8082\", width=800, height=400)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "965612190dd9a1f4",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "CancelledError",
+ "evalue": "",
+ "output_type": "error",
+ "traceback": [
+ "\u001B[31m---------------------------------------------------------------------------\u001B[39m",
+ "\u001B[31mCancelledError\u001B[39m Traceback (most recent call last)",
+ "\u001B[36mCell\u001B[39m\u001B[36m \u001B[39m\u001B[32mIn[8]\u001B[39m\u001B[32m, line 6\u001B[39m\n\u001B[32m 2\u001B[39m sim.step()\n\u001B[32m 3\u001B[39m arrays = point_arrays(sim)\n\u001B[32m 4\u001B[39m update_variables(visor1, dataset_id1, variables1, arrays)\n\u001B[32m 5\u001B[39m update_variables(visor2, dataset_id2, variables2, arrays)\n\u001B[32m----> \u001B[39m\u001B[32m6\u001B[39m \u001B[38;5;28;01mawait\u001B[39;00m asyncio.sleep(\u001B[32m0.4\u001B[39m)\n",
+ "\u001B[36mFile \u001B[39m\u001B[32m~\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\asyncio\\tasks.py:665\u001B[39m, in \u001B[36msleep\u001B[39m\u001B[34m(delay, result)\u001B[39m\n\u001B[32m 661\u001B[39m h = loop.call_later(delay,\n\u001B[32m 662\u001B[39m futures._set_result_unless_cancelled,\n\u001B[32m 663\u001B[39m future, result)\n\u001B[32m 664\u001B[39m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[32m--> \u001B[39m\u001B[32m665\u001B[39m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;01mawait\u001B[39;00m future\n\u001B[32m 666\u001B[39m \u001B[38;5;28;01mfinally\u001B[39;00m:\n\u001B[32m 667\u001B[39m h.cancel()\n",
+ "\u001B[31mCancelledError\u001B[39m: "
+ ]
+ }
+ ],
+ "source": [
+ "for _ in range(200):\n",
+ " sim.step()\n",
+ " arrays = point_arrays(sim)\n",
+ " update_variables(visor1, dataset_id1, variables1, arrays)\n",
+ " update_variables(visor2, dataset_id2, variables2, arrays)\n",
+ " await asyncio.sleep(0.4)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "9a0592bead7305e4",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.12.10"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/src/ansys/visor/viewer/app/paraview/visor_vtk_paraview.py b/src/ansys/visor/viewer/app/paraview/visor_vtk_paraview.py
index 78bdbe84..3f1316dd 100644
--- a/src/ansys/visor/viewer/app/paraview/visor_vtk_paraview.py
+++ b/src/ansys/visor/viewer/app/paraview/visor_vtk_paraview.py
@@ -114,12 +114,17 @@ def _initialize_rendering(self, standalone: bool, trame_log_dir: str | None) ->
set_dark_mode=self._scene.set_dark_mode,
rca_window=self._scene.rca_window,
bridge=bridge,
+ get_variable_records_json=self._scene.get_variable_records_json,
)
def _post_scene_change_hook(self) -> None:
"""Bump scene_version so connected clients rebuild; requests no frame, the operation already did."""
self._state_publisher.bump_scene_version()
+ def _post_data_change_hook(self) -> None:
+ """Bump data_version so connected clients refresh in place; requests no frame, the operation already did."""
+ self._state_publisher.bump_data_version()
+
def update_variables(self, dataset_id: int, variables: list[dict[str, Any]]) -> None:
"""Raise UnsupportedInModeError: pvserver holds its own copy of the arrays."""
raise UnsupportedInModeError("update_variables is not supported in PARAVIEW mode")
diff --git a/src/ansys/visor/viewer/app/trame/local_app.py b/src/ansys/visor/viewer/app/trame/local_app.py
index 92aab1f6..0ce0055b 100644
--- a/src/ansys/visor/viewer/app/trame/local_app.py
+++ b/src/ansys/visor/viewer/app/trame/local_app.py
@@ -59,6 +59,7 @@ def __init__(
trame_logger: Logger | None = None,
scene_mutation_api: LocalSceneMutationApi | None = None,
*,
+ get_variable_records_json: Callable[[], str],
pick_geometry_in_view: Callable[[PickView, int, int, str], GeometryPick],
pick_part_in_view: Callable[[PickView, int, int], int | None],
):
@@ -70,6 +71,7 @@ def __init__(
standalone=standalone,
trame_logger=trame_logger,
scene_mutation_api=scene_mutation_api,
+ get_variable_records_json=get_variable_records_json,
)
@property
diff --git a/src/ansys/visor/viewer/app/trame/scene_trigger_app.py b/src/ansys/visor/viewer/app/trame/scene_trigger_app.py
index 789a0d98..66c8c165 100644
--- a/src/ansys/visor/viewer/app/trame/scene_trigger_app.py
+++ b/src/ansys/visor/viewer/app/trame/scene_trigger_app.py
@@ -2,7 +2,7 @@
import urllib.parse
from abc import ABC, abstractmethod
from logging import Logger
-from typing import List, Optional, Protocol, Sequence
+from typing import Callable, List, Optional, Protocol, Sequence
from pydantic import BaseModel, Field, ValidationError
from trame.app.core import Server
@@ -217,10 +217,14 @@ def __init__(
standalone: bool,
trame_logger: Logger | None,
scene_mutation_api: SceneMutationApi | None,
+ *,
+ get_variable_records_json: Callable[[], str],
):
self.server = server
# Callable to get the scene details in JSON format
self._get_scene_details_json = get_scene_details_json
+ # Callable to get the held variable records in JSON format
+ self._get_variable_records_json = get_variable_records_json
# Per-part visual state coordinator (see SceneMutationApi). The one
# production construction site always supplies it; it is optional so
# that the class stays constructible without a scene.
@@ -291,6 +295,11 @@ def get_visor_scene_details_json(self):
""" returns the scene details in JSON format. """
return self._get_scene_details_json()
+ @trigger("get_variable_records_json")
+ def get_variable_records_json(self) -> str:
+ """Return the held variable records, keyed by identifier, in JSON format."""
+ return self._get_variable_records_json()
+
# ------------------------------------------------------------------
# Per-part visual state triggers
#
diff --git a/src/ansys/visor/viewer/app/trame/server_app.py b/src/ansys/visor/viewer/app/trame/server_app.py
index 4ef9dd44..3a013952 100644
--- a/src/ansys/visor/viewer/app/trame/server_app.py
+++ b/src/ansys/visor/viewer/app/trame/server_app.py
@@ -66,6 +66,8 @@ def __init__(
set_dark_mode: Callable[[bool], None],
rca_window: VisorRcaWindow,
bridge: ServerLoopBridge,
+ *,
+ get_variable_records_json: Callable[[], str],
) -> None:
"""Create the area before start; the view handler is built when the server is ready."""
self._pick_part_at = pick_part_at
@@ -79,6 +81,7 @@ def __init__(
standalone=standalone,
trame_logger=trame_logger,
scene_mutation_api=scene_mutation_api,
+ get_variable_records_json=get_variable_records_json,
)
# The server is passed explicitly: a widget left to resolve its own
# would register the stream protocol on the default server.
diff --git a/src/ansys/visor/viewer/app/trame/server_state_publisher.py b/src/ansys/visor/viewer/app/trame/server_state_publisher.py
index dc22cc7e..42e3dc94 100644
--- a/src/ansys/visor/viewer/app/trame/server_state_publisher.py
+++ b/src/ansys/visor/viewer/app/trame/server_state_publisher.py
@@ -27,6 +27,9 @@
SCENE_VERSION_KEY: str = "scene_version"
"""State key counting scene changes; absent until the first change, then 1, 2, ..."""
+DATA_VERSION_KEY: str = "data_version"
+"""State key counting data-only changes, which refresh the client in place; absent until the first, then 1, 2, ..."""
+
class ServerStatePublisher(ViewRecordPublisher):
"""Writes server-originated state keys from any thread onto the trame event loop."""
@@ -63,12 +66,16 @@ def bump_scene_version(self) -> None:
The read happens inside the callback, so bumps queued together from
any threads are serialised on the loop and each one counts.
"""
- self._async_runner.call_soon(self._write_next_scene_version)
+ self._async_runner.call_soon(lambda: self._write_next_version(SCENE_VERSION_KEY))
+
+ def bump_data_version(self) -> None:
+ """Increment data_version on the loop thread, as :meth:`bump_scene_version` does scene_version."""
+ self._async_runner.call_soon(lambda: self._write_next_version(DATA_VERSION_KEY))
- def _write_next_scene_version(self) -> None:
- """Read scene_version (absent counts as 0), write it plus one, and flush; loop thread only."""
- current = self._state[SCENE_VERSION_KEY]
- self._write(SCENE_VERSION_KEY, (current or 0) + 1)
+ def _write_next_version(self, key: str) -> None:
+ """Read the counter at *key* (absent counts as 0), write it plus one, and flush; loop thread only."""
+ current = self._state[key]
+ self._write(key, (current or 0) + 1)
def _write(self, key: str, value: object) -> None:
"""Set one state key and flush it; loop thread only."""
diff --git a/src/ansys/visor/viewer/app/visor_vtk.py b/src/ansys/visor/viewer/app/visor_vtk.py
index 62005ccd..ebc3dd98 100644
--- a/src/ansys/visor/viewer/app/visor_vtk.py
+++ b/src/ansys/visor/viewer/app/visor_vtk.py
@@ -98,6 +98,22 @@ def wrapper(self, *args, **kwargs):
return wrapper
+def notifies_data_change(func):
+ """Call self._post_data_change_hook() once after func, whether func returns or raises.
+
+ For an operation that changes data values only, so connected clients
+ refresh in place rather than rebuild. A failed operation can still have
+ changed data, so it notifies too. Placed directly above the method.
+ """
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ try:
+ return func(self, *args, **kwargs)
+ finally:
+ self._post_data_change_hook()
+ return wrapper
+
+
class VisorVTK(Visor):
"""
VisorVTK is a class that provides an interface for initializing and managing a
@@ -212,6 +228,11 @@ def _post_scene_change_hook(self) -> None:
"""Signal one finished scene-changing operation to connected clients."""
raise NotImplementedError
+ @abstractmethod
+ def _post_data_change_hook(self) -> None:
+ """Signal one finished data-only operation to connected clients, without a frontend rebuild."""
+ raise NotImplementedError
+
""" Properties """
@property
def running(self) -> bool:
@@ -364,7 +385,7 @@ def list_variables(self, dataset_id: int) -> List[VisorPartVariables]:
return self._scene.list_variables_for_dataset(dataset_id)
@handle_errors("update_variables")
- @notifies_scene_change
+ @notifies_data_change
def update_variables(self, dataset_id: int, variables: List[Dict[str, Any]]) -> None:
"""
Update the variables of a specific dataset in the scene.
diff --git a/src/ansys/visor/viewer/app/visor_vtk_local.py b/src/ansys/visor/viewer/app/visor_vtk_local.py
index a50dae7b..f13a3d6e 100644
--- a/src/ansys/visor/viewer/app/visor_vtk_local.py
+++ b/src/ansys/visor/viewer/app/visor_vtk_local.py
@@ -48,6 +48,7 @@ def _initialize_rendering(self, standalone: bool, trame_log_dir: str | None) ->
# structurally: the coordinator methods carry exactly the names
# and signatures the triggers call.
scene_mutation_api=self._scene,
+ get_variable_records_json=self._scene.get_variable_records_json,
pick_geometry_in_view=self._scene.pick_geometry_in_view,
pick_part_in_view=self._scene.pick_part_in_view,
)
@@ -55,3 +56,6 @@ def _initialize_rendering(self, standalone: bool, trame_log_dir: str | None) ->
def _post_scene_change_hook(self) -> None:
"""Client mode signals through LocalView.update and set_state; nothing to bump."""
+ def _post_data_change_hook(self) -> None:
+ """Client mode signals through the data-only LocalView.update the operation already pushed; nothing to bump."""
+
diff --git a/src/ansys/visor/viewer/app/visor_vtk_server.py b/src/ansys/visor/viewer/app/visor_vtk_server.py
index db646a4c..3a06e1ae 100644
--- a/src/ansys/visor/viewer/app/visor_vtk_server.py
+++ b/src/ansys/visor/viewer/app/visor_vtk_server.py
@@ -54,9 +54,14 @@ def _initialize_rendering(self, standalone: bool, trame_log_dir: str | None) ->
set_dark_mode=self._scene.set_dark_mode,
rca_window=self._scene.rca_window,
bridge=bridge,
+ get_variable_records_json=self._scene.get_variable_records_json,
)
def _post_scene_change_hook(self) -> None:
"""Bump scene_version so connected clients rebuild; requests no frame, the operation already did."""
self._state_publisher.bump_scene_version()
+ def _post_data_change_hook(self) -> None:
+ """Bump data_version so connected clients refresh in place; requests no frame, the operation already did."""
+ self._state_publisher.bump_data_version()
+
diff --git a/src/ansys/visor/viewer/models/common/visor_variable_record.py b/src/ansys/visor/viewer/models/common/visor_variable_record.py
index afd14db7..b36a154e 100644
--- a/src/ansys/visor/viewer/models/common/visor_variable_record.py
+++ b/src/ansys/visor/viewer/models/common/visor_variable_record.py
@@ -145,8 +145,7 @@ def add_part(self, part_id: int, variable: "VisorVariable") -> None:
def to_record(self, previous_record: VisorVariableRecord | None) -> VisorVariableRecord:
"""Build the record, carrying each custom slot from ``previous_record``."""
n = self.num_components
- default_magnitude = self.magnitude or (0.0, 0.0)
- default_ranges = [slot if slot is not None else (0.0, 0.0) for slot in self.components]
+ default_magnitude, default_ranges = self._default_slots()
custom_magnitude = default_magnitude
custom_ranges = list(default_ranges)
@@ -158,12 +157,34 @@ def to_record(self, previous_record: VisorVariableRecord | None) -> VisorVariabl
if k < len(old.ranges) and k < len(old.default_ranges) else default_ranges[k]
for k in range(n)
]
+ return self._record_at(custom_magnitude, custom_ranges)
+
+ def to_record_keeping_ranges(self, previous_record: VisorVariableRecord | None) -> VisorVariableRecord:
+ """Build the record, each slot keeping ``previous_record``'s effective range; a new id starts at default."""
+ default_magnitude, default_ranges = self._default_slots()
+ old = previous_record
+ if old is None:
+ return self._record_at(default_magnitude, list(default_ranges))
+ custom_ranges = [
+ tuple(old.ranges[k]) if k < len(old.ranges) else default_ranges[k]
+ for k in range(self.num_components)
+ ]
+ return self._record_at(tuple(old.magnitude_range), custom_ranges)
+
+ def _default_slots(self) -> Tuple[Range, List[Range]]:
+ """Return the widened default magnitude and component ranges, an empty slot as ``(0.0, 0.0)``."""
+ default_magnitude = self.magnitude or (0.0, 0.0)
+ default_ranges = [slot if slot is not None else (0.0, 0.0) for slot in self.components]
+ return default_magnitude, default_ranges
+ def _record_at(self, custom_magnitude: Range, custom_ranges: List[Range]) -> VisorVariableRecord:
+ """Build the record at these custom ranges over this accumulator's widened defaults."""
+ default_magnitude, default_ranges = self._default_slots()
return VisorVariableRecord(
id=self.variable_id,
array_name=self.name,
type=self.variable_type,
- num_components=n,
+ num_components=self.num_components,
part_ids=sorted(self.part_ids),
default_magnitude_range=default_magnitude,
default_ranges=default_ranges,
@@ -195,6 +216,36 @@ def from_registry(
``previous`` is never mutated.
"""
+ variables: Dict[str, VisorVariableRecord] = {}
+ for accumulator in cls._accumulate(registry).values():
+ variable_id = accumulator.variable_id
+ variables[variable_id] = accumulator.to_record(previous.variables.get(variable_id))
+ return cls(variables=variables)
+
+ @classmethod
+ def from_registry_keeping_ranges(
+ cls,
+ registry: "VisorDatasetRegistry",
+ previous: "VisorVariableRecords",
+ ) -> "VisorVariableRecords":
+ """Build a new holder from the registry; an existing id keeps its effective ranges, a new id starts at default.
+
+ Participation and default ranges are rebuilt as in :meth:`from_registry`,
+ so the defaults follow the registry's current data. Every slot of an
+ existing id takes ``previous``'s effective range as its custom range,
+ whether or not it had been edited.
+
+ ``previous`` is never mutated.
+ """
+ variables: Dict[str, VisorVariableRecord] = {}
+ for accumulator in cls._accumulate(registry).values():
+ variable_id = accumulator.variable_id
+ variables[variable_id] = accumulator.to_record_keeping_ranges(previous.variables.get(variable_id))
+ return cls(variables=variables)
+
+ @staticmethod
+ def _accumulate(registry: "VisorDatasetRegistry") -> Dict[tuple, _VariableAccumulator]:
+ """Union participation and widen default ranges per (association, name, width) key."""
accumulators: Dict[tuple, _VariableAccumulator] = {}
for dataset in list(registry.datasets.values()):
for part_variables in dataset.list_variables():
@@ -203,12 +254,7 @@ def from_registry(
if key not in accumulators:
accumulators[key] = _VariableAccumulator(*key)
accumulators[key].add_part(part_variables.part_id, variable)
-
- variables: Dict[str, VisorVariableRecord] = {}
- for accumulator in accumulators.values():
- variable_id = accumulator.variable_id
- variables[variable_id] = accumulator.to_record(previous.variables.get(variable_id))
- return cls(variables=variables)
+ return accumulators
@classmethod
def from_file(
diff --git a/src/ansys/visor/viewer/renderer/base.py b/src/ansys/visor/viewer/renderer/base.py
index f33bd3aa..3c78fa3f 100644
--- a/src/ansys/visor/viewer/renderer/base.py
+++ b/src/ansys/visor/viewer/renderer/base.py
@@ -337,4 +337,8 @@ def show_geometry_highlight(self, pick: "GeometryPick") -> None:
def render(self) -> None:
"""Trigger a render and flush to the frontend."""
+ @abstractmethod
+ def render_without_rebuild(self) -> None:
+ """Trigger a render and present it without rebuilding the client frontend."""
+
diff --git a/src/ansys/visor/viewer/renderer/local_renderer.py b/src/ansys/visor/viewer/renderer/local_renderer.py
index 0a35c175..66bcfaf9 100644
--- a/src/ansys/visor/viewer/renderer/local_renderer.py
+++ b/src/ansys/visor/viewer/renderer/local_renderer.py
@@ -228,6 +228,15 @@ def render(self) -> None:
self._local_view.update()
timer.log()
+ def render_without_rebuild(self) -> None:
+ """Render the window, then push it as data only so the wasm frontend is not rebuilt.
+
+ Renders on the calling thread, as :meth:`render` does; the push is
+ :meth:`push_without_rebuild`.
+ """
+ self._render_window.Render()
+ self.push_without_rebuild()
+
# ------------------------------------------------------------------
# Local-only: window render, wasm flush, frontend addressing
# ------------------------------------------------------------------
diff --git a/src/ansys/visor/viewer/renderer/null_renderer.py b/src/ansys/visor/viewer/renderer/null_renderer.py
index ad6dce89..ac8f24da 100644
--- a/src/ansys/visor/viewer/renderer/null_renderer.py
+++ b/src/ansys/visor/viewer/renderer/null_renderer.py
@@ -140,4 +140,7 @@ def show_geometry_highlight(self, pick: "GeometryPick") -> None:
def render(self) -> None:
pass
+ def render_without_rebuild(self) -> None:
+ """No window and no frontend; nothing to do."""
+
diff --git a/src/ansys/visor/viewer/renderer/paraview_renderer.py b/src/ansys/visor/viewer/renderer/paraview_renderer.py
index f659cf66..d3bc7c91 100644
--- a/src/ansys/visor/viewer/renderer/paraview_renderer.py
+++ b/src/ansys/visor/viewer/renderer/paraview_renderer.py
@@ -805,6 +805,10 @@ def render(self) -> None:
"""Request a frame; never renders on the calling thread."""
self._frame_requester.request_frame()
+ def render_without_rebuild(self) -> None:
+ """Request a frame, as :meth:`render` does."""
+ self.render()
+
# ------------------------------------------------------------------
# RCA render-target surface
# ------------------------------------------------------------------
diff --git a/src/ansys/visor/viewer/renderer/server_renderer.py b/src/ansys/visor/viewer/renderer/server_renderer.py
index 85e5d04c..5ba460db 100644
--- a/src/ansys/visor/viewer/renderer/server_renderer.py
+++ b/src/ansys/visor/viewer/renderer/server_renderer.py
@@ -162,6 +162,10 @@ def render(self) -> None:
"""Request a frame; never renders on the calling thread."""
self._frame_requester.request_frame()
+ def render_without_rebuild(self) -> None:
+ """Request a frame; a frame never rebuilds the client frontend."""
+ self._frame_requester.request_frame()
+
# ------------------------------------------------------------------
# VtkPipelineRenderer: publish hooks
# ------------------------------------------------------------------
diff --git a/src/ansys/visor/viewer/vtk/scene/base.py b/src/ansys/visor/viewer/vtk/scene/base.py
index a43ca79c..6a14e95e 100644
--- a/src/ansys/visor/viewer/vtk/scene/base.py
+++ b/src/ansys/visor/viewer/vtk/scene/base.py
@@ -150,10 +150,10 @@ def __init__(
self._ui_state = ui_defaults.model_copy()
# The server's variable records, keyed by composed identifier. Created once
- # here and never rebound. Written only by _rebuild_variable_records_from_registry
- # and _load_variable_records, under _vtk_lock, by assigning a new dict
- # (copy-on-write) so the unlocked reader in
- # get_scene_details never sees a dict change size. Handed out only as
+ # here and never rebound. Written only by _replace_variable_records,
+ # _load_variable_records and set_variable_range, under _vtk_lock, by assigning a new dict
+ # (copy-on-write) so the unlocked readers in get_scene_details and
+ # get_variable_records_json never see a dict change size. Handed out only as
# model_copy(deep=True): a shallow copy would share the dict and its entries.
self._variable_records = VisorVariableRecords()
@@ -414,6 +414,18 @@ def get_scene_details_json(self) -> str:
"""Return the VisorVtkPipelineState as JSON string."""
return json.dumps(self.get_scene_details().model_dump(by_alias=True))
+ def get_variable_records_json(self) -> str:
+ """Return the held variable records as JSON, keyed by composed identifier, dumped by alias.
+
+ Read without ``_vtk_lock``: every writer replaces the holder's dict whole
+ under the lock and never mutates it or its entries, so the dict read
+ here is a complete snapshot.
+ """
+ variables = self._variable_records.model_copy(deep=True).variables
+ return json.dumps(
+ {variable_id: record.model_dump(by_alias=True) for variable_id, record in variables.items()}
+ )
+
def clear(self):
"""Remove all actors from the renderer and reset the scene.
@@ -582,11 +594,13 @@ def update_variables_for_dataset(self, dataset_id: int, variables: List[VisorVar
with timer.phase("update_descendant_parts"):
dataset_node.refresh_descendant_variable_metadata(include_self=True)
- # After the reload and the metadata refresh: a width change changes the id.
- self._rebuild_variable_records_from_registry()
+ # After the reload and the metadata refresh: every existing slot keeps
+ # its effective range and the defaults follow the new data.
+ self._rebuild_variable_records_keeping_ranges()
+ # Data only: the frontend is updated in place, never rebuilt.
with timer.phase("render"):
- self.render()
+ self._renderer.render_without_rebuild()
timer.log()
@@ -594,14 +608,35 @@ def _rebuild_variable_records_from_registry(self) -> None:
"""Rebuild the held records from the registry, carrying custom ranges, then reconcile part references;
under ``_vtk_lock``.
- Used at add, remove, clear and update. Assigns a new dict to the holder
- (copy-on-write); never mutates the live dict or its entries, so the dict
- it replaces is still intact when it is handed to
- :meth:`_reconcile_part_color_variables` as the previous records.
+ Used at add, remove and clear. A slot at its default follows the new
+ default; a custom slot keeps its range.
"""
with self._vtk_lock:
- previous = self._variable_records.variables
records = VisorVariableRecords.from_registry(self._dataset_registry, self._variable_records).variables
+ self._replace_variable_records(records)
+
+ def _rebuild_variable_records_keeping_ranges(self) -> None:
+ """Rebuild the held records from the registry, every existing slot keeping its effective range, then
+ reconcile part references; under ``_vtk_lock``.
+
+ Used at update. The default ranges are recomputed from the new data.
+ """
+ with self._vtk_lock:
+ records = VisorVariableRecords.from_registry_keeping_ranges(
+ self._dataset_registry, self._variable_records
+ ).variables
+ self._replace_variable_records(records)
+
+ def _replace_variable_records(self, records: Dict[str, VisorVariableRecord]) -> None:
+ """Swap *records* into the holder, then reconcile part references against the replaced dict;
+ under ``_vtk_lock``.
+
+ Assigns a new dict to the holder (copy-on-write); never mutates the live
+ dict or its entries, so the dict it replaces is still intact when it is
+ handed to :meth:`_reconcile_part_color_variables` as the previous records.
+ """
+ with self._vtk_lock:
+ previous = self._variable_records.variables
self._variable_records.variables = records
logger.debug("variable records rebuilt from registry: %d records", len(records))
self._reconcile_part_color_variables(previous)
diff --git a/src/ansys/visor/visor-client/src/VisorFrontend.tsx b/src/ansys/visor/visor-client/src/VisorFrontend.tsx
index 8403e67e..d6c99d05 100644
--- a/src/ansys/visor/visor-client/src/VisorFrontend.tsx
+++ b/src/ansys/visor/visor-client/src/VisorFrontend.tsx
@@ -5,6 +5,7 @@ import VisorAppState from './state/appstate/VisorAppState.tsx';
import VisorDatasetState from './state/appstate/VisorDatasetState.tsx';
import VisorPartState from './state/appstate/VisorPartState.tsx';
import VisorSceneState from './state/appstate/VisorSceneState.tsx';
+import type VisorVariableState from './state/appstate/VisorVariableState.tsx';
import { TreeViewUtil } from './treeview/TreeView.tsx';
import { StateInput } from './state/appstate/VisorStateCommon.tsx';
import VisorVtkSceneNode from './state/appstate/vtkInfo/VisorVtkSceneNode.tsx';
@@ -517,6 +518,14 @@ export class VisorFrontend {
}
await renderer.resizeAsync();
};
+ this.applyVariableRecordsAsync = async (records) => {
+ variableManager.setRecords(records);
+ // setRecords fires nothing; the legend re-reads only on a refresh.
+ if (isPanelTopRightUtilSet()) {
+ const panelTopRight = await panelTopRightUtilPromise;
+ await panelTopRight.refreshSelectionAsync();
+ }
+ };
Object.freeze(this);
}
@@ -576,6 +585,8 @@ export class VisorFrontend {
setOrthographicModeAsync: (enable?: boolean) => Promise;
getAppStateAsync: (keyedByName?: boolean) => Promise;
setAppStateAsync: (state?: StateInput, updateUI?: boolean) => Promise;
+ /** Swap the held variable records and refresh the legend from them. */
+ applyVariableRecordsAsync: (records: VisorVariableState[]) => Promise;
// Selection mode
getSelectionMode: () => 'part' | 'vertex' | 'edge' | 'face';
setSelectionMode: (mode: 'part' | 'vertex' | 'edge' | 'face') => void;
diff --git a/src/ansys/visor/visor-client/src/frontend/ClientViewer.ts b/src/ansys/visor/visor-client/src/frontend/ClientViewer.ts
index 3b49d00a..2c7941b6 100644
--- a/src/ansys/visor/visor-client/src/frontend/ClientViewer.ts
+++ b/src/ansys/visor/visor-client/src/frontend/ClientViewer.ts
@@ -3,6 +3,7 @@ import VisorSceneDetails, {
SchemaVersionMismatchError,
} from '../state/appstate/VisorSceneDetails.tsx';
import VisorAppState from '../state/appstate/VisorAppState.tsx';
+import VisorVariableState from '../state/appstate/VisorVariableState.tsx';
import RemoteVtkScene from '../wasm/RemoteVtkScene';
import { WasmRenderer } from '../renderer/WasmRenderer';
import { requireWasmAnnotation } from '../renderer/RendererAnnotation';
@@ -10,6 +11,7 @@ import { attachCameraSyncReporter } from '../CameraSyncReporter';
import { buildFrontendAsync } from '../buildFrontendAsync';
import type { Trame } from '@kitware/trame/src/trame.js';
import type { VisorArgs } from '../hooks/useVisorArgs';
+import { FrontendUpdateQueue } from './FrontendUpdateQueue';
import {
CurrentFrontend,
type FrontendBuild,
@@ -30,9 +32,12 @@ class ClientFrontendBuild implements FrontendBuild {
}
}
-/** A client-mode view over the wasm scene: rebuilds on each server update and applies set_state to the current frontend. */
+/**
+ * A client-mode view over the wasm scene: rebuilds on each structural server update, refreshes the
+ * variable records in place on each data-only one, and applies set_state to the current frontend.
+ */
export class ClientViewer {
- /** Connect the wasm scene over the given session, listen for server updates and run the first build; all parameters required. */
+ /** Connect the wasm scene over the given session, listen for server updates and queue the first build; all parameters required. */
static async connectAsync(
visorArgs: VisorArgs,
trame: Trame,
@@ -49,8 +54,14 @@ export class ClientViewer {
serverOrigin,
});
const viewer = new ClientViewer(wasm, visorArgs.darkMode, onChange);
+ // Each listener is registered once for the viewer's lifetime, so an
+ // update arriving mid-rebuild is queued rather than missed.
wasm.addServerUpdatedListener(viewer.#onServerUpdated);
- await viewer.#rebuildAsync();
+ wasm.addSetStateListener(viewer.#onSetState);
+ wasm.addDataUpdatedListener(() => viewer.#queue.requestDataRefresh());
+ // Queued rather than awaited, so a data update during the first build
+ // waits for it instead of refreshing no frontend.
+ viewer.#queue.requestRebuild();
return viewer;
}
@@ -62,51 +73,63 @@ export class ClientViewer {
this.#wasm = wasm;
this.#darkMode = darkMode;
this.#current = new CurrentFrontend(onChange);
+ this.#queue = new FrontendUpdateQueue(
+ () => this.#rebuildAsync(),
+ () => this.#refreshDataAsync(),
+ (err) => console.error('[VISOR] client-mode rebuild failed', err)
+ );
}
readonly #wasm: RemoteVtkScene;
readonly #darkMode: boolean | undefined;
readonly #current: CurrentFrontend;
+ readonly #queue: FrontendUpdateQueue;
#cameraSyncRemover: (() => void) | null = null;
- readonly #onServerUpdated = () => this.#rebuildAsync();
+ readonly #onServerUpdated = () => this.#queue.requestRebuild();
readonly #onSetState = (payload: unknown) => this.#applySetStateAsync(payload);
- /** Rebuild from fresh scene details; the update and set_state listeners are registered again however it ends. */
+ /** Fetch the held variable records and apply them to the current frontend; sends nothing without one. */
+ async #refreshDataAsync(): Promise {
+ if (this.#current.frontend == null) {
+ return;
+ }
+ try {
+ const recordsJson = await this.#wasm.trameTriggerAsync('get_variable_records_json');
+ const records = VisorVariableState.listFromRecordsJson(recordsJson);
+ // Read again: the frontend may have been replaced during the fetch.
+ await this.#current.frontend?.applyVariableRecordsAsync(records);
+ } catch (err) {
+ console.error('[VISOR] variable records refresh failed', err);
+ }
+ }
+
+ /** Rebuild from fresh scene details; a schema mismatch keeps the current frontend. */
async #rebuildAsync(): Promise {
const wasm = this.#wasm;
const perfLogging = wasm.trameGetState('perf_logging') === true;
const t0 = perfLogging ? performance.now() : 0;
if (perfLogging) console.log(`[PERF] onServerUpdateAsync start`);
- wasm.clearObserversAndEventListeners();
+ const sceneDetailsJson = await wasm.trameTriggerAsync('get_visor_scene_details_json');
let newFrontend: VisorFrontend;
- // The listeners cleared above are registered again however this
- // block ends, so a failed rebuild still receives the next server
- // update, and `set_state` keeps reaching the current frontend.
try {
- const sceneDetailsJson = await wasm.trameTriggerAsync('get_visor_scene_details_json');
- try {
- newFrontend = await buildFrontendAsync(
- sceneDetailsJson,
- (sceneDetails) => this.#createRendererAsync(sceneDetails),
- wasm.trameTriggerAsync,
- this.#darkMode
- );
- } catch (err) {
- if (err instanceof SchemaVersionMismatchError) {
- this.#current.showMismatch(err);
- return;
- }
- throw err;
+ newFrontend = await buildFrontendAsync(
+ sceneDetailsJson,
+ (sceneDetails) => this.#createRendererAsync(sceneDetails),
+ wasm.trameTriggerAsync,
+ this.#darkMode
+ );
+ } catch (err) {
+ if (err instanceof SchemaVersionMismatchError) {
+ this.#current.showMismatch(err);
+ return;
}
- // Dash snapshots the frontend named here; it is written before
- // React commits the new frontend, as App writes it only after.
- (window as any).__visorState = newFrontend;
- this.#current.swapTo(new ClientFrontendBuild(newFrontend));
- } finally {
- wasm.addServerUpdatedListener(this.#onServerUpdated);
- wasm.addSetStateListener(this.#onSetState);
+ throw err;
}
+ // Dash snapshots the frontend named here; it is written before
+ // React commits the new frontend, as App writes it only after.
+ (window as any).__visorState = newFrontend;
+ this.#current.swapTo(new ClientFrontendBuild(newFrontend));
setTimeout(() => {
wasm.vtkScene.resizeAsync();
}, 100);
@@ -138,17 +161,18 @@ export class ClientViewer {
return renderer;
}
- /** Apply a set_state payload to the current frontend, the darkMode prop winning over the stored theme. */
+ /** Apply a set_state payload to the current frontend, the darkMode prop winning over the stored theme; dropped and logged with no frontend. */
async #applySetStateAsync(payload: any): Promise {
+ const frontend = this.#current.frontend;
+ if (frontend == null) {
+ console.error('[VISOR] set_state arrived before any frontend was built; dropped');
+ return;
+ }
const newAppState = new VisorAppState(payload?.appState);
if (this.#darkMode != null) {
// Explicit Dash prop takes precedence over the theme stored in saved state.
newAppState.ui.setDarkTheme(this.#darkMode);
}
- const frontend = this.#current.frontend;
- if (frontend == null) {
- throw new Error(`set_state arrived before any frontend was built`);
- }
await frontend.setAppStateAsync(newAppState, true);
}
}
diff --git a/src/ansys/visor/visor-client/src/frontend/FrontendRebuilder.ts b/src/ansys/visor/visor-client/src/frontend/FrontendRebuilder.ts
deleted file mode 100644
index e6773f32..00000000
--- a/src/ansys/visor/visor-client/src/frontend/FrontendRebuilder.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-/** Rebuilds the frontend on request, one build at a time; requests during a build collapse into one more build. */
-export class FrontendRebuilder {
- /** Rebuild with build; a rejected build goes to onError. Both required. */
- constructor(build: () => Promise, onError: (err: unknown) => void) {
- this.#build = build;
- this.#onError = onError;
- }
-
- readonly #build: () => Promise;
- readonly #onError: (err: unknown) => void;
- #building = false;
- #requested = false;
-
- /** Build now if idle, otherwise build once more after the current build. */
- request(): void {
- if (this.#building) {
- this.#requested = true;
- return;
- }
- void this.#buildAsync();
- }
-
- /** Build until no request arrived during the last build; the building flag is cleared in finally. */
- async #buildAsync(): Promise {
- this.#building = true;
- try {
- do {
- this.#requested = false;
- try {
- await this.#build();
- } catch (err) {
- this.#onError(err);
- }
- } while (this.#requested);
- } finally {
- this.#building = false;
- }
- }
-}
diff --git a/src/ansys/visor/visor-client/src/frontend/FrontendUpdateQueue.ts b/src/ansys/visor/visor-client/src/frontend/FrontendUpdateQueue.ts
new file mode 100644
index 00000000..7bc5c79e
--- /dev/null
+++ b/src/ansys/visor/visor-client/src/frontend/FrontendUpdateQueue.ts
@@ -0,0 +1,64 @@
+/** One queued unit of work: a rebuild when any merged request was a rebuild, otherwise a data refresh. */
+type PendingWork = { rebuild: boolean };
+
+/** Serializes awaited frontend rebuilds and in-place data refreshes, merging pending requests. */
+export class FrontendUpdateQueue {
+ /** Build the queue over an awaited rebuild, an awaited data refresh and an error sink; all required. */
+ constructor(
+ rebuild: () => Promise,
+ refreshData: () => Promise,
+ onError: (error: unknown) => void
+ ) {
+ this.#rebuild = rebuild;
+ this.#refreshData = refreshData;
+ this.#onError = onError;
+ }
+
+ readonly #rebuild: () => Promise;
+ readonly #refreshData: () => Promise;
+ readonly #onError: (error: unknown) => void;
+ #running = false;
+ #pending: PendingWork | null = null;
+
+ /** Request a frontend rebuild; merges with any pending request. */
+ requestRebuild(): void {
+ this.#enqueue(true);
+ }
+
+ /** Request an in-place data refresh; absorbed by a pending rebuild. */
+ requestDataRefresh(): void {
+ this.#enqueue(false);
+ }
+
+ /** Run at once when idle; otherwise OR the rebuild flag into the pending work. */
+ #enqueue(rebuild: boolean): void {
+ if (this.#running) {
+ if (this.#pending === null) {
+ this.#pending = { rebuild };
+ } else {
+ this.#pending.rebuild ||= rebuild;
+ }
+ return;
+ }
+ void this.#drainAsync({ rebuild });
+ }
+
+ /** Run work one item at a time until none is pending; a failure goes to onError and the loop continues. */
+ async #drainAsync(first: PendingWork): Promise {
+ this.#running = true;
+ try {
+ let work: PendingWork | null = first;
+ while (work !== null) {
+ try {
+ await (work.rebuild ? this.#rebuild() : this.#refreshData());
+ } catch (error) {
+ this.#onError(error);
+ }
+ work = this.#pending;
+ this.#pending = null;
+ }
+ } finally {
+ this.#running = false;
+ }
+ }
+}
diff --git a/src/ansys/visor/visor-client/src/frontend/ServerViewer.ts b/src/ansys/visor/visor-client/src/frontend/ServerViewer.ts
index 63621e6c..462bec16 100644
--- a/src/ansys/visor/visor-client/src/frontend/ServerViewer.ts
+++ b/src/ansys/visor/visor-client/src/frontend/ServerViewer.ts
@@ -5,7 +5,8 @@ import { RCA_AREA_NAME, ServerCanvas, type RcaSession } from '../rca/ServerCanva
import { ServerRenderer, type ServerStateSource } from '../renderer/ServerRenderer';
import type { TrameTriggerSender } from '../renderer/IRenderer';
import { buildFrontendAsync } from '../buildFrontendAsync';
-import { FrontendRebuilder } from './FrontendRebuilder';
+import VisorVariableState from '../state/appstate/VisorVariableState.tsx';
+import { FrontendUpdateQueue } from './FrontendUpdateQueue';
import {
CurrentFrontend,
type FrontendBuild,
@@ -15,6 +16,9 @@ import {
/** State key the server bumps after each scene change; must equal server_state_publisher.py's. */
export const SCENE_VERSION_KEY = 'scene_version';
+/** State key the server bumps after each data-only change; must equal server_state_publisher.py's. */
+export const DATA_VERSION_KEY = 'data_version';
+
/** A server-mode frontend and the renderer it was built over, released together when replaced. */
class ServerFrontendBuild implements FrontendBuild {
constructor(frontend: VisorFrontend, renderer: ServerRenderer) {
@@ -32,9 +36,12 @@ class ServerFrontendBuild implements FrontendBuild {
}
}
-/** A server-mode view over the probe's trame: streams frames and rebuilds the frontend on every scene_version change. */
+/**
+ * A server-mode view over the probe's trame: streams frames, rebuilds the frontend on every
+ * scene_version change and refreshes its variable records in place on every data_version change.
+ */
export class ServerViewer {
- /** Subscribe the canvas, watch scene_version and start the first build; all parameters required. */
+ /** Subscribe the canvas, watch scene_version and data_version and start the first build; all parameters required. */
constructor(trame: Trame, darkMode: boolean | undefined, onChange: FrontendChangeListener) {
this.#trame = trame;
this.#darkMode = darkMode;
@@ -44,12 +51,20 @@ export class ServerViewer {
// that render produces reaches the canvas.
this.#canvas = new ServerCanvas(sessionOf(trame), RCA_AREA_NAME);
this.#sender = (triggerName, payload) => trame.trigger(triggerName, [payload]);
- const rebuilder = new FrontendRebuilder(
+ const queue = new FrontendUpdateQueue(
() => this.#buildAsync(),
+ () => this.#refreshDataAsync(),
(err) => console.error('[VISOR] server-mode rebuild failed', err)
);
- // `watch` also calls back at once, which is the initial build.
- this.#unwatch = this.#state.watch([SCENE_VERSION_KEY], () => rebuilder.request());
+ // `watch` also calls back at once. scene_version is watched first, so
+ // its immediate callback starts the initial build and data_version's
+ // queues a records refresh to run after it.
+ const unwatchScene = this.#state.watch([SCENE_VERSION_KEY], () => queue.requestRebuild());
+ const unwatchData = this.#state.watch([DATA_VERSION_KEY], () => queue.requestDataRefresh());
+ this.#unwatch = () => {
+ unwatchScene();
+ unwatchData();
+ };
}
readonly #trame: Trame;
@@ -111,6 +126,21 @@ export class ServerViewer {
}
this.#current.swapTo(new ServerFrontendBuild(newFrontend, renderer));
}
+
+ /** Fetch the held variable records and apply them to the current frontend; sends nothing without one. */
+ async #refreshDataAsync(): Promise {
+ if (this.#disposed || this.#current.frontend == null) {
+ return;
+ }
+ try {
+ const recordsJson = await this.#trame.trigger('get_variable_records_json');
+ const records = VisorVariableState.listFromRecordsJson(recordsJson);
+ // Read again: the frontend may have been replaced or cleared during the fetch.
+ await this.#current.frontend?.applyVariableRecordsAsync(records);
+ } catch (err) {
+ console.error('[VISOR] variable records refresh failed', err);
+ }
+ }
}
/** The wslink session of a connected trame client. */
diff --git a/src/ansys/visor/visor-client/src/hooks/useClientVtk.ts b/src/ansys/visor/visor-client/src/hooks/useClientVtk.ts
index f17d76da..f7dc504a 100644
--- a/src/ansys/visor/visor-client/src/hooks/useClientVtk.ts
+++ b/src/ansys/visor/visor-client/src/hooks/useClientVtk.ts
@@ -11,7 +11,7 @@ export type ClientVtk = Readonly<{
schemaMismatchError: SchemaVersionMismatchError | null;
}>;
-/** Connect the wasm scene over the given session, rebuild on each server update, and apply set_state; idle while trame is null. */
+/** Connect the wasm scene over the given session, rebuild on each structural server update, refresh in place on each data-only one, and apply set_state; idle while trame is null. */
export function useClientVtk(visorArgs: VisorArgs, trame: Trame | null): ClientVtk {
const [visorFrontend, setVisorFrontend] = useState(null);
const [schemaMismatchError, setSchemaMismatchError] =
diff --git a/src/ansys/visor/visor-client/src/hooks/useServerVtk.ts b/src/ansys/visor/visor-client/src/hooks/useServerVtk.ts
index ebd151e5..fe29813c 100644
--- a/src/ansys/visor/visor-client/src/hooks/useServerVtk.ts
+++ b/src/ansys/visor/visor-client/src/hooks/useServerVtk.ts
@@ -11,7 +11,7 @@ export type ServerVtk = Readonly<{
schemaMismatchError: SchemaVersionMismatchError | null;
}>;
-/** Over the probe's session: stream frames, and rebuild the frontend on every scene_version change; idle when trame is null. */
+/** Over the probe's session: stream frames, rebuild the frontend on every scene_version change and refresh it in place on every data_version change; idle when trame is null. */
export function useServerVtk(trame: Trame | null, visorArgs: VisorArgs): ServerVtk {
const [visorFrontend, setVisorFrontend] = useState(null);
const [schemaMismatchError, setSchemaMismatchError] =
diff --git a/src/ansys/visor/visor-client/src/jest-tests/AppDarkModeOverride.test.tsx b/src/ansys/visor/visor-client/src/jest-tests/AppDarkModeOverride.test.tsx
index 9c447d98..1f1f6166 100644
--- a/src/ansys/visor/visor-client/src/jest-tests/AppDarkModeOverride.test.tsx
+++ b/src/ansys/visor/visor-client/src/jest-tests/AppDarkModeOverride.test.tsx
@@ -69,8 +69,8 @@ function mockSceneDetailsPayload() {
function mockMakeWasmView() {
return {
trameGetState: () => false,
- clearObserversAndEventListeners: () => {},
addServerUpdatedListener: () => () => {},
+ addDataUpdatedListener: () => {},
addSetStateListener: () => () => {},
trameTriggerAsync: async (name: string) =>
name === 'get_visor_scene_details_json' ? mockSceneDetailsPayload() : undefined,
diff --git a/src/ansys/visor/visor-client/src/jest-tests/AppSchemaMismatch.test.tsx b/src/ansys/visor/visor-client/src/jest-tests/AppSchemaMismatch.test.tsx
index dc18c222..7e4a1061 100644
--- a/src/ansys/visor/visor-client/src/jest-tests/AppSchemaMismatch.test.tsx
+++ b/src/ansys/visor/visor-client/src/jest-tests/AppSchemaMismatch.test.tsx
@@ -32,8 +32,8 @@ jest.mock('../hooks/useRenderingMode', () => ({
function mockMakeWasmView() {
return {
trameGetState: () => false,
- clearObserversAndEventListeners: () => {},
addServerUpdatedListener: () => () => {},
+ addDataUpdatedListener: () => {},
addSetStateListener: () => () => {},
trameTriggerAsync: async (name: string) =>
name === 'get_visor_scene_details_json' ? { schemaVersion: 3 } : undefined,
diff --git a/src/ansys/visor/visor-client/src/jest-tests/FrontendRebuilder.test.ts b/src/ansys/visor/visor-client/src/jest-tests/FrontendRebuilder.test.ts
deleted file mode 100644
index a328341a..00000000
--- a/src/ansys/visor/visor-client/src/jest-tests/FrontendRebuilder.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { FrontendRebuilder } from '../frontend/FrontendRebuilder';
-
-/**
- * The rebuilder runs one build at a time: requests made during a build
- * collapse into one more build, and a rejected build neither stops nor
- * wedges it.
- *
- * Expected values are hand-written literals.
- */
-
-/** Let every pending promise callback run. */
-async function settle(): Promise {
- await new Promise((resolve) => setTimeout(resolve, 0));
-}
-
-describe('FrontendRebuilder', () => {
- test('requests during a held build collapse into one more build', async () => {
- let releaseFirst: () => void = () => {};
- const firstBuild = new Promise((resolve) => {
- releaseFirst = resolve;
- });
- let builds = 0;
- const rebuilder = new FrontendRebuilder(async () => {
- builds += 1;
- if (builds === 1) {
- await firstBuild;
- }
- }, jest.fn());
-
- rebuilder.request();
- rebuilder.request();
- rebuilder.request();
- rebuilder.request();
- releaseFirst();
- await settle();
-
- expect(builds).toBe(2);
- });
-
- test('a rejected build is reported and the next request still builds', async () => {
- const failure = new Error('build failed');
- let builds = 0;
- const onError = jest.fn();
- const rebuilder = new FrontendRebuilder(async () => {
- builds += 1;
- if (builds === 1) {
- throw failure;
- }
- }, onError);
-
- rebuilder.request();
- await settle();
- rebuilder.request();
- await settle();
-
- expect(onError.mock.calls).toStrictEqual([[failure]]);
- expect(builds).toBe(2);
- });
-});
diff --git a/src/ansys/visor/visor-client/src/jest-tests/FrontendUpdateQueue.test.ts b/src/ansys/visor/visor-client/src/jest-tests/FrontendUpdateQueue.test.ts
new file mode 100644
index 00000000..7ef780d2
--- /dev/null
+++ b/src/ansys/visor/visor-client/src/jest-tests/FrontendUpdateQueue.test.ts
@@ -0,0 +1,126 @@
+import { FrontendUpdateQueue } from '../frontend/FrontendUpdateQueue';
+
+/**
+ * The queue runs one rebuild or data refresh at a time. Requests made while
+ * one runs merge into one pending item, which is a rebuild if any merged
+ * request was; a refresh requested while a rebuild runs still runs after it,
+ * whether that rebuild fulfilled or rejected.
+ *
+ * Expected values are hand-written literals.
+ */
+
+/** Let every pending promise callback run. */
+async function settle(): Promise {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+/** A promise the test settles, with its resolve and reject. */
+function held(): { promise: Promise; resolve: () => void; reject: (e: unknown) => void } {
+ let resolve: () => void = () => {};
+ let reject: (e: unknown) => void = () => {};
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+describe('FrontendUpdateQueue', () => {
+ test('requests during a held build collapse into one more build', async () => {
+ const firstBuild = held();
+ let builds = 0;
+ const queue = new FrontendUpdateQueue(
+ async () => {
+ builds += 1;
+ if (builds === 1) {
+ await firstBuild.promise;
+ }
+ },
+ async () => {},
+ jest.fn()
+ );
+
+ queue.requestRebuild();
+ queue.requestRebuild();
+ queue.requestRebuild();
+ queue.requestRebuild();
+ firstBuild.resolve();
+ await settle();
+
+ expect(builds).toBe(2);
+ });
+
+ test('a rejected build is reported and the next request still builds', async () => {
+ const failure = new Error('build failed');
+ let builds = 0;
+ const onError = jest.fn();
+ const queue = new FrontendUpdateQueue(
+ async () => {
+ builds += 1;
+ if (builds === 1) {
+ throw failure;
+ }
+ },
+ async () => {},
+ onError
+ );
+
+ queue.requestRebuild();
+ await settle();
+ queue.requestRebuild();
+ await settle();
+
+ expect(onError.mock.calls).toStrictEqual([[failure]]);
+ expect(builds).toBe(2);
+ });
+
+ test('a pending rebuild absorbs a refresh requested before it starts', async () => {
+ const firstBuild = held();
+ const record: string[] = [];
+ const queue = new FrontendUpdateQueue(
+ async () => {
+ record.push('rebuild');
+ if (record.length === 1) {
+ await firstBuild.promise;
+ }
+ },
+ async () => {
+ record.push('refresh');
+ },
+ jest.fn()
+ );
+
+ queue.requestRebuild();
+ queue.requestDataRefresh();
+ queue.requestRebuild();
+ firstBuild.resolve();
+ await settle();
+
+ expect(record).toEqual(['rebuild', 'rebuild']);
+ });
+
+ test('a refresh requested during a failed rebuild runs after it', async () => {
+ const build = held();
+ const record: string[] = [];
+ const queue = new FrontendUpdateQueue(
+ async () => {
+ record.push('rebuild');
+ await build.promise;
+ },
+ async () => {
+ record.push('refresh');
+ },
+ jest.fn()
+ );
+
+ queue.requestRebuild();
+ queue.requestDataRefresh();
+ await settle();
+ expect(record).toEqual(['rebuild']);
+
+ build.reject(new Error('build failed'));
+ await settle();
+
+ expect(record).toEqual(['rebuild', 'refresh']);
+ });
+});
diff --git a/src/ansys/visor/visor-client/src/jest-tests/SerialUpdateQueue.test.ts b/src/ansys/visor/visor-client/src/jest-tests/SerialUpdateQueue.test.ts
index 37c7029d..7e9f869e 100644
--- a/src/ansys/visor/visor-client/src/jest-tests/SerialUpdateQueue.test.ts
+++ b/src/ansys/visor/visor-client/src/jest-tests/SerialUpdateQueue.test.ts
@@ -4,10 +4,12 @@ import { SerialUpdateQueue } from '../wasm/SerialUpdateQueue';
* Server updates run one at a time. Updates arriving while one runs merge
* into one pending update, which keeps the latest options and rebuilds if any
* arrival was structural. A failed update never rebuilds and never blocks
- * the next one.
+ * the next one. A fulfilled update that does not rebuild fires the data
+ * listener instead.
*
* The fake apply records `start:` and is held on a promise the test
- * settles; the fake rebuild records `rebuild`. Expected records are literals.
+ * settles; the fake rebuild records `rebuild` and the fake data listener
+ * `data`. Expected records are literals.
*/
type Update = Readonly<{ tag: string; dataOnly?: boolean }>;
@@ -23,6 +25,9 @@ function makeQueue() {
},
() => {
record.push('rebuild');
+ },
+ () => {
+ record.push('data');
}
);
return { record, held, queue };
@@ -86,7 +91,7 @@ describe('SerialUpdateQueue', () => {
held[1].resolve();
await flushAsync();
- expect(record).toEqual(['start:A', 'start:D']);
+ expect(record).toEqual(['start:A', 'data', 'start:D', 'data']);
});
test('merged update rebuilds once when any arrival was structural', async () => {
@@ -98,11 +103,11 @@ describe('SerialUpdateQueue', () => {
queue.run({ tag: 'D', dataOnly: true });
held[0].resolve();
await flushAsync();
- expect(record).toEqual(['start:A', 'start:D']);
+ expect(record).toEqual(['start:A', 'data', 'start:D']);
held[1].resolve();
await flushAsync();
- expect(record).toEqual(['start:A', 'start:D', 'rebuild']);
+ expect(record).toEqual(['start:A', 'data', 'start:D', 'rebuild']);
});
test('an arrival after the pending update started waits for it', async () => {
@@ -114,10 +119,10 @@ describe('SerialUpdateQueue', () => {
await flushAsync();
queue.run({ tag: 'E', dataOnly: true });
await flushAsync();
- expect(record).toEqual(['start:A', 'start:B']);
+ expect(record).toEqual(['start:A', 'data', 'start:B']);
held[1].resolve();
await flushAsync();
- expect(record).toEqual(['start:A', 'start:B', 'start:E']);
+ expect(record).toEqual(['start:A', 'data', 'start:B', 'data', 'start:E']);
});
});
diff --git a/src/ansys/visor/visor-client/src/jest-tests/UseClientVtkCameraSync.test.tsx b/src/ansys/visor/visor-client/src/jest-tests/UseClientVtkCameraSync.test.tsx
index 7238ed63..1068b88c 100644
--- a/src/ansys/visor/visor-client/src/jest-tests/UseClientVtkCameraSync.test.tsx
+++ b/src/ansys/visor/visor-client/src/jest-tests/UseClientVtkCameraSync.test.tsx
@@ -19,7 +19,7 @@ import type { CameraOrigin, VisorCameraState } from '../renderer/IRenderer';
const mockScene = {
settledListeners: new Map<() => void, (origin: CameraOrigin) => void>(),
- serverUpdated: null as null | (() => Promise),
+ serverUpdated: null as null | (() => void),
trameTriggerAsync: jest.fn(),
renderersBuilt: 0,
settleDuringFirstSeed: false,
@@ -80,11 +80,11 @@ function mockSceneDetailsPayload() {
function mockMakeWasmView() {
return {
trameGetState: () => false,
- clearObserversAndEventListeners: () => {},
- addServerUpdatedListener: (handler: () => Promise) => {
+ addServerUpdatedListener: (handler: () => void) => {
mockScene.serverUpdated = handler;
return () => {};
},
+ addDataUpdatedListener: () => {},
addSetStateListener: () => () => {},
trameTriggerAsync: mockScene.trameTriggerAsync,
vtkScene: { resizeAsync: async () => undefined },
@@ -174,11 +174,14 @@ describe('useClientVtk camera sync', () => {
test('one gesture settle after two rebuilds sends one sync_camera', async () => {
const { result } = renderHook(() => useClientVtk(ARGS, TRAME));
await waitFor(() => expect(result.current.visorFrontend).not.toBeNull());
+ // The listener only queues the rebuild; drain lets each one finish.
await act(async () => {
- await mockScene.serverUpdated!();
+ mockScene.serverUpdated!();
+ await drain();
});
await act(async () => {
- await mockScene.serverUpdated!();
+ mockScene.serverUpdated!();
+ await drain();
});
await act(async () => {
diff --git a/src/ansys/visor/visor-client/src/jest-tests/UseClientVtkRebuild.test.tsx b/src/ansys/visor/visor-client/src/jest-tests/UseClientVtkRebuild.test.tsx
index 086ff057..0b9b1845 100644
--- a/src/ansys/visor/visor-client/src/jest-tests/UseClientVtkRebuild.test.tsx
+++ b/src/ansys/visor/visor-client/src/jest-tests/UseClientVtkRebuild.test.tsx
@@ -4,18 +4,27 @@ import type { VisorArgs } from '../hooks/useVisorArgs';
import type { Trame } from '@kitware/trame/src/trame.js';
/**
- * In client mode every server update rebuilds the frontend over the same wasm
- * scene. A successful rebuild releases the replaced frontend and names the new
+ * In client mode every structural server update rebuilds the frontend over the
+ * same wasm scene, and a data-only update fetches the variable records and keeps
+ * it. A successful rebuild releases the replaced frontend and names the new
* one on `window.__visorState`; a schema mismatch keeps the current frontend
* and reports the error. The scene connects over the session the hook is given.
+ * A structural update arriving while a rebuild runs builds once more.
+ *
+ * The scene double keeps every registration of a server-updated listener under
+ * its own remover, as the real scene does, and a details fetch can be held on a
+ * gate the test opens.
*
* Expected values are hand-written literals.
*/
const mockScene = {
- serverUpdated: null as null | (() => Promise),
+ serverUpdatedListeners: new Map<() => void, () => void>(),
+ dataUpdated: null as null | (() => void),
+ detailsGate: Promise.resolve() as Promise,
payloads: [] as unknown[],
fetches: 0,
+ recordsFetches: 0,
renderers: [] as { liveCanvasClicks: Set<() => void> }[],
configs: [] as { trame?: unknown }[],
};
@@ -69,20 +78,33 @@ function mockSceneDetailsPayload() {
};
}
-/** The client-mode scene connection: keeps the latest server-updated listener and answers each fetch in turn. */
+/** The client-mode scene connection: keeps every listener, answers each details fetch in turn after the gate and counts records fetches. */
function mockMakeWasmView() {
return {
trameGetState: () => false,
- clearObserversAndEventListeners: () => {},
- addServerUpdatedListener: (handler: () => Promise) => {
- mockScene.serverUpdated = handler;
- return () => {};
+ addServerUpdatedListener: (handler: () => void) => {
+ const remover = () => {
+ mockScene.serverUpdatedListeners.delete(remover);
+ };
+ mockScene.serverUpdatedListeners.set(remover, handler);
+ return remover;
+ },
+ addDataUpdatedListener: (listener: () => void) => {
+ mockScene.dataUpdated = listener;
},
addSetStateListener: () => () => {},
- trameTriggerAsync: async (name: string) =>
- name === 'get_visor_scene_details_json'
- ? mockScene.payloads[mockScene.fetches++]
- : undefined,
+ trameTriggerAsync: async (name: string) => {
+ if (name === 'get_visor_scene_details_json') {
+ const payload = mockScene.payloads[mockScene.fetches++];
+ await mockScene.detailsGate;
+ return payload;
+ }
+ if (name === 'get_variable_records_json') {
+ mockScene.recordsFetches++;
+ return '{}';
+ }
+ return undefined;
+ },
vtkScene: { resizeAsync: async () => undefined },
};
}
@@ -125,17 +147,33 @@ async function mountBuiltAsync() {
return hook;
}
-/** Deliver one server update and let its rebuild finish. */
+/** Let every pending promise chain, including a queued rebuild or refresh, run out. */
+async function drain() {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+/** Call every server-updated listener still registered, as the scene does after a structural update. */
+function fireServerUpdated() {
+ for (const listener of [...mockScene.serverUpdatedListeners.values()]) {
+ listener();
+ }
+}
+
+/** Deliver one server update and let its queued rebuild finish. */
async function serverUpdateAsync() {
await act(async () => {
- await mockScene.serverUpdated!();
+ fireServerUpdated();
+ await drain();
});
}
beforeEach(() => {
- mockScene.serverUpdated = null;
+ mockScene.serverUpdatedListeners.clear();
+ mockScene.dataUpdated = null;
+ mockScene.detailsGate = Promise.resolve();
mockScene.payloads = [];
mockScene.fetches = 0;
+ mockScene.recordsFetches = 0;
mockScene.renderers = [];
mockScene.configs = [];
});
@@ -158,10 +196,34 @@ describe('useClientVtk rebuild', () => {
await serverUpdateAsync();
+ expect(mockScene.fetches).toBe(2);
expect(mockScene.renderers.length).toBe(2);
expect(mockScene.renderers[0].liveCanvasClicks.size).toBe(0);
});
+ test('a server update during a rebuild builds once more', async () => {
+ mockScene.payloads = [mockSceneDetailsPayload(), mockSceneDetailsPayload()];
+ let openGate: () => void = () => {};
+ mockScene.detailsGate = new Promise((resolve) => {
+ openGate = resolve;
+ });
+ const { result } = renderHook(() => useClientVtk(ARGS, TRAME));
+ await waitFor(() => expect(mockScene.fetches).toBe(1));
+
+ await act(async () => {
+ fireServerUpdated();
+ openGate();
+ await drain();
+ });
+ await waitFor(() => expect(result.current.visorFrontend).not.toBeNull());
+ await act(async () => {
+ await drain();
+ });
+
+ expect(mockScene.fetches).toBe(2);
+ expect(mockScene.renderers.length).toBe(2);
+ });
+
test('a mismatch on client rebuild sets schemaMismatchError and keeps the frontend', async () => {
mockScene.payloads = [mockSceneDetailsPayload(), { schemaVersion: 3 }];
const { result } = await mountBuiltAsync();
@@ -183,4 +245,19 @@ describe('useClientVtk rebuild', () => {
expect(result.current.visorFrontend).not.toBe(first);
expect((window as any).__visorState).toBe(result.current.visorFrontend);
});
+
+ test('a data update fetches the records and does not rebuild', async () => {
+ mockScene.payloads = [mockSceneDetailsPayload()];
+ const { result } = await mountBuiltAsync();
+ const first = result.current.visorFrontend;
+
+ await act(async () => {
+ mockScene.dataUpdated!();
+ await drain();
+ });
+
+ expect(mockScene.recordsFetches).toBe(1);
+ expect(mockScene.fetches).toBe(1);
+ expect(result.current.visorFrontend).toBe(first);
+ });
});
diff --git a/src/ansys/visor/visor-client/src/jest-tests/UseServerVtkBuild.test.tsx b/src/ansys/visor/visor-client/src/jest-tests/UseServerVtkBuild.test.tsx
index c9d23a25..7e80f121 100644
--- a/src/ansys/visor/visor-client/src/jest-tests/UseServerVtkBuild.test.tsx
+++ b/src/ansys/visor/visor-client/src/jest-tests/UseServerVtkBuild.test.tsx
@@ -33,9 +33,12 @@ function sceneDetailsPayload() {
};
}
-const trigger = jest.fn(async (name: string, ..._args: unknown[]) =>
- name === 'get_visor_scene_details_json' ? sceneDetailsPayload() : undefined
-);
+const trigger = jest.fn(async (name: string, ..._args: unknown[]) => {
+ if (name === 'get_variable_records_json') {
+ return '{}';
+ }
+ return name === 'get_visor_scene_details_json' ? sceneDetailsPayload() : undefined;
+});
const session = {
subscribe: () => ({ unsubscribe: () => {} }),
call: async () => undefined,
diff --git a/src/ansys/visor/visor-client/src/jest-tests/UseServerVtkRebuild.test.tsx b/src/ansys/visor/visor-client/src/jest-tests/UseServerVtkRebuild.test.tsx
index 046ddd05..348f89bf 100644
--- a/src/ansys/visor/visor-client/src/jest-tests/UseServerVtkRebuild.test.tsx
+++ b/src/ansys/visor/visor-client/src/jest-tests/UseServerVtkRebuild.test.tsx
@@ -6,7 +6,8 @@ import type { VisorArgs } from '../hooks/useVisorArgs';
/**
* In server mode every change of scene_version rebuilds the frontend from
* freshly fetched scene details, one build at a time, and the replaced
- * build's renderer stops listening.
+ * build's renderer stops listening. A change of data_version only fetches
+ * the variable records and keeps the frontend.
*
* Expected values are hand-written literals.
*/
@@ -96,6 +97,10 @@ async function answerFetchAsync(n: number, payload: unknown): Promise {
});
}
+function recordsFetchCount(): number {
+ return triggerNames.filter((name) => name === 'get_variable_records_json').length;
+}
+
const globals = globalThis as unknown as { ResizeObserver: unknown; fetch: unknown };
let originalResizeObserver: unknown;
let originalFetch: unknown;
@@ -109,6 +114,9 @@ beforeEach(() => {
state,
trigger: async (name: string) => {
triggerNames.push(name);
+ if (name === 'get_variable_records_json') {
+ return '{}';
+ }
if (name !== 'get_visor_scene_details_json') {
return undefined;
}
@@ -160,6 +168,41 @@ describe('useServerVtk rebuild', () => {
expect(state.liveWatchers('server_camera_state')).toBe(1);
});
+ test('a data_version change fetches the records and does not rebuild', async () => {
+ const { result } = renderHook(() => useServerVtk(trame, argsWith(undefined)));
+ await answerFetchAsync(0, sceneDetailsPayload());
+ await waitFor(() => expect(result.current.visorFrontend).not.toBeNull());
+ const first = result.current.visorFrontend;
+ // The watch calls back at once, so one refresh follows the first build.
+ await waitFor(() => expect(recordsFetchCount()).toBe(1));
+
+ act(() => state.notify('data_version'));
+ await waitFor(() => expect(recordsFetchCount()).toBe(2));
+
+ expect(fetchAnswers.length).toBe(1);
+ expect(result.current.visorFrontend).toBe(first);
+ });
+
+ test('data_version and scene_version changed together build once more', async () => {
+ const { result } = renderHook(() => useServerVtk(trame, argsWith(undefined)));
+ await answerFetchAsync(0, sceneDetailsPayload());
+ await waitFor(() => expect(result.current.visorFrontend).not.toBeNull());
+ const first = result.current.visorFrontend;
+ await waitFor(() => expect(recordsFetchCount()).toBe(1));
+
+ act(() => {
+ state.notify('data_version');
+ state.notify('scene_version');
+ });
+ await answerFetchAsync(1, sceneDetailsPayload());
+ await waitFor(() => expect(result.current.visorFrontend).not.toBe(first));
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+ expect(fetchAnswers.length).toBe(2);
+ });
+
test('a mismatch on rebuild sets schemaMismatchError and keeps the frontend', async () => {
const { result } = renderHook(() => useServerVtk(trame, argsWith(undefined)));
await answerFetchAsync(0, sceneDetailsPayload());
diff --git a/src/ansys/visor/visor-client/src/jest-tests/VariableRecordProjection.test.tsx b/src/ansys/visor/visor-client/src/jest-tests/VariableRecordProjection.test.tsx
index 5901559d..dc352e34 100644
--- a/src/ansys/visor/visor-client/src/jest-tests/VariableRecordProjection.test.tsx
+++ b/src/ansys/visor/visor-client/src/jest-tests/VariableRecordProjection.test.tsx
@@ -604,6 +604,45 @@ describe('the legend follows a delivery with no selection change', () => {
});
});
+describe('an in-place records apply', () => {
+ /** The server's records payload holding one pressure record with a new default range. */
+ function recordsWithNewDefault(): VisorVariableState[] {
+ return VisorVariableState.listFromRecordsJson(
+ JSON.stringify({ [PRESSURE_ID]: pressureRecord({ defaultMagnitudeRange: [-1, 12] }) })
+ );
+ }
+
+ test('the held record takes the applied default range', async () => {
+ const { frontend } = await mountOnDeliveredRecord(pressureRecord(), PRESSURE_ID, -1);
+
+ await act(async () => {
+ await frontend.applyVariableRecordsAsync(recordsWithNewDefault());
+ });
+
+ expect(
+ frontend.globalVariableCollection.getVariable(PRESSURE_ID)!.getRangeInfo(-1)
+ ).toEqual({ defaultRange: [-1, 12], customRange: [2, 8] });
+ });
+
+ test('reset shows the applied default range', async () => {
+ const { frontend, container } = await mountOnDeliveredRecord(
+ pressureRecord(),
+ PRESSURE_ID,
+ -1
+ );
+
+ await act(async () => {
+ await frontend.applyVariableRecordsAsync(recordsWithNewDefault());
+ });
+ const minRow = legendRow(container, 'Min');
+ await act(async () => {
+ fireEvent.click(minRow.reset);
+ });
+
+ expect(minRow.input.value).toBe('-1');
+ });
+});
+
describe('the range trigger is sent for an edit and never for a delivery', () => {
test('an apply click on the magnitude sends one set_variable_range with component -1', async () => {
const { container, triggerSender } = await mountOnDeliveredRecord(
diff --git a/src/ansys/visor/visor-client/src/state/appstate/VisorVariableState.tsx b/src/ansys/visor/visor-client/src/state/appstate/VisorVariableState.tsx
index f573199b..a448022f 100644
--- a/src/ansys/visor/visor-client/src/state/appstate/VisorVariableState.tsx
+++ b/src/ansys/visor/visor-client/src/state/appstate/VisorVariableState.tsx
@@ -27,6 +27,15 @@ export default class VisorVariableState {
this.copy(state, false, key);
}
+ /** Parse a records payload keyed by composed id; a key differing from its record's id throws. */
+ static listFromRecordsJson(payload: StateInput): VisorVariableState[] {
+ const data = parseState(payload);
+ if (data == null) {
+ throw new Error(`variable records payload is empty`);
+ }
+ return Object.entries(data).map(([key, record]) => new VisorVariableState(record, key));
+ }
+
get id(): string {
return this._id;
}
diff --git a/src/ansys/visor/visor-client/src/wasm/RemoteVtkScene.js b/src/ansys/visor/visor-client/src/wasm/RemoteVtkScene.js
index 3297a240..15cffc59 100644
--- a/src/ansys/visor/visor-client/src/wasm/RemoteVtkScene.js
+++ b/src/ansys/visor/visor-client/src/wasm/RemoteVtkScene.js
@@ -442,13 +442,23 @@ export default class RemoteVtkScene {
callback();
}
};
+ /**
+ * Call every data-updated listener once.
+ * @return {void}
+ */
+ #fireDataUpdated = () => {
+ for (const callback of this.#dataUpdatedListeners) {
+ callback();
+ }
+ };
/**
* Serial queue every server update runs through.
* @type{SerialUpdateQueue}
*/
#updates = new SerialUpdateQueue(
(bindCanvas) => this.#applyUpdateAsync(bindCanvas),
- () => this.#fireServerUpdated()
+ () => this.#fireServerUpdated(),
+ () => this.#fireDataUpdated()
);
/**
* @param {string} name
@@ -485,22 +495,15 @@ export default class RemoteVtkScene {
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
- /**@type{Mapvoid>}*/
- #userObserverRemovers = new Map();
/**@type{Mapvoid>}*/
#serverUpdatedListeners = new Map();
/**@type{Mapvoid>}*/
#setStateListeners = new Map();
/**
- * @return {void}
+ * Never emptied, so a data update arriving during a rebuild still reaches its listener.
+ * @type{(()=>void)[]}
*/
- clearObserversAndEventListeners = () => {
- for (const remover of this.#userObserverRemovers.values()) {
- remover();
- }
- this.#serverUpdatedListeners.clear();
- this.#setStateListeners.clear();
- };
+ #dataUpdatedListeners = [];
/**
* @param {()=>void} handler
* @return {()=>void}
@@ -519,4 +522,12 @@ export default class RemoteVtkScene {
this.#setStateListeners.set(remover, handler);
return remover;
};
+ /**
+ * Register a listener fired after a fulfilled data-only (dataOnly=true) update.
+ * @param {()=>void} listener
+ * @return {void}
+ */
+ addDataUpdatedListener = (listener) => {
+ this.#dataUpdatedListeners.push(listener);
+ };
}
diff --git a/src/ansys/visor/visor-client/src/wasm/SerialUpdateQueue.ts b/src/ansys/visor/visor-client/src/wasm/SerialUpdateQueue.ts
index f74c875f..94d2dfb2 100644
--- a/src/ansys/visor/visor-client/src/wasm/SerialUpdateQueue.ts
+++ b/src/ansys/visor/visor-client/src/wasm/SerialUpdateQueue.ts
@@ -49,14 +49,20 @@ class PendingUpdate {
/** Applies server updates one at a time; updates arriving while one runs merge into a single pending update. */
export class SerialUpdateQueue {
readonly #applyWasmAsync: (bindCanvas: unknown) => Promise;
- readonly #rebuild: () => void;
+ readonly #serverUpdated: () => void;
+ readonly #dataUpdated: () => void;
#running: Promise | null = null;
#pending: PendingUpdate | null = null;
- /** applyAsync applies one wasm update; rebuild fires the server-updated listeners once. */
- constructor(applyAsync: (bindCanvas: unknown) => Promise, rebuild: () => void) {
+ /** Serial wasm update queue; fires serverUpdated after a rebuilding apply and dataUpdated after a data-only one. */
+ constructor(
+ applyAsync: (bindCanvas: unknown) => Promise,
+ serverUpdated: () => void,
+ dataUpdated: () => void
+ ) {
this.#applyWasmAsync = applyAsync;
- this.#rebuild = rebuild;
+ this.#serverUpdated = serverUpdated;
+ this.#dataUpdated = dataUpdated;
}
/** Starts at once on an idle queue; otherwise merges into the pending update; returns that update's promise. */
@@ -74,11 +80,13 @@ export class SerialUpdateQueue {
return this.#pending.promise;
}
- /** Apply one update; rebuild once if its flag is set and the apply fulfilled. */
+ /** Apply one update; once it fulfils, fire serverUpdated if its flag is set, dataUpdated otherwise. */
async #applyAsync(update: PendingUpdate): Promise {
await this.#applyWasmAsync(update.bindCanvas);
if (update.rebuildsFrontend) {
- this.#rebuild();
+ this.#serverUpdated();
+ } else {
+ this.#dataUpdated();
}
}
diff --git a/tests/unit/app/test_local_app.py b/tests/unit/app/test_local_app.py
index 468064ad..6d481a40 100644
--- a/tests/unit/app/test_local_app.py
+++ b/tests/unit/app/test_local_app.py
@@ -111,6 +111,7 @@ def app(mock_server, api):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
scene_mutation_api=api,
pick_geometry_in_view=MagicMock(),
@@ -124,6 +125,7 @@ def app_without_api(mock_server):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
diff --git a/tests/unit/app/test_local_app_set_projection.py b/tests/unit/app/test_local_app_set_projection.py
index 1a3af18b..23c611d1 100644
--- a/tests/unit/app/test_local_app_set_projection.py
+++ b/tests/unit/app/test_local_app_set_projection.py
@@ -82,6 +82,7 @@ def app(mock_server, api):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
scene_mutation_api=api,
pick_geometry_in_view=MagicMock(),
@@ -95,6 +96,7 @@ def app_without_api(mock_server):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
diff --git a/tests/unit/app/test_local_app_sync_camera.py b/tests/unit/app/test_local_app_sync_camera.py
index 38ca992f..ea711939 100644
--- a/tests/unit/app/test_local_app_sync_camera.py
+++ b/tests/unit/app/test_local_app_sync_camera.py
@@ -101,6 +101,7 @@ def app(mock_server, api):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
scene_mutation_api=api,
pick_geometry_in_view=MagicMock(),
@@ -114,6 +115,7 @@ def app_without_api(mock_server):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
diff --git a/tests/unit/app/test_local_app_sync_cross_section_plane.py b/tests/unit/app/test_local_app_sync_cross_section_plane.py
index cdfb159c..5f42f78c 100644
--- a/tests/unit/app/test_local_app_sync_cross_section_plane.py
+++ b/tests/unit/app/test_local_app_sync_cross_section_plane.py
@@ -78,6 +78,7 @@ def app(mock_server, api):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
scene_mutation_api=api,
pick_geometry_in_view=MagicMock(),
diff --git a/tests/unit/app/test_local_app_ui_panel_triggers.py b/tests/unit/app/test_local_app_ui_panel_triggers.py
index d82bf7f3..f2274b9f 100644
--- a/tests/unit/app/test_local_app_ui_panel_triggers.py
+++ b/tests/unit/app/test_local_app_ui_panel_triggers.py
@@ -83,6 +83,7 @@ def app(mock_server, api):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
scene_mutation_api=api,
pick_geometry_in_view=MagicMock(),
diff --git a/tests/unit/app/test_local_app_widget_triggers.py b/tests/unit/app/test_local_app_widget_triggers.py
index 385eb5bd..fb476e17 100644
--- a/tests/unit/app/test_local_app_widget_triggers.py
+++ b/tests/unit/app/test_local_app_widget_triggers.py
@@ -78,6 +78,7 @@ def app(mock_server, api):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
scene_mutation_api=api,
pick_geometry_in_view=MagicMock(),
@@ -91,6 +92,7 @@ def app_without_api(mock_server):
return LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
diff --git a/tests/unit/app/test_paraview_app.py b/tests/unit/app/test_paraview_app.py
index 765fd050..12feeb48 100644
--- a/tests/unit/app/test_paraview_app.py
+++ b/tests/unit/app/test_paraview_app.py
@@ -17,11 +17,12 @@
from ansys.visor.viewer.app.trame.paraview_app import ParaviewApp
from ansys.visor.viewer.core.visor_enums import RenderingMode
-# The exact 24 trigger names, each registered once. Written out by hand, not
+# The exact 25 trigger names, each registered once. Written out by hand, not
# derived from the production trigger list.
PARAVIEW_APP_TRIGGER_NAMES = sorted(
[
"get_visor_scene_details_json",
+ "get_variable_records_json",
"set_part_visibility",
"set_part_opacity",
"set_part_diffuse_color",
@@ -86,6 +87,7 @@ def _build(mock_server, rca_window=None, bridge=None):
return ParaviewApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
trame_logger=None,
scene_mutation_api=MagicMock(),
@@ -98,7 +100,7 @@ def _build(mock_server, rca_window=None, bridge=None):
def test_paraview_app_registers_each_trigger_once(mock_server, area_cls):
- """The registered trigger names are exactly the hand-written 24, none twice."""
+ """The registered trigger names are exactly the hand-written 25, none twice."""
_build(mock_server)
names = sorted(call.args[0] for call in mock_server.trigger.call_args_list)
diff --git a/tests/unit/app/test_scene_trigger_app.py b/tests/unit/app/test_scene_trigger_app.py
index 217be965..59ea017e 100644
--- a/tests/unit/app/test_scene_trigger_app.py
+++ b/tests/unit/app/test_scene_trigger_app.py
@@ -2,7 +2,7 @@
Coverage targets
----------------
-1. ``LocalApp`` registers exactly these 26 trigger names: the 21 shared ones
+1. ``LocalApp`` registers exactly these 27 trigger names: the 22 shared ones
defined on ``SceneTriggerApp`` plus its own five local-only ones.
Neither a missing nor a doubled registration passes this.
2. ``LocalApp`` seeds ``rendering_mode`` into server state as ``"client"``
@@ -30,13 +30,14 @@
from ansys.visor.viewer.models.runtime.picking.geometry_pick import EdgePick
from ansys.visor.viewer.vtk.picking.part_cell_hit import PickView
-# The exact 26 trigger names LocalApp registers: the 21 names shared with
+# The exact 27 trigger names LocalApp registers: the 22 names shared with
# every rendering mode, plus LocalApp's own five local-only ones. Written
# out by hand, not derived from the production trigger list, so a missing or
# a doubled registration fails this rather than following along.
LOCAL_APP_TRIGGER_NAMES = sorted(
[
"get_visor_scene_details_json",
+ "get_variable_records_json",
"set_part_visibility",
"set_part_opacity",
"set_part_diffuse_color",
@@ -96,7 +97,7 @@ def mock_server():
def test_local_app_registers_exactly_these_triggers(mock_server):
- """The registered trigger names are exactly the hand-written 26, sorted.
+ """The registered trigger names are exactly the hand-written 27, sorted.
A missing registration shortens the list; a doubled one (``@TrameApp()``
on both the base and the leaf) duplicates a name in
@@ -106,6 +107,7 @@ def test_local_app_registers_exactly_these_triggers(mock_server):
LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
@@ -121,6 +123,7 @@ def test_local_app_seeds_rendering_mode_client(mock_server):
LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
@@ -129,12 +132,27 @@ def test_local_app_seeds_rendering_mode_client(mock_server):
assert mock_server.state["rendering_mode"] == "client"
+def test_get_variable_records_json_returns_the_injected_records(mock_server):
+ """The trigger serves exactly what the injected records callable returns."""
+ app = LocalApp(
+ server=mock_server,
+ get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(return_value='{"POINT::pressure::1": {}}'),
+ standalone=True,
+ pick_geometry_in_view=MagicMock(),
+ pick_part_in_view=MagicMock(),
+ )
+
+ assert app.get_variable_records_json() == '{"POINT::pressure::1": {}}'
+
+
def test_set_geometry_highlight_forwards_the_parsed_pick(mock_server):
"""The wire payload, keyed by alias, reaches the coordinator as the one pick model it validates as."""
api = MagicMock(name="scene_mutation_api")
app = LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
scene_mutation_api=api,
pick_geometry_in_view=MagicMock(),
@@ -165,6 +183,7 @@ def test_set_pixel_scale_forwards_the_parsed_scale(mock_server):
app = LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
scene_mutation_api=api,
pick_geometry_in_view=MagicMock(),
@@ -184,6 +203,7 @@ def test_set_pixel_scale_ignores_a_scale_that_is_not_positive(mock_server, scale
app = LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
scene_mutation_api=api,
pick_geometry_in_view=MagicMock(),
@@ -216,6 +236,7 @@ def test_pick_geometry_in_view_forwards_a_pick_view_and_dumps_by_alias(mock_serv
app = LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=picker,
pick_part_in_view=MagicMock(),
@@ -258,6 +279,7 @@ def test_pick_geometry_in_view_rejects_a_zero_width(mock_server):
app = LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=picker,
pick_part_in_view=MagicMock(),
@@ -277,6 +299,7 @@ def test_pick_part_in_view_forwards_a_pick_view_and_returns_the_node(mock_server
app = LocalApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=picker,
diff --git a/tests/unit/app/test_server_app.py b/tests/unit/app/test_server_app.py
index 4d35ad98..6b1e505a 100644
--- a/tests/unit/app/test_server_app.py
+++ b/tests/unit/app/test_server_app.py
@@ -20,12 +20,13 @@
from ansys.visor.viewer.models.runtime.picking.geometry_pick import EdgePick
from ansys.visor.viewer.renderer.server_window import VisorRcaWindow
-# The exact 24 trigger names ServerApp registers: the 21 shared with every
+# The exact 25 trigger names ServerApp registers: the 22 shared with every
# rendering mode, plus its own three. Written out by hand, not derived from the
# production trigger list.
SERVER_APP_TRIGGER_NAMES = sorted(
[
"get_visor_scene_details_json",
+ "get_variable_records_json",
"set_part_visibility",
"set_part_opacity",
"set_part_diffuse_color",
@@ -104,6 +105,7 @@ def _build(
return ServerApp(
server=mock_server,
get_scene_details_json=MagicMock(),
+ get_variable_records_json=MagicMock(),
standalone=True,
trame_logger=None,
scene_mutation_api=MagicMock(),
@@ -116,7 +118,7 @@ def _build(
def test_server_app_registers_exactly_these_triggers(mock_server, area_cls):
- """The registered trigger names are exactly the hand-written 24, sorted."""
+ """The registered trigger names are exactly the hand-written 25, sorted."""
_build(mock_server)
names = sorted(call.args[0] for call in mock_server.trigger.call_args_list)
diff --git a/tests/unit/app/test_server_state_publisher.py b/tests/unit/app/test_server_state_publisher.py
index 4a1f70be..e8f9c317 100644
--- a/tests/unit/app/test_server_state_publisher.py
+++ b/tests/unit/app/test_server_state_publisher.py
@@ -151,6 +151,21 @@ def test_bumps_queued_together_count_up(runner, state):
]
+def test_data_bumps_count_up_data_version_only(runner, state):
+ """Data bumps queued together each count, on data_version; scene_version is never written."""
+ publisher = ServerStatePublisher(runner, state)
+ publisher.bump_data_version()
+ publisher.bump_data_version()
+ for callback in runner.callbacks:
+ callback()
+ assert state.events == [
+ ("set", "data_version", 1),
+ ("flush",),
+ ("set", "data_version", 2),
+ ("flush",),
+ ]
+
+
def test_bump_writes_on_loop_thread(state):
async_runner = AsyncRunner()
try:
diff --git a/tests/unit/app/test_visor_trame_app.py b/tests/unit/app/test_visor_trame_app.py
index e4c982b9..197e3727 100644
--- a/tests/unit/app/test_visor_trame_app.py
+++ b/tests/unit/app/test_visor_trame_app.py
@@ -54,6 +54,7 @@ def test_init_sets_attributes(
app = LocalApp(
server=mock_server,
get_scene_details_json=mock_get_scene_details_json,
+ get_variable_records_json=MagicMock(),
standalone=True,
trame_logger=mock_logger,
pick_geometry_in_view=MagicMock(),
@@ -71,6 +72,7 @@ def test_register_lifecycle_hooks_adds_handlers(
LocalApp(
server=mock_server,
get_scene_details_json=mock_get_scene_details_json,
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
@@ -85,6 +87,7 @@ def test_set_headers_sets_http_headers(
LocalApp(
server=mock_server,
get_scene_details_json=mock_get_scene_details_json,
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
@@ -108,6 +111,7 @@ def test_set_www_path_sets_www(
LocalApp(
server=mock_server,
get_scene_details_json=mock_get_scene_details_json,
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
@@ -122,6 +126,7 @@ def test_get_visor_scene_details_json_returns_scene_details(
app = LocalApp(
server=mock_server,
get_scene_details_json=mock_get_scene_details_json,
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
@@ -142,6 +147,7 @@ def test_trame_logger_is_set_when_provided(
app = LocalApp(
server=mock_server,
get_scene_details_json=mock_get_scene_details_json,
+ get_variable_records_json=MagicMock(),
standalone=True,
trame_logger=mock_logger,
pick_geometry_in_view=MagicMock(),
@@ -161,6 +167,7 @@ def test_trame_logger_is_none_when_not_provided(
app = LocalApp(
server=mock_server,
get_scene_details_json=mock_get_scene_details_json,
+ get_variable_records_json=MagicMock(),
standalone=True,
pick_geometry_in_view=MagicMock(),
pick_part_in_view=MagicMock(),
@@ -180,6 +187,7 @@ def test_lifecycle_logging_calls_debug(
LocalApp(
server=mock_server,
get_scene_details_json=mock_get_scene_details_json,
+ get_variable_records_json=MagicMock(),
standalone=True,
trame_logger=mock_logger,
pick_geometry_in_view=MagicMock(),
diff --git a/tests/unit/app/test_visor_vtk_local.py b/tests/unit/app/test_visor_vtk_local.py
index a3ac049b..7c1fa9b9 100644
--- a/tests/unit/app/test_visor_vtk_local.py
+++ b/tests/unit/app/test_visor_vtk_local.py
@@ -601,7 +601,7 @@ def _run_list_variables(iface):
pytest.param(_run_remove_dataset_with_datasets_left, 1, id="remove_dataset-left"),
pytest.param(_run_remove_last_dataset, 1, id="remove_dataset-last"),
pytest.param(_run_clear, 1, id="clear"),
- pytest.param(_run_update_variables, 1, id="update_variables"),
+ pytest.param(_run_update_variables, 0, id="update_variables"),
pytest.param(_run_load_state, 1, id="load_state"),
pytest.param(_run_start, 0, id="start"),
pytest.param(_run_list_datasets, 0, id="list_datasets"),
@@ -628,6 +628,15 @@ def test_failed_scene_operation_still_notifies(iface):
assert iface._post_scene_change_hook.call_count == 1
+def test_update_variables_notifies_a_data_change_once(iface):
+ """update_variables notifies the data-change hook once, so connected clients refresh rather than rebuild."""
+ iface._post_data_change_hook = MagicMock()
+
+ _run_update_variables(iface)
+
+ assert iface._post_data_change_hook.call_count == 1
+
+
# ================================================================== #
# LocalApp injection boundary
# ================================================================== #
diff --git a/tests/unit/app/test_visor_vtk_server.py b/tests/unit/app/test_visor_vtk_server.py
index b965cce2..cbb62e3b 100644
--- a/tests/unit/app/test_visor_vtk_server.py
+++ b/tests/unit/app/test_visor_vtk_server.py
@@ -76,3 +76,13 @@ def test_scene_change_bumps_the_one_publisher(wiring):
publishers[0][1].bump_scene_version.assert_called_once_with()
+def test_data_change_bumps_data_version_and_not_scene_version(wiring):
+ """The data-change hook bumps data_version, so connected clients refresh in place and do not rebuild."""
+ _app_cls, _scene_cls, _bridge_cls, _mgr, publishers, viewer = wiring
+
+ viewer._post_data_change_hook()
+
+ publishers[0][1].bump_data_version.assert_called_once_with()
+ publishers[0][1].bump_scene_version.assert_not_called()
+
+
diff --git a/tests/unit/renderer/test_server_renderer.py b/tests/unit/renderer/test_server_renderer.py
index a7bf4611..f96d31bd 100644
--- a/tests/unit/renderer/test_server_renderer.py
+++ b/tests/unit/renderer/test_server_renderer.py
@@ -141,6 +141,11 @@ def test_render_requests_a_frame(renderer, requester):
assert requester.count == 1
+def test_render_without_rebuild_requests_a_frame(renderer, requester):
+ renderer.render_without_rebuild()
+ assert requester.count == 1
+
+
def test_not_found_on_a_hidden_highlight_requests_no_frame(renderer, requester):
renderer.show_geometry_highlight(NoGeometryPick())
assert requester.count == 0
diff --git a/tests/unit/vtk/scene/test_base.py b/tests/unit/vtk/scene/test_base.py
index 4c2f007a..4b1ae293 100644
--- a/tests/unit/vtk/scene/test_base.py
+++ b/tests/unit/vtk/scene/test_base.py
@@ -17,7 +17,7 @@
"""
import json
import threading
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
import pytest
from vtkmodules.vtkCommonCore import vtkFloatArray
@@ -3481,7 +3481,7 @@ def _update_variables(dataset_id, variables):
node = records_scene._scene_graph.get_descendant_node.return_value
node.refresh_descendant_variable_metadata.side_effect = lambda **_: order.append("refresh")
- real_build = VisorVariableRecords.from_registry
+ real_build = VisorVariableRecords.from_registry_keeping_ranges
def _build(*args):
order.append("rebuild")
@@ -3489,7 +3489,7 @@ def _build(*args):
with (
patch.object(registry, "update_variables", side_effect=_update_variables),
- patch.object(VisorVariableRecords, "from_registry", side_effect=_build),
+ patch.object(VisorVariableRecords, "from_registry_keeping_ranges", side_effect=_build),
):
records_scene.update_variables_for_dataset(1, [])
@@ -3663,6 +3663,93 @@ def test_rebuild_keeps_a_custom_range_on_a_colored_part(scene, registry, pipelin
assert pipeline.mapper.GetScalarRange() == pytest.approx((3.25, 6.75))
+def _update_pressure_to_wider(scene, registry):
+ """update_variables_for_dataset so NODE_ID's "pressure" carries wider values at the same width."""
+ scene._scene_graph = MagicMock(name="scene_graph")
+
+ def _update_variables(dataset_id, variables):
+ _seed_part_variables(registry, [_wider_pressure_variable()])
+
+ with patch.object(registry, "update_variables", side_effect=_update_variables):
+ scene.update_variables_for_dataset(1, [])
+
+
+# A part coloured at the default, and one coloured at a custom range: both keep
+# their effective component range across an update that widens the data.
+_KEEP_ACROSS_UPDATE_CASES = [
+ pytest.param(None, (10.0, 20.0), id="no_custom"),
+ pytest.param((3.25, 6.75), (3.25, 6.75), id="custom"),
+]
+
+
+@pytest.mark.parametrize("custom_range,expected_range", _KEEP_ACROSS_UPDATE_CASES)
+def test_update_keeps_each_effective_range_and_recomputes_the_default(
+ scene, registry, pipeline, custom_range, expected_range
+):
+ """Store half: the record keeps its effective ranges, and its defaults follow the new data."""
+ _color_part_by_pressure_component(scene, registry)
+ if custom_range is not None:
+ scene.set_variable_range(VARIABLE_ID, 0, *custom_range)
+
+ _update_pressure_to_wider(scene, registry)
+
+ record = scene._variable_records.variables[VARIABLE_ID]
+ assert record.ranges == [expected_range]
+ assert record.magnitude_range == (0.0, 49.0)
+ assert record.default_ranges == [(-5.0, 30.0)]
+ assert record.default_magnitude_range == (0.0, 60.0)
+
+
+@pytest.mark.parametrize("custom_range,expected_range", _KEEP_ACROSS_UPDATE_CASES)
+def test_update_leaves_the_colored_part_mapper_at_the_effective_range(
+ scene, registry, pipeline, custom_range, expected_range
+):
+ """Apply half: the mapper stays at the effective range and is not re-serialized; the default still follows."""
+ _color_part_by_pressure_component(scene, registry)
+ if custom_range is not None:
+ scene.set_variable_range(VARIABLE_ID, 0, *custom_range)
+ scene._vtk_lock = _LockSpy()
+ serialized = _record_mapper_serializations(
+ scene, pipeline.mapper, lambda: tuple(pipeline.mapper.GetScalarRange())
+ )
+
+ _update_pressure_to_wider(scene, registry)
+
+ assert pipeline.mapper.GetScalarRange() == pytest.approx(expected_range)
+ assert serialized == []
+ assert scene._variable_records.variables[VARIABLE_ID].default_ranges == [(-5.0, 30.0)]
+
+
+def test_update_pushes_to_the_client_as_data_only(scene, registry, pipeline):
+ """update_variables_for_dataset pushes with dataOnly=True, so the wasm frontend is not rebuilt."""
+ _seed_part_variables(registry, [_pressure_variable()])
+ scene._rebuild_variable_records_from_registry()
+ scene._renderer._local_view.update.reset_mock()
+
+ _update_pressure_to_wider(scene, registry)
+
+ assert scene._renderer._local_view.update.call_args_list == [call(dataOnly=True)]
+
+
+def test_get_variable_records_json_serves_the_held_records_by_alias(records_scene):
+ """The records trigger's payload is the held records, keyed by identifier, dumped by alias."""
+ _seed_records(records_scene, _pressure_record())
+
+ assert json.loads(records_scene.get_variable_records_json()) == {
+ "POINT::pressure::1": {
+ "id": "POINT::pressure::1",
+ "arrayName": "pressure",
+ "type": "POINT",
+ "numComponents": 1,
+ "partIds": [7],
+ "defaultMagnitudeRange": [0.0, 49.0],
+ "defaultRanges": [[10.0, 20.0]],
+ "magnitudeRange": [0.0, 49.0],
+ "ranges": [[10.0, 20.0]],
+ }
+ }
+
+
def test_load_overlays_the_file_range_before_the_part_restore(scene, registry):
"""#14: the file's range is held after load.
diff --git a/tests/unit/vtk/scene/test_local_scene.py b/tests/unit/vtk/scene/test_local_scene.py
index 84b40e98..45dd38eb 100644
--- a/tests/unit/vtk/scene/test_local_scene.py
+++ b/tests/unit/vtk/scene/test_local_scene.py
@@ -684,10 +684,10 @@ def test_list_variables_for_dataset_delegates(pipeline_instance):
def test_update_variables_for_dataset_triggers_updates_and_render(pipeline_instance):
- """Test that update_variables_for_dataset triggers updates and render."""
+ """Test that update_variables_for_dataset triggers updates and a render that does not rebuild the frontend."""
vars_payload = ["dummy"]
render_spy = MagicMock()
- pipeline_instance.render = render_spy
+ pipeline_instance._renderer.render_without_rebuild = render_spy
pipeline_instance.update_variables_for_dataset(123, vars_payload)