src/mood.rs 11.6 K · 421 lines · raw · history

1 use bevy::prelude::*;
2 use serde::{Deserialize, Serialize};
3
4 use crate::{
5 climate::Warmth,
6 colonist::Colonist,
7 family::{Child, Family, Homes, Partner, floored},
8 food::{HUNGRY, Hunger},
9 items::{Carrying, ItemAssets, ItemKind, ItemQuery, drop_items},
10 jobs::Reservations,
11 needs::Rest,
12 population::ColonyLog,
13 rng::SimRng,
14 sim::{SimSystems, SimTick, TICKS_PER_HOUR},
15 skills::Skills,
16 structures::{Structure, StructureKind},
17 world::{TilePos, WorldMap},
18 worldgen::WorldGenerated,
19 };
20
21 pub struct MoodPlugin;
22
23 impl Plugin for MoodPlugin {
24 fn build(&self, app: &mut App) {
25 app.add_message::<Ate>()
26 .init_resource::<Losses>()
27 .add_systems(Update, clear_losses.run_if(on_message::<WorldGenerated>))
28 .add_systems(
29 FixedUpdate,
30 (assign_age, digest, update_mood, leave, old_age)
31 .chain()
32 .in_set(SimSystems::Act),
33 );
34 }
35 }
36
37 pub const DAY_TICKS: u64 = 24 * TICKS_PER_HOUR;
38 pub const SICK_TICKS: u64 = 12 * TICKS_PER_HOUR;
39 pub const MOOD_HOURS: f32 = 12.0;
40 pub const LEAVE_MOOD: f32 = 0.2;
41 pub const LEAVE_AFTER_HOURS: u32 = 48;
42 pub const OLD_AGE: u64 = 60;
43 pub const OLD_AGE_DEATH_PER_YEAR: f32 = 0.03;
44 const MEAL_MEMORY_TICKS: u64 = DAY_TICKS;
45 const GRIEF_TICKS: u64 = 2 * DAY_TICKS;
46 const ADULT_AGES: std::ops::Range<i32> = 18..41;
47
48 #[derive(Message, Debug, Clone, Copy)]
49 pub struct Ate {
50 pub colonist: Entity,
51 pub kind: ItemKind,
52 }
53
54 #[derive(Component, Debug, Clone, Copy, PartialEq)]
55 pub struct Mood(pub f32);
56
57 impl Default for Mood {
58 fn default() -> Self {
59 Self(0.6)
60 }
61 }
62
63 #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
64 pub struct Sick {
65 pub until: u64,
66 }
67
68 #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
69 pub struct LastMeal {
70 pub cooked: bool,
71 pub tick: u64,
72 }
73
74 #[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq)]
75 pub struct Unhappy(pub u32);
76
77 #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
78 pub struct Age {
79 pub born: i64,
80 }
81
82 impl Age {
83 pub fn years(&self, tick: SimTick) -> u64 {
84 ((tick.0 as i64 - self.born).max(0) as u64) / DAY_TICKS
85 }
86 }
87
88 #[derive(Resource, Default, Debug, Serialize, Deserialize)]
89 pub struct Losses(pub Vec<u64>);
90
91 fn clear_losses(mut losses: ResMut<Losses>) {
92 losses.0.clear();
93 }
94
95 pub fn poison_chance(kind: ItemKind) -> f32 {
96 match kind {
97 ItemKind::Meat => 0.15,
98 ItemKind::Berries | ItemKind::Vegetables => 0.04,
99 _ => 0.0,
100 }
101 }
102
103 #[derive(Debug, Default, Clone, Copy)]
104 pub struct MoodFactors {
105 pub fed: f32,
106 pub rest: f32,
107 pub sick: bool,
108 pub last_meal_cooked: Option<bool>,
109 pub partner: bool,
110 pub home: bool,
111 pub grieving: bool,
112 pub cold: bool,
113 pub beauty: bool,
114 pub floored: bool,
115 }
116
117 pub fn mood_target(f: MoodFactors) -> f32 {
118 let mut mood: f32 = 0.5;
119 mood += if f.fed < HUNGRY { -0.25 } else { 0.1 };
120 mood += if f.rest < 0.2 { -0.15 } else { 0.05 };
121 mood += match f.last_meal_cooked {
122 Some(true) => 0.1,
123 Some(false) => -0.05,
124 None => 0.0,
125 };
126 if f.sick {
127 mood -= 0.2;
128 }
129 if f.partner {
130 mood += 0.1;
131 }
132 if f.home {
133 mood += 0.1;
134 }
135 if f.grieving {
136 mood -= 0.15;
137 }
138 if f.cold {
139 mood -= 0.15;
140 }
141 if f.beauty {
142 mood += 0.1;
143 }
144 if f.floored {
145 mood += 0.05;
146 }
147 mood.clamp(0.0, 1.0)
148 }
149
150 fn assign_age(
151 mut commands: Commands,
152 tick: Res<SimTick>,
153 mut rng: ResMut<SimRng>,
154 newcomers: Query<(Entity, Has<Child>), (With<Colonist>, Without<Age>)>,
155 ) {
156 for (entity, child) in &newcomers {
157 let years = if child { 0 } else { rng.range_i32(ADULT_AGES) };
158 let born = tick.0 as i64 - years as i64 * DAY_TICKS as i64;
159 let skills = if child {
160 Skills::uniform(0)
161 } else {
162 Skills::random(&mut rng)
163 };
164 commands
165 .entity(entity)
166 .insert((Age { born }, Mood::default(), skills));
167 }
168 }
169
170 fn digest(
171 mut commands: Commands,
172 tick: Res<SimTick>,
173 mut rng: ResMut<SimRng>,
174 mut log: ResMut<ColonyLog>,
175 mut ate: MessageReader<Ate>,
176 colonists: Query<(&Colonist, Option<&Sick>)>,
177 ) {
178 for meal in ate.read() {
179 let Ok((colonist, sick)) = colonists.get(meal.colonist) else {
180 continue;
181 };
182 let mut entity = commands.entity(meal.colonist);
183 entity.insert(LastMeal {
184 cooked: !meal.kind.is_raw_food(),
185 tick: tick.0,
186 });
187 if sick.is_none() && rng.range_f32(0.0..1.0) < poison_chance(meal.kind) {
188 entity.insert(Sick {
189 until: tick.0 + SICK_TICKS,
190 });
191 log.push(*tick, format!("{} has food poisoning", colonist.name));
192 }
193 }
194 }
195
196 #[allow(clippy::type_complexity)]
197 fn update_mood(
198 mut commands: Commands,
199 tick: Res<SimTick>,
200 homes: Res<Homes>,
201 map: Res<WorldMap>,
202 losses: Res<Losses>,
203 structures: Query<(&TilePos, &Structure), Without<Colonist>>,
204 mut colonists: Query<(
205 Entity,
206 &mut Mood,
207 &Hunger,
208 &Rest,
209 Option<&Sick>,
210 Option<&LastMeal>,
211 Has<Partner>,
212 Option<&Family>,
213 &Warmth,
214 )>,
215 ) {
216 if !tick.0.is_multiple_of(TICKS_PER_HOUR) {
217 return;
218 }
219 let grieving = losses.0.iter().any(|&t| tick.0 < t + GRIEF_TICKS);
220 let statues: Vec<UVec2> = structures
221 .iter()
222 .filter(|(_, s)| s.kind == StructureKind::Statue)
223 .map(|(pos, _)| pos.0)
224 .collect();
225 for (entity, mut mood, hunger, rest, sick, meal, partner, family, warmth) in &mut colonists {
226 let sick_now = sick.is_some_and(|s| tick.0 < s.until);
227 if sick.is_some() && !sick_now {
228 commands.entity(entity).remove::<Sick>();
229 }
230 let own_home = homes.of(family.copied());
231 let home = own_home.is_some_and(|h| h.interior().all(|t| map.is_roofed(t.as_ivec2())));
232 let beauty = own_home.is_some_and(|h| statues.iter().any(|&t| h.contains(t)));
233 let floored = own_home.is_some_and(|h| h.interior().all(|t| floored(&map, t)));
234 let target = mood_target(MoodFactors {
235 fed: hunger.0,
236 rest: rest.0,
237 sick: sick_now,
238 last_meal_cooked: meal
239 .filter(|m| tick.0 < m.tick + MEAL_MEMORY_TICKS)
240 .map(|m| m.cooked),
241 partner,
242 home,
243 grieving,
244 cold: warmth.cold(),
245 beauty,
246 floored,
247 });
248 mood.0 += (target - mood.0) / MOOD_HOURS;
249 }
250 }
251
252 #[allow(clippy::too_many_arguments)]
253 fn leave(
254 mut commands: Commands,
255 tick: Res<SimTick>,
256 item_assets: Res<ItemAssets>,
257 mut log: ResMut<ColonyLog>,
258 mut reservations: ResMut<Reservations>,
259 mut items: ItemQuery,
260 mut colonists: Query<
261 (
262 Entity,
263 &Colonist,
264 &Mood,
265 &TilePos,
266 &Carrying,
267 Option<&mut Unhappy>,
268 ),
269 Without<Child>,
270 >,
271 ) {
272 if !tick.0.is_multiple_of(TICKS_PER_HOUR) {
273 return;
274 }
275 for (entity, colonist, mood, tile, carrying, unhappy) in &mut colonists {
276 let hours = if mood.0 < LEAVE_MOOD {
277 unhappy.as_ref().map_or(0, |u| u.0) + 1
278 } else {
279 0
280 };
281 match unhappy {
282 Some(mut u) => u.0 = hours,
283 None => {
284 commands.entity(entity).insert(Unhappy(hours));
285 }
286 }
287 if hours < LEAVE_AFTER_HOURS {
288 continue;
289 }
290 if let Some(load) = carrying.0 {
291 drop_items(&mut commands, &mut items, &item_assets, tile.0, load);
292 }
293 reservations.release_all(entity);
294 commands.entity(entity).despawn();
295 log.push(*tick, format!("{} left the colony, unhappy", colonist.name));
296 }
297 }
298
299 pub fn dies_of_old_age(years: u64, roll: f32) -> bool {
300 years >= OLD_AGE && roll < (years - OLD_AGE + 1) as f32 * OLD_AGE_DEATH_PER_YEAR
301 }
302
303 #[allow(clippy::too_many_arguments)]
304 fn old_age(
305 mut commands: Commands,
306 tick: Res<SimTick>,
307 item_assets: Res<ItemAssets>,
308 mut rng: ResMut<SimRng>,
309 mut log: ResMut<ColonyLog>,
310 mut losses: ResMut<Losses>,
311 mut reservations: ResMut<Reservations>,
312 mut items: ItemQuery,
313 colonists: Query<(Entity, &Colonist, &Age, &TilePos, &Carrying)>,
314 ) {
315 if !tick.0.is_multiple_of(DAY_TICKS) {
316 return;
317 }
318 for (entity, colonist, age, tile, carrying) in &colonists {
319 if !dies_of_old_age(age.years(*tick), rng.range_f32(0.0..1.0)) {
320 continue;
321 }
322 if let Some(load) = carrying.0 {
323 drop_items(&mut commands, &mut items, &item_assets, tile.0, load);
324 }
325 reservations.release_all(entity);
326 commands.entity(entity).despawn();
327 losses.0.push(tick.0);
328 log.push(*tick, format!("{} died of old age", colonist.name));
329 }
330 }
331
332 #[cfg(test)]
333 mod tests {
334 use super::*;
335
336 fn content() -> MoodFactors {
337 MoodFactors {
338 fed: 0.8,
339 rest: 0.8,
340 ..default()
341 }
342 }
343
344 #[test]
345 fn needs_meals_family_and_loss_move_mood() {
346 let base = mood_target(content());
347 let hungry = mood_target(MoodFactors {
348 fed: 0.1,
349 ..content()
350 });
351 assert!(hungry < base);
352 let settled = mood_target(MoodFactors {
353 partner: true,
354 home: true,
355 beauty: true,
356 floored: true,
357 last_meal_cooked: Some(true),
358 ..content()
359 });
360 assert!(settled > base + 0.25);
361 let miserable = mood_target(MoodFactors {
362 fed: 0.1,
363 rest: 0.1,
364 sick: true,
365 grieving: true,
366 cold: true,
367 last_meal_cooked: Some(false),
368 ..default()
369 });
370 assert!(miserable < LEAVE_MOOD);
371 }
372
373 // Cooking is what makes raw meat safe: meals never poison, raw meat is the riskiest.
374 #[test]
375 fn raw_food_can_poison_and_meals_never() {
376 assert_eq!(poison_chance(ItemKind::Meal), 0.0);
377 assert!(poison_chance(ItemKind::Meat) > poison_chance(ItemKind::Berries));
378 }
379
380 #[test]
381 fn old_age_comes_for_everyone_eventually() {
382 assert!(!dies_of_old_age(OLD_AGE - 1, 0.0));
383 assert!(dies_of_old_age(OLD_AGE, 0.0));
384 assert!(!dies_of_old_age(OLD_AGE, 0.5));
385 assert!(dies_of_old_age(OLD_AGE + 40, 0.99));
386 }
387
388 #[test]
389 fn colonists_leave_after_two_unhappy_days() {
390 let mut app = App::new();
391 app.init_resource::<SimTick>()
392 .init_resource::<ItemAssets>()
393 .init_resource::<ColonyLog>()
394 .init_resource::<Reservations>()
395 .add_systems(Update, leave);
396 let spawn = |app: &mut App, mood: f32| {
397 app.world_mut()
398 .spawn((
399 Colonist { name: "Ada".into() },
400 Mood(mood),
401 Unhappy(LEAVE_AFTER_HOURS - 1),
402 ))
403 .id()
404 };
405 let gloomy = spawn(&mut app, LEAVE_MOOD / 2.0);
406 let cheered_up = spawn(&mut app, 0.5);
407 app.update();
408 assert!(app.world().get_entity(gloomy).is_err());
409 assert_eq!(app.world().get::<Unhappy>(cheered_up), Some(&Unhappy(0)));
410 let log = app.world().resource::<ColonyLog>();
411 assert!(log.0[0].ends_with("Ada left the colony, unhappy"));
412 }
413
414 #[test]
415 fn ages_count_days_as_years() {
416 let age = Age {
417 born: -(20 * DAY_TICKS as i64),
418 };
419 assert_eq!(age.years(SimTick(DAY_TICKS / 2)), 20);
420 }
421 }