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