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