voxel_framework/world/loading.rs
1//! Initial world loading lifecycle — progress tracking and the ready signal.
2//!
3//! # Overview
4//!
5//! When a world first starts, the streaming system begins requesting chunks
6//! around the viewer. This module tracks how many of those chunks have been
7//! fully generated and meshed, and fires a one-shot signal when the world is
8//! ready to display.
9//!
10//! # What "loaded" means
11//!
12//! A chunk is considered **loaded** when it is registered in [`ChunkManager`]
13//! via [`ChunkManager::register`] — meaning voxel data has been generated
14//! **and** the renderable mesh entity has been spawned. The total number of
15//! chunks expected in the initial load sphere is computed once from
16//! `load_distance` using `count_chunks_in_sphere`.
17//!
18//! # Event flow
19//!
20//! ```text
21//! WorldPlugin starts
22//! │
23//! ▼
24//! loading_progress_system runs each frame (after GeneratorSystems)
25//! │
26//! ├─ emits LoadingProgress { loaded, total, progress } every frame
27//! │
28//! └─ when progress >= 1.0:
29//! emits WorldReady (once)
30//! sets WorldLoadingState::ready = true → system becomes a no-op
31//! ```
32//!
33//! # Usage
34//!
35//! Add [`LoadingPlugin`] to your [`App`] alongside [`super::WorldPlugin`].
36//! Subscribe to [`LoadingProgress`] to drive a loading screen, and to
37//! [`WorldReady`] to transition out of it:
38//!
39//! ```rust,no_run
40//! use bevy::prelude::*;
41//! use voxel_framework::world::{WorldPlugin, LoadingPlugin, LoadingProgress, WorldReady};
42//!
43//! fn on_world_ready(mut reader: MessageReader<WorldReady>) {
44//! for _ in reader.read() {
45//! println!("world is ready!");
46//! }
47//! }
48//!
49//! App::new()
50//! .add_plugins((WorldPlugin, LoadingPlugin))
51//! .add_systems(Update, on_world_ready)
52//! .run();
53//! ```
54
55use bevy::prelude::*;
56
57use crate::chunk::{CHUNK_SIZE, VOXEL_SIZE};
58use crate::generator::GeneratorSystems;
59
60use super::ChunkManager;
61
62// ─── Messages ────────────────────────────────────────────────────────────────
63
64/// Emitted every frame while the initial chunk sphere is still loading.
65///
66/// [`loading_progress_system`] writes this message once per frame from the
67/// moment the world starts until [`WorldReady`] fires. Once [`WorldReady`] has
68/// been emitted, this message is no longer written.
69///
70/// - `loaded` — number of chunks currently registered in [`ChunkManager`].
71/// - `total` — expected chunk count for the full load sphere (computed once
72/// from `load_distance` on the first frame).
73/// - `progress` — `loaded / total`, clamped to `[0.0, 1.0]`.
74///
75/// # Example
76///
77/// ```rust,no_run
78/// use bevy::prelude::*;
79/// use voxel_framework::world::LoadingProgress;
80///
81/// fn show_progress(mut reader: MessageReader<LoadingProgress>) {
82/// for msg in reader.read() {
83/// println!("loading: {:.0}%", msg.progress * 100.0);
84/// }
85/// }
86/// ```
87#[derive(Message, Debug, Clone)]
88pub struct LoadingProgress {
89 pub loaded: u32,
90 pub total: u32,
91 pub progress: f32,
92}
93
94/// One-shot signal emitted when the initial chunk sphere is fully loaded.
95///
96/// [`loading_progress_system`] emits this message exactly once, on the first
97/// frame that [`LoadingProgress::progress`] reaches `1.0`. After it fires,
98/// [`WorldLoadingState::ready`] is set to `true` and the progress system
99/// becomes a no-op — no further [`LoadingProgress`] or `WorldReady` messages
100/// are written.
101///
102/// Use this event to transition your app out of a loading screen, enable
103/// gameplay input, or trigger any one-time "world is ready" logic.
104///
105/// # Example
106///
107/// ```rust,no_run
108/// use bevy::prelude::*;
109/// use voxel_framework::world::WorldReady;
110///
111/// fn on_world_ready(mut reader: MessageReader<WorldReady>) {
112/// for _ in reader.read() {
113/// println!("all chunks generated — entering gameplay");
114/// }
115/// }
116///
117/// # fn main() {
118/// App::new()
119/// .add_message::<WorldReady>()
120/// .add_systems(Update, on_world_ready)
121/// .run();
122/// # }
123/// ```
124#[derive(Message, Debug, Clone)]
125pub struct WorldReady;
126
127// ─── Resource ─────────────────────────────────────────────────────────────────
128
129/// Internal resource that guards the one-shot [`WorldReady`] emission.
130///
131/// Inserted by [`LoadingPlugin`] via `init_resource`. [`loading_progress_system`]
132/// reads and mutates this resource each frame:
133///
134/// - `expected` is computed once on the first frame from [`ChunkManager::load_distance`]
135/// and cached here to avoid recomputing it every tick.
136/// - `ready` is set to `true` after [`WorldReady`] fires, turning the system
137/// into a no-op for the remainder of the session.
138///
139/// This resource is not intended to be mutated by user code. To check whether
140/// the world has finished loading, subscribe to [`WorldReady`] instead.
141#[derive(Resource, Default)]
142pub struct WorldLoadingState {
143 /// Set to `true` after [`WorldReady`] has been emitted.
144 pub ready: bool,
145 /// Total chunks expected in the initial load sphere (computed once).
146 pub expected: u32,
147}
148
149// ─── Helpers (pure, testable) ─────────────────────────────────────────────────
150
151/// Returns the number of chunk coords within a cubic grid of `[-r, r]^3` that
152/// also fall inside the sphere of radius `r` (measured in chunk units).
153pub(crate) fn count_chunks_in_sphere(radius_in_chunks: i32) -> u32 {
154 let r = radius_in_chunks;
155 let mut count = 0u32;
156 for dx in -r..=r {
157 for dy in -r..=r {
158 for dz in -r..=r {
159 // Use squared distance to stay in integer arithmetic.
160 let dist_sq = dx * dx + dy * dy + dz * dz;
161 if dist_sq <= r * r {
162 count += 1;
163 }
164 }
165 }
166 }
167 count
168}
169
170/// Computes the loading progress fraction given `loaded` and `expected` counts.
171/// Returns 0.0 when `expected` is 0 to avoid division by zero.
172pub(crate) fn compute_progress(loaded: u32, expected: u32) -> f32 {
173 if expected == 0 {
174 0.0
175 } else {
176 (loaded as f32 / expected as f32).min(1.0)
177 }
178}
179
180// ─── System ───────────────────────────────────────────────────────────────────
181
182/// Tracks initial chunk loading and emits [`LoadingProgress`] and [`WorldReady`].
183///
184/// Scheduled in [`Update`], ordered after [`GeneratorSystems`] so that any
185/// chunks completed in the current frame are already counted before progress
186/// is computed.
187///
188/// On the first invocation, the expected chunk count is derived from
189/// [`ChunkManager::load_distance`] and cached in [`WorldLoadingState::expected`].
190/// Subsequent frames skip this computation and go straight to the progress
191/// check.
192///
193/// Once [`WorldLoadingState::ready`] is `true` (set after [`WorldReady`]
194/// fires), the system returns immediately without writing any messages.
195pub fn loading_progress_system(
196 manager: Res<ChunkManager>,
197 mut loading_state: ResMut<WorldLoadingState>,
198 mut progress_writer: MessageWriter<LoadingProgress>,
199 mut ready_writer: MessageWriter<WorldReady>,
200) {
201 // Compute the expected chunk count once.
202 if loading_state.expected == 0 {
203 let radius_in_chunks =
204 (manager.load_distance / (CHUNK_SIZE as f32 * VOXEL_SIZE)).ceil() as i32;
205 loading_state.expected = count_chunks_in_sphere(radius_in_chunks);
206 }
207
208 if loading_state.ready {
209 return;
210 }
211
212 let loaded = manager.loaded_count() as u32;
213 let expected = loading_state.expected;
214 let progress = compute_progress(loaded, expected);
215
216 progress_writer.write(LoadingProgress {
217 loaded,
218 total: expected,
219 progress,
220 });
221
222 if progress >= 1.0 {
223 ready_writer.write(WorldReady);
224 loading_state.ready = true;
225 }
226}
227
228// ─── Plugin ───────────────────────────────────────────────────────────────────
229
230/// Plugin that tracks initial world loading and emits [`LoadingProgress`] and [`WorldReady`].
231///
232/// Registers the following on the Bevy [`App`]:
233///
234/// - [`WorldLoadingState`] resource (via `init_resource`).
235/// - [`LoadingProgress`] and [`WorldReady`] messages.
236/// - [`loading_progress_system`] scheduled in [`Update`] after [`GeneratorSystems`].
237///
238/// Must be used together with [`super::WorldPlugin`], which provides the
239/// [`ChunkManager`] resource this plugin reads.
240///
241/// # Example
242///
243/// ```rust,no_run
244/// use bevy::prelude::*;
245/// use voxel_framework::world::{WorldPlugin, LoadingPlugin, WorldReady};
246///
247/// fn on_ready(mut reader: MessageReader<WorldReady>) {
248/// for _ in reader.read() {
249/// println!("world ready — starting gameplay");
250/// }
251/// }
252///
253/// App::new()
254/// .add_plugins((WorldPlugin, LoadingPlugin))
255/// .add_systems(Update, on_ready)
256/// .run();
257/// ```
258pub struct LoadingPlugin;
259
260impl Plugin for LoadingPlugin {
261 fn build(&self, app: &mut App) {
262 app.init_resource::<WorldLoadingState>();
263 app.add_message::<LoadingProgress>();
264 app.add_message::<WorldReady>();
265 app.add_systems(Update, loading_progress_system.after(GeneratorSystems));
266 }
267}
268
269// ─── Tests ────────────────────────────────────────────────────────────────────
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274
275 #[test]
276 fn test_loading_progress_zero_when_nothing_loaded() {
277 // With nothing loaded, progress should be 0.0.
278 let progress = compute_progress(0, 100);
279 assert_eq!(progress, 0.0);
280 }
281
282 #[test]
283 fn test_loading_progress_zero_when_expected_is_zero() {
284 // Guard against division by zero when expected hasn't been computed yet.
285 let progress = compute_progress(0, 0);
286 assert_eq!(progress, 0.0);
287 }
288
289 #[test]
290 fn test_loading_progress_partial() {
291 let progress = compute_progress(50, 100);
292 assert!((progress - 0.5).abs() < f32::EPSILON);
293 }
294
295 #[test]
296 fn test_loading_ready_when_fully_loaded() {
297 // When loaded >= expected, progress reaches 1.0 — WorldReady condition met.
298 let progress = compute_progress(100, 100);
299 assert_eq!(progress, 1.0);
300 // Simulate the ready trigger.
301 assert!(progress >= 1.0);
302 }
303
304 #[test]
305 fn test_loading_ready_when_overloaded() {
306 // loaded can exceed expected briefly; progress is clamped to 1.0.
307 let progress = compute_progress(110, 100);
308 assert_eq!(progress, 1.0);
309 }
310
311 #[test]
312 fn test_count_chunks_in_sphere_radius_zero() {
313 // Radius 0 → only the origin chunk.
314 assert_eq!(count_chunks_in_sphere(0), 1);
315 }
316
317 #[test]
318 fn test_count_chunks_in_sphere_radius_one() {
319 // Radius 1 → 7 chunks (origin + 6 face-adjacent).
320 assert_eq!(count_chunks_in_sphere(1), 7);
321 }
322
323 #[test]
324 fn test_count_chunks_in_sphere_positive_count() {
325 // Any positive radius should yield a positive chunk count.
326 assert!(count_chunks_in_sphere(5) > 0);
327 }
328}