-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy path_engine.py
More file actions
390 lines (305 loc) · 13 KB
/
_engine.py
File metadata and controls
390 lines (305 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
from functools import partial
import numpy as np
import pygfx
from ._subplot import Subplot
from ._rect import RectManager
class ScreenSpaceCamera(pygfx.Camera):
"""
Same as pygfx.ScreenCoordsCamera but y-axis is inverted.
So top left corner is (0, 0). This is easier to manage because we
often resize using the bottom right corner.
"""
def _update_projection_matrix(self):
width, height = self._view_size
sx, sy, sz = 2 / width, 2 / height, 1
dx, dy, dz = -1, 1, 0 # pygfx is -1, -1, 0
m = sx, 0, 0, dx, 0, sy, 0, dy, 0, 0, sz, dz, 0, 0, 0, 1
proj_matrix = np.array(m, dtype=float).reshape(4, 4)
proj_matrix.flags.writeable = False
return proj_matrix
class BaseLayout:
def __init__(
self,
renderer: pygfx.WgpuRenderer,
subplots: np.ndarray[Subplot],
canvas_rect: tuple[float, float],
moveable: bool,
resizeable: bool,
):
"""
Base layout engine, subclass to create a usable layout engine.
"""
self._renderer = renderer
self._subplots: np.ndarray[Subplot] = subplots.ravel()
self._canvas_rect = canvas_rect
self._last_pointer_pos: np.ndarray[np.float64, np.float64] = np.array(
[np.nan, np.nan]
)
# the current user action, move or resize
self._active_action: str | None = None
# subplot that is currently in action, i.e. currently being moved or resized
self._active_subplot: Subplot | None = None
# subplot that is in focus, i.e. being hovered by the pointer
self._subplot_focus: Subplot | None = None
for subplot in self._subplots:
# highlight plane when pointer enters it
subplot.frame.plane.add_event_handler(
partial(self._highlight_plane, subplot), "pointer_enter"
)
if resizeable:
# highlight/unhighlight resize handler when pointer enters/leaves
subplot.frame.resize_handle.add_event_handler(
partial(self._highlight_resize_handler, subplot), "pointer_enter"
)
subplot.frame.resize_handle.add_event_handler(
partial(self._unhighlight_resize_handler, subplot), "pointer_leave"
)
def _inside_render_rect(self, subplot: Subplot, pos: tuple[int, int]) -> bool:
"""whether the pos is within the render area, used for filtering out pointer events"""
rect = subplot.frame.get_render_rect()
x0, y0 = rect[:2]
x1 = x0 + rect[2]
y1 = y0 + rect[3]
if (x0 < pos[0] < x1) and (y0 < pos[1] < y1):
return True
return False
def canvas_resized(self, canvas_rect: tuple):
"""
called by figure when canvas is resized
Parameters
----------
canvas_rect: (x, y, w, h)
the rect that pygfx can render to, excludes any areas used by imgui.
"""
self._canvas_rect = canvas_rect
for subplot in self._subplots:
subplot.frame.canvas_resized(canvas_rect)
def _highlight_resize_handler(self, subplot: Subplot, ev):
if self._active_action == "resize":
return
ev.target.material.color = subplot.frame.resize_handle_color.highlight
def _unhighlight_resize_handler(self, subplot: Subplot, ev):
if self._active_action == "resize":
return
ev.target.material.color = subplot.frame.resize_handle_color.idle
def _highlight_plane(self, subplot: Subplot, ev):
if self._active_action is not None:
return
# reset color of previous focus
if self._subplot_focus is not None:
self._subplot_focus.frame.plane.material.color = (
subplot.frame.plane_color.idle
)
self._subplot_focus = subplot
ev.target.material.color = subplot.frame.plane_color.highlight
def __len__(self):
return len(self._subplots)
class WindowLayout(BaseLayout):
def __init__(
self,
renderer,
subplots: np.ndarray[Subplot],
canvas_rect: tuple,
moveable=True,
resizeable=True,
):
"""
Flexible layout engine that allows freely moving and resizing subplots.
Subplots are not allowed to overlap.
We use a screenspace camera to perform an underlay render pass to draw the
subplot frames, there is no depth rendering so we do not allow overlaps.
"""
super().__init__(renderer, subplots, canvas_rect, moveable, resizeable)
self._last_pointer_pos: np.ndarray[np.float64, np.float64] = np.array(
[np.nan, np.nan]
)
for subplot in self._subplots:
if moveable:
# start a move action
subplot.frame.plane.add_event_handler(
partial(self._action_start, subplot, "move"), "pointer_down"
)
# start a resize action
subplot.frame.resize_handle.add_event_handler(
partial(self._action_start, subplot, "resize"), "pointer_down"
)
if moveable or resizeable:
# when pointer moves, do an iteration of move or resize action
self._renderer.add_event_handler(self._action_iter, "pointer_move")
# end the action when pointer button goes up
self._renderer.add_event_handler(self._action_end, "pointer_up")
def _new_extent_from_delta(self, delta: tuple[int, int]) -> np.ndarray:
delta_x, delta_y = delta
if self._active_action == "resize":
# subtract only from x1, y1
new_extent = self._active_subplot.frame.extent - np.asarray(
[0, delta_x, 0, delta_y]
)
else:
# moving
new_extent = self._active_subplot.frame.extent - np.asarray(
[delta_x, delta_x, delta_y, delta_y]
)
x0, x1, y0, y1 = new_extent
w = x1 - x0
h = y1 - y0
# make sure width and height are valid
# min width, height is 50px
if w <= 50: # width > 0
new_extent[:2] = self._active_subplot.frame.extent[:2]
if h <= 50: # height > 0
new_extent[2:] = self._active_subplot.frame.extent[2:]
# ignore movement if this would cause an overlap
for subplot in self._subplots:
if subplot is self._active_subplot:
continue
if subplot.frame.rect_manager.overlaps(new_extent):
# we have an overlap, need to ignore one or more deltas
# ignore x
if not subplot.frame.rect_manager.is_left_of(
x0
) or not subplot.frame.rect_manager.is_right_of(x1):
new_extent[:2] = self._active_subplot.frame.extent[:2]
# ignore y
if not subplot.frame.rect_manager.is_above(
y0
) or not subplot.frame.rect_manager.is_below(y1):
new_extent[2:] = self._active_subplot.frame.extent[2:]
# make sure all vals are non-negative
if (new_extent[:2] < 0).any():
# ignore delta_x
new_extent[:2] = self._active_subplot.frame.extent[:2]
if (new_extent[2:] < 0).any():
# ignore delta_y
new_extent[2:] = self._active_subplot.frame.extent[2:]
# canvas extent
cx0, cy0, cw, ch = self._canvas_rect
# check if new x-range is beyond canvas x-max
if (new_extent[:2] > cx0 + cw).any():
new_extent[:2] = self._active_subplot.frame.extent[:2]
# check if new y-range is beyond canvas y-max
if (new_extent[2:] > cy0 + ch).any():
new_extent[2:] = self._active_subplot.frame.extent[2:]
return new_extent
def _action_start(self, subplot: Subplot, action: str, ev):
if self._inside_render_rect(subplot, pos=(ev.x, ev.y)):
return
if ev.button == 1: # left mouse button
self._active_action = action
if action == "resize":
subplot.frame.resize_handle.material.color = (
subplot.frame.resize_handle_color.action
)
elif action == "move":
subplot.frame.plane.material.color = subplot.frame.plane_color.action
else:
raise ValueError
self._active_subplot = subplot
self._last_pointer_pos[:] = ev.x, ev.y
def _action_iter(self, ev):
if self._active_action is None:
return
delta_x, delta_y = self._last_pointer_pos - (ev.x, ev.y)
new_extent = self._new_extent_from_delta((delta_x, delta_y))
self._active_subplot.frame.extent = new_extent
self._last_pointer_pos[:] = ev.x, ev.y
def _action_end(self, ev):
self._active_action = None
if self._active_subplot is not None:
self._active_subplot.frame.resize_handle.material.color = (
self._active_subplot.frame.resize_handle_color.idle
)
self._active_subplot.frame.plane.material.color = (
self._active_subplot.frame.plane_color.idle
)
self._active_subplot = None
self._last_pointer_pos[:] = np.nan
def set_rect(self, subplot: Subplot, rect: tuple | list | np.ndarray):
"""
Set the rect of a Subplot
Parameters
----------
subplot: Subplot
the subplot to set the rect of
rect: (x, y, w, h)
as absolute pixels or fractional.
If width & height <= 1 the rect is assumed to be fractional.
Conversely, if width & height > 1 the rect is assumed to be in absolute pixels.
width & height must be > 0. Negative values are not allowed.
"""
new_rect = RectManager(*rect, self._canvas_rect)
extent = new_rect.extent
# check for overlaps
for s in self._subplots:
if s is subplot:
continue
if s.frame.rect_manager.overlaps(extent):
raise ValueError(f"Given rect: {rect} overlaps with another subplot.")
def set_extent(self, subplot: Subplot, extent: tuple | list | np.ndarray):
"""
Set the extent of a Subplot
Parameters
----------
subplot: Subplot
the subplot to set the extent of
extent: (xmin, xmax, ymin, ymax)
as absolute pixels or fractional.
If xmax & ymax <= 1 the extent is assumed to be fractional.
Conversely, if xmax & ymax > 1 the extent is assumed to be in absolute pixels.
Negative values are not allowed. xmax - xmin & ymax - ymin must be > 0.
"""
new_rect = RectManager.from_extent(extent, self._canvas_rect)
extent = new_rect.extent
# check for overlaps
for s in self._subplots:
if s is subplot:
continue
if s.frame.rect_manager.overlaps(extent):
raise ValueError(
f"Given extent: {extent} overlaps with another subplot."
)
class GridLayout(WindowLayout):
def __init__(
self,
renderer,
subplots: np.ndarray[Subplot],
canvas_rect: tuple[float, float, float, float],
shape: tuple[int, int],
):
"""
Grid layout engine that auto-sets Frame and Subplot rects such that they maintain
a fixed grid layout. Does not allow freely moving or resizing subplots.
"""
super().__init__(
renderer, subplots, canvas_rect, moveable=False, resizeable=False
)
# {Subplot: (row_ix, col_ix)}, dict mapping subplots to their row and col index in the grid layout
self._subplot_grid_position: dict[Subplot, tuple[int, int]]
self._shape = shape
@property
def shape(self) -> tuple[int, int]:
return self._shape
def set_rect(self, subplot, rect: np.ndarray | list | tuple):
raise NotImplementedError(
"set_rect() not implemented for GridLayout which is an auto layout manager"
)
def set_extent(self, subplot, extent: np.ndarray | list | tuple):
raise NotImplementedError(
"set_extent() not implemented for GridLayout which is an auto layout manager"
)
def add_row(self):
raise NotImplementedError("Not yet implemented")
def add_column(self):
raise NotImplementedError("Not yet implemented")
def remove_row(self):
raise NotImplementedError("Not yet implemented")
def remove_column(self):
raise NotImplementedError("Not yet implemented")
def add_subplot(self):
raise NotImplementedError(
"Not implemented for GridLayout which is an auto layout manager"
)
def remove_subplot(self, subplot):
raise NotImplementedError(
"Not implemented for GridLayout which is an auto layout manager"
)