Skip to main content

unbanished_game/behaviour/character/
actions.rs

1//! The character actions (`Action`): what each one does when it starts, each update, and when it
2//! stops or is aborted, and dropping off what a citizen carries.
3
4mod start;
5
6use super::*;
7
8/// One task.
9#[derive(Debug, Clone)]
10pub enum Action {
11    /// `MoveTo`: walk to a target.
12    MoveTo(Box<MoveTo>),
13    // vtable 0x14015ea70
14    /// `PlayAnimation`: play `anim` for `duration`.
15    PlayAnimation {
16        /// The clip.
17        anim: usize,
18        /// How long it plays, in microseconds.
19        duration: i64,
20        /// The time played so far.
21        elapsed: i64,
22    },
23    // vtable 0x1401662c0
24    /// `PerformWork`: face `facing` (if within ±180), play `anim` for `duration`.
25    PerformWork {
26        /// The heading to face, in degrees.
27        facing: f32,
28        /// The work clip.
29        anim: usize,
30        /// How long the work takes, in microseconds.
31        duration: i64,
32        /// The time worked so far.
33        elapsed: i64,
34        // +0x40; +0xac
35        /// Decrement the citizen's counter on start.
36        consume: bool,
37    },
38    // vtable 0x1401664e0
39    /// `SendComponentMessage`: deliver a message on start.
40    SendMessage(Message),
41    // vtable 0x140165f80
42    /// `CompleteRoad`: the cell becomes its road (or ground) on start.
43    ///
44    /// Original: `FUN_1400caea0`.
45    CompleteRoad {
46        /// The cell.
47        cell: i32,
48        /// The cell type it gets.
49        ty: u8,
50        /// The road kind built there.
51        built: u8,
52    },
53    /// Reserve at construction; consume on start.
54    ///
55    /// Original: `FUN_1400cb880`, `FUN_1400cb980`.
56    ConsumeStoredRawMaterial {
57        /// The storage.
58        storage: usize,
59        /// What it uses: `(raw material, count)`.
60        items: Vec<(usize, i32)>,
61        /// Whether the goods were reserved.
62        reserved: bool,
63    },
64    /// Reserve at construction; transfer on start.
65    ///
66    /// Original: `FUN_1400cf9f0`, `FUN_1400cf700`.
67    PickupStoredRawMaterial {
68        /// The storage.
69        storage: usize,
70        /// What it takes: `(raw material, count)`.
71        items: Vec<(usize, i32)>,
72        /// Whether it may take less than asked.
73        partial: bool,
74    },
75    // vtable 0x14015ead0
76    /// `ShowTool`: attach tool mesh `n` (0..10), the carried goods (−2), or nothing (−1). The town
77    /// draws it on the citizen's `tool` node (`StartingTown::model_instances`).
78    ///
79    /// Original: `FUN_140043070`, `FUN_14011c880`.
80    ShowTool(i32),
81    // vtable 0x140165fe0
82    /// `CompleteTask`: tell the job manager the task is done or abandoned.
83    ///
84    /// Original: `FUN_1400cb270`, `FUN_1400cb010`; abandoned `FUN_1400caf90`.
85    CompleteTask {
86        /// The work's id.
87        work: i32,
88        /// The task's parameter.
89        param: i32,
90    },
91    // vtable 0x140165f20
92    /// `AnimateNaturalResource`: play the resource's animation `anim`; with `wait`, run until it
93    /// ends.
94    ///
95    /// Original: `FUN_1400caca0`, `FUN_1400caad0`, `FUN_1400caa80`.
96    AnimateResource {
97        /// The resource.
98        entity: usize,
99        /// The clip.
100        anim: usize,
101        /// Whether the action waits until the clip ends.
102        wait: bool,
103    },
104    // vtable 0x140166470
105    /// `RemoveNaturalResource`: remove the resource and leave its pile; abort releases the claim
106    /// (flag `0x100000`).
107    ///
108    /// Original: `FUN_1400d02c0`, `FUN_1400cffe0`, `FUN_1400cff70`.
109    RemoveResource {
110        /// The resource.
111        entity: usize,
112        /// The removal flag passed to the resource.
113        flag: bool,
114    },
115    // vtable 0x140166330
116    /// `PickupRawMaterial`: take the whole pile into the carried storage and destroy it.
117    ///
118    /// Original: `FUN_1400cf040`, `FUN_1400ceda0`.
119    PickupPile {
120        /// The pile.
121        entity: usize,
122    },
123    // vtable 0x140166130
124    /// `CreateRawMaterial`: leave the output as piles near `cell`, `batch` weight each (the
125    /// worker's capacity).
126    ///
127    /// Original: `FUN_1400cc670`, `FUN_1400cc010`.
128    CreateRawMaterial {
129        /// The template of the output piles.
130        template: usize,
131        /// The cell they are left near.
132        cell: i32,
133        /// The weight of each pile.
134        batch: i32,
135        /// The workplace that made them.
136        workplace: Option<usize>,
137        // +0x4c
138        /// The yield is scaled by this (1 for production; a dock's share of the fish).
139        factor: f32,
140    },
141    // vtable 0x140166200
142    /// `HuntAnimal`, attached to a hunter's walk or wait: running until its notify (run by the
143    /// citizens' update) has started an attack.
144    ///
145    /// Original: `FUN_1400cd8d0`, `FUN_1400cd2b0`.
146    HuntAnimal {
147        /// The hunter's lodge.
148        lodge: usize,
149        /// Whether the attack has started.
150        done: bool,
151    },
152    // vtable 0x140166400
153    /// `RemoveAnimal`.
154    ///
155    /// Original: `FUN_1400cfcc0`.
156    RemoveAnimal {
157        /// The animal.
158        entity: usize,
159    },
160    // vtable 0x1401660c0
161    /// `CreateNaturalResource`: plant `template` on `cell`, which must hold no object and
162    /// `occupant` as its occupant.
163    ///
164    /// Original: `FUN_1400cbef0`.
165    CreateNaturalResource {
166        /// The resource's template.
167        template: usize,
168        /// The cell's required occupant.
169        occupant: Option<usize>,
170        /// The cell.
171        cell: i32,
172    },
173    // vtable 0x1401661a0; +0x20
174    /// `DropOffRawMaterial`: move up to `count` carried units into `storage`; with `redirect` a
175    /// storage that cannot take them sends the citizen on to another, or the goods are left on the
176    /// ground.
177    ///
178    /// Original: `FUN_1400cd1a0`, `FUN_1400cc7d0`.
179    DropOff {
180        /// The storage.
181        storage: usize,
182        /// The raw material.
183        material: usize,
184        /// The most units to move.
185        count: i32,
186        /// Whether a storage that cannot take them sends the citizen on.
187        redirect: bool,
188    },
189}
190
191/// `FUN_1400ccd90`: `n` units of `m` leave the citizen for a loose pile on the ground.
192pub(super) fn drop_pile(world: &mut World, m: usize, n: i32) {
193    if n == 0 {
194        return;
195    }
196    world.messages.push(Message {
197        component: Component::DropPile,
198        message: 0,
199        entity: None,
200        a: m as i32,
201        b: n,
202    });
203    world.carried.remove(m, n);
204}
205
206/// `FUN_1400ccaf0`: as many as carried, up to `count`, into `target` when they fit; else with
207/// `redirect`, the nearest storage that takes them (the action now points there and a walk
208/// is pushed) or, with none, a loose pile. True when the goods were left on the ground.
209pub(super) fn drop_off_one(
210    ch: &Character,
211    world: &mut World,
212    target: usize,
213    storage: &mut usize,
214    m: usize,
215    count: i32,
216    redirect: bool,
217) -> bool {
218    let carried = world.carried.available(m);
219    let n = if 0 <= count {
220        carried.min(count)
221    } else {
222        carried
223    };
224    if 0 < n && world.storages[target].fits(world.materials, m, n) {
225        world.storages[target].add(m, n);
226        world.carried.remove(m, n);
227        return false;
228    }
229    if !redirect {
230        return false;
231    }
232    let cell = world.cell(ch.position);
233    let found = match world.storage_search.as_mut() {
234        Some(search) => search(world.storages, world.rng, m, n, cell),
235        None => None,
236    };
237    match found {
238        Some((s, point)) => {
239            *storage = s;
240            let walk = MoveTo::new(point, 1, 0, crate::pathfind::WALKABLE, 0, -1.0, world.rng);
241            world.pushes.push(Action::move_to(walk));
242            false
243        }
244        None => {
245            drop_pile(world, m, n);
246            true
247        }
248    }
249}
250
251impl Action {
252    /// A `MoveTo` action.
253    pub fn move_to(m: MoveTo) -> Action {
254        Action::MoveTo(Box::new(m))
255    }
256
257    pub(super) fn update(
258        &mut self,
259        ch: &mut Character,
260        world: &mut World,
261        group: &AnimationGroup,
262        dt: i64,
263    ) -> Status {
264        match self {
265            Action::MoveTo(m) => m.update(ch, world, group),
266            Action::PlayAnimation {
267                duration, elapsed, ..
268            } => {
269                *elapsed += dt;
270                if *elapsed < *duration {
271                    Status::Running
272                } else {
273                    Status::Done
274                }
275            }
276            Action::PerformWork {
277                duration, elapsed, ..
278            } => {
279                if *duration <= *elapsed {
280                    // `FUN_14011bb20`: an injury fails the work.
281                    return if world.injury_check() {
282                        Status::Failed
283                    } else {
284                        Status::Done
285                    };
286                }
287                *elapsed += dt;
288                Status::Running
289            }
290            Action::AnimateResource { entity, .. } => {
291                if world.animating.get(*entity).copied().unwrap_or(false) {
292                    Status::Running
293                } else {
294                    Status::Done
295                }
296            }
297            // The base update returns 0.
298            Action::RemoveResource { .. }
299            | Action::PickupPile { .. }
300            | Action::CreateRawMaterial { .. }
301            | Action::CompleteRoad { .. }
302            | Action::CreateNaturalResource { .. }
303            | Action::RemoveAnimal { .. } => Status::Done,
304            // `FUN_1400cd710`.
305            Action::HuntAnimal { done, .. } => {
306                if *done {
307                    Status::Done
308                } else {
309                    Status::Running
310                }
311            }
312            Action::SendMessage(_)
313            | Action::ConsumeStoredRawMaterial { .. }
314            | Action::PickupStoredRawMaterial { .. }
315            | Action::ShowTool(_)
316            | Action::CompleteTask { .. }
317            | Action::DropOff { .. } => Status::Done,
318        }
319    }
320
321    /// Slot `+0x38` (stop) and `+0x40` (abort): MoveTo and PerformWork return to clip 0.
322    pub(super) fn stop(&mut self, ch: &mut Character, group: &AnimationGroup) {
323        match self {
324            Action::MoveTo(m) => ch.play(m.stand, group, 1.0),
325            Action::PerformWork { .. } => ch.play(0, group, 1.0),
326            _ => {}
327        }
328    }
329
330    /// FUN_1400cb300 / FUN_1400cf140: abort releases pending reservations.
331    pub(super) fn abort(
332        &mut self,
333        ch: &mut Character,
334        group: &AnimationGroup,
335        storages: &mut [Storage],
336    ) {
337        match self {
338            Action::ConsumeStoredRawMaterial {
339                storage,
340                items,
341                reserved: true,
342            }
343            | Action::PickupStoredRawMaterial { storage, items, .. } => {
344                for &(material, count) in items.iter() {
345                    storages[*storage].unreserve(material, count);
346                }
347            }
348            _ => {}
349        }
350        self.stop(ch, group);
351    }
352}