ghast-world 0.5.4

Chunk storage for the ghast Minecraft Java Edition client library: compact, O(1) block lookup, explicit loaded/unloaded columns, decoding of 1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3 chunk and block-change packets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! The 26.1 (protocol 775, 26.1 – 26.1.2) world: dimension heights from the configuration-phase
//! registries, compact paletted sections ([`crate::paletted`]), `level_chunk_with_light`
//! without its light data, `forget_level_chunk`, block and section updates, biomes, block
//! entities, chunk batches, the world border and the client's chunk window.
//!
//! ## Dimensions
//!
//! The build height is never assumed: the `login` / `respawn` packets name a `dimension_type`
//! registry entry by index, and [`World::apply_registry_data`] (fed with every configuration
//! `registry_data` packet) keeps that registry's `min_y` / `height`. A server sends an entry's
//! data only for packs the client did not declare as known; entries of the vanilla pack without
//! data use vanilla's values ([`DimensionType::vanilla`]). The biome registry's size gives the
//! width of global biome ids.
//!
//! ## Chunk format (vanilla `LevelChunkSection.read` / `PalettedContainer.read`)
//!
//! One section per 16 rows of the dimension, bottom to top: `i16` non-empty count, `i16` fluid
//! count (both ignored), the block container, the biome container. A container is a signed byte
//! `bits`, the palette, then exactly as many longs as the in-memory storage has:
//!
//! - blocks: `0` single value; `1..=4` linear palette (at most 16 ids) with 4-bit storage;
//!   `5..=8` hash palette with `bits`-bit storage; anything else global ids with
//!   `ceil(log2(state count))` bits (15), whatever the sent value;
//! - biomes: `0` single value; `1..=3` linear palette with `bits`-bit storage; anything else
//!   global ids with `ceil(log2(biome count))` bits.
//!
//! Palette ids that are not registry entries are an error (vanilla's `byIdOrThrow`), as are
//! stored indices past the palette (vanilla throws when such a block is read). An error unloads
//! the column. Trailing bytes are ignored. Heightmaps and light are not stored.
//!
//! ## Reads
//!
//! [`World::block_state`] hashes the column position. Hot loops (the physics) should take a
//! [`View`] around the player once per tick: a 3×3 column snapshot with O(1) reads and no
//! hashing inside it.
//!
//! Layout: this file holds the types ([`World`], [`Column`], [`View`], the registries and
//! dimensions); `access.rs` the world's accessors and reads, `apply.rs` the packets,
//! `decode.rs` chunk section decoding, `physics.rs` the physics world traits.

mod access;
mod apply;
mod decode;
#[cfg(feature = "physics")]
mod physics;
#[cfg(test)]
mod tests;

use decode::*;

// Row item (the per-version module this source is compiled in) the topic files name as
// `super::PROTOCOL`.
use super::PROTOCOL;

use super::data::{Block, BlockState, STATE_COUNT};
use super::proto::configuration::clientbound::RegistryData;
use super::proto::play::clientbound::{
    self as cb, BlockChange, ChunkBiomes, ClientboundPlayPacket, InitializeWorldBorder, Login,
    MapChunk, MultiBlockChange, Respawn, TileEntityData, UnloadChunk, UpdateViewDistance,
    UpdateViewPosition,
};
use bytes::Bytes;
use ghast_protocol::RawPacket;
use ghast_protocol::codec::Reader;
use ghast_protocol::nbt::{AnonNbt, Tag};

use crate::border::{Border, BorderPacket, LerpMath};
use crate::column::{BlockEntity, ColumnMap};
use crate::helpers::{changed, raw_state_or_air};
use std::sync::Arc;

use crate::paletted::{Builder, Ident, Section, WireBlocks, block_index};
use crate::{Applied, ChunkPos, SharedChunks, WorldConfig, WorldError};

/// Bits per block of the global palette: `ceil(log2(STATE_COUNT))` (15 for 26.1 and 26.2, 16
/// for 26.3). Vanilla's client reads a global-palette section with this many bits per entry
/// whatever bit count the server wrote (`Strategy.getConfigurationForBitCount` →
/// `Configuration.Global(globalPaletteBitsInMemory, …)`).
pub const GLOBAL_BITS: u32 = ceil_log2(STATE_COUNT);

/// Vanilla `Mth.ceillog2`.
const fn ceil_log2(n: usize) -> u32 {
    if n <= 1 {
        0
    } else {
        usize::BITS - (n - 1).leading_zeros()
    }
}

/// Clientbound play packet ids this world consumes (for a `PacketFilter`).
pub const PACKET_IDS: &[i32] = &[
    cb::id::LOGIN,
    cb::id::RESPAWN,
    cb::id::MAP_CHUNK,
    cb::id::UNLOAD_CHUNK,
    cb::id::BLOCK_CHANGE,
    cb::id::MULTI_BLOCK_CHANGE,
    cb::id::CHUNK_BIOMES,
    cb::id::CHUNK_BATCH_START,
    cb::id::CHUNK_BATCH_FINISHED,
    cb::id::UPDATE_VIEW_POSITION,
    cb::id::UPDATE_VIEW_DISTANCE,
    cb::id::INITIALIZE_WORLD_BORDER,
    cb::id::WORLD_BORDER_CENTER,
    cb::id::WORLD_BORDER_LERP_SIZE,
    cb::id::WORLD_BORDER_SIZE,
    cb::id::WORLD_BORDER_WARNING_DELAY,
    cb::id::WORLD_BORDER_WARNING_REACH,
];

/// Extra packet ids with [`WorldConfig::block_entities`] (chunk block entities come with
/// `map_chunk`).
pub const BLOCK_ENTITY_IDS: &[i32] = &[cb::id::TILE_ENTITY_DATA];

/// One `dimension_type` registry entry (the fields a client uses).
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct DimensionType {
    /// Registry key, e.g. `minecraft:overworld`.
    pub name: String,
    /// Lowest block Y (a multiple of 16).
    pub min_y: i32,
    /// Number of block rows (a multiple of 16, at least 16).
    pub height: i32,
    /// `logical_height`.
    pub logical_height: i32,
    /// `has_skylight`.
    pub has_skylight: bool,
    /// `has_ceiling`.
    pub has_ceiling: bool,
    /// Environment attribute `minecraft:gameplay/fast_lava` (the nether).
    pub fast_lava: bool,
    /// `default_clock`: the `minecraft:world_clock` entry that is this dimension's time of
    /// day (`None`: the dimension has no day, like the nether).
    pub default_clock: Option<String>,
    /// The entry's data as sent (`None` for a known-pack entry without data).
    pub nbt: Option<AnonNbt>,
}

impl DimensionType {
    /// Vanilla's built-in dimension types (the values the vanilla data pack defines), used for
    /// registry entries the server sent without data.
    #[must_use]
    pub fn vanilla(name: &str) -> Option<DimensionType> {
        let (min_y, height, logical, sky, ceiling, fast_lava, clock) = match name {
            "minecraft:overworld" => (-64, 384, 384, true, false, false, Some("overworld")),
            "minecraft:overworld_caves" => (-64, 384, 384, true, true, false, Some("overworld")),
            "minecraft:the_nether" => (0, 256, 128, false, true, true, None),
            "minecraft:the_end" => (0, 256, 256, true, false, false, Some("the_end")),
            _ => return None,
        };
        Some(DimensionType {
            name: name.to_string(),
            min_y,
            height,
            logical_height: logical,
            has_skylight: sky,
            has_ceiling: ceiling,
            fast_lava,
            default_clock: clock.map(|c| format!("minecraft:{c}")),
            nbt: None,
        })
    }

    /// Reads an entry's NBT (vanilla `DimensionType` network codec); `None` when required
    /// fields are missing or invalid (vanilla rejects such a registry).
    #[must_use]
    pub fn from_nbt(name: &str, nbt: &AnonNbt) -> Option<DimensionType> {
        let tag = nbt.parse().ok()??;
        let c = tag.as_compound()?;
        let int = |k: &str| match c.get(k) {
            Some(Tag::Int(v)) => Some(*v),
            Some(Tag::Short(v)) => Some(i32::from(*v)),
            Some(Tag::Byte(v)) => Some(i32::from(*v)),
            _ => None,
        };
        let flag = |k: &str| matches!(c.get(k), Some(Tag::Byte(v)) if *v != 0);
        let min_y = int("min_y")?;
        let height = int("height")?;
        let logical_height = int("logical_height").unwrap_or(height);
        // Vanilla's checks (DimensionType constructor).
        if height < 16
            || height % 16 != 0
            || min_y % 16 != 0
            || i64::from(min_y) + i64::from(height) > 2032
            || min_y < -2032
        {
            return None;
        }
        let fast_lava = match c.get("attributes") {
            Some(Tag::Compound(a)) => {
                matches!(a.get("minecraft:gameplay/fast_lava"), Some(Tag::Byte(v)) if *v != 0)
            }
            _ => false,
        };
        Some(DimensionType {
            name: name.to_string(),
            min_y,
            height,
            logical_height,
            has_skylight: flag("has_skylight"),
            has_ceiling: flag("has_ceiling"),
            fast_lava,
            default_clock: match c.get("default_clock") {
                Some(Tag::String(k)) if k.contains(':') => Some(k.to_string()),
                Some(Tag::String(k)) => Some(format!("minecraft:{k}")),
                _ => None,
            },
            nbt: Some(nbt.clone()),
        })
    }
}

/// A biome registry entry's climate (`has_precipitation`, `temperature`,
/// `temperature_modifier`); `None` when the data is malformed.
fn climate_from_nbt(nbt: &AnonNbt) -> Option<crate::climate::Climate> {
    let tag = nbt.parse().ok()??;
    let c = tag.as_compound()?;
    let has_precipitation = match c.get("has_precipitation")? {
        Tag::Byte(v) => *v != 0,
        _ => return None,
    };
    let temperature = match c.get("temperature")? {
        Tag::Float(v) => *v,
        Tag::Double(v) => *v as f32,
        _ => return None,
    };
    let frozen = match c.get("temperature_modifier") {
        None => false,
        Some(Tag::String(s)) => match &**s {
            "none" | "minecraft:none" => false,
            "frozen" | "minecraft:frozen" => true,
            _ => return None,
        },
        Some(_) => return None,
    };
    Some(crate::climate::Climate::new(
        has_precipitation,
        temperature,
        frozen,
    ))
}

/// What the world keeps from the configuration-phase registries.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Registries {
    /// `minecraft:dimension_type` in registry order (`None` = an entry without data that is
    /// not a vanilla dimension type, or invalid data).
    pub dimension_types: Vec<Option<DimensionType>>,
    /// Number of `minecraft:worldgen/biome` entries (0 until received).
    pub biome_count: usize,
    /// The climate of each `minecraft:worldgen/biome` entry in registry order (from its data,
    /// or vanilla's for an entry sent without data; `None` when neither is known).
    pub biome_climates: Vec<Option<crate::climate::Climate>>,
    /// `minecraft:world_clock` entry keys in registry order (a clock's network id is its
    /// index).
    pub world_clocks: Vec<String>,
}

/// The dimension the player is in.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Dimension {
    /// World name from `login` / `respawn` (e.g. `minecraft:overworld`).
    pub name: String,
    /// Index into the `dimension_type` registry.
    pub type_index: i32,
    /// The dimension type.
    pub kind: DimensionType,
}

/// A loaded 26.1 chunk column.
#[derive(Clone, Debug, Default)]
pub struct Column {
    /// The sections, behind the one pointer a read follows. With a [`SharedChunks`] store the
    /// array is shared with the other worlds that hold the same sections (it is never written
    /// while another handle exists).
    sections: Arc<[Section]>,
    /// What most columns of a bot do not have (kept out of the column table's slots).
    cold: Option<Box<Cold>>,
}

/// The rarely present parts of a [`Column`].
#[derive(Clone, Debug, Default)]
struct Cold {
    biomes: Option<Box<[BiomeSection]>>,
    /// Block entities keyed by [`be_key`] (only with [`WorldConfig::block_entities`]).
    block_entities: Vec<(u32, BlockEntity)>,
}

/// Exclusive access to a column's section array: the array itself when this is its only
/// handle (always, for a world that never had a store), else a copy of it first.
fn sections_mut(sections: &mut Arc<[Section]>) -> &mut [Section] {
    Arc::make_mut(sections)
}

/// Biomes of one section as sent (registry ids of `minecraft:worldgen/biome`).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BiomeSection {
    /// One biome for the whole section.
    Single(u16),
    /// One biome per 4×4×4 cell, index `y << 4 | z << 2 | x` (cell coordinates).
    Cells(Box<[u16; 64]>),
}

impl BiomeSection {
    /// The biome of cell `index` (`0..64`).
    #[must_use]
    pub fn get(&self, index: usize) -> u16 {
        match self {
            BiomeSection::Single(b) => *b,
            BiomeSection::Cells(c) => c[index & 63],
        }
    }
}

/// Column-local key of a block: `(y - min_y) << 8 | z << 4 | x`.
#[inline]
fn be_key(x: i32, ry: i32, z: i32) -> u32 {
    ((ry as u32) << 8) | (((z & 15) as u32) << 4) | ((x & 15) as u32)
}

impl Column {
    /// The sections, bottom to top (`(y - min_y) >> 4`).
    #[must_use]
    pub fn sections(&self) -> &[Section] {
        &self.sections
    }

    /// Raw state at column-local `x`, `z` (low four bits) and `ry = y - min_y`; air outside
    /// the column's height.
    #[inline]
    #[must_use]
    pub fn raw_rel(&self, x: i32, ry: i32, z: i32) -> u16 {
        match self.sections.get((ry >> 4) as usize) {
            Some(s) if ry >= 0 => s.get_at(x, ry, z),
            _ => 0,
        }
    }

    /// Biomes per section (only with [`WorldConfig::biomes`]).
    #[must_use]
    pub fn biomes(&self) -> Option<&[BiomeSection]> {
        self.cold.as_ref()?.biomes.as_deref()
    }

    fn stored_block_entities(&self) -> &[(u32, BlockEntity)] {
        self.cold.as_ref().map_or(&[], |c| &c.block_entities)
    }

    fn has_block_entities(&self) -> bool {
        self.cold
            .as_ref()
            .is_some_and(|c| !c.block_entities.is_empty())
    }

    fn set_stored_biomes(&mut self, biomes: Option<Box<[BiomeSection]>>) {
        match (&mut self.cold, biomes) {
            (Some(c), b) => c.biomes = b,
            (None, None) => {}
            (cold @ None, b) => {
                *cold = Some(Box::new(Cold {
                    biomes: b,
                    block_entities: Vec::new(),
                }));
            }
        }
    }

    /// Block entities as `([x, ry, z], data)` with `ry = y - min_y`, in arrival order. Empty
    /// unless [`WorldConfig::block_entities`] is on. [`BlockEntity::Nbt`]'s `action` is the
    /// block entity type's registry id (`u8::MAX` if it does not fit).
    pub fn block_entities(&self) -> impl Iterator<Item = ([i32; 3], &BlockEntity)> {
        self.stored_block_entities().iter().map(|(k, b)| {
            (
                [(k & 15) as i32, (k >> 8) as i32, ((k >> 4) & 15) as i32],
                b,
            )
        })
    }

    fn put_block_entity(&mut self, key: u32, be: BlockEntity) {
        let list = &mut self.cold.get_or_insert_default().block_entities;
        match list.iter_mut().find(|(k, _)| *k == key) {
            Some(slot) => slot.1 = be,
            None => list.push((key, be)),
        }
    }

    /// Heap bytes owned by this column. A section array shared through a [`SharedChunks`]
    /// store counts 0 here, like shared section storage (the store counts both once).
    #[must_use]
    pub fn heap_bytes(&self) -> usize {
        let sections = if Arc::weak_count(&self.sections) == 0 {
            self.sections.len() * size_of::<Section>()
                + self.sections.iter().map(Section::heap_bytes).sum::<usize>()
        } else {
            0
        };
        let cold = self.cold.as_ref().map_or(0, |_| size_of::<Cold>());
        let biomes = self.biomes().map_or(0, |b| {
            size_of_val(b)
                + b.iter()
                    .map(|s| match s {
                        BiomeSection::Single(_) => 0,
                        BiomeSection::Cells(_) => 128,
                    })
                    .sum::<usize>()
        });
        let be = self
            .cold
            .as_ref()
            .map_or(0, |c| c.block_entities.capacity())
            * size_of::<(u32, BlockEntity)>()
            + self
                .stored_block_entities()
                .iter()
                .map(|(_, b)| match b {
                    BlockEntity::Nbt { nbt, .. } => nbt.len(),
                    BlockEntity::Sign(l) => l.iter().map(|s| s.len()).sum(),
                })
                .sum::<usize>();
        sections + cold + biomes + be
    }
}

/// The client's chunk window (vanilla `ClientChunkCache.Storage`): chunks more than
/// `max(2, view distance) + 3` columns from the centre are not stored.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ViewWindow {
    radius: i32,
    center: (i32, i32),
}

impl ViewWindow {
    fn new(view_distance: i32) -> Self {
        ViewWindow {
            radius: view_distance.max(2).saturating_add(3),
            center: (0, 0),
        }
    }

    fn contains(self, cx: i32, cz: i32) -> bool {
        let r = i64::from(self.radius);
        (i64::from(cx) - i64::from(self.center.0)).abs() <= r
            && (i64::from(cz) - i64::from(self.center.1)).abs() <= r
    }
}

/// Vanilla's `ChunkBatchSizeCalculator`: how many chunks per tick the client asks for after
/// each chunk batch. Time is passed in (nanoseconds from any fixed origin), so it stays pure.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ChunkBatchSize {
    aggregated_nanos_per_chunk: f64,
    old_samples_weight: i32,
    batch_start_nanos: i64,
}

impl Default for ChunkBatchSize {
    fn default() -> Self {
        ChunkBatchSize {
            aggregated_nanos_per_chunk: 2_000_000.0,
            old_samples_weight: 1,
            batch_start_nanos: 0,
        }
    }
}

impl ChunkBatchSize {
    /// `chunk_batch_start` arrived at `now_nanos`.
    pub fn on_batch_start(&mut self, now_nanos: i64) {
        self.batch_start_nanos = now_nanos;
    }

    /// `chunk_batch_finished` with `batch_size` chunks arrived at `now_nanos`; returns the
    /// `chunks_per_tick` value of the `chunk_batch_received` answer the client must send.
    pub fn on_batch_finished(&mut self, batch_size: i32, now_nanos: i64) -> f32 {
        if batch_size > 0 {
            let duration = now_nanos.wrapping_sub(self.batch_start_nanos) as f64;
            let per = duration / f64::from(batch_size);
            let lo = self.aggregated_nanos_per_chunk / 3.0;
            let hi = self.aggregated_nanos_per_chunk * 3.0;
            // Mth.clamp(double): lower bound first, as Java's `value < min ? min : Math.min(value, max)`.
            let clamped = if per < lo { lo } else { per.min(hi) };
            let w = f64::from(self.old_samples_weight);
            self.aggregated_nanos_per_chunk =
                (self.aggregated_nanos_per_chunk * w + clamped) / (w + 1.0);
            self.old_samples_weight = (self.old_samples_weight + 1).min(49);
        }
        self.desired_chunks_per_tick()
    }

    /// `getDesiredChunksPerTick`.
    #[must_use]
    pub fn desired_chunks_per_tick(&self) -> f32 {
        (7_000_000.0 / self.aggregated_nanos_per_chunk) as f32
    }
}

/// The client-side world of a 26.1 connection.
pub struct World {
    columns: ColumnMap<Column>,
    config: WorldConfig,
    registries: Registries,
    dim: Option<Dimension>,
    view: ViewWindow,
    builder: Builder,
    border: Border,
    /// The border as the 26.1 client's collision reads it (tick-based lerp, one tick behind).
    #[cfg(feature = "physics")]
    collision_border: ghast_physics::modern::BorderState,
    batch: ChunkBatchSize,
    /// `BiomeManager.biomeZoomSeed` (the login / respawn hashed seed).
    biome_zoom_seed: i64,
    /// `Level.getSeaLevel()` (login / respawn).
    sea_level: i32,
    /// Where non-uniform sections are shared with other worlds ([`World::set_shared_chunks`]).
    shared: Option<SharedChunks>,
    /// Lowest block Y of the current dimension (0 without one), for the read path.
    min_y: i32,
}

impl std::fmt::Debug for World {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("World")
            .field("dimension", &self.dim.as_ref().map(|d| &d.name))
            .field("view", &self.view)
            .field("columns", &self.columns.len())
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

#[inline]
fn void_air() -> BlockState {
    Block::VOID_AIR.default_state()
}

#[inline]
fn state(raw: u16) -> BlockState {
    BlockState::from_id(raw).unwrap_or(BlockState::AIR)
}

/// `Block.BLOCK_STATE_REGISTRY.byId` with unknown ids as air (block updates; vanilla reads
/// `byIdOrThrow` there too, but a bad block update must not unload anything).
#[inline]
fn raw_from_wire(v: i64) -> u16 {
    raw_state_or_air::<STATE_COUNT>(v)
}

/// Same block type (the condition under which vanilla keeps a block entity).
fn same_block(a: u16, b: u16) -> bool {
    match (BlockState::from_id(a), BlockState::from_id(b)) {
        (Some(a), Some(b)) => a.block() == b.block(),
        _ => a == b,
    }
}

/// A 3×3-column snapshot of a [`World`] for fast reads in a small box (see [`World::view`]).
/// Reads outside the snapshot fall back to the world's hash map.
#[derive(Clone, Copy)]
pub struct View<'w> {
    world: &'w World,
    cx0: i32,
    cz0: i32,
    min_y: i32,
    cols: [Option<&'w Column>; 9],
}

impl std::fmt::Debug for View<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("View")
            .field("chunk", &(self.cx0 + 1, self.cz0 + 1))
            .finish_non_exhaustive()
    }
}

impl<'w> View<'w> {
    #[inline(always)]
    fn column(&self, cx: i32, cz: i32) -> Option<&'w Column> {
        let dx = cx.wrapping_sub(self.cx0) as u32;
        let dz = cz.wrapping_sub(self.cz0) as u32;
        if dx < 3 && dz < 3 {
            self.cols[(dz * 3 + dx) as usize]
        } else {
            self.world.columns.get(cx, cz)
        }
    }

    /// Like [`World::block_state`].
    #[inline(always)]
    #[must_use]
    pub fn block_state(&self, x: i32, y: i32, z: i32) -> Option<BlockState> {
        let c = self.column(x >> 4, z >> 4)?;
        Some(read(&c.sections, x, y.wrapping_sub(self.min_y), z))
    }

    /// Like [`World::is_column_loaded`].
    #[inline]
    #[must_use]
    pub fn is_column_loaded(&self, cx: i32, cz: i32) -> bool {
        self.column(cx, cz).is_some()
    }

    /// The world the view was taken from.
    #[must_use]
    pub fn world(&self) -> &'w World {
        self.world
    }
}