From c4e002ed8babea5825e659f140d64044e221f90e Mon Sep 17 00:00:00 2001 From: chexit Date: Fri, 20 Nov 2026 23:09:34 +0300 Subject: [PATCH] Add the recon UI and diagnostic layer to the smart enemy (#135) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The core recon flights and partial reports (9d8f3da57) had no player-facing or diagnostic consumer: enemy_picture().recon/recon_sorties were read only by core tests. This adds the missing layer on top, without touching the mechanics, models or textures. - Map: a tracked recon aircraft is a recognisable yellow hollow diamond with a "разведчик" label, a role line in the selection panel and a filter legend; in the sandbox truth mode it gets an amber marker of its own. - Battle UI: the summary panel and the map show the flight's coarse phase (разведка → донесение → завершение) only while the player's network actually holds a recon aircraft — what the visible aircraft are doing, not what the enemy learned. The truth mode adds a recon count line. - Diagnostics and after-action review: /airdef recon and the menu page "Разведка противника (разбор)" (from Main and Replays) list the enemy's marks best-first with the reason each outranks the rest — priority = freshness×4 + quality×3 + observed role (recon::priority_parts, cross-checked against Mark::priority by a test) — plus the sortie phases and the drones aimed at a mark. The omniscient enemy picture is never shown in the normal HUD; it is explicit debug/review only. recon_view reads only the current report types (EnemyPictureReport, ReconReport, ReconSortieReport); the sim side only widens visibility and adds priority_parts and the is_recon_drone/recon_status read helpers. Tests: recon_view, panel, command tree, priority_parts cross-check. README and IMPLEMENTATION-STATUS updated. Co-Authored-By: Kimi Code --- README.md | 17 +- airdef-mod/src/commands.rs | 7 +- airdef-mod/src/lib.rs | 32 ++++ airdef-mod/src/map.rs | 67 ++++++-- airdef-mod/src/panel.rs | 78 ++++++++++ airdef-mod/src/recon_view.rs | 286 ++++++++++++++++++++++++++++++++++ airdef-mod/src/sim/mod.rs | 4 +- airdef-mod/src/sim/recon.rs | 66 +++++++- docs/IMPLEMENTATION-STATUS.md | 1 + 9 files changed, 528 insertions(+), 30 deletions(-) create mode 100644 airdef-mod/src/recon_view.rs diff --git a/README.md b/README.md index 70568e6..40820fa 100644 --- a/README.md +++ b/README.md @@ -229,10 +229,23 @@ API мода `render.set-lights` (до 512, плавно интерполиру - `/airdef clear` — убрать дроны и ракеты; - `/airdef targets clear` — снять все цели; - `/airdef stats` — сводка. +- `/airdef recon` — debug/послебоевой разбор разведки противника (#135): отметки его картины best-first с причиной приоритета (`свежесть×4 + качество×3 + наблюдаемая роль`), фазы вылетов и дроны, нацеленные на отметку. То же — страница «Разведка противника (разбор)» в меню N. Всеведущая картина противника в обычный HUD не выводится. Интерфейс: -- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт; -- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели: форма значка различает дрон, самолёт, крылатую, сверхзвуковую и баллистическую ракету, хвост показывает курс, а близкие отметки объединяются с числом; жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара. +- **сверху справа — сводка:** тревога, цели по типам, ближайшая угроза (дальность, высота, скорость), перехватчики в воздухе, по каждому комплексу боезапас или перезарядка, его текущая цель и число сбитых, итоговый счёт; если сеть держит разведчиков противника — их число и фаза вылета (разведка/донесение/завершение); +- **снизу справа — радар на 500 м** со сканирующим лучом. Отметки гаснут после прохода луча. Красное — цели: форма значка различает дрон, самолёт, крылатую, сверхзвуковую и баллистическую ракету, хвост показывает курс, а близкие отметки объединяются с числом; жёлтое — ракеты, синее — ПВО с кругами дальности, крест — цели удара. Разведчик противника в картине сети — жёлтый полый ромб с подписью «разведчик». + +**Разведка противника (#135).** Налёт с целью «умный противник» перед ударом высылает небольшой бюджет +невооружённых разведчиков: они физически проходят игровые зоны вокруг отмеченных целей и передают домой +только область, грубую категорию, канал (пролёт/излучение/РЭБ/пуск) и возраст — не точную точку, тип, +прочность и боезапас. Сбитый до донесения разведчик ничего не передаёт; уже переданное противник помнит +между налётами, а скрытый переезд или выключение не переписывают старую отметку. На карте сети разведчик — +узнаваемый жёлтый ромб с подписью «разведчик» (в sandbox-режиме `/airdef truth on` — янтарная метка и +счётчик отметок), в сводке и на карте видна фаза вылета: разведка → донесение → завершение. Что противник +запомнил и почему выбирает цель, показывает `/airdef recon` и страница «Разведка противника (разбор)» в меню +N (есть и в «Повторы…»): отметки best-first с разбором приоритета (свежесть, качество, наблюдаемая роль) и +дроны, нацеленные на отметку. Это явный debug/послебоевой разбор — всеведущая картина противника в обычный +HUD не выводится. Простые пресеты налёта фазу разведки не получают. Комплексы ПВО и цели сохраняются между сессиями. diff --git a/airdef-mod/src/commands.rs b/airdef-mod/src/commands.rs index e1afeb1..89e840c 100644 --- a/airdef-mod/src/commands.rs +++ b/airdef-mod/src/commands.rs @@ -106,6 +106,7 @@ pub fn tree() -> Tree { Node::lit("guard").with([Node::lit("off").runs(), Node::arg("объекты", Value::word()).runs()]), Node::lit("reset").runs(), ])), + Node::lit("recon").runs(), Node::lit("stats").runs(), ]) } @@ -162,7 +163,7 @@ mod tests { #[test] fn every_branch_of_the_handler_parses() { for line in [ - "", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "roles", + "", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "recon", "roles", "replay", "replay map", "replay full", "replay reel", "replay film", "replay film best", "replay film all", "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", @@ -241,10 +242,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", "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"] { assert!(top.contains(&w.to_string()), "{w} in {top:?}"); } - assert_eq!(top.len(), 35); + assert_eq!(top.len(), 36); 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 3366b01..bf8aafc 100644 --- a/airdef-mod/src/lib.rs +++ b/airdef-mod/src/lib.rs @@ -24,6 +24,7 @@ mod monitor; mod panel; mod presentation; mod radar; +mod recon_view; mod replay; mod scene; mod smoke; @@ -200,6 +201,8 @@ enum Page { More, /// The last raid's events and its replays. Replays, + /// 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). Fleet, Doctrine(u32), @@ -235,7 +238,9 @@ const BTN_LAUNCH: u32 = 34; const BTN_NEXT: u32 = 35; const BTN_MORE: u32 = 17; const BTN_REPLAYS: u32 = 18; +const BTN_RECON: u32 = 23; const REPLAY_EVENTS: u32 = 3; +const RECON_ROWS: u32 = 6; const BTN_MAP: u32 = 40; const BTN_FULL: u32 = 41; const BTN_REEL: u32 = 42; @@ -1583,6 +1588,7 @@ impl AirDef { widgets.push(Widget::Button(ButtonWidget { id: BTN_DOCTRINE, label: format!("Доктрины: охрана, сектор, резерв (особых: {custom})…") })); widgets.push(Widget::Button(ButtonWidget { id: BTN_WAVE, label: "Налёт: состав и запуск…".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_REPLAYS, label: "Повторы…".into() })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)…".into() })); widgets.push(Widget::Button(ButtonWidget { id: BTN_MORE, label: "Огонь, ремонт, эффекты…".into() })); } Page::BatteryDeploy => { @@ -1604,6 +1610,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_RECON, label: "Разведка противника (разбор)".into() })); } None => { title = "Повторы".into(); @@ -1612,10 +1619,17 @@ impl AirDef { text: "Повторов пока нет: налёт записывается сам и появится здесь, когда небо очистится".into(), color: 0, })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() })); 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(); + widgets.push(Widget::List(ListWidget { id: RECON_ROWS, rows, selected: None })); + widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() })); + } Page::More => { title = "AirDef — управление".to_string(); widgets.push(Widget::Button(ButtonWidget { @@ -2263,6 +2277,16 @@ impl Mod for AirDef { self.open_menu(Page::Main); return; } + (Page::Main, BTN_RECON) | (Page::Replays, BTN_RECON) => { + self.open_menu(Page::Recon); + return; + } + (Page::Recon, BTN_BACK) => { + self.open_menu(Page::Main); + return; + } + // The review is read-only: a row click changes nothing. + (Page::Recon, RECON_ROWS) => return, (Page::Main, BTN_MORE) => { self.open_menu(Page::More); return; @@ -2588,6 +2612,14 @@ impl Mod for AirDef { self.set_effects(*v != "off", *v == "hd"); Some(format!("Эффекты: {}", match *v { "off" => "выкл", "hd" => "HD", _ => "обычные" })) } + ["recon"] => { + // The enemy's partial picture and why it prices each mark: explicit debug, never the + // normal HUD (#135). The same lines fill the after-action review page. + for l in recon_view::picture_lines(&self.sim.enemy_picture()) { + say(&l); + } + None + } ["stats"] => Some(format!( "В воздухе: {}, ракет: {}, ПВО: {}, сбито: {}, поражений: {}, разбились о препятствия: {}; удары по ПУ: пущено {}, уничтожено {}, подавлено {}, промахов {}, сбито ПВО {}; {}", self.sim.drones.iter().filter(|d| d.alive()).count(), diff --git a/airdef-mod/src/map.rs b/airdef-mod/src/map.rs index 7367e9b..dba6eb8 100644 --- a/airdef-mod/src/map.rs +++ b/airdef-mod/src/map.rs @@ -783,16 +783,26 @@ fn map_truth(sim: &Sim, ui: &mut MapUi, hover: Option, s: &mut Vec } prev = p; } - // The drone: a white frame, never the network's red diamond. - s.extend(frame(c.0 - 5.0, c.1 - 5.0, 10.0, 10.0, 1.2, alpha(WHITE, 0.95))); - s.push(fill(c.0 - 1.0, c.1 - 1.0, 2.0, 2.0, WHITE)); + // The drone: a white frame, never the network's red diamond. A recon aircraft has a + // sign of its own: an amber diamond, not the strike's frame (#135). + let recon = sim.is_recon_drone(d.id); + if recon { + let p = [(c.0, c.1 - 5.0), (c.0 + 5.0, c.1), (c.0, c.1 + 5.0), (c.0 - 5.0, c.1)]; + for i in 0..4 { + s.push(line(p[i], p[(i + 1) % 4], 1.2, alpha(0xFFC040, 0.95))); + } + } else { + s.extend(frame(c.0 - 5.0, c.1 - 5.0, 10.0, 10.0, 1.2, alpha(WHITE, 0.95))); + } + s.push(fill(c.0 - 1.0, c.1 - 1.0, 2.0, 2.0, if recon { alpha(0xFFC040, 0.95) } else { WHITE })); if ui.on_screen(aim, 6.0) { s.push(diamond(aim.0, aim.1, 4.5, alpha(0xFFE070, 0.85))); s.push(fill(aim.0 - 1.0, aim.1 - 1.0, 2.0, 2.0, alpha(0xFFE070, 0.9))); } taken.push([c.0 - 6.0, c.1 - 6.0, 12.0, 12.0]); let chosen = hover == Some(Hover::Drone(d.id)); - add_lab(ui, labs, format!("{} №{}", d.kind.spec().name, d.id), c, 7.0, alpha(YELLOW, 0.95), chosen); + let name = if recon { format!("разведчик №{}", d.id) } else { format!("{} №{}", d.kind.spec().name, d.id) }; + add_lab(ui, labs, name, c, 7.0, alpha(YELLOW, 0.95), chosen); if chosen { s.extend(frame(c.0 - 8.0, c.1 - 8.0, 16.0, 16.0, 1.0, GREEN)); } @@ -2299,26 +2309,34 @@ impl AirDef { let chosen = ui.sel == Some(Sel::Track(id)); let forecast = t.forecast(now); let age = t.age(now); - let col = if forecast { alpha(0xFFB0B0, 0.65) } else { 0xFFFF5050 }; - s.push(diamond(c.0, c.1, TRACK_R, col)); - if !forecast { - s.push(diamond(c.0, c.1, 3.0, 0xFF200808)); + // A recon aircraft is a role of its own: a yellow hollow diamond and a named label, so + // the player tells it from a strike drone the network tracks the same way (#135). + let recon = sim::is_drone_id(id); + let r = if recon { 5.0 } else { TRACK_R }; + let col = if recon { YELLOW } else if forecast { alpha(0xFFB0B0, 0.65) } else { 0xFFFF5050 }; + s.push(diamond(c.0, c.1, r, col)); + if recon || !forecast { + s.push(diamond(c.0, c.1, if recon { 2.0 } else { 3.0 }, 0xFF200808)); } // Its measured course, a tick out of the marker. let v = t.vel.normalize_or_zero(); if v != DVec3::ZERO { s.push(line(c, (c.0 + v.x as f32 * 10.0, c.1 + v.z as f32 * 10.0), 1.5, col)); } - taken.push([c.0 - TRACK_R - 1.0, c.1 - TRACK_R - 1.0, TRACK_R * 2.0 + 2.0, TRACK_R * 2.0 + 2.0]); - let mark = t.class.mark(); - let age = if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) }; - let txt = match (mark.is_empty(), forecast) { - (true, true) => format!("~{age}"), - (true, false) => age, - (false, true) => format!("{mark} ~{age}"), - (false, false) => format!("{mark} {age}"), + taken.push([c.0 - r - 1.0, c.1 - r - 1.0, r * 2.0 + 2.0, r * 2.0 + 2.0]); + let age_txt = if age < 20 { "сейчас".to_string() } else { format!("{} с", age / 20) }; + let txt = if recon { + format!("разведчик {age_txt}") + } else { + let mark = t.class.mark(); + match (mark.is_empty(), forecast) { + (true, true) => format!("~{age_txt}"), + (true, false) => age_txt, + (false, true) => format!("{mark} ~{age_txt}"), + (false, false) => format!("{mark} {age_txt}"), + } }; - add_lab(ui, labs, txt, c, TRACK_R + 1.0, col, chosen); + add_lab(ui, labs, txt, c, r + 1.0, col, chosen); if chosen { s.extend(frame(c.0 - 10.0, c.1 - 10.0, 20.0, 20.0, 1.0, GREEN)); } @@ -2437,6 +2455,9 @@ impl AirDef { inner.push(text(l, x0, y, GREY)); y += lh - 1.0; } + let rn = self.sim.picture().values().filter(|t| sim::is_drone_id(t.id)).count(); + inner.push(text(format!("жёлтый ромб — разведчик ({rn})"), x0, y, GREY)); + y += lh - 1.0; } _ => { inner.push(text("Имя сценария", x0, y, GREY)); @@ -2758,6 +2779,10 @@ impl AirDef { lines.push((format!("Трек №{id}: потерян сетью"), GREY)); return; }; + if sim::is_drone_id(id) { + lines.push((format!("Разведчик противника №{id}"), YELLOW)); + lines.push(("Роль: разведка (без оружия) — ищет технику вокруг объектов".into(), YELLOW)); + } let player = crate::player().map(|p| DVec3::new(p.x, p.y, p.z)); track_lines(&self.sim, t, player, lines); lines.push(("Тонкая линия — пройденное по измерениям,".into(), GREY)); @@ -2777,6 +2802,14 @@ impl AirDef { lines.push(("Режим ИСТИНА: настоящие дроны, их цели и маршруты.".into(), YELLOW)); lines.push(("Это песочница, не данные сети. T — обратно.".into(), YELLOW)); } + // The recon flight's phase, only while the network actually holds a recon aircraft: + // what the visible aircraft are doing, not what the enemy learned (#135). + if self.sim.picture().values().any(|t| sim::is_drone_id(t.id)) { + let pic = self.sim.enemy_picture(); + if let Some(phase) = crate::recon_view::battle_phase(&pic) { + lines.push((format!("Разведка противника: {phase} · разведчиков {}", pic.recon_sorties.len()), YELLOW)); + } + } if self.battle() { lines.push(("Идёт налёт: расстановка закрыта".into(), YELLOW)); } diff --git a/airdef-mod/src/panel.rs b/airdef-mod/src/panel.rs index c25fea9..923a2a9 100644 --- a/airdef-mod/src/panel.rs +++ b/airdef-mod/src/panel.rs @@ -64,6 +64,17 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec { )); } } + // Recon aircraft the network tracks: their presence and the coarse phase of the flight. This is + // what the visible aircraft are doing, not the enemy's knowledge — the marks and the reasons are + // the debug command's and the after-action review's alone (#135). + let recon_n = pic.tracks.iter().filter(|t| crate::sim::is_drone_id(t.id)).count(); + if recon_n > 0 { + let mut text = format!("Разведка противника: разведчиков в воздухе {recon_n}"); + if let Some(phase) = crate::recon_view::battle_phase(&sim.enemy_picture()) { + text += &format!(" · фаза: {phase}"); + } + lines.push(line(text, YELLOW)); + } if sim.truth { let real = sim.drones.iter().filter(|d| d.alive()).count(); let unseen = sim.drones.iter().filter(|d| d.alive() && pic.get(d.id).is_none()).count(); @@ -72,6 +83,12 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec { text += ", противник планирует налёт"; } lines.push(line(text, YELLOW)); + // The recon phase, in the truth only: the aircraft out and the marks the enemy holds + // are its knowledge, not the player's (#135). + let (out, marks) = sim.recon_status(); + if out > 0 || marks > 0 { + lines.push(line(format!("РАЗВЕДКА ПРОТИВНИКА: в воздухе {out}, отметок в картине {marks}"), YELLOW)); + } } // The launch sites found, and the strike missiles (#101). if !sim.strikes.known.is_empty() || !sim.strikes.flights.is_empty() { @@ -130,3 +147,64 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec { )); lines } + + +#[cfg(test)] +mod tests { + use super::*; + use crate::sim::{Aim, AirPicture, Approach, DroneKind, Out, RaidOrder, Track}; + use glam::DVec3; + + fn track(id: u32, class: ClassEst) -> Track { + Track { id, class, pos: DVec3::new(0.0, 120.0, 300.0), vel: DVec3::new(0.0, 0.0, -0.5), tick: 100, own_tick: 100, source: 0, product: crate::sim::battery::Measure::Search, quality: 40, own_product: crate::sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: false } + } + + // A recon aircraft the network holds is named as such, with the flight's coarse phase; the line + // carries no mark, area or priority — the enemy's knowledge is not the HUD's (#135). + #[test] + fn a_tracked_recon_aircraft_shows_presence_and_phase_not_marks() { + let mut sim = Sim::new(135); + let object = DVec3::new(0.0, 70.0, 0.0); + sim.targets.push(object); + sim.target_health.push(100.0); + let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart }; + sim.order_raid(&order, &[object], &mut Out::default()); + let pic = sim.air_picture(); + assert!(pic.tracks.iter().any(|t| crate::sim::is_drone_id(t.id)), "the smart wave sent no recon to track"); + let lines = summary(&sim, &pic, DVec3::ZERO); + let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line"); + assert!(recon.text.contains("разведчиков в воздухе"), "{}", recon.text); + assert!(recon.text.contains("фаза:"), "the flight's phase was not shown: {}", recon.text); + assert!(!recon.text.contains("приоритет") && !recon.text.contains("Отметка"), "the HUD leaked the enemy's marks: {}", recon.text); + assert!(lines.iter().all(|l| !l.text.contains("Отметка") && !l.text.contains("приоритет")), "a mark reached the normal HUD"); + } + + // An ordinary strike track is not a recon flight: no recon line appears. + #[test] + fn an_ordinary_track_is_not_called_recon() { + let sim = Sim::new(1); + let pic = AirPicture { now: 100, tracks: vec![track(1, ClassEst::Firm(Class::Drone))], unaided: false }; + let lines = summary(&sim, &pic, DVec3::ZERO); + assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}"); + } + + // A recon id in the picture is enough for the presence line even without a live sortie (a flight + // finishing its way home): the phase is then omitted, the presence stays. + #[test] + fn a_recon_track_without_a_sortie_still_names_the_presence() { + let sim = Sim::new(1); + let pic = AirPicture { now: 100, tracks: vec![track(0x3000_0001, ClassEst::Firm(Class::Drone))], unaided: false }; + let lines = summary(&sim, &pic, DVec3::ZERO); + let recon = lines.iter().find(|l| l.text.contains("Разведка противника")).expect("no recon line"); + assert!(recon.text.contains("разведчиков в воздухе 1"), "{}", recon.text); + assert!(!recon.text.contains("фаза:"), "a phase was invented without a sortie: {}", recon.text); + } + + #[test] + fn an_empty_sky_has_no_recon_line() { + let sim = Sim::new(1); + let pic = AirPicture { now: 100, tracks: Vec::new(), unaided: false }; + let lines = summary(&sim, &pic, DVec3::ZERO); + assert!(lines.iter().all(|l| !l.text.contains("Разведка противника")), "{lines:?}"); + } +} diff --git a/airdef-mod/src/recon_view.rs b/airdef-mod/src/recon_view.rs new file mode 100644 index 0000000..f47fbbf --- /dev/null +++ b/airdef-mod/src/recon_view.rs @@ -0,0 +1,286 @@ +//! Text for the enemy's reconnaissance (#135): the readable phase of a recon flight and the +//! reason a mark outranks another. It reads only the diagnostic report types (`EnemyPictureReport`, +//! `ReconReport`, `ReconSortieReport`) — an area, a public category, a channel, an age and a quality, +//! never a true place, `SamKind`, health, magazine, link or real id. The full picture is for the +//! explicit debug command and the after-action review; the battle HUD takes only the coarse phase +//! of aircraft the player's own network already tracks. +use crate::sim::{Category, Confidence, EnemyPictureReport, Quality, ReconReport, ReconSortieReport, priority_parts}; + +/// The public category a look reported, in the panel's words. +pub fn category_name(key: &str) -> &'static str { + match key { + "radar" => "РЛС", + "launcher" => "пусковая", + "gun" => "пушка", + "ew" => "РЭБ", + "support" => "тыл", + _ => "не определено", + } +} + +/// A radar's role, public only once a refined look told it. +pub fn role_name(key: &str) -> &'static str { + match key { + "multi" => "многофункциональная", + "search" => "обзорная", + "engagement" => "наведения", + "height" => "высотомер", + _ => "не определена", + } +} + +/// The channel that showed the unit. +pub fn source_name(key: &str) -> &'static str { + match key { + "emission" => "излучение", + "jamming" => "РЭБ", + "launch" => "пуск", + _ => "пролёт", + } +} + +/// How well the area is known. +pub fn quality_name(key: &str) -> &'static str { + match key { + "refined" => "уточнённая", + _ => "грубая", + } +} + +/// The trust the picture puts in a mark of this age. +pub fn confidence_name(confidence: Confidence) -> &'static str { + match confidence { + Confidence::Confirmed => "подтверждена", + Confidence::Probable => "вероятна", + Confidence::Doubtful => "сомнительна", + } +} + +/// The phase of a sortie, as the timeline and the battle UI read it. +pub fn phase_name(phase: &str) -> &'static str { + match phase { + "reporting" => "донесение", + "done" => "завершение", + "looking" => "осмотр", + _ => "разведка", + } +} + +/// Why a smart drone's aim is what it is, in words. +pub fn intent_name(intent: &str) -> &'static str { + match intent { + "sead" => "подавление ПВО", + "react" => "реакция", + "replace" => "замена", + _ => "план", + } +} + +/// One mark in a line: its area's category and role, the channel, the quality, the trust, the age +/// and the priority the planner prices it at. +pub fn mark_line(m: &ReconReport) -> String { + let role = m.role.map(|k| format!(" ({})", role_name(k))).unwrap_or_default(); + format!( + "Отметка {}: {}{} · {} · {} · {} · {} с назад · приоритет {}", + m.id, + category_name(m.category), + role, + source_name(m.source), + quality_name(m.quality), + confidence_name(m.confidence), + m.age / 20, + m.priority + ) +} + +/// Why the mark has the priority it does: the observed role, the freshness and the quality, each +/// with the weight the planner gives it, summing to the priority. The unit's true importance is not +/// in it — only what the look reported. +pub fn mark_reason(m: &ReconReport) -> String { + let category = Category::from_key(m.category).unwrap_or(Category::Unknown); + let quality = Quality::from_key(m.quality).unwrap_or(Quality::Coarse); + let role = m.role.and_then(crate::sim::battery::RadarRole::from_key); + let (freshness, quality_w, role_w) = priority_parts(m.confidence, quality, category, role); + let role_txt = match m.role { + Some(key) => format!("роль «{}»", role_name(key)), + None => format!("категория «{}»", category_name(m.category)), + }; + format!( + "приоритет {} = свежесть {}×4 + качество {}×3 + роль {}: {} {}, {}", + m.priority, + freshness, + quality_w, + role_w, + confidence_name(m.confidence), + quality_name(m.quality), + role_txt + ) +} + +/// One sortie in a line: its phase, the zones left and when its pending report is due. +pub fn sortie_line(s: &ReconSortieReport) -> String { + let mut text = format!("Разведчик {}: {}", s.drone, phase_name(s.phase)); + if s.zones_left > 0 { + text += &format!(" · зон осталось {}", s.zones_left); + } + if let Some(due) = s.report_in { + text += &format!(" · донесение через {} с", due / 20); + } + text +} + +/// The coarse phase of the recon flight for the battle UI: a report going home now, else aircraft +/// still looking, else the flight finishing. `None` when no sortie is out. It says nothing of what +/// the enemy learned — only what its visible aircraft are doing. +pub fn battle_phase(pic: &EnemyPictureReport) -> Option<&'static str> { + if pic.recon_sorties.iter().any(|s| s.phase == "reporting") { + Some("донесение") + } else if pic.recon_sorties.iter().any(|s| s.phase == "outbound" || s.phase == "looking") { + Some("разведка") + } else if !pic.recon_sorties.is_empty() { + Some("завершение") + } else { + None + } +} + +/// The whole picture for the debug command and the after-action review: the sorties and their +/// phases, then the marks best-first with the reason each outranks the rest, then the drones aimed +/// at a mark. Explicitly the enemy's belief, not the truth; never the normal HUD. +pub fn picture_lines(pic: &EnemyPictureReport) -> Vec { + let mut lines = Vec::new(); + if pic.recon.is_empty() && pic.recon_sorties.is_empty() { + lines.push("Разведки не было: противник не высылал разведчиков и ничего не запомнил.".into()); + return lines; + } + lines.push(format!( + "Картина противника (debug/разбор): отметок {}, разведчиков в воздухе {}", + pic.recon.len(), + pic.recon_sorties.len() + )); + for s in &pic.recon_sorties { + lines.push(sortie_line(s)); + } + let mut marks: Vec<&ReconReport> = pic.recon.iter().collect(); + marks.sort_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id))); + for m in marks { + lines.push(mark_line(m)); + lines.push(format!(" ↳ {}", mark_reason(m))); + } + for a in pic.aims.iter().filter(|a| a.recon) { + lines.push(format!( + "Дрон {} целится в отметку {} (приоритет {}, {})", + a.drone, + a.unit, + a.priority.unwrap_or(0), + intent_name(a.intent) + )); + } + lines +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sim::{AimReport, Confidence, EnemyPictureReport, ReconReport, ReconSortieReport}; + use glam::DVec3; + + fn mark(id: u32, category: &'static str, role: Option<&'static str>, quality: &'static str, confidence: Confidence, age: u64) -> ReconReport { + let cat = Category::from_key(category).unwrap(); + let qual = Quality::from_key(quality).unwrap(); + let role_enum = role.and_then(crate::sim::battery::RadarRole::from_key); + let (f, q, r) = priority_parts(confidence, qual, cat, role_enum); + ReconReport { id, area: DVec3::ZERO, radius: 120.0, category, role, source: "flyby", age, quality, confidence, live: true, priority: f * 4 + q * 3 + r } + } + + fn sortie(drone: u32, phase: &'static str, zones_left: usize, report_in: Option) -> ReconSortieReport { + ReconSortieReport { drone, phase, zones_left, report_in } + } + + fn picture(recon: Vec, recon_sorties: Vec, aims: Vec) -> EnemyPictureReport { + EnemyPictureReport { now: 1000, contacts: Vec::new(), aims, pending: Vec::new(), work_per_tick: 4, recon, recon_sorties } + } + + // The reason names all three factors with the planner's own weights, and they sum to the priority. + #[test] + fn the_reason_is_the_observed_role_freshness_and_quality() { + let m = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Confirmed, 100); + let reason = mark_reason(&m); + assert_eq!(m.priority, 4 * 4 + 2 * 3 + 3); + assert!(reason.contains("приоритет 25 = свежесть 4×4 + качество 2×3 + роль 3"), "{reason}"); + assert!(reason.contains("подтверждена") && reason.contains("уточнённая") && reason.contains("роль «наведения»"), "{reason}"); + // A coarse, doubtful, unknown mark: every part is zero, and the reason says so. + let weak = mark(0x1000_0002, "unknown", None, "coarse", Confidence::Doubtful, 5000); + assert_eq!(weak.priority, 0); + let weak_reason = mark_reason(&weak); + assert!(weak_reason.contains("свежесть 0×4 + качество 0×3 + роль 0"), "{weak_reason}"); + assert!(weak_reason.contains("сомнительна") && weak_reason.contains("категория «не определено»"), "{weak_reason}"); + } + + // A fresh modest mark can outrank a stale big one: the reason reflects the age, not the truth. + #[test] + fn a_fresh_modest_mark_outranks_a_stale_big_one() { + let stale_big = mark(0x1000_0001, "radar", Some("engagement"), "refined", Confidence::Doubtful, 5000); + let fresh_modest = mark(0x1000_0002, "gun", None, "coarse", Confidence::Confirmed, 100); + assert!(fresh_modest.priority > stale_big.priority, "{} vs {}", fresh_modest.priority, stale_big.priority); + let fresh_id = fresh_modest.id; + let lines = picture_lines(&picture(vec![stale_big, fresh_modest], Vec::new(), Vec::new())); + let first = lines.iter().position(|l| l.starts_with("Отметка")).unwrap(); + assert!(lines[first].contains(&format!("Отметка {fresh_id}")), "the fresh modest mark did not lead: {lines:?}"); + } + + #[test] + fn the_phase_reads_recon_report_and_done() { + assert_eq!(phase_name("outbound"), "разведка"); + assert_eq!(phase_name("reporting"), "донесение"); + assert_eq!(phase_name("done"), "завершение"); + let reporting = picture(Vec::new(), vec![sortie(0x3000_0001, "reporting", 0, Some(40)), sortie(0x3000_0002, "outbound", 2, None)], Vec::new()); + assert_eq!(battle_phase(&reporting), Some("донесение")); + let looking = picture(Vec::new(), vec![sortie(0x3000_0001, "outbound", 2, None)], Vec::new()); + assert_eq!(battle_phase(&looking), Some("разведка")); + let done = picture(Vec::new(), vec![sortie(0x3000_0001, "done", 0, None)], Vec::new()); + assert_eq!(battle_phase(&done), Some("завершение")); + assert_eq!(battle_phase(&picture(Vec::new(), Vec::new(), Vec::new())), None); + assert!(sortie_line(&sortie(0x3000_0001, "reporting", 1, Some(40))).contains("донесение через 2 с")); + } + + #[test] + fn an_empty_picture_says_there_was_no_recon() { + let lines = picture_lines(&picture(Vec::new(), Vec::new(), Vec::new())); + assert_eq!(lines.len(), 1); + assert!(lines[0].contains("Разведки не было"), "{lines:?}"); + } + + // The review shows the marks with their reasons and the drones aimed at them; the ids are the + // synthetic ones, and nothing of the unit's truth (kind, health, exact place) is in the report. + #[test] + fn the_review_lists_marks_reasons_and_recon_aims() { + let m = mark(0x1000_0001, "launcher", None, "coarse", Confidence::Probable, 1000); + let mid = m.id; + let aim = AimReport { drone: 7, unit: mid, intent: "sead", since: 900, switches: 0, confidence: Some(Confidence::Probable), recon: true, priority: Some(m.priority) }; + let unit_aim = AimReport { drone: 8, unit: 3, intent: "plan", since: 900, switches: 0, confidence: Some(Confidence::Confirmed), recon: false, priority: None }; + let lines = picture_lines(&picture(vec![m], vec![sortie(0x3000_0001, "outbound", 1, None)], vec![aim, unit_aim])); + assert!(lines.iter().any(|l| l.contains(&format!("Отметка {mid}")) && l.contains("пусковая")), "{lines:?}"); + assert!(lines.iter().any(|l| l.contains("↳") && l.contains("приоритет")), "{lines:?}"); + assert!(lines.iter().any(|l| l.contains("Дрон 7 целится в отметку") && l.contains("подавление ПВО")), "{lines:?}"); + // A unit contact's aim is not a recon aim: it is not listed here. + assert!(!lines.iter().any(|l| l.contains("Дрон 8")), "{lines:?}"); + // No true unit id leaks: the mark id is synthetic, far above any real unit's. + assert!(mid >= 0x1000_0000); + } + + #[test] + fn every_public_name_is_translated() { + for key in ["unknown", "radar", "launcher", "gun", "ew", "support"] { + assert_ne!(category_name(key), key, "{key}"); + } + for key in ["multi", "search", "engagement", "height"] { + assert_ne!(role_name(key), key, "{key}"); + } + for key in ["flyby", "emission", "jamming", "launch"] { + assert_ne!(source_name(key), key, "{key}"); + } + assert_ne!(quality_name("coarse"), "coarse"); + assert_ne!(quality_name("refined"), "refined"); + } +} diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 55bc7c7..5f9cd6d 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -27,8 +27,8 @@ mod terrain; mod ew; mod recon; mod durable; -pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport}; -pub use recon::{Category, Mark, Quality, Source}; +pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport, ReconReport, ReconSortieReport}; +pub use recon::{Category, Mark, Quality, Source, is_drone_id, priority_parts}; pub mod lights; mod logistics; mod orders; diff --git a/airdef-mod/src/sim/recon.rs b/airdef-mod/src/sim/recon.rs index 85f95dc..ccea64e 100644 --- a/airdef-mod/src/sim/recon.rs +++ b/airdef-mod/src/sim/recon.rs @@ -57,8 +57,9 @@ pub(super) fn is_mark(id: u32) -> bool { (ID_BASE..MARK_TOP).contains(&id) } -/// Whether an id belongs to a recon aircraft (a role of its own, not a strike drone). -pub(super) fn is_drone_id(id: u32) -> bool { +/// Whether an id belongs to a recon aircraft (a role of its own, not a strike drone). The +/// player's map and panel read it to mark a tracked aircraft as a recon flight (#135). +pub fn is_drone_id(id: u32) -> bool { id >= DRONE_BASE } @@ -85,7 +86,7 @@ impl Category { Self::Support => "support", } } - pub(super) fn from_key(key: &str) -> Option { + pub fn from_key(key: &str) -> Option { [Self::Unknown, Self::Radar, Self::Launcher, Self::Gun, Self::Ew, Self::Support].into_iter().find(|c| c.name() == key) } /// The public role a look at this kind can tell apart, nothing finer. @@ -101,7 +102,7 @@ impl Category { } } /// What a confirmed contact of this category is worth to the planner, before freshness. - pub(super) fn weight(self) -> u8 { + pub fn weight(self) -> u8 { match self { Self::Radar | Self::Launcher => 3, Self::Ew | Self::Gun => 2, @@ -112,7 +113,7 @@ impl Category { } /// A radar role is public only after a refined look; a coarse report leaves it unknown. -pub(super) fn role_weight(role: battery::RadarRole) -> u8 { +pub fn role_weight(role: battery::RadarRole) -> u8 { match role { battery::RadarRole::Multifunction | battery::RadarRole::Engagement => 3, battery::RadarRole::Search => 2, @@ -120,6 +121,24 @@ pub(super) fn role_weight(role: battery::RadarRole) -> u8 { } } +/// The three parts a mark's priority is priced from, in the same terms `Mark::priority` uses: +/// freshness (its confidence band), how well it is known (quality) and the observed public role +/// (a refined radar's role, else its category). The priority is `freshness * 4 + quality * 3 + role` +/// (#135). The diagnostic reads this to show *why* a mark outranks another, never the unit's truth. +pub fn priority_parts(confidence: Confidence, quality: Quality, category: Category, role: Option) -> (u8, u8, u8) { + let freshness = match confidence { + Confidence::Confirmed => 4, + Confidence::Probable => 2, + Confidence::Doubtful => 0, + }; + let quality = match quality { + Quality::Refined => 2, + Quality::Coarse => 0, + }; + let role = role.map_or_else(|| category.weight(), role_weight); + (freshness, quality, role) +} + #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Quality { Coarse, @@ -133,7 +152,7 @@ impl Quality { Self::Refined => "refined", } } - pub(super) fn from_key(key: &str) -> Option { + pub fn from_key(key: &str) -> Option { [Self::Coarse, Self::Refined].into_iter().find(|q| q.name() == key) } } @@ -485,6 +504,18 @@ pub(super) fn plan_zones(objects: &[DVec3], state: &Recon, now: u64) -> Vec bool { + recon::is_drone_id(id) + } + + /// The recon flight's state for the sandbox's truth line (#135): the aircraft still out + /// with a task, and the marks the picture holds. Nothing of the hidden force is in it. + pub fn recon_status(&self) -> (usize, usize) { + (self.recon.sorties.len(), self.recon.marks.values().filter(|m| m.live(self.tick)).count()) + } + /// Sends the raid's recon flight: a few unarmed aircraft, physically in the air, ahead /// of the strike. Their zones come from the marked objectives alone, never from the /// hidden force, so the same seed and objectives order the same flight whatever the @@ -854,6 +885,29 @@ mod tests { assert!(leads.iter().all(|m| m.id != 1 && m.id != 2), "a true id leaked into the marks"); } + // #135: the diagnostic's breakdown is the planner's own price: for every confidence, quality, + // category and role the parts sum to exactly `Mark::priority`, so the reason shown can never + // drift from the order the planner actually uses. + #[test] + fn priority_parts_sum_to_the_planners_priority() { + for confidence in [Confidence::Doubtful, Confidence::Probable, Confidence::Confirmed] { + let now = match confidence { + Confidence::Confirmed => 100, + Confidence::Probable => 1000, + Confidence::Doubtful => 4000, + }; + for quality in [Quality::Coarse, Quality::Refined] { + for category in [Category::Unknown, Category::Radar, Category::Launcher, Category::Gun, Category::Ew, Category::Support] { + for role in [None, Some(battery::RadarRole::Search), Some(battery::RadarRole::Engagement), Some(battery::RadarRole::Height), Some(battery::RadarRole::Multifunction)] { + let m = Mark { id: ID_BASE + 1, area: DVec3::ZERO, radius: COARSE_AREA, category, role, source: Source::Flyby, observed: 0, reported: 0, quality, looks: 1 }; + assert_eq!(m.confidence(now), confidence); + let (f, q, r) = priority_parts(confidence, quality, category, role); + assert_eq!(f * 4 + q * 3 + r, m.priority(now), "{confidence:?} {quality:?} {category:?} {role:?}"); + } + } + } + } + } // #135: only the smart enemy gets the phase. A simple preset's raid gets no aircraft and // spends no time on a role it never had. diff --git a/docs/IMPLEMENTATION-STATUS.md b/docs/IMPLEMENTATION-STATUS.md index 03b816a..e91b05b 100644 --- a/docs/IMPLEMENTATION-STATUS.md +++ b/docs/IMPLEMENTATION-STATUS.md @@ -55,6 +55,7 @@ | #124 | Motion + object transforms + feature-gated DLSS SR: engine `ed751714e`; NGX+HDR bootstrap, долгоживущий SDK/context, display↔linear conversion и ordered submit; native TAAU fallback. Полный `cargo xwin build` на MSVC и `v0.4.0-dlss-rc1` с PE32+, `airdef.hmod`, `nvngx_dlss.dll`, notices и A/B launchers опубликованы; 24 HD + layout, mods/no-mods, обычный Metal кадр проверены | Runtime/качество/FPS на RTX/Vulkan не подтверждены; нужна приёмка по `docs/DLSS-TESTING.md`. Ванильные сущности/ветер camera-only; reactive/transparency, FSR3/MetalFX и FG отдельно | | #130 | Первый небольшой backport: upstream `f7b77fbc8` перенесён как engine `94b572cd2`; oversized staging allocations округляются до степени двойки и переиспользуются, копируются только фактические байты; 3 upload/GPU readback-теста прошли на Metal | Полная миграция на Nightly не начата; VSync/pacing, дальний рельеф и другие кандидаты остаются; Windows/Vulkan и долгий игровой RSS-профиль не проверялись | | #127 | Этапы 1–2. **Картина:** журнал раскрытий заменён картой контактов (`Intel.contacts`: последнее «пуск/излучение/глушение», место, время, метка эмиссии, наблюдённая гибель, счётчик увиденных пусков), уверенность — функция возраста (Confirmed/Probable/Doubtful, TTL 6000), угроза и цены читают только published-параметры и факты наблюдений (launcher-only без донора «слеп»), уничтожение учится только из BSA. **Structured intent:** `Intent` (Plan/Sead/React/Replace) и `Aim` (юнит, since, switches, confidence) отделены от random-выбора; throttle `SWITCH_HOLD=160`, `SWITCH_CAP=3`, `ASSIGN_PER_TICK=16`, `ASSIGN_PER_CONTACT=6`, цена смены `SWITCH_GAIN=120`; в полёте цель меняется только когда картинка её убила/забыла. **Durable queue:** автосейв пишет версионированную секцию `air 1` — дроны, очередь запуска, задания (id, дрон, цель, юнит, версия, приоритет, намерение, версия рельефа), контакты, RLE-рельеф; очередь ограничена 256, устаревшие/фантомные/дублирующие задания отменяются при загрузке (`JOB_TTL=1200`), картина задания восстанавливается на свою версию, старые saves читаются (пустое небо), сценарии воздух не несут, Live/Replay не смешиваются. **Неизвестная земля не бесплатна** (`Relief.unknown=6` у повторного плана). **Объяснимость:** `enemy_picture()` дополнен aims/pending reason/aimed_by/pending_jobs без русского текста в core. Метаморфные тесты скрытых изменений (включая нагрев/замок РЭБ), save/restore посреди незавершённой очереди, детерминизм seed, 40+ массовый ретаргет. Замеры: `docs/measurements/issue-127-intent-queue-{baseline,result}.json` | GUI поверх `enemy_picture()`, игровая приёмка сохранения налёта на Windows/Linux, оценка баланса ew-adaptive (kills 59→58/59→58/56→63, потери 3→3/3→4/4→2 — следствие throttle, параметры не менялись) | +| #135 | **Core (`9d8f3da57`):** умная волна высылает ограниченный бюджет невооружённых разведчиков (Gerbera, собственные id `0x3000_0000`, не тратят combat RNG волны и не входят в её replay); они физически проходят игровые зоны вокруг отмеченных целей и через `REPORT_DELAY` передают только область, публичную категорию, канал (пролёт/излучение/РЭБ/пуск), возраст и качество — без точной точки, `SamKind`, HP, боезапаса, сети и реального id. Сбитый до донесения разведчик ничего не передаёт; уже переданное остаётся и переживает налёты. Планировщик читает отметки наравне с контактами раскрытия и назначает по наблюдаемой роли/свежести/качеству (`Mark::priority`), скрытая станция не становится целью, старая сомнительная отметка уступает свежей скромной; бюджет назначений и исходные цели волны сохранены. Save/load хранит отметки, вылеты, ожидающие донесения и проверенные зоны. **UI/диагностика (этот коммит):** на карте сети разведчик — узнаваемый жёлтый ромб с подписью «разведчик», роль в панели выбора и легенда фильтра; в боевом HUD и на карте — понятная фаза вылета (разведка/донесение/завершение) только пока сеть держит разведчика; в sandbox-режиме `truth` — янтарная метка и счётчик отметок. Причина выбора показана в `/airdef recon` и на странице меню «Разведка противника (разбор)» (из «Повторы…»): отметки best-first с разбором `приоритет = свежесть×4 + качество×3 + роль` (`recon::priority_parts`, сверен тестом с `Mark::priority`) и дроны, нацеленные на отметку. Всеведущая картина противника в обычный HUD не выводится — только явный debug/разбор. Механика, модели и текстуры не менялись. Тесты: `priority_parts`-кросс-чек, `recon_view`, панель, дерево команд | Игровая/визуальная приёмка значка и фазы на Windows/Linux; приёмка разбора в GUI; баланс приоритетов по серии seed остаётся за core-приёмкой | По #127 реализованы карта контактов, структурированное намерение с throttle и durable-очередь: autosave хранит дронов, очередь запуска, задания с картиной и рельефом своей версии, поэтому