ghast-world 0.5.6

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
//! The modern [`World`]: construction, configuration, the dimension and chunk-window
//! accessors, block / biome reads and [`World::view`].

use super::*;

impl World {
    /// An empty world (no dimension yet: nothing can load before `login`).
    #[must_use]
    pub fn new(config: WorldConfig) -> Self {
        World {
            columns: ColumnMap::default(),
            config,
            registries: Registries::default(),
            dim: None,
            view: ViewWindow::new(2),
            builder: Builder::new(STATE_COUNT),
            border: Border::new(LerpMath::Double),
            #[cfg(feature = "physics")]
            collision_border: ghast_physics::modern::BorderState::new(),
            batch: ChunkBatchSize::default(),
            biome_zoom_seed: 0,
            sea_level: 63,
            shared: None,
            min_y: 0,
        }
    }

    /// Shares the block storage of the sections this world decodes from now on through
    /// `cache` (see [`SharedChunks`]), or stops sharing (`None`). Columns already loaded keep
    /// the storage they have. Without a store (the default) sections are owned as before.
    pub fn set_shared_chunks(&mut self, cache: Option<SharedChunks>) {
        self.shared = cache;
    }

    /// The store this world shares sections through, if any.
    #[must_use]
    pub fn shared_chunks(&self) -> Option<&SharedChunks> {
        self.shared.as_ref()
    }

    /// The configuration.
    #[must_use]
    pub fn config(&self) -> WorldConfig {
        self.config
    }

    /// The registries received during configuration.
    #[must_use]
    pub fn registries(&self) -> &Registries {
        &self.registries
    }

    /// The current dimension (`None` before `login`, or when the server named a dimension
    /// type the registries do not describe).
    #[must_use]
    pub fn dimension(&self) -> Option<&Dimension> {
        self.dim.as_ref()
    }

    /// The network id of the current dimension's day clock (its `default_clock` in the
    /// `minecraft:world_clock` registry); `None` without a dimension, for a dimension without
    /// a day (the nether) or a clock the registry does not list.
    #[must_use]
    pub fn day_clock(&self) -> Option<i32> {
        let name = self.dim.as_ref()?.kind.default_clock.as_deref()?;
        let i = self
            .registries
            .world_clocks
            .iter()
            .position(|k| k == name)?;
        i32::try_from(i).ok()
    }

    /// Lowest block Y of the current dimension.
    #[must_use]
    pub fn min_y(&self) -> Option<i32> {
        self.dim.as_ref().map(|d| d.kind.min_y)
    }

    /// Number of block rows of the current dimension.
    #[must_use]
    pub fn height(&self) -> Option<i32> {
        self.dim.as_ref().map(|d| d.kind.height)
    }

    /// The block state at a position, or `None` when its column is not loaded. Positions
    /// outside the build height in a loaded column are `void_air`, as in vanilla.
    #[inline(always)]
    #[must_use]
    pub fn block_state(&self, x: i32, y: i32, z: i32) -> Option<BlockState> {
        let c = self.columns.get(x >> 4, z >> 4)?;
        Some(read(&c.sections, x, y.wrapping_sub(self.min_y), z))
    }

    /// `true` when the column `(chunk_x, chunk_z)` is loaded.
    #[inline]
    #[must_use]
    pub fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        self.columns.contains(chunk_x, chunk_z)
    }

    /// A loaded column.
    #[must_use]
    pub fn column(&self, chunk_x: i32, chunk_z: i32) -> Option<&Column> {
        self.columns.get(chunk_x, chunk_z)
    }

    /// All loaded columns.
    #[must_use]
    pub fn columns(&self) -> &ColumnMap<Column> {
        &self.columns
    }

    /// View distance from `login` / `set_chunk_cache_radius` as the window radius
    /// (`max(2, distance) + 3`).
    #[must_use]
    pub fn window_radius(&self) -> i32 {
        self.view.radius
    }

    /// Chunk window centre (`set_chunk_cache_center`; `(0, 0)` until one arrives).
    #[must_use]
    pub fn view_center(&self) -> ChunkPos {
        ChunkPos::new(self.view.center.0, self.view.center.1)
    }

    /// The world border.
    #[must_use]
    pub fn border(&self) -> &Border {
        &self.border
    }

    /// The chunk batch rate calculator (see [`World::on_chunk_batch_finished`]).
    #[must_use]
    pub fn chunk_batch(&self) -> &ChunkBatchSize {
        &self.batch
    }

    /// Approximate heap bytes used by the loaded columns.
    #[must_use]
    pub fn heap_bytes(&self) -> usize {
        self.columns.table_bytes()
            + self
                .columns
                .iter()
                .map(|(_, c)| c.heap_bytes())
                .sum::<usize>()
    }

    /// Advances time-dependent world state (a moving border) by one tick; the client calls
    /// this once per tick.
    pub fn tick(&mut self) {
        self.border.advance(50);
        #[cfg(feature = "physics")]
        self.collision_border.tick();
    }

    /// Unloads everything (keeps the registries and the dimension).
    pub fn clear(&mut self) {
        match &self.shared {
            None => self.columns.clear(),
            Some(cache) => {
                for col in self.columns.drain() {
                    cache.release_column(col.sections);
                }
            }
        }
    }

    /// Drops a column this world held (through the store, which then forgets a section array
    /// nobody holds any more).
    pub(super) fn release(&self, col: Option<Column>) {
        if let (Some(cache), Some(col)) = (&self.shared, col) {
            cache.release_column(col.sections);
        }
    }

    /// Turns [`WorldConfig::biomes`] on or off at run time. On: columns that arrive (and
    /// `chunks_biomes` updates) from now on keep their biomes; columns already loaded have none
    /// until the server resends them. Off: every stored biome is dropped.
    pub fn set_biomes(&mut self, on: bool) {
        self.config.biomes = on;
        if !on {
            for (_, col) in self.columns.iter_mut() {
                col.set_stored_biomes(None);
            }
        }
    }

    /// `BiomeManager.biomeZoomSeed`: the hashed seed of the last login / dimension change.
    #[must_use]
    pub fn biome_zoom_seed(&self) -> i64 {
        self.biome_zoom_seed
    }

    /// `Level.getSeaLevel()`: the sea level of the last login / dimension change.
    #[must_use]
    pub fn sea_level(&self) -> i32 {
        self.sea_level
    }

    /// `Level.getBiome(pos)`: the `minecraft:worldgen/biome` registry id of the block at `x`,
    /// `y`, `z` (the zoomed noise cell, `BiomeManager`), or `None` when the cell's column is not
    /// loaded or was loaded without biomes ([`WorldConfig::biomes`], [`World::set_biomes`]).
    /// Vanilla reads plains in a column it does not have.
    #[must_use]
    pub fn biome_at(&self, x: i32, y: i32, z: i32) -> Option<u16> {
        let d = self.dim.as_ref()?;
        let [qx, qy, qz] = crate::climate::zoom_cell(self.biome_zoom_seed, x, y, z);
        let biomes = self.columns.get(qx >> 2, qz >> 2)?.biomes()?;
        let lo = d.kind.min_y >> 2;
        let hi = lo + (d.kind.height >> 2) - 1;
        let qy = qy.clamp(lo, hi);
        let section = biomes.get((((qy << 2) - d.kind.min_y) >> 4) as usize)?;
        Some(section.get((((qy & 3) << 4) | ((qz & 3) << 2) | (qx & 3)) as usize))
    }

    /// The climate of biome registry id `id` (from the synced registry; vanilla's for entries
    /// sent without data).
    #[must_use]
    pub fn biome_climate(&self, id: u16) -> Option<crate::climate::Climate> {
        self.registries
            .biome_climates
            .get(usize::from(id))
            .copied()
            .flatten()
    }

    /// `Biome.getPrecipitationAt(pos, seaLevel)` of the biome at a block position, `None` when
    /// the biome or its climate is unknown ([`World::biome_at`]). `Level.isRainingAt` also needs
    /// rain, sky access and the motion-blocking height map, which this does not check.
    #[must_use]
    pub fn precipitation_at(
        &self,
        x: i32,
        y: i32,
        z: i32,
    ) -> Option<crate::climate::Precipitation> {
        let c = self.biome_climate(self.biome_at(x, y, z)?)?;
        Some(c.precipitation_at(x, y, z, self.sea_level))
    }

    /// The packet ids this world consumes with its configuration (for a `PacketFilter`).
    pub fn packet_ids(&self) -> impl Iterator<Item = i32> + use<> {
        let extra: &'static [i32] = if self.config.block_entities {
            BLOCK_ENTITY_IDS
        } else {
            &[]
        };
        PACKET_IDS.iter().chain(extra).copied()
    }

    /// A 3×3-column view around block `(x, z)` for many reads in a small box (the physics):
    /// reads inside it need no hashing. Valid until the world changes.
    #[must_use]
    pub fn view(&self, x: i32, z: i32) -> View<'_> {
        let (cx, cz) = (x >> 4, z >> 4);
        let mut cols = [None; 9];
        for (i, c) in cols.iter_mut().enumerate() {
            *c = self
                .columns
                .get(cx - 1 + (i % 3) as i32, cz - 1 + (i / 3) as i32);
        }
        View {
            world: self,
            cx0: cx - 1,
            cz0: cz - 1,
            min_y: self.min_y,
            cols,
        }
    }
}