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