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