1pub mod partial;
2pub mod storage;
3
4use std::{
5 collections::HashMap,
6 fmt::Debug,
7 io,
8 io::{Cursor, Write},
9};
10
11use azalea_block::block_state::{BlockState, BlockStateIntegerRepr};
12use azalea_buf::{AzBuf, BufReadError};
13use azalea_core::{
14 heightmap_kind::HeightmapKind,
15 position::{ChunkBiomePos, ChunkBlockPos, ChunkSectionBiomePos, ChunkSectionBlockPos},
16};
17use tracing::warn;
18
19use crate::{biome_id::BiomeId, heightmap::Heightmap, palette::PalettedContainer};
20
21const SECTION_HEIGHT: u32 = 16;
22
23#[derive(Debug)]
31pub struct Chunk {
32 pub sections: Box<[Section]>,
33 pub heightmaps: HashMap<HeightmapKind, Heightmap>,
37}
38
39#[derive(Clone, Debug, Default, PartialEq)]
41pub struct Section {
42 pub block_count: u16,
48 pub fluid_count: u16,
52 pub states: PalettedContainer<BlockState>,
53 pub biomes: PalettedContainer<BiomeId>,
54}
55
56pub fn calculate_chunk_storage_range(view_distance: u32) -> u32 {
60 u32::max(view_distance, 2) + 3
61}
62
63impl Default for Chunk {
64 fn default() -> Self {
65 Chunk {
66 sections: vec![Section::default(); (384 / 16) as usize].into(),
67 heightmaps: HashMap::new(),
68 }
69 }
70}
71
72impl Chunk {
73 pub fn read_with_dimension_height(
74 ctx: azalea_buf::Ctx,
75 buf: &mut Cursor<&[u8]>,
76 dimension_height: u32,
77 min_y: i32,
78 heightmaps_data: &[(HeightmapKind, Box<[u64]>)],
79 ) -> Result<Self, BufReadError> {
80 let section_count = dimension_height / SECTION_HEIGHT;
81 let mut sections = Vec::with_capacity(section_count as usize);
82 for _ in 0..section_count {
83 let section = Section::azalea_read(ctx, buf)?;
84 sections.push(section);
85 }
86 let sections = sections.into_boxed_slice();
87
88 let mut heightmaps = HashMap::new();
89 for (kind, data) in heightmaps_data {
90 let data = data.clone();
91 let heightmap = Heightmap::new(*kind, dimension_height, min_y, data);
92 heightmaps.insert(*kind, heightmap);
93 }
94
95 Ok(Chunk {
96 sections,
97 heightmaps,
98 })
99 }
100
101 pub fn get_block_state(&self, pos: &ChunkBlockPos, min_y: i32) -> Option<BlockState> {
102 get_block_state_from_sections(&self.sections, pos, min_y)
103 }
104
105 #[must_use = "Use Chunk::set_block_state instead if you don't need the previous state"]
106 pub fn get_and_set_block_state(
107 &mut self,
108 pos: &ChunkBlockPos,
109 state: BlockState,
110 min_y: i32,
111 ) -> BlockState {
112 let section_index = section_index(pos.y, min_y);
113 let Some(section) = self.sections.get_mut(section_index as usize) else {
114 warn!(
115 "Tried to get and set block state {state:?} at out-of-bounds relative chunk position {pos:?}",
116 );
117 return BlockState::AIR;
118 };
119 let chunk_section_pos = ChunkSectionBlockPos::from(pos);
120 let previous_state = section.get_and_set_block_state(chunk_section_pos, state);
121
122 for heightmap in self.heightmaps.values_mut() {
123 heightmap.update(pos, state, &self.sections);
124 }
125
126 previous_state
127 }
128
129 pub fn set_block_state(&mut self, pos: &ChunkBlockPos, state: BlockState, min_y: i32) {
130 let section_index = section_index(pos.y, min_y);
131 let Some(section) = self.sections.get_mut(section_index as usize) else {
132 warn!(
133 "Tried to set block state {state:?} at out-of-bounds relative chunk position {pos:?}",
134 );
135 return;
136 };
137 let chunk_section_pos = ChunkSectionBlockPos::from(pos);
138 section.get_and_set_block_state(chunk_section_pos, state);
139
140 for heightmap in self.heightmaps.values_mut() {
141 heightmap.update(pos, state, &self.sections);
142 }
143 }
144
145 pub fn get_biome_id(&self, pos: ChunkBiomePos, min_y: i32) -> Option<BiomeId> {
148 if pos.y < min_y {
149 return None;
151 }
152 let section_index = section_index(pos.y, min_y);
153 let Some(section) = self.sections.get(section_index as usize) else {
154 warn!("Tried to get biome at out-of-bounds relative chunk position {pos:?}",);
155 return None;
156 };
157 let chunk_section_pos = ChunkSectionBiomePos::from(pos);
158 Some(section.get_biome_id(chunk_section_pos))
159 }
160}
161
162#[inline]
165pub fn get_block_state_from_sections(
166 sections: &[Section],
167 pos: &ChunkBlockPos,
168 min_y: i32,
169) -> Option<BlockState> {
170 if pos.y < min_y {
171 return None;
173 }
174 let section_index = section_index(pos.y, min_y) as usize;
175 if section_index >= sections.len() {
176 return None;
178 };
179 let section = §ions[section_index];
180
181 let chunk_section_pos = ChunkSectionBlockPos::from(pos);
182 Some(section.get_block_state(chunk_section_pos))
183}
184
185impl AzBuf for Section {
186 fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
187 let block_count = u16::azalea_read(ctx, buf)?;
188 let fluid_count = u16::azalea_read(ctx, buf)?;
189
190 let states = PalettedContainer::<BlockState>::read(ctx, buf)?;
198
199 for i in 0..states.storage.size() {
200 if !BlockState::is_valid_state(states.storage.get(i) as BlockStateIntegerRepr) {
201 return Err(BufReadError::custom(format!(
202 "Invalid block state {} (index {i}) found in section.",
203 states.storage.get(i)
204 )));
205 }
206 }
207
208 let biomes = PalettedContainer::<BiomeId>::read(ctx, buf)?;
209 Ok(Section {
210 block_count,
211 fluid_count,
212 states,
213 biomes,
214 })
215 }
216 fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
217 self.block_count.azalea_write(ctx, buf)?;
218 self.fluid_count.azalea_write(ctx, buf)?;
219 self.states.write(ctx, buf)?;
220 self.biomes.write(ctx, buf)?;
221 Ok(())
222 }
223}
224
225impl Section {
226 pub fn get_block_state(&self, pos: ChunkSectionBlockPos) -> BlockState {
227 self.states.get(pos)
228 }
229 pub fn get_and_set_block_state(
230 &mut self,
231 pos: ChunkSectionBlockPos,
232 state: BlockState,
233 ) -> BlockState {
234 let previous_state = self.states.get_and_set(pos, state);
235
236 if previous_state.is_air() && !state.is_air() {
237 self.block_count += 1;
238 } else if !previous_state.is_air() && state.is_air() {
239 self.block_count -= 1;
240 }
241
242 previous_state
243 }
244
245 pub fn get_biome_id(&self, pos: ChunkSectionBiomePos) -> BiomeId {
246 self.biomes.get(pos)
247 }
248 pub fn set_biome_id(&mut self, pos: ChunkSectionBiomePos, biome: BiomeId) {
249 self.biomes.set(pos, biome);
250 }
251 pub fn get_and_set_biome_id(&mut self, pos: ChunkSectionBiomePos, biome: BiomeId) -> BiomeId {
252 self.biomes.get_and_set(pos, biome)
253 }
254}
255
256#[inline]
259pub fn section_index(y: i32, min_y: i32) -> u32 {
260 if y < min_y {
261 #[cfg(debug_assertions)]
262 tracing::warn!("y ({y}) must be at least {min_y}");
263 #[cfg(not(debug_assertions))]
264 tracing::trace!("y ({y}) must be at least {min_y}")
265 };
266 let min_section_index = min_y >> 4;
267 ((y >> 4) - min_section_index) as u32
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273 use crate::palette::SectionPos;
274
275 #[test]
276 fn test_section_index() {
277 assert_eq!(section_index(0, 0), 0);
278 assert_eq!(section_index(128, 0), 8);
279 assert_eq!(section_index(127, 0), 7);
280 assert_eq!(section_index(0, -64), 4);
281 assert_eq!(section_index(-64, -64), 0);
282 assert_eq!(section_index(-49, -64), 0);
283 assert_eq!(section_index(-48, -64), 1);
284 assert_eq!(section_index(128, -64), 12);
285 }
286
287 #[test]
288 fn serialize_and_deserialize_section() {
289 let mut states = PalettedContainer::new();
290
291 states.set(
292 SectionPos::new(1, 2, 3),
293 BlockState::try_from(BlockState::MAX_STATE).unwrap(),
294 );
295 states.set(
296 SectionPos::new(4, 5, 6),
297 BlockState::try_from(BlockState::MAX_STATE).unwrap(),
298 );
299 let biomes = PalettedContainer::new();
300 let section = Section {
301 block_count: 2,
302 fluid_count: 0,
303 states,
304 biomes,
305 };
306
307 let mut buf = Vec::new();
308 section.azalea_write(Default::default(), &mut buf).unwrap();
309
310 let mut cur = Cursor::new(buf.as_slice());
311 let deserialized_section = Section::azalea_read(Default::default(), &mut cur).unwrap();
312 assert_eq!(cur.position(), buf.len() as u64);
313
314 assert_eq!(section, deserialized_section);
315 }
316}