Source code for polyfoammesh.gui.viewer_widget
from __future__ import annotations
import logging
import re
import struct
import sys
from pathlib import Path
import numpy as np
import pyvista as pv
import trimesh
from PySide6.QtCore import QProcess, QTimer, Signal, Qt
from PySide6.QtWidgets import (
QAbstractItemView,
QCheckBox,
QComboBox,
QHBoxLayout,
QHeaderView,
QLabel,
QPushButton,
QTableWidget,
QTableWidgetItem,
QVBoxLayout,
QWidget,
)
from polyfoammesh.gui.design_tokens import WARNING_LIGHT
from polyfoammesh.gui.task_runner import FunctionWorker, TaskManager
logger = logging.getLogger(__name__)
PATCH_COLORS = [
(0.91, 0.30, 0.24),
(0.18, 0.80, 0.44),
(0.20, 0.60, 0.86),
(0.95, 0.61, 0.07),
(0.61, 0.35, 0.71),
(0.10, 0.74, 0.80),
(0.90, 0.40, 0.13),
(0.16, 0.50, 0.73),
]
VIEW_MODES = ["Surface", "Surface with Edges", "Wireframe"]
_MESH_COLOR = (0.86, 0.88, 0.91)
_HIGHLIGHT_COLOR = (1.0, 0.84, 0.0)
_MAX_CLIP_FACES = 50_000
BACKGROUNDS = {
"White": ((1.0, 1.0, 1.0), "black"),
"Dark": ((0.18, 0.18, 0.18), "white"),
"Black": ((0.12, 0.12, 0.14), "white"),
"ParaView": ((0.32, 0.34, 0.43), "white"),
}
def _format_distance(metres: float) -> str:
"""Distance in the unit a human reads at a glance: mm below 1 m.
The signal and logs always carry metres; only the on-screen overlay is
switched to mm, so a 12 mm gap reads "12.000 mm" instead of "0.012 m".
"""
if abs(metres) < 1.0:
return f"{metres * 1000.0:.3f} mm"
return f"{metres:.3f} m"
#: Canonical patch role -> the five labels the patch panel shows.
_PATCH_TYPE_BY_ROLE = {
"inlet": "inlet",
"outlet": "outlet",
"symmetry": "symmetry",
"empty": "symmetry",
"wall": "wall",
}
[docs]
def detect_patch_type(name: str, patch_type: str = "") -> str:
"""Auto-detected patch type: wall / inlet / outlet / symmetry / other.
Reuses the project's single wall-detection classifier
(``core.patch_roles.match_role`` — see its module docstring) and falls
back to the ``type`` recorded in the case boundary file, which the mesher
writes from ``meshdict_gen.infer_patch_type`` / ``case_setup``. No new
heuristic is introduced here.
"""
from polyfoammesh.core.patch_roles import match_role
role = match_role(name)
if role in _PATCH_TYPE_BY_ROLE:
return _PATCH_TYPE_BY_ROLE[role]
recorded = (patch_type or "").lower()
if recorded in ("symmetryplane", "symmetry", "empty"):
return "symmetry"
if recorded == "wall":
return "wall"
return "other"
def _patch_type_map(case_dir: Path) -> dict[str, str]:
"""name -> boundary-file ``type`` for a case polyMesh (best effort)."""
try:
from polyfoammesh.core.boundary_reader import parse_boundary
boundary = Path(case_dir) / "constant" / "polyMesh" / "boundary"
return {p.name: p.patch_type for p in parse_boundary(boundary)}
except Exception:
return {}
def _inferred_patch_roles(case_dir: Path) -> dict[str, str]:
"""name -> inferred role for a generated mesh, best effort ({} on failure).
``case_setup.infer_patch_roles`` classifies every patch geometrically when
the names are raw GMSH ``surface_N`` (no semantic information): the two
extreme flow-axis patches become inlet/outlet and everything else a wall.
This is what the patch table's Type column shows for a generated mesh
(instead of "other"), and what the BL uses to pick walls.
"""
try:
from polyfoammesh.core.boundary_reader import parse_boundary
from polyfoammesh.core.case_setup import infer_patch_roles
boundary = Path(case_dir) / "constant" / "polyMesh" / "boundary"
patches = parse_boundary(boundary)
if not patches:
return {}
return infer_patch_roles(Path(case_dir), patches)
except Exception:
return {}
def _trimesh_to_pydata(mesh: trimesh.Trimesh, color: tuple[float, float, float]) -> pv.PolyData:
faces = np.hstack([np.full((len(mesh.faces), 1), 3), mesh.faces]).astype(np.int32)
pd = pv.PolyData(mesh.vertices.astype(np.float64), faces)
pd.cell_data["color"] = np.tile(color, (pd.n_cells, 1))
return pd
def _strip_of_comments(text: str) -> str:
text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
text = re.sub(r"//[^\n]*", "", text)
return text
def _strip_of_comments_keep_offsets(text: str) -> str:
"""Like _strip_of_comments, but blanks comments to spaces instead of
deleting them, so every surviving character keeps its ORIGINAL index.
Required wherever a position found by scanning the stripped text is
later used to slice the raw, un-stripped bytes (see
_read_of_block_binary): deleting characters shifts every index after
the comment, so an index computed on the shortened text no longer
points at the same byte in the original buffer.
"""
text = re.sub(r"/\*.*?\*/", lambda m: " " * len(m.group(0)), text, flags=re.DOTALL)
text = re.sub(r"//[^\n]*", lambda m: " " * len(m.group(0)), text)
return text
def _is_binary_of(path: Path) -> bool:
"""Check if an OpenFOAM file is in binary format (reads only header)."""
from polyfoammesh.core.of_reader import _read_header_bytes
raw = _read_header_bytes(path)
return bool(re.search(rb"format\s+ binary\s*;", raw[:1024]))
def _read_of_block(path: Path) -> str:
from polyfoammesh.core.of_reader import _read_of_bytes
raw = _read_of_bytes(path)
if _is_binary_of(path):
return _read_of_block_binary(path, raw)
text = _strip_of_comments(raw.decode("ascii", errors="replace"))
match = re.search(r"\(\s*(.*)\s*\)", text, flags=re.DOTALL)
if not match:
raise ValueError(f"Cannot parse OF block in {path}")
return match.group(1)
def _read_of_block_binary(path: Path, raw: bytes) -> str:
"""Return ASCII representation of the data block in a binary OF file.
For points: returns 'x1 y1 z1 x2 y2 z2 ...'
For faces: returns 'n1 (v0 v1 ...) n2 (v0 v1 ...) ...'
"""
text_part = raw.decode("ascii", errors="replace")
# Deletes comments -> shifts every later index -> NOT usable to locate a
# position that will slice `raw`. Only safe for content extraction
# (e.g. the class= match below), never for offsets into raw.
text_part = _strip_of_comments(text_part)
# Length-preserving: comments become spaces of the same width, so an
# index found here still points at the same byte in `raw`. Binary data
# can contain a stray 0x7D ('}'), so the search is capped to the first
# 512 chars (safe header size) to avoid matching one inside the body.
header_scan = _strip_of_comments_keep_offsets(raw.decode("ascii", errors="replace"))
header_end = header_scan[:512].rfind("}")
if header_end < 0:
header_end = header_scan.find("}")
if header_end < 0:
raise ValueError(f"Cannot find FoamFile header end in {path}")
body = raw[header_end + 1:] if header_end != -1 else raw
m = re.search(rb"(\d+)\s*\(", body)
if not m:
raise ValueError(f"Cannot parse binary OF block header count in {path}")
body_start = header_end + 1 + m.end()
body_bytes = raw[body_start:] if body_start < len(raw) else b""
# Determine type from class in header
cls_match = re.search(r"class\s+(\w+);", text_part)
cls = cls_match.group(1) if cls_match else ""
if cls == "faceList":
return _binary_faces_to_ascii(body_bytes)
# Default: points, vectorField etc. - flat doubles. The element count
# from the header is what bounds the stream; see _binary_doubles_to_ascii.
return _binary_doubles_to_ascii(body_bytes, int(m.group(1)) * _OF_FIELD_WIDTH.get(cls, 1))
# Components per element, by FoamFile class. Anything unlisted is treated as
# scalar (1), which at worst reads fewer values than are present - never more.
_OF_FIELD_WIDTH = {
"vectorField": 3,
"pointField": 3,
"scalarField": 1,
"labelField": 1,
"sphericalTensorField": 1,
"symmTensorField": 6,
"tensorField": 9,
}
def _binary_doubles_to_ascii(data: bytes, n_values: int | None = None) -> str:
"""Convert a binary float64 array to a space-separated ASCII string.
``n_values`` is how many doubles to read, taken from the element count in
the FoamFile header. It is not a nicety: this function used to delimit the
stream by scanning for the closing ``)``, which cannot work. Raw float64
bytes are arbitrary, so 0x29 (the byte for ')') occurs constantly inside
legitimate coordinates, and the data was truncated at the first one.
Measured on a 16415-point cfMesh mesh (cartesianMesh, writeFormat binary):
the scan cut the stream after 38 doubles, so _parse_of_points() raised
"cannot reshape array of size 38 into shape (3)" and the caller turned
that into a silent None - i.e. the viewer showed nothing at all for any
binary mesh, which is the format the app writes by default.
Why this survived so long: tests/test_e2e_workflow.py step [7/7] is what
covers this path, and it wrote `writeFormat ascii` until commit aaf5e12
switched it to `binary`. From that commit the step could no longer pass -
but by then the same test hung at step [5/7] for a missing QApplication
(fixed in f18785c), so it never got far enough to report it. One bug was
hiding the other; do not assume a green-looking suite exercised this.
"""
pos = 0
while pos < len(data) and data[pos:pos + 1] in (b'\n', b' ', b'\r'):
pos += 1
data = data[pos:]
available = len(data) // 8
if n_values is None or n_values <= 0 or n_values > available:
# Header count missing or inconsistent with the file: fall back to
# whatever is actually there rather than raising. Still never scans
# for ')' - a short read beats a truncated one.
if n_values:
logger.debug(
"Binary field claims %d values but only %d fit in %d bytes; "
"reading what is present.", n_values, available, len(data),
)
n_values = available
if n_values == 0:
return ""
values = struct.unpack(f"<{n_values}d", data[:n_values * 8])
return " ".join(f"{v:.10g}" for v in values)
def _binary_faces_to_ascii(data: bytes) -> str:
"""Convert binary faceList to ASCII 'n (v0 v1 ...)' string.
Binary face format: for each face, nVertices (int32) followed by
nVertices vertex indices (int32). The first ( after the header
is already consumed by the caller.
"""
parts = []
pos = 0
while pos < len(data):
# Skip whitespace/newlines
while pos < len(data) and data[pos:pos+1] in (b'\n', b' ', b'\r'):
pos += 1
if pos >= len(data) or data[pos:pos+1] in (b')',):
break
# Check if it's an ASCII digit (mixed format)
if 48 <= data[pos] <= 57: # '0'-'9'
end = pos
while end < len(data) and 48 <= data[end] <= 57:
end += 1
n_verts = int(data[pos:end].decode("ascii"))
pos = end
else:
# Binary int32 for face size
n_verts = struct.unpack('<i', data[pos:pos+4])[0]
pos += 4
# Skip to '('
while pos < len(data) and data[pos:pos+1] in (b'\n', b' ', b'\r'):
pos += 1
if pos < len(data) and data[pos:pos+1] == b'(':
pos += 1
# Read n_verts int32 indices
n_bytes = n_verts * 4
if pos + n_bytes > len(data):
break
verts = struct.unpack(f"<{n_verts}i", data[pos:pos+n_bytes])
pos += n_bytes
# Skip ')'
while pos < len(data) and data[pos:pos+1] not in (b')',):
pos += 1
if pos < len(data):
pos += 1
parts.append(f"{n_verts} (" + " ".join(str(v) for v in verts) + ")")
return "\n".join(parts)
def _parse_of_points(path: Path) -> np.ndarray:
text = _read_of_block(path)
# Each point is written "(x y z)" — np.fromstring can't tokenize the
# parens (raises "unmatched data" on modern numpy), so strip them.
# cfMesh meshes are normally too large for this manual-parser fallback
# (they require foamToVTK instead), which is why this only surfaces on
# small meshes such as autopoly's.
text = text.replace("(", " ").replace(")", " ")
arr = np.array(text.split(), dtype=np.float64) # np.fromstring is deprecated
return arr.reshape(-1, 3)
def _parse_of_faces(path: Path) -> list[list[int]]:
text = _read_of_block(path)
faces = []
entry_re = re.compile(r"(\d+)\s*\(([^)]*)\)")
for entry in entry_re.finditer(text):
idx_str = entry.group(2)
indices = list(map(int, idx_str.split()))
faces.append(indices)
return faces
# ✅ F-012: delegato a boundary_reader.parse_boundary (elimina duplicazione)
def _parse_boundary(path: Path) -> list[dict]:
from polyfoammesh.core.boundary_reader import parse_boundary
patches = parse_boundary(path)
return [{"name": p.name, "nFaces": p.n_faces, "startFace": p.start_face} for p in patches]
# (_triangulate_face removed: its only caller was the manual boundary
# parser, which now emits the real polygons instead of fanning them into
# triangles — see read_openfoam_mesh_patches.)
# ✅ F-013: LRU cache con max 5 entries per evitare memory leak
_MESH_CACHE: dict[tuple[str, float], dict[str, pv.PolyData]] = {}
_MAX_CACHE_SIZE = 20
# Skip the slow manual parser when faces file exceeds this size (5 MB).
# Large polyhedral meshes crash/hang the GUI thread; foamToVTK is mandatory.
_MANUAL_PARSE_MAX_SIZE_BYTES = 5_000_000
def _cache_set(key: tuple[str, float], value: dict[str, pv.PolyData]) -> None:
if len(_MESH_CACHE) >= _MAX_CACHE_SIZE:
oldest = next(iter(_MESH_CACHE))
del _MESH_CACHE[oldest]
_MESH_CACHE[key] = value
def _human_size(n_bytes: int) -> str:
"""Format bytes as human-readable string."""
for unit in ("B", "KB", "MB", "GB"):
if n_bytes < 1024:
return f"{n_bytes:.1f}{unit}"
n_bytes /= 1024
return f"{n_bytes:.1f}TB"
def _find_internal_vtu(case_dir: Path, vtk_subdir: str = "VTK_view") -> list[Path]:
"""Locate the internal volume VTU(s) written by foamToVTK.
``foamToVTK -constant`` writes to ``constant/<name>/`` (the ``-constant``
flag makes it use the constant/ time directory), so the file can live
under either ``<case>/<name>/`` or ``<case>/constant/<name>/``. Check both
— the old code only looked in ``<case>/<name>/``, so a ``-constant`` run
was never found and the viewer reported a false "no internal mesh".
"""
for base in (case_dir / vtk_subdir, case_dir / "constant" / vtk_subdir):
if not base.exists():
continue
matches = sorted(base.glob("*_0/internal.vtu"))
if matches:
return matches
return []
def _poly_dir_state(poly_dir: Path, max_retries: int = 3, delay_ms: int = 500) -> float | None:
"""Check that all required polyMesh files exist and return newest mtime.
Never sleeps on the calling thread: callers that need the sync-delay
retry (on Windows, files written by cartesianMesh inside WSL may not
be visible from Windows for a few hundred ms; on Linux the write may
simply not have landed yet) schedule their own retries via QTimer —
this function is a single non-blocking check.
"""
files = ("points", "faces", "boundary")
mtimes: list[float] = []
all_exist = True
for name in files:
f = poly_dir / name
if not f.exists():
all_exist = False
break
try:
mtimes.append(f.stat().st_mtime)
except OSError:
all_exist = False
break
if all_exist:
return max(mtimes)
return None
def _run_foamtovtk_async(case_dir: Path, vtk_subdir: str, state: float) -> Path | None:
"""Run foamToVTK via Popen with polling loop to keep UI responsive.
Sleeps 100ms between polls so this function does NOT spin at 100% CPU,
which froze the main thread on meshes where foamToVTK takes >30s.
Shows a progress message in the viewer text during conversion.
"""
import shlex
import subprocess
import time as _time
from polyfoammesh.config import OFConfig
cfg = OFConfig()
linux_case = cfg._quoted_linux_path(case_dir)
env_quoted = shlex.quote(cfg.env_script)
cmd = cfg._build_wsl_cmd(
f"source {env_quoted} 2>/dev/null; cd {linux_case} && "
f"foamToVTK -constant -noZero -no-fields -overwrite -name {vtk_subdir}"
)
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, bufsize=4096,
)
deadline = _time.monotonic() + 180
last_progress = 0.0
while proc.poll() is None:
elapsed = _time.monotonic() - (deadline - 180)
if elapsed - last_progress > 5.0:
logger.info("foamToVTK running for %.0fs...", elapsed)
last_progress = elapsed
if _time.monotonic() > deadline:
proc.kill()
proc.wait(5)
logger.error("foamToVTK timed out after 180s")
return None
_time.sleep(0.1)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
stderr_detail = (stderr or stdout or "")[-500:]
logger.warning("foamToVTK failed (rc=%d): %s", proc.returncode, stderr_detail)
return None
matches = _find_internal_vtu(case_dir, vtk_subdir)
if matches:
try:
(case_dir / vtk_subdir / ".source_mtime").write_text(str(state))
except OSError:
pass
return matches[0]
return None
[docs]
def build_internal_volume_vtu(case_dir: Path) -> Path | None:
"""Run OpenFOAM's own `foamToVTK` to get the real internal volume cells.
The "Volume Mesh" view used to only ever show the boundary *patches*
(constant/polyMesh/boundary) — the outer surface, never the actual
internal cells — because that's all `read_openfoam_mesh_patches` reads.
cfMesh/cartesianMesh cells are polyhedral; meshio can't parse OpenFOAM
or polyhedral VTU at all, but PyVista (built on VTK directly) reads
them fine, so foamToVTK -> PyVista is the reliable path here.
Cached under <case_dir>/VTK_view, regenerated only when polyMesh changed.
Runs in a background task (the foamToVTK call takes 30-60s).
"""
case_dir = Path(case_dir)
poly_dir = case_dir / "constant" / "polyMesh"
state = _poly_dir_state(poly_dir)
if state is None:
return None
vtk_subdir = "VTK_view"
marker = case_dir / vtk_subdir / ".source_mtime"
existing = _find_internal_vtu(case_dir, vtk_subdir)
if existing and marker.exists():
try:
if float(marker.read_text().strip()) == state:
return existing[0]
except (ValueError, OSError):
pass
return _run_foamtovtk_async(case_dir, vtk_subdir, state)
[docs]
def read_openfoam_mesh_stats(case_dir: Path) -> dict:
"""Read mesh statistics from an OpenFOAM polyMesh directory.
Uses nCells/nPoints/nFaces from the FoamFile header where available
(fast path, reads only header bytes). Falls back to file-size-based
estimation to avoid loading the full data on the GUI thread.
"""
poly_dir = Path(case_dir) / "constant" / "polyMesh"
stats = {"points": 0, "faces": 0, "cells": 0}
# Fast path: read nCells from owner file header
from polyfoammesh.core.of_reader import of_list_count, of_ncells_from_header
owner_path = poly_dir / "owner"
if owner_path.exists():
n = of_ncells_from_header(owner_path)
if n is not None:
stats["cells"] = n
# Use of_list_count which reads only the header
points_path = poly_dir / "points"
if points_path.exists():
stats["points"] = of_list_count(points_path)
faces_path = poly_dir / "faces"
if faces_path.exists():
stats["faces"] = of_list_count(faces_path)
return stats
def _load_vtk_patches(case_dir: Path, vtk_subdir: str) -> dict[str, pv.PolyData] | None:
"""Load boundary patches from foamToVTK-generated VTU files (fast path)."""
vtk_dir = case_dir / vtk_subdir
time_dirs = sorted(vtk_dir.glob("*_0")) if vtk_dir.exists() else []
if not time_dirs:
return None
boundary_dir = time_dirs[0] / "boundary"
if not boundary_dir.is_dir():
return None
result: dict[str, pv.PolyData] = {}
# foamToVTK writes each boundary patch as 2D surface data (.vtp,
# PolyData) — searching for "*.vtu" (volumetric UnstructuredGrid) never
# matched anything, so this fast path silently always returned None and
# every mesh fell through to the manual ASCII parser, which bails with
# "too large" on anything but tiny cases (root cause of the integrated
# viewer showing "mesh too large, use ParaView" instead of the mesh).
boundary_files = sorted(boundary_dir.glob("*.vtp")) + sorted(boundary_dir.glob("*.vtu"))
for i, vtu in enumerate(boundary_files):
try:
pd = pv.read(str(vtu))
name = vtu.stem
color = PATCH_COLORS[i % len(PATCH_COLORS)]
pd.cell_data["color"] = np.tile(color, (pd.n_cells, 1))
result[name] = pd
except Exception:
continue
return result or None
[docs]
def read_openfoam_mesh_patches(case_dir: Path | str) -> dict[str, pv.PolyData] | None:
case_dir = Path(case_dir)
poly_dir = case_dir / "constant" / "polyMesh"
state = _poly_dir_state(poly_dir)
if state is None:
# Windows: files are written inside WSL2 and may lag on the 9P
# filesystem. Linux: cartesianMesh runs natively, so a delay here
# just means the write hasn't landed yet. Windows wording kept
# byte-identical.
_sync_note = (
"files may not have synced from WSL2 yet"
if sys.platform == "win32" else "files may not have synced yet"
)
logger.warning(
"read_openfoam_mesh_patches: polyMesh state is None for %s (%s)",
poly_dir, _sync_note,
)
return None
cache_key = (str(case_dir), state)
cached = _MESH_CACHE.get(cache_key)
if cached is not None:
logger.debug("Mesh patches loaded from cache (%d patches)", len(cached))
return cached
# Fast path: try loading from foamToVTK-generated VTU files
vtk_patches = _load_vtk_patches(case_dir, "VTK_view")
if vtk_patches is not None:
logger.info("Loaded %d mesh patches from foamToVTK VTU", len(vtk_patches))
_cache_set(cache_key, vtk_patches)
return vtk_patches
# Slow path: manual parsing of OpenFOAM binary files (for small meshes
# where foamToVTK hasn't been run yet — cfMesh polyhedral meshes with
# 3.5M+ cells are NOT reliably parsed here; foamToVTK is required).
faces_path = poly_dir / "faces"
if faces_path.exists() and faces_path.stat().st_size > _MANUAL_PARSE_MAX_SIZE_BYTES:
logger.info(
"Faces file too large (%s), skipping manual parser — foamToVTK required",
_human_size(faces_path.stat().st_size),
)
return None
logger.info("VTU not found, falling back to manual OF parser for %s", poly_dir)
try:
points = _parse_of_points(poly_dir / "points")
all_faces = _parse_of_faces(poly_dir / "faces")
patches = _parse_boundary(poly_dir / "boundary")
except (ValueError, IndexError, OSError, MemoryError) as exc:
# This used to say the failure was "normal for large binary cfMesh
# meshes". It was not: size was never the discriminator. Measured on
# one mesh written both ways, the 938 KB BINARY faces file failed
# while the 1.0 MB ASCII one parsed fine - the larger file was the
# one that worked, and both were far below the 5 MB cutoff above.
# The real cause was the ')'-scan truncation fixed in
# _binary_doubles_to_ascii. Blaming size sent anyone reading this log
# looking in the wrong place, so say only what is actually known.
logger.warning(
"Manual mesh parsing failed for %s: %s. Falling back to "
"foamToVTK; run it for this case if the viewer stays empty.",
poly_dir, exc,
)
return None
result: dict[str, pv.PolyData] = {}
for i, p in enumerate(patches):
start = p["startFace"]
end = start + p["nFaces"]
patch_faces = all_faces[start:end]
total_verts = sum(len(f) for f in patch_faces)
if total_verts == 0:
continue
# Emit each boundary face as the REAL polygon it is, not as a fan of
# triangles. This used to triangulate everything (a quad -> 2 tris,
# an n-gon -> n-2 tris), which is exactly what made a 100%
# polyhedral mesh look like a tetrahedral one in the viewer: the
# barycentric dual's boundary is quads (three per original boundary
# triangle), and after the fan split the user saw only their
# diagonals. PyVista/VTK take a variable-size face stream —
# [n, v0..vn-1, m, w0..wm-1, ...] — so no triangulation is needed at
# all, and `show_edges` then outlines the true cell boundaries.
verts_arr = np.empty((total_verts, 3), dtype=np.float64)
# one size prefix per face + one index per vertex
faces_pv = np.empty(len(patch_faces) + total_verts, dtype=np.int32)
v_offset = 0
f_offset = 0
for fi, face_indices in enumerate(patch_faces):
n = len(face_indices)
try:
verts_arr[v_offset:v_offset + n] = points[face_indices]
except IndexError:
logger.warning("Patch '%s' face %d: index out of bounds (points=%d, max_idx=%d). Mesh parsing incomplete.",
p["name"], fi, len(points), max(face_indices))
return None
faces_pv[f_offset] = n
faces_pv[f_offset + 1:f_offset + 1 + n] = np.arange(
v_offset, v_offset + n, dtype=np.int32,
)
f_offset += n + 1
v_offset += n
pd = pv.PolyData(verts_arr, faces_pv)
color = PATCH_COLORS[i % len(PATCH_COLORS)]
pd.cell_data["color"] = np.tile(color, (pd.n_cells, 1))
result[p["name"]] = pd
_cache_set(cache_key, result) # ✅ F-013
return result
[docs]
class ViewerWidget(QWidget):
face_picked = Signal(str)
#: (old_name, new_name) — emitted when the user renames a CAD patch in
#: the patch table. Additive: existing signals/consumers are unaffected.
patch_renamed = Signal(str, str)
#: (old_name, new_name) — emitted when the user renames a patch of a
#: GENERATED mesh in the patch table. The main window writes the new name
#: back to constant/polyMesh/boundary (after backing it up) and refreshes
#: the table/BC editor. Additive alongside patch_renamed.
mesh_patch_renamed = Signal(str, str)
distance_measured = Signal(str)
measure_hint = Signal(str)
refinement_point_picked = Signal(float, float, float)
refinement_boxes_changed = Signal(object)
def __init__(self, parent=None):
super().__init__(parent)
self._cad_meshes: list[trimesh.Trimesh] = []
self._mesh_case_dir: str = ""
self._bg_color: tuple[float, float, float] = (1.0, 1.0, 1.0)
self._refinement_pick_active: bool = False
self._text_color: str = "black"
self._plotter = None
self._plotter_ready: bool = False
self._pvdata_to_name: dict[str, str] = {}
self._section_enabled: bool = False
self._measure_points: list = []
self._measure_actors: list = []
self._measurements: list[tuple[str, float]] = []
self._measure_index: int = 0
self._mesh_patches: dict[str, pv.PolyData] = {}
self._patch_names: list[str] = []
#: name -> inferred role ("wall"/"inlet"/"outlet") for a generated
#: mesh, from case_setup.infer_patch_roles. Empty for CAD.
self._patch_roles: dict[str, str] = {}
self._patch_rename_guard: bool = False
self._highlighted_actor = None
self._showing_cad: bool = True
self._pending_vtu_mode: str = "surface_edges"
self._mesh_display_in_progress: bool = False
self._mesh_retry_count: int = 0
self._mesh_retry_max: int = 3
self._foam_to_vtk_attempted: bool = False
self._mesh_cancelled: bool = False
self._display_timeout_timer: QTimer | None = None
# Background tasks for heavy loads (foamToVTK, VTU reads) so the
# UI never freezes while the mesh display pipeline runs.
self._vtk_tasks = TaskManager(self)
self._layout = QVBoxLayout(self)
self._layout.setContentsMargins(0, 0, 0, 0)
toolbar = QHBoxLayout()
toolbar.setContentsMargins(4, 2, 4, 2)
toolbar.addWidget(QLabel("Display:"))
self._view_selector = QComboBox()
self._view_selector.addItems(VIEW_MODES)
self._view_selector.setCurrentIndex(-1)
self._view_selector.setEnabled(False)
self._view_selector.setToolTip(
"Representation applied to whatever is displayed: Surface, "
"Surface with Edges, or Wireframe."
)
self._view_selector.currentIndexChanged.connect(self._on_view_changed)
toolbar.addWidget(self._view_selector)
toolbar.addSpacing(12)
toolbar.addWidget(QLabel("Background:"))
self._bg_selector = QComboBox()
self._bg_selector.addItems(list(BACKGROUNDS.keys()))
self._bg_selector.setCurrentText("Dark")
self._bg_selector.setToolTip("Change the viewer background color.")
self._bg_selector.currentTextChanged.connect(self._on_bg_changed)
toolbar.addWidget(self._bg_selector)
toolbar.addSpacing(12)
self._section_check = QCheckBox("Section Cut")
self._section_check.setToolTip("Toggle interactive clipping plane")
self._section_check.toggled.connect(self._on_section_toggled)
toolbar.addWidget(self._section_check)
toolbar.addSpacing(8)
self._pick_check = QCheckBox("Select Patch")
self._pick_check.setToolTip("Toggle face selection mode. When ON, click a patch to rename it.")
self._pick_check.toggled.connect(self._on_pick_toggled)
toolbar.addWidget(self._pick_check)
self._measure_check = QCheckBox("Measure")
self._measure_check.setToolTip("Click two points to measure distance between them.")
self._measure_check.toggled.connect(self._on_measure_toggled)
toolbar.addWidget(self._measure_check)
self._measure_clear_btn = QPushButton("Clear")
self._measure_clear_btn.setToolTip("Remove all measurements and their markers.")
self._measure_clear_btn.setEnabled(False)
self._measure_clear_btn.clicked.connect(self._clear_measurements)
toolbar.addWidget(self._measure_clear_btn)
toolbar.addSpacing(8)
# Boundary layers are visible through the mesh itself: in
# Surface-with-Edges the layer stack shows as the dense edge band
# at the wall (previous-release behaviour). No overlay colouring
# and no scalar bar (user request: the orange overlay was
# unreadable).
self._stats_label = QLabel("")
self._stats_label.setStyleSheet(
"font-size: 11px; padding: 2px 8px; background: rgba(0,0,0,30); border-radius: 3px;"
)
toolbar.addWidget(self._stats_label)
toolbar.addStretch()
self._layout.addLayout(toolbar)
self._build_patch_panel()
self._measure_summary = QLabel(self)
self._measure_summary.setTextFormat(Qt.PlainText)
self._measure_summary.setStyleSheet(
f"background: rgba(0, 0, 0, 170); color: {WARNING_LIGHT}; padding: 6px 8px; "
"border: 1px solid rgba(255, 255, 255, 60); border-radius: 4px;"
)
self._measure_summary.setVisible(False)
QTimer.singleShot(0, self._init_vtk)
def _init_vtk(self):
if self._plotter is not None:
return
# Quick pre-check: try importing VTK rendering modules.
# If the import fails, skip QtInteractor entirely.
try:
import vtkmodules.vtkRenderingOpenGL2 # noqa: F401
except ImportError as exc:
logger.warning("VTK/OpenGL not available, 3D viewer disabled: %s", exc)
self._add_no_viewer_label()
return
from pyvistaqt import QtInteractor
try:
self._plotter = QtInteractor(parent=self, auto_update=30.0)
self._layout.addWidget(self._plotter)
self._plotter_ready = True
self._apply_background(self._bg_selector.currentText())
self._install_click_deselect()
QTimer.singleShot(0, self._position_measure_summary)
except Exception as exc:
logger.error("Failed to initialize VTK plotter: %s", exc)
self._add_no_viewer_label(f"Error: {exc}")
[docs]
def resizeEvent(self, event):
super().resizeEvent(event)
if getattr(self, "_measure_summary", None) is not None:
self._position_measure_summary()
def _build_patch_panel(self):
"""Compact BaramMesh-style patch list.
The widget is created here (so all the logic stays in the viewer)
but PLACED by the main window in the left dock, in the empty space
below the workflow tree - see MainWindow._setup_workflow_tree and
patch_panel().
"""
self._patch_panel = QWidget()
layout = QVBoxLayout(self._patch_panel)
layout.setContentsMargins(4, 2, 4, 2)
layout.setSpacing(2)
title = QLabel("Patches")
# Same style as the "Next action" title so the left dock reads as
# one ordered column (user request: make the app look tidy).
title.setStyleSheet(
"padding: 6px 4px 0 4px; font-size: 10px; font-weight: bold;"
)
layout.addWidget(title)
self._patch_table = QTableWidget(0, 3)
self._patch_table.setHorizontalHeaderLabels(["Name", "Faces", "Type"])
self._patch_table.verticalHeader().setVisible(False)
self._patch_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self._patch_table.setSelectionMode(QAbstractItemView.SingleSelection)
# Edit triggers are enabled here but actual editability is per-item:
# only the Name cell of a CAD patch is editable (see
# _populate_patch_panel). A loaded case mesh keeps every cell read-only.
self._patch_table.setEditTriggers(
QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed
)
self._patch_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self._patch_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
self._patch_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
# No height cap: the table fills the left dock below the workflow
# hint instead of leaving a dead gray band above it (user request:
# the dock looked unordered).
self._patch_table.setMinimumHeight(120)
self._patch_table.itemSelectionChanged.connect(self._on_patch_row_selected)
self._patch_table.itemChanged.connect(self._on_patch_item_changed)
self._patch_table.itemDoubleClicked.connect(self._on_patch_item_double_clicked)
layout.addWidget(self._patch_table)
self._patch_panel.setVisible(False)
# NOT added to the viewer layout: the main window embeds this panel
# in the left dock (empty space below the workflow tree).
[docs]
def patch_panel(self) -> QWidget:
"""The BaramMesh-style patch panel, for the main window to embed."""
return self._patch_panel
def _add_no_viewer_label(self, msg: str = ""):
"""Add a label explaining that 3D viewer is unavailable."""
self._plotter = None
self._plotter_ready = False
if not msg:
msg = "3D viewer unavailable.\nUse Tools > Launch ParaView."
lbl = QLabel(msg)
lbl.setAlignment(Qt.AlignCenter)
self._layout.addWidget(lbl)
def _apply_background(self, name: str):
if self._plotter is None:
return
bg, _ = BACKGROUNDS[name]
self._bg_color = bg
self._plotter.set_background(bg)
self._plotter.show_axes()
self._plotter.render()
self._redisplay_current()
def _on_bg_changed(self, text: str):
self._apply_background(text)
from PySide6.QtCore import QSettings
QSettings("cfmesh-autogui", "CFMesh-AutoGUI").setValue("viewer/background", text)
[docs]
def save_background(self, s):
s.setValue("viewer/background", self._bg_selector.currentText())
[docs]
def restore_background(self, s):
bg = s.value("viewer/background", "Dark")
if bg in BACKGROUNDS:
self._bg_selector.setCurrentText(bg)
self._apply_background(bg)
def _is_dark_bg(self) -> bool:
return not all(c > 0.5 for c in self._bg_color)
def _edge_color(self) -> str:
return "white" if self._is_dark_bg() else "gray"
[docs]
def highlight_patch(self, patch_name: str):
"""Highlight a picked patch with a bright, clearly outlined color.
Works in both representations: the CAD surface (per-patch
``_cad_meshes``) and a loaded case mesh (per-patch boundary patches
held in ``_mesh_patches``). The camera is never reset — the call is
a plain clear+redraw, so selecting a patch row leaves the view put.
"""
if self._plotter is None:
return
# Track the selection so a click on empty space can clear it.
self._selected_patch_name = patch_name
if not self._showing_cad and self._mesh_patches:
self._highlight_mesh_patch(patch_name)
return
self._plotter.clear()
ec = self._edge_color()
mode = self._current_mode()
self._pvdata_to_name.clear()
for i, mesh in enumerate(self._cad_meshes):
name = mesh.metadata.get("name", f"patch_{i}")
picked = name == patch_name
color = _HIGHLIGHT_COLOR if picked else PATCH_COLORS[i % len(PATCH_COLORS)]
pd = _trimesh_to_pydata(mesh, color)
kwargs = dict(scalars="color", rgb=True, label=name, smooth_shading=True)
if mode == "Wireframe":
kwargs.update(
style="wireframe",
line_width=2.5 if picked else 1.0,
)
else:
kwargs.update(
style="surface",
show_edges=True,
edge_color="red" if picked else ec,
line_width=2.5 if picked else 1.0,
)
actor = self._plotter.add_mesh(pd, **kwargs)
self._pvdata_to_name[actor.GetAddressAsString("")] = name
self._plotter.render()
def _highlight_mesh_patch(self, patch_name: str | None):
"""Redraw the loaded boundary patches with one highlighted.
``patch_name=None`` draws every patch unhighlighted — used when
Select Patch mode is turned on so the per-patch geometry exists for
picking. Actors are registered in ``_pvdata_to_name`` so a 3D click
maps back to a patch name (and then to a table row).
"""
self._plotter.clear()
ec = self._edge_color()
mode = self._current_mode()
self._pvdata_to_name.clear()
for i, (name, pd) in enumerate(self._mesh_patches.items()):
picked = name == patch_name
color = _HIGHLIGHT_COLOR if picked else PATCH_COLORS[i % len(PATCH_COLORS)]
data = pd.copy()
data.cell_data["color"] = np.tile(color, (data.n_cells, 1))
kwargs = dict(scalars="color", rgb=True, label=name, smooth_shading=True)
if mode == "Wireframe":
kwargs.update(style="wireframe", line_width=2.5 if picked else 1.0)
else:
kwargs.update(
style="surface", show_edges=True,
edge_color="red" if picked else ec,
line_width=2.5 if picked else 1.0,
)
actor = self._plotter.add_mesh(data, **kwargs)
self._pvdata_to_name[actor.GetAddressAsString("")] = name
self._plotter.render()
def _disable_picking_safely(self):
if self._plotter is None:
return
try:
self._plotter.disable_picking()
except Exception:
pass
def _on_pick_toggled(self, checked: bool):
if not self._plotter_ready:
return
if checked:
self._measure_check.blockSignals(True)
self._measure_check.setChecked(False)
self._measure_check.blockSignals(False)
self._measure_points = []
self._disable_picking_safely()
if self._plotter is not None:
self._plotter.unsetCursor()
# A loaded case mesh shows the internal volume as a single actor,
# which carries no per-patch identity to pick. Draw the boundary
# patches so a 3D click can be mapped back to a table row.
if not self._showing_cad and self._mesh_patches:
self._highlight_mesh_patch(None)
try:
self._plotter.enable_mesh_picking(
callback=self._on_mesh_picked,
show=False,
show_message=False,
left_clicking=True,
use_actor=True,
)
except Exception as exc:
logger.warning("enable_mesh_picking failed: %s", exc)
else:
self._disable_picking_safely()
def _on_measure_toggled(self, checked: bool):
if not self._plotter_ready:
return
if checked:
self._pick_check.blockSignals(True)
self._pick_check.setChecked(False)
self._pick_check.blockSignals(False)
self._measure_points = []
self._disable_picking_safely()
try:
# enable_surface_point_picking uses a vtkCellPicker, so the
# callback always receives a real world-space point on the
# surface of whatever is displayed (CAD or mesh, any
# representation). The previous enable_point_picking call
# passed use_marker=True, which PyVista 0.48 forwards to
# add_mesh -> TypeError -> the pick callback never ran.
self._plotter.enable_surface_point_picking(
callback=self._on_point_picked,
show_message=False,
show_point=False,
left_clicking=True,
picker="cell",
)
self._plotter.setCursor(Qt.CrossCursor)
except Exception as exc:
logger.warning("enable_surface_point_picking failed: %s", exc)
self._measure_check.blockSignals(True)
self._measure_check.setChecked(False)
self._measure_check.blockSignals(False)
return
self.measure_hint.emit(
"Click two points on the model to measure; unchecking "
"Measure (or Clear) removes the markers."
)
else:
self._measure_points = []
self._disable_picking_safely()
if self._plotter is not None:
self._plotter.unsetCursor()
# Unchecking Measure removes every measurement - markers, tags
# and the summary overlay (user report: they stayed on screen
# after the tool was switched off; once measured, the clutter
# is not wanted).
self._clear_measurements()
def _marker_radius(self) -> float:
"""A point-marker radius scaled to the current scene size."""
try:
b = self._plotter.bounds
diag = (
(b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2
) ** 0.5
if diag > 0:
return diag * 0.006
except Exception:
pass
return 0.01
def _on_point_picked(self, point):
pt = np.asarray(point, dtype=np.float64)[:3]
if self._plotter is None:
return
radius = self._marker_radius()
self._measure_points.append(pt)
marker = self._plotter.add_mesh(
pv.Sphere(radius=radius, center=pt),
color="red", pickable=False,
name=f"_measure_point_{len(self._measure_actors)}",
)
self._measure_actors.append(marker)
if len(self._measure_points) >= 2:
p1, p2 = self._measure_points[-2], self._measure_points[-1]
dist = float(np.linalg.norm(p2 - p1))
self._measure_index += 1
label = f"D{self._measure_index}"
line = self._plotter.add_lines(
np.array([p1, p2]), color="yellow", width=3,
)
self._measure_actors.append(line)
# Anchor the tag just off the midpoint, staggered by measurement
# index, so successive labels never sit on the line or each other.
try:
b = self._plotter.bounds
diag = (
(b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2
) ** 0.5
except Exception:
diag = 1.0
offset = np.array([
0.0, 0.0, diag * (0.03 + 0.02 * ((self._measure_index - 1) % 5)),
])
try:
tag = self._plotter.add_point_labels(
[(p1 + p2) / 2.0 + offset],
[f"{label}: {_format_distance(dist)}"],
font_size=11,
text_color="yellow",
always_visible=True,
name=f"_measure_label_{self._measure_index}",
)
self._measure_actors.append(tag)
except Exception as exc:
logger.debug("add_point_labels failed: %s", exc)
self._measurements.append((label, dist))
self._update_measure_summary()
self._plotter.render()
self.distance_measured.emit(f"{label}: {dist:.4f} m")
self._measure_points = []
else:
self._plotter.render()
def _clear_measure_actors(self):
if self._plotter:
for actor in self._measure_actors:
try:
self._plotter.remove_actor(actor)
except Exception:
pass
self._measure_actors = []
def _clear_measurements(self):
"""Clear every measurement: markers, tags and the summary overlay."""
self._measure_points = []
self._clear_measure_actors()
self._measurements = []
self._measure_index = 0
self._update_measure_summary()
if self._plotter is not None:
self._plotter.render()
def _update_measure_summary(self):
if not self._measurements:
self._measure_summary.setVisible(False)
self._measure_clear_btn.setEnabled(False)
return
self._measure_summary.setText(
"\n".join(
f"{label}: {_format_distance(value)}"
for label, value in self._measurements
)
)
self._measure_summary.setVisible(True)
self._measure_clear_btn.setEnabled(True)
self._position_measure_summary()
def _position_measure_summary(self):
if not self._measurements or self._plotter is None:
return
self._measure_summary.adjustSize()
g = self._plotter.geometry()
x = g.x() + g.width() - self._measure_summary.width() - 12
y = g.y() + 12
self._measure_summary.move(max(0, x), max(0, y))
self._measure_summary.raise_()
# Boundary layers are visible through the mesh itself (the dense
# edge band at the wall in Surface/Surface-with-Edges), exactly like
# the previous release - no overlay colouring, no scalar bar (user
# request: the orange overlay was unreadable).
# ------------------------------------------------------------------
# Patch list panel (BaramMesh-style): name / faces / auto type.
# Row <-> 3D highlight stay in sync through highlight_patch() and
# face_picked; neither path resets the camera.
# ------------------------------------------------------------------
def _populate_patch_panel(self, entries: list[tuple[str, int, str]]):
self._patch_table.blockSignals(True)
self._patch_table.setRowCount(0)
self._patch_names = []
for name, n_faces, ptype in entries:
row = self._patch_table.rowCount()
self._patch_table.insertRow(row)
name_item = QTableWidgetItem(name)
# Both CAD and generated-mesh patch names are editable now: a
# generated mesh writes the new name back to
# constant/polyMesh/boundary (see mesh_patch_renamed / main window).
name_item.setFlags(name_item.flags() | Qt.ItemIsEditable)
self._patch_table.setItem(row, 0, name_item)
faces_item = QTableWidgetItem(f"{int(n_faces):,}")
faces_item.setFlags(faces_item.flags() & ~Qt.ItemIsEditable)
faces_item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self._patch_table.setItem(row, 1, faces_item)
type_item = QTableWidgetItem(ptype)
type_item.setFlags(type_item.flags() & ~Qt.ItemIsEditable)
self._patch_table.setItem(row, 2, type_item)
self._patch_names.append(name)
self._patch_table.blockSignals(False)
self._patch_panel.setVisible(bool(entries))
def _clear_patch_panel(self):
self._patch_table.blockSignals(True)
self._patch_table.setRowCount(0)
self._patch_table.blockSignals(False)
self._patch_names = []
self._patch_panel.setVisible(False)
def _select_patch_row(self, patch_name: str):
"""Select the row for *patch_name* without re-triggering highlight."""
if patch_name not in self._patch_names:
return
row = self._patch_names.index(patch_name)
if row == self._patch_table.currentRow():
return
self._patch_table.blockSignals(True)
self._patch_table.setCurrentCell(row, 0)
self._patch_table.blockSignals(False)
def _on_patch_row_selected(self):
row = self._patch_table.currentRow()
if 0 <= row < len(self._patch_names):
self.highlight_patch(self._patch_names[row])
# Names may not contain the OpenFOAM structural characters, quotes, or
# whitespace (same rule the 3D-click rename has always enforced).
_INVALID_PATCH_NAME_RE = re.compile(r'[;{}"/\s]')
def _restore_patch_name(self, row: int, name: str | None = None) -> None:
"""Put *name* (or the tracked original) back into a Name cell."""
if name is None:
name = self._patch_names[row] if 0 <= row < len(self._patch_names) else ""
self._patch_rename_guard = True
try:
item = self._patch_table.item(row, 0)
if item is not None:
item.setText(name)
finally:
self._patch_rename_guard = False
[docs]
def revert_patch_name(self, current_name: str, original_name: str) -> None:
"""Undo a generated-mesh rename the writer refused (table + tracking).
Called by the main window when writing the boundary file fails, so the
Name cell never shows a name that is not on disk.
"""
if current_name in self._patch_names:
row = self._patch_names.index(current_name)
self._patch_names[row] = original_name
self._restore_patch_name(row, original_name)
def _on_patch_item_changed(self, item: QTableWidgetItem) -> None:
"""Commit a patch rename or revert an illegal edit.
CAD patches emit ``patch_renamed`` (mesh metadata only). Generated-mesh
patches emit ``mesh_patch_renamed``; the main window writes the new name
to constant/polyMesh/boundary (backing it up first) and refreshes.
"""
if self._patch_rename_guard or item.column() != 0:
return
row = item.row()
if not (0 <= row < len(self._patch_names)):
return
old_name = self._patch_names[row]
new_name = item.text().strip()
if not new_name:
self._restore_patch_name(row, old_name)
logger.warning("Patch name cannot be empty or whitespace.")
return
if self._INVALID_PATCH_NAME_RE.search(new_name):
self._restore_patch_name(row, old_name)
logger.warning(
"Invalid patch name '%s': must not contain ; { } \" / or "
"whitespace.", new_name,
)
return
if new_name == old_name:
return
if new_name in self._patch_names:
self._restore_patch_name(row, old_name)
logger.warning("Patch name '%s' is already in use.", new_name)
return
self._patch_names[row] = new_name
if self.is_showing_cad():
self.patch_renamed.emit(old_name, new_name)
else:
self.mesh_patch_renamed.emit(old_name, new_name)
[docs]
def apply_case_patch_rename(self, old_name: str, new_name: str) -> None:
"""Remap an already-committed generated-mesh rename (table already has
the new text). Keeps the 3D highlight/label maps consistent."""
if old_name in self._mesh_patches:
self._mesh_patches[new_name] = self._mesh_patches.pop(old_name)
role = self._patch_roles.pop(old_name, None)
if role is not None:
self._patch_roles[new_name] = role
def _on_patch_item_double_clicked(self, item: QTableWidgetItem) -> None:
"""No-op: every Name cell is editable (CAD metadata or case boundary)."""
return
def _reload_patch_panel_async(self):
"""Load the case boundary patches (background) and fill the panel."""
case_dir = self._mesh_case_dir
if not case_dir:
self._clear_patch_panel()
return
def work(worker):
return (
read_openfoam_mesh_patches(case_dir),
_patch_type_map(Path(case_dir)),
_inferred_patch_roles(Path(case_dir)),
)
def on_done(_name, payload):
patches, types, roles = payload
if not patches:
self._mesh_patches = {}
self._patch_roles = {}
self._clear_patch_panel()
return
self._mesh_patches = dict(patches)
self._patch_roles = dict(roles or {})
self._populate_patch_panel([
(name, int(pd.n_cells), self._display_patch_type(name, types, roles))
for name, pd in patches.items()
])
def on_failed(_name, msg):
logger.debug("Patch panel load failed: %s", msg)
self._vtk_tasks.submit(
"patch_panel", FunctionWorker(work),
on_finished=on_done, on_failed=on_failed,
heartbeat_timeout_s=600.0,
)
def _display_patch_type(self, name: str, types: dict, roles: dict) -> str:
"""Type column for a generated mesh: the INFERRED role when available.
Raw GMSH ``surface_N`` patches carry no name/type information, so the
name/type fallbacks in ``detect_patch_type`` return "other". The
geometric role inference (inlet/outlet/wall) is what the BL itself
uses, so show that instead.
"""
role = (roles or {}).get(name)
if role in _PATCH_TYPE_BY_ROLE:
return _PATCH_TYPE_BY_ROLE[role]
return detect_patch_type(name, (types or {}).get(name, ""))
[docs]
def start_refinement_pick(self):
"""Enter refinement-pick mode: click a point on the mesh to set
the centre of a manual refinement zone. Emits
``refinement_point_picked(x, y, z)`` on first pick, then
automatically exits pick mode."""
if self._plotter is None or not self._plotter_ready:
return
self._refinement_pick_active = True
# Disable other pick modes
self._pick_check.blockSignals(True)
self._pick_check.setChecked(False)
self._pick_check.blockSignals(False)
self._measure_check.blockSignals(True)
self._measure_check.setChecked(False)
self._measure_check.blockSignals(False)
self._measure_points = []
self._disable_picking_safely()
try:
self._plotter.enable_surface_point_picking(
callback=self._on_refinement_point_picked,
show_message=False,
show_point=False,
color="cyan",
point_size=12,
left_clicking=True,
picker="cell",
)
except Exception as exc:
logger.warning("start_refinement_pick failed: %s", exc)
self._refinement_pick_active = False
def _on_refinement_point_picked(self, point):
"""Handle a point pick in refinement mode: emit coordinates and exit."""
pt = np.asarray(point, dtype=np.float64)[:3]
# Show a visual marker at the picked point
if self._plotter is not None:
r = self._marker_radius()
self._plotter.add_mesh(
pv.Sphere(radius=r, center=pt),
color="cyan", opacity=0.7, pickable=False,
)
self._plotter.render()
self._refinement_pick_active = False
self._disable_picking_safely()
self.refinement_point_picked.emit(float(pt[0]), float(pt[1]), float(pt[2]))
[docs]
def show_refinement_zones(self, zones: list):
"""Display detected refinement zones as semi-transparent cyan spheres."""
if self._plotter is None or not self._cad_meshes:
return
# Remove previous refinement zone actors
for attr in ("_refinement_zone_actors",):
for actor in getattr(self, attr, []):
try:
self._plotter.remove_actor(actor)
except Exception:
pass
self._refinement_zone_actors = []
for z in zones:
cx, cy, cz = z.centre
r = z.radius
sphere = self._plotter.add_mesh(
pv.Sphere(radius=r, center=(cx, cy, cz)),
color="cyan", opacity=0.25, style="wireframe",
)
self._refinement_zone_actors.append(sphere)
if zones:
self._plotter.render()
def _on_mesh_picked(self, actor):
# use_actor=True (set in _on_pick_toggled) means `actor` is the
# picked vtkActor. Matching by the *mesh's* memory_address used to
# be used here, but PyVista internally copies/repacks the polydata
# when rendering with `scalars=..., rgb=True` (as _display_cad and
# highlight_patch always do) — the mapper's input dataset ends up
# with a DIFFERENT address than the pv.PolyData we built, so that
# lookup never matched and Select Patch silently did nothing.
# The actor object itself is never copied, so match on that instead.
#
# No `picked_actor` fallback on a None actor: the plotter's picker
# keeps the last actor on a miss, so the fallback re-selected the
# previous patch on every empty click (part of the un-clearable
# selection bug, user report).
if actor is None:
return
addr = actor.GetAddressAsString("")
name = self._pvdata_to_name.get(addr)
if name is None:
logger.debug("Picked actor addr=%s not in mapping", addr)
return
if name == getattr(self, "_selected_patch_name", None):
# Clicking the highlighted patch again clears it (toggle).
self._clear_patch_selection()
return
logger.info("Picked patch '%s'", name)
self._select_patch_row(name)
self.face_picked.emit(name)
[docs]
def is_showing_cad(self) -> bool:
"""True while the CAD surface is the displayed geometry."""
return bool(getattr(self, "_showing_cad", True))
[docs]
def set_rendering_paused(self, paused: bool) -> None:
"""Pause the periodic 3D re-render while a meshing run saturates the
CPU.
The viewer's 30 FPS auto-update competes with the meshing workers
for the GUI thread and makes interaction stutter; pausing it for
the duration of a run (the log flood was the other, bigger source -
fixed in the log panel) keeps the window responsive. The display
itself is untouched and rendering resumes immediately when done.
"""
if self._plotter is None:
return
try:
self._plotter.auto_update = 0.0 if paused else 30.0
except Exception as exc: # noqa: BLE001 - viewer keeps working
logger.debug("auto_update toggle failed: %s", exc)
def _install_click_deselect(self) -> None:
"""Clicking empty 3D space clears the current patch selection.
A patch selected from the table (or by a 3D click) used to stay
highlighted forever: clicking the empty background did nothing,
which made the selection useless (user report). A left-click that
hits no actor now clears both the highlight and the table row.
"""
if self._plotter is None:
return
try:
self._click_observer = self._plotter.add_observer(
"LeftButtonPressEvent", self._on_viewer_click
)
except Exception as exc: # noqa: BLE001 - viewer keeps working
logger.debug("click-deselect observer unavailable: %s", exc)
def _on_viewer_click(self, *_args) -> None:
"""Left click anywhere: if nothing is hit, clear the selection.
Uses a FRESH vtkPropPicker instead of ``pick_mouse_position()``:
the VTK picker keeps its last actor on a miss, so the old code
could never see "nothing" and the selection was un-clearable
(user report). A new picker has no previous state, so an empty
click reliably returns no actor.
"""
if self._plotter is None:
return
if getattr(self, "_selected_patch_name", None) is None:
return
actor = None
try:
import vtk
x, y = self._plotter.iren.get_event_position()
picker = vtk.vtkPropPicker()
picker.Pick(x, y, 0, self._plotter.renderer)
actor = picker.GetActor()
except Exception: # noqa: BLE001 - deselect is best effort
actor = None
if actor is None:
self._clear_patch_selection()
def _clear_patch_selection(self) -> None:
"""Remove the patch highlight and clear the table selection."""
self._selected_patch_name = None
table = getattr(self, "_patch_table", None)
if table is not None:
table.blockSignals(True)
try:
table.clearSelection()
table.setCurrentItem(None)
finally:
table.blockSignals(False)
# Repaint without the highlight. For a case mesh this re-renders the
# cached patches / VTU (no foamToVTK re-run).
self._redisplay_current()
def _current_mode(self) -> str:
idx = self._view_selector.currentIndex()
if 0 <= idx < len(VIEW_MODES):
return VIEW_MODES[idx]
return "Surface" if getattr(self, "_showing_cad", True) else "Surface with Edges"
def _on_view_changed(self, index: int):
if index < 0 or not self._plotter_ready:
return
self._disable_picking_safely()
self._pick_check.blockSignals(True)
self._pick_check.setChecked(False)
self._pick_check.blockSignals(False)
self._view_selector.blockSignals(True)
try:
self._render_current_mode()
finally:
self._view_selector.blockSignals(False)
def _render_current_mode(self):
"""Render whatever is currently shown (CAD or mesh) using the
representation selected in the "Display" combo."""
if self._plotter is None:
return
if getattr(self, "_showing_cad", True) and self._cad_meshes:
self._display_cad()
return
if not self._mesh_case_dir:
if self._cad_meshes:
self._display_cad()
return
mode = self._current_mode()
if mode == "Wireframe":
self._display_mesh()
elif mode == "Surface with Edges":
self._display_surface_edges()
else:
self._display_mesh_surface()
def _redisplay_current(self):
if self._plotter is None:
return
if self._view_selector.currentIndex() < 0:
return
self._render_current_mode()
def _on_section_toggled(self, checked: bool):
self._section_enabled = checked
if self._plotter is None or not self._plotter_ready:
return
if self._section_enabled and getattr(self, "_showing_cad", True):
total_faces = sum(len(m.faces) for m in self._cad_meshes)
if total_faces > _MAX_CLIP_FACES:
self._log_clip_too_big(total_faces)
self._section_check.blockSignals(True)
self._section_check.setChecked(False)
self._section_check.blockSignals(False)
self._section_enabled = False
return
self._redisplay_current()
def _log_clip_too_big(self, n_faces: int) -> None:
logger.warning(
"Section Cut disabled: CAD geometry has %d faces (cap=%d). "
"Reduce the CAD tessellation to enable.",
n_faces, _MAX_CLIP_FACES,
)
@staticmethod
def _section_clip_args(bounds) -> tuple[tuple[float, float, float], tuple[float, float, float]]:
"""Return (normal, origin) for the section plane, centred on bounds."""
origin = (
(bounds[0] + bounds[1]) * 0.5,
(bounds[2] + bounds[3]) * 0.5,
(bounds[4] + bounds[5]) * 0.5,
)
return (1.0, 0.0, 0.0), origin
def _clip_dataset(self, dataset, normal, origin):
"""Clip ``dataset`` with an explicit plane, keeping the geometry on
one side. Falls back to the unclipped dataset on any failure so a
section toggle can never blank the view."""
try:
clipped = dataset.clip(
normal=normal, origin=origin, invert=True, crinkle=False,
)
if getattr(clipped, "n_points", 0) > 0:
return clipped
except Exception as exc:
logger.warning("Section clip failed: %s", exc)
return dataset
def _apply_section_clip(self, dataset):
if not self._section_enabled or dataset is None:
return dataset
normal, origin = self._section_clip_args(dataset.bounds)
return self._clip_dataset(dataset, normal, origin)
@staticmethod
def _combined_bounds(datasets):
"""Union of the bounds of several datasets, or None if all empty."""
bounds = [d.bounds for d in datasets if getattr(d, "n_points", 0) > 0]
if not bounds:
return None
return (
min(b[0] for b in bounds), max(b[1] for b in bounds),
min(b[2] for b in bounds), max(b[3] for b in bounds),
min(b[4] for b in bounds), max(b[5] for b in bounds),
)
def _build_combined_pvdata(self) -> pv.PolyData | None:
if not self._cad_meshes:
return None
all_verts: list[np.ndarray] = []
all_faces: list[np.ndarray] = []
all_colors: list[np.ndarray] = []
v_offset = 0
for i, mesh in enumerate(self._cad_meshes):
color = PATCH_COLORS[i % len(PATCH_COLORS)]
nv = len(mesh.vertices)
nf = len(mesh.faces)
all_verts.append(mesh.vertices)
all_faces.append(mesh.faces + v_offset)
v_offset += nv
all_colors.append(np.tile(color, (nf, 1)))
if not all_verts:
return None
verts_arr = np.vstack(all_verts).astype(np.float64)
faces_arr = np.vstack(all_faces).astype(np.int32)
colors_arr = np.vstack(all_colors).astype(np.float64)
faces_pv = np.hstack([np.full((len(faces_arr), 1), 3), faces_arr]).astype(np.int32)
pd = pv.PolyData(verts_arr, faces_pv)
pd.cell_data["color"] = colors_arr
return pd
def _display_cad(self):
if self._plotter is None or not self._cad_meshes:
return
self._plotter.clear()
ec = self._edge_color()
mode = self._current_mode()
self._pvdata_to_name.clear()
if self._section_enabled:
combined = self._build_combined_pvdata()
if combined is not None:
combined = self._apply_section_clip(combined)
kwargs = dict(scalars="color", rgb=True, smooth_shading=True)
if mode == "Wireframe":
kwargs.update(style="wireframe", line_width=1.0)
elif mode == "Surface with Edges":
kwargs.update(
style="surface", show_edges=True,
edge_color=ec, line_width=1.0,
)
else:
kwargs.update(style="surface")
self._plotter.add_mesh(combined, **kwargs)
self._plotter.view_isometric()
self._plotter.render()
return
for i, mesh in enumerate(self._cad_meshes):
name = mesh.metadata.get("name", f"patch_{i}")
color = PATCH_COLORS[i % len(PATCH_COLORS)]
pd = _trimesh_to_pydata(mesh, color)
kwargs = dict(scalars="color", rgb=True, label=name, smooth_shading=True)
if mode == "Wireframe":
kwargs.update(style="wireframe", line_width=1.0)
elif mode == "Surface with Edges":
kwargs.update(
style="surface", show_edges=True,
edge_color=ec, line_width=1.0,
)
else:
kwargs.update(style="surface")
actor = self._plotter.add_mesh(pd, **kwargs)
self._pvdata_to_name[actor.GetAddressAsString("")] = name
self._plotter.view_isometric()
self._plotter.render()
def _cancel_vtk_process(self):
"""Kill any running foamToVTK QProcess and its timeout timer.
Uses a short timeout to avoid blocking the main thread.
"""
if hasattr(self, "_vtk_timeout_timer") and self._vtk_timeout_timer:
self._vtk_timeout_timer.stop()
self._vtk_timeout_timer.deleteLater()
self._vtk_timeout_timer = None
if hasattr(self, "_vtk_process") and self._vtk_process:
if self._vtk_process.state() != QProcess.NotRunning:
self._vtk_process.kill()
self._vtk_process.waitForFinished(500)
self._vtk_process.deleteLater()
self._vtk_process = None
[docs]
def cancel_vtk_process(self):
"""Public alias used by the main window's Cancel handler."""
self._cancel_vtk_process()
def _start_vtk_qprocess(self, case_dir: Path, vtk_subdir: str,
on_finished: callable) -> None:
"""Start foamToVTK via QProcess. Calls ``on_finished(ok)`` when done."""
self._cancel_vtk_process()
# Show status in label instead of rendering to the plotter
self._stats_label.setText("Generating foamToVTK... (attendi 1-3 min)")
from polyfoammesh.config import OFConfig
cfg = OFConfig()
linux_case = cfg._quoted_linux_path(case_dir)
import shlex
env_quoted = shlex.quote(cfg.env_script)
cmd = cfg._build_wsl_cmd(
f"source {env_quoted} 2>/dev/null; cd {linux_case} && "
f"foamToVTK -constant -noZero -no-fields -overwrite -name {vtk_subdir}"
)
self._vtk_process = QProcess(self)
# No console window for this child either (frozen GUI has none).
from polyfoammesh.core.subprocess_quiet import quiet_qprocess
quiet_qprocess(self._vtk_process)
# Use separate channels so stderr is readable independently
self._vtk_process.setProcessChannelMode(QProcess.SeparateChannels)
self._vtk_timeout_fired = False
self._vtk_process.finished.connect(
lambda ec, _exit_status: self._on_vtk_finished(
ec, case_dir, vtk_subdir, on_finished,
),
)
self._vtk_process.started.connect(lambda: logger.debug("foamToVTK QProcess started"))
program = cmd[0]
args = cmd[1:]
self._vtk_process.start(program, args)
self._vtk_timeout_timer = QTimer(self)
self._vtk_timeout_timer.setSingleShot(True)
self._vtk_timeout_timer.timeout.connect(self._on_vtk_timeout)
self._vtk_timeout_timer.start(180000)
def _on_vtk_timeout(self):
logger.error("foamToVTK QProcess timed out after 180s")
self._vtk_timeout_fired = True
self._mesh_display_in_progress = False
self._cancel_vtk_process()
self._show_mesh_too_large("foamToVTK timed out (>180s)")
def _on_vtk_finished(self, exit_code: int, case_dir: Path,
vtk_subdir: str, on_finished: callable) -> None:
if self._vtk_timeout_timer:
self._vtk_timeout_timer.stop()
if getattr(self, '_vtk_timeout_fired', False):
# Timeout already handled cleanup — skip stale callback
return
if exit_code == 0:
matches = _find_internal_vtu(case_dir, vtk_subdir)
if matches:
poly_dir = case_dir / "constant" / "polyMesh"
state = _poly_dir_state(poly_dir)
if state is not None:
try:
(case_dir / vtk_subdir / ".source_mtime").write_text(str(state))
except OSError:
pass
else:
try:
stderr = self._vtk_process.readAllStandardError() if self._vtk_process else b""
stderr_text = stderr.decode("utf-8", errors="replace")[-300:] if stderr else ""
except RuntimeError:
stderr_text = "(process already deleted)"
logger.warning("foamToVTK QProcess failed (rc=%d): %s", exit_code, stderr_text)
on_finished(exit_code == 0)
def _cancel_display_timeout(self):
"""Stop the display timeout timer if running."""
if self._display_timeout_timer is not None:
self._display_timeout_timer.stop()
self._display_timeout_timer.deleteLater()
self._display_timeout_timer = None
def _start_display_timeout(self, seconds: int = 90):
"""Start a timeout that shows the 'use ParaView' message if the
mesh display pipeline takes longer than ``seconds``."""
self._cancel_display_timeout()
self._display_timeout_timer = QTimer(self)
self._display_timeout_timer.setSingleShot(True)
self._display_timeout_timer.timeout.connect(
lambda: self._on_display_timeout(),
)
self._display_timeout_timer.start(seconds * 1000)
def _on_display_timeout(self):
"""Called when the mesh display pipeline times out."""
logger.warning("Mesh display timed out after 90s — showing fallback message")
self._mesh_display_in_progress = False
self._view_selector.setEnabled(False)
self._cancel_vtk_process()
self._show_mesh_too_large("Display pipeline timed out (>90s)")
def _display_mesh(self):
"""Render the whole internal volume as a wireframe ("Wireframe")."""
self._begin_mesh_display("internal", "Loading mesh (Wireframe)...")
def _display_surface_edges(self):
"""Render the mesh boundary as a filled surface with edges
(ParaView's "Surface with Edges")."""
self._begin_mesh_display(
"surface_edges", "Loading Surface with Edges...",
)
def _display_mesh_surface(self):
"""Render the mesh boundary as a smooth, edge-free surface."""
self._begin_mesh_display("surface", "Loading Surface...")
def _begin_mesh_display(self, vtu_mode: str, message: str):
"""Start the mesh display pipeline for the given representation,
guarded by a 90s safety timeout that falls back to the 'use
ParaView' message if the pipeline hangs."""
if self._plotter is None or not self._mesh_case_dir:
return
if getattr(self, "_mesh_display_in_progress", False):
logger.debug("%s already in progress — skipping duplicate call", vtu_mode)
return
self._mesh_display_in_progress = True
self._pending_vtu_mode = vtu_mode
# Show "Loading..." immediately, then chain async operations
try:
self._plotter.clear()
self._plotter.add_text(
message, color=self._text_color, font_size=14,
)
self._plotter.render()
except Exception as exc:
logger.error("Plotter failed to show loading message: %s", exc)
self._start_display_timeout(90)
QTimer.singleShot(0, self._step_vtu_for_mesh)
def _step_vtu_for_mesh(self):
"""Step 1: ensure VTU exists (async QProcess if needed), then load."""
self._do_step_vtu(
on_vtu_ready=lambda ok: QTimer.singleShot(0, self._step_mesh_patches),
)
def _do_step_vtu(self, on_vtu_ready: callable) -> None:
"""Check VTU cache; if stale/missing, start QProcess, else callback immediately.
If polyMesh files aren't visible yet (Windows WSL2 9P sync delay,
or a native write that hasn't landed yet), retries with increasing
delay up to 30s before giving up.
"""
if self._plotter is None or not self._mesh_case_dir:
return
case_dir = Path(self._mesh_case_dir)
poly_dir = case_dir / "constant" / "polyMesh"
# Use a shorter timeout here to avoid hanging the display pipeline
state = _poly_dir_state(poly_dir, max_retries=3, delay_ms=2000)
if state is None:
# Poly files not found yet; try again later or show loading message
logger.info("polyMesh files not found yet in %s — will retry via _do_load_patches", poly_dir)
on_vtu_ready(False)
return
vtk_subdir = "VTK_view"
marker = case_dir / vtk_subdir / ".source_mtime"
existing = _find_internal_vtu(case_dir, vtk_subdir)
if existing and marker.exists():
try:
if float(marker.read_text().strip()) == state:
on_vtu_ready(True)
return
except (ValueError, OSError):
pass
# If foamToVTK is already running, just attach the callback — don't
# kill and restart (that would waste 30-60s of progress).
vtk_proc = getattr(self, "_vtk_process", None)
if vtk_proc and vtk_proc.state() != QProcess.NotRunning:
logger.debug("foamToVTK already running — attaching callback to existing process")
# Disconnect old finished signal and reconnect with new callback
try:
vtk_proc.finished.disconnect()
except (RuntimeError, TypeError):
pass
vtk_proc.finished.connect(
lambda ec, _exit_status: self._on_vtk_finished(
ec, case_dir, vtk_subdir, on_vtu_ready,
),
)
return
logger.info("Starting foamToVTK for %s", case_dir)
self._start_vtk_qprocess(case_dir, vtk_subdir, on_vtu_ready)
def _step_mesh_patches(self):
"""Step 2: load mesh patches via fast path (VTU already generated) and display."""
if self._plotter is None or not self._mesh_case_dir:
return
QTimer.singleShot(0, lambda: self._do_load_patches(False))
@staticmethod
def _prepare_internal_vtu_grid(grid, mode: str):
"""Reduce the full-volume grid read from internal.vtu to what the
given representation should actually render.
"surface_edges" and "surface" must show ONLY the outer boundary of
the poly mesh — not every internal cell edge of the whole volume.
Before this, the surface views loaded the SAME full internal.vtu
and wireframed the entire volume, so a poly mesh with any real cell
count looked like solid static from outside: every internal edge of
every cell was superimposed in screen space, regardless of how well
graded the mesh actually was. extract_surface() on an
UnstructuredGrid is VTK's vtkGeometryFilter — it keeps the true
outer polygon faces (a poly cell's pentagon face stays a pentagon)
without triangulating them.
"internal" ("Wireframe") is returned unchanged — it exists
specifically to inspect internal structure.
algorithm="dataset_surface" is pinned explicitly: PyVista warns
that the default will change in a future release, and a silent
behaviour change here would be exactly the kind of "why does the
mesh look different now" regression this fix exists to prevent.
"""
if mode in ("surface_edges", "surface"):
return grid.extract_surface(algorithm="dataset_surface")
return grid
def _load_internal_vtu_async(self, vtu_path: Path, mode: str) -> None:
"""Read + optionally decimate a (possibly huge) internal.vtu in a
background task; render on the GUI thread when ready."""
def work(worker):
grid = pv.read(str(vtu_path))
full_grid = grid
grid = self._prepare_internal_vtu_grid(grid, mode)
n_cells = grid.n_cells
threshold, target = self._decimation_settings()
show_dec = n_cells > threshold
if show_dec:
# Cap the rendered surface so the GPU/OpenGL render on the
# GUI thread can never hang the whole app: extremely large
# grids decimate to ~1M cells instead of the 20% target.
if n_cells > 10_000_000:
target = min(target, 1_000_000 / n_cells)
try:
grid = grid.decimate_pro(target)
except Exception:
pass
return {
"grid": grid, "n": n_cells, "show_dec": show_dec,
"full": full_grid,
}
def on_done(_name, payload):
self._mesh_display_in_progress = False
self._cancel_display_timeout()
grid = payload["grid"]
n_cells = payload["n"]
show_dec = payload["show_dec"]
ec = self._edge_color()
try:
dataset = self._apply_section_clip(grid)
self._plotter.clear()
# "internal" (Wireframe) renders every internal cell edge
# of the WHOLE volume on purpose — that view exists to see
# through the mesh. A filled/shaded surface there would hide
# the interior it's meant to show, so it stays a bare
# wireframe (lines only, no fill).
if mode == "internal":
self._plotter.add_mesh(
dataset, style="wireframe", color=_MESH_COLOR,
show_edges=True, edge_color=ec,
line_width=0.6 if not show_dec else 0.8,
opacity=1.0,
)
else:
# ParaView "Surface"/"Surface With Edges": a shaded
# fill with the TRUE polygon edges outlined on top
# when requested. `grid` is already the boundary-only
# PolyData from _prepare_internal_vtu_grid, whose cells
# are the real n-gon faces (verified in
# test_viewer_surface_only.py).
self._plotter.add_mesh(
dataset, style="surface",
show_edges=(mode == "surface_edges"),
edge_color=ec, color=_MESH_COLOR,
line_width=0.6 if not show_dec else 0.8,
opacity=1.0, lighting=True, smooth_shading=True,
)
if show_dec:
self._plotter.add_text(
f"Simplified view ({n_cells:,} cells). "
"The real mesh file is unchanged.",
color=self._text_color, font_size=10,
)
self._plotter.view_isometric()
self._plotter.render()
self._reload_patch_panel_async()
except Exception as exc:
logger.error("Plotter display failed (internal VTU): %s", exc)
self._show_mesh_too_large(f"Display error: {exc}")
def on_failed(_name, msg):
self._mesh_display_in_progress = False
self._cancel_display_timeout()
logger.warning("Failed to load internal VTU %s: %s", vtu_path, msg)
# Fall back to the boundary patches path.
QTimer.singleShot(0, self._do_load_patches)
self._vtk_tasks.submit(
"vtk_display", FunctionWorker(work),
on_finished=on_done, on_failed=on_failed,
heartbeat_timeout_s=600.0,
)
def _load_patches_async(self, mode: str = "patches") -> None:
"""Read boundary patches (foamToVTK VTP files or manual parser) in
a background task; render on the GUI thread when ready. Used as a
fallback when the internal volume VTU isn't available."""
case_dir = self._mesh_case_dir
def work(worker):
return read_openfoam_mesh_patches(case_dir)
def on_done(_name, patches):
self._mesh_retry_count = 0
self._cancel_display_timeout()
self._mesh_display_in_progress = False
if not patches:
self._handle_no_patches()
return
total_faces = sum(pd.n_cells for pd in patches.values())
logger.info(
"Loaded %d mesh patches (%d total faces) for %s",
len(patches), total_faces, case_dir,
)
self._mesh_patches = dict(patches)
types = _patch_type_map(Path(case_dir))
roles = _inferred_patch_roles(Path(case_dir))
self._patch_roles = dict(roles or {})
self._populate_patch_panel([
(name, int(pd.n_cells), self._display_patch_type(name, types, roles))
for name, pd in patches.items()
])
threshold, target = self._decimation_settings()
show_decimated = total_faces > threshold
repr_mode = getattr(self, "_pending_vtu_mode", "surface_edges")
try:
self._plotter.clear()
ec = self._edge_color()
normal, origin = None, None
if self._section_enabled:
bounds = self._combined_bounds(patches.values())
if bounds is not None:
normal, origin = self._section_clip_args(bounds)
for _i, (name, pd) in enumerate(patches.items()):
if show_decimated:
try:
pd = pd.decimate_pro(target)
except Exception:
pass
if normal is not None:
pd = self._clip_dataset(pd, normal, origin)
kwargs = dict(
scalars="color", rgb=True, label=name,
smooth_shading=(repr_mode != "internal"),
)
if repr_mode == "internal":
kwargs.update(
style="wireframe", show_edges=True, edge_color=ec,
)
elif repr_mode == "surface_edges":
kwargs.update(
style="surface", show_edges=True, edge_color=ec,
)
else:
kwargs.update(style="surface")
actor = self._plotter.add_mesh(pd, **kwargs)
self._pvdata_to_name[actor.GetAddressAsString("")] = name
if show_decimated:
self._plotter.add_text(
f"Simplified view ({total_faces:,} \u2192 ~{int(total_faces*self.DECIMATE_TARGET):,} faces). "
"The real mesh file is unchanged.",
color=self._text_color, font_size=10,
)
self._plotter.view_isometric()
self._plotter.render()
except Exception as exc:
logger.error("Plotter display failed (mesh patches): %s", exc)
self._show_mesh_too_large(f"Display error: {exc}")
def on_failed(_name, msg):
self._mesh_display_in_progress = False
self._cancel_display_timeout()
logger.warning("Mesh patches load failed: %s", msg)
self._show_mesh_too_large(f"Load error: {msg}")
self._vtk_tasks.submit(
"vtk_display", FunctionWorker(work),
on_finished=on_done, on_failed=on_failed,
heartbeat_timeout_s=600.0,
)
def _do_load_patches(self, _unused: bool = False):
"""Load and display the mesh for the pending representation.
Preference: the internal volume cells (internal.vtu — the actual
3D polyhedral cells after tet→poly). "Wireframe" renders the whole
volume as lines; "Surface"/"Surface with Edges" render only the
boundary. Falls back to the boundary surface patches when the
volume VTU isn't available.
"""
self._mesh_display_in_progress = False
case_dir = Path(self._mesh_case_dir) if self._mesh_case_dir else None
if case_dir is None:
return
# --- Preferred: internal 3D cells ----------------------------------
vtk_dir = case_dir / "VTK_view"
internal_vtu = None
if vtk_dir.exists():
candidates = _find_internal_vtu(case_dir)
if candidates:
internal_vtu = candidates[0]
if internal_vtu is not None:
# Reading + decimating a big internal.vtu runs in a background
# task; the plotter (GUI thread only) renders when it's ready.
self._load_internal_vtu_async(
internal_vtu, getattr(self, "_pending_vtu_mode", "surface_edges"),
)
return
# --- Fallback: boundary surface patches ----------------------------
self._load_patches_async()
[docs]
def cancel_mesh_display(self) -> None:
"""Stop any pending mesh-view retry/timeout. Called from main_window
when the user cancels the meshing run."""
self._mesh_cancelled = True
self._cancel_display_timeout()
def _handle_no_patches(self) -> None:
"""Called when the patch load came back empty: decide whether to
trigger foamToVTK or show the 'use ParaView' message."""
if self._mesh_cancelled:
return
if self._foam_to_vtk_attempted:
self._foam_to_vtk_attempted = False
self._show_mesh_too_large("foamToVTK unavailable (use ParaView)")
return
if self._mesh_case_dir and self._mesh_retry_count < self._mesh_retry_max:
poly_dir = Path(self._mesh_case_dir) / "constant" / "polyMesh"
if poly_dir.is_dir():
self._mesh_retry_count += 1
logger.debug(
"Mesh load retry %d/%d (polyDir=%s)",
self._mesh_retry_count, self._mesh_retry_max, poly_dir,
)
# Trigger foamToVTK on first retry — but only once.
case_dir = Path(self._mesh_case_dir)
vtk_dir = case_dir / "VTK_view"
has_vtu = bool(_find_internal_vtu(case_dir))
if self._mesh_retry_count == 1 and not has_vtu and not self._foam_to_vtk_attempted:
logger.info("VTU not found — starting foamToVTK before next retry")
self._foam_to_vtk_attempted = True
self._do_step_vtu(
on_vtu_ready=lambda ok: QTimer.singleShot(
2000 if ok else 500,
lambda: self._do_load_patches(False),
),
)
return
QTimer.singleShot(
2000, lambda: self._do_load_patches(False),
)
return
self._mesh_retry_count = 0
self._foam_to_vtk_attempted = False
self._show_mesh_too_large("VTU unavailable (use ParaView)")
def _show_mesh_too_large(self, reason: str = "") -> None:
"""Display 'mesh too large' message via label instead of plotter text.
Avoids ``render()`` in the plotter which can hang with OpenGL issues.
"""
self._mesh_display_in_progress = False
self._view_selector.setEnabled(False)
self._view_selector.blockSignals(True)
self._view_selector.setCurrentIndex(-1)
self._view_selector.blockSignals(False)
msg = "Use ParaView to view the mesh"
if reason:
msg += f" ({reason})"
self._stats_label.setText(msg)
logger.info("Mesh display unavailable%s", f" ({reason})" if reason else "")
[docs]
def show_cad(self, meshes: list[trimesh.Trimesh]):
self._cad_meshes = list(meshes)
self._showing_cad = True
self._mesh_patches = {}
entries = []
for i, mesh in enumerate(self._cad_meshes):
name = mesh.metadata.get("name", f"patch_{i}")
entries.append((name, len(mesh.faces), detect_patch_type(name)))
self._populate_patch_panel(entries)
if not self._plotter_ready:
return
self._view_selector.setEnabled(True)
self._view_selector.blockSignals(True)
self._view_selector.setCurrentIndex(-1)
self._view_selector.blockSignals(False)
# CAD default representation is "Surface".
self._view_selector.setCurrentIndex(VIEW_MODES.index("Surface"))
if self._plotter:
self._plotter.reset_camera()
# Keep this high (10M) — meshes under 10M cells load fine via
# foamToVTK + cached VTU reading. The manual parser fallback
# is only used when foamToVTK hasn't run yet (first view).
MAX_VIEWER_CELLS = 10_000_000
# When cells > this threshold, show a decimated surface mesh instead
# of the full volume. The real mesh file is never touched.
DECIMATE_THRESHOLD = 2_000_000
# Target fraction of original cells after decimation
DECIMATE_TARGET = 0.2
def _decimation_settings(self) -> tuple[float, float]:
"""Return the fixed "Auto" decimation policy: decimate only above
DECIMATE_THRESHOLD, to DECIMATE_TARGET. The user-facing combo was
removed, so this always yields the Auto behaviour and the real
mesh file is never touched."""
return float(self.DECIMATE_THRESHOLD), float(self.DECIMATE_TARGET)
def _load_stats_async(self, case_dir: Path):
"""Load mesh stats in the background (deferred via timer)."""
try:
stats = read_openfoam_mesh_stats(case_dir)
except Exception as exc:
logger.warning("Failed to read mesh stats: %s", exc)
stats = {"points": 0, "faces": 0, "cells": 0}
total = stats["points"] + stats["faces"] + stats["cells"]
if total > 0:
self._stats_label.setText(
f"P:{stats['points']:,} F:{stats['faces']:,} C:{stats['cells']:,}"
)
else:
self._stats_label.setText("")
if not self._plotter_ready:
return
if stats["cells"] > self.MAX_VIEWER_CELLS:
self._show_mesh_too_large(
f"{stats['cells']:,} cells (max={self.MAX_VIEWER_CELLS:,})"
)
return
self._view_selector.setEnabled(True)
# Do NOT set the view selector here — _display_mesh() is already
# scheduled via QTimer from show_mesh(). Setting it here triggers
# _on_view_changed → _display_mesh, duplicating the foamToVTK launch
# and causing the first process to be killed (race condition).
def _delayed_display_mesh(self):
"""Deferred mesh rendering - no-ops if view selector was disabled
(e.g. mesh too large). Called via QTimer.singleShot from show_mesh()
so the stats label paints before the heavy VTK pipeline starts.
Dispatches on the representation currently selected in the
"Display" combo so the rendered mesh matches the dropdown, and
routes to the CAD path when CAD is what is being shown.
"""
if not self._view_selector.isEnabled():
return
if getattr(self, "_showing_cad", False) and getattr(self, "_cad_meshes", None):
self._display_cad()
return
idx = self._view_selector.currentIndex()
mode = VIEW_MODES[idx] if 0 <= idx < len(VIEW_MODES) else "Surface with Edges"
if mode == "Wireframe":
self._display_mesh()
elif mode == "Surface":
self._display_mesh_surface()
else:
self._display_surface_edges()
[docs]
def show_mesh(self, case_dir: Path | str):
"""Show mesh — always regenerates VTU from current polyMesh.
Invalidates the VTU cache marker so foamToVTK always runs after
meshing/conversion, ensuring the viewer shows the CURRENT mesh
(poly after tet→poly conversion) and not a stale cached version.
"""
try:
self._mesh_case_dir = str(case_dir)
self._showing_cad = False
self._mesh_patches = {}
self._clear_patch_panel()
self._cancel_display_timeout()
self._mesh_display_in_progress = False
self._mesh_retry_count = 0
self._foam_to_vtk_attempted = False
self._mesh_cancelled = False
# Kill any foamToVTK still running from a previous display so the
# new mesh (e.g. the poly result after tet->poly conversion) is
# generated from scratch instead of racing the old process.
self._cancel_vtk_process()
# Invalidate VTU cache: delete entire VTK_view directory so
# foamToVTK regenerates from current polyMesh. Just deleting
# the marker is not enough — the old tet boundary VTP files
# remain alongside new poly ones, causing the viewer to show
# BOTH tet and poly patches simultaneously.
try:
import shutil
vtk_dir = Path(case_dir) / "VTK_view"
if vtk_dir.exists():
shutil.rmtree(vtk_dir, ignore_errors=True)
logger.debug("Deleted VTK_view cache for %s", case_dir)
except Exception:
pass
# Read stats for the label (fast, header-only 16KB reads)
try:
stats = read_openfoam_mesh_stats(Path(case_dir))
except Exception:
stats = {"points": 0, "faces": 0, "cells": 0}
total = stats["points"] + stats["faces"] + stats["cells"]
if total > 0:
self._stats_label.setText(
f"P:{stats['points']:,} F:{stats['faces']:,} C:{stats['cells']:,}"
)
else:
self._stats_label.setText("Mesh ready — usa Strumenti > Launch ParaView")
self._view_selector.setEnabled(True)
# A completed meshing run must switch away from the CAD surface
# view to the ParaView-style "Surface with Edges" mesh view —
# filled surfaces with visible edges, the standard readable mesh
# display. Leaving the CAD "Surface" selected made the finished
# mesh look like an opaque/translucent CAD overlay even though
# the mesh existed. Block the signal here because the deferred
# render below is the single display request for this new case.
self._view_selector.blockSignals(True)
self._view_selector.setCurrentIndex(VIEW_MODES.index("Surface with Edges"))
self._view_selector.blockSignals(False)
# Actually render the mesh (deferred so the stats label above
# paints first). _delayed_display_mesh no-ops if the view
# selector got disabled above (mesh too large).
QTimer.singleShot(50, self._delayed_display_mesh)
except Exception as exc:
logger.exception("show_mesh failed: %s", exc)
[docs]
def clear(self):
self._cad_meshes = []
self._mesh_case_dir = ""
self._mesh_patches = {}
self._showing_cad = True
self._pending_vtu_mode = "surface_edges"
self._pvdata_to_name.clear()
self._stats_label.setText("")
self._mesh_display_in_progress = False
self._section_enabled = False
self._section_check.blockSignals(True)
self._section_check.setChecked(False)
self._section_check.blockSignals(False)
self._pick_check.blockSignals(True)
self._pick_check.setChecked(False)
self._pick_check.blockSignals(False)
self._measure_check.blockSignals(True)
self._measure_check.setChecked(False)
self._measure_check.blockSignals(False)
self._clear_measurements()
self._clear_patch_panel()
# Drop refinement-box actors/widgets/labels (the plotter clear below
# removes the actors themselves; this resets our bookkeeping).
self.__init_ref_box_state()
self.stop_refinement_box_drag()
self._ref_box_actors = []
self._ref_box_data = []
self._ref_box_selected = None
self._ref_box_hover = None
if not self._plotter_ready:
return
self._disable_picking_safely()
self._view_selector.setEnabled(False)
self._plotter.clear()
self._plotter.show_axes()
self._plotter.render()
# ✅ F-011: rimosso set_clip_plane() (mai chiamato, logica unificata in _on_section_toggled)
# ------------------------------------------------------------------
# Manual refinement BOXES: translucent cuboids with a 3D box gizmo.
# Each box is a vtk BoxWidget (PyVista add_box_widget) - the standard VTK
# 3D widget with handles on every face/edge to drag-size the cuboid along
# each axis, plus translation. It cooperates with the camera interaction
# natively (a hand-rolled drag handler on top of the camera style was
# jittery/unreliable - seen live). The level selector in the panel is the
# only other user input; cell_size derives from it.
# ------------------------------------------------------------------
#: High-contrast colours so a refinement box can never be mistaken for
#: CAD geometry. Bright, solid, and deliberately different from the
#: patch palette used for the part itself. Named colours (not hex) keep
#: gui/ free of hardcoded hex values (tests/test_design_system.py).
REF_BOX_FACE_COLOR = "darkorange" # bright orange, translucent
REF_BOX_EDGE_COLOR = "red" # bright red, thick wireframe
REF_BOX_SELECTED_FACE_COLOR = "gold" # brighter on hover/selection
REF_BOX_SELECTED_EDGE_COLOR = "cyan" # cyan on hover/selection
REF_BOX_FACE_OPACITY = 0.18
REF_BOX_SELECTED_OPACITY = 0.32
def __init_ref_box_state(self):
if not hasattr(self, "_ref_box_actors"):
self._ref_box_actors = [] # list[dict] {face, edge, label}
if not hasattr(self, "_ref_box_widgets"):
self._ref_box_widgets = []
if not hasattr(self, "_ref_box_data"):
self._ref_box_data = []
if not hasattr(self, "_ref_box_selected"):
self._ref_box_selected = None
if not hasattr(self, "_ref_box_hover"):
self._ref_box_hover = None
if not hasattr(self, "_ref_box_mouse_observer"):
self._ref_box_mouse_observer = None
@staticmethod
def _ref_box_label(index: int, box: dict) -> str:
"""The 3D label drawn on a box, e.g. ``Box 1 - L2``."""
try:
level = int(box.get("level", 2))
except (TypeError, ValueError):
level = 2
return f"Box {index + 1} - L{level}"
@staticmethod
def _ref_box_bounds(box: dict) -> tuple:
return (
box["xmin"], box["xmax"], box["ymin"], box["ymax"],
box["zmin"], box["zmax"],
)
def _remove_ref_box_actors(self):
if self._plotter is None:
self._ref_box_actors = []
return
for entry in self._ref_box_actors:
for key in ("face", "edge", "label"):
actor = entry.get(key)
if actor is None:
continue
try:
self._plotter.remove_actor(actor)
except Exception:
pass
self._ref_box_actors = []
def _add_ref_box_label(self, index: int, box: dict):
"""A small always-visible 3D label sitting on top of the box."""
if self._plotter is None:
return None
cx = (box["xmin"] + box["xmax"]) / 2.0
cy = (box["ymin"] + box["ymax"]) / 2.0
try:
return self._plotter.add_point_labels(
[(cx, cy, box["zmax"])],
[self._ref_box_label(index, box)],
font_size=12,
text_color=self.REF_BOX_EDGE_COLOR,
always_visible=True,
name=f"_ref_box_label_{index}",
)
except Exception as exc: # noqa: BLE001
logger.debug("Refinement box label %d failed: %s", index, exc)
return None
def _add_ref_box_actors(self, index: int, box: dict) -> dict:
"""Build the translucent face, thick wireframe and label for a box."""
mesh = pv.Box(bounds=self._ref_box_bounds(box))
face = self._plotter.add_mesh(
mesh, color=self.REF_BOX_FACE_COLOR,
opacity=self.REF_BOX_FACE_OPACITY, style="surface",
pickable=True, show_edges=False,
)
edge = self._plotter.add_mesh(
mesh, color=self.REF_BOX_EDGE_COLOR, style="wireframe",
line_width=4, pickable=True,
)
return {"face": face, "edge": edge,
"label": self._add_ref_box_label(index, box)}
[docs]
def show_refinement_boxes(self, boxes: list):
"""Render refinement boxes as bright translucent cuboids with a label.
*boxes* is a list of ``{type:'box', xmin..zmax, level, cell_size}``.
Each is drawn as a translucent bright-orange volume plus a thick red
wireframe and a "Box N - Lx" 3D label, so it is unmistakable in the
viewport. Subsequent calls replace the previous rendering.
Drag-sizing is entered separately via start_refinement_box_drag().
"""
self.__init_ref_box_state()
self.stop_refinement_box_drag()
if self._plotter is None:
return
try:
self._plotter.disable_picking()
except Exception:
pass
self._remove_ref_box_actors()
self._ref_box_data = [dict(b) for b in boxes]
self._ref_box_selected = None
self._ref_box_hover = None
for i, b in enumerate(self._ref_box_data):
try:
self._ref_box_actors.append(self._add_ref_box_actors(i, b))
except Exception as exc: # noqa: BLE001
logger.exception("Refinement box %d render failed: %s", i, exc)
self._install_ref_box_hover()
if boxes and self._plotter:
self._plotter.render()
def _install_ref_box_hover(self):
"""Best-effort: emphasise the box under the cursor on mouse move."""
if self._plotter is None or self._ref_box_mouse_observer is not None:
return
try:
import vtk
self._ref_box_picker = vtk.vtkPropPicker()
interactor = self._plotter.iren.interactor
self._ref_box_mouse_observer = interactor.AddObserver(
"MouseMoveEvent", self._on_ref_box_mouse_move
)
except Exception as exc: # noqa: BLE001
logger.debug("Refinement box hover picker unavailable: %s", exc)
self._ref_box_mouse_observer = None
def _on_ref_box_mouse_move(self, _caller=None, _event=None):
if self._plotter is None or not self._ref_box_actors:
return
try:
x, y = self._plotter.iren.interactor.GetEventPosition()
self._ref_box_picker.Pick(x, y, 0, self._plotter.renderer)
actor = self._ref_box_picker.GetViewProp()
except Exception:
return
hover = None
for i, entry in enumerate(self._ref_box_actors):
if actor is not None and actor in (entry.get("face"), entry.get("edge")):
hover = i
break
if hover != self._ref_box_hover:
self._ref_box_hover = hover
self._apply_ref_box_emphasis()
def _apply_ref_box_emphasis(self):
"""Recolour/thicken the hovered or selected box, dim the others."""
if self._plotter is None:
return
for i, entry in enumerate(self._ref_box_actors):
emphasised = (i == self._ref_box_selected) or (i == self._ref_box_hover)
face = entry.get("face")
edge = entry.get("edge")
label = entry.get("label")
try:
if face is not None:
face.prop.color = (
self.REF_BOX_SELECTED_FACE_COLOR if emphasised
else self.REF_BOX_FACE_COLOR
)
face.prop.opacity = (
self.REF_BOX_SELECTED_OPACITY if emphasised
else self.REF_BOX_FACE_OPACITY
)
if edge is not None:
edge.prop.color = (
self.REF_BOX_SELECTED_EDGE_COLOR if emphasised
else self.REF_BOX_EDGE_COLOR
)
edge.prop.line_width = (
7 if i == self._ref_box_selected
else (5 if i == self._ref_box_hover else 4)
)
if label is not None:
label.prop.color = (
self.REF_BOX_SELECTED_EDGE_COLOR if emphasised
else self.REF_BOX_EDGE_COLOR
)
except Exception:
continue
try:
self._plotter.render()
except Exception:
pass
[docs]
def set_refinement_box_selected(self, index: int | None) -> None:
"""Emphasise box *index* (the selected panel row), or clear it.
Public API used by the main window: selecting a row in the refinement
list highlights the matching box in the 3D view. ``None``/negative
clears the emphasis.
"""
self.__init_ref_box_state()
if isinstance(index, int) and index >= 0:
self._ref_box_selected = index
else:
self._ref_box_selected = None
self._apply_ref_box_emphasis()
[docs]
def start_refinement_box_drag(self):
"""Enable drag-sizing of the boxes with the vtk BoxWidget gizmo."""
self.__init_ref_box_state()
if self._plotter is None:
return
self.stop_refinement_box_drag()
widgets = []
for i, b in enumerate(self._ref_box_data):
bounds = (b["xmin"], b["xmax"], b["ymin"], b["ymax"],
b["zmin"], b["zmax"])
try:
w = self._plotter.add_box_widget(
callback=self._make_box_widget_cb(i),
bounds=bounds, color="lime",
rotation_enabled=False, use_planes=True,
interaction_event="end",
)
widgets.append(w)
except Exception as exc:
logger.exception("BoxWidget %d failed: %s", i, exc)
self._ref_box_widgets = widgets
if widgets and self._plotter:
self._plotter.render()
def _make_box_widget_cb(self, i: int):
def cb(arg):
try:
# pyvista's add_box_widget hands the callback the widget's
# vtkPlanes on interaction, not a bounds tuple — translate.
if hasattr(arg, "GetNormals"):
bounds = self._bounds_from_vtk_planes(arg)
else:
bounds = [float(v) for v in arg][:6]
if len(bounds) != 6:
return
except Exception:
return
if i >= len(self._ref_box_data):
return
b = self._ref_box_data[i]
(b["xmin"], b["xmax"], b["ymin"], b["ymax"],
b["zmin"], b["zmax"]) = bounds
self._sync_box_actor(i)
self.refinement_boxes_changed.emit(
[dict(x) for x in self._ref_box_data]
)
return cb
@staticmethod
def _bounds_from_vtk_planes(planes) -> list:
"""Axis-aligned bounds (xmin,xmax,ymin,ymax,zmin,zmax) from the 6 box
planes: for a unit normal n, a plane's origin o has n.dot(o) = d, and
d = +/- that axis bound depending on the normal's sign."""
import numpy as _np
pts = _np.asarray(planes.GetPoints().GetData(), dtype=float).reshape(-1, 3)
nrm = _np.asarray(planes.GetNormals().GetData(), dtype=float).reshape(-1, 3)
bounds = [None] * 6
for k in range(3):
for o, n in zip(pts, nrm):
d = float(o @ n)
if n[k] > 0.5:
bounds[2 * k + 1] = d
elif n[k] < -0.5:
bounds[2 * k] = -d
for _idx, v in enumerate(bounds):
if v is None:
return (0.0, 1.0, 0.0, 1.0, 0.0, 1.0)
return [float(v) for v in bounds]
def _sync_box_actor(self, i: int) -> None:
"""Move the box face/wireframe/label to match the widget bounds."""
if self._plotter is None or i >= len(self._ref_box_actors):
return
b = self._ref_box_data[i]
mesh = pv.Box(bounds=self._ref_box_bounds(b))
entry = self._ref_box_actors[i]
for key in ("face", "edge"):
actor = entry.get(key)
if actor is None:
continue
try:
actor.mapper.SetInputData(mesh)
except Exception:
pass
# The label lives at the box's top-centre — rebuild it so it follows
# a resize instead of sitting where the box used to be.
old_label = entry.get("label")
if old_label is not None:
try:
self._plotter.remove_actor(old_label)
except Exception:
pass
entry["label"] = self._add_ref_box_label(i, b)
self._apply_ref_box_emphasis()
if self._plotter:
self._plotter.render()
[docs]
def stop_refinement_box_drag(self):
self.__init_ref_box_state()
if self._plotter is None:
self._ref_box_widgets = []
return
for w in self._ref_box_widgets:
try:
self._plotter.remove_box_widget(w)
except Exception:
try:
w.off()
except Exception:
pass
self._ref_box_widgets = []
@property
def plotter(self):
return self._plotter