use bevy::prelude::*; use crate::{ colonist::{Colonist, Path}, items::Item, jobs::{CurrentJob, Job, Reservations, Target, Task}, light::StructureKind, pathfinding::nearest_tile, sim::{SimSystems, TICKS_PER_HOUR}, 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 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(mut colonists: Query<(&mut Rest, &CurrentJob, &TilePos, &Path)>) { for (mut rest, job, tile, path) in &mut colonists { let change = if is_sleeping(job, tile, path) { REST_RECOVERY_PER_TICK } else { -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 fires: &'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.fires.iter().any(|(pos, ..)| *pos == tile) && !self.items.iter().any(|(_, pos)| pos.0 == tile) && self.reservations.is_free(Target::SleepSpot(tile)) } pub fn spot(&self, from: UVec2) -> UVec2 { let campfire = self .fires .iter() .filter(|(_, kind, _)| *kind == StructureKind::Campfire) .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())) }); let anchor = campfire.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((Rest(0.5), CurrentJob(None), TilePos(tile), Path::default())) .id(); let asleep = app .world_mut() .spawn(( 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); } #[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: &[], fires: &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)); } }