src/jobs.rs 35.3 K · 1104 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, Terrain, TileChanged, TilePos, WorldMap},
19 worldgen::WorldGenerated,
20 zones::{Zones, find_stockpile_site, new_stockpile_tiles, plan_expansion},
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 EXPAND_TICKS: u32 = 120;
45 pub const EXPANSION_TILES: usize = 8;
46 pub const MIN_EMPTY_STOCKPILE_TILES: usize = 3;
47 const SEARCH_TILES: usize = 15000;
48 const WANDER_RADIUS: i32 = 8;
49 const IDLE_SECS: Range<f32> = 1.0..4.0;
50 const IDLE_AFTER_ORDER_SECS: f32 = 10.0;
51 const WORK_PAUSE_SECS: Range<f32> = 0.2..0.8;
52 const NEIGHBORS: [IVec2; 8] = [
53 IVec2::new(1, 0),
54 IVec2::new(-1, 0),
55 IVec2::new(0, 1),
56 IVec2::new(0, -1),
57 IVec2::new(1, 1),
58 IVec2::new(1, -1),
59 IVec2::new(-1, 1),
60 IVec2::new(-1, -1),
61 ];
62
63 #[derive(Component, Default, Debug, Clone, PartialEq)]
64 pub struct CurrentJob(pub Option<Job>);
65
66 #[derive(Debug, Clone, Copy, PartialEq)]
67 pub struct Job {
68 pub task: Task,
69 pub ordered: bool,
70 }
71
72 #[derive(Debug, Clone, Copy, PartialEq)]
73 pub enum Task {
74 MoveTo(UVec2),
75 Work {
76 site: UVec2,
77 kind: WorkKind,
78 progress: u32,
79 },
80 Haul {
81 pickup: Option<UVec2>,
82 to: UVec2,
83 },
84 ExpandStockpile {
85 site: UVec2,
86 progress: u32,
87 },
88 }
89
90 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
91 pub enum WorkKind {
92 Chop,
93 Mine,
94 }
95
96 impl WorkKind {
97 pub fn ticks(self) -> u32 {
98 match self {
99 WorkKind::Chop => 240,
100 WorkKind::Mine => 360,
101 }
102 }
103
104 fn complete(self, map: &mut WorldMap, site: UVec2) {
105 match self {
106 WorkKind::Chop => map.set_plant(site, None),
107 WorkKind::Mine => map.set(site, Terrain::Gravel),
108 }
109 }
110 }
111
112 pub struct SiteWork {
113 pub kind: WorkKind,
114 pub item: ItemKind,
115 pub count: u32,
116 }
117
118 pub fn site_work(map: &WorldMap, site: UVec2) -> Option<SiteWork> {
119 let p = site.as_ivec2();
120 if map.plant(p) == Some(Plant::Tree) {
121 return Some(SiteWork {
122 kind: WorkKind::Chop,
123 item: ItemKind::Wood,
124 count: 10,
125 });
126 }
127 let (item, count) = match map.get(p)? {
128 Terrain::Stone => (ItemKind::Stone, 10),
129 Terrain::IronOre => (ItemKind::Iron, 10),
130 Terrain::GoldOre => (ItemKind::Gold, 5),
131 _ => return None,
132 };
133 Some(SiteWork {
134 kind: WorkKind::Mine,
135 item,
136 count,
137 })
138 }
139
140 #[derive(Component, Debug)]
141 pub struct IdleTimer(Timer);
142
143 impl Default for IdleTimer {
144 fn default() -> Self {
145 Self(Timer::from_seconds(IDLE_SECS.start, TimerMode::Once))
146 }
147 }
148
149 impl IdleTimer {
150 fn restart(&mut self, secs: f32) {
151 self.0.set_duration(Duration::from_secs_f32(secs));
152 self.0.reset();
153 }
154 }
155
156 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
157 pub enum Target {
158 Site(UVec2),
159 Pickup(UVec2),
160 Storage(UVec2),
161 StockpileExpansion,
162 }
163
164 #[derive(Resource, Default, Debug)]
165 pub struct Reservations(HashMap<Target, Entity>);
166
167 impl Reservations {
168 pub fn reserve(&mut self, target: Target, by: Entity) {
169 self.0.insert(target, by);
170 }
171
172 pub fn holder(&self, target: Target) -> Option<Entity> {
173 self.0.get(&target).copied()
174 }
175
176 pub fn is_free(&self, target: Target) -> bool {
177 self.holder(target).is_none()
178 }
179
180 pub fn release(&mut self, target: Target) {
181 self.0.remove(&target);
182 }
183
184 pub fn release_all(&mut self, by: Entity) {
185 self.0.retain(|_, holder| *holder != by);
186 }
187 }
188
189 #[derive(Resource, Debug, Clone)]
190 pub struct ColonyGoals(pub HashMap<ItemKind, u32>);
191
192 impl Default for ColonyGoals {
193 fn default() -> Self {
194 Self(HashMap::from([
195 (ItemKind::Wood, 50),
196 (ItemKind::Stone, 40),
197 (ItemKind::Iron, 20),
198 (ItemKind::Gold, 10),
199 ]))
200 }
201 }
202
203 impl ColonyGoals {
204 pub fn goal(&self, kind: ItemKind) -> u32 {
205 self.0.get(&kind).copied().unwrap_or(0)
206 }
207
208 pub fn wanted(&self, kind: ItemKind, in_stock: u32, on_the_way: u32) -> bool {
209 in_stock + on_the_way < self.goal(kind)
210 }
211 }
212
213 #[derive(Message, Debug, Clone, Copy)]
214 pub struct Order {
215 pub colonist: Entity,
216 pub tile: UVec2,
217 }
218
219 fn clear_reservations(mut reservations: ResMut<Reservations>) {
220 reservations.0.clear();
221 }
222
223 fn handle_orders(
224 mut orders: MessageReader<Order>,
225 map: Res<WorldMap>,
226 zones: Res<Zones>,
227 items: Query<(&Item, &TilePos)>,
228 mut reservations: ResMut<Reservations>,
229 mut colonists: Query<(&TilePos, &mut Path, &mut CurrentJob)>,
230 ) {
231 for order in orders.read() {
232 let Ok((tile, mut path, mut job)) = colonists.get_mut(order.colonist) else {
233 continue;
234 };
235 let loose_item = items
236 .iter()
237 .find(|(_, pos)| pos.0 == order.tile && !zones.is_stockpile(pos.0));
238 let task = if let Some(work) = site_work(&map, order.tile) {
239 Some(Task::Work {
240 site: order.tile,
241 kind: work.kind,
242 progress: 0,
243 })
244 } else if let Some((item, _)) = loose_item {
245 find_storage(&map, &zones, &reservations, &items, order.tile, item.kind).map(|to| {
246 Task::Haul {
247 pickup: Some(order.tile),
248 to,
249 }
250 })
251 } else {
252 None
253 };
254 if let Some(task) = task {
255 reservations.release_all(order.colonist);
256 reserve_task(&mut reservations, task, order.colonist);
257 path.0.truncate(1);
258 job.0 = Some(Job {
259 task,
260 ordered: true,
261 });
262 } else if let Some(new_path) = repath(&map, tile.0, &path.0, order.tile) {
263 reservations.release_all(order.colonist);
264 path.0 = new_path;
265 job.0 = Some(Job {
266 task: Task::MoveTo(order.tile),
267 ordered: true,
268 });
269 }
270 }
271 }
272
273 fn reserve_task(reservations: &mut Reservations, task: Task, by: Entity) {
274 match task {
275 Task::MoveTo(_) => {}
276 Task::Work { site, .. } => reservations.reserve(Target::Site(site), by),
277 Task::Haul { pickup, to } => {
278 if let Some(pickup) = pickup {
279 reservations.reserve(Target::Pickup(pickup), by);
280 }
281 reservations.reserve(Target::Storage(to), by);
282 }
283 Task::ExpandStockpile { .. } => reservations.reserve(Target::StockpileExpansion, by),
284 }
285 }
286
287 pub fn find_work(
288 map: &WorldMap,
289 reservations: &Reservations,
290 from: UVec2,
291 wanted: impl Fn(ItemKind) -> bool,
292 ) -> Option<Task> {
293 let mut found = None;
294 nearest_tile(map, from, SEARCH_TILES, |stand| {
295 found = NEIGHBORS.iter().find_map(|&d| {
296 let site = stand.as_ivec2() + d;
297 if site.x < 0 || site.y < 0 {
298 return None;
299 }
300 let site = site.as_uvec2();
301 let work = site_work(map, site)?;
302 (wanted(work.item) && reservations.is_free(Target::Site(site))).then_some(Task::Work {
303 site,
304 kind: work.kind,
305 progress: 0,
306 })
307 });
308 found.is_some()
309 })?;
310 found
311 }
312
313 pub fn find_storage<'a>(
314 map: &WorldMap,
315 zones: &Zones,
316 reservations: &Reservations,
317 items: impl IntoIterator<Item = (&'a Item, &'a TilePos)> + Clone,
318 from: UVec2,
319 kind: ItemKind,
320 ) -> Option<UVec2> {
321 nearest_tile(map, from, SEARCH_TILES, |p| {
322 zones.is_stockpile(p)
323 && reservations.is_free(Target::Storage(p))
324 && room_for(items.clone().into_iter(), p, kind) > 0
325 })
326 }
327
328 pub fn find_haul(
329 map: &WorldMap,
330 zones: &Zones,
331 reservations: &Reservations,
332 items: &[(Item, TilePos)],
333 from: UVec2,
334 ) -> Option<Task> {
335 let loose: HashSet<UVec2> = items
336 .iter()
337 .map(|(_, pos)| pos.0)
338 .filter(|&p| !zones.is_stockpile(p) && reservations.is_free(Target::Pickup(p)))
339 .collect();
340 if loose.is_empty() {
341 return None;
342 }
343 let pickup = nearest_tile(map, from, SEARCH_TILES, |p| loose.contains(&p))?;
344 let (item, _) = items.iter().find(|(_, pos)| pos.0 == pickup)?;
345 let refs = items.iter().map(|(i, p)| (i, p));
346 let to = find_storage(map, zones, reservations, refs, pickup, item.kind)?;
347 Some(Task::Haul {
348 pickup: Some(pickup),
349 to,
350 })
351 }
352
353 pub fn stockpile_too_full(zones: &Zones, items: &[(Item, TilePos)]) -> bool {
354 let occupied: HashSet<UVec2> = items.iter().map(|(_, pos)| pos.0).collect();
355 zones.has_stockpile() && zones.empty_stockpile_tiles(&occupied) < MIN_EMPTY_STOCKPILE_TILES
356 }
357
358 pub fn find_expansion(
359 map: &WorldMap,
360 zones: &Zones,
361 reservations: &Reservations,
362 items: &[(Item, TilePos)],
363 ) -> Option<Task> {
364 if !reservations.is_free(Target::StockpileExpansion) {
365 return None;
366 }
367 let site = if zones.has_stockpile() {
368 if !stockpile_too_full(zones, items) {
369 return None;
370 }
371 *plan_expansion(map, zones, EXPANSION_TILES).first()?
372 } else {
373 find_stockpile_site(map, central_item_tile(items)?)?
374 };
375 Some(Task::ExpandStockpile { site, progress: 0 })
376 }
377
378 fn central_item_tile(items: &[(Item, TilePos)]) -> Option<UVec2> {
379 let tiles: Vec<Vec2> = items.iter().map(|(_, pos)| pos.0.as_vec2()).collect();
380 let centroid = tiles.iter().sum::<Vec2>() / tiles.len().max(1) as f32;
381 items.iter().map(|(_, pos)| pos.0).min_by(|a, b| {
382 a.as_vec2()
383 .distance_squared(centroid)
384 .total_cmp(&b.as_vec2().distance_squared(centroid))
385 })
386 }
387
388 fn on_the_way(map: &WorldMap, jobs: impl Iterator<Item = Option<Job>>) -> HashMap<ItemKind, u32> {
389 let mut totals = HashMap::new();
390 for job in jobs.flatten() {
391 if let Task::Work { site, .. } = job.task
392 && let Some(work) = site_work(map, site)
393 {
394 *totals.entry(work.item).or_insert(0) += work.count;
395 }
396 }
397 totals
398 }
399
400 #[allow(clippy::too_many_arguments)]
401 fn choose_jobs(
402 mut commands: Commands,
403 time: Res<Time>,
404 map: Res<WorldMap>,
405 zones: Res<Zones>,
406 goals: Res<ColonyGoals>,
407 item_assets: Res<ItemAssets>,
408 mut rng: ResMut<SimRng>,
409 mut reservations: ResMut<Reservations>,
410 mut items: ItemQuery,
411 mut colonists: Query<
412 (
413 Entity,
414 &TilePos,
415 &mut Path,
416 &mut CurrentJob,
417 &mut IdleTimer,
418 &mut Carrying,
419 ),
420 With<Colonist>,
421 >,
422 ) {
423 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.5.0).collect();
424 let stocks: HashMap<ItemKind, u32> = ItemKind::ALL
425 .iter()
426 .map(|&kind| {
427 let all = items.iter().map(|(_, item, _)| item).chain(carried.iter());
428 (kind, stock(all, kind))
429 })
430 .collect();
431 let mut pending = on_the_way(&map, colonists.iter().map(|c| c.3.0));
432 for (entity, tile, mut path, mut job, mut idle, mut carrying) in &mut colonists {
433 if job.0.is_some() || !path.0.is_empty() || !idle.0.tick(time.delta()).is_finished() {
434 continue;
435 }
436 let snapshot: Vec<(Item, TilePos)> =
437 items.iter().map(|(_, item, pos)| (*item, *pos)).collect();
438 let refs = snapshot.iter().map(|(i, p)| (i, p));
439 let wanted = |kind: ItemKind| {
440 goals.wanted(
441 kind,
442 stocks[&kind],
443 pending.get(&kind).copied().unwrap_or(0),
444 )
445 };
446 let task = if let Some(load) = carrying.0 {
447 let storage = find_storage(&map, &zones, &reservations, refs, tile.0, load.kind);
448 if storage.is_none() {
449 drop_items(
450 &mut commands,
451 &mut items,
452 &item_assets,
453 tile.0,
454 load.kind,
455 load.count,
456 );
457 carrying.0 = None;
458 }
459 storage.map(|to| Task::Haul { pickup: None, to })
460 } else {
461 find_expansion(&map, &zones, &reservations, &snapshot)
462 .or_else(|| find_work(&map, &reservations, tile.0, wanted))
463 .or_else(|| find_haul(&map, &zones, &reservations, &snapshot, tile.0))
464 };
465 if let Some(task) = task {
466 if let Task::Work { site, .. } = task
467 && let Some(work) = site_work(&map, site)
468 {
469 *pending.entry(work.item).or_insert(0) += work.count;
470 }
471 reserve_task(&mut reservations, task, entity);
472 job.0 = Some(Job {
473 task,
474 ordered: false,
475 });
476 continue;
477 }
478 let goal = tile.0.as_ivec2()
479 + IVec2::new(
480 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
481 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
482 );
483 if map.in_bounds(goal)
484 && let Some(wander_path) = find_path(&map, tile.0, goal.as_uvec2())
485 {
486 path.0 = wander_path.into();
487 idle.restart(rng.range_f32(IDLE_SECS));
488 }
489 }
490 }
491
492 enum Step {
493 Continue,
494 Done,
495 }
496
497 fn walk_to(map: &WorldMap, from: UVec2, to: UVec2, path: &mut Path) -> Step {
498 match find_path(map, from, to) {
499 Some(p) if !p.is_empty() => {
500 path.0 = p.into();
501 Step::Continue
502 }
503 _ => Step::Done,
504 }
505 }
506
507 #[allow(clippy::too_many_arguments)]
508 fn run_jobs(
509 mut commands: Commands,
510 mut map: ResMut<WorldMap>,
511 mut zones: ResMut<Zones>,
512 mut reservations: ResMut<Reservations>,
513 mut rng: ResMut<SimRng>,
514 item_assets: Res<ItemAssets>,
515 mut items: ItemQuery,
516 mut changed: MessageWriter<TileChanged>,
517 mut colonists: Query<(
518 Entity,
519 &TilePos,
520 &mut Path,
521 &mut CurrentJob,
522 &mut IdleTimer,
523 &mut Carrying,
524 )>,
525 ) {
526 for (entity, tile, mut path, mut current, mut idle, mut carrying) in &mut colonists {
527 let Some(mut job) = current.0 else {
528 continue;
529 };
530 if !path.0.is_empty() {
531 continue;
532 }
533 let step = match &mut job.task {
534 Task::MoveTo(_) => Step::Done,
535 Task::Work {
536 site,
537 kind,
538 progress,
539 } => {
540 let (site, kind) = (*site, *kind);
541 let work = site_work(&map, site).filter(|w| w.kind == kind);
542 let ours = reservations.holder(Target::Site(site)) == Some(entity);
543 match work {
544 Some(work) if ours => {
545 if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
546 match find_path_adjacent(&map, tile.0, site) {
547 Some(p) if !p.is_empty() => {
548 path.0 = p.into();
549 Step::Continue
550 }
551 _ => Step::Done,
552 }
553 } else {
554 *progress += 1;
555 if *progress < kind.ticks() {
556 Step::Continue
557 } else {
558 kind.complete(&mut map, site);
559 changed.write(TileChanged(site));
560 drop_items(
561 &mut commands,
562 &mut items,
563 &item_assets,
564 site,
565 work.item,
566 work.count,
567 );
568 Step::Done
569 }
570 }
571 }
572 _ => Step::Done,
573 }
574 }
575 Task::ExpandStockpile { site, progress } => {
576 if tile.0 != *site {
577 walk_to(&map, tile.0, *site, &mut path)
578 } else {
579 *progress += 1;
580 if *progress >= EXPAND_TICKS {
581 if zones.has_stockpile() {
582 let tiles = plan_expansion(&map, &zones, EXPANSION_TILES);
583 zones.add_tiles(&map, tiles);
584 } else {
585 zones.add_tiles(&map, new_stockpile_tiles(*site));
586 }
587 Step::Done
588 } else {
589 Step::Continue
590 }
591 }
592 }
593 Task::Haul { pickup, to } => {
594 let to = *to;
595 let destination_valid = zones.is_stockpile(to)
596 && reservations.holder(Target::Storage(to)) == Some(entity);
597 if !destination_valid {
598 Step::Done
599 } else if let Some(from) = *pickup {
600 if reservations.holder(Target::Pickup(from)) != Some(entity) {
601 Step::Done
602 } else if tile.0 != from {
603 walk_to(&map, tile.0, from, &mut path)
604 } else {
605 let kind = items
606 .iter()
607 .find(|(_, _, pos)| pos.0 == from)
608 .map(|(_, item, _)| item.kind);
609 let room = kind.map_or(0, |kind| {
610 room_for(items.iter().map(|(_, i, p)| (i, p)), to, kind)
611 });
612 match take_items(&mut commands, &mut items, from, CARRY_CAPACITY.min(room))
613 .filter(|load| load.count > 0)
614 {
615 Some(load) => {
616 carrying.0 = Some(load);
617 reservations.release(Target::Pickup(from));
618 *pickup = None;
619 Step::Continue
620 }
621 None => Step::Done,
622 }
623 }
624 } else if let Some(load) = carrying.0 {
625 if tile.0 != to {
626 walk_to(&map, tile.0, to, &mut path)
627 } else {
628 let room = room_for(items.iter().map(|(_, i, p)| (i, p)), to, load.kind);
629 let dropped = load.count.min(room);
630 if dropped > 0 {
631 drop_items(
632 &mut commands,
633 &mut items,
634 &item_assets,
635 to,
636 load.kind,
637 dropped,
638 );
639 }
640 carrying.0 = (load.count > dropped).then_some(Item {
641 count: load.count - dropped,
642 ..load
643 });
644 Step::Done
645 }
646 } else {
647 Step::Done
648 }
649 }
650 };
651 match step {
652 Step::Continue => current.0 = Some(job),
653 Step::Done => {
654 reservations.release_all(entity);
655 current.0 = None;
656 let ordered_move = matches!(
657 job,
658 Job {
659 task: Task::MoveTo(_),
660 ordered: true
661 }
662 );
663 idle.restart(if ordered_move {
664 IDLE_AFTER_ORDER_SECS
665 } else {
666 rng.range_f32(WORK_PAUSE_SECS)
667 });
668 }
669 }
670 }
671 }
672
673 #[cfg(test)]
674 mod tests {
675 use super::*;
676 use crate::{
677 colonist::follow_path,
678 items::STACK_LIMIT,
679 sim::{SimPos, sim_pos},
680 world::Terrain,
681 zones::NEW_STOCKPILE_SIZE,
682 };
683
684 const TICK: Duration = Duration::from_nanos(1_000_000_000 / 60);
685
686 fn test_app(map: WorldMap) -> App {
687 let mut app = App::new();
688 app.insert_resource(map)
689 .insert_resource(SimRng::new(1))
690 .init_resource::<Time>()
691 .init_resource::<Reservations>()
692 .init_resource::<ColonyGoals>()
693 .init_resource::<ItemAssets>()
694 .init_resource::<Zones>()
695 .add_message::<Order>()
696 .add_message::<TileChanged>()
697 .add_systems(
698 Update,
699 (handle_orders, choose_jobs, run_jobs, follow_path).chain(),
700 );
701 app
702 }
703
704 fn spawn_colonist(app: &mut App, tile: UVec2) -> Entity {
705 app.world_mut()
706 .spawn((
707 Colonist {
708 name: "Test".into(),
709 },
710 TilePos(tile),
711 sim_pos(WorldMap::tile_center(tile)),
712 ))
713 .id()
714 }
715
716 fn run_ticks(app: &mut App, ticks: u32) {
717 for _ in 0..ticks {
718 app.world_mut().resource_mut::<Time>().advance_by(TICK);
719 app.update();
720 }
721 }
722
723 fn map_with_trees(trees: &[UVec2]) -> WorldMap {
724 let mut map = WorldMap::filled(UVec2::new(20, 20), Terrain::Grass);
725 for &t in trees {
726 map.set_plant(t, Some(Plant::Tree));
727 }
728 map
729 }
730
731 fn wood_on_map(app: &mut App) -> u32 {
732 let world = app.world_mut();
733 let items: Vec<Item> = world.query::<&Item>().iter(world).copied().collect();
734 stock(items.iter(), ItemKind::Wood)
735 }
736
737 fn items_at(app: &mut App) -> Vec<(UVec2, u32)> {
738 let world = app.world_mut();
739 let mut items: Vec<(UVec2, u32)> = world
740 .query::<(&Item, &TilePos)>()
741 .iter(world)
742 .map(|(item, pos)| (pos.0, item.count))
743 .collect();
744 items.sort_by_key(|(p, _)| (p.y, p.x));
745 items
746 }
747
748 fn put_wood(app: &mut App, tile: UVec2, count: u32) {
749 app.world_mut().spawn((
750 Item {
751 kind: ItemKind::Wood,
752 count,
753 },
754 TilePos(tile),
755 ));
756 }
757
758 fn set_goals(app: &mut App, goals: &[(ItemKind, u32)]) {
759 *app.world_mut().resource_mut::<ColonyGoals>() =
760 ColonyGoals(goals.iter().copied().collect());
761 }
762
763 fn stockpile_size(app: &App) -> usize {
764 let map = app.world().resource::<WorldMap>();
765 let zones = app.world().resource::<Zones>();
766 map.positions().filter(|&p| zones.is_stockpile(p)).count()
767 }
768
769 fn stored(app: &mut App) -> u32 {
770 let zones = app.world().resource::<Zones>().clone();
771 items_at(app)
772 .iter()
773 .filter(|(p, _)| zones.is_stockpile(*p))
774 .map(|(_, c)| c)
775 .sum()
776 }
777
778 fn hauling_app(stockpile: (IVec2, IVec2)) -> App {
779 let mut app = test_app(map_with_trees(&[]));
780 set_goals(&mut app, &[]);
781 let map = app.world().resource::<WorldMap>().clone();
782 app.world_mut()
783 .resource_mut::<Zones>()
784 .add_stockpile(&map, stockpile.0, stockpile.1);
785 app
786 }
787
788 fn carrying(app: &App, colonist: Entity) -> Option<Item> {
789 app.world().get::<Carrying>(colonist).unwrap().0
790 }
791
792 fn job(app: &App, colonist: Entity) -> Option<Job> {
793 app.world().get::<CurrentJob>(colonist).unwrap().0
794 }
795
796 #[test]
797 fn idle_colonists_cut_trees_when_the_colony_needs_wood() {
798 let tree = UVec2::new(8, 5);
799 let mut app = test_app(map_with_trees(&[tree]));
800 spawn_colonist(&mut app, UVec2::new(2, 5));
801 run_ticks(&mut app, 60 * 15);
802 assert_eq!(
803 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
804 None
805 );
806 assert_eq!(wood_on_map(&mut app), 10);
807 assert!(app.world().resource::<Reservations>().0.is_empty());
808 }
809
810 #[test]
811 fn colonists_leave_trees_alone_when_there_is_enough_wood() {
812 let tree = UVec2::new(8, 5);
813 let mut app = test_app(map_with_trees(&[tree]));
814 set_goals(&mut app, &[]);
815 spawn_colonist(&mut app, UVec2::new(2, 5));
816 run_ticks(&mut app, 60 * 15);
817 assert_eq!(
818 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
819 Some(Plant::Tree)
820 );
821 }
822
823 #[test]
824 fn colonists_never_pick_the_same_tree() {
825 let trees = [UVec2::new(10, 10), UVec2::new(10, 11)];
826 let mut app = test_app(map_with_trees(&trees));
827 let a = spawn_colonist(&mut app, UVec2::new(5, 10));
828 let b = spawn_colonist(&mut app, UVec2::new(5, 11));
829 run_ticks(&mut app, 61);
830 let target = |c| match job(&app, c) {
831 Some(Job {
832 task: Task::Work { site, .. },
833 ..
834 }) => site,
835 other => panic!("expected chop job, got {other:?}"),
836 };
837 assert_ne!(target(a), target(b));
838 }
839
840 // Each tree or rock being worked will add its yield; counting that as material on the way
841 // keeps the whole colony from felling a forest when only a little more wood is needed.
842 #[test]
843 fn work_in_progress_counts_towards_goals() {
844 let goals = ColonyGoals(HashMap::from([(ItemKind::Wood, 25)]));
845 assert!(goals.wanted(ItemKind::Wood, 10, 10));
846 assert!(!goals.wanted(ItemKind::Wood, 10, 20));
847 assert!(!goals.wanted(ItemKind::Wood, 30, 0));
848 assert!(!goals.wanted(ItemKind::Gold, 0, 0));
849 }
850
851 #[test]
852 fn ordered_chop_ignores_the_wood_goal() {
853 let tree = UVec2::new(8, 5);
854 let mut app = test_app(map_with_trees(&[tree]));
855 set_goals(&mut app, &[]);
856 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
857 app.world_mut().write_message(Order {
858 colonist,
859 tile: tree,
860 });
861 run_ticks(&mut app, 60 * 15);
862 assert_eq!(
863 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
864 None
865 );
866 }
867
868 #[test]
869 fn ordering_a_move_cancels_the_current_job_and_frees_its_tree() {
870 let tree = UVec2::new(15, 5);
871 let mut app = test_app(map_with_trees(&[tree]));
872 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
873 run_ticks(&mut app, 61);
874 assert!(matches!(
875 job(&app, colonist),
876 Some(Job {
877 task: Task::Work { .. },
878 ..
879 })
880 ));
881 app.world_mut().write_message(Order {
882 colonist,
883 tile: UVec2::new(2, 15),
884 });
885 run_ticks(&mut app, 1);
886 assert_eq!(
887 job(&app, colonist).map(|j| j.task),
888 Some(Task::MoveTo(UVec2::new(2, 15)))
889 );
890 assert!(
891 app.world()
892 .resource::<Reservations>()
893 .is_free(Target::Site(tree))
894 );
895 }
896
897 #[test]
898 fn idle_colonists_haul_loose_items_into_the_stockpile() {
899 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(17, 15)));
900 put_wood(&mut app, UVec2::new(5, 5), 20);
901 spawn_colonist(&mut app, UVec2::new(2, 5));
902 run_ticks(&mut app, 60 * 15);
903 assert_eq!(items_at(&mut app), vec![(UVec2::new(15, 15), 20)]);
904 }
905
906 #[test]
907 fn large_stacks_take_several_trips_and_spill_into_more_stockpile_tiles() {
908 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(17, 15)));
909 put_wood(&mut app, UVec2::new(5, 5), STACK_LIMIT + 10);
910 spawn_colonist(&mut app, UVec2::new(2, 5));
911 run_ticks(&mut app, 60 * 40);
912 let stacks = items_at(&mut app);
913 assert_eq!(stored(&mut app), STACK_LIMIT + 10);
914 assert!(stacks.len() >= 2);
915 assert!(stacks.iter().all(|(_, count)| *count <= STACK_LIMIT));
916 }
917
918 #[test]
919 fn items_already_in_a_stockpile_stay_put() {
920 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(16, 16)));
921 put_wood(&mut app, UVec2::new(5, 5), 20);
922 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
923 run_ticks(&mut app, 60 * 5);
924 assert_eq!(items_at(&mut app), vec![(UVec2::new(5, 5), 20)]);
925 assert_eq!(carrying(&app, colonist), None);
926 }
927
928 #[test]
929 fn colonists_found_a_stockpile_when_items_need_storing() {
930 let mut app = test_app(map_with_trees(&[]));
931 set_goals(&mut app, &[]);
932 put_wood(&mut app, UVec2::new(5, 5), 20);
933 spawn_colonist(&mut app, UVec2::new(2, 5));
934 run_ticks(&mut app, 60 * 15);
935 assert_eq!(
936 stockpile_size(&app),
937 (NEW_STOCKPILE_SIZE * NEW_STOCKPILE_SIZE) as usize
938 );
939 assert_eq!(stored(&mut app), 20);
940 }
941
942 #[test]
943 fn no_stockpile_is_founded_while_there_is_nothing_to_store() {
944 let mut app = test_app(map_with_trees(&[]));
945 set_goals(&mut app, &[]);
946 spawn_colonist(&mut app, UVec2::new(2, 5));
947 run_ticks(&mut app, 60 * 5);
948 assert_eq!(stockpile_size(&app), 0);
949 }
950
951 #[test]
952 fn two_colonists_never_haul_the_same_stack() {
953 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(16, 16)));
954 put_wood(&mut app, UVec2::new(5, 5), 10);
955 put_wood(&mut app, UVec2::new(5, 6), 10);
956 let a = spawn_colonist(&mut app, UVec2::new(2, 5));
957 let b = spawn_colonist(&mut app, UVec2::new(2, 6));
958 run_ticks(&mut app, 61);
959 let pickup = |c| match job(&app, c).map(|j| j.task) {
960 Some(Task::Haul { pickup, .. }) => pickup,
961 other => panic!("expected haul, got {other:?}"),
962 };
963 assert_ne!(pickup(a), pickup(b));
964 }
965
966 // Orders interrupt whatever a colonist is doing, but whatever it is carrying stays in its
967 // hands; once it is idle again it finishes delivering it instead of dropping it anywhere.
968 #[test]
969 fn interrupted_haulers_deliver_their_load_later() {
970 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(17, 15)));
971 put_wood(&mut app, UVec2::new(4, 5), 20);
972 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
973 let mut ticks = 0;
974 while carrying(&app, colonist).is_none() && ticks < 60 * 10 {
975 run_ticks(&mut app, 1);
976 ticks += 1;
977 }
978 app.world_mut().write_message(Order {
979 colonist,
980 tile: UVec2::new(2, 2),
981 });
982 run_ticks(&mut app, 60 * 3);
983 assert!(carrying(&app, colonist).is_some());
984 run_ticks(&mut app, 60 * 20);
985 assert_eq!(carrying(&app, colonist), None);
986 assert_eq!(stored(&mut app), 20);
987 }
988
989 #[test]
990 fn right_clicking_loose_items_orders_a_haul() {
991 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(15, 15)));
992 set_goals(&mut app, &[(ItemKind::Wood, 1000)]);
993 put_wood(&mut app, UVec2::new(5, 5), 20);
994 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
995 app.world_mut().write_message(Order {
996 colonist,
997 tile: UVec2::new(5, 5),
998 });
999 run_ticks(&mut app, 1);
1000 assert!(matches!(
1001 job(&app, colonist),
1002 Some(Job {
1003 task: Task::Haul { .. },
1004 ordered: true
1005 })
1006 ));
1007 }
1008
1009 fn mining_map() -> WorldMap {
1010 let mut map = WorldMap::filled(UVec2::new(20, 20), Terrain::Grass);
1011 for y in 0..20 {
1012 map.set(UVec2::new(10, y), Terrain::Stone);
1013 }
1014 map.set(UVec2::new(10, 5), Terrain::IronOre);
1015 map
1016 }
1017
1018 fn items_of(app: &mut App, kind: ItemKind) -> u32 {
1019 let world = app.world_mut();
1020 let items: Vec<Item> = world.query::<&Item>().iter(world).copied().collect();
1021 stock(items.iter(), kind)
1022 }
1023
1024 #[test]
1025 fn colonists_mine_rock_the_colony_needs_and_leave_gravel() {
1026 let mut app = test_app(mining_map());
1027 set_goals(&mut app, &[(ItemKind::Stone, 10)]);
1028 spawn_colonist(&mut app, UVec2::new(8, 12));
1029 run_ticks(&mut app, 60 * 12);
1030 assert_eq!(items_of(&mut app, ItemKind::Stone), 10);
1031 assert_eq!(items_of(&mut app, ItemKind::Iron), 0);
1032 let map = app.world().resource::<WorldMap>();
1033 let gravel = map
1034 .positions()
1035 .filter(|p| map.get(p.as_ivec2()) == Some(Terrain::Gravel))
1036 .count();
1037 assert_eq!(gravel, 1);
1038 }
1039
1040 #[test]
1041 fn colonists_walk_past_rock_they_do_not_need() {
1042 let mut app = test_app(mining_map());
1043 set_goals(&mut app, &[(ItemKind::Iron, 10)]);
1044 spawn_colonist(&mut app, UVec2::new(8, 15));
1045 run_ticks(&mut app, 60 * 15);
1046 assert_eq!(items_of(&mut app, ItemKind::Iron), 10);
1047 assert_eq!(items_of(&mut app, ItemKind::Stone), 0);
1048 assert_eq!(
1049 app.world().resource::<WorldMap>().get(IVec2::new(10, 5)),
1050 Some(Terrain::Gravel)
1051 );
1052 }
1053
1054 #[test]
1055 fn right_clicking_rock_orders_mining_regardless_of_goals() {
1056 let mut app = test_app(mining_map());
1057 set_goals(&mut app, &[]);
1058 let colonist = spawn_colonist(&mut app, UVec2::new(8, 12));
1059 app.world_mut().write_message(Order {
1060 colonist,
1061 tile: UVec2::new(10, 12),
1062 });
1063 run_ticks(&mut app, 60 * 10);
1064 assert_eq!(
1065 app.world().resource::<WorldMap>().get(IVec2::new(10, 12)),
1066 Some(Terrain::Gravel)
1067 );
1068 }
1069
1070 #[test]
1071 fn colonists_expand_a_stockpile_that_is_nearly_full() {
1072 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(6, 5)));
1073 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1074 run_ticks(&mut app, 61);
1075 assert!(matches!(
1076 job(&app, colonist).map(|j| j.task),
1077 Some(Task::ExpandStockpile { .. })
1078 ));
1079 run_ticks(&mut app, 60 * 5);
1080 assert_eq!(stockpile_size(&app), 2 + EXPANSION_TILES);
1081 }
1082
1083 #[test]
1084 fn roomy_stockpiles_are_left_alone() {
1085 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(8, 5)));
1086 spawn_colonist(&mut app, UVec2::new(2, 5));
1087 run_ticks(&mut app, 60 * 5);
1088 assert_eq!(stockpile_size(&app), 4);
1089 }
1090
1091 #[test]
1092 fn colonists_chop_from_a_neighbouring_tile() {
1093 let tree = UVec2::new(8, 5);
1094 let mut app = test_app(map_with_trees(&[tree]));
1095 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1096 run_ticks(&mut app, 60 * 5);
1097 let tile = app.world().get::<TilePos>(colonist).unwrap().0;
1098 assert!(is_adjacent(tile.as_ivec2(), tree.as_ivec2()));
1099 assert_eq!(
1100 app.world().get::<SimPos>(colonist).unwrap().0,
1101 WorldMap::tile_center(tile)
1102 );
1103 }
1104 }