Debian Codegraph @

examples/02-plot/composite_picking.py

raw
1 """
2 .. _composite_picking_example:
3
4 Composite Picking
5 ~~~~~~~~~~~~~~~~~
6
7 Demonstrate how to pick individual blocks of a :class:`pyvista.MultiBlock`
8 using :func:`pyvista.Plotter.enable_block_picking`.
9
10 """
11
12 import numpy as np
13 import pyvista as pv
14
15 # %%
16 # Create a MultiBlock Dataset
17 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~
18 # Create 100 superellipsoids using :func:`pyvista.ParametricSuperEllipsoid`
19
20 # Seed rng for reproducibility
21 rng = np.random.default_rng(seed=0)
22
23
24 def make_poly():
25 """Create a superellipsoid in a random location."""
26 poly = pv.ParametricSuperEllipsoid(
27 n1=rng.random(),
28 n2=rng.random() * 2,
29 u_res=50,
30 v_res=50,
31 )
32 poly.points += rng.random(3) * 20
33 return poly
34
35
36 # Assemble the multiblock and plot it using the default plotting settings
37 blocks = pv.MultiBlock([make_poly() for _ in range(100)])
38 blocks.plot()
39
40 # %%
41 # Enable Block Picking
42 # ~~~~~~~~~~~~~~~~~~~~
43 # Add ``blocks`` to a :class:`pyvista.Plotter` and enable block picking. For
44 # fun, let's also enable physically based rendering and set the callback to set
45 # the block color to red when the block is clicked and unset the color if the
46 # color has already been set for the block.
47
48 # sphinx_gallery_start_ignore
49 # physically based rendering does not work in interactive mode
50 PYVISTA_GALLERY_FORCE_STATIC = True
51 # sphinx_gallery_end_ignore
52
53 pl = pv.Plotter()
54 actor, mapper = pl.add_composite(blocks, color='w', pbr=True, metallic=True)
55
56
57 def callback(index, *args): # noqa: ARG001
58 """Change a block to red if color is unset, and back to the actor color if set."""
59 if mapper.block_attr[index].color is None:
60 mapper.block_attr[index].color = 'r'
61 else:
62 mapper.block_attr[index].color = None
63
64
65 pl.enable_block_picking(callback, side='left')
66 pl.background_color = 'w'
67 pl.show()
68 # %%
69 # .. tags:: plot