Files
airdef/airdef-mod/src/sim/doctrine.rs
T
chexit 858735a4c6 Implement the first full radar-profile slice (#134)
Give the separate radar three real profiles over SamKind::Radar and the
typed catalog variants:

- radar_search: coarse, slow, long-range search plots; no fire authority.
- radar_height: raised mast, local refinement of low plots; no fire authority.
- radar_track: local search, fast revisit, two refined/fire channels.
- radar_multi remains the compatible universal profile, not best everywhere.

Tracks now carry the measuring station, product (search/refine/fire), and
quality (separate from identification), and keep the station's own plot when a
fresher network relay replaces the published position. A relay never refreshes
the measurement or authorizes a launch. Ordinary launches need the battery's
own confirmed fire plot; launcher-only batteries use a supporting radar's own
plot, and the existing heavy far shot keeps its cue-radar exception.

Per-tick refinement/fire work is bounded by profile channels and local search
radius. Off, damage, network and save/replay behavior are preserved: new saves
write the stable profile ID, old role-only lines migrate, and embedded SAM
radars keep their own fire authority. The deploy menu, status lines, map,
monitor, radar scope and /airdef why explain the profile, source, age, quality,
channels and refusal reason.

Models/textures are untouched: all profiles reuse the existing radar
silhouette (the separate art zone remains for its owner).

Tests: profile single/pair/full scenarios and duplicate station, channels,
relay source/age/quality, Off/damage, save migration, replay, embedded and
Multifunction radars, catalog/generator checks, airdef-mod suites, core lib
(non-balance on one thread; the four active balance tests in release) and core
scenarios.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:11:12 +03:00

279 lines
12 KiB
Rust

//! Fire doctrine (#47): what a system is told about its job beyond the roles. Protected objects (it fires
//! only at what threatens them), a sector of responsibility, a reserve of missiles held back for what
//! matters, and how many interceptors it asks for on one target. The predicates are shared by `step_sams`
//! (through `why::basis`) and the diagnostic; the default doctrine blocks nothing and changes nothing.
//! Everything is judged on the system's track (its forecast), never on the drone's true place.
use super::*;
/// How many interceptors a system asks for on one target: the base shoot-look-shoot only, as now, or one more.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Salvo {
Economy,
#[default]
Normal,
Heavy,
}
impl Salvo {
pub fn name(self) -> &'static str {
match self {
Salvo::Economy => "экономный",
Salvo::Normal => "обычный",
Salvo::Heavy => "усиленный",
}
}
pub fn key(self) -> &'static str {
match self {
Salvo::Economy => "eco",
Salvo::Normal => "normal",
Salvo::Heavy => "heavy",
}
}
pub fn from_key(s: &str) -> Option<Salvo> {
[Salvo::Economy, Salvo::Normal, Salvo::Heavy].into_iter().find(|v| v.key() == s)
}
pub fn next(self) -> Salvo {
match self {
Salvo::Economy => Salvo::Normal,
Salvo::Normal => Salvo::Heavy,
Salvo::Heavy => Salvo::Economy,
}
}
}
/// A system's doctrine. `Default` is the sandbox: no guards, no sector, no reserve, the usual salvo.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Doctrine {
/// Protected objects (their places): when any, the system fires only at what threatens one of them.
pub guards: Vec<DVec3>,
/// Sector of responsibility: centre (a yaw as `heading_of`, radians) and half-width.
pub sector: Option<(f64, f64)>,
/// Missiles held back: below this many, only what matters is shot at.
pub reserve: u32,
pub salvo: Salvo,
}
/// Where a track counts as threatening an object: within this many blocks of it, or flying at it.
pub const GUARD_R: f64 = 120.0;
/// Most missiles one can reserve.
pub const MAX_RESERVE: u32 = 64;
pub(super) const OUT_SECTOR: u8 = 1;
pub(super) const NO_THREAT: u8 = 2;
pub(super) const RESERVE: u8 = 4;
impl Doctrine {
pub fn is_default(&self) -> bool {
*self == Doctrine::default()
}
/// Whether the track is within the sector (judged from the system's place).
pub fn in_sector(&self, pos: DVec3, at: DVec3) -> bool {
self.sector.is_none_or(|(centre, half)| {
let to = at - pos;
to.x.hypot(to.z) < 30.0 || angle_diff(centre, heading_of(to)).abs() <= half
})
}
/// The first protected object the track threatens (its index in `guards`): near it, or flying towards it.
pub fn threatens(&self, track: &Track, now: u64) -> Option<usize> {
let at = track.est(now);
let slack = GUARD_R + track.uncertainty(now);
self.guards.iter().position(|g| {
let (dx, dz) = (g.x - at.x, g.z - at.z);
let near = dx.hypot(dz);
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.
speed > 1e-3 && vx * dx + vz * dz > 0.0 && (vx * dz - vz * dx).abs() / speed <= slack
})
}
/// Why the area (sector, protected objects) rules the track out; 0 is a pass.
pub fn area_blocks(&self, pos: DVec3, track: &Track, now: u64) -> u8 {
(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 (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, 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, 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, class),
Salvo::Heavy => why::needed(d, class) + 1,
}
}
/// The sector in words (`90±45°`); degrees on the same scale as `/airdef doctrine ... sector`.
pub fn sector_text(&self) -> String {
match self.sector {
Some((c, h)) => format!("{:.0}±{:.0}°", c.to_degrees().rem_euclid(360.0), h.to_degrees()),
None => "круговой".to_string(),
}
}
/// The doctrine as the player reads it, empty for the default.
pub fn text(&self, targets: &[DVec3]) -> String {
if self.is_default() {
return "обычная (без ограничений)".to_string();
}
let guards = if self.guards.is_empty() {
"нет".to_string()
} else {
self.guards.iter().map(|g| object_name(targets, *g)).collect::<Vec<_>>().join(", ")
};
format!("охрана: {guards}; сектор: {}; резерв: {}; залп: {}", self.sector_text(), self.reserve, self.salvo.name())
}
/// One line of the save: `salvo reserve sector-centre sector-half guards x y z ...` (`-` for no sector).
pub fn save_text(&self) -> String {
let sector = self.sector.map_or("- -".to_string(), |(c, h)| format!("{c} {h}"));
let mut s = format!("{} {} {sector} {}", self.salvo.key(), self.reserve, self.guards.len());
for g in &self.guards {
s += &format!(" {} {} {}", g.x, g.y, g.z);
}
s
}
}
/// An object by number in the world's list ("объект №2"), else by place.
pub fn object_name(targets: &[DVec3], g: DVec3) -> String {
match targets.iter().position(|t| t.distance(g) < 16.0) {
Some(i) => format!("объект №{}", i + 1),
None => format!("точка {:.0} {:.0}", g.x, g.z),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn track(pos: DVec3, vel: DVec3) -> Track {
Track {
id: 1,
class: ClassEst::Unknown,
pos,
vel,
tick: 0,
own_tick: 0,
source: 0,
product: battery::Measure::Search,
quality: 40,
own_product: battery::Measure::Search,
own_quality: 0,
ttl: 100,
hits: 3,
locked: false,
}
}
#[test]
fn the_default_doctrine_blocks_nothing() {
let d = Doctrine::default();
let t = track(DVec3::new(500.0, 100.0, 0.0), DVec3::ZERO);
assert_eq!(d.area_blocks(DVec3::ZERO, &t, 0), 0);
assert!(d.is_default());
assert_eq!(Doctrine::default().save_text(), "normal 0 - - 0");
}
#[test]
fn a_sector_and_guards_rule_targets_out_by_their_tracks() {
let mut d = Doctrine::default();
// North is yaw 0 (towards -z): a sector of 45 degrees either side of north.
d.sector = Some((0.0, 45f64.to_radians()));
let north = track(DVec3::new(0.0, 100.0, -800.0), DVec3::ZERO);
let south = track(DVec3::new(0.0, 100.0, 800.0), DVec3::ZERO);
assert_eq!(d.area_blocks(DVec3::ZERO, &north, 0), 0);
assert_eq!(d.area_blocks(DVec3::ZERO, &south, 0), OUT_SECTOR);
d.sector = None;
d.guards = vec![DVec3::new(1000.0, 70.0, 0.0)];
// Flying at the object from afar threatens it; flying past, or away, doesn't.
let at = track(DVec3::new(-2000.0, 100.0, 10.0), DVec3::new(2.0, 0.0, 0.0));
let past = track(DVec3::new(-2000.0, 100.0, 900.0), DVec3::new(2.0, 0.0, 0.0));
let away = track(DVec3::new(-2000.0, 100.0, 0.0), DVec3::new(-2.0, 0.0, 0.0));
assert_eq!(d.area_blocks(DVec3::ZERO, &at, 0), 0);
assert_eq!(d.area_blocks(DVec3::ZERO, &past, 0), NO_THREAT);
assert_eq!(d.area_blocks(DVec3::ZERO, &away, 0), NO_THREAT);
}
use super::sites::testland::{Land, serve};
/// One Patriot against one Shahed flying in from the north at its aim, the doctrine set before the raid:
/// the missiles it fired, the Shahed's ticks to its aim at the first launch, and the `why` lines at the end.
fn fire(doc: Doctrine) -> (u32, Option<f64>, Vec<String>) {
let mut sim = Sim::new(5);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 70.0, 0.0), 0.0));
sim.sams[0].roles = 0xFF;
sim.sams[0].doctrine = doc;
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -600.0), DVec3::Z, DVec3::new(0.0, 70.0, -80.0));
let (mut ground, land, mut out) = (Ground::default(), Land(|_, _| 64), Out::default());
let mut first = None;
let mut lines: Vec<String> = Vec::new();
for _ in 0..900 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
if first.is_none() && sim.sams[0].fired > 0 {
first = sim.drones.first().map(why::arrival);
}
if sim.drones.iter().all(|d| !d.alive()) {
break;
}
// The explanation while the target is in the sky: all the lines it gave then.
if sim.tick % 10 == 0 {
lines.extend(sim.why(0).into_iter().map(|c| c.legacy_text().to_owned()));
}
}
(sim.sams[0].fired, first, lines)
}
// #47: the defaults fire as before; each setting changes the decision and `why` names it
#[test]
fn each_setting_changes_the_shot_and_why_says_which() {
let (base, first, w) = fire(Doctrine::default());
assert!(base > 0, "the baseline never fired: {w:?}");
let first = first.unwrap();
assert!(first > why::URGENT, "the baseline fires late: {first}");
let has = |text: &[String], what: &str| text.iter().any(|l| l.contains(what));
// The raid comes from the north (yaw 0): a sector round north holds it, one round south does not.
let sector = |c: f64| Doctrine { sector: Some((f64::to_radians(c), f64::to_radians(40.0))), ..Default::default() };
assert_eq!(fire(sector(0.0)).0, base, "a sector that holds the raid changes nothing");
let (n, _, why) = fire(sector(180.0));
assert_eq!(n, 0);
assert!(has(&why, "вне сектора"), "{why:?}");
// A reserve above the magazine holds the shot until the target is urgent.
let (n, late, _) = fire(Doctrine { reserve: 64, ..Default::default() });
assert!(n > 0 && late.unwrap() < why::URGENT, "{n} {late:?}");
// An object far off the raid's line is no one's to guard here; the one it flies at is.
let (n, _, why) = fire(Doctrine { guards: vec![DVec3::new(0.0, 70.0, 50000.0)], ..Default::default() });
assert_eq!(n, 0);
assert!(has(&why, "не угрожает"), "{why:?}");
let (n, _, why) = fire(Doctrine { guards: vec![DVec3::new(0.0, 70.0, -80.0)], ..Default::default() });
assert_eq!(n, base);
assert!(has(&why, "прикрывает"), "{why:?}");
// Economical asks for no more interceptors than the usual, heavy no fewer.
let (eco, _, _) = fire(Doctrine { salvo: Salvo::Economy, ..Default::default() });
let (heavy, _, _) = fire(Doctrine { salvo: Salvo::Heavy, ..Default::default() });
assert!(eco <= base && base <= heavy, "{eco} {base} {heavy}");
}
}