src/jobs.rs 26 K · 812 lines · raw · history

1 use std::{
2 collections::{HashMap, HashSet},
3 ops::Range,
4 time::Duration,
5 };
6
7 use bevy::prelude::*;
8
9 use crate::{
10 colonist::{Colonist, Path, repath},
11 items::{
12 CARRY_CAPACITY, Carrying, Item, ItemAssets, ItemKind, ItemQuery, drop_items, room_for,
13 stock, take_items,
14 },
15 pathfinding::{find_path, find_path_adjacent, is_adjacent, nearest_tile},
16 rng::SimRng,
17 sim::SimSystems,
18 world::{Plant, TileChanged, TilePos, WorldMap},
19 worldgen::WorldGenerated,
20 zones::Zones,
21 };
22
23 pub struct JobsPlugin;
24
25 impl Plugin for JobsPlugin {
26 fn build(&self, app: &mut App) {
27 app.insert_resource(SimRng::new(0x5EED))
28 .init_resource::<Reservations>()
29 .init_resource::<ColonyGoals>()
30 .add_message::<Order>()
31 .add_message::<TileChanged>()
32 .add_systems(
33 Update,
34 (
35 clear_reservations.run_if(on_message::<WorldGenerated>),
36 handle_orders,
37 ),
38 )
39 .add_systems(FixedUpdate, choose_jobs.in_set(SimSystems::Decide))
40 .add_systems(FixedUpdate, run_jobs.in_set(SimSystems::Act));
41 }
42 }
43
44 pub const CHOP_TICKS: u32 = 240;
45 pub const WOOD_PER_TREE: u32 = 10;
46 const SEARCH_TILES: usize = 6000;
47 const WANDER_RADIUS: i32 = 8;
48 const IDLE_SECS: Range<f32> = 1.0..4.0;
49 const IDLE_AFTER_ORDER_SECS: f32 = 10.0;
50 const WORK_PAUSE_SECS: Range<f32> = 0.2..0.8;
51
52 #[derive(Component, Default, Debug, Clone, PartialEq)]
53 pub struct CurrentJob(pub Option<Job>);
54
55 #[derive(Debug, Clone, Copy, PartialEq)]
56 pub struct Job {
57 pub task: Task,
58 pub ordered: bool,
59 }
60
61 #[derive(Debug, Clone, Copy, PartialEq)]
62 pub enum Task {
63 MoveTo(UVec2),
64 Chop { tree: UVec2, progress: u32 },
65 Haul { pickup: Option<UVec2>, to: UVec2 },
66 }
67
68 #[derive(Component, Debug)]
69 pub struct IdleTimer(Timer);
70
71 impl Default for IdleTimer {
72 fn default() -> Self {
73 Self(Timer::from_seconds(IDLE_SECS.start, TimerMode::Once))
74 }
75 }
76
77 impl IdleTimer {
78 fn restart(&mut self, secs: f32) {
79 self.0.set_duration(Duration::from_secs_f32(secs));
80 self.0.reset();
81 }
82 }
83
84 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85 pub enum Target {
86 Tree(UVec2),
87 Pickup(UVec2),
88 Storage(UVec2),
89 }
90
91 #[derive(Resource, Default, Debug)]
92 pub struct Reservations(HashMap<Target, Entity>);
93
94 impl Reservations {
95 pub fn reserve(&mut self, target: Target, by: Entity) {
96 self.0.insert(target, by);
97 }
98
99 pub fn holder(&self, target: Target) -> Option<Entity> {
100 self.0.get(&target).copied()
101 }
102
103 pub fn is_free(&self, target: Target) -> bool {
104 self.holder(target).is_none()
105 }
106
107 pub fn release(&mut self, target: Target) {
108 self.0.remove(&target);
109 }
110
111 pub fn release_all(&mut self, by: Entity) {
112 self.0.retain(|_, holder| *holder != by);
113 }
114 }
115
116 #[derive(Resource, Debug)]
117 pub struct ColonyGoals {
118 pub wood: u32,
119 }
120
121 impl Default for ColonyGoals {
122 fn default() -> Self {
123 Self { wood: 50 }
124 }
125 }
126
127 #[derive(Message, Debug, Clone, Copy)]
128 pub struct Order {
129 pub colonist: Entity,
130 pub tile: UVec2,
131 }
132
133 fn clear_reservations(mut reservations: ResMut<Reservations>) {
134 reservations.0.clear();
135 }
136
137 fn handle_orders(
138 mut orders: MessageReader<Order>,
139 map: Res<WorldMap>,
140 zones: Res<Zones>,
141 items: Query<(&Item, &TilePos)>,
142 mut reservations: ResMut<Reservations>,
143 mut colonists: Query<(&TilePos, &mut Path, &mut CurrentJob)>,
144 ) {
145 for order in orders.read() {
146 let Ok((tile, mut path, mut job)) = colonists.get_mut(order.colonist) else {
147 continue;
148 };
149 let loose_item = items
150 .iter()
151 .find(|(_, pos)| pos.0 == order.tile && !zones.is_stockpile(pos.0));
152 let task = if map.plant(order.tile.as_ivec2()) == Some(Plant::Tree) {
153 Some(Task::Chop {
154 tree: order.tile,
155 progress: 0,
156 })
157 } else if let Some((item, _)) = loose_item {
158 find_storage(&map, &zones, &reservations, &items, order.tile, item.kind).map(|to| {
159 Task::Haul {
160 pickup: Some(order.tile),
161 to,
162 }
163 })
164 } else {
165 None
166 };
167 if let Some(task) = task {
168 reservations.release_all(order.colonist);
169 reserve_task(&mut reservations, task, order.colonist);
170 path.0.truncate(1);
171 job.0 = Some(Job {
172 task,
173 ordered: true,
174 });
175 } else if let Some(new_path) = repath(&map, tile.0, &path.0, order.tile) {
176 reservations.release_all(order.colonist);
177 path.0 = new_path;
178 job.0 = Some(Job {
179 task: Task::MoveTo(order.tile),
180 ordered: true,
181 });
182 }
183 }
184 }
185
186 fn reserve_task(reservations: &mut Reservations, task: Task, by: Entity) {
187 match task {
188 Task::MoveTo(_) => {}
189 Task::Chop { tree, .. } => reservations.reserve(Target::Tree(tree), by),
190 Task::Haul { pickup, to } => {
191 if let Some(pickup) = pickup {
192 reservations.reserve(Target::Pickup(pickup), by);
193 }
194 reservations.reserve(Target::Storage(to), by);
195 }
196 }
197 }
198
199 pub fn wood_wanted(goals: &ColonyGoals, in_stock: u32, trees_being_chopped: u32) -> bool {
200 in_stock + trees_being_chopped * WOOD_PER_TREE < goals.wood
201 }
202
203 pub fn find_tree(map: &WorldMap, reservations: &Reservations, from: UVec2) -> Option<UVec2> {
204 let tree = nearest_tile(map, from, SEARCH_TILES, |p| {
205 map.plant(p.as_ivec2()) == Some(Plant::Tree) && reservations.is_free(Target::Tree(p))
206 })?;
207 find_path_adjacent(map, from, tree)?;
208 Some(tree)
209 }
210
211 pub fn find_storage<'a>(
212 map: &WorldMap,
213 zones: &Zones,
214 reservations: &Reservations,
215 items: impl IntoIterator<Item = (&'a Item, &'a TilePos)> + Clone,
216 from: UVec2,
217 kind: ItemKind,
218 ) -> Option<UVec2> {
219 nearest_tile(map, from, SEARCH_TILES, |p| {
220 zones.is_stockpile(p)
221 && reservations.is_free(Target::Storage(p))
222 && room_for(items.clone().into_iter(), p, kind) > 0
223 })
224 }
225
226 pub fn find_haul(
227 map: &WorldMap,
228 zones: &Zones,
229 reservations: &Reservations,
230 items: &[(Item, TilePos)],
231 from: UVec2,
232 ) -> Option<Task> {
233 let loose: HashSet<UVec2> = items
234 .iter()
235 .map(|(_, pos)| pos.0)
236 .filter(|&p| !zones.is_stockpile(p) && reservations.is_free(Target::Pickup(p)))
237 .collect();
238 if loose.is_empty() {
239 return None;
240 }
241 let pickup = nearest_tile(map, from, SEARCH_TILES, |p| loose.contains(&p))?;
242 let (item, _) = items.iter().find(|(_, pos)| pos.0 == pickup)?;
243 let refs = items.iter().map(|(i, p)| (i, p));
244 let to = find_storage(map, zones, reservations, refs, pickup, item.kind)?;
245 Some(Task::Haul {
246 pickup: Some(pickup),
247 to,
248 })
249 }
250
251 #[allow(clippy::too_many_arguments)]
252 fn choose_jobs(
253 mut commands: Commands,
254 time: Res<Time>,
255 map: Res<WorldMap>,
256 zones: Res<Zones>,
257 goals: Res<ColonyGoals>,
258 item_assets: Res<ItemAssets>,
259 mut rng: ResMut<SimRng>,
260 mut reservations: ResMut<Reservations>,
261 mut items: ItemQuery,
262 mut colonists: Query<
263 (
264 Entity,
265 &TilePos,
266 &mut Path,
267 &mut CurrentJob,
268 &mut IdleTimer,
269 &mut Carrying,
270 ),
271 With<Colonist>,
272 >,
273 ) {
274 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.5.0).collect();
275 let wood = stock(
276 items.iter().map(|(_, item, _)| item).chain(carried.iter()),
277 ItemKind::Wood,
278 );
279 let mut chopping = colonists
280 .iter()
281 .filter(|c| {
282 matches!(
283 c.3.0,
284 Some(Job {
285 task: Task::Chop { .. },
286 ..
287 })
288 )
289 })
290 .count() as u32;
291 for (entity, tile, mut path, mut job, mut idle, mut carrying) in &mut colonists {
292 if job.0.is_some() || !path.0.is_empty() || !idle.0.tick(time.delta()).is_finished() {
293 continue;
294 }
295 let snapshot: Vec<(Item, TilePos)> =
296 items.iter().map(|(_, item, pos)| (*item, *pos)).collect();
297 let refs = snapshot.iter().map(|(i, p)| (i, p));
298 let task = if let Some(load) = carrying.0 {
299 let storage = find_storage(&map, &zones, &reservations, refs, tile.0, load.kind);
300 if storage.is_none() {
301 drop_items(
302 &mut commands,
303 &mut items,
304 &item_assets,
305 tile.0,
306 load.kind,
307 load.count,
308 );
309 carrying.0 = None;
310 }
311 storage.map(|to| Task::Haul { pickup: None, to })
312 } else if wood_wanted(&goals, wood, chopping)
313 && let Some(tree) = find_tree(&map, &reservations, tile.0)
314 {
315 chopping += 1;
316 Some(Task::Chop { tree, progress: 0 })
317 } else {
318 find_haul(&map, &zones, &reservations, &snapshot, tile.0)
319 };
320 if let Some(task) = task {
321 reserve_task(&mut reservations, task, entity);
322 job.0 = Some(Job {
323 task,
324 ordered: false,
325 });
326 continue;
327 }
328 let goal = tile.0.as_ivec2()
329 + IVec2::new(
330 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
331 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
332 );
333 if map.in_bounds(goal)
334 && let Some(wander_path) = find_path(&map, tile.0, goal.as_uvec2())
335 {
336 path.0 = wander_path.into();
337 idle.restart(rng.range_f32(IDLE_SECS));
338 }
339 }
340 }
341
342 enum Step {
343 Continue,
344 Done,
345 }
346
347 fn walk_to(map: &WorldMap, from: UVec2, to: UVec2, path: &mut Path) -> Step {
348 match find_path(map, from, to) {
349 Some(p) if !p.is_empty() => {
350 path.0 = p.into();
351 Step::Continue
352 }
353 _ => Step::Done,
354 }
355 }
356
357 #[allow(clippy::too_many_arguments)]
358 fn run_jobs(
359 mut commands: Commands,
360 mut map: ResMut<WorldMap>,
361 zones: Res<Zones>,
362 mut reservations: ResMut<Reservations>,
363 mut rng: ResMut<SimRng>,
364 item_assets: Res<ItemAssets>,
365 mut items: ItemQuery,
366 mut changed: MessageWriter<TileChanged>,
367 mut colonists: Query<(
368 Entity,
369 &TilePos,
370 &mut Path,
371 &mut CurrentJob,
372 &mut IdleTimer,
373 &mut Carrying,
374 )>,
375 ) {
376 for (entity, tile, mut path, mut current, mut idle, mut carrying) in &mut colonists {
377 let Some(mut job) = current.0 else {
378 continue;
379 };
380 if !path.0.is_empty() {
381 continue;
382 }
383 let step = match &mut job.task {
384 Task::MoveTo(_) => Step::Done,
385 Task::Chop { tree, progress } => {
386 let tree = *tree;
387 let still_ours = map.plant(tree.as_ivec2()) == Some(Plant::Tree)
388 && reservations.holder(Target::Tree(tree)) == Some(entity);
389 if !still_ours {
390 Step::Done
391 } else if !is_adjacent(tile.0.as_ivec2(), tree.as_ivec2()) {
392 match find_path_adjacent(&map, tile.0, tree) {
393 Some(p) if !p.is_empty() => {
394 path.0 = p.into();
395 Step::Continue
396 }
397 _ => Step::Done,
398 }
399 } else {
400 *progress += 1;
401 if *progress < CHOP_TICKS {
402 Step::Continue
403 } else {
404 map.set_plant(tree, None);
405 changed.write(TileChanged(tree));
406 drop_items(
407 &mut commands,
408 &mut items,
409 &item_assets,
410 tree,
411 ItemKind::Wood,
412 WOOD_PER_TREE,
413 );
414 Step::Done
415 }
416 }
417 }
418 Task::Haul { pickup, to } => {
419 let to = *to;
420 let destination_valid = zones.is_stockpile(to)
421 && reservations.holder(Target::Storage(to)) == Some(entity);
422 if !destination_valid {
423 Step::Done
424 } else if let Some(from) = *pickup {
425 if reservations.holder(Target::Pickup(from)) != Some(entity) {
426 Step::Done
427 } else if tile.0 != from {
428 walk_to(&map, tile.0, from, &mut path)
429 } else {
430 let kind = items
431 .iter()
432 .find(|(_, _, pos)| pos.0 == from)
433 .map(|(_, item, _)| item.kind);
434 let room = kind.map_or(0, |kind| {
435 room_for(items.iter().map(|(_, i, p)| (i, p)), to, kind)
436 });
437 match take_items(&mut commands, &mut items, from, CARRY_CAPACITY.min(room))
438 .filter(|load| load.count > 0)
439 {
440 Some(load) => {
441 carrying.0 = Some(load);
442 reservations.release(Target::Pickup(from));
443 *pickup = None;
444 Step::Continue
445 }
446 None => Step::Done,
447 }
448 }
449 } else if let Some(load) = carrying.0 {
450 if tile.0 != to {
451 walk_to(&map, tile.0, to, &mut path)
452 } else {
453 let room = room_for(items.iter().map(|(_, i, p)| (i, p)), to, load.kind);
454 let dropped = load.count.min(room);
455 if dropped > 0 {
456 drop_items(
457 &mut commands,
458 &mut items,
459 &item_assets,
460 to,
461 load.kind,
462 dropped,
463 );
464 }
465 carrying.0 = (load.count > dropped).then_some(Item {
466 count: load.count - dropped,
467 ..load
468 });
469 Step::Done
470 }
471 } else {
472 Step::Done
473 }
474 }
475 };
476 match step {
477 Step::Continue => current.0 = Some(job),
478 Step::Done => {
479 reservations.release_all(entity);
480 current.0 = None;
481 let ordered_move = matches!(
482 job,
483 Job {
484 task: Task::MoveTo(_),
485 ordered: true
486 }
487 );
488 idle.restart(if ordered_move {
489 IDLE_AFTER_ORDER_SECS
490 } else {
491 rng.range_f32(WORK_PAUSE_SECS)
492 });
493 }
494 }
495 }
496 }
497
498 #[cfg(test)]
499 mod tests {
500 use super::*;
501 use crate::{
502 colonist::follow_path,
503 items::STACK_LIMIT,
504 sim::{SimPos, sim_pos},
505 world::Terrain,
506 };
507
508 const TICK: Duration = Duration::from_nanos(1_000_000_000 / 60);
509
510 fn test_app(map: WorldMap) -> App {
511 let mut app = App::new();
512 app.insert_resource(map)
513 .insert_resource(SimRng::new(1))
514 .init_resource::<Time>()
515 .init_resource::<Reservations>()
516 .init_resource::<ColonyGoals>()
517 .init_resource::<ItemAssets>()
518 .init_resource::<Zones>()
519 .add_message::<Order>()
520 .add_message::<TileChanged>()
521 .add_systems(
522 Update,
523 (handle_orders, choose_jobs, run_jobs, follow_path).chain(),
524 );
525 app
526 }
527
528 fn spawn_colonist(app: &mut App, tile: UVec2) -> Entity {
529 app.world_mut()
530 .spawn((
531 Colonist {
532 name: "Test".into(),
533 },
534 TilePos(tile),
535 sim_pos(WorldMap::tile_center(tile)),
536 ))
537 .id()
538 }
539
540 fn run_ticks(app: &mut App, ticks: u32) {
541 for _ in 0..ticks {
542 app.world_mut().resource_mut::<Time>().advance_by(TICK);
543 app.update();
544 }
545 }
546
547 fn map_with_trees(trees: &[UVec2]) -> WorldMap {
548 let mut map = WorldMap::filled(UVec2::new(20, 20), Terrain::Grass);
549 for &t in trees {
550 map.set_plant(t, Some(Plant::Tree));
551 }
552 map
553 }
554
555 fn wood_on_map(app: &mut App) -> u32 {
556 let world = app.world_mut();
557 let items: Vec<Item> = world.query::<&Item>().iter(world).copied().collect();
558 stock(items.iter(), ItemKind::Wood)
559 }
560
561 fn items_at(app: &mut App) -> Vec<(UVec2, u32)> {
562 let world = app.world_mut();
563 let mut items: Vec<(UVec2, u32)> = world
564 .query::<(&Item, &TilePos)>()
565 .iter(world)
566 .map(|(item, pos)| (pos.0, item.count))
567 .collect();
568 items.sort_by_key(|(p, _)| (p.y, p.x));
569 items
570 }
571
572 fn put_wood(app: &mut App, tile: UVec2, count: u32) {
573 app.world_mut().spawn((
574 Item {
575 kind: ItemKind::Wood,
576 count,
577 },
578 TilePos(tile),
579 ));
580 }
581
582 fn hauling_app(stockpile: (IVec2, IVec2)) -> App {
583 let mut app = test_app(map_with_trees(&[]));
584 app.world_mut().resource_mut::<ColonyGoals>().wood = 0;
585 let map = app.world().resource::<WorldMap>().clone();
586 app.world_mut()
587 .resource_mut::<Zones>()
588 .add_stockpile(&map, stockpile.0, stockpile.1);
589 app
590 }
591
592 fn carrying(app: &App, colonist: Entity) -> Option<Item> {
593 app.world().get::<Carrying>(colonist).unwrap().0
594 }
595
596 fn job(app: &App, colonist: Entity) -> Option<Job> {
597 app.world().get::<CurrentJob>(colonist).unwrap().0
598 }
599
600 #[test]
601 fn idle_colonists_cut_trees_when_the_colony_needs_wood() {
602 let tree = UVec2::new(8, 5);
603 let mut app = test_app(map_with_trees(&[tree]));
604 spawn_colonist(&mut app, UVec2::new(2, 5));
605 run_ticks(&mut app, 60 * 15);
606 assert_eq!(
607 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
608 None
609 );
610 assert_eq!(wood_on_map(&mut app), WOOD_PER_TREE);
611 assert!(app.world().resource::<Reservations>().0.is_empty());
612 }
613
614 #[test]
615 fn colonists_leave_trees_alone_when_there_is_enough_wood() {
616 let tree = UVec2::new(8, 5);
617 let mut app = test_app(map_with_trees(&[tree]));
618 app.world_mut().resource_mut::<ColonyGoals>().wood = 0;
619 spawn_colonist(&mut app, UVec2::new(2, 5));
620 run_ticks(&mut app, 60 * 15);
621 assert_eq!(
622 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
623 Some(Plant::Tree)
624 );
625 }
626
627 #[test]
628 fn colonists_never_pick_the_same_tree() {
629 let trees = [UVec2::new(10, 10), UVec2::new(10, 11)];
630 let mut app = test_app(map_with_trees(&trees));
631 let a = spawn_colonist(&mut app, UVec2::new(5, 10));
632 let b = spawn_colonist(&mut app, UVec2::new(5, 11));
633 run_ticks(&mut app, 61);
634 let target = |c| match job(&app, c) {
635 Some(Job {
636 task: Task::Chop { tree, .. },
637 ..
638 }) => tree,
639 other => panic!("expected chop job, got {other:?}"),
640 };
641 assert_ne!(target(a), target(b));
642 }
643
644 // Each chopped tree will add WOOD_PER_TREE; counting trees already being chopped as future
645 // wood keeps the whole colony from felling a forest when only a little more wood is needed.
646 #[test]
647 fn trees_already_being_cut_count_towards_the_wood_goal() {
648 let goals = ColonyGoals { wood: 25 };
649 assert!(wood_wanted(&goals, 10, 1));
650 assert!(!wood_wanted(&goals, 10, 2));
651 assert!(!wood_wanted(&goals, 30, 0));
652 }
653
654 #[test]
655 fn ordered_chop_ignores_the_wood_goal() {
656 let tree = UVec2::new(8, 5);
657 let mut app = test_app(map_with_trees(&[tree]));
658 app.world_mut().resource_mut::<ColonyGoals>().wood = 0;
659 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
660 app.world_mut().write_message(Order {
661 colonist,
662 tile: tree,
663 });
664 run_ticks(&mut app, 60 * 15);
665 assert_eq!(
666 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
667 None
668 );
669 }
670
671 #[test]
672 fn ordering_a_move_cancels_the_current_job_and_frees_its_tree() {
673 let tree = UVec2::new(15, 5);
674 let mut app = test_app(map_with_trees(&[tree]));
675 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
676 run_ticks(&mut app, 61);
677 assert!(matches!(
678 job(&app, colonist),
679 Some(Job {
680 task: Task::Chop { .. },
681 ..
682 })
683 ));
684 app.world_mut().write_message(Order {
685 colonist,
686 tile: UVec2::new(2, 15),
687 });
688 run_ticks(&mut app, 1);
689 assert_eq!(
690 job(&app, colonist).map(|j| j.task),
691 Some(Task::MoveTo(UVec2::new(2, 15)))
692 );
693 assert!(
694 app.world()
695 .resource::<Reservations>()
696 .is_free(Target::Tree(tree))
697 );
698 }
699
700 #[test]
701 fn idle_colonists_haul_loose_items_into_the_stockpile() {
702 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(15, 15)));
703 put_wood(&mut app, UVec2::new(5, 5), 20);
704 spawn_colonist(&mut app, UVec2::new(2, 5));
705 run_ticks(&mut app, 60 * 15);
706 assert_eq!(items_at(&mut app), vec![(UVec2::new(15, 15), 20)]);
707 }
708
709 #[test]
710 fn large_stacks_take_several_trips_and_spill_into_more_stockpile_tiles() {
711 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(16, 15)));
712 put_wood(&mut app, UVec2::new(5, 5), STACK_LIMIT + 10);
713 spawn_colonist(&mut app, UVec2::new(2, 5));
714 run_ticks(&mut app, 60 * 40);
715 assert_eq!(
716 items_at(&mut app),
717 vec![(UVec2::new(15, 15), STACK_LIMIT), (UVec2::new(16, 15), 10)]
718 );
719 }
720
721 #[test]
722 fn items_already_in_a_stockpile_stay_put() {
723 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(16, 16)));
724 put_wood(&mut app, UVec2::new(5, 5), 20);
725 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
726 run_ticks(&mut app, 60 * 5);
727 assert_eq!(items_at(&mut app), vec![(UVec2::new(5, 5), 20)]);
728 assert_eq!(carrying(&app, colonist), None);
729 }
730
731 #[test]
732 fn without_a_stockpile_nothing_is_hauled() {
733 let mut app = test_app(map_with_trees(&[]));
734 app.world_mut().resource_mut::<ColonyGoals>().wood = 0;
735 put_wood(&mut app, UVec2::new(5, 5), 20);
736 spawn_colonist(&mut app, UVec2::new(2, 5));
737 run_ticks(&mut app, 60 * 5);
738 assert_eq!(items_at(&mut app), vec![(UVec2::new(5, 5), 20)]);
739 }
740
741 #[test]
742 fn two_colonists_never_haul_the_same_stack() {
743 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(16, 16)));
744 put_wood(&mut app, UVec2::new(5, 5), 10);
745 put_wood(&mut app, UVec2::new(5, 6), 10);
746 let a = spawn_colonist(&mut app, UVec2::new(2, 5));
747 let b = spawn_colonist(&mut app, UVec2::new(2, 6));
748 run_ticks(&mut app, 61);
749 let pickup = |c| match job(&app, c).map(|j| j.task) {
750 Some(Task::Haul { pickup, .. }) => pickup,
751 other => panic!("expected haul, got {other:?}"),
752 };
753 assert_ne!(pickup(a), pickup(b));
754 }
755
756 // Orders interrupt whatever a colonist is doing, but whatever it is carrying stays in its
757 // hands; once it is idle again it finishes delivering it instead of dropping it anywhere.
758 #[test]
759 fn interrupted_haulers_deliver_their_load_later() {
760 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(15, 15)));
761 put_wood(&mut app, UVec2::new(4, 5), 20);
762 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
763 let mut ticks = 0;
764 while carrying(&app, colonist).is_none() && ticks < 60 * 10 {
765 run_ticks(&mut app, 1);
766 ticks += 1;
767 }
768 app.world_mut().write_message(Order {
769 colonist,
770 tile: UVec2::new(2, 2),
771 });
772 run_ticks(&mut app, 60 * 3);
773 assert!(carrying(&app, colonist).is_some());
774 run_ticks(&mut app, 60 * 20);
775 assert_eq!(carrying(&app, colonist), None);
776 assert_eq!(items_at(&mut app), vec![(UVec2::new(15, 15), 20)]);
777 }
778
779 #[test]
780 fn right_clicking_loose_items_orders_a_haul() {
781 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(15, 15)));
782 app.world_mut().resource_mut::<ColonyGoals>().wood = 1000;
783 put_wood(&mut app, UVec2::new(5, 5), 20);
784 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
785 app.world_mut().write_message(Order {
786 colonist,
787 tile: UVec2::new(5, 5),
788 });
789 run_ticks(&mut app, 1);
790 assert!(matches!(
791 job(&app, colonist),
792 Some(Job {
793 task: Task::Haul { .. },
794 ordered: true
795 })
796 ));
797 }
798
799 #[test]
800 fn colonists_chop_from_a_neighbouring_tile() {
801 let tree = UVec2::new(8, 5);
802 let mut app = test_app(map_with_trees(&[tree]));
803 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
804 run_ticks(&mut app, 60 * 5);
805 let tile = app.world().get::<TilePos>(colonist).unwrap().0;
806 assert!(is_adjacent(tile.as_ivec2(), tree.as_ivec2()));
807 assert_eq!(
808 app.world().get::<SimPos>(colonist).unwrap().0,
809 WorldMap::tile_center(tile)
810 );
811 }
812 }