src/jobs.rs 61.4 K · 1822 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 building::{Blueprints, BuildKind},
11 colonist::{Colonist, Path, repath},
12 items::{
13 CARRY_CAPACITY, Carrying, Item, ItemAssets, ItemKind, ItemQuery, drop_items, room_for,
14 stock, take_items,
15 },
16 light::{LIT_BRIGHTNESS, LightMap, brightness, dark_soon, light_from},
17 needs::{EXHAUSTED_REST, Rest, SleepContext, done_sleeping, wants_sleep},
18 pathfinding::{find_path, find_path_adjacent, is_adjacent, nearest_tile},
19 rng::SimRng,
20 sim::{SimSystems, SimTick, hour_of_day},
21 structures::{Fuel, Structure, StructureAssets, StructureKind, spawn_structure},
22 world::{Plant, Terrain, TileChanged, TilePos, WorldMap},
23 worldgen::WorldGenerated,
24 zones::{Zones, can_zone, find_stockpile_site, new_stockpile_tiles, plan_expansion},
25 };
26
27 pub struct JobsPlugin;
28
29 impl Plugin for JobsPlugin {
30 fn build(&self, app: &mut App) {
31 app.insert_resource(SimRng::new(0x5EED))
32 .init_resource::<Reservations>()
33 .init_resource::<ColonyGoals>()
34 .add_message::<Order>()
35 .add_message::<TileChanged>()
36 .add_systems(
37 Update,
38 (
39 clear_reservations.run_if(on_message::<WorldGenerated>),
40 handle_orders,
41 ),
42 )
43 .add_systems(FixedUpdate, choose_jobs.in_set(SimSystems::Decide))
44 .add_systems(FixedUpdate, run_jobs.in_set(SimSystems::Act));
45 }
46 }
47
48 pub const EXPAND_WORK: u32 = 240;
49 pub const CAMPFIRE_MIN_FUEL: u32 = 3 * crate::sim::TICKS_PER_HOUR as u32;
50 pub const HOME_RADIUS: f32 = 10.0;
51 pub const BED_STOCKPILE_CLEARANCE: i32 = 3;
52 const LIT_WORK_RATE: u32 = 2;
53 const DARK_WORK_RATE: u32 = 1;
54 pub const EXPANSION_TILES: usize = 8;
55 pub const MIN_EMPTY_STOCKPILE_TILES: usize = 3;
56 const SEARCH_TILES: usize = 15000;
57 const WANDER_RADIUS: i32 = 8;
58 const IDLE_SECS: Range<f32> = 1.0..4.0;
59 const IDLE_AFTER_ORDER_SECS: f32 = 10.0;
60 const WORK_PAUSE_SECS: Range<f32> = 0.2..0.8;
61 const NEIGHBORS: [IVec2; 8] = [
62 IVec2::new(1, 0),
63 IVec2::new(-1, 0),
64 IVec2::new(0, 1),
65 IVec2::new(0, -1),
66 IVec2::new(1, 1),
67 IVec2::new(1, -1),
68 IVec2::new(-1, 1),
69 IVec2::new(-1, -1),
70 ];
71
72 #[derive(Component, Default, Debug, Clone, PartialEq)]
73 pub struct CurrentJob(pub Option<Job>);
74
75 #[derive(Debug, Clone, Copy, PartialEq)]
76 pub struct Job {
77 pub task: Task,
78 pub ordered: bool,
79 }
80
81 #[derive(Debug, Clone, Copy, PartialEq)]
82 pub enum Task {
83 MoveTo(UVec2),
84 Work {
85 site: UVec2,
86 kind: WorkKind,
87 progress: u32,
88 },
89 Haul {
90 pickup: Option<UVec2>,
91 to: UVec2,
92 },
93 ExpandStockpile {
94 site: UVec2,
95 progress: u32,
96 },
97 Build {
98 site: UVec2,
99 kind: BuildKind,
100 pickup: Option<UVec2>,
101 progress: u32,
102 },
103 Sleep {
104 spot: UVec2,
105 },
106 }
107
108 pub fn work_rate(light: &LightMap, tile: UVec2) -> u32 {
109 if light.is_lit(tile) {
110 LIT_WORK_RATE
111 } else {
112 DARK_WORK_RATE
113 }
114 }
115
116 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
117 pub enum WorkKind {
118 Chop,
119 Mine,
120 }
121
122 impl WorkKind {
123 pub fn work(self) -> u32 {
124 match self {
125 WorkKind::Chop => 480,
126 WorkKind::Mine => 720,
127 }
128 }
129
130 fn complete(self, map: &mut WorldMap, site: UVec2) {
131 match self {
132 WorkKind::Chop => map.set_plant(site, None),
133 WorkKind::Mine => map.set(site, Terrain::Gravel),
134 }
135 }
136 }
137
138 pub struct SiteWork {
139 pub kind: WorkKind,
140 pub item: ItemKind,
141 pub count: u32,
142 }
143
144 pub fn site_work(map: &WorldMap, site: UVec2) -> Option<SiteWork> {
145 let p = site.as_ivec2();
146 if map.plant(p) == Some(Plant::Tree) {
147 return Some(SiteWork {
148 kind: WorkKind::Chop,
149 item: ItemKind::Wood,
150 count: 10,
151 });
152 }
153 let (item, count) = match map.get(p)? {
154 Terrain::Stone => (ItemKind::Stone, 10),
155 Terrain::IronOre => (ItemKind::Iron, 10),
156 Terrain::GoldOre => (ItemKind::Gold, 5),
157 _ => return None,
158 };
159 Some(SiteWork {
160 kind: WorkKind::Mine,
161 item,
162 count,
163 })
164 }
165
166 #[derive(Component, Debug)]
167 pub struct IdleTimer(Timer);
168
169 impl Default for IdleTimer {
170 fn default() -> Self {
171 Self(Timer::from_seconds(IDLE_SECS.start, TimerMode::Once))
172 }
173 }
174
175 impl IdleTimer {
176 fn restart(&mut self, secs: f32) {
177 self.0.set_duration(Duration::from_secs_f32(secs));
178 self.0.reset();
179 }
180 }
181
182 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
183 pub enum Target {
184 Site(UVec2),
185 Pickup(UVec2),
186 Storage(UVec2),
187 StockpileExpansion,
188 SleepSpot(UVec2),
189 }
190
191 #[derive(Resource, Default, Debug)]
192 pub struct Reservations(HashMap<Target, Entity>);
193
194 impl Reservations {
195 pub fn reserve(&mut self, target: Target, by: Entity) {
196 self.0.insert(target, by);
197 }
198
199 pub fn holder(&self, target: Target) -> Option<Entity> {
200 self.0.get(&target).copied()
201 }
202
203 pub fn is_free(&self, target: Target) -> bool {
204 self.holder(target).is_none()
205 }
206
207 pub fn release(&mut self, target: Target) {
208 self.0.remove(&target);
209 }
210
211 pub fn release_all(&mut self, by: Entity) {
212 self.0.retain(|_, holder| *holder != by);
213 }
214 }
215
216 #[derive(Resource, Debug, Clone)]
217 pub struct ColonyGoals(pub HashMap<ItemKind, u32>);
218
219 impl Default for ColonyGoals {
220 fn default() -> Self {
221 Self(HashMap::from([
222 (ItemKind::Wood, 50),
223 (ItemKind::Stone, 40),
224 (ItemKind::Iron, 20),
225 (ItemKind::Gold, 10),
226 ]))
227 }
228 }
229
230 impl ColonyGoals {
231 pub fn goal(&self, kind: ItemKind) -> u32 {
232 self.0.get(&kind).copied().unwrap_or(0)
233 }
234
235 pub fn wanted(&self, kind: ItemKind, in_stock: u32, on_the_way: u32) -> bool {
236 in_stock + on_the_way < self.goal(kind)
237 }
238 }
239
240 #[derive(Message, Debug, Clone, Copy)]
241 pub struct Order {
242 pub colonist: Entity,
243 pub tile: UVec2,
244 }
245
246 fn clear_reservations(mut reservations: ResMut<Reservations>) {
247 reservations.0.clear();
248 }
249
250 fn handle_orders(
251 mut orders: MessageReader<Order>,
252 map: Res<WorldMap>,
253 zones: Res<Zones>,
254 items: Query<(&Item, &TilePos)>,
255 mut reservations: ResMut<Reservations>,
256 mut colonists: Query<(&TilePos, &mut Path, &mut CurrentJob)>,
257 ) {
258 for order in orders.read() {
259 let Ok((tile, mut path, mut job)) = colonists.get_mut(order.colonist) else {
260 continue;
261 };
262 let loose_item = items
263 .iter()
264 .find(|(_, pos)| pos.0 == order.tile && !zones.is_stockpile(pos.0));
265 let task = if let Some(work) = site_work(&map, order.tile) {
266 Some(Task::Work {
267 site: order.tile,
268 kind: work.kind,
269 progress: 0,
270 })
271 } else if let Some((item, _)) = loose_item {
272 find_storage(&map, &zones, &reservations, &items, order.tile, item.kind).map(|to| {
273 Task::Haul {
274 pickup: Some(order.tile),
275 to,
276 }
277 })
278 } else {
279 None
280 };
281 if let Some(task) = task {
282 reservations.release_all(order.colonist);
283 reserve_task(&mut reservations, task, order.colonist);
284 path.0.truncate(1);
285 job.0 = Some(Job {
286 task,
287 ordered: true,
288 });
289 } else if let Some(new_path) = repath(&map, tile.0, &path.0, order.tile) {
290 reservations.release_all(order.colonist);
291 path.0 = new_path;
292 job.0 = Some(Job {
293 task: Task::MoveTo(order.tile),
294 ordered: true,
295 });
296 }
297 }
298 }
299
300 fn reserve_task(reservations: &mut Reservations, task: Task, by: Entity) {
301 match task {
302 Task::MoveTo(_) => {}
303 Task::Work { site, .. } => reservations.reserve(Target::Site(site), by),
304 Task::Haul { pickup, to } => {
305 if let Some(pickup) = pickup {
306 reservations.reserve(Target::Pickup(pickup), by);
307 }
308 reservations.reserve(Target::Storage(to), by);
309 }
310 Task::ExpandStockpile { .. } => reservations.reserve(Target::StockpileExpansion, by),
311 Task::Sleep { spot } => reservations.reserve(Target::SleepSpot(spot), by),
312 Task::Build { site, pickup, .. } => {
313 reservations.reserve(Target::Site(site), by);
314 if let Some(pickup) = pickup {
315 reservations.reserve(Target::Pickup(pickup), by);
316 }
317 }
318 }
319 }
320
321 pub fn find_work(
322 map: &WorldMap,
323 reservations: &Reservations,
324 from: UVec2,
325 wanted: impl Fn(ItemKind) -> bool,
326 ) -> Option<Task> {
327 let mut found = None;
328 nearest_tile(map, from, SEARCH_TILES, |stand| {
329 found = NEIGHBORS.iter().find_map(|&d| {
330 let site = stand.as_ivec2() + d;
331 if site.x < 0 || site.y < 0 {
332 return None;
333 }
334 let site = site.as_uvec2();
335 let work = site_work(map, site)?;
336 (wanted(work.item) && reservations.is_free(Target::Site(site))).then_some(Task::Work {
337 site,
338 kind: work.kind,
339 progress: 0,
340 })
341 });
342 found.is_some()
343 })?;
344 found
345 }
346
347 pub fn find_storage<'a>(
348 map: &WorldMap,
349 zones: &Zones,
350 reservations: &Reservations,
351 items: impl IntoIterator<Item = (&'a Item, &'a TilePos)> + Clone,
352 from: UVec2,
353 kind: ItemKind,
354 ) -> Option<UVec2> {
355 nearest_tile(map, from, SEARCH_TILES, |p| {
356 zones.is_stockpile(p)
357 && reservations.is_free(Target::Storage(p))
358 && room_for(items.clone().into_iter(), p, kind) > 0
359 })
360 }
361
362 pub fn find_haul(
363 map: &WorldMap,
364 zones: &Zones,
365 reservations: &Reservations,
366 items: &[(Item, TilePos)],
367 from: UVec2,
368 ) -> Option<Task> {
369 let loose: HashSet<UVec2> = items
370 .iter()
371 .map(|(_, pos)| pos.0)
372 .filter(|&p| !zones.is_stockpile(p) && reservations.is_free(Target::Pickup(p)))
373 .collect();
374 if loose.is_empty() {
375 return None;
376 }
377 let pickup = nearest_tile(map, from, SEARCH_TILES, |p| loose.contains(&p))?;
378 let (item, _) = items.iter().find(|(_, pos)| pos.0 == pickup)?;
379 let refs = items.iter().map(|(i, p)| (i, p));
380 let to = find_storage(map, zones, reservations, refs, pickup, item.kind)?;
381 Some(Task::Haul {
382 pickup: Some(pickup),
383 to,
384 })
385 }
386
387 pub fn stockpile_too_full(zones: &Zones, items: &[(Item, TilePos)]) -> bool {
388 let occupied: HashSet<UVec2> = items.iter().map(|(_, pos)| pos.0).collect();
389 zones.has_stockpile() && zones.empty_stockpile_tiles(&occupied) < MIN_EMPTY_STOCKPILE_TILES
390 }
391
392 pub fn find_expansion(
393 map: &WorldMap,
394 zones: &Zones,
395 reservations: &Reservations,
396 items: &[(Item, TilePos)],
397 blueprints: &Blueprints,
398 ) -> Option<Task> {
399 if !reservations.is_free(Target::StockpileExpansion) {
400 return None;
401 }
402 let site = if zones.has_stockpile() {
403 if !stockpile_too_full(zones, items) {
404 return None;
405 }
406 *plan_expansion(map, zones, &blueprints.tiles(), EXPANSION_TILES).first()?
407 } else {
408 find_stockpile_site(map, central_item_tile(items)?)?
409 };
410 Some(Task::ExpandStockpile { site, progress: 0 })
411 }
412
413 fn central_item_tile(items: &[(Item, TilePos)]) -> Option<UVec2> {
414 let tiles: Vec<Vec2> = items.iter().map(|(_, pos)| pos.0.as_vec2()).collect();
415 let centroid = tiles.iter().sum::<Vec2>() / tiles.len().max(1) as f32;
416 items.iter().map(|(_, pos)| pos.0).min_by(|a, b| {
417 a.as_vec2()
418 .distance_squared(centroid)
419 .total_cmp(&b.as_vec2().distance_squared(centroid))
420 })
421 }
422
423 pub struct BuildContext<'a> {
424 pub map: &'a WorldMap,
425 pub zones: &'a Zones,
426 pub reservations: &'a Reservations,
427 pub items: &'a [(Item, TilePos)],
428 pub structures: &'a [(UVec2, StructureKind, u32)],
429 pub planned: &'a [(UVec2, StructureKind)],
430 pub blueprints: &'a Blueprints,
431 }
432
433 impl BuildContext<'_> {
434 fn buildable(&self, tile: UVec2) -> bool {
435 can_zone(self.map, tile.as_ivec2())
436 && !self.zones.is_stockpile(tile)
437 && self.map.plant(tile.as_ivec2()).is_none()
438 && !self.structures.iter().any(|(pos, ..)| *pos == tile)
439 && !self.planned.iter().any(|(pos, _)| *pos == tile)
440 && self.blueprints.get(tile).is_none()
441 && !self.items.iter().any(|(_, pos)| pos.0 == tile)
442 && self.reservations.is_free(Target::Site(tile))
443 }
444
445 fn lights(&self) -> impl Iterator<Item = (UVec2, StructureKind)> + Clone + '_ {
446 self.structures
447 .iter()
448 .map(|&(pos, kind, _)| (pos, kind))
449 .chain(self.planned.iter().copied())
450 }
451
452 fn campfire_needed(&self, home: UVec2) -> bool {
453 let burning = self.structures.iter().any(|&(pos, kind, fuel)| {
454 kind == StructureKind::Campfire
455 && fuel >= CAMPFIRE_MIN_FUEL
456 && pos.as_vec2().distance(home.as_vec2()) <= HOME_RADIUS
457 });
458 let planned = self
459 .planned
460 .iter()
461 .any(|(_, kind)| *kind == StructureKind::Campfire);
462 !burning && !planned
463 }
464
465 fn darkest_stockpile_tile(&self, home: UVec2) -> Option<UVec2> {
466 self.zones
467 .stockpile_tiles()
468 .filter(|&t| brightness(light_from(t, self.lights())) < LIT_BRIGHTNESS)
469 .min_by(|a, b| {
470 a.as_vec2()
471 .distance_squared(home.as_vec2())
472 .total_cmp(&b.as_vec2().distance_squared(home.as_vec2()))
473 .then((a.y, a.x).cmp(&(b.y, b.x)))
474 })
475 }
476
477 fn site_near(&self, target: UVec2, max_distance: f32) -> Option<UVec2> {
478 self.site_near_where(target, max_distance, |_| true)
479 }
480
481 fn site_near_where(
482 &self,
483 target: UVec2,
484 max_distance: f32,
485 extra: impl Fn(UVec2) -> bool,
486 ) -> Option<UVec2> {
487 nearest_tile(self.map, target, SEARCH_TILES, |p| {
488 self.buildable(p) && extra(p)
489 })
490 .filter(|site| site.as_vec2().distance(target.as_vec2()) <= max_distance)
491 }
492
493 fn clear_of_stockpile(&self, tile: UVec2) -> bool {
494 self.zones.stockpile_tiles().all(|s| {
495 (s.as_ivec2() - tile.as_ivec2()).abs().max_element() >= BED_STOCKPILE_CLEARANCE
496 })
497 }
498
499 fn count(&self, kind: StructureKind) -> usize {
500 let built = self.structures.iter().filter(|s| s.1 == kind).count();
501 built + self.planned.iter().filter(|p| p.1 == kind).count()
502 }
503
504 fn bed_anchor(&self, home: UVec2) -> UVec2 {
505 let positions = |kind: StructureKind| {
506 let built = self.structures.iter().map(|s| (s.0, s.1));
507 built
508 .chain(self.planned.iter().copied())
509 .filter(move |s| s.1 == kind)
510 .map(|s| s.0)
511 };
512 let nearest = |kind: StructureKind| {
513 positions(kind).min_by(|a, b| {
514 a.as_vec2()
515 .distance_squared(home.as_vec2())
516 .total_cmp(&b.as_vec2().distance_squared(home.as_vec2()))
517 })
518 };
519 nearest(StructureKind::Bed)
520 .or_else(|| nearest(StructureKind::Campfire))
521 .unwrap_or(home)
522 }
523
524 fn material_source(&self, from: UVec2, (kind, amount): (ItemKind, u32)) -> Option<UVec2> {
525 nearest_tile(self.map, from, SEARCH_TILES, |p| {
526 self.reservations.is_free(Target::Pickup(p))
527 && self
528 .items
529 .iter()
530 .any(|(item, pos)| pos.0 == p && item.kind == kind && item.count >= amount)
531 })
532 }
533
534 fn build_task(&self, from: UVec2, site: UVec2, kind: BuildKind) -> Option<Task> {
535 let pickup = self.material_source(from, kind.cost())?;
536 Some(Task::Build {
537 site,
538 kind,
539 pickup: Some(pickup),
540 progress: 0,
541 })
542 }
543 }
544
545 pub fn find_lighting(ctx: &BuildContext, from: UVec2) -> Option<Task> {
546 let home = ctx.zones.home(from);
547 let (kind, site) = if ctx.campfire_needed(home) {
548 (StructureKind::Campfire, ctx.site_near(home, HOME_RADIUS)?)
549 } else {
550 let dark = ctx.darkest_stockpile_tile(home)?;
551 let reach = StructureKind::Torch.radius() * 0.6;
552 (StructureKind::Torch, ctx.site_near(dark, reach)?)
553 };
554 ctx.build_task(from, site, BuildKind::Structure(kind))
555 }
556
557 pub fn find_bed_site(ctx: &BuildContext, colonists: usize, from: UVec2) -> Option<Task> {
558 if ctx.count(StructureKind::Bed) >= colonists {
559 return None;
560 }
561 let anchor = ctx.bed_anchor(ctx.zones.home(from));
562 let site = ctx.site_near_where(anchor, HOME_RADIUS * 1.5, |p| ctx.clear_of_stockpile(p))?;
563 ctx.build_task(from, site, BuildKind::Structure(StructureKind::Bed))
564 }
565
566 pub fn find_blueprint_work(ctx: &BuildContext, from: UVec2) -> Option<Task> {
567 let mut found = None;
568 nearest_tile(ctx.map, from, SEARCH_TILES, |p| {
569 let Some(kind) = ctx.blueprints.get(p) else {
570 return false;
571 };
572 if !ctx.reservations.is_free(Target::Site(p)) {
573 return false;
574 }
575 found = ctx.build_task(from, p, kind);
576 found.is_some()
577 })?;
578 found
579 }
580
581 fn on_the_way(map: &WorldMap, jobs: impl Iterator<Item = Option<Job>>) -> HashMap<ItemKind, u32> {
582 let mut totals = HashMap::new();
583 for job in jobs.flatten() {
584 if let Task::Work { site, .. } = job.task
585 && let Some(work) = site_work(map, site)
586 {
587 *totals.entry(work.item).or_insert(0) += work.count;
588 }
589 }
590 totals
591 }
592
593 #[allow(clippy::too_many_arguments)]
594 fn choose_jobs(
595 mut commands: Commands,
596 time: Res<Time>,
597 map: Res<WorldMap>,
598 zones: Res<Zones>,
599 goals: Res<ColonyGoals>,
600 item_assets: Res<ItemAssets>,
601 tick: Res<SimTick>,
602 blueprints: Res<Blueprints>,
603 mut rng: ResMut<SimRng>,
604 mut reservations: ResMut<Reservations>,
605 mut items: ItemQuery,
606 structures: Query<(&TilePos, &Structure, Option<&Fuel>), Without<Colonist>>,
607 mut colonists: Query<
608 (
609 Entity,
610 &TilePos,
611 &mut Path,
612 &mut CurrentJob,
613 &mut IdleTimer,
614 &mut Carrying,
615 &Rest,
616 ),
617 With<Colonist>,
618 >,
619 ) {
620 let colonist_count = colonists.iter().count();
621 let structures_list: Vec<(UVec2, StructureKind, u32)> = structures
622 .iter()
623 .map(|(pos, s, fuel)| (pos.0, s.kind, fuel.map_or(u32::MAX, |f| f.0)))
624 .collect();
625 let mut planned: Vec<(UVec2, StructureKind)> = colonists
626 .iter()
627 .filter_map(|c| match c.3.0?.task {
628 Task::Build {
629 site,
630 kind: BuildKind::Structure(kind),
631 ..
632 } => Some((site, kind)),
633 _ => None,
634 })
635 .collect();
636 let dark = dark_soon(*tick);
637 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.5.0).collect();
638 let stocks: HashMap<ItemKind, u32> = ItemKind::ALL
639 .iter()
640 .map(|&kind| {
641 let all = items.iter().map(|(_, item, _)| item).chain(carried.iter());
642 (kind, stock(all, kind))
643 })
644 .collect();
645 let mut pending = on_the_way(&map, colonists.iter().map(|c| c.3.0));
646 let hour = hour_of_day(*tick);
647 for (entity, tile, mut path, mut job, mut idle, mut carrying, rest) in &mut colonists {
648 let exhausted = rest.0 < EXHAUSTED_REST;
649 if exhausted
650 && job
651 .0
652 .is_some_and(|j| !j.ordered && !matches!(j.task, Task::Sleep { .. }))
653 {
654 reservations.release_all(entity);
655 job.0 = None;
656 path.0.truncate(1);
657 }
658 let rested = idle.0.tick(time.delta()).is_finished();
659 if job.0.is_some() || !path.0.is_empty() || !(rested || exhausted) {
660 continue;
661 }
662 let snapshot: Vec<(Item, TilePos)> =
663 items.iter().map(|(_, item, pos)| (*item, *pos)).collect();
664 let refs = snapshot.iter().map(|(i, p)| (i, p));
665 let wanted = |kind: ItemKind| {
666 goals.wanted(
667 kind,
668 stocks[&kind],
669 pending.get(&kind).copied().unwrap_or(0),
670 )
671 };
672 let sleep = SleepContext {
673 map: &map,
674 zones: &zones,
675 reservations: &reservations,
676 items: &snapshot,
677 structures: &structures_list,
678 blueprints: &blueprints,
679 };
680 let task = if wants_sleep(rest.0, hour) {
681 Some(Task::Sleep {
682 spot: sleep.spot(tile.0),
683 })
684 } else if let Some(load) = carrying.0 {
685 let storage = find_storage(&map, &zones, &reservations, refs, tile.0, load.kind);
686 if storage.is_none() {
687 drop_items(
688 &mut commands,
689 &mut items,
690 &item_assets,
691 tile.0,
692 load.kind,
693 load.count,
694 );
695 carrying.0 = None;
696 }
697 storage.map(|to| Task::Haul { pickup: None, to })
698 } else {
699 let build = BuildContext {
700 map: &map,
701 zones: &zones,
702 reservations: &reservations,
703 items: &snapshot,
704 structures: &structures_list,
705 planned: &planned,
706 blueprints: &blueprints,
707 };
708 find_expansion(&map, &zones, &reservations, &snapshot, &blueprints)
709 .or_else(|| dark.then(|| find_lighting(&build, tile.0)).flatten())
710 .or_else(|| find_work(&map, &reservations, tile.0, wanted))
711 .or_else(|| find_haul(&map, &zones, &reservations, &snapshot, tile.0))
712 .or_else(|| find_bed_site(&build, colonist_count, tile.0))
713 .or_else(|| find_blueprint_work(&build, tile.0))
714 };
715 if let Some(task) = task {
716 if let Task::Work { site, .. } = task
717 && let Some(work) = site_work(&map, site)
718 {
719 *pending.entry(work.item).or_insert(0) += work.count;
720 }
721 if let Task::Build {
722 site,
723 kind: BuildKind::Structure(kind),
724 ..
725 } = task
726 {
727 planned.push((site, kind));
728 }
729 reserve_task(&mut reservations, task, entity);
730 job.0 = Some(Job {
731 task,
732 ordered: false,
733 });
734 continue;
735 }
736 let goal = tile.0.as_ivec2()
737 + IVec2::new(
738 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
739 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
740 );
741 if map.in_bounds(goal)
742 && let Some(wander_path) = find_path(&map, tile.0, goal.as_uvec2())
743 {
744 path.0 = wander_path.into();
745 idle.restart(rng.range_f32(IDLE_SECS));
746 }
747 }
748 }
749
750 enum Step {
751 Continue,
752 Done,
753 }
754
755 fn walk_to(map: &WorldMap, from: UVec2, to: UVec2, path: &mut Path) -> Step {
756 match find_path(map, from, to) {
757 Some(p) if !p.is_empty() => {
758 path.0 = p.into();
759 Step::Continue
760 }
761 _ => Step::Done,
762 }
763 }
764
765 #[allow(clippy::too_many_arguments)]
766 fn run_jobs(
767 mut commands: Commands,
768 mut map: ResMut<WorldMap>,
769 mut zones: ResMut<Zones>,
770 mut reservations: ResMut<Reservations>,
771 mut rng: ResMut<SimRng>,
772 item_assets: Res<ItemAssets>,
773 structure_assets: Res<StructureAssets>,
774 light: Res<LightMap>,
775 tick: Res<SimTick>,
776 mut blueprints: ResMut<Blueprints>,
777 mut items: ItemQuery,
778 structures: Query<&TilePos, (With<Structure>, Without<Colonist>)>,
779 mut changed: MessageWriter<TileChanged>,
780 mut colonists: Query<
781 (
782 Entity,
783 &TilePos,
784 &mut Path,
785 &mut CurrentJob,
786 &mut IdleTimer,
787 &mut Carrying,
788 &Rest,
789 ),
790 With<Colonist>,
791 >,
792 ) {
793 let hour = hour_of_day(*tick);
794 let occupied: Vec<UVec2> = colonists.iter().map(|c| c.1.0).collect();
795 for (entity, tile, mut path, mut current, mut idle, mut carrying, rest) in &mut colonists {
796 let Some(mut job) = current.0 else {
797 continue;
798 };
799 if !path.0.is_empty() {
800 continue;
801 }
802 let step = match &mut job.task {
803 Task::MoveTo(_) => Step::Done,
804 Task::Sleep { spot } => {
805 if reservations.holder(Target::SleepSpot(*spot)) != Some(entity) {
806 Step::Done
807 } else if tile.0 != *spot {
808 let step = walk_to(&map, tile.0, *spot, &mut path);
809 if matches!(step, Step::Done) {
810 reservations.release(Target::SleepSpot(*spot));
811 *spot = tile.0;
812 reservations.reserve(Target::SleepSpot(*spot), entity);
813 }
814 Step::Continue
815 } else if done_sleeping(rest.0, hour) {
816 Step::Done
817 } else {
818 Step::Continue
819 }
820 }
821 Task::Work {
822 site,
823 kind,
824 progress,
825 } => {
826 let (site, kind) = (*site, *kind);
827 let work = site_work(&map, site).filter(|w| w.kind == kind);
828 let ours = reservations.holder(Target::Site(site)) == Some(entity);
829 match work {
830 Some(work) if ours => {
831 if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
832 match find_path_adjacent(&map, tile.0, site) {
833 Some(p) if !p.is_empty() => {
834 path.0 = p.into();
835 Step::Continue
836 }
837 _ => Step::Done,
838 }
839 } else {
840 *progress += work_rate(&light, tile.0);
841 if *progress < kind.work() {
842 Step::Continue
843 } else {
844 kind.complete(&mut map, site);
845 changed.write(TileChanged(site));
846 drop_items(
847 &mut commands,
848 &mut items,
849 &item_assets,
850 site,
851 work.item,
852 work.count,
853 );
854 Step::Done
855 }
856 }
857 }
858 _ => Step::Done,
859 }
860 }
861 Task::ExpandStockpile { site, progress } => {
862 if tile.0 != *site {
863 walk_to(&map, tile.0, *site, &mut path)
864 } else {
865 *progress += work_rate(&light, tile.0);
866 if *progress >= EXPAND_WORK {
867 if zones.has_stockpile() {
868 let excluded = blueprints.tiles();
869 let tiles = plan_expansion(&map, &zones, &excluded, EXPANSION_TILES);
870 zones.add_tiles(&map, tiles);
871 } else {
872 zones.add_tiles(&map, new_stockpile_tiles(*site));
873 }
874 Step::Done
875 } else {
876 Step::Continue
877 }
878 }
879 }
880 Task::Build {
881 site,
882 kind,
883 pickup,
884 progress,
885 } => {
886 let (site, kind) = (*site, *kind);
887 let ours = reservations.holder(Target::Site(site)) == Some(entity);
888 let planned = match kind {
889 BuildKind::Structure(
890 StructureKind::Campfire | StructureKind::Torch | StructureKind::Bed,
891 ) => true,
892 _ => blueprints.get(site) == Some(kind),
893 };
894 let blocked = map.plant(site.as_ivec2()).is_some()
895 || (kind != BuildKind::Roof && structures.iter().any(|pos| pos.0 == site));
896 let (material, cost) = kind.cost();
897 if !ours || blocked || !planned {
898 Step::Done
899 } else if let Some(from) = *pickup {
900 if reservations.holder(Target::Pickup(from)) != Some(entity) {
901 Step::Done
902 } else if tile.0 != from {
903 walk_to(&map, tile.0, from, &mut path)
904 } else {
905 let load = take_items(&mut commands, &mut items, from, cost)
906 .filter(|load| load.kind == material && load.count > 0);
907 carrying.0 = load;
908 match load {
909 Some(load) if load.count >= cost => {
910 reservations.release(Target::Pickup(from));
911 *pickup = None;
912 Step::Continue
913 }
914 _ => Step::Done,
915 }
916 }
917 } else if !carrying
918 .0
919 .is_some_and(|load| load.kind == material && load.count >= cost)
920 {
921 Step::Done
922 } else if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
923 match find_path_adjacent(&map, tile.0, site) {
924 Some(p) if !p.is_empty() => {
925 path.0 = p.into();
926 Step::Continue
927 }
928 _ => Step::Done,
929 }
930 } else {
931 *progress = (*progress + work_rate(&light, tile.0)).min(kind.work());
932 let someone_in_the_way = kind.blocks_tile() && occupied.contains(&site);
933 if *progress < kind.work() || someone_in_the_way {
934 Step::Continue
935 } else {
936 carrying.0 = carrying.0.and_then(|load| {
937 (load.count > cost).then_some(Item {
938 count: load.count - cost,
939 ..load
940 })
941 });
942 match kind {
943 BuildKind::Structure(structure) => {
944 spawn_structure(&mut commands, &structure_assets, site, structure);
945 if kind.blocks_tile() {
946 map.set_wall(site, true);
947 changed.write(TileChanged(site));
948 }
949 }
950 BuildKind::Roof => {
951 map.set_roof(site, true);
952 changed.write(TileChanged(site));
953 }
954 }
955 blueprints.0.remove(&site);
956 Step::Done
957 }
958 }
959 }
960 Task::Haul { pickup, to } => {
961 let to = *to;
962 let destination_valid = zones.is_stockpile(to)
963 && reservations.holder(Target::Storage(to)) == Some(entity);
964 if !destination_valid {
965 Step::Done
966 } else if let Some(from) = *pickup {
967 if reservations.holder(Target::Pickup(from)) != Some(entity) {
968 Step::Done
969 } else if tile.0 != from {
970 walk_to(&map, tile.0, from, &mut path)
971 } else {
972 let kind = items
973 .iter()
974 .find(|(_, _, pos)| pos.0 == from)
975 .map(|(_, item, _)| item.kind);
976 let room = kind.map_or(0, |kind| {
977 room_for(items.iter().map(|(_, i, p)| (i, p)), to, kind)
978 });
979 match take_items(&mut commands, &mut items, from, CARRY_CAPACITY.min(room))
980 .filter(|load| load.count > 0)
981 {
982 Some(load) => {
983 carrying.0 = Some(load);
984 reservations.release(Target::Pickup(from));
985 *pickup = None;
986 Step::Continue
987 }
988 None => Step::Done,
989 }
990 }
991 } else if let Some(load) = carrying.0 {
992 if tile.0 != to {
993 walk_to(&map, tile.0, to, &mut path)
994 } else {
995 let room = room_for(items.iter().map(|(_, i, p)| (i, p)), to, load.kind);
996 let dropped = load.count.min(room);
997 if dropped > 0 {
998 drop_items(
999 &mut commands,
1000 &mut items,
1001 &item_assets,
1002 to,
1003 load.kind,
1004 dropped,
1005 );
1006 }
1007 carrying.0 = (load.count > dropped).then_some(Item {
1008 count: load.count - dropped,
1009 ..load
1010 });
1011 Step::Done
1012 }
1013 } else {
1014 Step::Done
1015 }
1016 }
1017 };
1018 match step {
1019 Step::Continue => current.0 = Some(job),
1020 Step::Done => {
1021 reservations.release_all(entity);
1022 current.0 = None;
1023 let ordered_move = matches!(
1024 job,
1025 Job {
1026 task: Task::MoveTo(_),
1027 ordered: true
1028 }
1029 );
1030 idle.restart(if ordered_move {
1031 IDLE_AFTER_ORDER_SECS
1032 } else {
1033 rng.range_f32(WORK_PAUSE_SECS)
1034 });
1035 }
1036 }
1037 }
1038 }
1039
1040 #[cfg(test)]
1041 mod tests {
1042 use super::*;
1043 use crate::{
1044 colonist::follow_path,
1045 items::STACK_LIMIT,
1046 sim::{SimPos, sim_pos},
1047 world::Terrain,
1048 zones::NEW_STOCKPILE_SIZE,
1049 };
1050
1051 const TICK: Duration = Duration::from_nanos(1_000_000_000 / 60);
1052
1053 fn test_app(map: WorldMap) -> App {
1054 let mut app = App::new();
1055 app.insert_resource(map)
1056 .insert_resource(SimRng::new(1))
1057 .init_resource::<Time>()
1058 .init_resource::<Reservations>()
1059 .init_resource::<ColonyGoals>()
1060 .init_resource::<ItemAssets>()
1061 .init_resource::<StructureAssets>()
1062 .init_resource::<Blueprints>()
1063 .init_resource::<LightMap>()
1064 .init_resource::<SimTick>()
1065 .init_resource::<Zones>()
1066 .add_message::<Order>()
1067 .add_message::<TileChanged>()
1068 .add_systems(
1069 Update,
1070 (
1071 handle_orders,
1072 choose_jobs,
1073 run_jobs,
1074 follow_path,
1075 crate::needs::update_rest,
1076 )
1077 .chain(),
1078 );
1079 app
1080 }
1081
1082 fn spawn_colonist(app: &mut App, tile: UVec2) -> Entity {
1083 app.world_mut()
1084 .spawn((
1085 Colonist {
1086 name: "Test".into(),
1087 },
1088 TilePos(tile),
1089 sim_pos(WorldMap::tile_center(tile)),
1090 ))
1091 .id()
1092 }
1093
1094 fn run_ticks(app: &mut App, ticks: u32) {
1095 for _ in 0..ticks {
1096 app.world_mut().resource_mut::<Time>().advance_by(TICK);
1097 app.update();
1098 }
1099 }
1100
1101 fn map_with_trees(trees: &[UVec2]) -> WorldMap {
1102 let mut map = WorldMap::filled(UVec2::new(20, 20), Terrain::Grass);
1103 for &t in trees {
1104 map.set_plant(t, Some(Plant::Tree));
1105 }
1106 map
1107 }
1108
1109 fn wood_on_map(app: &mut App) -> u32 {
1110 let world = app.world_mut();
1111 let items: Vec<Item> = world.query::<&Item>().iter(world).copied().collect();
1112 stock(items.iter(), ItemKind::Wood)
1113 }
1114
1115 fn items_at(app: &mut App) -> Vec<(UVec2, u32)> {
1116 let world = app.world_mut();
1117 let mut items: Vec<(UVec2, u32)> = world
1118 .query::<(&Item, &TilePos)>()
1119 .iter(world)
1120 .map(|(item, pos)| (pos.0, item.count))
1121 .collect();
1122 items.sort_by_key(|(p, _)| (p.y, p.x));
1123 items
1124 }
1125
1126 fn put_wood(app: &mut App, tile: UVec2, count: u32) {
1127 app.world_mut().spawn((
1128 Item {
1129 kind: ItemKind::Wood,
1130 count,
1131 },
1132 TilePos(tile),
1133 ));
1134 }
1135
1136 fn set_goals(app: &mut App, goals: &[(ItemKind, u32)]) {
1137 *app.world_mut().resource_mut::<ColonyGoals>() =
1138 ColonyGoals(goals.iter().copied().collect());
1139 }
1140
1141 fn stockpile_size(app: &App) -> usize {
1142 let map = app.world().resource::<WorldMap>();
1143 let zones = app.world().resource::<Zones>();
1144 map.positions().filter(|&p| zones.is_stockpile(p)).count()
1145 }
1146
1147 fn stored(app: &mut App) -> u32 {
1148 let zones = app.world().resource::<Zones>().clone();
1149 items_at(app)
1150 .iter()
1151 .filter(|(p, _)| zones.is_stockpile(*p))
1152 .map(|(_, c)| c)
1153 .sum()
1154 }
1155
1156 fn put_beds(app: &mut App, count: u32) {
1157 for x in 0..count {
1158 app.world_mut().spawn((
1159 Structure {
1160 kind: StructureKind::Bed,
1161 },
1162 TilePos(UVec2::new(19 - x, 19)),
1163 ));
1164 }
1165 }
1166
1167 fn hauling_app(stockpile: (IVec2, IVec2)) -> App {
1168 let mut app = test_app(map_with_trees(&[]));
1169 put_beds(&mut app, 2);
1170 set_goals(&mut app, &[]);
1171 let map = app.world().resource::<WorldMap>().clone();
1172 app.world_mut()
1173 .resource_mut::<Zones>()
1174 .add_stockpile(&map, stockpile.0, stockpile.1);
1175 app
1176 }
1177
1178 fn carrying(app: &App, colonist: Entity) -> Option<Item> {
1179 app.world().get::<Carrying>(colonist).unwrap().0
1180 }
1181
1182 fn job(app: &App, colonist: Entity) -> Option<Job> {
1183 app.world().get::<CurrentJob>(colonist).unwrap().0
1184 }
1185
1186 #[test]
1187 fn idle_colonists_cut_trees_when_the_colony_needs_wood() {
1188 let tree = UVec2::new(8, 5);
1189 let mut app = test_app(map_with_trees(&[tree]));
1190 spawn_colonist(&mut app, UVec2::new(2, 5));
1191 run_ticks(&mut app, 60 * 15);
1192 assert_eq!(
1193 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
1194 None
1195 );
1196 assert_eq!(wood_on_map(&mut app), 10);
1197 assert!(app.world().resource::<Reservations>().0.is_empty());
1198 }
1199
1200 #[test]
1201 fn colonists_leave_trees_alone_when_there_is_enough_wood() {
1202 let tree = UVec2::new(8, 5);
1203 let mut app = test_app(map_with_trees(&[tree]));
1204 set_goals(&mut app, &[]);
1205 spawn_colonist(&mut app, UVec2::new(2, 5));
1206 run_ticks(&mut app, 60 * 15);
1207 assert_eq!(
1208 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
1209 Some(Plant::Tree)
1210 );
1211 }
1212
1213 #[test]
1214 fn colonists_never_pick_the_same_tree() {
1215 let trees = [UVec2::new(10, 10), UVec2::new(10, 11)];
1216 let mut app = test_app(map_with_trees(&trees));
1217 let a = spawn_colonist(&mut app, UVec2::new(5, 10));
1218 let b = spawn_colonist(&mut app, UVec2::new(5, 11));
1219 run_ticks(&mut app, 61);
1220 let target = |c| match job(&app, c) {
1221 Some(Job {
1222 task: Task::Work { site, .. },
1223 ..
1224 }) => site,
1225 other => panic!("expected chop job, got {other:?}"),
1226 };
1227 assert_ne!(target(a), target(b));
1228 }
1229
1230 // Each tree or rock being worked will add its yield; counting that as material on the way
1231 // keeps the whole colony from felling a forest when only a little more wood is needed.
1232 #[test]
1233 fn work_in_progress_counts_towards_goals() {
1234 let goals = ColonyGoals(HashMap::from([(ItemKind::Wood, 25)]));
1235 assert!(goals.wanted(ItemKind::Wood, 10, 10));
1236 assert!(!goals.wanted(ItemKind::Wood, 10, 20));
1237 assert!(!goals.wanted(ItemKind::Wood, 30, 0));
1238 assert!(!goals.wanted(ItemKind::Gold, 0, 0));
1239 }
1240
1241 #[test]
1242 fn ordered_chop_ignores_the_wood_goal() {
1243 let tree = UVec2::new(8, 5);
1244 let mut app = test_app(map_with_trees(&[tree]));
1245 set_goals(&mut app, &[]);
1246 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1247 app.world_mut().write_message(Order {
1248 colonist,
1249 tile: tree,
1250 });
1251 run_ticks(&mut app, 60 * 15);
1252 assert_eq!(
1253 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
1254 None
1255 );
1256 }
1257
1258 #[test]
1259 fn ordering_a_move_cancels_the_current_job_and_frees_its_tree() {
1260 let tree = UVec2::new(15, 5);
1261 let mut app = test_app(map_with_trees(&[tree]));
1262 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1263 run_ticks(&mut app, 61);
1264 assert!(matches!(
1265 job(&app, colonist),
1266 Some(Job {
1267 task: Task::Work { .. },
1268 ..
1269 })
1270 ));
1271 app.world_mut().write_message(Order {
1272 colonist,
1273 tile: UVec2::new(2, 15),
1274 });
1275 run_ticks(&mut app, 1);
1276 assert_eq!(
1277 job(&app, colonist).map(|j| j.task),
1278 Some(Task::MoveTo(UVec2::new(2, 15)))
1279 );
1280 assert!(
1281 app.world()
1282 .resource::<Reservations>()
1283 .is_free(Target::Site(tree))
1284 );
1285 }
1286
1287 #[test]
1288 fn idle_colonists_haul_loose_items_into_the_stockpile() {
1289 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(17, 15)));
1290 put_wood(&mut app, UVec2::new(5, 5), 20);
1291 spawn_colonist(&mut app, UVec2::new(2, 5));
1292 run_ticks(&mut app, 60 * 15);
1293 assert_eq!(items_at(&mut app), vec![(UVec2::new(15, 15), 20)]);
1294 }
1295
1296 #[test]
1297 fn large_stacks_take_several_trips_and_spill_into_more_stockpile_tiles() {
1298 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(17, 15)));
1299 put_wood(&mut app, UVec2::new(5, 5), STACK_LIMIT + 10);
1300 spawn_colonist(&mut app, UVec2::new(2, 5));
1301 run_ticks(&mut app, 60 * 40);
1302 let stacks = items_at(&mut app);
1303 assert_eq!(stored(&mut app), STACK_LIMIT + 10);
1304 assert!(stacks.len() >= 2);
1305 assert!(stacks.iter().all(|(_, count)| *count <= STACK_LIMIT));
1306 }
1307
1308 #[test]
1309 fn items_already_in_a_stockpile_stay_put() {
1310 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(16, 16)));
1311 put_wood(&mut app, UVec2::new(5, 5), 20);
1312 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1313 run_ticks(&mut app, 60 * 5);
1314 assert_eq!(items_at(&mut app), vec![(UVec2::new(5, 5), 20)]);
1315 assert_eq!(carrying(&app, colonist), None);
1316 }
1317
1318 #[test]
1319 fn colonists_found_a_stockpile_when_items_need_storing() {
1320 let mut app = test_app(map_with_trees(&[]));
1321 put_beds(&mut app, 1);
1322 set_goals(&mut app, &[]);
1323 put_wood(&mut app, UVec2::new(5, 5), 20);
1324 spawn_colonist(&mut app, UVec2::new(2, 5));
1325 run_ticks(&mut app, 60 * 15);
1326 assert_eq!(
1327 stockpile_size(&app),
1328 (NEW_STOCKPILE_SIZE * NEW_STOCKPILE_SIZE) as usize
1329 );
1330 assert_eq!(stored(&mut app), 20);
1331 }
1332
1333 #[test]
1334 fn no_stockpile_is_founded_while_there_is_nothing_to_store() {
1335 let mut app = test_app(map_with_trees(&[]));
1336 set_goals(&mut app, &[]);
1337 spawn_colonist(&mut app, UVec2::new(2, 5));
1338 run_ticks(&mut app, 60 * 5);
1339 assert_eq!(stockpile_size(&app), 0);
1340 }
1341
1342 #[test]
1343 fn two_colonists_never_haul_the_same_stack() {
1344 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(16, 16)));
1345 put_wood(&mut app, UVec2::new(5, 5), 10);
1346 put_wood(&mut app, UVec2::new(5, 6), 10);
1347 let a = spawn_colonist(&mut app, UVec2::new(2, 5));
1348 let b = spawn_colonist(&mut app, UVec2::new(2, 6));
1349 run_ticks(&mut app, 61);
1350 let pickup = |c| match job(&app, c).map(|j| j.task) {
1351 Some(Task::Haul { pickup, .. }) => pickup,
1352 other => panic!("expected haul, got {other:?}"),
1353 };
1354 assert_ne!(pickup(a), pickup(b));
1355 }
1356
1357 // Orders interrupt whatever a colonist is doing, but whatever it is carrying stays in its
1358 // hands; once it is idle again it finishes delivering it instead of dropping it anywhere.
1359 #[test]
1360 fn interrupted_haulers_deliver_their_load_later() {
1361 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(17, 15)));
1362 put_wood(&mut app, UVec2::new(4, 5), 20);
1363 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1364 let mut ticks = 0;
1365 while carrying(&app, colonist).is_none() && ticks < 60 * 10 {
1366 run_ticks(&mut app, 1);
1367 ticks += 1;
1368 }
1369 app.world_mut().write_message(Order {
1370 colonist,
1371 tile: UVec2::new(2, 2),
1372 });
1373 run_ticks(&mut app, 60 * 3);
1374 assert!(carrying(&app, colonist).is_some());
1375 run_ticks(&mut app, 60 * 20);
1376 assert_eq!(carrying(&app, colonist), None);
1377 assert_eq!(stored(&mut app), 20);
1378 }
1379
1380 #[test]
1381 fn right_clicking_loose_items_orders_a_haul() {
1382 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(15, 15)));
1383 set_goals(&mut app, &[(ItemKind::Wood, 1000)]);
1384 put_wood(&mut app, UVec2::new(5, 5), 20);
1385 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1386 app.world_mut().write_message(Order {
1387 colonist,
1388 tile: UVec2::new(5, 5),
1389 });
1390 run_ticks(&mut app, 1);
1391 assert!(matches!(
1392 job(&app, colonist),
1393 Some(Job {
1394 task: Task::Haul { .. },
1395 ordered: true
1396 })
1397 ));
1398 }
1399
1400 fn mining_map() -> WorldMap {
1401 let mut map = WorldMap::filled(UVec2::new(20, 20), Terrain::Grass);
1402 for y in 0..20 {
1403 map.set(UVec2::new(10, y), Terrain::Stone);
1404 }
1405 map.set(UVec2::new(10, 5), Terrain::IronOre);
1406 map
1407 }
1408
1409 fn items_of(app: &mut App, kind: ItemKind) -> u32 {
1410 let world = app.world_mut();
1411 let items: Vec<Item> = world.query::<&Item>().iter(world).copied().collect();
1412 stock(items.iter(), kind)
1413 }
1414
1415 #[test]
1416 fn colonists_mine_rock_the_colony_needs_and_leave_gravel() {
1417 let mut app = test_app(mining_map());
1418 set_goals(&mut app, &[(ItemKind::Stone, 10)]);
1419 spawn_colonist(&mut app, UVec2::new(8, 12));
1420 run_ticks(&mut app, 60 * 12);
1421 assert_eq!(items_of(&mut app, ItemKind::Stone), 10);
1422 assert_eq!(items_of(&mut app, ItemKind::Iron), 0);
1423 let map = app.world().resource::<WorldMap>();
1424 let gravel = map
1425 .positions()
1426 .filter(|p| map.get(p.as_ivec2()) == Some(Terrain::Gravel))
1427 .count();
1428 assert_eq!(gravel, 1);
1429 }
1430
1431 #[test]
1432 fn colonists_walk_past_rock_they_do_not_need() {
1433 let mut app = test_app(mining_map());
1434 set_goals(&mut app, &[(ItemKind::Iron, 10)]);
1435 spawn_colonist(&mut app, UVec2::new(8, 15));
1436 run_ticks(&mut app, 60 * 15);
1437 assert_eq!(items_of(&mut app, ItemKind::Iron), 10);
1438 assert_eq!(items_of(&mut app, ItemKind::Stone), 0);
1439 assert_eq!(
1440 app.world().resource::<WorldMap>().get(IVec2::new(10, 5)),
1441 Some(Terrain::Gravel)
1442 );
1443 }
1444
1445 #[test]
1446 fn right_clicking_rock_orders_mining_regardless_of_goals() {
1447 let mut app = test_app(mining_map());
1448 set_goals(&mut app, &[]);
1449 let colonist = spawn_colonist(&mut app, UVec2::new(8, 12));
1450 app.world_mut().write_message(Order {
1451 colonist,
1452 tile: UVec2::new(10, 12),
1453 });
1454 run_ticks(&mut app, 60 * 10);
1455 assert_eq!(
1456 app.world().resource::<WorldMap>().get(IVec2::new(10, 12)),
1457 Some(Terrain::Gravel)
1458 );
1459 }
1460
1461 #[test]
1462 fn colonists_expand_a_stockpile_that_is_nearly_full() {
1463 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(6, 5)));
1464 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1465 run_ticks(&mut app, 61);
1466 assert!(matches!(
1467 job(&app, colonist).map(|j| j.task),
1468 Some(Task::ExpandStockpile { .. })
1469 ));
1470 run_ticks(&mut app, 60 * 5);
1471 assert_eq!(stockpile_size(&app), 2 + EXPANSION_TILES);
1472 }
1473
1474 #[test]
1475 fn roomy_stockpiles_are_left_alone() {
1476 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(8, 5)));
1477 spawn_colonist(&mut app, UVec2::new(2, 5));
1478 run_ticks(&mut app, 60 * 5);
1479 assert_eq!(stockpile_size(&app), 4);
1480 }
1481
1482 fn set_hour(app: &mut App, hour: u64) {
1483 let ticks = (hour + 24 - 6) % 24 * crate::sim::TICKS_PER_HOUR;
1484 *app.world_mut().resource_mut::<SimTick>() = SimTick(ticks);
1485 }
1486
1487 fn structures(app: &mut App) -> Vec<(UVec2, StructureKind)> {
1488 let world = app.world_mut();
1489 world
1490 .query::<(&TilePos, &Structure)>()
1491 .iter(world)
1492 .map(|(pos, s)| (pos.0, s.kind))
1493 .collect()
1494 }
1495
1496 fn put_campfire(app: &mut App, tile: UVec2) {
1497 app.world_mut().spawn((
1498 Structure {
1499 kind: StructureKind::Campfire,
1500 },
1501 Fuel(StructureKind::Campfire.fuel_ticks().unwrap()),
1502 TilePos(tile),
1503 ));
1504 }
1505
1506 #[test]
1507 fn colonists_light_a_campfire_near_the_stockpile_when_night_falls() {
1508 let mut app = hauling_app((IVec2::new(10, 10), IVec2::new(12, 12)));
1509 put_wood(&mut app, UVec2::new(10, 10), 20);
1510 set_hour(&mut app, 18);
1511 spawn_colonist(&mut app, UVec2::new(2, 5));
1512 run_ticks(&mut app, 60 * 20);
1513 let built = structures(&mut app);
1514 let campfire = built
1515 .iter()
1516 .find(|(_, kind)| *kind == StructureKind::Campfire)
1517 .expect("a campfire");
1518 assert!(campfire.0.as_vec2().distance(Vec2::new(11.0, 11.0)) <= HOME_RADIUS);
1519 assert_eq!(wood_on_map(&mut app), 10);
1520 }
1521
1522 #[test]
1523 fn no_fires_are_built_during_the_day() {
1524 let mut app = hauling_app((IVec2::new(10, 10), IVec2::new(12, 12)));
1525 put_wood(&mut app, UVec2::new(10, 10), 20);
1526 set_hour(&mut app, 10);
1527 spawn_colonist(&mut app, UVec2::new(2, 5));
1528 run_ticks(&mut app, 60 * 10);
1529 assert!(
1530 structures(&mut app)
1531 .iter()
1532 .all(|(_, kind)| kind.light().is_none())
1533 );
1534 }
1535
1536 #[test]
1537 fn without_wood_nothing_can_be_built() {
1538 let mut app = hauling_app((IVec2::new(10, 10), IVec2::new(12, 12)));
1539 set_hour(&mut app, 22);
1540 spawn_colonist(&mut app, UVec2::new(2, 5));
1541 run_ticks(&mut app, 60 * 10);
1542 assert!(
1543 structures(&mut app)
1544 .iter()
1545 .all(|(_, kind)| kind.light().is_none())
1546 );
1547 }
1548
1549 #[test]
1550 fn torches_light_stockpile_tiles_beyond_the_campfire() {
1551 let mut app = hauling_app((IVec2::new(2, 10), IVec2::new(17, 10)));
1552 put_wood(&mut app, UVec2::new(9, 10), 20);
1553 put_campfire(&mut app, UVec2::new(9, 12));
1554 set_hour(&mut app, 22);
1555 spawn_colonist(&mut app, UVec2::new(9, 8));
1556 run_ticks(&mut app, 60 * 15);
1557 assert!(
1558 structures(&mut app)
1559 .iter()
1560 .any(|(_, kind)| *kind == StructureKind::Torch)
1561 );
1562 }
1563
1564 // Light is what makes fires worth building: work in darkness goes at half speed.
1565 #[test]
1566 fn work_is_slower_in_the_dark() {
1567 let tree = UVec2::new(8, 5);
1568 let finish_ticks = |daylight: f32| {
1569 let mut app = test_app(map_with_trees(&[tree]));
1570 let size = app.world().resource::<WorldMap>().size;
1571 app.insert_resource(LightMap::compute(size, daylight, []));
1572 spawn_colonist(&mut app, UVec2::new(7, 5));
1573 let mut ticks = 0;
1574 while app
1575 .world()
1576 .resource::<WorldMap>()
1577 .plant(tree.as_ivec2())
1578 .is_some()
1579 {
1580 run_ticks(&mut app, 1);
1581 ticks += 1;
1582 }
1583 ticks
1584 };
1585 let (lit, dark) = (finish_ticks(1.0), finish_ticks(0.0));
1586 assert!(
1587 dark > lit + WorkKind::Chop.work() / 2 - 10,
1588 "lit {lit}, dark {dark}"
1589 );
1590 }
1591
1592 const NAP_TEST_REST: f32 = 0.25;
1593
1594 fn set_rest(app: &mut App, colonist: Entity, rest: f32) {
1595 app.world_mut().get_mut::<Rest>(colonist).unwrap().0 = rest;
1596 }
1597
1598 fn rest(app: &App, colonist: Entity) -> f32 {
1599 app.world().get::<Rest>(colonist).unwrap().0
1600 }
1601
1602 fn task(app: &App, colonist: Entity) -> Option<Task> {
1603 job(app, colonist).map(|j| j.task)
1604 }
1605
1606 #[test]
1607 fn tired_colonists_nap_and_get_up_when_rested() {
1608 let mut app = test_app(map_with_trees(&[]));
1609 set_goals(&mut app, &[]);
1610 set_hour(&mut app, 10);
1611 let colonist = spawn_colonist(&mut app, UVec2::new(5, 5));
1612 set_rest(&mut app, colonist, NAP_TEST_REST);
1613 run_ticks(&mut app, 61);
1614 assert!(matches!(task(&app, colonist), Some(Task::Sleep { .. })));
1615 let mut ticks = 0;
1616 while matches!(task(&app, colonist), Some(Task::Sleep { .. })) && ticks < 60 * 60 * 10 {
1617 run_ticks(&mut app, 60);
1618 ticks += 60;
1619 }
1620 assert!(!matches!(task(&app, colonist), Some(Task::Sleep { .. })));
1621 assert!(rest(&app, colonist) > 0.95);
1622 }
1623
1624 #[test]
1625 fn colonists_go_to_bed_at_night_and_sleep_until_morning() {
1626 let mut app = test_app(map_with_trees(&[]));
1627 set_goals(&mut app, &[]);
1628 set_hour(&mut app, 22);
1629 let colonist = spawn_colonist(&mut app, UVec2::new(5, 5));
1630 set_rest(&mut app, colonist, 0.8);
1631 run_ticks(&mut app, 61);
1632 assert!(matches!(task(&app, colonist), Some(Task::Sleep { .. })));
1633 run_ticks(&mut app, 3 * crate::sim::TICKS_PER_HOUR as u32);
1634 assert_eq!(rest(&app, colonist), 1.0);
1635 assert!(matches!(task(&app, colonist), Some(Task::Sleep { .. })));
1636 }
1637
1638 #[test]
1639 fn rested_colonists_stay_up_during_the_day() {
1640 let mut app = test_app(map_with_trees(&[]));
1641 set_goals(&mut app, &[]);
1642 set_hour(&mut app, 12);
1643 let colonist = spawn_colonist(&mut app, UVec2::new(5, 5));
1644 set_rest(&mut app, colonist, 0.8);
1645 run_ticks(&mut app, 60 * 5);
1646 assert!(!matches!(task(&app, colonist), Some(Task::Sleep { .. })));
1647 }
1648
1649 #[test]
1650 fn exhausted_colonists_drop_their_work_to_sleep() {
1651 let tree = UVec2::new(15, 5);
1652 let mut app = test_app(map_with_trees(&[tree]));
1653 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1654 run_ticks(&mut app, 61);
1655 assert!(matches!(task(&app, colonist), Some(Task::Work { .. })));
1656 set_rest(&mut app, colonist, EXHAUSTED_REST / 2.0);
1657 run_ticks(&mut app, 30);
1658 assert!(matches!(task(&app, colonist), Some(Task::Sleep { .. })));
1659 assert!(
1660 app.world()
1661 .resource::<Reservations>()
1662 .is_free(Target::Site(tree))
1663 );
1664 }
1665
1666 #[test]
1667 fn exhaustion_does_not_override_orders() {
1668 let tree = UVec2::new(15, 5);
1669 let mut app = test_app(map_with_trees(&[tree]));
1670 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1671 app.world_mut().write_message(Order {
1672 colonist,
1673 tile: tree,
1674 });
1675 run_ticks(&mut app, 2);
1676 set_rest(&mut app, colonist, EXHAUSTED_REST / 2.0);
1677 run_ticks(&mut app, 30);
1678 assert!(matches!(
1679 job(&app, colonist),
1680 Some(Job {
1681 task: Task::Work { .. },
1682 ordered: true
1683 })
1684 ));
1685 }
1686
1687 fn beds(app: &mut App) -> usize {
1688 structures(app)
1689 .iter()
1690 .filter(|(_, kind)| *kind == StructureKind::Bed)
1691 .count()
1692 }
1693
1694 #[test]
1695 fn colonists_build_one_bed_each() {
1696 let mut app = test_app(map_with_trees(&[]));
1697 set_goals(&mut app, &[]);
1698 let map = app.world().resource::<WorldMap>().clone();
1699 app.world_mut().resource_mut::<Zones>().add_stockpile(
1700 &map,
1701 IVec2::new(2, 2),
1702 IVec2::new(5, 5),
1703 );
1704 put_wood(&mut app, UVec2::new(2, 2), 50);
1705 put_wood(&mut app, UVec2::new(3, 2), 50);
1706 spawn_colonist(&mut app, UVec2::new(10, 10));
1707 spawn_colonist(&mut app, UVec2::new(11, 10));
1708 run_ticks(&mut app, 60 * 40);
1709 assert_eq!(beds(&mut app), 2);
1710 assert_eq!(wood_on_map(&mut app), 100 - 2 * StructureKind::Bed.cost().1);
1711 }
1712
1713 // A shelter needs a wall ring with walking space around the beds; beds hugging the stockpile
1714 // would leave stored items where the walls must go and the room could never be planned.
1715 #[test]
1716 fn beds_keep_clear_of_the_stockpile() {
1717 let mut app = test_app(map_with_trees(&[]));
1718 set_goals(&mut app, &[]);
1719 let map = app.world().resource::<WorldMap>().clone();
1720 app.world_mut().resource_mut::<Zones>().add_stockpile(
1721 &map,
1722 IVec2::new(8, 8),
1723 IVec2::new(11, 11),
1724 );
1725 put_wood(&mut app, UVec2::new(8, 8), 50);
1726 spawn_colonist(&mut app, UVec2::new(10, 4));
1727 run_ticks(&mut app, 60 * 20);
1728 let built = structures(&mut app);
1729 let bed = built
1730 .iter()
1731 .find(|(_, kind)| *kind == StructureKind::Bed)
1732 .expect("a bed");
1733 let zones = app.world().resource::<Zones>();
1734 assert!(zones.stockpile_tiles().all(|s| {
1735 (s.as_ivec2() - bed.0.as_ivec2()).abs().max_element() >= BED_STOCKPILE_CLEARANCE
1736 }));
1737 }
1738
1739 #[test]
1740 fn colonists_sleep_in_their_beds() {
1741 let mut app = test_app(map_with_trees(&[]));
1742 set_goals(&mut app, &[]);
1743 put_beds(&mut app, 1);
1744 set_hour(&mut app, 22);
1745 let colonist = spawn_colonist(&mut app, UVec2::new(5, 5));
1746 set_rest(&mut app, colonist, 0.5);
1747 run_ticks(&mut app, 60 * 10);
1748 assert_eq!(
1749 app.world().get::<TilePos>(colonist).unwrap().0,
1750 UVec2::new(19, 19)
1751 );
1752 assert!(matches!(task(&app, colonist), Some(Task::Sleep { .. })));
1753 }
1754
1755 fn put_items(app: &mut App, tile: UVec2, kind: ItemKind, count: u32) {
1756 app.world_mut().spawn((Item { kind, count }, TilePos(tile)));
1757 }
1758
1759 #[test]
1760 fn blueprints_are_built_with_the_right_material() {
1761 let mut app = test_app(map_with_trees(&[]));
1762 set_goals(&mut app, &[]);
1763 put_beds(&mut app, 1);
1764 put_items(&mut app, UVec2::new(2, 2), ItemKind::Stone, 10);
1765 let wall = UVec2::new(8, 8);
1766 app.world_mut()
1767 .resource_mut::<Blueprints>()
1768 .0
1769 .insert(wall, BuildKind::Structure(StructureKind::Wall));
1770 spawn_colonist(&mut app, UVec2::new(5, 5));
1771 run_ticks(&mut app, 60 * 10);
1772 assert!(app.world().resource::<WorldMap>().is_wall(wall.as_ivec2()));
1773 assert!(app.world().resource::<Blueprints>().0.is_empty());
1774 assert_eq!(items_of(&mut app, ItemKind::Stone), 8);
1775 }
1776
1777 #[test]
1778 fn colonists_build_a_roofed_shelter_around_their_beds() {
1779 let mut app = test_app(map_with_trees(&[]));
1780 app.add_systems(Update, crate::building::plan_shelter.before(choose_jobs));
1781 set_goals(&mut app, &[]);
1782 for x in [10, 11] {
1783 app.world_mut().spawn((
1784 Structure {
1785 kind: StructureKind::Bed,
1786 },
1787 TilePos(UVec2::new(x, 10)),
1788 ));
1789 }
1790 put_items(&mut app, UVec2::new(2, 2), ItemKind::Stone, 50);
1791 put_items(&mut app, UVec2::new(3, 2), ItemKind::Wood, 50);
1792 spawn_colonist(&mut app, UVec2::new(4, 4));
1793 spawn_colonist(&mut app, UVec2::new(5, 4));
1794 run_ticks(&mut app, 60 * 150);
1795 let map = app.world().resource::<WorldMap>();
1796 assert!(map.is_roofed(IVec2::new(10, 10)) && map.is_roofed(IVec2::new(11, 10)));
1797 let walls = map
1798 .positions()
1799 .filter(|p| map.is_wall(p.as_ivec2()))
1800 .count();
1801 assert_eq!(walls, 17);
1802 assert!(
1803 structures(&mut app)
1804 .iter()
1805 .any(|(_, kind)| *kind == StructureKind::Door)
1806 );
1807 }
1808
1809 #[test]
1810 fn colonists_chop_from_a_neighbouring_tile() {
1811 let tree = UVec2::new(8, 5);
1812 let mut app = test_app(map_with_trees(&[tree]));
1813 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1814 run_ticks(&mut app, 60 * 5);
1815 let tile = app.world().get::<TilePos>(colonist).unwrap().0;
1816 assert!(is_adjacent(tile.as_ivec2(), tree.as_ivec2()));
1817 assert_eq!(
1818 app.world().get::<SimPos>(colonist).unwrap().0,
1819 WorldMap::tile_center(tile)
1820 );
1821 }
1822 }