voxel_framework/mesh/systems.rs
1//! Mesh generation system that responds to chunk modification events.
2//!
3//! [`chunk_mesh_system`] listens for [`ChunkModified`] messages, retrieves
4//! the chunk entity from [`ChunkManager`], runs the greedy mesher at the
5//! appropriate LOD level, and either updates an existing [`Mesh`] asset handle
6//! or inserts the full set of render components (`Mesh3d`, `MeshMaterial3d`,
7//! `Transform`, `Visibility`, AABB, [`ChunkLod`]).
8//!
9//! [`lod_update_system`] runs every frame, recomputes the LOD level for every
10//! rendered chunk based on distance to the viewer, and emits [`ChunkModified`]
11//! when the level changes so that `chunk_mesh_system` regenerates the mesh.
12
13use std::path::PathBuf;
14
15use bevy::camera::primitives::Aabb;
16use bevy::prelude::*;
17
18use crate::chunk::persistence as chunk_persistence;
19use crate::chunk::{CHUNK_SIZE, Chunk, ChunkCoord, ChunkCoordComp, ChunkLod};
20use crate::render::material::{ChunkMaterial, ChunkMaterialHandle, ChunkRendered};
21use crate::voxel::VoxelType;
22use crate::world::persistence::PersistenceConfig;
23use crate::world::{ChunkManager, ChunkModified, ChunkUnloadRequest, ViewerPosition};
24
25use super::lod::{compute_lod, compute_lod_with_hysteresis, lod_to_step};
26use super::{ChunkNeighbors, generate_chunk_mesh_with_neighbors};
27
28// ─── EmptyMesh ────────────────────────────────────────────────────────────────
29
30/// Marker component attached to chunk entities whose last meshing pass produced
31/// zero vertices (all faces were culled by loaded neighbors).
32///
33/// When a neighbor subsequently loads and triggers a re-mesh that produces
34/// geometry, [`chunk_mesh_system`] removes this marker and propagates a
35/// [`ChunkModified`] event to all six neighbors so they too can re-evaluate
36/// their border faces. This enables recursive multi-layer propagation: each
37/// chunk that transitions from empty → non-empty signals its neighbors, which
38/// may then transition themselves the following frame.
39#[derive(Component)]
40pub struct EmptyMesh;
41
42// ─── PendingNeighborRemesh ────────────────────────────────────────────────────
43
44/// Staging buffer for neighbor re-mesh requests emitted by [`chunk_mesh_system`].
45///
46/// `chunk_mesh_system` reads `MessageReader<ChunkModified>` (which requires
47/// `Res` access to the message storage) and therefore cannot hold a
48/// `MessageWriter<ChunkModified>` (which requires `ResMut`) in the same system
49/// without triggering a Bevy B0002 access-conflict panic.
50///
51/// Instead, newly-rendered chunks push their six neighbor coords here, and
52/// [`flush_neighbor_remesh_system`] drains the buffer and emits the
53/// `ChunkModified` messages in a separate, sequentially-ordered system.
54#[derive(Resource, Default)]
55pub struct PendingNeighborRemesh(pub Vec<ChunkCoord>);
56
57// ─── chunk_mesh_system ────────────────────────────────────────────────────────
58
59/// Regenerates the mesh for any chunk that received a [`ChunkModified`] message.
60///
61/// For each modified coord this system:
62///
63/// 1. Looks up the entity in [`ChunkManager`].
64/// 2. Fetches its [`Chunk<V>`] component.
65/// 3. Computes the LOD level from the viewer distance using [`compute_lod`].
66/// 4. Builds a [`ChunkNeighbors`] struct from the six adjacent chunks.
67/// 5. Runs [`generate_chunk_mesh_with_neighbors`] at the step size for that LOD level.
68/// 6. **Update path** — if the entity already has a `Mesh3d` handle, replaces
69/// the mesh asset data in-place and updates the [`ChunkLod`] component.
70/// 7. **First-time path** — otherwise, allocates a new handle and inserts
71/// `Mesh3d`, `MeshMaterial3d<StandardMaterial>` or `MeshMaterial3d<ChunkMaterial>`,
72/// `Transform`, `Visibility`, AABB, [`ChunkRendered`], and [`ChunkLod`].
73///
74/// If the chunk material has not yet been created (startup system hasn't run)
75/// or the entity no longer exists, the event is silently skipped.
76pub fn chunk_mesh_system<V: VoxelType>(
77 mut commands: Commands,
78 mut modified_reader: MessageReader<ChunkModified>,
79 mut pending_neighbors: ResMut<PendingNeighborRemesh>,
80 manager: Res<ChunkManager>,
81 chunk_material: Res<ChunkMaterialHandle>,
82 viewer: Res<ViewerPosition>,
83 mut meshes: ResMut<Assets<Mesh>>,
84 chunks: Query<(
85 &Chunk<V>,
86 Option<&Mesh3d>,
87 Option<&ChunkLod>,
88 Has<EmptyMesh>,
89 )>,
90) {
91 // Determine which material path is active.
92 // Custom (texture array) takes priority; fall back to StandardMaterial.
93 let use_custom = chunk_material.custom.is_some();
94 let has_material = chunk_material.custom.is_some() || chunk_material.standard.is_some();
95 if !has_material {
96 // Material not yet set up — skip until next frame.
97 return;
98 }
99
100 let chunk_size_f = CHUNK_SIZE as f32;
101
102 // Face direction offsets: index matches ChunkNeighbors.faces convention.
103 // [+Y, -Y, +X, -X, +Z, -Z]
104 const NEIGHBOR_OFFSETS: [IVec3; 6] = [
105 IVec3::new(0, 1, 0), // 0: +Y
106 IVec3::new(0, -1, 0), // 1: -Y
107 IVec3::new(1, 0, 0), // 2: +X
108 IVec3::new(-1, 0, 0), // 3: -X
109 IVec3::new(0, 0, 1), // 4: +Z
110 IVec3::new(0, 0, -1), // 5: -Z
111 ];
112
113 // For each face index i, the adjacent chunk's face that touches ours is
114 // the opposite direction. The face convention pairs are (0,1), (2,3), (4,5),
115 // so opposite = i ^ 1.
116
117 for &ChunkModified(coord) in modified_reader.read() {
118 let Some(entity) = manager.get_entity(coord) else {
119 // Entity not registered — task may have been cancelled or coord
120 // arrived out of order; ignore.
121 continue;
122 };
123
124 let Ok((chunk, maybe_mesh3d, _maybe_lod, has_empty_mesh)) = chunks.get(entity) else {
125 // Chunk component not yet attached — deferred command not flushed yet.
126 // Re-queue so we retry next frame when the component is available.
127 pending_neighbors.0.push(coord);
128 continue;
129 };
130
131 // Compute LOD from the chunk center to the viewer.
132 let chunk_center = coord.as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5);
133 let lod = compute_lod(chunk_center, viewer.position);
134 let lod_step = lod_to_step(lod);
135
136 // Clamp the step to the minimum among this chunk and all loaded neighbors
137 // to prevent border cracks when adjacent chunks have finer LOD levels.
138 let effective_step = {
139 let mut min_step = lod_step;
140 for &offset in &NEIGHBOR_OFFSETS {
141 let neighbor_coord = coord + offset;
142 if let Some(neighbor_entity) = manager.get_entity(neighbor_coord) {
143 if let Ok((_, _, Some(neighbor_lod), _)) = chunks.get(neighbor_entity) {
144 let neighbor_step = lod_to_step(neighbor_lod.0);
145 min_step = min_step.min(neighbor_step);
146 }
147 }
148 }
149 min_step
150 };
151
152 // Build ChunkNeighbors from the six adjacent loaded chunks.
153 let mut neighbors = ChunkNeighbors::<V>::default();
154 for (face_index, &offset) in NEIGHBOR_OFFSETS.iter().enumerate() {
155 let neighbor_coord = coord + offset;
156 if let Some(neighbor_entity) = manager.get_entity(neighbor_coord) {
157 if let Ok((neighbor_chunk, _, _, _)) = chunks.get(neighbor_entity) {
158 // The face of the neighbor that is adjacent to our face_index
159 // is the opposite direction: face_index ^ 1.
160 let opposite_face = face_index ^ 1;
161 neighbors.faces[face_index] = Some(neighbor_chunk.border_slice(opposite_face));
162 }
163 }
164 }
165
166 // Helper: remove all material-related render components from an entity.
167 // Both MeshMaterial3d variants must be removed regardless of which path
168 // is currently active, because the entity might have been created under
169 // the other path (e.g. if ChunkTextureArray was inserted mid-session).
170 let remove_render = |cmd: &mut EntityCommands| {
171 cmd.remove::<(
172 Mesh3d,
173 MeshMaterial3d<StandardMaterial>,
174 MeshMaterial3d<ChunkMaterial>,
175 ChunkRendered,
176 ChunkLod,
177 )>();
178 };
179
180 // Skip meshing entirely for all-air chunks — no render components needed.
181 if chunk.is_empty() {
182 if maybe_mesh3d.is_some() {
183 // Chunk was previously non-empty (e.g. all voxels mined out);
184 // strip render components so it becomes invisible.
185 let mut ec = commands.entity(entity);
186 remove_render(&mut ec);
187 // Notify neighbors — they may now have exposed border faces.
188 for &offset in &NEIGHBOR_OFFSETS {
189 let neighbor_coord = coord + offset;
190 if manager.is_loaded(neighbor_coord) {
191 pending_neighbors.0.push(neighbor_coord);
192 }
193 }
194 } else if !has_empty_mesh {
195 // First time seeing this air chunk — notify neighbors so they
196 // can generate faces that border this empty space.
197 commands.entity(entity).insert(EmptyMesh);
198 for &offset in &NEIGHBOR_OFFSETS {
199 let neighbor_coord = coord + offset;
200 if manager.is_loaded(neighbor_coord) {
201 pending_neighbors.0.push(neighbor_coord);
202 }
203 }
204 }
205 continue;
206 }
207
208 // Run the neighbor-aware greedy mesher at the effective LOD step.
209 let new_mesh = generate_chunk_mesh_with_neighbors(chunk, &neighbors, effective_step);
210
211 if new_mesh.count_vertices() == 0 {
212 // Mesher produced no geometry (e.g. all faces are hidden by neighbors).
213 // Remove render components if they were previously attached.
214 if maybe_mesh3d.is_some() {
215 let mut ec = commands.entity(entity);
216 remove_render(&mut ec);
217 }
218 // Tag this entity so we know its mesh is empty. When a neighbor
219 // loads later and triggers another re-mesh that produces geometry,
220 // we propagate the signal to our own neighbors at that point.
221 if !has_empty_mesh {
222 commands.entity(entity).insert(EmptyMesh);
223 }
224 continue;
225 }
226
227 if let Some(mesh3d) = maybe_mesh3d {
228 // Update path: reuse the existing handle, replace asset data.
229 if let Some(existing) = meshes.get_mut(&mesh3d.0) {
230 *existing = new_mesh;
231 }
232 // Update the LOD component to reflect the current level.
233 commands.entity(entity).insert(ChunkLod(lod));
234
235 // If this chunk was previously empty (all faces culled) and now has
236 // geometry, its border faces changed from invisible to visible.
237 // Propagate to neighbors so they can re-evaluate their own faces.
238 // This enables multi-layer propagation: each depth level transitions
239 // one frame at a time until all chunks converge.
240 if has_empty_mesh {
241 commands.entity(entity).remove::<EmptyMesh>();
242 for &offset in &NEIGHBOR_OFFSETS {
243 let neighbor_coord = coord + offset;
244 if manager.is_loaded(neighbor_coord) {
245 pending_neighbors.0.push(neighbor_coord);
246 }
247 }
248 }
249 } else {
250 // First-time path: allocate new handle and attach all render components.
251 let mesh_handle = meshes.add(new_mesh);
252
253 // World-space origin of this chunk's minimum corner.
254 let translation = coord.as_vec3() * chunk_size_f;
255
256 // AABB sized to the full chunk extent for frustum culling.
257 let aabb = Aabb::from_min_max(Vec3::ZERO, Vec3::splat(chunk_size_f));
258
259 let mut entity_cmd = commands.entity(entity);
260
261 if use_custom {
262 // Texture-array path.
263 let mat = chunk_material.custom.as_ref().unwrap().clone();
264 entity_cmd.insert((
265 Mesh3d(mesh_handle),
266 MeshMaterial3d(mat),
267 Transform::from_translation(translation),
268 Visibility::default(),
269 aabb,
270 ChunkRendered,
271 ChunkLod(lod),
272 ));
273 } else {
274 // Fallback StandardMaterial path.
275 let mat = chunk_material.standard.as_ref().unwrap().clone();
276 entity_cmd.insert((
277 Mesh3d(mesh_handle),
278 MeshMaterial3d(mat),
279 Transform::from_translation(translation),
280 Visibility::default(),
281 aabb,
282 ChunkRendered,
283 ChunkLod(lod),
284 ));
285 }
286
287 // If this chunk had EmptyMesh from a previous 0-vertex pass, remove it.
288 if has_empty_mesh {
289 commands.entity(entity).remove::<EmptyMesh>();
290 }
291
292 // A newly rendered chunk changes the border visibility of every
293 // adjacent chunk. Stage ChunkModified for each loaded neighbor so
294 // they re-mesh and cull (or un-cull) the faces that touch this chunk.
295 // Messages are emitted by flush_neighbor_remesh_system (runs after
296 // this system) to avoid a ResMut/Res conflict on the message storage.
297 // This is only done on the first-time path to avoid cascading
298 // re-meshes on every LOD or voxel-edit update.
299 for &offset in &NEIGHBOR_OFFSETS {
300 let neighbor_coord = coord + offset;
301 if manager.is_loaded(neighbor_coord) {
302 pending_neighbors.0.push(neighbor_coord);
303 }
304 }
305 }
306 }
307}
308
309// ─── flush_neighbor_remesh_system ────────────────────────────────────────────
310
311/// Drains [`PendingNeighborRemesh`] and emits a [`ChunkModified`] message for
312/// each staged coord.
313///
314/// This system exists solely to decouple the *write* of `ChunkModified` from
315/// [`chunk_mesh_system`], which holds a `MessageReader<ChunkModified>` (i.e.
316/// `Res` access to the message store). Having both `Res` and `ResMut` on the
317/// same resource in one system triggers Bevy's B0002 access-conflict panic.
318///
319/// By staging neighbor coords in [`PendingNeighborRemesh`] and draining them
320/// here — after `chunk_mesh_system` has finished — we keep the two accesses in
321/// separate systems, which Bevy schedules sequentially via `.after()`.
322pub fn flush_neighbor_remesh_system(
323 mut pending: ResMut<PendingNeighborRemesh>,
324 mut modified_writer: MessageWriter<ChunkModified>,
325) {
326 for coord in pending.0.drain(..) {
327 modified_writer.write(ChunkModified(coord));
328 }
329}
330
331// ─── lod_update_system ────────────────────────────────────────────────────────
332
333/// Every frame, recomputes the LOD level for every rendered chunk.
334///
335/// For each chunk entity that has a [`Transform`] and a [`ChunkLod`] component,
336/// this system:
337///
338/// 1. Reads the chunk's world-space center from its [`ChunkCoordComp`] (or
339/// falls back to the entity's [`Transform`] translation).
340/// 2. Calls [`compute_lod`] with the current [`ViewerPosition`].
341/// 3. If the computed LOD differs from the stored one, emits [`ChunkModified`]
342/// so that [`chunk_mesh_system`] regenerates the mesh at the new level.
343///
344/// The [`ChunkLod`] component is NOT updated here; `chunk_mesh_system` updates
345/// it once the new mesh has actually been built.
346pub fn lod_update_system<V: VoxelType>(
347 viewer: Res<ViewerPosition>,
348 chunks: Query<(Entity, &Transform, &ChunkLod, Option<&ChunkCoordComp>), With<ChunkRendered>>,
349 mut modified_writer: MessageWriter<ChunkModified>,
350 manager: Res<ChunkManager>,
351) {
352 let chunk_size_f = CHUNK_SIZE as f32;
353
354 for (entity, transform, current_lod, maybe_coord_comp) in &chunks {
355 // Determine the chunk's world-space center.
356 // Prefer the ChunkCoordComp (grid coord → center) over raw Transform
357 // translation, since the transform is at the minimum corner.
358 let chunk_center = if let Some(coord_comp) = maybe_coord_comp {
359 coord_comp.coord().as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5)
360 } else {
361 // Fallback: treat the transform translation as the minimum corner
362 // and offset to find the center.
363 transform.translation + Vec3::splat(chunk_size_f * 0.5)
364 };
365
366 let new_lod =
367 compute_lod_with_hysteresis(chunk_center, viewer.position, current_lod.0, 5.0);
368
369 if new_lod != current_lod.0 {
370 // Find the coord for this entity so we can emit ChunkModified(coord).
371 // We scan the manager's loaded set; this is O(n) but only runs when
372 // LOD actually changes, which is rare.
373 if let Some(coord) = manager
374 .iter_loaded()
375 .find_map(|(coord, e)| if e == entity { Some(coord) } else { None })
376 {
377 modified_writer.write(ChunkModified(coord));
378
379 // Also remesh each loaded neighbor: their effective_step may
380 // change now that this chunk's LOD has changed.
381 const NEIGHBOR_OFFSETS: [IVec3; 6] = [
382 IVec3::new(0, 1, 0),
383 IVec3::new(0, -1, 0),
384 IVec3::new(1, 0, 0),
385 IVec3::new(-1, 0, 0),
386 IVec3::new(0, 0, 1),
387 IVec3::new(0, 0, -1),
388 ];
389 for &offset in &NEIGHBOR_OFFSETS {
390 let neighbor_coord = coord + offset;
391 if manager.is_loaded(neighbor_coord) {
392 modified_writer.write(ChunkModified(neighbor_coord));
393 }
394 }
395 }
396 }
397 }
398}
399
400// ─── chunk_despawn_system ─────────────────────────────────────────────────────
401
402/// Responds to [`ChunkUnloadRequest`] messages by saving and despawning chunk entities.
403///
404/// For each unload request this system:
405/// 1. If [`PersistenceConfig::auto_save`] is `true`, saves the chunk's voxel
406/// data to disk before the entity is despawned.
407/// 2. Removes the chunk from [`ChunkManager`] so the streaming system can
408/// re-request the same coord if the viewer returns.
409/// 3. Despawns the entity.
410///
411/// Save errors are reported with `eprintln!` and do not panic.
412///
413/// This system is generic over `V` because it must query the [`Chunk<V>`]
414/// component to serialise voxel data. It is registered by [`MeshPlugin`](crate::mesh::MeshPlugin).
415pub fn chunk_despawn_system<V: VoxelType>(
416 mut commands: Commands,
417 mut unload_reader: MessageReader<ChunkUnloadRequest>,
418 mut manager: ResMut<ChunkManager>,
419 config: Option<Res<PersistenceConfig>>,
420 chunks: Query<&Chunk<V>>,
421) {
422 crate::profile_span!("voxel::world::chunk_unload");
423 for &ChunkUnloadRequest(coord) in unload_reader.read() {
424 // Save before unregistering so the entity is still valid.
425 if config.as_ref().map(|c| c.auto_save).unwrap_or(false) {
426 if let Some(entity) = manager.get_entity(coord) {
427 if let Ok(chunk) = chunks.get(entity) {
428 let filename = chunk_persistence::chunk_filename(coord);
429 let save_dir = config.as_ref().unwrap().save_dir.as_str();
430 let path: PathBuf = [save_dir, &filename].iter().collect();
431
432 if let Some(parent) = path.parent() {
433 if let Err(e) = std::fs::create_dir_all(parent) {
434 eprintln!(
435 "voxel-framework: failed to create chunk save directory '{}': {e}",
436 parent.display()
437 );
438 }
439 }
440
441 if let Err(e) = chunk_persistence::save_chunk(chunk, &path) {
442 eprintln!(
443 "voxel-framework: failed to save chunk {coord} on unload to '{}': {e}",
444 path.display()
445 );
446 }
447 }
448 }
449 }
450
451 if let Some(entity) = manager.unregister(coord) {
452 commands.entity(entity).despawn();
453 }
454 }
455}