map_editor/
camera.rs

1// TODO Huge hack -- this is just a copy of the map_gui file. I want to remove the dependency on
2// map_gui from map_editor, but this file really feels like it belongs there. I'm choosing faster
3// build time for map_editor over duplicate code, for now. :\
4
5use serde::{Deserialize, Serialize};
6
7use abstio::MapName;
8use abstutil::Timer;
9use widgetry::{Canvas, EventCtx};
10
11/// Represents the state of a widgetry Canvas.
12#[derive(Serialize, Deserialize, Debug)]
13pub struct CameraState {
14    cam_x: f64,
15    cam_y: f64,
16    cam_zoom: f64,
17}
18
19/// Track the last map used, to resume next session.
20#[derive(Serialize, Deserialize, Debug)]
21pub struct DefaultMap {
22    pub last_map: MapName,
23}
24
25impl CameraState {
26    /// Save the camera's configuration for the specified map, and also remember this map was the
27    /// last to be used.
28    pub fn save(canvas: &Canvas, name: &MapName) {
29        if name == &MapName::blank() {
30            return;
31        }
32
33        let state = CameraState {
34            cam_x: canvas.cam_x,
35            cam_y: canvas.cam_y,
36            cam_zoom: canvas.cam_zoom,
37        };
38        abstio::write_json(abstio::path_camera_state(name), &state);
39
40        abstio::write_json(
41            abstio::path_player("maps.json"),
42            &DefaultMap {
43                last_map: name.clone(),
44            },
45        );
46    }
47
48    /// Load the camera's configuration for the specified map. Returns true if successful, has no
49    /// effect if the file is missing or broken.
50    pub fn load(ctx: &mut EventCtx, name: &MapName) -> bool {
51        match abstio::maybe_read_json::<CameraState>(
52            abstio::path_camera_state(name),
53            &mut Timer::throwaway(),
54        ) {
55            Ok(ref loaded) => {
56                ctx.canvas.cam_x = loaded.cam_x;
57                ctx.canvas.cam_y = loaded.cam_y;
58                ctx.canvas.cam_zoom = loaded.cam_zoom;
59                true
60            }
61            Err(_) => false,
62        }
63    }
64}