unbanished_game/town.rs
1//! The simulation context jobs and construction run in: [`Sim`] implements the job manager's
2//! work slots ([`WorkHost`]) and the building state callbacks ([`Callbacks`]), over the
3//! citizens, the map, the storages and the construction state. See docs/JOBS.md.
4//!
5//! This file holds the context's state and a few free helpers; its methods are split by topic:
6//! - `geometry`: cells, ground heights, reachability and work points;
7//! - `orders`: a building's workers and the actions given to citizens;
8//! - `sites`: building sites and buildings, marking them on the map, destroying them;
9//! - `building`: carrying materials to a site and building it;
10//! - `clearing`: clearing an area before building;
11//! - `piles`: loose piles of goods on the ground;
12//! - `storage`: picking up goods, finding a storage, dropping off, emptying a storage;
13//! - `callbacks` and `work_host`: the two trait implementations.
14
15mod building;
16mod callbacks;
17mod clearing;
18mod geometry;
19mod orders;
20mod piles;
21mod sites;
22mod storage;
23mod work_host;
24
25use std::collections::{BTreeMap, BTreeSet};
26
27use unbanished_formats::types::AnimationGroup;
28
29use crate::behaviour::activities::{EntityView, StorageGeometry, TownView};
30use crate::behaviour::agents::{CitizenRulesAi, CitizenState};
31use crate::behaviour::character::{Action, Character, Component, Message, MoveTo};
32use crate::nature::seeding::{Cells, Placed, Template};
33use crate::pathfind::nearest_neighbour;
34use crate::pathfind::WALKABLE;
35use crate::random::Random;
36use crate::scheduler::{seconds, ticks};
37use crate::sectors::SectorGraph;
38use crate::terrain::HeightGrid;
39use crate::work::construction::{
40 run, BuildWork, Callback, Callbacks, ClearWork, Gather, Machine, PickupWork, Pile, Site,
41 SiteTemplate,
42};
43use crate::work::jobs::{JobEvent, Jobs, Work, WorkHost, WorkKind, NESTED};
44use crate::work::professions::{Professions, Worker, Workforce};
45use crate::work::stock::{find_material_storage, RawMaterial, Storage, StorageSite};
46use crate::world::placement::{PlacementRules, Rect};
47
48/// `0x2001`: the construction works' registration mask (category 13).
49pub const CONSTRUCTION_MASK: u32 = 0x2001;
50
51/// [`Sim::haul`]'s endpoints and flags.
52#[derive(Default)]
53pub(crate) struct Haul {
54 pub target_entity: usize,
55 pub target_storage: usize,
56 pub target: [f32; 3],
57 pub source_storage: usize,
58 pub source_entity: usize,
59 pub source: [f32; 3],
60 pub material: usize,
61 pub amount: i32,
62 pub param: i32,
63 pub partial: bool,
64 pub complete_on_pickup: bool,
65 /// `param_14`: the hauler uses a tool (its work steps spend one, its loaded walk is
66 /// clip 5).
67 pub tool: bool,
68 /// Several materials at once (when `material` is null): the delivery drops everything
69 /// carried.
70 ///
71 /// Original: `FUN_1400cf700` adds each one to the pickup.
72 pub items: Vec<(usize, i32)>,
73}
74
75/// The world the citizens' update borrows (everything but the citizens themselves).
76pub struct Env<'a, 't> {
77 /// Wild animals (hunting).
78 pub wildlife: &'a mut crate::nature::wildlife::Wildlife,
79 /// The gameplay map.
80 pub cells: &'a mut Cells,
81 /// The placed objects.
82 pub placed: &'a mut Vec<Placed>,
83 /// The object templates.
84 pub templates: &'a [Template],
85 /// The ground's heights.
86 pub terrain: &'a HeightGrid<'t>,
87 /// The raw materials.
88 pub materials: &'a [RawMaterial],
89 /// The town's storages.
90 pub storages: &'a mut [Storage],
91 /// The storage sites.
92 pub sites: &'a [StorageSite],
93 /// The game's random numbers.
94 pub rng: &'a mut Random,
95 /// The construction manager.
96 pub construction: &'a mut crate::work::construction::Construction,
97 /// The stock manager's `(count, limit)` per slot from the last recount.
98 pub stock: [(i32, i32); 21],
99 // Game +0x130 → +0x18
100 /// The environment's temperature.
101 pub temperature: f32,
102}
103
104/// Everything a work slot or a state callback touches.
105pub struct Sim<'s, 't> {
106 /// The citizens' characters.
107 pub characters: &'s mut [Character],
108 /// The citizens' states.
109 pub states: &'s mut [CitizenState],
110 /// Each citizen's animation group.
111 pub groups: &'s [Option<&'s AnimationGroup>],
112 /// Adult and not at school (the citizens assignment counts).
113 pub adult: &'s [bool],
114 /// The citizens' AI rules.
115 pub rules: CitizenRulesAi,
116 /// The map's size in cells.
117 pub size: usize,
118 /// The gameplay map.
119 pub cells: &'s mut Cells,
120 /// The walkable region of each cell.
121 pub regions: &'s [u16],
122 /// The sector graph.
123 pub sectors: &'s mut SectorGraph,
124 /// The ground's heights.
125 pub terrain: &'s HeightGrid<'t>,
126 /// The placed objects.
127 pub placed: &'s mut Vec<Placed>,
128 /// The object templates.
129 pub templates: &'s [Template],
130 /// A view of each entity.
131 pub entities: &'s [EntityView],
132 /// The town's storages.
133 pub storages: &'s mut [Storage],
134 /// The storage sites.
135 pub storage_sites: &'s [StorageSite],
136 /// The raw materials.
137 pub materials: &'s [RawMaterial],
138 /// The game's random numbers.
139 pub rng: &'s mut Random,
140 /// The stock manager's `(count, limit)` per slot from the last recount.
141 pub stock: [(i32, i32); 21],
142 /// The environment's temperature.
143 pub temperature: f32,
144 /// The professions.
145 pub professions: &'s Professions,
146 /// The workers assigned to each workplace.
147 pub workforce: &'s mut Workforce,
148 /// The building templates.
149 pub site_templates: &'s [SiteTemplate],
150 /// The buildings, by entity.
151 pub sites: &'s mut BTreeMap<usize, Site>,
152 /// The homes, by entity.
153 pub homes: &'s mut BTreeMap<usize, crate::people::life::Home>,
154 /// Who attends each service building, by entity.
155 pub attendance: &'s mut BTreeMap<usize, crate::work::construction::Attendance>,
156 /// The service buildings that people attend.
157 pub attendance_list: &'s mut Vec<usize>,
158 /// The herbalists and hospitals.
159 pub healers: &'s mut Vec<usize>,
160 /// The buildings that raise happiness nearby.
161 pub happiness: &'s mut Vec<usize>,
162 /// The calendar's seconds into the year.
163 pub calendar: f32,
164 /// The current year.
165 pub year: u32,
166 /// The orchards' fruit, by entity.
167 pub fruits: &'s mut BTreeMap<usize, crate::production::orchard::Fruit>,
168 /// The animals (livestock and their pastures).
169 pub wildlife: &'s mut crate::nature::wildlife::Wildlife,
170 /// Whether removing a resource leaves its piles behind, by resource.
171 pub keep_piles: &'s mut BTreeMap<usize, bool>,
172 /// Building events for the event log: `(kind, argument, entity)`.
173 pub site_events: &'s mut Vec<(i32, i32, usize)>,
174 /// Storages that opened or closed: `(entity, opened)`.
175 pub storage_changes: &'s mut Vec<(usize, bool)>,
176 /// The buildings to build again after they were destroyed.
177 pub rebuilds: &'s mut Vec<crate::work::destroy::Rebuild>,
178 /// The town's water sources (wells and shore points).
179 pub water: &'s mut crate::disasters::fire::Water,
180 // Game +0xd0
181 /// The game's debug flags (all four disaster bits are set when disasters are off).
182 pub game_flags: u32,
183 // +0x10
184 /// The sky's state is precipitation (environment = 0).
185 pub precipitation: bool,
186 // +0xa8
187 /// The town's population.
188 pub population: i32,
189 // +0x1a8; +0x1a0
190 /// The visitors' timer and the time of the last visitor.
191 pub visitors: &'s mut (f32, i64),
192 // +0xe8
193 /// The planned road cells, each with its road-building work.
194 pub pending_roads: &'s mut BTreeMap<i32, i32>,
195 /// The pending changes to the ground.
196 pub terraform_requests: &'s mut Vec<crate::world::terraform::Terraform>,
197 /// The rectangles to flatten: `[x0, y0, x1, y1]`.
198 pub flatten_requests: &'s mut Vec<[i32; 4]>,
199 /// The tornadoes, by entity.
200 pub tornadoes: &'s mut BTreeMap<usize, crate::disasters::tornado::Tornado>,
201 /// The citizens a tornado killed.
202 pub tornado_kills: &'s mut Vec<usize>,
203 /// The production trackers, by entity.
204 pub trackers: &'s mut BTreeMap<usize, crate::work::tracker::Tracker>,
205 /// The ground decals of building sites, by entity.
206 pub decals: &'s mut BTreeMap<usize, crate::work::construction::Decal>,
207 /// The counts of goods made and used.
208 pub counters: &'s mut crate::work::tracker::StockCounters,
209 // +0x30; +0x1ac
210 /// The town's trading posts.
211 pub trading_posts: &'s mut Vec<usize>,
212 /// The total value traded.
213 pub trade_value: &'s mut i32,
214 // +0x110; +0x120
215 /// The raw materials the town knows; `known` holds the crops, orchard trees and livestock it
216 /// knows.
217 ///
218 /// Original: `FUN_140097330`, `FUN_140096ef0`.
219 pub known_materials: &'s mut Vec<usize>,
220 /// The crops, orchard trees and livestock the town knows.
221 pub known: &'s mut Vec<usize>,
222 /// The goods traders can bring.
223 pub trade_goods: &'s [crate::commerce::trade::TradeGood],
224 /// The river's path.
225 pub river: &'s [[f32; 2]],
226 /// The path manager (the trader boats' water paths).
227 pub pathfinder: &'s mut crate::pathfind::Pathfinder,
228 /// The citizens' name databases (the merchants' names).
229 pub names: Option<&'s (
230 unbanished_formats::names::NameDatabase,
231 unbanished_formats::names::NameDatabase,
232 )>,
233 /// The scheduled update's elapsed time (ticks) for the site callbacks.
234 pub site_dt: i64,
235 /// The cemeteries.
236 pub cemeteries: &'s mut Vec<usize>,
237 /// The tombstones, with the time each one stays.
238 pub tombstones: &'s mut BTreeMap<usize, i64>,
239 /// The burials waiting: `(cemetery, cell)`.
240 pub burials: &'s mut Vec<(usize, i32, i64)>,
241 /// The buildings that have a site record.
242 pub site_list: &'s mut Vec<usize>,
243 /// The job events from this update.
244 pub events: Vec<JobEvent>,
245 /// The piles, by entity.
246 pub piles: &'s mut BTreeMap<usize, Pile>,
247 /// The resources a work has claimed.
248 pub claimed: &'s mut std::collections::BTreeSet<usize>,
249 /// The piles made in this update.
250 pub new_piles: &'s mut Vec<usize>,
251 /// Set when a model changed and must be drawn again.
252 pub models_dirty: &'s mut bool,
253 /// Works a ClearArea try asked the manager to offer ([`WorkHost::take_offers`]).
254 pub offers: Vec<i32>,
255 /// Scratch for `Sim::seeder` (planting removes nothing and plays no sounds).
256 pub removed: Vec<usize>,
257 /// The animation events to play: `(entity, effect)`.
258 pub animation_events: Vec<(usize, String)>,
259 /// Whether the offers get a second try (as an auto-pickup's do).
260 ///
261 /// Original: `FUN_1400fdaf0(.., 1)`.
262 pub offers_again: bool,
263 /// A ConsumeProduce try waiting on its pile offers ([`WorkHost::resume`]).
264 pub(crate) produce_resume: Option<crate::work::produce::ProduceResume>,
265 /// A pasture try waiting on its product pickups' offers ([`Sim::pasture_try`]).
266 pub(crate) pasture_stage: bool,
267}
268
269/// A pile's work category mask from its material's flags.
270///
271/// Original: `FUN_14012e950`.
272pub fn pile_mask(flags: u32) -> u32 {
273 for (bit, mask) in [
274 (5, 2),
275 (6, 4),
276 (10, 0x10),
277 (12, 0x40),
278 (11, 0x20),
279 (13, 0x100),
280 (16, 0x200),
281 (9, 8),
282 ] {
283 if flags >> bit & 1 != 0 {
284 return mask;
285 }
286 }
287 if flags >> 14 & 1 != 0 {
288 0x80
289 } else {
290 1
291 }
292}
293
294/// `FUN_14011ce30`'s clearing mask bit for a resource's raw material: logs `0x400`, iron
295/// `0x1000`, stone `0x800`, else 1.
296fn clear_mask(flags: u32) -> u32 {
297 if flags >> 10 & 1 != 0 {
298 0x400
299 } else if flags >> 12 & 1 != 0 {
300 0x1000
301 } else if flags >> 11 & 1 != 0 {
302 0x800
303 } else {
304 1
305 }
306}
307
308/// `MapComponent::IsAnimating` per placed entity.
309pub fn animating(placed: &[Placed], templates: &[Template]) -> Vec<bool> {
310 placed
311 .iter()
312 .map(|p| {
313 p.alive
314 && p.animation.as_ref().is_some_and(|pb| {
315 templates[p.template]
316 .animations
317 .get(p.variant)
318 .and_then(Option::as_ref)
319 .and_then(|g| g.clips.get(pb.clip))
320 .is_some_and(|clip| pb.is_animating(clip))
321 })
322 })
323 .collect()
324}
325
326/// The ground at a cell's centre, on the terrain only (bridge floors are skipped).
327///
328/// Original: `FUN_1400a48b0` with `param_4` 1.
329pub fn cell_ground(size: usize, terrain: &HeightGrid, cell: i32) -> [f32; 3] {
330 let n = size as i32;
331 let h = (n >> 1) as f32 - 0.5;
332 let (x, y) = ((cell % n) as f32 - h, (cell / n) as f32 - h);
333 let mut normal = [0.0; 3];
334 [x, y, terrain.ground(x, y, &mut normal)]
335}
336
337/// The ground at a cell's centre: on a bridge's floor where one covers the cell above the
338/// terrain, else on the terrain.
339///
340/// Original: `FUN_1400a48b0` with `param_4` 0, as nearly every caller passes.
341pub fn floor_ground(
342 floors: &crate::world::floor::Floors,
343 size: usize,
344 terrain: &HeightGrid,
345 cell: i32,
346) -> [f32; 3] {
347 let n = size as i32;
348 let h = (n >> 1) as f32 - 0.5;
349 let (x, y) = ((cell % n) as f32 - h, (cell / n) as f32 - h);
350 [x, y, floors.ground(size, terrain, x, y)]
351}
352
353/// The amount still to clear in an entity's area, over a grid of `n × n` cells that maps each
354/// cell to its object.
355///
356/// Original: `FUN_14011d800`.
357pub fn clear_remaining(objects: &[Option<usize>], n: i32, placed: &Placed, e: usize) -> i32 {
358 let (x, y) = placed.cell;
359 let (w, h) = placed.footprint;
360 let mut count = 0;
361 for cy in y..y + h {
362 for cx in x..x + w {
363 if objects[(cy * n + cx) as usize].is_some_and(|o| o != e) {
364 count += 1;
365 }
366 }
367 }
368 count
369}