Files
airdef/airdef-mod/src/why_view.rs
T
chexit 8afe691301
build / mod (push) Failing after 32s
Add typed battle reasons and short engagement chains (#148)
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>
2026-11-21 09:42:10 +03:00

208 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Text for diagnostics produced by the simulation.
use crate::sim::why::{BattleBlock, BattleKind, BattleMark, BattleReason, CheckReason, PartEffect};
use crate::sim::{Comps, Part, SamKind};
fn part_value(part: Part, value: f64) -> String {
if value <= 0.0 { format!("{} отказ", part.short()) }
else { format!("{} {:.0}%", part.short(), value * 100.0) }
}
fn part_value_on(part: Part, value: f64, kind: SamKind) -> String {
if value <= 0.0 { format!("{} отказ", part.short_on(kind)) }
else { format!("{} {:.0}%", part.short_on(kind), value * 100.0) }
}
/// Every worn or failed part of a system, as the monitor and the status line read it.
pub fn parts(comps: &Comps, kind: SamKind) -> String {
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
.map(|p| part_value_on(*p, comps.get(*p), kind)).collect::<Vec<_>>().join(", ")
}
/// The weakest worn or failed part alone, for a one-line status.
pub fn worst(comps: &Comps, kind: SamKind) -> String {
Part::ALL.iter().filter(|p| p.on(kind) && comps.get(**p) < 1.0)
.min_by(|a, b| comps.get(**a).total_cmp(&comps.get(**b)))
.map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default()
}
/// The mark's age and where it came from, in the battery's own picture: a relayed plot names
/// its station, never the target's true place or kind.
fn mark_text(mark: &BattleMark) -> String {
let age = if mark.age == 0 { "сейчас".to_string() } else { format!("{:.1} с назад", mark.age as f64 / 20.0) };
let source = if mark.own {
"своя РЛС".to_string()
} else {
mark.source.map_or_else(|| "сеть".to_string(), |i| format!("сеть, РЛС №{}", i + 1))
};
let mut own = String::new();
if let Some(product) = mark.own_product {
if !mark.own {
own = format!(", своё измерение: {}", product.name());
}
}
let forecast = if mark.forecast { ", прогноз" } else { "" };
format!(
"отметка {age}, источник {source}, {} кач.{} {}{}{forecast}",
mark.product.name(),
mark.quality,
mark.class.name(),
own
)
}
fn with_mark(text: String, mark: Option<BattleMark>) -> String {
match mark {
Some(mark) => format!("{text}: {}", mark_text(&mark)),
None => text,
}
}
/// The one headline reason a battery fires or not, as the player reads it.
pub fn battle_text(reason: &BattleReason) -> String {
match reason.kind {
BattleKind::Ready => with_mark("готов к пуску".into(), reason.mark),
BattleKind::ObserveOnly => with_mark("есть только обзор, пуск не разрешён — нужно своё подтверждённое измерение".into(), reason.mark),
BattleKind::AwaitingTrack => with_mark("ждёт сопровождения — своё измерение ещё не разрешает пуск".into(), reason.mark),
BattleKind::ChannelsBusy => {
let channels = reason.channels.map_or_else(|| "каналы заняты".to_string(), |(used, total)| format!("каналы заняты: {used}/{total}"));
with_mark(channels, reason.mark)
}
BattleKind::NoAmmo => {
let mut text = format!("нет боезапаса: ракет {}, очередей {}", reason.rounds, reason.bursts);
if reason.reloading > 0 {
text += &format!(", перезарядка ещё {:.1} с", reason.reloading as f64 / 20.0);
}
with_mark(text, reason.mark)
}
BattleKind::Blocked => {
let text = match reason.block {
Some(BattleBlock::Destroyed) => "уничтожен".to_string(),
Some(BattleBlock::Moving) => "на марше, не стреляет".to_string(),
Some(BattleBlock::Hold) => "огонь запрещён или роли не заданы".to_string(),
Some(BattleBlock::NoWeapon) => "нет оружия (РЛС, склад, РЭБ, прожектор)".to_string(),
Some(BattleBlock::NoTarget) => "нет целей в небе".to_string(),
Some(BattleBlock::NoTrack) => "цель не обнаружена своей РЛС или сетью".to_string(),
Some(BattleBlock::OutOfRoles) => "цель вне ролей комплекса".to_string(),
Some(BattleBlock::OutOfReach) => "цель вне дальности".to_string(),
Some(BattleBlock::Claimed) => "цель уже занята перехватчиками".to_string(),
Some(BattleBlock::Doctrine) => "запрещено доктриной (сектор, охрана или резерв)".to_string(),
Some(BattleBlock::Aiming) => "ещё доворачивается на цель".to_string(),
Some(BattleBlock::Preparing) => "открывает ТПК".to_string(),
Some(BattleBlock::LauncherDown) => "пусковая отказала".to_string(),
Some(BattleBlock::Other) | None => "стрелять сейчас не может".to_string(),
};
with_mark(text, reason.mark)
}
}
}
pub fn reason(reason: &CheckReason) -> String {
match reason {
CheckReason::Text(text) => text.clone(),
CheckReason::Battle(battle) => battle_text(battle),
CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| part_value(*part, *value)).collect::<Vec<_>>().join(", ")),
CheckReason::PartEffect(effect) => match effect {
PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(),
PartEffect::SensorDamaged { fit } => format!("РЛС повреждена: дальность {:.0}%, обзор вдвое реже при худшем", fit * 100.0),
PartEffect::MountFailed { yaw_degrees } => format!("привод наведения заклинил: стоит на {yaw_degrees:.0}°, не доворачивается"),
PartEffect::MountDamaged { fit } => format!("привод наведения повреждён: поворот {:.0}% от нормы", fit * 100.0),
PartEffect::LauncherFailed => "пусковая отказала: пуски невозможны".into(),
PartEffect::LauncherDamaged { cells, capacity, reload_seconds } => format!("пусковая повреждена: {cells} ячеек из {capacity}, перезарядка {reload_seconds:.0} с"),
PartEffect::GunFailed => "орудие заклинило: не стреляет".into(),
PartEffect::GunDamaged { fit } => format!("орудие повреждено: меткость {:.0}%, заклинивает", fit * 100.0),
PartEffect::TracksFailed => "ходовая отказала: на марш не выйдет".into(),
PartEffect::TracksDamaged { speed } => format!("ходовая повреждена: скорость марша {:.0}%", speed * 100.0),
PartEffect::CommsFailed => "связь отказала: сети нет, цели только свои".into(),
PartEffect::CommsDamaged { range } => format!("связь повреждена: линия {range:.0} м"),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::{Comps, Part, SamKind};
#[test]
fn renders_worn_parts_without_the_reason_prefix() {
let mut comps = Comps([1.0; 6]);
comps.0[Part::Sensor as usize] = 0.4;
comps.0[Part::Tracks as usize] = 0.0;
assert_eq!(parts(&comps, SamKind::Pantsir), "РЛС 40%, Ход отказ");
assert_eq!(worst(&comps, SamKind::Pantsir), "Ход отказ");
// A passive post's sensor is optics; only its sensor is fitted.
let mut optics = Comps([1.0; 6]);
optics.0[Part::Sensor as usize] = 0.4;
assert_eq!(parts(&optics, SamKind::Optical), "Опт 40%");
}
#[test]
fn damaged_simulation_produces_player_diagnostics_in_order() {
use crate::sim::{Sam, SamKind, Sim};
let mut sim = Sim::new(1);
let mut sam = Sam::new(1, SamKind::Pantsir, glam::DVec3::ZERO, 0.0);
sam.comps.0[Part::Sensor as usize] = 0.4;
sam.comps.0[Part::Tracks as usize] = 0.0;
sim.sams.push(sam);
let lines: Vec<String> = sim.why(0).iter().map(|c| reason(&c.reason)).collect();
let summary = lines.iter().position(|s| s == "узлы: РЛС 40%, Ход отказ").unwrap();
let sensor = lines.iter().position(|s| s.starts_with("РЛС повреждена: дальность ")).unwrap();
let tracks = lines.iter().position(|s| s == "ходовая отказала: на марш не выйдет").unwrap();
assert!(summary < sensor && sensor < tracks, "{lines:?}");
}
#[test]
fn the_headline_reason_shows_the_marks_age_and_source_without_the_true_kind() {
use crate::sim::battery::Measure;
use crate::sim::ClassEst;
let mark = BattleMark {
age: 46,
own_age: None,
source: Some(2),
own: false,
product: Measure::Search,
quality: 40,
own_product: None,
forecast: false,
class: ClassEst::Unknown,
};
let reason = BattleReason {
kind: BattleKind::ObserveOnly,
block: None,
sam: 0,
target: Some(7),
mark: Some(mark),
rounds: 4,
bursts: 0,
reloading: 0,
channels: None,
};
let text = battle_text(&reason);
assert!(text.starts_with("есть только обзор"), "{text}");
assert!(text.contains("2.3 с назад"), "{text}");
assert!(text.contains("источник сеть, РЛС №3"), "{text}");
assert!(text.contains("тип не определён"), "{text}");
assert!(!text.contains("Шахед"), "the true kind leaked into the HUD: {text}");
}
#[test]
fn renders_damage_diagnostics() {
assert_eq!(reason(&CheckReason::Parts(vec![(Part::Sensor, 0.4), (Part::Tracks, 0.0)])), "узлы: РЛС 40%, Ход отказ");
let cases = [
(PartEffect::SensorFailed, "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети"),
(PartEffect::SensorDamaged { fit: 0.4 }, "РЛС повреждена: дальность 40%, обзор вдвое реже при худшем"),
(PartEffect::MountFailed { yaw_degrees: 42.0 }, "привод наведения заклинил: стоит на 42°, не доворачивается"),
(PartEffect::MountDamaged { fit: 0.3 }, "привод наведения повреждён: поворот 30% от нормы"),
(PartEffect::LauncherFailed, "пусковая отказала: пуски невозможны"),
(PartEffect::LauncherDamaged { cells: 2, capacity: 4, reload_seconds: 12.0 }, "пусковая повреждена: 2 ячеек из 4, перезарядка 12 с"),
(PartEffect::GunFailed, "орудие заклинило: не стреляет"),
(PartEffect::GunDamaged { fit: 0.5 }, "орудие повреждено: меткость 50%, заклинивает"),
(PartEffect::TracksFailed, "ходовая отказала: на марш не выйдет"),
(PartEffect::TracksDamaged { speed: 0.2 }, "ходовая повреждена: скорость марша 20%"),
(PartEffect::CommsFailed, "связь отказала: сети нет, цели только свои"),
(PartEffect::CommsDamaged { range: 123.0 }, "связь повреждена: линия 123 м"),
];
for (effect, expected) in cases { assert_eq!(reason(&CheckReason::PartEffect(effect)), expected); }
}
}