unbanished_game/commerce/trade.rs
1//! Trade: TradeComponent (the trading post) and its merchants. See docs/TRADE.md.
2//!
3//! Now and then (more often in bigger towns) a merchant's boat comes up the river; while it is
4//! docked the merchant's goods can be traded for the post's. A merchant brings what was ordered
5//! from it, else lots of the goods it deals in.
6//!
7//! Original: `FUN_14005cd90`, `FUN_14005cfb0`.
8mod deals;
9mod visits;
10
11pub use visits::{next_merchant, trade_row};
12
13// vtable 0x140160df0
14
15use unbanished_formats::game::{Merchant, TradeRow, ValueDescription};
16
17use crate::scheduler::ticks;
18use crate::town::Sim;
19use crate::work::construction::Callbacks;
20
21/// `DAT_140178934`.
22const PERIOD: f32 = 300.0;
23/// `DAT_140178944`: how long a merchant stays (s).
24const STAY: f32 = 900.0;
25/// `DAT_140178858`: ordered goods cost more.
26const ORDERED: f32 = 1.25;
27/// Event type 13: a merchant arrived.
28const ARRIVED: i32 = 0xd;
29
30/// A resolved TradeDescription.
31#[derive(Debug, Clone, Default, PartialEq)]
32pub struct TradeTemplate {
33 // +0x30
34 /// The boat template.
35 pub boat: usize,
36 /// The merchants.
37 pub merchants: Vec<Merchant>,
38 /// The rows of the trade window.
39 pub rows: Vec<TradeRow>,
40 // +0x38
41 /// The categories' flags.
42 pub categories: Vec<u32>,
43 // +0x20; +0x28
44 /// The categories' icon and name keys (the trade window's), in the description's sprite sheet
45 /// and string table.
46 pub labels: Vec<(String, String)>,
47 /// The sprite sheet of the icons.
48 pub sprites: Option<String>,
49 /// The string table of the names.
50 pub strings: Option<String>,
51}
52
53/// A good with a ValueDescription: its template, its raw material (none for seeds and
54/// livestock) and value.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct TradeGood {
57 /// The template.
58 pub template: usize,
59 /// The raw material; none for seeds and livestock.
60 pub material: Option<usize>,
61 /// The value.
62 pub value: ValueDescription,
63}
64
65// +0x30
66/// A merchant's order (TradeComponent, 0x20 bytes): the merchant's name, the goods ordered and its
67/// state (0 none, 1 once, 2 every time).
68#[derive(Debug, Clone, Default, PartialEq, Eq)]
69pub struct Order {
70 /// The merchant's name.
71 pub name: String,
72 /// The goods ordered.
73 pub goods: Vec<usize>,
74 /// The order's state: 0 none, 1 once, 2 every time.
75 pub state: i32,
76}
77
78// +0x50
79/// A good the merchant brought (0x10 bytes): the good, its value and how many.
80#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
81pub struct Offer {
82 /// The good.
83 pub good: usize,
84 /// Its value.
85 pub value: i32,
86 /// How many.
87 pub amount: i32,
88}
89
90// +0x28; +0x2c; +0x30; +0x40; +0x50; +0x60; +0x70; +0x71; +0x78; +0x80
91/// TradeComponent: when it trades by itself (0 never, 1 when a merchant arrives, 2 when it leaves),
92/// the merchant docked (−1), the orders by merchant, the automatic trades by category (flags,
93/// index, amount), the merchant's goods, the goods to keep at the post by raw material, TradeWork
94/// on, held (the trade window is open), the time to the next merchant or until it leaves, the boat.
95#[derive(Debug, Clone, Default, PartialEq, Eq)]
96pub struct Trade {
97 /// When it trades by itself: 0 never, 1 when a merchant arrives, 2 when it leaves.
98 pub mode: i32,
99 /// The merchant docked (−1 none).
100 pub merchant: i32,
101 /// The orders, by merchant.
102 pub orders: Vec<Order>,
103 /// The automatic trades by category: `(flags, index, amount)`.
104 pub automatic: Vec<(u32, i32, i32)>,
105 /// The merchant's goods.
106 pub offers: Vec<Offer>,
107 /// The goods to keep at the post, by raw material.
108 pub keep: std::collections::BTreeMap<usize, i32>,
109 /// Whether the post's hauling work is on.
110 pub working: bool,
111 /// Whether the trade window is open.
112 pub held: bool,
113 /// The time to the next merchant, or until it leaves.
114 pub timer: i64,
115 /// The boat, if any.
116 pub boat: Option<usize>,
117}
118
119impl Trade {
120 /// The activation: every merchant a name (`Rand(2)`: 0 gives a woman's name, else a man's)
121 /// and no order; every category no automatic trade.
122 ///
123 /// Original: `FUN_14005cb80`.
124 pub fn new(
125 t: &TradeTemplate,
126 rng: &mut crate::random::Random,
127 names: Option<&(
128 unbanished_formats::names::NameDatabase,
129 unbanished_formats::names::NameDatabase,
130 )>,
131 ) -> Trade {
132 let orders = t
133 .merchants
134 .iter()
135 .map(|_| {
136 // `sete` after `Rand(2)` (0x14005cbfe): 0 sets FUN_1400aa130's female flag.
137 let female = rng.rand_below(2) == 0;
138 let name = names.map_or(String::new(), |(m, f)| {
139 crate::people::names::citizen_name(if female { f } else { m }, rng)
140 });
141 Order {
142 name,
143 ..Default::default()
144 }
145 })
146 .collect();
147 Trade {
148 merchant: -1,
149 orders,
150 automatic: t
151 .categories
152 .iter()
153 .enumerate()
154 .map(|(i, &f)| (f, i as i32, 0))
155 .collect(),
156 ..Default::default()
157 }
158 }
159}
160
161impl Sim<'_, '_> {
162 fn merchant_list(&self, m: &Merchant) -> Vec<usize> {
163 merchant_list(self.trade_goods, self.templates, self.materials, m)
164 }
165}
166
167// +0x14; +0x18
168/// What the merchant docked gives for one: with none, its value; else its value for what it buys,
169/// three quarters for what it takes, else nothing.
170///
171/// Original: `FUN_14005ae80`.
172pub fn sell_value(
173 goods: &[TradeGood],
174 materials: &[crate::work::stock::RawMaterial],
175 tr: &Trade,
176 d: Option<&TradeTemplate>,
177 material: usize,
178) -> i32 {
179 let Some(good) = goods.iter().find(|g| g.material == Some(material)) else {
180 return 0;
181 };
182 if tr.merchant < 0 {
183 return good.value.value;
184 }
185 let Some(m) = d.and_then(|d| d.merchants.get(tr.merchant as usize)) else {
186 return 0;
187 };
188 let flags = materials[material].flags;
189 if m.flags.0 & flags != 0 {
190 good.value.value
191 } else if m.flags.1 & flags != 0 {
192 (good.value.value as f32 * 0.75) as i32
193 } else {
194 0
195 }
196}
197
198// +0x10
199/// The merchant's own goods, then every good whose raw material has a flag it deals in, in the
200/// factory's order.
201///
202/// Original: `FUN_140059fd0`.
203pub fn merchant_list(
204 goods: &[TradeGood],
205 templates: &[crate::nature::seeding::Template],
206 materials: &[crate::work::stock::RawMaterial],
207 m: &Merchant,
208) -> Vec<usize> {
209 let mut list: Vec<usize> = m
210 .items
211 .iter()
212 .flatten()
213 .filter_map(|r| {
214 goods
215 .iter()
216 .position(|g| templates[g.template].reference.eq_ignore_ascii_case(r))
217 })
218 .collect();
219 for (i, g) in goods.iter().enumerate() {
220 if g.material
221 .is_some_and(|mat| materials[mat].flags & m.sells != 0)
222 {
223 list.push(i);
224 }
225 }
226 list
227}
228
229/// What the trade window changes on the post's TradeComponent.
230#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
231pub enum TradeSetting {
232 // +0x60
233 /// Storage tab spinner `2000 + i`: what to keep at the post.
234 ///
235 /// Original: `FUN_140086f80`.
236 Keep {
237 /// The raw material.
238 material: usize,
239 /// The amount to keep.
240 amount: i32,
241 },
242 /// Purchase tab up `5000 + i` / down `6000 + i`: two automatic trades change places.
243 ///
244 /// Original: `FUN_1400871d0`.
245 Swap(usize, usize),
246 /// Purchase tab spinner `7000 + i`: the automatic trade's amount.
247 ///
248 /// Original: `FUN_140087120`.
249 Automatic {
250 /// The automatic trade.
251 index: usize,
252 /// The amount.
253 amount: i32,
254 },
255 // +0x28
256 /// `comboPurchase` (`0x4e22`): when it trades by itself.
257 ///
258 /// Original: `FUN_140087090`.
259 Mode(i32),
260 /// `comboOrder` (`0x4e23`): the docked merchant's order state.
261 ///
262 /// Original: `FUN_140087350`.
263 OrderState(i32),
264 /// Order tab check `8000 + i`: a good ordered from the docked merchant.
265 ///
266 /// Original: `FUN_1400872a0`.
267 Order {
268 /// The good.
269 good: usize,
270 /// Whether it is ordered.
271 on: bool,
272 },
273 // +0x71
274 /// The window is open or closed.
275 ///
276 /// Original: `FUN_140087f40`, `FUN_140087ed0`.
277 Held(bool),
278}
279
280// vtable 0x140167e30; +0x48
281/// TradeWork: each hauler and what it carries to (more) or from (fewer) the post.
282///
283/// Original: `FUN_1400fc370`.
284#[derive(Debug, Clone, Default, PartialEq, Eq)]
285pub struct TradeWork {
286 /// Each hauler and what it carries: `(raw material, count)`.
287 pub haulers: std::collections::BTreeMap<usize, (usize, i32)>,
288}
289
290impl Sim<'_, '_> {
291 /// `FUN_140134130(work, 1, 0, TradeWork)`.
292 pub(crate) fn set_trade_work(&mut self, jobs: &mut crate::work::jobs::Jobs, e: usize) {
293 let work = crate::work::jobs::Work::new(
294 e,
295 self.rect_cell(e),
296 self.professions.laborer,
297 crate::work::jobs::WorkKind::Trade(TradeWork::default()),
298 );
299 self.set_work(jobs, e, work, 1, false);
300 }
301
302 /// [`sell_value`] at the post `e`.
303 pub fn sell_value(&self, e: usize, material: usize) -> i32 {
304 let Some(site) = self.sites.get(&e) else {
305 return 0;
306 };
307 let Some(tr) = site.trade.as_ref() else {
308 return 0;
309 };
310 sell_value(
311 self.trade_goods,
312 self.materials,
313 tr,
314 self.site_templates[site.template].trade.as_ref(),
315 material,
316 )
317 }
318}