src/economy.rs 7.3 K · 256 lines · raw · history

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