use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
use crate::section::{Section, block_index};
pub const SECTIONS: usize = 16;
pub const MIN_Y: i32 = 0;
pub const MAX_Y: i32 = 256;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct ChunkPos {
pub x: i32,
pub z: i32,
}
impl ChunkPos {
#[must_use]
pub const fn new(x: i32, z: i32) -> Self {
ChunkPos { x, z }
}
#[must_use]
pub const fn of_block(x: i32, z: i32) -> Self {
ChunkPos {
x: x >> 4,
z: z >> 4,
}
}
}
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub enum Biomes {
#[default]
None,
Legacy(Box<[u8; 256]>),
Cells(Box<[u16; 1024]>),
}
#[derive(Clone, Debug)]
pub struct SectionLight {
pub block: Box<[u8; 2048]>,
pub sky: Option<Box<[u8; 2048]>>,
}
impl SectionLight {
fn nibble(arr: &[u8; 2048], i: usize) -> u8 {
let b = arr[(i >> 1) & 2047];
if i & 1 == 0 { b & 15 } else { b >> 4 }
}
}
#[derive(Clone, Debug, Default)]
pub struct Column {
pub(crate) sections: [Option<Section>; SECTIONS],
pub(crate) biomes: Biomes,
pub(crate) light: Option<Box<[Option<SectionLight>; SECTIONS]>>,
pub(crate) block_entities: Vec<(u16, BlockEntity)>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BlockEntity {
Nbt {
action: u8,
nbt: bytes::Bytes,
},
Sign([Box<str>; 4]),
}
#[cfg_attr(
not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
allow(dead_code)
)]
pub(crate) fn put_nbt(
columns: &mut ColumnMap,
l: ghast_protocol::BlockPos,
action: u8,
nbt: Option<&ghast_protocol::nbt::RawNbt>,
) -> crate::Applied {
let Some(nbt) = nbt.filter(|n| !n.is_end()) else {
return crate::Applied::Ignored;
};
if !(MIN_Y..MAX_Y).contains(&l.y) {
return crate::Applied::Ignored;
}
let Some(col) = columns.get_mut(l.x >> 4, l.z >> 4) else {
return crate::Applied::Ignored;
};
col.put_block_entity(
l.x,
l.y,
l.z,
BlockEntity::Nbt {
action,
nbt: bytes::Bytes::copy_from_slice(nbt.as_bytes()),
},
);
crate::Applied::Changed
}
#[inline]
pub(crate) fn be_key(x: i32, y: i32, z: i32) -> u16 {
(((y & 0xFF) << 8) | ((z & 15) << 4) | (x & 15)) as u16
}
impl Column {
#[must_use]
pub fn empty() -> Self {
Column::default()
}
#[inline]
#[must_use]
pub fn raw(&self, x: i32, y: i32, z: i32) -> u16 {
if !(MIN_Y..MAX_Y).contains(&y) {
return 0;
}
match &self.sections[(y >> 4) as usize & (SECTIONS - 1)] {
Some(s) => s.get(block_index(x, y, z)),
None => 0,
}
}
pub fn set_raw(&mut self, x: i32, y: i32, z: i32, state: u16) {
if !(MIN_Y..MAX_Y).contains(&y) {
return;
}
let slot = &mut self.sections[(y >> 4) as usize & (SECTIONS - 1)];
let i = block_index(x, y, z);
match slot {
Some(s) => {
if !s.set(i, state) {
*slot = None;
}
}
None => *slot = Section::single(i, state),
}
}
pub fn block_entities(&self) -> impl Iterator<Item = ([u8; 3], &BlockEntity)> {
self.block_entities
.iter()
.map(|(k, b)| ([(k & 15) as u8, (k >> 8) as u8, ((k >> 4) & 15) as u8], b))
}
#[must_use]
pub fn block_entity(&self, x: i32, y: i32, z: i32) -> Option<&BlockEntity> {
if !(MIN_Y..MAX_Y).contains(&y) {
return None;
}
let k = be_key(x, y, z);
self.block_entities
.iter()
.find(|(key, _)| *key == k)
.map(|(_, b)| b)
}
#[cfg_attr(
not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
allow(dead_code)
)]
pub(crate) fn put_block_entity(&mut self, x: i32, y: i32, z: i32, be: BlockEntity) {
if !(MIN_Y..MAX_Y).contains(&y) {
return;
}
let k = be_key(x, y, z);
match self.block_entities.iter_mut().find(|(key, _)| *key == k) {
Some(slot) => slot.1 = be,
None => self.block_entities.push((k, be)),
}
}
#[cfg_attr(
not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
allow(dead_code)
)]
pub(crate) fn remove_block_entity(&mut self, x: i32, y: i32, z: i32) -> bool {
if !(MIN_Y..MAX_Y).contains(&y) {
return false;
}
let k = be_key(x, y, z);
let before = self.block_entities.len();
self.block_entities.retain(|(key, _)| *key != k);
before != self.block_entities.len()
}
#[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
pub(crate) fn remove_block_entities_in(&mut self, mask: u32) {
self.block_entities
.retain(|(k, _)| mask & (1 << (k >> 12)) == 0);
}
#[cfg_attr(
not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")),
allow(dead_code)
)]
pub(crate) fn set_raw_with(
&mut self,
x: i32,
y: i32,
z: i32,
state: u16,
same_block: fn(u16, u16) -> bool,
) {
if !self.block_entities.is_empty() && !same_block(self.raw(x, y, z), state) {
self.remove_block_entity(x, y, z);
}
self.set_raw(x, y, z, state);
}
#[must_use]
pub fn section(&self, index: usize) -> Option<&Section> {
self.sections.get(index)?.as_ref()
}
#[must_use]
pub fn biomes(&self) -> &Biomes {
&self.biomes
}
#[must_use]
pub fn block_light(&self, x: i32, y: i32, z: i32) -> Option<u8> {
let l = self.light_section(y)?;
Some(SectionLight::nibble(&l.block, block_index(x, y, z)))
}
#[must_use]
pub fn sky_light(&self, x: i32, y: i32, z: i32) -> Option<u8> {
let l = self.light_section(y)?;
Some(SectionLight::nibble(
l.sky.as_deref()?,
block_index(x, y, z),
))
}
fn light_section(&self, y: i32) -> Option<&SectionLight> {
if !(MIN_Y..MAX_Y).contains(&y) {
return None;
}
self.light.as_ref()?[(y >> 4) as usize].as_ref()
}
#[must_use]
pub fn section_count(&self) -> usize {
self.sections.iter().filter(|s| s.is_some()).count()
}
#[must_use]
pub fn heap_bytes(&self) -> usize {
let sections: usize = self
.sections
.iter()
.flatten()
.map(Section::heap_bytes)
.sum();
let biomes = match self.biomes {
Biomes::None => 0,
Biomes::Legacy(_) => 256,
Biomes::Cells(_) => 2048,
};
let light = self.light.as_ref().map_or(0, |l| {
size_of::<[Option<SectionLight>; SECTIONS]>()
+ l.iter()
.flatten()
.map(|s| 2048 + s.sky.as_ref().map_or(0, |_| 2048))
.sum::<usize>()
});
let be = self.block_entities.capacity() * size_of::<(u16, BlockEntity)>()
+ self
.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 + biomes + light + be
}
}
#[derive(Default, Clone, Copy)]
pub(crate) struct ChunkHasher(u64);
impl Hasher for ChunkHasher {
#[inline]
fn finish(&self) -> u64 {
let h = (self.0 ^ (self.0 >> 29)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
h ^ (h >> 32)
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.0 = (self.0 << 8) | u64::from(b);
}
}
#[inline]
fn write_u64(&mut self, v: u64) {
self.0 = v;
}
}
#[inline]
fn key(x: i32, z: i32) -> u64 {
u64::from(x as u32) | (u64::from(z as u32) << 32)
}
#[derive(Clone, Debug, Default)]
pub struct ColumnMap {
map: HashMap<u64, (ChunkPos, Column), BuildHasherDefault<ChunkHasher>>,
}
impl ColumnMap {
#[inline]
#[must_use]
pub fn get(&self, cx: i32, cz: i32) -> Option<&Column> {
self.map.get(&key(cx, cz)).map(|(_, c)| c)
}
#[inline]
pub fn get_mut(&mut self, cx: i32, cz: i32) -> Option<&mut Column> {
self.map.get_mut(&key(cx, cz)).map(|(_, c)| c)
}
#[inline]
#[must_use]
pub fn contains(&self, cx: i32, cz: i32) -> bool {
self.map.contains_key(&key(cx, cz))
}
#[inline]
#[must_use]
pub fn raw(&self, x: i32, y: i32, z: i32) -> Option<u16> {
self.get(x >> 4, z >> 4).map(|c| c.raw(x, y, z))
}
pub fn insert(&mut self, cx: i32, cz: i32, column: Column) {
self.map
.insert(key(cx, cz), (ChunkPos::new(cx, cz), column));
}
pub fn remove(&mut self, cx: i32, cz: i32) -> bool {
self.map.remove(&key(cx, cz)).is_some()
}
pub fn clear(&mut self) {
self.map.clear();
}
pub fn retain(&mut self, mut keep: impl FnMut(ChunkPos) -> bool) {
self.map.retain(|_, (p, _)| keep(*p));
}
#[must_use]
pub fn len(&self) -> usize {
self.map.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = (ChunkPos, &Column)> {
self.map.values().map(|(p, c)| (*p, c))
}
#[must_use]
pub fn heap_bytes(&self) -> usize {
let table = self.map.capacity() * (size_of::<(u64, (ChunkPos, Column))>() + 1);
table
+ self
.map
.values()
.map(|(_, c)| c.heap_bytes())
.sum::<usize>()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn set_and_drop_sections() {
let mut c = Column::empty();
c.set_raw(3, 70, 5, 16);
assert_eq!(c.raw(3, 70, 5), 16);
assert_eq!(
c.raw(3 + 16, 70, 5 - 32),
16,
"only low bits of x/z are used"
);
assert_eq!(c.section_count(), 1);
c.set_raw(3, 70, 5, 0);
assert_eq!(c.section_count(), 0);
c.set_raw(0, -1, 0, 16);
c.set_raw(0, 256, 0, 16);
assert_eq!(c.section_count(), 0);
assert_eq!(c.raw(0, -1, 0), 0);
}
#[test]
fn map_negative_coords() {
let mut m = ColumnMap::default();
let mut c = Column::empty();
c.set_raw(15, 0, 15, 7);
m.insert(-1, -1, c);
assert_eq!(m.raw(-1, 0, -1), Some(7));
assert_eq!(m.raw(0, 0, 0), None);
assert!(m.contains(-1, -1));
assert!(!m.contains(-1, 0));
}
}