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