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