Skip to main content

voxel_framework/world/
mod.rs

1//! World streaming, chunk lifecycle, and runtime configuration.
2//!
3//! # Overview
4//!
5//! The world module owns three concerns:
6//!
7//! - **Chunk registry** — [`ChunkManager`] tracks which chunks are fully
8//!   loaded, which are in-flight, and the configured streaming distances.
9//! - **Viewer tracking** — [`ViewerPosition`] is a lightweight resource that
10//!   your player/camera system updates every frame. The streaming system reads
11//!   it to decide which chunks to load or unload.
12//! - **Lifecycle events** — [`ChunkLoadRequest`], [`ChunkUnloadRequest`], and
13//!   [`ChunkModified`] are the message bus between the streaming system and
14//!   the rest of the engine (generation, meshing, persistence).
15//!
16//! Add [`WorldPlugin`] to your [`App`] to register all of the above
17//! automatically.
18//!
19//! # The Streaming Pipeline
20//!
21//! Every frame the [`systems::streaming_system`] executes the following steps:
22//!
23//! ```text
24//! ┌─────────────────────┐
25//! │   ViewerPosition    │  updated by your camera/player system each frame
26//! └────────┬────────────┘
27//!          │ read by streaming_system
28//!          ▼
29//! ┌─────────────────────┐
30//! │  Distance check     │  iterate cube of radius ceil(load_distance/CHUNK_SIZE)
31//! │  around viewer      │  compute world-space center distance per coord
32//! └────────┬────────────┘
33//!          │
34//!     ┌────┴─────┐
35//!     │          │
36//!     ▼          ▼
37//! ChunkLoad   ChunkUnload
38//! Request     Request
39//!  (enter      (exit
40//!  sphere)     sphere)
41//!     │          │
42//!     ▼          ▼
43//! Generator  Despawn
44//! system     system
45//! (async)
46//!     │
47//!     ▼
48//! ChunkModified  ←── voxel edits (mining, placement, etc.)
49//!     │
50//!     ▼
51//! Mesh rebuild system
52//! ```
53//!
54//! 1. [`ViewerPosition`] is updated by your player/camera system.
55//! 2. [`systems::streaming_system`] converts it to chunk-grid space and
56//!    iterates every coordinate within a bounding cube of radius
57//!    `ceil(load_distance / CHUNK_SIZE)`.
58//! 3. For each coordinate inside the load sphere that is neither loaded nor
59//!    pending, the system emits [`ChunkLoadRequest`] and marks the coord
60//!    pending in [`ChunkManager`].
61//! 4. For each currently loaded chunk whose center has drifted beyond
62//!    `unload_distance`, the system emits [`ChunkUnloadRequest`].
63//! 5. An external generation system receives [`ChunkLoadRequest`], generates
64//!    voxel data asynchronously, spawns the entity, and calls
65//!    [`ChunkManager::register`].
66//! 6. Whenever voxel data changes (mining, placement, etc.), the responsible
67//!    system emits [`ChunkModified`], which triggers mesh regeneration for
68//!    that chunk and its affected neighbors.
69//!
70//! # Events and Messages
71//!
72//! | Event | When it fires | Who consumes it |
73//! |---|---|---|
74//! | [`ChunkLoadRequest`] | Chunk coord enters `load_distance` sphere | Generation system |
75//! | [`ChunkUnloadRequest`] | Loaded chunk center exits `unload_distance` sphere | Despawn system |
76//! | [`ChunkModified`] | A loaded chunk needs a remesh: data written, finished loading, or a neighbour/LOD change | Mesh rebuild, occlusion, autosave (chunks with unsaved changes only) |
77//!
78//! # World Configuration
79//!
80//! [`config::WorldConfig`] is loaded from `world.toml` in the working
81//! directory at startup by [`config::WorldConfigPlugin`]. It is inserted as a
82//! Bevy [`Resource`] and its `load_distance` / `unload_distance` values are
83//! applied directly to [`ChunkManager`]. If the file is absent or malformed,
84//! [`config::WorldConfig::default`] is used silently.
85
86pub mod collision;
87pub mod config;
88pub mod daycycle;
89pub mod exposed_faces;
90pub mod loading;
91#[cfg(feature = "crafting")]
92pub mod manifest;
93pub mod mining;
94pub mod mining_overlay;
95pub mod occlusion;
96pub mod persistence;
97pub mod placement;
98pub mod raycast;
99pub mod systems;
100pub mod voxel_ops;
101
102pub use collision::{
103    capsule_overlaps_voxels, resolve_capsule_collision, resolve_sphere_collision,
104    sphere_overlaps_voxels,
105};
106pub use config::{WorldConfig, WorldConfigPlugin};
107pub use daycycle::{DayCycleConfig, DayCyclePlugin, SunLight};
108pub use exposed_faces::record_voxel_edit;
109pub use loading::{LoadingPlugin, LoadingProgress, WorldLoadingState, WorldReady};
110#[cfg(feature = "items")]
111pub use mining::MiningInputPlugin;
112pub use mining::{
113    MiningConfig, MiningPlugin, MiningProgress, MiningState, VoxelBroken, mining_input_system,
114    stop_mining, tick_mining,
115};
116pub use mining_overlay::{
117    MiningOverlay, MiningOverlayConfig, MiningOverlayPlugin, MiningOverlayStage,
118    MiningOverlaySystems, mining_overlay_stage, mining_overlay_transform, update_mining_overlay,
119};
120pub use occlusion::{OcclusionPlugin, is_chunk_occluded};
121pub use persistence::{
122    PersistenceConfig, PersistencePlugin, WorldDataDir, chunk_autosave_system, try_load_chunk,
123};
124pub use placement::{
125    PlacementConfig, PlacementPlugin, PlacementState, VoxelPlaced, tick_placement, try_place_voxel,
126};
127#[cfg(feature = "items")]
128pub use placement::{PlacementInputPlugin, placement_input_system};
129pub use raycast::{RaycastHit, raycast};
130pub use systems::ViewerPosition;
131pub use voxel_ops::{get_state_at, get_voxel_at, set_state_at, set_voxel_at};
132
133use std::collections::{HashMap, HashSet};
134
135use bevy::prelude::*;
136
137use crate::chunk::ChunkCoord;
138
139// ─── Constants ───────────────────────────────────────────────────────────────
140
141/// Default radius in world units within which chunks are loaded (150.0).
142///
143/// Used as the initial value for [`ChunkManager::load_distance`] when no
144/// [`config::WorldConfig`] overrides it. Can be overridden per-instance via
145/// [`ChunkManager::new`] or by loading a `world.toml` with
146/// [`config::WorldConfigPlugin`].
147pub const DEFAULT_LOAD_DISTANCE: f32 = 150.0;
148
149/// Default radius in world units beyond which chunks are unloaded (200.0).
150///
151/// Used as the initial value for [`ChunkManager::unload_distance`]. The
152/// 50-unit gap between this constant and [`DEFAULT_LOAD_DISTANCE`] creates a
153/// **hysteresis band**: chunks that have been loaded are not immediately
154/// unloaded when the viewer steps back past the load boundary. This prevents
155/// rapid load/unload cycling ("thrashing") near the edge of the streaming
156/// sphere.
157pub const DEFAULT_UNLOAD_DISTANCE: f32 = 200.0;
158
159// ─── Events ──────────────────────────────────────────────────────────────────
160
161/// Fired by [`systems::streaming_system`] when a chunk coordinate enters the
162/// load sphere and must be generated and spawned.
163///
164/// The wrapped [`ChunkCoord`] identifies the chunk-grid position that should
165/// be populated. Upon receiving this event, a generation system should:
166///
167/// 1. Generate voxel data for the coordinate (typically on a thread pool).
168/// 2. Spawn a Bevy entity with the resulting mesh and voxel components.
169/// 3. Call [`ChunkManager::register`] with the coord and new entity so the
170///    streaming system considers the chunk fully loaded.
171///
172/// The coord is guaranteed to be neither already loaded nor pending at the
173/// moment the event is written.
174#[derive(Message, Debug, Clone, Copy, PartialEq, Eq, Hash)]
175pub struct ChunkLoadRequest(pub ChunkCoord);
176
177/// Fired by [`systems::streaming_system`] when a loaded chunk's world-space
178/// center drifts beyond [`ChunkManager::unload_distance`].
179///
180/// The wrapped [`ChunkCoord`] identifies the chunk to remove. Upon receiving
181/// this event, a despawn system should despawn the entity returned by
182/// [`ChunkManager::get_entity`] and call [`ChunkManager::unregister`] so the
183/// coord becomes eligible for reloading in the future.
184///
185/// Note that the 50-unit hysteresis gap between [`DEFAULT_LOAD_DISTANCE`] and
186/// [`DEFAULT_UNLOAD_DISTANCE`] means this event fires noticeably later than
187/// the chunk first became "out of load range".
188#[derive(Message, Debug, Clone, Copy, PartialEq, Eq, Hash)]
189pub struct ChunkUnloadRequest(pub ChunkCoord);
190
191/// Fired whenever a loaded chunk needs its mesh rebuilt: its voxel data was
192/// written, it just finished loading, or a neighbour or LOD change affects
193/// its faces.
194///
195/// The message alone does not mean the data changed. Whether a chunk has
196/// unsaved changes is tracked by [`Chunk::is_dirty`](crate::chunk::Chunk::is_dirty),
197/// which is what the persistence systems check before writing.
198///
199/// The wrapped [`ChunkCoord`] identifies the modified chunk. Consumers
200/// — typically the mesh rebuild system — should regenerate the mesh for this
201/// chunk and re-evaluate the face visibility of its six face-adjacent
202/// neighbors, because a voxel change at a chunk boundary affects the neighbor's
203/// exposed faces as well.
204///
205/// This event is emitted by high-level operations such as [`mining`] and
206/// [`placement`], and also by any system that calls [`voxel_ops::set_voxel_at`]
207/// directly.
208#[derive(Message, Debug, Clone, Copy, PartialEq, Eq, Hash)]
209pub struct ChunkModified(pub ChunkCoord);
210
211// ─── ChunkManager ─────────────────────────────────────────────────────────────
212
213/// Central registry that tracks the state of every chunk in the streaming system.
214///
215/// `ChunkManager` is inserted as a Bevy [`Resource`] by [`WorldPlugin`] and
216/// updated by [`systems::streaming_system`] every frame. It maintains two
217/// internal sets:
218///
219/// - **Loaded** — chunks that have a live Bevy entity with a built mesh. Query
220///   membership with [`is_loaded`](ChunkManager::is_loaded) and retrieve the
221///   entity with [`get_entity`](ChunkManager::get_entity).
222/// - **Pending** — chunk coordinates for which a [`ChunkLoadRequest`] has been
223///   emitted but whose generation is not yet complete. Query membership with
224///   [`is_pending`](ChunkManager::is_pending).
225///
226/// The two public distance fields, [`load_distance`](ChunkManager::load_distance)
227/// and [`unload_distance`](ChunkManager::unload_distance), are read every frame
228/// by the streaming system. They default to [`DEFAULT_LOAD_DISTANCE`] and
229/// [`DEFAULT_UNLOAD_DISTANCE`] respectively, and can be overridden at runtime
230/// or by loading a [`config::WorldConfig`].
231///
232/// # Querying chunks
233///
234/// ```rust,no_run
235/// use bevy::prelude::*;
236/// use voxel_framework::world::ChunkManager;
237///
238/// fn inspect_chunks(manager: Res<ChunkManager>) {
239///     println!("loaded: {}, pending: {}", manager.loaded_count(), manager.pending_count());
240///
241///     for (coord, entity) in manager.iter_loaded() {
242///         println!("chunk {:?} → entity {:?}", coord, entity);
243///     }
244/// }
245/// ```
246///
247/// # Registering a generated chunk
248///
249/// After generating voxel data and spawning the entity, call
250/// [`register`](ChunkManager::register) to promote the coord from pending to
251/// loaded:
252///
253/// ```rust,no_run
254/// use bevy::prelude::*;
255/// use voxel_framework::world::ChunkManager;
256///
257/// fn finish_generation(mut manager: ResMut<ChunkManager>, mut commands: Commands) {
258///     let coord = IVec3::new(1, 0, 0);
259///     let entity = commands.spawn_empty().id();
260///     manager.register(coord, entity);
261/// }
262/// ```
263#[derive(Resource, Debug)]
264pub struct ChunkManager {
265    /// Fully loaded chunks: coord → Bevy entity with voxel mesh.
266    loaded_chunks: HashMap<IVec3, Entity>,
267    /// Chunk coords that have been requested but not yet fully loaded.
268    pending_load: HashSet<IVec3>,
269    /// Distance (world units) within which chunks are loaded.
270    pub load_distance: f32,
271    /// Distance (world units) beyond which chunks are unloaded.
272    pub unload_distance: f32,
273}
274
275impl ChunkManager {
276    /// Creates a new `ChunkManager` with the given streaming distances.
277    pub fn new(load_distance: f32, unload_distance: f32) -> Self {
278        Self {
279            loaded_chunks: HashMap::new(),
280            pending_load: HashSet::new(),
281            load_distance,
282            unload_distance,
283        }
284    }
285
286    /// Returns `true` if the chunk at `coord` is fully loaded.
287    #[inline]
288    pub fn is_loaded(&self, coord: IVec3) -> bool {
289        self.loaded_chunks.contains_key(&coord)
290    }
291
292    /// Returns `true` if the chunk at `coord` is queued or in-flight.
293    #[inline]
294    pub fn is_pending(&self, coord: IVec3) -> bool {
295        self.pending_load.contains(&coord)
296    }
297
298    /// Returns the Bevy entity for a fully loaded chunk, if any.
299    #[inline]
300    pub fn get_entity(&self, coord: IVec3) -> Option<Entity> {
301        self.loaded_chunks.get(&coord).copied()
302    }
303
304    /// Marks a chunk coord as pending load.
305    ///
306    /// No-op if the chunk is already loaded or already pending.
307    pub fn mark_pending(&mut self, coord: IVec3) {
308        if !self.is_loaded(coord) {
309            self.pending_load.insert(coord);
310        }
311    }
312
313    /// Registers a fully loaded chunk with its Bevy entity.
314    ///
315    /// Removes the coord from the pending set if it was there.
316    pub fn register(&mut self, coord: IVec3, entity: Entity) {
317        self.pending_load.remove(&coord);
318        self.loaded_chunks.insert(coord, entity);
319    }
320
321    /// Unregisters a chunk, removing it from loaded and pending sets.
322    ///
323    /// Returns the entity if it was loaded, `None` otherwise.
324    pub fn unregister(&mut self, coord: IVec3) -> Option<Entity> {
325        self.pending_load.remove(&coord);
326        self.loaded_chunks.remove(&coord)
327    }
328
329    /// Returns an iterator over all loaded chunk coordinates and their entities.
330    pub fn iter_loaded(&self) -> impl Iterator<Item = (IVec3, Entity)> + '_ {
331        self.loaded_chunks
332            .iter()
333            .map(|(&coord, &entity)| (coord, entity))
334    }
335
336    /// Returns the number of fully loaded chunks.
337    #[inline]
338    pub fn loaded_count(&self) -> usize {
339        self.loaded_chunks.len()
340    }
341
342    /// Returns the number of chunks queued for loading.
343    #[inline]
344    pub fn pending_count(&self) -> usize {
345        self.pending_load.len()
346    }
347}
348
349impl Default for ChunkManager {
350    fn default() -> Self {
351        Self::new(DEFAULT_LOAD_DISTANCE, DEFAULT_UNLOAD_DISTANCE)
352    }
353}
354
355// ─── WorldPlugin ─────────────────────────────────────────────────────────────
356
357/// Plugin that wires up the world streaming system.
358///
359/// Registers the following on the Bevy [`App`]:
360///
361/// - [`ChunkManager`] resource (via `init_resource`, defaults to
362///   [`DEFAULT_LOAD_DISTANCE`] / [`DEFAULT_UNLOAD_DISTANCE`]).
363/// - [`ViewerPosition`] resource (via `init_resource`, defaults to the origin).
364/// - [`ChunkLoadRequest`], [`ChunkUnloadRequest`], and [`ChunkModified`]
365///   messages.
366/// - [`systems::streaming_system`] scheduled in [`Update`].
367///
368/// For configuration loading, add [`config::WorldConfigPlugin`] as well. For
369/// initial-load progress tracking, add [`loading::LoadingPlugin`].
370///
371/// # Example
372///
373/// ```rust,no_run
374/// use bevy::prelude::*;
375/// use voxel_framework::world::{WorldPlugin, config::WorldConfigPlugin};
376///
377/// App::new()
378///     .add_plugins((WorldPlugin, WorldConfigPlugin))
379///     .run();
380/// ```
381pub struct WorldPlugin;
382
383impl Plugin for WorldPlugin {
384    fn build(&self, app: &mut App) {
385        app.init_resource::<ChunkManager>();
386        app.init_resource::<ViewerPosition>();
387        app.add_message::<ChunkLoadRequest>();
388        app.add_message::<ChunkUnloadRequest>();
389        app.add_message::<ChunkModified>();
390        app.add_systems(Update, systems::streaming_system);
391    }
392}
393
394// ─── Tests ───────────────────────────────────────────────────────────────────
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399
400    fn manager() -> ChunkManager {
401        ChunkManager::default()
402    }
403
404    #[test]
405    fn new_manager_is_empty() {
406        let m = manager();
407        assert_eq!(m.loaded_count(), 0);
408        assert_eq!(m.pending_count(), 0);
409    }
410
411    #[test]
412    fn mark_pending_adds_to_pending_set() {
413        let mut m = manager();
414        let coord = IVec3::new(1, 0, 0);
415        m.mark_pending(coord);
416        assert!(m.is_pending(coord));
417        assert!(!m.is_loaded(coord));
418        assert_eq!(m.pending_count(), 1);
419    }
420
421    #[test]
422    fn register_promotes_pending_to_loaded() {
423        let mut m = manager();
424        let coord = IVec3::new(2, 0, 0);
425        m.mark_pending(coord);
426
427        // Use bits to construct a fake Entity for testing.
428        let entity = Entity::from_bits(1);
429        m.register(coord, entity);
430
431        assert!(m.is_loaded(coord));
432        assert!(!m.is_pending(coord));
433        assert_eq!(m.get_entity(coord), Some(entity));
434        assert_eq!(m.loaded_count(), 1);
435        assert_eq!(m.pending_count(), 0);
436    }
437
438    #[test]
439    fn unregister_removes_loaded_chunk() {
440        let mut m = manager();
441        let coord = IVec3::new(3, 0, 0);
442        let entity = Entity::from_bits(2);
443        m.register(coord, entity);
444
445        let removed = m.unregister(coord);
446        assert_eq!(removed, Some(entity));
447        assert!(!m.is_loaded(coord));
448        assert_eq!(m.loaded_count(), 0);
449    }
450
451    #[test]
452    fn mark_pending_no_op_if_already_loaded() {
453        let mut m = manager();
454        let coord = IVec3::new(4, 0, 0);
455        let entity = Entity::from_bits(3);
456        m.register(coord, entity);
457
458        // Marking a loaded chunk pending should be a no-op.
459        m.mark_pending(coord);
460        assert!(!m.is_pending(coord));
461        assert!(m.is_loaded(coord));
462    }
463
464    #[test]
465    fn iter_loaded_yields_all_registered_chunks() {
466        let mut m = manager();
467        let coords: Vec<IVec3> = (0..5).map(|i| IVec3::new(i, 0, 0)).collect();
468
469        for (i, &coord) in coords.iter().enumerate() {
470            m.register(coord, Entity::from_bits(i as u64 + 1));
471        }
472
473        let loaded: Vec<IVec3> = m.iter_loaded().map(|(c, _)| c).collect();
474        assert_eq!(loaded.len(), coords.len());
475        for coord in &coords {
476            assert!(loaded.contains(coord));
477        }
478    }
479
480    #[test]
481    fn default_distances_match_constants() {
482        let m = manager();
483        assert_eq!(m.load_distance, DEFAULT_LOAD_DISTANCE);
484        assert_eq!(m.unload_distance, DEFAULT_UNLOAD_DISTANCE);
485    }
486}