Skip to main content
Verticopolis engine

verticopolis_engine/
sim_save.rs

1//! The saved game, as a JSON tree (`Simulation::serialize`) and as JSON text
2//! (`Simulation::save_text`, behind `Engine.serialize`). Both read one list
3//! of fields, so they write the same keys in the same order (the tree keeps
4//! that order because the crate builds `serde_json` with `preserve_order`);
5//! each value's bytes rest on `serde_json` writing a borrowed value as it
6//! writes that value's `Value`, which the tests pin. The ledger's and the
7//! events' objects are the two shapes written twice. The text is written as
8//! it goes: each unit and each person is written straight from its record
9//! (`save_entry`), each transport, log line and ledger day becomes its own
10//! `Value` that is written and dropped before the next, and the tower's name,
11//! the pending choice's message and each excavated tile, room id, blockbuster
12//! cinema and milestone are written from their own values, so a save never
13//! holds the whole game as a tree beside the game (#1242).
14
15use serde::ser::{Serialize, SerializeMap, Serializer};
16use serde_json::{json, Map, Value};
17
18use crate::crowd::commuters_save::CrowdMarks;
19use crate::crowd::save::SavedCrowd;
20use crate::crowd::Crowd;
21use crate::dispatch::ElevatorDispatch;
22use crate::events::{EventSystem, PendingChoice};
23use crate::ledger::{totals_json, Ledger};
24use crate::save_floor_runs::{SavedUnits, FLOOR_RUN_SAVE_VERSION};
25use crate::sim::{stamped_save_version, LogEntry, Simulation, LOG_SAVE_CAP};
26use crate::tower::{SavedUnit, Transport, Unit};
27
28/// One top-level value of the save. The lists stay borrowed until they are
29/// written, one entry at a time.
30enum Field<'a> {
31    Owned(Value),
32    Borrowed(&'a Value),
33    Text(&'a str),
34    /// The units with plain floor tiles folded into runs (`save_floor_runs`).
35    Units(&'a [Unit]),
36    /// Every unit's own entry, as a version 10 save lists them.
37    PlainUnits(&'a [Unit]),
38    Transports(&'a [Transport]),
39    Strings(&'a [String]),
40    Ids(&'a [i64]),
41    Floats(&'a [f64]),
42    Ledger(&'a Ledger),
43    Events(&'a EventSystem),
44    Log(&'a [LogEntry]),
45    /// The crowd, and the marks beside its desks.
46    Crowd(&'a Crowd, CrowdMarks),
47    Dispatch(&'a ElevatorDispatch),
48}
49
50fn log_entry(e: &LogEntry) -> Value {
51    json!({ "minute": e.minute, "text": e.text, "kind": e.kind.as_str() })
52}
53
54/// A list written as `Value::Array` writes its elements, each element's
55/// `Value` built in turn: the same sequence calls with the same length.
56pub(crate) struct Each<'a, T, F>(pub(crate) &'a [T], pub(crate) F);
57
58impl<T, F: Fn(&T) -> Value> Serialize for Each<'_, T, F> {
59    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
60        s.collect_seq(self.0.iter().map(&self.1))
61    }
62}
63
64impl Field<'_> {
65    fn into_value(self) -> Value {
66        match self {
67            Field::Owned(v) => v,
68            Field::Borrowed(v) => v.clone(),
69            Field::Text(t) => json!(t),
70            Field::Units(us) => Value::Array(SavedUnits::new(us).map(|e| e.to_value()).collect()),
71            Field::PlainUnits(us) => Value::Array(us.iter().map(Unit::serialize).collect()),
72            Field::Transports(ts) => Value::Array(ts.iter().map(Transport::serialize).collect()),
73            Field::Strings(ss) => json!(ss),
74            Field::Ids(ids) => json!(ids),
75            Field::Floats(fs) => json!(fs),
76            Field::Ledger(l) => l.serialize(),
77            Field::Events(e) => e.save_state(),
78            Field::Log(es) => Value::Array(es.iter().map(log_entry).collect()),
79            Field::Crowd(c, marks) => c.save_json(marks),
80            Field::Dispatch(d) => d.save_json(),
81        }
82    }
83}
84
85impl Serialize for Field<'_> {
86    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
87        match self {
88            Field::Owned(v) => v.serialize(s),
89            Field::Borrowed(v) => v.serialize(s),
90            Field::Units(us) => s.collect_seq(SavedUnits::new(us)),
91            Field::PlainUnits(us) => {
92                s.collect_seq(us.iter().map(|unit| SavedUnit { unit, run: None }))
93            }
94            Field::Transports(ts) => Each(ts, Transport::serialize).serialize(s),
95            // A `Value::String` writes as its string does, a
96            // `Value::Number` holding an integer as its digits do, and one
97            // holding a float, or the null a non-finite float becomes, as
98            // `serialize_f64` writes that float.
99            Field::Text(t) => t.serialize(s),
100            Field::Strings(ss) => ss.serialize(s),
101            Field::Ids(ids) => ids.serialize(s),
102            Field::Floats(fs) => fs.serialize(s),
103            // `Ledger::serialize`'s object, `today` then `history`.
104            Field::Ledger(l) => {
105                let mut m = s.serialize_map(Some(2))?;
106                m.serialize_entry("today", &totals_json(&l.today))?;
107                m.serialize_entry("history", &Each(&l.history, totals_json))?;
108                m.end()
109            }
110            // `EventSystem::save_state`'s object; `pending` is a literal null
111            // when there is no choice.
112            Field::Events(e) => {
113                let mut m = s.serialize_map(Some(3 + usize::from(e.bomb.is_some())))?;
114                m.serialize_entry("lastSantaYear", &json!(e.last_santa_year))?;
115                m.serialize_entry("rngState", &json!(e.extra.seed()))?;
116                match &e.pending {
117                    Some(p) => m.serialize_entry("pending", &Pending(p))?,
118                    None => m.serialize_entry("pending", &Value::Null)?,
119                }
120                // Written only while a search runs, so a save without one
121                // keeps its exact shape.
122                if let Some(b) = &e.bomb {
123                    m.serialize_entry("bomb", &b.save_state())?;
124                }
125                m.end()
126            }
127            Field::Log(es) => Each(es, log_entry).serialize(s),
128            Field::Crowd(c, marks) => SavedCrowd(c, *marks).serialize(s),
129            // A few numbers per car and per floor, so one small tree.
130            Field::Dispatch(d) => d.save_json().serialize(s),
131        }
132    }
133}
134
135/// A pending choice, written as `save_state` builds it, with its message
136/// from the borrow.
137struct Pending<'a>(&'a PendingChoice);
138
139impl Serialize for Pending<'_> {
140    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
141        let mut m = s.serialize_map(Some(3))?;
142        m.serialize_entry("kind", self.0.kind)?;
143        m.serialize_entry("cost", &json!(self.0.cost))?;
144        m.serialize_entry("message", self.0.message.as_str())?;
145        m.end()
146    }
147}
148
149/// The save's top-level object, written as `Value::Object` writes a map.
150struct Fields<'a>(Vec<(&'static str, Field<'a>)>);
151
152impl Serialize for Fields<'_> {
153    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
154        let mut m = s.serialize_map(Some(self.0.len()))?;
155        for (k, v) in &self.0 {
156            m.serialize_entry(k, v)?;
157        }
158        m.end()
159    }
160}
161
162/// A top-level value the save owns.
163fn own(k: &'static str, v: Value) -> (&'static str, Field<'static>) {
164    (k, Field::Owned(v))
165}
166
167impl Simulation {
168    /// The marks the save writes beside the crowd's desks (`CrowdMarks`).
169    pub(crate) fn crowd_marks(&self) -> CrowdMarks {
170        CrowdMarks::of(&self.crowd, &self.tower, self.clock.hour())
171    }
172
173    /// The save's fields, in the order `serialize` has always written them.
174    /// Absent optional fields are left out, which is what the canonical
175    /// writer expects. Each key appears once. `fold` writes plain floor tiles
176    /// as runs and stamps the version that reads them; without it the units
177    /// are listed one by one, as the state view (`snapshot::state_view`)
178    /// reads them, so a conformance digest does not depend on the encoding.
179    fn save_fields(&self, fold: bool) -> Vec<(&'static str, Field<'_>)> {
180        let mut m: Vec<(&'static str, Field<'_>)> = Vec::with_capacity(33);
181        let tall_lobbies = self.tower.tall_lobby_runs();
182        let version = if fold {
183            self.written_save_version()
184        } else {
185            stamped_save_version(!tall_lobbies.is_empty(), self.tower.holds_an_hour_back())
186        };
187        m.push(own("version", json!(version)));
188        m.push(own("seed", json!(self.rng.seed())));
189        m.push(own("initialSeed", json!(self.rng.initial_seed)));
190        m.push(own("money", json!(self.money)));
191        m.push(own("star", json!(self.star)));
192        m.push(own("minutes", json!(self.clock.minutes)));
193        m.push(own("mode", json!(self.mode.as_str())));
194        m.push(own("modernCalendar", json!(self.modern_calendar.as_str())));
195        if !self.auto_bridge {
196            m.push(own("autoBridge", json!(false)));
197        }
198        if self.founder {
199            m.push(own("founder", json!(true)));
200        }
201        m.push(own("lastQuarterMoney", json!(self.last_quarter_money)));
202        // Before 10:00 the shops' day is still open from yesterday's 10:00; a
203        // save without the mark loads as a day already closed (#1500).
204        if self.morning_venue_day != self.clock.day() {
205            m.push(own("morningVenueDay", json!(self.morning_venue_day)));
206        }
207        // A first-day game's hour, maintenance and quarter marks, so a
208        // reload bills as the unsaved game would (`sim_period_marks.rs`).
209        if let Some(marks) = self.period_marks_json() {
210            m.push(own("periodMarks", marks));
211        }
212        m.push((
213            "units",
214            if fold {
215                Field::Units(&self.tower.units)
216            } else {
217                Field::PlainUnits(&self.tower.units)
218            },
219        ));
220        m.push(("transports", Field::Transports(&self.tower.transports)));
221        m.push(own("nextId", json!(self.tower.next_id)));
222        if let Some(n) = &self.tower.tower_name {
223            m.push(("towerName", Field::Text(n)));
224        }
225        if let Some(b) = self.tower.built_wedding_hall {
226            m.push(own("builtWeddingHall", json!(b)));
227        }
228        if !tall_lobbies.is_empty() {
229            m.push(own("lobbyHeights", json!(&*tall_lobbies)));
230        }
231        if let Some(b) = self.evaluated_tower {
232            m.push(own("evaluatedTower", json!(b)));
233        }
234        m.push(own("vipVisitDay", json!(self.vip_visit_day)));
235        m.push(own("vipFavorable", json!(self.vip_favorable)));
236        m.push(own("vipVisits", json!(self.vip_visits)));
237        m.push(own("lastVipNagDay", json!(self.last_vip_nag_day)));
238        m.push(own("treasuresFound", json!(self.treasures_found)));
239        if let Some(d) = self.extermination_due_day {
240            m.push(own("exterminationDueDay", json!(d)));
241            if let Some(ids) = &self.extermination_room_ids {
242                m.push(("exterminationRoomIds", Field::Ids(ids)));
243            }
244        }
245        m.push(("events", Field::Events(&self.events)));
246        m.push(("excavated", Field::Strings(&self.excavated)));
247        m.push(("blockbusters", Field::Floats(&self.blockbusters)));
248        m.push(("milestones", Field::Strings(&self.milestones)));
249        m.push(("ledger", Field::Ledger(&self.ledger)));
250        // Everyone in the tower as they stand, so a reload keeps them
251        // (`crowd::save`).
252        m.push(("crowd", Field::Crowd(&self.crowd, self.crowd_marks())));
253        // The cars' timers mid-stop, so the riders' cars carry on too.
254        m.push(("dispatch", Field::Dispatch(&self.elevators)));
255        // Today's rooms cleaned and yesterday's shift, so the checkout line
256        // and the stats sheet read the same after a reload.
257        if let Some(tallies) = self.housekeeping.save_json() {
258            m.push(own("housekeeping", tallies));
259        }
260        // The day's move-ins so far, so the evening's "New tenants:" line
261        // counts the whole day after a reload (`churn/move_ins_save.rs`).
262        if let Some(move_ins) = self.move_ins_today.save_json() {
263            m.push(own("moveIns", move_ins));
264        }
265        if let Some(v) = &self.view {
266            m.push(("view", Field::Borrowed(v)));
267        }
268        if !self.log.is_empty() {
269            let start = self.log.len().saturating_sub(LOG_SAVE_CAP);
270            m.push(("log", Field::Log(&self.log[start..])));
271        }
272        m
273    }
274
275    /// The whole game as save JSON, the object a `.vctower` file wraps.
276    ///
277    /// A host that edits or inspects the save uses this, then
278    /// [`crate::load::stamp_save`] and [`crate::load::encode_vctower`] to
279    /// write the file. To go straight to the file's bytes, use
280    /// [`crate::load::encode_simulation_vctower`].
281    ///
282    /// ```
283    /// use verticopolis_engine::clock::GameMode;
284    /// use verticopolis_engine::sim::{Simulation, PLAIN_SAVE_VERSION};
285    ///
286    /// let sim = Simulation::new_game(3, GameMode::Classic);
287    /// let save = sim.serialize();
288    /// // A tower with no tall lobby is stamped with the version before them.
289    /// assert_eq!(save["version"], PLAIN_SAVE_VERSION);
290    /// ```
291    pub fn serialize(&self) -> Value {
292        self.serialize_without(&[])
293    }
294
295    /// The save tree without the top-level keys in `left_out`, which are
296    /// never built.
297    pub(crate) fn serialize_without(&self, left_out: &[&str]) -> Value {
298        self.tree(true, left_out)
299    }
300
301    /// The version [`Simulation::serialize`] stamps. A save that folds floor
302    /// tiles into runs is stamped with the version that reads them, so an
303    /// older build refuses it rather than load a run as its first tile alone.
304    pub(crate) fn written_save_version(&self) -> i64 {
305        if self.tower.lists_a_floor_run() {
306            FLOOR_RUN_SAVE_VERSION
307        } else {
308            stamped_save_version(
309                !self.tower.tall_lobby_runs().is_empty(),
310                self.tower.holds_an_hour_back(),
311            )
312        }
313    }
314
315    #[doc(hidden)]
316    /// [`Simulation::serialize`] with every unit listed on its own and the
317    /// version a version 10 writer stamped: the shape the state view and the
318    /// conformance digests read, whatever the save's encoding.
319    pub fn serialize_unfolded(&self) -> Value {
320        self.serialize_unfolded_without(&[])
321    }
322
323    /// [`Simulation::serialize_unfolded`] without the top-level keys in
324    /// `left_out`, which are never built.
325    pub(crate) fn serialize_unfolded_without(&self, left_out: &[&str]) -> Value {
326        self.tree(false, left_out)
327    }
328
329    /// The save tree, folded or not (`save_fields`), without the keys in
330    /// `left_out`.
331    fn tree(&self, fold: bool, left_out: &[&str]) -> Value {
332        let mut m = Map::new();
333        for (k, f) in self.save_fields(fold) {
334            if !left_out.contains(&k) {
335                m.insert(k.into(), f.into_value());
336            }
337        }
338        Value::Object(m)
339    }
340
341    /// The save as a tree without its `units`, and the units as `Value`s one
342    /// at a time: the `.TDT` export reads the units as they come and the
343    /// rest from the tree (`build_tdt_streamed`, #1431), so a save of
344    /// thousands of units is never a tree beside the game. Each unit comes on
345    /// its own, as `serialize_unfolded()` lists it, with no floor run to
346    /// unfold; the rest carries the version `serialize()` stamps.
347    #[cfg_attr(not(feature = "wasm"), allow(dead_code))]
348    pub(crate) fn save_without_units(&self) -> (Value, impl Iterator<Item = Value> + '_) {
349        // The `.TDT` format has no place for the crowd, the cars' timers,
350        // the housekeeping tallies, the day's move-ins or the period marks.
351        (
352            self.serialize_without(&[
353                "units",
354                "crowd",
355                "dispatch",
356                "housekeeping",
357                "moveIns",
358                "periodMarks",
359            ]),
360            self.tower.units.iter().map(Unit::serialize),
361        )
362    }
363
364    #[doc(hidden)]
365    /// The saved game as `serde_json`'s compact text: the same bytes as
366    /// `serialize().to_string()`, written without the tree. `Engine.serialize`
367    /// returns it; that binding keeps its doc line, `serialize()` as JSON
368    /// text, as `engine.d.ts` has it.
369    pub fn save_text(&self) -> String {
370        // Writing to memory fails only on a map key that is not a string or
371        // a value that refuses to serialize; every key here is a string, and
372        // every value a `Value`, a string, a number, or a map or list of
373        // those, so the write cannot fail.
374        serde_json::to_string(&Fields(self.save_fields(true))).expect("a save writes as JSON")
375    }
376
377    /// The save text as UTF-8 bytes with `"savedAt"` and `"appVersion"`
378    /// appended as the last two keys, the bytes the web game's `stampText`
379    /// and `TextEncoder` make from `serialize()`. A host that stores the save
380    /// takes it this way, without holding a megabyte of save as a JavaScript
381    /// string. The stamp is written as `JSON.stringify` writes it.
382    pub fn stamped_save_bytes(&self, app_version: &str, saved_at_ms: f64) -> Vec<u8> {
383        let mut buf = Vec::new();
384        // The same write as `save_text`, which cannot fail (see there).
385        serde_json::to_writer(&mut buf, &Fields(self.save_fields(true)))
386            .expect("a save writes as JSON");
387        // A save is a JSON object with keys, so it ends in its closing brace.
388        buf.pop();
389        let mut stamp = String::from(",\"savedAt\":");
390        crate::canonical::write_js_json(&mut stamp, &json!(saved_at_ms));
391        stamp.push_str(",\"appVersion\":");
392        crate::canonical::write_js_string(&mut stamp, app_version);
393        stamp.push('}');
394        buf.extend_from_slice(stamp.as_bytes());
395        buf
396    }
397
398    /// The same text, written into `buf`, so the memory tests can reserve the
399    /// buffer first and count only what the write builds beside it.
400    #[cfg(test)]
401    pub(crate) fn write_save(&self, buf: &mut Vec<u8>) {
402        serde_json::to_writer(buf, &Fields(self.save_fields(true))).expect("a save writes as JSON");
403    }
404}
405
406#[cfg(test)]
407#[path = "sim_save_tests.rs"]
408mod tests;