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