Add typed battle reasons and short engagement chains (#148)
build / mod (push) Failing after 32s

A battery's "why" now starts with one typed reason shared by the monitor,
the HUD and the chat: only observation, waiting for a track, busy channels,
no ammunition, or ready. It carries the age and the station of the mark it
is about, and `/airdef why <n> source` moves the monitor to that station.
The reason is computed from the same predicates the launch decision uses,
and the detailed decision settles it, so a headline cannot promise or deny
a shot the simulation does not take.

The after-action review builds 4-5 measured steps per contact from the
recording's scene journal and events: mark, handoff, lock, launch, outcome.
The menu lists them per battery with a filter and opens a replay frame on
a click (the outcome clip, else the map held at the launch or mark);
`/airdef chains [battery]` prints the same list. Missing transitions stay
missing and marked as no launch, never guessed, and the normal HUD still
shows only the battery's own picture.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
2026-11-21 09:40:55 +03:00
parent bd2d8f4fed
commit 8afe691301
7 changed files with 1058 additions and 7 deletions
+227
View File
@@ -275,6 +275,77 @@ pub struct Event {
pub kind: EventKind,
}
/// One step of a short after-action chain: отметка → передача → захват → пуск → исход.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ChainStepKind {
/// The contact first appears on the battery's picture.
Mark,
/// The plot's source changes (a relay became the battery's own measurement, or the reverse).
Handoff,
/// The battery's own radar locks it.
Lock,
/// The battery launches an interceptor at it.
Launch,
/// What came of the chain: shot down, broke through, lost.
Outcome,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ChainOutcome {
Destroyed,
/// The target reached its aim (an object, a system, the land).
Hit,
Lost,
/// The recording ended or the chain was cut short.
Unfinished,
}
#[derive(Clone, Copy, Debug)]
pub struct ChainStep {
pub kind: ChainStepKind,
pub at: u32,
/// The recorded event a replay can open (the outcome), when there is one.
pub event: Option<usize>,
/// For the mark and the handoff: the plot is the battery's own measurement.
pub own: bool,
/// For a launch: the interceptor's id.
pub missile: Option<u32>,
}
/// A battery's short engagement history for one contact, built from the recording's measured
/// scene transitions and events. At most one step of each kind: no inferred beats.
#[derive(Clone, Debug)]
pub struct Chain {
pub sam: u32,
pub target: u32,
pub steps: Vec<ChainStep>,
pub outcome: ChainOutcome,
}
impl Chain {
pub fn marked_at(&self) -> u32 {
self.steps.first().map_or(0, |s| s.at)
}
pub fn step(&self, kind: ChainStepKind) -> Option<&ChainStep> {
self.steps.iter().find(|s| s.kind == kind)
}
pub fn launched(&self) -> bool {
self.step(ChainStepKind::Launch).is_some()
}
/// A contact that appeared on the picture and was never launched at.
pub fn missed(&self) -> bool {
!self.launched()
}
/// The event a replay clip opens on: the outcome when there is one, else nothing.
pub fn outcome_event(&self) -> Option<usize> {
self.step(ChainStepKind::Outcome).and_then(|s| s.event)
}
}
/// Measured scene transitions. These are facts, not inferred cinematic beats.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SceneKind {
@@ -867,6 +938,119 @@ impl Recording {
pub fn sam(&self, id: u32) -> Option<(SamKind, DVec3)> {
self.sams.iter().find(|s| s.0 == id).map(|s| (s.1, s.2))
}
/// The battery's short chains through this raid, one per contact, in the order they began:
/// the picture's own transitions (mark, handoff, lock, launch) and the recorded outcome.
/// `battery` filters by system id; None keeps all. A recording with no scene journal (the
/// legacy format) has no chains, and a truncated one may miss a later step — that is marked
/// by `SceneJournal::truncated`, never guessed.
pub fn chains(&self, battery: Option<u32>) -> Vec<Chain> {
let Some(scene) = &self.scene else { return Vec::new() };
let mut chains: std::collections::BTreeMap<(u32, u32), Chain> = std::collections::BTreeMap::new();
for event in scene.events() {
match event.kind {
SceneKind::TrackAcquired { sam, target, ever_own } => {
let chain = chains.entry((sam, target)).or_insert_with(|| Chain {
sam,
target,
steps: Vec::new(),
outcome: ChainOutcome::Unfinished,
});
if chain.steps.is_empty() {
chain.steps.push(ChainStep { kind: ChainStepKind::Mark, at: event.at, event: None, own: ever_own, missile: None });
}
}
SceneKind::TrackSource { sam, target, ever_own } => {
if let Some(chain) = chains.get_mut(&(sam, target))
&& chain.step(ChainStepKind::Handoff).is_none()
{
chain.steps.push(ChainStep { kind: ChainStepKind::Handoff, at: event.at, event: None, own: ever_own, missile: None });
}
}
SceneKind::TrackLock { sam, target, locked: true } => {
if let Some(chain) = chains.get_mut(&(sam, target))
&& chain.step(ChainStepKind::Lock).is_none()
{
chain.steps.push(ChainStep { kind: ChainStepKind::Lock, at: event.at, event: None, own: true, missile: None });
}
}
SceneKind::MissileLaunch { sam, target, missile, .. } => {
if let Some(chain) = chains.get_mut(&(sam, target))
&& chain.step(ChainStepKind::Launch).is_none()
{
chain.steps.push(ChainStep { kind: ChainStepKind::Launch, at: event.at, event: None, own: true, missile: Some(missile) });
}
}
_ => {}
}
}
// The outcomes are the recorded events; a kill identifies its chain by the battery and
// the target, or by the interceptor when another battery's kill shares the target.
for (index, event) in self.events.iter().enumerate() {
match event.kind {
EventKind::Kill { drone, sam, missile, .. } => {
let mut keys = vec![(sam, drone)];
if let Some(missile) = missile {
keys.extend(chains.iter().filter(|(_, c)| c.steps.iter().any(|s| s.missile == Some(missile))).map(|(k, _)| *k));
}
for key in keys {
if let Some(chain) = chains.get_mut(&key) {
set_chain_outcome(chain, ChainOutcome::Destroyed, event.at, Some(index));
}
}
}
EventKind::Hit { drone, sam, .. } => {
let by_sam = sam.and_then(|(_, i)| self.sams.get(i).map(|s| s.0));
for ((_, target), chain) in chains.iter_mut() {
if *target == drone && by_sam.is_none_or(|id| id == chain.sam) {
set_chain_outcome(chain, ChainOutcome::Hit, event.at, Some(index));
}
}
}
EventKind::Crash { drone, .. } => {
for ((_, target), chain) in chains.iter_mut() {
if *target == drone && !chain.launched() {
set_chain_outcome(chain, ChainOutcome::Lost, event.at, Some(index));
}
}
}
_ => {}
}
}
// A contact dropped without an outcome and never fired at was missed, not engaged.
for event in scene.events() {
if let SceneKind::TrackLost { sam, target } = event.kind
&& let Some(chain) = chains.get_mut(&(sam, target))
&& !chain.launched()
{
set_chain_outcome(chain, ChainOutcome::Lost, event.at, None);
}
}
let mut out: Vec<Chain> = chains
.into_values()
.filter(|c| battery.is_none_or(|id| c.sam == id))
.filter(|c| !c.steps.is_empty())
.collect();
out.sort_by_key(|c| (c.marked_at(), c.sam, c.target));
out
}
}
/// Sets a chain's outcome, keeping the strongest one seen (shot down beats a hit, a hit beats a
/// lost or unfinished chain) and at most one outcome step.
fn set_chain_outcome(chain: &mut Chain, outcome: ChainOutcome, at: u32, event: Option<usize>) {
let rank = |o: ChainOutcome| match o {
ChainOutcome::Destroyed => 3,
ChainOutcome::Hit => 2,
ChainOutcome::Lost => 1,
ChainOutcome::Unfinished => 0,
};
if rank(chain.outcome) > rank(outcome) {
return;
}
chain.outcome = outcome;
chain.steps.retain(|s| s.kind != ChainStepKind::Outcome);
chain.steps.push(ChainStep { kind: ChainStepKind::Outcome, at, event, own: false, missile: None });
}
impl Sim {
@@ -1153,6 +1337,49 @@ mod tests {
s
}
#[test]
fn battle_chains_keep_four_or_five_measured_steps_and_filter_by_battery() {
let mut r = Recording::blank(400);
r.sams = vec![(10, SamKind::Pantsir, DVec3::ZERO), (20, SamKind::S400, DVec3::new(200.0, 64.0, 0.0))];
let mut scene = SceneJournal::default();
let at = |at: u32, kind| SceneEvent { at, pos: DVec3::ZERO, kind };
scene.push(at(20, SceneKind::TrackAcquired { sam: 10, target: 7, ever_own: false }));
scene.push(at(30, SceneKind::TrackSource { sam: 10, target: 7, ever_own: true }));
scene.push(at(40, SceneKind::TrackLock { sam: 10, target: 7, locked: true }));
scene.push(at(50, SceneKind::MissileLaunch { missile: 500, sam: 10, target: 7, kind: MissileKind::M57e6, sound: "airdef:launch.pantsir", pitch: 1.0 }));
scene.push(at(70, SceneKind::TrackLost { sam: 10, target: 7 }));
r.scene = Some(scene);
r.events.push(Event {
at: 60,
pos: DVec3::ZERO,
kind: EventKind::Kill { drone: 7, kind: DroneKind::Shahed, sam: 10, sam_kind: SamKind::Pantsir, sam_index: 0, missile: Some(500), outcome: Outcome::DisabledFalling },
});
let chains = r.chains(None);
assert_eq!(chains.len(), 1);
let chain = &chains[0];
let kinds: Vec<ChainStepKind> = chain.steps.iter().map(|s| s.kind).collect();
assert_eq!(kinds, vec![ChainStepKind::Mark, ChainStepKind::Handoff, ChainStepKind::Lock, ChainStepKind::Launch, ChainStepKind::Outcome]);
assert_eq!(chain.outcome, ChainOutcome::Destroyed);
assert_eq!(chain.outcome_event(), Some(0));
assert!(!chain.missed());
assert_eq!(chain.marked_at(), 20);
assert_eq!(r.chains(Some(10)).len(), 1);
assert!(r.chains(Some(20)).is_empty(), "the filter picked another battery");
// A contact marked and lost without a launch is a missed chain, not an engagement.
let mut r = Recording::blank(100);
r.sams = vec![(10, SamKind::Pantsir, DVec3::ZERO)];
let mut scene = SceneJournal::default();
scene.push(at(10, SceneKind::TrackAcquired { sam: 10, target: 8, ever_own: false }));
scene.push(at(50, SceneKind::TrackLost { sam: 10, target: 8 }));
r.scene = Some(scene);
let chain = &r.chains(None)[0];
assert!(chain.missed());
assert_eq!(chain.outcome, ChainOutcome::Lost);
assert_eq!(chain.steps.len(), 2);
assert_eq!(chain.outcome_event(), None);
}
fn recording() -> Recording {
Recording {
number: 1,
+463
View File
@@ -287,6 +287,312 @@ pub enum CheckReason {
Text(String),
Parts(Vec<(Part, f64)>),
PartEffect(PartEffect),
/// The one headline reason a battery fires or does not, shared by the sim, the monitor and
/// the chat command.
Battle(BattleReason),
}
// ---------------------------------------------------------------- the one headline reason
/// What a battery's picture holds of a contact: the newest plot, its age and the station that
/// made it. Only what the battery itself can know: a relayed plot's source, never the drone's
/// true kind or place.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct BattleMark {
/// Ticks since the newest measurement (any station).
pub age: u64,
/// Ticks since this battery's own radar measured it, if it ever did.
pub own_age: Option<u64>,
/// The station that made the newest plot, as an index into `Sim::sams`.
pub source: Option<usize>,
/// The newest plot is this battery's own measurement.
pub own: bool,
/// What the newest plot is good for.
pub product: battery::Measure,
pub quality: u8,
/// This battery's own measurement's product, if it has one.
pub own_product: Option<battery::Measure>,
/// The plot is carried on as a forecast, not a fresh measurement.
pub forecast: bool,
/// The class the picture estimated, never the target's own kind.
pub class: ClassEst,
}
impl BattleMark {
fn of(sim: &Sim, sam: &Sam, track: &sight::Track, now: u64) -> Self {
BattleMark {
age: track.age(now),
own_age: (track.own_tick > 0).then(|| now.saturating_sub(track.own_tick)),
source: sim.sams.iter().position(|s| s.id == track.source),
own: track.source == sam.id,
product: track.product,
quality: track.quality,
own_product: (track.own_tick > 0).then_some(track.own_product),
forecast: track.forecast(now),
class: track.class,
}
}
}
/// The headline state of a battery, in the words the player asks with.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BattleKind {
/// It can fire at the target it holds now.
Ready,
/// Есть только обзор: a search plot or a relayed one, no fire-quality measurement.
ObserveOnly,
/// Ждёт сопровождения: its own radar is refining, or a launcher waits for a supporting
/// radar's fire plot.
AwaitingTrack,
/// Каналы заняты: every tracked-contact channel of its radar is in use by other contacts.
ChannelsBusy,
/// Нет боезапаса: no rounds and no shells, or reloading.
NoAmmo,
/// Something else stops it, named by `block`.
Blocked,
}
/// What stops a battery that is otherwise ready to engage.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BattleBlock {
Destroyed,
Moving,
Hold,
NoWeapon,
NoTarget,
NoTrack,
OutOfRoles,
OutOfReach,
Claimed,
Doctrine,
Aiming,
Preparing,
LauncherDown,
Other,
}
/// The one reason, in a typed form. `mark` is the contact's own picture (age, source, product);
/// a hidden truth never enters it.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct BattleReason {
pub kind: BattleKind,
pub block: Option<BattleBlock>,
pub sam: usize,
pub target: Option<u32>,
pub mark: Option<BattleMark>,
pub rounds: u32,
pub bursts: u32,
/// Ticks left of a reload, 0 when loaded.
pub reloading: u32,
/// Tracked-contact channels in use and their total, when the radar has any.
pub channels: Option<(usize, u8)>,
}
impl BattleReason {
pub fn ready(self) -> bool {
self.kind == BattleKind::Ready
}
/// The detailed decision (`why`) is the authority on whether a shot goes now: a headline
/// that promised a shot it cannot take, or denied one it takes, is corrected here.
pub fn settle(&mut self, fires: bool) {
match (fires, self.kind == BattleKind::Ready) {
(true, false) => {
self.kind = BattleKind::Ready;
self.block = None;
}
(false, true) => {
self.kind = BattleKind::Blocked;
self.block = Some(BattleBlock::Other);
}
_ => {}
}
}
}
impl Sim {
/// Why battery `index` fires or doesn't, as one typed reason for the target it holds or the
/// most threatening one its picture allows. The same predicates `step_sams` uses.
pub fn battle_reason(&self, index: usize) -> Option<BattleReason> {
self.battle_reason_at(index, None)
}
/// The same, for a chosen contact (else the system's target, else the most threatening).
pub fn battle_reason_at(&self, index: usize, chosen: Option<u32>) -> Option<BattleReason> {
let sam = self.sams.get(index)?;
let spec = sam.kind.spec();
let now = self.tick;
let channels = (spec.sensor > 0.0 && sam.mode != battery::SamMode::LauncherOnly && sam.radar_profile().channels > 0)
.then(|| (sam.own_channels_used(), sam.radar_profile().channels));
let reason = |kind, block, target, mark| BattleReason {
kind,
block,
sam: index,
target,
mark,
rounds: sam.missiles,
bursts: sam.bursts,
reloading: sam.reloading,
channels,
};
if !sam.alive() {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Destroyed), None, None));
}
if self.hold {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Hold), None, None));
}
if sam.moving() {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Moving), None, None));
}
if !sam.kind.armed() {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoWeapon), None, None));
}
let (missile_on, guns_on) = engagement_counts(&self.sams);
let drone_at = |id: u32| self.drones.iter().find(|d| d.id == id);
let subject = chosen
.and_then(drone_at)
.filter(|d| d.alive())
.or_else(|| sam.target.or(sam.gun_target).and_then(drone_at).filter(|d| d.alive()))
.or_else(|| {
self.drones
.iter()
.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| {
let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, now) == 0);
area(a).cmp(&area(b)).then(a.threat(sam.pos).total_cmp(&b.threat(sam.pos)))
})
});
let Some(t) = subject else {
let block = if sam.roles == 0 {
BattleBlock::Hold
} else if self.drones.iter().any(|d| d.alive() && sam.seen.contains(&d.id)) {
BattleBlock::OutOfRoles
} else {
BattleBlock::NoTarget
};
return Some(reason(BattleKind::Blocked, Some(block), None, None));
};
let track = sam.track(t.id);
let mark = track.map(|tr| BattleMark::of(self, sam, tr, now));
let has_missile = spec.missile.is_some() && sam.missiles > 0 && sam.part(Part::Launcher) > 0.0;
let has_gun = spec.gun.is_some() && sam.bursts > 0 && sam.part(Part::Gun) > 0.0;
if sam.reloading > 0 || (!has_missile && !has_gun) {
return Some(reason(BattleKind::NoAmmo, None, Some(t.id), mark));
}
if spec.missile.is_some() && sam.part(Part::Launcher) <= 0.0 && !has_gun {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::LauncherDown), Some(t.id), mark));
}
let Some(tr) = track else {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoTrack), Some(t.id), mark));
};
let est = tr.class;
let blocks = target_blocks(sam.roles, Some(tr), now, t);
let claimed_now = claimed(t, &missile_on, sam.target);
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, t, claimed_now);
if blocks & ROLE != 0 && !chance {
return Some(reason(BattleKind::Blocked, Some(if sam.roles == 0 { BattleBlock::Hold } else { BattleBlock::OutOfRoles }), Some(t.id), mark));
}
let doc = &sam.doctrine;
let area = doc.area_blocks(sam.pos, tr, now);
let reserve = spec.missile.is_some().then(|| doc.reserve_blocks(sam.missiles, t, est)).unwrap_or(0);
if blocks & ROLE == 0 && (area | reserve) != 0 {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Doctrine), Some(t.id), mark));
}
let est_at = tr.est(now);
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 = spec.missile.as_ref().is_some_and(|load| {
self.drones.iter().any(|o| {
sam.track(o.id).is_some_and(|other| {
allowed(sam.roles, other, now, o)
&& in_reach(load.min, load.max, 1.0, sam.pos, other.est(now))
&& doc.area_blocks(sam.pos, other, now) | doc.reserve_blocks(sam.missiles, o, other.class) == 0
&& claimed(o, &missile_on, sam.target) < doc.needed(o, other.class)
})
})
});
let reach = spec.missile.as_ref().map_or(0, |load| reach_blocks(load.min, load.max, 1.0, sam.pos, est_at));
let far_ok = spec.missile.as_ref().is_some_and(|load| {
reach == TOO_FAR
&& reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0
&& far_blocks(self.far_shots, sam, load, cued, role_in_reach) == 0
});
if spec.missile.is_some() {
if reach == TOO_CLOSE || (reach == TOO_FAR && !far_ok) {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::OutOfReach), Some(t.id), mark));
}
} else if let Some(gun) = &spec.gun {
if sam.mount().0.distance(est_at) >= gun.range {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::OutOfReach), Some(t.id), mark));
}
}
let own_fire = tr.own_authorizes(now);
let gun_ready = spec.gun.is_some() && tr.own_within(now, sight::GUN_PICK_AGE);
let authorized = if spec.missile.is_some() {
own_fire || (sam.mode == battery::SamMode::LauncherOnly && cued) || far_ok
} else {
gun_ready
};
if !authorized {
if sam.mode == battery::SamMode::LauncherOnly {
// The launcher's picture is the supporting radar's. If that radar has the
// contact but every tracked-contact channel is taken, the reason is the
// channels, not a missing hand-off.
let support = radars.iter().find_map(|r| {
let linked = r.alive()
&& !r.moving()
&& r.radar_up()
&& r.radar_profile().products & battery::RadarProfile::FIRE_BIT != 0
&& r.link_range() > 0.0
&& sam.link_range() > 0.0
&& r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range());
linked.then(|| r.track(t.id).map(|tr| (*r, *tr))).flatten()
});
if let Some((radar, tr)) = support {
let profile = radar.radar_profile();
let used = radar.own_channels_used();
if profile.channels > 0 && used >= profile.channels as usize && !tr.own_authorizes(now) {
let mut busy = reason(BattleKind::ChannelsBusy, None, Some(t.id), mark);
busy.channels = Some((used, profile.channels));
return Some(busy);
}
}
return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark));
}
let busy = channels.is_some_and(|(used, total)| used >= total as usize);
if busy {
return Some(reason(BattleKind::ChannelsBusy, None, Some(t.id), mark));
}
if tr.own_tick > 0 && tr.own_product == battery::Measure::Refine {
return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark));
}
if tr.own_tick > 0 && tr.own_product == battery::Measure::Fire {
return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark));
}
return Some(reason(BattleKind::ObserveOnly, None, Some(t.id), mark));
}
let need = doc.needed(t, est);
if spec.missile.is_some() && claimed_now >= need {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Claimed), Some(t.id), mark));
}
if spec.missile.is_none() && guns_on.get(&t.id).copied().unwrap_or(0) > 1 {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Claimed), Some(t.id), mark));
}
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_at, tr.vel, lead_speed);
if aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch) >= 0.15 {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Aiming), Some(t.id), mark));
}
if sam.preparing.is_some() {
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Preparing), Some(t.id), mark));
}
Some(reason(BattleKind::Ready, None, Some(t.id), mark))
}
}
#[derive(Debug, PartialEq)]
@@ -310,6 +616,20 @@ fn check(ok: bool, text: impl Into<String>) -> Check {
Check { ok, reason: CheckReason::Text(text.into()) }
}
fn part_check(reason: CheckReason) -> Check { Check { ok: false, reason } }
fn battle_check(reason: Option<BattleReason>) -> Check {
let reason = reason.unwrap_or(BattleReason {
kind: BattleKind::Blocked,
block: Some(BattleBlock::Other),
sam: 0,
target: None,
mark: None,
rounds: 0,
bursts: 0,
reloading: 0,
channels: None,
});
Check { ok: reason.ready(), reason: CheckReason::Battle(reason) }
}
impl Sim {
/// Why system `index` fires or doesn't, at its current target or at the most threatening
@@ -321,14 +641,17 @@ impl Sim {
let mut v = vec![check(true, format!("№{} {}: {}", index + 1, spec.name, sam.state.name()))];
if !sam.alive() {
v.push(check(false, "уничтожен"));
v.push(battle_check(self.battle_reason(index)));
return v;
}
if self.hold {
v.push(check(false, "огонь запрещён (/airdef hold off)"));
v.push(battle_check(self.battle_reason(index)));
return v;
}
if sam.moving() {
v.push(check(false, format!("{}: не стреляет", sam.state.name().to_lowercase())));
v.push(battle_check(self.battle_reason(index)));
return v;
}
if !sam.kind.armed() {
@@ -364,6 +687,7 @@ impl Sim {
}
}
v.push(check(false, "нет оружия (РЛС, склад, РЭБ, прожектор)"));
v.push(battle_check(self.battle_reason(index)));
return v;
}
let logistics = self.logistics();
@@ -430,6 +754,7 @@ impl Sim {
format!("нет целей классов [{}]", roles_text(sam.roles))
};
v.push(check(false, text));
v.push(battle_check(self.battle_reason(index)));
return v;
};
let held = sam.target == Some(t.id) || sam.gun_target == Some(t.id);
@@ -644,6 +969,21 @@ impl Sim {
fires &= !opening;
}
v.push(check(fires, if fires { "итог: готова стрелять" } else { "итог: стрелять сейчас не может" }));
// The one typed reason the monitor, the HUD and the chat show first; the detailed checks
// below it explain it. The launch decision above has the final word.
let mut headline = self.battle_reason_at(index, Some(t.id)).unwrap_or_else(|| BattleReason {
kind: BattleKind::Blocked,
block: Some(BattleBlock::Other),
sam: index,
target: Some(t.id),
mark: track.map(|tr| BattleMark::of(self, sam, tr, now)),
rounds: sam.missiles,
bursts: sam.bursts,
reloading: sam.reloading,
channels: None,
});
headline.settle(fires);
v.insert(1, Check { ok: headline.ready(), reason: CheckReason::Battle(headline) });
v
}
}
@@ -1016,6 +1356,129 @@ mod tests {
assert!((reach_fit(100.0, 400.0) - 0.5).abs() < 1e-9);
}
/// A track as the battery's picture holds it, from `source`, measured by the battery's own
/// radar `own` ticks ago.
fn seeded_track(id: u32, source: u32, own_tick: u64, product: battery::Measure, now: u64) -> Track {
Track {
id,
class: ClassEst::Firm(Class::Drone),
pos: DVec3::new(0.0, 75.0, -100.0),
vel: DVec3::Z,
tick: now,
own_tick,
source,
product,
quality: 90,
own_product: product,
own_quality: if own_tick > 0 { 90 } else { 0 },
ttl: 400,
hits: 3,
locked: false,
}
}
#[test]
fn the_headline_reason_names_observation_waiting_channels_and_ammo() {
// Есть только обзор: the contact is on the network's picture, the battery's own radar
// has no fire plot, and no channel of its own is taken.
let mut sim = Sim::new(7);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Pantsir, DVec3::new(0.0, 70.0, 0.0), 0.0));
let radar = sim.id();
sim.sams.push(Sam::new(radar, SamKind::Radar, DVec3::new(50.0, 70.0, 0.0), 0.0));
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -100.0), DVec3::Z, DVec3::new(0.0, 70.0, -100.0));
let target = sim.drones[0].id;
let now = sim.tick;
sim.sams[0].tracks.push(seeded_track(target, radar, 0, battery::Measure::Search, now));
let reason = sim.battle_reason(0).expect("a reason");
assert_eq!(reason.kind, BattleKind::ObserveOnly, "{reason:?}");
let mark = reason.mark.expect("the mark");
assert_eq!(mark.source, Some(1));
assert!(!mark.own);
assert_eq!(mark.age, 0);
// Ждёт сопровождения: a launcher without its own radar waits for the supporting radar's
// fire plot; the same network mark is not enough.
let mut sim = Sim::new(8);
let id = sim.id();
let mut launcher = Sam::new(id, SamKind::S400, DVec3::new(0.0, 70.0, 0.0), 0.0);
launcher.set_mode(battery::SamMode::LauncherOnly);
sim.sams.push(launcher);
let radar = sim.id();
let mut station = Sam::new(radar, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0), 0.0);
station.set_radar_role(battery::RadarRole::Engagement);
sim.sams.push(station);
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, -300.0), DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
let target = sim.drones[0].id;
let now = 1;
sim.sams[0].tracks.push(seeded_track(target, radar, 0, battery::Measure::Search, now));
assert_eq!(sim.battle_reason(0).expect("a reason").kind, BattleKind::AwaitingTrack);
// Каналы заняты: the supporting radar has the contact but both tracked-contact channels
// are held by other contacts.
sim.sams[1].tracks.push(seeded_track(901, radar, now, battery::Measure::Fire, now));
sim.sams[1].tracks.push(seeded_track(902, radar, now, battery::Measure::Fire, now));
sim.sams[1].tracks.push(seeded_track(target, radar, now, battery::Measure::Search, now));
let reason = sim.battle_reason(0).expect("a reason");
assert_eq!(reason.kind, BattleKind::ChannelsBusy, "{reason:?}");
assert_eq!(reason.channels, Some((2, 2)));
// Нет боезапаса: no rounds and no shells.
let mut sim = Sim::new(9);
let id = sim.id();
let mut sam = Sam::new(id, SamKind::Pantsir, DVec3::new(0.0, 70.0, 0.0), 0.0);
sam.missiles = 0;
sam.bursts = 0;
sim.sams.push(sam);
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -100.0), DVec3::Z, DVec3::new(0.0, 70.0, -100.0));
let target = sim.drones[0].id;
let now = sim.tick;
sim.sams[0].tracks.push(seeded_track(target, id, now, battery::Measure::Fire, now));
let reason = sim.battle_reason(0).expect("a reason");
assert_eq!(reason.kind, BattleKind::NoAmmo, "{reason:?}");
assert_eq!((reason.rounds, reason.bursts), (0, 0));
}
#[test]
fn the_headline_reason_can_say_ready_and_defers_to_the_launch_decision() {
let mut sim = Sim::new(11);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, DVec3::new(0.0, 70.0, 0.0), 0.0));
sim.sams[0].cooldown = 0;
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, -300.0), DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
let d = sim.drones[0].clone();
let now = 1;
sim.sams[0].yaw = heading_of(d.pos - sim.sams[0].pos);
sim.sams[0].tracks.push(Track {
id: d.id,
class: ClassEst::Firm(Class::Cruise),
pos: d.pos,
vel: d.vel,
tick: now,
own_tick: now,
source: id,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 400,
hits: 3,
locked: false,
});
let reason = sim.battle_reason(0).expect("a reason");
assert_eq!(reason.kind, BattleKind::Ready, "{reason:?}");
// The detailed decision is the authority when the two are settled together.
let mut blocked = reason;
blocked.settle(false);
assert_eq!(blocked.kind, BattleKind::Blocked);
let mut ready = reason;
ready.settle(true);
assert_eq!(ready.kind, BattleKind::Ready);
// In the diagnostic the typed line is the headline, second only to the state.
let checks = sim.why(0);
assert!(matches!(checks.get(1).map(|c| &c.reason), Some(CheckReason::Battle(r)) if r.kind == BattleKind::Ready), "{checks:?}");
}
#[test]
fn every_interceptor_lives_long_enough_to_fly_its_reach() {
// Life × top speed must cover the far end of a heavy system's reach with room to chase; the rest their plain reach.