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