use std::collections::HashMap; use fastnbt::LongArray; use serde::{Deserialize, Serialize}; use crate::{ block::block_registry::BlockId, coordinates::{ChunkCoordinates, ChunkRelativeBlockCoordinates}, level::WorldError, WORLD_HEIGHT, }; pub struct ChunkData { pub blocks: Box<[BlockId; 16 * 16 * WORLD_HEIGHT]>, pub position: ChunkCoordinates, pub heightmaps: ChunkHeightmaps, } #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "PascalCase")] struct PaletteEntry { name: String, properties: Option>, } #[derive(Deserialize, Debug, Clone)] struct ChunkSectionBlockStates { data: Option, palette: Vec, } #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "UPPERCASE")] pub struct ChunkHeightmaps { motion_blocking: LongArray, world_surface: LongArray, } #[derive(Deserialize, Debug)] #[allow(dead_code)] struct ChunkSection { #[serde(rename = "Y")] y: i32, block_states: Option, } #[derive(Deserialize, Debug)] #[allow(dead_code)] struct ChunkNbt { #[serde(rename = "DataVersion")] data_version: usize, sections: Vec, #[serde(rename = "Heightmaps")] heightmaps: ChunkHeightmaps, } impl ChunkData { pub fn from_bytes(chunk_data: Vec, at: ChunkCoordinates) -> Result { let chunk_data = match fastnbt::from_bytes::(chunk_data.as_slice()) { Ok(v) => v, Err(err) => return Err(WorldError::ErrorDeserializingChunk(err.to_string())), }; // this needs to be boxed, otherwise it will cause a stack-overflow let mut blocks = Box::new([BlockId::default(); 16 * 16 * WORLD_HEIGHT]); for (k, section) in chunk_data.sections.into_iter().enumerate() { let block_states = match section.block_states { Some(states) => states, None => continue, // this should instead fill all blocks with the only element of the palette }; let palette = block_states .palette .iter() .map(|entry| BlockId::new(&entry.name, entry.properties.as_ref())) .collect::, _>>()?; let block_data = match block_states.data { None => continue, Some(d) => d, } .into_inner(); let block_bit_size = { let size = 64 - (palette.len() as i64 - 1).leading_zeros(); if size >= 4 { size } else { 4 } }; let mask = (1 << block_bit_size) - 1; let mut blocks_left = 16 * 16 * 16; 'block_loop: for (j, block) in block_data.iter().enumerate() { for i in 0..64 / block_bit_size { if blocks_left <= 0 { break 'block_loop; } let index = (block >> (i * block_bit_size)) & mask; let block = palette[index as usize]; blocks[k * 16 * 16 * 16 + j * ((64 / block_bit_size) as usize) + i as usize] = block; blocks_left -= 1; } } } Ok(ChunkData { blocks, position: at, heightmaps: chunk_data.heightmaps, }) } /// Sets the given block in the chunk, returning the old block pub fn set_block( &mut self, at: ChunkRelativeBlockCoordinates, block_id: BlockId, ) -> Result { Ok(std::mem::replace( &mut self.blocks [(at.y.get_absolute() * 16 * 16 + *at.z as u16 * 16 + *at.x as u16) as usize], block_id, )) } }