Skip to main content

unbanished_game/behaviour/
character.rs

1//! CharacterComponent and the `Action` task stack it runs. See docs/CITIZEN-AI.md.
2//!
3//! - Slot (bit `0x04` phase, every iteration): run the action stack, then turn toward the target
4//!   heading, move by the animation's root motion times the speed, and drop onto the ground.
5//! - Slot (bit `0x08` bucket phase): notify the running chain (action slot) on the started actions
6//!   of the running chain. MoveTo's sets whether it walks behind another character, at the
7//!   description's follow speed ([`ActionStack::notify_moves`]); HuntAnimal's looks for prey.
8//!
9//! Actions (registered `Action` types, vtable slots start, stop, abort) return [`Status`]. The
10//! stack is an array of chains; the top chain is started once, then updated each run. `Done` pops
11//! it and continues with the next chain in the same run, `Failed` clears everything, and when the
12//! stack empties the "on empty" chain runs once.
13//!
14//! Original: `FUN_14010f1f0`, `FUN_14010e990`, `FUN_1400ca120`, `FUN_14010e950`, `FUN_1400ca450`,
15//! `FUN_1400cde40`, `FUN_1400cd2b0`, `FUN_1400ca080`.
16
17mod actions;
18mod movement;
19mod stack;
20pub use actions::Action;
21pub use movement::MoveTo;
22pub use stack::ActionStack;
23
24// vtable 0x140168790; +0x40; +0x48; +0x30; +0x28 update; +0x58; +0x20; +0x38
25
26use unbanished_formats::game::CharacterDescription;
27use unbanished_formats::types::AnimationGroup;
28
29use crate::behaviour::animation::AnimationStack;
30use crate::pathfind::{self, Pathfinder};
31use crate::random::Random;
32use crate::scheduler::{seconds, ticks};
33use crate::terrain::{CellType, HeightGrid};
34use crate::work::stock::{consume_stored, pickup_stored, RawMaterial, Storage};
35
36// DAT_1401787d4
37/// Arrival distance.
38pub const ARRIVE: f32 = 0.05;
39/// `DAT_1401787e4`: turns smaller than this snap to the target heading.
40const SNAP_DEGREES: f32 = 0.1;
41/// MoveTo's path buffer (`+0x68`, 256 cells, `FUN_1400ac220`).
42const PATH_CELLS: usize = 0x100;
43/// Cell type whose surface is at height 0 (`FUN_14010e990`, type `0x0b`).
44const FLAT_TYPE: u8 = 11;
45
46/// The result of an action's step.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum Status {
49    /// The action finished.
50    Done = 0,
51    /// The action goes on.
52    Running = 1,
53    /// The action failed; the stack is abandoned.
54    Failed = 2,
55}
56
57// DAT_1401cf0e8; DAT_1401cf158
58/// Which component a `SendMessage` targets (CitizenAI, Citizen).
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum Component {
61    /// The citizen's AI.
62    CitizenAi,
63    /// The citizen component (needs, family).
64    Citizen,
65    // DAT_1401cc2c0
66    /// Not identified yet.
67    Happiness,
68    // DAT_1401cf008
69    /// BuildComponent message 0 adds one unit of construction work.
70    Build,
71    // DAT_1401cf5f0
72    /// DestroyComponent message 0 adds one unit of deconstruction work.
73    Destroy,
74    // DAT_1401cc1e0
75    /// FireComponent message 0, a bucket of water.
76    ///
77    /// Original: `FUN_1400499f0`.
78    Fire,
79    // +0x2b
80    /// CompleteRoad's start: `a` the cell, `b` the cell type, `message` the byte.
81    ///
82    /// Original: `FUN_1400cad20`, `FUN_1400a1b10`.
83    Road,
84    /// The job manager: message 0 is CompleteTask's start, 1 its abort; `a` is the work id, `b` the
85    /// task parameter.
86    ///
87    /// Original: `FUN_1400fdc30`, `FUN_1400fdcd0`.
88    Jobs,
89    // +0x30
90    /// A NaturalResourceComponent: 0 remove (RemoveNaturalResource start, `a` its flag), 1 release
91    /// the removal claim (its abort), 2 play animation `a` (AnimateNaturalResource start).
92    ///
93    /// Original: `FUN_14012b910`.
94    NaturalResource,
95    /// A RawMaterialComponent pile: 0 picked up (PickupRawMaterial start).
96    Pile,
97    // +0x4c
98    /// CreateRawMaterial's start: `a` the output template, `b` the cell, `entity` the workplace,
99    /// `message` the yield factor as `f32` bits.
100    ///
101    /// Original: `FUN_1400cc010`.
102    CreateRawMaterial,
103    /// CreateNaturalResource's start once the cell is free: `a` the template, `b` the cell.
104    ///
105    /// Original: `FUN_1400cbb20`.
106    CreateNaturalResource,
107    /// RemoveAnimal's start: the animal `entity` is removed.
108    ///
109    /// Original: `FUN_1400cfcc0`.
110    Animal,
111    /// CropFieldComponent's message slot: `message` 0 planted / 1 tended, `a` the cell index,
112    /// `entity` the field.
113    ///
114    /// Original: `FUN_140120020`.
115    CropField,
116    /// OrchardComponent's message slot: 0 planted, 1 picked, 2 tended; `a` the tree slot.
117    ///
118    /// Original: `FUN_1400522f0`.
119    Orchard,
120    /// PastureComponent's message slot: 0 a rancher's visit.
121    ///
122    /// Original: `FUN_14012cbf0`.
123    Pasture,
124    /// A loose pile of `a` (material), `b` units, left on the ground near the citizen (the units
125    /// already left its storage).
126    ///
127    /// Original: `FUN_1400ccd90`.
128    DropPile,
129    /// QuarryComponent's message slot: the quarry `entity` digs deeper.
130    ///
131    /// Original: `FUN_1400554e0`.
132    Quarry,
133    /// FishingComponent: the fishing sequence's report (`a` the catch's cell). It reaches the
134    /// component's default message handler, which does nothing.
135    Fishing,
136}
137
138// +0x78
139/// A message an action delivered (slot of the receiving component). The owner dispatches these
140/// after the character update.
141#[derive(Debug, Clone, Copy, PartialEq)]
142pub struct Message {
143    /// The component that receives the message.
144    pub component: Component,
145    /// The message's number.
146    pub message: i32,
147    /// The entity it is for, if any.
148    pub entity: Option<usize>,
149    /// The first argument.
150    pub a: i32,
151    /// The second argument.
152    pub b: i32,
153}
154
155/// Map state the character and its actions read. `Town::FindMaterialStorage` for a redirected
156/// drop-off: the storages, the game's Random, the material, the count and the citizen's cell give a
157/// storage and the point to walk to.
158///
159/// Original: `FUN_140092a60`.
160pub type StorageSearch<'a> =
161    dyn FnMut(&[Storage], &mut Random, usize, i32, i32) -> Option<(usize, [f32; 3])> + 'a;
162
163/// What a character needs from the world to move: the map, the ground and the path finder.
164pub struct World<'a> {
165    /// The map's size in cells.
166    pub size: usize,
167    /// The type of each map cell.
168    pub types: &'a [CellType],
169    // +0x08; +0x00; +0x28
170    /// The object stamped into each map cell.
171    pub objects: &'a [Option<usize>],
172    /// The occupant of each map cell.
173    pub occupants: &'a [Option<usize>],
174    /// The flags of each map cell.
175    pub flags: &'a [u8],
176    // +0x2a
177    /// The road kind planned or built (`0xff` none).
178    pub roads: &'a [u8],
179    // +0x2d
180    /// The floors (bridge decks) that characters walk on.
181    pub floors: &'a crate::world::floor::Floors,
182    /// The walkable region of each cell.
183    pub regions: &'a [u16],
184    /// The ground's heights.
185    pub terrain: &'a HeightGrid<'a>,
186    /// The pathfinder.
187    pub pathfinder: &'a mut Pathfinder,
188    /// The game's random numbers.
189    pub rng: &'a mut Random,
190    /// The messages that actions send, delivered after the update.
191    pub messages: &'a mut Vec<Message>,
192    /// What ConsumeRawMaterial used up (material, amount), for the stock manager's count.
193    pub used: &'a mut Vec<(usize, i32)>,
194    /// The town's storages.
195    pub storages: &'a mut [Storage],
196    /// The raw materials.
197    pub materials: &'a [RawMaterial],
198    /// What the character carries.
199    pub carried: &'a mut Storage,
200    /// The drop-off redirect's storage search (citizens only).
201    pub storage_search: Option<&'a mut StorageSearch<'a>>,
202    /// Actions an action pushed from its start (`ActionStack::Push`), pushed once it returns.
203    pub pushes: Vec<Action>,
204    // +0xac
205    /// Citizen: tool uses left (PerformWork with a tool spends one).
206    pub tool_uses: &'a mut i32,
207    /// The tool ShowTool attached (`-1` none, `-2` carried goods).
208    pub shown_tool: &'a mut i32,
209    /// Per placed entity: its model is playing an animation (`MeshInstance::IsAnimating`).
210    pub animating: &'a mut [bool],
211    // +0x1f8; +0x200
212    /// A citizen's accident: the profession whose work it had the accident at.
213    pub accident: &'a mut Option<usize>,
214    /// The time since the last check for an injury at work.
215    pub accident_timer: &'a mut i64,
216    // +0x54; +0x58; +0x30; +0x50
217    /// The current job's profession (→ the work's slot) and its accident odds.
218    pub accident_odds: Option<(usize, f32, f32)>,
219}
220
221impl World<'_> {
222    // RandFloat() < time since the last check / (+0x54 × 12 × 300 s × +0x58); Game +0xd0
223    /// Already hurt, or, at a job whose profession has accidents, `RandFloat < time since the last
224    /// check / (× 12 × 300 s ×)` (the time restarts at every check). Not ported: the debug flag
225    /// that stops it (`Game` bit 8).
226    ///
227    /// Original: `Citizen::InjuryCheck`, `FUN_14011bb20`, `FUN_1400ae760`.
228    pub fn injury_check(&mut self) -> bool {
229        if self.accident.is_some() {
230            return true;
231        }
232        let Some((profession, years, odds)) = self.accident_odds else {
233            return false;
234        };
235        if crate::chance::once_in_years(self.accident_timer, years, odds, self.rng) {
236            *self.accident = Some(profession);
237            return true;
238        }
239        false
240    }
241
242    /// Cell under a map position (clamped, as every caller in the original does).
243    pub fn cell(&self, p: [f32; 3]) -> i32 {
244        let n = self.size as i32;
245        let half = (n >> 1) as f32;
246        let x = ((p[0] + half) as i32).clamp(0, n - 1);
247        let y = ((p[1] + half) as i32).clamp(0, n - 1);
248        n * y + x
249    }
250
251    /// Centre of a cell on the ground (on a bridge's floor).
252    ///
253    /// Original: `FUN_1400a48b0`.
254    pub fn cell_centre(&self, cell: i32) -> [f32; 3] {
255        let n = self.size as i32;
256        let c = (n >> 1) as f32 - 0.5;
257        let (x, y) = ((cell % n) as f32 - c, (cell / n) as f32 - c);
258        [x, y, self.ground(x, y)]
259    }
260
261    /// `FUN_1400a48b0`: the terrain, or a bridge's floor above it.
262    fn ground(&self, x: f32, y: f32) -> f32 {
263        self.floors.ground(self.size, self.terrain, x, y)
264    }
265}
266
267/// `Math::Vector3::Heading`: `atan2(-x, y)` in degrees (0 faces +y).
268pub fn heading(dir: [f32; 2]) -> f32 {
269    crate::math::heading(dir[0], dir[1])
270}
271
272/// Normalize the full 3D vector before taking its heading.
273///
274/// Original: `FUN_1400c7e70`.
275pub fn work_facing(source: [f32; 3], target: [f32; 3]) -> f32 {
276    let d = crate::math::normalize3([
277        source[0] - target[0],
278        source[1] - target[1],
279        source[2] - target[2],
280    ]);
281    crate::math::heading(d[0], d[1])
282}
283
284fn normalize2(v: [f32; 2]) -> [f32; 2] {
285    crate::math::normalize2(v)
286}
287
288/// The character state the actions drive.
289pub struct Character {
290    /// The character description: speeds and turning.
291    pub desc: CharacterDescription,
292    // +0x158; +0x168
293    /// The position of the model.
294    pub position: [f32; 3],
295    /// The heading in degrees, including the model's yaw offset.
296    pub yaw: f32,
297    // +0x2c..+0x34; +0x38; +0x3c
298    /// The walking direction.
299    pub direction: [f32; 3],
300    /// The walking speed.
301    pub speed: f32,
302    /// The heading it turns towards.
303    pub target_heading: f32,
304    // +0x28
305    /// Set with a heading of its own, cleared when a waypoint is faced; no byte read of it was
306    /// found in the Application outside the saves, which keep it.
307    ///
308    /// Original: `FUN_14010f5b0`.
309    pub flag_28: bool,
310    // +0x13c; FUN_14010f6c0 multiplies it into the speed.
311    /// The model's z scale, which scales the walking speed.
312    pub scale: f32,
313    /// The model's animation state, its clips blending into each other.
314    pub animation: AnimationStack,
315    /// The actions it runs.
316    pub stack: ActionStack,
317    // +0x40; Game +0x88
318    /// Its slot in the characters' tree (`Game`), −1 while in none.
319    pub tree_slot: i32,
320}
321
322impl Character {
323    /// A character at a position, with its description and its model's scale.
324    pub fn new(desc: CharacterDescription, position: [f32; 3], scale: f32) -> Character {
325        Character {
326            desc,
327            position,
328            yaw: desc.yaw_offset,
329            direction: [0.0; 3],
330            speed: 0.0,
331            target_heading: 0.0,
332            flag_28: false,
333            scale,
334            animation: AnimationStack::new(0, 0),
335            stack: ActionStack::default(),
336            tree_slot: -1,
337        }
338    }
339
340    /// Play clip `anim` (a looping clip already playing keeps its time,
341    /// `AnimationState::PlayAnimation`) and set the speed to `scale * speed`.
342    ///
343    /// Original: `FUN_14010f6c0`.
344    pub fn play(&mut self, anim: usize, group: &AnimationGroup, speed: f32) {
345        self.animation.play(group, anim, 0);
346        self.speed = self.scale * speed;
347    }
348
349    /// Run the actions, turn and move. `dt` is the manager's iteration delta. Call
350    /// [`Character::animate`] first: `AnimationManager::Update` runs before the entity manager in
351    /// each iteration, and the move uses that step's root motion.
352    ///
353    /// Original: `FUN_14010e990`.
354    pub fn update(&mut self, world: &mut World, group: &AnimationGroup, dt: f32) {
355        let mut stack = std::mem::take(&mut self.stack);
356        stack.run(self, world, group, dt);
357        world.messages.append(&mut stack.outbox);
358        self.stack = stack;
359        self.turn();
360        self.walk(world, group);
361    }
362
363    /// The model's mesh update: advance the clip; the root delta moves the body when the
364    /// character walks. Returns the event resources the newest clip fired (its sounds, for
365    /// [`AnimationSounds::fire`](crate::behaviour::sounds::AnimationSounds::fire)).
366    pub fn animate(&mut self, group: &AnimationGroup, dt: f32) -> Vec<String> {
367        let fired = self.animation.update(group, ticks(dt));
368        let Some(clip) = self.animation.clip().and_then(|c| group.clips.get(c)) else {
369            return Vec::new();
370        };
371        fired
372            .into_iter()
373            .filter_map(|i| clip.events.get(i)?.resource.clone())
374            .collect()
375    }
376
377    /// Root motion of the last animation step (`MeshInstance::RootAnimationOffset`).
378    fn root_offset(&self, group: &AnimationGroup) -> f32 {
379        let Some(pose) = self.animation.pose(group) else {
380            return 0.0;
381        };
382        pose.first().map_or(0.0, |root| {
383            let t = root.translation;
384            (t[0] * t[0] + t[1] * t[1] + t[2] * t[2]).sqrt()
385        })
386    }
387
388    // Description +0x24 yaw offset, +0x28 turn_keep; character +0x3c target heading.
389    /// Turn toward the target heading the shortest way round, keeping `turn_keep` of the angle
390    /// left; within 0.1° the character faces the target at once.
391    ///
392    /// Original: `FUN_14010e990` (its turn).
393    fn turn(&mut self) {
394        // Turn: keep `turn_keep` of the remaining angle (shortest way round).
395        let desc = self.desc;
396        let current = self.yaw - desc.yaw_offset;
397        let mut diff = self.target_heading - current;
398        // ja at 0x14010eaae and jbe at 0x14010eab4: a NaN difference is wrapped, by + 360.
399        // The same as `|d| >= 180` and `d <= 0` for every other value.
400        #[allow(clippy::neg_cmp_op_on_partial_ord)]
401        if !(diff.abs() < 180.0) {
402            diff = if !(diff > 0.0) {
403                diff + 360.0
404            } else {
405                -(360.0 - diff)
406            };
407        }
408        let mut new_heading = self.target_heading;
409        if diff.abs() > SNAP_DEGREES {
410            new_heading = (diff + current) * (1.0 - desc.turn_keep) + desc.turn_keep * current;
411            if new_heading > 180.0 {
412                new_heading -= 360.0;
413            } else if new_heading < -180.0 {
414                new_heading += 360.0;
415            }
416        }
417        self.yaw = new_heading + desc.yaw_offset;
418    }
419
420    /// The movement part of a character's update, after the actions ran and the clip advanced.
421    ///
422    /// Original: the second half of `FUN_14010e990`.
423    pub fn walk(&mut self, world: &World, group: &AnimationGroup) {
424        let distance = self.root_offset(group) * self.speed;
425        let mut p = self.position;
426        if distance > 0.0 {
427            p[0] += distance * self.direction[0];
428            p[1] += distance * self.direction[1];
429            p[2] += distance * self.direction[2];
430        }
431        let cell = world.cell(p);
432        p[2] = if world.types[cell as usize].0 == FLAT_TYPE {
433            0.0
434        } else if self.desc.fixed_height {
435            self.desc.height
436        } else {
437            world.ground(p[0], p[1]).max(self.desc.min_height)
438        };
439        self.position = p;
440    }
441
442    /// Face a point and walk toward it (the end of a `MoveTo`). The direction is the 2D unit
443    /// vector normalised again in 3D; the heading comes from the 2D vector.
444    ///
445    /// Original: `FUN_1400ce1f0`.
446    pub fn face(&mut self, target: [f32; 3]) {
447        let d = normalize2([target[0] - self.position[0], target[1] - self.position[1]]);
448        self.flag_28 = false;
449        self.direction = crate::math::normalize3([d[0], d[1], 0.0]);
450        self.target_heading = heading(d);
451    }
452}
453
454/// Seconds as manager ticks, for action durations.
455pub fn duration(s: f32) -> i64 {
456    ticks(s)
457}
458
459/// Manager ticks as seconds.
460pub fn as_seconds(t: i64) -> f32 {
461    seconds(t)
462}
463
464#[cfg(test)]
465mod inventory_action_tests;
466
467#[cfg(test)]
468mod drop_off_tests;
469
470#[cfg(test)]
471mod on_empty_tests;
472
473#[cfg(test)]
474mod restored_move_tests;