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