Repository navigation
Expand file tree
/
Copy pathteximport.py
More file actions
1808 lines (1651 loc) · 82.8 KB
/
Copy pathteximport.py
File metadata and controls
1808 lines (1651 loc) · 82.8 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
"""teximport.py — edited PNGs back into a copy of the disc (texture import).
Edit PNGs in a copy of the folder ``browse`` wrote and give that folder to
``texture-import``: every PNG that differs from what the disc decodes to is
written back, into a copy of the disc, by ``texenc.py``. A PNG that matches
the disc (under the alpha-0 rule: colours with alpha 0 are equal whatever RGB
they carry) is unchanged and ignored, so a sparse tree holding only the edited
PNGs works the same as the whole tree.
What it reads (paths as ``browse.py`` / ``embedded.py`` write them):
* ``textures_png/<area>/<toc path>/<file>.txy/NNN_<name>[_bBB][_dupD].png``:
entry NNN of a standalone page. The file name must be exactly what the
current kit would write for that entry (``txy.entry_filename``), and the
size must match; otherwise the tree is from another revision and nothing is
written.
* ``textures_png/_embedded/<area>/<container path>/<0xoffset>/NNN_....png``:
entry NNN of the txy block at that offset inside an effect file.
* ``xtx/<area>/<path>.xtx.png``: a UI sheet. Sheets whose palette the kit
has solved are written (parked-corner sheets, their frame masks, the
portraits and item cards cut by a mask, and the true-colour title words
``yajima\\titleobj.xtx``); sheets drawn with a guessed palette (scan, gray)
are refused when edited and ignored when not.
* ``models/<area>/<path>.glb`` (or .gltf): the images of a model exported by
``browse``/``model``, mapped back to the entries of the .txy of the same
path, by image name (the PNG-file stem, or for files exported before images
were named that way an entry name unique among the model's entries). Image
order is never used (Blender reorders images); an unmatched image, or two
images on one entry, is a problem.
The sweep. The same picture is often stored many times on the disc, under
different names (KOS-MOS's hair is ``kosmos00_hair_col`` in kosmos00.txy and
``kosmos01_hair_col`` in kosmos01, 02 and 03, each with its palette at another
place). By default every entry anywhere on the disc (standalone pages and
embedded blocks, every carrier) whose decoded picture equals an edited entry's
original picture gets the edit too, encoded in its own file's palette context.
Single-colour pictures are swept only to entries of the same name, and every
swept group is printed so mixed-name groups (one 32x32 reflection map is
stored 1,512 times under many names) are visible in a dry run. ``--sweep
name`` keeps copies to the same entry name, ``--sweep none`` edits only what
the PNGs say.
Everything is written through ``repack.patch_copy`` (a complete, read-back
copy or nothing). Before the copy takes the ``--out`` name (its ``check``
hook), every replaced object is read from it and decoded again: edited,
swept, ride-along and joint-changed entries must show their planned
pictures, every other entry its original one, and untouched blocks inside a
replaced file must be byte-identical. A failure deletes the copy. The report
CSV is written after that, and never over ``--out`` or ``--iso``.
python teximport.py --iso DISC.iso --tree EDITED --out MODDED.iso [--dry-run]
python teximport.py --iso DISC.iso --verify-roundtrip
python teximport.py --self-test
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import math
import os
import re
import struct
import sys
import time
from concurrent.futures import ProcessPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import arx # noqa: E402
import embedded # noqa: E402
import pngread # noqa: E402
import region # noqa: E402
import texenc # noqa: E402
import txy # noqa: E402
import xtx as xtxmod # noqa: E402
from chains import CHAINS, ChainReader, available_chains # noqa: E402
from iso9660 import IsoImage # noqa: E402
from toc import parse_toc # noqa: E402
CARRIER_EXTS = {"esd", "esp", "bin"} # recolor.CARRIER_EXTS: files that hold txy blocks
XTX_OK = ("corner", "mask", "corner+mask", "ct32")
ROLES = ("edited", "swept", "ride-along", "joint-changed", "mip")
class ImportError_(ValueError):
pass
# ======================================================================= disc
class Disc:
"""Every TOC object of an image, readable by (chain, path), ARX objects
decompressed (what ``repack.read_entry`` returns, without re-parsing the
TOC for every object)."""
def __init__(self, iso_path, check: bool = True):
self.path = str(iso_path)
self.iso = IsoImage(iso_path)
if check:
region.require_known(self.iso, "texture-import")
self.by_path: Dict[Tuple[int, str], tuple] = {}
self.order: List[Tuple[int, object]] = []
for chain in available_chains(self.iso):
r = ChainReader(self.iso, chain)
for e in parse_toc(bytes(r.toc_bytes()), CHAINS[chain][0]):
self.by_path[(chain, e.path.lower())] = (r, e)
self.order.append((chain, e))
def entry(self, chain: int, path: str):
hit = self.by_path.get((chain, path.lower()))
return hit[1] if hit else None
def read(self, chain: int, path: str) -> bytes:
r, e = self.by_path[(chain, path.lower())]
raw = r.read(e.byte_offset, e.size)
return arx.decompress(raw) if e.compressed else raw
def close(self):
self.iso.close()
def blocks_of(path: str, data: bytes) -> List[Tuple[int, bytes]]:
"""The txy blocks of an object, as browse and recolor find them: a .txy
file is one block (0 banks = placeholder), anything else is searched with
``embedded.iter_blocks``."""
if path.lower().endswith(".txy"):
return [(0, data)] if data[:4] == b"txy\x00" else []
return list(embedded.iter_blocks(data))
def carrier_objects(disc: Disc) -> List[Tuple[int, str]]:
return [(c, e.path) for c, e in disc.order if e.ext == "txy" or e.ext in CARRIER_EXTS]
# ======================================================================= tree
@dataclass
class Ref:
kind: str # txy, emb, xtx, glb
chain: int
path: str # TOC path (backslashes), as spelt in the tree
block_off: int
entry: int
fname: str
file: Path
def resolve_roots(tree=None, textures=None, xtx=None, models=None) -> Dict[str, Optional[Path]]:
roots: Dict[str, Optional[Path]] = {"textures": None, "xtx": None, "models": None}
if tree:
t = Path(tree)
if not t.is_dir():
raise ImportError_(f"--tree {t} is not a folder")
if (t / "chain0").is_dir() or (t / "_embedded").is_dir():
roots["textures"] = t
else:
for k, sub in (("textures", "textures_png"), ("xtx", "xtx"), ("models", "models")):
if (t / sub).is_dir():
roots[k] = t / sub
if not any(roots.values()):
raise ImportError_(f"--tree {t} holds no textures_png/, xtx/ or models/ folder "
f"(nor chain0/ or _embedded/ for a textures_png folder itself)")
for k, v in (("textures", textures), ("xtx", xtx), ("models", models)):
if v:
if not Path(v).is_dir():
raise ImportError_(f"--{k} {v} is not a folder")
roots[k] = Path(v)
return roots
_NNN = re.compile(r"^(\d{3,})_.+\.png$")
_OFF = re.compile(r"^0x[0-9a-fA-F]+$")
def _chain_of(area: str) -> Optional[int]:
m = re.fullmatch(r"chain(\d)", area)
return int(m.group(1)) if m else None
def parse_texture_path(rel: Tuple[str, ...]) -> Tuple[Optional[Ref], str]:
"""(Ref, "") or (None, problem) for a PNG path relative to textures_png."""
if not rel[-1].lower().endswith(".png"):
return None, ""
m = _NNN.match(rel[-1])
if rel[0] == "_embedded":
if len(rel) < 5:
return None, "not an _embedded/<area>/<container>/<0xoffset>/NNN_name.png path"
chain = _chain_of(rel[1])
if chain is None or not _OFF.match(rel[-2]) or not m:
return None, "not an _embedded/<area>/<container>/<0xoffset>/NNN_name.png path"
return Ref("emb", chain, "\\".join(rel[2:-2]), int(rel[-2], 16), int(m.group(1)), rel[-1], Path()), ""
if len(rel) < 3:
return None, "not a <area>/<path>/<file>.txy/NNN_name.png path"
chain = _chain_of(rel[0])
if chain is None or not rel[-2].lower().endswith(".txy") or not m:
return None, "not a <area>/<path>/<file>.txy/NNN_name.png path"
return Ref("txy", chain, "\\".join(rel[1:-1]), 0, int(m.group(1)), rel[-1], Path()), ""
def parse_xtx_path(rel: Tuple[str, ...]) -> Tuple[Optional[Ref], str]:
if not rel[-1].lower().endswith(".png"):
return None, ""
chain = _chain_of(rel[0]) if len(rel) >= 2 else None
if chain is None or not rel[-1].lower().endswith(".xtx.png"):
return None, "not a <area>/<path>.xtx.png path"
return Ref("xtx", chain, "\\".join(rel[1:])[:-4], 0, -1, rel[-1], Path()), ""
def parse_model_path(rel: Tuple[str, ...]) -> Tuple[Optional[Ref], str]:
low = rel[-1].lower()
if not (low.endswith(".glb") or low.endswith(".gltf")):
return None, ""
chain = _chain_of(rel[0]) if len(rel) >= 2 else None
if chain is None:
return None, "not a <area>/<path>.glb path"
stem = "\\".join(rel[1:]).rsplit(".", 1)[0]
return Ref("glb", chain, stem + ".txy", 0, -1, rel[-1], Path()), ""
def scan_tree(roots) -> Tuple[List[Ref], List[str]]:
refs, problems = [], []
for kind, parse in (("textures", parse_texture_path), ("xtx", parse_xtx_path), ("models", parse_model_path)):
root = roots.get(kind)
if root is None:
continue
for dirpath, dirs, files in os.walk(root):
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
for f in sorted(files):
if f.startswith("."):
continue
p = Path(dirpath) / f
rel = p.relative_to(root).parts
ref, why = parse(rel)
if ref is None:
if why:
problems.append(f"{p}: {why}")
continue
ref.file = p
refs.append(ref)
return refs, problems
# ================================================================ edit search
@dataclass
class Edit:
chain: int
path: str # TOC path as the disc spells it
block_off: int
entry: int
name: str
w: int
h: int
fmt: int
mip: int
target: bytes
orig: bytes
source: str
role: str = "edited"
twin: tuple = () # (fmt, x, y, w, h, bank, palx, paly): what the dup flag re-lists
def _twin(e: dict) -> tuple:
return (e["fmt"], e["x"], e["y"], e["w"], e["h"], e["bank"], e["palx"], e["paly"])
def _png_target(file: Path, w: int, h: int) -> Tuple[Optional[bytes], str]:
try:
pw, ph, rgba = pngread.read_png(file.read_bytes())
except (pngread.PngError, OSError) as e:
return None, f"{file}: {e}"
if (pw, ph) != (w, h):
return None, f"{file}: the PNG is {pw}x{ph}, the texture on the disc is {w}x{h}"
return rgba, ""
def _txy_job(args):
"""Phase 1 for one object: which of the tree's PNGs differ from the disc."""
chain, path, refs = args
disc = _WORKER["disc"]
out = {"edits": [], "problems": [], "unchanged": 0}
e = disc.entry(chain, path)
if e is None:
out["problems"] += [f"{r.file}: no object {path!r} in chain {chain} on this disc" for r in refs]
return out
data = disc.read(chain, e.path)
blocks = dict(blocks_of(e.path, data))
decoded: Dict[int, tuple] = {}
for r in refs:
if r.block_off not in blocks:
out["problems"].append(f"{r.file}: {e.path} has no txy block at {r.block_off:#x}")
continue
if r.block_off not in decoded:
t = txy.parse(blocks[r.block_off])
dec = {en["i"]: (en, rgba) for en, _w, _h, rgba in txy.decode_fast(blocks[r.block_off])}
decoded[r.block_off] = (t, dec)
t, dec = decoded[r.block_off]
multi = len(t["banks"]) > 1
ent = next((x for x in t["entries"] if x["i"] == r.entry), None)
if ent is None:
out["problems"].append(f"{r.file}: {e.path} has no entry {r.entry}")
continue
want = txy.entry_filename(ent, multi)
if want != r.fname:
out["problems"].append(f"{r.file}: entry {r.entry} of {e.path} would be named {want}")
continue
if r.entry not in dec:
out["problems"].append(f"{r.file}: entry {r.entry} of {e.path} is a placeholder (nothing to edit)")
continue
en, orig = dec[r.entry]
target, why = _png_target(r.file, en["w"], en["h"])
if target is None:
out["problems"].append(why)
continue
if texenc.same(np.frombuffer(target, np.uint8), np.frombuffer(orig, np.uint8)).all():
out["unchanged"] += 1
continue
bogus = en["bank"] >= len(t["banks"]) or (en["fmt"] in (txy.PSMT8, txy.PSMT4) and en["cbp"] == 0xFFFFFFFF)
if bogus:
out["problems"].append(f"{r.file}: entry {r.entry} ({en['name']}) of {e.path} is refused: its bank or "
f"CLUT pointer is 0xFFFFFFFF (FORMATS.md, the bogus E2_ELS01 entries)")
continue
out["edits"].append(Edit(chain, e.path, r.block_off, r.entry, en["name"], en["w"], en["h"], en["fmt"],
en.get("mip", 0), target, orig, str(r.file), "edited", _twin(en)))
return out
# ----------------------------------------------------------------- xtx sheets
def _xtx_subs(data: bytes):
_total, count, hdr = struct.unpack_from("<III", data, 4)
subs = []
for i in range(count):
b = hdr + 20 * i
w, bufw, h = struct.unpack_from("<HHH", data, b)
gs_off, _size, addr = struct.unpack_from("<III", data, b + 8)
subs.append((w, bufw, h, gs_off, addr))
return subs
def _xtx_placed(data: bytes):
"""[(w, h, x0, y0, addr)] in placement order, by xtx._compose_ct32's rule
(a sub that does not fit the canvas is skipped)."""
subs = _xtx_subs(data)
clen = {4: 256, 8: 512}.get(subs[0][1] or 8)
out = []
for w, _b, h, gs_off, addr in subs:
y0 = (gs_off // (clen * 32)) * 32
x0 = (gs_off % (clen * 32)) // 32
if x0 + w > clen or y0 + h > clen:
continue
out.append((w, h, x0, y0, addr))
return clen, out
def mask_for(disc: Disc, chain: int, path: str) -> Optional[str]:
"""The frame mask browse cuts this sheet with: the last ``*_alpha.xtx``
in the same directory, in TOC order (browse.browse_xtx's rule)."""
if path.lower().endswith("_alpha.xtx"):
return None
d = path.rpartition("\\")[0].lower()
found = None
for c, e in disc.order:
if c == chain and e.path.lower().endswith(".xtx"):
ed, _, name = e.path.rpartition("\\")
if ed.lower() == d and name.lower().endswith("_alpha.xtx"):
found = e.path
return found
def xtx_view(data: bytes, mask: Optional[bytes]) -> Tuple[Optional[tuple], str]:
"""(browse's decode of a sheet, kind): kind is corner, mask, corner+mask,
ct32, or the decoder's palette source for sheets the kit cannot write."""
r = xtxmod.decode(data)
if r is None:
return None, "undecodable"
kind = r[3]
if kind == "corner" and mask is not None:
m = xtxmod.decode(mask)
if m is not None and m[3] == "mask":
cut = xtxmod.apply_mask(r, m)
if cut is not None:
return cut, "corner+mask"
return r, kind
def _corner_layout(data: bytes):
"""File offsets behind a parked-corner sheet: per pixel of the decoded
picture (index byte), per logical palette slot (word), plus the bytes of
the art area the picture does not reach."""
raw = arx.decompress(data) if data[:4] == b"ARX\x00" else data
comp = xtxmod._compose_ct32(raw)
canvas, clen, placed = comp
clen2, subs = _xtx_placed(raw)
if len(subs) != 1 or clen2 != clen:
raise ImportError_("sheet layout is not a single parked-corner image")
w, h, x0, y0, addr = subs[0]
W, H, rgba, _src = xtxmod._decode_parked(canvas, clen, w, h)
ys, xs = np.mgrid[0:H, 0:W]
o = txy.swz8_np(clen, xs.reshape(-1), ys.reshape(-1))
p = o // 4
cx, cy = p % clen, p // clen
inside = (cx < w) & (cy < h)
in_pal = (cx >= w - 16) & (cy < 16) & inside
if in_pal.any():
raise ImportError_("a picture pixel's index lies inside the sheet's palette tile")
# rows past an odd-height image (iwase\img\door\door_alpha.xtx is 33 rows) read the
# empty canvas: index 0, not stored, so they cannot change
pix = np.where(inside, addr + 32 + (cy * w + cx) * 4 + o % 4, -1)
pos = np.array(txy.csm1_positions(), np.int64)
pal_words = addr + 32 + ((pos // 16) * w + (w - 16) + pos % 16) * 4
art = np.zeros((h, w), bool)
art[:, :w - 16] = True
art_bytes = (addr + 32 + (np.nonzero(art.reshape(-1))[0][:, None] * 4 + np.arange(4))).reshape(-1)
rest = np.setdiff1d(art_bytes, pix[pix >= 0])
return raw, W, H, rgba, pix, pal_words, rest
def encode_corner(data: bytes, target: bytes, mode: str = "auto", dither: str = "none", keep=None):
"""(new sheet bytes, expected full picture, solution) for a parked-corner
sheet: the picture is the one user of its palette that can change; the art
bytes the picture does not show, and the pixels in ``keep`` (hidden by a
frame mask), keep their colours like an unedited sibling would."""
raw, W, H, orig, pix, pal_words, rest = _corner_layout(data)
arr = np.frombuffer(raw, np.uint8)
stored = pix >= 0
idx = np.zeros(len(pix), np.int64)
idx[stored] = arr[pix[stored]]
words = arr[(pal_words[:, None] + np.arange(4)).reshape(-1)].reshape(-1, 4)
pal = words.astype(np.int32).copy()
pal[:, 3] = texenc.a_dec(pal[:, 3])
origa = np.frombuffer(orig, np.uint8).reshape(-1, 4)
if not (pal[idx] == origa).all():
raise ImportError_("internal: the sheet's palette does not reproduce its decode")
tg = np.frombuffer(target, np.uint8).reshape(-1, 4)
keep = np.zeros(len(idx), bool) if keep is None else np.asarray(keep, bool).reshape(-1).copy()
keep |= ~stored
ed = ~keep
users = [texenc.User(idx[ed], origa[ed], tg[ed], None, None, "sheet")]
if keep.any():
users.append(texenc.User(idx[keep], origa[keep], None, None, None, "pixels the frame mask hides"))
if dither == "fs" and not keep.any():
users[0].shape = (W, H)
if len(rest):
ri = arr[rest].astype(np.int64)
users.append(texenc.User(ri, pal[ri].astype(np.uint8), None, None, None, "unshown art bytes"))
sol = texenc.solve_clut_group(pal.astype(np.uint8), users, "auto" if mode == "joint" else mode, dither)
buf = arr.copy()
for s in sol.changed_slots:
r, g, b, A = (int(v) for v in sol.pal[s])
buf[pal_words[s]:pal_words[s] + 4] = (r, g, b, int(texenc.a_raw(A)))
new_idx = idx.copy()
new_idx[ed] = sol.idx[0]
buf[pix[stored]] = new_idx[stored]
exp = origa.copy()
exp[ed] = sol.expected[0]
if keep.any():
exp[keep] = sol.expected[1]
return buf.tobytes(), exp.tobytes(), sol
def unmask_target(sheet: bytes, mask: bytes, png: bytes) -> Tuple[bytes, int]:
"""A corner+mask PNG back to a full-sheet target: inside the mask's crop,
pixels where the mask is opaque take the PNG's colour, the rest keep the
original. Returns (full target, number of changed pixels ignored because
the mask hides them, full-sheet mask of the pixels the PNG cannot reach)."""
full = xtxmod.decode(sheet)
m = xtxmod.decode(mask)
W, H, rgba = full[0], full[1], full[2]
MW, MH, mrgba = m[0], m[1], m[2]
ma = np.frombuffer(mrgba, np.uint8).reshape(MH, MW, 4)[:, :, 3]
if not np.isin(ma, (0, 255)).all():
raise ImportError_("the frame mask has partial alpha; the kit cannot invert it")
cols = np.nonzero(ma.any(0))[0]
rows = np.nonzero(ma.any(1))[0]
x0, x1, y0, y1 = cols[0], cols[-1] + 1, rows[0], rows[-1] + 1
OW, OH = x1 - x0, y1 - y0
masked = np.frombuffer(xtxmod.apply_mask(full, m)[2], np.uint8).reshape(-1, 4)
pngp = np.frombuffer(png, np.uint8).reshape(-1, 4)
if len(pngp) != OW * OH:
raise ImportError_(f"the PNG has {len(pngp)} pixels, the cut sheet {OW}x{OH}")
changed = ~texenc.same(pngp, masked)
tgt = np.frombuffer(rgba, np.uint8).reshape(H, W, 4).copy()
sub = ma[y0:y1, x0:x1].reshape(-1)
take = changed & (sub == 255)
yy, xx = np.divmod(np.nonzero(take)[0], OW)
tgt[yy + y0, xx + x0] = pngp[take]
keep = np.ones((H, W), bool)
keep[y0:y1, x0:x1] = (sub != 255).reshape(OH, OW)
return tgt.tobytes(), int((changed & (sub == 0)).sum()), keep
def encode_ct32(data: bytes, target: bytes):
"""(new sheet bytes, expected picture, warnings) for a true-colour sheet.
A changed pixel whose PNG alpha equals the shown original keeps its stored
alpha byte (this sheet stores full 8-bit alpha; how the engine reads values
above 0x80 is unverified); otherwise alpha is stored as min(0x80, (A+1)>>1)."""
raw = arx.decompress(data) if data[:4] == b"ARX\x00" else data
r = xtxmod.decode(raw)
W, H, orig = r[0], r[1], r[2]
clen, placed = _xtx_placed(raw)
own = np.full((H, W), -1, np.int64)
for w, h, x0, y0, addr in placed: # later subs win, as _compose_ct32 paints them
ys, xs = np.mgrid[0:h, 0:w]
sel = (y0 + ys < H) & (x0 + xs < W)
own[(y0 + ys)[sel], (x0 + xs)[sel]] = addr + 32 + (ys[sel] * w + xs[sel]) * 4
own = own.reshape(-1)
tg = np.frombuffer(target, np.uint8).reshape(-1, 4)
og = np.frombuffer(orig, np.uint8).reshape(-1, 4)
arr = np.frombuffer(raw, np.uint8)
buf = arr.copy()
st = own >= 0
warns = []
changed = ~texenc.same(tg, og)
lost = int((changed & ~st).sum())
if lost:
warns.append(f"{lost} changed pixels lie where no sub-image is stored; left as they were")
ch = changed & st
words = arr[(own[st][:, None] + np.arange(4)).reshape(-1)].reshape(-1, 4).astype(np.int64)
new = words.copy()
chs = ch[st]
new[chs, :3] = tg[ch, :3]
sa = texenc.canon(tg[ch])[:, 3]
keep_a = sa == texenc.canon(og[ch])[:, 3]
na = new[chs, 3]
na[~keep_a] = texenc.a_raw(tg[ch][~keep_a, 3])
new[chs, 3] = na
if (~keep_a).any():
warns.append(f"{int((~keep_a).sum())} pixels have new alpha, stored as min(0x80, (A+1)>>1); this sheet "
f"otherwise stores 8-bit alpha (how the engine reads it is unverified)")
buf[(own[st][:, None] + np.arange(4)).reshape(-1)] = new.reshape(-1).astype(np.uint8)
exp = og.astype(np.int32).copy()
e_st = exp[st]
e_st[chs, :3] = new[chs, :3]
e_st[chs, 3] = texenc.a_dec(new[chs, 3])
exp[st] = e_st
return buf.tobytes(), exp.astype(np.uint8).tobytes(), warns
def _xtx_job(args):
"""Phase 1 + encode for one sheet: (path, payload or None, report row, problems)."""
chain, path, file, mode, dither, force_target = args
disc = _WORKER["disc"]
out = {"problems": [], "warnings": [], "replace": None, "row": None, "unchanged": 0, "kind": ""}
e = disc.entry(chain, path)
if e is None:
out["problems"].append(f"{file}: no sheet {path!r} in chain {chain} on this disc")
return out
data = disc.read(chain, e.path)
mpath = mask_for(disc, chain, e.path)
mask = disc.read(chain, mpath) if mpath else None
view, kind = xtx_view(data, mask)
out["kind"] = kind
if view is None:
out["problems"].append(f"{file}: the kit cannot decode {e.path}")
return out
W, H, shown = view[0], view[1], view[2]
if force_target:
png = shown
else:
png, why = _png_target(Path(file), W, H)
if png is None:
out["problems"].append(why)
return out
if texenc.same(np.frombuffer(png, np.uint8), np.frombuffer(shown, np.uint8)).all():
out["unchanged"] = 1
return out
if kind not in XTX_OK:
if force_target:
return out
out["problems"].append(f"{file}: {e.path} is refused: its palette is {kind}, not solved "
f"(FORMATS.md, UI sheet palettes)")
return out
try:
if kind == "ct32":
new, exp, warns = encode_ct32(data, png)
out["warnings"] += [f"{e.path}: {w}" for w in warns]
action = "true colour"
else:
target, keep = png, None
if kind == "corner+mask":
target, ignored, keep = unmask_target(data, mask, png)
if ignored:
out["warnings"].append(f"{e.path}: {ignored} changed pixels lie where the frame mask hides "
f"them; ignored")
new, exp, sol = encode_corner(data, target, mode, dither, keep)
out["warnings"] += [f"{e.path}: {w}" for w in sol.warnings]
action = sol.action
check, kind2 = xtx_view(new, mask)
want = exp
if kind == "corner+mask":
full = xtxmod.decode(new)
want = xtxmod.apply_mask((full[0], full[1], exp, "corner"), xtxmod.decode(mask))[2]
slots = 0 if kind == "ct32" else len(sol.changed_slots)
if check is None or kind2 != kind or check[2] != want:
raise ImportError_("internal check failed: the rebuilt sheet does not decode to the plan (please report)")
raw = arx.decompress(data) if data[:4] == b"ARX\x00" else data
if new != raw:
got = np.frombuffer(check[2], np.uint8).reshape(-1, 4)
pc = ~(got == np.frombuffer(shown, np.uint8).reshape(-1, 4)).all(1)
out["replace"] = ((chain, e.path), new)
out["row"] = {"chain": chain, "path": e.path, "block_off": "", "entry": "", "name": e.path.rsplit("\\", 1)[-1],
"role": "edited", "source": str(file), "palette": action,
"slots_changed": slots,
"pixels_changed": int(pc.sum()),
"psnr": texenc.psnr(np.frombuffer(png, np.uint8).reshape(-1, 4)[pc], got[pc]),
"bytes_changed": int((np.frombuffer(new, np.uint8) != np.frombuffer(raw, np.uint8)).sum()),
"_before": (W, H, shown), "_after": (W, H, check[2]), "_kind": kind}
out["identical"] = new == raw
except (ImportError_, texenc.EncodeError) as err:
out["problems"].append(f"{file}: {e.path}: {err}")
return out
# ------------------------------------------------------------------ glb files
def read_gltf_images(file: Path) -> List[Tuple[Optional[str], bytes, str]]:
"""[(image name, encoded bytes, mime)] of a .glb or .gltf."""
import base64
import json
import gltf
data = file.read_bytes()
if data[:4] == b"glTF":
js, binc = gltf.read_glb(data)
bufs = {0: binc}
else:
js = json.loads(data.decode("utf-8"))
bufs = {}
for k, b in enumerate(js.get("buffers", [])):
uri = b.get("uri", "")
if uri.startswith("data:"):
bufs[k] = base64.b64decode(uri.split(",", 1)[1])
elif uri:
bufs[k] = (file.parent / uri).read_bytes()
out = []
for img in js.get("images", []):
mime = img.get("mimeType", "")
if "bufferView" in img:
v = js["bufferViews"][img["bufferView"]]
b = bufs[v.get("buffer", 0)]
blob = bytes(b[v.get("byteOffset", 0):v.get("byteOffset", 0) + v["byteLength"]])
else:
uri = img.get("uri", "")
if uri.startswith("data:"):
mime = mime or uri[5:].split(";", 1)[0]
blob = base64.b64decode(uri.split(",", 1)[1])
else:
blob = (file.parent / uri).read_bytes()
mime = mime or ("image/png" if uri.lower().endswith(".png") else "")
out.append((img.get("name"), blob, mime or ("image/png" if blob[:8] == pngread.SIGNATURE else "")))
return out
_DUP_SUFFIX = re.compile(r"^(.+)\.\d{3}$")
def map_glb_images(names: List[Optional[str]], t: dict, decoded: Dict[int, tuple], used: Optional[set]):
"""Image k -> entry index, by (1) the PNG-file stem the export names images
after, (2) an entry name unique among the entries the model uses (files
exported before images carried the stem). A ``.NNN`` tail (Blender's suffix
for a repeated image name) is tried without it when the full name does not
match. Image order is never used: Blender writes images in its own order.
Returns ({k: entry}, [unmapped k], {entry: [k, ...]} for entries two or
more images claim); unmapped and claimed-twice images are problems."""
multi = len(t["banks"]) > 1
by_stem = {Path(txy.entry_filename(e, multi)).stem: e["i"] for e in t["entries"] if e["i"] in decoded}
uniq = {}
if used is not None:
cnt: Dict[str, List[int]] = {}
for i in sorted(used & set(decoded)):
cnt.setdefault(t["entries"][i]["name"], []).append(i)
uniq = {n: v[0] for n, v in cnt.items() if len(v) == 1}
found: Dict[int, int] = {}
left = []
for k, nm in enumerate(names):
tries = [nm]
m = _DUP_SUFFIX.match(nm or "")
if m:
tries.append(m.group(1))
for cand in tries:
if cand in by_stem:
found[k] = by_stem[cand]
break
if cand in uniq:
found[k] = uniq[cand]
break
else:
left.append(k)
claims: Dict[int, List[int]] = {}
for k, i in found.items():
claims.setdefault(i, []).append(k)
clash = {i: ks for i, ks in claims.items() if len(ks) > 1}
mapping = {k: i for k, i in found.items() if i not in clash}
return mapping, left, clash
def _glb_job(args):
chain, txy_path, file = args
disc = _WORKER["disc"]
out = {"edits": [], "problems": [], "unchanged": 0}
try:
images = read_gltf_images(Path(file))
except Exception as err: # a damaged file is a problem, not a crash
out["problems"].append(f"{file}: cannot read ({type(err).__name__}: {err})")
return out
if not images: # exported untextured: nothing to bring back
return out
e = disc.entry(chain, txy_path)
if e is None:
out["problems"].append(f"{file}: no texture page {txy_path!r} beside this model on the disc")
return out
data = disc.read(chain, e.path)
try:
t = txy.parse(data)
except txy.TxyError as err:
out["problems"].append(f"{file}: {e.path}: {err}")
return out
decoded = {en["i"]: (en, rgba) for en, _w, _h, rgba in txy.decode_fast(data)}
names = [nm for nm, _b, _m in images]
multi = len(t["banks"]) > 1
stems = {Path(txy.entry_filename(x, multi)).stem for x in t["entries"]}
used = None
if not all(nm in stems for nm in names):
pe = disc.entry(chain, txy_path[:-4] + ".pxy")
if pe is not None:
import pxy
try:
p = pxy.parse(disc.read(chain, pe.path))
pxy.link_textures(p, t["entries"])
used = {m.txy_entry["i"] for d in p.draws for m in d.materials if m.txy_entry is not None}
except Exception as err:
out["problems"].append(f"{file}: the model {pe.path} does not parse ({err})")
return out
mapping, left, clash = map_glb_images(names, t, decoded, used)
for k in left:
out["problems"].append(f"{file}: image {k} ({names[k]!r}) matches no entry of {e.path}; name it after "
f"its PNG file (browse writes the names, e.g. 009_kosmos00_mune)")
for i, ks in sorted(clash.items()):
out["problems"].append(f"{file}: images " + ", ".join(f"{k} ({names[k]!r})" for k in ks)
+ f" all map to entry {i} ({t['entries'][i]['name']}) of {e.path}; keep one")
for k, i in sorted(mapping.items()):
nm, blob, mime = images[k]
en, orig = decoded[i]
if mime != "image/png":
out["problems"].append(f"{file}: image {k} ({nm!r}) is {mime or 'not a PNG'}; export PNG images")
continue
try:
pw, ph, rgba = pngread.read_png(blob)
except pngread.PngError as err:
out["problems"].append(f"{file}: image {k} ({nm!r}): {err}")
continue
if (pw, ph) != (en["w"], en["h"]):
out["problems"].append(f"{file}: image {k} ({nm!r}) is {pw}x{ph}, entry {i} is {en['w']}x{en['h']}")
continue
if texenc.same(np.frombuffer(rgba, np.uint8), np.frombuffer(orig, np.uint8)).all():
out["unchanged"] += 1
continue
if en["bank"] >= len(t["banks"]) or (en["fmt"] in (txy.PSMT8, txy.PSMT4) and en["cbp"] == 0xFFFFFFFF):
out["problems"].append(f"{file}: image {k} maps to entry {i} ({en['name']}), refused (bogus entry)")
continue
out["edits"].append(Edit(chain, e.path, 0, i, en["name"], en["w"], en["h"], en["fmt"], en.get("mip", 0),
rgba, orig, f"{file}#image{k}({nm})", "edited", _twin(en)))
return out
# ====================================================================== sweep
def _sweep_job(args):
"""Entries of one object whose decoded picture is one of the wanted ones."""
chain, path = args
wanted = _WORKER["wanted"]
disc = _WORKER["disc"]
data = disc.read(chain, path)
hits = []
for off, block in blocks_of(path, data):
try:
t = txy.parse(block)
except txy.TxyError:
continue
if not t["banks"] or not any((e["w"], e["h"]) in wanted for e in t["entries"]):
continue
cw, ch = t["canvas_w"], txy.canvas_height(t)
cache = {}
for e in t["entries"]:
shas = wanted.get((e["w"], e["h"]))
if not shas or e["bank"] >= len(t["banks"]) or \
(e["fmt"] in (txy.PSMT8, txy.PSMT4) and e["cbp"] == 0xFFFFFFFF):
continue
b = min(e["bank"], len(t["banks"]) - 1)
if b not in cache:
cache[b] = txy.canvas_np(block, txy.owner_map(t, b))
rgba = txy.decode_entry_np(cache[b], cw, ch, e)
if rgba is None:
continue
sha = hashlib.sha1(rgba).hexdigest()
if sha in shas:
hits.append((chain, path, off, e["i"], e["name"], sha, e["fmt"], e["w"], e["h"], e.get("mip", 0),
_twin(e)))
return hits
def box_down(rgba: np.ndarray, w: int, h: int) -> Tuple[np.ndarray, int, int]:
"""One mip level down: 2x2 box filter, RGB weighted by alpha."""
a = rgba.reshape(h, w, 4).astype(np.float64)
nw, nh = max(1, w // 2), max(1, h // 2)
a = a[:nh * 2 if h > 1 else 1, :nw * 2 if w > 1 else 1]
if h > 1:
a = a.reshape(nh, 2, a.shape[1], 4).transpose(0, 2, 1, 3).reshape(nh, a.shape[1], 2, 4)
a = a.reshape(nh, a.shape[1], 2, 4)
else:
a = a.reshape(1, a.shape[1], 1, 4)
# a: (nh, W2, ky, 4); now fold x
if w > 1:
a = a.reshape(nh, nw, 2, a.shape[2], 4).reshape(nh, nw, -1, 4)
else:
a = a.reshape(nh, 1, -1, 4)
al = a[..., 3]
s = al.sum(-1)
rgb = np.where(s[..., None] > 0, (a[..., :3] * al[..., None]).sum(-2) / np.maximum(s, 1e-9)[..., None],
a[..., :3].mean(-2))
out = np.concatenate([rgb, al.mean(-1)[..., None]], -1)
return np.clip(np.rint(out), 0, 255).astype(np.uint8).reshape(-1, 4), nw, nh
# ======================================================================= main
_WORKER: dict = {}
def _is_path(iso) -> bool:
return isinstance(iso, (str, Path))
def _init(iso_path, wanted=None):
_WORKER["disc"] = Disc(iso_path, check=False) if _is_path(iso_path) else iso_path
_WORKER["wanted"] = wanted or {}
def _pool_map(fn, jobs, iso_path, wanted=None, workers=None):
"""Map over jobs in worker processes (each opens the image once)."""
jobs = list(jobs)
if len(jobs) <= 2 or workers == 1 or not _is_path(iso_path):
_init(iso_path, wanted)
try:
return [fn(j) for j in jobs]
finally: # the image this call opened is closed again (Windows
if _is_path(iso_path): # cannot move or delete a file that is still open)
_WORKER.pop("disc").close()
with ProcessPoolExecutor(max_workers=workers or os.cpu_count() or 4, initializer=_init,
initargs=(iso_path, wanted)) as ex:
return list(ex.map(fn, jobs, chunksize=max(1, min(16, len(jobs) // 64 or 1))))
def _encode_obj_job(args):
"""Encode every block of one object that has edits: (key, new object
bytes, per-block results)."""
chain, path, per_block, mode, dither, force = args
disc = _WORKER["disc"]
data = disc.read(chain, path)
blocks = dict(blocks_of(path, data))
buf = bytearray(data)
res = {}
for off, edits in sorted(per_block.items()):
block = blocks[off]
bmode = mode[off] if isinstance(mode, dict) else mode
try:
r = texenc.encode_block(block, edits, bmode, dither, force=force)
except texenc.EncodeError as err:
return {"key": (chain, path), "error": f"{path} block {off:#x}: {err}"}
buf[off:off + len(block)] = r.block
res[off] = {"expected": r.expected, "roles": r.roles, "rows": r.rows, "warnings": r.warnings,
"identical": r.block == block}
return {"key": (chain, path), "data": bytes(buf), "orig_same": bytes(buf) == data, "blocks": res}
def _roundtrip_job(args):
chain, path = args
disc = _WORKER["disc"]
data = disc.read(chain, path)
out = {"blocks": 0, "entries": 0, "placeholders": 0, "bogus": 0, "fail": [], "std": 0, "emb": 0}
for off, block in blocks_of(path, data):
try:
t, infos = texenc.analyse(block)
except txy.TxyError as err:
out["fail"].append(f"{path} {off:#x}: {err}")
continue
if not t["banks"]:
out["placeholders"] += 1
continue
edits = {i: inf.orig for i, inf in infos.items() if not inf.bogus}
out["bogus"] += sum(1 for inf in infos.values() if inf.bogus)
try:
r = texenc.encode_block(block, edits, force=True, t=t, info=(t, infos))
if r.block != block:
out["fail"].append(f"{path} {off:#x}: bytes differ")
except texenc.EncodeError as err:
out["fail"].append(f"{path} {off:#x}: {err}")
continue
out["blocks"] += 1
out["entries"] += len(edits)
out["std" if path.lower().endswith(".txy") else "emb"] += 1
return out
def _fmt_psnr(v) -> str:
return "inf" if v == math.inf else f"{v:.2f}"
def verify_roundtrip(iso_path: str) -> int:
t0 = time.time()
disc = Disc(iso_path)
objs = carrier_objects(disc)
sheets = [(c, e.path) for c, e in disc.order if e.path.lower().endswith(".xtx")]
disc.close()
print(f"round trip: {len(objs)} texture pages and carriers, {len(sheets)} UI sheets; every entry is forced "
f"through the edit path with its own picture as the target")
res = _pool_map(_roundtrip_job, objs, iso_path)
tot = {k: 0 for k in ("blocks", "entries", "placeholders", "bogus", "std", "emb")}
fails = []
for r in res:
for k in tot:
tot[k] += r[k]
fails += r["fail"]
print(f"txy: {tot['std']} standalone + {tot['emb']} embedded blocks byte-identical "
f"({tot['entries']} entries), {tot['placeholders']} placeholders skipped, "
f"{tot['bogus']} bogus entries left out (refused for editing), {len(fails)} failures")
xres = _pool_map(_xtx_job, [(c, p, "", "auto", "none", True) for c, p in sheets], iso_path)
kinds: Dict[str, int] = {}
xok = 0
for (c, p), r in zip(sheets, xres):
kinds[r["kind"]] = kinds.get(r["kind"], 0) + 1
if r["kind"] in XTX_OK:
if r["problems"] or not r.get("identical"):
fails.append(f"{p}: " + ("; ".join(r["problems"]) or "bytes differ"))
else:
xok += 1
print(f"xtx: {xok} importable sheets byte-identical ("
+ ", ".join(f"{k} {v}" for k, v in sorted(kinds.items()) if k in XTX_OK) + "); not importable: "
+ ", ".join(f"{k} {v}" for k, v in sorted(kinds.items()) if k not in XTX_OK))
for f in fails:
print(f"FAIL {f}")
print(f"{len(fails)} failures, {time.time() - t0:.0f} s")
return 1 if fails else 0
def _key(e: Edit):
return (e.chain, e.path.lower(), e.block_off, e.entry)
def run(iso, out=None, tree=None, textures=None, xtx=None, models=None, palette="auto", dither="none",
sweep="pixels", mips="rebuild", grow=False, dry_run=False, preview=None, report=None,
verify_roundtrip_=False, workers=None, _plan=None) -> int:
if verify_roundtrip_:
try:
return verify_roundtrip(iso)
except region.UnknownBuild as err:
print(f"refused: {err}", file=sys.stderr)
return 1
t0 = time.time()
if palette not in texenc.MODES or dither not in texenc.DITHERS or sweep not in ("pixels", "name", "none") \
or mips not in ("keep", "rebuild"):
print("bad option value", file=sys.stderr)
return 2
if not out and not dry_run:
print("--out is required (or --dry-run)", file=sys.stderr)
return 2
why = report_clash(report, out, iso)
if why:
print(f"refused: {why}", file=sys.stderr)
return 2
try:
roots = resolve_roots(tree, textures, xtx, models)
disc = Disc(iso) if _is_path(iso) else iso
except (ImportError_, region.UnknownBuild) as err:
print(f"refused: {err}", file=sys.stderr)
return 1
refs, problems = scan_tree(roots)
# spell paths as the disc does and group by object
by_obj: Dict[Tuple[int, str], List[Ref]] = {}
xtx_refs, glb_refs = [], []
for r in refs:
if r.kind in ("txy", "emb"):
e = disc.entry(r.chain, r.path)
if e is None:
problems.append(f"{r.file}: no object {r.path!r} in chain {r.chain} on this disc")
continue
by_obj.setdefault((r.chain, e.path), []).append(r)
elif r.kind == "xtx":
xtx_refs.append(r)
else:
glb_refs.append(r)
n_png = sum(len(v) for v in by_obj.values())
print(f"tree: {n_png} texture PNGs in {len(by_obj)} files, {len(xtx_refs)} UI sheets, {len(glb_refs)} models")