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