Skip to main content

voxel_framework/ui/
mod.rs

1//! HUD overlay plugins for voxel game user interfaces.
2//!
3//! This module provides four legacy overlay plugins plus the explicit,
4//! author-defined [`VoxelHudPlugin`]. Each plugin is self-contained and can be
5//! added independently; [`UiPlugin`] remains an umbrella for only the four
6//! existing overlays and does not add [`VoxelHudPlugin`].
7//!
8//! # Available plugins
9//!
10//! | Plugin | What it provides |
11//! |--------|-----------------|
12//! | [`CrosshairPlugin`] | Center-screen crosshair rendered as four `Node` quads |
13//! | [`LoadingScreenPlugin`] | Full-screen overlay with progress bar while the world loads |
14//! | `HotbarUiPlugin` *(feature `items`)* | Bottom-center row of inventory slots |
15#![cfg_attr(
16    feature = "items",
17    doc = "| [`PickupNotificationPlugin`] | Timed top-right pop-up text on item pickup |"
18)]
19#![cfg_attr(
20    not(feature = "items"),
21    doc = "| `PickupNotificationPlugin` *(feature `items`)* | Timed top-right pop-up text on item pickup |"
22)]
23//! | [`VoxelHudPlugin`] | Retained, game-neutral text, bar, icon, and segment elements |
24//!
25//! # Choosing between [`UiPlugin`] and individual plugins
26//!
27#![cfg_attr(
28    feature = "items",
29    doc = "Use [`UiPlugin`] when your game uses [`DefaultItem`] and wants all four HUD elements with zero configuration:"
30)]
31#![cfg_attr(
32    not(feature = "items"),
33    doc = "Use [`UiPlugin`] with the default `items` feature when your game uses `DefaultItem` and wants all four HUD elements with zero configuration:"
34)]
35//!
36//! ```rust,no_run
37//! use bevy::prelude::*;
38//! use voxel_framework::ui::UiPlugin;
39//!
40//! App::new().add_plugins(UiPlugin);
41//! ```
42//!
43//! Use individual plugins when you need a custom item type for pickup
44//! notifications, want to omit specific HUD elements, or need to insert
45//! configuration resources before the plugin initializes them:
46//!
47//! ```rust,no_run
48//! use bevy::prelude::*;
49//! use voxel_framework::ui::{CrosshairPlugin, CrosshairConfig};
50//!
51//! App::new()
52//!     .insert_resource(CrosshairConfig {
53//!         color: [1.0, 0.3, 0.3, 1.0],
54//!         size: 14.0,
55//!         ..Default::default()
56//!     })
57//!     .add_plugins(CrosshairPlugin);
58//!
59//! // With the default `items` feature enabled, you can also add `HotbarUiPlugin`.
60//! ```
61//!
62//! # Pause menu
63//!
64//! The optional [`PauseMenuPlugin`] lives in the
65//! `pause_menu` submodule and is re-exported from this module. It is **not**
66//! included in [`UiPlugin`] because it manages its own [`PauseMenuState`] and
67//! cursor lifetime, which must be coordinated with your game's state machine.
68
69use bevy::prelude::*;
70
71#[cfg(feature = "items")]
72use crate::items::hotbar::{HotbarSelectionChanged, HotbarState};
73#[cfg(feature = "items")]
74use crate::items::inventory::ItemPickedUp;
75#[cfg(feature = "items")]
76use crate::items::inventory::ItemType;
77use crate::world::loading::{LoadingProgress, WorldLoadingState};
78
79/// Author-defined, game-neutral HUD data model and stores.
80pub mod hud;
81pub use hud::{
82    HudAnchor, HudBar, HudBindingKind, HudDefinitionError, HudDiagnostic, HudDiagnosticKind,
83    HudElementDefinition, HudElementId, HudElementSnapshot, HudIcon, HudIconSource, HudPlacement,
84    HudPresentation, HudRegistry, HudRegistryError, HudScalar, HudScalarField, HudSegments,
85    HudStackDirection, HudStyleOverride, HudSystemSet, HudText, HudTheme, HudValue,
86    HudValueChanged, HudValueError, HudValueId, HudValueKind, HudValueSet, HudValueSnapshot,
87    MAX_HUD_SEGMENTS, VoxelHudPlugin, remove_hud_value, set_hud_value,
88};
89
90// ─── Crosshair ────────────────────────────────────────────────────────────────
91
92/// Visual configuration for the [`CrosshairPlugin`] overlay.
93///
94/// Insert this resource before adding [`CrosshairPlugin`] to override any
95/// default. The crosshair is spawned once on `Startup`; changes made after
96/// that point have no effect unless you despawn and re-spawn the crosshair
97/// nodes.
98///
99/// # Default values
100///
101/// | Field       | Default              | Notes |
102/// |-------------|----------------------|-------|
103/// | `color`     | `[1,1,1,1]` (white)  | RGBA, linear |
104/// | `size`      | `20.0` px            | Half-length of each arm |
105/// | `gap`       | `4.0` px             | Empty space between center and arm start |
106/// | `thickness` | `2.0` px             | Width of each arm quad |
107/// | `visible`   | `true`               | `false` skips spawning entirely |
108#[derive(Resource, Debug, Clone)]
109pub struct CrosshairConfig {
110    /// RGBA color of the four crosshair arm quads in linear sRGB.
111    /// Alpha controls overall transparency of the overlay.
112    pub color: [f32; 4],
113    /// Half-length of each arm in logical (UI) pixels. The total visual width
114    /// of the crosshair is approximately `2 × (gap + size)`.
115    pub size: f32,
116    /// Empty gap in logical pixels between the screen center and the start of
117    /// each arm. Increase this to leave a clear center dot.
118    pub gap: f32,
119    /// Width of each arm quad in logical pixels. Thicker values (`4.0`–`6.0`)
120    /// are easier to see on busy backgrounds.
121    pub thickness: f32,
122    /// When `false`, [`CrosshairPlugin`] returns early from `spawn_crosshair`
123    /// without creating any entities. Useful for games that manage their own
124    /// reticle or disable the crosshair entirely in certain modes.
125    pub visible: bool,
126}
127
128impl Default for CrosshairConfig {
129    fn default() -> Self {
130        Self {
131            color: [1.0, 1.0, 1.0, 1.0],
132            size: 20.0,
133            gap: 4.0,
134            thickness: 2.0,
135            visible: true,
136        }
137    }
138}
139
140/// Marker component for crosshair quad entities.
141#[derive(Component)]
142struct CrosshairNode;
143
144fn spawn_crosshair(mut commands: Commands, config: Res<CrosshairConfig>) {
145    if !config.visible {
146        return;
147    }
148
149    let c = &*config;
150    let color = Color::srgba(c.color[0], c.color[1], c.color[2], c.color[3]);
151
152    // Root container — full screen, no interaction, just a layout anchor.
153    commands
154        .spawn((
155            CrosshairNode,
156            Node {
157                width: Val::Percent(100.0),
158                height: Val::Percent(100.0),
159                position_type: PositionType::Absolute,
160                justify_content: JustifyContent::Center,
161                align_items: AlignItems::Center,
162                ..default()
163            },
164            BackgroundColor(Color::NONE),
165        ))
166        .with_children(|root| {
167            // Left arm
168            root.spawn((
169                CrosshairNode,
170                Node {
171                    position_type: PositionType::Absolute,
172                    width: Val::Px(c.size),
173                    height: Val::Px(c.thickness),
174                    right: Val::Px(c.gap + c.size / 2.0 + c.size / 2.0),
175                    top: Val::Px(-c.thickness / 2.0),
176                    ..default()
177                },
178                BackgroundColor(color),
179            ));
180            // Right arm
181            root.spawn((
182                CrosshairNode,
183                Node {
184                    position_type: PositionType::Absolute,
185                    width: Val::Px(c.size),
186                    height: Val::Px(c.thickness),
187                    left: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
188                    top: Val::Px(-c.thickness / 2.0),
189                    ..default()
190                },
191                BackgroundColor(color),
192            ));
193            // Top arm
194            root.spawn((
195                CrosshairNode,
196                Node {
197                    position_type: PositionType::Absolute,
198                    width: Val::Px(c.thickness),
199                    height: Val::Px(c.size),
200                    left: Val::Px(-c.thickness / 2.0),
201                    bottom: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
202                    ..default()
203                },
204                BackgroundColor(color),
205            ));
206            // Bottom arm
207            root.spawn((
208                CrosshairNode,
209                Node {
210                    position_type: PositionType::Absolute,
211                    width: Val::Px(c.thickness),
212                    height: Val::Px(c.size),
213                    left: Val::Px(-c.thickness / 2.0),
214                    top: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
215                    ..default()
216                },
217                BackgroundColor(color),
218            ));
219        });
220}
221
222/// Plugin that renders a fixed center-screen crosshair using four UI quads.
223///
224/// The crosshair is built from four [`Node`] rectangles (left, right, top,
225/// bottom arms) positioned with `PositionType::Absolute` relative to a full-
226/// screen container. No images or asset loading are required.
227///
228/// Customize appearance by inserting [`CrosshairConfig`] before adding this
229/// plugin. If [`CrosshairConfig::visible`] is `false`, no entities are spawned.
230///
231/// # Example
232///
233/// ```rust,no_run
234/// use bevy::prelude::*;
235/// use voxel_framework::ui::{CrosshairPlugin, CrosshairConfig};
236///
237/// App::new()
238///     .insert_resource(CrosshairConfig {
239///         color: [0.0, 1.0, 0.0, 0.9],
240///         gap: 6.0,
241///         ..Default::default()
242///     })
243///     .add_plugins(CrosshairPlugin);
244/// ```
245pub struct CrosshairPlugin;
246
247impl Plugin for CrosshairPlugin {
248    fn build(&self, app: &mut App) {
249        app.init_resource::<CrosshairConfig>();
250        app.add_systems(Startup, spawn_crosshair);
251    }
252}
253
254// ─── Loading Screen ───────────────────────────────────────────────────────────
255
256/// Visual configuration for the [`LoadingScreenPlugin`] overlay.
257///
258/// Insert this resource before adding [`LoadingScreenPlugin`] to override
259/// defaults. Values are read once on `Startup` when the overlay is spawned.
260///
261/// # Default values
262///
263/// | Field              | Default                                   |
264/// |--------------------|-------------------------------------------|
265/// | `background_color` | `[0.05, 0.05, 0.05, 0.95]` (near-black)  |
266/// | `text_color`       | `[1, 1, 1, 1]` (white)                    |
267/// | `title`            | `"Loading..."`                             |
268/// | `show_progress_bar`| `true`                                    |
269#[derive(Resource, Debug, Clone)]
270pub struct LoadingScreenConfig {
271    /// RGBA background color of the full-screen overlay in linear sRGB. The
272    /// default near-black with high alpha (`0.95`) fully obscures the 3D scene
273    /// while the world loads.
274    pub background_color: [f32; 4],
275    /// RGBA color of the loading title text in linear sRGB.
276    pub text_color: [f32; 4],
277    /// Text displayed in the center of the overlay. Updated dynamically with
278    /// `"Loading… X/Y chunks"` as [`LoadingProgress`] messages arrive.
279    pub title: String,
280    /// When `true`, a 400×20 px progress bar is rendered below the title text.
281    /// The bar fill advances from 0 % to 100 % as [`LoadingProgress::progress`]
282    /// increases from `0.0` to `1.0`.
283    pub show_progress_bar: bool,
284}
285
286impl Default for LoadingScreenConfig {
287    fn default() -> Self {
288        Self {
289            background_color: [0.05, 0.05, 0.05, 0.95],
290            text_color: [1.0, 1.0, 1.0, 1.0],
291            title: "Loading...".to_string(),
292            show_progress_bar: true,
293        }
294    }
295}
296
297/// Marker for the loading overlay root.
298#[derive(Component)]
299struct LoadingOverlay;
300
301/// Marker for the loading text entity.
302#[derive(Component)]
303struct LoadingText;
304
305/// Marker for the progress bar fill entity.
306#[derive(Component)]
307struct LoadingProgressBar;
308
309fn spawn_loading_overlay(mut commands: Commands, config: Res<LoadingScreenConfig>) {
310    let bg = Color::srgba(
311        config.background_color[0],
312        config.background_color[1],
313        config.background_color[2],
314        config.background_color[3],
315    );
316    let tc = Color::srgba(
317        config.text_color[0],
318        config.text_color[1],
319        config.text_color[2],
320        config.text_color[3],
321    );
322
323    commands
324        .spawn((
325            LoadingOverlay,
326            Node {
327                width: Val::Percent(100.0),
328                height: Val::Percent(100.0),
329                position_type: PositionType::Absolute,
330                flex_direction: FlexDirection::Column,
331                justify_content: JustifyContent::Center,
332                align_items: AlignItems::Center,
333                ..default()
334            },
335            BackgroundColor(bg),
336            ZIndex(100),
337        ))
338        .with_children(|parent| {
339            // Title + progress text
340            parent.spawn((
341                LoadingText,
342                Text::new(config.title.clone()),
343                TextFont {
344                    font_size: 32.0,
345                    ..default()
346                },
347                TextColor(tc),
348            ));
349
350            if config.show_progress_bar {
351                // Progress bar background
352                parent
353                    .spawn((
354                        Node {
355                            width: Val::Px(400.0),
356                            height: Val::Px(20.0),
357                            margin: UiRect::top(Val::Px(20.0)),
358                            ..default()
359                        },
360                        BackgroundColor(Color::srgba(0.2, 0.2, 0.2, 1.0)),
361                    ))
362                    .with_children(|bar| {
363                        // Fill
364                        bar.spawn((
365                            LoadingProgressBar,
366                            Node {
367                                width: Val::Percent(0.0),
368                                height: Val::Percent(100.0),
369                                ..default()
370                            },
371                            BackgroundColor(Color::srgba(0.2, 0.7, 0.3, 1.0)),
372                        ));
373                    });
374            }
375        });
376}
377
378fn update_loading_overlay(
379    loading_state: Res<WorldLoadingState>,
380    mut progress_reader: bevy::ecs::message::MessageReader<LoadingProgress>,
381    mut overlay_query: Query<&mut Visibility, With<LoadingOverlay>>,
382    mut text_query: Query<&mut Text, With<LoadingText>>,
383    mut bar_query: Query<&mut Node, With<LoadingProgressBar>>,
384) {
385    // Hide overlay once world is ready
386    if loading_state.ready {
387        if let Ok(mut vis) = overlay_query.single_mut() {
388            *vis = Visibility::Hidden;
389        }
390        return;
391    }
392
393    // Process latest progress message
394    let mut latest: Option<LoadingProgress> = None;
395    for msg in progress_reader.read() {
396        latest = Some(msg.clone());
397    }
398
399    if let Some(progress) = latest {
400        // Update text
401        if let Ok(mut text) = text_query.single_mut() {
402            *text = Text::new(format!(
403                "Loading... {}/{} chunks",
404                progress.loaded, progress.total
405            ));
406        }
407
408        // Update progress bar width
409        if let Ok(mut node) = bar_query.single_mut() {
410            node.width = Val::Percent((progress.progress * 100.0).clamp(0.0, 100.0));
411        }
412    }
413}
414
415fn despawn_loading_overlay_on_ready(
416    mut commands: Commands,
417    loading_state: Res<WorldLoadingState>,
418    overlay_query: Query<Entity, With<LoadingOverlay>>,
419) {
420    if loading_state.ready {
421        for entity in overlay_query.iter() {
422            commands.entity(entity).despawn();
423        }
424    }
425}
426
427/// Plugin that displays a full-screen loading overlay during world generation.
428///
429/// The overlay is spawned on `Startup` and updates every frame by reading
430/// [`LoadingProgress`] messages broadcast by the chunk streaming system. Once
431/// [`WorldLoadingState::ready`] flips to `true`, the overlay is hidden and then
432/// despawned to free the UI node tree.
433///
434/// Customize appearance via [`LoadingScreenConfig`] inserted before this plugin.
435///
436/// # Example
437///
438/// ```rust,no_run
439/// use bevy::prelude::*;
440/// use voxel_framework::ui::{LoadingScreenPlugin, LoadingScreenConfig};
441///
442/// App::new()
443///     .insert_resource(LoadingScreenConfig {
444///         title: "Generating universe…".to_string(),
445///         show_progress_bar: false,
446///         ..Default::default()
447///     })
448///     .add_plugins(LoadingScreenPlugin);
449/// ```
450pub struct LoadingScreenPlugin;
451
452impl Plugin for LoadingScreenPlugin {
453    fn build(&self, app: &mut App) {
454        app.init_resource::<LoadingScreenConfig>();
455        app.add_systems(Startup, spawn_loading_overlay);
456        app.add_systems(
457            Update,
458            (update_loading_overlay, despawn_loading_overlay_on_ready),
459        );
460    }
461}
462
463// ─── Hotbar UI ────────────────────────────────────────────────────────────────
464//
465// Gated on the `items` feature: the hotbar UI reads `HotbarState` and listens
466// for `HotbarSelectionChanged` messages, both defined in `crate::items`.
467
468/// Visual configuration for the [`HotbarUiPlugin`] slot row.
469///
470/// Insert this resource before adding [`HotbarUiPlugin`] to customize the
471/// hotbar. Values are consumed on `Startup`; runtime slot-count changes are not
472/// supported (the hotbar is a static layout).
473///
474/// # Default values
475///
476/// | Field            | Default                             |
477/// |------------------|-------------------------------------|
478/// | `visible`        | `true`                              |
479/// | `slot_size`      | `50.0` px                           |
480/// | `slot_gap`       | `4.0` px                            |
481/// | `slot_color`     | `[0.15, 0.15, 0.15, 0.85]` (dark)  |
482/// | `selected_color` | `[0.45, 0.45, 0.45, 0.95]` (light) |
483#[cfg(feature = "items")]
484#[derive(Resource, Debug, Clone)]
485pub struct HotbarUiConfig {
486    /// When `false`, the hotbar is not spawned. Use this to disable the hotbar
487    /// entirely without removing [`HotbarUiPlugin`] from the app.
488    pub visible: bool,
489    /// Width and height of each square slot node in logical pixels.
490    pub slot_size: f32,
491    /// Horizontal gap between adjacent slot nodes in logical pixels.
492    pub slot_gap: f32,
493    /// RGBA background color applied to unselected hotbar slots in linear sRGB.
494    pub slot_color: [f32; 4],
495    /// RGBA background color applied to the currently selected slot in linear
496    /// sRGB. Updated in real time when a [`HotbarSelectionChanged`] message fires.
497    pub selected_color: [f32; 4],
498}
499
500#[cfg(feature = "items")]
501impl Default for HotbarUiConfig {
502    fn default() -> Self {
503        Self {
504            visible: true,
505            slot_size: 50.0,
506            slot_gap: 4.0,
507            slot_color: [0.15, 0.15, 0.15, 0.85],
508            selected_color: [0.45, 0.45, 0.45, 0.95],
509        }
510    }
511}
512
513/// Marker for the hotbar root container.
514#[cfg(feature = "items")]
515#[derive(Component)]
516struct HotbarUiRoot;
517
518/// Marker for individual hotbar slot nodes. Holds the slot index.
519#[cfg(feature = "items")]
520#[derive(Component)]
521struct HotbarSlot(usize);
522
523#[cfg(feature = "items")]
524fn spawn_hotbar_ui(mut commands: Commands, config: Res<HotbarUiConfig>, hotbar: Res<HotbarState>) {
525    if !config.visible {
526        return;
527    }
528
529    let slot_color = Color::srgba(
530        config.slot_color[0],
531        config.slot_color[1],
532        config.slot_color[2],
533        config.slot_color[3],
534    );
535    let selected_color = Color::srgba(
536        config.selected_color[0],
537        config.selected_color[1],
538        config.selected_color[2],
539        config.selected_color[3],
540    );
541
542    commands
543        .spawn((
544            HotbarUiRoot,
545            Node {
546                width: Val::Percent(100.0),
547                position_type: PositionType::Absolute,
548                bottom: Val::Px(16.0),
549                flex_direction: FlexDirection::Row,
550                justify_content: JustifyContent::Center,
551                align_items: AlignItems::Center,
552                column_gap: Val::Px(config.slot_gap),
553                ..default()
554            },
555            BackgroundColor(Color::NONE),
556        ))
557        .with_children(|row| {
558            for i in 0..hotbar.slots {
559                let bg = if i == hotbar.selected {
560                    selected_color
561                } else {
562                    slot_color
563                };
564                row.spawn((
565                    HotbarSlot(i),
566                    Node {
567                        width: Val::Px(config.slot_size),
568                        height: Val::Px(config.slot_size),
569                        border: UiRect::all(Val::Px(2.0)),
570                        ..default()
571                    },
572                    BackgroundColor(bg),
573                    BorderColor::all(Color::srgba(0.6, 0.6, 0.6, 0.6)),
574                ));
575            }
576        });
577}
578
579#[cfg(feature = "items")]
580fn update_hotbar_selection(
581    mut selection_reader: bevy::ecs::message::MessageReader<HotbarSelectionChanged>,
582    config: Res<HotbarUiConfig>,
583    mut slot_query: Query<(&HotbarSlot, &mut BackgroundColor)>,
584) {
585    let mut new_selected: Option<usize> = None;
586    for msg in selection_reader.read() {
587        new_selected = Some(msg.slot);
588    }
589
590    let Some(selected) = new_selected else {
591        return;
592    };
593
594    let slot_color = Color::srgba(
595        config.slot_color[0],
596        config.slot_color[1],
597        config.slot_color[2],
598        config.slot_color[3],
599    );
600    let selected_color = Color::srgba(
601        config.selected_color[0],
602        config.selected_color[1],
603        config.selected_color[2],
604        config.selected_color[3],
605    );
606
607    for (slot, mut bg) in slot_query.iter_mut() {
608        bg.0 = if slot.0 == selected {
609            selected_color
610        } else {
611            slot_color
612        };
613    }
614}
615
616/// Plugin that renders a horizontal hotbar at the bottom center of the screen.
617///
618/// Reads [`HotbarState`] on startup to determine the number of slots, spawns
619/// one [`Node`] quad per slot, and listens for [`HotbarSelectionChanged`]
620/// messages to update the selected-slot highlight in real time.
621///
622/// Customize via [`HotbarUiConfig`] inserted before this plugin.
623///
624/// # Example
625///
626/// ```rust,no_run
627/// use bevy::prelude::*;
628/// use voxel_framework::ui::{HotbarUiPlugin, HotbarUiConfig};
629///
630/// App::new()
631///     .insert_resource(HotbarUiConfig {
632///         slot_size: 64.0,
633///         slot_gap: 6.0,
634///         ..Default::default()
635///     })
636///     .add_plugins(HotbarUiPlugin);
637/// ```
638#[cfg(feature = "items")]
639pub struct HotbarUiPlugin;
640
641#[cfg(feature = "items")]
642impl Plugin for HotbarUiPlugin {
643    fn build(&self, app: &mut App) {
644        app.init_resource::<HotbarUiConfig>();
645        app.add_systems(Startup, spawn_hotbar_ui);
646        app.add_systems(Update, update_hotbar_selection);
647    }
648}
649
650// ─── Pickup Notification ──────────────────────────────────────────────────────
651//
652// Gated on the `items` feature: the pickup notification system listens for
653// `ItemPickedUp<I>` messages and is meaningless without an item palette.
654
655/// Visual configuration for the [`PickupNotificationPlugin`] pop-up system.
656///
657/// Insert this resource before adding [`PickupNotificationPlugin`] to override
658/// defaults. Configuration is read once per notification spawn.
659///
660/// # Default values
661///
662/// | Field               | Default              |
663/// |---------------------|----------------------|
664/// | `visible`           | `true`               |
665/// | `duration_secs`     | `3.0` s              |
666/// | `text_color`        | `[1, 1, 1, 1]` (white) |
667/// | `max_notifications` | `5`                  |
668#[cfg(feature = "items")]
669#[derive(Resource, Debug, Clone)]
670pub struct PickupNotificationConfig {
671    /// When `false`, no notification entities are spawned even when
672    /// [`ItemPickedUp`] messages fire.
673    pub visible: bool,
674    /// How long each notification text persists on screen in seconds before
675    /// being automatically despawned. Applied per-notification via a
676    /// [`Timer`].
677    pub duration_secs: f32,
678    /// RGBA color of the notification text in linear sRGB.
679    pub text_color: [f32; 4],
680    /// Maximum number of notifications displayed at the same time. When a new
681    /// pickup would exceed this limit, the oldest visible notification is
682    /// despawned first to make room.
683    pub max_notifications: usize,
684}
685
686#[cfg(feature = "items")]
687impl Default for PickupNotificationConfig {
688    fn default() -> Self {
689        Self {
690            visible: true,
691            duration_secs: 3.0,
692            text_color: [1.0, 1.0, 1.0, 1.0],
693            max_notifications: 5,
694        }
695    }
696}
697
698/// Timer component on each notification entity.
699#[cfg(feature = "items")]
700#[derive(Component)]
701struct NotificationTimer(Timer);
702
703/// Marker for the notification container.
704#[cfg(feature = "items")]
705#[derive(Component)]
706struct NotificationContainer;
707
708#[cfg(feature = "items")]
709fn spawn_notification_container(mut commands: Commands) {
710    commands.spawn((
711        NotificationContainer,
712        Node {
713            position_type: PositionType::Absolute,
714            top: Val::Px(16.0),
715            right: Val::Px(16.0),
716            flex_direction: FlexDirection::Column,
717            row_gap: Val::Px(4.0),
718            align_items: AlignItems::FlexEnd,
719            ..default()
720        },
721        BackgroundColor(Color::NONE),
722    ));
723}
724
725#[cfg(feature = "items")]
726fn on_item_picked_up<I: ItemType>(
727    mut commands: Commands,
728    mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
729    config: Res<PickupNotificationConfig>,
730    container_query: Query<Entity, With<NotificationContainer>>,
731    existing_query: Query<Entity, With<NotificationTimer>>,
732) {
733    if !config.visible {
734        return;
735    }
736
737    // Collect all pickups this frame
738    let pickups: Vec<(String, u32)> = pickup_reader
739        .read()
740        .map(|p| (p.item.name().to_string(), p.count))
741        .collect();
742
743    if pickups.is_empty() {
744        return;
745    }
746
747    let Ok(container) = container_query.single() else {
748        return;
749    };
750
751    let tc = Color::srgba(
752        config.text_color[0],
753        config.text_color[1],
754        config.text_color[2],
755        config.text_color[3],
756    );
757
758    // Enforce max_notifications — despawn oldest first
759    let existing: Vec<Entity> = existing_query.iter().collect();
760    let available = config.max_notifications.saturating_sub(existing.len());
761    let spawn_count = pickups.len().min(available);
762
763    if existing.len() + pickups.len() > config.max_notifications {
764        let overflow = (existing.len() + pickups.len()).saturating_sub(config.max_notifications);
765        for entity in existing.iter().take(overflow) {
766            commands.entity(*entity).despawn();
767        }
768    }
769
770    for (name, count) in pickups.iter().take(spawn_count) {
771        let label = format!("+{count} {name}");
772        let notification = commands
773            .spawn((
774                NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once)),
775                Text::new(label),
776                TextFont {
777                    font_size: 18.0,
778                    ..default()
779                },
780                TextColor(tc),
781                Node { ..default() },
782            ))
783            .id();
784        commands.entity(container).add_child(notification);
785    }
786}
787
788#[cfg(feature = "items")]
789fn tick_notifications(
790    mut commands: Commands,
791    time: Res<Time>,
792    mut query: Query<(Entity, &mut NotificationTimer)>,
793) {
794    for (entity, mut timer) in query.iter_mut() {
795        timer.0.tick(time.delta());
796        if timer.0.just_finished() {
797            commands.entity(entity).despawn();
798        }
799    }
800}
801
802/// Plugin that displays timed item-pickup notifications at the top-right corner.
803///
804/// Listens for [`ItemPickedUp<I>`] messages and spawns a text node formatted as
805/// `"+N ItemName"` for each pickup. Notifications fade out after
806/// [`PickupNotificationConfig::duration_secs`] and are despawned automatically.
807///
808/// When the number of simultaneous notifications would exceed
809/// [`PickupNotificationConfig::max_notifications`], the oldest notifications are
810/// despawned first.
811///
812/// The plugin is **generic over the item type** `I: ItemType`. Use [`UiPlugin`]
813/// for the built-in [`DefaultItem`], or add this plugin manually with a custom
814/// item type:
815///
816/// ```rust,no_run
817/// use bevy::prelude::*;
818/// use voxel_framework::ui::PickupNotificationPlugin;
819/// # use voxel_framework::items::inventory::ItemType;
820/// # #[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
821/// # struct MyItem;
822/// # impl ItemType for MyItem {
823/// #     fn name(&self) -> &'static str { "item" }
824/// #     fn color(&self) -> [f32; 4] { [1.0, 1.0, 1.0, 1.0] }
825/// #     fn to_byte(&self) -> u8 { 0 }
826/// #     fn from_byte(_: u8) -> Self { Self }
827/// # }
828///
829/// App::new().add_plugins(PickupNotificationPlugin::<MyItem>::new());
830/// ```
831#[cfg(feature = "items")]
832pub struct PickupNotificationPlugin<I: ItemType> {
833    _marker: std::marker::PhantomData<I>,
834}
835
836#[cfg(feature = "items")]
837impl<I: ItemType> PickupNotificationPlugin<I> {
838    pub fn new() -> Self {
839        Self {
840            _marker: std::marker::PhantomData,
841        }
842    }
843}
844
845#[cfg(feature = "items")]
846impl<I: ItemType> Default for PickupNotificationPlugin<I> {
847    fn default() -> Self {
848        Self::new()
849    }
850}
851
852#[cfg(feature = "items")]
853impl<I: ItemType> Plugin for PickupNotificationPlugin<I> {
854    fn build(&self, app: &mut App) {
855        app.init_resource::<PickupNotificationConfig>();
856        // Ensure the message is registered even if DropsPlugin<I> is not used.
857        app.add_message::<ItemPickedUp<I>>();
858        app.add_systems(Startup, spawn_notification_container);
859        app.add_systems(Update, (on_item_picked_up::<I>, tick_notifications));
860    }
861}
862
863mod pause_menu;
864pub use pause_menu::{PauseMenuConfig, PauseMenuPlugin, PauseMenuState, SaveSettingsRequest};
865
866// ─── Debug Overlay ────────────────────────────────────────────────────────────
867
868use crate::chunk::world_to_chunk_coord;
869use crate::player::Player;
870use crate::world::ChunkManager;
871use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
872
873/// Tracks whether the debug overlay (F3) is currently visible.
874#[derive(Resource, Default)]
875pub struct DebugOverlayState {
876    /// When `true` the overlay is rendered; toggle with **F3**.
877    pub visible: bool,
878}
879
880/// Marker component for the debug overlay root node.
881#[derive(Component)]
882struct DebugOverlay;
883
884/// Marker for the individual text lines (index 0–3).
885#[derive(Component)]
886struct DebugLine(usize);
887
888fn spawn_debug_overlay(mut commands: Commands) {
889    commands
890        .spawn((
891            DebugOverlay,
892            Node {
893                position_type: PositionType::Absolute,
894                top: Val::Px(8.0),
895                left: Val::Px(8.0),
896                flex_direction: FlexDirection::Column,
897                row_gap: Val::Px(2.0),
898                padding: UiRect::all(Val::Px(6.0)),
899                ..default()
900            },
901            BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
902            Visibility::Hidden,
903            ZIndex(200),
904        ))
905        .with_children(|root| {
906            let style = TextFont {
907                font_size: 14.0,
908                ..default()
909            };
910            let color = TextColor(Color::WHITE);
911            for i in 0..4 {
912                root.spawn((DebugLine(i), Text::new(""), style.clone(), color));
913            }
914        });
915}
916
917fn update_debug_overlay(
918    keys: Res<ButtonInput<KeyCode>>,
919    mut state: ResMut<DebugOverlayState>,
920    mut overlay_q: Query<&mut Visibility, With<DebugOverlay>>,
921    mut line_q: Query<(&DebugLine, &mut Text)>,
922    player_q: Query<&Transform, With<Player>>,
923    manager: Res<ChunkManager>,
924    diagnostics: Res<DiagnosticsStore>,
925) {
926    // Toggle visibility on F3 press.
927    if keys.just_pressed(KeyCode::F3) {
928        state.visible = !state.visible;
929        if let Ok(mut vis) = overlay_q.single_mut() {
930            *vis = if state.visible {
931                Visibility::Visible
932            } else {
933                Visibility::Hidden
934            };
935        }
936    }
937
938    if !state.visible {
939        return;
940    }
941
942    let pos = player_q
943        .single()
944        .map(|t| t.translation)
945        .unwrap_or(Vec3::ZERO);
946
947    let chunk = world_to_chunk_coord(pos);
948    let fps = diagnostics
949        .get(&FrameTimeDiagnosticsPlugin::FPS)
950        .and_then(|d| d.smoothed())
951        .unwrap_or(0.0);
952    let chunk_count = manager.loaded_count();
953
954    let lines = [
955        format!("XYZ: {:.1} / {:.1} / {:.1}", pos.x, pos.y, pos.z),
956        format!("Chunk: {} {} {}", chunk.x, chunk.y, chunk.z),
957        format!("FPS: {fps:.0}"),
958        format!("Chunks: {chunk_count}"),
959    ];
960
961    for (line_marker, mut text) in line_q.iter_mut() {
962        if let Some(content) = lines.get(line_marker.0) {
963            *text = Text::new(content.clone());
964        }
965    }
966}
967
968/// Plugin that renders a debug information overlay toggled with **F3**.
969///
970/// Shows player XYZ position, current chunk coordinate, FPS, and loaded chunk
971/// count. The overlay is hidden by default; press **F3** to show or hide it.
972///
973/// Automatically adds [`FrameTimeDiagnosticsPlugin`] for FPS measurement.
974///
975/// # Example
976///
977/// ```rust,no_run
978/// use bevy::prelude::*;
979/// use voxel_framework::ui::DebugOverlayPlugin;
980///
981/// App::new().add_plugins(DebugOverlayPlugin);
982/// ```
983pub struct DebugOverlayPlugin;
984
985impl Plugin for DebugOverlayPlugin {
986    fn build(&self, app: &mut App) {
987        app.add_plugins(FrameTimeDiagnosticsPlugin::default());
988        app.init_resource::<DebugOverlayState>();
989        app.add_systems(Startup, spawn_debug_overlay);
990        app.add_systems(Update, update_debug_overlay);
991    }
992}
993
994// ─── (InventoryUiPlugin removed — games provide their own inventory UI) ───────
995
996// ─── UiPlugin (umbrella) ──────────────────────────────────────────────────────
997
998#[cfg(feature = "items")]
999use crate::items::inventory::DefaultItem;
1000
1001#[cfg_attr(
1002    feature = "items",
1003    doc = "Umbrella plugin that adds all four HUD sub-plugins with [`DefaultItem`]."
1004)]
1005#[cfg_attr(
1006    not(feature = "items"),
1007    doc = "Umbrella plugin for the built-in HUD sub-plugins; item-specific overlays require the `items` feature."
1008)]
1009///
1010#[cfg_attr(
1011    feature = "items",
1012    doc = "Equivalent to adding [`CrosshairPlugin`], [`LoadingScreenPlugin`], [`HotbarUiPlugin`], and [`PickupNotificationPlugin::<DefaultItem>`] in one call. Configuration resources for each sub-plugin can still be inserted individually before `UiPlugin` is added to override their defaults."
1013)]
1014#[cfg_attr(
1015    not(feature = "items"),
1016    doc = "Without the `items` feature, this adds [`CrosshairPlugin`] and [`LoadingScreenPlugin`]. Configuration resources for each sub-plugin can still be inserted individually before `UiPlugin` is added to override their defaults."
1017)]
1018///
1019#[cfg_attr(
1020    feature = "items",
1021    doc = "To use a custom item type for pickup notifications, skip `UiPlugin` and add [`PickupNotificationPlugin::<YourItem>::new()`] alongside the other plugins individually."
1022)]
1023#[cfg_attr(
1024    not(feature = "items"),
1025    doc = "Enable the `items` feature before configuring item-specific pickup notifications or hotbar UI."
1026)]
1027///
1028/// # Example
1029///
1030/// ```rust,no_run
1031/// use bevy::prelude::*;
1032/// use voxel_framework::ui::UiPlugin;
1033///
1034/// App::new()
1035///     .add_plugins(DefaultPlugins)
1036///     .add_plugins(UiPlugin);
1037/// ```
1038pub struct UiPlugin;
1039
1040impl Plugin for UiPlugin {
1041    fn build(&self, app: &mut App) {
1042        app.add_plugins(CrosshairPlugin);
1043        app.add_plugins(LoadingScreenPlugin);
1044        #[cfg(feature = "items")]
1045        app.add_plugins(HotbarUiPlugin);
1046        #[cfg(feature = "items")]
1047        app.add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
1048    }
1049}