Skip to main content

unbanished_formats/
scenario.rs

1//! Achievements, scenarios and tutorials (`Game/Achievement`, `Game/Scenario`). See
2//! docs/ACHIEVEMENTS.md and docs/TUTORIAL.md.
3//!
4//! - `Achievement::Achievement`: its string table, title, description, sprite sheet and sprite, and
5//!   its goals.
6//! - A string table and text; then each class's own block: BuildingGoal, PopulationGoal, StatGoal,
7//!   TimeGoal, FinishTutorialGoal.
8//! - `Scenario`: an achievement, then the game it starts.
9//! - `Tutorial` and its steps, setups, goals and images.
10//!
11//! Original: `Achievement::Achievement::Serialize`, `Achievement::Goal`, `FUN_1400dcb70`,
12//! `FUN_1400dcd40`, `FUN_1400dfd80`, `FUN_1400dfff0`, `FUN_1400dcea0`, `FUN_1400ae840`,
13//! `FUN_1400e3fa0`.
14//!
15//! Original: Runtime `0x18009eb70`, Runtime `0x18009fd30`.
16
17mod tutorial;
18pub use tutorial::{tutorial_part, ImageExtra, Tutorial, TutorialPart, TutorialStep};
19
20use crate::crc::type_id;
21use crate::crs::{self, Reader};
22use crate::error::{format_err, Result};
23
24/// `Achievement::Achievement`.
25#[derive(Debug, Clone, Default, PartialEq)]
26pub struct Achievement {
27    // +0x20
28    /// The string table.
29    pub strings: Option<String>,
30    // +0x28, +0x30
31    /// The title's key.
32    pub title: String,
33    /// The description's key.
34    pub description: String,
35    // +0x38; +0x40
36    /// The sprite sheet.
37    pub sprites: Option<String>,
38    /// The sprite.
39    pub sprite: String,
40    // +0x48
41    /// The goals.
42    pub goals: Vec<Option<String>>,
43}
44
45fn achievement(r: &mut Reader) -> Result<Achievement> {
46    r.block(|r, _| {
47        let strings = r.external_ref()?;
48        let title = r.string()?;
49        let description = r.string()?;
50        let sprites = r.external_ref()?;
51        let sprite = r.string()?;
52        let goals = (0..r.count()?)
53            .map(|_| r.external_ref())
54            .collect::<Result<_>>()?;
55        Ok(Achievement {
56            strings,
57            title,
58            description,
59            sprites,
60            sprite,
61            goals,
62        })
63    })
64}
65
66/// A Goal's own fields, by class.
67#[derive(Debug, Clone, PartialEq)]
68pub enum GoalKind {
69    // +0x30; +0x38
70    /// Some buildings exist.
71    Building {
72        /// Whether all of the buildings must exist (else any).
73        all: bool,
74        /// The buildings (ComponentDescriptions).
75        buildings: Vec<String>,
76    },
77    // +0x30
78    /// The population is at least this many citizens.
79    Population(i32),
80    // +0x30..
81    /// A statistic compared with an amount or with a second statistic.
82    Stat {
83        /// The statistic.
84        e30: i32,
85        /// The second statistic, for odd comparisons.
86        e34: i32,
87        /// The comparison: 0/1 equal, 2/3 not, 4/5 less, 6/7 at most, 8/9 more, 10/11 at least.
88        e38: i32,
89        /// The amount the statistic is compared with.
90        amount: i32,
91        /// Whether the goal is met until the comparison holds, then fails.
92        flag: bool,
93        /// The statistic's reference.
94        r48: String,
95        /// The second statistic's reference.
96        r60: String,
97        /// Raw-material flags, for the statistics that take them.
98        e78: i32,
99        /// A number, for the statistics that take it.
100        i7c: i32,
101    },
102    // +0x30; +0x34
103    /// A number of years passed.
104    Time {
105        /// The years.
106        years: i32,
107        /// Whether the goal must be met within that time (else after it).
108        within: bool,
109    },
110    // +0x30
111    /// The tutorial is done.
112    FinishTutorial(Option<String>),
113}
114
115/// `Achievement::Goal`.
116#[derive(Debug, Clone, PartialEq)]
117pub struct Goal {
118    /// The string table.
119    pub strings: Option<String>,
120    /// The text's key.
121    pub text: String,
122    /// The class's own fields.
123    pub kind: GoalKind,
124}
125
126/// Read a [`Goal`] from the bytes of its resource.
127pub fn goal(data: &[u8]) -> Result<Goal> {
128    let (_, v) = crs::parse(data, |r, h| {
129        let (strings, text) = r.block(|r, _| Ok((r.external_ref()?, r.string()?)))?;
130        let kind = r.block(|r, _| {
131            Ok(match h.type_id {
132                t if t == type_id("BuildingGoal") => GoalKind::Building {
133                    all: r.bool()?,
134                    buildings: (0..r.count()?).map(|_| r.string()).collect::<Result<_>>()?,
135                },
136                t if t == type_id("PopulationGoal") => GoalKind::Population(r.i32()?),
137                t if t == type_id("StatGoal") => GoalKind::Stat {
138                    e30: r.i32()?,
139                    e34: r.i32()?,
140                    e38: r.i32()?,
141                    amount: r.i32()?,
142                    flag: r.bool()?,
143                    r48: r.string()?,
144                    r60: r.string()?,
145                    e78: r.i32()?,
146                    i7c: r.i32()?,
147                },
148                t if t == type_id("TimeGoal") => GoalKind::Time {
149                    years: r.i32()?,
150                    within: r.bool()?,
151                },
152                t if t == type_id("FinishTutorialGoal") => {
153                    GoalKind::FinishTutorial(r.external_ref()?)
154                }
155                t => return format_err(format!("unknown goal type {t:#010x}")),
156            })
157        })?;
158        Ok(Goal {
159            strings,
160            text,
161            kind,
162        })
163    })?;
164    Ok(v)
165}
166
167/// Read a [`Achievement`] from the bytes of its resource.
168pub fn achievement_description(data: &[u8]) -> Result<Achievement> {
169    let (_, v) = crs::parse(data, |r, h| {
170        if h.type_id != type_id("Achievement") {
171            return format_err(format!("expected Achievement, found {:#010x}", h.type_id));
172        }
173        achievement(r)
174    })?;
175    Ok(v)
176}
177
178/// `Scenario` (an Achievement).
179#[derive(Debug, Clone, Default, PartialEq)]
180pub struct Scenario {
181    /// The achievement.
182    pub achievement: Achievement,
183    // +0x60; +0x64
184    /// Not identified yet.
185    pub i60: i32,
186    /// Not identified yet.
187    pub i64: i32,
188    // +0x58
189    /// The town's name.
190    pub town_name: String,
191    // +0x70; +0x78; +0x80
192    /// Not identified yet.
193    pub r70: Option<String>,
194    /// Not identified yet.
195    pub r78: Option<String>,
196    /// Not identified yet.
197    pub r80: Option<String>,
198    // +0x88
199    /// The save to start from (`Save\{name}.sav` in the data, the tutorials'), empty for a new
200    /// game.
201    ///
202    /// Original: `FUN_14007d180`.
203    pub save: String,
204    // +0x68; +0x69
205    /// Not identified yet.
206    pub b68: bool,
207    /// Not identified yet.
208    pub b69: bool,
209}
210
211/// Read a [`Scenario`] from the bytes of its resource.
212pub fn scenario(data: &[u8]) -> Result<Scenario> {
213    let (_, v) = crs::parse(data, |r, h| {
214        if h.type_id != type_id("Scenario") {
215            return format_err(format!("expected Scenario, found {:#010x}", h.type_id));
216        }
217        let achievement = achievement(r)?;
218        r.block(|r, _| {
219            Ok(Scenario {
220                achievement,
221                i60: r.i32()?,
222                i64: r.i32()?,
223                town_name: r.string()?,
224                r70: r.external_ref()?,
225                r78: r.external_ref()?,
226                r80: r.external_ref()?,
227                save: r.string()?,
228                b68: r.bool()?,
229                b69: r.bool()?,
230            })
231        })
232    })?;
233    Ok(v)
234}
235
236fn refs(r: &mut Reader) -> Result<Vec<Option<String>>> {
237    (0..r.count()?).map(|_| r.external_ref()).collect()
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    /// Every shipped achievement, goal, scenario and tutorial part parses whole.
245    #[test]
246    fn every_achievement_and_tutorial_parses() {
247        let root =
248            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../game-data/extracted");
249        let mut counts = std::collections::BTreeMap::<&str, usize>::new();
250        for dir in ["Game/Achievement", "Game/Scenario"] {
251            let Ok(entries) = std::fs::read_dir(root.join(dir)) else {
252                return;
253            };
254            for e in entries {
255                let p = e.unwrap().path();
256                let b = std::fs::read(&p).unwrap();
257                let Ok(h) = crs::header(&b) else { continue };
258                let name = p.file_name().unwrap().to_string_lossy().to_string();
259                let t = h.type_id;
260                let kind = if t == type_id("Achievement") {
261                    achievement_description(&b).map(|_| "achievement")
262                } else if t == type_id("Scenario") {
263                    scenario(&b).map(|_| "scenario")
264                } else if [
265                    "BuildingGoal",
266                    "PopulationGoal",
267                    "StatGoal",
268                    "TimeGoal",
269                    "FinishTutorialGoal",
270                ]
271                .iter()
272                .any(|n| t == type_id(n))
273                {
274                    goal(&b).map(|_| "goal")
275                } else {
276                    match tutorial_part(&b) {
277                        Ok(_) => Ok("tutorial"),
278                        Err(e) if e.to_string().contains("not a tutorial part") => continue,
279                        Err(e) => Err(e),
280                    }
281                };
282                match kind {
283                    Ok(k) => *counts.entry(k).or_default() += 1,
284                    Err(e) => panic!("{name}: {e}"),
285                }
286            }
287        }
288        assert_eq!(counts.get("achievement"), Some(&36), "{counts:?}");
289        assert_eq!(counts.get("goal"), Some(&138), "{counts:?}");
290        assert_eq!(counts.get("scenario"), Some(&4), "{counts:?}");
291        assert_eq!(counts.get("tutorial"), Some(&557), "{counts:?}");
292    }
293}