Repository navigation
Expand file tree
/
Copy pathfont.py
More file actions
1755 lines (1569 loc) · 86.3 KB
/
Copy pathfont.py
File metadata and controls
1755 lines (1569 loc) · 86.3 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
"""font.py — Episode III's bitmap fonts (``mnu\\us\\font0.bin`` / ``font1.bin``).
Borrowed from Xenosaga2PythonExtractor/font.py (2026-11-20). What changed:
* the FILE layer is new. Episode III's fonts have no 0x20 headers and no GS
swizzle (the XS2 reader runs on them without error but returns noise), so
``decode_block`` / ``encode_block`` are replaced by a planar split, and the
file also carries a 512-pair metric table and an 8x8 system font;
* the ADDRESSING is a fresh port from SLUS_213.89 (below), with Episode III's
pair gate, the 0x1000 fixed-width flag, two extra-kanji lists and the
``right - left + 3`` / ``right + 2`` advance;
* the Measurer follows Episode III's width function (``$xx7``, ``$zoom``,
control bytes 0x12/0x15/0x18/0x19, half-size mode) instead of XS2's;
* kept unchanged from XS2: the stdlib PNG reader/writer (``sheet_to_png``,
``png_to_gray``, ``quantize``), the sheet convention (4 sheets of 640x768,
a 32x32 grid of 20x24 cells, 4 grey levels), the metrics CSV shape and the
font-rebuild refusals;
* Episode I's addressing (fenced in the XS2 module) is not carried over, and
neither is XS2's GS swizzle reader: the round-1 ``font-jp-kana`` helper that
used an Episode II Japan font as a kana donor is gone. A Japanese donor
must be the Episode III Japan disc (its font0 kanji are re-anti-aliased
and its half-size kana block 768-959 is new), so ``font-donor`` copies cells
and metrics between two Episode III fonts.
Regions (round 2). The FILE layer has no region branch: the Japanese fonts
(``mnu\\jp\\font0.bin`` / ``font1.bin`` on SLPS_256.40/41) have the same
layout. The ADDRESSING differs, and every difference is read from the
executable at the profile's VAs (``Addressing.from_executable``):
field read from us / proto jp
gate pair gate FUN_00181e48 (4 words at its VA) whitelist lead >= 0xA0 (EUC)
prop_cells the two prop-gate immediates 0x180 (384) 0xC0 (192)
(printer slti/sltiu, measurer slti) 0x1856e4/0x182dd4 0x185584/0x182c7c
a9_row code->cell jump table entry for lead A9 own case = the AA..AC fallback
(US FUN_00184938 table 0x540080; (Latin-1 singles) (0x80-0x9F -> 0x7F)
JP 0x1847d8 table 0x53e8c0)
half-size FUN_00181db8, checked by sha1 of its bytes same VA, identical code
So on Japan: every byte from 0xA0 up starts a two-byte code (trail not
tested), a lone 0x80-0x9F draws the fallback cell 0x7F (the single-byte path
goes through lead A9, which has no row), kana (cells 192-383) are never
proportional (advance 19), and the proportional tier is cells 0-191. The
half-size path (control 0x18) measures ``half_cell(cell)`` with the metric
pair of that cell and draws cell + 0x240: on Japan cells 768-959 hold the
half-size kana whose ink the metric pairs 192-383 describe (checked: 192/192
on font0), on USA they hold the proportional cp1252 images.
File layout (0x78C00 = 494,592 bytes, both files; Disc 1, Disc 2 and the
May 2006 prototype carry identical copies, and so do JP Disc 1 and Disc 2)::
0x00000 1,024 cells x 480 bytes: 20x24 PSMT8, row-major, linear.
Each byte packs four 2-bit planes: plane k = (byte >> 2k) & 3.
Glyph cell n lives in byte cell (n & 0x3FF), plane (n >> 10),
so the file holds 4 x 1,024 = 4,096 glyph cells.
0x78000 512 (left, right) byte pairs, indexed by base cell
0x78400 0x800 bytes: 1bpp 512x32 system font (8x8 glyphs, MSB first)
Sheet k (640x768) = plane k laid out as a 32x32 grid, so sheet k holds cells
1024k .. 1024k+1023, the same numbering as XS1/XS2 sheets.
How the engine draws (SLUS_213.89; the May 2006 prototype's code is the same
at the same function addresses, with its data shifted - see ``PROFILES``):
* ``FUN_00184188`` uploads one cell (``font + (cell & 0x3FF) * 0x1E0``) as a
PSMT8 20x24 image (GIF packet at VA 0x4B3250) and sets TEX0 CBP =
0x3FC0 + ((cell & 0xC00) >> 8): one CLUT per plane.
* The four CLUTs are uploaded from VA 0x4B1E90 (GIF packet at 0x4B1E40:
BITBLTBUF DBP 0x3FC0, 32x32 PSMCT32). Checked here (``clut_check``): CLUT k
maps index i to white with alpha (0, 0x2A, 0x55, 0x80)[(i >> 2k) & 3] for all
256 entries of all four CLUTs (CSM1 order). So the 2-bit value is a linear
coverage level, and the PNG grey levels 0/85/170/255 are exact.
* ``FUN_00181fa0`` expands the 8x8 font (nibble -> 4 bytes through the table
at VA 0x4B3058, high nibble first, bit 3 = leftmost pixel) into a 512x32
PSMT8H texture.
Addressing (``Addressing``, all tables read from the executable by VA):
* Code -> cell: ``xs3_cell`` = ``FUN_00184938``. Rows A1-AD by per-row rules
(jump table at VA 0x540080), kanji rows B0-CF = lead*94 + trail - 0x3D41
(B0A1 = cell 1024), lead D0 and up looked up by ``FUN_00181d40`` in an
extra-kanji list (font0: VA 0x4B3020, font1: VA 0x4B2F50; chosen by the
byte at 0x7E7E06), cell 0xF95 + index; anything else falls back to 0x7F.
Codes A1B9, A1BC, A1F9-A1FE and the A2A0-A2AF group carry bit 0x1000: the
proportional gate tests cell < 0x180 (Japan: 0xC0), so they are always fixed width. The
draw call ignores bit 12 (``cell_index`` strips it).
* Pair gate: ``pair_gate`` = ``FUN_00181e48``. Lead A4 or A6 with any non-zero
trail; A1 with BD DA DB DF EE F9 FA FB FC; A2 with A2-A6, AA-AD and F6; A3
with B0-B9; AD with B5-B7 (whole function read, 0x181E48-0x181F94). Any other byte from 0x80 up is ONE character: lead A9, trail
byte+0x80, so cell = byte + 0x80 (0xE9 'e acute' = cell 361). Japan: see
"Regions" above (``pair_gate(..., gate="euc")``).
* ``$han1;``: ASCII 0x20-0x7F -> EUC code from the u16 table at VA 0x4B2E50
(``FUN_00181d10``, table base + 2*byte). Without ``$han`` an ASCII byte is
not a cell: it is drawn from the 8x8 font and is ``$zoom`` pixels wide.
* Width of one glyph: ``FUN_00185770`` reads u16 ``font+0x78000+2*cell``:
``right - left + 3`` when left != 0, ``right + 2`` when left == 0, ``$xx1 + 1``
for cell 0, and ``2 * (xx3 >> 1)`` (10 when that is 0) while ``$xx3`` is
non-zero. The image of a proportional glyph is cell + 0x240 (576).
* Control bytes 0x01-0x1F: operand lengths from the table at VA 0x4B3150
(``FUN_00182290``); 0x08 and 0x15 are variable (0x08: a flag byte whose set
bits add the bytes at VA 0x53FD40 = 2,2,3,2,2; 0x15: a length byte L and L
more bytes).
* ``$``-commands: table at VA 0x4B31B0 (name, handler) pairs, 18 entries;
``FUN_00184090`` takes the FIRST name that is a prefix of the text after '$'.
Usage (wired into the kit CLI through ``add_commands``)::
font-extract --iso DISC.iso --out DIR # sheets, metrics, sys8x8, code table
font-rebuild --ref font0.bin --sheets DIR [--metrics CSV] --out new.bin
font-measure --iso DISC.iso --text '$prop1;$han1;Hello'
font-donor --from JP.iso --to US.iso --cells 192-255 --out DIR # cells + metrics
# (cells the --to disc's retail text draws are refused: on USA
# 256-383 are cp1252 0x80-0xFF, e.g. 361 é, 374 ö, 302 ®)
python font.py --self-test
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import os
import struct
import sys
import zlib
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, NamedTuple, Optional, Sequence, Tuple
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
FILE_SIZE = 0x78C00
CELL_BYTES = 480
CELL_W, CELL_H = 20, 24
SHEET_W, SHEET_H = 640, 768
CELLS_PER_ROW = 32
CELLS_PER_SHEET = 1024
SHEETS = 4
CELL_COUNT = CELLS_PER_SHEET * SHEETS # 4096
METRICS_OFF = 0x78000
METRIC_PAIRS = 512
SYS_OFF = 0x78400
SYS_SIZE = 0x800
SYS_W, SYS_H = 512, 32
FALLBACK_CELL = 0x7F
FIXED_FLAG = 0x1000
EXTRA_KANJI_BASE = 0xF95 # 3989, FUN_00181d40
PROP_LIMIT = 0x180 # proportional if cell < 0x180 (slti 0x180)
PROP_CELL_SHIFT = 0x240 # 576: image of a proportional glyph
FIXED_ADVANCE = 0x13 # 19
CLUT_ALPHA = (0x00, 0x2A, 0x55, 0x80)
GREY = (0, 85, 170, 255)
FONT_PATHS = ("\\mnu\\us\\font0.bin", "\\mnu\\us\\font1.bin") # the USA pair; see font_paths
JP_PROP_CELLS = 0xC0 # 192: the Japanese prop-gate immediate
def font_paths(lang: str = "us") -> Tuple[str, str]:
"""``mnu\\<lang>\\font0.bin`` and ``font1.bin`` (the engine's ``mnu\\xx\\`` template)."""
return (f"\\mnu\\{lang}\\font0.bin", f"\\mnu\\{lang}\\font1.bin")
class FontError(ValueError):
pass
# --- build profiles: where the tables live in each executable ---------------
#
# Not to be confused with regions.py (the LBA-source -> X3.* container mapper).
# Keyed by SHA-1 of the boot executable. US Disc 1 SLUS_213.89 and Disc 2
# SLUS_214.17 are the same file. The prototype's VAs were found by searching
# its executable for the retail tables' bytes (each found exactly once) and
# checked against its code: the font functions are at the retail addresses and
# differ only in the lui/addiu/lw immediates that point at these tables.
@dataclass(frozen=True)
class Profile:
name: str
han_va: int
extra_va: Tuple[int, int] # font0, font1
ctl_va: int
ctl08_va: int
cmd_va: int
clut_va: int
font_dir: str = "us"
# code addresses (round 2): the region rules are read from these. None
# (synthetic test profiles only) = the USA rules, unread.
gate_va: Optional[int] = None # pair gate (FUN_00181e48 in every build)
prop_imm_va: Tuple[int, ...] = () # prop gate: printer, measurer (slti/sltiu v0, rX, imm)
cell_fn_va: Optional[int] = None # code -> cell function
jump_va: Optional[int] = None # its 13-entry jump table (leads A1..AD)
half_va: Optional[int] = None # half-size map (FUN_00181db8 in every build)
PROFILES: Dict[str, Profile] = {
"def4d42429001ca86111c6fa86dc84bdeb9a93c4": Profile(
"us", han_va=0x4B2E50, extra_va=(0x4B3020, 0x4B2F50), ctl_va=0x4B3150,
ctl08_va=0x53FD40, cmd_va=0x4B31B0, clut_va=0x4B1E90,
gate_va=0x181E48, prop_imm_va=(0x1856E4, 0x182DD4), cell_fn_va=0x184938, jump_va=0x540080,
half_va=0x181DB8),
# the prototype's code is at the retail addresses; its data is shifted
"e6c40f2f512586498a2d266cb45377f07ea1e62f": Profile(
"proto-2006-05", han_va=0x4B2C10, extra_va=(0x4B2DE0, 0x4B2D10), ctl_va=0x4B2F10,
ctl08_va=0x53FAE0, cmd_va=0x4B2F70, clut_va=0x4B1C50,
gate_va=0x181E48, prop_imm_va=(0x1856E4, 0x182DD4), cell_fn_va=0x184938, jump_va=0x53FE20,
half_va=0x181DB8),
# SLPS_256.40 / SLPS_256.41 (one executable, sha256 b82b6744...). VAs from the
# JP synthesis brief (S1, section 1); ctl08 (0x53E580) and CLUT (0x4B05E0) found
# here by searching for the retail tables' bytes (one hit each, CLUT 4,096/4,096
# bytes equal); the jump table VA is the one the cell function's lui/addiu loads.
"e8125f743e0e7fda0ec392ea845dd0069470af3b": Profile(
"jp", han_va=0x4B15A0, extra_va=(0x4B1770, 0x4B16A0), ctl_va=0x4B18A0,
ctl08_va=0x53E580, cmd_va=0x4B1900, clut_va=0x4B05E0, font_dir="jp",
gate_va=0x181E48, prop_imm_va=(0x185584, 0x182C7C), cell_fn_va=0x1847D8, jump_va=0x53E8C0,
half_va=0x181DB8),
}
# the pair gate's first four words: the Japanese gate IS these four words
# (andi v0,a0,0xff; sltiu v0,v0,0xa0; jr ra; sltiu v0,v0,1 = "lead >= 0xA0");
# the USA whitelist gate starts andi a1,a1,0xff; andi a0,a0,0xff; beq a1,zero; ...
GATE_EUC_WORDS = bytes.fromhex("ff008230a000422c0800e0030100422c")
GATE_US_HEAD = bytes.fromhex("ff00a530ff0084305000a0102d100000")
# FUN_00181db8, the half-size map: these 0x90 bytes in us / proto / jp alike
HALF_FN_CODE = bytes.fromhex(
"40ff8324c000632c1f0060142d108000ff0f85301b0002241900a210000000001c00a228"
"080040503c0002241600a0102d100000050003241300a3107e0102240800e0037f010224"
"0d00a210000000003c00a2280c0040147f0102248d00a228090040107f0102248000a228"
"060040547f0102240800e00393008224000000000800e0037d0102240800e00300000000")
# the code words glyphs.py's optional unlocks rewrite in the USA / prototype
# executable: (VA, retail bytes, patched bytes). An executable that differs
# from a known one only at these sites gets that build's profile, and its rules
# are then read from the patched code (gate euc / prop cells 0xC0).
UNLOCK_SITES = (
(0x181E48, GATE_US_HEAD, GATE_EUC_WORDS), # pair gate -> JP's 4 words
(0x1856E4, struct.pack("<I", 0x2E220180), struct.pack("<I", 0x2E2200C0)), # printer prop gate
(0x182DD4, struct.pack("<I", 0x28820180), struct.pack("<I", 0x288200C0)), # measurer prop gate
)
def unpatched(exe: bytes) -> bytes:
"""``exe`` with every unlock site that holds its patched bytes put back."""
out = bytearray(exe)
for va, old, new in UNLOCK_SITES:
try:
o = va_to_offset(exe, va, len(new))
except FontError:
continue
if out[o:o + len(new)] == new:
out[o:o + len(new)] = old
return bytes(out)
def profile_for(exe: bytes) -> Profile:
h = hashlib.sha1(exe).hexdigest()
p = PROFILES.get(h)
if p is None and exe[:4] == b"\x7fELF":
p = PROFILES.get(hashlib.sha1(unpatched(exe)).hexdigest())
if p is None:
raise FontError(f"unknown executable (sha1 {h}): no font table addresses are known for it")
return p
def va_to_offset(exe: bytes, va: int, n: int = 1) -> int:
"""File offset of ``va`` through the ELF's PT_LOAD headers (US: data VA =
file offset + 0x11F000; read from the headers, not assumed)."""
if exe[:4] != b"\x7fELF":
raise FontError("not an ELF file")
phoff, = struct.unpack_from("<I", exe, 0x1C)
phnum, = struct.unpack_from("<H", exe, 0x2C)
for k in range(phnum):
typ, off, vaddr, _pa, filesz = struct.unpack_from("<5I", exe, phoff + 32 * k)
if typ == 1 and vaddr <= va and va + n <= vaddr + filesz:
return off + va - vaddr
raise FontError(f"VA {va:#x} is not in a loaded segment's file data")
def read_va(exe: bytes, va: int, n: int) -> bytes:
o = va_to_offset(exe, va, n)
return bytes(exe[o:o + n])
def _lui_refs(exe: bytes, fn_va: int, words: int = 64) -> List[int]:
"""Addresses built by ``lui rX, hi`` + ``addiu/lw ..., lo(rX)`` in the first
``words`` instructions of a function (a masked-signature check that a data VA
belongs to that code)."""
ws = struct.unpack(f"<{words}I", read_va(exe, fn_va, 4 * words))
hi, out = {}, []
for w in ws:
op, rs, rt, imm = w >> 26, (w >> 21) & 31, (w >> 16) & 31, w & 0xFFFF
if op == 0x0F:
hi[rt] = imm << 16
elif op in (0x09, 0x23) and rs in hi:
out.append((hi[rs] + (imm - 0x10000 if imm & 0x8000 else imm)) & 0xFFFFFFFF)
return out
# --- addressing ----------------------------------------------------------------
def pair_gate(lead: int, trail: int, gate: str = "whitelist") -> bool:
"""``FUN_00181e48``: does the print/width code read (lead, trail) as one code?
``gate`` "whitelist" = the USA/prototype function, "euc" = the Japanese
four-word function (lead >= 0xA0, trail not tested)."""
lead &= 0xFF
trail &= 0xFF
if gate == "euc":
return lead >= 0xA0
if trail == 0:
return False
if lead in (0xA4, 0xA6):
return True
if lead == 0xA1:
return trail in (0xBD, 0xDA, 0xDB, 0xDF, 0xEE, 0xF9, 0xFA, 0xFB, 0xFC)
if lead == 0xA2:
return ((trail + 0x5E) & 0xFF) < 5 or trail in (0xAA, 0xAB, 0xAC, 0xAD, 0xF6)
if lead == 0xA3:
return 0xB0 <= trail <= 0xB9
if lead == 0xAD:
return 0xB5 <= trail <= 0xB7
return False
def xs3_cell(lead: int, trail: int, extra: Sequence[Tuple[int, int]] = (), a9_row: bool = True) -> int:
"""``FUN_00184938`` (JP: 0x1847d8): the cell of a two-byte code, with bit
0x1000 for the codes that are always fixed width. ``extra`` is the active
extra-kanji list. ``a9_row`` False = the Japanese jump table, whose A9 entry
is the AA..AC fallback (every other row is the same code in both builds)."""
lead &= 0xFF
trail &= 0xFF
if lead < 0xB0:
if lead == 0xA1:
c = (trail - 0xA1) & 0xFFFF
if trail in (0xB9, 0xBC) or trail >= 0xF9:
c |= FIXED_FLAG
return c
if lead == 0xA2:
base = {0xA0: 0x105D, 0xE0: 0x6C, 0xF0: 0x75}.get(trail & 0xF0)
return FALLBACK_CELL if base is None else (trail & 0x0F) + base
if lead == 0xA3:
h = trail & 0xE0
if h == 0xA0:
return (trail & 0x0F) + 0x80
if h == 0xC0:
return (trail & 0x1F) + 0x89
if h == 0xE0:
return (trail & 0x1F) + 0xA3
return FALLBACK_CELL
if lead == 0xA4:
return trail + 0x1F
if lead == 0xA5:
return trail + 0x7F
if lead == 0xA6:
return (trail & 0x1F) + (0x17F if trail < 0xC0 else 0x197)
if lead == 0xA7:
return trail + (0x10F if trail < 0xD0 else 0x100)
if lead == 0xA8:
return trail + 0x15F
if lead == 0xA9:
return trail + 0x100 if a9_row else FALLBACK_CELL
if lead == 0xAD:
return trail + 0x17F
return FALLBACK_CELL
if lead < 0xD0:
return (lead * 94 + trail - 0x3D41) & 0xFFFF
for i, pair in enumerate(extra):
if tuple(pair) == (lead, trail):
return EXTRA_KANJI_BASE + i
return FALLBACK_CELL
def half_cell(cell: int) -> int:
"""``FUN_00181db8``: the cell measured in half-size mode (control byte 0x18)."""
if 0xC0 <= cell < 0x180:
return cell
a = cell & 0xFFF
if a == 0x1B or a == 0x3C:
return 0x17D
if a < 0x1C:
return 0 if a == 0 else (0x17E if a == 5 else 0x17F)
if a < 0x3C or a >= 0x8D or a < 0x80:
return 0x17F
return cell + 0x93
def cell_index(cell: int) -> int:
"""The glyph cell the draw call uses (bit 0x1000 is not part of it)."""
return cell & 0xFFF
# the built-in fallback names, used only by synthetic tests; real names are read
CMD_NAMES = ("ax", "ay", "az", "rx", "ry", "init", "save", "load", "col", "bg", "shadow",
"alpha", "zoom", "xx", "ruby", "prop", "han", "mark")
class Glyph(NamedTuple):
length: int # bytes of text consumed
kind: str # "cell" or "8x8"
code: int # EUC code looked up (0 for "8x8")
cell: Optional[int] # with bit 0x1000 when fixed width
class Token(NamedTuple):
kind: str # "cmd", "ctrl", "char", "8x8"
start: int
end: int
name: str = "" # cmd name
args: Tuple[str, ...] = () # cmd arguments (text between name and ';', split at ',')
cell: Optional[int] = None
@dataclass(frozen=True)
class Addressing:
"""Byte -> cell -> metric pair, with every table read from the executable."""
profile: str
han: Tuple[int, ...] # EUC codes of bytes 0x20..0x7F
extra: Tuple[Tuple[Tuple[int, int], ...], Tuple[Tuple[int, int], ...]]
ctl: Tuple[int, ...] # 32 operand lengths, 0xFF = variable
ctl08: Tuple[int, ...] # 8 byte counts per flag bit
commands: Tuple[str, ...] = CMD_NAMES
clut: Tuple[int, ...] = () # 1024 RGBA words as uploaded
gate: str = "whitelist" # "whitelist" (us/proto) or "euc" (jp)
prop_cells: int = PROP_LIMIT # proportional iff cell < prop_cells
a9_row: bool = True # single bytes 0x80+ -> lead A9 row
font_dir: str = "us"
@property
def latin1_singles(self) -> bool:
"""A lone byte 0x80+ draws its own cell (byte + 0x80). Japan: cell 0x7F."""
return self.a9_row
@staticmethod
def read_rules(exe: bytes, prof: Profile) -> Dict[str, object]:
"""gate / prop_cells / a9_row read from the code at the profile's VAs, each
checked against the instruction shape it must have (else FontError)."""
if prof.gate_va is None:
return {}
head = read_va(exe, prof.gate_va, 16)
if head == GATE_EUC_WORDS:
gate = "euc"
elif head == GATE_US_HEAD:
gate = "whitelist"
else:
raise FontError(f"the pair gate at {prof.gate_va:#x} is neither the USA whitelist nor the "
f"Japanese lead >= 0xA0 function ({head.hex()}): wrong profile or a patched gate "
f"of another shape")
imms = []
for va in prof.prop_imm_va:
w, = struct.unpack("<I", read_va(exe, va, 4))
if (w >> 26) not in (0x0A, 0x0B) or (w >> 16) & 0x1F != 2:
raise FontError(f"no slti/sltiu v0 at the prop gate {va:#x} ({w:08x})")
imms.append(w & 0xFFFF)
if not imms or len(set(imms)) != 1:
raise FontError(f"the printer and measurer prop gates disagree: {[hex(x) for x in imms]}")
jt = struct.unpack("<13I", read_va(exe, prof.jump_va, 52))
if not (jt[9] == jt[10] == jt[11]) or len(_lui_refs(exe, prof.cell_fn_va)) == 0 \
or prof.jump_va not in _lui_refs(exe, prof.cell_fn_va):
raise FontError(f"the code->cell jump table at {prof.jump_va:#x} is not the one the function at "
f"{prof.cell_fn_va:#x} loads, or its AA..AC entries are not one fallback")
if read_va(exe, prof.half_va, len(HALF_FN_CODE)) != HALF_FN_CODE:
raise FontError(f"the half-size map at {prof.half_va:#x} is not FUN_00181db8's code")
return {"gate": gate, "prop_cells": imms[0], "a9_row": jt[8] != jt[9]}
@classmethod
def from_executable(cls, exe: bytes, profile: Optional[Profile] = None) -> "Addressing":
prof = profile or profile_for(exe)
rules = cls.read_rules(exe, prof)
try:
han = struct.unpack("<96H", read_va(exe, prof.han_va + 0x40, 0xC0))
lists = []
for va in prof.extra_va:
lst = []
while True:
a, b = read_va(exe, va + 2 * len(lst), 2)
if a == 0:
break
lst.append((a, b))
if len(lst) > CELL_COUNT - EXTRA_KANJI_BASE:
raise FontError("the extra-kanji list does not end: wrong profile?")
lists.append(tuple(lst))
ctl = tuple(read_va(exe, prof.ctl_va, 32))
ctl08 = tuple(read_va(exe, prof.ctl08_va, 8))
names = []
for k in range(64):
p, _h = struct.unpack("<II", read_va(exe, prof.cmd_va + 8 * k, 8))
if p == 0:
break
o = va_to_offset(exe, p, 1)
names.append(bytes(exe[o:o + 16]).split(b"\0")[0].decode("ascii"))
clut = struct.unpack("<1024I", read_va(exe, prof.clut_va, 4096)) if prof.clut_va else ()
except struct.error as e:
raise FontError(f"cannot read the font tables: {e}")
if han[0] != 0xA1A1 or han[ord("A") - 0x20] != 0xA3C1:
raise FontError("the $han table is not at the profile's address: wrong executable?")
if any(a < 0xD0 for lst in lists for a, _ in lst):
raise FontError("an extra-kanji list holds a lead byte below 0xD0: wrong executable?")
if ctl[0x08] != 0xFF or ctl[0x15] != 0xFF:
raise FontError("the control-length table is not at the profile's address")
if not names or any(not n.isalpha() for n in names):
raise FontError("the $-command table is not at the profile's address")
return cls(prof.name, tuple(han), (lists[0], lists[1]), ctl, ctl08, tuple(names), tuple(clut),
font_dir=prof.font_dir, **rules)
@classmethod
def from_iso(cls, iso_path) -> "Addressing":
return cls.from_executable(read_boot_exe(iso_path))
# -- code -> cell
def pair(self, lead: int, trail: int) -> bool:
return pair_gate(lead, trail, self.gate)
def cell(self, lead: int, trail: int, font: int = 0) -> int:
return xs3_cell(lead, trail, self.extra[1 if font else 0], self.a9_row)
def han_code(self, b: int) -> int:
"""``FUN_00181d10``: EUC code of an ASCII byte under ``$han1;``."""
return 0xA1A1 if b < 0x20 or b >= 0x80 else self.han[b - 0x20]
def glyph(self, text: bytes, i: int = 0, han: bool = True, font: int = 0) -> Glyph:
"""The character at ``text[i]`` as the width/print code reads it.
Control bytes and '$' codes are the caller's business."""
b = text[i]
if b < 0x20:
raise FontError(f"control byte {b:#04x}: not a character")
if b < 0x80:
if not han:
return Glyph(1, "8x8", 0, None)
code = self.han_code(b)
return Glyph(1, "cell", code, self.cell(code >> 8, code & 0xFF, font))
nxt = text[i + 1] if i + 1 < len(text) else 0
if self.pair(b, nxt):
# the euc gate does not test the trail: at the very end of the text the
# game would read the terminator as the trail; here the code stops there
return Glyph(2 if i + 1 < len(text) else 1, "cell", b << 8 | nxt, self.cell(b, nxt, font))
trail = (b + 0x80) & 0xFF
return Glyph(1, "cell", 0xA900 | trail, self.cell(0xA9, trail, font))
def control_length(self, data: bytes, i: int) -> int:
"""Total bytes of the control sequence at ``data[i]`` (< 0x20), as the
width function's main loop steps over it (``FUN_00182290`` called with
the sequence start; the ruby skip calls it one byte later - see
``Measurer``)."""
return self._ctl_len(data, i, i)
def _ctl_len(self, data: bytes, i: int, base: int) -> int:
c = data[i]
n = self.ctl[c]
if n != 0xFF:
return 1 + n
arg = data[base + 1] if base + 1 < len(data) else 0
if c == 0x08:
return 2 + sum(self.ctl08[k] for k in range(8) if arg >> k & 1)
if c == 0x15:
return 2 + arg
raise FontError(f"control byte {c:#04x}: variable length, no rule known")
def command_at(self, text: bytes, i: int) -> Tuple[str, Tuple[str, ...], int]:
"""``FUN_00184090``: the '$' command at ``text[i]``: (name, args, end).
``end`` is just past the ';'. The first table name that prefixes the
text wins, as in the game. Raises when there is no match or no ';'."""
if text[i:i + 1] != b"$":
raise FontError("not a '$' command")
rest = text[i + 1:]
for name in self.commands:
if rest.startswith(name.encode()):
e = text.find(b";", i)
if e < 0:
raise FontError(f"${name} without its ';' (the game reads on past the text)")
body = text[i + 1 + len(name):e].decode("latin-1")
return name, tuple(body.split(",")) if body else (), e + 1
raise FontError(f"unknown $-command at byte {i}: {text[i:i + 8]!r}")
def tokens(self, text: bytes, han: bool = False, font: int = 0) -> List[Token]:
"""Split a string into $-commands, control sequences and characters.
``han`` is the starting ``$han`` state; ``$han`` and control byte 0x19
update it as the game does."""
out, i, n = [], 0, len(text)
flags = 2 if han else 0
while i < n and text[i] != 0:
b = text[i]
if b == 0x24:
name, args, e = self.command_at(text, i)
if name == "han":
flags = (flags & ~2) | ((text[i + 4] & 1) << 1 if i + 4 < n else 0)
out.append(Token("cmd", i, e, name, args))
i = e
elif b < 0x20:
L = self.control_length(text, i)
if b == 0x19 and i + 1 < n:
flags = text[i + 1]
out.append(Token("ctrl", i, i + L))
i += L
else:
g = self.glyph(text, i, bool(flags & 2), font)
out.append(Token("char" if g.kind == "cell" else "8x8", i, i + g.length, cell=g.cell))
i += g.length
return out
# -- cell -> what is drawn
def is_prop(self, cell: int, prop: bool = True) -> bool:
return prop and 0 <= cell < self.prop_cells
def drawn_cell(self, cell: int, prop: bool = True) -> int:
"""The cell whose image is drawn: cell + 0x240 for a proportional glyph."""
return cell + PROP_CELL_SHIFT if self.is_prop(cell, prop) else cell_index(cell)
@staticmethod
def glyph_width(cell: int, metrics: Sequence[Tuple[int, int]], xx1: int = 4, xx3: int = 0) -> int:
"""``FUN_00185770``: pixels for one proportional glyph (zoom 16, no ``$xx7``)."""
if xx3:
a = (xx3 & 0xFF) >> 1
return 2 * (a or 5)
if cell == 0:
return (xx1 & 0xFF) + 1
left, right = metrics[cell]
return right - left + 3 if left else right + 2
def advance(self, cell: int, metrics, prop: bool = True, xx1: int = 4) -> int:
"""Advance at zoom 16: proportional width, or 19 when fixed."""
return self.glyph_width(cell, metrics, xx1) if self.is_prop(cell, prop) else FIXED_ADVANCE
def measurer(self, metrics, prop: bool = False, han: bool = False, xx1: int = 4,
font: int = 0) -> "Measurer":
return Measurer(self, metrics, prop=prop, han=han, xx1=xx1, font=font)
def table(self, metrics: Sequence[Tuple[int, int]] = (), prop: bool = True, font: int = 0) -> List[dict]:
"""code -> cell rows: single bytes 0x20-0xFF (with ``$han1;``; on Japan up
to 0x9F, which all draw 0x7F) and every two-byte code the gate accepts
(trails A1-FE)."""
rows = []
def row(src, length, code, cell):
ci = cell_index(cell)
r = {"bytes": src, "length": length, "code": f"{code:04X}", "cell": ci,
"fixed_flag": int(bool(cell & FIXED_FLAG)), "sheet": ci >> 10,
"prop": int(self.is_prop(cell, prop)), "drawn_cell": self.drawn_cell(cell, prop),
"left": "", "right": "", "advance": FIXED_ADVANCE}
if self.is_prop(cell, prop) and cell < len(metrics):
r.update(left=metrics[cell][0], right=metrics[cell][1],
advance="$xx1+1" if cell == 0 else self.glyph_width(cell, metrics))
elif self.is_prop(cell, prop):
r["advance"] = ""
rows.append(r)
for b in range(0x20, 0x100):
if self.gate == "euc" and b >= 0xA0:
continue # euc gate: every byte from 0xA0 up is a lead
g = self.glyph(bytes((b, 0)), 0, True, font)
row(f"{b:02X}", 1, g.code, g.cell)
for lead in range(0xA1, 0xFF):
for trail in range(0xA1, 0xFF):
if self.pair(lead, trail):
row(f"{lead:02X}{trail:02X}", 2, lead << 8 | trail, self.cell(lead, trail, font))
return rows
def clut_check(self) -> Tuple[int, int]:
"""(entries matching, 1024): CLUT k index i = white, alpha level of plane k."""
if len(self.clut) != 1024:
return 0, 1024
ok = 0
for k in range(4):
ox, oy = (k & 1) * 16, (k >> 1) * 16
for i in range(256):
ii = (i & 0xE7) | ((i & 8) << 1) | ((i & 16) >> 1) # CSM1 order
v = self.clut[(oy + ii // 16) * 32 + ox + ii % 16]
lvl = (i >> (2 * k)) & 3
ok += (v >> 24) == CLUT_ALPHA[lvl] and (lvl == 0 or v & 0xFFFFFF == 0xFFFFFF)
return ok, 1024
def _number(s: bytes, i: int) -> int:
"""``FUN_00183260``: optional sign, then decimal or 0x hex; 0 when absent."""
sign = 1
if i < len(s) and s[i] in b"+-":
sign = -1 if s[i] == 0x2D else 1
i += 1
if s[i:i + 2] == b"0x":
j = i + 2
while j < len(s) and chr(s[j]) in "0123456789abcdefABCDEF":
j += 1
return sign * int(s[i + 2:j] or b"0", 16)
j = i
while j < len(s) and 0x30 <= s[j] <= 0x39:
j += 1
return sign * int(s[i:j] or b"0")
def _s8(v: int) -> int:
v &= 0xFF
return v - 256 if v >= 128 else v
class Measurer:
"""The pixel width of a string, as ``FUN_001828a0`` computes it.
State the game keeps in globals (and that therefore carries from one call to
the next here too): ``$prop`` / ``$han`` (flag bits 0 and 1 at 0x7E7E11,
also set wholesale by control byte 0x19), ``$xx1,N`` (default width of cell
0), ``$xx3,N`` (fixed-pitch mode), ``$xx7,N`` (signed extra spacing added to
every character). Per call: ``$zoom`` (default 16; control byte 0x12 sets it
too) and half-size mode (control byte 0x18).
Per character: ASCII without ``$han`` = zoom px. Otherwise the cell's width
(``Addressing.glyph_width``) when ``$prop`` is on and the cell is below
``prop_cells`` (0x180 USA, 0xC0 Japan), else 19; in half-size mode the cell goes through ``half_cell`` and
is always measured proportionally. Then ``w += ((width + xx7) * zoom) >> 4``.
``$rubys; ... $rubye;`` is skipped (control bytes inside it are stepped over
with the ruby skip's one-byte-late operand read, as the game does). A '$'
code that is not one of these has no width. Control bytes have no width.
"""
def __init__(self, a: Addressing, metrics: Sequence[Tuple[int, int]], prop: bool = False,
han: bool = False, xx1: int = 4, xx3: int = 0, xx7: int = 0, font: int = 0):
self.a, self.metrics, self.font = a, metrics, font
self.flags = (1 if prop else 0) | (2 if han else 0)
self.xx1, self.xx3, self.xx7 = xx1 & 0xFF, xx3 & 0xFF, _s8(xx7)
@property
def prop(self) -> bool:
return bool(self.flags & 1)
@property
def han(self) -> bool:
return bool(self.flags & 2)
def width(self, s: bytes, stop_at_space: bool = False) -> int:
w, zoom, half = 0, 16, 0
i, n = 0, len(s)
a = self.a
while i < n and s[i] != 0:
c = s[i]
if c == 0x24: # '$'
t = s[i + 1:i + 8]
if t.startswith(b"prop") and i + 5 < n:
self.flags = (self.flags & ~1) | (s[i + 5] & 1)
elif t.startswith(b"han") and i + 4 < n:
self.flags = (self.flags & ~2) | ((s[i + 4] & 1) << 1)
elif t.startswith(b"xx1,"):
self.xx1 = _number(s, i + 5) & 0xFF
elif t.startswith(b"xx3,"):
self.xx3 = _number(s, i + 5) & 0xFF
elif t.startswith(b"xx7,"):
self.xx7 = _s8(_number(s, i + 5))
elif t.startswith(b"rubys;"):
j = i + 7
while j < n and s[j] != 0:
if s[j:j + 7] == b"$rubye;":
i = j
break
j += a._ctl_len(s, j, j + 1) if s[j] < 0x20 else 1
elif t.startswith(b"zoom"):
zoom = _number(s, i + 5)
e = s.find(b";", i)
if e < 0:
raise FontError("a '$' code without its ';' (the game would read on past the text)")
i = e + 1
elif c < 0x20:
if c == 0x15 and i + 3 < n:
if s[i + 2] == 2:
self.xx1 = s[i + 3]
elif s[i + 2] == 4:
self.xx3 = s[i + 3]
elif c == 0x12 and i + 1 < n:
zoom = _s8(s[i + 1])
elif c == 0x18 and i + 1 < n:
half = _s8(s[i + 1])
elif c == 0x19 and i + 1 < n:
self.flags = s[i + 1]
i += a.control_length(s, i)
else:
if c < 0x80 and not self.han:
w += (zoom * 16) >> 4
i += 1
else:
g = a.glyph(s, i, True, self.font)
i += g.length
cell = g.cell
if half:
adv = a.glyph_width(half_cell(cell), self.metrics, self.xx1, self.xx3)
elif self.prop and cell < a.prop_cells:
adv = a.glyph_width(cell, self.metrics, self.xx1, self.xx3)
else:
adv = FIXED_ADVANCE
w += ((adv + self.xx7) * zoom) >> 4
if stop_at_space and i < n and s[i] == 0x20:
break
return w
# --- the file --------------------------------------------------------------
def _planes_to_sheets(raw: bytes) -> List[bytearray]:
d = np.frombuffer(raw, np.uint8, METRICS_OFF).reshape(CELLS_PER_SHEET, CELL_H, CELL_W)
out = []
for k in range(SHEETS):
p = (d >> (2 * k)) & 3
out.append(bytearray(p.reshape(32, 32, CELL_H, CELL_W).transpose(0, 2, 1, 3).tobytes()))
return out
def _sheets_to_planes(sheets: Sequence[Sequence[int]]) -> bytes:
acc = np.zeros((CELLS_PER_SHEET, CELL_H, CELL_W), np.uint8)
for k, sh in enumerate(sheets):
a = np.frombuffer(bytes(sh), np.uint8).reshape(32, CELL_H, 32, CELL_W).transpose(0, 2, 1, 3)
acc |= ((a & 3) << (2 * k)).reshape(CELLS_PER_SHEET, CELL_H, CELL_W).astype(np.uint8)
return acc.tobytes()
class Font:
def __init__(self, sheets: List[bytearray], metrics: List[Tuple[int, int]],
sys8x8: bytes = bytes(SYS_SIZE), tail: bytes = b""):
if len(sheets) != SHEETS or any(len(s) != SHEET_W * SHEET_H for s in sheets):
raise FontError("a font is four 640x768 sheets")
if len(metrics) != METRIC_PAIRS or len(sys8x8) != SYS_SIZE:
raise FontError("a font has 512 metric pairs and a 2,048-byte system font")
self.sheets = sheets # four 640*768 bytearrays, values 0..3
self.metrics = metrics # 512 (left, right), indexed by base cell
self.sys8x8 = bytes(sys8x8) # 1bpp, 512x32, MSB first
self.tail = tail # bytes past 0x78C00 (none on the discs)
@classmethod
def blank(cls) -> "Font":
return cls([bytearray(SHEET_W * SHEET_H) for _ in range(SHEETS)], [(0, 0)] * METRIC_PAIRS)
@classmethod
def from_bytes(cls, data: bytes) -> "Font":
if len(data) < FILE_SIZE:
raise FontError(f"font file is {len(data)} bytes; Episode III fonts are {FILE_SIZE}")
data = bytes(data)
m = data[METRICS_OFF:SYS_OFF]
metrics = [(m[2 * i], m[2 * i + 1]) for i in range(METRIC_PAIRS)]
return cls(_planes_to_sheets(data), metrics, data[SYS_OFF:SYS_OFF + SYS_SIZE], data[FILE_SIZE:])
@classmethod
def load(cls, path) -> "Font":
return cls.from_bytes(Path(path).read_bytes())
def to_bytes(self) -> bytes:
out = bytearray(_sheets_to_planes(self.sheets))
for left, right in self.metrics:
out += bytes((left & 0xFF, right & 0xFF))
out += self.sys8x8
out += self.tail
return bytes(out)
# cells
@staticmethod
def _xy(index: int) -> Tuple[int, int, int]:
if not 0 <= index < CELL_COUNT:
raise FontError(f"cell {index}: cells are 0..4095 (strip bit 0x1000 with cell_index)")
i = index % CELLS_PER_SHEET
return index // CELLS_PER_SHEET, (i % CELLS_PER_ROW) * CELL_W, (i // CELLS_PER_ROW) * CELL_H
def cell(self, index: int) -> List[List[int]]:
"""24 rows of 20 values (0..3)."""
s, x0, y0 = self._xy(index)
sh = self.sheets[s]
return [list(sh[(y0 + r) * SHEET_W + x0:(y0 + r) * SHEET_W + x0 + CELL_W]) for r in range(CELL_H)]
def set_cell(self, index: int, rows: Sequence[Sequence[int]]) -> None:
if len(rows) != CELL_H or any(len(r) != CELL_W for r in rows):
raise FontError("cell must be 24 rows of 20 values")
s, x0, y0 = self._xy(index)
sh = self.sheets[s]
for r in range(CELL_H):
sh[(y0 + r) * SHEET_W + x0:(y0 + r) * SHEET_W + x0 + CELL_W] = bytes(v & 3 for v in rows[r])
def ink_bounds(self, index: int) -> Optional[Tuple[int, int]]:
cols = [c for c in range(CELL_W) if any(row[c] for row in self.cell(index))]
return (cols[0], cols[-1]) if cols else None
def set_metrics(self, slot: int, left: int, right: int) -> None:
if not 0 <= slot < METRIC_PAIRS:
raise FontError(f"metric slot {slot}: the table has {METRIC_PAIRS} pairs and cannot grow")
if not (0 <= left <= 255 and 0 <= right <= 255):
raise FontError(f"metric slot {slot}: left and right are bytes")
self.metrics[slot] = (left, right)
def metrics_check(self) -> Tuple[int, int]:
"""(pairs whose ink of cell + 0x240 equals the pair, pairs with left != 0)."""
total = ok = 0
for c, (l, r) in enumerate(self.metrics):
if l and c + PROP_CELL_SHIFT < CELL_COUNT:
total += 1
ok += self.ink_bounds(c + PROP_CELL_SHIFT) == (l, r)
return ok, total
# the 8x8 system font
def sys8x8_image(self) -> bytearray:
"""512x32, one byte per pixel (0 or 1)."""
bits = np.unpackbits(np.frombuffer(self.sys8x8, np.uint8)) # MSB first
return bytearray(bits.tobytes())
def set_sys8x8_image(self, pixels: Sequence[int]) -> None:
if len(pixels) != SYS_W * SYS_H:
raise FontError("the system font image is 512x32")
self.sys8x8 = np.packbits(np.frombuffer(bytes(1 if p else 0 for p in pixels), np.uint8)).tobytes()
# --- donor: copy cells + metrics between two Episode III fonts -----------------
KANJI_CELLS = range(1024, 3989) # B0A1..CFD3: drawn identically by every build
def font_cells(f: "Font") -> np.ndarray:
"""(4096, 24, 20) view of a font's glyph cells, values 0..3."""
a = np.frombuffer(b"".join(bytes(s) for s in f.sheets), np.uint8)
return a.reshape(SHEETS, 32, CELL_H, 32, CELL_W).transpose(0, 1, 3, 2, 4).reshape(CELL_COUNT, CELL_H, CELL_W)
def kanji_agreement(a: "Font", b: "Font") -> int:
"""How many of the 2,965 kanji cells of two fonts differ by at most one
grey level per pixel. The same font of two builds scores 2,964-2,965 (the
Japanese font0 is re-anti-aliased, +-1 level); font0 against font1 scores 0."""
ca, cb = font_cells(a)[KANJI_CELLS.start:KANJI_CELLS.stop], font_cells(b)[KANJI_CELLS.start:KANJI_CELLS.stop]
d = np.abs(ca.astype(np.int16) - cb).reshape(len(KANJI_CELLS), -1).max(1)
return int((d <= 1).sum())
def parse_cells(spec: str) -> List[int]:
"""'192-383,851,3989-4088' -> sorted unique cell numbers (0..4095)."""
out = set()
for part in spec.replace(" ", "").split(","):
if not part:
continue
lo, _, hi = part.partition("-")
try:
a, b = int(lo, 0), int(hi or lo, 0)
except ValueError:
raise FontError(f"--cells: {part!r} is not N or N-M")
if not (0 <= a <= b < CELL_COUNT):
raise FontError(f"--cells: {part!r} is outside 0..{CELL_COUNT - 1}")
out.update(range(a, b + 1))
if not out:
raise FontError("--cells: no cells given")
return sorted(out)
def donate(src: "Font", dst: "Font", cells: Sequence[int], metrics: bool = True,
prop_images: bool = False, force: bool = False) -> Tuple["Font", Dict[str, object]]:
"""A copy of ``dst`` with ``cells`` (and their metric pairs, for cells below
512) taken from ``src``. ``prop_images`` also copies cell + 0x240 for every
given cell below 384 (the proportional image on USA, the half-size image on
Japan; the metric pairs 192-383 describe those images in both builds).
The two fonts must be the same font (font0 with font0): at least 2,900 of the
2,965 kanji cells must agree within one grey level, else this refuses
(``force`` skips the check)."""
agree = kanji_agreement(src, dst)
if agree < 2900 and not force:
raise FontError(f"only {agree}/{len(KANJI_CELLS)} kanji cells agree: not the same font of two builds "
f"(give font0 with font0, font1 with font1), or pass --force")
new = Font([bytearray(s) for s in dst.sheets], list(dst.metrics), dst.sys8x8, dst.tail)
todo = set(cells)
if prop_images:
todo |= {c + PROP_CELL_SHIFT for c in cells if c < PROP_LIMIT}
changed = 0
for c in sorted(todo):
rows = src.cell(c)
changed += rows != new.cell(c)
new.set_cell(c, rows)
m_changed = 0
m_slots = [c for c in cells if c < METRIC_PAIRS] if metrics else []
for c in m_slots:
m_changed += new.metrics[c] != src.metrics[c]
new.set_metrics(c, *src.metrics[c])
return new, {"kanji_agree": agree, "cells_copied": len(todo), "cells_changed": changed,
"metric_pairs_copied": len(m_slots), "metric_pairs_changed": m_changed}
# --- PNG (grayscale, stdlib only) — copied from the XS2 kit; png_to_gray now also
# reads 1/2/4-bit and 16-bit PNGs ---------------------------------------------------
def _png_chunk(tag: bytes, payload: bytes) -> bytes:
return (struct.pack(">I", len(payload)) + tag + payload
+ struct.pack(">I", zlib.crc32(tag + payload) & 0xFFFFFFFF))
def gray_png(gray: Sequence[int], width: int, height: int) -> bytes:
raw = bytearray()
g = bytes(gray)
for y in range(height):
raw.append(0)
raw += g[y * width:(y + 1) * width]
return (b"\x89PNG\r\n\x1a\n"
+ _png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0))
+ _png_chunk(b"IDAT", zlib.compress(bytes(raw), 6))
+ _png_chunk(b"IEND", b""))
def sheet_to_png(sheet: Sequence[int], width: int = SHEET_W, height: int = SHEET_H) -> bytes:
return gray_png(bytes(sheet).translate(bytes(GREY[i & 3] for i in range(256))), width, height)
def png_to_gray(data: bytes) -> Tuple[int, int, bytearray]:
"""Decode a non-interlaced PNG (gray, gray+alpha, RGB, RGBA or palette;
1/2/4/8-bit gray and palette, 8/16-bit otherwise; a 4-colour sheet saved
at 2 bits by GIMP or Pillow included) to (width, height, gray bytes).
16-bit samples are cut to their high byte. Transparency counts as
background. Chunk lengths and CRCs are checked."""