diff --git a/README.md b/README.md index a7e4e34..2cc682f 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 5ac0aab..c926d4f 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; @@ -1587,6 +1592,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 => { @@ -1608,6 +1614,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(); @@ -1616,10 +1623,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 { @@ -2267,6 +2281,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; @@ -2592,6 +2616,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 1dfa54e..e98ef46 100644 --- a/airdef-mod/src/map.rs +++ b/airdef-mod/src/map.rs @@ -784,16 +784,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)); } @@ -2349,26 +2359,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)); } @@ -2487,6 +2505,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)); @@ -2827,6 +2848,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)); @@ -2846,6 +2871,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 b8e9973..0a175c1 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() { @@ -135,3 +152,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/durable.rs b/airdef-mod/src/sim/durable.rs index 8df7d57..38155e3 100644 --- a/airdef-mod/src/sim/durable.rs +++ b/airdef-mod/src/sim/durable.rs @@ -9,6 +9,11 @@ //! picture is mixed into a replay: a recording keeps trajectories, and this section is written and //! read for the live simulation only. //! +//! Reconnaissance flights and the partial picture they radioed home are part of the same +//! section (#135): their marks (an area, a category and an age, never a unit's truth), the +//! sorties still out with their pending reports, and the zones already checked. A save keeps +//! that memory across raids, and a restored flight finishes the same way. +//! //! The format is its own versioned section of `state_text` (`air 1 ...`). A save without the section //! (every save made before #127) loads exactly as before: the layout, and an empty sky. Every value is //! checked before anything is restored, like [`layout`](crate::layout): a bad line refuses the whole @@ -25,6 +30,9 @@ const MAX_DRONES: usize = 512; /// Bytes the section may take before further drones are left out (the host allows 1 MiB a write; /// the layout and the headroom of the rest of the state stay clear of it). const MAX_BYTES: usize = 900_000; +/// Bytes the recon block (marks, checked zones, sorties) may take. The drone loop keeps this much +/// room free, so the recon memory never pushes the section past `MAX_BYTES` (#135). +const MAX_RECON_BYTES: usize = 150_000; /// Route points one drone may have in a save. const MAX_ROUTE: usize = 512; /// Contacts (the picture, and a job's picture rebuilt from it) a save may hold. @@ -32,6 +40,10 @@ const MAX_CONTACTS: usize = 4096; /// Relief versions a save may hold, and the cells of each. const MAX_RELIEFS: usize = 8; const MAX_CELLS: usize = 40_000; +/// Recon marks, checked zones and sorties a save may hold (#135). +const MAX_RECON_MARKS: usize = recon::MAX_MARKS; +const MAX_RECON_CHECKED: usize = recon::MAX_CHECKED; +const MAX_RECON_SORTIES: usize = recon::SORTIES_MAX * 2; /// What the air section of a save holds, checked as a whole before the scene is touched. pub struct AirSave { @@ -45,6 +57,8 @@ pub struct AirSave { jobs: Vec, /// The land new retarget jobs take as their version. known_relief: Option>, + /// The enemy's recon flights and the partial picture they radioed home (#135). + recon: recon::Recon, } pub(crate) struct JobRec { @@ -198,6 +212,7 @@ impl Sim { ^ (self.retargets.len() as u64) << 24 ^ (self.intel.contacts().len() as u64) << 36 ^ (self.job_next as u64) << 48 + ^ self.recon.mark().rotate_left(12) } /// The air section of the state text: `None` when there is nothing to keep (an empty sky and no @@ -273,7 +288,7 @@ impl Sim { // job with it (a job whose drone is not saved could never be restored). let mut body = String::new(); let mut saved: std::collections::HashSet = std::collections::HashSet::new(); - let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() <= MAX_BYTES; + let fits = |head: &str, body: &str, line: &str| head.len() + 32 + body.len() + line.len() + MAX_RECON_BYTES <= MAX_BYTES; let mut drone_count = 0usize; for d in &drones { let line = d.air_line("airdrone", ""); @@ -296,14 +311,15 @@ impl Sim { saved.insert(d.id); queued_count += 1; } - let units: std::collections::HashSet = contacts.iter().map(|c| c.id).collect(); + // A job's unit may be an exact contact or a recon mark's synthetic id (#135). + let units: std::collections::HashSet = contacts.iter().map(|c| c.id).chain(self.recon.marks.keys().copied()).collect(); let jobs: Vec<(&ew::RouteJob, Option)> = self .retargets .iter() .zip(job_relief) .filter(|(j, _)| saved.contains(&j.drone) && (j.unit == 0 || units.contains(&j.unit))) .collect(); - if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() { + if drone_count == 0 && queued_count == 0 && jobs.is_empty() && contacts.is_empty() && self.recon.is_empty() { return None; } let head = head.replacen( @@ -328,6 +344,89 @@ impl Sim { relief.map_or_else(|| "-".into(), |t| t.to_string()) ); } + // Recon: the marks are memory (survive a new raid), the sorties are the aircraft still + // out, and the zones already reported empty. Everything is bounded, and each line is + // added only while the block stays inside its budget (#135). + if !self.recon.is_empty() { + let room = MAX_RECON_BYTES.min(MAX_BYTES.saturating_sub(text.len() + 96)); + let mut recon_body = String::new(); + let mut add = |line: &str| -> bool { + if recon_body.len() + line.len() > room { + return false; + } + recon_body.push_str(line); + true + }; + let mut marks = 0usize; + for m in self.recon.marks.values().take(MAX_RECON_MARKS) { + let truth = self.recon.truth.get(&m.id).copied().unwrap_or(0); + let line = format!( + "airreconmark {} {} {} {} {} {} {} {} {} {} {} {} {}\n", + m.id, + truth, + coord(m.area.x), + coord(m.area.y), + coord(m.area.z), + coord(m.radius), + m.category.name(), + m.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()), + m.source.name(), + m.quality.name(), + m.observed, + m.reported, + m.looks, + ); + if !add(&line) { + break; + } + marks += 1; + } + let mut checked = 0usize; + for ((i, j), t) in self.recon.checked.iter().take(MAX_RECON_CHECKED) { + if !add(&format!("airreconchecked {i} {j} {t}\n")) { + break; + } + checked += 1; + } + let mut sorties = 0usize; + for s in self.recon.sorties.iter().filter(|s| saved.contains(&s.drone)).take(MAX_RECON_SORTIES) { + // A sortie is written whole or not at all: its look and zone lines follow its header. + let mut body = format!( + "airrec {} {} {} {} {} {} {}\n", + s.drone, + s.launched, + s.next, + tick(s.report_at), + s.report_zone.map_or_else(|| "-".into(), |z| z.to_string()), + s.pending.len(), + s.zones.len(), + ); + for l in &s.pending { + body += &format!( + "airrecobs {} {} {} {} {} {} {} {} {} {}\n", + l.truth, + coord(l.area.x), + coord(l.area.y), + coord(l.area.z), + coord(l.radius), + l.category.name(), + l.role.map_or_else(|| "-".to_string(), |r| r.key().to_string()), + l.quality.name(), + l.source.name(), + l.observed, + ); + } + for z in &s.zones { + body += &format!("airreczone {} {} {} {}\n", coord(z.center.x), coord(z.center.y), coord(z.center.z), coord(z.radius)); + } + if !add(&body) { + break; + } + sorties += 1; + } + text += &format!("airrecon {} {} {} {} {}\n", self.recon.next, self.recon.drone_next, marks, sorties, checked); + text += &recon_body; + } Some(text) } @@ -373,6 +472,12 @@ impl Sim { let mut drones: BTreeMap = BTreeMap::new(); let mut queue: Vec<(u64, Drone)> = Vec::new(); let mut jobs: Vec = Vec::new(); + // Recon (#135): a mark line carries the unit it is of (the observer's secret, never in + // the planner's picture); a sortie's look and zone lines follow its header. + let mut recon = recon::Recon::default(); + let mut recon_head: Option<(usize, usize, usize)> = None; + let mut recon_sortie_at: Option = None; + let mut recon_expect: Vec<(usize, usize)> = Vec::new(); for (n, w) in &lines { if w.first() == Some(&"air") { continue; @@ -512,6 +617,148 @@ impl Sim { }; jobs.push(JobRec { id, drone, aim, unit, version, intent, relief }); } + "airrecon" => { + if w.len() != 6 { + return Err(l.bad("разведка", "нужны счётчики отметок и дронов, отметки, разведчики и проверенные зоны")); + } + let next = l.int(1, "счётчик отметок", 0, i64::from(recon::MARK_TOP - recon::ID_BASE - 1))? as u32; + let drone_next = l.int(2, "счётчик дронов", 0, i64::from(recon::DRONE_TOP - recon::DRONE_BASE - 1))? as u32; + let marks = l.count(3, "отметки", MAX_RECON_MARKS)?; + let sorties = l.count(4, "разведчики", MAX_RECON_SORTIES)?; + let checked = l.count(5, "проверенные зоны", MAX_RECON_CHECKED)?; + if recon_head.is_some() { + return Err(l.bad("разведка", "заголовок записан дважды")); + } + recon_head = Some((marks, sorties, checked)); + recon.next = next; + recon.drone_next = drone_next; + } + "airreconmark" => { + if w.len() != 14 { + return Err(l.bad("отметка разведки", "нужны id, юнит, место, категория, источник, качество и времена")); + } + let id = l.int(1, "id отметки", 0, i64::from(u32::MAX))? as u32; + if !recon::is_mark(id) { + return Err(l.bad("id отметки", "не в диапазоне отметок")); + } + let truth = l.int(2, "юнит отметки", 0, 1 << 30)? as u32; + let area = DVec3::new(l.num(3, "отметка X")?, l.num(4, "отметка Y")?, l.num(5, "отметка Z")?); + let radius = l.num(6, "радиус отметки")?; + if radius <= 0.0 { + return Err(l.bad("радиус отметки", "должен быть больше нуля")); + } + let category = recon::Category::from_key(l.word(7, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?; + let role = match l.word(8, "роль")? { + "-" => None, + key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?), + }; + let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?; + let quality = recon::Quality::from_key(l.word(10, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?; + let observed = l.int(11, "такт наблюдения", 0, tick as i64)? as u64; + let reported = l.int(12, "такт донесения", 0, tick as i64)? as u64; + let looks = l.int(13, "число взглядов", 0, u16::MAX as i64)? as u16; + if recon.marks.contains_key(&id) { + return Err(l.bad("id отметки", "отметка записана дважды")); + } + recon.truth.insert(id, truth); + recon.marks.insert(id, recon::Mark { + id, + area, + radius, + category, + role, + source, + observed, + reported, + quality, + looks, + }); + let slot = id.saturating_sub(recon::ID_BASE); + recon.next = recon.next.max(slot); + } + "airreconchecked" => { + if w.len() != 4 { + return Err(l.bad("проверенная зона", "нужны X, Z и такт")); + } + let i = l.int(1, "зона X", -3_000_000, 3_000_000)?; + let j = l.int(2, "зона Z", -3_000_000, 3_000_000)?; + let t = l.int(3, "такт проверки", 0, tick as i64)? as u64; + recon.checked.insert((i, j), t); + } + "airrec" => { + if w.len() != 8 { + return Err(l.bad("разведчик", "нужны дрон, вылет, зона, донесение и счётчики")); + } + let drone = l.int(1, "дрон разведчика", 1, 1 << 30)? as u32; + let launched = l.int(2, "вылет", 0, tick as i64)? as u64; + let next = l.count(3, "следующая зона", 1_000_000)?; + let report_at = l.opt_tick(4, "такт донесения")?; + let report_zone = match l.word(5, "зона донесения")? { + "-" => None, + v => Some(v.parse::().map_err(|_| l.bad("зона донесения", "не номер"))?), + }; + let pending = l.count(6, "ожидающие наблюдения", recon::MAX_OBSERVED)?; + let zones = l.count(7, "зоны разведчика", recon::ZONES_MAX)?; + if recon.sorties.iter().any(|s| s.drone == drone) { + return Err(l.bad("дрон разведчика", "разведчик записан дважды")); + } + recon.sorties.push(recon::Sortie { + drone, + zones: Vec::new(), + next, + launched, + report_at, + report_zone, + pending: Vec::new(), + }); + recon_sortie_at = Some(recon.sorties.len() - 1); + recon_expect.push((pending, zones)); + } + "airrecobs" => { + if w.len() != 11 { + return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник и такт")); + } + let Some(at) = recon_sortie_at else { + return Err(l.bad("наблюдение разведки", "строка без разведчика")); + }; + let (want, _) = recon_expect[at]; + if recon.sorties[at].pending.len() >= want { + return Err(l.bad("наблюдение разведки", "наблюдений больше объявленного")); + } + let truth = l.int(1, "юнит наблюдения", 0, 1 << 30)? as u32; + let area = DVec3::new(l.num(2, "наблюдение X")?, l.num(3, "наблюдение Y")?, l.num(4, "наблюдение Z")?); + let radius = l.num(5, "радиус наблюдения")?; + if radius <= 0.0 { + return Err(l.bad("радиус наблюдения", "должен быть больше нуля")); + } + let category = recon::Category::from_key(l.word(6, "категория")?).ok_or_else(|| l.bad("категория", "unknown, radar, launcher, gun, ew или support"))?; + let role = match l.word(7, "роль")? { + "-" => None, + key => Some(battery::RadarRole::from_key(key).ok_or_else(|| l.bad("роль", "multi, search, engagement или height"))?), + }; + let quality = recon::Quality::from_key(l.word(8, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?; + let source = recon::Source::from_key(l.word(9, "источник")?).ok_or_else(|| l.bad("источник", "flyby, emission, jamming или launch"))?; + let observed = l.int(10, "такт наблюдения", 0, tick as i64)? as u64; + recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed }); + } + "airreczone" => { + if w.len() != 5 { + return Err(l.bad("зона разведчика", "нужны X, Y, Z и радиус")); + } + let Some(at) = recon_sortie_at else { + return Err(l.bad("зона разведчика", "строка без разведчика")); + }; + let (_, want) = recon_expect[at]; + if recon.sorties[at].zones.len() >= want { + return Err(l.bad("зона разведчика", "зон больше объявленного")); + } + let center = DVec3::new(l.num(1, "зона X")?, l.num(2, "зона Y")?, l.num(3, "зона Z")?); + let radius = l.num(4, "радиус зоны")?; + if radius <= 0.0 { + return Err(l.bad("радиус зоны", "должен быть больше нуля")); + } + recon.sorties[at].zones.push(recon::Zone { center, radius }); + } other => return Err(l.bad("строка", &format!("неизвестная строка воздушной части «{other}»"))), } } @@ -540,6 +787,32 @@ impl Sim { if let Some(g) = global && reliefs[g].is_none() { return Err("воздушная часть: глобальный рельеф не записан".into()); } + if let Some((marks, sorties, checked)) = recon_head { + if recon.marks.len() != marks { + return Err(format!("воздушная часть: отметок разведки {} вместо {marks}", recon.marks.len())); + } + if recon.sorties.len() != sorties { + return Err(format!("воздушная часть: разведчиков {} вместо {sorties}", recon.sorties.len())); + } + if recon.checked.len() != checked { + return Err(format!("воздушная часть: проверенных зон {} вместо {checked}", recon.checked.len())); + } + } else if !recon.is_empty() { + return Err("воздушная часть: разведка без заголовка airrecon".into()); + } + for (i, (pending, zones)) in recon_expect.iter().enumerate() { + if recon.sorties[i].pending.len() != *pending || recon.sorties[i].zones.len() != *zones { + return Err(format!("воздушная часть: разведчик {i} записан не полностью")); + } + if recon.sorties[i].next > recon.sorties[i].zones.len() { + return Err(format!("воздушная часть: разведчик {i} смотрит за пределами зон")); + } + if let Some(z) = recon.sorties[i].report_zone + && z >= recon.sorties[i].zones.len() + { + return Err(format!("воздушная часть: разведчик {i} доносит из несуществующей зоны")); + } + } let intel = intel.ok_or("воздушная часть: нет счётчиков секторов")?; let mut kills = [0u32; ew::SECTORS]; let mut hits = [0u32; ew::SECTORS]; @@ -555,6 +828,7 @@ impl Sim { queue, jobs, known_relief: global.and_then(|g| reliefs[g].clone()), + recon, })) } @@ -571,6 +845,10 @@ impl Sim { self.known_relief = save.known_relief; self.drones = save.drones; self.queue = save.queue; + self.recon = save.recon; + let alive: std::collections::HashSet = self.drones.iter().map(|d| d.id).chain(self.queue.iter().map(|(_, d)| d.id)).collect(); + self.recon.retain_drones(&alive); + self.recon.expire(self.tick); self.retargets.clear(); // A job's picture is its version's: the contacts observed no later than it, plus its own // target (whose last saved observation stands in for one made after the version). diff --git a/airdef-mod/src/sim/ew.rs b/airdef-mod/src/sim/ew.rs index 3d37fa9..14fb366 100644 --- a/airdef-mod/src/sim/ew.rs +++ b/airdef-mod/src/sim/ew.rs @@ -19,6 +19,12 @@ //! contact is a plain function of the contact's age, and its idea of a unit's //! capabilities is the type's published one — a contact says nothing about //! damage, roles, link health or magazine. +//! +//! A smart raid may also send a few recon aircraft ahead (#135). What they see is a +//! different, coarser kind of knowledge: an area, a public category, the channel that +//! showed it and its age, radioed home only after a delay and only while the aircraft +//! lives. It is kept as a `recon::Mark`, separate from a disclosure `Contact`; its +//! confidence is age alone and a duplicate report does not improve it. use super::*; use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; @@ -323,6 +329,15 @@ pub(super) const CONTACT_TTL: u64 = 6000; const CONFIRMED_AGE: u64 = 600; const PROBABLE_AGE: u64 = 3000; +/// The one source of confidence: a contact's age, in the bands the picture trusts. +pub(super) fn confidence_for_age(age: u64) -> Confidence { + match age { + 0..=CONFIRMED_AGE => Confidence::Confirmed, + ..=PROBABLE_AGE => Confidence::Probable, + _ => Confidence::Doubtful, + } +} + impl Contact { pub fn age(&self, now: u64) -> u64 { now.saturating_sub(self.tick) @@ -332,11 +347,7 @@ impl Contact { self.destroyed.is_none() && self.age(now) < CONTACT_TTL } pub fn confidence(&self, now: u64) -> Confidence { - match self.age(now) { - 0..=CONFIRMED_AGE => Confidence::Confirmed, - ..=PROBABLE_AGE => Confidence::Probable, - _ => Confidence::Doubtful, - } + confidence_for_age(self.age(now)) } /// Whether the enemy believes this unit sees on its own radar (#127). A kind without a /// sensor never does. A kind with one does while an emission fix of this contact is @@ -556,6 +567,9 @@ impl Sim { /// Whether the picture holds a live contact for this unit: what the old revelation log /// answered at a scan, now one map lookup. pub(super) fn known_live(&self, id: u32) -> bool { + if recon::is_mark(id) { + return self.recon.live(id, self.tick); + } self.intel.contacts.get(&id).is_some_and(|c| c.live(self.tick)) } @@ -578,8 +592,10 @@ impl Sim { /// the picture killed is a distinct, lower-priority decision. fn adapt_targets(&mut self) { self.intel.expire(self.tick); + self.recon.expire(self.tick); let picture = Arc::new(self.picture_of_defences()); - if picture.is_empty() { + let leads = self.recon.leads(self.tick); + if picture.is_empty() && leads.is_empty() { return; } // Every job of this adaptive tick plans over the same relief version, even if another smart @@ -601,9 +617,17 @@ impl Sim { if !eligible { continue; } + // A recon mark is an area, not a unit: it is kept while the mark lives. A + // hidden move does not move the aim; only a newer report can re-place it (#135). + if recon::is_mark(d.aim.unit) { + if self.recon.live(d.aim.unit, now) { + continue; + } + // The mark aged out: the drone falls through to a fresh lead below. + } // What it is aiming at in the picture now, if anything (a unit merely moved is still // aimed where it was seen: a contact is matched by its observed place). - if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) { + else if let Some(current) = Self::aimed_contact(&picture, d.target - d.err) { // Already aiming at a unit: a fresh disclosure may be worth a switch, under the throttle. let Some(c) = Self::switch_candidate(&picture, current, d, now) else { continue }; if per_contact.get(&c.id).copied().unwrap_or(0) >= ASSIGN_PER_CONTACT { @@ -627,13 +651,30 @@ impl Sim { if assigned >= ASSIGN_PER_TICK { continue; } - let Some(c) = Self::fresh_target(&picture, &per_contact, d.kind, n) else { continue }; - *per_contact.entry(c.id).or_insert(0) += 1; + let exact = Self::fresh_target(&picture, &per_contact, d.kind, n); + // No disclosure contact to take: a recon mark whose observed role fits this drone, + // best role and freshest first, bounded per mark as any assignment is. Where both + // exist, the better observed role and fresher mark wins; a hidden unit is in neither. + let mark = Self::fresh_recon_target(&leads, &per_contact); + let (at, unit, confidence) = match (exact, mark) { + (Some(c), Some(m)) => { + let exact_rank = Self::exact_rank(&c, now); + if m.priority(now) > exact_rank { + (m.area, m.id, m.confidence(now)) + } else { + (c.at, c.id, c.confidence(now)) + } + } + (Some(c), None) => (c.at, c.id, c.confidence(now)), + (None, Some(m)) => (m.area, m.id, m.confidence(now)), + (None, None) => continue, + }; + *per_contact.entry(unit).or_insert(0) += 1; assigned += 1; - d.target = c.at + d.err; + d.target = at + d.err; d.intent = Intent::React; // A first assignment is not a switch: the aim's clock starts here, the count is kept. - d.aim = Aim { unit: c.id, since: now, switches: d.aim.switches, confidence: Some(c.confidence(now)) }; + d.aim = Aim { unit, since: now, switches: d.aim.switches, confidence: Some(confidence) }; if Self::route_plannable(d) { jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&picture), relief.clone())); job_next += 1; @@ -648,11 +689,14 @@ impl Sim { // moved is still aimed where seen. for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart) { let aim = d.target - d.err; - let aim_gone = self - .intel - .contacts - .values() - .any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick)); + let aim_gone = if recon::is_mark(d.aim.unit) { + !self.recon.live(d.aim.unit, self.tick) + } else { + self.intel + .contacts + .values() + .any(|c| c.at.distance(aim) < 6.0 && !c.live(self.tick)) + }; if !aim_gone { continue; } @@ -663,17 +707,37 @@ impl Sim { if d.aim.switches >= SWITCH_CAP || assigned >= ASSIGN_PER_TICK { continue; } - let next = picture + let exact = picture .iter() .filter(|c| !plannable || Self::can_turn_to(d, c.at)) .filter(|c| per_contact.get(&c.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT) - .min_by(|a, b| a.at.distance(d.pos).total_cmp(&b.at.distance(d.pos))); - if let Some(c) = next { - *per_contact.entry(c.id).or_insert(0) += 1; + .map(|c| (c.at.distance(d.pos), c.id, c.at, c.confidence(now))) + .min_by(|a, b| a.0.total_cmp(&b.0)); + let mark = leads + .iter() + .filter(|m| !plannable || Self::can_turn_to(d, m.area)) + .filter(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT) + .map(|m| (m.area.distance(d.pos), m.id, m.area, m.confidence(now), m.priority(now))) + .min_by(|a, b| b.4.cmp(&a.4).then(a.0.total_cmp(&b.0))); + // A confirmed recon mark outranks a doubtful disclosure; an exact contact of equal + // freshness is preferred, because it is a fix rather than an area. + let exact_rank = exact.map(|(_, _, _, c)| match c { + Confidence::Confirmed => 30, + Confidence::Probable => 15, + Confidence::Doubtful => 0, + }); + let next = match (exact, mark) { + (Some(_), Some(m)) if m.4 > exact_rank.unwrap_or(0) + 3 => Some((m.0, m.1, m.2, m.3)), + (Some(e), _) => Some(e), + (None, Some(m)) => Some((m.0, m.1, m.2, m.3)), + (None, None) => None, + }; + if let Some((_, unit, at, confidence)) = next { + *per_contact.entry(unit).or_insert(0) += 1; assigned += 1; - d.target = c.at + d.err; + d.target = at + d.err; d.intent = Intent::Replace; - d.aim = d.aim.replaced(c.id, now, c.confidence(now)); + d.aim = d.aim.replaced(unit, now, confidence); if plannable { jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Replace, Arc::clone(&picture), relief.clone())); job_next += 1; @@ -716,6 +780,28 @@ impl Sim { all.get(n % all.len().max(1)).map(|c| **c) } + /// The rank of an exact disclosure contact: its confidence, what its observed kind is + /// worth, and a small premium for being a fix rather than an area. + fn exact_rank(c: &Contact, now: u64) -> u8 { + let seen = match c.confidence(now) { + Confidence::Confirmed => 30, + Confidence::Probable => 15, + Confidence::Doubtful => 0, + }; + seen + recon::Category::of(c.kind).weight() + 3 + } + + /// The best recon mark a drone not yet sent at a unit may be given: observed role and + /// freshness first (the list is sorted), bounded per mark. A mark's category must be one + /// worth a strike; a support or unknown mark is only navigation interest. + fn fresh_recon_target(leads: &[recon::Mark], per_contact: &HashMap) -> Option { + leads + .iter() + .copied() + .filter(|m| m.category.weight() >= 2) + .find(|m| per_contact.get(&m.id).copied().unwrap_or(0) < ASSIGN_PER_CONTACT) + } + /// Whether a fresh disclosure is worth replacing this drone's aim: a contact observed after the /// aim was chosen, trusted (not `Doubtful`), clearly better placed or better believed, and the /// throttle (hold time, switch cap) allows it (#127). A route change costs the planner a new @@ -1009,7 +1095,7 @@ pub struct ContactReport { #[derive(Clone, Debug, PartialEq)] pub struct AimReport { pub drone: u32, - /// The unit aimed at (0: a marked object). + /// The unit aimed at (0: a marked object; a recon mark has a synthetic id). pub unit: u32, /// "plan", "sead", "react" or "replace". pub intent: &'static str, @@ -1019,6 +1105,43 @@ pub struct AimReport { pub switches: u16, /// The confidence of the contact the aim rests on, when it is a unit. pub confidence: Option, + /// Whether the aim is a recon mark's area rather than a unit contact. + pub recon: bool, + /// A recon mark's priority (observed role, freshness, quality); `None` for a unit contact. + pub priority: Option, +} + +/// A recon mark as the diagnostic reports it (#135): an area, a coarse category, the channel, +/// its age and quality. There is no true place, SamKind, health, magazine, link or real id here. +#[derive(Clone, Debug, PartialEq)] +pub struct ReconReport { + pub id: u32, + pub area: DVec3, + pub radius: f64, + /// "unknown", "radar", "launcher", "gun", "ew" or "support". + pub category: &'static str, + /// A radar's role once a refined look told it. + pub role: Option<&'static str>, + /// "flyby", "emission", "jamming" or "launch". + pub source: &'static str, + pub age: u64, + /// "coarse" or "refined". + pub quality: &'static str, + pub confidence: Confidence, + pub live: bool, + /// What the planner makes of it, in words: observed role and freshness only. + pub priority: u8, +} + +/// One recon sortie as the diagnostic reports it (#135). +#[derive(Clone, Debug, PartialEq)] +pub struct ReconSortieReport { + pub drone: u32, + /// "outbound", "looking", "reporting" or "done". + pub phase: &'static str, + pub zones_left: usize, + /// The tick its pending report is due. + pub report_in: Option, } /// A route job the planner has not finished (#127): what it is for, why it is still waiting, @@ -1052,6 +1175,10 @@ pub struct EnemyPictureReport { pub pending: Vec, /// The planner's work a tick, for the pending queue's budget. pub work_per_tick: usize, + /// The partial picture recon flights radioed home (#135). + pub recon: Vec, + /// The recon flights still out. + pub recon_sorties: Vec, } impl Sim { @@ -1099,13 +1226,18 @@ impl Sim { .map(|(_, d)| d) .chain(self.drones.iter()) .filter(|d| d.alive() && d.smart) - .map(|d| AimReport { - drone: d.id, - unit: d.aim.unit, - intent: d.intent.name(), - since: d.aim.since, - switches: d.aim.switches, - confidence: d.aim.confidence, + .map(|d| { + let mark = self.recon.marks.get(&d.aim.unit).filter(|m| m.live(now)).copied(); + AimReport { + drone: d.id, + unit: d.aim.unit, + intent: d.intent.name(), + since: d.aim.since, + switches: d.aim.switches, + confidence: d.aim.confidence, + recon: mark.is_some(), + priority: mark.map(|m| m.priority(now)), + } }) .collect(); let pending = self @@ -1129,7 +1261,42 @@ impl Sim { }, }) .collect(); - EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK } + let recon = self + .recon + .marks + .values() + .map(|m| ReconReport { + id: m.id, + area: m.area, + radius: m.radius, + category: m.category.name(), + role: m.role.map(|r| r.key()), + source: m.source.name(), + age: m.age(now), + quality: m.quality.name(), + confidence: m.confidence(now), + live: m.live(now), + priority: m.priority(now), + }) + .collect(); + let recon_sorties = self + .recon + .sorties + .iter() + .map(|s| ReconSortieReport { + drone: s.drone, + phase: if s.report_at.is_some() { + "reporting" + } else if s.next < s.zones.len() { + "outbound" + } else { + "done" + }, + zones_left: s.zones.len().saturating_sub(s.next), + report_in: s.report_at.map(|t| t.saturating_sub(now)), + }) + .collect(); + EnemyPictureReport { now, contacts, aims, pending, work_per_tick: raid::WORK_PER_TICK, recon, recon_sorties } } /// What the planner makes of a contact, in words for the diagnostic (#127). diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 3fd1355..8685e42 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -26,8 +26,10 @@ mod sight; mod terrain; mod ew; mod optical; +mod recon; mod durable; -pub use ew::{AimReport, Confidence, ContactReport, EnemyPictureReport, Intent, PendingReport}; +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; @@ -175,6 +177,11 @@ impl Rng { pub fn state(&self) -> u64 { self.0 } + /// Puts the generator back exactly where it was (a recon launch must not spend the + /// strike's combat randomness). + pub(super) fn set_state(&mut self, state: u64) { + self.0 = state; + } pub fn next(&mut self) -> u64 { self.0 ^= self.0 << 13; self.0 ^= self.0 >> 7; @@ -1475,6 +1482,8 @@ pub struct Sim { pub tally: record::Tally, /// What the enemy has learned. intel: ew::Intel, + /// Reconnaissance flights and the partial picture they radioed home (#135). + recon: recon::Recon, /// Night: guns need light (the mod sets it from the game's clock). pub night: bool, /// The long fires at crash and impact points (#52). @@ -1551,6 +1560,7 @@ impl Sim { recordings: 0, tally: record::Tally::default(), intel: ew::Intel::default(), + recon: recon::Recon::default(), night: false, fires: fires::Fires::default(), day_time: None, @@ -1663,6 +1673,7 @@ impl Sim { self.plan = None; self.retargets.clear(); self.known_relief = None; + self.recon.clear_sorties(); self.wave = None; // Ammunition still to cook off, flares in the sky. self.later.clear(); @@ -1710,6 +1721,7 @@ impl Sim { self.release_queue(ground, out); self.begin_recording_if_active(); self.step_drones(ground, player, out); + self.step_recon(out); self.step_later(ground, player, out); self.step_moves(ground, out); self.step_supply(out); diff --git a/airdef-mod/src/sim/raid.rs b/airdef-mod/src/sim/raid.rs index 5df1120..cb1a398 100644 --- a/airdef-mod/src/sim/raid.rs +++ b/airdef-mod/src/sim/raid.rs @@ -284,6 +284,9 @@ impl Sim { // read-only while the plan is built, and taking it per drone made a big second order // quadratic in the force's size (#122); a map of contacts makes it linear in them (#127). let picture = self.picture_of_defences(); + // The partial picture the recon flights have radioed home. It is memory, not the + // force: a mark has an area, a category and an age, never a unit's exact place (#135). + let leads = self.recon.leads(self.tick); // A smart enemy comes from where its raids got through best. let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU }; // The raid's sides (1, 2, or 4-5): its launch sites go there (#100). @@ -312,7 +315,7 @@ impl Sim { index += 1; let (target, at_sam) = match job { Some((at, id)) => (at, Some(id)), - None => self.choose_target(kind, object, order.aim, &picture), + None => self.choose_target(kind, object, order.aim, &picture, &leads), }; let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0); let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0; @@ -323,7 +326,11 @@ impl Sim { // The plan's own decision, recorded as such (#127): a radar job is SEAD, a unit // chosen for the raid is the plan's objective, anything else is a marked object. if let Some(id) = at_sam { - let confidence = picture.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick)); + let confidence = picture + .iter() + .find(|c| c.id == id) + .map(|c| c.confidence(self.tick)) + .or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick))); d.intent = if job.is_some() { ew::Intent::Sead } else { ew::Intent::Plan }; d.aim = confidence.map_or_else(|| ew::Aim::point(self.tick), |c| ew::Aim::unit(id, self.tick, c)); } else { @@ -363,6 +370,11 @@ impl Sim { waited: 0, mapped: !smart, }); + // The smart enemy may send a small recon flight ahead of the strike -- physically in + // the air, not a pause: the strike is planned while they fly (#135). + if smart { + self.start_recon(objects, bearing, order.dist, out); + } // A raid without routes is ready at once. self.plan_step(None, out); total @@ -580,12 +592,25 @@ impl Sim { /// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid. /// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile. pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact]) -> Vec> { - let mut radars: Vec<(u32, DVec3)> = picture + // Exact disclosure contacts and recon marks of radars, best first. The order is the + // observed role, freshness and quality -- never the id: a hidden station has no id, + // and a big observed radar is worth more than a modest one (#135). + let now = self.tick; + let mut radars: Vec<(u8, u64, u32, DVec3)> = picture .iter() - .filter(|c| c.kind == SamKind::Radar && c.confidence(self.tick) >= ew::Confidence::Probable) - .map(|c| (c.id, c.at)) + .filter(|c| c.kind == SamKind::Radar && c.confidence(now) >= ew::Confidence::Probable) + .map(|c| { + let seen = match c.confidence(now) { + ew::Confidence::Confirmed => 4, + ew::Confidence::Probable => 2, + ew::Confidence::Doubtful => 0, + }; + (seen * 10 + 3, c.tick, c.id, c.at) + }) + .chain(self.recon.leads(now).into_iter().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area))) .collect(); - radars.sort_by_key(|(id, _)| *id); + radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2))); + let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect(); let flat: Vec = kinds.iter().flat_map(|&(k, n)| std::iter::repeat_n(k, n as usize)).collect(); let mut jobs = vec![None; flat.len()]; if radars.is_empty() { @@ -609,8 +634,8 @@ impl Sim { /// point and the unit's id. The planner has only the picture (#93, #127): what it knows of a /// unit is the last observation — the place seen then, the type identified then — never where /// the unit actually is or what it has become since. - fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact]) -> (DVec3, Option) { - if picture.is_empty() || kind.spec().decoy || aim == Aim::Objects { + fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, picture: &[ew::Contact], leads: &[recon::Mark]) -> (DVec3, Option) { + if (picture.is_empty() && leads.is_empty()) || kind.spec().decoy || aim == Aim::Objects { return (object, None); } let pick = |list: &[ew::Contact], r: f64| -> Option<(DVec3, u32)> { @@ -641,7 +666,15 @@ impl Sim { DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(picture, r), _ => None, }; - choice.map_or((object, None), |(p, id)| (p, Some(id))) + if let Some((p, id)) = choice { + return (p, Some(id)); + } + // Nothing disclosed and nothing the kind's usual preference picked: a recon mark + // whose observed role fits is the next best reason to turn a strike off the object. + if let Some(m) = recon_pick(kind, leads, r) { + return (m.area, Some(m.id)); + } + (object, None) } /// The price of each cell of `grid` for this kind flying low: 1, and much more where a @@ -935,6 +968,11 @@ const AIR_START_WAIT: u32 = 120; if !why.is_empty() { out.messages.push(format!("Неудачи ПВО: {why}")); } + // What the enemy's recon flights saw: the marks are memory, so the picture may be old (#135). + let marks = self.recon.marks.values().filter(|m| m.live(self.tick)).count(); + if marks > 0 { + out.messages.push(format!("Разведка противника: в картине {marks} отметок (возраст и качество — в разборе)")); + } // What the counter-strikes did to the raid (#101): the launches that never happened. let cut: u32 = self.strikes.cancelled.iter().map(|c| c.1).sum(); if cut > 0 { @@ -956,6 +994,21 @@ fn route_length(from: DVec3, route: &[DVec3], to: DVec3) -> f64 { len } +/// A recon mark whose observed category fits this kind. The list is already in priority +/// order, so the first fit is the best reason. +fn recon_pick(kind: DroneKind, leads: &[recon::Mark], r: f64) -> Option { + use recon::Category as C; + let fits = |c: C| match kind { + DroneKind::Lancet => matches!(c, C::Gun | C::Launcher | C::Ew), + DroneKind::Kh22 | DroneKind::Zircon => matches!(c, C::Radar | C::Launcher | C::Ew), + DroneKind::Iskander | DroneKind::Kinzhal => matches!(c, C::Radar | C::Launcher), + DroneKind::Shahed | DroneKind::Geran3 => matches!(c, C::Radar | C::Launcher | C::Gun | C::Ew), + _ => false, + }; + let fits: Vec<&recon::Mark> = leads.iter().filter(|m| fits(m.category)).collect(); + fits.get((r * fits.len() as f64) as usize).copied().copied() +} + #[cfg(test)] mod tests { use super::*; diff --git a/airdef-mod/src/sim/recon.rs b/airdef-mod/src/sim/recon.rs new file mode 100644 index 0000000..ccea64e --- /dev/null +++ b/airdef-mod/src/sim/recon.rs @@ -0,0 +1,1136 @@ +//! Reconnaissance sorties and the enemy's partial picture of the defences (#135). +//! +//! A smart raid may send a few unarmed aircraft ahead of its strike. They fly through +//! game zones round the marked objectives and look while they are there: a unit inside +//! a zone is seen as an *area*, a coarse category, the channel that showed it and the +//! tick it was seen. Nothing of the unit's live state — its exact place, kind, health, +//! magazine, radar role or data link — enters the picture. A look is radioed home only +//! after `REPORT_DELAY` ticks and only if the aircraft is still flying: a sortie lost +//! before its report leaves no mark, while marks already reported stay. +//! +//! What is reported is memory, not truth. A hidden move, a switch-off, a re-role or a +//! kill does not rewrite a mark; only a later look can. A repeated report of the same +//! observation does not raise its confidence: confidence is the mark's age alone, and a +//! second independent look may refine the area and (for a radar) its role. +use super::*; +use std::collections::BTreeMap; + +/// A zone a recon aircraft flies through. Its radius is the best it can say about where +/// a unit it saw there is. +pub const ZONE_RADIUS: f64 = 220.0; +/// How many zones one sortie may look through, and how many sorties may be out at once. +pub const ZONES_MAX: usize = 4; +pub const SORTIES_MAX: usize = 3; +/// Ticks from a look to its report: the aircraft must still be flying then. +pub const REPORT_DELAY: u64 = 90; +/// Ticks a sortie may stay out; past this its unreported look is lost. +pub const SORTIE_TTL: u64 = 5000; +/// A second independent look this much later may refine the mark. A duplicate report of +/// the same observation never does. +pub const REFINE_GAP: u64 = 600; +/// The area a first report leaves, and the smaller one a refined report leaves. Neither +/// is the unit's place: the reported point is a cell centre, jittered away from it. +pub const COARSE_AREA: f64 = 120.0; +pub const REFINED_AREA: f64 = 48.0; +/// How long a mark is remembered (five minutes, as a disclosure contact). +pub const MARK_TTL: u64 = 6000; +/// How long a checked empty zone is not worth another look (unless there is nothing else). +pub const REVISIT: u64 = 6000; +/// Synthetic contact ids: the planner never sees a real unit id through a recon mark. The range +/// is its own: it must not overlap the drawn-only effects (`FX_IDS`, 0x2000_0000), the engine +/// keys (0x4000_0000) or the recon aircraft below. +pub const ID_BASE: u32 = 0x1000_0000; +/// One past the last mark id a report may take (space for far more reports than a match holds). +pub const MARK_TOP: u32 = 0x1800_0000; +/// Recon aircraft ids come from their own range: launching the flight must not move the +/// strike's id sequence, and so its tie-breaks and recorded tracks. +pub const DRONE_BASE: u32 = 0x3000_0000; +/// One past the last recon aircraft id a save may hold: the drone parser's own bound (`1 << 30`). +pub const DRONE_TOP: u32 = 0x4000_0000; +/// Contacts and checked zones one save may hold (the section stays bounded). +pub const MAX_MARKS: usize = 512; +pub const MAX_CHECKED: usize = 128; +/// Observations one report may carry, and pending observations a sortie may hold. +pub const MAX_OBSERVED: usize = 64; + +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). 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 +} + +/// What a look can tell about a unit's role, in the terms the game already publishes. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Category { + /// A unit was there, nothing more. + Unknown, + Radar, + Launcher, + Gun, + Ew, + Support, +} + +impl Category { + pub fn name(self) -> &'static str { + match self { + Self::Unknown => "unknown", + Self::Radar => "radar", + Self::Launcher => "launcher", + Self::Gun => "gun", + Self::Ew => "ew", + Self::Support => "support", + } + } + 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. + pub(super) fn of(kind: SamKind) -> Self { + match kind { + SamKind::Radar => Self::Radar, + SamKind::Ew => Self::Ew, + SamKind::Depot | SamKind::Tzm | SamKind::Light => Self::Support, + _ if kind.armed() => { + if kind.has_gun() && kind.missile_magazine().is_none() { Self::Gun } else { Self::Launcher } + } + _ => Self::Unknown, + } + } + /// What a confirmed contact of this category is worth to the planner, before freshness. + pub fn weight(self) -> u8 { + match self { + Self::Radar | Self::Launcher => 3, + Self::Ew | Self::Gun => 2, + Self::Support => 1, + Self::Unknown => 0, + } + } +} + +/// A radar role is public only after a refined look; a coarse report leaves it unknown. +pub fn role_weight(role: battery::RadarRole) -> u8 { + match role { + battery::RadarRole::Multifunction | battery::RadarRole::Engagement => 3, + battery::RadarRole::Search => 2, + battery::RadarRole::Height => 1, + } +} + +/// 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, + Refined, +} + +impl Quality { + pub fn name(self) -> &'static str { + match self { + Self::Coarse => "coarse", + Self::Refined => "refined", + } + } + pub fn from_key(key: &str) -> Option { + [Self::Coarse, Self::Refined].into_iter().find(|q| q.name() == key) + } +} + +/// The channel a recon mark came from. A flyby sees the unit itself; an emitting radar or a +/// jamming station is recognizable while it transmits; a silent one is just a unit. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Source { + Flyby, + Emission, + Jamming, + Launch, +} + +impl Source { + pub fn name(self) -> &'static str { + match self { + Self::Flyby => "flyby", + Self::Emission => "emission", + Self::Jamming => "jamming", + Self::Launch => "launch", + } + } + pub(super) fn from_key(key: &str) -> Option { + [Self::Flyby, Self::Emission, Self::Jamming, Self::Launch].into_iter().find(|s| s.name() == key) + } +} + +/// A mark in the enemy's picture: an area, a coarse category, where it came from, when it +/// was seen and how well. There is deliberately no unit id, SamKind, exact point, health, +/// magazine or link here. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Mark { + /// Synthetic id: stable for the mark, never the unit's. + pub(super) id: u32, + pub(super) area: DVec3, + pub(super) radius: f64, + pub(super) category: Category, + /// A radar's role, once a refined look told it; never for a coarse mark. + pub(super) role: Option, + pub(super) source: Source, + /// The tick of the look this mark rests on. + pub(super) observed: u64, + /// The tick its report arrived (for the record; confidence is age alone). + pub(super) reported: u64, + pub(super) quality: Quality, + pub(super) looks: u16, +} + +impl Mark { + pub fn age(&self, now: u64) -> u64 { + now.saturating_sub(self.observed) + } + pub fn live(&self, now: u64) -> bool { + self.age(now) < MARK_TTL + } + pub fn confidence(&self, now: u64) -> Confidence { + ew::confidence_for_age(self.age(now)) + } + /// How much the planner wants this mark: its observed public role, its freshness and + /// how well it is known. The unit's id and its true importance are not in it. + pub fn priority(&self, now: u64) -> u8 { + let seen = match self.confidence(now) { + Confidence::Confirmed => 4, + Confidence::Probable => 2, + Confidence::Doubtful => 0, + }; + let quality = match self.quality { + Quality::Refined => 2, + Quality::Coarse => 0, + }; + let role = self.role.map_or_else(|| self.category.weight(), role_weight); + seen * 4 + quality * 3 + role + } +} + +/// A look waiting for its report: the aircraft saw it, but has not radioed it yet. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Look { + pub(super) truth: u32, + pub(super) area: DVec3, + pub(super) radius: f64, + pub(super) category: Category, + pub(super) role: Option, + pub(super) quality: Quality, + pub(super) source: Source, + pub(super) observed: u64, +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Zone { + pub(super) center: DVec3, + pub(super) radius: f64, +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Sortie { + pub(super) drone: u32, + pub(super) zones: Vec, + /// The next zone to look through. + pub(super) next: usize, + pub(super) launched: u64, + /// The report waiting to be sent: when, from which zone, and what it saw. + pub(super) report_at: Option, + pub(super) report_zone: Option, + pub(super) pending: Vec, +} + +/// What the enemy remembers from its recon flights, across raids. +#[derive(Default)] +pub(super) struct Recon { + pub(super) sorties: Vec, + pub(super) marks: BTreeMap, + /// The unit a mark is of. Internal to the observer: the planner only ever sees `Mark`. + pub(super) truth: BTreeMap, + /// Zones already reported as looked through, by their rounded centre. + pub(super) checked: BTreeMap<(i64, i64), u64>, + pub(super) next: u32, + pub(super) drone_next: u32, + pub(super) reports: u32, + pub(super) lost: u32, +} + +impl Recon { + pub(super) fn clear_sorties(&mut self) { + self.sorties.clear(); + } + + /// A cheap shape of the recon memory for the autosave's dirty check: a new mark, a checked + /// zone, a sortie's progress — and, because a report can refine an existing mark without + /// changing any count, the marks' own observed content (#135). + pub(super) fn mark(&self) -> u64 { + let mut h: u64 = 0xCBF2_9CE4_8422_2325; + let mut mix = |v: u64| h = (h ^ v).wrapping_mul(0x0000_0100_0000_01B3); + mix(self.sorties.len() as u64); + mix(self.marks.len() as u64); + mix(self.checked.len() as u64); + mix(u64::from(self.next)); + mix(u64::from(self.drone_next)); + for (id, m) in &self.marks { + mix(u64::from(*id)); + mix(m.observed); + mix(m.reported); + mix(u64::from(m.looks)); + mix(m.quality as u64); + mix(m.category as u64); + mix(m.source as u64); + mix(m.role.map_or(0xff, |r| r as u64)); + mix(m.area.x.to_bits()); + mix(m.area.z.to_bits()); + mix(m.radius.to_bits()); + } + for ((i, j), t) in &self.checked { + mix(*i as u64); + mix(*j as u64); + mix(*t); + } + for s in &self.sorties { + mix(u64::from(s.drone)); + mix(s.next as u64); + mix(s.pending.len() as u64); + mix(s.report_at.unwrap_or(u64::MAX)); + mix(s.report_zone.map_or(u64::MAX, |z| z as u64)); + } + h + } + + pub(super) fn is_empty(&self) -> bool { + self.sorties.is_empty() && self.marks.is_empty() && self.checked.is_empty() + } + + /// The marks the planner may see, newest and best first. The order uses the observed + /// public role, freshness and quality; the synthetic id is only a deterministic last tie. + pub(super) fn leads(&self, now: u64) -> Vec { + let mut out: Vec = self.marks.values().copied().filter(|m| m.live(now)).collect(); + out.sort_by(|a, b| { + b.priority(now) + .cmp(&a.priority(now)) + .then(b.observed.cmp(&a.observed)) + .then(a.id.cmp(&b.id)) + }); + out + } + + pub(super) fn live(&self, id: u32, now: u64) -> bool { + self.marks.get(&id).is_some_and(|m| m.live(now)) + } + + /// Remembers a zone that was reported as looked through, bounded. The oldest goes first. + pub(super) fn remember_zone(&mut self, center: DVec3, now: u64) { + self.checked.insert(zone_key(center), now); + while self.checked.len() > MAX_CHECKED { + let Some(oldest) = self.checked.iter().min_by_key(|(_, t)| **t).map(|(k, _)| *k) else { break }; + self.checked.remove(&oldest); + } + } + + pub(super) fn recently_checked(&self, center: DVec3, now: u64) -> bool { + self.checked.get(&zone_key(center)).is_some_and(|t| now.saturating_sub(*t) < REVISIT) + } + + pub(super) fn mark_for_truth(&self, truth: u32) -> Option { + self.truth.iter().find_map(|(id, t)| (*t == truth).then(|| self.marks.get(id).copied()).flatten()) + } + + /// A report that has arrived. The same observation twice changes nothing; a genuinely + /// later look updates the mark and may refine it. The mark keeps its synthetic id. + pub(super) fn report(&mut self, look: Look, now: u64) { + let existing = self.truth.iter().find_map(|(id, t)| (*t == look.truth).then_some(*id)); + match existing { + Some(id) => { + let Some(old) = self.marks.get(&id).copied() else { return }; + if look.observed <= old.observed { + return; + } + let refine = look.observed.saturating_sub(old.observed) >= REFINE_GAP; + let m = self.marks.get_mut(&id).unwrap(); + m.area = look.area; + m.radius = if refine { REFINED_AREA } else { m.radius }; + m.category = look.category; + m.source = look.source; + m.observed = look.observed; + m.reported = now; + m.looks = m.looks.saturating_add(1); + if refine { + m.quality = Quality::Refined; + m.role = look.role; + } + } + None => { + if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 { + return; + } + self.next += 1; + let id = ID_BASE + self.next; + self.truth.insert(id, look.truth); + self.marks.insert(id, Mark { + id, + area: look.area, + radius: look.radius, + category: look.category, + role: if look.quality == Quality::Refined { look.role } else { None }, + source: look.source, + observed: look.observed, + reported: now, + quality: look.quality, + looks: 1, + }); + } + } + } + + /// Marks older than a disclosure contact's life are forgotten. + pub(super) fn expire(&mut self, now: u64) { + self.marks.retain(|_, m| m.live(now)); + let ids: std::collections::HashSet = self.marks.keys().copied().collect(); + self.truth.retain(|id, _| ids.contains(id)); + } + + /// Drops sorties whose aircraft is gone and keeps the rest; a save may omit a drone it + /// could not write. + pub(super) fn retain_drones(&mut self, alive: &std::collections::HashSet) { + self.sorties.retain(|s| alive.contains(&s.drone)); + } +} + +/// The rounded place a zone is remembered by (the report, not the truth). +pub(super) fn zone_key(center: DVec3) -> (i64, i64) { + (center.x.round() as i64, center.z.round() as i64) +} + +/// The point a report gives for a unit seen at `at`: the centre of an area cell, moved +/// deterministically off the true point so the mark is an area, not a fix. +pub(super) fn area_of(at: DVec3, cell: f64, salt: u32) -> DVec3 { + let j = |k: u32| { + let h = salt.wrapping_mul(2_654_435_761).rotate_left(7) ^ k.wrapping_mul(2_246_822_519); + (f64::from(h % 1000) / 1000.0 - 0.5) * cell * 0.6 + }; + DVec3::new((at.x / cell).round() * cell + j(1), at.y, (at.z / cell).round() * cell + j(2)) +} + +/// One look through a zone: the units inside it, as the channels can tell them. The true +/// place and kind are read here, at the observation, and leave only as an area/category. +pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone, now: u64) -> Vec { + let mut out = Vec::new(); + for s in sams { + if horizontal(s.pos - zone.center).length() > zone.radius { + continue; + } + if out.len() >= MAX_OBSERVED { + break; + } + let old = state.mark_for_truth(s.id); + let refine = old.is_some_and(|m| now.saturating_sub(m.observed) >= REFINE_GAP); + let quality = if refine { Quality::Refined } else { Quality::Coarse }; + let cell = if refine { REFINED_AREA } else { COARSE_AREA }; + let category = Category::of(s.kind); + // A launch is a public event already watched by the disclosure channel; a look that + // passes just after one can name that source too. Health, magazine and link never are. + let launched = intel.contacts().get(&s.id).is_some_and(|c| c.seen == ew::Seen::Launch && now.saturating_sub(c.tick) < 200); + let source = match s.kind { + SamKind::Ew if s.ew_on => Source::Jamming, + SamKind::Radar if s.radar_on => Source::Emission, + _ if launched => Source::Launch, + _ => Source::Flyby, + }; + // The role is a public radar configuration only when a close second look can tell it. + let role = (refine && s.kind == SamKind::Radar).then_some(s.radar_role); + // The jitter is the zone's, not the unit's: the mark must not carry the unit id even + // indirectly. + let salt = (zone.center.x.round() as i64 as u32) ^ (zone.center.z.round() as i64 as u32).rotate_left(16); + out.push(Look { + truth: s.id, + area: area_of(s.pos, cell, salt), + radius: cell, + category, + role, + quality, + source, + observed: now, + }); + } + out +} + +/// The zones a smart raid sends its aircraft through: round the marked objectives, then +/// (when every one of those has been checked lately) round a mark the picture still doubts. +pub(super) fn plan_zones(objects: &[DVec3], state: &Recon, now: u64) -> Vec { + let mut out = Vec::new(); + for (i, p) in objects.iter().take(2).enumerate() { + // The marked objective itself, then one ring round it: the defence around the target + // is what the enemy came to look at, and a ring alone would miss a unit on the mark. + let a = i as f64 * 2.399_963_229_728_653; + let ring = *p + DVec3::new(a.sin() * 260.0, 0.0, a.cos() * 260.0); + for center in [*p, ring] { + if !state.recently_checked(center, now) { + out.push(Zone { center, radius: ZONE_RADIUS }); + } + } + } + if out.is_empty() { + // Nothing unchecked round the objectives: re-look at a mark the picture still doubts. + if let Some(m) = state.leads(now).into_iter().find(|m| m.confidence(now) == Confidence::Doubtful) { + out.push(Zone { center: m.area, radius: ZONE_RADIUS }); + } + } + out.truncate(ZONES_MAX); + out +} + +impl Sim { + /// Whether an aircraft is the enemy's recon flight (#135): the sandbox's truth gives it a + /// sign of its own; the normal picture classes it as any other drone. + pub fn is_recon_drone(&self, id: u32) -> 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 + /// defences are. + pub(super) fn start_recon(&mut self, objects: &[DVec3], bearing: f64, dist: f64, out: &mut Out) { + let zones = plan_zones(objects, &self.recon, self.tick); + // The allowance is the raid's whole recon budget, not one order's: a second wave does not + // launch more aircraft while the first flight is still out. + let room = SORTIES_MAX.saturating_sub(self.recon.sorties.len()); + if zones.is_empty() || room == 0 { + return; + } + let Some(&last) = objects.last() else { return }; + // Ids beyond the drone parser's bound would make the next save unreadable. + if self.recon.drone_next >= DRONE_TOP - DRONE_BASE - 1 { + return; + } + let want = room.min(2).min(zones.len()); + let centre = objects[0]; + let from = centre + DVec3::new(bearing.sin() * dist, 120.0, bearing.cos() * dist); + // The recon flight must not spend the strike's combat randomness: its own aim error + // may differ, but a new role must not re-roll the raid that follows it. + let combat_rng = self.rng.state(); + for n in 0..want { + // Each aircraft takes every `want`-th zone from `n` on: the first the first zones, + // the second the ones after them, so a loss does not take every look with it. + let mine: Vec = zones.iter().skip(n).step_by(want).cloned().collect(); + if mine.is_empty() { + continue; + } + let dir = (mine[0].center - from).normalize_or(DVec3::NEG_Z); + // The launch helper takes an id from the strike's counter; the recon aircraft + // gives it back and takes one from its own range, so the strike's ids and + // tie-breaks are exactly what they would have been without the flight. + let main_next = self.next; + self.launch(DroneKind::Gerbera, from, dir, last, out); + self.next = main_next; + let Some(d) = self.drones.last_mut() else { continue }; + self.recon.drone_next += 1; + d.id = DRONE_BASE + self.recon.drone_next; + d.low = true; + d.sector = ew::sector(bearing) as u8; + let at = d.id; + d.route = mine.iter().map(|z| z.center + DVec3::Y * 40.0).chain(std::iter::once(last)).collect(); + d.target = last; + self.recon.sorties.push(Sortie { + drone: at, + zones: mine, + next: 0, + launched: self.tick, + report_at: None, + report_zone: None, + pending: Vec::new(), + }); + } + self.rng.set_state(combat_rng); + if !self.recon.sorties.is_empty() { + out.messages.push("Разведка противника: впереди налёта высланы разведчики".into()); + } + } + + /// One tick of the recon flight: a look is radioed after its delay if the aircraft is + /// still flying; a lost aircraft leaves its unreported look behind. + pub(super) fn step_recon(&mut self, out: &mut Out) { + let now = self.tick; + if self.recon.sorties.is_empty() { + return; + } + let mut sorties = std::mem::take(&mut self.recon.sorties); + let mut kept = Vec::with_capacity(sorties.len()); + let mut lost = 0u32; + for mut s in sorties.drain(..) { + let alive = self.drones.iter().any(|d| d.id == s.drone && d.alive()); + if !alive { + // An aircraft that finished its look and flew on to the aim is not a loss: only a + // sortie with a zone left or a report still unsent ended before its work was done. + let unfinished = s.report_at.is_some() || s.next < s.zones.len(); + if unfinished { + lost += 1; + out.messages.push(if s.report_at.take().is_some() { + "Разведка противника: разведчик сбит до донесения".into() + } else { + "Разведка противника: разведчик сбит".into() + }); + } + continue; + } + if now.saturating_sub(s.launched) > SORTIE_TTL { + if s.report_at.is_some() || s.next < s.zones.len() { + lost += 1; + } + s.pending.clear(); + s.report_at = None; + out.messages.push("Разведка противника: разведчик вернулся ни с чем".into()); + continue; + } + if let Some(at) = s.report_at { + if now >= at { + if let Some(z) = s.report_zone.take() { + self.recon.remember_zone(s.zones[z].center, now); + } + let n = s.pending.len(); + for look in std::mem::take(&mut s.pending) { + self.recon.report(look, now); + } + self.recon.reports = self.recon.reports.saturating_add(1); + s.report_at = None; + out.messages.push(if n == 0 { + "Разведка противника: зона проверена, целей не обнаружено".into() + } else { + format!("Разведка противника: донесение, отметок {n}") + }); + } else { + kept.push(s); + continue; + } + } + if s.next < s.zones.len() { + let at = self.drones.iter().find(|d| d.id == s.drone).map(|d| d.pos); + let inside = at.is_some_and(|p| horizontal(p - s.zones[s.next].center).length() <= s.zones[s.next].radius); + if inside { + let z = s.zones[s.next].clone(); + s.pending = look(&self.sams, &self.recon, &self.intel, &z, now); + s.report_at = Some(now + REPORT_DELAY); + s.report_zone = Some(s.next); + s.next += 1; + kept.push(s); + continue; + } + kept.push(s); + continue; + } + // Every zone looked through and its report sent: the aircraft flies on to its aim. + } + self.recon.sorties = kept; + self.recon.expire(now); + if lost > 0 { + self.recon.lost = self.recon.lost.saturating_add(lost); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::sites::testland::{Land, serve}; + + fn sam(sim: &mut Sim, kind: SamKind, at: DVec3) -> u32 { + let id = sim.id(); + sim.sams.push(Sam::new(id, kind, at, 0.0)); + id + } + + fn order() -> RaidOrder { + RaidOrder { kinds: vec![(DroneKind::Shahed, 4)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart } + } + + /// Moves the first recon aircraft into its next zone and returns the tick of the look. + fn look_once(sim: &mut Sim) -> (u32, u64) { + let s = sim.recon.sorties.first().expect("no recon sortie").clone(); + let d = sim.drones.iter_mut().find(|d| d.id == s.drone).expect("the sortie has no aircraft"); + d.pos = s.zones[s.next].center + DVec3::Y * 40.0; + sim.tick += 1; + sim.step_recon(&mut Out::default()); + (s.drone, sim.tick) + } + + // #135: before anything is observed the recon flight and the strike's decisions are a + // function of the seed, the objectives and the published plan alone. Two hidden layouts + // -- different kinds and places, neither observed -- order the same flight and aims. + #[test] + fn the_same_seed_orders_the_same_flight_whatever_is_hidden() { + let object = DVec3::new(0.0, 70.0, 0.0); + let build = |hidden: bool| { + let mut sim = Sim::new(135); + if hidden { + sam(&mut sim, SamKind::S400, DVec3::new(-180.0, 70.0, 40.0)); + sam(&mut sim, SamKind::Radar, DVec3::new(210.0, 70.0, -60.0)); + sam(&mut sim, SamKind::Gepard, DVec3::new(20.0, 70.0, 240.0)); + } else { + sam(&mut sim, SamKind::Pantsir, DVec3::new(300.0, 70.0, 300.0)); + } + sim.targets.push(object); + sim.target_health.push(100.0); + let mut out = Out::default(); + sim.order_raid(&order(), &[object], &mut out); + let flight: Vec<_> = sim + .recon + .sorties + .iter() + .map(|s| s.zones.iter().map(|z| (z.center, z.radius)).collect::>()) + .collect(); + let aircraft: Vec<_> = sim + .drones + .iter() + .filter(|d| sim.recon.sorties.iter().any(|s| s.drone == d.id)) + .map(|d| (d.pos, d.target, d.route.clone())) + .collect(); + let aims: Vec<_> = sim.planned_aims().into_iter().map(|(_, i)| i).collect(); + let intents: Vec<_> = sim.planned_intents().into_iter().map(|(_, i)| i).collect(); + (flight, aircraft, aims, intents) + }; + let a = build(false); + let b = build(true); + assert_eq!(a, b, "a hidden layout changed the recon flight or the plan before any observation"); + } + + // #135: an empty zone proves nothing. The look reports no mark, and only the fact that + // this zone was looked through is remembered. + #[test] + fn an_empty_zone_reports_no_mark() { + let mut sim = Sim::new(1); + let object = DVec3::new(0.0, 70.0, 0.0); + sim.targets.push(object); + sim.target_health.push(100.0); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + assert!(!sim.recon.sorties.is_empty()); + let (_, at) = look_once(&mut sim); + assert!(sim.recon.marks.is_empty(), "an empty zone made a mark"); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + assert!(sim.recon.marks.is_empty(), "an empty zone proved a unit after the report"); + assert!(sim.recon.checked.values().any(|t| *t == sim.tick), "the checked zone was not remembered"); + } + + // #135: a report exists only once the aircraft that made the look is still flying when it + // is due. A sortie lost first leaves no mark; a mark already reported does not disappear + // when the aircraft is lost later. + #[test] + fn a_sortie_lost_before_its_report_sends_nothing() { + let mut sim = Sim::new(2); + let object = DVec3::new(0.0, 70.0, 0.0); + let id = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (drone, at) = look_once(&mut sim); + assert_eq!(sim.recon.marks.len(), 0, "a look reached the picture before its report"); + sim.drones.retain(|d| d.id != drone); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + assert_eq!(sim.recon.marks.len(), 0, "a lost sortie still delivered its look"); + + // The same look reported in time: the mark arrives and stays after the loss. + let mut sim = Sim::new(2); + let object = DVec3::new(0.0, 70.0, 0.0); + let _ = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (drone, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + assert_eq!(sim.recon.marks.len(), 1, "a timely report made no mark"); + let area = sim.recon.marks.values().next().unwrap().area; + sim.drones.retain(|d| d.id != drone); + sim.step_recon(&mut Out::default()); + assert_eq!(sim.recon.marks.values().next().unwrap().area, area, "a lost aircraft rewrote a delivered mark"); + let _ = id; + } + + // #135: confidence is the mark's age, not a count of reports. The same observation + // reported twice changes neither the mark's quality nor its looks. + #[test] + fn a_duplicate_report_does_not_raise_confidence() { + let mut sim = Sim::new(3); + let object = DVec3::new(0.0, 70.0, 0.0); + let _ = sam(&mut sim, SamKind::Radar, object + DVec3::new(30.0, 0.0, 0.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (_, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + let before = *sim.recon.marks.values().next().unwrap(); + // The same look arrives again, even much later: it is still the same observation. + let look = Look { + truth: sim.recon.truth.values().next().copied().unwrap(), + area: before.area, + radius: before.radius, + category: before.category, + role: before.role, + quality: Quality::Refined, + source: before.source, + observed: before.observed, + }; + sim.recon.report(look, before.reported + 10_000); + let after = *sim.recon.marks.values().next().unwrap(); + assert_eq!((after.quality, after.looks, after.observed, after.radius), (before.quality, before.looks, before.observed, before.radius)); + assert!(after.confidence(before.reported + 10_000) <= before.confidence(before.reported)); + } + + // #135: a hidden move or a hidden change does not rewrite the old mark. Only a new look, + // reported later, can re-place it. + #[test] + fn a_hidden_move_does_not_rewrite_the_mark() { + let mut sim = Sim::new(4); + let object = DVec3::new(0.0, 70.0, 0.0); + let id = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (_, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + let before = sim.enemy_picture().recon; + let key = |r: &[super::ew::ReconReport]| -> Vec<_> { r.iter().map(|m| (m.id, m.area, m.radius, m.category, m.role, m.source, m.quality)).collect() }; + // A hidden move, a re-role and damage: none of it is an observation. Age moves on, + // the mark's area, category, role and quality do not. + let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap(); + s.pos = DVec3::new(900.0, 70.0, 900.0); + s.health = 0.0; + s.radar_role = battery::RadarRole::Height; + s.missiles = 0; + sim.tick += 1000; + assert_eq!(key(&sim.enemy_picture().recon), key(&before), "a hidden change rewrote the recon picture"); + } + + + // #135: the channel matters. A silent radar is seen only by the flyby, a transmitting + // radar by its emission, a jamming station by its transmission, and a just-fired system + // by the launch the disclosure channel already watched. A hidden switch or magazine is + // not read: only what the game shows. + #[test] + fn the_source_is_the_channel_that_showed_the_unit() { + let mut sim = Sim::new(8); + let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS }; + let radar = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0)); + let ew = sam(&mut sim, SamKind::Ew, DVec3::new(-10.0, 70.0, 0.0)); + let s400 = sam(&mut sim, SamKind::S400, DVec3::new(0.0, 70.0, 10.0)); + sim.recon.checked.clear(); + let source = |sim: &Sim, id: u32| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).unwrap().source; + + sim.sams.iter_mut().find(|s| s.id == radar).unwrap().radar_on = false; + assert_eq!(source(&sim, radar), Source::Flyby, "a silent radar was read as emitting"); + sim.sams.iter_mut().find(|s| s.id == radar).unwrap().radar_on = true; + assert_eq!(source(&sim, radar), Source::Emission); + assert_eq!(source(&sim, ew), Source::Flyby, "a silent jammer was read as transmitting"); + sim.sams.iter_mut().find(|s| s.id == ew).unwrap().ew_on = true; + assert_eq!(source(&sim, ew), Source::Jamming); + sim.intel.observe(sim.sams.iter().find(|s| s.id == s400).unwrap(), sim.tick, ew::Seen::Launch); + assert_eq!(source(&sim, s400), Source::Launch); + // A hidden empty magazine does not change the source. + sim.sams.iter_mut().find(|s| s.id == s400).unwrap().missiles = 0; + assert_eq!(source(&sim, s400), Source::Launch); + } + + // #135: the planner's order is the observed public role, freshness and quality, not the + // unit id or its true importance. A fresh modest mark outranks an old doubtful big one; + // the synthetic ids are only the last deterministic tie. + #[test] + fn priority_is_observed_role_and_freshness_not_id_or_truth() { + let mut r = Recon::default(); + let mark = |id: u32, at: DVec3, category, role, observed, quality| Mark { + id, + area: at, + radius: REFINED_AREA, + category, + role, + source: Source::Flyby, + observed, + reported: observed, + quality, + looks: 1, + }; + r.marks.insert(ID_BASE + 1, mark(ID_BASE + 1, DVec3::ZERO, Category::Radar, Some(battery::RadarRole::Engagement), 100, Quality::Refined)); + r.marks.insert(ID_BASE + 2, mark(ID_BASE + 2, DVec3::X, Category::Launcher, None, 100, Quality::Refined)); + let now = 200; + let leads = r.leads(now); + assert_eq!((leads[0].id, leads[1].id), (ID_BASE + 1, ID_BASE + 2), "a bigger observed role did not lead"); + // The same observations age: the big one becomes doubtful, the modest one is fresh. + r.marks.insert(ID_BASE + 2, mark(ID_BASE + 2, DVec3::X, Category::Gun, None, 3900, Quality::Coarse)); + let leads = r.leads(4000); + assert_eq!(leads[0].id, ID_BASE + 2, "a stale doubtful mark outranked a fresh modest one"); + 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. + #[test] + fn a_simple_preset_gets_no_recon() { + let mut sim = Sim::new(9); + 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::Objects }; + sim.order_raid(&order, &[object], &mut Out::default()); + assert!(sim.recon.sorties.is_empty()); + } + + // #135: save/load keeps the flight, the pending report, the marks and the checked zones; + // the restored flight finishes the same way. + #[test] + fn save_and_load_keep_the_recon_flight_and_its_marks() { + let mut sim = Sim::new(5); + let object = DVec3::new(0.0, 70.0, 0.0); + let _ = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + let (_, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut Out::default()); + // A second sortie still out with a pending look. + if sim.recon.sorties.is_empty() { + sim.recon.checked.clear(); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + } + let _ = look_once(&mut sim); + // A drone turned onto a mark has a pending route job keyed by the synthetic id. + let mark = *sim.recon.marks.values().next().expect("no mark to aim at"); + let mut d = sim.make_drone(DroneKind::Kh22, DVec3::new(-800.0, 120.0, 0.0), DVec3::X, mark.area); + d.smart = true; + d.target = mark.area; + d.aim = ew::Aim::unit(mark.id, sim.tick, mark.confidence(sim.tick)); + let drone = d.id; + sim.drones.push(d); + sim.retargets.push_back(ew::RouteJob::restored(900, drone, mark.area, mark.id, sim.tick, ew::Intent::Plan, std::sync::Arc::new(Vec::new()), None)); + let text = sim.air_text().expect("a recon flight is durable"); + assert!(text.contains("airrecon"), "the recon section was not written"); + let mut back = Sim::new(6); + back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there")); + assert_eq!(back.recon.marks.len(), sim.recon.marks.len()); + assert_eq!(back.recon.sorties.len(), sim.recon.sorties.len()); + assert!(back.retargets.iter().any(|j| j.unit == mark.id), "a job on a recon mark was lost with the save"); + for (a, b) in sim.recon.marks.values().zip(back.recon.marks.values()) { + assert_eq!((a.id, a.category, a.quality, a.observed, a.reported), (b.id, b.category, b.quality, b.observed, b.reported)); + assert!(a.area.distance(b.area) < 0.02 && (a.radius - b.radius).abs() < 1e-6); + } + for (a, b) in sim.recon.sorties.iter().zip(&back.recon.sorties) { + assert_eq!((a.drone, a.next, a.launched, a.report_at, a.report_zone), (b.drone, b.next, b.launched, b.report_at, b.report_zone)); + assert_eq!(a.pending.len(), b.pending.len()); + assert_eq!(a.zones.len(), b.zones.len()); + } + // The restored pending report arrives on its tick and leaves a mark. + back.tick = at + REPORT_DELAY * 2; + back.step_recon(&mut Out::default()); + assert!(!back.recon.marks.is_empty()); + } + + // #135: a normal smart wave with a recon flight still ends. The recon phase is bounded and + // never holds the raid open; a lost or empty sortie does not pause the match. + #[test] + fn a_normal_smart_wave_with_recon_finishes() { + let mut sim = Sim::new(7); + sim.targets.push(DVec3::new(0.0, 70.0, 0.0)); + sim.target_health.push(100.0); + let mut ground = Ground::default(); + let land = Land(|_, _| 64); + let mut out = Out::default(); + for _ in 0..20 { + serve(&mut ground, &land, sim.tick); + sim.step(&mut ground, None, &mut out); + } + let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 2), (DroneKind::Gerbera, 2)], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart }; + assert_eq!(sim.order_raid(&order, &[DVec3::new(0.0, 70.0, 0.0)], &mut out), 4); + assert!(!sim.recon.sorties.is_empty(), "the smart wave sent no recon"); + let mut ticks = 0; + for _ in 0..8000 { + serve(&mut ground, &land, sim.tick); + out = Out::default(); + sim.step(&mut ground, None, &mut out); + ticks += 1; + if !sim.planning() && sim.queue.is_empty() && !sim.drones.iter().any(|d| d.alive()) { + break; + } + } + assert!(!sim.planning(), "the raid never stopped planning"); + assert!(sim.queue.is_empty(), "the raid still has launches waiting"); + assert!(!sim.drones.iter().any(|d| d.alive()), "a drone flew for ever"); + assert!(ticks < 8000); + } + + // #135: a later raid inherits the picture the earlier one radioed home -- the marks do not + // vanish with the wave -- and its flight never grows past the budget while an aircraft of + // the first wave is still out. + #[test] + fn a_new_raid_keeps_the_marks_and_stays_within_the_flight_budget() { + let mut sim = Sim::new(11); + let object = DVec3::new(0.0, 70.0, 0.0); + let _ = sam(&mut sim, SamKind::S400, object + DVec3::new(20.0, 0.0, 10.0)); + sim.targets.push(object); + sim.target_health.push(100.0); + let mut out = Out::default(); + // Far out, so no aircraft starts inside a zone and the second one can stay out. + sim.start_recon(&[object], 0.0, 900.0, &mut out); + let (_, at) = look_once(&mut sim); + sim.tick = at + REPORT_DELAY; + sim.step_recon(&mut out); + let seen = *sim.recon.marks.values().next().expect("the first flight reported nothing"); + assert!(!sim.recon.sorties.is_empty(), "the first flight left no aircraft out"); + sim.order_raid(&order(), &[object], &mut out); + assert!(sim.recon.sorties.len() <= SORTIES_MAX, "a second order launched past the recon budget"); + let kept = sim.recon.marks.get(&seen.id).copied().expect("a new raid forgot what the first one saw"); + assert_eq!((kept.area, kept.observed, kept.category), (seen.area, seen.observed, seen.category), "a new raid rewrote a mark"); + assert!(!sim.recon.leads(sim.tick).is_empty(), "the new wave planned without the old picture"); + } + + // #135: a refinement of an existing mark changes the save's dirty shape. A report that only + // updates the area, age, quality or role leaves every count as it was, so the counts alone + // would let an autosave miss it. + #[test] + fn a_refined_mark_changes_the_durable_shape() { + let mut r = Recon::default(); + let coarse_look = Look { + truth: 5, + area: DVec3::ZERO, + radius: COARSE_AREA, + category: Category::Radar, + role: None, + quality: Quality::Coarse, + source: Source::Flyby, + observed: 100, + }; + r.report(coarse_look, 200); + let coarse = r.mark(); + r.report( + Look { observed: 100 + REFINE_GAP, quality: Quality::Refined, role: Some(battery::RadarRole::Engagement), source: Source::Emission, area: DVec3::new(30.0, 70.0, 0.0), radius: REFINED_AREA, ..coarse_look }, + 200 + REFINE_GAP, + ); + assert_eq!(r.marks.len(), 1, "a refinement made a second mark"); + assert_ne!(r.mark(), coarse, "a refined mark is invisible to the autosave's dirty check"); + } + + // #135: among equally fresh, equally well known radars, the one whose observed role is the + // bigger is offered the strikers first; the modest one is still worked over, so the raid keeps + // its breadth. The seed does not change it: the order is the observed role, not a draw or an id. + #[test] + fn a_big_observed_radar_is_offered_the_strikers_first() { + for seed in [1u64, 2, 3] { + let mut sim = Sim::new(seed); + sim.tick = 1000; + let look = |truth: u32, role: battery::RadarRole| Look { + truth, + area: DVec3::new(f64::from(truth) * 100.0, 70.0, 0.0), + radius: REFINED_AREA, + category: Category::Radar, + role: Some(role), + quality: Quality::Refined, + source: Source::Emission, + observed: 1000, + }; + sim.recon.report(look(1, battery::RadarRole::Search), 1000); + sim.recon.report(look(2, battery::RadarRole::Engagement), 1000); + let id_of = |truth: u32| sim.recon.truth.iter().find_map(|(id, t)| (*t == truth).then_some(*id)).unwrap(); + let (modest, big) = (id_of(1), id_of(2)); + let jobs = sim.radar_strikes(&[(DroneKind::Kh22, 8)], &[]); + let first: Vec = jobs.iter().flatten().map(|(_, id)| *id).collect(); + assert_eq!(first.first().copied(), Some(big), "seed {seed}: a modest station was offered the first striker"); + assert!(first.contains(&modest), "seed {seed}: the modest station got no striker at all"); + } + } + + // #135: a recon aircraft is a role of its own: it neither opens a strike's replay nor keeps + // one open. A strike drone still does, so the check is not vacuous. + #[test] + fn a_recon_flight_does_not_open_the_strike_replay() { + let mut sim = Sim::new(12); + let object = DVec3::new(0.0, 70.0, 0.0); + sim.targets.push(object); + sim.target_health.push(100.0); + sim.start_recon(&[object], 0.0, 300.0, &mut Out::default()); + assert!(!sim.recon.sorties.is_empty(), "no recon aircraft to test with"); + sim.begin_recording_if_active(); + assert!(sim.rec.is_none(), "a recon aircraft opened a strike replay"); + sim.launch(DroneKind::Shahed, DVec3::new(-300.0, 120.0, 0.0), DVec3::X, object, &mut Out::default()); + sim.begin_recording_if_active(); + assert!(sim.rec.is_some(), "a strike drone did not open its replay"); + } + + // #135: the recon memory is as durable as the rest of the air state and stays inside the + // section's byte budget: every mark, checked zone and sortie written is read back. + #[test] + fn the_whole_recon_memory_fits_a_save_and_reads_back() { + let mut sim = Sim::new(13); + sim.tick = 100; + for truth in 1..=MAX_MARKS as u32 { + sim.recon.report( + Look { + truth, + area: DVec3::new(f64::from(truth), 70.0, -0.5), + radius: COARSE_AREA, + category: Category::Launcher, + role: None, + quality: Quality::Coarse, + source: Source::Flyby, + observed: 100, + }, + 100, + ); + } + for x in 0..MAX_CHECKED as i64 { + sim.recon.remember_zone(DVec3::new(x as f64 * 10.0, 70.0, 5.0), 100); + } + assert_eq!(sim.recon.marks.len(), MAX_MARKS); + let text = sim.air_text().expect("a full recon memory is durable"); + assert!(text.len() < 1 << 20, "the air section grew to {} bytes", text.len()); + let mut back = Sim::new(14); + back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there")); + assert_eq!(back.recon.marks.len(), MAX_MARKS); + assert_eq!(back.recon.checked.len(), MAX_CHECKED); + assert_eq!(back.recon.marks.values().map(|m| m.observed).sum::(), MAX_MARKS as u64 * 100); + } +} diff --git a/airdef-mod/src/sim/record.rs b/airdef-mod/src/sim/record.rs index e9ca74d..5259ef0 100644 --- a/airdef-mod/src/sim/record.rs +++ b/airdef-mod/src/sim/record.rs @@ -1,8 +1,9 @@ //! Raids are recorded for their replays: every drone's and interceptor's //! track (a point every other tick, falling wrecks included) and what //! happened (shot down, by what; hits; systems lost; the Oreshnik's split). -//! A recording starts with the first drone in the sky and ends when the sky -//! has been clear a while; the last few are kept. +//! A recording starts with the first strike drone in the sky and ends when the sky +//! has been clear a while; the last few are kept. A recon aircraft is a role of its own +//! and is not part of the strike's replay (#135). use super::*; /// A system's pose at a moment of a recording. @@ -834,8 +835,11 @@ impl Sim { } /// Open before the combat update so transitions on the first active tick are not lost. + /// A recon aircraft neither opens nor holds a strike's recording (#135). pub(super) fn begin_recording_if_active(&mut self) { - if self.rec.is_none() && (self.drones.iter().any(|d| d.alive()) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) { + if self.rec.is_none() + && (self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id)) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty()) + { self.recordings += 1; self.rec = Some(Recording::new(self.recordings, self)); } @@ -853,7 +857,13 @@ impl Sim { pub(super) fn record(&mut self) { // Wrecks still falling (far off they fall a long while) don't keep it going. A counter-strike is a recorded // object in its own right (#109): it holds the recording open until it lands, whatever the sky is doing. - let busy = self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || !self.queue.is_empty() || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty(); + // A recon flight is not part of the strike's replay: it neither opens nor holds a + // recording open. The strike's own drones and interceptors do (#135). + let busy = self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id)) + || !self.missiles.is_empty() + || !self.queue.is_empty() + || !self.strikes.flights.is_empty() + || !self.strikes.pending.is_empty(); self.begin_recording_if_active(); let Some(r) = &mut self.rec else { return }; r.note_tracks(&self.sams); @@ -867,7 +877,7 @@ impl Sim { if r.len % STEP == 0 { let now = r.len; r.note_sams(&self.sams, now); - for d in &self.drones { + for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) { r.point(d.id, What::Drone(d.kind), d.pos); } for m in &self.missiles { 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 хранит дронов, очередь запуска, задания с картиной и рельефом своей версии, поэтому