diff --git a/README.md b/README.md
index 9bec34b2..d9c886a6 100644
--- a/README.md
+++ b/README.md
@@ -242,7 +242,7 @@ Modding support and fan translations are first-class architectural requirements:
disc0:/PSP_GAME/USRDIR/umd0.cpk, umd1.cpk (original game archives)
```
On PC, `--mods
` maps `ms0:/PSP/P3P` to a host directory.
-- **Texture packs (work in progress, [#23](https://github.com/endercodezz/P3P3DS/issues/23), [#56](https://github.com/endercodezz/P3P3DS/issues/56)):** existing P3P packs are PPSSPP packs (`textures.ini` + PNG). `tools/texpack` (Rust, host only) checks a pack and encodes PNG into New 3DS texture data; the runtime does not load packs yet. From `tools/texpack`: `cargo run --release -- inspect ` and `cargo run --release -- encode --format rgba8|rgb8|rgb565|rgba5551|rgba4 --out ` (the same bytes as devkitPro `tex3ds -r -z none`). The runtime computes PPSSPP-compatible texture keys (`core/include/p3p3ds/ge/texture_replacement.hpp`); to see how much of a pack a PC run would find: `cargo run --release -- keys > keys.txt`, then `p3p_pc_bootstrap ... --texture-keys keys.txt --texture-keys-report keys.csv` (prints `[TEXKEYS]`, the CSV lists every texture key and whether the pack has it). `cargo run --release -- build [--max-size 512] [--format auto|rgba8|...]` converts a pack into the New 3DS pack format (`index.bin` + `textures.bin`, documented in `tools/texpack/src/build.rs`): images downscaled to at most `--max-size` texels per side, RGB565 / RGBA5551 / RGBA4 chosen from the alpha channel.
+- **Texture packs (work in progress, [#23](https://github.com/endercodezz/P3P3DS/issues/23), [#56](https://github.com/endercodezz/P3P3DS/issues/56)):** existing P3P packs are PPSSPP packs (`textures.ini` + PNG). `tools/texpack` (Rust, host only) checks a pack and encodes PNG into New 3DS texture data; the runtime does not load packs yet. From `tools/texpack`: `cargo run --release -- inspect ` and `cargo run --release -- encode --format rgba8|rgb8|rgb565|rgba5551|rgba4 --out ` (the same bytes as devkitPro `tex3ds -r -z none`). The runtime computes PPSSPP-compatible texture keys (`core/include/p3p3ds/ge/texture_replacement.hpp`); to see how much of a pack a PC run would find: `cargo run --release -- keys > keys.txt`, then `p3p_pc_bootstrap ... --texture-keys keys.txt --texture-keys-report keys.csv` (prints `[TEXKEYS]`, the CSV lists every texture key and whether the pack has it). `cargo run --release -- build [--max-size 512] [--format auto|rgba8|...]` converts a pack into the New 3DS pack format (`index.bin` + `textures.bin`, documented in `tools/texpack/src/build.rs`): images downscaled to at most `--max-size` texels per side, RGB565 / RGBA5551 / RGBA4 chosen from the alpha channel. Using a converted pack: copy `index.bin` and `textures.bin` to `sdmc:/p3p3ds/textures/` on the New 3DS (the bottom-screen report's `texpack:` line shows the texture count, replaced uploads, KiB and the milliseconds spent reading them), or run the PC runner with `--texture-pack `.
- **Translation & Mod Support (Future Goal):** The architecture aims to support community translations (such as Russian, Spanish, German, French) and mods via VFS redirection. Note that translations are not guaranteed to be drop-in asset-only packages: individual localizations may require custom font sheets, character encoding tables, `.bmd`/`.bf` script handling, or runtime executable hooks (such as glyph-spacing/kerning adjustments).
---
diff --git a/cmake/p3p3ds_sources.cmake b/cmake/p3p3ds_sources.cmake
index db2752ee..d72b0bf8 100644
--- a/cmake/p3p3ds_sources.cmake
+++ b/cmake/p3p3ds_sources.cmake
@@ -17,6 +17,7 @@ set(P3P3DS_CORE_SOURCES
core/src/ge/async_renderer.cpp
core/src/ge/geometry.cpp
core/src/ge/software_renderer.cpp
+ core/src/ge/texture_pack.cpp
core/src/ge/texture_replacement.cpp
core/src/ge/xxhash.cpp
core/src/hle/sysmem.cpp
diff --git a/core/include/p3p3ds/ge/renderer.hpp b/core/include/p3p3ds/ge/renderer.hpp
index b7be54e6..83dcfbae 100644
--- a/core/include/p3p3ds/ge/renderer.hpp
+++ b/core/include/p3p3ds/ge/renderer.hpp
@@ -8,6 +8,7 @@
// PPSSPP GPU/ge_constants.h was a behavioural cross-check only.
#include
#include
+#include
#include
namespace psprecomp { class GuestMemory; }
@@ -66,15 +67,28 @@ struct VertexLayout {
};
[[nodiscard]] VertexLayout vertex_layout(std::uint32_t vtype);
+class TexturePack;
+
+struct ReplacementStats {
+ std::uint64_t textured_draws{}, replaced_draws{}, loaded{}, read_errors{};
+};
+
class SoftwareRenderer final : public GeRenderer {
public:
+ SoftwareRenderer();
+ ~SoftwareRenderer() override;
void draw(psprecomp::GuestMemory &memory, const GeRegisters ®s, Prim prim, std::uint32_t count,
std::uint32_t vertex_address, std::uint32_t index_address) override;
void transfer(psprecomp::GuestMemory &memory, const GeRegisters ®s) override;
[[nodiscard]] const DrawStats &stats() const override { return stats_; }
+ // Texture replacement from a New 3DS pack (texture_pack.hpp); nullptr turns it off.
+ void set_texture_pack(std::shared_ptr pack);
+ [[nodiscard]] ReplacementStats replacement_stats() const;
private:
+ struct Replacements;
DrawStats stats_;
+ std::unique_ptr replacements_;
};
// 24-bit GE float argument -> float.
diff --git a/core/include/p3p3ds/ge/texture_pack.hpp b/core/include/p3p3ds/ge/texture_pack.hpp
new file mode 100644
index 00000000..777c4b4b
--- /dev/null
+++ b/core/include/p3p3ds/ge/texture_pack.hpp
@@ -0,0 +1,74 @@
+#pragma once
+// New 3DS texture pack written by `p3p-texpack build` (tools/texpack/src/build.rs
+// documents the format): index.bin (entries sorted by PPSSPP-compatible key)
+// and textures.bin (PICA200 tiled data, rows bottom-up). The index is read
+// once; texture data is read on demand.
+#include "p3p3ds/ge/texture_replacement.hpp"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace p3p3ds::ge {
+
+struct PackEntry {
+ ReplacementKey key;
+ std::uint32_t offset{}, size{};
+ std::uint16_t width{}, height{}; // 0 x 0: keep the original texture
+ std::uint8_t format{}; // citro3d GPU_TEXCOLOR (0 RGBA8, 1 RGB8, 2 RGBA5551, 3 RGB565, 4 RGBA4)
+};
+
+class TexturePack {
+public:
+ // nullptr with `error` set when the directory has no valid pack.
+ static std::unique_ptr open(const std::filesystem::path &dir, std::string &error);
+ ~TexturePack();
+ TexturePack(const TexturePack &) = delete;
+ TexturePack &operator=(const TexturePack &) = delete;
+
+ [[nodiscard]] bool ignore_address() const noexcept { return ignore_address_; }
+ [[nodiscard]] std::size_t size() const noexcept { return entries_.size(); }
+ // The entry PPSSPP's lookup order finds for `key` (find_replacement), or nullptr.
+ [[nodiscard]] const PackEntry *find(const ReplacementKey &key) const;
+ // Texture data of an entry with a size; false on a read error.
+ bool read(const PackEntry &entry, std::vector &out) const;
+ // The same into `out` (entry.size bytes, e.g. a C3D_Tex's data).
+ bool read_into(const PackEntry &entry, void *out) const;
+
+private:
+ TexturePack() = default;
+ [[nodiscard]] const PackEntry *exact(const ReplacementKey &key) const;
+ std::vector entries_;
+ bool ignore_address_{};
+ std::FILE *data_{};
+};
+
+// The replacement for the texture a draw binds: keeps the CLUT bytes and the
+// per-texture maxSeenV PPSSPP keys depend on (texture_replacement.hpp).
+// Used by the PC reference renderer and the New 3DS renderer.
+class TextureReplacer {
+public:
+ explicit TextureReplacer(std::shared_ptr pack) : pack_(std::move(pack)) {}
+ // nullptr when the pack has no replacement (or says "keep the original").
+ // `through` / `max_v`: the draw's mode and largest V texel (through_max_v).
+ const PackEntry *find(psprecomp::GuestMemory &memory, const GeRegisters ®s, bool through, std::uint16_t max_v);
+ [[nodiscard]] const TexturePack &pack() const noexcept { return *pack_; }
+
+private:
+ std::shared_ptr pack_;
+ TextureKeys keys_;
+ PpssppClut clut_;
+ std::uint64_t clut_seen_{};
+};
+
+// Largest V texel coordinate of a through-mode draw's vertices (0 otherwise).
+[[nodiscard]] std::uint16_t through_max_v(psprecomp::GuestMemory &memory, const GeRegisters ®s, std::uint32_t count,
+ std::uint32_t vertex_address, std::uint32_t index_address);
+
+// Texture data of `entry` -> RGBA texels (r in the low byte), image row 0 first.
+void decode_pack_texture(const PackEntry &entry, const std::vector &data, std::vector &out);
+
+} // namespace p3p3ds::ge
diff --git a/core/include/p3p3ds/ge/texture_replacement.hpp b/core/include/p3p3ds/ge/texture_replacement.hpp
index cd6bc9d5..ad2538ed 100644
--- a/core/include/p3p3ds/ge/texture_replacement.hpp
+++ b/core/include/p3p3ds/ge/texture_replacement.hpp
@@ -63,6 +63,8 @@ struct PpssppClut {
[[nodiscard]] std::uint32_t replacement_data_hash(const psprecomp::GuestMemory &memory, const GeRegisters ®s, std::uint16_t max_seen_v);
// PPSSPP's lookup order with fallbacks to keys with zeroed parts.
+[[nodiscard]] std::optional find_replacement(const std::function &contains, ReplacementKey key,
+ bool ignore_address);
[[nodiscard]] std::optional find_replacement(const ReplacementKeySet &pack, ReplacementKey key, bool ignore_address);
// Per-texture state PPSSPP keeps between draws (maxSeenV of 512-tall textures).
diff --git a/core/src/ge/software_renderer.cpp b/core/src/ge/software_renderer.cpp
index 165ca9f8..e1bb01fa 100644
--- a/core/src/ge/software_renderer.cpp
+++ b/core/src/ge/software_renderer.cpp
@@ -4,12 +4,15 @@
// (primitives with any vertex behind the eye are dropped, no near clipping).
#include "p3p3ds/ge/renderer.hpp"
#include "p3p3ds/ge/geometry.hpp"
+#include "p3p3ds/ge/texture_pack.hpp"
+#include "p3p3ds/ge/texture_replacement.hpp"
#include "psprecomp/guest_memory.hpp"
#include
#include
#include
+#include
namespace p3p3ds::ge {
namespace {
@@ -23,9 +26,17 @@ std::uint32_t pack(const std::array &c, std::uint32_t format) {
}
}
+// A replacement image covering the whole PSP texture (sampled with the
+// PSP texture's normalised coordinates).
+struct ReplacementImage {
+ std::uint32_t width{}, height{};
+ std::vector rgba; // r in the low byte, row 0 first
+};
+
struct Context {
psprecomp::GuestMemory &memory;
const GeRegisters &g;
+ const ReplacementImage *replacement{};
std::uint32_t r(std::uint32_t i) const { return g.reg[i] & 0xFFFFFFu; }
bool enabled(std::uint32_t i) const { return (g.reg[i] & 1u) != 0u; }
};
@@ -42,6 +53,14 @@ std::array sample(const Context &c, const Texture &t, float u,
if (clamp) return std::clamp(i, 0, static_cast(size) - 1);
return static_cast(static_cast(i) & (size - 1u));
};
+ if (const ReplacementImage *r = c.replacement) {
+ const float su = u * static_cast(r->width) / static_cast(t.width);
+ const float sv = v * static_cast(r->height) / static_cast(t.height);
+ const std::uint32_t texel = r->rgba[static_cast(coord(sv, r->height, (wrap >> 8) & 1u)) * r->width +
+ static_cast(coord(su, r->width, wrap & 1u))];
+ return {static_cast(texel), static_cast(texel >> 8), static_cast(texel >> 16),
+ static_cast(texel >> 24)};
+ }
return fetch_texel(c.memory, c.g, t, coord(u, t.width, wrap & 1u), coord(v, t.height, (wrap >> 8) & 1u));
}
@@ -205,6 +224,49 @@ VertexLayout vertex_layout(std::uint32_t vtype) {
return l;
}
+struct SoftwareRenderer::Replacements {
+ explicit Replacements(std::shared_ptr pack) : replacer(std::move(pack)) {}
+ TextureReplacer replacer;
+ // Pack entry -> decoded image (nullptr: read error).
+ std::unordered_map> images;
+ ReplacementStats stats;
+
+ const ReplacementImage *lookup(psprecomp::GuestMemory &memory, const GeRegisters ®s, bool through, std::uint16_t max_v) {
+ ++stats.textured_draws;
+ const PackEntry *entry = replacer.find(memory, regs, through, max_v);
+ if (!entry) return nullptr;
+ auto [it, inserted] = images.try_emplace(entry);
+ if (inserted) {
+ std::vector data;
+ if (replacer.pack().read(*entry, data)) {
+ auto image = std::make_shared();
+ image->width = entry->width;
+ image->height = entry->height;
+ decode_pack_texture(*entry, data, image->rgba);
+ it->second = std::move(image);
+ ++stats.loaded;
+ } else {
+ ++stats.read_errors;
+ }
+ }
+ if (it->second) ++stats.replaced_draws;
+ return it->second.get();
+ }
+};
+
+SoftwareRenderer::SoftwareRenderer() = default;
+SoftwareRenderer::~SoftwareRenderer() = default;
+
+void SoftwareRenderer::set_texture_pack(std::shared_ptr pack) {
+ if (!pack) {
+ replacements_.reset();
+ return;
+ }
+ replacements_ = std::make_unique(std::move(pack));
+}
+
+ReplacementStats SoftwareRenderer::replacement_stats() const { return replacements_ ? replacements_->stats : ReplacementStats{}; }
+
void SoftwareRenderer::draw(psprecomp::GuestMemory &memory, const GeRegisters ®s, Prim prim, std::uint32_t count,
std::uint32_t vertex_address, std::uint32_t index_address) {
Context c{memory, regs};
@@ -232,6 +294,13 @@ void SoftwareRenderer::draw(psprecomp::GuestMemory &memory, const GeRegisters &r
const bool flat = (c.r(0x50) & 1u) == 0u;
if ((c.r(0xD3) & 1u) != 0u) ++stats_.clears;
const Texture *tex = textured ? &texture : nullptr;
+ if (textured && replacements_) {
+ // Largest V of the draw (texels in through mode) feeds PPSSPP's maxSeenV.
+ std::uint16_t max_v = 0;
+ if (layout.through)
+ for (const auto &v : vertices) max_v = std::max(max_v, static_cast(std::clamp(v.v, 0.0f, 65535.0f)));
+ c.replacement = replacements_->lookup(memory, regs, layout.through, max_v);
+ }
auto sprite = [&](const Vertex &a, const Vertex &b) {
++stats_.sprites;
diff --git a/core/src/ge/texture_pack.cpp b/core/src/ge/texture_pack.cpp
new file mode 100644
index 00000000..f27375fe
--- /dev/null
+++ b/core/src/ge/texture_pack.cpp
@@ -0,0 +1,171 @@
+// See texture_pack.hpp.
+#include "p3p3ds/ge/texture_pack.hpp"
+#include "p3p3ds/ge/geometry.hpp"
+
+#include
+#include
+#include
+#include
+
+namespace p3p3ds::ge {
+namespace {
+
+constexpr char kMagic[8] = {'P', '3', 'T', 'X', 'P', 'A', 'C', 'K'};
+constexpr std::uint32_t kVersion = 1;
+constexpr std::size_t kHeaderSize = 24, kEntrySize = 32;
+
+std::uint16_t le16(const std::uint8_t *p) { return static_cast(p[0] | p[1] << 8); }
+std::uint32_t le32(const std::uint8_t *p) { return static_cast(le16(p)) | static_cast(le16(p + 2)) << 16; }
+std::uint64_t le64(const std::uint8_t *p) { return static_cast(le32(p)) | static_cast(le32(p + 4)) << 32; }
+
+bool key_less(const PackEntry &e, const ReplacementKey &k) {
+ return e.key.cachekey < k.cachekey || (e.key.cachekey == k.cachekey && e.key.hash < k.hash);
+}
+
+std::uint32_t bytes_per_texel(std::uint8_t format) {
+ switch (format) {
+ case 0: return 4;
+ case 1: return 3;
+ case 2: case 3: case 4: return 2;
+ default: return 0;
+ }
+}
+
+// Same tiling as platform/3ds/gpu_renderer.cpp tiled_index.
+std::uint32_t tiled_index(std::uint32_t x, std::uint32_t y, std::uint32_t w) {
+ const std::uint32_t m = (x & 1u) | ((y & 1u) << 1) | ((x & 2u) << 1) | ((y & 2u) << 2) | ((x & 4u) << 2) | ((y & 4u) << 3);
+ return ((y >> 3) * (w >> 3) + (x >> 3)) * 64u + m;
+}
+
+} // namespace
+
+std::unique_ptr TexturePack::open(const std::filesystem::path &dir, std::string &error) {
+ std::ifstream in(dir / "index.bin", std::ios::binary);
+ if (!in) {
+ error = "cannot open " + (dir / "index.bin").string();
+ return nullptr;
+ }
+ const std::vector index((std::istreambuf_iterator(in)), std::istreambuf_iterator());
+ if (index.size() < kHeaderSize || std::memcmp(index.data(), kMagic, 8) != 0) {
+ error = "index.bin is not a P3P3DS texture pack";
+ return nullptr;
+ }
+ if (le32(&index[8]) != kVersion) {
+ error = "unsupported texture pack version " + std::to_string(le32(&index[8]));
+ return nullptr;
+ }
+ const std::uint32_t count = le32(&index[16]);
+ if (index.size() != kHeaderSize + static_cast(count) * kEntrySize) {
+ error = "index.bin size does not match its entry count";
+ return nullptr;
+ }
+ std::unique_ptr pack(new TexturePack());
+ pack->ignore_address_ = (le32(&index[12]) & 1u) != 0u;
+ pack->entries_.reserve(count);
+ for (std::uint32_t i = 0; i < count; ++i) {
+ const std::uint8_t *p = &index[kHeaderSize + i * kEntrySize];
+ PackEntry e;
+ e.key = {le64(p), le32(p + 8)};
+ e.offset = le32(p + 12);
+ e.size = le32(p + 16);
+ e.width = le16(p + 20);
+ e.height = le16(p + 22);
+ e.format = p[24];
+ if (e.width != 0) {
+ const bool pow2 = (e.width & (e.width - 1u)) == 0u && (e.height & (e.height - 1u)) == 0u;
+ if (!pow2 || e.width < 8u || e.height < 8u || e.width > 1024u || e.height > 1024u || bytes_per_texel(e.format) == 0 ||
+ e.size != static_cast(e.width) * e.height * bytes_per_texel(e.format)) {
+ error = "invalid entry " + std::to_string(i) + " in index.bin";
+ return nullptr;
+ }
+ }
+ if (!pack->entries_.empty() && !key_less(pack->entries_.back(), e.key)) {
+ error = "index.bin entries are not sorted";
+ return nullptr;
+ }
+ pack->entries_.push_back(e);
+ }
+ pack->data_ = std::fopen((dir / "textures.bin").string().c_str(), "rb");
+ if (!pack->data_) {
+ error = "cannot open " + (dir / "textures.bin").string();
+ return nullptr;
+ }
+ return pack;
+}
+
+TexturePack::~TexturePack() {
+ if (data_) std::fclose(data_);
+}
+
+const PackEntry *TexturePack::exact(const ReplacementKey &key) const {
+ const auto it = std::lower_bound(entries_.begin(), entries_.end(), key, key_less);
+ return it != entries_.end() && it->key == key ? &*it : nullptr;
+}
+
+const PackEntry *TexturePack::find(const ReplacementKey &key) const {
+ const auto found = find_replacement([this](const ReplacementKey &k) { return exact(k) != nullptr; }, key, ignore_address_);
+ return found ? exact(*found) : nullptr;
+}
+
+bool TexturePack::read(const PackEntry &entry, std::vector &out) const {
+ if (entry.width == 0) return false;
+ out.resize(entry.size);
+ return std::fseek(data_, static_cast(entry.offset), SEEK_SET) == 0 && std::fread(out.data(), 1, out.size(), data_) == out.size();
+}
+
+bool TexturePack::read_into(const PackEntry &entry, void *out) const {
+ if (entry.width == 0) return false;
+ return std::fseek(data_, static_cast(entry.offset), SEEK_SET) == 0 && std::fread(out, 1, entry.size, data_) == entry.size;
+}
+
+const PackEntry *TextureReplacer::find(psprecomp::GuestMemory &memory, const GeRegisters ®s, bool through, std::uint16_t max_v) {
+ // The CLUT cache changes only on LOADCLUT, which updates clut_hash.
+ if (regs.clut_hash != clut_seen_) {
+ clut_seen_ = regs.clut_hash;
+ clut_.load(reinterpret_cast(regs.clut.data()), regs.clut_words * 4u);
+ }
+ const PackEntry *entry = pack_->find(keys_.key(memory, regs, clut_, through, max_v));
+ return entry && entry->width != 0 ? entry : nullptr;
+}
+
+std::uint16_t through_max_v(psprecomp::GuestMemory &memory, const GeRegisters ®s, std::uint32_t count, std::uint32_t vertex_address,
+ std::uint32_t index_address) {
+ const VertexLayout layout = vertex_layout(regs.reg[0x12] & 0xFFFFFFu);
+ if (!layout.through) return 0;
+ std::uint16_t max_v = 0;
+ ModelVertex v;
+ for (std::uint32_t i = 0; i < count; ++i)
+ if (decode_model_vertex(memory, regs, layout, vertex_address, vertex_index(memory, layout, index_address, i), v))
+ max_v = std::max(max_v, static_cast(std::clamp(v.uv[1], 0.0f, 65535.0f)));
+ return max_v;
+}
+
+void decode_pack_texture(const PackEntry &entry, const std::vector &data, std::vector &out) {
+ const std::uint32_t w = entry.width, h = entry.height, bpp = bytes_per_texel(entry.format);
+ out.assign(static_cast(w) * h, 0u);
+ if (bpp == 0 || data.size() < static_cast(w) * h * bpp) return;
+ auto expand = [](std::uint32_t v, int bits) { return (v << (8 - bits)) | (v >> (2 * bits - 8 > 0 ? 2 * bits - 8 : 0)); };
+ for (std::uint32_t y = 0; y < h; ++y) {
+ for (std::uint32_t x = 0; x < w; ++x) {
+ const std::uint8_t *t = &data[static_cast(tiled_index(x, h - 1u - y, w)) * bpp];
+ std::uint32_t r, g, b, a = 255;
+ switch (entry.format) {
+ case 0: a = t[0]; b = t[1]; g = t[2]; r = t[3]; break;
+ case 1: b = t[0]; g = t[1]; r = t[2]; break;
+ default: {
+ const std::uint32_t v = le16(t);
+ if (entry.format == 3) {
+ r = expand(v >> 11, 5); g = expand((v >> 5) & 63u, 6); b = expand(v & 31u, 5);
+ } else if (entry.format == 2) {
+ r = expand(v >> 11, 5); g = expand((v >> 6) & 31u, 5); b = expand((v >> 1) & 31u, 5); a = (v & 1u) ? 255u : 0u;
+ } else {
+ r = (v >> 12) * 17u; g = ((v >> 8) & 15u) * 17u; b = ((v >> 4) & 15u) * 17u; a = (v & 15u) * 17u;
+ }
+ }
+ }
+ out[static_cast(y) * w + x] = r | g << 8 | b << 16 | a << 24;
+ }
+ }
+}
+
+} // namespace p3p3ds::ge
diff --git a/core/src/ge/texture_replacement.cpp b/core/src/ge/texture_replacement.cpp
index 4f103d1e..90ecfad0 100644
--- a/core/src/ge/texture_replacement.cpp
+++ b/core/src/ge/texture_replacement.cpp
@@ -108,6 +108,11 @@ std::uint32_t replacement_data_hash(const psprecomp::GuestMemory &memory, const
}
std::optional find_replacement(const ReplacementKeySet &pack, ReplacementKey key, bool ignore_address) {
+ return find_replacement([&pack](const ReplacementKey &k) { return pack.contains(k); }, key, ignore_address);
+}
+
+std::optional find_replacement(const std::function &contains, ReplacementKey key,
+ bool ignore_address) {
if (ignore_address) key.cachekey &= 0xFFFFFFFFull;
const std::uint64_t ck = key.cachekey;
const std::uint32_t hash = key.hash;
@@ -124,7 +129,7 @@ std::optional find_replacement(const ReplacementKeySet &pack, Re
const bool needs_address[] = {false, false, true, false, true, true, false};
for (std::size_t i = 0; i < std::size(tries); ++i) {
if (needs_address[i] && ignore_address) continue;
- if (pack.contains(tries[i])) return tries[i];
+ if (contains(tries[i])) return tries[i];
}
return std::nullopt;
}
diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md
index dfc188cc..baefbb7a 100644
--- a/docs/CURRENT_STATE.md
+++ b/docs/CURRENT_STATE.md
@@ -2,6 +2,13 @@
This is the current source of truth, newest entries first. Evidence concerns ULUS-10512; each section says whether it was measured on the PC runner, in Azahar or on a real New 3DS.
+## Texture packs replace textures on the PC; 3DS path built, untested (#23, 2026-11-05)
+
+- `core/src/ge/texture_pack.cpp`: `TexturePack` reads the New 3DS pack (`index.bin` checked: magic, version, sizes, sort order; texture data read on demand) and finds an entry in PPSSPP's lookup order; `TextureReplacer` keeps the CLUT bytes and maxSeenV state and is shared by both renderers. `SoftwareRenderer::set_texture_pack` samples the replacement with the PSP texture's normalised coordinates; PC runner `--texture-pack ` prints `[TEXPACK]`. New 3DS: `GpuRenderer::bind_texture` reads a replacement straight into a `C3D_Tex` of the pack's size and format when it uploads a texture (textures narrower than 8 texels keep the original); `platform/3ds/main.cpp` opens `sdmc:/p3p3ds/textures`, the report line `texpack:` shows count, replaced uploads, KiB and read time.
+- [VERIFIED] PC, Community Expansion 3x pack converted at max 512: 20M title replay 10,288 of 10,341 textured draws replaced (7 textures loaded, 0 read errors), first-battle route 6,910,728 of 8,713,539 (0 read errors), the same draws the key probe matched. Guest execution unchanged: same stop PC, same event types and counts; only `frame` event fields differ (frame hashes). Frame dumps show the pack's art in place and aligned (title logo, Dark Hour scenes, Yukari portrait, font, hospital background): comparisons in `.tmp/texpacks/cmp_*.png`, `.tmp/texpacks/compare_title.png`.
+- [VERIFIED] `test_texture_replacement`: pack index parsing, lookup with the CLUT-only fallback, keep-original entries, RGBA8/RGB565 decode with bottom-up rows, rejection of bad magic, unsorted entries, wrong data size and non-power-of-two sizes. CTest 28/28; devkitARM build of `p3p3ds.3dsx` passes.
+- [UNVERIFIED] The New 3DS path (Azahar or hardware): picture, memory use and SD read stalls on the render thread. Test files: `.tmp/texpacks/for_3ds/` (`p3p3ds.3dsx`, `p3p3ds/textures/` = the pack at max 256, 302 MB).
+
## New 3DS texture pack format: `p3p-texpack build` (#56, 2026-11-05)
- [VERIFIED] In the Community Expansion 3x pack every replacement matched on the battle route is a uniform multiple of the full PSP texture (192 checked: 166 at 3x, 23 at 2x, 3 at 4.5x; same aspect ratio, not cropped to maxSeenV). So a replacement can be stored at any power-of-two size with that aspect ratio and sampled with the PSP texture's normalised coordinates.
diff --git a/platform/3ds/gpu_renderer.cpp b/platform/3ds/gpu_renderer.cpp
index 4d21fa78..f196f7d1 100644
--- a/platform/3ds/gpu_renderer.cpp
+++ b/platform/3ds/gpu_renderer.cpp
@@ -450,7 +450,8 @@ void GpuRenderer::evict_textures(std::uint32_t needed) {
}
}
-const C3D_Tex *GpuRenderer::bind_texture(psprecomp::GuestMemory &memory, const ge::GeRegisters ®s, float &scale_u, float &scale_v) {
+const C3D_Tex *GpuRenderer::bind_texture(psprecomp::GuestMemory &memory, const ge::GeRegisters ®s, float &scale_u, float &scale_v,
+ bool through, std::uint16_t max_v) {
const auto info = ge::texture_info(regs);
// Render-to-texture: a texture that starts at a GPU-drawn framebuffer.
const std::uint32_t canonical = psprecomp::GuestMemory::canonical(info.address);
@@ -489,26 +490,53 @@ const C3D_Tex *GpuRenderer::bind_texture(psprecomp::GuestMemory &memory, const g
else C3D_TexDelete(&it->second.tex);
textures_.erase(it);
}
- const auto fmt = pica_format(info);
const std::uint32_t tw = std::max(info.width, 8u), th = std::max(info.height, 8u);
- const std::uint32_t bytes = tw * th * (fmt == GPU_RGBA8 ? 4u : 2u);
- evict_textures(bytes);
CachedTexture entry;
- if (!C3D_TexInit(&entry.tex, static_cast(tw), static_cast(th), fmt)) {
- evict_textures(kTextureBudget); // free everything not used by this frame and retry
- if (!C3D_TexInit(&entry.tex, static_cast(tw), static_cast(th), fmt)) return nullptr;
+ std::uint32_t bytes = 0;
+ // Texture pack (#23): a replacement covers the whole PSP texture and is
+ // sampled with the same normalised coordinates (scale from tw/th below).
+ // Textures narrower than 8 texels are repeated to 8 here, so they keep the original.
+ if (replacer_ && info.width >= 8u && info.height >= 8u) {
+ const u64 start = svcGetSystemTick();
+ if (const ge::PackEntry *rep = replacer_->find(memory, regs, through, max_v)) {
+ evict_textures(rep->size);
+ const auto rfmt = static_cast(rep->format);
+ bool ok = C3D_TexInit(&entry.tex, rep->width, rep->height, rfmt);
+ if (!ok) {
+ evict_textures(kTextureBudget);
+ ok = C3D_TexInit(&entry.tex, rep->width, rep->height, rfmt);
+ }
+ if (ok && replacer_->pack().read_into(*rep, entry.tex.data)) {
+ C3D_TexFlush(&entry.tex);
+ bytes = rep->size;
+ ++gpu_stats_.replaced_uploads;
+ gpu_stats_.replaced_bytes += bytes;
+ } else if (ok) {
+ C3D_TexDelete(&entry.tex);
+ }
+ }
+ gpu_stats_.replace_ticks += svcGetSystemTick() - start;
}
- const u64 upload_start = svcGetSystemTick();
- ge::decode_texture(memory, regs, info, rgba_);
- for (std::uint32_t y = 0; y < th; ++y)
- for (std::uint32_t x = 0; x < tw; ++x) {
- const std::uint32_t c = rgba_[static_cast(y % info.height) * info.width + (x % info.width)];
- const std::uint32_t at = tiled_index(x, tiled_row(y, th), tw);
- if (fmt == GPU_RGBA8) static_cast(entry.tex.data)[at] = to_rgba8(c);
- else static_cast(entry.tex.data)[at] = to_16(c, fmt);
+ if (bytes == 0) {
+ const auto fmt = pica_format(info);
+ bytes = tw * th * (fmt == GPU_RGBA8 ? 4u : 2u);
+ evict_textures(bytes);
+ if (!C3D_TexInit(&entry.tex, static_cast(tw), static_cast(th), fmt)) {
+ evict_textures(kTextureBudget); // free everything not used by this frame and retry
+ if (!C3D_TexInit(&entry.tex, static_cast(tw), static_cast(th), fmt)) return nullptr;
}
- C3D_TexFlush(&entry.tex);
- gpu_stats_.upload_ticks += svcGetSystemTick() - upload_start;
+ const u64 upload_start = svcGetSystemTick();
+ ge::decode_texture(memory, regs, info, rgba_);
+ for (std::uint32_t y = 0; y < th; ++y)
+ for (std::uint32_t x = 0; x < tw; ++x) {
+ const std::uint32_t c = rgba_[static_cast(y % info.height) * info.width + (x % info.width)];
+ const std::uint32_t at = tiled_index(x, tiled_row(y, th), tw);
+ if (fmt == GPU_RGBA8) static_cast(entry.tex.data)[at] = to_rgba8(c);
+ else static_cast(entry.tex.data)[at] = to_16(c, fmt);
+ }
+ C3D_TexFlush(&entry.tex);
+ gpu_stats_.upload_ticks += svcGetSystemTick() - upload_start;
+ }
entry.hash = hash;
entry.width = tw;
entry.height = th;
@@ -726,7 +754,11 @@ void GpuRenderer::draw(psprecomp::GuestMemory &memory, const ge::GeRegisters &re
const bool textured = ge::draw_is_textured(regs, layout);
float su = 1.0f, sv = 1.0f;
- C3D_Tex *tex = textured ? const_cast(bind_texture(memory, regs, su, sv)) : nullptr;
+ // maxSeenV of a 512-tall through-mode texture keys a pack replacement (#23).
+ std::uint16_t max_v = 0;
+ if (textured && replacer_ && layout.through && ((r24(regs, 0xB8) >> 8) & 0xFu) == 9u)
+ max_v = ge::through_max_v(memory, regs, count, vertex_address, index_address);
+ C3D_Tex *tex = textured ? const_cast(bind_texture(memory, regs, su, sv, layout.through, max_v)) : nullptr;
const bool sprites = prim == ge::Prim::Sprites;
if (trace_ && (layout.through || clear_mode || sprites)) {
const auto ti = ge::texture_info(regs);
diff --git a/platform/3ds/gpu_renderer.hpp b/platform/3ds/gpu_renderer.hpp
index eeb59186..f7a99216 100644
--- a/platform/3ds/gpu_renderer.hpp
+++ b/platform/3ds/gpu_renderer.hpp
@@ -16,6 +16,7 @@
#include "p3p3ds/ge/geometry.hpp"
#include "p3p3ds/ge/model_batch.hpp"
#include "p3p3ds/ge/renderer.hpp"
+#include "p3p3ds/ge/texture_pack.hpp"
#include "p3p3ds/ge/vertex_cache.hpp"
#include "p3p3ds/hle/display.hpp"
@@ -25,6 +26,7 @@
#include
#include
#include
+#include
#include
#include
@@ -52,6 +54,9 @@ struct GpuStats {
std::uint64_t fast_draws{}; // model draws that joined a batch on the fast path
std::uint64_t model_runs{}; // vertex blocks filled for runs of contiguous model draws
std::uint64_t run_draws{}; // model draws that went into such a run
+ // Texture pack (#23): uploads served from the pack, their bytes and the
+ // CPU time spent finding and reading them (SD card reads included).
+ std::uint64_t replaced_uploads{}, replaced_bytes{}, replace_ticks{};
std::uint32_t textures{}, targets{};
};
@@ -77,6 +82,10 @@ class GpuRenderer final : public ge::GeRenderer {
bool read_top_screen(std::vector &rgb);
[[nodiscard]] const GpuStats &gpu_stats() const { return gpu_stats_; }
+ // Texture replacement from a New 3DS pack (sdmc:/p3p3ds/textures); nullptr: off.
+ void set_texture_pack(std::shared_ptr pack) {
+ replacer_ = pack ? std::make_unique(std::move(pack)) : nullptr;
+ }
[[nodiscard]] const ge::VertexCacheStats &vertex_cache_stats() const { return vertex_cache_.stats(); }
[[nodiscard]] bool vertex_cache_enabled() const { return vertex_cache_enabled_; }
// The last presented picture came from guest memory (CPU-written, e.g. a movie frame).
@@ -123,7 +132,8 @@ class GpuRenderer final : public ge::GeRenderer {
void upload_guest_framebuffer(psprecomp::GuestMemory &memory, std::uint32_t address, std::uint32_t stride,
std::uint32_t format);
void blit(C3D_Tex &source, float src_w, float src_h, bool to_screen);
- const C3D_Tex *bind_texture(psprecomp::GuestMemory &memory, const ge::GeRegisters ®s, float &scale_u, float &scale_v);
+ const C3D_Tex *bind_texture(psprecomp::GuestMemory &memory, const ge::GeRegisters ®s, float &scale_u, float &scale_v,
+ bool through, std::uint16_t max_v);
void apply_fragment_state(const ge::GeRegisters ®s, bool textured, bool clear_mode, bool no_cull);
Vertex *alloc_vertices(std::uint32_t count, std::uint32_t &first);
void *alloc_linear(std::uint32_t bytes, std::uint32_t align);
@@ -236,6 +246,7 @@ class GpuRenderer final : public ge::GeRenderer {
std::uint32_t trace_left_{};
std::vector screen_;
std::vector rgba_;
+ std::unique_ptr replacer_;
// What fallback_ holds: guest framebuffer address and the target's cpu_seq
// at upload time (re-upload only after new CPU writes).
std::uint32_t fallback_address_{};
diff --git a/platform/3ds/main.cpp b/platform/3ds/main.cpp
index 7dcf6227..b82cdab4 100644
--- a/platform/3ds/main.cpp
+++ b/platform/3ds/main.cpp
@@ -220,6 +220,8 @@ class HidSource final : public p3p3ds::input::InputSource {
};
p3p3ds::n3ds::GpuRenderer *g_gpu = nullptr;
+// Texture pack state for the report: " textures", an error, or empty (no pack).
+std::string g_texture_pack;
// The GE back end on core 2 (nullptr: the renderer runs on the game's thread).
// Everything that touches citro3d goes through it: posted in order, or called
// once the worker is idle.
@@ -421,13 +423,14 @@ void write_bmp(const char *path, const std::vector &rgb, std::uint
std::string gpu_text() {
if (g_gpu == nullptr) return {};
const auto &g = g_gpu->gpu_stats();
- char buf[384];
+ char buf[512];
std::snprintf(buf, sizeof buf,
"gpu : draws %llu tris %llu skip %llu\n"
" tex %lu up %llu hit %llu rtt %llu\n"
" present gpu %llu cpu %llu same %llu\n"
" flush cmd %llu arena %llu w/draw %llu\n"
- "movie : skip %llu rtt %llu merge %lluk>%lluk f%lluk\n",
+ "movie : skip %llu rtt %llu merge %lluk>%lluk f%lluk\n"
+ "texpack: %s up %llu %llu KiB %llu ms\n",
static_cast(g.draws), static_cast(g.triangles),
static_cast(g.skipped_prims), static_cast(g.textures),
static_cast(g.texture_uploads), static_cast(g.texture_hits),
@@ -437,7 +440,9 @@ std::string gpu_text() {
static_cast(g.counted_draws != 0u ? g.command_words / g.counted_draws : 0u),
static_cast(g_skip_presses), static_cast(g.cpu_to_target),
static_cast(g.model_draws / 1000u), static_cast(g.model_batches / 1000u),
- static_cast(g.fast_draws / 1000u));
+ static_cast(g.fast_draws / 1000u), g_texture_pack.empty() ? "off" : g_texture_pack.c_str(),
+ static_cast(g.replaced_uploads), static_cast(g.replaced_bytes / 1024u),
+ static_cast(ticks_to_s(g.replace_ticks) * 1000.0));
const auto &c = g_gpu->vertex_cache_stats();
char vc[192];
std::snprintf(vc, sizeof vc, "vcache : %lu KiB %lu src hit %lluk\n miss %lluk vol %lluk full %lluk\nruns : %lluk draws in %lluk runs\n",
@@ -844,6 +849,17 @@ int main() {
stage = "init gpu";
auto gpu = std::make_unique();
g_gpu = gpu.get();
+ // Texture pack (#23): sdmc:/p3p3ds/textures/{index.bin,textures.bin}, made
+ // from a PPSSPP pack by `p3p-texpack build` (tools/texpack).
+ {
+ std::string error;
+ if (std::shared_ptr pack = p3p3ds::ge::TexturePack::open("sdmc:/p3p3ds/textures", error)) {
+ g_texture_pack = std::to_string(pack->size()) + " textures";
+ gpu->set_texture_pack(std::move(pack));
+ } else if (error.find("cannot open sdmc:/p3p3ds/textures/index.bin") == std::string::npos) {
+ g_texture_pack = error; // a pack is there but unusable
+ }
+ }
// sdmc:/p3p3ds/gpu_trace.txt present: presents and screen-space draws of the
// first 1,200 presents (about 20 s) to sdmc:/p3p3ds/gpu_trace.log.
if (FILE *f = std::fopen("sdmc:/p3p3ds/gpu_trace.txt", "r")) {
diff --git a/platform/pc/main.cpp b/platform/pc/main.cpp
index 1c1b599b..b92e9205 100644
--- a/platform/pc/main.cpp
+++ b/platform/pc/main.cpp
@@ -16,6 +16,7 @@
#include
#include "p3p3ds/ge/async_renderer.hpp"
#include "texture_key_probe.hpp"
+#include "p3p3ds/ge/texture_pack.hpp"
#include "p3p3ds/vram_activity.hpp"
#include
#include
@@ -30,7 +31,7 @@ int main(int argc,char **argv) {
try {
std::filesystem::path elf_path="profiles/p3p/game/eboot.elf", events_path, umd_path, io_trace_path,
ms0_path="out/ms0", mods_path, frames_dir, wav_path, input_path, sample_path, draw_log_path;
- std::string texture_keys_path, texture_keys_report;
+ std::string texture_keys_path, texture_keys_report, texture_pack_path;
std::string savedata_policy="latest";
std::uint64_t frame_every=30, render_from=0, sample_from=0, draw_log_from=0, stop_vblank=0;
std::uint64_t budget=100000;
@@ -63,6 +64,7 @@ int main(int argc,char **argv) {
else if(a=="--draw-log") draw_log_path=value();
else if(a=="--draw-log-from") draw_log_from=std::stoull(value());
else if(a=="--texture-keys") texture_keys_path=value();
+ else if(a=="--texture-pack") texture_pack_path=value();
else if(a=="--texture-keys-report") texture_keys_report=value();
else if(a=="--savedata") savedata_policy=value();
else if(a=="--frame-every") frame_every=std::stoull(value());
@@ -84,6 +86,7 @@ int main(int argc,char **argv) {
<<"--stop-vblank (end the run at that vblank, e.g. the end of a sampled scene)\n"
<<"--ge-thread (GE renderer on a worker thread, drained after every list: must give the same run)\n"
<<"--draw-log --draw-log-from (one line per GE draw of the 2 displayed frames after that frame index)\n"
+ <<"--texture-pack (replace textures from a New 3DS pack: p3p-texpack build)\n"
<<"--texture-keys [--texture-keys-report ] (check textured draws against a pack's keys: p3p-texpack keys)\n"
<<"--savedata latest|cancel| (choice in the save/load list dialogs; default latest)\n";return 0;
} else throw std::runtime_error("unknown option: "+a);
@@ -207,12 +210,26 @@ int main(int argc,char **argv) {
std::size_t{4}<<20,std::move(hooks),true));
}
// --texture-keys: PPSSPP-compatible keys of every textured draw (#23).
+ // --texture-pack: replace textures in the reference renderer (#23).
p3p3ds::pc::TextureKeyProbe *texture_keys=nullptr;
+ p3p3ds::ge::SoftwareRenderer *pack_renderer=nullptr;
+ if((!texture_keys_path.empty() || !texture_pack_path.empty()) && ge_thread)
+ throw std::runtime_error("--texture-keys/--texture-pack do not combine with --ge-thread");
+ auto software=std::make_unique();
+ if(!texture_pack_path.empty()) {
+ std::string error;
+ std::shared_ptr pack=p3p3ds::ge::TexturePack::open(texture_pack_path,error);
+ if(!pack) throw std::runtime_error("--texture-pack: "+error);
+ std::cout<<"[TEXPACK] "<size()<<" entries from "<set_texture_pack(pack);
+ pack_renderer=software.get();
+ }
if(!texture_keys_path.empty()) {
- if(ge_thread) throw std::runtime_error("--texture-keys does not combine with --ge-thread");
- auto probe=std::make_unique(std::make_unique(),texture_keys_path);
+ auto probe=std::make_unique(std::move(software),texture_keys_path);
texture_keys=probe.get();
kernel.ge().set_renderer(std::move(probe));
+ } else if(pack_renderer) {
+ kernel.ge().set_renderer(std::move(software));
}
rt.event_observer=[&] {
if(kernel.ge().skip_rasterization && kernel.threads().vblank_count()>=render_from) kernel.ge().skip_rasterization=false;
@@ -335,6 +352,11 @@ int main(int argc,char **argv) {
rt.event("audio_summary",{{"buffers",mixer.buffers()},{"frames",mixer.frames()},{"nonzero_frames",mixer.nonzero_frames()},
{"peak",mixer.peak()},{"late_frames",mixer.late_frames()},{"clipped",mixer.clipped()}});
if(texture_keys) { std::cout.flush(); texture_keys->report(texture_keys_report); std::fflush(stdout); }
+ if(pack_renderer) {
+ const auto r=pack_renderer->replacement_stats();
+ std::cout<<"[TEXPACK] textured_draws="<
#include
+#include
+#include
#include
using namespace p3p3ds::ge;
@@ -76,6 +79,23 @@ const Vector kVectors[] = {
};
void set_reg(GeRegisters ®s, std::uint32_t op, std::uint32_t value) { regs.reg[op] = value & 0xFFFFFFu; }
+
+void put16(std::vector &v, std::uint32_t x) { v.push_back(static_cast(x)); v.push_back(static_cast(x >> 8)); }
+void put32(std::vector &v, std::uint32_t x) { put16(v, x & 0xFFFFu); put16(v, x >> 16); }
+void put64(std::vector &v, std::uint64_t x) { put32(v, static_cast(x)); put32(v, static_cast(x >> 32)); }
+void write_file(const std::filesystem::path &p, const std::vector &bytes) {
+ std::ofstream(p, std::ios::binary).write(reinterpret_cast(bytes.data()), static_cast(bytes.size()));
+}
+struct EntrySpec { std::uint64_t cachekey; std::uint32_t hash, offset, size; std::uint16_t w, h; std::uint8_t format; };
+std::vector make_index(const std::vector &entries, std::uint32_t flags = 1) {
+ std::vector v = {'P', '3', 'T', 'X', 'P', 'A', 'C', 'K'};
+ put32(v, 1); put32(v, flags); put32(v, static_cast(entries.size())); put32(v, 0);
+ for (const auto &e : entries) {
+ put64(v, e.cachekey); put32(v, e.hash); put32(v, e.offset); put32(v, e.size); put16(v, e.w); put16(v, e.h);
+ v.push_back(e.format); v.push_back(0); put16(v, 0); put32(v, 0);
+ }
+ return v;
+}
} // namespace
int main() {
@@ -167,6 +187,59 @@ int main() {
const auto k2 = keys.key(memory, tex, clut, true, 300);
check(k2.hash == replacement_data_hash(memory, tex, 512), "a taller draw switches to all 512 rows");
+ // New 3DS pack (tools/texpack/src/build.rs format): lookup, read, decode.
+ {
+ const std::filesystem::path dir = "texture_pack_test";
+ std::filesystem::remove_all(dir);
+ std::filesystem::create_directories(dir);
+ // Entry 0: 8x8 RGBA8, texel (x, y) = (x, y, 7, 255), stored rows bottom-up.
+ std::vector data(8 * 8 * 4);
+ for (std::uint32_t y = 0; y < 8; ++y)
+ for (std::uint32_t x = 0; x < 8; ++x) {
+ const std::uint32_t row = 7 - y; // memory row of image row y
+ const std::uint32_t m = (x & 1u) | ((row & 1u) << 1) | ((x & 2u) << 1) | ((row & 2u) << 2) | ((x & 4u) << 2) | ((row & 4u) << 3);
+ std::uint8_t *t = &data[m * 4];
+ t[0] = 255; t[1] = 7; t[2] = static_cast(y); t[3] = static_cast(x);
+ }
+ // Entry 1: 8x8 RGB565, all red (0xF800).
+ std::vector red;
+ for (int i = 0; i < 64; ++i) put16(red, 0xF800u);
+ data.insert(data.end(), red.begin(), red.end());
+ write_file(dir / "textures.bin", data);
+ write_file(dir / "index.bin", make_index({{0x100, 0xAABBCCDD, 0, 256, 8, 8, 0}, {0x200, 0, 256, 128, 8, 8, 3}, {0x300, 0x5, 0, 0, 0, 0, 0}}));
+ std::string error;
+ auto pack = TexturePack::open(dir, error);
+ check(pack != nullptr && pack->size() == 3 && pack->ignore_address(), "open pack");
+ if (pack) {
+ const PackEntry *e = pack->find({0x0900'0000'0000'0100ull, 0xAABBCCDDu}); // address bits ignored
+ check(e && e->width == 8 && e->format == 0, "find exact key");
+ std::vector bytes;
+ std::vector rgba;
+ check(e && pack->read(*e, bytes), "read entry");
+ if (e) decode_pack_texture(*e, bytes, rgba);
+ check(rgba.size() == 64 && rgba[3 * 8 + 5] == (5u | 3u << 8 | 7u << 16 | 255u << 24), "RGBA8 decode, rows bottom-up");
+ const PackEntry *red_entry = pack->find({0x200, 0x12345678u}); // falls back to the CLUT-only key
+ check(red_entry && red_entry->format == 3, "CLUT-only fallback");
+ if (red_entry && pack->read(*red_entry, bytes)) decode_pack_texture(*red_entry, bytes, rgba);
+ check(rgba.size() == 64 && rgba[0] == (255u | 255u << 24), "RGB565 decode");
+ const PackEntry *keep = pack->find({0x300, 0x5});
+ check(keep && keep->width == 0, "keep-original entry");
+ check(!pack->find({0x400, 1}), "unknown key");
+ }
+ pack.reset();
+ write_file(dir / "index.bin", make_index({{0x200, 0, 0, 128, 8, 8, 3}, {0x100, 0, 0, 128, 8, 8, 3}}));
+ check(!TexturePack::open(dir, error) && error.find("sorted") != std::string::npos, "reject unsorted index");
+ write_file(dir / "index.bin", make_index({{0x100, 0, 0, 100, 8, 8, 3}}));
+ check(!TexturePack::open(dir, error), "reject wrong data size");
+ write_file(dir / "index.bin", make_index({{0x100, 0, 0, 12 * 8 * 2, 12, 8, 3}}));
+ check(!TexturePack::open(dir, error), "reject non-power-of-two size");
+ std::vector bad = make_index({});
+ bad[0] = 'X';
+ write_file(dir / "index.bin", bad);
+ check(!TexturePack::open(dir, error), "reject bad magic");
+ std::filesystem::remove_all(dir);
+ }
+
if (failures == 0) std::printf("test_texture_replacement: all checks passed\n");
return failures == 0 ? 0 : 1;
}