Skip to main content

unbanished_game/behaviour/character/
stack.rs

1//! The action stack: the actions a character carries out in turn, their reservations, and saving
2//! and restoring them.
3
4use super::*;
5
6#[derive(Debug, Clone)]
7pub(super) struct Task {
8    action: Action,
9    started: bool,
10}
11
12// +0x48; +0x58; +0x60
13/// The CharacterComponent's task stack (top index) and its "on empty" chain.
14#[derive(Debug, Clone, Default)]
15pub struct ActionStack {
16    chains: Vec<Vec<Task>>,
17    on_empty: Vec<Task>,
18    /// Job-manager messages from aborted CompleteTasks, for the owner to deliver right after the
19    /// clear.
20    ///
21    /// Original: `FUN_1400caf90`.
22    pub outbox: Vec<Message>,
23    /// The "on empty" chain ran in the last [`ActionStack::run`]; see
24    /// [`ActionStack::end_on_empty`].
25    ran_on_empty: bool,
26}
27
28impl ActionStack {
29    // +0x18; +0x10
30    /// A saved stack: its entries bottom to top, each one action and whether it started, and the
31    /// "on empty" action. Actions linked to an entry are not saved.
32    ///
33    /// Original: `FUN_14010ef80`.
34    pub fn restored(entries: Vec<(Action, bool)>, on_empty: Option<Action>) -> ActionStack {
35        ActionStack {
36            chains: entries
37                .into_iter()
38                .map(|(action, started)| vec![Task { action, started }])
39                .collect(),
40            on_empty: on_empty
41                .into_iter()
42                .map(|action| Task {
43                    action,
44                    started: false,
45                })
46                .collect(),
47            outbox: Vec::new(),
48            ran_on_empty: false,
49        }
50    }
51
52    /// What a save holds: each entry's first action with its started flag, and the "on empty"
53    /// chain's first action.
54    ///
55    /// Original: `FUN_14010ef80`.
56    pub fn saved(&self) -> (Vec<(&Action, bool)>, Option<&Action>) {
57        (
58            self.chains
59                .iter()
60                .filter_map(|c| c.first().map(|t| (&t.action, t.started)))
61                .collect(),
62            self.on_empty.first().map(|t| &t.action),
63        )
64    }
65
66    // +0x60 + 1
67    /// How many entries the stack holds.
68    pub fn depth(&self) -> usize {
69        self.chains.len()
70    }
71
72    // +0x60 >= 0
73    /// `>= 0`: something is queued (the AI's "is busy" test).
74    pub fn is_active(&self) -> bool {
75        !self.chains.is_empty()
76    }
77
78    // +0x40
79    /// Abort every chain (slot on all actions) and drop the "on empty" chain.
80    ///
81    /// Original: `FUN_1400ca8d0`.
82    pub fn clear(&mut self, ch: &mut Character, group: &AnimationGroup, storages: &mut [Storage]) {
83        for chain in &mut self.chains {
84            for t in chain.iter_mut() {
85                if let Action::CompleteTask { work, param } = t.action {
86                    if work >= 0 {
87                        self.outbox.push(Message {
88                            component: Component::Jobs,
89                            message: 1,
90                            entity: None,
91                            a: work,
92                            b: param,
93                        });
94                    }
95                }
96                // `FUN_1400cff70`: the resource is free again.
97                if let Action::RemoveResource { entity, .. } = t.action {
98                    self.outbox.push(Message {
99                        component: Component::NaturalResource,
100                        message: 1,
101                        entity: Some(entity),
102                        a: 0,
103                        b: 0,
104                    });
105                }
106                t.action.abort(ch, group, storages);
107            }
108        }
109        self.chains.clear();
110        self.on_empty.clear();
111    }
112
113    /// The stored goods queued actions hold reserved: `(storage, material, count)` of each
114    /// unstarted PickupStoredRawMaterial and reserving ConsumeStoredRawMaterial.
115    pub fn pending_reservations(&self) -> Vec<(usize, usize, i32)> {
116        let mut out = Vec::new();
117        for t in self.chains.iter().flatten().filter(|t| !t.started) {
118            match &t.action {
119                Action::PickupStoredRawMaterial { storage, items, .. }
120                | Action::ConsumeStoredRawMaterial {
121                    storage,
122                    items,
123                    reserved: true,
124                } => out.extend(items.iter().map(|&(m, n)| (*storage, m, n))),
125                _ => {}
126            }
127        }
128        out
129    }
130
131    /// Does a chain start with this work's CompleteTask?
132    ///
133    /// Original: `FUN_1400fc5d0`.
134    pub fn holds_task(&self, work: i32) -> Option<i32> {
135        self.chains
136            .iter()
137            .find_map(|c| match c.first().map(|t| &t.action) {
138                Some(Action::CompleteTask { work: w, param }) if *w == work => Some(*param),
139                _ => None,
140            })
141    }
142
143    // +0x10
144    /// Link `action` into the top chain (the original's of the top action).
145    pub fn attach(&mut self, action: Action) {
146        if let Some(top) = self.chains.last_mut() {
147            top.push(Task {
148                action,
149                started: false,
150            });
151        }
152    }
153
154    /// The top chain's `HuntAnimal`, if any: its lodge and its `done` flag.
155    pub fn hunt_watch(&mut self) -> Option<(usize, &mut bool)> {
156        self.chains
157            .last_mut()?
158            .iter_mut()
159            .filter(|t| t.started)
160            .find_map(|t| match &mut t.action {
161                Action::HuntAnimal { lodge, done } => Some((*lodge, done)),
162                _ => None,
163            })
164    }
165
166    // +0x30
167    /// The scheduled notify: the running chain's started actions get slot; MoveTo's sets whether it
168    /// follows.
169    ///
170    /// Original: `FUN_14010e950`, `FUN_1400ca450`, `FUN_1400cde40`.
171    pub fn notify_moves(&mut self, following: bool) {
172        let Some(chain) = self.chains.last_mut() else {
173            return;
174        };
175        for t in chain.iter_mut().filter(|t| t.started) {
176            if let Action::MoveTo(m) = &mut t.action {
177                m.following = following;
178            }
179        }
180    }
181
182    // SendComponentMessage's start calls the component at once (`FUN_1400d03c0`); `RunOnEmpty`
183    // then deletes the chain at `+0x10`.
184    /// Call after delivering the messages of the last [`ActionStack::run`]. The original delivers
185    /// the "on empty" chain's message as it starts it, then deletes the chain. A chain the
186    /// message's handler set meanwhile is deleted with it, so a decision made from that message
187    /// ends with no "on empty" message and waits for the next scheduled update.
188    ///
189    /// Original: `FUN_1400ca080`.
190    pub fn end_on_empty(&mut self) {
191        if std::mem::take(&mut self.ran_on_empty) {
192            self.on_empty.clear();
193        }
194    }
195
196    /// Set the actions to run when the stack is empty.
197    pub fn set_on_empty(&mut self, actions: Vec<Action>) {
198        self.on_empty = actions
199            .into_iter()
200            .map(|action| Task {
201                action,
202                started: false,
203            })
204            .collect();
205    }
206
207    /// Stop the current top's started actions, then push a chain.
208    ///
209    /// Original: `FUN_1400ca9b0`.
210    pub fn push(&mut self, ch: &mut Character, group: &AnimationGroup, action: Action) {
211        if let Some(top) = self.chains.last_mut() {
212            for t in top.iter_mut().filter(|t| t.started) {
213                t.started = false;
214                t.action.stop(ch, group);
215            }
216        }
217        self.chains.push(vec![Task {
218            action,
219            started: false,
220        }]);
221    }
222
223    /// `FUN_1400ca120`.
224    pub(super) fn run(
225        &mut self,
226        ch: &mut Character,
227        world: &mut World,
228        group: &AnimationGroup,
229        dt: f32,
230    ) {
231        let dt = ticks(dt);
232        while let Some(top) = self.chains.last_mut() {
233            let mut status = Status::Running;
234            if !top.first().is_some_and(|t| t.started) {
235                for t in top.iter_mut() {
236                    t.started = true;
237                    status = t.action.start(ch, world, group);
238                    if status != Status::Running || !world.pushes.is_empty() {
239                        break;
240                    }
241                }
242            }
243            // An action's start pushed a chain (`ActionStack::Push`): the top's started
244            // actions stop and the new chain runs first.
245            if !world.pushes.is_empty() {
246                for action in std::mem::take(&mut world.pushes) {
247                    self.push(ch, group, action);
248                }
249                if status == Status::Failed {
250                    self.clear(ch, group, world.storages);
251                }
252                continue;
253            }
254            let mut ran = false;
255            if status == Status::Running {
256                for t in top.iter_mut() {
257                    status = t.action.update(ch, world, group, dt);
258                    if status != Status::Running {
259                        break;
260                    }
261                }
262                ran = status == Status::Running;
263            }
264            match status {
265                Status::Done => {
266                    let mut chain = self.chains.pop().unwrap_or_default();
267                    for t in chain.iter_mut().filter(|t| t.started) {
268                        t.started = false;
269                        t.action.stop(ch, group);
270                    }
271                }
272                // `FUN_1400ca8d0` also drops the "on empty" chain.
273                Status::Failed => self.clear(ch, group, world.storages),
274                Status::Running => {}
275            }
276            if ran {
277                break;
278            }
279        }
280        if self.chains.is_empty() && !self.on_empty.is_empty() {
281            self.ran_on_empty = true;
282            for t in self.on_empty.iter_mut() {
283                t.started = true;
284                if t.action.start(ch, world, group) != Status::Running {
285                    break;
286                }
287            }
288            self.on_empty.clear();
289        }
290    }
291}