chore: move to crates folder

This commit is contained in:
Alexander Medvedev committed 2026-08-06 12:56:40 +02:00
1 parent 5d10c0d8a8
commit cb3660bcd2
3393 files changed
+1270 -741

No files matched your search

@@ -0,0 +1,134 @@
use super::{ChunkLevel, ChunkPos, HashMapType};
use crate::chunk_system::chunk_state::StagedChunkEnum;
use crate::level::Level;
use std::collections::hash_map::Entry;
use std::mem::swap;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::{Arc, Condvar, Mutex};
pub type LevelChange = (
HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
ChunkLevel,
);
pub struct LevelChannel {
pub value: Mutex<(Option<LevelChange>, Option<Vec<ChunkPos>>)>,
pub notify: Condvar,
}
impl Default for LevelChannel {
fn default() -> Self {
Self::new()
}
}
impl LevelChannel {
#[must_use]
pub const fn new() -> Self {
Self {
value: Mutex::new((None, None)),
notify: Condvar::new(),
}
}
pub fn set_both(
&self,
new_value: (
HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
ChunkLevel,
),
pos: Vec<ChunkPos>,
) {
// debug!("set new level and priority");
let mut value = self.value.lock().unwrap();
value.1 = Some(pos);
if let Some(old) = &mut value.0 {
for (pos, change) in new_value.0 {
match old.0.entry(pos) {
Entry::Occupied(mut entry) => {
let tmp = entry.get_mut();
debug_assert_eq!(tmp.1, change.0);
if tmp.0 == change.1 {
entry.remove();
} else {
tmp.1 = change.1;
}
}
Entry::Vacant(entry) => {
debug_assert_ne!(change.0, change.1);
entry.insert(change);
}
}
}
old.1 = new_value.1;
} else {
value.0 = Some(new_value);
}
self.notify.notify_one();
}
pub fn set_level(
&self,
new_value: (
HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
ChunkLevel,
),
) {
// debug!("set new level");
let mut value = self.value.lock().unwrap();
if let Some(old) = &mut value.0 {
for (pos, change) in new_value.0 {
match old.0.entry(pos) {
Entry::Occupied(mut entry) => {
let tmp = entry.get_mut();
debug_assert_eq!(tmp.1, change.0);
if tmp.0 == change.1 {
entry.remove();
} else {
tmp.1 = change.1;
}
}
Entry::Vacant(entry) => {
debug_assert_ne!(change.0, change.1);
entry.insert(change);
}
}
}
old.1 = new_value.1;
} else {
value.0 = Some(new_value);
}
self.notify.notify_one();
}
pub fn set_priority(&self, pos: Vec<ChunkPos>) {
// debug!("set new priority");
self.value.lock().unwrap().1 = Some(pos);
self.notify.notify_one();
}
pub fn get(&self) -> (Option<LevelChange>, Option<Vec<ChunkPos>>) {
let mut lock = self.value.lock().unwrap();
let mut ret = (None, None);
swap(&mut ret, &mut *lock);
ret
}
pub fn wait_and_get(&self, level: &Arc<Level>) -> (Option<LevelChange>, Option<Vec<ChunkPos>>) {
let mut lock = self.value.lock().unwrap();
while lock.0.is_none()
&& lock.1.is_none()
&& !level.should_unload.load(SeqCst)
&& !level.should_save.load(SeqCst)
&& !level.shut_down_chunk_system.load(SeqCst)
{
lock = self.notify.wait(lock).unwrap();
}
let mut ret = (None, None);
swap(&mut ret, &mut *lock);
ret
}
pub fn notify(&self) {
let val = self
.value
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
drop(val);
self.notify.notify_one();
}
}
@@ -0,0 +1,33 @@
use super::chunk_state::{Chunk, StagedChunkEnum};
use super::dag::{EdgeKey, NodeKey};
use slotmap::Key;
pub struct ChunkHolder {
pub target_stage: StagedChunkEnum,
/// Minimum stage required by generation dependencies (e.g. `StructureReferences` neighbors).
/// May exceed `target_stage` when this chunk is needed by a neighbor's generation task
/// but isn't in the player's view radius. Tasks up to this stage are scheduled but the
/// chunk is not made public and is unloaded once the dependency is satisfied.
pub dependency_stage: StagedChunkEnum,
pub current_stage: StagedChunkEnum,
pub chunk: Option<Chunk>,
pub occupied: NodeKey,
pub occupied_by: EdgeKey,
pub public: bool,
pub tasks: [NodeKey; StagedChunkEnum::COUNT],
}
impl Default for ChunkHolder {
fn default() -> Self {
Self {
target_stage: StagedChunkEnum::None,
dependency_stage: StagedChunkEnum::None,
current_stage: StagedChunkEnum::None,
chunk: None,
occupied: NodeKey::null(),
occupied_by: EdgeKey::null(),
public: false,
tasks: [NodeKey::null(); StagedChunkEnum::COUNT],
}
}
}
@@ -0,0 +1,75 @@
use super::ChunkPos;
use crate::level::SyncChunk;
use crossbeam::channel::{Receiver, Sender};
use std::sync::Arc;
use std::sync::{Mutex, Weak};
use tokio::sync::oneshot;
#[expect(clippy::type_complexity)]
pub struct ChunkListener {
single: Mutex<Vec<(ChunkPos, oneshot::Sender<SyncChunk>)>>,
global: Mutex<Vec<Sender<(ChunkPos, Weak<crate::chunk::ChunkData>)>>>,
}
impl Default for ChunkListener {
fn default() -> Self {
Self::new()
}
}
impl ChunkListener {
#[must_use]
pub const fn new() -> Self {
Self {
single: Mutex::new(Vec::new()),
global: Mutex::new(Vec::new()),
}
}
pub fn add_single_chunk_listener(&self, pos: ChunkPos) -> oneshot::Receiver<SyncChunk> {
let (tx, rx) = oneshot::channel();
self.single.lock().unwrap().push((pos, tx));
rx
}
pub fn add_global_chunk_listener(&self) -> Receiver<(ChunkPos, Weak<crate::chunk::ChunkData>)> {
let (tx, rx) = crossbeam::channel::unbounded();
self.global.lock().unwrap().push(tx);
rx
}
pub fn process_new_chunk(&self, pos: ChunkPos, chunk: &SyncChunk) {
{
let mut single = self.single.lock().unwrap();
let mut i = 0;
let mut len = single.len();
while i < len {
if single[i].0 == pos {
let (_, send) = single.remove(i);
let _ = send.send(chunk.clone());
// log::debug!("single listener {i} send {pos:?}");
len -= 1;
continue;
}
i += 1;
}
}
{
let weak = Arc::downgrade(chunk);
let mut global = self.global.lock().unwrap();
let mut i = 0;
let mut len = global.len();
while i < len {
if matches!(global[i].send((pos, weak.clone())), Ok(())) {
// log::debug!("global listener {i} send {pos:?}");
} else {
// log::debug!("one global listener dropped");
global.remove(i);
len -= 1;
continue;
}
i += 1;
}
}
}
}
@@ -0,0 +1,428 @@
use super::{ChunkLevel, ChunkPos, HashMapType, LevelChannel};
use crate::chunk_system::chunk_state::StagedChunkEnum; // Fixed path
use itertools::Itertools;
use std::cmp::min;
use std::collections::VecDeque;
use std::collections::hash_map::Entry;
use std::fmt::Write;
use std::mem::swap;
use std::sync::Arc;
use tracing::debug;
struct LevelCache(i32, i32, usize, [(i8, i8); 256 * 256]);
#[expect(clippy::large_stack_arrays)]
impl LevelCache {
const fn new() -> Self {
Self(0, 0, 0, [(0, 0); 256 * 256])
}
}
impl LevelCache {
fn clean(&mut self, pos: ChunkPos, level: i8) {
let dst = ChunkLoading::MAX_LEVEL - level + 1;
self.0 = pos.x - dst as i32;
self.1 = pos.y - dst as i32;
self.2 = (dst as usize) << 1 | 1;
self.3[..self.2 * self.2].fill((-127, -127));
}
fn get(&mut self, map: &ChunkLevel, pos: ChunkPos) -> i8 {
let dx = (pos.x - self.0) as usize;
let dy = (pos.y - self.1) as usize;
debug_assert!(pos.x >= self.0 && pos.y >= self.1);
let value = &mut self.3[dx * self.2 + dy];
if value.0 == -127 {
value.0 = *map.get(&pos).unwrap_or(&ChunkLoading::MAX_LEVEL);
value.1 = value.0;
}
value.1
}
fn set(&mut self, map: &ChunkLevel, pos: ChunkPos, level: i8) {
let dx = (pos.x - self.0) as usize;
let dy = (pos.y - self.1) as usize;
debug_assert!(pos.x >= self.0 && pos.y >= self.1);
let value = &mut self.3[dx * self.2 + dy];
if value.0 == -127 {
value.0 = *map.get(&pos).unwrap_or(&ChunkLoading::MAX_LEVEL);
}
value.1 = level;
}
fn write(
&self,
map: &mut ChunkLevel,
change: &mut HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
) {
for i in 0..self.2 {
for j in 0..self.2 {
let value = self.3[i * self.2 + j];
if value.0 != value.1 {
let pos = ChunkPos::new(i as i32 + self.0, j as i32 + self.1);
if value.1 == ChunkLoading::MAX_LEVEL {
map.remove(&pos);
} else {
map.insert(pos, value.1);
}
let value = (
StagedChunkEnum::level_to_stage(value.0),
StagedChunkEnum::level_to_stage(value.1),
);
if value.0 == value.1 {
continue;
}
match change.entry(pos) {
Entry::Occupied(mut entry) => {
let i = entry.get_mut();
debug_assert_eq!(i.1, value.0);
if i.0 == value.1 {
entry.remove();
} else {
i.1 = value.1;
}
}
Entry::Vacant(entry) => {
entry.insert(value);
}
}
}
}
}
}
}
pub struct ChunkLoading {
pub is_priority_dirty: bool,
pub pos_level: ChunkLevel,
change: HashMapType<ChunkPos, (StagedChunkEnum, StagedChunkEnum)>,
pub ticket: HashMapType<ChunkPos, Vec<i8>>, // TODO lifetime & id
pub high_priority: Vec<ChunkPos>,
pub sender: Arc<LevelChannel>,
pub increase_update: VecDeque<(ChunkPos, i8)>,
pub decrease_update: VecDeque<(ChunkPos, i8)>,
cache: LevelCache,
}
impl ChunkLoading {
// pub const FULL_CHUNK_LEVEL: i8 = 33;
pub const FULL_CHUNK_LEVEL: i8 = 43;
pub const MAX_LEVEL: i8 = 49; // level 49 will be unloaded.
fn debug_check_error(&self) -> bool {
let mut temp = ChunkLevel::default();
for (ticket_pos, levels) in &self.ticket {
let level = *levels.iter().min().unwrap();
let range = Self::MAX_LEVEL - level - 1;
for dx in -range..=range {
for dy in -range..=range {
let new_pos = ticket_pos.add_raw(dx as i32, dy as i32);
let level_from_source = level + dx.abs().max(dy.abs());
let i = temp.entry(new_pos).or_insert(Self::MAX_LEVEL);
*i = min(*i, level_from_source);
}
}
}
if temp.len() != self.pos_level.len() {
debug!("temp: \n{temp:?}");
debug!("pos_level: \n{:?}", self.pos_level);
}
assert_eq!(temp.len(), self.pos_level.len());
for val in &temp {
if val != self.pos_level.get_key_value(val.0).unwrap() {
Self::dump_level_debug(
&self.high_priority,
&self.pos_level,
val.0.x - 40,
val.0.x + 40,
val.0.y - 40,
val.0.y + 40,
);
}
assert_eq!(val, self.pos_level.get_key_value(val.0).unwrap());
}
true
}
pub fn dump_level_debug(
pri: &[ChunkPos],
map: &ChunkLevel,
sx: i32,
tx: i32,
sy: i32,
ty: i32,
) {
debug!("high_priority {pri:?}");
let mut header = "X/Y".to_string();
for y in sy..=ty {
let _ = write!(header, "{y:4}");
}
let grid: String = (sx..=tx)
.map(|x| {
let mut row = format!("{x:3}");
let mut cols = String::new();
for y in sy..=ty {
let _ = write!(
cols,
"{:4}",
map.get(&ChunkPos::new(x, y)).unwrap_or(&Self::MAX_LEVEL)
);
}
row.push_str(&cols);
row
})
.collect::<Vec<_>>()
.join("\n");
debug!("\nloading level:\n{header}\n{grid}");
}
#[inline]
#[must_use]
pub const fn get_level_from_view_distance(view_distance: u8) -> i8 {
Self::FULL_CHUNK_LEVEL - (view_distance as i8)
}
#[inline]
#[must_use]
pub const fn get_level_from_simulation_distance(simulation_distance: u8) -> i8 {
Self::FULL_CHUNK_LEVEL - (simulation_distance as i8)
}
pub fn new(sender: Arc<LevelChannel>) -> Self {
Self {
is_priority_dirty: true,
pos_level: ChunkLevel::default(),
change: HashMapType::default(),
ticket: HashMapType::default(),
high_priority: Vec::new(),
sender,
increase_update: VecDeque::default(),
decrease_update: VecDeque::default(),
cache: LevelCache::new(),
}
}
pub fn send_change(&mut self) {
// debug!("sending change");
if !self.change.is_empty() {
let mut tmp = HashMapType::default();
swap(&mut tmp, &mut self.change);
if self.is_priority_dirty {
self.is_priority_dirty = false;
self.sender
.set_both((tmp, self.pos_level.clone()), self.high_priority.clone());
} else {
self.sender.set_level((tmp, self.pos_level.clone()));
}
}
if self.is_priority_dirty {
self.is_priority_dirty = false;
self.sender.set_priority(self.high_priority.clone());
}
}
fn run_increase_update(&mut self) {
while let Some((pos, level)) = self.increase_update.pop_front() {
debug_assert!(level < Self::MAX_LEVEL);
if level > self.cache.get(&self.pos_level, pos) {
continue;
}
debug_assert_eq!(level, self.cache.get(&self.pos_level, pos));
let spread_level = level + 1;
if spread_level >= Self::MAX_LEVEL {
continue;
}
for dx in -1..2 {
for dy in -1..2 {
let new_pos = pos.add_raw(dx, dy);
if new_pos != pos {
self.check_then_push(new_pos, spread_level);
}
}
}
}
}
fn check_then_push(&mut self, pos: ChunkPos, level: i8) {
debug_assert!(level < Self::MAX_LEVEL);
let old = self.cache.get(&self.pos_level, pos);
if old <= level {
return;
}
self.cache.set(&self.pos_level, pos, level);
self.increase_update.push_back((pos, level));
}
fn run_decrease_update(&mut self, pos: ChunkPos, range: i32) {
while let Some((pos, level)) = self.decrease_update.pop_front() {
debug_assert!(level < Self::MAX_LEVEL);
let spread_level = level + 1;
for dx in -1..2 {
for dy in -1..2 {
let new_pos = pos.add_raw(dx, dy);
if new_pos == pos {
continue;
}
let new_pos_level = self.cache.get(&self.pos_level, new_pos);
if new_pos_level == Self::MAX_LEVEL {
continue;
}
debug_assert!(new_pos_level <= spread_level);
if new_pos_level == spread_level {
self.cache.set(&self.pos_level, new_pos, Self::MAX_LEVEL);
if spread_level < Self::MAX_LEVEL {
self.decrease_update.push_back((new_pos, spread_level));
}
} else {
self.increase_update.push_back((new_pos, new_pos_level));
}
}
}
}
for (ticket_pos, levels) in &self.ticket {
if (ticket_pos.x - pos.x).abs() <= range && (ticket_pos.y - pos.y).abs() <= range {
let level = *levels.iter().min().unwrap();
debug_assert!(level < Self::MAX_LEVEL);
let old = self.cache.get(&self.pos_level, *ticket_pos);
if old <= level {
continue;
}
self.cache.set(&self.pos_level, *ticket_pos, level);
self.increase_update.push_back((*ticket_pos, level));
}
}
self.run_increase_update();
}
pub fn add_force_ticket(&mut self, pos: ChunkPos) {
// debug!("add force ticket at {pos:?}");
self.high_priority.push(pos);
self.is_priority_dirty = true;
self.add_ticket(pos, Self::FULL_CHUNK_LEVEL);
}
pub fn remove_force_ticket(&mut self, pos: ChunkPos) {
// debug!("remove force ticket at {pos:?}");
let index = self
.high_priority
.iter()
.find_position(|x| **x == pos)
.unwrap()
.0;
self.high_priority.remove(index);
self.is_priority_dirty = true;
self.remove_ticket(pos, Self::FULL_CHUNK_LEVEL);
}
pub fn add_ticket(&mut self, pos: ChunkPos, level: i8) {
// debug!("add ticket at {pos:?} level {level}");
debug_assert!(level < Self::MAX_LEVEL);
match self.ticket.entry(pos) {
Entry::Occupied(mut vec) => {
vec.get_mut().push(level);
}
Entry::Vacant(empty) => {
empty.insert(vec![level]);
}
}
let old = *self.pos_level.get(&pos).unwrap_or(&Self::MAX_LEVEL);
if old <= level {
return;
}
self.cache.clean(pos, level);
self.cache.set(&self.pos_level, pos, level);
debug_assert!(self.increase_update.is_empty());
self.increase_update.push_back((pos, level));
self.run_increase_update();
self.cache.write(&mut self.pos_level, &mut self.change);
debug_assert!(self.debug_check_error());
}
pub fn remove_ticket(&mut self, pos: ChunkPos, level: i8) {
// debug!("remove ticket at {pos:?} level {level}");
debug_assert!(level < Self::MAX_LEVEL);
let Some(vec) = self.ticket.get_mut(&pos) else {
// warn!("No ticket found at {pos:?}");
return;
};
let Some((index, _)) = vec.iter().find_position(|x| **x == level) else {
// warn!("No ticket found at {pos:?}");
return;
};
vec.remove(index);
match self.pos_level.entry(pos) {
Entry::Occupied(entry) => {
let old_level = *entry.get();
let source = *vec.iter().min().unwrap_or(&Self::MAX_LEVEL);
if vec.is_empty() {
self.ticket.remove(&pos);
}
if level == old_level && source != level {
self.cache.clean(pos, old_level);
self.cache.set(&self.pos_level, pos, Self::MAX_LEVEL);
debug_assert!(self.decrease_update.is_empty());
self.decrease_update.push_back((pos, level));
self.run_decrease_update(pos, (Self::MAX_LEVEL - level - 1) as i32);
self.cache.write(&mut self.pos_level, &mut self.change);
}
}
Entry::Vacant(_) => panic!(),
}
debug_assert!(self.debug_check_error());
}
}
#[test]
#[expect(clippy::print_stdout)]
fn test() {
let mut a = ChunkLoading::new(Arc::new(LevelChannel::new()));
a.add_ticket((0, 0).into(), 44);
a.add_ticket((0, 1).into(), 44);
a.remove_ticket((0, 0).into(), 44);
a.add_ticket((0, 0).into(), 30);
a.add_ticket((0, 10).into(), 25);
a.add_ticket((10, 10).into(), 26);
a.add_ticket((10, 10).into(), 26);
a.remove_ticket((0, 0).into(), 30);
a.remove_ticket((0, 10).into(), 25);
a.remove_ticket((10, 10).into(), 26);
a.remove_ticket((10, 10).into(), 26);
a.add_ticket((-72, 457).into(), 24);
a.add_ticket((-72, 455).into(), 33);
a.add_ticket((-72, 456).into(), 24);
a.remove_ticket((-72, 457).into(), 24);
a.add_ticket((-72, 455).into(), 24);
a.add_ticket((-59, 495).into(), 33);
a.add_ticket((-51, 504).into(), 24);
a.remove_ticket((-51, 504).into(), 24);
let sx = -59;
let tx = -51;
let sy = 495;
let ty = 504;
{
let mut header = "X/Y".to_string();
for y in sy..=ty {
let _ = write!(header, "{y:4}");
}
let grid: String = (sx..=tx)
.map(|x| {
let mut row = format!("{x:3}");
for y in sy..=ty {
let level = a
.pos_level
.get(&ChunkPos::new(x, y))
.unwrap_or(&ChunkLoading::MAX_LEVEL);
let _ = write!(row, "{level:4}");
}
row
})
.collect::<Vec<_>>()
.join("\n");
println!("\nloading level:\n{header}\n{grid}");
}
}
@@ -0,0 +1,331 @@
use crate::chunk::{
ChunkData, ChunkHeightmapType, ChunkHeightmaps, ChunkLight, ChunkSections,
palette::{BiomePalette, BlockPalette},
};
use crate::generation::biome_coords;
use crate::tick::scheduler::ChunkTickScheduler;
use pumpkin_config::lighting::LightingEngineConfig;
use pumpkin_data::dimension::Dimension;
use rustc_hash::FxHashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64};
use crate::ProtoChunk;
use crate::level::SyncChunk;
use pumpkin_data::chunk::ChunkStatus;
use std::sync::Mutex;
#[repr(u8)]
#[derive(Debug, Copy, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub enum StagedChunkEnum {
None,
/// Initial empty chunk, ready for biome population
Empty = 1, // EMPTY STRUCTURE_STARTS STRUCTURE_REFERENCES
/// Chunk with biomes populated, ready for noise generation
Biomes,
StructureStart,
StructureReferences,
/// Chunk with terrain noise generated, ready for surface building
Noise,
/// Chunk with surface built, ready for carvers
Surface,
/// Chunk with carvers applied, ready for features and structures
Carvers,
/// Chunk with features and structures, ready for lighting
Features, // FEATURES
/// Chunk with lighting calculated, ready for spawning
Lighting, // INITIALIZE LIGHT
/// Chunk with mobs spawned, ready for finalization
Spawn, // SPAWN
/// Fully generated chunk
Full,
}
#[expect(clippy::fallible_impl_from)]
impl From<u8> for StagedChunkEnum {
fn from(v: u8) -> Self {
match v {
1 => Self::Empty,
2 => Self::Biomes,
3 => Self::StructureStart,
4 => Self::StructureReferences,
5 => Self::Noise,
6 => Self::Surface,
7 => Self::Carvers,
8 => Self::Features,
9 => Self::Lighting,
10 => Self::Spawn,
11 => Self::Full,
_ => panic!(),
}
}
}
impl From<ChunkStatus> for StagedChunkEnum {
fn from(status: ChunkStatus) -> Self {
match status {
ChunkStatus::Empty => Self::Empty,
ChunkStatus::StructureStarts => Self::StructureStart,
ChunkStatus::StructureReferences => Self::StructureReferences,
ChunkStatus::Biomes => Self::Biomes,
ChunkStatus::Noise => Self::Noise,
ChunkStatus::Surface => Self::Surface,
ChunkStatus::Carvers => Self::Carvers,
ChunkStatus::Features => Self::Features,
ChunkStatus::InitializeLight | ChunkStatus::Light => Self::Lighting,
ChunkStatus::Spawn => Self::Spawn,
ChunkStatus::Full => Self::Full,
}
}
}
#[expect(clippy::fallible_impl_from)]
impl From<StagedChunkEnum> for ChunkStatus {
fn from(status: StagedChunkEnum) -> Self {
match status {
StagedChunkEnum::Empty => Self::Empty,
StagedChunkEnum::StructureStart => Self::StructureStarts,
StagedChunkEnum::StructureReferences => Self::StructureReferences,
StagedChunkEnum::Biomes => Self::Biomes,
StagedChunkEnum::Noise => Self::Noise,
StagedChunkEnum::Surface => Self::Surface,
StagedChunkEnum::Carvers => Self::Carvers,
StagedChunkEnum::Features => Self::Features,
StagedChunkEnum::Lighting => Self::Light,
StagedChunkEnum::Spawn => Self::Spawn,
StagedChunkEnum::Full => Self::Full,
StagedChunkEnum::None => panic!(),
}
}
}
impl StagedChunkEnum {
#[must_use]
pub const fn level_to_stage(level: i8) -> Self {
if level <= 43 {
Self::Full
} else if level <= 44 {
Self::Spawn
} else if level <= 45 {
Self::Lighting
} else if level <= 46 {
Self::Features
} else if level <= 47 {
Self::Carvers
} else if level <= 48 {
Self::Surface
} else {
Self::None
}
}
/// Total number of state values (0 = None … 11 = Full).
pub const COUNT: usize = Self::Full as usize + 1;
pub const FULL_DEPENDENCIES: &'static [Self] = &[
Self::Full,
Self::Spawn,
Self::Lighting,
Self::Features,
Self::Carvers,
Self::Surface,
];
pub const FULL_RADIUS: i32 = 4;
#[must_use]
pub const fn get_direct_radius(self) -> i32 {
// self exclude
match self {
Self::Features | Self::Lighting | Self::Spawn | Self::Full => 1,
_ => 0,
}
}
#[must_use]
pub const fn get_write_radius(self) -> i32 {
// self exclude
match self {
Self::Features | Self::Lighting | Self::Spawn => 1,
_ => 0,
}
}
#[must_use]
pub const fn get_direct_dependencies(self) -> &'static [Self] {
match self {
// In vanilla StructureStart is first, but since it needs the biome in Vanilla it gets computed in StructureStart and
// the Biome Step, this should be more efficient
Self::Biomes => &[Self::Empty],
Self::StructureStart => &[Self::Biomes],
Self::StructureReferences => &[
Self::StructureStart,
Self::StructureStart,
Self::StructureStart,
Self::StructureStart,
Self::StructureStart,
Self::StructureStart,
Self::StructureStart,
Self::StructureStart,
Self::StructureStart,
],
Self::Noise => &[Self::StructureReferences],
Self::Surface => &[Self::Noise],
Self::Carvers => &[Self::Surface],
Self::Features => &[Self::Carvers, Self::Carvers],
Self::Lighting => &[Self::Features, Self::Features],
Self::Spawn => &[Self::Lighting, Self::Lighting],
Self::Full => &[Self::Spawn, Self::Spawn],
_ => panic!(),
}
}
}
pub enum Chunk {
Level(SyncChunk),
Proto(Box<ProtoChunk>),
}
impl Chunk {
#[must_use]
pub fn get_stage_id(&self) -> u8 {
match self {
Self::Proto(data) => data.stage_id(),
Self::Level(_) => StagedChunkEnum::Full as u8,
}
}
pub fn get_proto_chunk_mut(&mut self) -> &mut ProtoChunk {
match self {
Self::Level(_) => panic!("chunk isn't a ProtoChunk"),
Self::Proto(chunk) => chunk,
}
}
#[must_use]
pub fn get_proto_chunk(&self) -> &ProtoChunk {
match self {
Self::Level(_) => panic!("chunk isn't a ProtoChunk"),
Self::Proto(chunk) => chunk,
}
}
fn build_level_sections(proto_chunk: &ProtoChunk, dimension: &Dimension) -> ChunkSections {
let total_sections = dimension.height as usize / BlockPalette::SIZE;
let biome_min_y = biome_coords::from_block(dimension.min_y);
let block_sections = (0..total_sections)
.map(|section_index| {
BlockPalette::from_fn(|x, y, z| {
let y = section_index * BlockPalette::SIZE + y;
proto_chunk.get_block_state_raw(x as i32, y as i32, z as i32)
})
})
.collect::<Vec<_>>()
.into_boxed_slice();
let biome_sections = (0..total_sections)
.map(|section_index| {
BiomePalette::from_fn(|x, y, z| {
let y = section_index * BiomePalette::SIZE + y;
proto_chunk.get_biome_id(x as i32, biome_min_y + y as i32, z as i32)
})
})
.collect::<Vec<_>>()
.into_boxed_slice();
ChunkSections::from_palettes(block_sections, biome_sections, dimension.min_y)
}
fn build_level_heightmaps(proto_chunk: &ProtoChunk, min_y: i32) -> ChunkHeightmaps {
let mut heightmaps = ChunkHeightmaps::default();
for x in 0..16 {
for z in 0..16 {
let source_index = x * 16 + z;
for (heightmap_type, height) in [
(
ChunkHeightmapType::WorldSurface,
proto_chunk.flat_surface_height_map[source_index],
),
(
ChunkHeightmapType::MotionBlocking,
proto_chunk.flat_motion_blocking_height_map[source_index],
),
(
ChunkHeightmapType::MotionBlockingNoLeaves,
proto_chunk.flat_motion_blocking_no_leaves_height_map[source_index],
),
] {
heightmaps.set(heightmap_type, x as i32, z as i32, i32::from(height), min_y);
}
}
}
heightmaps
}
pub fn upgrade_to_level_chunk(
&mut self,
dimension: &Dimension,
lighting_config: &LightingEngineConfig,
) {
// Take ownership of the ProtoChunk by temporarily replacing with a dummy value
// This allows us to move the light data instead of cloning it
let proto_chunk_box = match std::mem::replace(
self,
Self::Level(Arc::new(ChunkData {
section: ChunkSections::new(0, 0),
heightmap: Mutex::default(),
x: 0,
z: 0,
block_ticks: ChunkTickScheduler::default(),
fluid_ticks: ChunkTickScheduler::default(),
pending_block_entities: Mutex::default(),
light_engine: Mutex::new(ChunkLight::default()),
light_populated: AtomicBool::new(false),
status: ChunkStatus::Empty,
blending_data: None,
dirty: AtomicBool::new(false),
inhabited_time: AtomicU64::new(0),
})),
) {
Self::Proto(proto) => proto,
Self::Level(_) => panic!("Cannot upgrade a Level chunk"),
};
let proto_chunk = *proto_chunk_box;
let sections = Self::build_level_sections(&proto_chunk, dimension);
let heightmaps = Self::build_level_heightmaps(&proto_chunk, dimension.min_y);
// Move the light data instead of cloning it
// By taking ownership of proto_chunk, we can move the light data directly
// This prevents keeping duplicate lighting data in memory
let light_data = proto_chunk.light;
// Only mark lit if past the lighting stage, and the lighting config is "default" ("full" and "dark" modes skip proper lighting)
let is_lit = proto_chunk.stage >= StagedChunkEnum::Lighting
&& *lighting_config == LightingEngineConfig::Default;
// Convert pending block entities from structure generation to actual block entities
let mut pending_block_entities = FxHashMap::default();
for nbt in proto_chunk.pending_block_entities {
if let Some(x) = nbt.get_int("x")
&& let Some(y) = nbt.get_int("y")
&& let Some(z) = nbt.get_int("z")
{
pending_block_entities
.insert(pumpkin_util::math::position::BlockPos::new(x, y, z), nbt);
}
}
let chunk = ChunkData {
light_engine: Mutex::new(light_data),
light_populated: AtomicBool::new(is_lit),
section: sections,
heightmap: Mutex::new(heightmaps),
x: proto_chunk.x,
z: proto_chunk.z,
dirty: AtomicBool::new(true),
block_ticks: ChunkTickScheduler::default(),
fluid_ticks: ChunkTickScheduler::from_iter(proto_chunk.fluid_ticks),
pending_block_entities: Mutex::new(pending_block_entities),
status: proto_chunk.stage.into(),
blending_data: proto_chunk.blending_data,
inhabited_time: AtomicU64::new(0),
};
*self = Self::Level(Arc::new(chunk));
}
}
@@ -0,0 +1,72 @@
use super::ChunkPos;
use super::chunk_state::StagedChunkEnum;
use slotmap::{Key, SlotMap, new_key_type};
#[derive(Clone, Debug)]
pub struct Node {
pub pos: ChunkPos,
pub stage: StagedChunkEnum,
pub in_degree: u32,
pub in_queue: bool,
pub in_flight: bool,
pub edge: EdgeKey,
}
impl Node {
#[must_use]
pub fn new(pos: ChunkPos, stage: StagedChunkEnum) -> Self {
Self {
pos,
stage,
in_degree: 0,
in_queue: false,
in_flight: false,
edge: EdgeKey::null(),
}
}
}
#[derive(Clone, Debug)]
pub struct Edge {
pub to: NodeKey,
pub next: EdgeKey,
}
impl Edge {
#[must_use]
pub const fn new(to: NodeKey, next: EdgeKey) -> Self {
Self { to, next }
}
}
new_key_type! { pub struct NodeKey; }
new_key_type! { pub struct EdgeKey; }
#[derive(Default)]
pub struct DAG {
pub nodes: SlotMap<NodeKey, Node>,
pub edges: SlotMap<EdgeKey, Edge>,
}
impl DAG {
pub fn fast_drop_node(&mut self, node: NodeKey) {
let mut edge = self.nodes.remove(node).unwrap().edge;
// debug!("drop node {node:?}");
while !edge.is_null() {
edge = self.edges.remove(edge).unwrap().next;
}
}
pub fn add_edge(&mut self, from: NodeKey, to: NodeKey) {
// Ensure both nodes exist before adding edge
if !self.nodes.contains_key(to) || !self.nodes.contains_key(from) {
return;
}
if let Some(node) = self.nodes.get_mut(to) {
node.in_degree += 1;
}
if let Some(node) = self.nodes.get_mut(from) {
let edge = &mut node.edge;
*edge = self.edges.insert(Edge::new(to, *edge));
}
}
}
@@ -0,0 +1,389 @@
use pumpkin_data::dimension::Dimension;
use crate::ProtoChunk;
use crate::generation::generator::WorldGenerator;
use crate::world::WorldPortalExt;
use pumpkin_config::lighting::LightingEngineConfig;
use super::{Cache, Chunk, StagedChunkEnum};
pub fn generate_single_chunk(
dimension: &Dimension,
biome_mixer_seed: i64,
generator: &WorldGenerator,
block_registry: &dyn WorldPortalExt,
chunk_x: i32,
chunk_z: i32,
target_stage: StagedChunkEnum,
) -> Chunk {
generate_single_chunk_with_radius(
dimension,
biome_mixer_seed,
generator,
block_registry,
chunk_x,
chunk_z,
target_stage,
target_stage.get_direct_radius(),
)
}
#[expect(clippy::too_many_arguments)]
pub fn generate_single_chunk_with_radius(
_dimension: &Dimension,
_biome_mixer_seed: i64,
generator: &WorldGenerator,
block_registry: &dyn WorldPortalExt,
chunk_x: i32,
chunk_z: i32,
target_stage: StagedChunkEnum,
radius: i32,
) -> Chunk {
let mut cache = Cache::new(chunk_x - radius, chunk_z - radius, radius * 2 + 1);
for dx in -radius..=radius {
for dz in -radius..=radius {
let new_x = chunk_x + dx;
let new_z = chunk_z + dz;
let proto_chunk = Box::new(ProtoChunk::new(new_x, new_z, generator));
cache.chunks.push(Chunk::Proto(proto_chunk));
}
}
let stages = [
StagedChunkEnum::Biomes,
StagedChunkEnum::StructureStart,
StagedChunkEnum::StructureReferences,
StagedChunkEnum::Noise,
StagedChunkEnum::Surface,
StagedChunkEnum::Carvers,
StagedChunkEnum::Features,
StagedChunkEnum::Lighting,
StagedChunkEnum::Spawn,
StagedChunkEnum::Full,
];
for &stage in &stages {
if stage as u8 > target_stage as u8 {
break;
}
if matches!(
stage,
StagedChunkEnum::Biomes
| StagedChunkEnum::StructureStart
| StagedChunkEnum::StructureReferences
) {
cache.advance_all(
stage,
generator,
block_registry,
&LightingEngineConfig::Default,
);
} else {
cache.advance(
stage,
generator,
block_registry,
&LightingEngineConfig::Default,
);
}
}
let mid = ((cache.size * cache.size) >> 1) as usize;
cache.chunks.swap_remove(mid)
}
#[cfg(test)]
mod tests {
use crate::biome::hash_seed;
use crate::chunk::ChunkHeightmapType;
use crate::chunk_system::Chunk;
use crate::chunk_system::{
StagedChunkEnum, generate_single_chunk, generation::generate_single_chunk_with_radius,
};
use crate::generation::get_world_gen;
use crate::world::WorldPortalExt;
use pumpkin_data::BlockStateId;
use pumpkin_data::dimension::Dimension;
use pumpkin_util::world_seed::Seed;
use std::sync::Arc;
struct BlockRegistry;
impl WorldPortalExt for BlockRegistry {
fn can_place_at(
&self,
_block: &pumpkin_data::Block,
_state: &pumpkin_data::BlockState,
_block_accessor: &dyn crate::world::BlockAccessor,
_block_pos: &pumpkin_util::math::position::BlockPos,
) -> bool {
true
}
fn mirror(
&self,
block: &pumpkin_data::Block,
state_id: BlockStateId,
mirror: pumpkin_data::Mirror,
) -> &'static pumpkin_data::BlockState {
block.mirror(state_id, mirror)
}
fn rotate(
&self,
block: &pumpkin_data::Block,
state_id: BlockStateId,
rotation: pumpkin_data::Rotation,
) -> &'static pumpkin_data::BlockState {
block.rotate(state_id, rotation)
}
fn spawn_mobs_for_chunk_generation(
&self,
_cache: &mut dyn crate::generation::proto_chunk::GenerationCache,
_biome: &'static pumpkin_data::chunk::Biome,
_chunk_x: i32,
_chunk_z: i32,
) {
}
}
#[test]
fn generate_chunk_should_return() {
let dimension = Dimension::OVERWORLD;
let seed = Seed(42);
let block_registry = Arc::new(BlockRegistry);
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
let biome_mixer_seed = hash_seed(world_gen.seed());
let chunk = generate_single_chunk(
&dimension,
biome_mixer_seed,
&world_gen,
block_registry.as_ref(),
0,
0,
StagedChunkEnum::Full,
);
let Chunk::Level(chunk) = chunk else {
panic!("full generation must return a level chunk");
};
let recalculated = chunk.calculate_heightmap();
let generated = chunk.heightmap.lock().unwrap();
for x in 0..16 {
for z in 0..16 {
for heightmap_type in [
ChunkHeightmapType::WorldSurface,
ChunkHeightmapType::MotionBlocking,
ChunkHeightmapType::MotionBlockingNoLeaves,
] {
assert_eq!(
generated.get(heightmap_type, x, z, chunk.section.min_y),
recalculated.get(heightmap_type, x, z, chunk.section.min_y),
);
}
}
}
}
#[test]
fn configured_seed_generates_vanilla_ancient_city_chunk() {
let dimension = Dimension::OVERWORLD;
let seed = Seed(1_782_124_772_053_846_960);
let block_registry = Arc::new(BlockRegistry);
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
let biome_mixer_seed = hash_seed(world_gen.seed());
let chunk = generate_single_chunk(
&dimension,
biome_mixer_seed,
&world_gen,
block_registry.as_ref(),
31,
-12,
StagedChunkEnum::Features,
);
let super::Chunk::Proto(chunk) = chunk else {
panic!("features stage should return a proto chunk");
};
let mut city_blocks = 0;
let mut jigsaw_blocks = 0;
for x in 496..512 {
for z in -192..-176 {
for y in -64..320 {
let block = chunk
.get_block_state(&pumpkin_util::math::vector3::Vector3::new(x, y, z))
.to_block_id();
if [
pumpkin_data::Block::DEEPSLATE_BRICKS.id,
pumpkin_data::Block::POLISHED_DEEPSLATE.id,
pumpkin_data::Block::REINFORCED_DEEPSLATE.id,
pumpkin_data::Block::SCULK.id,
]
.contains(&block)
{
city_blocks += 1;
}
if block == pumpkin_data::Block::JIGSAW.id {
jigsaw_blocks += 1;
}
}
}
}
assert!(
city_blocks > 0,
"reference chunk contains no Ancient City blocks"
);
assert_eq!(jigsaw_blocks, 0, "jigsaw blocks were not replaced");
}
#[test]
fn seed_zero_generates_the_vanilla_pillager_outpost_chunk() {
let dimension = Dimension::OVERWORLD;
let seed = Seed(1_782_124_772_053_846_960);
let block_registry = Arc::new(BlockRegistry);
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
let biome_mixer_seed = hash_seed(world_gen.seed());
let chunk = generate_single_chunk_with_radius(
&dimension,
biome_mixer_seed,
&world_gen,
block_registry.as_ref(),
73,
-82,
StagedChunkEnum::Spawn,
16,
);
let super::Chunk::Proto(chunk) = chunk else {
panic!("spawn stage should return a proto chunk");
};
let mut outpost_blocks = 0;
let mut jigsaw_blocks = 0;
for x in 1168..1184 {
for z in -1328..-1312 {
for y in -64..320 {
let block = chunk
.get_block_state(&pumpkin_util::math::vector3::Vector3::new(x, y, z))
.to_block_id();
if [
pumpkin_data::Block::DARK_OAK_LOG.id,
pumpkin_data::Block::DARK_OAK_PLANKS.id,
pumpkin_data::Block::DARK_OAK_FENCE.id,
]
.contains(&block)
{
outpost_blocks += 1;
}
if block == pumpkin_data::Block::JIGSAW.id {
jigsaw_blocks += 1;
}
}
}
}
assert!(
outpost_blocks > 0,
"reference chunk contains no outpost blocks"
);
assert_eq!(jigsaw_blocks, 0, "jigsaw blocks were not replaced");
}
#[test]
fn fixed_seed_generates_vanilla_end_ship_chunk() {
// Vanilla 26.2 places this seed's ship in chunk (-306, -275).
let dimension = Dimension::THE_END;
let seed = Seed(12_345);
let block_registry = Arc::new(BlockRegistry);
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
let biome_mixer_seed = hash_seed(world_gen.seed());
let chunk = generate_single_chunk_with_radius(
&dimension,
biome_mixer_seed,
&world_gen,
block_registry.as_ref(),
-306,
-275,
StagedChunkEnum::Features,
16,
);
let Chunk::Proto(chunk) = chunk else {
panic!("features stage should return a proto chunk");
};
let mut non_air = 0;
for y in 123..=146 {
for x in -4896..=-4881 {
for z in -4405..=-4393 {
let state =
chunk.get_block_state(&pumpkin_util::math::vector3::Vector3::new(x, y, z));
non_air += usize::from(!state.to_state().is_air());
}
}
}
assert_eq!(non_air, 14);
assert!(chunk.pending_block_entities.iter().any(|nbt| {
nbt.get_string("id") == Some("minecraft:skull")
&& nbt.get_int("x") == Some(-4888)
&& nbt.get_int("y") == Some(131)
&& nbt.get_int("z") == Some(-4399)
}));
assert_eq!(
chunk
.pending_block_entities
.iter()
.filter(
|nbt| nbt.get_string("LootTable") == Some("minecraft:chests/end_city_treasure")
)
.count(),
2
);
}
#[test]
fn pillager_outpost_features_shape_ground_at_vanilla_height() {
let dimension = Dimension::OVERWORLD;
let seed = Seed(1_782_124_772_053_846_960);
let block_registry = Arc::new(BlockRegistry);
let world_gen = get_world_gen(seed, dimension.clone(), false, Vec::new(), String::new());
let biome_mixer_seed = hash_seed(world_gen.seed());
let chunk = generate_single_chunk(
&dimension,
biome_mixer_seed,
&world_gen,
block_registry.as_ref(),
73,
-82,
StagedChunkEnum::Features,
);
let super::Chunk::Proto(chunk) = chunk else {
panic!("features stage should return a proto chunk");
};
for (x, y, z) in [(1173, 70, -1311), (1173, 70, -1305)] {
let state = chunk.get_block_state(&pumpkin_util::math::vector3::Vector3::new(x, y, z));
assert_eq!(state.to_block_id(), pumpkin_data::Block::GRASS_BLOCK.id);
}
let cage_chunk = generate_single_chunk(
&dimension,
biome_mixer_seed,
&world_gen,
block_registry.as_ref(),
73,
-84,
StagedChunkEnum::Features,
);
let super::Chunk::Proto(cage_chunk) = cage_chunk else {
panic!("features stage should return a proto chunk");
};
let state =
cage_chunk.get_block_state(&pumpkin_util::math::vector3::Vector3::new(1183, 68, -1330));
assert_eq!(state.to_block_id(), pumpkin_data::Block::GRASS_BLOCK.id);
}
}
@@ -0,0 +1,514 @@
use super::chunk_state::{Chunk, StagedChunkEnum};
use crate::ProtoChunk;
use crate::chunk::ChunkHeightmapType;
use crate::generation::generator;
use crate::generation::height_limit::HeightLimitView;
use crate::generation::proto_chunk::GenerationCache;
use crate::world::{BlockAccessor, WorldPortalExt};
use pumpkin_config::lighting::LightingEngineConfig;
use pumpkin_data::biome::Biome;
use pumpkin_data::block_properties::is_air;
use pumpkin_data::fluid::{Fluid, FluidState};
use pumpkin_data::{Block, BlockState, BlockStateId};
use pumpkin_nbt::compound::NbtCompound;
use pumpkin_util::HeightMap;
use pumpkin_util::math::position::BlockPos;
use pumpkin_util::math::vector3::Vector3;
use tracing::debug;
pub struct Cache {
pub x: i32,
pub z: i32,
pub size: i32,
pub chunks: Vec<Chunk>,
}
impl HeightLimitView for Cache {
fn height(&self) -> u16 {
let mid = ((self.size * self.size) >> 1) as usize;
match &self.chunks[mid] {
Chunk::Proto(chunk) => chunk.height(),
Chunk::Level(_) => panic!(),
}
}
fn bottom_y(&self) -> i8 {
let mid = ((self.size * self.size) >> 1) as usize;
match &self.chunks[mid] {
Chunk::Proto(chunk) => chunk.bottom_y(),
Chunk::Level(_) => panic!(),
}
}
}
impl BlockAccessor for Cache {
fn get_block(&self, position: &BlockPos) -> &'static Block {
GenerationCache::get_block_state(self, &position.0).to_block()
}
fn get_block_state(&self, position: &BlockPos) -> &'static BlockState {
GenerationCache::get_block_state(self, &position.0).to_state()
}
fn get_block_state_id(&self, position: &BlockPos) -> BlockStateId {
GenerationCache::get_block_state(self, &position.0)
}
fn get_block_and_state(&self, position: &BlockPos) -> (&'static Block, &'static BlockState) {
let id = GenerationCache::get_block_state(self, &position.0);
BlockState::from_id_with_block(id)
}
}
impl GenerationCache for Cache {
fn get_chunk_mut(&mut self, chunk_x: i32, chunk_z: i32) -> Option<&mut ProtoChunk> {
let dx = chunk_x - self.x;
let dz = chunk_z - self.z;
if dx < 0 || dx >= self.size || dz < 0 || dz >= self.size {
return None;
}
match &mut self.chunks[(dx * self.size + dz) as usize] {
Chunk::Proto(chunk) => Some(chunk),
Chunk::Level(_) => None,
}
}
fn get_chunk(&self, chunk_x: i32, chunk_z: i32) -> Option<&ProtoChunk> {
let dx = chunk_x - self.x;
let dz = chunk_z - self.z;
if dx < 0 || dx >= self.size || dz < 0 || dz >= self.size {
return None;
}
match &self.chunks[(dx * self.size + dz) as usize] {
Chunk::Proto(chunk) => Some(chunk),
Chunk::Level(_) => None,
}
}
fn try_get_proto_chunk(&self, chunk_x: i32, chunk_z: i32) -> Option<&ProtoChunk> {
let dx = chunk_x - self.x;
let dz = chunk_z - self.z;
if dx < 0 || dx >= self.size || dz < 0 || dz >= self.size {
return None;
}
match &self.chunks[(dx * self.size + dz) as usize] {
Chunk::Proto(chunk) => Some(chunk),
Chunk::Level(_) => None,
}
}
fn get_center_chunk(&self) -> &ProtoChunk {
let mid = ((self.size * self.size) >> 1) as usize;
self.chunks[mid].get_proto_chunk()
}
fn get_center_chunk_mut(&mut self) -> &mut ProtoChunk {
let mid = ((self.size * self.size) >> 1) as usize;
self.chunks[mid].get_proto_chunk_mut()
}
fn get_fluid_and_fluid_state(&self, pos: &Vector3<i32>) -> (Fluid, FluidState) {
let id = GenerationCache::get_block_state(self, pos);
let Some(fluid) = Fluid::from_state_id(id) else {
let block = Block::from_state_id(id);
if let Some(properties) = block.properties(id) {
for (name, value) in properties.to_props() {
if name == "waterlogged" {
if value == "true" {
let fluid = Fluid::FLOWING_WATER;
let state = fluid.states[0].clone();
return (fluid, state);
}
break;
}
}
}
let fluid = Fluid::EMPTY;
let state = fluid.states[0].clone();
return (fluid, state);
};
//let state = fluid.get_state(id);
let state = fluid.states[0].clone();
(fluid.clone(), state)
}
fn get_block_state(&self, pos: &Vector3<i32>) -> BlockStateId {
let dx = (pos.x >> 4) - self.x;
let dz = (pos.z >> 4) - self.z;
// debug_assert!(dx < self.size && dz < self.size);
// debug_assert!(dx >= 0 && dz >= 0);
if !(dx < self.size && dz < self.size && dx >= 0 && dz >= 0) {
// breakpoint here
debug!(
"illegal get_block_state {pos:?} cache pos ({}, {}) size {}",
self.x, self.z, self.size
);
return BlockStateId::AIR;
}
match &self.chunks[(dx * self.size + dz) as usize] {
Chunk::Level(data) => data
.section
.get_block_absolute_y((pos.x & 15) as usize, pos.y, (pos.z & 15) as usize)
.unwrap_or(BlockStateId::AIR),
Chunk::Proto(data) => data.get_block_state(pos),
}
}
fn set_block_state(&mut self, pos: &Vector3<i32>, block_state: &BlockState) {
let dx = (pos.x >> 4) - self.x;
let dz = (pos.z >> 4) - self.z;
// debug_assert!(dx < self.size && dz < self.size);
// debug_assert!(dx >= 0 && dz >= 0);
if !(dx < self.size && dz < self.size && dx >= 0 && dz >= 0) {
// breakpoint here
debug!(
"illegal set_block_state {pos:?} cache pos ({}, {}) size {}",
self.x, self.z, self.size
);
return;
}
match &mut self.chunks[(dx * self.size + dz) as usize] {
Chunk::Level(data) => {
data.set_block_absolute_y(
(pos.x & 15) as usize,
pos.y,
(pos.z & 15) as usize,
block_state.id,
);
}
Chunk::Proto(data) => {
data.set_block_state(pos.x, pos.y, pos.z, block_state);
}
}
}
fn add_block_entity(&mut self, pos: &Vector3<i32>, nbt: NbtCompound) {
let dx = (pos.x >> 4) - self.x;
let dz = (pos.z >> 4) - self.z;
if !(dx < self.size && dz < self.size && dx >= 0 && dz >= 0) {
debug!(
"illegal add_block_entity {pos:?} cache pos ({}, {}) size {}",
self.x, self.z, self.size
);
return;
}
match &mut self.chunks[(dx * self.size + dz) as usize] {
Chunk::Level(_) => {
debug!("add_block_entity on non-proto chunk at {pos:?}");
}
Chunk::Proto(data) => {
data.add_block_entity(nbt);
}
}
}
fn get_top_y(&self, heightmap: &HeightMap, x: i32, z: i32) -> i32 {
match heightmap {
HeightMap::WorldSurfaceWg | HeightMap::WorldSurface => {
self.top_block_height_exclusive(x, z)
}
HeightMap::OceanFloorWg | HeightMap::OceanFloor => {
self.ocean_floor_height_exclusive(x, z)
}
HeightMap::MotionBlocking => self.top_motion_blocking_block_height_exclusive(x, z),
HeightMap::MotionBlockingNoLeaves => {
self.top_motion_blocking_block_no_leaves_height_exclusive(x, z)
}
}
}
fn top_motion_blocking_block_height_exclusive(&self, x: i32, z: i32) -> i32 {
let dx = (x >> 4) - self.x;
let dy = (z >> 4) - self.z;
debug_assert!(dx < self.size && dy < self.size);
debug_assert!(dx >= 0 && dy >= 0);
match &self.chunks[(dx * self.size + dy) as usize] {
Chunk::Level(data) => {
let heightmap = data.heightmap.lock().unwrap();
let min_y = data.section.min_y;
heightmap.get(ChunkHeightmapType::MotionBlocking, x, z, min_y)
}
Chunk::Proto(data) => data.top_motion_blocking_block_height_exclusive(x, z),
}
}
fn top_motion_blocking_block_no_leaves_height_exclusive(&self, x: i32, z: i32) -> i32 {
let dx = (x >> 4) - self.x;
let dy = (z >> 4) - self.z;
debug_assert!(dx < self.size && dy < self.size);
debug_assert!(dx >= 0 && dy >= 0);
match &self.chunks[(dx * self.size + dy) as usize] {
Chunk::Level(data) => {
let heightmap = data.heightmap.lock().unwrap();
let min_y = data.section.min_y;
heightmap.get(ChunkHeightmapType::MotionBlockingNoLeaves, x, z, min_y)
}
Chunk::Proto(data) => data.top_motion_blocking_block_no_leaves_height_exclusive(x, z),
}
}
fn top_block_height_exclusive(&self, x: i32, z: i32) -> i32 {
let dx = (x >> 4) - self.x;
let dy = (z >> 4) - self.z;
debug_assert!(dx < self.size && dy < self.size);
debug_assert!(dx >= 0 && dy >= 0);
match &self.chunks[(dx * self.size + dy) as usize] {
Chunk::Level(data) => {
let heightmap = data.heightmap.lock().unwrap();
let min_y = data.section.min_y;
heightmap.get(ChunkHeightmapType::WorldSurface, x, z, min_y) // can we return this?
}
Chunk::Proto(data) => data.top_block_height_exclusive(x, z),
}
}
fn ocean_floor_height_exclusive(&self, x: i32, z: i32) -> i32 {
let dx = (x >> 4) - self.x;
let dy = (z >> 4) - self.z;
if dx < 0 || dy < 0 || dx >= self.size || dy >= self.size {
return 0;
}
match &self.chunks[(dx * self.size + dy) as usize] {
Chunk::Level(_data) => {
0 // todo missing
}
Chunk::Proto(data) => data.ocean_floor_height_exclusive(x, z),
}
}
fn get_biome_for_terrain_gen(&self, x: i32, y: i32, z: i32) -> &'static Biome {
let dx = (x >> 4) - self.x;
let dy = (z >> 4) - self.z;
let (dx, dy) = if dx < 0 || dy < 0 || dx >= self.size || dy >= self.size {
// Position is outside the cache — fall back to the centre chunk's biome
let mid = self.size / 2;
(mid, mid)
} else {
(dx, dy)
};
match &self.chunks[(dx * self.size + dy) as usize] {
Chunk::Level(data) => {
// Could this happen?
Biome::from_id(
data.section
.get_rough_biome_absolute_y((x & 15) as usize, y, (z & 15) as usize)
.unwrap_or(0),
)
.unwrap()
}
Chunk::Proto(data) => data.get_terrain_gen_biome(x, y, z),
}
}
fn get_blending_data(
&self,
chunk_x: i32,
chunk_z: i32,
) -> Option<&crate::generation::blender::blending_data::BlendingData> {
let dx = chunk_x - self.x;
let dz = chunk_z - self.z;
if dx < 0 || dx >= self.size || dz < 0 || dz >= self.size {
return None;
}
match &self.chunks[(dx * self.size + dz) as usize] {
Chunk::Proto(chunk) => chunk.blending_data.as_ref(),
Chunk::Level(data) => data.blending_data.as_ref(),
}
}
fn is_air(&self, local_pos: &Vector3<i32>) -> bool {
is_air(GenerationCache::get_block_state(self, local_pos))
}
}
impl Cache {
pub fn advance_all(
&mut self,
stage: StagedChunkEnum,
generator: &generator::WorldGenerator,
block_registry: &dyn WorldPortalExt,
lighting_config: &LightingEngineConfig,
) {
for index in 0..self.chunks.len() {
self.advance_index(index, stage, generator, block_registry, lighting_config);
}
}
pub fn advance_index(
&mut self,
index: usize,
stage: StagedChunkEnum,
generator: &generator::WorldGenerator,
_block_registry: &dyn WorldPortalExt,
_lighting_config: &LightingEngineConfig,
) {
match &self.chunks[index] {
Chunk::Level(_) => return,
Chunk::Proto(chunk) if chunk.stage >= stage => return,
Chunk::Proto(_) => {}
}
match stage {
StagedChunkEnum::Empty => panic!("empty stage"),
StagedChunkEnum::StructureStart => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
self.chunks[index]
.get_proto_chunk_mut()
.set_structure_starts(noise_gen);
}
generator::WorldGenerator::Flat(_) => {}
},
StagedChunkEnum::StructureReferences => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
self.chunks[index]
.get_proto_chunk_mut()
.set_structure_references(noise_gen);
}
generator::WorldGenerator::Flat(_) => {}
},
StagedChunkEnum::Biomes => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
self.chunks[index]
.get_proto_chunk_mut()
.step_to_biomes(noise_gen);
}
generator::WorldGenerator::Flat(flat_gen) => {
flat_gen.step_to_biomes(self.chunks[index].get_proto_chunk_mut());
}
},
_ => {}
}
}
#[must_use]
pub fn new(x: i32, z: i32, size: i32) -> Self {
Self {
x,
z,
size,
chunks: Vec::with_capacity((size * size) as usize),
}
}
pub fn advance(
&mut self,
stage: StagedChunkEnum,
generator: &generator::WorldGenerator,
block_registry: &dyn WorldPortalExt,
lighting_config: &LightingEngineConfig,
) {
let mid = ((self.size * self.size) >> 1) as usize;
match &self.chunks[mid] {
Chunk::Level(_) => return,
Chunk::Proto(chunk) if chunk.stage >= stage => return,
Chunk::Proto(_) => {}
}
match stage {
StagedChunkEnum::Empty => panic!("empty stage"),
StagedChunkEnum::StructureStart => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
self.chunks[mid]
.get_proto_chunk_mut()
.set_structure_starts(noise_gen);
}
generator::WorldGenerator::Flat(_) => {}
},
StagedChunkEnum::StructureReferences => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
self.chunks[mid]
.get_proto_chunk_mut()
.set_structure_references(noise_gen);
}
generator::WorldGenerator::Flat(_) => {}
},
StagedChunkEnum::Biomes => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
self.chunks[mid]
.get_proto_chunk_mut()
.step_to_biomes(noise_gen);
}
generator::WorldGenerator::Flat(flat_gen) => {
flat_gen.step_to_biomes(self.chunks[mid].get_proto_chunk_mut());
}
},
StagedChunkEnum::Noise => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
self.chunks[mid]
.get_proto_chunk_mut()
.step_to_noise(noise_gen);
}
generator::WorldGenerator::Flat(flat_gen) => {
flat_gen.step_to_noise(self.chunks[mid].get_proto_chunk_mut());
}
},
StagedChunkEnum::Surface => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
self.chunks[mid]
.get_proto_chunk_mut()
.step_to_surface(noise_gen);
}
generator::WorldGenerator::Flat(flat_gen) => {
flat_gen.step_to_surface(self.chunks[mid].get_proto_chunk_mut());
}
},
StagedChunkEnum::Carvers => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
self.chunks[mid]
.get_proto_chunk_mut()
.step_to_carvers(noise_gen);
}
generator::WorldGenerator::Flat(flat_gen) => {
flat_gen.step_to_carvers(self.chunks[mid].get_proto_chunk_mut());
}
},
StagedChunkEnum::Features => match generator {
generator::WorldGenerator::Noise(noise_gen) => {
ProtoChunk::generate_features_and_structure(
self,
block_registry,
&noise_gen.random_config,
);
}
generator::WorldGenerator::Flat(_) => {
self.chunks[mid].get_proto_chunk_mut().stage = StagedChunkEnum::Features;
}
},
StagedChunkEnum::Lighting => {
let mut engine = crate::lighting::LightEngine::new();
engine.initialize_light(self, lighting_config);
// Only set stage to Lighting if it wasn't already at Lighting or higher
// (initialize_light may short-circuit for already-lit chunks)
let chunk = self.chunks[mid].get_proto_chunk_mut();
if chunk.stage < StagedChunkEnum::Lighting {
chunk.stage = StagedChunkEnum::Lighting;
}
// Engine's internal state is cleared by initialize_light() and will be dropped here
drop(engine);
}
StagedChunkEnum::Spawn => {
ProtoChunk::spawn_mobs(self, block_registry);
}
StagedChunkEnum::Full => {
let chunk = self.chunks[mid].get_proto_chunk_mut();
debug_assert_eq!(chunk.stage, StagedChunkEnum::Spawn);
chunk.stage = StagedChunkEnum::Full;
self.chunks[mid].upgrade_to_level_chunk(generator.dimension(), lighting_config);
}
StagedChunkEnum::None => {}
}
}
}
@@ -0,0 +1,40 @@
/*
TODO
1. add proto chunk dirty flag
2. better priority
5. add lifetime to loading ticket
6. solve entity not unload problem
*/
pub type HashMapType<K, V> = rustc_hash::FxHashMap<K, V>;
pub type HashSetType<K> = rustc_hash::FxHashSet<K>;
pub type ChunkPos = pumpkin_util::math::vector2::Vector2<i32>;
pub type ChunkLevel = HashMapType<ChunkPos, i8>;
pub type IOLock = std::sync::Arc<(
std::sync::Mutex<HashMapType<ChunkPos, u8>>,
tokio::sync::Notify,
)>;
pub mod channel;
pub mod chunk_holder;
pub mod chunk_listener;
pub mod chunk_loading;
pub mod chunk_state;
pub mod dag;
pub mod generation;
pub mod generation_cache;
pub mod schedule;
pub mod worker_logic;
#[cfg(test)]
mod tests;
pub use channel::LevelChannel;
pub use chunk_holder::ChunkHolder;
pub use chunk_listener::ChunkListener;
pub use chunk_loading::ChunkLoading;
pub use chunk_state::{Chunk, StagedChunkEnum};
pub use dag::DAG;
pub use generation::generate_single_chunk;
pub use generation_cache::Cache;
pub use schedule::GenerationSchedule;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,357 @@
use super::*;
use crate::chunk_system::dag::Node;
use crate::chunk_system::dag::NodeKey;
use slotmap::Key;
use std::collections::BinaryHeap;
use std::collections::HashMap;
#[test]
fn ensure_dependency_chain_builds_multistage_chain() {
let mut graph = DAG::default();
let mut queue = BinaryHeap::new();
let last_level: ChunkLevel = HashMapType::default();
let last_high_priority: Vec<ChunkPos> = Vec::new();
let chunk_pos = ChunkPos::new(0, 0);
// Create a dependency node in the graph which will depend on the chain
let dependency_task = graph
.nodes
.insert(Node::new(ChunkPos::new(10, 10), StagedChunkEnum::Features));
let mut holder = ChunkHolder {
current_stage: StagedChunkEnum::None,
..Default::default()
};
// Build a chain up to Surface (Empty -> ... -> Surface)
GenerationSchedule::ensure_dependency_chain(
&mut graph,
&mut queue,
&last_level,
&last_high_priority,
dependency_task,
chunk_pos,
&mut holder,
StagedChunkEnum::Surface,
);
let start = (holder.current_stage as usize + 1).max(StagedChunkEnum::Empty as usize);
let end = StagedChunkEnum::Surface as u8 as usize;
// Ensure tasks were created, present in the DAG, and correctly chained
for idx in start..=end {
let key = holder.tasks[idx];
assert!(!key.is_null(), "task {idx} was not created");
let node = graph.nodes.get(key).expect("graph missing node");
if idx == start {
assert_eq!(node.in_degree, 0, "Start task should have 0 in_degree");
} else {
assert_eq!(
node.in_degree, 1,
"Intermediate task {idx} should have in_degree of 1"
);
}
}
// The dependency node should have its in_degree incremented
let dep_node = graph.nodes.get(dependency_task).unwrap();
assert_eq!(dep_node.in_degree, 1);
// The entry task should have been queued
let queued = queue.pop().expect("queue should have entry task");
assert_eq!(queued.node_key(), holder.tasks[start]);
}
#[test]
fn ensure_dependency_chain_resumes_partial_chain() {
let mut graph = DAG::default();
let mut queue = BinaryHeap::new();
let last_level: ChunkLevel = HashMapType::default();
let last_high_priority: Vec<ChunkPos> = Vec::new();
let chunk_pos = ChunkPos::new(0, 0);
let dependency_task = graph
.nodes
.insert(Node::new(ChunkPos::new(10, 10), StagedChunkEnum::Features));
let mut holder = ChunkHolder {
current_stage: StagedChunkEnum::Biomes,
..Default::default()
};
GenerationSchedule::ensure_dependency_chain(
&mut graph,
&mut queue,
&last_level,
&last_high_priority,
dependency_task,
chunk_pos,
&mut holder,
StagedChunkEnum::Surface,
);
// Dynamically calculate the next stage after Biomes instead of guessing
let empty = StagedChunkEnum::Empty as usize;
let start = (holder.current_stage as usize + 1).max(empty);
let queued = queue.pop().expect("queue should have entry task");
assert_eq!(
queued.node_key(),
holder.tasks[start],
"Should resume directly from the next stage after Biomes"
);
let entry_node = graph.nodes.get(queued.node_key()).unwrap();
assert_eq!(
entry_node.in_degree, 0,
"Resumed task should have 0 in_degree because previous stages are already done"
);
}
#[test]
fn ensure_dependency_chain_does_nothing_if_already_met() {
let mut graph = DAG::default();
let mut queue = BinaryHeap::new();
let last_level: ChunkLevel = HashMapType::default();
let last_high_priority: Vec<ChunkPos> = Vec::new();
let chunk_pos = ChunkPos::new(0, 0);
let dependency_task = graph
.nodes
.insert(Node::new(ChunkPos::new(10, 10), StagedChunkEnum::Features));
let mut holder = ChunkHolder {
current_stage: StagedChunkEnum::Full,
..Default::default()
};
GenerationSchedule::ensure_dependency_chain(
&mut graph,
&mut queue,
&last_level,
&last_high_priority,
dependency_task,
chunk_pos,
&mut holder,
StagedChunkEnum::Surface, // Requesting a lower stage than it currently is
);
// Ensure the function returned early without creating any tasks or queueing anything
for task in &holder.tasks {
assert!(
task.is_null(),
"No tasks should be created if the stage requirement is already met"
);
}
assert!(queue.is_empty(), "Nothing should be queued");
}
#[test]
fn ensure_dependency_chain_respects_occupied_lock() {
let mut graph = DAG::default();
let mut queue = BinaryHeap::new();
let last_level: ChunkLevel = HashMapType::default();
let last_high_priority: Vec<ChunkPos> = Vec::new();
let chunk_pos = ChunkPos::new(0, 0);
let dependency_task = graph
.nodes
.insert(Node::new(ChunkPos::new(10, 10), StagedChunkEnum::Features));
// Create an "occupy" node to simulate another thread/process currently working on this chunk
let occupy_node = graph.nodes.insert(Node::new(
ChunkPos::new(i32::MAX, i32::MAX),
StagedChunkEnum::None,
));
let mut holder = ChunkHolder {
current_stage: StagedChunkEnum::None,
occupied: occupy_node,
..Default::default()
};
GenerationSchedule::ensure_dependency_chain(
&mut graph,
&mut queue,
&last_level,
&last_high_priority,
dependency_task,
chunk_pos,
&mut holder,
StagedChunkEnum::Surface,
);
let start = StagedChunkEnum::Empty as usize;
let entry_task = holder.tasks[start];
let entry_node = graph.nodes.get(entry_task).unwrap();
// The first task should depend on the occupy node finishing!
assert_eq!(
entry_node.in_degree, 1,
"Entry task should be blocked by the occupy node"
);
// Therefore, the queue MUST be empty. It shouldn't fire until the occupy node drops.
assert!(
queue.is_empty(),
"Task should not be queued because it is blocked by occupied status"
);
}
#[test]
fn ensure_dependency_chain_early_return_skips_edge() {
let mut graph = DAG::default();
let mut queue = BinaryHeap::new();
let last_level = HashMapType::default();
let last_high_priority = Vec::new();
let dependency_task = graph
.nodes
.insert(Node::new(ChunkPos::new(1, 1), StagedChunkEnum::Surface));
// Create a holder that is already at the required stage (Features > Surface)
let mut holder = ChunkHolder {
current_stage: StagedChunkEnum::Features,
target_stage: StagedChunkEnum::Features,
..Default::default()
};
// Require 'Empty', but holder is already at 'Features'
GenerationSchedule::ensure_dependency_chain(
&mut graph,
&mut queue,
&last_level,
&last_high_priority,
dependency_task,
ChunkPos::new(0, 0),
&mut holder,
StagedChunkEnum::Empty,
);
let dep_node = graph.nodes.get(dependency_task).unwrap();
// Because of the early return, the dependency_task should not have its in_degree increased
assert_eq!(
dep_node.in_degree, 0,
"Dependency task should not be blocked if the neighbor is already past the required stage"
);
}
#[test]
fn completed_proto_stage_drops_all_satisfied_tasks() {
let mut graph = DAG::default();
let mut holder = ChunkHolder {
current_stage: StagedChunkEnum::None,
target_stage: StagedChunkEnum::StructureStart,
..Default::default()
};
for stage in StagedChunkEnum::Empty as usize..=StagedChunkEnum::StructureStart as usize {
holder.tasks[stage] = graph.nodes.insert(Node::new(
ChunkPos::new(0, 0),
StagedChunkEnum::from(stage as u8),
));
}
for stage in StagedChunkEnum::Empty as usize..StagedChunkEnum::StructureStart as usize {
graph.add_edge(holder.tasks[stage], holder.tasks[stage + 1]);
}
let returned_stage = StagedChunkEnum::Biomes as usize;
for task_idx in
(holder.current_stage as usize + 1)..=(returned_stage).min(holder.tasks.len() - 1)
{
if !holder.tasks[task_idx].is_null() {
if let Some(old) = graph.nodes.remove(holder.tasks[task_idx]) {
let mut edge = old.edge;
while !edge.is_null() {
let cur = graph.edges.remove(edge).unwrap();
if let Some(node) = graph.nodes.get_mut(cur.to) {
node.in_degree -= 1;
}
edge = cur.next;
}
}
holder.tasks[task_idx] = NodeKey::null();
}
}
assert!(holder.tasks[StagedChunkEnum::Empty as usize].is_null());
assert!(holder.tasks[StagedChunkEnum::Biomes as usize].is_null());
assert!(!holder.tasks[StagedChunkEnum::StructureStart as usize].is_null());
assert!(
graph
.nodes
.get(holder.tasks[StagedChunkEnum::StructureStart as usize])
.is_some()
);
}
#[test]
fn cancellation_path_decrements_in_degree() {
let mut graph = DAG::default();
// Create a task that is waiting (in_degree = 1)
let waiting_task_key = graph
.nodes
.insert(Node::new(ChunkPos::new(0, 0), StagedChunkEnum::Surface));
let waiting_node = graph.nodes.get_mut(waiting_task_key).unwrap();
waiting_node.in_degree = 1;
// Create the occupy node that the task is waiting on
let occupy_key = graph.nodes.insert(Node::new(
ChunkPos::new(i32::MAX, i32::MAX),
StagedChunkEnum::None,
));
graph.add_edge(occupy_key, waiting_task_key);
// Set up the chunk map to simulate an in-flight task
let mut chunk_map = HashMap::new();
let mut holder = ChunkHolder {
current_stage: StagedChunkEnum::Empty,
target_stage: StagedChunkEnum::Surface,
occupied: occupy_key,
..Default::default()
};
holder.tasks[StagedChunkEnum::Surface as usize] = waiting_task_key;
chunk_map.insert(ChunkPos::new(0, 0), holder);
// Simulate the cancellation logic from `work()`
let mut nodes_to_drop = Vec::new();
for holder in chunk_map.values_mut() {
for task in &mut holder.tasks {
if !task.is_null() {
nodes_to_drop.push(*task);
*task = NodeKey::null();
}
}
if !holder.occupied.is_null() {
nodes_to_drop.push(holder.occupied);
holder.occupied = NodeKey::null();
}
}
// Drop nodes using the proper graph edge traversal
for node_key in nodes_to_drop {
// Simulating the self.drop_node logic inside the test
if let Some(old) = graph.nodes.remove(node_key) {
let mut edge = old.edge;
while !edge.is_null() {
let cur = graph.edges.remove(edge).unwrap();
if let Some(node) = graph.nodes.get_mut(cur.to) {
node.in_degree -= 1;
}
edge = cur.next;
}
}
}
// Assert that the waiting task was properly cleaned up
assert!(
graph.nodes.get(waiting_task_key).is_none(),
"The waiting task should have been dropped during cancellation"
);
}
@@ -0,0 +1,281 @@
use super::chunk_state::{Chunk, StagedChunkEnum};
use super::generation_cache::Cache;
use super::{ChunkPos, IOLock};
use crate::ProtoChunk;
use crate::chunk::format::LightContainer;
use crate::chunk::io::LoadedData;
use crate::chunk::io::LoadedData::Loaded;
use crate::level::Level;
use crossfire::compat::AsyncRx;
use pumpkin_config::lighting::LightingEngineConfig;
use pumpkin_data::chunk::ChunkStatus;
use pumpkin_data::chunk_gen_settings::GenerationSettings;
use std::collections::hash_map::Entry;
use std::sync::Arc;
use std::sync::atomic::Ordering::Relaxed;
use tracing::{debug, error, warn};
pub enum RecvChunk {
IO(Chunk),
Generation(Cache),
GenerationFailure {
pos: ChunkPos,
stage: StagedChunkEnum,
error: String,
},
}
/// Checks if a chunk needs relighting based on the current lighting configuration
/// Returns true if the chunk has uniform lighting (from full/dark mode) but the server
/// is now running in default mode (which needs proper lighting calculation)
fn needs_relighting(chunk: &crate::chunk::ChunkData, config: LightingEngineConfig) -> bool {
if config != LightingEngineConfig::Default {
return false;
}
// If the chunk says it's already lit, believe it.
if chunk.light_populated.load(Relaxed) {
return false;
}
let engine = chunk.light_engine.lock().expect("Mutex poisoned");
// Scan for any complex lighting data
let has_complex_light = engine.sky_light.iter().any(|lc| match lc {
LightContainer::Full(data) => data.iter().any(|&b| b != 0x00 && b != 0xFF),
LightContainer::Empty(val) => *val != 0 && *val != 15,
}) || engine.block_light.iter().any(|lc| match lc {
LightContainer::Full(data) => data.iter().any(|&b| b != 0x00 && b != 0xFF),
LightContainer::Empty(val) => *val != 0 && *val != 15,
});
// If it has complex light, we don't need to relight.
!has_complex_light
}
pub async fn io_read_work(
recv: crossfire::compat::MAsyncRx<Vec<ChunkPos>>,
send: crossfire::compat::MTx<(ChunkPos, RecvChunk)>,
level: Arc<Level>,
lock: IOLock,
) {
debug!("io read thread start");
// Cleaner loop and async recv
while let Ok(batch) = recv.recv().await {
for pos in &batch {
// Lock handling
loop {
let notified = lock.1.notified();
if !lock.0.lock().unwrap().contains_key(pos) {
break;
}
notified.await;
}
}
let (t_send, mut t_recv) = tokio::sync::mpsc::channel(1000);
let batch_len = batch.len();
let level_clone = level.clone();
let fetch_task = tokio::spawn(async move {
level_clone
.chunk_saver
.fetch_chunks(&level_clone.level_folder, &batch, t_send)
.await;
});
for _ in 0..batch_len {
let Some(data) = t_recv.recv().await else {
break;
};
match data {
Loaded(chunk) => {
let pos = ChunkPos::new(chunk.x, chunk.z);
if chunk.status == ChunkStatus::Full {
// Relighting check
let needs_relight = needs_relighting(&chunk, level.lighting_config);
if needs_relight {
debug!(
"Chunk {pos:?} has uniform lighting, downgrading to Features stage for relighting"
);
// Create ProtoChunk using the async method
let mut proto = ProtoChunk::from_chunk_data(&chunk, &level.world_gen);
// Clear all lighting data
let section_count = proto.light.sky_light.len();
proto.light.sky_light = (0..section_count)
.map(|_| LightContainer::new_empty(15))
.collect();
proto.light.block_light = (0..section_count)
.map(|_| LightContainer::new_empty(0))
.collect();
// Set stage to Features
proto.stage = StagedChunkEnum::Features;
if send
.send((pos, RecvChunk::IO(Chunk::Proto(Box::new(proto)))))
.is_err()
{
break;
}
} else {
// Send fully valid chunk
if send
.send((pos, RecvChunk::IO(Chunk::Level(chunk))))
.is_err()
{
break;
}
}
} else {
// Standard ProtoChunk handling for non-full chunks
let val = RecvChunk::IO(Chunk::Proto(Box::new(
ProtoChunk::from_chunk_data(&chunk, &level.world_gen),
)));
if send.send((pos, val)).is_err() {
break;
}
}
}
LoadedData::Missing(pos) | LoadedData::Error((pos, _)) => {
if send
.send((
pos,
RecvChunk::IO(Chunk::Proto(Box::new(ProtoChunk::new(
pos.x,
pos.y,
&level.world_gen,
)))),
))
.is_err()
{
break;
}
}
}
}
let _ = fetch_task.await;
}
debug!("io read thread stop");
}
pub async fn io_write_work(recv: AsyncRx<Vec<(ChunkPos, Chunk)>>, level: Arc<Level>, lock: IOLock) {
loop {
// Don't check cancel_token here (keep saving chunks)
let Ok(data) = recv.recv().await else { break };
// debug!("io write thread receive chunks size {}", data.len());
let mut vec = Vec::with_capacity(data.len());
let mut positions = Vec::with_capacity(data.len());
for (pos, chunk) in data {
positions.push(pos);
match chunk {
Chunk::Level(chunk) => vec.push((pos, chunk)),
Chunk::Proto(chunk) => {
let mut temp = Chunk::Proto(chunk);
temp.upgrade_to_level_chunk(
level.world_gen.dimension(),
&level.lighting_config,
);
let Chunk::Level(chunk) = temp else { panic!() };
vec.push((pos, chunk));
}
}
}
if let Err(e) = level
.chunk_saver
.save_chunks(&level.level_folder, vec)
.await
{
error!("Failed to save chunks: {:?}", e);
}
for i in positions {
let mut data = lock.0.lock().unwrap();
match data.entry(i) {
Entry::Occupied(mut entry) => {
let rc = entry.get_mut();
if *rc == 1 {
entry.remove();
drop(data);
lock.1.notify_waiters();
} else {
*rc -= 1;
}
}
Entry::Vacant(_) => {
warn!(
"io_write: attempted to release missing lock entry for {:?}",
i
);
// continue without panicking to avoid crashing on shutdown races
}
}
}
}
}
pub fn run_generation(
pos: ChunkPos,
mut cache: Cache,
stage: StagedChunkEnum,
level: &Level,
_settings: &GenerationSettings,
) -> RecvChunk {
let portal = level.world_portal.load_full();
let portal_ref = portal.as_deref().expect("Portal should be initialized");
// Run generation with panic catching
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
cache.advance(stage, &level.world_gen, portal_ref, &level.lighting_config);
cache // Return cache on success
}));
match result {
Ok(cache) => RecvChunk::Generation(cache),
Err(payload) => {
let msg = payload
.downcast_ref::<&str>()
.copied()
.or_else(|| {
payload
.downcast_ref::<String>()
.map(std::string::String::as_str)
})
.unwrap_or("Unknown panic payload");
error!("Chunk generation FAILED at {pos:?} ({stage:?}): {msg}");
RecvChunk::GenerationFailure {
pos,
stage,
error: msg.to_string(),
}
}
}
}
pub fn generation_work(
recv: &crossfire::compat::MRx<(ChunkPos, Cache, StagedChunkEnum)>,
send: &crossfire::compat::MTx<(ChunkPos, RecvChunk)>,
level: &Arc<Level>,
) {
let settings = GenerationSettings::from_dimension(level.world_gen.dimension());
loop {
let Ok((pos, cache, stage)) = recv.recv() else {
debug!("generation channel closed, exiting");
break;
};
let result = run_generation(pos, cache, stage, level, settings);
if send.send((pos, result)).is_err() {
break;
}
}
}