src/jobs/mod.rs 49.7 K · 1432 lines · raw · history

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