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