Debian Codegraph @

pyvista/plotting/picking.py

raw
1 """Module managing picking events.
2
3 The plotter exposes the public picking API through the
4 :class:`PickingComponent` plotter component, registered under
5 ``plotter.picking``. The component owns every picking observer, picked-
6 result attribute, and per-pick representation actor, and centralizes
7 teardown in ``__plotter_close__``.
8
9 Top-level methods on :class:`pyvista.BasePlotter` such as
10 ``enable_point_picking``, ``disable_picking``, and ``picked_point``
11 forward to the component for backward compatibility.
12 """
13
14 from __future__ import annotations
15
16 from functools import partial
17 from typing import TYPE_CHECKING
18 import weakref
19
20 import numpy as np
21
22 import pyvista as pv
23 from pyvista import _vtk
24 from pyvista._deprecate_positional_args import _deprecate_positional_args
25 from pyvista._warn_external import warn_external
26 from pyvista.core.errors import PyVistaDeprecationWarning
27 from pyvista.core.utilities.misc import _NoNewAttrMixin
28 from pyvista.core.utilities.misc import try_callback
29
30 from .composite_mapper import CompositePolyDataMapper
31 from .errors import PyVistaPickingError
32 from .mapper import _mapper_get_data_set_input
33 from .mapper import _mapper_has_data_set_input
34 from .opts import ElementType
35 from .opts import PickerType
36
37 if TYPE_CHECKING:
38 from collections.abc import Sequence
39
40 from pyvista.core.pointset import PolyData
41
42 PICKED_REPRESENTATION_NAMES = {
43 'point': '_picked_point',
44 'mesh': '_picked_mesh',
45 'through': '_picked_through_selection',
46 'visible': '_picked_visible_selection',
47 'element': '_picked_element',
48 'path': '_picked_path',
49 'horizon': '_picked_horizon',
50 'frustum': '_rectangle_selection_frustum',
51 }
52
53
54 def _launch_pick_event(interactor, _event):
55 """Create a Pick event based on coordinate or left-click."""
56 click_x, click_y = interactor.GetEventPosition()
57 click_z = 0
58
59 picker = interactor.GetPicker()
60 renderer = interactor.GetInteractorStyle()._parent()._plotter.iren.get_poked_renderer()
61 picker.Pick(click_x, click_y, click_z, renderer)
62
63
64 def _poked_context_callback(plotter, *args, **kwargs):
65 """Use _poked_context_callback in a poked renderer context."""
66 with plotter.iren.poked_subplot():
67 try_callback(*args, **kwargs)
68
69
70 class RectangleSelection(_NoNewAttrMixin):
71 """Internal data structure for rectangle based selections.
72
73 Parameters
74 ----------
75 frustum : :vtk:`vtkPlanes`
76 Frustum that defines the selection.
77 viewport : tuple[float, float, float, float]
78 The selected viewport coordinates, given as ``(x0, y0, x1, y1)``.
79
80 """
81
82 def __init__(self, frustum, viewport):
83 self._frustum = frustum
84 self._viewport = viewport
85
86 @property
87 def frustum(self) -> _vtk.vtkPlanes: # numpydoc ignore=RT01
88 """Get the selected frustum through the scene."""
89 return self._frustum
90
91 @property
92 def frustum_mesh(self) -> pv.PolyData: # numpydoc ignore=RT01
93 """Get the frustum as a PyVista mesh."""
94 frustum_source = _vtk.vtkFrustumSource()
95 frustum_source.ShowLinesOff()
96 frustum_source.SetPlanes(self.frustum)
97 frustum_source.Update()
98 return pv.wrap(frustum_source.GetOutput())
99
100 @property
101 def viewport(self) -> tuple[float, float, float, float]: # numpydoc ignore=RT01
102 """Get the selected viewport coordinates.
103
104 Coordinates are given as: ``(x0, y0, x1, y1)``
105 """
106 return self._viewport
107
108
109 class PointPickingElementHandler(_NoNewAttrMixin):
110 """Internal picking handler for element-based picking.
111
112 This handler is only valid for single point picking operations.
113
114 Parameters
115 ----------
116 mode : ElementType, optional
117 The element type to pick.
118 callback : callable, optional
119 A callback function to be executed on picking events.
120
121 """
122
123 def __init__(self, mode: ElementType = ElementType.CELL, callback=None):
124 self._picker_ = None
125 self.callback = callback
126 self.mode = ElementType.from_any(mode)
127
128 @property
129 def picker(self): # numpydoc ignore=RT01
130 """Get or set the picker instance."""
131 return self._picker_() # type: ignore[misc]
132
133 @picker.setter
134 def picker(self, picker):
135 self._picker_ = weakref.ref(picker) # type: ignore[assignment]
136
137 def get_mesh(self):
138 """Get the picked mesh.
139
140 Returns
141 -------
142 pyvista.DataSet
143 Picked mesh.
144
145 """
146 ds = self.picker.GetDataSet()
147 if ds is not None:
148 return pv.wrap(ds)
149 return None
150
151 def get_cell(self, picked_point):
152 """Get the picked cell of the picked mesh.
153
154 Parameters
155 ----------
156 picked_point : sequence[float]
157 Coordinates of the picked point.
158
159 Returns
160 -------
161 pyvista.UnstructuredGrid
162 UnstructuredGrid containing the picked cell.
163
164 """
165 mesh = self.get_mesh()
166 cell_id = mesh.find_containing_cell(picked_point) # more accurate
167 if cell_id < 0:
168 return None # TODO: this happens but shouldn't # pragma: no cover
169 cell = mesh.extract_cells(cell_id)
170 cell.cell_data['vtkOriginalCellIds'] = np.array([cell_id])
171 return cell
172
173 def get_face(self, picked_point):
174 """Get the picked face of the picked cell.
175
176 Parameters
177 ----------
178 picked_point : sequence[float]
179 Coordinates of the picked point.
180
181 Returns
182 -------
183 pyvista.UnstructuredGrid
184 UnstructuredGrid containing the picked face.
185
186 """
187 cell = self.get_cell(picked_point).get_cell(0)
188 if cell.n_faces > 1:
189 for face in cell.faces:
190 contains = face.cast_to_unstructured_grid().find_containing_cell(picked_point)
191 if contains > -1:
192 break
193 if contains < 0:
194 # this shouldn't happen
195 msg = 'Trouble aligning point with face.'
196 raise RuntimeError(msg)
197 face = face.cast_to_unstructured_grid()
198 face.field_data['vtkOriginalFaceIds'] = np.array([len(cell.faces) - 1])
199 else:
200 face = cell.cast_to_unstructured_grid()
201 face.field_data['vtkOriginalFaceIds'] = np.array([0])
202
203 return face
204
205 def get_edge(self, picked_point):
206 """Get the picked edge of the picked cell.
207
208 Parameters
209 ----------
210 picked_point : sequence[float]
211 Coordinates of the picked point.
212
213 Returns
214 -------
215 pyvista.UnstructuredGrid
216 UnstructuredGrid containing the picked edge.
217
218 """
219 cell = self.get_cell(picked_point).get_cell(0)
220 if cell.n_edges > 1:
221 ei = (
222 cell.cast_to_unstructured_grid()
223 .extract_all_edges()
224 .find_closest_cell(picked_point)
225 )
226 edge = cell.edges[ei].cast_to_unstructured_grid()
227 edge.field_data['vtkOriginalEdgeIds'] = np.array([ei])
228 else:
229 edge = cell.cast_to_unstructured_grid()
230
231 return edge
232
233 def get_point(self, picked_point: Sequence[float]) -> PolyData:
234 """Get the picked point of the picked mesh.
235
236 Parameters
237 ----------
238 picked_point : sequence[float]
239 Coordinates of the picked point.
240
241 Returns
242 -------
243 pyvista.PolyData
244 Picked mesh containing the point.
245
246 """
247 mesh = self.get_mesh()
248 pid = mesh.find_closest_point(picked_point)
249 picked = mesh.extract_points(pid, adjacent_cells=False, include_cells=False)
250 return picked.cast_to_poly_points()
251
252 def __call__(self, picked_point, picker):
253 """Perform the pick."""
254 self.picker = picker
255 mesh = self.get_mesh()
256 if mesh is None:
257 return # No selected mesh (point not on surface of mesh)
258
259 if self.mode == ElementType.MESH:
260 picked = mesh
261 elif self.mode == ElementType.CELL:
262 picked = self.get_cell(picked_point)
263 if picked is None:
264 return # TODO: handle
265 elif self.mode == ElementType.FACE:
266 picked = self.get_face(picked_point)
267 elif self.mode == ElementType.EDGE:
268 picked = self.get_edge(picked_point)
269 elif self.mode == ElementType.POINT:
270 picked = self.get_point(picked_point)
271
272 if self.callback:
273 try_callback(self.callback, picked)
274
275
276 class PickingComponent(_NoNewAttrMixin):
277 """Plotter picking component.
278
279 Owns every picking observer, picked-result attribute, and per-pick
280 representation actor for a single :class:`pyvista.BasePlotter`.
281 Constructed lazily on first access of ``plotter.picking`` and
282 registered for close-time teardown via ``__plotter_close__``.
283
284 The plotter exposes the public picking surface (``enable_*_picking``,
285 ``disable_picking``, ``picked_point`` and friends) as forwarding
286 shims that delegate here.
287
288 Parameters
289 ----------
290 plotter : pyvista.BasePlotter
291 Owning plotter. Stored as a strong reference; the component's
292 lifetime is bounded by the plotter's lifetime.
293
294 Attributes
295 ----------
296 picked_path : pyvista.PolyData | None
297 Polyline accumulated by :meth:`enable_path_picking`.
298 picked_geodesic : pyvista.PolyData | None
299 Geodesic polyline accumulated by :meth:`enable_geodesic_picking`.
300 picked_horizon : pyvista.PolyData | None
301 Ribbon surface produced by :meth:`enable_horizon_picking`.
302
303 .. versionadded:: 0.48.0
304
305 """
306
307 def __init__(self, plotter):
308 """Initialize the picking component."""
309 self._plotter = plotter
310 # Low-level picking state
311 self._picking_left_clicking_observer = None
312 self._picking_right_clicking_observer = None
313 self._picker_in_use = False
314 self._picked_point = None
315 # Mesh-aware picking state
316 self._picked_actor = None
317 self._picked_mesh = None
318 self._picked_cell: None | pv.MultiBlock | pv.UnstructuredGrid = None
319 self._picking_text = None
320 self._picked_block_index = None
321 # Path / geodesic / horizon state
322 self.picked_path = None
323 self.picked_geodesic = None
324 self.picked_horizon = None
325 self._last_picked_idx: int | None = None
326
327 # =========================================================================
328 # Lifecycle
329 # =========================================================================
330
331 def __plotter_close__(self) -> None:
332 """Release picking observers when the owning plotter closes."""
333 self.disable_picking()
334
335 def __plotter_deep_clean__(self) -> None:
336 """Release picking observers on deep clean."""
337 self.disable_picking()
338
339 # =========================================================================
340 # Picked-result properties
341 # =========================================================================
342
343 @property
344 def picked_point(self): # numpydoc ignore=RT01
345 """Return the picked point."""
346 return self._picked_point
347
348 @property
349 def picked_actor(self): # numpydoc ignore=RT01
350 """Return the picked actor."""
351 return self._picked_actor
352
353 @property
354 def picked_mesh(self): # numpydoc ignore=RT01
355 """Return the picked mesh."""
356 return self._picked_mesh
357
358 @property
359 def picked_cells(self) -> None | pv.UnstructuredGrid | pv.MultiBlock:
360 r"""Return the cell-picked object.
361
362 Returns
363 -------
364 output : None | pyvista.UnstructuredGrid | pyvista.MultiBlock
365 Picked object if available.
366
367 """
368 return self._picked_cell
369
370 @property
371 def picked_block_index(self): # numpydoc ignore=RT01
372 """Return the picked block index."""
373 return self._picked_block_index
374
375 # =========================================================================
376 # Pick position helpers
377 # =========================================================================
378
379 def get_pick_position(self):
380 """Get the pick position or area.
381
382 Returns
383 -------
384 sequence
385 Picked position or area as ``(x0, y0, x1, y1)``.
386
387 """
388 renderer = self._plotter.iren.get_poked_renderer()
389 return renderer.get_pick_position()
390
391 def pick_click_position(self):
392 """Get corresponding click location in the 3D plot.
393
394 Returns
395 -------
396 tuple
397 Three item tuple with the 3D picked position.
398
399 """
400 plotter = self._plotter
401 if plotter.click_position is None:
402 plotter.store_click_position()
403 renderer = plotter.iren.get_poked_renderer()
404 plotter.iren.picker.Pick(plotter.click_position[0], plotter.click_position[1], 0, renderer)
405 return plotter.iren.picker.GetPickPosition()
406
407 def pick_mouse_position(self):
408 """Get corresponding mouse location in the 3D plot.
409
410 Returns
411 -------
412 tuple
413 Three item tuple with the 3D picked position.
414
415 """
416 plotter = self._plotter
417 if plotter.mouse_position is None:
418 plotter.store_mouse_position()
419 renderer = plotter.iren.get_poked_renderer()
420 plotter.iren.picker.Pick(plotter.mouse_position[0], plotter.mouse_position[1], 0, renderer)
421 return plotter.iren.picker.GetPickPosition()
422
423 # =========================================================================
424 # Internal helpers
425 # =========================================================================
426
427 def _clear_picking_representations(self):
428 """Clear all picking representations."""
429 for name in PICKED_REPRESENTATION_NAMES.values():
430 self._plotter.remove_actor(name)
431
432 def _init_click_picking_callback(self, *, left_clicking=False):
433 if left_clicking:
434 self._picking_left_clicking_observer = self._plotter.iren.add_observer(
435 'LeftButtonPressEvent',
436 partial(try_callback, _launch_pick_event),
437 )
438 else:
439 self._picking_right_clicking_observer = self._plotter.iren.add_observer(
440 'RightButtonPressEvent',
441 partial(try_callback, _launch_pick_event),
442 )
443
444 def _validate_picker_not_in_use(self):
445 if self._picker_in_use:
446 msg = (
447 'Picking is already enabled, please disable previous picking '
448 'with `disable_picking()`.'
449 )
450 raise PyVistaPickingError(msg)
451
452 # =========================================================================
453 # disable_picking
454 # =========================================================================
455
456 def disable_picking(self) -> None:
457 """Disable any active picking and remove observers.
458
459 Examples
460 --------
461 Enable and then disable picking.
462
463 >>> import pyvista as pv
464 >>> mesh = pv.Sphere(center=(1, 0, 0))
465 >>> cube = pv.Cube()
466 >>> pl = pv.Plotter()
467 >>> _ = pl.add_mesh(mesh)
468 >>> _ = pl.add_mesh(cube)
469 >>> _ = pl.enable_mesh_picking()
470 >>> pl.disable_picking()
471
472 """
473 iren = getattr(self._plotter, 'iren', None)
474 if iren is not None:
475 iren.remove_observer(self._picking_left_clicking_observer)
476 iren.remove_observer(self._picking_right_clicking_observer)
477 iren.reset_picker()
478 self._picking_left_clicking_observer = None
479 self._picking_right_clicking_observer = None
480 self._picker_in_use = False
481
482 # Remove picking-text actor from every renderer.
483 if self._picking_text is not None and hasattr(self._plotter, 'renderers'):
484 for renderer in self._plotter.renderers:
485 renderer.remove_actor(self._picking_text, render=False)
486 self._picking_text = None
487
488 # =========================================================================
489 # Low-level picking entrypoints
490 # =========================================================================
491
492 @_deprecate_positional_args(allowed=['callback'])
493 def enable_point_picking( # noqa: PLR0917
494 self,
495 callback=None,
496 tolerance=0.025,
497 left_clicking=False, # noqa: FBT002
498 picker=PickerType.POINT,
499 show_message=True, # noqa: FBT002
500 font_size=18,
501 color='pink',
502 point_size=10,
503 show_point=True, # noqa: FBT002
504 use_picker=False, # noqa: FBT002
505 pickable_window=False, # noqa: FBT002
506 clear_on_no_selection=True, # noqa: FBT002
507 **kwargs,
508 ):
509 """Enable picking at points under the cursor.
510
511 Enable picking a point at the mouse location in the render
512 view using the right mouse button. This point is saved to the
513 ``.picked_point`` attribute on the plotter. Pass a callback
514 that takes that point as an argument. The picked
515 point can either be a point on the first intersecting mesh, or
516 a point in the 3D window.
517
518 The ``picker`` choice will help determine how the point picking
519 is performed.
520
521 Parameters
522 ----------
523 callback : callable, optional
524 When input, calls this callable after a pick is made. The
525 picked point is input as the first parameter to this
526 callable.
527
528 tolerance : float, tolerance: 0.025
529 Specify tolerance for performing pick operation. Tolerance
530 is specified as fraction of rendering window
531 size. Rendering window size is measured across diagonal.
532 This is only valid for some choices of ``picker``.
533
534 left_clicking : bool, default: False
535 When ``True``, points can be picked by clicking the left mouse
536 button. Default is to use the right mouse button.
537
538 picker : str | PickerType, optional
539 Choice of VTK picker class type:
540
541 * ``'hardware'``: Uses :vtk:`vtkHardwarePicker` which is more
542 performant for large geometries (default).
543 * ``'cell'``: Uses :vtk:`vtkCellPicker`.
544 * ``'point'``: Uses :vtk:`vtkPointPicker` which will snap to
545 points on the surface of the mesh.
546 * ``'volume'``: Uses :vtk:`vtkVolumePicker`.
547
548 show_message : bool | str, default: True
549 Show the message about how to use the point picking
550 tool. If this is a string, that will be the message shown.
551
552 font_size : int, default: 18
553 Sets the size of the message.
554
555 color : ColorLike, default: "pink"
556 The color of the selected mesh when shown.
557
558 point_size : int, default: 10
559 Size of picked points if ``show_point`` is ``True``.
560
561 show_point : bool, default: True
562 Show the picked point after clicking.
563
564 use_picker : bool, default: False
565 When ``True``, the callback will also be passed the picker.
566
567 pickable_window : bool, default: False
568 When ``True`` and the chosen picker supports it, points in the
569 3D window are pickable.
570
571 clear_on_no_selection : bool, default: True
572 Clear the selections when no point is selected.
573
574 **kwargs : dict, optional
575 All remaining keyword arguments are used to control how
576 the picked point is interactively displayed.
577
578 Examples
579 --------
580 Enable point picking with a custom message.
581
582 >>> import pyvista as pv
583 >>> pl = pv.Plotter()
584 >>> _ = pl.add_mesh(pv.Sphere())
585 >>> _ = pl.add_mesh(pv.Cube(), pickable=False)
586 >>> pl.enable_point_picking(show_message='Pick a point')
587
588 See :ref:`point_picking_example` for a full example using this method.
589
590
591 """
592 self._validate_picker_not_in_use()
593 if 'use_mesh' in kwargs:
594 warn_external(
595 '`use_mesh` is deprecated. See `use_picker` instead.',
596 PyVistaDeprecationWarning,
597 )
598 use_mesh = kwargs.pop('use_mesh')
599 else:
600 use_mesh = False
601
602 self_ = weakref.ref(self)
603
604 def _end_pick_event(picker, _event):
605 component = self_()
606 if component is None:
607 return
608 plotter = component._plotter
609 if (
610 not pickable_window
611 and hasattr(picker, 'GetDataSet')
612 and picker.GetDataSet() is None
613 ):
614 component._picked_point = None
615 if clear_on_no_selection:
616 with plotter.iren.poked_subplot():
617 component._clear_picking_representations()
618 return
619 with plotter.iren.poked_subplot():
620 point = np.array(picker.GetPickPosition())
621 point /= plotter.scale # HACK: handle scale
622 component._picked_point = point
623 if show_point:
624 _kwargs = kwargs.copy()
625 plotter.add_mesh(
626 component.picked_point,
627 color=color,
628 point_size=point_size,
629 name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['point']),
630 pickable=_kwargs.pop('pickable', False),
631 reset_camera=_kwargs.pop('reset_camera', False),
632 **_kwargs,
633 )
634 if callable(callback):
635 if use_picker:
636 _poked_context_callback(plotter, callback, component.picked_point, picker)
637 elif use_mesh: # Lower priority
638 _poked_context_callback(
639 plotter,
640 callback,
641 picker.GetDataSet(),
642 picker.GetPointId(),
643 )
644 else:
645 _poked_context_callback(plotter, callback, component.picked_point)
646
647 if picker is not None: # If None, use the already-set picker
648 self._plotter.iren.picker = picker
649 if hasattr(self._plotter.iren.picker, 'SetTolerance'):
650 self._plotter.iren.picker.SetTolerance(tolerance)
651 self._plotter.iren.add_pick_observer(_end_pick_event)
652 self._init_click_picking_callback(left_clicking=left_clicking)
653 self._picker_in_use = True
654
655 if show_message:
656 if show_message is True:
657 show_message = 'Left-click' if left_clicking else 'Right-click'
658 show_message += ' or press P to pick under the mouse'
659 self._picking_text = self._plotter.add_text(
660 str(show_message),
661 font_size=font_size,
662 name='_point_picking_message',
663 )
664
665 @_deprecate_positional_args(allowed=['callback'])
666 def enable_rectangle_picking( # noqa: PLR0917
667 self,
668 callback=None,
669 show_message=True, # noqa: FBT002
670 font_size=18,
671 start=False, # noqa: FBT002
672 show_frustum=False, # noqa: FBT002
673 style='wireframe',
674 color='pink',
675 **kwargs,
676 ):
677 """Enable rectangle based picking at cells.
678
679 Press ``"r"`` to enable rectangle based selection. Press
680 ``"r"`` again to turn it off.
681
682 Picking with the rectangle selection tool provides two values that
683 are passed as the ``RectangleSelection`` object in the callback:
684
685 1. ``RectangleSelection.viewport``: the viewport coordinates of the
686 selection rectangle.
687 2. ``RectangleSelection.frustum``: the full frustum made from
688 the selection rectangle into the scene.
689
690 Parameters
691 ----------
692 callback : callable, optional
693 When input, calls this callable after a selection is made.
694 The ``RectangleSelection`` is the only passed argument
695 containing the viewport coordinates of the selection and the
696 projected frustum.
697
698 show_message : bool | str, default: True
699 Show the message about how to use the cell picking tool. If this
700 is a string, that will be the message shown.
701
702 font_size : int, default: 18
703 Sets the font size of the message.
704
705 start : bool, default: False
706 Automatically start the cell selection tool.
707
708 show_frustum : bool, default: False
709 Show the frustum in the scene.
710
711 style : str, default: "wireframe"
712 Visualization style of the selection frustum. One of the
713 following: ``style='surface'``, ``style='wireframe'``, or
714 ``style='points'``.
715
716 color : ColorLike, default: "pink"
717 The color of the selected frustum when shown.
718
719 **kwargs : dict, optional
720 All remaining keyword arguments are used to control how
721 the selection frustum is interactively displayed.
722
723 Examples
724 --------
725 Add a mesh and a cube to a plot and enable cell picking.
726
727 >>> import pyvista as pv
728 >>> mesh = pv.Sphere(center=(1, 0, 0))
729 >>> cube = pv.Cube()
730 >>> pl = pv.Plotter()
731 >>> _ = pl.add_mesh(mesh)
732 >>> _ = pl.add_mesh(cube)
733 >>> _ = pl.enable_rectangle_picking()
734
735
736 """
737 self._validate_picker_not_in_use()
738
739 self_ = weakref.ref(self)
740
741 def _end_pick_helper(picker, *_):
742 component = self_()
743 if component is None:
744 return
745 plotter = component._plotter
746 renderer = picker.GetRenderer()
747 x0 = int(renderer.GetPickX1())
748 x1 = int(renderer.GetPickX2())
749 y0 = int(renderer.GetPickY1())
750 y1 = int(renderer.GetPickY2())
751
752 selection = RectangleSelection(frustum=picker.GetFrustum(), viewport=(x0, y0, x1, y1))
753
754 if show_frustum:
755 with plotter.iren.poked_subplot():
756 _kwargs = kwargs.copy()
757 plotter.add_mesh(
758 selection.frustum_mesh,
759 name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['frustum']),
760 style=style,
761 color=color,
762 pickable=_kwargs.pop('pickable', False),
763 reset_camera=_kwargs.pop('reset_camera', False),
764 **_kwargs,
765 )
766
767 if callback is not None:
768 _poked_context_callback(plotter, callback, selection)
769
770 self._plotter.enable_rubber_band_style()
771 self._plotter.iren.picker = 'rendered'
772 self._plotter.iren.add_pick_observer(_end_pick_helper)
773 self._picker_in_use = True
774
775 if show_message:
776 if show_message is True:
777 show_message = 'Press R to toggle selection tool'
778 self._picking_text = self._plotter.add_text(
779 str(show_message),
780 font_size=font_size,
781 name='_rectangle_picking_message',
782 )
783
784 if start:
785 self._plotter.iren._style_class.StartSelect()
786
787 # =========================================================================
788 # Mesh-aware picking
789 # =========================================================================
790
791 @_deprecate_positional_args(allowed=['callback'])
792 def enable_surface_point_picking( # noqa: PLR0917
793 self,
794 callback=None,
795 show_message=True, # noqa: FBT002
796 font_size=18,
797 color='pink',
798 show_point=True, # noqa: FBT002
799 point_size=10,
800 tolerance=0.025,
801 pickable_window=False, # noqa: FBT002
802 left_clicking=False, # noqa: FBT002
803 picker=PickerType.CELL,
804 use_picker=False, # noqa: FBT002
805 clear_on_no_selection=True, # noqa: FBT002
806 **kwargs,
807 ):
808 """Enable picking of a point on the surface of a mesh.
809
810 Parameters
811 ----------
812 callback : callable, optional
813 When input, calls this callable after a selection is made. The
814 ``mesh`` is input as the first parameter to this callable.
815
816 show_message : bool | str, default: True
817 Show the message about how to use the mesh picking tool. If this
818 is a string, that will be the message shown.
819
820 font_size : int, default: 18
821 Sets the font size of the message.
822
823 color : ColorLike, default: "pink"
824 The color of the selected mesh when shown.
825
826 show_point : bool, default: True
827 Show the selection interactively.
828
829 point_size : int, default: 10
830 Size of picked points if ``show_point`` is ``True``.
831
832 tolerance : float, default: 0.025
833 Specify tolerance for performing pick operation. Tolerance
834 is specified as fraction of rendering window
835 size. Rendering window size is measured across diagonal.
836
837 .. warning::
838 This is ignored with the ``'hardware'`` ``picker``.
839
840 pickable_window : bool, default: False
841 When ``True``, points in the 3D window are pickable.
842
843 left_clicking : bool, default: False
844 When ``True``, meshes can be picked by clicking the left
845 mousebutton.
846
847 .. note::
848 If enabled, left-clicking will **not** display the bounding box
849 around the picked mesh.
850
851 picker : str | PickerType, optional
852 Choice of VTK picker class type:
853
854 * ``'hardware'``: Uses :vtk:`vtkHardwarePicker` which is more
855 performant for large geometries (default).
856 * ``'cell'``: Uses :vtk:`vtkCellPicker`.
857 * ``'point'``: Uses :vtk:`vtkPointPicker` which will snap to
858 points on the surface of the mesh.
859 * ``'volume'``: Uses :vtk:`vtkVolumePicker`.
860
861 use_picker : bool, default: False
862 When ``True``, the callback will also be passed the picker.
863
864 clear_on_no_selection : bool, default: True
865 Clear the selections when no point is selected.
866
867 **kwargs : dict, optional
868 All remaining keyword arguments are used to control how
869 the picked path is interactively displayed.
870
871 Notes
872 -----
873 Picked point can be accessed from :attr:`picked_point
874 <pyvista.Plotter.picked_point>` attribute.
875
876 Examples
877 --------
878 Add a cube to a plot and enable cell picking.
879
880 >>> import pyvista as pv
881 >>> cube = pv.Cube()
882 >>> pl = pv.Plotter()
883 >>> _ = pl.add_mesh(cube)
884 >>> _ = pl.enable_surface_point_picking()
885
886 See :ref:`surface_point_picking_example` for a full example using this method.
887
888
889 """
890 picker = PickerType.from_any(picker)
891 valid_pickers = [
892 PickerType.POINT,
893 PickerType.CELL,
894 PickerType.HARDWARE,
895 PickerType.VOLUME,
896 ]
897 if picker not in valid_pickers:
898 msg = f'Invalid picker choice for surface picking. Use one of: {valid_pickers}'
899 raise ValueError(msg)
900
901 self_ = weakref.ref(self)
902
903 def _end_pick_event(picked_point, picker):
904 component = self_()
905 if component is None:
906 return
907 plotter = component._plotter
908 if not pickable_window and picker.GetActor() is None:
909 component._picked_point = None
910 component._picked_actor = None
911 component._picked_mesh = None
912 if clear_on_no_selection:
913 with plotter.iren.poked_subplot():
914 component._clear_picking_representations()
915 return
916 component._picked_actor = picker.GetActor()
917 component._picked_mesh = picker.GetDataSet()
918
919 if show_point:
920 with plotter.iren.poked_subplot():
921 _kwargs = kwargs.copy()
922 plotter.add_mesh(
923 picked_point,
924 color=color,
925 point_size=point_size,
926 name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['point']),
927 pickable=_kwargs.pop('pickable', False),
928 reset_camera=_kwargs.pop('reset_camera', False),
929 **_kwargs,
930 )
931 if callable(callback):
932 if use_picker:
933 _poked_context_callback(plotter, callback, picked_point, picker)
934 else:
935 _poked_context_callback(plotter, callback, picked_point)
936
937 self.enable_point_picking(
938 callback=_end_pick_event,
939 picker=picker,
940 show_point=False,
941 show_message=show_message,
942 left_clicking=left_clicking,
943 use_picker=True,
944 font_size=font_size,
945 tolerance=tolerance,
946 pickable_window=True, # let this callback handle pickable window
947 clear_on_no_selection=clear_on_no_selection,
948 )
949
950 @_deprecate_positional_args(allowed=['callback'])
951 def enable_mesh_picking( # noqa: PLR0917
952 self,
953 callback=None,
954 show=True, # noqa: FBT002
955 show_message=True, # noqa: FBT002
956 style='wireframe',
957 line_width=5,
958 color='pink',
959 font_size=18,
960 left_clicking=False, # noqa: FBT002
961 use_actor=False, # noqa: FBT002
962 picker=PickerType.CELL,
963 **kwargs,
964 ):
965 """Enable picking of a mesh.
966
967 Parameters
968 ----------
969 callback : callable, optional
970 When input, calls this callable after a selection is made. The
971 ``mesh`` is input as the first parameter to this callable.
972
973 show : bool, default: True
974 Show the selection interactively. Best when combined with
975 ``left_clicking``.
976
977 show_message : bool | str, default: True
978 Show the message about how to use the mesh picking tool. If this
979 is a string, that will be the message shown.
980
981 style : str, default: "wireframe"
982 Visualization style of the selection. One of the following:
983
984 * ``'surface'``
985 * ``'wireframe'``
986 * ``'points'``
987
988 line_width : float, default: 5.0
989 Thickness of selected mesh edges.
990
991 color : ColorLike, default: "pink"
992 The color of the selected mesh when shown.
993
994 font_size : int, default: 18
995 Sets the font size of the message.
996
997 left_clicking : bool, default: False
998 When ``True``, meshes can be picked by clicking the left
999 mousebutton.
1000
1001 .. note::
1002 If enabled, left-clicking will **not** display the bounding box
1003 around the picked point.
1004
1005 use_actor : bool, default: False
1006 If True, the callback will be passed the picked actor instead of
1007 the mesh object.
1008
1009 picker : str | PickerType, optional
1010 Choice of VTK picker class type:
1011
1012 * ``'hardware'``: Uses :vtk:`vtkHardwarePicker` which is more
1013 performant for large geometries (default).
1014 * ``'cell'``: Uses :vtk:`vtkCellPicker`.
1015 * ``'point'``: Uses :vtk:`vtkPointPicker` which will snap to
1016 points on the surface of the mesh.
1017 * ``'volume'``: Uses :vtk:`vtkVolumePicker`.
1018
1019
1020 **kwargs : dict, optional
1021 All remaining keyword arguments are used to control how
1022 the picked path is interactively displayed.
1023
1024 Returns
1025 -------
1026 :vtk:`vtkPropPicker`
1027 Property picker.
1028
1029 Examples
1030 --------
1031 Add a sphere and a cube to a plot and enable mesh picking. Enable
1032 ``left_clicking`` to immediately start picking on the left click and
1033 disable showing the box. You can still press the ``p`` key to select
1034 meshes.
1035
1036 >>> import pyvista as pv
1037 >>> mesh = pv.Sphere(center=(1, 0, 0))
1038 >>> cube = pv.Cube()
1039 >>> pl = pv.Plotter()
1040 >>> _ = pl.add_mesh(mesh)
1041 >>> _ = pl.add_mesh(cube)
1042 >>> _ = pl.enable_mesh_picking()
1043
1044 See :ref:`mesh_picking_example` for a full example using this method.
1045
1046
1047 """
1048 self_ = weakref.ref(self)
1049
1050 def end_pick_call_back(*args): # noqa: ARG001
1051 component = self_()
1052 if component is None:
1053 return
1054 plotter = component._plotter
1055 if callback:
1056 if use_actor:
1057 _poked_context_callback(plotter, callback, component._picked_actor)
1058 else:
1059 _poked_context_callback(plotter, callback, component._picked_mesh)
1060
1061 if show:
1062 # Select the renderer where the mesh is added.
1063 active_renderer_index = plotter.renderers._active_index
1064 loc = plotter.iren.get_event_subplot_loc()
1065 plotter.subplot(*loc)
1066
1067 # Use try in case selection is empty or invalid
1068 try:
1069 with plotter.iren.poked_subplot():
1070 _kwargs = kwargs.copy()
1071 plotter.add_mesh(
1072 component._picked_mesh,
1073 name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['mesh']),
1074 style=style,
1075 color=color,
1076 line_width=line_width,
1077 pickable=_kwargs.pop('pickable', False),
1078 reset_camera=_kwargs.pop('reset_camera', False),
1079 **_kwargs,
1080 )
1081 except Exception as e: # noqa: BLE001 # pragma: no cover
1082 warn_external(f'Unable to show mesh when picking:\n\n{e}')
1083
1084 # Reset to the active renderer.
1085 loc = plotter.renderers.index_to_loc(active_renderer_index)
1086 plotter.subplot(*loc)
1087
1088 # render here prior to running the callback
1089 plotter.render()
1090
1091 if show_message and show_message is True:
1092 show_message = 'Left-click' if left_clicking else 'Right-click'
1093 show_message += ' or press P to pick single dataset under the mouse pointer'
1094
1095 self.enable_surface_point_picking(
1096 callback=end_pick_call_back,
1097 picker=picker,
1098 show_point=False,
1099 show_message=show_message,
1100 left_clicking=left_clicking,
1101 use_picker=True,
1102 font_size=font_size,
1103 pickable_window=False,
1104 )
1105
1106 @_deprecate_positional_args(allowed=['callback'])
1107 def enable_rectangle_through_picking( # noqa: PLR0917
1108 self,
1109 callback=None,
1110 show=True, # noqa: FBT002
1111 style='wireframe',
1112 line_width=5,
1113 color='pink',
1114 show_message=True, # noqa: FBT002
1115 font_size=18,
1116 start=False, # noqa: FBT002
1117 show_frustum=False, # noqa: FBT002
1118 **kwargs,
1119 ):
1120 """Enable rectangle based cell picking through the scene.
1121
1122 Parameters
1123 ----------
1124 callback : callable, optional
1125 When input, calls this callable after a selection is made.
1126 The picked cells is the only passed argument.
1127
1128 show : bool, default: True
1129 Show the selection interactively.
1130
1131 style : str, default: "wireframe"
1132 Visualization style of the selection frustum. One of the
1133 following: ``style='surface'``, ``style='wireframe'``, or
1134 ``style='points'``.
1135
1136 line_width : float, default: 5.0
1137 Thickness of selected mesh edges.
1138
1139 color : ColorLike, default: "pink"
1140 The color of the selected frustum when shown.
1141
1142 show_message : bool | str, default: True
1143 Show the message about how to use the cell picking tool. If this
1144 is a string, that will be the message shown.
1145
1146 font_size : int, default: 18
1147 Sets the font size of the message.
1148
1149 start : bool, default: False
1150 Automatically start the cell selection tool.
1151
1152 show_frustum : bool, default: False
1153 Show the frustum in the scene.
1154
1155 **kwargs : dict, optional
1156 All remaining keyword arguments are used to control how
1157 the selection frustum is interactively displayed.
1158
1159
1160 """
1161 self_ = weakref.ref(self)
1162
1163 def finalize(picked):
1164 component = self_()
1165 if component is None:
1166 return
1167 plotter = component._plotter
1168 if picked is None:
1169 # Indicates invalid pick
1170 with plotter.iren.poked_subplot():
1171 component._clear_picking_representations()
1172 return
1173
1174 component._picked_cell = picked
1175
1176 if show:
1177 with plotter.iren.poked_subplot():
1178 _kwargs = kwargs.copy()
1179 plotter.add_mesh(
1180 picked,
1181 name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['through']),
1182 style=style,
1183 color=color,
1184 line_width=line_width,
1185 pickable=_kwargs.pop('pickable', False),
1186 reset_camera=_kwargs.pop('reset_camera', False),
1187 **_kwargs,
1188 )
1189
1190 if callback is not None:
1191 _poked_context_callback(plotter, callback, component.picked_cells)
1192
1193 def through_pick_callback(selection: RectangleSelection):
1194 component = self_()
1195 if component is None:
1196 return
1197 plotter = component._plotter
1198 picked = pv.MultiBlock()
1199 renderer = plotter.iren.get_poked_renderer()
1200 for actor in renderer.actors.values():
1201 if (
1202 (mapper := actor.GetMapper())
1203 and _mapper_has_data_set_input(mapper)
1204 and actor.GetPickable()
1205 ):
1206 input_mesh = pv.wrap(_mapper_get_data_set_input(actor.GetMapper()))
1207 input_mesh.cell_data['original_cell_ids'] = np.arange(input_mesh.n_cells)
1208 extract = _vtk.vtkExtractGeometry()
1209 extract.SetInputData(input_mesh)
1210 extract.SetImplicitFunction(selection.frustum)
1211 extract.Update()
1212
1213 if (wrapped := pv.wrap(extract.GetOutput())).n_cells > 0:
1214 picked.append(wrapped)
1215
1216 if picked.n_blocks == 0 or picked.combine().n_cells < 1:
1217 component._picked_cell = None
1218 elif picked.n_blocks == 1:
1219 component._picked_cell = picked[0] # type: ignore[assignment]
1220 else:
1221 component._picked_cell = picked
1222
1223 finalize(component._picked_cell)
1224
1225 self.enable_rectangle_picking(
1226 callback=through_pick_callback,
1227 show_message=show_message,
1228 font_size=font_size,
1229 show_frustum=show_frustum,
1230 start=start,
1231 style=style,
1232 color=color,
1233 )
1234
1235 @_deprecate_positional_args(allowed=['callback'])
1236 def enable_rectangle_visible_picking( # noqa: PLR0917
1237 self,
1238 callback=None,
1239 show=True, # noqa: FBT002
1240 style='wireframe',
1241 line_width=5,
1242 color='pink',
1243 show_message=True, # noqa: FBT002
1244 font_size=18,
1245 start=False, # noqa: FBT002
1246 show_frustum=False, # noqa: FBT002
1247 **kwargs,
1248 ):
1249 """Enable rectangle based cell picking on visible surfaces.
1250
1251 Parameters
1252 ----------
1253 callback : callable, optional
1254 When input, calls this callable after a selection is made.
1255 The picked cells is the only passed argument.
1256
1257 show : bool, default: True
1258 Show the selection interactively.
1259
1260 style : str, default: "wireframe"
1261 Visualization style of the selection frustum. One of the
1262 following: ``style='surface'``, ``style='wireframe'``, or
1263 ``style='points'``.
1264
1265 line_width : float, default: 5.0
1266 Thickness of selected mesh edges.
1267
1268 color : ColorLike, default: "pink"
1269 The color of the selected frustum when shown.
1270
1271 show_message : bool | str, default: True
1272 Show the message about how to use the cell picking tool. If this
1273 is a string, that will be the message shown.
1274
1275 font_size : int, default: 18
1276 Sets the font size of the message.
1277
1278 start : bool, default: False
1279 Automatically start the cell selection tool.
1280
1281 show_frustum : bool, default: False
1282 Show the frustum in the scene.
1283
1284 **kwargs : dict, optional
1285 All remaining keyword arguments are used to control how
1286 the selection frustum is interactively displayed.
1287
1288
1289 """
1290 self_ = weakref.ref(self)
1291
1292 def finalize(picked):
1293 component = self_()
1294 if component is None:
1295 return
1296 plotter = component._plotter
1297 if picked is None:
1298 with plotter.iren.poked_subplot():
1299 component._clear_picking_representations()
1300 return
1301
1302 if show:
1303 with plotter.iren.poked_subplot():
1304 _kwargs = kwargs.copy()
1305 plotter.add_mesh(
1306 picked,
1307 name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['visible']),
1308 style=style,
1309 color=color,
1310 line_width=line_width,
1311 pickable=_kwargs.pop('pickable', False),
1312 reset_camera=_kwargs.pop('reset_camera', False),
1313 **_kwargs,
1314 )
1315
1316 if callback is not None:
1317 _poked_context_callback(plotter, callback, picked)
1318
1319 def visible_pick_callback(selection):
1320 component = self_()
1321 if component is None:
1322 return
1323 plotter = component._plotter
1324 picked = pv.MultiBlock()
1325 renderer = plotter.iren.get_poked_renderer()
1326 x0, y0, x1, y1 = renderer.get_pick_position()
1327 if x0 >= 0: # initial pick position is (-1, -1, -1, -1)
1328 selector = _vtk.vtkOpenGLHardwareSelector()
1329 selector.SetFieldAssociation(_vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS)
1330 selector.SetRenderer(renderer)
1331 selector.SetArea(x0, y0, x1, y1)
1332 selection = selector.Select()
1333
1334 for node in range(selection.GetNumberOfNodes()):
1335 selection_node = selection.GetNode(node)
1336 if selection_node is None: # pragma: no cover
1337 continue
1338 cids = pv.convert_array(selection_node.GetSelectionList())
1339 actor = selection_node.GetProperties().Get(_vtk.vtkSelectionNode.PROP())
1340
1341 if not actor.GetMapper() or not hasattr(
1342 actor.GetProperty(),
1343 'GetRepresentation',
1344 ):
1345 continue
1346
1347 if actor.GetProperty().GetRepresentation() != 2: # pragma: no cover
1348 warn_external(
1349 'Display representations other than `surface` will result '
1350 'in incorrect results.',
1351 )
1352 smesh = pv.wrap(_mapper_get_data_set_input(actor.GetMapper()))
1353 smesh = smesh.copy()
1354 smesh.cell_data['original_cell_ids'] = np.arange(smesh.n_cells)
1355 tri_smesh = smesh.extract_surface(
1356 algorithm=None, pass_pointid=False, pass_cellid=False
1357 ).triangulate()
1358 cids_to_get = tri_smesh.extract_cells(cids)['original_cell_ids']
1359 picked.append(smesh.extract_cells(cids_to_get))
1360
1361 # memory leak issues on vtk==9.0.20210612.dev0
1362 # See https://gitlab.kitware.com/vtk/vtk/-/issues/18239#note_973826
1363 selection.UnRegister(selection)
1364
1365 if len(picked) == 0 or picked.combine().n_cells < 1:
1366 component._picked_cell = None
1367 elif len(picked) == 1:
1368 component._picked_cell = picked[0] # type: ignore[assignment]
1369 else:
1370 component._picked_cell = picked
1371
1372 finalize(component._picked_cell)
1373
1374 self.enable_rectangle_picking(
1375 callback=visible_pick_callback,
1376 show_message=show_message,
1377 font_size=font_size,
1378 start=start,
1379 show_frustum=show_frustum,
1380 style=style,
1381 color=color,
1382 )
1383
1384 @_deprecate_positional_args(allowed=['callback'])
1385 def enable_cell_picking( # noqa: PLR0917
1386 self,
1387 callback=None,
1388 through=True, # noqa: FBT002
1389 show=True, # noqa: FBT002
1390 show_message=True, # noqa: FBT002
1391 style='wireframe',
1392 line_width=5,
1393 color='pink',
1394 font_size=18,
1395 start=False, # noqa: FBT002
1396 show_frustum=False, # noqa: FBT002
1397 **kwargs,
1398 ):
1399 """Enable picking of cells with a rectangle selection tool.
1400
1401 Press ``"r"`` to enable rectangle based selection. Press
1402 ``"r"`` again to turn it off. Selection will be saved to
1403 :attr:`picked_cells <pyvista.Plotter.picked_cells>` as:
1404
1405 * a :class:`pyvista.MultiBlock` when multiple meshes have been picked,
1406 * an :class:`pyvista.UnstructuredGrid` if a single mesh have been picked.
1407
1408 All meshes in the scene are available for picking by default.
1409 If you would like to only pick a single mesh in the scene,
1410 use the ``pickable=False`` argument when adding the other
1411 meshes to the scene.
1412
1413 Uses last input mesh for input by default.
1414
1415 .. warning::
1416 Visible cell picking (``through=False``) will only work if
1417 the mesh is displayed with a ``'surface'`` representation
1418 style (the default).
1419
1420 Parameters
1421 ----------
1422 callback : callable, optional
1423 When input, calls this callable after a selection is made.
1424 The :attr:`picked_cells <pyvista.Plotter.picked_cells>` is given
1425 as the first parameter to this callable.
1426
1427 through : bool, default: True
1428 When ``True`` the picker will select all cells
1429 through the mesh(es). When ``False``, the picker will select
1430 only visible cells on the selected surface(s).
1431
1432 show : bool, default: True
1433 Show the selection interactively.
1434
1435 show_message : bool | str, default: True
1436 Show the message about how to use the cell picking tool. If this
1437 is a string, that will be the message shown.
1438
1439 style : str, default: "wireframe"
1440 Visualization style of the selection. One of the
1441 following: ``style='surface'``, ``style='wireframe'``, or
1442 ``style='points'``.
1443
1444 line_width : float, default: 5.0
1445 Thickness of selected mesh edges.
1446
1447 color : ColorLike, default: "pink"
1448 The color of the selected mesh when shown.
1449
1450 font_size : int, default: 18
1451 Sets the font size of the message.
1452
1453 start : bool, default: False
1454 Automatically start the cell selection tool.
1455
1456 show_frustum : bool, default: False
1457 Show the frustum in the scene.
1458
1459 **kwargs : dict, optional
1460 All remaining keyword arguments are used to control how
1461 the selection is interactively displayed.
1462
1463 Examples
1464 --------
1465 Add a mesh and a cube to a plot and enable cell picking.
1466
1467 >>> import pyvista as pv
1468 >>> mesh = pv.Sphere(center=(1, 0, 0))
1469 >>> cube = pv.Cube()
1470 >>> pl = pv.Plotter()
1471 >>> _ = pl.add_mesh(mesh)
1472 >>> _ = pl.add_mesh(cube)
1473 >>> _ = pl.enable_cell_picking()
1474
1475
1476 """
1477 if through:
1478 method = self.enable_rectangle_through_picking
1479 else:
1480 method = self.enable_rectangle_visible_picking
1481 method(
1482 callback=callback,
1483 show=show,
1484 show_message=show_message,
1485 style=style,
1486 line_width=line_width,
1487 color=color,
1488 font_size=font_size,
1489 start=start,
1490 show_frustum=show_frustum,
1491 **kwargs,
1492 )
1493
1494 @_deprecate_positional_args(allowed=['callback'])
1495 def enable_element_picking( # noqa: PLR0917
1496 self,
1497 callback=None,
1498 mode='cell',
1499 show=True, # noqa: FBT002
1500 show_message=True, # noqa: FBT002
1501 font_size=18,
1502 tolerance=0.025,
1503 pickable_window=False, # noqa: FBT002
1504 left_clicking=False, # noqa: FBT002
1505 picker=PickerType.CELL,
1506 **kwargs,
1507 ):
1508 """Select individual elements on a mesh.
1509
1510 Parameters
1511 ----------
1512 callback : callable, optional
1513 When input, calls this callable after a selection is made. The
1514 ``mesh`` is input as the first parameter to this callable.
1515
1516 mode : str | ElementType, default: "cell"
1517 The picking mode. Either ``"mesh"``, ``"cell"``, ``"face"``,
1518 ``"edge"``, or ``"point"``.
1519
1520 show : bool, default: True
1521 Show the selection interactively.
1522
1523 show_message : bool | str, default: True
1524 Show the message about how to use the mesh picking tool. If this
1525 is a string, that will be the message shown.
1526
1527 font_size : int, default: 18
1528 Sets the font size of the message.
1529
1530 tolerance : float, default: 0.025
1531 Specify tolerance for performing pick operation. Tolerance
1532 is specified as fraction of rendering window
1533 size. Rendering window size is measured across diagonal.
1534
1535 .. warning::
1536 This is ignored with the ``'hardware'`` ``picker``.
1537
1538 pickable_window : bool, default: False
1539 When ``True``, points in the 3D window are pickable.
1540
1541 left_clicking : bool, default: False
1542 When ``True``, meshes can be picked by clicking the left
1543 mousebutton.
1544
1545 .. note::
1546 If enabled, left-clicking will **not** display the bounding box
1547 around the picked mesh.
1548
1549 picker : str | PickerType, optional
1550 Choice of VTK picker class type:
1551
1552 * ``'hardware'``: Uses :vtk:`vtkHardwarePicker` which is more
1553 performant for large geometries (default).
1554 * ``'cell'``: Uses :vtk:`vtkCellPicker`.
1555 * ``'point'``: Uses :vtk:`vtkPointPicker` which will snap to
1556 points on the surface of the mesh.
1557 * ``'volume'``: Uses :vtk:`vtkVolumePicker`.
1558
1559 **kwargs : dict, optional
1560 All remaining keyword arguments are used to control how
1561 the picked path is interactively displayed.
1562
1563 See Also
1564 --------
1565 :ref:`element_picking_example`
1566
1567
1568 """
1569 mode = ElementType.from_any(mode)
1570 self_ = weakref.ref(self)
1571
1572 def _end_handler(picked):
1573 component = self_()
1574 if component is None:
1575 return
1576 plotter = component._plotter
1577 if callback:
1578 _poked_context_callback(plotter, callback, picked)
1579
1580 if mode == ElementType.CELL:
1581 component._picked_cell = picked
1582
1583 if show:
1584 if mode == ElementType.CELL:
1585 kwargs.setdefault('color', 'pink')
1586 elif mode == ElementType.EDGE:
1587 kwargs.setdefault('color', 'magenta')
1588 else:
1589 kwargs.setdefault('color', 'pink')
1590
1591 if mode in [ElementType.CELL, ElementType.FACE]:
1592 picked = picked.extract_all_edges()
1593
1594 with plotter.iren.poked_subplot():
1595 _kwargs = kwargs.copy()
1596 plotter.add_mesh(
1597 picked,
1598 name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['element']),
1599 pickable=_kwargs.pop('pickable', False),
1600 reset_camera=_kwargs.pop('reset_camera', False),
1601 point_size=_kwargs.pop('point_size', 5),
1602 line_width=_kwargs.pop('line_width', 5),
1603 **_kwargs,
1604 )
1605
1606 handler = PointPickingElementHandler(mode=mode, callback=_end_handler)
1607
1608 self.enable_surface_point_picking(
1609 callback=handler,
1610 show_message=show_message,
1611 font_size=font_size,
1612 show_point=False,
1613 tolerance=tolerance,
1614 pickable_window=pickable_window,
1615 left_clicking=left_clicking,
1616 picker=picker,
1617 use_picker=True,
1618 **kwargs,
1619 )
1620
1621 def enable_block_picking(self, callback=None, side='left'):
1622 """Enable composite block picking.
1623
1624 Use this picker to return the index of a DataSet when using composite
1625 dataset like :class:`pyvista.MultiBlock` and pass it to a callback.
1626
1627 Parameters
1628 ----------
1629 callback : callable, optional
1630 When input, this picker calls this callable after a selection is
1631 made. The composite index is passed to ``callback`` as the first
1632 argument and the dataset as the second argument.
1633
1634 side : str, default: "left"
1635 The mouse button to track (either ``'left'`` or ``'right'``).
1636 Also accepts ``'r'`` or ``'l'``.
1637
1638 Notes
1639 -----
1640 The picked block index can be accessed from :attr:`picked_block_index
1641 <pyvista.Plotter.picked_block_index>` attribute.
1642
1643 Examples
1644 --------
1645 Enable block picking with a multiblock dataset. Left clicking will turn
1646 blocks blue while right picking will turn the block back to the default
1647 color.
1648
1649 >>> import pyvista as pv
1650 >>> multiblock = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
1651 >>> pl = pv.Plotter()
1652 >>> actor, mapper = pl.add_composite(multiblock)
1653 >>> def turn_blue(index, dataset):
1654 ... mapper.block_attr[index].color = 'blue'
1655 >>> pl.enable_block_picking(callback=turn_blue, side='left')
1656 >>> def clear_color(index, dataset):
1657 ... mapper.block_attr[index].color = None
1658 >>> pl.enable_block_picking(callback=clear_color, side='right')
1659 >>> pl.show()
1660
1661
1662 """
1663 self_ = weakref.ref(self)
1664
1665 sel_index = _vtk.vtkSelectionNode.COMPOSITE_INDEX()
1666 sel_prop = _vtk.vtkSelectionNode.PROP()
1667
1668 def get_picked_block(*args, **kwargs): # numpydoc ignore=PR01 # noqa: ARG001
1669 component = self_()
1670 if component is None:
1671 return
1672 plotter = component._plotter
1673 x, y = plotter.mouse_position
1674 loc = plotter.iren.get_event_subplot_loc()
1675 index = plotter.renderers.loc_to_index(loc)
1676 renderer = plotter.renderers[index]
1677
1678 selector = _vtk.vtkOpenGLHardwareSelector()
1679 selector.SetRenderer(renderer)
1680 selector.SetArea(x, y, x, y)
1681 selection = selector.Select()
1682
1683 for ii in range(selection.GetNumberOfNodes()):
1684 node = selection.GetNode(ii)
1685 if node is None: # pragma: no cover
1686 continue
1687 node_prop = node.GetProperties()
1688 component._picked_block_index = node_prop.Get(sel_index)
1689
1690 # Safely return the dataset (a non-pyvista mapper may have been added).
1691 mapper = node_prop.Get(sel_prop).GetMapper()
1692 if isinstance(mapper, CompositePolyDataMapper):
1693 dataset = mapper.block_attr.get_block(component._picked_block_index)
1694 else: # pragma: no cover
1695 dataset = None
1696
1697 if callable(callback):
1698 _poked_context_callback(
1699 plotter, callback, component._picked_block_index, dataset
1700 )
1701
1702 self._plotter.track_click_position(callback=get_picked_block, viewport=True, side=side)
1703
1704 # =========================================================================
1705 # Higher-level convenience pickers
1706 # =========================================================================
1707
1708 @_deprecate_positional_args
1709 def fly_to_mouse_position(self, focus=False): # noqa: FBT002
1710 """Focus on last stored mouse position."""
1711 plotter = self._plotter
1712 if plotter.mouse_position is None:
1713 plotter.store_mouse_position()
1714 click_point = self.pick_mouse_position()
1715 if focus:
1716 plotter.set_focus(click_point)
1717 else:
1718 plotter.fly_to(click_point)
1719
1720 def enable_fly_to_right_click(self, callback=None):
1721 """Set the camera to track right click positions.
1722
1723 A convenience method to track right click positions and fly to
1724 the picked point in the scene. The callback will be passed the
1725 point in 3D space.
1726
1727 Parameters
1728 ----------
1729 callback : callable
1730 Callback to call immediately after right clicking.
1731
1732 """
1733 self_ = weakref.ref(self)
1734
1735 def _the_callback(*_):
1736 component = self_()
1737 if component is None:
1738 return
1739 plotter = component._plotter
1740 click_point = component.pick_mouse_position()
1741 plotter.fly_to(click_point)
1742 if callable(callback):
1743 _poked_context_callback(plotter, callback, click_point)
1744
1745 self._plotter.track_click_position(callback=_the_callback, side='right')
1746
1747 @_deprecate_positional_args(allowed=['callback'])
1748 def enable_path_picking( # noqa: PLR0917
1749 self,
1750 callback=None,
1751 show_message=True, # noqa: FBT002
1752 font_size=18,
1753 color='pink',
1754 point_size=10,
1755 line_width=5,
1756 show_path=True, # noqa: FBT002
1757 tolerance=0.025,
1758 **kwargs,
1759 ):
1760 """Enable picking at paths.
1761
1762 This is a convenience method for :func:`enable_point_picking
1763 <pyvista.Plotter.enable_point_picking>` to keep track of the
1764 picked points and create a line using those points.
1765
1766 The line is saved to the ``.picked_path`` attribute of this
1767 plotter
1768
1769 Parameters
1770 ----------
1771 callback : callable, optional
1772 When given, calls this callable after a pick is made. The
1773 entire picked path is passed as the only parameter to this
1774 callable.
1775
1776 show_message : bool | str, default: True
1777 Show the message about how to use the point picking
1778 tool. If this is a string, that will be the message shown.
1779
1780 font_size : int, default: 18
1781 Sets the size of the message.
1782
1783 color : ColorLike, default: "pink"
1784 The color of the selected mesh when shown.
1785
1786 point_size : int, default: 10
1787 Size of picked points if ``show_path`` is ``True``.
1788
1789 line_width : float, default: 5.0
1790 Thickness of path representation if ``show_path`` is
1791 ``True``.
1792
1793 show_path : bool, default: True
1794 Show the picked path interactively.
1795
1796 tolerance : float, default: 0.025
1797 Specify tolerance for performing pick operation. Tolerance
1798 is specified as fraction of rendering window
1799 size. Rendering window size is measured across diagonal.
1800
1801 **kwargs : dict, optional
1802 All remaining keyword arguments are used to control how
1803 the picked path is interactively displayed.
1804
1805
1806 """
1807 self_ = weakref.ref(self)
1808 kwargs.setdefault('pickable', False)
1809
1810 def make_line_cells(n_points):
1811 cells = np.arange(0, n_points, dtype=np.int_)
1812 return np.insert(cells, 0, n_points)
1813
1814 the_points = []
1815
1816 def _the_callback(picked_point, picker):
1817 component = self_()
1818 if component is None:
1819 return
1820 plotter = component._plotter
1821 if picker.GetDataSet() is None:
1822 return
1823 the_points.append(picked_point)
1824 component.picked_path = pv.PolyData(np.array(the_points))
1825 component.picked_path.lines = make_line_cells(len(the_points))
1826 if show_path:
1827 with plotter.iren.poked_subplot():
1828 _kwargs = kwargs.copy()
1829 plotter.add_mesh(
1830 component.picked_path,
1831 color=color,
1832 name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['path']),
1833 line_width=line_width,
1834 point_size=point_size,
1835 pickable=_kwargs.pop('pickable', False),
1836 reset_camera=_kwargs.pop('reset_camera', False),
1837 **_kwargs,
1838 )
1839 if callable(callback):
1840 _poked_context_callback(plotter, callback, component.picked_path)
1841
1842 def _clear_path_event_watcher():
1843 component = self_()
1844 if component is None:
1845 return
1846 plotter = component._plotter
1847 del the_points[:]
1848 with plotter.iren.poked_subplot():
1849 component._clear_picking_representations()
1850
1851 self._plotter.add_key_event('c', _clear_path_event_watcher)
1852 if show_message is True:
1853 show_message = 'Press P to pick under the mouse\nPress C to clear'
1854
1855 self.enable_surface_point_picking(
1856 callback=_the_callback,
1857 use_picker=True,
1858 font_size=font_size,
1859 show_message=show_message,
1860 show_point=False,
1861 tolerance=tolerance,
1862 clear_on_no_selection=False,
1863 )
1864
1865 @_deprecate_positional_args(allowed=['callback'])
1866 def enable_geodesic_picking( # noqa: PLR0917
1867 self,
1868 callback=None,
1869 show_message=True, # noqa: FBT002
1870 font_size=18,
1871 color='pink',
1872 point_size=10,
1873 line_width=5,
1874 tolerance=0.025,
1875 show_path=True, # noqa: FBT002
1876 keep_order=True, # noqa: FBT002
1877 **kwargs,
1878 ):
1879 """Enable picking at geodesic paths.
1880
1881 This is a convenience method for ``enable_point_picking`` to
1882 keep track of the picked points and create a geodesic path
1883 using those points.
1884
1885 The geodesic path is saved to the ``.picked_geodesic``
1886 attribute of this plotter.
1887
1888 Parameters
1889 ----------
1890 callback : callable, optional
1891 When given, calls this callable after a pick is made. The
1892 entire picked, geodesic path is passed as the only
1893 parameter to this callable.
1894
1895 show_message : bool | str, default: True
1896 Show the message about how to use the point picking
1897 tool. If this is a string, that will be the message shown.
1898
1899 font_size : int, default: 18
1900 Sets the size of the message.
1901
1902 color : ColorLike, default: "pink"
1903 The color of the selected mesh when shown.
1904
1905 point_size : int, default: 10
1906 Size of picked points if ``show_path`` is ``True``.
1907
1908 line_width : float, default: 5.0
1909 Thickness of path representation if ``show_path`` is
1910 ``True``.
1911
1912 tolerance : float, default: 0.025
1913 Specify tolerance for performing pick operation. Tolerance
1914 is specified as fraction of rendering window
1915 size. Rendering window size is measured across diagonal.
1916
1917 show_path : bool, default: True
1918 Show the picked path interactively.
1919
1920 keep_order : bool, default: True
1921 If ``True``, the created geodesic path is a single ordered
1922 and cleaned line from the first point to the last.
1923
1924 .. note::
1925
1926 In older versions there were apparent discontinuities
1927 in the resulting path due to the behavior of the
1928 underlying VTK filter which corresponds to
1929 ``keep_order=False``.
1930
1931 .. versionadded:: 0.32.0
1932
1933 **kwargs : dict, optional
1934 All remaining keyword arguments are used to control how
1935 the picked path is interactively displayed.
1936
1937
1938 """
1939 self_ = weakref.ref(self)
1940
1941 kwargs.setdefault('pickable', False)
1942
1943 self.picked_geodesic = pv.PolyData()
1944
1945 def _the_callback(picked_point, picker):
1946 component = self_()
1947 if component is None:
1948 return
1949 plotter = component._plotter
1950 if picker.GetDataSet() is None:
1951 return
1952 mesh = pv.wrap(picker.GetDataSet())
1953 idx = mesh.find_closest_point(picked_point)
1954 point = mesh.points[idx]
1955 if component._last_picked_idx is None:
1956 component.picked_geodesic = pv.PolyData(point)
1957 component.picked_geodesic['vtkOriginalPointIds'] = [idx]
1958 else:
1959 surface = mesh.extract_surface(algorithm=None).triangulate()
1960 locator = _vtk.vtkPointLocator()
1961 locator.SetDataSet(surface)
1962 locator.BuildLocator()
1963 start_idx = locator.FindClosestPoint(mesh.points[component._last_picked_idx])
1964 end_idx = locator.FindClosestPoint(point)
1965 component.picked_geodesic += surface.geodesic(
1966 start_idx, end_idx, keep_order=keep_order
1967 )
1968 if keep_order:
1969 component.picked_geodesic.clean(
1970 inplace=True,
1971 lines_to_points=False,
1972 polys_to_lines=False,
1973 strips_to_polys=False,
1974 )
1975 component._last_picked_idx = idx
1976
1977 if show_path:
1978 with plotter.iren.poked_subplot():
1979 _kwargs = kwargs.copy()
1980 plotter.add_mesh(
1981 component.picked_geodesic,
1982 color=color,
1983 name=_kwargs.pop('name', PICKED_REPRESENTATION_NAMES['path']),
1984 line_width=line_width,
1985 point_size=point_size,
1986 pickable=_kwargs.pop('pickable', False),
1987 reset_camera=_kwargs.pop('reset_camera', False),
1988 **_kwargs,
1989 )
1990 if callable(callback):
1991 _poked_context_callback(plotter, callback, component.picked_geodesic)
1992
1993 def _clear_g_path_event_watcher():
1994 component = self_()
1995 if component is None:
1996 return
1997 plotter = component._plotter
1998 component.picked_geodesic = pv.PolyData()
1999 with plotter.iren.poked_subplot():
2000 component._clear_picking_representations()
2001 component._last_picked_idx = None
2002
2003 self._plotter.add_key_event('c', _clear_g_path_event_watcher)
2004 if show_message is True:
2005 show_message = 'Press P to pick under the mouse\nPress C to clear'
2006
2007 self.enable_surface_point_picking(
2008 callback=_the_callback,
2009 use_picker=True,
2010 font_size=font_size,
2011 show_message=show_message,
2012 tolerance=tolerance,
2013 show_point=False,
2014 clear_on_no_selection=False,
2015 )
2016
2017 @_deprecate_positional_args(allowed=['callback'])
2018 def enable_horizon_picking( # noqa: PLR0917
2019 self,
2020 callback=None,
2021 normal=(0.0, 0.0, 1.0),
2022 width=None,
2023 show_message=True, # noqa: FBT002
2024 font_size=18,
2025 color='pink',
2026 point_size=10,
2027 line_width=5,
2028 show_path=True, # noqa: FBT002
2029 opacity=0.75,
2030 show_horizon=True, # noqa: FBT002
2031 **kwargs,
2032 ):
2033 """Enable horizon picking.
2034
2035 Helper for the ``enable_path_picking`` method to also show a
2036 ribbon surface along the picked path. Ribbon is saved under
2037 ``.picked_horizon``.
2038
2039 Parameters
2040 ----------
2041 callback : callable, optional
2042 When given, calls this callable after a pick is made. The
2043 entire picked path is passed as the only parameter to this
2044 callable.
2045
2046 normal : sequence[float], default: (0.0, 0.0, 1.0)
2047 The normal to the horizon surface's projection plane.
2048
2049 width : float, optional
2050 The width of the horizon surface. Default behaviour will
2051 dynamically change the surface width depending on its
2052 length.
2053
2054 show_message : bool | str, default: True
2055 Show the message about how to use the horizon picking
2056 tool. If this is a string, that will be the message shown.
2057
2058 font_size : int, default: 18
2059 Sets the font size of the message.
2060
2061 color : ColorLike, default: "pink"
2062 The color of the horizon surface if shown.
2063
2064 point_size : int, default: 10
2065 Size of picked points if ``show_horizon`` is ``True``.
2066
2067 line_width : float, default: 5.0
2068 Thickness of path representation if ``show_horizon`` is
2069 ``True``.
2070
2071 show_path : bool, default: True
2072 Show the picked path that the horizon is built from
2073 interactively.
2074
2075 opacity : float, default: 0.75
2076 The opacity of the horizon surface if shown.
2077
2078 show_horizon : bool, default: True
2079 Show the picked horizon surface interactively.
2080
2081 **kwargs : dict, optional
2082 All remaining keyword arguments are used to control how
2083 the picked path is interactively displayed.
2084
2085
2086 """
2087 self_ = weakref.ref(self)
2088
2089 def _clear_horizon_event_watcher():
2090 component = self_()
2091 if component is None:
2092 return
2093 plotter = component._plotter
2094 component.picked_horizon = pv.PolyData()
2095 with plotter.iren.poked_subplot():
2096 component._clear_picking_representations()
2097
2098 self._plotter.add_key_event('c', _clear_horizon_event_watcher)
2099
2100 def _the_callback(path):
2101 component = self_()
2102 if component is None:
2103 return
2104 plotter = component._plotter
2105 if path.n_points < 2:
2106 _clear_horizon_event_watcher()
2107 return
2108 component.picked_horizon = path.ribbon(normal=normal, width=width)
2109
2110 if show_horizon:
2111 with plotter.iren.poked_subplot():
2112 _kwargs = kwargs.copy()
2113 plotter.add_mesh(
2114 component.picked_horizon,
2115 name=_kwargs.get('name', PICKED_REPRESENTATION_NAMES['horizon']),
2116 color=color,
2117 opacity=opacity,
2118 pickable=_kwargs.pop('pickable', False),
2119 reset_camera=_kwargs.pop('reset_camera', False),
2120 **_kwargs,
2121 )
2122
2123 if callable(callback):
2124 _poked_context_callback(plotter, callback, path)
2125
2126 self.enable_path_picking(
2127 callback=_the_callback,
2128 show_message=show_message,
2129 font_size=font_size,
2130 color=color,
2131 point_size=point_size,
2132 line_width=line_width,
2133 show_path=show_path,
2134 **kwargs,
2135 )