-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·1453 lines (1239 loc) · 51.4 KB
/
main.py
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Using flake8 for linting
import os
import wx
import sys
import copy
import json
import math
import scipy
import functools
import jsonpickle
import numpy as np
from typing import List
from copy import deepcopy
from inspect import cleandoc
from datetime import date, time
from math import sqrt, cos, sin, radians
from wx.lib.scrolledpanel import ScrolledPanel
from wx.lib.splitter import MultiSplitterWindow
# Constants that aren't likely to change:
FIELD_X_INCHES = 54*12
FIELD_Y_INCHES = 27*12
# Round off a value to the nearest quarter. Handy since we're dealing with
# inches and this can be used when we calculate the field position that
# corresponds to a mouse click on the sceen.
def qtr_round(x):
return round(x*4)/4
def get_scale_matrix():
global glb_field_render
# 0,0 goes from being the middle of the field to the
# top left and we scale for screen resolution at the same time
if glb_field_render is not None:
ximg, yimg = glb_field_render.field_bmp.GetSize()
else: # Really not sure how to handle this yet.
ximg = 1280
yimg = 600
# Used to convert inches to pixels
xscale = ximg / FIELD_X_INCHES
yscale = yimg / FIELD_Y_INCHES
M = [
[xscale, 0],
[0, yscale]
]
return np.array(M)
# Returns a matrix and vector that can be used to transform a point from
# our field coordinates where 0,0 is the center of the field to screen where
# 0,0 is the upper left corner. The vector handles the offset of the field
# and the scaling matrix is used to size it properly for the screen.
def get_transform_center_basis_to_screen():
v = [(FIELD_X_INCHES/2), (FIELD_Y_INCHES/2)]
return get_scale_matrix(), np.array(v)
def _current_waypoints():
return _app_state[ROUTINES][_app_state[CURRENT_ROUTINE]].waypoints
# Define a type that can hold a waypoint's data.
class Waypoint():
x: float = 0.0
y: float = 0.0
v: float = 0.0
heading: float = 0.0
def __init__(self, x, y, v, heading):
self.x = x
self.y = y
self.v = v
self.heading = heading
def __str__(self):
return json.dumps(dict(self), ensure_ascii=False)
def __repr__(self):
return self.__str__()
# Container class for a step in an overall transformation. Most transformations
# will be one step but sometimes we'll mirror over X then Y, so, the
# Transformation class will hold a list of these.
class TransformationStep():
descr: str = ''
matrix = []
vector = []
def __init__(self, descr: str, matrix, vector):
self.descr = descr
self.matrix = matrix
self.vector = vector
def __str__(self):
return json.dumps(dict(self), ensure_ascii=False)
def __repr__(self):
return self.__str__()
# Container class for holding a transformation. This is a path based on
# our primary one but mirrored or rotated around a center point on the field.
# Using ChargedUp as an example if your main was "Red Right" or 'RR'
# then starting from Red Left might be named RL, Blue Right would be BR, and
# Blue Left BL.
class Transformation():
steps: List[TransformationStep] = []
def __init__(self):
self.steps = []
def __str__(self):
return json.dumps(dict(self), ensure_ascii=False)
def __repr__(self):
return self.__str__()
# Container for what will be selected eventually on the dashboard before
# running an auton. It allows us to name a routine (like 'Pick one piece' or
# 'leave community')
class Routine():
name: str = ''
waypoints: List[Waypoint] = []
active_transformations: List[str] = []
def __str__(self):
return json.dumps(dict(self), ensure_ascii=False)
def __repr__(self):
return self.__str__()
# Very routine matrices for mirroring over X or Y axis
MIRROR_X_MATRIX = [[-1, 0],
[ 0, 1]] # noqa
MIRROR_Y_MATRIX = [[1, 0],
[0, -1]]
# Constants for our _app_state dictionary
FIELD_BACKGROUND_IMAGE = 'field_background_img'
FIELD_X_OFFSET = 'field_x_offset'
FIELD_Y_OFFSET = 'field_y_offset'
WAYPOINT_DISTANCE_LIMIT = 'waypoint_select_distance_limit'
CROSSHAIR_LENGTH = 'crosshair_length'
CROSSHAIR_THICKNESS = 'crosshair_thickness'
ROUTINES = 'routines'
TFMS = 'transformations'
CURRENT_ROUTINE = 'current_routine'
def get_default_app_state():
initial_route_name = 'New Routine'
state = {
FIELD_BACKGROUND_IMAGE: 'field_reefscape.png',
FIELD_X_OFFSET: 0,
FIELD_Y_OFFSET: 52,
WAYPOINT_DISTANCE_LIMIT: 15,
CROSSHAIR_LENGTH: 50,
CROSSHAIR_THICKNESS: 10,
ROUTINES: {},
CURRENT_ROUTINE: initial_route_name,
TFMS: {},
}
r = Routine()
r.name = initial_route_name
r.active_transformations = ['RL', 'BR', 'BL']
state[ROUTINES][initial_route_name] = r
state[TFMS] = {
'RL': Transformation(),
'BR': Transformation(),
'BL': Transformation(),
}
state[TFMS]['BL'].steps = [
TransformationStep('Mirror Y', MIRROR_Y_MATRIX, None),
]
state[TFMS]['RL'].steps = [
TransformationStep('Mirror X', MIRROR_X_MATRIX, None)
]
state[TFMS]['BR'].steps = [
TransformationStep('Mirror X', MIRROR_X_MATRIX, None),
TransformationStep('Mirror Y', MIRROR_Y_MATRIX, None),
]
return state
# This function is used a function decorator:
# https://dbader.org/blog/python-decorators
# What this meeans is when you place '@modifies_state' above a function
# this function will run, but inside the 'wrapper' method we will call
# the method that you've placed the decorator above. This allows us to
# do some work before and after the function you've decorated runs.
# In this case we are storing the app state to disk after the function
# runs.
def modifies_state(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
store_app_state()
return wrapper
# Read the application state off disk and return it.
# We use the 'jsonpickle' library because it keeps the type information
def get_app_state():
try:
with open('app_state.json', 'r') as f:
obj = jsonpickle.decode(f.read())
except json.decoder.JSONDecodeError:
obj = None
except FileNotFoundError:
obj = None
return obj
# Write the application state to disk.
# We use the 'jsonpickle' library because it keeps the type information
def store_app_state():
json_str = jsonpickle.encode(_app_state)
with open('app_state.json', 'w') as f:
f.write(json_str)
# With the pyinstaller package we need to use this function to get the
# path to our resources (images). This is because when we package the app up
# with pyinstaller it creates a temporary directory with all of our
# resources in it. This function will return the path to that directory
# when we are running in a packaged state and the path to the current
# directory when we are running in a development state.
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def serialize(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, date):
serial = obj.isoformat()
return serial
if isinstance(obj, time):
serial = obj.isoformat()
return serial
return obj.__dict__
# Helper function to 'pretty' print a Python object in JSON
# format.
def pp(obj):
print(json.dumps(obj, sort_keys=True, indent=4,
default=serialize))
# We can use Heron's formula to find the height of a triangle given
# the lengths of the sides.
# This used to detect when we click between two existing points.
def triangle_height(way1, way2, way3):
a = math.dist([way2.x, way2.y], [way3.x, way3.y])
b = math.dist([way1.x, way1.y], [way2.x, way2.y])
c = math.dist([way3.x, way3.y], [way1.x, way1.y])
s = (a + b + c) / 2
A = sqrt(s * (s - a) * (s - b) * (s - c))
h = 2*A / b
return h
def totuple(a):
try:
return tuple(totuple(i) for i in a)
except TypeError:
return a
# The cache decorator remembers the return value of a function after the first
# time it is run for the given parameters. Subsequent calls don't have to
# do any computation, they just return the previously constructed value.
# This saves us a bit of a execution time but it only works if the function
# will always return exactly the same thing given the same inputs
@functools.cache
def lu_factor(M):
return scipy.linalg.lu_factor(M)
@functools.cache
def get_bezier_matrix(n):
show_la = False
# Complete documentation what we're doing is here:
# https://towardsdatascience.com/b%C3%A9zier-interpolation-8033e9a262c2
# build coefficents matrix
C = 4 * np.identity(n)
if show_la:
print('Initial C')
print(C)
np.fill_diagonal(C[1:], 1)
if show_la:
print('Diag 1')
print(C)
np.fill_diagonal(C[:, 1:], 1)
if show_la:
print('Diag 2')
print(C)
C[0, 0] = 2
C[n - 1, n - 1] = 7
C[n - 1, n - 2] = 2
if show_la:
print('Constants from derivatives')
print(C)
return C
# Given a 2D matrix of points to hit this will return two
# matrices of the control points that can be used to make a smooth
# cubic Bezier curve through them all.
def get_bezier_coef(points):
# If set to True we'll ouput some of the linear algebra as we compute it
show_la = False
# matrix is n x n, one less than total points
n = len(points) - 1
C = get_bezier_matrix(n)
lu, piv = lu_factor(totuple(C))
if show_la:
print('lu')
print(lu)
print('piv')
print(piv)
# build points vector
point_vector = [2 * (2 * points[i] + points[i + 1]) for i in range(n)]
point_vector[0] = points[0] + 2 * points[1]
point_vector[n - 1] = 8 * points[n - 1] + points[n]
if show_la:
print('Point Vector')
print(point_vector)
# this is where I'm playing with different ways of deconposing our matrix
# and computing the solution different ways.
# LU decomps are a bit easier on the CPU
A = scipy.linalg.lu_solve((lu, piv), point_vector)
# simplest method, computationally expensive
# A = np.linalg.solve(C, point_vector)
B = [0] * n
for i in range(n - 1):
B[i] = 2 * points[i + 1] - A[i + 1]
B[n - 1] = (A[n - 1] + points[n]) / 2
# A contains the "control point 1" for each segment
# B contains the "control point 2" for each segment
return A, B
# Creates a rotation matrix either with a degree or radian value
# https://scipython.com/book/chapter-6-numpy/examples/creating-a-rotation-matrix-in-numpy/
def rotation_matrix(deg=None, rad=None):
if deg is None and rad is None:
raise ValueError('Must specify either degrees or radians')
if deg is not None:
theta = radians(deg)
else:
theta = rad
return np.array([[cos(theta), -sin(theta)], [sin(theta), cos(theta)]])
class FieldRenderPanel(wx.Panel):
# Node that we've actually clicked on
_selected_node = None
# Node that we're near enough to to highlight
_highlight_node = None
redraw_needed = True
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.SetBackgroundStyle(wx.BG_STYLE_PAINT)
self.Bind(wx.EVT_IDLE, self.on_idle)
self.Bind(wx.EVT_PAINT, self.on_paint)
imgname = _app_state[FIELD_BACKGROUND_IMAGE]
imgpath = resource_path(imgname)
self.field_image = wx.Image(imgpath, wx.BITMAP_TYPE_ANY)
self.field_orig_x = self.field_image.GetWidth()
self.field_orig_y = self.field_image.GetHeight()
self.field_buffer = wx.Bitmap(self.field_orig_x, self.field_orig_y)
self.field_bmp = wx.StaticBitmap(self, -1, self.field_buffer)
self.field_bmp.Bind(wx.EVT_LEFT_DOWN, self.on_field_click)
self.field_bmp.Bind(wx.EVT_RIGHT_DOWN, self.on_field_click_right)
self.field_bmp.Bind(wx.EVT_MOTION, self.on_mouse_move)
# When no actiity in the app is occuring we'll hit this method and
# if the data says we need to redraw the window we will do that. This
# will force the on_paint method to be called where the updated bitmap
# is blitted to the screen
def on_idle(self, evt):
if self.redraw_needed:
self.redraw()
self.redraw_needed = False
self.Refresh(False)
def on_paint(self, evt):
# Create a buffered paint DC. It will create the real
# wx.PaintDC and then blit the bitmap to it when dc is
# deleted. Since we don't need to draw anything else
# here that's all there is to it.
dc = wx.BufferedPaintDC(self, self.field_buffer)
del dc
def force_redraw(self):
self.redraw_needed = True
self.redraw()
self.Refresh()
# Draw all waypoints and paths on the field
def redraw(self):
field_blank = self.field_image
if self.field_bmp is not None:
imgx, imgy = self.field_bmp.GetSize()
field_blank = field_blank.Scale(imgx, imgy)
self.field_buffer = field_blank.ConvertToBitmap()
dc = wx.BufferedDC(None, self.field_buffer)
gc = wx.GraphicsContext.Create(dc)
if glb_field_panel.draw_field_center:
self._draw_field_center(dc, _app_state[CROSSHAIR_LENGTH])
M, v = get_transform_center_basis_to_screen()
field_offset_vec = np.array([_app_state[FIELD_X_OFFSET],
_app_state[FIELD_Y_OFFSET]])
cr = _app_state[ROUTINES][_app_state[CURRENT_ROUTINE]]
# We're going to iterate though the different paths we can make
# via mirroring and rotation, but the first one will use 'None'
# values to signal that we want to draw th original and transformations
# don't need to be done on it; aside from mapping field to screen
# points.
for name, path_transformation in zip(
[None] + list(_app_state[TFMS].keys()),
[None] + list(_app_state[TFMS].values())):
final_matrix = np.identity(2)
final_vector = np.array([0, 0])
# Our first pass is w/ None, so no transformation takes place
# but for the others we need to alter a matrix and vector
# that will be applied to the path.
if path_transformation is not None:
if name not in cr.active_transformations:
continue
for s in path_transformation.steps:
if s.matrix is not None:
# Multiply the matrices
final_matrix = np.array(s.matrix) @ final_matrix
elif s.vector is not None:
# Add in the translation vector
final_vector += np.array(s.vector)
else:
print('unhandled ?')
points = np.array([(w.x, w.y) for w in _current_waypoints()])
if len(points) == 0:
return
points -= field_offset_vec
points = np.array(
[final_matrix.dot([w[0], w[1]]).astype(float) for w in points]
)
points += field_offset_vec
points += final_vector
screen_points = points + v
screen_points = screen_points @ M
# Draw path
A, B = get_bezier_coef(screen_points)
firstx, firsty = screen_points[0][0], screen_points[0][1]
path = gc.CreatePath()
path.MoveToPoint(firstx, firsty)
for end, ctl1P, ctl2P in zip(screen_points[1:], A, B):
x1, y1 = ctl1P[0], ctl1P[1]
x2, y2 = ctl2P[0], ctl2P[1]
endx, endy = end[0], end[1]
ctl1 = wx.Point2D(x1, y1)
ctl2 = wx.Point2D(x2, y2)
endP = wx.Point2D(endx, endy)
if glb_field_panel.show_control_points:
dc.SetPen(wx.Pen('magenta', 4))
dc.DrawCircle(int(ctl1.x), int(ctl1.y), 2)
dc.DrawCircle(int(ctl2.x), int(ctl2.y), 2)
path.AddCurveToPoint(ctl1, ctl2, endP)
gc.SetPen(wx.Pen('red', 2))
gc.StrokePath(path)
# Draw waypoints
for idx, (sp, w) in enumerate(
zip(screen_points, _current_waypoints())
):
screenx, screeny = sp
screenx = int(screenx)
screeny = int(screeny)
if path_transformation is None:
self._draw_orig_waypoint(dc, w, screenx, screeny, idx)
else:
self._draw_waypoint(dc, screenx, screeny, idx,
'orange', 'orange')
dc.SelectObject(wx.NullBitmap)
self.field_bmp.SetBitmap(self.field_buffer)
# Internal function to draw a waypoint on the field
def _draw_waypoint(self, dc, x, y, idx, marker_fg, marker_bg):
dc.SetBrush(wx.Brush(marker_bg))
dc.SetPen(wx.Pen(marker_fg, 4))
dc.DrawCircle(x, y, 10)
dc.SetTextForeground('white')
dc.SetTextBackground('black')
font = dc.GetFont()
font.SetPointSize(14)
dc.SetFont(font)
dc.DrawText(str(idx), x, y)
# Draw an original waypoint in the proper color. These are (currently)
# the only editable ones.
def _draw_orig_waypoint(self, dc, w, screenx, screeny, idx):
bgcolor = 'black'
if self._highlight_node == w:
bgcolor = 'white'
if self._selected_node == w:
bgcolor = 'orange'
self._draw_waypoint(dc, screenx, screeny, idx, 'red', bgcolor)
# Draw a crosshairs on the field center, or what we consider center
# for all mirror and rotation operations.
def _draw_field_center(self, dc, cross_size=5):
dc.SetPen(wx.Pen('magenta', _app_state[CROSSHAIR_THICKNESS]))
xoff = _app_state[FIELD_X_OFFSET]
yoff = _app_state[FIELD_Y_OFFSET]
M, v = get_transform_center_basis_to_screen()
field_points = np.array([
[xoff-cross_size, yoff],
[xoff+cross_size, yoff],
[xoff, yoff-cross_size],
[xoff, yoff+cross_size],
]).astype(float)
field_points += np.array(v)
screen_points = np.array(field_points) @ M
screen_points = screen_points.astype(int)
sx, sy = screen_points[0]
ex, ey = screen_points[1]
dc.DrawLine(sx, sy, ex, ey)
sx, sy = screen_points[2]
ex, ey = screen_points[3]
dc.DrawLine(sx, sy, ex, ey)
# When a click on the field occurs we locate the waypoint closest to that
# click so we know which one the users wishes to operate on.
# The distance_limit threshold sets a max distance the user can be away
# from the center of a point before we disregard it.
def _find_closest_waypoint(self, x, y, distance_limit=25):
closest_distance = distance_limit + 1
closest_waypoint = None
for w in _current_waypoints():
d = math.dist([x, y], [w.x, w.y])
if d < distance_limit and d < closest_distance:
closest_distance = d
closest_waypoint = w
return closest_waypoint
# We use the right click to delete a node that's close to the click
def on_field_click_right(self, evt):
x, y = evt.GetPosition()
x, y = self._screen_to_field(x, y)
self.del_node(x, y)
def _screen_to_field(self, x, y):
M, v = get_transform_center_basis_to_screen()
Minv = np.linalg.inv(M)
field_points = np.array([[x, y]])
field_points = field_points @ (Minv)
field_points = field_points - v
fieldx = qtr_round(field_points[0][0])
fieldy = qtr_round(field_points[0][1])
return fieldx, fieldy
def _field_to_screen(self, x, y):
M, v = get_transform_center_basis_to_screen()
field_points = np.array([[x, y]])
field_points = field_points + v
field_points = field_points @ M
screenx = int(field_points[0][0])
screeny = int(field_points[0][1])
return screenx, screeny
# Clicking on the field can either select or add a node depending
# on where it happens.
def on_field_click(self, evt):
x, y = evt.GetPosition()
fieldx, fieldy = self._screen_to_field(x, y)
# print(f'Clicky hit at {x},{y}')
selnode = self._find_closest_waypoint(
fieldx, fieldy, _app_state[WAYPOINT_DISTANCE_LIMIT]
)
if selnode is None:
self.add_node(fieldx, fieldy)
else:
self.sel_node(fieldx, fieldy)
# Adds a new waypoint
@modifies_state
def add_node(self, fieldx, fieldy):
global _app_state
# Defaulting velocity and headings for now.
new_waypoint = Waypoint(x=fieldx, y=fieldy, v=10, heading=0)
# Check to see if we need to insert it between two
# Poor implementation for now
waypoints = _current_waypoints()
if len(waypoints) >= 2:
# Find two nodes that makes the shortest triangle
shortest_combo = (None, None)
shortest_height = 100000
for w1 in waypoints:
for w2 in waypoints:
if w1 == w2:
continue
w1_idx = waypoints.index(w1)
w2_idx = waypoints.index(w2)
if abs(w1_idx - w2_idx) > 1:
continue
h = triangle_height(w1, w2, new_waypoint)
if h < shortest_height:
shortest_height = h
shortest_combo = (w1, w2)
# print('Shortest height', shortest_height)
# print('Shortest combo', shortest_combo)
print(waypoints.index(shortest_combo[0]),
waypoints.index(shortest_combo[1]))
if shortest_height < 4:
idx = max(waypoints.index(shortest_combo[0]),
waypoints.index(shortest_combo[1]))
waypoints.insert(idx, new_waypoint)
else:
waypoints.append(new_waypoint)
else:
waypoints.append(new_waypoint)
_app_state[ROUTINES][_app_state[CURRENT_ROUTINE]].waypoints = waypoints
self._selected_node = new_waypoint
glb_waypoint_panel.update_waypoint_grid()
self.force_redraw()
# Delete the closest waypoint to the click
# Or if we're not on a waypoint add one here between
# the start and end points of this spline
@modifies_state
def del_node(self, x, y):
global _app_state
self._selected_node = None
delnode = self._find_closest_waypoint(x, y)
current_routine = _app_state[ROUTINES][_app_state[CURRENT_ROUTINE]]
if delnode is not None:
current_routine.waypoints.remove(delnode)
self.force_redraw()
glb_waypoint_panel.update_waypoint_grid()
# select the closest waypoint to the click for modification
# via the controls in the control panel UI
def sel_node(self, x, y):
selnode = self._find_closest_waypoint(x, y)
if selnode is not None:
self._selected_node = selnode
self.force_redraw()
# Event fires any time the mouse moves on the field drawing
@modifies_state
def on_mouse_move(self, event):
x, y = event.GetPosition()
fieldx, fieldy = self._screen_to_field(x, y)
# print(f'x: {x}, y: {y} fieldx: {fieldx}, fieldy: {fieldy}')
# If we're not dragging an object/waypoint then we're just going to
# see if the mouse is near a node. If so, we'll highlight it to
# indicate that if the user left clicks it will be selected.
if not event.Dragging():
event.Skip()
last_highlight = self._highlight_node
self._highlight_node = self._find_closest_waypoint(fieldx, fieldy)
# We only wan to redraw the grid if we actually changed the
# highlight node
if last_highlight != self._highlight_node:
self.force_redraw()
return
event.Skip()
# print("Dragging position", x, y)
# If we're in a drag motion and have a seleted node we need to
# update its coordinates to the mouse position and redraw everything.
if self._selected_node is not None:
self._selected_node.x = fieldx
self._selected_node.y = fieldy
waypoints = (
_app_state[ROUTINES][_app_state[CURRENT_ROUTINE]].waypoints
)
idx = waypoints.index(self._selected_node)
waypoints[idx].x = fieldx
waypoints[idx].y = fieldy
glb_waypoint_panel.update_waypoint_data()
self.force_redraw()
# A wx Panel that holds the Field drawing portion of the UI
class FieldPanel(wx.Panel):
def __init__(self, parent):
self.show_control_points = False
self.draw_field_center = True
wx.Panel.__init__(self, parent=parent)
# Load in the field image
# Here any click that happens inside the field area will trigger the
# on_field_click function which handles the event.
# Establish controls for modifying the field properties
# Much like the buttons we create labels and text editing boxes
field_offset_x_lbl = wx.StaticText(self, label='Field Offset X')
self.field_offset_x_txt = wx.TextCtrl(self)
self.field_offset_x_txt.ChangeValue(str(_app_state[FIELD_X_OFFSET]))
field_offset_y_lbl = wx.StaticText(self, label='Field Offset Y')
self.field_offset_y_txt = wx.TextCtrl(self)
self.field_offset_y_txt.ChangeValue(str(_app_state[FIELD_Y_OFFSET]))
draw_field_center_btn = wx.CheckBox(self,
label='Draw Field Center')
show_control_points_btn = wx.CheckBox(self,
label='Show Control Points')
show_control_points_btn.SetValue(self.show_control_points)
draw_field_center_btn.SetValue(self.draw_field_center)
self.field_offset_x_txt.Bind(wx.EVT_TEXT, self.on_field_offset_change)
self.field_offset_y_txt.Bind(wx.EVT_TEXT, self.on_field_offset_change)
draw_field_center_btn.Bind(wx.EVT_CHECKBOX,
self.toggle_draw_field_center)
show_control_points_btn.Bind(wx.EVT_CHECKBOX,
self.toggle_control_points)
# The BoxSizer is a layout manager that arranges the controls in a box
# which can be made vertical or horizontal.
vbox = wx.BoxSizer(wx.VERTICAL)
border = 5
hbox = wx.BoxSizer(wx.HORIZONTAL)
xbox = wx.BoxSizer(wx.VERTICAL)
xbox.Add(field_offset_x_lbl, 0, wx.EXPAND | wx.ALL, border=border)
xbox.Add(self.field_offset_x_txt, 0, wx.EXPAND | wx.ALL, border=border)
ybox = wx.BoxSizer(wx.VERTICAL)
ybox.Add(field_offset_y_lbl, 0, wx.EXPAND | wx.ALL, border=border)
ybox.Add(self.field_offset_y_txt, 0, wx.EXPAND | wx.ALL, border=border)
zbox = wx.BoxSizer(wx.VERTICAL)
zbox.Add(draw_field_center_btn, 0, wx.EXPAND | wx.ALL, border=border)
zbox.Add(show_control_points_btn, 0, wx.EXPAND | wx.ALL, border=border)
hbox.Add(xbox)
hbox.Add(ybox)
hbox.Add(zbox)
vbox.Add(hbox)
self.SetSizer(vbox)
self.Fit()
self.Refresh()
def toggle_control_points(self, evt):
self.show_control_points = not self.show_control_points
glb_field_render.force_redraw()
def toggle_draw_field_center(self, evt):
self.draw_field_center = not self.draw_field_center
glb_field_render.force_redraw()
@modifies_state
def on_field_offset_change(self, evt):
print('offset change')
global _app_state
try:
_app_state[FIELD_X_OFFSET] = float(
self.field_offset_x_txt.GetValue()
)
except ValueError:
pass
try:
_app_state[FIELD_Y_OFFSET] = float(
self.field_offset_y_txt.GetValue()
)
except ValueError:
pass
glb_field_render.force_redraw()
class RoutinePanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.routine_grid = None
self.update_routine_grid()
def update_routine_grid(self):
if self.routine_grid is not None:
self.routine_grid.Clear(True)
else:
self.routine_grid = wx.StaticBoxSizer(
wx.VERTICAL, self, 'Routines'
)
self.routine_new_btn = wx.Button(self, label='+ Blank')
self.routine_clone_btn = wx.Button(self, label='+ Clone')
self.routine_delete_btn = wx.Button(self, label='Delete')
self.routine_new_btn.Bind(wx.EVT_BUTTON, self.on_routine_new)
self.routine_clone_btn.Bind(wx.EVT_BUTTON, self.on_routine_clone)
self.routine_delete_btn.Bind(wx.EVT_BUTTON, self.on_routine_delete)
gridstyle = wx.LC_REPORT | wx.LC_EDIT_LABELS | wx.LC_SINGLE_SEL
self.routine_list = wx.ListCtrl(self, style=gridstyle)
self.routine_list.AppendColumn('Routine Name')
self.routine_list.SetColumnWidth(0, 200)
self.routine_list.Bind(wx.EVT_LIST_ITEM_SELECTED,
self.on_routine_select)
self.routine_list.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT,
self.on_routine_name_change_begin)
self.routine_list.Bind(wx.EVT_LIST_END_LABEL_EDIT,
self.on_routine_name_change_end)
border = 5
button_grid = wx.BoxSizer(wx.HORIZONTAL)
button_grid.Add(self.routine_new_btn, 0, wx.EXPAND | wx.ALL,
border=border)
button_grid.AddSpacer(4)
button_grid.Add(self.routine_clone_btn, 0, wx.EXPAND | wx.ALL,
border=border)
button_grid.AddSpacer(4)
button_grid.Add(self.routine_delete_btn, 0, wx.EXPAND | wx.ALL,
border=border)
self.routine_grid.Add(button_grid, 0, wx.EXPAND | wx.ALL,
border=border)
self.routine_grid.AddSpacer(4)
self.routine_grid.Add(self.routine_list, 1, wx.EXPAND | wx.ALL,)
self.build_routine_choices()
self.SetSizerAndFit(self.routine_grid)
self.Layout()
self.Update()
if glb_control_panel is not None:
glb_control_panel.Layout()
glb_control_panel.Update()
def build_routine_choices(self):
self.routine_list.DeleteAllItems()
choices = [
r for r in _app_state[ROUTINES].keys()
]
idx = 0
for c in choices:
self.routine_list.InsertItem(idx, c)
if c == _app_state[CURRENT_ROUTINE]:
self.routine_list.SetItemState(idx,
wx.LIST_STATE_SELECTED,
wx.LIST_STATE_SELECTED)
idx += 1
self.Fit()
@modifies_state
def on_routine_new(self, evt):
newRoutine = Routine()
newRoutine.name = 'New Routine'
_app_state[ROUTINES][newRoutine.name] = newRoutine
_app_state[CURRENT_ROUTINE] = newRoutine.name
self.update_routine_grid()
pass
@modifies_state
def on_routine_clone(self, evt):
clone = copy.deepcopy(
_app_state[ROUTINES][_app_state[CURRENT_ROUTINE]]
)
clone.name = f'{clone.name} (clone)'
_app_state[ROUTINES][clone.name] = clone
_app_state[CURRENT_ROUTINE] = clone.name
self.update_routine_grid()
@modifies_state
def on_routine_delete(self, evt):
delname = _app_state[CURRENT_ROUTINE]
_app_state[CURRENT_ROUTINE] = list(_app_state[ROUTINES].keys())[0]
del _app_state[ROUTINES][delname]
self.update_routine_grid()
@modifies_state
def on_routine_select(self, evt):
routine = evt.GetLabel()
_app_state[CURRENT_ROUTINE] = routine
print(f'Selected routine {routine}')
global glb_waypoint_panel, glb_field_render
if glb_field_render is not None:
glb_field_render.force_redraw()
if glb_waypoint_panel is not None:
glb_waypoint_panel.update_waypoint_grid()
pass
def on_routine_name_change_begin(self, evt):
print('begin name change')
self.routine_rename_in_progress = evt.GetLabel()
print(evt.GetLabel())
@modifies_state
def on_routine_name_change_end(self, evt):
print('name change')
newlabel = evt.GetLabel()
oldlabel = self.routine_rename_in_progress
if newlabel == oldlabel:
print('no rename needed')
return
print(f'Rename {oldlabel} to {newlabel}')
r = _app_state[ROUTINES][oldlabel]
del _app_state[ROUTINES][oldlabel]
r.name = newlabel
_app_state[ROUTINES][newlabel] = r
if _app_state[CURRENT_ROUTINE] == oldlabel:
_app_state[CURRENT_ROUTINE] = newlabel
class WaypointPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.waypoint_grid = None
self.waypoint_x_list = []
self.waypoint_y_list = []
self.update_waypoint_grid()
def update_waypoint_data(self):
routine = _app_state[CURRENT_ROUTINE]
waypoints = _app_state[ROUTINES][routine].waypoints
for idx, w in enumerate(waypoints):
self.waypoint_x_list[idx].ChangeValue(str(w.x))
self.waypoint_y_list[idx].ChangeValue(str(w.y))
def update_waypoint_grid(self):
if self.waypoint_grid is not None:
self.waypoint_grid.Clear(True)
else:
# Make this staticboxsizer object grow/expand if needed
self.waypoint_grid = wx.StaticBoxSizer(
wx.VERTICAL, self, 'Waypoints'
)
routine = _app_state[CURRENT_ROUTINE]
waypoints = _app_state[ROUTINES][routine].waypoints
spacing = 4
vbox = wx.BoxSizer(wx.VERTICAL)
self.waypoint_x_list = []
self.waypoint_y_list = []
for idx, w in enumerate(waypoints):
# Create a box for each waypoint
wbox = wx.BoxSizer(wx.HORIZONTAL)
x_txt = wx.TextCtrl(self)
y_txt = wx.TextCtrl(self)
x_txt.Bind(wx.EVT_TEXT, self.on_waypoint_change_x)
y_txt.Bind(wx.EVT_TEXT, self.on_waypoint_change_y)
self.waypoint_x_list.append(x_txt)
self.waypoint_y_list.append(y_txt)
del_btn = wx.Button(self, name=str(idx), label='X', size=(35, -1))
del_btn.Bind(wx.EVT_BUTTON, self.on_waypoint_delete)
wbox.Add(wx.StaticText(self, label=f'{idx}'), 0, wx.EXPAND)
wbox.AddSpacer(spacing)
wbox.Add(x_txt, 0, wx.EXPAND)
wbox.AddSpacer(spacing)
wbox.Add(y_txt, 0, wx.EXPAND)
wbox.AddSpacer(spacing)
wbox.Add(del_btn, 0, wx.SHRINK)
# Add that waypoint to our vertical list
vbox.Add(wbox, 0, wx.EXPAND)
vbox.AddSpacer(spacing)
self.update_waypoint_data()
# Add the vertical list into the 'grid' area we have for the list
self.waypoint_grid.Add(vbox, proportion=1, flag=wx.EXPAND)