Fixed loading world, added saving meta data

This commit is contained in:
Piotrek
2021-05-09 16:27:04 +02:00
parent d0b7a781b4
commit 23d702ad6c
5 changed files with 105 additions and 36 deletions
+38 -7
View File
@@ -1,20 +1,23 @@
mod generator;
pub mod chunk;
pub mod block;
use linked_hash_map::LinkedHashMap;
use std::path::PathBuf;
use std::path::Path;
use std::io::Write;
use std::io::Read;
use std::fs;
use cgmath::Point3;
use cgmath::{Point3, InnerSpace};
use std::collections::HashMap;
use generator::WorldGen;
use chunk::WorldChunk;
use block::WorldBlock;
use yaml_rust::{Yaml, YamlLoader, YamlEmitter};
pub struct World {
name: String,
chunks: HashMap<Point3<u32>, WorldChunk>
chunks: HashMap<Point3<u32>, WorldChunk>,
}
impl World {
@@ -22,10 +25,23 @@ impl World {
pub fn new(name: String) -> Self {
Self {
name,
chunks: HashMap::new()
chunks: HashMap::new(),
}
}
pub fn all_blocks(&self) -> Vec<(Point3<u32>, &WorldBlock)> {
self.chunks.iter().map(|(chunk_pos, chunk)| {
let off = chunk_pos * chunk::SIZE as u32;
let result: Vec<(Point3<u32>, &WorldBlock)> = chunk.all_blocks().iter().map(|(pos, block)| {
(
Point3{x: off.x+pos.x, y: off.y+pos.y, z: off.z+pos.z},
*block
)
}).collect();
result
}).flatten().collect()
}
pub fn save(&self) {
// Get directory
let mut dir = dirs::data_local_dir().unwrap();
@@ -41,6 +57,18 @@ impl World {
let mut file = fs::File::create(path).expect("Failed to create file");
file.write(&bytes).unwrap();
}
// Save metadata
let mut data: LinkedHashMap<Yaml, Yaml> = LinkedHashMap::new();
data.insert(Yaml::String("name".to_string()), Yaml::String(self.name.clone()));
let mut data_str = String::new();
let mut emit = YamlEmitter::new(&mut data_str);
emit.dump(&Yaml::Hash(data)).expect("Failed to encode yaml");
let data_path: PathBuf = [dir.to_str().unwrap(), "world.yml"].iter().collect();
let mut data_file = fs::File::create(data_path).unwrap();
data_file.write_all(data_str.as_bytes()).expect("Failed to write");
}
pub fn load(&mut self) {
@@ -74,12 +102,15 @@ impl World {
println!("loaded {:?}", pos);
self.chunks.insert(pos, chunk);
}
// Load metadata
}
pub fn gen_block(&mut self, block_pos: &Point3<u32>) -> &WorldBlock {
// Split world space to chunk and block space
let ch_pos = block_pos / chunk::SIZE;
let bl_pos = block_pos % chunk::SIZE;
let ch_pos = block_pos / chunk::SIZE as u32;
let bl_pos = block_pos % chunk::SIZE as u32;
// Create chunk if does not exist
if let None = self.chunks.get(&ch_pos) {
self.chunks.insert(block_pos.clone(), WorldChunk::new());
@@ -94,8 +125,8 @@ impl World {
#[allow(unused)]
pub fn get_block(&mut self, block_pos: &Point3<u32>) -> Option<&WorldBlock> {
// Split world space to chunk and block space
let ch_pos = block_pos / chunk::SIZE;
let bl_pos = block_pos % chunk::SIZE;
let ch_pos = block_pos / chunk::SIZE as u32;
let bl_pos = block_pos % chunk::SIZE as u32;
// Return block if exists
if let Some(chunk) = self.chunks.get_mut(&ch_pos) {
return Some(chunk.get_block(&bl_pos));