Source code for pyvcad_rendering.sdf_visualization

import pyvcad as pv
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np

_AXIS_INDICES = {"x": 0, "y": 1, "z": 2}
_AXIS_NAMES = ("X", "Y", "Z")


def _resolve_plane(plane):
    """Map a plane name such as "xy" or "yz" to (horizontal, vertical, fixed) axis indices.

    The first axis of the name becomes the horizontal plot axis and the second
    the vertical one, so "zx" plots the same slice as "xz" with the axes swapped.
    """
    key = str(plane).strip().lower()
    if len(key) != 2 or key[0] not in _AXIS_INDICES or key[1] not in _AXIS_INDICES or key[0] == key[1]:
        raise ValueError(f"Invalid plane '{plane}'. Expected two distinct axes, e.g. 'xy', 'xz' or 'yz'.")

    horizontal_axis = _AXIS_INDICES[key[0]]
    vertical_axis = _AXIS_INDICES[key[1]]
    fixed_axis = 3 - horizontal_axis - vertical_axis
    return horizontal_axis, vertical_axis, fixed_axis


def _axis_components(point):
    """Return a bounding box corner as an indexable (x, y, z) tuple."""
    return (point.x, point.y, point.z)


[docs] class SDFSlice: """A sampled 2D slice of a signed distance field. ``values`` is indexed ``[vertical, horizontal]`` and holds NaN wherever the tree returned no value (outside the prepared band). """ def __init__(self, values, h_coords, v_coords, plane_axes, offset): self.values = values self.h_coords = h_coords self.v_coords = v_coords self.horizontal_axis, self.vertical_axis, self.fixed_axis = plane_axes self.offset = offset @property def horizontal_name(self): """Name of the horizontal image axis ("X", "Y" or "Z").""" return _AXIS_NAMES[self.horizontal_axis] @property def vertical_name(self): """Name of the vertical image axis ("X", "Y" or "Z").""" return _AXIS_NAMES[self.vertical_axis] @property def fixed_name(self): """Name of the axis normal to the slice ("X", "Y" or "Z").""" return _AXIS_NAMES[self.fixed_axis] @property def extent(self): """``[h_min, h_max, v_min, v_max]`` of the sample coordinates, for ``matplotlib.imshow``.""" return [self.h_coords[0], self.h_coords[-1], self.v_coords[0], self.v_coords[-1]] @property def title(self): """A plot title naming the fixed axis and the slice offset.""" return f'SDF Visualization at {self.fixed_name}={self.offset}'
[docs] class SDFSliceSampler: """Samples principal-plane slices of a node's signed distance field. The node is prepared on demand at the spacing each slice needs and is only re-prepared when that spacing changes, so stepping the slice offset through the part reuses the same preparation. Args: node: The OpenVCAD node to sample. It is prepared in place, so pass a ``clone()`` when the original tree is in use elsewhere. bandwidth (float, optional): Bandwidth to prepare the tree with. Defaults to the bounding box diagonal so the whole slice carries values; lower it when a wide band is expensive to prepare (e.g. mesh backed trees). """ def __init__(self, node, bandwidth=None): self.node = node self.bandwidth = bandwidth self._prepared_key = None # The tree has to be prepared before it can be queried, but a sensible # voxel size depends on the bounding box. Prepare coarsely to read the # extents; each slice then prepares again at its sampling resolution. node.prepare(pv.Vec3(1.0, 1.0, 1.0), 1.0) min_pt, max_pt = node.bounding_box() self.min_corner = _axis_components(min_pt) self.max_corner = _axis_components(max_pt)
[docs] def axis_range(self, axis): """Return the bounding box (min, max) along an axis index.""" return self.min_corner[axis], self.max_corner[axis]
[docs] def sample(self, plane="xy", offset=0.0, resolution=100): """Sample one slice. Args: plane (str, optional): The slice plane named by its two axes ("xy", "xz", "yz"). Defaults to "xy". offset (float, optional): Position of the slice along the axis that is not part of ``plane``. Defaults to 0.0. resolution (int, optional): Number of samples along the longest in-plane dimension. Defaults to 100. Returns: An :class:`SDFSlice`. """ plane_axes = _resolve_plane(plane) horizontal_axis, vertical_axis, fixed_axis = plane_axes min_h, max_h = self.axis_range(horizontal_axis) min_v, max_v = self.axis_range(vertical_axis) # Calculate sampling grid size based on resolution and aspect ratio width = max_h - min_h height = max_v - min_v if width > height: nh = resolution nv = int(resolution * (height / width)) if width > 0 else resolution else: nv = resolution nh = int(resolution * (width / height)) if height > 0 else resolution nh = max(1, nh) nv = max(1, nv) # Prepare at the sample spacing, with a band wide enough to cover the whole # slice so the heat map is not punched full of out-of-band holes. sample_size = max(width / max(1, nh - 1), height / max(1, nv - 1)) if sample_size <= 0.0: sample_size = 1.0 bandwidth = self.bandwidth if bandwidth is None: diagonal = np.linalg.norm(np.array(self.max_corner) - np.array(self.min_corner)) bandwidth = float(diagonal) if diagonal > 0.0 else sample_size key = (sample_size, bandwidth) if key != self._prepared_key: self.node.prepare(pv.Vec3(sample_size, sample_size, sample_size), bandwidth) self._prepared_key = key # Generate world-space sample coordinates hs = np.linspace(min_h, max_h, nh) vs = np.linspace(min_v, max_v, nv) # Evaluate SDF at each grid point. Points outside the prepared band come back # as None, which we carry through as NaN so matplotlib masks them out. point = [0.0, 0.0, 0.0] point[fixed_axis] = offset sdf_values = np.zeros((nv, nh)) for i in range(nv): point[vertical_axis] = vs[i] for j in range(nh): point[horizontal_axis] = hs[j] value = self.node.evaluate(point[0], point[1], point[2]) sdf_values[i, j] = np.nan if value is None else value result = SDFSlice(sdf_values, hs, vs, plane_axes, offset) if np.all(np.isnan(sdf_values)): raise RuntimeError( f"The {result.horizontal_name}{result.vertical_name} slice at {result.fixed_name}={offset} produced no samples. " "The slice may lie outside the object or outside the prepared bandwidth.") return result
[docs] def draw_sdf_slice(fig, ax, sdf_slice, iso_surface=0.0, theme=None): """Draw a sampled slice as a heat map with an iso-contour onto ``ax``. Args: fig: The matplotlib figure that owns ``ax`` (the colorbar is added to it). ax: The axes to draw into. sdf_slice (SDFSlice): The slice to draw. iso_surface (float, optional): The signed distance value to draw as a contour. Defaults to 0.0. theme (dict, optional): ``fg``/``bg``/``axis`` colors for embedding in a themed UI. Defaults to matplotlib's style. """ sdf_values = sdf_slice.values # Use TwoSlopeNorm to center the colormap at 0 (surface boundary) # This helps distinguish inside (negative) vs outside (positive) v_min, v_max = np.nanmin(sdf_values), np.nanmax(sdf_values) norm = None if v_min < 0 < v_max: norm = mcolors.TwoSlopeNorm(vmin=v_min, vcenter=0., vmax=v_max) # Plot the heat map im = ax.imshow(sdf_values, extent=sdf_slice.extent, origin='lower', cmap='seismic', norm=norm) colorbar = fig.colorbar(im, ax=ax, label='Signed Distance') # Draw the specific iso-surface contour. A level outside the sampled range # has nothing to trace, and matplotlib warns about it. if v_min <= iso_surface <= v_max: hv, vv = np.meshgrid(sdf_slice.h_coords, sdf_slice.v_coords) contour_color = 'black' if theme is None else theme["fg"] ax.contour(hv, vv, sdf_values, levels=[iso_surface], colors=contour_color, linewidths=1.5, linestyles='dashed') ax.set_title(sdf_slice.title) ax.set_xlabel(sdf_slice.horizontal_name) ax.set_ylabel(sdf_slice.vertical_name) if theme is not None: fig.patch.set_facecolor(theme["bg"]) ax.set_facecolor(theme["bg"]) for target in (ax, colorbar.ax): target.tick_params(colors=theme["axis"]) for spine in target.spines.values(): spine.set_color(theme["axis"]) ax.title.set_color(theme["fg"]) ax.xaxis.label.set_color(theme["fg"]) ax.yaxis.label.set_color(theme["fg"]) colorbar.ax.yaxis.label.set_color(theme["fg"])
[docs] def VisualizeSDF(object, offset=0.0, resolution=100, iso_surface=0.0, plane="xy", bandwidth=None, show=True, z_height=None): """Plots a slice of a node's signed distance field as a heat map. The slice plane is named by the two axes it spans, so any of the three principal planes can be visualized. For a slice at any angle, placed interactively, use the renderer's SDF Slice tool. Args: object: The OpenVCAD node to sample. It is prepared in place before sampling. offset (float, optional): Position of the slice along the axis that is not part of ``plane``. Defaults to 0.0. resolution (int, optional): Number of samples along the longest in-plane dimension. Defaults to 100. iso_surface (float, optional): The signed distance value to draw as a contour. Defaults to 0.0. plane (str, optional): The slice plane named by its two axes ("xy", "xz", "yz"). Defaults to "xy". bandwidth (float, optional): Bandwidth to prepare the tree with. Defaults to the bounding box diagonal so the whole slice carries values; lower it when a wide band is expensive to prepare (e.g. mesh backed trees). show (bool, optional): Whether to display the plot. Set to False to only build the figure, e.g. to save it from a headless script. Defaults to True. z_height (float, optional): Deprecated alias for ``offset``, kept for the original XY-only signature. Returns: A tuple of the matplotlib figure and axes holding the plot. """ if z_height is not None: offset = z_height # Validate the plane before paying for a prepare. _resolve_plane(plane) sdf_slice = SDFSliceSampler(object, bandwidth=bandwidth).sample(plane, offset, resolution) fig, ax = plt.subplots(figsize=(8, 6)) draw_sdf_slice(fig, ax, sdf_slice, iso_surface) if show: plt.show() return fig, ax
__all__ = ["SDFSlice", "SDFSliceSampler", "draw_sdf_slice", "VisualizeSDF"]