diff --git a/airdef-mod/src/map.rs b/airdef-mod/src/map.rs index 9dc7e8d..67f5f02 100644 --- a/airdef-mod/src/map.rs +++ b/airdef-mod/src/map.rs @@ -27,10 +27,14 @@ const F_TINT: usize = 8; /// Classes of systems for the filter: missile systems, guns, radars, the rear. const SYS_CLASSES: [&str; 4] = ["ЗРК", "ЗАК", "РЛС", "тыл"]; -/// Classes of the network's targets, by the speed of the track (the network doesn't know what a target is). +/// Classes of the network's targets: the class the tracks were *estimated* (#133), not what the +/// targets are; the unidentified are always shown — they cannot be filtered by a class they don't have yet. const TGT_CLASSES: [&str; 5] = ["Д", "Г", "К", "С", "Б"]; -/// Speed (blocks a tick) below which a track is of the class: drones, jets, cruise, supersonic, the rest ballistic. -const TGT_SPEED: [f64; 4] = [0.8, 1.8, 3.0, 6.5]; + +/// Whether the track passes the class filter: its estimated class is switched on, or it has none yet. +fn tclass_shown(t: &Track, on: &[bool; 5]) -> bool { + t.class.class().is_none_or(|c| on[c as usize]) +} /// A label line's height, pixels the markers merge within, how far from the pointer labels are kept at /// a low zoom, and the most labels at once. @@ -487,12 +491,6 @@ fn short_name(k: SamKind) -> &'static str { } } -/// The class of a track by its speed. -fn tgt_class(t: &Track) -> usize { - let v = t.vel.length(); - TGT_SPEED.iter().position(|&m| v < m).unwrap_or(TGT_SPEED.len()) -} - /// Markers within `r` pixels of the first of a group go with it: the groups, as indices into `pos`. pub(crate) fn group(pos: &[(f32, f32)], r: f32) -> Vec> { let r2 = r * r; @@ -618,7 +616,7 @@ fn hover_at(sim: &Sim, ui: &MapUi) -> Option { if ui.filters[F_TRACKS] { let now = sim.tick; for (id, t) in sim.picture() { - if !ui.tclass[tgt_class(&t)] { + if !tclass_shown(&t, &ui.tclass) { continue; } let e = t.est(now); @@ -654,8 +652,7 @@ fn track_lines(sim: &Sim, t: &Track, player: Option, lines: &mut Vec<(Str let now = sim.tick; let age = t.age(now); let forecast = t.forecast(now); - let class = t.kind.spec().class; - lines.push((format!("Трек №{} · {} ({})", t.id, t.kind.spec().name, class.name()), RED)); + lines.push((format!("Трек №{} · {}", t.id, t.class.name()), RED)); lines.push(( format!("Статус: {}{}", t.ident().name(), if forecast { format!(" · прогноз {} с", age / 20) } else { format!(" · измерение {} с назад", age / 20) }), if forecast { YELLOW } else { GREEN }, @@ -1418,7 +1415,7 @@ impl AirDef { let pic = self.sim.picture(); let mut best: Option<(f32, u32)> = None; for (id, t) in &pic { - if !ui.tclass[tgt_class(t)] { + if !tclass_shown(t, &ui.tclass) { continue; } let e = t.est(now); @@ -2227,8 +2224,8 @@ impl AirDef { fn map_tracks(&self, ui: &mut MapUi, s: &mut Vec, labs: &mut Vec, taken: &mut Vec<[f32; 4]>) { let now = self.sim.tick; let pic = self.sim.picture(); - // Only the classes asked for (the selected one always). - let shown: Vec<(&u32, &Track)> = pic.iter().filter(|(id, t)| ui.tclass[tgt_class(t)] || ui.sel == Some(Sel::Track(**id))).collect(); + // Only the classes asked for (the selected one and the unidentified always). + let shown: Vec<(&u32, &Track)> = pic.iter().filter(|(id, t)| tclass_shown(t, &ui.tclass) || ui.sel == Some(Sel::Track(**id))).collect(); for (id, t) in &shown { let chosen = ui.sel == Some(Sel::Track(**id)); if ui.filters[F_TRAILS] @@ -2294,13 +2291,20 @@ impl AirDef { if !forecast { s.push(diamond(c.0, c.1, 3.0, 0xFF200808)); } - // Its course, a tick out of the marker. + // Its measured course, a tick out of the marker. let v = t.vel.normalize_or_zero(); if v != DVec3::ZERO { s.push(line(c, (c.0 + v.x as f32 * 10.0, c.1 + v.z as f32 * 10.0), 1.5, col)); } taken.push([c.0 - TRACK_R - 1.0, c.1 - TRACK_R - 1.0, TRACK_R * 2.0 + 2.0, TRACK_R * 2.0 + 2.0]); - let txt = format!("{} {}{}", t.kind.spec().class.letter(), if forecast { "~" } else { "" }, if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) }); + let mark = t.class.mark(); + let age = if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) }; + let txt = match (mark.is_empty(), forecast) { + (true, true) => format!("~{age}"), + (true, false) => age, + (false, true) => format!("{mark} ~{age}"), + (false, false) => format!("{mark} {age}"), + }; add_lab(ui, labs, txt, c, TRACK_R + 1.0, col, chosen); if chosen { s.extend(frame(c.0 - 10.0, c.1 - 10.0, 20.0, 20.0, 1.0, GREEN)); @@ -2379,9 +2383,14 @@ impl AirDef { for x in &self.sim.sams { sc[sys_class(x.kind)] += 1; } + // By the estimated class; the unidentified are counted apart. let mut tc = [0usize; 5]; + let mut unknown = 0usize; for t in self.sim.picture().values() { - tc[tgt_class(t)] += 1; + match t.class.class() { + Some(c) => tc[c as usize] += 1, + None => unknown += 1, + } } inner.push(text("Системы по классу", x0, y, GREY)); y += lh; @@ -2396,7 +2405,7 @@ impl AirDef { x += draw_btn(ui, &mut inner, &label, Act::SysClass(i), ui.sclass[i], x, y, bh); } y += bh + 6.0; - inner.push(text("Цели сети по скорости", x0, y, GREY)); + inner.push(text("Цели сети по классу", x0, y, GREY)); y += lh; x = x0; for i in 0..TGT_CLASSES.len() { @@ -2408,6 +2417,8 @@ impl AirDef { } x += draw_btn(ui, &mut inner, &label, Act::TgtClass(i), ui.tclass[i], x, y, bh); } + // The unidentified: a count, not a filter (they are always shown). + inner.push(text(format!("? {unknown} (не опознано)"), x, y + 2.0, GREY)); y += bh + 5.0; for l in ["ЗРК ракеты · ЗАК пушки · тыл", "Д дроны · Г реактивные · К крылатые", "С сверхзвук · Б баллистика"] { inner.push(text(l, x0, y, GREY)); @@ -2917,7 +2928,7 @@ mod tests { assert_eq!(hover_at(&sim, &ui), Some(Hover::Drone(id))); // A measured track is hoverable in the honest picture too. sim.truth = false; - let t = Track { id, kind: sim::DroneKind::Shahed, pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, ttl: 200, hits: 3, locked: false }; + let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, ttl: 200, hits: 3, locked: false }; sim.sams[0].tracks.push(t); assert_eq!(hover_at(&sim, &ui), Some(Hover::Track(id))); // Away from the marker there is nothing. @@ -2929,7 +2940,7 @@ mod tests { #[test] fn the_network_card_never_claims_a_target_and_lists_its_status_and_interception() { let (mut sim, id, _) = hover_fixture(); - let t = Track { id, kind: sim::DroneKind::Shahed, pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::new(0.0, 0.0, 0.5), tick: 0, own_tick: 0, ttl: 200, hits: 3, locked: true }; + let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::new(0.0, 0.0, 0.5), tick: 0, own_tick: 0, ttl: 200, hits: 3, locked: true }; sim.sams[0].tracks.push(t); let mut lines = Vec::new(); track_lines(&sim, &t, Some(DVec3::ZERO), &mut lines); diff --git a/airdef-mod/src/monitor.rs b/airdef-mod/src/monitor.rs index 727e69b..3df159a 100644 --- a/airdef-mod/src/monitor.rs +++ b/airdef-mod/src/monitor.rs @@ -3,7 +3,7 @@ //! renders it) locked on its target. K shows one system at a time, J all of //! them in a grid. use crate::panel::distance; -use crate::sim::{Sam, SamState, Sim, heading_of, roles_text}; +use crate::sim::{ClassEst, Sam, SamState, Sim, heading_of, roles_text}; use glam::DVec3; use horizon_mod_sdk::render::{self, CameraView, FillShape, Point, QuadShape, Rect, Shape, TextShape, ViewShape}; @@ -146,13 +146,17 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec 50.0 { - s.push(text(fit(t.kind.spec().name.into(), cw - 6.0), cx + 3.0, cy + ch - 20.0, 0xFFFFFFFF)); + // What the system knows it by: the estimated class; the sandbox's truth names the model. + let name = if sim.truth { t.kind.spec().name.to_string() } else { track.map_or_else(|| "тип не определён".into(), |tr| tr.class.name()) }; + s.push(text(fit(name, cw - 6.0), cx + 3.0, cy + ch - 20.0, 0xFFFFFFFF)); } - let mut info = format!("{} в{:.0} {:.0}км/ч", distance(rel.length()), at.y - sam.pos.y, t.vel.length() * 72.0); + // The speed its own measurements showed, never the target's own figures. + let mut info = format!("{} в{:.0} {:.0}км/ч", distance(rel.length()), at.y - sam.pos.y, track.map_or(0.0, |tr| tr.vel.length()) * 72.0); if let Some(tr) = track { if tr.forecast(tick) { info += &format!(" прогноз {:.1}с", tr.age(tick) as f64 / 20.0); diff --git a/airdef-mod/src/panel.rs b/airdef-mod/src/panel.rs index 584a663..48fc459 100644 --- a/airdef-mod/src/panel.rs +++ b/airdef-mod/src/panel.rs @@ -1,6 +1,6 @@ //! The summary panel (top right): the alert, what is in the air, each //! air-defence system's state and the score. -use crate::sim::{AirPicture, DroneKind, Sim}; +use crate::sim::{AirPicture, Class, ClassEst, Sim}; use glam::DVec3; use horizon_mod_sdk::hud::Line; @@ -31,24 +31,35 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec { } else { let blink = (sim.tick / 10) % 2 == 0; lines.push(line(format!("ВОЗДУШНАЯ ТРЕВОГА — целей: {}", pic.tracks.len()), if blink { RED } else { PINK })); - // By type, as the radars classed them. + // By the class the tracks were estimated (#133): probable and firm counted apart, the + // unidentified named — the exact models stay in the sandbox's truth line. let mut by_type = String::new(); - for kind in DroneKind::ALL { - let n = pic.tracks.iter().filter(|t| t.kind == kind).count(); - if n > 0 { - if !by_type.is_empty() { - by_type += ", "; + for c in Class::ALL { + let firm = pic.tracks.iter().filter(|t| t.class == ClassEst::Firm(c)).count(); + let prob = pic.tracks.iter().filter(|t| t.class == ClassEst::Probable(c)).count(); + for (n, pre) in [(firm, ""), (prob, "вер. ")] { + if n > 0 { + if !by_type.is_empty() { + by_type += ", "; + } + by_type += &format!("{pre}{} ×{n}", c.name()); } - by_type += &format!("{} ×{n}", kind.spec().name); } } + let unknown = pic.tracks.iter().filter(|t| t.class == ClassEst::Unknown).count(); + if unknown > 0 { + if !by_type.is_empty() { + by_type += ", "; + } + by_type += &format!("не опознано ×{unknown}"); + } lines.push(line(by_type, PINK)); // The nearest track to the player: where it was last measured (a forecast says so, with its age). if let Some(t) = pic.nearest(player) { let e = t.est(now); let mark = if t.forecast(now) { format!(" ~{}с", t.age(now) / 20) } else { String::new() }; lines.push(line( - format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч{mark}", t.kind.spec().name, distance(e.distance(player)), e.y - player.y, kmh(t.vel)), + format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч{mark}", t.class.name(), distance(e.distance(player)), e.y - player.y, kmh(t.vel)), PINK, )); } @@ -99,7 +110,7 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec { crate::battery_view::sam_status(sam) }; if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) { - text += &format!(" > {} {}", t.kind.spec().name, distance(t.est(now).distance(sam.pos))); + text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos))); } if sam.kills > 0 { text += &format!(" ({})", sam.kills); diff --git a/airdef-mod/src/radar.rs b/airdef-mod/src/radar.rs index 63decbc..c4b5af1 100644 --- a/airdef-mod/src/radar.rs +++ b/airdef-mod/src/radar.rs @@ -2,7 +2,7 @@ //! with a sweeping beam; blips fade after the beam passes them. A track's blip is a shape by the //! class the radar measured (#132), big enough to read at a glance; close ones merge with a count. use crate::panel::distance; -use crate::sim::{Class, SamKind, Sim}; +use crate::sim::{Class, ClassEst, SamKind, Sim}; use glam::DVec3; use horizon_mod_sdk::render::{FillShape, Point, QuadShape, Rect, Shape, TextShape}; @@ -41,20 +41,22 @@ fn alpha(rgb: u32, a: f64) -> u32 { ((a.clamp(0.0, 1.0) * 255.0) as u32) << 24 | (rgb & 0xFFFFFF) } -/// A track's blip: a shape by the class the radar measured, pointing along the course where there is one. -/// Drones are triangles, jets darts, cruise squares, supersonic diamonds, ballistic octagons. -fn blip(class: Class, x: f32, y: f32, color: u32, vel: DVec3) -> Vec { +/// A track's blip: a shape by the estimated class, pointing along the measured course. +/// Drones are triangles, jets darts, cruise squares, supersonic diamonds, ballistic octagons; +/// an unidentified track gets a question mark instead of leaking the target's type (#133). +fn blip(class: ClassEst, x: f32, y: f32, color: u32, vel: DVec3) -> Vec { let h = DVec3::new(vel.x, 0.0, vel.z).normalize_or_zero(); let (hx, hy) = if h == DVec3::ZERO { (0.0, -1.0) } else { (h.x as f32, h.z as f32) }; let (px, py) = (-hy, hx); let r = BLIP; let at = |along: f32, side: f32| pt(x + hx * along + px * side, y + hy * along + py * side); - match class { - Class::Drone => vec![quad(at(r * 1.2, 0.0), at(-r * 0.8, r * 0.9), at(-r * 0.8, -r * 0.9), at(-r * 0.8, -r * 0.9), color)], - Class::Jet => vec![quad(at(r * 1.3, 0.0), at(-r * 0.9, r * 0.9), at(-r * 0.3, 0.0), at(-r * 0.9, -r * 0.9), color)], - Class::Cruise => vec![square(x, y, 2.6, color)], - Class::Supersonic => vec![quad(pt(x, y - 3.2), pt(x + 3.2, y), pt(x, y + 3.2), pt(x - 3.2, y), color)], - Class::Ballistic => vec![square(x, y, 2.3, color), quad(pt(x, y - r), pt(x + r, y), pt(x, y + r), pt(x - r, y), color)], + match class.class() { + Some(Class::Drone) => vec![quad(at(r * 1.2, 0.0), at(-r * 0.8, r * 0.9), at(-r * 0.8, -r * 0.9), at(-r * 0.8, -r * 0.9), color)], + Some(Class::Jet) => vec![quad(at(r * 1.3, 0.0), at(-r * 0.9, r * 0.9), at(-r * 0.3, 0.0), at(-r * 0.9, -r * 0.9), color)], + Some(Class::Cruise) => vec![square(x, y, 2.6, color)], + Some(Class::Supersonic) => vec![quad(pt(x, y - 3.2), pt(x + 3.2, y), pt(x, y + 3.2), pt(x - 3.2, y), color)], + Some(Class::Ballistic) => vec![square(x, y, 2.3, color), quad(pt(x, y - r), pt(x + r, y), pt(x, y + r), pt(x - r, y), color)], + None => vec![square(x, y, 2.4, color), text("?".into(), x, y - 3.0, 0xFF200808, true)], } } @@ -189,7 +191,7 @@ pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec { let pic = sim.air_picture(); let now = pic.now; // (x, y, class, colour, brightness, velocity) of every track on the scope, its icon kept inside the disc. - let mut marks: Vec<(f32, f32, Class, u32, f64, DVec3)> = Vec::new(); + let mut marks: Vec<(f32, f32, ClassEst, u32, f64, DVec3)> = Vec::new(); for t in &pic.tracks { let (pos, vel) = (t.est(now), t.vel); match scope(pos) { @@ -203,7 +205,7 @@ pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec { (1.0, 0xFF4040) }; let (x, y) = inside(x, y, cx, cy, r); - marks.push((x, y, t.kind.spec().class, color, a, vel)); + marks.push((x, y, t.class, color, a, vel)); } None => far += 1, } @@ -261,7 +263,7 @@ mod tests { #[test] fn every_class_has_its_own_blip_shape() { let vel = DVec3::new(0.5, 0.0, 0.0); - let shapes: Vec> = Class::ALL.iter().map(|c| blip(*c, 50.0, 50.0, 0xFFFF4040, vel)).collect(); + let shapes: Vec> = Class::ALL.iter().map(|c| blip(ClassEst::Firm(*c), 50.0, 50.0, 0xFFFF4040, vel)).collect(); for (i, a) in shapes.iter().enumerate() { assert!(!a.is_empty()); for b in &shapes[i + 1..] { @@ -269,7 +271,8 @@ mod tests { } } // A courseless track (a ballistic one straight overhead) still draws, pointing north. - assert!(!blip(Class::Ballistic, 50.0, 50.0, 0xFFFF4040, DVec3::Y).is_empty()); + assert!(!blip(ClassEst::Firm(Class::Ballistic), 50.0, 50.0, 0xFFFF4040, DVec3::Y).is_empty()); + assert!(blip(ClassEst::Unknown, 50.0, 50.0, 0xFFFF4040, vel).iter().any(|s| matches!(s, Shape::Text(t) if t.text == "?"))); } #[test] diff --git a/airdef-mod/src/sim/battery.rs b/airdef-mod/src/sim/battery.rs index 562a626..da935b2 100644 --- a/airdef-mod/src/sim/battery.rs +++ b/airdef-mod/src/sim/battery.rs @@ -113,7 +113,7 @@ mod tests { } fn track(now: u64) -> Track { - Track { id: 42, kind: DroneKind::Kh101, pos: DVec3::new(0.0, 100.0, -200.0), vel: DVec3::ZERO, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false } + 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, ttl: 400, hits: 3, locked: false } } #[test] @@ -294,7 +294,7 @@ mod emission_tests { 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, kind: DroneKind::Kh101, pos: sim.drones[0].pos, vel: DVec3::ZERO, tick: 20, own_tick: 20, ttl: 200, hits: 2, locked: false }); + source.tracks.push(Track { id, class: ClassEst::Firm(Class::Cruise), pos: sim.drones[0].pos, vel: DVec3::ZERO, tick: 20, own_tick: 20, ttl: 200, hits: 2, locked: false }); sim.sams.extend([source, receiver]); let mut ground = Ground::default(); sim.update_sight(&mut ground); diff --git a/airdef-mod/src/sim/doctrine.rs b/airdef-mod/src/sim/doctrine.rs index fb8f5da..1efc760 100644 --- a/airdef-mod/src/sim/doctrine.rs +++ b/airdef-mod/src/sim/doctrine.rs @@ -85,6 +85,11 @@ impl Doctrine { if near <= slack { return true; } + // One blip carries no measured course (#133): nothing says the contact passes the + // object by, so it is not ruled out as a threat on a velocity that is not there. + if track.hits <= 1 { + return true; + } let (vx, vz) = (track.vel.x, track.vel.z); let speed = vx.hypot(vz); // Closing, and the line of flight passes the object within the slack. @@ -97,23 +102,24 @@ impl Doctrine { (if self.in_sector(pos, track.est(now)) { 0 } else { OUT_SECTOR }) | (if self.guards.is_empty() || self.threatens(track, now).is_some() { 0 } else { NO_THREAT }) } - /// What matters enough to spend the reserve: a ballistic missile, or anything about to hit. - pub fn matters(d: &Drone) -> bool { - d.kind.spec().class == Class::Ballistic || why::arrival(d) < why::URGENT + /// What matters enough to spend the reserve: a ballistic missile (as the track's estimate + /// classes it, an unidentified contact does not count), or anything about to hit. + pub fn matters(d: &Drone, class: ClassEst) -> bool { + class.class() == Some(Class::Ballistic) || why::arrival(d) < why::URGENT } /// The reserve holds the launch back: the magazine is at the reserve and the target doesn't matter. - pub fn reserve_blocks(&self, missiles: u32, d: &Drone) -> u8 { - if self.reserve > 0 && missiles <= self.reserve && !Self::matters(d) { RESERVE } else { 0 } + pub fn reserve_blocks(&self, missiles: u32, d: &Drone, class: ClassEst) -> u8 { + if self.reserve > 0 && missiles <= self.reserve && !Self::matters(d, class) { RESERVE } else { 0 } } /// Interceptors this doctrine asks for on `d`: `why::needed` by default, the base only when economical, one more when heavy. - pub fn needed(&self, d: &Drone) -> u32 { - let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 }; + pub fn needed(&self, d: &Drone, class: ClassEst) -> u32 { + let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 }; match self.salvo { Salvo::Economy => base, - Salvo::Normal => why::needed(d), - Salvo::Heavy => why::needed(d) + 1, + Salvo::Normal => why::needed(d, class), + Salvo::Heavy => why::needed(d, class) + 1, } } @@ -162,7 +168,7 @@ mod tests { use super::*; fn track(pos: DVec3, vel: DVec3) -> Track { - Track { id: 1, kind: DroneKind::Shahed, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false } + Track { id: 1, class: ClassEst::Unknown, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false } } #[test] diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 8eb2eb7..7707860 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -574,11 +574,113 @@ impl Class { Class::Ballistic => "Б", } } + /// The class as one object ("дрон", "крылатая ракета"): what a track's estimate reads as. + pub fn singular(self) -> &'static str { + match self { + Class::Drone => "дрон", + Class::Jet => "реакт. дрон", + Class::Cruise => "крылатая ракета", + Class::Supersonic => "сверхзвуковая ракета", + Class::Ballistic => "баллистическая ракета", + } + } + /// The class a measured speed (blocks a tick) says: the classifier's bands (#133), between the + /// game's own speed clusters, so a slow propeller drone is never read as a jet. Contacts near a + /// boundary can sit in the wrong class for a while, or stay undecided between measurements: + /// there is no "three blips and the mark is known". A fast ballistic and a supersonic missile + /// fly alike (their bands overlap): only speed cannot tell them apart, and the first version + /// does not model the flight profile that would. + pub fn of_speed(v: f64) -> Class { + if v < 1.35 { + Class::Drone + } else if v < 1.9 { + Class::Jet + } else if v < 3.0 { + Class::Cruise + } else if v < 6.5 { + Class::Supersonic + } else { + Class::Ballistic + } + } pub fn from_key(key: &str) -> Option { Self::ALL.into_iter().find(|c| c.key() == key) } } +/// What the radars make of a track's class, from the measurements alone (#133): separate from +/// the track's confirmation (`Track::ident`, how firmly it is held), its own state with its own +/// rules. It travels with the measurement it grew from: a relay passes it as it was, ageing with +/// the track, and it is gone when the track drops — a re-detected contact starts over. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ClassEst { + /// One measurement yet: something is there, its class is not. + Unknown, + /// Measured again: a class by how it flies; a new contrary measurement can still change it. + Probable(Class), + /// Several measurements agreed: high confidence. + Firm(Class), +} + +impl ClassEst { + /// The class it holds, if any. + pub fn class(self) -> Option { + match self { + ClassEst::Unknown => None, + ClassEst::Probable(c) | ClassEst::Firm(c) => Some(c), + } + } + + /// The estimate stepped by one more measurement that saw `speed`, `hits` of them so far (#133): + /// the first says nothing; the second names a class by its speed; each further agreeing + /// measurement firms it up, a contrary one replaces the hypothesis with the new guess. + /// Pure arithmetic on the measurement: nothing random, nothing from the target itself. + pub fn step(self, hits: u8, speed: f64) -> ClassEst { + let seen = Class::of_speed(speed); + match (self, hits) { + (_, 1) => ClassEst::Unknown, + (_, 2) => ClassEst::Probable(seen), + (ClassEst::Firm(had), _) if had == seen => ClassEst::Firm(had), + (ClassEst::Probable(had), _) if had == seen => ClassEst::Firm(had), + _ => ClassEst::Probable(seen), + } + } + + /// Whether a system's roles cover the track's class. The explicit policy for the unknown + /// (#133): an unidentified track is not blocked by the class filter — it stays a candidate + /// under the general rules, and `why` says so. A system with no roles at all is holding its + /// fire: nothing is a candidate for it. A probable or firm class out of the roles is a block, + /// named in `why` too. + pub fn in_roles(self, roles: u8) -> bool { + match self { + ClassEst::Unknown => roles != 0, + ClassEst::Probable(c) | ClassEst::Firm(c) => roles & c.bit() != 0, + } + } + + /// As the screens read it: «тип не определён», «вероятно крылатая ракета», «крылатая ракета». + pub fn name(self) -> String { + match self { + ClassEst::Unknown => "тип не определён".into(), + ClassEst::Probable(c) => format!("вероятно {}", c.singular()), + ClassEst::Firm(c) => c.singular().into(), + } + } + + /// A short mark for the map's labels: the class letter, with `?` while the guess is only probable. + pub fn mark(self) -> &'static str { + match self { + ClassEst::Unknown => "", + ClassEst::Firm(c) => c.letter(), + ClassEst::Probable(Class::Drone) => "Д?", + ClassEst::Probable(Class::Jet) => "Г?", + ClassEst::Probable(Class::Cruise) => "К?", + ClassEst::Probable(Class::Supersonic) => "С?", + ClassEst::Probable(Class::Ballistic) => "Б?", + } + } +} + /// Roles as a mask of [`Class::bit`]s, from `drone,jet,...` or `all`. pub fn parse_roles(text: &str) -> Option { if text == "all" { @@ -2282,7 +2384,7 @@ impl Sim { let drone = |tr: &Track| drone_at.get(&tr.id).map(|&k| &self.drones[k]); let claimed = |d: &Drone| why::claimed(d, &missile_on, had_target); let doc = &me.doctrine; - let needed = |d: &Drone| doc.needed(d); + let needed = |tr: &Track, d: &Drone| doc.needed(d, tr.class); let opts = why::Opts { last_chance: self.last_chance, far_shots: self.far_shots }; let target = spec.missile.as_ref().map(|load| { // A launcher with nothing to fire (reloading, empty, failed) claims no target: others take it. @@ -2300,7 +2402,7 @@ impl Sim { let stuck = me.held > why::HOLD_MAX; let keep = had_target.filter(|t| !stuck && tracks.iter().any(|tr| tr.id == *t && basis(tr, 1.1, false).is_some())); keep.or_else(|| { - let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(d)); + let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(tr, d)); // Long shots only while nothing of the system's roles is in its normal reach. let role_in_reach = !radars.is_empty() && tracks.iter().any(|tr| free(tr) && basis(tr, 1.0, true) == Some(why::Basis::Role)); tracks @@ -2349,7 +2451,10 @@ impl Sim { } sam.target = target; } - if let Some(gun_target) = gun_target { + let gun_target = gun_target.flatten(); + if gun_target.is_some() || had_gun.is_some() { + // A track that stopped being a candidate is let go (a class estimated out of the + // roles since it was taken, #133, included): the gun must not keep firing at it. retarget(&mut guns_on, had_gun, gun_target); self.sams[i].gun_target = gun_target; } @@ -2385,13 +2490,14 @@ impl Sim { } else { SamState::Search }; - // Nothing to fire at: the mount watches the nearest track of its classes (a reaction a turn - // shorter), else it goes back to the rest position, under the drive's limits like any other turn. + // Nothing to fire at: the mount watches the nearest track of its classes (by the class + // the network estimates, the unknown among them: a reaction a turn shorter), else it + // goes back to the rest position, under the drive's limits like any other turn. let (mount, _) = sam.mount(); let watch = sam .tracks .iter() - .filter(|tr| tr.age(now) <= sight::MISSILE_AGE && drone_at.get(&tr.id).is_some_and(|&k| roles & self.drones[k].kind.spec().class.bit() != 0 && self.drones[k].alive())) + .filter(|tr| tr.age(now) <= sight::MISSILE_AGE && tr.class.in_roles(roles) && drone_at.get(&tr.id).is_some_and(|&k| self.drones[k].alive())) .min_by(|a, b| a.est(now).distance(mount).total_cmp(&b.est(now).distance(mount))) .map(|tr| why::aim_wants(mount, tr.est(now), tr.vel, spec.gun.as_ref().map_or(5.0, |g| g.shell))); match (watch, spec.family) { diff --git a/airdef-mod/src/sim/record.rs b/airdef-mod/src/sim/record.rs index e8bc126..00e9176 100644 --- a/airdef-mod/src/sim/record.rs +++ b/airdef-mod/src/sim/record.rs @@ -1290,7 +1290,7 @@ mod tests { let id = sim.id(); sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0)); let mut r = Recording::new(1, &sim); - let tr = sight::Track { id: 77, kind: DroneKind::Shahed, pos: DVec3::Z * 100.0, vel: -DVec3::Z, tick: 1, own_tick: 1, ttl: 10, hits: 1, locked: false }; + let tr = sight::Track { id: 77, class: ClassEst::Firm(Class::Drone), pos: DVec3::Z * 100.0, vel: -DVec3::Z, tick: 1, own_tick: 1, ttl: 10, hits: 1, locked: false }; sim.sams[0].tracks.push(tr); r.note_tracks(&sim.sams); r.len = 1; @@ -1356,7 +1356,7 @@ mod tests { let id = sim.id(); let mut sam = Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0); for target in 1..=4 { - sam.tracks.push(sight::Track { id: target, kind: DroneKind::Shahed, pos: DVec3::Z, vel: DVec3::ZERO, tick: 1, own_tick: 1, ttl: 1, hits: 1, locked: false }); + sam.tracks.push(sight::Track { id: target, class: ClassEst::Firm(Class::Drone), pos: DVec3::Z, vel: DVec3::ZERO, tick: 1, own_tick: 1, ttl: 1, hits: 1, locked: false }); } sim.sams.push(sam); } diff --git a/airdef-mod/src/sim/regress.rs b/airdef-mod/src/sim/regress.rs index b1894ad..406a25a 100644 --- a/airdef-mod/src/sim/regress.rs +++ b/airdef-mod/src/sim/regress.rs @@ -2433,7 +2433,7 @@ fn recorded_ignition_is_cold_ticks_after_ejection_and_replay_follows_it() { // the test is about the launch stages, not about the scan's chance. let now = sim.tick; let tracks: Vec = sim.drones.iter().filter(|d| d.alive()) - .map(|d| sight::Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }) + .map(|d| sight::Track { id: d.id, class: ClassEst::Firm(d.kind.spec().class), pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }) .collect(); sim.sams[0].tracks.retain(|t| !tracks.iter().any(|n| n.id == t.id)); sim.sams[0].tracks.extend(tracks); diff --git a/airdef-mod/src/sim/sensor_tests.rs b/airdef-mod/src/sim/sensor_tests.rs index 55854b1..0e48e56 100644 --- a/airdef-mod/src/sim/sensor_tests.rs +++ b/airdef-mod/src/sim/sensor_tests.rs @@ -122,6 +122,9 @@ fn a_failed_radar_gives_no_own_tracks_but_the_network_still_feeds_it() { let early = radar_at(&mut sim, SamKind::Radar, 120.0); let id = drone_from(&mut sim, -150.0); sim.sams[p].comps.0[Part::Sensor as usize] = 0.0; + // Hold fire: the fed track is now acted on (an unidentified contact is a candidate under the + // general rules, #133), and this test is about the feed, not about the intercept. + sim.sams[p].roles = 0; for _ in 0..500 { sim.step(&mut ground, None, &mut out); } @@ -254,3 +257,166 @@ fn the_same_seed_rolls_the_same_scan_and_damage() { }; assert_eq!(run(), run()); } + +// ---------------------------------------------------------------- #133: the class estimate + +#[test] +fn the_classifier_steps_by_the_measurements_alone() { + // The same observed speeds give the same estimate whatever the contact truly is, and a + // contrary measurement replaces the hypothesis instead of being ignored. + let mut est = ClassEst::Unknown; + assert_eq!(est.step(1, 0.6), ClassEst::Unknown, "one blip says nothing of the class"); + est = est.step(2, 0.6); + assert_eq!(est, ClassEst::Probable(Class::Drone)); + est = est.step(3, 0.62); + assert_eq!(est, ClassEst::Firm(Class::Drone), "agreeing measurements firm the guess"); + // The contact proves much faster (or the first readings misled): the hypothesis gives way, + // and one measurement is not enough to firm the new one. + est = est.step(4, 5.0); + assert_eq!(est, ClassEst::Probable(Class::Supersonic)); + est = est.step(5, 5.1); + assert_eq!(est, ClassEst::Firm(Class::Supersonic)); + // Whatever the true kind, the same observations read the same: a Kinzhal measured as a slow + // propeller is, to the network, a drone until its measurements say otherwise. + assert_eq!(ClassEst::Unknown.step(2, 0.5), ClassEst::Probable(Class::Drone)); +} + +#[test] +fn the_speed_bands_read_the_games_own_kinds_right() { + // The bands sit between the game's speed clusters: the measured speed of a kind reads as its + // class, so a slow Lancet is no jet and a Shahed no cruise missile. A fast ballistic and a + // supersonic missile fly alike (the Iskander and the Zircon): speed alone leaves that + // ambiguity, documented on `Class::of_speed`. + for kind in DroneKind::ALL { + let spec = kind.spec(); + if spec.class == Class::Ballistic && spec.speed < 6.5 { + continue; + } + assert_eq!(Class::of_speed(spec.speed), spec.class, "{kind:?} at {} blocks a tick", spec.speed); + } + assert_eq!(Class::of_speed(5.0), Class::Supersonic, "a fast ballistic and a supersonic fly alike"); +} + +#[test] +fn the_first_blip_gives_no_class_and_no_speed() { + let mut sim = Sim::new(5); + let (mut ground, mut out) = flat(); + let r = radar_at(&mut sim, SamKind::Radar, 0.0); + let id = drone_from(&mut sim, -150.0); + let mut first = None; + for _ in 0..300 { + sim.step(&mut ground, None, &mut out); + if let Some(t) = sim.sams[r].track(id) { + first = Some(*t); + break; + } + } + let t = first.expect("a track of the drone"); + assert_eq!(t.hits, 1); + assert_eq!(t.class, ClassEst::Unknown, "the first measurement must not name a class"); + assert_eq!(t.vel, DVec3::ZERO, "the true velocity must not leak into the track"); +} + +#[test] +fn tracks_of_different_kinds_one_class_firm_the_same_estimate() { + // A Shahed and a Gerbera are different machines of one class, flying alike; the picture both + // networks end up holding is the same: a firm slow drone, never a model name. (Faster kinds + // cross this little radar's reach between beam passes: too few measurements to firm anything.) + let roles = SamKind::S400.spec().roles; + let mut seen = Vec::new(); + for kind in [DroneKind::Shahed, DroneKind::Gerbera] { + let mut sim = Sim::new(7); + let (mut ground, mut out) = flat(); + // One radar: an uninterrupted chain of measurements (two early-warning radars do not + // exchange tracks — a radar is fed only when it serves fire control — so the second one + // would measure from a blank picture, its own chain apart). + radar_at(&mut sim, SamKind::Radar, 0.0); + let from = DVec3::new(-150.0, 95.0, 40.0); + sim.add_drone(kind, from, DVec3::X, DVec3::new(5000.0, 95.0, 40.0)); + let id = sim.drones.last().unwrap().id; + let mut est = None; + for _ in 0..700 { + sim.step(&mut ground, None, &mut out); + if let Some(t) = sim.picture().get(&id) { + est = Some(t.class); + } + } + assert_eq!(est, Some(ClassEst::Firm(Class::Drone)), "{kind:?}: {est:?}"); + // The wording and the class-dependent decisions come from the estimate, not the machine. + let est = est.unwrap(); + seen.push((est, est.name(), est.mark(), est.in_roles(roles))); + } + assert_eq!(seen[0], seen[1], "the same observations read differently for two kinds: {seen:?}"); +} + +#[test] +fn the_role_policy_keeps_the_unidentified_and_holds_fire_with_no_roles() { + let some = Class::Drone.bit() | Class::Jet.bit(); + // An unidentified contact is not a block: it stays a candidate under the general rules. + assert!(ClassEst::Unknown.in_roles(some)); + // No roles at all is holding fire: nothing is a candidate, the unidentified included. + assert!(!ClassEst::Unknown.in_roles(0), "hold fire must block the unidentified too"); + // A probable guess is a block when its class is out of the roles, and a pass when in them. + assert!(ClassEst::Probable(Class::Drone).in_roles(some)); + assert!(!ClassEst::Probable(Class::Cruise).in_roles(some)); + assert!(ClassEst::Firm(Class::Jet).in_roles(some)); + assert!(!ClassEst::Firm(Class::Ballistic).in_roles(0)); +} + +#[test] +fn a_gun_lets_go_of_a_track_classified_out_of_its_roles() { + // The Gepard's roles are drones, jets and cruise missiles: a supersonic missile is out of them. + assert_eq!(SamKind::Gepard.spec().roles & Class::Supersonic.bit(), 0); + let mut sim = Sim::new(11); + let (mut ground, mut out) = flat(); + let p = radar_at(&mut sim, SamKind::Gepard, 0.0); + sim.add_drone(DroneKind::Zircon, DVec3::new(0.0, 95.0, -60.0), DVec3::Z, DVec3::new(0.0, 70.0, -700.0)); + let id = sim.drones.last().unwrap().id; + sim.tick = 10; + let seed = |sim: &mut Sim, class| { + let d = sim.drones[0].clone(); + sim.sams[p].tracks.retain(|t| t.id != d.id); + sim.sams[p].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: sim.tick, own_tick: sim.tick, ttl: 400, hits: 3, locked: false }); + }; + // Taken while the class was unknown: the general rules make it a candidate. + seed(&mut sim, ClassEst::Unknown); + sim.step_sams(&mut ground, &mut out); + assert_eq!(sim.sams[p].gun_target, Some(id), "an unidentified track is not its gun target"); + // Classified: no longer a class the gun engages, and it is let go instead of being fired at. + seed(&mut sim, ClassEst::Firm(Class::Supersonic)); + sim.step_sams(&mut ground, &mut out); + assert_eq!(sim.sams[p].gun_target, None, "the gun kept a track its roles do not cover"); +} + +#[test] +fn forecasts_and_relays_add_no_confidence() { + let mut sim = Sim::new(7); + let (mut ground, mut out) = flat(); + let a = radar_at(&mut sim, SamKind::Radar, 0.0); + let _b = radar_at(&mut sim, SamKind::Radar, 500.0); + let n = radar_at(&mut sim, SamKind::P1sun, 250.0); + let id = drone_from(&mut sim, -50.0); + // The source's own track: while no new measurement lands (the tick unchanged, the track only + // forecast onwards) the estimate must not move — a forecast is not data. + let mut prev: Option<(u64, ClassEst)> = None; + let mut relayed = 0; + for _ in 0..800 { + sim.step(&mut ground, None, &mut out); + if let Some(t) = sim.sams[a].track(id).copied() { + if let Some((tick, class)) = prev { + assert!(t.tick > tick || t.class == class, "a forecast or a re-read firmed the class: {tick}->{:?} {:?}->{:?}", t.tick, class, t.class); + } + prev = Some((t.tick, t.class)); + } + // The network's copy carries the estimate as it was, with its measurement's age; passing + // it on adds nothing (the receiver never measures: own_tick stays 0). + if let Some(t) = sim.sams[n].track(id).copied() { + relayed += 1; + assert_eq!(t.own_tick, 0); + let freshest = sim.sams.iter().filter(|s| s.id != sim.sams[n].id).filter_map(|s| s.track(id)).max_by_key(|t| t.tick); + assert_eq!(Some(t.class), freshest.map(|f| f.class), "a relay altered the estimate"); + } + } + assert!(relayed > 100, "the network never passed the track ({relayed})"); + assert!(prev.is_some_and(|(_, c)| c.class().is_some()), "the source never classified the contact"); +} diff --git a/airdef-mod/src/sim/sight.rs b/airdef-mod/src/sim/sight.rs index 2065678..036768b 100644 --- a/airdef-mod/src/sim/sight.rs +++ b/airdef-mod/src/sim/sight.rs @@ -8,12 +8,15 @@ //! (a period by the kind of radar; an electronic one also revisits what it holds //! more often), a target is measured when the beam passes it, with a chance that //! falls with range and size, and the measurement is kept as a *track*: where it -//! was and how fast it went then, and when. Between measurements the track is +//! was measured, how fast it then seemed to go (from the measured places, never +//! the target's own figures), and when. Between measurements the track is //! carried on by that velocity (a forecast, shown as one), and after three missed //! scans it is dropped. A fire-control lock on a target the system is engaging is //! a dedicated channel: it measures every tick while the target is in reach and in -//! sight. The network passes tracks with the age of their measurement; relaying -//! makes none of them fresher. +//! sight. The track also carries what the measurements say of the contact's class, +//! the estimate growing only on real measurements: a forecast, a relayed copy adds +//! nothing to it. The network passes tracks with the age of their measurement; +//! relaying makes none of them fresher. use super::*; /// Rays round a radar, and blocks between the land's samples along them. @@ -243,12 +246,17 @@ impl Ident { } /// What a system knows of one target: the last measurement, not the target itself. +/// +/// The track never carries the target's type or its true velocity (#133): `class` is what the +/// radars inferred from the measurements so far, `vel` the speed those measurements showed — +/// none from the first blip, then the change of the measured places between real measurements, +/// smoothed a little. The forecast and the guns live with that. #[derive(Clone, Copy, Debug)] pub struct Track { pub id: u32, - /// What the radar made of it when it measured (the class the picture shows). - pub kind: DroneKind, - /// Where it was and how it went when last measured (blocks, blocks a tick). + /// What the radars make of it from the measurements (never the target's own type). + pub class: ClassEst, + /// Where it was measured and how fast it seemed to go then (blocks, blocks a tick). pub pos: DVec3, pub vel: DVec3, /// When that was, and when this system's own radar last measured it (0: never, the network's only). @@ -448,15 +456,29 @@ impl Sim { } let sigma = if locked { 0.3 } else if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement { 0.45 + dist * 0.002 } else { 0.8 + dist * 0.004 }; let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * 0.5, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma; + let measured = d.pos + noise; + let hits = held.map_or(1, |t| t.hits.saturating_add(1)); + // What this measurement says of the contact's class and speed, from the measured + // places alone: the first blip gives neither; a later one, the change of place over + // the ticks since the last real measurement (not a forecast's), smoothed into what + // the track held so the class does not flap on one noisy pair (#133). + let (vel, class) = match held { + Some(p) if p.tick < now => { + let seen = (measured - p.pos) / (now - p.tick) as f64; + let vel = if p.hits <= 1 { seen } else { p.vel + (seen - p.vel) / f64::from(p.hits.min(4)) }; + (vel, p.class.step(hits, vel.length())) + } + _ => (DVec3::ZERO, ClassEst::Unknown), + }; fresh.push(Track { id: d.id, - kind: d.kind, - pos: d.pos + noise, - vel: d.vel, + class, + pos: measured, + vel, tick: now, own_tick: now, ttl, - hits: held.map_or(1, |t| t.hits.saturating_add(1)), + hits, locked, }); } @@ -520,8 +542,10 @@ impl Sim { let mut tracks: Vec = if unaided { self.drones .iter() + // No system is deployed: no estimation happens, the fallback is the sky as it is + // (the screens have always had it), with the figures a system would show. .filter(|d| d.alive()) - .map(|d| Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 1, hits: 3, locked: false }) + .map(|d| Track { id: d.id, class: ClassEst::Firm(d.kind.spec().class), pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 1, hits: 3, locked: false }) .collect() } else { self.picture().into_values().collect() @@ -612,3 +636,28 @@ mod low_view_tests { assert!(seen > 0 && tint.as_millis() < 100, "{tint:?}"); } } + +#[cfg(test)] +mod relay_tests { + use super::*; + + /// A relayed measurement: its class and hits arrive as they were, the receiver's own age is + /// kept, and passing the same message again adds nothing (#133). + #[test] + fn a_repeated_relay_adds_no_confidence_and_stays_foreign() { + let ours = Track { id: 7, class: ClassEst::Unknown, pos: DVec3::new(0.0, 100.0, 0.0), vel: DVec3::ZERO, tick: 90, own_tick: 90, ttl: 400, hits: 1, locked: false }; + let relay = Track { id: 7, class: ClassEst::Probable(Class::Drone), pos: DVec3::new(0.0, 100.0, -10.0), vel: DVec3::X, tick: 100, own_tick: 0, ttl: 400, hits: 2, locked: false }; + let mut tracks = vec![ours]; + let mut index: HashMap = HashMap::from([(7, 0)]); + merge(&mut tracks, &mut index, relay); + assert_eq!(tracks[0].own_tick, 90, "a relayed track is not the receiver's own measurement"); + for _ in 0..5 { + merge(&mut tracks, &mut index, relay); + } + assert_eq!(tracks.len(), 1, "a relay of a held measurement is one track"); + assert_eq!(tracks[0].hits, 2, "a repeated relay added confidence"); + assert_eq!(tracks[0].class, ClassEst::Probable(Class::Drone), "a relay altered the estimate"); + assert_eq!(tracks[0].tick, 100, "a relay refreshed the measurement"); + assert_eq!(tracks[0].own_tick, 90, "a relay became the receiver's own"); + } +} diff --git a/airdef-mod/src/sim/strike.rs b/airdef-mod/src/sim/strike.rs index a96ac87..5380377 100644 --- a/airdef-mod/src/sim/strike.rs +++ b/airdef-mod/src/sim/strike.rs @@ -1083,7 +1083,7 @@ mod tests { sim.drones.push(d); sim.tick = hidden_launch_tick; sim.scout_launch(drone, id, DroneKind::Shahed, DVec3::new(hidden_x, 70.0, 700.0)); - let track = sight::Track { id: drone, kind: DroneKind::Shahed, pos: DVec3::new(0.0, 100.0, 1000.0), vel: -DVec3::Z * 5.0, tick: 100, own_tick: 100, ttl: 100, hits: 3, locked: false }; + let track = sight::Track { id: drone, class: ClassEst::Firm(Class::Drone), pos: DVec3::new(0.0, 100.0, 1000.0), vel: -DVec3::Z * 5.0, tick: 100, own_tick: 100, ttl: 100, hits: 3, locked: false }; sim.sams[0].tracks.push(track); sim.tick = 100; sim.step_strikes(&mut ground, None, &mut out); @@ -1429,10 +1429,14 @@ mod tests { fn an_off_map_site_is_found_by_bearing_and_a_strike_there_only_ends_its_launches() { let mut sim = Sim::new(5); - // Two radars apart watch the start of an off-map site's drones. + // Two radars apart watch the start of an off-map site's drones. They hold fire: this test + // is about the sighting and the strike, not about intercepting drones flown at 2 blocks a + // tick (which measure as cruise missiles, #133, and would be engaged on the roles). for x in [-150.0, 150.0] { let id = sim.id(); - sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0)); + let mut sam = Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0); + sam.roles = 0; + sim.sams.push(sam); } let id = sim.sites.add(LaunchSite { id: 0, diff --git a/airdef-mod/src/sim/why.rs b/airdef-mod/src/sim/why.rs index c34e9db..619713f 100644 --- a/airdef-mod/src/sim/why.rs +++ b/airdef-mod/src/sim/why.rs @@ -14,14 +14,20 @@ pub(super) const UNSEEN: u8 = 4; /// Its track is older than a launcher fires on. pub(super) const STALE: u8 = 8; +/// Why a drone is not a candidate for a system at all. The role is checked against the track's +/// *estimated* class, never the target's own (#133): an unidentified track is not blocked — the +/// explicit policy is that it stays a candidate under the general rules (a system with no roles +/// is holding its fire: nothing is a candidate for it) — and a probable or firm class out of the +/// roles is, with the reason named in `why`. pub(super) fn target_blocks(roles: u8, track: Option<&Track>, now: u64, d: &Drone) -> u8 { (if d.alive() { 0 } else { DEAD }) - | (if roles & d.kind.spec().class.bit() != 0 { 0 } else { ROLE }) + | (if track.is_some_and(|t| t.class.in_roles(roles)) { 0 } else { ROLE }) | (if track.is_some() { 0 } else { UNSEEN }) | (if track.is_some_and(|t| t.age(now) > sight::MISSILE_AGE) { STALE } else { 0 }) } -/// Alive, of a class the system engages, and on its picture (own radar or the network's), fresh enough. +/// Alive, of a class the system engages (or not yet classified), and on its picture (own radar +/// or the network's), fresh enough. pub(super) fn allowed(roles: u8, track: &Track, now: u64, d: &Drone) -> bool { target_blocks(roles, Some(track), now, d) == 0 } @@ -50,14 +56,15 @@ pub(super) fn arrival(d: &Drone) -> f64 { d.pos.distance(d.target) / d.vel.length().max(0.1) } -/// Shoot-look-shoot that grows with urgency: ballistic missiles get a pair, anything else one; a target +/// Shoot-look-shoot that grows with urgency: a ballistic missile gets a pair, anything else one; a target /// this close to its aim (ticks) has one more interceptor allowed on it at once, closer still another, and in the last seconds a fourth. +/// The class is the track's estimate (#133): an unidentified contact is treated as not ballistic. pub(super) const URGENT: f64 = 240.0; pub(super) const DESPERATE: f64 = 110.0; pub(super) const FINAL: f64 = 60.0; -pub(super) fn needed(d: &Drone) -> u32 { - let base = if d.kind.spec().class == Class::Ballistic { 2 } else { 1 }; +pub(super) fn needed(d: &Drone, class: ClassEst) -> u32 { + let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 }; let t = arrival(d); base + u32::from(t < URGENT) + u32::from(t < DESPERATE) + u32::from(t < FINAL) } @@ -68,12 +75,14 @@ pub(super) const SHY_TICKS: u64 = 120; // ---------------------------------------------------------------- the grounds to launch on -/// Last chance (`/airdef lastchance`): a target of a class the system does not engage that is about to -/// hit, with nobody's interceptor on it, is shot at anyway; a system told to hold fire (no roles) keeps to it. +/// Last chance (`/airdef lastchance`): a track of a *known* class the system does not engage that +/// is about to hit, with nobody's interceptor on it, is shot at anyway; a system told to hold fire +/// (no roles) keeps to it. An unidentified track is no last-chance case: it is already a candidate +/// under the general rules (#133). pub(super) const LAST_CHANCE_TICKS: f64 = 200.0; -pub(super) fn last_chance(on: bool, roles: u8, d: &Drone, claimed: u32) -> bool { - on && roles != 0 && roles & d.kind.spec().class.bit() == 0 && claimed == 0 && arrival(d) < LAST_CHANCE_TICKS +pub(super) fn last_chance(on: bool, roles: u8, class: ClassEst, d: &Drone, claimed: u32) -> bool { + on && roles != 0 && !class.in_roles(roles) && claimed == 0 && arrival(d) < LAST_CHANCE_TICKS } /// The big radar's cue (heavy systems only): they may fire out to `FAR_K` × max at a target the radar holds. @@ -142,20 +151,20 @@ pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Dro if blocks & !ROLE != 0 { return None; } - let est = track.est(now); - let reach = reach_blocks(load.min, load.max, k, sam.pos, est); + let est = track.class; + let reach = reach_blocks(load.min, load.max, k, sam.pos, track.est(now)); if blocks & ROLE == 0 { // The doctrine (sector, protected objects, reserve) rules over the role's shots and the long ones; the last chance is past it. - if sam.doctrine.area_blocks(sam.pos, track, now) | sam.doctrine.reserve_blocks(sam.missiles, d) != 0 { + if sam.doctrine.area_blocks(sam.pos, track, now) | sam.doctrine.reserve_blocks(sam.missiles, d, est) != 0 { return None; } if reach == 0 { return Some(Basis::Role); } - let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 0; + let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, track.est(now)) == 0; return (far && far_blocks(opts.far_shots, sam, load, cued, role_in_reach) == 0).then_some(Basis::FarShot); } - (reach == 0 && last_chance(opts.last_chance, sam.roles, d, claimed)).then_some(Basis::LastChance) + (reach == 0 && last_chance(opts.last_chance, sam.roles, est, d, claimed)).then_some(Basis::LastChance) } /// The kill chance of an interceptor that met its target `dist` from the launcher whose reach is `max`: @@ -352,7 +361,10 @@ impl Sim { let subject = sam.target.or(sam.gun_target).and_then(drone_at).or_else(|| { self.drones .iter() - .filter(|d| d.alive() && (sam.roles & d.kind.spec().class.bit() != 0 || last_chance(self.last_chance, sam.roles, d, claimed(d, &missile_on, sam.target)))) + // Of what the system's picture holds: a track of its roles' classes (or not yet + // classified), or a known out-of-role one about to hit (the last chance) — never + // the target's own class (#133). + .filter(|d| d.alive() && (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles)) || last_chance(self.last_chance, sam.roles, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target)))) .max_by(|a, b| { // What the doctrine lets the system shoot at comes first; then the most threatening. let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, self.tick) == 0); @@ -360,44 +372,61 @@ impl Sim { }) }); let Some(t) = subject else { - v.push(check(false, format!("нет целей классов [{}]", roles_text(sam.roles)))); + // Nothing to look at: either the sky holds nothing for this system, or it holds only + // tracks whose estimated class is out of the roles — the reasons differ and are named (#133). + let held = self.drones.iter().any(|d| d.alive() && sam.seen.contains(&d.id)); + // No roles is holding fire: a reason of its own, not an empty class filter. + let text = if sam.roles == 0 { + "роль: система не ведёт огонь (роли не заданы) — ни одна цель не выбирается".to_string() + } else if held { + format!("цели на картине есть, но не в ролях [{}] (классы по оценке)", roles_text(sam.roles)) + } else { + format!("нет целей классов [{}]", roles_text(sam.roles)) + }; + v.push(check(false, text)); return v; }; let held = sam.target == Some(t.id) || sam.gun_target == Some(t.id); let dist = sam.track(t.id).map_or(t.pos, |tr| tr.est(self.tick)).distance(sam.pos); + let track = sam.track(t.id); v.push(check( true, - format!("цель: {} {}, {}", t.kind.spec().name, if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)), + format!("цель: {} {}, {}", track.map_or_else(|| ClassEst::Unknown.name(), |tr| tr.class.name()), if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)), )); - let track = sam.track(t.id); + let est = track.map_or(ClassEst::Unknown, |tr| tr.class); let blocks = target_blocks(sam.roles, track, now, t); // Where the system believes the target is: its track's forecast (the true place only when it has no track). - let est = track.map_or(t.pos, |tr| tr.est(now)); + let est_at = track.map_or(t.pos, |tr| tr.est(now)); let evel = track.map_or(t.vel, |tr| tr.vel); let first_claim = claimed(t, &missile_on, sam.target); - let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, t, first_claim); + let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, t, first_claim); let role_text = if blocks & ROLE == 0 { - format!("роль: {} в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles)) + match est { + ClassEst::Unknown => "роль: тип не определён — цель ведётся по общим правилам, классовые ограничения не применяются".to_string(), + _ => format!("роль: {} в ролях [{}]", est.name(), roles_text(sam.roles)), + } } else if chance { format!( "последний шанс: {} не в ролях [{}], но до цели {:.0} с, перехватчиков на ней нет", - t.kind.spec().class.name(), + est.name(), roles_text(sam.roles), arrival(t) / 20.0 ) + } else if sam.roles == 0 { + "роль: система не ведёт огонь (роли не заданы) — цель не выбирается".to_string() } else { - format!("роль: {} не в ролях [{}]", t.kind.spec().class.name(), roles_text(sam.roles)) + format!("роль: {} не в ролях [{}]", est.name(), roles_text(sam.roles)) }; v.push(check(blocks & ROLE == 0 || chance, role_text)); // The doctrine: which of its settings let the shot through or stopped it. The last chance is past them. let doc = &sam.doctrine; let area = track.map_or(0, |tr| doc.area_blocks(sam.pos, tr, now)); - let held_back = if spec.missile.is_some() { doc.reserve_blocks(sam.missiles, t) } else { 0 }; + let held_back = if spec.missile.is_some() { doc.reserve_blocks(sam.missiles, t, est) } else { 0 }; if !doc.is_default() { v.push(check(true, format!("доктрина: {}", doc.text(&self.targets)))); } if area & doctrine::OUT_SECTOR != 0 { - let bearing = heading_of(est - sam.pos).to_degrees().rem_euclid(360.0); + let bearing = heading_of(est_at - sam.pos).to_degrees().rem_euclid(360.0); v.push(check(chance, format!("вне сектора {}: цель на {bearing:.0}°{}", doc.sector_text(), if chance { " — последний шанс сильнее" } else { "" }))); } else if doc.sector.is_some() { v.push(check(true, format!("в секторе {}", doc.sector_text()))); @@ -418,7 +447,7 @@ impl Sim { let age = tr.age(now) as f64 / 20.0; let lock = if tr.own_within(now, sight::GUN_AGE) && tr.locked { ", захват" } else { "" }; let how = if tr.forecast(now) { format!("прогноз ±{:.0} м", tr.uncertainty(now)) } else { "измерение".to_string() }; - format!("трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}", tr.ident().name(), if blocks & STALE != 0 { "устарел для пуска" } else { "годен для пуска" }) + format!("трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}, {}", tr.ident().name(), tr.class.name(), if blocks & STALE != 0 { "устарел для пуска" } else { "годен для пуска" }) } _ => "не обнаружена ни своей РЛС, ни сетью".to_string(), }; @@ -456,19 +485,19 @@ impl Sim { v.push(check(sam.reloading == 0 && !sam.empty && (sam.missiles > 0 || sam.bursts > 0), format!("{rounds}— {supply}"))); let mount = sam.mount().0; let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell); - let (_, want_yaw, want_pitch) = aim_wants(mount, est, evel, lead_speed); + let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, evel, lead_speed); let err = aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch); let vertical = spec.family == Family::Vertical; let mut fires = false; if let Some(load) = &spec.missile { - let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est); + let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est_at); // Beyond the normal reach, a heavy system may fire on a big radar's cue. let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect(); let cued = radar_cue(sam, &radars, t.id, now); let role_in_reach = self.drones.iter().any(|o| { - sam.track(o.id).is_some_and(|tr| allowed(sam.roles, tr, now, o) && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o)) + sam.track(o.id).is_some_and(|tr| allowed(sam.roles, tr, now, o) && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o, tr.class) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o, tr.class)) }); - let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est) == 0; + let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0; let far_ok = far && track.is_some_and(|tr| basis(sam, load, tr, t, now, 0, 1.0, Opts { last_chance: self.last_chance, far_shots: self.far_shots }, cued, role_in_reach) == Some(Basis::FarShot)); if far { let fb = far_blocks(self.far_shots, sam, load, cued, role_in_reach); @@ -487,7 +516,7 @@ impl Sim { v.push(check(far_ok, if far_ok { format!("дальний пуск по РЛС: цель на {} дальше обычных {}", super::distance(dist), super::distance(load.max)) } else { format!("дальний пуск по РЛС не разрешён: {}", no.join(", ")) })); } let free = first_claim; - let need = sam.doctrine.needed(t); + let need = sam.doctrine.needed(t, est); v.push(check(free < need, format!("цель занята перехватчиками: {free} из {need} (залп {}){}", doc.salvo.name(), if free < need { "" } else { " — другие уже на ней" }))); let mb = missile_blocks(sam); let mut why = Vec::new(); @@ -504,7 +533,7 @@ impl Sim { why.push("пусковая отказала".to_string()); } v.push(check(mb == 0, if mb == 0 { "пусковая готова".to_string() } else { format!("пусковая не готова: {}", why.join(", ")) })); - let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(est), t.id, t.id, err); + let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(est_at), t.id, t.id, err); let turn = if vertical { "вертикальный старт" } else { "доворот" }; v.push(check(aligned, format!("{turn}: ошибка наведения {:.0}°{}", err.to_degrees(), if aligned { "" } else { " — ещё доворачивается" }))); // The land: the verdict the launch decision gave this target (`terrain::launch_blocks`) a moment ago. @@ -535,7 +564,7 @@ impl Sim { if cand { "" } else { " — вне сопровождения (нужна своя РЛС)" } ), )); - let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est), gun.range, now); + let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est_at), gun.range, now); let mut why = Vec::new(); for (bit, name) in [ (AIM_ERROR, format!("орудие ещё наводится ({:.0}°)", err.to_degrees())), @@ -581,7 +610,7 @@ mod tests { } let w = sim.why(0); assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); - assert!(w.iter().any(|c| c.legacy_text().contains("нет целей классов"))); + assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); sim.sams[0].roles = 0xFF; assert!(sim.why(0).iter().any(|c| c.legacy_text().starts_with("роль"))); } @@ -612,23 +641,44 @@ mod tests { sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -80.0 - blocks), DVec3::Z, DVec3::new(0.0, 70.0, -80.0)); } + /// The system's picture holds the drone as a contact whose class is already estimated — as if + /// the network had passed enough measurements (#133). The sim's own radar then keeps the + /// estimate up from its measurements alone. + fn seed_classified(sim: &mut Sim, class: ClassEst) { + let now = sim.tick; + let d = sim.drones[0].clone(); + sim.sams[0].tracks.retain(|t| t.id != d.id); + sim.sams[0].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }); + } + #[test] fn last_chance_fires_at_a_class_out_of_roles_only_when_it_is_about_to_hit() { // The S-400 does not engage drones by default. assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0); let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); shahed_at(&mut sim, 60.0); + // Classified as a drone by the picture: the roles block it, the last chance is what fires. + seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); let at = until_fired(&mut sim, &mut ground, &land, &mut out, 140).expect("the S-400 never fired on a Shahed about to hit"); assert!(at < LAST_CHANCE_TICKS, "fired with {at:.0} ticks to go"); - // The diagnostic names why: the last chance. + // The diagnostic names why: first the role block, then the last chance. let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); shahed_at(&mut sim, 100.0); - for _ in 0..30 { + seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); + let mut saw_block = false; + let mut saw_chance = false; + for _ in 0..220 { serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); + let w = sim.why(0); + saw_block |= w.iter().any(|c| c.legacy_text().contains("не в ролях")); + saw_chance |= w.iter().any(|c| c.legacy_text().starts_with("последний шанс")); + if saw_chance || sim.sams[0].fired > 0 { + break; + } } - let w = sim.why(0); - assert!(w.iter().any(|c| c.ok && c.legacy_text().starts_with("последний шанс")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); + assert!(saw_block, "the role block was never named"); + assert!(saw_chance, "the last chance was never named"); } #[test] @@ -636,10 +686,12 @@ mod tests { let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); // In plain view 120 blocks off, but flying away from its aim, 480 blocks (800 ticks) ahead. sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -120.0), DVec3::NEG_Z, DVec3::new(0.0, 70.0, -600.0)); + // Classified as a drone: out of the S-400's roles, and not about to hit: nothing fires. + seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a Shahed far from its aim"); let w = sim.why(0); - // Still named as the role block it was: no target of its classes. - assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.legacy_text().contains("нет целей классов")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); + // Still named as what it was: a contact on the picture, out of the roles. + assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс"))); } @@ -650,6 +702,7 @@ mod tests { sim.last_chance = !off; sim.sams[0].roles = roles; shahed_at(&mut sim, 60.0); + seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 140).is_none(), "fired with last chance off={off}, roles {roles}"); } } @@ -658,12 +711,109 @@ mod tests { fn last_chance_leaves_a_target_that_already_has_an_interceptor_on_it() { let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); shahed_at(&mut sim, 60.0); + seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); // Another system's interceptor is on it. let id = sim.drones[0].id; sim.drones[0].engaged = 1; assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 40).is_none(), "fired at {id} that is claimed"); } + #[test] + fn a_probable_class_out_of_roles_is_blocked_and_named() { + // The S-400 does not engage drones. A track only *probably* a drone is already a block: + // the guess is a class, not an unidentified contact. + assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0); + let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); + sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -120.0), DVec3::NEG_Z, DVec3::new(0.0, 70.0, -600.0)); + seed_classified(&mut sim, ClassEst::Probable(Class::Drone)); + // A target taken before the class was estimated: the diagnostic names the probable class. + sim.sams[0].target = Some(sim.drones[0].id); + let want = format!("роль: вероятно дрон не в ролях [{}]", roles_text(SamKind::S400.spec().roles)); + let w = sim.why(0); + assert!(w.iter().any(|c| c.legacy_text() == want), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); + assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс"))); + // And nothing fires at it while it is far from its aim. + assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a probable drone far from its aim"); + } + + #[test] + fn hold_fire_blocks_an_unclassified_contact_and_says_so() { + // No roles: nothing is a candidate, the unidentified included. Running the sim must not + // turn it into a target. + let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); + sim.sams[0].roles = 0; + shahed_at(&mut sim, 60.0); + seed_classified(&mut sim, ClassEst::Unknown); + assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 200).is_none(), "fired while holding fire"); + let w = sim.why(0); + assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); + assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); + } + + #[test] + fn a_held_unknown_target_on_a_system_holding_fire_is_explained_without_a_panic() { + // The target was taken before the roles were emptied: the diagnostic must name the hold, + // not unwrap a class the estimate does not have. + let (mut sim, _, _, _) = setup(SamKind::S400); + shahed_at(&mut sim, 60.0); + seed_classified(&mut sim, ClassEst::Unknown); + sim.sams[0].target = Some(sim.drones[0].id); + sim.sams[0].roles = 0; + let w = sim.why(0); + assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); + assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); + } + + #[test] + fn roles_read_the_estimate_an_unidentified_track_is_not_blocked() { + // #133: the role filter reads the track's estimated class, never the target's own. While + // the contact is unidentified the S-400 (its roles exclude drones) keeps it as a candidate + // under the general rules — the explicit policy, named in why; once the estimate firms as + // a drone, the block applies and why names that instead. + assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0, "the S-400 does not engage drones"); + let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); + sim.last_chance = false; + shahed_at(&mut sim, 60.0); + let id = sim.drones[0].id; + let roles = sim.sams[0].roles; + let mut saw_open = false; + for _ in 0..300 { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + let Some(t) = sim.sams[0].track(id).copied() else { continue }; + if t.class != ClassEst::Unknown { + break; + } + saw_open = true; + assert_eq!(why::target_blocks(roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "an unidentified contact must not be role-blocked"); + let w = sim.why(0); + assert!(w.iter().any(|c| c.legacy_text().contains("по общим правилам")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); + break; + } + assert!(saw_open, "the contact was never seen unidentified"); + // Classified as a drone, out of the roles: blocked, and the diagnostic says so. + let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); + sim.last_chance = false; + shahed_at(&mut sim, 60.0); + seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); + let id = sim.drones[0].id; + for _ in 0..40 { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + if sim.sams[0].track(id).is_some_and(|t| t.class == ClassEst::Firm(Class::Drone)) { + break; + } + } + let t = *sim.sams[0].track(id).expect("the track"); + assert_ne!(why::target_blocks(sim.sams[0].roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "a classified out-of-role contact must be blocked"); + let w = sim.why(0); + assert!(w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); + // Holding fire (no roles at all): nothing is a candidate, the unidentified either. + let d = sim.drones[0].clone(); + let unknown = Track { id: d.id, class: ClassEst::Unknown, pos: d.pos, vel: DVec3::ZERO, tick: 0, own_tick: 0, ttl: 400, hits: 1, locked: false }; + assert_ne!(why::target_blocks(0, Some(&unknown), 0, &d) & why::ROLE, 0, "with no roles (hold fire) even the unknown is blocked"); + } + /// A Kh101 `dist` from the origin on the far side, at height, coming in along z; a radar beside the system. fn far_setup(radar: bool, dist: f64) -> (Sim, Ground, Land i32>, Out) { let (mut sim, ground, land, out) = setup(SamKind::S400); @@ -682,7 +832,7 @@ mod tests { .drones .iter() .filter(|d| d.alive()) - .map(|d| Track { id: d.id, kind: d.kind, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }) + .map(|d| Track { id: d.id, class: ClassEst::Firm(d.kind.spec().class), pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }) .collect(); for r in sim.sams.iter_mut().filter(|s| s.kind == SamKind::Radar) { for t in &tracks {