-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfirestaff_savegame_editor.py
More file actions
1424 lines (1281 loc) Β· 66.4 KB
/
Copy pathfirestaff_savegame_editor.py
File metadata and controls
1424 lines (1281 loc) Β· 66.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Firestaff Savegame Editor β read, edit and write savegames for all five
Dungeon Master games.
Supported formats:
DM1 β DMSAVE.DAT (PC 3.4, 512-byte XOR header, 5 obfuscated parts)
CSB β DMSAVE.DAT (PC 3.4, 512-byte header, obfuscation key 29)
DM2 β SKSAVE.* (SUPPRESS codec, 16 record types, 10 slots)
TQ β slotN.tqsv (Theron's Quest, 64-byte header, XOR seed 0x5A)
Nexus β *.fnxs (Firestaff native, magic FNXS, CRC32)
*.bkr (Saturn Backup RAM image; metadata/payload inspection)
Requires Python 3.10+ and Tk 8.6+.
"""
from __future__ import annotations
SAVEGAME_EDITOR_VERSION = "0.2"
import gettext, hashlib, os, struct, sys
from firestaff_studio_preferences import resolve_language, save_language
from pathlib import Path
from typing import Any
# ββ i18n βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
LANG_META = [
("sv", "\U0001f1f8\U0001f1ea", "Svenska"),
("en", "\U0001f1ec\U0001f1e7", "English"),
("de", "\U0001f1e9\U0001f1ea", "Deutsch"),
("fr", "\U0001f1eb\U0001f1f7", "FranΓ§ais"),
("es", "\U0001f1ea\U0001f1f8", "EspaΓ±ol"),
("it", "\U0001f1ee\U0001f1f9", "Italiano"),
("pt", "\U0001f1f5\U0001f1f9", "PortuguΓͺs"),
("nl", "\U0001f1f3\U0001f1f1", "Nederlands"),
("da", "\U0001f1e9\U0001f1f0", "Dansk"),
("no", "\U0001f1f3\U0001f1f4", "Norsk"),
("fi", "\U0001f1eb\U0001f1ee", "Suomi"),
("pl", "\U0001f1f5\U0001f1f1", "Polski"),
("cs", "\U0001f1e8\U0001f1ff", "ΔeΕ‘tina"),
("hu", "\U0001f1ed\U0001f1fa", "Magyar"),
("tr", "\U0001f1f9\U0001f1f7", "TΓΌrkΓ§e"),
("id", "\U0001f1ee\U0001f1e9", "Bahasa Indonesia"),
("ja", "\U0001f1ef\U0001f1f5", "ζ₯ζ¬θͺ"),
("ko", "\U0001f1f0\U0001f1f7", "νκ΅μ΄"),
("zh", "\U0001f1e8\U0001f1f3", "δΈζ"),
("ru", "\U0001f1f7\U0001f1fa", "Π ΡΡΡΠΊΠΈΠΉ"),
]
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
_LOCALE_DIR = Path(sys._MEIPASS) / "po" / "locale"
else:
_LOCALE_DIR = Path(os.environ.get(
"FIRESTAFF_LOCALE_DIR",
str(Path(__file__).resolve().parent.parent / "po" / "locale")))
_current_lang = "en"
def _detect_system_lang() -> str:
if sys.platform == "darwin":
try:
import subprocess
result = subprocess.run(
["defaults", "read", "-g", "AppleLanguages"],
capture_output=True, text=True, timeout=2,
)
for line in result.stdout.splitlines():
code = line.strip().strip('",').split("-")[0].lower()
if any(lc == code for lc, _, _ in LANG_META):
return code
except Exception:
pass
for env_var in ("LANG", "LC_ALL", "LC_MESSAGES", "LANGUAGE"):
val = os.environ.get(env_var, "")
if val:
code = val.split(".")[0].split("_")[0].lower()
if any(lc == code for lc, _, _ in LANG_META):
return code
return "en"
def _load_translations(lang: str):
try:
return gettext.translation(
"firestaff_studio", localedir=str(_LOCALE_DIR),
languages=[lang], fallback=True,
)
except Exception:
return gettext.NullTranslations()
_APP_ID = "savegame"
_current_lang = resolve_language(
_APP_ID, _detect_system_lang(), {code for code, _, _ in LANG_META})
_trans = _load_translations(_current_lang)
_ = _trans.gettext
# ββ Self-test gates ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def require_supported_tk(tk_module: Any) -> None:
version = tuple(int(p) for p in str(tk_module.TkVersion).split(".")[:2])
if version < (8, 6):
raise RuntimeError(f"Tk {tk_module.TkVersion} unsupported; need 8.6+")
if "--check-tkinter" in sys.argv:
try:
import tkinter as tk
require_supported_tk(tk)
except Exception as exc:
raise SystemExit(f"Tkinter check failed: {exc}")
print(f"Tkinter runtime check: PASS (Tk {tk.TkVersion})")
raise SystemExit(0)
if "--smoke-ui" in sys.argv:
import tkinter as tk
require_supported_tk(tk)
root = tk.Tk()
root.title("smoke")
root.after(200, root.destroy)
root.mainloop()
print("smoke-ui: PASS")
raise SystemExit(0)
# ββ Lookup tables ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
DM1_FORMAT_NAMES = {
5: "PC 3.4 (DOS)", 4: "PC 3.3", 3: "Amiga 3.6",
2: "Atari ST 3.6", 1: "Apple IIgs 3.1", 0: "Unknown (0)",
}
DM1_PLATFORM_NAMES = {
1: "IBM PC (DOS)", 2: "Amiga", 3: "Atari ST", 4: "Apple IIgs",
5: "Sharp X68000", 6: "FM Towns", 7: "SNES (Super Famicom)",
8: "Macintosh", 9: "PC Engine (TurboGrafx-16)", 10: "Sega Mega-CD",
}
DM1_DUNGEON_NAMES = {
0: "Dungeon Master", 1: "Chaos Strikes Back",
2: "Dungeon Master β Custom Dungeon", 10: "Theron's Quest dungeon",
}
PART_DESCRIPTIONS = {
"GLOBAL_DATA": _("Global dungeon state: event counts, active group limits, RNG seed. Fixed 128 bytes."),
"ACTIVE_GROUP": _("Active creature/item groups in the dungeon. Variable size from GLOBAL_DATA @46."),
"PARTY": _("Champion records (4 x 319 bytes) + party info (128 bytes). HP, stats, skills, inventory."),
"EVENTS": _("Dungeon event list: timers, triggers, sensors. Variable size from GLOBAL_DATA @28."),
"TIMELINE": _("Timeline/timer queue for scheduled events. Remainder of file after other parts."),
}
GAME_LABELS = {
"dm1": "Dungeon Master", "csb": "Chaos Strikes Back",
"csbwin": "Chaos Strikes Back (CSBWin)",
"dm2": "Dungeon Master II", "theron": "Theron's Quest", "nexus": "DM Nexus",
"nexus_bkr": "DM Nexus β Saturn Backup RAM",
}
SATURN_BKR_MAGIC = b"BackUpRam Format"
SATURN_BKR_SAVE_TAG = b"\x80\x00\x00\x00"
SATURN_BKR_CONTINUATION_TAG = b"\x00\x00\x00\x00"
def parse_saturn_bkr(data: bytes) -> list[dict[str, Any]]:
"""Read Saturn Backup RAM save entries without changing the image.
The block list is itself stored in save blocks and may cross into the
content area of blocks it names. This parser returns verified metadata
and byte-exact payloads; it does not interpret the game-specific bytes.
"""
if len(data) < 128 or data[:len(SATURN_BKR_MAGIC)] != SATURN_BKR_MAGIC:
raise ValueError("not a Saturn Backup RAM image")
repeats = 0
while data[repeats * len(SATURN_BKR_MAGIC):
(repeats + 1) * len(SATURN_BKR_MAGIC)] == SATURN_BKR_MAGIC:
repeats += 1
block_size = repeats * 16
if block_size not in (64, 512) or len(data) % block_size:
raise ValueError("unsupported or truncated Saturn Backup RAM geometry")
block_count = len(data) // block_size
if block_count < 2:
raise ValueError("Saturn Backup RAM image has no save area")
def u16(offset: int) -> int:
if offset + 2 > len(data):
raise ValueError("truncated Saturn Backup RAM block list")
return int.from_bytes(data[offset:offset + 2], "big")
saves = []
claimed: set[int] = set()
for first_block in range(2, block_count):
if first_block in claimed:
continue
base = first_block * block_size
if data[base:base + 4] != SATURN_BKR_SAVE_TAG:
continue
name = data[base + 4:base + 15].split(b"\0", 1)[0].decode("ascii", "replace")
language = data[base + 15]
comment = data[base + 16:base + 26].split(b"\0", 1)[0].decode("ascii", "replace")
timestamp = int.from_bytes(data[base + 26:base + 30], "big")
payload_size = int.from_bytes(data[base + 30:base + 34], "big")
references: list[int] = []
list_block = first_block
cursor = base + 34
visited_list_blocks = {first_block}
terminator_at = None
while len(references) <= block_count:
block_end = (list_block + 1) * block_size
if cursor + 2 > block_end:
next_reference = len(visited_list_blocks) - 1
if next_reference >= len(references):
raise ValueError("Saturn save block list cannot continue")
list_block = references[next_reference]
if (list_block in visited_list_blocks or list_block < 2 or
list_block >= block_count):
raise ValueError("invalid or cyclic Saturn save block list")
visited_list_blocks.add(list_block)
next_base = list_block * block_size
if data[next_base:next_base + 4] != SATURN_BKR_CONTINUATION_TAG:
raise ValueError("invalid Saturn save continuation tag")
cursor = next_base + 4
continue
value = u16(cursor)
cursor += 2
if value == 0:
terminator_at = cursor
break
if (value < 2 or value >= block_count or value == first_block or
value in claimed or value in references):
raise ValueError("invalid or overlapping Saturn save block reference")
references.append(value)
if terminator_at is None:
raise ValueError("unterminated Saturn save block list")
if payload_size == 0:
raise ValueError("empty Saturn save payload")
for block in references:
block_base = block * block_size
if data[block_base:block_base + 4] != SATURN_BKR_CONTINUATION_TAG:
raise ValueError("invalid Saturn save continuation tag")
stream_blocks = [first_block] + references
term_block = (terminator_at - 1) // block_size
if term_block not in stream_blocks:
raise ValueError("Saturn save directory escaped its block chain")
start_index = stream_blocks.index(term_block)
chunks = [data[terminator_at:(term_block + 1) * block_size]]
for block in stream_blocks[start_index + 1:]:
block_base = block * block_size
chunks.append(data[block_base + 4:block_base + block_size])
payload = b"".join(chunks)[:payload_size]
if len(payload) != payload_size:
raise ValueError("truncated Saturn save payload")
claimed.update(stream_blocks)
saves.append({"name": name, "language": language, "comment": comment,
"timestamp_minutes": timestamp, "payload": payload,
"blocks": tuple(stream_blocks)})
return saves
def saturn_bkr_display_metadata(entry: dict[str, Any]) -> list[tuple[str, str]]:
"""Format only container metadata; keep the Nexus payload uninterpreted."""
blocks = tuple(entry["blocks"])
return [
("comment", str(entry["comment"])),
("language_raw", f"0x{int(entry['language']):02X}"),
("timestamp_raw", f"0x{int(entry['timestamp_minutes']):08X}"),
("payload_size", f"{len(entry['payload']):,} bytes"),
("allocated_block_count", f"{len(blocks):,}"),
("allocated_block_ids", ", ".join(str(block) for block in blocks)),
]
def saturn_bkr_payload_diff_ranges(left: bytes, right: bytes) -> tuple[tuple[int, int], ...]:
"""Return half-open ranges of differing payload bytes, without decoding them."""
if len(left) != len(right):
raise ValueError("Saturn payloads must have equal lengths to compare")
ranges = []
start = None
for offset, (left_byte, right_byte) in enumerate(zip(left, right)):
if left_byte != right_byte:
if start is None:
start = offset
elif start is not None:
ranges.append((start, offset))
start = None
if start is not None:
ranges.append((start, len(left)))
return tuple(ranges)
def saturn_bkr_diff_preview(payload: bytes, start: int, end: int,
edge_bytes: int = 8) -> str:
"""Render a bounded raw-byte preview for one changed offset range."""
if not 0 <= start <= end <= len(payload) or edge_bytes < 1:
raise ValueError("invalid Saturn payload diff range")
span = payload[start:end]
if len(span) <= edge_bytes * 2:
return span.hex(" ").upper()
return (span[:edge_bytes].hex(" ").upper() + " β¦ " +
span[-edge_bytes:].hex(" ").upper())
CHAMPION_NAMES_DM1 = [
"Halk", "Stamm", "Zed", "Leyla", "Mophus", "Wuuf",
"Sonja", "Iaido", "Nabi", "Linflas", "Elija", "Chani",
"Hawk", "Boris", "Alex", "Azizi", "Syra", "Gothmog",
"Hissssa", "Daroou", "Wu Tse", "Gando", "Tiggy", "Leif",
]
class SaveField:
def __init__(self, name, offset, fmt, label="", choices=None,
description="", min_val=None, max_val=None):
self.name = name
self.offset = offset
self.fmt = fmt
self.label = label or name
self.description = description
self.choices = choices
self.min_val = min_val
self.max_val = max_val
self.size = struct.calcsize(fmt)
def read(self, data):
return struct.unpack_from(self.fmt, data, self.offset)[0]
def write(self, data, value):
struct.pack_into(self.fmt, data, self.offset, value)
# ββ DM1 PC34 format βββββββββββββββββββββββββββββββββββββββββββββββββββββ
DM1_PC34_HEADER_SIZE = 512
DM1_PART_NAMES = ["GLOBAL_DATA", "ACTIVE_GROUP", "PARTY", "EVENTS", "TIMELINE"]
DM1_PC34_HEADER_FIELDS = [
SaveField("random_words", 0, "<H", _("Random Words [0-148]"),
description=_("XOR obfuscation pad β 149 random 16-bit words (298 bytes)")),
SaveField("format_version", 299, "<B", _("Format Version"),
description=_("Save format version. 5=PC 3.4, 4=PC 3.3, 3=Amiga 3.6")),
SaveField("game_id", 306, "<H", _("Game ID"),
description=_("Identifies which game created this save")),
SaveField("key_part0", 310, "<H", _("Key: GLOBAL_DATA"),
description=_("XOR deobfuscation key for GLOBAL_DATA")),
SaveField("key_part1", 312, "<H", _("Key: ACTIVE_GROUP"),
description=_("XOR deobfuscation key for ACTIVE_GROUP")),
SaveField("key_part2", 314, "<H", _("Key: PARTY"),
description=_("XOR deobfuscation key for PARTY")),
SaveField("key_part3", 316, "<H", _("Key: EVENTS"),
description=_("XOR deobfuscation key for EVENTS")),
SaveField("key_part4", 318, "<H", _("Key: TIMELINE"),
description=_("XOR deobfuscation key for TIMELINE")),
SaveField("cs_part0", 342, "<H", _("Checksum: GLOBAL_DATA"),
description=_("F0418 checksum for GLOBAL_DATA validation")),
SaveField("cs_part1", 344, "<H", _("Checksum: ACTIVE_GROUP"),
description=_("F0418 checksum for ACTIVE_GROUP validation")),
SaveField("cs_part2", 346, "<H", _("Checksum: PARTY"),
description=_("F0418 checksum for PARTY validation")),
SaveField("cs_part3", 348, "<H", _("Checksum: EVENTS"),
description=_("F0418 checksum for EVENTS validation")),
SaveField("cs_part4", 350, "<H", _("Checksum: TIMELINE"),
description=_("F0418 checksum for TIMELINE validation")),
SaveField("platform", 374, "<H", _("Platform"),
description=_("Target platform. 1=PC, 2=Amiga, 9=PC Engine, etc.")),
SaveField("dungeon_id", 376, "<H", _("Dungeon ID"),
description=_("Dungeon. 0=DM1, 1=CSB, 10=Theron")),
]
DM1_CHAMPION_SIZE = 319
DM1_CHAMPION_FIELDS = [
SaveField("name", 0, "8s", _("Name")),
SaveField("title", 8, "20s", _("Title")),
SaveField("direction", 28, "<H", _("Direction"), choices=["N","E","S","W"]),
SaveField("action_index", 32, "<H", _("Action Index")),
SaveField("poison", 42, "<H", _("Poison"), min_val=0, max_val=65535),
SaveField("hp_current", 52, "<H", _("HP Current"), min_val=0, max_val=999),
SaveField("hp_max", 54, "<H", _("HP Max"), min_val=1, max_val=999),
SaveField("stamina_current", 56, "<H", _("Stamina Current"), min_val=0, max_val=9999),
SaveField("stamina_max", 58, "<H", _("Stamina Max"), min_val=1, max_val=9999),
SaveField("mana_current", 60, "<H", _("Mana Current"), min_val=0, max_val=999),
SaveField("mana_max", 62, "<H", _("Mana Max"), min_val=1, max_val=999),
SaveField("food", 66, "<H", _("Food"), min_val=0, max_val=2048),
SaveField("water", 68, "<H", _("Water"), min_val=0, max_val=2048),
SaveField("load", 271, "<H", _("Load"), min_val=0, max_val=65535),
]
DM1_SKILL_FIELDS = [
SaveField("fighter", 91, "<B", _("Fighter"), min_val=0, max_val=15),
SaveField("ninja", 93, "<B", _("Ninja"), min_val=0, max_val=15),
SaveField("priest", 95, "<B", _("Priest"), min_val=0, max_val=15),
SaveField("wizard", 97, "<B", _("Wizard"), min_val=0, max_val=15),
SaveField("swing", 99, "<B", _("Swing"), min_val=0, max_val=15),
SaveField("thrust", 101, "<B", _("Thrust"), min_val=0, max_val=15),
SaveField("club", 103, "<B", _("Club"), min_val=0, max_val=15),
SaveField("parry", 105, "<B", _("Parry"), min_val=0, max_val=15),
SaveField("steal", 107, "<B", _("Steal"), min_val=0, max_val=15),
SaveField("fight", 109, "<B", _("Fight"), min_val=0, max_val=15),
SaveField("throw", 111, "<B", _("Throw"), min_val=0, max_val=15),
SaveField("shoot", 113, "<B", _("Shoot"), min_val=0, max_val=15),
SaveField("identify", 115, "<B", _("Identify"), min_val=0, max_val=15),
SaveField("heal", 117, "<B", _("Heal"), min_val=0, max_val=15),
SaveField("influence", 119, "<B", _("Influence"), min_val=0, max_val=15),
SaveField("defend", 121, "<B", _("Defend"), min_val=0, max_val=15),
SaveField("fire", 123, "<B", _("Fire"), min_val=0, max_val=15),
SaveField("air", 125, "<B", _("Air"), min_val=0, max_val=15),
SaveField("earth", 127, "<B", _("Earth"), min_val=0, max_val=15),
SaveField("water_spell", 129, "<B", _("Water (spell)"), min_val=0, max_val=15),
]
DM1_GLOBAL_FIELDS = [
SaveField("event_count", 24, "<H", _("Event Count"),
description=_("Number of active events")),
SaveField("first_unused_event", 26, "<H", _("First Unused Event"),
description=_("Index of first free event slot")),
SaveField("event_max_count", 28, "<H", _("Event Max Count"),
description=_("Max events (determines EVENTS part size)")),
SaveField("active_group_count", 30, "<H", _("Active Group Count"),
description=_("Number of active creature/item groups")),
SaveField("max_active_group_count", 46, "<H", _("Max Active Group Count"),
description=_("Max active groups (determines ACTIVE_GROUP size)")),
]
DM1_PARTY_INFO_FIELDS = [
SaveField("magical_light", 0, "<H", _("Magical Light"),
description=_("Light spell intensity (0=dark)")),
SaveField("thieves_eye", 2, "<B", _("Thief's Eye"),
description=_("Thief's Eye active (0/1)")),
SaveField("footprints", 3, "<B", _("Footprints"),
description=_("Footprints active (0/1)")),
SaveField("shield", 4, "<H", _("Shield"),
description=_("Shield spell strength")),
SaveField("fire_shield", 6, "<H", _("Fire Shield"),
description=_("Fire Shield strength")),
SaveField("spell_shield", 8, "<H", _("Spell Shield"),
description=_("Spell Shield (Antimagic) strength")),
SaveField("scent", 10, "<B", _("Calming Scent"),
description=_("Calming influence active")),
SaveField("freeze_life", 11, "<B", _("Freeze Life"),
description=_("Freeze Life active (0/1)")),
]
# ββ F0417/F0418 ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def f0417_deobfuscate_part(data, key):
buf = bytearray(data)
checksum = key & 0xFFFF
wc = len(buf) // 2
for i in range(wc):
val = struct.unpack_from("<H", buf, i * 2)[0]
checksum = (checksum + val) & 0xFFFF
val ^= key & 0xFFFF
struct.pack_into("<H", buf, i * 2, val)
key = (key + wc - i) & 0xFFFF
checksum = (checksum + val) & 0xFFFF
return buf, checksum
def f0418_checksum_part(data, key):
checksum = key & 0xFFFF
wc = len(data) // 2
for i in range(wc):
val = struct.unpack_from("<H", data, i * 2)[0]
checksum = (checksum + val) & 0xFFFF
deob = val ^ (key & 0xFFFF)
key = (key + wc - i) & 0xFFFF
checksum = (checksum + deob) & 0xFFFF
return checksum
def dm1_pc34_decode_parts(raw):
hdr = raw[:DM1_PC34_HEADER_SIZE]
keys = [struct.unpack_from("<H", hdr, 310 + i*2)[0] for i in range(5)]
csums = [struct.unpack_from("<H", hdr, 342 + i*2)[0] for i in range(5)]
cursor = DM1_PC34_HEADER_SIZE
parts = {}
def add_part(name, size, idx):
nonlocal cursor
if size <= 0 or cursor + size > len(raw):
cursor += max(size, 0)
return
r = bytearray(raw[cursor:cursor+size])
d, _ = f0417_deobfuscate_part(r, keys[idx])
actual_cs = f0418_checksum_part(r, keys[idx])
parts[name] = {
"offset": cursor, "size": size,
"raw": r, "data": d,
"key": keys[idx], "checksum_expected": csums[idx],
"checksum_actual": actual_cs,
"valid": actual_cs == csums[idx] if name != "TIMELINE" else True,
}
cursor += size
add_part("GLOBAL_DATA", 128, 0)
gd = parts.get("GLOBAL_DATA")
max_ag = struct.unpack_from("<H", gd["data"], 46)[0] if gd else 0
ev_max = struct.unpack_from("<H", gd["data"], 28)[0] if gd else 0
add_part("ACTIVE_GROUP", max_ag * 2, 1)
add_part("PARTY", 4 * DM1_CHAMPION_SIZE + 128, 2)
add_part("EVENTS", ev_max * 4, 3)
add_part("TIMELINE", (len(raw) - cursor) & ~1, 4)
return parts
# ββ Savegame container βββββββββββββββββββββββββββββββββββββββββββββββββββ
class Savegame:
def __init__(self, game, path, raw):
self.game = game
self.path = path
self.raw = bytearray(raw)
self.header_fields = []
self.champion_count = 0
self.champion_names = []
self.header_data = bytearray()
self.parts = {}
self.modified = False
self.bkr_entries = []
self.read_only = False
self._parse()
def _parse(self):
if self.game == "nexus_bkr":
self.bkr_entries = parse_saturn_bkr(self.raw)
self.read_only = True
return
if self.game in ("dm1", "csb"):
self.header_data = bytearray(self.raw[:DM1_PC34_HEADER_SIZE])
self.header_fields = DM1_PC34_HEADER_FIELDS
self.champion_count = 4
self.parts = dm1_pc34_decode_parts(self.raw)
party = self.parts.get("PARTY")
if party:
names = []
for i in range(4):
off = i * DM1_CHAMPION_SIZE
rn = party["data"][off:off+8].split(b"\x00")[0].decode("ascii", errors="replace").strip()
names.append(rn if rn else _("Champion {}").format(i+1))
self.champion_names = names
else:
self.champion_names = [_("Champion {}").format(i+1) for i in range(4)]
def get_header_value(self, field):
return field.read(self.header_data)
def get_champion_data(self, idx):
p = self.parts.get("PARTY")
if not p: return bytearray()
off = idx * DM1_CHAMPION_SIZE
return bytearray(p["data"][off:off+DM1_CHAMPION_SIZE])
def get_party_info(self):
p = self.parts.get("PARTY")
if not p: return bytearray()
off = 4 * DM1_CHAMPION_SIZE
return bytearray(p["data"][off:off+128])
def get_global_data(self):
g = self.parts.get("GLOBAL_DATA")
return bytearray(g["data"]) if g else bytearray()
def save(self, path=None):
if self.read_only:
raise ValueError("Saturn Backup RAM images are inspection-only; editing is not supported")
(path or self.path).write_bytes(bytes(self.raw))
self.modified = False
def detect_game(data: bytes, filename: str = "") -> str | None:
"""Identify only documented, non-destructive save containers.
Unknown data is rejected rather than guessed. Containers without a
field-level editor still open as a byte-preserving inspection/save-as
document; this avoids re-encoding a format that has not been decoded.
"""
if data.startswith(b"CSBGAME\0") and len(data) >= 12:
version = struct.unpack_from("<I", data, 8)[0]
if version in (0x200, 0x201):
return "csbwin"
if data.startswith(b"FNXS"):
return "nexus"
if data.startswith(SATURN_BKR_MAGIC):
try:
if not parse_saturn_bkr(data):
return None
except ValueError:
return None
return "nexus_bkr"
if data.startswith(b"TQSV"):
return "theron"
if data.startswith(b"SKSAVE"):
return "dm2"
if len(data) >= 512 and data[299] in (3, 4, 5):
return "csb" if struct.unpack_from("<H", data, 376)[0] == 1 else "dm1"
return None
def self_test_saturn_bkr(require_real_corpus: bool) -> int:
authentic_corpus = {
"nexus-two-champion-retail-written-20260926.bkr":
"3d60856119df55ffa4937d13b5dc7487157c7c6b131a999a2e61683316679634",
"nexus-three-champion-retail-written-20260926.bkr":
"d9c86de3b0c668f9961a16529b1d5fd72f3e095823f8f0021cf8db8bfba48e9b",
"nexus-four-champion-retail-written-20260926.bkr":
"87d041baecca76a629b18b34e13b47adca1d5995a69bcac769aaca54c8f34035",
"nexus-four-champion-leader-3-retail-written-20260926.bkr":
"319ed84080a90eaeafb1bfa85ca4405a0153f4c85fda76ee7c557b34ac276867",
}
nexus_data_dir = os.environ.get("FIRESTAFF_NEXUS_DATA_DIR")
if not nexus_data_dir:
if require_real_corpus:
print("SKIP: FIRESTAFF_NEXUS_DATA_DIR is not set")
return 77
return 0
bkr_files = sorted(Path(nexus_data_dir).glob("*.bkr"))
if require_real_corpus:
bkr_files = [path for path in bkr_files if path.name in authentic_corpus]
if not bkr_files:
if require_real_corpus:
print("SKIP: no pinned authentic Nexus BKR samples found")
return 77
return 0
if require_real_corpus:
observed_names = {path.name for path in bkr_files}
if observed_names != set(authentic_corpus):
print("SKIP: pinned authentic Nexus BKR corpus is incomplete")
return 77
for bkr_path in bkr_files:
digest = hashlib.sha256(bkr_path.read_bytes()).hexdigest()
assert digest == authentic_corpus[bkr_path.name], (
f"authentic Nexus BKR digest mismatch: {bkr_path.name}")
corpus = []
payloads_by_name = {}
for bkr_path in bkr_files:
raw_bkr = bkr_path.read_bytes()
entries = parse_saturn_bkr(raw_bkr)
assert detect_game(raw_bkr, bkr_path.name) == "nexus_bkr"
assert detect_game(raw_bkr[:-1], bkr_path.name) is None
assert len(entries) == 1
entry = entries[0]
assert entry["name"] == "DMNEXUS__01"
assert len(entry["payload"]) == 20480
assert len(entry["blocks"]) == 354
repeats = 0
while raw_bkr[repeats * len(SATURN_BKR_MAGIC):
(repeats + 1) * len(SATURN_BKR_MAGIC)] == SATURN_BKR_MAGIC:
repeats += 1
block_size = repeats * 16
block_count = len(raw_bkr) // block_size
assert block_size in (64, 512) and len(raw_bkr) % block_size == 0
first_block_offset = entry["blocks"][0] * block_size
assert entry["language"] == raw_bkr[first_block_offset + 15]
assert entry["timestamp_minutes"] == int.from_bytes(
raw_bkr[first_block_offset + 26:first_block_offset + 30], "big")
assert len(set(entry["blocks"])) == len(entry["blocks"])
assert all(2 <= block < block_count for block in entry["blocks"])
metadata = dict(saturn_bkr_display_metadata(entry))
assert metadata["language_raw"] == f"0x{entry['language']:02X}"
assert metadata["timestamp_raw"] == f"0x{entry['timestamp_minutes']:08X}"
assert metadata["payload_size"] == "20,480 bytes"
assert metadata["allocated_block_count"] == "354"
assert metadata["allocated_block_ids"] == ", ".join(
str(block) for block in entry["blocks"])
broken_bkr = bytearray(raw_bkr)
broken_bkr[0xA2:0xA4] = b"\xFF\xFF"
assert detect_game(broken_bkr, bkr_path.name) is None
savegame = Savegame("nexus_bkr", bkr_path, raw_bkr)
assert savegame.read_only and len(savegame.bkr_entries) == 1
try:
savegame.save()
raise AssertionError("BKR image unexpectedly writable")
except ValueError:
pass
corpus.append(entry["payload"])
payloads_by_name[bkr_path.name] = entry["payload"]
assert len(set(corpus)) == len(corpus), "real Nexus BKR saves should remain distinct"
for left_index, left_payload in enumerate(corpus):
for right_payload in corpus[left_index + 1:]:
changed_offsets = [
offset for offset, (left_byte, right_byte) in
enumerate(zip(left_payload, right_payload))
if left_byte != right_byte
]
ranges = saturn_bkr_payload_diff_ranges(left_payload, right_payload)
ranged_offsets = [
offset for start, end in ranges for offset in range(start, end)
]
assert ranged_offsets == changed_offsets
assert all(
0 <= start < end <= len(left_payload) and
(previous_end is None or start > previous_end)
for previous_end, (start, end) in zip(
[None] + [end for _, end in ranges[:-1]], ranges)
)
for start, end in ranges:
assert saturn_bkr_diff_preview(left_payload, start, end)
assert saturn_bkr_diff_preview(right_payload, start, end)
named_samples = {
"nexus-two-champion-retail-written-20260926.bkr": 0x0434,
"nexus-three-champion-retail-written-20260926.bkr": 0x0514,
"nexus-four-champion-retail-written-20260926.bkr": 0x05F4,
"nexus-four-champion-leader-3-retail-written-20260926.bkr": 0x05F4,
}
named_champion_counts = {
"nexus-two-champion-retail-written-20260926.bkr": 2,
"nexus-three-champion-retail-written-20260926.bkr": 3,
"nexus-four-champion-retail-written-20260926.bkr": 4,
"nexus-four-champion-leader-3-retail-written-20260926.bkr": 4,
}
if all(name in payloads_by_name for name in named_samples):
for name, observed_value in named_samples.items():
payload = payloads_by_name[name]
assert int.from_bytes(payload[0x0A:0x0C], "big") == observed_value
assert observed_value == 0x0274 + 0x00E0 * named_champion_counts[name]
assert not any(payload[observed_value:]), (
f"authentic Nexus payload has nonzero bytes beyond its "
f"observed boundary: {name}")
assert named_samples["nexus-three-champion-retail-written-20260926.bkr"] - named_samples["nexus-two-champion-retail-written-20260926.bkr"] == 0xE0
assert named_samples["nexus-four-champion-retail-written-20260926.bkr"] - named_samples["nexus-three-champion-retail-written-20260926.bkr"] == 0xE0
print(f"firestaff_savegame_editor BKR corpus self-test: PASS ({len(bkr_files)} authentic images)")
return 0
if "--self-test-bkr" in sys.argv:
raise SystemExit(self_test_saturn_bkr(require_real_corpus=True))
if "--self-test" in sys.argv:
assert detect_game(b"CSBGAME\0\x00\x02\x00\x00") == "csbwin"
assert detect_game(b"FNXS\0") == "nexus"
assert detect_game(b"TQSV\0") == "theron"
assert detect_game(b"SKSAVE\0") == "dm2"
assert detect_game(b"not a save") is None
assert detect_game(b"BackUpRam Format" * 4 + bytes(64)) is None
self_test_saturn_bkr(require_real_corpus=False)
print("firestaff_savegame_editor self-test: PASS")
raise SystemExit(0)
# ββ Tk GUI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
class SavegameEditor(tk.Tk):
def __init__(self):
super().__init__()
self.title(_("Firestaff Savegame Editor 0.2"))
self.geometry("1000x750")
self.minsize(800, 550)
self.savegame = None
self.status = tk.StringVar(value=_("Ready"))
self._field_vars = {}
self._champ_vars = {}
self._icon_ref = None
self._set_app_identity()
self._build_ui()
def _set_app_identity(self):
if sys.platform == "darwin":
try:
from ctypes import cdll, c_void_p, c_char_p
objc = cdll.LoadLibrary("/usr/lib/libobjc.dylib")
objc.objc_getClass.restype = c_void_p
objc.sel_registerName.restype = c_void_p
objc.objc_msgSend.restype = c_void_p
objc.objc_msgSend.argtypes = [c_void_p, c_void_p]
pi = objc.objc_msgSend(
objc.objc_getClass(b"NSProcessInfo"),
objc.sel_registerName(b"processInfo"))
objc.objc_msgSend.argtypes = [c_void_p, c_void_p, c_char_p]
ns = objc.objc_msgSend(
objc.objc_getClass(b"NSString"),
objc.sel_registerName(b"stringWithUTF8String:"),
b"Firestaff Savegame Editor")
objc.objc_msgSend.argtypes = [c_void_p, c_void_p, c_void_p]
objc.objc_msgSend(pi, objc.sel_registerName(b"setProcessName:"), ns)
except Exception:
pass
icns = Path(__file__).resolve().parent.parent / "assets" / "icons" / "firestaff.icns"
if icns.exists():
try:
import subprocess
png = Path.home() / ".firestaff" / "cache" / "firestaff_icon.png"
png.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(["sips", "-s", "format", "png", str(icns),
"--out", str(png)], capture_output=True, timeout=5)
if png.exists():
img = tk.PhotoImage(file=str(png))
self.iconphoto(True, img)
self._icon_ref = img
except Exception:
pass
def _build_ui(self):
menubar = tk.Menu(self)
fm = tk.Menu(menubar, tearoff=0)
acc = "Cmd" if sys.platform == "darwin" else "Ctrl"
fm.add_command(label=_("Open..."), command=self.open_file, accelerator=f"{acc}+O")
fm.add_command(label=_("Save"), command=self.save_file, accelerator=f"{acc}+S")
fm.add_command(label=_("Save As..."), command=self.save_as)
fm.add_separator()
fm.add_command(label=_("Quit"), command=self.quit)
menubar.add_cascade(label=_("File"), menu=fm)
if sys.platform == "darwin":
app_menu = tk.Menu(menubar, tearoff=0)
app_menu.add_command(label=_("Settings..."), command=self.show_settings)
menubar.add_cascade(label="Firestaff", menu=app_menu)
lm = tk.Menu(menubar, tearoff=0)
lm.add_command(label=_("Auto (System Language)"), command=self._use_system_language)
lm.add_separator()
for code, flag, name in LANG_META:
lm.add_command(label=f"{flag} {name}", command=lambda c=code: self._switch_lang(c))
menubar.add_cascade(label=_("Language"), menu=lm)
self.config(menu=menubar)
mod = "Command" if sys.platform == "darwin" else "Control"
self.bind_all(f"<{mod}-o>", lambda e: self.open_file())
self.bind_all(f"<{mod}-s>", lambda e: self.save_file())
tb = ttk.Frame(self, padding=4)
tb.pack(fill="x")
ttk.Button(tb, text=_("Open"), command=self.open_file).pack(side="left", padx=2)
ttk.Button(tb, text=_("Save"), command=self.save_file).pack(side="left", padx=2)
ttk.Button(tb, text=_("Save As"), command=self.save_as).pack(side="left", padx=2)
ttk.Separator(tb, orient="vertical").pack(side="left", fill="y", padx=8)
self._game_label = ttk.Label(tb, text=_("No file loaded"))
self._game_label.pack(side="left", padx=4)
self._nb = ttk.Notebook(self)
self._nb.pack(fill="both", expand=True, padx=4, pady=4)
tabs = ["Overview", "Header", "Save Parts", "Champions", "Nexus Payload",
"Party Info", "Global Data", "Header Words", "Hex View"]
self._frames = {}
for t in tabs:
f = ttk.Frame(self._nb, padding=8)
self._nb.add(f, text=_(t))
self._frames[t] = f
hf = self._frames["Hex View"]
self._hex_text = tk.Text(hf, font=("Menlo", 11), state="disabled", wrap="none")
sy = ttk.Scrollbar(hf, command=self._hex_text.yview)
sx = ttk.Scrollbar(hf, orient="horizontal", command=self._hex_text.xview)
self._hex_text.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
sy.pack(side="right", fill="y")
sx.pack(side="bottom", fill="x")
self._hex_text.pack(fill="both", expand=True)
ttk.Label(self, textvariable=self.status, relief="sunken", padding=(4,2)).pack(fill="x", side="bottom")
def open_file(self):
path = filedialog.askopenfilename(
title=_("Open Savegame"),
filetypes=[(_("All Savegames"), "*.DAT *.dat *.tqsv *.fnxs *.bkr *.sav"),
(_("All Files"), "*")])
if not path: return
p = Path(path)
try: data = p.read_bytes()
except Exception as e:
messagebox.showerror(_("Error"), str(e)); return
game = detect_game(data, p.name)
if not game:
messagebox.showerror(_("Error"), _("Unrecognized savegame format.")); return
self.savegame = Savegame(game, p, data)
self._game_label.config(text=f"{GAME_LABELS.get(game,game)} β {p.name} ({len(data):,} bytes)")
self.status.set(_("Loaded: {}").format(p.name))
self._populate_all()
def save_file(self):
if not self.savegame:
messagebox.showwarning(_("Warning"), _("No savegame loaded")); return
if self.savegame.read_only:
messagebox.showinfo(_("Read only"),
_("Saturn Backup RAM images can be inspected but not edited or rewritten.")); return
try: self.savegame.save(); self.status.set(_("Saved: {}").format(self.savegame.path.name))
except Exception as e: messagebox.showerror(_("Error"), str(e))
def save_as(self):
if not self.savegame:
messagebox.showwarning(_("Warning"), _("No savegame loaded")); return
if self.savegame.read_only:
messagebox.showinfo(_("Read only"),
_("Saturn Backup RAM images can be inspected but not edited or rewritten.")); return
path = filedialog.asksaveasfilename(title=_("Save As"),
defaultextension=self.savegame.path.suffix, initialfile=self.savegame.path.name)
if not path: return
try: self.savegame.save(Path(path)); self.status.set(_("Saved as: {}").format(Path(path).name))
except Exception as e: messagebox.showerror(_("Error"), str(e))
def _populate_all(self):
self._populate_overview()
if self.savegame and self.savegame.game == "nexus_bkr":
for tab in ("Header", "Save Parts", "Champions", "Party Info",
"Global Data", "Header Words"):
self._clear(tab)
ttk.Label(self._frames[tab],
text=_("Game-specific Nexus payload fields are not yet verified."),
wraplength=680, justify="left").pack(anchor="w", padx=8, pady=8)
self._populate_bkr_payload()
self._populate_hex()
return
self._clear("Nexus Payload")
ttk.Label(self._frames["Nexus Payload"],
text=_("Only available for Saturn Backup RAM images."),
wraplength=680, justify="left").pack(anchor="w", padx=8, pady=8)
self._populate_header()
self._populate_parts()
self._populate_champions()
self._populate_party_info()
self._populate_global_data()
self._populate_header_words()
self._populate_hex()
def _clear(self, key):
for w in self._frames[key].winfo_children(): w.destroy()
def _scrollable(self, key):
f = self._frames[key]
c = tk.Canvas(f)
s = ttk.Scrollbar(f, orient="vertical", command=c.yview)
inner = ttk.Frame(c, padding=8)
inner.bind("<Configure>", lambda e: c.configure(scrollregion=c.bbox("all")))
c.create_window((0,0), window=inner, anchor="nw")
c.configure(yscrollcommand=s.set)
s.pack(side="right", fill="y")
c.pack(fill="both", expand=True)
return inner
# ββ Overview βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _populate_overview(self):
self._clear("Overview")
sg = self.savegame
if not sg: return
inner = self._scrollable("Overview")
ttk.Label(inner, text=_("File Overview"), font=("",14,"bold")).pack(anchor="w", pady=(0,8))
if sg.game == "nexus_bkr":
card = ttk.LabelFrame(inner, text=_("Saturn Backup RAM"), padding=8)
card.pack(fill="x", pady=4)
ttk.Label(card, text=_("This authentic Saturn card image is read-only. The Nexus payload schema is not yet verified, so payload bytes are shown without editing or conversion."),
wraplength=680, justify="left").pack(anchor="w", pady=(0,8))
for entry in sg.bkr_entries:
entry_frame = ttk.LabelFrame(card, text=entry["name"], padding=6)
entry_frame.pack(fill="x", pady=3)
labels = {
"comment": _("Comment"),
"language_raw": _("Language byte (raw)"),
"timestamp_raw": _("Timestamp field (raw)"),
"payload_size": _("Payload size"),
"allocated_block_count": _("Allocated blocks"),
"allocated_block_ids": _("Allocated block IDs"),
}
for key, value in saturn_bkr_display_metadata(entry):
ttk.Label(entry_frame,
text=f"{labels[key]}: {value}",
wraplength=680, justify="left").pack(anchor="w")
ttk.Button(
entry_frame, text=_("Compare with another cardβ¦"),
command=lambda current=entry:
self.compare_saturn_bkr(current),
).pack(anchor="w", pady=(4, 0))
preview = entry["payload"][:64].hex(" ").upper()
ttk.Label(entry_frame, text=_("Payload starts (hex): {}β¦").format(preview),
wraplength=680, justify="left").pack(anchor="w")
return
info = ttk.LabelFrame(inner, text=_("File Information"), padding=8)
info.pack(fill="x", pady=4)
fmt = sg.header_data[299] if len(sg.header_data) > 299 else 0
plat = struct.unpack_from("<H", sg.header_data, 374)[0] if len(sg.header_data) > 375 else 0
dung = struct.unpack_from("<H", sg.header_data, 376)[0] if len(sg.header_data) > 377 else 0
for i, (l, v) in enumerate([
(_("File"), f"{sg.path.name} ({len(sg.raw):,} bytes)"),
(_("Game"), GAME_LABELS.get(sg.game, sg.game)),
(_("Format"), "{} β {}".format(fmt, DM1_FORMAT_NAMES.get(fmt, _("Unknown")))),
(_("Platform"), "{} β {}".format(plat, DM1_PLATFORM_NAMES.get(plat, _("Unknown")))),
(_("Dungeon"), "{} β {}".format(dung, DM1_DUNGEON_NAMES.get(dung, _("Unknown")))),
]):
ttk.Label(info, text=f"{l}:", font=("",11,"bold")).grid(row=i, column=0, sticky="w", padx=(0,12), pady=2)
ttk.Label(info, text=v, font=("",11)).grid(row=i, column=1, sticky="w", pady=2)
pf = ttk.LabelFrame(inner, text=_("Save Parts"), padding=8)
pf.pack(fill="x", pady=8)
for c, t in enumerate([_("Part"), _("Offset"), _("Size"), _("Status")]):
ttk.Label(pf, text=t, font=("",10,"bold")).grid(row=0, column=c, sticky="w", padx=(0,12))
for i, name in enumerate(DM1_PART_NAMES):
part = sg.parts.get(name)
r = i + 1
ttk.Label(pf, text=name).grid(row=r, column=0, sticky="w", padx=(0,12), pady=1)
if part:
ttk.Label(pf, text=f"0x{part['offset']:04X}").grid(row=r, column=1, sticky="w", padx=(0,12))
ttk.Label(pf, text=f"{part['size']:,} bytes").grid(row=r, column=2, sticky="w", padx=(0,12))
ok = part["valid"]
ttk.Label(pf, text=_("Valid") if ok else _("MISMATCH"),
foreground="green" if ok else "red").grid(row=r, column=3, sticky="w")
if sg.champion_count > 0 and "PARTY" in sg.parts: