//! Game-only configuration for a launcher using shared radar tracks. use super::*; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum SamMode { #[default] Integrated, LauncherOnly, } impl SamMode { pub fn key(self) -> &'static str { match self { Self::Integrated => "integrated", Self::LauncherOnly => "launcher" } } pub fn from_key(key: &str) -> Option { match key { "integrated" => Some(Self::Integrated), "launcher" => Some(Self::LauncherOnly), _ => None } } } /// Game roles for the generic shared radar; all parameters are fictional. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum RadarRole { #[default] Multifunction, Search, Engagement, Height, } impl RadarRole { pub fn key(self) -> &'static str { match self { Self::Multifunction => "multi", Self::Search => "search", Self::Engagement => "engagement", Self::Height => "height" } } pub fn from_key(key: &str) -> Option { match key { "multi" => Some(Self::Multifunction), "search" => Some(Self::Search), "engagement" => Some(Self::Engagement), "height" => Some(Self::Height), _ => None } } pub fn profile(self) -> RadarProfile { RadarProfile::of(self) } pub fn authorizes(self) -> bool { self.profile().products & RadarProfile::FIRE_BIT != 0 } } /// What a measurement is good for. A search plot is a warning, a refined /// plot fixes a matched contact, and a fire plot is a confirmed measurement /// a launcher may use. Quality (0..100) is separate from identification: /// a well-measured track can still be an unknown type (#133). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] pub enum Measure { #[default] Search, Refine, Fire, } impl Measure { pub fn name(self) -> &'static str { match self { Self::Search => "обзор", Self::Refine => "уточнение", Self::Fire => "пригоден для пуска" } } pub fn allows_fire(self) -> bool { self == Self::Fire } } /// A radar profile: a stable catalog identity over the existing `SamKind::Radar`. /// The numbers are fictional game settings. The silhouette is shared with the /// existing radar model: this slice does not add art (a separate owner's zone). #[derive(Clone, Copy, Debug, PartialEq)] pub struct RadarProfile { /// Stable content ID; old saves only have `RadarRole`, which maps here. pub id: &'static str, pub name: &'static str, /// Allowed measurement products (`SEARCH_BIT`, `REFINE_BIT`, `FIRE_BIT`). pub products: u8, /// Ticks for the beam to go round. pub cycle: u32, /// Electronic revisit of held contacts between beam passes. pub agile: bool, /// Extra antenna height over the unit's spec mast (blocks). pub mast: f64, /// Search reach, a factor of the unit's sensor. pub reach: f64, /// Local search radius, a factor of the unit's sensor (1: the whole reach). pub local: f64, /// Simultaneous refined/fire channels; 0 means only search plots. pub channels: u8, /// Measurement error scale (blocks) and its growth per block of range. pub sigma: f64, pub spread: f64, /// Vertical error as a share of the horizontal one. pub vertical: f64, pub deployment: &'static str, /// The limit the profile deliberately keeps, shown in the UI. pub limit: &'static str, } impl RadarProfile { pub const SEARCH_BIT: u8 = 1; pub const REFINE_BIT: u8 = 2; pub const FIRE_BIT: u8 = 4; pub const MULTI: RadarProfile = RadarProfile { id: "radar_multi", name: "многофункциональная", products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT, cycle: 140, agile: false, mast: 0.0, reach: 1.0, local: 0.55, channels: 3, sigma: 0.7, spread: 0.004, vertical: 0.75, deployment: "стационарная", limit: "универсальная: уступает специализированным по циклу, каналам и точности", }; pub const SEARCH: RadarProfile = RadarProfile { id: "radar_search", name: "дальнего обзора", products: Self::SEARCH_BIT, cycle: 170, agile: false, mast: 0.0, reach: 1.15, local: 1.0, channels: 0, sigma: 1.0, spread: 0.008, vertical: 1.0, deployment: "крупная стационарная антенна", limit: "редкие грубые отметки; своего права на пуск не даёт", }; pub const ENGAGEMENT: RadarProfile = RadarProfile { id: "radar_track", name: "сопровождения", products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT, cycle: 70, agile: true, mast: 0.0, reach: 0.8, local: 0.12, channels: 2, sigma: 0.35, spread: 0.002, vertical: 0.6, deployment: "мобильная панель", limit: "локальный поиск и два канала; сеть лишь подсказывает, измеряет станция", }; pub const HEIGHT: RadarProfile = RadarProfile { id: "radar_height", name: "мачта низких высот", products: Self::SEARCH_BIT | Self::REFINE_BIT, cycle: 140, agile: false, mast: 8.0, reach: 1.05, local: 0.15, channels: 3, sigma: 0.5, spread: 0.003, vertical: 0.35, deployment: "шасси с поднятой антенной", limit: "уточняет низкие контакты над рельефом; сквозь препятствия не видит и права на пуск не даёт", }; /// A weapon's own radar: it measures for its own fire control. Kept out of /// the separate radar roles so embedded radars keep working as before. pub const EMBEDDED: RadarProfile = RadarProfile { id: "embedded", name: "РЛС комплекса", products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT, cycle: 0, agile: false, mast: 0.0, reach: 1.0, local: 1.0, channels: 0, sigma: 0.8, spread: 0.004, // The old embedded scan drew its vertical error at half the horizontal one. vertical: 0.5, deployment: "встроенная", limit: "обслуживает только свой комплекс", }; pub fn of(role: RadarRole) -> Self { match role { RadarRole::Multifunction => Self::MULTI, RadarRole::Search => Self::SEARCH, RadarRole::Engagement => Self::ENGAGEMENT, RadarRole::Height => Self::HEIGHT, } } /// Old saves write the role key; new saves write the stable profile ID. /// Both read here, so a legacy `search` line maps to `radar_search`. pub fn from_id(id: &str) -> Option { match id { "radar_multi" | "multi" => Some(Self::MULTI), "radar_search" | "search" => Some(Self::SEARCH), "radar_track" | "engagement" => Some(Self::ENGAGEMENT), "radar_height" | "height" => Some(Self::HEIGHT), _ => None, } } pub fn role(self) -> RadarRole { match self.id { "radar_search" => RadarRole::Search, "radar_track" => RadarRole::Engagement, "radar_height" => RadarRole::Height, _ => RadarRole::Multifunction, } } pub fn allows(self, product: Measure) -> bool { match product { Measure::Search => self.products & Self::SEARCH_BIT != 0, Measure::Refine => self.products & Self::REFINE_BIT != 0, Measure::Fire => self.products & Self::FIRE_BIT != 0, } } pub fn products_text(self) -> &'static str { match self.products { p if p == Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT => "обзор, уточнение, пуск", p if p == Self::SEARCH_BIT | Self::REFINE_BIT => "обзор, уточнение", p if p == Self::SEARCH_BIT | Self::FIRE_BIT => "обзор, пуск", _ => "обзор", } } } impl Sam { /// The profile this unit measures with. Embedded radars keep their kind's /// own scan and reach; only the separate radar uses a selectable profile. pub fn radar_profile(&self) -> RadarProfile { if self.kind == SamKind::Radar { RadarProfile::of(self.radar_role) } else { RadarProfile::EMBEDDED } } } impl Sam { pub fn set_radar_role(&mut self, role: RadarRole) -> bool { if self.kind != SamKind::Radar { return false; } if self.radar_role != role { self.radar_role = role; self.tracks.clear(); self.class_plots.clear(); self.seen.clear(); self.own.clear(); } true } /// Change the physical configuration. Invalid combinations leave the unit untouched. pub fn set_mode(&mut self, mode: SamMode) -> bool { if mode == SamMode::LauncherOnly && !catalog::has_separate_launcher(self.kind) { return false; } if self.mode != mode { self.mode = mode; self.tracks.clear(); self.class_plots.clear(); self.seen.clear(); self.own.clear(); self.target = None; self.gun_target = None; self.terrain.clear(); self.waits.clear(); } true } } /// A snapshot of the relevant configuration, independent of its presentation. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BatteryStatus { Radar { index: usize, role: RadarRole, emitting: bool, operational: bool }, Launcher { index: usize, kind: SamKind, mode: SamMode, linked: bool }, } impl Sim { /// Current configurations and whether a launcher has an operational radar link. pub fn battery_status(&self) -> Vec { self.sams.iter().enumerate().filter_map(|(index, sam)| { if sam.kind == SamKind::Radar { Some(BatteryStatus::Radar { index, role: sam.radar_role, emitting: sam.radar_on, operational: sam.radar_up() && sam.link_range() > 0.0 }) } else if catalog::has_separate_launcher(sam.kind) { let linked = self.sams.iter().any(|r| r.kind == SamKind::Radar && r.radar_role.authorizes() && r.radar_up() && r.link_range() > 0.0 && sam.link_range() > 0.0 && r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range())); Some(BatteryStatus::Launcher { index, kind: sam.kind, mode: sam.mode, linked }) } else { None } }).collect() } } #[cfg(test)] mod tests { use super::*; use super::super::{sight, why}; #[test] fn status_reports_real_radar_links_and_preserves_indices() { let mut sim = Sim::new(1); sim.sams.push(Sam::new(1, SamKind::Pantsir, DVec3::ZERO, 0.0)); let mut radar = Sam::new(2, SamKind::Radar, DVec3::ZERO, 0.0); radar.radar_role = RadarRole::Engagement; sim.sams.push(radar); let mut launcher = Sam::new(3, SamKind::S400, DVec3::new(10.0, 0.0, 0.0), 0.0); launcher.set_mode(SamMode::LauncherOnly); sim.sams.push(launcher); assert_eq!(sim.battery_status(), vec![ BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }, BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: true }, ]); sim.sams[1].radar_on = false; assert_eq!(sim.battery_status(), vec![ BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: false, operational: false }, BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: false }, ]); } fn track(now: u64) -> Track { Track { id: 42, class: ClassEst::Firm(Class::Cruise), pos: DVec3::new(0.0, 100.0, -200.0), vel: DVec3::ZERO, tick: now, own_tick: now, source: 1, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false, } } #[test] fn shared_radar_serves_multiple_launchers_and_failure_blocks_cue() { let mut radar = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0); let mut a = Sam::new(2, SamKind::S400, DVec3::new(10.0, 0.0, 0.0), 0.0); let mut b = Sam::new(3, SamKind::S500, DVec3::new(20.0, 0.0, 0.0), 0.0); assert!(a.set_mode(SamMode::LauncherOnly)); assert!(b.set_mode(SamMode::LauncherOnly)); assert!(!a.radar_up() && !b.radar_up()); radar.tracks.push(track(10)); radar.set_radar_role(RadarRole::Search); radar.tracks.push(track(10)); assert!(!why::radar_cue(&a, &[&radar], 42, 10)); radar.set_radar_role(RadarRole::Height); radar.tracks.push(track(10)); assert!(!why::radar_cue(&a, &[&radar], 42, 10)); radar.set_radar_role(RadarRole::Engagement); radar.tracks.push(track(10)); assert!(why::radar_cue(&a, &[&radar], 42, 10)); assert!(why::radar_cue(&b, &[&radar], 42, 10)); assert!(!why::radar_cue(&a, &[&radar], 42, 10 + why::FAR_RADAR_AGE + 1)); radar.comps.0[Part::Comms as usize] = 0.0; assert!(!why::radar_cue(&a, &[&radar], 42, 10)); radar.comps.0[Part::Comms as usize] = 1.0; a.comps.0[Part::Comms as usize] = 0.0; assert!(!why::radar_cue(&a, &[&radar], 42, 10)); a.comps.0[Part::Comms as usize] = 1.0; a.pos.x = sight::LINK + 1.0; assert!(!why::radar_cue(&a, &[&radar], 42, 10)); a.pos.x = 10.0; radar.health = 0.0; assert!(!why::radar_cue(&a, &[&radar], 42, 10)); } #[test] fn network_shares_a_measurement_to_both_launchers_without_fabricating_own_tracks() { let mut sim = Sim::new(7); sim.tick = 10; let id = sim.id(); sim.sams.push(Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0)); for kind in [SamKind::S400, SamKind::S500] { let id = sim.id(); let mut launcher = Sam::new(id, kind, DVec3::new(10.0, 0.0, 0.0), 0.0); launcher.set_mode(SamMode::LauncherOnly); launcher.roles = 0xff; sim.sams.push(launcher); } sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 100.0, -200.0), DVec3::Z, DVec3::ZERO); let id = sim.drones[0].id; let mut measurement = track(10); measurement.id = id; sim.sams[0].tracks.push(measurement); sim.update_sight(&mut Ground::default()); for launcher in &sim.sams[1..] { let received = launcher.track(id).expect("shared measurement"); assert_eq!(received.tick, 10); assert_eq!(received.own_tick, 0); assert!(why::radar_cue(launcher, &[&sim.sams[0]], id, 10)); let load = launcher.kind.spec().missile.as_ref().unwrap(); let opts = why::Opts { last_chance: false, far_shots: false }; assert!(why::basis(launcher, load, received, &sim.drones[0], 10, 0, 1.0, opts, true, false).is_some()); assert!(why::basis(launcher, load, received, &sim.drones[0], 10, 0, 1.0, opts, false, false).is_none()); } sim.sams[0].health = 0.0; for launcher in &sim.sams[1..] { assert!(launcher.track(id).is_some()); assert!(!why::radar_cue(launcher, &[&sim.sams[0]], id, 10)); } } #[test] fn search_cues_tracking_radar_but_only_its_own_measurement_authorizes_launch() { for in_range in [true, false] { let mut sim = Sim::new(71); sim.tick = 10; let mut search = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0); search.set_radar_role(RadarRole::Search); let mut fire_control = Sam::new(2, SamKind::Radar, DVec3::ZERO, 0.0); fire_control.set_radar_role(RadarRole::Engagement); let mut launcher = Sam::new(3, SamKind::S400, DVec3::ZERO, 0.0); launcher.set_mode(SamMode::LauncherOnly); launcher.roles = 0xff; sim.sams.extend([search, fire_control, launcher]); let distance = if in_range { 100.0 } else { 10000.0 }; sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 70.0, -distance), DVec3::Z, DVec3::ZERO); let id = sim.drones[0].id; let mut measurement = track(10); measurement.id = id; measurement.pos = sim.drones[0].pos; sim.sams[0].tracks.push(measurement); sim.sams[0].beam = std::f64::consts::PI; sim.sams[1].beam = std::f64::consts::PI; let mut ground = Ground::default(); sim.update_sight(&mut ground); assert_eq!(sim.sams[1].track(id).unwrap().own_tick, 0, "cue is not a measurement"); assert!(!why::radar_cue(&sim.sams[2], &[&sim.sams[1]], id, sim.tick)); for now in 11..40 { sim.tick = now; // Bearing is north (zero); force the ordinary beam away each tick. sim.sams[1].beam = std::f64::consts::PI; sim.update_sight(&mut ground); if sim.sams[1].track(id).is_some_and(|t| t.own_tick > 0) { break; } } let got_own = sim.sams[1].track(id).is_some_and(|t| t.own_tick > 0); assert_eq!(got_own, in_range); assert_eq!(why::radar_cue(&sim.sams[2], &[&sim.sams[1]], id, sim.tick), in_range); if in_range { let tr = sim.sams[2].track(id).unwrap(); let load = sim.sams[2].kind.spec().missile.as_ref().unwrap(); let opts = why::Opts { last_chance: false, far_shots: false }; assert!(why::basis(&sim.sams[2], load, tr, &sim.drones[0], sim.tick, 0, 1.0, opts, true, false).is_some()); let mut out = Out::default(); for _ in 0..100 { sim.step(&mut ground, None, &mut out); if sim.sams[2].fired > 0 { break; } } assert!(sim.sams[2].fired > 0, "launcher never fired after its tracking radar measured the cue"); } } } #[test] fn fictional_roles_change_scan_and_height_and_coverage() { let mut r = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0); let base_mast = r.sensor_mast(); let base_scan = r.scan_ticks(); let base_reach = sight::reach(&r, DroneKind::Kh101, 5000.0); r.set_radar_role(RadarRole::Height); assert!(r.sensor_mast() > base_mast); r.set_radar_role(RadarRole::Engagement); assert!(r.scan_ticks() < base_scan && r.scan_profile().agile); assert!(sight::reach(&r, DroneKind::Kh101, 5000.0) < base_reach); r.set_radar_role(RadarRole::Search); assert!(sight::reach(&r, DroneKind::Kh101, 5000.0) > base_reach); } #[test] fn profiles_have_stable_ids_and_deliberately_different_limits() { let search = RadarRole::Search.profile(); let height = RadarRole::Height.profile(); let engagement = RadarRole::Engagement.profile(); let multi = RadarRole::Multifunction.profile(); assert_eq!((search.id, height.id, engagement.id, multi.id), ("radar_search", "radar_height", "radar_track", "radar_multi")); assert!(!RadarRole::Search.authorizes() && !RadarRole::Height.authorizes() && RadarRole::Engagement.authorizes()); assert_eq!(search.products, RadarProfile::SEARCH_BIT); assert_eq!(height.products, RadarProfile::SEARCH_BIT | RadarProfile::REFINE_BIT); assert_ne!(search.cycle, engagement.cycle); assert!(height.mast > search.mast && height.mast > engagement.mast); assert!(engagement.channels < multi.channels && height.channels > 0 && search.channels == 0); assert!(search.local > height.local && height.local > engagement.local); assert_eq!(RadarProfile::from_id(search.id), Some(search)); assert_eq!(RadarProfile::from_id("search"), Some(search), "legacy role keys map to profiles"); } #[test] fn launcher_has_no_own_map_sensor_and_mode_switch_drops_stale_tracks() { let mut sim = Sim::new(3); sim.sams.push(Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0)); assert!(sim.low_sensor(SamKind::S400, DVec3::ZERO, Some(1)).is_some()); sim.sams[0].tracks.push(track(10)); sim.sams[0].terrain.insert(42, (10, 1)); assert!(sim.sams[0].set_mode(SamMode::LauncherOnly)); assert!(sim.low_sensor(SamKind::S400, DVec3::ZERO, Some(1)).is_none()); assert!(sim.low_sensors().is_empty()); assert!(sim.sams[0].track(42).is_none()); assert!(sim.sams[0].terrain.is_empty()); sim.sams[0].set_mode(SamMode::Integrated); assert!(sim.low_sensor(SamKind::S400, DVec3::ZERO, Some(1)).is_some()); } #[test] fn configuration_clears_old_tracks_and_rejects_other_kinds() { let mut sam = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0); sam.tracks.push(track(10)); assert!(sam.set_mode(SamMode::LauncherOnly)); assert!(sam.tracks.is_empty()); assert!(sam.set_mode(SamMode::Integrated)); assert!(sam.radar_up()); let mut other = Sam::new(2, SamKind::Patriot, DVec3::ZERO, 0.0); assert!(!other.set_mode(SamMode::LauncherOnly)); assert_eq!(other.mode, SamMode::Integrated); } } #[cfg(test)] mod emission_tests { use super::*; #[test] fn silence_discloses_nothing_and_contacts_age_and_channels_still_place_a_unit() { let mut sim = Sim::new(121); sim.tick = 20; let mut source = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0); let mut receiver = Sam::new(2, SamKind::Radar, DVec3::ZERO, 0.0); receiver.set_radar_role(RadarRole::Engagement); receiver.radar_on = false; sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 70.0, -100.0), DVec3::Z, DVec3::ZERO); let id = sim.drones[0].id; source.tracks.push(Track { id, class: ClassEst::Firm(Class::Cruise), pos: sim.drones[0].pos, vel: DVec3::ZERO, tick: 20, own_tick: 20, source: 1, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 200, hits: 2, locked: false, }); sim.sams.extend([source, receiver]); let mut ground = Ground::default(); sim.update_sight(&mut ground); assert_eq!(sim.sams[1].track(id).unwrap().own_tick, 0); assert_eq!(sim.sams[1].track(id).unwrap().tick, 20); assert!(!sim.sams[1].radar_up()); // The emitting source gives the drone a coarse area. The silent receiver stays hidden. let picture = sim.knowledge_now().observations(); assert_eq!(picture.len(), 1); let signal = picture[0]; assert!(recon::is_mark(signal.id) && !signal.exact()); assert_eq!((signal.channel, signal.kind), (recon::Source::Emission, None)); sim.sams[0].radar_on = false; // The truth moving is not an observation: the contact keeps the observed place. sim.sams[0].pos = DVec3::new(400.0, 0.0, 0.0); sim.tick = 40; sim.update_sight(&mut ground); assert_eq!(sim.sams[1].track(id).unwrap().tick, 20); assert_eq!(sim.knowledge_now().observations(), picture, "a hidden move changed the picture"); // A fresh witnessed emission moves the estimated area. sim.sams[0].radar_on = true; sim.tick = 60; sim.update_sight(&mut ground); let moved = sim.knowledge_now().observations()[0]; assert_eq!(moved.id, signal.id); assert!(moved.at != signal.at && moved.at != sim.sams[0].pos); assert!(moved.at.distance(sim.sams[0].pos) < moved.radius); sim.sams[0].radar_on = false; // Other disclosure channels still reveal a silent unit. sim.recon.signal(&sim.sams[1], 60, recon::Source::Launch); assert!(sim.knowledge_now().observations().iter().any(|o| o.channel == recon::Source::Launch && !o.exact())); sim.tick = 6060; assert!(sim.knowledge_now().observations().is_empty(), "an unrefreshed contact never ages out"); } }