Skip to main content

unbanished_game/work/
stock.rs

1//! StorageComponent ledgers and town storage search (`Game`). See docs/CITIZEN-AI.md and
2//! docs/RESOURCE-PRODUCTION-FLOW.md.
3mod search;
4pub use search::{find_material_storage, find_storage, scan_storages};
5
6// Game +0xf0
7
8use crate::random::Random;
9
10/// RawMaterialDescription: a template shared by ledger entries, not a stored entity.
11#[derive(Debug, Clone, Default)]
12pub struct RawMaterial {
13    /// The resource reference.
14    pub reference: String,
15    // +0x48
16    /// Weighted storage units per item.
17    pub size: i32,
18    // +0x5c
19    /// Category flags (distinct from the search's category index).
20    pub flags: u32,
21    // +0x54; sent to Citizen message 1 by FUN_1400c2540.
22    /// How many uses a tool has (for tools).
23    pub tool_uses: i32,
24    // +0x58; FUN_140094410 prefers the last eligible entry with this set.
25    /// Whether a food search prefers this material.
26    pub preferred: bool,
27    // +0x4c
28    /// A crop field leaves a pile on every this-many cells.
29    ///
30    /// Original: `FUN_14011f7e0`.
31    pub pile_spacing: i32,
32    // +0x40
33    /// The size of a pasture's product pile.
34    ///
35    /// Original: `FUN_14012bcb0`.
36    pub pile_amount: i32,
37}
38
39// +0x28
40/// A StorageComponent entry (16 bytes): the raw material, the count and the reserved count.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Item {
43    /// The raw material.
44    pub material: usize,
45    /// How many are stored.
46    pub count: i32,
47    /// How many are reserved.
48    pub reserved: i32,
49}
50
51/// A storage: its capacity and the goods in it, with their reservations.
52#[derive(Debug, Clone, Default)]
53pub struct Storage {
54    // +0x38; +0x3c
55    /// The capacity.
56    pub capacity: i32,
57    /// The flags of the goods it accepts.
58    pub accepts: u32,
59    /// The goods in it.
60    pub items: Vec<Item>,
61}
62
63impl Storage {
64    /// Weighted occupancy (includes reserved goods).
65    ///
66    /// Original: `FUN_1401323e0`.
67    pub fn used(&self, materials: &[RawMaterial]) -> i32 {
68        self.items.iter().fold(0i32, |n, e| {
69            n.wrapping_add(materials[e.material].size.wrapping_mul(e.count))
70        })
71    }
72
73    /// Whether `count` units of a material fit in the storage.
74    ///
75    /// Original: `FUN_140132250`, `FUN_140131a30`.
76    pub fn fits(&self, materials: &[RawMaterial], material: usize, count: i32) -> bool {
77        self.accepts & materials[material].flags != 0
78            && materials[material]
79                .size
80                .wrapping_mul(count)
81                .wrapping_add(self.used(materials))
82                <= self.capacity
83    }
84
85    /// The entry of a material.
86    pub fn entry(&self, material: usize) -> Option<&Item> {
87        self.items.iter().find(|e| e.material == material)
88    }
89
90    /// Quantity available for another task.
91    ///
92    /// Original: `FUN_14011bc90`.
93    pub fn available(&self, material: usize) -> i32 {
94        self.entry(material)
95            .map_or(0, |e| e.count.wrapping_sub(e.reserved))
96    }
97
98    /// Merge in place, otherwise append with no reservation.
99    ///
100    /// Original: `FUN_1401324d0`.
101    pub fn add(&mut self, material: usize, count: i32) {
102        if let Some(e) = self.items.iter_mut().find(|e| e.material == material) {
103            e.count = e.count.wrapping_add(count);
104        } else {
105            self.items.push(Item {
106                material,
107                count,
108                reserved: 0,
109            });
110        }
111    }
112
113    /// Subtract, erase exactly-zero entries preserving order; no clamp.
114    ///
115    /// Original: `FUN_140132620`.
116    pub fn remove(&mut self, material: usize, count: i32) {
117        if let Some(i) = self.items.iter().position(|e| e.material == material) {
118            self.items[i].count = self.items[i].count.wrapping_sub(count);
119            if self.items[i].count == 0 {
120                self.items.remove(i);
121            }
122        }
123    }
124
125    /// Reserve when building a task, not on arrival.
126    ///
127    /// Original: `FUN_1400cb980`, `FUN_1400cf700`.
128    pub fn reserve(&mut self, material: usize, count: i32) {
129        if let Some(e) = self.items.iter_mut().find(|e| e.material == material) {
130            e.reserved = e.reserved.wrapping_add(count);
131        }
132    }
133
134    /// Release a reservation, when a task is cancelled or before the goods are used or moved.
135    ///
136    /// Original: `FUN_1400cb300`, `FUN_1400cf140` (cancel).
137    pub fn unreserve(&mut self, material: usize, count: i32) {
138        if let Some(e) = self.items.iter_mut().find(|e| e.material == material) {
139            e.reserved = e.reserved.wrapping_sub(count).max(0);
140        }
141    }
142
143    /// Search category 0 food, 1 fuel, 2 tool, 3 herb, 4 clothing. Even a single eligible
144    /// unpreferred material draws Rand(1).
145    ///
146    /// Original: `FUN_140094410`.
147    pub fn find_item(
148        &self,
149        materials: &[RawMaterial],
150        category: u32,
151        rng: &mut Random,
152    ) -> Option<usize> {
153        let bit = *[5, 6, 9, 13, 14].get(category as usize)?;
154        let eligible = |e: &&Item| {
155            materials[e.material].flags & (1 << bit) != 0 && e.count.wrapping_sub(e.reserved) > 0
156        };
157        let count = self.items.iter().filter(eligible).count();
158        if count == 0 {
159            return None;
160        }
161        let preferred = self
162            .items
163            .iter()
164            .filter(eligible)
165            .enumerate()
166            .filter(|(_, e)| materials[e.material].preferred)
167            .map(|(i, _)| i)
168            .last();
169        let index = preferred.unwrap_or_else(|| rng.rand_below(count as u32) as usize);
170        self.items
171            .iter()
172            .filter(eligible)
173            .nth(index)
174            .map(|e| e.material)
175    }
176}
177
178// +0x10/+0x18
179/// Registration in the manager's ordinary (`+0/+8`) or market list.
180#[derive(Debug, Clone)]
181pub struct StorageSite {
182    /// The entity.
183    pub entity: usize,
184    /// Its storage.
185    pub storage: usize,
186    // +0x20; +0x3c
187    /// StorageLocationDescription; zero uses StorageComponent.
188    pub location_flags: u32,
189    // +0x28
190    /// RadiusDescription; Some marks a market-list entry.
191    pub radius: Option<i32>,
192}
193
194/// The result of a storage search: the storage and what it offers.
195#[derive(Debug, Clone, PartialEq)]
196pub struct StorageMatch {
197    /// The storage site.
198    pub site: usize,
199    /// The storage.
200    pub storage: usize,
201    /// The raw material it offers.
202    pub material: usize,
203    /// The point to walk to.
204    pub target: [f32; 3],
205}
206
207/// What the storage search needs from the map: distances, reach and the markets' areas.
208///
209/// Original: the map queries of `FUN_140093200`.
210pub trait StorageSearchMap {
211    /// The cell a citizen walks to at an entity.
212    fn entrance(&mut self, entity: usize, rng: &mut Random) -> i32;
213    /// The path-rank distance between two cells.
214    fn rank(&mut self, a: i32, b: i32) -> i32;
215    /// A market's position, if it can be reached.
216    fn market_position(
217        &mut self,
218        entity: usize,
219        from: i32,
220        rng: &mut Random,
221    ) -> Option<(i32, [f32; 3])>;
222    /// A storage's drop point, if it can be reached from `from`.
223    fn storage_position(&mut self, entity: usize, from: i32) -> Option<(i32, [f32; 3])>;
224}
225
226// ConsumeRawMaterial: vtable 0x140166050.
227/// The `ConsumeRawMaterial` action: take goods out of a storage. Reserved requests skip the check
228/// that the goods are there; the changes happen in list order.
229///
230/// Original: `FUN_1400cb420`.
231pub fn consume_stored(storage: &mut Storage, items: &[(usize, i32)], reserved: bool) -> bool {
232    // The stock manager's `+0xc` counts are kept by the caller (`character::World::used`).
233    if items.is_empty() {
234        return false;
235    }
236    for &(material, count) in items {
237        if reserved {
238            storage.unreserve(material, count);
239        } else if storage.available(material) < count {
240            return false;
241        }
242        storage.remove(material, count);
243    }
244    true
245}
246
247// PickupStoredRawMaterial: vtable 0x1401663a0; FUN_1400cf5a0 serialises the citizen and source
248// references, these material and count pairs, and partial.
249/// The `PickupStoredRawMaterial` action: a citizen takes goods from a storage. A request of zero
250/// or less takes as much as the citizen can still carry (by weight).
251///
252/// Original: `FUN_1400cf210`.
253pub fn pickup_stored(
254    source: &mut Storage,
255    carried: &mut Storage,
256    materials: &[RawMaterial],
257    items: &[(usize, i32)],
258    partial: bool,
259) -> bool {
260    for &(material, requested) in items {
261        let mut count = if requested > 0 {
262            requested
263        } else {
264            (carried.capacity - carried.used(materials)) / materials[material].size
265        };
266        let available = source.entry(material).map_or(0, |e| e.count);
267        if partial {
268            count = count.min(available);
269            if count == 0 {
270                return false;
271            }
272        } else if available < count {
273            return false;
274        }
275        source.unreserve(material, count);
276        source.remove(material, count);
277        carried.add(material, count);
278    }
279    true
280}
281
282/// Hand out up to `cap` single units of the candidates matching `mask`, round-robin over the
283/// candidates and one unit per storage per pass, until the cap is reached or a pass adds nothing.
284///
285/// Original: `FUN_140096b30`.
286pub fn distribute(
287    storages: &mut [Storage],
288    materials: &[RawMaterial],
289    candidates: &[usize],
290    mask: u32,
291    cap: i32,
292) {
293    let list: Vec<usize> = candidates
294        .iter()
295        .copied()
296        .filter(|&c| materials[c].flags & mask != 0)
297        .collect();
298    if list.is_empty() || cap <= 0 {
299        return;
300    }
301    let mut given = 0;
302    loop {
303        let mut progressed = false;
304        for s in storages.iter_mut() {
305            if given < cap {
306                let m = list[given as usize % list.len()];
307                if s.fits(materials, m, 1) {
308                    s.add(m, 1);
309                    given += 1;
310                    progressed = true;
311                }
312            }
313        }
314        if !progressed || cap <= given {
315            break;
316        }
317    }
318}
319
320// Game +0xf0 → +0x170
321/// The Status Bar stock slots (`Game →`, 0x20 bytes each): wood, stone, iron, firewood, tools,
322/// food, herbs, clothes, alcohol, coal, textile, custom 0..9.
323pub const STOCK_SLOTS: usize = 21;
324
325/// Which slot a raw material counts towards, in the original's test order (food, then firewood,
326/// then single flag bits).
327///
328/// Original: `FUN_14008f3a0`.
329pub fn stock_slot(flags: u32) -> Option<usize> {
330    if flags & 0x20 != 0 {
331        return Some(5);
332    }
333    if flags & 0x80 != 0 {
334        return Some(3);
335    }
336    const BITS: [(u32, usize); 18] = [
337        (8, 9),
338        (9, 4),
339        (10, 0),
340        (11, 1),
341        (12, 2),
342        (13, 6),
343        (14, 7),
344        (17, 8),
345        (16, 10),
346        (18, 11),
347        (19, 12),
348        (20, 13),
349        (21, 14),
350        (22, 15),
351        (23, 16),
352        (24, 17),
353        (25, 18),
354        (26, 19),
355    ];
356    for (bit, slot) in BITS {
357        if flags >> bit & 1 != 0 {
358            return Some(slot);
359        }
360    }
361    if flags >> 27 & 1 != 0 {
362        return Some(20);
363    }
364    None
365}
366
367/// Recompute the stock table from every storage.
368pub fn stock_table(storages: &[Storage], materials: &[RawMaterial]) -> [i32; STOCK_SLOTS] {
369    let mut table = [0; STOCK_SLOTS];
370    for s in storages {
371        for e in &s.items {
372            let (m, n) = (e.material, e.count);
373            if let Some(slot) = stock_slot(materials[m].flags) {
374                table[slot] += n;
375            }
376        }
377    }
378    table
379}
380
381#[cfg(test)]
382mod tests;