-
Notifications
You must be signed in to change notification settings - Fork 15
/
Image_maps_to_frames.py
2430 lines (2056 loc) · 96.3 KB
/
Image_maps_to_frames.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
import functools
import collections
import copy
import uuid
import struct
import math
import PyMCTranslate
from amulet_map_editor.api.wx.ui.block_select import BlockDefine
from amulet_map_editor.api.wx.ui.version_select import VersionSelect
from collections import namedtuple
from typing import TYPE_CHECKING, Tuple, List
from math import ceil
import io
from PIL import Image
import wx
import os
from os import path
from amulet_nbt import *
from amulet.api.selection import SelectionBox
import numpy
from amulet.api.block_entity import BlockEntity
from amulet.api.selection import SelectionGroup
from amulet_map_editor.programs.edit.api.operations import DefaultOperationUI
from amulet_map_editor.programs.edit.api.behaviour import PointerBehaviour
from amulet_map_editor.programs.edit.api.behaviour import StaticSelectionBehaviour
from amulet_map_editor.programs.edit.api.key_config import ACT_BOX_CLICK
from amulet.utils import block_coords_to_chunk_coords
from amulet.utils import chunk_coords_to_region_coords
from amulet.api.block import Block
from amulet.level.formats.anvil_world.region import AnvilRegion
from pathlib import Path
from amulet_map_editor.programs.edit.api.events import (
InputPressEvent,
EVT_INPUT_PRESS,
)
from amulet_map_editor.programs.edit.api.behaviour.pointer_behaviour import (
PointerBehaviour,
EVT_POINT_CHANGE,
PointChangeEvent,
)
from amulet_map_editor.api.wx.ui.block_select.properties import (
PropertySelect,
WildcardSNBTType,
EVT_PROPERTIES_CHANGE,
)
from amulet_map_editor.programs.edit.api.events import (
EVT_SELECTION_CHANGE,
)
class CustomRadioBox(wx.Panel):
def __init__(self, parent, label, choices, foreground_color, sty=None, md=1):
super().__init__(parent)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.label = wx.StaticText(self, label=label)
self.label.SetForegroundColour(foreground_color)
self.sizer.Add(self.label, 0, wx.ALL, 5)
self.radio_buttons = []
self.radio_buttons_map = {}
if sty == wx.RA_SPECIFY_ROWS:
self.radio_sizer = wx.FlexGridSizer(rows=md, cols=(len(choices) + md - 1) // md, vgap=5, hgap=5)
elif sty == wx.RA_SPECIFY_COLS:
self.radio_sizer = wx.FlexGridSizer(rows=(len(choices) + md - 1) // md, cols=md, vgap=5, hgap=5)
else:
self.radio_sizer = wx.BoxSizer(wx.VERTICAL if md == 1 else wx.HORIZONTAL)
for i, choice in enumerate(choices):
style = wx.RB_GROUP if i == 0 else 0
radio_btn = wx.RadioButton(self, label=choice, style=style)
radio_btn.SetForegroundColour(foreground_color)
self.radio_sizer.Add(radio_btn, 0, wx.ALL, 5)
self.radio_buttons.append(radio_btn)
self.radio_buttons_map[radio_btn] = i
self.sizer.Add(self.radio_sizer, 0, wx.ALL, 5)
self.SetSizer(self.sizer)
def GetString(self, index):
if 0 <= index < len(self.radio_buttons):
return self.radio_buttons[int(index)].GetLabel()
def SetSelection(self, index):
if 0 <= index < len(self.radio_buttons):
self.radio_buttons[int(index)].SetValue(True)
def GetSelection(self):
for index, radio_btn in enumerate(self.radio_buttons):
if radio_btn.GetValue():
return index
return None
class ProgressBar:
def __init__(self):
self.parent = None
self.prog = None
self.pos_start = False
def progress_bar(self, total, cnt, title=None, text=None, update_interval=50):
"""Manage progress bar updates."""
if self.prog and self.prog.WasCancelled():
self.stop()
return True
update, start = False, False
if cnt > 0:
cnt -= 1
self.pos_start = True
if cnt == 0:
start = True
update = False
elif cnt > 0:
start = False
update = True
if self.pos_start:
cnt += 1
if start:
self.start_progress(total, cnt, title, text, update_interval)
return None
if update:
if self.prog and self.prog.WasCancelled():
self.stop()
return True
else:
return self.update_progress(cnt, total, title, text, update_interval)
return False
def stop(self):
if self.prog:
self.prog.Hide()
self.prog.Destroy()
return True
def start_progress(self, total, cnt, title, text, update_interval):
"""Start the progress dialog."""
if total > update_interval:
self.prog = wx.ProgressDialog(
f"{title}",
f"{text}: {cnt} / {total}\n ", total,
style=wx.PD_AUTO_HIDE | wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME,
parent=self.parent
)
self.prog.Show(True)
def update_progress(self, cnt, total, title, text, update_interval):
"""Update the progress dialog."""
if cnt % update_interval == 0 or cnt == total:
if self.prog:
if self.prog.WasCancelled():
self.prog.Destroy()
return True
else:
self.prog.Update(cnt, f"{text}: {cnt} / {total}\n ")
return False
def scale_bitmap(bitmap, width, height):
image = bitmap.ConvertToImage()
image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)
return wx.Bitmap(image)
class ImportImageSettings(wx.Frame):
def __init__(self, parent, world=None):
super(ImportImageSettings, self).__init__(parent, title="Import Settings", size=(300,600), style=wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP)
parent_position = parent.GetScreenPosition()
self.world = world
self.SetPosition(parent_position + (50, 50))
self.parent = parent
self.font = wx.Font(14, wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
self.SetFont(self.font)
self.SetForegroundColour((0, 255, 0))
self.SetBackgroundColour((0, 0, 0))
# Color picker control
self.transparent_border = wx.CheckBox(self, label="Transparent Border?")
self.transparent_border.Bind(wx.EVT_CHECKBOX, self.is_color_picker_visable)
self.transparent_border.SetValue(True)
self.color_picker_label = wx.StaticText(self, label="Select A Color For Border:")
self.color_picker = wx.ColourPickerCtrl(self, size=(150, 40))
self.selected_file = wx.StaticText(self, label=" ( Dont Select File if Reusing Custom Maps )\n"
"No File Selected")
self.selected_block = wx.StaticText(self, label=str(self.parent.selected_block))
self.ok_btn = wx.Button(self, label="OK")
self.ok_btn.Bind(wx.EVT_BUTTON, self.done)
# Custom radio box for frame type
self.rb_frame_type = CustomRadioBox(self, 'Frame type?', self.parent.frame_types, (0, 255, 0), md=2)
# Image file selection button
self._set_images_on_frames = wx.Button(self, size=(160, 40), label="Select Image File")
self._set_images_on_frames.Bind(wx.EVT_BUTTON, self.open_file_dialof)
# Block type selection button
self.apply_back_block = wx.Button(self, size=(160, 40), label="Select Backing Block")
self.apply_back_block.Bind(wx.EVT_BUTTON, self.parent.apply_backblock)
# Bind close event
self.Bind(wx.EVT_CLOSE, self.on_close)
# Layout
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.color_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(self.sizer)
self.mode_sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self._set_images_on_frames, 0, wx.LEFT, 10)
self.sizer.Add(self.selected_file, 0, wx.LEFT, 10)
self.sizer.Add(self.apply_back_block, 0, wx.LEFT, 10)
self.sizer.Add(self.selected_block, 0, wx.LEFT, 10)
if self.world.level_wrapper.platform == 'java':
modes = ["Fast","Better","Lab(slow closer)"]
self.color_find_modes = CustomRadioBox(self, 'How to Match Colors?', modes, (0, 255, 0), md=2)
self.fixed_frame = wx.CheckBox(self, label="Fixed Frames No Backing Block Required")
self.invisible_frames = wx.CheckBox(self, label="Make Item Frames Invisible")
self.fixed_frame.SetValue(True)
self.invisible_frames.SetValue(True)
self.sizer.Add(self.fixed_frame, 0, wx.LEFT, 10)
self.sizer.Add(self.invisible_frames, 0, wx.LEFT, 10)
self.mode_sizer.Add(self.color_find_modes, 0, wx.LEFT, 10)
self.sizer.Add(self.rb_frame_type, 0, wx.LEFT, 50)
self.mode_sizer.Add(self.transparent_border, 0, wx.LEFT, 10)
self.color_sizer.Add(self.color_picker_label, 0, wx.LEFT, 0)
self.color_sizer.Add(self.color_picker, 0, wx.LEFT, 0)
self.sizer.Add(self.mode_sizer)
self.sizer.Add(self.color_sizer, 0, wx.LEFT, 10)
self.sizer.Add(self.ok_btn, 0, wx.LEFT, 150)
self.sizer.Hide(self.color_sizer)
self.sizer.Hide(self.mode_sizer)
self.Layout()
self.Fit()
def on_close(self, _):
if self.world.level_wrapper.platform == 'java':
self.java_options()
color = self.color_picker.GetColour()
# Update parent frame type and color properties
self.parent.rb_frame_type = self.rb_frame_type.GetString(self.rb_frame_type.GetSelection())
if self.transparent_border.IsChecked():
self.parent.color = (0, 0, 0, 0)
else:
self.parent.color = (color.Red(), color.Green(), color.Blue(), 255)
self.Destroy()
if self.parent.selected_file:
self.parent.set_images_on_frames(None)
def done(self, _):
# Similar to on_close, handles OK button press
self.on_close(None)
def is_color_picker_visable(self,_):
if self.transparent_border.IsChecked():
self.sizer.Hide(self.color_sizer)
else:
self.sizer.Show(self.color_sizer)
self.Fit() # Adjust the frame size to fit the new layout
def java_options(self):
self.parent.fixed_frame = self.fixed_frame.GetValue()
self.parent.invisible_frames = self.invisible_frames.GetValue()
selection = self.color_find_modes.GetSelection()
if selection == 1:
self.parent.map_data_manager.color_match_mode = 'closer'
elif selection == 2:
self.parent.map_data_manager.color_match_mode = 'lab'
else:
self.parent.map_data_manager.color_match_mode = None # fast default
def open_file_dialof(self, _):
with wx.FileDialog(self, "Open Image file", wildcard="*", style=wx.FD_OPEN) as file_dialog:
if file_dialog.ShowModal() == wx.ID_CANCEL:
return
else:
self.selected_file.SetLabel(file_dialog.GetPath())
self.parent.selected_file = file_dialog.GetPath()
self.sizer.Show(self.mode_sizer)
self.Fit()
self.Layout()
def GetSelectedFrame(self):
return self.rb_frame_type
def GetSelectedBlock(self):
pass
def SetBlock(self, text):
self.selected_block.SetLabel(text)
class BuildWallSettings(wx.Frame):
def __init__(self, parent, maps_img_data, world=None):
super(BuildWallSettings, self).__init__(parent, title="Map Wall Settings", size=(300,300),
style=wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP)
parent_position = parent.GetScreenPosition()
self.world = world
self.maps_img_data = maps_img_data
self.SetPosition(parent_position + (50, 50))
self.parent = parent
self.font = wx.Font(16, wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
self.SetFont(self.font)
self.SetForegroundColour((0, 255, 0))
self.SetBackgroundColour((0, 0, 0))
self.vsizer = wx.BoxSizer(wx.VERTICAL)
self.label_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.input_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.vsizer.Add(self.label_sizer)
self.vsizer.Add(self.input_sizer)
self.vsizer.Add(self.button_sizer)
self.label_col = wx.StaticText(self, label="Height: ")
self.label_row = wx.StaticText(self, label="Width: ")
self.label_sizer.Add(self.label_col,0,wx.LEFT,5)
self.label_sizer.Add(self.label_row,0,wx.LEFT,35)
self.text_cols = wx.TextCtrl(self, size=(120, 30))
self.text_rows = wx.TextCtrl(self, size=(120, 30))
self.input_sizer.Add(self.text_cols,0,wx.LEFT,5)
self.input_sizer.Add(self.text_rows,0,wx.LEFT,15)
self.text_cols.SetValue('4')
self.text_rows.SetValue('4')
self.ok_btn = wx.Button(self, label="OK")
self.ok_btn.Bind(wx.EVT_BUTTON, self.done)
self.button_sizer.Add(self.ok_btn)
self.SetSizer(self.vsizer)
self.Layout()
self.Fit()
self.Show()
def done(self, _):
cols, rows = int(self.text_cols.GetValue()),int(self.text_rows.GetValue())
BuildMapWall(cols, rows, self.maps_img_data, parent=self.parent)
self.Close()
class JavaMapColorsResolver:
def __init__(self):
self.MAP_SHADE_MODIFIERS = [180, 220, 255, 135]
self.map_colors = [
(0, 0, 0, 0), (127, 178, 56, 255), (247, 233, 163, 255),
(199, 199, 199, 255), (255, 0, 0, 255), (160, 160, 255, 255),
(167, 167, 167, 255), (0, 124, 0, 255), (255, 255, 255, 255),
(164, 168, 184, 255), (151, 109, 77, 255), (112, 112, 112, 255),
(64, 64, 255, 255), (143, 119, 72, 255), (255, 252, 245, 255),
(216, 127, 51, 255), (178, 76, 216, 255), (102, 153, 216, 255),
(229, 229, 51, 255), (127, 204, 25, 255), (242, 127, 165, 255),
(76, 76, 76, 255), (153, 153, 153, 255), (76, 127, 153, 255),
(127, 63, 178, 255), (51, 76, 178, 255), (102, 76, 51, 255),
(102, 127, 51, 255), (153, 51, 51, 255), (25, 25, 25, 255),
(250, 238, 77, 255), (92, 219, 213, 255), (74, 128, 255, 255),
(0, 217, 58, 255), (129, 86, 49, 255),
# Colors added in version 1.12
(112, 2, 0, 255), (209, 177, 161, 255), (159, 82, 36, 255),
(149, 87, 108, 255), (112, 108, 138, 255), (186, 133, 36, 255),
(103, 117, 53, 255), (160, 77, 78, 255), (57, 41, 35, 255),
(135, 107, 98, 255), (87, 92, 92, 255), (122, 73, 88, 255),
(76, 62, 92, 255), (76, 50, 35, 255), (76, 82, 42, 255),
(142, 60, 46, 255), (37, 22, 16, 255),
# Colors added in version 1.16
(189, 48, 49, 255), (148, 63, 97, 255), (92, 25, 29, 255),
(22, 126, 134, 255), (58, 142, 140, 255), (86, 44, 62, 255),
(20, 180, 133, 255), (100, 100, 100, 255), (216, 175, 147, 255),
(127, 167, 150, 255)
]
self.map_colors_shaded = self.generate_shaded_colors()
def generate_shaded_colors(self) -> numpy.ndarray:
return numpy.array([
[
(r * shade) // 255,
(g * shade) // 255,
(b * shade) // 255,
a
]
for r, g, b, a in self.map_colors
for shade in self.MAP_SHADE_MODIFIERS
])
# Helper function to convert RGB to XYZ color space using numpy
def rgb_to_xyz_np(self, rgb):
# Normalize the RGB values to [0, 1]
rgb = rgb / 255.0
# Apply sRGB companding (inverse gamma correction)
mask = rgb > 0.04045
rgb[mask] = ((rgb[mask] + 0.055) / 1.055) ** 2.4
rgb[~mask] = rgb[~mask] / 12.92
# Convert to XYZ using the sRGB matrix
matrix = numpy.array([[0.4124, 0.3576, 0.1805],
[0.2126, 0.7152, 0.0722],
[0.0193, 0.1192, 0.9505]])
xyz = numpy.dot(rgb, matrix.T)
return xyz
# Helper function to convert XYZ to Lab color space using numpy
def xyz_to_lab_np(self,xyz):
# Reference white point (D65)
ref_white = numpy.array([0.95047, 1.00000, 1.08883])
xyz = xyz / ref_white
# Convert to Lab
epsilon = 0.008856
kappa = 903.3
mask = xyz > epsilon
xyz[mask] = numpy.cbrt(xyz[mask])
xyz[~mask] = (kappa * xyz[~mask] + 16) / 116
L = 116 * xyz[:, 1] - 16
a = 500 * (xyz[:, 0] - xyz[:, 1])
b = 200 * (xyz[:, 1] - xyz[:, 2])
return numpy.stack([L, a, b], axis=1)
# Function to compute CIE76 color difference using numpy
def cie76_np(self, lab1, lab2):
return numpy.sqrt(numpy.sum((lab1 - lab2) ** 2, axis=1))
def find_closest_java_color_fast(self, rr: int, gg: int, bb: int, aa: int) -> int:
cr = self.map_colors_shaded[:, 0]
cg = self.map_colors_shaded[:, 1]
cb = self.map_colors_shaded[:, 2]
ca = self.map_colors_shaded[:, 3]
# Calculate the weighted differences
r_diff = (cr * 0.71 - rr * 0.71) ** 2
g_diff = (cg * 0.86 - gg * 0.986) ** 2
b_diff = (cb * 0.654 - bb * 0.754) ** 2
a_diff = (ca * 0.53 - aa * 0.53) ** 2
# Calculate the score
score = r_diff + g_diff + b_diff + a_diff
# Find the index with the minimum score
min_index = numpy.argmin(score)
return int(min_index)
def find_closest_java_color_closer(self, rr: int, gg: int, bb: int, aa: int) -> int:
cr = self.map_colors_shaded[:, 0]
cg = self.map_colors_shaded[:, 1]
cb = self.map_colors_shaded[:, 2]
ca = self.map_colors_shaded[:, 3]
rmean = (cr + rr) // 2
r = cr - rr
g = cg - gg
b = cb - bb
a = ca - aa
score = numpy.sqrt((((512 + rmean) * r * r) >> 8) + (4 * g * g ) + (((747 - rmean) * b * b) >> 8) + a)
min_index = numpy.argmin(score)
return int(min_index)
def find_closest_java_color_lab(self, rr: int, gg: int, bb: int, aa: int) -> int:
# Convert the target color to Lab
target_rgb = numpy.array([rr, gg, bb])
target_xyz = self.rgb_to_xyz_np(target_rgb)
target_lab = self.xyz_to_lab_np(numpy.array([target_xyz]))
# Convert all candidate colors to Lab
candidate_rgb = self.map_colors_shaded[:, :3] # Ignore alpha for color comparison
candidate_xyz = self.rgb_to_xyz_np(candidate_rgb)
candidate_lab = self.xyz_to_lab_np(candidate_xyz)
# Calculate CIE76 color differences
distances = self.cie76_np(candidate_lab, target_lab)
# Find the index of the minimum distance
min_index = numpy.argmin(distances)
return int(min_index)
def from_chunker_colors(self, chunker_map_colors: bytes, mode=None) -> bytes:
output_bytes = bytearray(len(chunker_map_colors) // 4)
for i in range(0, len(chunker_map_colors), 4):
r = chunker_map_colors[i] & 0xFF
g = chunker_map_colors[i + 1] & 0xFF
b = chunker_map_colors[i + 2] & 0xFF
a = chunker_map_colors[i + 3] & 0xFF
if mode == 'lab':
output_bytes[i // 4] = self.find_closest_java_color_lab(r, g, b, a)
elif mode == 'closer':
output_bytes[i // 4] = self.find_closest_java_color_closer(r, g, b, a)
else:
output_bytes[i // 4] = self.find_closest_java_color_fast(r, g, b, a)
return bytes(output_bytes)
def to_java_colors(self, java_map_colors: bytes) -> bytes:
output_bytes = bytearray(len(java_map_colors) * 4)
for i, value in enumerate(java_map_colors):
if 0 <= value < len(self.map_colors_shaded):
rgba = self.map_colors_shaded[value]
new_index = i * 4
output_bytes[new_index] = rgba[0]
output_bytes[new_index + 1] = rgba[1]
output_bytes[new_index + 2] = rgba[2]
output_bytes[new_index + 3] = rgba[3]
return bytes(output_bytes)
class ImageGridManager(wx.StaticBitmap):
def __init__(self, parent, bitmap, img_id, grid):
super().__init__(parent, bitmap=bitmap)
self.parent = parent
self.img_id = img_id
self.grid = grid
self.pos_in_grid = None
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftClick)
def OnLeftClick(self, event):
if self.pos_in_grid is None:
self.grid.PlaceImageInFirstAvailableSlot(self)
else:
self.grid.RemoveImageFromGrid(self)
def Copy(self):
# Create a copy of the image
return ImageGridManager(self.parent, self.GetBitmap(), self.img_id, self.grid)
class ImageGrid(wx.Panel):
def __init__(self, parent, rows, cols):
super().__init__(parent)
self.rows = rows
self.cols = cols
self.sizer = wx.GridSizer(rows, cols, 0, 0)
self.SetSizer(self.sizer)
self.image_positions = {}
for i in range(rows * cols):
placeholder = wx.Panel(self, size=(120, 120))
placeholder.SetBackgroundColour(wx.Colour(200, 200, 200))
self.sizer.Add(placeholder, 0, wx.ALL | wx.EXPAND, 1)
self.image_positions[i] = placeholder
def PlaceImageInFirstAvailableSlot(self, image):
# Check if image is already placed in the grid
if image.pos_in_grid is not None:
return
available_slot_found = False
for i in range(self.rows * self.cols):
if isinstance(self.image_positions[i], wx.Panel): # Placeholder check
available_slot_found = True
break
if not available_slot_found:
# Handle case where the grid is full
wx.MessageBox("The grid is full. Cannot place more images.", "Error", wx.ICON_ERROR)
return
# Create a copy of the image and add it to the grid
copied_image = image.Copy()
copied_image.Hide()
self.AddImageToGrid(copied_image)
def AddImageToGrid(self, image, from_last=False):
# Get grid cell size dynamically
grid_width, grid_height = self.get_grid_cell_size()
# Resize the image before adding it to the grid, keeping the img_id intact
resized_image = self.resize_image_to_fit_grid(image.GetBitmap(), grid_width, grid_height, image.img_id)
# Remove image from any existing sizer (including the ImageSourcePanel)
if image.GetContainingSizer() is not None:
image.GetContainingSizer().Detach(image)
# Reparent the resized image to the grid's panel
resized_image.Reparent(self)
if from_last:
for i in range(self.rows * self.cols - 1, -1, -1):
if isinstance(self.image_positions[i], wx.Panel): # Placeholder check
self.sizer.Hide(self.image_positions[i]) # Hide the placeholder
self.image_positions[i] = resized_image
# Add the resized image to the grid's sizer
self.sizer.Replace(self.sizer.GetChildren()[i].GetWindow(), resized_image)
resized_image.pos_in_grid = i
self.sizer.Layout()
break
else:
for i in range(self.rows * self.cols):
if isinstance(self.image_positions[i], wx.Panel): # Placeholder check
self.sizer.Hide(self.image_positions[i]) # Hide the placeholder
self.image_positions[i] = resized_image
# Add the resized image to the grid's sizer
self.sizer.Replace(self.sizer.GetChildren()[i].GetWindow(), resized_image)
resized_image.pos_in_grid = i
self.sizer.Layout()
break
def get_grid_cell_size(self):
# Dynamically retrieve the size of a single grid cell
grid_size = self.GetSize()
rows, cols = self.rows, self.cols
grid_width = grid_size.GetWidth() // cols
grid_height = grid_size.GetHeight() // rows
return grid_width, grid_height
def resize_image_to_fit_grid(self, bitmap, grid_width, grid_height, img_id):
# Convert the bitmap to wx.Image, resize it, and convert it back to wx.Bitmap
img = bitmap.ConvertToImage()
img = img.Rescale(grid_width, grid_height, wx.IMAGE_QUALITY_HIGH)
resized_bitmap = wx.Bitmap(img)
# Return a new ImageGridManager with the resized bitmap, preserving the img_id
return ImageGridManager(self.GetParent(), resized_bitmap, img_id=img_id, grid=self)
def RemoveImageFromGrid(self, image):
if image.pos_in_grid is not None:
pos = image.pos_in_grid
self.sizer.Hide(image)
placeholder = wx.Panel(self, size=(120, 120))
placeholder.SetBackgroundColour(wx.Colour(200, 200, 200))
self.image_positions[pos] = placeholder
self.sizer.Replace(image, placeholder)
image.pos_in_grid = None
self.sizer.Layout()
class ImageSourcePanel(wx.ScrolledWindow):
def __init__(self, parent, grid):
super().__init__(parent)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.sizer)
self.SetScrollRate(5, 5)
self.grid = grid
def AddImage(self, bitmap, img_id):
img = ImageGridManager(self, bitmap, img_id, self.grid)
self.sizer.Add(img, 0, wx.ALL, 5)
self.Layout()
self.FitInside()
class BuildMapWall(wx.Frame):
def __init__(self, col, rows, map_img_list, parent=None):
super().__init__(parent=None, title="Build Map Wall", size=(800, 800),
style=wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP)
self.parent = parent
panel = wx.Panel(self)
parent_position = parent.GetScreenPosition()
self.SetPosition(parent_position + (50, 50))
self.font = wx.Font(16, wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
self.SetFont(self.font)
self.SetForegroundColour((0, 255, 0))
self.SetBackgroundColour((0, 0, 0))
self.grid_rows = col
self.grid_cols = rows
self.grid = ImageGrid(panel, self.grid_rows, self.grid_cols)
self.image_source = ImageSourcePanel(panel, self.grid)
for map_image, map_id in map_img_list:
self.image_source.AddImage(map_image, map_id)
self.image_source.SetMinSize((160, 168))
get_image_order = wx.Button(panel, size=(80, 50), label="Apply")
get_image_order.Bind(wx.EVT_BUTTON, self.GetImageOrder)
_close = wx.Button(panel, size=(80, 50), label="Close")
_close.Bind(wx.EVT_BUTTON, self.close)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox = wx.BoxSizer(wx.HORIZONTAL)
hbox.Add(self.image_source, 0, wx.EXPAND | wx.ALL, 5)
hbox.Add(self.grid, 5, wx.EXPAND | wx.ALL, 0)
vbox.Add(hbox, 10, wx.EXPAND | wx.ALL, 0)
vbox.Add(get_image_order, 0, wx.CENTER, 0)
panel.SetSizer(vbox)
self.Show()
def close(self, ):
self.Close()
def GetImageOrder(self, _):
map_order_list = []
for i in range(self.grid_rows * self.grid_cols):
if self.grid.image_positions.get(i, None):
if hasattr(self.grid.image_positions.get(i), 'img_id'):
map_order_list.append(self.grid.image_positions.get(i).img_id)
else:
map_order_list.append(None)
self.parent.custom_map_wall = (map_order_list,self.grid_rows , self.grid_cols)
if None in map_order_list:
wx.MessageBox(f"The Grid need to be full",
"Can Not Apply",
wx.OK | wx.ICON_ERROR)
return
self.parent.custom_map_wall_add()
self.Close()
class JavaMapData:
facing = {
"Facing Down": 0,
"Facing Up": 1,
"Facing North": 2,
"Facing South": 3,
"Facing West": 4,
"Facing East": 5,
}
pointing = {
"Flip Right": 0,
"Flip Left": 1,
"Up (Like Preview)": 2,
"Upside Down": 3
}
def __init__(self, parent=None, canvas=None, world=None):
self.parent = parent
self.world = world
self.canvas = canvas
self.map_data_converter = JavaMapColorsResolver()
self.color_match_mode = None
self.maps_path = os.path.join(self.world.level_wrapper.path, 'data')
self.cols_rows = (0, 0)
self.progress = ProgressBar()
self.maps_tobe = {}
self.c_map_counts = -1
self.maps_tobe_color_ready = []
self.custom_map_tobe = {}
self.all_map = {}
self.custom_map = {}
self.temp_new_custom_keys = []
self.temp_new_map_keys = []
self.load_all_maps()
def convert_images(self):
maps_tobe_new = []
total = len(self.maps_tobe)
cnt = 0
for v in self.maps_tobe:
cnt += 1
stop = self.progress.progress_bar(total, cnt, update_interval=1, title="Converting Image to Java Image Preview",
text=f"Processing...")
if stop:
return
java_colors = self.map_data_converter.from_chunker_colors(v[0], mode=self.color_match_mode)
java_rgba = self.map_data_converter.to_java_colors(java_colors)
maps_tobe_new.append((java_rgba,v[1], v[2]))
self.maps_tobe_color_ready.append((java_colors,v[1], v[2]))
self.maps_tobe = maps_tobe_new
def get_map_img(self, img_bytes):
colors = self.map_data_converter.to_java_colors(bytes(img_bytes))
bb = wx.Bitmap.FromBufferRGBA(128, 128, colors)
img = scale_bitmap(bb, 128,128)
return img
def apply(self, map_key_list=None):
if not map_key_list:
map_key_list = self.apply_compund_maps()
self.java_region_data_apply()
self.custom_map_location_entry(map_key_list)
wx.MessageBox(
f'Amulet does not render Item Frames.\n'
f'They will be where you placed them.\n'
f'Also note: You can reuse this by selecting\n'
f'{self.custom_key_str} from the custom maps list.\n'
f'After clicking ok this will auto select your custom map'
f'Click once somewhere in the world\n'
f'to trigger mouse move selection.',
"Operation Completed",
wx.OK | wx.ICON_INFORMATION
)
self.refresh_all()
self.parent._custom_map_list.Clear()
self.parent._custom_map_list.AppendItems([x for x in self.custom_map.keys()])
self.parent._custom_map_list.SetStringSelection(self.custom_key_str)
self.parent._custom_event = wx.CommandEvent(wx.EVT_LISTBOX.evtType[0], self.parent._custom_map_list.GetId())
self.parent._custom_event.SetEventObject(self.parent._custom_map_list)
self.parent._custom_map_list.GetEventHandler().ProcessEvent(self.parent._custom_event)
def get_block_placement_offset(self, xx, yy, zz):
facing = self.parent.facing.GetSelection()
block_offset = {
0: (0, -1, 0),
# Facing Up
1: (0, 1, 0),
# Facing North
2: (0, 0, -1),
# Facing South
3: (0, 0, 1),
# Facing West
4: (-1, 0, 0),
# Facing East
5: (1, 0, 0)
}
x, y, z = block_offset[facing]
return xx - x, yy - y, zz - z
def get_item_rotation(self):
pointing, facing = self.parent.pointing.GetSelection(), self.parent.facing.GetSelection()
rotation_data = {
# Facing Down
(0, 0): (0, 6, [0, 90]), # North or Right
(0, 1): (0, 5, [0, 90]), # East or Left
(0, 2): (0, 4, [0, 90]), # South or Up
(0, 3): (0, 7, [0, 90]), # West or Down
# Facing Up
(1, 0): (1, 0, [0, -90]), # North or Right
(1, 1): (1, 5, [0, -90]), # East or Left
(1, 2): (1, 2, [0, -90]), # South or Up
(1, 3): (1, 7, [0, -90]), # West or Down
# Facing North
(2, 0): (2, 5, [180, 0]), # North or Right
(2, 1): (2, 7, [180, 0]), # East or Left
(2, 2): (2, 4, [180, 0]), # South or Up
(2, 3): (2, 6, [180, 0]), # West or Down
# Facing South
(3, 0): (3, 5, [180, 0]), # North or Right
(3, 1): (3, 7, [180, 0]), # East or Left
(3, 2): (3, 4, [180, 0]), # South or Up
(3, 3): (3, 6, [180, 0]), # West or Down
# Facing West
(4, 0): (4, 5, [0, 0]), # North or Right
(4, 1): (4, 7, [90, 0]), # East or Left
(4, 2): (4, 4, [90, 0]), # South or Up
(4, 3): (4, 6, [90, 0]), # West or Down
# Facing East
(5, 0): (5, 1, [270, 0]), # North or Right
(5, 1): (5, 7, [270, 0]), # East or Left
(5, 2): (5, 4, [270, 0]), # South or Up
(5, 3): (5, 6, [270, 0]), # West or Down
}
_facing, _item_rotation, (rx, ry) = rotation_data[(facing, pointing)]
return ByteTag(_facing), ByteTag(_item_rotation), ListTag([FloatTag(rx),FloatTag(ry)])
def get_dim_vpath_java_dir(self, regonx, regonz, folder='region'): # entities
file = "r." + str(regonx) + "." + str(regonz) + ".mca"
path = self.world.level_wrapper.path
full_path = ''
dim = ''
if 'minecraft:the_end' in self.canvas.dimension:
dim = 'DIM1'
elif 'minecraft:the_nether' in self.canvas.dimension:
dim = 'DIM-1'
elif 'minecraft:overworld' in self.canvas.dimension:
dim = ''
full_path = os.path.join(path, dim, folder, file)
return full_path
def custom_map_location_entry(self, maps_keys: list[str]):
idcounts_dat = os.path.join(self.maps_path,'idcounts.dat')
count_data = None
if os.path.exists(idcounts_dat):
count_data = load(idcounts_dat)
count = count_data['data'].get('map').py_int
count += len(maps_keys)
count_data['data']['map'] = IntTag(count)
else:
count_data = CompoundTag({
'data': CompoundTag({
'map': IntTag(len(maps_keys))}),
'DataVersion': IntTag(self.world.level_wrapper.version)
})
count_data.save_to(idcounts_dat, compressed=True, little_endian=False,
string_encoder=utf8_encoder)
custom_pre_fix = self.get_available_custom_key
self.custom_key_str = custom_pre_fix + ":" + self.parent.custom_map_name.GetValue()
custom_path_file = os.path.join(self.maps_path, f'{custom_pre_fix}.dat')
pointing = self.parent.pointing.GetSelection()
facing = self.parent.facing.GetSelection()
cols, rows = self.cols_rows
nbt_maps = [StringTag(m) for m in maps_keys]
x, y, z = self.canvas.camera.location
xz, yy = self.canvas.camera.rotation
sg = self.canvas.selection.selection_group
(sx, sy, sg), (xs, xy, xg) = sg.min, sg.max
c_data = CompoundTag({
"name": StringTag(self.custom_key_str),
"pointing": IntTag(pointing),
"facing": IntTag(facing),
"cols": IntTag(cols),
"rows": IntTag(rows),
"map_list": ListTag(nbt_maps),
"dimension": StringTag(self.canvas.dimension),
"rotation": IntArrayTag([xz, yy]),
"location": IntArrayTag([x, y, z]),
"selectionGp": IntArrayTag([sx, sy, sg, xs, xy, xg])
})
c_data.save_to(custom_path_file, compressed=True, little_endian=False,
string_encoder=utf8_encoder)
return self.custom_key_str
def get_map_colors(self, map_name):
nbt = load(self.all_map[map_name])
colors = nbt['data'].get('colors', None)
name = map_name
map_id = int(name[4:])
self.maps_tobe_color_ready.append((name, map_id, name))
rgba_colors = self.map_data_converter.to_java_colors(bytes(colors.py_data))
return rgba_colors
def get_custom_map_nbt(self, selection):
custom_data = load(self.custom_map[selection])
return custom_data
def item_frame_entitle(self, item_map_id, position):
fixed_frame, invisible_frame = 0,0
if self.parent.fixed_frame:
fixed_frame = 1
if self.parent.invisible_frames:
invisible_frame = 1
cord_pos = {
0: (0.5, 0.03125, 0.5),
1: (0.5, 0.96875, 0.5),
2: (0.5, 0.5, 0.03125),
3: (0.5, 0.5, 0.96875), #96875
4: (0.03125, 0.5, 0.5),
5: (0.96875, 0.5, 0.5)
}
facing, item_rotation, rotation = self.get_item_rotation()
item_name = None
if self.parent.rb_frame_type == "Regular Frame":
item_name = 'minecraft:item_frame'
elif self.parent.rb_frame_type == "Glow Frame":
item_name = 'minecraft:glow_item_frame'
x,y,z = position
if x >= 0:
x = x + cord_pos[facing.py_int][0]
else:
x = -(abs(x) + cord_pos[facing.py_int][0])
# Handle y-coordinate
if y >= 0:
y = y + cord_pos[facing.py_int][1]
else:
y = -(abs(y) + cord_pos[facing.py_int][1])
# Handle z-coordinate
if z >= 0:
z = z + cord_pos[facing.py_int][2]
else:
z = -(abs(z) + cord_pos[facing.py_int][2])
print(x,y,z, position)
entitle_compound = CompoundTag({
'Motion': ListTag([DoubleTag(0), DoubleTag(0), DoubleTag(0)]),
'Facing': facing,
'ItemRotation': item_rotation,
'Invulnerable': ByteTag(0),
'Air': ShortTag(300),
'OnGround': ByteTag(0),
'PortalCooldown': IntTag(0),
'Rotation': rotation,
'FallDistance': FloatTag(0),
'Item': CompoundTag({
'components': CompoundTag({
"minecraft:map_id": IntTag(item_map_id)
}),
'count': ByteTag(1),
'id': StringTag("minecraft:filled_map")
}),
'ItemDropChance': FloatTag(1),
'Pos': ListTag([DoubleTag(x), DoubleTag(y), DoubleTag(z)]),
'Fire': ShortTag(-1),
'TileY': IntTag(y),