Files
airdef/airdef-mod/src/sim/breakthrough.rs
T

270 lines
9.6 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.
//! Bounded, observed facts about impacts. This is session history, not save data.
use super::*;
const MAX_ACTIVE: usize = 4096;
const MAX_HITS: usize = 128;
const PAGE_SIZE: usize = 3;
#[derive(Clone, Copy, Default)]
pub(super) struct FlightFacts {
/// False when observation began after the flight began, or after a load.
complete: bool,
pub(super) first: Option<(u64, u32)>,
launches: u32,
}
impl FlightFacts {
pub(super) fn new(complete: bool) -> Self {
Self {
complete,
..Default::default()
}
}
}
struct Hit {
tick: u64,
id: u32,
kind: DroneKind,
pos: DVec3,
object: Option<usize>,
facts: Option<FlightFacts>,
nearby: Vec<BatterySnapshot>,
}
struct BatterySnapshot {
kind: SamKind,
reason: why::BattleReason,
terrain_blocked: bool,
}
#[derive(Default)]
pub(super) struct Breakthroughs {
pub(super) active: HashMap<u32, FlightFacts>,
hits: VecDeque<Hit>,
}
impl Breakthroughs {
pub(super) fn begin(&mut self, id: u32, complete: bool) {
if self.active.len() < MAX_ACTIVE {
self.active.insert(id, FlightFacts::new(complete));
}
}
pub(super) fn bytes(&self) -> usize {
use super::memory::{map_bytes, vec_bytes, vecdeque_bytes};
map_bytes(
self.active.capacity(),
std::mem::size_of::<(u32, FlightFacts)>(),
) + vecdeque_bytes(&self.hits)
+ self
.hits
.iter()
.map(|h| vec_bytes(&h.nearby))
.sum::<usize>()
}
}
impl Sim {
/// Clears the displayed history; observation of flights already in progress continues.
pub fn clear_breakthroughs(&mut self) {
self.breakthroughs.hits.clear();
}
pub(super) fn breakthrough_launch(&mut self, id: u32) {
if let Some(facts) = self.breakthroughs.active.get_mut(&id) {
facts.launches = facts.launches.saturating_add(1);
}
}
pub(super) fn breakthrough_hit(
&mut self,
id: u32,
kind: DroneKind,
pos: DVec3,
object: Option<usize>,
) {
// Only the nearest three armed systems; this runs once per impact, not per tick.
let mut nearest: Vec<_> = self
.sams
.iter()
.enumerate()
.filter(|(_, s)| s.kind.armed())
.map(|(i, s)| (i, s.pos.distance_squared(pos)))
.collect();
nearest.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
let nearby = nearest
.into_iter()
.take(3)
.filter_map(|(i, _)| {
let sam = &self.sams[i];
Some(BatterySnapshot {
kind: sam.kind,
reason: self.battle_reason_at(i, Some(id))?,
terrain_blocked: sam.terrain_verdict(id, self.tick).is_some_and(|v| v != 0),
})
})
.collect();
let hit = Hit {
tick: self.tick,
id,
kind,
pos,
object,
facts: self.breakthroughs.active.get(&id).copied(),
nearby,
};
if self.breakthroughs.hits.len() == MAX_HITS {
self.breakthroughs.hits.pop_front();
}
self.breakthroughs.hits.push_back(hit);
}
pub fn breakthrough_pages(&self) -> usize {
self.breakthroughs.hits.len().div_ceil(PAGE_SIZE)
}
/// Most recent recorded impacts, three per page. Page is zero-based.
pub fn breakthrough_page(&self, page: usize) -> String {
let total = self.breakthroughs.hits.len();
if total == 0 {
return "Прорывов в истории нет".into();
}
let pages = self.breakthrough_pages();
if page >= pages {
return format!("Нет страницы {}. Страниц: {pages}", page.saturating_add(1));
}
let mut lines = vec![format!(
"Прорывы: страница {}/{} (последние {total})",
page + 1,
pages
)];
for hit in self
.breakthroughs
.hits
.iter()
.rev()
.skip(page * PAGE_SIZE)
.take(PAGE_SIZE)
{
let detection = match hit.facts {
Some(f) if f.complete => match f.first {
Some((t, radar)) => format!(
"первое измерение РЛС id {radar}: тик {t}, за {:.1} с до удара",
hit.tick.saturating_sub(t) as f64 / 20.0
),
None => "своих измерений РЛС не было".into(),
},
Some(f) => match f.first {
Some((t, radar)) => format!(
"первое известное измерение РЛС id {radar}: тик {t} (предыдущее неизвестно)"
),
None => "обнаружение до загрузки или начала наблюдения неизвестно".into(),
},
None => "данные обнаружения недоступны".into(),
};
let launches = hit.facts.map_or("пуски неизвестны".to_string(), |f| {
if f.complete {
format!("пусков: {}", f.launches)
} else {
format!("известных пусков: {} (предыдущие неизвестны)", f.launches)
}
});
let object = hit
.object
.map_or_else(String::new, |i| format!(" · объект №{}", i + 1));
lines.push(format!(
"{} №{} · ({:.0}, {:.0}, {:.0}){object}",
hit.kind.spec().name,
hit.id,
hit.pos.x,
hit.pos.y,
hit.pos.z
));
lines.push(format!("{detection} · {launches}"));
if !hit.nearby.is_empty() {
lines.push("Снимок перед ударом · ближайшие комплексы".into());
for battery in &hit.nearby {
let terrain = if battery.terrain_blocked {
" · рельеф перекрывал траекторию"
} else {
""
};
lines.push(format!(
"{} №{} · {}{terrain}",
battery.kind.name(),
battery.reason.sam + 1,
reason_text(&battery.reason),
));
}
}
}
lines.join("\n")
}
}
fn reason_text(reason: &why::BattleReason) -> &'static str {
use why::{BattleBlock as B, BattleKind as K};
match reason.kind {
K::Ready => "готов к пуску",
K::ObserveOnly => "только обзор",
K::AwaitingTrack => "ждёт сопровождения",
K::ChannelsBusy => "каналы заняты",
K::NoAmmo => "нет боезапаса или перезарядка",
K::Blocked => match reason.block {
Some(B::Destroyed) => "уничтожен",
Some(B::Moving) => "на марше",
Some(B::Hold) => "огонь запрещён",
Some(B::NoWeapon) => "нет оружия",
Some(B::NoTarget) => "нет цели",
Some(B::NoTrack) => "нет трассы",
Some(B::ClassPending) => "ждёт подтверждения класса цели",
Some(B::OutOfRoles) => "вне ролей",
Some(B::OutOfReach) => "вне дальности",
Some(B::Claimed) => "занята перехватчиками",
Some(B::Doctrine) => "доктрина",
Some(B::Aiming) => "наводится",
Some(B::Preparing) => "подготовка пуска",
Some(B::LauncherDown) => "пусковая отказала",
Some(B::Other) | None => "другая причина",
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn impact_history_is_bounded_and_pages_are_safe() {
let mut sim = Sim::new(1);
for id in 0..130 {
sim.tick = id as u64;
sim.breakthrough_hit(id, DroneKind::Geran3, DVec3::ZERO, None);
}
assert_eq!(sim.breakthroughs.hits.len(), MAX_HITS);
assert!(sim.breakthrough_page(0).contains("№129"));
assert!(sim.breakthrough_page(usize::MAX).contains("Нет страницы"));
sim.clear_breakthroughs();
assert!(sim.breakthrough_page(0).contains("истории нет"));
}
#[test]
fn detection_and_launches_distinguish_complete_and_partial_history() {
let mut sim = Sim::new(1);
sim.tick = 20;
sim.breakthroughs.active.insert(1, FlightFacts::new(true));
sim.breakthrough_launch(1);
sim.breakthrough_hit(1, DroneKind::Geran3, DVec3::ZERO, None);
let page = sim.breakthrough_page(0);
assert!(page.contains("измерений РЛС не было"));
assert!(page.contains("пусков: 1"));
sim.breakthroughs.active.insert(2, FlightFacts::new(false));
sim.breakthrough_hit(2, DroneKind::Geran3, DVec3::ZERO, None);
assert!(
sim.breakthrough_page(0)
.contains("до загрузки или начала наблюдения неизвестно")
);
}
}