-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVRW-gui.py
1541 lines (1367 loc) · 58.4 KB
/
VRW-gui.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 python
#
# Vector Recursion Workbench
# Copyright (c) 2014-2016 Nathan Williams, Jason Fletcher
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
POINT_SNAP_PIXEL_DIST = 25
import copy
import os
import time
import wx
from recursion_excursion import generate_recursion, generate_svg
from project import project, shape, polygon, vec2
# File menu
ID_EXPORT_FULL = wx.NewId()
ID_EXPORT_INDIVIDUAL = wx.NewId()
# Control panel
ID_BTN_ADD_LINE = wx.NewId()
ID_BTN_DEL_LINE = wx.NewId()
ID_CHK_SNAP = wx.NewId()
ID_CHK_HIDE_GUIDE = wx.NewId()
ID_CHK_HIDE_NUM = wx.NewId()
ID_RAD_PREVIEW = wx.NewId()
ID_RAD_ASPECT_RATIO = wx.NewId()
# Attributes panel
## Shape
ID_RA_SHAPE_DIR = wx.NewId()
ID_TXT_SHAPE_ATTRS = wx.NewId()
ID_SL_SHAPE_DEPTH = wx.NewId()
ID_SP_SHAPE_DEPTH = wx.NewId()
ID_SL_SHAPE_STEP = wx.NewId()
ID_SP_SHAPE_STEP = wx.NewId()
ID_SL_SHAPE_INNER = wx.NewId()
ID_SP_SHAPE_INNER = wx.NewId()
ID_CHK_REVERSE_COLORS = wx.NewId()
ID_CHK_DISABLED = wx.NewId()
ID_SL_SHAPE_FOOTER = wx.NewId()
ID_SP_SHAPE_FOOTER = wx.NewId()
ID_SL_SHAPE_FOOTER_BUFFER = wx.NewId()
ID_SP_SHAPE_FOOTER_BUFFER = wx.NewId()
ID_SL_SHAPE_FOOTER_OFFSET = wx.NewId()
ID_SP_SHAPE_FOOTER_OFFSET = wx.NewId()
## Global
ID_SL_GLOBAL_STEP = wx.NewId()
ID_SP_GLOBAL_STEP = wx.NewId()
ID_CP_GLOBAL_COLOR1 = wx.NewId()
ID_CP_GLOBAL_COLOR2 = wx.NewId()
ID_SP_GLOBAL_CANVAS_WIDTH = wx.NewId()
ID_SP_GLOBAL_CANVAS_HEIGHT = wx.NewId()
ID_BTN_GLOBAL_BG_IMAGE = wx.NewId()
class ProjectDefaults(object):
depth = 50
step = 0.20
inc = 0.0
footer = 0.0
clockwise = True
colors = [ '#000000', '#FFFFFF' ]
# 16:9 Default
canvas = [ 0, 0, 896, 504 ]
reverse_colors=False
class ControlsState(object):
json_save_filename = None
# Controls
do_point_snapping = True
do_hide_guide_lines = False
do_hide_shape_numbers = False
do_draw_recursion = False
aspect_ratio_fit = True
bg_bitmap = None
class AppState(object):
project = None
rec_list = None
canvas_w = None
canvas_h = None
# Shape selection
do_num_hotkey = True
selected_shape = None
# Guide line addition
add_line_proposed = None # vec2 from projection onto existing line
add_line_proposed_info = None # (shape, index) of where proposed was projected
add_line_stage = None # list of accepted proposed
add_line_stage_info = None # list of accepted proposed infos
# Guide line deletion
del_line_stage = None # [vec2,vec2] of proposed line to delete
class UndoStack(object):
def __init__(self):
self._callback = None
self.reset()
def __repr__(self):
return 'UndoStack(%d,%s)' % (self._pos, str(self._stack))
def do_callback(self):
if self._callback:
self._callback(self)
def set_callback(self, cb):
self._callback = cb
def reset(self):
self._pos = -1
self._stack = []
self.do_callback()
def do(self, x):
del self._stack[(self._pos + 1):]
self._stack.append(x)
self._pos = len(self._stack) - 1
self.do_callback()
def can_undo(self):
return (self._pos > 0)
def undo(self):
self._pos -= 1
self.do_callback()
return self._stack[self._pos]
def can_redo(self):
return ((self._pos + 1) < len(self._stack))
def redo(self):
self._pos += 1
self.do_callback()
return self._stack[self._pos]
g_project_defaults = ProjectDefaults()
g_app = None
g_state = AppState()
g_controls = ControlsState()
g_undo_stack = UndoStack()
def get_scale(view_xy):
canvas_x = g_state.project.canvas[2] - g_state.project.canvas[0]
canvas_y = g_state.project.canvas[3] - g_state.project.canvas[1]
# Default stretch
xs = view_xy[0] / float(canvas_x)
ys = view_xy[1] / float(canvas_y)
if g_controls.aspect_ratio_fit:
if xs < ys:
ys = xs
else:
xs = ys
return xs,ys
def colour_from_name(color_name):
c = wx.Colour()
c.SetFromName(color_name)
return c
def post_project_modification():
p_copy = copy.deepcopy(g_state.project)
g_undo_stack.do(p_copy)
def state_from_project(orig_proj, with_undo_reset=True):
global g_state
try:
proj = copy.deepcopy(orig_proj)
cw = proj.canvas[2] - proj.canvas[0]
ch = proj.canvas[3] - proj.canvas[1]
rl = generate_recursion(proj)
g_state = AppState()
g_state.project = proj
g_state.rec_list = rl
g_state.canvas_w = cw
g_state.canvas_h = ch
g_app.set_global_ui()
g_app.force_redraw()
if with_undo_reset:
g_undo_stack.reset()
post_project_modification()
except Exception as e:
print 'Failed, keeping old project:', e
def new_project():
# Simple empty project
d = g_project_defaults
p1 = d.canvas[0:2]
p2 = d.canvas[2:4]
s = shape(
poly=polygon([vec2(p1[0], p1[1]),
vec2(p2[0], p1[1]),
vec2(p2[0], p2[1]),
vec2(p1[0], p2[1])]),
depth=d.depth,
step=d.step,
inc=d.inc,
clockwise=d.clockwise,
reverse_colors=d.reverse_colors,
disabled=False,
footer=d.footer,
footer_inc=0.0,
footer_offset=0,
)
p = project(d.canvas, d.colors, [s])
g_controls.json_save_filename = None
state_from_project(p)
def load_project(filename):
print 'Loading project file:', filename
try:
tmp_p = project.load_file(filename)
state_from_project(tmp_p)
g_controls.json_save_filename = filename
except Exception as e:
print 'Failed, keeping old project:', e
def save_project(filename, keep_filename):
if g_state is None:
print 'Nothing to save!'
return
print 'Saving project file:', filename
try:
p_copy = copy.deepcopy(g_state.project)
p_copy.save_file(filename)
if keep_filename:
g_controls.json_save_filename = filename
except Exception as e:
print 'Failed:', e
def export_full(filename):
if g_state is None:
print 'Nothing to export!'
return
print 'Exporting SVG file:', filename
try:
p_copy = copy.deepcopy(g_state.project)
rl = generate_recursion(p_copy)
with open(filename, 'w') as f:
generate_svg(p_copy.canvas, rl, f)
except Exception as e:
print 'Failed:', e
def export_individual(directory):
if g_state is None:
print 'Nothing to export!'
return
print 'Exporting individual SVG files to:', directory
try:
p_copy = copy.deepcopy(g_state.project)
rl = generate_recursion(p_copy)
for i,r in enumerate(rl):
if r:
filename = '%02d.svg' % (i + 1)
with open(os.path.join(directory, filename), 'w') as f:
generate_svg(p_copy.canvas, [r], f)
except Exception as e:
print 'Failed:', e
def unique_list(l):
out = []
for x in l:
if x not in out:
out.append(x)
return out
class BaseDrawPanel(wx.Panel):
def __init__(self, parent, style=wx.TAB_TRAVERSAL):
wx.Panel.__init__(self, parent=parent, style=style)
def bind_events(self, target):
target.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
target.Bind(wx.EVT_MOTION, self.OnMotion)
#
# Events
#
def OnLeftUp(target, evt):
if g_state.add_line_stage is not None:
# May not have proposed yet if keyboard shotcut was used
if not g_state.add_line_proposed:
evt.Skip()
return
g_state.add_line_stage.append(g_state.add_line_proposed)
g_state.add_line_stage_info.append(g_state.add_line_proposed_info)
g_state.add_line_proposed = None
g_state.add_line_proposed_info = None
if len(g_state.add_line_stage) == 2:
# Check
assert len(g_state.add_line_stage_info) == 2
stage = g_state.add_line_stage
info = g_state.add_line_stage_info
s_shape= info[0][0]
assert s_shape == info[1][0]
if s_shape == g_state.selected_shape:
g_state.selected_shape = None
# Order clockwise
if info[0][1] > info[1][1]:
stage = [ stage[1], stage[0] ]
info = [ info[1], info[0] ]
# Clear out
g_state.rec_list = None
g_state.project.shapes.remove(s_shape)
# Split the shape
points = s_shape.poly.points
s_a_p = []
for i in range(0, info[0][1]+1):
s_a_p.append(points[i])
s_a_p.append(stage[0])
s_a_p.append(stage[1])
for i in range(info[1][1]+1, len(points)):
s_a_p.append(points[i])
s_b_p = []
s_b_p.append(stage[0])
for i in range(info[0][1]+1, info[1][1]+1):
s_b_p.append(points[i])
s_b_p.append(stage[1])
s_a_p = unique_list(s_a_p)
s_b_p = unique_list(s_b_p)
new_footer = s_shape.footer
s_a = shape(
poly=polygon(s_a_p),
depth=s_shape.depth,
step=s_shape.step,
inc=s_shape.inc,
clockwise=s_shape.clockwise,
reverse_colors=s_shape.reverse_colors,
disabled=False,
footer=new_footer,
footer_inc=s_shape.footer_inc,
footer_offset=s_shape.footer_offset,
)
s_b = shape(
poly=polygon(s_b_p),
depth=s_shape.depth,
step=s_shape.step,
inc=s_shape.inc,
clockwise=s_shape.clockwise,
reverse_colors=s_shape.reverse_colors,
disabled=False,
footer=new_footer,
footer_inc=s_shape.footer_inc,
footer_offset=s_shape.footer_offset,
)
g_state.project.shapes.extend([s_a, s_b])
# Generate
g_state.rec_list = generate_recursion(g_state.project)
post_project_modification()
# Clear
g_state.add_line_stage = None
g_state.add_line_stage_info = None
g_app.force_redraw()
elif g_state.del_line_stage is not None:
# May not have proposed yet if keyboard shortcut was used
if not g_state.del_line_stage:
evt.Skip()
return
line = g_state.del_line_stage
g_state.del_line_stage = None
shapes = []
error_msg = None
for s in g_state.project.shapes:
if (line[0] in s.poly.points) and (line[1] in s.poly.points):
shapes.append(s)
if len(shapes) == 0:
error_msg = 'Found no shapes with line segment!'
elif len(shapes) == 1:
# Remove line[0] from shape
t_poly = polygon(shapes[0].poly.points)
t_poly.points.remove(line[0])
if len(t_poly.points) < 3:
g_state.project.shapes.remove(shapes[0])
elif t_poly.is_concave():
shapes[0].poly = t_poly
else:
error_msg = 'Combined shape is convex!'
elif len(shapes) == 2:
points = []
# Collect all points
for s in shapes:
points.extend(s.poly.points)
# Contains 2 copies of line[0] and line[1]. Remove one copy.
for p in line:
points.remove(p)
# Get them clockwise
t_poly = polygon(points)
points = t_poly.points
# Remove any points that are on a line segment instead of being a corner.
# For points A, B, C, if AB and BC are co-linear (cross of 0), remove B.
repeat = True
while repeat:
repeat = False
n = len(points)
for i,a in enumerate(points):
b = points[(i+1)%n]
c = points[(i+2)%n]
ab = b - a
bc = c - b
if abs(ab.cross(bc)) < 0.001:
points.remove(b)
repeat = True
break
t_poly = polygon(points)
if t_poly.is_concave():
shapes[0].poly = t_poly
g_state.project.shapes.remove(shapes[1])
else:
error_msg = 'Combined shape is convex!'
else:
error_msg = 'Found more than two shapes with line segment!'
if error_msg:
wx.MessageBox(error_msg, 'Deletion error', wx.OK|wx.ICON_ERROR)
else:
g_state.rec_list = generate_recursion(g_state.project)
post_project_modification()
g_app.force_redraw()
else:
# [De]Select shape
sp = wx.GetMousePosition() - target.GetScreenPosition()
w,h = target.GetClientSize()
xs,ys = get_scale((w, h))
inv_xs,inv_ys = (1.0/xs), (1.0/ys)
# Scale to canvas coordinates
p = vec2(sp.x * inv_xs, sp.y * inv_ys)
for i,s in enumerate(g_state.project.shapes):
if s.poly.contains(p):
if g_state.selected_shape == s:
g_state.selected_shape = None
else:
g_state.selected_shape = s
break
g_app.force_redraw()
evt.Skip()
def OnMotion(target, evt):
w,h = target.GetClientSize()
xs,ys = get_scale((w, h))
inv_xs,inv_ys = (1.0/xs), (1.0/ys)
if g_state.add_line_stage is not None:
sp = evt.GetPosition()
# Scale to canvas coordinates
p = vec2(sp.x * inv_xs, sp.y * inv_ys)
# Snap current point to closest if close enough to existing.
if g_controls.do_point_snapping:
closest = None
for shape in g_state.project.shapes:
for point in shape.poly.points:
if (closest is None) or (p.dist_sq(point) < p.dist_sq(closest)):
closest = point
# Back to screen coordinates, closer dist^2?
screen_p = vec2(p.x * xs, p.y * ys)
screen_c = vec2(closest.x * xs, closest.y * ys)
if screen_p.dist_sq(screen_c) <= (POINT_SNAP_PIXEL_DIST**2):
p = closest
# Project onto all shape lines
closest = None
closest_info = None
last_info = (None,None)
if g_state.add_line_stage_info:
last_info = g_state.add_line_stage_info[0]
for shape in g_state.project.shapes:
if (g_state.selected_shape is not None) and (g_state.selected_shape != shape):
continue
# TODO: Restricted to current shape for poly split simplicity
if last_info[0] and last_info[0] != shape:
continue
cnt = len(shape.poly.points)
for i in range(cnt):
# Skip current line segment
if (shape, i) == last_info:
continue
a = shape.poly.points[i]
b = shape.poly.points[(i+1)%cnt]
pp = p.project_onto_line(a, b)
pp.x = round(pp.x, 8)
pp.y = round(pp.y, 8)
if (closest is None) or (p.dist_sq(pp) < p.dist_sq(closest)):
closest = pp
closest_info = (shape, i)
g_state.add_line_proposed = closest
g_state.add_line_proposed_info = closest_info
g_app.force_redraw()
elif g_state.del_line_stage is not None:
sp = evt.GetPosition()
# Scale to canvas coordinates
p = vec2(sp.x * inv_xs, sp.y * inv_ys)
# Find closest line segment
closest = None
closest_info = None
for shape in g_state.project.shapes:
if (g_state.selected_shape is not None) and (g_state.selected_shape != shape):
continue
cnt = len(shape.poly.points)
for i,a in enumerate(shape.poly.points):
b = shape.poly.points[(i+1)%cnt]
pp = p.project_onto_line(a, b)
if (closest is None) or (p.dist_sq(pp) < p.dist_sq(closest)):
closest = pp
closest_info = [a,b]
g_state.del_line_stage = closest_info
g_app.force_redraw()
evt.Skip()
class GraphicsContextDrawPanel(BaseDrawPanel):
def __init__(self, parent):
BaseDrawPanel.__init__(self, parent=parent, style=wx.FULL_REPAINT_ON_RESIZE)
self._bg_color = wx.Brush(True and 'white' or self.GetBackgroundColour())
# Manual buffer on Windows to prevent resize flicker
self._use_buffer = ('wxMSW' in wx.PlatformInfo)
if self._use_buffer:
self._buffer = None
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnErase)
# Events
self.bind_events(self)
self.Bind(wx.EVT_PAINT, self.OnPaint)
#
# Internal
#
def init_buffer(self):
sz = self.GetClientSize()
sz.width = max(1, sz.width)
sz.height = max(1, sz.height)
self._buffer = wx.EmptyBitmap(sz.width, sz.height, 32)
dc = wx.MemoryDC(self._buffer)
dc.SetBackground(self._bg_color)
dc.Clear()
self.draw_gc(dc)
def draw_gc(self, dc):
if g_state.rec_list is None:
return
gc = wx.GraphicsContext.Create(dc)
xs,ys = get_scale(gc.GetSize())
if g_controls.do_draw_recursion:
brush_map = {}
brushes = []
paths = []
for tlist in g_state.rec_list:
for c,poly in tlist:
path = gc.CreatePath()
for n,point in enumerate(poly.points):
x = point.x * xs
y = point.y * ys
if n == 0:
path.MoveToPoint(x, y)
else:
path.AddLineToPoint(x, y)
path.CloseSubpath()
b = brush_map.get(c, None)
if b == None:
brush_map[c] = b = wx.Brush(colour_from_name(c))
brushes.append(b)
paths.append(path)
for b,p in zip(brushes, paths):
gc.SetBrush(b)
gc.FillPath(p)
else:
if g_controls.bg_bitmap:
bgw = (g_state.project.canvas[2] - g_state.project.canvas[0]) * xs
bgh = (g_state.project.canvas[3] - g_state.project.canvas[1]) * ys
gc.DrawBitmap(g_controls.bg_bitmap, 0, 0, bgw, bgh)
if not g_controls.do_hide_guide_lines:
gc.SetPen(wx.Pen('black', 3))
for s in g_state.project.shapes:
path = gc.CreatePath()
for n,point in enumerate(s.poly.points):
x = point.x * xs
y = point.y * ys
if n == 0:
path.MoveToPoint(x, y)
else:
path.AddLineToPoint(x, y)
path.CloseSubpath()
gc.StrokePath(path)
if not g_controls.do_hide_shape_numbers:
f = wx.Font(pointSize=18, family=wx.FONTFAMILY_DEFAULT, style=wx.FONTSTYLE_NORMAL, weight=wx.FONTWEIGHT_BOLD)
bg = gc.CreateBrush(wx.Brush('white'))
for i,s in enumerate(g_state.project.shapes):
gc.SetFont(f, (g_state.selected_shape == s) and wx.RED or wx.BLACK)
c = s.poly.center()
gc.DrawText(str(i+1), c.x*xs - 9, c.y*ys - 9, bg)
# Draw in-progress guide line
points = []
line_color = 'gray'
line_size = 3
if g_state.add_line_proposed:
points.append(g_state.add_line_proposed)
if g_state.add_line_stage:
points.extend(g_state.add_line_stage)
if g_state.del_line_stage:
line_color = 'red'
line_size = 5
points.extend(g_state.del_line_stage)
if points:
gc.SetPen(wx.Pen(line_color, 1))
gc.SetBrush(wx.Brush(line_color))
path = gc.CreatePath()
for p in points:
path.AddCircle(p.x * xs, p.y * ys, 7)
gc.SetPen(wx.Pen(line_color, line_size))
if len(points) == 2:
path.MoveToPoint(points[0].x * xs, points[0].y * ys)
path.AddLineToPoint(points[1].x * xs, points[1].y * ys)
path.CloseSubpath()
gc.DrawPath(path)
#
# Events
#
def OnErase(self, evt):
# Prevent flicker
pass
def OnPaint(self, evt):
if self._use_buffer:
if self._buffer is None:
self.init_buffer()
dc = wx.BufferedPaintDC(self, self._buffer)
else:
dc = wx.PaintDC(self)
dc.SetBackground(self._bg_color)
dc.Clear()
self.draw_gc(dc)
def OnSize(self, evt):
self.init_buffer()
evt.Skip()
class ControlsPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
btn1 = wx.Button(parent=self, id=ID_BTN_ADD_LINE, label='Draw Guide Line (d)')
btn2 = wx.Button(parent=self, id=ID_BTN_DEL_LINE, label='Delete Guide Line (x)')
chk1 = wx.CheckBox(parent=self, id=ID_CHK_SNAP, label='Snapping')
chk2 = wx.CheckBox(parent=self, id=ID_CHK_HIDE_GUIDE, label='Hide Guide Lines')
chk3 = wx.CheckBox(parent=self, id=ID_CHK_HIDE_NUM, label='Hide Shape #\'s')
sf = wx.SizerFlags().Left()
checks = wx.BoxSizer(wx.VERTICAL)
checks.AddF(chk1, sf)
checks.AddF(chk2, sf)
checks.AddF(chk3, sf)
rbox1 = wx.RadioBox(parent=self, label='Preview',
id=ID_RAD_PREVIEW,
choices=['Guide Lines', 'Recursion'],
style=wx.RA_SPECIFY_ROWS,
majorDimension=2)
rbox2 = wx.RadioBox(parent=self, label='Aspect Ratio',
id=ID_RAD_ASPECT_RATIO,
choices=['Fit', 'Stretch'],
style=wx.RA_SPECIFY_ROWS,
majorDimension=2)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.AddStretchSpacer()
sf = wx.SizerFlags().Center().DoubleBorder()
for c in [btn1, btn2, checks, rbox1, rbox2]:
sizer.AddF(c, sf)
sizer.AddStretchSpacer()
self.SetAutoLayout(True)
self.SetSizer(sizer)
# Initial state
chk1.SetValue(g_controls.do_point_snapping)
chk2.SetValue(g_controls.do_hide_guide_lines)
chk3.SetValue(g_controls.do_hide_shape_numbers)
rbox1.SetSelection(1 if g_controls.do_draw_recursion else 0)
# Events
btn1.Bind(wx.EVT_BUTTON, self.OnAddLine)
btn2.Bind(wx.EVT_BUTTON, self.OnDelLine)
chk1.Bind(wx.EVT_CHECKBOX, self.OnSnap)
chk2.Bind(wx.EVT_CHECKBOX, self.OnHideGuide)
chk3.Bind(wx.EVT_CHECKBOX, self.OnHideNum)
rbox1.Bind(wx.EVT_RADIOBOX, self.OnPreview)
rbox2.Bind(wx.EVT_RADIOBOX, self.OnAspectRatio)
#
# Events
#
def OnAddLine(self, evt):
g_state.add_line_stage = []
g_state.add_line_stage_info = []
g_state.del_line_stage = None
def OnDelLine(self, evt):
g_state.add_line_stage = None
g_state.add_line_stage_info = None
g_state.del_line_stage = []
def OnSnap(self, evt):
g_controls.do_point_snapping = evt.Checked()
def OnHideGuide(self, evt):
g_controls.do_hide_guide_lines = evt.Checked()
self.GetParent().force_redraw()
def OnHideNum(self, evt):
g_controls.do_hide_shape_numbers = evt.Checked()
self.GetParent().force_redraw()
def OnPreview(self, evt):
g_controls.do_draw_recursion = (evt.GetInt() == 1)
self.GetParent().force_redraw()
def OnAspectRatio(self, evt):
g_controls.aspect_ratio_fit = (evt.GetInt() == 0)
self.GetParent().force_redraw()
class MainFrame(wx.Frame):
def __init__(self, parent, title, size):
wx.Frame.__init__(self, parent=parent, title=title, size=size)
# File menu
file_menu = wx.Menu()
file_menu.Append(wx.ID_NEW, "", "New Project")
file_menu.Append(wx.ID_OPEN, "", "Open Project")
file_menu.Append(wx.ID_SAVE, "", "Save Project")
file_menu.Append(wx.ID_SAVEAS, "", "Save Project As")
file_menu.Append(ID_EXPORT_FULL, "Export", "Export Full SVG");
file_menu.Append(ID_EXPORT_INDIVIDUAL, "Export Shapes", "Export Individual SVGs");
file_menu.Append(wx.ID_EXIT, "", "")
# Edit menu
edit_menu = wx.Menu()
edit_menu.Append(wx.ID_UNDO, "", "")
edit_menu.Append(wx.ID_REDO, "", "")
self._edit_menu = edit_menu
# Menu bar
menu_bar = wx.MenuBar()
menu_bar.Append(file_menu, "&File")
menu_bar.Append(edit_menu, "&Edit")
self.SetMenuBar(menu_bar)
self.CreateStatusBar()
# Control panel
self._control_panel = ControlsPanel(parent=self)
# Draw panel
self._draw_panel = None
self.init_draw_panel()
# Events
self.Bind(wx.EVT_PAINT, self.OnPaint)
# File
self.Bind(wx.EVT_MENU, self.OnNew, id=wx.ID_NEW)
self.Bind(wx.EVT_MENU, self.OnOpen, id=wx.ID_OPEN)
self.Bind(wx.EVT_MENU, self.OnSave, id=wx.ID_SAVE)
self.Bind(wx.EVT_MENU, self.OnSaveAs, id=wx.ID_SAVEAS)
self.Bind(wx.EVT_MENU, self.OnExportFull, id=ID_EXPORT_FULL)
self.Bind(wx.EVT_MENU, self.OnExportIndividual, id=ID_EXPORT_INDIVIDUAL)
self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
# Edit
self.Bind(wx.EVT_MENU, self.OnUndo, id=wx.ID_UNDO)
self.Bind(wx.EVT_MENU, self.OnRedo, id=wx.ID_REDO)
#
# Internal
#
def set_undo_state(self, undo_stack):
self._edit_menu.Enable(wx.ID_UNDO, undo_stack.can_undo())
self._edit_menu.Enable(wx.ID_REDO, undo_stack.can_redo())
def init_draw_panel(self):
if self._draw_panel:
self._draw_panel.Destroy()
self._draw_panel = GraphicsContextDrawPanel(self)
# Layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.AddF(self._control_panel, wx.SizerFlags().Expand())
sizer.AddF(self._draw_panel, wx.SizerFlags().Expand().Proportion(1))
self.SetAutoLayout(True)
self.SetSizer(sizer)
self.Layout()
def force_redraw(self):
self._draw_panel._buffer = None
self.Update()
self.Refresh()
def post_paint(self, start_time):
end_time = time.clock()
fps = int(1 / (end_time - start_time))
w,h = self._draw_panel.GetSize()
x,y = self._draw_panel.ScreenToClient(wx.GetMousePosition())
#self.SetStatusText('Canvas: %dx%d Cursor: (%d,%d) FPS: %d' % (w,h,x,y,fps))
self.SetStatusText('Canvas: %dx%d Cursor: (%d,%d)' % (w,h,x,y))
def save_internal(self, title, default_filename, keep_filename):
filename = default_filename
if not filename:
dlg = wx.FileDialog(self, title, "", "", "JSON Files (*.json)|*.json", wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
dlg.Destroy()
if filename:
save_project(filename, keep_filename)
#
# Events
#
def OnNew(self, evt):
dlg = wx.MessageDialog(self, 'All Unsaved progress will be lost.', 'Create New Project', wx.OK|wx.CANCEL)
if dlg.ShowModal() == wx.ID_OK:
new_project()
self.force_redraw()
dlg.Destroy()
def OnOpen(self, evt):
dlg = wx.FileDialog(self, "Open project file", "", "", "JSON Files (*.json)|*.json", wx.OPEN|wx.FD_FILE_MUST_EXIST)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
load_project(filename)
dlg.Destroy()
self.force_redraw()
def OnSave(self, evt):
self.save_internal("Save project file", g_controls.json_save_filename, True)
def OnSaveAs(self, evt):
self.save_internal("Save project file as", None, False)
def OnExportFull(self, evt):
dlg = wx.FileDialog(self, "Export SVG file", "", "", "SVG Files (*.svg)|*.svg", wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
export_full(filename)
dlg.Destroy()
def OnExportIndividual(self, evt):
dlg = wx.DirDialog(parent=self)
if dlg.ShowModal() == wx.ID_OK:
directory = dlg.GetPath()
export_individual(directory)
dlg.Destroy()
def OnExit(self, evt):
self.Close()
def OnUndo(self, evt):
if g_undo_stack.can_undo():
tmp_proj = g_undo_stack.undo()
state_from_project(tmp_proj, False)
def OnRedo(self, evt):
if g_undo_stack.can_redo():
tmp_proj = g_undo_stack.redo()
state_from_project(tmp_proj, False)
def OnOptDrawing(self, evt):
self.set_draw_type(evt.Id)
self.force_redraw()
def OnPaint(self, evt):
start_time = time.clock()
wx.CallAfter(self.post_paint, start_time)
class AttrFrame(wx.Frame):
def __init__(self, parent, title, size):
wx.Frame.__init__(self, parent=parent, title=title, size=size)
#
# Shape attributes
#
self._shape_panel = wx.Panel(parent=self)
txtShapeAttrs = wx.StaticText(parent=self._shape_panel, id=ID_TXT_SHAPE_ATTRS, label='SHAPE ATTRIBUTES')
txtShapeAttrs.SetFont(txtShapeAttrs.GetFont().Larger().Bold())
raDir = wx.RadioBox(parent=self._shape_panel, label='Direction',
id=ID_RA_SHAPE_DIR,
choices=['Clockwise', 'Counter-Clockwise'],
style=wx.RA_SPECIFY_ROWS,
majorDimension=2)
txtDepth = wx.StaticText(parent=self._shape_panel, label='Depth')
txtDepth.SetMinSize((52, -1))
slDepth = wx.Slider(parent=self._shape_panel, id=ID_SL_SHAPE_DEPTH, minValue=1, maxValue=150, value=1)
slDepth.SetMinSize((200, slDepth.GetMinSize()[1]))
spDepth = wx.SpinCtrl(parent=self._shape_panel, id=ID_SP_SHAPE_DEPTH, min=1, max=1000, value='1',
style=wx.SP_ARROW_KEYS|wx.ALIGN_RIGHT|wx.TE_PROCESS_ENTER)
spDepth.SetMinSize((75, -1))
txtStep = wx.StaticText(parent=self._shape_panel, label='Step')
txtStep.SetMinSize(txtDepth.GetMinSize())
slStep = wx.Slider(parent=self._shape_panel, id=ID_SL_SHAPE_STEP, minValue=1, maxValue=1000)
slStep.SetMinSize((200, slStep.GetMinSize()[1]))
spStep = wx.SpinCtrlDouble(parent=self._shape_panel, id=ID_SP_SHAPE_STEP, min=0.001, max=1.0, inc=0.01, initial=0.0,
style=wx.SP_ARROW_KEYS|wx.ALIGN_RIGHT|wx.TE_PROCESS_ENTER)
spStep.SetMinSize(spDepth.GetMinSize())
spStep.SetDigits(3)
txtInc = wx.StaticText(parent=self._shape_panel, label='Inner')
txtInc.SetMinSize(txtDepth.GetMinSize())
slInc = wx.Slider(parent=self._shape_panel, id=ID_SL_SHAPE_INNER, minValue=0, maxValue=1000)
slInc.SetMinSize((200, slInc.GetMinSize()[1]))
spInc = wx.SpinCtrlDouble(parent=self._shape_panel, id=ID_SP_SHAPE_INNER, min=0.0, max=0.1, inc=0.0001, initial=0.0,
style=wx.SP_ARROW_KEYS|wx.ALIGN_RIGHT|wx.TE_PROCESS_ENTER)
spInc.SetMinSize(spDepth.GetMinSize())
spInc.SetDigits(4)
chkReverseColors = wx.CheckBox(parent=self._shape_panel, id=ID_CHK_REVERSE_COLORS, label='Reverse colors')
chkDisabled = wx.CheckBox(parent=self._shape_panel, id=ID_CHK_DISABLED, label='Disable')
txtFooter = wx.StaticText(parent=self._shape_panel, label='Footer')
txtFooter.SetMinSize(txtDepth.GetMinSize())
slFooter = wx.Slider(parent=self._shape_panel, id=ID_SL_SHAPE_FOOTER,
minValue=0, maxValue=500, value=0)
slFooter.SetMinSize((200, slFooter.GetMinSize()[1]))
spFooter = wx.SpinCtrlDouble(parent=self._shape_panel, id=ID_SP_SHAPE_FOOTER,
min=0.0, max=1.0, inc=0.002, initial=0.0,
style=wx.SP_ARROW_KEYS|wx.ALIGN_RIGHT|wx.TE_PROCESS_ENTER)
spFooter.SetMinSize(spDepth.GetMinSize())
spFooter.SetDigits(3)
txtFooterInc = wx.StaticText(parent=self._shape_panel, label='Buffer')
txtFooterInc.SetMinSize(txtDepth.GetMinSize())
slFooterInc = wx.Slider(parent=self._shape_panel, id=ID_SL_SHAPE_FOOTER_BUFFER,
minValue=0, maxValue=500, value=0)
slFooterInc.SetMinSize((200, slFooterInc.GetMinSize()[1]))
spFooterInc = wx.SpinCtrlDouble(parent=self._shape_panel, id=ID_SP_SHAPE_FOOTER_BUFFER,
min=0.0, max=1.0, inc=0.002, initial=0.0,
style=wx.SP_ARROW_KEYS|wx.ALIGN_RIGHT|wx.TE_PROCESS_ENTER)
spFooterInc.SetMinSize(spDepth.GetMinSize())
spFooterInc.SetDigits(3)
txtFooterOffset = wx.StaticText(parent=self._shape_panel, label='Offset')
txtFooterOffset.SetMinSize(txtDepth.GetMinSize())
slFooterOffset = wx.Slider(parent=self._shape_panel, id=ID_SL_SHAPE_FOOTER_OFFSET,
minValue=0, maxValue=150, value=0)
slFooterOffset.SetMinSize((200, slFooterOffset.GetMinSize()[1]))
spFooterOffset = wx.SpinCtrl(parent=self._shape_panel, id=ID_SP_SHAPE_FOOTER_OFFSET,
min=0, max=1000, value='0',
style=wx.SP_ARROW_KEYS|wx.ALIGN_RIGHT|wx.TE_PROCESS_ENTER)
spFooterOffset.SetMinSize(spDepth.GetMinSize())
flags = wx.SizerFlags()
szDepth = wx.BoxSizer(wx.HORIZONTAL)
szDepth.AddF(txtDepth, flags)
szDepth.AddF(slDepth, flags)
szDepth.AddF(spDepth, flags)
szStep = wx.BoxSizer(wx.HORIZONTAL)
szStep.AddF(txtStep, flags)
szStep.AddF(slStep, flags)
szStep.AddF(spStep, flags)
szInc = wx.BoxSizer(wx.HORIZONTAL)
szInc.AddF(txtInc, flags)
szInc.AddF(slInc, flags)
szInc.AddF(spInc, flags)
szFooter = wx.BoxSizer(wx.HORIZONTAL)
szFooter.AddF(txtFooter, flags)
szFooter.AddF(slFooter, flags)
szFooter.AddF(spFooter, flags)
szFooterInc = wx.BoxSizer(wx.HORIZONTAL)
szFooterInc.AddF(txtFooterInc, flags)
szFooterInc.AddF(slFooterInc, flags)
szFooterInc.AddF(spFooterInc, flags)
szFooterOffset = wx.BoxSizer(wx.HORIZONTAL)