Skip to main content
Verticopolis engine

verticopolis_engine/load/
reader.rs

1//! Reading a save into a `Simulation`: the entry points and the per-unit reader.
2
3use super::*;
4use crate::economy::visitors::census_follows_the_day;
5use crate::tower::Extras;
6
7#[doc(hidden)]
8/// The sentence a save written by a newer build is refused with.
9pub const NEWER_SAVE_REFUSAL: &str =
10    "This save was made by a newer version of Verticopolis. Update the game to load it.";
11
12#[doc(hidden)]
13/// The sentence a save with no numeric `minutes` or no `units` list at its
14/// top level is refused with (#1418).
15pub const NOT_A_SAVE_REFUSAL: &str =
16    "This is not a saved tower: it has no game clock or no list of rooms.";
17
18/// Whether save JSON as written has a numeric `minutes` and a `units` list at
19/// its top level, as every save the game writes does. A file that carries them
20/// only inside another object would load as an empty tower (#1418).
21pub(crate) fn has_save_shape(raw: &Value) -> bool {
22    raw.get("minutes").is_some_and(Value::is_number)
23        && raw.get("units").is_some_and(Value::is_array)
24}
25
26/// Builds a game from save JSON (from [`decode_vctower`] or
27/// [`Simulation::serialize`]). An older save is upgraded first, and damaged
28/// or edited fields are corrected the way the web game's loader corrects
29/// them. Refuses a save from a newer version of the engine, one with no
30/// numeric `minutes` or no `units` list at its top level, and one it cannot
31/// read, with a sentence a player can read.
32pub fn deserialize(raw: &Value) -> Result<Simulation, String> {
33    deserialize_owned(raw.clone())
34}
35
36/// [`deserialize`] for a save that [`import_tdt`](crate::import_tdt) made from
37/// a 1994 `.TDT` file. It also keeps the basement floors the original's
38/// express elevators skip, which a normal load of a shaft without
39/// `preserveBasementStops` would turn back on.
40#[doc(hidden)]
41pub fn deserialize_tdt(raw: &Value) -> Result<Simulation, String> {
42    let mut sim = deserialize(raw)?;
43    // The original closes a shop's day at 10:00 (#1500), so a tower saved
44    // before 10:00 still has today's close to come.
45    if raw.get("morningVenueDay").is_none()
46        && sim.clock.hour() < crate::economy::visitors::MORNING_VENUE_DAY_ENDS_AT_HOUR
47    {
48        sim.morning_venue_day = sim.clock.day() - 1;
49    }
50    let Some(source) = raw.get("transports").and_then(Value::as_array) else {
51        return Ok(sim);
52    };
53    let mut changed = false;
54    for shaft in &mut sim.tower.transports {
55        if shaft.kind != Kind::ElevatorExpress || shaft.bottom >= 0 {
56            continue;
57        }
58        let original = source.iter().find(|t| {
59            t.get("kind").and_then(Value::as_str) == Some("elevatorExpress")
60                && t.get("x").and_then(Value::as_i64) == Some(shaft.x)
61                && t.get("bottom").and_then(Value::as_i64) == Some(shaft.bottom)
62                && t.get("top").and_then(Value::as_i64) == Some(shaft.top)
63        });
64        let Some(authored) = original
65            .and_then(|t| t.get("skipFloors"))
66            .and_then(Value::as_array)
67        else {
68            continue;
69        };
70        let saved_skips: Vec<f64> = authored
71            .iter()
72            .filter_map(Value::as_f64)
73            .filter(|v| v.is_finite())
74            .collect();
75        // The load cleared the basement skips and marked the shaft; put back
76        // the ones the file wrote, inside the span. The marker stays on the
77        // .vctower saves made from here, so a reload keeps them.
78        shaft.preserve_basement_stops = true;
79        let (bottom, top) = (shaft.bottom as f64, shaft.top as f64);
80        let have = shaft.skip_floors.as_deref().unwrap_or(&[]);
81        let mut back: Vec<f64> = saved_skips
82            .iter()
83            .copied()
84            .filter(|&floor| crate::facilities::is_basement_stop(floor))
85            .filter(|&floor| floor > bottom && floor < top && !have.contains(&floor))
86            .collect();
87        back.dedup();
88        if back.is_empty() {
89            continue;
90        }
91        // A shaft whose load left no skip list still takes the file's own.
92        let skips = shaft.skip_floors.get_or_insert_with(Vec::new);
93        skips.extend(back);
94        skips.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
95        skips.dedup();
96        changed = true;
97    }
98    if changed {
99        sim.tower.revision += 1;
100    }
101    Ok(sim)
102}
103
104/// [`deserialize`] for save JSON the caller no longer needs: it upgrades the
105/// save in place and frees it as it goes, so a large tower loads in less
106/// memory.
107pub fn deserialize_owned(raw: Value) -> Result<Simulation, String> {
108    // `migrateSave(null)` throws reading `version`; any other top-level value
109    // loads as the TypeScript loads it (#858).
110    if raw.is_null() {
111        return Err("not a tower save (the save is null)".into());
112    }
113    // A save from a build newer than this one may carry fields this loader
114    // would drop, and the next save would write the loss back. Refuse it so
115    // the stored copy stays whole until the game is updated (#1603).
116    if let Some(version) = raw.get("version").and_then(Value::as_f64) {
117        if version.is_finite() && version > SAVE_VERSION as f64 {
118            return Err(NEWER_SAVE_REFUSAL.into());
119        }
120    }
121    // A save without its clock or its rooms would load as an empty tower that
122    // the next save writes over the real one (#1418).
123    if !has_save_shape(&raw) {
124        return Err(NOT_A_SAVE_REFUSAL.into());
125    }
126    // The founder test reads the save as written, and `assemble` reads
127    // nothing else from it, so two keys stand in for it.
128    let written = founder_keys(&raw);
129    let mut data = migrate_save_owned(raw);
130    let modern = data.get("mode").and_then(Value::as_str) == Some("modern");
131    let runs = reads_floor_runs(version_of(&data));
132    let listed = match data.get_mut("units") {
133        Some(Value::Array(units)) => std::mem::take(units),
134        _ => Vec::new(),
135    };
136    // The entries `unit_from_value` keeps, counted before any unit is built
137    // (a floor run counts each of its tiles), so a save past the cap is
138    // refused first and the rest fill vectors of their exact size.
139    let mut kept = 0usize;
140    for u in listed.iter().filter(|u| kind_of(u).is_some()) {
141        kept += listed_units(u, runs);
142        if kept > UNIT_CAP {
143            break;
144        }
145    }
146    if kept > UNIT_CAP {
147        return Err(format!(
148            "This save lists more than {UNIT_CAP} units, more than the whole lot can hold, so it cannot be a real tower."
149        ));
150    }
151    let mut units = Vec::with_capacity(kept + unit_list_headroom(kept));
152    let mut ids = Vec::with_capacity(kept);
153    for entry in listed {
154        each_listed_unit(&entry, runs, |tile| {
155            if let Some((unit, id)) = unit_from_value(tile, modern) {
156                units.push(unit);
157                ids.push(id);
158            }
159            true
160        });
161    }
162    debug_assert_eq!(units.len(), kept, "unit_from_value skipped a counted entry");
163    Ok(assemble(&data, units, ids, &written))
164}
165
166/// The keys `detect_founder` reads off a save.
167pub(crate) fn founder_keys(raw: &Value) -> Value {
168    let mut keys = Map::new();
169    for key in ["founder", "appVersion"] {
170        if let Some(v) = raw.get(key) {
171            keys.insert(key.to_string(), v.clone());
172        }
173    }
174    Value::Object(keys)
175}
176
177/// One entry of a save's `units` array as `deserialize` reads it, with its
178/// saved id; `None` for an entry it skips (null, or a kind the catalog does
179/// not know), exactly when `kind_of` gives `None`, which the unit cap's
180/// count in `deserialize` relies on. It reads nothing outside the entry but
181/// the save's mode.
182pub(crate) fn unit_from_value(u: &Value, modern: bool) -> Option<(Unit, Option<i64>)> {
183    let kind = kind_of(u)?;
184    let cat = kind.facility().width;
185    // `drop_overlapping_units` indexes its tile grids by the floors and tiles
186    // these clamps allow, so a loosened clamp would trap there.
187    let floor =
188        (round(num(u.get("floor"), 1.0)) as i64).clamp(MIN_FLOOR, kind.highest_base_floor());
189    let x = (round(num(u.get("x"), 0.0)) as i64).clamp(0, LOT - 1);
190    let cap = if kind.is_structural() { cat } else { LOT - x };
191    let width = (round(num(u.get("width"), cat as f64)) as i64)
192        .min(cap)
193        .min(LOT - x)
194        .max(1);
195    let state = if kind.is_structural() {
196        UnitState::Empty
197    } else {
198        parse_state(u.get("state")).unwrap_or(UnitState::Empty)
199    };
200    let not_owned = matches!(
201        state,
202        UnitState::Empty | UnitState::Construction | UnitState::Gutted
203    );
204    let ever_occupied =
205        u.get("everOccupied") == Some(&Value::Bool(true)) && !(not_owned && !kind.is_hotel());
206    let sold_condo = kind == Kind::Condo && ever_occupied;
207    let keep_household = ever_occupied && kind.has_household();
208    let ladder_priced = !modern && classic_ladder(kind).is_some();
209    let mut rent: Option<f64> = match u.get("rent") {
210        None => None,
211        Some(r) if ladder_priced => Some(r.as_f64().unwrap_or(f64::NAN)),
212        Some(r) => Some(num(
213            Some(r),
214            rent_config(kind).map(|c| c.default).unwrap_or(0.0),
215        )),
216    };
217    if let Some(r) = rent {
218        if kind == Kind::Condo {
219            let ladder = if modern {
220                None
221            } else {
222                classic_ladder(Kind::Condo)
223            };
224            if sold_condo {
225                rent = Some(match ladder {
226                    Some(l) => js_max(l[0], js_min(l[3], r)),
227                    None => js_max(SOLD_CONDO_MIN_PRICE, js_min(SOLD_CONDO_MAX_PRICE, r)),
228                });
229            } else if ladder.is_none() {
230                let band = rent_config(Kind::Condo).unwrap();
231                rent = Some(js_max(band.min, js_min(band.max, r)));
232            }
233        }
234    }
235    let residents = if keep_household && modern {
236        match u.get("residents") {
237            None => None,
238            Some(r) => {
239                let v = if r.as_f64().is_some_and(|x| x.is_finite()) {
240                    r.as_f64().unwrap()
241                } else {
242                    3.0
243                };
244                Some((round(v) as i64).clamp(2, 5))
245            }
246        }
247    } else {
248        None
249    };
250    let film_policy = film_policy(u.get("filmPolicy"));
251    let subtype: Option<&'static str> = match (
252        u.get("subtype").and_then(Value::as_str),
253        kind.subtype_list(),
254    ) {
255        (Some(s), Some(list)) => list.iter().copied().find(|c| *c == s),
256        _ => None,
257    };
258    let retail = kind.subtype_list().is_some();
259    let retail_field = |key: &str| -> Option<f64> {
260        if !retail {
261            return None;
262        }
263        let v = u.get(key)?;
264        Some(num(Some(v), 0.0).max(0.0))
265    };
266    let no_rate =
267        rent_config(kind).is_some() && !modern && u.get("noRate") == Some(&Value::Bool(true));
268    let unit = Unit {
269        id: 0,
270        kind,
271        floor,
272        x,
273        width,
274        state,
275        satisfaction: if kind.is_structural() {
276            1.0
277        } else {
278            num(u.get("satisfaction"), 1.0).min(1.0).max(0.0)
279        },
280        occupants: if kind.counts_visitors() || kind.is_structural() {
281            0
282        } else {
283            let occupants = num(u.get("occupants"), 0.0).clamp(0.0, MAX_SAFE_INTEGER) as i64;
284            // An office's head count is its workers at their desks, each of
285            // whom may leave as a person (`crowd::commuters`): never more
286            // than the office holds (#2230).
287            if kind == Kind::Office {
288                occupants.min(kind.facility().population)
289            } else {
290                occupants
291            }
292        },
293        customers_in: None,
294        hotel_customers_in: None,
295        staff_in: 0,
296        out_for_meal: None,
297        residents,
298        visitors_yest: if census_follows_the_day(kind) {
299            u.get("visitorsYest")
300                .map(|v| num(Some(v), 0.0).clamp(0.0, f64::from(u8::MAX)).floor() as u8)
301        } else {
302            None
303        },
304        ever_occupied,
305        pending_income: num(u.get("pendingIncome"), 0.0),
306        rent,
307        no_rate,
308        label: u
309            .get("label")
310            .and_then(Value::as_str)
311            .map(|s| s.to_string())
312            .unwrap_or_else(|| kind.facility().name.to_string()),
313        subtype,
314        extras: Extras {
315            vacate_reason: vacate_reason(u.get("vacateReason")),
316            vacate_at: u.get("vacateAt").map(|v| num(Some(v), 0.0)),
317            film_policy,
318            film_days: film_days(kind, u.get("filmDays")),
319            film_classic: cinema_flag(kind, u.get("filmClassic")),
320            // Only Modern shows a blockbuster (#1950); Classic reads a new film.
321            film_blockbuster: modern && cinema_flag(kind, u.get("filmBlockbuster")),
322            ticket_price: ticket_price(kind, modern, u.get("ticketPrice")),
323            second_screen: second_screen(kind, u.get("screen2")),
324            patronage_today: retail_field("patronageToday"),
325            patronage_yest: retail_field("patronageYest"),
326            profit_today: retail_field("profitToday"),
327            profit_yest: retail_field("profitYest"),
328            complete_at: u.get("completeAt").and_then(Value::as_f64),
329            complete_at_raw: match u.get("completeAt") {
330                Some(v) if !v.is_number() => Some(v.clone()),
331                _ => None,
332            },
333            dirty_days: coerce_dirty_days(state, kind, u.get("dirtyDays")),
334            // Set from the save's `lobbyHeights` once every unit is read.
335            lobby_stories: None,
336        }
337        .without_mirrored_screen()
338        .boxed(),
339    };
340    Some((unit, sane_id(u.get("id"))))
341}