Skip to main content

unbanished_game/commerce/trade/
visits.rs

1//! A trading post's states: a merchant's arrival, stay and departure, its messages and the goods it brings.
2
3use super::*;
4
5// The rows are at TradeDescription +0x58 (count +0x60, 0x14 bytes each); the population is
6// Game +0xf0 → +0xa8.
7/// The trade row for a population: the first row whose population it is below, or the last row
8/// (also when the population is below 0).
9///
10/// Measured: `tools/emu/trade_timer.py` (the original on 2,000 cases).
11///
12/// Original: `FUN_14005be50`.
13pub fn trade_row(rows: &[TradeRow], population: i32) -> usize {
14    rows.iter()
15        .position(|r| 0 <= population && population < r.population)
16        .unwrap_or(rows.len().saturating_sub(1))
17}
18
19// Row +0x4 months, +0x8 range; the result goes to TradeComponent +0x78.
20/// The time to the next merchant: the row's months plus `RandFloatTol` × its range, × 300 s.
21///
22/// Measured: `tools/emu/trade_timer.py` (the original on 2,000 cases).
23///
24/// Original: `FUN_14005bdb0`.
25pub fn next_merchant(row: &TradeRow, rng: &mut crate::random::Random) -> i64 {
26    let f = rng.rand_float_tol();
27    ticks((f * row.range + row.months) * PERIOD)
28}
29
30impl Sim<'_, '_> {
31    /// TradeComponent's activation (slot `+0x30`, `FUN_14005cb30`): the post joins the town's
32    /// and its merchants get their names (`FUN_14005cb80`).
33    pub(crate) fn trade_activate(&mut self, e: usize) {
34        let Some(site) = self.sites.get(&e) else {
35            return;
36        };
37        if site.trade.is_some() {
38            return;
39        }
40        let Some(d) = self.site_templates[site.template].trade.clone() else {
41            return;
42        };
43        self.trading_posts.push(e);
44        let trade = Trade::new(&d, self.rng, self.names);
45        self.sites.get_mut(&e).unwrap().trade = Some(trade);
46    }
47
48    pub(super) fn trade_desc(&self, e: usize) -> Option<&TradeTemplate> {
49        self.site_templates[self.sites.get(&e)?.template]
50            .trade
51            .as_ref()
52    }
53
54    pub(crate) fn trade(&mut self, e: usize) -> Option<&mut Trade> {
55        self.sites.get_mut(&e)?.trade.as_mut()
56    }
57
58    /// The trade row for the town's population now.
59    ///
60    /// Original: `FUN_14005be50`.
61    pub(super) fn trade_row(&self, d: &TradeTemplate) -> usize {
62        trade_row(&d.rows, self.population)
63    }
64
65    /// State 2 enter (`FUN_14005b530`): with the post's workplace on and no work yet, its
66    /// TradeWork; then the time to the next merchant.
67    pub(crate) fn trade_enter2(&mut self, jobs: &mut crate::work::jobs::Jobs, e: usize) {
68        let id = self.sites[&e].work_id;
69        if !jobs.works.contains_key(&id)
70            && self.workforce.workplaces.get(&e).is_some_and(|w| w.enabled)
71        {
72            self.set_trade_work(jobs, e);
73        }
74        let Some(d) = self.trade_desc(e).cloned() else {
75            return;
76        };
77        let t = next_merchant(&d.rows[self.trade_row(&d)], self.rng);
78        if let Some(tr) = self.trade(e) {
79            tr.timer = t;
80        }
81    }
82
83    /// State 2 update (`FUN_14005b3c0`): when the time is out, the merchant's boat sets out
84    /// and the post waits for it (0x12).
85    pub(crate) fn trade_update2(&mut self, e: usize, dt: i64) {
86        let Some(tr) = self.trade(e) else { return };
87        tr.timer -= dt;
88        if 0 < tr.timer {
89            return;
90        }
91        let Some(boat_t) = self.trade_desc(e).map(|d| d.boat) else {
92            return;
93        };
94        let boat = self.add_boat(boat_t, e);
95        if let Some(tr) = self.trade(e) {
96            tr.boat = boat;
97        }
98        self.machine(e).request(0x12);
99    }
100
101    /// The transitions to 3 (`FUN_14005bac0`): the post leaves the town's; its boat sails off.
102    pub(crate) fn trade_leave(&mut self, e: usize) {
103        self.trading_posts.retain(|&p| p != e);
104        if let Some(boat) = self.trade(e).and_then(|t| t.boat) {
105            self.boat_orphan(boat);
106            let tr = self.trade(e).unwrap();
107            tr.offers.clear();
108            tr.merchant = -1;
109            tr.boat = None;
110        }
111    }
112
113    /// State 0x13 enter (`FUN_14005b160`): the merchant's goods (`FUN_14005bee0`); it stays
114    /// 900 s; trading by itself on arrival.
115    pub(crate) fn trade_enter13(&mut self, e: usize) {
116        self.merchant_goods(e);
117        if let Some(tr) = self.trade(e) {
118            tr.timer = ticks(STAY);
119        }
120        if self.trade(e).is_some_and(|t| t.mode == 1) {
121            self.trade_automatically(e);
122        }
123    }
124
125    /// State 0x13 exit (`FUN_14005b030`): trading by itself on leaving; the boat casts off.
126    pub(crate) fn trade_exit13(&mut self, e: usize) {
127        if self.trade(e).is_some_and(|t| t.mode == 2) {
128            self.trade_automatically(e);
129        }
130        if let Some(boat) = self.trade(e).and_then(|t| t.boat) {
131            self.boat_message(boat, 0);
132        }
133        let tr = self.trade(e).unwrap();
134        tr.boat = None;
135        tr.offers.clear();
136        tr.merchant = -1;
137    }
138
139    /// State 0x13 update (`FUN_14005b0e0`): the stay runs out, unless the trade window holds it.
140    pub(crate) fn trade_update13(&mut self, e: usize, dt: i64) {
141        let Some(tr) = self.trade(e) else { return };
142        tr.timer -= dt;
143        if tr.timer < 1 && !tr.held {
144            self.machine(e).request(2);
145        }
146    }
147
148    /// The post's state messages: 9 in 0x12 the boat docked: event 13 at severity 2, → 0x13; 0xb in
149    /// 0x12 it went without docking: → 2; 0xa in 0x13 the merchant leaves now.
150    ///
151    /// Original: `FUN_14005b1b0`, `FUN_14005b320`, `FUN_14005bba0`.
152    pub fn trade_message(&mut self, e: usize, msg: i32) {
153        if self.trade(e).is_none() || self.machine(e).index < 0 {
154            return;
155        }
156        match (self.machine(e).state, msg) {
157            (0x12, crate::commerce::boat::DOCKED_MESSAGE) => {
158                self.site_events.push((ARRIVED, 2, e));
159                self.machine(e).request(0x13);
160            }
161            (0x12, crate::commerce::boat::GONE_MESSAGE) => {
162                if let Some(tr) = self.trade(e) {
163                    tr.boat = None;
164                }
165                self.machine(e).request(2);
166            }
167            (0x13, 0xa) => self.machine(e).request(2),
168            _ => {}
169        }
170    }
171
172    /// `FUN_14005bee0`: a random merchant (`Rand(merchants)`); what was ordered from it, else
173    /// the goods it deals in (`FUN_140059fd0`); a single order is used up. Then `merchant lots
174    /// / the row's lot divisor` lots (at least one) of a random good: `max(lot / amount
175    /// divisor, smallest lot)` (at least one) of it at its value (× 1.25 when ordered, at least
176    /// one), added to its offer if it has one.
177    pub(super) fn merchant_goods(&mut self, e: usize) {
178        let Some(d) = self.trade_desc(e).cloned() else {
179            return;
180        };
181        let m = self.rng.rand_below(d.merchants.len() as u32) as usize;
182        let row = d.rows[self.trade_row(&d)];
183        let tr = self.trade(e).unwrap();
184        tr.offers.clear();
185        tr.merchant = m as i32;
186        let order = tr.orders.get(m).cloned().unwrap_or_default();
187        let ordered = order.state != 0 && !order.goods.is_empty();
188        let list = if ordered {
189            order.goods.clone()
190        } else {
191            self.merchant_list(&d.merchants[m])
192        };
193        if order.state != 2 {
194            if let Some(o) = self.trade(e).unwrap().orders.get_mut(m) {
195                o.goods.clear();
196                o.state = 0;
197            }
198        }
199        let lots = (d.merchants[m].lots / row.lot_divisor.max(1)).max(1);
200        for _ in 0..lots {
201            // Deviation: a merchant with nothing to sell brings nothing (the original reads
202            // an empty list).
203            if list.is_empty() {
204                break;
205            }
206            let k = self.rng.rand_below(list.len() as u32) as usize;
207            let good = list[k];
208            let v = &self.trade_goods[good].value;
209            let amount = (v.lot / row.amount_divisor.max(1)).max(v.min_lot).max(1);
210            let mut value = v.value;
211            if ordered {
212                value = (value as f32 * ORDERED) as i32;
213            }
214            let value = value.max(1);
215            let tr = self.trade(e).unwrap();
216            match tr.offers.iter_mut().find(|o| o.good == good) {
217                Some(o) => o.amount += amount,
218                None => tr.offers.push(Offer {
219                    good,
220                    value,
221                    amount,
222                }),
223            }
224        }
225    }
226
227    // slot +0x70
228    /// The TradeWork switched (the post's work button): the workplace on with the work, or off
229    /// without it.
230    ///
231    /// Original: `FUN_14005c960`.
232    pub fn toggle_trade_work(&mut self, jobs: &mut crate::work::jobs::Jobs, e: usize) {
233        let on = !self.workforce.workplaces.get(&e).is_some_and(|w| w.enabled);
234        if let Some(tr) = self.trade(e) {
235            tr.working = on;
236        }
237        if on {
238            self.set_trade_work(jobs, e);
239        } else {
240            self.remove_work(jobs, e);
241        }
242        self.enable_workplace(e, on);
243    }
244}