//! Deterministic spatial travel primitives. use std::{ cmp::Reverse, collections::{BTreeMap, BinaryHeap, HashMap, HashSet}, }; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::{epoch::EpochInfo, stats::Position}; /// An undirected, stable road between two towns. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Road { /// Stable road identity. pub id: Uuid, /// First town endpoint. pub from: Uuid, /// Second town endpoint. pub to: Uuid, /// Travel speed as a percentage of one map unit per tick. pub speed_percent: u32, /// Setting-specific searchable labels. #[serde(default)] pub tags: Vec, } /// Persisted character relationship to space. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "state", rename_all = "snake_case")] pub enum MobilityState { /// Character remains tied to one town. Resident { /// Town containing the resident. place: Uuid, }, /// Character is not tied to a town and may travel directly. Roaming { /// Current unconstrained position. position: Position, }, /// Character is following a reviewable travel plan. Travelling { /// Position at the start of this plan. origin: Position, /// Destination town. destination: Uuid, /// Towns selected by the pathfinder, including destination. route: Vec, /// Applied ticks. elapsed_ticks: u64, /// Ticks required to arrive. total_ticks: u64, }, } /// A deterministic route preview. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TravelPlan { /// Towns traversed; empty means direct off-road travel. pub route: Vec, /// Required simulation ticks. pub total_ticks: u64, /// Whether the selected route uses roads. pub uses_roads: bool, } /// Invalid topology or travel request. #[derive(Debug, thiserror::Error)] pub enum SimulationError { /// A referenced character does not exist. #[error("character @{0} does not exist")] CharacterMissing(Uuid), /// A referenced town does not exist. #[error("town @{0} does not exist")] TownMissing(Uuid), /// A road violates a topology invariant. #[error("invalid road @{id}: {reason}")] InvalidRoad { /// Offending road identity. id: Uuid, /// Violated invariant. reason: String, }, /// Travel speed must be positive. #[error("off-road speed must be greater than zero")] InvalidSpeed, } /// Validate road identities, endpoints, and speeds. pub fn validate_roads(world: &EpochInfo) -> Result<(), SimulationError> { let towns = world .towns .iter() .map(|town| town.id) .collect::>(); let mut ids = HashSet::new(); let mut edges = HashSet::new(); for road in &world.roads { let edge = if road.from < road.to { (road.from, road.to) } else { (road.to, road.from) }; let reason = if road.id.is_nil() || !ids.insert(road.id) { Some("missing or duplicate identity") } else if road.from == road.to { Some("endpoints are identical") } else if !towns.contains(&road.from) || !towns.contains(&road.to) { Some("endpoint is not a town") } else if road.speed_percent == 0 { Some("speed percentage is zero") } else if !edges.insert(edge) { Some("duplicate endpoints") } else { None }; if let Some(reason) = reason { return Err(SimulationError::InvalidRoad { id: road.id, reason: reason.into(), }); } } Ok(()) } /// Validate that mobility keys and place references match stored entities. pub fn validate_mobility(world: &EpochInfo) -> Result<(), SimulationError> { let characters = world .characters .iter() .map(|entity| entity.id) .collect::>(); let towns = world .towns .iter() .map(|entity| entity.id) .collect::>(); for (character, state) in &world.mobility { if !characters.contains(character) { return Err(SimulationError::CharacterMissing(*character)); } let place = match state { MobilityState::Resident { place } => Some(*place), MobilityState::Travelling { destination, .. } => Some(*destination), MobilityState::Roaming { .. } => None, }; if let Some(place) = place && !towns.contains(&place) { return Err(SimulationError::TownMissing(place)); } } Ok(()) } /// Select the fastest road route, falling back to slower direct travel. pub fn plan_travel( world: &EpochInfo, character: Uuid, destination: Uuid, offroad_speed: u32, ) -> Result { validate_roads(world)?; if offroad_speed == 0 { return Err(SimulationError::InvalidSpeed); } let person = world .characters .iter() .find(|entity| entity.id == character) .ok_or(SimulationError::CharacterMissing(character))?; let target = world .towns .iter() .find(|entity| entity.id == destination) .ok_or(SimulationError::TownMissing(destination))?; let direct = ticks(person.position(), target.position(), offroad_speed); let start = world .mobility .get(&character) .and_then(|state| match state { MobilityState::Resident { place } => Some(*place), _ => None, }) .or_else(|| { world .towns .iter() .find(|town| town.position() == person.position()) .map(|town| town.id) }); let Some(start) = start else { return Ok(TravelPlan { route: Vec::new(), total_ticks: direct, uses_roads: false, }); }; let Some((cost, route)) = road_route(world, start, destination) else { return Ok(TravelPlan { route: Vec::new(), total_ticks: direct, uses_roads: false, }); }; if cost < direct { Ok(TravelPlan { route, total_ticks: cost, uses_roads: true, }) } else { Ok(TravelPlan { route: Vec::new(), total_ticks: direct, uses_roads: false, }) } } /// Store a previewed plan as worktree travel intent. pub fn begin_travel( world: &mut EpochInfo, character: Uuid, destination: Uuid, plan: &TravelPlan, ) -> Result<(), SimulationError> { let origin = world .characters .iter() .find(|entity| entity.id == character) .ok_or(SimulationError::CharacterMissing(character))? .position() .clone(); world.mobility.insert( character, MobilityState::Travelling { origin, destination, route: plan.route.clone(), elapsed_ticks: 0, total_ticks: plan.total_ticks, }, ); Ok(()) } /// Advance every active journey and return the characters that arrived. pub fn tick_travel(world: &mut EpochInfo, amount: u64) -> Vec { let towns = world .towns .iter() .map(|town| (town.id, town.position().clone())) .collect::>(); let mut arrived = Vec::new(); for (character, state) in &mut world.mobility { if let MobilityState::Travelling { destination, elapsed_ticks, total_ticks, .. } = state { *elapsed_ticks = elapsed_ticks.saturating_add(amount).min(*total_ticks); if *elapsed_ticks == *total_ticks { if let Some(position) = towns.get(destination) && let Some(entity) = world .characters .iter_mut() .find(|entity| entity.id == *character) { entity.modify_position(position.clone()); } let place = *destination; *state = MobilityState::Resident { place }; arrived.push(*character); } } } arrived.sort_unstable(); arrived } /// Find the deterministic shortest road-time path. fn road_route(world: &EpochInfo, start: Uuid, destination: Uuid) -> Option<(u64, Vec)> { if start == destination { return Some((0, vec![destination])); } let towns = world .towns .iter() .map(|town| (town.id, town.position())) .collect::>(); let mut graph: HashMap> = HashMap::new(); for road in &world.roads { let cost = ticks(towns[&road.from], towns[&road.to], road.speed_percent); graph.entry(road.from).or_default().push((road.to, cost)); graph.entry(road.to).or_default().push((road.from, cost)); } for edges in graph.values_mut() { edges.sort_unstable_by_key(|edge| edge.0); } let mut distances = HashMap::from([(start, 0_u64)]); let mut previous = BTreeMap::new(); let mut queue = BinaryHeap::from([Reverse((0_u64, start))]); while let Some(Reverse((cost, node))) = queue.pop() { if node == destination { break; } if cost > *distances.get(&node).unwrap_or(&u64::MAX) { continue; } for &(next, edge) in graph.get(&node).map_or(&[][..], Vec::as_slice) { let candidate = cost.saturating_add(edge); if candidate < *distances.get(&next).unwrap_or(&u64::MAX) { distances.insert(next, candidate); previous.insert(next, node); queue.push(Reverse((candidate, next))); } } } let cost = *distances.get(&destination)?; let mut route = vec![destination]; let mut cursor = destination; while cursor != start { cursor = *previous.get(&cursor)?; route.push(cursor); } route.reverse(); Some((cost, route)) } /// Convert geometric distance and integer speed into at least one tick. fn ticks(from: &Position, to: &Position, speed_percent: u32) -> u64 { let distance = from.distance(to).unsigned_abs() as u64; distance .saturating_mul(100) .div_ceil(u64::from(speed_percent)) .max(1) }