unbanished_game/behaviour/agents.rs
1//! The citizens' CharacterComponent and CitizenAIComponent run together each simulation
2//! iteration. See docs/CITIZEN-AI.md.
3//!
4//! Order per iteration: each citizen's model advances its clip (and draws for its sound events),
5//! then its character runs its actions and moves; "sequence finished" messages run the AI again
6//! with zero time, then the AI updates.
7//!
8//! One iteration runs in the entity manager's order (docs/ITERATION-ORDER.md): the every-
9//! iteration phase (bit `0x04`: the citizens' characters, then the sites' state machines, nomads,
10//! boats and tornadoes; [`Agents::every_iteration`]), then bucket 1's citizens
11//! ([`Agents::visit_citizens`]: the character's notify, CitizenComponent, CitizenAIComponent),
12//! then bucket 3's sites and piles ([`Agents::visit_sites`]), with the seeder's buckets 2 and 4
13//! between and after them, then the deletions ([`Agents::finish`]).
14//!
15//! Deviation: the every-iteration phase runs one kind at a time (the animals, then the models,
16//! then the citizens, then the sites); the original runs it entity by entity, in its set's order.
17//! Animals and sites are also deleted at other points than citizens. See
18//! docs/ITERATION-ORDER.md, steps 3 and 4, and issue #22.
19//!
20//! This file holds the agents' state and set-up; the rest is split by topic: `update` (the
21//! iteration), `thinking` (the AI), `lives`, `commands`, `paths` and `views`.
22//!
23//! Original: `AnimationManager::Update`; the entity manager's bit-`0x04` components;
24//! `FUN_140114810` (sequence finished); `FUN_1400c9560` (the buckets).
25
26// The bucket order: FUN_1400c9560 loops over buckets 0 to 4 and dispatches slot +0x48 to each
27// visited entity's bit-0x08 components in array order, stopping at entity flag 0x400.
28mod commands;
29mod lives;
30mod paths;
31mod thinking;
32mod update;
33mod views;
34pub use views::entity_views;
35use views::{refresh_views, storage_of};
36
37use unbanished_formats::game::CharacterDescription;
38use unbanished_formats::types::AnimationGroup;
39
40use crate::behaviour::activities::{loiter, EntityView, StorageGeometry, TownView};
41use crate::behaviour::ai::{activity, CitizenAi, CitizenView, Thresholds};
42use crate::behaviour::character::{Action, Character, Component, Message, MoveTo, World};
43use crate::nature::seeding::{Cells, Placed, Template};
44use crate::pathfind::{regions, Pathfinder, WALKABLE};
45use crate::people::citizens::Citizen;
46use crate::random::Random;
47use crate::scheduler::ticks;
48use crate::sectors::SectorGraph;
49use crate::terrain::{CellType, HeightGrid};
50use crate::town::{Env, Sim};
51use crate::work::stock::{find_storage, RawMaterial, Storage, StorageSite};
52
53/// `DAT_140178818`: children's model and walk scale (`FUN_14011a700`).
54const CHILD_SCALE: f32 = 0.66;
55
56/// `DAT_1401788fc`: cooldown set by the fetch-tool and fetch-clothing activities.
57const FETCH_COOLDOWN: f32 = 75.0;
58
59/// The CitizenDescription values the AI reads.
60#[derive(Debug, Clone, Copy, Default)]
61pub struct CitizenRulesAi {
62 /// The thresholds of the citizen's needs.
63 pub thresholds: Thresholds,
64 // +0x6c; +0xa4
65 /// The starting health.
66 pub health: f32,
67 /// The starting happiness.
68 pub happiness: f32,
69 // +0xbc
70 /// Loiter search range.
71 pub loiter_range: i32,
72 // +0x130
73 /// How long clothing lasts, in seconds (the citizen description's value multiplied by 300).
74 ///
75 /// Original: `FUN_140117730`.
76 pub clothing_duration: f32,
77 /// The highest health.
78 pub health_max: f32,
79 /// Midpoint for food, quarter-point for cold status warnings.
80 ///
81 /// Original: `FUN_140118340`.
82 pub hunger_limit: f32,
83 /// The cold level of the cold warning.
84 pub cold_limit: f32,
85 /// Whether a citizen without a workplace shows no job warning, when no professions are loaded.
86 pub profession_allows_idle: bool,
87 // +0x110
88 /// CitizenDescription: the tool type CitizenUI calls "Iron" (others are "Steel").
89 pub tool_grade: i32,
90 // CitizenDescription +0xfc, +0x100, +0x104 (ints) and +0x108, +0x10c (°F); used by FUN_1400fc3c0.
91 /// The rank of work a citizen takes at once, before it has waited.
92 pub work_near: i32,
93 /// The rank of work a citizen takes after it has waited the longest.
94 pub work_far: i32,
95 /// The longest wait, in months (of 300 seconds).
96 pub work_minutes: i32,
97 /// The rank of work a citizen always takes.
98 pub work_ok: i32,
99 /// The temperature at or above which a citizen takes any work in range.
100 pub work_cold: f32,
101 // +0x114
102 /// CitizenDescription: work duration factor without a tool.
103 ///
104 /// Original: `FUN_1400cebf0`.
105 pub no_tool_factor: f32,
106 // +0x118
107 /// The education a citizen counts as educated with.
108 pub education: i32,
109 // +0xf8
110 /// How far a firefighter looks for water.
111 ///
112 /// Original: `FUN_14008d6a0`.
113 pub water_distance: i32,
114}
115
116/// Citizen fields read/written by equipment activities and Citizen messages 1/6/7.
117#[derive(Debug, Clone, Default)]
118pub struct CitizenState {
119 /// The health.
120 pub health: f32,
121 /// The happiness.
122 pub happiness: f32,
123 /// The hunger.
124 pub hunger: f32,
125 /// The cold.
126 pub cold: f32,
127 /// Whether the citizen is sick.
128 pub sick: bool,
129 /// The work it is assigned, if any (*inferred*).
130 pub work: Option<usize>,
131 // +0xf0; +0x280
132 /// StatusIconComponent (Citizen points to that component).
133 pub status: u32,
134 // +0xa8
135 /// The tool level shown in the citizen window.
136 pub tool_status: i32,
137 // +0xac
138 /// The uses left on its tool.
139 pub tool_uses: i32,
140 // +0x1e0
141 /// The clothing level shown in the citizen window.
142 pub clothing_status: i32,
143 // +0x1e4
144 /// The clothing level: 0 none, 1 or 2.
145 pub clothing: i32,
146 // +0x1e8
147 /// The time its clothing lasts.
148 pub clothing_remaining: i64,
149 // +0x54
150 /// Flags of health events.
151 pub health_events: u32,
152 // +0x88
153 /// Status flags.
154 pub flags: u32,
155 // +0xb0
156 /// The supply errand it runs for its home: 1 food, 2 firewood.
157 pub supply_activity: i32,
158 // +0x30
159 /// The id of the work it does (−1 none).
160 pub job: i32,
161 // +0x238
162 /// The home, if any.
163 pub home: Option<usize>,
164 /// What it carries.
165 pub carried: Storage,
166 // +0x1f0
167 /// Profession (index into the profession list).
168 pub profession: usize,
169 // +0x248
170 /// Workplace entity.
171 pub workplace: Option<usize>,
172 /// The tool ShowTool attached (−1 none, −2 carried goods).
173 pub shown_tool: i32,
174 // +0x240
175 /// Family slot in the home's ResidenceComponent (−1 none).
176 pub home_slot: i32,
177 // +0x4c
178 /// Pregnancy (positive, counting down) or the wait after a birth (negative).
179 pub reproduction: f32,
180 // +0x58, +0x90
181 /// Time towards the next health step.
182 pub health_timer: i64,
183 /// Time towards the next happiness step.
184 pub happiness_timer: i64,
185 // +0x98
186 /// Every kind of food eaten.
187 pub foods: Vec<usize>,
188 // +0x260
189 /// The children and other dependents, in ring order.
190 pub dependents: Vec<usize>,
191 // +0x218
192 /// Time attending school.
193 pub school_time: i64,
194 // +0x208
195 /// The school's AttendanceComponent entity (`Citizen::school` mirrors it).
196 pub school: Option<usize>,
197 // +0x228, +0x230
198 /// The doctor's AttendanceComponent entity.
199 pub doctor: Option<usize>,
200 /// The chapel's AttendanceComponent entity.
201 pub priest: Option<usize>,
202 // +0x68
203 /// The disease (index into the disease list).
204 pub disease: Option<usize>,
205 // +0x70
206 /// The illness left while sick.
207 pub disease_left: i64,
208 /// The immunity left after an illness.
209 pub immunity: i64,
210 // +0x78
211 /// Time to the next spread attempt.
212 pub spread: i64,
213 // +0x60
214 /// Time since the last disease check.
215 pub disease_clock: i64,
216 // +0x84
217 /// The work count the happiness compares with `_workForHappiness`; never written in 1.0.7, so
218 /// 0.
219 pub field_84: i32,
220 // +0x220
221 /// Has had a school place.
222 pub schooled: bool,
223 // +0x1f8
224 /// The profession whose work it had an accident at.
225 ///
226 /// Original: `FUN_14011bb20`.
227 pub accident: Option<usize>,
228 // +0x200
229 /// Time since the last injury check.
230 pub accident_timer: i64,
231}
232
233impl CitizenState {
234 /// The state of a new citizen.
235 ///
236 /// Original: `FUN_140119c40`, set-up `FUN_140119520`.
237 pub fn newborn(rules: &crate::people::life::LifeRules) -> CitizenState {
238 CitizenState {
239 job: -1,
240 // The constructor's values: -1 tool status, 4 clothing status.
241 tool_status: -1,
242 clothing_status: 4,
243 shown_tool: -1,
244 // `+0x240` is left at the allocator's 0; leaving a home sets −1 (`FUN_14011b8a0`).
245 home_slot: 0,
246 health: rules.f(0x6c),
247 happiness: rules.f(0xa4),
248 ..Default::default()
249 }
250 }
251}
252
253impl CitizenState {
254 /// Handle a message about equipment (a tool or clothing given, worn out or used).
255 ///
256 /// Original: the equipment branches of `FUN_140117730` and `FUN_1401152b0`.
257 pub fn message(&mut self, m: Message, rules: CitizenRulesAi) {
258 match m.message {
259 1 => {
260 crate::people::status::set_icon(&mut self.status, 4, false, false);
261 self.tool_uses = self.tool_uses.wrapping_add(m.a);
262 self.tool_status = m.a;
263 }
264 6 | 7 => {
265 self.clothing = m.message - 5;
266 self.clothing_status = self.clothing;
267 self.clothing_remaining = ticks(rules.clothing_duration);
268 self.flags |= 0x800;
269 }
270 8 => self.flags |= 0x40000,
271 _ => {}
272 }
273 }
274}
275
276struct TownStock<'a> {
277 materials: &'a [RawMaterial],
278 storages: &'a mut [Storage],
279 sites: &'a [StorageSite],
280}
281
282/// The citizens' agents: each citizen's AI and character, and the state the iteration needs.
283pub struct Agents {
284 /// The citizens' characters.
285 pub characters: Vec<Character>,
286 /// The citizens' AI.
287 pub ais: Vec<CitizenAi>,
288 /// The citizens' states.
289 pub states: Vec<CitizenState>,
290 /// The CitizenDescription for the CitizenComponent's update.
291 pub life: crate::people::life::LifeRules,
292 // +0xa0
293 /// The living citizens, in activation order.
294 pub registry: Vec<usize>,
295 /// Log entries the citizens asked for since the caller last took them.
296 pub events: Vec<crate::people::life::LifeEvent>,
297 // GameGlobal +0xa8
298 /// `Game/Disease/Diseases.rsc` (`GameGlobal`).
299 pub diseases: Vec<unbanished_formats::game::Disease>,
300 // +0x1a8
301 /// The town's disease level.
302 pub town_disease: f32,
303 /// The character description new citizens get.
304 desc: CharacterDescription,
305 /// A new citizen's carried storage.
306 carried: Storage,
307 /// Citizens queued for deletion this iteration (`FUN_14011c2a0`), with the reason.
308 dying: Vec<(usize, i32)>,
309 // +0x50
310 /// The laborer profession's carry amount (what home stocking carries at least).
311 pub carry: i32,
312 sectors: SectorGraph,
313 pathfinder: Pathfinder,
314 regions: Vec<u16>,
315 region_types: Vec<CellType>,
316 /// The [`Cells::types_revision`] `region_types` was last brought up to.
317 types_seen: u64,
318 /// How far `Cells::sector_marks` has been taken in.
319 marks_seen: usize,
320 rules: CitizenRulesAi,
321 /// The sound events the citizens' and animals' clips fire.
322 pub sounds: crate::behaviour::sounds::AnimationSounds,
323}
324
325impl Agents {
326 /// New agents with no citizens.
327 pub fn new(
328 citizens: &[Citizen],
329 cells: &Cells,
330 desc: CharacterDescription,
331 rules: CitizenRulesAi,
332 carried: Storage,
333 scale: impl Fn(&Citizen) -> f32,
334 ) -> Agents {
335 let mut states: Vec<CitizenState> = citizens
336 .iter()
337 .map(|c| CitizenState {
338 job: -1,
339 // As `newborn`: the constructor `FUN_140119c40` sets these.
340 tool_status: -1,
341 clothing_status: 4,
342 shown_tool: -1,
343 home_slot: 0,
344 // `FUN_14011c550`: an educated citizen starts with its school done (`+0x220`).
345 schooled: c.educated,
346 health: rules.health,
347 happiness: rules.happiness,
348 carried: carried.clone(),
349 ..Default::default()
350 })
351 .collect();
352 for (s, c) in states.iter_mut().zip(citizens) {
353 s.school = c.school;
354 }
355 // `FUN_14011bd70` put each child in its guardian's ring.
356 for (i, c) in citizens.iter().enumerate() {
357 if let Some(g) = c.parent {
358 states[g].dependents.push(i);
359 }
360 }
361 Agents {
362 characters: citizens
363 .iter()
364 .map(|c| {
365 // Activation (`FUN_14010ee90`) faces the target heading the model's yaw.
366 let mut ch = Character::new(desc, c.position, scale(c));
367 ch.target_heading = ch.yaw;
368 ch
369 })
370 .collect(),
371 ais: citizens.iter().map(|_| CitizenAi::default()).collect(),
372 states,
373 life: crate::people::life::LifeRules::default(),
374 registry: (0..citizens.len()).collect(),
375 events: Vec::new(),
376 diseases: Vec::new(),
377 town_disease: 0.0,
378 desc,
379 carried,
380 carry: 0,
381 dying: Vec::new(),
382 sectors: SectorGraph::new(cells.size, &cells.types),
383 pathfinder: Pathfinder::new(cells.size, &cells.types),
384 regions: regions(cells.size, &cells.types),
385 region_types: cells.types.clone(),
386 types_seen: cells.types_revision,
387 marks_seen: cells.sector_marks.len(),
388 rules,
389 sounds: Default::default(),
390 }
391 }
392
393 /// The AI's rules, from the citizen description.
394 pub fn rules(&self) -> CitizenRulesAi {
395 self.rules
396 }
397
398 /// The work and construction context over these citizens and `env`.
399 fn sim<'s, 't>(
400 &'s mut self,
401 citizens: &[Citizen],
402 env: &'s mut Env<'_, 't>,
403 groups: &'s [Option<&'s AnimationGroup>],
404 adult: &'s [bool],
405 entities: &'s [EntityView],
406 ) -> (Sim<'s, 't>, &'s mut crate::work::jobs::Jobs) {
407 let _ = citizens;
408 let c = &mut *env.construction;
409 (
410 Sim {
411 characters: &mut self.characters,
412 states: &mut self.states,
413 groups,
414 adult,
415 rules: self.rules,
416 size: env.cells.size,
417 cells: &mut *env.cells,
418 regions: &self.regions,
419 sectors: &mut self.sectors,
420 terrain: env.terrain,
421 placed: &mut *env.placed,
422 templates: env.templates,
423 entities,
424 storages: &mut *env.storages,
425 storage_sites: env.sites,
426 materials: env.materials,
427 rng: &mut *env.rng,
428 stock: env.stock,
429 temperature: env.temperature,
430 professions: &c.professions,
431 workforce: &mut c.workforce,
432 site_templates: &c.templates,
433 sites: &mut c.sites,
434 homes: &mut c.homes,
435 attendance: &mut c.attendance,
436 attendance_list: &mut c.attendance_list,
437 healers: &mut c.healers,
438 happiness: &mut c.happiness,
439 calendar: c.calendar,
440 year: c.year,
441 fruits: &mut c.fruits,
442 wildlife: &mut *env.wildlife,
443 keep_piles: &mut c.keep_piles,
444 site_events: &mut c.site_events,
445 storage_changes: &mut c.storage_changes,
446 rebuilds: &mut c.rebuilds,
447 site_dt: 0,
448 water: &mut c.water,
449 game_flags: c.game_flags,
450 precipitation: c.precipitation,
451 population: c.population,
452 visitors: &mut c.visitors,
453 trading_posts: &mut c.trading_posts,
454 trade_value: &mut c.trade_value,
455 known_materials: &mut c.known_materials,
456 known: &mut c.known,
457 pending_roads: &mut c.pending_roads,
458 terraform_requests: &mut c.terraform_requests,
459 flatten_requests: &mut c.flatten_requests,
460 tornadoes: &mut c.tornadoes,
461 tornado_kills: &mut c.tornado_kills,
462 trackers: &mut c.trackers,
463 decals: &mut c.decals,
464 counters: &mut c.counters,
465 trade_goods: &c.trade_goods,
466 river: &c.river,
467 pathfinder: &mut self.pathfinder,
468 names: c.names.as_deref(),
469 cemeteries: &mut c.cemeteries,
470 tombstones: &mut c.tombstones,
471 burials: &mut c.burials,
472 site_list: &mut c.site_list,
473 events: Vec::new(),
474 piles: &mut c.piles,
475 claimed: &mut c.claimed_resources,
476 new_piles: &mut c.new_piles,
477 models_dirty: &mut c.models_dirty,
478 offers: Vec::new(),
479 offers_again: false,
480 removed: Vec::new(),
481 animation_events: Vec::new(),
482 produce_resume: None,
483 pasture_stage: false,
484 },
485 &mut c.jobs,
486 )
487 }
488
489 /// Adults without a school: the citizens professions count.
490 fn adults(&self, citizens: &[Citizen]) -> Vec<bool> {
491 citizens
492 .iter()
493 .zip(&self.states)
494 .map(|(c, s)| c.alive && c.age >= self.rules.thresholds.adult_age && s.school.is_none())
495 .collect()
496 }
497}