Skip to main content

ghast_world/
column.rs

1//! Chunk columns and the column map.
2
3use std::collections::HashMap;
4use std::hash::{BuildHasherDefault, Hasher};
5
6use crate::section::{Section, block_index};
7
8/// Number of sections in a column (both 1.8 and 1.16.5 have a fixed 0..256 build height).
9pub const SECTIONS: usize = 16;
10
11/// Lowest block Y (inclusive).
12pub const MIN_Y: i32 = 0;
13/// Build height: highest block Y + 1.
14pub const MAX_Y: i32 = 256;
15
16/// Position of a chunk column (block coordinates `>> 4`).
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
18pub struct ChunkPos {
19    /// Chunk X (`block_x >> 4`).
20    pub x: i32,
21    /// Chunk Z (`block_z >> 4`).
22    pub z: i32,
23}
24
25impl ChunkPos {
26    /// Creates a chunk position.
27    #[must_use]
28    pub const fn new(x: i32, z: i32) -> Self {
29        ChunkPos { x, z }
30    }
31
32    /// The column containing block `(x, z)` (floor division by 16).
33    #[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/// Biome data of a column as the server sent it.
43#[derive(Clone, Debug, Default)]
44#[non_exhaustive]
45pub enum Biomes {
46    /// Not received (partial chunk only so far) or not kept ([`crate::WorldConfig::biomes`]).
47    #[default]
48    None,
49    /// 1.8: one biome id per (x, z), index `z << 4 | x`.
50    Legacy(Box<[u8; 256]>),
51    /// 1.16.5: one biome id per 4×4×4 cell, index `(y >> 2) << 4 | (z >> 2) << 2 | (x >> 2)`
52    /// (vanilla `BiomeArray`). Ids that do not fit `u16` are stored as `u16::MAX`.
53    Cells(Box<[u16; 1024]>),
54}
55
56/// 1.8 light of one section, as sent in the chunk packet (never recomputed locally).
57#[derive(Clone, Debug)]
58pub struct SectionLight {
59    /// Block light nibbles, index [`block_index`] (low nibble = even index).
60    pub block: Box<[u8; 2048]>,
61    /// Sky light nibbles (`None` in dimensions without sky).
62    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/// A loaded chunk column: 16 sections (`None` = all air), biomes and optional light.
73#[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    /// Block entities by [`be_key`] (only with [`crate::WorldConfig::block_entities`]).
79    pub(crate) block_entities: Vec<(u16, BlockEntity)>,
80}
81
82/// A block entity's data as the server sent it.
83#[derive(Clone, Debug, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum BlockEntity {
86    /// Raw NBT compound (a private copy, never a view into a packet buffer). `action` is the
87    /// `tile_entity_data` action (1.8: 1 spawner, 2 command block, 3 beacon, 4 skull, 5 flower
88    /// pot, 6 banner; 1.16 adds 7..15, 9 = sign), or 0 for the block entity list of a 1.16 chunk.
89    Nbt {
90        /// Update action.
91        action: u8,
92        /// The NBT bytes (`TAG_Compound` root).
93        nbt: bytes::Bytes,
94    },
95    /// 1.8 `update_sign`: the four lines as raw chat JSON.
96    Sign([Box<str>; 4]),
97}
98
99/// Stores a `tile_entity_data` / chunk block entity NBT payload (both versions): ignored for
100/// unloaded columns, `y` outside `0..256` and the "no compound" value.
101#[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/// Column-local key of a block position: `y << 8 | z << 4 | x` (`y` in `0..256`).
133#[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    /// An all-air column.
140    #[must_use]
141    pub fn empty() -> Self {
142        Column::default()
143    }
144
145    /// Raw state at column-local `x`, `z` (only the low four bits are used) and world `y`.
146    /// `y` outside `0..256` is air (0), as in vanilla.
147    #[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    /// Sets the raw state at column-local `x`, `z` and world `y` (ignored outside `0..256`).
160    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    /// Block entities as `([x, y, z] column-local, data)`, in arrival order. Empty unless
177    /// [`crate::WorldConfig::block_entities`] is on.
178    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    /// The block entity at column-local `x`, `z` (low four bits) and world `y`.
185    #[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    /// Drops the block entities in the sections of `mask` (bit = section index).
227    #[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    /// Sets a block like [`Column::set_raw`] and drops the block entity there when the block
234    /// type changes (`same_block(old, new)` is the version's block-type comparison), as vanilla
235    /// does.
236    #[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    /// The section at index `0..16` (`y >> 4`); `None` when it is all air.
255    #[must_use]
256    pub fn section(&self, index: usize) -> Option<&Section> {
257        self.sections.get(index)?.as_ref()
258    }
259
260    /// Biomes as received.
261    #[must_use]
262    pub fn biomes(&self) -> &Biomes {
263        &self.biomes
264    }
265
266    /// 1.8 block light at column-local `x`, `z` and world `y`, when light is kept and the section
267    /// was sent. Light is never recomputed after block changes.
268    #[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    /// 1.8 sky light (see [`Column::block_light`]); `None` also in dimensions without sky.
275    #[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    /// Number of non-empty sections.
292    #[must_use]
293    pub fn section_count(&self) -> usize {
294        self.sections.iter().filter(|s| s.is_some()).count()
295    }
296
297    /// Heap bytes owned by this column (sections, biomes, light), excluding the map entry.
298    #[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/// Hasher for packed chunk positions: one multiply plus a fold, so both halves reach the low
332/// bits that pick the bucket.
333#[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/// The position a [`key`] was made from.
362#[inline]
363fn pos(key: u64) -> ChunkPos {
364    ChunkPos::new(key as u32 as i32, (key >> 32) as u32 as i32)
365}
366
367/// The loaded columns. Version-independent; the version worlds wrap it. `C` is the column
368/// type (the legacy [`Column`] by default; the modern worlds use their own).
369#[derive(Clone, Debug)]
370pub struct ColumnMap<C = Column> {
371    /// By packed position ([`key`]); the table holds nothing else per column, so a slot is the
372    /// key plus the column.
373    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    /// The column at `(cx, cz)` if loaded.
386    #[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    /// Mutable access to a loaded column.
393    #[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    /// `true` when the column has been received and not unloaded.
399    #[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    /// Inserts (replaces) a column.
406    pub fn insert(&mut self, cx: i32, cz: i32, column: C) {
407        self.map.insert(key(cx, cz), column);
408    }
409
410    /// Inserts a column and returns the one it replaced.
411    #[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    /// Removes and returns a column.
417    #[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    /// Removes and returns every column.
423    #[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    /// Removes and returns the columns for which `keep` returns `false`.
429    #[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    /// Removes a column; `true` if it was loaded.
440    pub fn remove(&mut self, cx: i32, cz: i32) -> bool {
441        self.map.remove(&key(cx, cz)).is_some()
442    }
443
444    /// Unloads everything.
445    pub fn clear(&mut self) {
446        self.map.clear();
447    }
448
449    /// Keeps only the columns for which `keep` returns `true`.
450    pub fn retain(&mut self, mut keep: impl FnMut(ChunkPos) -> bool) {
451        self.map.retain(|k, _| keep(pos(*k)));
452    }
453
454    /// Number of loaded columns.
455    #[must_use]
456    pub fn len(&self) -> usize {
457        self.map.len()
458    }
459
460    /// `true` when no column is loaded.
461    #[must_use]
462    pub fn is_empty(&self) -> bool {
463        self.map.is_empty()
464    }
465
466    /// Iterates the loaded columns (arbitrary order).
467    pub fn iter(&self) -> impl Iterator<Item = (ChunkPos, &C)> {
468        self.map.iter().map(|(k, c)| (pos(*k), c))
469    }
470
471    /// Iterates the loaded columns mutably (arbitrary order).
472    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    /// Heap bytes of the hash table itself (entries included, column contents excluded).
477    #[must_use]
478    pub fn table_bytes(&self) -> usize {
479        // The table has a power of two of buckets and fills at most 7/8 of them (`capacity`
480        // is that usable part); each bucket is a slot plus a control byte.
481        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    /// Raw state at a block position; `None` when the column is not loaded.
493    #[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    /// Approximate heap bytes: columns plus the hash table.
500    #[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}