Files
airdef/airdef-mod/src/sim/recon.rs
T
chexit 433e1500e2
build / mod (push) Failing after 37s
Do not treat a cooling jammer as an active emitter (#139)
Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:20:46 +03:00

1369 lines
64 KiB
Rust

//! Reconnaissance sorties and the enemy's partial picture of the defences (#135).
//!
//! A smart raid may send a few unarmed aircraft ahead of its strike. They fly through
//! game zones round the marked objectives and look while they are there: a unit inside
//! a zone is seen as an *area*, a coarse category, the channel that showed it and the
//! tick it was seen. Nothing of the unit's live state — its exact place, kind, health,
//! magazine, radar role or data link — enters the picture. A look is radioed home only
//! after `REPORT_DELAY` ticks and only if the aircraft is still flying: a sortie lost
//! before its report leaves no mark, while marks already reported stay.
//!
//! What is reported is memory, not truth. A hidden move, a switch-off, a re-role or a
//! kill does not rewrite a mark; only a later look can. A repeated report of the same
//! observation does not raise its confidence: confidence is the mark's age alone, and a
//! second independent look may refine the area and (for a radar) its role. A wreck a look
//! flies over is not a lead: a fresh one makes no mark, and one the picture already held is
//! radioed home as destroyed and its mark leaves the picture (#139).
use super::*;
use std::collections::BTreeMap;
/// A zone a recon aircraft flies through. Its radius is the best it can say about where
/// a unit it saw there is.
pub const ZONE_RADIUS: f64 = 220.0;
/// How many zones one sortie may look through, and how many sorties may be out at once.
pub const ZONES_MAX: usize = 4;
pub const SORTIES_MAX: usize = 3;
/// Ticks from a look to its report: the aircraft must still be flying then.
pub const REPORT_DELAY: u64 = 90;
/// Ticks a sortie may stay out; past this its unreported look is lost.
pub const SORTIE_TTL: u64 = 5000;
/// A second independent look this much later may refine the mark. A duplicate report of
/// the same observation never does.
pub const REFINE_GAP: u64 = 600;
/// The area a first report leaves, and the smaller one a refined report leaves. Neither
/// is the unit's place: the reported point is a cell centre, jittered away from it.
pub const COARSE_AREA: f64 = 120.0;
pub const REFINED_AREA: f64 = 48.0;
/// How long a mark is remembered (five minutes, as a disclosure contact).
pub const MARK_TTL: u64 = 6000;
/// How long a checked empty zone is not worth another look (unless there is nothing else).
pub const REVISIT: u64 = 6000;
/// Synthetic contact ids: the planner never sees a real unit id through a recon mark. The range
/// is its own: it must not overlap the drawn-only effects (`FX_IDS`, 0x2000_0000), the engine
/// keys (0x4000_0000) or the recon aircraft below.
pub const ID_BASE: u32 = 0x1000_0000;
/// One past the last mark id a report may take (space for far more reports than a match holds).
pub const MARK_TOP: u32 = 0x1800_0000;
/// Recon aircraft ids come from their own range: launching the flight must not move the
/// strike's id sequence, and so its tie-breaks and recorded tracks.
pub const DRONE_BASE: u32 = 0x3000_0000;
/// One past the last recon aircraft id a save may hold: the drone parser's own bound (`1 << 30`).
pub const DRONE_TOP: u32 = 0x4000_0000;
/// Contacts and checked zones one save may hold (the section stays bounded).
pub const MAX_MARKS: usize = 512;
pub const MAX_CHECKED: usize = 128;
/// Observations one report may carry, and pending observations a sortie may hold.
pub const MAX_OBSERVED: usize = 64;
pub(super) fn is_mark(id: u32) -> bool {
(ID_BASE..MARK_TOP).contains(&id)
}
/// Whether an id belongs to a recon aircraft (a role of its own, not a strike drone). The
/// player's map and panel read it to mark a tracked aircraft as a recon flight (#135).
pub fn is_drone_id(id: u32) -> bool {
id >= DRONE_BASE
}
/// What a look can tell about a unit's role, in the terms the game already publishes.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Category {
/// A unit was there, nothing more.
Unknown,
Radar,
Launcher,
Gun,
Ew,
Support,
}
impl Category {
pub fn name(self) -> &'static str {
match self {
Self::Unknown => "unknown",
Self::Radar => "radar",
Self::Launcher => "launcher",
Self::Gun => "gun",
Self::Ew => "ew",
Self::Support => "support",
}
}
pub fn from_key(key: &str) -> Option<Self> {
[Self::Unknown, Self::Radar, Self::Launcher, Self::Gun, Self::Ew, Self::Support].into_iter().find(|c| c.name() == key)
}
/// The public role a look at this kind can tell apart, nothing finer.
pub(super) fn of(kind: SamKind) -> Self {
match kind {
SamKind::Radar => Self::Radar,
SamKind::Ew => Self::Ew,
SamKind::Depot | SamKind::Tzm | SamKind::Light => Self::Support,
_ if kind.armed() => {
if kind.has_gun() && kind.missile_magazine().is_none() { Self::Gun } else { Self::Launcher }
}
_ => Self::Unknown,
}
}
/// What a confirmed contact of this category is worth to the planner, before freshness.
pub fn weight(self) -> u8 {
match self {
Self::Radar | Self::Launcher => 3,
Self::Ew | Self::Gun => 2,
Self::Support => 1,
Self::Unknown => 0,
}
}
}
/// A radar role is public only after a refined look; a coarse report leaves it unknown.
pub fn role_weight(role: battery::RadarRole) -> u8 {
match role {
battery::RadarRole::Multifunction | battery::RadarRole::Engagement => 3,
battery::RadarRole::Search => 2,
battery::RadarRole::Height => 1,
}
}
/// The three parts a mark's priority is priced from, in the same terms `Mark::priority` uses:
/// freshness (its confidence band), how well it is known (quality) and the observed public role
/// (a refined radar's role, else its category). The priority is `freshness * 4 + quality * 3 + role`
/// (#135). The diagnostic reads this to show *why* a mark outranks another, never the unit's truth.
pub fn priority_parts(confidence: Confidence, quality: Quality, category: Category, role: Option<battery::RadarRole>) -> (u8, u8, u8) {
let freshness = match confidence {
Confidence::Confirmed => 4,
Confidence::Probable => 2,
Confidence::Doubtful => 0,
};
let quality = match quality {
Quality::Refined => 2,
Quality::Coarse => 0,
};
let role = role.map_or_else(|| category.weight(), role_weight);
(freshness, quality, role)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Quality {
Coarse,
Refined,
}
impl Quality {
pub fn name(self) -> &'static str {
match self {
Self::Coarse => "coarse",
Self::Refined => "refined",
}
}
pub fn from_key(key: &str) -> Option<Self> {
[Self::Coarse, Self::Refined].into_iter().find(|q| q.name() == key)
}
}
/// The channel a recon mark came from. A flyby sees the unit itself; an emitting radar or a
/// jamming station is recognizable while it transmits; a silent one is just a unit.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Source {
Flyby,
Emission,
Jamming,
Launch,
}
impl Source {
pub fn name(self) -> &'static str {
match self {
Self::Flyby => "flyby",
Self::Emission => "emission",
Self::Jamming => "jamming",
Self::Launch => "launch",
}
}
pub(super) fn from_key(key: &str) -> Option<Self> {
[Self::Flyby, Self::Emission, Self::Jamming, Self::Launch].into_iter().find(|s| s.name() == key)
}
}
/// A mark in the enemy's picture: an area, a coarse category, where it came from, when it
/// was seen and how well. There is deliberately no unit id, SamKind, exact point, health,
/// magazine or link here.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mark {
/// Synthetic id: stable for the mark, never the unit's.
pub(super) id: u32,
pub(super) area: DVec3,
pub(super) radius: f64,
pub(super) category: Category,
/// A radar's role, once a refined look told it; never for a coarse mark.
pub(super) role: Option<battery::RadarRole>,
pub(super) source: Source,
/// The tick of the look this mark rests on.
pub(super) observed: u64,
/// The tick its report arrived (for the record; confidence is age alone).
pub(super) reported: u64,
pub(super) quality: Quality,
pub(super) looks: u16,
}
impl Mark {
pub fn age(&self, now: u64) -> u64 {
now.saturating_sub(self.observed)
}
pub fn live(&self, now: u64) -> bool {
self.age(now) < MARK_TTL
}
pub fn confidence(&self, now: u64) -> Confidence {
ew::confidence_for_age(self.age(now))
}
/// How much the planner wants this mark: its observed public role, its freshness and
/// how well it is known. The unit's id and its true importance are not in it.
pub fn priority(&self, now: u64) -> u8 {
let seen = match self.confidence(now) {
Confidence::Confirmed => 4,
Confidence::Probable => 2,
Confidence::Doubtful => 0,
};
let quality = match self.quality {
Quality::Refined => 2,
Quality::Coarse => 0,
};
let role = self.role.map_or_else(|| self.category.weight(), role_weight);
seen * 4 + quality * 3 + role
}
}
/// A look waiting for its report: the aircraft saw it, but has not radioed it yet.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Look {
pub(super) truth: u32,
pub(super) area: DVec3,
pub(super) radius: f64,
pub(super) category: Category,
pub(super) role: Option<battery::RadarRole>,
pub(super) quality: Quality,
pub(super) source: Source,
pub(super) observed: u64,
/// The unit was a wreck when it was seen: the report takes its mark out of the picture.
pub(super) wreck: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Zone {
pub(super) center: DVec3,
pub(super) radius: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Sortie {
pub(super) drone: u32,
pub(super) zones: Vec<Zone>,
/// The next zone to look through.
pub(super) next: usize,
pub(super) launched: u64,
/// The report waiting to be sent: when, from which zone, and what it saw.
pub(super) report_at: Option<u64>,
pub(super) report_zone: Option<usize>,
pub(super) pending: Vec<Look>,
}
/// What the enemy remembers from its recon flights, across raids.
#[derive(Default)]
pub(super) struct Recon {
pub(super) sorties: Vec<Sortie>,
pub(super) marks: BTreeMap<u32, Mark>,
/// The unit a mark is of. Internal to the observer: the planner only ever sees `Mark`.
pub(super) truth: BTreeMap<u32, u32>,
/// Zones already reported as looked through, by their rounded centre.
pub(super) checked: BTreeMap<(i64, i64), u64>,
pub(super) next: u32,
pub(super) drone_next: u32,
pub(super) reports: u32,
pub(super) lost: u32,
}
impl Recon {
pub(super) fn clear_sorties(&mut self) {
self.sorties.clear();
}
/// A cheap shape of the recon memory for the autosave's dirty check: a new mark, a checked
/// zone, a sortie's progress — and, because a report can refine an existing mark without
/// changing any count, the marks' own observed content (#135).
pub(super) fn mark(&self) -> u64 {
let mut h: u64 = 0xCBF2_9CE4_8422_2325;
let mut mix = |v: u64| h = (h ^ v).wrapping_mul(0x0000_0100_0000_01B3);
mix(self.sorties.len() as u64);
mix(self.marks.len() as u64);
mix(self.checked.len() as u64);
mix(u64::from(self.next));
mix(u64::from(self.drone_next));
for (id, m) in &self.marks {
mix(u64::from(*id));
mix(m.observed);
mix(m.reported);
mix(u64::from(m.looks));
mix(m.quality as u64);
mix(m.category as u64);
mix(m.source as u64);
mix(m.role.map_or(0xff, |r| r as u64));
mix(m.area.x.to_bits());
mix(m.area.z.to_bits());
mix(m.radius.to_bits());
}
for ((i, j), t) in &self.checked {
mix(*i as u64);
mix(*j as u64);
mix(*t);
}
for s in &self.sorties {
mix(u64::from(s.drone));
mix(s.next as u64);
mix(s.pending.len() as u64);
mix(s.report_at.unwrap_or(u64::MAX));
mix(s.report_zone.map_or(u64::MAX, |z| z as u64));
}
h
}
pub(super) fn is_empty(&self) -> bool {
self.sorties.is_empty() && self.marks.is_empty() && self.checked.is_empty()
}
/// The marks the planner may see, newest and best first. The order uses the observed
/// public role, freshness and quality; the synthetic id is only a deterministic last tie.
pub(super) fn leads(&self, now: u64) -> Vec<Mark> {
let mut out: Vec<Mark> = self.marks.values().copied().filter(|m| m.live(now)).collect();
out.sort_by(|a, b| {
b.priority(now)
.cmp(&a.priority(now))
.then(b.observed.cmp(&a.observed))
.then(a.id.cmp(&b.id))
});
out
}
pub(super) fn live(&self, id: u32, now: u64) -> bool {
self.marks.get(&id).is_some_and(|m| m.live(now))
}
/// Remembers a zone that was reported as looked through, bounded. The oldest goes first.
pub(super) fn remember_zone(&mut self, center: DVec3, now: u64) {
self.checked.insert(zone_key(center), now);
while self.checked.len() > MAX_CHECKED {
let Some(oldest) = self.checked.iter().min_by_key(|(_, t)| **t).map(|(k, _)| *k) else { break };
self.checked.remove(&oldest);
}
}
pub(super) fn recently_checked(&self, center: DVec3, now: u64) -> bool {
self.checked.get(&zone_key(center)).is_some_and(|t| now.saturating_sub(*t) < REVISIT)
}
pub(super) fn mark_for_truth(&self, truth: u32) -> Option<Mark> {
self.truth.iter().find_map(|(id, t)| (*t == truth).then(|| self.marks.get(id).copied()).flatten())
}
/// A report that has arrived. The same observation twice changes nothing; a genuinely
/// later look updates the mark and may refine it. The mark keeps its synthetic id.
pub(super) fn report(&mut self, look: Look, now: u64) {
let existing = self.truth.iter().find_map(|(id, t)| (*t == look.truth).then_some(*id));
match existing {
Some(id) => {
let Some(old) = self.marks.get(&id).copied() else { return };
if look.observed <= old.observed {
return;
}
// The flight saw the wreck itself: the station is off the planner's leads, and
// only the observation — never a hidden kill — takes the mark away (#139).
if look.wreck {
self.marks.remove(&id);
self.truth.remove(&id);
return;
}
let refine = look.observed.saturating_sub(old.observed) >= REFINE_GAP;
let m = self.marks.get_mut(&id).unwrap();
m.area = look.area;
m.radius = if refine { REFINED_AREA } else { m.radius };
m.category = look.category;
m.source = look.source;
m.observed = look.observed;
m.reported = now;
m.looks = m.looks.saturating_add(1);
if refine {
m.quality = Quality::Refined;
m.role = look.role;
}
}
None => {
// A wreck is no target: a first look at one leaves no mark at all.
if look.wreck {
return;
}
if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 {
return;
}
self.next += 1;
let id = ID_BASE + self.next;
self.truth.insert(id, look.truth);
self.marks.insert(id, Mark {
id,
area: look.area,
radius: look.radius,
category: look.category,
role: if look.quality == Quality::Refined { look.role } else { None },
source: look.source,
observed: look.observed,
reported: now,
quality: look.quality,
looks: 1,
});
}
}
}
/// Marks older than a disclosure contact's life are forgotten.
pub(super) fn expire(&mut self, now: u64) {
self.marks.retain(|_, m| m.live(now));
let ids: std::collections::HashSet<u32> = self.marks.keys().copied().collect();
self.truth.retain(|id, _| ids.contains(id));
}
/// Drops sorties whose aircraft is gone and keeps the rest; a save may omit a drone it
/// could not write.
pub(super) fn retain_drones(&mut self, alive: &std::collections::HashSet<u32>) {
self.sorties.retain(|s| alive.contains(&s.drone));
}
}
/// The rounded place a zone is remembered by (the report, not the truth).
pub(super) fn zone_key(center: DVec3) -> (i64, i64) {
(center.x.round() as i64, center.z.round() as i64)
}
/// The point a report gives for a unit seen at `at`: the centre of an area cell, moved
/// deterministically off the true point so the mark is an area, not a fix.
pub(super) fn area_of(at: DVec3, cell: f64, salt: u32) -> DVec3 {
let j = |k: u32| {
let h = salt.wrapping_mul(2_654_435_761).rotate_left(7) ^ k.wrapping_mul(2_246_822_519);
(f64::from(h % 1000) / 1000.0 - 0.5) * cell * 0.6
};
DVec3::new((at.x / cell).round() * cell + j(1), at.y, (at.z / cell).round() * cell + j(2))
}
/// One look through a zone: the units inside it, as the channels can tell them. The true
/// place and kind are read here, at the observation, and leave only as an area/category.
pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone, now: u64) -> Vec<Look> {
let mut out = Vec::new();
for s in sams {
if horizontal(s.pos - zone.center).length() > zone.radius {
continue;
}
if out.len() >= MAX_OBSERVED {
break;
}
let old = state.mark_for_truth(s.id);
// The jitter is the zone's, not the unit's: the mark must not carry the unit id even
// indirectly.
let salt = (zone.center.x.round() as i64 as u32) ^ (zone.center.z.round() as i64 as u32).rotate_left(16);
// A wreck is no lead and no emitter (#139). A fresh one makes no mark; one the picture
// already held is reported as destroyed, and the report takes the old mark away. A
// hidden kill never passes through here, so it never rewrites the picture.
if !s.alive() {
if old.is_none() {
continue;
}
out.push(Look {
truth: s.id,
area: area_of(s.pos, COARSE_AREA, salt),
radius: COARSE_AREA,
category: Category::of(s.kind),
role: None,
quality: Quality::Coarse,
source: Source::Flyby,
observed: now,
wreck: true,
});
continue;
}
let refine = old.is_some_and(|m| now.saturating_sub(m.observed) >= REFINE_GAP);
let quality = if refine { Quality::Refined } else { Quality::Coarse };
let cell = if refine { REFINED_AREA } else { COARSE_AREA };
let category = Category::of(s.kind);
// A launch is a public event already watched by the disclosure channel; a look that
// passes just after one can name that source too. Health, magazine and link never are.
let launched = intel.contacts().get(&s.id).is_some_and(|c| c.seen == ew::Seen::Launch && now.saturating_sub(c.tick) < 200);
// The switch is intent, not work: a radar is an emitter only while `radar_up`, a jammer
// only while the transmitter is really on the air. A silent, packed or failed one is
// just a unit the flyby saw.
let source = match s.kind {
SamKind::Ew if s.ew_up() => Source::Jamming,
SamKind::Radar if s.radar_up() => Source::Emission,
_ if launched => Source::Launch,
_ => Source::Flyby,
};
// The role is a public radar configuration only when a close second look can tell it.
let role = (refine && s.kind == SamKind::Radar).then_some(s.radar_role);
out.push(Look {
truth: s.id,
area: area_of(s.pos, cell, salt),
radius: cell,
category,
role,
quality,
source,
observed: now,
wreck: false,
});
}
out
}
/// The zones a smart raid sends its aircraft through: round the marked objectives, then
/// (when every one of those has been checked lately) round a mark the picture still doubts.
pub(super) fn plan_zones(objects: &[DVec3], state: &Recon, now: u64) -> Vec<Zone> {
let mut out = Vec::new();
for (i, p) in objects.iter().take(2).enumerate() {
// The marked objective itself, then one ring round it: the defence around the target
// is what the enemy came to look at, and a ring alone would miss a unit on the mark.
let a = i as f64 * 2.399_963_229_728_653;
let ring = *p + DVec3::new(a.sin() * 260.0, 0.0, a.cos() * 260.0);
for center in [*p, ring] {
if !state.recently_checked(center, now) {
out.push(Zone { center, radius: ZONE_RADIUS });
}
}
}
if out.is_empty() {
// Nothing unchecked round the objectives: re-look at a mark the picture still doubts.
if let Some(m) = state.leads(now).into_iter().find(|m| m.confidence(now) == Confidence::Doubtful) {
out.push(Zone { center: m.area, radius: ZONE_RADIUS });
}
}
out.truncate(ZONES_MAX);
out
}
impl Sim {
/// Whether an aircraft is the enemy's recon flight (#135): the sandbox's truth gives it a
/// sign of its own; the normal picture classes it as any other drone.
pub fn is_recon_drone(&self, id: u32) -> bool {
recon::is_drone_id(id)
}
/// The recon flight's state for the sandbox's truth line (#135): the aircraft still out
/// with a task, and the marks the picture holds. Nothing of the hidden force is in it.
pub fn recon_status(&self) -> (usize, usize) {
(self.recon.sorties.len(), self.recon.marks.values().filter(|m| m.live(self.tick)).count())
}
/// Sends the raid's recon flight: a few unarmed aircraft, physically in the air, ahead
/// of the strike. Their zones come from the marked objectives alone, never from the
/// hidden force, so the same seed and objectives order the same flight whatever the
/// defences are.
pub(super) fn start_recon(&mut self, objects: &[DVec3], bearing: f64, dist: f64, out: &mut Out) {
let zones = plan_zones(objects, &self.recon, self.tick);
// The allowance is the raid's whole recon budget, not one order's: a second wave does not
// launch more aircraft while the first flight is still out.
let room = SORTIES_MAX.saturating_sub(self.recon.sorties.len());
if zones.is_empty() || room == 0 {
return;
}
let Some(&last) = objects.last() else { return };
// Ids beyond the drone parser's bound would make the next save unreadable.
if self.recon.drone_next >= DRONE_TOP - DRONE_BASE - 1 {
return;
}
let want = room.min(2).min(zones.len());
let centre = objects[0];
let from = centre + DVec3::new(bearing.sin() * dist, 120.0, bearing.cos() * dist);
// The recon flight must not spend the strike's combat randomness: its own aim error
// may differ, but a new role must not re-roll the raid that follows it.
let combat_rng = self.rng.state();
for n in 0..want {
// Each aircraft takes every `want`-th zone from `n` on: the first the first zones,
// the second the ones after them, so a loss does not take every look with it.
let mine: Vec<Zone> = zones.iter().skip(n).step_by(want).cloned().collect();
if mine.is_empty() {
continue;
}
let dir = (mine[0].center - from).normalize_or(DVec3::NEG_Z);
// The launch helper takes an id from the strike's counter; the recon aircraft
// gives it back and takes one from its own range, so the strike's ids and
// tie-breaks are exactly what they would have been without the flight.
let main_next = self.next;
self.launch(DroneKind::Gerbera, from, dir, last, out);
self.next = main_next;
let Some(d) = self.drones.last_mut() else { continue };
self.recon.drone_next += 1;
d.id = DRONE_BASE + self.recon.drone_next;
d.low = true;
d.sector = ew::sector(bearing) as u8;
let at = d.id;
d.route = mine.iter().map(|z| z.center + DVec3::Y * 40.0).chain(std::iter::once(last)).collect();
d.target = last;
self.recon.sorties.push(Sortie {
drone: at,
zones: mine,
next: 0,
launched: self.tick,
report_at: None,
report_zone: None,
pending: Vec::new(),
});
}
self.rng.set_state(combat_rng);
if !self.recon.sorties.is_empty() {
out.messages.push("Разведка противника: впереди налёта высланы разведчики".into());
}
}
/// One tick of the recon flight: a look is radioed after its delay if the aircraft is
/// still flying; a lost aircraft leaves its unreported look behind.
pub(super) fn step_recon(&mut self, out: &mut Out) {
let now = self.tick;
if self.recon.sorties.is_empty() {
return;
}
let mut sorties = std::mem::take(&mut self.recon.sorties);
let mut kept = Vec::with_capacity(sorties.len());
let mut lost = 0u32;
for mut s in sorties.drain(..) {
let alive = self.drones.iter().any(|d| d.id == s.drone && d.alive());
if !alive {
// An aircraft that finished its look and flew on to the aim is not a loss: only a
// sortie with a zone left or a report still unsent ended before its work was done.
let unfinished = s.report_at.is_some() || s.next < s.zones.len();
if unfinished {
lost += 1;
out.messages.push(if s.report_at.take().is_some() {
"Разведка противника: разведчик сбит до донесения".into()
} else {
"Разведка противника: разведчик сбит".into()
});
}
continue;
}
if now.saturating_sub(s.launched) > SORTIE_TTL {
if s.report_at.is_some() || s.next < s.zones.len() {
lost += 1;
}
s.pending.clear();
s.report_at = None;
out.messages.push("Разведка противника: разведчик вернулся ни с чем".into());
continue;
}
if let Some(at) = s.report_at {
if now >= at {
if let Some(z) = s.report_zone.take() {
self.recon.remember_zone(s.zones[z].center, now);
}
let n = s.pending.len();
for look in std::mem::take(&mut s.pending) {
self.recon.report(look, now);
}
self.recon.reports = self.recon.reports.saturating_add(1);
s.report_at = None;
out.messages.push(if n == 0 {
"Разведка противника: зона проверена, целей не обнаружено".into()
} else {
format!("Разведка противника: донесение, отметок {n}")
});
} else {
kept.push(s);
continue;
}
}
if s.next < s.zones.len() {
let at = self.drones.iter().find(|d| d.id == s.drone).map(|d| d.pos);
let inside = at.is_some_and(|p| horizontal(p - s.zones[s.next].center).length() <= s.zones[s.next].radius);
if inside {
let z = s.zones[s.next].clone();
s.pending = look(&self.sams, &self.recon, &self.intel, &z, now);
s.report_at = Some(now + REPORT_DELAY);
s.report_zone = Some(s.next);
s.next += 1;
kept.push(s);
continue;
}
kept.push(s);
continue;
}
// Every zone looked through and its report sent: the aircraft flies on to its aim.
}
self.recon.sorties = kept;
self.recon.expire(now);
if lost > 0 {
self.recon.lost = self.recon.lost.saturating_add(lost);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::sites::testland::{Land, serve};
fn sam(sim: &mut Sim, kind: SamKind, at: DVec3) -> u32 {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, at, 0.0));
id
}
fn order() -> RaidOrder {
RaidOrder { kinds: vec![(DroneKind::Shahed, 4)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart }
}
/// Moves the first recon aircraft into its next zone and returns the tick of the look.
fn look_once(sim: &mut Sim) -> (u32, u64) {
let s = sim.recon.sorties.first().expect("no recon sortie").clone();
let d = sim.drones.iter_mut().find(|d| d.id == s.drone).expect("the sortie has no aircraft");
d.pos = s.zones[s.next].center + DVec3::Y * 40.0;
sim.tick += 1;
sim.step_recon(&mut Out::default());
(s.drone, sim.tick)
}
// #135: before anything is observed the recon flight and the strike's decisions are a
// function of the seed, the objectives and the published plan alone. Two hidden layouts
// -- different kinds and places, neither observed -- order the same flight and aims.
#[test]
fn the_same_seed_orders_the_same_flight_whatever_is_hidden() {
let object = DVec3::new(0.0, 70.0, 0.0);
let build = |hidden: bool| {
let mut sim = Sim::new(135);
if hidden {
sam(&mut sim, SamKind::S400, DVec3::new(-180.0, 70.0, 40.0));
sam(&mut sim, SamKind::Radar, DVec3::new(210.0, 70.0, -60.0));
sam(&mut sim, SamKind::Gepard, DVec3::new(20.0, 70.0, 240.0));
} else {
sam(&mut sim, SamKind::Pantsir, DVec3::new(300.0, 70.0, 300.0));
}
sim.targets.push(object);
sim.target_health.push(100.0);
let mut out = Out::default();
sim.order_raid(&order(), &[object], &mut out);
let flight: Vec<_> = sim
.recon
.sorties
.iter()
.map(|s| s.zones.iter().map(|z| (z.center, z.radius)).collect::<Vec<_>>())
.collect();
let aircraft: Vec<_> = sim
.drones
.iter()
.filter(|d| sim.recon.sorties.iter().any(|s| s.drone == d.id))
.map(|d| (d.pos, d.target, d.route.clone()))
.collect();
let aims: Vec<_> = sim.planned_aims().into_iter().map(|(_, i)| i).collect();
let intents: Vec<_> = sim.planned_intents().into_iter().map(|(_, i)| i).collect();
(flight, aircraft, aims, intents)
};
let a = build(false);
let b = build(true);
assert_eq!(a, b, "a hidden layout changed the recon flight or the plan before any observation");
}
// #135: an empty zone proves nothing. The look reports no mark, and only the fact that
// this zone was looked through is remembered.
#[test]
fn an_empty_zone_reports_no_mark() {
let mut sim = Sim::new(1);
let object = DVec3::new(0.0, 70.0, 0.0);
sim.targets.push(object);
sim.target_health.push(100.0);
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
assert!(!sim.recon.sorties.is_empty());
let (_, at) = look_once(&mut sim);
assert!(sim.recon.marks.is_empty(), "an empty zone made a mark");
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
assert!(sim.recon.marks.is_empty(), "an empty zone proved a unit after the report");
assert!(sim.recon.checked.values().any(|t| *t == sim.tick), "the checked zone was not remembered");
}
// #135: a report exists only once the aircraft that made the look is still flying when it
// is due. A sortie lost first leaves no mark; a mark already reported does not disappear
// when the aircraft is lost later.
#[test]
fn a_sortie_lost_before_its_report_sends_nothing() {
let mut sim = Sim::new(2);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (drone, at) = look_once(&mut sim);
assert_eq!(sim.recon.marks.len(), 0, "a look reached the picture before its report");
sim.drones.retain(|d| d.id != drone);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
assert_eq!(sim.recon.marks.len(), 0, "a lost sortie still delivered its look");
// The same look reported in time: the mark arrives and stays after the loss.
let mut sim = Sim::new(2);
let object = DVec3::new(0.0, 70.0, 0.0);
let _ = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (drone, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
assert_eq!(sim.recon.marks.len(), 1, "a timely report made no mark");
let area = sim.recon.marks.values().next().unwrap().area;
sim.drones.retain(|d| d.id != drone);
sim.step_recon(&mut Out::default());
assert_eq!(sim.recon.marks.values().next().unwrap().area, area, "a lost aircraft rewrote a delivered mark");
let _ = id;
}
// #135: confidence is the mark's age, not a count of reports. The same observation
// reported twice changes neither the mark's quality nor its looks.
#[test]
fn a_duplicate_report_does_not_raise_confidence() {
let mut sim = Sim::new(3);
let object = DVec3::new(0.0, 70.0, 0.0);
let _ = sam(&mut sim, SamKind::Radar, object + DVec3::new(30.0, 0.0, 0.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
let before = *sim.recon.marks.values().next().unwrap();
// The same look arrives again, even much later: it is still the same observation.
let look = Look {
truth: sim.recon.truth.values().next().copied().unwrap(),
area: before.area,
radius: before.radius,
category: before.category,
role: before.role,
quality: Quality::Refined,
source: before.source,
observed: before.observed,
wreck: false,
};
sim.recon.report(look, before.reported + 10_000);
let after = *sim.recon.marks.values().next().unwrap();
assert_eq!((after.quality, after.looks, after.observed, after.radius), (before.quality, before.looks, before.observed, before.radius));
assert!(after.confidence(before.reported + 10_000) <= before.confidence(before.reported));
}
// #135: a hidden move or a hidden change does not rewrite the old mark. Only a new look,
// reported later, can re-place it.
#[test]
fn a_hidden_move_does_not_rewrite_the_mark() {
let mut sim = Sim::new(4);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
let before = sim.enemy_picture().recon;
let key = |r: &[super::ew::ReconReport]| -> Vec<_> { r.iter().map(|m| (m.id, m.area, m.radius, m.category, m.role, m.source, m.quality)).collect() };
// A hidden move, a re-role and damage: none of it is an observation. Age moves on,
// the mark's area, category, role and quality do not.
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
s.pos = DVec3::new(900.0, 70.0, 900.0);
s.health = 0.0;
s.radar_role = battery::RadarRole::Height;
s.missiles = 0;
sim.tick += 1000;
assert_eq!(key(&sim.enemy_picture().recon), key(&before), "a hidden change rewrote the recon picture");
// A hidden kill does not take the mark away either: it is still a lead until its age
// runs out, and then it is forgotten like any other unrevisited mark (#139).
let mark = before.first().expect("the look made no mark").id;
let observed = sim.recon.marks.get(&mark).expect("the mark is gone").observed;
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark), "a hidden kill removed an active lead");
assert!(sim.recon.leads(observed + MARK_TTL - 1).iter().any(|m| m.id == mark), "a mark died before its age");
assert!(sim.recon.leads(observed + MARK_TTL).iter().all(|m| m.id != mark), "a mark outlived its age");
}
// #139: a look at a wreck is not a lead. A station destroyed before the flight arrives, with
// its switch still on, makes no mark and no lead; its report is an empty observation.
#[test]
fn a_fresh_wreck_makes_no_mark_and_no_lead() {
let mut sim = Sim::new(21);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
s.health = 0.0;
s.radar_on = true;
assert!(!s.radar_up(), "a destroyed radar still reported itself working");
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
assert!(sim.recon.marks.is_empty(), "a look at a fresh wreck reached the picture");
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
assert!(sim.recon.marks.is_empty(), "a fresh wreck made a mark");
assert!(sim.recon.leads(sim.tick).is_empty(), "a fresh wreck became an active lead");
}
// #139: a hidden kill leaves the mark as the picture remembers it, but a look that flies over
// the wreck reports the destruction and the mark leaves the leads. Nothing of it stays to
// aim at, and a mark no look revisits still ages out on its own.
#[test]
fn a_known_mark_leaves_the_leads_when_its_wreck_is_seen() {
let mut sim = Sim::new(22);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
let mark = sim.recon.mark_for_truth(id).expect("a live radar made no mark");
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark.id));
// A hidden kill is not an observation: the old assessment stands.
sim.sams.iter_mut().find(|s| s.id == id).unwrap().health = 0.0;
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark.id), "a hidden kill removed the mark");
// A look that sees the wreck names it as a flyby, and its report takes the mark away.
let zone = Zone { center: object, radius: ZONE_RADIUS };
let wreck = super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).expect("the wreck was not observed");
assert!(wreck.wreck);
assert_eq!(wreck.source, Source::Flyby, "a wreck named an emission");
sim.recon.report(wreck, sim.tick + REPORT_DELAY);
assert!(sim.recon.marks.is_empty(), "the wreck's report left a mark");
assert!(sim.recon.truth.iter().all(|(_, t)| *t != id), "the wreck's truth mapping stayed");
assert!(sim.recon.leads(sim.tick + REPORT_DELAY).is_empty(), "the wreck stayed an active lead");
}
// #139: a wreck observation still waiting for its report is durable. A restored flight takes
// the mark away on its tick, while an older save without the wreck flag reads as before.
#[test]
fn a_wreck_report_survives_a_save_and_removes_the_mark() {
let mut sim = Sim::new(23);
let object = DVec3::new(0.0, 70.0, 0.0);
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
let mark = sim.recon.mark_for_truth(id).expect("no mark to destroy");
// The radar dies unseen; a second flight looks at the wreck and its report is unsent
// when the save is taken.
sim.sams.iter_mut().find(|s| s.id == id).unwrap().health = 0.0;
sim.recon.sorties.clear();
sim.recon.checked.clear();
sim.start_recon(&[object], 0.0, 900.0, &mut Out::default());
let (_, seen_wreck) = look_once(&mut sim);
assert!(sim.recon.sorties.iter().flat_map(|s| &s.pending).any(|l| l.wreck), "the wreck was not pending");
let text = sim.air_text().expect("a wreck report is durable");
assert!(text.lines().any(|l| l.starts_with("airrecobs ") && l.ends_with(" true")), "the wreck flag was not written");
// An older save has no flag: the same look reads as a live re-observation.
let legacy: String = text
.lines()
.map(|l| {
if l.starts_with("airrecobs ") {
let mut w: Vec<&str> = l.split_whitespace().collect();
w.pop();
w.join(" ")
} else {
l.to_string()
}
})
.collect::<Vec<_>>()
.join("\n")
+ "\n";
let mut old = Sim::new(24);
old.restore_air(Sim::parse_air(&legacy).expect("an older save reads").expect("the air section is there"));
assert!(old.recon.sorties.iter().flat_map(|s| &s.pending).all(|l| !l.wreck), "an older save invented a wreck");
let mut back = Sim::new(25);
back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there"));
assert!(back.recon.marks.contains_key(&mark.id), "the save forgot the mark before its wreck report");
assert!(back.recon.sorties.iter().flat_map(|s| &s.pending).any(|l| l.wreck), "the save lost the wreck report");
back.tick = seen_wreck + REPORT_DELAY;
back.step_recon(&mut Out::default());
assert!(!back.recon.marks.contains_key(&mark.id), "a restored wreck report left the mark");
assert!(back.recon.leads(back.tick).is_empty(), "a restored wreck report stayed an active lead");
}
// #135/#139: the channel matters. A silent, packed or failed radar is only a flyby; so is a
// jammer whose transmitter is off, packed or destroyed. Only a station actually working shows
// its emission, and a wreck is no source at all. A just-fired system is still a launch the
// disclosure channel already watched. A hidden empty magazine is not read.
#[test]
fn the_source_is_the_channel_that_showed_a_working_unit() {
let mut sim = Sim::new(8);
let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS };
let radar = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0));
let ew = sam(&mut sim, SamKind::Ew, DVec3::new(-10.0, 70.0, 0.0));
let s400 = sam(&mut sim, SamKind::S400, DVec3::new(0.0, 70.0, 10.0));
let source = |sim: &Sim, id: u32| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).map(|l| l.source);
fn unit(sim: &mut Sim, id: u32) -> &mut Sam {
sim.sams.iter_mut().find(|s| s.id == id).unwrap()
}
// Working: the radar emits and the jammer transmits.
assert_eq!(source(&sim, radar), Some(Source::Emission));
unit(&mut sim, ew).ew_on = true;
assert_eq!(source(&sim, ew), Some(Source::Jamming));
// Off: the switch is intent, not work.
unit(&mut sim, radar).radar_on = false;
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a silent radar was read as emitting");
unit(&mut sim, radar).radar_on = true;
unit(&mut sim, ew).ew_on = false;
assert_eq!(source(&sim, ew), Some(Source::Flyby), "a silent jammer was read as transmitting");
unit(&mut sim, ew).ew_on = true;
// Packed for a march: neither is on the air, whatever the switch says.
unit(&mut sim, radar).state = SamState::Moving;
unit(&mut sim, ew).state = SamState::Moving;
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a radar on the march was read as emitting");
assert_eq!(source(&sim, ew), Some(Source::Flyby), "a jammer on the march was read as transmitting");
unit(&mut sim, radar).state = SamState::Search;
unit(&mut sim, ew).state = SamState::Search;
// Cooling down: a jammer locked by heat is not transmitting either.
unit(&mut sim, ew).ew_lock = true;
assert_eq!(source(&sim, ew), Some(Source::Flyby), "an overheated jammer was read as transmitting");
unit(&mut sim, ew).ew_lock = false;
// Damage: a failed sensor is no radar; a damaged hull with a working sensor still emits.
unit(&mut sim, radar).comps.0[Part::Sensor as usize] = 0.0;
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a radar with a failed sensor was read as emitting");
unit(&mut sim, radar).comps.0[Part::Sensor as usize] = 1.0;
unit(&mut sim, radar).health = 0.5;
assert_eq!(source(&sim, radar), Some(Source::Emission), "a damaged but working radar lost its emission");
// Destroyed: a wreck is no source and makes no lead at all.
unit(&mut sim, radar).health = 0.0;
unit(&mut sim, ew).health = 0.0;
assert_eq!(source(&sim, radar), None, "a wreck was reported as a lead");
assert_eq!(source(&sim, ew), None, "a wrecked jammer was reported as transmitting");
sim.intel.observe(sim.sams.iter().find(|s| s.id == s400).unwrap(), sim.tick, ew::Seen::Launch);
assert_eq!(source(&sim, s400), Some(Source::Launch));
// A hidden empty magazine does not change the source.
sim.sams.iter_mut().find(|s| s.id == s400).unwrap().missiles = 0;
assert_eq!(source(&sim, s400), Some(Source::Launch));
}
// #139: a station the picture already holds, seen off, packed or damaged, stays a flyby
// contact: the switch never turns its mark into an emitter, and a working station seen
// again still names its emission.
#[test]
fn a_known_station_that_stops_working_stays_a_flyby_contact() {
let mut sim = Sim::new(26);
let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS };
let id = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0));
let seen = |sim: &Sim, now: u64| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, now).into_iter().find(|l| l.truth == id).expect("the radar was not observed");
let first = seen(&sim, 100);
assert_eq!(first.source, Source::Emission);
sim.recon.report(first, 100);
let mark = sim.recon.mark_for_truth(id).expect("the working look made no mark");
// Off, then packed for a march, then with a failed sensor: the contact stays, the
// channel is the flyby alone.
for (change, now) in [(0, 200), (1, 900), (2, 1600)] {
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
match change {
0 => s.radar_on = false,
1 => {
s.radar_on = true;
s.state = SamState::Moving;
}
_ => {
s.state = SamState::Search;
s.comps.0[Part::Sensor as usize] = 0.0;
}
}
let look = seen(&sim, now);
assert!(!look.wreck, "case {change}: a working station was read as a wreck");
assert_eq!(look.source, Source::Flyby, "case {change}: the switch was read as work");
sim.recon.report(look, now);
assert!(sim.recon.marks.contains_key(&mark.id), "case {change}: the contact was lost");
}
// Working again: the refined look names the emission.
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
s.comps.0[Part::Sensor as usize] = 1.0;
let look = seen(&sim, 2300);
assert_eq!(look.source, Source::Emission);
assert_eq!(look.quality, Quality::Refined);
sim.recon.report(look, 2300);
assert_eq!(sim.recon.mark_for_truth(id).unwrap().source, Source::Emission);
}
// #135: the planner's order is the observed public role, freshness and quality, not the
// unit id or its true importance. A fresh modest mark outranks an old doubtful big one;
// the synthetic ids are only the last deterministic tie.
#[test]
fn priority_is_observed_role_and_freshness_not_id_or_truth() {
let mut r = Recon::default();
let mark = |id: u32, at: DVec3, category, role, observed, quality| Mark {
id,
area: at,
radius: REFINED_AREA,
category,
role,
source: Source::Flyby,
observed,
reported: observed,
quality,
looks: 1,
};
r.marks.insert(ID_BASE + 1, mark(ID_BASE + 1, DVec3::ZERO, Category::Radar, Some(battery::RadarRole::Engagement), 100, Quality::Refined));
r.marks.insert(ID_BASE + 2, mark(ID_BASE + 2, DVec3::X, Category::Launcher, None, 100, Quality::Refined));
let now = 200;
let leads = r.leads(now);
assert_eq!((leads[0].id, leads[1].id), (ID_BASE + 1, ID_BASE + 2), "a bigger observed role did not lead");
// The same observations age: the big one becomes doubtful, the modest one is fresh.
r.marks.insert(ID_BASE + 2, mark(ID_BASE + 2, DVec3::X, Category::Gun, None, 3900, Quality::Coarse));
let leads = r.leads(4000);
assert_eq!(leads[0].id, ID_BASE + 2, "a stale doubtful mark outranked a fresh modest one");
assert!(leads.iter().all(|m| m.id != 1 && m.id != 2), "a true id leaked into the marks");
}
// #135: the diagnostic's breakdown is the planner's own price: for every confidence, quality,
// category and role the parts sum to exactly `Mark::priority`, so the reason shown can never
// drift from the order the planner actually uses.
#[test]
fn priority_parts_sum_to_the_planners_priority() {
for confidence in [Confidence::Doubtful, Confidence::Probable, Confidence::Confirmed] {
let now = match confidence {
Confidence::Confirmed => 100,
Confidence::Probable => 1000,
Confidence::Doubtful => 4000,
};
for quality in [Quality::Coarse, Quality::Refined] {
for category in [Category::Unknown, Category::Radar, Category::Launcher, Category::Gun, Category::Ew, Category::Support] {
for role in [None, Some(battery::RadarRole::Search), Some(battery::RadarRole::Engagement), Some(battery::RadarRole::Height), Some(battery::RadarRole::Multifunction)] {
let m = Mark { id: ID_BASE + 1, area: DVec3::ZERO, radius: COARSE_AREA, category, role, source: Source::Flyby, observed: 0, reported: 0, quality, looks: 1 };
assert_eq!(m.confidence(now), confidence);
let (f, q, r) = priority_parts(confidence, quality, category, role);
assert_eq!(f * 4 + q * 3 + r, m.priority(now), "{confidence:?} {quality:?} {category:?} {role:?}");
}
}
}
}
}
// #135: only the smart enemy gets the phase. A simple preset's raid gets no aircraft and
// spends no time on a role it never had.
#[test]
fn a_simple_preset_gets_no_recon() {
let mut sim = Sim::new(9);
let object = DVec3::new(0.0, 70.0, 0.0);
sim.targets.push(object);
sim.target_health.push(100.0);
let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Objects };
sim.order_raid(&order, &[object], &mut Out::default());
assert!(sim.recon.sorties.is_empty());
}
// #135: save/load keeps the flight, the pending report, the marks and the checked zones;
// the restored flight finishes the same way.
#[test]
fn save_and_load_keep_the_recon_flight_and_its_marks() {
let mut sim = Sim::new(5);
let object = DVec3::new(0.0, 70.0, 0.0);
let _ = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0));
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut Out::default());
// A second sortie still out with a pending look.
if sim.recon.sorties.is_empty() {
sim.recon.checked.clear();
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
}
let _ = look_once(&mut sim);
// A drone turned onto a mark has a pending route job keyed by the synthetic id.
let mark = *sim.recon.marks.values().next().expect("no mark to aim at");
let mut d = sim.make_drone(DroneKind::Kh22, DVec3::new(-800.0, 120.0, 0.0), DVec3::X, mark.area);
d.smart = true;
d.target = mark.area;
d.aim = ew::Aim::unit(mark.id, sim.tick, mark.confidence(sim.tick));
let drone = d.id;
sim.drones.push(d);
sim.retargets.push_back(ew::RouteJob::restored(900, drone, mark.area, mark.id, sim.tick, ew::Intent::Plan, std::sync::Arc::new(Vec::new()), None));
let text = sim.air_text().expect("a recon flight is durable");
assert!(text.contains("airrecon"), "the recon section was not written");
let mut back = Sim::new(6);
back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there"));
assert_eq!(back.recon.marks.len(), sim.recon.marks.len());
assert_eq!(back.recon.sorties.len(), sim.recon.sorties.len());
assert!(back.retargets.iter().any(|j| j.unit == mark.id), "a job on a recon mark was lost with the save");
for (a, b) in sim.recon.marks.values().zip(back.recon.marks.values()) {
assert_eq!((a.id, a.category, a.quality, a.observed, a.reported), (b.id, b.category, b.quality, b.observed, b.reported));
assert!(a.area.distance(b.area) < 0.02 && (a.radius - b.radius).abs() < 1e-6);
}
for (a, b) in sim.recon.sorties.iter().zip(&back.recon.sorties) {
assert_eq!((a.drone, a.next, a.launched, a.report_at, a.report_zone), (b.drone, b.next, b.launched, b.report_at, b.report_zone));
assert_eq!(a.pending.len(), b.pending.len());
assert_eq!(a.zones.len(), b.zones.len());
}
// The restored pending report arrives on its tick and leaves a mark.
back.tick = at + REPORT_DELAY * 2;
back.step_recon(&mut Out::default());
assert!(!back.recon.marks.is_empty());
}
// #135: a normal smart wave with a recon flight still ends. The recon phase is bounded and
// never holds the raid open; a lost or empty sortie does not pause the match.
#[test]
fn a_normal_smart_wave_with_recon_finishes() {
let mut sim = Sim::new(7);
sim.targets.push(DVec3::new(0.0, 70.0, 0.0));
sim.target_health.push(100.0);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..20 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2), (DroneKind::Gerbera, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart };
assert_eq!(sim.order_raid(&order, &[DVec3::new(0.0, 70.0, 0.0)], &mut out), 4);
assert!(!sim.recon.sorties.is_empty(), "the smart wave sent no recon");
let mut ticks = 0;
for _ in 0..8000 {
serve(&mut ground, &land, sim.tick);
out = Out::default();
sim.step(&mut ground, None, &mut out);
ticks += 1;
if !sim.planning() && sim.queue.is_empty() && !sim.drones.iter().any(|d| d.alive()) {
break;
}
}
assert!(!sim.planning(), "the raid never stopped planning");
assert!(sim.queue.is_empty(), "the raid still has launches waiting");
assert!(!sim.drones.iter().any(|d| d.alive()), "a drone flew for ever");
assert!(ticks < 8000);
}
// #135: a later raid inherits the picture the earlier one radioed home -- the marks do not
// vanish with the wave -- and its flight never grows past the budget while an aircraft of
// the first wave is still out.
#[test]
fn a_new_raid_keeps_the_marks_and_stays_within_the_flight_budget() {
let mut sim = Sim::new(11);
let object = DVec3::new(0.0, 70.0, 0.0);
let _ = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0));
sim.targets.push(object);
sim.target_health.push(100.0);
let mut out = Out::default();
// Far out, so no aircraft starts inside a zone and the second one can stay out.
sim.start_recon(&[object], 0.0, 900.0, &mut out);
let (_, at) = look_once(&mut sim);
sim.tick = at + REPORT_DELAY;
sim.step_recon(&mut out);
let seen = *sim.recon.marks.values().next().expect("the first flight reported nothing");
assert!(!sim.recon.sorties.is_empty(), "the first flight left no aircraft out");
sim.order_raid(&order(), &[object], &mut out);
assert!(sim.recon.sorties.len() <= SORTIES_MAX, "a second order launched past the recon budget");
let kept = sim.recon.marks.get(&seen.id).copied().expect("a new raid forgot what the first one saw");
assert_eq!((kept.area, kept.observed, kept.category), (seen.area, seen.observed, seen.category), "a new raid rewrote a mark");
assert!(!sim.recon.leads(sim.tick).is_empty(), "the new wave planned without the old picture");
}
// #135: a refinement of an existing mark changes the save's dirty shape. A report that only
// updates the area, age, quality or role leaves every count as it was, so the counts alone
// would let an autosave miss it.
#[test]
fn a_refined_mark_changes_the_durable_shape() {
let mut r = Recon::default();
let coarse_look = Look {
truth: 5,
area: DVec3::ZERO,
radius: COARSE_AREA,
category: Category::Radar,
role: None,
quality: Quality::Coarse,
source: Source::Flyby,
observed: 100,
wreck: false,
};
r.report(coarse_look, 200);
let coarse = r.mark();
r.report(
Look { observed: 100 + REFINE_GAP, quality: Quality::Refined, role: Some(battery::RadarRole::Engagement), source: Source::Emission, area: DVec3::new(30.0, 70.0, 0.0), radius: REFINED_AREA, ..coarse_look },
200 + REFINE_GAP,
);
assert_eq!(r.marks.len(), 1, "a refinement made a second mark");
assert_ne!(r.mark(), coarse, "a refined mark is invisible to the autosave's dirty check");
}
// #135: among equally fresh, equally well known radars, the one whose observed role is the
// bigger is offered the strikers first; the modest one is still worked over, so the raid keeps
// its breadth. The seed does not change it: the order is the observed role, not a draw or an id.
#[test]
fn a_big_observed_radar_is_offered_the_strikers_first() {
for seed in [1u64, 2, 3] {
let mut sim = Sim::new(seed);
sim.tick = 1000;
let look = |truth: u32, role: battery::RadarRole| Look {
truth,
area: DVec3::new(f64::from(truth) * 100.0, 70.0, 0.0),
radius: REFINED_AREA,
category: Category::Radar,
role: Some(role),
quality: Quality::Refined,
source: Source::Emission,
observed: 1000,
wreck: false,
};
sim.recon.report(look(1, battery::RadarRole::Search), 1000);
sim.recon.report(look(2, battery::RadarRole::Engagement), 1000);
let id_of = |truth: u32| sim.recon.truth.iter().find_map(|(id, t)| (*t == truth).then_some(*id)).unwrap();
let (modest, big) = (id_of(1), id_of(2));
let jobs = sim.radar_strikes(&[(DroneKind::Kh22, 8)], &[]);
let first: Vec<u32> = jobs.iter().flatten().map(|(_, id)| *id).collect();
assert_eq!(first.first().copied(), Some(big), "seed {seed}: a modest station was offered the first striker");
assert!(first.contains(&modest), "seed {seed}: the modest station got no striker at all");
}
}
// #135: a recon aircraft is a role of its own: it neither opens a strike's replay nor keeps
// one open. A strike drone still does, so the check is not vacuous.
#[test]
fn a_recon_flight_does_not_open_the_strike_replay() {
let mut sim = Sim::new(12);
let object = DVec3::new(0.0, 70.0, 0.0);
sim.targets.push(object);
sim.target_health.push(100.0);
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
assert!(!sim.recon.sorties.is_empty(), "no recon aircraft to test with");
sim.begin_recording_if_active();
assert!(sim.rec.is_none(), "a recon aircraft opened a strike replay");
sim.launch(DroneKind::Shahed, DVec3::new(-300.0, 120.0, 0.0), DVec3::X, object, &mut Out::default());
sim.begin_recording_if_active();
assert!(sim.rec.is_some(), "a strike drone did not open its replay");
}
// #135: the recon memory is as durable as the rest of the air state and stays inside the
// section's byte budget: every mark, checked zone and sortie written is read back.
#[test]
fn the_whole_recon_memory_fits_a_save_and_reads_back() {
let mut sim = Sim::new(13);
sim.tick = 100;
for truth in 1..=MAX_MARKS as u32 {
sim.recon.report(
Look {
truth,
area: DVec3::new(f64::from(truth), 70.0, -0.5),
radius: COARSE_AREA,
category: Category::Launcher,
role: None,
quality: Quality::Coarse,
source: Source::Flyby,
observed: 100,
wreck: false,
},
100,
);
}
for x in 0..MAX_CHECKED as i64 {
sim.recon.remember_zone(DVec3::new(x as f64 * 10.0, 70.0, 5.0), 100);
}
assert_eq!(sim.recon.marks.len(), MAX_MARKS);
let text = sim.air_text().expect("a full recon memory is durable");
assert!(text.len() < 1 << 20, "the air section grew to {} bytes", text.len());
let mut back = Sim::new(14);
back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there"));
assert_eq!(back.recon.marks.len(), MAX_MARKS);
assert_eq!(back.recon.checked.len(), MAX_CHECKED);
assert_eq!(back.recon.marks.values().map(|m| m.observed).sum::<u64>(), MAX_MARKS as u64 * 100);
}
}