Add de-/serialization for World

3c1ce566939f54a0c8d5794033b4088c0c33cb91
This commit is contained in:
Tobias Berger 2022-09-07 00:44:41 +02:00
parent ba0cc9b571
commit 39ecfb3cc2
Signed by: toby
GPG key ID: 2D05EFAB764D6A88
7 changed files with 81 additions and 9 deletions

2
Cargo.lock generated
View file

@ -2067,6 +2067,8 @@ dependencies = [
"bevy", "bevy",
"noise", "noise",
"rand 0.8.5", "rand 0.8.5",
"ron",
"serde",
] ]
[[package]] [[package]]

View file

@ -20,4 +20,4 @@ default-features = false
[dependencies.bevy_pancam] [dependencies.bevy_pancam]
version = "0.6.1" version = "0.6.1"
optional = true optional = true

1
planet.ron Normal file

File diff suppressed because one or more lines are too long

View file

@ -18,3 +18,11 @@ version = "0.8.5"
[dependencies.bevy] [dependencies.bevy]
version = "0.8" version = "0.8"
default-features = false default-features = false
[dependencies.serde]
version = "1.0"
default-features = false
features = ["derive"]
[dependencies.ron]
version = "0.7.1"

View file

@ -1,3 +1,4 @@
use serde::{Deserialize, Serialize};
use std::{ use std::{
error::Error, error::Error,
f32::consts::{PI, TAU}, f32::consts::{PI, TAU},
@ -39,7 +40,7 @@ impl Display for WorldGenError {
} }
} }
#[derive(Clone)] #[derive(Clone, Deserialize, Serialize)]
pub struct World { pub struct World {
pub width: i32, pub width: i32,
pub height: i32, pub height: i32,
@ -48,6 +49,7 @@ pub struct World {
pub terrain: Vec<Vec<TerrainCell>>, pub terrain: Vec<Vec<TerrainCell>>,
continent_offsets: [Vec2; World::NUM_CONTINENTS as usize], continent_offsets: [Vec2; World::NUM_CONTINENTS as usize],
continent_widths: [f32; World::NUM_CONTINENTS as usize], continent_widths: [f32; World::NUM_CONTINENTS as usize],
#[serde(skip)]
perlin: Perlin, perlin: Perlin,
} }
impl Debug for World { impl Debug for World {
@ -73,20 +75,22 @@ impl Debug for World {
} }
} }
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct Biome { pub(crate) struct Biome {
pub altitude: f32, pub altitude: f32,
pub rainfall: f32, pub rainfall: f32,
pub temperature: f32, pub temperature: f32,
} }
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct TerrainCell { pub struct TerrainCell {
pub altitude: f32, pub altitude: f32,
pub rainfall: f32, pub rainfall: f32,
pub temperature: f32, pub temperature: f32,
#[serde(skip)]
pub rain_accumulated: f32, pub rain_accumulated: f32,
#[serde(skip)]
pub previous_rain_accumulated: f32, pub previous_rain_accumulated: f32,
} }

View file

@ -1,14 +1,20 @@
#[cfg(feature = "render")] #[cfg(feature = "render")]
use crate::TerrainCell; use crate::TerrainCell;
use crate::{World, WorldGenError}; use crate::{World, WorldGenError};
use bevy::log::error;
#[cfg(all(feature = "debug", feature = "render"))] #[cfg(all(feature = "debug", feature = "render"))]
use bevy::log::debug; use bevy::log::{debug, info};
#[cfg(feature = "render")] #[cfg(feature = "render")]
use bevy::{ use bevy::{
asset::HandleId, asset::HandleId,
render::{color::Color, texture::Image}, render::{color::Color, texture::Image},
}; };
use rand::random; use rand::random;
use std::{
fs::File,
io::{Read, Write},
path::Path,
};
#[derive(Debug)] #[derive(Debug)]
pub struct WorldManager { pub struct WorldManager {
@ -38,6 +44,43 @@ impl WorldManager {
} }
} }
pub fn save_world<P: AsRef<Path>>(&self, path: P) {
let world = match self.get_world() {
Some(world) => world,
None => {
info!("No world to save");
return;
}
};
let serialized = match ron::to_string(world) {
Ok(serialized) => serialized,
Err(err) => {
error!("Could not serialize world: {}", err);
return;
}
};
File::create(path).unwrap().write_all(serialized.as_bytes());
}
pub fn load_world<P: AsRef<Path>>(&mut self, path: P) {
let mut file = match File::open(path) {
Ok(file) => file,
Err(err) => {
error!("Could not open world file: {}", err);
return;
}
};
let mut buf = String::new();
file.read_to_string(&mut buf);
match ron::from_str(buf.as_str()) {
Ok(world) => self.world = Some(world),
Err(err) => {
error!("Could not deserialize world: {}", err);
return;
}
}
}
#[cfg(feature = "render")] #[cfg(feature = "render")]
pub fn toggle_rainfall(&mut self) { pub fn toggle_rainfall(&mut self) {
#[cfg(feature = "debug")] #[cfg(feature = "debug")]

View file

@ -149,9 +149,23 @@ fn handle_toolbar_button(
debug!("Toggling contours"); debug!("Toggling contours");
world_manager.toggle_contours(); world_manager.toggle_contours();
} }
ToolbarButton::GenerateWorld => todo!(), ToolbarButton::GenerateWorld => {
ToolbarButton::SaveWorld => todo!(), #[cfg(feature = "debug")]
ToolbarButton::LoadWorld => todo!(), debug!("Generating new world");
_ = world_manager
.new_world()
.expect("Failed to generate new world");
}
ToolbarButton::SaveWorld => {
#[cfg(feature = "debug")]
debug!("Saving world");
_ = world_manager.save_world("planet.ron");
}
ToolbarButton::LoadWorld => {
#[cfg(feature = "debug")]
debug!("Loading world");
_ = world_manager.load_world("planet.ron");
}
} }
refresh_world_texture(&mut images, &world_manager) refresh_world_texture(&mut images, &world_manager)
} }