1use std::collections::HashMap;
4use std::hash::{BuildHasherDefault, Hasher};
5
6use crate::section::{Section, block_index};
7
8pub const SECTIONS: usize = 16;
10
11pub const MIN_Y: i32 = 0;
13pub const MAX_Y: i32 = 256;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
18pub struct ChunkPos {
19 pub x: i32,
21 pub z: i32,
23}
24
25impl ChunkPos {
26 #[must_use]
28 pub const fn new(x: i32, z: i32) -> Self {
29 ChunkPos { x, z }
30 }
31
32 #[must_use]
34 pub const fn of_block(x: i32, z: i32) -> Self {
35 ChunkPos {
36 x: x >> 4,
37 z: z >> 4,
38 }
39 }
40}
41
42#[derive(Clone, Debug, Default)]
44#[non_exhaustive]
45pub enum Biomes {
46 #[default]
48 None,
49 Legacy(Box<[u8; 256]>),
51 Cells(Box<[u16; 1024]>),
54}
55
56#[derive(Clone, Debug)]
58pub struct SectionLight {
59 pub block: Box<[u8; 2048]>,
61 pub sky: Option<Box<[u8; 2048]>>,
63}
64
65impl SectionLight {
66 fn nibble(arr: &[u8; 2048], i: usize) -> u8 {
67 let b = arr[(i >> 1) & 2047];
68 if i & 1 == 0 { b & 15 } else { b >> 4 }
69 }
70}
71
72#[derive(Clone, Debug, Default)]
74pub struct Column {
75 pub(crate) sections: [Option<Section>; SECTIONS],
76 pub(crate) biomes: Biomes,
77 pub(crate) light: Option<Box<[Option<SectionLight>; SECTIONS]>>,
78 pub(crate) block_entities: Vec<(u16, BlockEntity)>,
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum BlockEntity {
86 Nbt {
90 action: u8,
92 nbt: bytes::Bytes,
94 },
95 Sign([Box<str>; 4]),
97}
98
99#[cfg_attr(
102 not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
103 allow(dead_code)
104)]
105pub(crate) fn put_nbt(
106 columns: &mut ColumnMap,
107 l: ghast_protocol::BlockPos,
108 action: u8,
109 nbt: Option<&ghast_protocol::nbt::RawNbt>,
110) -> crate::Applied {
111 let Some(nbt) = nbt.filter(|n| !n.is_end()) else {
112 return crate::Applied::Ignored;
113 };
114 if !(MIN_Y..MAX_Y).contains(&l.y) {
115 return crate::Applied::Ignored;
116 }
117 let Some(col) = columns.get_mut(l.x >> 4, l.z >> 4) else {
118 return crate::Applied::Ignored;
119 };
120 col.put_block_entity(
121 l.x,
122 l.y,
123 l.z,
124 BlockEntity::Nbt {
125 action,
126 nbt: bytes::Bytes::copy_from_slice(nbt.as_bytes()),
127 },
128 );
129 crate::Applied::Changed
130}
131
132#[inline]
134pub(crate) fn be_key(x: i32, y: i32, z: i32) -> u16 {
135 (((y & 0xFF) << 8) | ((z & 15) << 4) | (x & 15)) as u16
136}
137
138impl Column {
139 #[must_use]
141 pub fn empty() -> Self {
142 Column::default()
143 }
144
145 #[inline]
148 #[must_use]
149 pub fn raw(&self, x: i32, y: i32, z: i32) -> u16 {
150 if !(MIN_Y..MAX_Y).contains(&y) {
151 return 0;
152 }
153 match &self.sections[(y >> 4) as usize & (SECTIONS - 1)] {
154 Some(s) => s.get(block_index(x, y, z)),
155 None => 0,
156 }
157 }
158
159 pub fn set_raw(&mut self, x: i32, y: i32, z: i32, state: u16) {
161 if !(MIN_Y..MAX_Y).contains(&y) {
162 return;
163 }
164 let slot = &mut self.sections[(y >> 4) as usize & (SECTIONS - 1)];
165 let i = block_index(x, y, z);
166 match slot {
167 Some(s) => {
168 if !s.set(i, state) {
169 *slot = None;
170 }
171 }
172 None => *slot = Section::single(i, state),
173 }
174 }
175
176 pub fn block_entities(&self) -> impl Iterator<Item = ([u8; 3], &BlockEntity)> {
179 self.block_entities
180 .iter()
181 .map(|(k, b)| ([(k & 15) as u8, (k >> 8) as u8, ((k >> 4) & 15) as u8], b))
182 }
183
184 #[must_use]
186 pub fn block_entity(&self, x: i32, y: i32, z: i32) -> Option<&BlockEntity> {
187 if !(MIN_Y..MAX_Y).contains(&y) {
188 return None;
189 }
190 let k = be_key(x, y, z);
191 self.block_entities
192 .iter()
193 .find(|(key, _)| *key == k)
194 .map(|(_, b)| b)
195 }
196
197 #[cfg_attr(
198 not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
199 allow(dead_code)
200 )]
201 pub(crate) fn put_block_entity(&mut self, x: i32, y: i32, z: i32, be: BlockEntity) {
202 if !(MIN_Y..MAX_Y).contains(&y) {
203 return;
204 }
205 let k = be_key(x, y, z);
206 match self.block_entities.iter_mut().find(|(key, _)| *key == k) {
207 Some(slot) => slot.1 = be,
208 None => self.block_entities.push((k, be)),
209 }
210 }
211
212 #[cfg_attr(
213 not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
214 allow(dead_code)
215 )]
216 pub(crate) fn remove_block_entity(&mut self, x: i32, y: i32, z: i32) -> bool {
217 if !(MIN_Y..MAX_Y).contains(&y) {
218 return false;
219 }
220 let k = be_key(x, y, z);
221 let before = self.block_entities.len();
222 self.block_entities.retain(|(key, _)| *key != k);
223 before != self.block_entities.len()
224 }
225
226 #[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
228 pub(crate) fn remove_block_entities_in(&mut self, mask: u32) {
229 self.block_entities
230 .retain(|(k, _)| mask & (1 << (k >> 12)) == 0);
231 }
232
233 #[cfg_attr(
237 not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
238 allow(dead_code)
239 )]
240 pub(crate) fn set_raw_with(
241 &mut self,
242 x: i32,
243 y: i32,
244 z: i32,
245 state: u16,
246 same_block: fn(u16, u16) -> bool,
247 ) {
248 if !self.block_entities.is_empty() && !same_block(self.raw(x, y, z), state) {
249 self.remove_block_entity(x, y, z);
250 }
251 self.set_raw(x, y, z, state);
252 }
253
254 #[must_use]
256 pub fn section(&self, index: usize) -> Option<&Section> {
257 self.sections.get(index)?.as_ref()
258 }
259
260 #[must_use]
262 pub fn biomes(&self) -> &Biomes {
263 &self.biomes
264 }
265
266 #[must_use]
269 pub fn block_light(&self, x: i32, y: i32, z: i32) -> Option<u8> {
270 let l = self.light_section(y)?;
271 Some(SectionLight::nibble(&l.block, block_index(x, y, z)))
272 }
273
274 #[must_use]
276 pub fn sky_light(&self, x: i32, y: i32, z: i32) -> Option<u8> {
277 let l = self.light_section(y)?;
278 Some(SectionLight::nibble(
279 l.sky.as_deref()?,
280 block_index(x, y, z),
281 ))
282 }
283
284 fn light_section(&self, y: i32) -> Option<&SectionLight> {
285 if !(MIN_Y..MAX_Y).contains(&y) {
286 return None;
287 }
288 self.light.as_ref()?[(y >> 4) as usize].as_ref()
289 }
290
291 #[must_use]
293 pub fn section_count(&self) -> usize {
294 self.sections.iter().filter(|s| s.is_some()).count()
295 }
296
297 #[must_use]
299 pub fn heap_bytes(&self) -> usize {
300 let sections: usize = self
301 .sections
302 .iter()
303 .flatten()
304 .map(Section::heap_bytes)
305 .sum();
306 let biomes = match self.biomes {
307 Biomes::None => 0,
308 Biomes::Legacy(_) => 256,
309 Biomes::Cells(_) => 2048,
310 };
311 let light = self.light.as_ref().map_or(0, |l| {
312 size_of::<[Option<SectionLight>; SECTIONS]>()
313 + l.iter()
314 .flatten()
315 .map(|s| 2048 + s.sky.as_ref().map_or(0, |_| 2048))
316 .sum::<usize>()
317 });
318 let be = self.block_entities.capacity() * size_of::<(u16, BlockEntity)>()
319 + self
320 .block_entities
321 .iter()
322 .map(|(_, b)| match b {
323 BlockEntity::Nbt { nbt, .. } => nbt.len(),
324 BlockEntity::Sign(l) => l.iter().map(|s| s.len()).sum(),
325 })
326 .sum::<usize>();
327 sections + biomes + light + be
328 }
329}
330
331#[derive(Default, Clone, Copy)]
334pub(crate) struct ChunkHasher(u64);
335
336impl Hasher for ChunkHasher {
337 #[inline]
338 fn finish(&self) -> u64 {
339 let h = (self.0 ^ (self.0 >> 29)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
340 h ^ (h >> 32)
341 }
342
343 #[inline]
344 fn write(&mut self, bytes: &[u8]) {
345 for &b in bytes {
346 self.0 = (self.0 << 8) | u64::from(b);
347 }
348 }
349
350 #[inline]
351 fn write_u64(&mut self, v: u64) {
352 self.0 = v;
353 }
354}
355
356#[inline]
357fn key(x: i32, z: i32) -> u64 {
358 u64::from(x as u32) | (u64::from(z as u32) << 32)
359}
360
361#[inline]
363fn pos(key: u64) -> ChunkPos {
364 ChunkPos::new(key as u32 as i32, (key >> 32) as u32 as i32)
365}
366
367#[derive(Clone, Debug)]
370pub struct ColumnMap<C = Column> {
371 map: HashMap<u64, C, BuildHasherDefault<ChunkHasher>>,
374}
375
376impl<C> Default for ColumnMap<C> {
377 fn default() -> Self {
378 ColumnMap {
379 map: HashMap::default(),
380 }
381 }
382}
383
384impl<C> ColumnMap<C> {
385 #[inline]
387 #[must_use]
388 pub fn get(&self, cx: i32, cz: i32) -> Option<&C> {
389 self.map.get(&key(cx, cz))
390 }
391
392 #[inline]
394 pub fn get_mut(&mut self, cx: i32, cz: i32) -> Option<&mut C> {
395 self.map.get_mut(&key(cx, cz))
396 }
397
398 #[inline]
400 #[must_use]
401 pub fn contains(&self, cx: i32, cz: i32) -> bool {
402 self.map.contains_key(&key(cx, cz))
403 }
404
405 pub fn insert(&mut self, cx: i32, cz: i32, column: C) {
407 self.map.insert(key(cx, cz), column);
408 }
409
410 #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
412 pub(crate) fn replace(&mut self, cx: i32, cz: i32, column: C) -> Option<C> {
413 self.map.insert(key(cx, cz), column)
414 }
415
416 #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
418 pub(crate) fn take(&mut self, cx: i32, cz: i32) -> Option<C> {
419 self.map.remove(&key(cx, cz))
420 }
421
422 #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
424 pub(crate) fn drain(&mut self) -> impl Iterator<Item = C> + '_ {
425 self.map.drain().map(|(_, c)| c)
426 }
427
428 #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
430 pub(crate) fn extract(
431 &mut self,
432 mut keep: impl FnMut(ChunkPos) -> bool,
433 ) -> impl Iterator<Item = C> {
434 self.map
435 .extract_if(move |k, _| !keep(pos(*k)))
436 .map(|(_, c)| c)
437 }
438
439 pub fn remove(&mut self, cx: i32, cz: i32) -> bool {
441 self.map.remove(&key(cx, cz)).is_some()
442 }
443
444 pub fn clear(&mut self) {
446 self.map.clear();
447 }
448
449 pub fn retain(&mut self, mut keep: impl FnMut(ChunkPos) -> bool) {
451 self.map.retain(|k, _| keep(pos(*k)));
452 }
453
454 #[must_use]
456 pub fn len(&self) -> usize {
457 self.map.len()
458 }
459
460 #[must_use]
462 pub fn is_empty(&self) -> bool {
463 self.map.is_empty()
464 }
465
466 pub fn iter(&self) -> impl Iterator<Item = (ChunkPos, &C)> {
468 self.map.iter().map(|(k, c)| (pos(*k), c))
469 }
470
471 pub fn iter_mut(&mut self) -> impl Iterator<Item = (ChunkPos, &mut C)> {
473 self.map.iter_mut().map(|(k, c)| (pos(*k), c))
474 }
475
476 #[must_use]
478 pub fn table_bytes(&self) -> usize {
479 let capacity = self.map.capacity();
482 let buckets = if capacity == 0 {
483 0
484 } else {
485 (capacity * 8 / 7).next_power_of_two()
486 };
487 buckets * (size_of::<(u64, C)>() + 1)
488 }
489}
490
491impl ColumnMap<Column> {
492 #[inline]
494 #[must_use]
495 pub fn raw(&self, x: i32, y: i32, z: i32) -> Option<u16> {
496 self.get(x >> 4, z >> 4).map(|c| c.raw(x, y, z))
497 }
498
499 #[must_use]
501 pub fn heap_bytes(&self) -> usize {
502 self.table_bytes() + self.map.values().map(Column::heap_bytes).sum::<usize>()
503 }
504}
505
506#[cfg(test)]
507mod tests {
508 use super::*;
509
510 #[test]
511 fn set_and_drop_sections() {
512 let mut c = Column::empty();
513 c.set_raw(3, 70, 5, 16);
514 assert_eq!(c.raw(3, 70, 5), 16);
515 assert_eq!(
516 c.raw(3 + 16, 70, 5 - 32),
517 16,
518 "only low bits of x/z are used"
519 );
520 assert_eq!(c.section_count(), 1);
521 c.set_raw(3, 70, 5, 0);
522 assert_eq!(c.section_count(), 0);
523 c.set_raw(0, -1, 0, 16);
524 c.set_raw(0, 256, 0, 16);
525 assert_eq!(c.section_count(), 0);
526 assert_eq!(c.raw(0, -1, 0), 0);
527 }
528
529 #[test]
530 fn map_negative_coords() {
531 let mut m = ColumnMap::default();
532 let mut c = Column::empty();
533 c.set_raw(15, 0, 15, 7);
534 m.insert(-1, -1, c);
535 assert_eq!(m.raw(-1, 0, -1), Some(7));
536 assert_eq!(m.raw(0, 0, 0), None);
537 assert!(m.contains(-1, -1));
538 assert!(!m.contains(-1, 0));
539 }
540}