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