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