Debian Codegraph @

pyvista/core/utilities/geometric_sources.py

raw
1 """Provides an easy way of generating several geometric sources.
2
3 Also includes some pure-python helpers.
4
5 """
6
7 from __future__ import annotations
8
9 from enum import IntEnum
10 import itertools
11 from typing import TYPE_CHECKING
12 from typing import Any
13 from typing import ClassVar
14 from typing import Literal
15 from typing import cast
16 from typing import get_args
17
18 import numpy as np
19
20 import pyvista as pv
21 from pyvista import _vtk
22 from pyvista._deprecate_positional_args import _deprecate_positional_args
23 from pyvista.core import _validation
24 from pyvista.core._typing_core import BoundsTuple
25 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
26 from pyvista.core._vtk_utilities import vtk_version_info
27 from pyvista.core.utilities.arrays import _coerce_pointslike_arg
28 from pyvista.core.utilities.helpers import wrap
29 from pyvista.core.utilities.misc import _check_range
30 from pyvista.core.utilities.misc import _NoNewAttrMixin
31 from pyvista.core.utilities.misc import _reciprocal
32
33 if TYPE_CHECKING:
34 from collections.abc import Sequence
35
36 from pyvista.core._typing_core import MatrixLike
37 from pyvista.core._typing_core import NumpyArray
38 from pyvista.core._typing_core import VectorLike
39 from pyvista.core.composite import MultiBlock
40 from pyvista.core.dataset import DataSet
41 from pyvista.core.pointset import PolyData
42
43
44 SINGLE_PRECISION = _vtk.vtkAlgorithm.SINGLE_PRECISION
45 DOUBLE_PRECISION = _vtk.vtkAlgorithm.DOUBLE_PRECISION
46
47
48 def translate(
49 surf: DataSet,
50 center: VectorLike[float] = (0.0, 0.0, 0.0),
51 direction: VectorLike[float] = (1.0, 0.0, 0.0),
52 ) -> None:
53 """Translate and orient a mesh to a new center and direction.
54
55 By default, the input mesh is considered centered at the origin
56 and facing in the x direction.
57
58 Parameters
59 ----------
60 surf : pyvista.core.pointset.PolyData
61 Mesh to be translated and oriented.
62 center : tuple, optional, default: (0.0, 0.0, 0.0)
63 Center point to which the mesh should be translated.
64 direction : tuple, optional, default: (1.0, 0.0, 0.0)
65 Direction vector along which the mesh should be oriented.
66
67 """
68 normx = np.array(direction) / np.linalg.norm(direction)
69 normy_temp = [0.0, 1.0, 0.0]
70
71 # Adjust normy if collinear with normx since cross-product will
72 # be zero otherwise
73 if np.allclose(normx, [0, 1, 0]):
74 normy_temp = [-1.0, 0.0, 0.0]
75 elif np.allclose(normx, [0, -1, 0]):
76 normy_temp = [1.0, 0.0, 0.0]
77
78 normz = np.cross(normx, normy_temp)
79 normz /= np.linalg.norm(normz)
80 normy = np.cross(normz, normx)
81
82 trans = np.zeros((4, 4))
83 trans[:3, 0] = normx
84 trans[:3, 1] = normy
85 trans[:3, 2] = normz
86 trans[3, 3] = 1
87
88 surf.transform(trans, inplace=True)
89 if not np.allclose(center, [0.0, 0.0, 0.0]):
90 surf.points += np.array(center, dtype=surf.points.dtype)
91
92
93 if vtk_version_info < (9, 3):
94
95 class CapsuleSource(_NoNewAttrMixin, _vtk.vtkCapsuleSource): # type: ignore[misc]
96 """Capsule source algorithm class.
97
98 .. versionadded:: 0.44.0
99
100 Parameters
101 ----------
102 center : sequence[float], default: (0.0, 0.0, 0.0)
103 Center in ``[x, y, z]``.
104
105 direction : sequence[float], default: (1.0, 0.0, 0.0)
106 Direction of the capsule in ``[x, y, z]``.
107
108 radius : float, default: 0.5
109 Radius of the capsule.
110
111 cylinder_length : float, default: 1.0
112 Cylinder length of the capsule.
113
114 theta_resolution : int, default: 30
115 Set the number of points in the azimuthal direction (ranging
116 from ``start_theta`` to ``end_theta``).
117
118 phi_resolution : int, default: 30
119 Set the number of points in the polar direction (ranging from
120 ``start_phi`` to ``end_phi``).
121
122 Examples
123 --------
124 Create a default CapsuleSource.
125
126 >>> import pyvista as pv
127 >>> source = pv.CapsuleSource()
128 >>> source.output.plot(show_edges=True, line_width=5)
129
130 """
131
132 @_deprecate_positional_args
133 def __init__( # noqa: PLR0917
134 self: CapsuleSource,
135 center: VectorLike[float] = (0.0, 0.0, 0.0),
136 direction: VectorLike[float] = (1.0, 0.0, 0.0),
137 radius: float = 0.5,
138 cylinder_length: float = 1.0,
139 theta_resolution: int = 30,
140 phi_resolution: int = 30,
141 ) -> None:
142 """Initialize the capsule source class."""
143 super().__init__()
144 self.center = center
145 self.direction = direction
146 self.radius = radius
147 self.cylinder_length = cylinder_length
148 self.theta_resolution = theta_resolution
149 self.phi_resolution = phi_resolution
150
151 @property
152 def center(self: CapsuleSource) -> tuple[float, float, float]:
153 """Get the center in ``[x, y, z]``. Axis of the capsule passes through this point.
154
155 Returns
156 -------
157 tuple[float, float, float]
158 Center in ``[x, y, z]``. Axis of the capsule passes through this
159 point.
160
161 """
162 return self.GetCenter()
163
164 @center.setter
165 def center(self: CapsuleSource, center: VectorLike[float]) -> None:
166 """Set the center in ``[x, y, z]``. Axis of the capsule passes through this point.
167
168 Parameters
169 ----------
170 center : sequence[float]
171 Center in ``[x, y, z]``. Axis of the capsule passes through this
172 point.
173
174 """
175 self.SetCenter(*center)
176
177 @property
178 def direction(self: CapsuleSource) -> tuple[float, float, float]:
179 """Get the direction vector in ``[x, y, z]``. Orientation vector of the capsule.
180
181 Returns
182 -------
183 sequence[float]
184 Direction vector in ``[x, y, z]``. Orientation vector of the
185 capsule.
186
187 """
188 return self._direction
189
190 @direction.setter
191 def direction(self: CapsuleSource, direction: VectorLike[float]) -> None:
192 """Set the direction in ``[x, y, z]``. Axis of the capsule passes through this point.
193
194 Parameters
195 ----------
196 direction : sequence[float]
197 Direction vector in ``[x, y, z]``. Orientation vector of the
198 capsule.
199
200 """
201 valid_direction = _validation.validate_array3(
202 direction, dtype_out=float, to_tuple=True
203 )
204 self._direction = cast('tuple[float, float, float]', valid_direction)
205
206 @property
207 def cylinder_length(self: CapsuleSource) -> float:
208 """Get the cylinder length along the capsule in its specified direction.
209
210 Returns
211 -------
212 float
213 Cylinder length along the capsule in its specified direction.
214
215 """
216 return self.GetCylinderLength()
217
218 @cylinder_length.setter
219 def cylinder_length(self: CapsuleSource, length: float) -> None:
220 """Set the cylinder length of the capsule.
221
222 Parameters
223 ----------
224 length : float
225 Cylinder length of the capsule.
226
227 """
228 self.SetCylinderLength(length)
229
230 @property
231 def radius(self: CapsuleSource) -> float:
232 """Get base radius of the capsule.
233
234 Returns
235 -------
236 float
237 Base radius of the capsule.
238
239 """
240 return self.GetRadius()
241
242 @radius.setter
243 def radius(self: CapsuleSource, radius: float) -> None:
244 """Set base radius of the capsule.
245
246 Parameters
247 ----------
248 radius : float
249 Base radius of the capsule.
250
251 """
252 self.SetRadius(radius)
253
254 @property
255 def theta_resolution(self: CapsuleSource) -> int:
256 """Get the number of points in the azimuthal direction.
257
258 Returns
259 -------
260 int
261 The number of points in the azimuthal direction.
262
263 """
264 return self.GetThetaResolution()
265
266 @theta_resolution.setter
267 def theta_resolution(self: CapsuleSource, theta_resolution: int) -> None:
268 """Set the number of points in the azimuthal direction.
269
270 Parameters
271 ----------
272 theta_resolution : int
273 The number of points in the azimuthal direction.
274
275 """
276 self.SetThetaResolution(theta_resolution)
277
278 @property
279 def phi_resolution(self: CapsuleSource) -> int:
280 """Get the number of points in the polar direction.
281
282 Returns
283 -------
284 int
285 The number of points in the polar direction.
286
287 """
288 return self.GetPhiResolution()
289
290 @phi_resolution.setter
291 def phi_resolution(self: CapsuleSource, phi_resolution: int) -> None:
292 """Set the number of points in the polar direction.
293
294 Parameters
295 ----------
296 phi_resolution : int
297 The number of points in the polar direction.
298
299 """
300 self.SetPhiResolution(phi_resolution)
301
302 @property
303 def output(self: CapsuleSource) -> PolyData:
304 """Get the output data object for a port on this algorithm.
305
306 Returns
307 -------
308 pyvista.PolyData
309 Capsule surface.
310
311 """
312 self.Update()
313 return wrap(self.GetOutput())
314
315
316 class ConeSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkConeSource):
317 """Cone source algorithm class.
318
319 Parameters
320 ----------
321 center : sequence[float], default: (0.0, 0.0, 0.0)
322 Center in ``[x, y, z]``. Axis of the cone passes through this
323 point.
324
325 direction : sequence[float], default: (1.0, 0.0, 0.0)
326 Direction vector in ``[x, y, z]``. Orientation vector of the
327 cone.
328
329 height : float, default: 1.0
330 Height along the cone in its specified direction.
331
332 radius : float, optional
333 Base radius of the cone.
334
335 capping : bool, default: True
336 Enable or disable the capping the base of the cone with a
337 polygon.
338
339 angle : float, optional
340 The angle in degrees between the axis of the cone and a
341 generatrix.
342
343 resolution : int, default: 6
344 Number of facets used to represent the cone.
345
346 Examples
347 --------
348 Create a default ConeSource.
349
350 >>> import pyvista as pv
351 >>> source = pv.ConeSource()
352 >>> source.output.plot(show_edges=True, line_width=5)
353
354 """
355
356 @_deprecate_positional_args
357 def __init__( # noqa: PLR0917
358 self: ConeSource,
359 center: VectorLike[float] = (0.0, 0.0, 0.0),
360 direction: VectorLike[float] = (1.0, 0.0, 0.0),
361 height: float = 1.0,
362 radius: float | None = None,
363 capping: bool = True, # noqa: FBT001, FBT002
364 angle: float | None = None,
365 resolution: int = 6,
366 ) -> None:
367 """Initialize the cone source class."""
368 super().__init__()
369 self.center = center
370 self.direction = direction
371 self.height = height
372 self.capping = capping
373 if angle is not None and radius is not None:
374 msg = 'Both radius and angle cannot be specified. They are mutually exclusive.'
375 raise ValueError(msg)
376 elif angle is not None and radius is None:
377 self.angle = angle
378 elif angle is None and radius is not None:
379 self.radius = radius
380 elif angle is None and radius is None:
381 self.radius = 0.5
382 self.resolution = resolution
383
384 @property
385 def center(self: ConeSource) -> tuple[float, float, float]:
386 """Get the center in ``[x, y, z]``. Axis of the cone passes through this point.
387
388 Returns
389 -------
390 tuple[float, float, float]
391 Center in ``[x, y, z]``. Axis of the cone passes through this
392 point.
393
394 """
395 return self.GetCenter()
396
397 @center.setter
398 def center(self: ConeSource, center: VectorLike[float]) -> None:
399 """Set the center in ``[x, y, z]``. Axis of the cone passes through this point.
400
401 Parameters
402 ----------
403 center : sequence[float]
404 Center in ``[x, y, z]``. Axis of the cone passes through this
405 point.
406
407 """
408 self.SetCenter(*center)
409
410 @property
411 def direction(self: ConeSource) -> tuple[float, float, float]:
412 """Get the direction vector in ``[x, y, z]``. Orientation vector of the cone.
413
414 Returns
415 -------
416 sequence[float]
417 Direction vector in ``[x, y, z]``. Orientation vector of the
418 cone.
419
420 """
421 return self.GetDirection()
422
423 @direction.setter
424 def direction(self: ConeSource, direction: VectorLike[float]) -> None:
425 """Set the direction in ``[x, y, z]``. Axis of the cone passes through this point.
426
427 Parameters
428 ----------
429 direction : sequence[float]
430 Direction vector in ``[x, y, z]``. Orientation vector of the
431 cone.
432
433 """
434 self.SetDirection(*direction)
435
436 @property
437 def height(self: ConeSource) -> float:
438 """Get the height along the cone in its specified direction.
439
440 Returns
441 -------
442 float
443 Height along the cone in its specified direction.
444
445 """
446 return self.GetHeight()
447
448 @height.setter
449 def height(self: ConeSource, height: float) -> None:
450 """Set the height of the cone.
451
452 Parameters
453 ----------
454 height : float
455 Height of the cone.
456
457 """
458 self.SetHeight(height)
459
460 @property
461 def radius(self: ConeSource) -> float:
462 """Get base radius of the cone.
463
464 Returns
465 -------
466 float
467 Base radius of the cone.
468
469 """
470 return self.GetRadius()
471
472 @radius.setter
473 def radius(self: ConeSource, radius: float) -> None:
474 """Set base radius of the cone.
475
476 Parameters
477 ----------
478 radius : float
479 Base radius of the cone.
480
481 """
482 self.SetRadius(radius)
483
484 @property
485 def capping(self: ConeSource) -> bool:
486 """Enable or disable the capping the base of the cone with a polygon.
487
488 Returns
489 -------
490 bool
491 Enable or disable the capping the base of the cone with a
492 polygon.
493
494 """
495 return bool(self.GetCapping())
496
497 @capping.setter
498 def capping(self: ConeSource, capping: bool) -> None:
499 """Set base capping of the cone.
500
501 Parameters
502 ----------
503 capping : bool, optional
504 Enable or disable the capping the base of the cone with a
505 polygon.
506
507 """
508 self.SetCapping(capping)
509
510 @property
511 def angle(self: ConeSource) -> float:
512 """Get the angle in degrees between the axis of the cone and a generatrix.
513
514 Returns
515 -------
516 float
517 The angle in degrees between the axis of the cone and a
518 generatrix.
519
520 """
521 return self.GetAngle()
522
523 @angle.setter
524 def angle(self: ConeSource, angle: float) -> None:
525 """Set the angle in degrees between the axis of the cone and a generatrix.
526
527 Parameters
528 ----------
529 angle : float, optional
530 The angle in degrees between the axis of the cone and a
531 generatrix.
532
533 """
534 self.SetAngle(angle)
535
536 @property
537 def resolution(self: ConeSource) -> int:
538 """Get number of points on the circular face of the cone.
539
540 Returns
541 -------
542 int
543 Number of points on the circular face of the cone.
544
545 """
546 return self.GetResolution()
547
548 @resolution.setter
549 def resolution(self: ConeSource, resolution: int) -> None:
550 """Set number of points on the circular face of the cone.
551
552 Parameters
553 ----------
554 resolution : int
555 Number of points on the circular face of the cone.
556
557 """
558 self.SetResolution(resolution)
559
560 @property
561 def output(self: ConeSource) -> PolyData:
562 """Get the output data object for a port on this algorithm.
563
564 Returns
565 -------
566 pyvista.PolyData
567 Cone surface.
568
569 """
570 self.Update()
571 return wrap(self.GetOutput())
572
573
574 class CylinderSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkCylinderSource):
575 """Cylinder source algorithm class.
576
577 .. warning::
578 :func:`pyvista.Cylinder` function rotates the :class:`pyvista.CylinderSource` 's
579 :class:`pyvista.PolyData` in its own way.
580 It rotates the :attr:`pyvista.CylinderSource.output` 90 degrees in z-axis, translates and
581 orients the mesh to a new ``center`` and ``direction``.
582
583 Parameters
584 ----------
585 center : sequence[float], default: (0.0, 0.0, 0.0)
586 Location of the centroid in ``[x, y, z]``.
587
588 direction : sequence[float], default: (1.0, 0.0, 0.0)
589 Direction cylinder points to in ``[x, y, z]``.
590
591 radius : float, default: 0.5
592 Radius of the cylinder.
593
594 height : float, default: 1.0
595 Height of the cylinder.
596
597 capping : bool, default: True
598 Cap cylinder ends with polygons.
599
600 resolution : int, default: 100
601 Number of points on the circular face of the cylinder.
602
603 Examples
604 --------
605 Create a default CylinderSource.
606
607 >>> import pyvista as pv
608 >>> source = pv.CylinderSource()
609 >>> source.output.plot(show_edges=True, line_width=5)
610
611 Display a 3D plot of a default :class:`CylinderSource`.
612
613 >>> import pyvista as pv
614 >>> pl = pv.Plotter()
615 >>> _ = pl.add_mesh(pv.CylinderSource(), show_edges=True, line_width=5)
616 >>> pl.show()
617
618 Visualize the output of :class:`CylinderSource` in a 3D plot.
619
620 >>> pl = pv.Plotter()
621 >>> _ = pl.add_mesh(pv.CylinderSource().output, show_edges=True, line_width=5)
622 >>> pl.show()
623
624 The above examples are similar in terms of their behavior.
625
626 """
627
628 @_deprecate_positional_args
629 def __init__( # noqa: PLR0917
630 self: CylinderSource,
631 center: VectorLike[float] = (0.0, 0.0, 0.0),
632 direction: VectorLike[float] = (1.0, 0.0, 0.0),
633 radius: float = 0.5,
634 height: float = 1.0,
635 capping: bool = True, # noqa: FBT001, FBT002
636 resolution: int = 100,
637 ) -> None:
638 """Initialize the cylinder source class."""
639 super().__init__()
640 self.center = center
641 self.direction = direction
642 self.radius = radius
643 self.height = height
644 self.resolution = resolution
645 self.capping = capping
646
647 @property
648 def center(self: CylinderSource) -> tuple[float, float, float]:
649 """Get location of the centroid in ``[x, y, z]``.
650
651 Returns
652 -------
653 tuple[float, float, float]
654 Center in ``[x, y, z]``. Axis of the cylinder passes through this
655 point.
656
657 """
658 return self._center
659
660 @center.setter
661 def center(self: CylinderSource, center: VectorLike[float]) -> None:
662 """Set location of the centroid in ``[x, y, z]``.
663
664 Parameters
665 ----------
666 center : sequence[float]
667 Center in ``[x, y, z]``. Axis of the cylinder passes through this
668 point.
669
670 """
671 valid_center = _validation.validate_array3(center, dtype_out=float, to_tuple=True)
672 self._center = cast('tuple[float, float, float]', valid_center)
673
674 @property
675 def direction(self: CylinderSource) -> tuple[float, float, float]:
676 """Get the direction vector in ``[x, y, z]``. Orientation vector of the cylinder.
677
678 Returns
679 -------
680 sequence[float]
681 Direction vector in ``[x, y, z]``. Orientation vector of the
682 cylinder.
683
684 """
685 return self._direction
686
687 @direction.setter
688 def direction(self: CylinderSource, direction: VectorLike[float]) -> None:
689 """Set the direction in ``[x, y, z]``. Axis of the cylinder passes through this point.
690
691 Parameters
692 ----------
693 direction : sequence[float]
694 Direction vector in ``[x, y, z]``. Orientation vector of the
695 cylinder.
696
697 """
698 valid_direction = _validation.validate_array3(direction, dtype_out=float, to_tuple=True)
699 self._direction = cast('tuple[float, float, float]', valid_direction)
700
701 @property
702 def radius(self: CylinderSource) -> float:
703 """Get radius of the cylinder.
704
705 Returns
706 -------
707 float
708 Radius of the cylinder.
709
710 """
711 return self.GetRadius()
712
713 @radius.setter
714 def radius(self: CylinderSource, radius: float) -> None:
715 """Set radius of the cylinder.
716
717 Parameters
718 ----------
719 radius : float
720 Radius of the cylinder.
721
722 """
723 self.SetRadius(radius)
724
725 @property
726 def height(self: CylinderSource) -> float:
727 """Get the height of the cylinder.
728
729 Returns
730 -------
731 float
732 Height of the cylinder.
733
734 """
735 return self.GetHeight()
736
737 @height.setter
738 def height(self: CylinderSource, height: float) -> None:
739 """Set the height of the cylinder.
740
741 Parameters
742 ----------
743 height : float
744 Height of the cylinder.
745
746 """
747 self.SetHeight(height)
748
749 @property
750 def resolution(self: CylinderSource) -> int:
751 """Get number of points on the circular face of the cylinder.
752
753 Returns
754 -------
755 int
756 Number of points on the circular face of the cone.
757
758 """
759 return self.GetResolution()
760
761 @resolution.setter
762 def resolution(self: CylinderSource, resolution: int) -> None:
763 """Set number of points on the circular face of the cone.
764
765 Parameters
766 ----------
767 resolution : int
768 Number of points on the circular face of the cone.
769
770 """
771 self.SetResolution(resolution)
772
773 @property
774 def capping(self: CylinderSource) -> bool:
775 """Get cap cylinder ends with polygons.
776
777 Returns
778 -------
779 bool
780 Cap cylinder ends with polygons.
781
782 """
783 return bool(self.GetCapping())
784
785 @capping.setter
786 def capping(self: CylinderSource, capping: bool) -> None:
787 """Set cap cylinder ends with polygons.
788
789 Parameters
790 ----------
791 capping : bool, optional
792 Cap cylinder ends with polygons.
793
794 """
795 self.SetCapping(capping)
796
797 @property
798 def capsule_cap(self: CylinderSource) -> bool:
799 """Get whether the capping should make the cylinder a capsule.
800
801 .. versionadded:: 0.44.0
802
803 Returns
804 -------
805 bool
806 Capsule cap.
807
808 """
809 return bool(self.GetCapsuleCap())
810
811 @capsule_cap.setter
812 def capsule_cap(self: CylinderSource, capsule_cap: bool) -> None:
813 """Set whether the capping should make the cylinder a capsule.
814
815 Parameters
816 ----------
817 capsule_cap : bool
818 Capsule cap.
819
820 """
821 self.SetCapsuleCap(capsule_cap)
822
823 @property
824 def output(self: CylinderSource) -> PolyData:
825 """Get the output data object for a port on this algorithm.
826
827 Returns
828 -------
829 pyvista.PolyData
830 Cylinder surface.
831
832 """
833 self.Update()
834 return wrap(self.GetOutput())
835
836
837 class MultipleLinesSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkLineSource):
838 """Multiple lines source algorithm class.
839
840 Parameters
841 ----------
842 points : array_like[float], default: [[-0.5, 0.0, 0.0], [0.5, 0.0, 0.0]]
843 List of points defining a broken line.
844
845 """
846
847 def __init__(self: MultipleLinesSource, points: MatrixLike[float] | None = None) -> None:
848 """Initialize the multiple lines source class."""
849 if points is None:
850 points = [[-0.5, 0.0, 0.0], [0.5, 0.0, 0.0]]
851 super().__init__()
852 self.points = points
853
854 @property
855 def points(self: MultipleLinesSource) -> NumpyArray[float]:
856 """Return the points defining a broken line.
857
858 Returns
859 -------
860 np.ndarray
861 Points defining a broken line.
862
863 """
864 return _vtk.vtk_to_numpy(self.GetPoints().GetData())
865
866 @points.setter
867 def points(self: MultipleLinesSource, points: MatrixLike[float] | VectorLike[float]) -> None:
868 """Set the list of points defining a broken line.
869
870 Parameters
871 ----------
872 points : VectorLike[float] | MatrixLike[float]
873 List of points defining a broken line.
874
875 """
876 points, _ = _coerce_pointslike_arg(points)
877 if not (len(points) >= 2):
878 msg = '>=2 points need to define multiple lines.'
879 raise ValueError(msg)
880 self.SetPoints(pv.vtk_points(points))
881
882 @property
883 def output(self: MultipleLinesSource) -> PolyData:
884 """Get the output data object for a port on this algorithm.
885
886 Returns
887 -------
888 pyvista.PolyData
889 Line mesh.
890
891 """
892 self.Update()
893 return wrap(self.GetOutput())
894
895
896 class Text3DSource(_NoNewAttrMixin):
897 """3D text from a string.
898
899 Generate 3D text from a string with a specified width, height or depth.
900
901 .. versionadded:: 0.43
902
903 .. versionchanged:: 0.48
904
905 This class no longer inherits from :vtk:`vtkVectorText`, and uses composition instead.
906
907 Parameters
908 ----------
909 string : str, default: ""
910 Text string of the source.
911
912 depth : float, optional
913 Depth of the text. If ``None``, the depth is set to half
914 the :attr:`height` by default. Set to ``0.0`` for planar
915 text.
916
917 width : float, optional
918 Width of the text. If ``None``, the width is scaled
919 proportional to :attr:`height`.
920
921 height : float, optional
922 Height of the text. If ``None``, the height is scaled
923 proportional to :attr:`width`.
924
925 center : Sequence[float], default: (0.0, 0.0, 0.0)
926 Center of the text, defined as the middle of the axis-aligned
927 bounding box of the text.
928
929 normal : Sequence[float], default: (0.0, 0.0, 1.0)
930 Normal direction of the text. The direction is parallel to the
931 :attr:`depth` of the text and points away from the front surface
932 of the text.
933
934 process_empty_string : bool, default: True
935 If ``True``, when :attr:`string` is empty the :attr:`output` is a
936 single point located at :attr:`center` instead of an empty mesh.
937 See :attr:`process_empty_string` for details.
938
939 """
940
941 @_deprecate_positional_args(allowed=['string'])
942 def __init__( # noqa: PLR0917
943 self: Text3DSource,
944 string: str | None = None,
945 depth: float | None = None,
946 width: float | None = None,
947 height: float | None = None,
948 center: VectorLike[float] = (0.0, 0.0, 0.0),
949 normal: VectorLike[float] = (0.0, 0.0, 1.0),
950 process_empty_string: bool = True, # noqa: FBT001, FBT002
951 ) -> None:
952 """Initialize source."""
953 super().__init__()
954
955 self._source = _vtk.vtkVectorText()
956 self._output = pv.PolyData()
957
958 # Set params
959 self.string = '' if string is None else string
960 self._process_empty_string = process_empty_string
961 self.center = center
962 self.normal = normal
963 self._height = height
964 self._width = width
965 self._depth = depth
966 self._modified = True
967
968 def __setattr__(self: Text3DSource, name: str, value: Any) -> None:
969 """Override to set modified flag and disable setting new attributes."""
970 if hasattr(self, name) and name != '_modified':
971 # Set modified flag
972 old_value = getattr(self, name)
973 if not np.array_equal(old_value, value):
974 object.__setattr__(self, name, value)
975 object.__setattr__(self, '_modified', True)
976 else:
977 super().__setattr__(name, value)
978
979 @property
980 def string(self: Text3DSource) -> str: # numpydoc ignore=RT01
981 """Return or set the text string."""
982 return self._source.GetText()
983
984 @string.setter
985 def string(self: Text3DSource, string: str | None) -> None:
986 self._source.SetText('' if string is None else string)
987
988 @property
989 def process_empty_string(self: Text3DSource) -> bool: # numpydoc ignore=RT01
990 """Return or set flag to control behavior when empty strings are set.
991
992 When :attr:`string` is empty or only contains whitespace, the :attr:`output`
993 mesh will be empty. This can cause the bounds of the output to be undefined.
994
995 If ``True``, the output is modified to instead have a single point located
996 at :attr:`center`.
997
998 """
999 return self._process_empty_string
1000
1001 @process_empty_string.setter
1002 def process_empty_string(self: Text3DSource, value: bool) -> None:
1003 self._process_empty_string = value
1004
1005 @property
1006 def center(
1007 self: Text3DSource,
1008 ) -> tuple[float, float, float]: # numpydoc ignore=RT01
1009 """Return or set the center of the text.
1010
1011 The center is defined as the middle of the axis-aligned bounding box
1012 of the text.
1013 """
1014 return self._center
1015
1016 @center.setter
1017 def center(self: Text3DSource, center: VectorLike[float]) -> None:
1018 valid_center = _validation.validate_array3(center, dtype_out=float, to_tuple=True)
1019 self._center = cast('tuple[float, float, float]', valid_center)
1020
1021 @property
1022 def normal(
1023 self: Text3DSource,
1024 ) -> tuple[float, float, float]: # numpydoc ignore=RT01
1025 """Return or set the normal direction of the text.
1026
1027 The normal direction is parallel to the :attr:`depth` of the text, and
1028 points away from the front surface of the text.
1029 """
1030 return self._normal
1031
1032 @normal.setter
1033 def normal(self: Text3DSource, normal: VectorLike[float]) -> None:
1034 normal_ = _validation.validate_array3(normal, dtype_out=float, to_tuple=True)
1035 self._normal = cast('tuple[float, float, float]', normal_)
1036
1037 @property
1038 def width(self: Text3DSource) -> float | None: # numpydoc ignore=RT01
1039 """Return or set the width of the text."""
1040 return self._width
1041
1042 @width.setter
1043 def width(self: Text3DSource, width: float | None) -> None:
1044 _check_range(
1045 width, rng=(0, float('inf')), parm_name='width'
1046 ) if width is not None else None
1047 self._width = width
1048
1049 @property
1050 def height(self: Text3DSource) -> float | None: # numpydoc ignore=RT01
1051 """Return or set the height of the text."""
1052 return self._height
1053
1054 @height.setter
1055 def height(self: Text3DSource, height: float | None) -> None:
1056 (
1057 _check_range(height, rng=(0, float('inf')), parm_name='height')
1058 if height is not None
1059 else None
1060 )
1061 self._height = height
1062
1063 @property
1064 def depth(self: Text3DSource) -> float | None: # numpydoc ignore=RT01
1065 """Return or set the depth of the text."""
1066 return self._depth
1067
1068 @depth.setter
1069 def depth(self: Text3DSource, depth: float | None) -> None:
1070 _check_range(
1071 depth, rng=(0, float('inf')), parm_name='depth'
1072 ) if depth is not None else None
1073 self._depth = depth
1074
1075 def update(self: Text3DSource) -> None:
1076 """Update the output of the source."""
1077 if self._modified:
1078 is_empty_string = self.string == '' or self.string.isspace()
1079 is_2d = self.depth == 0 or (self.depth is None and self.height == 0)
1080 if is_empty_string or is_2d:
1081 # Do not apply filters
1082 self._source.Update()
1083 out = self._source.GetOutput()
1084 else:
1085 # 3D case, apply filters
1086 # Create output filters to make text 3D
1087 extrude = _vtk.vtkLinearExtrusionFilter()
1088 extrude.SetInputConnection(self._source.GetOutputPort())
1089 extrude.SetExtrusionTypeToNormalExtrusion()
1090 extrude.SetVector(0, 0, 1)
1091
1092 tri_filter = _vtk.vtkTriangleFilter()
1093 tri_filter.SetInputConnection(extrude.GetOutputPort())
1094 tri_filter.Update()
1095 out = tri_filter.GetOutput()
1096
1097 # Modify output object
1098 self._output.copy_from(out)
1099
1100 # For empty strings, the bounds are either default values (+/- 1) initially or
1101 # become uninitialized (+/- VTK_DOUBLE_MAX) if set to empty a second time
1102 if is_empty_string and self.process_empty_string:
1103 # Add a single point to 'fix' the bounds
1104 self._output.points = (0.0, 0.0, 0.0)
1105
1106 self._transform_output()
1107 self._modified = False
1108
1109 @property
1110 def output(self: Text3DSource) -> PolyData: # numpydoc ignore=RT01
1111 """Get the output of the source.
1112
1113 The source is automatically updated by :meth:`update` prior
1114 to returning the output.
1115 """
1116 self.update()
1117 return self._output
1118
1119 def _transform_output(self: Text3DSource) -> None:
1120 """Scale, rotate, and translate the output mesh."""
1121 # Create aliases
1122 out, width, height, depth = self._output, self.width, self.height, self.depth
1123 width_set, height_set, depth_set = (
1124 width is not None,
1125 height is not None,
1126 depth is not None,
1127 )
1128
1129 # Scale mesh
1130 size_w, size_h, size_d = out.bounds_size
1131 scale_w, scale_h, scale_d = _reciprocal((size_w, size_h, size_d))
1132
1133 # Scale width and height first
1134 if width_set and height_set:
1135 # Scale independently
1136 scale_w *= width
1137 scale_h *= height
1138 elif not width_set and height_set:
1139 # Scale proportional to height
1140 scale_h *= height
1141 scale_w = scale_h
1142 elif width_set and not height_set:
1143 # Scale proportional to width
1144 scale_w *= width
1145 scale_h = scale_w
1146 else:
1147 # Do not scale
1148 scale_w = 1
1149 scale_h = 1
1150
1151 out.points[:, 0] *= scale_w
1152 out.points[:, 1] *= scale_h
1153
1154 # Scale depth
1155 if depth_set:
1156 if depth == 0:
1157 # Do not scale since depth is already zero (no extrusion)
1158 scale_d = 1
1159 else:
1160 scale_d *= depth
1161 else:
1162 # Scale to half the height by default
1163 scale_d *= size_h * scale_h * 0.5
1164
1165 out.points[:, 2] *= scale_d
1166
1167 # Center points at origin
1168 out.points -= out.center
1169
1170 # Move to final position.
1171 # Only rotate if non-default normal.
1172 if not np.array_equal(self.normal, (0, 0, 1)):
1173 out.rotate_x(90, inplace=True)
1174 out.rotate_z(90, inplace=True)
1175 translate(out, self.center, self.normal)
1176 else:
1177 out.points += self.center
1178
1179
1180 class CubeSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkCubeSource):
1181 """Cube source algorithm class.
1182
1183 .. versionadded:: 0.44.0
1184
1185 Parameters
1186 ----------
1187 center : sequence[float], default: (0.0, 0.0, 0.0)
1188 Center in ``[x, y, z]``.
1189
1190 x_length : float, default: 1.0
1191 Length of the cube in the x-direction.
1192
1193 y_length : float, default: 1.0
1194 Length of the cube in the y-direction.
1195
1196 z_length : float, default: 1.0
1197 Length of the cube in the z-direction.
1198
1199 bounds : sequence[float], optional
1200 Specify the bounding box of the cube. If given, all other size
1201 arguments are ignored. ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
1202
1203 point_dtype : str, default: 'float32'
1204 Set the desired output point types. It must be either 'float32' or 'float64'.
1205
1206 .. versionadded:: 0.44.0
1207
1208 Examples
1209 --------
1210 Create a default CubeSource.
1211
1212 >>> import pyvista as pv
1213 >>> source = pv.CubeSource()
1214 >>> source.output.plot(show_edges=True, line_width=5)
1215
1216 """
1217
1218 @_deprecate_positional_args
1219 def __init__( # noqa: PLR0917
1220 self: CubeSource,
1221 center: VectorLike[float] = (0.0, 0.0, 0.0),
1222 x_length: float = 1.0,
1223 y_length: float = 1.0,
1224 z_length: float = 1.0,
1225 bounds: VectorLike[float] | None = None,
1226 point_dtype: str = 'float32',
1227 ) -> None:
1228 """Initialize the cube source class."""
1229 super().__init__()
1230 if bounds is not None:
1231 self.bounds = bounds
1232 else:
1233 self.center = center
1234 self.x_length = x_length
1235 self.y_length = y_length
1236 self.z_length = z_length
1237 self.point_dtype = point_dtype
1238
1239 @property
1240 def bounds(self: CubeSource) -> BoundsTuple: # numpydoc ignore=RT01
1241 """Return or set the bounding box of the cube."""
1242 bnds = [0.0] * 6
1243 self.GetBounds(bnds)
1244 return BoundsTuple(*bnds)
1245
1246 @bounds.setter
1247 def bounds(self: CubeSource, bounds: VectorLike[float]) -> None:
1248 if np.array(bounds).size != 6:
1249 msg = (
1250 'Bounds must be given as length 6 tuple: '
1251 '(x_min, x_max, y_min, y_max, z_min, z_max)'
1252 )
1253 raise TypeError(msg)
1254 self.SetBounds(bounds) # type: ignore[arg-type]
1255
1256 @property
1257 def center(self: CubeSource) -> tuple[float, float, float]:
1258 """Get the center in ``[x, y, z]``.
1259
1260 Returns
1261 -------
1262 tuple[float, float, float]
1263 Center in ``[x, y, z]``.
1264
1265 """
1266 return self.GetCenter()
1267
1268 @center.setter
1269 def center(self: CubeSource, center: VectorLike[float]) -> None:
1270 """Set the center in ``[x, y, z]``.
1271
1272 Parameters
1273 ----------
1274 center : sequence[float]
1275 Center in ``[x, y, z]``.
1276
1277 """
1278 self.SetCenter(*center)
1279
1280 @property
1281 def x_length(self: CubeSource) -> float:
1282 """Get the x length along the cube in its specified direction.
1283
1284 Returns
1285 -------
1286 float
1287 XLength along the cone in its specified direction.
1288
1289 """
1290 return self.GetXLength()
1291
1292 @x_length.setter
1293 def x_length(self: CubeSource, x_length: float) -> None:
1294 """Set the x length of the cube.
1295
1296 Parameters
1297 ----------
1298 x_length : float
1299 XLength of the cone.
1300
1301 """
1302 self.SetXLength(x_length)
1303
1304 @property
1305 def y_length(self: CubeSource) -> float:
1306 """Get the y length along the cube in its specified direction.
1307
1308 Returns
1309 -------
1310 float
1311 YLength along the cone in its specified direction.
1312
1313 """
1314 return self.GetYLength()
1315
1316 @y_length.setter
1317 def y_length(self: CubeSource, y_length: float) -> None:
1318 """Set the y length of the cube.
1319
1320 Parameters
1321 ----------
1322 y_length : float
1323 YLength of the cone.
1324
1325 """
1326 self.SetYLength(y_length)
1327
1328 @property
1329 def z_length(self: CubeSource) -> float:
1330 """Get the z length along the cube in its specified direction.
1331
1332 Returns
1333 -------
1334 float
1335 ZLength along the cone in its specified direction.
1336
1337 """
1338 return self.GetZLength()
1339
1340 @z_length.setter
1341 def z_length(self: CubeSource, z_length: float) -> None:
1342 """Set the z length of the cube.
1343
1344 Parameters
1345 ----------
1346 z_length : float
1347 ZLength of the cone.
1348
1349 """
1350 self.SetZLength(z_length)
1351
1352 @property
1353 def output(self: CubeSource) -> PolyData:
1354 """Get the output data object for a port on this algorithm.
1355
1356 Returns
1357 -------
1358 pyvista.PolyData
1359 Cube surface.
1360
1361 """
1362 self.Update()
1363 return wrap(self.GetOutput())
1364
1365 @property
1366 def point_dtype(self: CubeSource) -> str:
1367 """Get the desired output point types.
1368
1369 Returns
1370 -------
1371 str
1372 Desired output point types.
1373 It must be either 'float32' or 'float64'.
1374
1375 """
1376 precision = self.GetOutputPointsPrecision()
1377 return {
1378 SINGLE_PRECISION: 'float32',
1379 DOUBLE_PRECISION: 'float64',
1380 }[precision] # type: ignore[index]
1381
1382 @point_dtype.setter
1383 def point_dtype(self: CubeSource, point_dtype: str) -> None:
1384 """Set the desired output point types.
1385
1386 Parameters
1387 ----------
1388 point_dtype : str, default: 'float32'
1389 Set the desired output point types.
1390 It must be either 'float32' or 'float64'.
1391
1392 Returns
1393 -------
1394 point_dtype: str
1395 Desired output point types.
1396
1397 """
1398 if point_dtype not in ['float32', 'float64']:
1399 msg = "Point dtype must be either 'float32' or 'float64'"
1400 raise ValueError(msg)
1401 precision = {
1402 'float32': SINGLE_PRECISION,
1403 'float64': DOUBLE_PRECISION,
1404 }[point_dtype]
1405 self.SetOutputPointsPrecision(precision)
1406
1407
1408 class DiscSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkDiskSource):
1409 """Disc source algorithm class.
1410
1411 .. versionadded:: 0.44.0
1412
1413 Parameters
1414 ----------
1415 center : sequence[float], default: (0.0, 0.0, 0.0)
1416 Center in ``[x, y, z]``. Middle of the axis of the disc.
1417
1418 inner : float, default: 0.25
1419 The inner radius.
1420
1421 outer : float, default: 0.5
1422 The outer radius.
1423
1424 r_res : int, default: 1
1425 Number of points in radial direction.
1426
1427 c_res : int, default: 6
1428 Number of points in circumferential direction.
1429
1430 Examples
1431 --------
1432 Create a disc with 50 points in the circumferential direction.
1433
1434 >>> import pyvista as pv
1435 >>> source = pv.DiscSource(c_res=50)
1436 >>> source.output.plot(show_edges=True, line_width=5)
1437
1438 """
1439
1440 @_deprecate_positional_args
1441 def __init__( # noqa: PLR0917
1442 self: DiscSource,
1443 center: VectorLike[float] | None = None,
1444 inner: float = 0.25,
1445 outer: float = 0.5,
1446 r_res: int = 1,
1447 c_res: int = 6,
1448 ) -> None:
1449 """Initialize the disc source class."""
1450 super().__init__()
1451 if center is not None:
1452 self.center = center
1453 self.inner = inner
1454 self.outer = outer
1455 self.r_res = r_res
1456 self.c_res = c_res
1457
1458 @property
1459 def center(self: DiscSource) -> tuple[float, float, float]:
1460 """Get the center in ``[x, y, z]``.
1461
1462 Returns
1463 -------
1464 tuple[float, float, float]
1465 Center in ``[x, y, z]``.
1466
1467 """
1468 return self.GetCenter()
1469
1470 @center.setter
1471 def center(self: DiscSource, center: VectorLike[float]) -> None:
1472 """Set the center in ``[x, y, z]``.
1473
1474 Parameters
1475 ----------
1476 center : sequence[float]
1477 Center in ``[x, y, z]``.
1478
1479 """
1480 self.SetCenter(*center)
1481
1482 @property
1483 def inner(self: DiscSource) -> float:
1484 """Get the inner radius.
1485
1486 Returns
1487 -------
1488 float
1489 The inner radius.
1490
1491 """
1492 return self.GetInnerRadius()
1493
1494 @inner.setter
1495 def inner(self: DiscSource, inner: float) -> None:
1496 """Set the inner radius.
1497
1498 Parameters
1499 ----------
1500 inner : float
1501 The inner radius.
1502
1503 """
1504 self.SetInnerRadius(inner)
1505
1506 @property
1507 def outer(self: DiscSource) -> float:
1508 """Get the outer radius.
1509
1510 Returns
1511 -------
1512 float
1513 The outer radius.
1514
1515 """
1516 return self.GetOuterRadius()
1517
1518 @outer.setter
1519 def outer(self: DiscSource, outer: float) -> None:
1520 """Set the outer radius.
1521
1522 Parameters
1523 ----------
1524 outer : float
1525 The outer radius.
1526
1527 """
1528 self.SetOuterRadius(outer)
1529
1530 @property
1531 def r_res(self: DiscSource) -> int:
1532 """Get number of points in radial direction.
1533
1534 Returns
1535 -------
1536 int
1537 Number of points in radial direction.
1538
1539 """
1540 return self.GetRadialResolution()
1541
1542 @r_res.setter
1543 def r_res(self: DiscSource, r_res: int) -> None:
1544 """Set number of points in radial direction.
1545
1546 Parameters
1547 ----------
1548 r_res : int
1549 Number of points in radial direction.
1550
1551 """
1552 self.SetRadialResolution(r_res)
1553
1554 @property
1555 def c_res(self: DiscSource) -> int:
1556 """Get number of points in circumferential direction.
1557
1558 Returns
1559 -------
1560 int
1561 Number of points in circumferential direction.
1562
1563 """
1564 return self.GetCircumferentialResolution()
1565
1566 @c_res.setter
1567 def c_res(self: DiscSource, c_res: int) -> None:
1568 """Set number of points in circumferential direction.
1569
1570 Parameters
1571 ----------
1572 c_res : int
1573 Number of points in circumferential direction.
1574
1575 """
1576 self.SetCircumferentialResolution(c_res)
1577
1578 @property
1579 def output(self: DiscSource) -> PolyData:
1580 """Get the output data object for a port on this algorithm.
1581
1582 Returns
1583 -------
1584 pyvista.PolyData
1585 Line mesh.
1586
1587 """
1588 self.Update()
1589 return wrap(self.GetOutput())
1590
1591
1592 class LineSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkLineSource):
1593 """Create a line.
1594
1595 .. versionadded:: 0.44
1596
1597 Parameters
1598 ----------
1599 pointa : sequence[float], default: (-0.5, 0.0, 0.0)
1600 Location in ``[x, y, z]``.
1601
1602 pointb : sequence[float], default: (0.5, 0.0, 0.0)
1603 Location in ``[x, y, z]``.
1604
1605 resolution : int, default: 1
1606 Number of pieces to divide line into.
1607
1608 """
1609
1610 def __init__(
1611 self: LineSource,
1612 pointa: VectorLike[float] = (-0.5, 0.0, 0.0),
1613 pointb: VectorLike[float] = (0.5, 0.0, 0.0),
1614 resolution: int = 1,
1615 ) -> None:
1616 """Initialize source."""
1617 super().__init__()
1618 self.pointa = pointa
1619 self.pointb = pointb
1620 self.resolution = resolution
1621
1622 @property
1623 def pointa(self: LineSource) -> tuple[float, float, float]:
1624 """Location in ``[x, y, z]``.
1625
1626 Returns
1627 -------
1628 sequence[float]
1629 Location in ``[x, y, z]``.
1630
1631 """
1632 return self.GetPoint1()
1633
1634 @pointa.setter
1635 def pointa(self: LineSource, pointa: VectorLike[float]) -> None:
1636 """Set the Location in ``[x, y, z]``.
1637
1638 Parameters
1639 ----------
1640 pointa : sequence[float]
1641 Location in ``[x, y, z]``.
1642
1643 """
1644 self.SetPoint1(*pointa)
1645
1646 @property
1647 def pointb(self: LineSource) -> tuple[float, float, float]:
1648 """Location in ``[x, y, z]``.
1649
1650 Returns
1651 -------
1652 sequence[float]
1653 Location in ``[x, y, z]``.
1654
1655 """
1656 return self.GetPoint2()
1657
1658 @pointb.setter
1659 def pointb(self: LineSource, pointb: VectorLike[float]) -> None:
1660 """Set the Location in ``[x, y, z]``.
1661
1662 Parameters
1663 ----------
1664 pointb : sequence[float]
1665 Location in ``[x, y, z]``.
1666
1667 """
1668 self.SetPoint2(*pointb)
1669
1670 @property
1671 def resolution(self: LineSource) -> int:
1672 """Number of pieces to divide line into.
1673
1674 Returns
1675 -------
1676 int
1677 Number of pieces to divide line into.
1678
1679 """
1680 return self.GetResolution()
1681
1682 @resolution.setter
1683 def resolution(self: LineSource, resolution: int) -> None:
1684 """Set number of pieces to divide line into.
1685
1686 Parameters
1687 ----------
1688 resolution : int
1689 Number of pieces to divide line into.
1690
1691 """
1692 if resolution <= 0:
1693 msg = 'Resolution must be positive'
1694 raise ValueError(msg)
1695 self.SetResolution(resolution)
1696
1697 @property
1698 def output(self: LineSource) -> PolyData:
1699 """Get the output data object for a port on this algorithm.
1700
1701 Returns
1702 -------
1703 pyvista.PolyData
1704 Line mesh.
1705
1706 """
1707 self.Update()
1708 return wrap(self.GetOutput())
1709
1710
1711 class SphereSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkSphereSource):
1712 """Sphere source algorithm class.
1713
1714 .. versionadded:: 0.44.0
1715
1716 Parameters
1717 ----------
1718 radius : float, default: 0.5
1719 Sphere radius.
1720
1721 center : sequence[float], default: (0.0, 0.0, 0.0)
1722 Center coordinate vector in ``[x, y, z]``.
1723
1724 theta_resolution : int, default: 30
1725 Set the number of points in the azimuthal direction (ranging
1726 from ``start_theta`` to ``end_theta``).
1727
1728 phi_resolution : int, default: 30
1729 Set the number of points in the polar direction (ranging from
1730 ``start_phi`` to ``end_phi``).
1731
1732 start_theta : float, default: 0.0
1733 Starting azimuthal angle in degrees ``[0, 360]``.
1734
1735 end_theta : float, default: 360.0
1736 Ending azimuthal angle in degrees ``[0, 360]``.
1737
1738 start_phi : float, default: 0.0
1739 Starting polar angle in degrees ``[0, 180]``.
1740
1741 end_phi : float, default: 180.0
1742 Ending polar angle in degrees ``[0, 180]``.
1743
1744 See Also
1745 --------
1746 pyvista.Icosphere : Sphere created from projection of icosahedron.
1747 pyvista.SolidSphere : Sphere that fills 3D space.
1748
1749 Examples
1750 --------
1751 Create a sphere using default parameters.
1752
1753 >>> import pyvista as pv
1754 >>> sphere = pv.SphereSource()
1755 >>> sphere.output.plot(show_edges=True)
1756
1757 Create a quarter sphere by setting ``end_theta``.
1758
1759 >>> sphere = pv.SphereSource(end_theta=90)
1760 >>> out = sphere.output.plot(show_edges=True)
1761
1762 Create a hemisphere by setting ``end_phi``.
1763
1764 >>> sphere = pv.SphereSource(end_phi=90)
1765 >>> out = sphere.output.plot(show_edges=True)
1766
1767 """
1768
1769 @_deprecate_positional_args
1770 def __init__( # noqa: PLR0917
1771 self: SphereSource,
1772 radius: float = 0.5,
1773 center: VectorLike[float] | None = None,
1774 theta_resolution: int = 30,
1775 phi_resolution: int = 30,
1776 start_theta: float = 0.0,
1777 end_theta: float = 360.0,
1778 start_phi: float = 0.0,
1779 end_phi: float = 180.0,
1780 ) -> None:
1781 """Initialize the sphere source class."""
1782 super().__init__()
1783 self.radius = radius
1784 if center is not None: # pragma: no cover
1785 self.center = center
1786 self.theta_resolution = theta_resolution
1787 self.phi_resolution = phi_resolution
1788 self.start_theta = start_theta
1789 self.end_theta = end_theta
1790 self.start_phi = start_phi
1791 self.end_phi = end_phi
1792
1793 @property
1794 def center(self: SphereSource) -> tuple[float, float, float]:
1795 """Get the center in ``[x, y, z]``.
1796
1797 Returns
1798 -------
1799 tuple[float, float, float]
1800 Center in ``[x, y, z]``.
1801
1802 """
1803 return self.GetCenter()
1804
1805 @center.setter
1806 def center(self: SphereSource, center: VectorLike[float]) -> None:
1807 """Set the center in ``[x, y, z]``.
1808
1809 Parameters
1810 ----------
1811 center : sequence[float]
1812 Center in ``[x, y, z]``.
1813
1814 """
1815 self.SetCenter(*center)
1816
1817 @property
1818 def radius(self: SphereSource) -> float:
1819 """Get sphere radius.
1820
1821 Returns
1822 -------
1823 float
1824 Sphere radius.
1825
1826 """
1827 return self.GetRadius()
1828
1829 @radius.setter
1830 def radius(self: SphereSource, radius: float) -> None:
1831 """Set sphere radius.
1832
1833 Parameters
1834 ----------
1835 radius : float
1836 Sphere radius.
1837
1838 """
1839 self.SetRadius(radius)
1840
1841 @property
1842 def theta_resolution(self: SphereSource) -> int:
1843 """Get the number of points in the azimuthal direction.
1844
1845 Returns
1846 -------
1847 int
1848 The number of points in the azimuthal direction.
1849
1850 """
1851 return self.GetThetaResolution()
1852
1853 @theta_resolution.setter
1854 def theta_resolution(self: SphereSource, theta_resolution: int) -> None:
1855 """Set the number of points in the azimuthal direction.
1856
1857 Parameters
1858 ----------
1859 theta_resolution : int
1860 The number of points in the azimuthal direction.
1861
1862 """
1863 self.SetThetaResolution(theta_resolution)
1864
1865 @property
1866 def phi_resolution(self: SphereSource) -> int:
1867 """Get the number of points in the polar direction.
1868
1869 Returns
1870 -------
1871 int
1872 The number of points in the polar direction.
1873
1874 """
1875 return self.GetPhiResolution()
1876
1877 @phi_resolution.setter
1878 def phi_resolution(self: SphereSource, phi_resolution: int) -> None:
1879 """Set the number of points in the polar direction.
1880
1881 Parameters
1882 ----------
1883 phi_resolution : int
1884 The number of points in the polar direction.
1885
1886 """
1887 self.SetPhiResolution(phi_resolution)
1888
1889 @property
1890 def start_theta(self: SphereSource) -> float:
1891 """Get starting azimuthal angle in degrees ``[0, 360]``.
1892
1893 Returns
1894 -------
1895 float
1896 The number of points in the azimuthal direction.
1897
1898 """
1899 return self.GetStartTheta()
1900
1901 @start_theta.setter
1902 def start_theta(self: SphereSource, start_theta: float) -> None:
1903 """Set starting azimuthal angle in degrees ``[0, 360]``.
1904
1905 Parameters
1906 ----------
1907 start_theta : float
1908 The number of points in the azimuthal direction.
1909
1910 """
1911 self.SetStartTheta(start_theta)
1912
1913 @property
1914 def end_theta(self: SphereSource) -> float:
1915 """Get ending azimuthal angle in degrees ``[0, 360]``.
1916
1917 Returns
1918 -------
1919 float
1920 The number of points in the azimuthal direction.
1921
1922 """
1923 return self.GetEndTheta()
1924
1925 @end_theta.setter
1926 def end_theta(self: SphereSource, end_theta: float) -> None:
1927 """Set ending azimuthal angle in degrees ``[0, 360]``.
1928
1929 Parameters
1930 ----------
1931 end_theta : float
1932 The number of points in the azimuthal direction.
1933
1934 """
1935 self.SetEndTheta(end_theta)
1936
1937 @property
1938 def start_phi(self: SphereSource) -> float:
1939 """Get starting polar angle in degrees ``[0, 360]``.
1940
1941 Returns
1942 -------
1943 float
1944 The number of points in the polar direction.
1945
1946 """
1947 return self.GetStartPhi()
1948
1949 @start_phi.setter
1950 def start_phi(self: SphereSource, start_phi: float) -> None:
1951 """Set starting polar angle in degrees ``[0, 360]``.
1952
1953 Parameters
1954 ----------
1955 start_phi : float
1956 The number of points in the polar direction.
1957
1958 """
1959 self.SetStartPhi(start_phi)
1960
1961 @property
1962 def end_phi(self: SphereSource) -> float:
1963 """Get ending polar angle in degrees ``[0, 360]``.
1964
1965 Returns
1966 -------
1967 float
1968 The number of points in the polar direction.
1969
1970 """
1971 return self.GetEndPhi()
1972
1973 @end_phi.setter
1974 def end_phi(self: SphereSource, end_phi: float) -> None:
1975 """Set ending polar angle in degrees ``[0, 360]``.
1976
1977 Parameters
1978 ----------
1979 end_phi : float
1980 The number of points in the polar direction.
1981
1982 """
1983 self.SetEndPhi(end_phi)
1984
1985 @property
1986 def output(self: SphereSource) -> PolyData:
1987 """Get the output data object for a port on this algorithm.
1988
1989 Returns
1990 -------
1991 pyvista.PolyData
1992 Sphere surface.
1993
1994 """
1995 self.Update()
1996 return wrap(self.GetOutput())
1997
1998
1999 class PolygonSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkRegularPolygonSource):
2000 """Polygon source algorithm class.
2001
2002 .. versionadded:: 0.44.0
2003
2004 Parameters
2005 ----------
2006 center : sequence[float], default: (0.0, 0.0, 0.0)
2007 Center in ``[x, y, z]``. Central axis of the polygon passes
2008 through this point.
2009
2010 radius : float, default: 1.0
2011 The radius of the polygon.
2012
2013 normal : sequence[float], default: (0.0, 0.0, 1.0)
2014 Direction vector in ``[x, y, z]``. Orientation vector of the polygon.
2015
2016 n_sides : int, default: 6
2017 Number of sides of the polygon.
2018
2019 fill : bool, default: True
2020 Enable or disable producing filled polygons.
2021
2022 Examples
2023 --------
2024 Create an 8 sided polygon.
2025
2026 >>> import pyvista as pv
2027 >>> source = pv.PolygonSource(n_sides=8)
2028 >>> source.output.plot(show_edges=True, line_width=5)
2029
2030 """
2031
2032 @_deprecate_positional_args
2033 def __init__( # noqa: PLR0917
2034 self: PolygonSource,
2035 center: VectorLike[float] = (0.0, 0.0, 0.0),
2036 radius: float = 1.0,
2037 normal: VectorLike[float] = (0.0, 0.0, 1.0),
2038 n_sides: int = 6,
2039 fill: bool = True, # noqa: FBT001, FBT002
2040 ) -> None:
2041 """Initialize the polygon source class."""
2042 super().__init__()
2043 self.center = center
2044 self.radius = radius
2045 self.normal = normal
2046 self.n_sides = n_sides
2047 self.fill = fill
2048
2049 @property
2050 def center(self: PolygonSource) -> tuple[float, float, float]:
2051 """Get the center in ``[x, y, z]``.
2052
2053 Returns
2054 -------
2055 tuple[float, float, float]
2056 Center in ``[x, y, z]``.
2057
2058 """
2059 return self.GetCenter()
2060
2061 @center.setter
2062 def center(self: PolygonSource, center: VectorLike[float]) -> None:
2063 """Set the center in ``[x, y, z]``.
2064
2065 Parameters
2066 ----------
2067 center : sequence[float]
2068 Center in ``[x, y, z]``.
2069
2070 """
2071 self.SetCenter(*center)
2072
2073 @property
2074 def radius(self: PolygonSource) -> float:
2075 """Get the radius of the polygon.
2076
2077 Returns
2078 -------
2079 float
2080 The radius of the polygon.
2081
2082 """
2083 return self.GetRadius()
2084
2085 @radius.setter
2086 def radius(self: PolygonSource, radius: float) -> None:
2087 """Set the radius of the polygon.
2088
2089 Parameters
2090 ----------
2091 radius : float
2092 The radius of the polygon.
2093
2094 """
2095 self.SetRadius(radius)
2096
2097 @property
2098 def normal(self: PolygonSource) -> tuple[float, float, float]:
2099 """Get the normal in ``[x, y, z]``.
2100
2101 Returns
2102 -------
2103 sequence[float]
2104 Normal in ``[x, y, z]``.
2105
2106 """
2107 return self.GetNormal()
2108
2109 @normal.setter
2110 def normal(self: PolygonSource, normal: VectorLike[float]) -> None:
2111 """Set the normal in ``[x, y, z]``.
2112
2113 Parameters
2114 ----------
2115 normal : sequence[float]
2116 Normal in ``[x, y, z]``.
2117
2118 """
2119 self.SetNormal(*normal)
2120
2121 @property
2122 def n_sides(self: PolygonSource) -> int:
2123 """Get number of sides of the polygon.
2124
2125 Returns
2126 -------
2127 int
2128 Number of sides of the polygon.
2129
2130 """
2131 return self.GetNumberOfSides()
2132
2133 @n_sides.setter
2134 def n_sides(self: PolygonSource, n_sides: int) -> None:
2135 """Set number of sides of the polygon.
2136
2137 Parameters
2138 ----------
2139 n_sides : int
2140 Number of sides of the polygon.
2141
2142 """
2143 self.SetNumberOfSides(n_sides)
2144
2145 @property
2146 def fill(self: PolygonSource) -> bool:
2147 """Get enable or disable producing filled polygons.
2148
2149 Returns
2150 -------
2151 bool
2152 Enable or disable producing filled polygons.
2153
2154 """
2155 return bool(self.GetGeneratePolygon())
2156
2157 @fill.setter
2158 def fill(self: PolygonSource, fill: bool) -> None:
2159 """Set enable or disable producing filled polygons.
2160
2161 Parameters
2162 ----------
2163 fill : bool, optional
2164 Enable or disable producing filled polygons.
2165
2166 """
2167 self.SetGeneratePolygon(fill)
2168
2169 @property
2170 def output(self: PolygonSource) -> PolyData:
2171 """Get the output data object for a port on this algorithm.
2172
2173 Returns
2174 -------
2175 pyvista.PolyData
2176 Polygon surface.
2177
2178 """
2179 self.Update()
2180 return wrap(self.GetOutput())
2181
2182
2183 class PlatonicSolidSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkPlatonicSolidSource):
2184 """Platonic solid source algorithm class.
2185
2186 .. versionadded:: 0.44.0
2187
2188 Parameters
2189 ----------
2190 kind : str | int, default: 'tetrahedron'
2191 The kind of Platonic solid to create. Either the name of the
2192 polyhedron or an integer index:
2193
2194 * ``'tetrahedron'`` or ``0``
2195 * ``'cube'`` or ``1``
2196 * ``'octahedron'`` or ``2``
2197 * ``'icosahedron'`` or ``3``
2198 * ``'dodecahedron'`` or ``4``
2199
2200 Examples
2201 --------
2202 Create and plot a dodecahedron.
2203
2204 >>> import pyvista as pv
2205 >>> dodeca = pv.PlatonicSolidSource('dodecahedron')
2206 >>> dodeca.output.plot(categories=True)
2207
2208 See :ref:`create_platonic_solids_example` for more examples using this filter.
2209
2210 """
2211
2212 def __init__(self: PlatonicSolidSource, kind: str = 'tetrahedron') -> None:
2213 """Initialize the platonic solid source class."""
2214 super().__init__()
2215 self._kinds: dict[str, int] = {
2216 'tetrahedron': 0,
2217 'cube': 1,
2218 'octahedron': 2,
2219 'icosahedron': 3,
2220 'dodecahedron': 4,
2221 }
2222 self.kind = kind
2223
2224 @property
2225 def kind(self: PlatonicSolidSource) -> str:
2226 """Get the kind of Platonic solid to create.
2227
2228 Returns
2229 -------
2230 str
2231 The kind of Platonic solid to create.
2232
2233 """
2234 return list(self._kinds.keys())[self.GetSolidType()]
2235
2236 @kind.setter
2237 def kind(self: PlatonicSolidSource, kind: str | int) -> None:
2238 """Set the kind of Platonic solid to create.
2239
2240 Parameters
2241 ----------
2242 kind : str | int, default: 'tetrahedron'
2243 The kind of Platonic solid to create. Either the name of the
2244 polyhedron or an integer index:
2245
2246 * ``'tetrahedron'`` or ``0``
2247 * ``'cube'`` or ``1``
2248 * ``'octahedron'`` or ``2``
2249 * ``'icosahedron'`` or ``3``
2250 * ``'dodecahedron'`` or ``4``
2251
2252 """
2253 if isinstance(kind, int):
2254 if kind not in range(5):
2255 msg = f'Invalid Platonic solid index "{kind}".'
2256 raise ValueError(msg)
2257 self.SetSolidType(kind)
2258 return
2259
2260 if isinstance(kind, str):
2261 if kind not in self._kinds:
2262 msg = f'Invalid Platonic solid kind "{kind}".'
2263 raise ValueError(msg)
2264 self.SetSolidType(self._kinds[kind])
2265 return
2266
2267 msg = f'Invalid Platonic solid index type "{type(kind).__name__}".' # type: ignore[unreachable]
2268 raise ValueError(msg)
2269
2270 @property
2271 def output(self: PlatonicSolidSource) -> PolyData:
2272 """Get the output data object for a port on this algorithm.
2273
2274 Returns
2275 -------
2276 pyvista.PolyData
2277 PlatonicSolid surface.
2278
2279 """
2280 self.Update()
2281 return wrap(self.GetOutput())
2282
2283
2284 class PlaneSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkPlaneSource):
2285 """Create a plane source.
2286
2287 The plane is defined by specifying an origin point, and then
2288 two other points that, together with the origin, define two
2289 axes for the plane (magnitude and direction). These axes do
2290 not have to be orthogonal - so you can create a parallelogram.
2291 The axes must not be parallel.
2292
2293 .. versionadded:: 0.44
2294
2295 Parameters
2296 ----------
2297 i_resolution : int, default: 10
2298 Number of points on the plane in the i direction.
2299
2300 j_resolution : int, default: 10
2301 Number of points on the plane in the j direction.
2302
2303 center : sequence[float], default: (0.0, 0.0, 0.0)
2304 Center in ``[x, y, z]``.
2305
2306 origin : sequence[float], default: (-0.5, -0.5, 0.0)
2307 Origin in ``[x, y, z]``.
2308
2309 point_a : sequence[float], default: (0.5, -0.5, 0.0)
2310 Location in ``[x, y, z]``.
2311
2312 point_b : sequence[float], default: (-0.5, 0.5, 0.0)
2313 Location in ``[x, y, z]``.
2314
2315 """
2316
2317 @_deprecate_positional_args
2318 def __init__( # noqa: PLR0917
2319 self: PlaneSource,
2320 i_resolution: int = 10,
2321 j_resolution: int = 10,
2322 center: VectorLike[float] = (0.0, 0.0, 0.0),
2323 origin: VectorLike[float] = (-0.5, -0.5, 0.0),
2324 point_a: VectorLike[float] = (0.5, -0.5, 0.0),
2325 point_b: VectorLike[float] = (-0.5, 0.5, 0.0),
2326 ) -> None:
2327 """Initialize source."""
2328 super().__init__()
2329 self.i_resolution = i_resolution
2330 self.j_resolution = j_resolution
2331 self.center = center
2332 self.origin = origin
2333 self.point_a = point_a
2334 self.point_b = point_b
2335
2336 @property
2337 def i_resolution(self: PlaneSource) -> int:
2338 """Number of points on the plane in the i direction.
2339
2340 Returns
2341 -------
2342 int
2343 Number of points on the plane in the i direction.
2344
2345 """
2346 return self.GetXResolution()
2347
2348 @i_resolution.setter
2349 def i_resolution(self: PlaneSource, i_resolution: int) -> None:
2350 """Set number of points on the plane in the i direction.
2351
2352 Parameters
2353 ----------
2354 i_resolution : int
2355 Number of points on the plane in the i direction.
2356
2357 """
2358 self.SetXResolution(i_resolution)
2359
2360 @property
2361 def j_resolution(self: PlaneSource) -> int:
2362 """Number of points on the plane in the j direction.
2363
2364 Returns
2365 -------
2366 int
2367 Number of points on the plane in the j direction.
2368
2369 """
2370 return self.GetYResolution()
2371
2372 @j_resolution.setter
2373 def j_resolution(self: PlaneSource, j_resolution: int) -> None:
2374 """Set number of points on the plane in the j direction.
2375
2376 Parameters
2377 ----------
2378 j_resolution : int
2379 Number of points on the plane in the j direction.
2380
2381 """
2382 self.SetYResolution(j_resolution)
2383
2384 @property
2385 def center(self: PlaneSource) -> tuple[float, float, float]:
2386 """Get the center in ``[x, y, z]``.
2387
2388 The center of the plane is translated to the specified point.
2389
2390 Returns
2391 -------
2392 tuple[float, float, float]
2393 Center in ``[x, y, z]``.
2394
2395 """
2396 return self.GetCenter()
2397
2398 @center.setter
2399 def center(self: PlaneSource, center: VectorLike[float]) -> None:
2400 """Set the center in ``[x, y, z]``.
2401
2402 Parameters
2403 ----------
2404 center : sequence[float]
2405 Center in ``[x, y, z]``.
2406
2407 """
2408 self.SetCenter(*center)
2409
2410 @property
2411 def origin(self: PlaneSource) -> tuple[float, float, float]:
2412 """Get the origin in ``[x, y, z]``.
2413
2414 Returns
2415 -------
2416 sequence[float]
2417 Origin in ``[x, y, z]``.
2418
2419 """
2420 return self.GetOrigin()
2421
2422 @origin.setter
2423 def origin(self: PlaneSource, origin: VectorLike[float]) -> None:
2424 """Set the origin in ``[x, y, z]``.
2425
2426 Parameters
2427 ----------
2428 origin : sequence[float]
2429 Origin in ``[x, y, z]``.
2430
2431 """
2432 self.SetOrigin(*origin)
2433
2434 @property
2435 def point_a(self: PlaneSource) -> tuple[float, float, float]:
2436 """Get the Location in ``[x, y, z]``.
2437
2438 Returns
2439 -------
2440 sequence[float]
2441 Location in ``[x, y, z]``.
2442
2443 """
2444 return self.GetPoint1()
2445
2446 @point_a.setter
2447 def point_a(self: PlaneSource, point_a: VectorLike[float]) -> None:
2448 """Set the Location in ``[x, y, z]``.
2449
2450 Parameters
2451 ----------
2452 point_a : sequence[float]
2453 Location in ``[x, y, z]``.
2454
2455 """
2456 self.SetPoint1(*point_a)
2457
2458 @property
2459 def point_b(self: PlaneSource) -> tuple[float, float, float]:
2460 """Get the Location in ``[x, y, z]``.
2461
2462 Returns
2463 -------
2464 sequence[float]
2465 Location in ``[x, y, z]``.
2466
2467 """
2468 return self.GetPoint2()
2469
2470 @point_b.setter
2471 def point_b(self: PlaneSource, point_b: VectorLike[float]) -> None:
2472 """Set the Location in ``[x, y, z]``.
2473
2474 Parameters
2475 ----------
2476 point_b : sequence[float]
2477 Location in ``[x, y, z]``.
2478
2479 """
2480 self.SetPoint2(point_b) # type: ignore[call-overload]
2481
2482 @property
2483 def output(self: PlaneSource) -> PolyData:
2484 """Get the output data object for a port on this algorithm.
2485
2486 Returns
2487 -------
2488 pyvista.PolyData
2489 Plane mesh.
2490
2491 """
2492 self.Update()
2493 return wrap(self.GetOutput())
2494
2495 @property
2496 def normal(
2497 self: PlaneSource,
2498 ) -> tuple[float, float, float]: # numpydoc ignore: RT01
2499 """Get the plane's normal vector."""
2500 origin = np.array(self.origin)
2501 v1 = self.point_a - origin
2502 v2 = self.point_b - origin
2503 normal = np.cross(v1, v2)
2504 norm = np.linalg.norm(normal)
2505 # Avoid div by zero and return +z normal by default
2506 return tuple((normal / norm).tolist()) if norm else (0.0, 0.0, 1.0)
2507
2508 def flip_normal(self: PlaneSource) -> None:
2509 """Flip the plane's normal.
2510
2511 This method modifies the plane's :attr:`point_a` and :attr:`point_b` by
2512 swapping them.
2513 """
2514 point_a = self.point_a
2515 self.point_a = self.point_b
2516 self.point_b = point_a
2517
2518 def push(self: PlaneSource, distance: float) -> None: # numpydoc ignore: PR01
2519 """Translate the plane in the direction of the normal by the distance specified."""
2520 _validation.validate_number(distance, dtype_out=float)
2521 self.center = (self.center + np.array(self.normal) * distance).tolist()
2522
2523
2524 class ArrowSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkArrowSource):
2525 """Create a arrow source.
2526
2527 .. versionadded:: 0.44
2528
2529 Parameters
2530 ----------
2531 tip_length : float, default: 0.25
2532 Length of the tip.
2533
2534 tip_radius : float, default: 0.1
2535 Radius of the tip.
2536
2537 tip_resolution : int, default: 20
2538 Number of faces around the tip.
2539
2540 shaft_radius : float, default: 0.05
2541 Radius of the shaft.
2542
2543 shaft_resolution : int, default: 20
2544 Number of faces around the shaft.
2545
2546 """
2547
2548 @_deprecate_positional_args
2549 def __init__( # noqa: PLR0917
2550 self: ArrowSource,
2551 tip_length: float = 0.25,
2552 tip_radius: float = 0.1,
2553 tip_resolution: int = 20,
2554 shaft_radius: float = 0.05,
2555 shaft_resolution: int = 20,
2556 ) -> None:
2557 """Initialize source."""
2558 self.tip_length = tip_length
2559 self.tip_radius = tip_radius
2560 self.tip_resolution = tip_resolution
2561 self.shaft_radius = shaft_radius
2562 self.shaft_resolution = shaft_resolution
2563
2564 @property
2565 def tip_length(self: ArrowSource) -> float:
2566 """Get the length of the tip.
2567
2568 Returns
2569 -------
2570 int
2571 The length of the tip.
2572
2573 """
2574 return self.GetTipLength()
2575
2576 @tip_length.setter
2577 def tip_length(self: ArrowSource, tip_length: float) -> None:
2578 """Set the length of the tip.
2579
2580 Parameters
2581 ----------
2582 tip_length : int
2583 The length of the tip.
2584
2585 """
2586 self.SetTipLength(tip_length)
2587
2588 @property
2589 def tip_radius(self: ArrowSource) -> float:
2590 """Get the radius of the tip.
2591
2592 Returns
2593 -------
2594 int
2595 The radius of the tip.
2596
2597 """
2598 return self.GetTipRadius()
2599
2600 @tip_radius.setter
2601 def tip_radius(self: ArrowSource, tip_radius: float) -> None:
2602 """Set the radius of the tip.
2603
2604 Parameters
2605 ----------
2606 tip_radius : int
2607 The radius of the tip.
2608
2609 """
2610 self.SetTipRadius(tip_radius)
2611
2612 @property
2613 def tip_resolution(self: ArrowSource) -> int:
2614 """Get the number of faces around the tip.
2615
2616 Returns
2617 -------
2618 int
2619 The number of faces around the tip.
2620
2621 """
2622 return self.GetTipResolution()
2623
2624 @tip_resolution.setter
2625 def tip_resolution(self: ArrowSource, tip_resolution: int) -> None:
2626 """Set the number of faces around the tip.
2627
2628 Parameters
2629 ----------
2630 tip_resolution : int
2631 The number of faces around the tip.
2632
2633 """
2634 self.SetTipResolution(tip_resolution)
2635
2636 @property
2637 def shaft_resolution(self: ArrowSource) -> int:
2638 """Get the number of faces around the shaft.
2639
2640 Returns
2641 -------
2642 int
2643 The number of faces around the shaft.
2644
2645 """
2646 return self.GetShaftResolution()
2647
2648 @shaft_resolution.setter
2649 def shaft_resolution(self: ArrowSource, shaft_resolution: int) -> None:
2650 """Set the number of faces around the shaft.
2651
2652 Parameters
2653 ----------
2654 shaft_resolution : int
2655 The number of faces around the shaft.
2656
2657 """
2658 self.SetShaftResolution(shaft_resolution)
2659
2660 @property
2661 def shaft_radius(self: ArrowSource) -> float:
2662 """Get the radius of the shaft.
2663
2664 Returns
2665 -------
2666 int
2667 The radius of the shaft.
2668
2669 """
2670 return self.GetShaftRadius()
2671
2672 @shaft_radius.setter
2673 def shaft_radius(self: ArrowSource, shaft_radius: float) -> None:
2674 """Set the radius of the shaft.
2675
2676 Parameters
2677 ----------
2678 shaft_radius : int
2679 The radius of the shaft.
2680
2681 """
2682 self.SetShaftRadius(shaft_radius)
2683
2684 @property
2685 def output(self: ArrowSource) -> PolyData:
2686 """Get the output data object for a port on this algorithm.
2687
2688 Returns
2689 -------
2690 pyvista.PolyData
2691 Plane mesh.
2692
2693 """
2694 self.Update()
2695 return wrap(self.GetOutput())
2696
2697
2698 class BoxSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkTessellatedBoxSource):
2699 """Create a box source.
2700
2701 .. versionadded:: 0.44
2702
2703 Parameters
2704 ----------
2705 bounds : sequence[float], default: (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
2706 Specify the bounds of the box.
2707 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
2708
2709 level : int, default: 0
2710 Level of subdivision of the faces.
2711
2712 quads : bool, default: True
2713 Flag to tell the source to generate either a quad or two
2714 triangle for a set of four points.
2715
2716 """
2717
2718 @_deprecate_positional_args(allowed=['bounds'])
2719 def __init__(
2720 self: BoxSource,
2721 bounds: VectorLike[float] = (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0),
2722 level: int = 0,
2723 quads: bool = True, # noqa: FBT001, FBT002
2724 ) -> None:
2725 """Initialize source."""
2726 super().__init__()
2727 self.bounds = bounds
2728 self.level = level
2729 self.quads = quads
2730
2731 @property
2732 def bounds(self: BoxSource) -> BoundsTuple: # numpydoc ignore=RT01
2733 """Return or set the bounds of the box."""
2734 return BoundsTuple(*self.GetBounds())
2735
2736 @bounds.setter
2737 def bounds(self: BoxSource, bounds: VectorLike[float]) -> None:
2738 if np.array(bounds).size != 6:
2739 msg = (
2740 'Bounds must be given as length 6 tuple: '
2741 '(x_min, x_max, y_min, y_max, z_min, z_max)'
2742 )
2743 raise TypeError(msg)
2744 self.SetBounds(bounds) # type: ignore[arg-type]
2745
2746 @property
2747 def level(self: BoxSource) -> int:
2748 """Get level of subdivision of the faces.
2749
2750 Returns
2751 -------
2752 int
2753 Level of subdivision of the faces.
2754
2755 """
2756 return self.GetLevel()
2757
2758 @level.setter
2759 def level(self: BoxSource, level: int) -> None:
2760 """Set level of subdivision of the faces.
2761
2762 Parameters
2763 ----------
2764 level : int
2765 Level of subdivision of the faces.
2766
2767 """
2768 self.SetLevel(level)
2769
2770 @property
2771 def quads(self: BoxSource) -> bool:
2772 """Flag to tell the source to generate a quad or two triangle for a set of four points.
2773
2774 Returns
2775 -------
2776 bool
2777 Flag to tell the source to generate either a quad or two
2778 triangle for a set of four points.
2779
2780 """
2781 return bool(self.GetQuads())
2782
2783 @quads.setter
2784 def quads(self: BoxSource, quads: bool) -> None:
2785 """Set flag to tell the source to generate a quad or two triangle for a set of four points.
2786
2787 Parameters
2788 ----------
2789 quads : bool, optional
2790 Flag to tell the source to generate either a quad or two
2791 triangle for a set of four points.
2792
2793 """
2794 self.SetQuads(quads)
2795
2796 @property
2797 def output(self: BoxSource) -> PolyData:
2798 """Get the output data object for a port on this algorithm.
2799
2800 Returns
2801 -------
2802 pyvista.PolyData
2803 Plane mesh.
2804
2805 """
2806 self.Update()
2807 return wrap(self.GetOutput())
2808
2809
2810 class SuperquadricSource(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkSuperquadricSource):
2811 """Create superquadric source.
2812
2813 .. versionadded:: 0.44
2814
2815 Parameters
2816 ----------
2817 center : sequence[float], default: (0.0, 0.0, 0.0)
2818 Center of the superquadric in ``[x, y, z]``.
2819
2820 scale : sequence[float], default: (1.0, 1.0, 1.0)
2821 Scale factors of the superquadric in ``[x, y, z]``.
2822
2823 size : float, default: 0.5
2824 Superquadric isotropic size.
2825
2826 theta_roundness : float, default: 1.0
2827 Superquadric east/west roundness.
2828 Values range from 0 (rectangular) to 1 (circular) to higher orders.
2829
2830 phi_roundness : float, default: 1.0
2831 Superquadric north/south roundness.
2832 Values range from 0 (rectangular) to 1 (circular) to higher orders.
2833
2834 theta_resolution : int, default: 16
2835 Number of points in the longitude direction.
2836 Values are rounded to nearest multiple of 4.
2837
2838 phi_resolution : int, default: 16
2839 Number of points in the latitude direction.
2840 Values are rounded to nearest multiple of 8.
2841
2842 toroidal : bool, default: False
2843 Whether or not the superquadric is toroidal (``True``)
2844 or ellipsoidal (``False``).
2845
2846 thickness : float, default: 0.3333333333
2847 Superquadric ring thickness.
2848 Only applies if toroidal is set to ``True``.
2849
2850 """
2851
2852 @_deprecate_positional_args
2853 def __init__( # noqa: PLR0917
2854 self: SuperquadricSource,
2855 center: VectorLike[float] = (0.0, 0.0, 0.0),
2856 scale: VectorLike[float] = (1.0, 1.0, 1.0),
2857 size: float = 0.5,
2858 theta_roundness: float = 1.0,
2859 phi_roundness: float = 1.0,
2860 theta_resolution: int = 16,
2861 phi_resolution: int = 16,
2862 toroidal: bool = False, # noqa: FBT001, FBT002
2863 thickness: float = 1 / 3,
2864 ) -> None:
2865 """Initialize source."""
2866 super().__init__()
2867 self.center = center
2868 self.scale = scale
2869 self.size = size
2870 self.theta_roundness = theta_roundness
2871 self.phi_roundness = phi_roundness
2872 self.theta_resolution = theta_resolution
2873 self.phi_resolution = phi_resolution
2874 self.toroidal = toroidal
2875 self.thickness = thickness
2876
2877 @property
2878 def center(self: SuperquadricSource) -> tuple[float, float, float]:
2879 """Center of the superquadric in ``[x, y, z]``.
2880
2881 Returns
2882 -------
2883 tuple[float, float, float]
2884 Center of the superquadric in ``[x, y, z]``.
2885
2886 """
2887 return self.GetCenter()
2888
2889 @center.setter
2890 def center(self: SuperquadricSource, center: VectorLike[float]) -> None:
2891 """Set center of the superquadric in ``[x, y, z]``.
2892
2893 Parameters
2894 ----------
2895 center : sequence[float]
2896 Center of the superquadric in ``[x, y, z]``.
2897
2898 """
2899 self.SetCenter(*center)
2900
2901 @property
2902 def scale(self: SuperquadricSource) -> tuple[float, float, float]:
2903 """Scale factors of the superquadric in ``[x, y, z]``.
2904
2905 Returns
2906 -------
2907 sequence[float]
2908 Scale factors of the superquadric in ``[x, y, z]``.
2909
2910 """
2911 return self.GetScale()
2912
2913 @scale.setter
2914 def scale(self: SuperquadricSource, scale: VectorLike[float]) -> None:
2915 """Set scale factors of the superquadric in ``[x, y, z]``.
2916
2917 Parameters
2918 ----------
2919 scale : sequence[float]
2920 Scale factors of the superquadric in ``[x, y, z]``.
2921
2922 """
2923 self.SetScale(*scale)
2924
2925 @property
2926 def size(self: SuperquadricSource) -> float:
2927 """Superquadric isotropic size.
2928
2929 Returns
2930 -------
2931 float
2932 Superquadric isotropic size.
2933
2934 """
2935 return self.GetSize()
2936
2937 @size.setter
2938 def size(self: SuperquadricSource, size: float) -> None:
2939 """Set superquadric isotropic size.
2940
2941 Parameters
2942 ----------
2943 size : float
2944 Superquadric isotropic size.
2945
2946 """
2947 self.SetSize(size)
2948
2949 @property
2950 def theta_roundness(self: SuperquadricSource) -> float:
2951 """Superquadric east/west roundness.
2952
2953 Returns
2954 -------
2955 float
2956 Superquadric east/west roundness.
2957
2958 """
2959 return self.GetThetaRoundness()
2960
2961 @theta_roundness.setter
2962 def theta_roundness(self: SuperquadricSource, theta_roundness: float) -> None:
2963 """Set superquadric east/west roundness.
2964
2965 Parameters
2966 ----------
2967 theta_roundness : float
2968 Superquadric east/west roundness.
2969
2970 """
2971 self.SetThetaRoundness(theta_roundness)
2972
2973 @property
2974 def phi_roundness(self: SuperquadricSource) -> float:
2975 """Superquadric north/south roundness.
2976
2977 Returns
2978 -------
2979 float
2980 Superquadric north/south roundness.
2981
2982 """
2983 return self.GetPhiRoundness()
2984
2985 @phi_roundness.setter
2986 def phi_roundness(self: SuperquadricSource, phi_roundness: float) -> None:
2987 """Set superquadric north/south roundness.
2988
2989 Parameters
2990 ----------
2991 phi_roundness : float
2992 Superquadric north/south roundness.
2993
2994 """
2995 self.SetPhiRoundness(phi_roundness)
2996
2997 @property
2998 def theta_resolution(self: SuperquadricSource) -> float:
2999 """Number of points in the longitude direction.
3000
3001 Returns
3002 -------
3003 float
3004 Number of points in the longitude direction.
3005
3006 """
3007 return self.GetThetaResolution()
3008
3009 @theta_resolution.setter
3010 def theta_resolution(self: SuperquadricSource, theta_resolution: float) -> None:
3011 """Set number of points in the longitude direction.
3012
3013 Parameters
3014 ----------
3015 theta_resolution : float
3016 Number of points in the longitude direction.
3017
3018 """
3019 self.SetThetaResolution(round(theta_resolution / 4) * 4)
3020
3021 @property
3022 def phi_resolution(self: SuperquadricSource) -> float:
3023 """Number of points in the latitude direction.
3024
3025 Returns
3026 -------
3027 float
3028 Number of points in the latitude direction.
3029
3030 """
3031 return self.GetPhiResolution()
3032
3033 @phi_resolution.setter
3034 def phi_resolution(self: SuperquadricSource, phi_resolution: float) -> None:
3035 """Set number of points in the latitude direction.
3036
3037 Parameters
3038 ----------
3039 phi_resolution : float
3040 Number of points in the latitude direction.
3041
3042 """
3043 self.SetPhiResolution(round(phi_resolution / 8) * 8)
3044
3045 @property
3046 def toroidal(self: SuperquadricSource) -> bool:
3047 """Whether or not the superquadric is toroidal (``True``) or ellipsoidal (``False``).
3048
3049 Returns
3050 -------
3051 bool
3052 Whether or not the superquadric is toroidal (``True``)
3053 or ellipsoidal (``False``).
3054
3055 """
3056 return self.GetToroidal() # type: ignore[return-value]
3057
3058 @toroidal.setter
3059 def toroidal(self: SuperquadricSource, toroidal: bool) -> None:
3060 """Set whether or not the superquadric is toroidal (``True``) or ellipsoidal (``False``).
3061
3062 Parameters
3063 ----------
3064 toroidal : bool
3065 Whether or not the superquadric is toroidal (``True``)
3066 or ellipsoidal (``False``).
3067
3068 """
3069 self.SetToroidal(toroidal)
3070
3071 @property
3072 def thickness(self: SuperquadricSource) -> float:
3073 """Superquadric ring thickness.
3074
3075 Returns
3076 -------
3077 float
3078 Superquadric ring thickness.
3079
3080 """
3081 return self.GetThickness()
3082
3083 @thickness.setter
3084 def thickness(self: SuperquadricSource, thickness: float) -> None:
3085 """Set superquadric ring thickness.
3086
3087 Parameters
3088 ----------
3089 thickness : float
3090 Superquadric ring thickness.
3091
3092 """
3093 self.SetThickness(thickness)
3094
3095 @property
3096 def output(self: SuperquadricSource) -> PolyData:
3097 """Get the output data object for a port on this algorithm.
3098
3099 Returns
3100 -------
3101 pyvista.PolyData
3102 Plane mesh.
3103
3104 """
3105 self.Update()
3106 return wrap(self.GetOutput())
3107
3108
3109 class _AxisEnum(IntEnum):
3110 x = 0
3111 y = 1
3112 z = 2
3113
3114
3115 class _PartEnum(IntEnum):
3116 shaft = 0
3117 tip = 1
3118
3119
3120 class AxesGeometrySource(_NoNewAttrMixin):
3121 """Create axes geometry source.
3122
3123 Source for generating fully 3-dimensional axes shaft and tip geometry.
3124
3125 By default, the shafts are cylinders and the tips are cones, though other geometries
3126 such as spheres and cubes are also supported. The use of an arbitrary dataset
3127 for the shafts and/or tips is also supported.
3128
3129 Unlike :class:`pyvista.AxesActor`, the output from this source is a
3130 :class:`pyvista.MultiBlock`, not an actor, and does not support colors or labels.
3131 The generated axes are "true-to-scale" by default, i.e. a shaft with a
3132 radius of 0.1 will truly have a radius of 0.1, and the axes may be oriented
3133 arbitrarily in space (this is not the case for :class:`pyvista.AxesActor`).
3134
3135 Parameters
3136 ----------
3137 shaft_type : str | pyvista.DataSet, default: 'cylinder'
3138 Shaft type for all axes. Can be any of the following:
3139
3140 - ``'cylinder'``
3141 - ``'sphere'``
3142 - ``'hemisphere'``
3143 - ``'cone'``
3144 - ``'pyramid'``
3145 - ``'cube'``
3146 - ``'octahedron'``
3147
3148 Alternatively, any arbitrary 3-dimensional :class:`pyvista.DataSet` may be
3149 specified. In this case, the dataset must be oriented such that it "points" in
3150 the positive z direction.
3151
3152 shaft_radius : float | VectorLike[float], default: 0.025
3153 Radius of the axes shafts.
3154
3155 shaft_length : float | VectorLike[float], default: 0.8
3156 Length of the shaft for each axis.
3157
3158 tip_type : str | pyvista.DataSet, default: 'cone'
3159 Tip type for all axes. Can be any of the following:
3160
3161 - ``'cylinder'``
3162 - ``'sphere'``
3163 - ``'hemisphere'``
3164 - ``'cone'``
3165 - ``'pyramid'``
3166 - ``'cube'``
3167 - ``'octahedron'``
3168
3169 Alternatively, any arbitrary 3-dimensional :class:`pyvista.DataSet` may be
3170 specified. In this case, the dataset must be oriented such that it "points" in
3171 the positive z direction.
3172
3173 tip_radius : float | VectorLike[float], default: 0.1
3174 Radius of the axes tips.
3175
3176 tip_length : float | VectorLike[float], default: 0.2
3177 Length of the tip for each axis.
3178
3179 symmetric : bool, default: False
3180 Mirror the axes such that they extend to negative values.
3181
3182 symmetric_bounds : bool, default: False
3183 Make the bounds of the axes symmetric. This option is similar to
3184 :attr:`symmetric`, except only the bounds are made to be symmetric,
3185 not the actual geometry. Has no effect if :attr:`symmetric` is ``True``.
3186
3187 """
3188
3189 GeometryTypes = Literal[
3190 'cylinder',
3191 'sphere',
3192 'hemisphere',
3193 'cone',
3194 'pyramid',
3195 'cube',
3196 'octahedron',
3197 ]
3198 GEOMETRY_TYPES: ClassVar[tuple[str]] = get_args(GeometryTypes)
3199
3200 def __init__(
3201 self: AxesGeometrySource,
3202 *,
3203 shaft_type: GeometryTypes | DataSet = 'cylinder',
3204 shaft_radius: float | VectorLike[float] = 0.025,
3205 shaft_length: float | VectorLike[float] = 0.8,
3206 tip_type: GeometryTypes | DataSet = 'cone',
3207 tip_radius: float | VectorLike[float] = 0.1,
3208 tip_length: float | VectorLike[float] = 0.2,
3209 symmetric: bool = False,
3210 symmetric_bounds: bool = False,
3211 ) -> None:
3212 super().__init__()
3213 # Init datasets
3214 names = ['x_shaft', 'y_shaft', 'z_shaft', 'x_tip', 'y_tip', 'z_tip']
3215 polys = [pv.PolyData() for _ in range(len(names))]
3216 self._output = pv.MultiBlock(dict(zip(names, polys, strict=True)))
3217
3218 # Store shaft/tip references in separate vars for convenience
3219 self._shaft_datasets = (polys[0], polys[1], polys[2])
3220 self._tip_datasets = (polys[3], polys[4], polys[5])
3221
3222 # Also store datasets for internal use
3223 self._shaft_datasets_normalized = [pv.PolyData() for _ in range(3)]
3224 self._tip_datasets_normalized = [pv.PolyData() for _ in range(3)]
3225
3226 # Set geometry-dependent params
3227 self.shaft_type = shaft_type
3228 self.shaft_radius = shaft_radius
3229 self.shaft_length = shaft_length
3230 self.tip_type = tip_type
3231 self.tip_radius = tip_radius
3232 self.tip_length = tip_length
3233
3234 # Set flags
3235 self._symmetric = symmetric
3236 self._symmetric_bounds = symmetric_bounds
3237
3238 # Used by AxesAssembly for scale_mode='anti_distortion'
3239 self._anti_distortion_factor: NumpyArray[float] = np.ones(shape=(3,), dtype=float)
3240
3241 def __repr__(self: AxesGeometrySource) -> str:
3242 """Representation of the axes."""
3243 attr = [
3244 f'{type(self).__name__} ({hex(id(self))})',
3245 f" Shaft type: '{self.shaft_type}'",
3246 f' Shaft radius: {self.shaft_radius}',
3247 f' Shaft length: {self.shaft_length}',
3248 f" Tip type: '{self.tip_type}'",
3249 f' Tip radius: {self.tip_radius}',
3250 f' Tip length: {self.tip_length}',
3251 f' Symmetric: {self.symmetric}',
3252 f' Symmetric bounds: {self.symmetric_bounds}',
3253 ]
3254 return '\n'.join(attr)
3255
3256 @property
3257 def symmetric(self: AxesGeometrySource) -> bool: # numpydoc ignore=RT01
3258 """Mirror the axes such that they extend to negative values.
3259
3260 Examples
3261 --------
3262 >>> import pyvista as pv
3263 >>> axes_geometry_source = pv.AxesGeometrySource(symmetric=True)
3264 >>> axes_geometry_source.output.plot()
3265
3266 """
3267 return self._symmetric
3268
3269 @symmetric.setter
3270 def symmetric(self: AxesGeometrySource, val: bool) -> None:
3271 self._symmetric = val
3272
3273 @property
3274 def symmetric_bounds(self: AxesGeometrySource) -> bool: # numpydoc ignore=RT01
3275 """Enable or disable symmetry in the axes bounds.
3276
3277 This option is similar to :attr:`~pyvista.AxesGeometrySource.symmetric`, except instead
3278 of making the axes parts symmetric, only the bounds of the axes are made to be
3279 symmetric. This is achieved by adding a single invisible cell to each tip
3280 dataset along each axis to simulate the symmetry. Setting this
3281 parameter primarily affects camera positioning and is useful if the
3282 axes are used as a widget, as it allows for the axes to rotate
3283 about its origin.
3284
3285 Examples
3286 --------
3287 Get the symmetric bounds of the axes.
3288
3289 >>> import pyvista as pv
3290 >>> axes_geometry_source = pv.AxesGeometrySource(symmetric_bounds=True)
3291 >>> axes_geometry_source.output.bounds
3292 BoundsTuple(x_min = -1.0,
3293 x_max = 1.0,
3294 y_min = -1.0,
3295 y_max = 1.0,
3296 z_min = -1.0,
3297 z_max = 1.0)
3298
3299 >>> axes_geometry_source.output.center
3300 (0.0, 0.0, 0.0)
3301
3302 Get the asymmetric bounds.
3303
3304 >>> axes_geometry_source.symmetric_bounds = False
3305 >>> axes_geometry_source.output.bounds
3306 BoundsTuple(x_min = -0.1,
3307 x_max = 1.0,
3308 y_min = -0.1,
3309 y_max = 1.0,
3310 z_min = -0.1,
3311 z_max = 1.0)
3312
3313 >>> axes_geometry_source.output.center
3314 (0.45, 0.45, 0.45)
3315
3316 Show the difference in camera positioning with and without
3317 symmetric bounds. Orientation is added for visualization.
3318
3319 Create actors.
3320
3321 >>> axes_sym = pv.AxesAssembly(orientation=(90, 0, 0), symmetric_bounds=True)
3322 >>> axes_asym = pv.AxesAssembly(orientation=(90, 0, 0), symmetric_bounds=False)
3323
3324 Show multi-window plot.
3325
3326 >>> pl = pv.Plotter(shape=(1, 2))
3327 >>> pl.subplot(0, 0)
3328 >>> _ = pl.add_text('Symmetric bounds')
3329 >>> _ = pl.add_actor(axes_sym)
3330 >>> pl.subplot(0, 1)
3331 >>> _ = pl.add_text('Asymmetric bounds')
3332 >>> _ = pl.add_actor(axes_asym)
3333 >>> pl.show()
3334
3335 """
3336 return self._symmetric_bounds
3337
3338 @symmetric_bounds.setter
3339 def symmetric_bounds(self: AxesGeometrySource, val: bool) -> None:
3340 self._symmetric_bounds = val
3341
3342 @property
3343 def shaft_length(
3344 self: AxesGeometrySource,
3345 ) -> tuple[float, float, float]: # numpydoc ignore=RT01
3346 """Length of the shaft for each axis.
3347
3348 Value must be non-negative.
3349
3350 Examples
3351 --------
3352 >>> import pyvista as pv
3353 >>> axes_geometry_source = pv.AxesGeometrySource()
3354 >>> axes_geometry_source.shaft_length
3355 (0.8, 0.8, 0.8)
3356 >>> axes_geometry_source.shaft_length = 0.7
3357 >>> axes_geometry_source.shaft_length
3358 (0.7, 0.7, 0.7)
3359 >>> axes_geometry_source.shaft_length = (1.0, 0.9, 0.5)
3360 >>> axes_geometry_source.shaft_length
3361 (1.0, 0.9, 0.5)
3362
3363 """
3364 return tuple(self._shaft_length.tolist())
3365
3366 @shaft_length.setter
3367 def shaft_length(self: AxesGeometrySource, length: float | VectorLike[float]) -> None:
3368 self._shaft_length: NumpyArray[float] = _validation.validate_array3(
3369 length,
3370 broadcast=True,
3371 must_be_in_range=[0.0, np.inf],
3372 name='Shaft length',
3373 )
3374
3375 @property
3376 def tip_length(
3377 self: AxesGeometrySource,
3378 ) -> tuple[float, float, float]: # numpydoc ignore=RT01
3379 """Length of the tip for each axis.
3380
3381 Value must be non-negative.
3382
3383 Examples
3384 --------
3385 >>> import pyvista as pv
3386 >>> axes_geometry_source = pv.AxesGeometrySource()
3387 >>> axes_geometry_source.tip_length
3388 (0.2, 0.2, 0.2)
3389 >>> axes_geometry_source.tip_length = 0.3
3390 >>> axes_geometry_source.tip_length
3391 (0.3, 0.3, 0.3)
3392 >>> axes_geometry_source.tip_length = (0.1, 0.4, 0.2)
3393 >>> axes_geometry_source.tip_length
3394 (0.1, 0.4, 0.2)
3395
3396 """
3397 return tuple(self._tip_length.tolist())
3398
3399 @tip_length.setter
3400 def tip_length(self: AxesGeometrySource, length: float | VectorLike[float]) -> None:
3401 self._tip_length: NumpyArray[float] = _validation.validate_array3(
3402 length,
3403 broadcast=True,
3404 must_be_in_range=[0.0, np.inf],
3405 name='Tip length',
3406 )
3407
3408 @property
3409 def tip_radius(self: AxesGeometrySource) -> tuple[float, float, float]: # numpydoc ignore=RT01
3410 """Radius of the axes tips.
3411
3412 Value must be non-negative.
3413
3414 Examples
3415 --------
3416 >>> import pyvista as pv
3417 >>> axes_geometry_source = pv.AxesGeometrySource()
3418 >>> axes_geometry_source.tip_radius
3419 (0.1, 0.1, 0.1)
3420 >>> axes_geometry_source.tip_radius = 0.2
3421 >>> axes_geometry_source.tip_radius
3422 (0.2, 0.2, 0.2)
3423
3424 """
3425 return self._tip_radius
3426
3427 @tip_radius.setter
3428 def tip_radius(self: AxesGeometrySource, radius: float | VectorLike[float]) -> None:
3429 self._tip_radius = _validation.validate_array3(
3430 radius,
3431 broadcast=True,
3432 must_be_in_range=(0, float('inf')),
3433 to_tuple=True,
3434 name='tip radius',
3435 )
3436
3437 @property
3438 def shaft_radius(
3439 self: AxesGeometrySource,
3440 ) -> tuple[float, float, float]: # numpydoc ignore=RT01
3441 """Radius of the axes shafts.
3442
3443 Value must be non-negative.
3444
3445 Examples
3446 --------
3447 >>> import pyvista as pv
3448 >>> axes_geometry_source = pv.AxesGeometrySource()
3449 >>> axes_geometry_source.shaft_radius
3450 (0.025, 0.025, 0.025)
3451 >>> axes_geometry_source.shaft_radius = 0.05
3452 >>> axes_geometry_source.shaft_radius
3453 (0.05, 0.05, 0.05)
3454
3455 """
3456 return self._shaft_radius
3457
3458 @shaft_radius.setter
3459 def shaft_radius(self: AxesGeometrySource, radius: float | VectorLike[float]) -> None:
3460 self._shaft_radius = _validation.validate_array3(
3461 radius,
3462 broadcast=True,
3463 must_be_in_range=(0, float('inf')),
3464 to_tuple=True,
3465 name='shaft radius',
3466 )
3467
3468 @property
3469 def shaft_type(self: AxesGeometrySource) -> str: # numpydoc ignore=RT01
3470 """Shaft type for all axes.
3471
3472 Must be a string, e.g. ``'cylinder'`` or ``'cube'`` or any other supported
3473 geometry. Alternatively, any arbitrary 3-dimensional :class:`pyvista.DataSet`
3474 may also be specified. In this case, the dataset must be oriented such that it
3475 "points" in the positive z direction.
3476
3477 Examples
3478 --------
3479 Show a list of all shaft type options.
3480
3481 >>> import pyvista as pv
3482 >>> pv.AxesGeometrySource.GEOMETRY_TYPES
3483 ('cylinder', 'sphere', 'hemisphere', 'cone', 'pyramid', 'cube', 'octahedron')
3484
3485 Show the default shaft type and modify it.
3486
3487 >>> axes_geometry_source = pv.AxesGeometrySource()
3488 >>> axes_geometry_source.shaft_type
3489 'cylinder'
3490 >>> axes_geometry_source.shaft_type = 'cube'
3491 >>> axes_geometry_source.shaft_type
3492 'cube'
3493
3494 Set the shaft type to any 3-dimensional dataset.
3495
3496 >>> axes_geometry_source.shaft_type = pv.Superquadric()
3497 >>> axes_geometry_source.shaft_type
3498 'custom'
3499
3500 """
3501 return self._shaft_type
3502
3503 @shaft_type.setter
3504 def shaft_type(self: AxesGeometrySource, shaft_type: GeometryTypes | DataSet) -> None:
3505 self._shaft_type = self._set_normalized_datasets(part=_PartEnum.shaft, geometry=shaft_type)
3506
3507 @property
3508 def tip_type(self: AxesGeometrySource) -> str: # numpydoc ignore=RT01
3509 """Tip type for all axes.
3510
3511 Must be a string, e.g. ``'cone'`` or ``'sphere'`` or any other supported
3512 geometry. Alternatively, any arbitrary 3-dimensional :class:`pyvista.DataSet`
3513 may also be specified. In this case, the dataset must be oriented such that it
3514 "points" in the positive z direction.
3515
3516 Examples
3517 --------
3518 Show a list of all shaft type options.
3519
3520 >>> import pyvista as pv
3521 >>> pv.AxesGeometrySource.GEOMETRY_TYPES
3522 ('cylinder', 'sphere', 'hemisphere', 'cone', 'pyramid', 'cube', 'octahedron')
3523
3524 Show the default tip type and modify it.
3525
3526 >>> axes_geometry_source = pv.AxesGeometrySource()
3527 >>> axes_geometry_source.tip_type
3528 'cone'
3529 >>> axes_geometry_source.tip_type = 'sphere'
3530 >>> axes_geometry_source.tip_type
3531 'sphere'
3532
3533 Set the tip type to any 3-dimensional dataset.
3534
3535 >>> axes_geometry_source.tip_type = pv.Text3D('O')
3536 >>> axes_geometry_source.tip_type
3537 'custom'
3538
3539 >>> axes_geometry_source.output.plot(cpos='xy')
3540
3541 """
3542 return self._tip_type
3543
3544 @tip_type.setter
3545 def tip_type(self: AxesGeometrySource, tip_type: GeometryTypes | DataSet) -> None:
3546 self._tip_type = self._set_normalized_datasets(part=_PartEnum.tip, geometry=tip_type)
3547
3548 def _set_normalized_datasets(
3549 self: AxesGeometrySource, part: _PartEnum, geometry: str | DataSet
3550 ) -> str:
3551 geometry_name, new_datasets = AxesGeometrySource._make_axes_parts(geometry)
3552 datasets = (
3553 self._shaft_datasets_normalized
3554 if part == _PartEnum.shaft
3555 else self._tip_datasets_normalized
3556 )
3557 datasets[_AxisEnum.x].copy_from(new_datasets[_AxisEnum.x])
3558 datasets[_AxisEnum.y].copy_from(new_datasets[_AxisEnum.y])
3559 datasets[_AxisEnum.z].copy_from(new_datasets[_AxisEnum.z])
3560 return geometry_name
3561
3562 def _reset_shaft_and_tip_geometry(self: AxesGeometrySource) -> None:
3563 # Store local copies of properties for iterating
3564 shaft_radius, shaft_length = list(self.shaft_radius), list(self.shaft_length)
3565 tip_radius, tip_length = list(self.tip_radius), list(self.tip_length)
3566
3567 nested_datasets = [self._shaft_datasets, self._tip_datasets]
3568 nested_datasets_normalized = [
3569 self._shaft_datasets_normalized,
3570 self._tip_datasets_normalized,
3571 ]
3572 for part_type, axis in itertools.product(_PartEnum, _AxisEnum):
3573 # Reset part by copying from the normalized version
3574 part_normalized = nested_datasets_normalized[part_type][axis]
3575 part = nested_datasets[part_type][axis]
3576 part.copy_from(part_normalized)
3577
3578 # Offset so axis bounds are [0, 1]
3579 part.points[:, axis] += 0.5
3580
3581 # Scale by length along axis, scale by radius off-axis
3582 diameter = (shaft_radius if part_type == _PartEnum.shaft else tip_radius)[axis] * 2
3583 factor = self._anti_distortion_factor
3584 scale = np.array((diameter, diameter, diameter)) * factor
3585
3586 if part_type == _PartEnum.shaft:
3587 shaft_length[axis] += tip_length[axis] * (1 - factor[axis])
3588 scale[axis] = shaft_length[axis]
3589 else:
3590 scale[axis] = tip_length[axis] * factor[axis]
3591
3592 part.scale(scale, inplace=True)
3593
3594 if part_type == _PartEnum.tip:
3595 # Move tip to end of shaft
3596 part.points[:, axis] += shaft_length[axis]
3597
3598 if self.symmetric:
3599 # Flip and append to part
3600 origin = [0, 0, 0]
3601 normal = [0, 0, 0]
3602 normal[axis] = 1
3603 flipped = part.flip_normal(normal=normal, point=origin)
3604 part.append_polydata(flipped, inplace=True)
3605 elif self.symmetric_bounds and part_type == _PartEnum.tip:
3606 # For this feature we add a single degenerate cell
3607 # at the tip and flip its position
3608 point = [0, 0, 0]
3609 total_length = shaft_length[axis] + tip_length[axis]
3610 point[axis] = total_length # type: ignore[call-overload]
3611 flipped_point = np.array([point]) * -1 # Flip point
3612 point_id = part.n_points
3613 new_face = [3, point_id, point_id, point_id]
3614
3615 # Update mesh
3616 part.points = np.append(part.points, flipped_point, axis=0)
3617 part.faces = np.append(part.faces, new_face)
3618
3619 def update(self: AxesGeometrySource) -> None:
3620 """Update the output of the source."""
3621 self._reset_shaft_and_tip_geometry()
3622
3623 @property
3624 def output(self: AxesGeometrySource) -> MultiBlock:
3625 """Get the output of the source.
3626
3627 The output is a :class:`pyvista.MultiBlock` with six blocks: one for each part
3628 of the axes. The blocks are ordered by shafts first then tips, and in x-y-z order.
3629 Specifically, they are named as follows:
3630
3631 (``'x_shaft'``, ``'y_shaft'``, ``'z_shaft'``, ``'x_tip'``, ``'y_tip'``, ``'z_tip'``)
3632
3633 The source is automatically updated by :meth:`update` prior to returning
3634 the output.
3635
3636 Returns
3637 -------
3638 pyvista.MultiBlock
3639 Composite mesh with separate shaft and tip datasets.
3640
3641 """
3642 self.update()
3643 return self._output
3644
3645 @staticmethod
3646 def _make_default_part(geometry: str) -> PolyData:
3647 """Create part geometry with its length axis pointing in the +z direction."""
3648 resolution = 50
3649 if geometry == 'cylinder':
3650 out = pv.Cylinder(direction=(0, 0, 1), resolution=resolution)
3651 elif geometry == 'sphere':
3652 out = pv.Sphere(phi_resolution=resolution, theta_resolution=resolution)
3653 elif geometry == 'hemisphere':
3654 out = pv.SolidSphere(end_phi=90).extract_surface(
3655 algorithm=None, pass_pointid=False, pass_cellid=False
3656 )
3657 elif geometry == 'cone':
3658 out = pv.Cone(direction=(0, 0, 1), resolution=resolution)
3659 elif geometry == 'pyramid':
3660 out = pv.Pyramid().extract_surface(
3661 algorithm=None, pass_pointid=False, pass_cellid=False
3662 )
3663 elif geometry == 'cube':
3664 out = pv.Cube()
3665 elif geometry == 'octahedron':
3666 mesh = pv.Octahedron()
3667 mesh.cell_data.remove('FaceIndex')
3668 out = mesh
3669 else:
3670 _validation.check_contains(
3671 AxesGeometrySource.GEOMETRY_TYPES,
3672 must_contain=geometry,
3673 name='Geometry',
3674 )
3675 msg = f"Geometry '{geometry}' is not implemented" # pragma: no cover
3676 raise NotImplementedError(msg) # pragma: no cover
3677 return out
3678
3679 @staticmethod
3680 def _make_any_part(geometry: str | DataSet) -> tuple[str, PolyData]:
3681 part: DataSet
3682 part_poly: PolyData
3683 if isinstance(geometry, str):
3684 name = geometry
3685 part = AxesGeometrySource._make_default_part(
3686 geometry,
3687 )
3688 elif isinstance(geometry, pv.DataSet):
3689 name = 'custom'
3690 part = geometry.copy()
3691 else:
3692 msg = f'Geometry must be a string or pyvista.DataSet. Got {type(geometry)}.' # type: ignore[unreachable]
3693 raise TypeError(msg)
3694 part_poly = (
3695 part
3696 if isinstance(part, pv.PolyData)
3697 else part.extract_surface(algorithm=None, pass_pointid=False, pass_cellid=False)
3698 )
3699 part_poly = AxesGeometrySource._normalize_part(part_poly)
3700 return name, part_poly
3701
3702 @staticmethod
3703 def _normalize_part(part: PolyData) -> PolyData:
3704 """Scale and translate part to have origin-centered bounding box with edge length one."""
3705 # Center points at origin
3706 # mypy ignore since pyvista_ndarray is not compatible with np.ndarray, see GH#5434
3707 part.points -= part.center
3708
3709 # Scale so bounding box edges have length one
3710 size = np.array(part.bounds_size)
3711 if np.any(size < 1e-8):
3712 msg = f'Custom axes part must be 3D. Got bounds:\n{part.bounds}.'
3713 raise ValueError(msg)
3714 part.scale(np.reciprocal(size), inplace=True)
3715 return part
3716
3717 @staticmethod
3718 def _make_axes_parts(
3719 geometry: str | DataSet,
3720 ) -> tuple[str, tuple[PolyData, PolyData, PolyData]]:
3721 """Return three axis-aligned normalized parts centered at the origin."""
3722 name, part_z = AxesGeometrySource._make_any_part(geometry)
3723 part_x = part_z.copy().rotate_y(90)
3724 part_y = part_z.copy().rotate_x(-90)
3725 return name, (part_x, part_y, part_z)
3726
3727
3728 class OrthogonalPlanesSource(_NoNewAttrMixin):
3729 """Orthogonal planes source.
3730
3731 This source generates three orthogonal planes. The :attr:`output` is a
3732 :class:`~pyvista.MultiBlock` with named plane meshes ``'yz'``, ``'zx'``, ``'xy'``.
3733 The meshes are ordered such that the first, second, and third plane is perpendicular
3734 to the x, y, and z-axis, respectively.
3735
3736 .. versionadded:: 0.45
3737
3738 Parameters
3739 ----------
3740 bounds : VectorLike[float], default: (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
3741 Specify the bounds of the planes in the form:
3742 ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
3743 The generated planes are centered in these bounds.
3744
3745 resolution : int | VectorLike[int], default: 2
3746 Number of points on the planes in the x-y-z directions. Use a single number
3747 for a uniform resolution, or three values to set independent resolutions.
3748
3749 normal_sign : '+' | '-' | sequence['+' | '-'], default: '+'
3750 Sign of the plane's normal vectors. Use a single value to set all normals to
3751 the same sign, or three values to set them independently.
3752
3753 names : sequence[str], default: ('xy','yz','zx')
3754 Name of each plane in the generated :class:`~pyvista.MultiBlock`.
3755
3756 Examples
3757 --------
3758 Generate default orthogonal planes.
3759
3760 >>> import pyvista as pv
3761 >>> from pyvista import examples
3762 >>> planes_source = pv.OrthogonalPlanesSource()
3763 >>> output = planes_source.output
3764 >>> output.plot()
3765
3766 Modify the planes to fit a mesh's bounds.
3767
3768 >>> human = examples.download_human()
3769 >>> planes_source.bounds = human.bounds
3770 >>> planes_source.update()
3771
3772 Plot the mesh and the planes.
3773
3774 >>> pl = pv.Plotter()
3775 >>> _ = pl.add_mesh(human, scalars='Color', rgb=True)
3776 >>> _ = pl.add_mesh(output, opacity=0.3, show_edges=True)
3777 >>> pl.show()
3778
3779 The planes are centered geometrically, but the frontal plane is positioned a bit
3780 too far forward. Use :meth:`push` to move the frontal plane.
3781
3782 >>> planes_source.push(0.0, -10.0, 0)
3783 >>> planes_source.update()
3784
3785 >>> pl = pv.Plotter()
3786 >>> _ = pl.add_mesh(human, scalars='Color', rgb=True)
3787 >>> _ = pl.add_mesh(output, opacity=0.3, show_edges=True, line_width=10)
3788 >>> pl.view_yz()
3789 >>> pl.show()
3790
3791 """
3792
3793 def __init__(
3794 self: OrthogonalPlanesSource,
3795 bounds: VectorLike[float] = (-1.0, 1.0, -1.0, 1.0, -1.0, 1.0),
3796 *,
3797 resolution: int | VectorLike[int] = 2,
3798 normal_sign: Literal['+', '-'] | Sequence[str] = '+',
3799 names: Sequence[str] = ('yz', 'zx', 'xy'),
3800 ) -> None:
3801 # Init sources and the output dataset
3802 self._output = pv.MultiBlock([pv.PolyData() for _ in range(3)])
3803 self.sources = tuple(pv.PlaneSource() for _ in range(3))
3804
3805 # Init properties
3806 self.bounds = bounds
3807 self.resolution = resolution
3808 self.normal_sign = normal_sign
3809 self.names = names
3810
3811 @property
3812 def normal_sign(
3813 self: OrthogonalPlanesSource,
3814 ) -> tuple[str, str, str]: # numpydoc ignore=RT01
3815 """Return or set the sign of the plane's normal vectors."""
3816 return cast('tuple[str, str, str]', self._normal_sign)
3817
3818 @normal_sign.setter
3819 def normal_sign(
3820 self: OrthogonalPlanesSource, sign: Literal['+', '-'] | Sequence[str] = '+'
3821 ) -> None:
3822 def _check_sign(sign_: str) -> None:
3823 allowed = ['+', '-']
3824 _validation.check_contains(allowed, must_contain=sign_, name='normal sign')
3825
3826 valid_sign: Sequence[str]
3827 _validation.check_instance(sign, (tuple, list, str), name='normal sign')
3828 if isinstance(sign, str):
3829 _check_sign(sign)
3830 valid_sign = [sign] * 3
3831 else:
3832 _validation.check_length(sign, exact_length=3)
3833 [_check_sign(s) for s in sign] # type: ignore[func-returns-value]
3834 valid_sign = sign
3835 self._normal_sign = tuple(valid_sign)
3836
3837 # Modify sources
3838 for source, axis_vector, sign_ in zip(self.sources, np.eye(3), valid_sign, strict=True):
3839 has_positive_normal = np.dot(source.normal, axis_vector) > 0
3840 if has_positive_normal and sign_ == '-':
3841 source.flip_normal()
3842
3843 @property
3844 def resolution(
3845 self: OrthogonalPlanesSource,
3846 ) -> tuple[int, int, int]: # numpydoc ignore=RT01
3847 """Return or set the resolution of the planes."""
3848 return cast('tuple[int, int, int]', tuple(self._resolution))
3849
3850 @resolution.setter
3851 def resolution(self: OrthogonalPlanesSource, resolution: int | VectorLike[int]) -> None:
3852 valid_resolution = _validation.validate_array3(
3853 resolution, broadcast=True, to_tuple=True, name='resolution'
3854 )
3855 self._resolution = valid_resolution
3856
3857 # Modify sources
3858 x_res, y_res, z_res = valid_resolution
3859 yz_source, zx_source, xy_source = self.sources
3860
3861 yz_source.i_resolution = y_res
3862 yz_source.j_resolution = z_res
3863 zx_source.i_resolution = z_res
3864 zx_source.j_resolution = x_res
3865 xy_source.i_resolution = x_res
3866 xy_source.j_resolution = y_res
3867
3868 @property
3869 def bounds(self: OrthogonalPlanesSource) -> BoundsTuple: # numpydoc ignore=RT01
3870 """Return or set the bounds of the planes."""
3871 return self._bounds
3872
3873 @bounds.setter
3874 def bounds(self: OrthogonalPlanesSource, bounds: VectorLike[float]) -> None:
3875 bounds_tuple = _validation.validate_array(
3876 bounds, dtype_out=float, must_have_length=6, to_tuple=True, name='bounds'
3877 )
3878 self._bounds = BoundsTuple(*bounds_tuple)
3879
3880 # Modify sources
3881 x_min, x_max, y_min, y_max, z_min, z_max = bounds_tuple
3882 x_size, y_size, z_size = x_max - x_min, y_max - y_min, z_max - z_min
3883 center = (x_max + x_min) / 2, (y_max + y_min) / 2, (z_max + z_min) / 2
3884 ORIGIN = (0.0, 0.0, 0.0)
3885 yz_source, zx_source, xy_source = self.sources
3886
3887 xy_source.point_a = x_size, 0.0, 0.0
3888 xy_source.point_b = 0.0, y_size, 0.0
3889 xy_source.origin = ORIGIN
3890 xy_source.center = center
3891
3892 yz_source.point_a = 0.0, y_size, 0.0
3893 yz_source.point_b = 0.0, 0.0, z_size
3894 yz_source.origin = ORIGIN
3895 yz_source.center = center
3896
3897 zx_source.point_a = 0.0, 0.0, z_size
3898 zx_source.point_b = x_size, 0.0, 0.0
3899 zx_source.origin = ORIGIN
3900 zx_source.center = center
3901
3902 @property
3903 def names(
3904 self: OrthogonalPlanesSource,
3905 ) -> tuple[str, str, str]: # numpydoc ignore=RT01
3906 """Return or set the names of the planes."""
3907 return self._names
3908
3909 @names.setter
3910 def names(self: OrthogonalPlanesSource, names: Sequence[str]) -> None:
3911 _validation.check_instance(names, (tuple, list), name='names')
3912 _validation.check_iterable_items(names, str, name='names')
3913 _validation.check_length(names, exact_length=3, name='names')
3914 valid_names = cast('tuple[str, str, str]', tuple(names))
3915 self._names = valid_names
3916
3917 output = self._output
3918 for i, name in enumerate(valid_names):
3919 output.set_block_name(i, name)
3920
3921 def push(
3922 self: OrthogonalPlanesSource, *distance: float | VectorLike[float]
3923 ) -> None: # numpydoc ignore=RT01
3924 """Translate each plane by the specified distance along its normal.
3925
3926 Internally, this method calls :meth:`pyvista.PlaneSource.push` on each
3927 plane source.
3928
3929 Parameters
3930 ----------
3931 *distance : float | VectorLike[float], default: (0.0, 0.0, 0.0)
3932 Distance to move each plane.
3933
3934 """
3935 valid_distance = _validation.validate_array3(
3936 distance, # type: ignore[arg-type]
3937 broadcast=True,
3938 dtype_out=float,
3939 to_tuple=True,
3940 )
3941 for source, dist in zip(self.sources, valid_distance, strict=True):
3942 source.push(dist)
3943
3944 def update(self: OrthogonalPlanesSource) -> None:
3945 """Update the output of the source."""
3946 for source, plane in zip(self.sources, self._output, strict=True):
3947 plane.copy_from(source.output)
3948
3949 @property
3950 def output(self: OrthogonalPlanesSource) -> MultiBlock:
3951 """Get the output of the source.
3952
3953 The output is a :class:`pyvista.MultiBlock` with three blocks: one for each
3954 plane. The blocks are named ``'yz'``, ``'zx'``, ``'xy'``, and are ordered such
3955 that the first, second, and third plane is perpendicular to the x, y, and
3956 z-axis, respectively.
3957
3958 The source is automatically updated by :meth:`update` prior to returning
3959 the output.
3960
3961 Returns
3962 -------
3963 pyvista.MultiBlock
3964 Composite mesh with three planes.
3965
3966 """
3967 self.update()
3968 return self._output
3969
3970
3971 class CubeFacesSource(CubeSource):
3972 """Generate the faces of a cube.
3973
3974 This source generates a :class:`~pyvista.MultiBlock` with the six :class:`PolyData`
3975 comprising the faces of a cube.
3976
3977 The faces may be shrunk or exploded to create equal-sized gaps or intersections
3978 between the faces. Additionally, the faces may be converted to frames with a
3979 constant-width border.
3980
3981 .. versionadded:: 0.45.0
3982
3983 Parameters
3984 ----------
3985 center : VectorLike[float], default: (0.0, 0.0, 0.0)
3986 Center in ``[x, y, z]``.
3987
3988 x_length : float, default: 1.0
3989 Length of the cube in the x-direction.
3990
3991 y_length : float, default: 1.0
3992 Length of the cube in the y-direction.
3993
3994 z_length : float, default: 1.0
3995 Length of the cube in the z-direction.
3996
3997 bounds : sequence[float], optional
3998 Specify the bounding box of the cube. If given, all other size
3999 arguments are ignored. ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
4000
4001 frame_width : float, optional
4002 Convert the faces into frames with the specified width. If set, the center
4003 portion of each face is removed and the output faces will each have four quad
4004 cells (one for each side of the frame) instead of a single quad cell. Values
4005 must be between ``0.0`` (minimal frame) and ``1.0`` (large frame). The frame is
4006 scaled to ensure it has a constant width.
4007
4008 shrink_factor : float, optional
4009 Shrink or grow the cube's faces. If set, this is the factor by which to shrink
4010 or grow each face. The amount of shrinking or growth is relative to the smallest
4011 edge length of the cube, and all sides of the faces are shrunk by the same
4012 (constant) value.
4013
4014 .. note::
4015 - A value of ``1.0`` has no effect.
4016 - Values between ``0.0`` and ``1.0`` will shrink the faces.
4017 - Values greater than ``1.0`` will grow the faces.
4018
4019 This has a similar effect to using :meth:`~pyvista.DataSetFilters.shrink`.
4020
4021 explode_factor : float, optional
4022 Push the faces away from (or pull them toward) the cube's center. If set, this
4023 is the factor by which to move each face. The magnitude of the move is relative
4024 to the smallest edge length of the cube, and all faces are moved by the same
4025 (constant) amount.
4026
4027 .. note::
4028 - A value of ``0.0`` has no effect.
4029 - Increasing positive values will push the faces farther away (explode).
4030 - Decreasing negative values will pull the faces closer together (implode).
4031
4032 This has a similar effect to using :meth:`~pyvista.DataSetFilters.explode`.
4033
4034 names : sequence[str], default: ('+X','-X','+Y','-Y','+Z','-Z')
4035 Name of each face in the generated :class:`~pyvista.MultiBlock`.
4036
4037 point_dtype : str, default: 'float32'
4038 Set the desired output point types. It must be either 'float32' or 'float64'.
4039
4040 Examples
4041 --------
4042 Generate the default faces of a cube.
4043
4044 >>> import pyvista as pv
4045 >>> from pyvista import examples
4046 >>> cube_faces_source = pv.CubeFacesSource()
4047 >>> output = cube_faces_source.output
4048 >>> output.plot(show_edges=True, line_width=10)
4049
4050 The output is similar to that of :class:`CubeSource` except it's a
4051 :class:`~pyvista.MultiBlock`.
4052
4053 >>> output
4054 MultiBlock (...)
4055 N Blocks: 6
4056 X Bounds: -5.000e-01, 5.000e-01
4057 Y Bounds: -5.000e-01, 5.000e-01
4058 Z Bounds: -5.000e-01, 5.000e-01
4059
4060 >>> cube_source = pv.CubeSource()
4061 >>> cube_source.output
4062 PolyData (...)
4063 N Cells: 6
4064 N Points: 24
4065 N Strips: 0
4066 X Bounds: -5.000e-01, 5.000e-01
4067 Y Bounds: -5.000e-01, 5.000e-01
4068 Z Bounds: -5.000e-01, 5.000e-01
4069 N Arrays: 2
4070
4071 Use :attr:`explode_factor` to explode the faces.
4072
4073 >>> cube_faces_source.explode_factor = 0.5
4074 >>> cube_faces_source.update()
4075 >>> output.plot(show_edges=True, line_width=10)
4076
4077 Use :attr:`shrink_factor` to also shrink the faces.
4078
4079 >>> cube_faces_source.shrink_factor = 0.5
4080 >>> cube_faces_source.update()
4081 >>> output.plot(show_edges=True, line_width=10)
4082
4083 Fit cube faces to a dataset and only plot four of them.
4084
4085 >>> mesh = examples.load_airplane()
4086 >>> cube_faces_source = pv.CubeFacesSource(bounds=mesh.bounds)
4087 >>> output = cube_faces_source.output
4088
4089 >>> pl = pv.Plotter()
4090 >>> _ = pl.add_mesh(mesh, color='tomato')
4091 >>> _ = pl.add_mesh(output['+X'], opacity=0.5)
4092 >>> _ = pl.add_mesh(output['-X'], opacity=0.5)
4093 >>> _ = pl.add_mesh(output['+Y'], opacity=0.5)
4094 >>> _ = pl.add_mesh(output['-Y'], opacity=0.5)
4095 >>> pl.show()
4096
4097 Generate a frame instead of full faces.
4098
4099 >>> mesh = pv.ParametricEllipsoid(5, 4, 3)
4100 >>> cube_faces_source = pv.CubeFacesSource(bounds=mesh.bounds, frame_width=0.1)
4101 >>> output = cube_faces_source.output
4102
4103 >>> pl = pv.Plotter()
4104 >>> _ = pl.add_mesh(mesh, color='tomato')
4105 >>> _ = pl.add_mesh(output, show_edges=True, line_width=10)
4106 >>> pl.show()
4107
4108 """
4109
4110 class _FaceIndex(IntEnum):
4111 X_NEG = 0
4112 X_POS = 1
4113 Y_NEG = 2
4114 Y_POS = 3
4115 Z_NEG = 4
4116 Z_POS = 5
4117
4118 def __init__(
4119 self: CubeFacesSource,
4120 *,
4121 center: VectorLike[float] = (0.0, 0.0, 0.0),
4122 x_length: float = 1.0,
4123 y_length: float = 1.0,
4124 z_length: float = 1.0,
4125 bounds: VectorLike[float] | None = None,
4126 frame_width: float | None = None,
4127 shrink_factor: float | None = None,
4128 explode_factor: float | None = None,
4129 names: Sequence[str] = ('+X', '-X', '+Y', '-Y', '+Z', '-Z'),
4130 point_dtype: str = 'float32',
4131 ) -> None:
4132 # Init CubeSource
4133 super().__init__(
4134 center=center,
4135 x_length=x_length,
4136 y_length=y_length,
4137 z_length=z_length,
4138 bounds=bounds,
4139 point_dtype=point_dtype,
4140 )
4141 # Init output
4142 self._output = pv.MultiBlock([pv.PolyData() for _ in range(6)])
4143
4144 # Set properties
4145 self.frame_width = frame_width
4146 self.shrink_factor = shrink_factor
4147 self.explode_factor = explode_factor
4148 self.names = names # type: ignore[assignment]
4149
4150 @property
4151 def frame_width(self: CubeFacesSource) -> float | None: # numpydoc ignore=RT01
4152 """Convert the faces into frames with the specified border width.
4153
4154 If set, the center portion of each face is removed and the :attr:`output`
4155 :class:`pyvista.PolyData` will each have four quad cells (one for each
4156 side of the frame) instead of a single quad cell. Values must be between ``0.0``
4157 (minimal frame) and ``1.0`` (large frame). The frame is scaled to ensure it has
4158 a constant width.
4159
4160 Examples
4161 --------
4162 >>> import pyvista as pv
4163 >>> cube_faces_source = pv.CubeFacesSource(
4164 ... x_length=3, y_length=2, z_length=1, frame_width=0.2
4165 ... )
4166 >>> cube_faces_source.output.plot(show_edges=True, line_width=10)
4167
4168 >>> cube_faces_source.frame_width = 0.8
4169 >>> cube_faces_source.output.plot(show_edges=True, line_width=10)
4170
4171 """
4172 return self._frame_width
4173
4174 @frame_width.setter
4175 def frame_width(self: CubeFacesSource, width: float | None) -> None:
4176 self._frame_width = (
4177 width
4178 if width is None
4179 else _validation.validate_number(
4180 width, must_be_in_range=[0.0, 1.0], name='frame width'
4181 )
4182 )
4183
4184 @property
4185 def shrink_factor(self: CubeFacesSource) -> float | None: # numpydoc ignore=RT01
4186 """Shrink or grow the cube's faces.
4187
4188 If set, this is the factor by which to shrink or grow each face. The amount of
4189 shrinking or growth is relative to the smallest edge length of the cube, and
4190 all sides of the faces are shrunk by the same (constant) value.
4191
4192 .. note::
4193 - A value of ``1.0`` has no effect.
4194 - Values between ``0.0`` and ``1.0`` will shrink the faces.
4195 - Values greater than ``1.0`` will grow the faces.
4196
4197 This has a similar effect to using :meth:`~pyvista.DataSetFilters.shrink`.
4198
4199 Examples
4200 --------
4201 >>> import pyvista as pv
4202 >>> cube_faces_source = pv.CubeFacesSource(
4203 ... x_length=3, y_length=2, z_length=1, shrink_factor=0.8
4204 ... )
4205 >>> output = cube_faces_source.output
4206 >>> output.plot(show_edges=True, line_width=10)
4207
4208 Note how all edges are shrunk by the same (constant) amount in terms of absolute
4209 distance. Compare this to :meth:`~pyvista.DataSetFilters.shrink` where the
4210 amount of shrinkage is relative to the size of the faces.
4211
4212 >>> exploded = pv.merge(output).shrink(0.8)
4213 >>> exploded.plot(show_edges=True, line_width=10)
4214
4215 """
4216 return self._shrink_factor
4217
4218 @shrink_factor.setter
4219 def shrink_factor(self: CubeFacesSource, factor: float | None) -> None:
4220 self._shrink_factor = (
4221 factor
4222 if factor is None
4223 else _validation.validate_number(
4224 factor, must_be_in_range=[0.0, np.inf], name='shrink factor'
4225 )
4226 )
4227
4228 @property
4229 def explode_factor(self: CubeFacesSource) -> float | None: # numpydoc ignore=RT01
4230 """Push the faces away from (or pull them toward) the cube's center.
4231
4232 If set, this is the factor by which to move each face. The magnitude of the
4233 move is relative to the smallest edge length of the cube, and all faces are
4234 moved by the same (constant) amount.
4235
4236 .. note::
4237 - A value of ``0.0`` has no effect.
4238 - Increasing positive values will push the faces farther away (explode).
4239 - Decreasing negative values will pull the faces closer together (implode).
4240
4241 This has a similar effect to using :meth:`~pyvista.DataSetFilters.explode`.
4242
4243 Examples
4244 --------
4245 >>> import pyvista as pv
4246 >>> cube_faces_source = pv.CubeFacesSource(
4247 ... x_length=3, y_length=2, z_length=1, explode_factor=0.2
4248 ... )
4249 >>> output = cube_faces_source.output
4250 >>> output.plot(show_edges=True, line_width=10)
4251
4252 Note how all faces are moved by the same amount. Compare this to using
4253 :meth:`~pyvista.DataSetFilters.explode` where the distance each face moves
4254 is relative to distance of each face to the center of the cube.
4255
4256 >>> exploded = pv.merge(output).explode(0.2)
4257 >>> exploded.plot(show_edges=True, line_width=10)
4258
4259 """
4260 return self._explode_factor
4261
4262 @explode_factor.setter
4263 def explode_factor(self: CubeFacesSource, factor: float | None) -> None:
4264 self._explode_factor = (
4265 factor
4266 if factor is None
4267 else _validation.validate_number(factor, name='explode factor')
4268 )
4269
4270 @property
4271 def names(
4272 self: CubeFacesSource,
4273 ) -> tuple[str, str, str, str, str, str]: # numpydoc ignore=RT01
4274 """Return or set the names of the faces.
4275
4276 Specify three strings, one for each '+/-' face pair, or six strings, one for
4277 each individual face.
4278
4279 If three strings, plus ``'+'`` and minus ``'-'`` characters are added to
4280 the names.
4281
4282 Examples
4283 --------
4284 >>> import pyvista as pv
4285 >>> cube_faces = pv.CubeFacesSource()
4286
4287 Use three strings to set the names. Plus ``'+'`` and minus ``'-'``
4288 characters are added automatically.
4289
4290 >>> cube_faces.names = ['U', 'V', 'W']
4291 >>> cube_faces.names
4292 ('+U', '-U', '+V', '-V', '+W', '-W')
4293
4294 Alternatively, use six strings to set the names explicitly.
4295
4296 >>> cube_faces.names = [
4297 ... 'right',
4298 ... 'left',
4299 ... 'anterior',
4300 ... 'posterior',
4301 ... 'superior',
4302 ... 'inferior',
4303 ... ]
4304 >>> cube_faces.names
4305 ('right', 'left', 'anterior', 'posterior', 'superior', 'inferior')
4306
4307 """
4308 return self._names
4309
4310 @names.setter
4311 def names(
4312 self: CubeFacesSource,
4313 names: list[str] | tuple[str, str, str] | tuple[str, str, str, str, str, str],
4314 ) -> None:
4315 name = 'face names'
4316 _validation.check_instance(names, (list, tuple), name=name)
4317 _validation.check_iterable_items(names, str, name=name)
4318 _validation.check_length(names, exact_length=[3, 6], name=name)
4319 valid_names = (
4320 tuple(names)
4321 if len(names) == 6
4322 else (
4323 '+' + names[0],
4324 '-' + names[0],
4325 '+' + names[1],
4326 '-' + names[1],
4327 '+' + names[2],
4328 '-' + names[2],
4329 )
4330 )
4331 self._names = cast('tuple[str, str, str, str, str, str]', valid_names)
4332
4333 def update(self: CubeFacesSource) -> None:
4334 """Update the output of the source."""
4335
4336 def _scale_points(
4337 points_: NumpyArray[float],
4338 origin_: NumpyArray[float],
4339 scale_: NumpyArray[float],
4340 ) -> NumpyArray[float]:
4341 points_ -= origin_
4342 points_ *= scale_
4343 points_ += origin_
4344 return points_
4345
4346 def _create_frame_from_quad_points(
4347 quad_points: NumpyArray[float],
4348 center: NumpyArray[float],
4349 scale: NumpyArray[float],
4350 ) -> tuple[NumpyArray[float], NumpyArray[float]]:
4351 """Create a picture-frame from 4 points defining a rectangle.
4352
4353 The inner points of the frame are generated by scaling the quad_points by
4354 the length-3 scaling factor.
4355 """
4356 inner_points = _scale_points(quad_points.copy(), center, scale)
4357
4358 # Define frame quads from outer and inner points
4359 quad1_points = np.vstack((quad_points[[0, 1]], inner_points[[1, 0]]))
4360 quad2_points = np.vstack((quad_points[[1, 2]], inner_points[[2, 1]]))
4361 quad3_points = np.vstack((quad_points[[2, 3]], inner_points[[3, 2]]))
4362 quad4_points = np.vstack((quad_points[[3, 0]], inner_points[[0, 3]]))
4363 frame_points = np.vstack((quad1_points, quad2_points, quad3_points, quad4_points))
4364 frame_faces = np.array(
4365 [
4366 [4, 0, 1, 2, 3],
4367 [4, 4, 5, 6, 7],
4368 [4, 8, 9, 10, 11],
4369 [4, 12, 13, 14, 15],
4370 ]
4371 ).ravel()
4372 return frame_points, frame_faces
4373
4374 # Get initial cube output
4375 cube = CubeSource.output.fget(self) # type: ignore[attr-defined]
4376
4377 # Extract list of points for each face in the desired order
4378 cube_points, cube_faces = cube.points, cube.regular_faces
4379 Index = CubeFacesSource._FaceIndex
4380 face_points = [
4381 cube_points[cube_faces[Index.X_POS]],
4382 cube_points[cube_faces[Index.X_NEG]],
4383 cube_points[cube_faces[Index.Y_POS]],
4384 cube_points[cube_faces[Index.Y_NEG]],
4385 cube_points[cube_faces[Index.Z_POS]],
4386 cube_points[cube_faces[Index.Z_NEG]],
4387 ]
4388
4389 # Calc lengths/properties of cube
4390 cube_center = np.array(cube.center)
4391 bnds = cube.bounds
4392 x_len = np.linalg.norm(bnds[1] - bnds[0])
4393 y_len = np.linalg.norm(bnds[3] - bnds[2])
4394 z_len = np.linalg.norm(bnds[5] - bnds[4])
4395 lengths = np.array((x_len, y_len, z_len))
4396 min_length = np.min(lengths)
4397
4398 # Store vars for updating the output
4399 shrink_factor = self.shrink_factor
4400 explode_factor = self.explode_factor
4401 frame_width = self.frame_width
4402 output = self._output
4403
4404 # Modify each face mesh of the output
4405 for index, (name, points) in enumerate(zip(self.names, face_points, strict=True)):
4406 output.set_block_name(index, name)
4407 face_poly = output[index]
4408 face_center = np.mean(points, axis=0)
4409
4410 if shrink_factor is not None:
4411 # Shrink proportional to the smallest face
4412 shrink_scale = shrink_factor + (1 - shrink_factor) * (1 - min_length / lengths)
4413 _scale_points(points, face_center, shrink_scale)
4414
4415 if explode_factor is not None:
4416 # Move away from center by some distance proportional to the smallest face
4417 explode_scale = min_length * explode_factor
4418 direction = face_center - cube_center
4419 direction /= np.linalg.norm(direction)
4420 vector = direction * explode_scale
4421 points += vector # noqa: PLW2901
4422
4423 # Set poly as a single quad cell
4424 face_poly.points = points # type: ignore[union-attr]
4425 face_poly.faces = [4, 0, 1, 2, 3] # type: ignore[union-attr]
4426
4427 if frame_width is not None:
4428 # Create frame proportional to the smallest face
4429 frame_scale = 1 - (frame_width * min_length / lengths)
4430 frame_points, frame_faces = _create_frame_from_quad_points(
4431 points, face_center, frame_scale
4432 )
4433 # Set poly as four quad cells of the frame
4434 face_poly.points = frame_points # type: ignore[union-attr]
4435 face_poly.faces = frame_faces # type: ignore[union-attr]
4436
4437 @property
4438 def output(self: CubeFacesSource) -> MultiBlock: # type: ignore[override]
4439 """Get the output of the source.
4440
4441 The output is a :class:`pyvista.MultiBlock` with six blocks: one for each
4442 face. The blocks are named and ordered as ``('+X','-X','+Y','-Y','+Z','-Z')``.
4443
4444 The source is automatically updated by :meth:`update` prior to returning
4445 the output.
4446
4447 Returns
4448 -------
4449 pyvista.MultiBlock
4450 Composite mesh with six cube faces.
4451
4452 """
4453 self.update()
4454 return self._output