use bevy::prelude::*;
use crate::chunk::{CHUNK_SIZE, VOXEL_SIZE};
use crate::generator::GeneratorSystems;
use crate::mesh::{MeshSystems, PendingChunkMeshes};
use super::ChunkManager;
#[derive(Message, Debug, Clone)]
pub struct LoadingProgress {
pub loaded: u32,
pub total: u32,
pub progress: f32,
}
#[derive(Message, Debug, Clone)]
pub struct WorldReady;
#[derive(Resource, Default)]
pub struct WorldLoadingState {
pub ready: bool,
pub expected: u32,
}
pub(crate) fn count_chunks_in_sphere(radius_in_chunks: i32) -> u32 {
let r = radius_in_chunks;
let mut count = 0u32;
for dx in -r..=r {
for dy in -r..=r {
for dz in -r..=r {
let dist_sq = dx * dx + dy * dy + dz * dz;
if dist_sq <= r * r {
count += 1;
}
}
}
}
count
}
pub(crate) fn compute_progress(loaded: u32, expected: u32) -> f32 {
if expected == 0 {
0.0
} else {
(loaded as f32 / expected as f32).min(1.0)
}
}
pub fn loading_progress_system(
manager: Res<ChunkManager>,
mut loading_state: ResMut<WorldLoadingState>,
mut progress_writer: MessageWriter<LoadingProgress>,
mut ready_writer: MessageWriter<WorldReady>,
pending_meshes: Option<Res<PendingChunkMeshes>>,
) {
if loading_state.expected == 0 {
let radius_in_chunks =
(manager.load_distance / (CHUNK_SIZE as f32 * VOXEL_SIZE)).ceil() as i32;
loading_state.expected = count_chunks_in_sphere(radius_in_chunks);
}
if loading_state.ready {
return;
}
let loaded = manager.loaded_count() as u32;
let expected = loading_state.expected;
let progress = compute_progress(loaded, expected);
progress_writer.write(LoadingProgress {
loaded,
total: expected,
progress,
});
let meshing_done =
pending_meshes.is_none_or(|pending| pending.is_empty() || pending.is_stalled());
if progress >= 1.0 && meshing_done {
ready_writer.write(WorldReady);
loading_state.ready = true;
}
}
pub struct LoadingPlugin;
impl Plugin for LoadingPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<WorldLoadingState>();
app.add_message::<LoadingProgress>();
app.add_message::<WorldReady>();
app.add_systems(
Update,
loading_progress_system
.after(GeneratorSystems)
.after(MeshSystems),
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_loading_progress_zero_when_nothing_loaded() {
let progress = compute_progress(0, 100);
assert_eq!(progress, 0.0);
}
#[test]
fn test_loading_progress_zero_when_expected_is_zero() {
let progress = compute_progress(0, 0);
assert_eq!(progress, 0.0);
}
#[test]
fn test_loading_progress_partial() {
let progress = compute_progress(50, 100);
assert!((progress - 0.5).abs() < f32::EPSILON);
}
#[test]
fn test_loading_ready_when_fully_loaded() {
let progress = compute_progress(100, 100);
assert_eq!(progress, 1.0);
assert!(progress >= 1.0);
}
use bevy::ecs::message::Messages;
use bevy::ecs::system::RunSystemOnce;
fn fully_loaded_world() -> World {
let mut world = World::new();
let mut manager = ChunkManager::new(0.0, 0.0);
let entity = world.spawn_empty().id();
manager.register(IVec3::ZERO, entity);
world.insert_resource(manager);
world.init_resource::<WorldLoadingState>();
world.init_resource::<Messages<LoadingProgress>>();
world.init_resource::<Messages<WorldReady>>();
world
}
fn run_loading(world: &mut World) {
world
.run_system_once(loading_progress_system)
.expect("loading_progress_system should run");
}
fn ready_count(world: &World) -> usize {
world.resource::<Messages<WorldReady>>().len()
}
#[test]
fn world_is_ready_when_loaded_and_there_is_no_mesh_queue() {
let mut world = fully_loaded_world();
run_loading(&mut world);
assert_eq!(ready_count(&world), 1);
assert!(world.resource::<WorldLoadingState>().ready);
}
#[test]
fn world_ready_waits_for_pending_chunk_meshes() {
let mut world = fully_loaded_world();
let mut pending = PendingChunkMeshes::default();
pending.push(IVec3::ZERO);
world.insert_resource(pending);
run_loading(&mut world);
assert_eq!(ready_count(&world), 0, "a chunk still has no mesh");
assert!(!world.resource::<WorldLoadingState>().ready);
let progress = world
.resource::<Messages<LoadingProgress>>()
.iter_current_update_messages()
.last()
.map(|message| message.progress);
assert_eq!(progress, Some(1.0), "loading itself is complete");
world.insert_resource(PendingChunkMeshes::default());
run_loading(&mut world);
assert_eq!(ready_count(&world), 1);
}
#[test]
fn world_ready_does_not_wait_for_a_stalled_mesh_queue() {
use crate::mesh::chunk_mesh_system;
use crate::render::material::ChunkMaterialHandle;
use crate::voxel::DefaultVoxel;
use crate::world::{ChunkModified, ViewerPosition};
let mut world = fully_loaded_world();
world.init_resource::<Messages<ChunkModified>>();
world.init_resource::<crate::mesh::PendingNeighborRemesh>();
world.init_resource::<PendingChunkMeshes>();
world.init_resource::<ViewerPosition>();
world.init_resource::<Assets<Mesh>>();
world.init_resource::<ChunkMaterialHandle>();
world.write_message(ChunkModified(IVec3::ZERO));
world
.run_system_once(chunk_mesh_system::<DefaultVoxel>)
.expect("chunk_mesh_system should run");
assert!(!world.resource::<PendingChunkMeshes>().is_empty());
run_loading(&mut world);
assert_eq!(ready_count(&world), 1);
}
#[test]
fn world_ready_is_evaluated_after_this_frame_meshing() {
use crate::chunk::Chunk;
use crate::mesh::{ChunkMeshBudget, MeshPlugin};
use crate::render::material::ChunkMaterialHandle;
use crate::voxel::DefaultVoxel;
use crate::world::{ChunkModified, ChunkUnloadRequest, ViewerPosition};
let mut app = App::new();
app.add_message::<ChunkModified>();
app.add_message::<ChunkUnloadRequest>();
app.init_resource::<ViewerPosition>();
app.init_resource::<Assets<Mesh>>();
let mut materials = Assets::<StandardMaterial>::default();
let standard = materials.add(StandardMaterial::default());
app.insert_resource(materials);
app.insert_resource(ChunkMaterialHandle {
standard: Some(standard),
custom: None,
});
let mut manager = ChunkManager::new(0.0, 0.0);
let coords = [IVec3::ZERO, IVec3::new(5, 0, 0)];
for coord in coords {
let mut chunk = Chunk::<DefaultVoxel>::new();
chunk.set(8, 8, 8, DefaultVoxel::Rock);
let entity = app.world_mut().spawn(chunk).id();
manager.register(coord, entity);
}
app.insert_resource(manager);
app.add_plugins((MeshPlugin::<DefaultVoxel>::new(), LoadingPlugin));
app.insert_resource(ChunkMeshBudget::new(1));
for coord in coords {
app.world_mut().write_message(ChunkModified(coord));
}
app.update();
assert!(!app.world().resource::<WorldLoadingState>().ready);
app.update();
assert!(app.world().resource::<WorldLoadingState>().ready);
}
#[test]
fn test_loading_ready_when_overloaded() {
let progress = compute_progress(110, 100);
assert_eq!(progress, 1.0);
}
#[test]
fn test_count_chunks_in_sphere_radius_zero() {
assert_eq!(count_chunks_in_sphere(0), 1);
}
#[test]
fn test_count_chunks_in_sphere_radius_one() {
assert_eq!(count_chunks_in_sphere(1), 7);
}
#[test]
fn test_count_chunks_in_sphere_positive_count() {
assert!(count_chunks_in_sphere(5) > 0);
}
}