-
Notifications
You must be signed in to change notification settings - Fork 1
/
maped.py
1774 lines (1491 loc) · 72 KB
/
maped.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
from tkinter import *
from tkinter import filedialog
from tkinter import font
from tkinter import messagebox
from tkinter import simpledialog
from tkinter import ttk
from types import SimpleNamespace
from zipfile import ZipFile
import base64
import collections
import json
import math
import pathlib
import png
import platform
import re
import struct
import zipfile
TAG_PALETTE = ['#edd400', '#f57900', '#c17d11', '#73d216',
'#3465a4', '#75507b', '#cc0000', '#555753',
'#555753']
class Ctx:
class __serialiser__:
def __init__(self, ctx):
self.tiles = []
for tile in ctx.tiles:
self.tiles.append(base64.b64encode(tile).decode())
self.data = []
for datum in ctx.data_tree.get_children():
self.data.append(ctx.data_tree.item(datum)['values'])
for attr in ['map', 'tags', 'notes', 'entity_size', 'entities',
'palette', 'width', 'height', 'mode',
'tile_width', 'tile_height']:
setattr(self, attr, getattr(ctx, attr))
def __repl_func__(self, match: re.Match):
return " ".join(match.group().split())
def toJSON(self):
return re.sub(r"(?<=\[)[^\[\]]+(?=])", self.__repl_func__,
json.dumps(self, default=lambda o: o.__dict__, indent=4))
def __init__(self):
self.canvas = None # Main map drawing canvas
self.clipboard = None # The last thing copied or cut [ width, height, [tilemap] ]
self.tiles_canvas = None # Tiles drawing canvas
self.main_frame = None # Main window frame
self.property_widgets = [] # List of widgets that require a selection
self.note_text = None # The Text widget for cell notes
self.set_cell_tag = None # Callback (tag, desc) to update the cell properties UI
self.data_tree = None # Treeview containing cell data (id, data, desc)
self.entity_tree = None # Treeview containing entity list (x, y, desc)
self.entity_data_tree = None # Treeview to show individual entity data (data)
self.status_left = None # Status bar text variable
self.status_right = None # Status bar text variable
self.menu = None # Main menubar
self.zoom = 1 # Current map zoom level (must be whole number)
self.draw_grid = False
self.draw_tags = True
self.draw_entities = True
def reset(self):
self.name = None # Open file name
self.tiles = [] # Tile store (in binary CPC pixel format)
self.map = [] # Tile map
self.tags = [] # Tile tags map
self.notes = [] # Map of notes for cells in tile map
self.entity_size = 4
self.entities = [] # Entity list (x, y, desc, [[data, desc]+])
self.palette = [] # Palette as hex values
self.width = 0 # Map width in tiles
self.height = 0 # Map height in tiles
self.mode = 0 # CPC screen mode
self.tile_width = 8
self.tile_height = 8
self.selection = None # List of top-left and bottom-right tile coordinate lists
self.data_tree.delete(*self.data_tree.get_children())
self.entity_tree.delete(*self.entity_tree.get_children())
self.entity_data_tree.delete(*self.entity_data_tree.get_children())
self.note_text.delete('1.0', END)
update_selection()
def load(self, data):
obj = json.loads(data, object_hook=lambda d: SimpleNamespace(**d))
self.tiles = []
for tile in obj.tiles:
self.tiles.append(base64.b64decode(tile))
self.data_tree.delete(*self.data_tree.get_children())
for datum in obj.data:
self.data_tree.insert('', END, values=datum)
for attr in ['map', 'tags', 'notes', 'entity_size', 'entities',
'palette', 'width', 'height', 'mode',
'tile_width', 'tile_height']:
setattr(self, attr, getattr(obj, attr))
self.entity_tree.delete(*self.entity_tree.get_children())
self.entity_data_tree.delete(*self.entity_data_tree.get_children())
for entity in self.entities:
self.entity_tree.insert('', END, values=(entity[0], entity[1], entity[2]))
def toJSON(self):
return Ctx.__serialiser__(self).toJSON()
ctx = Ctx()
def get_pixel(tile, x, y):
pixel = 0
pixels_per_byte = 2 if ctx.mode == 0 else (4 if ctx.mode == 1 else 8)
cpc_pixel = tile[(int(ctx.tile_width / pixels_per_byte) * y) + int(x // pixels_per_byte)]
# TODO: Verify mode 2 and 1 are correct here
if ctx.mode == 2:
pixel = (cpc_pixel & (1 << (x % 8))) >> (x % 8)
elif ctx.mode == 1:
cpc_pixel = cpc_pixel << (x % 4)
pixel = ((cpc_pixel & 0b10000000) >> 7) | ((cpc_pixel & 0b00001000) >> 2)
elif ctx.mode == 0:
cpc_pixel = cpc_pixel << (x % 2)
pixel = ((cpc_pixel & 0b10000000) >> 7) | \
((cpc_pixel & 0b00001000) >> 2) | \
((cpc_pixel & 0b00100000) >> 3) | \
((cpc_pixel & 0b00000010) << 2)
return pixel
def get_byte(row, offset, mode):
cpc_pixel = 0
if mode == 2:
cpc_pixel = (row[offset] << 7) | \
(row[offset+1] << 6) | \
(row[offset+2] << 5) | \
(row[offset+3] << 4) | \
(row[offset+4] << 3) | \
(row[offset+5] << 2) | \
(row[offset+6] << 1) | \
row[offset+7]
elif mode == 1:
pixel0 = row[offset]
pixel1 = row[offset+1]
pixel2 = row[offset+2]
pixel3 = row[offset+3]
cpc_pixel = ((pixel0 & 0b01) << 7) | ((pixel1 & 0b01) << 6) | \
((pixel2 & 0b01) << 5) | ((pixel3 & 0b01) << 4) | \
((pixel0 & 0b10) << 2) | ((pixel1 & 0b10) << 1) | \
((pixel2 & 0b10)) | ((pixel3 & 0b10) >> 1)
elif mode == 0:
pixel0 = row[offset]
pixel1 = row[offset+1]
cpc_pixel = (0b10000000 if (pixel0 & 0b0001) != 0 else 0) | \
(0b01000000 if (pixel1 & 0b0001) != 0 else 0) | \
(0b00100000 if (pixel0 & 0b0100) != 0 else 0) | \
(0b00010000 if (pixel1 & 0b0100) != 0 else 0) | \
(0b00001000 if (pixel0 & 0b0010) != 0 else 0) | \
(0b00000100 if (pixel1 & 0b0010) != 0 else 0) | \
(0b00000010 if (pixel0 & 0b1000) != 0 else 0) | \
(0b00000001 if (pixel1 & 0b1000) != 0 else 0)
return cpc_pixel
def validate_number(S):
return S.isdecimal()
def update_status():
ctx.status_left.set('%d x %d, %d %dx%d tiles, mode %d' % \
(ctx.width, ctx.height, len(ctx.tiles),
ctx.tile_width, ctx.tile_height, ctx.mode))
# TODO: Adjust scroll to zoom around the current cursor position/selection?
def adjust_zoom(delta, force=False):
if len(ctx.tiles) == 0:
return
new_zoom = int(max(1, min(4, ctx.zoom + delta)))
if new_zoom == ctx.zoom and not force:
return
old_zoom = ctx.zoom
ctx.zoom = new_zoom
# Store the old xview/yview to work out the new centre
xview = ctx.canvas.xview()
yview = ctx.canvas.yview()
width_scale = 2 if ctx.mode == 0 else 1
height_scale = 2 if ctx.mode == 2 else 1
img = ctx.canvas.image.zoom(width_scale * ctx.zoom, height_scale * ctx.zoom)
ctx.canvas.config(scrollregion=(0, 0, img.width(), img.height()))
ctx.canvas.delete('image')
ctx.canvas.create_image((img.width()/2, img.height()/2), image=img, tags='image')
ctx.canvas.zoomed_image = img
# Reset the scroll position after zoom change
view_scale = old_zoom / new_zoom
newxview = max(0, xview[0] + ((xview[1] - xview[0]) / 2 * (1.0 - view_scale)))
newyview = max(0, yview[0] + ((yview[1] - yview[0]) / 2 * (1.0 - view_scale)))
ctx.canvas.xview_moveto(newxview)
ctx.canvas.yview_moveto(newyview)
redraw_grid()
redraw_entities()
update_selection()
def tile_coords_from_coords(e):
x = ctx.canvas.canvasx(e.x)
y = ctx.canvas.canvasy(e.y)
width_scale = (2 if ctx.mode == 0 else 1) * ctx.zoom
height_scale = (2 if ctx.mode == 2 else 1) * ctx.zoom
if x < 0 or x >= ctx.width * ctx.tile_width * width_scale:
return None
if y < 0 or y >= ctx.height * ctx.tile_height * height_scale:
return None
tilex = int((x / width_scale) // ctx.tile_width)
tiley = int((y / height_scale) // ctx.tile_height)
return [tilex, tiley]
def entry_has_focus(root):
focus = root.focus_get()
return isinstance(focus, Entry) or isinstance(focus, ttk.Entry) or isinstance(focus, Text)
def copy(root, cut=False):
if ctx.selection is None or entry_has_focus(root):
return
x1 = min(ctx.selection[0][0], ctx.selection[1][0])
x2 = max(ctx.selection[0][0], ctx.selection[1][0]) + 1
y1 = min(ctx.selection[0][1], ctx.selection[1][1])
y2 = max(ctx.selection[0][1], ctx.selection[1][1]) + 1
ctx.clipboard = [x2 - x1, y2 - y1, [], []]
for x in range(x1, x2):
for y in range(y1, y2):
i = x * ctx.height + y
ctx.clipboard[2].append(ctx.map[i])
ctx.clipboard[3].append(ctx.tags[i])
if cut:
ctx.map[i] = 0
ctx.tags[i] = 0
if cut:
redraw_map()
def paste(root, ):
if ctx.selection is None or ctx.selection[0] != ctx.selection[1] or entry_has_focus(root):
return
for x in range(0, ctx.clipboard[0]):
for y in range(0, ctx.clipboard[1]):
if x + ctx.selection[0][0] >= ctx.width or y + ctx.selection[0][1] >= ctx.height:
continue
i = x * ctx.clipboard[1] + y
mi = (ctx.selection[0][0] + x) * ctx.height + (ctx.selection[0][1] + y)
ctx.map[mi] = ctx.clipboard[2][i]
ctx.tags[mi] = ctx.clipboard[3][i]
redraw_map()
def update_selection():
editmenu = ctx.menu.nametowidget(ctx.menu.entrycget('Edit', 'menu'))
if ctx.selection is None:
for widget in ctx.property_widgets:
widget.config(state=DISABLED)
ctx.note_text.config(state=DISABLED)
ctx.canvas.delete('selection')
editmenu.entryconfig('Cut', state='disabled')
editmenu.entryconfig('Copy', state='disabled')
editmenu.entryconfig('Paste', state='disabled')
return
editmenu.entryconfig('Cut', state='normal')
editmenu.entryconfig('Copy', state='normal')
if ctx.selection[0] == ctx.selection[1]:
if ctx.clipboard is not None:
editmenu.entryconfig('Paste', state='normal')
ctx.note_text.config(state=NORMAL)
else:
editmenu.entryconfig('Paste', state='disabled')
ctx.note_text.config(state=DISABLED)
for widget in ctx.property_widgets:
widget.config(state=NORMAL)
# Work out selection coordinates
x1 = min(ctx.selection[0][0], ctx.selection[1][0])
x2 = max(ctx.selection[0][0], ctx.selection[1][0]) + 1
y1 = min(ctx.selection[0][1], ctx.selection[1][1])
y2 = max(ctx.selection[0][1], ctx.selection[1][1]) + 1
i = x1 * ctx.height + y1
width_scale = (2 if ctx.mode == 0 else 1) * ctx.zoom
height_scale = (2 if ctx.mode == 2 else 1) * ctx.zoom
x1 *= ctx.tile_width * width_scale
x2 *= ctx.tile_width * width_scale
y1 *= ctx.tile_height * height_scale
y2 *= ctx.tile_height * height_scale
rect = ctx.canvas.find_withtag('selection')
if len(rect) == 0:
ctx.canvas.create_rectangle((x1, y1, x2, y2), tags=['selection'], width=max(2, ctx.zoom))
else:
ctx.canvas.itemconfig(rect[0], width=max(2, ctx.zoom))
ctx.canvas.coords(rect[0], x1, y1, x2, y2)
ctx.canvas.lift(rect[0])
# Update cell tag
if ctx.selection[0] == ctx.selection[1]:
ctx.set_cell_tag(ctx.tags[i], ctx.notes[i])
def map_coords_from_event(e):
x = ctx.canvas.canvasx(e.x)
y = ctx.canvas.canvasy(e.y)
width_scale = (2 if ctx.mode == 0 else 1) * ctx.zoom
height_scale = (2 if ctx.mode == 2 else 1) * ctx.zoom
return (int(x / width_scale), int(y / height_scale))
def entity_at_point(x, y):
for i in range(len(ctx.entities)):
if x > ctx.entities[i][0] - 4 and x < ctx.entities[i][0] + 4 and \
y > ctx.entities[i][1] - 4 and y < ctx.entities[i][1] + 4:
return i
return -1
def canvas_motion(e):
if e.state & 0x0100: # Button1 mask (FIXME: this must be defined somewhere?)
i = tile_coords_from_coords(e)
if i is not None:
ctx.selection[1] = i
update_selection()
(x, y) = map_coords_from_event(e)
i = entity_at_point(x, y)
if i == -1:
ctx.status_right.set('(%d, %d)' % (x, y))
else:
ctx.status_right.set('%s (%d, %d)' % (ctx.entities[i][2], x, y))
def canvas_release(e):
i = tile_coords_from_coords(e)
if i is not None:
ctx.selection[1] = i
update_selection()
if ctx.selection is not None:
# Make sure selection is always top-left, bottom-right
# FIXME: We need to stop code using selections until they're completed here
x1 = min(ctx.selection[0][0], ctx.selection[1][0])
x2 = max(ctx.selection[0][0], ctx.selection[1][0])
y1 = min(ctx.selection[0][1], ctx.selection[1][1])
y2 = max(ctx.selection[0][1], ctx.selection[1][1])
ctx.selection[0][0] = x1
ctx.selection[1][0] = x2
ctx.selection[0][1] = y1
ctx.selection[1][1] = y2
def canvas_press(e):
ctx.canvas.focus_set()
# If we've clicked an entity, select it (should we disable selection when this happens?)
(x, y) = map_coords_from_event(e)
i = entity_at_point(x, y)
if i != -1:
ctx.entity_tree.selection_set(ctx.entity_tree.get_children()[i])
if ctx.map is None:
return
i = tile_coords_from_coords(e)
if i is None:
ctx.selection = None
update_selection()
return
ctx.selection = [i, i]
update_selection()
def canvas_alt_press(e, root):
(x, y) = map_coords_from_event(e)
i = entity_at_point(x, y)
if i == -1:
add_entity(root, [x, y, ''])
else:
ctx.entity_tree.selection_set(ctx.entity_tree.get_children()[i])
edit_entity(root)
def canvas_mousewheel(e):
delta = 0.0
if platform.system() == 'Windows':
delta = e.delta/120
elif platform.system() == 'Darwin':
delta = e.delta
else:
if e.num == 4:
e.delta = 1
elif e.num == 5:
e.delta = -1
adjust_zoom(delta)
def canvas_entered(e):
canvas = e.widget
if platform.system() == 'Linux':
canvas.bind_all("<Button-4>", canvas_mousewheel)
canvas.bind_all("<Button-5>", canvas_mousewheel)
else:
canvas.bind_all("<MouseWheel>", canvas_mousewheel)
def canvas_left(e):
canvas = e.widget
if platform.system() == 'Linux':
canvas.unbind_all("<Button-4>")
canvas.unbind_all("<Button-5>")
else:
canvas.unbind_all("<MouseWheel>")
def canvas_scroll(root, x, y):
if entry_has_focus(root):
return
xview = ctx.canvas.xview()
yview = ctx.canvas.yview()
if x < 0 and xview[0] > 0.0:
ctx.canvas.xview_moveto(max(0, xview[0] - 1.0/ctx.width))
elif x > 0 and xview[1] < 1.0:
ctx.canvas.xview_moveto(min(1.0 - (xview[1] - xview[0]), xview[0] + 1.0/ctx.width))
if y < 0 and yview[0] > 0.0:
ctx.canvas.yview_moveto(max(0, yview[0] - 1.0/ctx.height))
elif y > 0 and yview[1] < 1.0:
ctx.canvas.yview_moveto(min(1.0 - (yview[1] - yview[0]), yview[0] + 1.0/ctx.height))
def tiles_canvas_clicked(e):
if ctx.selection is None:
return
target = ctx.tiles_canvas.find_overlapping(ctx.tiles_canvas.canvasx(e.x),
ctx.tiles_canvas.canvasy(e.y),
ctx.tiles_canvas.canvasx(e.x),
ctx.tiles_canvas.canvasy(e.y))
if len(target) != 1:
return
tile = int(ctx.tiles_canvas.gettags(target[0])[0])
for y in range(ctx.selection[0][1], ctx.selection[1][1]+1):
for x in range(ctx.selection[0][0], ctx.selection[1][0]+1):
ctx.map[x * ctx.height + y] = tile
draw_map_tile(x, y)
adjust_zoom(0, True)
def tiles_canvas_alt_clicked(e):
target = ctx.tiles_canvas.find_overlapping(ctx.tiles_canvas.canvasx(e.x),
ctx.tiles_canvas.canvasy(e.y),
ctx.tiles_canvas.canvasx(e.x),
ctx.tiles_canvas.canvasy(e.y))
if len(target) != 1:
return
idx = int(ctx.tiles_canvas.gettags(target[0])[0])
if idx == 0:
return
old_tile = ctx.tiles[0]
ctx.tiles[0] = ctx.tiles[idx]
ctx.tiles[idx] = old_tile
for i in range(0, ctx.width * ctx.height):
if ctx.map[i] == 0:
ctx.map[i] = idx
elif ctx.map[i] == idx:
ctx.map[i] = 0
redraw_tiles()
def store_cell_tag(number):
if ctx.selection is not None:
changed = False
for y in range(ctx.selection[0][1], ctx.selection[1][1] + 1):
for x in range(ctx.selection[0][0], ctx.selection[1][0] + 1):
i = x * ctx.height + y
if ctx.tags[i] != number:
changed = True
ctx.tags[i] = number
if ctx.draw_tags:
draw_map_tile(x, y)
if changed and ctx.draw_tags:
adjust_zoom(0, True)
def update_hex(number, hex_text):
hex_text[0].set('%x' % (number >> 4))
hex_text[1].set('%x' % (number & 0xF))
def number_widgets_update(text, buttons, hex_text):
number = int(text.get())
for bit in range(0, 8):
if number & (1 << bit) != 0:
buttons[bit].text.set('1')
buttons[bit].configure(relief=SUNKEN, bg='black', fg='white')
else:
buttons[bit].text.set('0')
buttons[bit].configure(relief=RAISED, bg='white', fg='black')
update_hex(number, hex_text)
store_cell_tag(number)
def toggle_bit(buttons, bit, text, hex_text):
number = int(text.get())
if number & (1 << bit) != 0:
number &= ~(1 << bit)
else:
number |= (1 << bit)
text.set(str(number))
number_widgets_update(text, buttons, hex_text)
def note_modified():
ctx.note_text.edit_modified(False)
if ctx.selection is None:
return
for y in range(ctx.selection[0][1], ctx.selection[1][1]+1):
for x in range(ctx.selection[0][0], ctx.selection[1][0]+1):
ctx.notes[x * ctx.height + y] = ctx.note_text.get('1.0', END).rstrip()
def update_cell_tag(number, desc, tag_entry):
ctx.note_text.unbind('<<Modified>>')
tag_entry.set(number)
ctx.note_text.delete('1.0', END)
ctx.note_text.insert('1.0', desc)
ctx.note_text.edit_reset()
ctx.note_text.bind('<<Modified>>', lambda e: note_modified())
def apply_cell_tag_to_similar():
if ctx.selection is None:
return
changed = False
for y in range(0, ctx.height):
for x in range(0, ctx.width):
# Don't check inside the selection
if x >= min(ctx.selection[0][0], ctx.selection[1][0]) and \
x <= max(ctx.selection[0][0], ctx.selection[1][0]) and \
y >= min(ctx.selection[0][1], ctx.selection[1][1]) and \
y <= max(ctx.selection[0][1], ctx.selection[1][1]):
continue
# Check if this bit of the map matches the selection
same = True
for sy in range(ctx.selection[0][1], ctx.selection[1][1]+1):
for sx in range(ctx.selection[0][0], ctx.selection[1][0]+1):
mx = x + (sx - ctx.selection[0][0])
my = y + (sy - ctx.selection[0][1])
i = mx * ctx.height + my
si = sx * ctx.height + sy
if ctx.map[i] != ctx.map[si]:
same = False
break
if not same:
break
if not same:
continue
# Update the tags and redraw that part of the map
for sy in range(ctx.selection[0][1], ctx.selection[1][1]+1):
for sx in range(ctx.selection[0][0], ctx.selection[1][0]+1):
mx = x + (sx - ctx.selection[0][0])
my = y + (sy - ctx.selection[0][1])
i = mx * ctx.height + my
si = sx * ctx.height + sy
ctx.tags[i] = ctx.tags[si]
draw_map_tile(mx, my)
changed = True
if changed:
adjust_zoom(0, True)
def edit_entity_data(root):
selection = ctx.entity_tree.selection()
if len(selection) < 1:
return
i = ctx.entity_tree.index(selection[0])
for item in ctx.entity_data_tree.selection():
j = ctx.entity_data_tree.index(item)
d = EntityDataDialog(root, ctx.entities[i][3][j]).result
if d is None:
continue
ctx.entities[i][3][j][0] = d['data']
ctx.entities[i][3][j][1] = d['desc']
ctx.entity_data_tree.item(item, values=ctx.entities[i][3][j])
class EntityDataDialog(simpledialog.Dialog):
def __init__(self, parent, data):
self.defaults = data
super().__init__(parent, 'Edit entity data')
def body(self, master):
master.pack(expand=True, fill=BOTH, padx=5, pady=5)
ttk.Label(master, text='Data').grid(row=0, column=0, sticky=W, padx=5, pady=5)
ttk.Label(master, text='Description').grid(row=1, column=0, sticky=W, padx=5, pady=5)
self.data_entry = Spinbox(master, from_=0, to=255)
self.desc_entry = ttk.Entry(master)
self.data_entry.grid(row=0, column=1, sticky=EW)
self.desc_entry.grid(row=1, column=1, sticky=EW)
if self.defaults is not None:
self.data_entry.delete(0)
self.data_entry.insert(0, str(self.defaults[0]))
self.desc_entry.insert(0, self.defaults[1])
vcmd = (master.register(validate_number), '%S')
self.data_entry.configure(validate='key', validatecommand=vcmd)
def buttonbox(self):
ttk.Button(self, text='OK', width=6, command=self.ok_pressed).pack(side=RIGHT, padx=5, pady=5)
ttk.Button(self, text='Cancel', width=6, command=self.cancel_pressed).pack(side=RIGHT, padx=5, pady=5)
self.bind("<Return>", lambda event: self.ok_pressed())
self.bind("<Escape>", lambda event: self.cancel_pressed())
def ok_pressed(self):
data = int('0' + self.data_entry.get())
if data < 0 or data > 255:
messagebox.showerror('Data error', 'Invalid data (must be between 0 and 255)')
return
self.result = {
'data': data,
'desc': self.desc_entry.get(),
}
self.destroy()
def cancel_pressed(self):
self.result = None
self.destroy()
def edit_entity(root):
changed = False
for item in ctx.entity_tree.selection():
i = ctx.entity_tree.index(item)
d = EntityDialog(root, 'Edit entity', ctx.entities[i]).result
if d is None:
continue
ctx.entities[i][0] = d['x']
ctx.entities[i][1] = d['y']
ctx.entities[i][2] = d['desc']
ctx.entity_tree.item(item, values=ctx.entities[i][0:3])
changed = True
if changed:
redraw_entities()
def select_entity():
selection = ctx.entity_tree.selection()
if len(selection) < 1:
return
ctx.entity_data_tree.delete(*ctx.entity_data_tree.get_children())
i = ctx.entity_tree.index(selection[0])
for datum in ctx.entities[i][3]:
ctx.entity_data_tree.insert('', END, values=datum)
def remove_entity():
for item in ctx.entity_tree.selection():
i = ctx.entity_tree.index(item)
del ctx.entities[i]
ctx.entity_tree.delete(item)
ctx.entity_data_tree.delete(*ctx.entity_data_tree.get_children())
redraw_entities()
def add_entity(root, defaults=None):
if defaults is None:
defaults = [0, 0, '']
if ctx.selection is not None:
defaults[0] = int((ctx.selection[0][0] + ctx.selection[1][0] + 1) / 2 * ctx.tile_width)
defaults[1] = int((ctx.selection[0][1] + ctx.selection[1][1] + 1) / 2 * ctx.tile_height)
d = EntityDialog(root, 'Add entity', defaults).result
if d is None:
return
entity = [d['x'], d['y'], d['desc'], [[0, ''] for x in range(ctx.entity_size)]]
if len(ctx.entities) > 0:
for x in range(ctx.entity_size):
entity[3][x][1] = ctx.entities[-1][3][x][1]
ctx.entities.append(entity)
ctx.entity_tree.insert('', END, values=entity[0:3])
redraw_entities()
def validate_entity(data):
if data['x'] < 0 or data['x'] > 65535:
messagebox.showerror('Data error', 'Invalid X coordinate (must be between 0 and 65535)')
return False
if data['y'] < 0 or data['y'] > 65535:
messagebox.showerror('Data error', 'Invalid Y coordinate (must be between 0 and 65535)')
return False
return True
class EntityDialog(simpledialog.Dialog):
def __init__(self, parent, title='', data=None):
self.defaults = data
super().__init__(parent, title)
def body(self, master):
master.pack(expand=True, fill=BOTH, padx=5, pady=5)
ttk.Label(master, text='X').grid(row=0, column=0, sticky=W, padx=5, pady=5)
ttk.Label(master, text='Y').grid(row=1, column=0, sticky=W, padx=5, pady=5)
ttk.Label(master, text='Description').grid(row=2, column=0, sticky=W, padx=5, pady=5)
self.x_entry = Spinbox(master, from_=0, to=65535)
self.y_entry = Spinbox(master, from_=0, to=65535)
self.desc_entry = ttk.Entry(master)
self.x_entry.grid(row=0, column=1, sticky=EW)
self.y_entry.grid(row=1, column=1, sticky=EW)
self.desc_entry.grid(row=2, column=1, sticky=EW)
if self.defaults is not None:
self.x_entry.delete(0)
self.x_entry.insert(0, str(self.defaults[0]))
self.y_entry.delete(0)
self.y_entry.insert(0, str(self.defaults[1]))
self.desc_entry.insert(0, self.defaults[2])
vcmd = (master.register(validate_number), '%S')
self.x_entry.configure(validate='key', validatecommand=vcmd)
self.y_entry.configure(validate='key', validatecommand=vcmd)
def buttonbox(self):
ttk.Button(self, text='OK', width=6, command=self.ok_pressed).pack(side=RIGHT, padx=5, pady=5)
ttk.Button(self, text='Cancel', width=6, command=self.cancel_pressed).pack(side=RIGHT, padx=5, pady=5)
self.bind("<Return>", lambda event: self.ok_pressed())
self.bind("<Escape>", lambda event: self.cancel_pressed())
def ok_pressed(self):
data = {
'x': int('0' + self.x_entry.get()),
'y': int('0' + self.y_entry.get()),
'desc': self.desc_entry.get(),
}
if validate_entity(data):
self.result = data
self.destroy()
def cancel_pressed(self):
self.result = None
self.destroy()
def remove_data():
for item in ctx.data_tree.selection():
ctx.data_tree.delete(item)
def validate_data(data):
if data['id'] < 0 or data['id'] > 255:
messagebox.showerror('Data error', 'Invalid data ID (must be between 0 and 255)')
return False
if data['data'] < 0 or data['data'] > 255:
messagebox.showerror('Data error', 'Invalid data (must be between 0 and 255)')
return False
return True
def add_data(root):
d = MetadataDialog(root, 'Add data')
if d.result is None:
return
ctx.data_tree.insert('', END, values=(d.result['id'], d.result['data'], d.result['desc']))
def edit_data(root):
for i in ctx.data_tree.selection():
d = MetadataDialog(root, 'Edit data', ctx.data_tree.item(i)['values'])
if d.result is None:
continue
ctx.data_tree.item(i, values=(d.result['id'], d.result['data'], d.result['desc']))
def data_sort_key(a):
if a[0].isdecimal():
return int(a[0])
return a[0]
def data_sort(col, reverse):
items = [(ctx.data_tree.set(i, col), i) for i in ctx.data_tree.get_children('')]
items.sort(key=data_sort_key, reverse=reverse)
for index, (val, i) in enumerate(items):
ctx.data_tree.move(i, '', index)
heading = ctx.data_tree.heading(col)
ctx.data_tree.heading(col, command=lambda col=col: data_sort(col, not reverse))
class MetadataDialog(simpledialog.Dialog):
def __init__(self, parent, title='', data=None):
self.defaults = data
super().__init__(parent, title)
def body(self, master):
master.pack(expand=True, fill=BOTH, padx=5, pady=5)
ttk.Label(master, text='ID').grid(row=0, column=0, sticky=W, padx=5, pady=5)
ttk.Label(master, text='Value').grid(row=1, column=0, sticky=W, padx=5, pady=5)
ttk.Label(master, text='Description').grid(row=2, column=0, sticky=W, padx=5, pady=5)
self.id_entry = Spinbox(master, from_=0, to=255)
self.data_entry = Spinbox(master, from_=0, to=255)
self.desc_entry = ttk.Entry(master)
self.id_entry.grid(row=0, column=1, sticky=EW)
self.data_entry.grid(row=1, column=1, sticky=EW)
self.desc_entry.grid(row=2, column=1, sticky=EW)
if self.defaults is not None:
self.id_entry.delete(0)
self.id_entry.insert(0, str(self.defaults[0]))
self.data_entry.delete(0)
self.data_entry.insert(0, str(self.defaults[1]))
self.desc_entry.insert(0, self.defaults[2])
vcmd = (master.register(validate_number), '%S')
self.id_entry.configure(validate='key', validatecommand=vcmd)
self.data_entry.configure(validate='key', validatecommand=vcmd)
def buttonbox(self):
ttk.Button(self, text='OK', width=6, command=self.ok_pressed).pack(side=RIGHT, padx=5, pady=5)
ttk.Button(self, text='Cancel', width=6, command=self.cancel_pressed).pack(side=RIGHT, padx=5, pady=5)
self.bind("<Return>", lambda event: self.ok_pressed())
self.bind("<Escape>", lambda event: self.cancel_pressed())
def ok_pressed(self):
data = {
'id': int('0'+self.id_entry.get()),
'data': int('0'+self.data_entry.get()),
'desc': self.desc_entry.get(),
}
if validate_data(data):
self.result = data
self.destroy()
def cancel_pressed(self):
self.result = None
self.destroy()
class PropertiesDialog(simpledialog.Dialog):
def __init__(self, parent, title='Map properties'):
super().__init__(parent, title)
def body(self, master):
master.pack(expand=True, fill=BOTH)
ttk.Label(master, text='Map width').grid(row=0, column=0, sticky=SW, padx=5, pady=10)
ttk.Label(master, text='Map height').grid(row=1, column=0, sticky=SW, padx=5, pady=5)
ttk.Label(master, text='Entity size').grid(row=2, column=0, sticky=SW, padx=5, pady=5)
self.width_entry = Spinbox(master, from_=0, to=255)
self.height_entry = Spinbox(master, from_=0, to=255)
self.size_entry = Spinbox(master, from_=1, to=16380)
self.width_entry.delete(0)
self.width_entry.insert(0, str(ctx.width))
self.height_entry.delete(0)
self.height_entry.insert(0, str(ctx.height))
self.size_entry.delete(0)
self.size_entry.insert(0, str(ctx.entity_size))
vcmd = (master.register(validate_number), '%S')
self.width_entry.configure(validate='key', validatecommand=vcmd)
self.height_entry.configure(validate='key', validatecommand=vcmd)
self.size_entry.configure(validate='key', validatecommand=vcmd)
self.width_entry.grid(row=0, column=1, sticky=EW)
self.height_entry.grid(row=1, column=1, sticky=EW)
self.size_entry.grid(row=2, column=1, sticky=EW)
if len(ctx.tiles) == 0:
ttk.Label(master, text='Screen mode').grid(row=3, column=0, sticky=SW, padx=5, pady=5)
ttk.Label(master, text='Tile width').grid(row=4, column=0, sticky=SW, padx=5, pady=5)
ttk.Label(master, text='Tile height').grid(row=5, column=0, sticky=SW, padx=5, pady=5)
self.mode_entry = Spinbox(master, from_=0, to=2)
self.tile_width_entry = Spinbox(master, from_=1, to=384)
self.tile_height_entry = Spinbox(master, from_=1, to=512)
self.mode_entry.delete(0)
self.mode_entry.insert(0, str(ctx.mode))
self.tile_width_entry.delete(0)
self.tile_width_entry.insert(0, str(ctx.tile_width))
self.tile_height_entry.delete(0)
self.tile_height_entry.insert(0, str(ctx.tile_height))
self.mode_entry.configure(validate='key', validatecommand=vcmd)
self.tile_width_entry.configure(validate='key', validatecommand=vcmd)
self.tile_height_entry.configure(validate='key', validatecommand=vcmd)
self.mode_entry.grid(row=3, column=1, sticky=EW)
self.tile_width_entry.grid(row=4, column=1, sticky=EW)
self.tile_height_entry.grid(row=5, column=1, sticky=EW)
def buttonbox(self):
ttk.Button(self, text='OK', width=6, command=self.ok_pressed).pack(side=RIGHT, padx=5, pady=5)
ttk.Button(self, text='Cancel', width=6, command=self.cancel_pressed).pack(side=RIGHT, padx=5, pady=5)
self.bind("<Return>", lambda event: self.ok_pressed())
self.bind("<Escape>", lambda event: self.cancel_pressed())
def ok_pressed(self):
new_width = int('0' + self.width_entry.get())
new_height = int('0' + self.height_entry.get())
new_size = int('0' + self.size_entry.get())
if new_width < 0 or new_width > 255:
messagebox.showerror('Property error', 'Invalid map width (must be 0-255)')
return
if new_height < 0 or new_height > 255:
messagebox.showerror('Property error', 'Invalid map height (must be 0-255)')
return
if new_size < 1:
messagebox.showerror('Property error', 'Invalid entity size (must be greater than 0)')
return
if len(ctx.tiles) == 0:
new_mode = int('0' + self.mode_entry.get())
new_tile_width = int('0' + self.tile_width_entry.get())
new_tile_height = int('0' + self.tile_height_entry.get())
if new_mode < 0 or new_mode > 2:
messagebox.showerror('Property error', 'Invalid screen mode (must be 0, 1 or 2)')
return
pixels_per_byte = 2 if new_mode == 0 else (4 if new_mode == 1 else 8)
if new_tile_width % pixels_per_byte != 0 or new_tile_width < 1 or new_tile_height < 1:
messagebox.showerror('Property error', 'Tile size of %dx%d invalid for mode %d' %
(new_tile_width, new_tile_height, new_mode))
return
ctx.mode = new_mode
ctx.tile_width = new_tile_width
ctx.tile_height = new_tile_height
if new_width != ctx.width or new_height != ctx.height:
if new_width == 0 or new_height == 0:
ctx.reset()
else:
new_map = [0 for x in range(new_width * new_height)]
new_tags = [0 for x in range(new_width * new_height)]
new_notes = ['' for x in range(new_width * new_height)]
for y in range(0, min(ctx.height, new_height)):
for x in range(0, min(ctx.width, new_width)):
i = x * ctx.height + y
i2 = x * new_height + y
new_map[i2] = ctx.map[i]
new_tags[i2] = ctx.tags[i]
new_notes[i2] = ctx.notes[i]
ctx.map = new_map if len(ctx.tiles) > 0 else []
ctx.tags = new_tags
ctx.notes = new_notes
ctx.selection = None
update_selection()
ctx.width = new_width
ctx.height = new_height
if new_size != ctx.entity_size:
for entity in ctx.entities:
if new_size < ctx.entity_size:
entity[3] = entity[3][:new_size]
else:
entity[3] = entity[3] + [[0, ''] for x in range(new_size - ctx.entity_size)]
ctx.entity_size = new_size
ctx.entity_tree.delete(*ctx.entity_tree.get_children())
ctx.entity_data_tree.delete(*ctx.entity_data_tree.get_children())
for entity in ctx.entities:
ctx.entity_tree.insert('', END, values=(entity[0], entity[1], entity[2]))
refresh_ui()
self.destroy()
def cancel_pressed(self):
self.destroy()
def draw_entity(entity):
width_scale = (2 if ctx.mode == 0 else 1) * ctx.zoom
height_scale = (2 if ctx.mode == 2 else 1) * ctx.zoom
x = entity[0] * width_scale
y = entity[1] * height_scale
r = 4 * ctx.zoom
ctx.canvas.create_bitmap(x, y, background='red', foreground='white', bitmap='info', tags='entity')
#ctx.canvas.create_oval(x-r, y-r, x+r, y+r, outline='#5073fc', fill='#50c8fc', width=ctx.zoom, tags='entity')
def redraw_entities():
ctx.canvas.delete('entity')
if not ctx.draw_entities:
return
for entity in ctx.entities:
draw_entity(entity)
def redraw_grid():
ctx.canvas.delete('grid')
if not ctx.draw_grid:
return
width_scale = (2 if ctx.mode == 0 else 1) * ctx.zoom
height_scale = (2 if ctx.mode == 2 else 1) * ctx.zoom
dash = (2, 2)