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 pop-up text on item pickup, top-right by default |"
18)]
19#![cfg_attr(
20    not(feature = "items"),
21    doc = "| `PickupNotificationPlugin` *(feature `items`)* | Timed pop-up text on item pickup, top-right by default |"
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`],
67//! which must be coordinated with your game's state machine. It works together
68//! with [`PlayerPlugin`](crate::player::PlayerPlugin), which pauses with it and
69//! supplies first-click cursor capture and focus-loss release.
70//!
71//! # Colors
72//!
73//! The pause menu and the loading screen take their colors from two optional
74//! resources, [`PauseMenuTheme`] and [`LoadingScreenTheme`]. Both default to
75//! the framework's built-in look.
76
77use bevy::prelude::*;
78
79#[cfg(feature = "items")]
80use crate::items::inventory::ItemPickedUp;
81#[cfg(feature = "items")]
82use crate::items::inventory::ItemType;
83use crate::world::loading::{LoadingProgress, WorldLoadingState};
84
85/// Author-defined, game-neutral HUD data model and stores.
86pub mod hud;
87pub use hud::{
88    HudAnchor, HudBar, HudBindingKind, HudDefinitionError, HudDiagnostic, HudDiagnosticKind,
89    HudElementDefinition, HudElementId, HudElementSnapshot, HudIcon, HudIconSource, HudPlacement,
90    HudPresentation, HudRegistry, HudRegistryError, HudScalar, HudScalarField, HudSegments,
91    HudStackDirection, HudStyleOverride, HudSystemSet, HudText, HudTheme, HudValue,
92    HudValueChanged, HudValueError, HudValueId, HudValueKind, HudValueSet, HudValueSnapshot,
93    MAX_HUD_SEGMENTS, VoxelHudPlugin, remove_hud_value, set_hud_value,
94};
95
96// ─── Crosshair ────────────────────────────────────────────────────────────────
97
98/// Visual configuration for the [`CrosshairPlugin`] overlay.
99///
100/// Insert this resource before adding [`CrosshairPlugin`] to override any
101/// default. The crosshair is spawned once on `Startup`; changes made after
102/// that point have no effect unless you despawn and re-spawn the crosshair
103/// nodes.
104///
105/// # Default values
106///
107/// | Field       | Default              | Notes |
108/// |-------------|----------------------|-------|
109/// | `color`     | `[1,1,1,1]` (white)  | RGBA, linear |
110/// | `size`      | `20.0` px            | Half-length of each arm |
111/// | `gap`       | `4.0` px             | Empty space between center and arm start |
112/// | `thickness` | `2.0` px             | Width of each arm quad |
113/// | `visible`   | `true`               | `false` skips spawning entirely |
114#[derive(Resource, Debug, Clone)]
115pub struct CrosshairConfig {
116    /// RGBA color of the four crosshair arm quads in linear sRGB.
117    /// Alpha controls overall transparency of the overlay.
118    pub color: [f32; 4],
119    /// Half-length of each arm in logical (UI) pixels. The total visual width
120    /// of the crosshair is approximately `2 × (gap + size)`.
121    pub size: f32,
122    /// Empty gap in logical pixels between the screen center and the start of
123    /// each arm. Increase this to leave a clear center dot.
124    pub gap: f32,
125    /// Width of each arm quad in logical pixels. Thicker values (`4.0`–`6.0`)
126    /// are easier to see on busy backgrounds.
127    pub thickness: f32,
128    /// When `false`, [`CrosshairPlugin`] returns early from `spawn_crosshair`
129    /// without creating any entities. Useful for games that manage their own
130    /// reticle or disable the crosshair entirely in certain modes.
131    pub visible: bool,
132}
133
134impl Default for CrosshairConfig {
135    fn default() -> Self {
136        Self {
137            color: [1.0, 1.0, 1.0, 1.0],
138            size: 20.0,
139            gap: 4.0,
140            thickness: 2.0,
141            visible: true,
142        }
143    }
144}
145
146/// Marker component for crosshair quad entities.
147#[derive(Component)]
148struct CrosshairNode;
149
150fn spawn_crosshair(mut commands: Commands, config: Res<CrosshairConfig>) {
151    if !config.visible {
152        return;
153    }
154
155    let c = &*config;
156    let color = Color::srgba(c.color[0], c.color[1], c.color[2], c.color[3]);
157
158    // Root container — full screen, no interaction, just a layout anchor.
159    commands
160        .spawn((
161            CrosshairNode,
162            Node {
163                width: Val::Percent(100.0),
164                height: Val::Percent(100.0),
165                position_type: PositionType::Absolute,
166                justify_content: JustifyContent::Center,
167                align_items: AlignItems::Center,
168                ..default()
169            },
170            BackgroundColor(Color::NONE),
171        ))
172        .with_children(|root| {
173            // Left arm
174            root.spawn((
175                CrosshairNode,
176                Node {
177                    position_type: PositionType::Absolute,
178                    width: Val::Px(c.size),
179                    height: Val::Px(c.thickness),
180                    right: Val::Px(c.gap + c.size / 2.0 + c.size / 2.0),
181                    top: Val::Px(-c.thickness / 2.0),
182                    ..default()
183                },
184                BackgroundColor(color),
185            ));
186            // Right arm
187            root.spawn((
188                CrosshairNode,
189                Node {
190                    position_type: PositionType::Absolute,
191                    width: Val::Px(c.size),
192                    height: Val::Px(c.thickness),
193                    left: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
194                    top: Val::Px(-c.thickness / 2.0),
195                    ..default()
196                },
197                BackgroundColor(color),
198            ));
199            // Top arm
200            root.spawn((
201                CrosshairNode,
202                Node {
203                    position_type: PositionType::Absolute,
204                    width: Val::Px(c.thickness),
205                    height: Val::Px(c.size),
206                    left: Val::Px(-c.thickness / 2.0),
207                    bottom: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
208                    ..default()
209                },
210                BackgroundColor(color),
211            ));
212            // Bottom arm
213            root.spawn((
214                CrosshairNode,
215                Node {
216                    position_type: PositionType::Absolute,
217                    width: Val::Px(c.thickness),
218                    height: Val::Px(c.size),
219                    left: Val::Px(-c.thickness / 2.0),
220                    top: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
221                    ..default()
222                },
223                BackgroundColor(color),
224            ));
225        });
226}
227
228/// Plugin that renders a fixed center-screen crosshair using four UI quads.
229///
230/// The crosshair is built from four [`Node`] rectangles (left, right, top,
231/// bottom arms) positioned with `PositionType::Absolute` relative to a full-
232/// screen container. No images or asset loading are required.
233///
234/// Customize appearance by inserting [`CrosshairConfig`] before adding this
235/// plugin. If [`CrosshairConfig::visible`] is `false`, no entities are spawned.
236///
237/// # Example
238///
239/// ```rust,no_run
240/// use bevy::prelude::*;
241/// use voxel_framework::ui::{CrosshairPlugin, CrosshairConfig};
242///
243/// App::new()
244///     .insert_resource(CrosshairConfig {
245///         color: [0.0, 1.0, 0.0, 0.9],
246///         gap: 6.0,
247///         ..Default::default()
248///     })
249///     .add_plugins(CrosshairPlugin);
250/// ```
251pub struct CrosshairPlugin;
252
253impl Plugin for CrosshairPlugin {
254    fn build(&self, app: &mut App) {
255        app.init_resource::<CrosshairConfig>();
256        app.add_systems(Startup, spawn_crosshair);
257    }
258}
259
260// ─── Loading Screen ───────────────────────────────────────────────────────────
261
262/// Visual configuration for the [`LoadingScreenPlugin`] overlay.
263///
264/// Insert this resource before adding [`LoadingScreenPlugin`] to override
265/// defaults. Values are read once on `Startup` when the overlay is spawned.
266/// The colors of the progress bar are in [`LoadingScreenTheme`].
267///
268/// # Default values
269///
270/// | Field              | Default                                   |
271/// |--------------------|-------------------------------------------|
272/// | `background_color` | `[0.05, 0.05, 0.05, 0.95]` (near-black)  |
273/// | `text_color`       | `[1, 1, 1, 1]` (white)                    |
274/// | `title`            | `"Loading..."`                             |
275/// | `show_progress_bar`| `true`                                    |
276#[derive(Resource, Debug, Clone)]
277pub struct LoadingScreenConfig {
278    /// RGBA background color of the full-screen overlay in linear sRGB. The
279    /// default near-black with high alpha (`0.95`) fully obscures the 3D scene
280    /// while the world loads.
281    pub background_color: [f32; 4],
282    /// RGBA color of the loading title text in linear sRGB.
283    pub text_color: [f32; 4],
284    /// Text displayed in the center of the overlay. Updated dynamically with
285    /// `"Loading… X/Y chunks"` as [`LoadingProgress`] messages arrive.
286    pub title: String,
287    /// When `true`, a 400×20 px progress bar is rendered below the title text.
288    /// The bar fill advances from 0 % to 100 % as [`LoadingProgress::progress`]
289    /// increases from `0.0` to `1.0`.
290    pub show_progress_bar: bool,
291}
292
293impl Default for LoadingScreenConfig {
294    fn default() -> Self {
295        Self {
296            background_color: [0.05, 0.05, 0.05, 0.95],
297            text_color: [1.0, 1.0, 1.0, 1.0],
298            title: "Loading...".to_string(),
299            show_progress_bar: true,
300        }
301    }
302}
303
304/// Colors of the progress bar drawn by [`LoadingScreenPlugin`].
305///
306/// Insert this resource to recolor the bar; the plugin initializes it with
307/// [`Default`] when the game has not inserted one, and never replaces one
308/// that is already there. The default is the green bar on a dark grey track
309/// that the loading screen has always drawn. The overlay background and the
310/// text color stay in [`LoadingScreenConfig`]; the bar is only drawn when
311/// [`LoadingScreenConfig::show_progress_bar`] is `true`.
312///
313/// Values are read once on `Startup`, when the overlay is spawned.
314///
315/// | Field            | Default                            |
316/// |------------------|------------------------------------|
317/// | `bar_color`      | `Color::srgba(0.2, 0.7, 0.3, 1.0)` |
318/// | `bar_background` | `Color::srgba(0.2, 0.2, 0.2, 1.0)` |
319///
320/// # Example
321///
322/// ```rust,no_run
323/// use bevy::prelude::*;
324/// use voxel_framework::prelude::*;
325///
326/// App::new()
327///     .add_plugins(DefaultPlugins)
328///     .insert_resource(LoadingScreenTheme {
329///         bar_color: Color::srgb(0.2, 0.2, 0.2),
330///         bar_background: Color::srgb(0.8, 0.8, 0.78),
331///     })
332///     .add_plugins(LoadingScreenPlugin)
333///     .run();
334/// ```
335#[derive(Resource, Debug, Clone, PartialEq)]
336pub struct LoadingScreenTheme {
337    /// Color of the part of the bar that fills as the world loads.
338    pub bar_color: Color,
339    /// Color of the bar's track, visible where the bar is not filled yet.
340    pub bar_background: Color,
341}
342
343impl Default for LoadingScreenTheme {
344    fn default() -> Self {
345        Self {
346            bar_color: Color::srgba(0.2, 0.7, 0.3, 1.0),
347            bar_background: Color::srgba(0.2, 0.2, 0.2, 1.0),
348        }
349    }
350}
351
352/// Marker for the loading overlay root.
353#[derive(Component)]
354struct LoadingOverlay;
355
356/// Marker for the loading text entity.
357#[derive(Component)]
358struct LoadingText;
359
360/// Marker for the progress bar track (the background behind the fill).
361#[derive(Component)]
362struct LoadingProgressBarTrack;
363
364/// Marker for the progress bar fill entity.
365#[derive(Component)]
366struct LoadingProgressBar;
367
368fn spawn_loading_overlay(
369    mut commands: Commands,
370    config: Res<LoadingScreenConfig>,
371    theme: Option<Res<LoadingScreenTheme>>,
372) {
373    // Absent when the system runs without `LoadingScreenPlugin`.
374    let theme = theme.as_deref().cloned().unwrap_or_default();
375    let bg = Color::srgba(
376        config.background_color[0],
377        config.background_color[1],
378        config.background_color[2],
379        config.background_color[3],
380    );
381    let tc = Color::srgba(
382        config.text_color[0],
383        config.text_color[1],
384        config.text_color[2],
385        config.text_color[3],
386    );
387
388    commands
389        .spawn((
390            LoadingOverlay,
391            Node {
392                width: Val::Percent(100.0),
393                height: Val::Percent(100.0),
394                position_type: PositionType::Absolute,
395                flex_direction: FlexDirection::Column,
396                justify_content: JustifyContent::Center,
397                align_items: AlignItems::Center,
398                ..default()
399            },
400            BackgroundColor(bg),
401            ZIndex(100),
402        ))
403        .with_children(|parent| {
404            // Title + progress text
405            parent.spawn((
406                LoadingText,
407                Text::new(config.title.clone()),
408                TextFont {
409                    font_size: 32.0,
410                    ..default()
411                },
412                TextColor(tc),
413            ));
414
415            if config.show_progress_bar {
416                // Progress bar background
417                parent
418                    .spawn((
419                        LoadingProgressBarTrack,
420                        Node {
421                            width: Val::Px(400.0),
422                            height: Val::Px(20.0),
423                            margin: UiRect::top(Val::Px(20.0)),
424                            ..default()
425                        },
426                        BackgroundColor(theme.bar_background),
427                    ))
428                    .with_children(|bar| {
429                        // Fill
430                        bar.spawn((
431                            LoadingProgressBar,
432                            Node {
433                                width: Val::Percent(0.0),
434                                height: Val::Percent(100.0),
435                                ..default()
436                            },
437                            BackgroundColor(theme.bar_color),
438                        ));
439                    });
440            }
441        });
442}
443
444fn update_loading_overlay(
445    loading_state: Res<WorldLoadingState>,
446    mut progress_reader: bevy::ecs::message::MessageReader<LoadingProgress>,
447    mut overlay_query: Query<&mut Visibility, With<LoadingOverlay>>,
448    mut text_query: Query<&mut Text, With<LoadingText>>,
449    mut bar_query: Query<&mut Node, With<LoadingProgressBar>>,
450) {
451    // Hide overlay once world is ready
452    if loading_state.ready {
453        if let Ok(mut vis) = overlay_query.single_mut() {
454            *vis = Visibility::Hidden;
455        }
456        return;
457    }
458
459    // Process latest progress message
460    let mut latest: Option<LoadingProgress> = None;
461    for msg in progress_reader.read() {
462        latest = Some(msg.clone());
463    }
464
465    if let Some(progress) = latest {
466        // Update text
467        if let Ok(mut text) = text_query.single_mut() {
468            *text = Text::new(format!(
469                "Loading... {}/{} chunks",
470                progress.loaded, progress.total
471            ));
472        }
473
474        // Update progress bar width
475        if let Ok(mut node) = bar_query.single_mut() {
476            node.width = Val::Percent((progress.progress * 100.0).clamp(0.0, 100.0));
477        }
478    }
479}
480
481fn despawn_loading_overlay_on_ready(
482    mut commands: Commands,
483    loading_state: Res<WorldLoadingState>,
484    overlay_query: Query<Entity, With<LoadingOverlay>>,
485) {
486    if loading_state.ready {
487        for entity in overlay_query.iter() {
488            commands.entity(entity).despawn();
489        }
490    }
491}
492
493/// Plugin that displays a full-screen loading overlay during world generation.
494///
495/// The overlay is spawned on `Startup` and updates every frame by reading
496/// [`LoadingProgress`] messages broadcast by the chunk streaming system. Once
497/// [`WorldLoadingState::ready`] flips to `true`, the overlay is hidden and then
498/// despawned to free the UI node tree.
499///
500/// Customize appearance via [`LoadingScreenConfig`] (background, text, title)
501/// and [`LoadingScreenTheme`] (progress bar colors) inserted before `Startup`.
502///
503/// # Example
504///
505/// ```rust,no_run
506/// use bevy::prelude::*;
507/// use voxel_framework::ui::{LoadingScreenPlugin, LoadingScreenConfig};
508///
509/// App::new()
510///     .insert_resource(LoadingScreenConfig {
511///         title: "Generating universe…".to_string(),
512///         show_progress_bar: false,
513///         ..Default::default()
514///     })
515///     .add_plugins(LoadingScreenPlugin);
516/// ```
517pub struct LoadingScreenPlugin;
518
519impl Plugin for LoadingScreenPlugin {
520    fn build(&self, app: &mut App) {
521        app.init_resource::<LoadingScreenConfig>();
522        app.init_resource::<LoadingScreenTheme>();
523        app.add_systems(Startup, spawn_loading_overlay);
524        app.add_systems(
525            Update,
526            (update_loading_overlay, despawn_loading_overlay_on_ready),
527        );
528    }
529}
530
531/// Hotbar layout and optional item content (requires `items`).
532#[cfg(feature = "items")]
533pub mod hotbar;
534#[cfg(feature = "items")]
535pub use hotbar::{HotbarContentPlugin, HotbarUiConfig, HotbarUiPlugin, ItemIconPalette};
536
537// ─── Pickup Notification ──────────────────────────────────────────────────────
538//
539// Gated on the `items` feature: the pickup notification system listens for
540// `ItemPickedUp<I>` messages and is meaningless without an item palette.
541
542/// Visual configuration for the [`PickupNotificationPlugin`] pop-up system.
543///
544/// Insert this resource before adding [`PickupNotificationPlugin`] to override
545/// defaults. Configuration is read once per notification spawn. Which pickups
546/// notify is set by [`PickupNotificationFilter`]; placement and decoration by
547/// [`PickupNotificationLayout`].
548///
549/// # Default values
550///
551/// | Field               | Default              |
552/// |---------------------|----------------------|
553/// | `visible`           | `true`               |
554/// | `duration_secs`     | `3.0` s              |
555/// | `text_color`        | `[1, 1, 1, 1]` (white) |
556/// | `max_notifications` | `5`                  |
557#[cfg(feature = "items")]
558#[derive(Resource, Debug, Clone)]
559pub struct PickupNotificationConfig {
560    /// When `false`, no notification entities are spawned even when
561    /// [`ItemPickedUp`] messages fire.
562    pub visible: bool,
563    /// How long each notification text persists on screen in seconds before
564    /// being automatically despawned. Applied per-notification via a
565    /// [`Timer`].
566    pub duration_secs: f32,
567    /// RGBA color of the notification text in linear sRGB.
568    pub text_color: [f32; 4],
569    /// Maximum number of notifications displayed at the same time. When a new
570    /// pickup would exceed this limit, the oldest visible notification is
571    /// despawned first to make room.
572    pub max_notifications: usize,
573}
574
575#[cfg(feature = "items")]
576impl Default for PickupNotificationConfig {
577    fn default() -> Self {
578        Self {
579            visible: true,
580            duration_secs: 3.0,
581            text_color: [1.0, 1.0, 1.0, 1.0],
582            max_notifications: 5,
583        }
584    }
585}
586
587/// Decides which pickups produce a notification.
588///
589/// A resource initialized by [`PickupNotificationPlugin`] with the default
590/// [`PickupNotificationFilter::Every`], which is the behavior the plugin always
591/// had. Insert another variant before or after adding the plugin; the filter is
592/// read every time pickups are processed, so it can also be changed at runtime.
593///
594/// The filter applies only to [`ItemPickedUp`] messages. A
595/// [`ShowPickupNotification`] message is an explicit request and is shown under
596/// every variant.
597///
598/// # Example
599///
600/// Notify only the first time each item type is collected, in the bottom-left
601/// corner, on a dark panel with an accent bar and a label line:
602///
603/// ```rust,no_run
604/// use bevy::prelude::*;
605/// use voxel_framework::prelude::*;
606///
607/// App::new()
608///     .insert_resource(PickupNotificationFilter::FirstPerItemType)
609///     .insert_resource(PickupNotificationLayout {
610///         anchor: HudAnchor::BottomLeft,
611///         offset: [24.0, 96.0],
612///         background: Some([0.0, 0.0, 0.0, 0.6]),
613///         padding: [10.0, 6.0],
614///         accent_bar: Some(PickupNotificationAccentBar {
615///             color: [1.0, 0.8, 0.2, 1.0],
616///             width: 4.0,
617///         }),
618///         label: Some(PickupNotificationLabel {
619///             text: "New item".to_string(),
620///             color: [1.0, 0.8, 0.2, 1.0],
621///         }),
622///     })
623///     .add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
624/// ```
625///
626/// For a rule only the game can evaluate, use
627/// [`PickupNotificationFilter::OnRequest`] and write a
628/// [`ShowPickupNotification`] message from a game system:
629///
630/// ```rust,no_run
631/// use bevy::prelude::*;
632/// use voxel_framework::prelude::*;
633///
634/// fn notify_large_pickups(
635///     mut pickups: MessageReader<ItemPickedUp<DefaultItem>>,
636///     mut requests: MessageWriter<ShowPickupNotification<DefaultItem>>,
637/// ) {
638///     for pickup in pickups.read() {
639///         if pickup.count >= 10 {
640///             requests.write(ShowPickupNotification::new(pickup.item, pickup.count));
641///         }
642///     }
643/// }
644///
645/// App::new()
646///     .insert_resource(PickupNotificationFilter::OnRequest)
647///     .add_plugins(PickupNotificationPlugin::<DefaultItem>::new())
648///     .add_systems(Update, notify_large_pickups);
649/// ```
650#[cfg(feature = "items")]
651#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
652pub enum PickupNotificationFilter {
653    /// Every [`ItemPickedUp`] message produces a notification.
654    #[default]
655    Every,
656    /// Only the first shown pickup of each item type produces a notification.
657    ///
658    /// The item types already shown are recorded in
659    /// [`PickupNotificationSeen`]. A pickup that could not be shown (the
660    /// overlay is hidden or full) is not recorded, so the next pickup of that
661    /// type still notifies.
662    FirstPerItemType,
663    /// No [`ItemPickedUp`] message produces a notification by itself. The game
664    /// decides with its own rule and writes [`ShowPickupNotification`].
665    OnRequest,
666}
667
668/// Item types that already produced a notification under
669/// [`PickupNotificationFilter::FirstPerItemType`].
670///
671/// Initialized empty by [`PickupNotificationPlugin`] and kept in memory only:
672/// the framework does not persist it. A game that wants the record to survive
673/// a restart saves the items itself and calls
674/// [`insert`](PickupNotificationSeen::insert) for each of them on load;
675/// [`clear`](PickupNotificationSeen::clear) starts over, for example for a new
676/// world. Other filter variants neither read nor write this resource.
677#[cfg(feature = "items")]
678#[derive(Resource, Clone, Default)]
679pub struct PickupNotificationSeen<I: ItemType> {
680    seen: std::collections::HashSet<I>,
681}
682
683#[cfg(feature = "items")]
684impl<I: ItemType> PickupNotificationSeen<I> {
685    /// Returns `true` if `item` is recorded as already notified.
686    pub fn contains(&self, item: I) -> bool {
687        self.seen.contains(&item)
688    }
689
690    /// Records `item` as already notified. Returns `true` if it was not
691    /// recorded before.
692    pub fn insert(&mut self, item: I) -> bool {
693        self.seen.insert(item)
694    }
695
696    /// Forgets every recorded item type.
697    pub fn clear(&mut self) {
698        self.seen.clear();
699    }
700
701    /// Number of recorded item types.
702    pub fn len(&self) -> usize {
703        self.seen.len()
704    }
705
706    /// Returns `true` if no item type is recorded.
707    pub fn is_empty(&self) -> bool {
708        self.seen.is_empty()
709    }
710}
711
712/// Explicit request to show one pickup notification.
713///
714/// Registered by [`PickupNotificationPlugin`]. Each message produces a
715/// notification formatted like the ones for [`ItemPickedUp`], whatever the
716/// [`PickupNotificationFilter`] is; [`PickupNotificationConfig::visible`] and
717/// [`PickupNotificationConfig::max_notifications`] still apply. It is the way
718/// to implement a game-defined rule: set
719/// [`PickupNotificationFilter::OnRequest`], read [`ItemPickedUp`] in a game
720/// system and write this message for the pickups that should be announced.
721///
722/// A request does not touch [`PickupNotificationSeen`].
723#[cfg(feature = "items")]
724#[derive(Message, Debug, Clone)]
725pub struct ShowPickupNotification<I: ItemType> {
726    /// Item whose name is shown.
727    pub item: I,
728    /// Amount shown after the `+` sign.
729    pub count: u32,
730}
731
732#[cfg(feature = "items")]
733impl<I: ItemType> ShowPickupNotification<I> {
734    /// Creates a request to show `count` of `item`.
735    pub fn new(item: I, count: u32) -> Self {
736        Self { item, count }
737    }
738}
739
740/// Accent bar drawn at the left edge of each pickup notification.
741///
742/// Used through [`PickupNotificationLayout::accent_bar`].
743#[cfg(feature = "items")]
744#[derive(Debug, Clone, Copy, PartialEq)]
745pub struct PickupNotificationAccentBar {
746    /// RGBA color of the bar, in the same convention as
747    /// [`PickupNotificationConfig::text_color`].
748    pub color: [f32; 4],
749    /// Width of the bar in logical pixels. The bar is as tall as the
750    /// notification. A width that is not finite and positive draws no bar.
751    pub width: f32,
752}
753
754/// Fixed line of text shown above the item line of each pickup notification.
755///
756/// Used through [`PickupNotificationLayout::label`]. It uses the same font and
757/// size as the item line.
758#[cfg(feature = "items")]
759#[derive(Debug, Clone, PartialEq)]
760pub struct PickupNotificationLabel {
761    /// Text of the line, for example `"New item"`.
762    pub text: String,
763    /// RGBA color of the line, in the same convention as
764    /// [`PickupNotificationConfig::text_color`].
765    pub color: [f32; 4],
766}
767
768/// Placement and decoration of the [`PickupNotificationPlugin`] pop-ups.
769///
770/// A resource initialized by [`PickupNotificationPlugin`]; its default is the
771/// placement and style the plugin always had. Insert it before adding the
772/// plugin, or change it later: placement is applied to the notification
773/// container whenever the resource changes, and decoration is read when each
774/// notification is spawned (notifications already on screen keep theirs).
775///
776/// # Default values
777///
778/// | Field        | Default        |
779/// |--------------|----------------|
780/// | `anchor`     | [`HudAnchor::TopRight`] |
781/// | `offset`     | `[16, 16]` px  |
782/// | `background` | `None`         |
783/// | `padding`    | `[0, 0]` px    |
784/// | `accent_bar` | `None`         |
785/// | `label`      | `None`         |
786///
787/// See [`PickupNotificationFilter`] for a complete example.
788#[cfg(feature = "items")]
789#[derive(Resource, Debug, Clone, PartialEq)]
790pub struct PickupNotificationLayout {
791    /// Screen location the stack of notifications is attached to.
792    /// Notifications are aligned to the same side: right-aligned for the right
793    /// anchors, centered for the center ones.
794    pub anchor: HudAnchor,
795    /// `[x, y]` offset in logical pixels. On an axis anchored to an edge it is
796    /// the distance inward from that edge; on a centered axis it moves the
797    /// stack right (`x`) or down (`y`). Non-finite components count as `0`.
798    pub offset: [f32; 2],
799    /// RGBA fill behind each notification, in the same convention as
800    /// [`PickupNotificationConfig::text_color`]. `None` draws no fill.
801    pub background: Option<[f32; 4]>,
802    /// `[horizontal, vertical]` space in logical pixels between the edge of a
803    /// notification and its text. Components that are not finite and positive
804    /// count as `0`.
805    pub padding: [f32; 2],
806    /// Optional bar at the left edge of each notification.
807    pub accent_bar: Option<PickupNotificationAccentBar>,
808    /// Optional line of text above the item line.
809    pub label: Option<PickupNotificationLabel>,
810}
811
812#[cfg(feature = "items")]
813impl Default for PickupNotificationLayout {
814    fn default() -> Self {
815        Self {
816            anchor: HudAnchor::TopRight,
817            offset: [16.0, 16.0],
818            background: None,
819            padding: [0.0, 0.0],
820            accent_bar: None,
821            label: None,
822        }
823    }
824}
825
826/// Font size of the notification text lines.
827#[cfg(feature = "items")]
828const NOTIFICATION_FONT_SIZE: f32 = 18.0;
829
830/// Timer component on each notification entity.
831#[cfg(feature = "items")]
832#[derive(Component)]
833struct NotificationTimer(Timer);
834
835/// Marker for the notification container.
836#[cfg(feature = "items")]
837#[derive(Component)]
838struct NotificationContainer;
839
840/// Marker for the accent bar node of a decorated notification.
841#[cfg(feature = "items")]
842#[derive(Component)]
843struct NotificationAccentBar;
844
845/// Marker for the label line of a decorated notification.
846#[cfg(feature = "items")]
847#[derive(Component)]
848struct NotificationLabel;
849
850/// Where the notification stack sits along one screen axis.
851#[cfg(feature = "items")]
852#[derive(Clone, Copy)]
853enum NotificationAxis {
854    Start,
855    Center,
856    End,
857}
858
859/// Splits an anchor into its `(horizontal, vertical)` axes.
860#[cfg(feature = "items")]
861fn notification_axes(anchor: HudAnchor) -> (NotificationAxis, NotificationAxis) {
862    use NotificationAxis::{Center, End, Start};
863    match anchor {
864        HudAnchor::TopLeft => (Start, Start),
865        HudAnchor::TopCenter => (Center, Start),
866        HudAnchor::TopRight => (End, Start),
867        HudAnchor::CenterLeft => (Start, Center),
868        HudAnchor::Center => (Center, Center),
869        HudAnchor::CenterRight => (End, Center),
870        HudAnchor::BottomLeft => (Start, End),
871        HudAnchor::BottomCenter => (Center, End),
872        HudAnchor::BottomRight => (End, End),
873    }
874}
875
876#[cfg(feature = "items")]
877fn notification_align(axis: NotificationAxis) -> AlignItems {
878    match axis {
879        NotificationAxis::Start => AlignItems::FlexStart,
880        NotificationAxis::Center => AlignItems::Center,
881        NotificationAxis::End => AlignItems::FlexEnd,
882    }
883}
884
885#[cfg(feature = "items")]
886fn finite_or_zero(value: f32) -> f32 {
887    if value.is_finite() { value } else { 0.0 }
888}
889
890#[cfg(feature = "items")]
891fn positive_or_zero(value: f32) -> f32 {
892    if value.is_finite() && value > 0.0 {
893        value
894    } else {
895        0.0
896    }
897}
898
899#[cfg(feature = "items")]
900fn notification_color(rgba: [f32; 4]) -> Color {
901    Color::srgba(rgba[0], rgba[1], rgba[2], rgba[3])
902}
903
904/// Node of the notification container for `layout`.
905///
906/// An axis anchored to an edge sets only that edge. A centered axis spans the
907/// screen (shifted by the offset) and centers its content.
908#[cfg(feature = "items")]
909fn notification_container_node(layout: &PickupNotificationLayout) -> Node {
910    let [x, y] = layout.offset.map(finite_or_zero);
911    let (horizontal, vertical) = notification_axes(layout.anchor);
912    let mut node = Node {
913        position_type: PositionType::Absolute,
914        flex_direction: FlexDirection::Column,
915        row_gap: Val::Px(4.0),
916        align_items: notification_align(horizontal),
917        ..default()
918    };
919    match horizontal {
920        NotificationAxis::Start => node.left = Val::Px(x),
921        NotificationAxis::Center => {
922            node.left = Val::Px(x);
923            node.right = Val::Px(-x);
924        }
925        NotificationAxis::End => node.right = Val::Px(x),
926    }
927    match vertical {
928        NotificationAxis::Start => node.top = Val::Px(y),
929        NotificationAxis::Center => {
930            node.top = Val::Px(y);
931            node.bottom = Val::Px(-y);
932            node.justify_content = JustifyContent::Center;
933        }
934        NotificationAxis::End => node.bottom = Val::Px(y),
935    }
936    node
937}
938
939#[cfg(feature = "items")]
940fn spawn_notification_container(mut commands: Commands, layout: Res<PickupNotificationLayout>) {
941    commands.spawn((
942        NotificationContainer,
943        notification_container_node(&layout),
944        BackgroundColor(Color::NONE),
945    ));
946}
947
948/// Moves the container when [`PickupNotificationLayout`] changes.
949#[cfg(feature = "items")]
950fn apply_notification_layout(
951    layout: Res<PickupNotificationLayout>,
952    mut container_query: Query<&mut Node, With<NotificationContainer>>,
953) {
954    if !layout.is_changed() {
955        return;
956    }
957    let desired = notification_container_node(&layout);
958    for mut node in container_query.iter_mut() {
959        if *node != desired {
960            *node = desired.clone();
961        }
962    }
963}
964
965/// Spawns one notification under `container`.
966///
967/// Without decoration the notification is a single text entity, as it always
968/// was. With a background, padding, accent bar or label it is a row holding
969/// the optional bar and a column with the optional label and the item line.
970#[cfg(feature = "items")]
971fn spawn_notification(
972    commands: &mut Commands,
973    container: Entity,
974    config: &PickupNotificationConfig,
975    layout: &PickupNotificationLayout,
976    text: String,
977) {
978    let timer = NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once));
979    let text_font = TextFont {
980        font_size: NOTIFICATION_FONT_SIZE,
981        ..default()
982    };
983    let item_line = (
984        Text::new(text),
985        text_font.clone(),
986        TextColor(notification_color(config.text_color)),
987        Node { ..default() },
988    );
989
990    let [pad_x, pad_y] = layout.padding.map(positive_or_zero);
991    let accent_bar = layout
992        .accent_bar
993        .filter(|bar| positive_or_zero(bar.width) > 0.0);
994    let decorated = layout.background.is_some()
995        || accent_bar.is_some()
996        || layout.label.is_some()
997        || pad_x > 0.0
998        || pad_y > 0.0;
999
1000    if !decorated {
1001        let notification = commands.spawn((timer, item_line)).id();
1002        commands.entity(container).add_child(notification);
1003        return;
1004    }
1005
1006    let notification = commands
1007        .spawn((
1008            timer,
1009            Node {
1010                flex_direction: FlexDirection::Row,
1011                align_items: AlignItems::Stretch,
1012                ..default()
1013            },
1014            BackgroundColor(
1015                layout
1016                    .background
1017                    .map(notification_color)
1018                    .unwrap_or(Color::NONE),
1019            ),
1020        ))
1021        .id();
1022
1023    if let Some(bar) = accent_bar {
1024        let bar_entity = commands
1025            .spawn((
1026                NotificationAccentBar,
1027                Node {
1028                    width: Val::Px(bar.width),
1029                    ..default()
1030                },
1031                BackgroundColor(notification_color(bar.color)),
1032            ))
1033            .id();
1034        commands.entity(notification).add_child(bar_entity);
1035    }
1036
1037    let (horizontal, _) = notification_axes(layout.anchor);
1038    let body = commands
1039        .spawn(Node {
1040            flex_direction: FlexDirection::Column,
1041            align_items: notification_align(horizontal),
1042            padding: UiRect::axes(Val::Px(pad_x), Val::Px(pad_y)),
1043            ..default()
1044        })
1045        .id();
1046    commands.entity(notification).add_child(body);
1047
1048    if let Some(label) = &layout.label {
1049        let label_entity = commands
1050            .spawn((
1051                NotificationLabel,
1052                Text::new(label.text.clone()),
1053                text_font,
1054                TextColor(notification_color(label.color)),
1055                Node { ..default() },
1056            ))
1057            .id();
1058        commands.entity(body).add_child(label_entity);
1059    }
1060
1061    let item_entity = commands.spawn(item_line).id();
1062    commands.entity(body).add_child(item_entity);
1063    commands.entity(container).add_child(notification);
1064}
1065
1066#[cfg(feature = "items")]
1067#[allow(clippy::too_many_arguments)]
1068fn on_item_picked_up<I: ItemType>(
1069    mut commands: Commands,
1070    mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
1071    mut request_reader: bevy::ecs::message::MessageReader<ShowPickupNotification<I>>,
1072    config: Res<PickupNotificationConfig>,
1073    filter: Res<PickupNotificationFilter>,
1074    layout: Res<PickupNotificationLayout>,
1075    mut seen: ResMut<PickupNotificationSeen<I>>,
1076    container_query: Query<Entity, With<NotificationContainer>>,
1077    existing_query: Query<Entity, With<NotificationTimer>>,
1078) {
1079    if !config.visible {
1080        return;
1081    }
1082
1083    // Collect what should be shown this frame: filtered pickups first, then
1084    // explicit requests. The flag marks the entries that must be recorded as
1085    // seen once they are actually spawned.
1086    let mut pending: Vec<(I, u32, bool)> = Vec::new();
1087    for pickup in pickup_reader.read() {
1088        match *filter {
1089            PickupNotificationFilter::Every => pending.push((pickup.item, pickup.count, false)),
1090            PickupNotificationFilter::FirstPerItemType => {
1091                let queued = pending
1092                    .iter()
1093                    .any(|(item, _, first_of_type)| *first_of_type && *item == pickup.item);
1094                if !queued && !seen.contains(pickup.item) {
1095                    pending.push((pickup.item, pickup.count, true));
1096                }
1097            }
1098            PickupNotificationFilter::OnRequest => {}
1099        }
1100    }
1101    for request in request_reader.read() {
1102        pending.push((request.item, request.count, false));
1103    }
1104
1105    if pending.is_empty() {
1106        return;
1107    }
1108
1109    let Ok(container) = container_query.single() else {
1110        return;
1111    };
1112
1113    // Enforce max_notifications — despawn oldest first
1114    let existing: Vec<Entity> = existing_query.iter().collect();
1115    let available = config.max_notifications.saturating_sub(existing.len());
1116    let spawn_count = pending.len().min(available);
1117
1118    if existing.len() + pending.len() > config.max_notifications {
1119        let overflow = (existing.len() + pending.len()).saturating_sub(config.max_notifications);
1120        for entity in existing.iter().take(overflow) {
1121            commands.entity(*entity).despawn();
1122        }
1123    }
1124
1125    for (item, count, first_of_type) in pending.into_iter().take(spawn_count) {
1126        if first_of_type {
1127            seen.insert(item);
1128        }
1129        let text = format!("+{count} {}", item.name());
1130        spawn_notification(&mut commands, container, &config, &layout, text);
1131    }
1132}
1133
1134#[cfg(feature = "items")]
1135fn tick_notifications(
1136    mut commands: Commands,
1137    time: Res<Time>,
1138    mut query: Query<(Entity, &mut NotificationTimer)>,
1139) {
1140    for (entity, mut timer) in query.iter_mut() {
1141        timer.0.tick(time.delta());
1142        if timer.0.just_finished() {
1143            commands.entity(entity).despawn();
1144        }
1145    }
1146}
1147
1148/// Plugin that displays timed item-pickup notifications, at the top-right
1149/// corner by default.
1150///
1151/// Listens for [`ItemPickedUp<I>`] messages and spawns a text node formatted as
1152/// `"+N ItemName"` for each pickup. Notifications fade out after
1153/// [`PickupNotificationConfig::duration_secs`] and are despawned automatically.
1154///
1155/// When the number of simultaneous notifications would exceed
1156/// [`PickupNotificationConfig::max_notifications`], the oldest notifications are
1157/// despawned first.
1158///
1159/// Three more resources are initialized with defaults that keep that behavior
1160/// and can be replaced by the game: [`PickupNotificationFilter`] chooses which
1161/// pickups notify, [`PickupNotificationLayout`] places and decorates the
1162/// notifications, and [`PickupNotificationSeen<I>`] records the item types
1163/// already announced. [`ShowPickupNotification<I>`] requests a notification
1164/// explicitly.
1165///
1166/// The plugin is **generic over the item type** `I: ItemType`. Use [`UiPlugin`]
1167/// for the built-in [`DefaultItem`], or add this plugin manually with a custom
1168/// item type:
1169///
1170/// ```rust,no_run
1171/// use bevy::prelude::*;
1172/// use voxel_framework::ui::PickupNotificationPlugin;
1173/// # use voxel_framework::items::inventory::ItemType;
1174/// # #[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
1175/// # struct MyItem;
1176/// # impl ItemType for MyItem {
1177/// #     fn name(&self) -> &'static str { "item" }
1178/// #     fn color(&self) -> [f32; 4] { [1.0, 1.0, 1.0, 1.0] }
1179/// #     fn to_byte(&self) -> u8 { 0 }
1180/// #     fn from_byte(_: u8) -> Self { Self }
1181/// # }
1182///
1183/// App::new().add_plugins(PickupNotificationPlugin::<MyItem>::new());
1184/// ```
1185#[cfg(feature = "items")]
1186pub struct PickupNotificationPlugin<I: ItemType> {
1187    _marker: std::marker::PhantomData<I>,
1188}
1189
1190#[cfg(feature = "items")]
1191impl<I: ItemType> PickupNotificationPlugin<I> {
1192    pub fn new() -> Self {
1193        Self {
1194            _marker: std::marker::PhantomData,
1195        }
1196    }
1197}
1198
1199#[cfg(feature = "items")]
1200impl<I: ItemType> Default for PickupNotificationPlugin<I> {
1201    fn default() -> Self {
1202        Self::new()
1203    }
1204}
1205
1206#[cfg(feature = "items")]
1207impl<I: ItemType> Plugin for PickupNotificationPlugin<I> {
1208    fn build(&self, app: &mut App) {
1209        app.init_resource::<PickupNotificationConfig>();
1210        app.init_resource::<PickupNotificationFilter>();
1211        app.init_resource::<PickupNotificationLayout>();
1212        app.init_resource::<PickupNotificationSeen<I>>();
1213        // Ensure the message is registered even if DropsPlugin<I> is not used.
1214        app.add_message::<ItemPickedUp<I>>();
1215        app.add_message::<ShowPickupNotification<I>>();
1216        app.add_systems(Startup, spawn_notification_container);
1217        app.add_systems(
1218            Update,
1219            (
1220                apply_notification_layout,
1221                on_item_picked_up::<I>,
1222                tick_notifications,
1223            ),
1224        );
1225    }
1226}
1227
1228mod pause_menu;
1229pub use pause_menu::{
1230    ButtonColors, PauseMenuConfig, PauseMenuPlugin, PauseMenuState, PauseMenuTheme,
1231    SaveSettingsRequest,
1232};
1233
1234// ─── Debug Overlay ────────────────────────────────────────────────────────────
1235
1236use crate::chunk::world_to_chunk_coord;
1237use crate::player::Player;
1238use crate::world::ChunkManager;
1239use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
1240
1241/// Tracks whether the debug overlay (F3) is currently visible.
1242#[derive(Resource, Default)]
1243pub struct DebugOverlayState {
1244    /// When `true` the overlay is rendered; toggle with **F3**.
1245    pub visible: bool,
1246}
1247
1248/// Marker component for the debug overlay root node.
1249#[derive(Component)]
1250struct DebugOverlay;
1251
1252/// Marker for the individual text lines (index 0–3).
1253#[derive(Component)]
1254struct DebugLine(usize);
1255
1256fn spawn_debug_overlay(mut commands: Commands) {
1257    commands
1258        .spawn((
1259            DebugOverlay,
1260            Node {
1261                position_type: PositionType::Absolute,
1262                top: Val::Px(8.0),
1263                left: Val::Px(8.0),
1264                flex_direction: FlexDirection::Column,
1265                row_gap: Val::Px(2.0),
1266                padding: UiRect::all(Val::Px(6.0)),
1267                ..default()
1268            },
1269            BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
1270            Visibility::Hidden,
1271            ZIndex(200),
1272        ))
1273        .with_children(|root| {
1274            let style = TextFont {
1275                font_size: 14.0,
1276                ..default()
1277            };
1278            let color = TextColor(Color::WHITE);
1279            for i in 0..4 {
1280                root.spawn((DebugLine(i), Text::new(""), style.clone(), color));
1281            }
1282        });
1283}
1284
1285fn update_debug_overlay(
1286    keys: Res<ButtonInput<KeyCode>>,
1287    mut state: ResMut<DebugOverlayState>,
1288    mut overlay_q: Query<&mut Visibility, With<DebugOverlay>>,
1289    mut line_q: Query<(&DebugLine, &mut Text)>,
1290    player_q: Query<&Transform, With<Player>>,
1291    manager: Res<ChunkManager>,
1292    diagnostics: Res<DiagnosticsStore>,
1293) {
1294    // Toggle visibility on F3 press.
1295    if keys.just_pressed(KeyCode::F3) {
1296        state.visible = !state.visible;
1297        if let Ok(mut vis) = overlay_q.single_mut() {
1298            *vis = if state.visible {
1299                Visibility::Visible
1300            } else {
1301                Visibility::Hidden
1302            };
1303        }
1304    }
1305
1306    if !state.visible {
1307        return;
1308    }
1309
1310    let pos = player_q
1311        .single()
1312        .map(|t| t.translation)
1313        .unwrap_or(Vec3::ZERO);
1314
1315    let chunk = world_to_chunk_coord(pos);
1316    let fps = diagnostics
1317        .get(&FrameTimeDiagnosticsPlugin::FPS)
1318        .and_then(|d| d.smoothed())
1319        .unwrap_or(0.0);
1320    let chunk_count = manager.loaded_count();
1321
1322    let lines = [
1323        format!("XYZ: {:.1} / {:.1} / {:.1}", pos.x, pos.y, pos.z),
1324        format!("Chunk: {} {} {}", chunk.x, chunk.y, chunk.z),
1325        format!("FPS: {fps:.0}"),
1326        format!("Chunks: {chunk_count}"),
1327    ];
1328
1329    for (line_marker, mut text) in line_q.iter_mut() {
1330        if let Some(content) = lines.get(line_marker.0) {
1331            *text = Text::new(content.clone());
1332        }
1333    }
1334}
1335
1336/// Plugin that renders a debug information overlay toggled with **F3**.
1337///
1338/// Shows player XYZ position, current chunk coordinate, FPS, and loaded chunk
1339/// count. The overlay is hidden by default; press **F3** to show or hide it.
1340///
1341/// Automatically adds [`FrameTimeDiagnosticsPlugin`] for FPS measurement.
1342///
1343/// # Example
1344///
1345/// ```rust,no_run
1346/// use bevy::prelude::*;
1347/// use voxel_framework::ui::DebugOverlayPlugin;
1348///
1349/// App::new().add_plugins(DebugOverlayPlugin);
1350/// ```
1351pub struct DebugOverlayPlugin;
1352
1353impl Plugin for DebugOverlayPlugin {
1354    fn build(&self, app: &mut App) {
1355        app.add_plugins(FrameTimeDiagnosticsPlugin::default());
1356        app.init_resource::<DebugOverlayState>();
1357        app.add_systems(Startup, spawn_debug_overlay);
1358        app.add_systems(Update, update_debug_overlay);
1359    }
1360}
1361
1362// ─── (InventoryUiPlugin removed — games provide their own inventory UI) ───────
1363
1364// ─── UiPlugin (umbrella) ──────────────────────────────────────────────────────
1365
1366#[cfg(feature = "items")]
1367use crate::items::inventory::DefaultItem;
1368
1369#[cfg_attr(
1370    feature = "items",
1371    doc = "Umbrella plugin that adds all four HUD sub-plugins with [`DefaultItem`]."
1372)]
1373#[cfg_attr(
1374    not(feature = "items"),
1375    doc = "Umbrella plugin for the built-in HUD sub-plugins; item-specific overlays require the `items` feature."
1376)]
1377///
1378#[cfg_attr(
1379    feature = "items",
1380    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."
1381)]
1382#[cfg_attr(
1383    not(feature = "items"),
1384    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."
1385)]
1386///
1387#[cfg_attr(
1388    feature = "items",
1389    doc = "To use a custom item type for pickup notifications, skip `UiPlugin` and add [`PickupNotificationPlugin::<YourItem>::new()`] alongside the other plugins individually."
1390)]
1391#[cfg_attr(
1392    not(feature = "items"),
1393    doc = "Enable the `items` feature before configuring item-specific pickup notifications or hotbar UI."
1394)]
1395///
1396/// # Example
1397///
1398/// ```rust,no_run
1399/// use bevy::prelude::*;
1400/// use voxel_framework::ui::UiPlugin;
1401///
1402/// App::new()
1403///     .add_plugins(DefaultPlugins)
1404///     .add_plugins(UiPlugin);
1405/// ```
1406pub struct UiPlugin;
1407
1408impl Plugin for UiPlugin {
1409    fn build(&self, app: &mut App) {
1410        app.add_plugins(CrosshairPlugin);
1411        app.add_plugins(LoadingScreenPlugin);
1412        #[cfg(feature = "items")]
1413        app.add_plugins(HotbarUiPlugin);
1414        #[cfg(feature = "items")]
1415        app.add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
1416    }
1417}
1418
1419#[cfg(test)]
1420mod loading_screen_tests {
1421    use super::*;
1422    use bevy::ecs::system::RunSystemOnce;
1423
1424    fn spawn_overlay(world: &mut World) {
1425        world
1426            .run_system_once(spawn_loading_overlay)
1427            .expect("spawn_loading_overlay should run");
1428    }
1429
1430    /// Background color of the bar's fill, and the entity it is a child of.
1431    fn bar_fill(world: &mut World) -> (Color, Entity) {
1432        let mut query =
1433            world.query_filtered::<(&BackgroundColor, &ChildOf), With<LoadingProgressBar>>();
1434        let (bg, child_of) = query.single(world).expect("one progress bar fill");
1435        (bg.0, child_of.parent())
1436    }
1437
1438    /// Background color of the bar's track, and the track entity.
1439    fn bar_track(world: &mut World) -> (Color, Entity) {
1440        let mut query =
1441            world.query_filtered::<(&BackgroundColor, Entity), With<LoadingProgressBarTrack>>();
1442        let (bg, entity) = query.single(world).expect("one progress bar track");
1443        (bg.0, entity)
1444    }
1445
1446    #[test]
1447    fn default_loading_theme_equals_the_previous_constants() {
1448        let theme = LoadingScreenTheme::default();
1449        assert_eq!(theme.bar_color, Color::srgba(0.2, 0.7, 0.3, 1.0));
1450        assert_eq!(theme.bar_background, Color::srgba(0.2, 0.2, 0.2, 1.0));
1451    }
1452
1453    #[test]
1454    fn loading_bar_without_a_theme_resource_keeps_the_previous_colors() {
1455        let mut world = World::new();
1456        world.insert_resource(LoadingScreenConfig::default());
1457
1458        spawn_overlay(&mut world);
1459
1460        let (track_color, track) = bar_track(&mut world);
1461        let (fill_color, fill_parent) = bar_fill(&mut world);
1462        assert_eq!(track_color, Color::srgba(0.2, 0.2, 0.2, 1.0));
1463        assert_eq!(fill_color, Color::srgba(0.2, 0.7, 0.3, 1.0));
1464        assert_eq!(fill_parent, track);
1465    }
1466
1467    #[test]
1468    fn custom_loading_theme_colors_the_bar_and_its_track() {
1469        let theme = LoadingScreenTheme {
1470            bar_color: Color::srgb(0.9, 0.1, 0.2),
1471            bar_background: Color::srgb(0.1, 0.2, 0.9),
1472        };
1473        let mut world = World::new();
1474        world.insert_resource(LoadingScreenConfig::default());
1475        world.insert_resource(theme.clone());
1476
1477        spawn_overlay(&mut world);
1478
1479        let (track_color, track) = bar_track(&mut world);
1480        let (fill_color, fill_parent) = bar_fill(&mut world);
1481        assert_eq!(track_color, theme.bar_background);
1482        assert_eq!(fill_color, theme.bar_color);
1483        assert_eq!(fill_parent, track);
1484
1485        // The theme does not touch what `LoadingScreenConfig` owns.
1486        let mut overlay = world.query_filtered::<&BackgroundColor, With<LoadingOverlay>>();
1487        assert_eq!(
1488            overlay.single(&world).expect("one overlay").0,
1489            Color::srgba(0.05, 0.05, 0.05, 0.95)
1490        );
1491    }
1492
1493    #[test]
1494    fn loading_theme_is_unused_when_the_bar_is_hidden() {
1495        let mut world = World::new();
1496        world.insert_resource(LoadingScreenConfig {
1497            show_progress_bar: false,
1498            ..Default::default()
1499        });
1500        world.insert_resource(LoadingScreenTheme::default());
1501
1502        spawn_overlay(&mut world);
1503
1504        let mut tracks = world.query_filtered::<Entity, With<LoadingProgressBarTrack>>();
1505        assert_eq!(tracks.iter(&world).count(), 0);
1506        let mut fills = world.query_filtered::<Entity, With<LoadingProgressBar>>();
1507        assert_eq!(fills.iter(&world).count(), 0);
1508    }
1509}
1510
1511#[cfg(all(test, feature = "items"))]
1512mod pickup_notification_tests {
1513    use super::*;
1514    use crate::items::inventory::DefaultItem;
1515
1516    const BACKGROUND: [f32; 4] = [0.0, 0.0, 0.0, 0.6];
1517    const ACCENT: [f32; 4] = [1.0, 0.8, 0.2, 1.0];
1518    const LABEL: [f32; 4] = [0.4, 0.9, 1.0, 1.0];
1519
1520    fn app() -> App {
1521        let mut app = App::new();
1522        app.add_plugins((
1523            MinimalPlugins,
1524            PickupNotificationPlugin::<DefaultItem>::new(),
1525        ));
1526        app
1527    }
1528
1529    fn pick_up(app: &mut App, item: DefaultItem, count: u32) {
1530        app.world_mut().write_message(ItemPickedUp { item, count });
1531        app.update();
1532    }
1533
1534    fn line(item: DefaultItem, count: u32) -> String {
1535        format!("+{count} {}", item.name())
1536    }
1537
1538    /// Root entities of the notifications on screen.
1539    fn notifications(app: &mut App) -> Vec<Entity> {
1540        let world = app.world_mut();
1541        let mut query = world.query_filtered::<Entity, With<NotificationTimer>>();
1542        query.iter(world).collect()
1543    }
1544
1545    /// Item lines on screen, sorted.
1546    fn item_lines(app: &mut App) -> Vec<String> {
1547        let world = app.world_mut();
1548        let mut query = world.query_filtered::<&Text, Without<NotificationLabel>>();
1549        let mut lines: Vec<String> = query.iter(world).map(|text| text.0.clone()).collect();
1550        lines.sort();
1551        lines
1552    }
1553
1554    fn container(app: &mut App) -> (Entity, Node) {
1555        let world = app.world_mut();
1556        let mut query = world.query_filtered::<(Entity, &Node), With<NotificationContainer>>();
1557        let (entity, node) = query.single(world).unwrap();
1558        (entity, node.clone())
1559    }
1560
1561    fn children(app: &App, entity: Entity) -> Vec<Entity> {
1562        app.world()
1563            .get::<Children>(entity)
1564            .map(|children| children.to_vec())
1565            .unwrap_or_default()
1566    }
1567
1568    fn text(app: &App, entity: Entity) -> String {
1569        app.world().get::<Text>(entity).unwrap().0.clone()
1570    }
1571
1572    #[test]
1573    fn defaults_keep_the_top_right_plain_text() {
1574        let mut app = app();
1575        app.update();
1576        assert_eq!(
1577            *app.world().resource::<PickupNotificationFilter>(),
1578            PickupNotificationFilter::Every
1579        );
1580        assert_eq!(
1581            *app.world().resource::<PickupNotificationLayout>(),
1582            PickupNotificationLayout {
1583                anchor: HudAnchor::TopRight,
1584                offset: [16.0, 16.0],
1585                background: None,
1586                padding: [0.0, 0.0],
1587                accent_bar: None,
1588                label: None,
1589            }
1590        );
1591        let (container_entity, container_node) = container(&mut app);
1592        assert_eq!(
1593            container_node,
1594            Node {
1595                position_type: PositionType::Absolute,
1596                top: Val::Px(16.0),
1597                right: Val::Px(16.0),
1598                flex_direction: FlexDirection::Column,
1599                row_gap: Val::Px(4.0),
1600                align_items: AlignItems::FlexEnd,
1601                ..default()
1602            }
1603        );
1604
1605        pick_up(&mut app, DefaultItem::Dirt, 2);
1606        let entities = notifications(&mut app);
1607        assert_eq!(entities.len(), 1);
1608        let entity = entities[0];
1609        assert!(children(&app, entity).is_empty());
1610        assert_eq!(text(&app, entity), line(DefaultItem::Dirt, 2));
1611        let world = app.world();
1612        assert_eq!(world.get::<TextFont>(entity).unwrap().font_size, 18.0);
1613        assert_eq!(
1614            world.get::<TextColor>(entity).unwrap().0,
1615            Color::srgba(1.0, 1.0, 1.0, 1.0)
1616        );
1617        assert_eq!(*world.get::<Node>(entity).unwrap(), Node::default());
1618        assert_eq!(world.get::<BackgroundColor>(entity).unwrap().0, Color::NONE);
1619        assert_eq!(
1620            world.get::<ChildOf>(entity).unwrap().parent(),
1621            container_entity
1622        );
1623    }
1624
1625    #[test]
1626    fn plugin_keeps_resources_inserted_by_the_game() {
1627        let layout = PickupNotificationLayout {
1628            anchor: HudAnchor::BottomRight,
1629            ..default()
1630        };
1631        let mut app = App::new();
1632        app.insert_resource(PickupNotificationFilter::OnRequest)
1633            .insert_resource(layout.clone())
1634            .add_plugins((
1635                MinimalPlugins,
1636                PickupNotificationPlugin::<DefaultItem>::new(),
1637            ));
1638        app.update();
1639        assert_eq!(
1640            *app.world().resource::<PickupNotificationFilter>(),
1641            PickupNotificationFilter::OnRequest
1642        );
1643        assert_eq!(*app.world().resource::<PickupNotificationLayout>(), layout);
1644    }
1645
1646    #[test]
1647    fn every_filter_notifies_each_pickup() {
1648        let mut app = app();
1649        pick_up(&mut app, DefaultItem::Dirt, 1);
1650        pick_up(&mut app, DefaultItem::Dirt, 3);
1651        assert_eq!(
1652            item_lines(&mut app),
1653            [line(DefaultItem::Dirt, 1), line(DefaultItem::Dirt, 3)]
1654        );
1655        assert!(
1656            app.world()
1657                .resource::<PickupNotificationSeen<DefaultItem>>()
1658                .is_empty()
1659        );
1660    }
1661
1662    #[test]
1663    fn first_per_item_type_notifies_once_per_type() {
1664        let mut app = app();
1665        app.insert_resource(PickupNotificationFilter::FirstPerItemType);
1666        pick_up(&mut app, DefaultItem::Dirt, 1);
1667        pick_up(&mut app, DefaultItem::Dirt, 5);
1668        assert_eq!(item_lines(&mut app), [line(DefaultItem::Dirt, 1)]);
1669
1670        pick_up(&mut app, DefaultItem::Sand, 2);
1671        assert_eq!(
1672            item_lines(&mut app),
1673            [line(DefaultItem::Dirt, 1), line(DefaultItem::Sand, 2)]
1674        );
1675        let seen = app
1676            .world()
1677            .resource::<PickupNotificationSeen<DefaultItem>>();
1678        assert!(seen.contains(DefaultItem::Dirt));
1679        assert!(seen.contains(DefaultItem::Sand));
1680        assert_eq!(seen.len(), 2);
1681    }
1682
1683    #[test]
1684    fn first_per_item_type_merges_pickups_of_one_frame() {
1685        let mut app = app();
1686        app.insert_resource(PickupNotificationFilter::FirstPerItemType);
1687        app.world_mut().write_message(ItemPickedUp {
1688            item: DefaultItem::Wood,
1689            count: 1,
1690        });
1691        app.world_mut().write_message(ItemPickedUp {
1692            item: DefaultItem::Wood,
1693            count: 4,
1694        });
1695        app.update();
1696        assert_eq!(item_lines(&mut app), [line(DefaultItem::Wood, 1)]);
1697    }
1698
1699    #[test]
1700    fn seen_record_can_be_restored_and_cleared_by_the_game() {
1701        let mut app = app();
1702        app.insert_resource(PickupNotificationFilter::FirstPerItemType);
1703        app.world_mut()
1704            .resource_mut::<PickupNotificationSeen<DefaultItem>>()
1705            .insert(DefaultItem::Dirt);
1706        pick_up(&mut app, DefaultItem::Dirt, 1);
1707        assert!(notifications(&mut app).is_empty());
1708
1709        app.world_mut()
1710            .resource_mut::<PickupNotificationSeen<DefaultItem>>()
1711            .clear();
1712        pick_up(&mut app, DefaultItem::Dirt, 2);
1713        assert_eq!(item_lines(&mut app), [line(DefaultItem::Dirt, 2)]);
1714    }
1715
1716    #[test]
1717    fn pickup_that_cannot_be_shown_is_not_recorded_as_seen() {
1718        let mut app = app();
1719        app.insert_resource(PickupNotificationFilter::FirstPerItemType)
1720            .insert_resource(PickupNotificationConfig {
1721                max_notifications: 0,
1722                ..default()
1723            });
1724        pick_up(&mut app, DefaultItem::Dirt, 1);
1725        assert!(notifications(&mut app).is_empty());
1726        assert!(
1727            app.world()
1728                .resource::<PickupNotificationSeen<DefaultItem>>()
1729                .is_empty()
1730        );
1731
1732        app.world_mut()
1733            .resource_mut::<PickupNotificationConfig>()
1734            .max_notifications = 5;
1735        pick_up(&mut app, DefaultItem::Dirt, 3);
1736        assert_eq!(item_lines(&mut app), [line(DefaultItem::Dirt, 3)]);
1737    }
1738
1739    #[test]
1740    fn on_request_shows_only_what_the_game_asks_for() {
1741        let mut app = app();
1742        app.insert_resource(PickupNotificationFilter::OnRequest);
1743        pick_up(&mut app, DefaultItem::Dirt, 1);
1744        assert!(notifications(&mut app).is_empty());
1745
1746        app.world_mut()
1747            .write_message(ShowPickupNotification::new(DefaultItem::Sand, 7));
1748        app.update();
1749        assert_eq!(item_lines(&mut app), [line(DefaultItem::Sand, 7)]);
1750    }
1751
1752    #[test]
1753    fn request_is_shown_under_other_filters_without_touching_seen() {
1754        let mut app = app();
1755        app.insert_resource(PickupNotificationFilter::FirstPerItemType);
1756        app.world_mut()
1757            .resource_mut::<PickupNotificationSeen<DefaultItem>>()
1758            .insert(DefaultItem::Dirt);
1759        app.world_mut()
1760            .write_message(ShowPickupNotification::new(DefaultItem::Dirt, 2));
1761        app.world_mut()
1762            .write_message(ShowPickupNotification::new(DefaultItem::Sand, 1));
1763        app.update();
1764        assert_eq!(
1765            item_lines(&mut app),
1766            [line(DefaultItem::Sand, 1), line(DefaultItem::Dirt, 2)]
1767        );
1768        let seen = app
1769            .world()
1770            .resource::<PickupNotificationSeen<DefaultItem>>();
1771        assert!(!seen.contains(DefaultItem::Sand));
1772        assert_eq!(seen.len(), 1);
1773    }
1774
1775    #[test]
1776    fn anchor_and_offset_place_the_container() {
1777        let mut app = app();
1778        app.insert_resource(PickupNotificationLayout {
1779            anchor: HudAnchor::BottomLeft,
1780            offset: [24.0, 40.0],
1781            ..default()
1782        });
1783        app.update();
1784        assert_eq!(
1785            container(&mut app).1,
1786            Node {
1787                position_type: PositionType::Absolute,
1788                left: Val::Px(24.0),
1789                bottom: Val::Px(40.0),
1790                flex_direction: FlexDirection::Column,
1791                row_gap: Val::Px(4.0),
1792                align_items: AlignItems::FlexStart,
1793                ..default()
1794            }
1795        );
1796    }
1797
1798    #[test]
1799    fn centered_anchor_spans_the_screen_shifted_by_the_offset() {
1800        let mut app = app();
1801        app.insert_resource(PickupNotificationLayout {
1802            anchor: HudAnchor::Center,
1803            offset: [10.0, -20.0],
1804            ..default()
1805        });
1806        app.update();
1807        assert_eq!(
1808            container(&mut app).1,
1809            Node {
1810                position_type: PositionType::Absolute,
1811                left: Val::Px(10.0),
1812                right: Val::Px(-10.0),
1813                top: Val::Px(-20.0),
1814                bottom: Val::Px(20.0),
1815                flex_direction: FlexDirection::Column,
1816                row_gap: Val::Px(4.0),
1817                align_items: AlignItems::Center,
1818                justify_content: JustifyContent::Center,
1819                ..default()
1820            }
1821        );
1822    }
1823
1824    #[test]
1825    fn layout_change_at_runtime_moves_the_container() {
1826        let mut app = app();
1827        app.update();
1828        assert_eq!(container(&mut app).1.right, Val::Px(16.0));
1829
1830        app.insert_resource(PickupNotificationLayout {
1831            anchor: HudAnchor::TopLeft,
1832            offset: [8.0, f32::NAN],
1833            ..default()
1834        });
1835        app.update();
1836        let node = container(&mut app).1;
1837        assert_eq!(node.left, Val::Px(8.0));
1838        assert_eq!(node.top, Val::Px(0.0));
1839        assert_eq!(node.right, Val::Auto);
1840        assert_eq!(node.align_items, AlignItems::FlexStart);
1841    }
1842
1843    #[test]
1844    fn background_accent_bar_and_label_are_spawned_on_the_notification() {
1845        let mut app = app();
1846        app.insert_resource(PickupNotificationLayout {
1847            background: Some(BACKGROUND),
1848            padding: [10.0, 6.0],
1849            accent_bar: Some(PickupNotificationAccentBar {
1850                color: ACCENT,
1851                width: 4.0,
1852            }),
1853            label: Some(PickupNotificationLabel {
1854                text: "New item".to_string(),
1855                color: LABEL,
1856            }),
1857            ..default()
1858        });
1859        pick_up(&mut app, DefaultItem::Dirt, 1);
1860
1861        let entities = notifications(&mut app);
1862        assert_eq!(entities.len(), 1);
1863        let root = entities[0];
1864        let root_children = children(&app, root);
1865        assert_eq!(root_children.len(), 2);
1866        let (bar, body) = (root_children[0], root_children[1]);
1867        let body_children = children(&app, body);
1868        assert_eq!(body_children.len(), 2);
1869        let (label, item) = (body_children[0], body_children[1]);
1870        assert_eq!(text(&app, label), "New item");
1871        assert_eq!(text(&app, item), line(DefaultItem::Dirt, 1));
1872
1873        let world = app.world();
1874        assert!(world.get::<Text>(root).is_none());
1875        assert_eq!(
1876            world.get::<BackgroundColor>(root).unwrap().0,
1877            notification_color(BACKGROUND)
1878        );
1879        assert_eq!(
1880            world.get::<Node>(root).unwrap().flex_direction,
1881            FlexDirection::Row
1882        );
1883
1884        assert!(world.get::<NotificationAccentBar>(bar).is_some());
1885        assert_eq!(world.get::<Node>(bar).unwrap().width, Val::Px(4.0));
1886        assert_eq!(
1887            world.get::<BackgroundColor>(bar).unwrap().0,
1888            notification_color(ACCENT)
1889        );
1890
1891        let body_node = world.get::<Node>(body).unwrap();
1892        assert_eq!(body_node.padding, UiRect::axes(Val::Px(10.0), Val::Px(6.0)));
1893        assert_eq!(body_node.flex_direction, FlexDirection::Column);
1894        assert_eq!(body_node.align_items, AlignItems::FlexEnd);
1895
1896        assert!(world.get::<NotificationLabel>(label).is_some());
1897        assert_eq!(
1898            world.get::<TextColor>(label).unwrap().0,
1899            notification_color(LABEL)
1900        );
1901        assert_eq!(world.get::<TextFont>(label).unwrap().font_size, 18.0);
1902        assert_eq!(
1903            world.get::<TextColor>(item).unwrap().0,
1904            Color::srgba(1.0, 1.0, 1.0, 1.0)
1905        );
1906    }
1907
1908    #[test]
1909    fn background_alone_adds_no_bar_and_no_label() {
1910        let mut app = app();
1911        app.insert_resource(PickupNotificationLayout {
1912            background: Some(BACKGROUND),
1913            accent_bar: Some(PickupNotificationAccentBar {
1914                color: ACCENT,
1915                width: 0.0,
1916            }),
1917            ..default()
1918        });
1919        pick_up(&mut app, DefaultItem::Sand, 3);
1920
1921        let entities = notifications(&mut app);
1922        assert_eq!(entities.len(), 1);
1923        let root_children = children(&app, entities[0]);
1924        assert_eq!(root_children.len(), 1);
1925        let body_children = children(&app, root_children[0]);
1926        assert_eq!(body_children.len(), 1);
1927        assert_eq!(text(&app, body_children[0]), line(DefaultItem::Sand, 3));
1928
1929        let world = app.world_mut();
1930        let mut bars = world.query_filtered::<Entity, With<NotificationAccentBar>>();
1931        assert_eq!(bars.iter(world).count(), 0);
1932        let mut labels = world.query_filtered::<Entity, With<NotificationLabel>>();
1933        assert_eq!(labels.iter(world).count(), 0);
1934    }
1935}