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`],
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.
546///
547/// # Default values
548///
549/// | Field               | Default              |
550/// |---------------------|----------------------|
551/// | `visible`           | `true`               |
552/// | `duration_secs`     | `3.0` s              |
553/// | `text_color`        | `[1, 1, 1, 1]` (white) |
554/// | `max_notifications` | `5`                  |
555#[cfg(feature = "items")]
556#[derive(Resource, Debug, Clone)]
557pub struct PickupNotificationConfig {
558    /// When `false`, no notification entities are spawned even when
559    /// [`ItemPickedUp`] messages fire.
560    pub visible: bool,
561    /// How long each notification text persists on screen in seconds before
562    /// being automatically despawned. Applied per-notification via a
563    /// [`Timer`].
564    pub duration_secs: f32,
565    /// RGBA color of the notification text in linear sRGB.
566    pub text_color: [f32; 4],
567    /// Maximum number of notifications displayed at the same time. When a new
568    /// pickup would exceed this limit, the oldest visible notification is
569    /// despawned first to make room.
570    pub max_notifications: usize,
571}
572
573#[cfg(feature = "items")]
574impl Default for PickupNotificationConfig {
575    fn default() -> Self {
576        Self {
577            visible: true,
578            duration_secs: 3.0,
579            text_color: [1.0, 1.0, 1.0, 1.0],
580            max_notifications: 5,
581        }
582    }
583}
584
585/// Timer component on each notification entity.
586#[cfg(feature = "items")]
587#[derive(Component)]
588struct NotificationTimer(Timer);
589
590/// Marker for the notification container.
591#[cfg(feature = "items")]
592#[derive(Component)]
593struct NotificationContainer;
594
595#[cfg(feature = "items")]
596fn spawn_notification_container(mut commands: Commands) {
597    commands.spawn((
598        NotificationContainer,
599        Node {
600            position_type: PositionType::Absolute,
601            top: Val::Px(16.0),
602            right: Val::Px(16.0),
603            flex_direction: FlexDirection::Column,
604            row_gap: Val::Px(4.0),
605            align_items: AlignItems::FlexEnd,
606            ..default()
607        },
608        BackgroundColor(Color::NONE),
609    ));
610}
611
612#[cfg(feature = "items")]
613fn on_item_picked_up<I: ItemType>(
614    mut commands: Commands,
615    mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
616    config: Res<PickupNotificationConfig>,
617    container_query: Query<Entity, With<NotificationContainer>>,
618    existing_query: Query<Entity, With<NotificationTimer>>,
619) {
620    if !config.visible {
621        return;
622    }
623
624    // Collect all pickups this frame
625    let pickups: Vec<(String, u32)> = pickup_reader
626        .read()
627        .map(|p| (p.item.name().to_string(), p.count))
628        .collect();
629
630    if pickups.is_empty() {
631        return;
632    }
633
634    let Ok(container) = container_query.single() else {
635        return;
636    };
637
638    let tc = Color::srgba(
639        config.text_color[0],
640        config.text_color[1],
641        config.text_color[2],
642        config.text_color[3],
643    );
644
645    // Enforce max_notifications — despawn oldest first
646    let existing: Vec<Entity> = existing_query.iter().collect();
647    let available = config.max_notifications.saturating_sub(existing.len());
648    let spawn_count = pickups.len().min(available);
649
650    if existing.len() + pickups.len() > config.max_notifications {
651        let overflow = (existing.len() + pickups.len()).saturating_sub(config.max_notifications);
652        for entity in existing.iter().take(overflow) {
653            commands.entity(*entity).despawn();
654        }
655    }
656
657    for (name, count) in pickups.iter().take(spawn_count) {
658        let label = format!("+{count} {name}");
659        let notification = commands
660            .spawn((
661                NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once)),
662                Text::new(label),
663                TextFont {
664                    font_size: 18.0,
665                    ..default()
666                },
667                TextColor(tc),
668                Node { ..default() },
669            ))
670            .id();
671        commands.entity(container).add_child(notification);
672    }
673}
674
675#[cfg(feature = "items")]
676fn tick_notifications(
677    mut commands: Commands,
678    time: Res<Time>,
679    mut query: Query<(Entity, &mut NotificationTimer)>,
680) {
681    for (entity, mut timer) in query.iter_mut() {
682        timer.0.tick(time.delta());
683        if timer.0.just_finished() {
684            commands.entity(entity).despawn();
685        }
686    }
687}
688
689/// Plugin that displays timed item-pickup notifications at the top-right corner.
690///
691/// Listens for [`ItemPickedUp<I>`] messages and spawns a text node formatted as
692/// `"+N ItemName"` for each pickup. Notifications fade out after
693/// [`PickupNotificationConfig::duration_secs`] and are despawned automatically.
694///
695/// When the number of simultaneous notifications would exceed
696/// [`PickupNotificationConfig::max_notifications`], the oldest notifications are
697/// despawned first.
698///
699/// The plugin is **generic over the item type** `I: ItemType`. Use [`UiPlugin`]
700/// for the built-in [`DefaultItem`], or add this plugin manually with a custom
701/// item type:
702///
703/// ```rust,no_run
704/// use bevy::prelude::*;
705/// use voxel_framework::ui::PickupNotificationPlugin;
706/// # use voxel_framework::items::inventory::ItemType;
707/// # #[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
708/// # struct MyItem;
709/// # impl ItemType for MyItem {
710/// #     fn name(&self) -> &'static str { "item" }
711/// #     fn color(&self) -> [f32; 4] { [1.0, 1.0, 1.0, 1.0] }
712/// #     fn to_byte(&self) -> u8 { 0 }
713/// #     fn from_byte(_: u8) -> Self { Self }
714/// # }
715///
716/// App::new().add_plugins(PickupNotificationPlugin::<MyItem>::new());
717/// ```
718#[cfg(feature = "items")]
719pub struct PickupNotificationPlugin<I: ItemType> {
720    _marker: std::marker::PhantomData<I>,
721}
722
723#[cfg(feature = "items")]
724impl<I: ItemType> PickupNotificationPlugin<I> {
725    pub fn new() -> Self {
726        Self {
727            _marker: std::marker::PhantomData,
728        }
729    }
730}
731
732#[cfg(feature = "items")]
733impl<I: ItemType> Default for PickupNotificationPlugin<I> {
734    fn default() -> Self {
735        Self::new()
736    }
737}
738
739#[cfg(feature = "items")]
740impl<I: ItemType> Plugin for PickupNotificationPlugin<I> {
741    fn build(&self, app: &mut App) {
742        app.init_resource::<PickupNotificationConfig>();
743        // Ensure the message is registered even if DropsPlugin<I> is not used.
744        app.add_message::<ItemPickedUp<I>>();
745        app.add_systems(Startup, spawn_notification_container);
746        app.add_systems(Update, (on_item_picked_up::<I>, tick_notifications));
747    }
748}
749
750mod pause_menu;
751pub use pause_menu::{
752    ButtonColors, PauseMenuConfig, PauseMenuPlugin, PauseMenuState, PauseMenuTheme,
753    SaveSettingsRequest,
754};
755
756// ─── Debug Overlay ────────────────────────────────────────────────────────────
757
758use crate::chunk::world_to_chunk_coord;
759use crate::player::Player;
760use crate::world::ChunkManager;
761use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
762
763/// Tracks whether the debug overlay (F3) is currently visible.
764#[derive(Resource, Default)]
765pub struct DebugOverlayState {
766    /// When `true` the overlay is rendered; toggle with **F3**.
767    pub visible: bool,
768}
769
770/// Marker component for the debug overlay root node.
771#[derive(Component)]
772struct DebugOverlay;
773
774/// Marker for the individual text lines (index 0–3).
775#[derive(Component)]
776struct DebugLine(usize);
777
778fn spawn_debug_overlay(mut commands: Commands) {
779    commands
780        .spawn((
781            DebugOverlay,
782            Node {
783                position_type: PositionType::Absolute,
784                top: Val::Px(8.0),
785                left: Val::Px(8.0),
786                flex_direction: FlexDirection::Column,
787                row_gap: Val::Px(2.0),
788                padding: UiRect::all(Val::Px(6.0)),
789                ..default()
790            },
791            BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
792            Visibility::Hidden,
793            ZIndex(200),
794        ))
795        .with_children(|root| {
796            let style = TextFont {
797                font_size: 14.0,
798                ..default()
799            };
800            let color = TextColor(Color::WHITE);
801            for i in 0..4 {
802                root.spawn((DebugLine(i), Text::new(""), style.clone(), color));
803            }
804        });
805}
806
807fn update_debug_overlay(
808    keys: Res<ButtonInput<KeyCode>>,
809    mut state: ResMut<DebugOverlayState>,
810    mut overlay_q: Query<&mut Visibility, With<DebugOverlay>>,
811    mut line_q: Query<(&DebugLine, &mut Text)>,
812    player_q: Query<&Transform, With<Player>>,
813    manager: Res<ChunkManager>,
814    diagnostics: Res<DiagnosticsStore>,
815) {
816    // Toggle visibility on F3 press.
817    if keys.just_pressed(KeyCode::F3) {
818        state.visible = !state.visible;
819        if let Ok(mut vis) = overlay_q.single_mut() {
820            *vis = if state.visible {
821                Visibility::Visible
822            } else {
823                Visibility::Hidden
824            };
825        }
826    }
827
828    if !state.visible {
829        return;
830    }
831
832    let pos = player_q
833        .single()
834        .map(|t| t.translation)
835        .unwrap_or(Vec3::ZERO);
836
837    let chunk = world_to_chunk_coord(pos);
838    let fps = diagnostics
839        .get(&FrameTimeDiagnosticsPlugin::FPS)
840        .and_then(|d| d.smoothed())
841        .unwrap_or(0.0);
842    let chunk_count = manager.loaded_count();
843
844    let lines = [
845        format!("XYZ: {:.1} / {:.1} / {:.1}", pos.x, pos.y, pos.z),
846        format!("Chunk: {} {} {}", chunk.x, chunk.y, chunk.z),
847        format!("FPS: {fps:.0}"),
848        format!("Chunks: {chunk_count}"),
849    ];
850
851    for (line_marker, mut text) in line_q.iter_mut() {
852        if let Some(content) = lines.get(line_marker.0) {
853            *text = Text::new(content.clone());
854        }
855    }
856}
857
858/// Plugin that renders a debug information overlay toggled with **F3**.
859///
860/// Shows player XYZ position, current chunk coordinate, FPS, and loaded chunk
861/// count. The overlay is hidden by default; press **F3** to show or hide it.
862///
863/// Automatically adds [`FrameTimeDiagnosticsPlugin`] for FPS measurement.
864///
865/// # Example
866///
867/// ```rust,no_run
868/// use bevy::prelude::*;
869/// use voxel_framework::ui::DebugOverlayPlugin;
870///
871/// App::new().add_plugins(DebugOverlayPlugin);
872/// ```
873pub struct DebugOverlayPlugin;
874
875impl Plugin for DebugOverlayPlugin {
876    fn build(&self, app: &mut App) {
877        app.add_plugins(FrameTimeDiagnosticsPlugin::default());
878        app.init_resource::<DebugOverlayState>();
879        app.add_systems(Startup, spawn_debug_overlay);
880        app.add_systems(Update, update_debug_overlay);
881    }
882}
883
884// ─── (InventoryUiPlugin removed — games provide their own inventory UI) ───────
885
886// ─── UiPlugin (umbrella) ──────────────────────────────────────────────────────
887
888#[cfg(feature = "items")]
889use crate::items::inventory::DefaultItem;
890
891#[cfg_attr(
892    feature = "items",
893    doc = "Umbrella plugin that adds all four HUD sub-plugins with [`DefaultItem`]."
894)]
895#[cfg_attr(
896    not(feature = "items"),
897    doc = "Umbrella plugin for the built-in HUD sub-plugins; item-specific overlays require the `items` feature."
898)]
899///
900#[cfg_attr(
901    feature = "items",
902    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."
903)]
904#[cfg_attr(
905    not(feature = "items"),
906    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."
907)]
908///
909#[cfg_attr(
910    feature = "items",
911    doc = "To use a custom item type for pickup notifications, skip `UiPlugin` and add [`PickupNotificationPlugin::<YourItem>::new()`] alongside the other plugins individually."
912)]
913#[cfg_attr(
914    not(feature = "items"),
915    doc = "Enable the `items` feature before configuring item-specific pickup notifications or hotbar UI."
916)]
917///
918/// # Example
919///
920/// ```rust,no_run
921/// use bevy::prelude::*;
922/// use voxel_framework::ui::UiPlugin;
923///
924/// App::new()
925///     .add_plugins(DefaultPlugins)
926///     .add_plugins(UiPlugin);
927/// ```
928pub struct UiPlugin;
929
930impl Plugin for UiPlugin {
931    fn build(&self, app: &mut App) {
932        app.add_plugins(CrosshairPlugin);
933        app.add_plugins(LoadingScreenPlugin);
934        #[cfg(feature = "items")]
935        app.add_plugins(HotbarUiPlugin);
936        #[cfg(feature = "items")]
937        app.add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
938    }
939}
940
941#[cfg(test)]
942mod loading_screen_tests {
943    use super::*;
944    use bevy::ecs::system::RunSystemOnce;
945
946    fn spawn_overlay(world: &mut World) {
947        world
948            .run_system_once(spawn_loading_overlay)
949            .expect("spawn_loading_overlay should run");
950    }
951
952    /// Background color of the bar's fill, and the entity it is a child of.
953    fn bar_fill(world: &mut World) -> (Color, Entity) {
954        let mut query =
955            world.query_filtered::<(&BackgroundColor, &ChildOf), With<LoadingProgressBar>>();
956        let (bg, child_of) = query.single(world).expect("one progress bar fill");
957        (bg.0, child_of.parent())
958    }
959
960    /// Background color of the bar's track, and the track entity.
961    fn bar_track(world: &mut World) -> (Color, Entity) {
962        let mut query =
963            world.query_filtered::<(&BackgroundColor, Entity), With<LoadingProgressBarTrack>>();
964        let (bg, entity) = query.single(world).expect("one progress bar track");
965        (bg.0, entity)
966    }
967
968    #[test]
969    fn default_loading_theme_equals_the_previous_constants() {
970        let theme = LoadingScreenTheme::default();
971        assert_eq!(theme.bar_color, Color::srgba(0.2, 0.7, 0.3, 1.0));
972        assert_eq!(theme.bar_background, Color::srgba(0.2, 0.2, 0.2, 1.0));
973    }
974
975    #[test]
976    fn loading_bar_without_a_theme_resource_keeps_the_previous_colors() {
977        let mut world = World::new();
978        world.insert_resource(LoadingScreenConfig::default());
979
980        spawn_overlay(&mut world);
981
982        let (track_color, track) = bar_track(&mut world);
983        let (fill_color, fill_parent) = bar_fill(&mut world);
984        assert_eq!(track_color, Color::srgba(0.2, 0.2, 0.2, 1.0));
985        assert_eq!(fill_color, Color::srgba(0.2, 0.7, 0.3, 1.0));
986        assert_eq!(fill_parent, track);
987    }
988
989    #[test]
990    fn custom_loading_theme_colors_the_bar_and_its_track() {
991        let theme = LoadingScreenTheme {
992            bar_color: Color::srgb(0.9, 0.1, 0.2),
993            bar_background: Color::srgb(0.1, 0.2, 0.9),
994        };
995        let mut world = World::new();
996        world.insert_resource(LoadingScreenConfig::default());
997        world.insert_resource(theme.clone());
998
999        spawn_overlay(&mut world);
1000
1001        let (track_color, track) = bar_track(&mut world);
1002        let (fill_color, fill_parent) = bar_fill(&mut world);
1003        assert_eq!(track_color, theme.bar_background);
1004        assert_eq!(fill_color, theme.bar_color);
1005        assert_eq!(fill_parent, track);
1006
1007        // The theme does not touch what `LoadingScreenConfig` owns.
1008        let mut overlay = world.query_filtered::<&BackgroundColor, With<LoadingOverlay>>();
1009        assert_eq!(
1010            overlay.single(&world).expect("one overlay").0,
1011            Color::srgba(0.05, 0.05, 0.05, 0.95)
1012        );
1013    }
1014
1015    #[test]
1016    fn loading_theme_is_unused_when_the_bar_is_hidden() {
1017        let mut world = World::new();
1018        world.insert_resource(LoadingScreenConfig {
1019            show_progress_bar: false,
1020            ..Default::default()
1021        });
1022        world.insert_resource(LoadingScreenTheme::default());
1023
1024        spawn_overlay(&mut world);
1025
1026        let mut tracks = world.query_filtered::<Entity, With<LoadingProgressBarTrack>>();
1027        assert_eq!(tracks.iter(&world).count(), 0);
1028        let mut fills = world.query_filtered::<Entity, With<LoadingProgressBar>>();
1029        assert_eq!(fills.iter(&world).count(), 0);
1030    }
1031}