use std::path::PathBuf;
use bevy::prelude::*;
use crate::chunk::{Chunk, ChunkCoord, persistence as chunk_persistence};
use crate::voxel::VoxelType;
use crate::world::{ChunkManager, ChunkModified};
#[derive(Resource, Clone, Debug)]
pub struct WorldDataDir(pub String);
impl Default for WorldDataDir {
fn default() -> Self {
Self("./worlds/world".to_string())
}
}
impl WorldDataDir {
pub fn for_world(world_name: &str) -> Self {
Self(format!("./worlds/{}", world_name))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Resource, Debug, Clone)]
pub struct PersistenceConfig {
pub save_dir: String,
pub auto_save: bool,
}
impl Default for PersistenceConfig {
fn default() -> Self {
Self {
save_dir: "./worlds/world/chunks".to_string(),
auto_save: true,
}
}
}
pub fn try_load_chunk<V: VoxelType>(coord: ChunkCoord, save_dir: &str) -> Option<Chunk<V>> {
let filename = chunk_persistence::chunk_filename(coord);
let path: PathBuf = [save_dir, &filename].iter().collect();
chunk_persistence::load_chunk::<V>(&path).ok()
}
pub fn chunk_autosave_system<V: VoxelType>(
mut modified_reader: MessageReader<ChunkModified>,
config: Res<PersistenceConfig>,
manager: Res<ChunkManager>,
chunks: Query<&Chunk<V>>,
) {
if !config.auto_save {
return;
}
for &ChunkModified(coord) in modified_reader.read() {
let Some(entity) = manager.get_entity(coord) else {
continue;
};
let Ok(chunk) = chunks.get(entity) else {
continue;
};
let filename = chunk_persistence::chunk_filename(coord);
let path: PathBuf = [config.save_dir.as_str(), &filename].iter().collect();
if let Some(parent) = path.parent()
&& let Err(e) = std::fs::create_dir_all(parent)
{
eprintln!(
"voxel-framework: failed to create chunk save directory '{}': {e}",
parent.display()
);
continue;
}
if let Err(e) = chunk_persistence::save_chunk(chunk, &path) {
eprintln!(
"voxel-framework: failed to save chunk {coord} to '{}': {e}",
path.display()
);
}
}
}
pub struct PersistencePlugin<V: VoxelType> {
_marker: std::marker::PhantomData<V>,
world_name: String,
}
impl<V: VoxelType> PersistencePlugin<V> {
pub fn new() -> Self {
Self {
_marker: std::marker::PhantomData,
world_name: String::new(),
}
}
pub fn with_world(world_name: impl Into<String>) -> Self {
Self {
_marker: std::marker::PhantomData,
world_name: world_name.into(),
}
}
}
impl<V: VoxelType> Default for PersistencePlugin<V> {
fn default() -> Self {
Self::new()
}
}
impl<V: VoxelType> Plugin for PersistencePlugin<V> {
fn build(&self, app: &mut App) {
let name = if self.world_name.is_empty() {
"world"
} else {
&self.world_name
};
let save_dir = format!("./worlds/{}/chunks", name);
app.insert_resource(PersistenceConfig {
save_dir,
auto_save: true,
});
app.add_systems(Update, chunk_autosave_system::<V>);
}
}