Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir>` 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 <pack dir>` and `cargo run --release -- encode <image.png> --format rgba8|rgb8|rgb565|rgba5551|rgba4 --out <file>` (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 <pack dir> > 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).
- **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 <pack dir>` and `cargo run --release -- encode <image.png> --format rgba8|rgb8|rgb565|rgba5551|rgba4 --out <file>` (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 <pack dir> > 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 <pack dir> <out dir> [--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.
- **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).

---
Expand Down
6 changes: 6 additions & 0 deletions docs/CURRENT_STATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

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.

## 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.
- `build` (`tools/texpack/src/build.rs`, format documented there): `index.bin` (magic `P3TXPACK`, version 1, ignoreAddress flag, 32-byte entries sorted by key: data offset/size, width, height, citro3d texture format) + `textures.bin` (PICA200 data, 128-byte aligned, rows bottom-up like the 3DS renderer's uploads, `tiled_row` in `platform/3ds/gpu_renderer.cpp`). Box downscale with premultiplied alpha to at most `--max-size` per side (default 512); RGB565 if opaque, RGBA5551 if alpha is only 0/255, else RGBA4.
- [VERIFIED] The 3x pack converts in 52 s (max 512, 12 threads): 4,580 textures (10 skipped: files missing from the pack), 871,815,168 bytes; RGBA4 2,813, RGB565 1,673, RGBA5551 94. With `--max-size 256`: 301,750,272 bytes, 27 s. The ATLUS logo entry decodes back to the expected image (512x256 RGB565). `cargo test` 14/14 (sizes, box filter, alpha formats, index layout, alignment, row order).
- Next: read the pack in the runtime and replace textures, first in the PC renderer (frame dumps), then on the 3DS (#23).
## Optional BinDiff host CLI in Zig (#59, 2026-11-05)

- [VERIFIED] `tools/bindiff/src/diff.zig::{compare,parseElf,compareElf}` and `src/main.zig::run` implement positional byte ranges/counts and ELF32 little-endian MIPS/PSP PRX header/segment/section comparison, text/JSON output and exit codes 0/1/2. Metadata entries are paired by table index, without relocation normalization or function matching. The runtime and CMake build do not depend on Zig.
Expand Down
238 changes: 238 additions & 0 deletions tools/texpack/src/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
//! `build`: PPSSPP pack -> New 3DS pack (two files in the output directory).
//!
//! index.bin (little endian):
//! 0 "P3TXPACK" magic
//! 8 u32 version = 1
//! 12 u32 flags bit 0: ignoreAddress (keys carry no address)
//! 16 u32 entry count
//! 20 u32 reserved = 0
//! 24 entries, 32 bytes each, sorted by (cachekey, hash):
//! u64 cachekey, u32 hash, u32 data offset in textures.bin,
//! u32 data size, u16 width, u16 height (power of two, 8..1024),
//! u8 format (citro3d GPU_TEXCOLOR: 0 RGBA8, 2 RGBA5551, 3 RGB565, 4 RGBA4),
//! u8 reserved, u16 reserved, u32 reserved
//! An entry with width 0 means "keep the original texture" (an empty or `|`
//! file in textures.ini).
//! textures.bin: PICA200 texture data (pica.rs), each entry 128-byte aligned,
//! rows bottom-up as the P3P3DS 3DS renderer uploads textures: image row y
//! is memory row h - 1 - y (platform/3ds/gpu_renderer.cpp, tiled_row).
//!
//! The replacement covers the whole PSP texture: the renderer samples it with
//! the PSP texture's normalised coordinates, so any power-of-two size with the
//! same aspect ratio works.

use crate::pack::{Key, Pack};
use crate::pica::{self, Format, Image};
use crate::resample;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;

pub const MAGIC: &[u8; 8] = b"P3TXPACK";
pub const VERSION: u32 = 1;
pub const ENTRY_SIZE: usize = 32;
const ALIGN: usize = 128;

pub struct Options {
pub max_size: usize,
/// None: pick per texture from its alpha channel.
pub format: Option<Format>,
}

/// citro3d GPU_TEXCOLOR value of a format.
pub fn gpu_format(format: Format) -> u8 {
match format {
Format::Rgba8 => 0,
Format::Rgb8 => 1,
Format::Rgba5551 => 2,
Format::Rgb565 => 3,
Format::Rgba4 => 4,
}
}

/// Opaque -> RGB565, alpha only 0/255 -> RGBA5551, otherwise RGBA4.
pub fn auto_format(image: &Image) -> Format {
let (mut partial, mut transparent) = (false, false);
for a in image.rgba.iter().skip(3).step_by(4) {
match a {
255 => {}
0 => transparent = true,
_ => {
partial = true;
break;
}
}
}
if partial {
Format::Rgba4
} else if transparent {
Format::Rgba5551
} else {
Format::Rgb565
}
}

/// Image row y becomes row h - 1 - y.
pub fn flip_vertical(image: Image) -> Image {
let row = image.width * 4;
let rgba = image.rgba.chunks_exact(row).rev().flatten().copied().collect();
Image { rgba, ..image }
}

struct Built {
key: Key,
width: u16,
height: u16,
format: u8,
data: Vec<u8>,
}

pub struct Summary {
pub entries: usize,
pub keep_original: usize,
pub skipped: Vec<String>,
pub data_bytes: u64,
pub by_format: [usize; 5],
}

fn build_one(dir: &Path, key: Key, file: &str, options: &Options, load: &dyn Fn(&Path) -> Result<Image, String>) -> Result<Built, String> {
let image = load(&dir.join(file))?;
let (w, h) = resample::target_size(image.width, image.height, options.max_size);
let (w, h) = (w.max(pica::MIN_SIZE), h.max(pica::MIN_SIZE));
let scaled = flip_vertical(resample::resize(&image, w, h));
let format = options.format.unwrap_or_else(|| auto_format(&scaled));
let data = pica::encode(&scaled, format).map_err(|e| format!("{file}: {e}"))?;
Ok(Built { key, width: w as u16, height: h as u16, format: gpu_format(format), data })
}

/// Converts level 0 of every entry. `load` decodes a PNG (main.rs).
pub fn build(dir: &Path, pack: &Pack, out: &Path, options: &Options, load: &(dyn Fn(&Path) -> Result<Image, String> + Sync)) -> Result<Summary, String> {
std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
let jobs: Vec<(Key, Option<String>)> = pack.entries.iter().filter_map(|(k, e)| e.levels.get(&0).map(|f| (*k, f.clone()))).collect();
let next = AtomicUsize::new(0);
let results: Mutex<Vec<Option<Result<Built, String>>>> = Mutex::new((0..jobs.len()).map(|_| None).collect());
let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
std::thread::scope(|s| {
for _ in 0..threads {
s.spawn(|| loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= jobs.len() {
break;
}
let (key, file) = &jobs[i];
let r = match file {
Some(f) => build_one(dir, *key, f, options, load),
None => Ok(Built { key: *key, width: 0, height: 0, format: 0, data: Vec::new() }),
};
results.lock().unwrap()[i] = Some(r);
});
}
});
let mut built = Vec::new();
let mut summary = Summary { entries: 0, keep_original: 0, skipped: Vec::new(), data_bytes: 0, by_format: [0; 5] };
for r in results.into_inner().unwrap().into_iter().flatten() {
match r {
Ok(b) => built.push(b),
Err(e) => summary.skipped.push(e),
}
}
built.sort_by_key(|b| (b.key.cachekey, b.key.hash));

let data_path: PathBuf = out.join("textures.bin");
let mut data = BufWriter::new(File::create(&data_path).map_err(|e| format!("{}: {e}", data_path.display()))?);
let mut index = Vec::with_capacity(24 + built.len() * ENTRY_SIZE);
index.extend_from_slice(MAGIC);
index.extend_from_slice(&VERSION.to_le_bytes());
index.extend_from_slice(&(pack.options.ignore_address as u32).to_le_bytes());
index.extend_from_slice(&(built.len() as u32).to_le_bytes());
index.extend_from_slice(&0u32.to_le_bytes());
let mut offset: u64 = 0;
for b in &built {
if offset > u32::MAX as u64 {
return Err("textures.bin would exceed 4 GiB; lower --max-size".into());
}
index.extend_from_slice(&b.key.cachekey.to_le_bytes());
index.extend_from_slice(&b.key.hash.to_le_bytes());
index.extend_from_slice(&(offset as u32).to_le_bytes());
index.extend_from_slice(&(b.data.len() as u32).to_le_bytes());
index.extend_from_slice(&b.width.to_le_bytes());
index.extend_from_slice(&b.height.to_le_bytes());
index.extend_from_slice(&[b.format, 0, 0, 0]);
index.extend_from_slice(&0u32.to_le_bytes());
if b.width == 0 {
summary.keep_original += 1;
continue;
}
data.write_all(&b.data).map_err(|e| e.to_string())?;
let pad = (ALIGN - b.data.len() % ALIGN) % ALIGN;
data.write_all(&vec![0; pad]).map_err(|e| e.to_string())?;
offset += (b.data.len() + pad) as u64;
summary.by_format[b.format.min(4) as usize] += 1;
}
data.flush().map_err(|e| e.to_string())?;
std::fs::write(out.join("index.bin"), &index).map_err(|e| format!("{}: {e}", out.display()))?;
summary.entries = built.len();
summary.data_bytes = offset;
Ok(summary)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn flips_rows() {
let img = Image { width: 1, height: 3, rgba: vec![1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3] };
assert_eq!(flip_vertical(img).rgba, vec![3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1]);
}

#[test]
fn auto_format_by_alpha() {
let img = |a: [u8; 2]| Image { width: 2, height: 1, rgba: vec![1, 2, 3, a[0], 4, 5, 6, a[1]] };
assert_eq!(auto_format(&img([255, 255])), Format::Rgb565);
assert_eq!(auto_format(&img([255, 0])), Format::Rgba5551);
assert_eq!(auto_format(&img([255, 128])), Format::Rgba4);
}

#[test]
fn writes_sorted_index_and_aligned_data() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../build/texpack/test-build");
let _ = std::fs::remove_dir_all(&root);
let src = root.join("pack");
std::fs::create_dir_all(&src).unwrap();
let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
std::fs::copy(fixtures.join("all_values_16x16.png"), src.join("b.png")).unwrap();
std::fs::copy(fixtures.join("pattern_16x8.png"), src.join("a.png")).unwrap();
let ini = "[options]\nhash = xxh64\nignoreAddress = true\n[hashes]\n\
00000000000000ff00000002 = b.png\n0000000000000001aaaaaaaa = a.png\n000000000000000500000000 = |\n";
let pack = crate::pack::parse_ini(ini, &[]).unwrap();
let out = root.join("out");
let options = Options { max_size: 8, format: Some(Format::Rgba8) };
let summary = build(&src, &pack, &out, &options, &crate::load_png).unwrap();
assert_eq!((summary.entries, summary.keep_original), (3, 1));
let index = std::fs::read(out.join("index.bin")).unwrap();
assert_eq!(&index[..8], MAGIC);
assert_eq!(u32::from_le_bytes(index[12..16].try_into().unwrap()), 1);
assert_eq!(u32::from_le_bytes(index[16..20].try_into().unwrap()), 3);
assert_eq!(index.len(), 24 + 3 * ENTRY_SIZE);
let entry = |i: usize| &index[24 + i * ENTRY_SIZE..24 + (i + 1) * ENTRY_SIZE];
let ck = |i: usize| u64::from_le_bytes(entry(i)[..8].try_into().unwrap());
assert_eq!((ck(0), ck(1), ck(2)), (1, 5, 0xff));
// a.png 16x8 -> 8x8 at max 8 (aspect 2:1 -> 8x4, raised to the 8 minimum).
let e0 = entry(0);
assert_eq!(u16::from_le_bytes([e0[20], e0[21]]), 8);
assert_eq!(u32::from_le_bytes(e0[16..20].try_into().unwrap()), 8 * 8 * 4);
let e1 = entry(1);
assert_eq!(u16::from_le_bytes([e1[20], e1[21]]), 0, "keep-original entry has no size");
let e2 = entry(2);
assert_eq!(u32::from_le_bytes(e2[12..16].try_into().unwrap()), 256, "second texture starts on the next 128-byte boundary");
let data = std::fs::read(out.join("textures.bin")).unwrap();
assert_eq!(data.len(), 512);
// Stored bottom-up: the first entry equals encode() of the flipped, resized image.
let a = crate::load_png(&src.join("a.png")).unwrap();
let expect = pica::encode(&flip_vertical(resample::resize(&a, 8, 8)), Format::Rgba8).unwrap();
assert_eq!(&data[..256], &expect[..]);
}
}
41 changes: 38 additions & 3 deletions tools/texpack/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,25 @@
//!
//! p3p-texpack inspect <pack dir>
//! p3p-texpack keys <pack dir>
//! p3p-texpack build <pack dir> <out dir> [--max-size <n>] [--format auto|<fmt>]
//! p3p-texpack encode <image.png> --format <fmt> --out <file>
//!
//! `encode` writes PICA200 texture data (no header), the same bytes as
//! `tex3ds -r -z none -f <fmt>` after its 4-byte header. Exit codes: 0 ok,
//! `tex3ds -r -z none -f <fmt>` after its 4-byte header. `build` writes the
//! New 3DS pack (build.rs: index.bin + textures.bin). Exit codes: 0 ok,
//! 1 error, 2 usage.

mod build;
mod pack;
mod pica;
mod resample;

use std::fs::File;
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

const USAGE: &str = "usage: p3p-texpack inspect <pack dir>\n p3p-texpack keys <pack dir>\n p3p-texpack encode <image.png> --format <fmt> --out <file>\n\
const USAGE: &str = "usage: p3p-texpack inspect <pack dir>\n p3p-texpack keys <pack dir>\n p3p-texpack build <pack dir> <out dir> [--max-size <n>] [--format auto|<fmt>]\n p3p-texpack encode <image.png> --format <fmt> --out <file>\n\
formats: rgba8 rgb8 rgb565 rgba5551 rgba4";

/// Largest source image accepted (packs ship upscales; the 3DS limit applies at encode).
Expand All @@ -37,7 +41,7 @@ fn png_info(path: &Path) -> Result<PngInfo, String> {
Ok(PngInfo { width: info.width, height: info.height, color: info.color_type, depth: info.bit_depth })
}

fn load_png(path: &Path) -> Result<pica::Image, String> {
pub(crate) fn load_png(path: &Path) -> Result<pica::Image, String> {
let file = File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
let mut decoder = png::Decoder::new_with_limits(BufReader::new(file), png::Limits { bytes: MAX_SOURCE_BYTES });
decoder.set_transformations(png::Transformations::normalize_to_color8());
Expand Down Expand Up @@ -120,6 +124,19 @@ fn keys(dir: &Path) -> Result<(), String> {
Ok(())
}

fn build_pack(dir: &Path, out: &Path, options: &build::Options) -> Result<(), String> {
let pack = pack::load(dir).map_err(|e| e.to_string())?;
let start = std::time::Instant::now();
let s = build::build(dir, &pack, out, options, &load_png)?;
for e in &s.skipped {
println!("skipped {e}");
}
println!("entries={} keep_original={} skipped={} data_bytes={} rgba8={} rgba5551={} rgb565={} rgba4={} seconds={:.1}",
s.entries, s.keep_original, s.skipped.len(), s.data_bytes, s.by_format[0], s.by_format[2], s.by_format[3],
s.by_format[4], start.elapsed().as_secs_f64());
Ok(())
}

fn encode(input: &Path, format: pica::Format, out: &Path) -> Result<(), String> {
let image = load_png(input)?;
let data = pica::encode(&image, format).map_err(|e| format!("{}: {e}", input.display()))?;
Expand All @@ -133,6 +150,24 @@ fn run(args: &[String]) -> Result<Result<(), String>, ()> {
match args {
[cmd, dir] if cmd == "inspect" => Ok(inspect(Path::new(dir))),
[cmd, dir] if cmd == "keys" => Ok(keys(Path::new(dir))),
[cmd, dir, out, rest @ ..] if cmd == "build" => {
let mut options = build::Options { max_size: 512, format: None };
let mut it = rest.iter();
while let Some(a) = it.next() {
match (a.as_str(), it.next()) {
("--max-size", Some(n)) => {
options.max_size = n.parse().map_err(|_| ())?;
if !(pica::MIN_SIZE..=pica::MAX_SIZE).contains(&options.max_size) {
return Err(());
}
}
("--format", Some(f)) if f == "auto" => options.format = None,
("--format", Some(f)) => options.format = Some(pica::Format::parse(f).ok_or(())?),
_ => return Err(()),
}
}
Ok(build_pack(Path::new(dir), Path::new(out), &options))
}
[cmd, input, rest @ ..] if cmd == "encode" => {
let (mut format, mut out) = (None, None);
let mut it = rest.iter();
Expand Down
Loading