Skip to main content

voxel_framework/world/
systems.rs

1//! Bevy systems that implement the chunk streaming loop.
2//!
3//! # Systems in this module
4//!
5//! | System | Schedule | Reads | Writes / Emits |
6//! |---|---|---|---|
7//! | [`streaming_system`] | [`Update`] | [`ViewerPosition`], [`ChunkManager`] | [`ChunkLoadRequest`], [`ChunkUnloadRequest`], `ChunkManager` pending set |
8//!
9//! # Execution order
10//!
11//! [`streaming_system`] has no explicit ordering constraints relative to other
12//! `Update` systems. It should run **after** your camera/player system has
13//! updated [`ViewerPosition`] for the current frame. If you need a hard
14//! ordering guarantee, use `.after(YourMovementSystem)` when adding the plugin
15//! or configure a system set.
16//!
17//! # Authoring note
18//!
19//! [`ViewerPosition`] is defined here (alongside the system that consumes it)
20//! because both share the same module-level concern: mapping a world-space
21//! position to chunk-grid decisions. It is re-exported from the crate root via
22//! [`super`].
23
24use bevy::prelude::*;
25
26use crate::chunk::{CHUNK_SIZE, ChunkCoord};
27
28use super::{ChunkLoadRequest, ChunkManager, ChunkUnloadRequest};
29
30// ─── ViewerPosition ───────────────────────────────────────────────────────────
31
32/// World-space position of the primary viewer (player or camera).
33///
34/// This resource is read by [`streaming_system`] every frame to decide which
35/// chunk coordinates lie within the load sphere and which loaded chunks have
36/// drifted beyond the unload sphere. It **must be updated every frame** by
37/// your player or camera system — if it is stale, the streaming system will
38/// not respond to player movement and chunks near the new position will never
39/// be requested.
40///
41/// The resource defaults to the origin (`Vec3::ZERO`). [`WorldPlugin`](crate::world::WorldPlugin)
42/// registers it via `init_resource`, so it is always present when the plugin
43/// is active.
44///
45/// # What happens if it is not updated?
46///
47/// The streaming system will continue to evaluate distances against the last
48/// written position. No new [`ChunkLoadRequest`] events will be emitted for
49/// the region around the player's actual position, and no
50/// [`ChunkUnloadRequest`] events will fire for chunks the player has left
51/// behind. The world will appear frozen at the last known viewer position.
52///
53/// # Example
54///
55/// ```rust,no_run
56/// use bevy::prelude::*;
57/// use voxel_framework::world::ViewerPosition;
58///
59/// fn sync_viewer_to_camera(
60///     mut viewer: ResMut<ViewerPosition>,
61///     camera: Query<&Transform, With<Camera3d>>,
62/// ) {
63///     if let Ok(transform) = camera.single() {
64///         viewer.position = transform.translation;
65///     }
66/// }
67/// ```
68///
69/// Register your sync system in [`Update`] before the streaming system runs:
70///
71/// ```rust,no_run
72/// use bevy::prelude::*;
73/// use voxel_framework::world::ViewerPosition;
74///
75/// # fn sync_viewer_to_camera() {}
76/// # fn main() {
77/// App::new()
78///     .add_systems(Update, sync_viewer_to_camera)
79///     .run();
80/// # }
81/// ```
82#[derive(Resource, Default, Debug, Clone, Copy)]
83pub struct ViewerPosition {
84    /// Current world-space position of the viewer.
85    pub position: Vec3,
86}
87
88// ─── streaming_system ────────────────────────────────────────────────────────
89
90/// The chunks [`streaming_system`] keeps loaded around a viewer: every chunk
91/// whose center is within `load_distance` world units of `viewer`.
92///
93/// This is the single definition of the load range. The loading screen counts
94/// the same chunks, so its total always matches what streaming requests.
95pub(crate) fn chunks_in_load_range(
96    viewer: Vec3,
97    load_distance: f32,
98) -> impl Iterator<Item = ChunkCoord> {
99    let chunk_size_f = CHUNK_SIZE as f32;
100    let radius = (load_distance / chunk_size_f).ceil() as i32;
101    let origin = (viewer / chunk_size_f).floor().as_ivec3();
102
103    (-radius..=radius).flat_map(move |dx| {
104        (-radius..=radius).flat_map(move |dy| {
105            (-radius..=radius).filter_map(move |dz| {
106                let coord: ChunkCoord = origin + IVec3::new(dx, dy, dz);
107                let center = coord.as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5);
108                (center.distance(viewer) <= load_distance).then_some(coord)
109            })
110        })
111    })
112}
113
114/// Drives chunk load and unload decisions based on [`ViewerPosition`].
115///
116/// Scheduled in [`Update`] by [`super::WorldPlugin`]. Each frame this system:
117///
118/// 1. Reads [`ViewerPosition`] and converts it to fractional chunk-grid space
119///    by dividing by `CHUNK_SIZE`.
120/// 2. Computes `load_radius_chunks = ceil(load_distance / CHUNK_SIZE)` and
121///    iterates every integer coordinate in the `[-r, r]³` bounding cube.
122/// 3. For each coordinate whose world-space center is within `load_distance`
123///    and that is neither already loaded nor pending in [`ChunkManager`]:
124///    - calls [`ChunkManager::mark_pending`] to prevent duplicate requests,
125///    - writes a [`ChunkLoadRequest`] for the generation system to consume.
126/// 4. Collects all currently loaded chunk coordinates whose world-space center
127///    distance exceeds `unload_distance`, then writes one
128///    [`ChunkUnloadRequest`] per coordinate.
129///
130/// The unload pass uses a separate `Vec` to avoid holding a shared borrow on
131/// [`ChunkManager`] while emitting messages that may mutate it in the same
132/// frame.
133pub fn streaming_system(
134    viewer: Res<ViewerPosition>,
135    mut manager: ResMut<ChunkManager>,
136    mut load_writer: MessageWriter<ChunkLoadRequest>,
137    mut unload_writer: MessageWriter<ChunkUnloadRequest>,
138) {
139    crate::profile_span!("voxel::world::streaming");
140    let chunk_size_f = CHUNK_SIZE as f32;
141
142    // ── Emit load requests ────────────────────────────────────────────────
143
144    for coord in chunks_in_load_range(viewer.position, manager.load_distance) {
145        if !manager.is_loaded(coord) && !manager.is_pending(coord) {
146            manager.mark_pending(coord);
147            load_writer.write(ChunkLoadRequest(coord));
148        }
149    }
150
151    // ── Emit unload requests ──────────────────────────────────────────────
152
153    // Collect coords to unload first to avoid borrowing `manager` mutably
154    // while iterating its loaded set.
155    let to_unload: Vec<ChunkCoord> = manager
156        .iter_loaded()
157        .filter_map(|(coord, _entity)| {
158            let center = coord.as_vec3() * chunk_size_f + Vec3::splat(chunk_size_f * 0.5);
159            if center.distance(viewer.position) > manager.unload_distance {
160                Some(coord)
161            } else {
162                None
163            }
164        })
165        .collect();
166
167    for coord in to_unload {
168        unload_writer.write(ChunkUnloadRequest(coord));
169    }
170}