src/selection.rs 27.2 K · 818 lines · raw · history

1 use bevy::{prelude::*, transform::TransformSystems, window::PrimaryWindow};
2
3 use crate::{
4 actions::Action,
5 animals::Animal,
6 building::{Blueprints, BuildMode, BuildTool},
7 camera::CameraController,
8 colonist::{Colonist, Path},
9 designations::DesignateTool,
10 economy::{ColonyGoals, Stock, in_colony},
11 family::{Child, Partner},
12 food::Hunger,
13 items::{Carrying, Item, stock},
14 jobs::{BUTCHER_WORK, COOK_WORK, CurrentJob, EXPAND_WORK, Job, Order, Task, WorkKind},
15 light::daylight,
16 needs::Rest,
17 population::ColonyLog,
18 sim::{SimSpeed, SimTick, TICKS_PER_HOUR, format_clock, hour_of_day},
19 structures::{Fuel, Structure, StructureKind},
20 ui::{HideableUi, PointerOverUi},
21 world::{TILE_SIZE, TilePos, WorldMap},
22 worldgen::{WorldGenerated, WorldSeed},
23 zones::{ZoneKind, ZoneTool, Zones},
24 };
25
26 pub struct SelectionPlugin;
27
28 impl Plugin for SelectionPlugin {
29 fn build(&self, app: &mut App) {
30 app.init_resource::<Cursor>()
31 .init_resource::<Selection>()
32 .add_systems(Startup, spawn_tile_info)
33 .add_systems(Update, clear_selection.run_if(on_message::<WorldGenerated>))
34 .add_systems(
35 PostUpdate,
36 (
37 update_cursor,
38 update_selection.run_if(
39 |tool: Res<ZoneTool>, build: Res<BuildTool>, mark: Res<DesignateTool>| {
40 !tool.active() && !build.active() && !mark.active
41 },
42 ),
43 issue_move_orders,
44 draw_highlights,
45 update_tile_info,
46 )
47 .chain()
48 .after(TransformSystems::Propagate),
49 );
50 }
51 }
52
53 #[derive(Resource, Default, Debug, PartialEq)]
54 pub struct Cursor {
55 pub screen: Option<Vec2>,
56 pub world: Option<Vec2>,
57 pub tile: Option<UVec2>,
58 }
59
60 #[derive(Resource, Default, Debug, PartialEq, Clone, Copy)]
61 pub enum Selection {
62 #[default]
63 None,
64 Tile(UVec2),
65 Colonist(Entity),
66 }
67
68 #[derive(Component)]
69 struct TileInfoText;
70
71 const HOVER_COLOR: Color = Color::srgba(1.0, 1.0, 1.0, 0.6);
72 const SELECT_COLOR: Color = Color::srgb(1.0, 0.85, 0.2);
73 const PROGRESS_COLOR: Color = Color::srgb(0.4, 0.9, 0.4);
74 const PROGRESS_BACK_COLOR: Color = Color::srgba(0.0, 0.0, 0.0, 0.6);
75 const PATH_COLOR: Color = Color::srgba(1.0, 0.85, 0.2, 0.7);
76 const PICK_RADIUS: f32 = TILE_SIZE * 0.6;
77 const CLICK_SLOP_PX: f32 = 4.0;
78
79 pub fn update_cursor(
80 map: Res<WorldMap>,
81 window: Single<&Window, With<PrimaryWindow>>,
82 camera: Single<(&Camera, &GlobalTransform), With<CameraController>>,
83 over_ui: Res<PointerOverUi>,
84 mut cursor: ResMut<Cursor>,
85 ) {
86 let (camera, global) = *camera;
87 let screen = window.cursor_position();
88 let world = screen
89 .filter(|_| !over_ui.0)
90 .and_then(|s| camera.viewport_to_world_2d(global, s).ok());
91 let tile = world.and_then(|w| map.tile_at(w));
92 cursor.set_if_neq(Cursor {
93 screen,
94 world,
95 tile,
96 });
97 }
98
99 fn clear_selection(mut selection: ResMut<Selection>) {
100 *selection = Selection::None;
101 }
102
103 fn update_selection(
104 mut actions: MessageReader<Action>,
105 buttons: Res<ButtonInput<MouseButton>>,
106 over_ui: Res<PointerOverUi>,
107 cursor: Res<Cursor>,
108 colonists: Query<(Entity, &Transform), With<Colonist>>,
109 mut selection: ResMut<Selection>,
110 ) {
111 if actions.read().any(|a| *a == Action::Cancel) {
112 selection.set_if_neq(Selection::None);
113 } else if buttons.just_pressed(MouseButton::Left) && !over_ui.0 {
114 let picked = cursor.world.and_then(|world| {
115 pick_nearest(
116 world,
117 colonists.iter().map(|(e, t)| (e, t.translation.truncate())),
118 )
119 });
120 let new = match (picked, cursor.tile) {
121 (Some(entity), _) => Selection::Colonist(entity),
122 (None, Some(tile)) => Selection::Tile(tile),
123 (None, None) => Selection::None,
124 };
125 selection.set_if_neq(new);
126 }
127 }
128
129 pub fn pick_nearest(
130 point: Vec2,
131 candidates: impl Iterator<Item = (Entity, Vec2)>,
132 ) -> Option<Entity> {
133 candidates
134 .map(|(e, pos)| (e, pos.distance(point)))
135 .filter(|&(_, d)| d <= PICK_RADIUS)
136 .min_by(|a, b| a.1.total_cmp(&b.1))
137 .map(|(e, _)| e)
138 }
139
140 fn issue_move_orders(
141 buttons: Res<ButtonInput<MouseButton>>,
142 cursor: Res<Cursor>,
143 selection: Res<Selection>,
144 over_ui: Res<PointerOverUi>,
145 mut orders: MessageWriter<Order>,
146 mut pressed_at: Local<Option<Vec2>>,
147 ) {
148 if buttons.just_pressed(MouseButton::Right) {
149 *pressed_at = cursor.screen.filter(|_| !over_ui.0);
150 }
151 if !buttons.just_released(MouseButton::Right) {
152 return;
153 }
154 let (Some(press), Some(release)) = (pressed_at.take(), cursor.screen) else {
155 return;
156 };
157 if let (true, Selection::Colonist(colonist), Some(tile)) =
158 (is_click(press, release), *selection, cursor.tile)
159 {
160 orders.write(Order { colonist, tile });
161 }
162 }
163
164 pub fn is_click(press: Vec2, release: Vec2) -> bool {
165 press.distance(release) <= CLICK_SLOP_PX
166 }
167
168 fn draw_highlights(
169 mut gizmos: Gizmos,
170 cursor: Res<Cursor>,
171 selection: Res<Selection>,
172 colonists: Query<(Entity, &Transform, &Path, &CurrentJob), With<Colonist>>,
173 ) {
174 for (_, transform, _, job) in &colonists {
175 if let Some(fraction) = job.0.and_then(|j| progress_fraction(j.task))
176 && fraction > 0.0
177 {
178 let left =
179 transform.translation.truncate() + Vec2::new(-TILE_SIZE * 0.4, TILE_SIZE * 0.6);
180 let full = TILE_SIZE * 0.8;
181 let done = full * fraction;
182 gizmos.line_2d(left, left + Vec2::X * full, PROGRESS_BACK_COLOR);
183 gizmos.line_2d(left, left + Vec2::X * done, PROGRESS_COLOR);
184 }
185 }
186 if let Some(tile) = cursor.tile {
187 gizmos.rect_2d(
188 WorldMap::tile_center(tile),
189 Vec2::splat(TILE_SIZE),
190 HOVER_COLOR,
191 );
192 }
193 match *selection {
194 Selection::None => {}
195 Selection::Tile(tile) => {
196 gizmos.rect_2d(
197 WorldMap::tile_center(tile),
198 Vec2::splat(TILE_SIZE),
199 SELECT_COLOR,
200 );
201 }
202 Selection::Colonist(entity) => {
203 let Ok((_, transform, path, job)) = colonists.get(entity) else {
204 return;
205 };
206 if let Some(Job {
207 task:
208 Task::Work { site, .. }
209 | Task::ExpandStockpile { site, .. }
210 | Task::Build { site, .. },
211 ..
212 }) = job.0
213 {
214 gizmos.rect_2d(
215 WorldMap::tile_center(site),
216 Vec2::splat(TILE_SIZE),
217 PATH_COLOR,
218 );
219 }
220 let pos = transform.translation.truncate();
221 gizmos.circle_2d(pos, TILE_SIZE * 0.5, SELECT_COLOR);
222 let points = path.0.iter().map(|&t| WorldMap::tile_center(t));
223 gizmos.linestrip_2d(std::iter::once(pos).chain(points), PATH_COLOR);
224 }
225 }
226 }
227
228 fn spawn_tile_info(mut commands: Commands) {
229 commands.spawn((
230 TileInfoText,
231 HideableUi,
232 Text::default(),
233 TextFont::from_font_size(14.0),
234 Node {
235 position_type: PositionType::Absolute,
236 top: px(8),
237 left: px(8),
238 padding: UiRect::all(px(6)),
239 ..default()
240 },
241 BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.5)),
242 ));
243 }
244
245 #[allow(clippy::too_many_arguments)]
246 fn update_tile_info(
247 map: Res<WorldMap>,
248 cursor: Res<Cursor>,
249 selection: Res<Selection>,
250 colonists: Query<(
251 &Colonist,
252 &TilePos,
253 &Path,
254 &CurrentJob,
255 &Carrying,
256 &Rest,
257 &Hunger,
258 )>,
259 items: Query<(&Item, &TilePos)>,
260 structures: Query<(&Structure, &TilePos, Option<&Fuel>)>,
261 animals: Query<(&Animal, &TilePos)>,
262 blueprints: Res<Blueprints>,
263 goals: Res<ColonyGoals>,
264 log: Res<ColonyLog>,
265 zones: Res<Zones>,
266 tools: (Res<ZoneTool>, Res<BuildTool>, Res<DesignateTool>),
267 clock: (
268 Res<Time<Virtual>>,
269 Res<SimTick>,
270 Res<SimSpeed>,
271 Res<WorldSeed>,
272 ),
273 kin: Query<(Option<&Partner>, Option<&Child>)>,
274 mut text: Single<&mut Text, With<TileInfoText>>,
275 ) {
276 let (time, tick, speed, seed) = clock;
277 let selected = match *selection {
278 Selection::None => "-".to_string(),
279 Selection::Tile(tile) => describe_tile(&map, Some(tile)),
280 Selection::Colonist(entity) => colonists
281 .get(entity)
282 .map(|(colonist, tile, path, job, carrying, rest, hunger)| {
283 describe_colonist(&ColonistView {
284 name: &colonist.name,
285 tile: tile.0,
286 job: job.0,
287 steps_left: path.0.len(),
288 carrying: carrying.0,
289 rest: rest.0,
290 fed: hunger.0,
291 }) + &kin
292 .get(entity)
293 .map(|(partner, child)| {
294 let partner = partner
295 .and_then(|p| colonists.get(p.0).ok())
296 .map(|p| format!(", partner {}", p.0.name));
297 let child =
298 child.map(|c| format!(", child (grows up in {}d)", c.days_left(*tick)));
299 partner.unwrap_or_default() + &child.unwrap_or_default()
300 })
301 .unwrap_or_default()
302 })
303 .unwrap_or_else(|_| "-".into()),
304 };
305 let clock = format!(
306 "{} ({})",
307 format_clock(*tick),
308 time_of_day(hour_of_day(*tick))
309 );
310 let speed = describe_speed(*speed, time.is_paused(), time.relative_speed());
311 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.4.0).collect();
312 let home = zones.home(map.size / 2);
313 let stock_line = |food: bool| {
314 Stock::ALL
315 .iter()
316 .filter(|s| s.is_food() == food)
317 .map(|&s| {
318 let have: u32 = s
319 .members()
320 .map(|kind| {
321 stock(
322 items
323 .iter()
324 .filter(|(_, pos)| in_colony(home, pos.0))
325 .map(|(item, _)| item)
326 .chain(carried.iter()),
327 kind,
328 )
329 })
330 .sum();
331 format!("{} {have}/{}", s.label(), goals.goal(s))
332 })
333 .collect::<Vec<_>>()
334 .join(" ")
335 };
336 let materials = format!("{}\n{}", stock_line(false), stock_line(true));
337 let hovered_zone = match cursor.tile {
338 Some(tile) if zones.is_stockpile(tile) => ", Stockpile",
339 Some(tile) if zones.is_farm(tile) => ", Farm",
340 _ => "",
341 };
342 let hovered_items: String = items
343 .iter()
344 .filter(|(_, pos)| Some(pos.0) == cursor.tile)
345 .map(|(item, _)| describe_item(item))
346 .collect();
347 let hovered_structure: String = structures
348 .iter()
349 .filter(|(_, pos, _)| Some(pos.0) == cursor.tile)
350 .map(|(structure, _, fuel)| describe_structure(structure.kind, fuel.map(|f| f.0)))
351 .chain(
352 cursor
353 .tile
354 .and_then(|t| blueprints.get(t))
355 .map(|kind| format!(", planned {}", kind.name())),
356 )
357 .chain(
358 animals
359 .iter()
360 .filter(|(_, pos)| Some(pos.0) == cursor.tile)
361 .map(|(animal, _)| format!(", {}", animal.kind.name())),
362 )
363 .collect();
364 let events: String = log.0.iter().map(|line| format!("\n{line}")).collect();
365 let (tool, build_tool, designate_tool) = tools;
366 let tool_hint = match (tool.mode, build_tool.mode) {
367 _ if designate_tool.active => {
368 "\nCHOP/MINE: drag over trees and rock, shift-drag to clear".to_string()
369 }
370 (Some(ZoneKind::Stockpile), _) => {
371 "\nSTOCKPILE TOOL: drag to add, shift-drag to remove".to_string()
372 }
373 (Some(ZoneKind::Farm), _) => "\nFARM TOOL: drag to add, shift-drag to remove".to_string(),
374 (None, Some(BuildMode::Deconstruct)) => {
375 "\nDECONSTRUCT: drag over structures, shift-drag to remove plans, B for next"
376 .to_string()
377 }
378 (None, Some(BuildMode::Place(kind))) => format!(
379 "\nBUILD {}: {}, shift-drag to remove plans, B for next",
380 kind.name().to_uppercase(),
381 if kind == StructureKind::Wall {
382 "drag a room outline"
383 } else {
384 "click to place"
385 }
386 ),
387 (None, None) => String::new(),
388 };
389 let info = format!(
390 "{clock} {speed}\nSeed: {} Colonists: {}\n{materials}{tool_hint}\nHover: {}{hovered_zone}{hovered_items}{hovered_structure}\nSelected: {selected}{events}",
391 seed.0,
392 colonists.iter().count(),
393 describe_tile(&map, cursor.tile)
394 );
395 if text.0 != info {
396 text.0 = info;
397 }
398 }
399
400 pub fn describe_tile(map: &WorldMap, tile: Option<UVec2>) -> String {
401 let Some((t, terrain)) = tile.and_then(|t| map.get(t.as_ivec2()).map(|terrain| (t, terrain)))
402 else {
403 return "-".into();
404 };
405 let p = t.as_ivec2();
406 let roof = if map.is_roofed(p) { ", Roofed" } else { "" };
407 let plant = map
408 .plant(p)
409 .map(|plant| match plant.ripening_ticks() {
410 None => format!(", {plant:?}"),
411 Some(_) if plant.is_ripe(map.growth(p)) => format!(", {plant:?} (ripe)"),
412 Some(_) => format!(", {plant:?} ({:.0}% grown)", map.growth(p) * 100.0),
413 })
414 .unwrap_or_default();
415 let height = map.height(p).unwrap_or(0.0);
416 let wear = match map.wear(p) {
417 w if w >= 1.0 => format!(", worn {w:.0}"),
418 _ => String::new(),
419 };
420 format!(
421 "({}, {}) {terrain:?}{plant}{roof}, {height:.0} m{wear}",
422 t.x, t.y
423 )
424 }
425
426 pub fn describe_item(item: &Item) -> String {
427 let spoil = if item.kind.is_food() && item.spoil >= 0.01 {
428 format!(" ({:.0}% spoiled)", item.spoil * 100.0)
429 } else {
430 String::new()
431 };
432 format!(", {:?} x{}{spoil}", item.kind, item.count)
433 }
434
435 pub fn describe_speed(speed: SimSpeed, paused: bool, relative: f32) -> String {
436 match (paused, speed) {
437 (true, _) => "PAUSED".into(),
438 (false, SimSpeed::Max) => format!("Max ({relative:.0}x)"),
439 (false, _) => format!("{}x", speed.multiplier()),
440 }
441 }
442
443 pub fn time_of_day(hour: f32) -> &'static str {
444 match daylight(hour) {
445 1.0 => "day",
446 0.0 => "night",
447 _ if hour < 12.0 => "dawn",
448 _ => "dusk",
449 }
450 }
451
452 pub fn describe_structure(kind: StructureKind, fuel: Option<u32>) -> String {
453 match fuel {
454 Some(fuel) => {
455 let hours = fuel as f32 / TICKS_PER_HOUR as f32;
456 format!(", {:?} ({hours:.1}h of fuel)", kind)
457 }
458 None => format!(", {kind:?}"),
459 }
460 }
461
462 pub fn progress_fraction(task: Task) -> Option<f32> {
463 match task {
464 Task::Work { kind, progress, .. } => Some(progress as f32 / kind.work() as f32),
465 Task::ExpandStockpile { progress, .. } => Some(progress as f32 / EXPAND_WORK as f32),
466 Task::Build { kind, progress, .. } => Some(progress as f32 / kind.work() as f32),
467 Task::Hunt { kind, progress, .. } => Some(progress as f32 / kind.hunt_work() as f32),
468 Task::Cook { progress, .. } => Some(progress as f32 / COOK_WORK as f32),
469 Task::Butcher { progress, .. } => Some(progress as f32 / BUTCHER_WORK as f32),
470 _ => None,
471 }
472 }
473
474 fn percent(task: Task) -> u32 {
475 (progress_fraction(task).unwrap_or(0.0) * 100.0).round() as u32
476 }
477
478 pub struct ColonistView<'a> {
479 pub name: &'a str,
480 pub tile: UVec2,
481 pub job: Option<Job>,
482 pub steps_left: usize,
483 pub carrying: Option<Item>,
484 pub rest: f32,
485 pub fed: f32,
486 }
487
488 pub fn describe_colonist(view: &ColonistView) -> String {
489 let (tile, job, carrying) = (view.tile, view.job, view.carrying);
490 let activity = match (job.map(|j| j.task), view.steps_left) {
491 (None, 0) => "idle".to_string(),
492 (None, _) => "wandering".to_string(),
493 (Some(Task::MoveTo(_)), n) => format!("moving, {n} steps left"),
494 (
495 Some(Task::Work {
496 kind: WorkKind::Chop,
497 ..
498 }),
499 n,
500 ) if n > 0 => "walking to a tree".to_string(),
501 (
502 Some(Task::Work {
503 kind: WorkKind::Mine,
504 ..
505 }),
506 n,
507 ) if n > 0 => "walking to rock".to_string(),
508 (
509 Some(Task::Work {
510 kind: WorkKind::Harvest | WorkKind::Sow,
511 ..
512 }),
513 n,
514 ) if n > 0 => "walking to a plant".to_string(),
515 (Some(task @ Task::Work { kind, .. }), _) => {
516 let verb = match kind {
517 WorkKind::Chop => "chopping a tree",
518 WorkKind::Mine => "mining",
519 WorkKind::Harvest => "harvesting",
520 WorkKind::Sow => "sowing",
521 };
522 format!("{verb}, {}%", percent(task))
523 }
524 (Some(Task::ExpandStockpile { .. }), n) if n > 0 => {
525 "going to expand the stockpile".to_string()
526 }
527 (Some(task @ Task::ExpandStockpile { .. }), _) => {
528 format!("expanding the stockpile, {}%", percent(task))
529 }
530 (
531 Some(Task::Haul {
532 pickup: Some(_), ..
533 }),
534 _,
535 ) => "fetching items to haul".to_string(),
536 (Some(Task::Haul { pickup: None, .. }), _) => "hauling to the stockpile".to_string(),
537 (
538 Some(Task::Build {
539 kind,
540 pickup: Some(_),
541 ..
542 }),
543 _,
544 ) => format!("fetching {:?} for a {}", kind.cost().0, kind.name()).to_lowercase(),
545 (Some(Task::Build { kind, .. }), n) if n > 0 => {
546 format!("carrying {:?} to build a {}", kind.cost().0, kind.name()).to_lowercase()
547 }
548 (Some(Task::Sleep { .. }), n) if n > 0 => "going to sleep".to_string(),
549 (Some(Task::Sleep { .. }), _) => "sleeping".to_string(),
550 (
551 Some(Task::Eat {
552 pickup: Some(_), ..
553 }),
554 _,
555 ) => "fetching food".to_string(),
556 (Some(Task::Eat { .. }), _) => "eating".to_string(),
557 (Some(task @ Task::Hunt { kind, progress, .. }), _) if progress > 0 => {
558 format!("hunting a {}, {}%", kind.name(), percent(task))
559 }
560 (Some(Task::Hunt { kind, .. }), _) => format!("stalking a {}", kind.name()),
561 (
562 Some(Task::Cook {
563 pickup: Some(_), ..
564 }),
565 _,
566 ) => "fetching ingredients".to_string(),
567 (Some(Task::Cook { .. }), n) if n > 0 => "carrying ingredients to the fire".to_string(),
568 (Some(task @ Task::Cook { .. }), _) => format!("cooking a meal, {}%", percent(task)),
569 (Some(Task::Butcher { .. }), n) if n > 0 => "walking to a carcass".to_string(),
570 (Some(task @ Task::Butcher { .. }), _) => format!("butchering, {}%", percent(task)),
571 (Some(task @ Task::Build { kind, .. }), _) => {
572 format!("building a {}, {}%", kind.name(), percent(task))
573 }
574 };
575 let load = carrying
576 .map(|item| format!(", carrying {} {:?}", item.count, item.kind))
577 .unwrap_or_default();
578 let ordered = if job.is_some_and(|j| j.ordered) {
579 " (ordered)"
580 } else {
581 ""
582 };
583 format!(
584 "{} at ({}, {}), {activity}{ordered}{load}, rest {:.0}%, food {:.0}%",
585 view.name,
586 tile.x,
587 tile.y,
588 view.rest * 100.0,
589 view.fed * 100.0
590 )
591 }
592
593 #[cfg(test)]
594 mod tests {
595 use super::*;
596 use crate::world::Terrain;
597
598 fn selection_app(cursor: Cursor, selection: Selection) -> App {
599 let mut app = App::new();
600 app.init_resource::<ButtonInput<MouseButton>>()
601 .init_resource::<PointerOverUi>()
602 .insert_resource(cursor)
603 .insert_resource(selection)
604 .add_message::<Order>()
605 .add_message::<Action>()
606 .add_systems(Update, (update_selection, issue_move_orders));
607 app
608 }
609
610 fn cursor_on_tile(tile: UVec2) -> Cursor {
611 Cursor {
612 screen: Some(Vec2::new(50.0, 50.0)),
613 world: Some(WorldMap::tile_center(tile)),
614 tile: Some(tile),
615 }
616 }
617
618 fn press(app: &mut App, button: MouseButton) {
619 app.world_mut()
620 .resource_mut::<ButtonInput<MouseButton>>()
621 .press(button);
622 app.update();
623 }
624
625 fn release(app: &mut App, button: MouseButton) {
626 let mut input = app.world_mut().resource_mut::<ButtonInput<MouseButton>>();
627 input.clear();
628 input.release(button);
629 app.update();
630 }
631
632 fn selection(app: &App) -> Selection {
633 *app.world().resource::<Selection>()
634 }
635
636 fn sent_orders(app: &mut App) -> Vec<(Entity, UVec2)> {
637 app.world_mut()
638 .resource_mut::<Messages<Order>>()
639 .drain()
640 .map(|o| (o.colonist, o.tile))
641 .collect()
642 }
643
644 #[test]
645 fn clicking_selects_the_hovered_tile() {
646 let mut app = selection_app(cursor_on_tile(UVec2::new(3, 4)), Selection::None);
647 press(&mut app, MouseButton::Left);
648 assert_eq!(selection(&app), Selection::Tile(UVec2::new(3, 4)));
649 }
650
651 #[test]
652 fn clicking_a_colonist_selects_it_instead_of_its_tile() {
653 let tile = UVec2::new(3, 4);
654 let mut app = selection_app(cursor_on_tile(tile), Selection::None);
655 let colonist = app
656 .world_mut()
657 .spawn((
658 Colonist { name: "Ada".into() },
659 Transform::from_translation(WorldMap::tile_center(tile).extend(1.0)),
660 ))
661 .id();
662 press(&mut app, MouseButton::Left);
663 assert_eq!(selection(&app), Selection::Colonist(colonist));
664 }
665
666 #[test]
667 fn clicking_outside_the_world_clears_the_selection() {
668 let mut app = selection_app(Cursor::default(), Selection::Tile(UVec2::new(3, 4)));
669 press(&mut app, MouseButton::Left);
670 assert_eq!(selection(&app), Selection::None);
671 }
672
673 #[test]
674 fn cancel_clears_the_selection() {
675 let mut app = selection_app(
676 cursor_on_tile(UVec2::ONE),
677 Selection::Tile(UVec2::new(3, 4)),
678 );
679 app.world_mut().write_message(Action::Cancel);
680 app.update();
681 assert_eq!(selection(&app), Selection::None);
682 }
683
684 #[test]
685 fn clicks_on_the_ui_do_not_reach_the_map() {
686 let colonist = Entity::from_raw_u32(7).unwrap();
687 let mut app = selection_app(
688 cursor_on_tile(UVec2::new(5, 6)),
689 Selection::Colonist(colonist),
690 );
691 app.insert_resource(PointerOverUi(true));
692 press(&mut app, MouseButton::Left);
693 assert_eq!(selection(&app), Selection::Colonist(colonist));
694 press(&mut app, MouseButton::Right);
695 release(&mut app, MouseButton::Right);
696 assert!(sent_orders(&mut app).is_empty());
697 }
698
699 #[test]
700 fn right_click_orders_selected_colonist_to_hovered_tile() {
701 let colonist = Entity::from_raw_u32(7).unwrap();
702 let mut app = selection_app(
703 cursor_on_tile(UVec2::new(5, 6)),
704 Selection::Colonist(colonist),
705 );
706 press(&mut app, MouseButton::Right);
707 release(&mut app, MouseButton::Right);
708 assert_eq!(sent_orders(&mut app), vec![(colonist, UVec2::new(5, 6))]);
709 }
710
711 #[test]
712 fn right_drag_does_not_order_because_it_pans_the_camera() {
713 let colonist = Entity::from_raw_u32(7).unwrap();
714 let mut app = selection_app(
715 cursor_on_tile(UVec2::new(5, 6)),
716 Selection::Colonist(colonist),
717 );
718 press(&mut app, MouseButton::Right);
719 app.world_mut().resource_mut::<Cursor>().screen = Some(Vec2::new(200.0, 50.0));
720 release(&mut app, MouseButton::Right);
721 assert!(sent_orders(&mut app).is_empty());
722 }
723
724 #[test]
725 fn pick_nearest_ignores_far_candidates() {
726 let a = Entity::from_raw_u32(1).unwrap();
727 let b = Entity::from_raw_u32(2).unwrap();
728 let candidates = [(a, Vec2::new(5.0, 0.0)), (b, Vec2::new(2.0, 0.0))];
729 assert_eq!(pick_nearest(Vec2::ZERO, candidates.into_iter()), Some(b));
730 assert_eq!(
731 pick_nearest(Vec2::new(100.0, 0.0), candidates.into_iter()),
732 None
733 );
734 }
735
736 #[test]
737 fn describe_tile_shows_coordinates_terrain_plant_and_height() {
738 let mut map = WorldMap::filled(UVec2::new(4, 4), Terrain::Sand);
739 map.set_height(UVec2::new(1, 2), 12.4);
740 assert_eq!(
741 describe_tile(&map, Some(UVec2::new(1, 2))),
742 "(1, 2) Sand, 12 m"
743 );
744 map.set_plant(UVec2::new(1, 2), Some(crate::world::Plant::Tree));
745 assert_eq!(
746 describe_tile(&map, Some(UVec2::new(1, 2))),
747 "(1, 2) Sand, Tree, 12 m"
748 );
749 assert_eq!(describe_tile(&map, None), "-");
750 }
751
752 #[test]
753 fn time_of_day_labels() {
754 assert_eq!(time_of_day(12.0), "day");
755 assert_eq!(time_of_day(6.0), "dawn");
756 assert_eq!(time_of_day(19.0), "dusk");
757 assert_eq!(time_of_day(1.0), "night");
758 }
759
760 #[test]
761 fn describe_speed_shows_multiplier_or_paused() {
762 assert_eq!(describe_speed(SimSpeed::Fastest, false, 6.0), "6x");
763 assert_eq!(describe_speed(SimSpeed::Fast, true, 3.0), "PAUSED");
764 assert_eq!(describe_speed(SimSpeed::Max, false, 123.4), "Max (123x)");
765 }
766
767 fn view(job: Option<Job>, steps_left: usize, carrying: Option<Item>) -> ColonistView<'static> {
768 ColonistView {
769 name: "Ada",
770 tile: UVec2::new(1, 2),
771 job,
772 steps_left,
773 carrying,
774 rest: 1.0,
775 fed: 0.5,
776 }
777 }
778
779 #[test]
780 fn describe_colonist_shows_activity_and_needs() {
781 assert_eq!(
782 describe_colonist(&view(None, 0, None)),
783 "Ada at (1, 2), idle, rest 100%, food 50%"
784 );
785 let ordered_move = Job {
786 task: Task::MoveTo(UVec2::ZERO),
787 ordered: true,
788 };
789 assert_eq!(
790 describe_colonist(&view(Some(ordered_move), 3, None)),
791 "Ada at (1, 2), moving, 3 steps left (ordered), rest 100%, food 50%"
792 );
793 let chop = Job {
794 task: Task::Work {
795 site: UVec2::ZERO,
796 kind: WorkKind::Chop,
797 progress: WorkKind::Chop.work() / 2,
798 },
799 ordered: false,
800 };
801 assert_eq!(
802 describe_colonist(&view(Some(chop), 0, None)),
803 "Ada at (1, 2), chopping a tree, 50%, rest 100%, food 50%"
804 );
805 let eat = Job {
806 task: Task::Eat {
807 pickup: None,
808 progress: 0,
809 },
810 ordered: false,
811 };
812 let meal = Item::new(crate::items::ItemKind::Meal, 1);
813 assert_eq!(
814 describe_colonist(&view(Some(eat), 0, Some(meal))),
815 "Ada at (1, 2), eating, carrying 1 Meal, rest 100%, food 50%"
816 );
817 }
818 }