use std::collections::HashSet; use bevy::prelude::*; use crate::{ colonist::{Colonist, Path}, 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 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( structures: Query<(&TilePos, &Structure), Without>, mut colonists: Query<(&mut Rest, &CurrentJob, &TilePos, &Path), With>, ) { let beds: HashSet = structures .iter() .filter(|(_, s)| s.kind == StructureKind::Bed) .map(|(pos, _)| pos.0) .collect(); for (mut rest, job, tile, path) 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, }; 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)], } 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.reservations.is_free(Target::SleepSpot(tile)) } fn nearest(&self, kind: StructureKind, from: UVec2) -> Option { self.structures .iter() .filter(|(pos, k, _)| { *k == kind && (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(bed) = self.nearest(StructureKind::Bed, from) { return bed; } let anchor = self .nearest(StructureKind::Campfire, from) .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::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.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.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 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, }; assert_eq!(ctx.spot(UVec2::new(2, 2)), UVec2::new(16, 15)); } #[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, }; 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)); } }