Skip to main content

voxel_framework/world/
persistence.rs

1//! Chunk persistence integration — auto-save and disk-backed load.
2//!
3//! This module wires the low-level [`chunk::persistence`](crate::chunk::persistence) I/O into the Bevy
4//! game loop via two pieces:
5//!
6//! - [`PersistenceConfig`] — a [`Resource`] that controls where chunk files
7//!   live on disk and whether auto-save is enabled.
8//! - [`chunk_autosave_system`] — listens for [`ChunkModified`] messages and
9//!   saves the affected chunk to disk when [`PersistenceConfig::auto_save`] is
10//!   `true`.
11//! - [`try_load_chunk`] — a free function (not a system) that attempts to load
12//!   a chunk from disk; called by the generator pipeline before spawning an
13//!   async generation task.
14
15use std::path::PathBuf;
16
17use bevy::prelude::*;
18
19use crate::chunk::{Chunk, ChunkCoord, persistence as chunk_persistence};
20use crate::voxel::VoxelType;
21use crate::world::{ChunkManager, ChunkModified};
22
23// ─── WorldDataDir ─────────────────────────────────────────────────────────────
24
25/// Resource that holds the base data directory for the active world.
26///
27/// Set automatically by [`PersistencePlugin::with_world`] and
28/// [`PlayerPlugin::with_world`](crate::player::PlayerPlugin::with_world).  All world-specific files (chunks,
29/// `player_data.json`) are stored under this path:
30///
31/// ```text
32/// ./worlds/{world_name}/
33///   ├── chunks/
34///   │   └── chunk_X_Y_Z.bin
35///   └── player_data.json
36/// ```
37///
38/// The default value (`"./worlds/world"`) matches the default world name.
39#[derive(Resource, Clone, Debug)]
40pub struct WorldDataDir(pub String);
41
42impl Default for WorldDataDir {
43    fn default() -> Self {
44        Self("./worlds/world".to_string())
45    }
46}
47
48impl WorldDataDir {
49    /// Creates a `WorldDataDir` for the given world name.
50    pub fn for_world(world_name: &str) -> Self {
51        Self(format!("./worlds/{}", world_name))
52    }
53    /// Returns the directory path as a string slice.
54    pub fn as_str(&self) -> &str {
55        &self.0
56    }
57}
58
59// ─── PersistenceConfig ────────────────────────────────────────────────────────
60
61/// Configuration resource that controls chunk persistence behaviour.
62///
63/// Insert this resource before or after adding [`PersistencePlugin`] to
64/// override the defaults.
65///
66/// # Example
67///
68/// ```rust,no_run
69/// use bevy::prelude::*;
70/// use voxel_framework::world::PersistenceConfig;
71///
72/// App::new()
73///     .insert_resource(PersistenceConfig {
74///         save_dir: "./saves/chunks".to_string(),
75///         auto_save: true,
76///     });
77/// ```
78#[derive(Resource, Debug, Clone)]
79pub struct PersistenceConfig {
80    /// Directory where chunk binary files are stored.
81    ///
82    /// The directory is created automatically (including all parent
83    /// directories) the first time a chunk is saved.
84    ///
85    /// Default: `"./chunks"`.
86    pub save_dir: String,
87
88    /// When `true`, every [`ChunkModified`] event triggers a disk write for
89    /// the affected chunk.
90    ///
91    /// Default: `true`.
92    pub auto_save: bool,
93}
94
95impl Default for PersistenceConfig {
96    fn default() -> Self {
97        Self {
98            save_dir: "./worlds/world/chunks".to_string(),
99            auto_save: true,
100        }
101    }
102}
103
104// ─── try_load_chunk ───────────────────────────────────────────────────────────
105
106/// Attempts to load a chunk from disk.
107///
108/// Constructs the expected file path from `save_dir` and `coord`, then tries
109/// to read and deserialise it via [`load_chunk`](crate::chunk::persistence::load_chunk).
110///
111/// Returns `Some(chunk)` on success, `None` if the file does not exist or
112/// cannot be read.
113pub fn try_load_chunk<V: VoxelType>(coord: ChunkCoord, save_dir: &str) -> Option<Chunk<V>> {
114    let filename = chunk_persistence::chunk_filename(coord);
115    let path: PathBuf = [save_dir, &filename].iter().collect();
116
117    chunk_persistence::load_chunk::<V>(&path).ok()
118}
119
120// ─── chunk_autosave_system ────────────────────────────────────────────────────
121
122/// Saves modified chunks to disk when [`PersistenceConfig::auto_save`] is enabled.
123///
124/// For each [`ChunkModified`] message this system:
125/// 1. Resolves the chunk entity from [`ChunkManager`].
126/// 2. Queries the [`Chunk<V>`] component on that entity.
127/// 3. Constructs the output path from [`PersistenceConfig::save_dir`] and the
128///    chunk coordinate.
129/// 4. Ensures the save directory exists (`std::fs::create_dir_all`).
130/// 5. Writes the chunk data via [`save_chunk`](crate::chunk::persistence::save_chunk).
131///
132/// Errors are reported with `eprintln!` and do not panic.
133pub fn chunk_autosave_system<V: VoxelType>(
134    mut modified_reader: MessageReader<ChunkModified>,
135    config: Res<PersistenceConfig>,
136    manager: Res<ChunkManager>,
137    chunks: Query<&Chunk<V>>,
138) {
139    if !config.auto_save {
140        return;
141    }
142
143    for &ChunkModified(coord) in modified_reader.read() {
144        let Some(entity) = manager.get_entity(coord) else {
145            continue;
146        };
147
148        let Ok(chunk) = chunks.get(entity) else {
149            continue;
150        };
151
152        let filename = chunk_persistence::chunk_filename(coord);
153        let path: PathBuf = [config.save_dir.as_str(), &filename].iter().collect();
154
155        // Ensure the save directory exists.
156        if let Some(parent) = path.parent()
157            && let Err(e) = std::fs::create_dir_all(parent)
158        {
159            eprintln!(
160                "voxel-framework: failed to create chunk save directory '{}': {e}",
161                parent.display()
162            );
163            continue;
164        }
165
166        if let Err(e) = chunk_persistence::save_chunk(chunk, &path) {
167            eprintln!(
168                "voxel-framework: failed to save chunk {coord} to '{}': {e}",
169                path.display()
170            );
171        }
172    }
173}
174
175// ─── PersistencePlugin ────────────────────────────────────────────────────────
176
177/// Plugin that registers [`PersistenceConfig`] and the auto-save system.
178///
179/// The plugin is generic over the voxel type `V` so it can operate on any
180/// [`Chunk<V>`] component.
181///
182/// Users who want the default [`DefaultVoxel`] pipeline can add
183/// [`PersistencePlugin::<DefaultVoxel>::new()`].  Users with a custom voxel
184/// type add `PersistencePlugin::<MyVoxel>::new()`.
185///
186/// [`DefaultVoxel`]: crate::voxel::DefaultVoxel
187///
188/// # Example
189///
190/// ```rust,no_run
191/// use bevy::prelude::*;
192/// use voxel_framework::world::{PersistenceConfig, PersistencePlugin};
193/// use voxel_framework::voxel::DefaultVoxel;
194///
195/// App::new()
196///     .add_plugins(PersistencePlugin::<DefaultVoxel>::new());
197/// ```
198pub struct PersistencePlugin<V: VoxelType> {
199    _marker: std::marker::PhantomData<V>,
200    world_name: String,
201}
202
203impl<V: VoxelType> PersistencePlugin<V> {
204    /// Creates a `PersistencePlugin` using the default world name (`"world"`).
205    pub fn new() -> Self {
206        Self {
207            _marker: std::marker::PhantomData,
208            world_name: String::new(),
209        }
210    }
211
212    /// Creates a `PersistencePlugin` that saves chunks under
213    /// `./worlds/{world_name}/chunks/`.
214    ///
215    /// # Example
216    ///
217    /// ```rust,no_run
218    /// use bevy::prelude::*;
219    /// use voxel_framework::world::PersistencePlugin;
220    /// use voxel_framework::voxel::DefaultVoxel;
221    ///
222    /// App::new().add_plugins(PersistencePlugin::<DefaultVoxel>::with_world("survival"));
223    /// ```
224    pub fn with_world(world_name: impl Into<String>) -> Self {
225        Self {
226            _marker: std::marker::PhantomData,
227            world_name: world_name.into(),
228        }
229    }
230}
231
232impl<V: VoxelType> Default for PersistencePlugin<V> {
233    fn default() -> Self {
234        Self::new()
235    }
236}
237
238impl<V: VoxelType> Plugin for PersistencePlugin<V> {
239    fn build(&self, app: &mut App) {
240        let name = if self.world_name.is_empty() {
241            "world"
242        } else {
243            &self.world_name
244        };
245        let save_dir = format!("./worlds/{}/chunks", name);
246        app.insert_resource(PersistenceConfig {
247            save_dir,
248            auto_save: true,
249        });
250        app.add_systems(Update, chunk_autosave_system::<V>);
251    }
252}