use std::collections::HashSet; use bevy::prelude::*; use crate::{ building::Blueprints, climate::Warmth, colonist::{Colonist, Path}, family::{Family, Homes}, items::Item, jobs::{CurrentJob, Job, Reservations, Target, Task}, pathfinding::nearest_tile, sim::{SimSystems, TICKS_PER_HOUR}, structures::{Structure, StructureKind}, world::{TILE_SIZE, TilePos, WorldMap}, zones::{Zones, can_zone}, }; pub struct NeedsPlugin; impl Plugin for NeedsPlugin { fn build(&self, app: &mut App) { app.add_systems(FixedUpdate, update_rest.in_set(SimSystems::Act)) .add_systems(Update, show_sleep_markers); } } pub const REST_DRAIN_PER_TICK: f32 = 1.0 / (24.0 * TICKS_PER_HOUR as f32); pub const REST_RECOVERY_PER_TICK: f32 = 1.0 / (7.0 * TICKS_PER_HOUR as f32); pub const BED_REST_RECOVERY_PER_TICK: f32 = 1.0 / (5.0 * TICKS_PER_HOUR as f32); pub const ROOF_REST_BONUS: f32 = 1.25; pub const COLD_REST_FACTOR: f32 = 0.5; pub const BEDTIME_REST: f32 = 0.9; pub const NAP_REST: f32 = 0.3; pub const EXHAUSTED_REST: f32 = 0.1; const SLEEP_SPOT_SEARCH_TILES: usize = 3000; #[derive(Component, Debug, Clone, Copy, PartialEq)] pub struct Rest(pub f32); impl Default for Rest { fn default() -> Self { Self(1.0) } } pub fn is_night(hour: f32) -> bool { !(6.0..21.0).contains(&hour) } pub fn wants_sleep(rest: f32, hour: f32) -> bool { rest < NAP_REST || (is_night(hour) && rest < BEDTIME_REST) } pub fn done_sleeping(rest: f32, hour: f32) -> bool { rest >= 1.0 && !is_night(hour) } pub fn is_sleeping(job: &CurrentJob, tile: &TilePos, path: &Path) -> bool { matches!( job.0, Some(Job { task: Task::Sleep { spot }, .. }) if spot == tile.0 && path.0.is_empty() ) } pub fn update_rest( map: Res, structures: Query<(&TilePos, &Structure), Without>, mut colonists: Query<(&mut Rest, &CurrentJob, &TilePos, &Path, &Warmth), With>, ) { let beds: HashSet = structures .iter() .filter(|(_, s)| s.kind == StructureKind::Bed) .map(|(pos, _)| pos.0) .collect(); for (mut rest, job, tile, path, warmth) in &mut colonists { let change = match (is_sleeping(job, tile, path), beds.contains(&tile.0)) { (true, true) => BED_REST_RECOVERY_PER_TICK, (true, false) => REST_RECOVERY_PER_TICK, (false, _) => -REST_DRAIN_PER_TICK, }; let change = if change > 0.0 && map.is_roofed(tile.0.as_ivec2()) { change * ROOF_REST_BONUS } else { change }; let change = if change > 0.0 && warmth.cold() { change * COLD_REST_FACTOR } else { change }; rest.0 = (rest.0 + change).clamp(0.0, 1.0); } } pub struct SleepContext<'a> { pub map: &'a WorldMap, pub zones: &'a Zones, pub reservations: &'a Reservations, pub items: &'a [(Item, TilePos)], pub structures: &'a [(UVec2, StructureKind, u32)], pub blueprints: &'a Blueprints, pub homes: &'a Homes, pub family: Option, pub child: bool, } impl SleepContext<'_> { fn free(&self, tile: UVec2) -> bool { can_zone(self.map, tile.as_ivec2()) && self.map.plant(tile.as_ivec2()).is_none() && !self.zones.is_stockpile(tile) && !self.structures.iter().any(|(pos, ..)| *pos == tile) && !self.items.iter().any(|(_, pos)| pos.0 == tile) && self.blueprints.get(tile).is_none() && self.reservations.is_free(Target::SleepSpot(tile)) } fn nearest( &self, kind: StructureKind, from: UVec2, allowed: impl Fn(UVec2) -> bool, ) -> Option { self.structures .iter() .filter(|(pos, k, _)| { *k == kind && allowed(*pos) && (kind != StructureKind::Bed || self.reservations.is_free(Target::SleepSpot(*pos))) }) .map(|(pos, ..)| *pos) .min_by(|a, b| { a.as_vec2() .distance_squared(from.as_vec2()) .total_cmp(&b.as_vec2().distance_squared(from.as_vec2())) }) } pub fn spot(&self, from: UVec2) -> UVec2 { if let Some(home) = self.homes.of(self.family) { let own_bed = (!self.child) .then(|| self.nearest(StructureKind::Bed, from, |p| home.contains(p))) .flatten(); let built = home.interior().all(|t| self.map.is_roofed(t.as_ivec2())); let floor = || { built .then(|| home.interior().find(|&t| self.free(t))) .flatten() }; if let Some(spot) = own_bed.or_else(floor) { return spot; } } let communal = |p: UVec2| self.homes.owner(p).is_none(); if let Some(bed) = self.nearest(StructureKind::Bed, from, communal) { return bed; } let anchor = self .nearest(StructureKind::Campfire, from, |_| true) .unwrap_or_else(|| self.zones.home(from)); nearest_tile(self.map, anchor, SLEEP_SPOT_SEARCH_TILES, |p| self.free(p)).unwrap_or(from) } } #[derive(Component)] pub struct SleepMarker; pub fn sleep_marker() -> impl Bundle { ( SleepMarker, Text2d::new("z"), TextFont::from_font_size(12.0), TextColor(Color::srgb(0.85, 0.9, 1.0)), Transform::from_xyz(TILE_SIZE * 0.35, TILE_SIZE * 0.45, 0.2), Visibility::Hidden, ) } fn show_sleep_markers( colonists: Query<(&CurrentJob, &TilePos, &Path, &Children), With>, mut markers: Query<&mut Visibility, With>, ) { for (job, tile, path, children) in &colonists { let shown = if is_sleeping(job, tile, path) { Visibility::Inherited } else { Visibility::Hidden }; for &child in children { if let Ok(mut visibility) = markers.get_mut(child) { visibility.set_if_neq(shown); } } } } #[cfg(test)] mod tests { use super::*; use crate::{family::Home, world::Terrain}; #[test] fn colonists_sleep_at_night_and_nap_only_when_tired() { assert!(wants_sleep(0.8, 22.0)); assert!(!wants_sleep(0.95, 22.0)); assert!(!wants_sleep(0.8, 12.0)); assert!(wants_sleep(0.2, 12.0)); } // A colonist that is fully rested at 3 am keeps resting rather than wandering off into the // dark; the night ends sleep, a full rest bar alone does not. #[test] fn sleep_lasts_until_morning() { assert!(!done_sleeping(1.0, 3.0)); assert!(done_sleeping(1.0, 7.0)); assert!(!done_sleeping(0.7, 7.0)); } #[test] fn rest_drains_awake_and_recovers_asleep() { let mut app = App::new(); app.insert_resource(WorldMap::filled(UVec2::splat(10), Terrain::Grass)) .add_systems(Update, update_rest); let tile = UVec2::new(3, 3); let awake = app .world_mut() .spawn(( Colonist { name: "Waker".into(), }, Rest(0.5), CurrentJob(None), TilePos(tile), Path::default(), )) .id(); let asleep = app .world_mut() .spawn(( Colonist { name: "Sleeper".into(), }, Rest(0.5), CurrentJob(Some(Job { task: Task::Sleep { spot: tile }, ordered: false, })), TilePos(tile), Path::default(), )) .id(); app.update(); assert!(app.world().get::(awake).unwrap().0 < 0.5); assert!(app.world().get::(asleep).unwrap().0 > 0.5); } fn sleeper(app: &mut App, tile: UVec2) -> Entity { app.world_mut() .spawn(( Colonist { name: "Sleeper".into(), }, Rest(0.2), CurrentJob(Some(Job { task: Task::Sleep { spot: tile }, ordered: false, })), TilePos(tile), Path::default(), )) .id() } #[test] fn beds_restore_rest_faster_than_the_ground() { let mut app = App::new(); app.insert_resource(WorldMap::filled(UVec2::splat(10), Terrain::Grass)) .add_systems(Update, update_rest); let bed = UVec2::new(1, 1); app.world_mut().spawn(( Structure { kind: StructureKind::Bed, }, TilePos(bed), )); let in_bed = sleeper(&mut app, bed); let on_ground = sleeper(&mut app, UVec2::new(5, 5)); app.update(); let rest = |e| app.world().get::(e).unwrap().0; assert!(rest(in_bed) > rest(on_ground)); } #[test] fn sleeping_under_a_roof_restores_more_rest() { let mut map = WorldMap::filled(UVec2::splat(10), Terrain::Grass); map.set_roof(UVec2::new(1, 1), true); let mut app = App::new(); app.insert_resource(map).add_systems(Update, update_rest); let sheltered = sleeper(&mut app, UVec2::new(1, 1)); let outside = sleeper(&mut app, UVec2::new(5, 5)); app.update(); let rest = |e| app.world().get::(e).unwrap().0; assert!(rest(sheltered) > rest(outside)); } #[test] fn sleepers_take_a_free_bed_over_the_campfire() { let map = WorldMap::filled(UVec2::splat(20), Terrain::Grass); let zones = Zones::default(); let mut reservations = Reservations::default(); let structures = [ (UVec2::new(3, 3), StructureKind::Campfire, 1000), (UVec2::new(15, 15), StructureKind::Bed, u32::MAX), (UVec2::new(16, 15), StructureKind::Bed, u32::MAX), ]; reservations.reserve(Target::SleepSpot(UVec2::new(15, 15)), Entity::PLACEHOLDER); let ctx = SleepContext { map: &map, zones: &zones, reservations: &reservations, items: &[], structures: &structures, blueprints: &Blueprints::default(), homes: &Homes::default(), family: None, child: false, }; assert_eq!(ctx.spot(UVec2::new(2, 2)), UVec2::new(16, 15)); } #[test] fn families_sleep_at_home_and_leave_other_homes_alone() { let mut map = WorldMap::filled(UVec2::splat(30), Terrain::Grass); let zones = Zones::default(); let reservations = Reservations::default(); let mut homes = Homes::default(); let ours = homes.new_family(); let theirs = homes.new_family(); let our_home = Home::at(UVec2::new(20, 20)); let their_home = Home::at(UVec2::new(2, 2)); homes.by_family.insert(ours.0, our_home); homes.by_family.insert(theirs.0, their_home); for tile in our_home.interior() { map.set_roof(tile, true); } let mut structures: Vec<(UVec2, StructureKind, u32)> = our_home .bed_tiles() .into_iter() .chain(their_home.bed_tiles()) .map(|t| (t, StructureKind::Bed, u32::MAX)) .collect(); let communal = UVec2::new(12, 12); structures.push((communal, StructureKind::Bed, u32::MAX)); let blueprints = Blueprints::default(); let ctx = |family, child| SleepContext { map: &map, zones: &zones, reservations: &reservations, items: &[], structures: &structures, blueprints: &blueprints, homes: &homes, family, child, }; assert!( our_home .bed_tiles() .contains(&ctx(Some(ours), false).spot(UVec2::ONE)) ); assert_eq!(ctx(None, false).spot(UVec2::ONE), communal); let child_spot = ctx(Some(ours), true).spot(UVec2::ONE); assert!(our_home.interior().any(|t| t == child_spot)); assert!(!our_home.bed_tiles().contains(&child_spot)); } #[test] fn sleepers_bed_down_by_the_campfire() { let map = WorldMap::filled(UVec2::splat(20), Terrain::Grass); let zones = Zones::default(); let reservations = Reservations::default(); let fires = [(UVec2::new(15, 15), StructureKind::Campfire, 1000)]; let ctx = SleepContext { map: &map, zones: &zones, reservations: &reservations, items: &[], structures: &fires, blueprints: &Blueprints::default(), homes: &Homes::default(), family: None, child: false, }; let spot = ctx.spot(UVec2::new(2, 2)); assert!(spot.as_vec2().distance(Vec2::splat(15.0)) < 2.0); assert_ne!(spot, UVec2::new(15, 15)); } }