src/jobs/mod.rs 73.3 K · 2131 lines · raw · history

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