voxel_framework/mesh/mod.rs
1//! Greedy mesh generation for voxel chunks with LOD and neighbor-aware seam culling.
2//!
3//! # Greedy meshing
4//!
5//! Naive voxel renderers emit one quad per visible face, producing O(n³) geometry
6//! even for flat surfaces. Greedy meshing collapses adjacent coplanar faces of the
7//! same voxel type into a single merged quad, reducing geometry by an order of
8//! magnitude for typical terrain. The algorithm processes each of the six cardinal
9//! directions independently: for every slice perpendicular to the current axis it
10//! builds a 2-D visibility mask, then scans the mask left-to-right / top-to-bottom
11//! extending each run into the largest rectangle of identical voxels before emitting
12//! a single quad and clearing the merged region.
13//!
14//! # Entry points
15//!
16//! Two public meshing functions are provided:
17//!
18//! - [`generate_chunk_mesh`] — standalone meshing. Border faces that exit the
19//! chunk boundary are always emitted as visible, which leaves gaps between
20//! adjacent loaded chunks until they are meshed independently.
21//! - [`generate_chunk_mesh_with_neighbors`] — seam-free meshing. Border faces are
22//! checked against the corresponding face of each adjacent chunk via
23//! [`ChunkNeighbors`]. A face is culled when the neighboring voxel is solid,
24//! eliminating single-voxel cracks at chunk boundaries.
25//!
26//! Prefer [`generate_chunk_mesh_with_neighbors`] for in-world rendering.
27//! Use [`generate_chunk_mesh`] for isolated previews or when neighbor data is
28//! unavailable.
29//!
30//! # Level of detail (LOD)
31//!
32//! The `step` parameter controls the LOD resolution. A step of `1` samples every
33//! voxel at full detail. A step of `2` groups each `2×2×2` block into a single
34//! super-voxel (half resolution), halving triangle counts for distant chunks.
35//! [`lod::compute_lod`] maps viewer distance to a level; [`lod::lod_to_step`]
36//! converts a level to the step value to pass here.
37//!
38//! | LOD level | Step | Distance threshold |
39//! |-----------|------|------------------------|
40//! | `0` | `1` | < 200 world units |
41//! | `1` | `2` | ≥ 200 world units |
42//!
43//! [`lod::compute_lod_with_hysteresis`] adds a ±5-unit hysteresis band around the
44//! threshold to prevent rapid LOD oscillation as the viewer moves along the boundary.
45//!
46//! # Output mesh attributes
47//!
48//! Every mesh produced by this module contains:
49//!
50//! | Attribute | Type | Description |
51//! |-------------------------|---------------|------------------------------------|
52//! | `ATTRIBUTE_POSITION` | `Float32x3` | Vertex positions in chunk-local space |
53//! | `ATTRIBUTE_NORMAL` | `Float32x3` | Face normals (one of six unit axes) |
54//! | `ATTRIBUTE_UV_0` | `Float32x2` | UVs scaled by voxel count for tiling |
55//! | `ATTRIBUTE_COLOR` | `Float32x4` | Per-vertex color from [`VoxelType::color`] |
56//! | Indices | `U32` | Triangle list with CCW winding |
57//!
58//! [`MeshPlugin<V>`] wires the mesh generation, LOD update, and chunk despawn
59//! systems into a Bevy app.
60
61mod greedy;
62pub mod lod;
63mod neighbor;
64pub mod systems;
65
66pub use greedy::{ATTRIBUTE_TEXTURE_LAYER, generate_chunk_mesh};
67pub use neighbor::generate_chunk_mesh_with_neighbors;
68pub use systems::{
69 ChunkMeshBudget, PendingChunkMeshes, PendingNeighborRemesh, chunk_despawn_system,
70 chunk_mesh_system, flush_neighbor_remesh_system, lod_update_system,
71};
72
73use bevy::prelude::*;
74
75use crate::chunk::CHUNK_SIZE;
76use crate::generator::GeneratorSystems;
77use crate::voxel::VoxelType;
78
79/// System set containing the chunk meshing systems that
80/// [`MeshPlugin`] adds: [`chunk_mesh_system`] and
81/// [`flush_neighbor_remesh_system`].
82///
83/// Order your own systems `.after(MeshSystems)` to observe the state left by
84/// this frame's meshing, such as [`PendingChunkMeshes`].
85#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
86pub struct MeshSystems;
87
88// ─── MeshPlugin ───────────────────────────────────────────────────────────────
89
90/// Bevy [`Plugin`] that registers the mesh generation, LOD update, and chunk
91/// despawn systems for a specific voxel type `V`.
92///
93/// Add this plugin after [`crate::world::WorldPlugin`] and
94/// [`crate::generator::GeneratorPlugin`]. It registers three systems in the
95/// [`Update`] schedule:
96///
97/// - [`lod_update_system`] — recomputes LOD levels every frame and emits
98/// [`crate::world::ChunkModified`] when a level changes.
99/// - [`ChunkMeshBudget`] and [`PendingChunkMeshes`] resources: the per-frame
100/// bound on meshing and the queue of chunks waiting for it.
101/// - [`chunk_mesh_system`] — runs after [`crate::generator::GeneratorSystems`];
102/// responds to [`crate::world::ChunkModified`] by (re)building chunk meshes.
103/// - [`chunk_despawn_system`] — responds to [`crate::world::ChunkUnloadRequest`]
104/// by saving the chunk if it has unsaved changes and despawning the entity.
105///
106/// # Examples
107///
108/// ```rust,no_run
109/// use bevy::prelude::*;
110/// use voxel_framework::{VoxelPlugin, generator::GeneratorPlugin, mesh::MeshPlugin, voxel::DefaultVoxel};
111///
112/// App::new()
113/// .add_plugins(DefaultPlugins)
114/// .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
115/// .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
116/// .add_plugins(MeshPlugin::<DefaultVoxel>::new())
117/// .run();
118/// ```
119pub struct MeshPlugin<V: VoxelType> {
120 _marker: std::marker::PhantomData<V>,
121}
122
123impl<V: VoxelType> MeshPlugin<V> {
124 /// Creates a new [`MeshPlugin`] for voxel type `V`.
125 pub fn new() -> Self {
126 Self {
127 _marker: std::marker::PhantomData,
128 }
129 }
130}
131
132impl<V: VoxelType> Default for MeshPlugin<V> {
133 fn default() -> Self {
134 Self::new()
135 }
136}
137
138impl<V: VoxelType> Plugin for MeshPlugin<V> {
139 fn build(&self, app: &mut App) {
140 app.init_resource::<systems::PendingNeighborRemesh>();
141 app.init_resource::<systems::PendingChunkMeshes>();
142 app.init_resource::<systems::ChunkMeshBudget>();
143 app.add_systems(
144 Update,
145 (
146 systems::lod_update_system::<V>,
147 systems::chunk_mesh_system::<V>
148 .after(GeneratorSystems)
149 .in_set(MeshSystems),
150 systems::flush_neighbor_remesh_system
151 .after(systems::chunk_mesh_system::<V>)
152 .in_set(MeshSystems),
153 systems::chunk_despawn_system::<V>,
154 ),
155 );
156 }
157}
158
159/// Border voxel data from the six cardinal neighbors of a chunk, used for
160/// seam-free meshing with [`generate_chunk_mesh_with_neighbors`].
161///
162/// Each slot holds a flat `CHUNK_SIZE × CHUNK_SIZE` array containing the
163/// outermost face of the adjacent chunk that abuts the current chunk on that
164/// side. The array is obtained from `Chunk::border_slice` on the neighbor.
165///
166/// The face index convention matches `FACE_DIRS`:
167///
168/// | Index | Direction | Neighbor face stored |
169/// |-------|-----------|-------------------------------|
170/// | `0` | `+Y` | bottom face of the chunk above |
171/// | `1` | `-Y` | top face of the chunk below |
172/// | `2` | `+X` | left face of the chunk to the right |
173/// | `3` | `-X` | right face of the chunk to the left |
174/// | `4` | `+Z` | back face of the chunk in front |
175/// | `5` | `-Z` | front face of the chunk behind |
176///
177/// A slot set to `None` means the neighbor is not loaded; the border face is
178/// then treated as open air and the face is emitted unconditionally.
179pub struct ChunkNeighbors<V: VoxelType> {
180 /// Six border face slices in `[+Y, -Y, +X, -X, +Z, -Z]` order.
181 ///
182 /// Each `Some` entry is a `CHUNK_SIZE * CHUNK_SIZE` flat array packed in
183 /// the same order as `Chunk::border_slice` for that face index.
184 pub faces: [Option<[V; CHUNK_SIZE * CHUNK_SIZE]>; 6],
185}
186
187impl<V: VoxelType> Default for ChunkNeighbors<V> {
188 fn default() -> Self {
189 Self {
190 faces: [None, None, None, None, None, None],
191 }
192 }
193}