Repository navigation
Expand file tree
/
Copy pathlangpack.py
More file actions
1917 lines (1768 loc) · 91 KB
/
Copy pathlangpack.py
File metadata and controls
1917 lines (1768 loc) · 91 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
"""langpack.py — translate Episode II (USA) into scripts its font never had: shape,
order, wrap and encode text for the game's print function.
Borrowed from Xenosaga1PythonExtractor/langpack.py (2026-10-14): the shaping
(``HBShaper``, and ``SimpleShaper`` with its Arabic presentation-form table for
hand-drawn PNG cells), the bidi run ordering of that encoder, the greedy wrap at
spaces, mirrored brackets, Latin and digit runs kept forward, an all-Latin
paragraph kept left-to-right, and the disc's own Japanese left alone. What is
Episode II's: the glyph codes (``glyphs.py``: single bytes, A4 pairs, AD pairs,
read from the USA executable), the widths (``font.Measurer``, the port of the
game's width function, on the REBUILT font), the text tree (``textpack``'s
text-export tree), the control tokens, the state codes re-emitted for
right-to-left lines, several scripts in one project, and the byte budgets.
The engine draws left to right, one cell per code, with no joining, reordering
or bidi. All of that happens here, at build time; the game only ever sees glyph
codes, written into the tree as ``⟦XX⟧`` escapes, which text-import never checks
against the font. Pipeline (docs/ALPHABETS.md)::
text-export DISC1 -> TREE translate TREE (logical-order UTF-8)
lang-scan --iso DISC1 --text TREE ... -> font0.us font1.us glyphset.json langpack.json
lang-encode --text TREE --glyphset G -> TREE-ENC (same tree, glyphs as escapes)
patch --set chain0:font0.us=... --set chain0:font1.us=... (into a copy)
text-import --iso <that copy> --text TREE-ENC --out OUT.iso
What the encoder knows about the text (read from SLUS_208.92 unless marked):
* ``$name...;`` codes have no width. ``$col``, ``$zoom``, ``$shadow``, ``$bg``, ``$alpha``
and ``$xxN`` set a state that lasts; on a right-to-left line those codes are
re-emitted in front of each word that needs them, so every word is drawn with
the state in effect at its logical position, and the logical end state is
restored after the line.
* A leading ``[Speaker]`` is cut off bytewise by the field window
(``FUN_00282380``/``FUN_00282338``), so it stays first.
* The two characters ``\\n`` and a real 0x0A are line breaks (``FUN_002870b0``);
in executable strings (``.exe.txt``) a break is ``⟦0A⟧``.
* ``%d`` and the other ``%`` tokens pass through at their logical place;
``&NN`` controller icons are measured as 19 px (an ASSUMPTION, not read).
* The field window wraps a line by itself (``FUN_002865f0`` asks
``FUN_00196118`` how many bytes fit and breaks at spaces), so a right-to-left
bank line has to be pre-wrapped narrower than the window, whose width has
NOT been read: give ``--width-kind bank=PX`` (a warning says when an RTL
paragraph is encoded without one). Subtitles (``FUN_001e7a08``) and cfe
event lines (``FUN_0024b450``) are centred per line and never wrapped by
the engine; the encoder wraps subtitles at 440 px by default (the widest
retail line is 454 px on Disc 1, 445 on Disc 2) and never pads them.
* The space is A1A1 (cell 0, pair (0, 19)): its advance is ``$xx1`` + 1, 9 px in
the subtitle and cfe states (``$xx1,8``, 0x6883F0 and 0x68CD88). The field
window's ``$xx1`` has not been read; ``--space-px 9`` is assumed for it.
Tree files, by suffix: ``.sbl.txt`` and ``.txd.txt`` block bodies (bank, menu);
``batdat.us.txt`` block bodies, each within its ``max N bytes`` and with the
first byte of a section's first string kept 20-7E or A1-FE; ``.sub.txt`` only
the text after ``time<TAB>`` on cue lines (the frame-0 cue untouched);
``.exe.txt`` block bodies within ``max N bytes``; ``.sjis.txt`` copied (quest
text cannot take new glyphs); everything else copied byte for byte. A body
with no character of a scanned script is passed through unchanged, so an
untouched tree encodes to itself. If any glyph has no slot or any block breaks
its byte budget, nothing is written.
Usage:
python langpack.py scan --iso DISC1.iso --text TREE --font F.ttf --script Arab --rtl --out FONTS
python langpack.py encode --text TREE --glyphset FONTS/glyphset.json --out TREE-ENC [--width-kind bank=360]
python langpack.py preview --glyphset FONTS/glyphset.json --text "..." --out line.png
python langpack.py --self-test
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import sys
import unicodedata
from collections import Counter, defaultdict
from pathlib import Path
from typing import Callable, Dict, List, Optional, Sequence, Tuple
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import font as fontmod # noqa: E402
import textcodec # noqa: E402
from font import Font, FontError # noqa: E402
from glyphs import (FIXED, PAIR, PREFER, SINGLE, TIERS, Glyph, GlyphError, GlyphSet, # noqa: E402
Tiers, battle_first_ok, from_png, visible_retail)
MIRROR = {"(": ")", ")": "(", "[": "]", "]": "[", "{": "}", "}": "{", "<": ">", ">": "<",
"\u00ab": "\u00bb", "\u00bb": "\u00ab"} # « » are Bidi_Mirrored too (Arabic quotation marks)
_EXE_AT = re.compile(r"### @0x([0-9A-Fa-f]+) max ") # an exe-export block header
DEFAULT_SPACE_PX = 9 # $xx1,8 + 1 in the subtitle and cfe states; assumed for the window
ICON_PX = 19 # &NN: an assumption (a fixed-width cell)
SUBTITLE_WIDTH = 440
KINDS = ("bank", "menu", "subtitle", "battle", "exe")
LIMITED_KINDS = ("battle", "exe", "subtitle")
LANGPACK = "langpack.json"
STATE_CODES = ("col", "zoom", "shadow", "bg", "alpha", "xx0", "xx1", "xx2", "xx3")
_CODE = re.compile(r"\$[A-Za-z][^;$\n⟦]{0,40};")
_STATE = re.compile(r"\$(col|zoom|shadow|bg|alpha|xx[0-9])")
_BREAK = re.compile(r"\\n|\n|⟦0[Aa]⟧")
_FMT = re.compile(r"%[A-Za-z]")
_ICON = re.compile(r"&[0-9]{2}")
# '<○>' (also <△> <□> <×>): the field window draws the button picture and neither bracket.
# Seen in PCSX2 on the LANGTEST disc (2026-11-20): an RTL line holding '<○>' came out one
# '<' + '>' narrower than its padded neighbour, and the retail sc1010 #0006 line measures
# as drawn only without the brackets. So the tag is one unit as wide as its symbol.
_BUTTON = re.compile(r"<[○△□×]>")
_ESC = re.compile(r"⟦[0-9A-Fa-f]{2}⟧")
_MAX = re.compile(r"\bmax (\d+) bytes\b")
class LangError(ValueError):
pass
# --- scripts ---------------------------------------------------------------------
_SCRIPT_RANGES = sorted([
(0x0600, 0x06FF, "Arab"), (0x0750, 0x077F, "Arab"), (0x08A0, 0x08FF, "Arab"),
(0xFB50, 0xFDFF, "Arab"), (0xFE70, 0xFEFF, "Arab"),
(0x0590, 0x05FF, "Hebr"), (0xFB1D, 0xFB4F, "Hebr"),
(0x0700, 0x074F, "Syrc"), (0x0780, 0x07BF, "Thaa"),
(0x0900, 0x097F, "Deva"), (0xA8E0, 0xA8FF, "Deva"), (0x0980, 0x09FF, "Beng"),
(0x0A00, 0x0A7F, "Guru"), (0x0A80, 0x0AFF, "Gujr"), (0x0B80, 0x0BFF, "Taml"),
(0x0C00, 0x0C7F, "Telu"), (0x0C80, 0x0CFF, "Knda"), (0x0D00, 0x0D7F, "Mlym"),
(0x0D80, 0x0DFF, "Sinh"), (0x0E00, 0x0E7F, "Thai"),
(0x1200, 0x139F, "Ethi"), (0x2D80, 0x2DDF, "Ethi"), (0xAB00, 0xAB2F, "Ethi"),
(0x10A0, 0x10FF, "Geor"), (0x1C90, 0x1CBF, "Geor"), (0x2D00, 0x2D2F, "Geor"),
(0x0530, 0x058F, "Armn"), (0xFB13, 0xFB17, "Armn"),
(0x0400, 0x052F, "Cyrl"), (0x1C80, 0x1C8F, "Cyrl"), (0x2DE0, 0x2DFF, "Cyrl"), (0xA640, 0xA69F, "Cyrl"),
(0x0370, 0x03FF, "Grek"), (0x1F00, 0x1FFF, "Grek"),
])
RTL_SCRIPTS = {"Arab", "Hebr", "Syrc", "Thaa"}
def script_of(ch: str) -> Optional[str]:
o = ord(ch)
for lo, hi, tag in _SCRIPT_RANGES:
if lo <= o <= hi:
return tag
if o < lo:
break
return None
def _joiner(ch: str) -> bool:
"""Characters that belong to the run before them: combining marks, ZWJ, ZWNJ."""
return unicodedata.category(ch) in ("Mn", "Mc", "Me") or ch in "\u200c\u200d"
def _is_native(s: str) -> bool:
"""The disc's own Japanese (kana, kanji, full-width forms): left alone."""
return any(0x3000 <= ord(c) <= 0x30FF or 0x3400 <= ord(c) <= 0x9FFF
or 0xFF00 <= ord(c) <= 0xFFEF or 0x2500 <= ord(c) <= 0x25FF for c in s)
_US = textcodec.UsCodec()
def _drawable(ch: str) -> bool:
"""Can the USA build draw this character as it is (ASCII, Latin-1, the retail symbol pairs)?"""
if ord(ch) < 0x80:
return True
try:
_US.encode_char(ch)
return True
except textcodec.TextError:
return False
def _direction(word: str) -> str:
"""R (right-to-left strong), L (left-to-right strong), E (numbers), N."""
classes = {unicodedata.bidirectional(c) for c in word}
if classes & {"R", "AL"}:
return "R"
if "L" in classes:
return "L"
if classes & {"EN", "AN"}:
return "E"
return "N"
# --- Arabic presentation forms (the PNG-cell shaper) --------------------------------
# letter -> (isolated, final, initial, medial); two entries = right-joining only
_ARABIC = {
0x0621: (0xFE80,), 0x0622: (0xFE81, 0xFE82), 0x0623: (0xFE83, 0xFE84),
0x0624: (0xFE85, 0xFE86), 0x0625: (0xFE87, 0xFE88),
0x0626: (0xFE89, 0xFE8A, 0xFE8B, 0xFE8C), 0x0627: (0xFE8D, 0xFE8E),
0x0628: (0xFE8F, 0xFE90, 0xFE91, 0xFE92), 0x0629: (0xFE93, 0xFE94),
0x062A: (0xFE95, 0xFE96, 0xFE97, 0xFE98), 0x062B: (0xFE99, 0xFE9A, 0xFE9B, 0xFE9C),
0x062C: (0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0), 0x062D: (0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4),
0x062E: (0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8), 0x062F: (0xFEA9, 0xFEAA),
0x0630: (0xFEAB, 0xFEAC), 0x0631: (0xFEAD, 0xFEAE), 0x0632: (0xFEAF, 0xFEB0),
0x0633: (0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4), 0x0634: (0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8),
0x0635: (0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC), 0x0636: (0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0),
0x0637: (0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4), 0x0638: (0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8),
0x0639: (0xFEC9, 0xFECA, 0xFECB, 0xFECC), 0x063A: (0xFECD, 0xFECE, 0xFECF, 0xFED0),
0x0640: (0x0640, 0x0640, 0x0640, 0x0640),
0x0641: (0xFED1, 0xFED2, 0xFED3, 0xFED4), 0x0642: (0xFED5, 0xFED6, 0xFED7, 0xFED8),
0x0643: (0xFED9, 0xFEDA, 0xFEDB, 0xFEDC), 0x0644: (0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0),
0x0645: (0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4), 0x0646: (0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8),
0x0647: (0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC), 0x0648: (0xFEED, 0xFEEE),
0x0649: (0xFEEF, 0xFEF0), 0x064A: (0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4),
}
_LAM_ALEF = {0x0622: (0xFEF5, 0xFEF6), 0x0623: (0xFEF7, 0xFEF8),
0x0625: (0xFEF9, 0xFEFA), 0x0627: (0xFEFB, 0xFEFC)}
def arabic_forms(word: str) -> List[str]:
"""Contextual presentation forms for one word, logical order; marks are dropped."""
letters = [c for c in word if not (0x064B <= ord(c) <= 0x0652 or ord(c) == 0x0670)]
out: List[str] = []
i = 0
prev_joins = False
while i < len(letters):
c = letters[i]
o = ord(c)
forms = _ARABIC.get(o)
if forms is None:
out.append(c)
prev_joins = False
i += 1
continue
nxt = ord(letters[i + 1]) if i + 1 < len(letters) else None
if o == 0x0644 and nxt in _LAM_ALEF:
iso, fin = _LAM_ALEF[nxt]
out.append(chr(fin if prev_joins else iso))
prev_joins = False
i += 2
continue
dual = len(forms) == 4
next_joins = nxt in _ARABIC
if prev_joins and dual and next_joins:
f = forms[3]
elif prev_joins:
f = forms[1] if len(forms) > 1 else forms[0]
elif dual and next_joins:
f = forms[2]
else:
f = forms[0]
out.append(chr(f))
prev_joins = dual and next_joins
i += 1
return out
# --- shapers ---------------------------------------------------------------------
class SimpleShaper:
"""Hand-drawn PNG cells: one key per character (presentation forms for Arabic)."""
name = "cells"
def __init__(self):
self.notdef: set = set()
def keys(self, word: str, rtl: bool) -> List[str]:
if any(0x0600 <= ord(c) <= 0x06FF for c in word):
seq = [f"u:{f}" for f in arabic_forms(word)]
else:
seq = [f"u:{c}" for c in word if unicodedata.category(c) != "Mn"]
return seq[::-1] if rtl else seq # visual order, like HarfBuzz
def glyph(self, key: str):
return None
class HBShaper:
"""HarfBuzz shaping through glyphs.TTFRenderer; keys name glyph ids."""
name = "harfbuzz"
def __init__(self, renderer, script: Optional[str], language: Optional[str], max_cluster_px: int = 18):
self.r = renderer
self.script = script
self.language = language
self.max_cluster = max_cluster_px
self._parts: Dict[str, list] = {}
self._adv: Dict[str, int] = {}
self._cache: Dict[Tuple[str, bool], List[str]] = {}
self.notdef: set = set() # words the font had no glyph for
def keys(self, word: str, rtl: bool) -> List[str]:
hit = self._cache.get((word, rtl))
if hit is not None:
return hit
r = self.r
glyphs = r.shape(word, "rtl" if rtl else "ltr", self.script, self.language)
if any(g[0] == 0 for g in glyphs):
self.notdef.add(word)
groups: List[list] = []
for g in glyphs:
if groups and groups[-1][0][1] == g[1]:
groups[-1].append(g)
else:
groups.append([g])
out = []
for grp in groups:
if len(grp) == 1:
out.append(f"g:{r.name}:{grp[0][0]}")
continue
pen = 0.0
parts = []
for gid, _, adv, xo, yo in grp:
parts.append((gid, (pen + xo) * r.scale, yo * r.scale))
pen += adv
if pen * r.scale <= self.max_cluster:
key = "c:%s:%s" % (r.name, ";".join(f"{gid}@{dx:.1f},{dy:.1f}" for gid, dx, dy in parts))
self._parts[key] = parts
self._adv[key] = round(pen * r.scale)
out.append(key)
else:
out += [f"g:{r.name}:{gid}" for gid, *_ in grp]
self._cache[(word, rtl)] = out
return out
def glyph(self, key: str) -> Glyph:
kind, _, rest = key.partition(":")
if kind == "g":
return self.r.render_gid(int(rest.split(":")[1]))
if kind == "c":
parts = self._parts.get(key)
if parts is None:
parts = []
for p in rest.split(":", 1)[1].split(";"):
gid, _, off = p.partition("@")
dx, dy = off.split(",")
parts.append((int(gid), float(dx), float(dy)))
return self.r.render_cluster(parts, key, self._adv.get(key))
return self.r.render_text(rest, key)
def make_shaper(cfg: dict):
if cfg.get("ttf"):
from glyphs import TTFRenderer
r = TTFRenderer(cfg["ttf"], cfg.get("px", 18.0), cfg.get("baseline", 19), cfg.get("face", 0))
return HBShaper(r, cfg.get("script"), cfg.get("language"))
return SimpleShaper()
# --- the encoder -------------------------------------------------------------------
class Item:
__slots__ = ("kind", "text", "keys", "dir", "width", "pre", "state", "level", "verbatim")
def __init__(self, kind, text="", keys=(), d="N", width=0, pre="", state=None, verbatim=False):
self.kind, self.text, self.keys, self.dir, self.width = kind, text, list(keys), d, width
self.verbatim = verbatim # a control token (<○>, &NN): placed like a neutral, never mirrored
self.pre = pre # control text in front of it (state codes too, as written)
self.state = dict(state or {}) # state codes in effect when it is drawn
self.level = 0
class Encoder:
"""Encodes one body (a string of the tree) at a time.
``configs`` is the list from langpack.json; ``widths`` maps a kind to its wrap
width (0 = no wrap). With ``collect`` set the encoder only gathers glyph keys
(scan); ``only`` limits that to one config index."""
def __init__(self, configs: List[dict], glyphset: GlyphSet, adr: "fontmod.Addressing",
metrics: Sequence[Tuple[int, int]], rtl: Optional[bool] = None,
widths: Optional[Dict[str, int]] = None, align: str = "left",
space_px: int = DEFAULT_SPACE_PX, collect: bool = False, only: Optional[int] = None,
shapers: Optional[list] = None):
self.configs = configs
self.gs = glyphset
self.adr = adr
self.metrics = metrics
self.rtl = rtl
self.widths = dict(widths or {})
self.align = align
self.space_px = space_px
self.collect = collect
self.only = only
self._shapers = list(shapers) if shapers else [None] * len(configs)
self.counts: Counter = Counter()
self.kinds_of: Dict[str, set] = defaultdict(set)
self.script_uses: Counter = Counter()
self.missing: Counter = Counter()
self.unknown: Counter = Counter()
self.typed: Dict[int, Tuple[int, str, str]] = {} # cell -> (uses, character, where) of typed Latin-1
# tree file name -> {address: retail bytes} of the executables' strings (retail_exe_strings),
# so an untouched executable string is not taken for typed text; None: not known
self.retail_exe: Optional[Dict[str, Dict[int, bytes]]] = None
self.exe_unchecked = 0
self.provisional: Dict[str, int] = {}
self.warnings: List[str] = []
self.errors: List[str] = []
self._first: Optional[list] = None
self._emitted_any = False
self.widest: Dict[str, Tuple[int, str]] = {}
self.kind = "bank"
self.where = ""
self._claims = {c.get("script"): i for i, c in enumerate(configs) if c.get("script")}
self._catchall = next((i for i, c in enumerate(configs) if not c.get("script")), None)
# configs and shapers
def shaper(self, i: int):
if self._shapers[i] is None:
self._shapers[i] = make_shaper(self.configs[i])
return self._shapers[i]
def char_class(self, ch: str):
"""'a' ASCII letter/digit, 'p' ASCII other, 'n' drawable as it is, an int (the
config that shapes it), or '?' (no config and not drawable)."""
o = ord(ch)
if o < 0x80:
return "a" if ch.isalnum() else "p"
tag = script_of(ch)
if tag in self._claims:
return self._claims[tag]
if _is_native(ch) or _drawable(ch):
return "n"
if self._catchall is not None:
return self._catchall
return "?"
def targets(self, text: str) -> bool:
"""Does ``text`` hold a character this project shapes (or cannot draw at all)?"""
for ch in _ESC.sub("", text):
if ord(ch) >= 0x80:
cls = self.char_class(ch)
if not isinstance(cls, str) or cls == "?":
return True
return False
# measuring
def lit_width(self, text: str) -> int:
try:
data = _US.from_text(text)
return self.adr.measurer(self.metrics, han=True, prop=True, xx1=self.space_px - 1).width(data)
except (FontError, textcodec.TextError):
return 0
def key_width(self, key: str) -> int:
if key in self.gs.slots:
return self.gs.advance(key, self.adr.prop_pad)
return self.provisional.get(key, 10)
# tokens -> items
def _runs(self, units: List[str]) -> List[Tuple[object, str]]:
out: List[Tuple[object, str]] = []
for u in units:
if u.startswith("⟦") and len(u) == 4:
cls = "e"
elif _joiner(u) and out and not isinstance(out[-1][0], str):
cls = out[-1][0]
else:
cls = self.char_class(u)
if out and out[-1][0] == cls:
out[-1] = (cls, out[-1][1] + u)
else:
out.append((cls, u))
return out
def _word_items(self, word: str, state: dict, pre: str) -> List[Item]:
units, i = [], 0
while i < len(word):
m = _ESC.match(word, i)
if m:
units.append(m.group(0))
i = m.end()
else:
units.append(word[i])
i += 1
items = []
for cls, text in self._runs(units):
if cls == "e":
bytes_ = _US.from_text(text)
d = "L" if any(b >= 0x80 for b in bytes_) else "N"
it = Item("lit", text, d=d, width=self.lit_width(text))
elif isinstance(cls, int):
d = _direction(text)
if self.only is not None and cls != self.only:
it = Item("keys", text, d=d)
else:
keys = self.shaper(cls).keys(text, d == "R")
self.script_uses[self.configs[cls].get("script") or "*"] += len(keys)
if self.collect:
self.counts.update(keys)
for k in keys:
self.kinds_of[k].add(self.kind)
w = 0
for k in keys:
if not self.collect and k not in self.gs.slots:
self.missing[k] += 1
w += self.key_width(k)
it = Item("keys", text, keys, d, w)
elif cls == "?":
for ch in text:
self.unknown[ch] += 1
it = Item("lit", text, d=_direction(text), width=0)
else:
it = Item("lit", text, d=_direction(text), width=self.lit_width(text))
it.pre, it.state = pre, dict(state)
pre = ""
items.append(it)
# UBA W5: a currency or percent sign (ET) next to a number takes the number's direction
for i, it in enumerate(items):
if it.kind == "lit" and it.text and all(unicodedata.bidirectional(c) == "ET" for c in it.text):
if any(0 <= j < len(items) and items[j].dir == "E" for j in (i - 1, i + 1)):
it.dir = "E"
return items
def items(self, text: str, state: dict) -> Tuple[List[Item], dict]:
"""One paragraph (no line breaks) -> items, and the state after it."""
state = dict(state)
items: List[Item] = []
pre = ""
i, n = 0, len(text)
word_start = None
def flush_word(end):
nonlocal pre, word_start
if word_start is not None:
items.extend(self._word_items(text[word_start:end], state, pre))
pre = ""
word_start = None
while i < n:
m = _CODE.match(text, i) if text[i] == "$" else None
if m:
flush_word(i)
tok = m.group(0)
s = _STATE.match(tok)
if s:
state[s.group(1)] = tok
pre += tok
i = m.end()
continue
m = (_FMT.match(text, i) if text[i] == "%" else None)
if m:
flush_word(i)
pre += m.group(0)
i = m.end()
continue
m = (_BUTTON.match(text, i) if text[i] == "<" else None)
if m:
flush_word(i)
it = Item("lit", m.group(0), d="N", width=self.lit_width(m.group(0)[1]), pre=pre, state=state,
verbatim=True)
pre = ""
items.append(it)
i = m.end()
continue
m = (_ICON.match(text, i) if text[i] == "&" else None)
if m:
flush_word(i)
# its own kind: an icon code is never reversed or mirrored in a right-to-left line
it = Item("icon", m.group(0), d="N", width=ICON_PX, pre=pre, state=state)
pre = ""
items.append(it)
i = m.end()
continue
if text[i] == " ":
flush_word(i)
j = i
while j < n and text[j] == " ":
j += 1
if pre:
items.append(Item("ctrl", pre=pre, state=state))
pre = ""
items.append(Item("space", text[i:j], d="N", width=self.space_px * (j - i), state=state))
i = j
continue
if word_start is None:
word_start = i
i += 1
flush_word(n)
if pre:
items.append(Item("ctrl", pre=pre, state=state))
return items, state
# wrapping
def _wrap(self, items: List[Item], width: int) -> List[List[Item]]:
"""Greedy fill; breaks only at spaces, so a word and the punctuation or codes
glued to it travel together. The spaces at a break are dropped."""
groups, grp = [], []
for it in items:
if it.kind == "space":
if grp:
groups.append(grp)
groups.append([it])
grp = []
else:
grp.append(it)
if grp:
groups.append(grp)
lines, cur, cur_w = [], [], 0
for g in groups:
w = sum(it.width for it in g)
if g[0].kind == "space":
if cur:
cur += g
cur_w += w
continue
if cur and cur_w + w > width:
while cur and cur[-1].kind == "space":
cur.pop()
lines.append(cur)
cur, cur_w = [], 0
cur += g
cur_w += w
while cur and cur[-1].kind == "space":
cur.pop()
if cur or not lines:
lines.append(cur)
return lines
# emitting
def _order(self, items: List[Item], base_rtl: bool) -> List[int]:
if not base_rtl: # a left-to-right paragraph (or --ltr): logical order
for it in items:
it.level = 0
return list(range(len(items)))
base = 1
levels: List[Optional[int]] = []
for it in items:
if it.dir == "R":
levels.append(1)
elif it.dir in ("L", "E"):
levels.append(2 if base_rtl else 0)
else:
levels.append(None)
for i, lv in enumerate(levels):
if lv is None:
prev = next((levels[j] for j in range(i - 1, -1, -1) if levels[j] is not None), base)
nxt = next((levels[j] for j in range(i + 1, len(levels)) if levels[j] is not None), base)
levels[i] = prev if prev == nxt else base
for it, lv in zip(items, levels):
it.level = lv
order = list(range(len(items)))
for lv in (2, 1): # UBA L2: reverse runs at each level from the highest down to 1
i = 0
while i < len(order):
if levels[order[i]] >= lv:
j = i
while j < len(order) and levels[order[j]] >= lv:
j += 1
order[i:j] = order[i:j][::-1]
i = j
else:
i += 1
return order
def _emit(self, items: List[Item], base_rtl: bool, start: dict, end: dict, pad_to: int = 0
) -> List[Tuple[str, str]]:
"""-> atoms ('t', text) / ('k', key) in visual order."""
order = self._order(items, base_rtl)
atoms: List[Tuple[str, str]] = []
if order == list(range(len(items))) and not base_rtl:
for it in items:
atoms.append(("t", it.pre))
atoms += self._render(it, False)
return [a for a in atoms if a[0] == "k" or a[1]]
cur = dict(start)
if items: # codes in front of the first logical word stay first
atoms.append(("t", _strip_state(items[0].pre)))
if pad_to:
line_w = sum(it.width for it in items)
if line_w < pad_to:
atoms.append(("t", " " * ((pad_to - line_w) // self.space_px)))
for idx in order:
it = items[idx]
if it.kind != "space": # a space is drawn the same in any state
for k, v in it.state.items():
if cur.get(k) != v:
atoms.append(("t", v))
cur[k] = v
for k in cur:
if k not in it.state and it.kind in ("lit", "keys", "icon"):
self.warnings.append(f"{self.where}: the {k} code cannot be undone for the words before "
f"it (their state before the code is not known); it carries onto them")
if idx != 0:
atoms.append(("t", _strip_state(it.pre)))
atoms += self._render(it, base_rtl)
for k, v in end.items():
if cur.get(k) != v:
atoms.append(("t", v))
return [a for a in atoms if a[0] == "k" or a[1]]
def _render(self, it: Item, rtl: bool) -> List[Tuple[str, str]]:
if it.kind == "icon": # &NN: as written, whatever the direction
return [("t", it.text)]
if it.kind in ("space", "lit"):
s = it.text
if rtl and it.kind == "lit" and it.level == 1 and not it.verbatim: # neutral ASCII inside RTL
s = "".join(MIRROR.get(c, c) for c in s)
if it.dir == "N" and not _ESC.search(s):
s = s[::-1]
return [("t", s)]
if it.kind == "keys":
if not it.keys: # another config's run (scan --script)
return [("t", it.text)]
return [("k", k) for k in it.keys]
return []
def _atoms_text(self, atoms) -> str:
out = []
for kind, v in atoms:
if kind == "t":
out.append(v)
elif v in self.gs.slots:
out.append("".join(f"⟦{b:02X}⟧" for b in self.gs.code_bytes(v)))
else:
out.append("⟦A1⟧⟦A1⟧") # no slot: encode refuses anyway
return "".join(out)
def _check_atoms(self, atoms) -> Optional[str]:
"""Every glyph code is read by the game where it was written (no lone lead byte
before it takes its first byte as a trail)."""
data, spans = bytearray(), []
for kind, v in atoms:
if kind == "t":
try:
data += _US.from_text(v)
except textcodec.TextError:
return None # text-import reports it
elif v in self.gs.slots:
b = self.gs.code_bytes(v)
spans.append((len(data), len(b), v))
data += b
data = bytes(data)
starts, i = {}, 0
while i < len(data):
n = _US.read(data, i) if data[i] >= 0x80 else 1
starts[i] = n
i += n
for a, n, key in spans:
if starts.get(a) != n:
return (f"{self.where}: the glyph {key} would not be read as written (a lone lead byte "
f"such as ¡ ¢ ¤ ¦ or the soft hyphen stands in front of it)")
return None
def paragraph(self, text: str, state: dict, width: int, rtl_ok: bool, pad: bool) -> Tuple[List[str], dict]:
items, end_state = self.items(text, state)
has_r = any(it.dir == "R" for it in items)
base_rtl = has_r and rtl_ok
if base_rtl and not width and self.kind == "bank" and not self.collect:
self.warnings.append(f"{self.where}: a right-to-left paragraph encoded with no --width; the field window "
f"re-wraps lines that are too wide from the left (give --width-kind bank=PX)")
lines = self._wrap(items, width) if width else [items]
out, cur = [], dict(state)
for line in lines:
end = dict(line[-1].state) if line else dict(cur)
atoms = self._emit(line, base_rtl, cur, end, width if pad and base_rtl and width else 0)
if self.collect:
if not self._emitted_any:
self._first = atoms[:1]
else:
why = self._check_atoms(atoms)
if why:
self.warnings.append(why)
self.errors.append(why)
text_out = self._atoms_text(atoms)
w = sum(it.width for it in line)
if w > self.widest.get(self.kind, (-1, ""))[0]:
self.widest[self.kind] = (w, f"{self.where}: {text[:50]}")
out.append(text_out)
self._emitted_any = self._emitted_any or bool(text_out)
cur = end
return out, end_state
def string(self, body: str, kind: str = "bank", where: str = "") -> str:
"""A whole body (one string of the tree, ``\\n`` as two characters) -> encoded body.
A body with no character this project shapes comes back unchanged."""
self.kind, self.where = kind, where
self._first = None
self._emitted_any = False
target = self.targets(body)
self._note_typed(body, target)
if not target:
return body
width = self.widths.get(kind, 0)
rtl_ok = self.rtl is not False
pad = self.align == "right" and kind in ("bank", "menu")
brk = "⟦0A⟧" if kind == "exe" else "\\n"
head = ""
if body.startswith("[") and "]" in body:
j = body.index("]")
inner = body[1:j]
if self.targets(inner):
lines, _ = self.paragraph(inner, {}, 0, rtl_ok, False)
inner = "".join(lines)
head, body = "[" + inner + "]", body[j + 1:]
self._emitted_any = True
parts = _BREAK.split(body)
seps = _BREAK.findall(body)
state: dict = {}
out = []
for p in parts:
if not p.strip(" ") or not self.targets(p):
out.append(p)
if p:
state = self.items(p, state)[1]
self._emitted_any = True
continue
lead = p[:len(p) - len(p.lstrip(" "))]
tail = p[len(p.rstrip(" ")):]
core = p.strip(" ")
self._emitted_any = self._emitted_any or bool(lead)
lines, state = self.paragraph(core, state, width, rtl_ok, pad)
out.append(lead + brk.join(lines) + tail)
self._emitted_any = True
res = out[0] + "".join(s + t for s, t in zip(seps, out[1:]))
res = head + res
if res.startswith("#"):
res = "⟦23⟧" + res[1:]
return res
def _note_typed(self, body: str, target: bool) -> None:
"""Record the cell of every non-ASCII character the tree types that the USA
build draws as it is (Latin-1 such as « » £ é): it is written as its own byte,
so its cell must not be given to a new glyph. The disc's own Japanese and the
⟦XX⟧ escapes are left out. A body the encoder leaves alone is left out too when
the retail reserve would skip it (glyphs.visible_retail): text-export shows the
EUC-JP developer lines as Latin-1 (e.g. 'ͽÈ÷£±'), and the player never sees them.
An executable string (``.exe.txt``) without the new script is left out when it
still holds its retail bytes: exe-export lists data and developer strings whose
bytes read as Latin-1 (EUC-JP fullwidth letters, pointers, a JPEG marker), the
retail reserve does not cover the executables either, and exe-import writes
only the strings that changed. Without the retail strings (lang-encode with no
--iso) such bodies are not checked, and the encoder says so."""
if not target and self.kind == "exe":
m = _EXE_AT.search(self.where)
if self.retail_exe is None or not m:
self.exe_unchecked += 1
return
rel = self.where.split(" ### ", 1)[0].rsplit("/", 1)[-1]
try:
if self.retail_exe.get(rel, {}).get(int(m.group(1), 16)) == _US.from_text(body):
return
except textcodec.TextError:
pass
elif not target:
try:
if not visible_retail(_US.from_text(body)):
return
except textcodec.TextError:
pass
for ch in _ESC.sub("", body):
if ord(ch) < 0x80 or _is_native(ch):
continue
if self.char_class(ch) != "n":
continue
for c in {ch, MIRROR.get(ch, ch)}: # a mirrored « is written as »
try:
data = _US.encode_char(c)
cell = self.adr.glyph(data + b"\x00", 0, han=True).cell
except (textcodec.TextError, FontError):
continue
if cell is None:
continue
n, c0, w0 = self.typed.get(cell, (0, c, self.where))
self.typed[cell] = (n + 1, c0, w0)
def typed_conflicts(self) -> List[str]:
"""Typed characters whose cell holds a glyph of the glyphset: the game would draw
the new glyph in their place."""
by_cell = {s["cell"]: k for k, s in self.gs.slots.items()}
out = []
for cell, (n, ch, where) in sorted(self.typed.items()):
if cell in by_cell:
out.append(f"{ch!r} (U+{ord(ch):04X}, typed {n} time(s), e.g. {where}) is written as byte(s) "
f"{_US.encode_char(ch).hex().upper()}, whose cell {cell} now holds the glyph "
f"{by_cell[cell]}; run lang-scan again on this tree (it reserves typed characters) "
f"or replace the character")
return out
def first_key(self) -> Optional[str]:
"""After ``string`` in collect mode: the glyph key drawn first, if the encoded
string would start with a glyph code."""
f = self._first or []
return f[0][1] if f and f[0][0] == "k" else None
def _strip_state(pre: str) -> str:
return "".join(t for t in re.findall(r"\$[A-Za-z][^;$\n⟦]{0,40};|[^$]+|\$", pre) if not _STATE.match(t))
# --- trees -----------------------------------------------------------------------
def tree_kind(path: Path) -> Optional[str]:
n = path.name.lower()
if n.endswith(".sbl.txt"):
return "bank"
if n.endswith(".txd.txt"):
return "menu"
if n.endswith("batdat.us.txt"):
return "battle"
if n.endswith(".sub.txt"):
return "subtitle"
if n.endswith(".exe.txt"):
return "exe"
if n.endswith(".sjis.txt"):
return "sjis"
return None
def _read_text(raw: bytes) -> Tuple[str, bool]:
bom = raw.startswith(b"\xef\xbb\xbf")
return raw[3:].decode("utf-8") if bom else raw.decode("utf-8"), bom
class Block:
def __init__(self, header: str, body: str, index: int):
self.header, self.body, self.index = header, body, index
def transform_blocks(text: str, fn: Callable[[Block], str], marker: str = "### ") -> str:
"""A block file with each body passed through ``fn``; a body ``fn`` returns
unchanged leaves its lines exactly as they were (textpack.parse_blocks reading)."""
lines = text.split("\n")
blocks: List[Tuple[str, List[int]]] = []
for n, line in enumerate(lines):
bare = line.rstrip("\r")
if bare.startswith(marker):
blocks.append((bare[len(marker):].strip(), []))
elif bare.startswith("#"):
continue
elif blocks:
blocks[-1][1].append(n)
drop = set()
for bi, (head, idx) in enumerate(blocks):
while len(idx) > 1 and lines[idx[-1]].rstrip("\r") == "":
idx = idx[:-1]
body = "\\n".join(lines[i].rstrip("\r") for i in idx)
new = fn(Block(head, body, bi))
if new == body:
continue
if "\n" in new:
raise LangError(f"### {head}: an encoded body may not hold a real line break")
if not idx:
raise LangError(f"### {head}: a block without a body line")
cr = "\r" if lines[idx[0]].endswith("\r") else ""
lines[idx[0]] = new + cr
drop.update(idx[1:])
return "\n".join(l for n, l in enumerate(lines) if n not in drop)
_ZERO_TIME = re.compile(r"[0:+]*0[0:]*")
def transform_subtitle(text: str, fn: Callable[[str, int], str]) -> str:
"""Only the text after ``time<TAB>`` on cue lines; ';' lines, the frame-0 cue and
every other line stay as they are."""
out = []
for n, line in enumerate(text.split("\n"), 1):
bare = line.rstrip("\r")
cr = line[len(bare):]
if bare.startswith(";") or "\t" not in bare:
out.append(line)
continue
time, _, rest = bare.partition("\t")
if not time.strip() or _ZERO_TIME.fullmatch(time.strip()):
out.append(line)
continue
ws = rest[:len(rest) - len(rest.lstrip(" \t"))]
body = rest[len(ws):]
new = fn(body, n)
out.append(line if new == body else f"{time}\t{ws}{new}{cr}")
return "\n".join(out)
class TreeResult:
def __init__(self):
self.files: Dict[str, bytes] = {} # relative path -> bytes to write
self.errors: List[str] = []
self.budgets: List[Tuple[str, int, int, bool]] = [] # where, encoded bytes, max, changed
self.sub_lines: List[Tuple[str, int, int]] = [] # where, bytes, px
self.changed = 0
def _battle_firsts(text: str) -> set:
firsts, seen = set(), set()
for bi, (head, _) in enumerate(_blocks_heads(text)):
sec = head.split()[0] if head else ""
if sec not in seen:
seen.add(sec)
firsts.add(bi)
return firsts
def _blocks_heads(text: str) -> List[Tuple[str, int]]:
out = []
for line in text.split("\n"):
bare = line.rstrip("\r")
if bare.startswith("### "):
out.append((bare[4:].strip(), 0))
return out
def run_tree(roots: Sequence[Path], enc: Encoder, collect_first: Optional[set] = None) -> TreeResult:
"""Encode (or, in collect mode, scan) every file of the trees. Nothing is written here."""
res = TreeResult()
seen_rel = {}
for root in roots:
root = Path(root)
if not root.is_dir():