Skip to main content

unbanished_game/work/
jobs.rs

1//! The job manager (`Game`). See docs/JOBS.md.
2//!
3//! Every `Work` gets a sequential id (from 1) and a priority (sequential unless the owner keeps
4//! one). The manager indexes works by id, by priority, by category (`+ (c − 1)·0x10`, categories
5//! 1..14 from the registration mask's bits) and by profession (the work's slot). All of them are
6//! trees keyed by id, so iteration is in id order.
7//!
8//! The AI's work (9) and emergency (2) activities ask the manager for a job:
9//!
10//! - [`Jobs::assign_work`]: the citizen's own profession's works, then [`Jobs::assign_emergency`],
11//!   then the laborers' works;
12//! - [`Jobs::assign_emergency`]: category lists chosen from low stock (`Rand(n)` on the game
13//!   stream), each tried by distance;
14//! - `try_list` sorts candidate works by priority or path rank, ties by id, and `offer` offers them
15//!   in order.
16//!
17//! A work's virtual slots are supplied by a [`WorkHost`]: try to assign (0 no, 1 not now, 2 taken),
18//! a second try, a task completed, a task failed, cancel every worker, refresh.
19//!
20//! Original: `FUN_1400fe650`, `FUN_1400fcd00`, `FUN_1400fca20`, `FUN_1400fce80`, `FUN_1400fd4d0`,
21//! `FUN_1400fd160`, `FUN_1400fd030`.
22mod offers;
23mod queue;
24
25// Game +0x118; +0x00; +0x04; +0x30; +0x10; +0x120; +0x40 + (c − 1)·0x10; +0x50; +0x20; +0x28;
26// +0x38; +0x40; +0x48
27
28use std::collections::{BTreeMap, BTreeSet};
29
30use crate::random::Random;
31
32/// Categories 1..14 (the registration mask's bits 1..14).
33pub const CATEGORIES: usize = 14;
34/// Construction (`BuildStructure` and `GatherRawMaterials`, mask `0x2001`).
35pub const CONSTRUCTION: u32 = 13;
36/// Emergency (fire) work, the only category a citizen with an emergency tries.
37pub const EMERGENCY: u32 = 14;
38
39/// The kinds of work the port has, with their own state.
40#[derive(Debug, Clone)]
41pub enum WorkKind {
42    // vtable 0x140167840
43    /// `GatherRawMaterials`.
44    ///
45    /// Original: `FUN_1400f1be0`.
46    Gather(crate::work::construction::Gather),
47    // vtable 0x1401674c0
48    /// `BuildStructure`.
49    ///
50    /// Original: `FUN_1400eae90`.
51    Build(crate::work::construction::BuildWork),
52    // vtable 0x140167540
53    /// `ClearArea`.
54    ///
55    /// Original: `FUN_1400ebe30`.
56    Clear(crate::work::construction::ClearWork),
57    // vtable 0x140167c30
58    /// `Pickup`: carry a pile to storage. A pile makes it when it is activated.
59    ///
60    /// Original: made by `FUN_14012e6a0`.
61    Pickup(crate::work::construction::PickupWork),
62    // vtable 0x140167640; +0x90
63    /// `ConsumeProduce`: a workplace's production.
64    ///
65    /// Original: `FUN_1400ee6d0`; made by slot `FUN_14011e1d0`.
66    Produce(crate::work::construction::ProduceWork),
67    // vtable 0x140167ab0
68    /// `LocationWork`: staff stand at a school, chapel or doctor.
69    Location(crate::people::services::LocationWork),
70    // vtable 0x1401679c0
71    /// The work of gatherers and herbalists.
72    ///
73    /// Original: made by `FUN_14004bac0`.
74    Herbalist(crate::production::herbalist::HerbalistWork),
75    // vtable 0x1401677c0
76    /// A forester's work, with the same fields.
77    ///
78    /// Original: made by `FUN_140124c50`.
79    Forester(crate::production::herbalist::HerbalistWork),
80    // vtable 0x140167a40
81    /// A hunter's work, with the gatherer's fields.
82    ///
83    /// Original: made by `FUN_140127b70`.
84    Hunt(crate::production::herbalist::HerbalistWork),
85    // vtable 0x140167cb0
86    /// `PlantArea`.
87    ///
88    /// Original: `FUN_1400f9b70`.
89    PlantArea(crate::production::farm::AreaWork),
90    // vtable 0x140167db0
91    /// `TendArea`: the workers, as the gatherer's.
92    TendArea(crate::production::herbalist::HerbalistWork),
93    // vtable 0x1401678c0
94    /// The harvest work.
95    ///
96    /// Original: `FUN_1400f2990`.
97    Harvest(crate::production::farm::AreaWork),
98    // vtable 0x140167d30
99    /// `PlantOrchard`: `need` marks the slots being planted.
100    ///
101    /// Original: `FUN_1400fa610`.
102    PlantOrchard(crate::production::farm::AreaWork),
103    // vtable 0x140167940
104    /// Fruit picking.
105    ///
106    /// Original: `FUN_1400f3530`.
107    PickFruit(crate::production::farm::AreaWork),
108    // vtable 0x140167bc0; +0x48
109    /// PastureComponent's work: the ranchers tending, as the gatherer's.
110    ///
111    /// Original: `FUN_1400f8250`.
112    Pasture(crate::production::herbalist::HerbalistWork),
113    // vtable 0x1401675c0; +0x58
114    /// `ClearStorage`: an empty house's goods go to the town's storage; the haulers.
115    ///
116    /// Original: `FUN_1400ec920`.
117    ClearStorage(crate::production::herbalist::HerbalistWork),
118    // vtable 0x1401676c0; +0x50
119    /// `FireWork`: firefighters carrying buckets to a burning building; the workers.
120    ///
121    /// Original: `FUN_1400ef0a0`.
122    Fire(crate::production::herbalist::HerbalistWork),
123    // vtable 0x140167e30
124    /// `TradeWork`: haulers keeping the trading post's stock.
125    Trade(crate::commerce::trade::TradeWork),
126    // vtable 0x140167430
127    /// `BuildRoad`: one cell of road.
128    Road(crate::work::road::RoadWork),
129    // vtable 0x140167b40; +0x90
130    /// MarketWork (made by MarketComponent's slot).
131    Market(crate::commerce::market::MarketWork),
132    // vtable 0x140167740
133    /// `FishingWork`.
134    ///
135    /// Original: `FUN_1400eff90`.
136    Fishing(crate::production::fishing::FishingWork),
137    /// A test stand-in.
138    Test(i32),
139}
140
141// vtable 0x140167e30
142/// `Work`.
143///
144/// Original: `FUN_1400fc7b0`.
145#[derive(Debug, Clone)]
146pub struct Work {
147    // +0x10
148    /// The owning entity.
149    pub entity: usize,
150    // +0x20; +0x24
151    /// The id.
152    pub id: i32,
153    /// The priority.
154    pub priority: i32,
155    // +0x28
156    /// The owner's map-rectangle centre cell.
157    pub cell: i32,
158    // +0x2c
159    /// The manager pass in which it last answered "not now".
160    pub failed_pass: i32,
161    // +0x30, +0x38, +0x40
162    /// The clock of the distance patience: how long a far work waits before a citizen takes it.
163    ///
164    /// Original: used by `FUN_1400fc3c0`.
165    pub patience: i64,
166    /// The clock when the patience was last brought up to date.
167    pub patience_base: i64,
168    /// How many times a citizen found the work too far.
169    pub far_count: i32,
170    // +0x50
171    /// The profession whose citizens do this work.
172    pub profession: usize,
173    /// What kind of work it is.
174    pub kind: WorkKind,
175}
176
177impl Work {
178    /// `cell` is `(y + h/2)·n + x + w/2` of the owner's map rectangle.
179    ///
180    /// Original: `FUN_1400fc7b0`.
181    pub fn new(entity: usize, cell: i32, profession: usize, kind: WorkKind) -> Work {
182        Work {
183            entity,
184            id: -1,
185            priority: 0,
186            cell,
187            failed_pass: 0,
188            patience: 0,
189            patience_base: 0,
190            far_count: 0,
191            profession,
192            kind,
193        }
194    }
195}
196
197/// The citizen and world queries and the work slots the manager calls.
198pub trait WorkHost {
199    /// Citizen `+0x1f0`, `+0x248`, the character's cell, and `FUN_14011b0b0`.
200    fn profession(&self, citizen: usize) -> usize;
201    /// The citizen's workplace.
202    fn workplace(&self, citizen: usize) -> Option<usize>;
203    /// The citizen's map cell.
204    fn cell(&self, citizen: usize) -> i32;
205    /// Whether there is an emergency near the citizen.
206    fn has_emergency(&self, citizen: usize) -> bool;
207    /// Profession `+0x4c`.
208    fn works_anywhere(&self, profession: usize) -> bool;
209    /// `FUN_1400a4ce0(map, a, b, 1)`, with the callers' fallback `n + (int)sqrtf(d²)`.
210    fn rank(&mut self, a: i32, b: i32) -> i32;
211    /// The stock manager's `(count, limit)` per slot (`Game +0xf0 → +0x170`).
212    fn stock(&self, slot: usize) -> (i32, i32);
213    /// The laborer and builder professions (`Game +0xb0 → +0x30/+0x38`).
214    fn laborer(&self) -> usize;
215    /// The builder profession.
216    fn builder(&self) -> usize;
217    /// The game's random numbers.
218    fn rng(&mut self) -> &mut Random;
219
220    /// Slot `+0x48`: refresh (drop workers that no longer hold this work's task).
221    fn refresh(&mut self, work: &mut Work);
222    /// Slot `+0x20`: 0 cannot, 1 not now, 2 assigned. `time` is the manager's clock `+0x130`.
223    fn try_assign(&mut self, work: &mut Work, citizen: usize, time: i64) -> u8;
224    /// Slot `+0x28` (the base returns false).
225    fn try_assign_again(&mut self, _work: &mut Work, _citizen: usize, _time: i64) -> bool {
226        false
227    }
228    /// Slot `+0x30`: a CompleteTask finished; true removes the work.
229    fn complete(&mut self, work: &mut Work, citizen: usize, param: i32) -> bool;
230    /// Slot `+0x38`: a CompleteTask was aborted.
231    fn fail(&mut self, work: &mut Work, citizen: usize, param: i32);
232    /// Job messages raised while the host ran a slot (aborted CompleteTasks of other works),
233    /// for the manager to deliver: `(work, citizen, param, completed)`.
234    fn take_events(&mut self) -> Vec<JobEvent> {
235        Vec::new()
236    }
237    /// Slot `+0x40`: clear every worker's action stack (their CompleteTask aborts call
238    /// [`WorkHost::fail`] on this work, which the host handles directly).
239    fn cancel(&mut self, work: &mut Work);
240    /// Works a slot `+0x20` asked the manager to offer in its place (`FUN_1400fdaf0` called
241    /// from inside a try, as ClearArea does with the piles in its footprint), in order. A try
242    /// answering [`NESTED`] has queued them.
243    fn take_offers(&mut self) -> Vec<i32> {
244        Vec::new()
245    }
246    /// The queued offers get a second try (`FUN_1400fdaf0(.., 1)`).
247    fn offers_again(&mut self) -> bool {
248        false
249    }
250    /// After a [`NESTED`] answer none of whose offers was taken: the rest of the try
251    /// (ConsumeProduce goes on to work a cycle).
252    fn resume(&mut self, _work: &mut Work, _citizen: usize) -> u8 {
253        1
254    }
255}
256
257/// A try's answer meaning "offer these other works for me" ([`WorkHost::take_offers`]).
258pub const NESTED: u8 = 3;
259
260/// A CompleteTask's report: `complete` (start) or failed (abort).
261#[derive(Debug, Clone, Copy, PartialEq, Eq)]
262pub struct JobEvent {
263    /// The work.
264    pub work: i32,
265    /// The citizen.
266    pub citizen: usize,
267    /// The task's parameter.
268    pub param: i32,
269    /// Whether the task completed (else it was aborted).
270    pub complete: bool,
271}
272
273/// The manager.
274#[derive(Debug, Clone)]
275pub struct Jobs {
276    /// `+0x00`: last id (wraps from `0x7ffffffe` to 0); `+0x04`: next sequential priority.
277    next_id: i32,
278    next_priority: i32,
279    // +0x08
280    /// Pass counter (one per simulation iteration).
281    ///
282    /// Original: `FUN_14009b850`.
283    pub pass: i32,
284    /// `+0x10`: priority → id.
285    priorities: BTreeMap<i32, i32>,
286    // +0x30
287    /// Id → work.
288    pub works: BTreeMap<i32, Work>,
289    /// `+0x40..`: category 1..14 → ids.
290    categories: [BTreeSet<i32>; CATEGORIES],
291    /// `+0x120`: profession → ids.
292    professions: BTreeMap<usize, BTreeSet<i32>>,
293    // +0x130
294    /// Manager clock (ticks), advanced with the pass.
295    pub time: i64,
296}
297
298impl Default for Jobs {
299    fn default() -> Self {
300        Jobs {
301            next_id: 0,
302            next_priority: 0,
303            pass: 1,
304            priorities: BTreeMap::new(),
305            works: BTreeMap::new(),
306            categories: Default::default(),
307            professions: BTreeMap::new(),
308            time: 0,
309        }
310    }
311}
312
313/// `FUN_1400fca20`'s stock checks: `(slot, categories)`, tried when `count <= limit / 10`.
314const EMERGENCY_LISTS: [(usize, &[u32]); 9] = [
315    (5, &[1]),
316    (3, &[2, 4, 10]),
317    (4, &[3, 6, 4, 10, 12]),
318    (0, &[4, 10]),
319    (2, &[6, 12]),
320    (1, &[5, 11]),
321    (10, &[9]),
322    (7, &[7, 9]),
323    (6, &[8]),
324];
325
326impl Jobs {
327    /// One simulation iteration of the job manager.
328    ///
329    /// Original: `FUN_1400fe650`, and the step in `FUN_14009b850`.
330    pub fn step(&mut self, dt: i64) {
331        self.pass = self.pass.wrapping_add(1);
332        self.time = self.time.wrapping_add(dt);
333    }
334
335    /// Whether there is no work.
336    pub fn is_empty(&self) -> bool {
337        self.works.is_empty()
338    }
339
340    /// Register a work. With `keep`, the work gets that priority (moved down past any value already
341    /// taken), else the next one in sequence. Returns the work's id.
342    ///
343    /// Original: `FUN_1400fdd70(work, mask, keep, priority)`.
344    pub fn add(&mut self, mut work: Work, mask: u32, keep: Option<i32>) -> i32 {
345        self.next_id = self.next_id.wrapping_add(1);
346        let id = self.next_id;
347        if id == 0x7ffffffe {
348            self.next_id = 0;
349        }
350        let priority = match keep {
351            None => {
352                let p = self.next_priority;
353                self.next_priority = p.wrapping_add(1);
354                p
355            }
356            Some(mut p) => {
357                while self.priorities.contains_key(&p) {
358                    p -= 1;
359                }
360                p
361            }
362        };
363        work.id = id;
364        work.priority = priority;
365        self.priorities.entry(priority).or_insert(id);
366        for c in 1..=CATEGORIES {
367            if mask & (1 << c) != 0 {
368                self.categories[c - 1].insert(id);
369            }
370        }
371        self.professions
372            .entry(work.profession)
373            .or_default()
374            .insert(id);
375        self.works.insert(id, work);
376        id
377    }
378
379    // +0x130
380    /// A saved manager: its counters, then each work with the categories it was filed under
381    /// (1..14), and the professions its profession map holds. The priority index is rebuilt from
382    /// the works' own priorities, as the load pass does; the clock is not saved and restarts at 0.
383    ///
384    /// Original: `FUN_1400fe710`.
385    pub fn restore(
386        &mut self,
387        next_id: i32,
388        next_priority: i32,
389        pass: i32,
390        works: impl IntoIterator<Item = (Work, Vec<u32>)>,
391        professions: &[usize],
392    ) {
393        *self = Jobs {
394            next_id,
395            next_priority,
396            pass,
397            ..Default::default()
398        };
399        // The profession map keeps a profession whose works are all gone.
400        for &p in professions {
401            self.professions.entry(p).or_default();
402        }
403        for (work, categories) in works {
404            let id = work.id;
405            self.priorities.entry(work.priority).or_insert(id);
406            for c in categories {
407                if let Some(set) = (c as usize)
408                    .checked_sub(1)
409                    .and_then(|c| self.categories.get_mut(c))
410                {
411                    set.insert(id);
412                }
413            }
414            self.professions
415                .entry(work.profession)
416                .or_default()
417                .insert(id);
418            self.works.insert(id, work);
419        }
420    }
421
422    // +0x00; +0x04
423    /// The counters a save holds.
424    pub fn counters(&self) -> (i32, i32) {
425        (self.next_id, self.next_priority)
426    }
427
428    /// The works filed under category `c` (1..14), in id order.
429    pub fn category(&self, c: u32) -> Vec<i32> {
430        (c as usize)
431            .checked_sub(1)
432            .and_then(|c| self.categories.get(c))
433            .map(|set| set.iter().copied().collect())
434            .unwrap_or_default()
435    }
436
437    // +0x120
438    /// The works by profession, in profession then id order.
439    pub fn by_profession(&self) -> Vec<(usize, Vec<i32>)> {
440        self.professions
441            .iter()
442            .map(|(&p, ids)| (p, ids.iter().copied().collect()))
443            .collect()
444    }
445
446    /// A task finished (the start of `CompleteTask`): remove the work when its slot says it is
447    /// done.
448    ///
449    /// Original: `FUN_1400fdc30`.
450    pub fn complete(&mut self, id: i32, citizen: usize, param: i32, host: &mut impl WorkHost) {
451        let Some(mut work) = self.works.remove(&id) else {
452            return;
453        };
454        let done = host.complete(&mut work, citizen, param);
455        self.works.insert(id, work);
456        self.drain(host);
457        if done {
458            self.remove(id, host);
459        }
460    }
461
462    /// A task failed (`CompleteTask` cancelled).
463    ///
464    /// Original: `FUN_1400fdcd0`.
465    pub fn fail(&mut self, id: i32, citizen: usize, param: i32, host: &mut impl WorkHost) {
466        if let Some(mut work) = self.works.remove(&id) {
467            host.fail(&mut work, citizen, param);
468            self.works.insert(id, work);
469            self.drain(host);
470        }
471    }
472}
473
474#[cfg(test)]
475mod tests;