src/economy.rs 9.8 K · 327 lines · raw · history

1 use std::collections::HashMap;
2
3 use bevy::prelude::*;
4
5 use crate::{
6 building::Blueprints,
7 climate::cold_days_ahead,
8 items::ItemKind,
9 sim::{SimSystems, SimTick, TICKS_PER_HOUR},
10 };
11
12 pub struct EconomyPlugin;
13
14 impl Plugin for EconomyPlugin {
15 fn build(&self, app: &mut App) {
16 app.init_resource::<ColonyGoals>()
17 .add_systems(FixedUpdate, learn_needs.in_set(SimSystems::Decide));
18 }
19 }
20
21 pub const COLONY_RADIUS: i32 = 60;
22 const HOURS_OF_MEMORY: f32 = 24.0;
23 const MAX_GOAL: f32 = 300.0;
24
25 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26 pub enum Stock {
27 Wood,
28 Stone,
29 Iron,
30 Gold,
31 RawFood,
32 Meals,
33 Tools,
34 }
35
36 impl Stock {
37 pub const ALL: [Stock; 7] = [
38 Stock::Wood,
39 Stock::Stone,
40 Stock::Iron,
41 Stock::Gold,
42 Stock::RawFood,
43 Stock::Meals,
44 Stock::Tools,
45 ];
46
47 pub fn of(kind: ItemKind) -> Stock {
48 match kind {
49 ItemKind::Wood => Stock::Wood,
50 ItemKind::Stone => Stock::Stone,
51 ItemKind::Iron => Stock::Iron,
52 ItemKind::Gold => Stock::Gold,
53 ItemKind::Berries | ItemKind::Meat | ItemKind::Vegetables | ItemKind::Carcass => {
54 Stock::RawFood
55 }
56 ItemKind::Meal => Stock::Meals,
57 ItemKind::Tools => Stock::Tools,
58 }
59 }
60
61 pub fn members(self) -> impl Iterator<Item = ItemKind> {
62 ItemKind::ALL
63 .into_iter()
64 .filter(move |&k| Stock::of(k) == self)
65 }
66
67 pub fn is_food(self) -> bool {
68 matches!(self, Stock::RawFood | Stock::Meals)
69 }
70
71 pub fn label(self) -> &'static str {
72 match self {
73 Stock::Wood => "Wood",
74 Stock::Stone => "Stone",
75 Stock::Iron => "Iron",
76 Stock::Gold => "Gold",
77 Stock::RawFood => "Raw food",
78 Stock::Meals => "Meals",
79 Stock::Tools => "Tools",
80 }
81 }
82
83 fn buffer_days(self, cold_days: u64) -> f32 {
84 let normal: f32 = if self.is_food() { 1.5 } else { 2.0 };
85 match self {
86 Stock::Wood | Stock::RawFood | Stock::Meals => normal.max(cold_days as f32),
87 _ => normal,
88 }
89 }
90
91 fn minimum(self) -> f32 {
92 match self {
93 Stock::Wood => 15.0,
94 Stock::Stone => 5.0,
95 Stock::Iron => 6.0,
96 Stock::Gold => 0.0,
97 Stock::RawFood => 10.0,
98 Stock::Meals => 3.0,
99 Stock::Tools => 1.0,
100 }
101 }
102
103 fn initial_use_per_day(self) -> f32 {
104 match self {
105 Stock::Wood => 20.0,
106 Stock::Stone => 10.0,
107 Stock::Iron => 3.0,
108 Stock::Gold => 0.0,
109 Stock::RawFood => 30.0,
110 Stock::Meals => 3.0,
111 Stock::Tools => 1.0,
112 }
113 }
114 }
115
116 #[derive(Resource, Debug, Clone)]
117 pub struct ColonyGoals {
118 goals: HashMap<Stock, u32>,
119 use_per_day: HashMap<Stock, f32>,
120 used_this_hour: HashMap<Stock, u32>,
121 overrides: HashMap<Stock, u32>,
122 cold_days: u64,
123 }
124
125 impl Default for ColonyGoals {
126 fn default() -> Self {
127 let mut goals = Self {
128 goals: HashMap::new(),
129 use_per_day: Stock::ALL
130 .iter()
131 .map(|&s| (s, s.initial_use_per_day()))
132 .collect(),
133 used_this_hour: HashMap::new(),
134 overrides: HashMap::new(),
135 cold_days: 0,
136 };
137 goals.recompute(&HashMap::new());
138 goals
139 }
140 }
141
142 impl ColonyGoals {
143 #[cfg(test)]
144 pub fn fixed(goals: &[(ItemKind, u32)]) -> Self {
145 Self {
146 goals: goals.iter().map(|&(k, n)| (Stock::of(k), n)).collect(),
147 use_per_day: HashMap::new(),
148 used_this_hour: HashMap::new(),
149 overrides: HashMap::new(),
150 cold_days: 0,
151 }
152 }
153
154 pub fn goal(&self, stock: Stock) -> u32 {
155 self.overrides
156 .get(&stock)
157 .or_else(|| self.goals.get(&stock))
158 .copied()
159 .unwrap_or(0)
160 }
161
162 pub fn is_overridden(&self, stock: Stock) -> bool {
163 self.overrides.contains_key(&stock)
164 }
165
166 pub fn adjust(&mut self, stock: Stock, delta: i32) {
167 let goal = (self.goal(stock) as i32 + delta).clamp(0, MAX_GOAL as i32) as u32;
168 self.overrides.insert(stock, goal);
169 }
170
171 pub fn reset(&mut self, stock: Stock) {
172 self.overrides.remove(&stock);
173 }
174
175 pub fn use_per_day(&self, stock: Stock) -> f32 {
176 self.use_per_day.get(&stock).copied().unwrap_or(0.0)
177 }
178
179 pub fn record_use(&mut self, kind: ItemKind, count: u32) {
180 *self.used_this_hour.entry(Stock::of(kind)).or_insert(0) += count;
181 }
182
183 pub fn wanted(
184 &self,
185 kind: ItemKind,
186 stocks: &HashMap<ItemKind, u32>,
187 on_the_way: &HashMap<ItemKind, u32>,
188 ) -> bool {
189 let stock = Stock::of(kind);
190 let have: u32 = stock
191 .members()
192 .map(|k| {
193 stocks.get(&k).copied().unwrap_or(0) + on_the_way.get(&k).copied().unwrap_or(0)
194 })
195 .sum();
196 have < self.goal(stock)
197 }
198
199 pub fn set_cold_days(&mut self, days: u64) {
200 self.cold_days = days;
201 }
202
203 pub fn learn_hour(&mut self, planned: &HashMap<Stock, u32>) {
204 for stock in Stock::ALL {
205 let used = self.used_this_hour.remove(&stock).unwrap_or(0) as f32;
206 let rate = self.use_per_day.entry(stock).or_insert(0.0);
207 *rate += (used * 24.0 - *rate) / HOURS_OF_MEMORY;
208 }
209 self.recompute(planned);
210 }
211
212 fn recompute(&mut self, planned: &HashMap<Stock, u32>) {
213 for stock in Stock::ALL {
214 let learned = (self.use_per_day(stock) * stock.buffer_days(self.cold_days))
215 .clamp(stock.minimum(), MAX_GOAL)
216 .ceil() as u32;
217 let goal = learned + planned.get(&stock).copied().unwrap_or(0);
218 self.goals.insert(stock, goal);
219 }
220 }
221 }
222
223 pub fn in_colony(home: UVec2, tile: UVec2) -> bool {
224 (tile.as_ivec2() - home.as_ivec2()).abs().max_element() <= COLONY_RADIUS
225 }
226
227 pub fn planned_needs(blueprints: &Blueprints) -> HashMap<Stock, u32> {
228 let mut needs = HashMap::new();
229 for kind in blueprints.0.values() {
230 let (item, count) = kind.cost();
231 *needs.entry(Stock::of(item)).or_insert(0) += count;
232 }
233 needs
234 }
235
236 fn learn_needs(tick: Res<SimTick>, blueprints: Res<Blueprints>, mut goals: ResMut<ColonyGoals>) {
237 if tick.0 == 0 || !tick.0.is_multiple_of(TICKS_PER_HOUR) {
238 return;
239 }
240 goals.set_cold_days(cold_days_ahead(*tick));
241 goals.learn_hour(&planned_needs(&blueprints));
242 }
243
244 #[cfg(test)]
245 mod tests {
246 use super::*;
247 use crate::building::BuildKind;
248
249 fn learn_days(goals: &mut ColonyGoals, kind: ItemKind, per_hour: u32, days: u32) {
250 for _ in 0..days * 24 {
251 goals.record_use(kind, per_hour);
252 goals.learn_hour(&HashMap::new());
253 }
254 }
255
256 #[test]
257 fn targets_follow_what_the_colony_actually_uses() {
258 let mut goals = ColonyGoals::default();
259 learn_days(&mut goals, ItemKind::Meal, 1, 5);
260 let meals = goals.goal(Stock::Meals);
261 assert!((32..=40).contains(&meals), "{meals}");
262 learn_days(&mut goals, ItemKind::Meal, 0, 5);
263 assert_eq!(goals.goal(Stock::Meals), 3);
264 }
265
266 #[test]
267 fn players_can_override_learned_targets_and_hand_them_back() {
268 let mut goals = ColonyGoals::default();
269 let learned = goals.goal(Stock::Wood);
270 goals.adjust(Stock::Wood, 10);
271 assert_eq!(goals.goal(Stock::Wood), learned + 10);
272 learn_days(&mut goals, ItemKind::Wood, 5, 3);
273 assert_eq!(goals.goal(Stock::Wood), learned + 10);
274 goals.adjust(Stock::Iron, -10);
275 assert_eq!(goals.goal(Stock::Iron), 0);
276 goals.reset(Stock::Wood);
277 assert!(!goals.is_overridden(Stock::Wood));
278 assert!(goals.goal(Stock::Wood) > learned);
279 }
280
281 // Nothing grows in the cold days ahead and fires burn all day, so food and wood targets cover
282 // those days instead of the usual short buffer.
283 #[test]
284 fn winter_ahead_raises_food_and_wood_targets() {
285 let mut goals = ColonyGoals::default();
286 learn_days(&mut goals, ItemKind::Berries, 1, 3);
287 let (food, stone) = (goals.goal(Stock::RawFood), goals.goal(Stock::Stone));
288 goals.set_cold_days(5);
289 goals.learn_hour(&HashMap::new());
290 assert!(goals.goal(Stock::RawFood) > food * 3);
291 assert_eq!(goals.goal(Stock::Stone), stone);
292 }
293
294 #[test]
295 fn unused_materials_are_not_stockpiled() {
296 let mut goals = ColonyGoals::default();
297 learn_days(&mut goals, ItemKind::Wood, 0, 10);
298 assert_eq!(goals.goal(Stock::Wood), 15);
299 assert_eq!(goals.goal(Stock::Gold), 0);
300 }
301
302 // Raw foods stand in for each other (cooking accepts any), so the colony targets them as one
303 // group and is free to forage, hunt or farm whichever is at hand.
304 #[test]
305 fn raw_foods_share_one_target() {
306 let goals = ColonyGoals::fixed(&[(ItemKind::Berries, 20)]);
307 let stocks = HashMap::from([(ItemKind::Meat, 15), (ItemKind::Vegetables, 4)]);
308 assert!(goals.wanted(ItemKind::Berries, &stocks, &HashMap::new()));
309 let on_the_way = HashMap::from([(ItemKind::Berries, 1)]);
310 assert!(!goals.wanted(ItemKind::Meat, &stocks, &on_the_way));
311 }
312
313 #[test]
314 fn planned_construction_raises_material_targets() {
315 let mut blueprints = Blueprints::default();
316 for x in 0..10 {
317 blueprints.0.insert(
318 UVec2::new(x, 0),
319 BuildKind::Structure(crate::structures::StructureKind::Wall),
320 );
321 }
322 let mut goals = ColonyGoals::default();
323 let before = goals.goal(Stock::Stone);
324 goals.learn_hour(&planned_needs(&blueprints));
325 assert!(goals.goal(Stock::Stone) >= before + 19);
326 }
327 }