src/jobs.rs 47.3 K · 1437 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 light::{
16 LIT_BRIGHTNESS, LightMap, Structure, StructureAssets, StructureKind, brightness, dark_soon,
17 light_from, spawn_structure,
18 },
19 pathfinding::{find_path, find_path_adjacent, is_adjacent, nearest_tile},
20 rng::SimRng,
21 sim::{SimSystems, SimTick},
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 const LIT_WORK_RATE: u32 = 2;
52 const DARK_WORK_RATE: u32 = 1;
53 pub const EXPANSION_TILES: usize = 8;
54 pub const MIN_EMPTY_STOCKPILE_TILES: usize = 3;
55 const SEARCH_TILES: usize = 15000;
56 const WANDER_RADIUS: i32 = 8;
57 const IDLE_SECS: Range<f32> = 1.0..4.0;
58 const IDLE_AFTER_ORDER_SECS: f32 = 10.0;
59 const WORK_PAUSE_SECS: Range<f32> = 0.2..0.8;
60 const NEIGHBORS: [IVec2; 8] = [
61 IVec2::new(1, 0),
62 IVec2::new(-1, 0),
63 IVec2::new(0, 1),
64 IVec2::new(0, -1),
65 IVec2::new(1, 1),
66 IVec2::new(1, -1),
67 IVec2::new(-1, 1),
68 IVec2::new(-1, -1),
69 ];
70
71 #[derive(Component, Default, Debug, Clone, PartialEq)]
72 pub struct CurrentJob(pub Option<Job>);
73
74 #[derive(Debug, Clone, Copy, PartialEq)]
75 pub struct Job {
76 pub task: Task,
77 pub ordered: bool,
78 }
79
80 #[derive(Debug, Clone, Copy, PartialEq)]
81 pub enum Task {
82 MoveTo(UVec2),
83 Work {
84 site: UVec2,
85 kind: WorkKind,
86 progress: u32,
87 },
88 Haul {
89 pickup: Option<UVec2>,
90 to: UVec2,
91 },
92 ExpandStockpile {
93 site: UVec2,
94 progress: u32,
95 },
96 Build {
97 site: UVec2,
98 kind: StructureKind,
99 pickup: Option<UVec2>,
100 progress: u32,
101 },
102 }
103
104 pub fn build_work(kind: StructureKind) -> u32 {
105 match kind {
106 StructureKind::Campfire => 360,
107 StructureKind::Torch => 120,
108 }
109 }
110
111 pub fn work_rate(light: &LightMap, tile: UVec2) -> u32 {
112 if light.is_lit(tile) {
113 LIT_WORK_RATE
114 } else {
115 DARK_WORK_RATE
116 }
117 }
118
119 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
120 pub enum WorkKind {
121 Chop,
122 Mine,
123 }
124
125 impl WorkKind {
126 pub fn work(self) -> u32 {
127 match self {
128 WorkKind::Chop => 480,
129 WorkKind::Mine => 720,
130 }
131 }
132
133 fn complete(self, map: &mut WorldMap, site: UVec2) {
134 match self {
135 WorkKind::Chop => map.set_plant(site, None),
136 WorkKind::Mine => map.set(site, Terrain::Gravel),
137 }
138 }
139 }
140
141 pub struct SiteWork {
142 pub kind: WorkKind,
143 pub item: ItemKind,
144 pub count: u32,
145 }
146
147 pub fn site_work(map: &WorldMap, site: UVec2) -> Option<SiteWork> {
148 let p = site.as_ivec2();
149 if map.plant(p) == Some(Plant::Tree) {
150 return Some(SiteWork {
151 kind: WorkKind::Chop,
152 item: ItemKind::Wood,
153 count: 10,
154 });
155 }
156 let (item, count) = match map.get(p)? {
157 Terrain::Stone => (ItemKind::Stone, 10),
158 Terrain::IronOre => (ItemKind::Iron, 10),
159 Terrain::GoldOre => (ItemKind::Gold, 5),
160 _ => return None,
161 };
162 Some(SiteWork {
163 kind: WorkKind::Mine,
164 item,
165 count,
166 })
167 }
168
169 #[derive(Component, Debug)]
170 pub struct IdleTimer(Timer);
171
172 impl Default for IdleTimer {
173 fn default() -> Self {
174 Self(Timer::from_seconds(IDLE_SECS.start, TimerMode::Once))
175 }
176 }
177
178 impl IdleTimer {
179 fn restart(&mut self, secs: f32) {
180 self.0.set_duration(Duration::from_secs_f32(secs));
181 self.0.reset();
182 }
183 }
184
185 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
186 pub enum Target {
187 Site(UVec2),
188 Pickup(UVec2),
189 Storage(UVec2),
190 StockpileExpansion,
191 }
192
193 #[derive(Resource, Default, Debug)]
194 pub struct Reservations(HashMap<Target, Entity>);
195
196 impl Reservations {
197 pub fn reserve(&mut self, target: Target, by: Entity) {
198 self.0.insert(target, by);
199 }
200
201 pub fn holder(&self, target: Target) -> Option<Entity> {
202 self.0.get(&target).copied()
203 }
204
205 pub fn is_free(&self, target: Target) -> bool {
206 self.holder(target).is_none()
207 }
208
209 pub fn release(&mut self, target: Target) {
210 self.0.remove(&target);
211 }
212
213 pub fn release_all(&mut self, by: Entity) {
214 self.0.retain(|_, holder| *holder != by);
215 }
216 }
217
218 #[derive(Resource, Debug, Clone)]
219 pub struct ColonyGoals(pub HashMap<ItemKind, u32>);
220
221 impl Default for ColonyGoals {
222 fn default() -> Self {
223 Self(HashMap::from([
224 (ItemKind::Wood, 50),
225 (ItemKind::Stone, 40),
226 (ItemKind::Iron, 20),
227 (ItemKind::Gold, 10),
228 ]))
229 }
230 }
231
232 impl ColonyGoals {
233 pub fn goal(&self, kind: ItemKind) -> u32 {
234 self.0.get(&kind).copied().unwrap_or(0)
235 }
236
237 pub fn wanted(&self, kind: ItemKind, in_stock: u32, on_the_way: u32) -> bool {
238 in_stock + on_the_way < self.goal(kind)
239 }
240 }
241
242 #[derive(Message, Debug, Clone, Copy)]
243 pub struct Order {
244 pub colonist: Entity,
245 pub tile: UVec2,
246 }
247
248 fn clear_reservations(mut reservations: ResMut<Reservations>) {
249 reservations.0.clear();
250 }
251
252 fn handle_orders(
253 mut orders: MessageReader<Order>,
254 map: Res<WorldMap>,
255 zones: Res<Zones>,
256 items: Query<(&Item, &TilePos)>,
257 mut reservations: ResMut<Reservations>,
258 mut colonists: Query<(&TilePos, &mut Path, &mut CurrentJob)>,
259 ) {
260 for order in orders.read() {
261 let Ok((tile, mut path, mut job)) = colonists.get_mut(order.colonist) else {
262 continue;
263 };
264 let loose_item = items
265 .iter()
266 .find(|(_, pos)| pos.0 == order.tile && !zones.is_stockpile(pos.0));
267 let task = if let Some(work) = site_work(&map, order.tile) {
268 Some(Task::Work {
269 site: order.tile,
270 kind: work.kind,
271 progress: 0,
272 })
273 } else if let Some((item, _)) = loose_item {
274 find_storage(&map, &zones, &reservations, &items, order.tile, item.kind).map(|to| {
275 Task::Haul {
276 pickup: Some(order.tile),
277 to,
278 }
279 })
280 } else {
281 None
282 };
283 if let Some(task) = task {
284 reservations.release_all(order.colonist);
285 reserve_task(&mut reservations, task, order.colonist);
286 path.0.truncate(1);
287 job.0 = Some(Job {
288 task,
289 ordered: true,
290 });
291 } else if let Some(new_path) = repath(&map, tile.0, &path.0, order.tile) {
292 reservations.release_all(order.colonist);
293 path.0 = new_path;
294 job.0 = Some(Job {
295 task: Task::MoveTo(order.tile),
296 ordered: true,
297 });
298 }
299 }
300 }
301
302 fn reserve_task(reservations: &mut Reservations, task: Task, by: Entity) {
303 match task {
304 Task::MoveTo(_) => {}
305 Task::Work { site, .. } => reservations.reserve(Target::Site(site), by),
306 Task::Haul { pickup, to } => {
307 if let Some(pickup) = pickup {
308 reservations.reserve(Target::Pickup(pickup), by);
309 }
310 reservations.reserve(Target::Storage(to), by);
311 }
312 Task::ExpandStockpile { .. } => reservations.reserve(Target::StockpileExpansion, by),
313 Task::Build { site, pickup, .. } => {
314 reservations.reserve(Target::Site(site), by);
315 if let Some(pickup) = pickup {
316 reservations.reserve(Target::Pickup(pickup), by);
317 }
318 }
319 }
320 }
321
322 pub fn find_work(
323 map: &WorldMap,
324 reservations: &Reservations,
325 from: UVec2,
326 wanted: impl Fn(ItemKind) -> bool,
327 ) -> Option<Task> {
328 let mut found = None;
329 nearest_tile(map, from, SEARCH_TILES, |stand| {
330 found = NEIGHBORS.iter().find_map(|&d| {
331 let site = stand.as_ivec2() + d;
332 if site.x < 0 || site.y < 0 {
333 return None;
334 }
335 let site = site.as_uvec2();
336 let work = site_work(map, site)?;
337 (wanted(work.item) && reservations.is_free(Target::Site(site))).then_some(Task::Work {
338 site,
339 kind: work.kind,
340 progress: 0,
341 })
342 });
343 found.is_some()
344 })?;
345 found
346 }
347
348 pub fn find_storage<'a>(
349 map: &WorldMap,
350 zones: &Zones,
351 reservations: &Reservations,
352 items: impl IntoIterator<Item = (&'a Item, &'a TilePos)> + Clone,
353 from: UVec2,
354 kind: ItemKind,
355 ) -> Option<UVec2> {
356 nearest_tile(map, from, SEARCH_TILES, |p| {
357 zones.is_stockpile(p)
358 && reservations.is_free(Target::Storage(p))
359 && room_for(items.clone().into_iter(), p, kind) > 0
360 })
361 }
362
363 pub fn find_haul(
364 map: &WorldMap,
365 zones: &Zones,
366 reservations: &Reservations,
367 items: &[(Item, TilePos)],
368 from: UVec2,
369 ) -> Option<Task> {
370 let loose: HashSet<UVec2> = items
371 .iter()
372 .map(|(_, pos)| pos.0)
373 .filter(|&p| !zones.is_stockpile(p) && reservations.is_free(Target::Pickup(p)))
374 .collect();
375 if loose.is_empty() {
376 return None;
377 }
378 let pickup = nearest_tile(map, from, SEARCH_TILES, |p| loose.contains(&p))?;
379 let (item, _) = items.iter().find(|(_, pos)| pos.0 == pickup)?;
380 let refs = items.iter().map(|(i, p)| (i, p));
381 let to = find_storage(map, zones, reservations, refs, pickup, item.kind)?;
382 Some(Task::Haul {
383 pickup: Some(pickup),
384 to,
385 })
386 }
387
388 pub fn stockpile_too_full(zones: &Zones, items: &[(Item, TilePos)]) -> bool {
389 let occupied: HashSet<UVec2> = items.iter().map(|(_, pos)| pos.0).collect();
390 zones.has_stockpile() && zones.empty_stockpile_tiles(&occupied) < MIN_EMPTY_STOCKPILE_TILES
391 }
392
393 pub fn find_expansion(
394 map: &WorldMap,
395 zones: &Zones,
396 reservations: &Reservations,
397 items: &[(Item, TilePos)],
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, 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 LightingContext<'a> {
424 pub map: &'a WorldMap,
425 pub zones: &'a Zones,
426 pub reservations: &'a Reservations,
427 pub items: &'a [(Item, TilePos)],
428 pub fires: &'a [(UVec2, StructureKind, u32)],
429 pub planned: &'a [(UVec2, StructureKind)],
430 }
431
432 impl LightingContext<'_> {
433 fn buildable(&self, tile: UVec2) -> bool {
434 can_zone(self.map, tile.as_ivec2())
435 && !self.zones.is_stockpile(tile)
436 && self.map.plant(tile.as_ivec2()).is_none()
437 && !self.fires.iter().any(|(pos, ..)| *pos == tile)
438 && !self.items.iter().any(|(_, pos)| pos.0 == tile)
439 && self.reservations.is_free(Target::Site(tile))
440 }
441
442 fn home(&self, fallback: UVec2) -> UVec2 {
443 let tiles: Vec<UVec2> = self.zones.stockpile_tiles().collect();
444 if tiles.is_empty() {
445 return fallback;
446 }
447 let centroid = tiles.iter().map(|t| t.as_vec2()).sum::<Vec2>() / tiles.len() as f32;
448 *tiles
449 .iter()
450 .min_by(|a, b| {
451 a.as_vec2()
452 .distance_squared(centroid)
453 .total_cmp(&b.as_vec2().distance_squared(centroid))
454 .then((a.y, a.x).cmp(&(b.y, b.x)))
455 })
456 .unwrap()
457 }
458
459 fn lights(&self) -> impl Iterator<Item = (UVec2, StructureKind)> + Clone + '_ {
460 self.fires
461 .iter()
462 .map(|&(pos, kind, _)| (pos, kind))
463 .chain(self.planned.iter().copied())
464 }
465
466 fn campfire_needed(&self, home: UVec2) -> bool {
467 let burning = self.fires.iter().any(|&(pos, kind, fuel)| {
468 kind == StructureKind::Campfire
469 && fuel >= CAMPFIRE_MIN_FUEL
470 && pos.as_vec2().distance(home.as_vec2()) <= HOME_RADIUS
471 });
472 let planned = self
473 .planned
474 .iter()
475 .any(|(_, kind)| *kind == StructureKind::Campfire);
476 !burning && !planned
477 }
478
479 fn darkest_stockpile_tile(&self, home: UVec2) -> Option<UVec2> {
480 self.zones
481 .stockpile_tiles()
482 .filter(|&t| brightness(light_from(t, self.lights())) < LIT_BRIGHTNESS)
483 .min_by(|a, b| {
484 a.as_vec2()
485 .distance_squared(home.as_vec2())
486 .total_cmp(&b.as_vec2().distance_squared(home.as_vec2()))
487 .then((a.y, a.x).cmp(&(b.y, b.x)))
488 })
489 }
490
491 fn site_near(&self, target: UVec2, max_distance: f32) -> Option<UVec2> {
492 nearest_tile(self.map, target, SEARCH_TILES, |p| self.buildable(p))
493 .filter(|site| site.as_vec2().distance(target.as_vec2()) <= max_distance)
494 }
495
496 fn wood_source(&self, from: UVec2, amount: u32) -> Option<UVec2> {
497 nearest_tile(self.map, from, SEARCH_TILES, |p| {
498 self.reservations.is_free(Target::Pickup(p))
499 && self.items.iter().any(|(item, pos)| {
500 pos.0 == p && item.kind == ItemKind::Wood && item.count >= amount
501 })
502 })
503 }
504 }
505
506 pub fn find_lighting(ctx: &LightingContext, from: UVec2) -> Option<Task> {
507 let home = ctx.home(from);
508 let (kind, site) = if ctx.campfire_needed(home) {
509 (StructureKind::Campfire, ctx.site_near(home, HOME_RADIUS)?)
510 } else {
511 let dark = ctx.darkest_stockpile_tile(home)?;
512 let reach = StructureKind::Torch.radius() * 0.6;
513 (StructureKind::Torch, ctx.site_near(dark, reach)?)
514 };
515 let pickup = ctx.wood_source(from, kind.wood_cost())?;
516 Some(Task::Build {
517 site,
518 kind,
519 pickup: Some(pickup),
520 progress: 0,
521 })
522 }
523
524 fn on_the_way(map: &WorldMap, jobs: impl Iterator<Item = Option<Job>>) -> HashMap<ItemKind, u32> {
525 let mut totals = HashMap::new();
526 for job in jobs.flatten() {
527 if let Task::Work { site, .. } = job.task
528 && let Some(work) = site_work(map, site)
529 {
530 *totals.entry(work.item).or_insert(0) += work.count;
531 }
532 }
533 totals
534 }
535
536 #[allow(clippy::too_many_arguments)]
537 fn choose_jobs(
538 mut commands: Commands,
539 time: Res<Time>,
540 map: Res<WorldMap>,
541 zones: Res<Zones>,
542 goals: Res<ColonyGoals>,
543 item_assets: Res<ItemAssets>,
544 tick: Res<SimTick>,
545 mut rng: ResMut<SimRng>,
546 mut reservations: ResMut<Reservations>,
547 mut items: ItemQuery,
548 structures: Query<(&TilePos, &Structure), Without<Colonist>>,
549 mut colonists: Query<
550 (
551 Entity,
552 &TilePos,
553 &mut Path,
554 &mut CurrentJob,
555 &mut IdleTimer,
556 &mut Carrying,
557 ),
558 With<Colonist>,
559 >,
560 ) {
561 let fires: Vec<(UVec2, StructureKind, u32)> = structures
562 .iter()
563 .map(|(pos, s)| (pos.0, s.kind, s.fuel))
564 .collect();
565 let mut planned: Vec<(UVec2, StructureKind)> = colonists
566 .iter()
567 .filter_map(|c| match c.3.0?.task {
568 Task::Build { site, kind, .. } => Some((site, kind)),
569 _ => None,
570 })
571 .collect();
572 let dark = dark_soon(*tick);
573 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.5.0).collect();
574 let stocks: HashMap<ItemKind, u32> = ItemKind::ALL
575 .iter()
576 .map(|&kind| {
577 let all = items.iter().map(|(_, item, _)| item).chain(carried.iter());
578 (kind, stock(all, kind))
579 })
580 .collect();
581 let mut pending = on_the_way(&map, colonists.iter().map(|c| c.3.0));
582 for (entity, tile, mut path, mut job, mut idle, mut carrying) in &mut colonists {
583 if job.0.is_some() || !path.0.is_empty() || !idle.0.tick(time.delta()).is_finished() {
584 continue;
585 }
586 let snapshot: Vec<(Item, TilePos)> =
587 items.iter().map(|(_, item, pos)| (*item, *pos)).collect();
588 let refs = snapshot.iter().map(|(i, p)| (i, p));
589 let wanted = |kind: ItemKind| {
590 goals.wanted(
591 kind,
592 stocks[&kind],
593 pending.get(&kind).copied().unwrap_or(0),
594 )
595 };
596 let task = if let Some(load) = carrying.0 {
597 let storage = find_storage(&map, &zones, &reservations, refs, tile.0, load.kind);
598 if storage.is_none() {
599 drop_items(
600 &mut commands,
601 &mut items,
602 &item_assets,
603 tile.0,
604 load.kind,
605 load.count,
606 );
607 carrying.0 = None;
608 }
609 storage.map(|to| Task::Haul { pickup: None, to })
610 } else {
611 let lighting = LightingContext {
612 map: &map,
613 zones: &zones,
614 reservations: &reservations,
615 items: &snapshot,
616 fires: &fires,
617 planned: &planned,
618 };
619 find_expansion(&map, &zones, &reservations, &snapshot)
620 .or_else(|| dark.then(|| find_lighting(&lighting, tile.0)).flatten())
621 .or_else(|| find_work(&map, &reservations, tile.0, wanted))
622 .or_else(|| find_haul(&map, &zones, &reservations, &snapshot, tile.0))
623 };
624 if let Some(task) = task {
625 if let Task::Work { site, .. } = task
626 && let Some(work) = site_work(&map, site)
627 {
628 *pending.entry(work.item).or_insert(0) += work.count;
629 }
630 if let Task::Build { site, kind, .. } = task {
631 planned.push((site, kind));
632 }
633 reserve_task(&mut reservations, task, entity);
634 job.0 = Some(Job {
635 task,
636 ordered: false,
637 });
638 continue;
639 }
640 let goal = tile.0.as_ivec2()
641 + IVec2::new(
642 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
643 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
644 );
645 if map.in_bounds(goal)
646 && let Some(wander_path) = find_path(&map, tile.0, goal.as_uvec2())
647 {
648 path.0 = wander_path.into();
649 idle.restart(rng.range_f32(IDLE_SECS));
650 }
651 }
652 }
653
654 enum Step {
655 Continue,
656 Done,
657 }
658
659 fn walk_to(map: &WorldMap, from: UVec2, to: UVec2, path: &mut Path) -> Step {
660 match find_path(map, from, to) {
661 Some(p) if !p.is_empty() => {
662 path.0 = p.into();
663 Step::Continue
664 }
665 _ => Step::Done,
666 }
667 }
668
669 #[allow(clippy::too_many_arguments)]
670 fn run_jobs(
671 mut commands: Commands,
672 mut map: ResMut<WorldMap>,
673 mut zones: ResMut<Zones>,
674 mut reservations: ResMut<Reservations>,
675 mut rng: ResMut<SimRng>,
676 item_assets: Res<ItemAssets>,
677 structure_assets: Res<StructureAssets>,
678 light: Res<LightMap>,
679 mut items: ItemQuery,
680 structures: Query<&TilePos, (With<Structure>, Without<Colonist>)>,
681 mut changed: MessageWriter<TileChanged>,
682 mut colonists: Query<
683 (
684 Entity,
685 &TilePos,
686 &mut Path,
687 &mut CurrentJob,
688 &mut IdleTimer,
689 &mut Carrying,
690 ),
691 With<Colonist>,
692 >,
693 ) {
694 for (entity, tile, mut path, mut current, mut idle, mut carrying) in &mut colonists {
695 let Some(mut job) = current.0 else {
696 continue;
697 };
698 if !path.0.is_empty() {
699 continue;
700 }
701 let step = match &mut job.task {
702 Task::MoveTo(_) => Step::Done,
703 Task::Work {
704 site,
705 kind,
706 progress,
707 } => {
708 let (site, kind) = (*site, *kind);
709 let work = site_work(&map, site).filter(|w| w.kind == kind);
710 let ours = reservations.holder(Target::Site(site)) == Some(entity);
711 match work {
712 Some(work) if ours => {
713 if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
714 match find_path_adjacent(&map, tile.0, site) {
715 Some(p) if !p.is_empty() => {
716 path.0 = p.into();
717 Step::Continue
718 }
719 _ => Step::Done,
720 }
721 } else {
722 *progress += work_rate(&light, tile.0);
723 if *progress < kind.work() {
724 Step::Continue
725 } else {
726 kind.complete(&mut map, site);
727 changed.write(TileChanged(site));
728 drop_items(
729 &mut commands,
730 &mut items,
731 &item_assets,
732 site,
733 work.item,
734 work.count,
735 );
736 Step::Done
737 }
738 }
739 }
740 _ => Step::Done,
741 }
742 }
743 Task::ExpandStockpile { site, progress } => {
744 if tile.0 != *site {
745 walk_to(&map, tile.0, *site, &mut path)
746 } else {
747 *progress += work_rate(&light, tile.0);
748 if *progress >= EXPAND_WORK {
749 if zones.has_stockpile() {
750 let tiles = plan_expansion(&map, &zones, EXPANSION_TILES);
751 zones.add_tiles(&map, tiles);
752 } else {
753 zones.add_tiles(&map, new_stockpile_tiles(*site));
754 }
755 Step::Done
756 } else {
757 Step::Continue
758 }
759 }
760 }
761 Task::Build {
762 site,
763 kind,
764 pickup,
765 progress,
766 } => {
767 let (site, kind) = (*site, *kind);
768 let ours = reservations.holder(Target::Site(site)) == Some(entity);
769 let blocked = map.plant(site.as_ivec2()).is_some()
770 || structures.iter().any(|pos| pos.0 == site);
771 let cost = kind.wood_cost();
772 if !ours || blocked {
773 Step::Done
774 } else if let Some(from) = *pickup {
775 if reservations.holder(Target::Pickup(from)) != Some(entity) {
776 Step::Done
777 } else if tile.0 != from {
778 walk_to(&map, tile.0, from, &mut path)
779 } else {
780 let load = take_items(&mut commands, &mut items, from, cost)
781 .filter(|load| load.kind == ItemKind::Wood && load.count > 0);
782 carrying.0 = load;
783 match load {
784 Some(load) if load.count >= cost => {
785 reservations.release(Target::Pickup(from));
786 *pickup = None;
787 Step::Continue
788 }
789 _ => Step::Done,
790 }
791 }
792 } else if !carrying
793 .0
794 .is_some_and(|load| load.kind == ItemKind::Wood && load.count >= cost)
795 {
796 Step::Done
797 } else if !is_adjacent(tile.0.as_ivec2(), site.as_ivec2()) {
798 match find_path_adjacent(&map, tile.0, site) {
799 Some(p) if !p.is_empty() => {
800 path.0 = p.into();
801 Step::Continue
802 }
803 _ => Step::Done,
804 }
805 } else {
806 *progress += work_rate(&light, tile.0);
807 if *progress < build_work(kind) {
808 Step::Continue
809 } else {
810 carrying.0 = carrying.0.and_then(|load| {
811 (load.count > cost).then_some(Item {
812 count: load.count - cost,
813 ..load
814 })
815 });
816 spawn_structure(&mut commands, &structure_assets, site, kind);
817 Step::Done
818 }
819 }
820 }
821 Task::Haul { pickup, to } => {
822 let to = *to;
823 let destination_valid = zones.is_stockpile(to)
824 && reservations.holder(Target::Storage(to)) == Some(entity);
825 if !destination_valid {
826 Step::Done
827 } else if let Some(from) = *pickup {
828 if reservations.holder(Target::Pickup(from)) != Some(entity) {
829 Step::Done
830 } else if tile.0 != from {
831 walk_to(&map, tile.0, from, &mut path)
832 } else {
833 let kind = items
834 .iter()
835 .find(|(_, _, pos)| pos.0 == from)
836 .map(|(_, item, _)| item.kind);
837 let room = kind.map_or(0, |kind| {
838 room_for(items.iter().map(|(_, i, p)| (i, p)), to, kind)
839 });
840 match take_items(&mut commands, &mut items, from, CARRY_CAPACITY.min(room))
841 .filter(|load| load.count > 0)
842 {
843 Some(load) => {
844 carrying.0 = Some(load);
845 reservations.release(Target::Pickup(from));
846 *pickup = None;
847 Step::Continue
848 }
849 None => Step::Done,
850 }
851 }
852 } else if let Some(load) = carrying.0 {
853 if tile.0 != to {
854 walk_to(&map, tile.0, to, &mut path)
855 } else {
856 let room = room_for(items.iter().map(|(_, i, p)| (i, p)), to, load.kind);
857 let dropped = load.count.min(room);
858 if dropped > 0 {
859 drop_items(
860 &mut commands,
861 &mut items,
862 &item_assets,
863 to,
864 load.kind,
865 dropped,
866 );
867 }
868 carrying.0 = (load.count > dropped).then_some(Item {
869 count: load.count - dropped,
870 ..load
871 });
872 Step::Done
873 }
874 } else {
875 Step::Done
876 }
877 }
878 };
879 match step {
880 Step::Continue => current.0 = Some(job),
881 Step::Done => {
882 reservations.release_all(entity);
883 current.0 = None;
884 let ordered_move = matches!(
885 job,
886 Job {
887 task: Task::MoveTo(_),
888 ordered: true
889 }
890 );
891 idle.restart(if ordered_move {
892 IDLE_AFTER_ORDER_SECS
893 } else {
894 rng.range_f32(WORK_PAUSE_SECS)
895 });
896 }
897 }
898 }
899 }
900
901 #[cfg(test)]
902 mod tests {
903 use super::*;
904 use crate::{
905 colonist::follow_path,
906 items::STACK_LIMIT,
907 sim::{SimPos, sim_pos},
908 world::Terrain,
909 zones::NEW_STOCKPILE_SIZE,
910 };
911
912 const TICK: Duration = Duration::from_nanos(1_000_000_000 / 60);
913
914 fn test_app(map: WorldMap) -> App {
915 let mut app = App::new();
916 app.insert_resource(map)
917 .insert_resource(SimRng::new(1))
918 .init_resource::<Time>()
919 .init_resource::<Reservations>()
920 .init_resource::<ColonyGoals>()
921 .init_resource::<ItemAssets>()
922 .init_resource::<StructureAssets>()
923 .init_resource::<LightMap>()
924 .init_resource::<SimTick>()
925 .init_resource::<Zones>()
926 .add_message::<Order>()
927 .add_message::<TileChanged>()
928 .add_systems(
929 Update,
930 (handle_orders, choose_jobs, run_jobs, follow_path).chain(),
931 );
932 app
933 }
934
935 fn spawn_colonist(app: &mut App, tile: UVec2) -> Entity {
936 app.world_mut()
937 .spawn((
938 Colonist {
939 name: "Test".into(),
940 },
941 TilePos(tile),
942 sim_pos(WorldMap::tile_center(tile)),
943 ))
944 .id()
945 }
946
947 fn run_ticks(app: &mut App, ticks: u32) {
948 for _ in 0..ticks {
949 app.world_mut().resource_mut::<Time>().advance_by(TICK);
950 app.update();
951 }
952 }
953
954 fn map_with_trees(trees: &[UVec2]) -> WorldMap {
955 let mut map = WorldMap::filled(UVec2::new(20, 20), Terrain::Grass);
956 for &t in trees {
957 map.set_plant(t, Some(Plant::Tree));
958 }
959 map
960 }
961
962 fn wood_on_map(app: &mut App) -> u32 {
963 let world = app.world_mut();
964 let items: Vec<Item> = world.query::<&Item>().iter(world).copied().collect();
965 stock(items.iter(), ItemKind::Wood)
966 }
967
968 fn items_at(app: &mut App) -> Vec<(UVec2, u32)> {
969 let world = app.world_mut();
970 let mut items: Vec<(UVec2, u32)> = world
971 .query::<(&Item, &TilePos)>()
972 .iter(world)
973 .map(|(item, pos)| (pos.0, item.count))
974 .collect();
975 items.sort_by_key(|(p, _)| (p.y, p.x));
976 items
977 }
978
979 fn put_wood(app: &mut App, tile: UVec2, count: u32) {
980 app.world_mut().spawn((
981 Item {
982 kind: ItemKind::Wood,
983 count,
984 },
985 TilePos(tile),
986 ));
987 }
988
989 fn set_goals(app: &mut App, goals: &[(ItemKind, u32)]) {
990 *app.world_mut().resource_mut::<ColonyGoals>() =
991 ColonyGoals(goals.iter().copied().collect());
992 }
993
994 fn stockpile_size(app: &App) -> usize {
995 let map = app.world().resource::<WorldMap>();
996 let zones = app.world().resource::<Zones>();
997 map.positions().filter(|&p| zones.is_stockpile(p)).count()
998 }
999
1000 fn stored(app: &mut App) -> u32 {
1001 let zones = app.world().resource::<Zones>().clone();
1002 items_at(app)
1003 .iter()
1004 .filter(|(p, _)| zones.is_stockpile(*p))
1005 .map(|(_, c)| c)
1006 .sum()
1007 }
1008
1009 fn hauling_app(stockpile: (IVec2, IVec2)) -> App {
1010 let mut app = test_app(map_with_trees(&[]));
1011 set_goals(&mut app, &[]);
1012 let map = app.world().resource::<WorldMap>().clone();
1013 app.world_mut()
1014 .resource_mut::<Zones>()
1015 .add_stockpile(&map, stockpile.0, stockpile.1);
1016 app
1017 }
1018
1019 fn carrying(app: &App, colonist: Entity) -> Option<Item> {
1020 app.world().get::<Carrying>(colonist).unwrap().0
1021 }
1022
1023 fn job(app: &App, colonist: Entity) -> Option<Job> {
1024 app.world().get::<CurrentJob>(colonist).unwrap().0
1025 }
1026
1027 #[test]
1028 fn idle_colonists_cut_trees_when_the_colony_needs_wood() {
1029 let tree = UVec2::new(8, 5);
1030 let mut app = test_app(map_with_trees(&[tree]));
1031 spawn_colonist(&mut app, UVec2::new(2, 5));
1032 run_ticks(&mut app, 60 * 15);
1033 assert_eq!(
1034 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
1035 None
1036 );
1037 assert_eq!(wood_on_map(&mut app), 10);
1038 assert!(app.world().resource::<Reservations>().0.is_empty());
1039 }
1040
1041 #[test]
1042 fn colonists_leave_trees_alone_when_there_is_enough_wood() {
1043 let tree = UVec2::new(8, 5);
1044 let mut app = test_app(map_with_trees(&[tree]));
1045 set_goals(&mut app, &[]);
1046 spawn_colonist(&mut app, UVec2::new(2, 5));
1047 run_ticks(&mut app, 60 * 15);
1048 assert_eq!(
1049 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
1050 Some(Plant::Tree)
1051 );
1052 }
1053
1054 #[test]
1055 fn colonists_never_pick_the_same_tree() {
1056 let trees = [UVec2::new(10, 10), UVec2::new(10, 11)];
1057 let mut app = test_app(map_with_trees(&trees));
1058 let a = spawn_colonist(&mut app, UVec2::new(5, 10));
1059 let b = spawn_colonist(&mut app, UVec2::new(5, 11));
1060 run_ticks(&mut app, 61);
1061 let target = |c| match job(&app, c) {
1062 Some(Job {
1063 task: Task::Work { site, .. },
1064 ..
1065 }) => site,
1066 other => panic!("expected chop job, got {other:?}"),
1067 };
1068 assert_ne!(target(a), target(b));
1069 }
1070
1071 // Each tree or rock being worked will add its yield; counting that as material on the way
1072 // keeps the whole colony from felling a forest when only a little more wood is needed.
1073 #[test]
1074 fn work_in_progress_counts_towards_goals() {
1075 let goals = ColonyGoals(HashMap::from([(ItemKind::Wood, 25)]));
1076 assert!(goals.wanted(ItemKind::Wood, 10, 10));
1077 assert!(!goals.wanted(ItemKind::Wood, 10, 20));
1078 assert!(!goals.wanted(ItemKind::Wood, 30, 0));
1079 assert!(!goals.wanted(ItemKind::Gold, 0, 0));
1080 }
1081
1082 #[test]
1083 fn ordered_chop_ignores_the_wood_goal() {
1084 let tree = UVec2::new(8, 5);
1085 let mut app = test_app(map_with_trees(&[tree]));
1086 set_goals(&mut app, &[]);
1087 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1088 app.world_mut().write_message(Order {
1089 colonist,
1090 tile: tree,
1091 });
1092 run_ticks(&mut app, 60 * 15);
1093 assert_eq!(
1094 app.world().resource::<WorldMap>().plant(tree.as_ivec2()),
1095 None
1096 );
1097 }
1098
1099 #[test]
1100 fn ordering_a_move_cancels_the_current_job_and_frees_its_tree() {
1101 let tree = UVec2::new(15, 5);
1102 let mut app = test_app(map_with_trees(&[tree]));
1103 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1104 run_ticks(&mut app, 61);
1105 assert!(matches!(
1106 job(&app, colonist),
1107 Some(Job {
1108 task: Task::Work { .. },
1109 ..
1110 })
1111 ));
1112 app.world_mut().write_message(Order {
1113 colonist,
1114 tile: UVec2::new(2, 15),
1115 });
1116 run_ticks(&mut app, 1);
1117 assert_eq!(
1118 job(&app, colonist).map(|j| j.task),
1119 Some(Task::MoveTo(UVec2::new(2, 15)))
1120 );
1121 assert!(
1122 app.world()
1123 .resource::<Reservations>()
1124 .is_free(Target::Site(tree))
1125 );
1126 }
1127
1128 #[test]
1129 fn idle_colonists_haul_loose_items_into_the_stockpile() {
1130 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(17, 15)));
1131 put_wood(&mut app, UVec2::new(5, 5), 20);
1132 spawn_colonist(&mut app, UVec2::new(2, 5));
1133 run_ticks(&mut app, 60 * 15);
1134 assert_eq!(items_at(&mut app), vec![(UVec2::new(15, 15), 20)]);
1135 }
1136
1137 #[test]
1138 fn large_stacks_take_several_trips_and_spill_into_more_stockpile_tiles() {
1139 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(17, 15)));
1140 put_wood(&mut app, UVec2::new(5, 5), STACK_LIMIT + 10);
1141 spawn_colonist(&mut app, UVec2::new(2, 5));
1142 run_ticks(&mut app, 60 * 40);
1143 let stacks = items_at(&mut app);
1144 assert_eq!(stored(&mut app), STACK_LIMIT + 10);
1145 assert!(stacks.len() >= 2);
1146 assert!(stacks.iter().all(|(_, count)| *count <= STACK_LIMIT));
1147 }
1148
1149 #[test]
1150 fn items_already_in_a_stockpile_stay_put() {
1151 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(16, 16)));
1152 put_wood(&mut app, UVec2::new(5, 5), 20);
1153 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1154 run_ticks(&mut app, 60 * 5);
1155 assert_eq!(items_at(&mut app), vec![(UVec2::new(5, 5), 20)]);
1156 assert_eq!(carrying(&app, colonist), None);
1157 }
1158
1159 #[test]
1160 fn colonists_found_a_stockpile_when_items_need_storing() {
1161 let mut app = test_app(map_with_trees(&[]));
1162 set_goals(&mut app, &[]);
1163 put_wood(&mut app, UVec2::new(5, 5), 20);
1164 spawn_colonist(&mut app, UVec2::new(2, 5));
1165 run_ticks(&mut app, 60 * 15);
1166 assert_eq!(
1167 stockpile_size(&app),
1168 (NEW_STOCKPILE_SIZE * NEW_STOCKPILE_SIZE) as usize
1169 );
1170 assert_eq!(stored(&mut app), 20);
1171 }
1172
1173 #[test]
1174 fn no_stockpile_is_founded_while_there_is_nothing_to_store() {
1175 let mut app = test_app(map_with_trees(&[]));
1176 set_goals(&mut app, &[]);
1177 spawn_colonist(&mut app, UVec2::new(2, 5));
1178 run_ticks(&mut app, 60 * 5);
1179 assert_eq!(stockpile_size(&app), 0);
1180 }
1181
1182 #[test]
1183 fn two_colonists_never_haul_the_same_stack() {
1184 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(16, 16)));
1185 put_wood(&mut app, UVec2::new(5, 5), 10);
1186 put_wood(&mut app, UVec2::new(5, 6), 10);
1187 let a = spawn_colonist(&mut app, UVec2::new(2, 5));
1188 let b = spawn_colonist(&mut app, UVec2::new(2, 6));
1189 run_ticks(&mut app, 61);
1190 let pickup = |c| match job(&app, c).map(|j| j.task) {
1191 Some(Task::Haul { pickup, .. }) => pickup,
1192 other => panic!("expected haul, got {other:?}"),
1193 };
1194 assert_ne!(pickup(a), pickup(b));
1195 }
1196
1197 // Orders interrupt whatever a colonist is doing, but whatever it is carrying stays in its
1198 // hands; once it is idle again it finishes delivering it instead of dropping it anywhere.
1199 #[test]
1200 fn interrupted_haulers_deliver_their_load_later() {
1201 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(17, 15)));
1202 put_wood(&mut app, UVec2::new(4, 5), 20);
1203 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1204 let mut ticks = 0;
1205 while carrying(&app, colonist).is_none() && ticks < 60 * 10 {
1206 run_ticks(&mut app, 1);
1207 ticks += 1;
1208 }
1209 app.world_mut().write_message(Order {
1210 colonist,
1211 tile: UVec2::new(2, 2),
1212 });
1213 run_ticks(&mut app, 60 * 3);
1214 assert!(carrying(&app, colonist).is_some());
1215 run_ticks(&mut app, 60 * 20);
1216 assert_eq!(carrying(&app, colonist), None);
1217 assert_eq!(stored(&mut app), 20);
1218 }
1219
1220 #[test]
1221 fn right_clicking_loose_items_orders_a_haul() {
1222 let mut app = hauling_app((IVec2::new(15, 15), IVec2::new(15, 15)));
1223 set_goals(&mut app, &[(ItemKind::Wood, 1000)]);
1224 put_wood(&mut app, UVec2::new(5, 5), 20);
1225 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1226 app.world_mut().write_message(Order {
1227 colonist,
1228 tile: UVec2::new(5, 5),
1229 });
1230 run_ticks(&mut app, 1);
1231 assert!(matches!(
1232 job(&app, colonist),
1233 Some(Job {
1234 task: Task::Haul { .. },
1235 ordered: true
1236 })
1237 ));
1238 }
1239
1240 fn mining_map() -> WorldMap {
1241 let mut map = WorldMap::filled(UVec2::new(20, 20), Terrain::Grass);
1242 for y in 0..20 {
1243 map.set(UVec2::new(10, y), Terrain::Stone);
1244 }
1245 map.set(UVec2::new(10, 5), Terrain::IronOre);
1246 map
1247 }
1248
1249 fn items_of(app: &mut App, kind: ItemKind) -> u32 {
1250 let world = app.world_mut();
1251 let items: Vec<Item> = world.query::<&Item>().iter(world).copied().collect();
1252 stock(items.iter(), kind)
1253 }
1254
1255 #[test]
1256 fn colonists_mine_rock_the_colony_needs_and_leave_gravel() {
1257 let mut app = test_app(mining_map());
1258 set_goals(&mut app, &[(ItemKind::Stone, 10)]);
1259 spawn_colonist(&mut app, UVec2::new(8, 12));
1260 run_ticks(&mut app, 60 * 12);
1261 assert_eq!(items_of(&mut app, ItemKind::Stone), 10);
1262 assert_eq!(items_of(&mut app, ItemKind::Iron), 0);
1263 let map = app.world().resource::<WorldMap>();
1264 let gravel = map
1265 .positions()
1266 .filter(|p| map.get(p.as_ivec2()) == Some(Terrain::Gravel))
1267 .count();
1268 assert_eq!(gravel, 1);
1269 }
1270
1271 #[test]
1272 fn colonists_walk_past_rock_they_do_not_need() {
1273 let mut app = test_app(mining_map());
1274 set_goals(&mut app, &[(ItemKind::Iron, 10)]);
1275 spawn_colonist(&mut app, UVec2::new(8, 15));
1276 run_ticks(&mut app, 60 * 15);
1277 assert_eq!(items_of(&mut app, ItemKind::Iron), 10);
1278 assert_eq!(items_of(&mut app, ItemKind::Stone), 0);
1279 assert_eq!(
1280 app.world().resource::<WorldMap>().get(IVec2::new(10, 5)),
1281 Some(Terrain::Gravel)
1282 );
1283 }
1284
1285 #[test]
1286 fn right_clicking_rock_orders_mining_regardless_of_goals() {
1287 let mut app = test_app(mining_map());
1288 set_goals(&mut app, &[]);
1289 let colonist = spawn_colonist(&mut app, UVec2::new(8, 12));
1290 app.world_mut().write_message(Order {
1291 colonist,
1292 tile: UVec2::new(10, 12),
1293 });
1294 run_ticks(&mut app, 60 * 10);
1295 assert_eq!(
1296 app.world().resource::<WorldMap>().get(IVec2::new(10, 12)),
1297 Some(Terrain::Gravel)
1298 );
1299 }
1300
1301 #[test]
1302 fn colonists_expand_a_stockpile_that_is_nearly_full() {
1303 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(6, 5)));
1304 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1305 run_ticks(&mut app, 61);
1306 assert!(matches!(
1307 job(&app, colonist).map(|j| j.task),
1308 Some(Task::ExpandStockpile { .. })
1309 ));
1310 run_ticks(&mut app, 60 * 5);
1311 assert_eq!(stockpile_size(&app), 2 + EXPANSION_TILES);
1312 }
1313
1314 #[test]
1315 fn roomy_stockpiles_are_left_alone() {
1316 let mut app = hauling_app((IVec2::new(5, 5), IVec2::new(8, 5)));
1317 spawn_colonist(&mut app, UVec2::new(2, 5));
1318 run_ticks(&mut app, 60 * 5);
1319 assert_eq!(stockpile_size(&app), 4);
1320 }
1321
1322 fn set_hour(app: &mut App, hour: u64) {
1323 let ticks = (hour + 24 - 6) % 24 * crate::sim::TICKS_PER_HOUR;
1324 *app.world_mut().resource_mut::<SimTick>() = SimTick(ticks);
1325 }
1326
1327 fn structures(app: &mut App) -> Vec<(UVec2, StructureKind)> {
1328 let world = app.world_mut();
1329 world
1330 .query::<(&TilePos, &Structure)>()
1331 .iter(world)
1332 .map(|(pos, s)| (pos.0, s.kind))
1333 .collect()
1334 }
1335
1336 fn put_campfire(app: &mut App, tile: UVec2) {
1337 app.world_mut().spawn((
1338 Structure {
1339 kind: StructureKind::Campfire,
1340 fuel: StructureKind::Campfire.fuel_ticks(),
1341 },
1342 TilePos(tile),
1343 ));
1344 }
1345
1346 #[test]
1347 fn colonists_light_a_campfire_near_the_stockpile_when_night_falls() {
1348 let mut app = hauling_app((IVec2::new(10, 10), IVec2::new(12, 12)));
1349 put_wood(&mut app, UVec2::new(10, 10), 20);
1350 set_hour(&mut app, 18);
1351 spawn_colonist(&mut app, UVec2::new(2, 5));
1352 run_ticks(&mut app, 60 * 20);
1353 let built = structures(&mut app);
1354 let campfire = built
1355 .iter()
1356 .find(|(_, kind)| *kind == StructureKind::Campfire)
1357 .expect("a campfire");
1358 assert!(campfire.0.as_vec2().distance(Vec2::new(11.0, 11.0)) <= HOME_RADIUS);
1359 assert_eq!(wood_on_map(&mut app), 10);
1360 }
1361
1362 #[test]
1363 fn no_fires_are_built_during_the_day() {
1364 let mut app = hauling_app((IVec2::new(10, 10), IVec2::new(12, 12)));
1365 put_wood(&mut app, UVec2::new(10, 10), 20);
1366 set_hour(&mut app, 10);
1367 spawn_colonist(&mut app, UVec2::new(2, 5));
1368 run_ticks(&mut app, 60 * 10);
1369 assert!(structures(&mut app).is_empty());
1370 }
1371
1372 #[test]
1373 fn without_wood_nothing_can_be_built() {
1374 let mut app = hauling_app((IVec2::new(10, 10), IVec2::new(12, 12)));
1375 set_hour(&mut app, 22);
1376 spawn_colonist(&mut app, UVec2::new(2, 5));
1377 run_ticks(&mut app, 60 * 10);
1378 assert!(structures(&mut app).is_empty());
1379 }
1380
1381 #[test]
1382 fn torches_light_stockpile_tiles_beyond_the_campfire() {
1383 let mut app = hauling_app((IVec2::new(2, 10), IVec2::new(17, 10)));
1384 put_wood(&mut app, UVec2::new(9, 10), 20);
1385 put_campfire(&mut app, UVec2::new(9, 12));
1386 set_hour(&mut app, 22);
1387 spawn_colonist(&mut app, UVec2::new(9, 8));
1388 run_ticks(&mut app, 60 * 15);
1389 assert!(
1390 structures(&mut app)
1391 .iter()
1392 .any(|(_, kind)| *kind == StructureKind::Torch)
1393 );
1394 }
1395
1396 // Light is what makes fires worth building: work in darkness goes at half speed.
1397 #[test]
1398 fn work_is_slower_in_the_dark() {
1399 let tree = UVec2::new(8, 5);
1400 let finish_ticks = |daylight: f32| {
1401 let mut app = test_app(map_with_trees(&[tree]));
1402 let size = app.world().resource::<WorldMap>().size;
1403 app.insert_resource(LightMap::compute(size, daylight, []));
1404 spawn_colonist(&mut app, UVec2::new(7, 5));
1405 let mut ticks = 0;
1406 while app
1407 .world()
1408 .resource::<WorldMap>()
1409 .plant(tree.as_ivec2())
1410 .is_some()
1411 {
1412 run_ticks(&mut app, 1);
1413 ticks += 1;
1414 }
1415 ticks
1416 };
1417 let (lit, dark) = (finish_ticks(1.0), finish_ticks(0.0));
1418 assert!(
1419 dark > lit + WorkKind::Chop.work() / 2 - 10,
1420 "lit {lit}, dark {dark}"
1421 );
1422 }
1423
1424 #[test]
1425 fn colonists_chop_from_a_neighbouring_tile() {
1426 let tree = UVec2::new(8, 5);
1427 let mut app = test_app(map_with_trees(&[tree]));
1428 let colonist = spawn_colonist(&mut app, UVec2::new(2, 5));
1429 run_ticks(&mut app, 60 * 5);
1430 let tile = app.world().get::<TilePos>(colonist).unwrap().0;
1431 assert!(is_adjacent(tile.as_ivec2(), tree.as_ivec2()));
1432 assert_eq!(
1433 app.world().get::<SimPos>(colonist).unwrap().0,
1434 WorldMap::tile_center(tile)
1435 );
1436 }
1437 }