Represent damage diagnostics as typed reasons

Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
2026-11-04 15:57:46 +03:00
parent eea1b3692e
commit 0c870c10d5
8 changed files with 127 additions and 31 deletions
+53 -24
View File
@@ -250,15 +250,42 @@ pub(super) fn gun_blocks(s: &Sam, aim_id: u32, gt: u32, aim_error: f64, dist: f6
// ---------------------------------------------------------------- the diagnostic
/// One condition and whether it holds.
/// A diagnostic condition and its structured or legacy reason.
#[derive(Debug)]
pub struct Check {
pub ok: bool,
pub text: String,
pub reason: CheckReason,
}
#[derive(Debug)]
pub enum CheckReason {
/// Diagnostics not yet migrated to typed reasons.
Text(String),
Parts(Vec<(Part, f64)>),
PartEffect(PartEffect),
}
#[derive(Debug, PartialEq)]
pub enum PartEffect {
SensorFailed, SensorDamaged { fit: f64 },
MountFailed { yaw_degrees: f64 }, MountDamaged { fit: f64 },
LauncherFailed, LauncherDamaged { cells: u32, capacity: u32, reload_seconds: f64 },
GunFailed, GunDamaged { fit: f64 },
TracksFailed, TracksDamaged { speed: f64 },
CommsFailed, CommsDamaged { range: f64 },
}
impl Check {
#[cfg(test)]
pub(super) fn legacy_text(&self) -> &str {
match &self.reason { CheckReason::Text(text) => text, _ => "" }
}
}
fn check(ok: bool, text: impl Into<String>) -> Check {
Check { ok, text: text.into() }
Check { ok, reason: CheckReason::Text(text.into()) }
}
fn part_check(reason: CheckReason) -> Check { Check { ok: false, reason } }
impl Sim {
/// Why system `index` fires or doesn't, at its current target or at the most threatening
@@ -293,7 +320,9 @@ impl Sim {
v.push(check(alive > 0, format!("в небе {alive}, на картине {seen} (своя РЛС {own}, остальные по сети)")));
// The parts: what is worn or failed and what it costs.
if !sam.comps.whole() {
v.push(check(false, format!("узлы: {}", sam.parts_text())));
let parts = Part::ALL.into_iter().filter(|p| p.on(sam.kind) && sam.comps.get(*p) < 1.0)
.map(|p| (p, sam.comps.get(p))).collect();
v.push(part_check(CheckReason::Parts(parts)));
}
for p in Part::ALL {
if !p.on(sam.kind) || sam.part_state(p) == PartState::Ok {
@@ -301,20 +330,20 @@ impl Sim {
}
let failed = sam.part_state(p) == PartState::Failed;
let effect = match (p, failed) {
(Part::Sensor, true) => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".to_string(),
(Part::Sensor, false) => format!("РЛС повреждена: дальность {:.0}%, обзор вдвое реже при худшем", sam.radar_fit() * 100.0),
(Part::Mount, true) => format!("привод наведения заклинил: стоит на {:.0}°, не доворачивается", sam.yaw.to_degrees().rem_euclid(360.0)),
(Part::Mount, false) => format!("привод наведения повреждён: поворот {:.0}% от нормы", sam.drive_fit() * 100.0),
(Part::Launcher, true) => "пусковая отказала: пуски невозможны".to_string(),
(Part::Launcher, false) => format!("пусковая повреждена: {} ячеек из {}, перезарядка {:.0} с", sam.cells(), spec.missile.as_ref().map_or(0, |m| m.magazine), sam.reload_time() as f64 / 20.0),
(Part::Gun, true) => "орудие заклинило: не стреляет".to_string(),
(Part::Gun, false) => format!("орудие повреждено: меткость {:.0}%, заклинивает", sam.gun_fit() * 100.0),
(Part::Tracks, true) => "ходовая отказала: на марш не выйдет".to_string(),
(Part::Tracks, false) => format!("ходовая повреждена: скорость марша {:.0}%", sam.drive_speed() * 100.0),
(Part::Comms, true) => "связь отказала: сети нет, цели только свои".to_string(),
(Part::Comms, false) => format!("связь повреждена: линия {:.0} м", sam.link_range()),
(Part::Sensor, true) => PartEffect::SensorFailed,
(Part::Sensor, false) => PartEffect::SensorDamaged { fit: sam.radar_fit() },
(Part::Mount, true) => PartEffect::MountFailed { yaw_degrees: sam.yaw.to_degrees().rem_euclid(360.0) },
(Part::Mount, false) => PartEffect::MountDamaged { fit: sam.drive_fit() },
(Part::Launcher, true) => PartEffect::LauncherFailed,
(Part::Launcher, false) => PartEffect::LauncherDamaged { cells: sam.cells(), capacity: spec.missile.as_ref().map_or(0, |m| m.magazine), reload_seconds: sam.reload_time() as f64 / 20.0 },
(Part::Gun, true) => PartEffect::GunFailed,
(Part::Gun, false) => PartEffect::GunDamaged { fit: sam.gun_fit() },
(Part::Tracks, true) => PartEffect::TracksFailed,
(Part::Tracks, false) => PartEffect::TracksDamaged { speed: sam.drive_speed() },
(Part::Comms, true) => PartEffect::CommsFailed,
(Part::Comms, false) => PartEffect::CommsDamaged { range: sam.link_range() },
};
v.push(check(false, effect));
v.push(part_check(CheckReason::PartEffect(effect)));
}
if sam.jam > 0 {
v.push(check(false, format!("орудие заклинило, ещё {:.1} с", sam.jam as f64 / 20.0)));
@@ -551,10 +580,10 @@ mod tests {
sim.step(&mut ground, None, &mut out);
}
let w = sim.why(0);
assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
assert!(w.iter().any(|c| c.text.contains("нет целей классов")));
assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
assert!(w.iter().any(|c| c.legacy_text().contains("нет целей классов")));
sim.sams[0].roles = 0xFF;
assert!(sim.why(0).iter().any(|c| c.text.starts_with("роль")));
assert!(sim.why(0).iter().any(|c| c.legacy_text().starts_with("роль")));
}
use super::sites::testland::{Land, serve};
@@ -599,7 +628,7 @@ mod tests {
sim.step(&mut ground, None, &mut out);
}
let w = sim.why(0);
assert!(w.iter().any(|c| c.ok && c.text.starts_with("последний шанс")), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
assert!(w.iter().any(|c| c.ok && c.legacy_text().starts_with("последний шанс")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
}
#[test]
@@ -610,8 +639,8 @@ mod tests {
assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a Shahed far from its aim");
let w = sim.why(0);
// Still named as the role block it was: no target of its classes.
assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.text.contains("нет целей классов")), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
assert!(!w.iter().any(|c| c.text.starts_with("последний шанс")));
assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.legacy_text().contains("нет целей классов")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс")));
}
#[test]
@@ -678,7 +707,7 @@ mod tests {
let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4);
assert!(fire_far(&mut sim, &mut ground, &land, &mut out, 80) >= 1, "no long shot at 1.4 x max with a radar");
let w = sim.why(0);
assert!(w.iter().any(|c| c.text.starts_with("дальний пуск по РЛС")), "{:?}", w.iter().map(|c| &c.text).collect::<Vec<_>>());
assert!(w.iter().any(|c| c.legacy_text().starts_with("дальний пуск по РЛС")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
// No radar, no shot (the system's own radar may well see it: that is not a cue).
let (mut sim, mut ground, land, mut out) = far_setup(false, max * 1.4);
assert_eq!(fire_far(&mut sim, &mut ground, &land, &mut out, 80), 0, "a long shot with no radar");