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