diff --git a/Cargo.lock b/Cargo.lock
index 0e7dc6e..49a37cd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3985,6 +3985,7 @@ version = "0.5.0"
dependencies = [
"anyhow",
"dirs",
+ "flate2",
"memchr",
"openrage-plugins",
"png",
@@ -4068,6 +4069,12 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "opus-rs"
+version = "0.1.42"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bafbcaf2ed381cdf68ced4ed8d16517de90ffd7424e36f0b9e45d67fbe30b1f9"
+
[[package]]
name = "orbclient"
version = "0.3.55"
@@ -4547,6 +4554,7 @@ version = "0.5.0"
dependencies = [
"flate2",
"lewton",
+ "opus-rs",
"png",
"rage-core",
"rage-resource",
diff --git a/NOTICE.md b/NOTICE.md
index 5a60ca7..9896c16 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -51,6 +51,27 @@ Vorbis audio (Red Dead Redemption 2) is decoded with lewton
(https://github.com/RustAudio/lewton), licensed under the MIT or Apache-2.0
license.
+## opus-rs
+
+Opus audio (GTA VI) is decoded with opus-rs
+(https://github.com/restsend/opus-rs), a port of libopus, licensed under the
+BSD 3-Clause licence.
+
+## Leonida
+
+What is known about GTA VI's formats (RPF9 archives, audio containers, PSIN
+and RBF0 metadata, texture pools) comes from the documentation of Leonida
+(https://github.com/ItsNotRexed/Leonida, GPL-3.0). The PSIN reader in
+`crates/rage-formats/src/psin.rs` follows its `tools/psin_data.py`, the
+texture pool reader in `crates/rage-formats/src/ttpf.rs` its
+`tools/ttpf_mips.py` and `tools/tex_headers.py`.
+
+## rpf9-explorer
+
+The layout of GTA VI's models (`crates/rage-formats/src/drawable6.rs`) is the
+one found by rpf9-explorer (https://github.com/breadbbbb/rpf9-explorer). Its
+decoder was read to learn the layout; no code was taken from it.
+
## RDR2-RPF-Tool
The TFIT2-CBC cipher and the strided file encryption of Red Dead Redemption 2
diff --git a/README.md b/README.md
index bbcceac..b020261 100644
--- a/README.md
+++ b/README.md
@@ -40,7 +40,7 @@ OpenIV's last release was in January 2022. OpenRAGE picks up where it left off a
- **Mods, safely:** changes go to OpenIV's `mods` folder, never into your game files; every change and every `.oiv` package can be undone.
- **Models in:** replace props and vehicle bodies of GTA V Enhanced with your own OBJ models; doors and bonnets keep moving (preview).
- **ASI mods:** see and switch GTA V's ASI mods, and on Linux let Proton load the ASI loader with one click.
-- **Ready for GTA VI:** support follows as fast as possible once GTA VI comes to PC.
+- **Experimental GTA VI Scarlett support:** RPF9 TOC browsing, named lookup, streaming extraction, model previews and standalone TTPF textures for the analysed 1.0.2.1 build. See [scope and setup](crates/rage-rpf/RPF9.md).
- **Tested on the whole game:** every format is checked against every file of GTA V ([details](https://two-play.github.io/openrage/#status)).
@@ -62,7 +62,7 @@ More screenshots and all features: **[two-play.github.io/openrage](https://two-p
|---|---|---|
| **GTA V** (Legacy & Enhanced) | ✅ read and edit (mods folder, with undo) | ✅ textures (also inside models) · models · audio · animations · metadata · text · collisions · paths · cutscenes · scripts · ASI mods (manager, Proton fix on Linux) · ◐ model import from OBJ with compressed textures and detail levels (Enhanced `.ydr` and vehicle bodies `.yft`, preview; explorer via the OBJ tools plugin) |
| **Red Dead Redemption 2** | ✅ read, with keys from your own game · ◐ edit (Lenny's Mod Loader `lml/replace` folder, with undo; nested archives rewritten; not yet tried in the game) | ◐ textures (replace same-shape) · models with moving parts and cloth · texts · metadata · audio · animations on fitting models · ped outfits (read-only) |
-| **GTA VI** | 🔜 next: as fast as possible once it comes to PC | – |
+| **GTA VI Scarlett 1.0.2.1** | Experimental RPF9 reader, GUI and selected model/texture formats | Read-only; requires the user's reference executable |
| **GTA IV** (Complete Edition) | ✅ read (IMG3, RPF2, RPF3), key from your own `GTAIV.exe` | ◐ textures · models · collisions · animations · text · scripts · maps in 3D · cutscenes (played with their cast, camera, subtitles and particle effects) · particle effect lists (`.wpfl`) · editing `.img`, `.rpf`, placement files, loose files and textures (`.wtd`, inside `.wdr`) (update folder, or the game files with originals kept) |
**Plugins** (API 0.3, preview): sandboxed WebAssembly plugins add file types, previews (text, tree, table, image, 3D model), tool windows of their own (Tools menu), export and batch actions with access to the game's models and textures, and changes to game files through the `mods` folder (with undo), for every game. ✅ explorer (file list, preview, context menu, Settings → Plugins) and command line (`openrage plugin`), four example plugins included (OBJ export and import, a number and hash converter among them) · plugin packages (`.orp`) with install/uninstall in the explorer and the CLI · models into game formats (`build-model`) · ✅ openFormats: OpenIV's text formats (`.odr`, `.oft`, `.odd`, `.otd` with `.mesh`, `.skel`, DDS) exported and imported back (preview). [Writing plugins](https://two-play.github.io/openrage/plugins/)
diff --git a/crates/openrage-app/Cargo.toml b/crates/openrage-app/Cargo.toml
index 3a3572c..c4a724f 100644
--- a/crates/openrage-app/Cargo.toml
+++ b/crates/openrage-app/Cargo.toml
@@ -24,4 +24,5 @@ png = "0.18"
zip.workspace = true
[dev-dependencies]
+flate2.workspace = true
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
diff --git a/crates/openrage-app/examples/rpf9_model_probe.rs b/crates/openrage-app/examples/rpf9_model_probe.rs
new file mode 100644
index 0000000..00dba1b
--- /dev/null
+++ b/crates/openrage-app/examples/rpf9_model_probe.rs
@@ -0,0 +1,140 @@
+//! Bounded local-corpus probe, with no recovery scan or archive extraction.
+//! Run with the game directory as the sole argument. The reference executable
+//! is discovered by Rpf9 in that directory's ancestors.
+
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, ensure};
+use rage_formats::drawable6;
+use rage_rpf::{Rpf9, rpf9::Kind};
+
+const MAX_RESOURCE: u64 = 32 << 20;
+const MAX_SAMPLES: usize = 16;
+
+fn main() -> Result<()> {
+ let root = PathBuf::from(std::env::args_os().nth(1).context("usage: rpf9_model_probe ")?);
+ let rpf = Rpf9::open(&root.join("data.rpf"))?;
+ ensure!(rpf.has_toc(), "no usable TOC: refusing to scan archive payloads");
+ let mut totals = (0, 0);
+ probe_models(&rpf, "data.rpf", &mut totals)?;
+ let entries = rpf.entries()?;
+ for (index, _) in entries
+ .iter()
+ .enumerate()
+ .filter(|(_, e)| matches!(e.kind, Kind::Toc { file_type: 0, resource: false, .. }))
+ .take(10)
+ {
+ if totals.0 + totals.1 >= MAX_SAMPLES {
+ break;
+ }
+ match rpf.open_child(index) {
+ Ok(child) => probe_models(&child, &format!("data.rpf/{index}"), &mut totals)?,
+ Err(error) => println!("CHILD_FAIL index={index} error={error}"),
+ }
+ }
+ println!("MODEL_SUMMARY parsed={} failed={}", totals.0, totals.1);
+ let textures = probe_textures(&root)?;
+ ensure!(totals.0 > 0 || textures > 0, "neither sampled models nor textures decoded successfully");
+ Ok(())
+}
+
+fn probe_models(rpf: &Rpf9, archive: &str, totals: &mut (usize, usize)) -> Result<()> {
+ ensure!(rpf.has_toc(), "refusing recovery scan");
+ let entries = rpf.entries()?;
+ let candidates: Vec<_> = entries
+ .iter()
+ .enumerate()
+ .filter(|(_, e)| matches!(e.kind, Kind::Toc { resource: true, file_type: 2..=4, .. }) && e.size <= MAX_RESOURCE)
+ .take(MAX_SAMPLES.saturating_sub(totals.0 + totals.1))
+ .collect();
+ println!(
+ "archive={archive} entries={} samples={} max_resource_bytes={MAX_RESOURCE}",
+ entries.len(),
+ candidates.len()
+ );
+ for (index, entry) in candidates {
+ let name = rpf.entry_name(entry);
+ let result = (|| -> Result<(usize, usize, usize, usize, usize)> {
+ let (system, graphics) = rpf.resource_parts(index)?.context("TOC entry has no resource parts")?;
+ ensure!(system.len() as u64 + graphics.len() as u64 <= MAX_RESOURCE, "decoded resource exceeds limit");
+ let drawables = drawable6::parse(&system, &graphics)?;
+ let meshes: usize = drawables.iter().map(|d| d.meshes.len()).sum();
+ let vertices: usize = drawables.iter().flat_map(|d| &d.meshes).map(|m| m.positions.len()).sum();
+ ensure!(meshes > 0 && vertices > 0, "parser returned no renderable geometry");
+ Ok((system.len(), graphics.len(), drawables.len(), meshes, vertices))
+ })();
+ match result {
+ Ok((sys, gfx, drawables, meshes, vertices)) => {
+ totals.0 += 1;
+ println!(
+ "OK archive={archive} index={index} name={name:?} sys={sys} gfx={gfx} drawables={drawables} meshes={meshes} vertices={vertices}"
+ );
+ }
+ Err(error) => {
+ totals.1 += 1;
+ println!(
+ "FAIL archive={archive} index={index} name={name:?} logical_bytes={} error={error:#}",
+ entry.size
+ );
+ }
+ }
+ }
+ Ok(())
+}
+
+fn probe_textures(root: &Path) -> Result {
+ let mut files = Vec::new();
+ openrage_app::detect::collect_archives(&root.join("data/ttdb"), &["ttpf"], &mut files);
+ files.sort_by_key(|p| std::fs::metadata(p).map_or(u64::MAX, |m| m.len()));
+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_nanos();
+ let output = std::env::temp_dir().join(format!("openrage-rpf9-textures-{}-{stamp}", std::process::id()));
+ let (mut attempted, mut decoded, mut pools) = (0, 0, 0);
+ for file in files.into_iter().take(64) {
+ if attempted >= MAX_SAMPLES {
+ break;
+ }
+ pools += 1;
+ let pool = match rage_formats::ttpf::Pool::open(&file) {
+ Ok(pool) => pool,
+ Err(error) => {
+ println!("POOL_FAIL path={file:?} error={error}");
+ continue;
+ }
+ };
+ for index in 0..pool.len() {
+ if attempted >= MAX_SAMPLES {
+ break;
+ }
+ let Some(d) = pool.descriptor(index) else {
+ continue;
+ };
+ if d.base.is_none() || d.dimension != 1 || d.depth != 1 || d.width > 512 || d.height > 512 {
+ continue;
+ }
+ attempted += 1;
+ let result = (|| -> Result<_> {
+ let texture = pool.texture_with_limit(index, Some(512), MAX_RESOURCE as usize)?;
+ ensure!(texture.width <= 512 && texture.height <= 512, "mip fallback exceeds preview dimensions");
+ let rgba = texture.to_rgba().context("pixel decoder does not support this format")?;
+ let png = rage_formats::png(texture.width, texture.height, &rgba)?;
+ std::fs::create_dir_all(&output)?;
+ let path = output.join(format!("pool{pools}-texture{index}.png"));
+ std::fs::File::create_new(&path)?.write_all(&png)?;
+ Ok((texture.width, texture.height, texture.format.name(), path))
+ })();
+ match result {
+ Ok((width, height, format, path)) => {
+ decoded += 1;
+ println!(
+ "TEXTURE_OK pool={file:?} index={index} key={:016x} width={width} height={height} format={format} png={path:?}",
+ pool.keys()[index]
+ );
+ }
+ Err(error) => println!("TEXTURE_FAIL pool={file:?} index={index} error={error:#}"),
+ }
+ }
+ }
+ println!("TEXTURE_SUMMARY pools={pools} attempted={attempted} decoded={decoded} failed={}", attempted - decoded);
+ Ok(decoded)
+}
diff --git a/crates/openrage-app/src/audio.rs b/crates/openrage-app/src/audio.rs
index 8870310..a93952e 100644
--- a/crates/openrage-app/src/audio.rs
+++ b/crates/openrage-app/src/audio.rs
@@ -18,6 +18,7 @@ pub fn load(game_dir: &Path, keys: Option>, vpath: &str) -> Result
let data = match node {
Node::ArchiveFile(rpf, id) => rpf.read(id)?,
Node::PlainFile(p) => std::fs::read(p)?,
+ Node::Rpf9File(rpf, i) => rpf.read_at(i)?,
_ => bail!("{vpath} is not a file"),
};
parse(data, keys.as_deref())
diff --git a/crates/openrage-app/src/detect.rs b/crates/openrage-app/src/detect.rs
index 5f532e1..a58f3f2 100644
--- a/crates/openrage-app/src/detect.rs
+++ b/crates/openrage-app/src/detect.rs
@@ -63,7 +63,7 @@ pub fn find_installs() -> Vec {
}
pub fn is_gta5_dir(dir: &Path) -> bool {
- EXECUTABLES.iter().any(|exe| dir.join(exe).is_file())
+ !is_gta6_dir(dir) && EXECUTABLES.iter().any(|exe| dir.join(exe).is_file())
}
/// The program that marks a Red Dead Redemption 2 installation.
@@ -71,11 +71,32 @@ pub const RDR2_EXE: &str = "RDR2.exe";
/// Whether a folder is a Red Dead Redemption 2 installation.
pub fn is_rdr2_dir(dir: &Path) -> bool {
- dir.join(RDR2_EXE).is_file()
+ !is_gta6_dir(dir) && dir.join(RDR2_EXE).is_file()
+}
+
+/// Whether a folder holds RPF9 archives. Archive signatures take precedence
+/// over executable names, since a reference executable may have been copied here.
+pub fn is_gta6_dir(dir: &Path) -> bool {
+ if rage_rpf::Rpf9::file_is_rpf9(&dir.join("common.rpf")) {
+ return true;
+ }
+ let Ok(rd) = fs::read_dir(dir) else { return false };
+ rd.flatten()
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("rpf")))
+ .any(|p| rage_rpf::Rpf9::file_is_rpf9(&p))
+}
+
+/// Whether a folder holds a game OpenRAGE can open.
+pub fn is_game_dir(dir: &Path) -> bool {
+ is_gta5_dir(dir) || is_rdr2_dir(dir) || crate::gta4::is_gta4_dir(dir) || is_gta6_dir(dir)
}
/// The icon of the game in `dir`, from its own program: (width, height, RGBA).
pub fn game_icon(dir: &Path) -> Option<(u32, u32, Vec)> {
+ if is_gta6_dir(dir) {
+ return None;
+ }
let programs: &[&str] = if is_rdr2_dir(dir) {
&[RDR2_EXE]
} else if crate::gta4::is_gta4_dir(dir) {
@@ -87,9 +108,11 @@ pub fn game_icon(dir: &Path) -> Option<(u32, u32, Vec)> {
}
/// Short name of the game installed in `dir`: "GTA V Enhanced", "GTA V",
-/// "GTA IV", "RDR2", or `None` when no known executable is there.
+/// "GTA IV", "RDR2", "GTA VI", or `None` when the folder holds no known game.
pub fn game_name(dir: &Path) -> Option<&'static str> {
- if is_rdr2_dir(dir) {
+ if is_gta6_dir(dir) {
+ Some("GTA VI")
+ } else if is_rdr2_dir(dir) {
Some("RDR2")
} else if dir.join("GTA5_Enhanced.exe").is_file() {
Some("GTA V Enhanced")
@@ -130,6 +153,27 @@ pub fn collect_rpfs(dir: &Path, out: &mut Vec) {
mod tests {
use super::*;
+ #[test]
+ fn archive_signature_overrides_copied_executables() {
+ let dir = std::env::temp_dir().join(format!("openrage-detect-rpf9-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("GTA5_Enhanced.exe"), []).unwrap();
+ fs::write(dir.join("RDR2.exe"), []).unwrap();
+ fs::write(dir.join("GTAIV.exe"), []).unwrap();
+ // Detection reads only the signature, never the archive's payload.
+ fs::write(dir.join("common.rpf"), b"9FPR").unwrap();
+ assert!(is_gta6_dir(&dir));
+ assert!(!is_gta5_dir(&dir));
+ assert!(!is_rdr2_dir(&dir));
+ assert_eq!(game_name(&dir), Some("GTA VI"));
+ assert!(game_icon(&dir).is_none());
+ // Other RPF9 archives still identify the game if common is another format.
+ fs::write(dir.join("common.rpf"), b"RPF7").unwrap();
+ fs::write(dir.join("data.rpf"), b"9FPR").unwrap();
+ assert_eq!(game_name(&dir), Some("GTA VI"));
+ fs::remove_dir_all(dir).unwrap();
+ }
+
#[test]
fn parses_library_folders() {
let vdf = r#"
diff --git a/crates/openrage-app/src/gta6_models.rs b/crates/openrage-app/src/gta6_models.rs
new file mode 100644
index 0000000..84f64ce
--- /dev/null
+++ b/crates/openrage-app/src/gta6_models.rs
@@ -0,0 +1,79 @@
+//! GTA VI models using the TOC resource boundaries when available.
+//! The stream-boundary heuristic below is only used for the recovery view.
+//!
+//! A model is stored as its system part and then its graphics part, each
+//! cut into zlib streams of 64 KiB. Without the table of contents nothing
+//! says where one part ends: the recovery view lists a resource as its first
+//! entry (which starts the system part) and what follows it. So the parts
+//! are found by trying: every cut between two streams is a possible end of
+//! the system part, and the reader says whether the graphics part reaches
+//! far enough.
+
+use anyhow::{Context, Result, bail};
+use rage_formats::drawable::Drawable;
+use rage_formats::drawable6::{self, ModelError};
+use rage_rpf::Rpf9;
+
+/// Streams unpack to this many bytes, the last one of a part to fewer.
+const STREAM: usize = 0x10000;
+/// A system part is at most this long.
+const MAX_SYSTEM: usize = 32 << 20;
+/// A resource is at most this long, and spread over at most this many entries.
+const MAX_RESOURCE: usize = 256 << 20;
+const MAX_ENTRIES: usize = 4096;
+
+/// Reads the model that starts at entry `index`: its drawables with their names.
+pub fn load(rpf: &Rpf9, index: usize) -> Result> {
+ let entries = rpf.entries()?;
+ let first = entries.get(index).context("no such entry")?;
+ if first.size > MAX_RESOURCE as u64 {
+ bail!("model exceeds the preview size limit");
+ }
+ if let Some((system, graphics)) = rpf.resource_parts(index)? {
+ return Ok(named(drawable6::parse(&system, &graphics)?));
+ }
+ if rpf.has_toc() {
+ bail!("this TOC entry is not a model resource");
+ }
+ let mut data = rpf.read(first)?;
+ if drawable6::root(&data).is_none() {
+ bail!("this resource is not a model");
+ }
+ // Where streams end: the possible ends of the system part.
+ let mut cuts: Vec = (1..=data.len().div_ceil(STREAM)).map(|i| (i * STREAM).min(data.len())).collect();
+ let mut last = index;
+ loop {
+ let mut needs_more = false;
+ let mut failure = None;
+ for cut in cuts.iter().copied().take_while(|c| *c <= MAX_SYSTEM) {
+ match drawable6::parse(&data[..cut], &data[cut..]) {
+ Ok(drawables) => return Ok(named(drawables)),
+ Err(ModelError::Graphics(_)) => needs_more = true,
+ Err(e) => failure = failure.or(Some(e)),
+ }
+ }
+ // The graphics part goes on in the next entry.
+ if !needs_more || !Rpf9::follows(&entries, last) || last - index >= MAX_ENTRIES || data.len() >= MAX_RESOURCE {
+ match failure {
+ Some(e) if !needs_more => bail!(e),
+ _ => bail!("the model's vertex and index data was not found after it"),
+ }
+ }
+ last += 1;
+ if entries[last].size > MAX_RESOURCE.saturating_sub(data.len()) as u64 {
+ bail!("model exceeds the preview size limit");
+ }
+ let more = rpf.read(&entries[last])?;
+ let start = data.len();
+ data.extend_from_slice(&more);
+ cuts.extend((1..=more.len().div_ceil(STREAM)).map(|i| start + (i * STREAM).min(more.len())));
+ }
+}
+
+fn named(drawables: Vec) -> Vec<(String, Drawable)> {
+ drawables
+ .into_iter()
+ .enumerate()
+ .map(|(i, d)| (if d.name.is_empty() { format!("drawable {i}") } else { d.name.clone() }, d))
+ .collect()
+}
diff --git a/crates/openrage-app/src/gta6_textures.rs b/crates/openrage-app/src/gta6_textures.rs
new file mode 100644
index 0000000..131d4f3
--- /dev/null
+++ b/crates/openrage-app/src/gta6_textures.rs
@@ -0,0 +1,106 @@
+//! GTA VI: the textures of models, which are in the texture pools.
+//!
+//! A model's shader names a texture by a 64-bit key; each texture pool
+//! (`.ttpf`, see [`rage_formats::ttpf`]) lists the keys of its textures. So
+//! the pools of a game are read once into a catalog of key → pool and number.
+//! These are standalone files: discovery reads their bounded tables and does
+//! not scan RPF payloads, in either TOC or recovery mode. Pools embedded inside
+//! an RPF are not catalogued here; they need a seekable archive-entry reader.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex, OnceLock};
+
+use rage_formats::drawable::Drawable;
+use rage_formats::drawable6::texture_name;
+use rage_formats::ttpf::Pool;
+use rage_formats::ytd::{Layout, TextureDictionary};
+
+/// Textures on a model are read at most this many pixels wide and high.
+const MAX_SIDE: u32 = 1024;
+/// A model gets at most this many textures.
+const MAX_TEXTURES: usize = 64;
+
+/// Where the textures of a game are: per key, the pool and the number in it.
+#[derive(Default)]
+pub struct Catalog {
+ pools: Vec<(PathBuf, Pool)>,
+ by_key: HashMap,
+}
+
+impl Catalog {
+ /// Reads the tables of all texture pools below `game_dir`.
+ fn build(game_dir: &Path) -> Catalog {
+ let mut files = Vec::new();
+ crate::detect::collect_archives(game_dir, &["ttpf"], &mut files);
+ let mut catalog = Catalog::default();
+ for file in files {
+ let Ok(pool) = Pool::open(&file) else { continue };
+ for (number, key) in pool.keys().iter().enumerate().filter(|(_, key)| **key != 0) {
+ // The same texture can be in several pools: the first one that has data wins.
+ let has_data = pool.descriptor(number).is_some_and(|d| d.base.is_some());
+ let known = catalog
+ .by_key
+ .get(key)
+ .is_some_and(|(p, n)| catalog.pools[*p].1.descriptor(*n).is_some_and(|d| d.base.is_some()));
+ if !known && (has_data || !catalog.by_key.contains_key(key)) {
+ catalog.by_key.insert(*key, (catalog.pools.len(), number));
+ }
+ }
+ catalog.pools.push((file, pool));
+ }
+ catalog
+ }
+
+ pub fn len(&self) -> usize {
+ self.by_key.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.by_key.is_empty()
+ }
+
+ /// The texture with this key, named by the key.
+ pub fn texture(&self, key: u64) -> Option {
+ let (pool, number) = *self.by_key.get(&key)?;
+ let mut texture = self.pools[pool].1.texture(number, Some(MAX_SIDE)).ok()?;
+ texture.name = texture_name(key);
+ Some(texture)
+ }
+}
+
+/// The catalog of a game's texture pools; read on first use and kept.
+pub fn catalog(game_dir: &Path) -> Arc {
+ static CATALOGS: OnceLock>>> = OnceLock::new();
+ let mut catalogs = CATALOGS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
+ Arc::clone(catalogs.entry(game_dir.to_path_buf()).or_insert_with(|| Arc::new(Catalog::build(game_dir))))
+}
+
+/// The textures the shaders of these drawables name, from the pools of the
+/// game: a dictionary of them, `None` if none was found.
+pub fn for_drawables(game_dir: &Path, drawables: &[(String, Drawable)]) -> Option {
+ let mut names: Vec<&str> =
+ drawables.iter().flat_map(|(_, d)| &d.shaders).flat_map(|s| &s.textures).map(String::as_str).collect();
+ names.sort_unstable();
+ names.dedup();
+ if names.is_empty() {
+ return None;
+ }
+ let catalog = catalog(game_dir);
+ let total = names.len().min(MAX_TEXTURES);
+ let mut textures = Vec::new();
+ for (i, name) in names.into_iter().take(MAX_TEXTURES).enumerate() {
+ crate::progress::set("Loading textures", i as u64, total as u64);
+ if let Some(texture) = u64::from_str_radix(name, 16).ok().and_then(|key| catalog.texture(key)) {
+ textures.push(texture);
+ }
+ }
+ (!textures.is_empty()).then(|| TextureDictionary {
+ textures,
+ errors: Vec::new(),
+ layout: Layout::Enhanced,
+ version: 0,
+ root: Vec::new(),
+ stored: Vec::new(),
+ })
+}
diff --git a/crates/openrage-app/src/lib.rs b/crates/openrage-app/src/lib.rs
index d670f98..6a38ad2 100644
--- a/crates/openrage-app/src/lib.rs
+++ b/crates/openrage-app/src/lib.rs
@@ -14,6 +14,8 @@ pub mod extract;
pub mod gta4;
pub mod gta4_cutscene;
pub mod gta4_effects;
+pub mod gta6_models;
+pub mod gta6_textures;
pub mod install;
pub mod journal;
pub mod licenses;
@@ -33,6 +35,7 @@ pub mod rdr2;
pub mod rdr2_install;
pub mod render;
pub mod repack;
+pub mod rpf9;
pub mod setup;
pub mod suggest;
pub mod texttable;
diff --git a/crates/openrage-app/src/metadata.rs b/crates/openrage-app/src/metadata.rs
index ef10faa..b83c5fb 100644
--- a/crates/openrage-app/src/metadata.rs
+++ b/crates/openrage-app/src/metadata.rs
@@ -12,7 +12,7 @@ use rage_resource::Resource;
use rage_rpf::vfs::Node;
/// Extensions of files that hold metadata.
-pub const EXTENSIONS: &[&str] = &["ymap", "ytyp", "ymt", "ymf", "cut", "pso"];
+pub const EXTENSIONS: &[&str] = &["ymap", "ytyp", "ymt", "ymf", "cut", "pso", "psin", "rbf0"];
pub fn is_metadata(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
@@ -72,6 +72,11 @@ fn from_bytes_for(data: &[u8], rdr2: bool) -> Result {
}
return from_resource(&res);
}
+ if rage_formats::psin::is_psin(data) {
+ let psin = rage_formats::psin::parse(data)?;
+ let (text, errors) = psin.to_xml();
+ return Ok(Xml { text, encoding: Encoding::Pso, root: Some(psin.root_type()), errors });
+ }
if rage_formats::pso::is_pso(data) {
let pso = if rdr2 { rage_formats::pso::parse_rdr2(data)? } else { rage_formats::pso::parse(data)? };
let (text, errors) = pso.to_xml();
@@ -116,6 +121,7 @@ pub fn load(game_dir: &Path, keys: Option>, vpath: &str) -> Result
Node::ArchiveFile(rpf, id) => rpf.read(id)?,
Node::PlainFile(p) => std::fs::read(p)?,
Node::Rpf8File(rpf, i) => return from_rpf8(&rpf, i),
+ Node::Rpf9File(rpf, i) => rpf.read_at(i)?,
_ => bail!("{vpath} is not a file"),
};
from_bytes(&data)
diff --git a/crates/openrage-app/src/models.rs b/crates/openrage-app/src/models.rs
index 23503de..bb7256d 100644
--- a/crates/openrage-app/src/models.rs
+++ b/crates/openrage-app/src/models.rs
@@ -533,6 +533,10 @@ pub fn is_model(name: &str) -> bool {
|| n.ends_with(".wft")
|| n.ends_with(".wbn")
|| n.ends_with(".wbd")
+ // GTA VI: drawables, fragments and drawable dictionaries.
+ || n.ends_with(".#dr")
+ || n.ends_with(".#ft")
+ || n.ends_with(".#dd")
|| rage_formats::paths::is_path_file(&n)
}
@@ -675,6 +679,15 @@ fn load_model(game_dir: &Path, keys: Option>, vpath: &str) -> Resu
if let Node::Gta4File(archive, id) = node {
return load_gta4(&archive, id);
}
+ if let Node::Rpf9File(rpf, i) = node {
+ let drawables = crate::gta6_models::load(&rpf, i)?;
+ let textures = crate::gta6_textures::for_drawables(game_dir, &drawables);
+ let mut model = LoadedModel::from_drawables(drawables);
+ if let Some(textures) = textures {
+ model.add_textures("texture pools".to_owned(), textures);
+ }
+ return Ok(model);
+ }
let Node::ArchiveFile(rpf, id) = node else { bail!("{vpath} is not a file inside an archive") };
let name = rpf.entry(id).name.clone();
let res = rpf.read_resource(id)?;
diff --git a/crates/openrage-app/src/plugins.rs b/crates/openrage-app/src/plugins.rs
index 8781b86..ed9a9c1 100644
--- a/crates/openrage-app/src/plugins.rs
+++ b/crates/openrage-app/src/plugins.rs
@@ -163,7 +163,8 @@ impl GameFiles for GameDir {
None => bail!("{vpath}: not found"),
},
Node::Gta4File(a, id) => a.read(id)?,
- Node::Dir(_) | Node::ArchiveDir(..) | Node::Rpf8Dir(..) | Node::Gta4Dir(..) => {
+ Node::Rpf9File(rpf, i) => rpf.read_at(i)?,
+ Node::Dir(_) | Node::ArchiveDir(..) | Node::Rpf8Dir(..) | Node::Gta4Dir(..) | Node::Rpf9Dir(..) => {
bail!("{vpath} is a folder")
}
_ => bail!("{vpath}: not supported"),
@@ -223,7 +224,26 @@ impl GameFiles for GameDir {
out.push(DirEntry { name: e.name.clone(), is_dir: e.is_dir(), size: e.size() });
}
}
- Node::PlainFile(_) | Node::ArchiveFile(..) | Node::Rpf8File(..) | Node::Gta4File(..) => {
+ Node::Rpf9Dir(rpf, dir) => {
+ let entries = rpf.entries()?;
+ let (dirs, files) = rpf.list_dir(&entries, &dir);
+ for d in dirs {
+ out.push(DirEntry { name: d, is_dir: true, size: 0 });
+ }
+ for i in files {
+ let name = rpf.entry_name(&entries[i]);
+ out.push(DirEntry {
+ name: name.rsplit('/').next().unwrap_or(&name).to_owned(),
+ is_dir: false,
+ size: entries[i].size,
+ });
+ }
+ }
+ Node::PlainFile(_)
+ | Node::ArchiveFile(..)
+ | Node::Rpf8File(..)
+ | Node::Gta4File(..)
+ | Node::Rpf9File(..) => {
bail!("{vpath} is a file")
}
_ => bail!("{vpath}: not supported"),
diff --git a/crates/openrage-app/src/rpf9.rs b/crates/openrage-app/src/rpf9.rs
new file mode 100644
index 0000000..db4fe6e
--- /dev/null
+++ b/crates/openrage-app/src/rpf9.rs
@@ -0,0 +1,426 @@
+//! GTA VI archives (RPF9): TOC browsing, recovery caches, and extraction.
+//! TOC-backed archives bypass recovery scanning and model-name harvesting.
+//!
+//! Without a usable TOC, recovery means scanning the archive (see
+//! [`rage_rpf::rpf9`]), which takes minutes for the large ones. The result
+//! is kept in the cache directory, one file per archive, and used as long as
+//! the archive's size and modification time stay the same.
+
+use std::collections::HashMap;
+use std::fs;
+use std::io::{BufWriter, Write};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::UNIX_EPOCH;
+
+use anyhow::{Context, Result};
+use rage_rpf::rpf9::{self, Entry};
+use rage_rpf::{Rpf9, RpfError, vfs};
+
+use crate::extract::ExtractSummary;
+
+/// Start of an index file; the digit changes with the format.
+const INDEX_MAGIC: &[u8; 8] = b"ORP9IDX2";
+
+/// Where the index of an archive is stored:
+/// `/openrage/rpf9-.idx`.
+pub fn index_path(archive: &Path) -> Option {
+ crate::paths::game_cache(archive, "rpf9", "idx")
+}
+
+/// Size and modification time (seconds) of the archive: an index made for
+/// other values is out of date.
+fn identity(archive: &Path) -> Option<[u8; 16]> {
+ let meta = fs::metadata(archive).ok()?;
+ let modified = meta.modified().ok()?.duration_since(UNIX_EPOCH).ok()?.as_secs();
+ let mut id = [0u8; 16];
+ id[..8].copy_from_slice(&meta.len().to_le_bytes());
+ id[8..].copy_from_slice(&modified.to_le_bytes());
+ Some(id)
+}
+
+/// The stored index of an archive, if there is one and it is up to date.
+pub fn load_index(archive: &Path) -> Option> {
+ load_index_from(&index_path(archive)?, archive)
+}
+
+fn load_index_from(index: &Path, archive: &Path) -> Option> {
+ let data = fs::read(index).ok()?;
+ let rest = data.strip_prefix(INDEX_MAGIC)?.strip_prefix(&identity(archive)?)?;
+ rpf9::decode_index(rest)
+}
+
+/// Stores the index of an archive.
+pub fn store_index(archive: &Path, entries: &[Entry]) -> Result<()> {
+ store_index_to(&index_path(archive).context("no cache directory")?, archive, entries)
+}
+
+fn store_index_to(index: &Path, archive: &Path, entries: &[Entry]) -> Result<()> {
+ let id = identity(archive).context("archive not readable")?;
+ if let Some(dir) = index.parent() {
+ fs::create_dir_all(dir)?;
+ }
+ // Written beside and renamed: a stopped write leaves no half index.
+ let partial = index.with_extension("idx.part");
+ let mut data = Vec::from(INDEX_MAGIC);
+ data.extend_from_slice(&id);
+ data.extend_from_slice(&rpf9::encode_index(entries));
+ fs::write(&partial, data)?;
+ fs::rename(&partial, index)?;
+ Ok(())
+}
+
+/// Start of a names file; the digit changes with the format.
+const NAMES_MAGIC: &[u8; 8] = b"ORP9NAM2";
+/// How much of a resource is read to find its name.
+const NAME_PREFIX: usize = 256 << 10;
+
+/// Where the names of an archive's models are stored, beside its index.
+pub fn names_path(archive: &Path) -> Option {
+ crate::paths::game_cache(archive, "rpf9", "names")
+}
+
+/// The stored names of an archive, if there are any and they are up to date.
+pub fn load_names(archive: &Path) -> Option {
+ let data = fs::read(names_path(archive)?).ok()?;
+ let mut rest = data.strip_prefix(NAMES_MAGIC)?.strip_prefix(&identity(archive)?)?;
+ let mut found = Vec::new();
+ while !rest.is_empty() {
+ let offset = u64::from_le_bytes(rest.get(..8)?.try_into().ok()?);
+ let len = usize::from(u16::from_le_bytes(rest.get(8..10)?.try_into().ok()?));
+ found.push((offset, String::from_utf8(rest.get(10..10 + len)?.to_vec()).ok()?));
+ rest = &rest[10 + len..];
+ }
+ Some(rpf9::Names::new(found))
+}
+
+/// Stores the names of an archive's models.
+pub fn store_names(archive: &Path, names: &[(u64, String)]) -> Result<()> {
+ let path = names_path(archive).context("no cache directory")?;
+ let id = identity(archive).context("archive not readable")?;
+ if let Some(dir) = path.parent() {
+ fs::create_dir_all(dir)?;
+ }
+ let mut data = Vec::from(NAMES_MAGIC);
+ data.extend_from_slice(&id);
+ for (offset, name) in names {
+ data.extend_from_slice(&offset.to_le_bytes());
+ data.extend_from_slice(&(name.len().min(usize::from(u16::MAX)) as u16).to_le_bytes());
+ data.extend_from_slice(&name.as_bytes()[..name.len().min(usize::from(u16::MAX))]);
+ }
+ let partial = path.with_extension("names.part");
+ fs::write(&partial, data)?;
+ fs::rename(&partial, &path)?;
+ Ok(())
+}
+
+/// Reads the start of every resource of an archive and returns the names
+/// of those that are models; a dictionary of models is named by its offset. `progress` gets the resources read and their
+/// number; setting `cancel` stops with what was found so far (`None`).
+pub fn scan_names(
+ rpf: &Rpf9,
+ entries: &[Entry],
+ cancel: &AtomicBool,
+ progress: &(dyn Fn(u64, u64) + Sync),
+) -> Option> {
+ // Recovery offsets and model names are not a TOC filename dictionary.
+ if rpf.has_toc() {
+ return None;
+ }
+ use rayon::prelude::*;
+ let resources: Vec<&Entry> = entries.iter().filter(|e| e.is_resource()).collect();
+ let (done, total) = (std::sync::atomic::AtomicU64::new(0), resources.len() as u64);
+ let found: Vec<(u64, String)> = resources
+ .par_iter()
+ .filter_map(|e| {
+ if cancel.load(Ordering::Relaxed) {
+ return None;
+ }
+ let n = done.fetch_add(1, Ordering::Relaxed) + 1;
+ if n.is_multiple_of(256) || n == total {
+ progress(n, total);
+ }
+ let start = rpf.read_start(e, NAME_PREFIX).ok()?;
+ // A dictionary of models has no name of its own.
+ let name = match rage_formats::drawable6::root(&start)? {
+ rage_formats::drawable6::Root::Dictionary => format!("dictionary_{:012x}.#dd", e.offset),
+ _ => rage_formats::drawable6::name(&start)?,
+ };
+ Some((e.offset, name))
+ })
+ .collect();
+ (!cancel.load(Ordering::Relaxed)).then_some(found)
+}
+
+/// What [`register`] reports to: the archive's file name with the bytes read
+/// and to read, or `None` when the scan is over.
+pub type Report = dyn Fn(Option<(&str, u64, u64)>) + Send + Sync;
+
+/// Makes [`Rpf9::entries`] use the stored index, and scan and store it when
+/// there is none. `report` gets the archive's file name with the bytes read
+/// and to read while scanning, and `None` when the scan is over.
+pub fn register(report: Arc) {
+ let _ = REPORT.set(Arc::clone(&report));
+ rpf9::set_indexer(Arc::new(move |rpf: &Rpf9| index(rpf, &AtomicBool::new(false), &*report)));
+ rpf9::set_namer(Arc::new(|rpf: &Rpf9| if rpf.has_toc() { None } else { load_names(rpf.path()) }));
+}
+
+static REPORT: OnceLock> = OnceLock::new();
+
+/// One lock per archive: two threads that want the same index (the window
+/// and the background run) scan it once; the second finds it stored.
+fn scan_lock(archive: &Path) -> Arc> {
+ static LOCKS: OnceLock>>>> = OnceLock::new();
+ let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
+ Arc::clone(locks.entry(archive.to_path_buf()).or_default())
+}
+
+/// The entries of an archive: from the stored index, or scanned and stored.
+fn index(rpf: &Rpf9, cancel: &AtomicBool, report: &Report) -> Result, RpfError> {
+ if rpf.has_toc() {
+ return rpf.entries().map(|entries| entries.as_ref().clone());
+ }
+ let lock = scan_lock(rpf.path());
+ let _scanning = lock.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(entries) = load_index(rpf.path()) {
+ return Ok(entries);
+ }
+ let name = rpf.path().file_name().unwrap_or_default().to_string_lossy().into_owned();
+ report(Some((&name, 0, rpf.data_len())));
+ let scanned = rpf.scan(cancel, &|done, total| report(Some((&name, done, total))));
+ report(None);
+ let entries = scanned?;
+ // The index only saves time: failing to store it is no error.
+ let _ = store_index(rpf.path(), &entries);
+ Ok(entries)
+}
+
+/// Finds and stores the names of an archive's models, unless they are
+/// stored already, and gives them to `rpf`.
+pub fn ensure_names(rpf: &Rpf9, entries: &[Entry], cancel: &AtomicBool, report: &Report) {
+ if rpf.has_toc() {
+ return;
+ }
+ let lock = scan_lock(rpf.path());
+ let _scanning = lock.lock().unwrap_or_else(|e| e.into_inner());
+ if load_names(rpf.path()).is_some() {
+ return;
+ }
+ let name = format!("{} (model names)", rpf.path().file_name().unwrap_or_default().to_string_lossy());
+ report(Some((&name, 0, 1)));
+ let found = scan_names(rpf, entries, cancel, &|done, total| report(Some((&name, done, total))));
+ report(None);
+ if let Some(found) = found {
+ // The names only help reading the list: failing to store them is no error.
+ let _ = store_names(rpf.path(), &found);
+ rpf.set_names(rpf9::Names::new(found));
+ }
+}
+
+/// The names for the archive a command works on: read from the models once
+/// if they are not stored yet. For programs without a background run.
+pub fn names_now(rpf: &Rpf9) {
+ if rpf.has_toc() {
+ return;
+ }
+ if let (Ok(entries), Some(report)) = (rpf.entries(), REPORT.get()) {
+ ensure_names(rpf, &entries, &AtomicBool::new(false), &**report);
+ }
+}
+
+/// The run started by [`index_in_background`], to stop it.
+static BACKGROUND: Mutex>> = Mutex::new(None);
+
+/// Stops the background run, if one is going.
+pub fn stop_background() {
+ if let Some(stop) = BACKGROUND.lock().unwrap_or_else(|e| e.into_inner()).take() {
+ stop.store(true, Ordering::Relaxed);
+ }
+}
+
+/// Indexes the archives below `game_dir` that have no stored index yet, one
+/// after the other (smallest first), on a thread of its own. Opening an
+/// archive meanwhile waits for its index or makes it. A run started before
+/// is stopped.
+pub fn index_in_background(game_dir: &Path) {
+ stop_background();
+ let stop = Arc::new(AtomicBool::new(false));
+ *BACKGROUND.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::clone(&stop));
+ let game_dir = game_dir.to_path_buf();
+ std::thread::spawn(move || {
+ let mut archives = Vec::new();
+ crate::detect::collect_archives(&game_dir, &["rpf"], &mut archives);
+ archives.retain(|p| Rpf9::file_is_rpf9(p));
+ archives.sort_by_key(|p| fs::metadata(p).map_or(0, |m| m.len()));
+ let quiet: &Report = &|_| {};
+ let report: &Report = REPORT.get().map_or(quiet, |r| &**r);
+ for archive in archives {
+ if stop.load(Ordering::Relaxed) {
+ break;
+ }
+ let Ok(rpf) = Rpf9::open(&archive) else { continue };
+ // No payload scan or recovery-cache load for an authoritative TOC.
+ if rpf.has_toc() {
+ continue;
+ }
+ let Ok(entries) = index(&rpf, &stop, report) else { continue };
+ ensure_names(&rpf, &entries, &stop, report);
+ }
+ });
+}
+
+/// Totals of a recovery view.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
+pub struct Coverage {
+ pub files: u64,
+ /// Bytes of the archive the files take.
+ pub stored: u64,
+ /// Bytes the files unpack to.
+ pub unpacked: u64,
+ /// Bytes of the data area that belong to no file: padding, and data that
+ /// is neither zlib, Bink 2 nor an audio container.
+ pub unread: u64,
+}
+
+pub fn coverage(rpf: &Rpf9, entries: &[Entry]) -> Coverage {
+ let stored: u64 = entries.iter().map(|e| e.stored).sum();
+ Coverage {
+ files: entries.len() as u64,
+ stored,
+ unpacked: entries.iter().map(|e| e.size).sum(),
+ unread: rpf.data_len().saturating_sub(stored),
+ }
+}
+
+/// Extracts from the recovery view into `out`: one file (`file`), or
+/// everything below folder `dir`. Files are written unpacked, straight to
+/// disk. Unreadable files are listed in `failures` and skipped.
+pub fn extract(
+ rpf: &Rpf9,
+ dir: &str,
+ file: Option,
+ out: &Path,
+ cancel: &AtomicBool,
+ progress: &mut dyn FnMut(&ExtractSummary, &str),
+) -> Result {
+ let entries = rpf.entries()?;
+ let mut summary = ExtractSummary { target: out.to_path_buf(), ..Default::default() };
+ let mut write = |i: usize, rel: &str, s: &mut ExtractSummary| -> Result<()> {
+ let target = out.join(vfs::safe_relative_path(rel).with_context(|| format!("unsafe path {rel}"))?);
+ if let Some(parent) = target.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ let mut writer = BufWriter::new(fs::File::create(&target)?);
+ match rpf.copy_to(&entries[i], &mut writer).and_then(|n| Ok(writer.flush().map(|()| n)?)) {
+ Ok(bytes) => {
+ s.files += 1;
+ s.bytes += bytes;
+ }
+ Err(e) => {
+ drop(writer);
+ let _ = fs::remove_file(&target);
+ s.failures.push(e.to_string());
+ }
+ }
+ progress(s, rel);
+ Ok(())
+ };
+ if let Some(i) = file {
+ let name = rpf.entry_name(&entries[i]);
+ let base = name.rsplit('/').next().unwrap_or(&name).to_owned();
+ write(i, &base, &mut summary)?;
+ summary.target = out.join(base);
+ return Ok(summary);
+ }
+ // Everything below `dir`, with its path from there on.
+ let prefix = if dir.is_empty() { String::new() } else { format!("{}/", dir.to_ascii_lowercase()) };
+ for (i, e) in entries.iter().enumerate() {
+ let name = rpf.entry_name(e);
+ let Some(rel) = name.strip_prefix(&prefix) else { continue };
+ if cancel.load(Ordering::Relaxed) {
+ summary.cancelled = true;
+ break;
+ }
+ write(i, rel, &mut summary)?;
+ }
+ Ok(summary)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use flate2::Compression;
+ use flate2::write::ZlibEncoder;
+
+ fn archive(dir: &Path) -> PathBuf {
+ let mut data = vec![0u8; 0x40];
+ data[..4].copy_from_slice(b"9FPR");
+ data[4..8].copy_from_slice(&0x40u32.to_le_bytes());
+ for text in [&b" "[..], b"PSIN\x00\x01binary"] {
+ let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
+ enc.write_all(text).unwrap();
+ data.extend(enc.finish().unwrap());
+ data.resize(data.len().next_multiple_of(16), 0);
+ }
+ let path = dir.join("test.rpf");
+ fs::write(&path, data).unwrap();
+ path
+ }
+
+ fn temp(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("openrage-app-rpf9-{}-{name}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn the_index_is_stored_and_dropped_when_the_archive_changes() {
+ let dir = temp("index");
+ let path = archive(&dir);
+ let rpf = Rpf9::open(&path).unwrap();
+ let entries = rpf.scan(&AtomicBool::new(false), &|_, _| {}).unwrap();
+ assert_eq!(entries.len(), 2);
+ let index = dir.join("test.idx");
+ assert_eq!(load_index_from(&index, &path), None);
+ store_index_to(&index, &path, &entries).unwrap();
+ assert_eq!(load_index_from(&index, &path).as_deref(), Some(&entries[..]));
+ let c = coverage(&rpf, &entries);
+ assert_eq!((c.files, c.unpacked), (2, 25 + 12));
+ assert_eq!(c.stored + c.unread, rpf.data_len());
+
+ let mut longer = fs::read(&path).unwrap();
+ longer.extend([0u8; 16]);
+ fs::write(&path, longer).unwrap();
+ assert_eq!(load_index_from(&index, &path), None);
+ fs::remove_dir_all(dir).unwrap();
+ }
+
+ #[test]
+ fn extracts_a_folder_and_a_single_file() {
+ let dir = temp("extract");
+ let path = archive(&dir);
+ let rpf = Rpf9::open(&path).unwrap();
+ rpf.set_entries(rpf.scan(&AtomicBool::new(false), &|_, _| {}).unwrap());
+ let quiet = AtomicBool::new(false);
+
+ let all = extract(&rpf, "", None, &dir.join("all"), &quiet, &mut |_, _| {}).unwrap();
+ assert_eq!((all.files, all.failures.len()), (2, 0));
+ assert_eq!(fs::read(dir.join("all/xml/000000000040.xml")).unwrap(), b" ");
+
+ let psin = extract(&rpf, "PSIN", None, &dir.join("psin"), &quiet, &mut |_, _| {}).unwrap();
+ assert_eq!(psin.files, 1);
+ assert!(
+ fs::read_dir(dir.join("psin"))
+ .unwrap()
+ .flatten()
+ .all(|f| f.file_name().to_string_lossy().ends_with(".psin"))
+ );
+
+ let one = extract(&rpf, "", Some(0), &dir.join("one"), &quiet, &mut |_, _| {}).unwrap();
+ assert_eq!(one.target, dir.join("one/000000000040.xml"));
+ assert!(one.target.is_file());
+ fs::remove_dir_all(dir).unwrap();
+ }
+}
diff --git a/crates/openrage-cli/src/cli.rs b/crates/openrage-cli/src/cli.rs
index 13ea834..3c6971a 100644
--- a/crates/openrage-cli/src/cli.rs
+++ b/crates/openrage-cli/src/cli.rs
@@ -232,6 +232,35 @@ pub(crate) enum Command {
#[arg(long, conflicts_with_all = ["textures", "models", "text", "meta", "audio"])]
anims: bool,
},
+ /// Inspect an RPF9 archive from the analysed Xbox Series/Scarlett build.
+ ///
+ /// Header inspection needs only the archive. With --exe, OpenRAGE takes
+ /// TFIT material from your own executable and reads the encrypted TOC.
+ /// Entries use stored hashes; --extract decrypts and decompresses supported files.
+ Rpf9 {
+ path: PathBuf,
+ /// Xbox Series/Scarlett PE from the analysed 1.0.2.1 build.
+ #[arg(long)]
+ exe: Option,
+ /// Enter a directly stored nested archive by index; repeat for deeper levels.
+ #[arg(long, requires = "exe")]
+ nested: Vec,
+ /// Candidate paths, one per line (<=8MiB), matched against native name hashes.
+ #[arg(long, requires_all = ["exe", "list"])]
+ names: Option,
+ /// List logical entries, stored hashes and physical extents.
+ #[arg(long, requires = "exe")]
+ list: bool,
+ /// Export one logical entry verbatim, including stored padding.
+ #[arg(long, requires_all = ["exe", "output"], conflicts_with = "extract")]
+ extract_raw: Option,
+ /// Decrypt and decompress one logical entry to --output.
+ #[arg(long, requires_all = ["exe", "output"], conflicts_with = "extract_raw")]
+ extract: Option,
+ /// Destination for an export; an existing file is never replaced.
+ #[arg(long, requires = "exe")]
+ output: Option,
+ },
/// Show facts about a Scaleform movie (.gfx) or a Bink video (.bik).
Media {
path: String,
@@ -379,6 +408,23 @@ pub(crate) enum Command {
#[arg(short = 'o', long, visible_alias = "out")]
export: Option,
},
+ /// GTA VI: count the textures of a texture pool (.ttpf) and optionally export them as PNG.
+ Ttpf {
+ /// The pool file.
+ path: PathBuf,
+ /// Export the textures into this folder as .png, named by their number.
+ #[arg(short = 'o', long, visible_alias = "out")]
+ export: Option,
+ /// The first texture to read.
+ #[arg(long, default_value_t = 0)]
+ from: usize,
+ /// How many textures to read (default: all).
+ #[arg(long)]
+ count: Option,
+ /// Read the largest mip level that is at most this many pixels wide and high.
+ #[arg(long)]
+ max_side: Option,
+ },
/// List the textures of a texture dictionary (.ytd) and optionally export them.
Textures {
/// Virtual path of the .ytd file.
diff --git a/crates/openrage-cli/src/cmd/archive.rs b/crates/openrage-cli/src/cmd/archive.rs
index 471180c..b29e2f1 100644
--- a/crates/openrage-cli/src/cmd/archive.rs
+++ b/crates/openrage-cli/src/cmd/archive.rs
@@ -161,6 +161,32 @@ pub(crate) fn cmd_ls(game_dir: &Path, path: &str, recursive: bool, keys: Option<
print_rpf8_entry(&mut out, &rpf, i, name.rsplit('/').next().unwrap_or(&name));
}
}
+ Node::Rpf9File(rpf, i) => {
+ let entries = rpf.entries()?;
+ print_rpf9_entry(&mut out, &entries[i], &rpf.entry_name(&entries[i]));
+ }
+ Node::Rpf9Dir(rpf, dir) => {
+ let entries = rpf.entries()?;
+ openrage_app::rpf9::names_now(&rpf);
+ if recursive {
+ let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
+ for e in entries.iter() {
+ let name = rpf.entry_name(e);
+ if let Some(rel) = name.strip_prefix(&prefix) {
+ print_rpf9_entry(&mut out, e, rel);
+ }
+ }
+ } else {
+ let (dirs, files) = rpf.list_dir(&entries, &dir);
+ for d in dirs {
+ ls_row(&mut out, "dir", None, "", &d, true);
+ }
+ for i in files {
+ let name = rpf.entry_name(&entries[i]);
+ print_rpf9_entry(&mut out, &entries[i], name.rsplit('/').next().unwrap_or(&name));
+ }
+ }
+ }
Node::Gta4File(a, id) => print_gta4_entry(&mut out, &a, id, &a.entry_path(id)),
Node::Gta4Dir(a, dir) => {
if recursive {
@@ -232,6 +258,54 @@ pub(crate) fn cmd_info(game_dir: &Path, path: &str, keys: Option>)
outln!("Folder: {dir}");
}
}
+ Node::Rpf9Dir(rpf, dir) => {
+ outln!("Archive: {}", rpf.display_name());
+ outln!("Format: RPF9 (Grand Theft Auto VI)");
+ outln!("Size: {} ({} bytes)", human(rpf.size()), rpf.size());
+ outln!(
+ "Table: {}",
+ if rpf.has_toc() { "decrypted; exact logical entries" } else { "encrypted; recovery view" }
+ );
+ outln!("Data: from offset {:#x}, {}", rpf.header().data_offset, human(rpf.data_len()));
+ // The archive itself is described without reading all of it.
+ let known = rpf.loaded().or_else(|| openrage_app::rpf9::load_index(rpf.path()).map(Arc::new));
+ let entries = if dir.is_empty() { known } else { Some(rpf.entries()?) };
+ match entries {
+ Some(entries) => {
+ let c = openrage_app::rpf9::coverage(&rpf, &entries);
+ outln!(
+ "Entries: {} files, {} in the archive, {} unpacked",
+ c.files,
+ human(c.stored),
+ human(c.unpacked)
+ );
+ if !rpf.has_toc() {
+ outln!(
+ "Not read: {} (padding, and data that is neither zlib, Bink 2 nor an audio container)",
+ human(c.unread)
+ );
+ }
+ }
+ None => outln!("Recovered: not indexed yet; `openrage ls` on the archive reads all of it once"),
+ }
+ if !dir.is_empty() {
+ outln!("Folder: {dir}");
+ }
+ }
+ Node::Rpf9File(rpf, i) => {
+ let entries = rpf.entries()?;
+ let e = &entries[i];
+ outln!("Path: {}/{}", rpf.display_name(), rpf.entry_name(e));
+ outln!("Kind: {}", if rpf.has_toc() { "TOC entry" } else { "recovered file" });
+ outln!("Offset: {:#x}", e.offset);
+ outln!("Size: {} ({} on disk)", human(e.size), human(e.stored));
+ match e.kind {
+ rage_rpf::rpf9::Kind::Zlib => outln!("Stored as: {} zlib stream(s)", e.streams),
+ rage_rpf::rpf9::Kind::Bink2 => outln!("Stored as: Bink 2 video"),
+ rage_rpf::rpf9::Kind::Awc => outln!("Stored as: audio container"),
+ rage_rpf::rpf9::Kind::Toc { index, .. } => outln!("TOC entry: {index}"),
+ }
+ }
Node::Rpf8File(rpf, i) => {
let e = &rpf.entries().expect("entries")[i];
outln!("Path: {}/{}", rpf.display_name(), rpf.entry_name(i));
@@ -303,6 +377,20 @@ pub(crate) fn report_rpf8_extract(rpf: &rage_rpf::Rpf8, dir: &str, file: Option<
extraction_result(s.failures.len())
}
+pub(crate) fn report_rpf9_extract(rpf: &rage_rpf::Rpf9, dir: &str, file: Option, out: &Path) -> Result<()> {
+ let s = openrage_app::rpf9::extract(rpf, dir, file, out, &AtomicBool::new(false), &mut |_, _| {})?;
+ for f in &s.failures {
+ eprintln!("warning: {f}");
+ }
+ outln!("{} file(s) ({}) extracted to {}, {} failed", s.files, human(s.bytes), out.display(), s.failures.len());
+ extraction_result(s.failures.len())
+}
+
+/// One recovered file of a GTA VI archive.
+pub(crate) fn print_rpf9_entry(out: &mut Rows, e: &rage_rpf::rpf9::Entry, name: &str) {
+ ls_row(out, "file", Some(e.size), "", name, false);
+}
+
/// Extraction goes on past single failures, but the command still fails then,
/// so scripts notice.
pub(crate) fn extraction_result(failures: usize) -> Result<()> {
@@ -336,6 +424,8 @@ pub(crate) fn cmd_extract(
Node::ArchiveFile(rpf, id) | Node::ArchiveDir(rpf, id) => (rpf, id),
Node::Rpf8File(rpf, i) => return report_rpf8_extract(&rpf, "", Some(i), out),
Node::Rpf8Dir(rpf, dir) => return report_rpf8_extract(&rpf, &dir, None, out),
+ Node::Rpf9File(rpf, i) => return report_rpf9_extract(&rpf, "", Some(i), out),
+ Node::Rpf9Dir(rpf, dir) => return report_rpf9_extract(&rpf, &dir, None, out),
Node::Gta4Dir(a, id) | Node::Gta4File(a, id) => {
let s = openrage_app::gta4::extract(&a, id, out, &AtomicBool::new(false), &mut |_, _| {})?;
for f in &s.failures {
diff --git a/crates/openrage-cli/src/cmd/mod.rs b/crates/openrage-cli/src/cmd/mod.rs
index a7ebbe7..cd6a192 100644
--- a/crates/openrage-cli/src/cmd/mod.rs
+++ b/crates/openrage-cli/src/cmd/mod.rs
@@ -7,6 +7,7 @@ mod oiv;
mod openformats;
mod plugin;
mod rdr2;
+mod rpf9;
mod search;
mod verify;
mod verify_gta4;
@@ -20,6 +21,7 @@ pub(crate) use oiv::*;
pub(crate) use openformats::*;
pub(crate) use plugin::*;
pub(crate) use rdr2::*;
+pub(crate) use rpf9::*;
pub(crate) use search::*;
pub(crate) use verify::*;
pub(crate) use verify_gta4::*;
diff --git a/crates/openrage-cli/src/cmd/rpf9.rs b/crates/openrage-cli/src/cmd/rpf9.rs
new file mode 100644
index 0000000..5282367
--- /dev/null
+++ b/crates/openrage-cli/src/cmd/rpf9.rs
@@ -0,0 +1,115 @@
+//! Experimental Scarlett RPF9 inspection.
+
+use crate::*;
+
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn cmd_rpf9(
+ path: &Path,
+ exe: Option<&Path>,
+ nested: &[u32],
+ names: Option<&Path>,
+ list: bool,
+ extract_raw: Option,
+ extract: Option,
+ output: Option<&Path>,
+) -> Result<()> {
+ use rage_rpf::rpf9::{Archive, read_header};
+
+ anyhow::ensure!(
+ output.is_none() || extract_raw.is_some() || extract.is_some(),
+ "--output requires --extract or --extract-raw"
+ );
+ let (header, file_size) = read_header(path).with_context(|| format!("reading {}", path.display()))?;
+ outln!("RPF9 {}", path.display());
+ outln!(" size: {file_size:#x}");
+ outln!(" archive id: {:#018x}", header.archive_id);
+ outln!(" entries: {}", header.entry_count);
+ outln!(" metadata: {:#x}..{:#x}", rage_rpf::rpf9::HEADER_SIZE, header.metadata_end);
+ outln!(
+ " region B: {:#x}..{:#x} (mode {}, index width {})",
+ header.region_b_offset,
+ header.metadata_end,
+ header.region_b_mode,
+ header.index_width
+ );
+ outln!(" trailer size: {:#x}", header.trailer_size);
+ outln!(" profile tag: {:#010x}", header.profile_tag);
+ outln!(" crypto profile: {}", header.crypto_profile);
+
+ let Some(exe) = exe else {
+ outln!(" metadata: encrypted (pass --exe to decrypt the TOC)");
+ return Ok(());
+ };
+ let extracted = rage_rpf::rpf9_exe::extract_scarlett_1_0_2_1(exe)
+ .with_context(|| format!("extracting RPF9 material from {}", exe.display()))?;
+ let mut archive = Archive::open(path, &extracted)?;
+ for &index in nested {
+ archive = archive.open_child(index, &extracted).with_context(|| format!("opening nested entry {index}"))?;
+ outln!(
+ " nested entry {index}: archive base {:#x}, {} entries",
+ archive.base_offset,
+ archive.header.entry_count
+ );
+ }
+ outln!(" TOC: {} entries, key selector {:#x}", archive.metadata.entries.len(), archive.metadata.key_selector);
+ let wanted = archive.metadata.entries.iter().filter_map(|e| e.name_hash).collect();
+ let names = names.map(|p| rage_rpf::rpf9::NameIndex::load_candidates(p, &wanted)).transpose()?;
+ let mut named = 0;
+ if list {
+ outln!(" index hash offset stored unpacked flags crypto");
+ for entry in &archive.metadata.entries {
+ match &entry.extent {
+ Some(e) => outln!(
+ " {:5} {:016x} {:012x} {:012x} {:012x} {:06x} {}",
+ entry.index,
+ entry.hash,
+ e.offset,
+ e.stored_size,
+ e.unpacked_size,
+ e.flags,
+ entry.has_crypto_descriptor
+ ),
+ None => outln!(" {:5} {:016x} unsupported storage descriptor", entry.index, entry.hash),
+ }
+ if let Some(hash) = entry.name_hash
+ && let Some(names) = &names
+ {
+ let candidates: Vec<_> = names.candidates(hash).collect();
+ if !candidates.is_empty() {
+ named += 1;
+ outln!(" matched path ({hash:016x}): {}", candidates.join(" | "));
+ }
+ }
+ }
+ }
+ if let Some(index) = extract_raw.or(extract) {
+ let entry = archive.metadata.entries.get(index as usize).context("entry index out of bounds")?;
+ anyhow::ensure!(entry.extent.is_some(), "entry has no supported physical extent");
+ let output = output.context("export requires --output")?;
+ let mut file = std::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(output)
+ .with_context(|| format!("creating {}", output.display()))?;
+ let result = if extract_raw.is_some() {
+ archive.copy_raw(index, &mut file)
+ } else {
+ archive.copy_decoded(index, &extracted, &mut file)
+ };
+ let copied = match result {
+ Ok(copied) => copied,
+ Err(error) => {
+ drop(file);
+ // This invocation exclusively created the output. Do not leave
+ // a partial export looking like a successfully decoded file.
+ std::fs::remove_file(output)
+ .with_context(|| format!("removing incomplete {} after {error}", output.display()))?;
+ return Err(error.into());
+ }
+ };
+ let kind = if extract_raw.is_some() { "stored" } else { "decoded" };
+ outln!(" exported {copied} {kind} bytes to {}", output.display());
+ }
+ outln!(" {named} entries matched candidate paths; extensions may be absent from the hashed path");
+ Ok(())
+}
diff --git a/crates/openrage-cli/src/cmd/view.rs b/crates/openrage-cli/src/cmd/view.rs
index 0f501a6..40a8dc8 100644
--- a/crates/openrage-cli/src/cmd/view.rs
+++ b/crates/openrage-cli/src/cmd/view.rs
@@ -491,6 +491,49 @@ pub(crate) fn cmd_audio(game_dir: &Path, path: &str, export: Option<&Path>, keys
Ok(())
}
+/// GTA VI: what a texture pool holds, and its textures as PNG.
+pub(crate) fn cmd_ttpf(
+ path: &Path,
+ export: Option<&Path>,
+ from: usize,
+ count: Option,
+ max_side: Option,
+) -> Result<()> {
+ let pool = rage_formats::ttpf::Pool::open(path)?;
+ outln!("{}: {} textures", path.display(), pool.len());
+ if let Some(dir) = export {
+ fs::create_dir_all(dir)?;
+ }
+ let started = Instant::now();
+ let (mut read, mut full) = (0u32, 0u32);
+ let mut skipped: std::collections::BTreeMap = Default::default();
+ for index in (from..pool.len()).take(count.unwrap_or(usize::MAX)) {
+ let d = *pool.descriptor(index).context("texture")?;
+ let texture = match pool.texture(index, max_side) {
+ Ok(t) => t,
+ Err(e) => {
+ *skipped.entry(e.to_string()).or_default() += 1;
+ continue;
+ }
+ };
+ read += 1;
+ full += u32::from(texture.width == d.width && texture.height == d.height);
+ let Some(dir) = export else { continue };
+ match texture.to_rgba() {
+ Some(rgba) => fs::write(
+ dir.join(format!("{index:06}.png")),
+ rage_formats::png(texture.width, texture.height, &rgba)?,
+ )?,
+ None => *skipped.entry(format!("no decoder for format {}", texture.format.name())).or_default() += 1,
+ }
+ }
+ outln!("Read: {read} ({full} at full size) in {} ms", started.elapsed().as_millis());
+ for (reason, n) in skipped {
+ outln!("Not read: {n} — {reason}");
+ }
+ Ok(())
+}
+
pub(crate) fn cmd_xml(
game_dir: &Path,
path: &str,
diff --git a/crates/openrage-cli/src/main.rs b/crates/openrage-cli/src/main.rs
index 5fbedd6..6c9712c 100644
--- a/crates/openrage-cli/src/main.rs
+++ b/crates/openrage-cli/src/main.rs
@@ -107,6 +107,10 @@ fn run() -> Result<()> {
return Ok(());
}
+ if let Command::Ttpf { path, export, from, count, max_side } = &cli.command {
+ return cmd_ttpf(path, export.as_deref(), *from, *count, *max_side);
+ }
+
if let Command::Rpf8 { path, list, textures, models, text, meta, rebuild, audio, anims } = &cli.command {
let checks = Checks {
textures: *textures,
@@ -119,6 +123,18 @@ fn run() -> Result<()> {
};
return cmd_rpf8(path, *list, checks);
}
+ if let Command::Rpf9 { path, exe, nested, names, list, extract_raw, extract, output } = &cli.command {
+ return cmd_rpf9(
+ path,
+ exe.as_deref(),
+ nested,
+ names.as_deref(),
+ *list,
+ *extract_raw,
+ *extract,
+ output.as_deref(),
+ );
+ }
// Managing plugins needs no game; previews and actions use it when there is one.
if let Command::Plugin(cmd) = &cli.command
&& (game_dir.is_none()
@@ -159,10 +175,31 @@ fn run() -> Result<()> {
eprintln!("warning: {e}");
None
});
+ // GTA VI archives are read through once to find their files; say so.
+ openrage_app::rpf9::register(Arc::new(|step| {
+ use std::io::IsTerminal;
+ static SHOWN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
+ let err = std::io::stderr();
+ match step {
+ Some((name, 0, _)) => {
+ eprintln!("Indexing {name}: reading the whole archive once, the result is kept for next time.");
+ }
+ Some((_, done, total)) if err.is_terminal() && total > 0 => {
+ let percent = done * 100 / total;
+ if SHOWN.swap(percent, std::sync::atomic::Ordering::Relaxed) != percent {
+ eprint!("\r{percent:>3} %");
+ }
+ }
+ None if err.is_terminal() => eprint!("\r \r"),
+ _ => {}
+ }
+ }));
match cli.command {
Command::Keys { .. }
| Command::Rpf8 { .. }
+ | Command::Rpf9 { .. }
+ | Command::Ttpf { .. }
| Command::Rdr2Keys { .. }
| Command::Rdr2Names { .. }
| Command::Licenses { .. } => {
diff --git a/crates/openrage-gui/src/badges.rs b/crates/openrage-gui/src/badges.rs
index fefc290..819fe7f 100644
--- a/crates/openrage-gui/src/badges.rs
+++ b/crates/openrage-gui/src/badges.rs
@@ -125,7 +125,7 @@ fn known_name(ext: &str) -> &'static str {
"awc" => "Audio container",
"gxt2" | "gxt" => "Text table",
"gfx" => "Scaleform movie",
- "bik" => "Bink video",
+ "bik" | "bk2" => "Bink video",
"nametable" => "Name table",
"ugc" => "UGC (JSON)",
"orp" => "OpenRAGE plugin",
diff --git a/crates/openrage-gui/src/browser.rs b/crates/openrage-gui/src/browser.rs
index 5e090dc..b7baa51 100644
--- a/crates/openrage-gui/src/browser.rs
+++ b/crates/openrage-gui/src/browser.rs
@@ -82,6 +82,8 @@ pub enum Location {
Archive(Arc, EntryId),
/// A folder inside a Red Dead Redemption 2 archive (read-only).
Rpf8(Arc, String),
+ /// A folder of the recovery view of a GTA VI archive (read-only).
+ Rpf9(Arc, String),
/// A folder inside a GTA IV archive (`.img`, RPF2/RPF3; read-only).
Gta4(Arc, rage_rpf::Gta4EntryId),
/// Results of a search; `summary` describes hash lookups etc.
@@ -119,6 +121,71 @@ pub fn is_texture_dict(name: &str) -> bool {
lower.ends_with(".ytd") || lower.ends_with(".ypt") || lower.ends_with(".wtd")
}
+/// GTA VI texture pools (`.ttpf`): they open as folders of [`POOL_PAGE`]
+/// textures each.
+pub fn is_texture_pool(name: &str) -> bool {
+ name.to_ascii_lowercase().ends_with(".ttpf")
+}
+
+/// Textures per folder of a texture pool: as many as are read at once.
+const POOL_PAGE: usize = 64;
+
+/// For `…/pool.ttpf/000128-000191`: the pool's path and the first texture.
+fn pool_page(vpath: &str) -> Option<(&str, usize)> {
+ let (pool, page) = vpath.rsplit_once('/')?;
+ let (from, to) = page.split_once('-')?;
+ let numeric = |s: &str| s.len() == 6 && s.bytes().all(|b| b.is_ascii_digit());
+ (is_texture_pool(pool) && numeric(from) && numeric(to)).then(|| Some((pool, from.parse().ok()?))).flatten()
+}
+
+fn pool_error(vpath: &str, e: rage_formats::ttpf::TtpfError) -> RpfError {
+ RpfError::BadResource { path: vpath.to_owned(), reason: e.to_string() }
+}
+
+/// A texture pool: its pages as folders.
+fn list_pool(vpath: String, file: &Path, origin: Origin) -> Result {
+ let pool = rage_formats::ttpf::Pool::open(file).map_err(|e| pool_error(&vpath, e))?;
+ let items = (0..pool.len())
+ .step_by(POOL_PAGE)
+ .map(|from| {
+ let to = (from + POOL_PAGE).min(pool.len()) - 1;
+ Item {
+ name: format!("{from:06}-{to:06}"),
+ kind: ItemKind::Dir,
+ size: 0,
+ info: format!("{} textures", to - from + 1),
+ entry: None,
+ vpath: None,
+ mark: None,
+ detail: None,
+ }
+ })
+ .collect();
+ Ok(Listing { vpath, origin, location: Location::Disk(file.to_path_buf()), items })
+}
+
+/// A page of a texture pool as a texture dictionary (read-only). Textures
+/// that cannot be read are left out and counted in the dictionary's errors.
+fn list_pool_page(vpath: String, file: &Path, from: usize, origin: Origin) -> Result {
+ let pool = rage_formats::ttpf::Pool::open(file).map_err(|e| pool_error(&vpath, e))?;
+ let (mut textures, mut errors) = (Vec::new(), Vec::new());
+ for index in (from..pool.len()).take(POOL_PAGE) {
+ match pool.texture(index, None) {
+ Ok(t) => textures.push(t),
+ Err(e) => errors.push(format!("{index:06}: {e}")),
+ }
+ }
+ let dict = rage_formats::ytd::TextureDictionary {
+ textures,
+ errors,
+ layout: rage_formats::ytd::Layout::Enhanced,
+ version: 0,
+ root: Vec::new(),
+ stored: Vec::new(),
+ };
+ Ok(texture_listing(vpath, dict, origin, true))
+}
+
/// Particle dictionaries open like texture dictionaries, read-only.
pub fn is_particles(name: &str) -> bool {
name.to_ascii_lowercase().ends_with(".ypt")
@@ -244,6 +311,17 @@ pub fn list(
let (listing, _) = list(game_dir, &dict_path, keys, overlay)?;
return Ok((listing, Some(last_segment(&vpath))));
}
+ // `…/pool.ttpf/000000-000063`: a page of a GTA VI texture pool.
+ Err(_) if pool_page(&vpath).is_some() => {
+ let (pool, from) = pool_page(&vpath).unwrap_or_default();
+ let (Node::PlainFile(file), origin) = resolve(pool)? else { return Err(RpfError::NotFound(vpath)) };
+ return Ok((list_pool_page(vpath.clone(), &file, from, origin)?, None));
+ }
+ // `…/pool.ttpf/000000-000063/000012`: that page, with the texture selected.
+ Err(_) if parent(&vpath).is_some_and(|p| pool_page(&p).is_some()) => {
+ let (listing, _) = list(game_dir, &parent(&vpath).unwrap_or_default(), keys, overlay)?;
+ return Ok((listing, Some(last_segment(&vpath))));
+ }
// `…/model/textures`: the textures inside a model (GTA IV .wdr, GTA V .ydr/.yft/.ydd).
Err(RpfError::NotFound(_)) if model_of_textures(&vpath).is_some() => {
let model = model_of_textures(&vpath).unwrap_or_default();
@@ -297,6 +375,13 @@ pub fn list(
.map_err(|e| RpfError::BadResource { path: vpath.clone(), reason: format!("{e:#}") })?;
Ok((audio_listing(vpath, awc, origin), None))
}
+ Node::PlainFile(file) if is_texture_pool(&vpath) => Ok((list_pool(vpath, &file, origin)?, None)),
+ Node::Rpf9Dir(rpf, dir) => Ok((list_rpf9(vpath, rpf, dir, origin)?, None)),
+ Node::Rpf9File(rpf, i) if is_audio(&vpath) => {
+ let awc = rage_formats::awc::Awc::parse(rpf.read_at(i)?, None)
+ .map_err(|e| RpfError::BadResource { path: vpath.clone(), reason: format!("{e:#}") })?;
+ Ok((audio_listing(vpath, awc, origin), None))
+ }
Node::Gta4Dir(a, dir) => Ok((list_gta4(vpath, a, dir, origin), None)),
// An RDR2 dictionary replaced in lml/replace: a loose RSC8 file.
Node::PlainFile(p) if is_texture_dict(&vpath) && rage_mods::overlay::is_rdr2(game_dir) => {
@@ -516,6 +601,7 @@ fn list_disk(vpath: String, dir: PathBuf, origin: Origin) -> Result, dir: String, origin: Origi
Listing { vpath, origin, location: Location::Rpf8(rpf, dir), items }
}
+/// A folder of the recovery view of a GTA VI archive: files named by their
+/// offset, in folders by what they look like.
+fn list_rpf9(vpath: String, rpf: Arc, dir: String, origin: Origin) -> Result {
+ let entries = rpf.entries()?;
+ let (dirs, files) = rpf.list_dir(&entries, &dir);
+ let item = |name: String, kind, size, info| Item {
+ name,
+ kind,
+ size,
+ info,
+ entry: None,
+ vpath: None,
+ mark: None,
+ detail: None,
+ };
+ let mut items: Vec- = dirs.into_iter().map(|name| item(name, ItemKind::Dir, 0, String::new())).collect();
+ for i in files {
+ let e = &entries[i];
+ let full = rpf.entry_name(e);
+ let info = match e.kind {
+ rage_rpf::rpf9::Kind::Bink2 => "video".to_owned(),
+ rage_rpf::rpf9::Kind::Awc => "sounds".to_owned(),
+ rage_rpf::rpf9::Kind::Toc { .. } => "TOC".to_owned(),
+ rage_rpf::rpf9::Kind::Zlib if e.streams > 1 => format!("{} chunks", e.streams),
+ rage_rpf::rpf9::Kind::Zlib => String::new(),
+ };
+ // The entries known to be models open in the viewer.
+ let kind = if e.extension() == "rpf" && rpf.has_toc() {
+ ItemKind::Archive
+ } else if openrage_app::models::is_model(&full) {
+ ItemKind::Resource
+ } else {
+ ItemKind::File
+ };
+ items.push(item(full.rsplit('/').next().unwrap_or(&full).to_owned(), kind, e.size, info));
+ }
+ Ok(Listing { vpath, origin, location: Location::Rpf9(rpf, dir), items })
+}
+
/// A folder of a GTA IV archive: its folders, files and resources.
fn list_gta4(vpath: String, a: Arc
, dir: rage_rpf::Gta4EntryId, origin: Origin) -> Listing {
let items = a
diff --git a/crates/openrage-gui/src/callbacks.rs b/crates/openrage-gui/src/callbacks.rs
index bb72f06..34cce21 100644
--- a/crates/openrage-gui/src/callbacks.rs
+++ b/crates/openrage-gui/src/callbacks.rs
@@ -173,9 +173,8 @@ fn wire_files(ui: &AppWindow) {
let video = with_app(|a| {
let listing = a.listing.as_ref()?;
let item = &listing.items[*a.visible.get(i as usize)?];
- item.name
- .to_ascii_lowercase()
- .ends_with(".bik")
+ let name = item.name.to_ascii_lowercase();
+ (name.ends_with(".bik") || name.ends_with(".bk2"))
.then(|| item.vpath.clone().unwrap_or_else(|| browser::join(&listing.vpath, &item.name)))
});
if let Some(vpath) = video {
@@ -687,6 +686,8 @@ fn wire_setup(ui: &AppWindow) {
});
let w = ui.as_weak();
ui.on_setup_run(move || with_ui(&w, run_setup));
+ let w = ui.as_weak();
+ ui.on_setup_leave(move || with_ui(&w, leave_setup));
}
pub(crate) fn theme_name(mode: i32) -> &'static str {
diff --git a/crates/openrage-gui/src/docs.rs b/crates/openrage-gui/src/docs.rs
index 7c8dee8..013f5bd 100644
--- a/crates/openrage-gui/src/docs.rs
+++ b/crates/openrage-gui/src/docs.rs
@@ -16,6 +16,7 @@ pub(crate) fn read_file(ui: &AppWindow, vpath: &str) -> anyhow::Result>
Ok(rpf.read(entry)?)
}
Node::Gta4File(a, id) => Ok(a.read(id)?),
+ Node::Rpf9File(rpf, i) => Ok(rpf.read_at(i)?),
_ => anyhow::bail!("{vpath} is not a file"),
}
}
@@ -53,8 +54,25 @@ pub(crate) fn open_text_file(ui: &AppWindow, vpath: String) {
open_text_data(ui, vpath, &data);
}
+/// A table of strings that each end with a zero byte (GTA VI keeps texts
+/// that way), one string per line; `None` for anything else.
+pub(crate) fn zero_ended_strings(data: &[u8]) -> Option> {
+ let text = std::str::from_utf8(data).ok()?;
+ let plain = |c: char| !c.is_control() || matches!(c, '\0' | '\t' | '\r' | '\n');
+ (text.contains('\0') && text.chars().all(plain)).then(|| {
+ let lines: Vec = text.trim_end_matches('\0').split('\0').map(|s| s.replace('\n', "\\n")).collect();
+ lines.join("\n").into_bytes()
+ })
+}
+
pub(crate) fn open_text_data(ui: &AppWindow, vpath: String, data: &[u8]) {
- match editor::Document::from_file(vpath.clone(), data) {
+ let opened = editor::Document::from_file(vpath.clone(), data).or_else(|e| {
+ let mut doc =
+ zero_ended_strings(data).and_then(|lines| editor::Document::from_bytes(vpath.clone(), &lines)).ok_or(e)?;
+ doc.locked_reason = "A table of strings, shown one per line for reading.".into();
+ Ok::<_, String>(doc)
+ });
+ match opened {
Ok(doc) => {
editor::open(ui, doc);
ui.set_status(SharedString::new());
diff --git a/crates/openrage-gui/src/extract_ui.rs b/crates/openrage-gui/src/extract_ui.rs
index 23e0fd5..54466f6 100644
--- a/crates/openrage-gui/src/extract_ui.rs
+++ b/crates/openrage-gui/src/extract_ui.rs
@@ -61,6 +61,24 @@ pub(crate) fn start_extract(ui: &AppWindow) {
});
return;
}
+ // GTA VI: the selected file or folder of the recovery view, or the whole folder.
+ let gta6 = with_app(|a| {
+ let listing = a.listing.as_ref()?;
+ let Location::Rpf9(rpf, dir) = &listing.location else { return None };
+ let item = a.selected.map(|s| &listing.items[s]);
+ let find = |name: &str| rpf.loaded().and_then(|entries| rpf.find(&entries, &browser::join(dir, name)));
+ Some(match item {
+ Some(item) if item.kind == ItemKind::Dir => (Arc::clone(rpf), browser::join(dir, &item.name), None),
+ Some(item) => (Arc::clone(rpf), dir.clone(), find(&item.name)),
+ None => (Arc::clone(rpf), dir.clone(), None),
+ })
+ });
+ if let Some((rpf, dir, file)) = gta6 {
+ spawn_extract(ui, move |out, cancel, progress| {
+ openrage_app::rpf9::extract(&rpf, &dir, file, out, cancel, progress)
+ });
+ return;
+ }
let target = with_app(|a| -> Result<(Arc, EntryId), String> {
let listing = a.listing.as_ref().ok_or("nothing to extract")?;
let item = a.selected.map(|s| &listing.items[s]);
diff --git a/crates/openrage-gui/src/main.rs b/crates/openrage-gui/src/main.rs
index de19007..6b1c0d7 100644
--- a/crates/openrage-gui/src/main.rs
+++ b/crates/openrage-gui/src/main.rs
@@ -156,6 +156,25 @@ fn main() -> anyhow::Result<()> {
}
let cfg = Config::load();
plugins::reload(&cfg);
+ // GTA VI archives are read through once to find their files: show how far that is.
+ let status = ui.as_weak();
+ openrage_app::rpf9::register(std::sync::Arc::new(move |step| {
+ static SHOWN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);
+ let text = match step {
+ Some((name, done, total)) => {
+ let percent = done * 100 / total.max(1);
+ if SHOWN.swap(percent, Ordering::Relaxed) == percent {
+ return;
+ }
+ format!("Indexing {name} (read once, then remembered)… {percent} %")
+ }
+ None => {
+ SHOWN.store(u64::MAX, Ordering::Relaxed);
+ String::new()
+ }
+ };
+ let _ = status.upgrade_in_event_loop(move |ui| ui.set_status(text.into()));
+ }));
let keys = load_keys().unwrap_or(None);
// Several games set up and none chosen as default: ask (after the window is up).
let known = installed_games(&cfg);
@@ -167,7 +186,9 @@ fn main() -> anyhow::Result<()> {
default.or_else(|| cfg.game_dir.clone().filter(|d| known.contains(d))).or_else(|| known.first().cloned())
};
let rdr2_ready = game_dir.as_deref().is_some_and(|d| {
- (is_rdr2_dir(d) && register_rdr2(d)) || (is_gta4_dir(d) && openrage_app::gta4::register(d).is_ok())
+ detect::is_gta6_dir(d)
+ || (is_rdr2_dir(d) && register_rdr2(d))
+ || (is_gta4_dir(d) && openrage_app::gta4::register(d).is_ok())
});
APP.with(|a| {
diff --git a/crates/openrage-gui/src/navigate.rs b/crates/openrage-gui/src/navigate.rs
index b23c5d4..eb4b73b 100644
--- a/crates/openrage-gui/src/navigate.rs
+++ b/crates/openrage-gui/src/navigate.rs
@@ -25,6 +25,12 @@ pub(crate) fn start_browsing(ui: &AppWindow) {
});
ui.set_window_title(title.into());
start_index_update(ui);
+ // GTA VI: its archives are read through once to find their files. That
+ // starts now, not when an archive is opened first.
+ match with_app(|a| a.game_dir.clone()).filter(|d| detect::is_gta6_dir(d)) {
+ Some(dir) => openrage_app::rpf9::index_in_background(&dir),
+ None => openrage_app::rpf9::stop_background(),
+ }
refresh_asi(ui);
refresh_tool_menu(ui);
refresh_undo(ui);
@@ -614,6 +620,15 @@ pub(crate) fn show_folder_info(ui: &AppWindow) {
),
]
}
+ Location::Rpf9(rpf, _) => {
+ let mut meta = vec![
+ kv("Type", "Recovered from a GTA VI archive"),
+ kv("Archive", rpf.display_name().rsplit('/').next().unwrap_or_default()),
+ ];
+ meta.extend(crate::preview::rpf9_archive_info(rpf));
+ meta.push(note("Read-only. Extract… saves the files unpacked."));
+ meta
+ }
Location::Gta4(a, _) => {
let mut meta = vec![kv("Type", "Inside a GTA IV archive")];
meta.extend(gta4_archive_info(a));
diff --git a/crates/openrage-gui/src/plugins_ui.rs b/crates/openrage-gui/src/plugins_ui.rs
index 30c8eb6..83ea02a 100644
--- a/crates/openrage-gui/src/plugins_ui.rs
+++ b/crates/openrage-gui/src/plugins_ui.rs
@@ -75,6 +75,7 @@ pub(crate) fn plugin_preview(
rpf.read(entry).ok()?
}
Node::Gta4File(a, id) if a.entry(id).size() <= MAX => a.read(id).ok()?,
+ Node::Rpf9File(rpf, i) if rpf.entries().ok()?.get(i)?.size <= MAX => rpf.read_at(i).ok()?,
_ => return None,
};
if !specific && rage_core::text::decode_text(&data, 4096).is_some() {
diff --git a/crates/openrage-gui/src/preview.rs b/crates/openrage-gui/src/preview.rs
index 62c9463..44ff241 100644
--- a/crates/openrage-gui/src/preview.rs
+++ b/crates/openrage-gui/src/preview.rs
@@ -65,6 +65,8 @@ pub(crate) enum PreviewSource {
Entry(Arc, EntryId),
/// A file in a Red Dead Redemption 2 archive (index into its entries).
Rpf8(Arc, usize),
+ /// A recovered file of a GTA VI archive (index into its entries).
+ Rpf9(Arc, usize),
/// A file in a GTA IV archive.
Gta4(Arc, rage_rpf::Gta4EntryId),
/// A texture of an opened texture dictionary (index into its textures).
@@ -127,6 +129,10 @@ pub(crate) fn select_row(ui: &AppWindow, row: usize) {
(Location::Rpf8(rpf, dir), _) if item.kind != ItemKind::Dir => {
rpf.find(&browser::join(dir, &item.name)).map(|i| PreviewSource::Rpf8(Arc::clone(rpf), i))
}
+ (Location::Rpf9(rpf, dir), _) if item.kind != ItemKind::Dir => rpf
+ .loaded()
+ .and_then(|entries| rpf.find(&entries, &browser::join(dir, &item.name)))
+ .map(|i| PreviewSource::Rpf9(Arc::clone(rpf), i)),
(Location::Gta4(a, dir), _) if item.kind != ItemKind::Dir => {
a.find_child(*dir, &item.name).map(|i| PreviewSource::Gta4(Arc::clone(a), i))
}
@@ -420,6 +426,8 @@ pub(crate) fn load_preview_text(source: PreviewSource, keys: Option load_preview_text(PreviewSource::DiskFile(p), keys),
Ok(Node::Rpf8File(rpf, i)) => rpf8_preview(&rpf, i),
Ok(Node::Rpf8Dir(..)) => (Meta::new(), String::new()),
+ Ok(Node::Rpf9File(rpf, i)) => rpf9_preview(&rpf, i),
+ Ok(Node::Rpf9Dir(rpf, dir)) if dir.is_empty() => (rpf9_archive_info(&rpf), String::new()),
Ok(Node::Gta4File(a, i)) => gta4_preview(&a, i),
Ok(Node::Gta4Dir(a, i)) if i == rage_rpf::Gta4Archive::ROOT => (gta4_archive_info(&a), String::new()),
Ok(Node::Gta4Dir(..)) => (Meta::new(), String::new()),
@@ -427,6 +435,7 @@ pub(crate) fn load_preview_text(source: PreviewSource, keys: Option (vec![kv("Error", e)], String::new()),
},
PreviewSource::Rpf8(rpf, i) => rpf8_preview(&rpf, i),
+ PreviewSource::Rpf9(rpf, i) => rpf9_preview(&rpf, i),
PreviewSource::Gta4(a, i) => gta4_preview(&a, i),
PreviewSource::Texture(..) => (Meta::new(), String::new()),
PreviewSource::DiskFile(path)
@@ -468,6 +477,31 @@ pub(crate) fn load_preview_text(source: PreviewSource, keys: Option (vec![kv("Error", e)], String::new()),
}
}
+ // GTA VI: a texture pool.
+ PreviewSource::DiskArchive(path) if browser::is_texture_pool(&path.to_string_lossy()) => {
+ match rage_formats::ttpf::Pool::open(&path) {
+ Ok(pool) => {
+ let plain = (0..pool.len()).filter(|i| pool.descriptor(*i).is_some_and(|d| d.is_2d())).count();
+ let meta = vec![
+ kv("Format", "Texture pool (GTA VI)"),
+ kv("Textures", grouped(pool.len())),
+ kv("Arrays, cube maps, volumes", grouped(pool.len() - plain)),
+ note(
+ "Opens as folders of 64 textures. Textures have no names here, only numbers. \
+ Arrays, cube maps and volumes are not read yet; textures packed with BCPack \
+ are shown from their largest level that is not.",
+ ),
+ ];
+ (meta, String::new())
+ }
+ Err(e) => (vec![kv("Error", e)], String::new()),
+ }
+ }
+ // GTA VI: RPF9. Described from its header and a stored index: no scan here.
+ PreviewSource::DiskArchive(path) if rage_rpf::Rpf9::file_is_rpf9(&path) => match rage_rpf::Rpf9::open(&path) {
+ Ok(rpf) => (rpf9_archive_info(&rpf), String::new()),
+ Err(e) => (vec![kv("Error", e)], String::new()),
+ },
// RDR2: RPF8, not RPF7.
PreviewSource::DiskArchive(path) if rage_rpf::Rpf8::file_is_rpf8(&path) => {
match rage_rpf::Rpf8::open_default(&path) {
@@ -768,6 +802,99 @@ pub(crate) fn gta4_preview(a: &rage_rpf::Gta4Archive, i: rage_rpf::Gta4EntryId)
}
}
+/// Overview of a GTA VI archive (RPF9): what was recovered, if it has been
+/// indexed already. Never starts the scan.
+pub(crate) fn rpf9_archive_info(rpf: &rage_rpf::Rpf9) -> Meta {
+ use openrage_app::extract::human_size;
+ let mut meta = vec![kv("Format", "RPF9 (GTA VI)"), kv("Data", human_size(rpf.data_len()))];
+ if rpf.has_toc() {
+ if let Some(entries) = rpf.loaded() {
+ meta.push(kv("TOC entries", grouped(entries.len())));
+ }
+ meta.push(note(
+ "Entries and sizes come from the decrypted table of contents. Unresolved names are shown as hashes.",
+ ));
+ return meta;
+ }
+ match rpf.loaded().or_else(|| openrage_app::rpf9::load_index(rpf.path()).map(Arc::new)) {
+ Some(entries) => {
+ let c = openrage_app::rpf9::coverage(rpf, &entries);
+ meta.push(kv("Recovered files", grouped(c.files as usize)));
+ meta.push(kv("Unpacked", human_size(c.unpacked)));
+ meta.push(kv("Not read", human_size(c.unread)));
+ }
+ None => meta.push(note(
+ "Not indexed yet: opening it reads the whole archive once, which takes a while for large ones.",
+ )),
+ }
+ meta.push(note(
+ "The table of contents is encrypted, so names and folders are unknown. Files are found in the data itself \
+ and named by their offset; data that is neither zlib, Bink 2 nor an audio container is not listed.",
+ ));
+ meta
+}
+
+/// Facts about a recovered file of a GTA VI archive, and the start of it as
+/// text or hex.
+pub(crate) fn rpf9_preview(rpf: &rage_rpf::Rpf9, i: usize) -> (Meta, String) {
+ let Some(entries) = rpf.loaded() else { return (Meta::new(), String::new()) };
+ let Some(e) = entries.get(i) else { return (Meta::new(), String::new()) };
+ let mut meta = vec![
+ kv("Offset", format!("0x{:x}", e.offset)),
+ kv("Stored", openrage_app::extract::human_size(e.stored)),
+ kv(
+ "Stored as",
+ match e.kind {
+ rage_rpf::rpf9::Kind::Bink2 => "Bink 2 video".to_owned(),
+ rage_rpf::rpf9::Kind::Awc => "audio container".to_owned(),
+ rage_rpf::rpf9::Kind::Zlib if e.streams > 1 => format!("{} zlib streams", e.streams),
+ rage_rpf::rpf9::Kind::Zlib => "zlib stream".to_owned(),
+ rage_rpf::rpf9::Kind::Toc { index, .. } => format!("TOC entry {index}"),
+ },
+ ),
+ ];
+ if matches!(e.kind, rage_rpf::rpf9::Kind::Bink2 | rage_rpf::rpf9::Kind::Awc) {
+ return (meta, String::new());
+ }
+ // The start is enough for a look; large files are not unpacked whole.
+ let mut start = Vec::new();
+ let mut limited = LimitedWriter { out: &mut start, left: 1 << 20 };
+ match rpf.copy_to(e, &mut limited) {
+ Ok(_) => {}
+ Err(_) if limited.left == 0 => meta.push(note("Showing the start; Extract… saves all of it.")),
+ Err(err) => {
+ meta.push(kv("Error", err));
+ return (meta, String::new());
+ }
+ }
+ // A start that was cut off ends in the middle of a string.
+ let whole = start.iter().rposition(|b| *b == 0).map_or(&start[..], |end| &start[..=end]);
+ let text = crate::docs::zero_ended_strings(whole);
+ (meta, preview::render(text.as_deref().unwrap_or(&start)))
+}
+
+/// Takes up to `left` bytes, then fails, which ends the unpacking.
+struct LimitedWriter<'a> {
+ out: &'a mut Vec,
+ left: usize,
+}
+
+impl std::io::Write for LimitedWriter<'_> {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result {
+ if self.left == 0 {
+ return Err(std::io::ErrorKind::WriteZero.into());
+ }
+ let n = buf.len().min(self.left);
+ self.out.extend_from_slice(&buf[..n]);
+ self.left -= n;
+ Ok(n)
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+}
+
/// Overview of an RDR2 archive (RPF8).
pub(crate) fn rpf8_archive_info(rpf: &rage_rpf::Rpf8) -> Meta {
let mut meta = vec![kv("Format", "RPF8")];
diff --git a/crates/openrage-gui/src/setup_ui.rs b/crates/openrage-gui/src/setup_ui.rs
index f93d451..c7dc2eb 100644
--- a/crates/openrage-gui/src/setup_ui.rs
+++ b/crates/openrage-gui/src/setup_ui.rs
@@ -4,7 +4,7 @@ use crate::*;
/// The games set up so far that are still installed.
pub(crate) fn installed_games(cfg: &Config) -> Vec {
- cfg.known_games().into_iter().filter(|d| detect::is_gta5_dir(d) || is_rdr2_dir(d) || is_gta4_dir(d)).collect()
+ cfg.known_games().into_iter().filter(|d| detect::is_game_dir(d)).collect()
}
thread_local! {
@@ -108,7 +108,9 @@ pub(crate) fn close_launcher() {
/// Opens a game that was set up before (from the chooser); `remember` makes it the default.
pub(crate) fn open_game(ui: &AppWindow, index: usize, remember: bool) {
let Some(dir) = with_app(|a| installed_games(&a.cfg).get(index).cloned()) else { return };
- let ready = if is_rdr2_dir(&dir) {
+ let ready = if detect::is_gta6_dir(&dir) {
+ true
+ } else if is_rdr2_dir(&dir) {
register_rdr2(&dir)
} else if is_gta4_dir(&dir) {
openrage_app::gta4::register(&dir).is_ok()
@@ -154,11 +156,15 @@ pub(crate) fn show_setup(ui: &AppWindow, can_cancel: bool) {
// A key blob that is gone (moved, or a temporary copy) is not offered again.
let magic = a.cfg.magic_path.as_ref().filter(|p| p.is_file());
ui.set_setup_magic_path(magic.map(|p| p.display().to_string()).unwrap_or_default().into());
- ui.set_setup_can_cancel(
- can_cancel
- && (a.keys.is_some() || rage_rpf::rpf8::has_default_keys() || rage_rpf::gta4::default_key().is_some())
- && a.game_dir.is_some(),
- );
+ // Closing goes back to a game that is open and readable.
+ let open = a.game_dir.as_deref().is_some_and(|d| {
+ detect::is_gta6_dir(d)
+ || a.keys.is_some()
+ || rage_rpf::rpf8::has_default_keys()
+ || rage_rpf::gta4::default_key().is_some()
+ });
+ ui.set_setup_can_cancel(can_cancel && open);
+ ui.set_setup_has_games(!installed_games(&a.cfg).is_empty());
});
let model: Vec = detected.into_iter().map(Into::into).collect();
ui.set_setup_detected(ModelRc::new(VecModel::from(model)));
@@ -173,12 +179,13 @@ pub(crate) fn show_folder_hint(ui: &AppWindow) {
let hint = if text.trim().is_empty() {
String::new()
} else if let Some(name) = detect::game_name(&dir) {
- format!("Found {name}. Press Set up to continue.")
+ if detect::is_gta6_dir(&dir) {
+ format!("Found {name}. Its archives open without keys, but without file names. Press Open to continue.")
+ } else {
+ format!("Found {name}. Press Open to continue.")
+ }
} else if dir.is_dir() {
- format!(
- "No supported game in {}: the folder must contain GTA5_Enhanced.exe, GTA5.exe, GTAIV.exe or RDR2.exe.",
- dir.display()
- )
+ format!("No supported game in {}. {NO_GAME}", dir.display())
} else {
format!("{} does not exist.", dir.display())
};
@@ -195,8 +202,43 @@ pub(crate) fn pick_path(w: Weak, file: bool, title: &'static str, app
});
}
+/// What a game folder must hold.
+const NO_GAME: &str =
+ "The folder must contain GTA5_Enhanced.exe, GTA5.exe, GTAIV.exe or RDR2.exe, or the archives of GTA VI.";
+
+/// Leaves a setup that cannot be closed: back to the list of games when there
+/// is one, otherwise out of OpenRAGE.
+pub(crate) fn leave_setup(ui: &AppWindow) {
+ if with_app(|a| installed_games(&a.cfg).is_empty()) {
+ let _ = slint::quit_event_loop();
+ } else {
+ ui.set_setup_visible(false);
+ ui.invoke_open_game_chooser(false);
+ }
+}
+
+/// Opens a game that needs no keys.
+fn open_without_keys(ui: &AppWindow, game_dir: PathBuf) {
+ let saved = with_app(|a| {
+ a.cfg.remember_game(&game_dir);
+ a.game_dir = Some(game_dir.clone());
+ a.cfg.game_dir = Some(game_dir);
+ a.cfg.save()
+ });
+ ui.set_setup_visible(false);
+ refresh_games(ui);
+ start_browsing(ui);
+ if let Err(e) = saved {
+ show_error(ui, format!("Could not save the settings: {e}"));
+ }
+}
+
pub(crate) fn run_setup(ui: &AppWindow) {
let game_dir = openrage_app::gta4::normalize_dir(&PathBuf::from(ui.get_setup_game_dir().trim()));
+ if detect::is_gta6_dir(&game_dir) {
+ open_without_keys(ui, game_dir);
+ return;
+ }
if is_gta4_dir(&game_dir) {
ui.set_setup_running(true);
ui.set_setup_log("Looking for the archive key in GTAIV.exe…".into());
@@ -235,25 +277,11 @@ pub(crate) fn run_setup(ui: &AppWindow) {
);
return;
}
- let saved = with_app(|a| {
- a.cfg.remember_game(&game_dir);
- a.game_dir = Some(game_dir.clone());
- a.cfg.game_dir = Some(game_dir);
- a.cfg.save()
- });
- ui.set_setup_visible(false);
- refresh_games(ui);
- start_browsing(ui);
- if let Err(e) = saved {
- show_error(ui, format!("Could not save the settings: {e}"));
- }
+ open_without_keys(ui, game_dir);
return;
}
if !detect::is_gta5_dir(&game_dir) {
- ui.set_setup_log(
- format!("{} does not contain GTA5_Enhanced.exe, GTA5.exe, GTAIV.exe or RDR2.exe.", game_dir.display())
- .into(),
- );
+ ui.set_setup_log(format!("No supported game in {}. {NO_GAME}", game_dir.display()).into());
return;
}
// Keys set up before that open this game: no scan, no key blob needed.
diff --git a/crates/openrage-gui/ui/app.slint b/crates/openrage-gui/ui/app.slint
index eed0511..632779d 100644
--- a/crates/openrage-gui/ui/app.slint
+++ b/crates/openrage-gui/ui/app.slint
@@ -1122,6 +1122,8 @@ export component AppWindow inherits Window {
in property setup-log;
in property setup-running;
in property setup-can-cancel;
+ // Other games are set up: leaving the setup goes back to their list.
+ in property setup-has-games;
callback navigate(string);
callback go-back();
@@ -1187,6 +1189,7 @@ export component AppWindow inherits Window {
callback setup-browse-magic();
callback setup-pick-detected(string);
callback setup-run();
+ callback setup-leave();
callback theme-changed(int);
// Accent color (View → Accent color): mode 0 style, 1 orange, 2 custom color.
callback accent-chosen(int, color);
@@ -3668,7 +3671,7 @@ export component AppWindow inherits Window {
height: 48px;
}
Text {
- text: @tr("OpenRAGE reads the archive keys from your own copy of GTA V. No keys or game files are included with OpenRAGE.");
+ text: @tr("Choose the folder of your game. OpenRAGE reads the archive keys from your own copy; no keys or game files are included. GTA VI archives open without keys.");
wrap: word-wrap;
color: Theme.text-muted;
}
@@ -3699,7 +3702,7 @@ export component AppWindow inherits Window {
text <=> root.setup-game-dir;
edited => { root.setup-game-dir-edited(); }
accessible-label: @tr("Game directory");
- placeholder-text: @tr("Folder containing GTA5_Enhanced.exe, GTA5.exe, GTAIV.exe or RDR2.exe");
+ placeholder-text: @tr("Folder of GTA V, GTA IV, Red Dead Redemption 2 or GTA VI");
}
Button {
text: @tr("Browse…");
@@ -3751,12 +3754,17 @@ export component AppWindow inherits Window {
indeterminate: true;
}
if root.setup-can-cancel: Button {
- text: @tr("Close");
+ text: @tr("Cancel");
enabled: !root.setup-running;
clicked => { root.setup-visible = false; }
}
+ if !root.setup-can-cancel: Button {
+ text: root.setup-has-games ? @tr("Back to the games") : @tr("Quit");
+ enabled: !root.setup-running;
+ clicked => { root.setup-leave(); }
+ }
Button {
- text: @tr("Derive keys");
+ text: @tr("Open");
primary: true;
enabled: !root.setup-running && root.setup-game-dir != "";
clicked => { root.setup-run(); }
diff --git a/crates/rage-formats/Cargo.toml b/crates/rage-formats/Cargo.toml
index 63b1c54..d43f1c9 100644
--- a/crates/rage-formats/Cargo.toml
+++ b/crates/rage-formats/Cargo.toml
@@ -12,6 +12,7 @@ png = "0.18"
texture2ddecoder = "0.1"
symphonia = { version = "0.6", default-features = false, features = ["mp3"] }
lewton = { version = "0.10", default-features = false }
+opus-rs = "0.1"
thiserror.workspace = true
roxmltree.workspace = true
flate2.workspace = true
diff --git a/crates/rage-formats/src/awc.rs b/crates/rage-formats/src/awc.rs
index c6a78c7..02f3a2a 100644
--- a/crates/rage-formats/src/awc.rs
+++ b/crates/rage-formats/src/awc.rs
@@ -21,6 +21,12 @@
//! a stream keeps each channel's headers in a chunk (`0x7F`) of a stream
//! named after the channel. The data is cut into 2048-byte units of Vorbis
//! packets, each with a 16-bit length.
+//!
+//! GTA VI keeps RDR2's layout with two more optional tables in front of the
+//! streams (flags `0x20` and `0x40`) and Opus instead of Vorbis: the same
+//! 2048-byte units of packets, always 48 kHz, mono or stereo (channel count
+//! at 29 of the format chunk). A format chunk counts samples of all channels
+//! together. The encoder's lookahead ([`OPUS_PRE_SKIP`] samples) is not stored.
use rage_core::bytes::LeRead;
@@ -64,6 +70,7 @@ pub enum Codec {
Pcm16,
Adpcm,
Vorbis,
+ Opus,
Other(u8),
}
@@ -73,6 +80,7 @@ impl Codec {
0 => Self::Pcm16,
4 => Self::Adpcm,
8 => Self::Vorbis,
+ 11 => Self::Opus,
other => Self::Other(other),
}
}
@@ -82,6 +90,7 @@ impl Codec {
Self::Pcm16 => "PCM".into(),
Self::Adpcm => "IMA ADPCM".into(),
Self::Vorbis => "Vorbis".into(),
+ Self::Opus => "Opus".into(),
Self::Other(c) => format!("codec {c}"),
}
}
@@ -106,6 +115,8 @@ pub struct Sound {
pub channel: Option,
/// Vorbis: where its three headers are (offset and size in the data).
pub headers: Option<(usize, usize)>,
+ /// Channels of a single sound (GTA VI's Opus sounds can be stereo).
+ pub channels: u8,
}
impl Sound {
@@ -177,6 +188,32 @@ impl Awc {
if flags & 1 != 0 {
o += 2 * count;
}
+ // GTA VI: two more tables, if only with them the chunk table ends
+ // where the header says the data starts.
+ let extra = if flags & 0x20 != 0 { (count + 1) * 4 } else { 0 } + if flags & 0x40 != 0 { 4 } else { 0 };
+ let table_end = |from: usize| -> Option {
+ let words = data.get(from..from + count * 4)?.as_chunks::<4>().0;
+ Some(from + count * 4 + words.iter().map(|w| usize::from(w[3] >> 5) * 8).sum::())
+ };
+ // Whether the chunks of a table that starts at `from` are inside the file.
+ let fits = |from: usize| -> bool {
+ let Some(end) = table_end(from) else { return false };
+ data.get(from + count * 4..end).is_some_and(|table| {
+ table.as_chunks::<8>().0.iter().all(|c| {
+ let v = u64::from_le_bytes(*c);
+ (v & 0x0FFF_FFFF) + ((v >> 28) & 0x0FFF_FFFF) <= data.len() as u64
+ })
+ })
+ };
+ let header_end = u32_at(&data, 12)? as usize;
+ // The tables' bytes read as stream words can add up to the same end
+ // by chance: then the chunks decide.
+ let gta6 =
+ extra > 0 && table_end(o + extra) == Some(header_end) && (table_end(o) != Some(header_end) || !fits(o));
+ if gta6 {
+ o += extra;
+ }
+ let rdr2 = rdr2 || gta6;
let mut infos = Vec::with_capacity(count);
for _ in 0..count {
let v = u32_at(&data, o)?;
@@ -248,6 +285,22 @@ impl Awc {
if d.len() < 32 {
return Err(damaged("short format chunk"));
}
+ let codec = Codec::from_byte(d[28]);
+ if codec == Codec::Opus {
+ // Samples of all channels together, always at 48 kHz
+ // (whatever the rate field says).
+ let channels = d[29].clamp(1, 2);
+ self.sounds.push(Sound {
+ id: *id,
+ samples: u32_at(d, 0)? / u32::from(channels),
+ sample_rate: OPUS_RATE,
+ codec,
+ channel: None,
+ headers: None,
+ channels,
+ });
+ continue;
+ }
let header_size = u16_at(d, 30)? as usize;
// Without headers of its own, a Vorbis sound has them in a
// headers chunk of the same stream.
@@ -260,9 +313,10 @@ impl Awc {
id: *id,
samples: u32_at(d, 0)?,
sample_rate: u16_at(d, 8)? as u32,
- codec: Codec::from_byte(d[28]),
+ codec,
channel: None,
headers,
+ channels: 1,
});
continue;
}
@@ -278,6 +332,7 @@ impl Awc {
codec: Codec::from_byte(d[19]),
channel: None,
headers: None,
+ channels: 1,
});
}
Ok(())
@@ -311,9 +366,28 @@ impl Awc {
codec: Codec::from_byte(*d.get(o + 12).ok_or_else(|| damaged("truncated"))?),
channel: Some(c),
headers,
+ channels: 1,
});
}
self.stream_format = Some(StreamFormat { block_count, block_size, channels });
+ // An Opus channel can be stereo, which only its packets say; its
+ // sample count then counts both sides.
+ if self.sounds.iter().any(|s| s.codec == Codec::Opus) {
+ let stereo: Vec = self
+ .stream_channels_with(24)?
+ .iter()
+ .map(|blocks| {
+ blocks.first().and_then(|(data, ..)| opus_packets(data).next()).map(opus_packet_channels) == Some(2)
+ })
+ .collect();
+ for (sound, stereo) in self.sounds.iter_mut().zip(stereo) {
+ sound.sample_rate = OPUS_RATE;
+ if stereo {
+ sound.channels = 2;
+ sound.samples /= 2;
+ }
+ }
+ }
Ok(())
}
}
@@ -509,6 +583,78 @@ pub fn decode_vorbis(headers: &[u8], data: &[u8]) -> Result, AwcError>
Ok(out)
}
+/// Opus is always decoded at this rate.
+pub const OPUS_RATE: u32 = 48_000;
+/// Samples the Opus encoder puts in front of a sound (its lookahead). The
+/// containers do not store it; this is what GTA VI's sounds measure.
+pub const OPUS_PRE_SKIP: usize = 312;
+
+/// The Opus packets of 2048-byte units: each unit holds packets with a
+/// 16-bit length in front; a zero length ends the unit.
+fn opus_packets(data: &[u8]) -> impl Iterator- {
+ data.chunks(2048).flat_map(|unit| {
+ let mut at = 0;
+ std::iter::from_fn(move || {
+ let len = usize::from(u16::from_le_bytes([*unit.get(at)?, *unit.get(at + 1)?]));
+ if len == 0 || at + 2 + len > unit.len() {
+ return None;
+ }
+ at += 2 + len;
+ Some(&unit[at - len..at])
+ })
+ })
+}
+
+/// Channels of an Opus packet (1 or 2), from its first byte.
+fn opus_packet_channels(packet: &[u8]) -> usize {
+ if packet.first().is_some_and(|toc| toc & 4 != 0) { 2 } else { 1 }
+}
+
+/// Samples per channel an Opus packet decodes to at 48 kHz, from its first
+/// bytes (RFC 6716, section 3.1); 0 for a packet that is not valid.
+fn opus_packet_samples(packet: &[u8]) -> usize {
+ let Some(&toc) = packet.first() else { return 0 };
+ let config = toc >> 3;
+ let frame = match config {
+ // SILK: 10, 20, 40, 60 ms.
+ 0..=11 => [480, 960, 1920, 2880][usize::from(config & 3)],
+ // Hybrid: 10, 20 ms.
+ 12..=15 => [480, 960][usize::from(config & 1)],
+ // CELT: 2.5, 5, 10, 20 ms.
+ _ => [120, 240, 480, 960][usize::from(config & 3)],
+ };
+ let frames = match toc & 3 {
+ 0 => 1,
+ 1 | 2 => 2,
+ _ => usize::from(packet.get(1).copied().unwrap_or(0) & 0x3F),
+ };
+ frame * frames
+}
+
+/// Decodes Opus packets to interleaved samples of `channels` channels.
+fn decode_opus_packets<'a>(packets: impl Iterator
- , channels: usize) -> Result
, AwcError> {
+ /// The longest an Opus packet can be: 120 ms.
+ const MAX_FRAME: usize = 5760;
+ let mut decoder =
+ opus_rs::OpusDecoder::new(OPUS_RATE as i32, channels).map_err(|e| damaged(format!("Opus decoder: {e}")))?;
+ let mut frame = vec![0f32; MAX_FRAME * channels];
+ let mut out = Vec::new();
+ for packet in packets {
+ let n = decoder.decode(packet, MAX_FRAME, &mut frame).map_err(|e| damaged(format!("Opus packet: {e}")))?;
+ out.extend(frame[..n * channels].iter().map(|s| (s * 32768.0).round().clamp(-32768.0, 32767.0) as i16));
+ }
+ Ok(out)
+}
+
+/// Decodes a sound stored as Opus: `frames` samples per channel, after the
+/// encoder's lookahead.
+pub fn decode_opus(data: &[u8], channels: usize, frames: usize) -> Result, AwcError> {
+ let mut out = decode_opus_packets(opus_packets(data), channels)?;
+ out.drain(..(OPUS_PRE_SKIP * channels).min(out.len()));
+ out.truncate(frames * channels);
+ Ok(out)
+}
+
fn decode_codec(sound: &Sound, all: &[u8], data: &[u8], samples: usize) -> Result, AwcError> {
let mut out = match sound.codec {
Codec::Pcm16 => data.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(),
@@ -517,6 +663,7 @@ fn decode_codec(sound: &Sound, all: &[u8], data: &[u8], samples: usize) -> Resul
let (at, len) = sound.headers.ok_or_else(|| damaged("Vorbis sound without headers"))?;
decode_vorbis(all.get(at..at + len).ok_or_else(|| damaged("Vorbis headers outside the file"))?, data)?
}
+ Codec::Opus => return decode_opus(data, usize::from(sound.channels.max(1)), samples),
Codec::Other(7) => decode_mp3(data)?,
Codec::Other(c) => return Err(damaged(format!("unsupported codec {c}"))),
};
@@ -538,7 +685,8 @@ impl Awc {
let chunk = self.chunk(stream, CHUNK_DATA).ok_or_else(|| damaged("sound without data"))?;
let data = &self.data[chunk.offset..chunk.offset + chunk.size];
let samples = decode_codec(sound, &self.data, data, sound.samples as usize)?;
- Ok(Pcm { sample_rate: sound.sample_rate, channels: 1, samples })
+ let channels = if sound.codec == Codec::Opus { u16::from(sound.channels.max(1)) } else { 1 };
+ Ok(Pcm { sample_rate: sound.sample_rate, channels, samples })
}
/// The data of each channel of a multi-channel stream: per block the bytes
@@ -607,8 +755,45 @@ impl Awc {
Ok(channels)
}
+ /// Decodes an Opus stream. Each block repeats the end of the one before
+ /// (the samples to skip): those packets are left out, and each channel is
+ /// decoded in one go. A stereo channel becomes two channels of the result.
+ fn decode_opus_stream(&self) -> Result {
+ let blocks = self.stream_channels_with(24)?;
+ let mut decoded: Vec> = Vec::new();
+ for (blocks, sound) in blocks.iter().zip(&self.sounds) {
+ let mut packets = Vec::new();
+ for (data, skip, _) in blocks {
+ let mut skipped = 0;
+ for packet in opus_packets(data) {
+ if skipped < *skip {
+ skipped += opus_packet_samples(packet).max(1);
+ } else {
+ packets.push(packet);
+ }
+ }
+ }
+ let channels = usize::from(sound.channels.max(1));
+ let mut pcm = decode_opus_packets(packets.into_iter(), channels)?;
+ pcm.drain(..(OPUS_PRE_SKIP * channels).min(pcm.len()));
+ pcm.truncate(sound.samples as usize * channels);
+ for c in 0..channels {
+ decoded.push(pcm.iter().skip(c).step_by(channels).copied().collect());
+ }
+ }
+ let frames = decoded.iter().map(Vec::len).max().unwrap_or(0);
+ let mut samples = Vec::with_capacity(frames * decoded.len());
+ for i in 0..frames {
+ samples.extend(decoded.iter().map(|ch| ch.get(i).copied().unwrap_or(0)));
+ }
+ Ok(Pcm { sample_rate: OPUS_RATE, channels: decoded.len().max(1) as u16, samples })
+ }
+
/// Decodes a multi-channel stream to one interleaved signal.
pub fn decode_stream(&self) -> Result {
+ if self.sounds.first().is_some_and(|s| s.codec == Codec::Opus) {
+ return self.decode_opus_stream();
+ }
let channels = self.stream_channels()?;
let mut decoded = Vec::with_capacity(channels.len());
for (blocks, sound) in channels.iter().zip(&self.sounds) {
@@ -723,6 +908,58 @@ mod tests {
assert_eq!(awc.decode_sound(0).unwrap().samples, vec![5, -5, 300]);
}
+ /// GTA VI: the three optional tables in front of the streams, and a
+ /// stereo Opus sound of two packets without content (silence).
+ #[test]
+ fn parses_gta6_opus() {
+ let mut unit = vec![0u8; 2048];
+ // Two packets of one byte: 20 ms of full-band stereo, no data.
+ unit[..6].copy_from_slice(&[1, 0, 0xFC, 1, 0, 0xFC]);
+ let mut out = Vec::new();
+ out.extend_from_slice(&MAGIC.to_le_bytes());
+ out.extend_from_slice(&1u16.to_le_bytes());
+ out.extend_from_slice(&0xFF61u16.to_le_bytes());
+ out.extend_from_slice(&1u32.to_le_bytes());
+ let tables = 2 + 8 + 4;
+ let format_at = 16 + tables + 4 + 16;
+ out.extend_from_slice(&(format_at as u32).to_le_bytes());
+ out.extend_from_slice(&[0xEE; 14]);
+ out.extend_from_slice(&(0x1234u32 | (2 << 29)).to_le_bytes());
+ let chunk =
+ |kind: u8, size: usize, offset: usize| ((kind as u64) << 56) | ((size as u64) << 28) | offset as u64;
+ out.extend_from_slice(&chunk(CHUNK_FORMAT_RDR2, 32, format_at).to_le_bytes());
+ out.extend_from_slice(&chunk(CHUNK_DATA, unit.len(), format_at + 32).to_le_bytes());
+ let frames = 2 * 960 - OPUS_PRE_SKIP as u32;
+ let mut format = vec![0u8; 32];
+ format[0..4].copy_from_slice(&(frames * 2).to_le_bytes());
+ format[8..10].copy_from_slice(&32000u16.to_le_bytes());
+ format[28] = 11;
+ format[29] = 2;
+ out.extend_from_slice(&format);
+ out.extend_from_slice(&unit);
+
+ let awc = Awc::parse(out, None).unwrap();
+ let sound = &awc.sounds[0];
+ assert_eq!((sound.codec, sound.channels, sound.samples, sound.sample_rate), (Codec::Opus, 2, frames, 48000));
+ let pcm = awc.decode_sound(0).unwrap();
+ assert_eq!((pcm.channels, pcm.sample_rate, pcm.samples.len()), (2, 48000, frames as usize * 2));
+ assert!(pcm.samples.iter().all(|s| *s == 0));
+ }
+
+ #[test]
+ fn opus_packet_lengths() {
+ // CELT 20 ms, one frame; SILK 60 ms, two frames; hybrid 10 ms, three frames, stereo.
+ assert_eq!(opus_packet_samples(&[0xF8]), 960);
+ assert_eq!(opus_packet_samples(&[(3 << 3) | 1, 0]), 2 * 2880);
+ assert_eq!(opus_packet_samples(&[(12 << 3) | 4 | 3, 3]), 3 * 480);
+ assert_eq!(opus_packet_channels(&[(12 << 3) | 4 | 3, 3]), 2);
+ assert_eq!(opus_packet_samples(&[]), 0);
+ let mut units = vec![0u8; 4096];
+ units[..5].copy_from_slice(&[3, 0, 1, 2, 3]);
+ units[2048..2052].copy_from_slice(&[2, 0, 9, 9]);
+ assert_eq!(opus_packets(&units).collect::>(), [&[1u8, 2, 3][..], &[9, 9]]);
+ }
+
#[test]
fn vorbis_header_packets() {
let mut d = Vec::new();
diff --git a/crates/rage-formats/src/bcpack/mod.rs b/crates/rage-formats/src/bcpack/mod.rs
new file mode 100644
index 0000000..1b3b84f
--- /dev/null
+++ b/crates/rage-formats/src/bcpack/mod.rs
@@ -0,0 +1,594 @@
+//! BCPack: the packing of block-compressed textures on the Xbox Series
+//! consoles (GTA VI's texture pools use it for about a tenth of their data).
+//!
+//! BCPack does not replace the block formats: it takes the fields of each
+//! BC1 to BC7 block apart, predicts them from earlier blocks and codes what
+//! is left with an entropy coder. Unpacking gives ordinary blocks again.
+//!
+//! - The entropy layer: 12 or 16 *lanes*, each a stream of symbols of a few
+//! bits, coded with rANS (16-bit probabilities, bytes fed in as the state
+//! runs low). The lanes' bytes are interleaved the way the hardware reads
+//! them: at most eight bytes per cycle, handed to the lanes that need one
+//! in lane order. A lane's stream comes in pieces, each with a header
+//! (quality of the frequency model, symbol width, byte count).
+//! - Per block format, a rule that turns one symbol per lane back into a
+//! block: endpoints as differences to an earlier block (up to 255 back; a
+//! reference before the first block reads a built-in history), indices
+//! through rank tables.
+//!
+//! Read: BC1, BC3, BC4 and BC5. Not read: BC6H and BC7. Not every entry of
+//! the built-in histories is known; a chunk that needs an unknown one is not
+//! unpacked (BC3 and BC5 tolerate a few such blocks, which then start from
+//! the format's neutral endpoints).
+//!
+//! This follows `tools/bcpack.py` of the Leonida project (GPL-3.0), a
+//! clean-room description of the bitstream (`docs/textures.md` there); its
+//! entropy layer is a port of the decoder in Microsoft's silicon-rans (MIT).
+
+mod tables;
+
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum BcpackError {
+ #[error("damaged BCPack data: {0}")]
+ Damaged(String),
+ #[error("BCPack mode {0} is not read yet")]
+ Mode(u8),
+ #[error("the BCPack data refers to an unknown built-in history entry ({0})")]
+ History(usize),
+}
+
+fn damaged(msg: impl Into) -> BcpackError {
+ BcpackError::Damaged(msg.into())
+}
+
+/// The state a lane's piece ends at, and below which a byte is fed in.
+const LOW: u64 = 1 << 24;
+const MAX_WIDTH: usize = 10;
+/// Bytes handed out per cycle.
+const BYTES_PER_CYCLE: usize = 8;
+const MAX_VIRTUAL_ZEROS: u8 = 8;
+
+/// Widths of the lanes' symbols, in stream order.
+fn lane_widths(mode: u8) -> Option<&'static [u8]> {
+ Some(match mode {
+ 1 => &[8, 8, 5, 6, 5, 5, 6, 5, 8, 8, 8, 8],
+ 3 => &[4, 4, 8, 6, 6, 6, 6, 5, 6, 5, 8, 8],
+ 4 => &[8, 8, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6],
+ 5 => &[4, 4, 8, 8, 6, 6, 6, 6, 6, 6, 6, 6],
+ _ => return None,
+ })
+}
+
+/// Whether [`unpack`] reads this mode (the codec number of a pool's chunk).
+pub fn reads_mode(mode: u8) -> bool {
+ lane_widths(mode).is_some()
+}
+
+/// A frequency model: for each band its weight per symbol and where the
+/// band starts in the 16-bit range.
+struct Model {
+ width: usize,
+ freq: &'static [u16],
+ base: [u32; MAX_WIDTH + 1],
+}
+
+impl Model {
+ fn get(width: usize, quality: usize) -> Option {
+ let freq = *tables::MODELS.get(width.checked_sub(1)?)?.get(quality)?;
+ if freq.len() != width + 1 {
+ return None;
+ }
+ let mut base = [0u32; MAX_WIDTH + 1];
+ let mut total = 0u32;
+ for (band, f) in freq.iter().enumerate() {
+ base[band] = total;
+ total += u32::from(*f) * if band == 0 { 1 } else { 1 << (band - 1) };
+ }
+ (total == 65536).then_some(Model { width, freq, base })
+ }
+
+ /// The symbol whose range holds `low` (the state's low 16 bits).
+ fn lookup(&self, low: u32) -> u32 {
+ let mut band = self.width;
+ while band > 0 && low < self.base[band] {
+ band -= 1;
+ }
+ if band == 0 { 0 } else { (1 << (band - 1)) + (low - self.base[band]) / u32::from(self.freq[band]) }
+ }
+
+ /// The state after taking symbol `s` out of state `x`.
+ fn advance(&self, s: u32, x: u64) -> u64 {
+ let band = (u32::BITS - s.leading_zeros()) as usize;
+ let mut f = u64::from(self.freq[band]);
+ let mut c = u64::from(self.base[band]) + f * u64::from(s - if band == 0 { 0 } else { 1 << (band - 1) });
+ if c == 0 {
+ (f, c) = (f - 1, 1);
+ }
+ (f * (x >> 16) + (x & 0xFFFF)).wrapping_sub(c)
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Step {
+ /// The three header bytes of a piece, then its symbols.
+ Header0,
+ Header1,
+ Header2,
+ Symbols,
+}
+
+/// One lane of the entropy decoder. The fields mirror the registers of the
+/// hardware decoder this is modelled on.
+struct Lane {
+ step: Step,
+ /// Symbols still to come.
+ left: usize,
+ width: usize,
+ quality: usize,
+ long: bool,
+ flush: bool,
+ done: bool,
+ /// A byte is waiting in `byte`.
+ full: bool,
+ /// A symbol is decoded and waits to be released.
+ held: bool,
+ zeros: u8,
+ byte: u8,
+ symbol: u32,
+ bytes_left: u32,
+ state_in: u64,
+ state: u64,
+ model: Option,
+ slot: Option,
+ stalled: bool,
+ out: Vec,
+}
+
+/// The entropy layer: `count` symbols for each lane.
+fn decode_lanes(raw: &[u8], widths: &[u8], count: usize) -> Result>, BcpackError> {
+ let mut lanes: Vec = widths
+ .iter()
+ .map(|_| Lane {
+ step: Step::Header0,
+ left: count,
+ width: 0,
+ quality: 0,
+ long: false,
+ flush: false,
+ done: count == 0,
+ full: false,
+ held: false,
+ zeros: 0,
+ byte: 0,
+ symbol: 0,
+ bytes_left: 0,
+ state_in: 0,
+ state: 0,
+ model: None,
+ slot: None,
+ stalled: false,
+ out: Vec::with_capacity(count),
+ })
+ .collect();
+ let mut pos = 0;
+ let home = || damaged("a piece of a lane does not end at its home state");
+ loop {
+ if lanes.iter().all(|l| l.done && l.slot.is_none()) {
+ break;
+ }
+ // The state moves on, bytes are handed out (eight per cycle, in lane
+ // order) and decoded symbols move to their slots.
+ let mut budget = BYTES_PER_CYCLE;
+ for l in &mut lanes {
+ if l.done || (l.held && l.slot.is_some()) {
+ l.stalled = true;
+ continue;
+ }
+ l.stalled = false;
+ if l.step == Step::Symbols {
+ l.state_in = match (&l.model, l.held) {
+ (Some(model), true) => model.advance(l.symbol, l.state),
+ _ => l.state,
+ };
+ }
+ if !l.full && (l.step != Step::Symbols || l.bytes_left > 0) {
+ if budget == 0 {
+ l.stalled = true;
+ continue;
+ }
+ l.byte = *raw.get(pos).ok_or_else(|| damaged("the data ends too early"))?;
+ pos += 1;
+ l.full = true;
+ budget -= 1;
+ }
+ if l.held {
+ l.slot = Some(l.symbol);
+ l.held = false;
+ }
+ }
+
+ // Headers are read, bytes merged into the states, symbols looked up.
+ for (i, l) in lanes.iter_mut().enumerate() {
+ if l.done || l.stalled {
+ continue;
+ }
+ match l.step {
+ Step::Header0 => {
+ if !l.full {
+ continue;
+ }
+ let h = l.byte;
+ l.quality = usize::from(h & 15);
+ l.flush = h >> 4 & 1 != 0;
+ l.long = h >> 5 & 1 != 0;
+ l.width = usize::from(widths[i]).wrapping_sub(usize::from(h >> 6));
+ l.full = false;
+ l.step = Step::Header1;
+ l.zeros = 0;
+ }
+ Step::Header1 => {
+ if !l.full {
+ continue;
+ }
+ l.full = false;
+ if !(1..=MAX_WIDTH).contains(&l.width) {
+ return Err(damaged("a symbol width out of range"));
+ }
+ l.model = Some(
+ Model::get(l.width, l.quality)
+ .ok_or_else(|| damaged("no frequency model for a lane's width and quality"))?,
+ );
+ if l.long {
+ l.bytes_left = u32::from(l.byte);
+ l.step = Step::Header2;
+ } else {
+ l.bytes_left = u32::from(l.byte) + 1;
+ l.step = Step::Symbols;
+ }
+ }
+ Step::Header2 => {
+ if !l.full {
+ continue;
+ }
+ l.bytes_left = (u32::from(l.byte) << 8 | (l.bytes_left & 0xFF)) + 257;
+ l.step = Step::Symbols;
+ l.full = false;
+ }
+ Step::Symbols => {
+ let mut st = l.state_in;
+ let pad = |st: &mut u64, zeros: &mut u8| {
+ while *st < LOW && *st != 0 && *zeros < MAX_VIRTUAL_ZEROS {
+ *st <<= 8;
+ *zeros += 1;
+ }
+ };
+ if st < LOW {
+ if l.bytes_left > 0 {
+ if l.full {
+ st = st << 8 | u64::from(l.byte);
+ l.bytes_left -= 1;
+ l.full = false;
+ if l.bytes_left == 0 && l.flush {
+ pad(&mut st, &mut l.zeros);
+ }
+ }
+ } else if l.flush {
+ if st == 0 || l.zeros >= MAX_VIRTUAL_ZEROS {
+ return Err(home());
+ }
+ pad(&mut st, &mut l.zeros);
+ } else {
+ l.state = st;
+ if l.left > 0 {
+ l.step = Step::Header0;
+ } else {
+ l.done = true;
+ }
+ continue;
+ }
+ }
+ let next = st > LOW && l.left > 0;
+ if next {
+ let Some(model) = &l.model else { return Err(damaged("symbols without a model")) };
+ l.symbol = model.lookup((st & 0xFFFF) as u32);
+ l.left -= 1;
+ if l.symbol >> l.width != 0 {
+ return Err(damaged("a symbol outside its width"));
+ }
+ }
+ l.held = next;
+ l.state = st;
+ if l.bytes_left == 0 {
+ if l.flush {
+ if st == LOW {
+ if l.left > 0 {
+ l.step = Step::Header0;
+ l.state_in = 0;
+ l.state = 0;
+ } else {
+ l.done = true;
+ }
+ } else if st > LOW && !next {
+ return Err(home());
+ }
+ } else if l.left == 0 && !next {
+ l.done = true;
+ }
+ } else if st == LOW || (l.left == 0 && !next && st > LOW) {
+ return Err(home());
+ }
+ }
+ }
+ }
+
+ // One symbol per lane is released when every lane has one.
+ let ready = lanes.iter().all(|l| l.slot.is_some() || (l.done && !l.held));
+ if ready && lanes.iter().any(|l| l.slot.is_some()) {
+ for l in &mut lanes {
+ if let Some(symbol) = l.slot.take() {
+ l.out.push(symbol);
+ }
+ }
+ }
+ for l in &mut lanes {
+ if l.done && l.held && l.slot.is_none() {
+ l.slot = Some(l.symbol);
+ l.held = false;
+ }
+ }
+ }
+ if raw[pos..].iter().any(|b| *b != 0) {
+ return Err(damaged("data is left over after the last lane"));
+ }
+ if lanes.iter().any(|l| l.out.len() != count) {
+ return Err(damaged("a lane ends before its last symbol"));
+ }
+ Ok(lanes.into_iter().map(|l| l.out).collect())
+}
+
+/// A difference stored without a sign: 0, -1, 1, -2, 2, …
+fn unzig(v: u32) -> i32 {
+ if v & 1 != 0 { -(((v + 1) >> 1) as i32) } else { (v >> 1) as i32 }
+}
+
+/// The bits of two 4-bit symbols, taken in turn.
+fn interleave(a: u32, b: u32) -> u32 {
+ (0..4).fold(0, |d, k| d | (a >> k & 1) << (2 * k) | (b >> k & 1) << (2 * k + 1))
+}
+
+fn known(table: &[(u8, [u8; N])], entry: usize) -> Option<[i32; N]> {
+ let i = table.binary_search_by_key(&entry, |(k, _)| usize::from(*k)).ok()?;
+ Some(table[i].1.map(i32::from))
+}
+
+/// How many blocks of a chunk may start from an unknown history entry.
+fn tolerated(blocks: usize) -> usize {
+ (blocks / 1024).max(2)
+}
+
+/// A table symbol; a symbol the table does not have is damage.
+fn ranked(table: &[T], symbol: u32) -> Result {
+ table.get(symbol as usize).copied().ok_or_else(|| damaged("an index symbol outside its table"))
+}
+
+/// Four rows of 3-bit indices (48 bits) from two symbols per row.
+fn index_rows(pairs: &[(u8, u8)], row: impl Fn(usize) -> (u32, u32)) -> Result<[u8; 6], BcpackError> {
+ let mut bits = 0u64;
+ for r in 0..4 {
+ let (left, right) = row(r);
+ let (left, right) = (ranked(pairs, left)?, ranked(pairs, right)?);
+ let twelve = u64::from(left.0) | u64::from(left.1) << 3 | u64::from(right.0) << 6 | u64::from(right.1) << 9;
+ bits |= twelve << (12 * r);
+ }
+ let mut out = [0u8; 6];
+ out.copy_from_slice(&bits.to_le_bytes()[..6]);
+ Ok(out)
+}
+
+/// The four index bytes of a colour block from four quadrant bytes (each
+/// holds the 2-bit indices of the pixels top left, top right, bottom left,
+/// bottom right of a quadrant).
+fn colour_indices(a: u8, b: u8, c: u8, d: u8) -> [u8; 4] {
+ [(a & 15) | (b & 15) << 4, (a >> 4) | (b >> 4) << 4, (c & 15) | (d & 15) << 4, (c >> 4) | (d >> 4) << 4]
+}
+
+fn colours(e: &[i32]) -> [u8; 4] {
+ let (c0, c1) = ((e[0] << 11 | e[1] << 5 | e[2]) as u16, (e[3] << 11 | e[4] << 5 | e[5]) as u16);
+ let (a, b) = (c0.to_le_bytes(), c1.to_le_bytes());
+ [a[0], a[1], b[0], b[1]]
+}
+
+/// The distance back to the block a block's endpoints build on, for the
+/// formats with one symbol per block.
+fn distance(v: u32) -> usize {
+ (if v & 1 != 0 { 256 - ((v + 1) >> 1) } else { v >> 1 }) as usize
+}
+
+fn bc1(lanes: &[Vec], blocks: usize) -> Result, BcpackError> {
+ const MODS: [i32; 6] = [32, 64, 32, 32, 64, 32];
+ let mut out = Vec::with_capacity(blocks * 8);
+ let mut history: Vec<[i32; 6]> = Vec::with_capacity(blocks);
+ for i in 0..blocks {
+ let d = distance(lanes[0][i]);
+ let base = match d {
+ 0 => [0; 6],
+ d if d <= i => history[i - d],
+ d => known(&tables::BC1_HISTORY, 256 + i - d).ok_or(BcpackError::History(256 + i - d))?,
+ };
+ let e: [i32; 6] = std::array::from_fn(|k| (base[k] + unzig(lanes[2 + k][i])).rem_euclid(MODS[k]));
+ history.push(e);
+ let quadrant = |lane: usize| ranked(&tables::BC1_QUADRANT, lanes[lane][i]);
+ out.extend_from_slice(&colours(&e));
+ out.extend_from_slice(&colour_indices(quadrant(8)?, quadrant(9)?, quadrant(10)?, quadrant(11)?));
+ }
+ Ok(out)
+}
+
+fn bc4(lanes: &[Vec], blocks: usize) -> Result, BcpackError> {
+ let mut out = Vec::with_capacity(blocks * 8);
+ let mut history: Vec<[i32; 2]> = Vec::with_capacity(blocks);
+ for i in 0..blocks {
+ let d = distance(lanes[0][i]);
+ let base = match d {
+ 0 => [128; 2],
+ d if d <= i => history[i - d],
+ d => known(&tables::BC4_HISTORY, 256 + i - d).ok_or(BcpackError::History(256 + i - d))?,
+ };
+ let e = [(base[0] + unzig(lanes[2][i])) & 255, (base[1] + unzig(lanes[3][i])) & 255];
+ history.push(e);
+ out.extend_from_slice(&[e[0] as u8, e[1] as u8]);
+ out.extend_from_slice(&index_rows(&tables::BC4_PAIR, |r| (lanes[4 + 2 * r][i], lanes[5 + 2 * r][i]))?);
+ }
+ Ok(out)
+}
+
+/// Where a block of the two-symbol formats starts from: an earlier block,
+/// a built-in entry, or (for a few blocks) the neutral endpoints.
+fn base_of(
+ table: &[(u8, [u8; N])],
+ neutral: [i32; N],
+ history: &[[i32; N]],
+ lost: &mut Vec,
+ i: usize,
+ d: usize,
+) -> [i32; N] {
+ match d {
+ 0 => {
+ lost.push(false);
+ neutral
+ }
+ d if d <= i => {
+ lost.push(lost[i - d]);
+ history[i - d]
+ }
+ d => {
+ let entry = known(table, 256 + i - d);
+ lost.push(entry.is_none());
+ entry.unwrap_or(neutral)
+ }
+ }
+}
+
+fn check_lost(lost: &[bool]) -> Result<(), BcpackError> {
+ let count = lost.iter().filter(|l| **l).count();
+ if count > tolerated(lost.len()) { Err(BcpackError::History(count)) } else { Ok(()) }
+}
+
+fn bc3(lanes: &[Vec], blocks: usize) -> Result, BcpackError> {
+ const MODS: [i32; 8] = [256, 256, 32, 64, 32, 32, 64, 32];
+ const NEUTRAL: [i32; 8] = [128, 128, 0, 0, 0, 0, 0, 0];
+ let mut out = Vec::with_capacity(blocks * 16);
+ let mut history: Vec<[i32; 8]> = Vec::with_capacity(blocks);
+ let mut lost = Vec::with_capacity(blocks);
+ for i in 0..blocks {
+ let (a, b) = (2 * i, 2 * i + 1);
+ let d = (unzig(interleave(lanes[0][a], lanes[0][b])) & 255) as usize;
+ let base = base_of(&tables::BC3_HISTORY, NEUTRAL, &history, &mut lost, i, d);
+ let diffs =
+ [lanes[2][a], lanes[2][b], lanes[7][a], lanes[8][a], lanes[9][a], lanes[7][b], lanes[8][b], lanes[9][b]];
+ let e: [i32; 8] = std::array::from_fn(|k| (base[k] + unzig(diffs[k])).rem_euclid(MODS[k]));
+ history.push(e);
+ out.extend_from_slice(&[e[0] as u8, e[1] as u8]);
+ out.extend_from_slice(&index_rows(&tables::BC3_ALPHA_PAIR, |r| (lanes[3 + r][a], lanes[3 + r][b]))?);
+ out.extend_from_slice(&colours(&e[2..]));
+ let quadrant = |lane: usize, at: usize| ranked(&tables::BC3_COLOUR_QUADRANT, lanes[lane][at]);
+ out.extend_from_slice(&colour_indices(quadrant(10, a)?, quadrant(10, b)?, quadrant(11, a)?, quadrant(11, b)?));
+ }
+ check_lost(&lost)?;
+ Ok(out)
+}
+
+fn bc5(lanes: &[Vec], blocks: usize) -> Result, BcpackError> {
+ let mut out = Vec::with_capacity(blocks * 16);
+ let mut history: Vec<[i32; 4]> = Vec::with_capacity(blocks);
+ let mut lost = Vec::with_capacity(blocks);
+ for i in 0..blocks {
+ let (a, b) = (2 * i, 2 * i + 1);
+ let d = (unzig(interleave(lanes[0][a], lanes[0][b])) & 255) as usize;
+ let base = base_of(&tables::BC5_HISTORY, [128; 4], &history, &mut lost, i, d);
+ let diffs = [lanes[2][a], lanes[2][b], lanes[3][a], lanes[3][b]];
+ let e: [i32; 4] = std::array::from_fn(|k| (base[k] + unzig(diffs[k])) & 255);
+ history.push(e);
+ for channel in 0..2 {
+ out.extend_from_slice(&[e[2 * channel] as u8, e[2 * channel + 1] as u8]);
+ let rows = |r: usize| (lanes[4 + 4 * channel + r][a], lanes[4 + 4 * channel + r][b]);
+ out.extend_from_slice(&index_rows(&tables::BC5_PAIR, rows)?);
+ }
+ }
+ check_lost(&lost)?;
+ Ok(out)
+}
+
+/// Unpacks a chunk to `size` bytes of blocks. `mode` is the block format:
+/// 1 BC1, 3 BC3, 4 BC4, 5 BC5.
+pub fn unpack(raw: &[u8], mode: u8, size: usize) -> Result, BcpackError> {
+ let widths = lane_widths(mode).ok_or(BcpackError::Mode(mode))?;
+ let block = if matches!(mode, 1 | 4) { 8 } else { 16 };
+ if !size.is_multiple_of(block) {
+ return Err(damaged("the unpacked size is not whole blocks"));
+ }
+ // Every lane gives one symbol per eight bytes of blocks.
+ let lanes = decode_lanes(raw, widths, size / 8)?;
+ if lanes[1].iter().any(|s| *s != 0) {
+ return Err(damaged("the second lane is not empty"));
+ }
+ let blocks = size / block;
+ match mode {
+ 1 => bc1(&lanes, blocks),
+ 3 => bc3(&lanes, blocks),
+ 4 => bc4(&lanes, blocks),
+ _ => bc5(&lanes, blocks),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn frequency_models_fill_their_range() {
+ let mut models = 0;
+ for width in 1..=MAX_WIDTH {
+ for quality in 0..16 {
+ if tables::MODELS[width - 1][quality].is_empty() {
+ continue;
+ }
+ let model = Model::get(width, quality).expect("a model that sums to 65536");
+ models += 1;
+ // Every symbol is found again from the start of its range.
+ for s in 0..1u32 << width {
+ let band = (u32::BITS - s.leading_zeros()) as usize;
+ if model.freq[band] == 0 {
+ continue;
+ }
+ let start = model.base[band]
+ + u32::from(model.freq[band]) * (s - if band == 0 { 0 } else { 1 << (band - 1) });
+ assert_eq!(model.lookup(start), s, "width {width}, quality {quality}");
+ }
+ }
+ }
+ assert_eq!(models, 160);
+ }
+
+ #[test]
+ fn small_helpers() {
+ assert_eq!([0, 1, 2, 3, 4].map(unzig), [0, -1, 1, -2, 2]);
+ assert_eq!([0, 1, 2, 3, 255].map(distance), [0, 255, 1, 254, 128]);
+ assert_eq!(interleave(0b1111, 0), 0b0101_0101);
+ assert_eq!(interleave(0, 0b1001), 0b1000_0010);
+ assert_eq!(colour_indices(0x1B, 0, 0, 0xE4), [0x0B, 0x01, 0x40, 0xE0]);
+ assert_eq!(known(&tables::BC1_HISTORY, 255), Some([0, 0, 1, 0, 0, 0]));
+ assert_eq!(known(&tables::BC4_HISTORY, 0), None);
+ assert_eq!((tolerated(100), tolerated(4096)), (2, 4));
+ }
+
+ #[test]
+ fn rejects_what_is_not_bcpack() {
+ assert_eq!(unpack(&[], 7, 16), Err(BcpackError::Mode(7)));
+ assert!(matches!(unpack(&[], 1, 12), Err(BcpackError::Damaged(_))));
+ assert!(matches!(unpack(&[0xFF; 4], 1, 8), Err(BcpackError::Damaged(_))));
+ assert_eq!(unpack(&[], 1, 0), Ok(Vec::new()));
+ assert!(reads_mode(5) && !reads_mode(6) && !reads_mode(0) && !reads_mode(8));
+ }
+}
diff --git a/crates/rage-formats/src/bcpack/tables.rs b/crates/rage-formats/src/bcpack/tables.rs
new file mode 100644
index 0000000..07770e6
--- /dev/null
+++ b/crates/rage-formats/src/bcpack/tables.rs
@@ -0,0 +1,1125 @@
+//! Constants of the BCPack codec: the frequency models of its entropy coder,
+//! the rank tables of its index symbols and the known entries of its built-in
+//! endpoint histories.
+//!
+//! Generated from `tools/bcpack_tables.py` of the Leonida project (GPL-3.0),
+//! which recovered them from public specifications and by fitting. The
+//! frequency models are those of Microsoft's silicon-rans (MIT, see `NOTICE.md`).
+
+/// Frequency models by symbol width (1 to 10) and quality (0 to 15): the
+/// weight of each band of symbols (band 0 is symbol 0, band `p` the symbols
+/// from `2^(p-1)` below `2^p`). Empty where no model is known.
+pub(super) const MODELS: [[&[u16]; 16]; 10] = [
+ [
+ &[32768, 32768],
+ &[38761, 26775],
+ &[44484, 21052],
+ &[49818, 15718],
+ &[54623, 10913],
+ &[58721, 6815],
+ &[61911, 3625],
+ &[64036, 1500],
+ &[65121, 415],
+ &[65477, 59],
+ &[65534, 2],
+ &[65535, 1],
+ &[65535, 1],
+ &[65535, 1],
+ &[65535, 1],
+ &[65535, 1],
+ ],
+ [
+ &[16384, 16384, 16384],
+ &[21168, 17592, 13388],
+ &[26354, 18130, 10526],
+ &[31900, 17918, 7859],
+ &[37750, 16874, 5456],
+ &[43800, 14920, 3408],
+ &[49850, 12062, 1812],
+ &[55537, 8499, 750],
+ &[60308, 4812, 208],
+ &[63575, 1901, 30],
+ &[65132, 402, 1],
+ &[65511, 23, 1],
+ &[65533, 1, 1],
+ &[65533, 1, 1],
+ &[65533, 1, 1],
+ &[65533, 1, 1],
+ ],
+ [
+ &[8192, 8192, 8192, 8192],
+ &[11073, 10095, 8796, 6694],
+ &[14406, 11948, 9065, 5263],
+ &[18234, 13666, 8958, 3930],
+ &[22624, 15126, 8437, 2728],
+ &[27657, 16143, 7460, 1704],
+ &[33414, 16436, 6031, 906],
+ &[39920, 15616, 4250, 375],
+ &[47024, 13284, 2406, 104],
+ &[54201, 9375, 950, 15],
+ &[60388, 4744, 200, 1],
+ &[64250, 1262, 10, 1],
+ &[65456, 74, 1, 1],
+ &[65529, 1, 1, 1],
+ &[65529, 1, 1, 1],
+ &[65529, 1, 1, 1],
+ ],
+ [
+ &[4096, 4096, 4096, 4096, 4096],
+ &[5665, 5407, 5048, 4398, 3347],
+ &[7539, 6867, 5973, 4532, 2632],
+ &[9773, 8461, 6833, 4479, 1965],
+ &[12447, 10177, 7564, 4218, 1364],
+ &[15679, 11977, 8072, 3730, 852],
+ &[19640, 13774, 8217, 3016, 453],
+ &[24559, 15361, 7808, 2124, 188],
+ &[30704, 16320, 6642, 1203, 52],
+ &[38280, 15920, 4688, 476, 7],
+ &[47169, 13219, 2372, 99, 1],
+ &[56354, 7896, 631, 4, 1],
+ &[63248, 2208, 34, 1, 1],
+ &[65465, 57, 1, 1, 1],
+ &[65521, 1, 1, 1, 1],
+ &[65521, 1, 1, 1, 1],
+ ],
+ [
+ &[2048, 2048, 2048, 2048, 2048, 2048],
+ &[2865, 2799, 2704, 2524, 2200, 1673],
+ &[3858, 3682, 3434, 2986, 2266, 1316],
+ &[5063, 4709, 4230, 3418, 2240, 982],
+ &[6536, 5912, 5088, 3782, 2109, 682],
+ &[8366, 7314, 5988, 4036, 1865, 426],
+ &[10688, 8952, 6888, 4108, 1507, 227],
+ &[13713, 10847, 7680, 3904, 1062, 94],
+ &[17758, 12946, 8160, 3320, 602, 26],
+ &[23272, 15008, 7960, 2344, 237, 4],
+ &[30841, 16327, 6610, 1187, 48, 1],
+ &[41006, 15348, 3947, 316, 1, 1],
+ &[53291, 9957, 1104, 14, 1, 1],
+ &[63380, 2084, 22, 1, 1, 1],
+ &[65505, 1, 1, 1, 1, 1],
+ &[65505, 1, 1, 1, 1, 1],
+ ],
+ [
+ &[1024, 1024, 1024, 1024, 1024, 1024, 1024],
+ &[1441, 1423, 1400, 1352, 1262, 1099, 837],
+ &[1951, 1907, 1841, 1717, 1493, 1133, 658],
+ &[2577, 2487, 2354, 2115, 1709, 1120, 491],
+ &[3350, 3186, 2956, 2544, 1890, 1055, 341],
+ &[4324, 4042, 3657, 2994, 2019, 932, 213],
+ &[5581, 5107, 4476, 3444, 2055, 754, 113],
+ &[7258, 6454, 5424, 3840, 1952, 531, 47],
+ &[9579, 8179, 6473, 4080, 1660, 301, 13],
+ &[12907, 10365, 7504, 3980, 1171, 119, 2],
+ &[17852, 12988, 8164, 3304, 594, 23, 1],
+ &[25441, 15565, 7673, 1974, 155, 1, 1],
+ &[37208, 16084, 4978, 552, 4, 1, 1],
+ &[53649, 9731, 1042, 4, 1, 1, 1],
+ &[65147, 327, 1, 1, 1, 1, 1],
+ &[65473, 1, 1, 1, 1, 1, 1],
+ ],
+ [
+ &[512, 512, 512, 512, 512, 512, 512, 512],
+ &[722, 718, 712, 700, 676, 632, 550, 418],
+ &[981, 971, 952, 920, 858, 748, 566, 329],
+ &[1300, 1276, 1244, 1178, 1058, 854, 559, 246],
+ &[1696, 1654, 1593, 1478, 1272, 946, 526, 171],
+ &[2198, 2126, 2022, 1828, 1498, 1009, 467, 106],
+ &[2852, 2728, 2554, 2238, 1721, 1028, 376, 57],
+ &[3736, 3522, 3227, 2712, 1920, 977, 266, 23],
+ &[4979, 4601, 4090, 3236, 2040, 831, 151, 6],
+ &[6807, 6101, 5182, 3752, 1991, 586, 59, 1],
+ &[9634, 8218, 6494, 4082, 1652, 296, 11, 1],
+ &[14275, 11165, 7784, 3836, 988, 74, 1, 1],
+ &[22449, 14759, 8042, 2489, 272, 1, 1, 1],
+ &[37625, 16023, 4866, 509, 1, 1, 1, 1],
+ &[60485, 4663, 132, 1, 1, 1, 1, 1],
+ &[65409, 1, 1, 1, 1, 1, 1, 1],
+ ],
+ [
+ &[256, 256, 256, 256, 256, 256, 256, 256, 256],
+ &[362, 360, 359, 356, 350, 338, 316, 275, 209],
+ &[492, 488, 486, 476, 460, 429, 374, 284, 164],
+ &[653, 647, 638, 622, 589, 529, 426, 280, 123],
+ &[853, 843, 828, 796, 739, 636, 473, 264, 85],
+ &[1108, 1090, 1063, 1011, 914, 748, 504, 234, 53],
+ &[1442, 1410, 1364, 1277, 1120, 860, 514, 189, 28],
+ &[1895, 1841, 1760, 1614, 1356, 961, 488, 132, 12],
+ &[2538, 2442, 2300, 2045, 1618, 1021, 414, 76, 3],
+ &[3497, 3311, 3050, 2591, 1875, 996, 292, 29, 1],
+ &[5008, 4626, 4109, 3247, 2041, 826, 149, 4, 1],
+ &[7575, 6701, 5582, 3892, 1918, 494, 34, 1, 1],
+ &[12397, 10051, 7380, 4020, 1245, 129, 1, 1, 1],
+ &[22767, 14857, 8012, 2432, 240, 1, 1, 1, 1],
+ &[47343, 13141, 2332, 35, 1, 1, 1, 1, 1],
+ &[65281, 1, 1, 1, 1, 1, 1, 1, 1],
+ ],
+ [
+ &[128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
+ &[181, 181, 179, 180, 178, 175, 169, 157, 137, 105],
+ &[246, 246, 244, 243, 238, 231, 214, 187, 142, 82],
+ &[327, 325, 324, 319, 310, 294, 265, 213, 141, 61],
+ &[428, 424, 422, 414, 397, 370, 319, 236, 131, 43],
+ &[557, 551, 546, 530, 506, 457, 374, 252, 116, 27],
+ &[725, 717, 705, 683, 638, 560, 430, 256, 95, 14],
+ &[955, 941, 920, 880, 807, 677, 481, 244, 66, 6],
+ &[1282, 1256, 1219, 1150, 1023, 810, 510, 207, 37, 2],
+ &[1772, 1724, 1656, 1524, 1295, 938, 498, 147, 13, 1],
+ &[2554, 2454, 2312, 2054, 1625, 1020, 414, 74, 1, 1],
+ &[3904, 3672, 3350, 2791, 1946, 959, 247, 14, 1, 1],
+ &[6523, 5873, 5026, 3690, 2011, 621, 58, 1, 1, 1],
+ &[12593, 10175, 7428, 4006, 1216, 105, 1, 1, 1, 1],
+ &[31009, 16335, 6572, 1136, 1, 1, 1, 1, 1, 1],
+ &[65025, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ ],
+ [
+ &[64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64],
+ &[91, 89, 90, 90, 90, 90, 88, 85, 79, 69, 52],
+ &[123, 123, 123, 123, 121, 120, 115, 108, 93, 71, 41],
+ &[164, 164, 162, 161, 160, 155, 148, 131, 108, 69, 31],
+ &[214, 214, 212, 211, 206, 199, 184, 160, 117, 67, 21],
+ &[279, 277, 276, 273, 265, 252, 229, 187, 126, 59, 13],
+ &[364, 360, 358, 352, 342, 319, 280, 215, 129, 47, 7],
+ &[479, 477, 470, 460, 441, 404, 339, 240, 122, 33, 3],
+ &[644, 638, 627, 610, 576, 511, 405, 254, 105, 18, 1],
+ &[892, 880, 862, 828, 763, 647, 469, 248, 73, 6, 1],
+ &[1290, 1264, 1227, 1156, 1028, 812, 510, 207, 34, 1, 1],
+ &[1982, 1922, 1836, 1674, 1396, 972, 481, 123, 4, 1, 1],
+ &[3347, 3177, 2936, 2513, 1846, 1004, 311, 22, 1, 1, 1],
+ &[6632, 5962, 5087, 3714, 2003, 609, 37, 1, 1, 1, 1],
+ &[17963, 13041, 8168, 3285, 506, 1, 1, 1, 1, 1, 1],
+ &[64513, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ ],
+];
+
+/// BC1 index symbols: the four 2-bit indices of a 2×2 quadrant.
+pub(super) const BC1_QUADRANT: [u8; 256] = [
+ 0xaa, 0xff, 0x00, 0x55, 0xfa, 0xaf, 0xfb, 0xbf, 0xfe, 0xef, 0xbb, 0xee, 0xdf, 0xba, 0x5a, 0xae, 0x7f, 0xea, 0xab,
+ 0xf7, 0xfd, 0xa5, 0x5f, 0xf5, 0xdd, 0x77, 0x66, 0x99, 0x2a, 0x8a, 0xa2, 0x50, 0x05, 0xa8, 0x11, 0x9a, 0x44, 0x3f,
+ 0xa6, 0xa9, 0xcf, 0xbe, 0xfc, 0xf3, 0x6a, 0xeb, 0x7e, 0xe7, 0xdb, 0xbd, 0x7a, 0xa7, 0xda, 0x0f, 0xad, 0x57, 0xd5,
+ 0x0a, 0x5d, 0x75, 0x2f, 0x6e, 0xf0, 0x8f, 0xf8, 0xe6, 0x3d, 0xf2, 0xb9, 0x25, 0x7c, 0x9b, 0x3b, 0x85, 0xce, 0xec,
+ 0x58, 0xb3, 0xd3, 0xa0, 0x52, 0xde, 0x7b, 0x2b, 0xb7, 0x5e, 0xc7, 0xed, 0x5b, 0xb2, 0x8e, 0xcc, 0x6f, 0x19, 0xf6,
+ 0x9f, 0x64, 0xe8, 0xe5, 0x29, 0xf9, 0x33, 0x46, 0x22, 0xb5, 0xd7, 0x2d, 0x78, 0x56, 0x86, 0x88, 0x68, 0x91, 0x95,
+ 0x92, 0xd2, 0x87, 0x7d, 0x76, 0x67, 0x9d, 0x59, 0x65, 0xd9, 0x15, 0x37, 0x93, 0x5c, 0xc6, 0x35, 0x6c, 0xcd, 0x39,
+ 0x45, 0xdc, 0x54, 0x73, 0x51, 0x53, 0xc5, 0x2e, 0x8b, 0x8d, 0x27, 0xe2, 0x1f, 0xf4, 0x1d, 0xd8, 0xf1, 0x72, 0xa3,
+ 0x4f, 0x74, 0xb8, 0xca, 0x3a, 0xac, 0xd1, 0x89, 0x47, 0x26, 0x62, 0x98, 0x70, 0x0d, 0xa1, 0x1a, 0x4a, 0x6b, 0x1b,
+ 0xd0, 0xa4, 0xe9, 0x07, 0xb1, 0x9e, 0xb6, 0xe4, 0x4e, 0xbc, 0xe3, 0x3e, 0xcb, 0x82, 0x31, 0x02, 0x28, 0x4c, 0x13,
+ 0xc4, 0x20, 0x0e, 0x0b, 0x08, 0x96, 0x80, 0xe0, 0x09, 0xb0, 0x69, 0x60, 0x06, 0x90, 0x23, 0x97, 0x8c, 0xd6, 0x21,
+ 0x6d, 0x79, 0x32, 0xc8, 0x48, 0x84, 0x17, 0x12, 0xd4, 0x4d, 0x71, 0x01, 0x36, 0x63, 0x9c, 0xc9, 0x40, 0x04, 0x10,
+ 0xe1, 0x16, 0x94, 0x49, 0x4b, 0x1e, 0xb4, 0x61, 0x03, 0x0c, 0xc0, 0x42, 0x81, 0x18, 0x30, 0x24, 0xc3, 0x3c, 0xc2,
+ 0x41, 0x14, 0x83, 0x2c, 0x38, 0x43, 0x34, 0x1c, 0xc1,
+];
+
+/// BC3 colour index symbols: the four 2-bit indices of a 2×2 quadrant.
+pub(super) const BC3_COLOUR_QUADRANT: [u8; 256] = [
+ 0x55, 0xaa, 0xff, 0x00, 0x50, 0x05, 0xaf, 0xfa, 0xae, 0xea, 0xab, 0xba, 0xee, 0xbb, 0xfe, 0xbf, 0xef, 0xfb, 0xa5,
+ 0x5a, 0xf0, 0x11, 0x0f, 0x44, 0xf5, 0x5f, 0xa0, 0x0a, 0x8a, 0xa2, 0xa8, 0x2a, 0x7f, 0xf7, 0x77, 0xdf, 0xfd, 0xdd,
+ 0x66, 0x99, 0x88, 0xbe, 0xeb, 0x22, 0xcc, 0x33, 0x8f, 0xf8, 0x57, 0x75, 0xd5, 0x5d, 0x2f, 0xf2, 0x7a, 0x85, 0xa7,
+ 0xda, 0x58, 0x25, 0xad, 0x52, 0x3f, 0xf3, 0xcf, 0xe8, 0xfc, 0x8e, 0x2b, 0x7e, 0x6a, 0xa6, 0x9a, 0x70, 0x07, 0x0d,
+ 0xa9, 0x78, 0x80, 0x08, 0x02, 0xe7, 0xb2, 0x20, 0xdb, 0xd0, 0x87, 0x5e, 0xbd, 0x7c, 0x2d, 0xe5, 0xc7, 0xec, 0xce,
+ 0x5b, 0xb3, 0xd2, 0x2e, 0xb5, 0x3b, 0xe0, 0xe6, 0x6e, 0x68, 0x8b, 0x9b, 0xe2, 0xb9, 0x0e, 0xb8, 0x0b, 0x3d, 0xd3,
+ 0x51, 0x86, 0x27, 0x45, 0x15, 0xde, 0x54, 0x8d, 0xb7, 0xed, 0x7b, 0xb0, 0xd8, 0x29, 0x72, 0x92, 0x7d, 0xd7, 0x35,
+ 0xa3, 0xc5, 0x82, 0x37, 0x53, 0x28, 0x5c, 0x56, 0x65, 0x76, 0x95, 0x59, 0xcd, 0x9f, 0x3a, 0x73, 0x89, 0xca, 0xac,
+ 0x67, 0x9d, 0xf6, 0xd9, 0xf9, 0x91, 0x19, 0xdc, 0x98, 0x6c, 0x46, 0x64, 0x6f, 0x26, 0x39, 0x62, 0xc6, 0x93, 0x09,
+ 0x23, 0x06, 0x60, 0x8c, 0xc8, 0x90, 0x32, 0x03, 0x3e, 0xc0, 0x13, 0x31, 0xe3, 0x4c, 0x9e, 0x0c, 0xc4, 0xcb, 0xbc,
+ 0xb6, 0xe9, 0x30, 0x6b, 0x1f, 0xf1, 0x1d, 0xd1, 0x47, 0x74, 0x4f, 0x10, 0x40, 0xf4, 0x01, 0x04, 0xa1, 0x1a, 0xa4,
+ 0x1b, 0x4a, 0xb1, 0xe4, 0x4e, 0x36, 0xc9, 0x9c, 0x63, 0x97, 0x71, 0x79, 0x17, 0x48, 0x69, 0x21, 0x12, 0x3c, 0x84,
+ 0x83, 0x6d, 0xd6, 0x96, 0xc3, 0x38, 0x1e, 0x4d, 0xe1, 0xd4, 0xc2, 0x2c, 0x18, 0x81, 0xb4, 0x4b, 0x16, 0x61, 0xc1,
+ 0x24, 0x1c, 0x49, 0x14, 0x42, 0x94, 0x41, 0x34, 0x43,
+];
+
+/// BC3 alpha index symbols: two 3-bit indices.
+pub(super) const BC3_ALPHA_PAIR: [(u8, u8); 64] = [
+ (0, 0),
+ (1, 1),
+ (6, 6),
+ (4, 4),
+ (3, 3),
+ (5, 5),
+ (7, 7),
+ (1, 6),
+ (6, 1),
+ (0, 1),
+ (1, 0),
+ (7, 1),
+ (1, 7),
+ (0, 3),
+ (3, 0),
+ (0, 2),
+ (2, 0),
+ (2, 2),
+ (5, 4),
+ (3, 4),
+ (4, 3),
+ (4, 5),
+ (1, 5),
+ (5, 1),
+ (0, 4),
+ (4, 0),
+ (2, 3),
+ (3, 2),
+ (5, 3),
+ (3, 5),
+ (6, 5),
+ (5, 6),
+ (6, 7),
+ (7, 6),
+ (5, 7),
+ (4, 6),
+ (6, 4),
+ (7, 5),
+ (6, 0),
+ (0, 6),
+ (4, 2),
+ (2, 4),
+ (4, 1),
+ (1, 4),
+ (5, 0),
+ (0, 5),
+ (6, 3),
+ (3, 6),
+ (3, 1),
+ (5, 2),
+ (1, 3),
+ (2, 5),
+ (7, 4),
+ (4, 7),
+ (7, 3),
+ (3, 7),
+ (2, 6),
+ (6, 2),
+ (2, 1),
+ (1, 2),
+ (0, 7),
+ (7, 0),
+ (2, 7),
+ (7, 2),
+];
+
+/// BC4 index symbols: two 3-bit indices.
+pub(super) const BC4_PAIR: [(u8, u8); 64] = [
+ (1, 1),
+ (0, 0),
+ (3, 3),
+ (6, 6),
+ (4, 4),
+ (5, 5),
+ (3, 0),
+ (0, 3),
+ (6, 1),
+ (1, 6),
+ (7, 7),
+ (2, 2),
+ (6, 3),
+ (3, 6),
+ (1, 0),
+ (0, 1),
+ (4, 1),
+ (1, 4),
+ (3, 1),
+ (1, 3),
+ (6, 0),
+ (0, 6),
+ (4, 2),
+ (7, 5),
+ (5, 7),
+ (2, 4),
+ (0, 5),
+ (5, 0),
+ (6, 4),
+ (4, 6),
+ (5, 3),
+ (3, 5),
+ (4, 0),
+ (0, 4),
+ (1, 5),
+ (5, 1),
+ (3, 4),
+ (4, 3),
+ (2, 6),
+ (6, 2),
+ (7, 3),
+ (3, 7),
+ (1, 2),
+ (2, 1),
+ (0, 7),
+ (7, 0),
+ (2, 5),
+ (5, 2),
+ (7, 4),
+ (4, 7),
+ (4, 5),
+ (5, 4),
+ (3, 2),
+ (2, 3),
+ (0, 2),
+ (2, 0),
+ (1, 7),
+ (7, 1),
+ (6, 5),
+ (5, 6),
+ (6, 7),
+ (7, 6),
+ (2, 7),
+ (7, 2),
+];
+
+/// BC5 index symbols: two 3-bit indices.
+pub(super) const BC5_PAIR: [(u8, u8); 64] = [
+ (0, 0),
+ (1, 1),
+ (4, 4),
+ (3, 3),
+ (6, 6),
+ (7, 7),
+ (4, 0),
+ (0, 4),
+ (0, 1),
+ (2, 2),
+ (1, 0),
+ (3, 0),
+ (0, 3),
+ (5, 5),
+ (2, 0),
+ (0, 2),
+ (1, 6),
+ (6, 1),
+ (4, 3),
+ (1, 7),
+ (3, 4),
+ (1, 4),
+ (7, 1),
+ (6, 0),
+ (0, 6),
+ (6, 3),
+ (6, 4),
+ (3, 6),
+ (3, 2),
+ (4, 6),
+ (1, 5),
+ (1, 3),
+ (2, 3),
+ (5, 4),
+ (5, 3),
+ (5, 0),
+ (4, 1),
+ (7, 6),
+ (4, 5),
+ (4, 2),
+ (3, 1),
+ (3, 5),
+ (5, 1),
+ (6, 7),
+ (2, 4),
+ (7, 5),
+ (7, 4),
+ (0, 5),
+ (6, 5),
+ (4, 7),
+ (5, 7),
+ (7, 0),
+ (5, 6),
+ (0, 7),
+ (7, 3),
+ (3, 7),
+ (5, 2),
+ (2, 5),
+ (1, 2),
+ (6, 2),
+ (2, 1),
+ (2, 6),
+ (7, 2),
+ (2, 7),
+];
+
+/// BC1: known entries of the built-in endpoint history (r0, g0, b0, r1, g1, b1).
+pub(super) const BC1_HISTORY: [(u8, [u8; 6]); 255] = [
+ (1, [7, 29, 6, 8, 30, 7]),
+ (2, [15, 29, 15, 16, 36, 17]),
+ (3, [20, 38, 14, 3, 5, 2]),
+ (4, [12, 27, 13, 6, 12, 6]),
+ (5, [10, 22, 11, 6, 14, 7]),
+ (6, [12, 24, 11, 7, 14, 6]),
+ (7, [12, 26, 12, 7, 14, 7]),
+ (8, [22, 36, 15, 20, 32, 14]),
+ (9, [14, 23, 8, 1, 2, 1]),
+ (10, [23, 5, 30, 9, 5, 30]),
+ (11, [11, 22, 11, 7, 15, 7]),
+ (12, [17, 22, 7, 10, 11, 3]),
+ (13, [12, 25, 12, 7, 16, 7]),
+ (14, [13, 28, 8, 5, 11, 3]),
+ (15, [11, 20, 8, 16, 31, 14]),
+ (16, [23, 32, 30, 17, 12, 29]),
+ (17, [8, 44, 30, 6, 26, 30]),
+ (18, [10, 24, 30, 6, 45, 30]),
+ (19, [10, 12, 4, 8, 8, 2]),
+ (20, [16, 23, 30, 14, 6, 26]),
+ (21, [12, 25, 13, 10, 22, 12]),
+ (22, [19, 27, 10, 12, 15, 5]),
+ (23, [11, 24, 12, 4, 11, 6]),
+ (24, [29, 60, 29, 6, 13, 6]),
+ (25, [17, 31, 11, 1, 2, 1]),
+ (26, [26, 54, 24, 12, 24, 10]),
+ (27, [23, 49, 30, 20, 36, 30]),
+ (28, [16, 23, 10, 10, 14, 6]),
+ (29, [11, 24, 10, 6, 13, 5]),
+ (30, [18, 52, 30, 14, 22, 30]),
+ (31, [14, 51, 30, 9, 34, 30]),
+ (32, [2, 3, 1, 19, 37, 16]),
+ (33, [14, 15, 30, 9, 31, 30]),
+ (34, [29, 57, 27, 27, 52, 25]),
+ (35, [13, 29, 15, 8, 20, 11]),
+ (36, [13, 17, 5, 9, 10, 3]),
+ (37, [18, 50, 29, 15, 10, 29]),
+ (38, [11, 25, 13, 8, 19, 10]),
+ (39, [17, 32, 12, 6, 11, 4]),
+ (40, [22, 18, 30, 19, 41, 30]),
+ (41, [10, 22, 11, 8, 18, 9]),
+ (42, [18, 30, 31, 10, 44, 30]),
+ (43, [25, 50, 24, 2, 4, 1]),
+ (44, [11, 30, 31, 7, 15, 29]),
+ (45, [12, 19, 8, 11, 16, 7]),
+ (46, [19, 29, 30, 14, 55, 28]),
+ (47, [9, 20, 10, 4, 10, 5]),
+ (48, [12, 24, 10, 7, 13, 5]),
+ (49, [26, 53, 25, 6, 13, 6]),
+ (50, [19, 27, 31, 11, 19, 30]),
+ (51, [21, 31, 30, 22, 31, 30]),
+ (52, [10, 19, 5, 11, 21, 6]),
+ (53, [30, 50, 3, 29, 46, 2]),
+ (54, [15, 9, 30, 7, 9, 30]),
+ (55, [14, 18, 6, 11, 14, 4]),
+ (56, [28, 56, 26, 4, 7, 3]),
+ (57, [9, 20, 10, 5, 13, 7]),
+ (58, [28, 58, 26, 15, 32, 14]),
+ (59, [11, 19, 8, 6, 9, 4]),
+ (60, [16, 22, 9, 13, 17, 7]),
+ (61, [1, 2, 1, 14, 28, 12]),
+ (62, [22, 45, 30, 9, 15, 30]),
+ (63, [19, 22, 30, 16, 23, 31]),
+ (64, [25, 50, 24, 21, 43, 20]),
+ (65, [6, 11, 4, 16, 31, 13]),
+ (66, [13, 25, 8, 3, 6, 1]),
+ (67, [5, 9, 3, 12, 24, 10]),
+ (68, [16, 29, 13, 7, 13, 5]),
+ (69, [20, 38, 16, 13, 25, 10]),
+ (70, [18, 35, 15, 5, 9, 3]),
+ (71, [13, 25, 11, 6, 11, 4]),
+ (72, [11, 21, 7, 7, 13, 4]),
+ (73, [20, 39, 16, 11, 20, 8]),
+ (74, [16, 31, 12, 4, 8, 2]),
+ (75, [22, 41, 30, 18, 23, 30]),
+ (76, [24, 50, 24, 9, 19, 8]),
+ (77, [3, 12, 7, 4, 16, 8]),
+ (78, [18, 27, 12, 16, 22, 10]),
+ (79, [24, 49, 23, 13, 28, 12]),
+ (80, [24, 50, 24, 18, 37, 18]),
+ (81, [17, 33, 12, 14, 27, 9]),
+ (82, [20, 10, 31, 13, 10, 31]),
+ (83, [7, 8, 2, 5, 5, 1]),
+ (84, [1, 2, 1, 10, 21, 9]),
+ (85, [10, 18, 6, 1, 1, 0]),
+ (86, [22, 46, 21, 1, 3, 1]),
+ (87, [11, 20, 8, 8, 14, 5]),
+ (88, [17, 35, 31, 14, 14, 29]),
+ (89, [16, 22, 31, 12, 40, 31]),
+ (90, [12, 22, 9, 8, 15, 6]),
+ (91, [18, 15, 30, 15, 33, 31]),
+ (92, [19, 32, 30, 15, 43, 31]),
+ (93, [18, 35, 15, 8, 15, 5]),
+ (94, [21, 43, 20, 18, 37, 17]),
+ (95, [10, 17, 6, 9, 15, 6]),
+ (96, [14, 27, 12, 7, 13, 5]),
+ (97, [8, 16, 7, 12, 25, 11]),
+ (98, [18, 37, 17, 1, 1, 0]),
+ (99, [17, 45, 30, 15, 33, 31]),
+ (100, [13, 25, 11, 8, 16, 7]),
+ (101, [23, 47, 22, 16, 32, 15]),
+ (102, [18, 33, 13, 11, 21, 8]),
+ (103, [4, 10, 4, 8, 17, 7]),
+ (104, [1, 2, 1, 3, 7, 3]),
+ (105, [11, 22, 9, 6, 11, 4]),
+ (106, [16, 29, 11, 13, 23, 9]),
+ (107, [12, 24, 12, 6, 12, 6]),
+ (108, [23, 47, 22, 7, 14, 6]),
+ (109, [11, 32, 30, 11, 31, 30]),
+ (110, [14, 26, 11, 10, 18, 7]),
+ (111, [20, 41, 19, 1, 3, 1]),
+ (112, [14, 28, 12, 8, 16, 6]),
+ (113, [11, 21, 9, 8, 15, 6]),
+ (114, [1, 2, 1, 7, 13, 6]),
+ (115, [19, 35, 14, 16, 29, 12]),
+ (116, [13, 27, 13, 7, 15, 7]),
+ (117, [15, 33, 16, 8, 18, 9]),
+ (118, [15, 42, 31, 11, 22, 30]),
+ (119, [23, 48, 23, 4, 9, 4]),
+ (120, [22, 45, 21, 11, 22, 10]),
+ (121, [31, 62, 30, 31, 61, 29]),
+ (122, [13, 26, 11, 5, 8, 3]),
+ (123, [19, 39, 19, 9, 20, 10]),
+ (124, [7, 14, 2, 6, 12, 2]),
+ (125, [21, 42, 20, 3, 7, 3]),
+ (126, [10, 17, 7, 8, 13, 5]),
+ (127, [11, 20, 8, 9, 17, 7]),
+ (128, [19, 33, 31, 12, 31, 31]),
+ (129, [21, 43, 20, 5, 11, 5]),
+ (130, [10, 20, 9, 7, 13, 6]),
+ (131, [10, 21, 10, 6, 13, 6]),
+ (132, [15, 29, 12, 11, 20, 8]),
+ (133, [21, 43, 20, 9, 18, 8]),
+ (134, [3, 8, 3, 5, 11, 5]),
+ (135, [16, 31, 13, 9, 17, 7]),
+ (136, [11, 22, 11, 6, 12, 6]),
+ (137, [10, 21, 10, 7, 15, 7]),
+ (138, [27, 3, 1, 26, 1, 0]),
+ (139, [18, 37, 18, 16, 32, 16]),
+ (140, [12, 23, 10, 9, 17, 7]),
+ (141, [12, 25, 12, 8, 17, 8]),
+ (142, [11, 21, 9, 2, 4, 1]),
+ (143, [7, 15, 7, 8, 18, 9]),
+ (144, [17, 33, 15, 13, 24, 11]),
+ (145, [9, 19, 9, 7, 15, 7]),
+ (146, [21, 43, 20, 13, 27, 12]),
+ (147, [17, 36, 17, 2, 4, 2]),
+ (148, [10, 20, 9, 6, 12, 5]),
+ (149, [20, 41, 19, 7, 14, 7]),
+ (150, [3, 9, 6, 2, 8, 5]),
+ (151, [13, 24, 10, 11, 20, 8]),
+ (152, [18, 38, 18, 4, 7, 3]),
+ (153, [19, 38, 18, 8, 17, 8]),
+ (154, [16, 35, 17, 4, 10, 4]),
+ (155, [11, 23, 11, 10, 21, 10]),
+ (156, [17, 36, 17, 7, 14, 7]),
+ (157, [13, 27, 13, 6, 12, 6]),
+ (158, [9, 15, 4, 8, 13, 4]),
+ (159, [10, 19, 7, 5, 9, 3]),
+ (160, [19, 40, 19, 11, 24, 11]),
+ (161, [11, 23, 11, 8, 17, 8]),
+ (162, [14, 29, 14, 7, 15, 7]),
+ (163, [12, 22, 9, 5, 8, 3]),
+ (164, [10, 20, 9, 8, 17, 8]),
+ (165, [21, 42, 19, 15, 31, 14]),
+ (166, [14, 29, 13, 1, 1, 0]),
+ (167, [8, 16, 8, 7, 14, 7]),
+ (168, [9, 18, 8, 8, 16, 7]),
+ (169, [10, 17, 7, 3, 4, 1]),
+ (170, [14, 28, 13, 2, 4, 1]),
+ (171, [14, 30, 14, 3, 6, 3]),
+ (172, [19, 38, 18, 5, 11, 5]),
+ (173, [12, 26, 12, 1, 2, 1]),
+ (174, [9, 16, 6, 8, 13, 5]),
+ (175, [8, 13, 4, 7, 11, 4]),
+ (176, [16, 34, 16, 3, 7, 3]),
+ (177, [13, 28, 13, 4, 9, 4]),
+ (178, [15, 31, 15, 6, 13, 6]),
+ (179, [12, 24, 11, 9, 19, 9]),
+ (180, [9, 19, 8, 7, 14, 6]),
+ (181, [14, 28, 13, 5, 10, 4]),
+ (182, [10, 20, 7, 4, 6, 2]),
+ (183, [16, 34, 17, 11, 25, 12]),
+ (184, [15, 30, 15, 8, 16, 8]),
+ (185, [13, 27, 13, 10, 20, 10]),
+ (186, [9, 20, 9, 0, 1, 0]),
+ (187, [16, 32, 15, 2, 4, 2]),
+ (188, [13, 27, 12, 3, 6, 3]),
+ (189, [13, 26, 12, 12, 23, 11]),
+ (190, [12, 25, 12, 5, 10, 5]),
+ (191, [11, 23, 11, 5, 11, 5]),
+ (192, [16, 34, 16, 6, 12, 5]),
+ (193, [16, 35, 31, 15, 25, 31]),
+ (194, [16, 33, 16, 7, 15, 7]),
+ (195, [13, 27, 13, 8, 18, 8]),
+ (196, [18, 36, 17, 11, 22, 10]),
+ (197, [18, 37, 18, 13, 27, 13]),
+ (198, [12, 25, 12, 4, 8, 4]),
+ (199, [9, 18, 7, 6, 11, 4]),
+ (200, [15, 30, 14, 9, 19, 9]),
+ (201, [17, 35, 16, 9, 18, 9]),
+ (202, [11, 24, 11, 2, 4, 2]),
+ (203, [16, 33, 16, 0, 1, 0]),
+ (204, [15, 31, 15, 4, 9, 4]),
+ (205, [16, 31, 15, 14, 27, 13]),
+ (206, [14, 29, 14, 13, 25, 12]),
+ (207, [11, 23, 11, 3, 6, 3]),
+ (208, [16, 32, 16, 10, 21, 10]),
+ (209, [11, 22, 11, 4, 9, 4]),
+ (210, [11, 22, 10, 1, 2, 0]),
+ (211, [8, 14, 5, 2, 4, 1]),
+ (212, [9, 16, 6, 6, 10, 4]),
+ (213, [10, 21, 10, 9, 19, 9]),
+ (214, [14, 30, 14, 11, 22, 11]),
+ (215, [9, 18, 8, 6, 13, 6]),
+ (216, [6, 13, 6, 5, 11, 5]),
+ (217, [7, 14, 6, 0, 1, 0]),
+ (218, [4, 7, 2, 3, 4, 1]),
+ (219, [10, 20, 9, 4, 8, 4]),
+ (220, [9, 17, 7, 5, 9, 3]),
+ (221, [7, 14, 7, 1, 2, 1]),
+ (222, [10, 20, 10, 5, 10, 5]),
+ (223, [8, 15, 5, 4, 6, 2]),
+ (224, [8, 17, 8, 1, 2, 1]),
+ (225, [10, 20, 10, 3, 6, 3]),
+ (226, [7, 10, 3, 6, 8, 3]),
+ (227, [8, 15, 7, 6, 12, 6]),
+ (228, [9, 19, 9, 2, 4, 2]),
+ (229, [6, 11, 4, 3, 4, 1]),
+ (230, [6, 11, 4, 0, 1, 0]),
+ (231, [8, 16, 7, 2, 4, 2]),
+ (232, [16, 34, 16, 15, 29, 15]),
+ (233, [7, 16, 7, 5, 10, 5]),
+ (234, [8, 14, 5, 5, 9, 3]),
+ (235, [9, 18, 8, 4, 8, 4]),
+ (236, [5, 9, 3, 4, 7, 2]),
+ (237, [9, 18, 8, 5, 10, 5]),
+ (238, [6, 12, 6, 2, 4, 2]),
+ (239, [7, 12, 5, 4, 7, 3]),
+ (240, [5, 11, 5, 1, 2, 1]),
+ (241, [8, 17, 8, 3, 6, 3]),
+ (242, [16, 31, 31, 16, 32, 31]),
+ (243, [7, 14, 7, 3, 6, 3]),
+ (244, [5, 11, 6, 4, 9, 4]),
+ (245, [7, 15, 7, 4, 8, 4]),
+ (246, [2, 4, 2, 0, 0, 1]),
+ (247, [5, 11, 5, 3, 6, 3]),
+ (248, [4, 8, 4, 1, 1, 1]),
+ (249, [3, 6, 3, 1, 2, 1]),
+ (250, [2, 4, 1, 1, 2, 1]),
+ (251, [4, 8, 4, 3, 6, 3]),
+ (252, [3, 6, 3, 2, 4, 2]),
+ (253, [4, 9, 4, 2, 4, 2]),
+ (254, [17, 27, 31, 15, 34, 31]),
+ (255, [0, 0, 1, 0, 0, 0]),
+];
+
+/// BC3: known entries of the built-in endpoint history (a0, a1, r0, g0, b0, r1, g1, b1).
+pub(super) const BC3_HISTORY: [(u8, [u8; 8]); 35] = [
+ (2, [177, 134, 27, 55, 24, 14, 54, 24]),
+ (26, [255, 255, 21, 34, 8, 15, 22, 3]),
+ (29, [220, 109, 17, 35, 17, 15, 30, 15]),
+ (30, [219, 96, 2, 53, 14, 2, 59, 16]),
+ (35, [95, 65, 16, 31, 16, 15, 31, 15]),
+ (37, [136, 13, 16, 33, 16, 15, 32, 15]),
+ (47, [146, 108, 18, 37, 18, 13, 26, 13]),
+ (52, [255, 255, 20, 38, 16, 3, 5, 2]),
+ (71, [200, 51, 17, 34, 17, 15, 31, 15]),
+ (76, [170, 150, 2, 60, 20, 1, 61, 20]),
+ (78, [248, 10, 3, 4, 2, 0, 1, 0]),
+ (95, [237, 229, 26, 51, 25, 1, 3, 1]),
+ (98, [255, 0, 19, 38, 18, 14, 29, 13]),
+ (104, [255, 6, 13, 27, 13, 8, 17, 8]),
+ (109, [254, 4, 15, 27, 11, 3, 4, 2]),
+ (112, [117, 39, 21, 41, 21, 1, 3, 1]),
+ (126, [170, 119, 16, 31, 16, 15, 30, 15]),
+ (138, [122, 121, 14, 29, 14, 13, 27, 13]),
+ (139, [247, 1, 15, 28, 13, 9, 16, 7]),
+ (153, [105, 126, 2, 7, 4, 1, 3, 2]),
+ (154, [93, 100, 20, 40, 20, 15, 30, 15]),
+ (166, [91, 99, 17, 35, 17, 15, 30, 15]),
+ (167, [155, 99, 16, 33, 16, 15, 31, 15]),
+ (177, [255, 255, 13, 24, 12, 11, 23, 10]),
+ (185, [254, 255, 10, 17, 7, 2, 3, 1]),
+ (197, [253, 255, 11, 20, 9, 6, 11, 4]),
+ (210, [254, 255, 5, 10, 5, 1, 2, 1]),
+ (220, [255, 255, 11, 20, 9, 9, 17, 7]),
+ (225, [106, 113, 24, 39, 23, 0, 13, 0]),
+ (226, [1, 255, 8, 15, 7, 5, 10, 4]),
+ (230, [1, 2, 0, 1, 1, 0, 0, 0]),
+ (232, [140, 131, 16, 31, 16, 15, 34, 16]),
+ (237, [255, 254, 5, 11, 5, 4, 9, 3]),
+ (244, [255, 255, 1, 1, 1, 0, 0, 0]),
+ (246, [253, 254, 3, 5, 2, 1, 2, 1]),
+];
+
+/// BC4: known entries of the built-in endpoint history (a0, a1).
+pub(super) const BC4_HISTORY: [(u8, [u8; 2]); 172] = [
+ (3, [122, 77]),
+ (15, [67, 91]),
+ (25, [83, 49]),
+ (32, [114, 158]),
+ (33, [58, 31]),
+ (34, [83, 58]),
+ (35, [103, 121]),
+ (40, [246, 65]),
+ (41, [244, 137]),
+ (42, [101, 141]),
+ (43, [181, 141]),
+ (49, [224, 201]),
+ (52, [217, 182]),
+ (55, [227, 73]),
+ (57, [213, 205]),
+ (60, [125, 83]),
+ (62, [243, 91]),
+ (63, [214, 190]),
+ (64, [226, 53]),
+ (66, [230, 227]),
+ (69, [156, 116]),
+ (70, [250, 174]),
+ (71, [220, 86]),
+ (72, [238, 115]),
+ (73, [227, 42]),
+ (74, [166, 80]),
+ (75, [200, 166]),
+ (77, [164, 124]),
+ (80, [74, 115]),
+ (81, [83, 99]),
+ (82, [186, 74]),
+ (83, [140, 148]),
+ (84, [204, 141]),
+ (85, [220, 103]),
+ (86, [208, 44]),
+ (87, [147, 108]),
+ (88, [190, 88]),
+ (90, [203, 82]),
+ (91, [222, 142]),
+ (92, [218, 217]),
+ (93, [206, 63]),
+ (94, [186, 189]),
+ (96, [197, 48]),
+ (98, [203, 203]),
+ (99, [147, 116]),
+ (100, [196, 14]),
+ (101, [172, 137]),
+ (102, [214, 124]),
+ (103, [200, 174]),
+ (104, [122, 83]),
+ (105, [152, 157]),
+ (106, [88, 51]),
+ (107, [178, 87]),
+ (108, [169, 149]),
+ (109, [170, 98]),
+ (110, [171, 71]),
+ (111, [202, 183]),
+ (112, [138, 100]),
+ (114, [153, 148]),
+ (116, [77, 34]),
+ (117, [140, 82]),
+ (118, [171, 106]),
+ (119, [194, 127]),
+ (120, [197, 193]),
+ (121, [179, 118]),
+ (123, [190, 161]),
+ (124, [179, 167]),
+ (125, [115, 126]),
+ (126, [139, 108]),
+ (127, [132, 115]),
+ (128, [161, 89]),
+ (129, [182, 152]),
+ (130, [186, 61]),
+ (131, [165, 56]),
+ (132, [170, 175]),
+ (133, [186, 177]),
+ (134, [167, 159]),
+ (135, [153, 81]),
+ (137, [145, 140]),
+ (139, [151, 94]),
+ (140, [57, 74]),
+ (141, [112, 107]),
+ (142, [132, 91]),
+ (145, [74, 16]),
+ (147, [177, 43]),
+ (148, [151, 124]),
+ (149, [123, 107]),
+ (150, [145, 73]),
+ (151, [113, 75]),
+ (152, [75, 71]),
+ (153, [107, 90]),
+ (154, [194, 106]),
+ (155, [158, 69]),
+ (156, [159, 40]),
+ (157, [71, 51]),
+ (158, [144, 132]),
+ (159, [156, 15]),
+ (160, [144, 62]),
+ (161, [81, 75]),
+ (162, [122, 91]),
+ (163, [55, 33]),
+ (164, [76, 58]),
+ (165, [152, 53]),
+ (167, [89, 83]),
+ (168, [114, 83]),
+ (169, [65, 74]),
+ (171, [152, 39]),
+ (172, [140, 119]),
+ (173, [42, 15]),
+ (174, [65, 41]),
+ (175, [114, 91]),
+ (178, [90, 50]),
+ (179, [48, 8]),
+ (180, [102, 102]),
+ (181, [132, 70]),
+ (182, [73, 56]),
+ (183, [123, 119]),
+ (184, [72, 34]),
+ (185, [159, 136]),
+ (186, [131, 107]),
+ (187, [105, 12]),
+ (188, [143, 40]),
+ (189, [113, 99]),
+ (190, [43, 25]),
+ (192, [79, 85]),
+ (193, [126, 100]),
+ (195, [98, 58]),
+ (196, [90, 74]),
+ (197, [133, 135]),
+ (198, [96, 90]),
+ (200, [55, 17]),
+ (202, [82, 42]),
+ (203, [71, 66]),
+ (204, [133, 52]),
+ (205, [89, 58]),
+ (206, [113, 6]),
+ (207, [132, 123]),
+ (208, [39, 9]),
+ (209, [136, 27]),
+ (211, [39, 23]),
+ (212, [81, 50]),
+ (213, [19, 41]),
+ (214, [39, 17]),
+ (215, [103, 82]),
+ (217, [115, 21]),
+ (218, [120, 60]),
+ (219, [81, 58]),
+ (220, [73, 42]),
+ (221, [47, 17]),
+ (223, [64, 25]),
+ (224, [119, 34]),
+ (226, [66, 58]),
+ (227, [33, 16]),
+ (228, [101, 67]),
+ (229, [66, 49]),
+ (230, [101, 75]),
+ (232, [78, 5]),
+ (234, [33, 60]),
+ (235, [57, 24]),
+ (236, [69, 2]),
+ (239, [105, 25]),
+ (240, [96, 35]),
+ (241, [112, 46]),
+ (243, [47, 25]),
+ (244, [88, 22]),
+ (245, [85, 66]),
+ (246, [49, 33]),
+ (247, [22, 17]),
+ (248, [55, 41]),
+ (250, [130, 129]),
+ (252, [27, 8]),
+ (254, [12, 6]),
+];
+
+/// BC5: known entries of the built-in endpoint history (r0, r1, g0, g1).
+pub(super) const BC5_HISTORY: [(u8, [u8; 4]); 214] = [
+ (3, [130, 218, 45, 192]),
+ (4, [172, 109, 158, 94]),
+ (5, [183, 136, 113, 69]),
+ (6, [125, 129, 86, 34]),
+ (7, [171, 196, 33, 82]),
+ (9, [142, 149, 102, 118]),
+ (14, [82, 62, 26, 23]),
+ (15, [100, 94, 32, 32]),
+ (16, [97, 123, 61, 97]),
+ (19, [133, 140, 118, 123]),
+ (20, [206, 194, 128, 123]),
+ (22, [147, 145, 64, 66]),
+ (24, [76, 189, 55, 171]),
+ (27, [94, 115, 86, 102]),
+ (28, [163, 38, 152, 29]),
+ (29, [143, 133, 89, 80]),
+ (30, [197, 67, 172, 50]),
+ (31, [164, 218, 130, 127]),
+ (32, [141, 145, 111, 132]),
+ (33, [177, 125, 131, 32]),
+ (34, [49, 113, 26, 94]),
+ (36, [173, 169, 40, 28]),
+ (38, [117, 125, 43, 50]),
+ (39, [139, 111, 99, 72]),
+ (40, [123, 93, 83, 49]),
+ (41, [189, 166, 135, 116]),
+ (42, [198, 97, 178, 73]),
+ (43, [205, 201, 76, 86]),
+ (44, [172, 174, 73, 72]),
+ (46, [157, 210, 136, 188]),
+ (47, [126, 149, 115, 129]),
+ (48, [158, 67, 137, 41]),
+ (49, [214, 120, 131, 80]),
+ (51, [147, 150, 119, 119]),
+ (52, [169, 107, 135, 65]),
+ (54, [231, 168, 223, 154]),
+ (55, [115, 144, 99, 120]),
+ (56, [74, 104, 50, 83]),
+ (57, [220, 132, 32, 123]),
+ (58, [150, 136, 110, 96]),
+ (60, [139, 147, 124, 108]),
+ (61, [121, 124, 78, 94]),
+ (63, [169, 151, 124, 103]),
+ (64, [120, 106, 103, 88]),
+ (65, [134, 147, 110, 109]),
+ (67, [133, 125, 103, 107]),
+ (68, [160, 133, 118, 123]),
+ (69, [175, 78, 163, 68]),
+ (70, [229, 133, 166, 121]),
+ (71, [233, 147, 224, 134]),
+ (72, [127, 142, 104, 121]),
+ (73, [134, 150, 99, 121]),
+ (74, [110, 149, 83, 129]),
+ (75, [175, 187, 129, 141]),
+ (77, [115, 124, 96, 104]),
+ (78, [164, 128, 141, 109]),
+ (79, [129, 85, 114, 22]),
+ (80, [246, 131, 241, 125]),
+ (82, [168, 186, 145, 165]),
+ (83, [192, 133, 158, 100]),
+ (84, [107, 143, 105, 133]),
+ (85, [201, 212, 172, 181]),
+ (86, [124, 138, 116, 121]),
+ (87, [92, 60, 71, 40]),
+ (88, [203, 134, 149, 126]),
+ (90, [61, 123, 25, 114]),
+ (91, [123, 160, 113, 145]),
+ (92, [150, 169, 135, 150]),
+ (93, [134, 139, 101, 109]),
+ (94, [253, 94, 255, 63]),
+ (95, [123, 87, 106, 67]),
+ (96, [238, 133, 121, 121]),
+ (98, [24, 18, 15, 10]),
+ (99, [117, 41, 97, 25]),
+ (100, [123, 121, 70, 67]),
+ (101, [64, 59, 51, 49]),
+ (102, [11, 103, 12, 88]),
+ (103, [144, 133, 111, 123]),
+ (104, [189, 200, 65, 52]),
+ (105, [219, 153, 195, 135]),
+ (106, [150, 110, 138, 98]),
+ (107, [118, 142, 60, 117]),
+ (108, [139, 145, 114, 118]),
+ (109, [216, 225, 191, 200]),
+ (110, [46, 46, 38, 33]),
+ (111, [91, 132, 85, 126]),
+ (112, [154, 178, 115, 132]),
+ (114, [132, 126, 122, 15]),
+ (115, [136, 134, 15, 123]),
+ (116, [131, 129, 105, 123]),
+ (119, [132, 215, 122, 149]),
+ (120, [129, 138, 112, 111]),
+ (123, [136, 145, 119, 131]),
+ (124, [179, 196, 165, 183]),
+ (125, [126, 125, 111, 92]),
+ (126, [136, 150, 122, 123]),
+ (127, [168, 158, 136, 126]),
+ (128, [146, 153, 129, 134]),
+ (129, [127, 130, 85, 124]),
+ (130, [132, 241, 120, 126]),
+ (131, [155, 124, 125, 85]),
+ (132, [121, 115, 115, 108]),
+ (133, [106, 72, 89, 51]),
+ (134, [136, 155, 118, 137]),
+ (135, [121, 145, 106, 133]),
+ (136, [119, 220, 102, 209]),
+ (137, [179, 136, 150, 122]),
+ (138, [120, 133, 102, 113]),
+ (139, [145, 142, 111, 112]),
+ (140, [130, 108, 123, 62]),
+ (141, [121, 132, 37, 122]),
+ (142, [157, 142, 135, 119]),
+ (143, [80, 201, 59, 191]),
+ (144, [130, 133, 122, 104]),
+ (145, [138, 136, 112, 120]),
+ (146, [131, 107, 123, 37]),
+ (147, [122, 120, 107, 119]),
+ (148, [126, 181, 121, 146]),
+ (149, [143, 141, 137, 135]),
+ (150, [134, 178, 121, 161]),
+ (151, [103, 135, 55, 126]),
+ (152, [193, 132, 128, 123]),
+ (153, [141, 129, 111, 114]),
+ (154, [79, 77, 53, 51]),
+ (155, [133, 72, 127, 64]),
+ (157, [102, 101, 83, 80]),
+ (159, [92, 137, 39, 125]),
+ (160, [108, 136, 87, 122]),
+ (161, [102, 97, 65, 57]),
+ (162, [163, 149, 151, 134]),
+ (163, [133, 17, 121, 15]),
+ (165, [179, 162, 153, 133]),
+ (166, [119, 132, 98, 125]),
+ (167, [175, 132, 130, 124]),
+ (169, [132, 92, 124, 81]),
+ (170, [40, 31, 27, 19]),
+ (171, [188, 211, 180, 202]),
+ (172, [139, 121, 117, 101]),
+ (173, [150, 125, 130, 106]),
+ (174, [129, 184, 123, 131]),
+ (175, [132, 158, 126, 148]),
+ (176, [130, 155, 126, 129]),
+ (177, [131, 167, 124, 127]),
+ (178, [155, 131, 132, 125]),
+ (179, [198, 139, 170, 124]),
+ (180, [200, 196, 190, 186]),
+ (182, [133, 126, 124, 55]),
+ (183, [128, 126, 116, 112]),
+ (184, [173, 157, 163, 147]),
+ (185, [197, 175, 158, 137]),
+ (186, [102, 129, 98, 126]),
+ (187, [131, 216, 121, 198]),
+ (188, [127, 135, 115, 130]),
+ (189, [139, 196, 94, 111]),
+ (190, [132, 106, 123, 94]),
+ (191, [219, 130, 193, 116]),
+ (192, [212, 133, 127, 124]),
+ (193, [196, 176, 173, 151]),
+ (194, [56, 192, 15, 27]),
+ (195, [129, 198, 124, 131]),
+ (196, [131, 124, 125, 99]),
+ (197, [176, 130, 169, 126]),
+ (198, [137, 127, 121, 111]),
+ (199, [144, 137, 131, 123]),
+ (200, [132, 130, 114, 120]),
+ (201, [182, 165, 169, 153]),
+ (202, [138, 136, 113, 109]),
+ (203, [185, 172, 179, 164]),
+ (204, [131, 127, 123, 81]),
+ (205, [124, 141, 121, 137]),
+ (206, [173, 131, 136, 92]),
+ (208, [120, 133, 108, 123]),
+ (209, [147, 134, 123, 110]),
+ (210, [130, 142, 125, 129]),
+ (211, [136, 137, 122, 131]),
+ (212, [130, 119, 127, 114]),
+ (214, [117, 136, 111, 131]),
+ (215, [199, 181, 187, 167]),
+ (216, [132, 215, 124, 125]),
+ (217, [135, 138, 120, 114]),
+ (218, [131, 85, 123, 45]),
+ (219, [197, 131, 193, 126]),
+ (221, [69, 206, 57, 195]),
+ (222, [131, 128, 123, 37]),
+ (223, [161, 156, 96, 92]),
+ (225, [130, 136, 123, 121]),
+ (226, [126, 60, 118, 46]),
+ (227, [139, 137, 120, 124]),
+ (228, [140, 130, 124, 123]),
+ (229, [122, 127, 118, 123]),
+ (231, [130, 141, 127, 138]),
+ (232, [54, 205, 50, 185]),
+ (233, [75, 74, 69, 68]),
+ (234, [223, 130, 217, 125]),
+ (235, [111, 129, 108, 127]),
+ (236, [160, 129, 157, 126]),
+ (237, [129, 217, 126, 217]),
+ (238, [148, 128, 146, 126]),
+ (239, [130, 129, 127, 118]),
+ (241, [60, 200, 50, 200]),
+ (242, [131, 130, 120, 124]),
+ (243, [123, 132, 116, 127]),
+ (244, [132, 135, 130, 132]),
+ (245, [129, 41, 126, 37]),
+ (246, [122, 133, 120, 133]),
+ (247, [118, 128, 116, 126]),
+ (248, [136, 128, 133, 126]),
+ (249, [128, 133, 123, 131]),
+ (250, [82, 81, 78, 77]),
+ (251, [124, 130, 122, 128]),
+ (252, [130, 130, 125, 124]),
+ (253, [128, 128, 127, 127]),
+ (254, [127, 126, 126, 125]),
+ (255, [129, 127, 128, 126]),
+];
diff --git a/crates/rage-formats/src/drawable6.rs b/crates/rage-formats/src/drawable6.rs
new file mode 100644
index 0000000..4718920
--- /dev/null
+++ b/crates/rage-formats/src/drawable6.rs
@@ -0,0 +1,626 @@
+//! GTA VI models: drawables, fragments and drawable dictionaries.
+//!
+//! A model resource has two parts: the *system* part with the structures,
+//! and the *graphics* part with vertex and index data. Pointers are 64-bit
+//! addresses, from `0x5000_0000` into the system part and from
+//! `0x6000_0000` into the graphics part. All of it is little-endian.
+//!
+//! The resource starts with one of three roots, each with zero in its first
+//! eight bytes and at 8 a pointer to the page counts:
+//! - a **drawable**: shader group (16), radius (44), bounds (48, 64), four
+//! levels of detail (80 to 104), name (168);
+//! - a **fragment**: its drawable (24) and name (168);
+//! - a **drawable dictionary**: name hashes (32) and drawables (48), with
+//! their number at 40, 42, 56 and 58.
+//!
+//! A level of detail lists *models* (pointers, count at 8); a model lists
+//! *geometries* (pointers at 8, count at 16) with their bounds (24) and
+//! shaders (32, a 16-bit index each). A geometry has a vertex buffer (8) and,
+//! through a descriptor (64), an index buffer.
+//!
+//! A buffer says how many elements of how many bytes it has (8, 12) and
+//! where they are in the graphics part (24). The vertex buffer's format (64)
+//! has, for each of the vertex's parts: its offset in the buffer (4 bytes
+//! each from 0), its size (a byte each from `0xD0`) and its encoding (a byte
+//! each from `0x104`); the vertex count is in the word at `0x138`, from bit
+//! 10 on. So a buffer holds all positions, then all texture coordinates, …
+//!
+//! - Positions (part 0): three floats, or 64 bits of fixed point (24, 24
+//! and 16 bits) with a bias and a scale in the buffer's first bytes and an
+//! order of the axes.
+//! - Texture coordinates (part 28): two floats, or two 16-bit numbers with a
+//! scale.
+//!
+//! The index buffer is cut into *clusters* of up to 128 vertices and 256
+//! triangles: a list of the vertices each cluster uses, and triangles as
+//! three 7-bit numbers into its cluster's list.
+//!
+//! A shader names its textures by keys into the texture pools
+//! ([`crate::ttpf`]); of those, the one for the base colour is read.
+//!
+//! Not read: the other textures of materials, skeletons and skinning, the
+//! lower levels of detail.
+//!
+//! The layout is the one found by the rpf9-explorer project
+//! (), whose decoder was read to
+//! learn it; this reader is written anew.
+
+use rage_core::bytes::LeRead;
+
+use crate::drawable::{Drawable, Mesh, Shader};
+
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum ModelError {
+ #[error("not a GTA VI model")]
+ NotAModel,
+ /// The graphics part ends before the data a buffer points to: at least
+ /// this many bytes are needed.
+ #[error("the model's vertex or index data is missing ({0} bytes are needed)")]
+ Graphics(usize),
+ #[error("damaged or unknown model data: {0}")]
+ Bad(String),
+}
+
+fn bad(msg: impl Into) -> ModelError {
+ ModelError::Bad(msg.into())
+}
+
+const SYSTEM: u64 = 0x5000_0000;
+const GRAPHICS: u64 = 0x6000_0000;
+/// No part of a resource is larger than this.
+const MAX_PART: u64 = 256 << 20;
+const MAX_VERTICES: usize = 1_000_000;
+const MAX_MESHES: usize = 1024;
+/// Slots of the vertex format.
+const POSITION: usize = 0;
+const TEXCOORD: usize = 28;
+
+/// The parameters of shaders that hold the base colour, the best first:
+/// `diffusetex`, `diffusetexture`, and the first layer of the layered ones
+/// (`lyr0diffusetex`, `diffusetexture_layer0`). Other textures of a shader
+/// (normals, specular, masks) are not colours and must not stand in.
+const BASE_COLOUR: [u32; 4] = [0xC8E8_C282, 0x2D14_F172, 0x3463_94EA, 0xCE7B_968E];
+
+/// The name a texture of the pools goes by in a model: its key.
+pub fn texture_name(key: u64) -> String {
+ format!("{key:016x}")
+}
+
+/// What a resource starts with.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Root {
+ Drawable,
+ Fragment,
+ Dictionary,
+}
+
+fn system_pointer(d: &[u8], at: usize) -> Option {
+ let p = d.u64_at(at)?;
+ (SYSTEM..SYSTEM + MAX_PART).contains(&p).then(|| (p - SYSTEM) as usize)
+}
+
+fn vec3(d: &[u8], at: usize) -> Option<[f32; 3]> {
+ let f = |o| d.u32_at(at + o).map(f32::from_bits).filter(|v: &f32| v.is_finite() && v.abs() < 1e7);
+ Some([f(0)?, f(4)?, f(8)?])
+}
+
+/// Whether a drawable starts at `at`: bounds that make sense, and pointers
+/// where it has them. One inside another resource has no page counts.
+fn is_drawable(d: &[u8], at: usize, inside: bool) -> bool {
+ let check = || -> Option {
+ let (min, max) = (vec3(d, at + 48)?, vec3(d, at + 64)?);
+ let radius = f32::from_bits(d.u32_at(at + 44)?);
+ let pages = if inside { d.u64_at(at + 8)? == 0 } else { system_pointer(d, at + 8).is_some() };
+ let name = system_pointer(d, at + 168).is_some() || (inside && d.u64_at(at + 168)? == 0);
+ Some(
+ d.u64_at(at)? == 0
+ && pages
+ && name
+ && system_pointer(d, at + 16).is_some()
+ && system_pointer(d, at + 80).is_some()
+ && (0..3).all(|i| min[i] <= max[i])
+ && (0.0..1e6).contains(&radius),
+ )
+ };
+ check().unwrap_or(false)
+}
+
+/// What the resource whose system part starts with these bytes is; `None`
+/// if it is no model, or if the bytes end before the drawable of a fragment
+/// or the first one of a dictionary.
+pub fn root(system: &[u8]) -> Option {
+ if system.u64_at(0)? != 0 || system_pointer(system, 8).is_none() {
+ return None;
+ }
+ if is_drawable(system, 0, false) {
+ return Some(Root::Drawable);
+ }
+ let optional = |at| system.u64_at(at) == Some(0) || system_pointer(system, at).is_some();
+ let counts = |at| system.u16_at(at).filter(|n| *n <= 4096);
+ if system_pointer(system, 24).is_some()
+ && system_pointer(system, 168).is_some()
+ && [16, 32, 40].into_iter().all(optional)
+ && counts(48)? > 0
+ && counts(50).is_some()
+ && counts(52)? <= counts(54)?
+ {
+ // Other resources have pointers and small numbers there too: what
+ // tells a fragment is the drawable it points to.
+ return is_drawable(system, system_pointer(system, 24)?, true).then_some(Root::Fragment);
+ }
+ let count = system.u16_at(56)?;
+ let first = || is_drawable(system, system_pointer(system, system_pointer(system, 48)?)?, true).then_some(());
+ (count > 0
+ && [40, 42, 58].into_iter().all(|at| system.u16_at(at) == Some(count))
+ && system_pointer(system, 32).is_some()
+ && first().is_some())
+ .then_some(Root::Dictionary)
+}
+
+/// The name of the model whose system part starts with these bytes: a
+/// drawable's or a fragment's own name. `None` for anything else, for a
+/// dictionary (its drawables have names, it has none), and when the name
+/// lies after these bytes.
+pub fn name(system: &[u8]) -> Option {
+ let text = |pointer_at: usize| -> Option {
+ let bytes = system.get(system_pointer(system, pointer_at)?..)?;
+ let bytes = &bytes[..bytes.len().min(256)];
+ let name = std::str::from_utf8(&bytes[..bytes.iter().position(|b| *b == 0)?]).ok()?;
+ (!name.is_empty() && !name.chars().any(char::is_control)).then(|| name.to_owned())
+ };
+ match root(system)? {
+ Root::Drawable => text(168),
+ // The drawable inside is named like the fragment, with `.#ft`.
+ Root::Fragment => {
+ system_pointer(system, 24).and_then(|at| text(at + 168)).or_else(|| text(168).map(|n| format!("{n}.#ft")))
+ }
+ Root::Dictionary => None,
+ }
+}
+
+struct Reader<'a> {
+ sys: &'a [u8],
+ gfx: &'a [u8],
+}
+
+impl<'a> Reader<'a> {
+ /// The system offset a pointer at `at` leads to, with `size` bytes there.
+ fn s(&self, at: usize, size: usize) -> Result {
+ let to = system_pointer(self.sys, at).ok_or_else(|| bad("a pointer that leads nowhere"))?;
+ if to + size > self.sys.len() { Err(bad("a structure outside the resource")) } else { Ok(to) }
+ }
+
+ /// The bytes of the graphics part a pointer at `at` leads to.
+ fn g(&self, at: usize, size: usize) -> Result<&'a [u8], ModelError> {
+ let p = self.sys.u64_at(at).filter(|p| (GRAPHICS..GRAPHICS + MAX_PART).contains(p));
+ let to = (p.ok_or_else(|| bad("a buffer that leads nowhere"))? - GRAPHICS) as usize;
+ self.gfx.get(to..to + size).ok_or(ModelError::Graphics(to + size))
+ }
+
+ fn u16(&self, at: usize) -> Result {
+ self.sys.u16_at(at).map(usize::from).ok_or_else(|| bad("truncated"))
+ }
+
+ fn u32(&self, at: usize) -> Result {
+ self.sys.u32_at(at).ok_or_else(|| bad("truncated"))
+ }
+
+ fn name(&self, at: usize) -> Result {
+ let from = self.s(at, 1)?;
+ let bytes = &self.sys[from..self.sys.len().min(from + 256)];
+ let len = bytes.iter().position(|b| *b == 0).ok_or_else(|| bad("a name without an end"))?;
+ Ok(String::from_utf8_lossy(&bytes[..len]).into_owned())
+ }
+
+ /// Where a buffer's data is: element count × element size bytes.
+ fn buffer(&self, at: usize) -> Result<(&'a [u8], usize), ModelError> {
+ let (count, stride) = (self.u32(at + 8)? as usize, self.u16(at + 12)?);
+ let len = count.checked_mul(stride).filter(|n| (1..=MAX_PART as usize).contains(n));
+ Ok((self.g(at + 24, len.ok_or_else(|| bad("a buffer of an impossible size"))?)?, stride))
+ }
+
+ fn drawable(&self, at: usize, fallback_name: &str) -> Result {
+ if at + 176 > self.sys.len() {
+ return Err(bad("a drawable outside the resource"));
+ }
+ let name = if self.sys.u64_at(at + 168) == Some(0) { fallback_name.to_owned() } else { self.name(at + 168)? };
+ let bounds = |o| vec3(self.sys, at + o).ok_or_else(|| bad("bounds that are no numbers"));
+ // The most detailed level.
+ let lod = self.s(at + 80, 16)?;
+ let models = self.u16(lod + 8)?;
+ if !(1..=256).contains(&models) {
+ return Err(bad("an impossible number of models"));
+ }
+ let list = self.s(lod, models * 8)?;
+ let mut meshes = Vec::new();
+ for m in 0..models {
+ let model = self.s(list + m * 8, 56)?;
+ let count = self.u16(model + 16)?;
+ if !(1..=MAX_MESHES).contains(&count) || meshes.len() + count > MAX_MESHES {
+ return Err(bad("an impossible number of geometries"));
+ }
+ let geometries = self.s(model + 8, count * 8)?;
+ let shaders = self.s(model + 32, count * 2).ok();
+ for g in 0..count {
+ let mut mesh = self.mesh(self.s(geometries + g * 8, 160)?)?;
+ mesh.shader = shaders.and_then(|s| self.sys.u16_at(s + g * 2)).unwrap_or(0);
+ meshes.push(mesh);
+ }
+ }
+ Ok(Drawable {
+ name,
+ meshes,
+ shaders: self.shaders(at).unwrap_or_default(),
+ textures: None,
+ bounds_min: bounds(48)?,
+ bounds_max: bounds(64)?,
+ skeleton: None,
+ })
+ }
+
+ /// The key of the texture a shader binds to one of the parameters for
+ /// the base colour. A shader (64 bytes) has its textures at 16 and, at
+ /// 32, counts and its parameters: 8 bytes each from 8 on, the name hash
+ /// and a word whose low two bits are 0 for a texture, with its number in
+ /// the next eight. A texture (80 bytes) points at 48 to its asset, whose
+ /// second word is the key by which the texture pools know it.
+ fn base_texture(&self, shader: usize) -> Option {
+ let info = self.s(shader + 32, 8).ok()?;
+ let (textures, parameters) = (usize::from(self.sys[info + 1]), usize::from(self.sys[info + 4]));
+ let list = self.s(shader + 16, textures * 8).ok()?;
+ let key = |parameter: usize| -> Option<(u32, u64)> {
+ let at = info + 8 + parameter * 8;
+ let (name, data) = (self.sys.u32_at(at)?, self.sys.u32_at(at + 4)?);
+ let number = (data >> 2 & 255) as usize;
+ if data & 3 != 0 || number >= textures {
+ return None;
+ }
+ let texture = self.s(list + number * 8, 80).ok()?;
+ let asset = self.s(texture + 48, 16).ok()?;
+ let key = self.sys.u64_at(asset + 8).filter(|k| *k != 0)?;
+ // In front of an asset: its kind, 6 for a texture of the pools.
+ (self.sys.u32_at(asset.checked_sub(16)?)? == 6).then_some((name, key))
+ };
+ let bound: Vec<(u32, u64)> = (0..parameters).filter_map(key).collect();
+ BASE_COLOUR.iter().find_map(|wanted| bound.iter().find(|(name, _)| name == wanted).map(|(_, key)| *key))
+ }
+
+ /// The shaders of a drawable, by their name hashes, each with the
+ /// texture of its base colour: named by its key in the texture pools
+ /// (16 hexadecimal digits).
+ fn shaders(&self, drawable: usize) -> Result, ModelError> {
+ let group = self.s(drawable + 16, 64)?;
+ let count = self.u16(group + 24)?;
+ if count == 0 || count > 512 {
+ return Ok(Vec::new());
+ }
+ let list = self.s(group + 16, count * 8)?;
+ (0..count)
+ .map(|i| {
+ let shader = self.s(list + i * 8, 64)?;
+ let texture: Vec = self.base_texture(shader).map(texture_name).into_iter().collect();
+ let samplers = texture.iter().map(|name| (crate::drawable::param::DIFFUSE_TEX, name.clone())).collect();
+ Ok(Shader { name_hash: self.u32(shader)?, textures: texture, samplers })
+ })
+ .collect()
+ }
+
+ fn mesh(&self, geometry: usize) -> Result {
+ let vb = self.s(geometry + 8, 80)?;
+ let format = self.s(vb + 64, 320)?;
+ let flags = self.u32(format + 0x138)?;
+ let vertices = (flags >> 10) as usize;
+ if flags & 1 == 0 || !(1..=MAX_VERTICES).contains(&vertices) {
+ return Err(bad("an impossible vertex count"));
+ }
+ let (data, _) = self.buffer(vb)?;
+ let part = |slot: usize| -> (usize, u8, u8) {
+ let offset = self.sys.u32_at(format + slot * 4).unwrap_or(0) as usize;
+ (offset, self.sys[format + 0xD0 + slot], self.sys[format + 0x104 + slot])
+ };
+ let within = |offset: usize, size: usize| {
+ offset.checked_add(vertices * size).filter(|end| *end <= data.len()).map(|_| offset)
+ };
+
+ let (offset, size, encoding) = part(POSITION);
+ let at = within(offset, usize::from(size)).ok_or_else(|| bad("positions outside their buffer"))?;
+ let positions: Vec<[f32; 3]> = match (size, encoding) {
+ (12, 6) => (0..vertices).map(|i| vec3(data, at + i * 12)).collect::>(),
+ // Fixed point: 24 bits, 24 bits (the lowest byte and two more
+ // above the first number) and 16 bits.
+ (8, 16) => (|| {
+ let (bias, scale, axes) = (vec3(data, 96)?, vec3(data, 112)?, data.u32_at(108)?);
+ let numbers = data[at..at + vertices * 8].as_chunks::<8>().0;
+ Some(
+ numbers
+ .iter()
+ .map(|c| {
+ let q = u64::from_le_bytes(*c);
+ let parts = [q >> 8 & 0xFF_FFFF, (q >> 32 & 0xFFFF) << 8 | q & 0xFF, q >> 48];
+ let p: [f32; 3] = std::array::from_fn(|k| {
+ (f64::from(bias[k]) + f64::from(scale[k]) * parts[k] as f64) as f32
+ });
+ match axes {
+ 0 => [p[2], p[1], p[0]],
+ 1 => [p[1], p[2], p[0]],
+ _ => p,
+ }
+ })
+ .collect(),
+ )
+ })(),
+ _ => return Err(bad(format!("positions of an unknown kind ({size} bytes, encoding {encoding})"))),
+ }
+ .ok_or_else(|| bad("positions that are no numbers"))?;
+
+ let (offset, size, encoding) = part(TEXCOORD);
+ let uvs: Vec<[f32; 2]> = match (size, encoding, within(offset, usize::from(size))) {
+ (8, 16, Some(at)) => data[at..at + vertices * 8]
+ .as_chunks::<8>()
+ .0
+ .iter()
+ .map(|c| [f32::from_le_bytes([c[0], c[1], c[2], c[3]]), f32::from_le_bytes([c[4], c[5], c[6], c[7]])])
+ .collect(),
+ (4, 38, Some(at)) => {
+ let scale = data.u32_at(124).map(f32::from_bits).filter(|s| s.is_finite()).unwrap_or(1.0);
+ let number = |a: u8, b: u8| (f32::from(i16::from_le_bytes([a, b])) / 32767.0).max(-1.0) * scale;
+ data[at..at + vertices * 4]
+ .as_chunks::<4>()
+ .0
+ .iter()
+ .map(|c| [number(c[0], c[1]), number(c[2], c[3])])
+ .collect()
+ }
+ _ => Vec::new(),
+ };
+
+ let descriptor = self.s(geometry + 64, 16)?;
+ let (index, stride) = self.buffer(self.s(descriptor, 64)?)?;
+ if stride != 4 {
+ return Err(bad("an index buffer of an unknown kind"));
+ }
+ let indices = clusters(index, vertices)?;
+ let normals = smooth_normals(&positions, &indices);
+ Ok(Mesh { positions, normals, uvs, indices, ..Default::default() })
+ }
+}
+
+/// The triangles of an index buffer: a word of flags and the cluster count,
+/// the triangle count, the count of vertex references; 16 bytes per cluster
+/// (vertices and triangles minus one in 7 and 8 bits, then where its
+/// references and triangles start); a word per triangle (three 7-bit numbers
+/// into the cluster's references, the cluster from bit 21); the references
+/// (16 bits each if the top flag is set, else 32).
+fn clusters(index: &[u8], vertices: usize) -> Result, ModelError> {
+ let word = |at: usize| index.u32_at(at).ok_or_else(|| bad("an index buffer that is cut off"));
+ let flags = word(0)?;
+ let cluster_count = (flags & if flags & 0x4000_0000 != 0 { 0xFFFF } else { 0x7FFF_FFFF }) as usize;
+ let (triangles, refs) = (word(4)? as usize, word(8)? as usize);
+ if !(1..=2048).contains(&cluster_count) || !(1..=65535).contains(&triangles) || !(1..=65535).contains(&refs) {
+ return Err(bad("impossible counts in an index buffer"));
+ }
+ let wide = flags & 0x8000_0000 == 0;
+ let (triangles_at, refs_at) = (12 + cluster_count * 16, 12 + cluster_count * 16 + triangles * 4);
+ let reference = |i: usize| -> Result {
+ let v = if wide {
+ word(refs_at + i * 4)?
+ } else {
+ u32::from(index.u16_at(refs_at + i * 2).ok_or_else(|| bad("truncated"))?)
+ };
+ if (v as usize) < vertices { Ok(v) } else { Err(bad("a triangle with a vertex that does not exist")) }
+ };
+ let mut out = Vec::with_capacity(triangles * 3);
+ for cluster in 0..cluster_count {
+ let (counts, starts) = (word(12 + cluster * 16)?, word(16 + cluster * 16)?);
+ let (own_refs, own_triangles) = ((counts & 127) as usize + 1, (counts >> 7 & 255) as usize + 1);
+ let (first_ref, first_triangle) = ((starts & 0xFFFF) as usize, (starts >> 16) as usize);
+ if first_ref + own_refs > refs || first_triangle + own_triangles > triangles {
+ return Err(bad("a cluster outside its buffer"));
+ }
+ for t in first_triangle..first_triangle + own_triangles {
+ let w = word(triangles_at + t * 4)?;
+ for corner in 0..3 {
+ let local = (w >> (corner * 7) & 127) as usize;
+ if local >= own_refs {
+ return Err(bad("a triangle outside its cluster"));
+ }
+ out.push(reference(first_ref + local)?);
+ }
+ }
+ }
+ if out.len() != triangles * 3 {
+ return Err(bad("clusters that do not add up to the triangle count"));
+ }
+ Ok(out)
+}
+
+/// A normal per vertex: the sum of the normals of its triangles.
+fn smooth_normals(positions: &[[f32; 3]], indices: &[u32]) -> Vec<[f32; 3]> {
+ let mut normals = vec![[0f32; 3]; positions.len()];
+ for t in indices.as_chunks::<3>().0 {
+ let [a, b, c] = t.map(|i| positions[i as usize]);
+ let (u, v) = ([b[0] - a[0], b[1] - a[1], b[2] - a[2]], [c[0] - a[0], c[1] - a[1], c[2] - a[2]]);
+ let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
+ for i in t {
+ for k in 0..3 {
+ normals[*i as usize][k] += n[k];
+ }
+ }
+ }
+ for n in &mut normals {
+ let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
+ *n = if len > 0.0 { [n[0] / len, n[1] / len, n[2] / len] } else { [0.0, 0.0, 1.0] };
+ }
+ normals
+}
+
+/// Reads the drawables of a resource: one, or those of a dictionary.
+/// [`ModelError::Graphics`] says the graphics part is too short.
+pub fn parse(system: &[u8], graphics: &[u8]) -> Result, ModelError> {
+ let reader = Reader { sys: system, gfx: graphics };
+ let pages = reader.s(8, 16).map_err(|_| ModelError::NotAModel)?;
+ if !(1..=32).contains(&system[pages + 8]) || !(1..=32).contains(&system[pages + 9]) {
+ return Err(ModelError::NotAModel);
+ }
+ match root(system).ok_or(ModelError::NotAModel)? {
+ Root::Drawable => Ok(vec![reader.drawable(0, "")?]),
+ Root::Fragment => {
+ let at = reader.s(24, 176)?;
+ if !is_drawable(system, at, true) {
+ return Err(ModelError::NotAModel);
+ }
+ Ok(vec![reader.drawable(at, &reader.name(168)?)?])
+ }
+ Root::Dictionary => {
+ let count = reader.u16(56)?;
+ let list = reader.s(48, count * 8)?;
+ let mut drawables = Vec::with_capacity(count);
+ let mut first_error = None;
+ for i in 0..count {
+ let at = reader.s(list + i * 8, 176)?;
+ if !is_drawable(system, at, true) {
+ return Err(ModelError::NotAModel);
+ }
+ match reader.drawable(at, &format!("drawable {i}")) {
+ Ok(d) => drawables.push(d),
+ // More graphics data may help; anything else only costs this one.
+ Err(e @ ModelError::Graphics(_)) => return Err(e),
+ Err(e) => first_error = first_error.or(Some(e)),
+ }
+ }
+ if drawables.is_empty() { Err(first_error.unwrap_or(ModelError::NotAModel)) } else { Ok(drawables) }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn put(d: &mut [u8], at: usize, bytes: &[u8]) {
+ d[at..at + bytes.len()].copy_from_slice(bytes);
+ }
+
+ fn pointer(d: &mut [u8], at: usize, base: u64, to: usize) {
+ put(d, at, &(base + to as u64).to_le_bytes());
+ }
+
+ /// A drawable with one model of one geometry: a square of two triangles
+ /// in one cluster, positions as floats, texture coordinates as floats.
+ fn resource() -> (Vec, Vec) {
+ let mut s = vec![0u8; 0x800];
+ let mut g = vec![0u8; 0x200];
+ let (pages, group, lod, models, model, geometries, geometry) =
+ (0x100, 0x120, 0x180, 0x1A0, 0x1B0, 0x200, 0x210);
+ let (vb, format, descriptor, ib, name, shaders, shader) = (0x300, 0x380, 0x500, 0x520, 0x580, 0x5A0, 0x5B0);
+ pointer(&mut s, 8, SYSTEM, pages);
+ s[pages + 8] = 1;
+ s[pages + 9] = 1;
+ pointer(&mut s, 16, SYSTEM, group);
+ put(&mut s, 44, &2.0f32.to_le_bytes());
+ for (i, v) in [0.0f32, 0.0, 0.0].iter().chain(&[0.0]).chain(&[1.0, 1.0, 0.0]).enumerate() {
+ put(&mut s, 48 + i * 4, &v.to_le_bytes());
+ }
+ pointer(&mut s, 80, SYSTEM, lod);
+ pointer(&mut s, 168, SYSTEM, name);
+ put(&mut s, name, b"square\0");
+ // One shader.
+ pointer(&mut s, group + 16, SYSTEM, shaders);
+ put(&mut s, group + 24, &[1, 0, 1, 0]);
+ pointer(&mut s, shaders, SYSTEM, shader);
+ put(&mut s, shader, &0xABCD_1234u32.to_le_bytes());
+ pointer(&mut s, lod, SYSTEM, models);
+ put(&mut s, lod + 8, &[1, 0, 1, 0]);
+ pointer(&mut s, models, SYSTEM, model);
+ pointer(&mut s, model + 8, SYSTEM, geometries);
+ put(&mut s, model + 16, &[1, 0, 1, 0]);
+ pointer(&mut s, geometries, SYSTEM, geometry);
+ pointer(&mut s, geometry + 8, SYSTEM, vb);
+ pointer(&mut s, geometry + 64, SYSTEM, descriptor);
+ // Vertex buffer: 4 vertices; positions at 0x80, texture coordinates at 0xB0.
+ put(&mut s, vb + 8, &0x100u32.to_le_bytes());
+ put(&mut s, vb + 12, &[1, 0]);
+ pointer(&mut s, vb + 24, GRAPHICS, 0);
+ pointer(&mut s, vb + 64, SYSTEM, format);
+ put(&mut s, format, &0x80u32.to_le_bytes());
+ s[format + 0xD0] = 12;
+ s[format + 0x104] = 6;
+ put(&mut s, format + TEXCOORD * 4, &0xB0u32.to_le_bytes());
+ s[format + 0xD0 + TEXCOORD] = 8;
+ s[format + 0x104 + TEXCOORD] = 16;
+ put(&mut s, format + 0x138, &(4u32 << 10 | 1).to_le_bytes());
+ let corners = [[0.0f32, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
+ for (i, c) in corners.iter().enumerate() {
+ put(&mut g, 0x80 + i * 12, &c[0].to_le_bytes());
+ put(&mut g, 0x84 + i * 12, &c[1].to_le_bytes());
+ put(&mut g, 0xB0 + i * 8, &c[0].to_le_bytes());
+ put(&mut g, 0xB4 + i * 8, &c[1].to_le_bytes());
+ }
+ // Index buffer at 0x100 of the graphics part: one cluster, two
+ // triangles, four references of 16 bits.
+ pointer(&mut s, descriptor, SYSTEM, ib);
+ put(&mut s, ib + 8, &16u32.to_le_bytes());
+ put(&mut s, ib + 12, &[4, 0]);
+ pointer(&mut s, ib + 24, GRAPHICS, 0x100);
+ let words = [0x8000_0001u32, 2, 4, (4 - 1) | (2 - 1) << 7, 0, 0, 0, 1 << 7 | 2 << 14, 2 << 7 | 3 << 14];
+ for (i, w) in words.iter().enumerate() {
+ put(&mut g, 0x100 + i * 4, &w.to_le_bytes());
+ }
+ for (i, r) in [0u16, 1, 2, 3].iter().enumerate() {
+ put(&mut g, 0x100 + 36 + i * 2, &r.to_le_bytes());
+ }
+ (s, g)
+ }
+
+ #[test]
+ fn reads_a_drawable() {
+ let (s, g) = resource();
+ assert_eq!(root(&s), Some(Root::Drawable));
+ let drawables = parse(&s, &g).unwrap();
+ let d = &drawables[0];
+ assert_eq!((d.name.as_str(), d.meshes.len(), d.shaders[0].name_hash), ("square", 1, 0xABCD_1234));
+ let mesh = &d.meshes[0];
+ assert_eq!(mesh.positions, [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]);
+ assert_eq!(mesh.uvs[2], [1.0, 1.0]);
+ assert_eq!(mesh.indices, [0, 1, 2, 0, 2, 3]);
+ assert!(mesh.normals.iter().all(|n| *n == [0.0, 0.0, 1.0]));
+ assert_eq!(d.bounds_max, [1.0, 1.0, 0.0]);
+ assert_eq!(name(&s).as_deref(), Some("square"));
+ assert_eq!(name(&s[..0x400]), None);
+ }
+
+ #[test]
+ fn says_when_graphics_data_is_missing() {
+ let (s, g) = resource();
+ assert_eq!(parse(&s, &g[..0x80]).unwrap_err(), ModelError::Graphics(0x100));
+ assert_eq!(parse(&s, &g[..0x120]).unwrap_err(), ModelError::Graphics(0x140));
+ let mut other = s.clone();
+ other[0] = 1;
+ assert_eq!(root(&other), None);
+ assert_eq!(parse(&vec![0u8; 0x400], &g).unwrap_err(), ModelError::NotAModel);
+ }
+
+ #[test]
+ fn fixed_point_positions() {
+ let (mut s, mut g) = resource();
+ let format = 0x380;
+ s[format + 0xD0] = 8;
+ s[format + 0x104] = 16;
+ // Bias (1, 2, 3), scale (0.5, 0.25, 2), axes as they are.
+ for (i, v) in [1.0f32, 2.0, 3.0].iter().enumerate() {
+ put(&mut g, 96 + i * 4, &v.to_le_bytes());
+ }
+ put(&mut g, 108, &2u32.to_le_bytes());
+ for (i, v) in [0.5f32, 0.25, 2.0].iter().enumerate() {
+ put(&mut g, 112 + i * 4, &v.to_le_bytes());
+ }
+ // x = 2, y = 0x000104 (two high bytes 0x0001, low byte 4), z = 3.
+ let q: u64 = 4 | 2 << 8 | 1 << 32 | 3 << 48;
+ for i in 0..4 {
+ put(&mut g, 0x80 + i * 8, &q.to_le_bytes());
+ }
+ let mesh = &parse(&s, &g).unwrap()[0].meshes[0];
+ assert_eq!(mesh.positions[0], [1.0 + 0.5 * 2.0, 2.0 + 0.25 * 260.0, 3.0 + 2.0 * 3.0]);
+ }
+}
diff --git a/crates/rage-formats/src/lib.rs b/crates/rage-formats/src/lib.rs
index 0c22a27..39189f6 100644
--- a/crates/rage-formats/src/lib.rs
+++ b/crates/rage-formats/src/lib.rs
@@ -8,9 +8,11 @@
#![forbid(unsafe_code)]
pub mod awc;
+pub mod bcpack;
pub mod clip;
pub mod dds;
pub mod drawable;
+pub mod drawable6;
pub mod expression;
pub mod geometry;
pub mod gltf;
@@ -25,11 +27,13 @@ pub mod model_textures;
pub mod names;
pub mod openformats;
pub mod paths;
+pub mod psin;
pub mod pso;
pub mod rbf;
pub mod sco;
pub mod shaders;
pub mod texture;
+pub mod ttpf;
pub mod wad;
pub mod wbn;
pub mod wdr;
diff --git a/crates/rage-formats/src/psin.rs b/crates/rage-formats/src/psin.rs
new file mode 100644
index 0000000..9f20b74
--- /dev/null
+++ b/crates/rage-formats/src/psin.rs
@@ -0,0 +1,695 @@
+//! GTA VI metadata containers (`PSIN` with an `LSCH` schema).
+//!
+//! The successor of the PSO files of GTA V and RDR2 ([`crate::pso`]): the
+//! same magic, another layout. Little-endian, except the offset of the first
+//! section and the section sizes.
+//!
+//! - `PSIN`, then the big-endian offset of the first section.
+//! - From 8 on, the block table: rows of 16 bytes (type, size, eight `AA`),
+//! ended by `70` bytes up to the next 16-byte boundary. A block's type is
+//! the name hash of a struct, a member type below `0x100`, or `0x100 + n`.
+//! The blocks follow in this order, each padded to 16 bytes, numbered
+//! from 1.
+//! - Sections up to the end of the file, each a tag and its big-endian size
+//! (tag and size included): `LSCH` (structs of 32 bytes, then all their
+//! members of 16), `LENM` (enums of 24 bytes, then all their values of 16),
+//! `LRSC` (`0DRP`, and at 16 the number of the root block), and others
+//! that are not needed to read the data.
+//!
+//! A pointer is 64 bits: the block number in the low 20 (0: none), the byte
+//! offset in that block above. Names are hashes (case-sensitive joaat); the
+//! names themselves are not in the files, so the XML shows `hash_…`.
+//!
+//! The layout was worked out by the Leonida project (`docs/psin.md`,
+//! `tools/psin_data.py`, GPL-3.0), which this reader follows.
+
+use std::collections::{HashMap, HashSet};
+
+use rage_core::bytes::LeRead;
+
+use crate::xml::{self, Writer};
+
+#[derive(Debug, thiserror::Error)]
+#[non_exhaustive]
+pub enum PsinError {
+ #[error("invalid PSIN file: {0}")]
+ Invalid(String),
+}
+
+fn invalid(msg: impl Into) -> PsinError {
+ PsinError::Invalid(msg.into())
+}
+
+/// The member that describes the elements of an array or map.
+const ELEMENT: u32 = 0x100;
+/// Pointers nest at most this deep.
+const MAX_DEPTH: usize = 64;
+
+#[derive(Debug, Clone, Copy)]
+struct Member {
+ name: u32,
+ offset: usize,
+ kind: u8,
+ /// For an array: which member of the struct describes its elements.
+ index: usize,
+ /// A struct or enum name, a length, or a map's key and value members.
+ reference: u32,
+}
+
+#[derive(Debug, Clone)]
+struct Struct {
+ size: usize,
+ align: usize,
+ members: Vec,
+}
+
+/// A parsed container.
+#[derive(Debug)]
+pub struct Psin<'a> {
+ data: &'a [u8],
+ structs: HashMap,
+ /// Per enum: value and the hash of its name.
+ enums: HashMap>,
+ /// Per block: type, offset in the file, size.
+ blocks: Vec<(u32, usize, usize)>,
+ root: usize,
+}
+
+/// Whether this is a container of the GTA VI kind: `PSIN`, and `LSCH` where
+/// the header says the sections start.
+pub fn is_psin(data: &[u8]) -> bool {
+ data.starts_with(b"PSIN") && be32(data, 4).and_then(|first| data.get(first..first + 4)) == Some(b"LSCH")
+}
+
+fn be32(d: &[u8], at: usize) -> Option {
+ Some(u32::from_be_bytes(d.get(at..at + 4)?.try_into().ok()?) as usize)
+}
+
+/// How many headers a schema section has: the one count whose headers and
+/// the elements they announce fill it exactly.
+fn header_count(d: &[u8], header: usize, element: usize, count_at: usize, wide: bool) -> Option {
+ if d.is_empty() {
+ return Some(0);
+ }
+ let mut elements = 0usize;
+ for k in 1..=d.len() / header {
+ let at = header * (k - 1) + count_at;
+ elements += if wide { d.u32_at(at)? as usize } else { usize::from(d.u16_at(at)?) };
+ if header * k + element * elements == d.len() {
+ return Some(k);
+ }
+ }
+ None
+}
+
+pub fn parse(data: &[u8]) -> Result, PsinError> {
+ if !is_psin(data) {
+ return Err(invalid("no LSCH section"));
+ }
+ let first = be32(data, 4).ok_or_else(|| invalid("truncated"))?;
+ let mut sections: HashMap<&[u8], &[u8]> = HashMap::new();
+ let mut at = first;
+ while let Some(tag) = data.get(at..at + 4) {
+ let size = be32(data, at + 4).ok_or_else(|| invalid("truncated section"))?;
+ let payload = (size >= 8).then(|| data.get(at + 8..at + size)).flatten();
+ sections.insert(tag, payload.ok_or_else(|| invalid("the file is cut off inside a section"))?);
+ at += size;
+ }
+
+ let lsch = sections[&b"LSCH"[..]];
+ let count = header_count(lsch, 32, 16, 30, false).ok_or_else(|| invalid("no struct count fills LSCH"))?;
+ let mut structs = HashMap::new();
+ let mut member = 32 * count;
+ for h in lsch[..32 * count].as_chunks::<32>().0 {
+ let members = (0..usize::from(u16::from_le_bytes([h[30], h[31]])))
+ .map(|i| {
+ let m = &lsch[member + 16 * i..member + 16 * i + 16];
+ Member {
+ name: m.u32_at(0).unwrap_or(0),
+ offset: m.u32_at(4).unwrap_or(0) as usize,
+ kind: m[8],
+ index: usize::from(m.u16_at(10).unwrap_or(0)),
+ reference: m.u32_at(12).unwrap_or(0),
+ }
+ })
+ .collect::>();
+ member += 16 * members.len();
+ let (name, size) = (h.u32_at(0).unwrap_or(0), h.u32_at(24).unwrap_or(0) as usize);
+ structs.insert(name, Struct { size, align: 1 << h[9].min(4), members });
+ }
+
+ let mut enums = HashMap::new();
+ if let Some(lenm) = sections.get(&b"LENM"[..]) {
+ let count = header_count(lenm, 24, 16, 16, true).ok_or_else(|| invalid("no enum count fills LENM"))?;
+ let mut value = 24 * count;
+ for h in lenm[..24 * count].as_chunks::<24>().0 {
+ let n = h.u32_at(16).unwrap_or(0) as usize;
+ let values = lenm[value..value + 16 * n]
+ .as_chunks::<16>()
+ .0
+ .iter()
+ .map(|v| (v.u64_at(0).unwrap_or(0) as i64, v.u32_at(8).unwrap_or(0)))
+ .collect();
+ value += 16 * n;
+ enums.insert(h.u32_at(0).unwrap_or(0), values);
+ }
+ }
+
+ // The block table, then the blocks.
+ let mut rows = Vec::new();
+ let mut at = 8;
+ loop {
+ let kind = data.u32_at(at).filter(|_| at + 8 <= first).ok_or_else(|| invalid("block table without end"))?;
+ if kind == 0x7070_7070 {
+ break;
+ }
+ let size = data.u32_at(at + 4).filter(|_| at + 16 <= first).ok_or_else(|| invalid("block table cut off"))?;
+ rows.push((kind, size as usize));
+ at += 16;
+ }
+ at = at.next_multiple_of(16);
+ let mut blocks = Vec::with_capacity(rows.len());
+ for (kind, size) in rows {
+ if at + size > first {
+ return Err(invalid("a block ends after the first section"));
+ }
+ blocks.push((kind, at, size));
+ at += size.next_multiple_of(16);
+ }
+
+ let lrsc = sections.get(&b"LRSC"[..]).filter(|s| s.starts_with(b"0DRP"));
+ let root = lrsc.and_then(|s| s.u32_at(0x10)).ok_or_else(|| invalid("no root (LRSC section)"))? as usize;
+ match blocks.get(root.wrapping_sub(1)) {
+ Some((kind, ..)) if structs.contains_key(kind) => {}
+ _ => return Err(invalid("the root is not a struct block")),
+ }
+ Ok(Psin { data, structs, enums, blocks, root })
+}
+
+fn hash_name(hash: u32) -> String {
+ format!("hash_{hash:08X}")
+}
+
+impl Psin<'_> {
+ /// The name (as a hash) of the root struct.
+ pub fn root_type(&self) -> String {
+ hash_name(self.blocks[self.root - 1].0)
+ }
+
+ pub fn to_xml(&self) -> (String, Vec) {
+ let mut w = Writer::new();
+ let (kind, at, _) = self.blocks[self.root - 1];
+ let name = hash_name(kind);
+ let mut open = HashSet::new();
+ self.members(&mut w, 0, &name, &name, kind, at, &mut open);
+ w.finish()
+ }
+
+ /// Size of a member's value in its struct, if its type is understood.
+ fn size_of(&self, m: &Member) -> Option {
+ Some(match m.kind {
+ 0x01 | 0x10 | 0x11 | 0x60 | 0x63 => 1,
+ 0x12 | 0x13 | 0x20 | 0x64 => 2,
+ 0x14 | 0x15 | 0x21 | 0x4A | 0x4B | 0x4D | 0x62 | 0x65 => 4,
+ 0x07 | 0x08 | 0x16 | 0x17 | 0x30 | 0x42 | 0x4F | 0x68 => 8,
+ 0x32 => 12,
+ 0x0C | 0x0D | 0x31 | 0x33 | 0x34 | 0x35 | 0x44 | 0x52 | 0x5C | 0x73 | 0x75 => 16,
+ 0x71 => 24,
+ 0x36 => 64,
+ 0x05 => self.structs.get(&m.reference)?.size,
+ 0x40 => m.reference as usize,
+ _ => return None,
+ })
+ }
+
+ fn align_of(&self, m: &Member) -> usize {
+ match m.kind {
+ 0x05 => self.structs.get(&m.reference).map_or(8, |s| s.align),
+ 0x0C | 0x0D | 0x31 | 0x33 | 0x34 | 0x35 | 0x36 => 16,
+ 0x32 => 4,
+ 0x40 => 1,
+ _ => self.size_of(m).filter(|n| matches!(n, 1 | 2 | 4)).unwrap_or(8),
+ }
+ }
+
+ /// Where a pointer leads: the block's type, the offset in the file, and
+ /// the end of the block. `None` for no target or one outside its block.
+ fn pointer(&self, at: usize) -> Option<(u32, usize, usize)> {
+ let v = self.data.u64_at(at)?;
+ let (number, offset) = ((v & 0xF_FFFF) as usize, usize::try_from(v >> 20).ok()?);
+ let (kind, base, size) = *self.blocks.get(number.checked_sub(1)?)?;
+ (offset < size).then_some((kind, base + offset, base + size))
+ }
+
+ /// The end of the block that holds `at`.
+ fn block_end(&self, at: usize) -> Option {
+ self.blocks.iter().find(|(_, base, size)| (*base..*base + *size).contains(&at)).map(|(_, b, s)| b + s)
+ }
+
+ fn string_at(&self, at: usize, end: usize) -> Option {
+ let bytes = self.data.get(at..end)?;
+ let len = bytes.iter().position(|b| *b == 0)?;
+ Some(String::from_utf8_lossy(&bytes[..len]).into_owned())
+ }
+
+ fn floats(&self, at: usize, n: usize) -> Option> {
+ (0..n).map(|i| Some(xml::float(f32::from_bits(self.data.u32_at(at + 4 * i)?)))).collect()
+ }
+
+ /// Writes a struct: its members between an opening and a closing tag.
+ #[allow(clippy::too_many_arguments)]
+ fn members(
+ &self,
+ w: &mut Writer,
+ level: usize,
+ tag: &str,
+ name: &str,
+ kind: u32,
+ at: usize,
+ open: &mut HashSet<(u32, usize)>,
+ ) {
+ let Some(s) = self.structs.get(&kind) else {
+ return w.error(level, format!("{name}: struct {} is not described in this file", hash_name(kind)));
+ };
+ if self.data.len() < at + s.size {
+ return w.error(level, format!("{name}: outside the file"));
+ }
+ // A struct that points back to itself, or far too deep.
+ if open.len() > MAX_DEPTH || !open.insert((kind, at)) {
+ return w.error(level, format!("{name}: refers back to itself"));
+ }
+ if s.members.iter().all(|m| m.name == ELEMENT) {
+ w.empty(level, tag);
+ } else {
+ w.open(level, tag);
+ for m in s.members.iter().filter(|m| m.name != ELEMENT) {
+ if w.full() {
+ break;
+ }
+ self.value(w, level + 1, &hash_name(m.name), m, &s.members, at + m.offset, open);
+ }
+ w.close(level, name);
+ }
+ open.remove(&(kind, at));
+ }
+
+ /// Writes one value: a member of a struct, or an element of an array.
+ #[allow(clippy::too_many_arguments)]
+ fn value(
+ &self,
+ w: &mut Writer,
+ level: usize,
+ name: &str,
+ m: &Member,
+ members: &[Member],
+ at: usize,
+ open: &mut HashSet<(u32, usize)>,
+ ) {
+ let d = self.data;
+ let missing = |w: &mut Writer| w.error(level, format!("{name}: outside the file"));
+ let number = |w: &mut Writer, v: Option| match v {
+ Some(v) => w.value(level, name, &v),
+ None => w.error(level, format!("{name}: outside the file")),
+ };
+ match m.kind {
+ 0x01 => number(w, d.get(at).map(|b| (*b != 0).to_string())),
+ 0x10 => number(w, d.get(at).map(|b| (*b as i8).to_string())),
+ 0x11 => number(w, d.get(at).map(u8::to_string)),
+ 0x12 => number(w, d.u16_at(at).map(|v| (v as i16).to_string())),
+ 0x13 => number(w, d.u16_at(at).map(|v| v.to_string())),
+ 0x14 => number(w, d.u32_at(at).map(|v| (v as i32).to_string())),
+ 0x15 => number(w, d.u32_at(at).map(|v| v.to_string())),
+ 0x16 | 0x08 => number(w, d.u64_at(at).map(|v| (v as i64).to_string())),
+ 0x17 => number(w, d.u64_at(at).map(|v| v.to_string())),
+ 0x20 => number(w, d.u16_at(at).map(|v| xml::float(half(v)))),
+ 0x21 => number(w, self.floats(at, 1).map(|f| f[0].clone())),
+ 0x4A | 0x4B | 0x4D => number(w, d.u32_at(at).map(|v| format!("0x{v:08X}"))),
+ 0x4F => number(w, d.u64_at(at).map(|v| format!("0x{v:016X}"))),
+ 0x30 | 0x32 | 0x31 | 0x33 | 0x34 | 0x35 | 0x0C | 0x0D => {
+ let n = match m.kind {
+ 0x30 => 2,
+ 0x32 => 3,
+ _ => 4,
+ };
+ match self.floats(at, n) {
+ Some(f) => {
+ let parts: Vec =
+ f.iter().zip(["x", "y", "z", "w"]).map(|(v, axis)| format!("{axis}=\"{v}\"")).collect();
+ w.empty(level, &format!("{name} {}", parts.join(" ")));
+ }
+ None => missing(w),
+ }
+ }
+ 0x36 => match self.floats(at, 16) {
+ Some(f) => w.raw_array(level, name, &f, 4),
+ None => missing(w),
+ },
+ 0x60 | 0x63 | 0x64 | 0x62 | 0x65 | 0x68 => self.enumeration(w, level, name, m, at),
+ 0x05 => self.members(w, level, name, name, m.reference, at, open),
+ 0x07 => match self.pointer(at) {
+ Some((kind, target, _)) => {
+ let tag = format!("{name} type=\"{}\"", hash_name(kind));
+ self.members(w, level, &tag, name, kind, target, open);
+ }
+ None => w.empty(level, name),
+ },
+ 0x44 if d.get(at + 15).is_some_and(|b| b & 0x80 != 0) => {
+ let len = usize::from(d[at + 15] & 0x7F).min(15);
+ w.string(level, name, &String::from_utf8_lossy(&d[at..at + len]));
+ }
+ 0x42 | 0x44 => match self.pointer(at) {
+ Some((_, target, end)) => match self.string_at(target, end) {
+ Some(text) => w.string(level, name, &text),
+ None => w.error(level, format!("{name}: a string without an end")),
+ },
+ None => w.empty(level, name),
+ },
+ 0x40 => match d.get(at..at + m.reference as usize) {
+ Some(bytes) => {
+ let len = bytes.iter().position(|b| *b == 0).unwrap_or(bytes.len());
+ w.string(level, name, &String::from_utf8_lossy(&bytes[..len]));
+ }
+ None => missing(w),
+ },
+ 0x50 | 0x53 | 0x54 | 0x5C | 0x52 => self.array(w, level, name, m, members, at, open),
+ 0x71 | 0x73 | 0x75 => self.map(w, level, name, m, members, at, open),
+ other => w.error(level, format!("{name}: type {other:#04x} is not understood")),
+ }
+ }
+
+ fn enumeration(&self, w: &mut Writer, level: usize, name: &str, m: &Member, at: usize) {
+ let d = self.data;
+ let raw = match m.kind {
+ 0x60 | 0x63 => d.get(at).map(|b| i64::from(*b)),
+ 0x64 => d.u16_at(at).map(i64::from),
+ 0x62 => d.u32_at(at).map(|v| i64::from(v as i32)),
+ 0x65 => d.u32_at(at).map(i64::from),
+ _ => d.u64_at(at).map(|v| v as i64),
+ };
+ let Some(raw) = raw else { return w.error(level, format!("{name}: outside the file")) };
+ let values = self.enums.get(&m.reference).map(Vec::as_slice).unwrap_or_default();
+ // A set of flags: the names of the bits that are set.
+ if m.kind == 0x65 {
+ let flags: Vec = (0..32)
+ .filter(|bit| raw >> bit & 1 != 0)
+ .map(|bit| match values.iter().find(|(v, _)| *v == bit) {
+ Some((_, hash)) => hash_name(*hash),
+ None => format!("bit{bit}"),
+ })
+ .collect();
+ return w.value(level, name, &flags.join(" "));
+ }
+ // A 32-bit enum lists its values as negative numbers or as numbers
+ // from 2^31 on.
+ let listed = values.iter().find(|(v, _)| *v == raw || (m.kind == 0x62 && *v == i64::from(raw as i32 as u32)));
+ match listed {
+ Some((_, hash)) => w.value(level, name, &hash_name(*hash)),
+ None => w.value(level, name, &raw.to_string()),
+ }
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn array(
+ &self,
+ w: &mut Writer,
+ level: usize,
+ name: &str,
+ m: &Member,
+ members: &[Member],
+ at: usize,
+ open: &mut HashSet<(u32, usize)>,
+ ) {
+ let d = self.data;
+ let element = members.get(m.index).filter(|e| e.name == ELEMENT);
+ // An empty array may name a struct that this file does not describe.
+ let empty = match m.kind {
+ 0x5C => d.u32_at(at) == Some(0),
+ 0x52 => d.u16_at(at + 8) == Some(0),
+ _ => false,
+ };
+ if empty {
+ return w.empty(level, name);
+ }
+ let Some((element, size)) = element.and_then(|e| Some((e, self.size_of(e).filter(|s| *s > 0)?))) else {
+ let kind = members.get(m.index).map_or(0, |e| e.kind);
+ return w.error(level, format!("{name}: an array of type {kind:#04x}, which is not understood"));
+ };
+ let bad = |w: &mut Writer| w.error(level, format!("{name}: array outside its block"));
+ // Where the elements are, how many, and where their block ends.
+ let (start, count, end) = match m.kind {
+ 0x50 | 0x53 => (at, (m.reference & 0xFFFF) as usize, self.block_end(at)),
+ 0x54 => {
+ let (Some(capacity), Some(count)) = (d.u32_at(at), d.u32_at(at + 4)) else { return bad(w) };
+ (at + 8, count.min(capacity) as usize, self.block_end(at))
+ }
+ _ => {
+ let (count, pointer) = if m.kind == 0x5C {
+ (d.u32_at(at).map(|c| c as usize), at + 8)
+ } else {
+ (d.u16_at(at + 8).map(usize::from), at)
+ };
+ let Some(count) = count else { return bad(w) };
+ if count == 0 {
+ return w.empty(level, name);
+ }
+ match self.pointer(pointer) {
+ Some((_, target, end)) => (target, count, Some(end)),
+ None => return bad(w),
+ }
+ }
+ };
+ if end.is_none_or(|end| start + size * count > end) {
+ return bad(w);
+ }
+ if count == 0 {
+ return w.empty(level, name);
+ }
+ w.open(level, name);
+ for i in 0..count {
+ if w.full() {
+ break;
+ }
+ self.value(w, level + 1, "Item", element, members, start + i * size, open);
+ }
+ w.close(level, name);
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn map(
+ &self,
+ w: &mut Writer,
+ level: usize,
+ name: &str,
+ m: &Member,
+ members: &[Member],
+ at: usize,
+ open: &mut HashSet<(u32, usize)>,
+ ) {
+ let d = self.data;
+ let part = |i: u32| members.get(i as usize).filter(|e| e.name == ELEMENT);
+ let (Some(key), Some(value)) = (part(m.reference & 0xFFFF), part(m.reference >> 16)) else {
+ return w.error(level, format!("{name}: a map without a description of its entries"));
+ };
+ let (Some(key_size), Some(value_size)) = (self.size_of(key), self.size_of(value)) else {
+ return w.error(level, format!("{name}: a map of types that are not understood"));
+ };
+ // The value starts where its alignment allows; the pair is rounded
+ // up to the larger alignment.
+ let value_at = key_size.next_multiple_of(self.align_of(value));
+ let pair = (value_at + value_size).next_multiple_of(self.align_of(key).max(self.align_of(value)));
+ let bad = |w: &mut Writer| w.error(level, format!("{name}: map outside its block"));
+ let mut pairs = Vec::new();
+ match m.kind {
+ // Pairs sorted by key.
+ 0x71 => {
+ let Some(count) = d.u16_at(at + 16).map(usize::from) else { return bad(w) };
+ if count > 0 {
+ let Some((_, start, end)) = self.pointer(at + 8) else { return bad(w) };
+ if start + count * pair > end.next_multiple_of(16) {
+ return bad(w);
+ }
+ pairs.extend((0..count).map(|i| start + i * pair));
+ }
+ }
+ // Groups of 16 control bytes and 16 pairs; bit 7 marks a free one.
+ 0x75 => {
+ let (Some(groups), Some(count)) = (d.u32_at(at), d.u32_at(at + 4)) else { return bad(w) };
+ if count > 0 {
+ let group = 16 + 16 * pair;
+ let Some((_, start, end)) = self.pointer(at + 8) else { return bad(w) };
+ if start + groups as usize * group > end.next_multiple_of(16) {
+ return bad(w);
+ }
+ for g in 0..groups as usize {
+ let base = start + g * group;
+ pairs.extend((0..16).filter(|i| d[base + i] & 0x80 == 0).map(|i| base + 16 + i * pair));
+ }
+ }
+ }
+ // Slots; a key of zeros marks a free one.
+ _ => {
+ let (Some(capacity), Some(count)) = (d.u32_at(at), d.u32_at(at + 4)) else { return bad(w) };
+ if count > 0 {
+ let Some((_, start, end)) = self.pointer(at + 8) else { return bad(w) };
+ if start + capacity as usize * pair > end.next_multiple_of(16) {
+ return bad(w);
+ }
+ let used = |slot: &usize| d[*slot..*slot + key_size].iter().any(|b| *b != 0);
+ pairs.extend((0..capacity as usize).map(|i| start + i * pair).filter(used));
+ }
+ }
+ }
+ if pairs.iter().any(|p| p + pair > d.len()) {
+ return bad(w);
+ }
+ if pairs.is_empty() {
+ return w.empty(level, name);
+ }
+ w.open(level, name);
+ for at in pairs {
+ if w.full() {
+ break;
+ }
+ w.open(level + 1, "Item");
+ self.value(w, level + 2, "key", key, members, at, open);
+ self.value(w, level + 2, "value", value, members, at + value_at, open);
+ w.close(level + 1, "Item");
+ }
+ w.close(level, name);
+ }
+}
+
+/// A 16-bit float.
+fn half(v: u16) -> f32 {
+ let (sign, exponent, fraction) = (v >> 15, i32::from(v >> 10 & 0x1F), f32::from(v & 0x3FF));
+ let magnitude = match exponent {
+ 0 => fraction / 1024.0 * 2f32.powi(-14),
+ 31 if fraction == 0.0 => f32::INFINITY,
+ 31 => f32::NAN,
+ e => (1.0 + fraction / 1024.0) * 2f32.powi(e - 15),
+ };
+ if sign == 1 { -magnitude } else { magnitude }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn section(tag: &[u8; 4], payload: &[u8]) -> Vec {
+ let mut out = tag.to_vec();
+ out.extend_from_slice(&(payload.len() as u32 + 8).to_be_bytes());
+ out.extend_from_slice(payload);
+ out
+ }
+
+ fn member(name: u32, offset: u32, kind: u8, index: u16, reference: u32) -> Vec {
+ let mut m = Vec::new();
+ m.extend_from_slice(&name.to_le_bytes());
+ m.extend_from_slice(&offset.to_le_bytes());
+ m.extend_from_slice(&[kind, 0]);
+ m.extend_from_slice(&index.to_le_bytes());
+ m.extend_from_slice(&reference.to_le_bytes());
+ m
+ }
+
+ /// A root struct with a number, a float, an enum, a string pointer and
+ /// an array of numbers in a second block.
+ fn container() -> Vec {
+ let pointer = |block: u64, offset: u64| (block | offset << 20).to_le_bytes();
+ let mut root = Vec::new();
+ root.extend_from_slice(&(-5i32).to_le_bytes()); // 0: s32
+ root.extend_from_slice(&1.5f32.to_le_bytes()); // 4: f32
+ root.extend_from_slice(&2u32.to_le_bytes()); // 8: enum
+ root.extend_from_slice(&[0; 4]);
+ root.extend_from_slice(&pointer(2, 0)); // 16: string
+ root.extend_from_slice(&3u32.to_le_bytes()); // 24: array {count, capacity, pointer}
+ root.extend_from_slice(&4u32.to_le_bytes());
+ root.extend_from_slice(&pointer(3, 2));
+ let blocks: [(u32, Vec); 3] =
+ [(0xAA01, root), (0x10, b"hello\0".to_vec()), (0x13, vec![9, 9, 1, 0, 2, 0, 3, 0])];
+
+ let mut out = b"PSIN\0\0\0\0".to_vec();
+ for (kind, data) in &blocks {
+ out.extend_from_slice(&kind.to_le_bytes());
+ out.extend_from_slice(&(data.len() as u32).to_le_bytes());
+ out.extend_from_slice(&[0xAA; 8]);
+ }
+ out.extend_from_slice(&[0x70; 8]);
+ for (_, data) in &blocks {
+ out.extend_from_slice(data);
+ out.resize(out.len().next_multiple_of(16), 0);
+ }
+ let first = out.len() as u32;
+ out[4..8].copy_from_slice(&first.to_be_bytes());
+
+ let mut lsch = Vec::new();
+ lsch.extend_from_slice(&0xAA01u32.to_le_bytes());
+ lsch.extend_from_slice(&[0; 5]);
+ lsch.push(3); // aligned to 8
+ lsch.extend_from_slice(&[0; 6]);
+ lsch.extend_from_slice(&[0xAA; 8]);
+ lsch.extend_from_slice(&40u32.to_le_bytes());
+ lsch.extend_from_slice(&[0, 0, 6, 0]);
+ lsch.extend(member(0x11, 0, 0x14, 0, 0));
+ lsch.extend(member(0x22, 4, 0x21, 0, 0));
+ lsch.extend(member(0x33, 8, 0x62, 0, 0xE001));
+ lsch.extend(member(0x44, 16, 0x42, 0, 0));
+ lsch.extend(member(0x55, 24, 0x5C, 5, 0));
+ lsch.extend(member(ELEMENT, 0, 0x13, 0, 0));
+ let mut lenm = Vec::new();
+ lenm.extend_from_slice(&0xE001u32.to_le_bytes());
+ lenm.extend_from_slice(&[0; 4]);
+ lenm.extend_from_slice(&[0xEE; 8]);
+ lenm.extend_from_slice(&1u32.to_le_bytes());
+ lenm.extend_from_slice(&[0; 4]);
+ lenm.extend_from_slice(&2i64.to_le_bytes());
+ lenm.extend_from_slice(&0xBEEFu64.to_le_bytes());
+ let mut lrsc = b"0DRP".to_vec();
+ lrsc.extend_from_slice(&122u32.to_le_bytes());
+ lrsc.extend_from_slice(&[0; 8]);
+ lrsc.extend_from_slice(&1u32.to_le_bytes());
+ out.extend(section(b"LSCH", &lsch));
+ out.extend(section(b"LENM", &lenm));
+ out.extend(section(b"LGID", &[]));
+ out.extend(section(b"LRSC", &lrsc));
+ out
+ }
+
+ #[test]
+ fn reads_a_container_as_xml() {
+ let data = container();
+ assert!(is_psin(&data));
+ let psin = parse(&data).unwrap();
+ assert_eq!(psin.root_type(), "hash_0000AA01");
+ let (text, errors) = psin.to_xml();
+ assert!(errors.is_empty(), "{errors:?}");
+ for line in [
+ "",
+ " ",
+ " ",
+ " ",
+ " hello ",
+ " ",
+ " ",
+ " ",
+ ] {
+ assert!(text.contains(line), "{line} is missing in\n{text}");
+ }
+ }
+
+ #[test]
+ fn rejects_what_is_cut_off() {
+ let data = container();
+ assert!(parse(&data[..data.len() - 4]).is_err());
+ assert!(!is_psin(b"PSIN\0\0\0\x10PMAP"));
+ let mut no_root = data.clone();
+ let at = no_root.len() - 4;
+ no_root[at] = 9;
+ assert!(parse(&no_root).is_err());
+ }
+
+ #[test]
+ fn half_floats() {
+ assert_eq!((half(0x3C00), half(0xC000), half(0x0000), half(0x3800)), (1.0, -2.0, 0.0, 0.5));
+ }
+}
diff --git a/crates/rage-formats/src/rbf.rs b/crates/rage-formats/src/rbf.rs
index d987f19..2ffd6ef 100644
--- a/crates/rage-formats/src/rbf.rs
+++ b/crates/rage-formats/src/rbf.rs
@@ -8,6 +8,9 @@
//! `0x60` string (u16 length + ASCII). `FD FF` + i32 length + bytes is element
//! content; `FF FF` closes the current element. The first `n` values after an
//! element (its attribute count) are its attributes.
+//!
+//! GTA VI: most files have `FB FF 01 00` after the magic, and with it
+//! integers and floats of 8 bytes instead of 4.
use crate::xml::{self, Writer};
@@ -24,6 +27,10 @@ pub enum RbfError {
pub enum Value {
Element(Element),
Uint(String, u32),
+ /// GTA VI: an 8-byte integer.
+ Uint64(String, u64),
+ /// GTA VI: an 8-byte float.
+ Float64(String, f64),
Bool(String, bool),
Float(String, f32),
Float3(String, [f32; 3]),
@@ -84,6 +91,12 @@ impl Reader<'_> {
fn f32(&mut self) -> Result {
Ok(f32::from_bits(self.u32()?))
}
+ fn u64(&mut self) -> Result {
+ Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap_or_default()))
+ }
+ fn f64(&mut self) -> Result {
+ Ok(f64::from_bits(self.u64()?))
+ }
fn string(&mut self) -> Result {
let n = self.u16()? as usize;
Ok(String::from_utf8_lossy(self.take(n)?).into_owned())
@@ -95,7 +108,9 @@ pub fn parse(data: &[u8]) -> Result {
if !is_rbf(data) {
return Err(RbfError::Invalid("missing RBF0 header".into()));
}
- let mut r = Reader { d: data, pos: 4 };
+ // GTA VI: with these four bytes, numbers take 8 bytes.
+ let wide = data.get(4..8) == Some(&[0xFB, 0xFF, 0x01, 0x00]);
+ let mut r = Reader { d: data, pos: if wide { 8 } else { 4 } };
let mut names: Vec = Vec::new();
let mut stack: Vec = Vec::new();
while r.pos < data.len() {
@@ -139,6 +154,9 @@ pub fn parse(data: &[u8]) -> Result {
stack.push(Element { name, pending, ..Default::default() });
continue;
}
+ 0x10 if wide => Value::Uint64(name, r.u64()?),
+ 0x40 if wide => Value::Float64(name, r.f64()?),
+ 0x50 if wide => Value::Float3(name, [r.f64()? as f32, r.f64()? as f32, r.f64()? as f32]),
0x10 => Value::Uint(name, r.u32()?),
0x20 => Value::Bool(name, true),
0x30 => Value::Bool(name, false),
@@ -163,6 +181,16 @@ pub fn to_xml(data: &[u8]) -> Result<(String, Vec, String), RbfError> {
Ok((text, errors, root.name))
}
+/// An 8-byte float as text: like a 4-byte one when it is one exactly.
+fn float64(v: f64) -> String {
+ if f64::from(v as f32) == v { xml::float(v as f32) } else { v.to_string() }
+}
+
+/// An 8-byte integer as text: small ones as numbers, the rest (hashes) in hex.
+fn uint64(v: u64) -> String {
+ if v < 1 << 31 { v.to_string() } else { format!("0x{v:016X}") }
+}
+
fn bool_text(b: bool) -> &'static str {
if b { "True" } else { "False" }
}
@@ -174,6 +202,8 @@ fn write(w: &mut Writer, level: usize, e: &Element) {
Value::Str(n, v) => (n, xml::escape(v)),
Value::Float(n, v) => (n, xml::float(*v)),
Value::Uint(n, v) => (n, v.to_string()),
+ Value::Uint64(n, v) => (n, uint64(*v)),
+ Value::Float64(n, v) => (n, float64(*v)),
Value::Bool(n, v) => (n, bool_text(*v).to_owned()),
_ => continue,
};
@@ -203,10 +233,14 @@ fn write(w: &mut Writer, level: usize, e: &Element) {
}
// Matrices and float lists: little-endian floats, a row per line
// (matrix34: the three axes and the position).
- Some(kind @ ("matrix34" | "matrix44" | "float_array" | "vector3_array" | "vector4_array")) => {
+ Some(
+ kind @ ("matrix34" | "matrix44" | "float_array" | "vector2_array" | "vec2v_array" | "vector3_array"
+ | "vector4_array"),
+ ) => {
let per_row = match kind {
"matrix34" | "vector3_array" => 3,
"float_array" => 1,
+ "vector2_array" | "vec2v_array" => 2,
_ => 4,
};
let floats: Vec =
@@ -222,6 +256,8 @@ fn write(w: &mut Writer, level: usize, e: &Element) {
},
Value::Element(c) => write(w, inner, c),
Value::Uint(n, v) => w.value(inner, n, &format!("0x{v:08X}")),
+ Value::Uint64(n, v) => w.value(inner, n, &uint64(*v)),
+ Value::Float64(n, v) => w.value(inner, n, &float64(*v)),
Value::Bool(n, v) => w.value(inner, n, bool_text(*v)),
Value::Float(n, v) => w.value(inner, n, &xml::float(*v)),
Value::Float3(n, v) => w.empty(
@@ -254,4 +290,25 @@ mod tests {
assert!(errors.is_empty());
assert!(text.contains("\n \n "), "{text}");
}
+
+ /// GTA VI: 8-byte numbers after the four bytes that announce them.
+ #[test]
+ fn parses_wide_numbers() {
+ let mut d = b"RBF0\xFB\xFF\x01\x00".to_vec();
+ d.extend([0, 0, 1, 0, b'r', 0, 0, 0, 0, 1, 0]);
+ d.extend([1, 0x10, 1, 0, b'n']);
+ d.extend(7u64.to_le_bytes());
+ d.extend([2, 0x40, 1, 0, b'v']);
+ d.extend(0.25f64.to_le_bytes());
+ // The same name with another type, as GTA VI's files have it.
+ d.extend([2, 0x10]);
+ d.extend(u64::MAX.to_le_bytes());
+ d.extend([0xFF, 0xFF]);
+ let (text, errors, _) = to_xml(&d).unwrap();
+ assert!(errors.is_empty());
+ assert!(
+ text.contains("\n \n \n "),
+ "{text}"
+ );
+ }
}
diff --git a/crates/rage-formats/src/ttpf.rs b/crates/rage-formats/src/ttpf.rs
new file mode 100644
index 0000000..72edee8
--- /dev/null
+++ b/crates/rage-formats/src/ttpf.rs
@@ -0,0 +1,692 @@
+//! GTA VI texture pools (`.ttpf`, magic `RDS5`).
+//!
+//! GTA VI keeps its textures outside the archives, in pools below
+//! `data/ttdb`. A pool is a virtual address space cut into chunks, with a
+//! list of textures that says where in that space each one lives.
+//!
+//! Layout (little-endian):
+//! - `RDS5`, entry count, virtual size (56 bits; the top byte is 22).
+//! - From 24 on, a 64-bit word per chunk and a last one that marks the end
+//! of the file: the offset in the file in units of 256 bytes (26 bits),
+//! the codec (4 bits: 0 stored, 8 zlib, 1 to 7 BCPack), the virtual
+//! address in pages of 4 KiB (22 bits), and the bytes of padding at the
+//! end of the chunk's file range (12 bits).
+//! - On the next multiple of 256: `ETPF`, version 634, texture count, size
+//! of the records that follow, 16 bytes per texture: width and height
+//! (14 bits each, minus one), mip levels, format (DXGI), depth, shape,
+//! tiling mode, and the address of its allocation in pages. Then a 64-bit
+//! key per texture: models name their textures by these.
+//!
+//! A texture's allocation holds its mip levels the way the console's GPU
+//! stores them (AMD's "Gfx10" layout): the large levels one after the other,
+//! smallest first, each cut into tiles of 4 or 64 KiB whose elements are in
+//! a bit-interleaved order; the small levels share the one tile in front.
+//! [`Pool::texture`] undoes that and returns ordinary rows of pixels or
+//! blocks.
+//!
+//! Chunks packed with BCPack go through [`crate::bcpack`]. Not read: BCPack
+//! for BC6H and BC7 (a texture is then read from its largest level that is
+//! packed otherwise), and volumes.
+//!
+//! The format was worked out by the Leonida project (`docs/textures.md`,
+//! GPL-3.0); this reader follows its `tools/ttpf_mips.py` and
+//! `tools/tex_headers.py`.
+
+use std::fs::File;
+use std::io::{Read, Seek, SeekFrom};
+use std::path::Path;
+use std::sync::Mutex;
+
+use rage_core::bytes::LeRead;
+
+use crate::texture::{Dimension, Format, Texture};
+
+#[derive(Debug, thiserror::Error)]
+#[non_exhaustive]
+pub enum TtpfError {
+ #[error("not a texture pool: {0}")]
+ Invalid(String),
+ #[error("{0}")]
+ Unsupported(String),
+ #[error(transparent)]
+ Io(#[from] std::io::Error),
+}
+
+fn invalid(msg: impl Into) -> TtpfError {
+ TtpfError::Invalid(msg.into())
+}
+
+fn unsupported(msg: impl Into) -> TtpfError {
+ TtpfError::Unsupported(msg.into())
+}
+
+const ETPF_VERSION: u32 = 634;
+/// No chunk unpacks to more than this.
+const MAX_CHUNK: usize = 256 << 20;
+const MAX_TEXTURES: usize = 250_000;
+
+/// One chunk of the pool's virtual space.
+#[derive(Debug, Clone, Copy)]
+struct Chunk {
+ /// Virtual address and size.
+ address: u64,
+ size: usize,
+ /// Where it is in the file, and how many bytes.
+ offset: u64,
+ packed: usize,
+ codec: u8,
+}
+
+/// What the pool says about a texture.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Descriptor {
+ pub width: u32,
+ pub height: u32,
+ pub mips: u32,
+ /// DXGI format code.
+ pub format: u32,
+ /// Slices of an array or volume; 6 for a cube map.
+ pub depth: u32,
+ /// 1: 2D (an array if `depth` is more than 1), 2: cube map, 3: volume.
+ pub dimension: u32,
+ /// Tiling mode: a flag and, from bit 1, the GPU's tile mode.
+ pub mode: u32,
+ /// For a cube map: how many smaller copies of it come before the full one.
+ pub earlier_copies: u32,
+ /// Virtual address of its allocation; `None` when it has none.
+ pub base: Option,
+}
+
+impl Descriptor {
+ fn parse(r: &[u8]) -> Descriptor {
+ let (a, b, c) = (r.u32_at(0).unwrap_or(0), r.u32_at(4).unwrap_or(0), r.u32_at(8).unwrap_or(0));
+ let page = c & 0x1F_FFFF;
+ Descriptor {
+ width: (a & 0x3FFF) + 1,
+ height: (a >> 14 & 0x3FFF) + 1,
+ mips: (a >> 28) + (b & 7),
+ format: b >> 3 & 0x7F,
+ depth: (b >> 10 & 0x7FF) + 1,
+ dimension: b >> 21 & 3,
+ mode: b >> 23,
+ earlier_copies: b & 7,
+ base: (page != 0 && page != 0x1F_FFFF).then(|| u64::from(page) * 4096),
+ }
+ }
+
+ /// Whether it is a plain 2D texture (the kind [`Pool::texture`] reads).
+ pub fn is_2d(&self) -> bool {
+ self.dimension == 1 && self.depth == 1
+ }
+
+ /// "2D", "2D array", "cube map" or "volume".
+ pub fn shape(&self) -> &'static str {
+ match (self.dimension, self.depth) {
+ (1, 1) => "2D",
+ (1, _) => "2D array",
+ (2, _) => "cube map",
+ _ => "volume",
+ }
+ }
+}
+
+/// Bytes of one pixel, or of one 4×4 block of a compressed format.
+fn element_bytes(format: u32) -> Option {
+ Some(match format {
+ 2..=4 => 16,
+ 6..=8 => 12,
+ 10..=14 | 16..=18 => 8,
+ 24..=26 | 28..=32 | 34..=38 | 41..=43 | 87 | 88 | 91 | 93 => 4,
+ 49..=52 | 54 | 56..=59 => 2,
+ 61..=65 => 1,
+ 71 | 72 | 80 | 81 => 8,
+ 74 | 75 | 77 | 78 | 83 | 84 | 95 | 96 | 98 | 99 => 16,
+ _ => return None,
+ })
+}
+
+fn is_block_format(format: u32) -> bool {
+ matches!(format, 70..=84 | 94..=99)
+}
+
+/// Where each address bit inside a tile comes from, lowest bit first: `n`
+/// is bit `n - 1` of x, `-n` bit `n - 1` of y, 0 a bit inside the element.
+/// By the element size (1, 2, 4, 8, 16 bytes). These are the GPU's public
+/// tile patterns (Mesa's addrlib: `GFX10_SW_4K_S_RBPLUS` and
+/// `GFX10_SW_64K_D_RBPLUS`).
+const PATTERNS_4K: [[i8; 12]; 5] = [
+ [1, 2, 3, 4, -1, -2, -3, -4, -5, 5, -6, 6],
+ [0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6],
+ [0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5],
+ [0, 0, 0, 1, -1, -2, 2, 3, -3, 4, -4, 5],
+ [0, 0, 0, 0, -1, -2, 1, 2, -3, 3, -4, 4],
+];
+const PATTERNS_64K: [[i8; 16]; 5] = [
+ [1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8],
+ [0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8],
+ [0, 0, 1, 2, -1, -2, 3, -3, -4, 4, -5, 5, -6, 6, -7, 7],
+ [0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7],
+ [0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6],
+];
+/// Per element size: the step, in elements, of the grid on which the small
+/// levels sit inside their shared tile.
+const TAIL_GRID: [(usize, usize); 5] = [(16, 16), (16, 8), (8, 8), (8, 4), (4, 4)];
+
+/// One mip level in a texture's allocation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct Level {
+ /// Size in elements (pixels, or blocks of a compressed format).
+ across: usize,
+ down: usize,
+ /// Elements per row of the stored region, which is whole tiles.
+ stored_across: usize,
+ pixels: (u32, u32),
+ /// Offset in the allocation and size of the stored region.
+ offset: usize,
+ region: usize,
+ /// Position inside the shared tile, for the small levels.
+ tile_x: usize,
+ tile_y: usize,
+}
+
+/// How a 2D texture's allocation is laid out.
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct Layout {
+ size: usize,
+ tile: usize,
+ /// Elements per tile across and down.
+ tile_across: usize,
+ tile_down: usize,
+ element: usize,
+ /// The first level in the shared tile (the number of levels if none is).
+ tail: usize,
+ levels: Vec,
+}
+
+impl Layout {
+ fn new(width: u32, height: u32, mips: u32, element: usize, block: usize, tile: usize) -> Option {
+ let log = element.trailing_zeros() as usize;
+ let (width, height, mips) = (width as usize, height as usize, mips as usize);
+ if !element.is_power_of_two()
+ || log > 4
+ || mips == 0
+ || mips > (usize::BITS - width.max(height).leading_zeros()) as usize
+ {
+ return None;
+ }
+ let (half_bits, max_tail) = if tile == 4096 { (6, 8) } else { (8, 12) };
+ let (tile_across, tile_down) = (1 << (half_bits - log / 2), 1 << (half_bits - log.div_ceil(2)));
+ let (grid_x, grid_y) = TAIL_GRID[log];
+ let (across, down) = (width.div_ceil(block), height.div_ceil(block));
+ let size_of = |i: usize| (across.div_ceil(1 << i).max(1), down.div_ceil(1 << i).max(1));
+ let pixels = |i: usize| ((width >> i).max(1) as u32, (height >> i).max(1) as u32);
+
+ // The levels that get tiles of their own, largest first.
+ let mut levels = Vec::with_capacity(mips);
+ let mut tail = mips;
+ for i in 0..mips {
+ let (w, h) = size_of(i);
+ if mips > 1 && w <= tile_across / 2 && h <= tile_down && mips - i <= max_tail {
+ tail = i;
+ break;
+ }
+ let (stored_across, stored_down) = (w.next_multiple_of(tile_across), h.next_multiple_of(tile_down));
+ levels.push(Level {
+ across: w,
+ down: h,
+ stored_across,
+ pixels: pixels(i),
+ offset: 0,
+ region: stored_across * stored_down * element,
+ tile_x: 0,
+ tile_y: 0,
+ });
+ }
+ // They are stored smallest first, after the shared tile if there is one.
+ let mut offset = if tail < mips { tile } else { 0 };
+ for level in levels.iter_mut().rev() {
+ level.offset = offset;
+ offset += level.region;
+ }
+ // The small levels, each at a fixed place of the shared tile.
+ for i in tail..mips {
+ let entry = max_tail - 1 - (i - tail);
+ let place = if entry > 6 { 16usize << entry } else { entry << 8 };
+ let (mut x, mut y) = (0, 0);
+ for bit in 0..6 {
+ x |= (place >> (9 + 2 * bit) & 1) << bit;
+ y |= (place >> (8 + 2 * bit) & 1) << bit;
+ }
+ let (w, h) = size_of(i);
+ levels.push(Level {
+ across: w,
+ down: h,
+ stored_across: tile_across,
+ pixels: pixels(i),
+ offset: 0,
+ region: tile,
+ tile_x: x * grid_x,
+ tile_y: y * grid_y,
+ });
+ }
+ Some(Layout { size: offset, tile, tile_across, tile_down, element, tail, levels })
+ }
+
+ /// Puts a level's elements, as stored in tiles, into rows.
+ fn untile(&self, level: &Level, stored: &[u8]) -> Option> {
+ let log = self.element.trailing_zeros() as usize;
+ let pattern: &[i8] = if self.tile == 4096 { &PATTERNS_4K[log] } else { &PATTERNS_64K[log] };
+ // The offset inside a tile is the sum of a part from x and one from y.
+ let part = |v: usize, from_x: bool| -> usize {
+ pattern.iter().enumerate().fold(0, |acc, (bit, &s)| match (s, from_x) {
+ (s, true) if s > 0 => acc | (v >> (s - 1) & 1) << bit,
+ (s, false) if s < 0 => acc | (v >> (-s - 1) & 1) << bit,
+ _ => acc,
+ })
+ };
+ let x_parts: Vec = (0..level.across).map(|x| part(x + level.tile_x, true)).collect();
+ let tiles_across = level.stored_across / self.tile_across;
+ let mut out = Vec::with_capacity(level.across * level.down * self.element);
+ for y in 0..level.down {
+ let row = (y / self.tile_down) * tiles_across;
+ let y_part = part(y + level.tile_y, false);
+ for (x, x_part) in x_parts.iter().enumerate() {
+ let at = ((row + x / self.tile_across) * self.tile) | x_part | y_part;
+ out.extend_from_slice(stored.get(at..at + self.element)?);
+ }
+ }
+ Some(out)
+ }
+}
+
+/// An opened texture pool.
+#[derive(Debug)]
+pub struct Pool {
+ file: Mutex,
+ virtual_size: u64,
+ chunks: Vec,
+ descriptors: Vec,
+ keys: Vec,
+}
+
+impl Pool {
+ /// Whether these bytes start a texture pool.
+ pub fn is_pool(start: &[u8]) -> bool {
+ start.starts_with(b"RDS5")
+ }
+
+ /// Opens a pool: reads its tables, not its textures.
+ pub fn open(path: &Path) -> Result {
+ let mut file = File::open(path)?;
+ let length = file.metadata()?.len();
+ let mut head = [0u8; 24];
+ file.read_exact(&mut head).map_err(|_| invalid("too short"))?;
+ if !Self::is_pool(&head) {
+ return Err(invalid("no RDS5 magic"));
+ }
+ let count = head.u32_at(4).unwrap_or(0) as usize;
+ let size_word = head.u64_at(8).unwrap_or(0);
+ let virtual_size = size_word & 0x00FF_FFFF_FFFF_FFFF;
+ if !(3..=1_000_002).contains(&count) || size_word >> 56 != 22 {
+ return Err(invalid("unknown index layout"));
+ }
+ let mut table = vec![0u8; (count - 1) * 8];
+ file.read_exact(&mut table).map_err(|_| invalid("the chunk table is cut off"))?;
+ let words: Vec = table.as_chunks::<8>().0.iter().map(|w| u64::from_le_bytes(*w)).collect();
+ let place = |w: u64| ((w & 0x3FF_FFFF) * 256, (w >> 30 & 0x3F_FFFF) * 4096);
+ if words.last().map(|w| place(*w)) != Some((length, virtual_size)) {
+ return Err(invalid("the chunk table does not end where the file does"));
+ }
+ let mut chunks = Vec::with_capacity(words.len() - 1);
+ for pair in words.windows(2) {
+ let ((offset, address), (end, address_end)) = (place(pair[0]), place(pair[1]));
+ let padding = pair[0] >> 52;
+ let packed = end.checked_sub(offset + padding).filter(|n| (1..=MAX_CHUNK as u64).contains(n));
+ let size = address_end.checked_sub(address).filter(|n| (1..=MAX_CHUNK as u64).contains(n));
+ let (Some(packed), Some(size)) = (packed, size) else {
+ return Err(invalid("a chunk with an impossible range"));
+ };
+ let codec = (pair[0] >> 26 & 15) as u8;
+ chunks.push(Chunk { address, size: size as usize, offset, packed: packed as usize, codec });
+ }
+
+ let etpf = (24 + table.len() as u64).next_multiple_of(256);
+ let mut header = [0u8; 16];
+ file.seek(SeekFrom::Start(etpf))?;
+ file.read_exact(&mut header).map_err(|_| invalid("no texture list"))?;
+ if &header[..4] != b"ETPF" || header.u32_at(4) != Some(ETPF_VERSION) {
+ return Err(invalid("unknown texture list version"));
+ }
+ let textures = header.u32_at(8).unwrap_or(0) as usize;
+ if !(1..=MAX_TEXTURES).contains(&textures) || (header.u32_at(12).unwrap_or(0) as usize) < textures * 16 {
+ return Err(invalid("impossible texture count"));
+ }
+ let mut records = vec![0u8; textures * 16];
+ file.read_exact(&mut records).map_err(|_| invalid("the texture list is cut off"))?;
+ let descriptors = records.as_chunks::<16>().0.iter().map(|r| Descriptor::parse(r)).collect();
+ // Right after the records: the key of each texture, by which models
+ // refer to it.
+ let mut keys = vec![0u8; textures * 8];
+ file.read_exact(&mut keys).map_err(|_| invalid("the texture keys are cut off"))?;
+ let keys = keys.as_chunks::<8>().0.iter().map(|k| u64::from_le_bytes(*k)).collect();
+ Ok(Pool { file: Mutex::new(file), virtual_size, chunks, descriptors, keys })
+ }
+
+ /// The keys of the textures, in their order: the materials of models
+ /// name their textures by these (0: none).
+ pub fn keys(&self) -> &[u64] {
+ &self.keys
+ }
+
+ /// Number of textures.
+ pub fn len(&self) -> usize {
+ self.descriptors.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.descriptors.is_empty()
+ }
+
+ pub fn descriptor(&self, index: usize) -> Option<&Descriptor> {
+ self.descriptors.get(index)
+ }
+
+ /// The size of a texture's allocation: up to the next texture's.
+ fn span(&self, index: usize, base: u64) -> Option {
+ for next in self.descriptors[index + 1..].iter().filter_map(|d| d.base) {
+ match next.cmp(&base) {
+ std::cmp::Ordering::Less => return None,
+ std::cmp::Ordering::Greater => return Some(next - base),
+ std::cmp::Ordering::Equal => {}
+ }
+ }
+ self.virtual_size.checked_sub(base)
+ }
+
+ /// The chunks that hold `size` bytes from virtual address `start`;
+ /// `None` when part of the range is in no chunk.
+ fn chunks_for(&self, start: u64, size: usize) -> Option<&[Chunk]> {
+ let end = start + size as u64;
+ let first = self.chunks.partition_point(|c| c.address + c.size as u64 <= start);
+ let count = self.chunks[first..].iter().take_while(|c| c.address < end).count();
+ let found = &self.chunks[first..first + count];
+ let gapless = found.windows(2).all(|w| w[0].address + w[0].size as u64 == w[1].address);
+ let covers = found.first().is_some_and(|c| c.address <= start)
+ && found.last().is_some_and(|c| c.address + c.size as u64 >= end);
+ (gapless && covers).then_some(found)
+ }
+
+ /// Whether a range can be read: none of its chunks is packed in a way
+ /// that is not read (BCPack for BC6H and BC7).
+ fn readable(&self, start: u64, size: usize) -> bool {
+ let reads = |c: &Chunk| matches!(c.codec, 0 | 8) || crate::bcpack::reads_mode(c.codec);
+ self.chunks_for(start, size).is_some_and(|chunks| chunks.iter().all(reads))
+ }
+
+ fn read_range(&self, start: u64, size: usize, max_bytes: usize) -> Result, TtpfError> {
+ let chunks = self.chunks_for(start, size).ok_or_else(|| invalid("a texture outside the pool's chunks"))?;
+ if size > max_bytes || chunks.iter().any(|c| c.size.saturating_add(c.packed).saturating_add(size) > max_bytes) {
+ return Err(unsupported("texture decode exceeds the requested memory limit"));
+ }
+ let mut out = vec![0u8; size];
+ let mut file = self.file.lock().unwrap_or_else(|e| e.into_inner());
+ for c in chunks {
+ let mut packed = vec![0u8; c.packed];
+ file.seek(SeekFrom::Start(c.offset))?;
+ for block in packed.chunks_mut(64 << 10) {
+ file.read_exact(block)?;
+ }
+ let data = match c.codec {
+ 0 => packed,
+ 8 => {
+ let mut data = Vec::with_capacity(c.size);
+ flate2::read::ZlibDecoder::new(&packed[..]).take(c.size as u64 + 1).read_to_end(&mut data)?;
+ data
+ }
+ codec => crate::bcpack::unpack(&packed, codec, c.size).map_err(|e| unsupported(e.to_string()))?,
+ };
+ if data.len() != c.size {
+ return Err(invalid("a chunk unpacks to another size than its range"));
+ }
+ let (from, to) = (start.max(c.address), (start + size as u64).min(c.address + c.size as u64));
+ out[(from - start) as usize..(to - start) as usize]
+ .copy_from_slice(&data[(from - c.address) as usize..(to - c.address) as usize]);
+ }
+ Ok(out)
+ }
+
+ /// Where the slices of each mip level are: per level the offset of the
+ /// first slice in the allocation and the distance to the next one.
+ /// `None` when the texture's kind or its allocation is not understood.
+ fn placement(&self, d: &Descriptor, span: u64) -> Option<(Layout, Vec<(u64, u64)>)> {
+ let element = element_bytes(d.format)?;
+ let block = if is_block_format(d.format) { 4 } else { 1 };
+ let tile = if d.mode >> 1 & 0xF == 0 { 65536 } else { 4096 };
+ match (d.dimension, d.depth) {
+ (1, 1) => {
+ let layout = Layout::new(d.width, d.height, d.mips, element, block, tile)?;
+ let places = layout.levels.iter().map(|l| (l.offset as u64, 0)).collect();
+ (span == layout.size as u64).then_some((layout, places))
+ }
+ // An array: level by level, each with all its slices. The small
+ // levels of slice `s` are in tile `s`.
+ (1, depth) if d.mode == 1 => {
+ let layout = Layout::new(d.width, d.height, d.mips, element, block, tile)?;
+ let depth = u64::from(depth);
+ let mut places = vec![(0, tile as u64); layout.levels.len()];
+ let mut offset = if layout.tail < layout.levels.len() { depth * tile as u64 } else { 0 };
+ for i in (0..layout.tail).rev() {
+ let region = layout.levels[i].region as u64;
+ places[i] = (offset, region);
+ offset += depth * region;
+ }
+ (span == offset).then_some((layout, places))
+ }
+ // A cube map: face by face, each laid out like a 2D texture in
+ // 4 KiB tiles; smaller copies of the whole cube map may come first.
+ (2, 6) if d.earlier_copies <= 3 && d.mode == 18 + 2 * d.earlier_copies => {
+ let layout = Layout::new(d.width, d.height, d.mips, element, block, 4096)?;
+ let all = 6 * layout.size as u64;
+ let start = if d.earlier_copies == 0 {
+ (span == all).then_some(0)?
+ } else {
+ let padded = if all >= 36 * 4096 { all.next_multiple_of(65536) } else { all };
+ span.checked_sub(padded)?
+ };
+ let places = layout.levels.iter().map(|l| (start + l.offset as u64, layout.size as u64)).collect();
+ Some((layout, places))
+ }
+ _ => None,
+ }
+ }
+
+ /// Reads a texture: its largest mip level that can be read and is at
+ /// most `max_side` pixels wide and high (`None`: any size). The result
+ /// has that one level, of every slice of an array and every face of a
+ /// cube map; its name is the texture's number. Volumes are not read.
+ pub fn texture(&self, index: usize, max_side: Option) -> Result {
+ self.texture_with_limit(index, max_side, 128 << 20)
+ }
+
+ /// Like `texture`, with an explicit cap on decoded texture/chunk buffers.
+ pub fn texture_with_limit(
+ &self,
+ index: usize,
+ max_side: Option,
+ max_bytes: usize,
+ ) -> Result {
+ let d = *self.descriptor(index).ok_or_else(|| invalid("no such texture"))?;
+ if d.dimension == 3 {
+ return Err(unsupported("a volume, which is not read yet"));
+ }
+ let base = d.base.ok_or_else(|| unsupported("it has no data in this pool"))?;
+ if element_bytes(d.format).is_none() {
+ return Err(unsupported(format!("unknown pixel format {}", d.format)));
+ }
+ let span = self.span(index, base).ok_or_else(|| unsupported("its layout is not understood"))?;
+ let (layout, places) = self
+ .placement(&d, span)
+ .ok_or_else(|| unsupported(format!("a {} whose layout is not understood", d.shape())))?;
+ let slices = u64::from(d.depth);
+ let slice_at = |i: usize, s: u64| base + places[i].0 + s * places[i].1;
+ let fits =
+ |i: &usize| max_side.is_none_or(|max| layout.levels[*i].pixels.0.max(layout.levels[*i].pixels.1) <= max);
+ let readable = |i: &usize| (0..slices).all(|s| self.readable(slice_at(*i, s), layout.levels[*i].region));
+ // The largest level that fits; if only larger ones can be read, the
+ // smallest of those.
+ let all = 0..layout.levels.len();
+ let chosen = all
+ .clone()
+ .filter(fits)
+ .find(readable)
+ .or_else(|| all.rev().filter(|i| !fits(i)).find(readable))
+ .ok_or_else(|| unsupported("packed with BCPack for BC6H or BC7, which is not read yet"))?;
+ let level = &layout.levels[chosen];
+ if level.region.saturating_mul(slices as usize) > max_bytes {
+ return Err(unsupported("texture slices exceed the requested memory limit"));
+ }
+ let mut data = Vec::new();
+ for s in 0..slices {
+ let stored = self.read_range(slice_at(chosen, s), level.region, max_bytes.saturating_sub(data.len()))?;
+ data.extend(layout.untile(level, &stored).ok_or_else(|| invalid("a mip level outside its allocation"))?);
+ }
+ Ok(Texture {
+ name: format!("{index:06}"),
+ width: level.pixels.0,
+ height: level.pixels.1,
+ depth: d.depth,
+ levels: 1,
+ format: Format(d.format),
+ dimension: if d.dimension == 2 { Dimension::Cube } else { Dimension::Texture2D },
+ usage: 0,
+ data,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Write;
+
+ /// The address of element (x, y) in its tile, bit by bit from the pattern.
+ fn tile_offset(pattern: &[i8], x: usize, y: usize) -> usize {
+ pattern.iter().enumerate().fold(0, |acc, (bit, &s)| {
+ let source = if s > 0 {
+ x >> (s - 1)
+ } else if s < 0 {
+ y >> (-s - 1)
+ } else {
+ 0
+ };
+ acc | (source & 1) << bit
+ })
+ }
+
+ #[test]
+ fn layout_of_a_compressed_texture() {
+ // 256×256 in blocks of 8 bytes, 4 KiB tiles: 64×64 blocks; a tile is
+ // 32×16 blocks. Levels 0 and 1 get tiles, the rest share one.
+ let layout = Layout::new(256, 256, 9, 8, 4, 4096).unwrap();
+ assert_eq!((layout.tile_across, layout.tile_down), (32, 16));
+ let own: Vec<(usize, usize, usize)> = layout.levels.iter().map(|l| (l.across, l.offset, l.region)).collect();
+ assert_eq!(&own[..3], [(64, 4096 + 8192, 32768), (32, 4096, 8192), (16, 0, 4096)]);
+ assert_eq!(layout.size, 4096 + 8192 + 32768);
+ assert!(layout.levels[2..].iter().all(|l| l.offset == 0 && l.region == 4096));
+ // The shared tile: no two levels overlap.
+ let mut used = std::collections::HashSet::new();
+ for l in &layout.levels[2..] {
+ for (x, y) in (0..l.across).flat_map(|x| (0..l.down).map(move |y| (x, y))) {
+ assert!(used.insert((x + l.tile_x, y + l.tile_y)), "levels overlap in the shared tile");
+ }
+ }
+ assert_eq!(Layout::new(256, 256, 10, 8, 4, 4096), None);
+ assert_eq!(Layout::new(256, 256, 1, 8, 4, 4096).unwrap().size, 32768);
+ }
+
+ #[test]
+ fn untiling_puts_every_element_in_its_row() {
+ let layout = Layout::new(128, 64, 1, 4, 1, 4096).unwrap();
+ let level = layout.levels[0];
+ assert_eq!((layout.tile_across, layout.tile_down, level.region), (32, 32, 128 * 64 * 4));
+ // Each element holds its own coordinates.
+ let mut stored = vec![0u8; level.region];
+ for (x, y) in (0..128usize).flat_map(|x| (0..64usize).map(move |y| (x, y))) {
+ let tile = (y / 32) * 4 + x / 32;
+ let at = tile * 4096 + tile_offset(&PATTERNS_4K[2], x, y);
+ stored[at..at + 4].copy_from_slice(&[x as u8, y as u8, 0xAB, 0xCD]);
+ }
+ let rows = layout.untile(&level, &stored).unwrap();
+ for (i, element) in rows.as_chunks::<4>().0.iter().enumerate() {
+ assert_eq!(*element, [(i % 128) as u8, (i / 128) as u8, 0xAB, 0xCD]);
+ }
+ }
+
+ /// A pool with one texture of 64×64 pixels (4 bytes each, one level) in
+ /// one zlib chunk, and one without data.
+ #[test]
+ fn reads_a_texture_from_a_pool() {
+ let layout = Layout::new(64, 64, 1, 4, 1, 4096).unwrap();
+ let level = layout.levels[0];
+ let mut stored = vec![0u8; level.region];
+ for (x, y) in (0..64usize).flat_map(|x| (0..64usize).map(move |y| (x, y))) {
+ let at = ((y / 32) * 2 + x / 32) * 4096 + tile_offset(&PATTERNS_4K[2], x, y);
+ stored[at..at + 4].copy_from_slice(&[x as u8, y as u8, 7, 255]);
+ }
+ let mut packed = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
+ packed.write_all(&stored).unwrap();
+ let mut packed = packed.finish().unwrap();
+ let padding = packed.len().next_multiple_of(256) - packed.len();
+ packed.resize(packed.len() + padding, 0);
+
+ let data_at = 1024u64;
+ let word = |offset: u64, codec: u64, page: u64, padding: u64| {
+ (offset / 256) | (codec << 26) | page << 30 | padding << 52
+ };
+ let mut file = b"RDS5".to_vec();
+ file.extend_from_slice(&3u32.to_le_bytes());
+ file.extend_from_slice(&(((1 + 4) * 4096u64) | (22 << 56)).to_le_bytes());
+ file.extend_from_slice(&[0; 8]);
+ file.extend_from_slice(&word(data_at, 8, 1, padding as u64).to_le_bytes());
+ file.extend_from_slice(&word(data_at + packed.len() as u64, 0, 5, 0).to_le_bytes());
+ file.resize(256, 0);
+ file.extend_from_slice(b"ETPF");
+ file.extend_from_slice(&ETPF_VERSION.to_le_bytes());
+ file.extend_from_slice(&2u32.to_le_bytes());
+ file.extend_from_slice(&48u32.to_le_bytes());
+ let record = |page: u32| {
+ let mut r = Vec::new();
+ r.extend_from_slice(&(63u32 | 63 << 14 | 1 << 28).to_le_bytes());
+ // Format 28 (RGBA8), 2D, tiling mode 2 (4 KiB tiles).
+ r.extend_from_slice(&(28u32 << 3 | 1 << 21 | 2 << 23).to_le_bytes());
+ r.extend_from_slice(&page.to_le_bytes());
+ r.extend_from_slice(&[0; 4]);
+ r
+ };
+ file.extend(record(1));
+ file.extend(record(0));
+ file.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
+ file.extend_from_slice(&[0; 8]);
+ file.resize(data_at as usize, 0);
+ file.extend_from_slice(&packed);
+
+ let dir = std::env::temp_dir().join(format!("rage-ttpf-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("pool.ttpf");
+ std::fs::write(&path, &file).unwrap();
+ let pool = Pool::open(&path).unwrap();
+ assert_eq!(pool.len(), 2);
+ assert_eq!(pool.keys(), [0x1122_3344_5566_7788, 0]);
+ let d = pool.descriptor(0).unwrap();
+ assert_eq!((d.width, d.height, d.mips, d.format, d.shape()), (64, 64, 1, 28, "2D"));
+ assert!(pool.texture_with_limit(0, None, 1024).is_err());
+ let texture = pool.texture(0, None).unwrap();
+ assert_eq!((texture.width, texture.height, texture.levels, texture.name.as_str()), (64, 64, 1, "000000"));
+ for (i, pixel) in texture.data.as_chunks::<4>().0.iter().enumerate() {
+ assert_eq!(*pixel, [(i % 64) as u8, (i / 64) as u8, 7, 255]);
+ }
+ assert!(matches!(pool.texture(1, None), Err(TtpfError::Unsupported(_))));
+ assert!(pool.texture(2, None).is_err());
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+}
diff --git a/crates/rage-rpf/Cargo.toml b/crates/rage-rpf/Cargo.toml
index f8028ec..bd373d5 100644
--- a/crates/rage-rpf/Cargo.toml
+++ b/crates/rage-rpf/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "rage-rpf"
-description = "Reader and writer for RAGE archives (RPF7 GTA V, IMG3/RPF2/RPF3 GTA IV; RPF8 RDR2 with the `rdr2` feature)"
+description = "RAGE archives: RPF7, IMG3/RPF2/RPF3, optional RPF8, and experimental RPF9 inspection"
version.workspace = true
edition.workspace = true
license.workspace = true
diff --git a/crates/rage-rpf/README.md b/crates/rage-rpf/README.md
index f5f1b48..938de3f 100644
--- a/crates/rage-rpf/README.md
+++ b/crates/rage-rpf/README.md
@@ -8,6 +8,7 @@ Read and write RAGE archives, part of
| RPF7 (incl. nested archives, AES and NG encryption) | GTA V Legacy and Enhanced | yes | yes |
| IMG3, RPF2, RPF3 | GTA IV | yes | yes |
| RPF8 | Red Dead Redemption 2 | with the `rdr2` feature | no |
+| RPF9 (Scarlett 1.0.2.1) | TOC, hash listing, raw/decoded export | partial | no |
`vfs` resolves paths that cross archive boundaries
(`update/update.rpf/x64/data/lang/americandlc.rpf/global.gxt2`).
@@ -24,6 +25,23 @@ Untrusted archives are expected: nesting depth (`MAX_NESTING`) and unpacked
sizes (`MAX_UNPACKED`) are limited, and `vfs::safe_relative_path` must be used
for every extraction path.
+## Experimental RPF9 support
+
+`rpf9::Archive` reads the encrypted TOC and lists logical entries by their
+stored hashes. It exports raw allocations or supported decoded files using
+per-entry selective TFIT-CTR and block decompression. Metadata and payload I/O
+are bounded; the reader never loads a whole game archive into memory.
+
+`rpf9_exe` reads only the necessary ranges from the user's Scarlett 1.0.2.1
+PE and validates cipher material with SHA-256 fingerprints. No game keys,
+IVs, tables, executable bytes or archive fixtures are shipped.
+
+Use `openrage rpf9 --help` for inspection and export. See [RPF9.md](RPF9.md)
+for native evidence, validation coverage and remaining unsupported layouts.
+The application-facing `Rpf9` adapter uses the TOC for VFS/GUI browsing,
+candidate-name lookup and directly stored nested archives. Editing and writing
+remain unsupported.
+
## The `rdr2` feature and its licence
RPF8 decryption uses [`rage-tfit2`](../rage-tfit2), which is licensed under
diff --git a/crates/rage-rpf/RPF9.md b/crates/rage-rpf/RPF9.md
new file mode 100644
index 0000000..6a87944
--- /dev/null
+++ b/crates/rage-rpf/RPF9.md
@@ -0,0 +1,169 @@
+# RPF9 Scarlett reader
+
+This branch reads the encrypted TOC of the analysed Scarlett 1.0.2.1 build,
+lists logical entries by their stored 64-bit hashes, and exports stored bytes
+or supported decoded payloads. It reads cipher material from the user's PE;
+no game keys, tables, executable bytes or archive fixtures are distributed.
+
+```sh
+openrage rpf9 common.rpf --exe game_scarlett_master.exe --list
+openrage rpf9 common.rpf --exe game_scarlett_master.exe --extract 0 --output entry.bin
+openrage rpf9 script.rpf --exe game_scarlett_master.exe --extract-raw 0 --output nested.rpf
+openrage rpf9 pack/story000/story000.rpf --exe game_scarlett_master.exe --nested 419 --list
+openrage rpf9 common.rpf --exe game_scarlett_master.exe --list --names candidates.txt
+```
+
+Outputs must not already exist. `--extract-raw` retains encryption, compression
+and allocation padding. `--extract` uses the logical entry's crypto and block
+descriptors; it does not infer file boundaries from signatures. Unknown codecs
+and unsupported layouts produce explicit errors.
+
+`--nested` opens a directly stored child archive without exporting it first.
+Resource exports skip the physical 16-byte prefix and prepend the native
+synthetic `RSC8` header to the decoded data. The reader supports multiple
+external metadata columns, including archives containing only resources.
+
+## Candidate name resolution
+
+Like OpenRAGE's RPF8 resolver, `--names` tests an explicit list of candidate
+paths against the TOC. The list is UTF-8, one path per line, limited to 8 MiB
+with a 4096-byte line limit and at most 250,000 indexed keys.
+It tries normalized paths, paths without mount prefixes, basenames and stems.
+Distinct matches are preserved rather than choosing between collisions.
+
+The name lookup column is `73bcb72dce74f11f`, **not** `b6f5bdb2c66da2e9`.
+The latter remains an opaque stored identifier. Native `0x144F66DE0` uses
+MurmurHash3 x64-style mixing with seed zero, returning the low 64 bits.
+The table at `0x1465B23B0` folds ASCII case and maps backslashes to slashes.
+Its finalizer uses the low byte of the length. Some matched paths include
+extensions; others do not. The application derives known resource extensions
+from the TOC file type; unknown types retain the candidate spelling.
+
+A bounded local experiment decoded 256 small appdata/common entries, with
+6,608,262 bytes charged against the output budget. Their 18,519 candidate
+strings produced 1,071 matching entries across the 22 outer archives
+(1,062 distinct name hashes). These are candidate path matches, not a claim
+that every original filename or directory tree has been recovered.
+Encrypted trailer/name-table decoding is still unsupported.
+
+## Bounded I/O
+
+PE loading seeks to the headers, key registry and selected key/table blobs;
+it does not read the complete executable. Each PE read is capped at 1 MiB.
+Archive loading reads the 64-byte header and at most 64 MiB of head metadata;
+there is no archive-sized allocation. Payload reads and decompression use
+64-KiB buffers and validate declared input/output lengths. The reader never
+loads a complete multi-gigabyte archive into memory. Raw copying streams to
+the caller's writer. Callers choosing a `Vec` writer still own that output's
+memory use.
+
+## Native evidence and corrections
+
+Addresses below are VAs in the reference PE, base `0x140000000`.
+
+The former TFIT prefix proof used the wrong final permutation. Native block
+`0x145642C50` uses `[0,13,10,7,4,1,14,11,8,5,2,15,12,9,6,3]`.
+The corrected prefix is a property directory with IDs 1, 5, 6, 9 and relative
+offsets 0, 0x18, 0x30, 0x140. The old pseudo-plaintext is not a valid vector.
+
+`0x14087AFF0` and `0x14087B0F0` construct the physical views. For the supported
+outer profile, the global TFIT-CBC profile decrypts `[0x40,0x1a0)` with
+continuous chaining across the property directory and values.
+`0x140A348A0` / `0x1406BD160` establish this chaining. Property 1 supplies
+the archive's TOC key selector, algorithm 0x10 and IV at descriptor +6.
+`0x1406BD090` decrypts `[0x1a0,w08)` with that profile, while `0x1408EC360`
+decrypts `[w08,w04)` in a fresh provider with the original IV.
+
+For general layouts, let `P = 0x40 + align16(property_count * 8)` and
+`S = P + H[0x1c] - H[0x30]`. The outer span is `[0x40,S)`; the inner
+spans are `[S,w08)` and `[w08,w04)`, with independent IV resets. `H[0x30]`
+is the length of the inner-encrypted property suffix, not an alignment.
+
+The 24-byte column descriptor is `(u64 hash, u32 count, u32 offset,
+u16 stride, u16 region, u32 reserved)`. Native `0x144DB6600` resolves
+row-major indices and all-ones sentinels. `0x1455B2600` selects the A/B data
+base and applies the column offset and index. Logical entry order must not
+be confused with physical record order.
+
+| Column hash | Record |
+|---|---|
+| `33f70dfaf2c50989` | 24-byte ordinary extent |
+| `ba180afb232d1b4b` | 20-byte resource extent |
+| `286030a358a789fb` | 64-byte selective crypto descriptor |
+| `e0c12d7a5d4884c5` | 8-byte relative block-table descriptor |
+| `b6f5bdb2c66da2e9` | opaque 64-bit entry identifier |
+| `73bcb72dce74f11f` | normalized 64-bit path hash |
+
+Native getters `0x1400C6950`, `0x141330AD0`, `0x141331670` and
+`0x1400F62E0` define offset, stored size, logical size and stream codec.
+Ordinary offsets and stored sizes mask to 40 bits then multiply by 16;
+logical size masks to 44 bits. Resource extents use separate packed fields.
+The extent stream codec is byte +6 (resource +17), not byte +5.
+
+Block tables override the stream codec. `0x14550DB40` decodes formats 2/3/4;
+actual compressed bytes exclude block padding. Codec 3 is independently
+zlib-validated. Each block resets decompression. Input length, decoded length,
+checksum and stream termination are checked.
+
+Payload algorithm 0x11 maps through `0x140536AC0`, `0x144C11250` and
+`0x14171FD00` to TFIT-CTR `0x1455DC010`, block `0x1456437C0` and context
+loader `0x1455DC890`. Its fixed tables are at `0x146040F30`, and its key
+blob magic is `0x2718CE5D`; it is distinct from the metadata CBC primitive.
+
+Crypto fields at +24/+32/+40/+48 are encrypted prefix, encrypted middle run,
+clear middle run and encrypted suffix. Flags at +56 select the size coordinate.
+`0x1428CEBC0` / `0x141616150` establish selective ranges. `0x140FC9040`
+adds the absolute byte position divided by 16 to the original big-endian
+128-bit IV; skipped clear bytes still advance the counter coordinate.
+
+## Verification
+
+Synthetic tests cover column indirection, missing records, corrupt indices,
+size bounds, TFIT final permutation, CTR chunk boundaries, range boundaries,
+and zlib truncation/checksum failures. No proprietary test fixture is needed.
+
+Opt-in local validation:
+
+```sh
+RPF9_EXE=/path/to/game_scarlett_master.exe RPF9_ROOT=/path/to/game \
+ cargo test -p rage-rpf --test rpf9_local -- --ignored --nocapture
+```
+
+The local corpus has 22 outer archives and 6,534 logical entries. Payload
+validation selects bounded samples and streams decoded output to a sink.
+It is not a claim that every byte in the corpus has been decoded.
+Local nested validation covers 24 distinct metadata layouts.
+
+## GUI, VFS and previews
+
+The PR #144 interface and format readers are integrated with the exact TOC.
+Place `game_scarlett_master.exe` and optionally `rpf9-names.txt` in the game
+root (`RPF9_NAMES` overrides the dictionary path). RPF9 signature detection
+takes precedence over copied GTA V/RDR2 executables. Opening an archive with
+the reference executable uses its decrypted TOC and skips recovery scans.
+Directly stored nested archives are navigable through the normal VFS.
+
+Known paths can be opened without first adding them to the dictionary: lookup
+normalizes the path, hashes it, checks the native file type and requires a
+unique matching entry. Listing readable names still needs the dictionary.
+For example: `openrage --game /path/to/game info common.rpf/data/ai/conversationlist.meta`.
+
+Model previews use exact system/graphics partitions from resource flags.
+TOC reads and model allocations are capped at 128 MiB; extraction streams.
+Standalone `data/ttdb` TTPF pools support texture previews and PNG output;
+the decoder has an explicit byte-budget API. Local bounded validation decoded
+16 model resources and exported 16 textures, including BC1, successfully.
+These samples do not establish support for all models or texture layouts.
+
+The metadata export covers 1,255,039 entries across 4,373 archives (22 outer
+and 4,351 direct nested). A local GPU dictionary run tested 18,959,548 candidates
+and matched 80,958 distinct 64-bit hashes covering 101,484 entries. Candidate
+preimages are not proof of original spelling; 32-bit-only matches remain
+separate hypotheses. See `tools/` for reproducible dictionary tooling.
+
+## Remaining scope
+
+Trailer decoding, missing names, transformed nested archives and codecs not
+yet verified remain separate work. Embedded texture-pool discovery, BC6H/BC7
+BCPack decoding, volume textures, skeletons and model LOD support are incomplete.
+No editing/repacking or support for other executable builds is claimed.
diff --git a/crates/rage-rpf/examples/gta5_name_export.rs b/crates/rage-rpf/examples/gta5_name_export.rs
new file mode 100644
index 0000000..b15a66c
--- /dev/null
+++ b/crates/rage-rpf/examples/gta5_name_export.rs
@@ -0,0 +1,259 @@
+//! Inventory installed RPF7 names, including nested TOCs, without reading assets.
+//! Usage: gta5_name_export GAME_DIR MAGIC_DAT OUTPUT
+//! Every filesystem read <=1MiB; each combined TOC <=64MiB. No production changes.
+use rage_crypto::{GtaVKeys, decode_codewalker_magic, scan_executable};
+use std::{
+ collections::HashSet,
+ error::Error,
+ fs::{self, File},
+ io::{self, BufWriter, Read, Seek, SeekFrom, Write},
+ path::{Path, PathBuf},
+ process::Command,
+};
+
+type Result = std::result::Result>;
+const CHUNK: usize = 1 << 20;
+const CAP: u64 = 64 << 20;
+fn bad(s: &str) -> io::Error {
+ io::Error::new(io::ErrorKind::InvalidData, s)
+}
+fn word(b: &[u8], o: usize) -> u32 {
+ u32::from_le_bytes(b[o..o + 4].try_into().unwrap())
+}
+fn u24(b: &[u8], o: usize) -> u32 {
+ u32::from_le_bytes([b[o], b[o + 1], b[o + 2], 0])
+}
+fn read_at(file: &mut File, offset: u64, size: usize) -> Result> {
+ if size as u64 > CAP
+ || offset.checked_add(size as u64).is_none_or(|e| e > file.metadata().map(|m| m.len()).unwrap_or(0))
+ {
+ return Err(bad("bounded read exceeds file or cap").into());
+ }
+ file.seek(SeekFrom::Start(offset))?;
+ let mut bytes = vec![0; size];
+ for chunk in bytes.chunks_mut(CHUNK) {
+ file.read_exact(chunk)?;
+ }
+ Ok(bytes)
+}
+fn keys(game: &Path, magic: &Path) -> Result {
+ let mut exe = File::open(game.join("GTA5_Enhanced.exe"))?;
+ let size = exe.metadata()?.len();
+ // 1024-byte overlap also preserves all windows considered by the scanner.
+ // The step is 8-byte aligned, as are its fingerprint search positions.
+ let mut at = 0;
+ let aes = loop {
+ if at >= size {
+ return Err(bad("AES fingerprint absent from executable").into());
+ }
+ let bytes = read_at(&mut exe, at, (size - at).min(CHUNK as u64) as usize)?;
+ let scan = scan_executable(&bytes);
+ if let Some(aes) = scan.aes_key {
+ break aes;
+ }
+ at += (CHUNK - 1024) as u64;
+ if at % (8 * (CHUNK - 1024) as u64) == 0 {
+ eprintln!("AES scan: {} MiB", at >> 20);
+ }
+ };
+ eprintln!("AES fingerprint verified; key bytes are not logged");
+ let mut file = File::open(magic)?;
+ let size = file.metadata()?.len();
+ if size == 0 || size > CHUNK as u64 {
+ return Err(bad("magic.dat exceeds 1MiB cap").into());
+ }
+ let blob = read_at(&mut file, 0, size as usize)?;
+ let material = decode_codewalker_magic(&blob, &aes)?;
+ GtaVKeys::from_magic(aes, &material).ok_or_else(|| bad("invalid key blob layout").into())
+}
+
+struct Job {
+ base: u64,
+ size: u64,
+ name: String,
+ qualified: String,
+ depth: u8,
+}
+#[derive(Default)]
+struct Stats {
+ archives: u64,
+ entries: u64,
+ errors: u64,
+ metadata: u64,
+}
+fn toc(file: &mut File, job: &Job, keys: &GtaVKeys, output: &mut impl Write, stats: &mut Stats) -> Result> {
+ if job.size < 16 || job.depth > 16 {
+ return Err(bad("invalid nested archive window").into());
+ }
+ let h = read_at(file, job.base, 16)?;
+ if word(&h, 0) != 0x52504637 {
+ return Err(bad("not RPF7").into());
+ }
+ let n = word(&h, 4) as usize;
+ let names_len = word(&h, 8) as usize;
+ let len = 16 + (n as u64) * 16 + names_len as u64;
+ if n == 0 || n > 1 << 20 || names_len as u64 > CAP || len > CAP || len > job.size {
+ return Err(bad("TOC exceeds count/metadata/archive bounds").into());
+ }
+ let mut entries = read_at(file, job.base + 16, n * 16)?;
+ let mut names = read_at(file, job.base + 16 + (n as u64) * 16, names_len)?;
+ match word(&h, 12) {
+ 0 | 0x4e45504f => {}
+ 0x0ffffff9 => {
+ keys.decrypt_aes(&mut entries);
+ keys.decrypt_aes(&mut names);
+ }
+ _ => {
+ keys.decrypt_ng(&mut entries, &job.name, job.size as u32);
+ keys.decrypt_ng(&mut names, &job.name, job.size as u32);
+ }
+ }
+ stats.metadata += len;
+ if word(&entries, 4) != 0x7fffff00 {
+ return Err(bad("decrypted root is not directory").into());
+ }
+ let mut seen = vec![false; n];
+ seen[0] = true;
+ let mut pending = vec![(0usize, String::new(), 0u16)];
+ let mut children = Vec::new();
+ while let Some((dir, parent, depth)) = pending.pop() {
+ if depth > 256 {
+ return Err(bad("directory depth cap").into());
+ }
+ let r = &entries[dir * 16..dir * 16 + 16];
+ let first = word(r, 8) as usize;
+ let count = word(r, 12) as usize;
+ let end = first.checked_add(count).filter(|end| *end <= n).ok_or_else(|| bad("directory range"))?;
+ if count > 0 && first == 0 {
+ return Err(bad("root claimed as child").into());
+ }
+ for (i, claimed) in seen.iter_mut().enumerate().take(end).skip(first) {
+ if *claimed {
+ return Err(bad("shared/cyclic directory entry").into());
+ }
+ *claimed = true;
+ let r = &entries[i * 16..i * 16 + 16];
+ let second = word(r, 4);
+ let directory = second == 0x7fffff00;
+ let no = if directory { word(r, 0) as usize } else { u16::from_le_bytes([r[0], r[1]]) as usize };
+ let tail = names.get(no..).ok_or_else(|| bad("name offset"))?;
+ let end = tail
+ .iter()
+ .position(|b| *b == 0)
+ .filter(|end| *end <= 4096)
+ .ok_or_else(|| bad("unterminated/long name"))?;
+ let name = std::str::from_utf8(&tail[..end])?;
+ if name.is_empty() || name.chars().any(char::is_control) || name.contains(['/', '\\']) {
+ return Err(bad("invalid path component").into());
+ }
+ let path = if parent.is_empty() { name.to_owned() } else { format!("{parent}/{name}") };
+ if path.len() > 4096 {
+ return Err(bad("path length cap").into());
+ }
+ if directory {
+ pending.push((i, path, depth + 1));
+ continue;
+ }
+ stats.entries += 1;
+ writeln!(output, "{path}")?;
+ writeln!(output, "{name}")?;
+ writeln!(output, "{}/{path}", job.qualified)?;
+ if !name.to_ascii_lowercase().ends_with(".rpf") {
+ continue;
+ }
+ if second & 0x80000000 != 0 || u24(r, 2) != 0 || word(r, 12) != 0 {
+ return Err(bad("nested RPF is compressed/encrypted/resource; payload reads forbidden").into());
+ }
+ let offset = u64::from(u24(r, 5)) * 512;
+ let size = u64::from(word(r, 8));
+ if offset < len || size < 16 || offset.checked_add(size).is_none_or(|end| end > job.size) {
+ return Err(bad("nested RPF outside parent/data window").into());
+ }
+ children.push(Job {
+ base: job.base + offset,
+ size,
+ name: name.into(),
+ qualified: format!("{}/{path}", job.qualified),
+ depth: job.depth + 1,
+ });
+ }
+ }
+ if seen.iter().any(|v| !*v) {
+ return Err(bad("unreachable TOC entries").into());
+ }
+ stats.archives += 1;
+ Ok(children)
+}
+fn roots(dir: &Path, output: &mut Vec) -> Result<()> {
+ for item in fs::read_dir(dir)? {
+ let item = item?;
+ let kind = item.file_type()?;
+ if kind.is_symlink() {
+ continue;
+ }
+ if kind.is_dir() {
+ roots(&item.path(), output)?;
+ } else if item.path().extension().is_some_and(|s| s.eq_ignore_ascii_case("rpf")) {
+ output.push(item.path());
+ }
+ }
+ Ok(())
+}
+fn main() -> Result<()> {
+ let args: Vec<_> = std::env::args_os().skip(1).collect();
+ if args.len() != 3 {
+ return Err(bad("usage: gta5_name_export GAME_DIR MAGIC_DAT OUTPUT").into());
+ }
+ let game = Path::new(&args[0]);
+ let dest = Path::new(&args[2]);
+ let keys = keys(game, Path::new(&args[1]))?;
+ if let Some(parent) = dest.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ let spool = dest.with_extension("unsorted.tmp");
+ let mut output = BufWriter::new(File::create(&spool)?);
+ let mut errors = BufWriter::new(File::create(dest.with_extension("errors.log"))?);
+ let mut files = Vec::new();
+ roots(game, &mut files)?;
+ files.sort();
+ let mut stats = Stats::default();
+ for path in files {
+ let mut file = File::open(&path)?;
+ let name = path.file_name().unwrap().to_string_lossy().into_owned();
+ let qualified = path.strip_prefix(game)?.to_string_lossy().replace('\\', "/");
+ let mut pending = vec![Job { base: 0, size: file.metadata()?.len(), name, qualified, depth: 0 }];
+ let mut seen = HashSet::new();
+ while let Some(job) = pending.pop() {
+ if !seen.insert((job.base, job.size)) {
+ continue;
+ }
+ match toc(&mut file, &job, &keys, &mut output, &mut stats) {
+ Ok(children) => pending.extend(children),
+ Err(e) => {
+ stats.errors += 1;
+ writeln!(errors, "{}: {e}", job.qualified)?;
+ }
+ }
+ if stats.archives > 0 && stats.archives % 100 == 0 {
+ eprintln!("{} archives, {} files, {} errors", stats.archives, stats.entries, stats.errors);
+ }
+ }
+ }
+ output.flush()?;
+ errors.flush()?;
+ drop(output);
+ let status =
+ Command::new("sort").env("LC_ALL", "C").args(["-u", "-S", "64M", "-o"]).arg(dest).arg(&spool).status()?;
+ if !status.success() {
+ return Err(bad("external bounded-memory dictionary sort failed").into());
+ }
+ fs::remove_file(spool)?;
+ eprintln!(
+ "DONE archives={} files={} errors={} metadata_bytes={}",
+ stats.archives, stats.entries, stats.errors, stats.metadata
+ );
+ if stats.errors != 0 {
+ return Err(bad("partial inventory: see errors.log").into());
+ }
+ Ok(())
+}
diff --git a/crates/rage-rpf/examples/rpf9_dictionary_attack.rs b/crates/rage-rpf/examples/rpf9_dictionary_attack.rs
new file mode 100644
index 0000000..3ada1dc
--- /dev/null
+++ b/crates/rage-rpf/examples/rpf9_dictionary_attack.rs
@@ -0,0 +1,387 @@
+//! CPU-only extension dictionary comparison. No archive access.
+//! Usage: rpf9_dictionary_attack EXPORT_DIR CANDIDATE_LIST...
+//! Reads bounded lines; sorted target vectors, disk dedupe, one hash worker.
+use rage_rpf::rpf9::name_hash;
+use std::{
+ collections::HashSet,
+ error::Error,
+ fs::{self, File, OpenOptions},
+ io::{self, BufRead, BufReader, BufWriter, Write},
+ path::{Path, PathBuf},
+ process::Command,
+};
+type Result = std::result::Result>;
+const MIB: usize = 1 << 20;
+fn bad(s: &str) -> io::Error {
+ io::Error::new(io::ErrorKind::InvalidData, s)
+}
+fn lines(path: &Path, mut f: impl FnMut(&str) -> Result<()>) -> Result<()> {
+ let mut r = BufReader::with_capacity(64 * 1024, File::open(path)?);
+ let mut line = Vec::new();
+ loop {
+ let b = r.fill_buf()?;
+ if b.is_empty() {
+ break;
+ }
+ let n = b.iter().position(|v| *v == b'\n').map_or(b.len(), |i| i + 1);
+ if line.len() + n > 65536 {
+ return Err(bad("line exceeds 64KiB").into());
+ }
+ line.extend_from_slice(&b[..n]);
+ r.consume(n);
+ if line.last() == Some(&b'\n') {
+ f(std::str::from_utf8(&line)?.trim_end_matches(['\r', '\n']))?;
+ line.clear();
+ }
+ }
+ if !line.is_empty() {
+ f(std::str::from_utf8(&line)?)?
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn native_hash_vectors() {
+ assert_eq!(hash32("ADDER"), 0xb779a091);
+ assert_eq!(hash32("\"adder\"unused"), 0xb779a091);
+ assert_eq!(hash32("a\\b\0ignored"), hash32("A/B"));
+ assert_eq!(name_hash("DATA\\graphics/graphics_definitions.meta"), 0x5c33030f6402b9dd);
+ assert_eq!(name_hash(&"a".repeat(256)), 0x42bffdb35fe459a8);
+ }
+
+ #[test]
+ fn nested_paths_and_compound_suffixes() {
+ let v = variants("COMMON:/outer.rpf/inside.rpf/x64/audio/example.dat151.rel");
+ assert!(v.iter().any(|s| s == "audio/example.dat151.rel"));
+ assert!(v.iter().any(|s| s == "audio/example"));
+ assert!(v.iter().any(|s| s == "example"));
+ assert!(variants("// a comment").is_empty());
+ }
+}
+fn create(p: &Path) -> Result> {
+ Ok(BufWriter::new(OpenOptions::new().write(true).create_new(true).open(p)?))
+}
+fn hash32(s: &str) -> u32 {
+ let data = if let Some(s) = s.strip_prefix('"') { s.split('"').next().unwrap_or("") } else { s };
+ let mut h = 0u32;
+ for b in data.bytes().take_while(|b| *b != 0) {
+ let b = if b == b'\\' { b'/' } else { b.to_ascii_lowercase() };
+ h = h.wrapping_add(b as u32);
+ h = h.wrapping_add(h << 10);
+ h ^= h >> 6;
+ }
+ h = h.wrapping_add(h << 3);
+ h ^= h >> 11;
+ h.wrapping_add(h << 15)
+}
+fn variants(line: &str) -> Vec {
+ let p = line
+ .trim()
+ .trim_start_matches('\u{feff}')
+ .split('=')
+ .next()
+ .unwrap_or("")
+ .trim()
+ .trim_matches('"')
+ .to_ascii_lowercase()
+ .replace('\\', "/");
+ if p.is_empty()
+ || p.len() > 1024
+ || p.starts_with("//")
+ || p.starts_with('#')
+ || p.starts_with('[')
+ || !p.is_ascii()
+ || p.bytes().any(|c| !(c.is_ascii_alphanumeric() || b"_./:-@+ #".contains(&c)))
+ {
+ return vec![];
+ }
+ let after = p.split_once(":/").map_or(p.as_str(), |(_, s)| s).trim_start_matches('/');
+ let inner = after.rsplit_once(".rpf/").map_or(after, |(_, s)| s);
+ let x = inner.strip_prefix("x64/").unwrap_or(inner);
+ let base = x.rsplit('/').next().unwrap_or(x);
+ let mut v = vec![p.clone(), after.into(), inner.into(), x.into(), base.into()];
+ for s in v.clone() {
+ if let Some((stem, ext)) = s.rsplit_once('.') {
+ if !ext.contains('/') {
+ v.push(stem.into());
+ }
+ }
+ // Compound .dat151.rel and friends: also permit replacing the whole suffix.
+ if let Some((stem, ext)) = s.rsplit_once(".dat") {
+ if ext.ends_with(".rel") {
+ v.push(stem.into());
+ }
+ }
+ }
+ v.retain(|s| !s.is_empty());
+ v.sort();
+ v.dedup();
+ v
+}
+struct Targets {
+ values: Vec,
+ bloom: Vec,
+}
+impl Targets {
+ fn positions(x: u64) -> [usize; 2] {
+ let y = x.wrapping_mul(0x9e3779b97f4a7c15);
+ [(y ^ (y >> 32)) as usize & ((1 << 24) - 1), (y.rotate_left(23) ^ (x >> 19)) as usize & ((1 << 24) - 1)]
+ }
+ fn load(p: &Path) -> Result {
+ let mut values = Vec::new();
+ lines(p, |s| {
+ if !s.is_empty() {
+ values.push(u64::from_str_radix(s, 16)?);
+ if values.len() > 2_000_000 {
+ return Err(bad("target count cap").into());
+ }
+ }
+ Ok(())
+ })?;
+ values.sort_unstable();
+ values.dedup();
+ let mut bloom = vec![0u64; 1 << 18];
+ for &v in &values {
+ for bit in Self::positions(v) {
+ bloom[bit / 64] |= 1 << (bit % 64);
+ }
+ }
+ Ok(Self { values, bloom })
+ }
+ fn has(&self, x: u64) -> bool {
+ Self::positions(x).into_iter().all(|b| self.bloom[b / 64] & (1 << (b % 64)) != 0)
+ && self.values.binary_search(&x).is_ok()
+ }
+}
+struct Hit {
+ h64: u64,
+ h32: u32,
+ m64: bool,
+ m32: bool,
+ candidate: String,
+ source: usize,
+}
+fn main() -> Result<()> {
+ let args: Vec<_> = std::env::args_os().skip(1).collect();
+ if args.len() < 2 {
+ return Err(bad("usage: rpf9_dictionary_attack EXPORT_DIR CANDIDATE_LIST...").into());
+ }
+ let root = Path::new(&args[0]);
+ let sources: Vec = args[1..].iter().map(PathBuf::from).collect();
+ let prefix = root.join("cpu_extensions");
+ fs::create_dir(&prefix)?;
+ let mut sourceout = create(&prefix.join("sources.tsv"))?;
+ writeln!(sourceout, "source_id\tpath")?;
+ let spool = prefix.join("variants.unsorted.tsv");
+ let sorted = prefix.join("variants.sorted.tsv");
+ let mut out = create(&spool)?;
+ let mut input_lines = 0u64;
+ for (id, path) in sources.iter().enumerate() {
+ writeln!(sourceout, "{id}\t{}", path.display())?;
+ let mut n = 0;
+ lines(path, |s| {
+ n += 1;
+ for v in variants(s) {
+ writeln!(out, "{v}\t{id}")?
+ }
+ Ok(())
+ })?;
+ input_lines += n;
+ eprintln!("prepared source {id}: {n} lines");
+ }
+ out.flush()?;
+ drop(out);
+ sourceout.flush()?;
+ if !Command::new("sort")
+ .env("LC_ALL", "C")
+ .args(["-u", "--parallel=1", "-S", "32M", "-T"])
+ .arg(&prefix)
+ .arg("-o")
+ .arg(&sorted)
+ .arg(&spool)
+ .status()?
+ .success()
+ {
+ return Err(bad("disk dedupe failed").into());
+ }
+ fs::remove_file(spool)?;
+ let targets64 = Targets::load(&root.join("name_hashes_unique.txt"))?;
+ let targets32 = Targets::load(&root.join("name_hashes32_unique.txt"))?;
+ // Freeze prior verified entry coverage. Never treat 32-only rows as baseline names.
+ let mut baseline = HashSet::new();
+ let mut baseline_bytes = 0usize;
+ let mut baselines = create(&prefix.join("baseline_sources.txt"))?;
+ for item in fs::read_dir(root)? {
+ let p = item?.path();
+ let n = p.file_name().unwrap().to_string_lossy();
+ if !n.ends_with("matches.tsv") {
+ continue;
+ }
+ let mut header: Vec = vec![];
+ let mut accepted = false;
+ lines(&p, |s| {
+ if header.is_empty() {
+ header = s.split('\t').map(str::to_owned).collect();
+ accepted =
+ header.first().is_some_and(|h| h == "archive") && header.get(1).is_some_and(|h| h == "index");
+ return Ok(());
+ }
+ if !accepted {
+ return Ok(());
+ }
+ let f: Vec<_> = s.split('\t').collect();
+ if let Some(i) = header.iter().position(|h| h == "evidence") {
+ if f.get(i).is_some_and(|s| s.starts_with("32")) {
+ return Ok(());
+ }
+ }
+ if f.len() > 2 {
+ let key = format!("{}\t{}", f[0], f[1]);
+ if baseline.insert(key.clone()) {
+ baseline_bytes += key.len() + 64;
+ if baseline_bytes > 16 * MIB {
+ return Err(bad("baseline memory cap").into());
+ }
+ }
+ }
+ Ok(())
+ })?;
+ if accepted {
+ writeln!(baselines, "{}", p.display())?;
+ }
+ }
+ baselines.flush()?;
+ let mut extensions:Vec="meta xml dat txt rpf ymt ytd ydr ydd yft ybn ycd ytyp ymap ysc awc rel gfx dat151.rel dat54.rel dat10.rel dat15.rel dat16.rel dat22.rel dat149.rel dat150.rel dat151 dat54 dat10 cut pso psin rbf rbf0 yld ypt yvr yed yfd ymap ytyp ycd yclip ynv ynm yhn ycs ymf ybs ysd ypd ybd ydatb ybdr ybdd ybft yvert dds png json ini cfg bin".split_whitespace().map(|s|format!(".{s}")).collect();
+ for pre in ["z", "i", "#"] {
+ for suffix in [
+ "mf", "dr", "ft", "dd", "td", "bn", "bd", "pd", "bs", "sd", "mt", "sc", "cs", "datb", "bdr", "bdd", "bft",
+ "vert",
+ ] {
+ extensions.push(format!(".{pre}{suffix}"));
+ }
+ }
+ extensions.sort();
+ extensions.dedup();
+ extensions.insert(0, String::new());
+ let mut exts = create(&prefix.join("extensions.txt"))?;
+ for e in &extensions {
+ writeln!(exts, "{e}")?
+ }
+ exts.flush()?;
+ let mut matches = create(&prefix.join("matches.tsv"))?;
+ writeln!(matches, "hash64\thash32\tmatched64\tmatched32\tcandidate\tsource_id")?;
+ let mut hits = Vec::new();
+ let mut hit_bytes = 0usize;
+ let mut trials = 0u64;
+ let mut bases = 0u64;
+ lines(&sorted, |s| {
+ let (base, source) = s.rsplit_once('\t').ok_or_else(|| bad("invalid spool"))?;
+ let source: usize = source.parse()?;
+ bases += 1;
+ let mut candidate = String::with_capacity(base.len() + 24);
+ for ext in &extensions {
+ candidate.clear();
+ candidate.push_str(base);
+ candidate.push_str(ext);
+ let h64 = name_hash(&candidate);
+ let h32 = hash32(&candidate);
+ trials += 1;
+ let m64 = targets64.has(h64);
+ let m32 = targets32.has(u64::from(h32));
+ if m64 || m32 {
+ hit_bytes += candidate.len() + 64;
+ if hit_bytes > 32 * MIB {
+ return Err(bad("match memory cap; partial evidence retained").into());
+ }
+ writeln!(matches, "{h64:016x}\t{h32:08x}\t{m64}\t{m32}\t{candidate}\t{source}")?;
+ hits.push(Hit { h64, h32, m64, m32, candidate: candidate.clone(), source });
+ }
+ }
+ if bases % 100_000 == 0 {
+ eprintln!("bases={bases} trials={trials} hits={}", hits.len());
+ }
+ Ok(())
+ })?;
+ matches.flush()?;
+ // Match records are bounded; sort indexes, not copies of candidate strings.
+ let mut by64: Vec<_> = (0..hits.len()).filter(|i| hits[*i].m64).collect();
+ by64.sort_unstable_by_key(|i| hits[*i].h64);
+ let mut by32: Vec<_> = (0..hits.len()).filter(|i| hits[*i].m32).collect();
+ by32.sort_unstable_by_key(|i| hits[*i].h32);
+ let mut rows = create(&prefix.join("entry_matches.tsv"))?;
+ writeln!(rows, "archive\tindex\thash64\thash32\tevidence\tcandidate\tsource_id\tnew_verified_entry")?;
+ let (mut entries64, mut entriesboth, mut only32, mut new64) = (0u64, 0u64, 0u64, 0u64);
+ let mut first = true;
+ lines(&root.join("entries.tsv"), |s| {
+ if first {
+ first = false;
+ return Ok(());
+ }
+ let f: Vec<_> = s.split('\t').collect();
+ if f.len() < 4 {
+ return Err(bad("entry row fields").into());
+ }
+ let h64 = u64::from_str_radix(f[2], 16).ok();
+ let h32 = u32::from_str_radix(f[3], 16).ok();
+ let mut found64 = false;
+ let mut both = false;
+ let mut found32 = false;
+ let key = format!("{}\t{}", f[0], f[1]);
+ let new = !baseline.contains(&key);
+ if let Some(h) = h64 {
+ let start = by64.partition_point(|i| hits[*i].h64 < h);
+ for &i in by64[start..].iter().take_while(|i| hits[**i].h64 == h) {
+ let m = &hits[i];
+ let confirmed = h32 == Some(m.h32);
+ found64 = true;
+ both |= confirmed;
+ writeln!(
+ rows,
+ "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{new}",
+ f[0],
+ f[1],
+ f[2],
+ f[3],
+ if confirmed { "64+32" } else { "64" },
+ m.candidate,
+ m.source
+ )?;
+ }
+ }
+ if let Some(h) = h32 {
+ let start = by32.partition_point(|i| hits[*i].h32 < h);
+ for &i in by32[start..].iter().take_while(|i| hits[**i].h32 == h) {
+ let m = &hits[i];
+ if h64 == Some(m.h64) {
+ continue;
+ }
+ found32 = true;
+ writeln!(
+ rows,
+ "{}\t{}\t{}\t{}\t32-only-unverified\t{}\t{}\tfalse",
+ f[0], f[1], f[2], f[3], m.candidate, m.source
+ )?;
+ }
+ }
+ entries64 += u64::from(found64);
+ entriesboth += u64::from(both);
+ only32 += u64::from(found32 && !found64);
+ new64 += u64::from(found64 && new);
+ Ok(())
+ })?;
+ rows.flush()?;
+ let unique64 = by64.iter().map(|i| hits[*i].h64).collect::>().len();
+ let unique32 = by32.iter().map(|i| hits[*i].h32).collect::>().len();
+ let summary = format!(
+ "{{\"input_lines\":{input_lines},\"base_source_pairs\":{bases},\"extensions_including_empty\":{},\"trials\":{trials},\"matched_hashes64\":{unique64},\"matched_hashes32\":{unique32},\"entries64\":{entries64},\"entries_both\":{entriesboth},\"entries32_only_unverified\":{only32},\"new_entries64\":{new64},\"baseline_verified_entries\":{}}}",
+ extensions.len(),
+ baseline.len()
+ );
+ writeln!(create(&prefix.join("summary.json"))?, "{summary}")?;
+ eprintln!("{summary}");
+ Ok(())
+}
diff --git a/crates/rage-rpf/examples/rpf9_hash32_export.rs b/crates/rage-rpf/examples/rpf9_hash32_export.rs
new file mode 100644
index 0000000..fecfdad
--- /dev/null
+++ b/crates/rage-rpf/examples/rpf9_hash32_export.rs
@@ -0,0 +1,40 @@
+//! Add the separate 32-bit lookup column to a previous recursive inventory.
+use rage_rpf::{rpf9::Archive, rpf9_exe::extract_scarlett_1_0_2_1};
+use std::{
+ fs::File,
+ io::{BufRead, BufReader, BufWriter, Write},
+ path::PathBuf,
+};
+fn main() -> Result<(), Box> {
+ let args: Vec<_> = std::env::args_os().skip(1).collect();
+ if args.len() != 3 {
+ return Err("usage: ROOT EXE EXPORT_DIRECTORY".into());
+ }
+ let root = PathBuf::from(&args[0]);
+ let dir = PathBuf::from(&args[2]);
+ let keys = extract_scarlett_1_0_2_1(&PathBuf::from(&args[1]))?;
+ let mut out = BufWriter::new(File::options().write(true).create_new(true).open(dir.join("lookup32.tsv"))?);
+ let mut hashes =
+ BufWriter::new(File::options().write(true).create_new(true).open(dir.join("name_hashes32_all.txt"))?);
+ writeln!(out, "archive\tindex\tname_hash_32")?;
+ let (mut count, mut present) = (0u64, 0u64);
+ for line in BufReader::new(File::open(dir.join("archives.tsv"))?).lines().skip(1) {
+ let line = line?;
+ let parts: Vec<_> = line.split('\t').collect();
+ let path = root.join(parts[0].split('!').next().ok_or("missing path")?);
+ let archive = Archive::open_range(&path, parts[1].parse()?, parts[2].parse()?, &keys)?;
+ for entry in &archive.metadata.entries {
+ count += 1;
+ let value = entry.name_hash32.map(|h| format!("{h:08x}")).unwrap_or_default();
+ if !value.is_empty() {
+ writeln!(hashes, "{value}")?;
+ present += 1;
+ }
+ writeln!(out, "{}\t{}\t{value}", parts[0], entry.index)?;
+ }
+ }
+ out.flush()?;
+ hashes.flush()?;
+ println!("entries={count}, entries_with_32bit_column={present}");
+ Ok(())
+}
diff --git a/crates/rage-rpf/examples/rpf9_hash_export.rs b/crates/rage-rpf/examples/rpf9_hash_export.rs
new file mode 100644
index 0000000..47d0eb8
--- /dev/null
+++ b/crates/rage-rpf/examples/rpf9_hash_export.rs
@@ -0,0 +1,136 @@
+//! Streaming metadata inventory. Usage: ROOT EXE NEW_OUTPUT_DIRECTORY
+use rage_rpf::{rpf9::Archive, rpf9_exe::extract_scarlett_1_0_2_1};
+use std::{
+ fs::{self, File},
+ io::{BufWriter, Read, Seek, SeekFrom, Write},
+ path::PathBuf,
+};
+
+fn main() -> Result<(), Box> {
+ let args: Vec<_> = std::env::args_os().skip(1).collect();
+ if args.len() != 3 {
+ return Err("usage: rpf9_hash_export ROOT EXE NEW_OUTPUT_DIRECTORY".into());
+ }
+ let root = PathBuf::from(&args[0]);
+ let output = PathBuf::from(&args[2]);
+ let keys = extract_scarlett_1_0_2_1(&PathBuf::from(&args[1]))?;
+ fs::create_dir(&output)?;
+ let mut entries = BufWriter::new(File::create(output.join("entries.tsv"))?);
+ let mut archives = BufWriter::new(File::create(output.join("archives.tsv"))?);
+ let mut failures = BufWriter::new(File::create(output.join("errors.tsv"))?);
+ let mut names = BufWriter::new(File::create(output.join("name_hashes_all.txt"))?);
+ let mut ids = BufWriter::new(File::create(output.join("opaque_ids_all.txt"))?);
+ writeln!(
+ entries,
+ "archive\tindex\tname_hash_64\topaque_id_64\tphysical_offset\tstored_size\tdecoded_size\tresource\ttransformed\tnested_rpf9"
+ )?;
+ writeln!(archives, "archive\tphysical_base\tarchive_size\tentries\tmetadata_bytes")?;
+ writeln!(failures, "archive\terror")?;
+ let mut directories = vec![root.clone()];
+ let mut roots = Vec::new();
+ while let Some(dir) = directories.pop() {
+ for item in fs::read_dir(dir)? {
+ let item = item?;
+ let path = item.path();
+ let kind = item.file_type()?;
+ if kind.is_dir() && (item.file_name() == "pack" || path.starts_with(root.join("pack"))) {
+ directories.push(path);
+ } else if kind.is_file() && path.extension().is_some_and(|e| e == "rpf") {
+ roots.push(path);
+ }
+ }
+ }
+ roots.sort();
+ let root_count = roots.len();
+ let mut pending = Vec::new();
+ for path in roots.into_iter().rev() {
+ let label = path.strip_prefix(&root)?.to_string_lossy().into_owned();
+ let size = fs::metadata(&path)?.len();
+ pending.push((path, label, 0u64, size, 0usize));
+ }
+ let (mut archive_count, mut entry_count, mut errors, mut transformed_count, mut detected) =
+ (0u64, 0u64, 0u64, 0u64, 0u64);
+ let mut max_metadata = 0;
+ while let Some((path, label, base, size, depth)) = pending.pop() {
+ let archive = match Archive::open_range(&path, base, size, &keys) {
+ Ok(a) => a,
+ Err(e) => {
+ errors += 1;
+ writeln!(failures, "{label}\t{e}")?;
+ continue;
+ }
+ };
+ archive_count += 1;
+ max_metadata = max_metadata.max(archive.header.metadata_end);
+ writeln!(
+ archives,
+ "{label}\t{base}\t{size}\t{}\t{}",
+ archive.metadata.entries.len(),
+ archive.header.metadata_end
+ )?;
+ let mut source = File::open(&path)?;
+ for entry in &archive.metadata.entries {
+ entry_count += 1;
+ let transformed = entry.crypto.is_some()
+ || entry.blocks.is_some()
+ || entry.extent.as_ref().is_some_and(|e| e.stream_codec != 0);
+ transformed_count += u64::from(transformed);
+ let mut nested = false;
+ let mut offset = String::new();
+ let mut stored = String::new();
+ let mut decoded = String::new();
+ if let Some(extent) = &entry.extent {
+ let physical = base.checked_add(extent.offset).ok_or("physical offset overflow")?;
+ offset = physical.to_string();
+ stored = extent.stored_size.to_string();
+ decoded = extent.unpacked_size.to_string();
+ if !transformed && entry.resource_flags.is_none() && extent.stored_size >= 4 {
+ source.seek(SeekFrom::Start(physical))?;
+ let mut magic = [0; 4];
+ source.read_exact(&mut magic)?;
+ nested = magic == *b"9FPR";
+ if nested {
+ detected += 1;
+ let child = format!("{label}!{}", entry.index);
+ if depth >= 16
+ || extent.unpacked_size > extent.stored_size
+ || extent.stored_size - extent.unpacked_size >= 16
+ {
+ errors += 1;
+ writeln!(failures, "{child}\tunsupported nesting depth or stored size")?;
+ } else {
+ pending.push((path.clone(), child, physical, extent.unpacked_size, depth + 1));
+ }
+ }
+ }
+ }
+ let name = entry.name_hash.map(|h| format!("{h:016x}")).unwrap_or_default();
+ if !name.is_empty() {
+ writeln!(names, "{name}")?;
+ }
+ writeln!(ids, "{:016x}", entry.hash)?;
+ writeln!(
+ entries,
+ "{label}\t{}\t{name}\t{:016x}\t{offset}\t{stored}\t{decoded}\t{}\t{transformed}\t{nested}",
+ entry.index,
+ entry.hash,
+ entry.resource_flags.is_some()
+ )?;
+ }
+ if archive_count.is_multiple_of(100) {
+ eprintln!("{archive_count} archives, {entry_count} entries, {errors} errors");
+ }
+ // Archive and all its decoded metadata are dropped before the next one.
+ }
+ entries.flush()?;
+ archives.flush()?;
+ failures.flush()?;
+ names.flush()?;
+ ids.flush()?;
+ let summary = format!(
+ "root_archives={root_count}\nread_archives={archive_count}\nentries={entry_count}\ndetected_nested_archives={detected}\nerrors={errors}\ntransformed_entries_not_probed_for_nested_archives={transformed_count}\nmax_single_metadata_bytes={max_metadata}\n\nCoverage: all entries in readable outer and directly stored nested RPF9 archives.\nTransformed payloads are inventoried but not decoded to discover hidden containers.\nOnly metadata (<=64MiB per archive) and 4-byte direct payload signatures are read.\nHashes are exported as hexadecimal strings. Opaque IDs are not path hashes.\n"
+ );
+ fs::write(output.join("summary.txt"), &summary)?;
+ print!("{summary}");
+ Ok(())
+}
diff --git a/crates/rage-rpf/src/error.rs b/crates/rage-rpf/src/error.rs
index 7c94b4e..ebbc66d 100644
--- a/crates/rage-rpf/src/error.rs
+++ b/crates/rage-rpf/src/error.rs
@@ -29,6 +29,9 @@ pub enum RpfError {
NotFound(String),
#[error("not a file or directory: {0}")]
BadPath(PathBuf),
+ /// A scan that was stopped before it finished.
+ #[error("cancelled")]
+ Cancelled,
/// An edit that cannot be made (with the reason).
#[error("{0}")]
Edit(String),
diff --git a/crates/rage-rpf/src/lib.rs b/crates/rage-rpf/src/lib.rs
index 216a8e0..d182c90 100644
--- a/crates/rage-rpf/src/lib.rs
+++ b/crates/rage-rpf/src/lib.rs
@@ -2,7 +2,7 @@
//!
//! Supports RPF7 (GTA V Legacy and Enhanced, including nested archives),
//! the GTA IV archives (IMG3, RPF2, RPF3) and, with the `rdr2` feature,
-//! RPF8 (RDR2).
+//! RPF8 (RDR2), plus experimental read-only RPF9 inspection for Scarlett.
//!
//! # Licence of the `rdr2` feature
//!
@@ -35,6 +35,8 @@ pub mod rpf8_exe;
pub mod rpf8_keys;
#[cfg(feature = "rdr2")]
pub mod rpf8_names;
+pub mod rpf9;
+pub mod rpf9_exe;
mod toc;
pub mod vfs;
pub mod writer;
@@ -63,4 +65,5 @@ pub use gta4::{Gta4Archive, Gta4Entry, Gta4EntryId, Gta4EntryKind, Gta4Format};
pub use rpf7::{Encryption, Entry, EntryId, EntryKind, Rpf7};
#[cfg(feature = "rdr2")]
pub use rpf8::Rpf8;
+pub use rpf9::Rpf9;
pub use writer::{ArchiveWriter, RawEntry, entry_for, file_entry, resource_entry};
diff --git a/crates/rage-rpf/src/rpf9.rs b/crates/rage-rpf/src/rpf9.rs
new file mode 100644
index 0000000..b844002
--- /dev/null
+++ b/crates/rage-rpf/src/rpf9.rs
@@ -0,0 +1,408 @@
+//! Experimental, read-only support for the RPF9 variant observed on Scarlett.
+//!
+//! Reads the two-stage encrypted metadata and lists entries by their stored
+//! hash. Decoded export supports selective TFIT-CTR and verified block codecs.
+//! Raw export preserves encryption, compression and padding. Candidate path
+//! lists can resolve name hashes; trailer decoding and writing are unsupported.
+
+#[path = "rpf9/archive.rs"]
+mod archive;
+#[path = "rpf9/ctr.rs"]
+mod ctr;
+#[path = "rpf9/names.rs"]
+mod names;
+pub use archive::{Archive, ArchiveEntry, Block, CryptoDescriptor, Extent, Metadata};
+pub use ctr::TfitCtr;
+pub use names::{NameIndex, name_hash};
+
+use std::fs::File;
+use std::io::{Read, Seek, SeekFrom};
+use std::path::Path;
+
+pub const MAGIC: u32 = 0x5250_4639;
+pub const HEADER_SIZE: usize = 0x40;
+pub const FORMAT_CONSTANT: u32 = 0x0004_7A00;
+pub const REGION_CONSTANT: u32 = 0x0000_0150;
+pub const ALIGNMENT: u32 = 0x10;
+pub const KEY_BLOB_MAGIC: u32 = 0x4E3B_9B8E;
+pub const CTR_KEY_BLOB_MAGIC: u32 = 0x2718_CE5D;
+pub const KEY_BLOB_SIZE: usize = 0x10F4;
+pub const FIXED_TABLES_SIZE: usize = 0x5000;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Header {
+ pub metadata_end: u32,
+ pub region_b_offset: u32,
+ pub trailer_size: u32,
+ pub archive_id: u64,
+ pub format_constant: u32,
+ pub region_constant: u32,
+ pub field_20_low: u16,
+ pub region_b_mode: u16,
+ pub entry_count: u32,
+ pub profile_tag: u32,
+ pub index_width: u8,
+ pub byte_2d: u8,
+ pub crypto_profile: u8,
+ pub byte_2f: u8,
+ /// Historical field name: encrypted property suffix length at +0x30.
+ pub alignment: u32,
+ pub reserved: [u8; 12],
+}
+
+impl Header {
+ pub fn parse(bytes: &[u8]) -> Result {
+ if bytes.len() < HEADER_SIZE {
+ return Err(Rpf9Error::TruncatedHeader(bytes.len()));
+ }
+ let magic = u32_at(bytes, 0).expect("header length checked");
+ if magic != MAGIC {
+ return Err(Rpf9Error::BadMagic(magic));
+ }
+ let packed_20 = u32_at(bytes, 0x20).expect("header length checked");
+ let packed_2c = u32_at(bytes, 0x2C).expect("header length checked");
+ Ok(Self {
+ metadata_end: u32_at(bytes, 0x04).expect("header length checked"),
+ region_b_offset: u32_at(bytes, 0x08).expect("header length checked"),
+ trailer_size: u32_at(bytes, 0x0C).expect("header length checked"),
+ archive_id: u64_at(bytes, 0x10).expect("header length checked"),
+ format_constant: u32_at(bytes, 0x18).expect("header length checked"),
+ region_constant: u32_at(bytes, 0x1C).expect("header length checked"),
+ field_20_low: packed_20 as u16,
+ region_b_mode: (packed_20 >> 16) as u16,
+ entry_count: u32_at(bytes, 0x24).expect("header length checked"),
+ profile_tag: u32_at(bytes, 0x28).expect("header length checked"),
+ index_width: packed_2c as u8,
+ byte_2d: (packed_2c >> 8) as u8,
+ crypto_profile: (packed_2c >> 16) as u8,
+ byte_2f: (packed_2c >> 24) as u8,
+ alignment: u32_at(bytes, 0x30).expect("header length checked"),
+ reserved: bytes[0x34..0x40].try_into().expect("header length checked"),
+ })
+ }
+
+ pub fn region_a_size(self) -> Option {
+ self.region_b_offset.checked_sub(HEADER_SIZE as u32)
+ }
+
+ pub fn region_b_size(self) -> Option {
+ self.metadata_end.checked_sub(self.region_b_offset)
+ }
+
+ pub fn predicted_region_b_size(self) -> Option {
+ let raw = self.entry_count.checked_mul(8 + u32::from(self.index_width))?;
+ raw.checked_add(ALIGNMENT - 1).map(|n| n & !(ALIGNMENT - 1))
+ }
+
+ /// The first encrypted span is `align16(u16(header + 0x1a) * 8)`.
+ pub fn first_metadata_span_size(self) -> usize {
+ let records = (self.format_constant >> 16) as u16;
+ align_up(u32::from(records) * 8, ALIGNMENT) as usize
+ }
+
+ pub fn validation_errors(self, file_size: u64) -> Vec {
+ let mut errors = Vec::new();
+ if self.format_constant & 0xffff != FORMAT_CONSTANT & 0xffff
+ || !(1..=64).contains(&(self.format_constant >> 16))
+ {
+ errors.push("unsupported property directory signature/count".to_owned());
+ }
+ // +0x30 is an encrypted property suffix size, not an alignment.
+ if self.alignment > self.region_constant
+ || !self.alignment.is_multiple_of(16)
+ || !self.region_constant.is_multiple_of(16)
+ {
+ errors.push("invalid encrypted property-area sizes".to_owned());
+ }
+ if self.reserved.iter().any(|&b| b != 0) {
+ errors.push("reserved bytes +0x34..+0x3f are non-zero".to_owned());
+ }
+ if !(HEADER_SIZE as u32 <= self.region_b_offset
+ && self.region_b_offset <= self.metadata_end
+ && u64::from(self.metadata_end) <= file_size)
+ {
+ errors.push("expected 0x40 <= region_b_offset <= metadata_end <= file size".to_owned());
+ }
+ if !self.metadata_end.is_multiple_of(ALIGNMENT)
+ || !self.region_b_offset.is_multiple_of(ALIGNMENT)
+ || !self.trailer_size.is_multiple_of(ALIGNMENT)
+ {
+ errors.push("metadata offsets or trailer size are not 16-byte aligned".to_owned());
+ }
+ if u64::from(self.trailer_size) > file_size.saturating_sub(u64::from(self.metadata_end)) {
+ errors.push("trailer overlaps the metadata region".to_owned());
+ }
+ if !matches!(self.index_width, 1 | 2 | 4) {
+ errors.push(format!("unexpected index width {}", self.index_width));
+ }
+ let expected_width = if self.entry_count <= 255 {
+ 1
+ } else if self.entry_count <= 65535 {
+ 2
+ } else {
+ 4
+ };
+ if self.index_width != expected_width {
+ errors
+ .push(format!("index width {} disagrees with count-derived width {expected_width}", self.index_width));
+ }
+ if u64::from(self.region_b_offset) < (HEADER_SIZE + self.first_metadata_span_size()) as u64 {
+ errors.push("first metadata span exceeds region A".to_owned());
+ }
+ if self.region_b_mode == 1 && self.region_b_size() != self.predicted_region_b_size() {
+ errors.push(format!(
+ "compact region B has size {:?}, predicted {:?}",
+ self.region_b_size(),
+ self.predicted_region_b_size()
+ ));
+ }
+ errors
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum Rpf9Error {
+ #[error("RPF9 header is truncated ({0} bytes, expected at least {HEADER_SIZE})")]
+ TruncatedHeader(usize),
+ #[error("not an RPF9 archive (magic {0:#010x})")]
+ BadMagic(u32),
+ #[error("invalid RPF9 header: {0}")]
+ InvalidHeader(String),
+ #[error("invalid RPF9 TFIT material: {0}")]
+ InvalidMaterial(String),
+ #[error("TFIT-CBC input length {0} is not a multiple of 16")]
+ InvalidCiphertextLength(usize),
+ #[error("unsupported RPF9 feature: {0}")]
+ Unsupported(String),
+ #[error("invalid RPF9 metadata: {0}")]
+ InvalidMetadata(String),
+ #[error("I/O error: {0}")]
+ Io(#[from] std::io::Error),
+}
+
+#[derive(Clone)]
+pub struct CryptoMaterial {
+ key_blob: Vec,
+ fixed_tables: Vec,
+ iv: [u8; 16],
+}
+
+impl CryptoMaterial {
+ pub(crate) fn from_parts(key_blob: Vec, fixed_tables: Vec, iv: [u8; 16]) -> Result {
+ Self::from_parts_with_magic(key_blob, fixed_tables, iv, KEY_BLOB_MAGIC)
+ }
+
+ pub(crate) fn from_parts_with_magic(
+ key_blob: Vec,
+ fixed_tables: Vec,
+ iv: [u8; 16],
+ magic: u32,
+ ) -> Result {
+ if key_blob.len() != KEY_BLOB_SIZE {
+ return Err(Rpf9Error::InvalidMaterial(format!(
+ "key blob is {:#x} bytes, expected {KEY_BLOB_SIZE:#x}",
+ key_blob.len()
+ )));
+ }
+ if u32_at(&key_blob, 0) != Some(magic) {
+ return Err(Rpf9Error::InvalidMaterial("bad key-blob magic".to_owned()));
+ }
+ if fixed_tables.len() != FIXED_TABLES_SIZE {
+ return Err(Rpf9Error::InvalidMaterial(format!(
+ "fixed tables are {:#x} bytes, expected {FIXED_TABLES_SIZE:#x}",
+ fixed_tables.len()
+ )));
+ }
+ Ok(Self { key_blob, fixed_tables, iv })
+ }
+
+ pub fn decryptor(self) -> TfitDecryptor {
+ TfitDecryptor { material: self }
+ }
+}
+
+pub struct TfitDecryptor {
+ material: CryptoMaterial,
+}
+
+impl TfitDecryptor {
+ const FINAL_PERMUTATION: [usize; 16] = [0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3];
+
+ pub fn decrypt_block(&self, block: [u8; 16]) -> [u8; 16] {
+ let key = |i: usize| u32_at(&self.material.key_blob, 4 + i * 4).expect("validated key blob");
+ let initial = &self.material.fixed_tables[..0x1000];
+ let table = |table: usize, byte: u8| {
+ u32_at(&self.material.fixed_tables, 0x1000 + table * 0x400 + usize::from(byte) * 4)
+ .expect("validated fixed tables")
+ };
+ let mut words = [0u32; 4];
+ for (group, word) in words.iter_mut().enumerate() {
+ let mut value = 0u32;
+ for index in 0..4 {
+ let position = group * 4 + index;
+ value = (value << 8) ^ u32::from(initial[position * 256 + usize::from(block[position])]);
+ }
+ *word = value ^ key(group);
+ }
+
+ for round in 1..14 {
+ let data: [u8; 16] = std::array::from_fn(|i| words[i / 4].to_be_bytes()[i % 4]);
+ let at = round * 4;
+ words = [
+ table(0, data[0]) ^ table(7, data[7]) ^ table(10, data[10]) ^ table(13, data[13]) ^ key(at),
+ table(1, data[1]) ^ table(4, data[4]) ^ table(11, data[11]) ^ table(14, data[14]) ^ key(at + 1),
+ table(2, data[2]) ^ table(5, data[5]) ^ table(8, data[8]) ^ table(15, data[15]) ^ key(at + 2),
+ table(3, data[3]) ^ table(6, data[6]) ^ table(9, data[9]) ^ table(12, data[12]) ^ key(at + 3),
+ ];
+ }
+
+ let data: [u8; 16] = std::array::from_fn(|i| words[i / 4].to_be_bytes()[i % 4]);
+ let final_tables = &self.material.key_blob[0xF4..];
+ std::array::from_fn(|position| {
+ let source = Self::FINAL_PERMUTATION[position];
+ final_tables[position * 256 + usize::from(data[source])]
+ })
+ }
+
+ pub fn decrypt_cbc(&self, ciphertext: &[u8]) -> Result, Rpf9Error> {
+ self.decrypt_cbc_with_iv(ciphertext, self.material.iv)
+ }
+
+ pub fn decrypt_cbc_with_iv(&self, ciphertext: &[u8], iv: [u8; 16]) -> Result, Rpf9Error> {
+ if !ciphertext.len().is_multiple_of(16) {
+ return Err(Rpf9Error::InvalidCiphertextLength(ciphertext.len()));
+ }
+ let mut previous = iv;
+ let mut output = Vec::with_capacity(ciphertext.len());
+ for chunk in ciphertext.as_chunks::<16>().0 {
+ let current = *chunk;
+ let decoded = self.decrypt_block(current);
+ output.extend(decoded.iter().zip(previous).map(|(a, b)| a ^ b));
+ previous = current;
+ }
+ Ok(output)
+ }
+}
+
+pub fn read_header(path: &Path) -> Result<(Header, u64), Rpf9Error> {
+ let mut file = File::open(path)?;
+ let file_size = file.metadata()?.len();
+ let mut bytes = Vec::with_capacity(HEADER_SIZE);
+ file.by_ref().take(HEADER_SIZE as u64).read_to_end(&mut bytes)?;
+ let header = Header::parse(&bytes)?;
+ let errors = header.validation_errors(file_size);
+ if !errors.is_empty() {
+ return Err(Rpf9Error::InvalidHeader(errors.join("; ")));
+ }
+ Ok((header, file_size))
+}
+
+pub fn decrypt_first_metadata_span(path: &Path, cipher: &TfitDecryptor) -> Result, Rpf9Error> {
+ let (header, _) = read_header(path)?;
+ if header.crypto_profile != 9 {
+ return Err(Rpf9Error::Unsupported("first-span crypto profile".into()));
+ }
+ let span_size = header.first_metadata_span_size();
+ let mut file = File::open(path)?;
+ file.seek(SeekFrom::Start(HEADER_SIZE as u64))?;
+ let mut encrypted = vec![0u8; span_size];
+ file.read_exact(&mut encrypted)?;
+ cipher.decrypt_cbc(&encrypted)
+}
+
+fn align_up(value: u32, alignment: u32) -> u32 {
+ value.div_ceil(alignment) * alignment
+}
+
+fn u32_at(bytes: &[u8], at: usize) -> Option {
+ Some(u32::from_le_bytes(bytes.get(at..at.checked_add(4)?)?.try_into().ok()?))
+}
+
+fn u64_at(bytes: &[u8], at: usize) -> Option {
+ Some(u64::from_le_bytes(bytes.get(at..at.checked_add(8)?)?.try_into().ok()?))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn header() -> [u8; HEADER_SIZE] {
+ let mut b = [0u8; HEADER_SIZE];
+ b[0..4].copy_from_slice(&MAGIC.to_le_bytes());
+ b[4..8].copy_from_slice(&0x110u32.to_le_bytes());
+ b[8..12].copy_from_slice(&0xF0u32.to_le_bytes());
+ b[12..16].copy_from_slice(&0x40u32.to_le_bytes());
+ b[16..24].copy_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
+ b[24..28].copy_from_slice(&FORMAT_CONSTANT.to_le_bytes());
+ b[28..32].copy_from_slice(®ION_CONSTANT.to_le_bytes());
+ b[32..36].copy_from_slice(&0x0001_1234u32.to_le_bytes());
+ b[36..40].copy_from_slice(&3u32.to_le_bytes());
+ b[40..44].copy_from_slice(&0xAABB_CCDDu32.to_le_bytes());
+ b[44..48].copy_from_slice(&0x0009_0001u32.to_le_bytes());
+ b[48..52].copy_from_slice(&ALIGNMENT.to_le_bytes());
+ b
+ }
+
+ #[test]
+ fn final_round_uses_inverse_row_permutation() {
+ // Synthetic tables: the final state is 00..0f, with identity final
+ // substitutions. This detects the previous forward-row permutation
+ // without embedding any executable or archive material.
+ let mut key = vec![0; KEY_BLOB_SIZE];
+ key[..4].copy_from_slice(&KEY_BLOB_MAGIC.to_le_bytes());
+ for group in 0..4 {
+ let word = u32::from_be_bytes(std::array::from_fn(|i| (group * 4 + i) as u8));
+ key[4 + (52 + group) * 4..8 + (52 + group) * 4].copy_from_slice(&word.to_le_bytes());
+ }
+ for table in 0..16 {
+ for byte in 0..256 {
+ key[0xf4 + table * 256 + byte] = byte as u8;
+ }
+ }
+ let cipher = CryptoMaterial::from_parts(key, vec![0; FIXED_TABLES_SIZE], [0; 16]).unwrap().decryptor();
+ assert_eq!(cipher.decrypt_block([0; 16]), [0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3]);
+ assert!(cipher.decrypt_cbc(&[0; 15]).is_err());
+ let result = cipher.decrypt_cbc(&[0x80; 32]).unwrap();
+ for i in 0..16 {
+ assert_eq!(result[16 + i], result[i] ^ 0x80);
+ }
+ }
+
+ #[test]
+ fn predicted_size_cannot_overflow_on_alignment() {
+ let mut h = Header::parse(&header()).unwrap();
+ h.entry_count = u32::MAX / 9;
+ assert_eq!(h.predicted_region_b_size(), None);
+ }
+
+ #[test]
+ fn parses_and_validates_header() {
+ let bytes = header();
+ let h = Header::parse(&bytes).unwrap();
+ assert_eq!(h.archive_id, 0x1122_3344_5566_7788);
+ assert_eq!(h.region_b_mode, 1);
+ assert_eq!(h.entry_count, 3);
+ assert_eq!(h.index_width, 1);
+ assert_eq!(h.crypto_profile, 9);
+ assert_eq!(h.first_metadata_span_size(), 0x20);
+ assert_eq!(h.region_b_size(), Some(0x20));
+ assert_eq!(h.predicted_region_b_size(), Some(0x20));
+ assert!(h.validation_errors(0x200).is_empty());
+ }
+
+ #[test]
+ fn rejects_short_and_other_formats() {
+ assert!(matches!(Header::parse(&[]), Err(Rpf9Error::TruncatedHeader(0))));
+ let mut bytes = header();
+ bytes[..4].copy_from_slice(b"NOPE");
+ assert!(matches!(Header::parse(&bytes), Err(Rpf9Error::BadMagic(_))));
+ }
+}
+
+#[path = "rpf9/recovery.rs"]
+mod recovery;
+#[path = "rpf9/toc_view.rs"]
+mod toc_view;
+pub use recovery::{
+ Entry, HEADER_LEN, Indexer, Kind, Namer, Names, Rpf9, decode_index, encode_index, set_indexer, set_namer,
+};
diff --git a/crates/rage-rpf/src/rpf9/archive.rs b/crates/rage-rpf/src/rpf9/archive.rs
new file mode 100644
index 0000000..0f7ed20
--- /dev/null
+++ b/crates/rage-rpf/src/rpf9/archive.rs
@@ -0,0 +1,563 @@
+//! Physical metadata views from 0x14087AFF0 / 0x14087B0F0, crypto spans
+//! from 0x140A348A0 / 0x1406BD090 / 0x1408EC360 in the Scarlett reference.
+use super::*;
+use crate::rpf9_exe::ExtractedMaterial;
+use std::io::Write;
+#[path = "read.rs"]
+mod decoded;
+
+const MAX_METADATA: usize = 64 << 20;
+const EXTENT_COLUMN: u64 = 0x33f7_0dfa_f2c5_0989;
+const HASH_COLUMN: u64 = 0xb6f5_bdb2_c66d_a2e9;
+const NAME_HASH_COLUMN: u64 = 0x73bc_b72d_ce74_f11f;
+const NAME_HASH32_COLUMN: u64 = 0xb707_6b62_45d3_5fb5;
+const RESOURCE_COLUMN: u64 = 0xba18_0afb_232d_1b4b;
+const BLOCK_COLUMN: u64 = 0xe0c1_2d7a_5d48_84c5;
+const CRYPTO_COLUMN: u64 = 0x2860_30a3_58a7_89fb;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Extent {
+ pub offset: u64,
+ /// Stored allocation in bytes, including any trailing padding.
+ pub stored_size: u64,
+ pub unpacked_size: u64,
+ /// Uninterpreted upper 24 bits of the packed offset (includes codec).
+ pub flags: u32,
+ pub stream_codec: u8,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CryptoDescriptor {
+ pub selector: u32,
+ pub algorithm: u16,
+ pub iv: [u8; 16],
+ pub range_fields: [u64; 5],
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ArchiveEntry {
+ /// Logical entry index; this is not necessarily its physical record index.
+ pub index: u32,
+ /// Opaque stored identifier, distinct from the path lookup hash.
+ pub hash: u64,
+ /// Normalized path lookup hash; extensions are not always included.
+ pub name_hash: Option,
+ /// Separate Jenkins lookup key used by some entry types.
+ pub name_hash32: Option,
+ /// Some entries use a different storage descriptor; never invent an extent.
+ pub extent: Option,
+ pub has_crypto_descriptor: bool,
+ pub crypto: Option,
+ pub resource_flags: Option<[u32; 2]>,
+ pub blocks: Option>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Block {
+ pub compressed_size: u64,
+ pub stored_size: u64,
+ pub unpacked_size: u64,
+ pub codec: u8,
+}
+impl Block {
+ /// Native packed descriptor decoding at 0x14550DB40.
+ pub fn parse(q: u64, format: u8) -> Result {
+ let (stored, padding, unpacked, codec) = match format {
+ 2 => ((q >> 28) & 0x0fff_fff0, (q >> 58) & 15, (q << 4) & 0x0fff_fff0, q >> 62),
+ 3 => {
+ let actual = 0x10000 - ((q >> 16) & 0xffff);
+ let pad = (q >> 16) & 15;
+ (actual + pad, pad, 0x10000 - (q & 0xffff), (q >> 60) & 3)
+ }
+ 4 => ((q >> 24) & 0x0fff_fff0, (q >> 52) & 15, q & 0x0fff_ffff, (q >> 56) & 3),
+ _ => return Err(Rpf9Error::Unsupported(format!("packed block format {format}"))),
+ };
+ let compressed_size = stored.checked_sub(padding).ok_or_else(|| invalid("block padding exceeds size"))?;
+ if compressed_size == 0 || unpacked == 0 {
+ return Err(invalid("empty compressed block"));
+ }
+ Ok(Self { compressed_size, stored_size: stored, unpacked_size: unpacked, codec: codec as u8 })
+ }
+}
+
+#[derive(Debug)]
+pub struct Metadata {
+ pub entries: Vec,
+ pub key_selector: u32,
+}
+
+pub struct Archive {
+ file: File,
+ path: std::path::PathBuf,
+ pub base_offset: u64,
+ depth: u8,
+ pub header: Header,
+ pub metadata: Metadata,
+}
+
+fn invalid(message: &str) -> Rpf9Error {
+ Rpf9Error::InvalidMetadata(message.to_owned())
+}
+
+fn aligned(n: usize, alignment: usize) -> Result {
+ n.checked_add(alignment - 1).map(|n| n & !(alignment - 1)).ok_or_else(|| invalid("alignment overflow"))
+}
+
+fn slice(bytes: &[u8], at: usize, len: usize) -> Result<&[u8], Rpf9Error> {
+ bytes
+ .get(at..at.checked_add(len).ok_or_else(|| invalid("range overflow"))?)
+ .ok_or_else(|| invalid("metadata range out of bounds"))
+}
+
+#[derive(Debug)]
+struct Column {
+ hash: u64,
+ count: usize,
+ offset: usize,
+ stride: usize,
+ external: bool,
+}
+
+impl Metadata {
+ /// Parses already-decrypted physical views. Kept separate so malformed
+ /// metadata can be tested without distributing game keys or ciphertext.
+ pub fn from_decrypted(header: Header, file_size: u64, a: &[u8], b: &[u8]) -> Result {
+ let errors = header.validation_errors(file_size);
+ if !errors.is_empty() {
+ return Err(Rpf9Error::InvalidHeader(errors.join("; ")));
+ }
+ if header.byte_2d != 0x0f {
+ return Err(Rpf9Error::Unsupported("metadata flags (expected 0x0f)".into()));
+ }
+ let count = header.entry_count as usize;
+ let columns = usize::from(header.field_20_low);
+ if count > 1_000_000 || !(1..=64).contains(&columns) || a.len() > MAX_METADATA || b.len() > MAX_METADATA {
+ return Err(invalid("metadata exceeds reader limits"));
+ }
+ let external = usize::from(header.region_b_mode);
+ if external == 0 || external > columns {
+ return Err(invalid("external column count"));
+ }
+ let internal = columns - external;
+ // The inner cipher also covers H[0x30] bytes of property values.
+ let column_start = header.alignment as usize;
+ let index_start = column_start + columns * 24;
+ let row_size = internal * usize::from(header.index_width);
+ let data_start = aligned(index_start + row_size * count, 8)?;
+ slice(a, 0, data_start)?;
+ let b_data = aligned(count * external * usize::from(header.index_width), 8)?;
+ slice(b, 0, b_data)?;
+ let mut parsed = Vec::with_capacity(columns);
+ let mut column_hashes = std::collections::HashSet::new();
+ for i in 0..columns {
+ let record = slice(a, column_start + i * 24, 24)?;
+ let stride_flags = u32_at(record, 16).unwrap();
+ let column = Column {
+ hash: u64_at(record, 0).unwrap(),
+ count: u32_at(record, 8).unwrap() as usize,
+ offset: u32_at(record, 12).unwrap() as usize,
+ stride: (stride_flags & 0xffff) as usize,
+ external: stride_flags >> 16 == 1,
+ };
+ if stride_flags >> 16 > 1 || column.external != (i >= internal) || u32_at(record, 20) != Some(0) {
+ return Err(Rpf9Error::Unsupported("column storage layout".into()));
+ }
+ if !column_hashes.insert(column.hash) {
+ return Err(invalid("duplicate column hash"));
+ }
+ if column.stride == 0 || column.count > 1_000_000 {
+ return Err(invalid("invalid column size"));
+ }
+ let (bytes, start) = if column.external { (b, b_data) } else { (a, data_start) };
+ let length = column.count.checked_mul(column.stride).ok_or_else(|| invalid("column size overflow"))?;
+ let at = start.checked_add(column.offset).ok_or_else(|| invalid("column offset overflow"))?;
+ slice(bytes, at, length)?;
+ parsed.push(column);
+ }
+ let find = |hash| -> Result {
+ let matches: Vec<_> = parsed.iter().enumerate().filter(|(_, c)| c.hash == hash).map(|(i, _)| i).collect();
+ if matches.len() != 1 {
+ return Err(invalid("missing or duplicate required column"));
+ }
+ Ok(matches[0])
+ };
+ let extent_column = parsed.iter().position(|c| c.hash == EXTENT_COLUMN);
+ let hash_column = find(HASH_COLUMN)?;
+ if extent_column.is_some_and(|i| parsed[i].stride != 24) || parsed[hash_column].stride != 8 {
+ return Err(invalid("unexpected extent/hash record size"));
+ }
+ let mut entries = Vec::with_capacity(count);
+ let mut block_cache = std::collections::HashMap::new();
+ let mut total_blocks = 0usize;
+ for entry in 0..count {
+ let mut extent = None;
+ let mut hash = None;
+ let mut name_hash = None;
+ let mut name_hash32 = None;
+ let mut has_crypto_descriptor = false;
+ let mut crypto = None;
+ let mut resource_flags = None;
+ let mut resource_extent = None;
+ let mut blocks: Option> = None;
+ for (i, col) in parsed.iter().enumerate() {
+ let (indices, at) = if col.external {
+ (b, (entry * external + i - internal) * usize::from(header.index_width))
+ } else {
+ (a, index_start + entry * row_size + i * usize::from(header.index_width))
+ };
+ let (index, missing) = match header.index_width {
+ 1 => (usize::from(slice(indices, at, 1)?[0]), 0xff),
+ 2 => (usize::from(u16::from_le_bytes(slice(indices, at, 2)?.try_into().unwrap())), 0xffff),
+ 4 => (u32_at(slice(indices, at, 4)?, 0).unwrap() as usize, u32::MAX as usize),
+ _ => return Err(invalid("unsupported index width")),
+ };
+ if index == missing {
+ continue;
+ }
+ if index >= col.count {
+ return Err(invalid("column index out of bounds"));
+ }
+ let (bytes, start) = if col.external { (b, b_data) } else { (a, data_start) };
+ let record = slice(bytes, start + col.offset + index * col.stride, col.stride)?;
+ if col.hash == NAME_HASH_COLUMN {
+ if record.len() != 8 {
+ return Err(invalid("name hash record size"));
+ }
+ name_hash = u64_at(record, 0);
+ }
+ if col.hash == NAME_HASH32_COLUMN {
+ if record.len() != 4 {
+ return Err(invalid("32-bit name hash record size"));
+ }
+ name_hash32 = u32_at(record, 0);
+ }
+ if Some(i) == extent_column {
+ let packed = u64_at(record, 0).unwrap();
+ let offset = (packed & 0xff_ffff_ffff) * 16;
+ let stored_size = (u64_at(record, 8).unwrap() & 0xff_ffff_ffff) * 16;
+ let end = offset.checked_add(stored_size).ok_or_else(|| invalid("payload end overflow"))?;
+ if offset < u64::from(header.metadata_end) || end > file_size - u64::from(header.trailer_size) {
+ return Err(invalid("payload overlaps metadata/trailer or exceeds archive"));
+ }
+ extent = Some(Extent {
+ offset,
+ stored_size,
+ unpacked_size: u64_at(record, 16).unwrap() & 0xfff_ffff_ffff,
+ flags: (packed >> 40) as u32,
+ stream_codec: record[6],
+ });
+ }
+ if col.hash == RESOURCE_COLUMN {
+ if record.len() != 20 {
+ return Err(invalid("resource descriptor size"));
+ }
+ let f0 = u32_at(record, 0).unwrap();
+ let f1 = u32_at(record, 4).unwrap();
+ resource_flags = Some([f0, f1]);
+ resource_extent = Some(Extent {
+ offset: u64::from(u32_at(record, 12).unwrap()) * 16,
+ stored_size: u64::from(u32_at(record, 8).unwrap().wrapping_shl(4)),
+ unpacked_size: u64::from(f0 & 0x7fff_fff0) + u64::from(f1 & 0xffff_fff0),
+ flags: u32_at(record, 16).unwrap(),
+ stream_codec: record[17],
+ });
+ }
+ if col.hash == BLOCK_COLUMN {
+ if record.len() != 8 {
+ return Err(invalid("block-table descriptor layout"));
+ }
+ let record_at = start + col.offset + index * col.stride;
+ if let Some(cached) = block_cache.get(&record_at) {
+ blocks = Some(std::sync::Arc::clone(cached));
+ } else {
+ let table_at = record_at
+ .checked_add(u32_at(record, 0).unwrap() as usize)
+ .ok_or_else(|| invalid("block table overflow"))?;
+ let block_count = usize::from(u16::from_le_bytes(record[4..6].try_into().unwrap()));
+ total_blocks += block_count;
+ if total_blocks > 1_000_000 {
+ return Err(invalid("too many block descriptors"));
+ }
+ let raw = slice(bytes, table_at, block_count * 8)?;
+ let decoded: Vec<_> = raw
+ .as_chunks::<8>()
+ .0
+ .iter()
+ .map(|q| Block::parse(u64_at(q, 0).unwrap(), record[7]))
+ .collect::>()?;
+ let decoded: std::sync::Arc<[Block]> = decoded.into();
+ block_cache.insert(record_at, std::sync::Arc::clone(&decoded));
+ blocks = Some(decoded);
+ }
+ }
+ if i == hash_column {
+ hash = u64_at(record, 0);
+ }
+ if col.hash == CRYPTO_COLUMN {
+ if record.len() != 64 {
+ return Err(invalid("crypto descriptor size"));
+ }
+ has_crypto_descriptor = true;
+ crypto = Some(CryptoDescriptor {
+ selector: u32_at(record, 0).unwrap(),
+ algorithm: u16::from_le_bytes(record[4..6].try_into().unwrap()),
+ iv: record[6..22].try_into().unwrap(),
+ range_fields: std::array::from_fn(|i| u64_at(record, 24 + i * 8).unwrap()),
+ });
+ }
+ }
+ if resource_extent.is_some() {
+ extent = resource_extent;
+ }
+ if let Some(e) = &extent {
+ if e.offset < u64::from(header.metadata_end)
+ || e.offset
+ .checked_add(e.stored_size)
+ .is_none_or(|end| end > file_size - u64::from(header.trailer_size))
+ {
+ return Err(invalid("resource extent outside payload area"));
+ }
+ if let Some(blocks) = &blocks {
+ let stored: u64 = blocks.iter().map(|b| b.stored_size).sum();
+ let unpacked: u64 = blocks.iter().map(|b| b.unpacked_size).sum();
+ let prefix = if resource_flags.is_some() { 16 } else { 0 };
+ if stored.checked_add(prefix) != Some(e.stored_size) || unpacked != e.unpacked_size {
+ return Err(invalid("block totals disagree with extent"));
+ }
+ }
+ }
+ entries.push(ArchiveEntry {
+ index: entry as u32,
+ hash: hash.ok_or_else(|| invalid("entry has no hash"))?,
+ name_hash,
+ name_hash32,
+ extent,
+ has_crypto_descriptor,
+ crypto,
+ resource_flags,
+ blocks,
+ });
+ }
+ Ok(Self { entries, key_selector: 0 })
+ }
+}
+
+impl Archive {
+ pub fn open(path: &Path, keys: &ExtractedMaterial) -> Result {
+ Self::open_range(path, 0, std::fs::metadata(path)?.len(), keys)
+ }
+
+ /// Opens an uncompressed archive stored inside a bounded physical range.
+ pub fn open_range(path: &Path, base_offset: u64, size: u64, keys: &ExtractedMaterial) -> Result {
+ let mut file = File::open(path)?;
+ let physical_size = file.metadata()?.len();
+ if size < HEADER_SIZE as u64 || base_offset.checked_add(size).is_none_or(|end| end > physical_size) {
+ return Err(invalid("archive range outside physical file"));
+ }
+ file.seek(SeekFrom::Start(base_offset))?;
+ let mut bytes = [0u8; HEADER_SIZE];
+ file.read_exact(&mut bytes)?;
+ let header = Header::parse(&bytes)?;
+ let errors = header.validation_errors(size);
+ if !errors.is_empty() {
+ return Err(Rpf9Error::InvalidHeader(errors.join("; ")));
+ }
+ if header.crypto_profile != 9 || header.byte_2d != 0x0f {
+ return Err(Rpf9Error::Unsupported("crypto profile or metadata mode".into()));
+ }
+ let end = header.metadata_end as usize;
+ if end > MAX_METADATA {
+ return Err(invalid("metadata exceeds reader limit"));
+ }
+ let mut head = vec![0u8; end];
+ head[..HEADER_SIZE].copy_from_slice(&bytes);
+ file.read_exact(&mut head[HEADER_SIZE..])?;
+ let first_size = header.first_metadata_span_size();
+ let property_start = HEADER_SIZE + first_size;
+ let property_end = property_start + header.region_constant as usize - header.alignment as usize;
+ let split = header.region_b_offset as usize;
+ if property_end > split {
+ return Err(invalid("property area exceeds region A"));
+ }
+ // Algorithm 0x10 chains both property spans; it does NOT reset the IV
+ // between the descriptor directory and its values (0x1406BD160).
+ let properties =
+ keys.material.clone().decryptor().decrypt_cbc(slice(&head, HEADER_SIZE, property_end - HEADER_SIZE)?)?;
+ let mut descriptor = None;
+ for record in slice(&properties, 0, (header.format_constant >> 16) as usize * 8)?.as_chunks::<8>().0 {
+ if u32_at(record, 0) == Some(1) {
+ if descriptor.is_some() {
+ return Err(invalid("duplicate TOC crypto property"));
+ }
+ let at = first_size + u32_at(record, 4).unwrap() as usize;
+ descriptor = Some(slice(&properties, at, 24)?);
+ }
+ }
+ let descriptor = descriptor.ok_or_else(|| invalid("missing TOC crypto property"))?;
+ if u16::from_le_bytes(descriptor[4..6].try_into().unwrap()) != 0x10 {
+ return Err(Rpf9Error::Unsupported("TOC cipher is not TFIT-CBC".into()));
+ }
+ let selector = u32_at(descriptor, 0).unwrap();
+ let cipher = keys
+ .metadata_keys
+ .get(&selector)
+ .ok_or_else(|| Rpf9Error::Unsupported(format!("metadata key {selector:#x}")))?
+ .clone()
+ .decryptor();
+ let iv = descriptor[6..22].try_into().unwrap();
+ // Each of these calls creates a fresh provider in the reference.
+ let a = cipher.decrypt_cbc_with_iv(slice(&head, property_end, split - property_end)?, iv)?;
+ let b = cipher.decrypt_cbc_with_iv(slice(&head, split, end - split)?, iv)?;
+ let mut metadata = Metadata::from_decrypted(header, size, &a, &b)?;
+ metadata.key_selector = selector;
+ Ok(Self { file, path: path.to_owned(), base_offset, depth: 0, header, metadata })
+ }
+
+ /// Opens a directly stored nested archive without extracting it or allocating
+ /// its payload. Compressed/encrypted containers must be decoded separately.
+ pub fn open_child(&self, index: u32, keys: &ExtractedMaterial) -> Result {
+ if self.depth >= 16 {
+ return Err(invalid("archive nesting limit exceeded"));
+ }
+ let entry = self.metadata.entries.get(index as usize).ok_or_else(|| invalid("entry index out of bounds"))?;
+ let extent = entry.extent.as_ref().ok_or_else(|| Rpf9Error::Unsupported("nested extent type".into()))?;
+ if entry.crypto.is_some()
+ || entry.blocks.is_some()
+ || entry.resource_flags.is_some()
+ || extent.stream_codec != 0
+ || extent.unpacked_size > extent.stored_size
+ || extent.stored_size - extent.unpacked_size >= 16
+ {
+ return Err(Rpf9Error::Unsupported("nested archive is not stored directly".into()));
+ }
+ let mut child = Self::open_range(&self.path, self.base_offset + extent.offset, extent.unpacked_size, keys)?;
+ child.depth = self.depth + 1;
+ Ok(child)
+ }
+
+ /// Copies the stored allocation verbatim. No names are used as paths,
+ /// and no decompression/decryption is implied. The caller owns the writer.
+ pub fn copy_raw(&mut self, index: u32, output: &mut impl Write) -> Result {
+ let entry = self.metadata.entries.get(index as usize).ok_or_else(|| invalid("entry index out of bounds"))?;
+ let extent = entry
+ .extent
+ .as_ref()
+ .ok_or_else(|| Rpf9Error::Unsupported("entry has no supported physical extent".into()))?;
+ self.file.seek(SeekFrom::Start(self.base_offset + extent.offset))?;
+ let copied = std::io::copy(&mut Read::by_ref(&mut self.file).take(extent.stored_size), output)?;
+ if copied != extent.stored_size {
+ return Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof).into());
+ }
+ Ok(copied)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn fixture() -> (Header, Vec, Vec) {
+ let header = Header {
+ metadata_end: 0x260,
+ region_b_offset: 0x240,
+ trailer_size: 0x40,
+ archive_id: 0,
+ format_constant: FORMAT_CONSTANT,
+ region_constant: REGION_CONSTANT,
+ field_20_low: 2,
+ region_b_mode: 1,
+ entry_count: 2,
+ profile_tag: 0,
+ index_width: 1,
+ byte_2d: 0x0f,
+ crypto_profile: 9,
+ byte_2f: 0,
+ alignment: 16,
+ reserved: [0; 12],
+ };
+ let mut a = vec![0; 0xa0];
+ for (i, (hash, stride)) in [(EXTENT_COLUMN, 24u32), (HASH_COLUMN, 0x10008)].into_iter().enumerate() {
+ let at = 16 + i * 24;
+ a[at..at + 8].copy_from_slice(&hash.to_le_bytes());
+ a[at + 8..at + 12].copy_from_slice(&2u32.to_le_bytes());
+ a[at + 16..at + 20].copy_from_slice(&stride.to_le_bytes());
+ }
+ // Logical order reverses physical order, both in A and B.
+ a[64..66].copy_from_slice(&[1, 0]);
+ for (i, offset) in [0x30u64, 0x40].into_iter().enumerate() {
+ let at = 72 + i * 24;
+ a[at..at + 8].copy_from_slice(&offset.to_le_bytes());
+ a[at + 8..at + 16].copy_from_slice(&2u64.to_le_bytes());
+ a[at + 16..at + 24].copy_from_slice(&32u64.to_le_bytes());
+ }
+ let mut b = vec![0; 32];
+ b[..2].copy_from_slice(&[1, 0]);
+ b[8..16].copy_from_slice(&0x11u64.to_le_bytes());
+ b[16..24].copy_from_slice(&0x22u64.to_le_bytes());
+ (header, a, b)
+ }
+
+ #[test]
+ fn logical_indices_select_physical_records() {
+ let (h, a, b) = fixture();
+ let m = Metadata::from_decrypted(h, 0x500, &a, &b).unwrap();
+ assert_eq!(m.entries[0].hash, 0x22);
+ assert_eq!(m.entries[0].extent.as_ref().unwrap().offset, 0x400);
+ assert_eq!(m.entries[1].hash, 0x11);
+ assert_eq!(m.entries[1].extent.as_ref().unwrap().offset, 0x300);
+ }
+
+ #[test]
+ fn multiple_external_columns_use_their_own_row_stride() {
+ let (mut h, old_a, _) = fixture();
+ h.field_20_low = 3;
+ h.region_b_mode = 2;
+ h.alignment = 32;
+ let mut a = vec![0; 192];
+ a[32..56].copy_from_slice(&old_a[16..40]);
+ a[56..64].copy_from_slice(&0x1234u64.to_le_bytes());
+ a[64..68].copy_from_slice(&2u32.to_le_bytes());
+ a[72..76].copy_from_slice(&0x10004u32.to_le_bytes());
+ a[80..104].copy_from_slice(&old_a[40..64]);
+ a[92..96].copy_from_slice(&8u32.to_le_bytes());
+ a[104..106].copy_from_slice(&[1, 0]);
+ a[112..160].copy_from_slice(&old_a[72..120]);
+ let mut b = vec![0; 32];
+ b[..4].copy_from_slice(&[0, 1, 1, 0]);
+ b[16..24].copy_from_slice(&0x11u64.to_le_bytes());
+ b[24..32].copy_from_slice(&0x22u64.to_le_bytes());
+ let metadata = Metadata::from_decrypted(h, 0x500, &a, &b).unwrap();
+ assert_eq!(metadata.entries[0].hash, 0x22);
+ assert_eq!(metadata.entries[1].hash, 0x11);
+ assert_eq!(metadata.entries[0].extent.as_ref().unwrap().offset, 0x400);
+ }
+
+ #[test]
+ fn missing_extent_is_not_invented() {
+ let (h, mut a, b) = fixture();
+ a[64] = 0xff;
+ let m = Metadata::from_decrypted(h, 0x500, &a, &b).unwrap();
+ assert!(m.entries[0].extent.is_none());
+ }
+
+ #[test]
+ fn rejects_corrupt_indices_sizes_and_ranges() {
+ let (h, a, b) = fixture();
+ let mut bad = a.clone();
+ bad[64] = 2;
+ assert!(Metadata::from_decrypted(h, 0x500, &bad, &b).is_err());
+ let mut bad = a.clone();
+ bad[24..28].copy_from_slice(&u32::MAX.to_le_bytes());
+ assert!(Metadata::from_decrypted(h, 0x500, &bad, &b).is_err());
+ let mut bad = a.clone();
+ bad[80..88].copy_from_slice(&u64::MAX.to_le_bytes());
+ assert!(Metadata::from_decrypted(h, 0x500, &bad, &b).is_err());
+ assert!(Metadata::from_decrypted(h, 0x400, &a, &b).is_err());
+ for end in 0..120 {
+ assert!(Metadata::from_decrypted(h, 0x500, &a[..end], &b).is_err());
+ }
+ for end in 0..24 {
+ assert!(Metadata::from_decrypted(h, 0x500, &a, &b[..end]).is_err());
+ }
+ }
+}
diff --git a/crates/rage-rpf/src/rpf9/ctr.rs b/crates/rage-rpf/src/rpf9/ctr.rs
new file mode 100644
index 0000000..a44a5d0
--- /dev/null
+++ b/crates/rage-rpf/src/rpf9/ctr.rs
@@ -0,0 +1,99 @@
+//! TFIT-CTR: reference block 0x1456437C0, stream 0x1455DC010,
+//! context loader 0x1455DC890. The counter is a big-endian 128-bit integer.
+use super::*;
+
+pub struct TfitCtr {
+ material: CryptoMaterial,
+ counter: u128,
+ initial_counter: u128,
+ stream: [u8; 16],
+ used: usize,
+}
+impl TfitCtr {
+ pub fn new(material: CryptoMaterial, iv: [u8; 16]) -> Result {
+ if u32_at(&material.key_blob, 0) != Some(CTR_KEY_BLOB_MAGIC) {
+ return Err(Rpf9Error::InvalidMaterial("CTR key-blob magic".into()));
+ }
+ Ok(Self {
+ material,
+ counter: u128::from_be_bytes(iv),
+ initial_counter: u128::from_be_bytes(iv),
+ stream: [0; 16],
+ used: 16,
+ })
+ }
+
+ fn block(&self, input: [u8; 16]) -> [u8; 16] {
+ let key = |i| u32_at(&self.material.key_blob, 4 + i * 4).expect("validated key");
+ let mut words: [u32; 4] = std::array::from_fn(|g| {
+ let bytes =
+ std::array::from_fn(|i| self.material.fixed_tables[(g * 4 + i) * 256 + usize::from(input[g * 4 + i])]);
+ u32::from_be_bytes(bytes) ^ key(g)
+ });
+ let groups = [[0, 5, 10, 15], [3, 4, 9, 14], [2, 7, 8, 13], [1, 6, 11, 12]];
+ for round in 1..14 {
+ let bytes: [u8; 16] = std::array::from_fn(|i| words[i / 4].to_be_bytes()[i % 4]);
+ words = std::array::from_fn(|g| {
+ groups[g].iter().fold(key(round * 4 + g), |word, &t| {
+ word ^ u32_at(&self.material.fixed_tables, 0x1000 + t * 0x400 + usize::from(bytes[t]) * 4)
+ .expect("validated tables")
+ })
+ });
+ }
+ let bytes: [u8; 16] = std::array::from_fn(|i| words[i / 4].to_be_bytes()[i % 4]);
+ let permutation = [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11];
+ std::array::from_fn(|i| self.material.key_blob[0xf4 + i * 256 + usize::from(bytes[permutation[i]])])
+ }
+
+ /// Selects an absolute byte position, including the partial counter block.
+ /// The native range wrapper adds position >> 4 to the original IV.
+ pub fn seek(&mut self, position: u64) {
+ self.counter = self.initial_counter.wrapping_add(u128::from(position / 16));
+ self.used = 16;
+ if !position.is_multiple_of(16) {
+ self.stream = self.block(self.counter.to_be_bytes());
+ self.counter = self.counter.wrapping_add(1);
+ self.used = (position % 16) as usize;
+ }
+ }
+
+ /// Applies the keystream in place, retaining partial-block state across calls.
+ pub fn apply(&mut self, bytes: &mut [u8]) {
+ for byte in bytes {
+ if self.used == 16 {
+ self.stream = self.block(self.counter.to_be_bytes());
+ self.counter = self.counter.wrapping_add(1);
+ self.used = 0;
+ }
+ *byte ^= self.stream[self.used];
+ self.used += 1;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn arbitrary_chunks_preserve_ctr_state() {
+ let mut key = vec![0; KEY_BLOB_SIZE];
+ key[..4].copy_from_slice(&CTR_KEY_BLOB_MAGIC.to_le_bytes());
+ for i in 0..16 {
+ for j in 0..256 {
+ key[0xf4 + i * 256 + j] = (i * 17 + j) as u8;
+ }
+ }
+ let material =
+ CryptoMaterial::from_parts_with_magic(key, vec![0; FIXED_TABLES_SIZE], [0; 16], CTR_KEY_BLOB_MAGIC)
+ .unwrap();
+ let mut whole = vec![0x77; 197];
+ TfitCtr::new(material.clone(), [0xff; 16]).unwrap().apply(&mut whole);
+ let mut chunks = vec![0x77; 197];
+ let mut ctr = TfitCtr::new(material, [0xff; 16]).unwrap();
+ for chunk in chunks.chunks_mut(7) {
+ ctr.apply(chunk);
+ }
+ assert_eq!(chunks, whole);
+ assert_ne!(whole, vec![0x77; 197]);
+ }
+}
diff --git a/crates/rage-rpf/src/rpf9/names.rs b/crates/rage-rpf/src/rpf9/names.rs
new file mode 100644
index 0000000..8a83478
--- /dev/null
+++ b/crates/rage-rpf/src/rpf9/names.rs
@@ -0,0 +1,147 @@
+//! Candidate dictionary matching, analogous to the RPF8 name resolver.
+//! Native hash: 0x144F66DE0; ASCII normalization table: 0x1465B23B0.
+//! A match identifies the hashed path, not necessarily its file extension.
+use std::collections::{BTreeSet, HashMap, HashSet};
+use std::io::{self, BufRead, BufReader, Read};
+use std::path::Path;
+
+const C1: u64 = 0x87c3_7b91_1142_53d5;
+const C2: u64 = 0x4cf5_ad43_2745_937f;
+
+fn fmix(mut h: u64) -> u64 {
+ h = (h ^ (h >> 33)).wrapping_mul(0xff51_afd7_ed55_8ccd);
+ h = (h ^ (h >> 33)).wrapping_mul(0xc4ce_b9fe_1a85_ec53);
+ h ^ (h >> 33)
+}
+
+/// Native normalized MurmurHash3-derived low 64 bits, seed zero.
+/// Stops at NUL, folds ASCII case and backslashes. The native finalizer uses
+/// the low byte of the length; this differs from standard Murmur for >=256.
+pub fn name_hash(path: &str) -> u64 {
+ let data: Vec =
+ path.bytes().take_while(|b| *b != 0).map(|b| if b == b'\\' { b'/' } else { b.to_ascii_lowercase() }).collect();
+ let (mut h1, mut h2) = (0u64, 0u64);
+ let (chunks, tail) = data.as_chunks::<16>();
+ for chunk in chunks {
+ let k1 = u64::from_le_bytes(chunk[..8].try_into().unwrap());
+ let k2 = u64::from_le_bytes(chunk[8..].try_into().unwrap());
+ h1 ^= k1.wrapping_mul(C1).rotate_left(31).wrapping_mul(C2);
+ h1 = h1.rotate_left(27).wrapping_add(h2).wrapping_mul(5).wrapping_add(0x52dc_e729);
+ h2 ^= k2.wrapping_mul(C2).rotate_left(33).wrapping_mul(C1);
+ h2 = h2.rotate_left(31).wrapping_add(h1).wrapping_mul(5).wrapping_add(0x3849_5ab5);
+ }
+ let mut last = [0u8; 16];
+ last[..tail.len()].copy_from_slice(tail);
+ if tail.len() > 8 {
+ h2 ^= u64::from_le_bytes(last[8..].try_into().unwrap()).wrapping_mul(C2).rotate_left(33).wrapping_mul(C1);
+ }
+ if !tail.is_empty() {
+ h1 ^= u64::from_le_bytes(last[..8].try_into().unwrap()).wrapping_mul(C1).rotate_left(31).wrapping_mul(C2);
+ }
+ h1 ^= (data.len() & 255) as u64;
+ h2 ^= (data.len() & 255) as u64;
+ h1 = h1.wrapping_add(h2);
+ h2 = h2.wrapping_add(h1);
+ fmix(h1).wrapping_add(fmix(h2))
+}
+
+#[derive(Debug, Default)]
+pub struct NameIndex {
+ // Preserve distinct matches: never silently choose between collisions.
+ names: HashMap>,
+}
+
+impl NameIndex {
+ /// Import a UTF-8 candidate list (one path per line), <=8MiB, streaming.
+ /// Only matching paths are retained. This never scans game payloads.
+ pub fn load_candidates(path: &Path, wanted: &HashSet) -> io::Result {
+ Self::load(path, Some(wanted))
+ }
+
+ pub(crate) fn load_all_candidates(path: &Path) -> io::Result {
+ Self::load(path, None)
+ }
+
+ fn load(path: &Path, wanted: Option<&HashSet>) -> io::Result