src/family.rs 32.6 K · 993 lines · raw · history

1 use serde::{Deserialize, Serialize};
2 use std::collections::{HashMap, HashSet};
3
4 use bevy::prelude::*;
5
6 use crate::{
7 building::{Blueprints, BuildKind, enclosed_room},
8 colonist::{Colonist, ColonistAssets, NAMES, spawn_colonist},
9 economy::in_colony,
10 items::{Item, ItemAssets},
11 pathfinding::nearest_tile,
12 population::{ColonyLog, MAX_COLONISTS, food_in_store},
13 rng::SimRng,
14 sim::{SimSystems, SimTick, TICKS_PER_HOUR},
15 structures::{Structure, StructureKind},
16 world::{TilePos, WorldMap},
17 worldgen::WorldGenerated,
18 zones::{Zones, can_zone},
19 };
20
21 pub struct FamilyPlugin;
22
23 impl Plugin for FamilyPlugin {
24 fn build(&self, app: &mut App) {
25 app.init_resource::<Homes>()
26 .init_resource::<Affinity>()
27 .add_systems(Update, clear_families.run_if(on_message::<WorldGenerated>))
28 .add_systems(
29 FixedUpdate,
30 (
31 plan_homes.in_set(SimSystems::Decide),
32 (bond, births, grow_up).chain().in_set(SimSystems::Act),
33 ),
34 );
35 }
36 }
37
38 pub const HOME_INTERIOR: UVec2 = UVec2::new(4, 3);
39 pub const HOME_MIN_DISTANCE: i32 = 6;
40 pub const BOND_RANGE: i32 = 4;
41 pub const BOND_HOURS: u32 = 16;
42 pub const BOND_CHANCE: f32 = 0.2;
43 pub const MAX_CHILDREN: usize = 2;
44 pub const BIRTH_CHANCE: f32 = 0.35;
45 pub const CHILDHOOD_TICKS: u64 = 4 * 24 * TICKS_PER_HOUR;
46 pub const CHILD_SCALE: f32 = 0.6;
47 const BIRTH_HOUR_TICK: u64 = 20 * TICKS_PER_HOUR;
48 const DAY_TICKS: u64 = 24 * TICKS_PER_HOUR;
49 const HOME_PLAN_INTERVAL_TICKS: u64 = 300;
50 const HOME_SEARCH_TILES: usize = 6000;
51 const HOME_CLEARANCE: i32 = 1;
52
53 #[derive(Component, Clone, Copy, Debug, PartialEq, Eq, Hash)]
54 pub struct Family(pub u32);
55
56 #[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
57 pub struct Partner(pub Entity);
58
59 #[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
60 pub struct Child {
61 pub born: u64,
62 }
63
64 impl Child {
65 pub fn days_left(&self, tick: SimTick) -> u64 {
66 (self.born + CHILDHOOD_TICKS)
67 .saturating_sub(tick.0)
68 .div_ceil(DAY_TICKS)
69 }
70 }
71
72 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
73 pub struct Home {
74 pub lo: UVec2,
75 pub hi: UVec2,
76 }
77
78 impl Home {
79 pub fn at(lo: UVec2) -> Self {
80 Self {
81 lo,
82 hi: lo + HOME_INTERIOR + UVec2::ONE,
83 }
84 }
85
86 pub fn contains(&self, tile: UVec2) -> bool {
87 tile.cmpge(self.lo).all() && tile.cmple(self.hi).all()
88 }
89
90 pub fn interior(&self) -> impl Iterator<Item = UVec2> + use<> {
91 let (lo, hi) = (self.lo + UVec2::ONE, self.hi - UVec2::ONE);
92 (lo.y..=hi.y).flat_map(move |y| (lo.x..=hi.x).map(move |x| UVec2::new(x, y)))
93 }
94
95 pub fn ring(&self) -> impl Iterator<Item = UVec2> + use<> {
96 let (lo, hi) = (self.lo, self.hi);
97 (lo.y..=hi.y)
98 .flat_map(move |y| (lo.x..=hi.x).map(move |x| UVec2::new(x, y)))
99 .filter(move |t| t.x == lo.x || t.x == hi.x || t.y == lo.y || t.y == hi.y)
100 }
101
102 pub fn bed_tiles(&self) -> [UVec2; 2] {
103 let corner = UVec2::new(self.lo.x + 1, self.hi.y - 1);
104 [corner, corner + UVec2::X]
105 }
106
107 pub fn outward(&self, tile: UVec2) -> IVec2 {
108 let t = tile.as_ivec2();
109 let step = if tile.y == self.lo.y {
110 IVec2::NEG_Y
111 } else if tile.y == self.hi.y {
112 IVec2::Y
113 } else if tile.x == self.lo.x {
114 IVec2::NEG_X
115 } else {
116 IVec2::X
117 };
118 t + step
119 }
120
121 fn is_corner(&self, t: UVec2) -> bool {
122 (t.x == self.lo.x || t.x == self.hi.x) && (t.y == self.lo.y || t.y == self.hi.y)
123 }
124
125 pub fn door_sites(&self) -> impl Iterator<Item = UVec2> + use<> {
126 let home = *self;
127 self.ring().filter(move |t| !home.is_corner(*t))
128 }
129
130 pub fn statue_tile(&self) -> UVec2 {
131 UVec2::new(self.hi.x - 1, self.lo.y + 1)
132 }
133
134 pub fn blueprints(&self, toward: UVec2) -> HashMap<UVec2, BuildKind> {
135 let door = self
136 .door_sites()
137 .min_by(|a, b| {
138 a.as_vec2()
139 .distance_squared(toward.as_vec2())
140 .total_cmp(&b.as_vec2().distance_squared(toward.as_vec2()))
141 .then((a.y, a.x).cmp(&(b.y, b.x)))
142 })
143 .unwrap_or(self.lo);
144 let mut plan: HashMap<UVec2, BuildKind> = self
145 .ring()
146 .map(|t| (t, BuildKind::Structure(StructureKind::Wall)))
147 .collect();
148 plan.insert(door, BuildKind::Structure(StructureKind::Door));
149 for bed in self.bed_tiles() {
150 plan.insert(bed, BuildKind::Structure(StructureKind::Bed));
151 }
152 plan
153 }
154 }
155
156 #[derive(Resource, Default, Debug, Clone, Serialize, Deserialize)]
157 pub struct Homes {
158 pub by_family: HashMap<u32, Home>,
159 next_family: u32,
160 #[serde(default)]
161 pub vacant: Vec<Home>,
162 }
163
164 impl Homes {
165 pub fn new_family(&mut self) -> Family {
166 self.next_family += 1;
167 Family(self.next_family)
168 }
169
170 pub fn owner(&self, tile: UVec2) -> Option<u32> {
171 self.by_family
172 .iter()
173 .find(|(_, home)| home.contains(tile))
174 .map(|(family, _)| *family)
175 }
176
177 pub fn all(&self) -> impl Iterator<Item = &Home> {
178 self.by_family.values().chain(&self.vacant)
179 }
180
181 pub fn is_home(&self, tile: UVec2) -> bool {
182 self.all().any(|home| home.contains(tile))
183 }
184
185 pub fn of(&self, family: Option<Family>) -> Option<&Home> {
186 self.by_family.get(&family?.0)
187 }
188 }
189
190 #[derive(Resource, Default, Debug)]
191 pub struct Affinity(pub HashMap<(Entity, Entity), u32>);
192
193 fn clear_families(mut homes: ResMut<Homes>, mut affinity: ResMut<Affinity>) {
194 homes.by_family.clear();
195 homes.vacant.clear();
196 affinity.0.clear();
197 }
198
199 #[derive(Clone, Copy)]
200 pub struct Single {
201 pub entity: Entity,
202 pub tile: UVec2,
203 pub family: Option<Family>,
204 }
205
206 pub fn bond_hour(
207 affinity: &mut Affinity,
208 singles: &[Single],
209 rng: &mut SimRng,
210 ) -> Vec<(Entity, Entity)> {
211 let mut bonded: Vec<(Entity, Entity)> = Vec::new();
212 let taken =
213 |bonded: &[(Entity, Entity)], e: Entity| bonded.iter().any(|&(a, b)| a == e || b == e);
214 for (i, a) in singles.iter().enumerate() {
215 for b in &singles[i + 1..] {
216 let near = (a.tile.as_ivec2() - b.tile.as_ivec2()).abs().max_element() <= BOND_RANGE;
217 let kin = a.family.is_some() && a.family == b.family;
218 if !near || kin {
219 continue;
220 }
221 let key = (a.entity.min(b.entity), a.entity.max(b.entity));
222 let hours = affinity.0.entry(key).or_insert(0);
223 *hours += 1;
224 if *hours >= BOND_HOURS
225 && !taken(&bonded, a.entity)
226 && !taken(&bonded, b.entity)
227 && rng.range_f32(0.0..1.0) < BOND_CHANCE
228 {
229 bonded.push(key);
230 }
231 }
232 }
233 for pair in &bonded {
234 affinity
235 .0
236 .retain(|&(a, b), _| ![a, b].iter().any(|e| *e == pair.0 || *e == pair.1));
237 }
238 bonded
239 }
240
241 #[allow(clippy::type_complexity)]
242 fn bond(
243 mut commands: Commands,
244 tick: Res<SimTick>,
245 mut rng: ResMut<SimRng>,
246 mut homes: ResMut<Homes>,
247 mut affinity: ResMut<Affinity>,
248 mut log: ResMut<ColonyLog>,
249 colonists: Query<(
250 Entity,
251 &Colonist,
252 &TilePos,
253 Option<&Family>,
254 Option<&Partner>,
255 Has<Child>,
256 )>,
257 ) {
258 if !tick.0.is_multiple_of(TICKS_PER_HOUR) {
259 return;
260 }
261 for (entity, _, _, _, partner, _) in &colonists {
262 if let Some(partner) = partner
263 && !colonists.contains(partner.0)
264 {
265 commands.entity(entity).remove::<Partner>();
266 }
267 }
268 let singles: Vec<Single> = colonists
269 .iter()
270 .filter(|(.., partner, child)| partner.is_none() && !child)
271 .map(|(entity, _, tile, family, ..)| Single {
272 entity,
273 tile: tile.0,
274 family: family.copied(),
275 })
276 .collect();
277 for (a, b) in bond_hour(&mut affinity, &singles, &mut rng) {
278 let family = homes.new_family();
279 commands.entity(a).insert((Partner(b), family));
280 commands.entity(b).insert((Partner(a), family));
281 let name = |e: Entity| {
282 colonists
283 .get(e)
284 .map(|c| c.1.name.clone())
285 .unwrap_or_default()
286 };
287 log.push(
288 *tick,
289 format!("{} and {} became partners", name(a), name(b)),
290 );
291 }
292 }
293
294 pub struct HomeContext<'a> {
295 pub map: &'a WorldMap,
296 pub zones: &'a Zones,
297 pub blueprints: &'a Blueprints,
298 pub homes: &'a Homes,
299 pub occupied: &'a HashSet<UVec2>,
300 }
301
302 impl HomeContext<'_> {
303 fn claimed(&self, tile: UVec2) -> bool {
304 self.zones.is_stockpile(tile)
305 || self.zones.is_farm(tile)
306 || self.blueprints.get(tile).is_some()
307 || self.homes.is_home(tile)
308 }
309
310 fn open(&self, tile: IVec2) -> bool {
311 self.map.in_bounds(tile)
312 && can_zone(self.map, tile)
313 && self.map.plant(tile).is_none()
314 && !self.map.is_wall(tile)
315 && !self.occupied.contains(&tile.as_uvec2())
316 && !self.claimed(tile.as_uvec2())
317 }
318
319 fn fits(&self, home: Home) -> bool {
320 let (lo, hi) = (home.lo.as_ivec2(), home.hi.as_ivec2());
321 let (outer_lo, outer_hi) = (lo - HOME_CLEARANCE, hi + HOME_CLEARANCE);
322 (outer_lo.y..=outer_hi.y).all(|y| {
323 (outer_lo.x..=outer_hi.x).all(|x| {
324 let tile = IVec2::new(x, y);
325 let core = tile.cmpge(lo).all() && tile.cmple(hi).all();
326 if core {
327 self.open(tile)
328 } else {
329 !self.map.in_bounds(tile)
330 || (!self.claimed(tile.as_uvec2()) && self.map.move_cost(tile).is_some())
331 }
332 })
333 })
334 }
335
336 pub fn plan(&self, colony_home: UVec2) -> Option<Home> {
337 let center = (HOME_INTERIOR / 2 + UVec2::ONE).as_ivec2();
338 let mut found = None;
339 nearest_tile(self.map, colony_home, HOME_SEARCH_TILES, |p| {
340 let lo = p.as_ivec2() - center;
341 if lo.min_element() < 0 {
342 return false;
343 }
344 let home = Home::at(lo.as_uvec2());
345 let middle = (home.lo + home.hi).as_ivec2() / 2;
346 if (middle - colony_home.as_ivec2()).abs().max_element() < HOME_MIN_DISTANCE {
347 return false;
348 }
349 found = self.fits(home).then_some(home);
350 found.is_some()
351 })?;
352 found
353 }
354 }
355
356 pub fn door_repair(
357 map: &WorldMap,
358 doors: &HashSet<UVec2>,
359 reachable: &HashSet<UVec2>,
360 home: &Home,
361 toward: UVec2,
362 ) -> Option<(UVec2, BuildKind)> {
363 let open_outside = |t: &UVec2| {
364 let out = home.outward(*t);
365 out.min_element() >= 0 && reachable.contains(&out.as_uvec2())
366 };
367 if home
368 .door_sites()
369 .any(|t| doors.contains(&t) && open_outside(&t))
370 {
371 return None;
372 }
373 let site = home
374 .door_sites()
375 .filter(|t| !doors.contains(t) && open_outside(t))
376 .min_by_key(|t| {
377 let d = t.as_ivec2() - toward.as_ivec2();
378 (map.is_wall(t.as_ivec2()), d.length_squared(), t.y, t.x)
379 })?;
380 let kind = if map.is_wall(site.as_ivec2()) {
381 BuildKind::Deconstruct
382 } else {
383 BuildKind::Structure(StructureKind::Door)
384 };
385 Some((site, kind))
386 }
387
388 pub fn abandoned_home(map: &WorldMap, doors: &HashSet<UVec2>, bed: UVec2) -> Option<Home> {
389 let room = enclosed_room(map, doors, bed)?;
390 let lo = room.iter().fold(UVec2::MAX, |a, t| a.min(*t));
391 let hi = room.iter().fold(UVec2::ZERO, |a, t| a.max(*t));
392 let size = hi - lo + UVec2::ONE;
393 (size == HOME_INTERIOR && room.len() == size.element_product() as usize && lo.min_element() > 0)
394 .then(|| Home::at(lo - UVec2::ONE))
395 }
396
397 pub fn surplus_beds(communal: &[UVec2], homeless_adults: usize, toward: UVec2) -> Vec<UVec2> {
398 let mut beds = communal.to_vec();
399 beds.sort_by_key(|b| {
400 let d = b.as_ivec2() - toward.as_ivec2();
401 (d.length_squared(), b.y, b.x)
402 });
403 beds.split_off(homeless_adults.min(beds.len()))
404 }
405
406 pub fn roofs_needed(map: &WorldMap, doors: &HashSet<UVec2>, home: &Home) -> Vec<UVec2> {
407 let interior: Vec<UVec2> = home.interior().collect();
408 let Some(room) = enclosed_room(map, doors, interior[0]) else {
409 return Vec::new();
410 };
411 if room.len() != interior.len() {
412 return Vec::new();
413 }
414 interior
415 .into_iter()
416 .filter(|t| !map.is_roofed(t.as_ivec2()))
417 .collect()
418 }
419
420 #[allow(clippy::too_many_arguments)]
421 fn plan_homes(
422 tick: Res<SimTick>,
423 map: Res<WorldMap>,
424 zones: Res<Zones>,
425 mut homes: ResMut<Homes>,
426 mut blueprints: ResMut<Blueprints>,
427 structures: Query<(&TilePos, &Structure), Without<Colonist>>,
428 items: Query<&TilePos, With<Item>>,
429 families: Query<(Option<&Family>, Has<Partner>, Has<Child>), With<Colonist>>,
430 ) {
431 if !tick.0.is_multiple_of(HOME_PLAN_INTERVAL_TICKS) {
432 return;
433 }
434 let colony_home = zones.home(map.size / 2);
435 let living: HashSet<u32> = families
436 .iter()
437 .filter_map(|(f, ..)| f)
438 .map(|f| f.0)
439 .collect();
440 let extinct: Vec<u32> = homes
441 .by_family
442 .keys()
443 .filter(|f| !living.contains(f))
444 .copied()
445 .collect();
446 for family in extinct {
447 if let Some(home) = homes.by_family.remove(&family) {
448 homes.vacant.push(home);
449 }
450 }
451 let of_kind = |kind: StructureKind| -> HashSet<UVec2> {
452 structures
453 .iter()
454 .filter(|(_, s)| s.kind == kind)
455 .map(|(pos, _)| pos.0)
456 .collect()
457 };
458 let doors = of_kind(StructureKind::Door);
459 let statues = of_kind(StructureKind::Statue);
460 let beds = of_kind(StructureKind::Bed);
461 for &bed in &beds {
462 if !homes.is_home(bed)
463 && let Some(home) = abandoned_home(&map, &doors, bed)
464 && !homes.all().any(|h| h.ring().any(|t| home.contains(t)))
465 {
466 homes.vacant.push(home);
467 }
468 }
469 let homeless_family = |homes: &Homes| {
470 families
471 .iter()
472 .filter(|(_, partnered, _)| *partnered)
473 .filter_map(|(f, ..)| f)
474 .map(|f| f.0)
475 .filter(|f| !homes.by_family.contains_key(f))
476 .min()
477 };
478 while let Some(family) = homeless_family(&homes)
479 && let Some(index) = (0..homes.vacant.len()).min_by_key(|&i| {
480 let d = homes.vacant[i].lo.as_ivec2() - colony_home.as_ivec2();
481 d.length_squared()
482 })
483 {
484 let home = homes.vacant.swap_remove(index);
485 homes.by_family.insert(family, home);
486 }
487 let mut reachable = HashSet::new();
488 nearest_tile(&map, colony_home, usize::MAX, |p| {
489 reachable.insert(p);
490 false
491 });
492 let anchored = map.move_cost(colony_home.as_ivec2()).is_some();
493 blueprints.0.retain(|tile, _| {
494 !anchored
495 || (-1..=1).any(|dy| {
496 (-1..=1).any(|dx| {
497 let near = tile.as_ivec2() + IVec2::new(dx, dy);
498 near.min_element() >= 0 && reachable.contains(&near.as_uvec2())
499 })
500 })
501 });
502 let owned: HashSet<Home> = homes.by_family.values().copied().collect();
503 let door = BuildKind::Structure(StructureKind::Door);
504 let entries: HashSet<UVec2> = blueprints
505 .0
506 .iter()
507 .filter(|(_, kind)| **kind == door)
508 .map(|(tile, _)| *tile)
509 .chain(doors.iter().copied())
510 .collect();
511 for home in homes.all() {
512 if let Some((tile, kind)) = door_repair(&map, &entries, &reachable, home, colony_home) {
513 blueprints.0.insert(tile, kind);
514 continue;
515 }
516 if blueprints.0.keys().any(|t| home.contains(*t)) {
517 continue;
518 }
519 let roofs = roofs_needed(&map, &doors, home);
520 let built = roofs.is_empty() && home.interior().all(|t| map.is_roofed(t.as_ivec2()));
521 for tile in roofs {
522 blueprints.0.insert(tile, BuildKind::Roof);
523 }
524 if built && owned.contains(home) && !statues.iter().any(|&t| home.contains(t)) {
525 let statue = BuildKind::Structure(StructureKind::Statue);
526 blueprints.0.insert(home.statue_tile(), statue);
527 }
528 }
529 let homeless_adults = families
530 .iter()
531 .filter(|(family, _, child)| !child && homes.of(family.copied()).is_none())
532 .count();
533 let communal: Vec<UVec2> = beds
534 .iter()
535 .filter(|b| !homes.is_home(**b) && blueprints.get(**b).is_none() && reachable.contains(b))
536 .copied()
537 .collect();
538 for bed in surplus_beds(&communal, homeless_adults, colony_home) {
539 blueprints.0.insert(bed, BuildKind::Deconstruct);
540 }
541 let Some(family) = homeless_family(&homes) else {
542 return;
543 };
544 let occupied: HashSet<UVec2> = structures
545 .iter()
546 .map(|(pos, _)| pos.0)
547 .chain(items.iter().map(|pos| pos.0))
548 .collect();
549 let ctx = HomeContext {
550 map: &map,
551 zones: &zones,
552 blueprints: &blueprints,
553 homes: &homes,
554 occupied: &occupied,
555 };
556 if let Some(home) = ctx.plan(colony_home) {
557 blueprints.0.extend(home.blueprints(colony_home));
558 homes.by_family.insert(family, home);
559 }
560 }
561
562 #[allow(clippy::too_many_arguments, clippy::type_complexity)]
563 fn births(
564 mut commands: Commands,
565 tick: Res<SimTick>,
566 map: Res<WorldMap>,
567 zones: Res<Zones>,
568 homes: Res<Homes>,
569 assets: Res<ColonistAssets>,
570 item_assets: Res<ItemAssets>,
571 mut materials: ResMut<Assets<ColorMaterial>>,
572 mut rng: ResMut<SimRng>,
573 mut log: ResMut<ColonyLog>,
574 items: Query<(&Item, &TilePos)>,
575 structures: Query<(&TilePos, &Structure), Without<Colonist>>,
576 colonists: Query<(&Colonist, Option<&Family>, Has<Partner>, Has<Child>)>,
577 ) {
578 if tick.0 % DAY_TICKS != BIRTH_HOUR_TICK {
579 return;
580 }
581 let count = colonists.iter().count();
582 let colony_home = zones.home(map.size / 2);
583 let food = food_in_store(
584 items
585 .iter()
586 .filter(|(_, pos)| in_colony(colony_home, pos.0))
587 .map(|(item, _)| item),
588 );
589 let mut born = 0;
590 let mut taken: Vec<&str> = colonists.iter().map(|c| c.0.name.as_str()).collect();
591 let mut families: Vec<(&u32, &Home)> = homes.by_family.iter().collect();
592 families.sort_by_key(|(family, _)| **family);
593 for (&family, home) in families {
594 let members = || {
595 colonists
596 .iter()
597 .filter(move |c| c.1 == Some(&Family(family)))
598 };
599 let parents: Vec<&str> = members()
600 .filter(|c| c.2)
601 .map(|c| c.0.name.as_str())
602 .collect();
603 let children = members().filter(|c| c.3).count();
604 let beds = structures
605 .iter()
606 .filter(|(pos, s)| s.kind == StructureKind::Bed && home.contains(pos.0))
607 .count();
608 let built = home.interior().all(|t| map.is_roofed(t.as_ivec2()));
609 let room = count + born < MAX_COLONISTS && food >= (count + born) as f32;
610 if parents.len() < 2 || children >= MAX_CHILDREN || beds < 2 || !built || !room {
611 continue;
612 }
613 if rng.range_f32(0.0..1.0) >= BIRTH_CHANCE {
614 continue;
615 }
616 let index = (0..NAMES.len())
617 .find(|&i| !taken.contains(&NAMES[i]))
618 .unwrap_or(count + born);
619 if let Some(name) = NAMES.get(index) {
620 taken.push(name);
621 }
622 let tile = home
623 .interior()
624 .find(|t| !home.bed_tiles().contains(t))
625 .unwrap_or(home.lo);
626 let child = spawn_colonist(
627 &mut commands,
628 &assets,
629 &item_assets,
630 &mut materials,
631 index,
632 tile,
633 );
634 commands.entity(child).insert((
635 Child { born: tick.0 },
636 Family(family),
637 Transform::from_translation(WorldMap::tile_center(tile).extend(1.0))
638 .with_scale(Vec3::splat(CHILD_SCALE)),
639 ));
640 born += 1;
641 log.push(
642 *tick,
643 format!(
644 "{} and {} had a child, {}",
645 parents[0],
646 parents[1],
647 NAMES[index % NAMES.len()]
648 ),
649 );
650 }
651 }
652
653 fn grow_up(
654 mut commands: Commands,
655 tick: Res<SimTick>,
656 mut log: ResMut<ColonyLog>,
657 mut children: Query<(Entity, &Colonist, &Child, &mut Transform)>,
658 ) {
659 if !tick.0.is_multiple_of(TICKS_PER_HOUR) {
660 return;
661 }
662 for (entity, colonist, child, mut transform) in &mut children {
663 if tick.0 < child.born + CHILDHOOD_TICKS {
664 continue;
665 }
666 transform.scale = Vec3::ONE;
667 commands.entity(entity).remove::<Child>();
668 log.push(*tick, format!("{} has grown up", colonist.name));
669 }
670 }
671
672 #[cfg(test)]
673 mod tests {
674 use super::*;
675 use crate::world::Terrain;
676
677 fn singles(app_world: &mut World, tiles: &[UVec2]) -> Vec<Single> {
678 tiles
679 .iter()
680 .map(|&tile| Single {
681 entity: app_world.spawn_empty().id(),
682 tile,
683 family: None,
684 })
685 .collect()
686 }
687
688 fn bond_for(hours: u32, singles: &[Single]) -> Vec<(Entity, Entity)> {
689 let mut affinity = Affinity::default();
690 let mut rng = SimRng::new(3);
691 let mut bonded: Vec<(Entity, Entity)> = Vec::new();
692 for _ in 0..hours {
693 let free: Vec<Single> = singles
694 .iter()
695 .filter(|s| !bonded.iter().any(|&(a, b)| a == s.entity || b == s.entity))
696 .copied()
697 .collect();
698 bonded.extend(bond_hour(&mut affinity, &free, &mut rng));
699 }
700 bonded
701 }
702
703 #[test]
704 fn colonists_who_spend_time_together_become_partners() {
705 let mut world = World::new();
706 let near = singles(&mut world, &[UVec2::new(5, 5), UVec2::new(6, 7)]);
707 assert!(bond_for(BOND_HOURS - 1, &near).is_empty());
708 assert_eq!(bond_for(BOND_HOURS * 4, &near).len(), 1);
709 let apart = singles(&mut world, &[UVec2::new(5, 5), UVec2::new(15, 5)]);
710 assert!(bond_for(BOND_HOURS * 4, &apart).is_empty());
711 }
712
713 #[test]
714 fn everyone_has_at_most_one_partner_and_family_never_pairs() {
715 let mut world = World::new();
716 let mut trio = singles(&mut world, &[UVec2::ONE, UVec2::ONE, UVec2::ONE]);
717 let bonded = bond_for(BOND_HOURS * 10, &trio);
718 assert_eq!(bonded.len(), 1);
719 for single in &mut trio {
720 single.family = Some(Family(1));
721 }
722 assert!(bond_for(BOND_HOURS * 10, &trio).is_empty());
723 }
724
725 fn plan_on(map: &WorldMap, zones: &Zones, occupied: &HashSet<UVec2>) -> Home {
726 HomeContext {
727 map,
728 zones,
729 blueprints: &Blueprints::default(),
730 homes: &Homes::default(),
731 occupied,
732 }
733 .plan(UVec2::new(20, 20))
734 .unwrap()
735 }
736
737 #[test]
738 fn homes_go_on_open_ground_away_from_the_colony_center() {
739 let mut map = WorldMap::filled(UVec2::splat(40), Terrain::Grass);
740 for x in 0..40 {
741 map.set_plant(UVec2::new(x, 14), Some(crate::world::Plant::Tree));
742 }
743 let mut zones = Zones::default();
744 zones.add_tiles(&map, [UVec2::new(20, 20), UVec2::new(21, 20)]);
745 let occupied = HashSet::from([UVec2::new(20, 26)]);
746 let home = plan_on(&map, &zones, &occupied);
747 let center = (home.lo + home.hi).as_ivec2() / 2;
748 assert!((center - IVec2::new(20, 20)).abs().max_element() >= HOME_MIN_DISTANCE);
749 for y in home.lo.y - 1..=home.hi.y + 1 {
750 for x in home.lo.x - 1..=home.hi.x + 1 {
751 let tile = UVec2::new(x, y);
752 assert!(!zones.is_stockpile(tile));
753 if home.contains(tile) {
754 assert!(map.plant(tile.as_ivec2()).is_none());
755 assert!(!occupied.contains(&tile));
756 }
757 }
758 }
759 }
760
761 #[test]
762 fn a_home_is_a_walled_room_with_a_door_and_two_beds() {
763 let home = Home::at(UVec2::new(10, 10));
764 let plan = home.blueprints(UVec2::new(12, 0));
765 let count = |kind: StructureKind| {
766 plan.values()
767 .filter(|k| **k == BuildKind::Structure(kind))
768 .count()
769 };
770 let ring = 2 * (HOME_INTERIOR.x + 2) + 2 * HOME_INTERIOR.y;
771 assert_eq!(
772 count(StructureKind::Wall) + count(StructureKind::Door),
773 ring as usize
774 );
775 assert_eq!(count(StructureKind::Door), 1);
776 assert_eq!(count(StructureKind::Bed), 2);
777 let door = plan
778 .iter()
779 .find(|(_, k)| **k == BuildKind::Structure(StructureKind::Door))
780 .unwrap()
781 .0;
782 assert_eq!(door.y, home.lo.y);
783 for bed in home.bed_tiles() {
784 assert!(home.interior().any(|t| t == bed));
785 }
786 }
787
788 #[test]
789 fn finished_homes_get_a_roof() {
790 let mut map = WorldMap::filled(UVec2::splat(20), Terrain::Grass);
791 let home = Home::at(UVec2::new(5, 5));
792 let door = UVec2::new(7, 5);
793 for tile in home.ring().filter(|t| *t != door) {
794 map.set_wall(tile, true);
795 }
796 assert!(roofs_needed(&map, &HashSet::new(), &home).is_empty());
797 let roofs = roofs_needed(&map, &HashSet::from([door]), &home);
798 assert_eq!(roofs.len(), (HOME_INTERIOR.x * HOME_INTERIOR.y) as usize);
799 }
800
801 // Gold has one use: a statue in each finished home, which lifts the family's mood. Planning
802 // it is what makes the colony want gold at all.
803 #[test]
804 fn finished_homes_get_a_statue() {
805 let mut map = WorldMap::filled(UVec2::splat(20), Terrain::Grass);
806 let home = Home::at(UVec2::new(5, 5));
807 let door = UVec2::new(7, 5);
808 for tile in home.ring().filter(|t| *t != door) {
809 map.set_wall(tile, true);
810 }
811 for tile in home.interior() {
812 map.set_roof(tile, true);
813 }
814 let mut app = App::new();
815 app.insert_resource(map)
816 .init_resource::<SimTick>()
817 .init_resource::<Zones>()
818 .init_resource::<Blueprints>()
819 .insert_resource(Homes {
820 by_family: HashMap::from([(1, home)]),
821 ..default()
822 })
823 .add_systems(Update, plan_homes);
824 app.world_mut().spawn((
825 Structure {
826 kind: StructureKind::Door,
827 },
828 TilePos(door),
829 ));
830 app.world_mut()
831 .spawn((Colonist { name: "Ada".into() }, Family(1)));
832 app.update();
833 let blueprints = app.world().resource::<Blueprints>();
834 assert_eq!(
835 blueprints.get(home.statue_tile()),
836 Some(BuildKind::Structure(StructureKind::Statue))
837 );
838 }
839
840 fn walled(map: &mut WorldMap, home: Home, door: UVec2) -> HashSet<UVec2> {
841 for tile in home.ring().filter(|t| *t != door) {
842 map.set_wall(tile, true);
843 }
844 HashSet::from([door])
845 }
846
847 fn reachable(map: &WorldMap, from: UVec2) -> HashSet<UVec2> {
848 let mut seen = HashSet::new();
849 nearest_tile(map, from, usize::MAX, |p| {
850 seen.insert(p);
851 false
852 });
853 seen
854 }
855
856 // New homes keep a walkable tile all around, so any door they get opens onto open ground.
857 // Homes used to be packed wall to wall and their doors ended up facing a neighbour's wall.
858 #[test]
859 fn new_homes_never_touch_existing_walls() {
860 let mut map = WorldMap::filled(UVec2::splat(40), Terrain::Grass);
861 for y in 0..40 {
862 map.set_wall(UVec2::new(27, y), true);
863 }
864 let mut zones = Zones::default();
865 zones.add_tiles(&map, [UVec2::new(20, 20)]);
866 let home = plan_on(&map, &zones, &HashSet::new());
867 for y in home.lo.y - 1..=home.hi.y + 1 {
868 for x in home.lo.x - 1..=home.hi.x + 1 {
869 assert!(!map.is_wall(IVec2::new(x as i32, y as i32)), "{home:?}");
870 }
871 }
872 }
873
874 // A home whose only door faces a wall can't be entered; it gets a new door on a side that
875 // opens onto ground connected to the colony, knocking out a wall first if needed.
876 #[test]
877 fn homes_with_a_blocked_door_get_a_new_one() {
878 let mut map = WorldMap::filled(UVec2::splat(20), Terrain::Grass);
879 let home = Home::at(UVec2::new(5, 5));
880 let blocked = UVec2::new(7, 5);
881 let doors = walled(&mut map, home, blocked);
882 map.set_wall(UVec2::new(7, 4), true);
883 let colony = UVec2::new(7, 0);
884 let open = reachable(&map, colony);
885 let (site, kind) = door_repair(&map, &doors, &open, &home, colony).unwrap();
886 assert_eq!(kind, BuildKind::Deconstruct);
887 assert!(home.door_sites().any(|t| t == site) && site != blocked);
888 map.set_wall(site, false);
889 let open = reachable(&map, colony);
890 assert_eq!(
891 door_repair(&map, &doors, &open, &home, colony),
892 Some((site, BuildKind::Structure(StructureKind::Door)))
893 );
894 let fine = walled(
895 &mut WorldMap::filled(UVec2::splat(20), Terrain::Grass),
896 home,
897 blocked,
898 );
899 let map = WorldMap::filled(UVec2::splat(20), Terrain::Grass);
900 assert_eq!(
901 door_repair(&map, &fine, &reachable(&map, colony), &home, colony),
902 None
903 );
904 }
905
906 // Blueprints sealed off from the colony can never be built; they only inflate material
907 // targets, so they are dropped (a home's own repairs reopen it and plan again).
908 #[test]
909 fn unreachable_blueprints_are_dropped() {
910 let mut map = WorldMap::filled(UVec2::splat(20), Terrain::Grass);
911 let pocket = Home::at(UVec2::new(12, 12));
912 for tile in pocket.ring() {
913 map.set_wall(tile, true);
914 }
915 let mut app = App::new();
916 app.insert_resource(map)
917 .init_resource::<SimTick>()
918 .init_resource::<Zones>()
919 .init_resource::<Homes>()
920 .insert_resource(Blueprints(HashMap::from([
921 (UVec2::new(14, 14), BuildKind::Roof),
922 (UVec2::new(2, 2), BuildKind::Roof),
923 (UVec2::new(12, 12), BuildKind::Deconstruct),
924 ])))
925 .add_systems(Update, plan_homes);
926 app.update();
927 let blueprints = app.world().resource::<Blueprints>();
928 assert_eq!(blueprints.get(UVec2::new(14, 14)), None);
929 assert!(blueprints.get(UVec2::new(2, 2)).is_some());
930 assert!(blueprints.get(UVec2::new(12, 12)).is_some());
931 }
932
933 // Couples move into the homes of families that died out before anyone builds anew, and
934 // communal beds beyond the adults who still lack a home are taken down.
935 #[test]
936 fn vacant_homes_are_reused_and_spare_beds_removed() {
937 let mut map = WorldMap::filled(UVec2::splat(30), Terrain::Grass);
938 let old = Home::at(UVec2::new(5, 5));
939 let door = UVec2::new(7, 5);
940 walled(&mut map, old, door);
941 for tile in old.interior() {
942 map.set_roof(tile, true);
943 }
944 let mut app = App::new();
945 app.insert_resource(map)
946 .init_resource::<SimTick>()
947 .init_resource::<Zones>()
948 .init_resource::<Blueprints>()
949 .init_resource::<Homes>()
950 .add_systems(Update, plan_homes);
951 let world = app.world_mut();
952 let structure = |kind| Structure { kind };
953 world.spawn((structure(StructureKind::Door), TilePos(door)));
954 for bed in old.bed_tiles() {
955 world.spawn((structure(StructureKind::Bed), TilePos(bed)));
956 }
957 for x in 20..24 {
958 world.spawn((structure(StructureKind::Bed), TilePos(UVec2::new(x, 20))));
959 }
960 let a = world
961 .spawn((Colonist { name: "Ada".into() }, Family(2)))
962 .id();
963 let b = world
964 .spawn((
965 Colonist {
966 name: "Bram".into(),
967 },
968 Family(2),
969 Partner(a),
970 ))
971 .id();
972 world.entity_mut(a).insert(Partner(b));
973 world.spawn(Colonist {
974 name: "Cleo".into(),
975 });
976 app.update();
977 let homes = app.world().resource::<Homes>();
978 assert_eq!(homes.by_family.get(&2), Some(&old));
979 let blueprints = app.world().resource::<Blueprints>();
980 let removed = blueprints
981 .0
982 .values()
983 .filter(|k| **k == BuildKind::Deconstruct)
984 .count();
985 assert_eq!(removed, 3);
986 assert!(
987 !blueprints
988 .0
989 .values()
990 .any(|k| *k == BuildKind::Structure(StructureKind::Wall))
991 );
992 }
993 }