diff --git a/README.md b/README.md index 72f4bf0..85b5b22 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,10 @@ API мода `render.set-lights` (до 512, плавно интерполиру **Командный пункт ПВО:** клавиша **J** или строка «Командный пункт» в меню **N** открывает прокручиваемый список всей развёрнутой техники. Кнопка фильтра перебирает роли и состояния. Для поиска по названию или номеру используйте `/airdef post Панцирь` или `/airdef post 12`. Нажатие на строку открывает карточку. В ней видны текущая причина, -отметка и её источник. Из карточки можно открыть карту, камеру, цепочки последнего повтора и закрепить технику. +отметка и её источник. Из карточки можно открыть карту, камеру, историю решений и закрепить технику. +История показывает отказы на проверке, фактические выстрелы и известные исходы с отметкой, которая была у комплекса +на тот момент. По записи завершившегося налёта можно открыть соответствующий кадр повтора. +История живёт вместе с повторами текущей игровой сессии. В ней доступны последние 128 записей выбранного комплекса. Та же карточка доступна с выбранного маркера на карте **M** и по **I** при открытом мониторе **K**. В мире от первого лица наведите прицел на видимую часть техники на расстоянии до 24 блоков и нажмите **I**. Если между прицелом и моделью есть блок, карточка по наведению не откроется. diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs index 696d564..5e85047 100644 --- a/airdef-mod/src/lib.rs +++ b/airdef-mod/src/lib.rs @@ -235,6 +235,8 @@ enum Page { Post, Unit(u32, post::From), UnitChecks(u32, post::From), + UnitHistory(u32, post::From), + UnitDecision(u32, post::From, usize), /// Fire, repair, effects, damage. More, /// The last raid's events and its replays. @@ -327,6 +329,10 @@ const POST_NEXT: u32 = 75; const POST_CLEAR: u32 = 76; const POST_ACTIONS: u32 = 77; const POST_REFRESH: u32 = 78; +const POST_DECISION_ROWS: u32 = 79; +const POST_DECISION_REPLAY: u32 = 80; +const POST_CHAINS: u32 = 81; +const POST_DECISION_LIMIT: usize = 128; const BTN_BACK: u32 = 199; fn say(text: &str) { @@ -1750,7 +1756,7 @@ impl AirDef { } fn post_open(&self) -> bool { - matches!(self.menu, Some(Page::Post | Page::Unit(..) | Page::UnitChecks(..))) + matches!(self.menu, Some(Page::Post | Page::Unit(..) | Page::UnitChecks(..) | Page::UnitHistory(..) | Page::UnitDecision(..))) } fn open_monitor_card(&mut self) { @@ -1887,7 +1893,7 @@ impl AirDef { { actions.push((Action::Source(source.id), "Источник отметки")); } - actions.push((Action::History, "Цепочки в последнем повторе")); + actions.push((Action::History, "История решений")); actions.push((Action::Pin, if self.post.pinned == Some(id) { "Открепить" } else { "Закрепить в списке и сетке" })); self.post.actions = actions.iter().map(|(action, _)| *action).collect(); widgets.push(Widget::List(ListWidget { id: POST_ACTIONS, rows: actions.into_iter().map(|(_, label)| label.into()).collect(), selected: None })); @@ -1902,6 +1908,43 @@ impl AirDef { }; widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: label.into() })); } + Page::UnitHistory(id, _) => { + let recordings = || self.sim.recording().into_iter().chain(self.sim.replays.iter().rev()); + self.post.decisions = recordings().flat_map(|rec| rec.decisions.entries().rev() + .filter(move |entry| entry.unit == id) + .map(|&entry| post::RecordedChoice { raid: rec.number, entry })) + .take(POST_DECISION_LIMIT + 1) + .collect(); + let shortened = self.post.decisions.len() > POST_DECISION_LIMIT; + self.post.decisions.truncate(POST_DECISION_LIMIT); + title = "Решения комплекса".into(); + if self.post.decisions.is_empty() { + widgets.push(Widget::Text(TextWidget { id: 0, text: "Записей решений нет".into(), color: 0 })); + } else { + if shortened || recordings().any(|rec| rec.decisions.truncated()) { + widgets.push(Widget::Text(TextWidget { id: 0, text: "Показана часть истории".into(), color: 0 })); + } + let rows = self.post.decisions.iter().map(|row| monitor::fit( + format!("№{} {} · {}", row.raid, replay::clock(f64::from(row.entry.at)), post::decision_label(row.entry.outcome)), + 184.0, + )).collect(); + widgets.push(Widget::List(ListWidget { id: POST_DECISION_ROWS, rows, selected: None })); + } + widgets.push(Widget::Button(ButtonWidget { id: POST_CHAINS, label: "Цепочки последнего повтора".into() })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "К карточке".into() })); + } + Page::UnitDecision(_, _, row) => { + let Some(&choice) = self.post.decisions.get(row) else { return }; + let replay = self.sim.replay(choice.raid); + let recording = replay.or_else(|| self.sim.recording().filter(|rec| rec.number == choice.raid)); + title = "Решение на момент боя".into(); + let rows = post::decision_lines(choice, recording).into_iter().flat_map(|line| ui_lines(&line)).collect(); + widgets.push(Widget::List(ListWidget { id: 0, rows, selected: None })); + if replay.is_some() { + widgets.push(Widget::Button(ButtonWidget { id: POST_DECISION_REPLAY, label: "Открыть кадр повтора".into() })); + } + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "К истории".into() })); + } Page::Village => { title = "Оборона деревни".into(); let status = self.village_status(); @@ -1998,7 +2041,7 @@ impl AirDef { })); } } - let back = if self.chain_view.from_unit.is_some() { "К карточке" } else { "К повторам" }; + let back = if self.chain_view.from_unit.is_some() { "К истории" } else { "К повторам" }; widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: back.into() })); } Page::Recon => { @@ -2596,7 +2639,7 @@ impl Mod for AirDef { self.post.source_origin = Some((unit, from)); self.open_menu(Page::Unit(source, post::From::Source)); } - Some(post::Action::History) => self.open_chains(Some((unit, from))), + Some(post::Action::History) => self.open_menu(Page::UnitHistory(unit, from)), Some(post::Action::Pin) => { self.post.pinned = (self.post.pinned != Some(unit)).then_some(unit); self.post.page = 0; @@ -2610,6 +2653,33 @@ impl Mod for AirDef { self.open_menu(Page::Unit(unit, from)); return; } + (Page::UnitHistory(unit, from), POST_DECISION_ROWS) => { + if self.post.decisions.get(row as usize).is_some() { + self.open_menu(Page::UnitDecision(unit, from, row as usize)); + } + return; + } + (Page::UnitHistory(unit, from), POST_CHAINS) => { + self.open_chains(Some((unit, from))); + return; + } + (Page::UnitHistory(unit, from), BTN_BACK) => { + self.open_menu(Page::Unit(unit, from)); + return; + } + (Page::UnitDecision(unit, from, _), BTN_BACK) => { + self.open_menu(Page::UnitHistory(unit, from)); + return; + } + (Page::UnitDecision(_, _, selected), POST_DECISION_REPLAY) => { + if let Some(&choice) = self.post.decisions.get(selected) { + match self.start_chain(choice.raid, None, f64::from(choice.entry.at)) { + Ok(()) => self.close_menu(), + Err(error) => say(&error), + } + } + return; + } (Page::Unit(_, from), BTN_BACK) => { match from { post::From::World => self.close_menu(), @@ -2832,7 +2902,7 @@ impl Mod for AirDef { } (Page::Chains, BTN_BACK) => { match self.chain_view.from_unit { - Some((id, from)) => self.open_menu(Page::Unit(id, from)), + Some((id, from)) => self.open_menu(Page::UnitHistory(id, from)), None => self.open_menu(Page::Replays), } return; diff --git a/airdef-mod/src/post.rs b/airdef-mod/src/post.rs index 2ecc09c..dd303fd 100644 --- a/airdef-mod/src/post.rs +++ b/airdef-mod/src/post.rs @@ -1,5 +1,5 @@ //! The command post lists every deployed unit without requesting camera views. -use crate::sim::{Part, PartState, Sam, SamKind, SamState, battery::RadarRole}; +use crate::sim::{Part, PartState, Sam, SamKind, SamState, battery::RadarRole, decision, record::Recording}; /// Keep enough room under the engine's 512-row limit for large layouts. pub const PAGE_SIZE: usize = 200; @@ -93,11 +93,77 @@ pub struct Post { /// IDs and actions exactly as shown in the screen, even if the sim advances before a click. pub shown: Vec, pub actions: Vec, + pub decisions: Vec, pub source_origin: Option<(u32, From)>, /// Let the client finish closing one screen before opening a different kind. pub transition: Option<(Transition, bool)>, } +#[derive(Clone, Copy)] +pub struct RecordedChoice { + pub raid: u32, + pub entry: decision::Entry, +} + +pub fn decision_label(outcome: decision::Outcome) -> &'static str { + use decision::{Block as B, Outcome as O}; + match outcome { + O::Held(B::Hold) => "Огонь запрещён", + O::Held(B::Moving) => "Комплекс на марше", + O::Held(B::Reload) => "Перезарядка", + O::Held(B::Empty) => "Ожидает пополнения", + O::Held(B::NoSelection) => "Цель не назначена", + O::Held(B::WaitingForTerrain) => "Ожидает данных о рельефе", + O::Held(B::Terrain) => "Траектория перекрыта", + O::Held(B::Aim) => "Доворачивается", + O::Held(B::Opening) => "Открывает ТПК", + O::Held(B::BusyWithGroundShot) => "Готовит наземный пуск", + O::Held(B::Cooldown) => "Пауза между выстрелами", + O::Held(B::GunFault) => "Орудие недоступно", + O::Held(B::LauncherFault) => "Пусковая недоступна", + O::Held(B::NoLock) => "Нет свежего захвата", + O::Held(B::Range) => "Вне дальности орудия", + O::Burst => "Очередь выпущена", + O::BurstMissed => "Промах очереди", + O::BurstHit | O::Intercepted(_) => "Цель сбита", + O::Launched(_) => "Ракета выпущена", + O::InterceptorMissed(_) => "Промах перехватчика", + O::InterceptorEnded(_) => "Полёт перехватчика завершён", + } +} + +pub fn decision_lines(choice: RecordedChoice, rec: Option<&Recording>) -> Vec { + use decision::{Channel, Outcome}; + let entry = choice.entry; + let channel = match entry.channel { + Channel::Launcher => "Пусковая", + Channel::Gun => "Орудие", + Channel::Unit => "Комплекс", + }; + let mut lines = vec![ + format!("Налёт №{} · {} · {channel}", choice.raid, crate::replay::clock(f64::from(entry.at))), + format!("На тот момент · {}", decision_label(entry.outcome)), + ]; + if matches!(entry.outcome, Outcome::Held(_)) { + lines.push("На этой проверке выстрела не было".to_owned()); + } + if let Some(target) = entry.target { + lines.push(format!("Трек №{target}")); + } + if let Some(mark) = entry.mark { + let source = if mark.own { "своя отметка".to_owned() } else { + rec.and_then(|rec| rec.sams.iter().position(|s| s.0 == mark.source)) + .map_or_else(|| format!("источник ID {}", mark.source), |i| format!("источник №{}", i + 1)) + }; + lines.push(format!("{source} · {:.1} с назад", f64::from(mark.age) / 20.0)); + lines.push(format!("{} · {} · качество {}", mark.product.name(), mark.class.name(), mark.quality)); + } + if let Outcome::Launched(id) | Outcome::Intercepted(id) | Outcome::InterceptorMissed(id) | Outcome::InterceptorEnded(id) = entry.outcome { + lines.push(format!("Перехватчик ID {id}")); + } + lines +} + impl Post { pub fn matching(&self, sams: &[Sam]) -> Vec { let number = self.query.trim_start_matches('№').parse::().ok(); @@ -201,4 +267,29 @@ mod tests { assert_eq!(state(&ready), "Уничтожен"); assert!(Filter::Damaged.matches(&ready)); } + + #[test] + fn historical_details_use_the_recorded_station_and_separate_a_miss_from_a_refusal() { + let mut rec = Recording::blank(100); + rec.sams = vec![(96, SamKind::S400, DVec3::ZERO), (48, SamKind::Radar, DVec3::X)]; + let entry = decision::Entry { + unit: 96, + at: 40, + target: Some(112), + channel: decision::Channel::Launcher, + outcome: decision::Outcome::Held(decision::Block::Terrain), + mark: Some(decision::Mark { + source: 48, age: 12, own: false, quality: 62, + product: crate::sim::battery::Measure::Search, + class: crate::sim::ClassEst::Unknown, + }), + }; + let lines = decision_lines(RecordedChoice { raid: 2, entry }, Some(&rec)); + assert!(lines.iter().any(|line| line == "источник №2 · 0.6 с назад")); + assert!(lines.iter().any(|line| line.contains("выстрела не было"))); + let missed = decision::Entry { outcome: decision::Outcome::InterceptorMissed(144), mark: None, ..entry }; + let lines = decision_lines(RecordedChoice { raid: 2, entry: missed }, None); + assert!(lines.iter().any(|line| line.contains("Промах перехватчика"))); + assert!(!lines.iter().any(|line| line.contains("выстрела не было"))); + } } diff --git a/airdef-mod/src/replay.rs b/airdef-mod/src/replay.rs index 4007477..d6128d6 100644 --- a/airdef-mod/src/replay.rs +++ b/airdef-mod/src/replay.rs @@ -124,7 +124,7 @@ fn line(a: (f32, f32), b: (f32, f32), w: f32, color: u32) -> Shape { let p = |x: f32, y: f32| Point { x, y }; Shape::Quad(QuadShape { corners: (p(a.0 + nx, a.1 + ny), p(b.0 + nx, b.1 + ny), p(b.0 - nx, b.1 - ny), p(a.0 - nx, a.1 - ny)), color }) } -fn clock(ticks: f64) -> String { +pub(crate) fn clock(ticks: f64) -> String { let s = (ticks / 20.0).max(0.0); format!("{:02}:{:04.1}", (s / 60.0) as u32, s % 60.0) } diff --git a/airdef-mod/src/sim/decision.rs b/airdef-mod/src/sim/decision.rs new file mode 100644 index 0000000..a8c1789 --- /dev/null +++ b/airdef-mod/src/sim/decision.rs @@ -0,0 +1,257 @@ +//! Recorded choices at the firing checks, on the same clock as the replay. +use super::{ClassEst, Sam, battery::Measure, memory, why}; +use std::collections::{HashMap, VecDeque}; + +const MAX_ENTRIES: usize = 4096; +const MAX_STREAMS: usize = 1024; + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub enum Channel { + Unit, + Gun, + Launcher, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Block { + Hold, + Moving, + Reload, + Empty, + NoSelection, + WaitingForTerrain, + Terrain, + Aim, + Opening, + BusyWithGroundShot, + Cooldown, + GunFault, + LauncherFault, + NoLock, + Range, +} + +impl Block { + pub(super) fn gun(bits: u8) -> Self { + if bits & why::RELOADING != 0 { + Self::Reload + } else if bits & why::NO_ROUNDS != 0 { + Self::Empty + } else if bits & why::JAMMED != 0 { + Self::GunFault + } else if bits & why::NO_LOCK != 0 { + Self::NoLock + } else if bits & (why::NOT_AIMED | why::AIM_ERROR) != 0 { + Self::Aim + } else if bits & why::OUT_OF_RANGE != 0 { + Self::Range + } else { + Self::Cooldown + } + } + + pub(super) fn launcher(bits: u8) -> Self { + if bits & why::RELOADING != 0 { + Self::Reload + } else if bits & why::NO_ROUNDS != 0 { + Self::Empty + } else if bits & why::LAUNCHER_DOWN != 0 { + Self::LauncherFault + } else { + Self::Cooldown + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Outcome { + Held(Block), + Burst, + BurstMissed, + BurstHit, + Launched(u32), + Intercepted(u32), + InterceptorMissed(u32), + InterceptorEnded(u32), +} + +/// What the unit itself measured or received, with IDs fixed at recording time. +#[derive(Clone, Copy, Debug)] +pub struct Mark { + pub source: u32, + pub age: u16, + pub own: bool, + pub quality: u8, + pub product: Measure, + pub class: ClassEst, +} + +#[derive(Clone, Copy, Debug)] +pub struct Entry { + pub at: u32, + pub unit: u32, + pub target: Option, + pub channel: Channel, + pub outcome: Outcome, + pub mark: Option, +} + +#[derive(Default)] +pub struct History { + entries: VecDeque, + last: HashMap<(u32, Channel), (Option, Outcome)>, + truncated: bool, +} + +impl History { + pub fn entries(&self) -> impl DoubleEndedIterator { + self.entries.iter() + } + + pub fn truncated(&self) -> bool { + self.truncated + } + + pub(super) fn resume(&mut self, unit: u32, channel: Channel) { + self.last.remove(&(unit, channel)); + } + + pub(super) fn note( + &mut self, + at: u32, + now: u64, + sam: &Sam, + channel: Channel, + target: Option, + outcome: Outcome, + ) { + let key = (sam.id, channel); + if matches!(outcome, Outcome::Held(_)) { + if self.last.get(&key) == Some(&(target, outcome)) { + return; + } + if self.last.len() == MAX_STREAMS && !self.last.contains_key(&key) { + self.truncated = true; + return; + } + self.last.insert(key, (target, outcome)); + } else { + self.last.remove(&key); + } + let mark = target.and_then(|id| sam.track(id)).map(|track| Mark { + source: track.source, + age: track.age(now).min(u64::from(u16::MAX)) as u16, + own: track.source == sam.id, + quality: track.quality, + product: track.product, + class: track.class, + }); + // A refusal is for a public track, or the absence of a selected track. + // An actual shot still identifies the track it was fired at. + let target = if matches!(outcome, Outcome::Held(_)) && mark.is_none() { + None + } else { + target + }; + self.push(Entry { + at, + unit: sam.id, + target, + channel, + outcome, + mark, + }); + } + + pub(super) fn outcome( + &mut self, + at: u32, + unit: u32, + target: u32, + channel: Channel, + outcome: Outcome, + ) { + self.push(Entry { + at, + unit, + target: Some(target), + channel, + outcome, + mark: None, + }); + } + + fn push(&mut self, entry: Entry) { + if self.entries.len() == MAX_ENTRIES { + self.entries.pop_front(); + self.truncated = true; + } + self.entries.push_back(entry); + } + + pub(super) fn close(&mut self) { + self.last = HashMap::new(); + } + + pub(super) fn bytes(&self) -> usize { + memory::vecdeque_bytes(&self.entries) + + memory::map_bytes( + self.last.capacity(), + size_of::<((u32, Channel), (Option, Outcome))>(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sim::SamKind; + use glam::DVec3; + + #[test] + fn deduplicates_continuous_refusals_and_preserves_a_known_miss() { + let sam = Sam::new(16, SamKind::S400, DVec3::ZERO, 0.0); + let mut history = History::default(); + for at in 0..100 { + history.note( + at, + u64::from(at), + &sam, + Channel::Unit, + None, + Outcome::Held(Block::Hold), + ); + } + history.note( + 100, + 100, + &sam, + Channel::Launcher, + Some(93), + Outcome::Launched(94), + ); + history.outcome( + 130, + sam.id, + 93, + Channel::Launcher, + Outcome::InterceptorMissed(94), + ); + let entries: Vec<_> = history.entries().collect(); + assert_eq!(entries.len(), 3); + assert_eq!(entries[0].at, 0); + assert_eq!(entries[1].outcome, Outcome::Launched(94)); + assert_eq!(entries[2].outcome, Outcome::InterceptorMissed(94)); + } + + #[test] + fn a_full_journal_keeps_recent_entries_and_marks_the_gap() { + let mut history = History::default(); + for at in 0..MAX_ENTRIES as u32 + 3 { + history.outcome(at, 16, 93, Channel::Gun, Outcome::BurstHit); + } + assert!(history.truncated()); + assert_eq!(history.entries().count(), MAX_ENTRIES); + assert_eq!(history.entries().next().unwrap().at, 3); + } +} diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 7c8c550..9ecfa85 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -41,6 +41,7 @@ pub mod outcome; mod units; pub mod why; mod breakthrough; +pub mod decision; pub mod world; pub mod memory; pub use memory::MemoryReport; @@ -2432,6 +2433,7 @@ impl Sim { // ------------------------------------------------ air defence fn step_sams(&mut self, ground: &mut Ground, out: &mut Out) { + use decision::{Block, Channel, Outcome as Decision}; for sam in &mut self.sams { sam.sync_tube_cells(); if (self.hold && !sam.preparing.is_some_and(|p| p.ground)) || !sam.alive() || sam.moving() || sam.reloading > 0 || sam.part(Part::Launcher) <= 0.0 { @@ -2443,6 +2445,12 @@ impl Sim { for i in 0..self.sams.len() { if self.sams[i].alive() && !self.sams[i].moving() && self.sams[i].kind != SamKind::Optical { self.sams[i].state = SamState::Hold; + if let Some(rec) = &mut self.rec + && self.sams[i].kind.armed() + && !self.sams[i].tracks.is_empty() + { + rec.decisions.note(rec.len, self.tick, &self.sams[i], Channel::Unit, None, Decision::Held(Block::Hold)); + } } self.draw_sam(i, out); } @@ -2492,6 +2500,12 @@ impl Sim { } } if self.sams[i].moving() { + if let Some(rec) = &mut self.rec + && self.sams[i].kind.armed() + && !self.sams[i].tracks.is_empty() + { + rec.decisions.note(rec.len, self.tick, &self.sams[i], Channel::Unit, None, Decision::Held(Block::Moving)); + } continue; } if !self.sams[i].kind.armed() { @@ -2631,6 +2645,20 @@ impl Sim { } else { SamState::Search }; + if let Some(rec) = &mut self.rec { + rec.decisions.resume(sam.id, Channel::Gun); + rec.decisions.resume(sam.id, Channel::Launcher); + if !sam.tracks.is_empty() { + let block = match sam.state { + SamState::Reload => Block::Reload, + SamState::Waiting => Block::Empty, + _ => Block::NoSelection, + }; + rec.decisions.note(rec.len, now, sam, Channel::Unit, None, Decision::Held(block)); + } else { + rec.decisions.resume(sam.id, Channel::Unit); + } + } // Nothing to fire at: the mount watches the nearest track of its classes (by the class // the network estimates, the unknown among them: a reaction a turn shorter), else it // goes back to the rest position, under the drive's limits like any other turn. @@ -2652,6 +2680,15 @@ impl Sim { } continue; }; + if let Some(rec) = &mut self.rec { + rec.decisions.resume(sam.id, Channel::Unit); + if sam.target.is_none() { + rec.decisions.resume(sam.id, Channel::Launcher); + } + if sam.gun_target.is_none() { + rec.decisions.resume(sam.id, Channel::Gun); + } + } let (mount, _) = sam.mount(); let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell); let (aim_id, aim_pos, aim_vel) = aim; @@ -2733,17 +2770,26 @@ impl Sim { // The aim point is the track's forecast: the farther it is from the truth, the more shells miss. let off = est.distance(t.pos); let p = gun.p * sam.gun_fit() * dark / (t.kind.spec().stealth * (1.0 + (off / 8.0).powi(2))) * (1.0 - dist / (gun.range * 1.3)).max(0.35); - if self.rng.chance(p) { + let hit = self.rng.chance(p); + if let Some(rec) = &mut self.rec { + let outcome = if hit { Decision::Burst } else { Decision::BurstMissed }; + rec.decisions.note(rec.len, now, sam, Channel::Gun, Some(gt), outcome); + } + if hit { gun_hits.push((gt, sam.id)); } else { out.particles("minecraft:crit", t.pos, 1.2, DVec3::ZERO, 0.2, 4); } + } else if let Some(rec) = &mut self.rec { + rec.decisions.note(rec.len, now, sam, Channel::Gun, Some(gt), Decision::Held(Block::gun(blocks))); } } } // Missiles. if let (Some(load), Some(mt)) = (&spec.missile, sam.target) { - let ready = why::missile_blocks(sam) == 0 && !sam.preparing.is_some_and(|p| p.ground); + let blocks = why::missile_blocks(sam); + let busy = sam.preparing.is_some_and(|p| p.ground); + let ready = blocks == 0 && !busy; // The missile turns after its boost, but the launcher must point near the target. let t = sam.track(mt).filter(|_| drone_at.contains_key(&mt)).map(|tr| tr.est(now)); let aligned = why::missile_aligned(spec.family, sam.yaw, mount, t, aim_id, mt, aim_error); @@ -2773,13 +2819,23 @@ impl Sim { } else { 0 }; + let fire = land == 0 && ready && aligned && sam.prepare_tube(mt, now); + if !fire && let Some(rec) = &mut self.rec { + let block = if land == terrain::WAIT { Block::WaitingForTerrain } + else if land != 0 { Block::Terrain } + else if blocks != 0 { Block::launcher(blocks) } + else if busy { Block::BusyWithGroundShot } + else if !aligned { Block::Aim } + else { Block::Opening }; + rec.decisions.note(rec.len, now, sam, Channel::Launcher, Some(mt), Decision::Held(block)); + } if land == terrain::WAIT { // The land under the shot is not known yet: it waits. } else if land != 0 { sam.cancel_prepare(); retarget(&mut missile_on, Some(mt), None); sam.target = None; - } else if ready && aligned && sam.prepare_tube(mt, now) { + } else if fire { sam.eject_cell(n); // Past its normal reach: a long shot, and the next waits. if sam.kind.far_shooter() && t.is_some_and(|t| t.distance(sam.pos) >= load.max) { @@ -2822,6 +2878,11 @@ impl Sim { .map(|tr| Fix { pos: tr.pos, vel: tr.vel, tick: tr.tick, seeker: false }); let spec = kind.spec(); let id = self.id(); + if let Some(rec) = &mut self.rec + && let Some(unit) = self.sams.iter().find(|s| s.id == sam) + { + rec.decisions.note(rec.len, self.tick, unit, Channel::Launcher, Some(target), Decision::Launched(id)); + } let v0 = if spec.cold > 0 { spec.eject } else { 0.8 }; self.breakthrough_launch(target); self.missiles.push(Missile { id, kind, pos: muzzle, vel: dir * v0, target, sam, age: 0, hold: 0, fix, seen: 0 }); @@ -2847,8 +2908,11 @@ impl Sim { self.fx.push((id, Fx::Tracer { pos, vel, life })); } for (t, by) in gun_hits { - if let Some(i) = self.drones.iter().position(|d| d.id == t) { - let _ = self.shoot_down(i, by, None, ground, out); + if let Some(i) = self.drones.iter().position(|d| d.id == t) + && self.shoot_down(i, by, None, ground, out).is_some() + && let Some(rec) = &mut self.rec + { + rec.decisions.outcome(rec.len, by, t, Channel::Gun, Decision::BurstHit); } } for i in 0..self.sams.len() { @@ -3088,11 +3152,12 @@ impl Sim { self.fireball(m.pos, 2.5 * m.kind.spec().scale, 7); out.particles("minecraft:explosion", m.pos, 0.4, DVec3::ZERO, 0.0, 3); out.sound(sound::BLAST_AIR, m.pos, 1.0, 1.25); + let mut hit = false; if let Some(t) = target.and_then(|t| self.drones.iter().position(|d| d.id == t)) { self.drones[t].engaged = self.drones[t].engaged.saturating_sub(1); if kill { let (at, closing) = impacts[&mid]; - let _ = self.shoot_down_by(t, sam, Some(mid), Impact::missile(m.kind, at, closing), ground, out); + hit = self.shoot_down_by(t, sam, Some(mid), Impact::missile(m.kind, at, closing), ground, out).is_some(); } } // A missile that lost its target frees it for others. @@ -3101,6 +3166,13 @@ impl Sim { { d.engaged = d.engaged.saturating_sub(1); } + if let Some(rec) = &mut self.rec { + use decision::{Channel, Outcome}; + let outcome = if hit { Outcome::Intercepted(mid) } + else if !kill && impacts.contains_key(&mid) { Outcome::InterceptorMissed(mid) } + else { Outcome::InterceptorEnded(mid) }; + rec.decisions.outcome(rec.len, sam, m.target, Channel::Launcher, outcome); + } } } for m in &self.missiles { diff --git a/airdef-mod/src/sim/record.rs b/airdef-mod/src/sim/record.rs index 3e5b4c0..ce199de 100644 --- a/airdef-mod/src/sim/record.rs +++ b/airdef-mod/src/sim/record.rs @@ -168,6 +168,7 @@ impl Recording { index: HashMap::new(), events: Vec::new(), scene: None, + decisions: decision::History::default(), tally: Tally::default(), sams: Vec::new(), objects: Vec::new(), @@ -584,6 +585,7 @@ pub struct Recording { pub events: Vec, /// None is the legacy event/track-only format. pub scene: Option, + pub decisions: decision::History, /// The failures counted during the raid. pub tally: Tally, /// The systems and objects as they stood: (id, kind, where). @@ -834,6 +836,7 @@ impl Recording { index: HashMap::new(), events: Vec::new(), scene: Some(SceneJournal::default()), + decisions: decision::History::default(), tally: Tally::default(), sams: sim.sams.iter().map(|s| (s.id, s.kind, s.pos)).collect(), objects: sim.targets.clone(), @@ -859,6 +862,7 @@ impl Recording { /// `Sim` calls this once the raid is over; its own events are always appended in time order /// (ties in the order they happened), so the index is only built for a journal altered later. pub fn close(&mut self) { + self.decisions.close(); self.closed = true; if self.events.windows(2).all(|w| w[0].at <= w[1].at) { self.time_order = None; @@ -976,7 +980,7 @@ impl Recording { let tracks = vec_bytes(&self.tracks) + self.tracks.iter().map(|t| vec_bytes(&t.points)).sum::() + map_bytes(self.index.len(), std::mem::size_of::() + std::mem::size_of::()); - let mut journal = vec_bytes(&self.events); + let mut journal = vec_bytes(&self.events) + self.decisions.bytes(); if let Some(scene) = &self.scene { journal += vec_bytes(&scene.events) + map_bytes(scene.tracks.len(), std::mem::size_of::<(u32, u32)>() + std::mem::size_of::<(bool, bool, DVec3)>()) @@ -1517,7 +1521,7 @@ impl Sim { } done.len = done.len.saturating_sub(done.quiet.saturating_sub(40)); done.close(); - if !done.events.is_empty() || done.scene.as_ref().is_some_and(|s| !s.events.is_empty()) { + if !done.events.is_empty() || done.scene.as_ref().is_some_and(|s| !s.events.is_empty()) || done.decisions.entries().next().is_some() { self.replays.push(done); if self.replays.len() > KEPT { self.replays.remove(0);