Mesh click eventsΒΆ
Click on meshes to select them. The index of the last clicked mesh is displayed in the GUI.
1import time
2
3import matplotlib
4
5import viser
6
7
8def main() -> None:
9 grid_shape = (4, 5)
10 server = viser.ViserServer()
11
12 with server.gui.add_folder("Last clicked"):
13 x_value = server.gui.add_number(
14 label="x",
15 initial_value=0,
16 disabled=True,
17 hint="x coordinate of the last clicked mesh",
18 )
19 y_value = server.gui.add_number(
20 label="y",
21 initial_value=0,
22 disabled=True,
23 hint="y coordinate of the last clicked mesh",
24 )
25
26 def add_swappable_mesh(i: int, j: int) -> None:
27 """Simple callback that swaps between:
28 - a gray box
29 - a colored box
30 - a colored sphere
31
32 Color is chosen based on the position (i, j) of the mesh in the grid.
33 """
34
35 colormap = matplotlib.colormaps["tab20"]
36
37 def create_mesh(counter: int) -> None:
38 if counter == 0:
39 color = (0.8, 0.8, 0.8)
40 else:
41 index = (i * grid_shape[1] + j) / (grid_shape[0] * grid_shape[1])
42 color = colormap(index)[:3]
43
44 if counter in (0, 1):
45 handle = server.scene.add_box(
46 name=f"/sphere_{i}_{j}",
47 position=(i, j, 0.0),
48 color=color,
49 dimensions=(0.5, 0.5, 0.5),
50 )
51 else:
52 handle = server.scene.add_icosphere(
53 name=f"/sphere_{i}_{j}",
54 radius=0.4,
55 color=color,
56 position=(i, j, 0.0),
57 )
58
59 @handle.on_click
60 def _(_) -> None:
61 x_value.value = i
62 y_value.value = j
63
64 # The new mesh will replace the old one because the names
65 # /sphere_{i}_{j} are the same.
66 create_mesh((counter + 1) % 3)
67
68 create_mesh(0)
69
70 for i in range(grid_shape[0]):
71 for j in range(grid_shape[1]):
72 add_swappable_mesh(i, j)
73
74 while True:
75 time.sleep(10.0)
76
77
78if __name__ == "__main__":
79 main()