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 cursor
23//! (`CursorGrabMode::None`, visible). Returning to `Playing` re-locks it
24//! (`CursorGrabMode::Locked`, hidden). Do not combine this plugin with
25//! [`player_cursor_system`](crate::player::player_cursor_system), which
26//! implements a conflicting two-stage Escape handler.
27//!
28//! # Integration
29//!
30//! Gate all gameplay systems on [`PauseMenuState::Playing`]:
31//!
32//! ```rust,no_run
33//! use bevy::prelude::*;
34//! use voxel_framework::prelude::*;
35//! use voxel_framework::player::{spawn_player, player_look, player_move,
36//!     player_resolve_collision};
37//! use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
38//!
39//! App::new()
40//!     .add_plugins(DefaultPlugins)
41//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
42//!     .add_plugins(PauseMenuPlugin)
43//!     .add_systems(Startup, spawn_player)
44//!     .add_systems(Update,
45//!         (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
46//!             .chain()
47//!             .run_if(in_state(PauseMenuState::Playing)),
48//!     );
49//! ```
50
51use bevy::asset::embedded_asset;
52use bevy::prelude::*;
53
54use crate::audio::{SfxConfig, SfxEvent, SfxRequest};
55use crate::player::PlayerConfig;
56use crate::world::{ChunkManager, WorldConfig};
57
58/// Asset path of the NotoSans font embedded into the framework binary.
59///
60/// The `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin`
61/// (part of `AssetPlugin` / `DefaultPlugins`). The path format is
62/// `embedded://{crate_name}/{path relative to the crate's `src/` dir}`, where
63/// the crate name uses underscores. See [`PauseMenuPlugin`] for how this font
64/// becomes the default value of [`PauseMenuConfig::font`].
65pub const EMBEDDED_NOTO_SANS_PATH: &str = "embedded://voxel_framework/ui/NotoSans-Regular.ttf";
66
67/// Asset path of the NotoSansSymbols2 font embedded into the framework binary.
68///
69/// Used exclusively to render symbol glyphs (e.g. `◀`, `▶`) that are absent
70/// from the subset of NotoSans shipped at [`EMBEDDED_NOTO_SANS_PATH`]. The
71/// `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin` (part
72/// of `AssetPlugin` / `DefaultPlugins`).
73pub const EMBEDDED_NOTO_SYMBOLS_PATH: &str =
74    "embedded://voxel_framework/ui/NotoSansSymbols2-Regular.ttf";
75
76// ─── State ────────────────────────────────────────────────────────────────────
77
78/// Bevy state enum that drives the pause menu lifecycle.
79///
80/// [`PauseMenuPlugin`] registers this as a Bevy `State` and transitions between
81/// variants automatically. Your own systems should use `run_if(in_state(…))`
82/// to participate in the pause flow.
83///
84/// # Variant transitions
85///
86/// | From | Trigger | To |
87/// |------|---------|-----|
88/// | `Playing` | Escape key | `Paused` |
89/// | `Paused` | Resume button or Escape | `Playing` |
90/// | `Paused` | Settings button | `Settings` |
91/// | `Settings` | Back button | `Paused` |
92///
93/// # Gating gameplay systems
94///
95/// ```rust,no_run
96/// # use bevy::prelude::*;
97/// # use voxel_framework::ui::PauseMenuState;
98/// # fn my_gameplay_system() {}
99/// App::new()
100///     .add_systems(Update,
101///         my_gameplay_system.run_if(in_state(PauseMenuState::Playing)),
102///     );
103/// ```
104#[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default)]
105pub enum PauseMenuState {
106    /// The game is running normally. Player input is active and the pause
107    /// menu is not visible. This is the default starting state.
108    #[default]
109    Playing,
110    /// The game is paused. The pause menu overlay is displayed and gameplay
111    /// systems gated on `Playing` are inactive. The cursor is free.
112    Paused,
113    /// The settings submenu is open. The pause menu overlay is replaced by the
114    /// settings panel. FOV and SFX volume can be adjusted here.
115    Settings,
116}
117
118// ─── Styling constants ────────────────────────────────────────────────────────
119
120const BTN_NORMAL: Color = Color::srgb(0.15, 0.15, 0.20);
121const BTN_HOVERED: Color = Color::srgb(0.25, 0.25, 0.35);
122const BTN_PRESSED: Color = Color::srgb(0.35, 0.35, 0.50);
123const OVERLAY: Color = Color::srgba(0.0, 0.0, 0.0, 0.78);
124
125// ─── Markers ─────────────────────────────────────────────────────────────────
126
127#[derive(Component)]
128struct PauseMenuRoot;
129#[derive(Component)]
130struct SettingsMenuRoot;
131#[derive(Component)]
132struct FovLabel;
133#[derive(Component)]
134struct VolumeLabel;
135#[derive(Component)]
136struct RenderDistLabel;
137#[derive(Component)]
138struct SensitivityLabel;
139
140#[derive(Component)]
141enum PauseButton {
142    Resume,
143    Settings,
144    Quit,
145}
146
147#[derive(Component)]
148enum SettingsButton {
149    FovInc,
150    FovDec,
151    VolumeInc,
152    VolumeDec,
153    RenderDistInc,
154    RenderDistDec,
155    SensitivityInc,
156    SensitivityDec,
157    Back,
158}
159
160// ─── Config ───────────────────────────────────────────────────────────────────
161
162// ─── Messages ─────────────────────────────────────────────────────────────────
163
164/// Emitted when the player clicks Back in the Settings submenu.
165///
166/// The host game should listen for this message and persist the current
167/// settings (FOV, volume, render distance, sensitivity) to disk using
168/// [`crate::settings::PersistedSettings`].
169#[derive(Message, Debug, Clone)]
170pub struct SaveSettingsRequest;
171
172// ─── Config ───────────────────────────────────────────────────────────────────
173
174/// Visual configuration for [`PauseMenuPlugin`].
175///
176/// Insert this resource before adding [`PauseMenuPlugin`] to supply a custom
177/// font. If omitted, [`PauseMenuPlugin`] populates `font` with the framework's
178/// embedded [NotoSans](https://fonts.google.com/noto/specimen/Noto+Sans)
179/// regular TTF — a unicode-capable font that renders the settings submenu's
180/// arrow glyphs (`←`, `◀`, `▶`) without tofu.
181///
182/// # Example
183///
184/// ```rust,no_run
185/// use bevy::prelude::*;
186/// use voxel_framework::ui::PauseMenuConfig;
187///
188/// fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
189///     commands.insert_resource(PauseMenuConfig {
190///         font: asset_server.load("fonts/MyFont.ttf"),
191///         symbol_font: asset_server.load("fonts/MyFont.ttf"),
192///     });
193/// }
194/// ```
195#[derive(Resource, Clone)]
196pub struct PauseMenuConfig {
197    /// Font handle used for every text element in both the pause menu and the
198    /// settings submenu (title, button labels, slider values).
199    ///
200    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
201    /// replaces the default handle with the embedded NotoSans font during
202    /// `Startup` (see `EMBEDDED_NOTO_SANS_PATH`) so games inherit a legible
203    /// unicode-capable font without loading any asset themselves. To override,
204    /// insert [`PauseMenuConfig`] with a custom `font` handle before the menu is
205    /// first spawned.
206    pub font: Handle<Font>,
207    /// Font handle used for symbol-only glyphs that are absent from the main
208    /// [`font`](Self::font) subset — specifically the `◀` and `▶` triangle
209    /// glyphs used on the settings slider inc/dec buttons.
210    ///
211    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
212    /// replaces the default handle with the embedded NotoSansSymbols2 font
213    /// during `Startup` (see `EMBEDDED_NOTO_SYMBOLS_PATH`). To override,
214    /// insert [`PauseMenuConfig`] with a custom `symbol_font` handle before the
215    /// menu is first spawned.
216    pub symbol_font: Handle<Font>,
217}
218
219impl Default for PauseMenuConfig {
220    fn default() -> Self {
221        Self {
222            font: Handle::default(),
223            symbol_font: Handle::default(),
224        }
225    }
226}
227
228// ─── Plugin ───────────────────────────────────────────────────────────────────
229
230/// Plugin that adds a full-screen pause menu with a settings submenu.
231///
232/// Registers [`PauseMenuState`] and wires all transitions, UI spawning, and
233/// cursor management. The settings submenu exposes real-time controls for FOV
234/// (±5° per click, clamped to `50°`–`120°`) and SFX volume (±10% per click,
235/// clamped to `0%`–`100%`).
236///
237/// **Does not** include [`player_cursor_system`](crate::player::player_cursor_system).
238/// If you use this plugin, omit that system — this plugin handles cursor locking
239/// and releasing as part of the `Playing ↔ Paused` transition.
240///
241/// # Simple usage
242///
243/// ```rust,no_run
244/// use bevy::prelude::*;
245/// use voxel_framework::prelude::*;
246/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
247///
248/// App::new()
249///     .add_plugins(DefaultPlugins)
250///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
251///     .add_plugins(PauseMenuPlugin)
252///     .run();
253/// ```
254///
255/// # With state-gated player systems
256///
257/// ```rust,no_run
258/// use bevy::prelude::*;
259/// use voxel_framework::prelude::*;
260/// use voxel_framework::player::{spawn_player, player_look, player_move,
261///     player_resolve_collision};
262/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
263///
264/// App::new()
265///     .add_plugins(DefaultPlugins)
266///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
267///     .add_plugins(PauseMenuPlugin)
268///     .add_systems(Startup, spawn_player)
269///     .add_systems(Update,
270///         (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
271///             .chain()
272///             .run_if(in_state(PauseMenuState::Playing)),
273///     );
274/// ```
275pub struct PauseMenuPlugin;
276
277impl Plugin for PauseMenuPlugin {
278    fn build(&self, app: &mut App) {
279        // Embed the NotoSans TTF into the framework binary. The resulting asset
280        // is reachable from any `AssetServer::load(...)` call via the
281        // `embedded://` scheme — see [`EMBEDDED_NOTO_SANS_PATH`].
282        embedded_asset!(app, "NotoSans-Regular.ttf");
283        embedded_asset!(app, "NotoSansSymbols2-Regular.ttf");
284
285        app.init_resource::<PauseMenuConfig>();
286        app.init_state::<PauseMenuState>();
287        app.add_message::<SaveSettingsRequest>();
288
289        // Populate `PauseMenuConfig::font` with the embedded NotoSans handle
290        // when the user hasn't supplied their own font. Runs once on `Startup`,
291        // which fires before any `OnEnter(Paused)` transition can spawn the
292        // menu, so the handle is always ready by the time the menu is built.
293        app.add_systems(Startup, load_default_font);
294
295        // Playing — toggle on Escape
296        app.add_systems(
297            Update,
298            toggle_pause.run_if(in_state(PauseMenuState::Playing)),
299        );
300
301        // Paused
302        app.add_systems(
303            OnEnter(PauseMenuState::Paused),
304            (spawn_pause_menu, release_cursor),
305        );
306        app.add_systems(OnExit(PauseMenuState::Paused), despawn_pause_menu);
307        app.add_systems(
308            Update,
309            (handle_pause_buttons, escape_to_resume).run_if(in_state(PauseMenuState::Paused)),
310        );
311
312        // Settings
313        app.add_systems(OnEnter(PauseMenuState::Settings), spawn_settings_menu);
314        app.add_systems(OnExit(PauseMenuState::Settings), despawn_settings_menu);
315        app.add_systems(
316            Update,
317            handle_settings_buttons.run_if(in_state(PauseMenuState::Settings)),
318        );
319    }
320}
321
322// ─── Default font loader ──────────────────────────────────────────────────────
323
324/// Populates [`PauseMenuConfig::font`] with the embedded NotoSans font on
325/// startup if the game has not supplied a custom font.
326///
327/// `Default` can't access the [`AssetServer`], so we use a startup sentinel:
328/// when `font == Handle::default()` (the weak, uninitialised handle produced
329/// by [`PauseMenuConfig::default()`]), we load the embedded font and overwrite
330/// the field. Games that insert their own [`PauseMenuConfig`] before this
331/// plugin — or before `Startup` runs — keep their custom handle untouched.
332fn load_default_font(mut cfg: ResMut<PauseMenuConfig>, asset_server: Res<AssetServer>) {
333    if cfg.font == Handle::default() {
334        cfg.font = asset_server.load(EMBEDDED_NOTO_SANS_PATH);
335    }
336    if cfg.symbol_font == Handle::default() {
337        cfg.symbol_font = asset_server.load(EMBEDDED_NOTO_SYMBOLS_PATH);
338    }
339}
340
341// ─── Cursor helpers ───────────────────────────────────────────────────────────
342
343/// Releases the cursor when entering [`PauseMenuState::Paused`].
344///
345/// Called via `OnEnter(Paused)`. Sets `CursorGrabMode::None` and makes the
346/// cursor visible so the player can interact with the menu buttons.
347fn release_cursor(mut windows: Query<&mut bevy::window::CursorOptions>) {
348    for mut cursor in &mut windows {
349        cursor.grab_mode = bevy::window::CursorGrabMode::None;
350        cursor.visible = true;
351    }
352}
353
354/// Re-locks the cursor when returning to [`PauseMenuState::Playing`].
355///
356/// Called as a plain function (not a system) from [`escape_to_resume`] and
357/// [`handle_pause_buttons`] so that cursor re-lock and state transition happen
358/// in the same frame without a one-frame gap.
359fn lock_cursor(windows: &mut Query<&mut bevy::window::CursorOptions>) {
360    for mut cursor in windows.iter_mut() {
361        cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
362        cursor.visible = false;
363    }
364}
365
366// ─── Toggle pause ─────────────────────────────────────────────────────────────
367
368/// Transitions from `Playing` → `Paused` when Escape is pressed.
369///
370/// Runs only in [`PauseMenuState::Playing`]. Also fires a
371/// [`SfxEvent::PauseOpen`] sound request.
372fn toggle_pause(
373    keys: Res<ButtonInput<KeyCode>>,
374    mut next: ResMut<NextState<PauseMenuState>>,
375    mut sfx: MessageWriter<SfxRequest>,
376) {
377    if keys.just_pressed(KeyCode::Escape) {
378        next.set(PauseMenuState::Paused);
379        sfx.write(SfxRequest {
380            event: SfxEvent::PauseOpen,
381            position: None,
382        });
383    }
384}
385
386/// Transitions from `Paused` → `Playing` when Escape is pressed.
387///
388/// Runs only in [`PauseMenuState::Paused`]. Re-locks the cursor via
389/// [`lock_cursor`] in the same frame and fires [`SfxEvent::PauseClose`].
390fn escape_to_resume(
391    keys: Res<ButtonInput<KeyCode>>,
392    mut next: ResMut<NextState<PauseMenuState>>,
393    mut windows: Query<&mut bevy::window::CursorOptions>,
394    mut sfx: MessageWriter<SfxRequest>,
395) {
396    if keys.just_pressed(KeyCode::Escape) {
397        next.set(PauseMenuState::Playing);
398        lock_cursor(&mut windows);
399        sfx.write(SfxRequest {
400            event: SfxEvent::PauseClose,
401            position: None,
402        });
403    }
404}
405
406// ─── Spawn helpers ────────────────────────────────────────────────────────────
407
408fn spawn_btn<C: Component>(
409    parent: &mut ChildSpawnerCommands,
410    label: &str,
411    action: C,
412    width: f32,
413    height: f32,
414    font: Handle<Font>,
415) {
416    parent
417        .spawn((
418            action,
419            Button,
420            Node {
421                width: Val::Px(width),
422                height: Val::Px(height),
423                justify_content: JustifyContent::Center,
424                align_items: AlignItems::Center,
425                ..default()
426            },
427            BackgroundColor(BTN_NORMAL),
428        ))
429        .with_children(|b| {
430            b.spawn((
431                Text::new(label),
432                TextFont {
433                    font,
434                    font_size: 20.0,
435                    ..default()
436                },
437                TextColor(Color::WHITE),
438            ));
439        });
440}
441
442fn overlay_node() -> (Node, BackgroundColor) {
443    (
444        Node {
445            width: Val::Percent(100.0),
446            height: Val::Percent(100.0),
447            flex_direction: FlexDirection::Column,
448            justify_content: JustifyContent::Center,
449            align_items: AlignItems::Center,
450            row_gap: Val::Px(14.0),
451            ..default()
452        },
453        BackgroundColor(OVERLAY),
454    )
455}
456
457// ─── Pause menu ───────────────────────────────────────────────────────────────
458
459/// Spawns the pause menu overlay when entering [`PauseMenuState::Paused`].
460///
461/// Builds a full-screen semi-transparent overlay with three buttons: Resume,
462/// Settings, and Quit. Runs via `OnEnter(Paused)`.
463fn spawn_pause_menu(mut commands: Commands, config: Res<PauseMenuConfig>) {
464    let (node, bg) = overlay_node();
465    commands
466        .spawn((PauseMenuRoot, node, bg))
467        .with_children(|p| {
468            p.spawn((
469                Text::new("PAUSED"),
470                TextFont {
471                    font: config.font.clone(),
472                    font_size: 52.0,
473                    ..default()
474                },
475                TextColor(Color::WHITE),
476                Node {
477                    margin: UiRect::bottom(Val::Px(28.0)),
478                    ..default()
479                },
480            ));
481            spawn_btn(
482                p,
483                "Resume",
484                PauseButton::Resume,
485                280.0,
486                52.0,
487                config.font.clone(),
488            );
489            spawn_btn(
490                p,
491                "Settings",
492                PauseButton::Settings,
493                280.0,
494                52.0,
495                config.font.clone(),
496            );
497            spawn_btn(
498                p,
499                "Quit",
500                PauseButton::Quit,
501                280.0,
502                52.0,
503                config.font.clone(),
504            );
505        });
506}
507
508/// Despawns the pause menu overlay when leaving [`PauseMenuState::Paused`].
509///
510/// Runs via `OnExit(Paused)`, which fires for both `Paused → Playing` and
511/// `Paused → Settings` transitions.
512fn despawn_pause_menu(mut commands: Commands, q: Query<Entity, With<PauseMenuRoot>>) {
513    for e in &q {
514        commands.entity(e).despawn();
515    }
516}
517
518/// Handles hover/press styling and click actions for pause menu buttons.
519///
520/// Runs every frame in [`PauseMenuState::Paused`]. Updates button background
521/// colors on hover and press, then on `Pressed` dispatches: Resume → `Playing`
522/// (re-locks cursor), Settings → `Settings`, Quit → [`AppExit`].
523fn handle_pause_buttons(
524    mut q: Query<
525        (&Interaction, &mut BackgroundColor, &PauseButton),
526        (Changed<Interaction>, With<Button>),
527    >,
528    mut next: ResMut<NextState<PauseMenuState>>,
529    mut windows: Query<&mut bevy::window::CursorOptions>,
530    mut app_exit: MessageWriter<AppExit>,
531    mut sfx: MessageWriter<SfxRequest>,
532) {
533    for (interaction, mut bg, action) in &mut q {
534        *bg = BackgroundColor(match interaction {
535            Interaction::Hovered => BTN_HOVERED,
536            Interaction::Pressed => BTN_PRESSED,
537            Interaction::None => BTN_NORMAL,
538        });
539        if *interaction != Interaction::Pressed {
540            continue;
541        }
542        match action {
543            PauseButton::Resume => {
544                next.set(PauseMenuState::Playing);
545                lock_cursor(&mut windows);
546                sfx.write(SfxRequest {
547                    event: SfxEvent::PauseClose,
548                    position: None,
549                });
550            }
551            PauseButton::Settings => next.set(PauseMenuState::Settings),
552            PauseButton::Quit => {
553                app_exit.write(AppExit::Success);
554            }
555        }
556    }
557}
558
559// ─── Settings menu ────────────────────────────────────────────────────────────
560
561/// Spawns the settings overlay when entering [`PauseMenuState::Settings`].
562///
563/// Reads the current FOV from the [`Camera3d`] projection, the current SFX
564/// volume from [`SfxConfig`], the render distance from [`WorldConfig`], and the
565/// mouse sensitivity from [`PlayerConfig`] to initialise the slider labels.
566/// Runs via `OnEnter(Settings)`.
567fn spawn_settings_menu(
568    mut commands: Commands,
569    sfx_config: Res<SfxConfig>,
570    world_config: Option<Res<WorldConfig>>,
571    player_config: Option<Res<PlayerConfig>>,
572    camera_q: Query<&Projection, With<Camera3d>>,
573    config: Res<PauseMenuConfig>,
574) {
575    let fov_deg = camera_q
576        .single()
577        .ok()
578        .and_then(|p| {
579            if let Projection::Perspective(pp) = p {
580                Some(pp.fov.to_degrees())
581            } else {
582                None
583            }
584        })
585        .unwrap_or(90.0);
586    let volume_pct = sfx_config.volume * 100.0;
587    let render_dist_chunks = world_config
588        .as_ref()
589        .map(|wc| ((wc.load_distance / 16.0).round() as i32).clamp(4, 32) as i32)
590        .unwrap_or(10);
591    // Round to nearest even
592    let render_dist_chunks = if render_dist_chunks % 2 == 0 {
593        render_dist_chunks
594    } else {
595        render_dist_chunks + 1
596    };
597    let sensitivity_pct = player_config
598        .as_ref()
599        .map(|pc| ((pc.sensitivity * 100.0).round() as i32).clamp(10, 100))
600        .unwrap_or(100);
601
602    let (node, bg) = overlay_node();
603    commands
604        .spawn((SettingsMenuRoot, node, bg))
605        .with_children(|p| {
606            p.spawn((
607                Text::new("SETTINGS"),
608                TextFont {
609                    font: config.font.clone(),
610                    font_size: 42.0,
611                    ..default()
612                },
613                TextColor(Color::WHITE),
614                Node {
615                    margin: UiRect::bottom(Val::Px(20.0)),
616                    ..default()
617                },
618            ));
619
620            spawn_slider_row(
621                p,
622                "Field of View",
623                format!("{fov_deg:.0}°"),
624                FovLabel,
625                SettingsButton::FovDec,
626                SettingsButton::FovInc,
627                config.font.clone(),
628                config.symbol_font.clone(),
629            );
630
631            spawn_slider_row(
632                p,
633                "SFX Volume",
634                format!("{volume_pct:.0}%"),
635                VolumeLabel,
636                SettingsButton::VolumeDec,
637                SettingsButton::VolumeInc,
638                config.font.clone(),
639                config.symbol_font.clone(),
640            );
641
642            spawn_slider_row(
643                p,
644                "Render Distance",
645                format!("{render_dist_chunks} chunks"),
646                RenderDistLabel,
647                SettingsButton::RenderDistDec,
648                SettingsButton::RenderDistInc,
649                config.font.clone(),
650                config.symbol_font.clone(),
651            );
652
653            spawn_slider_row(
654                p,
655                "Sensitivity",
656                format!("{sensitivity_pct:.0}%"),
657                SensitivityLabel,
658                SettingsButton::SensitivityDec,
659                SettingsButton::SensitivityInc,
660                config.font.clone(),
661                config.symbol_font.clone(),
662            );
663
664            p.spawn(Node {
665                margin: UiRect::top(Val::Px(20.0)),
666                ..default()
667            })
668            .with_children(|row| {
669                spawn_btn(
670                    row,
671                    "< Back",
672                    SettingsButton::Back,
673                    200.0,
674                    50.0,
675                    config.font.clone(),
676                );
677            });
678        });
679}
680
681fn spawn_slider_row<L: Component, D: Component, I: Component>(
682    parent: &mut ChildSpawnerCommands,
683    label: &str,
684    value: String,
685    value_marker: L,
686    dec: D,
687    inc: I,
688    font: Handle<Font>,
689    symbol_font: Handle<Font>,
690) {
691    parent
692        .spawn(Node {
693            flex_direction: FlexDirection::Row,
694            align_items: AlignItems::Center,
695            column_gap: Val::Px(12.0),
696            ..default()
697        })
698        .with_children(|row| {
699            row.spawn((
700                Text::new(label),
701                TextFont {
702                    font: font.clone(),
703                    font_size: 20.0,
704                    ..default()
705                },
706                TextColor(Color::srgb(0.8, 0.8, 0.8)),
707                Node {
708                    width: Val::Px(200.0),
709                    ..default()
710                },
711            ));
712            spawn_btn(row, "\u{25C0}", dec, 44.0, 44.0, symbol_font.clone());
713            row.spawn((
714                value_marker,
715                Text::new(value),
716                TextFont {
717                    font: font.clone(),
718                    font_size: 22.0,
719                    ..default()
720                },
721                TextColor(Color::WHITE),
722                Node {
723                    width: Val::Px(80.0),
724                    justify_content: JustifyContent::Center,
725                    ..default()
726                },
727            ));
728            spawn_btn(row, "\u{25B6}", inc, 44.0, 44.0, symbol_font);
729        });
730}
731
732/// Despawns the settings overlay when leaving [`PauseMenuState::Settings`].
733///
734/// Runs via `OnExit(Settings)`. The only exit transition is `Settings → Paused`
735/// via the Back button.
736fn despawn_settings_menu(mut commands: Commands, q: Query<Entity, With<SettingsMenuRoot>>) {
737    for e in &q {
738        commands.entity(e).despawn();
739    }
740}
741
742/// Handles hover/press styling and click actions for settings menu buttons.
743///
744/// Runs every frame in [`PauseMenuState::Settings`]. Adjusts values on press:
745/// - `FovInc` / `FovDec`: changes FOV by ±5° (clamped `50°`–`120°`) and updates
746///   [`FovLabel`] text and the [`Camera3d`] perspective projection.
747/// - `VolumeInc` / `VolumeDec`: changes [`SfxConfig::volume`] by ±0.1 (clamped
748///   `0.0`–`1.0`) and updates [`VolumeLabel`] text.
749/// - `RenderDistInc` / `RenderDistDec`: changes [`WorldConfig::load_distance`] by
750///   ±2 chunks (clamped `4`–`32`) and updates [`RenderDistLabel`] text and
751///   [`ChunkManager`] distances.
752/// - `SensitivityInc` / `SensitivityDec`: changes [`PlayerConfig::sensitivity`] by
753///   ±1% (clamped `10`–`100`) and updates [`SensitivityLabel`] text.
754/// - `Back`: emits [`SaveSettingsRequest`] and transitions to [`PauseMenuState::Paused`].
755#[allow(clippy::too_many_arguments)]
756fn handle_settings_buttons(
757    mut q: Query<
758        (&Interaction, &mut BackgroundColor, &SettingsButton),
759        (Changed<Interaction>, With<Button>),
760    >,
761    mut sfx_config: ResMut<SfxConfig>,
762    mut world_config: Option<ResMut<WorldConfig>>,
763    mut chunk_manager: Option<ResMut<ChunkManager>>,
764    mut player_config: Option<ResMut<PlayerConfig>>,
765    mut next: ResMut<NextState<PauseMenuState>>,
766    mut fov_label: Query<
767        &mut Text,
768        (
769            With<FovLabel>,
770            Without<VolumeLabel>,
771            Without<RenderDistLabel>,
772            Without<SensitivityLabel>,
773        ),
774    >,
775    mut vol_label: Query<
776        &mut Text,
777        (
778            With<VolumeLabel>,
779            Without<FovLabel>,
780            Without<RenderDistLabel>,
781            Without<SensitivityLabel>,
782        ),
783    >,
784    mut rdist_label: Query<
785        &mut Text,
786        (
787            With<RenderDistLabel>,
788            Without<FovLabel>,
789            Without<VolumeLabel>,
790            Without<SensitivityLabel>,
791        ),
792    >,
793    mut sens_label: Query<
794        &mut Text,
795        (
796            With<SensitivityLabel>,
797            Without<FovLabel>,
798            Without<VolumeLabel>,
799            Without<RenderDistLabel>,
800        ),
801    >,
802    mut camera_q: Query<&mut Projection, With<Camera3d>>,
803    mut save_writer: MessageWriter<SaveSettingsRequest>,
804) {
805    for (interaction, mut bg, action) in &mut q {
806        *bg = BackgroundColor(match interaction {
807            Interaction::Hovered => BTN_HOVERED,
808            Interaction::Pressed => BTN_PRESSED,
809            Interaction::None => BTN_NORMAL,
810        });
811        if *interaction != Interaction::Pressed {
812            continue;
813        }
814
815        match action {
816            SettingsButton::FovInc | SettingsButton::FovDec => {
817                if let Ok(mut proj) = camera_q.single_mut() {
818                    if let Projection::Perspective(ref mut pp) = *proj {
819                        let delta = if matches!(action, SettingsButton::FovInc) {
820                            5.0
821                        } else {
822                            -5.0
823                        };
824                        let new_fov = (pp.fov.to_degrees() + delta).clamp(50.0, 120.0);
825                        pp.fov = new_fov.to_radians();
826                        if let Ok(mut t) = fov_label.single_mut() {
827                            **t = format!("{new_fov:.0}°");
828                        }
829                    }
830                }
831            }
832            SettingsButton::VolumeInc | SettingsButton::VolumeDec => {
833                let delta = if matches!(action, SettingsButton::VolumeInc) {
834                    0.1
835                } else {
836                    -0.1
837                };
838                sfx_config.volume = (sfx_config.volume + delta).clamp(0.0, 1.0);
839                let pct = sfx_config.volume * 100.0;
840                if let Ok(mut t) = vol_label.single_mut() {
841                    **t = format!("{pct:.0}%");
842                }
843            }
844            SettingsButton::RenderDistInc | SettingsButton::RenderDistDec => {
845                if let Some(ref mut wc) = world_config {
846                    // Current value in chunks (rounded to nearest even)
847                    let current = ((wc.load_distance / 16.0).round() as i32).clamp(4, 32);
848                    let current = if current % 2 == 0 {
849                        current
850                    } else {
851                        current + 1
852                    };
853                    let delta: i32 = if matches!(action, SettingsButton::RenderDistInc) {
854                        2
855                    } else {
856                        -2
857                    };
858                    let new_chunks = (current + delta).clamp(4, 32);
859                    wc.load_distance = new_chunks as f32 * 16.0;
860                    wc.unload_distance = wc.load_distance + 32.0;
861                    if let Some(ref mut cm) = chunk_manager {
862                        cm.load_distance = wc.load_distance;
863                        cm.unload_distance = wc.unload_distance;
864                    }
865                    if let Ok(mut t) = rdist_label.single_mut() {
866                        **t = format!("{new_chunks} chunks");
867                    }
868                }
869            }
870            SettingsButton::SensitivityInc | SettingsButton::SensitivityDec => {
871                if let Some(ref mut pc) = player_config {
872                    let current_pct = (pc.sensitivity * 100.0).round() as i32;
873                    let delta: i32 = if matches!(action, SettingsButton::SensitivityInc) {
874                        1
875                    } else {
876                        -1
877                    };
878                    let new_pct = (current_pct + delta).clamp(10, 100);
879                    pc.sensitivity = new_pct as f32 / 100.0;
880                    if let Ok(mut t) = sens_label.single_mut() {
881                        **t = format!("{new_pct:.0}%");
882                    }
883                }
884            }
885            SettingsButton::Back => {
886                save_writer.write(SaveSettingsRequest);
887                next.set(PauseMenuState::Paused);
888            }
889        }
890    }
891}