1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
|
"""These are private methods we keep out of plotting.py to simplify the module."""
from __future__ import annotations
import warnings
import numpy as np
import pyvista
from pyvista.core.utilities.arrays import get_array
from pyvista.core.utilities.misc import assert_empty_kwargs
from .colors import Color
from .opts import InterpolationType
from .tools import opacity_transfer_function
def prepare_smooth_shading(mesh, scalars, texture, split_sharp_edges, feature_angle, preference):
"""Prepare a dataset for smooth shading.
VTK requires datasets with Phong shading to have active normals.
This requires extracting the external surfaces from non-polydata
datasets and computing the point normals.
Parameters
----------
mesh : pyvista.DataSet
Dataset to prepare smooth shading for.
scalars : sequence
Sequence of scalars.
texture : pyvista.Texture or np.ndarray, optional
A texture to apply to the mesh.
split_sharp_edges : bool
Split sharp edges exceeding 30 degrees when plotting with
smooth shading. Control the angle with the optional
keyword argument ``feature_angle``. By default this is
``False``. Note that enabling this will create a copy of
the input mesh within the plotter. See
:ref:`shading_example`.
feature_angle : float
Angle to consider an edge a sharp edge.
preference : str
If the number of points is identical to the number of cells.
Either ``'point'`` or ``'cell'``.
Returns
-------
pyvista.PolyData
Always a surface as we need to compute point normals.
"""
is_polydata = isinstance(mesh, pyvista.PolyData)
indices_array = None
has_scalars = scalars is not None
use_points = False
if has_scalars:
if not isinstance(scalars, np.ndarray):
scalars = np.array(scalars)
if scalars.shape[0] == mesh.n_points and scalars.shape[0] == mesh.n_cells:
use_points = preference == 'point'
else:
use_points = scalars.shape[0] == mesh.n_points
# extract surface if not already a surface
if not is_polydata:
mesh = mesh.extract_surface(
pass_pointid=use_points or texture is not None,
pass_cellid=not use_points,
)
indices_array = 'vtkOriginalPointIds' if use_points else 'vtkOriginalCellIds'
try:
if split_sharp_edges:
mesh = mesh.compute_normals(
cell_normals=False,
split_vertices=True,
feature_angle=feature_angle,
)
if is_polydata:
if has_scalars and use_points:
# we must track the original IDs with our own array from compute_normals
indices_array = 'pyvistaOriginalPointIds'
elif mesh.point_data.active_normals is None:
mesh.compute_normals(cell_normals=False, inplace=True)
except TypeError as e:
if "Normals cannot be computed" in repr(e):
pass
else:
raise
if has_scalars and indices_array is not None:
ind = mesh[indices_array]
scalars = np.asarray(scalars)[ind]
return mesh, scalars
def process_opacity(mesh, opacity, preference, n_colors, scalars, use_transparency):
"""Process opacity.
This function accepts an opacity string or array and always
returns an array that can be applied to a dataset for plotting.
Parameters
----------
mesh : pyvista.DataSet
Dataset to process the opacity for.
opacity : str, sequence
String or array. If string, can be a ``str`` name of a
predefined mapping such as ``'linear'``, ``'geom'``,
``'sigmoid'``, ``'sigmoid3-10'``, or the key of a cell or
point data array.
preference : str
When ``mesh.n_points == mesh.n_cells``, this parameter
sets how the scalars will be mapped to the mesh. If
``'point'``, causes the scalars will be associated with
the mesh points. Can be either ``'point'`` or
``'cell'``.
n_colors : int
Number of colors to use when displaying the opacity.
scalars : numpy.ndarray
Dataset scalars.
use_transparency : bool
Invert the opacity mappings and make the values correspond
to transparency.
Returns
-------
custom_opac : bool
If using custom opacity.
opacity : numpy.ndarray
Array containing the opacity.
"""
custom_opac = False
if isinstance(opacity, str):
try:
# Get array from mesh
opacity = get_array(mesh, opacity, preference=preference, err=True)
if np.any(opacity > 1):
warnings.warn("Opacity scalars contain values over 1")
if np.any(opacity < 0):
warnings.warn("Opacity scalars contain values less than 0")
custom_opac = True
except KeyError:
# Or get opacity transfer function (e.g. "linear")
opacity = opacity_transfer_function(opacity, n_colors)
else:
if scalars.shape[0] != opacity.shape[0]:
raise ValueError(
"Opacity array and scalars array must have the same number of elements.",
)
elif isinstance(opacity, (np.ndarray, list, tuple)):
opacity = np.asanyarray(opacity)
if opacity.shape[0] in [mesh.n_cells, mesh.n_points]:
# User could pass an array of opacities for every point/cell
custom_opac = True
else:
opacity = opacity_transfer_function(opacity, n_colors)
if use_transparency:
if np.max(opacity) <= 1.0:
opacity = 1 - opacity
elif isinstance(opacity, np.ndarray):
opacity = 255 - opacity
return custom_opac, opacity
def _common_arg_parser(
dataset,
theme,
n_colors,
scalar_bar_args,
split_sharp_edges,
show_scalar_bar,
render_points_as_spheres,
smooth_shading,
pbr,
clim,
cmap,
culling,
name,
nan_color,
nan_opacity,
color,
texture,
rgb,
style,
**kwargs,
):
"""Parse arguments in common between add_volume, composite, and mesh."""
# supported aliases
clim = kwargs.pop('rng', clim)
cmap = kwargs.pop('colormap', cmap)
culling = kwargs.pop("backface_culling", culling)
rgb = kwargs.pop('rgba', rgb)
vertex_color = kwargs.pop('vertex_color', theme.edge_color)
vertex_style = kwargs.pop('vertex_style', 'points')
vertex_opacity = kwargs.pop('vertex_opacity', 1.0)
# Support aliases for 'back', 'front', or 'none'. Consider deprecating
if culling is False:
culling = 'none'
elif culling in ['b', 'backface', True]:
culling = 'back'
elif culling in ['f', 'frontface']:
culling = 'front'
if show_scalar_bar is None:
# use theme unless plotting RGB
_default = theme.show_scalar_bar or scalar_bar_args
show_scalar_bar = False if rgb else _default
# Avoid mutating input
scalar_bar_args = {'n_colors': n_colors} if scalar_bar_args is None else scalar_bar_args.copy()
# theme based parameters
if split_sharp_edges is None:
split_sharp_edges = theme.split_sharp_edges
feature_angle = kwargs.pop('feature_angle', theme.sharp_edges_feature_angle)
if render_points_as_spheres is None:
if style == 'points_gaussian':
render_points_as_spheres = False
else:
render_points_as_spheres = theme.render_points_as_spheres
if smooth_shading is None:
smooth_shading = True if pbr else theme.smooth_shading
if name is None:
name = f'{type(dataset).__name__}({dataset.memory_address})'
remove_existing_actor = False
else:
# check if this actor already exists
remove_existing_actor = True
nan_color = Color(nan_color, opacity=nan_opacity, default_color=theme.nan_color)
if color is True:
color = theme.color
if texture is False:
texture = None
# allow directly specifying interpolation (potential future feature)
if 'interpolation' in kwargs:
interpolation = kwargs.pop('interpolation') # pragma: no cover:
elif pbr:
interpolation = InterpolationType.PBR
elif smooth_shading:
interpolation = InterpolationType.PHONG
else:
interpolation = theme.lighting_params.interpolation
if "scalar" in kwargs:
raise TypeError(
"`scalar` is an invalid keyword argument. Perhaps you mean `scalars` with an s?",
)
assert_empty_kwargs(**kwargs)
return (
scalar_bar_args,
split_sharp_edges,
show_scalar_bar,
feature_angle,
render_points_as_spheres,
smooth_shading,
clim,
cmap,
culling,
name,
nan_color,
color,
texture,
rgb,
interpolation,
remove_existing_actor,
vertex_color,
vertex_style,
vertex_opacity,
)
|