1#![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#![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::*;
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
92pub 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
103mod fonts;
106pub use fonts::UiFonts;
107use fonts::{UiFontRole, register_ui_fonts};
108
109mod 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#[derive(Resource, Debug, Clone)]
138pub struct LoadingScreenConfig {
139 pub background_color: [f32; 4],
143 pub text_color: [f32; 4],
145 pub title: String,
148 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#[derive(Resource, Debug, Clone, PartialEq)]
197pub struct LoadingScreenTheme {
198 pub bar_color: Color,
200 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#[derive(Component)]
215struct LoadingOverlay;
216
217#[derive(Component)]
219struct LoadingText;
220
221#[derive(Component)]
223struct LoadingProgressBarTrack;
224
225#[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 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 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 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 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 if loading_state.ready {
318 if let Ok(mut vis) = overlay_query.single_mut() {
319 *vis = Visibility::Hidden;
320 }
321 return;
322 }
323
324 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 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 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
358pub 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#[cfg(feature = "items")]
401pub mod hotbar;
402#[cfg(feature = "items")]
403pub use hotbar::{
404 HotbarContentPlugin, HotbarPickupPulse, HotbarSlotStyle, HotbarUiConfig, HotbarUiPlugin,
405 ItemIconPalette,
406};
407
408#[cfg(feature = "items")]
429#[derive(Resource, Debug, Clone)]
430pub struct PickupNotificationConfig {
431 pub visible: bool,
434 pub duration_secs: f32,
438 pub text_color: [f32; 4],
440 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#[cfg(feature = "items")]
522#[derive(Resource, Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
523pub enum PickupNotificationFilter {
524 #[default]
526 Every,
527 FirstPerItemType,
534 OnRequest,
537}
538
539#[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 pub fn contains(&self, item: I) -> bool {
558 self.seen.contains(&item)
559 }
560
561 pub fn insert(&mut self, item: I) -> bool {
564 self.seen.insert(item)
565 }
566
567 pub fn clear(&mut self) {
569 self.seen.clear();
570 }
571
572 pub fn len(&self) -> usize {
574 self.seen.len()
575 }
576
577 pub fn is_empty(&self) -> bool {
579 self.seen.is_empty()
580 }
581}
582
583#[cfg(feature = "items")]
595#[derive(Message, Debug, Clone)]
596pub struct ShowPickupNotification<I: ItemType> {
597 pub item: I,
599 pub count: u32,
601}
602
603#[cfg(feature = "items")]
604impl<I: ItemType> ShowPickupNotification<I> {
605 pub fn new(item: I, count: u32) -> Self {
607 Self { item, count }
608 }
609}
610
611#[cfg(feature = "items")]
615#[derive(Debug, Clone, Copy, PartialEq)]
616pub struct PickupNotificationAccentBar {
617 pub color: [f32; 4],
620 pub width: f32,
623}
624
625#[cfg(feature = "items")]
630#[derive(Debug, Clone, PartialEq)]
631pub struct PickupNotificationLabel {
632 pub text: String,
634 pub color: [f32; 4],
637}
638
639#[cfg(feature = "items")]
660#[derive(Resource, Debug, Clone, PartialEq)]
661pub struct PickupNotificationLayout {
662 pub anchor: HudAnchor,
666 pub offset: [f32; 2],
670 pub background: Option<[f32; 4]>,
673 pub padding: [f32; 2],
677 pub accent_bar: Option<PickupNotificationAccentBar>,
679 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#[cfg(feature = "items")]
699const NOTIFICATION_FONT_SIZE: f32 = 18.0;
700
701#[cfg(feature = "items")]
703#[derive(Component)]
704struct NotificationTimer(Timer);
705
706#[cfg(feature = "items")]
708#[derive(Component)]
709struct NotificationContainer;
710
711#[cfg(feature = "items")]
713#[derive(Component)]
714struct NotificationAccentBar;
715
716#[cfg(feature = "items")]
718#[derive(Component)]
719struct NotificationLabel;
720
721#[cfg(feature = "items")]
723#[derive(Clone, Copy)]
724enum NotificationAxis {
725 Start,
726 Center,
727 End,
728}
729
730#[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#[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#[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#[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 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 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#[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 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
1122use crate::chunk::world_to_chunk_coord;
1125use crate::player::Player;
1126use crate::world::ChunkManager;
1127use bevy::diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin};
1128
1129#[derive(Resource, Default)]
1131pub struct DebugOverlayState {
1132 pub visible: bool,
1134}
1135
1136#[derive(Component)]
1138struct DebugOverlay;
1139
1140#[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 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
1224pub 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#[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#[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#[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)]
1283pub 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 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 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 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 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 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 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 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}