#![cfg_attr(
feature = "items",
doc = "| [`PickupNotificationPlugin`] | Timed pop-up text on item pickup, top-right by default |"
)]
#![cfg_attr(
not(feature = "items"),
doc = "| `PickupNotificationPlugin` *(feature `items`)* | Timed pop-up text on item pickup, top-right by default |"
)]
#![cfg_attr(
feature = "items",
doc = "Use [`UiPlugin`] when your game uses [`DefaultItem`] and wants all four HUD elements with zero configuration:"
)]
#![cfg_attr(
not(feature = "items"),
doc = "Use [`UiPlugin`] with the default `items` feature when your game uses `DefaultItem` and wants all four HUD elements with zero configuration:"
)]
use bevy::prelude::*;
#[cfg(feature = "items")]
use crate::items::inventory::ItemPickedUp;
#[cfg(feature = "items")]
use crate::items::inventory::ItemType;
use crate::world::loading::{LoadingProgress, WorldLoadingState};
pub mod hud;
pub use hud::{
HudAnchor, HudBar, HudBindingKind, HudDefinitionError, HudDiagnostic, HudDiagnosticKind,
HudElementDefinition, HudElementId, HudElementSnapshot, HudIcon, HudIconSource, HudPlacement,
HudPresentation, HudRegistry, HudRegistryError, HudScalar, HudScalarField, HudSegments,
HudStackDirection, HudStyleOverride, HudSystemSet, HudText, HudTheme, HudValue,
HudValueChanged, HudValueError, HudValueId, HudValueKind, HudValueSet, HudValueSnapshot,
MAX_HUD_SEGMENTS, VoxelHudPlugin, remove_hud_value, set_hud_value,
};
#[derive(Resource, Debug, Clone)]
pub struct CrosshairConfig {
pub color: [f32; 4],
pub size: f32,
pub gap: f32,
pub thickness: f32,
pub visible: bool,
}
impl Default for CrosshairConfig {
fn default() -> Self {
Self {
color: [1.0, 1.0, 1.0, 1.0],
size: 20.0,
gap: 4.0,
thickness: 2.0,
visible: true,
}
}
}
#[derive(Component)]
struct CrosshairNode;
fn spawn_crosshair(mut commands: Commands, config: Res<CrosshairConfig>) {
if !config.visible {
return;
}
let c = &*config;
let color = Color::srgba(c.color[0], c.color[1], c.color[2], c.color[3]);
commands
.spawn((
CrosshairNode,
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
position_type: PositionType::Absolute,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::NONE),
))
.with_children(|root| {
root.spawn((
CrosshairNode,
Node {
position_type: PositionType::Absolute,
width: Val::Px(c.size),
height: Val::Px(c.thickness),
right: Val::Px(c.gap + c.size / 2.0 + c.size / 2.0),
top: Val::Px(-c.thickness / 2.0),
..default()
},
BackgroundColor(color),
));
root.spawn((
CrosshairNode,
Node {
position_type: PositionType::Absolute,
width: Val::Px(c.size),
height: Val::Px(c.thickness),
left: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
top: Val::Px(-c.thickness / 2.0),
..default()
},
BackgroundColor(color),
));
root.spawn((
CrosshairNode,
Node {
position_type: PositionType::Absolute,
width: Val::Px(c.thickness),
height: Val::Px(c.size),
left: Val::Px(-c.thickness / 2.0),
bottom: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
..default()
},
BackgroundColor(color),
));
root.spawn((
CrosshairNode,
Node {
position_type: PositionType::Absolute,
width: Val::Px(c.thickness),
height: Val::Px(c.size),
left: Val::Px(-c.thickness / 2.0),
top: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
..default()
},
BackgroundColor(color),
));
});
}
pub struct CrosshairPlugin;
impl Plugin for CrosshairPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<CrosshairConfig>();
app.add_systems(Startup, spawn_crosshair);
}
}
#[derive(Resource, Debug, Clone)]
pub struct LoadingScreenConfig {
pub background_color: [f32; 4],
pub text_color: [f32; 4],
pub title: String,
pub show_progress_bar: bool,
}
impl Default for LoadingScreenConfig {
fn default() -> Self {
Self {
background_color: [0.05, 0.05, 0.05, 0.95],
text_color: [1.0, 1.0, 1.0, 1.0],
title: "Loading...".to_string(),
show_progress_bar: true,
}
}
}
#[derive(Resource, Debug, Clone, PartialEq)]
pub struct LoadingScreenTheme {
pub bar_color: Color,
pub bar_background: Color,
}
impl Default for LoadingScreenTheme {
fn default() -> Self {
Self {
bar_color: Color::srgba(0.2, 0.7, 0.3, 1.0),
bar_background: Color::srgba(0.2, 0.2, 0.2, 1.0),
}
}
}
#[derive(Component)]
struct LoadingOverlay;
#[derive(Component)]
struct LoadingText;
#[derive(Component)]
struct LoadingProgressBarTrack;
#[derive(Component)]
struct LoadingProgressBar;
fn spawn_loading_overlay(
mut commands: Commands,
config: Res<LoadingScreenConfig>,
theme: Option<Res<LoadingScreenTheme>>,
) {
let theme = theme.as_deref().cloned().unwrap_or_default();
let bg = Color::srgba(
config.background_color[0],
config.background_color[1],
config.background_color[2],
config.background_color[3],
);
let tc = Color::srgba(
config.text_color[0],
config.text_color[1],
config.text_color[2],
config.text_color[3],
);
commands
.spawn((
LoadingOverlay,
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
position_type: PositionType::Absolute,
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(bg),
ZIndex(100),
))
.with_children(|parent| {
parent.spawn((
LoadingText,
Text::new(config.title.clone()),
TextFont {
font_size: 32.0,
..default()
},
TextColor(tc),
));
if config.show_progress_bar {
parent
.spawn((
LoadingProgressBarTrack,
Node {
width: Val::Px(400.0),
height: Val::Px(20.0),
margin: UiRect::top(Val::Px(20.0)),
..default()
},
BackgroundColor(theme.bar_background),
))
.with_children(|bar| {
bar.spawn((
LoadingProgressBar,
Node {
width: Val::Percent(0.0),
height: Val::Percent(100.0),
..default()
},
BackgroundColor(theme.bar_color),
));
});
}
});
}
fn update_loading_overlay(
loading_state: Res<WorldLoadingState>,
mut progress_reader: bevy::ecs::message::MessageReader<LoadingProgress>,
mut overlay_query: Query<&mut Visibility, With<LoadingOverlay>>,
mut text_query: Query<&mut Text, With<LoadingText>>,
mut bar_query: Query<&mut Node, With<LoadingProgressBar>>,
) {
if loading_state.ready {
if let Ok(mut vis) = overlay_query.single_mut() {
*vis = Visibility::Hidden;
}
return;
}
let mut latest: Option<LoadingProgress> = None;
for msg in progress_reader.read() {
latest = Some(msg.clone());
}
if let Some(progress) = latest {
if let Ok(mut text) = text_query.single_mut() {
*text = Text::new(format!(
"Loading... {}/{} chunks",
progress.loaded, progress.total
));
}
if let Ok(mut node) = bar_query.single_mut() {
node.width = Val::Percent((progress.progress * 100.0).clamp(0.0, 100.0));
}
}
}
fn despawn_loading_overlay_on_ready(
mut commands: Commands,
loading_state: Res<WorldLoadingState>,
overlay_query: Query<Entity, With<LoadingOverlay>>,
) {
if loading_state.ready {
for entity in overlay_query.iter() {
commands.entity(entity).despawn();
}
}
}
pub struct LoadingScreenPlugin;
impl Plugin for LoadingScreenPlugin {
fn build(&self, app: &mut App) {
app.init_resource::<LoadingScreenConfig>();
app.init_resource::<LoadingScreenTheme>();
app.add_systems(Startup, spawn_loading_overlay);
app.add_systems(
Update,
(update_loading_overlay, despawn_loading_overlay_on_ready),
);
}
}
#[cfg(feature = "items")]
pub mod hotbar;
#[cfg(feature = "items")]
pub use hotbar::{HotbarContentPlugin, HotbarUiConfig, HotbarUiPlugin, ItemIconPalette};
#[cfg(feature = "items")]
#[derive(Resource, Debug, Clone)]
pub struct PickupNotificationConfig {
pub visible: bool,
pub duration_secs: f32,
pub text_color: [f32; 4],
pub max_notifications: usize,
}
#[cfg(feature = "items")]
impl Default for PickupNotificationConfig {
fn default() -> Self {
Self {
visible: true,
duration_secs: 3.0,
text_color: [1.0, 1.0, 1.0, 1.0],
max_notifications: 5,
}
}
}
#[cfg(feature = "items")]
#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum PickupNotificationFilter {
#[default]
Every,
FirstPerItemType,
OnRequest,
}
#[cfg(feature = "items")]
#[derive(Resource, Clone, Default)]
pub struct PickupNotificationSeen<I: ItemType> {
seen: std::collections::HashSet<I>,
}
#[cfg(feature = "items")]
impl<I: ItemType> PickupNotificationSeen<I> {
pub fn contains(&self, item: I) -> bool {
self.seen.contains(&item)
}
pub fn insert(&mut self, item: I) -> bool {
self.seen.insert(item)
}
pub fn clear(&mut self) {
self.seen.clear();
}
pub fn len(&self) -> usize {
self.seen.len()
}
pub fn is_empty(&self) -> bool {
self.seen.is_empty()
}
}
#[cfg(feature = "items")]
#[derive(Message, Debug, Clone)]
pub struct ShowPickupNotification<I: ItemType> {
pub item: I,
pub count: u32,
}
#[cfg(feature = "items")]
impl<I: ItemType> ShowPickupNotification<I> {
pub fn new(item: I, count: u32) -> Self {
Self { item, count }
}
}
#[cfg(feature = "items")]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PickupNotificationAccentBar {
pub color: [f32; 4],
pub width: f32,
}
#[cfg(feature = "items")]
#[derive(Debug, Clone, PartialEq)]
pub struct PickupNotificationLabel {
pub text: String,
pub color: [f32; 4],
}
#[cfg(feature = "items")]
#[derive(Resource, Debug, Clone, PartialEq)]
pub struct PickupNotificationLayout {
pub anchor: HudAnchor,
pub offset: [f32; 2],
pub background: Option<[f32; 4]>,
pub padding: [f32; 2],
pub accent_bar: Option<PickupNotificationAccentBar>,
pub label: Option<PickupNotificationLabel>,
}
#[cfg(feature = "items")]
impl Default for PickupNotificationLayout {
fn default() -> Self {
Self {
anchor: HudAnchor::TopRight,
offset: [16.0, 16.0],
background: None,
padding: [0.0, 0.0],
accent_bar: None,
label: None,
}
}
}
#[cfg(feature = "items")]
const NOTIFICATION_FONT_SIZE: f32 = 18.0;
#[cfg(feature = "items")]
#[derive(Component)]
struct NotificationTimer(Timer);
#[cfg(feature = "items")]
#[derive(Component)]
struct NotificationContainer;
#[cfg(feature = "items")]
#[derive(Component)]
struct NotificationAccentBar;
#[cfg(feature = "items")]
#[derive(Component)]
struct NotificationLabel;
#[cfg(feature = "items")]
#[derive(Clone, Copy)]
enum NotificationAxis {
Start,
Center,
End,
}
#[cfg(feature = "items")]
fn notification_axes(anchor: HudAnchor) -> (NotificationAxis, NotificationAxis) {
use NotificationAxis::{Center, End, Start};
match anchor {
HudAnchor::TopLeft => (Start, Start),
HudAnchor::TopCenter => (Center, Start),
HudAnchor::TopRight => (End, Start),
HudAnchor::CenterLeft => (Start, Center),
HudAnchor::Center => (Center, Center),
HudAnchor::CenterRight => (End, Center),
HudAnchor::BottomLeft => (Start, End),
HudAnchor::BottomCenter => (Center, End),
HudAnchor::BottomRight => (End, End),
}
}
#[cfg(feature = "items")]
fn notification_align(axis: NotificationAxis) -> AlignItems {
match axis {
NotificationAxis::Start => AlignItems::FlexStart,
NotificationAxis::Center => AlignItems::Center,
NotificationAxis::End => AlignItems::FlexEnd,
}
}
#[cfg(feature = "items")]
fn finite_or_zero(value: f32) -> f32 {
if value.is_finite() { value } else { 0.0 }
}
#[cfg(feature = "items")]
fn positive_or_zero(value: f32) -> f32 {
if value.is_finite() && value > 0.0 {
value
} else {
0.0
}
}
#[cfg(feature = "items")]
fn notification_color(rgba: [f32; 4]) -> Color {
Color::srgba(rgba[0], rgba[1], rgba[2], rgba[3])
}
#[cfg(feature = "items")]
fn notification_container_node(layout: &PickupNotificationLayout) -> Node {
let [x, y] = layout.offset.map(finite_or_zero);
let (horizontal, vertical) = notification_axes(layout.anchor);
let mut node = Node {
position_type: PositionType::Absolute,
flex_direction: FlexDirection::Column,
row_gap: Val::Px(4.0),
align_items: notification_align(horizontal),
..default()
};
match horizontal {
NotificationAxis::Start => node.left = Val::Px(x),
NotificationAxis::Center => {
node.left = Val::Px(x);
node.right = Val::Px(-x);
}
NotificationAxis::End => node.right = Val::Px(x),
}
match vertical {
NotificationAxis::Start => node.top = Val::Px(y),
NotificationAxis::Center => {
node.top = Val::Px(y);
node.bottom = Val::Px(-y);
node.justify_content = JustifyContent::Center;
}
NotificationAxis::End => node.bottom = Val::Px(y),
}
node
}
#[cfg(feature = "items")]
fn spawn_notification_container(mut commands: Commands, layout: Res<PickupNotificationLayout>) {
commands.spawn((
NotificationContainer,
notification_container_node(&layout),
BackgroundColor(Color::NONE),
));
}
#[cfg(feature = "items")]
fn apply_notification_layout(
layout: Res<PickupNotificationLayout>,
mut container_query: Query<&mut Node, With<NotificationContainer>>,
) {
if !layout.is_changed() {
return;
}
let desired = notification_container_node(&layout);
for mut node in container_query.iter_mut() {
if *node != desired {
*node = desired.clone();
}
}
}
#[cfg(feature = "items")]
fn spawn_notification(
commands: &mut Commands,
container: Entity,
config: &PickupNotificationConfig,
layout: &PickupNotificationLayout,
text: String,
) {
let timer = NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once));
let text_font = TextFont {
font_size: NOTIFICATION_FONT_SIZE,
..default()
};
let item_line = (
Text::new(text),
text_font.clone(),
TextColor(notification_color(config.text_color)),
Node { ..default() },
);
let [pad_x, pad_y] = layout.padding.map(positive_or_zero);
let accent_bar = layout
.accent_bar
.filter(|bar| positive_or_zero(bar.width) > 0.0);
let decorated = layout.background.is_some()
|| accent_bar.is_some()
|| layout.label.is_some()
|| pad_x > 0.0
|| pad_y > 0.0;
if !decorated {
let notification = commands.spawn((timer, item_line)).id();
commands.entity(container).add_child(notification);
return;
}
let notification = commands
.spawn((
timer,
Node {
flex_direction: FlexDirection::Row,
align_items: AlignItems::Stretch,
..default()
},
BackgroundColor(
layout
.background
.map(notification_color)
.unwrap_or(Color::NONE),
),
))
.id();
if let Some(bar) = accent_bar {
let bar_entity = commands
.spawn((
NotificationAccentBar,
Node {
width: Val::Px(bar.width),
..default()
},
BackgroundColor(notification_color(bar.color)),
))
.id();
commands.entity(notification).add_child(bar_entity);
}
let (horizontal, _) = notification_axes(layout.anchor);
let body = commands
.spawn(Node {
flex_direction: FlexDirection::Column,
align_items: notification_align(horizontal),
padding: UiRect::axes(Val::Px(pad_x), Val::Px(pad_y)),
..default()
})
.id();
commands.entity(notification).add_child(body);
if let Some(label) = &layout.label {
let label_entity = commands
.spawn((
NotificationLabel,
Text::new(label.text.clone()),
text_font,
TextColor(notification_color(label.color)),
Node { ..default() },
))
.id();
commands.entity(body).add_child(label_entity);
}
let item_entity = commands.spawn(item_line).id();
commands.entity(body).add_child(item_entity);
commands.entity(container).add_child(notification);
}
#[cfg(feature = "items")]
#[allow(clippy::too_many_arguments)]
fn on_item_picked_up<I: ItemType>(
mut commands: Commands,
mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
mut request_reader: bevy::ecs::message::MessageReader<ShowPickupNotification<I>>,
config: Res<PickupNotificationConfig>,
filter: Res<PickupNotificationFilter>,
layout: Res<PickupNotificationLayout>,
mut seen: ResMut<PickupNotificationSeen<I>>,
container_query: Query<Entity, With<NotificationContainer>>,
existing_query: Query<Entity, With<NotificationTimer>>,
) {
if !config.visible {
return;
}
let mut pending: Vec<(I, u32, bool)> = Vec::new();
for pickup in pickup_reader.read() {
match *filter {
PickupNotificationFilter::Every => pending.push((pickup.item, pickup.count, false)),
PickupNotificationFilter::FirstPerItemType => {
let queued = pending
.iter()
.any(|(item, _, first_of_type)| *first_of_type && *item == pickup.item);
if !queued && !seen.contains(pickup.item) {
pending.push((pickup.item, pickup.count, true));
}
}
PickupNotificationFilter::OnRequest => {}
}
}
for request in request_reader.read() {
pending.push((request.item, request.count, false));
}
if pending.is_empty() {
return;
}
let Ok(container) = container_query.single() else {
return;
};
let existing: Vec<Entity> = existing_query.iter().collect();
let available = config.max_notifications.saturating_sub(existing.len());
let spawn_count = pending.len().min(available);
if existing.len() + pending.len() > config.max_notifications {
let overflow = (existing.len() + pending.len()).saturating_sub(config.max_notifications);
for entity in existing.iter().take(overflow) {
commands.entity(*entity).despawn();
}
}
for (item, count, first_of_type) in pending.into_iter().take(spawn_count) {
if first_of_type {
seen.insert(item);
}
let text = format!("+{count} {}", item.name());
spawn_notification(&mut commands, container, &config, &layout, text);
}
}
#[cfg(feature = "items")]
fn tick_notifications(
mut commands: Commands,
time: Res<Time>,
mut query: Query<(Entity, &mut NotificationTimer)>,
) {
for (entity, mut timer) in query.iter_mut() {
timer.0.tick(time.delta());
if timer.0.just_finished() {
commands.entity(entity).despawn();
}
}
}
#[cfg(feature = "items")]
pub struct PickupNotificationPlugin<I: ItemType> {
_marker: std::marker::PhantomData<I>,
}
#[cfg(feature = "items")]
impl<I: ItemType> PickupNotificationPlugin<I> {
pub fn new() -> Self {
Self {
_marker: std::marker::PhantomData,
}
}
}
#[cfg(feature = "items")]
impl<I: ItemType> Default for PickupNotificationPlugin<I> {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "items")]
impl<I: ItemType> Plugin for PickupNotificationPlugin<I> {
fn build(&self, app: &mut App) {
app.init_resource::<PickupNotificationConfig>();
app.init_resource::<PickupNotificationFilter>();
app.init_resource::<PickupNotificationLayout>();
app.init_resource::<PickupNotificationSeen<I>>();
app.add_message::<ItemPickedUp<I>>();
app.add_message::<ShowPickupNotification<I>>();
app.add_systems(Startup, spawn_notification_container);
app.add_systems(
Update,
(
apply_notification_layout,
on_item_picked_up::<I>,
tick_notifications,
),
);
}
}
mod pause_menu;
pub use pause_menu::{
ButtonColors, PauseMenuConfig, PauseMenuPlugin, PauseMenuState, PauseMenuTheme,
SaveSettingsRequest,
};
use crate::chunk::world_to_chunk_coord;
use crate::player::Player;
use crate::world::ChunkManager;
use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
#[derive(Resource, Default)]
pub struct DebugOverlayState {
pub visible: bool,
}
#[derive(Component)]
struct DebugOverlay;
#[derive(Component)]
struct DebugLine(usize);
fn spawn_debug_overlay(mut commands: Commands) {
commands
.spawn((
DebugOverlay,
Node {
position_type: PositionType::Absolute,
top: Val::Px(8.0),
left: Val::Px(8.0),
flex_direction: FlexDirection::Column,
row_gap: Val::Px(2.0),
padding: UiRect::all(Val::Px(6.0)),
..default()
},
BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
Visibility::Hidden,
ZIndex(200),
))
.with_children(|root| {
let style = TextFont {
font_size: 14.0,
..default()
};
let color = TextColor(Color::WHITE);
for i in 0..4 {
root.spawn((DebugLine(i), Text::new(""), style.clone(), color));
}
});
}
fn update_debug_overlay(
keys: Res<ButtonInput<KeyCode>>,
mut state: ResMut<DebugOverlayState>,
mut overlay_q: Query<&mut Visibility, With<DebugOverlay>>,
mut line_q: Query<(&DebugLine, &mut Text)>,
player_q: Query<&Transform, With<Player>>,
manager: Res<ChunkManager>,
diagnostics: Res<DiagnosticsStore>,
) {
if keys.just_pressed(KeyCode::F3) {
state.visible = !state.visible;
if let Ok(mut vis) = overlay_q.single_mut() {
*vis = if state.visible {
Visibility::Visible
} else {
Visibility::Hidden
};
}
}
if !state.visible {
return;
}
let pos = player_q
.single()
.map(|t| t.translation)
.unwrap_or(Vec3::ZERO);
let chunk = world_to_chunk_coord(pos);
let fps = diagnostics
.get(&FrameTimeDiagnosticsPlugin::FPS)
.and_then(|d| d.smoothed())
.unwrap_or(0.0);
let chunk_count = manager.loaded_count();
let lines = [
format!("XYZ: {:.1} / {:.1} / {:.1}", pos.x, pos.y, pos.z),
format!("Chunk: {} {} {}", chunk.x, chunk.y, chunk.z),
format!("FPS: {fps:.0}"),
format!("Chunks: {chunk_count}"),
];
for (line_marker, mut text) in line_q.iter_mut() {
if let Some(content) = lines.get(line_marker.0) {
*text = Text::new(content.clone());
}
}
}
pub struct DebugOverlayPlugin;
impl Plugin for DebugOverlayPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(FrameTimeDiagnosticsPlugin::default());
app.init_resource::<DebugOverlayState>();
app.add_systems(Startup, spawn_debug_overlay);
app.add_systems(Update, update_debug_overlay);
}
}
#[cfg(feature = "items")]
use crate::items::inventory::DefaultItem;
#[cfg_attr(
feature = "items",
doc = "Umbrella plugin that adds all four HUD sub-plugins with [`DefaultItem`]."
)]
#[cfg_attr(
not(feature = "items"),
doc = "Umbrella plugin for the built-in HUD sub-plugins; item-specific overlays require the `items` feature."
)]
#[cfg_attr(
feature = "items",
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."
)]
#[cfg_attr(
not(feature = "items"),
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."
)]
#[cfg_attr(
feature = "items",
doc = "To use a custom item type for pickup notifications, skip `UiPlugin` and add [`PickupNotificationPlugin::<YourItem>::new()`] alongside the other plugins individually."
)]
#[cfg_attr(
not(feature = "items"),
doc = "Enable the `items` feature before configuring item-specific pickup notifications or hotbar UI."
)]
pub struct UiPlugin;
impl Plugin for UiPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(CrosshairPlugin);
app.add_plugins(LoadingScreenPlugin);
#[cfg(feature = "items")]
app.add_plugins(HotbarUiPlugin);
#[cfg(feature = "items")]
app.add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
}
}
#[cfg(test)]
mod loading_screen_tests {
use super::*;
use bevy::ecs::system::RunSystemOnce;
fn spawn_overlay(world: &mut World) {
world
.run_system_once(spawn_loading_overlay)
.expect("spawn_loading_overlay should run");
}
fn bar_fill(world: &mut World) -> (Color, Entity) {
let mut query =
world.query_filtered::<(&BackgroundColor, &ChildOf), With<LoadingProgressBar>>();
let (bg, child_of) = query.single(world).expect("one progress bar fill");
(bg.0, child_of.parent())
}
fn bar_track(world: &mut World) -> (Color, Entity) {
let mut query =
world.query_filtered::<(&BackgroundColor, Entity), With<LoadingProgressBarTrack>>();
let (bg, entity) = query.single(world).expect("one progress bar track");
(bg.0, entity)
}
#[test]
fn default_loading_theme_equals_the_previous_constants() {
let theme = LoadingScreenTheme::default();
assert_eq!(theme.bar_color, Color::srgba(0.2, 0.7, 0.3, 1.0));
assert_eq!(theme.bar_background, Color::srgba(0.2, 0.2, 0.2, 1.0));
}
#[test]
fn loading_bar_without_a_theme_resource_keeps_the_previous_colors() {
let mut world = World::new();
world.insert_resource(LoadingScreenConfig::default());
spawn_overlay(&mut world);
let (track_color, track) = bar_track(&mut world);
let (fill_color, fill_parent) = bar_fill(&mut world);
assert_eq!(track_color, Color::srgba(0.2, 0.2, 0.2, 1.0));
assert_eq!(fill_color, Color::srgba(0.2, 0.7, 0.3, 1.0));
assert_eq!(fill_parent, track);
}
#[test]
fn custom_loading_theme_colors_the_bar_and_its_track() {
let theme = LoadingScreenTheme {
bar_color: Color::srgb(0.9, 0.1, 0.2),
bar_background: Color::srgb(0.1, 0.2, 0.9),
};
let mut world = World::new();
world.insert_resource(LoadingScreenConfig::default());
world.insert_resource(theme.clone());
spawn_overlay(&mut world);
let (track_color, track) = bar_track(&mut world);
let (fill_color, fill_parent) = bar_fill(&mut world);
assert_eq!(track_color, theme.bar_background);
assert_eq!(fill_color, theme.bar_color);
assert_eq!(fill_parent, track);
let mut overlay = world.query_filtered::<&BackgroundColor, With<LoadingOverlay>>();
assert_eq!(
overlay.single(&world).expect("one overlay").0,
Color::srgba(0.05, 0.05, 0.05, 0.95)
);
}
#[test]
fn loading_theme_is_unused_when_the_bar_is_hidden() {
let mut world = World::new();
world.insert_resource(LoadingScreenConfig {
show_progress_bar: false,
..Default::default()
});
world.insert_resource(LoadingScreenTheme::default());
spawn_overlay(&mut world);
let mut tracks = world.query_filtered::<Entity, With<LoadingProgressBarTrack>>();
assert_eq!(tracks.iter(&world).count(), 0);
let mut fills = world.query_filtered::<Entity, With<LoadingProgressBar>>();
assert_eq!(fills.iter(&world).count(), 0);
}
}
#[cfg(all(test, feature = "items"))]
mod pickup_notification_tests {
use super::*;
use crate::items::inventory::DefaultItem;
const BACKGROUND: [f32; 4] = [0.0, 0.0, 0.0, 0.6];
const ACCENT: [f32; 4] = [1.0, 0.8, 0.2, 1.0];
const LABEL: [f32; 4] = [0.4, 0.9, 1.0, 1.0];
fn app() -> App {
let mut app = App::new();
app.add_plugins((
MinimalPlugins,
PickupNotificationPlugin::<DefaultItem>::new(),
));
app
}
fn pick_up(app: &mut App, item: DefaultItem, count: u32) {
app.world_mut().write_message(ItemPickedUp { item, count });
app.update();
}
fn line(item: DefaultItem, count: u32) -> String {
format!("+{count} {}", item.name())
}
fn notifications(app: &mut App) -> Vec<Entity> {
let world = app.world_mut();
let mut query = world.query_filtered::<Entity, With<NotificationTimer>>();
query.iter(world).collect()
}
fn item_lines(app: &mut App) -> Vec<String> {
let world = app.world_mut();
let mut query = world.query_filtered::<&Text, Without<NotificationLabel>>();
let mut lines: Vec<String> = query.iter(world).map(|text| text.0.clone()).collect();
lines.sort();
lines
}
fn container(app: &mut App) -> (Entity, Node) {
let world = app.world_mut();
let mut query = world.query_filtered::<(Entity, &Node), With<NotificationContainer>>();
let (entity, node) = query.single(world).unwrap();
(entity, node.clone())
}
fn children(app: &App, entity: Entity) -> Vec<Entity> {
app.world()
.get::<Children>(entity)
.map(|children| children.to_vec())
.unwrap_or_default()
}
fn text(app: &App, entity: Entity) -> String {
app.world().get::<Text>(entity).unwrap().0.clone()
}
#[test]
fn defaults_keep_the_top_right_plain_text() {
let mut app = app();
app.update();
assert_eq!(
*app.world().resource::<PickupNotificationFilter>(),
PickupNotificationFilter::Every
);
assert_eq!(
*app.world().resource::<PickupNotificationLayout>(),
PickupNotificationLayout {
anchor: HudAnchor::TopRight,
offset: [16.0, 16.0],
background: None,
padding: [0.0, 0.0],
accent_bar: None,
label: None,
}
);
let (container_entity, container_node) = container(&mut app);
assert_eq!(
container_node,
Node {
position_type: PositionType::Absolute,
top: Val::Px(16.0),
right: Val::Px(16.0),
flex_direction: FlexDirection::Column,
row_gap: Val::Px(4.0),
align_items: AlignItems::FlexEnd,
..default()
}
);
pick_up(&mut app, DefaultItem::Dirt, 2);
let entities = notifications(&mut app);
assert_eq!(entities.len(), 1);
let entity = entities[0];
assert!(children(&app, entity).is_empty());
assert_eq!(text(&app, entity), line(DefaultItem::Dirt, 2));
let world = app.world();
assert_eq!(world.get::<TextFont>(entity).unwrap().font_size, 18.0);
assert_eq!(
world.get::<TextColor>(entity).unwrap().0,
Color::srgba(1.0, 1.0, 1.0, 1.0)
);
assert_eq!(*world.get::<Node>(entity).unwrap(), Node::default());
assert_eq!(world.get::<BackgroundColor>(entity).unwrap().0, Color::NONE);
assert_eq!(
world.get::<ChildOf>(entity).unwrap().parent(),
container_entity
);
}
#[test]
fn plugin_keeps_resources_inserted_by_the_game() {
let layout = PickupNotificationLayout {
anchor: HudAnchor::BottomRight,
..default()
};
let mut app = App::new();
app.insert_resource(PickupNotificationFilter::OnRequest)
.insert_resource(layout.clone())
.add_plugins((
MinimalPlugins,
PickupNotificationPlugin::<DefaultItem>::new(),
));
app.update();
assert_eq!(
*app.world().resource::<PickupNotificationFilter>(),
PickupNotificationFilter::OnRequest
);
assert_eq!(*app.world().resource::<PickupNotificationLayout>(), layout);
}
#[test]
fn every_filter_notifies_each_pickup() {
let mut app = app();
pick_up(&mut app, DefaultItem::Dirt, 1);
pick_up(&mut app, DefaultItem::Dirt, 3);
assert_eq!(
item_lines(&mut app),
[line(DefaultItem::Dirt, 1), line(DefaultItem::Dirt, 3)]
);
assert!(
app.world()
.resource::<PickupNotificationSeen<DefaultItem>>()
.is_empty()
);
}
#[test]
fn first_per_item_type_notifies_once_per_type() {
let mut app = app();
app.insert_resource(PickupNotificationFilter::FirstPerItemType);
pick_up(&mut app, DefaultItem::Dirt, 1);
pick_up(&mut app, DefaultItem::Dirt, 5);
assert_eq!(item_lines(&mut app), [line(DefaultItem::Dirt, 1)]);
pick_up(&mut app, DefaultItem::Sand, 2);
assert_eq!(
item_lines(&mut app),
[line(DefaultItem::Dirt, 1), line(DefaultItem::Sand, 2)]
);
let seen = app
.world()
.resource::<PickupNotificationSeen<DefaultItem>>();
assert!(seen.contains(DefaultItem::Dirt));
assert!(seen.contains(DefaultItem::Sand));
assert_eq!(seen.len(), 2);
}
#[test]
fn first_per_item_type_merges_pickups_of_one_frame() {
let mut app = app();
app.insert_resource(PickupNotificationFilter::FirstPerItemType);
app.world_mut().write_message(ItemPickedUp {
item: DefaultItem::Wood,
count: 1,
});
app.world_mut().write_message(ItemPickedUp {
item: DefaultItem::Wood,
count: 4,
});
app.update();
assert_eq!(item_lines(&mut app), [line(DefaultItem::Wood, 1)]);
}
#[test]
fn seen_record_can_be_restored_and_cleared_by_the_game() {
let mut app = app();
app.insert_resource(PickupNotificationFilter::FirstPerItemType);
app.world_mut()
.resource_mut::<PickupNotificationSeen<DefaultItem>>()
.insert(DefaultItem::Dirt);
pick_up(&mut app, DefaultItem::Dirt, 1);
assert!(notifications(&mut app).is_empty());
app.world_mut()
.resource_mut::<PickupNotificationSeen<DefaultItem>>()
.clear();
pick_up(&mut app, DefaultItem::Dirt, 2);
assert_eq!(item_lines(&mut app), [line(DefaultItem::Dirt, 2)]);
}
#[test]
fn pickup_that_cannot_be_shown_is_not_recorded_as_seen() {
let mut app = app();
app.insert_resource(PickupNotificationFilter::FirstPerItemType)
.insert_resource(PickupNotificationConfig {
max_notifications: 0,
..default()
});
pick_up(&mut app, DefaultItem::Dirt, 1);
assert!(notifications(&mut app).is_empty());
assert!(
app.world()
.resource::<PickupNotificationSeen<DefaultItem>>()
.is_empty()
);
app.world_mut()
.resource_mut::<PickupNotificationConfig>()
.max_notifications = 5;
pick_up(&mut app, DefaultItem::Dirt, 3);
assert_eq!(item_lines(&mut app), [line(DefaultItem::Dirt, 3)]);
}
#[test]
fn on_request_shows_only_what_the_game_asks_for() {
let mut app = app();
app.insert_resource(PickupNotificationFilter::OnRequest);
pick_up(&mut app, DefaultItem::Dirt, 1);
assert!(notifications(&mut app).is_empty());
app.world_mut()
.write_message(ShowPickupNotification::new(DefaultItem::Sand, 7));
app.update();
assert_eq!(item_lines(&mut app), [line(DefaultItem::Sand, 7)]);
}
#[test]
fn request_is_shown_under_other_filters_without_touching_seen() {
let mut app = app();
app.insert_resource(PickupNotificationFilter::FirstPerItemType);
app.world_mut()
.resource_mut::<PickupNotificationSeen<DefaultItem>>()
.insert(DefaultItem::Dirt);
app.world_mut()
.write_message(ShowPickupNotification::new(DefaultItem::Dirt, 2));
app.world_mut()
.write_message(ShowPickupNotification::new(DefaultItem::Sand, 1));
app.update();
assert_eq!(
item_lines(&mut app),
[line(DefaultItem::Sand, 1), line(DefaultItem::Dirt, 2)]
);
let seen = app
.world()
.resource::<PickupNotificationSeen<DefaultItem>>();
assert!(!seen.contains(DefaultItem::Sand));
assert_eq!(seen.len(), 1);
}
#[test]
fn anchor_and_offset_place_the_container() {
let mut app = app();
app.insert_resource(PickupNotificationLayout {
anchor: HudAnchor::BottomLeft,
offset: [24.0, 40.0],
..default()
});
app.update();
assert_eq!(
container(&mut app).1,
Node {
position_type: PositionType::Absolute,
left: Val::Px(24.0),
bottom: Val::Px(40.0),
flex_direction: FlexDirection::Column,
row_gap: Val::Px(4.0),
align_items: AlignItems::FlexStart,
..default()
}
);
}
#[test]
fn centered_anchor_spans_the_screen_shifted_by_the_offset() {
let mut app = app();
app.insert_resource(PickupNotificationLayout {
anchor: HudAnchor::Center,
offset: [10.0, -20.0],
..default()
});
app.update();
assert_eq!(
container(&mut app).1,
Node {
position_type: PositionType::Absolute,
left: Val::Px(10.0),
right: Val::Px(-10.0),
top: Val::Px(-20.0),
bottom: Val::Px(20.0),
flex_direction: FlexDirection::Column,
row_gap: Val::Px(4.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
}
);
}
#[test]
fn layout_change_at_runtime_moves_the_container() {
let mut app = app();
app.update();
assert_eq!(container(&mut app).1.right, Val::Px(16.0));
app.insert_resource(PickupNotificationLayout {
anchor: HudAnchor::TopLeft,
offset: [8.0, f32::NAN],
..default()
});
app.update();
let node = container(&mut app).1;
assert_eq!(node.left, Val::Px(8.0));
assert_eq!(node.top, Val::Px(0.0));
assert_eq!(node.right, Val::Auto);
assert_eq!(node.align_items, AlignItems::FlexStart);
}
#[test]
fn background_accent_bar_and_label_are_spawned_on_the_notification() {
let mut app = app();
app.insert_resource(PickupNotificationLayout {
background: Some(BACKGROUND),
padding: [10.0, 6.0],
accent_bar: Some(PickupNotificationAccentBar {
color: ACCENT,
width: 4.0,
}),
label: Some(PickupNotificationLabel {
text: "New item".to_string(),
color: LABEL,
}),
..default()
});
pick_up(&mut app, DefaultItem::Dirt, 1);
let entities = notifications(&mut app);
assert_eq!(entities.len(), 1);
let root = entities[0];
let root_children = children(&app, root);
assert_eq!(root_children.len(), 2);
let (bar, body) = (root_children[0], root_children[1]);
let body_children = children(&app, body);
assert_eq!(body_children.len(), 2);
let (label, item) = (body_children[0], body_children[1]);
assert_eq!(text(&app, label), "New item");
assert_eq!(text(&app, item), line(DefaultItem::Dirt, 1));
let world = app.world();
assert!(world.get::<Text>(root).is_none());
assert_eq!(
world.get::<BackgroundColor>(root).unwrap().0,
notification_color(BACKGROUND)
);
assert_eq!(
world.get::<Node>(root).unwrap().flex_direction,
FlexDirection::Row
);
assert!(world.get::<NotificationAccentBar>(bar).is_some());
assert_eq!(world.get::<Node>(bar).unwrap().width, Val::Px(4.0));
assert_eq!(
world.get::<BackgroundColor>(bar).unwrap().0,
notification_color(ACCENT)
);
let body_node = world.get::<Node>(body).unwrap();
assert_eq!(body_node.padding, UiRect::axes(Val::Px(10.0), Val::Px(6.0)));
assert_eq!(body_node.flex_direction, FlexDirection::Column);
assert_eq!(body_node.align_items, AlignItems::FlexEnd);
assert!(world.get::<NotificationLabel>(label).is_some());
assert_eq!(
world.get::<TextColor>(label).unwrap().0,
notification_color(LABEL)
);
assert_eq!(world.get::<TextFont>(label).unwrap().font_size, 18.0);
assert_eq!(
world.get::<TextColor>(item).unwrap().0,
Color::srgba(1.0, 1.0, 1.0, 1.0)
);
}
#[test]
fn background_alone_adds_no_bar_and_no_label() {
let mut app = app();
app.insert_resource(PickupNotificationLayout {
background: Some(BACKGROUND),
accent_bar: Some(PickupNotificationAccentBar {
color: ACCENT,
width: 0.0,
}),
..default()
});
pick_up(&mut app, DefaultItem::Sand, 3);
let entities = notifications(&mut app);
assert_eq!(entities.len(), 1);
let root_children = children(&app, entities[0]);
assert_eq!(root_children.len(), 1);
let body_children = children(&app, root_children[0]);
assert_eq!(body_children.len(), 1);
assert_eq!(text(&app, body_children[0]), line(DefaultItem::Sand, 3));
let world = app.world_mut();
let mut bars = world.query_filtered::<Entity, With<NotificationAccentBar>>();
assert_eq!(bars.iter(world).count(), 0);
let mut labels = world.query_filtered::<Entity, With<NotificationLabel>>();
assert_eq!(labels.iter(world).count(), 0);
}
}