use bevy::prelude::*; use bevy::window::PrimaryWindow; use crate::audio::SoundEvent; use crate::map::{MapHover, WorldText}; use crate::model::{ MIN_USABLE_CONDITION, Network, NodeClicked, NodeId, Notify, REPAIR_COST, TRACK_COST_PER_UNIT, Tool, TrackClicked, TrackSeg, Treasury, }; pub struct BuildPlugin; impl Plugin for BuildPlugin { fn build(&self, app: &mut App) { app.add_systems(Startup, spawn_cost_label).add_systems( Update, (handle_node_clicks, handle_track_clicks, build_preview).chain(), ); } } /// Logical pixels within which the cursor snaps to a node. const SNAP_RADIUS: f32 = 24.0; /// Cost label glyph size in world units (see `map::WorldText`). const COST_LABEL_SIZE: f32 = 27.0; /// Dash and gap lengths of the preview line, in world units. const DASH_LEN: f32 = 12.0; const GAP_LEN: f32 = 8.0; #[derive(Component)] struct BuildCostLabel; fn spawn_cost_label(mut commands: Commands) { commands.spawn(( BuildCostLabel, Text2d::new(""), WorldText { size: COST_LABEL_SIZE, }, TextColor(Color::WHITE), Visibility::Hidden, Transform::from_xyz(0.0, 0.0, 20.0), )); } /// Cost of a track of the given length, in dollars. pub(crate) fn track_cost(length: f32) -> i64 { (length * TRACK_COST_PER_UNIT as f32) as i64 } /// Cost of laying the given track segments, in dollars. pub(crate) fn segments_cost(segs: &[TrackSeg]) -> i64 { segs.iter().map(|s| track_cost(s.length)).sum() } /// A node within this many world units of a straight track counts as lying on it. const ON_TRACK_RADIUS: f32 = 30.0; /// The new segments that make a straight track from `from` to `to`. /// /// The line is split at every node it passes within `ON_TRACK_RADIUS`, so the track /// connects there instead of running past it. Segments that already exist are left /// out. Empty when nothing new would be laid: the pair is already linked directly, /// or a link on the way is cut and must be repaired first. pub(crate) fn new_segments(net: &Network, from: NodeId, to: NodeId) -> Vec { if from == to || net.track_between(from, to).is_some() { return Vec::new(); } let a = net.nodes[from.0].pos; let d = net.nodes[to.0].pos - a; let len2 = d.length_squared(); let mut mids: Vec<(f32, NodeId)> = Vec::new(); if len2 > 0.0 { for (i, node) in net.nodes.iter().enumerate() { let id = NodeId(i); if id == from || id == to { continue; } let t = (node.pos - a).dot(d) / len2; if t > 0.0 && t < 1.0 && node.pos.distance(a + d * t) <= ON_TRACK_RADIUS { mids.push((t, id)); } } } mids.sort_by(|x, y| x.0.total_cmp(&y.0)); let mut chain = vec![from]; chain.extend(mids.into_iter().map(|(_, id)| id)); chain.push(to); let mut segs = Vec::new(); for link in chain.windows(2) { let (x, y) = (link[0], link[1]); match net.track_between(x, y) { // A cut link on the way blocks the whole line. Some(i) if net.tracks[i].condition < MIN_USABLE_CONDITION => return Vec::new(), Some(_) => {} None => segs.push(TrackSeg { a: x, b: y, length: net.nodes[x.0].pos.distance(net.nodes[y.0].pos), condition: 1.0, }), } } segs } /// "A-B" using the node names of a track. fn track_name(net: &Network, seg: &TrackSeg) -> String { format!("{}-{}", net.nodes[seg.a.0].name, net.nodes[seg.b.0].name) } fn handle_node_clicks( mut clicks: MessageReader, mut tool: ResMut, mut net: ResMut, mut treasury: ResMut, mut notify: MessageWriter, mut sounds: MessageWriter, ) { for &NodeClicked(n) in clicks.read() { let Tool::BuildTrack { from } = tool.as_mut() else { continue; }; match *from { None => *from = Some(n), Some(f) if f == n => *from = None, Some(f) => { let segs = new_segments(&net, f, n); let cost = segments_cost(&segs); if segs.is_empty() { let msg = if net.track_between(f, n).is_some() { "Track already exists" } else { "No new track to lay" }; notify.write(Notify(msg.into())); } else if treasury.0 >= cost { let name = format!("{}-{}", net.nodes[f.0].name, net.nodes[n.0].name); net.tracks.extend(segs); treasury.0 -= cost; notify.write(Notify(format!("Laid track {name} for ${cost}"))); sounds.write(SoundEvent::TrackLaid); } else { notify.write(Notify(format!("Not enough funds (${cost} needed)"))); } // Keep chaining from the node just clicked. *from = Some(n); } } } } fn handle_track_clicks( mut clicks: MessageReader, tool: Res, mut net: ResMut, mut treasury: ResMut, mut notify: MessageWriter, mut sounds: MessageWriter, ) { for &TrackClicked(i) in clicks.read() { let Some(seg) = net.tracks.get(i).copied() else { continue; }; match tool.as_ref() { Tool::Repair => repair_track(i, &mut net, &mut treasury, &mut notify, &mut sounds), // Inspect is the default mode: a click on a damaged track repairs it, an intact one does nothing. Tool::Inspect if seg.condition < 1.0 => { repair_track(i, &mut net, &mut treasury, &mut notify, &mut sounds) } _ => {} } } } /// Repairs track `i` to full condition if the treasury can pay for it, otherwise says why not. fn repair_track( i: usize, net: &mut Network, treasury: &mut Treasury, notify: &mut MessageWriter, sounds: &mut MessageWriter, ) { let seg = net.tracks[i]; let name = track_name(net, &seg); if seg.condition >= 1.0 { notify.write(Notify("Track is intact".into())); } else if treasury.0 >= REPAIR_COST { net.tracks[i].condition = 1.0; treasury.0 -= REPAIR_COST; notify.write(Notify(format!("Repaired {name} (-${REPAIR_COST})"))); sounds.write(SoundEvent::TrackLaid); } else { notify.write(Notify("Not enough funds".into())); } } /// Draws the dashed track preview and the cost label while laying track. #[allow( clippy::too_many_arguments, reason = "Bevy system: one parameter per resource and query" )] fn build_preview( tool: Res, net: Res, treasury: Res, hover: Res, windows: Query<&Window, With>, cameras: Query<(&Camera, &GlobalTransform), With>, mut gizmos: Gizmos, mut labels: Query< (&mut Text2d, &mut TextColor, &mut Transform, &mut Visibility), With, >, ) { let Ok((mut text, mut color, mut transform, mut visibility)) = labels.single_mut() else { return; }; let Tool::BuildTrack { from: Some(f) } = tool.as_ref() else { *visibility = Visibility::Hidden; return; }; let f = *f; let cursor_world = windows .single() .ok() .and_then(|w| w.cursor_position()) .and_then(|cursor| { let (camera, gt) = cameras.single().ok()?; camera.viewport_to_world_2d(gt, cursor).ok() }); let (Some(cursor_world), Some(from_node)) = (cursor_world, net.nodes.get(f.0)) else { *visibility = Visibility::Hidden; return; }; let from_pos = from_node.pos; let snapped = net.node_at(cursor_world, SNAP_RADIUS * hover.world_per_px); let target = match snapped { Some(n) => net.nodes[n.0].pos, None => cursor_world, }; let on_origin = snapped == Some(f); // Snapped to another node: the exact new segments, split at any node the line passes. let segs = match snapped { Some(n) if !on_origin => Some(new_segments(&net, f, n)), _ => None, }; let (label, label_color) = if on_origin { // Hovering the origin node: clicking it again cancels. ( "Click again to cancel".to_string(), Color::srgb(0.35, 0.35, 0.35), ) } else if matches!(&segs, Some(s) if s.is_empty()) { ( "Track already exists".to_string(), Color::srgb(0.8, 0.1, 0.1), ) } else { let cost = match &segs { Some(segs) => segments_cost(segs), None => track_cost(from_pos.distance(target)), }; let color = if treasury.0 >= cost { Color::srgb(0.1, 0.5, 0.1) } else { Color::srgb(0.8, 0.1, 0.1) }; // Off-node cursor: the cost is only an estimate from the cursor distance. let prefix = if snapped.is_some() { "" } else { "~" }; (format!("{prefix}${cost}"), color) }; // Draw each new segment; otherwise the straight dashed preview, unless on the origin. match &segs { Some(segs) if !segs.is_empty() => { for s in segs { draw_dashed( &mut gizmos, net.nodes[s.a.0].pos, net.nodes[s.b.0].pos, Color::srgba(0.2, 0.15, 0.1, 0.8), ); } } _ if !on_origin => draw_dashed( &mut gizmos, from_pos, target, Color::srgba(0.2, 0.15, 0.1, 0.8), ), _ => {} } if text.0 != label { text.0 = label; } *color = TextColor(label_color); transform.translation = Vec3::new(target.x + 14.0, target.y + 14.0, 20.0); *visibility = Visibility::Visible; } fn draw_dashed(gizmos: &mut Gizmos<'_, '_>, from: Vec2, to: Vec2, color: Color) { let delta = to - from; let len = delta.length(); if len <= 0.0 { return; } let dir = delta / len; let mut s = 0.0; while s < len { let e = (s + DASH_LEN).min(len); gizmos.line_2d(from + dir * s, from + dir * e, color); s += DASH_LEN + GAP_LEN; } }