use std::fs;
use std::io;
use std::path::Path;
use bevy::math::IVec3;
use super::storage::Chunk;
use super::{CHUNK_SIZE, CHUNK_VOLUME};
use crate::voxel::VoxelType;
pub fn save_chunk<V: VoxelType>(chunk: &Chunk<V>, path: impl AsRef<Path>) -> io::Result<()> {
let mut bytes = Vec::with_capacity(CHUNK_VOLUME * 2);
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
bytes.push(chunk.get(x, y, z).to_byte());
}
}
}
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
bytes.push(chunk.get_state(x, y, z));
}
}
}
fs::write(path, &bytes)
}
pub fn load_chunk<V: VoxelType>(path: impl AsRef<Path>) -> io::Result<Chunk<V>> {
let bytes = fs::read(path)?;
if bytes.len() < CHUNK_VOLUME {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
format!(
"chunk file too small: expected at least {} bytes, got {}",
CHUNK_VOLUME,
bytes.len()
),
));
}
let mut chunk = Chunk::<V>::new();
let mut i = 0;
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
chunk.set(x, y, z, V::from_byte(bytes[i]));
i += 1;
}
}
}
if bytes.len() >= CHUNK_VOLUME * 2 {
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
chunk.set_state(x, y, z, bytes[i]);
i += 1;
}
}
}
}
Ok(chunk)
}
pub fn chunk_filename(coord: IVec3) -> String {
format!("chunk_{}_{}_{}.bin", coord.x, coord.y, coord.z)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::voxel::DefaultVoxel;
fn temp_path(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(name)
}
#[test]
fn round_trip_save_load() {
let path = temp_path("test_round_trip_chunk.bin");
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(0, 0, 0, DefaultVoxel::Rock);
chunk.set(1, 2, 3, DefaultVoxel::IronOre);
chunk.set(15, 15, 15, DefaultVoxel::SiliconCrystal);
chunk.set(8, 4, 12, DefaultVoxel::RareMineral);
chunk.set(7, 7, 7, DefaultVoxel::Rock);
save_chunk(&chunk, &path).expect("save_chunk failed");
let loaded = load_chunk::<DefaultVoxel>(&path).expect("load_chunk failed");
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
assert_eq!(
chunk.get(x, y, z),
loaded.get(x, y, z),
"mismatch at ({x}, {y}, {z})"
);
}
}
}
let _ = fs::remove_file(&path);
}
#[test]
fn empty_chunk_round_trip() {
let path = temp_path("test_empty_chunk.bin");
let chunk = Chunk::<DefaultVoxel>::new();
save_chunk(&chunk, &path).expect("save_chunk failed");
let loaded = load_chunk::<DefaultVoxel>(&path).expect("load_chunk failed");
for x in 0..CHUNK_SIZE {
for y in 0..CHUNK_SIZE {
for z in 0..CHUNK_SIZE {
assert_eq!(loaded.get(x, y, z), DefaultVoxel::Air);
}
}
}
assert!(loaded.is_empty());
let _ = fs::remove_file(&path);
}
#[test]
fn chunk_filename_formatting() {
assert_eq!(chunk_filename(IVec3::new(1, 2, 3)), "chunk_1_2_3.bin");
assert_eq!(chunk_filename(IVec3::new(-5, 0, 10)), "chunk_-5_0_10.bin");
assert_eq!(chunk_filename(IVec3::new(0, 0, 0)), "chunk_0_0_0.bin");
assert_eq!(
chunk_filename(IVec3::new(-100, -200, -300)),
"chunk_-100_-200_-300.bin"
);
}
#[test]
fn load_too_small_file_returns_error() {
let path = temp_path("test_small_chunk.bin");
fs::write(&path, &[0u8; 100]).expect("write failed");
let result = load_chunk::<DefaultVoxel>(&path);
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
let _ = fs::remove_file(&path);
}
#[test]
fn load_nonexistent_file_returns_error() {
let path = temp_path("test_nonexistent_chunk_xyz.bin");
let result = load_chunk::<DefaultVoxel>(&path);
assert!(result.is_err());
}
}