Skip to main content

voxel_framework/player/
persistence.rs

1//! Spawn-point persistence for the player.
2//!
3//! Saves and loads the player's spawn position to/from a JSON file
4//! (`player_data.json`) inside the world data directory.  The format is
5//! intentionally simple and hand-editable:
6//!
7//! ```json
8//! {"spawn_x": 8.0, "spawn_y": 60.0, "spawn_z": 8.0}
9//! ```
10//!
11//! # Contract
12//!
13//! * [`save_spawn_position`] creates or overwrites `{data_dir}/player_data.json`.
14//! * [`load_spawn_position`] returns `None` if the file is missing or
15//!   unparseable — callers should fall back to their configured default.
16//! * Both functions are infallible from the caller's perspective: errors are
17//!   logged with [`eprintln!`] but never propagate as panics.
18
19use bevy::prelude::*;
20use serde::{Deserialize, Serialize};
21
22// ─── On-disk format ──────────────────────────────────────────────────────────
23
24/// JSON representation of the player's persistent spawn point.
25#[derive(Serialize, Deserialize, Debug, Clone)]
26pub(crate) struct PlayerSaveData {
27    pub spawn_x: f32,
28    pub spawn_y: f32,
29    pub spawn_z: f32,
30}
31
32// ─── Public API ───────────────────────────────────────────────────────────────
33
34/// Saves the spawn position to `{data_dir}/player_data.json`.
35///
36/// Creates the directory and file if they do not exist; overwrites the file if
37/// it does.  Any I/O or serialisation error is logged with [`eprintln!`] and
38/// silently swallowed so that a disk failure never crashes the game.
39///
40/// # Examples
41///
42/// ```rust,no_run
43/// use bevy::prelude::*;
44/// use voxel_framework::player::persistence::save_spawn_position;
45///
46/// save_spawn_position(Vec3::new(8.0, 60.0, 8.0), "./worlds/survival");
47/// ```
48pub fn save_spawn_position(pos: Vec3, data_dir: &str) {
49    let data = PlayerSaveData {
50        spawn_x: pos.x,
51        spawn_y: pos.y,
52        spawn_z: pos.z,
53    };
54    let path = format!("{}/player_data.json", data_dir);
55    if let Err(e) = std::fs::create_dir_all(data_dir) {
56        eprintln!(
57            "[warn] Failed to create world data directory '{}': {}",
58            data_dir, e
59        );
60        return;
61    }
62    match serde_json::to_string(&data) {
63        Ok(json) => {
64            if let Err(e) = std::fs::write(&path, json) {
65                eprintln!("[warn] Failed to save spawn position to '{}': {}", path, e);
66            }
67        }
68        Err(e) => {
69            eprintln!("[warn] Failed to serialise spawn position: {}", e);
70        }
71    }
72}
73
74/// Loads the spawn position from `{data_dir}/player_data.json`.
75///
76/// Returns `None` if the file does not exist or cannot be parsed.  The caller
77/// should fall back to [`crate::player::PlayerConfig::spawn_position`] in that
78/// case.
79///
80/// # Examples
81///
82/// ```rust,no_run
83/// use voxel_framework::player::persistence::load_spawn_position;
84///
85/// if let Some(pos) = load_spawn_position("./worlds/survival") {
86///     println!("Loaded spawn: {:?}", pos);
87/// }
88/// ```
89pub fn load_spawn_position(data_dir: &str) -> Option<Vec3> {
90    let path = format!("{}/player_data.json", data_dir);
91    let json = std::fs::read_to_string(&path).ok()?;
92    let data: PlayerSaveData = match serde_json::from_str(&json) {
93        Ok(d) => d,
94        Err(e) => {
95            eprintln!("[warn] Failed to parse '{}': {}", path, e);
96            return None;
97        }
98    };
99    Some(Vec3::new(data.spawn_x, data.spawn_y, data.spawn_z))
100}
101
102// ─── Tests ───────────────────────────────────────────────────────────────────
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn roundtrip_serialise() {
110        let pos = Vec3::new(1.5, 64.0, -3.25);
111        let data = PlayerSaveData {
112            spawn_x: pos.x,
113            spawn_y: pos.y,
114            spawn_z: pos.z,
115        };
116        let json = serde_json::to_string(&data).unwrap();
117        let loaded: PlayerSaveData = serde_json::from_str(&json).unwrap();
118        assert_eq!(loaded.spawn_x, pos.x);
119        assert_eq!(loaded.spawn_y, pos.y);
120        assert_eq!(loaded.spawn_z, pos.z);
121    }
122}