src/ui.rs 8.2 K · 283 lines · raw · history

1 use bevy::{
2 picking::{
3 hover::{HoverMap, Hovered},
4 pointer::PointerId,
5 },
6 prelude::*,
7 ui::Pressed,
8 ui_widgets::{Activate, ActivateOnPress, Button},
9 };
10
11 use crate::{
12 actions::Action,
13 sim::SimSpeed,
14 zones::{ZoneKind, ZoneTool},
15 };
16
17 pub struct HudPlugin;
18
19 impl Plugin for HudPlugin {
20 fn build(&self, app: &mut App) {
21 app.init_resource::<PointerOverUi>()
22 .init_resource::<UiVisible>()
23 .add_systems(Startup, spawn_toolbar)
24 .add_systems(
25 Update,
26 (
27 detect_pointer_over_ui,
28 toggle_ui,
29 apply_ui_visibility.run_if(resource_changed::<UiVisible>),
30 style_buttons,
31 ),
32 )
33 .add_observer(on_button_activated);
34 }
35 }
36
37 const TOOLBAR: [Action; 9] = [
38 Action::TogglePause,
39 Action::SetSpeed(SimSpeed::Normal),
40 Action::SetSpeed(SimSpeed::Fast),
41 Action::SetSpeed(SimSpeed::Fastest),
42 Action::ToggleStockpileTool,
43 Action::ToggleFarmTool,
44 Action::Cancel,
45 Action::NewWorld,
46 Action::ToggleUi,
47 ];
48
49 const BUTTON_COLOR: Color = Color::srgba(0.12, 0.12, 0.14, 0.9);
50 const BUTTON_HOVER_COLOR: Color = Color::srgba(0.22, 0.22, 0.26, 0.95);
51 const BUTTON_ACTIVE_COLOR: Color = Color::srgba(0.2, 0.45, 0.75, 0.95);
52 const BUTTON_PRESSED_COLOR: Color = Color::srgba(0.3, 0.6, 0.9, 1.0);
53 const KEY_HINT_COLOR: Color = Color::srgb(0.65, 0.65, 0.7);
54
55 #[derive(Resource, Default, Debug, Clone, Copy, PartialEq)]
56 pub struct PointerOverUi(pub bool);
57
58 #[derive(Resource, Debug, Clone, Copy, PartialEq)]
59 pub struct UiVisible(pub bool);
60
61 impl Default for UiVisible {
62 fn default() -> Self {
63 Self(true)
64 }
65 }
66
67 #[derive(Component)]
68 pub struct HideableUi;
69
70 #[derive(Component)]
71 struct ShowUiButton;
72
73 #[derive(Component, Debug, Clone, Copy)]
74 pub struct ActionButton(pub Action);
75
76 fn action_button(action: Action, label: &str) -> impl Bundle {
77 (
78 Button,
79 ActivateOnPress,
80 Hovered::default(),
81 ActionButton(action),
82 Node {
83 flex_direction: FlexDirection::Column,
84 align_items: AlignItems::Center,
85 min_width: px(52),
86 padding: UiRect::axes(px(8), px(4)),
87 border_radius: BorderRadius::all(px(4)),
88 ..default()
89 },
90 BackgroundColor(BUTTON_COLOR),
91 children![
92 (Text::new(label), TextFont::from_font_size(14.0)),
93 (
94 Text::new(action.key_label()),
95 TextFont::from_font_size(10.0),
96 TextColor(KEY_HINT_COLOR),
97 ),
98 ],
99 )
100 }
101
102 fn spawn_toolbar(mut commands: Commands) {
103 let toolbar = commands
104 .spawn((
105 HideableUi,
106 Pickable::IGNORE,
107 Node {
108 position_type: PositionType::Absolute,
109 bottom: px(8),
110 width: percent(100),
111 justify_content: JustifyContent::Center,
112 ..default()
113 },
114 ))
115 .id();
116 let row = commands
117 .spawn((
118 Node {
119 column_gap: px(4),
120 padding: UiRect::all(px(4)),
121 border_radius: BorderRadius::all(px(6)),
122 ..default()
123 },
124 BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.4)),
125 ChildOf(toolbar),
126 ))
127 .id();
128 for action in TOOLBAR {
129 commands.spawn((action_button(action, action.label()), ChildOf(row)));
130 }
131 commands
132 .spawn((
133 ShowUiButton,
134 action_button(Action::ToggleUi, "Show UI"),
135 Visibility::Hidden,
136 ))
137 .entry::<Node>()
138 .and_modify(|mut node| {
139 node.position_type = PositionType::Absolute;
140 node.bottom = px(8);
141 node.right = px(8);
142 });
143 }
144
145 fn on_button_activated(
146 activate: On<Activate>,
147 buttons: Query<&ActionButton>,
148 mut actions: MessageWriter<Action>,
149 ) {
150 if let Ok(button) = buttons.get(activate.entity) {
151 actions.write(button.0);
152 }
153 }
154
155 fn detect_pointer_over_ui(
156 hover_map: Res<HoverMap>,
157 nodes: Query<(), With<Node>>,
158 mut over_ui: ResMut<PointerOverUi>,
159 ) {
160 let over = hover_map
161 .get(&PointerId::Mouse)
162 .is_some_and(|hits| hits.keys().any(|&entity| nodes.contains(entity)));
163 over_ui.set_if_neq(PointerOverUi(over));
164 }
165
166 fn toggle_ui(mut actions: MessageReader<Action>, mut visible: ResMut<UiVisible>) {
167 for action in actions.read() {
168 if *action == Action::ToggleUi {
169 visible.0 = !visible.0;
170 }
171 }
172 }
173
174 fn apply_ui_visibility(
175 visible: Res<UiVisible>,
176 mut hideable: Query<&mut Visibility, (With<HideableUi>, Without<ShowUiButton>)>,
177 mut show_button: Query<&mut Visibility, With<ShowUiButton>>,
178 ) {
179 let (shown, hidden) = (Visibility::Inherited, Visibility::Hidden);
180 for mut visibility in &mut hideable {
181 *visibility = if visible.0 { shown } else { hidden };
182 }
183 for mut visibility in &mut show_button {
184 *visibility = if visible.0 { hidden } else { shown };
185 }
186 }
187
188 pub fn is_active(action: Action, paused: bool, speed: SimSpeed, tool: Option<ZoneKind>) -> bool {
189 match action {
190 Action::TogglePause => paused,
191 Action::SetSpeed(s) => !paused && s == speed,
192 Action::ToggleStockpileTool => tool == Some(ZoneKind::Stockpile),
193 Action::ToggleFarmTool => tool == Some(ZoneKind::Farm),
194 _ => false,
195 }
196 }
197
198 fn style_buttons(
199 time: Res<Time<Virtual>>,
200 speed: Res<SimSpeed>,
201 tool: Res<ZoneTool>,
202 mut buttons: Query<(&ActionButton, &Hovered, Has<Pressed>, &mut BackgroundColor)>,
203 ) {
204 for (button, hovered, pressed, mut color) in &mut buttons {
205 let active = is_active(button.0, time.is_paused(), *speed, tool.mode);
206 let new = match (pressed && hovered.get(), active, hovered.get()) {
207 (true, ..) => BUTTON_PRESSED_COLOR,
208 (_, true, _) => BUTTON_ACTIVE_COLOR,
209 (_, _, true) => BUTTON_HOVER_COLOR,
210 _ => BUTTON_COLOR,
211 };
212 color.set_if_neq(BackgroundColor(new));
213 }
214 }
215
216 #[cfg(test)]
217 mod tests {
218 use super::*;
219 use crate::actions::KEYBINDS;
220
221 #[test]
222 fn toolbar_spawns_one_button_per_action_plus_restore_button() {
223 let mut app = App::new();
224 app.add_systems(Startup, spawn_toolbar);
225 app.update();
226 let world = app.world_mut();
227 let buttons = world.query::<&ActionButton>().iter(world).count();
228 assert_eq!(buttons, TOOLBAR.len() + 1);
229 }
230
231 #[test]
232 fn every_keybind_has_a_toolbar_button() {
233 for (key, action) in KEYBINDS {
234 assert!(TOOLBAR.contains(&action), "{key:?} has no button");
235 }
236 }
237
238 #[test]
239 fn active_buttons_reflect_simulation_state() {
240 let normal = SimSpeed::Normal;
241 assert!(is_active(Action::TogglePause, true, normal, None));
242 let fast = Action::SetSpeed(SimSpeed::Fast);
243 assert!(is_active(fast, false, SimSpeed::Fast, None));
244 assert!(!is_active(fast, true, SimSpeed::Fast, None));
245 let farm = Some(ZoneKind::Farm);
246 assert!(is_active(Action::ToggleFarmTool, false, normal, farm));
247 assert!(!is_active(Action::ToggleStockpileTool, false, normal, farm));
248 }
249
250 #[test]
251 fn toggling_hides_the_ui_and_shows_the_restore_button() {
252 let mut app = App::new();
253 app.init_resource::<UiVisible>()
254 .add_message::<Action>()
255 .add_systems(
256 Update,
257 (
258 toggle_ui,
259 apply_ui_visibility.run_if(resource_changed::<UiVisible>),
260 )
261 .chain(),
262 );
263 let panel = app
264 .world_mut()
265 .spawn((HideableUi, Visibility::Inherited))
266 .id();
267 let restore = app
268 .world_mut()
269 .spawn((ShowUiButton, Visibility::Hidden))
270 .id();
271 app.update();
272 app.world_mut().write_message(Action::ToggleUi);
273 app.update();
274 assert_eq!(
275 app.world().get::<Visibility>(panel),
276 Some(&Visibility::Hidden)
277 );
278 assert_eq!(
279 app.world().get::<Visibility>(restore),
280 Some(&Visibility::Inherited)
281 );
282 }
283 }