src/selection.rs 28.9 K · 860 lines · raw · history

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