voxel-framework 0.10.0

A reusable voxel engine framework built on Bevy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
//! Optional pause menu with a settings submenu for FOV and SFX volume.
//!
//! This module implements a self-contained pause flow driven by the
//! [`PauseMenuState`] state machine. Add [`PauseMenuPlugin`] to wire it up;
//! then gate your own gameplay systems on [`PauseMenuState::Playing`] so they
//! freeze automatically when the player pauses.
//!
//! # State machine
//!
//! ```text
//!                  Escape
//! ┌─────────┐ ──────────────► ┌────────┐
//! │ Playing │                 │ Paused │ ◄─────────────────┐
//! └─────────┘ ◄────────────── └────────┘                   │
//!                Resume btn /       │ Settings btn          │
//!                Escape             ▼                       │
//!                             ┌──────────┐  ← Back btn     │
//!                             │ Settings │ ────────────────►┘
//!                             └──────────┘
//! ```
//!
//! **Cursor management:** entering `Paused` releases the cursor
//! (`CursorGrabMode::None`, visible). Returning to `Playing` re-locks it
//! (`CursorGrabMode::Locked`, hidden). Do not combine this plugin with
//! [`player_cursor_system`](crate::player::player_cursor_system), which
//! implements a conflicting two-stage Escape handler.
//!
//! # Integration
//!
//! Gate all gameplay systems on [`PauseMenuState::Playing`]:
//!
//! ```rust,no_run
//! use bevy::prelude::*;
//! use voxel_framework::prelude::*;
//! use voxel_framework::player::{spawn_player, player_look, player_move,
//!     player_resolve_collision};
//! use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
//!
//! App::new()
//!     .add_plugins(DefaultPlugins)
//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
//!     .add_plugins(PauseMenuPlugin)
//!     .add_systems(Startup, spawn_player)
//!     .add_systems(Update,
//!         (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
//!             .chain()
//!             .run_if(in_state(PauseMenuState::Playing)),
//!     );
//! ```

use bevy::asset::embedded_asset;
use bevy::prelude::*;

use crate::audio::{SfxConfig, SfxEvent, SfxRequest};
use crate::player::PlayerConfig;
use crate::world::{ChunkManager, WorldConfig};

/// Asset path of the NotoSans font embedded into the framework binary.
///
/// The `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin`
/// (part of `AssetPlugin` / `DefaultPlugins`). The path format is
/// `embedded://{crate_name}/{path relative to the crate's `src/` dir}`, where
/// the crate name uses underscores. See [`PauseMenuPlugin`] for how this font
/// becomes the default value of [`PauseMenuConfig::font`].
pub const EMBEDDED_NOTO_SANS_PATH: &str = "embedded://voxel_framework/ui/NotoSans-Regular.ttf";

/// Asset path of the NotoSansSymbols2 font embedded into the framework binary.
///
/// Used exclusively to render symbol glyphs (e.g. `◀`, `▶`) that are absent
/// from the subset of NotoSans shipped at [`EMBEDDED_NOTO_SANS_PATH`]. The
/// `embedded://` scheme is registered by the Bevy `EmbeddedAssetPlugin` (part
/// of `AssetPlugin` / `DefaultPlugins`).
pub const EMBEDDED_NOTO_SYMBOLS_PATH: &str =
    "embedded://voxel_framework/ui/NotoSansSymbols2-Regular.ttf";

// ─── State ────────────────────────────────────────────────────────────────────

/// Bevy state enum that drives the pause menu lifecycle.
///
/// [`PauseMenuPlugin`] registers this as a Bevy `State` and transitions between
/// variants automatically. Your own systems should use `run_if(in_state(…))`
/// to participate in the pause flow.
///
/// # Variant transitions
///
/// | From | Trigger | To |
/// |------|---------|-----|
/// | `Playing` | Escape key | `Paused` |
/// | `Paused` | Resume button or Escape | `Playing` |
/// | `Paused` | Settings button | `Settings` |
/// | `Settings` | Back button | `Paused` |
///
/// # Gating gameplay systems
///
/// ```rust,no_run
/// # use bevy::prelude::*;
/// # use voxel_framework::ui::PauseMenuState;
/// # fn my_gameplay_system() {}
/// App::new()
///     .add_systems(Update,
///         my_gameplay_system.run_if(in_state(PauseMenuState::Playing)),
///     );
/// ```
#[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum PauseMenuState {
    /// The game is running normally. Player input is active and the pause
    /// menu is not visible. This is the default starting state.
    #[default]
    Playing,
    /// The game is paused. The pause menu overlay is displayed and gameplay
    /// systems gated on `Playing` are inactive. The cursor is free.
    Paused,
    /// The settings submenu is open. The pause menu overlay is replaced by the
    /// settings panel. FOV and SFX volume can be adjusted here.
    Settings,
}

// ─── Styling constants ────────────────────────────────────────────────────────

const BTN_NORMAL: Color = Color::srgb(0.15, 0.15, 0.20);
const BTN_HOVERED: Color = Color::srgb(0.25, 0.25, 0.35);
const BTN_PRESSED: Color = Color::srgb(0.35, 0.35, 0.50);
const OVERLAY: Color = Color::srgba(0.0, 0.0, 0.0, 0.78);

// ─── Markers ─────────────────────────────────────────────────────────────────

#[derive(Component)]
struct PauseMenuRoot;
#[derive(Component)]
struct SettingsMenuRoot;
#[derive(Component)]
struct FovLabel;
#[derive(Component)]
struct VolumeLabel;
#[derive(Component)]
struct RenderDistLabel;
#[derive(Component)]
struct SensitivityLabel;

#[derive(Component)]
enum PauseButton {
    Resume,
    Settings,
    Quit,
}

#[derive(Component)]
enum SettingsButton {
    FovInc,
    FovDec,
    VolumeInc,
    VolumeDec,
    RenderDistInc,
    RenderDistDec,
    SensitivityInc,
    SensitivityDec,
    Back,
}

// ─── Config ───────────────────────────────────────────────────────────────────

// ─── Messages ─────────────────────────────────────────────────────────────────

/// Emitted when the player clicks Back in the Settings submenu.
///
/// The host game should listen for this message and persist the current
/// settings (FOV, volume, render distance, sensitivity) to disk using
/// [`crate::settings::PersistedSettings`].
#[derive(Message, Debug, Clone)]
pub struct SaveSettingsRequest;

// ─── Config ───────────────────────────────────────────────────────────────────

/// Visual configuration for [`PauseMenuPlugin`].
///
/// Insert this resource before adding [`PauseMenuPlugin`] to supply a custom
/// font. If omitted, [`PauseMenuPlugin`] populates `font` with the framework's
/// embedded [NotoSans](https://fonts.google.com/noto/specimen/Noto+Sans)
/// regular TTF — a unicode-capable font that renders the settings submenu's
/// arrow glyphs (`←`, `◀`, `▶`) without tofu.
///
/// # Example
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::ui::PauseMenuConfig;
///
/// fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
///     commands.insert_resource(PauseMenuConfig {
///         font: asset_server.load("fonts/MyFont.ttf"),
///         symbol_font: asset_server.load("fonts/MyFont.ttf"),
///     });
/// }
/// ```
#[derive(Resource, Clone)]
pub struct PauseMenuConfig {
    /// Font handle used for every text element in both the pause menu and the
    /// settings submenu (title, button labels, slider values).
    ///
    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
    /// replaces the default handle with the embedded NotoSans font during
    /// `Startup` (see `EMBEDDED_NOTO_SANS_PATH`) so games inherit a legible
    /// unicode-capable font without loading any asset themselves. To override,
    /// insert [`PauseMenuConfig`] with a custom `font` handle before the menu is
    /// first spawned.
    pub font: Handle<Font>,
    /// Font handle used for symbol-only glyphs that are absent from the main
    /// [`font`](Self::font) subset — specifically the `◀` and `▶` triangle
    /// glyphs used on the settings slider inc/dec buttons.
    ///
    /// Defaults to [`Handle::default()`] at construction time. [`PauseMenuPlugin`]
    /// replaces the default handle with the embedded NotoSansSymbols2 font
    /// during `Startup` (see `EMBEDDED_NOTO_SYMBOLS_PATH`). To override,
    /// insert [`PauseMenuConfig`] with a custom `symbol_font` handle before the
    /// menu is first spawned.
    pub symbol_font: Handle<Font>,
}

impl Default for PauseMenuConfig {
    fn default() -> Self {
        Self {
            font: Handle::default(),
            symbol_font: Handle::default(),
        }
    }
}

// ─── Plugin ───────────────────────────────────────────────────────────────────

/// Plugin that adds a full-screen pause menu with a settings submenu.
///
/// Registers [`PauseMenuState`] and wires all transitions, UI spawning, and
/// cursor management. The settings submenu exposes real-time controls for FOV
/// (±5° per click, clamped to `50°`–`120°`) and SFX volume (±10% per click,
/// clamped to `0%`–`100%`).
///
/// **Does not** include [`player_cursor_system`](crate::player::player_cursor_system).
/// If you use this plugin, omit that system — this plugin handles cursor locking
/// and releasing as part of the `Playing ↔ Paused` transition.
///
/// # Simple usage
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
///     .add_plugins(PauseMenuPlugin)
///     .run();
/// ```
///
/// # With state-gated player systems
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
/// use voxel_framework::player::{spawn_player, player_look, player_move,
///     player_resolve_collision};
/// use voxel_framework::ui::{PauseMenuPlugin, PauseMenuState};
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
///     .add_plugins(PauseMenuPlugin)
///     .add_systems(Startup, spawn_player)
///     .add_systems(Update,
///         (player_look, player_move::<DefaultVoxel>, player_resolve_collision::<DefaultVoxel>)
///             .chain()
///             .run_if(in_state(PauseMenuState::Playing)),
///     );
/// ```
pub struct PauseMenuPlugin;

impl Plugin for PauseMenuPlugin {
    fn build(&self, app: &mut App) {
        // Embed the NotoSans TTF into the framework binary. The resulting asset
        // is reachable from any `AssetServer::load(...)` call via the
        // `embedded://` scheme — see [`EMBEDDED_NOTO_SANS_PATH`].
        embedded_asset!(app, "NotoSans-Regular.ttf");
        embedded_asset!(app, "NotoSansSymbols2-Regular.ttf");

        app.init_resource::<PauseMenuConfig>();
        app.init_state::<PauseMenuState>();
        app.add_message::<SaveSettingsRequest>();

        // Populate `PauseMenuConfig::font` with the embedded NotoSans handle
        // when the user hasn't supplied their own font. Runs once on `Startup`,
        // which fires before any `OnEnter(Paused)` transition can spawn the
        // menu, so the handle is always ready by the time the menu is built.
        app.add_systems(Startup, load_default_font);

        // Playing — toggle on Escape
        app.add_systems(
            Update,
            toggle_pause.run_if(in_state(PauseMenuState::Playing)),
        );

        // Paused
        app.add_systems(
            OnEnter(PauseMenuState::Paused),
            (spawn_pause_menu, release_cursor),
        );
        app.add_systems(OnExit(PauseMenuState::Paused), despawn_pause_menu);
        app.add_systems(
            Update,
            (handle_pause_buttons, escape_to_resume).run_if(in_state(PauseMenuState::Paused)),
        );

        // Settings
        app.add_systems(OnEnter(PauseMenuState::Settings), spawn_settings_menu);
        app.add_systems(OnExit(PauseMenuState::Settings), despawn_settings_menu);
        app.add_systems(
            Update,
            handle_settings_buttons.run_if(in_state(PauseMenuState::Settings)),
        );
    }
}

// ─── Default font loader ──────────────────────────────────────────────────────

/// Populates [`PauseMenuConfig::font`] with the embedded NotoSans font on
/// startup if the game has not supplied a custom font.
///
/// `Default` can't access the [`AssetServer`], so we use a startup sentinel:
/// when `font == Handle::default()` (the weak, uninitialised handle produced
/// by [`PauseMenuConfig::default()`]), we load the embedded font and overwrite
/// the field. Games that insert their own [`PauseMenuConfig`] before this
/// plugin — or before `Startup` runs — keep their custom handle untouched.
fn load_default_font(mut cfg: ResMut<PauseMenuConfig>, asset_server: Res<AssetServer>) {
    if cfg.font == Handle::default() {
        cfg.font = asset_server.load(EMBEDDED_NOTO_SANS_PATH);
    }
    if cfg.symbol_font == Handle::default() {
        cfg.symbol_font = asset_server.load(EMBEDDED_NOTO_SYMBOLS_PATH);
    }
}

// ─── Cursor helpers ───────────────────────────────────────────────────────────

/// Releases the cursor when entering [`PauseMenuState::Paused`].
///
/// Called via `OnEnter(Paused)`. Sets `CursorGrabMode::None` and makes the
/// cursor visible so the player can interact with the menu buttons.
fn release_cursor(mut windows: Query<&mut bevy::window::CursorOptions>) {
    for mut cursor in &mut windows {
        cursor.grab_mode = bevy::window::CursorGrabMode::None;
        cursor.visible = true;
    }
}

/// Re-locks the cursor when returning to [`PauseMenuState::Playing`].
///
/// Called as a plain function (not a system) from [`escape_to_resume`] and
/// [`handle_pause_buttons`] so that cursor re-lock and state transition happen
/// in the same frame without a one-frame gap.
fn lock_cursor(windows: &mut Query<&mut bevy::window::CursorOptions>) {
    for mut cursor in windows.iter_mut() {
        cursor.grab_mode = bevy::window::CursorGrabMode::Locked;
        cursor.visible = false;
    }
}

// ─── Toggle pause ─────────────────────────────────────────────────────────────

/// Transitions from `Playing` → `Paused` when Escape is pressed.
///
/// Runs only in [`PauseMenuState::Playing`]. Also fires a
/// [`SfxEvent::PauseOpen`] sound request.
fn toggle_pause(
    keys: Res<ButtonInput<KeyCode>>,
    mut next: ResMut<NextState<PauseMenuState>>,
    mut sfx: MessageWriter<SfxRequest>,
) {
    if keys.just_pressed(KeyCode::Escape) {
        next.set(PauseMenuState::Paused);
        sfx.write(SfxRequest {
            event: SfxEvent::PauseOpen,
            position: None,
        });
    }
}

/// Transitions from `Paused` → `Playing` when Escape is pressed.
///
/// Runs only in [`PauseMenuState::Paused`]. Re-locks the cursor via
/// [`lock_cursor`] in the same frame and fires [`SfxEvent::PauseClose`].
fn escape_to_resume(
    keys: Res<ButtonInput<KeyCode>>,
    mut next: ResMut<NextState<PauseMenuState>>,
    mut windows: Query<&mut bevy::window::CursorOptions>,
    mut sfx: MessageWriter<SfxRequest>,
) {
    if keys.just_pressed(KeyCode::Escape) {
        next.set(PauseMenuState::Playing);
        lock_cursor(&mut windows);
        sfx.write(SfxRequest {
            event: SfxEvent::PauseClose,
            position: None,
        });
    }
}

// ─── Spawn helpers ────────────────────────────────────────────────────────────

fn spawn_btn<C: Component>(
    parent: &mut ChildSpawnerCommands,
    label: &str,
    action: C,
    width: f32,
    height: f32,
    font: Handle<Font>,
) {
    parent
        .spawn((
            action,
            Button,
            Node {
                width: Val::Px(width),
                height: Val::Px(height),
                justify_content: JustifyContent::Center,
                align_items: AlignItems::Center,
                ..default()
            },
            BackgroundColor(BTN_NORMAL),
        ))
        .with_children(|b| {
            b.spawn((
                Text::new(label),
                TextFont {
                    font,
                    font_size: 20.0,
                    ..default()
                },
                TextColor(Color::WHITE),
            ));
        });
}

fn overlay_node() -> (Node, BackgroundColor) {
    (
        Node {
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            flex_direction: FlexDirection::Column,
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            row_gap: Val::Px(14.0),
            ..default()
        },
        BackgroundColor(OVERLAY),
    )
}

// ─── Pause menu ───────────────────────────────────────────────────────────────

/// Spawns the pause menu overlay when entering [`PauseMenuState::Paused`].
///
/// Builds a full-screen semi-transparent overlay with three buttons: Resume,
/// Settings, and Quit. Runs via `OnEnter(Paused)`.
fn spawn_pause_menu(mut commands: Commands, config: Res<PauseMenuConfig>) {
    let (node, bg) = overlay_node();
    commands
        .spawn((PauseMenuRoot, node, bg))
        .with_children(|p| {
            p.spawn((
                Text::new("PAUSED"),
                TextFont {
                    font: config.font.clone(),
                    font_size: 52.0,
                    ..default()
                },
                TextColor(Color::WHITE),
                Node {
                    margin: UiRect::bottom(Val::Px(28.0)),
                    ..default()
                },
            ));
            spawn_btn(
                p,
                "Resume",
                PauseButton::Resume,
                280.0,
                52.0,
                config.font.clone(),
            );
            spawn_btn(
                p,
                "Settings",
                PauseButton::Settings,
                280.0,
                52.0,
                config.font.clone(),
            );
            spawn_btn(
                p,
                "Quit",
                PauseButton::Quit,
                280.0,
                52.0,
                config.font.clone(),
            );
        });
}

/// Despawns the pause menu overlay when leaving [`PauseMenuState::Paused`].
///
/// Runs via `OnExit(Paused)`, which fires for both `Paused → Playing` and
/// `Paused → Settings` transitions.
fn despawn_pause_menu(mut commands: Commands, q: Query<Entity, With<PauseMenuRoot>>) {
    for e in &q {
        commands.entity(e).despawn();
    }
}

/// Handles hover/press styling and click actions for pause menu buttons.
///
/// Runs every frame in [`PauseMenuState::Paused`]. Updates button background
/// colors on hover and press, then on `Pressed` dispatches: Resume → `Playing`
/// (re-locks cursor), Settings → `Settings`, Quit → [`AppExit`].
fn handle_pause_buttons(
    mut q: Query<
        (&Interaction, &mut BackgroundColor, &PauseButton),
        (Changed<Interaction>, With<Button>),
    >,
    mut next: ResMut<NextState<PauseMenuState>>,
    mut windows: Query<&mut bevy::window::CursorOptions>,
    mut app_exit: MessageWriter<AppExit>,
    mut sfx: MessageWriter<SfxRequest>,
) {
    for (interaction, mut bg, action) in &mut q {
        *bg = BackgroundColor(match interaction {
            Interaction::Hovered => BTN_HOVERED,
            Interaction::Pressed => BTN_PRESSED,
            Interaction::None => BTN_NORMAL,
        });
        if *interaction != Interaction::Pressed {
            continue;
        }
        match action {
            PauseButton::Resume => {
                next.set(PauseMenuState::Playing);
                lock_cursor(&mut windows);
                sfx.write(SfxRequest {
                    event: SfxEvent::PauseClose,
                    position: None,
                });
            }
            PauseButton::Settings => next.set(PauseMenuState::Settings),
            PauseButton::Quit => {
                app_exit.write(AppExit::Success);
            }
        }
    }
}

// ─── Settings menu ────────────────────────────────────────────────────────────

/// Spawns the settings overlay when entering [`PauseMenuState::Settings`].
///
/// Reads the current FOV from the [`Camera3d`] projection, the current SFX
/// volume from [`SfxConfig`], the render distance from [`WorldConfig`], and the
/// mouse sensitivity from [`PlayerConfig`] to initialise the slider labels.
/// Runs via `OnEnter(Settings)`.
fn spawn_settings_menu(
    mut commands: Commands,
    sfx_config: Res<SfxConfig>,
    world_config: Option<Res<WorldConfig>>,
    player_config: Option<Res<PlayerConfig>>,
    camera_q: Query<&Projection, With<Camera3d>>,
    config: Res<PauseMenuConfig>,
) {
    let fov_deg = camera_q
        .single()
        .ok()
        .and_then(|p| {
            if let Projection::Perspective(pp) = p {
                Some(pp.fov.to_degrees())
            } else {
                None
            }
        })
        .unwrap_or(90.0);
    let volume_pct = sfx_config.volume * 100.0;
    let render_dist_chunks = world_config
        .as_ref()
        .map(|wc| ((wc.load_distance / 16.0).round() as i32).clamp(4, 32) as i32)
        .unwrap_or(10);
    // Round to nearest even
    let render_dist_chunks = if render_dist_chunks % 2 == 0 {
        render_dist_chunks
    } else {
        render_dist_chunks + 1
    };
    let sensitivity_pct = player_config
        .as_ref()
        .map(|pc| ((pc.sensitivity * 100.0).round() as i32).clamp(10, 100))
        .unwrap_or(100);

    let (node, bg) = overlay_node();
    commands
        .spawn((SettingsMenuRoot, node, bg))
        .with_children(|p| {
            p.spawn((
                Text::new("SETTINGS"),
                TextFont {
                    font: config.font.clone(),
                    font_size: 42.0,
                    ..default()
                },
                TextColor(Color::WHITE),
                Node {
                    margin: UiRect::bottom(Val::Px(20.0)),
                    ..default()
                },
            ));

            spawn_slider_row(
                p,
                "Field of View",
                format!("{fov_deg:.0}°"),
                FovLabel,
                SettingsButton::FovDec,
                SettingsButton::FovInc,
                config.font.clone(),
                config.symbol_font.clone(),
            );

            spawn_slider_row(
                p,
                "SFX Volume",
                format!("{volume_pct:.0}%"),
                VolumeLabel,
                SettingsButton::VolumeDec,
                SettingsButton::VolumeInc,
                config.font.clone(),
                config.symbol_font.clone(),
            );

            spawn_slider_row(
                p,
                "Render Distance",
                format!("{render_dist_chunks} chunks"),
                RenderDistLabel,
                SettingsButton::RenderDistDec,
                SettingsButton::RenderDistInc,
                config.font.clone(),
                config.symbol_font.clone(),
            );

            spawn_slider_row(
                p,
                "Sensitivity",
                format!("{sensitivity_pct:.0}%"),
                SensitivityLabel,
                SettingsButton::SensitivityDec,
                SettingsButton::SensitivityInc,
                config.font.clone(),
                config.symbol_font.clone(),
            );

            p.spawn(Node {
                margin: UiRect::top(Val::Px(20.0)),
                ..default()
            })
            .with_children(|row| {
                spawn_btn(
                    row,
                    "< Back",
                    SettingsButton::Back,
                    200.0,
                    50.0,
                    config.font.clone(),
                );
            });
        });
}

fn spawn_slider_row<L: Component, D: Component, I: Component>(
    parent: &mut ChildSpawnerCommands,
    label: &str,
    value: String,
    value_marker: L,
    dec: D,
    inc: I,
    font: Handle<Font>,
    symbol_font: Handle<Font>,
) {
    parent
        .spawn(Node {
            flex_direction: FlexDirection::Row,
            align_items: AlignItems::Center,
            column_gap: Val::Px(12.0),
            ..default()
        })
        .with_children(|row| {
            row.spawn((
                Text::new(label),
                TextFont {
                    font: font.clone(),
                    font_size: 20.0,
                    ..default()
                },
                TextColor(Color::srgb(0.8, 0.8, 0.8)),
                Node {
                    width: Val::Px(200.0),
                    ..default()
                },
            ));
            spawn_btn(row, "\u{25C0}", dec, 44.0, 44.0, symbol_font.clone());
            row.spawn((
                value_marker,
                Text::new(value),
                TextFont {
                    font: font.clone(),
                    font_size: 22.0,
                    ..default()
                },
                TextColor(Color::WHITE),
                Node {
                    width: Val::Px(80.0),
                    justify_content: JustifyContent::Center,
                    ..default()
                },
            ));
            spawn_btn(row, "\u{25B6}", inc, 44.0, 44.0, symbol_font);
        });
}

/// Despawns the settings overlay when leaving [`PauseMenuState::Settings`].
///
/// Runs via `OnExit(Settings)`. The only exit transition is `Settings → Paused`
/// via the Back button.
fn despawn_settings_menu(mut commands: Commands, q: Query<Entity, With<SettingsMenuRoot>>) {
    for e in &q {
        commands.entity(e).despawn();
    }
}

/// Handles hover/press styling and click actions for settings menu buttons.
///
/// Runs every frame in [`PauseMenuState::Settings`]. Adjusts values on press:
/// - `FovInc` / `FovDec`: changes FOV by ±5° (clamped `50°`–`120°`) and updates
///   [`FovLabel`] text and the [`Camera3d`] perspective projection.
/// - `VolumeInc` / `VolumeDec`: changes [`SfxConfig::volume`] by ±0.1 (clamped
///   `0.0`–`1.0`) and updates [`VolumeLabel`] text.
/// - `RenderDistInc` / `RenderDistDec`: changes [`WorldConfig::load_distance`] by
///   ±2 chunks (clamped `4`–`32`) and updates [`RenderDistLabel`] text and
///   [`ChunkManager`] distances.
/// - `SensitivityInc` / `SensitivityDec`: changes [`PlayerConfig::sensitivity`] by
///   ±1% (clamped `10`–`100`) and updates [`SensitivityLabel`] text.
/// - `Back`: emits [`SaveSettingsRequest`] and transitions to [`PauseMenuState::Paused`].
#[allow(clippy::too_many_arguments)]
fn handle_settings_buttons(
    mut q: Query<
        (&Interaction, &mut BackgroundColor, &SettingsButton),
        (Changed<Interaction>, With<Button>),
    >,
    mut sfx_config: ResMut<SfxConfig>,
    mut world_config: Option<ResMut<WorldConfig>>,
    mut chunk_manager: Option<ResMut<ChunkManager>>,
    mut player_config: Option<ResMut<PlayerConfig>>,
    mut next: ResMut<NextState<PauseMenuState>>,
    mut fov_label: Query<
        &mut Text,
        (
            With<FovLabel>,
            Without<VolumeLabel>,
            Without<RenderDistLabel>,
            Without<SensitivityLabel>,
        ),
    >,
    mut vol_label: Query<
        &mut Text,
        (
            With<VolumeLabel>,
            Without<FovLabel>,
            Without<RenderDistLabel>,
            Without<SensitivityLabel>,
        ),
    >,
    mut rdist_label: Query<
        &mut Text,
        (
            With<RenderDistLabel>,
            Without<FovLabel>,
            Without<VolumeLabel>,
            Without<SensitivityLabel>,
        ),
    >,
    mut sens_label: Query<
        &mut Text,
        (
            With<SensitivityLabel>,
            Without<FovLabel>,
            Without<VolumeLabel>,
            Without<RenderDistLabel>,
        ),
    >,
    mut camera_q: Query<&mut Projection, With<Camera3d>>,
    mut save_writer: MessageWriter<SaveSettingsRequest>,
) {
    for (interaction, mut bg, action) in &mut q {
        *bg = BackgroundColor(match interaction {
            Interaction::Hovered => BTN_HOVERED,
            Interaction::Pressed => BTN_PRESSED,
            Interaction::None => BTN_NORMAL,
        });
        if *interaction != Interaction::Pressed {
            continue;
        }

        match action {
            SettingsButton::FovInc | SettingsButton::FovDec => {
                if let Ok(mut proj) = camera_q.single_mut() {
                    if let Projection::Perspective(ref mut pp) = *proj {
                        let delta = if matches!(action, SettingsButton::FovInc) {
                            5.0
                        } else {
                            -5.0
                        };
                        let new_fov = (pp.fov.to_degrees() + delta).clamp(50.0, 120.0);
                        pp.fov = new_fov.to_radians();
                        if let Ok(mut t) = fov_label.single_mut() {
                            **t = format!("{new_fov:.0}°");
                        }
                    }
                }
            }
            SettingsButton::VolumeInc | SettingsButton::VolumeDec => {
                let delta = if matches!(action, SettingsButton::VolumeInc) {
                    0.1
                } else {
                    -0.1
                };
                sfx_config.volume = (sfx_config.volume + delta).clamp(0.0, 1.0);
                let pct = sfx_config.volume * 100.0;
                if let Ok(mut t) = vol_label.single_mut() {
                    **t = format!("{pct:.0}%");
                }
            }
            SettingsButton::RenderDistInc | SettingsButton::RenderDistDec => {
                if let Some(ref mut wc) = world_config {
                    // Current value in chunks (rounded to nearest even)
                    let current = ((wc.load_distance / 16.0).round() as i32).clamp(4, 32);
                    let current = if current % 2 == 0 {
                        current
                    } else {
                        current + 1
                    };
                    let delta: i32 = if matches!(action, SettingsButton::RenderDistInc) {
                        2
                    } else {
                        -2
                    };
                    let new_chunks = (current + delta).clamp(4, 32);
                    wc.load_distance = new_chunks as f32 * 16.0;
                    wc.unload_distance = wc.load_distance + 32.0;
                    if let Some(ref mut cm) = chunk_manager {
                        cm.load_distance = wc.load_distance;
                        cm.unload_distance = wc.unload_distance;
                    }
                    if let Ok(mut t) = rdist_label.single_mut() {
                        **t = format!("{new_chunks} chunks");
                    }
                }
            }
            SettingsButton::SensitivityInc | SettingsButton::SensitivityDec => {
                if let Some(ref mut pc) = player_config {
                    let current_pct = (pc.sensitivity * 100.0).round() as i32;
                    let delta: i32 = if matches!(action, SettingsButton::SensitivityInc) {
                        1
                    } else {
                        -1
                    };
                    let new_pct = (current_pct + delta).clamp(10, 100);
                    pc.sensitivity = new_pct as f32 / 100.0;
                    if let Ok(mut t) = sens_label.single_mut() {
                        **t = format!("{new_pct:.0}%");
                    }
                }
            }
            SettingsButton::Back => {
                save_writer.write(SaveSettingsRequest);
                next.set(PauseMenuState::Paused);
            }
        }
    }
}