mod access;
mod apply;
mod decode;
#[cfg(feature = "physics")]
mod physics;
#[cfg(test)]
mod tests;
use decode::*;
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};
pub const GLOBAL_BITS: u32 = ceil_log2(STATE_COUNT);
const fn ceil_log2(n: usize) -> u32 {
if n <= 1 {
0
} else {
usize::BITS - (n - 1).leading_zeros()
}
}
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,
];
pub const BLOCK_ENTITY_IDS: &[i32] = &[cb::id::TILE_ENTITY_DATA];
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct DimensionType {
pub name: String,
pub min_y: i32,
pub height: i32,
pub logical_height: i32,
pub has_skylight: bool,
pub has_ceiling: bool,
pub fast_lava: bool,
pub default_clock: Option<String>,
pub nbt: Option<AnonNbt>,
}
impl DimensionType {
#[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,
})
}
#[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);
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()),
})
}
}
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,
))
}
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Registries {
pub dimension_types: Vec<Option<DimensionType>>,
pub biome_count: usize,
pub biome_climates: Vec<Option<crate::climate::Climate>>,
pub world_clocks: Vec<String>,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Dimension {
pub name: String,
pub type_index: i32,
pub kind: DimensionType,
}
#[derive(Clone, Debug, Default)]
pub struct Column {
sections: Arc<[Section]>,
cold: Option<Box<Cold>>,
}
#[derive(Clone, Debug, Default)]
struct Cold {
biomes: Option<Box<[BiomeSection]>>,
block_entities: Vec<(u32, BlockEntity)>,
}
fn sections_mut(sections: &mut Arc<[Section]>) -> &mut [Section] {
Arc::make_mut(sections)
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BiomeSection {
Single(u16),
Cells(Box<[u16; 64]>),
}
impl BiomeSection {
#[must_use]
pub fn get(&self, index: usize) -> u16 {
match self {
BiomeSection::Single(b) => *b,
BiomeSection::Cells(c) => c[index & 63],
}
}
}
#[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 {
#[must_use]
pub fn sections(&self) -> &[Section] {
&self.sections
}
#[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,
}
}
#[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(),
}));
}
}
}
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)),
}
}
#[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
}
}
#[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
}
}
#[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 {
pub fn on_batch_start(&mut self, now_nanos: i64) {
self.batch_start_nanos = now_nanos;
}
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;
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()
}
#[must_use]
pub fn desired_chunks_per_tick(&self) -> f32 {
(7_000_000.0 / self.aggregated_nanos_per_chunk) as f32
}
}
pub struct World {
columns: ColumnMap<Column>,
config: WorldConfig,
registries: Registries,
dim: Option<Dimension>,
view: ViewWindow,
builder: Builder,
border: Border,
#[cfg(feature = "physics")]
collision_border: ghast_physics::modern::BorderState,
batch: ChunkBatchSize,
biome_zoom_seed: i64,
sea_level: i32,
shared: Option<SharedChunks>,
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)
}
#[inline]
fn raw_from_wire(v: i64) -> u16 {
raw_state_or_air::<STATE_COUNT>(v)
}
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,
}
}
#[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)
}
}
#[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))
}
#[inline]
#[must_use]
pub fn is_column_loaded(&self, cx: i32, cz: i32) -> bool {
self.column(cx, cz).is_some()
}
#[must_use]
pub fn world(&self) -> &'w World {
self.world
}
}