diff --git a/README.md b/README.md index f3a5a05..10401e8 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,12 @@ API 31 форка) и следуют за взглядом покадрово; целью, потом за перехватчиком (или смотрит из пушки, со стороны на прилёт), в момент сбития время замедляется; - **полный повтор** — весь налёт, камера-режиссёр сама выбирает, за чем следить; колесо — перемотка, стрелки — скорость; - **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения - объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты. + объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты; +- **цепочки боя** — меню N → «Повторы…» → «Цепочки боя»: по каждому контакту короткая строка + «отметка → передача → захват → пуск → исход» из 4–5 измеренных переходов записи, без домыслов. Видны + время каждого шага, батарея и контакт, у пропущенных контактов — «без пуска». Фильтр по батарее + переключает список; клик открывает кадр повтора (клип исхода, а если исхода нет — карту налёта на + моменте пуска или отметки). То же списком: `/airdef chains [номер батареи]`. Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. Управление (подсказка показывается в начале, после нажатия и на паузе): **← →** — перемотка на 5 с (в нарезке — соседний момент), @@ -232,6 +237,18 @@ API 31 форка) и следуют за взглядом покадрово; - `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — три разные игровые РЛС с устойчивыми профилями в каталоге. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав, профиль, цикл, продукты измерения и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию. Профиль РЛС задаётся при размещении и не переключается на ходу: `radar <номер> on|off` сохраняется. Обзорная станция даёт редкие грубые отметки и область поиска; мачтовая уточняет низкие контакты над рельефом; сопровождения ищет локально, ведёт ограниченное число точных треков и только её собственное подтверждённое измерение разрешает пуск. Сеть передаёт источник, возраст и качество, но повторная пересылка не освежает измерение. Старые С-400/С-500 сохраняют сборную конфигурацию, старые роли РЛС при загрузке сопоставляются с профилями. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md). - `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`; - `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve ` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48). +- `/airdef why <номер>` — почему комплекс стреляет или нет. Сразу под строкой состояния — одна typed-причина: + «есть только обзор», «ждёт сопровождения», «каналы заняты», «нет боезапаса» или «готов к пуску», вместе с возрастом и + источником отметки (своя РЛС или сеть, РЛС №N). «Есть только обзор» — на картине лишь поисковая или + сетевая отметка, своё подтверждённое измерение пуск не разрешает; «ждёт сопровождения» — своя РЛС ещё + уточняет контакт или пусковая ждёт огневой трек поддерживающей РЛС; «каналы заняты» — все каналы + сопровождения заняты другими контактами; «нет боезапаса» — нет ракет и снарядов или идёт перезарядка. + `/airdef why <номер> source` переводит монитор K на станцию, которая поставила отметку. Подробные + проверки (роли, доктрина, дальность, наведение) идут ниже и не расходятся с этой причиной. В обычном + HUD — только картина самой батареи: класс по оценке, без истинного типа и скрытых данных. +- `/airdef chains [номер батареи]` — короткие цепочки последнего налёта: «отметка → передача → захват → + пуск → исход» с временем шагов; без номера — все батареи. Строка кликабельна в меню N → «Повторы…» → + «Цепочки боя» и открывает кадр повтора. - `/airdef deploy ` — поставить комплекс в 8 блоках перед собой; - `/airdef hold on|off` — запретить или разрешить ПВО огонь, удобно для съёмки ударов; - `/airdef damage on|off` — разрушать ли ландшафт взрывами (через TNT, нужны читы); diff --git a/airdef-mod/src/commands.rs b/airdef-mod/src/commands.rs index 89e840c..2cef837 100644 --- a/airdef-mod/src/commands.rs +++ b/airdef-mod/src/commands.rs @@ -57,7 +57,10 @@ pub fn tree() -> Tree { Node::lit("list").runs(), Node::lit("delete").then(Node::arg("имя", Value::names(SCENARIOS)).runs()), ]), - Node::lit("why").runs().then(Node::arg("номер", Value::int_from(1)).runs()), + Node::lit("why").runs().then( + Node::arg("номер", Value::int_from(1)).runs().then(Node::lit("source").runs()), + ), + Node::lit("chains").runs().then(Node::arg("батарея", Value::int_from(1)).runs()), Node::lit("raid").runs(), Node::lit("sites").runs(), Node::lit("ground-stock").then(Node::arg("склад", Value::int_from(1)).then(Node::arg("количество", Value::int_from(0)).runs())), @@ -168,7 +171,7 @@ mod tests { "replay film 3", "replay export", "replay export mine", "replay export best", "replay export all", "replay export 3", "replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop", "scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list", - "scenario delete a", "why", "why 2", "ew on", "ew off", "move 4", "target here", "targets clear", + "scenario delete a", "why", "why 2", "why 2 source", "chains", "chains 2", "ew on", "ew off", "move 4", "target here", "targets clear", "sites", "strike 3", "battery", "battery 1 launcher", "battery 1 integrated", "radar 2 on", "radar 2 off", "radar 2 engagement", "radar 2 search", "deploy s400_launcher", "deploy s500_launcher", "deploy radar_search", "deploy radar_track", "deploy radar_height", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000", "wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off", "roles all default", "doctrine", "doctrine 1 reserve 4", "doctrine all salvo eco", "doctrine 2 sector 90 45", "doctrine 2 sector off", "doctrine 1 guard 1,2", "doctrine 1 reset", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic", @@ -242,10 +245,10 @@ mod tests { fn completion_offers_the_next_word_only() { let top = complete("", &[]); for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move", - "target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel"] { + "target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel", "chains"] { assert!(top.contains(&w.to_string()), "{w} in {top:?}"); } - assert_eq!(top.len(), 36); + assert_eq!(top.len(), 37); assert_eq!(complete("rep", &[]), ["repair", "replay"]); assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]); assert_eq!(complete("replay film ", &[]), ["all", "best"]); diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs index fb00bbd..9a20308 100644 --- a/airdef-mod/src/lib.rs +++ b/airdef-mod/src/lib.rs @@ -79,6 +79,8 @@ struct AirDef { health_mark: u64, /// The menu's page while it is open. menu: Option, + /// The battery the after-action chain list is filtered to (its id; None: all). + chain_filter: Option, /// Where the player is, for the sounds' delay and far variants. listener: DVec3, /// The picture punch (#51) the HD exposure and bloom were last set for. @@ -206,6 +208,8 @@ enum Page { More, /// The last raid's events and its replays. Replays, + /// The last raid's short battle chains: mark → handoff → lock → launch → outcome (#148). + Chains, /// The enemy's recon picture and why it prices each mark: debug and after-action review (#135). Recon, /// The systems with their doctrines, and one system's doctrine (by id) (#47). @@ -246,6 +250,9 @@ const BTN_REPLAYS: u32 = 18; const BTN_RECON: u32 = 23; const REPLAY_EVENTS: u32 = 3; const RECON_ROWS: u32 = 6; +const CHAIN_ROWS: u32 = 7; +const BTN_CHAINS: u32 = 43; +const BTN_CHAIN_FILTER: u32 = 44; const BTN_MAP: u32 = 40; const BTN_FULL: u32 = 41; const BTN_REEL: u32 = 42; @@ -1311,6 +1318,23 @@ impl AirDef { Ok(()) } + /// Opens a battle chain's replay frame: its outcome clip when recorded, else the map at the + /// launch (or the mark) held still. + fn start_chain(&mut self, row: replay::ChainRow) -> Result<(), String> { + match row.event { + Some(i) => self.start_replay("clip", Some(i)), + None => { + self.start_replay("map", None)?; + if let Some(player) = self.presentation.playback_mut() + && let Some(rec) = self.sim.replays.last() + { + player.seek(rec, row.at); + } + Ok(()) + } + } + } + fn stop_replay(&mut self) { let was_export = self.presentation.is_exporting(); self.end_session(presentation::ExitCause::UserStop); @@ -1638,6 +1662,7 @@ impl AirDef { widgets.push(Widget::Button(ButtonWidget { id: BTN_MAP, label: "Карта налёта (R)".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_FULL, label: "Полный повтор".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_REEL, label: format!("Лучшие моменты ({})", replay::reel(rec).len()) })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAINS, label: format!("Цепочки боя (разбор): {}", rec.chains(None).len()) })); widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() })); } None => { @@ -1647,11 +1672,40 @@ impl AirDef { text: "Повторов пока нет: налёт записывается сам и появится здесь, когда небо очистится".into(), color: 0, })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAINS, label: "Цепочки боя (разбор)".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() })); } } } + Page::Chains => { + match self.sim.replays.last() { + Some(rec) => { + let rows = replay::chain_rows(rec, self.chain_filter); + let filter = self.chain_filter.and_then(|id| { + rec.sams.iter().position(|s| s.0 == id).map(|i| format!("№{} {}", i + 1, rec.sam(id).map_or("ПВО", |(k, _)| k.name()))) + }); + title = format!( + "Цепочки боя: отметка → передача → захват → пуск → исход · {} · фильтр: {} · клик: кадр повтора", + if rows.is_empty() { "нет цепочек".to_string() } else { format!("{}", rows.len()) }, + filter.unwrap_or_else(|| "все батареи".into()), + ); + let rows = rows.into_iter().take(200).map(|r| r.text).collect(); + widgets.push(Widget::List(ListWidget { id: CHAIN_ROWS, rows, selected: None })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAIN_FILTER, label: "Фильтр по батарее".into() })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← К повторам".into() })); + } + None => { + title = "Цепочки боя".into(); + widgets.push(Widget::Text(horizon_mod_sdk::ui::TextWidget { + id: 0, + text: "Повторов пока нет: цепочки появятся после первого налёта".into(), + color: 0, + })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← К повторам".into() })); + } + } + } Page::Recon => { title = "Разведка противника — разбор (debug): что враг запомнил и почему".into(); let rows: Vec = recon_view::picture_lines(&self.sim.enemy_picture()).into_iter().take(200).collect(); @@ -1886,6 +1940,7 @@ impl Mod for AirDef { world: None, health_mark: 0, menu: None, + chain_filter: None, listener: DVec3::ZERO, punch: 0.0, pending: Vec::new(), @@ -2321,6 +2376,37 @@ impl Mod for AirDef { self.open_menu(Page::Main); return; } + (Page::Replays, BTN_CHAINS) => { + self.open_menu(Page::Chains); + return; + } + (Page::Chains, CHAIN_ROWS) => { + let Some(rec) = self.sim.replays.last() else { return }; + let Some(row) = replay::chain_rows(rec, self.chain_filter).into_iter().nth(row as usize) else { return }; + match self.start_chain(row) { + Ok(()) => { + self.menu = None; + ui::close_screen(); + } + Err(e) => say(&e), + } + return; + } + (Page::Chains, BTN_CHAIN_FILTER) => { + // All → each battery → all. Only systems are offered; a battery with no chains + // still narrows the list to "nothing", which is the honest answer. + let ids: Vec = self.sim.sams.iter().map(|s| s.id).collect(); + self.chain_filter = match self.chain_filter { + None => ids.first().copied(), + Some(id) => ids.iter().position(|x| *x == id).and_then(|i| ids.get(i + 1).copied()), + }; + self.open_menu(Page::Chains); + return; + } + (Page::Chains, BTN_BACK) => { + self.open_menu(Page::Replays); + return; + } (Page::Main, BTN_RECON) | (Page::Replays, BTN_RECON) => { self.open_menu(Page::Recon); return; @@ -2492,11 +2578,53 @@ impl Mod for AirDef { if i >= self.sim.sams.len() { return Err("Нет такой техники".into()); } + // `/airdef why source`: move the monitor to the station that measured the mark. + if rest.get(1).is_some_and(|w| *w == "source") { + let mark = self.sim.battle_reason(i).and_then(|r| r.mark); + let Some(mark) = mark else { return Err("У комплекса нет отметки: источник неизвестен".into()) }; + if mark.own { + return Err("Отметка своя: источник — сама батарея".into()); + } + let Some(source) = mark.source else { return Err("Источник отметки неизвестен".into()) }; + self.monitor = Some(source); + let name = self.sim.sams.get(source).map_or("РЛС", |s| s.kind.name()); + return Ok(Some(format!( + "Переход к источнику отметки: №{} {}, возраст {:.1} с", + source + 1, + name, + mark.age as f64 / 20.0 + ))); + } for c in self.sim.why(i) { say(&format!("{} {}", if c.ok { "+" } else { "-" }, why_view::reason(&c.reason))); } + if let Some(mark) = self.sim.battle_reason(i).and_then(|r| r.mark) + && !mark.own + && mark.source.is_some() + { + say(&format!("Источник отметки: перейти — /airdef why {} source", i + 1)); + } None } + ["chains", rest @ ..] => { + let battery = match rest.first() { + Some(n) => { + let i = n.parse::().ok().and_then(|n| n.checked_sub(1)).ok_or("/airdef chains [номер батареи]")?; + Some(self.sim.sams.get(i).ok_or("Нет такой техники")?.id) + } + None => None, + }; + let Some(rec) = self.sim.replays.last() else { return Err("Повторов пока нет: запишется первый же налёт".into()) }; + let rows = replay::chain_rows(rec, battery); + if rows.is_empty() { + say("Цепочек нет: в записи не было ни одной отметки (или формат старый)"); + } else { + for row in rows.iter().take(200) { + say(&row.text); + } + } + Some("Клик по строке в меню N → «Повторы…» → «Цепочки боя» открывает кадр повтора".into()) + } ["raid"] => { self.launch_wave(&mut out)?; None @@ -2760,6 +2888,7 @@ mod tests { world: None, health_mark: 0, menu: None, + chain_filter: None, listener: DVec3::ZERO, punch: 0.0, pending: Vec::new(), diff --git a/airdef-mod/src/replay.rs b/airdef-mod/src/replay.rs index 25742b4..34d82f0 100644 --- a/airdef-mod/src/replay.rs +++ b/airdef-mod/src/replay.rs @@ -9,7 +9,7 @@ use crate::sim::catalog::sound; use crate::film::{self, Film}; use crate::panel::distance; use crate::sim::Ground; -use crate::sim::record::{EventKind, Recording, STEP, StrikeResult, What}; +use crate::sim::record::{Chain, ChainOutcome, ChainStepKind, EventKind, Recording, STEP, StrikeResult, What}; use std::cell::Cell; use crate::sim::{Class, DroneKind, Out, Sim}; use glam::DVec3; @@ -187,6 +187,67 @@ pub fn row(rec: &Recording, i: usize) -> String { format!("{} {what}", clock(e.at as f64)) } +/// A row of the after-action chain list and where a click on it opens a replay. +#[derive(Clone, Debug, PartialEq)] +pub struct ChainRow { + pub text: String, + /// The recorded event to clip (the outcome), when there is one. + pub event: Option, + /// Otherwise the recording's tick to open the map at (the launch, else the mark). + pub at: f64, +} + +/// The short chains of a raid: отметка → передача → захват → пуск → исход, filtered by a +/// battery's id when asked. The list is the recording's measured transitions, not a guess. +pub fn chain_rows(rec: &Recording, battery: Option) -> Vec { + rec.chains(battery).iter().map(|chain| ChainRow { text: chain_row(rec, chain), event: chain.outcome_event(), at: chain_jump_at(chain) }).collect() +} + +/// Where a chain opens in a replay when its outcome has no recorded event. +fn chain_jump_at(chain: &Chain) -> f64 { + chain + .step(ChainStepKind::Launch) + .or_else(|| chain.step(ChainStepKind::Mark)) + .map_or(0.0, |s| s.at as f64) +} + +fn chain_step_name(chain: &Chain, kind: ChainStepKind, own: bool) -> &'static str { + match kind { + ChainStepKind::Mark => "отметка", + ChainStepKind::Handoff if own => "передача (своя РЛС)", + ChainStepKind::Handoff => "передача (сеть)", + ChainStepKind::Lock => "захват", + ChainStepKind::Launch => "пуск", + ChainStepKind::Outcome => match chain.outcome { + ChainOutcome::Destroyed => "сбит", + ChainOutcome::Hit => "прорыв", + ChainOutcome::Lost => "потерян", + ChainOutcome::Unfinished => "без исхода", + }, + } +} + +/// One chain as a line: the battery, its contact, and the four or five measured steps. +pub fn chain_row(rec: &Recording, chain: &Chain) -> String { + let index = rec.sams.iter().position(|s| s.0 == chain.sam).map(|i| i + 1); + let kind = rec.sam(chain.sam).map_or("ПВО", |(kind, _)| kind.name()); + let target = rec + .track(chain.target) + .and_then(|t| match t.what { + What::Drone(kind) => Some(kind.spec().name), + _ => None, + }) + .unwrap_or("цель"); + let steps: Vec = chain.steps.iter().map(|s| format!("{} {}", chain_step_name(chain, s.kind, s.own), clock(s.at as f64))).collect(); + let battery = index.map_or_else(|| format!("№? {kind}"), |i| format!("№{i} {kind}")); + format!( + "{} {battery} → «{target}»: {}{}", + clock(chain.marked_at() as f64), + steps.join(" → "), + if chain.missed() { " · без пуска" } else { "" }, + ) +} + /// How worth watching an event is: the reel takes the best. pub fn interest(rec: &Recording, i: usize) -> f64 { let e = &rec.events[i]; @@ -299,6 +360,16 @@ impl Player { } } + /// Opens the replay at a recording tick (a chain's launch or mark), holding that frame. + pub fn seek(&mut self, rec: &Recording, at: f64) { + self.t = at.clamp(0.0, rec.len as f64); + self.heard = self.t; + self.shot = (usize::MAX, 0); + self.fade = 0; + self.card = 0; + self.paused = true; + } + /// The wheel: scrubs the map and the full replay, skips clips. pub fn wheel(&mut self, steps: f32, rec: &Recording) { let c = if steps > 0.0 { Control::Back } else { Control::Forward }; @@ -1102,6 +1173,41 @@ impl Player { mod surface_tests { use super::*; + #[test] + fn a_chain_row_lists_the_measured_steps_and_opens_its_frame() { + use crate::sim::record::{Event, SceneEvent, SceneJournal, SceneKind}; + use crate::sim::outcome::Outcome; + use crate::sim::MissileKind; + let mut rec = Recording::blank(300); + rec.sams = vec![(10, crate::sim::SamKind::Pantsir, DVec3::ZERO)]; + rec.straight(7, What::Drone(DroneKind::Shahed), 0, 200, DVec3::new(0.0, 80.0, 0.0), DVec3::new(200.0, 80.0, 0.0)); + let mut scene = SceneJournal::default(); + let at = |at: u32, kind| SceneEvent { at, pos: DVec3::ZERO, kind }; + scene.fixture_push(at(20, SceneKind::TrackAcquired { sam: 10, target: 7, ever_own: false })); + scene.fixture_push(at(30, SceneKind::TrackSource { sam: 10, target: 7, ever_own: true })); + scene.fixture_push(at(40, SceneKind::TrackLock { sam: 10, target: 7, locked: true })); + scene.fixture_push(at(50, SceneKind::MissileLaunch { missile: 500, sam: 10, target: 7, kind: MissileKind::M57e6, sound: "airdef:launch.pantsir", pitch: 1.0 })); + rec.scene = Some(scene); + rec.events.push(Event { + at: 90, + pos: DVec3::ZERO, + kind: EventKind::Kill { drone: 7, kind: DroneKind::Shahed, sam: 10, sam_kind: crate::sim::SamKind::Pantsir, sam_index: 0, missile: Some(500), outcome: Outcome::DisabledFalling }, + }); + let rows = chain_rows(&rec, None); + assert_eq!(rows.len(), 1); + for step in ["отметка", "передача", "захват", "пуск", "сбит"] { + assert!(rows[0].text.contains(step), "the chain row misses {step}: {}", rows[0].text); + } + assert_eq!(rows[0].event, Some(0)); + assert!(chain_rows(&rec, Some(10)).len() == 1); + assert!(chain_rows(&rec, Some(11)).is_empty()); + // A chain with no recorded outcome opens its launch frame on the map, held still. + let mut player = Player::new(1, Mode::Map, &Sim::new(1)); + player.seek(&rec, rows[0].at); + assert!(player.paused); + assert!((player.time() - rows[0].at).abs() < 1e-9); + } + /// A gun standing on the sea floor films from above the water, not from under it. #[test] fn the_gun_camera_is_lifted_above_the_water() { diff --git a/airdef-mod/src/sim/record.rs b/airdef-mod/src/sim/record.rs index 033f5fe..576db21 100644 --- a/airdef-mod/src/sim/record.rs +++ b/airdef-mod/src/sim/record.rs @@ -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, + /// 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, +} + +/// 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, + 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 { + 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) -> Vec { + 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 = 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) { + 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 = 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, diff --git a/airdef-mod/src/sim/why.rs b/airdef-mod/src/sim/why.rs index c8c62ee..43f758c 100644 --- a/airdef-mod/src/sim/why.rs +++ b/airdef-mod/src/sim/why.rs @@ -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, + /// The station that made the newest plot, as an index into `Sim::sams`. + pub source: Option, + /// 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, + /// 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, + pub sam: usize, + pub target: Option, + pub mark: Option, + 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 { + 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) -> Option { + 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) -> Check { Check { ok, reason: CheckReason::Text(text.into()) } } fn part_check(reason: CheckReason) -> Check { Check { ok: false, reason } } +fn battle_check(reason: Option) -> 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. diff --git a/airdef-mod/src/why_view.rs b/airdef-mod/src/why_view.rs index 401a480..23ea1fe 100644 --- a/airdef-mod/src/why_view.rs +++ b/airdef-mod/src/why_view.rs @@ -1,5 +1,5 @@ //! Text for diagnostics produced by the simulation. -use crate::sim::why::{CheckReason, PartEffect}; +use crate::sim::why::{BattleBlock, BattleKind, BattleMark, BattleReason, CheckReason, PartEffect}; use crate::sim::{Comps, Part, SamKind}; fn part_value(part: Part, value: f64) -> String { @@ -25,9 +25,81 @@ pub fn worst(comps: &Comps, kind: SamKind) -> String { .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) -> 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::>().join(", ")), CheckReason::PartEffect(effect) => match effect { PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(), @@ -79,6 +151,40 @@ mod tests { 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%, Ход отказ");