1use std::path::{Path, PathBuf};
33
34use bevy::prelude::*;
35use serde::{Deserialize, Serialize};
36
37use crate::audio::SfxConfig;
38use crate::player::PlayerConfig;
39use crate::ui::SaveSettingsRequest;
40use crate::world::{ChunkManager, WorldConfig};
41
42pub const RENDER_DISTANCE_STEP: f32 = 16.0;
45
46pub const RENDER_DISTANCE_UNLOAD_MARGIN: f32 = 32.0;
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct PersistedSettings {
63 pub fov_degrees: f32,
65 pub sfx_volume: f32,
67 pub render_distance_chunks: u32,
69 pub sensitivity_pct: u32,
76}
77
78impl PersistedSettings {
79 pub fn save(&self, world_name: &str) {
84 self.save_to(&settings_path(world_name));
85 }
86
87 pub fn load(world_name: &str) -> Option<Self> {
92 Self::load_from(&settings_path(world_name))
93 }
94
95 pub fn save_to(&self, path: &Path) {
100 if let Some(dir) = path.parent() {
101 let _ = std::fs::create_dir_all(dir);
102 }
103 if let Ok(json) = serde_json::to_string_pretty(self) {
104 let _ = std::fs::write(path, json);
105 }
106 }
107
108 pub fn load_from(path: &Path) -> Option<Self> {
112 let data = std::fs::read_to_string(path).ok()?;
113 serde_json::from_str(&data).ok()
114 }
115
116 pub fn load_distance(&self) -> f32 {
119 self.render_distance_chunks.clamp(4, 32) as f32 * RENDER_DISTANCE_STEP
120 }
121
122 pub fn capture(
127 player: Option<&PlayerConfig>,
128 world: Option<&WorldConfig>,
129 sfx: Option<&SfxConfig>,
130 ) -> Self {
131 let default_player = PlayerConfig::default();
132 let player = player.unwrap_or(&default_player);
133 let load_distance = world.map_or(WorldConfig::default().load_distance, |w| w.load_distance);
134 let volume = sfx.map_or(SfxConfig::default().volume, |s| s.volume);
135 Self {
136 fov_degrees: player.fov_degrees,
137 sfx_volume: volume,
138 render_distance_chunks: ((load_distance / RENDER_DISTANCE_STEP).round() as i64)
139 .clamp(4, 32) as u32,
140 sensitivity_pct: ((player.sensitivity * 100.0).round() as i64).clamp(10, 100) as u32,
141 }
142 }
143
144 pub fn apply(
155 &self,
156 player: Option<&mut PlayerConfig>,
157 world: Option<&mut WorldConfig>,
158 manager: Option<&mut ChunkManager>,
159 sfx: Option<&mut SfxConfig>,
160 ) {
161 if let Some(player) = player {
162 if self.fov_degrees.is_finite() {
163 player.fov_degrees = self.fov_degrees.clamp(50.0, 120.0);
164 }
165 player.sensitivity = self.sensitivity_pct.clamp(10, 100) as f32 / 100.0;
166 }
167 if let Some(sfx) = sfx
168 && self.sfx_volume.is_finite()
169 {
170 sfx.volume = self.sfx_volume.clamp(0.0, 1.0);
171 }
172
173 let load = self.load_distance();
174 let unload = load + RENDER_DISTANCE_UNLOAD_MARGIN;
175 let configured = match (&world, &manager) {
176 (Some(world), _) => Some(world.load_distance),
177 (None, Some(manager)) => Some(manager.load_distance),
178 (None, None) => None,
179 };
180 if configured == Some(load) {
181 return;
182 }
183 if let Some(world) = world {
184 world.load_distance = load;
185 world.unload_distance = unload;
186 }
187 if let Some(manager) = manager {
188 manager.load_distance = load;
189 manager.unload_distance = unload;
190 }
191 }
192}
193
194fn settings_path(world_name: &str) -> PathBuf {
195 PathBuf::from(format!("worlds/{world_name}/settings.json"))
196}
197
198#[derive(Resource, Debug, Clone, PartialEq, Eq)]
207pub struct SettingsFile {
208 pub path: PathBuf,
210}
211
212impl SettingsFile {
213 pub fn for_world(world_name: &str) -> Self {
215 Self {
216 path: settings_path(world_name),
217 }
218 }
219}
220
221#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
223pub enum SettingsSystems {
224 Load,
229 Save,
231}
232
233pub struct SettingsPlugin {
266 world_name: String,
267}
268
269impl SettingsPlugin {
270 pub fn with_world(world_name: impl Into<String>) -> Self {
272 Self {
273 world_name: world_name.into(),
274 }
275 }
276}
277
278impl Plugin for SettingsPlugin {
279 fn build(&self, app: &mut App) {
280 app.insert_resource(SettingsFile::for_world(&self.world_name));
281 app.add_message::<SaveSettingsRequest>();
283 app.add_systems(
284 Startup,
285 load_settings_system
286 .in_set(SettingsSystems::Load)
287 .after(crate::world::config::load_world_config)
288 .before(crate::player::spawn_player),
289 );
290 app.add_systems(Update, save_settings_system.in_set(SettingsSystems::Save));
291 }
292}
293
294pub fn load_settings_system(
298 file: Res<SettingsFile>,
299 mut player: Option<ResMut<PlayerConfig>>,
300 mut world: Option<ResMut<WorldConfig>>,
301 mut manager: Option<ResMut<ChunkManager>>,
302 mut sfx: Option<ResMut<SfxConfig>>,
303) {
304 let Some(saved) = PersistedSettings::load_from(&file.path) else {
305 return;
306 };
307 saved.apply(
308 player.as_deref_mut(),
309 world.as_deref_mut(),
310 manager.as_deref_mut(),
311 sfx.as_deref_mut(),
312 );
313}
314
315pub fn save_settings_system(
320 mut requests: MessageReader<SaveSettingsRequest>,
321 file: Res<SettingsFile>,
322 player: Option<Res<PlayerConfig>>,
323 world: Option<Res<WorldConfig>>,
324 sfx: Option<Res<SfxConfig>>,
325) {
326 if requests.read().count() == 0 {
327 return;
328 }
329 PersistedSettings::capture(player.as_deref(), world.as_deref(), sfx.as_deref())
330 .save_to(&file.path);
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336
337 fn saved() -> PersistedSettings {
338 PersistedSettings {
339 fov_degrees: 75.0,
340 sfx_volume: 0.4,
341 render_distance_chunks: 12,
342 sensitivity_pct: 60,
343 }
344 }
345
346 fn settings_app(dir: &Path) -> App {
349 let mut app = App::new();
350 app.add_plugins(MinimalPlugins)
351 .init_resource::<PlayerConfig>()
352 .init_resource::<WorldConfig>()
353 .init_resource::<ChunkManager>()
354 .init_resource::<SfxConfig>()
355 .add_plugins(SettingsPlugin::with_world("unused"))
356 .insert_resource(SettingsFile {
357 path: dir.join("settings.json"),
358 });
359 app
360 }
361
362 #[test]
363 fn the_file_of_a_world_is_inside_its_world_directory() {
364 assert_eq!(
365 SettingsFile::for_world("alpha").path,
366 PathBuf::from("worlds/alpha/settings.json")
367 );
368 }
369
370 #[test]
371 fn a_saved_file_is_applied_at_startup() {
372 let dir = tempfile::tempdir().unwrap();
373 saved().save_to(&dir.path().join("settings.json"));
374 let mut app = settings_app(dir.path());
375
376 app.update();
377
378 let player = app.world().resource::<PlayerConfig>();
379 assert_eq!(player.fov_degrees, 75.0);
380 assert!((player.sensitivity - 0.6).abs() < 1e-6);
381 assert_eq!(app.world().resource::<SfxConfig>().volume, 0.4);
382 let world = app.world().resource::<WorldConfig>();
383 assert_eq!(world.load_distance, 192.0);
384 assert_eq!(world.unload_distance, 224.0);
385 let manager = app.world().resource::<ChunkManager>();
386 assert_eq!(manager.load_distance, 192.0);
387 assert_eq!(manager.unload_distance, 224.0);
388 }
389
390 #[test]
391 fn a_missing_file_leaves_the_configuration_untouched() {
392 let dir = tempfile::tempdir().unwrap();
393 let mut app = settings_app(dir.path());
394 app.world_mut().resource_mut::<PlayerConfig>().fov_degrees = 101.0;
395
396 app.update();
397
398 assert_eq!(app.world().resource::<PlayerConfig>().fov_degrees, 101.0);
399 let defaults = WorldConfig::default();
400 let world = app.world().resource::<WorldConfig>();
401 assert_eq!(world.load_distance, defaults.load_distance);
402 assert_eq!(world.unload_distance, defaults.unload_distance);
403 }
404
405 #[test]
406 fn an_unreadable_file_leaves_the_configuration_untouched() {
407 let dir = tempfile::tempdir().unwrap();
408 std::fs::write(dir.path().join("settings.json"), b"{ not json").unwrap();
409 let mut app = settings_app(dir.path());
410
411 app.update();
412
413 assert_eq!(
414 app.world().resource::<PlayerConfig>().fov_degrees,
415 PlayerConfig::default().fov_degrees
416 );
417 }
418
419 #[test]
420 fn values_outside_the_menu_ranges_are_limited() {
421 let mut player = PlayerConfig::default();
422 let mut sfx = SfxConfig::default();
423 let mut world = WorldConfig::default();
424 PersistedSettings {
425 fov_degrees: 500.0,
426 sfx_volume: -3.0,
427 render_distance_chunks: 1000,
428 sensitivity_pct: 0,
429 }
430 .apply(Some(&mut player), Some(&mut world), None, Some(&mut sfx));
431
432 assert_eq!(player.fov_degrees, 120.0);
433 assert!((player.sensitivity - 0.1).abs() < 1e-6);
434 assert_eq!(sfx.volume, 0.0);
435 assert_eq!(world.load_distance, 32.0 * RENDER_DISTANCE_STEP);
436 }
437
438 #[test]
439 fn values_that_are_not_numbers_are_skipped() {
440 let mut player = PlayerConfig::default();
441 let mut sfx = SfxConfig::default();
442 PersistedSettings {
443 fov_degrees: f32::NAN,
444 sfx_volume: f32::INFINITY,
445 ..saved()
446 }
447 .apply(Some(&mut player), None, None, Some(&mut sfx));
448
449 assert_eq!(player.fov_degrees, PlayerConfig::default().fov_degrees);
450 assert_eq!(sfx.volume, SfxConfig::default().volume);
451 }
452
453 #[test]
454 fn a_render_distance_equal_to_the_configured_one_keeps_the_unload_distance() {
455 let mut world = WorldConfig {
456 load_distance: 192.0,
457 unload_distance: 400.0,
458 ..default()
459 };
460 let mut manager = ChunkManager::new(192.0, 400.0);
461
462 saved().apply(None, Some(&mut world), Some(&mut manager), None);
463
464 assert_eq!(world.unload_distance, 400.0);
465 assert_eq!(manager.unload_distance, 400.0);
466 }
467
468 #[test]
469 fn a_save_request_writes_the_current_values() {
470 let dir = tempfile::tempdir().unwrap();
471 let mut app = settings_app(dir.path());
472 app.update();
473 assert!(!dir.path().join("settings.json").exists());
474
475 {
476 let world = app.world_mut();
477 world.resource_mut::<PlayerConfig>().fov_degrees = 85.0;
478 world.resource_mut::<PlayerConfig>().sensitivity = 0.35;
479 world.resource_mut::<SfxConfig>().volume = 0.7;
480 world.resource_mut::<WorldConfig>().load_distance = 20.0 * RENDER_DISTANCE_STEP;
481 world.write_message(SaveSettingsRequest);
482 }
483 app.update();
484
485 let written = PersistedSettings::load_from(&dir.path().join("settings.json")).unwrap();
486 assert_eq!(written.fov_degrees, 85.0);
487 assert_eq!(written.sfx_volume, 0.7);
488 assert_eq!(written.render_distance_chunks, 20);
489 assert_eq!(written.sensitivity_pct, 35);
490 }
491
492 #[test]
493 fn what_is_saved_is_what_the_next_start_loads() {
494 let dir = tempfile::tempdir().unwrap();
495 let mut first = settings_app(dir.path());
496 first.update();
497 first.world_mut().resource_mut::<PlayerConfig>().fov_degrees = 65.0;
498 first.world_mut().write_message(SaveSettingsRequest);
499 first.update();
500
501 let mut second = settings_app(dir.path());
502 second.update();
503
504 assert_eq!(second.world().resource::<PlayerConfig>().fov_degrees, 65.0);
505 }
506
507 #[test]
508 fn the_plugin_runs_without_the_pause_menu_and_without_the_resources() {
509 let dir = tempfile::tempdir().unwrap();
510 saved().save_to(&dir.path().join("settings.json"));
511 let mut app = App::new();
512 app.add_plugins(MinimalPlugins)
513 .add_plugins(SettingsPlugin::with_world("unused"))
514 .insert_resource(SettingsFile {
515 path: dir.path().join("settings.json"),
516 });
517
518 app.update();
519 app.world_mut().write_message(SaveSettingsRequest);
520 app.update();
521 }
522
523 #[test]
524 fn the_saved_field_of_view_reaches_the_spawned_camera() {
525 use crate::player::{Player, PlayerHealth, spawn_player};
526 let dir = tempfile::tempdir().unwrap();
527 saved().save_to(&dir.path().join("settings.json"));
528 let mut app = settings_app(dir.path());
529 app.init_resource::<PlayerHealth>()
530 .add_systems(Startup, spawn_player);
531
532 app.update();
533
534 let mut cameras = app
535 .world_mut()
536 .query_filtered::<&Projection, With<Player>>();
537 let Projection::Perspective(perspective) = cameras.single(app.world()).unwrap() else {
538 panic!("the player camera is perspective");
539 };
540 assert!((perspective.fov.to_degrees() - 75.0).abs() < 1e-3);
541 }
542}