use std::path::PathBuf;
use bevy::camera::primitives::Aabb;
use bevy::prelude::*;
use crate::chunk::persistence as chunk_persistence;
use crate::chunk::{CHUNK_SIZE, Chunk, ChunkCoord, ChunkCoordComp, ChunkLod};
use crate::render::material::{ChunkMaterial, ChunkMaterialHandle, ChunkRendered};
use crate::voxel::VoxelType;
use crate::world::persistence::PersistenceConfig;
use crate::world::{ChunkManager, ChunkModified, ChunkUnloadRequest, ViewerPosition};
use super::lod::{compute_lod, compute_lod_with_hysteresis, lod_to_step};
use super::{ChunkNeighbors, generate_chunk_mesh_with_neighbors};
#[derive(Component)]
pub struct EmptyMesh;
#[derive(Resource, Default)]
pub struct PendingNeighborRemesh(pub Vec<ChunkCoord>);
pub fn chunk_mesh_system<V: VoxelType>(
mut commands: Commands,
mut modified_reader: MessageReader<ChunkModified>,
mut pending_neighbors: ResMut<PendingNeighborRemesh>,
manager: Res<ChunkManager>,
chunk_material: Res<ChunkMaterialHandle>,
viewer: Res<ViewerPosition>,
mut meshes: ResMut<Assets<Mesh>>,
chunks: Query<(
&Chunk<V>,
Option<&Mesh3d>,
Option<&ChunkLod>,
Has<EmptyMesh>,
)>,
) {
let use_custom = chunk_material.custom.is_some();
let has_material = chunk_material.custom.is_some() || chunk_material.standard.is_some();
if !has_material {
return;
}
let chunk_size_f = CHUNK_SIZE as f32;
const NEIGHBOR_OFFSETS: [IVec3; 6] = [
IVec3::new(0, 1, 0), IVec3::new(0, -1, 0), IVec3::new(1, 0, 0), IVec3::new(-1, 0, 0), IVec3::new(0, 0, 1), IVec3::new(0, 0, -1), ];
for &ChunkModified(coord) in modified_reader.read() {
let Some(entity) = manager.get_entity(coord) else {
continue;
};
let Ok((chunk, maybe_mesh3d, _maybe_lod, has_empty_mesh)) = chunks.get(entity) else {
pending_neighbors.0.push(coord);
continue;
};
let chunk_center = coord.as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5);
let lod = compute_lod(chunk_center, viewer.position);
let lod_step = lod_to_step(lod);
let effective_step = {
let mut min_step = lod_step;
for &offset in &NEIGHBOR_OFFSETS {
let neighbor_coord = coord + offset;
if let Some(neighbor_entity) = manager.get_entity(neighbor_coord) {
if let Ok((_, _, Some(neighbor_lod), _)) = chunks.get(neighbor_entity) {
let neighbor_step = lod_to_step(neighbor_lod.0);
min_step = min_step.min(neighbor_step);
}
}
}
min_step
};
let mut neighbors = ChunkNeighbors::<V>::default();
for (face_index, &offset) in NEIGHBOR_OFFSETS.iter().enumerate() {
let neighbor_coord = coord + offset;
if let Some(neighbor_entity) = manager.get_entity(neighbor_coord) {
if let Ok((neighbor_chunk, _, _, _)) = chunks.get(neighbor_entity) {
let opposite_face = face_index ^ 1;
neighbors.faces[face_index] = Some(neighbor_chunk.border_slice(opposite_face));
}
}
}
let remove_render = |cmd: &mut EntityCommands| {
cmd.remove::<(
Mesh3d,
MeshMaterial3d<StandardMaterial>,
MeshMaterial3d<ChunkMaterial>,
ChunkRendered,
ChunkLod,
)>();
};
if chunk.is_empty() {
if maybe_mesh3d.is_some() {
let mut ec = commands.entity(entity);
remove_render(&mut ec);
for &offset in &NEIGHBOR_OFFSETS {
let neighbor_coord = coord + offset;
if manager.is_loaded(neighbor_coord) {
pending_neighbors.0.push(neighbor_coord);
}
}
} else if !has_empty_mesh {
commands.entity(entity).insert(EmptyMesh);
for &offset in &NEIGHBOR_OFFSETS {
let neighbor_coord = coord + offset;
if manager.is_loaded(neighbor_coord) {
pending_neighbors.0.push(neighbor_coord);
}
}
}
continue;
}
let new_mesh = generate_chunk_mesh_with_neighbors(chunk, &neighbors, effective_step);
if new_mesh.count_vertices() == 0 {
if maybe_mesh3d.is_some() {
let mut ec = commands.entity(entity);
remove_render(&mut ec);
}
if !has_empty_mesh {
commands.entity(entity).insert(EmptyMesh);
}
continue;
}
if let Some(mesh3d) = maybe_mesh3d {
if let Some(existing) = meshes.get_mut(&mesh3d.0) {
*existing = new_mesh;
}
commands.entity(entity).insert(ChunkLod(lod));
if has_empty_mesh {
commands.entity(entity).remove::<EmptyMesh>();
for &offset in &NEIGHBOR_OFFSETS {
let neighbor_coord = coord + offset;
if manager.is_loaded(neighbor_coord) {
pending_neighbors.0.push(neighbor_coord);
}
}
}
} else {
let mesh_handle = meshes.add(new_mesh);
let translation = coord.as_vec3() * chunk_size_f;
let aabb = Aabb::from_min_max(Vec3::ZERO, Vec3::splat(chunk_size_f));
let mut entity_cmd = commands.entity(entity);
if use_custom {
let mat = chunk_material.custom.as_ref().unwrap().clone();
entity_cmd.insert((
Mesh3d(mesh_handle),
MeshMaterial3d(mat),
Transform::from_translation(translation),
Visibility::default(),
aabb,
ChunkRendered,
ChunkLod(lod),
));
} else {
let mat = chunk_material.standard.as_ref().unwrap().clone();
entity_cmd.insert((
Mesh3d(mesh_handle),
MeshMaterial3d(mat),
Transform::from_translation(translation),
Visibility::default(),
aabb,
ChunkRendered,
ChunkLod(lod),
));
}
if has_empty_mesh {
commands.entity(entity).remove::<EmptyMesh>();
}
for &offset in &NEIGHBOR_OFFSETS {
let neighbor_coord = coord + offset;
if manager.is_loaded(neighbor_coord) {
pending_neighbors.0.push(neighbor_coord);
}
}
}
}
}
pub fn flush_neighbor_remesh_system(
mut pending: ResMut<PendingNeighborRemesh>,
mut modified_writer: MessageWriter<ChunkModified>,
) {
for coord in pending.0.drain(..) {
modified_writer.write(ChunkModified(coord));
}
}
pub fn lod_update_system<V: VoxelType>(
viewer: Res<ViewerPosition>,
chunks: Query<(Entity, &Transform, &ChunkLod, Option<&ChunkCoordComp>), With<ChunkRendered>>,
mut modified_writer: MessageWriter<ChunkModified>,
manager: Res<ChunkManager>,
) {
let chunk_size_f = CHUNK_SIZE as f32;
for (entity, transform, current_lod, maybe_coord_comp) in &chunks {
let chunk_center = if let Some(coord_comp) = maybe_coord_comp {
coord_comp.coord().as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5)
} else {
transform.translation + Vec3::splat(chunk_size_f * 0.5)
};
let new_lod =
compute_lod_with_hysteresis(chunk_center, viewer.position, current_lod.0, 5.0);
if new_lod != current_lod.0 {
if let Some(coord) = manager
.iter_loaded()
.find_map(|(coord, e)| if e == entity { Some(coord) } else { None })
{
modified_writer.write(ChunkModified(coord));
const NEIGHBOR_OFFSETS: [IVec3; 6] = [
IVec3::new(0, 1, 0),
IVec3::new(0, -1, 0),
IVec3::new(1, 0, 0),
IVec3::new(-1, 0, 0),
IVec3::new(0, 0, 1),
IVec3::new(0, 0, -1),
];
for &offset in &NEIGHBOR_OFFSETS {
let neighbor_coord = coord + offset;
if manager.is_loaded(neighbor_coord) {
modified_writer.write(ChunkModified(neighbor_coord));
}
}
}
}
}
}
pub fn chunk_despawn_system<V: VoxelType>(
mut commands: Commands,
mut unload_reader: MessageReader<ChunkUnloadRequest>,
mut manager: ResMut<ChunkManager>,
config: Option<Res<PersistenceConfig>>,
chunks: Query<&Chunk<V>>,
) {
crate::profile_span!("voxel::world::chunk_unload");
for &ChunkUnloadRequest(coord) in unload_reader.read() {
if config.as_ref().map(|c| c.auto_save).unwrap_or(false) {
if let Some(entity) = manager.get_entity(coord) {
if let Ok(chunk) = chunks.get(entity) {
let filename = chunk_persistence::chunk_filename(coord);
let save_dir = config.as_ref().unwrap().save_dir.as_str();
let path: PathBuf = [save_dir, &filename].iter().collect();
if let Some(parent) = path.parent() {
if let Err(e) = std::fs::create_dir_all(parent) {
eprintln!(
"voxel-framework: failed to create chunk save directory '{}': {e}",
parent.display()
);
}
}
if let Err(e) = chunk_persistence::save_chunk(chunk, &path) {
eprintln!(
"voxel-framework: failed to save chunk {coord} on unload to '{}': {e}",
path.display()
);
}
}
}
}
if let Some(entity) = manager.unregister(coord) {
commands.entity(entity).despawn();
}
}
}