Debian Codegraph @

pyvista/plotting/actor.py

raw
1 """Wrap :vtk:`vtkActor` module."""
2
3 from __future__ import annotations
4
5 from typing import TYPE_CHECKING
6 import weakref
7
8 import numpy as np
9
10 import pyvista as pv
11 from pyvista import _vtk
12 from pyvista._deprecate_positional_args import _deprecate_positional_args
13 from pyvista._warn_external import warn_external
14
15 from ._property import Property
16 from .opts import PointSpriteShape
17 from .opts import ShaderType
18 from .prop3d import Prop3D
19
20 if TYPE_CHECKING:
21 from collections.abc import Sequence
22
23 from typing_extensions import Self
24
25 from .mapper import _BaseMapper
26
27 _POINT_SPRITE_SHADERS: dict[str, str] = {
28 'circle': (
29 '//VTK::Color::Impl\n'
30 'vec2 p = gl_PointCoord * 2.0 - 1.0;\n'
31 'float d = dot(p, p);\n'
32 'if (d > 1.0) {\n'
33 ' discard;\n'
34 '}\n'
35 ),
36 'triangle': (
37 '//VTK::Color::Impl\n'
38 'vec2 p = gl_PointCoord * 2.0 - 1.0;\n'
39 'float a = 0.5;\n'
40 'float b = 0.8660254;\n'
41 'vec2 v0 = vec2(0.0, a);\n'
42 'vec2 v1 = vec2(-b, -a);\n'
43 'vec2 v2 = vec2(b, -a);\n'
44 'float area = abs((v1.x - v0.x)*(v2.y - v0.y) - (v2.x - v0.x)*(v1.y - v0.y));\n'
45 'float a1 = abs((v1.x - p.x)*(v2.y - p.y) - (v2.x - p.x)*(v1.y - p.y)) / area;\n'
46 'float a2 = abs((v2.x - p.x)*(v0.y - p.y) - (v0.x - p.x)*(v2.y - p.y)) / area;\n'
47 'float a3 = abs((v0.x - p.x)*(v1.y - p.y) - (v1.x - p.x)*(v0.y - p.y)) / area;\n'
48 'if ((a1 + a2 + a3) > 1.01) {\n'
49 ' discard;\n'
50 '}\n'
51 ),
52 'hexagon': (
53 '//VTK::Color::Impl\n'
54 'vec2 p = gl_PointCoord * 2.0 - 1.0;\n'
55 'p = abs(p);\n'
56 'if (p.x > 1.0 || p.y > 1.0) {\n'
57 ' discard;\n'
58 '}\n'
59 'if (p.x + 0.577 * p.y > 1.0) {\n'
60 ' discard;\n'
61 '}\n'
62 ),
63 'diamond': (
64 '//VTK::Color::Impl\n'
65 'vec2 p = gl_PointCoord * 2.0 - 1.0;\n'
66 'if (abs(p.x) + abs(p.y) > 1.0) {\n'
67 ' discard;\n'
68 '}\n'
69 ),
70 'asterisk': (
71 '//VTK::Color::Impl\n'
72 'vec2 p = gl_PointCoord * 2.0 - 1.0;\n'
73 'float r = length(p);\n'
74 'if (r > 1.0) discard;\n'
75 'float theta = atan(p.y, p.x);\n'
76 'float N = 5.0;\n'
77 'float inner = 0.5;\n'
78 'float star_radius = mix(1.0, inner, abs(cos(N * theta)));\n'
79 'if (r > star_radius)\n'
80 ' discard;\n'
81 ),
82 'star': (
83 '//VTK::Color::Impl\n'
84 'vec2 p = gl_PointCoord * 2.0 - 1.0;\n'
85 'float r = length(p);\n'
86 'if (r > 1.0) discard;\n'
87 'float theta = atan(p.y, p.x);\n'
88 'theta = mod(theta + 6.2831853 + 1.5707963, 6.2831853);\n'
89 'float N = 5.0;\n'
90 'float inner = 0.4;\n'
91 'float radial = pow(0.5 * (1.0 + cos(N * theta)), 3.0);\n'
92 'float radius = mix(inner, 1.0, radial);\n'
93 'if (r > radius)\n'
94 ' discard;\n'
95 ),
96 }
97
98
99 class Actor(Prop3D, _vtk.vtkActor):
100 """Wrap :vtk:`vtkActor`.
101
102 This class represents the geometry & properties in a rendered
103 scene. Normally, a :class:`pyvista.Actor` is constructed from
104 :func:`pyvista.Plotter.add_mesh`, but there may be times when it is more
105 convenient to construct an actor directly from a
106 :class:`pyvista.DataSetMapper`.
107
108 Parameters
109 ----------
110 mapper : pyvista.DataSetMapper, optional
111 DataSetMapper.
112
113 prop : pyvista.Property, optional
114 Property of the actor.
115
116 name : str, optional
117 The name of this actor used when tracking on a plotter.
118
119 Examples
120 --------
121 Create an actor without using :class:`pyvista.Plotter`.
122
123 >>> import pyvista as pv
124 >>> mesh = pv.Sphere()
125 >>> mapper = pv.DataSetMapper(mesh)
126 >>> actor = pv.Actor(mapper=mapper)
127 >>> actor
128 Actor (...)
129 Center: (0.0, 0.0, 0.0)
130 Pickable: True
131 Position: (0.0, 0.0, 0.0)
132 Scale: (1.0, 1.0, 1.0)
133 Visible: True
134 X Bounds -4.993E-01, 4.993E-01
135 Y Bounds -4.965E-01, 4.965E-01
136 Z Bounds -5.000E-01, 5.000E-01
137 User matrix: Identity
138 Has mapper: True
139 ...
140
141 Change the actor properties and plot the actor.
142
143 >>> import pyvista as pv
144 >>> mesh = pv.Sphere()
145 >>> mapper = pv.DataSetMapper(mesh)
146 >>> actor = pv.Actor(mapper=mapper)
147 >>> actor.prop.color = 'blue'
148 >>> actor.plot()
149
150 Create an actor using the :class:`pyvista.Plotter` and then change the
151 visibility of the actor.
152
153 >>> import pyvista as pv
154 >>> pl = pv.Plotter()
155 >>> mesh = pv.Sphere()
156 >>> actor = pl.add_mesh(mesh)
157 >>> actor.visibility = False
158 >>> actor.visibility
159 False
160
161 """
162
163 def __init__(self, mapper=None, prop=None, name=None) -> None:
164 """Initialize actor."""
165 super().__init__()
166 if mapper is not None:
167 self.mapper = mapper
168 if prop is None:
169 self.prop = Property()
170 else:
171 self.prop = prop
172 self._name = name
173 self._shader_replacements: dict[str, list[tuple[ShaderType, str, bool]]] = {}
174 self._point_sprite_shape: str | None = None
175 self._point_sprite_applied: str | None = None
176 self._point_sprite_observer: int | None = None
177
178 @property
179 def mapper(self) -> _BaseMapper: # numpydoc ignore=RT01
180 """Return or set the mapper of the actor.
181
182 Examples
183 --------
184 Create an actor and assign a mapper to it.
185
186 >>> import pyvista as pv
187 >>> dataset = pv.Sphere()
188 >>> actor = pv.Actor()
189 >>> actor.mapper = pv.DataSetMapper(dataset)
190 >>> actor.mapper
191 DataSetMapper (...)
192 Scalar visibility: True
193 Scalar range: (0.0, 1.0)
194 Interpolate before mapping: True
195 Scalar map mode: default
196 Color mode: direct
197 <BLANKLINE>
198 Attached dataset:
199 PolyData (...)
200 N Cells: 1680
201 N Points: 842
202 N Strips: 0
203 X Bounds: -4.993e-01, 4.993e-01
204 Y Bounds: -4.965e-01, 4.965e-01
205 Z Bounds: -5.000e-01, 5.000e-01
206 N Arrays: 1
207
208 """
209 return self.GetMapper() # type: ignore[return-value]
210
211 @mapper.setter
212 def mapper(self, obj) -> None:
213 self.SetMapper(obj)
214
215 @property
216 def prop(self): # numpydoc ignore=RT01
217 """Return or set the property of this actor.
218
219 Examples
220 --------
221 Modify the properties of an actor after adding a dataset to the plotter.
222
223 >>> import pyvista as pv
224 >>> pl = pv.Plotter()
225 >>> actor = pl.add_mesh(pv.Sphere())
226 >>> prop = actor.prop
227 >>> prop.diffuse = 0.6
228 >>> pl.show()
229
230 """
231 return self.GetProperty()
232
233 @prop.setter
234 def prop(self, obj: Property) -> None:
235 self.SetProperty(obj)
236
237 @property
238 def texture(self): # numpydoc ignore=RT01
239 """Return or set the actor texture.
240
241 Notes
242 -----
243 The mapper dataset must have texture coordinates for the texture to be
244 used.
245
246 Examples
247 --------
248 Create an actor and add a texture to it. Note how the
249 :class:`pyvista.PolyData` has texture coordinates by default.
250
251 >>> import pyvista as pv
252 >>> from pyvista import examples
253 >>> plane = pv.Plane()
254 >>> plane.active_texture_coordinates is not None
255 True
256 >>> pl = pv.Plotter()
257 >>> actor = pl.add_mesh(plane)
258 >>> actor.texture = examples.download_masonry_texture()
259 >>> actor.texture
260 Texture (...)
261 Components: 3
262 Cube Map: False
263 Dimensions: 256, 256
264
265 """
266 return self.GetTexture()
267
268 @texture.setter
269 def texture(self, obj) -> None:
270 self.SetTexture(obj)
271
272 @property
273 def memory_address(self): # numpydoc ignore=RT01
274 """Return the memory address of this actor."""
275 return self.GetAddressAsString('')
276
277 @property
278 def pickable(self) -> bool: # numpydoc ignore=RT01
279 """Return or set actor pickability.
280
281 Examples
282 --------
283 Create an actor using the :class:`pyvista.Plotter` and then make the
284 actor unpickable.
285
286 >>> import pyvista as pv
287 >>> pl = pv.Plotter()
288 >>> actor = pl.add_mesh(pv.Sphere())
289 >>> actor.pickable = False
290 >>> actor.pickable
291 False
292
293 """
294 return bool(self.GetPickable())
295
296 @pickable.setter
297 def pickable(self, value) -> None:
298 self.SetPickable(value)
299
300 @property
301 def force_opaque(self) -> bool: # numpydoc ignore=RT01
302 """Return or set actor opacity behavior.
303
304 .. versionadded:: 0.48
305
306 Examples
307 --------
308 Create an actor using the :class:`pyvista.Plotter` and then force the
309 actor to be opaque.
310
311 >>> import pyvista as pv
312 >>> pl = pv.Plotter()
313 >>> actor = pl.add_mesh(pv.Sphere())
314 >>> actor.force_opaque
315 False
316 >>> actor.force_opaque = True
317 >>> actor.force_opaque
318 True
319
320 """
321 return bool(self.GetForceOpaque())
322
323 @force_opaque.setter
324 def force_opaque(self, value: bool) -> None:
325 self.SetForceOpaque(value)
326
327 @property
328 def visibility(self) -> bool: # numpydoc ignore=RT01
329 """Return or set actor visibility.
330
331 See Also
332 --------
333 use_bounds
334 pyvista.Plotter.compute_bounds
335
336 Examples
337 --------
338 Create an actor using the :class:`pyvista.Plotter` and then change the
339 visibility of the actor.
340
341 >>> import pyvista as pv
342 >>> from pyvista import examples
343 >>> mesh = examples.load_airplane()
344 >>> pl = pv.Plotter()
345 >>> actor = pl.add_mesh(mesh)
346 >>> pl.bounds
347 BoundsTuple(x_min = 139.06100463867188,
348 x_max = 1654.9300537109375,
349 y_min = 32.09429931640625,
350 y_max = 1319.949951171875,
351 z_min = -17.741199493408203,
352 z_max = 282.1300048828125)
353
354 >>> actor.visibility = False
355 >>> pl.bounds
356 BoundsTuple(x_min = -1.0,
357 x_max = 1.0,
358 y_min = -1.0,
359 y_max = 1.0,
360 z_min = -1.0,
361 z_max = 1.0)
362
363 """
364 return bool(self.GetVisibility())
365
366 @visibility.setter
367 def visibility(self, value: bool) -> None:
368 self.SetVisibility(value)
369
370 @property
371 def use_bounds(self) -> bool: # numpydoc ignore=RT01
372 """Return or set the use of actor's bounds.
373
374 .. versionadded:: 0.45
375
376 See Also
377 --------
378 visibility
379 pyvista.Plotter.compute_bounds
380
381 Examples
382 --------
383 Create an actor using the :class:`pyvista.Plotter` and then change the
384 use of bounds for the actor.
385
386 >>> import pyvista as pv
387 >>> from pyvista import examples
388 >>> mesh = examples.load_airplane()
389 >>> pl = pv.Plotter()
390 >>> actor = pl.add_mesh(mesh)
391 >>> pl.bounds
392 BoundsTuple(x_min = 139.06100463867188,
393 x_max = 1654.9300537109375,
394 y_min = 32.09429931640625,
395 y_max = 1319.949951171875,
396 z_min = -17.741199493408203,
397 z_max = 282.1300048828125)
398
399 >>> actor.use_bounds = False
400 >>> pl.bounds
401 BoundsTuple(x_min = -1.0,
402 x_max = 1.0,
403 y_min = -1.0,
404 y_max = 1.0,
405 z_min = -1.0,
406 z_max = 1.0)
407
408 Although the actor's bounds are no longer used, the actor remains visible.
409
410 >>> actor.visibility
411 True
412
413 """
414 return bool(self.GetUseBounds())
415
416 @use_bounds.setter
417 def use_bounds(self, value: bool) -> None:
418 self.SetUseBounds(value)
419
420 def plot(self, **kwargs) -> None:
421 """Plot just the actor.
422
423 This may be useful when interrogating or debugging individual actors.
424
425 Parameters
426 ----------
427 **kwargs : dict, optional
428 Optional keyword arguments passed to :func:`pyvista.Plotter.show`.
429
430 Examples
431 --------
432 Create an actor without the :class:`pyvista.Plotter`, change its
433 properties, and plot it.
434
435 >>> import pyvista as pv
436 >>> mesh = pv.Sphere()
437 >>> mapper = pv.DataSetMapper(mesh)
438 >>> actor = pv.Actor(mapper=mapper)
439 >>> actor.prop.color = 'red'
440 >>> actor.prop.show_edges = True
441 >>> actor.plot()
442
443 """
444 pl = pv.Plotter()
445 pl.add_actor(self)
446 pl.show(**kwargs)
447
448 @_deprecate_positional_args
449 def copy(self: Self, deep: bool = True) -> Self: # noqa: FBT001, FBT002
450 """Create a copy of this actor.
451
452 Parameters
453 ----------
454 deep : bool, default: True
455 Create a shallow or deep copy of the actor. A deep copy will have a
456 new property and mapper, while a shallow copy will use the mapper
457 and property of this actor.
458
459 Returns
460 -------
461 Actor
462 Deep or shallow copy of this actor.
463
464 Examples
465 --------
466 Create an actor of a cube by adding it to a :class:`~pyvista.Plotter`
467 and then copy the actor, change the properties, and add it back to the
468 :class:`~pyvista.Plotter`.
469
470 >>> import pyvista as pv
471 >>> mesh = pv.Cube()
472 >>> pl = pv.Plotter()
473 >>> actor = pl.add_mesh(mesh, color='b')
474 >>> new_actor = actor.copy()
475 >>> new_actor.prop.style = 'wireframe'
476 >>> new_actor.prop.line_width = 5
477 >>> new_actor.prop.color = 'r'
478 >>> new_actor.prop.lighting = False
479 >>> _ = pl.add_actor(new_actor)
480 >>> pl.show()
481
482 """
483 new_actor = type(self)()
484 if deep:
485 if self.mapper is not None:
486 new_actor.mapper = self.mapper.copy()
487 new_actor.prop = self.prop.copy()
488 else:
489 new_actor.ShallowCopy(self)
490 return new_actor
491
492 def __repr__(self):
493 """Representation of the actor."""
494 mat_info = 'Identity' if np.array_equal(self.user_matrix, np.eye(4)) else 'Set'
495 bnd = self.bounds
496 attr = [
497 f'{type(self).__name__} ({hex(id(self))})',
498 f' Center: {self.center}',
499 f' Pickable: {self.pickable}',
500 f' Position: {self.position}',
501 f' Scale: {self.scale}',
502 f' Visible: {self.visibility}',
503 f' X Bounds {bnd[0]:.3E}, {bnd[1]:.3E}',
504 f' Y Bounds {bnd[2]:.3E}, {bnd[3]:.3E}',
505 f' Z Bounds {bnd[4]:.3E}, {bnd[5]:.3E}',
506 f' User matrix: {mat_info}',
507 f' Has mapper: {self.mapper is not None}',
508 '',
509 repr(self.prop),
510 ]
511 if self.mapper is not None:
512 attr.append('')
513 attr.append(repr(self.mapper))
514 return '\n'.join(attr)
515
516 @property
517 def backface_prop(self) -> Property | None: # numpydoc ignore=RT01
518 """Return or set the backface property.
519
520 By default this property matches the frontface property
521 :attr:`Actor.prop`. Once accessed or modified, this backface
522 property becomes independent of the frontface property. In
523 order to restore the fallback to frontface property, assign
524 ``None`` to the property.
525
526 Returns
527 -------
528 pyvista.Property
529 The object describing backfaces.
530
531 See Also
532 --------
533 :ref:`backface_prop_example`
534
535 Examples
536 --------
537 Clip a sphere by a plane and color the inside of the clipped sphere
538 light blue using the ``backface_prop``.
539
540 >>> import numpy as np
541 >>> import pyvista as pv
542 >>> plane = pv.Plane(i_size=1.5, j_size=1.5)
543 >>> mesh = pv.Sphere().clip_surface(plane, invert=False)
544 >>> pl = pv.Plotter()
545 >>> actor = pl.add_mesh(mesh, smooth_shading=True)
546 >>> actor.backface_prop.color = 'lightblue'
547 >>> _ = pl.add_mesh(
548 ... plane,
549 ... opacity=0.25,
550 ... show_edges=True,
551 ... color='grey',
552 ... lighting=False,
553 ... )
554 >>> pl.show()
555
556 """
557 if self.GetBackfaceProperty() is None:
558 self.SetBackfaceProperty(self.prop.copy())
559 return self.GetBackfaceProperty() # type: ignore[return-value]
560
561 @backface_prop.setter
562 def backface_prop(self, value: Property) -> None:
563 self.SetBackfaceProperty(value)
564
565 def add_shader_replacement(
566 self,
567 shader_type: ShaderType | str,
568 original: str,
569 replacement: str,
570 *,
571 replace_first: bool = True,
572 replace_all: bool = False,
573 _feature_name: str = '_user',
574 ) -> None:
575 r"""Add a GLSL shader replacement to this actor.
576
577 .. versionadded:: 0.48
578
579 This wraps VTK's shader replacement API, providing conflict detection
580 and tracking so that multiple independent shader features can coexist
581 safely on the same actor.
582
583 Parameters
584 ----------
585 shader_type : ShaderType | str
586 Type of shader to modify. Accepts a :class:`~pyvista.plotting.opts.ShaderType`
587 enum value or a string. One of ``'vertex'``, ``'fragment'``,
588 or ``'geometry'``.
589
590 original : str
591 The VTK shader tag to replace (e.g., ``'//VTK::Color::Impl'``).
592
593 replacement : str
594 The GLSL replacement code.
595
596 replace_first : bool, default: True
597 Whether the replacement is applied before VTK's standard
598 shader substitutions.
599
600 replace_all : bool, default: False
601 Whether to replace all occurrences of ``original``.
602
603 _feature_name : str, default: '_user'
604 Internal key used to track which feature owns this replacement.
605 End users should not need to change this. Built-in features
606 use dedicated keys like ``'mip'`` and ``'point_sprite'``.
607
608 Raises
609 ------
610 ValueError
611 If ``shader_type`` is invalid or if another feature already
612 targets the same shader tag.
613
614 Examples
615 --------
616 Add a custom fragment shader that discards pixels outside a circle.
617
618 >>> import pyvista as pv
619 >>> mesh = pv.Sphere()
620 >>> pl = pv.Plotter()
621 >>> actor = pl.add_mesh(mesh, style='points', point_size=20)
622 >>> actor.add_shader_replacement(
623 ... 'fragment',
624 ... '//VTK::Color::Impl',
625 ... '//VTK::Color::Impl\n'
626 ... 'vec2 p = gl_PointCoord * 2.0 - 1.0;\n'
627 ... 'if (dot(p, p) > 1.0) discard;\n',
628 ... )
629
630 """
631 try:
632 shader_type = ShaderType(shader_type)
633 except ValueError:
634 valid = ', '.join(s.value for s in ShaderType)
635 msg = f'Invalid shader_type {shader_type!r}. Must be one of: {valid}'
636 raise ValueError(msg) from None
637
638 vtk_enum = getattr(_vtk.vtkShader, shader_type.value.capitalize())
639 key = (shader_type, original, replace_first)
640 registry = self._shader_replacements
641
642 # Check for conflicts with other features
643 for other_feature, entries in registry.items():
644 if other_feature != _feature_name and key in entries:
645 msg = (
646 f'Shader replacement conflict: feature {other_feature!r} '
647 f'already targets ({shader_type!r}, {original!r}, '
648 f'replace_first={replace_first}). Clear it first with '
649 f'clear_shader_replacements(_feature_name={other_feature!r}).'
650 )
651 raise ValueError(msg)
652
653 # GetShaderProperty() returns vtkShaderProperty at the type-stub level,
654 # but the runtime object is vtkOpenGLShaderProperty which has these methods.
655 shader_prop = self.GetShaderProperty()
656
657 # If this feature already owns this slot, clear the old one first
658 if _feature_name in registry and key in registry[_feature_name]:
659 shader_prop.ClearShaderReplacement( # type: ignore[attr-defined]
660 vtk_enum,
661 original,
662 replace_first,
663 )
664 registry[_feature_name].remove(key)
665
666 # Add the replacement
667 shader_prop.AddShaderReplacement( # type: ignore[attr-defined]
668 vtk_enum,
669 original,
670 replace_first,
671 replacement,
672 replace_all,
673 )
674
675 # Register it
676 registry.setdefault(_feature_name, []).append(key)
677
678 def clear_shader_replacements(self, *, _feature_name: str | None = None) -> None:
679 """Clear shader replacements from this actor.
680
681 .. versionadded:: 0.48
682
683 Parameters
684 ----------
685 _feature_name : str, optional
686 If specified, only clear replacements registered under this
687 feature name. If ``None``, clear all shader replacements.
688
689 Examples
690 --------
691 Clear all shader replacements from an actor.
692
693 >>> import pyvista as pv
694 >>> actor = pv.Plotter().add_mesh(pv.Sphere())
695 >>> actor.clear_shader_replacements()
696
697 """
698 registry = self._shader_replacements
699 shader_prop = self.GetShaderProperty()
700
701 if _feature_name is None:
702 shader_prop.ClearAllShaderReplacements()
703 registry.clear()
704 elif _feature_name in registry:
705 for shader_type_val, original, replace_first in registry[_feature_name]:
706 vtk_enum = getattr(_vtk.vtkShader, shader_type_val.value.capitalize())
707 # vtkOpenGLShaderProperty at runtime; stubs only know vtkShaderProperty
708 shader_prop.ClearShaderReplacement( # type: ignore[attr-defined]
709 vtk_enum,
710 original,
711 replace_first,
712 )
713 del registry[_feature_name]
714
715 def enable_maximum_intensity_projection(
716 self,
717 clim: Sequence[float] | None = None,
718 ) -> None:
719 """Enable maximum intensity projection.
720
721 .. versionadded:: 0.48
722
723 This resets the z screen coordinates so that vertices with higher
724 scalar values are rendered closer to the screen, regardless of their
725 actual 3D position. This is useful for dense point cloud visualization
726 where high-value data points should be visible even when occluded by
727 lower-value points.
728
729 Scalar values are normalized to the ``[-1, 0]`` range to stay within
730 the OpenGL clip space.
731
732 Parameters
733 ----------
734 clim : sequence[float], optional
735 Two-element sequence ``(min, max)`` specifying the scalar range
736 for normalization. If not provided, the range is computed from
737 the active scalars on the actor's dataset.
738
739 Raises
740 ------
741 RuntimeError
742 If the VTK version is older than 9.3.
743
744 ValueError
745 If no mapper, dataset, or active scalars are available and
746 ``clim`` is not provided.
747
748 Warnings
749 --------
750 Requires VTK >= 9.3. The vertex shader replacements used by
751 this method are not supported in older VTK versions.
752
753 Maximum Intensity Projection does not work correctly with
754 ``opacity < 1`` unless depth peeling is enabled. See
755 :func:`pyvista.Plotter.enable_depth_peeling`.
756
757 See Also
758 --------
759 :ref:`maximum_intensity_projection_example`
760
761 References
762 ----------
763 Cowan, E.J., 2014. 'X-ray Plunge Projection' - Understanding
764 Structural Geology from Grade Data. AusIMM Monograph 30: Mineral
765 Resource and Ore Reserve Estimation - The AusIMM Guide to Good
766 Practice, second edition, 207-220.
767
768 Examples
769 --------
770 Enable maximum intensity projection on a point cloud actor.
771
772 >>> import numpy as np
773 >>> import pyvista as pv
774 >>> rng = np.random.default_rng(0)
775 >>> cloud = pv.PolyData(rng.random((1000, 3)))
776 >>> cloud['values'] = cloud.points[:, 2]
777 >>> pl = pv.Plotter()
778 >>> actor = pl.add_mesh(cloud, scalars='values', style='points')
779 >>> actor.enable_maximum_intensity_projection()
780
781 """
782 if pv.vtk_version_info < (9, 3):
783 msg = 'Maximum intensity projection requires VTK >= 9.3.'
784 raise RuntimeError(msg)
785
786 if clim is not None:
787 min_val, max_val = float(clim[0]), float(clim[1])
788 else:
789 # The mapper property is typed as _BaseMapper (never None) but can
790 # be None at runtime when no mapper has been assigned.
791 mapper: _BaseMapper | None = self.mapper # type: ignore[assignment,unused-ignore]
792 if mapper is None:
793 msg = 'Actor must have a mapper to enable MIP without explicit clim.'
794 raise ValueError(msg)
795 dataset = mapper.dataset
796 if dataset is None:
797 msg = 'Mapper must have a dataset to enable MIP without explicit clim.'
798 raise ValueError(msg)
799 scalars = dataset.active_scalars
800 if scalars is None:
801 msg = (
802 'Dataset must have active scalars to enable MIP without '
803 'explicit clim. Set scalars on your dataset or pass clim=(min, max).'
804 )
805 raise ValueError(msg)
806 min_val = float(np.nanmin(scalars))
807 max_val = float(np.nanmax(scalars))
808
809 if self.prop.opacity < 1.0:
810 warn_external(
811 'Maximum Intensity Projection does not work correctly with '
812 'opacity < 1.0 unless depth peeling is enabled. See '
813 'pyvista.Plotter.enable_depth_peeling().'
814 )
815
816 denom = max_val - min_val
817 if abs(denom) < 1e-12:
818 denom = 1.0
819
820 glsl_code = (
821 f'float _mip_norm = (colorTCoord[0] - {min_val}) / {denom};\n'
822 'gl_Position.z = -_mip_norm;\n'
823 '//VTK::LineWidthGLES30::Impl\n'
824 )
825
826 self.add_shader_replacement(
827 'vertex',
828 '//VTK::LineWidthGLES30::Impl',
829 glsl_code,
830 replace_first=True,
831 replace_all=False,
832 _feature_name='mip',
833 )
834
835 def disable_maximum_intensity_projection(self) -> None:
836 """Disable maximum intensity projection.
837
838 .. versionadded:: 0.48
839
840 Clears the vertex shader replacement that reorders z-coordinates
841 by scalar value, restoring normal depth-based rendering.
842
843 Examples
844 --------
845 >>> import numpy as np
846 >>> import pyvista as pv
847 >>> rng = np.random.default_rng(0)
848 >>> cloud = pv.PolyData(rng.random((1000, 3)))
849 >>> cloud['values'] = cloud.points[:, 2]
850 >>> pl = pv.Plotter()
851 >>> actor = pl.add_mesh(cloud, scalars='values', style='points')
852 >>> actor.enable_maximum_intensity_projection()
853 >>> actor.disable_maximum_intensity_projection()
854
855 """
856 self.clear_shader_replacements(_feature_name='mip')
857
858 def set_point_sprite_shape(self, shape: PointSpriteShape | str) -> None:
859 """Set a custom point sprite shape via fragment shader.
860
861 .. versionadded:: 0.48
862
863 Replaces the default square point rendering with a custom shape
864 defined by a GLSL fragment shader. This uses the ``discard``
865 instruction to clip fragments outside the desired shape boundary.
866
867 The chosen shape is **persisted on the actor** and is only
868 injected into the fragment shader while the actor's
869 :attr:`~pyvista.Property.style` is ``'points'``. When the style
870 is ``'surface'`` or ``'wireframe'`` the shader replacement is
871 transparently removed, because the underlying GLSL relies on
872 ``gl_PointCoord`` which is undefined for non-point primitives
873 and would otherwise corrupt the rendering. Switching
874 ``prop.style`` back to ``'points'`` later will re-install the
875 shader automatically.
876
877 Parameters
878 ----------
879 shape : PointSpriteShape | str
880 The sprite shape to use. Accepts a :class:`PointSpriteShape`
881 enum value or a string. Must be one of:
882
883 * ``'circle'`` - Circular disc
884 * ``'triangle'`` - Upward-pointing triangle
885 * ``'hexagon'`` - Regular hexagon
886 * ``'diamond'`` - Diamond (rotated square)
887 * ``'asterisk'`` - Five-pointed asterisk
888 * ``'star'`` - Five-pointed star
889
890 Raises
891 ------
892 ValueError
893 If ``shape`` is not one of the supported shapes.
894
895 Notes
896 -----
897 Point sprite shapes only produce visible results when
898 ``render_points_as_spheres=False`` and ``style='points'``.
899 When ``render_points_as_spheres=True``, VTK uses a different
900 rendering path that bypasses the fragment shader.
901
902 See Also
903 --------
904 :ref:`point_sprites_example`
905
906 Examples
907 --------
908 Render points as circles instead of squares.
909
910 >>> import numpy as np
911 >>> import pyvista as pv
912 >>> cloud = pv.PolyData(np.random.default_rng(0).random((100, 3)))
913 >>> pl = pv.Plotter()
914 >>> actor = pl.add_mesh(
915 ... cloud,
916 ... style='points',
917 ... render_points_as_spheres=False,
918 ... point_size=20,
919 ... )
920 >>> actor.set_point_sprite_shape('circle')
921
922 """
923 if shape not in _POINT_SPRITE_SHADERS:
924 valid = ', '.join(sorted(_POINT_SPRITE_SHADERS))
925 msg = f'Invalid point sprite shape {shape!r}. Must be one of: {valid}'
926 raise ValueError(msg)
927
928 self._point_sprite_shape = shape.value if isinstance(shape, PointSpriteShape) else shape
929 self._install_point_sprite_observer()
930 self._sync_point_sprite_shader()
931
932 def clear_point_sprite_shape(self) -> None:
933 """Clear the custom point sprite shape.
934
935 .. versionadded:: 0.48
936
937 Restores the default square point rendering by removing the
938 fragment shader replacement and stopping the representation
939 observer installed by :meth:`set_point_sprite_shape`.
940
941 Examples
942 --------
943 >>> import numpy as np
944 >>> import pyvista as pv
945 >>> cloud = pv.PolyData(np.random.default_rng(0).random((100, 3)))
946 >>> pl = pv.Plotter()
947 >>> actor = pl.add_mesh(cloud, style='points', point_size=20)
948 >>> actor.set_point_sprite_shape('circle')
949 >>> actor.clear_point_sprite_shape()
950
951 """
952 self._point_sprite_shape = None
953 if self._point_sprite_observer is not None:
954 self.prop.RemoveObserver(self._point_sprite_observer)
955 self._point_sprite_observer = None
956 self._sync_point_sprite_shader()
957
958 def _install_point_sprite_observer(self) -> None:
959 """Install the property-level observer that syncs the sprite shader.
960
961 The point sprite fragment shader uses ``gl_PointCoord`` which is
962 only valid when the current primitive is drawn as ``GL_POINTS``.
963 Rather than leaving the shader replacement in place across all
964 representations (which corrupts surface and wireframe rendering),
965 we attach a lightweight observer to the actor's :class:`Property`
966 and re-sync the shader replacement whenever the representation
967 state changes.
968 """
969 if self._point_sprite_observer is not None:
970 return
971
972 # Use a weak reference to avoid a strong reference cycle between
973 # the Python-level Actor and the vtkCommand retained by vtkProperty.
974 self_ref = weakref.ref(self)
975
976 def _on_property_modified(
977 caller: object, # noqa: ARG001
978 event: str, # noqa: ARG001
979 ) -> None:
980 owner = self_ref()
981 if owner is not None:
982 owner._sync_point_sprite_shader()
983
984 self._point_sprite_observer = self.prop.AddObserver(
985 'ModifiedEvent',
986 _on_property_modified,
987 )
988
989 def _sync_point_sprite_shader(self) -> None:
990 """Install, update, or remove the point sprite shader replacement.
991
992 The replacement is only active while the representation is
993 ``'Points'`` — for any other representation the ``gl_PointCoord``
994 built-in is undefined and would otherwise corrupt fragment output.
995 Tracks the currently-applied shape (rather than a boolean) so
996 that unrelated property modifications (color, opacity, ...) do
997 not repeatedly rebuild the shader, while still honoring real
998 shape changes and representation transitions.
999 """
1000 shape = self._point_sprite_shape
1001 is_points = self.prop.GetRepresentationAsString() == 'Points'
1002 target = shape if is_points else None
1003
1004 if target == self._point_sprite_applied:
1005 return
1006
1007 if target is not None:
1008 self.add_shader_replacement(
1009 'fragment',
1010 '//VTK::Color::Impl',
1011 _POINT_SPRITE_SHADERS[target],
1012 replace_first=True,
1013 replace_all=False,
1014 _feature_name='point_sprite',
1015 )
1016 else:
1017 self.clear_shader_replacements(_feature_name='point_sprite')
1018
1019 self._point_sprite_applied = target