//! Front sectors: supply and line simulation, the front-line drawing, //! air raids, and the victory/defeat overlay with restart. use std::collections::HashMap; use bevy::input::ButtonInput; use bevy::prelude::*; use bevy::time::{Real, Time}; use crate::audio::SoundEvent; use crate::economy::advance_clock; use crate::model::{ FrontState, Good, HourTick, MIN_USABLE_CONDITION, Network, Notify, Outcome, Selected, SimClock, Tool, Train, Treasury, }; use crate::seasons::SeasonState; use crate::trains::TrainCounter; /// Ammo, food and troops one sector needs per game hour. pub const AMMO_NEED: f32 = 1.0; pub const FOOD_NEED: f32 = 0.8; pub const TROOPS_NEED: f32 = 0.15; /// Hourly need of a front sector for `g`. Food scales with the season's food multiplier. pub fn hourly_need(g: Good, food_mult: f32) -> f32 { match g { Good::Ammo => AMMO_NEED, Good::Food => FOOD_NEED * food_mult, Good::Troops => TROOPS_NEED, Good::Wounded => 0.0, } } /// Fraction of the gap to the hour's supply ratio closed each hour. const SUPPLY_RATE: f32 = 0.1; /// Line drift per hour per unit of supply above or below the neutral point. const LINE_RATE: f32 = 0.004; pub const NEUTRAL_SUPPLY: f32 = 0.5; /// Wounded produced per hour: base plus shortage scaled. const WOUNDED_BASE: f32 = 0.2; const WOUNDED_SHORTAGE: f32 = 0.5; const WOUNDED_CAP: f32 = 200.0; const LOW_SUPPLY: f32 = 0.35; const NOTICE_COOLDOWN_HOURS: u32 = 24; const ADVANCE_LINE: f32 = 0.5; const RETREAT_LINE: f32 = -0.5; /// Air raids are checked every this many game hours. const RAID_EVERY_HOURS: u32 = 24; const RAID_CHANCE: f64 = 0.35; /// Condition lost by a damaged track in one raid. const RAID_DAMAGE_MIN: f32 = 0.25; const RAID_DAMAGE_MAX: f32 = 0.5; /// Track condition regained per game hour without repair crews. const SELF_REPAIR_PER_HOUR: f32 = 0.01; /// Raids only hit track with an endpoint east of this x. const FRONT_ZONE_X: f32 = 100.0; /// Raid animation length in real seconds. Shown even while paused. const RAID_FX_SECS: f32 = 2.5; /// The bomber crosses from this far off the track's midpoint to the other side. const RAID_PLANE_REACH: Vec2 = Vec2::new(480.0, 140.0); /// Bomb bursts: (age in seconds, fraction along the hit track). const RAID_BURSTS: [(f32, f32); 4] = [(0.6, 0.18), (0.85, 0.42), (1.1, 0.62), (1.35, 0.84)]; const RAID_BURST_SECS: f32 = 1.0; /// Track flashes from this age, then fades out. const RAID_FLASH_START: f32 = 0.5; /// Front line geometry. const LINE_OFFSET_X: f32 = 70.0; const LINE_SWING_X: f32 = 120.0; const LINE_EXTENT_Y: f32 = 360.0; const JAG_STEP: f32 = 12.0; const JAG_AMPLITUDE: f32 = 5.0; const TOOTH_SPACING: f32 = 15.0; const TOOTH_LEN: f32 = 8.0; const HATCH_STEP: f32 = 14.0; const HATCH_LEN: f32 = 36.0; const BAR_W: f32 = 90.0; const BAR_H: f32 = 8.0; /// Supply bar sits above the node; the stock bars and the name label sit below it. const BAR_DY: f32 = 16.0; /// Next state of one front sector after one game hour. /// /// `stock` is `[ammo, food, troops, wounded]` of the sector node. Ammo, food /// and troops are consumed up to what is available; wounded are produced. fn step_sector(stock: [f32; 4], front: FrontState, food_mult: f32) -> ([f32; 4], FrontState) { let mut stock = stock; let mut ratio_sum = 0.0; for g in [Good::Ammo, Good::Food, Good::Troops] { let idx = g.idx(); let need = hourly_need(g, food_mult); let taken = need.min(stock[idx].max(0.0)); stock[idx] -= taken; ratio_sum += taken / need; } let ratio = ratio_sum / 3.0; let supply = front.supply + (ratio - front.supply) * SUPPLY_RATE; let line = (front.line + (supply - NEUTRAL_SUPPLY) * LINE_RATE).clamp(-1.0, 1.0); let wounded = stock[Good::Wounded.idx()] + WOUNDED_BASE + (1.0 - supply) * WOUNDED_SHORTAGE; stock[Good::Wounded.idx()] = wounded.min(WOUNDED_CAP); (stock, FrontState { line, supply }) } /// Track condition after one game hour of self-repair, capped at fully intact. pub fn repair_step(condition: f32) -> f32 { (condition + SELF_REPAIR_PER_HOUR).min(1.0) } /// Outcome implied by the current front lines, if any. fn judge(net: &Network) -> Option { let lines: Vec = net .nodes .iter() .filter_map(|n| n.front.map(|f| f.line)) .collect(); if lines.iter().any(|&l| l <= -1.0) { Some(Outcome::Defeat) } else if !lines.is_empty() && lines.iter().all(|&l| l >= 1.0) { Some(Outcome::Victory) } else { None } } /// A low-supply notice may fire at most once per cooldown window per sector. fn notice_due(last: Option, now: u32) -> bool { last.is_none_or(|h| now.saturating_sub(h) >= NOTICE_COOLDOWN_HOURS) } /// Advances every front sector one hour and returns the news lines. fn step_fronts(net: &mut Network, runtime: &mut FrontRuntime, now: u32, food_mult: f32) -> Vec { let mut news = Vec::new(); for (i, node) in net.nodes.iter_mut().enumerate() { let Some(old) = node.front else { continue }; let (stock, new) = step_sector(node.stock, old, food_mult); node.stock = stock; node.front = Some(new); if new.supply < LOW_SUPPLY && notice_due(runtime.low_notice.get(&i).copied(), now) { runtime.low_notice.insert(i, now); news.push(format!("{} is running out of supplies!", node.name)); } if old.line < ADVANCE_LINE && new.line >= ADVANCE_LINE { news.push(format!("{} advances", node.name)); } if old.line > RETREAT_LINE && new.line <= RETREAT_LINE { news.push(format!("{} is falling back", node.name)); } } news } /// Track indices eligible for a raid: usable and touching the front zone. fn raid_candidates(net: &Network) -> Vec { net.tracks .iter() .enumerate() .filter(|(_, t)| { t.condition >= MIN_USABLE_CONDITION && (net.nodes[t.a.0].pos.x > FRONT_ZONE_X || net.nodes[t.b.0].pos.x > FRONT_ZONE_X) }) .map(|(i, _)| i) .collect() } /// Damages one random eligible track. Returns its index and the news line. pub(crate) fn air_raid(net: &mut Network, runtime: &mut FrontRuntime) -> Option<(usize, String)> { let candidates = raid_candidates(net); if candidates.is_empty() { return None; } let i = candidates[rand::random_range(0..candidates.len())]; let track = net.tracks[i]; let a = &net.nodes[track.a.0]; let b = &net.nodes[track.b.0]; let text = format!("Air raid! Line {}-{} damaged", a.name, b.name); let (pa, pb) = (a.pos, b.pos); let loss: f32 = rand::random_range(RAID_DAMAGE_MIN..RAID_DAMAGE_MAX); net.tracks[i].condition = (track.condition - loss).max(0.0); runtime.raids.push(RaidFx { a: pa, b: pb, age: 0.0, }); Some((i, text)) } /// A raid effect still on screen, over the track it hit. pub(crate) struct RaidFx { /// Endpoints of the hit track. a: Vec2, b: Vec2, /// Real seconds since the raid. age: f32, } /// Per-session state owned by the front. Reset on restart. #[derive(Resource, Default)] pub(crate) struct FrontRuntime { /// Game hours processed since start or restart. hours: u32, /// Node index -> hour of the last low-supply notice. low_notice: HashMap, pub(crate) raids: Vec, } #[derive(Component)] struct OutcomeOverlay; pub struct FrontPlugin; impl Plugin for FrontPlugin { fn build(&self, app: &mut App) { app.init_resource::().add_systems( Update, ( // Reads the hour ticks written by the clock in the same frame. front_hour_system.after(advance_clock), restart_system, outcome_overlay, draw_front, ) .chain(), ); } } #[allow(clippy::too_many_arguments, reason = "bevy system parameters")] pub(crate) fn front_hour_system( mut ticks: MessageReader, mut net: ResMut, mut outcome: ResMut, mut clock: ResMut, season: Res, mut runtime: ResMut, mut notify: MessageWriter, mut sounds: MessageWriter, ) { for _ in ticks.read() { runtime.hours += 1; if *outcome != Outcome::Ongoing { continue; } for news in step_fronts(&mut net, &mut runtime, clock.hour, season.season.food_mult()) { notify.write(Notify(news)); } // Track touching a captured site stays cut. let cut: Vec = net.tracks.iter().map(|t| net.is_cut(t)).collect(); for (track, cut) in net.tracks.iter_mut().zip(cut) { if !cut { track.condition = repair_step(track.condition); } } if let Some(result) = judge(&net) { *outcome = result; clock.speed = 0; let text = match result { Outcome::Victory => "OPERATION SUCCESSFUL", _ => "THE FRONT HAS COLLAPSED", }; sounds.write(match result { Outcome::Victory => SoundEvent::Victory, _ => SoundEvent::Defeat, }); notify.write(Notify(text.to_string())); continue; } // Fog keeps the bombers grounded; summer skies raise the odds. if runtime.hours.is_multiple_of(RAID_EVERY_HOURS) && !season.fog && rand::random_bool(RAID_CHANCE * f64::from(season.season.raid_mult())) && let Some((_, text)) = air_raid(&mut net, &mut runtime) { sounds.write(SoundEvent::Raid); notify.write(Notify(text)); } } } /// Enter restarts a finished game. fn restart_system(world: &mut World) { let pressed = { let keys = world.resource::>(); keys.just_pressed(KeyCode::Enter) || keys.just_pressed(KeyCode::NumpadEnter) }; if !pressed || *world.resource::() == Outcome::Ongoing { return; } reset_game(world); } /// Starts a fresh operation: default map, treasury, clock, trains and front state. /// Used by Enter after a finished game and by the menu's New Operation. pub fn reset_game(world: &mut World) { *world.resource_mut::() = Network::default(); *world.resource_mut::() = Treasury::default(); *world.resource_mut::() = SimClock::default(); *world.resource_mut::() = Outcome::Ongoing; *world.resource_mut::() = Tool::Inspect; *world.resource_mut::() = Selected(None); *world.resource_mut::() = FrontRuntime::default(); *world.resource_mut::() = TrainCounter::default(); *world.resource_mut::() = SeasonState::default(); let trains: Vec = world .query_filtered::>() .iter(world) .collect(); for e in trains { world.entity_mut(e).despawn(); } world.spawn(crate::trains::starting_train()); } /// Keeps the centred result panel in step with `Outcome`. fn outcome_overlay( mut commands: Commands, outcome: Res, clock: Res, existing: Query>, ) { let (title, accent) = match *outcome { Outcome::Ongoing => { for e in &existing { commands.entity(e).despawn(); } return; } Outcome::Victory => ("OPERATION SUCCESSFUL", Color::srgb(0.72, 0.84, 0.46)), Outcome::Defeat => ("THE FRONT HAS COLLAPSED", Color::srgb(0.92, 0.28, 0.22)), }; if !existing.is_empty() { return; } let paper = Color::srgb(0.90, 0.85, 0.70); let day = format!("Day {}", clock.day() + 1); commands.spawn(( OutcomeOverlay, GlobalZIndex(100), Node { position_type: PositionType::Absolute, width: Val::Percent(100.0), height: Val::Percent(100.0), justify_content: JustifyContent::Center, align_items: AlignItems::Center, ..default() }, BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.6)), children![( Node { flex_direction: FlexDirection::Column, align_items: AlignItems::Center, row_gap: Val::Px(16.0), padding: UiRect::all(Val::Px(36.0)), border: UiRect::all(Val::Px(4.0)), min_width: Val::Px(560.0), ..default() }, BackgroundColor(Color::srgb(0.20, 0.21, 0.15)), BorderColor::all(accent), children![ ( Text::new("FRONT COMMAND - OPERATIONS REPORT"), TextFont { font_size: FontSize::Px(18.0), ..default() }, TextColor(paper), ), ( Text::new(title), TextFont { font_size: FontSize::Px(44.0), ..default() }, TextColor(accent), ), ( Text::new(day), TextFont { font_size: FontSize::Px(24.0), ..default() }, TextColor(paper), ), ( Text::new("Press Enter to restart"), TextFont { font_size: FontSize::Px(20.0), ..default() }, TextColor(paper), ), ] )], )); } fn front_red() -> Color { Color::srgb(0.78, 0.12, 0.10) } /// Colour of the supply bar: red at 0, green at 1. fn supply_color(t: f32) -> Color { let red = Vec3::new(0.85, 0.15, 0.10); let green = Vec3::new(0.20, 0.75, 0.25); let c = red.lerp(green, t.clamp(0.0, 1.0)); Color::srgb(c.x, c.y, c.z) } /// Front-line points, north to south: sector points plus extensions to y = ±360. fn front_base_line(net: &Network) -> Vec { let mut sectors: Vec = net .nodes .iter() .filter_map(|n| { n.front .map(|f| Vec2::new(n.pos.x + LINE_OFFSET_X + f.line * LINE_SWING_X, n.pos.y)) }) .collect(); if sectors.is_empty() { return sectors; } sectors.sort_by(|a, b| b.y.total_cmp(&a.y)); let north = sectors[0]; let south = sectors[sectors.len() - 1]; let mut out = vec![Vec2::new(north.x, LINE_EXTENT_Y)]; out.extend(sectors); out.push(Vec2::new(south.x, -LINE_EXTENT_Y)); out } /// Zig-zags the base line so it reads as jagged. fn jagged(base: &[Vec2]) -> Vec { let mut out = Vec::new(); for w in base.windows(2) { let (a, b) = (w[0], w[1]); let steps = ((a.y - b.y).abs() / JAG_STEP).ceil().max(1.0) as usize; for s in 0..steps { let p = a.lerp(b, s as f32 / steps as f32); let sign = if s % 2 == 0 { -1.0 } else { 1.0 }; out.push(Vec2::new(p.x + sign * JAG_AMPLITUDE, p.y)); } } if let Some(&last) = base.last() { out.push(last); } out } /// X of the smooth base line at height `y`. fn x_at(base: &[Vec2], y: f32) -> f32 { for w in base.windows(2) { let (a, b) = (w[0], w[1]); if y <= a.y && y >= b.y { let span = a.y - b.y; if span <= 0.0 { return a.x; } return a.x + (b.x - a.x) * ((a.y - y) / span); } } base.first().map_or(0.0, |p| p.x) } fn draw_line(gizmos: &mut Gizmos, base: &[Vec2]) { let pts = jagged(base); // Four offset strokes make the line read as thick. for dx in [-1.5_f32, -0.5, 0.5, 1.5] { gizmos.linestrip_2d(pts.iter().map(|p| *p + Vec2::new(dx, 0.0)), front_red()); } // Teeth every TOOTH_SPACING along the line, perpendicular, pointing east. let mut to_next = TOOTH_SPACING; for w in pts.windows(2) { let seg = w[1] - w[0]; let len = seg.length(); if len <= f32::EPSILON { continue; } let dir = seg / len; let mut normal = Vec2::new(-dir.y, dir.x); if normal.x < 0.0 { normal = -normal; } let mut along = to_next; while along <= len { let p = w[0] + dir * along; gizmos.line_2d(p, p + normal * TOOTH_LEN, front_red()); along += TOOTH_SPACING; } to_next = along - len; } } /// Faint diagonal hatching east of the line: enemy territory. fn draw_hatching(gizmos: &mut Gizmos, base: &[Vec2]) { let color = Color::srgba(0.78, 0.12, 0.10, 0.22); let mut y = -LINE_EXTENT_Y; while y <= LINE_EXTENT_Y { let x = x_at(base, y); gizmos.line_2d( Vec2::new(x, y), Vec2::new(x + HATCH_LEN, y + HATCH_LEN), color, ); y += HATCH_STEP; } } /// Small supply bar below a front node, filled red to green by supply. fn draw_supply_bar(gizmos: &mut Gizmos, pos: Vec2, supply: f32) { let left = pos + Vec2::new(-BAR_W * 0.5, BAR_DY); let frac = supply.clamp(0.0, 1.0); let frame = Color::srgb(0.12, 0.11, 0.09); gizmos.linestrip_2d( [ left, left + Vec2::new(BAR_W, 0.0), left + Vec2::new(BAR_W, BAR_H), left + Vec2::new(0.0, BAR_H), left, ], frame, ); let fill = supply_color(frac); for row in 0..=(BAR_H as u32) { let y = left.y + row as f32; gizmos.line_2d( Vec2::new(left.x, y), Vec2::new(left.x + BAR_W * frac, y), fill, ); } } /// Bomber silhouette in local units, nose along +x. Each part is a closed outline. const BOMBER: [&[[f32; 2]]; 5] = [ &[[22.0, 0.0], [15.0, -2.5], [-14.0, -2.5], [-20.0, -1.0], [-20.0, 1.0], [-14.0, 2.5], [15.0, 2.5]], &[[8.0, 2.5], [-3.0, 19.0], [-9.0, 19.0], [-6.0, 2.5]], &[[8.0, -2.5], [-3.0, -19.0], [-9.0, -19.0], [-6.0, -2.5]], &[[-15.0, 1.5], [-20.0, 9.0], [-24.0, 9.0], [-21.0, 1.0]], &[[-15.0, -1.5], [-20.0, -9.0], [-24.0, -9.0], [-21.0, -1.0]], ]; /// Small escort fighter, same convention. const FIGHTER: [&[[f32; 2]]; 3] = [ &[[16.0, 0.0], [8.0, -1.5], [-10.0, -1.5], [-12.0, 0.0], [-10.0, 1.5], [8.0, 1.5]], &[[3.0, 1.5], [-3.0, 11.0], [-6.0, 11.0], [-5.0, 1.5]], &[[3.0, -1.5], [-3.0, -11.0], [-6.0, -11.0], [-5.0, -1.5]], ]; /// Draws a plane as a thick-outlined silhouette, rotated to `heading`. fn draw_plane( gizmos: &mut Gizmos, center: Vec2, heading: Vec2, scale: f32, parts: &[&[[f32; 2]]], color: Color, ) { let side = Vec2::new(-heading.y, heading.x); for part in parts { let pts: Vec = part .iter() .map(|p| center + heading * (p[0] * scale) + side * (p[1] * scale)) .collect(); // Several strokes side by side make the outline read as a solid shape. for off in [-0.6_f32, 0.0, 0.6] { let o = side * off; gizmos.linestrip_2d( pts.iter().map(|p| *p + o).chain(std::iter::once(pts[0] + o)), color, ); } } } /// Filled disc from concentric rings. fn fill_disc(gizmos: &mut Gizmos, c: Vec2, radius: f32, color: Color) { let mut r = radius; while r > 0.5 { gizmos.circle_2d(c, r, color); r -= 1.5; } } /// Air raid: the hit track flashes, a bomber and escort cross it, and bombs burst along it. fn draw_raid(gizmos: &mut Gizmos, fx: &RaidFx) { let t = (fx.age / RAID_FX_SECS).clamp(0.0, 1.0); let dir = (fx.b - fx.a).normalize_or_zero(); let perp = Vec2::new(-dir.y, dir.x); // Track flashes red-orange, blinking, then fades. if fx.age >= RAID_FLASH_START { let fade = (1.0 - (fx.age - RAID_FLASH_START) / 1.5).clamp(0.0, 1.0); let blink = 0.5 + 0.5 * (fx.age * 16.0).sin(); let color = Color::srgba(1.0, 0.32, 0.06, fade * (0.35 + 0.65 * blink)); for s in [-3.0_f32, -1.5, 0.0, 1.5, 3.0] { gizmos.line_2d(fx.a + perp * s, fx.b + perp * s, color); } } // Bomber crosses from one side of the track to the other, escort just ahead. let mid = (fx.a + fx.b) * 0.5; let from = mid + RAID_PLANE_REACH; let to = mid - RAID_PLANE_REACH; let pos = from.lerp(to, t); let heading = (to - from).normalize_or_zero(); let alpha = (t / 0.08).min(1.0) * ((1.0 - t) / 0.1).min(1.0); let ink = Color::srgba(0.10, 0.08, 0.07, alpha); draw_plane(gizmos, pos, heading, 1.0, &BOMBER, ink); draw_plane(gizmos, pos + heading * 70.0, heading, 0.55, &FIGHTER, ink); // Bomb bursts along the hit track: hot core, expanding rings, debris spokes. for (start, along) in RAID_BURSTS { let local = fx.age - start; if !(0.0..RAID_BURST_SECS).contains(&local) { continue; } let u = local / RAID_BURST_SECS; let fade = 1.0 - u; let c = fx.a.lerp(fx.b, along); fill_disc(gizmos, c, 4.0 + 9.0 * fade, Color::srgba(1.0, 0.85, 0.3, fade)); gizmos.circle_2d(c, 6.0 + 30.0 * u, Color::srgba(1.0, 0.5, 0.1, fade)); gizmos.circle_2d(c, 4.0 + 20.0 * u, Color::srgba(0.05, 0.05, 0.05, fade)); for k in 0..8 { let ang = k as f32 * std::f32::consts::FRAC_PI_4 + 0.3; let u2 = Vec2::new(ang.cos(), ang.sin()); gizmos.line_2d( c + u2 * (8.0 + 14.0 * u), c + u2 * (12.0 + 26.0 * u), Color::srgba(1.0, 0.7, 0.2, fade), ); } } } fn draw_front( mut gizmos: Gizmos, net: Res, time: Res>, mut runtime: ResMut, ) { let base = front_base_line(&net); if !base.is_empty() { draw_hatching(&mut gizmos, &base); draw_line(&mut gizmos, &base); } for node in net.nodes.iter() { if let Some(f) = node.front { draw_supply_bar(&mut gizmos, node.pos, f.supply); } } let dt = time.delta_secs(); runtime.raids.retain_mut(|r| { r.age += dt; r.age < RAID_FX_SECS }); for fx in &runtime.raids { draw_raid(&mut gizmos, fx); } } #[cfg(test)] mod tests { use super::*; fn front(line: f32, supply: f32) -> FrontState { FrontState { line, supply } } fn close(a: f32, b: f32) -> bool { (a - b).abs() < 1e-5 } #[test] fn fully_supplied_sector_consumes_and_gains_supply() { let (stock, f) = step_sector([15.0, 15.0, 15.0, 0.0], front(0.0, 0.5), 1.0); assert!(close(stock[0], 14.0)); assert!(close(stock[1], 14.2)); assert!(close(stock[2], 14.85)); assert!(close(f.supply, 0.55)); assert!(close(f.line, (0.55 - NEUTRAL_SUPPLY) * LINE_RATE)); assert!(close(stock[3], 0.2 + (1.0 - 0.55) * 0.5)); } #[test] fn self_repair_adds_one_percent_and_caps_at_intact() { assert!(close(repair_step(0.5), 0.51)); assert!(close(repair_step(0.995), 1.0)); assert!(close(repair_step(1.0), 1.0)); } }