upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/ttpf_mips.py
diff options
context:
space:
mode:
Diffstat (limited to 'tools/ttpf_mips.py')
-rw-r--r--tools/ttpf_mips.py845
1 files changed, 845 insertions, 0 deletions
diff --git a/tools/ttpf_mips.py b/tools/ttpf_mips.py
new file mode 100644
index 000000000..050eb9b22
--- /dev/null
+++ b/tools/ttpf_mips.py
@@ -0,0 +1,845 @@
1"""Measure and decode the TTPF (RDS5) compact mip chain, including the packed tail.
2
3The compact profile in `TtpfReader` is the AMD Gfx10 mip-tail layout: mips smaller
4than half a tile share one tile at offset 0, and the rest are standalone, smallest
5first. `TtpfReader` only trusts a hand-validated tuple table and stops at the
6descriptor's `nonTail` field, which is not the layout boundary. This tool computes
7the layout from the descriptor and validates it against the native allocation span,
8then decodes the mips that are zlib/raw (no BCPack backend is used or guessed).
9
10Read-only: no texture bytes are printed or committed. `scan` emits aggregate
11counters only. `layout` prints descriptor fields and offsets. `check` prints the
12BC block-average error against a 2x2 downsample of the parent mip; it decodes
13BC1, BC3, BC4_UNORM and BC5_UNORM (BC2, the SNORM BC4/5 variants, BC6H and BC7
14are sized but not decoded, and uncompressed tiling is not validated). `export`
15writes a full BC chain only when every source mip is zlib/raw.
16
17 python -I tools/ttpf_mips.py scan <game root or pool paths...> [--json out]
18 python -I tools/ttpf_mips.py layout <pool.ttpf> <index>
19 python -I tools/ttpf_mips.py check <pool.ttpf> <index>
20 python -I tools/ttpf_mips.py export <pool.ttpf> <index> <out.dds> [--mips N] [--force]
21
22Standard library only. The RDS5/ETPF checks mirror rpf9-explorer's `TtpfReader`
23(MIT); the tile patterns and tail formula are the AMD Gfx10 4 KiB/64 KiB layouts
24already used by that reader and recorded in docs/textures.md.
25"""
26import argparse
27import glob
28import json
29import mmap
30import os
31import struct
32import sys
33import zlib
34
35MAX_OUTPUT = 256 * 1024 * 1024
36MAX_TEXTURES = 250_000
37ETPF_VERSION = 634
38
39# DXGI format -> element bytes, as RageTextureDecoder.ElementBytes. DXGI 11
40# (R16G16B16A16_UNORM) is 8 bytes but is left out here as well: its uncompressed
41# tiling has not been validated, so `scan` reports it as a format gap.
42ELEMENT_BYTES = {
43 2: 16, 3: 16, 4: 16, 6: 12, 7: 12, 8: 12, 10: 8, 12: 8, 13: 8, 14: 8,
44 16: 8, 17: 8, 18: 8, 24: 4, 25: 4, 26: 4, 28: 4, 29: 4, 30: 4, 31: 4, 32: 4,
45 34: 4, 35: 4, 36: 4, 37: 4, 38: 4, 41: 4, 42: 4, 43: 4, 49: 2, 50: 2, 51: 2,
46 52: 2, 54: 2, 56: 2, 57: 2, 58: 2, 59: 2, 61: 1, 62: 1, 63: 1, 64: 1, 65: 1,
47 71: 8, 72: 8, 74: 16, 75: 16, 77: 16, 78: 16, 80: 8, 81: 8, 83: 16, 84: 16,
48 87: 4, 88: 4, 91: 4, 93: 4, 95: 16, 96: 16, 98: 16, 99: 16,
49}
50BC_FORMATS = frozenset(range(70, 85)) | frozenset(range(94, 100))
51
52# AMD Gfx10 intra-tile bit order (bit index -> source bit), from TtpfReader.
53PATTERNS_4K = {
54 0: (1, 2, 3, 4, -1, -2, -3, -4, -5, 5, -6, 6),
55 1: (0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6),
56 2: (0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5),
57 3: (0, 0, 0, 1, -1, -2, 2, 3, -3, 4, -4, 5),
58 4: (0, 0, 0, 0, -1, -2, 1, 2, -3, 3, -4, 4),
59}
60PATTERNS_64K = {
61 0: (1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8),
62 1: (0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8),
63 2: (0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7),
64 3: (0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7),
65 4: (0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6),
66}
67
68# The profile tuples `TtpfReader.ValidatedCompactProfile` accepts. Reproduced only
69# so `scan` can show the reader's published skip/partial split next to the layout
70# result; decoding does not depend on this table.
71VALIDATED_COMPACT = {
72 (4, 1024, 1024, 9, 3, 8, 0x503, 0x00B00106),
73 (6, 512, 512, 8, 3, 8, 0x041, 0x00B800D4),
74 (4, 256, 256, 7, 1, 8, 0x103, 0),
75 (4, 512, 512, 8, 3, 16, 0x482, 0x015000F5),
76 (4, 1024, 512, 8, 3, 8, 0x482, 0x015000F5),
77 (4, 512, 1024, 8, 3, 8, 0x483, 0x013000F5),
78 (4, 128, 256, 6, 1, 8, 0x083, 0),
79 (4, 256, 512, 7, 1, 8, 0x167, 0),
80 (4, 512, 256, 7, 1, 8, 0x166, 0),
81 (4, 256, 256, 7, 1, 16, 0x166, 0),
82 (4, 1024, 512, 8, 3, 16, 0x504, 0x900106),
83 (4, 1024, 256, 7, 3, 16, 0x484, 0x11000F5),
84 (6, 1024, 256, 7, 3, 8, 0x42, 0x9800D4),
85 (6, 64, 1024, 5, 3, 8, 0x83, 0x3800B4),
86 (4, 512, 1024, 8, 3, 16, 0x503, 0xB00106),
87 (4, 512, 128, 6, 1, 16, 0x168, 0),
88 (6, 256, 1024, 7, 3, 8, 0x83, 0x3800D4),
89 (4, 1024, 128, 6, 1, 8, 0x168, 0),
90 (4, 2048, 256, 7, 3, 16, 0x508, 0x100106),
91 (4, 2048, 512, 8, 3, 8, 0x504, 0x900106),
92 (6, 512, 256, 7, 3, 16, 0x42, 0x9800D4),
93 (6, 1024, 128, 6, 3, 16, 0x84, 0x1800D4),
94 (4, 512, 128, 6, 1, 8, 0x104, 0),
95 (4, 256, 1024, 7, 3, 16, 0x483, 0x13000F5),
96 (6, 1024, 64, 5, 3, 16, 0x83, 0x3800B4),
97 (6, 256, 512, 7, 3, 16, 0x41, 0xB800D4),
98 (4, 128, 128, 6, 1, 16, 0x82, 0),
99 (4, 512, 64, 5, 1, 16, 0x108, 0),
100 (4, 256, 128, 6, 1, 16, 0x104, 0),
101 (6, 128, 1024, 6, 3, 16, 0x83, 0x3800D4),
102 (4, 512, 64, 5, 1, 8, 0x84, 0),
103 (4, 128, 512, 6, 1, 16, 0x167, 0),
104 (4, 256, 128, 6, 1, 8, 0x82, 0),
105 (4, 1024, 64, 5, 1, 8, 0x108, 0),
106 (6, 1024, 32, 4, 3, 16, 0x82, 0x5800B4),
107 (4, 128, 512, 6, 1, 8, 0x107, 0),
108 (4, 512, 2048, 8, 3, 8, 0x507, 0x300106),
109 (4, 256, 2048, 7, 3, 8, 0x507, 0x3000F5),
110 (4, 512, 32, 4, 1, 16, 0x107, 0),
111 (6, 128, 1024, 6, 3, 8, 0x83, 0x3800B4),
112 (6, 64, 1024, 5, 3, 16, 0x83, 0x3800B4),
113 (4, 256, 256, 5, 1, 16, 0x166, 0),
114 (4, 128, 256, 6, 1, 16, 0x103, 0),
115 (4, 256, 64, 5, 1, 16, 0x84, 0),
116 (4, 16, 256, 3, 1, 16, 0x83, 0),
117 (4, 256, 32, 4, 1, 16, 0x84, 0),
118 (4, 64, 512, 5, 1, 16, 0x107, 0),
119 (4, 2048, 256, 7, 3, 8, 0x484, 0x11000F5),
120 (4, 64, 512, 5, 1, 8, 0x107, 0),
121 (4, 64, 256, 5, 1, 8, 0x83, 0),
122 (6, 256, 512, 9, 3, 16, 0x41, 0xB800D4),
123 (6, 32, 1024, 4, 3, 16, 0x82, 0x5800B4),
124 (4, 512, 512, 3, 3, 8, 0x502, 0xD00006),
125 (36, 1024, 1024, 9, 3, 8, 0x503, 0xB00106),
126 (36, 256, 256, 7, 1, 8, 0x103, 0),
127}
128VALIDATED_AUX = dict(mips=3, non_tail=3, meta=0x1A8, extra=0x01080008, width=1024,
129 height_a=512, fmt_a=61, height_b=1024, bytes_b=8)
130
131
132class LayoutError(ValueError):
133 pass
134
135
136class BcpackRequired(NotImplementedError):
137 pass
138
139
140def u32(b, o):
141 return struct.unpack_from("<I", b, o)[0]
142
143
144def u64(b, o):
145 return struct.unpack_from("<Q", b, o)[0]
146
147
148def align(v, n):
149 return (v + n - 1) // n * n
150
151
152def tile_mode(mode):
153 """Descriptor mode is a flag bit plus a 4-bit Gfx10 tile mode at bit 1."""
154 return (mode >> 1) & 0xF
155
156
157def tile_bytes(mode):
158 # Tile mode 0 is SW_64KB_D; 1-3 are SW_4KB_S; 9-12 appear only on arrays.
159 return 65536 if tile_mode(mode) == 0 else 4096
160
161
162def element_bytes(fmt):
163 if fmt not in ELEMENT_BYTES:
164 raise LayoutError(f"no element-size mapping for DXGI format {fmt}")
165 return ELEMENT_BYTES[fmt]
166
167
168def surface_layout(width, height, fmt, mips, tile=4096):
169 """AMD Gfx10 surface layout: standalone mips smallest-first, then one tail tile.
170
171 Returns a dict with the allocation size, the first tail mip index, block
172 dimensions and a per-mip list. `offset` is relative to the allocation base.
173 """
174 eb = element_bytes(fmt)
175 log = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[eb]
176 px = 4 if fmt in BC_FORMATS else 1
177 levels = 1
178 v = max(width, height)
179 while v > 1:
180 levels += 1
181 v >>= 1
182 if mips < 1 or mips > levels:
183 raise LayoutError(f"invalid mip count {mips} for {width}x{height}")
184 half_bits = 6 if tile == 4096 else 8
185 max_tail = 8 if tile == 4096 else 12
186 bw = 1 << (half_bits - log // 2)
187 bh = 1 << (half_bits - (log + 1) // 2)
188 mw, mh = {0: (16, 16), 1: (16, 8), 2: (8, 8), 3: (8, 4)}.get(log, (4, 4))
189 ew = (width + px - 1) // px
190 eh = (height + px - 1) // px
191 tail = mips
192 sizes = []
193 out = []
194 for i in range(mips):
195 wc = max(1, (ew + (1 << i) - 1) >> i)
196 hc = max(1, (eh + (1 << i) - 1) >> i)
197 if mips > 1 and wc <= bw // 2 and hc <= bh and mips - i <= max_tail:
198 tail = i
199 break
200 pw = align(wc, bw)
201 ph = align(hc, bh)
202 sizes.append(pw * ph * eb)
203 out.append(dict(index=i, blocks_w=wc, blocks_h=hc, padded_w=pw, padded_h=ph,
204 pixels_w=max(1, width >> i), pixels_h=max(1, height >> i),
205 offset=0, region=pw * ph * eb, tile_x=0, tile_y=0, in_tail=False))
206 off = tile if tail < mips else 0
207 for i in range(tail - 1, -1, -1):
208 out[i]["offset"] = off
209 off += sizes[i]
210 for i in range(tail, mips):
211 entry = max_tail - 1 - (i - tail)
212 moff = (16 << entry) if entry > 6 else entry << 8
213 x = y = 0
214 for bit in range(6):
215 x |= ((moff >> (9 + 2 * bit)) & 1) << bit
216 y |= ((moff >> (8 + 2 * bit)) & 1) << bit
217 wc = max(1, (ew + (1 << i) - 1) >> i)
218 hc = max(1, (eh + (1 << i) - 1) >> i)
219 out.append(dict(index=i, blocks_w=wc, blocks_h=hc, padded_w=bw, padded_h=bh,
220 pixels_w=max(1, width >> i), pixels_h=max(1, height >> i),
221 offset=0, region=tile, tile_x=x * mw, tile_y=y * mh,
222 in_tail=True, tail_offset=moff))
223 return dict(size=off, tile=tile, first_tail=tail, block_w=bw, block_h=bh,
224 element_bytes=eb, mips=out)
225
226
227def detile(layout, mip, tiled):
228 """Copy the mip's elements out of the tiled allocation into block-linear order."""
229 pat = (PATTERNS_4K if layout["tile"] == 4096 else PATTERNS_64K)[
230 {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[layout["element_bytes"]]]
231 bw, bh = layout["block_w"], layout["block_h"]
232 eb = layout["element_bytes"]
233 out = bytearray(mip["blocks_w"] * mip["blocks_h"] * eb)
234 for y in range(mip["blocks_h"]):
235 for x in range(mip["blocks_w"]):
236 off = ((y // bh) * (mip["padded_w"] // bw) + x // bw) * layout["tile"]
237 for bit, s in enumerate(pat):
238 if s > 0:
239 off |= (((x + mip["tile_x"]) >> (s - 1)) & 1) << bit
240 elif s < 0:
241 off |= (((y + mip["tile_y"]) >> (-s - 1)) & 1) << bit
242 at = (y * mip["blocks_w"] + x) * eb
243 out[at:at + eb] = tiled[off:off + eb]
244 return bytes(out)
245
246
247# --- BC decoding (color only; enough for the downsample check) -------------
248
249def _rgb565(c):
250 return ((c >> 11) & 31) * 255.0 / 31, ((c >> 5) & 63) * 255.0 / 63, (c & 31) * 255.0 / 31
251
252
253def decode_bc1_block(data, at):
254 c0, c1, idx = struct.unpack_from("<HHI", data, at)
255 p0, p1 = _rgb565(c0), _rgb565(c1)
256 if c0 > c1:
257 pal = [p0, p1, tuple((2 * a + b) / 3 for a, b in zip(p0, p1)),
258 tuple((a + 2 * b) / 3 for a, b in zip(p0, p1))]
259 else:
260 pal = [p0, p1, tuple((a + b) / 2 for a, b in zip(p0, p1)), (0.0, 0.0, 0.0)]
261 return [pal[(idx >> (2 * (y * 4 + x))) & 3] for y in range(4) for x in range(4)]
262
263
264def decode_bc4_block(data, at):
265 e0, e1 = data[at], data[at + 1]
266 bits = int.from_bytes(data[at + 2:at + 8], "little")
267 if e0 > e1:
268 pal = [e0, e1] + [((7 - i) * e0 + i * e1) // 7 for i in range(1, 7)]
269 else:
270 pal = [e0, e1] + [((5 - i) * e0 + i * e1) // 5 for i in range(1, 5)] + [0, 255]
271 vals = [pal[(bits >> (3 * (y * 4 + x))) & 7] for y in range(4) for x in range(4)]
272 return [(float(v),) * 3 for v in vals]
273
274
275def decode_pixels(fmt, data, blocks_w, blocks_h):
276 """Return one (r, g, b) per pixel, or None for a format this tool cannot decode."""
277 px = []
278 for by in range(blocks_h):
279 rows = [[None] * (blocks_w * 4) for _ in range(4)]
280 for bx in range(blocks_w):
281 at = (by * blocks_w + bx) * 16
282 if fmt in (71, 72):
283 blk = decode_bc1_block(data, (by * blocks_w + bx) * 8)
284 elif fmt in (77, 78):
285 blk = decode_bc1_block(data, at + 8)
286 elif fmt in (80,):
287 blk = decode_bc4_block(data, (by * blocks_w + bx) * 8, False)
288 elif fmt in (83,):
289 a = decode_bc4_block(data, at, False)
290 b = decode_bc4_block(data, at + 8, False)
291 blk = [(p[0], q[0], 0.0) for p, q in zip(a, b)]
292 else:
293 return None
294 for y in range(4):
295 for x in range(4):
296 rows[y][bx * 4 + x] = blk[y * 4 + x]
297 px.extend(rows)
298 return [p for row in px for p in row]
299
300
301def block_means(pixels, blocks_w, blocks_h):
302 out = []
303 for by in range(blocks_h):
304 for bx in range(blocks_w):
305 acc = [0.0, 0.0, 0.0]
306 for y in range(4):
307 for x in range(4):
308 q = pixels[(by * 4 + y) * (blocks_w * 4) + bx * 4 + x]
309 for k in range(3):
310 acc[k] += q[k]
311 out.append((acc[0] / 16, acc[1] / 16, acc[2] / 16))
312 return out
313
314
315def downsample2(blocks, blocks_w, blocks_h):
316 ow, oh = max(1, blocks_w // 2), max(1, blocks_h // 2)
317 out = []
318 for y in range(oh):
319 for x in range(ow):
320 acc = [0.0, 0.0, 0.0]
321 n = 0
322 for dy in range(2):
323 for dx in range(2):
324 bx = min(blocks_w - 1, 2 * x + dx)
325 by = min(blocks_h - 1, 2 * y + dy)
326 q = blocks[by * blocks_w + bx]
327 for k in range(3):
328 acc[k] += q[k]
329 n += 1
330 out.append(tuple(a / n for a in acc))
331 return out
332
333
334def mean_abs_error(a, b):
335 if not a:
336 return None
337 return sum(abs(x - y) for pa, pb in zip(a, b) for x, y in zip(pa, pb)) / (3 * len(a))
338
339
340# --- RDS5 / ETPF container ------------------------------------------------
341
342class Pool:
343 """Read-only RDS5 texture pool, mirroring TtpfReader's catalog checks."""
344
345 def __init__(self, path):
346 self.path = path
347 self._fh = open(path, "rb")
348 try:
349 self.data = mmap.mmap(self._fh.fileno(), 0, access=mmap.ACCESS_READ)
350 except Exception:
351 self._fh.close()
352 raise
353 d = self.data
354 if len(d) < 256 or d[:4] != b"RDS5":
355 raise ValueError("not an RDS5 container or truncated header")
356 count = u32(d, 4)
357 size_word = u64(d, 8)
358 self.virtual_size = size_word & 0x00FFFFFFFFFFFFFF
359 if (count < 3 or count > 1_000_002 or (size_word >> 56) != 22 or
360 self.virtual_size < 4096 or u32(d, 16) not in
361 ((count + 31) // 32, (count + 31) // 32 + 1)):
362 raise ValueError("unsupported RDS5 index layout")
363 self.chunk_count = count - 2
364 table_end = 24 + (count - 1) * 8
365 self.etpf = align(table_end, 256)
366 if table_end > len(d) - 16:
367 raise ValueError("RDS5 index exceeds its source")
368 table = d[24:table_end]
369 if ((u64(table, len(table) - 8) & 0x3FFFFFF) * 256 != len(d) or
370 ((u64(table, len(table) - 8) >> 30) & 0x3FFFFF) * 4096 != self.virtual_size):
371 raise ValueError("RDS5 sentinel does not match its lengths")
372 self.chunks = []
373 for i in range(self.chunk_count):
374 v, nxt = u64(table, i * 8), u64(table, (i + 1) * 8)
375 start, end = (v & 0x3FFFFFF) * 256, (nxt & 0x3FFFFFF) * 256
376 virt, vend = ((v >> 30) & 0x3FFFFF) * 4096, ((nxt >> 30) & 0x3FFFFF) * 4096
377 pad = v >> 52
378 codec = (v >> 26) & 15
379 packed, size = end - start - pad, vend - virt
380 if (start < self.etpf + 16 or end > len(d) or packed < 1 or packed > MAX_OUTPUT or
381 size < 1 or size > MAX_OUTPUT or vend > self.virtual_size or
382 (codec == 0 and packed != size)):
383 raise ValueError(f"RDS5 chunk {i} range is invalid")
384 self.chunks.append((virt, size, start, packed, codec, pad))
385 eh = d[self.etpf:self.etpf + 16]
386 if eh[:4] != b"ETPF" or u32(eh, 4) != ETPF_VERSION:
387 raise ValueError("unsupported embedded ETPF version")
388 self.textures = u32(eh, 8)
389 area = u32(eh, 12)
390 metadata = 16 + area + self.textures * 32
391 padded = align(metadata, 4096)
392 alignment = u32(d, 20)
393 source_padding = (alignment >> 28) * 256
394 if (self.textures < 1 or self.textures > MAX_TEXTURES or area < self.textures * 16 or
395 (alignment & 0x0FFFFFFF) != 0 or padded != self.chunks[0][0] or
396 self.etpf + padded + source_padding != self.chunks[0][2]):
397 raise ValueError("ETPF tables do not match the data boundary")
398 self.area = area
399 self.records = d[self.etpf + 16:self.etpf + 16 + area]
400 self.ids = d[self.etpf + 16 + area:self.etpf + 16 + area + self.textures * 32]
401 self._starts = [c[0] for c in self.chunks]
402
403 def close(self):
404 self.data.close()
405 self._fh.close()
406
407 def descriptor(self, index):
408 if not 0 <= index < self.textures:
409 raise IndexError(index)
410 a, b, c, d = struct.unpack_from("<IIII", self.records, index * 16)
411 return dict(
412 index=index, width=(a & 0x3FFF) + 1, height=((a >> 14) & 0x3FFF) + 1,
413 mips=(a >> 28) + (b & 7), packed_mips=a >> 28, non_tail=b & 7,
414 format=(b >> 3) & 255, depth=((b >> 11) & 1023) + 1,
415 dimension=(b >> 21) & 3, mode=b >> 23, meta=c >> 21, extra=d,
416 base=(c & 0x1FFFFF) * 4096, asset_key_at=(
417 u64(self.records, self.textures * 16 + index * 8)
418 if (self.textures * 16 + index * 8 + 8 <= len(self.records))
419 else None),
420 )
421
422 def chunks_for(self, start, size):
423 import bisect
424 end = start + size
425 i = max(0, bisect.bisect_right(self._starts, start) - 1)
426 out = []
427 covered = start
428 while i < len(self.chunks) and self.chunks[i][0] < end:
429 virt, csize, src, packed, codec, pad = self.chunks[i]
430 if virt > covered:
431 raise ValueError("texture crosses an unmapped virtual range")
432 out.append(self.chunks[i])
433 covered = min(end, virt + csize)
434 i += 1
435 if covered != end:
436 raise ValueError("texture range is not completely mapped")
437 return out
438
439 def codecs(self, start, size):
440 return {c[4] for c in self.chunks_for(start, size)}
441
442 def readable(self, start, size):
443 return self.codecs(start, size) <= {0, 8}
444
445 def read_range(self, start, size, cache=None):
446 cache = {} if cache is None else cache
447 out = bytearray(size)
448 for virt, csize, src, packed, codec, pad in self.chunks_for(start, size):
449 key = (src, packed, codec)
450 if key not in cache:
451 raw = self.data[src:src + packed]
452 if codec == 0:
453 cache[key] = bytes(raw)
454 elif codec == 8:
455 cache[key] = zlib.decompress(raw)
456 else:
457 raise BcpackRequired("range touches a BCPack chunk")
458 if len(cache[key]) != csize:
459 raise ValueError("decoded chunk length disagrees with its range")
460 lo, hi = max(start, virt), min(start + size, virt + csize)
461 out[lo - start:hi - start] = cache[key][lo - virt:hi - virt]
462 return bytes(out)
463
464 def span(self, index, base):
465 for j in range(index + 1, self.textures):
466 cand = (u32(self.records, j * 16 + 8) & 0x1FFFFF) * 4096
467 if cand < base:
468 return None
469 if cand > base:
470 return cand - base
471 return self.virtual_size - base
472
473
474def compact_row(desc):
475 """The reader's compact-profile gate (mode families 4/6/36 and aux mode 2)."""
476 return desc["mode"] in (4, 6, 36) or (desc["mode"] == 2 and (desc["meta"] or desc["extra"]))
477
478
479def validated_compact(desc, eb):
480 return (desc["mode"], desc["width"], desc["height"], desc["mips"], desc["non_tail"],
481 eb, desc["meta"], desc["extra"]) in VALIDATED_COMPACT
482
483
484def validated_aux(desc):
485 a = VALIDATED_AUX
486 return (desc["mips"] == a["mips"] and desc["non_tail"] == a["non_tail"] and
487 desc["meta"] == a["meta"] and desc["extra"] == a["extra"] and
488 desc["width"] == a["width"] and
489 ((desc["height"] == a["height_a"] and desc["format"] == a["fmt_a"]) or
490 (desc["height"] == a["height_b"] and desc["format"] in BC_FORMATS and
491 ELEMENT_BYTES.get(desc["format"]) == a["bytes_b"])))
492
493
494def analyze(pool, index):
495 """Descriptor + layout + per-mip codec availability for one texture."""
496 d = pool.descriptor(index)
497 out = dict(descriptor=d, tile_mode=tile_mode(d["mode"]), tile=tile_bytes(d["mode"]))
498 if d["dimension"] != 1 or d["depth"] != 1:
499 out["blocked"] = "array/volume descriptor"
500 return out
501 try:
502 layout = surface_layout(d["width"], d["height"], d["format"], d["mips"],
503 out["tile"])
504 except LayoutError as e:
505 out["blocked"] = str(e)
506 return out
507 out["layout"] = layout
508 if d["base"] == 0 or (d["base"] >> 12) == 0x1FFFFF:
509 out["blocked"] = "no mapped allocation"
510 return out
511 span = pool.span(index, d["base"])
512 out["allocation_span"] = span
513 out["span_matches"] = span == layout["size"]
514 if not out["span_matches"]:
515 out["blocked"] = "layout does not match the allocation span"
516 return out
517 avail = []
518 for mip in layout["mips"]:
519 try:
520 avail.append(pool.readable(d["base"] + mip["offset"], mip["region"]))
521 except ValueError:
522 avail = []
523 break
524 out["available"] = avail
525 if avail:
526 limit = d["non_tail"] if compact_row(d) else d["mips"]
527 limit = max(0, min(limit, len(avail)))
528 base_mip = next((i for i in range(limit) if avail[i]), None)
529 exported = 0
530 if base_mip is not None:
531 while base_mip + exported < limit and avail[base_mip + exported]:
532 exported += 1
533 out["reader_limit"] = limit
534 out["reader_base_mip"] = base_mip
535 out["reader_exported"] = exported
536 out["full_chain"] = bool(avail) and all(avail)
537 out["recoverable_mips"] = sum(1 for a in avail[exported:] if a) if base_mip == 0 else 0
538 return out
539
540
541# --- commands --------------------------------------------------------------
542
543def find_pools(arg):
544 if os.path.isfile(arg):
545 return [arg]
546 pools = sorted(glob.glob(os.path.join(arg, "data", "ttdb", "**", "*.ttpf"), recursive=True))
547 pools += sorted(glob.glob(os.path.join(arg, "pack", "*", "data", "ttdb", "**", "*.ttpf"),
548 recursive=True))
549 return pools
550
551
552def scan_pools(paths, as_json=None):
553 total = dict(pools=0, entries=0, arrays=0, unsupported_format=0, format11=0,
554 layout_mismatch=0, reader_full=0, reader_partial=0,
555 reader_skip_bcpack=0, whitelist_gated=0, gated_layout_ok=0,
556 gated_full_chain=0, gated_full_mips=0, gated_full_bytes=0,
557 gated_tail_only=0, gated_by_mode={},
558 compact_partial_rows=0, compact_missing_mips=0,
559 compact_decodable_mips=0, compact_decodable_bytes=0,
560 compact_missing_standalone=0, compact_missing_tail=0,
561 compact_rows_measured=0, compact_non_tail_before_tail=0,
562 compact_standalone_beyond_limit=0,
563 compact_standalone_decodable_beyond_limit=0,
564 compact_full_rows=0, tile_modes={})
565 for path in paths:
566 pool = Pool(path)
567 try:
568 total["pools"] += 1
569 for i in range(pool.textures):
570 d = pool.descriptor(i)
571 total["entries"] += 1
572 tm = str(tile_mode(d["mode"]))
573 total["tile_modes"][tm] = total["tile_modes"].get(tm, 0) + 1
574 if d["dimension"] != 1 or d["depth"] != 1:
575 total["arrays"] += 1
576 continue
577 # The reader's gate: modes 4/6/36 and aux mode 2 need a validated tuple;
578 # every other non-0/2 mode is rejected by the same branch.
579 aux = d["mode"] == 2 and (d["meta"] or d["extra"])
580 if d["mode"] in (0, 2):
581 gated = d["mode"] == 2 and aux and not validated_aux(d)
582 else:
583 eb = ELEMENT_BYTES.get(d["format"])
584 gated = not (d["mode"] in (4, 6, 36) and eb is not None and
585 validated_compact(d, eb))
586 try:
587 layout = surface_layout(d["width"], d["height"], d["format"],
588 d["mips"], tile_bytes(d["mode"]))
589 except LayoutError:
590 total["unsupported_format"] += 1
591 if d["format"] == 11:
592 total["format11"] += 1
593 if gated:
594 total["whitelist_gated"] += 1
595 continue
596 span = pool.span(i, d["base"])
597 if d["base"] == 0 or span != layout["size"]:
598 total["layout_mismatch"] += 1
599 continue
600 avail = []
601 for mip in layout["mips"]:
602 try:
603 avail.append(pool.readable(d["base"] + mip["offset"], mip["region"]))
604 except ValueError:
605 avail = []
606 break
607 if not avail:
608 total["layout_mismatch"] += 1
609 continue
610 if gated:
611 total["whitelist_gated"] += 1
612 total["gated_layout_ok"] += 1
613 key = str(d["mode"])
614 total["gated_by_mode"][key] = total["gated_by_mode"].get(key, 0) + 1
615 if all(avail):
616 total["gated_full_chain"] += 1
617 total["gated_full_mips"] += d["mips"]
618 total["gated_full_bytes"] += sum(
619 mip["blocks_w"] * mip["blocks_h"] * layout["element_bytes"]
620 for mip in layout["mips"])
621 elif (layout["first_tail"] < d["mips"] and
622 all(avail[k] for k in range(layout["first_tail"], d["mips"]))):
623 total["gated_tail_only"] += 1
624 continue
625 is_compact = compact_row(d)
626 limit = min(d["non_tail"], len(avail)) if is_compact else len(avail)
627 base_mip = next((k for k in range(limit) if avail[k]), None)
628 exported = 0
629 if base_mip is not None:
630 while base_mip + exported < limit and avail[base_mip + exported]:
631 exported += 1
632 if exported == 0:
633 total["reader_skip_bcpack"] += 1
634 elif exported < d["mips"]:
635 total["reader_partial"] += 1
636 if is_compact and base_mip == 0 and exported == limit:
637 total["compact_partial_rows"] += 1
638 missing = d["mips"] - exported
639 total["compact_missing_mips"] += missing
640 dec = 0
641 for k in range(exported, d["mips"]):
642 if avail[k]:
643 dec += 1
644 if k < layout["first_tail"]:
645 total["compact_missing_standalone"] += 1
646 else:
647 total["compact_missing_tail"] += 1
648 total["compact_decodable_mips"] += dec
649 total["compact_decodable_bytes"] += sum(
650 layout["mips"][k]["blocks_w"] * layout["mips"][k]["blocks_h"] *
651 layout["element_bytes"] for k in range(exported, d["mips"])
652 if avail[k])
653 if dec == missing:
654 total["compact_full_rows"] += 1
655 else:
656 total["reader_full"] += 1
657 if d["mode"] in (4, 6, 36):
658 total["compact_rows_measured"] += 1
659 if d["non_tail"] < layout["first_tail"]:
660 total["compact_non_tail_before_tail"] += 1
661 total["compact_standalone_beyond_limit"] += (
662 layout["first_tail"] - d["non_tail"])
663 total["compact_standalone_decodable_beyond_limit"] += sum(
664 1 for k in range(d["non_tail"], layout["first_tail"]) if avail[k])
665 finally:
666 pool.close()
667 report = dict(total=total)
668 if as_json:
669 with open(as_json, "w", encoding="utf-8") as f:
670 json.dump(report, f, indent=1)
671 print(json.dumps(report, indent=1))
672
673
674def describe(pool, index):
675 a = analyze(pool, index)
676 d = a["descriptor"]
677 out = dict(index=index, width=d["width"], height=d["height"], format=d["format"],
678 mips=d["mips"], non_tail=d["non_tail"], mode=d["mode"],
679 tile_mode=a["tile_mode"], tile=a["tile"], base=d["base"],
680 meta=d["meta"], extra=d["extra"])
681 if "layout" in a:
682 out["allocation_size"] = a["layout"]["size"]
683 out["allocation_span"] = a.get("allocation_span")
684 out["span_matches"] = a.get("span_matches")
685 out["first_tail_mip"] = a["layout"]["first_tail"]
686 out["mips_detail"] = [
687 dict(index=m["index"], blocks=[m["blocks_w"], m["blocks_h"]], offset=m["offset"],
688 region=m["region"], tail=m["in_tail"], tile_origin=[m["tile_x"], m["tile_y"]])
689 for m in a["layout"]["mips"]]
690 if "available" in a:
691 out["available"] = a["available"]
692 out["reader_limit"] = a["reader_limit"]
693 out["reader_exported"] = a["reader_exported"]
694 out["full_chain"] = a["full_chain"]
695 if a.get("blocked"):
696 out["blocked"] = a["blocked"]
697 return out
698
699
700def check(pool, index):
701 a = analyze(pool, index)
702 if "layout" not in a:
703 print(json.dumps(dict(index=index, blocked=a.get("blocked")), indent=1))
704 return 2
705 layout = a["layout"]
706 d = a["descriptor"]
707 cache = {}
708 try:
709 tiled = pool.read_range(d["base"], layout["size"], cache)
710 except BcpackRequired:
711 print(json.dumps(dict(index=index, blocked="BCPack in allocation"), indent=1))
712 return 2
713 decoded, means = [], []
714 for mip in layout["mips"]:
715 data = detile(layout, mip, tiled[mip["offset"]:mip["offset"] + mip["region"]])
716 px = decode_pixels(d["format"], data, mip["blocks_w"], mip["blocks_h"])
717 if px is None:
718 decoded.append(None)
719 means.append(None)
720 else:
721 decoded.append(px)
722 means.append(block_means(px, mip["blocks_w"], mip["blocks_h"]))
723 if all(px is None for px in decoded):
724 print(json.dumps(dict(index=index, blocked=(
725 f"format {d['format']} is not one of the BC formats this tool decodes "
726 "(71/72/77/78/80/83)")), indent=1))
727 return 2
728 errs = []
729 for k in range(1, d["mips"]):
730 if means[k - 1] is None or means[k] is None:
731 errs.append(None)
732 continue
733 pm = layout["mips"][k - 1]
734 cm = layout["mips"][k]
735 errs.append(round(mean_abs_error(downsample2(means[k - 1], pm["blocks_w"], pm["blocks_h"]),
736 means[k]), 2))
737 control = None
738 if layout["first_tail"] < d["mips"] and decoded[layout["first_tail"] - 1] is not None:
739 tm = layout["mips"][layout["first_tail"]]
740 bad = dict(tm, tile_x=0, tile_y=0)
741 data = detile(layout, bad, tiled[:layout["tile"]])
742 px = decode_pixels(d["format"], data, tm["blocks_w"], tm["blocks_h"])
743 if px is not None:
744 pm = layout["mips"][layout["first_tail"] - 1]
745 control = round(mean_abs_error(
746 downsample2(means[layout["first_tail"] - 1], pm["blocks_w"], pm["blocks_h"]),
747 block_means(px, tm["blocks_w"], tm["blocks_h"])), 2)
748 result = dict(index=index, width=d["width"], height=d["height"], format=d["format"],
749 mips=d["mips"], non_tail=d["non_tail"], first_tail=layout["first_tail"],
750 tile=layout["tile"], chain_error=errs, max_error=max(
751 (e for e in errs if e is not None), default=None),
752 tail_origin_control=control, full_chain=a.get("full_chain"))
753 print(json.dumps(result, indent=1))
754 return 0 if all(e is not None and e <= 6 for e in errs) else 1
755
756
757def dds_bytes(width, height, fmt, mips, linear, payload):
758 hdr = bytearray(128)
759 hdr[0:4] = b"DDS "
760 flags = 0x81007 if mips == 1 else 0xA1007
761 struct.pack_into("<IIIIIII", hdr, 4, 124, flags, height, width, linear, 0, mips)
762 struct.pack_into("<II4s", hdr, 76, 32, 4, b"DX10")
763 struct.pack_into("<II", hdr, 108, 0x1000 if mips == 1 else 0x401008, 0)
764 return bytes(hdr) + struct.pack("<IIIII", fmt, 3, 0, 1, 0) + payload
765
766
767def export(pool, index, out_path, mips=None, force=False):
768 a = analyze(pool, index)
769 if "layout" not in a or "available" not in a:
770 print(f"texture {index}: {a.get('blocked', 'layout unavailable')}", file=sys.stderr)
771 return 2
772 d = a["descriptor"]
773 if d["format"] not in BC_FORMATS:
774 print(f"texture {index}: format {d['format']} is uncompressed; this tool does not "
775 "validate uncompressed tiling, so it will not write a DDS", file=sys.stderr)
776 return 2
777 if not a["full_chain"]:
778 print(f"texture {index}: not every source mip is zlib/raw; refusing to mix BCPack",
779 file=sys.stderr)
780 return 2
781 count = d["mips"] if mips is None else mips
782 if count < 1 or count > d["mips"]:
783 print(f"texture {index}: --mips must be 1..{d['mips']}", file=sys.stderr)
784 return 2
785 layout = a["layout"]
786 cache = {}
787 payload = bytearray()
788 for mip in layout["mips"][:count]:
789 tiled = pool.read_range(d["base"] + mip["offset"], mip["region"], cache)
790 payload += detile(layout, mip, tiled)
791 if 148 + len(payload) > MAX_OUTPUT:
792 print("DDS exceeds the 256 MiB output limit", file=sys.stderr)
793 return 2
794 if os.path.exists(out_path) and not force:
795 print(f"{out_path} exists; pass --force to replace it", file=sys.stderr)
796 return 2
797 top = layout["mips"][0]
798 linear = (top["blocks_w"] * top["blocks_h"] * layout["element_bytes"]
799 if d["format"] in BC_FORMATS else d["width"] * layout["element_bytes"])
800 with open(out_path, "wb") as f:
801 f.write(dds_bytes(d["width"], d["height"], d["format"], count, linear, payload))
802 print(f"texture {index}: {d['width']}x{d['height']} fmt {d['format']} {count} mips "
803 f"({148 + len(payload)} bytes) -> {out_path}")
804 return 0
805
806
807def main(argv=None):
808 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
809 sub = ap.add_subparsers(dest="cmd", required=True)
810 ps = sub.add_parser("scan", help="aggregate counters over pools")
811 ps.add_argument("paths", nargs="+")
812 ps.add_argument("--json")
813 pl = sub.add_parser("layout", help="descriptor fields and mip offsets")
814 pl.add_argument("pool")
815 pl.add_argument("index", type=int)
816 pc = sub.add_parser("check", help="decode a chain and report downsample error")
817 pc.add_argument("pool")
818 pc.add_argument("index", type=int)
819 pe = sub.add_parser("export", help="write the full zlib/raw chain as DDS")
820 pe.add_argument("pool")
821 pe.add_argument("index", type=int)
822 pe.add_argument("out")
823 pe.add_argument("--mips", type=int)
824 pe.add_argument("--force", action="store_true")
825 a = ap.parse_args(argv)
826 if a.cmd == "scan":
827 pools = []
828 for p in a.paths:
829 pools += find_pools(p)
830 scan_pools(pools, a.json)
831 return 0
832 pool = Pool(a.pool)
833 try:
834 if a.cmd == "layout":
835 print(json.dumps(describe(pool, a.index), indent=1))
836 return 0
837 if a.cmd == "check":
838 return check(pool, a.index)
839 return export(pool, a.index, a.out, a.mips, a.force)
840 finally:
841 pool.close()
842
843
844if __name__ == "__main__":
845 sys.exit(main())