//! Train simulation and train drawing. use bevy::prelude::*; use crate::audio::SoundEvent; use crate::map::good_color; use crate::model::{ CAR_CAPACITY, CarKind, GOODS, LocoKind, MIN_USABLE_CONDITION, Network, NodeId, Notify, SimClock, Stop, Train, speed_factor, }; use crate::seasons::SeasonState; /// The train every game starts with: a Heavy with four ammo cars running Ostwerk /// (factory, node 3) to Centre Sector (node 10), loading Ammo at Ostwerk. pub fn starting_train() -> Train { new_train( LocoKind::Heavy, vec![CarKind::Ammo; 4], vec![ Stop { node: NodeId(3), load: [true, false, false, false], }, Stop { node: NodeId(10), load: [false; 4], }, ], ) } /// A new train waiting at the first stop of `route`, with nothing aboard. pub fn new_train(loco: LocoKind, cars: Vec, route: Vec) -> Train { Train { loco, cars, at: route[0].node, route, stop_idx: 0, path: Vec::new(), progress: 0.0, cargo: [0.0; 4], dwell: 0.0, stalled: false, crates: 0, } } fn spawn_starting_train(mut commands: Commands) { commands.spawn(starting_train()); } /// World position of a train: along its current segment, or at its node. pub fn train_center(net: &Network, train: &Train) -> Vec2 { let origin = net.nodes[train.at.0].pos; match train.path.first() { Some(next) => origin.lerp(net.nodes[next.0].pos, train.progress.clamp(0.0, 1.0)), None => origin, } } /// Display number of a train, counted from 1 in spawn order. #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)] pub struct TrainNo(pub u32); /// Last number handed out. Reset to zero on restart so numbering starts again at 1. #[derive(Resource, Debug, Default)] pub struct TrainCounter(pub u32); /// Private per-train bookkeeping for stalls. #[derive(Component, Debug, Default)] struct TrainAux { /// Seconds until the next re-route attempt while stalled. retry: f32, /// True once the stall news was sent for the current stall. notified: bool, } const DWELL_SECS: f32 = 1.0; const STALL_RETRY_SECS: f32 = 1.0; /// Locomotive length, and car length and spacing, in world units. const LOCO_LEN: f32 = 18.0; const CAR_LEN: f32 = 12.0; const CAR_GAP: f32 = 2.0; const TRAIN_HALF_WIDTH: f32 = 4.0; const LOAD_EPS: f32 = 1e-4; /// Splits the free space among the goods that are in stock and have room. /// /// `room[i]` caps how much of good `i` may be taken: zero for goods the stop /// does not load or the train has no car for. Each round every open good gets /// an equal share of what is left. A good capped by its stock or its room drops /// out and its unused share goes to the others in the next round. Returns the /// amount taken per good. The result never exceeds `free` in total, nor `stock` /// or `room` per good. pub fn split_load(free: f32, stock: [f32; 4], room: [f32; 4]) -> [f32; 4] { let limit = |i: usize| stock[i].min(room[i]); let mut take = [0.0_f32; 4]; let mut left = free.max(0.0); let mut open: Vec = (0..4).filter(|&i| limit(i) > LOAD_EPS).collect(); while left > LOAD_EPS && !open.is_empty() { let share = left / open.len() as f32; let mut spent = 0.0; for &i in &open { let t = share.min(limit(i) - take[i]); take[i] += t; spent += t; } left -= spent; open.retain(|&i| limit(i) - take[i] > LOAD_EPS); } take } /// Gives every new train a `TrainNo` and its private bookkeeping. fn number_new_trains( mut commands: Commands, mut counter: ResMut, new_trains: Query>, ) { for entity in &new_trains { counter.0 += 1; commands .entity(entity) .insert((TrainNo(counter.0), TrainAux::default())); } } /// Finds the path from the train's position to its current stop target and /// drops the first element (the node it is already at). Returns false and /// marks the train stalled when no usable track exists. fn plan_next(train: &mut Train, net: &Network) -> bool { let target = train.route[train.stop_idx].node; match net.shortest_path(train.at, target) { Some(mut p) => { p.remove(0); train.path = p; train.stalled = false; true } None => { train.path.clear(); train.stalled = true; false } } } /// Plans the next leg. On failure sets the stall retry timer and sends the /// stall news once per stall. fn plan_or_stall( train: &mut Train, aux: &mut TrainAux, net: &Network, no: TrainNo, notify: &mut MessageWriter, ) { if plan_next(train, net) { aux.notified = false; return; } aux.retry = STALL_RETRY_SECS; if !aux.notified { aux.notified = true; let target = train.route[train.stop_idx].node; notify.write(Notify(format!( "Train #{} stalled: no track to {}", no.0, net.nodes[target.0].name ))); } } /// Stop actions for a train that is at its current stop node: unload, load, /// start the dwell and advance to the next stop. The caller then plans the /// path to that next stop. fn run_stop(train: &mut Train, net: &mut Network) { let stop = train.route[train.stop_idx]; // (0) Crates: credit what reached the destination to the evacuation at the // route's first stop, then take on crates at an evacuating site. let origin = train.route[0].node; if train.crates > 0 && origin != train.at { if let Some(evac) = net.nodes[origin.0].evac.as_mut() { evac.delivered += train.crates; } train.crates = 0; } if let Some(evac) = net.nodes[train.at.0].evac.as_mut() && evac.dest.is_some() { let take = train.crate_slots().saturating_sub(train.crates).min(evac.crates_left); evac.crates_left -= take; train.crates += take; } let node = &mut net.nodes[train.at.0]; // (1) Unload every good the node accepts. for g in GOODS { let i = g.idx(); if train.cargo[i] > 0.0 && node.kind.accepts(g) { node.stock[i] += train.cargo[i]; train.cargo[i] = 0.0; } } // (2) Load flagged goods up to what each good's cars can still hold. let mut room = [0.0_f32; 4]; for g in GOODS { let i = g.idx(); if stop.load[i] { room[i] = (train.capacity(g) - train.cargo[i]).max(0.0); } } let take = split_load(room.iter().sum(), node.stock, room); for (i, &amount) in take.iter().enumerate() { train.cargo[i] += amount; node.stock[i] = (node.stock[i] - amount).max(0.0); } // (3) Dwell and advance to the next stop. train.dwell = DWELL_SECS; train.stop_idx = (train.stop_idx + 1) % train.route.len(); } fn simulate_trains( time: Res