Skip to main content

voxel_framework/ui/
pause_menu.rs

1//! Optional pause menu with a settings submenu for FOV and SFX volume.
2//!
3//! This module implements a self-contained pause flow driven by the
4//! [`PauseMenuState`] state machine. Add [`PauseMenuPlugin`] to wire it up;
5//! then gate your own gameplay systems on [`PauseMenuState::Playing`] so they
6//! freeze automatically when the player pauses.
7//!
8//! # State machine
9//!
10//! ```text
11//!                  Escape
12//! ┌─────────┐ ──────────────► ┌────────┐
13//! │ Playing │                 │ Paused │ ◄─────────────────┐
14//! └─────────┘ ◄────────────── └────────┘                   │
15//!                Resume btn /       │ Settings btn          │
16//!                Escape             ▼                       │
17//!                             ┌──────────┐  ← Back btn     │
18//!                             │ Settings │ ────────────────►┘
19//!                             └──────────┘
20//! ```
21//!
22//! **Cursor management:** entering `Paused` releases the primary window's
23//! cursor (`CursorGrabMode::None`, visible). Returning to `Playing` re-locks
24//! it (`CursorGrabMode::Locked`, hidden) when the window is focused.
25//!
26//! This plugin does not capture the cursor on the first click or release it
27//! when the window loses focus. Add
28//! [`PlayerPlugin`](crate::player::PlayerPlugin), or
29//! [`player_cursor_system`](crate::player::player_cursor_system) on its own,
30//! for that: when this plugin is installed the cursor system leaves Escape to
31//! the pause menu, so the two work together.
32//!
33//! # Integration
34//!
35//! [`PlayerPlugin`](crate::player::PlayerPlugin) pauses with the menu on its
36//! own. Gate your other gameplay systems on [`PauseMenuState::Playing`]:
37//!
38//! ```rust,no_run
39//! use bevy::prelude::*;
40//! use voxel_framework::prelude::*;
41//! use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
42//!
43//! fn my_gameplay_system() {}
44//!
45//! App::new()
46//!     .add_plugins(DefaultPlugins)
47//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
48//!     .add_plugins(PauseMenuPlugin)
49//!     .add_plugins(PlayerPlugin::<DefaultVoxel>::new())
50//!     .add_systems(Update, my_gameplay_system.run_if(in_state(PauseMenuState::Playing)));
51//! ```
52
53use bevy::asset::embedded_asset;
54use bevy::prelude::*;
55
56use crate::audio::{SfxConfig, SfxEvent, SfxRequest};
57use crate::player::{Player, PlayerConfig};
58use crate::world::{ChunkManager, WorldConfig};
59
60/// Asset path of the NotoSans font embedded into the framework binary.
61///
62/// The `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin`
63/// (part of `AssetPlugin` / `DefaultPlugins`). The path format is
64/// `embedded://{crate_name}/{path relative to the crate's `src/` dir}`, where
65/// the crate name uses underscores. See [`PauseMenuPlugin`] for how this font
66/// becomes the default value of [`PauseMenuConfig::font`].
67pub const EMBEDDED_NOTO_SANS_PATH: &str = "embedded://voxel_framework/ui/NotoSans-Regular.ttf";
68
69/// Asset path of the NotoSansSymbols2 font embedded into the framework binary.
70///
71/// Used exclusively to render symbol glyphs (e.g. `◀`, `▶`) that are absent
72/// from the subset of NotoSans shipped at [`EMBEDDED_NOTO_SANS_PATH`]. The
73/// `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin` (part
74/// of `AssetPlugin` / `DefaultPlugins`).
75pub const EMBEDDED_NOTO_SYMBOLS_PATH: &str =
76    "embedded://voxel_framework/ui/NotoSansSymbols2-Regular.ttf";
77
78// ─── State ────────────────────────────────────────────────────────────────────
79
80/// Bevy state enum that drives the pause menu lifecycle.
81///
82/// [`PauseMenuPlugin`] registers this as a Bevy `State` and transitions between
83/// variants automatically. Your own systems should use `run_if(in_state(…))`
84/// to participate in the pause flow.
85///
86/// # Variant transitions
87///
88/// | From | Trigger | To |
89/// |------|---------|-----|
90/// | `Playing` | Escape key | `Paused` |
91/// | `Paused` | Resume button or Escape | `Playing` |
92/// | `Paused` | Settings button | `Settings` |
93/// | `Settings` | Back button | `Paused` |
94///
95/// # Gating gameplay systems
96///
97/// ```rust,no_run
98/// # use bevy::prelude::*;
99/// # use voxel_framework::ui::PauseMenuState;
100/// # fn my_gameplay_system() {}
101/// App::new()
102///     .add_systems(Update,
103///         my_gameplay_system.run_if(in_state(PauseMenuState::Playing)),
104///     );
105/// ```
106#[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default)]
107pub enum PauseMenuState {
108    /// The game is running normally. Player input is active and the pause
109    /// menu is not visible. This is the default starting state.
110    #[default]
111    Playing,
112    /// The game is paused. The pause menu overlay is displayed and gameplay
113    /// systems gated on `Playing` are inactive. The cursor is free.
114    Paused,
115    /// The settings submenu is open. The pause menu overlay is replaced by the
116    /// settings panel. FOV and SFX volume can be adjusted here.
117    Settings,
118}
119
120// ─── Styling constants ────────────────────────────────────────────────────────
121
122const BTN_NORMAL: Color = Color::srgb(0.15, 0.15, 0.20);
123const BTN_HOVERED: Color = Color::srgb(0.25, 0.25, 0.35);
124const BTN_PRESSED: Color = Color::srgb(0.35, 0.35, 0.50);
125const OVERLAY: Color = Color::srgba(0.0, 0.0, 0.0, 0.78);
126
127// ─── Markers ─────────────────────────────────────────────────────────────────
128
129#[derive(Component)]
130struct PauseMenuRoot;
131#[derive(Component)]
132struct SettingsMenuRoot;
133#[derive(Component)]
134struct FovLabel;
135#[derive(Component)]
136struct VolumeLabel;
137#[derive(Component)]
138struct RenderDistLabel;
139#[derive(Component)]
140struct SensitivityLabel;
141
142#[derive(Component)]
143enum PauseButton {
144    Resume,
145    Settings,
146    Quit,
147}
148
149#[derive(Component)]
150enum SettingsButton {
151    FovInc,
152    FovDec,
153    VolumeInc,
154    VolumeDec,
155    RenderDistInc,
156    RenderDistDec,
157    SensitivityInc,
158    SensitivityDec,
159    Back,
160}
161
162// ─── Config ───────────────────────────────────────────────────────────────────
163
164// ─── Messages ─────────────────────────────────────────────────────────────────
165
166/// Emitted when the player clicks Back in the Settings submenu.
167///
168/// The host game should listen for this message and persist the current
169/// settings (FOV, volume, render distance, sensitivity) to disk using
170/// [`crate::settings::PersistedSettings`].
171#[derive(Message, Debug, Clone)]
172pub struct SaveSettingsRequest;
173
174// ─── Config ───────────────────────────────────────────────────────────────────
175
176/// Visual configuration for [`PauseMenuPlugin`].
177///
178/// Insert this resource before adding [`PauseMenuPlugin`] to supply a custom
179/// font. If omitted, [`PauseMenuPlugin`] populates `font` with the framework's
180/// embedded [NotoSans](https://fonts.google.com/noto/specimen/Noto+Sans)
181/// regular TTF — a unicode-capable font that renders the settings submenu's
182/// arrow glyphs (`←`, `◀`, `▶`) without tofu.
183///
184/// # Example
185///
186/// ```rust,no_run
187/// use bevy::prelude::*;
188/// use voxel_framework::ui::PauseMenuConfig;
189///
190/// fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
191///     commands.insert_resource(PauseMenuConfig {
192///         font: asset_server.load("fonts/MyFont.ttf"),
193///         symbol_font: asset_server.load("fonts/MyFont.ttf"),
194///     });
195/// }
196/// ```
197#[derive(Resource, Clone)]
198pub struct PauseMenuConfig {
199    /// Font handle used for every text element in both the pause menu and the
200    /// settings submenu (title, button labels, slider values).
201    ///
202    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
203    /// replaces the default handle with the embedded NotoSans font during
204    /// `Startup` (see `EMBEDDED_NOTO_SANS_PATH`) so games inherit a legible
205    /// unicode-capable font without loading any asset themselves. To override,
206    /// insert [`PauseMenuConfig`] with a custom `font` handle before the menu is
207    /// first spawned.
208    pub font: Handle<Font>,
209    /// Font handle used for symbol-only glyphs that are absent from the main
210    /// [`font`](Self::font) subset — specifically the `◀` and `▶` triangle
211    /// glyphs used on the settings slider inc/dec buttons.
212    ///
213    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
214    /// replaces the default handle with the embedded NotoSansSymbols2 font
215    /// during `Startup` (see `EMBEDDED_NOTO_SYMBOLS_PATH`). To override,
216    /// insert [`PauseMenuConfig`] with a custom `symbol_font` handle before the
217    /// menu is first spawned.
218    pub symbol_font: Handle<Font>,
219}
220
221impl Default for PauseMenuConfig {
222    fn default() -> Self {
223        Self {
224            font: Handle::default(),
225            symbol_font: Handle::default(),
226        }
227    }
228}
229
230// ─── Plugin ───────────────────────────────────────────────────────────────────
231
232/// Plugin that adds a full-screen pause menu with a settings submenu.
233///
234/// Registers [`PauseMenuState`] and wires all transitions, UI spawning, and
235/// cursor management. The settings submenu exposes real-time controls for FOV
236/// (±5° per click, clamped to `50°`–`120°`) and SFX volume (±10% per click,
237/// clamped to `0%`–`100%`).
238///
239/// Handles cursor releasing and locking as part of the `Playing ↔ Paused`
240/// transition. First-click capture and focus-loss release come from
241/// [`player_cursor_system`](crate::player::player_cursor_system), which
242/// [`PlayerPlugin`](crate::player::PlayerPlugin) registers and which defers
243/// Escape to this plugin when both are present.
244///
245/// # Simple usage
246///
247/// ```rust,no_run
248/// use bevy::prelude::*;
249/// use voxel_framework::prelude::*;
250/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
251///
252/// App::new()
253///     .add_plugins(DefaultPlugins)
254///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
255///     .add_plugins(PauseMenuPlugin)
256///     .run();
257/// ```
258///
259/// # With hand-registered player systems
260///
261/// Include [`player_cursor_system`](crate::player::player_cursor_system) so the
262/// first click captures the cursor and focus loss releases it:
263///
264/// ```rust,no_run
265/// use bevy::prelude::*;
266/// use voxel_framework::prelude::*;
267/// use voxel_framework::player::{spawn_player, player_cursor_system, player_look,
268///     player_move, player_resolve_collision};
269/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
270///
271/// App::new()
272///     .add_plugins(DefaultPlugins)
273///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
274///     .add_plugins(PauseMenuPlugin)
275///     .add_systems(Startup, spawn_player)
276///     .add_systems(Update,
277///         (player_cursor_system, player_look, player_move::<DefaultVoxel>,
278///             player_resolve_collision::<DefaultVoxel>)
279///             .chain()
280///             .run_if(in_state(PauseMenuState::Playing)),
281///     );
282/// ```
283pub struct PauseMenuPlugin;
284
285impl Plugin for PauseMenuPlugin {
286    fn build(&self, app: &mut App) {
287        // Embed the NotoSans TTF into the framework binary. The resulting asset
288        // is reachable from any `AssetServer::load(...)` call via the
289        // `embedded://` scheme — see [`EMBEDDED_NOTO_SANS_PATH`].
290        embedded_asset!(app, "NotoSans-Regular.ttf");
291        embedded_asset!(app, "NotoSansSymbols2-Regular.ttf");
292
293        app.init_resource::<PauseMenuConfig>();
294        app.init_state::<PauseMenuState>();
295        app.add_message::<SaveSettingsRequest>();
296
297        // Populate `PauseMenuConfig::font` with the embedded NotoSans handle
298        // when the user hasn't supplied their own font. Runs once on `Startup`,
299        // which fires before any `OnEnter(Paused)` transition can spawn the
300        // menu, so the handle is always ready by the time the menu is built.
301        app.add_systems(Startup, load_default_font);
302
303        // Playing — toggle on Escape
304        app.add_systems(
305            Update,
306            toggle_pause.run_if(in_state(PauseMenuState::Playing)),
307        );
308
309        // Paused
310        app.add_systems(
311            OnEnter(PauseMenuState::Paused),
312            (spawn_pause_menu, release_cursor),
313        );
314        app.add_systems(OnExit(PauseMenuState::Paused), despawn_pause_menu);
315        app.add_systems(
316            Update,
317            (handle_pause_buttons, escape_to_resume).run_if(in_state(PauseMenuState::Paused)),
318        );
319
320        // Settings
321        app.add_systems(OnEnter(PauseMenuState::Settings), spawn_settings_menu);
322        app.add_systems(OnExit(PauseMenuState::Settings), despawn_settings_menu);
323        app.add_systems(
324            Update,
325            handle_settings_buttons.run_if(in_state(PauseMenuState::Settings)),
326        );
327    }
328}
329
330// ─── Default font loader ──────────────────────────────────────────────────────
331
332/// Populates [`PauseMenuConfig::font`] with the embedded NotoSans font on
333/// startup if the game has not supplied a custom font.
334///
335/// `Default` can't access the [`AssetServer`], so we use a startup sentinel:
336/// when `font == Handle::default()` (the weak, uninitialised handle produced
337/// by [`PauseMenuConfig::default()`]), we load the embedded font and overwrite
338/// the field. Games that insert their own [`PauseMenuConfig`] before this
339/// plugin — or before `Startup` runs — keep their custom handle untouched.
340fn load_default_font(mut cfg: ResMut<PauseMenuConfig>, asset_server: Res<AssetServer>) {
341    if cfg.font == Handle::default() {
342        cfg.font = asset_server.load(EMBEDDED_NOTO_SANS_PATH);
343    }
344    if cfg.symbol_font == Handle::default() {
345        cfg.symbol_font = asset_server.load(EMBEDDED_NOTO_SYMBOLS_PATH);
346    }
347}
348
349// ─── Cursor helpers ───────────────────────────────────────────────────────────
350
351/// Releases the cursor when entering [`PauseMenuState::Paused`].
352///
353/// Called via `OnEnter(Paused)`. Sets `CursorGrabMode::None` on the primary
354/// window and makes the cursor visible so the player can interact with the
355/// menu buttons.
356fn release_cursor(mut windows: PrimaryCursor) {
357    for (_, mut cursor) in &mut windows {
358        cursor.grab_mode = bevy::window::CursorGrabMode::None;
359        cursor.visible = true;
360    }
361}
362
363/// The primary window and its cursor options: the only cursor the pause menu
364/// manages.
365type PrimaryCursor<'w, 's> = Query<
366    'w,
367    's,
368    (&'static Window, &'static mut bevy::window::CursorOptions),
369    With<bevy::window::PrimaryWindow>,
370>;
371
372/// Re-locks the cursor when returning to [`PauseMenuState::Playing`].
373///
374/// Called as a plain function (not a system) from [`escape_to_resume`] and
375/// [`handle_pause_buttons`] so that cursor re-lock and state transition happen
376/// in the same frame without a one-frame gap.
377///
378/// An unfocused window is left alone: a window must be focused before its
379/// cursor is captured, and a click captures it later.
380fn lock_cursor(windows: &mut PrimaryCursor) {
381    for (window, mut cursor) in windows.iter_mut() {
382        if !window.focused {
383            continue;
384        }
385        cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
386        cursor.visible = false;
387    }
388}
389
390// ─── Toggle pause ─────────────────────────────────────────────────────────────
391
392/// Transitions from `Playing` → `Paused` when Escape is pressed.
393///
394/// Runs only in [`PauseMenuState::Playing`]. Also fires a
395/// [`SfxEvent::PauseOpen`] sound request.
396fn toggle_pause(
397    keys: Res<ButtonInput<KeyCode>>,
398    mut next: ResMut<NextState<PauseMenuState>>,
399    mut sfx: MessageWriter<SfxRequest>,
400) {
401    if keys.just_pressed(KeyCode::Escape) {
402        next.set(PauseMenuState::Paused);
403        sfx.write(SfxRequest {
404            event: SfxEvent::PauseOpen,
405            position: None,
406        });
407    }
408}
409
410/// Transitions from `Paused` → `Playing` when Escape is pressed.
411///
412/// Runs only in [`PauseMenuState::Paused`]. Re-locks the cursor via
413/// [`lock_cursor`] in the same frame and fires [`SfxEvent::PauseClose`].
414fn escape_to_resume(
415    keys: Res<ButtonInput<KeyCode>>,
416    mut next: ResMut<NextState<PauseMenuState>>,
417    mut windows: PrimaryCursor,
418    mut sfx: MessageWriter<SfxRequest>,
419) {
420    if keys.just_pressed(KeyCode::Escape) {
421        next.set(PauseMenuState::Playing);
422        lock_cursor(&mut windows);
423        sfx.write(SfxRequest {
424            event: SfxEvent::PauseClose,
425            position: None,
426        });
427    }
428}
429
430// ─── Spawn helpers ────────────────────────────────────────────────────────────
431
432fn spawn_btn<C: Component>(
433    parent: &mut ChildSpawnerCommands,
434    label: &str,
435    action: C,
436    width: f32,
437    height: f32,
438    font: Handle<Font>,
439) {
440    parent
441        .spawn((
442            action,
443            Button,
444            Node {
445                width: Val::Px(width),
446                height: Val::Px(height),
447                justify_content: JustifyContent::Center,
448                align_items: AlignItems::Center,
449                ..default()
450            },
451            BackgroundColor(BTN_NORMAL),
452        ))
453        .with_children(|b| {
454            b.spawn((
455                Text::new(label),
456                TextFont {
457                    font,
458                    font_size: 20.0,
459                    ..default()
460                },
461                TextColor(Color::WHITE),
462            ));
463        });
464}
465
466fn overlay_node() -> (Node, BackgroundColor) {
467    (
468        Node {
469            width: Val::Percent(100.0),
470            height: Val::Percent(100.0),
471            flex_direction: FlexDirection::Column,
472            justify_content: JustifyContent::Center,
473            align_items: AlignItems::Center,
474            row_gap: Val::Px(14.0),
475            ..default()
476        },
477        BackgroundColor(OVERLAY),
478    )
479}
480
481// ─── Pause menu ───────────────────────────────────────────────────────────────
482
483/// Spawns the pause menu overlay when entering [`PauseMenuState::Paused`].
484///
485/// Builds a full-screen semi-transparent overlay with three buttons: Resume,
486/// Settings, and Quit. Runs via `OnEnter(Paused)`.
487fn spawn_pause_menu(mut commands: Commands, config: Res<PauseMenuConfig>) {
488    let (node, bg) = overlay_node();
489    commands
490        .spawn((PauseMenuRoot, node, bg))
491        .with_children(|p| {
492            p.spawn((
493                Text::new("PAUSED"),
494                TextFont {
495                    font: config.font.clone(),
496                    font_size: 52.0,
497                    ..default()
498                },
499                TextColor(Color::WHITE),
500                Node {
501                    margin: UiRect::bottom(Val::Px(28.0)),
502                    ..default()
503                },
504            ));
505            spawn_btn(
506                p,
507                "Resume",
508                PauseButton::Resume,
509                280.0,
510                52.0,
511                config.font.clone(),
512            );
513            spawn_btn(
514                p,
515                "Settings",
516                PauseButton::Settings,
517                280.0,
518                52.0,
519                config.font.clone(),
520            );
521            spawn_btn(
522                p,
523                "Quit",
524                PauseButton::Quit,
525                280.0,
526                52.0,
527                config.font.clone(),
528            );
529        });
530}
531
532/// Despawns the pause menu overlay when leaving [`PauseMenuState::Paused`].
533///
534/// Runs via `OnExit(Paused)`, which fires for both `Paused → Playing` and
535/// `Paused → Settings` transitions.
536fn despawn_pause_menu(mut commands: Commands, q: Query<Entity, With<PauseMenuRoot>>) {
537    for e in &q {
538        commands.entity(e).despawn();
539    }
540}
541
542/// Handles hover/press styling and click actions for pause menu buttons.
543///
544/// Runs every frame in [`PauseMenuState::Paused`]. Updates button background
545/// colors on hover and press, then on `Pressed` dispatches: Resume → `Playing`
546/// (re-locks cursor), Settings → `Settings`, Quit → [`AppExit`].
547fn handle_pause_buttons(
548    mut q: Query<
549        (&Interaction, &mut BackgroundColor, &PauseButton),
550        (Changed<Interaction>, With<Button>),
551    >,
552    mut next: ResMut<NextState<PauseMenuState>>,
553    mut windows: PrimaryCursor,
554    mut app_exit: MessageWriter<AppExit>,
555    mut sfx: MessageWriter<SfxRequest>,
556) {
557    for (interaction, mut bg, action) in &mut q {
558        *bg = BackgroundColor(match interaction {
559            Interaction::Hovered => BTN_HOVERED,
560            Interaction::Pressed => BTN_PRESSED,
561            Interaction::None => BTN_NORMAL,
562        });
563        if *interaction != Interaction::Pressed {
564            continue;
565        }
566        match action {
567            PauseButton::Resume => {
568                next.set(PauseMenuState::Playing);
569                lock_cursor(&mut windows);
570                sfx.write(SfxRequest {
571                    event: SfxEvent::PauseClose,
572                    position: None,
573                });
574            }
575            PauseButton::Settings => next.set(PauseMenuState::Settings),
576            PauseButton::Quit => {
577                app_exit.write(AppExit::Success);
578            }
579        }
580    }
581}
582
583// ─── Settings menu ────────────────────────────────────────────────────────────
584
585/// Spawns the settings overlay when entering [`PauseMenuState::Settings`].
586///
587/// Reads the current FOV from the [`Camera3d`] projection, the current SFX
588/// volume from [`SfxConfig`], the render distance from [`WorldConfig`], and the
589/// mouse sensitivity from [`PlayerConfig`] to initialise the slider labels.
590/// Runs via `OnEnter(Settings)`.
591fn spawn_settings_menu(
592    mut commands: Commands,
593    sfx_config: Res<SfxConfig>,
594    world_config: Option<Res<WorldConfig>>,
595    player_config: Option<Res<PlayerConfig>>,
596    camera_q: Query<&Projection, With<Camera3d>>,
597    config: Res<PauseMenuConfig>,
598) {
599    let fov_deg = camera_q
600        .single()
601        .ok()
602        .and_then(|p| {
603            if let Projection::Perspective(pp) = p {
604                Some(pp.fov.to_degrees())
605            } else {
606                None
607            }
608        })
609        .unwrap_or(90.0);
610    let volume_pct = sfx_config.volume * 100.0;
611    let render_dist_chunks = world_config
612        .as_ref()
613        .map(|wc| ((wc.load_distance / 16.0).round() as i32).clamp(4, 32) as i32)
614        .unwrap_or(10);
615    // Round to nearest even
616    let render_dist_chunks = if render_dist_chunks % 2 == 0 {
617        render_dist_chunks
618    } else {
619        render_dist_chunks + 1
620    };
621    let sensitivity_pct = player_config
622        .as_ref()
623        .map(|pc| ((pc.sensitivity * 100.0).round() as i32).clamp(10, 100))
624        .unwrap_or(100);
625
626    let (node, bg) = overlay_node();
627    commands
628        .spawn((SettingsMenuRoot, node, bg))
629        .with_children(|p| {
630            p.spawn((
631                Text::new("SETTINGS"),
632                TextFont {
633                    font: config.font.clone(),
634                    font_size: 42.0,
635                    ..default()
636                },
637                TextColor(Color::WHITE),
638                Node {
639                    margin: UiRect::bottom(Val::Px(20.0)),
640                    ..default()
641                },
642            ));
643
644            spawn_slider_row(
645                p,
646                "Field of View",
647                format!("{fov_deg:.0}°"),
648                FovLabel,
649                SettingsButton::FovDec,
650                SettingsButton::FovInc,
651                config.font.clone(),
652                config.symbol_font.clone(),
653            );
654
655            spawn_slider_row(
656                p,
657                "SFX Volume",
658                format!("{volume_pct:.0}%"),
659                VolumeLabel,
660                SettingsButton::VolumeDec,
661                SettingsButton::VolumeInc,
662                config.font.clone(),
663                config.symbol_font.clone(),
664            );
665
666            spawn_slider_row(
667                p,
668                "Render Distance",
669                format!("{render_dist_chunks} chunks"),
670                RenderDistLabel,
671                SettingsButton::RenderDistDec,
672                SettingsButton::RenderDistInc,
673                config.font.clone(),
674                config.symbol_font.clone(),
675            );
676
677            spawn_slider_row(
678                p,
679                "Sensitivity",
680                format!("{sensitivity_pct:.0}%"),
681                SensitivityLabel,
682                SettingsButton::SensitivityDec,
683                SettingsButton::SensitivityInc,
684                config.font.clone(),
685                config.symbol_font.clone(),
686            );
687
688            p.spawn(Node {
689                margin: UiRect::top(Val::Px(20.0)),
690                ..default()
691            })
692            .with_children(|row| {
693                spawn_btn(
694                    row,
695                    "< Back",
696                    SettingsButton::Back,
697                    200.0,
698                    50.0,
699                    config.font.clone(),
700                );
701            });
702        });
703}
704
705fn spawn_slider_row<L: Component, D: Component, I: Component>(
706    parent: &mut ChildSpawnerCommands,
707    label: &str,
708    value: String,
709    value_marker: L,
710    dec: D,
711    inc: I,
712    font: Handle<Font>,
713    symbol_font: Handle<Font>,
714) {
715    parent
716        .spawn(Node {
717            flex_direction: FlexDirection::Row,
718            align_items: AlignItems::Center,
719            column_gap: Val::Px(12.0),
720            ..default()
721        })
722        .with_children(|row| {
723            row.spawn((
724                Text::new(label),
725                TextFont {
726                    font: font.clone(),
727                    font_size: 20.0,
728                    ..default()
729                },
730                TextColor(Color::srgb(0.8, 0.8, 0.8)),
731                Node {
732                    width: Val::Px(200.0),
733                    ..default()
734                },
735            ));
736            spawn_btn(row, "\u{25C0}", dec, 44.0, 44.0, symbol_font.clone());
737            row.spawn((
738                value_marker,
739                Text::new(value),
740                TextFont {
741                    font: font.clone(),
742                    font_size: 22.0,
743                    ..default()
744                },
745                TextColor(Color::WHITE),
746                Node {
747                    width: Val::Px(80.0),
748                    justify_content: JustifyContent::Center,
749                    ..default()
750                },
751            ));
752            spawn_btn(row, "\u{25B6}", inc, 44.0, 44.0, symbol_font);
753        });
754}
755
756/// Despawns the settings overlay when leaving [`PauseMenuState::Settings`].
757///
758/// Runs via `OnExit(Settings)`. The only exit transition is `Settings → Paused`
759/// via the Back button.
760fn despawn_settings_menu(mut commands: Commands, q: Query<Entity, With<SettingsMenuRoot>>) {
761    for e in &q {
762        commands.entity(e).despawn();
763    }
764}
765
766/// Handles hover/press styling and click actions for settings menu buttons.
767///
768/// Runs every frame in [`PauseMenuState::Settings`]. Adjusts values on press:
769/// - `FovInc` / `FovDec`: changes FOV by ±5° (clamped `50°`–`120°`) and updates
770///   [`FovLabel`] text and the [`Camera3d`] perspective projection.
771/// - `VolumeInc` / `VolumeDec`: changes [`SfxConfig::volume`] by ±0.1 (clamped
772///   `0.0`–`1.0`) and updates [`VolumeLabel`] text.
773/// - `RenderDistInc` / `RenderDistDec`: changes [`WorldConfig::load_distance`] by
774///   ±2 chunks (clamped `4`–`32`) and updates [`RenderDistLabel`] text and
775///   [`ChunkManager`] distances.
776/// - `SensitivityInc` / `SensitivityDec`: changes [`PlayerConfig::sensitivity`] by
777///   ±1% (clamped `10`–`100`), applies it to every live [`Player`] so mouse
778///   look changes immediately, and updates [`SensitivityLabel`] text.
779/// - `Back`: emits [`SaveSettingsRequest`] and transitions to [`PauseMenuState::Paused`].
780#[allow(clippy::too_many_arguments)]
781fn handle_settings_buttons(
782    mut q: Query<
783        (&Interaction, &mut BackgroundColor, &SettingsButton),
784        (Changed<Interaction>, With<Button>),
785    >,
786    mut sfx_config: ResMut<SfxConfig>,
787    mut world_config: Option<ResMut<WorldConfig>>,
788    mut chunk_manager: Option<ResMut<ChunkManager>>,
789    mut player_config: Option<ResMut<PlayerConfig>>,
790    mut next: ResMut<NextState<PauseMenuState>>,
791    mut fov_label: Query<
792        &mut Text,
793        (
794            With<FovLabel>,
795            Without<VolumeLabel>,
796            Without<RenderDistLabel>,
797            Without<SensitivityLabel>,
798        ),
799    >,
800    mut vol_label: Query<
801        &mut Text,
802        (
803            With<VolumeLabel>,
804            Without<FovLabel>,
805            Without<RenderDistLabel>,
806            Without<SensitivityLabel>,
807        ),
808    >,
809    mut rdist_label: Query<
810        &mut Text,
811        (
812            With<RenderDistLabel>,
813            Without<FovLabel>,
814            Without<VolumeLabel>,
815            Without<SensitivityLabel>,
816        ),
817    >,
818    mut sens_label: Query<
819        &mut Text,
820        (
821            With<SensitivityLabel>,
822            Without<FovLabel>,
823            Without<VolumeLabel>,
824            Without<RenderDistLabel>,
825        ),
826    >,
827    mut camera_q: Query<&mut Projection, With<Camera3d>>,
828    mut players: Query<&mut Player>,
829    mut save_writer: MessageWriter<SaveSettingsRequest>,
830) {
831    for (interaction, mut bg, action) in &mut q {
832        *bg = BackgroundColor(match interaction {
833            Interaction::Hovered => BTN_HOVERED,
834            Interaction::Pressed => BTN_PRESSED,
835            Interaction::None => BTN_NORMAL,
836        });
837        if *interaction != Interaction::Pressed {
838            continue;
839        }
840
841        match action {
842            SettingsButton::FovInc | SettingsButton::FovDec => {
843                if let Ok(mut proj) = camera_q.single_mut() {
844                    if let Projection::Perspective(ref mut pp) = *proj {
845                        let new_fov = step_fov_degrees(
846                            pp.fov.to_degrees(),
847                            matches!(action, SettingsButton::FovInc),
848                        );
849                        pp.fov = new_fov.to_radians();
850                        if let Ok(mut t) = fov_label.single_mut() {
851                            **t = format!("{new_fov:.0}°");
852                        }
853                    }
854                }
855            }
856            SettingsButton::VolumeInc | SettingsButton::VolumeDec => {
857                sfx_config.volume = step_volume(
858                    sfx_config.volume,
859                    matches!(action, SettingsButton::VolumeInc),
860                );
861                let pct = sfx_config.volume * 100.0;
862                if let Ok(mut t) = vol_label.single_mut() {
863                    **t = format!("{pct:.0}%");
864                }
865            }
866            SettingsButton::RenderDistInc | SettingsButton::RenderDistDec => {
867                if let Some(ref mut wc) = world_config {
868                    let new_chunks = step_render_distance_chunks(
869                        wc.load_distance,
870                        matches!(action, SettingsButton::RenderDistInc),
871                    );
872                    wc.load_distance = new_chunks as f32 * 16.0;
873                    wc.unload_distance = wc.load_distance + 32.0;
874                    if let Some(ref mut cm) = chunk_manager {
875                        cm.load_distance = wc.load_distance;
876                        cm.unload_distance = wc.unload_distance;
877                    }
878                    if let Ok(mut t) = rdist_label.single_mut() {
879                        **t = format!("{new_chunks} chunks");
880                    }
881                }
882            }
883            SettingsButton::SensitivityInc | SettingsButton::SensitivityDec => {
884                if let Some(ref mut pc) = player_config {
885                    let new_pct = step_sensitivity_pct(
886                        pc.sensitivity,
887                        matches!(action, SettingsButton::SensitivityInc),
888                    );
889                    pc.sensitivity = new_pct as f32 / 100.0;
890                    // `Player::sensitivity` is copied from the config at spawn
891                    // and is what mouse look reads, so update live players too;
892                    // otherwise the change only applied after a restart.
893                    for mut player in &mut players {
894                        player.sensitivity = pc.sensitivity;
895                    }
896                    if let Ok(mut t) = sens_label.single_mut() {
897                        **t = format!("{new_pct:.0}%");
898                    }
899                }
900            }
901            SettingsButton::Back => {
902                save_writer.write(SaveSettingsRequest);
903                next.set(PauseMenuState::Paused);
904            }
905        }
906    }
907}
908
909// ─── Slider steps ─────────────────────────────────────────────────────────────
910//
911// Pure helpers behind the settings buttons, kept separate from the Bevy system
912// so the rules (step size, limits, rounding) are unit-testable.
913
914/// Next field of view in degrees: ±5°, clamped to `50`–`120`.
915fn step_fov_degrees(current_deg: f32, increase: bool) -> f32 {
916    let delta = if increase { 5.0 } else { -5.0 };
917    (current_deg + delta).clamp(50.0, 120.0)
918}
919
920/// Next SFX volume: ±0.1, clamped to `0.0`–`1.0`.
921fn step_volume(current: f32, increase: bool) -> f32 {
922    let delta = if increase { 0.1 } else { -0.1 };
923    (current + delta).clamp(0.0, 1.0)
924}
925
926/// Next render distance in chunks: the current `load_distance` is rounded to
927/// whole chunks, clamped to `4`–`32` and bumped to even, then moved ±2 chunks
928/// and clamped again.
929fn step_render_distance_chunks(load_distance: f32, increase: bool) -> i32 {
930    let current = ((load_distance / 16.0).round() as i32).clamp(4, 32);
931    let current = if current % 2 == 0 {
932        current
933    } else {
934        current + 1
935    };
936    let delta = if increase { 2 } else { -2 };
937    (current + delta).clamp(4, 32)
938}
939
940/// Next mouse sensitivity in percent: ±1%, clamped to `10`–`100`.
941fn step_sensitivity_pct(sensitivity: f32, increase: bool) -> i32 {
942    let current_pct = (sensitivity * 100.0).round() as i32;
943    let delta = if increase { 1 } else { -1 };
944    (current_pct + delta).clamp(10, 100)
945}
946
947// ─── Tests ────────────────────────────────────────────────────────────────────
948
949#[cfg(test)]
950mod tests {
951    use super::*;
952    use bevy::ecs::message::Messages;
953    use bevy::ecs::system::RunSystemOnce;
954
955    use crate::player::player_cursor_system;
956    use bevy::state::app::StatesPlugin;
957    use bevy::window::{CursorGrabMode, CursorOptions, PrimaryWindow};
958
959    /// Headless app with the pause transitions wired as [`PauseMenuPlugin`]
960    /// does (minus UI and assets) plus the player's cursor system, and a
961    /// focused primary window with a free cursor.
962    fn pause_cursor_app() -> (App, Entity) {
963        let mut app = App::new();
964        app.add_plugins(StatesPlugin);
965        app.init_state::<PauseMenuState>();
966        app.add_message::<SfxRequest>();
967        app.init_resource::<ButtonInput<KeyCode>>();
968        app.init_resource::<ButtonInput<MouseButton>>();
969        app.add_systems(
970            Update,
971            (
972                toggle_pause.run_if(in_state(PauseMenuState::Playing)),
973                escape_to_resume.run_if(in_state(PauseMenuState::Paused)),
974                player_cursor_system.run_if(in_state(PauseMenuState::Playing)),
975            ),
976        );
977        app.add_systems(OnEnter(PauseMenuState::Paused), release_cursor);
978        let window = app
979            .world_mut()
980            .spawn((
981                Window {
982                    focused: true,
983                    ..default()
984                },
985                PrimaryWindow,
986            ))
987            .id();
988        (app, window)
989    }
990
991    /// Presses `key` for one frame, then runs a second frame so the state
992    /// transition it requested is applied.
993    fn tap(app: &mut App, key: KeyCode) {
994        app.world_mut()
995            .resource_mut::<ButtonInput<KeyCode>>()
996            .press(key);
997        app.update();
998        app.world_mut()
999            .resource_mut::<ButtonInput<KeyCode>>()
1000            .reset_all();
1001        app.update();
1002    }
1003
1004    fn click(app: &mut App) {
1005        app.world_mut()
1006            .resource_mut::<ButtonInput<MouseButton>>()
1007            .press(MouseButton::Left);
1008        app.update();
1009        app.world_mut()
1010            .resource_mut::<ButtonInput<MouseButton>>()
1011            .reset_all();
1012    }
1013
1014    fn pause_state(app: &App) -> PauseMenuState {
1015        app.world()
1016            .resource::<State<PauseMenuState>>()
1017            .get()
1018            .clone()
1019    }
1020
1021    fn grab(app: &App, window: Entity) -> CursorGrabMode {
1022        app.world()
1023            .get::<CursorOptions>(window)
1024            .expect("window should still exist")
1025            .grab_mode
1026    }
1027
1028    #[test]
1029    fn cursor_follows_pause_focus_and_click_with_the_player_cursor_system() {
1030        let (mut app, window) = pause_cursor_app();
1031
1032        // Escape before the first click opens the menu; it must not close the window.
1033        tap(&mut app, KeyCode::Escape);
1034        assert_eq!(pause_state(&app), PauseMenuState::Paused);
1035        assert_eq!(grab(&app, window), CursorGrabMode::None);
1036
1037        // Escape again resumes with the cursor captured.
1038        tap(&mut app, KeyCode::Escape);
1039        assert_eq!(pause_state(&app), PauseMenuState::Playing);
1040        assert_eq!(grab(&app, window), CursorGrabMode::Locked);
1041
1042        // Losing focus releases the cursor without pausing.
1043        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
1044        app.update();
1045        assert_eq!(grab(&app, window), CursorGrabMode::None);
1046        assert_eq!(pause_state(&app), PauseMenuState::Playing);
1047
1048        // Regaining focus alone does not recapture; a click does.
1049        app.world_mut().get_mut::<Window>(window).unwrap().focused = true;
1050        app.update();
1051        assert_eq!(grab(&app, window), CursorGrabMode::None);
1052        click(&mut app);
1053        assert_eq!(grab(&app, window), CursorGrabMode::Locked);
1054
1055        // Pausing from a captured cursor releases it for the menu.
1056        tap(&mut app, KeyCode::Escape);
1057        assert_eq!(pause_state(&app), PauseMenuState::Paused);
1058        assert_eq!(grab(&app, window), CursorGrabMode::None);
1059    }
1060
1061    #[test]
1062    fn resuming_does_not_capture_an_unfocused_window() {
1063        let (mut app, window) = pause_cursor_app();
1064        tap(&mut app, KeyCode::Escape);
1065        assert_eq!(pause_state(&app), PauseMenuState::Paused);
1066        app.world_mut().get_mut::<Window>(window).unwrap().focused = false;
1067
1068        app.world_mut()
1069            .resource_mut::<ButtonInput<KeyCode>>()
1070            .press(KeyCode::Escape);
1071        app.update();
1072        // Checked before the next frame, where the player's cursor system
1073        // would release an unfocused capture anyway.
1074        assert_eq!(grab(&app, window), CursorGrabMode::None);
1075        app.world_mut()
1076            .resource_mut::<ButtonInput<KeyCode>>()
1077            .reset_all();
1078        app.update();
1079
1080        assert_eq!(pause_state(&app), PauseMenuState::Playing);
1081        assert_eq!(grab(&app, window), CursorGrabMode::None);
1082    }
1083
1084    #[test]
1085    fn pause_cursor_changes_only_touch_the_primary_window() {
1086        let (mut app, window) = pause_cursor_app();
1087        let secondary = app
1088            .world_mut()
1089            .spawn((
1090                Window {
1091                    focused: false,
1092                    ..default()
1093                },
1094                CursorOptions {
1095                    grab_mode: CursorGrabMode::Confined,
1096                    ..default()
1097                },
1098            ))
1099            .id();
1100
1101        tap(&mut app, KeyCode::Escape);
1102        tap(&mut app, KeyCode::Escape);
1103
1104        assert_eq!(grab(&app, window), CursorGrabMode::Locked);
1105        assert_eq!(grab(&app, secondary), CursorGrabMode::Confined);
1106    }
1107
1108    #[test]
1109    fn fov_steps_by_five_degrees_within_limits() {
1110        assert_eq!(step_fov_degrees(70.0, true), 75.0);
1111        assert_eq!(step_fov_degrees(70.0, false), 65.0);
1112        assert_eq!(step_fov_degrees(118.0, true), 120.0);
1113        assert_eq!(step_fov_degrees(52.0, false), 50.0);
1114    }
1115
1116    #[test]
1117    fn volume_steps_by_a_tenth_within_limits() {
1118        assert!((step_volume(0.5, true) - 0.6).abs() < 1e-6);
1119        assert!((step_volume(0.5, false) - 0.4).abs() < 1e-6);
1120        assert_eq!(step_volume(0.95, true), 1.0);
1121        assert_eq!(step_volume(0.05, false), 0.0);
1122    }
1123
1124    #[test]
1125    fn render_distance_steps_by_two_chunks_within_limits() {
1126        // Default load distance is 150 units ≈ 9.4 chunks → 9 → bumped to 10.
1127        assert_eq!(step_render_distance_chunks(150.0, true), 12);
1128        assert_eq!(step_render_distance_chunks(150.0, false), 8);
1129        assert_eq!(step_render_distance_chunks(8.0 * 16.0, true), 10);
1130        assert_eq!(step_render_distance_chunks(32.0 * 16.0, true), 32);
1131        assert_eq!(step_render_distance_chunks(4.0 * 16.0, false), 4);
1132        // Values outside the slider range are clamped first.
1133        assert_eq!(step_render_distance_chunks(1000.0 * 16.0, false), 30);
1134    }
1135
1136    #[test]
1137    fn sensitivity_steps_by_one_percent_within_limits() {
1138        assert_eq!(step_sensitivity_pct(1.0, false), 99);
1139        assert_eq!(step_sensitivity_pct(1.0, true), 100);
1140        assert_eq!(step_sensitivity_pct(0.5, true), 51);
1141        assert_eq!(step_sensitivity_pct(0.1, false), 10);
1142    }
1143
1144    /// World with the resources `handle_settings_buttons` needs and one
1145    /// pressed button.
1146    fn settings_world(pressed: SettingsButton) -> World {
1147        let mut world = World::new();
1148        world.insert_resource(SfxConfig::default());
1149        world.init_resource::<NextState<PauseMenuState>>();
1150        world.init_resource::<Messages<SaveSettingsRequest>>();
1151        world.spawn((
1152            Button,
1153            Interaction::Pressed,
1154            BackgroundColor(BTN_NORMAL),
1155            pressed,
1156        ));
1157        world
1158    }
1159
1160    fn press(world: &mut World) {
1161        world
1162            .run_system_once(handle_settings_buttons)
1163            .expect("handle_settings_buttons should run");
1164    }
1165
1166    #[test]
1167    fn sensitivity_button_updates_config_and_live_players() {
1168        let mut world = settings_world(SettingsButton::SensitivityDec);
1169        world.insert_resource(PlayerConfig::default());
1170        let player = world.spawn(Player::default()).id();
1171        assert_eq!(world.get::<Player>(player).unwrap().sensitivity, 1.0);
1172
1173        press(&mut world);
1174
1175        assert!((world.resource::<PlayerConfig>().sensitivity - 0.99).abs() < 1e-6);
1176        assert!(
1177            (world.get::<Player>(player).unwrap().sensitivity - 0.99).abs() < 1e-6,
1178            "the live player must pick up the new sensitivity without a restart"
1179        );
1180    }
1181
1182    #[test]
1183    fn volume_button_updates_sfx_config() {
1184        let mut world = settings_world(SettingsButton::VolumeDec);
1185        let before = world.resource::<SfxConfig>().volume;
1186
1187        press(&mut world);
1188
1189        let after = world.resource::<SfxConfig>().volume;
1190        assert!((after - (before - 0.1).clamp(0.0, 1.0)).abs() < 1e-6);
1191    }
1192
1193    #[test]
1194    fn back_button_requests_save_and_returns_to_pause() {
1195        let mut world = settings_world(SettingsButton::Back);
1196
1197        press(&mut world);
1198
1199        let saves = world.resource::<Messages<SaveSettingsRequest>>();
1200        assert_eq!(saves.iter_current_update_messages().count(), 1);
1201        assert!(matches!(
1202            *world.resource::<NextState<PauseMenuState>>(),
1203            NextState::Pending(PauseMenuState::Paused)
1204        ));
1205    }
1206}