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