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