handling chunk decompresion errors

This commit is contained in:
Piotrek
2021-05-18 09:20:15 +02:00
parent 688405a579
commit 5a62d8c70d
2 changed files with 16 additions and 11 deletions
+3 -3
View File
@@ -37,7 +37,7 @@ impl WorldChunk {
} }
} }
pub fn from_bytes(bytes: Vec<u8>) -> Self { pub fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
let mut instance = Self::new(); let mut instance = Self::new();
// Header // Header
@@ -58,7 +58,7 @@ impl WorldChunk {
let mut block_bytes = vec![0_u8; num_blocks*block::SIZE_QB]; let mut block_bytes = vec![0_u8; num_blocks*block::SIZE_QB];
if lz4::decompress(&block_bytes_compressed, &mut block_bytes[0..num_blocks*block::SIZE_QB]).is_err() { if lz4::decompress(&block_bytes_compressed, &mut block_bytes[0..num_blocks*block::SIZE_QB]).is_err() {
println!("Decompression failed"); println!("Decompression failed");
num_blocks = 0; return None;
} }
for i in 0..num_blocks { for i in 0..num_blocks {
@@ -68,7 +68,7 @@ impl WorldChunk {
instance.blocks.push(block); instance.blocks.push(block);
} }
instance Some(instance)
} }
pub fn to_bytes(&self) -> Vec<u8> { pub fn to_bytes(&self) -> Vec<u8> {
+12 -7
View File
@@ -28,7 +28,7 @@ impl ChunkLoader {
// Figure out number of workers // Figure out number of workers
let mut n = num_cpus::get_physical(); let mut n = num_cpus::get_physical();
n = min(max(n / 2, 2), 4); n = max((n as f64 * 0.66).round() as usize, 1);
// Spawn n workers // Spawn n workers
for _ in 0..n { for _ in 0..n {
@@ -87,15 +87,20 @@ impl ChunkLoader {
let filepath = dirs::data_local_dir().unwrap().join("Voxelgame").join("saves").join(&name).join(filename); let filepath = dirs::data_local_dir().unwrap().join("Voxelgame").join("saves").join(&name).join(filename);
if filepath.is_file() { if filepath.is_file() {
let mut buff = Vec::new(); let mut buff = Vec::new();
let mut file = fs::File::open(filepath).expect("Failed to open chunk file"); let mut file = fs::File::open(&filepath).expect("Failed to open chunk file");
file.read_to_end(&mut buff).expect("Failed to read chunk file"); file.read_to_end(&mut buff).expect("Failed to read chunk file");
let chunk = WorldChunk::from_bytes(buff);
// send // Create chunk from bytes
if let Err(_) = tx.send((pos, chunk)) { if let Some(chunk) = WorldChunk::from_bytes(buff) {
break; // Send it to channel
if let Err(_) = tx.send((pos, chunk)) {
break;
}
// Process next chunk
continue;
} }
continue;
// Generate if from_bytes failed
} }
// Try generating chunk // Try generating chunk