1#![cfg_attr(
16 feature = "items",
17 doc = "| [`PickupNotificationPlugin`] | Timed top-right pop-up text on item pickup |"
18)]
19#![cfg_attr(
20 not(feature = "items"),
21 doc = "| `PickupNotificationPlugin` *(feature `items`)* | Timed top-right pop-up text on item pickup |"
22)]
23#![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)]
35use bevy::prelude::*;
78
79#[cfg(feature = "items")]
80use crate::items::inventory::ItemPickedUp;
81#[cfg(feature = "items")]
82use crate::items::inventory::ItemType;
83use crate::world::loading::{LoadingProgress, WorldLoadingState};
84
85pub mod hud;
87pub use hud::{
88 HudAnchor, HudBar, HudBindingKind, HudDefinitionError, HudDiagnostic, HudDiagnosticKind,
89 HudElementDefinition, HudElementId, HudElementSnapshot, HudIcon, HudIconSource, HudPlacement,
90 HudPresentation, HudRegistry, HudRegistryError, HudScalar, HudScalarField, HudSegments,
91 HudStackDirection, HudStyleOverride, HudSystemSet, HudText, HudTheme, HudValue,
92 HudValueChanged, HudValueError, HudValueId, HudValueKind, HudValueSet, HudValueSnapshot,
93 MAX_HUD_SEGMENTS, VoxelHudPlugin, remove_hud_value, set_hud_value,
94};
95
96#[derive(Resource, Debug, Clone)]
115pub struct CrosshairConfig {
116 pub color: [f32; 4],
119 pub size: f32,
122 pub gap: f32,
125 pub thickness: f32,
128 pub visible: bool,
132}
133
134impl Default for CrosshairConfig {
135 fn default() -> Self {
136 Self {
137 color: [1.0, 1.0, 1.0, 1.0],
138 size: 20.0,
139 gap: 4.0,
140 thickness: 2.0,
141 visible: true,
142 }
143 }
144}
145
146#[derive(Component)]
148struct CrosshairNode;
149
150fn spawn_crosshair(mut commands: Commands, config: Res<CrosshairConfig>) {
151 if !config.visible {
152 return;
153 }
154
155 let c = &*config;
156 let color = Color::srgba(c.color[0], c.color[1], c.color[2], c.color[3]);
157
158 commands
160 .spawn((
161 CrosshairNode,
162 Node {
163 width: Val::Percent(100.0),
164 height: Val::Percent(100.0),
165 position_type: PositionType::Absolute,
166 justify_content: JustifyContent::Center,
167 align_items: AlignItems::Center,
168 ..default()
169 },
170 BackgroundColor(Color::NONE),
171 ))
172 .with_children(|root| {
173 root.spawn((
175 CrosshairNode,
176 Node {
177 position_type: PositionType::Absolute,
178 width: Val::Px(c.size),
179 height: Val::Px(c.thickness),
180 right: Val::Px(c.gap + c.size / 2.0 + c.size / 2.0),
181 top: Val::Px(-c.thickness / 2.0),
182 ..default()
183 },
184 BackgroundColor(color),
185 ));
186 root.spawn((
188 CrosshairNode,
189 Node {
190 position_type: PositionType::Absolute,
191 width: Val::Px(c.size),
192 height: Val::Px(c.thickness),
193 left: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
194 top: Val::Px(-c.thickness / 2.0),
195 ..default()
196 },
197 BackgroundColor(color),
198 ));
199 root.spawn((
201 CrosshairNode,
202 Node {
203 position_type: PositionType::Absolute,
204 width: Val::Px(c.thickness),
205 height: Val::Px(c.size),
206 left: Val::Px(-c.thickness / 2.0),
207 bottom: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
208 ..default()
209 },
210 BackgroundColor(color),
211 ));
212 root.spawn((
214 CrosshairNode,
215 Node {
216 position_type: PositionType::Absolute,
217 width: Val::Px(c.thickness),
218 height: Val::Px(c.size),
219 left: Val::Px(-c.thickness / 2.0),
220 top: Val::Px(c.gap + c.size / 2.0 - c.size / 2.0),
221 ..default()
222 },
223 BackgroundColor(color),
224 ));
225 });
226}
227
228pub struct CrosshairPlugin;
252
253impl Plugin for CrosshairPlugin {
254 fn build(&self, app: &mut App) {
255 app.init_resource::<CrosshairConfig>();
256 app.add_systems(Startup, spawn_crosshair);
257 }
258}
259
260#[derive(Resource, Debug, Clone)]
277pub struct LoadingScreenConfig {
278 pub background_color: [f32; 4],
282 pub text_color: [f32; 4],
284 pub title: String,
287 pub show_progress_bar: bool,
291}
292
293impl Default for LoadingScreenConfig {
294 fn default() -> Self {
295 Self {
296 background_color: [0.05, 0.05, 0.05, 0.95],
297 text_color: [1.0, 1.0, 1.0, 1.0],
298 title: "Loading...".to_string(),
299 show_progress_bar: true,
300 }
301 }
302}
303
304#[derive(Resource, Debug, Clone, PartialEq)]
336pub struct LoadingScreenTheme {
337 pub bar_color: Color,
339 pub bar_background: Color,
341}
342
343impl Default for LoadingScreenTheme {
344 fn default() -> Self {
345 Self {
346 bar_color: Color::srgba(0.2, 0.7, 0.3, 1.0),
347 bar_background: Color::srgba(0.2, 0.2, 0.2, 1.0),
348 }
349 }
350}
351
352#[derive(Component)]
354struct LoadingOverlay;
355
356#[derive(Component)]
358struct LoadingText;
359
360#[derive(Component)]
362struct LoadingProgressBarTrack;
363
364#[derive(Component)]
366struct LoadingProgressBar;
367
368fn spawn_loading_overlay(
369 mut commands: Commands,
370 config: Res<LoadingScreenConfig>,
371 theme: Option<Res<LoadingScreenTheme>>,
372) {
373 let theme = theme.as_deref().cloned().unwrap_or_default();
375 let bg = Color::srgba(
376 config.background_color[0],
377 config.background_color[1],
378 config.background_color[2],
379 config.background_color[3],
380 );
381 let tc = Color::srgba(
382 config.text_color[0],
383 config.text_color[1],
384 config.text_color[2],
385 config.text_color[3],
386 );
387
388 commands
389 .spawn((
390 LoadingOverlay,
391 Node {
392 width: Val::Percent(100.0),
393 height: Val::Percent(100.0),
394 position_type: PositionType::Absolute,
395 flex_direction: FlexDirection::Column,
396 justify_content: JustifyContent::Center,
397 align_items: AlignItems::Center,
398 ..default()
399 },
400 BackgroundColor(bg),
401 ZIndex(100),
402 ))
403 .with_children(|parent| {
404 parent.spawn((
406 LoadingText,
407 Text::new(config.title.clone()),
408 TextFont {
409 font_size: 32.0,
410 ..default()
411 },
412 TextColor(tc),
413 ));
414
415 if config.show_progress_bar {
416 parent
418 .spawn((
419 LoadingProgressBarTrack,
420 Node {
421 width: Val::Px(400.0),
422 height: Val::Px(20.0),
423 margin: UiRect::top(Val::Px(20.0)),
424 ..default()
425 },
426 BackgroundColor(theme.bar_background),
427 ))
428 .with_children(|bar| {
429 bar.spawn((
431 LoadingProgressBar,
432 Node {
433 width: Val::Percent(0.0),
434 height: Val::Percent(100.0),
435 ..default()
436 },
437 BackgroundColor(theme.bar_color),
438 ));
439 });
440 }
441 });
442}
443
444fn update_loading_overlay(
445 loading_state: Res<WorldLoadingState>,
446 mut progress_reader: bevy::ecs::message::MessageReader<LoadingProgress>,
447 mut overlay_query: Query<&mut Visibility, With<LoadingOverlay>>,
448 mut text_query: Query<&mut Text, With<LoadingText>>,
449 mut bar_query: Query<&mut Node, With<LoadingProgressBar>>,
450) {
451 if loading_state.ready {
453 if let Ok(mut vis) = overlay_query.single_mut() {
454 *vis = Visibility::Hidden;
455 }
456 return;
457 }
458
459 let mut latest: Option<LoadingProgress> = None;
461 for msg in progress_reader.read() {
462 latest = Some(msg.clone());
463 }
464
465 if let Some(progress) = latest {
466 if let Ok(mut text) = text_query.single_mut() {
468 *text = Text::new(format!(
469 "Loading... {}/{} chunks",
470 progress.loaded, progress.total
471 ));
472 }
473
474 if let Ok(mut node) = bar_query.single_mut() {
476 node.width = Val::Percent((progress.progress * 100.0).clamp(0.0, 100.0));
477 }
478 }
479}
480
481fn despawn_loading_overlay_on_ready(
482 mut commands: Commands,
483 loading_state: Res<WorldLoadingState>,
484 overlay_query: Query<Entity, With<LoadingOverlay>>,
485) {
486 if loading_state.ready {
487 for entity in overlay_query.iter() {
488 commands.entity(entity).despawn();
489 }
490 }
491}
492
493pub struct LoadingScreenPlugin;
518
519impl Plugin for LoadingScreenPlugin {
520 fn build(&self, app: &mut App) {
521 app.init_resource::<LoadingScreenConfig>();
522 app.init_resource::<LoadingScreenTheme>();
523 app.add_systems(Startup, spawn_loading_overlay);
524 app.add_systems(
525 Update,
526 (update_loading_overlay, despawn_loading_overlay_on_ready),
527 );
528 }
529}
530
531#[cfg(feature = "items")]
533pub mod hotbar;
534#[cfg(feature = "items")]
535pub use hotbar::{HotbarContentPlugin, HotbarUiConfig, HotbarUiPlugin, ItemIconPalette};
536
537#[cfg(feature = "items")]
556#[derive(Resource, Debug, Clone)]
557pub struct PickupNotificationConfig {
558 pub visible: bool,
561 pub duration_secs: f32,
565 pub text_color: [f32; 4],
567 pub max_notifications: usize,
571}
572
573#[cfg(feature = "items")]
574impl Default for PickupNotificationConfig {
575 fn default() -> Self {
576 Self {
577 visible: true,
578 duration_secs: 3.0,
579 text_color: [1.0, 1.0, 1.0, 1.0],
580 max_notifications: 5,
581 }
582 }
583}
584
585#[cfg(feature = "items")]
587#[derive(Component)]
588struct NotificationTimer(Timer);
589
590#[cfg(feature = "items")]
592#[derive(Component)]
593struct NotificationContainer;
594
595#[cfg(feature = "items")]
596fn spawn_notification_container(mut commands: Commands) {
597 commands.spawn((
598 NotificationContainer,
599 Node {
600 position_type: PositionType::Absolute,
601 top: Val::Px(16.0),
602 right: Val::Px(16.0),
603 flex_direction: FlexDirection::Column,
604 row_gap: Val::Px(4.0),
605 align_items: AlignItems::FlexEnd,
606 ..default()
607 },
608 BackgroundColor(Color::NONE),
609 ));
610}
611
612#[cfg(feature = "items")]
613fn on_item_picked_up<I: ItemType>(
614 mut commands: Commands,
615 mut pickup_reader: bevy::ecs::message::MessageReader<ItemPickedUp<I>>,
616 config: Res<PickupNotificationConfig>,
617 container_query: Query<Entity, With<NotificationContainer>>,
618 existing_query: Query<Entity, With<NotificationTimer>>,
619) {
620 if !config.visible {
621 return;
622 }
623
624 let pickups: Vec<(String, u32)> = pickup_reader
626 .read()
627 .map(|p| (p.item.name().to_string(), p.count))
628 .collect();
629
630 if pickups.is_empty() {
631 return;
632 }
633
634 let Ok(container) = container_query.single() else {
635 return;
636 };
637
638 let tc = Color::srgba(
639 config.text_color[0],
640 config.text_color[1],
641 config.text_color[2],
642 config.text_color[3],
643 );
644
645 let existing: Vec<Entity> = existing_query.iter().collect();
647 let available = config.max_notifications.saturating_sub(existing.len());
648 let spawn_count = pickups.len().min(available);
649
650 if existing.len() + pickups.len() > config.max_notifications {
651 let overflow = (existing.len() + pickups.len()).saturating_sub(config.max_notifications);
652 for entity in existing.iter().take(overflow) {
653 commands.entity(*entity).despawn();
654 }
655 }
656
657 for (name, count) in pickups.iter().take(spawn_count) {
658 let label = format!("+{count} {name}");
659 let notification = commands
660 .spawn((
661 NotificationTimer(Timer::from_seconds(config.duration_secs, TimerMode::Once)),
662 Text::new(label),
663 TextFont {
664 font_size: 18.0,
665 ..default()
666 },
667 TextColor(tc),
668 Node { ..default() },
669 ))
670 .id();
671 commands.entity(container).add_child(notification);
672 }
673}
674
675#[cfg(feature = "items")]
676fn tick_notifications(
677 mut commands: Commands,
678 time: Res<Time>,
679 mut query: Query<(Entity, &mut NotificationTimer)>,
680) {
681 for (entity, mut timer) in query.iter_mut() {
682 timer.0.tick(time.delta());
683 if timer.0.just_finished() {
684 commands.entity(entity).despawn();
685 }
686 }
687}
688
689#[cfg(feature = "items")]
719pub struct PickupNotificationPlugin<I: ItemType> {
720 _marker: std::marker::PhantomData<I>,
721}
722
723#[cfg(feature = "items")]
724impl<I: ItemType> PickupNotificationPlugin<I> {
725 pub fn new() -> Self {
726 Self {
727 _marker: std::marker::PhantomData,
728 }
729 }
730}
731
732#[cfg(feature = "items")]
733impl<I: ItemType> Default for PickupNotificationPlugin<I> {
734 fn default() -> Self {
735 Self::new()
736 }
737}
738
739#[cfg(feature = "items")]
740impl<I: ItemType> Plugin for PickupNotificationPlugin<I> {
741 fn build(&self, app: &mut App) {
742 app.init_resource::<PickupNotificationConfig>();
743 app.add_message::<ItemPickedUp<I>>();
745 app.add_systems(Startup, spawn_notification_container);
746 app.add_systems(Update, (on_item_picked_up::<I>, tick_notifications));
747 }
748}
749
750mod pause_menu;
751pub use pause_menu::{
752 ButtonColors, PauseMenuConfig, PauseMenuPlugin, PauseMenuState, PauseMenuTheme,
753 SaveSettingsRequest,
754};
755
756use crate::chunk::world_to_chunk_coord;
759use crate::player::Player;
760use crate::world::ChunkManager;
761use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
762
763#[derive(Resource, Default)]
765pub struct DebugOverlayState {
766 pub visible: bool,
768}
769
770#[derive(Component)]
772struct DebugOverlay;
773
774#[derive(Component)]
776struct DebugLine(usize);
777
778fn spawn_debug_overlay(mut commands: Commands) {
779 commands
780 .spawn((
781 DebugOverlay,
782 Node {
783 position_type: PositionType::Absolute,
784 top: Val::Px(8.0),
785 left: Val::Px(8.0),
786 flex_direction: FlexDirection::Column,
787 row_gap: Val::Px(2.0),
788 padding: UiRect::all(Val::Px(6.0)),
789 ..default()
790 },
791 BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)),
792 Visibility::Hidden,
793 ZIndex(200),
794 ))
795 .with_children(|root| {
796 let style = TextFont {
797 font_size: 14.0,
798 ..default()
799 };
800 let color = TextColor(Color::WHITE);
801 for i in 0..4 {
802 root.spawn((DebugLine(i), Text::new(""), style.clone(), color));
803 }
804 });
805}
806
807fn update_debug_overlay(
808 keys: Res<ButtonInput<KeyCode>>,
809 mut state: ResMut<DebugOverlayState>,
810 mut overlay_q: Query<&mut Visibility, With<DebugOverlay>>,
811 mut line_q: Query<(&DebugLine, &mut Text)>,
812 player_q: Query<&Transform, With<Player>>,
813 manager: Res<ChunkManager>,
814 diagnostics: Res<DiagnosticsStore>,
815) {
816 if keys.just_pressed(KeyCode::F3) {
818 state.visible = !state.visible;
819 if let Ok(mut vis) = overlay_q.single_mut() {
820 *vis = if state.visible {
821 Visibility::Visible
822 } else {
823 Visibility::Hidden
824 };
825 }
826 }
827
828 if !state.visible {
829 return;
830 }
831
832 let pos = player_q
833 .single()
834 .map(|t| t.translation)
835 .unwrap_or(Vec3::ZERO);
836
837 let chunk = world_to_chunk_coord(pos);
838 let fps = diagnostics
839 .get(&FrameTimeDiagnosticsPlugin::FPS)
840 .and_then(|d| d.smoothed())
841 .unwrap_or(0.0);
842 let chunk_count = manager.loaded_count();
843
844 let lines = [
845 format!("XYZ: {:.1} / {:.1} / {:.1}", pos.x, pos.y, pos.z),
846 format!("Chunk: {} {} {}", chunk.x, chunk.y, chunk.z),
847 format!("FPS: {fps:.0}"),
848 format!("Chunks: {chunk_count}"),
849 ];
850
851 for (line_marker, mut text) in line_q.iter_mut() {
852 if let Some(content) = lines.get(line_marker.0) {
853 *text = Text::new(content.clone());
854 }
855 }
856}
857
858pub struct DebugOverlayPlugin;
874
875impl Plugin for DebugOverlayPlugin {
876 fn build(&self, app: &mut App) {
877 app.add_plugins(FrameTimeDiagnosticsPlugin::default());
878 app.init_resource::<DebugOverlayState>();
879 app.add_systems(Startup, spawn_debug_overlay);
880 app.add_systems(Update, update_debug_overlay);
881 }
882}
883
884#[cfg(feature = "items")]
889use crate::items::inventory::DefaultItem;
890
891#[cfg_attr(
892 feature = "items",
893 doc = "Umbrella plugin that adds all four HUD sub-plugins with [`DefaultItem`]."
894)]
895#[cfg_attr(
896 not(feature = "items"),
897 doc = "Umbrella plugin for the built-in HUD sub-plugins; item-specific overlays require the `items` feature."
898)]
899#[cfg_attr(
901 feature = "items",
902 doc = "Equivalent to adding [`CrosshairPlugin`], [`LoadingScreenPlugin`], [`HotbarUiPlugin`], and [`PickupNotificationPlugin::<DefaultItem>`] in one call. Configuration resources for each sub-plugin can still be inserted individually before `UiPlugin` is added to override their defaults."
903)]
904#[cfg_attr(
905 not(feature = "items"),
906 doc = "Without the `items` feature, this adds [`CrosshairPlugin`] and [`LoadingScreenPlugin`]. Configuration resources for each sub-plugin can still be inserted individually before `UiPlugin` is added to override their defaults."
907)]
908#[cfg_attr(
910 feature = "items",
911 doc = "To use a custom item type for pickup notifications, skip `UiPlugin` and add [`PickupNotificationPlugin::<YourItem>::new()`] alongside the other plugins individually."
912)]
913#[cfg_attr(
914 not(feature = "items"),
915 doc = "Enable the `items` feature before configuring item-specific pickup notifications or hotbar UI."
916)]
917pub struct UiPlugin;
929
930impl Plugin for UiPlugin {
931 fn build(&self, app: &mut App) {
932 app.add_plugins(CrosshairPlugin);
933 app.add_plugins(LoadingScreenPlugin);
934 #[cfg(feature = "items")]
935 app.add_plugins(HotbarUiPlugin);
936 #[cfg(feature = "items")]
937 app.add_plugins(PickupNotificationPlugin::<DefaultItem>::new());
938 }
939}
940
941#[cfg(test)]
942mod loading_screen_tests {
943 use super::*;
944 use bevy::ecs::system::RunSystemOnce;
945
946 fn spawn_overlay(world: &mut World) {
947 world
948 .run_system_once(spawn_loading_overlay)
949 .expect("spawn_loading_overlay should run");
950 }
951
952 fn bar_fill(world: &mut World) -> (Color, Entity) {
954 let mut query =
955 world.query_filtered::<(&BackgroundColor, &ChildOf), With<LoadingProgressBar>>();
956 let (bg, child_of) = query.single(world).expect("one progress bar fill");
957 (bg.0, child_of.parent())
958 }
959
960 fn bar_track(world: &mut World) -> (Color, Entity) {
962 let mut query =
963 world.query_filtered::<(&BackgroundColor, Entity), With<LoadingProgressBarTrack>>();
964 let (bg, entity) = query.single(world).expect("one progress bar track");
965 (bg.0, entity)
966 }
967
968 #[test]
969 fn default_loading_theme_equals_the_previous_constants() {
970 let theme = LoadingScreenTheme::default();
971 assert_eq!(theme.bar_color, Color::srgba(0.2, 0.7, 0.3, 1.0));
972 assert_eq!(theme.bar_background, Color::srgba(0.2, 0.2, 0.2, 1.0));
973 }
974
975 #[test]
976 fn loading_bar_without_a_theme_resource_keeps_the_previous_colors() {
977 let mut world = World::new();
978 world.insert_resource(LoadingScreenConfig::default());
979
980 spawn_overlay(&mut world);
981
982 let (track_color, track) = bar_track(&mut world);
983 let (fill_color, fill_parent) = bar_fill(&mut world);
984 assert_eq!(track_color, Color::srgba(0.2, 0.2, 0.2, 1.0));
985 assert_eq!(fill_color, Color::srgba(0.2, 0.7, 0.3, 1.0));
986 assert_eq!(fill_parent, track);
987 }
988
989 #[test]
990 fn custom_loading_theme_colors_the_bar_and_its_track() {
991 let theme = LoadingScreenTheme {
992 bar_color: Color::srgb(0.9, 0.1, 0.2),
993 bar_background: Color::srgb(0.1, 0.2, 0.9),
994 };
995 let mut world = World::new();
996 world.insert_resource(LoadingScreenConfig::default());
997 world.insert_resource(theme.clone());
998
999 spawn_overlay(&mut world);
1000
1001 let (track_color, track) = bar_track(&mut world);
1002 let (fill_color, fill_parent) = bar_fill(&mut world);
1003 assert_eq!(track_color, theme.bar_background);
1004 assert_eq!(fill_color, theme.bar_color);
1005 assert_eq!(fill_parent, track);
1006
1007 let mut overlay = world.query_filtered::<&BackgroundColor, With<LoadingOverlay>>();
1009 assert_eq!(
1010 overlay.single(&world).expect("one overlay").0,
1011 Color::srgba(0.05, 0.05, 0.05, 0.95)
1012 );
1013 }
1014
1015 #[test]
1016 fn loading_theme_is_unused_when_the_bar_is_hidden() {
1017 let mut world = World::new();
1018 world.insert_resource(LoadingScreenConfig {
1019 show_progress_bar: false,
1020 ..Default::default()
1021 });
1022 world.insert_resource(LoadingScreenTheme::default());
1023
1024 spawn_overlay(&mut world);
1025
1026 let mut tracks = world.query_filtered::<Entity, With<LoadingProgressBarTrack>>();
1027 assert_eq!(tracks.iter(&world).count(), 0);
1028 let mut fills = world.query_filtered::<Entity, With<LoadingProgressBar>>();
1029 assert_eq!(fills.iter(&world).count(), 0);
1030 }
1031}