Debian Codegraph @

pyvista/plotting/prop3d.py

raw
1 """Prop3D module."""
2
3 from __future__ import annotations
4
5 from abc import ABC
6 from abc import abstractmethod
7 from functools import wraps
8 from typing import TYPE_CHECKING
9 from typing import Literal
10
11 import numpy as np
12
13 from pyvista import _vtk
14 from pyvista._deprecate_positional_args import _deprecate_positional_args
15 from pyvista.core import _validation
16 from pyvista.core._typing_core import BoundsTuple
17 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
18 from pyvista.core.utilities.arrays import array_from_vtkmatrix
19 from pyvista.core.utilities.arrays import vtkmatrix_from_array
20 from pyvista.core.utilities.misc import _BoundsSizeMixin
21 from pyvista.core.utilities.misc import _NameMixin
22 from pyvista.core.utilities.misc import _NoNewAttrMixin
23 from pyvista.core.utilities.transform import Transform
24
25 if TYPE_CHECKING:
26 from typing_extensions import Self
27
28 from pyvista.core._typing_core import NumpyArray
29 from pyvista.core._typing_core import RotationLike
30 from pyvista.core._typing_core import TransformLike
31 from pyvista.core._typing_core import VectorLike
32
33
34 class Prop3D(_NoNewAttrMixin, _NameMixin, _BoundsSizeMixin, DisableVtkSnakeCase, _vtk.vtkProp3D):
35 """Prop3D wrapper for :vtk:`vtkProp3D`.
36
37 Used to represent an entity in a rendering scene. It provides spatial
38 properties and methods relating to an entity's position, orientation
39 and scale. It is used as parent class for :class:`pyvista.Actor`,
40 :class:`pyvista.AxesActor`, and :class:`pyvista.plotting.volume.Volume`.
41
42 ``Prop3D`` applies transformations in the following order:
43
44 #. Translate entity to its :attr:`~origin`.
45 #. Scale entity by the values in :attr:`~scale`.
46 #. Rotate entity using the values in :attr:`~orientation`. Internally, rotations are
47 applied in the order :func:`~rotate_y`, then :func:`~rotate_x`, then :func:`~rotate_z`.
48 #. Translate entity away from its origin and to its :attr:`~position`.
49 #. Transform entity with :attr:`~user_matrix`.
50
51 """
52
53 def __init__(self) -> None:
54 """Initialize Prop3D."""
55 super().__init__()
56
57 @property
58 def scale(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
59 """Return or set entity scale.
60
61 Examples
62 --------
63 Create an actor using the :class:`pyvista.Plotter` and then change the
64 scale of the actor.
65
66 >>> import pyvista as pv
67 >>> pl = pv.Plotter()
68 >>> actor = pl.add_mesh(pv.Sphere())
69 >>> actor.scale = (2.0, 2.0, 2.0)
70 >>> actor.scale
71 (2.0, 2.0, 2.0)
72
73 """
74 return self.GetScale()
75
76 @scale.setter
77 def scale(self, value: float | VectorLike[float]) -> None:
78 self.SetScale(value) # type: ignore[arg-type]
79
80 @property
81 def position(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
82 """Return or set the entity position.
83
84 Examples
85 --------
86 Change the position of an actor. Note how this does not change the
87 position of the underlying dataset, just the relative location of the
88 actor in the :class:`pyvista.Plotter`.
89
90 >>> import pyvista as pv
91 >>> mesh = pv.Sphere()
92 >>> pl = pv.Plotter()
93 >>> _ = pl.add_mesh(mesh, color='b')
94 >>> actor = pl.add_mesh(mesh, color='r')
95 >>> actor.position = (0, 0, 1) # shifts the red sphere up
96 >>> pl.show()
97
98 """
99 return self.GetPosition()
100
101 @position.setter
102 def position(self, value: VectorLike[float]) -> None:
103 self.SetPosition(value) # type: ignore[call-overload]
104
105 def rotate_x(self, angle: float) -> None:
106 """Rotate the entity about the x-axis.
107
108 Parameters
109 ----------
110 angle : float
111 Angle to rotate the entity about the x-axis in degrees.
112
113 Examples
114 --------
115 Rotate the actor about the x-axis 45 degrees. Note how this does not
116 change the location of the underlying dataset.
117
118 >>> import pyvista as pv
119 >>> mesh = pv.Cube()
120 >>> pl = pv.Plotter()
121 >>> _ = pl.add_mesh(mesh, color='b')
122 >>> actor = pl.add_mesh(
123 ... mesh,
124 ... color='r',
125 ... style='wireframe',
126 ... line_width=5,
127 ... lighting=False,
128 ... )
129 >>> actor.rotate_x(45)
130 >>> pl.show_axes()
131 >>> pl.show()
132
133 """
134 self.RotateX(angle)
135
136 def rotate_y(self, angle: float) -> None:
137 """Rotate the entity about the y-axis.
138
139 Parameters
140 ----------
141 angle : float
142 Angle to rotate the entity about the y-axis in degrees.
143
144 Examples
145 --------
146 Rotate the actor about the y-axis 45 degrees. Note how this does not
147 change the location of the underlying dataset.
148
149 >>> import pyvista as pv
150 >>> mesh = pv.Cube()
151 >>> pl = pv.Plotter()
152 >>> _ = pl.add_mesh(mesh, color='b')
153 >>> actor = pl.add_mesh(
154 ... mesh,
155 ... color='r',
156 ... style='wireframe',
157 ... line_width=5,
158 ... lighting=False,
159 ... )
160 >>> actor.rotate_y(45)
161 >>> pl.show_axes()
162 >>> pl.show()
163
164 """
165 self.RotateY(angle)
166
167 def rotate_z(self, angle: float) -> None:
168 """Rotate the entity about the z-axis.
169
170 Parameters
171 ----------
172 angle : float
173 Angle to rotate the entity about the z-axis in degrees.
174
175 Examples
176 --------
177 Rotate the actor about the z-axis 45 degrees. Note how this does not
178 change the location of the underlying dataset.
179
180 >>> import pyvista as pv
181 >>> mesh = pv.Cube()
182 >>> pl = pv.Plotter()
183 >>> _ = pl.add_mesh(mesh, color='b')
184 >>> actor = pl.add_mesh(
185 ... mesh,
186 ... color='r',
187 ... style='wireframe',
188 ... line_width=5,
189 ... lighting=False,
190 ... )
191 >>> actor.rotate_z(45)
192 >>> pl.show_axes()
193 >>> pl.show()
194
195 """
196 self.RotateZ(angle)
197
198 @property
199 def orientation(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
200 """Return or set the entity orientation angles.
201
202 Orientation angles of the axes which define rotations about the
203 world's x-y-z axes. The angles are specified in degrees and in
204 x-y-z order. However, the actual rotations are applied in the
205 following order: :func:`~rotate_y` first, then :func:`~rotate_x`
206 and finally :func:`~rotate_z`.
207
208 Rotations are applied about the specified :attr:`~origin`.
209
210 See Also
211 --------
212 rotation_from
213 Alternative method for setting the :attr:`orientation`.
214
215 Examples
216 --------
217 Reorient just the actor and plot it. Note how the actor is rotated
218 about the origin ``(0, 0, 0)`` by default.
219
220 >>> import pyvista as pv
221 >>> mesh = pv.Cube(center=(0, 0, 3))
222 >>> pl = pv.Plotter()
223 >>> _ = pl.add_mesh(mesh, color='b')
224 >>> actor = pl.add_mesh(
225 ... mesh,
226 ... color='r',
227 ... style='wireframe',
228 ... line_width=5,
229 ... lighting=False,
230 ... )
231 >>> actor.orientation = (45, 0, 0)
232 >>> _ = pl.add_axes_at_origin()
233 >>> pl.show()
234
235 Repeat the last example, but this time reorient the actor about
236 its center by specifying its :attr:`~origin`.
237
238 >>> import pyvista as pv
239 >>> mesh = pv.Cube(center=(0, 0, 3))
240 >>> pl = pv.Plotter()
241 >>> _ = pl.add_mesh(mesh, color='b')
242 >>> actor = pl.add_mesh(
243 ... mesh,
244 ... color='r',
245 ... style='wireframe',
246 ... line_width=5,
247 ... lighting=False,
248 ... )
249 >>> actor.origin = actor.center
250 >>> actor.orientation = (45, 0, 0)
251 >>> _ = pl.add_axes_at_origin()
252 >>> pl.show()
253
254 Show that the orientation changes with rotation.
255
256 >>> import pyvista as pv
257 >>> mesh = pv.Cube()
258 >>> pl = pv.Plotter()
259 >>> actor = pl.add_mesh(mesh)
260 >>> actor.rotate_x(90)
261 >>> actor.orientation # doctest:+SKIP
262 (90, 0, 0)
263
264 Set the orientation directly.
265
266 >>> actor.orientation = (0, 45, 45)
267 >>> actor.orientation # doctest:+SKIP
268 (0, 45, 45)
269
270 """
271 return self.GetOrientation()
272
273 @orientation.setter
274 def orientation(self, value: VectorLike[float]) -> None:
275 self.SetOrientation(value) # type: ignore[call-overload]
276
277 @property
278 def origin(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
279 """Return or set the entity origin.
280
281 This is the point about which all rotations take place.
282
283 See :attr:`~orientation` for examples.
284
285 """
286 return self.GetOrigin()
287
288 @origin.setter
289 def origin(self, value: VectorLike[float]) -> None:
290 self.SetOrigin(value) # type: ignore[arg-type]
291
292 @property
293 def bounds(self) -> BoundsTuple: # numpydoc ignore=RT01
294 """Return the bounds of the entity.
295
296 Bounds are ``(x_min, x_max, y_min, y_max, z_min, z_max)``
297
298 Examples
299 --------
300 >>> import pyvista as pv
301 >>> pl = pv.Plotter()
302 >>> mesh = pv.Cube(x_length=0.1, y_length=0.2, z_length=0.3)
303 >>> actor = pl.add_mesh(mesh)
304 >>> actor.bounds
305 BoundsTuple(x_min = -0.05,
306 x_max = 0.05,
307 y_min = -0.1,
308 y_max = 0.1,
309 z_min = -0.15,
310 z_max = 0.15)
311
312 """
313 return BoundsTuple(*self.GetBounds())
314
315 @property
316 def center(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
317 """Return the center of the entity.
318
319 Examples
320 --------
321 >>> import pyvista as pv
322 >>> pl = pv.Plotter()
323 >>> actor = pl.add_mesh(pv.Sphere(center=(0.5, 0.5, 1)))
324 >>> actor.center # doctest:+SKIP
325 (0.5, 0.5, 1)
326
327 """
328 return self.GetCenter()
329
330 @property
331 def user_matrix(self) -> NumpyArray[float]: # numpydoc ignore=RT01
332 """Return or set the user matrix.
333
334 In addition to the instance variables such as position and orientation, the user
335 can add an additional transformation to the actor.
336
337 This matrix is concatenated with the actor's internal transformation that is
338 implicitly created when the actor is created. This affects the actor/rendering
339 only, not the input data itself.
340
341 The user matrix is the last transformation applied to the actor before
342 rendering.
343
344 See Also
345 --------
346 pyvista.Prop3D.transform
347 Apply a transformation to the :attr:`user_matrix`.
348
349 Returns
350 -------
351 np.ndarray
352 A 4x4 transformation matrix.
353
354 Examples
355 --------
356 Apply a 4x4 translation to a wireframe actor. This 4x4 transformation
357 effectively translates the actor by one unit in the Z direction,
358 rotates the actor about the z-axis by approximately 45 degrees, and
359 shrinks the actor by a factor of 0.5.
360
361 >>> import pyvista as pv
362 >>> mesh = pv.Cube()
363 >>> pl = pv.Plotter()
364 >>> _ = pl.add_mesh(mesh, color='b')
365 >>> actor = pl.add_mesh(
366 ... mesh,
367 ... color='r',
368 ... style='wireframe',
369 ... line_width=5,
370 ... lighting=False,
371 ... )
372 >>> arr = [
373 ... [0.707, -0.707, 0, 0],
374 ... [0.707, 0.707, 0, 0],
375 ... [0, 0, 1, 1.5],
376 ... [0, 0, 0, 2],
377 ... ]
378 >>> actor.user_matrix = arr
379 >>> pl.show_axes()
380 >>> pl.show()
381
382 """
383 if self.GetUserMatrix() is None:
384 self.SetUserMatrix(vtkmatrix_from_array(np.eye(4)))
385 return array_from_vtkmatrix(self.GetUserMatrix())
386
387 @user_matrix.setter
388 def user_matrix(self, value: TransformLike) -> None:
389 array = np.eye(4) if value is None else _validation.validate_transform4x4(value)
390 self.SetUserMatrix(vtkmatrix_from_array(array))
391
392 def transform(
393 self,
394 trans: TransformLike,
395 multiply_mode: Literal['pre', 'post'] = 'post',
396 *,
397 inplace: bool = False,
398 ):
399 """Apply a transformation to this object's :attr:`~Prop3D.user_matrix`.
400
401 .. note::
402
403 This applies a transformation by modifying the :attr:`user_matrix`. This
404 differs from methods like :meth:`rotate_x`, :meth:`rotate_y`, :meth:`rotate_z`,
405 and :meth:`rotation_from` which apply a transformation indirectly by modifying
406 the :attr:`orientation`. See the :class:`Prop3D` class description for more
407 information about how this class is transformed.
408
409 .. versionadded:: 0.45
410
411 Parameters
412 ----------
413 trans : TransformLike
414 Transformation matrix as a 3x3 or 4x4 array, :vtk:`vtkMatrix3x3` or
415 :vtk:`vtkMatrix4x4`, :vtk:`vtkTransform`, or a SciPy ``Rotation`` instance.
416 If the input is 3x3, the array is padded using a 4x4 identity matrix.
417
418 multiply_mode : 'pre' | 'post', default: 'post'
419 Multiplication mode to use.
420
421 - ``'pre'``: pre-multiply ``trans`` with the :attr:`user_matrix`, i.e.
422 ``user_matrix @ trans``. The transformation is applied `before` the
423 current user-matrix.
424 - ``'post'``: post-multiply ``trans`` with the :attr:`user_matrix`, i.e.
425 ``trans @ user_matrix``. The transformation is applied `after` the
426 current user-matrix.
427
428 inplace : bool, default: False
429 When ``True``, modifies the prop inplace. Otherwise, a copy is returned.
430
431 Returns
432 -------
433 Prop3D
434 Transformed prop.
435
436 See Also
437 --------
438 pyvista.Transform
439 Describe linear transformations via a 4x4 matrix.
440 pyvista.DataObjectFilters.transform
441 Apply a transformation to a mesh.
442
443 """
444 # Validate input
445 _validation.check_contains(
446 ['pre', 'post'], must_contain=multiply_mode, name='multiply_mode'
447 )
448 matrix = _validation.validate_transform4x4(trans)
449
450 # Update user matrix
451 new_matrix = (
452 self.user_matrix @ matrix if multiply_mode == 'pre' else matrix @ self.user_matrix
453 )
454 output = self if inplace else self.copy()
455 output.user_matrix = new_matrix
456 return output
457
458 @abstractmethod
459 @_deprecate_positional_args
460 def copy(
461 self: Self,
462 deep: bool = True, # noqa: FBT001, FBT002
463 ) -> Self: # numpydoc ignore=RT01
464 """Return a copy of this prop."""
465 raise NotImplementedError # pragma: no cover
466
467 @property
468 def length(self) -> float: # numpydoc ignore=RT01
469 """Return the length of the entity.
470
471 Examples
472 --------
473 >>> import pyvista as pv
474 >>> pl = pv.Plotter()
475 >>> actor = pl.add_mesh(pv.Sphere())
476 >>> actor.length
477 1.7272069317100354
478
479 """
480 return self.GetLength()
481
482 def rotation_from(self, rotation: RotationLike) -> None:
483 """Set the entity's orientation from a rotation.
484
485 Set the rotation of this entity from a 3x3 rotation matrix. This includes
486 NumPy arrays, a :vtk:`vtkMatrix3x3`, and SciPy ``Rotation`` objects.
487
488 This method may be used as an alternative for setting the :attr:`orientation`.
489
490 .. versionadded:: 0.45
491
492 Parameters
493 ----------
494 rotation : RotationLike
495 3x3 rotation matrix or a SciPy ``Rotation`` object.
496
497 Examples
498 --------
499 Create an actor and show its initial orientation.
500
501 >>> import pyvista as pv
502 >>> pl = pv.Plotter()
503 >>> actor = pl.add_mesh(pv.Sphere())
504 >>> actor.orientation
505 (0.0, -0.0, 0.0)
506
507 Set the orientation using a 3x3 matrix.
508
509 >>> actor.rotation_from([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
510 >>> actor.orientation
511 (0.0, -180.0, -90.0)
512
513 """
514 self.orientation = _rotation_matrix_as_orientation(rotation) # type: ignore[arg-type]
515
516
517 def _rotation_matrix_as_orientation(
518 array: NumpyArray[float] | _vtk.vtkMatrix3x3,
519 ) -> tuple[float, float, float]:
520 """Convert a 3x3 rotation matrix to x-y-z orientation angles.
521
522 The orientation angles define rotations about the world's x-y-z axes. The angles
523 are specified in degrees and in x-y-z order. However, the rotations should
524 be applied in the order: first rotate about the y-axis, then x-axis, then z-axis.
525
526 The rotation angles and rotation matrix can be used interchangeably for
527 transformations.
528
529 Parameters
530 ----------
531 array : NumpyArray[float] | :vtk:`vtkMatrix3x3`
532 3x3 rotation matrix as a NumPy array or a :vtk:`vtkMatrix3x3`.
533
534 Returns
535 -------
536 tuple
537 Tuple with x-y-z axis rotation angles in degrees.
538
539 """
540 return Transform().rotate(array).GetOrientation()
541
542
543 def _orientation_as_rotation_matrix(orientation: VectorLike[float]) -> NumpyArray[float]:
544 """Convert x-y-z orientation angles to a 3x3 matrix.
545
546 The orientation angles define rotations about the world's x-y-z axes. The angles
547 are specified in degrees and in x-y-z order. However, the rotations should
548 be applied in the order: first rotate about the y-axis, then x-axis, then z-axis.
549
550 The rotation angles and rotation matrix can be used interchangeably for
551 transformations.
552
553 Parameters
554 ----------
555 orientation : VectorLike[float]
556 The x-y-z axis orientation angles in degrees.
557
558 Returns
559 -------
560 numpy.ndarray
561 3x3 rotation matrix.
562
563 """
564 valid_orientation = _validation.validate_array3(orientation, name='orientation')
565 prop = _vtk.vtkActor()
566 prop.SetOrientation(valid_orientation)
567 matrix = _vtk.vtkMatrix4x4()
568 prop.GetMatrix(matrix)
569 return array_from_vtkmatrix(matrix)[:3, :3]
570
571
572 class _Prop3DMixin(_BoundsSizeMixin, ABC):
573 """Add 3D transformations to props which do not inherit from :class:`pyvista.Prop3D`.
574
575 Derived classes need to implement the :meth:`_post_set_update` method to define
576 their behavior, e.g. manually apply a transformation.
577 """
578
579 def __init__(self) -> None:
580 from pyvista import Actor # Avoid circular import # noqa: PLC0415
581
582 self._prop3d = Actor()
583
584 @property
585 @wraps(Prop3D.scale.fget) # type: ignore[attr-defined]
586 def scale(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
587 """Wrap :class:`pyvista.Prop3D.scale."""
588 return self._prop3d.scale
589
590 @scale.setter
591 @wraps(Prop3D.scale.fset) # type: ignore[attr-defined]
592 def scale(self, scale: VectorLike[float]) -> None:
593 self._prop3d.scale = scale
594 self._post_set_update()
595
596 @property
597 @wraps(Prop3D.position.fget) # type: ignore[attr-defined]
598 def position(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
599 """Wrap :class:`pyvista.Prop3D.position."""
600 return self._prop3d.position
601
602 @position.setter
603 @wraps(Prop3D.position.fset) # type: ignore[attr-defined]
604 def position(self, position: VectorLike[float]) -> None:
605 self._prop3d.position = position
606 self._post_set_update()
607
608 @property
609 @wraps(Prop3D.orientation.fget) # type: ignore[attr-defined]
610 def orientation(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
611 """Wrap :class:`pyvista.Prop3D.orientation."""
612 return self._prop3d.orientation
613
614 @orientation.setter
615 @wraps(Prop3D.orientation.fset) # type: ignore[attr-defined]
616 def orientation(self, orientation: VectorLike[float]) -> None:
617 self._prop3d.orientation = orientation
618 self._post_set_update()
619
620 @property
621 @wraps(Prop3D.origin.fget) # type: ignore[attr-defined]
622 def origin(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
623 """Wrap :class:`pyvista.Prop3D.origin."""
624 return self._prop3d.origin
625
626 @origin.setter
627 @wraps(Prop3D.origin.fset) # type: ignore[attr-defined]
628 def origin(self, origin: VectorLike[float]) -> None:
629 self._prop3d.origin = origin
630 self._post_set_update()
631
632 @property
633 @wraps(Prop3D.user_matrix.fget) # type: ignore[attr-defined]
634 def user_matrix(self) -> NumpyArray[float]: # numpydoc ignore=RT01
635 """Wrap :class:`pyvista.Prop3D.user_matrix."""
636 return self._prop3d.user_matrix
637
638 @user_matrix.setter
639 @wraps(Prop3D.user_matrix.fset) # type: ignore[attr-defined]
640 def user_matrix(self, matrix: TransformLike) -> None:
641 self._prop3d.user_matrix = matrix
642 self._post_set_update()
643
644 @property
645 def _transformation_matrix(self):
646 """Transformation matrix applied to the actor.
647
648 The transformation is computed from the attributes :attr:`position`
649 :attr:`origin`, :attr:`scale`, :attr:`orientation`, and :attr:`user_matrix`.
650
651 It is the actual transformation applied to the actor under-the-hood by vtk.
652 """
653 return array_from_vtkmatrix(self._prop3d.GetMatrix())
654
655 @abstractmethod
656 def _post_set_update(self):
657 """Update object after setting Prop3D attributes."""
658
659 @abstractmethod
660 def _get_bounds(self) -> BoundsTuple:
661 """Return the object's 3D bounds."""
662
663 @property
664 @wraps(Prop3D.bounds.fget) # type: ignore[attr-defined]
665 def bounds(self) -> BoundsTuple: # numpydoc ignore=RT01
666 """Wrap :class:`pyvista.Prop3D.bounds`."""
667 return BoundsTuple(*self._get_bounds())
668
669 @property
670 @wraps(Prop3D.center.fget) # type: ignore[attr-defined]
671 def center(self) -> tuple[float, float, float]: # numpydoc ignore=RT01
672 """Wrap :class:`pyvista.Prop3D.center."""
673 bnds = self.bounds
674 return (
675 (bnds.x_min + bnds.x_max) / 2,
676 (bnds.y_min + bnds.y_max) / 2,
677 (bnds.z_min + bnds.z_max) / 2,
678 )
679
680 @property
681 @wraps(Prop3D.length.fget) # type: ignore[attr-defined]
682 def length(self) -> float: # numpydoc ignore=RT01
683 """Wrap :class:`pyvista.Prop3D.length."""
684 bnds = self.bounds
685 return np.linalg.norm(
686 (bnds.x_max - bnds.x_min, bnds.y_max - bnds.y_min, bnds.z_max - bnds.z_min)
687 ).tolist()