voxel-framework 0.13.2

A reusable voxel engine framework built on Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Persistent user settings saved to `worlds/{world_name}/settings.json`.
//!
//! [`PersistedSettings`] holds the four in-game slider values (FOV, SFX
//! volume, render distance, mouse sensitivity).
//!
//! [`SettingsPlugin`] does the whole job for one world: it applies the saved
//! file to the configuration resources at startup and writes the file when the
//! player leaves the Settings menu.
//!
//! # By hand
//!
//! A game with its own rules can read and write the file itself:
//!
//! ```rust,no_run
//! use voxel_framework::settings::PersistedSettings;
//!
//! // Save
//! let settings = PersistedSettings {
//!     fov_degrees: 90.0,
//!     sfx_volume: 0.8,
//!     render_distance_chunks: 10,
//!     sensitivity_pct: 100,
//! };
//! settings.save("my_world");
//!
//! // Load
//! if let Some(saved) = PersistedSettings::load("my_world") {
//!     println!("Loaded FOV: {}", saved.fov_degrees);
//! }
//! ```

use std::path::{Path, PathBuf};

use bevy::prelude::*;
use serde::{Deserialize, Serialize};

use crate::audio::SfxConfig;
use crate::player::PlayerConfig;
use crate::ui::SaveSettingsRequest;
use crate::world::{ChunkManager, WorldConfig};

/// World units of load distance per render-distance step of the settings
/// menu. One step is one chunk.
pub const RENDER_DISTANCE_STEP: f32 = 16.0;

/// How far beyond the load distance chunks are kept when the render distance
/// comes from the settings menu or from a settings file.
pub const RENDER_DISTANCE_UNLOAD_MARGIN: f32 = 32.0;

/// User-adjustable settings persisted to `worlds/{world_name}/settings.json`.
///
/// All four fields map directly to the in-game sliders exposed by
/// [`crate::ui::PauseMenuPlugin`]:
///
/// | Field | Slider | Range |
/// |-------|--------|-------|
/// | `fov_degrees` | Field of View | 50–120 |
/// | `sfx_volume` | SFX Volume | 0.0–1.0 |
/// | `render_distance_chunks` | Render Distance | 4–32 (even) |
/// | `sensitivity_pct` | Mouse Sensitivity | 10–100 |
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersistedSettings {
    /// Vertical field-of-view in degrees. Valid range: `50.0`–`120.0`.
    pub fov_degrees: f32,
    /// SFX volume in the range `[0.0, 1.0]`.
    pub sfx_volume: f32,
    /// Render distance in chunks (even values only). Valid range: `4`–`32`.
    pub render_distance_chunks: u32,
    /// Mouse sensitivity as a percentage of the default.
    /// `100` = default ("Minecraft-like" feel), `10` = slowest.
    /// The underlying [`crate::player::Player::sensitivity`] multiplier is
    /// `sensitivity_pct / 100`, combined internally with the hidden
    /// `MOUSE_SCALE` constant (rad/px) to produce camera rotation per mouse
    /// pixel.
    pub sensitivity_pct: u32,
}

impl PersistedSettings {
    /// Saves these settings to `worlds/{world_name}/settings.json`.
    ///
    /// Creates the directory if it does not exist. Silently ignores I/O errors
    /// so that a read-only filesystem does not crash the game.
    pub fn save(&self, world_name: &str) {
        self.save_to(&settings_path(world_name));
    }

    /// Loads settings from `worlds/{world_name}/settings.json`.
    ///
    /// Returns `None` if the file does not exist or cannot be parsed (e.g. on
    /// the first run before any settings have been saved).
    pub fn load(world_name: &str) -> Option<Self> {
        Self::load_from(&settings_path(world_name))
    }

    /// Saves these settings to the file at `path`.
    ///
    /// Creates the parent directory if it does not exist. Silently ignores
    /// I/O errors, like [`save`](Self::save).
    pub fn save_to(&self, path: &Path) {
        if let Some(dir) = path.parent() {
            let _ = std::fs::create_dir_all(dir);
        }
        if let Ok(json) = serde_json::to_string_pretty(self) {
            let _ = std::fs::write(path, json);
        }
    }

    /// Loads settings from the file at `path`.
    ///
    /// Returns `None` if the file does not exist or cannot be parsed.
    pub fn load_from(path: &Path) -> Option<Self> {
        let data = std::fs::read_to_string(path).ok()?;
        serde_json::from_str(&data).ok()
    }

    /// Load distance in world units for the saved render distance, with the
    /// chunk count limited to the menu range `4`–`32`.
    pub fn load_distance(&self) -> f32 {
        self.render_distance_chunks.clamp(4, 32) as f32 * RENDER_DISTANCE_STEP
    }

    /// Reads the four settings from the resources the settings menu edits.
    ///
    /// A missing resource contributes the default of its type. The render
    /// distance is the load distance in whole chunks, limited to `4`–`32`.
    pub fn capture(
        player: Option<&PlayerConfig>,
        world: Option<&WorldConfig>,
        sfx: Option<&SfxConfig>,
    ) -> Self {
        let default_player = PlayerConfig::default();
        let player = player.unwrap_or(&default_player);
        let load_distance = world.map_or(WorldConfig::default().load_distance, |w| w.load_distance);
        let volume = sfx.map_or(SfxConfig::default().volume, |s| s.volume);
        Self {
            fov_degrees: player.fov_degrees,
            sfx_volume: volume,
            render_distance_chunks: ((load_distance / RENDER_DISTANCE_STEP).round() as i64)
                .clamp(4, 32) as u32,
            sensitivity_pct: ((player.sensitivity * 100.0).round() as i64).clamp(10, 100) as u32,
        }
    }

    /// Writes these settings to the resources the settings menu edits.
    ///
    /// Every value is limited to the range documented on its field first; a
    /// field of view or volume that is not a finite number is skipped.
    ///
    /// The render distance is written to [`WorldConfig`] and [`ChunkManager`]
    /// only when it differs from the load distance already configured. The
    /// unload distance then becomes the load distance plus
    /// [`RENDER_DISTANCE_UNLOAD_MARGIN`]. A saved value equal to the
    /// configured one leaves a custom unload distance as it is.
    pub fn apply(
        &self,
        player: Option<&mut PlayerConfig>,
        world: Option<&mut WorldConfig>,
        manager: Option<&mut ChunkManager>,
        sfx: Option<&mut SfxConfig>,
    ) {
        if let Some(player) = player {
            if self.fov_degrees.is_finite() {
                player.fov_degrees = self.fov_degrees.clamp(50.0, 120.0);
            }
            player.sensitivity = self.sensitivity_pct.clamp(10, 100) as f32 / 100.0;
        }
        if let Some(sfx) = sfx
            && self.sfx_volume.is_finite()
        {
            sfx.volume = self.sfx_volume.clamp(0.0, 1.0);
        }

        let load = self.load_distance();
        let unload = load + RENDER_DISTANCE_UNLOAD_MARGIN;
        let configured = match (&world, &manager) {
            (Some(world), _) => Some(world.load_distance),
            (None, Some(manager)) => Some(manager.load_distance),
            (None, None) => None,
        };
        if configured == Some(load) {
            return;
        }
        if let Some(world) = world {
            world.load_distance = load;
            world.unload_distance = unload;
        }
        if let Some(manager) = manager {
            manager.load_distance = load;
            manager.unload_distance = unload;
        }
    }
}

fn settings_path(world_name: &str) -> PathBuf {
    PathBuf::from(format!("worlds/{world_name}/settings.json"))
}

// ─── SettingsPlugin ───────────────────────────────────────────────────────────

/// The file [`SettingsPlugin`] reads at startup and writes on
/// [`SaveSettingsRequest`].
///
/// [`SettingsPlugin::with_world`] inserts it as
/// `worlds/{world_name}/settings.json`. Replace the resource to keep the file
/// somewhere else.
#[derive(Resource, Debug, Clone, PartialEq, Eq)]
pub struct SettingsFile {
    /// Path of the settings file.
    pub path: PathBuf,
}

impl SettingsFile {
    /// The settings file of a world: `worlds/{world_name}/settings.json`.
    pub fn for_world(world_name: &str) -> Self {
        Self {
            path: settings_path(world_name),
        }
    }
}

/// System sets of [`SettingsPlugin`].
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SettingsSystems {
    /// `Startup`: the saved file is applied to the configuration resources.
    /// Runs after the `world.toml` load of `WorldConfigPlugin` and before
    /// [`spawn_player`](crate::player::spawn_player). Order your own startup
    /// systems after this set when they read the configured values.
    Load,
    /// `Update`: the file is written when a [`SaveSettingsRequest`] arrives.
    Save,
}

/// Loads and saves the settings of the pause menu for one world.
///
/// The settings menu of [`PauseMenuPlugin`](crate::ui::PauseMenuPlugin) edits
/// four values and writes [`SaveSettingsRequest`] when the player leaves it.
/// This plugin is the other half: it applies the saved file at startup and
/// writes the file on that request. The game only names the world.
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
///
/// App::new()
///     .add_plugins(PauseMenuPlugin)
///     .add_plugins(SettingsPlugin::with_world("my_world"));
/// ```
///
/// # At startup
///
/// [`load_settings_system`] reads the file and writes its values to
/// [`PlayerConfig`], [`WorldConfig`], [`ChunkManager`] and [`SfxConfig`], each
/// only when the resource exists. See [`PersistedSettings::apply`] for the
/// limits and for how the unload distance is treated. A missing or unreadable
/// file leaves every configured value untouched.
///
/// # On `SaveSettingsRequest`
///
/// [`save_settings_system`] writes [`PersistedSettings::capture`] of the
/// current resources to the file. Any system may write the request; it does
/// not have to come from the pause menu.
///
/// The plugin is opt-in and no bundle adds it. It does not add the pause
/// menu, and it works without it.
pub struct SettingsPlugin {
    world_name: String,
}

impl SettingsPlugin {
    /// Settings stored in `worlds/{world_name}/settings.json`.
    pub fn with_world(world_name: impl Into<String>) -> Self {
        Self {
            world_name: world_name.into(),
        }
    }
}

impl Plugin for SettingsPlugin {
    fn build(&self, app: &mut App) {
        app.insert_resource(SettingsFile::for_world(&self.world_name));
        // The pause menu registers it too; this plugin must run without it.
        app.add_message::<SaveSettingsRequest>();
        app.add_systems(
            Startup,
            load_settings_system
                .in_set(SettingsSystems::Load)
                .after(crate::world::config::load_world_config)
                .before(crate::player::spawn_player),
        );
        app.add_systems(Update, save_settings_system.in_set(SettingsSystems::Save));
    }
}

/// Applies the saved settings file to the configuration resources.
///
/// Added by [`SettingsPlugin`] in `Startup`, in [`SettingsSystems::Load`].
pub fn load_settings_system(
    file: Res<SettingsFile>,
    mut player: Option<ResMut<PlayerConfig>>,
    mut world: Option<ResMut<WorldConfig>>,
    mut manager: Option<ResMut<ChunkManager>>,
    mut sfx: Option<ResMut<SfxConfig>>,
) {
    let Some(saved) = PersistedSettings::load_from(&file.path) else {
        return;
    };
    saved.apply(
        player.as_deref_mut(),
        world.as_deref_mut(),
        manager.as_deref_mut(),
        sfx.as_deref_mut(),
    );
}

/// Writes the settings file when a [`SaveSettingsRequest`] arrives.
///
/// Added by [`SettingsPlugin`] in `Update`, in [`SettingsSystems::Save`].
/// Several requests in one frame write the file once.
pub fn save_settings_system(
    mut requests: MessageReader<SaveSettingsRequest>,
    file: Res<SettingsFile>,
    player: Option<Res<PlayerConfig>>,
    world: Option<Res<WorldConfig>>,
    sfx: Option<Res<SfxConfig>>,
) {
    if requests.read().count() == 0 {
        return;
    }
    PersistedSettings::capture(player.as_deref(), world.as_deref(), sfx.as_deref())
        .save_to(&file.path);
}

#[cfg(test)]
mod tests {
    use super::*;

    fn saved() -> PersistedSettings {
        PersistedSettings {
            fov_degrees: 75.0,
            sfx_volume: 0.4,
            render_distance_chunks: 12,
            sensitivity_pct: 60,
        }
    }

    /// App with the four resources at their defaults and the plugin pointed
    /// at a file inside `dir`.
    fn settings_app(dir: &Path) -> App {
        let mut app = App::new();
        app.add_plugins(MinimalPlugins)
            .init_resource::<PlayerConfig>()
            .init_resource::<WorldConfig>()
            .init_resource::<ChunkManager>()
            .init_resource::<SfxConfig>()
            .add_plugins(SettingsPlugin::with_world("unused"))
            .insert_resource(SettingsFile {
                path: dir.join("settings.json"),
            });
        app
    }

    #[test]
    fn the_file_of_a_world_is_inside_its_world_directory() {
        assert_eq!(
            SettingsFile::for_world("alpha").path,
            PathBuf::from("worlds/alpha/settings.json")
        );
    }

    #[test]
    fn a_saved_file_is_applied_at_startup() {
        let dir = tempfile::tempdir().unwrap();
        saved().save_to(&dir.path().join("settings.json"));
        let mut app = settings_app(dir.path());

        app.update();

        let player = app.world().resource::<PlayerConfig>();
        assert_eq!(player.fov_degrees, 75.0);
        assert!((player.sensitivity - 0.6).abs() < 1e-6);
        assert_eq!(app.world().resource::<SfxConfig>().volume, 0.4);
        let world = app.world().resource::<WorldConfig>();
        assert_eq!(world.load_distance, 192.0);
        assert_eq!(world.unload_distance, 224.0);
        let manager = app.world().resource::<ChunkManager>();
        assert_eq!(manager.load_distance, 192.0);
        assert_eq!(manager.unload_distance, 224.0);
    }

    #[test]
    fn a_missing_file_leaves_the_configuration_untouched() {
        let dir = tempfile::tempdir().unwrap();
        let mut app = settings_app(dir.path());
        app.world_mut().resource_mut::<PlayerConfig>().fov_degrees = 101.0;

        app.update();

        assert_eq!(app.world().resource::<PlayerConfig>().fov_degrees, 101.0);
        let defaults = WorldConfig::default();
        let world = app.world().resource::<WorldConfig>();
        assert_eq!(world.load_distance, defaults.load_distance);
        assert_eq!(world.unload_distance, defaults.unload_distance);
    }

    #[test]
    fn an_unreadable_file_leaves_the_configuration_untouched() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("settings.json"), b"{ not json").unwrap();
        let mut app = settings_app(dir.path());

        app.update();

        assert_eq!(
            app.world().resource::<PlayerConfig>().fov_degrees,
            PlayerConfig::default().fov_degrees
        );
    }

    #[test]
    fn values_outside_the_menu_ranges_are_limited() {
        let mut player = PlayerConfig::default();
        let mut sfx = SfxConfig::default();
        let mut world = WorldConfig::default();
        PersistedSettings {
            fov_degrees: 500.0,
            sfx_volume: -3.0,
            render_distance_chunks: 1000,
            sensitivity_pct: 0,
        }
        .apply(Some(&mut player), Some(&mut world), None, Some(&mut sfx));

        assert_eq!(player.fov_degrees, 120.0);
        assert!((player.sensitivity - 0.1).abs() < 1e-6);
        assert_eq!(sfx.volume, 0.0);
        assert_eq!(world.load_distance, 32.0 * RENDER_DISTANCE_STEP);
    }

    #[test]
    fn values_that_are_not_numbers_are_skipped() {
        let mut player = PlayerConfig::default();
        let mut sfx = SfxConfig::default();
        PersistedSettings {
            fov_degrees: f32::NAN,
            sfx_volume: f32::INFINITY,
            ..saved()
        }
        .apply(Some(&mut player), None, None, Some(&mut sfx));

        assert_eq!(player.fov_degrees, PlayerConfig::default().fov_degrees);
        assert_eq!(sfx.volume, SfxConfig::default().volume);
    }

    #[test]
    fn a_render_distance_equal_to_the_configured_one_keeps_the_unload_distance() {
        let mut world = WorldConfig {
            load_distance: 192.0,
            unload_distance: 400.0,
            ..default()
        };
        let mut manager = ChunkManager::new(192.0, 400.0);

        saved().apply(None, Some(&mut world), Some(&mut manager), None);

        assert_eq!(world.unload_distance, 400.0);
        assert_eq!(manager.unload_distance, 400.0);
    }

    #[test]
    fn a_save_request_writes_the_current_values() {
        let dir = tempfile::tempdir().unwrap();
        let mut app = settings_app(dir.path());
        app.update();
        assert!(!dir.path().join("settings.json").exists());

        {
            let world = app.world_mut();
            world.resource_mut::<PlayerConfig>().fov_degrees = 85.0;
            world.resource_mut::<PlayerConfig>().sensitivity = 0.35;
            world.resource_mut::<SfxConfig>().volume = 0.7;
            world.resource_mut::<WorldConfig>().load_distance = 20.0 * RENDER_DISTANCE_STEP;
            world.write_message(SaveSettingsRequest);
        }
        app.update();

        let written = PersistedSettings::load_from(&dir.path().join("settings.json")).unwrap();
        assert_eq!(written.fov_degrees, 85.0);
        assert_eq!(written.sfx_volume, 0.7);
        assert_eq!(written.render_distance_chunks, 20);
        assert_eq!(written.sensitivity_pct, 35);
    }

    #[test]
    fn what_is_saved_is_what_the_next_start_loads() {
        let dir = tempfile::tempdir().unwrap();
        let mut first = settings_app(dir.path());
        first.update();
        first.world_mut().resource_mut::<PlayerConfig>().fov_degrees = 65.0;
        first.world_mut().write_message(SaveSettingsRequest);
        first.update();

        let mut second = settings_app(dir.path());
        second.update();

        assert_eq!(second.world().resource::<PlayerConfig>().fov_degrees, 65.0);
    }

    #[test]
    fn the_plugin_runs_without_the_pause_menu_and_without_the_resources() {
        let dir = tempfile::tempdir().unwrap();
        saved().save_to(&dir.path().join("settings.json"));
        let mut app = App::new();
        app.add_plugins(MinimalPlugins)
            .add_plugins(SettingsPlugin::with_world("unused"))
            .insert_resource(SettingsFile {
                path: dir.path().join("settings.json"),
            });

        app.update();
        app.world_mut().write_message(SaveSettingsRequest);
        app.update();
    }

    #[test]
    fn the_saved_field_of_view_reaches_the_spawned_camera() {
        use crate::player::{Player, PlayerHealth, spawn_player};
        let dir = tempfile::tempdir().unwrap();
        saved().save_to(&dir.path().join("settings.json"));
        let mut app = settings_app(dir.path());
        app.init_resource::<PlayerHealth>()
            .add_systems(Startup, spawn_player);

        app.update();

        let mut cameras = app
            .world_mut()
            .query_filtered::<&Projection, With<Player>>();
        let Projection::Perspective(perspective) = cameras.single(app.world()).unwrap() else {
            panic!("the player camera is perspective");
        };
        assert!((perspective.fov.to_degrees() - 75.0).abs() < 1e-3);
    }
}