mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 18:08:40 +00:00
`if a.limit: texs = texs[: a.limit]` read --limit 0 as "no limit" and exported every texture in the index, and a negative --limit silently dropped the last textures. --limit is now a positive whole number (an argparse error otherwise, before the output folder is made), and the slice runs whenever it is given. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
285 lines
11 KiB
Python
285 lines
11 KiB
Python
"""Tests for tools/tex_export.py, on synthetic textures and swizzle equations (no game data, no addrlib header).
|
|
|
|
python -m pytest tests/test_tex_export.py -q
|
|
"""
|
|
import pytest # noqa: E402 (keeps the CI bash loop from running this file)
|
|
|
|
import json
|
|
import os
|
|
import struct
|
|
import sys
|
|
|
|
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tools"))
|
|
|
|
np = pytest.importorskip("numpy")
|
|
import tex_export as T # noqa: E402
|
|
|
|
|
|
def linear_eq(bpe, xor=False):
|
|
"""A 4 KB equation in the shape eq4k returns: byte bits, then x bits, then y bits (row-major in the tile).
|
|
With xor=True each x bit also takes a y bit, which keeps it a bijection but no longer row-major."""
|
|
lb = (4096 // bpe).bit_length() - 1
|
|
xb, yb = (lb + 1) // 2, lb - (lb + 1) // 2
|
|
low = bpe.bit_length() - 1
|
|
xs = [(1 << k, (1 << (k % yb)) if xor else 0) for k in range(xb)]
|
|
return [(0, 0)] * low + xs + [(0, 1 << k) for k in range(yb)]
|
|
|
|
|
|
@pytest.fixture
|
|
def eq(monkeypatch):
|
|
"""Install synthetic equations in eq4k's cache, so nothing reads the addrlib header."""
|
|
def install(bpe, xor=False):
|
|
monkeypatch.setitem(T._EQ, bpe, linear_eq(bpe, xor))
|
|
return install
|
|
|
|
|
|
def tile(elements, offs, nbytes):
|
|
"""Inverse of detiling: put each row-major element at the address detile_offsets gives it."""
|
|
bpe = elements.shape[1]
|
|
buf = np.zeros(nbytes, np.uint8)
|
|
buf.reshape(-1, bpe)[offs] = elements
|
|
return buf.tobytes()
|
|
|
|
|
|
def gradient(we, he, bpe):
|
|
y, x = np.mgrid[0:he, 0:we]
|
|
e = np.zeros((he * we, bpe), np.uint8)
|
|
e[:, 0] = (x * 255 // max(1, we - 1)).reshape(-1)
|
|
e[:, 1] = (y * 255 // max(1, he - 1)).reshape(-1)
|
|
e[:, 2] = 128
|
|
e[:, 3] = 255
|
|
return e
|
|
|
|
|
|
def noise(nbytes, seed=1):
|
|
return np.random.default_rng(seed).integers(0, 256, nbytes, dtype=np.uint8).tobytes()
|
|
|
|
|
|
def write_blob(carve, archive, off, data):
|
|
d = os.path.join(carve, archive)
|
|
os.makedirs(d, exist_ok=True)
|
|
with open(os.path.join(d, f"{off:012x}.bin"), "wb") as f:
|
|
f.write(data)
|
|
|
|
|
|
def texture(fmt, fmt_name, w, h, mips, data_off=0, gpu=0x1000, **extra):
|
|
t = {"archive": "x.rpf", "cpu": 0xABC, "q_index": 3, "gpu": gpu, "gpu_size": 0, "fmt": fmt,
|
|
"fmt_name": fmt_name, "w": w, "h": h, "mips": mips, "data_off": data_off}
|
|
t.update(extra)
|
|
return t
|
|
|
|
|
|
# ---- eq4k ----
|
|
|
|
def test_import_does_not_read_the_addrlib_header(monkeypatch):
|
|
import importlib.util
|
|
import amd_swizzle
|
|
|
|
def no_header(*a, **k):
|
|
raise AssertionError("load() called at import")
|
|
|
|
monkeypatch.setattr(amd_swizzle, "load", no_header)
|
|
spec = importlib.util.spec_from_file_location("tex_export_fresh", T.__file__)
|
|
spec.loader.exec_module(importlib.util.module_from_spec(spec))
|
|
|
|
|
|
def test_eq4k_reads_the_patterns_once_and_picks_the_entry_for_bpe(monkeypatch):
|
|
calls = []
|
|
bits8 = [0, 0, 0] + [1 << k for k in range(5)] + [(1 << k) << 16 for k in range(4)]
|
|
bits4 = [0, 0] + [1 << k for k in range(5)] + [(1 << k) << 16 for k in range(5)]
|
|
nibbles = {"NIBBLE01": [bits8[:8], bits4[:8]], "NIBBLE2": [bits8[8:12], bits4[8:12]],
|
|
"NIBBLE3": [[0] * 4], "NIBBLE4": [[0] * 4]}
|
|
tables = {"GFX10_SW_4K_S_PATINFO": [(1, 1, 1, 0, 0, "SW_4K_S 4 bpe"), (1, 0, 0, 0, 0, "SW_4K_S 8 bpe")]}
|
|
|
|
def fake_load():
|
|
calls.append(1)
|
|
return nibbles, tables
|
|
|
|
monkeypatch.setattr(T, "load", fake_load)
|
|
monkeypatch.setattr(T, "_PATTERNS", [])
|
|
monkeypatch.setattr(T, "_EQ", {})
|
|
assert T.eq4k(8) == linear_eq(8)
|
|
assert T.eq4k(4) == linear_eq(4)
|
|
assert T.eq4k(8) == linear_eq(8)
|
|
assert len(calls) == 1
|
|
|
|
|
|
# ---- detile_offsets / level_bytes ----
|
|
|
|
@pytest.mark.parametrize("bpe", [1, 2, 4, 8, 16])
|
|
def test_linear_equation_detiles_row_major_tiles(eq, bpe):
|
|
eq(bpe)
|
|
offs, bw, bh = T.detile_offsets(bpe, 2 * 64, 2 * 64)
|
|
assert bw * bh * bpe == 4096
|
|
we = 2 * 64
|
|
y, x = np.divmod(np.arange(we * we), we)
|
|
tile_index = (y // bh) * (we // bw) + x // bw
|
|
assert np.array_equal(offs, tile_index * (4096 // bpe) + (y % bh) * bw + x % bw)
|
|
|
|
|
|
@pytest.mark.parametrize("bpe", [4, 8, 16])
|
|
def test_offsets_are_a_permutation_of_whole_tiles(eq, bpe):
|
|
eq(bpe, xor=True)
|
|
_, bw, bh = T.detile_offsets(bpe, 1, 1)
|
|
we, he = 3 * bw, 2 * bh
|
|
offs, _, _ = T.detile_offsets(bpe, we, he)
|
|
assert sorted(offs.tolist()) == list(range(we * he))
|
|
assert T.level_bytes(we, he, bpe, bw, bh) == 6 * 4096
|
|
|
|
|
|
def test_partial_tiles_are_padded_to_whole_tiles(eq):
|
|
eq(4)
|
|
_, bw, bh = T.detile_offsets(4, 1, 1)
|
|
assert T.level_bytes(1, 1, 4, bw, bh) == 4096
|
|
assert T.level_bytes(bw + 1, bh, 4, bw, bh) == 2 * 4096
|
|
offs, _, _ = T.detile_offsets(4, bw + 1, 1)
|
|
assert int(offs.max()) == 4096 // 4 # first element of the second tile
|
|
assert len(set(offs.tolist())) == bw + 1
|
|
|
|
|
|
# ---- dds_bytes ----
|
|
|
|
def test_dds_header_is_a_dx10_texture2d():
|
|
payload = bytes(range(64))
|
|
b = T.dds_bytes(16, 8, 71, payload)
|
|
assert len(b) == 128 + 20 + len(payload)
|
|
assert b[:4] == b"DDS "
|
|
size, flags, h, w, linear = struct.unpack_from("<IIIII", b, 4)
|
|
assert (size, h, w, linear) == (124, 8, 16, len(payload))
|
|
assert flags & 0x1007 == 0x1007 and flags & 0x80000 # caps|height|width|pixelformat, linearsize
|
|
assert struct.unpack_from("<II4s", b, 76) == (32, 4, b"DX10")
|
|
assert struct.unpack_from("<I", b, 108)[0] == 0x1000
|
|
fmt, dim, misc, array, misc2 = struct.unpack_from("<IIIII", b, 128)
|
|
assert (fmt, dim, misc, array, misc2) == (71, 3, 0, 1, 0)
|
|
assert b[148:] == payload
|
|
|
|
|
|
# ---- export_one ----
|
|
|
|
def build_case(eq, tmp_path, fmt, top_first):
|
|
"""A 64x64 texture with two mips: a smooth top mip and a noise mip, in either order in the GPU blob."""
|
|
bpe, blk = T.FMT[fmt]
|
|
eq(bpe)
|
|
w = h = 64
|
|
we, he = w // blk, h // blk
|
|
offs, bw, bh = T.detile_offsets(bpe, we, he)
|
|
top_bytes = T.level_bytes(we, he, bpe, bw, bh)
|
|
small = T.level_bytes(max(1, (w // 2) // blk), max(1, (h // 2) // blk), bpe, bw, bh)
|
|
top = gradient(we, he, bpe)
|
|
tiled = tile(top, offs, top_bytes)
|
|
blob = tiled + noise(small) if top_first else noise(small) + tiled
|
|
carve = str(tmp_path / "carve")
|
|
write_blob(carve, "x.rpf", 0x1000, blob)
|
|
return carve, top.tobytes()
|
|
|
|
|
|
@pytest.mark.parametrize("fmt,name", [(10, "R16G16B16A16_FLOAT"), (28, "R8G8B8A8_UNORM")])
|
|
@pytest.mark.parametrize("top_first", [True, False])
|
|
def test_export_picks_the_top_mip_placement_and_writes_dds(eq, tmp_path, fmt, name, top_first):
|
|
if fmt in T.PILLOW_OK:
|
|
pytest.importorskip("PIL")
|
|
carve, expected = build_case(eq, tmp_path, fmt, top_first)
|
|
out = str(tmp_path / "out")
|
|
t = texture(fmt, name, 64, 64, mips=2)
|
|
r = T.export_one(t, carve, out, {})
|
|
place = "first" if top_first else "last"
|
|
assert r == "ok:" + place
|
|
assert t["export"]["place"] == place
|
|
assert t["export"]["file"] == f"{0xABC:012x}_3_64x64_{name}.dds"
|
|
with open(os.path.join(out, "x.rpf", t["export"]["file"]), "rb") as f:
|
|
dds = f.read()
|
|
assert struct.unpack_from("<I", dds, 128)[0] == fmt
|
|
assert dds[148:] == expected
|
|
|
|
|
|
def test_gpu_chain_parts_are_read_in_order(eq, tmp_path):
|
|
carve, expected = build_case(eq, tmp_path, 10, top_first=True)
|
|
with open(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin"), "rb") as f:
|
|
blob = f.read()
|
|
os.remove(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin"))
|
|
cut = 12345
|
|
write_blob(carve, "x.rpf", 0x1000, blob[:cut])
|
|
write_blob(carve, "x.rpf", 0x9000, blob[cut:])
|
|
t = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2,
|
|
gpu_chain=[[0x1000, cut], [0x9000, len(blob) - cut]])
|
|
out = str(tmp_path / "out")
|
|
assert T.export_one(t, carve, out, {}) == "ok:first"
|
|
with open(os.path.join(out, "x.rpf", t["export"]["file"]), "rb") as f:
|
|
assert f.read()[148:] == expected
|
|
|
|
|
|
def test_blob_cache_is_reused_for_the_same_blob(eq, tmp_path):
|
|
carve, _ = build_case(eq, tmp_path, 10, top_first=True)
|
|
cache = {}
|
|
t = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2)
|
|
assert T.export_one(t, carve, str(tmp_path / "out"), cache) == "ok:first"
|
|
os.remove(os.path.join(carve, "x.rpf", f"{0x1000:012x}.bin")) # a second read would fail
|
|
t2 = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2)
|
|
assert T.export_one(t2, carve, str(tmp_path / "out"), cache) == "ok:first"
|
|
|
|
|
|
def test_unsupported_format_is_reported():
|
|
assert T.export_one(texture(9999, "X", 4, 4, 1), "unused", "unused", {}) == "unsupported format"
|
|
|
|
|
|
@pytest.mark.parametrize("fmt,bpe", [(61, 1), (56, 2), (10, 8), (28, 4)])
|
|
@pytest.mark.parametrize("w,h", [(5, 3), (5, 1), (1, 5)])
|
|
def test_score_prefers_a_smooth_gradient(fmt, bpe, w, h):
|
|
if fmt in T.PILLOW_OK:
|
|
pytest.importorskip("PIL")
|
|
pixels = max(w, h)
|
|
values = [i * 240 // (pixels - 1) for i in range(pixels)]
|
|
zigzag = values[::2] + values[1::2][::-1]
|
|
copies = min(w, h)
|
|
ramp = b"".join(bytes([value]) * bpe for value in values * copies)
|
|
rough = b"".join(bytes([value]) * bpe for value in zigzag * copies)
|
|
assert T.score_image(w, h, fmt, ramp, bpe) < T.score_image(w, h, fmt, rough, bpe)
|
|
|
|
|
|
def test_single_element_has_no_edge_transitions():
|
|
assert T.score_image(1, 1, 61, b"\x80", 1) == 0
|
|
|
|
|
|
def test_data_outside_the_blob_is_reported(eq, tmp_path):
|
|
eq(8)
|
|
carve = str(tmp_path / "carve")
|
|
write_blob(carve, "x.rpf", 0x1000, bytes(100))
|
|
t = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=1)
|
|
assert T.export_one(t, carve, str(tmp_path / "out"), {}) == "data outside GPU blob"
|
|
assert "export" not in t
|
|
|
|
|
|
# ---- main ----
|
|
|
|
def test_main_writes_the_log_and_honours_limit(eq, tmp_path, monkeypatch, capsys):
|
|
carve, _ = build_case(eq, tmp_path, 10, top_first=True)
|
|
index = tmp_path / "textures_index.json"
|
|
good = texture(10, "R16G16B16A16_FLOAT", 64, 64, mips=2)
|
|
bad = texture(9999, "X", 4, 4, 1, gpu=0x2000)
|
|
index.write_text(json.dumps([bad, good]), encoding="utf-8")
|
|
out = tmp_path / "out"
|
|
monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), carve, str(out)])
|
|
T.main()
|
|
log = json.loads((out / "export_log.json").read_text(encoding="utf-8"))
|
|
assert [t["gpu"] for t in log] == [0x1000, 0x2000] # sorted by (archive, gpu)
|
|
assert log[0]["export"]["place"] == "first" and "export" not in log[1]
|
|
assert "2 textures:" in capsys.readouterr().out
|
|
|
|
monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), carve, str(out), "--limit", "1"])
|
|
T.main()
|
|
assert len(json.loads((out / "export_log.json").read_text(encoding="utf-8"))) == 1
|
|
|
|
|
|
@pytest.mark.parametrize("value", ["0", "-1", "x"])
|
|
def test_main_rejects_a_limit_below_one(tmp_path, monkeypatch, capsys, value):
|
|
# --limit 0 exported every texture (0 read as "no limit") and -1 silently dropped the last one.
|
|
index = tmp_path / "textures_index.json"
|
|
index.write_text("[]", encoding="utf-8")
|
|
out = tmp_path / "out"
|
|
monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), str(tmp_path), str(out), "--limit", value])
|
|
with pytest.raises(SystemExit) as e:
|
|
T.main()
|
|
assert e.value.code == 2
|
|
assert "--limit" in capsys.readouterr().err
|
|
assert not out.exists()
|