voxel-framework 0.10.0

A reusable voxel engine framework built on Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Mesh generation system that responds to chunk modification events.
//!
//! [`chunk_mesh_system`] listens for [`ChunkModified`] messages, retrieves
//! the chunk entity from [`ChunkManager`], runs the greedy mesher at the
//! appropriate LOD level, and either updates an existing [`Mesh`] asset handle
//! or inserts the full set of render components (`Mesh3d`, `MeshMaterial3d`,
//! `Transform`, `Visibility`, AABB, [`ChunkLod`]).
//!
//! [`lod_update_system`] runs every frame, recomputes the LOD level for every
//! rendered chunk based on distance to the viewer, and emits [`ChunkModified`]
//! when the level changes so that `chunk_mesh_system` regenerates the mesh.

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};

// ─── EmptyMesh ────────────────────────────────────────────────────────────────

/// Marker component attached to chunk entities whose last meshing pass produced
/// zero vertices (all faces were culled by loaded neighbors).
///
/// When a neighbor subsequently loads and triggers a re-mesh that produces
/// geometry, [`chunk_mesh_system`] removes this marker and propagates a
/// [`ChunkModified`] event to all six neighbors so they too can re-evaluate
/// their border faces.  This enables recursive multi-layer propagation: each
/// chunk that transitions from empty → non-empty signals its neighbors, which
/// may then transition themselves the following frame.
#[derive(Component)]
pub struct EmptyMesh;

// ─── PendingNeighborRemesh ────────────────────────────────────────────────────

/// Staging buffer for neighbor re-mesh requests emitted by [`chunk_mesh_system`].
///
/// `chunk_mesh_system` reads `MessageReader<ChunkModified>` (which requires
/// `Res` access to the message storage) and therefore cannot hold a
/// `MessageWriter<ChunkModified>` (which requires `ResMut`) in the same system
/// without triggering a Bevy B0002 access-conflict panic.
///
/// Instead, newly-rendered chunks push their six neighbor coords here, and
/// [`flush_neighbor_remesh_system`] drains the buffer and emits the
/// `ChunkModified` messages in a separate, sequentially-ordered system.
#[derive(Resource, Default)]
pub struct PendingNeighborRemesh(pub Vec<ChunkCoord>);

// ─── chunk_mesh_system ────────────────────────────────────────────────────────

/// Regenerates the mesh for any chunk that received a [`ChunkModified`] message.
///
/// For each modified coord this system:
///
/// 1. Looks up the entity in [`ChunkManager`].
/// 2. Fetches its [`Chunk<V>`] component.
/// 3. Computes the LOD level from the viewer distance using [`compute_lod`].
/// 4. Builds a [`ChunkNeighbors`] struct from the six adjacent chunks.
/// 5. Runs [`generate_chunk_mesh_with_neighbors`] at the step size for that LOD level.
/// 6. **Update path** — if the entity already has a `Mesh3d` handle, replaces
///    the mesh asset data in-place and updates the [`ChunkLod`] component.
/// 7. **First-time path** — otherwise, allocates a new handle and inserts
///    `Mesh3d`, `MeshMaterial3d<StandardMaterial>` or `MeshMaterial3d<ChunkMaterial>`,
///    `Transform`, `Visibility`, AABB, [`ChunkRendered`], and [`ChunkLod`].
///
/// If the chunk material has not yet been created (startup system hasn't run)
/// or the entity no longer exists, the event is silently skipped.
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>,
    )>,
) {
    // Determine which material path is active.
    // Custom (texture array) takes priority; fall back to StandardMaterial.
    let use_custom = chunk_material.custom.is_some();
    let has_material = chunk_material.custom.is_some() || chunk_material.standard.is_some();
    if !has_material {
        // Material not yet set up — skip until next frame.
        return;
    }

    let chunk_size_f = CHUNK_SIZE as f32;

    // Face direction offsets: index matches ChunkNeighbors.faces convention.
    // [+Y, -Y, +X, -X, +Z, -Z]
    const NEIGHBOR_OFFSETS: [IVec3; 6] = [
        IVec3::new(0, 1, 0),  // 0: +Y
        IVec3::new(0, -1, 0), // 1: -Y
        IVec3::new(1, 0, 0),  // 2: +X
        IVec3::new(-1, 0, 0), // 3: -X
        IVec3::new(0, 0, 1),  // 4: +Z
        IVec3::new(0, 0, -1), // 5: -Z
    ];

    // For each face index i, the adjacent chunk's face that touches ours is
    // the opposite direction. The face convention pairs are (0,1), (2,3), (4,5),
    // so opposite = i ^ 1.

    for &ChunkModified(coord) in modified_reader.read() {
        let Some(entity) = manager.get_entity(coord) else {
            // Entity not registered — task may have been cancelled or coord
            // arrived out of order; ignore.
            continue;
        };

        let Ok((chunk, maybe_mesh3d, _maybe_lod, has_empty_mesh)) = chunks.get(entity) else {
            // Chunk component not yet attached — deferred command not flushed yet.
            // Re-queue so we retry next frame when the component is available.
            pending_neighbors.0.push(coord);
            continue;
        };

        // Compute LOD from the chunk center to the viewer.
        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);

        // Clamp the step to the minimum among this chunk and all loaded neighbors
        // to prevent border cracks when adjacent chunks have finer LOD levels.
        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
        };

        // Build ChunkNeighbors from the six adjacent loaded chunks.
        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) {
                    // The face of the neighbor that is adjacent to our face_index
                    // is the opposite direction: face_index ^ 1.
                    let opposite_face = face_index ^ 1;
                    neighbors.faces[face_index] = Some(neighbor_chunk.border_slice(opposite_face));
                }
            }
        }

        // Helper: remove all material-related render components from an entity.
        // Both MeshMaterial3d variants must be removed regardless of which path
        // is currently active, because the entity might have been created under
        // the other path (e.g. if ChunkTextureArray was inserted mid-session).
        let remove_render = |cmd: &mut EntityCommands| {
            cmd.remove::<(
                Mesh3d,
                MeshMaterial3d<StandardMaterial>,
                MeshMaterial3d<ChunkMaterial>,
                ChunkRendered,
                ChunkLod,
            )>();
        };

        // Skip meshing entirely for all-air chunks — no render components needed.
        if chunk.is_empty() {
            if maybe_mesh3d.is_some() {
                // Chunk was previously non-empty (e.g. all voxels mined out);
                // strip render components so it becomes invisible.
                let mut ec = commands.entity(entity);
                remove_render(&mut ec);
                // Notify neighbors — they may now have exposed border faces.
                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 {
                // First time seeing this air chunk — notify neighbors so they
                // can generate faces that border this empty space.
                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;
        }

        // Run the neighbor-aware greedy mesher at the effective LOD step.
        let new_mesh = generate_chunk_mesh_with_neighbors(chunk, &neighbors, effective_step);

        if new_mesh.count_vertices() == 0 {
            // Mesher produced no geometry (e.g. all faces are hidden by neighbors).
            // Remove render components if they were previously attached.
            if maybe_mesh3d.is_some() {
                let mut ec = commands.entity(entity);
                remove_render(&mut ec);
            }
            // Tag this entity so we know its mesh is empty. When a neighbor
            // loads later and triggers another re-mesh that produces geometry,
            // we propagate the signal to our own neighbors at that point.
            if !has_empty_mesh {
                commands.entity(entity).insert(EmptyMesh);
            }
            continue;
        }

        if let Some(mesh3d) = maybe_mesh3d {
            // Update path: reuse the existing handle, replace asset data.
            if let Some(existing) = meshes.get_mut(&mesh3d.0) {
                *existing = new_mesh;
            }
            // Update the LOD component to reflect the current level.
            commands.entity(entity).insert(ChunkLod(lod));

            // If this chunk was previously empty (all faces culled) and now has
            // geometry, its border faces changed from invisible to visible.
            // Propagate to neighbors so they can re-evaluate their own faces.
            // This enables multi-layer propagation: each depth level transitions
            // one frame at a time until all chunks converge.
            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 {
            // First-time path: allocate new handle and attach all render components.
            let mesh_handle = meshes.add(new_mesh);

            // World-space origin of this chunk's minimum corner.
            let translation = coord.as_vec3() * chunk_size_f;

            // AABB sized to the full chunk extent for frustum culling.
            let aabb = Aabb::from_min_max(Vec3::ZERO, Vec3::splat(chunk_size_f));

            let mut entity_cmd = commands.entity(entity);

            if use_custom {
                // Texture-array path.
                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 {
                // Fallback StandardMaterial path.
                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 this chunk had EmptyMesh from a previous 0-vertex pass, remove it.
            if has_empty_mesh {
                commands.entity(entity).remove::<EmptyMesh>();
            }

            // A newly rendered chunk changes the border visibility of every
            // adjacent chunk.  Stage ChunkModified for each loaded neighbor so
            // they re-mesh and cull (or un-cull) the faces that touch this chunk.
            // Messages are emitted by flush_neighbor_remesh_system (runs after
            // this system) to avoid a ResMut/Res conflict on the message storage.
            // This is only done on the first-time path to avoid cascading
            // re-meshes on every LOD or voxel-edit update.
            for &offset in &NEIGHBOR_OFFSETS {
                let neighbor_coord = coord + offset;
                if manager.is_loaded(neighbor_coord) {
                    pending_neighbors.0.push(neighbor_coord);
                }
            }
        }
    }
}

// ─── flush_neighbor_remesh_system ────────────────────────────────────────────

/// Drains [`PendingNeighborRemesh`] and emits a [`ChunkModified`] message for
/// each staged coord.
///
/// This system exists solely to decouple the *write* of `ChunkModified` from
/// [`chunk_mesh_system`], which holds a `MessageReader<ChunkModified>` (i.e.
/// `Res` access to the message store).  Having both `Res` and `ResMut` on the
/// same resource in one system triggers Bevy's B0002 access-conflict panic.
///
/// By staging neighbor coords in [`PendingNeighborRemesh`] and draining them
/// here — after `chunk_mesh_system` has finished — we keep the two accesses in
/// separate systems, which Bevy schedules sequentially via `.after()`.
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));
    }
}

// ─── lod_update_system ────────────────────────────────────────────────────────

/// Every frame, recomputes the LOD level for every rendered chunk.
///
/// For each chunk entity that has a [`Transform`] and a [`ChunkLod`] component,
/// this system:
///
/// 1. Reads the chunk's world-space center from its [`ChunkCoordComp`] (or
///    falls back to the entity's [`Transform`] translation).
/// 2. Calls [`compute_lod`] with the current [`ViewerPosition`].
/// 3. If the computed LOD differs from the stored one, emits [`ChunkModified`]
///    so that [`chunk_mesh_system`] regenerates the mesh at the new level.
///
/// The [`ChunkLod`] component is NOT updated here; `chunk_mesh_system` updates
/// it once the new mesh has actually been built.
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 {
        // Determine the chunk's world-space center.
        // Prefer the ChunkCoordComp (grid coord → center) over raw Transform
        // translation, since the transform is at the minimum corner.
        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 {
            // Fallback: treat the transform translation as the minimum corner
            // and offset to find the center.
            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 {
            // Find the coord for this entity so we can emit ChunkModified(coord).
            // We scan the manager's loaded set; this is O(n) but only runs when
            // LOD actually changes, which is rare.
            if let Some(coord) = manager
                .iter_loaded()
                .find_map(|(coord, e)| if e == entity { Some(coord) } else { None })
            {
                modified_writer.write(ChunkModified(coord));

                // Also remesh each loaded neighbor: their effective_step may
                // change now that this chunk's LOD has changed.
                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));
                    }
                }
            }
        }
    }
}

// ─── chunk_despawn_system ─────────────────────────────────────────────────────

/// Responds to [`ChunkUnloadRequest`] messages by saving and despawning chunk entities.
///
/// For each unload request this system:
/// 1. If [`PersistenceConfig::auto_save`] is `true`, saves the chunk's voxel
///    data to disk before the entity is despawned.
/// 2. Removes the chunk from [`ChunkManager`] so the streaming system can
///    re-request the same coord if the viewer returns.
/// 3. Despawns the entity.
///
/// Save errors are reported with `eprintln!` and do not panic.
///
/// This system is generic over `V` because it must query the [`Chunk<V>`]
/// component to serialise voxel data. It is registered by [`MeshPlugin`](crate::mesh::MeshPlugin).
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() {
        // Save before unregistering so the entity is still valid.
        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();
        }
    }
}