Repository navigation
Expand file tree
/
Copy pathlangpack.py
More file actions
2437 lines (2215 loc) · 110 KB
/
Copy pathlangpack.py
File metadata and controls
2437 lines (2215 loc) · 110 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 III into scripts its font never had (Arabic,
Hebrew, Devanagari, Georgian, Japanese on the USA build, ...): shape, wrap,
order and encode text for the game's font.
Borrowed from Xenosaga1PythonExtractor/langpack.py (2026-11-20). Kept: the
pipeline (scan -> encode -> preview), ``arabic_forms`` and ``SimpleShaper`` (for
the hand-drawn ``--cells`` sheet only), ``HBShaper`` (HarfBuzz clusters as glyph
keys), the bidi pass (rewritten 2026-11-20 as UAX #9 proper: ``bidi_levels`` = rules
W1-W7, N0 paired brackets, N1-N2, I1-I2 on the whole paragraph before the wrap;
``reorder`` = L2 per wrapped line; L4 mirroring; checked against ICU 78), the
greedy pixel wrap, mixed-script words split into runs so their Latin halves stay Latin, ``--extend`` (a
second script into the same font pair), ``--prop-only`` / ``--wide-only``. What
changed for Episode III:
* uharfbuzz + fonttools are REQUIRED; there is no "no HarfBuzz" path for a
TrueType font (``SimpleShaper`` serves only ``--cells``, where there is no
font to shape with);
* slots come from ``glyphs.SlotModel`` (the build's addressing read from its
executable, the cells retail text draws reserved, optional USA executable
unlocks), not a fixed 256-slot block. A proportional glyph is drawn at
cell + 0x240 with its metric pair, as ``glyphs.GlyphSet.apply`` does;
* widths are measured with ``font.Measurer`` (FUN_001828a0) on the bytes the
game will see, in the ``$prop1;$han1;`` state the menus and dialogue use
(``--state`` changes it);
* the tree is the XS3 ``text-export`` tree (``textpack``: ``### KEY`` block files
and whole subtitle / .mes files, manifest FORMAT 2). Only strings in the
build's DISPLAY codec are touched (``us`` on USA / the May 2006 prototype,
``jp`` on Japan); identifiers, developers' notes (cp932 / euc_jp), the cp932
pse director scripts and ``fixed`` nj blocks are copied unchanged;
* a character is TARGET SCRIPT when the build cannot already draw it: the
display codec refuses it, or its cell has no ink in either font (e.g. Arabic,
Cyrillic, kana on USA; Arabic, Devanagari on Japan; Cyrillic and Greek ARE
drawn by the Japanese font's JIS rows and stay as typed). A paragraph without
a target character is copied byte for byte, so ``encode`` on an unmodified
tree is the identity (exit test);
* control codes pass through in place and are never shaped, mirrored or
wrapped across: ``$name...;`` commands (the executable's 18 names),
``$rubys; ... $rubye;`` spans, ``<...>`` script tags (``<f> <wNN> <lN> <colX>
<kWORD> <○>``), escaped control bytes 0x01-0x1F WITH their operands (operand
lengths from the executable's table, 0x08 / 0x15 variable), the game's line
breaks (``\\n`` typed as backslash-n, and CR LF = ``⟦0D⟧⟦0A⟧``), the speaker
prefix ``[Name]`` of a dialogue string (encoded on its own, kept first) and
the Japanese subtitle ruby ``[base/reading]``. Tags before the first word of
a paragraph stay first, tags after the last word stay last, tags between
words travel with the following word;
* ``<lN>`` is updated to the new line count when the wrap changes it and it
matched before (``sb.line_count``);
* Japanese (and any wide script) may break between any two characters;
* glyph codes are written as ``⟦XX⟧`` escapes, which ``textcodec`` turns into the
exact bytes and ``textpack.FontCheck`` does not refuse;
* ``--donor`` takes glyph images from another Episode III font (the Japanese
disc's) instead of a TrueType font: Japanese on the USA build in the game's
own kana and kanji;
* ``--unlock`` (USA / prototype only, ``glyphs.UNLOCKS``) builds the slot model of
the patched executable: ``jp-gate`` opens the 2,965 kanji cells (which the USA
font still holds) and A5 katakana codes, ``jp-prop`` makes cells 192-383 fixed
width. Under ``jp-gate`` every Latin-1 byte becomes a pair lead, so ``encode``
re-encodes EVERY display string of the tree (each retail character gets its
cell's new code, ``SlotModel.code_for``), and ``lang import`` writes the patched
boot executable of each disc (both discs' executables) together with the text
and the fonts. Text that is not in the tree (executable / overlay strings,
``.xep``) is not re-encoded: Latin-1 there draws wrong under ``jp-gate``;
* ``--reclaim-latin`` frees the Latin-1 cells retail text draws (the 0xA0-0xFF
singles: accented letters, ``®``, ``°``...; the ``$han`` ASCII cells always stay).
Only for a tree that no longer uses them: ``encode`` refuses any display
string that still draws a reclaimed cell.
Pipeline::
text-export --iso D1 --iso D2 --out tr/en -> logical UTF-8 tree (translate it)
lang scan --iso D1 --text tr/ar --font F.ttf ... --out tr/pack
lang encode --text tr/ar --pack tr/pack --out tr/ar-enc [--width 440 --align right]
lang import --iso D1 --iso D2 --text tr/ar-enc --pack tr/pack --out OUT/ [--grow]
(= text-import + font0/font1.bin + the patched executables, one verified copy)
lang preview --pack tr/pack --text "..." --out line.png
lang preview --iso OUT/D1.iso --path 'cf\\us\\1010.sb' --key 0001 --out back.png
``lang preview`` draws through the build's own code -> cell rules and the
rebuilt font file (fixed cells at 19 px, proportional images at cell + 0x240,
advance ``right - left + 3``), so a code that lands on the wrong cell shows.
Nothing produced here has been booted in PCSX2.
python langpack.py --self-test
"""
from __future__ import annotations
import argparse
import dataclasses
import json
import os
import re
import shutil
import sys
import unicodedata
from collections import Counter
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import font as fontmod # noqa: E402
import glyphs as glyphmod # noqa: E402
import region as regionmod # noqa: E402
import textcodec # noqa: E402
from font import FIXED_ADVANCE, Addressing, Font, FontError # noqa: E402
from glyphs import Glyph, GlyphError, GlyphSet, SlotModel # noqa: E402
# Bidi_Paired_Bracket pairs (UAX #9 BD14-BD16, BidiBrackets.txt) for the characters
# this kit can meet, and Bidi_Mirroring_Glyph (rule L4) for those plus the angle
# quotes and less/greater-than (mirrored, but not paired brackets).
# U+2329/U+232A are canonically equivalent to U+3008/U+3009 and BD16 pairs
# canonical equivalents. ICU does it by pushing an angle opener twice: the
# equivalent closer first, then its own (``_BRACKET_ALT``), so a closer that
# matches the top entry leaves the other one on the stack — ICU 78 output,
# kept as is.
_BRACKETS = "()[]{}()[]{}〈〉《》「」『』【】〔〕〖〗〘〙〚〛⦅⦆「」⁅⁆⁽⁾₍₎\u2329\u232a"
_OPEN = {_BRACKETS[i]: _BRACKETS[i + 1] for i in range(0, len(_BRACKETS), 2)}
_CLOSE = {v: k for k, v in _OPEN.items()}
_BRACKET_ALT = {"\u232a": "\u3009", "\u3009": "\u232a"}
MIRROR = dict(_OPEN, **_CLOSE)
MIRROR.update({"<": ">", ">": "<", "«": "»", "»": "«", "‹": "›", "›": "‹", "≤": "≥", "≥": "≤"})
PACK_CFG = "langpack.json"
STATES = {"prop1han1": (True, True), "prop0han1": (False, True), "prop1han0": (True, False),
"prop0han0": (False, False)}
_ESC1 = re.compile(r"⟦([0-9A-Fa-f]{2})⟧")
_TAG = re.compile(r"<[^<>\n⟦⟧]{1,40}>")
_PREFIX = re.compile(r"\[[^\[\]/\n]{1,40}\]")
_RUBY = re.compile(r"\[[^\[\]/\n]{1,40}/[^\[\]\n]{1,40}\]")
_LTAG = re.compile(r"<l(\d+)>")
# script tags that only steer the printer (page end, wait, line count, position,
# speed, colour); every other <...> tag (button marks <○> <×> <△> <□>, keywords
# <Shion> <kGnosis> <variant URTV>) draws something and is placed by the bidi pass
# as an inline object
_CTRL_TAG = re.compile(r"<(?:f|[wlxs]\d+|col[0-9A-Za-z]*)>")
def _visible_tag(t: str) -> bool:
return bool(_TAG.fullmatch(t)) and not _CTRL_TAG.fullmatch(t)
BLOCK_KINDS = ("sb", "txd", "nj", "msgdat", "batdat")
STRIP = 17 # px per strip of a cluster wider than a proportional cell
class LangError(ValueError):
pass
# --- Arabic presentation forms (for hand-drawn --cells sheets only) -------------------
# 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
(harakat) are dropped. Lam-alef becomes one ligature form."""
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
# --- shaping back-ends ----------------------------------------------------------------
class SimpleShaper:
"""Hand-drawn ``--cells`` sheets: one key per character (Arabic through the
presentation-form table). Not a fallback for a TrueType font."""
name = "cells"
def __init__(self, rtl: bool):
self.rtl = rtl
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, or a
cluster of glyphs (base + marks, a conjunct) drawn into one cell."""
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, float] = {}
self.notdef: set = set()
def keys(self, word: str, rtl: bool) -> List[str]:
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:
pen = 0.0
parts = []
for gid, _, adv, xo, yo in grp:
parts.append((gid, (pen + xo) * r.scale, yo * r.scale))
pen += adv
pen_px = pen * r.scale
lo, hi = self._extent(parts)
# one cell when the advance AND the ink fit a proportional image (origin at
# column 1: ink from column 0 to 19)
fits = pen_px <= self.max_cluster and lo >= -1.0 and hi <= 19.0
if fits and len(grp) == 1:
out.append(f"g:{r.name}:{grp[0][0]}")
continue
spec = ";".join(f"{gid}@{dx:.1f},{dy:.1f}" for gid, dx, dy in parts)
if fits:
key = f"c:{r.name}:{spec}"
self._parts[key] = parts
self._adv[key] = pen_px
out.append(key)
else:
# wider than a proportional cell (a long conjunct, a ligature, a mark
# hanging past the advance): cut the composed cluster into STRIP-px
# strips, each its own glyph whose advance is the strip width, so the
# pieces abut exactly
n = max(1, -(-int(round(pen_px)) // STRIP))
for i in range(n):
key = f"s:{r.name}:{spec}#{i}/{n}"
self._parts[key] = parts
self._adv[key] = STRIP if i < n - 1 else max(1, round(pen_px) - STRIP * (n - 1))
out.append(key)
return out
def _extent(self, parts) -> Tuple[float, float]:
"""Ink extent in px from the pen origin (outline bounds, so no raster needed)."""
if not hasattr(self, "_bounds"):
self._bounds: Dict[int, Optional[Tuple[float, float]]] = {}
lo, hi = 0.0, 0.0
for gid, dx, _dy in parts:
if gid not in self._bounds:
xs = [x for c in self.r.contours(gid) for x, _y in c]
self._bounds[gid] = (min(xs), max(xs)) if xs else None
bd = self._bounds[gid]
if bd:
lo = min(lo, dx + bd[0] * self.r.scale)
hi = max(hi, dx + bd[1] * self.r.scale)
return lo, hi
@staticmethod
def _parse_parts(spec: str) -> list:
parts = []
for p in spec.split(";"):
gid, _, off = p.partition("@")
dx, dy = off.split(",")
parts.append((int(gid), float(dx), float(dy)))
return parts
def covers(self, word: str) -> bool:
"""Does the font have every character of ``word`` (marks and joiners too)?"""
if not hasattr(self, "_cmap"):
self._cmap = set(self.r.tt.getBestCmap() or {})
return all(ord(c) in self._cmap or c in "\u200c\u200d" for c in word)
def glyph(self, key: str) -> Glyph:
kind, _, rest = key.partition(":")
if kind == "g":
return self.r.render_gid(int(rest.split(":")[1]))
if kind == "s":
body, _, frac = rest.rpartition("#")
i, n = (int(x) for x in frac.split("/"))
parts = self._parts.get(key) or self._parse_parts(body.split(":", 1)[1])
bm = self.r.raster(parts, x_origin=1.0 - STRIP * i)
for row in bm:
for x in range(fontmod.CELL_W):
if (x < 1 and i > 0) or (x >= 1 + STRIP and i < n - 1):
row[x] = 0
adv = self._adv.get(key) or (STRIP if i < n - 1 else None)
return Glyph(key, bm, adv)
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)))
g = self.r.render_cluster(parts, key)
if key in self._adv:
g.advance_hint = round(self._adv[key])
return g
return self.r.render_text(rest, key)
class Donor:
"""Glyph images from another Episode III font (``font-donor``'s source): a
character the donor build draws (its codec + addressing) becomes key
``u:<ch>`` with the donor cell's image. For Japanese on the USA build the
donor is the Japanese disc: its own kana and kanji, as the game drew them."""
def __init__(self, addr: Addressing, font: Font, codec, label: str = ""):
self.addr, self.font, self.codec, self.label = addr, font, codec, label
self._cache: Dict[str, Optional[Glyph]] = {}
@classmethod
def from_iso(cls, iso) -> "Donor":
from disc import Disc
a = Addressing.from_iso(iso)
with Disc(iso) as d:
reg = regionmod.region_of(d)
f = Font.from_bytes(d.read(fontmod.font_paths(a.font_dir)[0]))
return cls(a, f, textcodec.for_region(reg), Path(iso).name)
def glyph_for(self, ch: str) -> Optional[Glyph]:
if ch in self._cache:
return self._cache[ch]
g = None
try:
b = self.codec.encode_char(ch)
except textcodec.TextError:
b = b""
if len(b) == 2 and b[0] >= 0xA1:
gl = self.addr.glyph(b, 0, True, 0)
cell = fontmod.cell_index(gl.cell or 0)
if gl.length == 2 and cell not in (0, fontmod.FALLBACK_CELL):
bm = self.font.cell(cell)
if any(any(r) for r in bm):
g = Glyph(f"u:{ch}", [list(r) for r in bm])
self._cache[ch] = g
return g
# --- the pack: model, addressing, fonts, config --------------------------------------
def _addr_to_json(a: Addressing) -> dict:
return dataclasses.asdict(a)
def _addr_from_json(d: dict) -> Addressing:
d = dict(d)
d["han"] = tuple(d["han"])
d["extra"] = tuple(tuple(tuple(p) for p in lst) for lst in d["extra"])
for k in ("ctl", "ctl08", "commands", "clut"):
d[k] = tuple(d[k])
return Addressing(**d)
def _model_to_json(m: SlotModel) -> dict:
return {"build": m.build, "unlock": m.unlock, "gate": m.gate, "prop_cells": m.prop_cells,
"a9_row": m.a9_row, "exe_sha1": m.exe_sha1,
"codes": {str(c): v.hex().upper() for c, v in sorted(m.codes.items())},
"reserved": sorted(m.reserved), "prop": m.prop, "wide": m.wide}
def _model_from_json(d: dict) -> SlotModel:
return SlotModel(d["build"], d["unlock"], d["gate"], d["prop_cells"], d["a9_row"],
{int(c): bytes.fromhex(v) for c, v in d["codes"].items()}, set(d["reserved"]),
list(d["prop"]), list(d["wide"]), d.get("exe_sha1", ""))
class Pack:
"""What ``scan`` writes and ``encode`` / ``preview`` / ``import`` read:
glyphset.json, font0.bin, font1.bin, langpack.json (options, region, the
retail addressing, the slot model)."""
def __init__(self, cfg: dict, gs: GlyphSet, fonts: List[Font]):
self.cfg, self.gs, self.fonts = cfg, gs, fonts
self.retail = _addr_from_json(cfg["addressing"])
self.model = _model_from_json(cfg["model"])
self.unlock = cfg.get("unlock", "none")
self.addr = glyphmod.unlocked_addressing(self.retail, self.unlock) if self.unlock != "none" \
else self.retail
self.region = regionmod.by_name(cfg["region"])
self.codec = textcodec.codec_by_name(self.region.codec)
self.reclaimed = set(cfg.get("reclaimed", []))
@classmethod
def load(cls, d) -> "Pack":
d = Path(d)
if not (d / PACK_CFG).exists():
raise LangError(f"{d / PACK_CFG} is missing: give the folder 'lang scan --out' wrote")
cfg = json.loads((d / PACK_CFG).read_text(encoding="utf-8"))
gs = GlyphSet.load(d / "glyphset.json")
fonts = [Font.load(d / "font0.bin"), Font.load(d / "font1.bin")]
pk = cls(cfg, gs, fonts)
pk.dir = d
return pk
def shaper(self):
return make_shaper(self.cfg)
def donor(self) -> Optional[Donor]:
return self.donor_from_cfg(self.cfg.get("donor"), getattr(self, "dir", None))
@staticmethod
def donor_from_cfg(dn, base=None) -> Optional[Donor]:
"""The donor a pack names: its addressing (json) and its font0 (donor_font0.bin)."""
if not dn or base is None:
return None
a = _addr_from_json(dn["addressing"])
f = Font.load(Path(base) / dn["font_file"])
return Donor(a, f, textcodec.codec_by_name(dn["codec"]), dn.get("label", ""))
class MultiShaper:
"""Several TrueType fonts in one pack (``scan --extend``): a run goes to the
first font that has all its characters; ``keys`` returns None when none has
(scan leaves such runs to a later --extend scan; encode writes '?')."""
name = "multi"
def __init__(self, shapers: List[HBShaper]):
self.shapers = shapers
self.notdef: set = set()
def keys(self, word: str, rtl: bool) -> Optional[List[str]]:
for sh in self.shapers:
if sh.covers(word):
k = sh.keys(word, rtl)
self.notdef |= sh.notdef
return k
return None
def glyph(self, key: str) -> Glyph:
name = key.split(":")[1] if key.count(":") >= 2 else ""
for sh in self.shapers:
if sh.r.name == name:
return sh.glyph(key)
raise LangError(f"no font of this pack made glyph key {key!r}")
def shaper_specs(cfg: dict) -> List[dict]:
if cfg.get("shapers"):
return list(cfg["shapers"])
if cfg.get("ttf"):
return [{k: cfg.get(k) for k in ("ttf", "px", "baseline", "face", "script", "language")}]
return []
def make_shaper(cfg: dict):
specs = shaper_specs(cfg)
if specs:
shs = []
for sp in specs:
r = glyphmod.TTFRenderer(sp["ttf"], sp.get("px") or 20.0, sp.get("baseline") or 17, sp.get("face") or 0)
shs.append(HBShaper(r, sp.get("script"), sp.get("language")))
return MultiShaper(shs)
return SimpleShaper(bool(cfg.get("rtl")))
# --- what the build draws ---------------------------------------------------------------
class Drawable:
"""Can the build (after the pack's unlock) draw a character as it is, and with
which bytes? ``bytes_for`` returns (bytes, typed) - typed = the character may
stay typed in the tree (no unlock: the display codec writes those bytes) - or
None for a target-script character."""
def __init__(self, pack: "Pack", fonts: Optional[List[Font]] = None, fill_blank: bool = False):
self.p = pack
self.fill_blank = fill_blank
self.blank: Counter = Counter() # encodable characters whose cell has no ink
fonts = fonts or pack.fonts
cells = [fontmod.font_cells(f) for f in fonts]
self.ink = [c.reshape(len(c), -1).any(axis=1) for c in cells]
self.slot_cells = {s["cell"] for s in pack.gs.slots.values()}
self._jp = textcodec.codec_by_name("jp")
self._cache: Dict[str, Optional[Tuple[bytes, bool]]] = {}
def inked(self, a: Addressing, b: bytes) -> Optional[int]:
"""The cell ``b`` draws under ``a`` if it is one character with ink (or the
full-width space, cell 0), else None."""
g = a.glyph(b + b"\0", 0, True, 0)
if g.length != len(b):
return None
for f in (0, 1):
c = a.cell(b[0], b[1], f) if len(b) == 2 else (g.cell or 0)
ci = fontmod.cell_index(c)
if ci == 0:
return 0
if ci != fontmod.FALLBACK_CELL and (self.ink[f][ci] or
(a.is_prop(c) and self.ink[f][ci + fontmod.PROP_CELL_SHIFT])):
return ci
return None
def bytes_for(self, ch: str) -> Optional[Tuple[bytes, bool]]:
if ch in self._cache:
return self._cache[ch]
r = None
p = self.p
try:
b = p.codec.encode_char(ch)
except textcodec.TextError:
b = b""
if b:
cell = self.inked(p.retail, b)
if cell is None and not self.fill_blank:
# the build reads it but draws nothing (or the fallback): keep it typed, so
# an untouched retail string never changes (JP 縊 E5D0); textpack's font
# check refuses it if a translator types it anew
self.blank[ch] += 1
g = p.retail.glyph(b + b"\0", 0, True, 0)
cell = fontmod.cell_index(g.cell or 0) if g.length == len(b) else None
if cell is not None: # reclaimed cells stay typed: encode's reclaim check lists them
if p.unlock == "none":
r = (b, True)
elif cell in p.model.codes or len(b) == 2:
r = (reencode_char(p, b, cell), False)
if r is None and p.unlock != "none" and p.addr.gate == "euc":
# under jp-gate: a kanji the USA font still holds, by its own EUC code
try:
b = self._jp.encode_char(ch)
except textcodec.TextError:
b = b""
if len(b) == 2 and b == b"\xa1\xa1":
r = (b, False) # the full-width space (A1A1, cell 0): no ink to check
elif len(b) == 2 and 0xB0 <= b[0] <= 0xCF:
cell = self.inked(p.addr, b)
if cell is not None and cell >= 1024 and cell not in self.slot_cells \
and cell not in p.model.reserved:
r = (b, False)
self._cache[ch] = r
return r
def reencode_char(pack: "Pack", b: bytes, cell: int) -> bytes:
"""The code of a retail character after the unlock: unchanged if the unlocked
addressing still reads it as one character on the same cell, else the
model's code for that cell."""
g = pack.addr.glyph(b + b"\0", 0, True, 0)
if g.length == len(b) and fontmod.cell_index(g.cell or 0) == cell:
return b
return pack.model.code_for(cell)
def reencode_bytes(pack: "Pack", data: bytes) -> bytes:
"""Every character of a retail string re-coded for the unlocked executable
('$' commands and control sequences with their operands are left alone)."""
a = pack.retail
out = bytearray()
i, n = 0, len(data)
while i < n:
c = data[i]
if c == 0x24:
try:
e = a.command_at(data, i)[2]
except FontError:
e = i + 1
out += data[i:e]
i = e
elif c < 0x20:
try:
L = max(1, a.control_length(data, i))
except (FontError, IndexError):
L = 1
out += data[i:i + L]
i += L
elif c < 0x80:
out.append(c)
i += 1
else:
g = a.glyph(data, i, True, 0)
piece = data[i:i + g.length]
out += reencode_char(pack, piece, fontmod.cell_index(g.cell or 0))
i += g.length
return bytes(out)
def bytes_to_text(data: bytes) -> str:
"""Bytes as tree text that encodes back to exactly them under any codec:
printable ASCII typed, everything else (control bytes, 0x7F, high bytes) as
``⟦XX⟧``, and an ASCII byte right after a high byte escaped too (``guard``)."""
return guard("".join(chr(b) if 0x20 <= b < 0x7F else f"⟦{b:02X}⟧" for b in data))
_HIGH_THEN_TYPED = re.compile(r"(⟦[89A-Fa-f][0-9A-Fa-f]⟧)([\x20-\x7e])")
def guard(text: str) -> str:
"""Escape a typed ASCII character that directly follows an escaped high byte.
The bytes do not change; ``textcodec`` refuses a typed piece that the RETAIL
gate would fuse with an escaped lead (``⟦A6⟧]`` = A6 5D, one USA pair), which
is wrong for text meant for an unlocked executable, and two escapes may pair."""
return _HIGH_THEN_TYPED.sub(lambda m: m.group(1) + f"⟦{ord(m.group(2)):02X}⟧", text)
def cells_of(addr: Addressing, data: bytes) -> List[int]:
out = []
i, n = 0, len(data)
while i < n:
c = data[i]
if c == 0x24:
try:
i = addr.command_at(data, i)[2]
continue
except FontError:
i += 1
continue
if c < 0x20:
try:
i += max(1, addr.control_length(data, i))
except (FontError, IndexError):
i += 1
continue
if c < 0x80:
i += 1
continue
g = addr.glyph(data, i, True, 0)
out.append(fontmod.cell_index(g.cell or 0))
i += g.length
return out
# --- text atoms ----------------------------------------------------------------------------
# '$' always starts a command for the game. FUN_00184090 (the printer) logs
# "[*error*:....]" for a name it does not know and then draws the '$' as a
# character, but FUN_001828a0 (the width function every centred, right-aligned
# or wrapped box uses) skips from any '$' to the next ';' — past the end of the
# string when there is none. So a typed '$' (currency, "$5") is drawn but the
# line is measured wrong. Write the amount without it ("5 dollars", "5 USD").
DOLLAR_WARNING = ("a literal '$' is not text for the game: it is drawn, but the width function "
"skips from it to the next ';' (wrong centring/wrapping); write the amount without '$'")
class Atom:
__slots__ = ("kind", "text", "byte")
def __init__(self, kind: str, text: str, byte: int = -1):
self.kind, self.text, self.byte = kind, text, byte
def __repr__(self):
return f"{self.kind}:{self.text!r}"
def atoms(text: str, addr: Addressing, prefix: bool = False, ruby: bool = False) -> List[Atom]:
"""Split tree text into atoms: ctrl (``$cmd;``, ``<tag>``, escaped control bytes
with their operands), ruby (``$rubys;...$rubye;``, ``[base/reading]``), break
(``\\n``, ``⟦0D⟧⟦0A⟧``), prefix (a leading ``[Name]`` when ``prefix``), space,
esc (an escaped byte from 0x80 up) and char."""
out: List[Atom] = []
i, n = 0, len(text)
names = sorted(addr.commands, key=len, reverse=True)
def unit(j: int) -> Tuple[int, int]:
"""(byte value, end) of one operand unit at text[j]: an escape or a char."""
m = _ESC1.match(text, j)
if m:
return int(m.group(1), 16), m.end()
if j < n:
return (ord(text[j]) if ord(text[j]) < 0x100 else 0x3F), j + 1
return 0, j
if prefix:
m = _PREFIX.match(text)
if m:
out.append(Atom("prefix", m.group(0)))
i = m.end()
while i < n:
ch = text[i]
m = _ESC1.match(text, i)
if m:
b = int(m.group(1), 16)
if b < 0x20:
j = m.end()
if b == 0x0D:
v, e = unit(j)
if v == 0x0A and e > j:
out.append(Atom("break", text[i:e]))
i = e
continue
L = addr.ctl[b]
if L == 0xFF:
v, e = unit(j)
if b == 0x08:
L = 1 + sum(addr.ctl08[k] for k in range(8) if v >> k & 1)
else:
L = 1 + v
for _ in range(L):
_v, j = unit(j)
out.append(Atom("ctrl", text[i:j], b))
i = j
continue
if b >= 0x80:
j = m.end()
while True:
m2 = _ESC1.match(text, j)
if not m2 or int(m2.group(1), 16) < 0x80:
break
j = m2.end()
out.append(Atom("esc", text[i:j], b))
i = j
continue
out.append(Atom("ctrl", m.group(0), b)) # 0x7F
i = m.end()
continue
if ch == "\\" and text.startswith("\\n", i):
out.append(Atom("break", "\\n"))
i += 2
continue
if ch == "$":
if text.startswith("$rubys;", i):
e = text.find("$rubye;", i)
if e >= 0:
out.append(Atom("ruby", text[i:e + 7]))
i = e + 7
continue
name = next((nm for nm in names if text.startswith(nm, i + 1)), None)
e = text.find(";", i)
if name and e > 0 and "\\n" not in text[i:e]:
out.append(Atom("ctrl", text[i:e + 1]))
i = e + 1
continue
if ch == "<":
m = _TAG.match(text, i)
if m:
out.append(Atom("ctrl", m.group(0)))
i = m.end()
continue
if ch == "[" and ruby:
m = _RUBY.match(text, i)
if m:
out.append(Atom("ruby", m.group(0)))
i = m.end()
continue
if ch in " ":
out.append(Atom("space", ch))
i += 1
continue
if ch in "\r\n\t":
out.append(Atom("ctrl", ch))
i += 1
continue
out.append(Atom("char", ch))
i += 1
return out
# --- the encoder ---------------------------------------------------------------------------
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"
def _strong(t: str) -> Optional[str]:
"""Strong direction for N0-N2: L, or R (EN and AN count as R)."""
return "L" if t == "L" else ("R" if t in ("R", "AL", "EN", "AN") else None)
def bidi_levels(chars: Sequence[str], base: int, classes: Optional[Sequence[str]] = None) -> List[int]:
"""Embedding levels of one paragraph (UAX #9 rules W1-W7, N0-N2, I1-I2) with no
explicit embeddings or isolates: game text has none, so the paragraph is one
isolating run sequence with sos = eos = the paragraph direction. ``chars`` are
the paragraph's characters in logical order (an item that stands for an
escape or a control may be given as "" with its class in ``classes``).
Boundary neutrals (BN: joiners, format characters) are removed (X9) and take
the level of the character after them (the paragraph level at the end), as
ICU 78 places them. Rule L1 (trailing white space) is a
per-line rule: see ``Encoder._emit``."""
n = len(chars)
cls = list(classes) if classes is not None else [unicodedata.bidirectional(c) or "L" for c in chars]
keep = [i for i in range(n) if cls[i] not in ("BN", "LRE", "RLE", "LRO", "RLO", "PDF")]
t = [("ON" if cls[i] in ("LRI", "RLI", "FSI", "PDI") else cls[i]) for i in keep]
orig = list(t)
e = "R" if base & 1 else "L"
m = len(t)
# W1: NSM takes the type of the character before it (sos at the start)
for i in range(m):
if t[i] == "NSM":
t[i] = t[i - 1] if i else e
# W2: EN after AL (last strong) is AN; W3: AL is R
last = e
for i in range(m):
if t[i] in ("L", "R", "AL"):
last = t[i]
elif t[i] == "EN" and last == "AL":
t[i] = "AN"
t = ["R" if x == "AL" else x for x in t]
# W4: one ES between ENs, one CS between two numbers of the same type
for i in range(1, m - 1):
if t[i] == "ES" and t[i - 1] == "EN" and t[i + 1] == "EN":
t[i] = "EN"
elif t[i] == "CS" and t[i - 1] == t[i + 1] and t[i - 1] in ("EN", "AN"):
t[i] = t[i - 1]
# W5: a sequence of ETs next to an EN becomes EN
i = 0
while i < m:
if t[i] != "ET":
i += 1
continue
j = i
while j < m and t[j] == "ET":
j += 1
if (i and t[i - 1] == "EN") or (j < m and t[j] == "EN"):
t[i:j] = ["EN"] * (j - i)
i = j
# W6: remaining separators and terminators are ON; W7: EN after L is L
t = ["ON" if x in ("ES", "ET", "CS") else x for x in t]
last = e
for i in range(m):
if t[i] in ("L", "R"):
last = t[i]
elif t[i] == "EN" and last == "L":
t[i] = "L"
# N0: paired brackets (BD16: a stack of 63, mismatches skipped)
ch = [chars[i] for i in keep]
pairs, stack = [], []
for i in range(m):
if t[i] != "ON":
continue
c = ch[i]
if c in _OPEN:
if len(stack) == 63:
break
if _OPEN[c] in _BRACKET_ALT:
stack.append((i, _BRACKET_ALT[_OPEN[c]]))
stack.append((i, _OPEN[c]))
elif c in _CLOSE:
for k in range(len(stack) - 1, -1, -1):
if stack[k][1] == c:
o = stack[k][0]
pairs.append((o, i))
if any(_strong(x) for x in t[o + 1:i]):
while k and stack[k - 1][0] == o: # ICU: a resolved pair drops
k -= 1 # the opener's synonym too,
del stack[k:] # an N0d pair keeps it
break
for o, c in sorted(pairs):
inside = {_strong(x) for x in t[o + 1:c]} - {None}
if e in inside:
new = e
elif inside:
new = next((_strong(t[k]) for k in range(o - 1, -1, -1) if _strong(t[k])), e) # N0 c
else:
continue
# UAX #9 also gives marks right after a resolved bracket the bracket's
# type; ICU 78 does not (the mark stays the neutral W1 made it), and the
# kit follows ICU
for b in (o, c):
t[b] = new
# N1 / N2: neutrals take the direction around them, else the embedding's
i = 0
while i < m:
if t[i] not in ("B", "S", "WS", "ON"):
i += 1
continue
j = i
while j < m and t[j] in ("B", "S", "WS", "ON"):
j += 1
left = _strong(t[i - 1]) if i else e
right = _strong(t[j]) if j < m else e
t[i:j] = [left if left == right else e] * (j - i)
i = j
# I1 / I2
lv = []
for x in t:
if base & 1:
lv.append(base + 1 if x in ("L", "EN", "AN") else base)
else:
lv.append(base + (1 if x == "R" else 2 if x in ("EN", "AN") else 0))
out = [base] * n
nxt = base
pos = {k: j for j, k in enumerate(keep)}
for i in range(n - 1, -1, -1):
if i in pos:
nxt = out[i] = lv[pos[i]]
else:
out[i] = nxt
return out
def reorder(levels: Sequence[int]) -> List[int]:
"""Rule L2: the visual order (indices) of one line from its levels."""
order = list(range(len(levels)))
if not order:
return order
hi = max(levels)
lo = min(lv for lv in levels if lv & 1) if any(lv & 1 for lv in levels) else hi + 1
for lvl in range(hi, lo - 1, -1):
i = 0
while i < len(order):
if levels[order[i]] >= lvl:
j = i
while j < len(order) and levels[order[j]] >= lvl:
j += 1
order[i:j] = order[i:j][::-1]
i = j
else:
i += 1
return order
def _wide(ch: str) -> bool:
return unicodedata.east_asian_width(ch) in ("W", "F")
class Item:
"""One placeable piece of a paragraph: kind space / native / ascii / keys /
ctrl(trailing). ``brk`` = a line may break before it. ``text`` = its logical
characters (what the bidi pass classifies; "" for an opaque escape / ruby
piece, which counts as one strong L), ``level`` = its resolved embedding
level (``bidi_levels``)."""
__slots__ = ("kind", "payload", "dir", "width", "ctrl", "brk", "native", "text", "level")
def __init__(self, kind, payload, d, width, ctrl, brk=False, native=None, text=None):
self.kind, self.payload, self.dir, self.width, self.ctrl, self.brk, self.native = \
kind, payload, d, width, ctrl, brk, native
self.text = payload if text is None else text
self.level = 0
class Encoder:
"""Logical tree text -> the same text with target-script runs as glyph codes,
wrapped and in visual order. ``collect`` (scan) gathers glyph keys only."""
def __init__(self, pack: Pack, shaper, rtl: Optional[bool], width: int = 0, align: str = "left",
state: str = "prop1han1", collect: bool = False, donor: Optional[Donor] = None,
fonts: Optional[List[Font]] = None, fill_blank: bool = False):
self.p = pack
self.gs = pack.gs
self.shaper = shaper
self.rtl = rtl
self.width = width
self.align = align
self.prop, self.han = STATES[state]
self.collect = collect
self.donor = donor
self.fonts = fonts or pack.fonts
self.draw = Drawable(pack, self.fonts, fill_blank)
self.counts: Counter = Counter()
self.missing: Counter = Counter()
self.donor_glyphs: Dict[str, Glyph] = {}