//! Shared types for Iron Lifeline. Every other module builds on these. use bevy::prelude::{Component, Message, Resource, Vec2}; /// Marks a UI node (and its descendants) that never blocks map clicks, such as tooltips. #[derive(Component, Default, Clone, Copy)] pub struct UiPassThrough; /// Index into `Network::nodes`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct NodeId(pub usize); /// Goods moved over the network. Index order matches `Node::stock`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Good { Ammo, Food, Troops, Wounded, } pub const GOODS: [Good; 4] = [Good::Ammo, Good::Food, Good::Troops, Good::Wounded]; impl Good { pub fn idx(self) -> usize { match self { Good::Ammo => 0, Good::Food => 1, Good::Troops => 2, Good::Wounded => 3, } } pub fn name(self) -> &'static str { match self { Good::Ammo => "Ammo", Good::Food => "Food", Good::Troops => "Troops", Good::Wounded => "Wounded", } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum NodeKind { Capital, City, Factory, Farm, Depot, Front, } impl NodeKind { pub fn name(self) -> &'static str { match self { NodeKind::Capital => "Capital", NodeKind::City => "City", NodeKind::Factory => "Factory", NodeKind::Farm => "Farm", NodeKind::Depot => "Depot", NodeKind::Front => "Front", } } pub fn accepts(self, g: Good) -> bool { match self { NodeKind::Front => matches!(g, Good::Ammo | Good::Food | Good::Troops), NodeKind::Capital | NodeKind::City => matches!(g, Good::Food | Good::Wounded), NodeKind::Depot => true, NodeKind::Factory | NodeKind::Farm => false, } } /// What the node produces, in words, for tooltips. pub fn makes_text(self) -> &'static str { match self { NodeKind::Capital | NodeKind::City => "Troops", NodeKind::Factory => "Ammo", NodeKind::Farm => "Food", NodeKind::Depot | NodeKind::Front => "nothing", } } } #[derive(Debug, Clone, Copy, PartialEq)] pub struct FrontState { /// -1 collapse .. +1 breakthrough. Starts at 0. pub line: f32, /// 0..1 recent supply ratio. pub supply: f32, } /// A building under threat, being railed to the rear one crate at a time. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Evac { /// Game hours until the building is overrun. pub hours_left: u32, /// Crates still on site, not yet loaded. pub crates_left: u32, /// Where the crates go. Set by the first drag. pub dest: Option, /// Crates that have arrived at `dest`. pub delivered: u32, /// Index of the front sector threatening the building. pub threat: usize, } #[derive(Debug, Clone)] pub struct Node { pub name: String, pub kind: NodeKind, pub pos: Vec2, /// Indexed by `Good::idx()`: [ammo, food, troops, wounded]. pub stock: [f32; 4], pub front: Option, /// 0..1, cities only. pub hunger: f32, /// Production multiplier. 1.0 unless the site lost crates in an evacuation. pub output: f32, /// Overrun by the enemy: produces nothing and its rail is cut. pub captured: bool, pub evac: Option, } #[derive(Debug, Clone, Copy, PartialEq)] pub struct TrackSeg { pub a: NodeId, pub b: NodeId, pub length: f32, /// 0..1; below `MIN_USABLE_CONDITION` the track is blocked. pub condition: f32, } /// Tracks with condition below this value are blocked. pub const MIN_USABLE_CONDITION: f32 = 0.3; /// Tracks with condition below this value slow trains to half speed. pub const SLOW_CONDITION: f32 = 0.7; /// Speed multiplier for a train on track of the given condition. pub fn speed_factor(condition: f32) -> f32 { if condition < SLOW_CONDITION { 0.5 } else { 1.0 } } #[derive(Resource, Debug, Clone)] pub struct Network { pub nodes: Vec, pub tracks: Vec, } impl Network { /// Index of the track connecting `a` and `b` in either direction. pub fn track_between(&self, a: NodeId, b: NodeId) -> Option { self.tracks .iter() .position(|t| (t.a == a && t.b == b) || (t.a == b && t.b == a)) } /// True when either end of the track is captured. pub fn is_cut(&self, t: &TrackSeg) -> bool { self.nodes[t.a.0].captured || self.nodes[t.b.0].captured } /// Marks a node captured and breaks the track touching it. pub fn capture(&mut self, i: usize) { self.nodes[i].captured = true; for t in self.tracks.iter_mut() { if t.a.0 == i || t.b.0 == i { t.condition = 0.0; } } } /// Adjacent nodes over usable tracks (condition >= 0.3), with track length. pub fn neighbors(&self, n: NodeId) -> Vec<(NodeId, f32)> { self.tracks .iter() .filter(|t| t.condition >= MIN_USABLE_CONDITION && !self.is_cut(t)) .filter_map(|t| { if t.a == n { Some((t.b, t.length)) } else if t.b == n { Some((t.a, t.length)) } else { None } }) .collect() } /// Dijkstra over usable tracks. The returned path includes both endpoints. pub fn shortest_path(&self, from: NodeId, to: NodeId) -> Option> { let n = self.nodes.len(); if from.0 >= n || to.0 >= n { return None; } let mut dist = vec![f32::INFINITY; n]; let mut prev: Vec> = vec![None; n]; let mut done = vec![false; n]; dist[from.0] = 0.0; loop { let mut cur: Option = None; for i in 0..n { if !done[i] && dist[i].is_finite() && cur.is_none_or(|c| dist[i] < dist[c]) { cur = Some(i); } } let Some(u) = cur else { break }; if u == to.0 { break; } done[u] = true; for (v, w) in self.neighbors(NodeId(u)) { let alt = dist[u] + w; if alt < dist[v.0] { dist[v.0] = alt; prev[v.0] = Some(u); } } } if !dist[to.0].is_finite() { return None; } let mut path = vec![to]; let mut c = to.0; while let Some(p) = prev[c] { path.push(NodeId(p)); c = p; } path.reverse(); Some(path) } /// Nearest node within `radius` of `pos`. pub fn node_at(&self, pos: Vec2, radius: f32) -> Option { self.nodes .iter() .enumerate() .map(|(i, n)| (i, n.pos.distance(pos))) .filter(|(_, d)| *d <= radius) .min_by(|a, b| a.1.total_cmp(&b.1)) .map(|(i, _)| NodeId(i)) } } pub fn node(name: &str, kind: NodeKind, x: f32, y: f32, stock: [f32; 4]) -> Node { let front = (kind == NodeKind::Front).then_some(FrontState { line: 0.0, supply: 0.7, }); Node { name: name.to_string(), kind, pos: Vec2::new(x, y), stock, front, hunger: 0.0, output: 1.0, captured: false, evac: None, } } impl Default for Network { /// The operation map. World coordinates, roughly ±600 x ±340. /// Stock order: [ammo, food, troops, wounded]. fn default() -> Self { let nodes = vec![ node( "Varenholm", NodeKind::Capital, -500.0, 0.0, [0.0, 0.0, 10.0, 0.0], ), // 0 node("Brenhollow", NodeKind::City, -340.0, 160.0, [0.0; 4]), // 1 node("Kestrau", NodeKind::City, -340.0, -170.0, [0.0; 4]), // 2 node( "Ostwerk", NodeKind::Factory, -470.0, 200.0, [20.0, 0.0, 0.0, 0.0], ), // 3 node("Vellin", NodeKind::Factory, -470.0, -200.0, [0.0; 4]), // 4 node( "Lindach", NodeKind::Farm, -250.0, 110.0, [0.0, 20.0, 0.0, 0.0], ), // 5 node("Sorvik", NodeKind::Farm, -250.0, -110.0, [0.0; 4]), // 6 node("Feldau", NodeKind::Depot, 0.0, 60.0, [0.0; 4]), // 7 node("Rhunen", NodeKind::Depot, 0.0, -80.0, [0.0; 4]), // 8 node( "North Sector", NodeKind::Front, 500.0, 200.0, [40.0, 40.0, 10.0, 0.0], ), // 9 node( "Centre Sector", NodeKind::Front, 510.0, 0.0, [40.0, 40.0, 10.0, 0.0], ), // 10 node( "South Sector", NodeKind::Front, 500.0, -200.0, [40.0, 40.0, 10.0, 0.0], ), // 11 node( "Dornmark", NodeKind::Factory, 280.0, 170.0, [12.0, 0.0, 0.0, 0.0], ), // 12, forward factory: first evacuation target node("Halvik", NodeKind::Farm, 280.0, -160.0, [0.0, 15.0, 0.0, 0.0]), // 13, forward farm ]; let mut net = Network { nodes, tracks: Vec::new(), }; // Starting line: Capital-Brenhollow, Capital-Ostwerk, and the rail // from the Capital through Feldau to Centre Sector. for (a, b) in [(0usize, 1usize), (0, 3), (0, 7), (7, 10)] { let length = net.nodes[a].pos.distance(net.nodes[b].pos); net.tracks.push(TrackSeg { a: NodeId(a), b: NodeId(b), length, condition: 1.0, }); } net } } /// Cargo units one freight car holds of its good. pub const CAR_CAPACITY: f32 = 10.0; /// Speed lost per car beyond the first, as a fraction of the locomotive's speed. const CAR_SLOWDOWN: f32 = 0.05; /// Slowest a train gets, however many cars it pulls. const MIN_CAR_SPEED: f32 = 0.7; /// The locomotive that pulls a train's cars. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum LocoKind { Light, Heavy, } impl LocoKind { /// World units per second at 1x. pub fn speed(self) -> f32 { match self { LocoKind::Light => 175.0, LocoKind::Heavy => 100.0, } } /// Most cars this locomotive can pull. pub fn max_cars(self) -> usize { match self { LocoKind::Light => 3, LocoKind::Heavy => 6, } } pub fn cost(self) -> i64 { match self { LocoKind::Light => 600, LocoKind::Heavy => 1400, } } pub fn upkeep_per_week(self) -> i64 { match self { LocoKind::Light => 50, LocoKind::Heavy => 120, } } pub fn name(self) -> &'static str { match self { LocoKind::Light => "Light", LocoKind::Heavy => "Heavy", } } } /// One car type. The first four carry one good each; `Flat` carries one evacuation crate. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum CarKind { Ammo, Food, Troop, Hospital, Flat, } impl CarKind { /// Every car type, in the order the HUD shows them. pub const ALL: [CarKind; 5] = [ CarKind::Ammo, CarKind::Food, CarKind::Troop, CarKind::Hospital, CarKind::Flat, ]; /// The good this car carries, if any. pub fn good(self) -> Option { match self { CarKind::Ammo => Some(Good::Ammo), CarKind::Food => Some(Good::Food), CarKind::Troop => Some(Good::Troops), CarKind::Hospital => Some(Good::Wounded), CarKind::Flat => None, } } pub fn cost(self) -> i64 { 100 } pub fn upkeep_per_week(self) -> i64 { 10 } /// Short label for HUD buttons and tooltips. pub fn name(self) -> &'static str { match self { CarKind::Ammo => "Ammo", CarKind::Food => "Food", CarKind::Troop => "Troop", CarKind::Hospital => "Hospital", CarKind::Flat => "Flat", } } } /// Price of a locomotive pulling `cars`. pub fn consist_cost(loco: LocoKind, cars: &[CarKind]) -> i64 { loco.cost() + cars.iter().map(|c| c.cost()).sum::() } /// One ordered stop on a route. `load[g.idx()]` means load that good here. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Stop { pub node: NodeId, pub load: [bool; 4], } #[derive(Component, Debug, Clone, PartialEq)] pub struct Train { pub loco: LocoKind, /// Freight cars behind the locomotive, front to back. pub cars: Vec, pub route: Vec, pub stop_idx: usize, /// Node the train is currently at (or last left). pub at: NodeId, /// Remaining nodes to the next stop, excluding `at`. pub path: Vec, /// 0..1 along the current segment. pub progress: f32, /// [ammo, food, troops, wounded]. pub cargo: [f32; 4], /// Seconds left loading. pub dwell: f32, /// True when no path to the next stop exists. pub stalled: bool, /// Crates aboard, carried by the Flat cars. pub crates: u32, } impl Train { /// Cargo units the train can hold of `g`: one car's worth per car carrying it. pub fn capacity(&self, g: Good) -> f32 { CAR_CAPACITY * self.cars.iter().filter(|c| c.good() == Some(g)).count() as f32 } pub fn can_carry(&self, g: Good) -> bool { self.capacity(g) > 0.0 } /// Crates the train can hold: one per Flat car. pub fn crate_slots(&self) -> u32 { self.cars.iter().filter(|c| **c == CarKind::Flat).count() as u32 } /// World units per second at 1x: the locomotive's speed, less a little per car past the first. pub fn speed(&self) -> f32 { let extra = self.cars.len().saturating_sub(1) as f32; self.loco.speed() * (1.0 - CAR_SLOWDOWN * extra).max(MIN_CAR_SPEED) } pub fn upkeep_per_week(&self) -> i64 { self.loco.upkeep_per_week() + self.cars.iter().map(|c| c.upkeep_per_week()).sum::() } } #[derive(Resource, Debug, Clone, Copy, PartialEq, Eq)] pub struct Treasury(pub i64); impl Default for Treasury { fn default() -> Self { Treasury(6000) } } /// Real seconds per game hour at 1x. pub const SECS_PER_HOUR: f32 = 0.5; #[derive(Resource, Debug, Clone, Copy, PartialEq)] pub struct SimClock { /// Total elapsed game hours. pub hour: u32, /// 0 = paused, 1, 2 or 4. pub speed: u32, /// Real-time accumulator in seconds. pub acc: f32, } impl Default for SimClock { fn default() -> Self { SimClock { hour: 0, speed: 1, acc: 0.0, } } } impl SimClock { /// Elapsed whole game days. pub fn day(&self) -> u32 { self.hour / 24 } /// Elapsed whole game weeks. pub fn week(&self) -> u32 { self.hour / (24 * 7) } } #[derive(Resource, Debug, Clone, Default, PartialEq)] pub enum Tool { #[default] Inspect, BuildTrack { from: Option, }, NewRoute { loco: LocoKind, cars: Vec, stops: Vec, }, Repair, } #[derive(Resource, Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct Selected(pub Option); #[derive(Resource, Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Outcome { #[default] Ongoing, Victory, Defeat, } #[derive(Message, Debug, Clone, Copy, PartialEq, Eq)] pub struct NodeClicked(pub NodeId); #[derive(Message, Debug, Clone, Copy, PartialEq, Eq)] pub struct TrackClicked(pub usize); /// Sent once per game hour by the economy. #[derive(Message, Debug, Clone, Copy, PartialEq, Eq)] pub struct HourTick; /// News and log lines shown by the HUD. #[derive(Message, Debug, Clone, PartialEq, Eq)] pub struct Notify(pub String); pub const TRACK_COST_PER_UNIT: i64 = 2; pub const REPAIR_COST: i64 = 150; /// "Ammo 20, Food 0, Troops 5, Wounded 0", whole numbers, every good listed. pub fn stock_text(v: &[f32; 4]) -> String { GOODS .iter() .map(|g| format!("{} {:.0}", g.name(), v[g.idx()])) .collect::>() .join(", ") } #[cfg(test)] mod tests { use super::*; #[test] fn shortest_path_factory_to_centre_via_capital_and_feldau() { let net = Network::default(); // Ostwerk (3) -> Varenholm (0) -> Feldau (7) -> Centre Sector (10). let path = net.shortest_path(NodeId(3), NodeId(10)); assert_eq!( path, Some(vec![NodeId(3), NodeId(0), NodeId(7), NodeId(10)]) ); } }