Skip to main content

unbanished_formats/savegame_schema/
mod.rs

1//! The serializers of the objects a save holds, as schemas (see [`crate::savegame`]). Each
2//! entry names the Application function it follows; field names give the in-memory offset
3//! where no better name is known.
4
5use std::collections::HashMap;
6use std::sync::OnceLock;
7
8use crate::crc::type_id;
9
10mod actions;
11mod events;
12mod kinds;
13mod managers;
14mod objects;
15mod resources;
16mod work;
17
18pub use managers::*;
19
20/// A version test against the enclosing block's version.
21#[derive(Debug, Clone, Copy)]
22pub enum Cond {
23    /// The block's version is at least this.
24    VersionAtLeast(u32),
25    /// The block's version is below this.
26    VersionBelow(u32),
27    /// An earlier `Bool` of the same fields is true.
28    Flag(&'static str),
29}
30
31/// One step of a serializer.
32#[derive(Debug, Clone, Copy)]
33pub enum Op {
34    /// A named bool.
35    Bool(&'static str),
36    /// A named `i8`.
37    I8(&'static str),
38    /// A named `i16`.
39    I16(&'static str),
40    /// A named `u16`.
41    U16(&'static str),
42    /// A named `i32`.
43    I32(&'static str),
44    /// A named `u32`.
45    U32(&'static str),
46    /// `System::Time`: an `i64` of ticks.
47    Time(&'static str),
48    /// A named `f32`.
49    F32(&'static str),
50    /// A fixed number of `System::Time`s.
51    Times(&'static str, usize),
52    /// A fixed number of `f32`s.
53    F32s(&'static str, usize),
54    /// A fixed number of `u32`s.
55    U32s(&'static str, usize),
56    /// `i32`s counted by an earlier field of the same fields.
57    I32sBy(&'static str, &'static str),
58    /// `f32`s counted by an earlier field.
59    F32sBy(&'static str, &'static str),
60    /// `System::String` with the 8-bit flag.
61    Str(&'static str),
62    /// A UTF-16 string.
63    WStr(&'static str),
64    /// An `ExternalPtr` in reference mode: the reference id.
65    Ext(&'static str),
66    /// An `InternalBasePtr`.
67    Ptr(&'static str),
68    /// An `i32` count, then the items.
69    List(&'static str, &'static [Op]),
70    /// Items repeated until the enclosing block ends (no count is written).
71    Rest(&'static str, &'static [Op]),
72    /// An `IO::Serializer` block written at this version.
73    Block(&'static str, u32, &'static [Op]),
74    /// Inline steps (shared fragments).
75    Sub(&'static [Op]),
76    /// Steps read only when the condition holds.
77    If(Cond, &'static [Op]),
78}
79
80use Cond::*;
81use Op::*;
82
83/// `Component::Serialize` (`FUN_14011de80`): `Internal::Persist` writes nothing, then the
84/// entity, flags (`+0x20`) and description (`+0x18`).
85/// `Work::Serialize` (`FUN_1400fc8d0`, version 3): the entity and its WorkComponent, the
86/// worker counts and the times.
87const WORK: Op = Block(
88    "work",
89    3,
90    &[
91        Ptr("entity"),
92        Ptr("component"),
93        I32("id"),
94        I32("cell"),
95        If(VersionAtLeast(1), &[I32("priority")]),
96        If(
97            VersionAtLeast(3),
98            &[Time("patience"), Time("patience_base"), I32("far_count")],
99        ),
100    ],
101);
102
103/// `AutoPickupWork`: Work, then an empty block.
104const AUTO_PICKUP_WORK: Op = Sub(&[WORK, Block("auto_pickup", 0, &[])]);
105
106/// `FUN_14002a010`: a set of citizens.
107const CITIZENS: Op = List("citizens", &[Ptr("citizen")]);
108
109/// `FUN_14002a740`: key → citizen.
110const KEYED_CITIZENS: Op = List("keyed", &[I32("key"), Ptr("citizen")]);
111
112const BASE: Op = Block(
113    "base",
114    0,
115    &[Ptr("entity"), U32("flags"), Ext("description")],
116);
117/// `Action::Serialize`: started (`+0x18`).
118const ACTION: Op = Block("action", 0, &[Bool("started")]);
119/// `ControllerComponent`'s own (empty) block.
120const CONTROLLER: Op = Block("controller", 0, &[]);
121/// `ResourceProduceComponent::Serialize` (`FUN_140130970`): switched off (`+0x48`).
122const RESOURCE_PRODUCE: Op = Sub(&[BASE, CONTROLLER, Block("produce", 0, &[Bool("disabled")])]);
123
124// Runtime FUN_18005d610, one 0x38-byte entry each: the group +0x00, the clip +0x08, the speed
125// +0x10, the clock +0x18, the blend time +0x20 and what is left of it +0x28, the shared instance
126// +0x0c, and +0x30.
127/// One layer of an `AnimationState` (newest first): the animation group, the clip, the speed, the
128/// clip's clock, the blend time and the blend time left while a newer layer covers it, the shared
129/// instance an instanced clip follows (−1 for none), and whether the layer has been updated once.
130pub const ANIMATION_STATE: &[Op] = &[
131    Ext("animation"),
132    I32("clip"),
133    F32("speed"),
134    Time("elapsed"),
135    Time("blend"),
136    Time("left"),
137    I32("instance"),
138    Bool("started"),
139];
140
141/// `Graphics::MeshInstance::Serialize` (`0x180101f10`): `AnimationState` entries
142/// (`FUN_18005d610`), its flag, then the material references.
143const MESH_INSTANCE: Op = Sub(&[
144    List("animations", ANIMATION_STATE),
145    Bool("animating"),
146    List("materials", &[Ext("material")]),
147]);
148
149const GOAL_INSTANCE: Op = Block("goal", 0, &[Ext("goal"), I32("value")]);
150
151/// The object schemas, in groups (one per child module), in the table's order.
152static SCHEMAS: &[&[(&str, &[Op])]] = &[
153    objects::SCHEMAS,
154    actions::SCHEMAS,
155    kinds::SCHEMAS,
156    work::SCHEMAS,
157    events::SCHEMAS,
158    resources::SCHEMAS,
159];
160
161/// The schema for a type id: its name and steps.
162/// An entity list (`FUN_140008150` and the inline copies): a count, then the pointers.
163const fn ptr_list(name: &'static str) -> Op {
164    List(name, &[Ptr("entity")])
165}
166
167/// The class name and the schema of an object type, by type id.
168pub fn schema_for(ty: u32) -> Option<(&'static str, &'static [Op])> {
169    static BY_ID: OnceLock<HashMap<u32, (&'static str, &'static [Op])>> = OnceLock::new();
170    BY_ID
171        .get_or_init(|| {
172            SCHEMAS
173                .iter()
174                .flat_map(|g| g.iter())
175                .map(|&(name, ops)| (type_id(name), (name, ops)))
176                .collect()
177        })
178        .get(&ty)
179        .copied()
180}
181
182/// A new object's fields for type `name`: every step's default (zero, false, none, empty), in
183/// the schema's order, each block at its version. The writer fills them in.
184pub fn default_fields(name: &str) -> Option<crate::savegame::Fields> {
185    let (_, ops) = schema_for(type_id(name))?;
186    let mut out = crate::savegame::Fields::default();
187    defaults_into(ops, 0, &mut out);
188    Some(out)
189}
190
191/// A block's fields at their defaults (the town, the managers), as [`default_fields`] makes
192/// an object's.
193pub fn default_block(ops: &[Op], version: u32) -> crate::savegame::Fields {
194    let mut out = crate::savegame::Fields::default();
195    defaults_into(ops, version, &mut out);
196    out
197}
198
199fn defaults_into(ops: &[Op], version: u32, out: &mut crate::savegame::Fields) {
200    use crate::savegame::{Fields, Value};
201    for op in ops {
202        let (name, value) = match *op {
203            Bool(n) => (n, Value::Bool(false)),
204            I8(n) => (n, Value::I8(0)),
205            I16(n) => (n, Value::I16(0)),
206            U16(n) => (n, Value::U16(0)),
207            I32(n) => (n, Value::I32(0)),
208            U32(n) => (n, Value::U32(0)),
209            Time(n) => (n, Value::I64(0)),
210            F32(n) => (n, Value::F32(0.0)),
211            Times(n, k) => (n, Value::I64s(vec![0; k])),
212            F32s(n, k) => (n, Value::F32s(vec![0.0; k])),
213            U32s(n, k) => (n, Value::U32s(vec![0; k])),
214            I32sBy(n, _) => (n, Value::U32s(Vec::new())),
215            F32sBy(n, _) => (n, Value::F32s(Vec::new())),
216            Str(n) | WStr(n) => (n, Value::Str(String::new())),
217            Ext(n) => (n, Value::Ext(u32::MAX)),
218            Ptr(n) => (n, Value::Ptr(None)),
219            List(n, _) | Rest(n, _) => (n, Value::List(Vec::new())),
220            Block(n, v, inner) => {
221                let mut f = Fields::default();
222                defaults_into(inner, v, &mut f);
223                (n, Value::Block(v, f))
224            }
225            Sub(inner) => {
226                defaults_into(inner, version, out);
227                continue;
228            }
229            If(cond, inner) => {
230                let take = match cond {
231                    VersionAtLeast(v) => version >= v,
232                    VersionBelow(v) => version < v,
233                    Flag(_) => false,
234                };
235                if take {
236                    defaults_into(inner, version, out);
237                }
238                continue;
239            }
240        };
241        out.0.push((name, value));
242    }
243}
244
245/// Every object type the schemas cover.
246pub fn type_names() -> impl Iterator<Item = &'static str> {
247    SCHEMAS.iter().flat_map(|g| g.iter()).map(|&(name, _)| name)
248}