Skip to main content

frostbite_formats/
layout.rs

1//! `layout.toc`: the native DB (behind the TOC envelope) that names the superbundles, the install chunks that give the
2//! archives' directories their `persistentIndex`, the initfs and the bundle format. [`read`] types the keys the stock
3//! layout and the 98 layouts of installed mods hold; the tree stays reachable as [`Layout::root`] for the rest
4//! (`layeredInstallChunkFiles`, `meta`, ...).
5//!
6//! Every key below occurs in the stock layout (a measured build 20260929) and in all 98 mod layouts read beside it; no
7//! mod layout holds a key the stock one does not. A key of another type than the one named here is refused.
8
9use crate::db::{self, Node};
10use crate::{Result, bad};
11
12const W: &str = "layout.toc";
13
14/// An install chunk (`installManifest.installChunks[]`): the directory of CAS archives that `persistentIndex` names.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct InstallChunk {
17    /// `id`: a GUID, in the byte order stored.
18    pub id: Option<[u8; 16]>,
19    /// `name`: the directory relative to `Win32`, as stored (`configurations/layout/initialinstallpackage`).
20    pub name: String,
21    /// `installBundle`: the same directory with the platform in front (`Win32/` + `name` in all 16 stock chunks).
22    pub install_bundle: Option<String>,
23    /// `persistentIndex`: the number a file identifier's bits 16..48 name this chunk by.
24    pub persistent_index: Option<u32>,
25    /// `superbundles`: the superbundle names (`Win32/loc/br`) the chunk holds.
26    pub superbundles: Vec<String>,
27    /// `requiredChunks`: the `id`s of the chunks this one needs.
28    pub required_chunks: Vec<[u8; 16]>,
29    /// `alwaysInstalled`.
30    pub always_installed: Option<bool>,
31}
32
33impl InstallChunk {
34    /// The directory of the chunk's archives relative to `Win32`: `name`, else `installBundle` without its `Win32/`.
35    pub fn directory(&self) -> String {
36        if !self.name.is_empty() {
37            return self.name.clone();
38        }
39        self.install_bundle
40            .as_deref()
41            .map(|b| b.strip_prefix("Win32/").unwrap_or(b).to_string())
42            .unwrap_or_default()
43    }
44}
45
46/// An install group (`installManifest.installGroups[]`): a name and the `id`s of its chunks.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct InstallGroup {
49    /// `name`.
50    pub name: String,
51    /// `chunks`: install chunk ids.
52    pub chunks: Vec<[u8; 16]>,
53}
54
55/// A read `layout.toc`.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct Layout {
58    /// The envelope bytes in front of the DB, as stored.
59    pub envelope: Vec<u8>,
60    /// The whole DB tree.
61    pub root: Node,
62    /// The bytes after the tree (none in the measured layouts).
63    pub trailer: Vec<u8>,
64    /// `superBundles[].name`: the superbundles the game loads, as `Win32/globals`; the TOC of each is `<name>.toc` in the
65    /// data folder. In the stock layout, 23 of 24 names have their TOC in `Data` and every TOC there is named.
66    pub super_bundles: Vec<String>,
67    /// `fs`: the initfs files (`initfs_Win32`), which are encrypted.
68    pub fs: Vec<String>,
69    /// `head`: a 32-bit number (625,200 in the stock layout and all mod layouts).
70    pub head: Option<u32>,
71    /// `platform`.
72    pub platform: Option<String>,
73    /// `installManifest.installChunks`, in stored order.
74    pub install_chunks: Vec<InstallChunk>,
75    /// `installManifest.installGroups`.
76    pub install_groups: Vec<InstallGroup>,
77    /// `installManifest.excludedSuperbundles`.
78    pub excluded_superbundles: Vec<String>,
79    /// `installManifest.settings.bundleFormat`: a 64-bit number as stored.
80    pub bundle_format: Option<u64>,
81}
82
83fn err(detail: impl Into<String>) -> crate::Error {
84    bad(W, 0, detail)
85}
86
87fn kind(n: &Node, ty: u8, key: &str) -> Result<()> {
88    if n.ty == ty {
89        Ok(())
90    } else {
91        Err(err(format!("{key}: expected type {ty}, found {}", n.ty)))
92    }
93}
94
95fn text(parent: &Node, key: &str) -> Result<Option<String>> {
96    parent
97        .field(key)
98        .map(|n| kind(n, 7, key).map(|()| n.text()))
99        .transpose()
100}
101
102fn guid(n: &Node, key: &str) -> Result<[u8; 16]> {
103    kind(n, 15, key)?;
104    n.payload
105        .as_slice()
106        .try_into()
107        .map_err(|_| err(format!("{key}: expected 16 bytes")))
108}
109
110fn strings(parent: &Node, key: &str) -> Result<Vec<String>> {
111    let Some(list) = parent.field(key) else {
112        return Ok(Vec::new());
113    };
114    kind(list, 1, key)?;
115    list.children
116        .iter()
117        .map(|c| kind(c, 7, key).map(|()| c.text()))
118        .collect()
119}
120
121fn guids(parent: &Node, key: &str) -> Result<Vec<[u8; 16]>> {
122    let Some(list) = parent.field(key) else {
123        return Ok(Vec::new());
124    };
125    kind(list, 1, key)?;
126    list.children.iter().map(|c| guid(c, key)).collect()
127}
128
129/// Parse a `layout.toc` (envelope included). Refused: an envelope or DB that does not read, and a key of the typed set
130/// that has another type than the stock layout gives it.
131pub fn read(data: &[u8]) -> Result<Layout> {
132    let (envelope, root, trailer) = db::read_file(data)?;
133    let super_bundles = match root.field("superBundles") {
134        None => Vec::new(),
135        Some(list) => {
136            kind(list, 1, "superBundles")?;
137            list.children
138                .iter()
139                .map(|e| text(e, "name")?.ok_or_else(|| err("superBundles: an entry without a name")))
140                .collect::<Result<_>>()?
141        }
142    };
143    let head = match root.field("head") {
144        None => None,
145        Some(n) => Some(n.u32().ok_or_else(|| err("head: expected a 32-bit value"))?),
146    };
147    let manifest = root.field("installManifest");
148    let mut install_chunks = Vec::new();
149    let mut install_groups = Vec::new();
150    let mut excluded_superbundles = Vec::new();
151    let mut bundle_format = None;
152    if let Some(m) = manifest {
153        if let Some(list) = m.field("installChunks") {
154            kind(list, 1, "installChunks")?;
155            for e in &list.children {
156                install_chunks.push(InstallChunk {
157                    id: e.field("id").map(|n| guid(n, "id")).transpose()?,
158                    name: text(e, "name")?.unwrap_or_default(),
159                    install_bundle: text(e, "installBundle")?,
160                    persistent_index: e
161                        .field("persistentIndex")
162                        .map(|n| {
163                            n.u32()
164                                .ok_or_else(|| err("persistentIndex: expected a 32-bit value"))
165                        })
166                        .transpose()?,
167                    superbundles: strings(e, "superbundles")?,
168                    required_chunks: guids(e, "requiredChunks")?,
169                    always_installed: e
170                        .field("alwaysInstalled")
171                        .map(|n| match (n.ty, n.payload.as_slice()) {
172                            (6, &[b]) => Ok(b != 0),
173                            _ => Err(err("alwaysInstalled: expected a boolean")),
174                        })
175                        .transpose()?,
176                });
177            }
178        }
179        if let Some(list) = m.field("installGroups") {
180            kind(list, 1, "installGroups")?;
181            for e in &list.children {
182                install_groups.push(InstallGroup {
183                    name: text(e, "name")?.unwrap_or_default(),
184                    chunks: guids(e, "chunks")?,
185                });
186            }
187        }
188        excluded_superbundles = strings(m, "excludedSuperbundles")?;
189        if let Some(b) = m.field("settings").and_then(|s| s.field("bundleFormat")) {
190            bundle_format = Some(match (b.ty, b.payload.as_slice()) {
191                (9, &[a, b, c, d, e, f, g, h]) => u64::from_le_bytes([a, b, c, d, e, f, g, h]),
192                _ => return Err(err("bundleFormat: expected a 64-bit value")),
193            });
194        }
195    }
196    Ok(Layout {
197        envelope,
198        super_bundles,
199        fs: strings(&root, "fs")?,
200        head,
201        platform: text(&root, "platform")?,
202        install_chunks,
203        install_groups,
204        excluded_superbundles,
205        bundle_format,
206        root,
207        trailer,
208    })
209}
210
211impl Layout {
212    /// The layout written again: the envelope, the tree and the trailer as read ([`db::write_file`]).
213    pub fn write(&self) -> Result<Vec<u8>> {
214        db::write_file(&self.envelope, &self.root, &self.trailer)
215    }
216}