//! Route building for the demo script, and the two supply line actions the HUD //! chips use: add a train to a line, and scrap one train. Supply lines are made //! by dragging between nodes (see `supply.rs`). use bevy::ecs::system::SystemParam; use bevy::prelude::*; use bevy::ui_widgets::Activate; use crate::audio::SoundEvent; use crate::map::{WorldText, dashed}; use crate::model::{ CarKind, GOODS, Good, Network, NodeClicked, NodeId, NodeKind, Notify, Stop, Tool, Train, Treasury, consist_cost, }; use crate::supply::{buy_line, money, produces}; pub struct RoutesPlugin; impl Plugin for RoutesPlugin { fn build(&self, app: &mut App) { app.add_systems( Update, (on_node_clicked, sync_route_labels, draw_route_preview), ) .add_observer(on_scrap) .add_observer(on_add_train) .add_observer(on_remove_car) .add_observer(on_add_car); } } /// Route preview dash and gap lengths, in world units. const DASH_LEN: f32 = 10.0; const GAP_LEN: f32 = 6.0; /// Stop number glyph size in world units (see `map::WorldText`). const STOP_LABEL_SIZE: f32 = 16.0; fn ink() -> Color { Color::srgb(0.15, 0.12, 0.08) } fn amber() -> Color { Color::srgb(1.0, 0.75, 0.2) } fn red() -> Color { Color::srgb(0.9, 0.15, 0.1) } /// Removes a supply line's train from the map, refunding half its price. /// Put on a HUD chip button. #[derive(Component, Debug, Clone, Copy)] pub(crate) struct Scrap(pub Entity); /// Buys one more train for the supply line between two nodes, as a second drag would. /// Put on a HUD chip button. #[derive(Component, Debug, Clone, Copy)] pub(crate) struct AddTrain { pub from: NodeId, pub to: NodeId, } /// Removes car `index` from a train when its car icon is pressed in the HUD. /// Put on a HUD car icon button. Refunds half the car's price. #[derive(Component, Debug, Clone, Copy)] pub(crate) struct RemoveCar { pub entity: Entity, pub index: usize, } /// Appends a car to a train when its car-type button is pressed in the HUD. /// Put on a HUD car-type button. #[derive(Component, Debug, Clone, Copy)] pub(crate) struct AddCar { pub entity: Entity, pub car: CarKind, } /// Numbered world-space marker for a stop of the route being built. #[derive(Component)] struct RouteLabel; #[derive(SystemParam)] struct ScrapParams<'w, 's> { commands: Commands<'w, 's>, treasury: ResMut<'w, Treasury>, trains: Query<'w, 's, &'static Train>, notify: MessageWriter<'w, Notify>, } #[derive(SystemParam)] struct CarParams<'w, 's> { net: Res<'w, Network>, treasury: ResMut<'w, Treasury>, trains: Query<'w, 's, &'static mut Train>, notify: MessageWriter<'w, Notify>, } /// Default load flags for a stop, by node kind, filtered by the goods the cars carry. fn default_load(cars: &[CarKind], node: NodeKind) -> [bool; 4] { let wanted = match node { NodeKind::Factory => [true, false, false, false], NodeKind::Farm => [false, true, false, false], NodeKind::Capital | NodeKind::City => [false, false, true, false], NodeKind::Front => [false, false, false, true], NodeKind::Depot => [true, true, true, false], }; let mut load = [false; 4]; for g in GOODS { load[g.idx()] = wanted[g.idx()] && cars.iter().any(|c| c.good() == Some(g)); } load } /// The good a train carries, read from the loads of its first stop. pub(crate) fn cargo_good(train: &Train) -> Option { let first = train.route.first()?; GOODS.into_iter().find(|g| first.load[g.idx()]) } /// Adds the clicked node as a stop while a route is being built (demo script). fn on_node_clicked( mut clicks: MessageReader, mut tool: ResMut, network: Res, ) { if !matches!(*tool, Tool::NewRoute { .. }) { return; } for NodeClicked(node) in clicks.read() { let Some(info) = network.nodes.get(node.0) else { continue; }; let Tool::NewRoute { cars, stops, .. } = &mut *tool else { continue; }; if stops.last().is_some_and(|s| s.node == *node) { continue; } stops.push(Stop { node: *node, load: default_load(cars, info.kind), }); } } /// Scraps a train when its [✕] chip button is pressed. fn on_scrap(ev: On, scraps: Query<&Scrap>, mut p: ScrapParams<'_, '_>) { let Ok(Scrap(entity)) = scraps.get(ev.entity) else { return; }; let entity = *entity; let Ok(train) = p.trains.get(entity) else { return; }; let loco = train.loco; let refund = consist_cost(loco, &train.cars) / 2; p.treasury.0 += refund; p.commands.entity(entity).despawn(); p.notify.write(Notify(format!( "{} train scrapped, ${refund} refunded", loco.name() ))); } /// Takes one car off a train when its car icon is pressed. Refunds half its price. fn on_remove_car(ev: On, removes: Query<&RemoveCar>, mut p: CarParams) { let Ok(&RemoveCar { entity, index }) = removes.get(ev.entity) else { return; }; let Ok(mut train) = p.trains.get_mut(entity) else { return; }; if index >= train.cars.len() { return; } let car = train.cars.remove(index); let refund = car.cost() / 2; p.treasury.0 += refund; p.notify.write(Notify(format!( "{} car removed, ${refund} refunded", car.name() ))); } /// Couples a car of the chosen type onto the end of a train, if the locomotive has room /// and the treasury can pay. A car of a good also turns on loading of that good at the /// first stop that makes it or has it in stock, so the new car fills. fn on_add_car(ev: On, adds: Query<&AddCar>, mut p: CarParams) { let Ok(&AddCar { entity, car }) = adds.get(ev.entity) else { return; }; let Ok(mut train) = p.trains.get_mut(entity) else { return; }; if train.cars.len() >= train.loco.max_cars() { p.notify.write(Notify(format!("{} is full", train.loco.name()))); return; } if car.cost() > p.treasury.0 { p.notify.write(Notify(format!("Need {}", money(car.cost())))); return; } p.treasury.0 -= car.cost(); train.cars.push(car); if let Some(good) = car.good() { let net = &p.net; let source = train.route.iter_mut().find(|s| { let node = &net.nodes[s.node.0]; produces(node.kind) == Some(good) || node.stock[good.idx()] > 0.0 }); if let Some(stop) = source { stop.load[good.idx()] = true; } } p.notify.write(Notify(format!("{} car added", car.name()))); } /// Adds a train to an existing line when its [+] chip button is pressed. /// Same checks and charges as a drag from `from` to `to` (see `supply::plan`). fn on_add_train( ev: On, adds: Query<&AddTrain>, mut net: ResMut, mut treasury: ResMut, mut commands: Commands, mut notify: MessageWriter, mut sounds: MessageWriter, ) { let Ok(&AddTrain { from, to }) = adds.get(ev.entity) else { return; }; buy_line( &mut net, &mut treasury, &mut commands, &mut notify, &mut sounds, from, to, ); } /// Keeps one numbered marker per stop of the route being built. fn sync_route_labels( mut commands: Commands, tool: Res, network: Res, old: Query>, ) { if !tool.is_changed() { return; } for e in &old { commands.entity(e).despawn(); } let Tool::NewRoute { stops, .. } = tool.as_ref() else { return; }; for (i, stop) in stops.iter().enumerate() { let Some(node) = network.nodes.get(stop.node.0) else { continue; }; commands.spawn(( RouteLabel, Text2d::new(format!("{}", i + 1)), WorldText { size: STOP_LABEL_SIZE, }, TextColor(ink()), Transform::from_xyz(node.pos.x, node.pos.y, 10.0), )); } } /// Draws the route being built: amber dashed path per leg (red if no path), and stop rings. fn draw_route_preview(mut gizmos: Gizmos, tool: Res, network: Res) { let Tool::NewRoute { stops, .. } = tool.as_ref() else { return; }; for stop in stops { if let Some(node) = network.nodes.get(stop.node.0) { gizmos.circle_2d(node.pos, 16.0, amber()); } } for pair in stops.windows(2) { let (a, b) = (pair[0].node, pair[1].node); let (Some(na), Some(nb)) = (network.nodes.get(a.0), network.nodes.get(b.0)) else { continue; }; match network.shortest_path(a, b) { Some(path) => { for leg in path.windows(2) { let p = network.nodes[leg[0].0].pos; let q = network.nodes[leg[1].0].pos; dashed(&mut gizmos, p, q, DASH_LEN, GAP_LEN, amber()); } } None => dashed(&mut gizmos, na.pos, nb.pos, DASH_LEN, GAP_LEN, red()), } } }