Skip to main content

unbanished_formats/
save.rs

1//! Banished save files (`.sav`): container, game-state stream, and the fields needed to check
2//! world generation. Layout notes are in docs/SAVE-FORMAT-AND-RESTORE.md.
3
4mod events;
5mod map;
6use events::{parse_event_block, skip_rest};
7pub use events::{SavedEvent, SavedEventLog};
8pub use map::{MapCell, MapCells, MapHeights};
9
10use crate::crs::{Reader, Writer};
11use crate::error::{format_err, Error, Result};
12use crate::stream;
13
14/// A save file: its two payloads, expanded. See the [module documentation](self).
15pub struct Save {
16    /// Expanded metadata stream (the first payload; see [`SaveMetadata`]).
17    pub metadata: Vec<u8>,
18    /// Expanded game-state stream (the second payload).
19    pub state: Vec<u8>,
20}
21
22/// The first payload (`SaveLoad::SaveMetaData`): what the load dialog shows. One block at version
23/// 3.
24///
25/// Original: Runtime `0x1800c3d00`.
26#[derive(Debug, Clone, PartialEq)]
27pub struct SaveMetadata {
28    /// The town's name, as the Load dialog shows it.
29    pub name: String,
30    /// The preview picture's width in pixels.
31    pub width: i32,
32    /// The preview picture's height in pixels.
33    pub height: i32,
34    /// `width × height` 4-byte texels (blue, green, red, unused) of the preview.
35    pub image: Vec<u8>,
36    /// From version 3: an unnamed value (2 in the samples), then the active mods.
37    pub value: i32,
38    /// The mods that were on when the town was saved.
39    pub mods: Vec<SavedMod>,
40    /// The strings were UTF-16 (2015 builds).
41    pub wide: bool,
42}
43
44/// A mod active when the game was saved: its name, its `.pkm` file and three values.
45#[derive(Debug, Clone, PartialEq)]
46pub struct SavedMod {
47    /// The mod's name.
48    pub name: String,
49    /// The mod's file name.
50    pub file: String,
51    /// Three values saved with the mod (not identified yet).
52    pub values: [u32; 3],
53}
54
55impl SaveMetadata {
56    /// Read a [`SaveMetadata`] from the bytes of its resource.
57    pub fn parse(data: &[u8]) -> Result<SaveMetadata> {
58        let mut r = Reader::new(data);
59        let mut meta = r.block(|r, version| {
60            let name = r.string()?;
61            let width = r.i32()?;
62            let height = r.i32()?;
63            let image = r
64                .bytes(width.max(0) as usize * height.max(0) as usize * 4)?
65                .to_vec();
66            let (value, mods) = if version > 2 {
67                let value = r.i32()?;
68                let mods = (0..r.count()?)
69                    .map(|_| {
70                        Ok(SavedMod {
71                            name: r.string()?,
72                            file: r.string()?,
73                            values: [r.u32()?, r.u32()?, r.u32()?],
74                        })
75                    })
76                    .collect::<Result<_>>()?;
77                (value, mods)
78            } else {
79                (0, Vec::new())
80            };
81            Ok(SaveMetadata {
82                name,
83                width,
84                height,
85                image,
86                value,
87                mods,
88                wide: false,
89            })
90        })?;
91        meta.wide = r.wide_seen;
92        Ok(meta)
93    }
94
95    /// The block at version 3.
96    pub fn write(&self) -> Vec<u8> {
97        let mut w = Writer::new();
98        w.wide_strings = self.wide;
99        let at = w.begin_block(3);
100        w.string(&self.name);
101        w.i32(self.width);
102        w.i32(self.height);
103        w.bytes(&self.image);
104        w.i32(self.value);
105        w.count(self.mods.len());
106        for m in &self.mods {
107            w.string(&m.name);
108            w.string(&m.file);
109            m.values.iter().for_each(|&v| w.u32(v));
110        }
111        w.end_block(at);
112        w.data
113    }
114}
115
116/// The file header's check value (`IO::Persistence`'s writer, Runtime around `0x1800b9500`):
117/// CRC-32 steps from `0xffffffff` over the block table, complemented, then over each block in
118/// 32 KiB pieces, complemented after each piece.
119fn header_check(table: &[u8], blocks: &[&[u8]]) -> u32 {
120    let step = |c: u32, data: &[u8]| !crate::crc::crc32_raw(c, data);
121    let mut c = step(!0, table);
122    for b in blocks {
123        for piece in b.chunks(stream::BLOCK_SIZE) {
124            c = step(c, piece);
125        }
126    }
127    c
128}
129
130/// Fields the game loop writes right after the reference table and settings block.
131///
132/// Original: `FUN_14009af60`.
133#[derive(Debug, Clone)]
134pub struct LoopHeader {
135    /// The climate profile's reference.
136    pub climate: String,
137    /// The start condition's reference.
138    pub start_condition: String,
139    /// The terrain profile's reference.
140    pub terrain: String,
141    /// The map seed.
142    pub seed: u32,
143    /// The map size: 0 small, 1 medium, 2 large.
144    pub size_index: i32,
145}
146
147fn u32_at(b: &[u8], at: usize) -> Result<u32> {
148    b.get(at..at + 4)
149        .map(|s| u32::from_le_bytes(s.try_into().unwrap()))
150        .ok_or(Error::Truncated { at, wanted: 4 })
151}
152
153impl Save {
154    /// Read a [`Save`] from the bytes of its resource.
155    pub fn parse(data: &[u8]) -> Result<Save> {
156        let (meta, state) = Save::payloads(data)?;
157        Ok(Save {
158            metadata: stream::decode(meta)?,
159            state: stream::decode(state)?,
160        })
161    }
162
163    /// Only the metadata, as the save list reads it: the game state is not expanded.
164    ///
165    /// Original: `Persistence::BeginGetSaveGameInfo`, then `SaveLoad::LoadMetaData`.
166    ///
167    /// Original: Runtime `0x1800c43a0`.
168    pub fn read_metadata(data: &[u8]) -> Result<SaveMetadata> {
169        SaveMetadata::parse(&stream::decode(Save::payloads(data)?.0)?)
170    }
171
172    /// The compressed metadata and game-state payloads, checked against the header.
173    fn payloads(data: &[u8]) -> Result<(&[u8], &[u8])> {
174        if data.len() < 2 {
175            return Err(Error::Truncated { at: 0, wanted: 2 });
176        }
177        let version = u16::from_le_bytes([data[0], data[1]]);
178        // Version 1: the first payload's offset and size at 0x08, the second's id, offset and
179        // size at 0x10. Version 2: `u16 2, u16 count, 0x80808080, u32 check`, then `{id,
180        // offset, size}` per payload from 0x0c.
181        let (first, second) = match version {
182            1 => ((0x08, 0x0c), (0x14, 0x18)),
183            2 => ((0x10, 0x14), (0x1c, 0x20)),
184            v => return Err(Error::Unsupported(format!("save container version {v}"))),
185        };
186        let payload = |(o, s): (usize, usize)| -> Result<&[u8]> {
187            let (off, size) = (u32_at(data, o)? as usize, u32_at(data, s)? as usize);
188            data.get(off..off + size).ok_or(Error::Truncated {
189                at: off,
190                wanted: size,
191            })
192        };
193        let (meta, state) = (payload(first)?, payload(second)?);
194        if state.as_ptr_range().end != data.as_ptr_range().end {
195            return format_err("game-state payload does not end at EOF");
196        }
197        if version == 2 && u32_at(data, 4)? == 0x8080_8080 {
198            let count = u16::from_le_bytes([data[2], data[3]]) as usize;
199            let table = data.get(12..12 + 12 * count).ok_or(Error::Truncated {
200                at: 12,
201                wanted: 12 * count,
202            })?;
203            if header_check(table, &[meta, state]) != u32_at(data, 8)? {
204                return format_err("save check value does not match");
205            }
206        }
207        Ok((meta, state))
208    }
209
210    /// The metadata: the town's name, the preview picture and the mods.
211    pub fn metadata(&self) -> Result<SaveMetadata> {
212        SaveMetadata::parse(&self.metadata)
213    }
214
215    /// A version 2 save file: the metadata as payload `0x24` and the game state as payload 1,
216    /// each compressed (`IO::CompressedStream`), behind the checked header.
217    pub fn write(metadata: &SaveMetadata, state: &[u8]) -> Vec<u8> {
218        let meta = stream::encode(&metadata.write());
219        let state = stream::encode(state);
220        const HEADER: usize = 12 + 2 * 12;
221        let mut table = Vec::new();
222        for (id, off, size) in [
223            (0, HEADER, meta.len()),
224            (1, HEADER + meta.len(), state.len()),
225        ] {
226            for v in [id as u32, off as u32, size as u32] {
227                table.extend_from_slice(&v.to_le_bytes());
228            }
229        }
230        let mut out = Vec::with_capacity(HEADER + meta.len() + state.len());
231        out.extend_from_slice(&2u16.to_le_bytes());
232        out.extend_from_slice(&2u16.to_le_bytes());
233        out.extend_from_slice(&0x8080_8080u32.to_le_bytes());
234        out.extend_from_slice(&header_check(&table, &[&meta, &state]).to_le_bytes());
235        out.extend_from_slice(&table);
236        out.extend_from_slice(&meta);
237        out.extend_from_slice(&state);
238        out
239    }
240
241    /// Find the event-log block (version 1: six notify bytes, a count and entries of colour,
242    /// text, type, severity, cell, category, icon). Located by scanning for a block whose
243    /// contents parse as exactly that and fill the block; the game-state order before it is
244    /// not walked.
245    pub fn event_log(&self) -> Option<SavedEventLog> {
246        let d = &self.state;
247        let marker = 0xaaaa_aaaau32.to_le_bytes();
248        let mut at = 0;
249        while let Some(p) = d[at..].windows(4).position(|w| w == marker) {
250            let start = at + p;
251            at = start + 4;
252            if let Some(log) = parse_event_block(&d[start..]) {
253                return Some(log);
254            }
255        }
256        None
257    }
258
259    /// External reference table: (id, path) pairs.
260    pub fn references(&self) -> Result<Vec<(u32, String)>> {
261        let mut r = Reader::new(&self.state);
262        r.block(|r, _| {
263            r.block(|r, _| {
264                let n = r.count()?;
265                (0..n).map(|_| Ok((r.u32()?, r.string()?))).collect()
266            })
267            .inspect(|_refs| {
268                // Skip the rest of the outer block; only the table is needed.
269                skip_rest(r);
270            })
271        })
272    }
273
274    /// The game loop's header: the seed, the map size, and the terrain, climate and start condition.
275    pub fn loop_header(&self) -> Result<LoopHeader> {
276        let refs = self.references()?;
277        let name = |id: u32| {
278            refs.iter()
279                .find(|(i, _)| *i == id)
280                .map(|(_, p)| p.clone())
281                .unwrap_or_default()
282        };
283        let mut r = Reader::new(&self.state);
284        r.block(|r, _| {
285            r.skip_block()?; // reference table
286            r.skip_block()?; // UI settings
287            let (climate, start, terrain) = (r.u32()?, r.u32()?, r.u32()?);
288            let seed = r.u32()?;
289            let size_index = r.i32()?;
290            skip_rest(r);
291            Ok(LoopHeader {
292                climate: name(climate),
293                start_condition: name(start),
294                terrain: name(terrain),
295                seed,
296                size_index,
297            })
298        })
299    }
300
301    /// Locate the map block by its dimension header (`2n, n, 32, 33, 2n+1, 33^2`).
302    pub fn map_heights(&self) -> Result<MapHeights> {
303        for n in [256i32, 384, 512] {
304            let pat: Vec<u8> = [2 * n, n, 32, 33, 2 * n + 1, 33 * 33]
305                .iter()
306                .flat_map(|v| v.to_le_bytes())
307                .collect();
308            if let Some(at) = self
309                .state
310                .windows(pat.len())
311                .position(|w| w == pat.as_slice())
312            {
313                let count = u32_at(&self.state, at + 24)? as usize;
314                let width = (2 * n + 1) as usize;
315                if count != width * width {
316                    return format_err("map height count does not match its dimensions");
317                }
318                let start = at + 28;
319                let bytes = self
320                    .state
321                    .get(start..start + 2 * count)
322                    .ok_or(Error::Truncated {
323                        at: start,
324                        wanted: 2 * count,
325                    })?;
326                let heights = bytes
327                    .chunks_exact(2)
328                    .map(|c| i16::from_le_bytes([c[0], c[1]]))
329                    .collect();
330                return Ok(MapHeights { width, heights });
331            }
332        }
333        format_err("no map block found")
334    }
335}
336
337impl Save {
338    /// Locate the gameplay map block (`0xaaaaaaaa, size, 4, n, n²`) and read its cells.
339    /// `n` is half the terrain size (see `map_heights`).
340    pub fn map_cells(&self) -> Result<MapCells> {
341        let n = (self.map_heights()?.width - 1) / 2;
342        let pat: Vec<u8> = [0xaaaa_aaaau32, 0, 4, n as u32, (n * n) as u32]
343            .iter()
344            .flat_map(|v| v.to_le_bytes())
345            .collect();
346        let at = self
347            .state
348            .windows(pat.len())
349            .position(|w| w[..4] == pat[..4] && w[8..] == pat[8..])
350            .ok_or_else(|| Error::Format("no map cell block found".into()))?;
351        let mut r = Reader::new(&self.state[at + 20..]);
352        let ptr = |r: &mut Reader| -> Result<bool> {
353            let set = r.u8()? != 0;
354            if set {
355                r.bytes(12)?;
356            }
357            Ok(set)
358        };
359        let mut cells = Vec::with_capacity(n * n);
360        for _ in 0..n * n {
361            let objects = [ptr(&mut r)?, ptr(&mut r)?];
362            let external = r.u32()?;
363            let flags: [u8; 9] = r.bytes(9)?.try_into().unwrap();
364            let value = u16::from_le_bytes(r.bytes(2)?.try_into().unwrap());
365            let bytes: [u8; 6] = r.bytes(6)?.try_into().unwrap();
366            cells.push(MapCell {
367                objects,
368                external,
369                flags,
370                value,
371                bytes,
372            });
373        }
374        let mut trailer = [0i16; 9];
375        for t in &mut trailer {
376            *t = i16::from_le_bytes(r.bytes(2)?.try_into().unwrap());
377        }
378        if r.u32()? != 0xbbbb_bbbb {
379            return format_err("map cell block does not end with its terminator");
380        }
381        Ok(MapCells {
382            size: n,
383            cells,
384            trailer,
385        })
386    }
387}