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)]
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]>>,
}
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),
}
}
#[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>()
});
sections + biomes + light
}
}
#[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));
}
}