Repository navigation
Expand file tree
/
Copy pathtextpack.py
More file actions
1976 lines (1788 loc) · 102 KB
/
Copy pathtextpack.py
File metadata and controls
1976 lines (1788 loc) · 102 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
"""textpack.py — Episode II's text as an editable UTF-8 tree, and back.
``export_text`` writes one file per text object under
``OUT/chainN/<in-game path>``, and ``OUT/xs2-text-export.json``, the manifest
that ties the tree to the disc it came from::
kind on the disc in the tree form
bank cf\\en\\*.sbl, model\\map\\en\\*.sbl X.sbl.txt ### NNNN blocks (USA)
inline cf\\*.sb, model\\map\\*.bin, ... X.inline.txt ### @0xOFFSET blocks (Japan, demo)
menu yosikawa\\*.txd X.txd.txt ### NNNN blocks
battle yamamoto\\batdat.us | .bin batdat.us.txt ### S<sec> @<off> blocks
subtitle movie\\en\\*.txt | movie\\*.txt X.sub.txt the file itself
quest iwase\\*.txt (Shift-JIS) X.sjis.txt the file itself
**Block files.** The first line is a ``#`` header. Each ``### KEY`` line opens
one string; the text is the line after it::
# cf\\en\\sc1010.sbl chain0 7 strings stored 284 bytes, slot 2048 bytes
### 0004
[Canaan]What is this thing?
* Inside a block, a line that starts with ``#`` is a COMMENT and is not text
(the export writes notes and reading hints that way: ``#sjis:`` / ``#euc:``
for Japanese leftovers, a battle banner, a tutorial command, the slot
placeholder). To start a line of text with
``#``, write ``⟦23⟧``: the export does this itself, so ``#1`` on the disc
reads ``⟦23⟧1`` in the tree. A ``#`` anywhere else in a line is plain.
* ``⟦XX⟧`` is a raw byte. Line breaks inside a string are the game's own
code, ``\\n`` typed as backslash + n; a raw 0x0A byte reads ``⟦0A⟧``. If you
type a real line break inside a block the lines are joined with ``\\n``;
empty lines at the end of a block are dropped.
* Every block of the export must come back: same keys, same order, none
twice, none missing, none new. Anything else is refused.
* ``[Speaker]``, ``$zoom13;``, ``$col...;``, ``%p`` are the game's codes: keep them.
**What the characters mean depends on the build** (``textcodec.py``): on the
USA discs a letter like ``é`` is the Latin-1 byte 0xE9, on the Japanese discs
text is EUC-JP. A character typed into a CHANGED string is checked against
the font of the disc being patched and refused, with the reason, when the
game cannot draw it; an explicit ``⟦XX⟧`` escape is never checked.
**The manifest** records the build and, for every exported object, the sha1
of its bytes on the disc. ``import_text`` refuses a tree without one, a disc
of another build, and any object that is not the one the text was exported
from (an already patched image, another revision), unless ``rebase`` is set
(``text-import --rebase``). A tree exported from Disc 1 imports into Disc 2 of
the same build: chain 0 is the same there and each object is still checked.
**What an edit may do**, per kind (``docs/MODDING.md`` has the evidence):
* bank: strings grow and shrink, the bank is rebuilt. It may leave its slot
only with ``grow`` and never past the room its loader has (``bank_budget``,
USA only: the rule is read from the USA executable).
* inline: each string in place, same length or shorter.
* battle: in place; on the USA build a longer string moves the rest of its
section down through the string fields OV01's getters read
(``smallfiles.batdat_rebuild``), the file within its sectors.
* subtitle: a file in the tree for a movie that has none on the disc is
refused (``_new_subtitle_files``: the decoder's block has no room for it).
* menu, quest: rebuilt or rewritten; the file may not need more sectors than
the original (that is what the loader read; the slot could be larger).
USA MainMenu: a string with the memory-card slot placeholder keeps it where
FUN_00238038's walk finds it (``slot_problem``). Tutorial.txd: the entries
FUN_00215f10 runs as commands or skips may not change, and a page of text
may not become one (``tutorial_role``). USA quest files: typed characters
go through the reader's pair conversion (``textcodec.UsQuestCodec``).
* bank strings that scripts pass to ``bat.namePut`` (battle banners): marked in
the export; ``banner_report`` refuses one FUN_002353b8 would measure past its
end, and notes copies edited unalike and banners wider than any retail one.
* subtitle: ``moviesub.check_edit``; may be relocated with ``grow``.
Nothing is written unless every file passes; the output image is produced by
``repack.patch_copy`` (a complete, verified copy or nothing).
python textpack.py export DISC.iso OUTDIR
python textpack.py import DISC.iso OUTDIR MODDED.iso [--grow] [--rebase]
python textpack.py --self-test
"""
from __future__ import annotations
import hashlib
import json
import os
import struct
import sys
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import region # noqa: E402
import sbl # noqa: E402
import textcodec # noqa: E402
from chains import CHAINS, ChainReader, available_chains # noqa: E402
from iso9660 import IsoImage, SECTOR # noqa: E402
from textcodec import TextError # noqa: E402
from toc import parse_toc # noqa: E402
MANIFEST = "xs2-text-export.json"
FORMAT = 2
SCENE_BUFFER = 0x20000 # the static script buffer at USA 0x3C6DC0 (FUN_001eece0)
MAP_BUFFER = 0x12000 # the block FUN_001df928(0x12000) returns (FUN_001e00f0)
def _round(n: int, to: int) -> int:
return (n + to - 1) // to * to
def _allocations(entries) -> Dict[str, int]:
starts = sorted({e.sector for e in entries})
nxt = {s: n for s, n in zip(starts, starts[1:])}
out = {}
for e in entries:
end = nxt.get(e.sector)
out[e.path] = ((end - e.sector) * SECTOR if end is not None
else (e.size + SECTOR - 1) // SECTOR * SECTOR)
return out
def bank_budget(bank_path: str, sizes: Dict[str, int], build: str = "us") -> Tuple[Optional[int], str]:
"""(largest .sbl byte size the loader has room for, why) for a bank path on a
build. ``sizes`` maps lower-case TOC path -> stored size. (None, reason) when
no loader rule is known: any build but USA (the two rules were read from the
USA executable), a bank outside the build's language folder, a missing script."""
if build != "us":
return None, f"no loader rule has been read for the {build} build"
low = bank_path.lower()
head, _, name = low.rpartition("\\")
parent, _, lang = head.rpartition("\\")
stem = name.rsplit(".", 1)[0]
if lang != region.US.lang_dir:
return None, f"the USA loaders read text banks from '{region.US.lang_dir}\\' only"
if parent == "cf":
script, buf, align, who = f"cf\\{stem}.sb", SCENE_BUFFER, SECTOR, "FUN_001eece0"
elif parent == "model\\map":
script, buf, align, who = f"model\\map\\{stem}.bin", MAP_BUFFER, 64, "FUN_001e00f0"
else:
return None, "no loader is known for a bank at this path"
if script not in sizes:
return None, f"its script {script} is not in the table of contents"
used = _round(sizes[script], align)
room = max(0, (buf - used) // SECTOR * SECTOR) # the bank is read in whole sectors
return room, (f"{who} loads {script} ({sizes[script]} bytes, {used} with rounding) and then this bank "
f"into one {buf}-byte buffer")
# ---------------------------------------------------------------- block files
def parse_blocks(text: str, marker: str = "### ") -> List[Tuple[str, str]]:
"""(header after the marker, body) of every block. Comment lines (``#...``) are
dropped, trailing empty lines too, and the lines left are joined with the
game's ``\\n``."""
out: List[Tuple[str, List[str]]] = []
for line in text.split("\n"):
line = line.rstrip("\r")
if line.startswith(marker):
out.append((line[len(marker):].strip(), []))
elif line.startswith("#"):
continue
elif out:
out[-1][1].append(line)
elif line.strip():
raise TextError(f"text before the first '{marker.strip()}' block: {line[:40]!r}")
res = []
for head, b in out:
while len(b) > 1 and b[-1] == "":
b.pop()
res.append((head, "\\n".join(b)))
return res
def keyed_bodies(text: str, expected: List[str], key_tokens: int = 1) -> List[str]:
"""The bodies of a block file, in the order of ``expected`` keys. The file must
hold exactly those keys, each once, in that order."""
blocks = parse_blocks(text)
keys = [" ".join(h.split()[:key_tokens]) for h, _ in blocks]
if keys != expected:
seen, want = set(), set(expected)
dup = sorted({k for k in keys if k in seen or seen.add(k)})
missing = [k for k in expected if k not in set(keys)]
unknown = sorted(k for k in set(keys) if k not in want)
why = []
if dup:
why.append(f"{len(dup)} key(s) appear twice ({', '.join(dup[:3])})")
if missing:
why.append(f"{len(missing)} block(s) are missing ({', '.join(missing[:3])})")
if unknown:
why.append(f"{len(unknown)} key(s) are not in the export ({', '.join(unknown[:3])})")
if not why:
first = next(i for i, (a, b) in enumerate(zip(keys, expected)) if a != b)
why.append(f"the blocks are out of order from '### {keys[first]}' (expected '### {expected[first]}')")
raise TextError("; ".join(why) + ". Every '###' block of the export must be there once, in its order")
return [b for _, b in blocks]
# -------------------------------------------------------------------- context
class Context:
"""One disc being exported or imported: its build, codecs, and (lazily) the font
tables and subtitle bounds that the checks on typed text need."""
def __init__(self, iso: IsoImage, need_executable: bool = False):
self.iso = iso
self.profile = (region.require_executable(iso, "text-import") if need_executable
else region.region_of(iso))
self.build = self.profile.name
self.codec = textcodec.for_build(self.build)
self.subcodec = textcodec.subtitle_codec(self.build)
self.sjis = textcodec.SjisCodec()
self.usquest = textcodec.UsQuestCodec()
self._adr = self._fonts = self._limits = None
def _toc(self, chain: int):
reader = ChainReader(self.iso, chain)
return reader, parse_toc(bytes(reader.toc_bytes()), CHAINS[chain][0])
def addressing(self):
import font
if self._adr is None:
try:
self._adr = font.Addressing.from_iso(self.iso)
reader, entries = self._toc(0)
byp = {e.path.lower(): e for e in entries}
self._fonts = {n: font.Font.from_bytes(reader.read(byp[n].byte_offset, byp[n].size))
for n in self.profile.fonts if n in byp}
except font.FontError as e:
raise TextError(f"the font tables of this disc cannot be read, so typed text cannot be "
f"checked: {e}")
if not self._fonts:
raise TextError("this disc has no font file to check typed text against")
return self._adr, self._fonts
def check_typed(self, codec, text: str) -> Optional[str]:
if all(ch == "" or ord(ch) < 0x80 for ch, _ in textcodec.tokens(text)):
return None
adr, fonts = self.addressing()
return textcodec.check_typed(codec, text, adr, fonts)
def check_lines(self, codec, old_text: str, new_text: str, skip: Callable[[str], bool] = lambda ln: False
) -> Optional[str]:
"""check_typed over the lines of a whole-file text that are not in the original."""
old = set(old_text.split("\n"))
for n, ln in enumerate(new_text.split("\n"), 1):
if ln in old or skip(ln):
continue
why = self.check_typed(codec, ln)
if why:
return f"line {n}: {why}"
return None
def measure(self):
"""A factory of width functions with the state a subtitle file starts in
($bg3;$prop1;$han1;$xx0,24;$xx1,8;$xx2,0; at USA 0x6883F0, the same string in
the Japanese executable)."""
adr, fonts = self.addressing()
metrics = next(iter(fonts.values())).metrics
return lambda: adr.measurer(metrics, han=True, prop=True, xx1=8).width
def subtitle_limits(self):
import moviesub
if self._limits is None:
files = []
for chain in available_chains(self.iso):
reader, entries = self._toc(chain)
files += [reader.read(e.byte_offset, e.size) for e in entries
if region.is_movie_subtitle(e.path.lower()) and not e.compressed]
try:
self._limits = moviesub.limits_of(files, self.measure())
except moviesub.SubtitleError as e:
raise TextError(f"a retail subtitle file of this disc does not parse ({e})")
except ValueError as e: # a line the width function cannot follow: without the
# pixel bound the check would be weaker than promised, so subtitles are not editable here
raise TextError(f"a subtitle line of this disc cannot be measured ({e}); subtitle edits are "
f"refused on this image")
return self._limits
# ---------------------------------------------------------------------- kinds
def _encode(ctx: Context, codec, key: str, old: bytes, body: str) -> bytes:
"""One block's bytes. An unchanged body gives the original bytes back untouched;
a changed one is encoded, may not hold NUL, and has its typed characters checked."""
if codec.to_text(old) == body:
return old
try:
new = codec.from_text(body)
except TextError as e:
raise TextError(f"### {key}: {e}")
if b"\x00" in new:
raise TextError(f"### {key}: a NUL byte (⟦00⟧) inside a string; the game would stop reading there")
if new == old:
return old
why = ctx.check_typed(codec, body)
if why:
raise TextError(f"### {key}: {why}. Write ⟦XX⟧ escapes if these bytes are meant")
return new
def _jp_hint(s: bytes) -> str:
"""A reading hint for bytes that are Japanese developer text in a file of the USA build:
``#sjis: ...`` or ``#euc: ...`` (Shift-JIS tried first), when the bytes decode and
nearly all of what they read as is full-width kana, kanji or full-width signs (so a
Latin-1 line with accents, and EUC bytes that Shift-JIS would read as half-width kana,
get no false hint). A '#' line is a comment: an unedited export still imports as no change."""
if not any(b >= 0x80 for b in s):
return ""
for tag, enc in (("sjis", "shift_jis"), ("euc", sbl.CODEC)):
try:
t = s.decode(enc)
except UnicodeDecodeError:
continue
jp = sum(0x3040 <= ord(c) <= 0x30FF or 0x4E00 <= ord(c) <= 0x9FFF or 0x3000 <= ord(c) <= 0x303F
or 0xFF01 <= ord(c) <= 0xFF5E for c in t)
if jp >= 2 and 2 * jp >= len(t.replace(" ", "")):
from exetext import hint_safe
return f"#{tag}: " + hint_safe(t.replace("\n", " ").replace("\r", " "))
return ""
# The memory-card slot placeholder (USA SLUS_208.92). FUN_00238038 walks a menu string as the
# print function would (a byte from 0x80 up steps two bytes, any other one, NUL ends it) and at the
# first pair that is one of the three placeholders read gp-relative (82 4F at 0x69DA30, A3 B0 at
# 0x69DA38, '##' at 0x69DA40), or a digit it stamped before (07 then a byte of '12' at 0x69DA48),
# writes 07 and the slot's digit. FUN_002381a8 calls it on MainMenu 0x21F, 0x220, 0x224, 0x227 and
# 0x22F, FUN_0023b210 on 0x22F. The USA MainMenu.txd writes the placeholder as A3 B0 ('£°').
SLOT_PLACEHOLDERS = (b"\x82\x4f", b"\xa3\xb0", b"##")
SLOT_STAMPED = (b"\x071", b"\x072")
SLOT_MENU = "yosikawa\\mainmenu.txd"
def slot_markers(s: bytes) -> List[int]:
"""Offsets of the slot placeholders FUN_00238038 finds in ``s``, walking it as it does
(it stamps the first; the rest are counted by the same walk)."""
out, i, n = [], 0, len(s)
while i < n and s[i]:
if s[i:i + 2] in SLOT_PLACEHOLDERS or s[i:i + 2] in SLOT_STAMPED:
out.append(i)
i += 2 if s[i] >= 0x80 else 1
return out
def slot_problem(old: bytes, new: bytes, show: Callable[[bytes], str]) -> Optional[str]:
"""Why an edited menu string loses the memory-card slot placeholder of its original, or None."""
want = slot_markers(old)
if not want:
return None
got = slot_markers(new)
if len(got) == len(want):
return None
mark = show(old[want[0]:want[0] + 2])
hidden = [k for k in range(len(new) - 1) if new[k:k + 2] in SLOT_PLACEHOLDERS and k not in got]
if len(got) < len(want) and hidden:
k = hidden[0]
return (f"the slot placeholder {mark} is there, but the byte before it ({show(new[k - 1:k])}, 0x{new[k - 1]:02X}) "
f"is from 0x80 up, so FUN_00238038 reads it with the placeholder's first byte as one pair and never "
f"finds the placeholder: the game would not write the memory-card slot number. Put a space or "
f"another plain ASCII character right before {mark}")
return (f"the original holds {len(want)} memory-card slot placeholder(s) {mark}, the edit {len(got)}: the game "
f"writes the slot number over the first one (FUN_00238038), so keep {mark} where the number belongs, "
f"once")
# The Skill Tutorial script (yosikawa\Tutorial.txd, read through FUN_0022d118). FUN_00215f10 runs an
# entry by its first byte: '%' is a command chosen by the next byte(s) (%p, %tNN, %c+, %l0, ...),
# '*' calls FUN_00215de8, an empty entry and one starting with '#' are skipped; any other entry is
# the text the tutorial shows.
TUTORIAL = "yosikawa\\tutorial.txd"
def tutorial_role(s: bytes) -> str:
if not s:
return "empty"
return {0x25: "command", 0x2A: "command", 0x23: "skipped"}.get(s[0], "text")
TUTORIAL_NOTE = {"command": "# tutorial command, not shown (FUN_00215f10 runs it); leave it as is",
"empty": "# empty: the tutorial skips it (FUN_00215f10); leave it empty",
"skipped": "# starts with '#': the tutorial skips it (FUN_00215f10); leave it as is"}
class Kind:
name = ""
relocatable = False
why_fixed = ""
def match(self, low: str, head: bytes) -> bool:
raise NotImplementedError
def tree_path(self, root: Path, chain: int, path: str) -> Path:
raise NotImplementedError
def export(self, ctx: Context, path: str, data: bytes, info: dict) -> str:
raise NotImplementedError
def rebuild(self, ctx: Context, path: str, data: bytes, text: str) -> bytes:
raise NotImplementedError
def count(self, ctx: Context, data: bytes) -> int:
return 0
def limit(self, ctx: Context, e, data: bytes, new: bytes, alloc: int, sizes, grow: bool) -> Optional[str]:
"""Why ``new`` may not replace the object, or None. The default: the file may
not need more sectors than the original did."""
if _round(len(new), SECTOR) > _round(len(data), SECTOR) or len(new) > alloc:
return (f"{len(new)} bytes need {_round(len(new), SECTOR) // SECTOR} sectors, the original "
f"({len(data)} bytes) {_round(len(data), SECTOR) // SECTOR}; this file may not grow past "
f"the sectors the game read ({self.why_fixed}). Shorten other text in the same file")
return None
def _tree(root: Path, chain: int, path: str) -> Path:
parts = path.replace("/", "\\").split("\\")
if any(p in ("", ".", "..") or ":" in p for p in parts): # a damaged table of contents must not
raise TextError(f"object path {path!r} cannot be a file path") # write outside the export folder
return root / f"chain{chain}" / Path(*parts)
class Bank(Kind):
name = "bank"
relocatable = True
def match(self, low, head):
return low.endswith(".sbl") and head[:4] == sbl.MAGIC
def tree_path(self, root, chain, path):
return _tree(root, chain, path).with_suffix(".sbl.txt")
def count(self, ctx, data):
return len(sbl.parse(data))
def export(self, ctx, path, data, info):
strings = sbl.parse(data)
room, _why = bank_budget(path, info["sizes"], ctx.build)
lines = [f"# {path} chain{info['chain']} {len(strings)} strings "
f"stored {len(data)} bytes, slot {info['alloc']} bytes"
+ (f", loader room {room} bytes (--grow)" if room is not None else "")]
banners = info.get("banners", {})
for i, s in enumerate(strings):
lines.append(f"### {i:04d}")
t = ctx.codec.to_text(s)
if i in banners:
lines.append("# battle banner (bat.namePut)" + (f"; the same name is in {banners[i]} banks: give every "
f"copy the same text" if banners[i] > 1 else ""))
hint = _jp_hint(s) if ctx.build == "us" else ""
if hint:
lines.append(hint)
lines.append(t)
return "\n".join(lines) + "\n"
def rebuild(self, ctx, path, data, text):
old = sbl.parse(data)
keys = [f"{i:04d}" for i in range(len(old))]
new = [_encode(ctx, ctx.codec, k, o, b) for k, o, b in zip(keys, old, keyed_bodies(text, keys))]
if new == old:
return data
blob = sbl.build(new, data)
if sbl.parse(blob) != new:
raise TextError("the rebuilt bank does not read back as written")
return blob
def limit(self, ctx, e, data, new, alloc, sizes, grow):
room, why = bank_budget(e.path, sizes, ctx.build)
if room is not None and len(new) > room:
return (f"rebuilt size {len(new)} is {len(new) - room} bytes past the {room} bytes the game has "
f"room for ({why}); shorten the text, relocating cannot help")
if len(new) > alloc:
if room is None:
return f"rebuilt size {len(new)} exceeds its {alloc}-byte slot and cannot be relocated: {why}"
if not grow:
return (f"rebuilt size {len(new)} exceeds its {alloc}-byte slot (over by {len(new) - alloc}; "
f"--grow relocates it to the end of the image, loader room {room} bytes)")
return None
class Inline(Kind):
"""Japan and the demo: strings inside the script (``sb.py``). A string is listed
when a pushtext names it or a variable slot holds its offset ("table")."""
name = "inline"
def match(self, low, head):
import sb
return low.endswith((".sb", ".bin")) and head[:4] == sb.MAGIC
def tree_path(self, root, chain, path):
return _tree(root, chain, path).with_suffix(".inline.txt")
def _script(self, data):
import sb
s = sb.parse(data)
return s if s.text_kind in ("inline", "mixed") else None
def count(self, ctx, data):
s = self._script(data)
return len(s.text_offsets()) if s else 0
def export(self, ctx, path, data, info):
s = self._script(data)
if s is None:
return ""
lines = [f"# {path} chain{info['chain']} inline strings (in place: same length or shorter, never longer)"]
for o, how in s.text_offsets():
raw = s.inline_text(o)
lines += [f"### @{o:#x} max {len(raw)} bytes" + (" table" if how == "table" else ""),
ctx.codec.to_text(raw)]
return "\n".join(lines) + "\n"
def rebuild(self, ctx, path, data, text):
import sb
s = self._script(data)
if s is None:
raise TextError("this script has no inline text")
offs = s.text_offsets()
keys = [f"@{o:#x}" for o, _ in offs]
glob_off = struct.unpack_from("<I", data, 0x18)[0]
out = bytearray(data)
for (o, how), key, body in zip(offs, keys, keyed_bodies(text, keys)):
old = s.inline_text(o)
new = _encode(ctx, ctx.codec, key, old, body)
if new == old:
continue
if len(new) > len(old):
raise TextError(f"### {key} grows {len(old)} -> {len(new)} bytes; inline strings are replaced "
f"in place and may not get longer")
a = glob_off + o
out[a:a + len(old)] = new + bytes(len(old) - len(new))
if bytes(out) == data:
return data
again = sb.parse(bytes(out))
if again.text_offsets() != offs:
lost = sorted(set(offs) - set(again.text_offsets()))
raise TextError(f"the edit would make {len(lost)} string(s) disappear from the next export "
+ (f"(### @{lost[0][0]:#x}: a string that only a table points at may not be emptied)"
if lost else "(the script's string list changed)"))
return bytes(out)
def limit(self, ctx, e, data, new, alloc, sizes, grow):
return None if len(new) == len(data) else "the script changed size"
def txd_parse(data: bytes) -> Tuple[List[bytes], bytes]:
"""(strings, tail) of a .txd: u32 offsets (count = first offset / 4), then the
NUL-terminated strings back to back in table order; ``tail`` is whatever
follows the last string (zero bytes, or nothing)."""
if len(data) < 4:
raise TextError("too short for a .txd")
first = struct.unpack_from("<I", data, 0)[0]
n = first // 4
if first % 4 or not 0 < first <= len(data):
raise TextError("not a .txd (first offset)")
offs = struct.unpack_from(f"<{n}I", data, 0)
strings, pos = [], first
for o in offs:
if o != pos or o >= len(data):
raise TextError(f"not a plain .txd: string at {o:#x}, expected {pos:#x}")
end = data.find(b"\x00", o)
if end < 0:
raise TextError("a .txd string runs off the end")
strings.append(data[o:end])
pos = end + 1
return strings, data[pos:]
def txd_build(strings: List[bytes], tail: bytes = b"") -> bytes:
offs, body = [], bytearray()
for s in strings:
if b"\x00" in s:
raise TextError("a string may not contain NUL")
offs.append(4 * len(strings) + len(body))
body += s + b"\x00"
return struct.pack(f"<{len(strings)}I", *offs) + bytes(body) + tail
class Menu(Kind):
name = "menu"
why_fixed = "the game reads menu text into static buffers of fixed size"
def match(self, low, head):
return low.endswith(".txd")
def tree_path(self, root, chain, path):
return _tree(root, chain, path).with_suffix(".txd.txt")
def count(self, ctx, data):
return len(txd_parse(data)[0])
def export(self, ctx, path, data, info):
strings, tail = txd_parse(data)
if txd_build(strings, tail) != data or any(tail):
raise TextError("does not rebuild to the same bytes; left alone")
low = path.lower().replace("/", "\\")
tutorial = low == TUTORIAL
slots = ctx.build == "us" and low == SLOT_MENU
lines = [f"# {path} {len(strings)} strings (menu text; keep %p, %d and the game's codes)"]
if tutorial:
lines.append("# The Skill Tutorial's script: FUN_00215f10 runs the entries in order. An entry that starts "
"with % or * is a command, an empty one or one starting with # is skipped, every other one "
"is a page of text. Edit the text pages only; a page may not be emptied or start with % * #")
for i, s in enumerate(strings):
lines.append(f"### {i:04d}")
if tutorial and tutorial_role(s) != "text":
lines.append(TUTORIAL_NOTE[tutorial_role(s)])
if slots and slot_markers(s):
m = slot_markers(s)[0]
mark = ctx.codec.to_text(s[m:m + 2])
lines.append(f"# {mark} = the memory-card slot number, filled in by the game (FUN_00238038); keep it "
f"as written, with a plain ASCII character (not an accented letter) right before it")
hint = _jp_hint(s) if ctx.build == "us" else ""
if hint:
lines.append(hint)
lines.append(ctx.codec.to_text(s))
return "\n".join(lines) + "\n"
def rebuild(self, ctx, path, data, text):
old, tail = txd_parse(data)
keys = [f"{i:04d}" for i in range(len(old))]
new = [_encode(ctx, ctx.codec, k, o, b) for k, o, b in zip(keys, old, keyed_bodies(text, keys))]
if new == old:
return data
low = path.lower().replace("/", "\\")
for k, o, n in zip(keys, old, new):
if n == o:
continue
if low == TUTORIAL:
if tutorial_role(o) != "text":
raise TextError(f"### {k}: this entry is not text: FUN_00215f10 runs it as a tutorial command "
f"({ctx.codec.to_text(o) or 'empty: skipped'}), so changing it changes what the "
f"Skill Tutorial does. Leave it as exported")
if tutorial_role(n) != "text":
raise TextError(f"### {k}: a page of tutorial text may not "
+ ("be emptied" if not n else f"start with '{chr(n[0])}'")
+ ": FUN_00215f10 would " + ("skip it" if tutorial_role(n) != "command"
else "run it as a command") + " instead of showing it")
if ctx.build == "us" and low == SLOT_MENU:
why = slot_problem(o, n, ctx.codec.to_text)
if why:
raise TextError(f"### {k}: {why}")
blob = txd_build(new, tail)
if txd_parse(blob) != (new, tail):
raise TextError("the rebuilt menu file does not read back as written")
return blob
class Battle(Kind):
name = "battle"
why_fixed = "the game loads it into a static buffer"
def match(self, low, head):
return low in ("yamamoto\\batdat.us", "yamamoto\\batdat.bin")
def tree_path(self, root, chain, path):
p = _tree(root, chain, path)
return p.with_name(p.name + ".txt") # batdat.us.txt / batdat.bin.txt
def count(self, ctx, data):
import smallfiles
return len(smallfiles.batdat_raw_strings(data))
def export(self, ctx, path, data, info):
import smallfiles
rows = smallfiles.batdat_raw_strings(data)
if ctx.build == "us":
room = _round(len(data), SECTOR) - len(data)
grow = ", ".join(str(si) for si in smallfiles.BATDAT_STRING_FIELDS)
lines = [f"# {path} {len(rows)} strings. 'max N' is a string's own bytes. A string of sections {grow} "
f"may be longer: the strings after it in its section move down (the file has {room} spare "
f"bytes in its last sector). Section 17 is in place only"]
else:
lines = [f"# {path} {len(rows)} strings (replaced in place: same length or shorter, never longer)"]
for si, o, raw in rows:
lines += [f"### S{si:02d} @{o:#06x} max {len(raw)} bytes", ctx.codec.to_text(raw)]
return "\n".join(lines) + "\n"
def rebuild(self, ctx, path, data, text):
import smallfiles
rows = smallfiles.batdat_raw_strings(data)
keys = [f"S{si:02d} @{o:#06x}" for si, o, _ in rows]
new = {}
want = []
for (si, o, raw), key, body in zip(rows, keys, keyed_bodies(text, keys, key_tokens=2)):
b = _encode(ctx, ctx.codec, key, raw, body)
want.append((si, o, b))
if b != raw:
new[(si, o)] = b
if not new:
return data
try:
blob = smallfiles.batdat_rebuild(data, new, grow=ctx.build == "us")
except smallfiles.SmallFileError as e:
raise TextError(str(e))
if len(blob) != len(data): # strings moved: the next export finds the same strings
if sorted((si, r) for si, _, r in smallfiles.batdat_raw_strings(blob)) != sorted(
(si, b) for si, _, b in want):
raise TextError("the edit would change which strings the next export finds: a string that "
"grows must keep its first byte printable, and the strings after it must still be "
"found where they move to")
return blob
if smallfiles.batdat_raw_strings(blob) != want:
got = {(si, o) for si, o, _ in smallfiles.batdat_raw_strings(blob)}
lost = [k for k, (si, o, _) in zip(keys, rows) if (si, o) not in got]
raise TextError(f"the edit would change which strings the next export finds"
+ (f" ({len(lost)} would disappear, the first ### {lost[0]})" if lost else "")
+ ": a section is recognised by the first byte of its first string, which must stay "
"a printable ASCII or EUC byte")
return blob
def limit(self, ctx, e, data, new, alloc, sizes, grow):
"""In place, or (USA) grown within the sectors the game reads: OV01 FUN_00a81a70 loads the file with
FUN_00a83dc0 -> FUN_0019c1e0, which reads the TOC size rounded up to whole sectors into the static
buffer at 0x61D040. The next address any decompiled code names after it is 0x631140, so the
buffer may well be larger, but its size was not read; the file keeps to its sectors."""
if len(new) == len(data):
return None
if ctx.build != "us":
return "the battle database changed size"
if _round(len(new), SECTOR) > _round(len(data), SECTOR) or len(new) > alloc:
return (f"the longer battle strings make the file {len(new)} bytes; it may hold "
f"{min(_round(len(data), SECTOR), alloc)} ({len(new) - min(_round(len(data), SECTOR), alloc)} "
f"over): the game reads whole sectors of the file into a static buffer whose size is not "
f"known. Shorten other battle strings")
return None
def quest_skeleton(text: str) -> Optional[str]:
"""A quest file with the contents of every "..." removed: the record numbers,
braces, field names and ruler lines. None when the quotes do not pair up."""
out, i, n = [], 0, len(text)
while i < n:
c = text[i]
out.append(c)
i += 1
if c == '"':
while i < n and text[i] != '"':
i += 2 if text[i] == "\\" else 1
if i >= n:
return None
out.append('"')
i += 1
return "".join(out)
# The USA loaders (FUN_0022ee08 QuestMes, FUN_0022f000 Citizen, FUN_00232160 Treasure) read a fixed
# number of records into a zeroed buffer of fixed-size records (0x195D8 = 36 x 0xB46, 0x29FE =
# 50 x 0xD7, 0xBE2 = 18 x 0xA9) with FUN_0022ec18, which finds each field by name, then copies the
# quoted text with no length check and no terminator of its own: a field holds its size minus one
# byte, the rest is the zeroed buffer's NUL. In the copy, CR LF is skipped, \n is one byte (0x0A), \"
# is a quote, any other backslash pair is dropped, a byte from 0x80 up takes two bytes (FUN_0023ebb8
# converts the pair in place), and a lone LF is copied as a line break.
QUEST_LAYOUTS = {
"iwase\\questmes.txt": (0x24, 0xB46, (("Subject", 0x000), ("Locate", 0x01F), ("Client", 0x030),
("MesIPG", 0x041), ("MesSCD", 0x142), ("MesFLD", 0x243),
("UkunSCD", 0x344), ("UkunFLD", 0x745))),
"iwase\\citizen.txt": (50, 0xD7, (("Name", 0x00), ("Sex", 0x11), ("Age", 0x18), ("Hobby", 0x29),
("Profile", 0x40))),
"iwase\\treasure.txt": (0x12, 0xA9, (("Item", 0x00), ("Locate", 0x15), ("Expl", 0x30))),
}
def _quest_name_match(pat: bytes, d: bytes, p: int) -> bool:
"""FUN_0024f480: the pattern ('Name:%s\\n') matches when the text agrees up to its '%'."""
i, n = 0, len(d)
while True:
c2 = pat[i]
if c2 == 0x0A:
return p < n and d[p] == 0x0A
if p >= n or d[p] != c2:
return c2 == 0x25
p += 1
i += 1
def quest_fields(data: bytes, layout) -> List[Tuple[int, str, int, int]]:
"""(record, field, bytes the game copies, field size) for every field the loader reads,
walking the file as FUN_0022ec18 does. TextError when a field cannot be found."""
nrec, rsize, fields = layout
out, p, n = [], 0, len(data)
for r in range(nrec):
for k, (name, off) in enumerate(fields):
size = (fields[k + 1][1] if k + 1 < len(fields) else rsize) - off
pat = (name + ":%s\n").encode()
while True:
while p < n and data[p] != pat[0]:
p += 1
if p >= n:
raise TextError(f"record {r + 1}: the game would not find its field {name}: and read past "
f"the end of the file")
if _quest_name_match(pat, data, p):
break
p += 1
while p < n and data[p] != 0x22:
p += 1
p += 1
length = 0
while True:
if p >= n:
raise TextError(f"record {r + 1} {name}: the text has no closing quote")
c = data[p]
if c == 0x22:
p += 1
break
if c == 0x0D and p + 1 < n and data[p + 1] == 0x0A:
p += 2
elif c == 0x5C:
length += p + 1 < n and data[p + 1] in (0x22, 0x6E)
p += 2
elif c < 0x80:
length += 1
p += 1
else:
length += 2
p += 2
out.append((r, name, length, size))
return out
class Quest(Kind):
name = "quest"
why_fixed = ("its loader allocates by the file's size from the game's heap, whose room has not been read; "
"each text also has a fixed field size")
def match(self, low, head):
low = low.replace("/", "\\")
return low.startswith("iwase\\") and low.endswith(".txt") and low.count("\\") == 1
def tree_path(self, root, chain, path):
return _tree(root, chain, path).with_suffix(".sjis.txt")
@staticmethod
def _layout(path):
return QUEST_LAYOUTS.get(path.lower().replace("/", "\\"))
def _codec(self, ctx, path):
"""USA: the three files its loaders read, as the game draws them (UsQuestCodec); every other
quest file (Japan, and the USA build's unloaded Japanese placeholders) as plain Shift-JIS."""
return ctx.usquest if ctx.build == "us" and self._layout(path) is not None else ctx.sjis
def export(self, ctx, path, data, info):
return self._codec(ctx, path).to_text(data, file=True)
def rebuild(self, ctx, path, data, text):
codec = self._codec(ctx, path)
old_text = codec.to_text(data, file=True)
if text == old_text:
return data
if "\r\n" in old_text and "\r" not in text and "\n" in text:
# an editor saved the file with LF line ends: the game skips CR LF inside a text but copies
# a lone LF as a line break, so the file's own CR LF are restored, every line alike
text = text.replace("\n", "\r\n")
elif "\r\n" in old_text and text.replace("\r\n", "").count("\n"):
raise TextError("the file mixes CR LF and LF line ends: keep CR LF line ends, as exported (the game "
"skips CR LF inside a text and copies a lone LF as a line break)")
try:
new = codec.from_text(text)
except TextError as e:
for n, ln in enumerate(text.split("\n"), 1):
try:
codec.from_text(ln)
except TextError as e2:
raise TextError(f"line {n}: {e2}")
raise e
if new == data:
return data
if b"\x00" in new:
raise TextError("a NUL byte in the file")
a, b = quest_skeleton(old_text), quest_skeleton(text)
if a is not None and a != b:
raise TextError("the file's structure changed: only the text between double quotes may be edited "
"(record numbers, braces, field names and every line outside the quotes must stay; "
"a quote inside a text is written \\\")")
if ctx.build == "us":
layout = self._layout(path)
old_lines = set(old_text.split("\n"))
for n, ln in enumerate(text.split("\n"), 1):
if ln in old_lines:
continue
typed = [ch for ch, _ in textcodec.tokens(ln) if ch and ord(ch) > 0x7F]
if typed and layout is None:
raise TextError(f"line {n}: a non-ASCII character in a quest file no USA loader reads (the "
f"loaders read QuestMes.txt, Citizen.txt and Treasure.txt), so what the game "
f"would make of it is not known; write plain ASCII, or \u27e6XX\u27e7 escapes "
f"if you know the bytes")
for ch in typed:
why = codec.typed_problem(ch)
if why is None: # a symbol pair: its glyph in the USA font, as in any other text
why = ctx.check_typed(ctx.codec, codec.drawn(codec.encode_char(ch)))
if why:
raise TextError(f"line {n}: {why}")
if layout is not None:
old_f = quest_fields(data, layout)
for (r, name, length, size), (_, _, was, _) in zip(quest_fields(new, layout), old_f):
if length > size - 1 and length != was:
raise TextError(f"record {r + 1} {name}: {length} bytes, but the game copies it into a "
f"{size}-byte field (at most {size - 1} and the terminator; \\n counts one "
f"byte, the line ends inside the quotes none); shorten it by "
f"{length - size + 1}")
else:
# the file is Shift-JIS; the glyph check assumes the game maps each character to its JIS code
why = ctx.check_lines(textcodec.EucCodec(), old_text, text)
if why:
raise TextError(why)
return new
class Subtitle(Kind):
name = "subtitle"
relocatable = True
def match(self, low, head):
return region.is_movie_subtitle(low)
def tree_path(self, root, chain, path):
return _tree(root, chain, path).with_suffix(".sub.txt")
def export(self, ctx, path, data, info):
return ctx.subcodec.to_text(data, file=True)
def rebuild(self, ctx, path, data, text):
import moviesub
old_text = ctx.subcodec.to_text(data, file=True)
if text == old_text:
return data
new = ctx.subcodec.from_text(text)
if new == data:
return data
why = ctx.check_lines(ctx.codec, old_text, text, skip=lambda ln: ln.startswith(";"))
if why:
raise TextError(why)
why = moviesub.check_edit(data, new, ctx.subtitle_limits(), ctx.measure())
if why:
raise TextError(why)
return new
def limit(self, ctx, e, data, new, alloc, sizes, grow):
if len(new) > alloc and not grow:
return f"{len(new)} bytes exceeds its {alloc}-byte slot (over by {len(new) - alloc}; --grow relocates it)"
return None
ICON_TITLE_AT, ICON_TITLE_LEN = 0xC0, 68 # icon.sys: the title field, Shift-JIS, NUL-padded
ICON_BREAK_AT = 6 # icon.sys: u16, the byte offset where line 2 starts
# FUN_0019dc10 (USA), called from FUN_00239f98 at 0x0023A8C4 with the loaded carddata.bin, the slot
# number + 1 and the save time, writes these bytes of the title when it saves (offsets in the
# title; the buffer has the pack's 0x40-byte table first, icon.sys at 0x40): the trail bytes of
# the slot digits (+0x1B, +0x1D), the hour's tens as a whole pair (+0x20/+0x21: 81 40 or 82 4F+d),
# the trail bytes of the hour's ones and the minutes (+0x23, +0x27, +0x29). The leads before
# them stay as loaded, so the whole pairs +0x1A..+0x1D, +0x20..+0x23 and +0x26..+0x29 are kept.
ICON_STAMPED = tuple(range(0x1A, 0x1E)) + tuple(range(0x20, 0x24)) + tuple(range(0x26, 0x2A))
class IconTitle(Kind):
"""The save's title in the PS2 memory-card browser: ``icon.sys`` (member 0 of
carddata.bin; Japan carddata.new), Shift-JIS at +0xC0, two lines split at the u16 byte
offset at +6. Rewritten in place: the pack keeps its size."""
name = "icontitle"
why_fixed = "the pack is rewritten in place"
def match(self, low, head):
return low in ("carddata.bin", "carddata.new")
def tree_path(self, root, chain, path):
p = _tree(root, chain, path)
return p.with_name(p.name + ".title.txt")
def count(self, ctx, data):
return 1
@staticmethod
def _sys(data: bytes) -> Tuple[int, bytes]:
import smallfiles
try:
start, end = smallfiles.pack_members(data)[0]
except smallfiles.SmallFileError as e:
raise TextError(f"not a pack: {e}")
sys_ = data[start:end]
if sys_[:4] != b"PS2D" or len(sys_) < ICON_TITLE_AT + ICON_TITLE_LEN:
raise TextError("member 0 is not an icon.sys")
return start, sys_
def _lines(self, ctx, sys_: bytes) -> Tuple[bytes, int]:
field = sys_[ICON_TITLE_AT:ICON_TITLE_AT + ICON_TITLE_LEN]
title = field.split(b"\0")[0]
if any(field[len(title):]):
raise TextError("bytes after the title's terminator; left alone")
brk = struct.unpack_from("<H", sys_, ICON_BREAK_AT)[0]
if not 0 < brk <= len(title):
raise TextError(f"the line-break offset {brk} is outside the title")
return title, brk
def _show(self, ctx, title: bytes, brk: int) -> str:
a, b = ctx.sjis.to_text(title[:brk]), ctx.sjis.to_text(title[brk:])
if ctx.sjis.from_text(a) != title[:brk]:
raise TextError("the line break falls inside a character; left alone")
return a + "\\n" + b
def export(self, ctx, path, data, info):
_, sys_ = self._sys(data)
title, brk = self._lines(ctx, sys_)
shown = self._show(ctx, title, brk)
return "\n".join([
f"# {path} the save's title in the PS2 memory-card browser (icon.sys, Shift-JIS)",
f"# Two lines, split where \\n stands. At most {ICON_TITLE_LEN - 1} bytes in all (2 per full-width "