#![cfg_attr(
feature = "items",
doc = "| [`PickupNotificationPlugin`] | Timed top-right pop-up text on item pickup |"
)]
#![cfg_attr(
not(feature = "items"),
doc = "| `PickupNotificationPlugin` *(feature `items`)* | Timed top-right pop-up text on item pickup |"
)]
#![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(Component)]
struct NotificationTimer(Timer);
#[cfg(feature = "items")]
#[derive(Component)]
struct NotificationContainer;
#[cfg(feature = "items")]
fn spawn_notification_container(mut commands: Commands) {
commands.spawn((
NotificationContainer,
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()
},
BackgroundColor(Color::NONE),
));
}
#[cfg(feature = "items")]
fn on_item_picked_up<I: ItemType>(
mut commands: Commands,
mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
config: Res<PickupNotificationConfig>,
container_query: Query<Entity, With<NotificationContainer>>,
existing_query: Query<Entity, With<NotificationTimer>>,
) {
if !config.visible {
return;
}
let pickups: Vec<(String, u32)> = pickup_reader
.read()
.map(|p| (p.item.name().to_string(), p.count))
.collect();
if pickups.is_empty() {
return;
}
let Ok(container) = container_query.single() else {
return;
};
let tc = Color::srgba(
config.text_color[0],
config.text_color[1],
config.text_color[2],
config.text_color[3],
);
let existing: Vec<Entity> = existing_query.iter().collect();
let available = config.max_notifications.saturating_sub(existing.len());
let spawn_count = pickups.len().min(available);
if existing.len() + pickups.len() > config.max_notifications {
let overflow = (existing.len() + pickups.len()).saturating_sub(config.max_notifications);
for entity in existing.iter().take(overflow) {
commands.entity(*entity).despawn();
}
}
for (name, count) in pickups.iter().take(spawn_count) {
let label = format!("+{count} {name}");
let notification = commands
.spawn((
NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once)),
Text::new(label),
TextFont {
font_size: 18.0,
..default()
},
TextColor(tc),
Node { ..default() },
))
.id();
commands.entity(container).add_child(notification);
}
}
#[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.add_message::<ItemPickedUp<I>>();
app.add_systems(Startup, spawn_notification_container);
app.add_systems(Update, (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);
}
}