Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9370fd4ed4 |
@@ -193,9 +193,7 @@ API мода `render.set-lights` (до 512, плавно интерполиру
|
|||||||
трек-прогноз оранжевый и помечен возрастом. Свои перехватчики — маленькие жёлтые квадраты. Это данные сети
|
трек-прогноз оранжевый и помечен возрастом. Свои перехватчики — маленькие жёлтые квадраты. Это данные сети
|
||||||
РЛС, как на радаре и карте; в режиме «Истина» (`/airdef truth on`, T на карте) добавляются белые рамки
|
РЛС, как на радаре и карте; в режиме «Истина» (`/airdef truth on`, T на карте) добавляются белые рамки
|
||||||
реальных дронов с их настоящим типом — отдельно от сетевых оценок, чтобы видеть расхождение. Отпустил
|
реальных дронов с их настоящим типом — отдельно от сетевых оценок, чтобы видеть расхождение. Отпустил
|
||||||
клавишу — метки исчезли. Метки достаются ближайшим из видимых целей: цель за камерой или за краем
|
клавишу — метки исчезли. Метки проектируются через камеру последнего отрисованного кадра (`render.project`,
|
||||||
экрана бюджет кадра не тратит, а заголовок показывает, сколько целей в кадре, сколько за кадром и сколько
|
|
||||||
не поместилось в бюджет. Метки проектируются через камеру последнего отрисованного кадра (`render.project`,
|
|
||||||
API 31 форка) и следуют за взглядом покадрово; поверх повтора, сетки J, монитора K и карты M обзор не рисуется.
|
API 31 форка) и следуют за взглядом покадрово; поверх повтора, сетки J, монитора K и карты M обзор не рисуется.
|
||||||
|
|
||||||
**Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто
|
**Повторы.** Каждый налёт записывается сам: с первой цели в небе до момента, когда небо 5 с чисто
|
||||||
@@ -206,12 +204,7 @@ API 31 форка) и следуют за взглядом покадрово;
|
|||||||
целью, потом за перехватчиком (или смотрит из пушки, со стороны на прилёт), в момент сбития время замедляется;
|
целью, потом за перехватчиком (или смотрит из пушки, со стороны на прилёт), в момент сбития время замедляется;
|
||||||
- **полный повтор** — весь налёт, камера-режиссёр сама выбирает, за чем следить; колесо — перемотка, стрелки — скорость;
|
- **полный повтор** — весь налёт, камера-режиссёр сама выбирает, за чем следить; колесо — перемотка, стрелки — скорость;
|
||||||
- **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения
|
- **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения
|
||||||
объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты;
|
объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты.
|
||||||
- **цепочки боя** — меню N → «Повторы…» → «Цепочки боя»: по каждому контакту короткая строка
|
|
||||||
«отметка → передача → захват → пуск → исход» из 4–5 измеренных переходов записи, без домыслов. Видны
|
|
||||||
время каждого шага, батарея и контакт, у пропущенных контактов — «без пуска». Фильтр по батарее
|
|
||||||
переключает список; клик открывает кадр повтора (клип исхода, а если исхода нет — карту налёта на
|
|
||||||
моменте пуска или отметки). То же списком: `/airdef chains [номер батареи]`.
|
|
||||||
|
|
||||||
Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. Управление (подсказка
|
Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. Управление (подсказка
|
||||||
показывается в начале, после нажатия и на паузе): **← →** — перемотка на 5 с (в нарезке — соседний момент),
|
показывается в начале, после нажатия и на паузе): **← →** — перемотка на 5 с (в нарезке — соседний момент),
|
||||||
@@ -237,18 +230,6 @@ API 31 форка) и следуют за взглядом покадрово;
|
|||||||
- `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — три разные игровые РЛС с устойчивыми профилями в каталоге. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав, профиль, цикл, продукты измерения и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию. Профиль РЛС задаётся при размещении и не переключается на ходу: `radar <номер> on|off` сохраняется. Обзорная станция даёт редкие грубые отметки и область поиска; мачтовая уточняет низкие контакты над рельефом; сопровождения ищет локально, ведёт ограниченное число точных треков и только её собственное подтверждённое измерение разрешает пуск. Сеть передаёт источник, возраст и качество, но повторная пересылка не освежает измерение. Старые С-400/С-500 сохраняют сборную конфигурацию, старые роли РЛС при загрузке сопоставляются с профилями. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md).
|
- `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — три разные игровые РЛС с устойчивыми профилями в каталоге. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав, профиль, цикл, продукты измерения и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию. Профиль РЛС задаётся при размещении и не переключается на ходу: `radar <номер> on|off` сохраняется. Обзорная станция даёт редкие грубые отметки и область поиска; мачтовая уточняет низкие контакты над рельефом; сопровождения ищет локально, ведёт ограниченное число точных треков и только её собственное подтверждённое измерение разрешает пуск. Сеть передаёт источник, возраст и качество, но повторная пересылка не освежает измерение. Старые С-400/С-500 сохраняют сборную конфигурацию, старые роли РЛС при загрузке сопоставляются с профилями. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md).
|
||||||
- `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <patriot|gepard|pantsir|s400|s500|all> <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`;
|
- `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <patriot|gepard|pantsir|s400|s500|all> <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`;
|
||||||
- `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve <K>` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48).
|
- `/airdef doctrine` — доктрины комплексов (#47; в меню N: «Доктрины…»): `/airdef doctrine <номер|all> reserve <K>` — держать K ракет для срочных целей (баллистика или до удара меньше 12 с); `salvo eco|normal|heavy` — сколько перехватчиков на цель (только базовые / как обычно / на один больше); `sector <центр°> <полуширина°>` или `sector off` — сектор ответственности (0° — север); `guard <объект№>[,<№>]` или `guard off` — стрелять только по тому, что идёт на охраняемые объекты (отметка: `/airdef target here`). По умолчанию ограничений нет; последний шанс сильнее доктрины; `/airdef why <номер>` называет, какая настройка остановила или разрешила пуск; сохраняется с миром и сценариями. Карта охраны и пробелов в ней — вместе с картой (#48).
|
||||||
- `/airdef why <номер>` — почему комплекс стреляет или нет. Сразу под строкой состояния — одна typed-причина:
|
|
||||||
«есть только обзор», «ждёт сопровождения», «каналы заняты», «нет боезапаса» или «готов к пуску», вместе с возрастом и
|
|
||||||
источником отметки (своя РЛС или сеть, РЛС №N). «Есть только обзор» — на картине лишь поисковая или
|
|
||||||
сетевая отметка, своё подтверждённое измерение пуск не разрешает; «ждёт сопровождения» — своя РЛС ещё
|
|
||||||
уточняет контакт или пусковая ждёт огневой трек поддерживающей РЛС; «каналы заняты» — все каналы
|
|
||||||
сопровождения заняты другими контактами; «нет боезапаса» — нет ракет и снарядов или идёт перезарядка.
|
|
||||||
`/airdef why <номер> source` переводит монитор K на станцию, которая поставила отметку. Подробные
|
|
||||||
проверки (роли, доктрина, дальность, наведение) идут ниже и не расходятся с этой причиной. В обычном
|
|
||||||
HUD — только картина самой батареи: класс по оценке, без истинного типа и скрытых данных.
|
|
||||||
- `/airdef chains [номер батареи]` — короткие цепочки последнего налёта: «отметка → передача → захват →
|
|
||||||
пуск → исход» с временем шагов; без номера — все батареи. Строка кликабельна в меню N → «Повторы…» →
|
|
||||||
«Цепочки боя» и открывает кадр повтора.
|
|
||||||
- `/airdef deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
|
- `/airdef deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
|
||||||
- `/airdef hold on|off` — запретить или разрешить ПВО огонь, удобно для съёмки ударов;
|
- `/airdef hold on|off` — запретить или разрешить ПВО огонь, удобно для съёмки ударов;
|
||||||
- `/airdef damage on|off` — разрушать ли ландшафт взрывами (через TNT, нужны читы);
|
- `/airdef damage on|off` — разрушать ли ландшафт взрывами (через TNT, нужны читы);
|
||||||
|
|||||||
@@ -9,7 +9,5 @@ glam = "0.30"
|
|||||||
|
|
||||||
[features]
|
[features]
|
||||||
test-fixtures = []
|
test-fixtures = []
|
||||||
# Counts the events the by-time journal readers hand out (the `replay_bench` example).
|
|
||||||
bench-counters = []
|
|
||||||
|
|
||||||
[workspace]
|
[workspace]
|
||||||
|
|||||||
@@ -8,10 +8,6 @@ description = "AirDef: long-range drones and air defence for the AirDef fork of
|
|||||||
[lib]
|
[lib]
|
||||||
crate-type = ["cdylib", "rlib"]
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
[features]
|
|
||||||
# Counts the events the by-time readers hand out (the `replay_bench` example); off in the mod build.
|
|
||||||
bench-counters = ["airdef-core/bench-counters"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
airdef-core = { path = "../airdef-core" }
|
airdef-core = { path = "../airdef-core" }
|
||||||
horizon-mod-sdk = { path = "../horizon/crates/horizon-mod-sdk" }
|
horizon-mod-sdk = { path = "../horizon/crates/horizon-mod-sdk" }
|
||||||
|
|||||||
@@ -1,261 +0,0 @@
|
|||||||
//! Replay hot-path benchmark (#150): a 10-minute raid with its journals almost full.
|
|
||||||
//!
|
|
||||||
//! Plays the recording the ways a player does — ordinary playback, reverse seeks, a pause and
|
|
||||||
//! an MP4 export (the director's film) — and reports the CPU per frame (p50/p95/p99) and the
|
|
||||||
//! events the by-time readers handed out. Run it with the counters built in:
|
|
||||||
//!
|
|
||||||
//! cargo run --release --example replay_bench --features bench-counters
|
|
||||||
//!
|
|
||||||
//! Without `bench-counters` the scanned-events numbers read 0. Native timings compare runs on
|
|
||||||
//! one machine; they say nothing about the WASM build or the GPU.
|
|
||||||
use airdef::film::{Film, Which};
|
|
||||||
use airdef::replay::{Control, Mode, Player};
|
|
||||||
use airdef::sim::record::{Event, EventKind, Recording, SceneEvent, SceneJournal, SceneKind, StrikeResult, What};
|
|
||||||
use airdef::sim::{DroneKind, Ground, MissileKind, Out, SamKind, Sim};
|
|
||||||
use glam::DVec3;
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
/// The longest recording, ticks (10 minutes at 20 a second).
|
|
||||||
const TICKS: u32 = 12_000;
|
|
||||||
/// The event journal's cap, and the scene journal's (`MAX_SCENE_EVENTS`), nearly reached.
|
|
||||||
const EVENTS: usize = 64_000;
|
|
||||||
const SCENE: usize = 65_000;
|
|
||||||
/// Frames measured per mode (20 a second, half a minute of playback; a film frame is 0.05 s).
|
|
||||||
const FRAMES: usize = 600;
|
|
||||||
const LISTENER: DVec3 = DVec3::new(0.0, 70.0, 0.0);
|
|
||||||
|
|
||||||
/// A 10-minute raid's recording: 200 flights, a nearly full event journal and scene journal,
|
|
||||||
/// the objects, systems, tracks and the fires — the journal a busy raid leaves.
|
|
||||||
fn recording() -> Recording {
|
|
||||||
let mut rec = Recording::blank(TICKS);
|
|
||||||
rec.number = 1;
|
|
||||||
rec.len = TICKS;
|
|
||||||
rec.origin = DVec3::ZERO;
|
|
||||||
rec.sams = (0..8).map(|i| (10 + i, SamKind::S400, DVec3::new(i as f64 * 120.0, 64.0, 400.0))).collect();
|
|
||||||
rec.objects = (0..8).map(|i| DVec3::new(i as f64 * 90.0, 70.0, 0.0)).collect();
|
|
||||||
// 200 flights, each a few hundred ticks of the raid (a point every 2 ticks): the map and
|
|
||||||
// the ghosts draw them, the sounds read their launches.
|
|
||||||
for k in 0..200u32 {
|
|
||||||
let first = k * 55 % (TICKS - 700);
|
|
||||||
let last = first + 600;
|
|
||||||
let what = match k % 4 {
|
|
||||||
0 => What::Drone(DroneKind::Geran3),
|
|
||||||
1 => What::Drone(DroneKind::Shahed),
|
|
||||||
2 => What::Missile(MissileKind::M48n6, 10 + k % 8),
|
|
||||||
_ => What::Strike,
|
|
||||||
};
|
|
||||||
rec.straight(1000 + k, what, first, last, DVec3::new(-2000.0, 100.0, k as f64 * 5.0), DVec3::new(500.0, 70.0, k as f64 * 5.0));
|
|
||||||
}
|
|
||||||
// The events: interceptions, hits, losses and splits spread through the raid.
|
|
||||||
rec.events = (0..EVENTS)
|
|
||||||
.map(|i| {
|
|
||||||
let at = (i as u64 * u64::from(TICKS) / EVENTS as u64) as u32;
|
|
||||||
let drone = 1000 + (i as u32 * 7 % 200);
|
|
||||||
let pos = DVec3::new((i % 40) as f64 * 10.0, 95.0, (i % 17) as f64 * 12.0);
|
|
||||||
let kind = match i % 10 {
|
|
||||||
0 | 1 => EventKind::Kill { drone, kind: DroneKind::Geran3, sam: 10, sam_kind: SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() },
|
|
||||||
2 | 3 => EventKind::Hit { drone, kind: DroneKind::Geran3, power: (i % 5) as u32, object: Some(i % 8), sam: None },
|
|
||||||
4 | 5 => EventKind::Crash { drone, kind: DroneKind::Geran3, power: (i % 5) as u32 },
|
|
||||||
6 => EventKind::SamLost { sam: 10 + (i % 8) as u32, kind: SamKind::S400, index: i % 8 },
|
|
||||||
7 => EventKind::Split { drone },
|
|
||||||
_ => EventKind::Strike { site: 1, result: StrikeResult::Destroyed },
|
|
||||||
};
|
|
||||||
Event { at, pos, kind }
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
// The scene journal: launches and ignitions (the exact sounds), track changes and fires.
|
|
||||||
let mut scene = SceneJournal::default();
|
|
||||||
for i in 0..SCENE {
|
|
||||||
let at = (i as u64 * u64::from(TICKS) / SCENE as u64) as u32;
|
|
||||||
let missile = 5000 + (i as u32 % 300);
|
|
||||||
let pos = DVec3::new((i % 30) as f64 * 8.0, 66.0, 300.0);
|
|
||||||
let kind = match i % 100 {
|
|
||||||
// Fires are a small share of a raid's transitions (hundreds over ten minutes).
|
|
||||||
0 => SceneKind::FireStarted { fire: (i / 100) as u32, age: 0, life: 4000, size: 1.0, quiet: false, shown: true, water: Some(false) },
|
|
||||||
1 => SceneKind::FireEnded { fire: (i / 100) as u32 },
|
|
||||||
2 | 3 => SceneKind::MissileLaunch { missile, sam: 10, target: 2000, kind: MissileKind::M48n6, sound: "airdef:launch.s400", pitch: 1.0 },
|
|
||||||
4 | 5 => SceneKind::MotorIgnition { missile, kind: MissileKind::M48n6, sound: Some("airdef:launch.s400") },
|
|
||||||
6 => SceneKind::MotorBurnout { missile, kind: MissileKind::M48n6 },
|
|
||||||
7 => SceneKind::MotorEnergyLost { missile, kind: MissileKind::M48n6, speed: 4.0 },
|
|
||||||
8 | 9 => SceneKind::TrackAcquired { sam: 10, target: 2000 + (i as u32 % 200), ever_own: true },
|
|
||||||
_ => SceneKind::TrackLost { sam: 10, target: 2000 + (i as u32 % 200) },
|
|
||||||
};
|
|
||||||
scene.fixture_push(SceneEvent { at, pos, kind });
|
|
||||||
}
|
|
||||||
rec.scene = Some(scene);
|
|
||||||
rec.close();
|
|
||||||
rec
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Answers the ground queries the replays make with a flat 70-block land, as the game would.
|
|
||||||
fn settle(ground: &mut Ground, now: u64) {
|
|
||||||
let wanted = ground.take_wanted();
|
|
||||||
if !wanted.is_empty() {
|
|
||||||
ground.answer(wanted.into_iter().map(|(x, z)| (x, z, 70)).collect(), now);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn percentile(sorted: &[Duration], p: f64) -> f64 {
|
|
||||||
if sorted.is_empty() {
|
|
||||||
return 0.0;
|
|
||||||
}
|
|
||||||
let i = (((sorted.len() - 1) as f64) * p).round() as usize;
|
|
||||||
sorted[i].as_secs_f64() * 1e6
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Measured {
|
|
||||||
mode: &'static str,
|
|
||||||
frames: usize,
|
|
||||||
scanned: u64,
|
|
||||||
cpu: Vec<Duration>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Measured {
|
|
||||||
fn cpu_p(&self, p: f64) -> f64 {
|
|
||||||
let mut sorted = self.cpu.clone();
|
|
||||||
sorted.sort_unstable();
|
|
||||||
percentile(&sorted, p)
|
|
||||||
}
|
|
||||||
fn json(&self, rec: &Recording, sim: &Sim) -> String {
|
|
||||||
let events_bytes = rec.events.capacity() * std::mem::size_of::<Event>();
|
|
||||||
let scene_events = rec.scene.as_ref().map_or(0, |s| s.events().len());
|
|
||||||
let scene_bytes = scene_events * std::mem::size_of::<SceneEvent>();
|
|
||||||
let index_bytes: usize = sim.replays.iter().map(Recording::index_bytes).sum();
|
|
||||||
format!(
|
|
||||||
"{{\"mode\":\"{}\",\"frames\":{},\"journal_events\":{},\"journal_scene\":{},\
|
|
||||||
\"scanned_events\":{},\"scanned_per_frame\":{:.1},\"full_pass_events\":{},\
|
|
||||||
\"p50_us\":{:.1},\"p95_us\":{:.1},\"p99_us\":{:.1},\"max_us\":{:.1},\
|
|
||||||
\"events_bytes\":{},\"scene_bytes\":{},\"index_bytes\":{}}}",
|
|
||||||
self.mode,
|
|
||||||
self.frames,
|
|
||||||
rec.events.len(),
|
|
||||||
scene_events,
|
|
||||||
self.scanned,
|
|
||||||
self.scanned as f64 / self.frames.max(1) as f64,
|
|
||||||
// One whole-journal pass per frame: what the readers did before the ranges (#150).
|
|
||||||
(rec.events.len() + scene_events) as u64 * self.frames as u64,
|
|
||||||
self.cpu_p(0.50),
|
|
||||||
self.cpu_p(0.95),
|
|
||||||
self.cpu_p(0.99),
|
|
||||||
self.cpu.iter().copied().max().unwrap_or_default().as_secs_f64() * 1e6,
|
|
||||||
events_bytes,
|
|
||||||
scene_bytes,
|
|
||||||
index_bytes,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Steps the replay's clock to `t` the way the wheel does (5 s a press), so the seek resets the
|
|
||||||
/// sound cursor and the shot as a player's would.
|
|
||||||
fn seek_to(p: &mut Player, rec: &Recording, t: f64) {
|
|
||||||
for _ in 0..((t.max(0.0) / 100.0) as usize) {
|
|
||||||
p.control(Control::Forward, rec);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sim_with(rec: Recording) -> (Sim, u64) {
|
|
||||||
let mut sim = Sim::new(1);
|
|
||||||
sim.replays.push(rec);
|
|
||||||
(sim, 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ordinary playback from a moment near the end of the raid, time running at ×2.
|
|
||||||
fn playback() -> Measured {
|
|
||||||
let (sim, mut tick) = sim_with(recording());
|
|
||||||
let rec = &sim.replays[0];
|
|
||||||
let mut p = Player::new(1, Mode::Full, &sim);
|
|
||||||
seek_to(&mut p, rec, rec.len as f64 - 1_200.0);
|
|
||||||
let mut ground = Ground::default();
|
|
||||||
let mut out = Out::default();
|
|
||||||
let _ = airdef::sim::record::scanned_events();
|
|
||||||
let mut cpu = Vec::with_capacity(FRAMES);
|
|
||||||
for _ in 0..FRAMES {
|
|
||||||
let started = Instant::now();
|
|
||||||
p.tick(&sim, &mut ground, LISTENER, &mut out);
|
|
||||||
settle(&mut ground, tick);
|
|
||||||
tick += 1;
|
|
||||||
cpu.push(started.elapsed());
|
|
||||||
out = Out::default();
|
|
||||||
}
|
|
||||||
Measured { mode: "playback", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reverse seeks: five seconds back every frame, then a frame of playback.
|
|
||||||
fn reverse_seek() -> Measured {
|
|
||||||
let (sim, mut tick) = sim_with(recording());
|
|
||||||
let rec = &sim.replays[0];
|
|
||||||
let mut p = Player::new(1, Mode::Full, &sim);
|
|
||||||
seek_to(&mut p, rec, rec.len as f64 - 200.0);
|
|
||||||
let mut ground = Ground::default();
|
|
||||||
let mut out = Out::default();
|
|
||||||
let _ = airdef::sim::record::scanned_events();
|
|
||||||
let mut cpu = Vec::with_capacity(FRAMES);
|
|
||||||
for _ in 0..FRAMES {
|
|
||||||
let started = Instant::now();
|
|
||||||
p.control(Control::Back, rec);
|
|
||||||
p.tick(&sim, &mut ground, LISTENER, &mut out);
|
|
||||||
settle(&mut ground, tick);
|
|
||||||
tick += 1;
|
|
||||||
cpu.push(started.elapsed());
|
|
||||||
out = Out::default();
|
|
||||||
}
|
|
||||||
Measured { mode: "reverse_seek", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A pause held while frames keep coming (the HUD and the ghosts stay, nothing sounds).
|
|
||||||
fn paused() -> Measured {
|
|
||||||
let (sim, mut tick) = sim_with(recording());
|
|
||||||
let rec = &sim.replays[0];
|
|
||||||
let mut p = Player::new(1, Mode::Full, &sim);
|
|
||||||
seek_to(&mut p, rec, rec.len as f64 * 0.75);
|
|
||||||
p.control(Control::Pause, rec);
|
|
||||||
let mut ground = Ground::default();
|
|
||||||
let mut out = Out::default();
|
|
||||||
let _ = airdef::sim::record::scanned_events();
|
|
||||||
let mut cpu = Vec::with_capacity(FRAMES);
|
|
||||||
for _ in 0..FRAMES {
|
|
||||||
let started = Instant::now();
|
|
||||||
p.tick(&sim, &mut ground, LISTENER, &mut out);
|
|
||||||
settle(&mut ground, tick);
|
|
||||||
tick += 1;
|
|
||||||
cpu.push(started.elapsed());
|
|
||||||
out = Out::default();
|
|
||||||
}
|
|
||||||
Measured { mode: "pause", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An MP4 export: the director's film, its frames prepared and drawn as the game records them.
|
|
||||||
fn mp4() -> Measured {
|
|
||||||
let (sim, mut tick) = sim_with(recording());
|
|
||||||
let rec = &sim.replays[0];
|
|
||||||
let film = Film::build(rec, Which::Best).expect("the raid has moments to film");
|
|
||||||
let mut p = Player::new(1, Mode::Film(Box::new(film)), &sim);
|
|
||||||
p.wait = true;
|
|
||||||
p.clean = true;
|
|
||||||
let mut ground = Ground::default();
|
|
||||||
let mut out = Out::default();
|
|
||||||
let _ = airdef::sim::record::scanned_events();
|
|
||||||
let mut cpu = Vec::with_capacity(FRAMES);
|
|
||||||
for _ in 0..FRAMES {
|
|
||||||
let started = Instant::now();
|
|
||||||
p.tick(&sim, &mut ground, LISTENER, &mut out);
|
|
||||||
settle(&mut ground, tick);
|
|
||||||
tick += 1;
|
|
||||||
cpu.push(started.elapsed());
|
|
||||||
out = Out::default();
|
|
||||||
}
|
|
||||||
Measured { mode: "mp4", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn main() {
|
|
||||||
let (playback, reverse_seek, paused, mp4) = (playback(), reverse_seek(), paused(), mp4());
|
|
||||||
let (sim, _) = sim_with(recording());
|
|
||||||
let rec = &sim.replays[0];
|
|
||||||
if !airdef::sim::record::scan_counters() {
|
|
||||||
eprintln!("replay_bench: scanned events read 0; rerun with --features bench-counters");
|
|
||||||
}
|
|
||||||
let rows = [playback.json(rec, &sim), reverse_seek.json(rec, &sim), paused.json(rec, &sim), mp4.json(rec, &sim)];
|
|
||||||
println!("[");
|
|
||||||
println!("{}", rows.join(",\n"));
|
|
||||||
println!("]");
|
|
||||||
}
|
|
||||||
@@ -39,7 +39,7 @@ pub fn status(status: BatteryStatus) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// One system's line in the summary panel and on the map.
|
/// One system's line in the summary panel and on the map.
|
||||||
pub fn sam_status(sam: &Sam, now: u64) -> String {
|
pub fn sam_status(sam: &Sam) -> String {
|
||||||
let spec = sam.kind.spec();
|
let spec = sam.kind.spec();
|
||||||
let mut text = spec.name.to_string();
|
let mut text = spec.name.to_string();
|
||||||
if !sam.alive() {
|
if !sam.alive() {
|
||||||
@@ -67,7 +67,7 @@ pub fn sam_status(sam: &Sam, now: u64) -> String {
|
|||||||
let channels = if profile.channels == 0 {
|
let channels = if profile.channels == 0 {
|
||||||
"без уточнения".to_string()
|
"без уточнения".to_string()
|
||||||
} else {
|
} else {
|
||||||
format!("каналы {}/{}", sam.own_channels_used(now), profile.channels)
|
format!("каналы {}/{}", sam.own_channels_used(), profile.channels)
|
||||||
};
|
};
|
||||||
return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len());
|
return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len());
|
||||||
}
|
}
|
||||||
@@ -126,20 +126,20 @@ mod tests {
|
|||||||
let mut s400 = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0);
|
let mut s400 = Sam::new(1, SamKind::S400, DVec3::ZERO, 0.0);
|
||||||
s400.missiles = 1;
|
s400.missiles = 1;
|
||||||
s400.ground_rounds = 2;
|
s400.ground_rounds = 2;
|
||||||
assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек");
|
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек");
|
||||||
s400.ground_return = true;
|
s400.ground_return = true;
|
||||||
assert_eq!(sam_status(&s400, 0), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U");
|
assert_eq!(sam_status(&s400), "С-400 ПВО 1 · RM48U 2 / 4 ячеек · ожидает вывоза RM48U");
|
||||||
|
|
||||||
let mut pantsir = Sam::new(2, SamKind::Pantsir, DVec3::ZERO, 0.0);
|
let mut pantsir = Sam::new(2, SamKind::Pantsir, DVec3::ZERO, 0.0);
|
||||||
pantsir.missiles = 7;
|
pantsir.missiles = 7;
|
||||||
pantsir.bursts = 100;
|
pantsir.bursts = 100;
|
||||||
assert_eq!(sam_status(&pantsir, 0), "Панцирь-С1 ракеты 7/12 очереди 100");
|
assert_eq!(sam_status(&pantsir), "Панцирь-С1 ракеты 7/12 очереди 100");
|
||||||
|
|
||||||
let mut worn = Sam::new(3, SamKind::Patriot, DVec3::ZERO, 0.0);
|
let mut worn = Sam::new(3, SamKind::Patriot, DVec3::ZERO, 0.0);
|
||||||
worn.health = 0.5;
|
worn.health = 0.5;
|
||||||
worn.comps.0[Part::Sensor as usize] = 0.4;
|
worn.comps.0[Part::Sensor as usize] = 0.4;
|
||||||
worn.reloading = 21;
|
worn.reloading = 21;
|
||||||
assert_eq!(sam_status(&worn, 0), "Patriot (50%) [РЛС 40%] перезарядка 2с");
|
assert_eq!(sam_status(&worn), "Patriot (50%) [РЛС 40%] перезарядка 2с");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -147,41 +147,41 @@ mod tests {
|
|||||||
let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0);
|
let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0);
|
||||||
radar.own.push(7);
|
radar.own.push(7);
|
||||||
radar.comps.0[Part::Sensor as usize] = 0.0;
|
radar.comps.0[Part::Sensor as usize] = 0.0;
|
||||||
assert_eq!(sam_status(&radar, 0), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
|
assert_eq!(sam_status(&radar), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
|
||||||
|
|
||||||
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
|
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
|
||||||
depot.cargo = 2;
|
depot.cargo = 2;
|
||||||
depot.ground_stock = 3;
|
depot.ground_stock = 3;
|
||||||
depot.air_48n6_stock = 1;
|
depot.air_48n6_stock = 1;
|
||||||
assert_eq!(sam_status(&depot, 0), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1");
|
assert_eq!(sam_status(&depot), "Склад боеприпасов: 2 перезарядок, RM48U 3, снятых ПВО 1");
|
||||||
|
|
||||||
let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0);
|
let mut tzm = Sam::new(6, SamKind::Tzm, DVec3::ZERO, 0.0);
|
||||||
tzm.cargo = 1;
|
tzm.cargo = 1;
|
||||||
tzm.return_cargo = true;
|
tzm.return_cargo = true;
|
||||||
assert_eq!(sam_status(&tzm, 0), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад");
|
assert_eq!(sam_status(&tzm), "ТЗМ: на борту 1/2, RM48U 0, снятых ПВО 0, везёт RM48U на склад");
|
||||||
|
|
||||||
let mut ew = Sam::new(7, SamKind::Ew, DVec3::ZERO, 0.0);
|
let mut ew = Sam::new(7, SamKind::Ew, DVec3::ZERO, 0.0);
|
||||||
ew.ew_on = true;
|
ew.ew_on = true;
|
||||||
ew.heat = 0.5;
|
ew.heat = 0.5;
|
||||||
assert_eq!(sam_status(&ew, 0), "Станция РЭБ: ГЛУШИТ, нагрев 50%");
|
assert_eq!(sam_status(&ew), "Станция РЭБ: ГЛУШИТ, нагрев 50%");
|
||||||
|
|
||||||
let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0);
|
let mut light = Sam::new(8, SamKind::Light, DVec3::ZERO, 0.0);
|
||||||
light.target = Some(1);
|
light.target = Some(1);
|
||||||
assert_eq!(sam_status(&light, 0), "Прожектор: в луче цель");
|
assert_eq!(sam_status(&light), "Прожектор: в луче цель");
|
||||||
|
|
||||||
let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0);
|
let optical = Sam::new(9, SamKind::Optical, DVec3::ZERO, 0.0);
|
||||||
assert_eq!(sam_status(&optical, 0), "Оптический пост: ищет");
|
assert_eq!(sam_status(&optical), "Оптический пост: ищет");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn renders_moving_and_destroyed_systems_in_existing_format() {
|
fn renders_moving_and_destroyed_systems_in_existing_format() {
|
||||||
let mut moving = Sam::new(9, SamKind::S400, DVec3::ZERO, 0.0);
|
let mut moving = Sam::new(9, SamKind::S400, DVec3::ZERO, 0.0);
|
||||||
moving.state = SamState::Moving;
|
moving.state = SamState::Moving;
|
||||||
assert_eq!(sam_status(&moving, 0), "С-400 на марше");
|
assert_eq!(sam_status(&moving), "С-400 на марше");
|
||||||
|
|
||||||
let mut dead = Sam::new(10, SamKind::S400, DVec3::ZERO, 0.0);
|
let mut dead = Sam::new(10, SamKind::S400, DVec3::ZERO, 0.0);
|
||||||
dead.health = 0.0;
|
dead.health = 0.0;
|
||||||
assert_eq!(sam_status(&dead, 0), "С-400 УНИЧТОЖЕН");
|
assert_eq!(sam_status(&dead), "С-400 УНИЧТОЖЕН");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -57,10 +57,7 @@ pub fn tree() -> Tree {
|
|||||||
Node::lit("list").runs(),
|
Node::lit("list").runs(),
|
||||||
Node::lit("delete").then(Node::arg("имя", Value::names(SCENARIOS)).runs()),
|
Node::lit("delete").then(Node::arg("имя", Value::names(SCENARIOS)).runs()),
|
||||||
]),
|
]),
|
||||||
Node::lit("why").runs().then(
|
Node::lit("why").runs().then(Node::arg("номер", Value::int_from(1)).runs()),
|
||||||
Node::arg("номер", Value::int_from(1)).runs().then(Node::lit("source").runs()),
|
|
||||||
),
|
|
||||||
Node::lit("chains").runs().then(Node::arg("батарея", Value::int_from(1)).runs()),
|
|
||||||
Node::lit("raid").runs(),
|
Node::lit("raid").runs(),
|
||||||
Node::lit("sites").runs(),
|
Node::lit("sites").runs(),
|
||||||
Node::lit("ground-stock").then(Node::arg("склад", Value::int_from(1)).then(Node::arg("количество", Value::int_from(0)).runs())),
|
Node::lit("ground-stock").then(Node::arg("склад", Value::int_from(1)).then(Node::arg("количество", Value::int_from(0)).runs())),
|
||||||
@@ -171,7 +168,7 @@ mod tests {
|
|||||||
"replay film 3", "replay export", "replay export mine", "replay export best", "replay export all", "replay export 3",
|
"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",
|
"replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop",
|
||||||
"scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list",
|
"scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list",
|
||||||
"scenario delete a", "why", "why 2", "why 2 source", "chains", "chains 2", "ew on", "ew off", "move 4", "target here", "targets clear",
|
"scenario delete a", "why", "why 2", "ew on", "ew off", "move 4", "target here", "targets clear",
|
||||||
"sites", "strike 3", "battery", "battery 1 launcher", "battery 1 integrated", "radar 2 on", "radar 2 off", "radar 2 engagement", "radar 2 search", "deploy s400_launcher", "deploy s500_launcher", "deploy radar_search", "deploy radar_track", "deploy radar_height", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000",
|
"sites", "strike 3", "battery", "battery 1 launcher", "battery 1 integrated", "radar 2 on", "radar 2 off", "radar 2 engagement", "radar 2 search", "deploy s400_launcher", "deploy s500_launcher", "deploy radar_search", "deploy radar_track", "deploy radar_height", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000",
|
||||||
"wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off",
|
"wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off",
|
||||||
"roles all default", "doctrine", "doctrine 1 reserve 4", "doctrine all salvo eco", "doctrine 2 sector 90 45", "doctrine 2 sector off", "doctrine 1 guard 1,2", "doctrine 1 reset", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic",
|
"roles all default", "doctrine", "doctrine 1 reserve 4", "doctrine all salvo eco", "doctrine 2 sector 90 45", "doctrine 2 sector off", "doctrine 1 guard 1,2", "doctrine 1 reset", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic",
|
||||||
@@ -245,10 +242,10 @@ mod tests {
|
|||||||
fn completion_offers_the_next_word_only() {
|
fn completion_offers_the_next_word_only() {
|
||||||
let top = complete("", &[]);
|
let top = complete("", &[]);
|
||||||
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
|
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
|
||||||
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel", "chains"] {
|
"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!(top.contains(&w.to_string()), "{w} in {top:?}");
|
||||||
}
|
}
|
||||||
assert_eq!(top.len(), 37);
|
assert_eq!(top.len(), 36);
|
||||||
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
|
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
|
||||||
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
|
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
|
||||||
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
|
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
|
||||||
|
|||||||
+2
-131
@@ -19,14 +19,14 @@ mod engines;
|
|||||||
mod commands;
|
mod commands;
|
||||||
mod layout;
|
mod layout;
|
||||||
mod map;
|
mod map;
|
||||||
pub mod film;
|
mod film;
|
||||||
mod monitor;
|
mod monitor;
|
||||||
mod overlay;
|
mod overlay;
|
||||||
mod panel;
|
mod panel;
|
||||||
mod presentation;
|
mod presentation;
|
||||||
mod radar;
|
mod radar;
|
||||||
mod recon_view;
|
mod recon_view;
|
||||||
pub mod replay;
|
mod replay;
|
||||||
mod scene;
|
mod scene;
|
||||||
mod smoke;
|
mod smoke;
|
||||||
pub use airdef_core::sim;
|
pub use airdef_core::sim;
|
||||||
@@ -79,8 +79,6 @@ struct AirDef {
|
|||||||
health_mark: u64,
|
health_mark: u64,
|
||||||
/// The menu's page while it is open.
|
/// The menu's page while it is open.
|
||||||
menu: Option<Page>,
|
menu: Option<Page>,
|
||||||
/// The battery the after-action chain list is filtered to (its id; None: all).
|
|
||||||
chain_filter: Option<u32>,
|
|
||||||
/// Where the player is, for the sounds' delay and far variants.
|
/// Where the player is, for the sounds' delay and far variants.
|
||||||
listener: DVec3,
|
listener: DVec3,
|
||||||
/// The picture punch (#51) the HD exposure and bloom were last set for.
|
/// The picture punch (#51) the HD exposure and bloom were last set for.
|
||||||
@@ -208,8 +206,6 @@ enum Page {
|
|||||||
More,
|
More,
|
||||||
/// The last raid's events and its replays.
|
/// The last raid's events and its replays.
|
||||||
Replays,
|
Replays,
|
||||||
/// The last raid's short battle chains: mark → handoff → lock → launch → outcome (#148).
|
|
||||||
Chains,
|
|
||||||
/// The enemy's recon picture and why it prices each mark: debug and after-action review (#135).
|
/// The enemy's recon picture and why it prices each mark: debug and after-action review (#135).
|
||||||
Recon,
|
Recon,
|
||||||
/// The systems with their doctrines, and one system's doctrine (by id) (#47).
|
/// The systems with their doctrines, and one system's doctrine (by id) (#47).
|
||||||
@@ -250,9 +246,6 @@ const BTN_REPLAYS: u32 = 18;
|
|||||||
const BTN_RECON: u32 = 23;
|
const BTN_RECON: u32 = 23;
|
||||||
const REPLAY_EVENTS: u32 = 3;
|
const REPLAY_EVENTS: u32 = 3;
|
||||||
const RECON_ROWS: u32 = 6;
|
const RECON_ROWS: u32 = 6;
|
||||||
const CHAIN_ROWS: u32 = 7;
|
|
||||||
const BTN_CHAINS: u32 = 43;
|
|
||||||
const BTN_CHAIN_FILTER: u32 = 44;
|
|
||||||
const BTN_MAP: u32 = 40;
|
const BTN_MAP: u32 = 40;
|
||||||
const BTN_FULL: u32 = 41;
|
const BTN_FULL: u32 = 41;
|
||||||
const BTN_REEL: u32 = 42;
|
const BTN_REEL: u32 = 42;
|
||||||
@@ -1318,23 +1311,6 @@ impl AirDef {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Opens a battle chain's replay frame: its outcome clip when recorded, else the map at the
|
|
||||||
/// launch (or the mark) held still.
|
|
||||||
fn start_chain(&mut self, row: replay::ChainRow) -> Result<(), String> {
|
|
||||||
match row.event {
|
|
||||||
Some(i) => self.start_replay("clip", Some(i)),
|
|
||||||
None => {
|
|
||||||
self.start_replay("map", None)?;
|
|
||||||
if let Some(player) = self.presentation.playback_mut()
|
|
||||||
&& let Some(rec) = self.sim.replays.last()
|
|
||||||
{
|
|
||||||
player.seek(rec, row.at);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stop_replay(&mut self) {
|
fn stop_replay(&mut self) {
|
||||||
let was_export = self.presentation.is_exporting();
|
let was_export = self.presentation.is_exporting();
|
||||||
self.end_session(presentation::ExitCause::UserStop);
|
self.end_session(presentation::ExitCause::UserStop);
|
||||||
@@ -1662,7 +1638,6 @@ impl AirDef {
|
|||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_MAP, label: "Карта налёта (R)".into() }));
|
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_FULL, label: "Полный повтор".into() }));
|
||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_REEL, label: format!("Лучшие моменты ({})", replay::reel(rec).len()) }));
|
widgets.push(Widget::Button(ButtonWidget { id: BTN_REEL, label: format!("Лучшие моменты ({})", replay::reel(rec).len()) }));
|
||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAINS, label: format!("Цепочки боя (разбор): {}", rec.chains(None).len()) }));
|
|
||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() }));
|
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() }));
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
@@ -1672,40 +1647,11 @@ impl AirDef {
|
|||||||
text: "Повторов пока нет: налёт записывается сам и появится здесь, когда небо очистится".into(),
|
text: "Повторов пока нет: налёт записывается сам и появится здесь, когда небо очистится".into(),
|
||||||
color: 0,
|
color: 0,
|
||||||
}));
|
}));
|
||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAINS, label: "Цепочки боя (разбор)".into() }));
|
|
||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() }));
|
widgets.push(Widget::Button(ButtonWidget { id: BTN_RECON, label: "Разведка противника (разбор)".into() }));
|
||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
|
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Page::Chains => {
|
|
||||||
match self.sim.replays.last() {
|
|
||||||
Some(rec) => {
|
|
||||||
let rows = replay::chain_rows(rec, self.chain_filter);
|
|
||||||
let filter = self.chain_filter.and_then(|id| {
|
|
||||||
rec.sams.iter().position(|s| s.0 == id).map(|i| format!("№{} {}", i + 1, rec.sam(id).map_or("ПВО", |(k, _)| k.name())))
|
|
||||||
});
|
|
||||||
title = format!(
|
|
||||||
"Цепочки боя: отметка → передача → захват → пуск → исход · {} · фильтр: {} · клик: кадр повтора",
|
|
||||||
if rows.is_empty() { "нет цепочек".to_string() } else { format!("{}", rows.len()) },
|
|
||||||
filter.unwrap_or_else(|| "все батареи".into()),
|
|
||||||
);
|
|
||||||
let rows = rows.into_iter().take(200).map(|r| r.text).collect();
|
|
||||||
widgets.push(Widget::List(ListWidget { id: CHAIN_ROWS, rows, selected: None }));
|
|
||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_CHAIN_FILTER, label: "Фильтр по батарее".into() }));
|
|
||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← К повторам".into() }));
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
title = "Цепочки боя".into();
|
|
||||||
widgets.push(Widget::Text(horizon_mod_sdk::ui::TextWidget {
|
|
||||||
id: 0,
|
|
||||||
text: "Повторов пока нет: цепочки появятся после первого налёта".into(),
|
|
||||||
color: 0,
|
|
||||||
}));
|
|
||||||
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← К повторам".into() }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Page::Recon => {
|
Page::Recon => {
|
||||||
title = "Разведка противника — разбор (debug): что враг запомнил и почему".into();
|
title = "Разведка противника — разбор (debug): что враг запомнил и почему".into();
|
||||||
let rows: Vec<String> = recon_view::picture_lines(&self.sim.enemy_picture()).into_iter().take(200).collect();
|
let rows: Vec<String> = recon_view::picture_lines(&self.sim.enemy_picture()).into_iter().take(200).collect();
|
||||||
@@ -1940,7 +1886,6 @@ impl Mod for AirDef {
|
|||||||
world: None,
|
world: None,
|
||||||
health_mark: 0,
|
health_mark: 0,
|
||||||
menu: None,
|
menu: None,
|
||||||
chain_filter: None,
|
|
||||||
listener: DVec3::ZERO,
|
listener: DVec3::ZERO,
|
||||||
punch: 0.0,
|
punch: 0.0,
|
||||||
pending: Vec::new(),
|
pending: Vec::new(),
|
||||||
@@ -2376,37 +2321,6 @@ impl Mod for AirDef {
|
|||||||
self.open_menu(Page::Main);
|
self.open_menu(Page::Main);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
(Page::Replays, BTN_CHAINS) => {
|
|
||||||
self.open_menu(Page::Chains);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
(Page::Chains, CHAIN_ROWS) => {
|
|
||||||
let Some(rec) = self.sim.replays.last() else { return };
|
|
||||||
let Some(row) = replay::chain_rows(rec, self.chain_filter).into_iter().nth(row as usize) else { return };
|
|
||||||
match self.start_chain(row) {
|
|
||||||
Ok(()) => {
|
|
||||||
self.menu = None;
|
|
||||||
ui::close_screen();
|
|
||||||
}
|
|
||||||
Err(e) => say(&e),
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
(Page::Chains, BTN_CHAIN_FILTER) => {
|
|
||||||
// All → each battery → all. Only systems are offered; a battery with no chains
|
|
||||||
// still narrows the list to "nothing", which is the honest answer.
|
|
||||||
let ids: Vec<u32> = self.sim.sams.iter().map(|s| s.id).collect();
|
|
||||||
self.chain_filter = match self.chain_filter {
|
|
||||||
None => ids.first().copied(),
|
|
||||||
Some(id) => ids.iter().position(|x| *x == id).and_then(|i| ids.get(i + 1).copied()),
|
|
||||||
};
|
|
||||||
self.open_menu(Page::Chains);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
(Page::Chains, BTN_BACK) => {
|
|
||||||
self.open_menu(Page::Replays);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
(Page::Main, BTN_RECON) | (Page::Replays, BTN_RECON) => {
|
(Page::Main, BTN_RECON) | (Page::Replays, BTN_RECON) => {
|
||||||
self.open_menu(Page::Recon);
|
self.open_menu(Page::Recon);
|
||||||
return;
|
return;
|
||||||
@@ -2578,53 +2492,11 @@ impl Mod for AirDef {
|
|||||||
if i >= self.sim.sams.len() {
|
if i >= self.sim.sams.len() {
|
||||||
return Err("Нет такой техники".into());
|
return Err("Нет такой техники".into());
|
||||||
}
|
}
|
||||||
// `/airdef why <n> source`: move the monitor to the station that measured the mark.
|
|
||||||
if rest.get(1).is_some_and(|w| *w == "source") {
|
|
||||||
let mark = self.sim.battle_reason(i).and_then(|r| r.mark);
|
|
||||||
let Some(mark) = mark else { return Err("У комплекса нет отметки: источник неизвестен".into()) };
|
|
||||||
if mark.own {
|
|
||||||
return Err("Отметка своя: источник — сама батарея".into());
|
|
||||||
}
|
|
||||||
let Some(source) = mark.source else { return Err("Источник отметки неизвестен".into()) };
|
|
||||||
self.monitor = Some(source);
|
|
||||||
let name = self.sim.sams.get(source).map_or("РЛС", |s| s.kind.name());
|
|
||||||
return Ok(Some(format!(
|
|
||||||
"Переход к источнику отметки: №{} {}, возраст {:.1} с",
|
|
||||||
source + 1,
|
|
||||||
name,
|
|
||||||
mark.age as f64 / 20.0
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
for c in self.sim.why(i) {
|
for c in self.sim.why(i) {
|
||||||
say(&format!("{} {}", if c.ok { "+" } else { "-" }, why_view::reason(&c.reason)));
|
say(&format!("{} {}", if c.ok { "+" } else { "-" }, why_view::reason(&c.reason)));
|
||||||
}
|
}
|
||||||
if let Some(mark) = self.sim.battle_reason(i).and_then(|r| r.mark)
|
|
||||||
&& !mark.own
|
|
||||||
&& mark.source.is_some()
|
|
||||||
{
|
|
||||||
say(&format!("Источник отметки: перейти — /airdef why {} source", i + 1));
|
|
||||||
}
|
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
["chains", rest @ ..] => {
|
|
||||||
let battery = match rest.first() {
|
|
||||||
Some(n) => {
|
|
||||||
let i = n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("/airdef chains [номер батареи]")?;
|
|
||||||
Some(self.sim.sams.get(i).ok_or("Нет такой техники")?.id)
|
|
||||||
}
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
let Some(rec) = self.sim.replays.last() else { return Err("Повторов пока нет: запишется первый же налёт".into()) };
|
|
||||||
let rows = replay::chain_rows(rec, battery);
|
|
||||||
if rows.is_empty() {
|
|
||||||
say("Цепочек нет: в записи не было ни одной отметки (или формат старый)");
|
|
||||||
} else {
|
|
||||||
for row in rows.iter().take(200) {
|
|
||||||
say(&row.text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some("Клик по строке в меню N → «Повторы…» → «Цепочки боя» открывает кадр повтора".into())
|
|
||||||
}
|
|
||||||
["raid"] => {
|
["raid"] => {
|
||||||
self.launch_wave(&mut out)?;
|
self.launch_wave(&mut out)?;
|
||||||
None
|
None
|
||||||
@@ -2888,7 +2760,6 @@ mod tests {
|
|||||||
world: None,
|
world: None,
|
||||||
health_mark: 0,
|
health_mark: 0,
|
||||||
menu: None,
|
menu: None,
|
||||||
chain_filter: None,
|
|
||||||
listener: DVec3::ZERO,
|
listener: DVec3::ZERO,
|
||||||
punch: 0.0,
|
punch: 0.0,
|
||||||
pending: Vec::new(),
|
pending: Vec::new(),
|
||||||
|
|||||||
@@ -2732,7 +2732,7 @@ impl AirDef {
|
|||||||
lines.push((format!("Профиль РЛС: {} [{}]", profile.name, profile.id), WHITE));
|
lines.push((format!("Профиль РЛС: {} [{}]", profile.name, profile.id), WHITE));
|
||||||
lines.push((crate::battery_view::radar_profile_line(profile), GREY));
|
lines.push((crate::battery_view::radar_profile_line(profile), GREY));
|
||||||
lines.push((format!("Ограничение: {}", profile.limit), GREY));
|
lines.push((format!("Ограничение: {}", profile.limit), GREY));
|
||||||
lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(now), profile.channels), GREY));
|
lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(), profile.channels), GREY));
|
||||||
} else if sam.mode == sim::battery::SamMode::LauncherOnly {
|
} else if sam.mode == sim::battery::SamMode::LauncherOnly {
|
||||||
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
|
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
|
||||||
}
|
}
|
||||||
@@ -2740,7 +2740,7 @@ impl AirDef {
|
|||||||
lines.push((format!("Излучение РЛС: {}", if sam.radar_on { "вкл" } else { "выкл" }), WHITE));
|
lines.push((format!("Излучение РЛС: {}", if sam.radar_on { "вкл" } else { "выкл" }), WHITE));
|
||||||
btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on));
|
btns.push((if sam.radar_on { "Выключить РЛС" } else { "Включить РЛС" }.into(), Act::RadarEmission, sam.radar_on));
|
||||||
}
|
}
|
||||||
lines.push((crate::battery_view::sam_status(sam, now), WHITE));
|
lines.push((crate::battery_view::sam_status(sam), WHITE));
|
||||||
if k == SamKind::Optical
|
if k == SamKind::Optical
|
||||||
&& let Some(r) = self.sim.optical_report(sam.id)
|
&& let Some(r) = self.sim.optical_report(sam.id)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -189,7 +189,7 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
|
|||||||
format!("сеть · {seen}")
|
format!("сеть · {seen}")
|
||||||
} else if radar_up {
|
} else if radar_up {
|
||||||
let profile = sam.radar_profile();
|
let profile = sam.radar_profile();
|
||||||
let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(tick), profile.channels) };
|
let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(), profile.channels) };
|
||||||
format!("{} · {} · {}{channels}", profile.name, distance(reach), seen)
|
format!("{} · {} · {}{channels}", profile.name, distance(reach), seen)
|
||||||
} else {
|
} else {
|
||||||
"РЛС ОТКАЗ".to_string()
|
"РЛС ОТКАЗ".to_string()
|
||||||
|
|||||||
+38
-175
@@ -5,22 +5,14 @@
|
|||||||
//! network's. The player's own interceptors wear small yellow squares, as the radar shows them.
|
//! network's. The player's own interceptors wear small yellow squares, as the radar shows them.
|
||||||
//! Letting the key go hides everything. The markers are projected through the camera the last
|
//! Letting the key go hides everything. The markers are projected through the camera the last
|
||||||
//! drawn frame used (`render.project`, API 31), so they sit on the world as it is drawn.
|
//! drawn frame used (`render.project`, API 31), so they sit on the world as it is drawn.
|
||||||
//! Visibility comes before the draw budget (#141): each layer projects at most a bounded number
|
|
||||||
//! of its nearest candidates, keeps the markers of the nearest visible ones, and counts a target
|
|
||||||
//! that leaves the frame without spending a slot.
|
|
||||||
use crate::panel::distance;
|
use crate::panel::distance;
|
||||||
use crate::sim::{ClassEst, Sim, Track};
|
use crate::sim::{ClassEst, Sim, Track};
|
||||||
use glam::DVec3;
|
use glam::DVec3;
|
||||||
use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape};
|
use horizon_mod_sdk::render::{FillShape, Point, Rect, Shape, TextShape};
|
||||||
|
|
||||||
/// The most markers of one picture (the network's, the truth's and the interceptors' each): a full
|
/// The most markers of one picture (the network's and the truth's each): a full raid still fits
|
||||||
/// raid still fits the HUD's 1024 shapes — a marker is four sides and a label.
|
/// the HUD's 1024 shapes — a marker is four sides and a label.
|
||||||
const MAX_MARKERS: usize = 64;
|
const MAX_MARKERS: usize = 64;
|
||||||
/// The most candidates of one layer the frame looks at: the nearest ones by distance. The draw
|
|
||||||
/// budget is spent on what is in frame, but the projection work stays bounded — a crowd the frame
|
|
||||||
/// does not hold cannot buy an unbounded scan, and what the scan never reaches counts as past the
|
|
||||||
/// budget rather than out of the frame.
|
|
||||||
const MAX_SCAN: usize = 4 * MAX_MARKERS;
|
|
||||||
/// A marker's side thickness, pixels.
|
/// A marker's side thickness, pixels.
|
||||||
const LINE: f32 = 1.0;
|
const LINE: f32 = 1.0;
|
||||||
/// A label line's height (the HUD font with its shadow).
|
/// A label line's height (the HUD font with its shadow).
|
||||||
@@ -94,50 +86,6 @@ fn label_y(y: f32, half: f32, gui_h: f32, above: bool) -> f32 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What one layer shows this frame: the markers to draw (the nearest visible candidates), how
|
|
||||||
/// many of the scanned candidates left the frame, and how many the budgets left out.
|
|
||||||
struct Pick<T> {
|
|
||||||
marks: Vec<(T, Point, f32)>,
|
|
||||||
offscreen: usize,
|
|
||||||
capped: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The markers one layer gets this frame. The candidates are ordered nearest the player first and
|
|
||||||
/// at most [`MAX_SCAN`] of them are projected; a candidate the frame does not hold (behind the
|
|
||||||
/// camera or past an edge) is counted and its slot stays free for the next, so the nearest
|
|
||||||
/// [`MAX_MARKERS`] visible candidates are drawn. Work stays bounded by the scan, not the picture.
|
|
||||||
fn pick<T: Copy>(
|
|
||||||
items: impl Iterator<Item = T>,
|
|
||||||
at: impl Fn(T) -> DVec3,
|
|
||||||
half_at: impl Fn(T) -> f32,
|
|
||||||
player: DVec3,
|
|
||||||
gui: (f32, f32),
|
|
||||||
project: &impl Fn(DVec3) -> Option<Point>,
|
|
||||||
) -> Pick<T> {
|
|
||||||
let near = |a: &T, b: &T| at(*a).distance(player).total_cmp(&at(*b).distance(player));
|
|
||||||
let mut items: Vec<T> = items.collect();
|
|
||||||
let total = items.len();
|
|
||||||
// Only the nearest candidates are ever projected: no sort of the whole picture is needed.
|
|
||||||
if items.len() > MAX_SCAN {
|
|
||||||
items.select_nth_unstable_by(MAX_SCAN, near);
|
|
||||||
items.truncate(MAX_SCAN);
|
|
||||||
}
|
|
||||||
items.sort_by(near);
|
|
||||||
let mut marks = Vec::new();
|
|
||||||
let mut offscreen = 0usize;
|
|
||||||
for it in items {
|
|
||||||
if marks.len() >= MAX_MARKERS {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
let h = half_at(it);
|
|
||||||
match project(at(it)) {
|
|
||||||
Some(p) if p.x >= h && p.x <= gui.0 - h && p.y >= h && p.y <= gui.1 - h => marks.push((it, p, h)),
|
|
||||||
_ => offscreen += 1,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Pick { capped: total - marks.len() - offscreen, marks, offscreen }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The overlay's shapes for this frame. `project` is the game's `render.project` (the last drawn
|
/// The overlay's shapes for this frame. `project` is the game's `render.project` (the last drawn
|
||||||
/// frame's camera); a point behind the camera projects to None, a point off the screen still
|
/// frame's camera); a point behind the camera projects to None, a point off the screen still
|
||||||
/// projects past its edges — both are counted, not drawn. Drawn only while the key is held.
|
/// projects past its edges — both are counted, not drawn. Drawn only while the key is held.
|
||||||
@@ -149,17 +97,20 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -
|
|||||||
let pic = sim.air_picture();
|
let pic = sim.air_picture();
|
||||||
let now = pic.now;
|
let now = pic.now;
|
||||||
let truth = sim.truth && !pic.unaided;
|
let truth = sim.truth && !pic.unaided;
|
||||||
// The frame's counts: what got a marker and what did not — out of the frame (behind the camera
|
// The network's tracks, nearest first: a full raid keeps the closest markers.
|
||||||
// or past an edge) or past the budget. The header keeps the two apart (#141).
|
let mut tracks: Vec<&Track> = pic.tracks.iter().collect();
|
||||||
|
tracks.sort_by(|a, b| a.est(now).distance(player).total_cmp(&b.est(now).distance(player)));
|
||||||
let mut shown = 0usize;
|
let mut shown = 0usize;
|
||||||
let mut offscreen = 0usize;
|
let mut hidden = tracks.len().saturating_sub(MAX_MARKERS);
|
||||||
let mut capped = 0usize;
|
for t in tracks.into_iter().take(MAX_MARKERS) {
|
||||||
// The network's tracks: the nearest visible keep the markers; a target behind the camera no
|
let e = t.est(now);
|
||||||
// longer spends one, so a crowd behind cannot crowd out the target in frame.
|
let dist = e.distance(player);
|
||||||
let net = pick(pic.tracks.iter(), |t| t.est(now), |t| half(t.est(now).distance(player)), player, gui, &project);
|
let Some(p) = project(e) else { hidden += 1; continue };
|
||||||
offscreen += net.offscreen;
|
let h = half(dist);
|
||||||
capped += net.capped;
|
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
|
||||||
for (t, p, h) in net.marks {
|
hidden += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
// Fresh: red; a forecast: orange, fading as it ages towards the track's drop (the radar's colours).
|
// Fresh: red; a forecast: orange, fading as it ages towards the track's drop (the radar's colours).
|
||||||
let (color, a) = if pic.unaided {
|
let (color, a) = if pic.unaided {
|
||||||
(RED, 1.0)
|
(RED, 1.0)
|
||||||
@@ -177,17 +128,16 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -
|
|||||||
// with the actual type the network never shows. A tracked drone wears both: the network's
|
// with the actual type the network never shows. A tracked drone wears both: the network's
|
||||||
// estimate under the square, the truth over it — the offset between them is the point.
|
// estimate under the square, the truth over it — the offset between them is the point.
|
||||||
if truth {
|
if truth {
|
||||||
let real = pick(
|
let mut drones: Vec<_> = sim.drones.iter().filter(|d| d.alive()).collect();
|
||||||
sim.drones.iter().filter(|d| d.alive()),
|
drones.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
|
||||||
|d| d.pos,
|
hidden += drones.len().saturating_sub(MAX_MARKERS);
|
||||||
|d| half(d.pos.distance(player)) + 2.0,
|
for d in drones.into_iter().take(MAX_MARKERS) {
|
||||||
player,
|
let Some(p) = project(d.pos) else { hidden += 1; continue };
|
||||||
gui,
|
let h = half(d.pos.distance(player)) + 2.0;
|
||||||
&project,
|
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
|
||||||
);
|
hidden += 1;
|
||||||
offscreen += real.offscreen;
|
continue;
|
||||||
capped += real.capped;
|
}
|
||||||
for (d, p, h) in real.marks {
|
|
||||||
s.extend(square_outline(p.x, p.y, h, WHITE));
|
s.extend(square_outline(p.x, p.y, h, WHITE));
|
||||||
let label = format!("{} {}", d.kind.spec().name, distance(d.pos.distance(player)));
|
let label = format!("{} {}", d.kind.spec().name, distance(d.pos.distance(player)));
|
||||||
s.push(text(label, p.x, label_y(p.y, h, gui.1, true), WHITE, true));
|
s.push(text(label, p.x, label_y(p.y, h, gui.1, true), WHITE, true));
|
||||||
@@ -195,18 +145,24 @@ pub fn draw(sim: &Sim, player: DVec3, gui: (f32, f32), project: impl Fn(DVec3) -
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// The player's own interceptors: small yellow squares, no label — they are not targets, and
|
// The player's own interceptors: small yellow squares, no label — they are not targets, and
|
||||||
// the network never hid them (the radar has always shown them). They keep their own budget.
|
// the network never hid them (the radar has always shown them).
|
||||||
let own = pick(sim.missiles.iter(), |m| m.pos, |_| MISSILE_HALF, player, gui, &project);
|
let mut missiles: Vec<_> = sim.missiles.iter().collect();
|
||||||
for (_, p, h) in own.marks {
|
missiles.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
|
||||||
|
for m in missiles.into_iter().take(MAX_MARKERS) {
|
||||||
|
let Some(p) = project(m.pos) else { continue };
|
||||||
|
let h = MISSILE_HALF;
|
||||||
|
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
s.extend(square_outline(p.x, p.y, h, MISSILE));
|
s.extend(square_outline(p.x, p.y, h, MISSILE));
|
||||||
}
|
}
|
||||||
// The mode, named as the map names it: the network's data by default, the sandbox's truth
|
// The mode, named as the map names it: the network's data by default, the sandbox's truth
|
||||||
// explicitly marked. The counts say what the frame holds, what left it, and what the budget cut.
|
// explicitly marked. The counts say what the frame holds and what stayed behind the camera
|
||||||
let counts = format!("в кадре {shown}, за кадром {offscreen}, сверх бюджета {capped}");
|
// or past the edges.
|
||||||
let head = if truth {
|
let head = if truth {
|
||||||
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · {counts}")
|
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре {shown}, за кадром {hidden}")
|
||||||
} else {
|
} else {
|
||||||
format!("ОБЗОР · данные сети РЛС · {counts}")
|
format!("ОБЗОР · данные сети РЛС · в кадре {shown}, за кадром {hidden}")
|
||||||
};
|
};
|
||||||
s.push(text(head, gui.0 / 2.0, 2.0, if truth { YELLOW } else { GREEN }, true));
|
s.push(text(head, gui.0 / 2.0, 2.0, if truth { YELLOW } else { GREEN }, true));
|
||||||
s
|
s
|
||||||
@@ -245,17 +201,6 @@ mod tests {
|
|||||||
}).collect()
|
}).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn head(shapes: &[Shape]) -> String {
|
|
||||||
texts(shapes).into_iter().find(|t| t.text.starts_with("ОБЗОР")).expect("no header").text.clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `n` targets in a row right behind the camera, each nearer than anything the tests put ahead.
|
|
||||||
fn crowd_behind(sim: &mut Sim, n: u32) {
|
|
||||||
for i in 0..n {
|
|
||||||
sim.launch(DroneKind::Shahed, DVec3::new(i as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_visible_target_gets_a_square_and_a_short_line() {
|
fn a_visible_target_gets_a_square_and_a_short_line() {
|
||||||
let sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
|
let sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
|
||||||
@@ -337,88 +282,6 @@ mod tests {
|
|||||||
assert!(fills(&shapes, RED) / 4 <= MAX_MARKERS);
|
assert!(fills(&shapes, RED) / 4 <= MAX_MARKERS);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// #141: 64 targets behind the camera and one in frame. The budget used to be spent on the
|
|
||||||
/// crowd before the visibility check, so the picture came out empty; the target in frame must
|
|
||||||
/// keep its marker, and the crowd is out of frame, not past the budget.
|
|
||||||
#[test]
|
|
||||||
fn a_crowd_behind_the_camera_leaves_the_network_budget_to_the_target_in_frame() {
|
|
||||||
let mut sim = Sim::new(1);
|
|
||||||
crowd_behind(&mut sim, 64);
|
|
||||||
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
|
|
||||||
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
|
|
||||||
assert_eq!(fills(&shapes, RED), 4, "the target in frame got no marker");
|
|
||||||
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 1, за кадром 64, сверх бюджета 0");
|
|
||||||
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The truth layer keeps its own budget the same way: the real drone in frame is drawn, the
|
|
||||||
/// crowd behind the camera costs no white marker.
|
|
||||||
#[test]
|
|
||||||
fn a_crowd_behind_the_camera_leaves_the_truth_budget_to_the_target_in_frame() {
|
|
||||||
let mut sim = Sim::new(1);
|
|
||||||
let id = sim.id();
|
|
||||||
sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 64.0, 0.0), 0.0));
|
|
||||||
sim.truth = true;
|
|
||||||
crowd_behind(&mut sim, 64);
|
|
||||||
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
|
|
||||||
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
|
|
||||||
assert_eq!(fills(&shapes, WHITE), 4, "the drone in frame got no truth marker");
|
|
||||||
assert_eq!(fills(&shapes, RED), 0, "the network drew a track it does not hold");
|
|
||||||
assert_eq!(head(&shapes), "ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре 1, за кадром 64, сверх бюджета 0");
|
|
||||||
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The interceptors keep their own budget too: a salvo behind the camera leaves the marker
|
|
||||||
/// to the one in frame.
|
|
||||||
#[test]
|
|
||||||
fn a_crowd_behind_the_camera_leaves_the_interceptor_budget_to_the_one_in_frame() {
|
|
||||||
let mut sim = Sim::new(1);
|
|
||||||
for i in 0..64 {
|
|
||||||
sim.missiles.push(crate::sim::Missile::test_at(i + 1, DVec3::new(i as f64, 64.0, -50.0), 0));
|
|
||||||
}
|
|
||||||
sim.missiles.push(crate::sim::Missile::test_at(100, DVec3::new(0.0, 64.0, 100.0), 0));
|
|
||||||
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
|
|
||||||
assert_eq!(fills(&shapes, MISSILE), 4, "the interceptor in frame got no marker");
|
|
||||||
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The header tells what really left the frame from what the draw budget cut, and the markers
|
|
||||||
/// go to the nearest of the visible: 64 behind the camera, 65 in frame.
|
|
||||||
#[test]
|
|
||||||
fn the_header_separates_the_frames_edge_from_the_draw_budget() {
|
|
||||||
let mut sim = Sim::new(1);
|
|
||||||
crowd_behind(&mut sim, 64);
|
|
||||||
for i in 0..65 {
|
|
||||||
let z = 100.0 + i as f64 * 10.0;
|
|
||||||
sim.launch(DroneKind::Shahed, DVec3::new(0.0, 64.0, z), DVec3::ZERO, DVec3::new(0.0, 64.0, 5000.0), &mut Out::default());
|
|
||||||
}
|
|
||||||
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, ahead);
|
|
||||||
// The 64 nearest in frame are drawn; the farthest one is past the draw budget, not out of frame.
|
|
||||||
assert_eq!(fills(&shapes, RED), 4 * MAX_MARKERS);
|
|
||||||
assert!(texts(&shapes).iter().any(|t| t.text.contains("100 м")), "the nearest visible lost its marker");
|
|
||||||
assert!(!texts(&shapes).iter().any(|t| t.text.contains("740 м")), "the farthest visible took a nearer one's marker");
|
|
||||||
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 64, за кадром 64, сверх бюджета 1");
|
|
||||||
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The projection work itself is bounded: with more candidates than the scan budget, only the
|
|
||||||
/// nearest `MAX_SCAN` are looked at, and the rest are counted as past the budget.
|
|
||||||
#[test]
|
|
||||||
fn the_projection_work_is_bounded_by_the_scan_budget() {
|
|
||||||
let mut sim = Sim::new(1);
|
|
||||||
for i in 0..1000 {
|
|
||||||
sim.launch(DroneKind::Shahed, DVec3::new((i % 100) as f64, 64.0, -50.0), DVec3::ZERO, DVec3::new(0.0, 64.0, -5000.0), &mut Out::default());
|
|
||||||
}
|
|
||||||
let calls = std::cell::Cell::new(0usize);
|
|
||||||
let shapes = draw(&sim, DVec3::new(0.0, 64.0, 0.0), GUI, |p| {
|
|
||||||
calls.set(calls.get() + 1);
|
|
||||||
ahead(p)
|
|
||||||
});
|
|
||||||
assert_eq!(calls.get(), MAX_SCAN, "one layer projected more than its scan budget");
|
|
||||||
assert_eq!(head(&shapes), "ОБЗОР · данные сети РЛС · в кадре 0, за кадром 256, сверх бюджета 744");
|
|
||||||
assert!(shapes.len() <= 1024, "{} shapes", shapes.len());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn interceptors_wear_small_yellow_squares_without_labels() {
|
fn interceptors_wear_small_yellow_squares_without_labels() {
|
||||||
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
|
let mut sim = sim_with(DroneKind::Shahed, DVec3::new(0.0, 64.0, 100.0));
|
||||||
|
|||||||
@@ -127,9 +127,9 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
|
|||||||
}
|
}
|
||||||
for sam in sim.sams.iter().take(shown) {
|
for sam in sim.sams.iter().take(shown) {
|
||||||
let mut text = if sam.kind.armed() {
|
let mut text = if sam.kind.armed() {
|
||||||
format!("{} [{}]", crate::battery_view::sam_status(sam, now), crate::sim::roles_text(sam.roles))
|
format!("{} [{}]", crate::battery_view::sam_status(sam), crate::sim::roles_text(sam.roles))
|
||||||
} else {
|
} else {
|
||||||
crate::battery_view::sam_status(sam, now)
|
crate::battery_view::sam_status(sam)
|
||||||
};
|
};
|
||||||
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) {
|
if let Some(t) = sam.gun_target.or(sam.target).and_then(|t| pic.get(t)) {
|
||||||
text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos)));
|
text += &format!(" > {} {}", t.class.name(), distance(t.est(now).distance(sam.pos)));
|
||||||
|
|||||||
+28
-242
@@ -9,7 +9,7 @@ use crate::sim::catalog::sound;
|
|||||||
use crate::film::{self, Film};
|
use crate::film::{self, Film};
|
||||||
use crate::panel::distance;
|
use crate::panel::distance;
|
||||||
use crate::sim::Ground;
|
use crate::sim::Ground;
|
||||||
use crate::sim::record::{Chain, ChainOutcome, ChainStepKind, EventKind, Recording, STEP, StrikeResult, What};
|
use crate::sim::record::{EventKind, Recording, STEP, StrikeResult, What};
|
||||||
use std::cell::Cell;
|
use std::cell::Cell;
|
||||||
use crate::sim::{Class, DroneKind, Out, Sim};
|
use crate::sim::{Class, DroneKind, Out, Sim};
|
||||||
use glam::DVec3;
|
use glam::DVec3;
|
||||||
@@ -187,67 +187,6 @@ pub fn row(rec: &Recording, i: usize) -> String {
|
|||||||
format!("{} {what}", clock(e.at as f64))
|
format!("{} {what}", clock(e.at as f64))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A row of the after-action chain list and where a click on it opens a replay.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct ChainRow {
|
|
||||||
pub text: String,
|
|
||||||
/// The recorded event to clip (the outcome), when there is one.
|
|
||||||
pub event: Option<usize>,
|
|
||||||
/// Otherwise the recording's tick to open the map at (the launch, else the mark).
|
|
||||||
pub at: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The short chains of a raid: отметка → передача → захват → пуск → исход, filtered by a
|
|
||||||
/// battery's id when asked. The list is the recording's measured transitions, not a guess.
|
|
||||||
pub fn chain_rows(rec: &Recording, battery: Option<u32>) -> Vec<ChainRow> {
|
|
||||||
rec.chains(battery).iter().map(|chain| ChainRow { text: chain_row(rec, chain), event: chain.outcome_event(), at: chain_jump_at(chain) }).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a chain opens in a replay when its outcome has no recorded event.
|
|
||||||
fn chain_jump_at(chain: &Chain) -> f64 {
|
|
||||||
chain
|
|
||||||
.step(ChainStepKind::Launch)
|
|
||||||
.or_else(|| chain.step(ChainStepKind::Mark))
|
|
||||||
.map_or(0.0, |s| s.at as f64)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn chain_step_name(chain: &Chain, kind: ChainStepKind, own: bool) -> &'static str {
|
|
||||||
match kind {
|
|
||||||
ChainStepKind::Mark => "отметка",
|
|
||||||
ChainStepKind::Handoff if own => "передача (своя РЛС)",
|
|
||||||
ChainStepKind::Handoff => "передача (сеть)",
|
|
||||||
ChainStepKind::Lock => "захват",
|
|
||||||
ChainStepKind::Launch => "пуск",
|
|
||||||
ChainStepKind::Outcome => match chain.outcome {
|
|
||||||
ChainOutcome::Destroyed => "сбит",
|
|
||||||
ChainOutcome::Hit => "прорыв",
|
|
||||||
ChainOutcome::Lost => "потерян",
|
|
||||||
ChainOutcome::Unfinished => "без исхода",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One chain as a line: the battery, its contact, and the four or five measured steps.
|
|
||||||
pub fn chain_row(rec: &Recording, chain: &Chain) -> String {
|
|
||||||
let index = rec.sams.iter().position(|s| s.0 == chain.sam).map(|i| i + 1);
|
|
||||||
let kind = rec.sam(chain.sam).map_or("ПВО", |(kind, _)| kind.name());
|
|
||||||
let target = rec
|
|
||||||
.track(chain.target)
|
|
||||||
.and_then(|t| match t.what {
|
|
||||||
What::Drone(kind) => Some(kind.spec().name),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.unwrap_or("цель");
|
|
||||||
let steps: Vec<String> = chain.steps.iter().map(|s| format!("{} {}", chain_step_name(chain, s.kind, s.own), clock(s.at as f64))).collect();
|
|
||||||
let battery = index.map_or_else(|| format!("№? {kind}"), |i| format!("№{i} {kind}"));
|
|
||||||
format!(
|
|
||||||
"{} {battery} → «{target}»: {}{}",
|
|
||||||
clock(chain.marked_at() as f64),
|
|
||||||
steps.join(" → "),
|
|
||||||
if chain.missed() { " · без пуска" } else { "" },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How worth watching an event is: the reel takes the best.
|
/// How worth watching an event is: the reel takes the best.
|
||||||
pub fn interest(rec: &Recording, i: usize) -> f64 {
|
pub fn interest(rec: &Recording, i: usize) -> f64 {
|
||||||
let e = &rec.events[i];
|
let e = &rec.events[i];
|
||||||
@@ -360,16 +299,6 @@ impl Player {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Opens the replay at a recording tick (a chain's launch or mark), holding that frame.
|
|
||||||
pub fn seek(&mut self, rec: &Recording, at: f64) {
|
|
||||||
self.t = at.clamp(0.0, rec.len as f64);
|
|
||||||
self.heard = self.t;
|
|
||||||
self.shot = (usize::MAX, 0);
|
|
||||||
self.fade = 0;
|
|
||||||
self.card = 0;
|
|
||||||
self.paused = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The wheel: scrubs the map and the full replay, skips clips.
|
/// The wheel: scrubs the map and the full replay, skips clips.
|
||||||
pub fn wheel(&mut self, steps: f32, rec: &Recording) {
|
pub fn wheel(&mut self, steps: f32, rec: &Recording) {
|
||||||
let c = if steps > 0.0 { Control::Back } else { Control::Forward };
|
let c = if steps > 0.0 { Control::Back } else { Control::Forward };
|
||||||
@@ -596,7 +525,7 @@ impl Player {
|
|||||||
/// Sounds as the camera hears them: moved so the player stands where the camera is.
|
/// Sounds as the camera hears them: moved so the player stands where the camera is.
|
||||||
fn sounds(&mut self, rec: &Recording, listener: DVec3, out: &mut Out) {
|
fn sounds(&mut self, rec: &Recording, listener: DVec3, out: &mut Out) {
|
||||||
let heard = |p: DVec3| listener + (p - self.eye);
|
let heard = |p: DVec3| listener + (p - self.eye);
|
||||||
for (_, e) in rec.events_between(self.heard, self.t) {
|
for e in rec.events.iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) {
|
||||||
let event = match e.kind {
|
let event = match e.kind {
|
||||||
EventKind::Kill { kind, outcome, .. } => crate::sim::outcome::look(kind, outcome).3,
|
EventKind::Kill { kind, outcome, .. } => crate::sim::outcome::look(kind, outcome).3,
|
||||||
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
|
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
|
||||||
@@ -617,7 +546,7 @@ impl Player {
|
|||||||
}
|
}
|
||||||
// New recordings carry the exact launch and ignition sounds and their actual positions.
|
// New recordings carry the exact launch and ignition sounds and their actual positions.
|
||||||
if let Some(scene) = &rec.scene {
|
if let Some(scene) = &rec.scene {
|
||||||
for e in scene.events_between(self.heard, self.t) {
|
for e in scene.events().iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) {
|
||||||
match e.kind {
|
match e.kind {
|
||||||
crate::sim::record::SceneKind::MissileLaunch { sound, pitch, .. } => out.sound(sound, heard(e.pos), 1.0, pitch),
|
crate::sim::record::SceneKind::MissileLaunch { sound, pitch, .. } => out.sound(sound, heard(e.pos), 1.0, pitch),
|
||||||
crate::sim::record::SceneKind::MotorIgnition { sound: Some(sound), .. } => out.sound(sound, heard(e.pos), 1.0, 1.0),
|
crate::sim::record::SceneKind::MotorIgnition { sound: Some(sound), .. } => out.sound(sound, heard(e.pos), 1.0, 1.0),
|
||||||
@@ -844,9 +773,9 @@ impl Player {
|
|||||||
// The full replay follows what comes next: the next event within 6 s, else the drone
|
// The full replay follows what comes next: the next event within 6 s, else the drone
|
||||||
// nearest its target.
|
// nearest its target.
|
||||||
Mode::Full => rec
|
Mode::Full => rec
|
||||||
.events_between(self.t - 30.0, self.t + 120.0)
|
.events
|
||||||
.next()
|
.iter()
|
||||||
.map(|(i, _)| i)
|
.position(|e| (self.t - 30.0..self.t + 120.0).contains(&(e.at as f64)))
|
||||||
.or(if self.shot.0 != usize::MAX && (rec.events[self.shot.0].at as f64) > self.t - 60.0 { Some(self.shot.0) } else { None }),
|
.or(if self.shot.0 != usize::MAX && (rec.events[self.shot.0].at as f64) > self.t - 60.0 { Some(self.shot.0) } else { None }),
|
||||||
Mode::Map | Mode::Film(_) => None,
|
Mode::Map | Mode::Film(_) => None,
|
||||||
};
|
};
|
||||||
@@ -1070,13 +999,29 @@ impl Player {
|
|||||||
s.push(fill(prev.0 - 1.5, prev.1 - 1.5, 3.0, 3.0, head));
|
s.push(fill(prev.0 - 1.5, prev.1 - 1.5, 3.0, 3.0, head));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Events so far, in their order. The header's counts come from the recording's prefix
|
// Events so far.
|
||||||
// index, not from walking the journal again; past the shape cap nothing drawn here
|
for e in rec.events.iter().filter(|e| (e.at as f64) <= self.t) {
|
||||||
// survives `truncate`.
|
let (x, y) = at(e.pos);
|
||||||
s.extend(event_marks(rec, self.t, &at, &inside, 1024usize.saturating_sub(s.len())));
|
if !inside((x, y)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match e.kind {
|
||||||
|
EventKind::Kill { .. } => {
|
||||||
|
s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040));
|
||||||
|
s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040));
|
||||||
|
}
|
||||||
|
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
|
||||||
|
let r = 2.0 + power as f32;
|
||||||
|
s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020));
|
||||||
|
}
|
||||||
|
EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)),
|
||||||
|
EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)),
|
||||||
|
EventKind::Strike { .. } => s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFA040)),
|
||||||
|
}
|
||||||
|
}
|
||||||
// Header, legend, time line.
|
// Header, legend, time line.
|
||||||
let kills = rec.kills_until(self.t);
|
let kills = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Kill { .. })).count();
|
||||||
let hits = rec.hits_until(self.t);
|
let hits = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Hit { .. })).count();
|
||||||
let state = if self.paused { "ПАУЗА".to_string() } else { format!("×{}", self.speed) };
|
let state = if self.paused { "ПАУЗА".to_string() } else { format!("×{}", self.speed) };
|
||||||
s.push(text(format!("КАРТА НАЛЁТА №{} · {} / {} {state} · сбито {kills} · прилётов {hits}", rec.number, clock(self.t), clock(rec.len as f64)), 8.0, 6.0, 0xFF9FE0FF, false));
|
s.push(text(format!("КАРТА НАЛЁТА №{} · {} / {} {state} · сбито {kills} · прилётов {hits}", rec.number, clock(self.t), clock(rec.len as f64)), 8.0, 6.0, 0xFF9FE0FF, false));
|
||||||
let legend = "красный: цели · серый: ложные · жёлтый: перехватчики · x сбит · квадрат: прилёт";
|
let legend = "красный: цели · серый: ложные · жёлтый: перехватчики · x сбит · квадрат: прилёт";
|
||||||
@@ -1095,10 +1040,6 @@ impl Player {
|
|||||||
s.push(fill(tx, ty, tw, 3.0, 0x60FFFFFF));
|
s.push(fill(tx, ty, tw, 3.0, 0x60FFFFFF));
|
||||||
let len = rec.len.max(1) as f32;
|
let len = rec.len.max(1) as f32;
|
||||||
for e in &rec.events {
|
for e in &rec.events {
|
||||||
// The line is cut at 1024 shapes: past that, a mark would not be kept.
|
|
||||||
if s.len() >= 1024 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
let x = tx + tw * e.at as f32 / len;
|
let x = tx + tw * e.at as f32 / len;
|
||||||
let c = match e.kind {
|
let c = match e.kind {
|
||||||
EventKind::Kill { .. } => 0xFFFFE040,
|
EventKind::Kill { .. } => 0xFFFFE040,
|
||||||
@@ -1116,42 +1057,6 @@ impl Player {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The marks of the events up to `t` on the raid map, in the order they happened: a kill as a
|
|
||||||
/// cross, a hit as a square, a lost system as a dark square, a split and a strike as dots. Reads
|
|
||||||
/// the journal by time (`events_until`) and stops at `room` shapes, the rest of the map's cap.
|
|
||||||
fn event_marks(
|
|
||||||
rec: &Recording,
|
|
||||||
t: f64,
|
|
||||||
at: &impl Fn(DVec3) -> (f32, f32),
|
|
||||||
inside: &impl Fn((f32, f32)) -> bool,
|
|
||||||
room: usize,
|
|
||||||
) -> Vec<Shape> {
|
|
||||||
let mut s = Vec::new();
|
|
||||||
for (_, e) in rec.events_until(t) {
|
|
||||||
if s.len() >= room {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
let (x, y) = at(e.pos);
|
|
||||||
if !inside((x, y)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
match e.kind {
|
|
||||||
EventKind::Kill { .. } => {
|
|
||||||
s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040));
|
|
||||||
s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040));
|
|
||||||
}
|
|
||||||
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
|
|
||||||
let r = 2.0 + power as f32;
|
|
||||||
s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020));
|
|
||||||
}
|
|
||||||
EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)),
|
|
||||||
EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)),
|
|
||||||
EventKind::Strike { .. } => s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFA040)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The ground the map shows, as [lo x, lo z, hi x, hi z]: everything that
|
/// The ground the map shows, as [lo x, lo z, hi x, hi z]: everything that
|
||||||
/// flew (not the ballistic falls), with the systems and objects, or round the
|
/// flew (not the ballistic falls), with the systems and objects, or round the
|
||||||
/// origin when nothing did.
|
/// origin when nothing did.
|
||||||
@@ -1197,41 +1102,6 @@ impl Player {
|
|||||||
mod surface_tests {
|
mod surface_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_chain_row_lists_the_measured_steps_and_opens_its_frame() {
|
|
||||||
use crate::sim::record::{Event, SceneEvent, SceneJournal, SceneKind};
|
|
||||||
use crate::sim::outcome::Outcome;
|
|
||||||
use crate::sim::MissileKind;
|
|
||||||
let mut rec = Recording::blank(300);
|
|
||||||
rec.sams = vec![(10, crate::sim::SamKind::Pantsir, DVec3::ZERO)];
|
|
||||||
rec.straight(7, What::Drone(DroneKind::Shahed), 0, 200, DVec3::new(0.0, 80.0, 0.0), DVec3::new(200.0, 80.0, 0.0));
|
|
||||||
let mut scene = SceneJournal::default();
|
|
||||||
let at = |at: u32, kind| SceneEvent { at, pos: DVec3::ZERO, kind };
|
|
||||||
scene.fixture_push(at(20, SceneKind::TrackAcquired { sam: 10, target: 7, ever_own: false }));
|
|
||||||
scene.fixture_push(at(30, SceneKind::TrackSource { sam: 10, target: 7, ever_own: true }));
|
|
||||||
scene.fixture_push(at(40, SceneKind::TrackLock { sam: 10, target: 7, locked: true }));
|
|
||||||
scene.fixture_push(at(50, SceneKind::MissileLaunch { missile: 500, sam: 10, target: 7, kind: MissileKind::M57e6, sound: "airdef:launch.pantsir", pitch: 1.0 }));
|
|
||||||
rec.scene = Some(scene);
|
|
||||||
rec.events.push(Event {
|
|
||||||
at: 90,
|
|
||||||
pos: DVec3::ZERO,
|
|
||||||
kind: EventKind::Kill { drone: 7, kind: DroneKind::Shahed, sam: 10, sam_kind: crate::sim::SamKind::Pantsir, sam_index: 0, missile: Some(500), outcome: Outcome::DisabledFalling },
|
|
||||||
});
|
|
||||||
let rows = chain_rows(&rec, None);
|
|
||||||
assert_eq!(rows.len(), 1);
|
|
||||||
for step in ["отметка", "передача", "захват", "пуск", "сбит"] {
|
|
||||||
assert!(rows[0].text.contains(step), "the chain row misses {step}: {}", rows[0].text);
|
|
||||||
}
|
|
||||||
assert_eq!(rows[0].event, Some(0));
|
|
||||||
assert!(chain_rows(&rec, Some(10)).len() == 1);
|
|
||||||
assert!(chain_rows(&rec, Some(11)).is_empty());
|
|
||||||
// A chain with no recorded outcome opens its launch frame on the map, held still.
|
|
||||||
let mut player = Player::new(1, Mode::Map, &Sim::new(1));
|
|
||||||
player.seek(&rec, rows[0].at);
|
|
||||||
assert!(player.paused);
|
|
||||||
assert!((player.time() - rows[0].at).abs() < 1e-9);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A gun standing on the sea floor films from above the water, not from under it.
|
/// A gun standing on the sea floor films from above the water, not from under it.
|
||||||
#[test]
|
#[test]
|
||||||
fn the_gun_camera_is_lifted_above_the_water() {
|
fn the_gun_camera_is_lifted_above_the_water() {
|
||||||
@@ -1456,90 +1326,6 @@ mod engine_tests {
|
|||||||
assert!(host.0.is_empty());
|
assert!(host.0.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
// #150: the sounds of a window are exactly the events it holds: the same set, order and
|
|
||||||
// names after any seek, forward or back, empty or spanning ties.
|
|
||||||
#[test]
|
|
||||||
fn event_sounds_are_exactly_the_events_of_the_window_after_any_seek() {
|
|
||||||
use crate::sim::catalog::sound;
|
|
||||||
use crate::sim::record::{Event, EventKind};
|
|
||||||
let mut rec = Recording::blank(1000);
|
|
||||||
rec.events = [10u32, 10, 25, 40, 40, 40, 75, 130]
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(i, at)| Event {
|
|
||||||
at,
|
|
||||||
pos: DVec3::new(i as f64, 80.0, 0.0),
|
|
||||||
kind: EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: (i % 5) as u32 },
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let names = |lo: f64, hi: f64| -> Vec<&'static str> {
|
|
||||||
rec.events
|
|
||||||
.iter()
|
|
||||||
.filter(|e| (lo..hi).contains(&(e.at as f64)))
|
|
||||||
.map(|e| match e.kind {
|
|
||||||
EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
|
|
||||||
_ => unreachable!(),
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
let mut p = player(&rec);
|
|
||||||
let mut out = Out::default();
|
|
||||||
for &(heard, t) in &[(0.0, 11.0), (10.0, 10.0), (11.0, 25.0), (10.0, 40.0), (25.0, 40.5), (40.0, 41.0), (40.0, 75.0), (75.0, 130.5), (130.0, 0.0), (41.0, 25.0), (10.5, 40.0)] {
|
|
||||||
out.sounds.clear();
|
|
||||||
p.heard = heard;
|
|
||||||
p.t = t;
|
|
||||||
p.sounds(&rec, DVec3::ZERO, &mut out);
|
|
||||||
let got: Vec<&'static str> = out.sounds.iter().map(|s| s.0).collect();
|
|
||||||
assert_eq!(got, names(heard, t), "{heard}..{t}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// #150: the map draws every event up to now, in its order, and reads only that far.
|
|
||||||
#[test]
|
|
||||||
fn the_map_marks_the_events_up_to_now_in_their_order() {
|
|
||||||
use crate::sim::record::{Event, EventKind, StrikeResult};
|
|
||||||
let ev = |at, kind| Event { at, pos: DVec3::new(at as f64, 0.0, 0.0), kind };
|
|
||||||
let mut rec = Recording::blank(1000);
|
|
||||||
rec.events = vec![
|
|
||||||
ev(100, EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 1, sam_kind: crate::sim::SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() }),
|
|
||||||
ev(200, EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power: 2, object: None, sam: None }),
|
|
||||||
ev(300, EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: 1 }),
|
|
||||||
ev(400, EventKind::SamLost { sam: 1, kind: crate::sim::SamKind::S400, index: 0 }),
|
|
||||||
ev(500, EventKind::Split { drone: 1 }),
|
|
||||||
ev(600, EventKind::Strike { site: 1, result: StrikeResult::Stunned }),
|
|
||||||
ev(900, EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 1, sam_kind: crate::sim::SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() }),
|
|
||||||
];
|
|
||||||
rec.close();
|
|
||||||
let at = |p: DVec3| (p.x as f32, 0.0);
|
|
||||||
let all = |_: (f32, f32)| true;
|
|
||||||
let colors = |shapes: Vec<Shape>| shapes
|
|
||||||
.iter()
|
|
||||||
.map(|s| match s {
|
|
||||||
Shape::Fill(f) => f.color,
|
|
||||||
Shape::Quad(q) => q.color,
|
|
||||||
_ => 0,
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
// The kill's cross, then the hit, the crash, the lost system and the split: the earlier
|
|
||||||
// events only, in their order.
|
|
||||||
assert_eq!(
|
|
||||||
colors(event_marks(&rec, 500.0, &at, &all, usize::MAX)),
|
|
||||||
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020, 0xB0FF3020, 0xFF200000, 0xFFFF9020]
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
colors(event_marks(&rec, 600.0, &at, &all, usize::MAX)),
|
|
||||||
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020, 0xB0FF3020, 0xFF200000, 0xFFFF9020, 0xFFFFA040]
|
|
||||||
);
|
|
||||||
// The map's shape cap stops the reading; nothing past it would be kept anyway.
|
|
||||||
assert_eq!(event_marks(&rec, 600.0, &at, &all, 3).len(), 3);
|
|
||||||
// What lies outside the map is skipped, the rest keeps its order.
|
|
||||||
let left = |(x, _): (f32, f32)| x < 250.0;
|
|
||||||
assert_eq!(
|
|
||||||
colors(event_marks(&rec, 600.0, &at, &left, usize::MAX)),
|
|
||||||
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_fast_replay_is_silent() {
|
fn a_fast_replay_is_silent() {
|
||||||
let rec = recording();
|
let rec = recording();
|
||||||
|
|||||||
@@ -403,7 +403,7 @@ impl Sim {
|
|||||||
);
|
);
|
||||||
for l in &s.pending {
|
for l in &s.pending {
|
||||||
body += &format!(
|
body += &format!(
|
||||||
"airrecobs {} {} {} {} {} {} {} {} {} {} {}\n",
|
"airrecobs {} {} {} {} {} {} {} {} {} {}\n",
|
||||||
l.truth,
|
l.truth,
|
||||||
coord(l.area.x),
|
coord(l.area.x),
|
||||||
coord(l.area.y),
|
coord(l.area.y),
|
||||||
@@ -414,7 +414,6 @@ impl Sim {
|
|||||||
l.quality.name(),
|
l.quality.name(),
|
||||||
l.source.name(),
|
l.source.name(),
|
||||||
l.observed,
|
l.observed,
|
||||||
l.wreck,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
for z in &s.zones {
|
for z in &s.zones {
|
||||||
@@ -716,8 +715,8 @@ impl Sim {
|
|||||||
recon_expect.push((pending, zones));
|
recon_expect.push((pending, zones));
|
||||||
}
|
}
|
||||||
"airrecobs" => {
|
"airrecobs" => {
|
||||||
if w.len() != 11 && w.len() != 12 {
|
if w.len() != 11 {
|
||||||
return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник, такт и признак остова"));
|
return Err(l.bad("наблюдение разведки", "нужны юнит, место, категория, источник и такт"));
|
||||||
}
|
}
|
||||||
let Some(at) = recon_sortie_at else {
|
let Some(at) = recon_sortie_at else {
|
||||||
return Err(l.bad("наблюдение разведки", "строка без разведчика"));
|
return Err(l.bad("наблюдение разведки", "строка без разведчика"));
|
||||||
@@ -740,10 +739,7 @@ impl Sim {
|
|||||||
let quality = recon::Quality::from_key(l.word(8, "качество")?).ok_or_else(|| l.bad("качество", "coarse или refined"))?;
|
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 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;
|
let observed = l.int(10, "такт наблюдения", 0, tick as i64)? as u64;
|
||||||
// An older save has no wreck flag: every pending look it holds is of a unit
|
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed });
|
||||||
// that was alive when it was seen.
|
|
||||||
let wreck = if w.len() > 11 { l.flag(11, "остов")? } else { false };
|
|
||||||
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed, wreck });
|
|
||||||
}
|
}
|
||||||
"airreczone" => {
|
"airreczone" => {
|
||||||
if w.len() != 5 {
|
if w.len() != 5 {
|
||||||
|
|||||||
@@ -1416,8 +1416,6 @@ pub struct Sim {
|
|||||||
/// The next blast's id (separate from `next`, so the other units' ids stay as they were).
|
/// The next blast's id (separate from `next`, so the other units' ids stay as they were).
|
||||||
blast_seq: u32,
|
blast_seq: u32,
|
||||||
next: u32,
|
next: u32,
|
||||||
/// The optical probe sequence: a ready post is served oldest-probe first (fair queue, #138).
|
|
||||||
optical_seq: u64,
|
|
||||||
/// The combat randomness: what is rolled for aim, hits, damage and raids. Drawing, sound and camera never
|
/// The combat randomness: what is rolled for aim, hits, damage and raids. Drawing, sound and camera never
|
||||||
/// spend it (#85).
|
/// spend it (#85).
|
||||||
pub rng: Rng,
|
pub rng: Rng,
|
||||||
@@ -1531,7 +1529,6 @@ impl Sim {
|
|||||||
blasts: Vec::new(),
|
blasts: Vec::new(),
|
||||||
blast_seq: 0,
|
blast_seq: 0,
|
||||||
next: 1,
|
next: 1,
|
||||||
optical_seq: 0,
|
|
||||||
rng: Rng::new(seed),
|
rng: Rng::new(seed),
|
||||||
vis: Rng::new(seed ^ 0x5DEE_CE66_D1CE_4E5B),
|
vis: Rng::new(seed ^ 0x5DEE_CE66_D1CE_4E5B),
|
||||||
fx_next: 0,
|
fx_next: 0,
|
||||||
|
|||||||
+38
-239
@@ -16,12 +16,6 @@
|
|||||||
//! mode in this first version. Weather/fog is not in the simulation API yet, so only the game's own
|
//! mode in this first version. Weather/fog is not in the simulation API yet, so only the game's own
|
||||||
//! day/night state and the world geometry are used here.
|
//! day/night state and the world geometry are used here.
|
||||||
//!
|
//!
|
||||||
//! An automatic contact is kept while it is within the optics' own reach; after a few failed probes
|
|
||||||
//! it is let go and not picked again for a while, so a visible alternative can be tried without the
|
|
||||||
//! post thrashing between hopeless contacts. A player's explicit command is different: it waits
|
|
||||||
//! until the player changes it, and the status says so. Ready posts are served oldest-probe first,
|
|
||||||
//! so posts whose phases coincide all get their turn under the same per-tick probe budget.
|
|
||||||
//!
|
|
||||||
//! #133 owns the shared class-estimate contract. The observation stays an independent
|
//! #133 owns the shared class-estimate contract. The observation stays an independent
|
||||||
//! [`OpticalObservation`] — never a [`Track`] — and the explicit adapter [`Sim::apply_optical_classes`]
|
//! [`OpticalObservation`] — never a [`Track`] — and the explicit adapter [`Sim::apply_optical_classes`]
|
||||||
//! feeds its [`OpticalClassEstimate`] into the class of the network's existing tracks through
|
//! feeds its [`OpticalClassEstimate`] into the class of the network's existing tracks through
|
||||||
@@ -54,14 +48,6 @@ const LOCAL_CANDIDATES: usize = 8;
|
|||||||
const TERRAIN_SAMPLES: usize = 6;
|
const TERRAIN_SAMPLES: usize = 6;
|
||||||
/// A relayed track older than this is not worth turning the head for.
|
/// A relayed track older than this is not worth turning the head for.
|
||||||
const CUE_MAX_AGE: u64 = 120;
|
const CUE_MAX_AGE: u64 = 120;
|
||||||
/// Consecutive failed probes before an automatic contact is let go.
|
|
||||||
const MISS_LIMIT: u32 = 3;
|
|
||||||
/// Unknown world geometry is a wait, not a verdict: it takes longer to let a contact go.
|
|
||||||
const UNKNOWN_LIMIT: u32 = 8;
|
|
||||||
/// Ticks a contact let go after failures is not picked again (no constant switching).
|
|
||||||
const RETRY_AFTER: u64 = PERIOD * 20;
|
|
||||||
/// Let-go contacts remembered at once.
|
|
||||||
const AVOID_MAX: usize = 8;
|
|
||||||
|
|
||||||
/// What the post is doing, in the words the map and monitor use.
|
/// What the post is doing, in the words the map and monitor use.
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
|
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
|
||||||
@@ -206,12 +192,6 @@ pub struct Optical {
|
|||||||
/// The freshest relayed track: a direction to look, never a measurement and never a track.
|
/// The freshest relayed track: a direction to look, never a measurement and never a track.
|
||||||
cue: Option<Track>,
|
cue: Option<Track>,
|
||||||
checks: u64,
|
checks: u64,
|
||||||
/// Consecutive failed probes of the current automatic contact.
|
|
||||||
misses: u32,
|
|
||||||
/// Automatic contacts let go after failures: not picked again before the tick (anti-thrash).
|
|
||||||
avoid: Vec<(u32, u64)>,
|
|
||||||
/// The probe sequence number this post was last served at: the fair queue serves the oldest.
|
|
||||||
served: Option<u64>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Optical {
|
impl Optical {
|
||||||
@@ -258,7 +238,6 @@ impl Optical {
|
|||||||
fn clear_activity(&mut self) {
|
fn clear_activity(&mut self) {
|
||||||
self.target = None;
|
self.target = None;
|
||||||
self.held = 0;
|
self.held = 0;
|
||||||
self.misses = 0;
|
|
||||||
self.state = OpticalState::Searching;
|
self.state = OpticalState::Searching;
|
||||||
self.block = None;
|
self.block = None;
|
||||||
}
|
}
|
||||||
@@ -266,7 +245,6 @@ impl Optical {
|
|||||||
self.target = None;
|
self.target = None;
|
||||||
self.commanded = None;
|
self.commanded = None;
|
||||||
self.held = 0;
|
self.held = 0;
|
||||||
self.misses = 0;
|
|
||||||
self.observations = 0;
|
self.observations = 0;
|
||||||
self.seen = None;
|
self.seen = None;
|
||||||
self.state = OpticalState::Searching;
|
self.state = OpticalState::Searching;
|
||||||
@@ -275,42 +253,18 @@ impl Optical {
|
|||||||
fn select(&mut self, id: Option<u32>) {
|
fn select(&mut self, id: Option<u32>) {
|
||||||
if self.target != id {
|
if self.target != id {
|
||||||
self.held = 0;
|
self.held = 0;
|
||||||
self.misses = 0;
|
self.observations = 0;
|
||||||
self.seen = None;
|
self.seen = None;
|
||||||
// The old picture belongs to the old contact: it must not be read as this one's. Letting
|
// The old picture belongs to the old contact: it must not be read as this one's.
|
||||||
// the contact go (None) or picking the same one again keeps it: it is a record and ages.
|
self.observation = None;
|
||||||
if let Some(id) = id {
|
|
||||||
if !self.observation.is_some_and(|o| o.target == id) {
|
|
||||||
self.observations = 0;
|
|
||||||
self.observation = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
self.target = id;
|
self.target = id;
|
||||||
self.block = None;
|
self.block = None;
|
||||||
self.state = if id.is_some() { OpticalState::Holding } else { OpticalState::Searching };
|
self.state = if id.is_some() { OpticalState::Holding } else { OpticalState::Searching };
|
||||||
}
|
}
|
||||||
fn avoided(&self, id: u32, now: u64) -> bool {
|
|
||||||
self.avoid.iter().any(|&(other, until)| other == id && until > now)
|
|
||||||
}
|
|
||||||
/// Let an automatic contact go after its failed probes and keep it out of the next picks for a
|
|
||||||
/// while, so the post can try a visible alternative instead of thrashing on this one.
|
|
||||||
fn release(&mut self, id: u32, now: u64) {
|
|
||||||
self.target = None;
|
|
||||||
self.held = 0;
|
|
||||||
self.misses = 0;
|
|
||||||
self.state = OpticalState::Searching;
|
|
||||||
self.block = None;
|
|
||||||
self.seen = None;
|
|
||||||
self.avoid.retain(|&(_, until)| until > now);
|
|
||||||
self.avoid.push((id, now + RETRY_AFTER));
|
|
||||||
if self.avoid.len() > AVOID_MAX {
|
|
||||||
self.avoid.remove(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/// A short line for the panel and the monitor: status, class and uncertainty, never a model name.
|
/// A short line for the panel and the monitor: status, class and uncertainty, never a model name.
|
||||||
pub fn status_text(&self) -> String {
|
pub fn status_text(&self) -> String {
|
||||||
let body = match self.state {
|
match self.state {
|
||||||
OpticalState::Searching => "ищет".into(),
|
OpticalState::Searching => "ищет".into(),
|
||||||
OpticalState::Holding => "занят: удерживает контакт".into(),
|
OpticalState::Holding => "занят: удерживает контакт".into(),
|
||||||
OpticalState::Observing => match self.observation {
|
OpticalState::Observing => match self.observation {
|
||||||
@@ -321,8 +275,7 @@ impl Optical {
|
|||||||
Some(b) => format!("нет видимости: {}", b.name()),
|
Some(b) => format!("нет видимости: {}", b.name()),
|
||||||
None => "нет видимости".into(),
|
None => "нет видимости".into(),
|
||||||
},
|
},
|
||||||
};
|
}
|
||||||
if self.commanded.is_some() { format!("по команде: {body}") } else { body }
|
|
||||||
}
|
}
|
||||||
fn report(&self, post: u32, index: usize, now: u64, night: bool) -> OpticalReport {
|
fn report(&self, post: u32, index: usize, now: u64, night: bool) -> OpticalReport {
|
||||||
OpticalReport {
|
OpticalReport {
|
||||||
@@ -337,7 +290,6 @@ impl Optical {
|
|||||||
required: self.required(night),
|
required: self.required(night),
|
||||||
seen: self.seen(now).map(|(_, p)| p),
|
seen: self.seen(now).map(|(_, p)| p),
|
||||||
checks: self.checks,
|
checks: self.checks,
|
||||||
commanded: self.commanded,
|
|
||||||
night,
|
night,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -353,8 +305,6 @@ pub struct OpticalReport {
|
|||||||
pub state: OpticalState,
|
pub state: OpticalState,
|
||||||
pub block: Option<SightBlock>,
|
pub block: Option<SightBlock>,
|
||||||
pub target: Option<u32>,
|
pub target: Option<u32>,
|
||||||
/// The contact the player has pinned, if any: the post waits for it until the command changes.
|
|
||||||
pub commanded: Option<u32>,
|
|
||||||
pub observation: Option<OpticalObservation>,
|
pub observation: Option<OpticalObservation>,
|
||||||
pub observations: u32,
|
pub observations: u32,
|
||||||
pub held: u32,
|
pub held: u32,
|
||||||
@@ -374,7 +324,7 @@ impl OpticalReport {
|
|||||||
format!("оптический пост №{}", self.index)
|
format!("оптический пост №{}", self.index)
|
||||||
}
|
}
|
||||||
pub fn line(&self) -> String {
|
pub fn line(&self) -> String {
|
||||||
let body = match self.state {
|
match self.state {
|
||||||
OpticalState::Searching => "ищет".into(),
|
OpticalState::Searching => "ищет".into(),
|
||||||
OpticalState::Holding => format!("занят: удерживает контакт {}/{}", self.held, self.required),
|
OpticalState::Holding => format!("занят: удерживает контакт {}/{}", self.held, self.required),
|
||||||
OpticalState::Observing => match self.observation {
|
OpticalState::Observing => match self.observation {
|
||||||
@@ -390,8 +340,7 @@ impl OpticalReport {
|
|||||||
Some(b) => format!("нет видимости: {}", b.name()),
|
Some(b) => format!("нет видимости: {}", b.name()),
|
||||||
None => "нет видимости".into(),
|
None => "нет видимости".into(),
|
||||||
},
|
},
|
||||||
};
|
}
|
||||||
if self.commanded.is_some() { format!("по команде: {body}") } else { body }
|
|
||||||
}
|
}
|
||||||
/// The observation's age, if it has one; an old observation only ages.
|
/// The observation's age, if it has one; an old observation only ages.
|
||||||
pub fn age(&self, now: u64) -> Option<u64> {
|
pub fn age(&self, now: u64) -> Option<u64> {
|
||||||
@@ -428,7 +377,6 @@ impl Sim {
|
|||||||
if sam.optical.target != target {
|
if sam.optical.target != target {
|
||||||
sam.optical.target = None;
|
sam.optical.target = None;
|
||||||
sam.optical.held = 0;
|
sam.optical.held = 0;
|
||||||
sam.optical.misses = 0;
|
|
||||||
sam.optical.observations = 0;
|
sam.optical.observations = 0;
|
||||||
sam.optical.seen = None;
|
sam.optical.seen = None;
|
||||||
// An explicit switch drops the old contact's picture; it was never this contact's.
|
// An explicit switch drops the old contact's picture; it was never this contact's.
|
||||||
@@ -439,39 +387,33 @@ impl Sim {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The post's own pick: a manual command, the contact it already holds, a cue within reach or
|
/// The post's own pick: a manual/network cue first, then its narrow near sector. At most one contact.
|
||||||
/// the near sector, and only then a far cue that merely points the head. At most one contact.
|
|
||||||
fn optical_target(&self, i: usize, now: u64, alive: &std::collections::HashSet<u32>) -> Option<u32> {
|
fn optical_target(&self, i: usize, now: u64, alive: &std::collections::HashSet<u32>) -> Option<u32> {
|
||||||
let sam = &self.sams[i];
|
let sam = &self.sams[i];
|
||||||
let optical = &sam.optical;
|
let optical = &sam.optical;
|
||||||
let alive = |id: u32| alive.contains(&id);
|
let alive = |id: u32| alive.contains(&id);
|
||||||
// A player's command keeps its contact until the command changes, reachable or not.
|
|
||||||
if let Some(id) = optical.commanded() {
|
if let Some(id) = optical.commanded() {
|
||||||
if alive(id) {
|
if alive(id) {
|
||||||
return Some(id);
|
return Some(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Keep the current contact while it is still within the optics' own reach: observations
|
if let Some(id) = optical.target() {
|
||||||
// accumulate instead of the post hopping between equally good contacts.
|
if let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive()) {
|
||||||
if let Some(id) = optical.target()
|
if d.pos.distance(sam.pos) <= CUE_RANGE {
|
||||||
&& alive(id)
|
return Some(id);
|
||||||
&& !optical.avoided(id, now)
|
}
|
||||||
&& let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive())
|
}
|
||||||
&& d.pos.distance(sam.pos) <= RANGE
|
|
||||||
{
|
|
||||||
return Some(id);
|
|
||||||
}
|
}
|
||||||
// A cue within reach is a known contact: the head turns to it and the post measures it itself.
|
// The network's freshest cue: the post measures it itself, the relay only points the head.
|
||||||
if let Some(t) = optical.cue()
|
if let Some(t) = optical.cue()
|
||||||
&& t.age(now) <= CUE_MAX_AGE
|
&& t.age(now) <= CUE_MAX_AGE
|
||||||
&& alive(t.id)
|
&& alive(t.id)
|
||||||
&& !optical.avoided(t.id, now)
|
&& t.est(now).distance(sam.pos) <= CUE_RANGE
|
||||||
&& t.est(now).distance(sam.pos) <= RANGE
|
|
||||||
{
|
{
|
||||||
return Some(t.id);
|
return Some(t.id);
|
||||||
}
|
}
|
||||||
// Search a narrow near sector, nearest first, comparing no more than a few. The sector is
|
// Nothing cued: search a narrow near sector, nearest first, comparing no more than a few.
|
||||||
// the head's (`dish`, which turns while it searches), not the base's heading.
|
// The sector is the head's (`dish`, which turns while it searches), not the base's heading.
|
||||||
let mut local: Vec<(f64, u32)> = self
|
let mut local: Vec<(f64, u32)> = self
|
||||||
.drones
|
.drones
|
||||||
.iter()
|
.iter()
|
||||||
@@ -479,7 +421,7 @@ impl Sim {
|
|||||||
.filter_map(|d| {
|
.filter_map(|d| {
|
||||||
let rel = d.pos - sam.pos;
|
let rel = d.pos - sam.pos;
|
||||||
let dist = rel.length();
|
let dist = rel.length();
|
||||||
if dist > RANGE || optical.avoided(d.id, now) {
|
if dist > RANGE {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let bearing = heading_of(rel);
|
let bearing = heading_of(rel);
|
||||||
@@ -488,19 +430,7 @@ impl Sim {
|
|||||||
.collect();
|
.collect();
|
||||||
local.sort_by(|a, b| a.0.total_cmp(&b.0));
|
local.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||||
local.truncate(LOCAL_CANDIDATES);
|
local.truncate(LOCAL_CANDIDATES);
|
||||||
if let Some(&(_, id)) = local.first() {
|
local.first().map(|&(_, id)| id)
|
||||||
return Some(id);
|
|
||||||
}
|
|
||||||
// A far cue points the head but never displaces a visible local contact above.
|
|
||||||
if let Some(t) = optical.cue()
|
|
||||||
&& t.age(now) <= CUE_MAX_AGE
|
|
||||||
&& alive(t.id)
|
|
||||||
&& !optical.avoided(t.id, now)
|
|
||||||
&& t.est(now).distance(sam.pos) <= CUE_RANGE
|
|
||||||
{
|
|
||||||
return Some(t.id);
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One tick of every optical post: age state, then spend the bounded line-of-sight budget.
|
/// One tick of every optical post: age state, then spend the bounded line-of-sight budget.
|
||||||
@@ -551,31 +481,22 @@ impl Sim {
|
|||||||
sam.dish = (sam.dish + 0.02) % TAU;
|
sam.dish = (sam.dish + 0.02) % TAU;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// A fair queue over the posts ready this tick: the post probed longest ago goes first, so
|
// Fair round-robin: a crowd of posts does not starve the last ones for ever.
|
||||||
// posts whose phases coincide all get their turn. The per-tick probe budget still caps work.
|
let start = (now as usize) % posts.len();
|
||||||
let mut ready: Vec<usize> = posts
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.filter(|&i| {
|
|
||||||
let sam = &self.sams[i];
|
|
||||||
sam.alive()
|
|
||||||
&& !sam.moving()
|
|
||||||
&& sam.part(Part::Sensor) > 0.0
|
|
||||||
&& now % PERIOD == (sam.id / PARTS) as u64 % PERIOD
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
ready.sort_by(|&a, &b| {
|
|
||||||
self.sams[a]
|
|
||||||
.optical
|
|
||||||
.served
|
|
||||||
.cmp(&self.sams[b].optical.served)
|
|
||||||
.then(self.sams[a].id.cmp(&self.sams[b].id))
|
|
||||||
});
|
|
||||||
let mut checks = 0usize;
|
let mut checks = 0usize;
|
||||||
for i in ready {
|
for k in 0..posts.len() {
|
||||||
if checks >= CHECKS_PER_TICK {
|
if checks >= CHECKS_PER_TICK {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
let i = posts[(start + k) % posts.len()];
|
||||||
|
// A dead, moving or blinded post spends none of the tick's probe budget.
|
||||||
|
if !self.sams[i].alive() || self.sams[i].moving() || self.sams[i].part(Part::Sensor) <= 0.0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let phase = (self.sams[i].id / PARTS) as u64 % PERIOD;
|
||||||
|
if now % PERIOD != phase {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let Some(target) = self.optical_target(i, now, &alive) else {
|
let Some(target) = self.optical_target(i, now, &alive) else {
|
||||||
self.sams[i].optical.select(None);
|
self.sams[i].optical.select(None);
|
||||||
continue;
|
continue;
|
||||||
@@ -595,14 +516,10 @@ impl Sim {
|
|||||||
let night = self.night;
|
let night = self.night;
|
||||||
let sight = line_of_sight(ground, from, to, now, range, night);
|
let sight = line_of_sight(ground, from, to, now, range, night);
|
||||||
checks += 1;
|
checks += 1;
|
||||||
self.optical_seq = self.optical_seq.wrapping_add(1);
|
|
||||||
let seq = self.optical_seq;
|
|
||||||
let sam = &mut self.sams[i];
|
let sam = &mut self.sams[i];
|
||||||
sam.optical.checks += 1;
|
sam.optical.checks += 1;
|
||||||
sam.optical.served = Some(seq);
|
|
||||||
match sight {
|
match sight {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
sam.optical.misses = 0;
|
|
||||||
sam.optical.block = None;
|
sam.optical.block = None;
|
||||||
sam.optical.seen = Some((target, d.pos, d.vel, now));
|
sam.optical.seen = Some((target, d.pos, d.vel, now));
|
||||||
sam.optical.held = sam.optical.held.saturating_add(1);
|
sam.optical.held = sam.optical.held.saturating_add(1);
|
||||||
@@ -637,19 +554,11 @@ impl Sim {
|
|||||||
sam.optical.held = 0;
|
sam.optical.held = 0;
|
||||||
sam.optical.block = Some(block);
|
sam.optical.block = Some(block);
|
||||||
sam.optical.state = OpticalState::NoSight;
|
sam.optical.state = OpticalState::NoSight;
|
||||||
// A player's pin waits for the player. An automatic contact that keeps failing
|
|
||||||
// is let go, then left out of the picks for a while so an alternative can win.
|
|
||||||
if sam.optical.commanded().is_none() {
|
|
||||||
sam.optical.misses = sam.optical.misses.saturating_add(1);
|
|
||||||
let limit = if block == SightBlock::UnknownGeometry { UNKNOWN_LIMIT } else { MISS_LIMIT };
|
|
||||||
if sam.optical.misses >= limit {
|
|
||||||
sam.optical.release(target, now);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// The post's own state is `OpticalState`: it never claims a fire-control track.
|
// The post's own state is `OpticalState`: it never claims a fire-control track.
|
||||||
sam.state = SamState::Search;
|
sam.state = SamState::Search;
|
||||||
|
sam.optical.target = Some(target);
|
||||||
}
|
}
|
||||||
self.apply_optical_classes();
|
self.apply_optical_classes();
|
||||||
}
|
}
|
||||||
@@ -798,8 +707,7 @@ mod tests {
|
|||||||
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
|
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
|
||||||
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -200.0), DVec3::new(0.5, 0.0, -0.6));
|
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -200.0), DVec3::new(0.5, 0.0, -0.6));
|
||||||
let mut ground = clear_ground();
|
let mut ground = clear_ground();
|
||||||
// Two night probes: beyond the reduced reach, before the post lets the contact go.
|
run(&mut sim, &mut ground, 200);
|
||||||
run(&mut sim, &mut ground, 2 * PERIOD);
|
|
||||||
let r = sim.optical_report(post).unwrap();
|
let r = sim.optical_report(post).unwrap();
|
||||||
assert_eq!(r.state, OpticalState::NoSight);
|
assert_eq!(r.state, OpticalState::NoSight);
|
||||||
assert_eq!(r.block, Some(SightBlock::Night));
|
assert_eq!(r.block, Some(SightBlock::Night));
|
||||||
@@ -826,17 +734,11 @@ mod tests {
|
|||||||
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6));
|
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6));
|
||||||
let mut ground = clear_ground();
|
let mut ground = clear_ground();
|
||||||
ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -4), fill: world::Fill::Full }], 0);
|
ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -4), fill: world::Fill::Full }], 0);
|
||||||
run(&mut sim, &mut ground, 2 * PERIOD);
|
run(&mut sim, &mut ground, 200);
|
||||||
let r = sim.optical_report(post).unwrap();
|
let r = sim.optical_report(post).unwrap();
|
||||||
assert_eq!(r.state, OpticalState::NoSight);
|
assert_eq!(r.state, OpticalState::NoSight);
|
||||||
assert_eq!(r.block, Some(SightBlock::Obstacle));
|
assert_eq!(r.block, Some(SightBlock::Obstacle));
|
||||||
assert!(r.observation.is_none());
|
assert!(r.observation.is_none());
|
||||||
// With no alternative the post lets the blocked contact go after its failed probes; it does
|
|
||||||
// not sit on it for ever, and it may try again only after the retry delay.
|
|
||||||
run(&mut sim, &mut ground, MISS_LIMIT as u64 * PERIOD + 2);
|
|
||||||
let r = sim.optical_report(post).unwrap();
|
|
||||||
assert_eq!(r.target, None);
|
|
||||||
assert_eq!(r.state, OpticalState::Searching);
|
|
||||||
|
|
||||||
// The same clear land and sky, but no answered sections: unknown, not clear.
|
// The same clear land and sky, but no answered sections: unknown, not clear.
|
||||||
let mut unknown = Sim::new(5);
|
let mut unknown = Sim::new(5);
|
||||||
@@ -850,15 +752,10 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
ground.answer(cols, 0);
|
ground.answer(cols, 0);
|
||||||
run(&mut unknown, &mut ground, 2 * PERIOD);
|
run(&mut unknown, &mut ground, 200);
|
||||||
let r = unknown.optical_report(post).unwrap();
|
let r = unknown.optical_report(post).unwrap();
|
||||||
assert_eq!(r.block, Some(SightBlock::UnknownGeometry));
|
assert_eq!(r.block, Some(SightBlock::UnknownGeometry));
|
||||||
assert!(r.observation.is_none());
|
assert!(r.observation.is_none());
|
||||||
// Waiting for the world is bounded too: the unknown line is not an eternal block.
|
|
||||||
run(&mut unknown, &mut ground, UNKNOWN_LIMIT as u64 * PERIOD + 2);
|
|
||||||
let r = unknown.optical_report(post).unwrap();
|
|
||||||
assert_eq!(r.target, None);
|
|
||||||
assert_eq!(r.state, OpticalState::Searching);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Once the view is lost, the old observation only ages: no new observation is invented.
|
// Once the view is lost, the old observation only ages: no new observation is invented.
|
||||||
@@ -872,20 +769,13 @@ mod tests {
|
|||||||
let first = sim.optical_report(post).unwrap().observation.expect("no day observation");
|
let first = sim.optical_report(post).unwrap().observation.expect("no day observation");
|
||||||
let count = sim.optical_report(post).unwrap().observations;
|
let count = sim.optical_report(post).unwrap().observations;
|
||||||
sim.night = true;
|
sim.night = true;
|
||||||
// The first night probes fail: the old picture is not refreshed.
|
|
||||||
run(&mut sim, &mut ground, 2 * PERIOD);
|
|
||||||
let mid = sim.optical_report(post).unwrap();
|
|
||||||
assert_eq!(mid.state, OpticalState::NoSight);
|
|
||||||
assert_eq!(mid.block, Some(SightBlock::Night));
|
|
||||||
assert_eq!(mid.observation.unwrap().tick, first.tick);
|
|
||||||
// The post lets the contact go and only rechecks it now and then; the old observation ages.
|
|
||||||
run(&mut sim, &mut ground, 300);
|
run(&mut sim, &mut ground, 300);
|
||||||
let r = sim.optical_report(post).unwrap();
|
let r = sim.optical_report(post).unwrap();
|
||||||
let last = r.observation.expect("the old observation was thrown away");
|
let last = r.observation.expect("the old observation was thrown away");
|
||||||
assert_eq!(last.tick, first.tick, "a new observation was invented while the view was lost");
|
assert_eq!(last.tick, first.tick, "a new observation was invented while the view was lost");
|
||||||
assert_eq!(r.observations, count);
|
assert_eq!(r.observations, count);
|
||||||
assert!(last.age(sim.tick) > 200);
|
assert!(last.age(sim.tick) > 200);
|
||||||
assert_ne!(r.state, OpticalState::Observing);
|
assert_eq!(r.state, OpticalState::NoSight);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The class comes from observable motion, never from DroneKind: two true models with the same
|
// The class comes from observable motion, never from DroneKind: two true models with the same
|
||||||
@@ -951,17 +841,12 @@ mod tests {
|
|||||||
});
|
});
|
||||||
let mut ground = clear_ground();
|
let mut ground = clear_ground();
|
||||||
// The cue is fresh only for its `CUE_MAX_AGE`; the contact is beyond the optics' own reach.
|
// The cue is fresh only for its `CUE_MAX_AGE`; the contact is beyond the optics' own reach.
|
||||||
run(&mut sim, &mut ground, 2 * PERIOD);
|
run(&mut sim, &mut ground, 60);
|
||||||
let r = sim.optical_report(post).unwrap();
|
let r = sim.optical_report(post).unwrap();
|
||||||
assert_eq!(r.target, Some(id));
|
assert_eq!(r.target, Some(id));
|
||||||
assert_eq!(r.state, OpticalState::NoSight);
|
assert_eq!(r.state, OpticalState::NoSight);
|
||||||
assert_eq!(r.block, Some(SightBlock::OutOfRange));
|
assert_eq!(r.block, Some(SightBlock::OutOfRange));
|
||||||
assert!(r.observation.is_none() && r.observations == 0, "a relayed track became a measurement");
|
assert!(r.observation.is_none() && r.observations == 0, "a relayed track became a measurement");
|
||||||
// A far cue may point the head, but after a few failed probes the post lets it go.
|
|
||||||
run(&mut sim, &mut ground, MISS_LIMIT as u64 * PERIOD + 2);
|
|
||||||
let r = sim.optical_report(post).unwrap();
|
|
||||||
assert_eq!(r.target, None);
|
|
||||||
assert_eq!(r.state, OpticalState::Searching);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A searching post turns its head: a near contact outside the base heading comes into the sector.
|
// A searching post turns its head: a near contact outside the base heading comes into the sector.
|
||||||
@@ -1042,98 +927,12 @@ mod tests {
|
|||||||
run(&mut sim, &mut ground, 60);
|
run(&mut sim, &mut ground, 60);
|
||||||
let r = sim.optical_report(post).unwrap();
|
let r = sim.optical_report(post).unwrap();
|
||||||
assert_eq!(r.target, Some(far));
|
assert_eq!(r.target, Some(far));
|
||||||
assert_eq!(r.commanded, Some(far));
|
|
||||||
assert!(r.line().starts_with("по команде"), "the pin is not in the status: {}", r.line());
|
|
||||||
// A manual pin is predictable: it waits even when the contact leaves the optics' reach.
|
|
||||||
sim.drones.iter_mut().find(|d| d.id == far).unwrap().pos = DVec3::new(0.0, 95.0, -500.0);
|
|
||||||
run(&mut sim, &mut ground, 60);
|
|
||||||
let r = sim.optical_report(post).unwrap();
|
|
||||||
assert_eq!(r.target, Some(far), "a manual pin was dropped when the contact left the reach");
|
|
||||||
assert_eq!(r.block, Some(SightBlock::OutOfRange));
|
|
||||||
assert!(r.line().starts_with("по команде"), "{}", r.line());
|
|
||||||
assert!(sim.assign_optical(post, Some(near)));
|
assert!(sim.assign_optical(post, Some(near)));
|
||||||
run(&mut sim, &mut ground, 10);
|
run(&mut sim, &mut ground, 10);
|
||||||
assert_eq!(sim.optical_report(post).unwrap().target, Some(near));
|
assert_eq!(sim.optical_report(post).unwrap().target, Some(near));
|
||||||
assert!(sim.assign_optical(post, None));
|
|
||||||
run(&mut sim, &mut ground, 10);
|
|
||||||
let r = sim.optical_report(post).unwrap();
|
|
||||||
assert_eq!(r.commanded, None);
|
|
||||||
assert!(!r.line().contains("по команде"), "{}", r.line());
|
|
||||||
assert!(!sim.assign_optical(post, Some(u32::MAX)), "a dead contact cannot be assigned");
|
assert!(!sim.assign_optical(post, Some(u32::MAX)), "a dead contact cannot be assigned");
|
||||||
}
|
}
|
||||||
|
|
||||||
// #138: a contact that leaves the optics' reach must not keep the post for ever. The visible
|
|
||||||
// alternative is picked instead, and it is observed once the post has had its bounded probes.
|
|
||||||
#[test]
|
|
||||||
fn an_unreachable_contact_yields_to_a_visible_alternative() {
|
|
||||||
let mut sim = Sim::new(21);
|
|
||||||
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
|
|
||||||
let gone = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -50.0), DVec3::ZERO);
|
|
||||||
let alt = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -90.0), DVec3::ZERO);
|
|
||||||
let mut ground = clear_ground();
|
|
||||||
run(&mut sim, &mut ground, 30);
|
|
||||||
assert_eq!(sim.optical_report(post).unwrap().target, Some(gone), "the near contact was not picked");
|
|
||||||
// The held contact is moved far outside the optics' own reach; the alternative stays visible.
|
|
||||||
sim.drones.iter_mut().find(|d| d.id == gone).unwrap().pos = DVec3::new(0.0, 95.0, -500.0);
|
|
||||||
run(&mut sim, &mut ground, 20);
|
|
||||||
let r = sim.optical_report(post).unwrap();
|
|
||||||
assert_eq!(r.target, Some(alt), "the post still sat on the unreachable contact");
|
|
||||||
assert_ne!(r.block, Some(SightBlock::OutOfRange));
|
|
||||||
run(&mut sim, &mut ground, 200);
|
|
||||||
let r = sim.optical_report(post).unwrap();
|
|
||||||
assert_eq!(r.target, Some(alt));
|
|
||||||
let obs = r.observation.expect("the visible alternative was never observed");
|
|
||||||
assert_eq!(obs.target, alt);
|
|
||||||
}
|
|
||||||
|
|
||||||
// #138: a contact hidden behind a wall is let go after its failed probes, not held for ever,
|
|
||||||
// and the post observes the visible alternative in the same sector.
|
|
||||||
#[test]
|
|
||||||
fn a_blocked_contact_yields_to_a_visible_alternative() {
|
|
||||||
let mut sim = Sim::new(22);
|
|
||||||
let post = optical_at(&mut sim, 0.0, 0.0, 0.0);
|
|
||||||
let hidden = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::ZERO);
|
|
||||||
let alt = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(20.0, 95.0, -100.0), DVec3::ZERO);
|
|
||||||
let mut ground = clear_ground();
|
|
||||||
// A wall on the hidden contact's line only: the alternative at x=20 clears it.
|
|
||||||
ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -6), fill: world::Fill::Full }], 0);
|
|
||||||
run(&mut sim, &mut ground, 300);
|
|
||||||
let r = sim.optical_report(post).unwrap();
|
|
||||||
assert_eq!(r.target, Some(alt), "the post never tried the visible alternative to {hidden}");
|
|
||||||
assert_eq!(r.state, OpticalState::Observing);
|
|
||||||
assert_eq!(r.observation.expect("no observation of the alternative").target, alt);
|
|
||||||
}
|
|
||||||
|
|
||||||
// #138: five posts whose phases coincide must all advance under the per-tick probe budget. The
|
|
||||||
// ready queue serves the post probed longest ago first, so the fifth is not starved for ever.
|
|
||||||
#[test]
|
|
||||||
fn five_posts_in_one_phase_each_get_their_turn() {
|
|
||||||
let mut sim = Sim::new(23);
|
|
||||||
let mut posts = Vec::new();
|
|
||||||
for k in 0..5 {
|
|
||||||
let x = k as f64 * 5.0;
|
|
||||||
let post = optical_at(&mut sim, x, 0.0, 0.0);
|
|
||||||
flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(x, 95.0, -100.0), DVec3::ZERO);
|
|
||||||
posts.push(post);
|
|
||||||
// The contact consumed one id; three ordinary ids make four between deployments, so
|
|
||||||
// every post lands in the same `(id / PARTS) % PERIOD` phase.
|
|
||||||
for _ in 0..3 {
|
|
||||||
sim.id();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert!(
|
|
||||||
posts.iter().all(|&post| (post / PARTS) as u64 % PERIOD == (posts[0] / PARTS) as u64 % PERIOD),
|
|
||||||
"the posts do not share a phase: {posts:?}"
|
|
||||||
);
|
|
||||||
let mut ground = clear_ground();
|
|
||||||
run(&mut sim, &mut ground, 500);
|
|
||||||
let counts: Vec<u32> = posts.iter().map(|&p| sim.optical_report(p).unwrap().observations).collect();
|
|
||||||
assert!(counts.iter().all(|&c| c > 0), "a post never got a probe in 500 ticks: {counts:?}");
|
|
||||||
let min = counts.iter().copied().min().unwrap();
|
|
||||||
let max = counts.iter().copied().max().unwrap();
|
|
||||||
assert!(max - min <= 1, "the phase collision starved a post: {counts:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// A dead post neither probes nor invents an observation.
|
// A dead post neither probes nor invents an observation.
|
||||||
#[test]
|
#[test]
|
||||||
fn a_dead_post_does_not_probe() {
|
fn a_dead_post_does_not_probe() {
|
||||||
|
|||||||
+23
-255
@@ -11,9 +11,7 @@
|
|||||||
//! What is reported is memory, not truth. A hidden move, a switch-off, a re-role or a
|
//! 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
|
//! 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
|
//! 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. A wreck a look
|
//! second independent look may refine the area and (for a radar) its role.
|
||||||
//! flies over is not a lead: a fresh one makes no mark, and one the picture already held is
|
|
||||||
//! radioed home as destroyed and its mark leaves the picture (#139).
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
@@ -242,8 +240,6 @@ pub(super) struct Look {
|
|||||||
pub(super) quality: Quality,
|
pub(super) quality: Quality,
|
||||||
pub(super) source: Source,
|
pub(super) source: Source,
|
||||||
pub(super) observed: u64,
|
pub(super) observed: u64,
|
||||||
/// The unit was a wreck when it was seen: the report takes its mark out of the picture.
|
|
||||||
pub(super) wreck: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
@@ -372,13 +368,6 @@ impl Recon {
|
|||||||
if look.observed <= old.observed {
|
if look.observed <= old.observed {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// The flight saw the wreck itself: the station is off the planner's leads, and
|
|
||||||
// only the observation — never a hidden kill — takes the mark away (#139).
|
|
||||||
if look.wreck {
|
|
||||||
self.marks.remove(&id);
|
|
||||||
self.truth.remove(&id);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let refine = look.observed.saturating_sub(old.observed) >= REFINE_GAP;
|
let refine = look.observed.saturating_sub(old.observed) >= REFINE_GAP;
|
||||||
let m = self.marks.get_mut(&id).unwrap();
|
let m = self.marks.get_mut(&id).unwrap();
|
||||||
m.area = look.area;
|
m.area = look.area;
|
||||||
@@ -394,10 +383,6 @@ impl Recon {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
// A wreck is no target: a first look at one leaves no mark at all.
|
|
||||||
if look.wreck {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 {
|
if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -461,29 +446,6 @@ pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone,
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
let old = state.mark_for_truth(s.id);
|
let old = state.mark_for_truth(s.id);
|
||||||
// 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);
|
|
||||||
// A wreck is no lead and no emitter (#139). A fresh one makes no mark; one the picture
|
|
||||||
// already held is reported as destroyed, and the report takes the old mark away. A
|
|
||||||
// hidden kill never passes through here, so it never rewrites the picture.
|
|
||||||
if !s.alive() {
|
|
||||||
if old.is_none() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
out.push(Look {
|
|
||||||
truth: s.id,
|
|
||||||
area: area_of(s.pos, COARSE_AREA, salt),
|
|
||||||
radius: COARSE_AREA,
|
|
||||||
category: Category::of(s.kind),
|
|
||||||
role: None,
|
|
||||||
quality: Quality::Coarse,
|
|
||||||
source: Source::Flyby,
|
|
||||||
observed: now,
|
|
||||||
wreck: true,
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let refine = old.is_some_and(|m| now.saturating_sub(m.observed) >= REFINE_GAP);
|
let refine = old.is_some_and(|m| now.saturating_sub(m.observed) >= REFINE_GAP);
|
||||||
let quality = if refine { Quality::Refined } else { Quality::Coarse };
|
let quality = if refine { Quality::Refined } else { Quality::Coarse };
|
||||||
let cell = if refine { REFINED_AREA } else { COARSE_AREA };
|
let cell = if refine { REFINED_AREA } else { COARSE_AREA };
|
||||||
@@ -491,17 +453,17 @@ pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone,
|
|||||||
// A launch is a public event already watched by the disclosure channel; a look that
|
// 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.
|
// 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 launched = intel.contacts().get(&s.id).is_some_and(|c| c.seen == ew::Seen::Launch && now.saturating_sub(c.tick) < 200);
|
||||||
// The switch is intent, not work: a radar is an emitter only while `radar_up`, a jammer
|
|
||||||
// only while the transmitter is really on the air. A silent, packed or failed one is
|
|
||||||
// just a unit the flyby saw.
|
|
||||||
let source = match s.kind {
|
let source = match s.kind {
|
||||||
SamKind::Ew if s.ew_up() => Source::Jamming,
|
SamKind::Ew if s.ew_on => Source::Jamming,
|
||||||
SamKind::Radar if s.radar_up() => Source::Emission,
|
SamKind::Radar if s.radar_on => Source::Emission,
|
||||||
_ if launched => Source::Launch,
|
_ if launched => Source::Launch,
|
||||||
_ => Source::Flyby,
|
_ => Source::Flyby,
|
||||||
};
|
};
|
||||||
// The role is a public radar configuration only when a close second look can tell it.
|
// 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);
|
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 {
|
out.push(Look {
|
||||||
truth: s.id,
|
truth: s.id,
|
||||||
area: area_of(s.pos, cell, salt),
|
area: area_of(s.pos, cell, salt),
|
||||||
@@ -511,7 +473,6 @@ pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone,
|
|||||||
quality,
|
quality,
|
||||||
source,
|
source,
|
||||||
observed: now,
|
observed: now,
|
||||||
wreck: false,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
out
|
out
|
||||||
@@ -834,7 +795,6 @@ mod tests {
|
|||||||
quality: Quality::Refined,
|
quality: Quality::Refined,
|
||||||
source: before.source,
|
source: before.source,
|
||||||
observed: before.observed,
|
observed: before.observed,
|
||||||
wreck: false,
|
|
||||||
};
|
};
|
||||||
sim.recon.report(look, before.reported + 10_000);
|
sim.recon.report(look, before.reported + 10_000);
|
||||||
let after = *sim.recon.marks.values().next().unwrap();
|
let after = *sim.recon.marks.values().next().unwrap();
|
||||||
@@ -864,224 +824,35 @@ mod tests {
|
|||||||
s.missiles = 0;
|
s.missiles = 0;
|
||||||
sim.tick += 1000;
|
sim.tick += 1000;
|
||||||
assert_eq!(key(&sim.enemy_picture().recon), key(&before), "a hidden change rewrote the recon picture");
|
assert_eq!(key(&sim.enemy_picture().recon), key(&before), "a hidden change rewrote the recon picture");
|
||||||
// A hidden kill does not take the mark away either: it is still a lead until its age
|
|
||||||
// runs out, and then it is forgotten like any other unrevisited mark (#139).
|
|
||||||
let mark = before.first().expect("the look made no mark").id;
|
|
||||||
let observed = sim.recon.marks.get(&mark).expect("the mark is gone").observed;
|
|
||||||
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark), "a hidden kill removed an active lead");
|
|
||||||
assert!(sim.recon.leads(observed + MARK_TTL - 1).iter().any(|m| m.id == mark), "a mark died before its age");
|
|
||||||
assert!(sim.recon.leads(observed + MARK_TTL).iter().all(|m| m.id != mark), "a mark outlived its age");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// #139: a look at a wreck is not a lead. A station destroyed before the flight arrives, with
|
|
||||||
// its switch still on, makes no mark and no lead; its report is an empty observation.
|
// #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]
|
#[test]
|
||||||
fn a_fresh_wreck_makes_no_mark_and_no_lead() {
|
fn the_source_is_the_channel_that_showed_the_unit() {
|
||||||
let mut sim = Sim::new(21);
|
|
||||||
let object = DVec3::new(0.0, 70.0, 0.0);
|
|
||||||
let id = sam(&mut sim, SamKind::Radar, object + DVec3::new(20.0, 0.0, 10.0));
|
|
||||||
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
|
|
||||||
s.health = 0.0;
|
|
||||||
s.radar_on = true;
|
|
||||||
assert!(!s.radar_up(), "a destroyed radar still reported itself working");
|
|
||||||
sim.start_recon(&[object], 0.0, 300.0, &mut Out::default());
|
|
||||||
let (_, at) = look_once(&mut sim);
|
|
||||||
assert!(sim.recon.marks.is_empty(), "a look at a fresh wreck reached the picture");
|
|
||||||
sim.tick = at + REPORT_DELAY;
|
|
||||||
sim.step_recon(&mut Out::default());
|
|
||||||
assert!(sim.recon.marks.is_empty(), "a fresh wreck made a mark");
|
|
||||||
assert!(sim.recon.leads(sim.tick).is_empty(), "a fresh wreck became an active lead");
|
|
||||||
}
|
|
||||||
|
|
||||||
// #139: a hidden kill leaves the mark as the picture remembers it, but a look that flies over
|
|
||||||
// the wreck reports the destruction and the mark leaves the leads. Nothing of it stays to
|
|
||||||
// aim at, and a mark no look revisits still ages out on its own.
|
|
||||||
#[test]
|
|
||||||
fn a_known_mark_leaves_the_leads_when_its_wreck_is_seen() {
|
|
||||||
let mut sim = Sim::new(22);
|
|
||||||
let object = DVec3::new(0.0, 70.0, 0.0);
|
|
||||||
let id = sam(&mut sim, SamKind::Radar, 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 mark = sim.recon.mark_for_truth(id).expect("a live radar made no mark");
|
|
||||||
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark.id));
|
|
||||||
|
|
||||||
// A hidden kill is not an observation: the old assessment stands.
|
|
||||||
sim.sams.iter_mut().find(|s| s.id == id).unwrap().health = 0.0;
|
|
||||||
assert!(sim.recon.leads(sim.tick).iter().any(|m| m.id == mark.id), "a hidden kill removed the mark");
|
|
||||||
|
|
||||||
// A look that sees the wreck names it as a flyby, and its report takes the mark away.
|
|
||||||
let zone = Zone { center: object, radius: ZONE_RADIUS };
|
|
||||||
let wreck = super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).expect("the wreck was not observed");
|
|
||||||
assert!(wreck.wreck);
|
|
||||||
assert_eq!(wreck.source, Source::Flyby, "a wreck named an emission");
|
|
||||||
sim.recon.report(wreck, sim.tick + REPORT_DELAY);
|
|
||||||
assert!(sim.recon.marks.is_empty(), "the wreck's report left a mark");
|
|
||||||
assert!(sim.recon.truth.iter().all(|(_, t)| *t != id), "the wreck's truth mapping stayed");
|
|
||||||
assert!(sim.recon.leads(sim.tick + REPORT_DELAY).is_empty(), "the wreck stayed an active lead");
|
|
||||||
}
|
|
||||||
|
|
||||||
// #139: a wreck observation still waiting for its report is durable. A restored flight takes
|
|
||||||
// the mark away on its tick, while an older save without the wreck flag reads as before.
|
|
||||||
#[test]
|
|
||||||
fn a_wreck_report_survives_a_save_and_removes_the_mark() {
|
|
||||||
let mut sim = Sim::new(23);
|
|
||||||
let object = DVec3::new(0.0, 70.0, 0.0);
|
|
||||||
let id = sam(&mut sim, SamKind::Radar, 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 mark = sim.recon.mark_for_truth(id).expect("no mark to destroy");
|
|
||||||
// The radar dies unseen; a second flight looks at the wreck and its report is unsent
|
|
||||||
// when the save is taken.
|
|
||||||
sim.sams.iter_mut().find(|s| s.id == id).unwrap().health = 0.0;
|
|
||||||
sim.recon.sorties.clear();
|
|
||||||
sim.recon.checked.clear();
|
|
||||||
sim.start_recon(&[object], 0.0, 900.0, &mut Out::default());
|
|
||||||
let (_, seen_wreck) = look_once(&mut sim);
|
|
||||||
assert!(sim.recon.sorties.iter().flat_map(|s| &s.pending).any(|l| l.wreck), "the wreck was not pending");
|
|
||||||
let text = sim.air_text().expect("a wreck report is durable");
|
|
||||||
assert!(text.lines().any(|l| l.starts_with("airrecobs ") && l.ends_with(" true")), "the wreck flag was not written");
|
|
||||||
|
|
||||||
// An older save has no flag: the same look reads as a live re-observation.
|
|
||||||
let legacy: String = text
|
|
||||||
.lines()
|
|
||||||
.map(|l| {
|
|
||||||
if l.starts_with("airrecobs ") {
|
|
||||||
let mut w: Vec<&str> = l.split_whitespace().collect();
|
|
||||||
w.pop();
|
|
||||||
w.join(" ")
|
|
||||||
} else {
|
|
||||||
l.to_string()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n")
|
|
||||||
+ "\n";
|
|
||||||
let mut old = Sim::new(24);
|
|
||||||
old.restore_air(Sim::parse_air(&legacy).expect("an older save reads").expect("the air section is there"));
|
|
||||||
assert!(old.recon.sorties.iter().flat_map(|s| &s.pending).all(|l| !l.wreck), "an older save invented a wreck");
|
|
||||||
|
|
||||||
let mut back = Sim::new(25);
|
|
||||||
back.restore_air(Sim::parse_air(&text).expect("the save reads").expect("the air section is there"));
|
|
||||||
assert!(back.recon.marks.contains_key(&mark.id), "the save forgot the mark before its wreck report");
|
|
||||||
assert!(back.recon.sorties.iter().flat_map(|s| &s.pending).any(|l| l.wreck), "the save lost the wreck report");
|
|
||||||
back.tick = seen_wreck + REPORT_DELAY;
|
|
||||||
back.step_recon(&mut Out::default());
|
|
||||||
assert!(!back.recon.marks.contains_key(&mark.id), "a restored wreck report left the mark");
|
|
||||||
assert!(back.recon.leads(back.tick).is_empty(), "a restored wreck report stayed an active lead");
|
|
||||||
}
|
|
||||||
|
|
||||||
// #135/#139: the channel matters. A silent, packed or failed radar is only a flyby; so is a
|
|
||||||
// jammer whose transmitter is off, packed or destroyed. Only a station actually working shows
|
|
||||||
// its emission, and a wreck is no source at all. A just-fired system is still a launch the
|
|
||||||
// disclosure channel already watched. A hidden empty magazine is not read.
|
|
||||||
#[test]
|
|
||||||
fn the_source_is_the_channel_that_showed_a_working_unit() {
|
|
||||||
let mut sim = Sim::new(8);
|
let mut sim = Sim::new(8);
|
||||||
let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS };
|
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 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 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));
|
let s400 = sam(&mut sim, SamKind::S400, DVec3::new(0.0, 70.0, 10.0));
|
||||||
let source = |sim: &Sim, id: u32| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).map(|l| l.source);
|
sim.recon.checked.clear();
|
||||||
fn unit(sim: &mut Sim, id: u32) -> &mut Sam {
|
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 == id).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Working: the radar emits and the jammer transmits.
|
|
||||||
assert_eq!(source(&sim, radar), Some(Source::Emission));
|
|
||||||
unit(&mut sim, ew).ew_on = true;
|
|
||||||
assert_eq!(source(&sim, ew), Some(Source::Jamming));
|
|
||||||
|
|
||||||
// Off: the switch is intent, not work.
|
|
||||||
unit(&mut sim, radar).radar_on = false;
|
|
||||||
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a silent radar was read as emitting");
|
|
||||||
unit(&mut sim, radar).radar_on = true;
|
|
||||||
unit(&mut sim, ew).ew_on = false;
|
|
||||||
assert_eq!(source(&sim, ew), Some(Source::Flyby), "a silent jammer was read as transmitting");
|
|
||||||
unit(&mut sim, ew).ew_on = true;
|
|
||||||
|
|
||||||
// Packed for a march: neither is on the air, whatever the switch says.
|
|
||||||
unit(&mut sim, radar).state = SamState::Moving;
|
|
||||||
unit(&mut sim, ew).state = SamState::Moving;
|
|
||||||
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a radar on the march was read as emitting");
|
|
||||||
assert_eq!(source(&sim, ew), Some(Source::Flyby), "a jammer on the march was read as transmitting");
|
|
||||||
unit(&mut sim, radar).state = SamState::Search;
|
|
||||||
unit(&mut sim, ew).state = SamState::Search;
|
|
||||||
|
|
||||||
// Cooling down: a jammer locked by heat is not transmitting either.
|
|
||||||
unit(&mut sim, ew).ew_lock = true;
|
|
||||||
assert_eq!(source(&sim, ew), Some(Source::Flyby), "an overheated jammer was read as transmitting");
|
|
||||||
unit(&mut sim, ew).ew_lock = false;
|
|
||||||
|
|
||||||
// Damage: a failed sensor is no radar; a damaged hull with a working sensor still emits.
|
|
||||||
unit(&mut sim, radar).comps.0[Part::Sensor as usize] = 0.0;
|
|
||||||
assert_eq!(source(&sim, radar), Some(Source::Flyby), "a radar with a failed sensor was read as emitting");
|
|
||||||
unit(&mut sim, radar).comps.0[Part::Sensor as usize] = 1.0;
|
|
||||||
unit(&mut sim, radar).health = 0.5;
|
|
||||||
assert_eq!(source(&sim, radar), Some(Source::Emission), "a damaged but working radar lost its emission");
|
|
||||||
|
|
||||||
// Destroyed: a wreck is no source and makes no lead at all.
|
|
||||||
unit(&mut sim, radar).health = 0.0;
|
|
||||||
unit(&mut sim, ew).health = 0.0;
|
|
||||||
assert_eq!(source(&sim, radar), None, "a wreck was reported as a lead");
|
|
||||||
assert_eq!(source(&sim, ew), None, "a wrecked jammer was reported as transmitting");
|
|
||||||
|
|
||||||
|
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);
|
sim.intel.observe(sim.sams.iter().find(|s| s.id == s400).unwrap(), sim.tick, ew::Seen::Launch);
|
||||||
assert_eq!(source(&sim, s400), Some(Source::Launch));
|
assert_eq!(source(&sim, s400), Source::Launch);
|
||||||
// A hidden empty magazine does not change the source.
|
// A hidden empty magazine does not change the source.
|
||||||
sim.sams.iter_mut().find(|s| s.id == s400).unwrap().missiles = 0;
|
sim.sams.iter_mut().find(|s| s.id == s400).unwrap().missiles = 0;
|
||||||
assert_eq!(source(&sim, s400), Some(Source::Launch));
|
assert_eq!(source(&sim, s400), Source::Launch);
|
||||||
}
|
|
||||||
|
|
||||||
// #139: a station the picture already holds, seen off, packed or damaged, stays a flyby
|
|
||||||
// contact: the switch never turns its mark into an emitter, and a working station seen
|
|
||||||
// again still names its emission.
|
|
||||||
#[test]
|
|
||||||
fn a_known_station_that_stops_working_stays_a_flyby_contact() {
|
|
||||||
let mut sim = Sim::new(26);
|
|
||||||
let zone = Zone { center: DVec3::new(0.0, 70.0, 0.0), radius: ZONE_RADIUS };
|
|
||||||
let id = sam(&mut sim, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0));
|
|
||||||
let seen = |sim: &Sim, now: u64| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, now).into_iter().find(|l| l.truth == id).expect("the radar was not observed");
|
|
||||||
|
|
||||||
let first = seen(&sim, 100);
|
|
||||||
assert_eq!(first.source, Source::Emission);
|
|
||||||
sim.recon.report(first, 100);
|
|
||||||
let mark = sim.recon.mark_for_truth(id).expect("the working look made no mark");
|
|
||||||
|
|
||||||
// Off, then packed for a march, then with a failed sensor: the contact stays, the
|
|
||||||
// channel is the flyby alone.
|
|
||||||
for (change, now) in [(0, 200), (1, 900), (2, 1600)] {
|
|
||||||
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
|
|
||||||
match change {
|
|
||||||
0 => s.radar_on = false,
|
|
||||||
1 => {
|
|
||||||
s.radar_on = true;
|
|
||||||
s.state = SamState::Moving;
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
s.state = SamState::Search;
|
|
||||||
s.comps.0[Part::Sensor as usize] = 0.0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let look = seen(&sim, now);
|
|
||||||
assert!(!look.wreck, "case {change}: a working station was read as a wreck");
|
|
||||||
assert_eq!(look.source, Source::Flyby, "case {change}: the switch was read as work");
|
|
||||||
sim.recon.report(look, now);
|
|
||||||
assert!(sim.recon.marks.contains_key(&mark.id), "case {change}: the contact was lost");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Working again: the refined look names the emission.
|
|
||||||
let s = sim.sams.iter_mut().find(|s| s.id == id).unwrap();
|
|
||||||
s.comps.0[Part::Sensor as usize] = 1.0;
|
|
||||||
let look = seen(&sim, 2300);
|
|
||||||
assert_eq!(look.source, Source::Emission);
|
|
||||||
assert_eq!(look.quality, Quality::Refined);
|
|
||||||
sim.recon.report(look, 2300);
|
|
||||||
assert_eq!(sim.recon.mark_for_truth(id).unwrap().source, Source::Emission);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// #135: the planner's order is the observed public role, freshness and quality, not the
|
// #135: the planner's order is the observed public role, freshness and quality, not the
|
||||||
@@ -1272,7 +1043,6 @@ mod tests {
|
|||||||
quality: Quality::Coarse,
|
quality: Quality::Coarse,
|
||||||
source: Source::Flyby,
|
source: Source::Flyby,
|
||||||
observed: 100,
|
observed: 100,
|
||||||
wreck: false,
|
|
||||||
};
|
};
|
||||||
r.report(coarse_look, 200);
|
r.report(coarse_look, 200);
|
||||||
let coarse = r.mark();
|
let coarse = r.mark();
|
||||||
@@ -1301,7 +1071,6 @@ mod tests {
|
|||||||
quality: Quality::Refined,
|
quality: Quality::Refined,
|
||||||
source: Source::Emission,
|
source: Source::Emission,
|
||||||
observed: 1000,
|
observed: 1000,
|
||||||
wreck: false,
|
|
||||||
};
|
};
|
||||||
sim.recon.report(look(1, battery::RadarRole::Search), 1000);
|
sim.recon.report(look(1, battery::RadarRole::Search), 1000);
|
||||||
sim.recon.report(look(2, battery::RadarRole::Engagement), 1000);
|
sim.recon.report(look(2, battery::RadarRole::Engagement), 1000);
|
||||||
@@ -1348,7 +1117,6 @@ mod tests {
|
|||||||
quality: Quality::Coarse,
|
quality: Quality::Coarse,
|
||||||
source: Source::Flyby,
|
source: Source::Flyby,
|
||||||
observed: 100,
|
observed: 100,
|
||||||
wreck: false,
|
|
||||||
},
|
},
|
||||||
100,
|
100,
|
||||||
);
|
);
|
||||||
|
|||||||
+57
-840
File diff suppressed because it is too large
Load Diff
@@ -496,7 +496,7 @@ fn run_profile_world(roles: &[RadarRole], ticks: u64) -> (ProfileStats, Sim, Vec
|
|||||||
if sam.radar_profile().id == "radar_search" || sam.radar_profile().id == "radar_height" {
|
if sam.radar_profile().id == "radar_search" || sam.radar_profile().id == "radar_height" {
|
||||||
stats.search_or_height_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
|
stats.search_or_height_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
|
||||||
}
|
}
|
||||||
stats.max_channels = stats.max_channels.max(sam.own_channels_used(sim.tick));
|
stats.max_channels = stats.max_channels.max(sam.own_channels_used());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
(stats, sim, radars, ids)
|
(stats, sim, radars, ids)
|
||||||
@@ -633,65 +633,11 @@ fn tracked_channels_are_a_hard_limit_but_the_rest_keep_search_plots() {
|
|||||||
let own: Vec<&Track> = sim.sams[engagement].tracks.iter().filter(|t| t.own_tick > 0).collect();
|
let own: Vec<&Track> = sim.sams[engagement].tracks.iter().filter(|t| t.own_tick > 0).collect();
|
||||||
let precise = own.iter().filter(|t| t.own_product != Measure::Search).count();
|
let precise = own.iter().filter(|t| t.own_product != Measure::Search).count();
|
||||||
assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}");
|
assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}");
|
||||||
assert_eq!(sim.sams[engagement].own_channels_used(sim.tick), 2);
|
assert_eq!(sim.sams[engagement].own_channels_used(), 2);
|
||||||
assert_eq!(own.len(), 4, "a full station stopped giving coarse search plots: {own:?}");
|
assert_eq!(own.len(), 4, "a full station stopped giving coarse search plots: {own:?}");
|
||||||
assert!(own.iter().filter(|t| t.own_product == Measure::Search).all(|t| !t.own_authorizes(sim.tick)));
|
assert!(own.iter().filter(|t| t.own_product == Measure::Search).all(|t| !t.own_authorizes(sim.tick)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// #140: a network heartbeat keeps an old contact's track fresh, but never holds the station's
|
|
||||||
// channel: two stale own fire plots free the channels for a new contact, and the survey tracks
|
|
||||||
// of the old ones stay on the picture — with the search radar left running.
|
|
||||||
#[test]
|
|
||||||
fn stale_own_plots_free_their_channels_while_the_network_keeps_the_tracks() {
|
|
||||||
let mut sim = Sim::new(140);
|
|
||||||
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 0.0);
|
|
||||||
let search = radar_with_role(&mut sim, RadarRole::Search, 1550.0);
|
|
||||||
for x in [100.0, 140.0] {
|
|
||||||
sim.add_drone(DroneKind::Gerbera, DVec3::new(x, 120.0, 0.0), DVec3::Z, DVec3::new(x, 120.0, 0.0));
|
|
||||||
}
|
|
||||||
let old: Vec<u32> = sim.drones.iter().map(|d| d.id).collect();
|
|
||||||
let mut ground = Ground::default();
|
|
||||||
let radars = [engagement, search];
|
|
||||||
for tick in 1..=40 {
|
|
||||||
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
|
|
||||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
|
||||||
}
|
|
||||||
let frozen: Vec<u64> = old
|
|
||||||
.iter()
|
|
||||||
.map(|&id| {
|
|
||||||
let t = sim.sams[engagement].track(id).expect("the station took the contact");
|
|
||||||
assert_ne!(t.own_product, Measure::Search, "the station took no channel: {t:?}");
|
|
||||||
t.own_tick
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
assert_eq!(sim.sams[engagement].own_channels_used(sim.tick), 2);
|
|
||||||
// The two contacts leave the station's reach for the search radar beside them; the new one
|
|
||||||
// arrives close to the station. Only the network keeps the old tracks alive now.
|
|
||||||
for (k, d) in sim.drones.iter_mut().enumerate() {
|
|
||||||
d.pos = DVec3::new(1600.0 + 20.0 * k as f64, 120.0, 0.0);
|
|
||||||
}
|
|
||||||
sim.add_drone(DroneKind::Gerbera, DVec3::new(180.0, 120.0, 0.0), DVec3::Z, DVec3::new(180.0, 120.0, 0.0));
|
|
||||||
let fresh = sim.drones.last().unwrap().id;
|
|
||||||
for tick in 41..=750 {
|
|
||||||
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
|
|
||||||
sweep(&mut sim, &mut ground, &radars, &targets, tick);
|
|
||||||
}
|
|
||||||
let now = sim.tick;
|
|
||||||
let station = &sim.sams[engagement];
|
|
||||||
assert_eq!(station.own_channels_used(now), 1, "the stale channels still hold: {:?}", station.tracks);
|
|
||||||
for (&id, &own_tick) in old.iter().zip(&frozen) {
|
|
||||||
let t = station.track(id).expect("the survey track was thrown away with its channel");
|
|
||||||
assert_eq!(t.own_tick, own_tick, "the network renewed the station's own plot");
|
|
||||||
assert!(t.tick > 500, "the network stopped relaying the old contact: {t:?}");
|
|
||||||
assert_eq!(t.product, Measure::Search, "the relayed survey plot is gone: {t:?}");
|
|
||||||
assert!(!t.holds_channel(now, station.track_ttl() as u64), "an old own plot still holds a channel: {t:?}");
|
|
||||||
assert!(!t.own_authorizes(now));
|
|
||||||
}
|
|
||||||
let new = station.track(fresh).expect("the new contact is not held");
|
|
||||||
assert_eq!(new.own_product, Measure::Fire, "the new contact never got a channel: {new:?}");
|
|
||||||
assert!(new.own_authorizes(now), "the new contact's own fire plot does not authorize: {new:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() {
|
fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() {
|
||||||
let mut sim = Sim::new(1342);
|
let mut sim = Sim::new(1342);
|
||||||
@@ -805,7 +751,7 @@ fn profiles_keep_their_jobs_over_a_ridge_on_one_seed_and_land() {
|
|||||||
stats.high_marked |= t.id == ids[1];
|
stats.high_marked |= t.id == ids[1];
|
||||||
}
|
}
|
||||||
if profile.id == "radar_track" {
|
if profile.id == "radar_track" {
|
||||||
stats.track_channels = stats.track_channels.max(sam.own_channels_used(sim.tick));
|
stats.track_channels = stats.track_channels.max(sam.own_channels_used());
|
||||||
}
|
}
|
||||||
if profile.id == "radar_search" || profile.id == "radar_height" {
|
if profile.id == "radar_search" || profile.id == "radar_height" {
|
||||||
stats.nonfire_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
|
stats.nonfire_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
|
||||||
|
|||||||
@@ -322,15 +322,6 @@ impl Track {
|
|||||||
pub fn own_authorizes(&self, now: u64) -> bool {
|
pub fn own_authorizes(&self, now: u64) -> bool {
|
||||||
self.own_fire_within(now, MISSILE_AGE)
|
self.own_fire_within(now, MISSILE_AGE)
|
||||||
}
|
}
|
||||||
/// The station's own refine/fire channel on this contact is still live: the plot is its own,
|
|
||||||
/// finer than a search, and no older than the station keeps a contact without a fresh
|
|
||||||
/// measurement. A relayed plot never holds a channel: the network's heartbeat keeps the
|
|
||||||
/// track fresh, not the station's own tracking (#140).
|
|
||||||
pub fn holds_channel(&self, now: u64, ttl: u64) -> bool {
|
|
||||||
self.own_tick > 0
|
|
||||||
&& self.own_product != battery::Measure::Search
|
|
||||||
&& now.saturating_sub(self.own_tick) <= ttl
|
|
||||||
}
|
|
||||||
/// Who measured the latest plot, as an ID (`0`: no station).
|
/// Who measured the latest plot, as an ID (`0`: no station).
|
||||||
pub fn measured_by(&self) -> Option<u32> {
|
pub fn measured_by(&self) -> Option<u32> {
|
||||||
(self.source != 0).then_some(self.source)
|
(self.source != 0).then_some(self.source)
|
||||||
@@ -372,23 +363,12 @@ impl Sam {
|
|||||||
pub fn radar_up(&self) -> bool {
|
pub fn radar_up(&self) -> bool {
|
||||||
self.radar_on && self.mode != battery::SamMode::LauncherOnly && self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0
|
self.radar_on && self.mode != battery::SamMode::LauncherOnly && self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0
|
||||||
}
|
}
|
||||||
/// Its jammer is really on the air: the switch, a live station and a deployed one. The same
|
|
||||||
/// state `step_ew` transmits in, so a look names jamming only while the transmitter works.
|
|
||||||
pub fn ew_up(&self) -> bool {
|
|
||||||
self.ew_on && !self.ew_lock && self.alive() && !self.moving()
|
|
||||||
}
|
|
||||||
pub fn track(&self, id: u32) -> Option<&Track> {
|
pub fn track(&self, id: u32) -> Option<&Track> {
|
||||||
self.tracks.iter().find(|t| t.id == id)
|
self.tracks.iter().find(|t| t.id == id)
|
||||||
}
|
}
|
||||||
/// Ticks a contact stays this station's own without a fresh measurement: three missed turns, at least 60.
|
/// Refined/fire channels this station is currently using.
|
||||||
pub(super) fn track_ttl(&self) -> u32 {
|
pub fn own_channels_used(&self) -> usize {
|
||||||
((self.scan_ticks() * 3.0) as u32).max(60)
|
self.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count()
|
||||||
}
|
|
||||||
/// Refined/fire channels this station is currently using: the same test the planner applies,
|
|
||||||
/// so the panel and the allocation never disagree about a stale channel.
|
|
||||||
pub fn own_channels_used(&self, now: u64) -> usize {
|
|
||||||
let ttl = self.track_ttl() as u64;
|
|
||||||
self.tracks.iter().filter(|t| t.holds_channel(now, ttl)).count()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -488,14 +468,13 @@ impl Sim {
|
|||||||
let scan = sam.scan_profile();
|
let scan = sam.scan_profile();
|
||||||
let period = sam.scan_ticks();
|
let period = sam.scan_ticks();
|
||||||
let w = TAU / period;
|
let w = TAU / period;
|
||||||
let (b0, ttl) = (sam.beam, sam.track_ttl());
|
let (b0, ttl) = (sam.beam, ((period * 3.0) as u32).max(60));
|
||||||
sam.beam = (b0 + w) % TAU;
|
sam.beam = (b0 + w) % TAU;
|
||||||
let at = antenna(sam);
|
let at = antenna(sam);
|
||||||
let horizon = self.horizons.get(&sam.id);
|
let horizon = self.horizons.get(&sam.id);
|
||||||
let local = spec.sensor * profile.local;
|
let local = spec.sensor * profile.local;
|
||||||
// Channels already refining or holding fire plots, by the same test the UI shows:
|
// Channels already refining or holding fire plots. Search plots do not use one.
|
||||||
// a stale own plot (the network may keep the track) no longer occupies one.
|
let mut used = sam.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count();
|
||||||
let mut used = sam.own_channels_used(now);
|
|
||||||
let mut fresh: Vec<Track> = Vec::new();
|
let mut fresh: Vec<Track> = Vec::new();
|
||||||
for (d, h) in self.drones.iter().zip(&heights) {
|
for (d, h) in self.drones.iter().zip(&heights) {
|
||||||
if !d.alive() {
|
if !d.alive() {
|
||||||
@@ -527,7 +506,8 @@ impl Sim {
|
|||||||
// and a full station does not silently refine the whole sky. A station already
|
// and a full station does not silently refine the whole sky. A station already
|
||||||
// refining a contact keeps its channel; a new refinement needs a free one, and
|
// refining a contact keeps its channel; a new refinement needs a free one, and
|
||||||
// without one the station still publishes its ordinary coarse search plot.
|
// without one the station still publishes its ordinary coarse search plot.
|
||||||
let holds_channel = held.is_some_and(|t| t.holds_channel(now, ttl as u64));
|
let own_held = held.is_some_and(|t| t.own_tick > 0);
|
||||||
|
let holds_channel = own_held && held.is_some_and(|t| t.own_product != battery::Measure::Search);
|
||||||
let mut product = if profile.allows(battery::Measure::Fire) {
|
let mut product = if profile.allows(battery::Measure::Fire) {
|
||||||
battery::Measure::Fire
|
battery::Measure::Fire
|
||||||
} else if profile.allows(battery::Measure::Refine) && held.is_some() {
|
} else if profile.allows(battery::Measure::Refine) && held.is_some() {
|
||||||
|
|||||||
+1
-464
@@ -287,312 +287,6 @@ pub enum CheckReason {
|
|||||||
Text(String),
|
Text(String),
|
||||||
Parts(Vec<(Part, f64)>),
|
Parts(Vec<(Part, f64)>),
|
||||||
PartEffect(PartEffect),
|
PartEffect(PartEffect),
|
||||||
/// The one headline reason a battery fires or does not, shared by the sim, the monitor and
|
|
||||||
/// the chat command.
|
|
||||||
Battle(BattleReason),
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------- the one headline reason
|
|
||||||
|
|
||||||
/// What a battery's picture holds of a contact: the newest plot, its age and the station that
|
|
||||||
/// made it. Only what the battery itself can know: a relayed plot's source, never the drone's
|
|
||||||
/// true kind or place.
|
|
||||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
|
||||||
pub struct BattleMark {
|
|
||||||
/// Ticks since the newest measurement (any station).
|
|
||||||
pub age: u64,
|
|
||||||
/// Ticks since this battery's own radar measured it, if it ever did.
|
|
||||||
pub own_age: Option<u64>,
|
|
||||||
/// The station that made the newest plot, as an index into `Sim::sams`.
|
|
||||||
pub source: Option<usize>,
|
|
||||||
/// The newest plot is this battery's own measurement.
|
|
||||||
pub own: bool,
|
|
||||||
/// What the newest plot is good for.
|
|
||||||
pub product: battery::Measure,
|
|
||||||
pub quality: u8,
|
|
||||||
/// This battery's own measurement's product, if it has one.
|
|
||||||
pub own_product: Option<battery::Measure>,
|
|
||||||
/// The plot is carried on as a forecast, not a fresh measurement.
|
|
||||||
pub forecast: bool,
|
|
||||||
/// The class the picture estimated, never the target's own kind.
|
|
||||||
pub class: ClassEst,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BattleMark {
|
|
||||||
fn of(sim: &Sim, sam: &Sam, track: &sight::Track, now: u64) -> Self {
|
|
||||||
BattleMark {
|
|
||||||
age: track.age(now),
|
|
||||||
own_age: (track.own_tick > 0).then(|| now.saturating_sub(track.own_tick)),
|
|
||||||
source: sim.sams.iter().position(|s| s.id == track.source),
|
|
||||||
own: track.source == sam.id,
|
|
||||||
product: track.product,
|
|
||||||
quality: track.quality,
|
|
||||||
own_product: (track.own_tick > 0).then_some(track.own_product),
|
|
||||||
forecast: track.forecast(now),
|
|
||||||
class: track.class,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The headline state of a battery, in the words the player asks with.
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
||||||
pub enum BattleKind {
|
|
||||||
/// It can fire at the target it holds now.
|
|
||||||
Ready,
|
|
||||||
/// Есть только обзор: a search plot or a relayed one, no fire-quality measurement.
|
|
||||||
ObserveOnly,
|
|
||||||
/// Ждёт сопровождения: its own radar is refining, or a launcher waits for a supporting
|
|
||||||
/// radar's fire plot.
|
|
||||||
AwaitingTrack,
|
|
||||||
/// Каналы заняты: every tracked-contact channel of its radar is in use by other contacts.
|
|
||||||
ChannelsBusy,
|
|
||||||
/// Нет боезапаса: no rounds and no shells, or reloading.
|
|
||||||
NoAmmo,
|
|
||||||
/// Something else stops it, named by `block`.
|
|
||||||
Blocked,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What stops a battery that is otherwise ready to engage.
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
||||||
pub enum BattleBlock {
|
|
||||||
Destroyed,
|
|
||||||
Moving,
|
|
||||||
Hold,
|
|
||||||
NoWeapon,
|
|
||||||
NoTarget,
|
|
||||||
NoTrack,
|
|
||||||
OutOfRoles,
|
|
||||||
OutOfReach,
|
|
||||||
Claimed,
|
|
||||||
Doctrine,
|
|
||||||
Aiming,
|
|
||||||
Preparing,
|
|
||||||
LauncherDown,
|
|
||||||
Other,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one reason, in a typed form. `mark` is the contact's own picture (age, source, product);
|
|
||||||
/// a hidden truth never enters it.
|
|
||||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
|
||||||
pub struct BattleReason {
|
|
||||||
pub kind: BattleKind,
|
|
||||||
pub block: Option<BattleBlock>,
|
|
||||||
pub sam: usize,
|
|
||||||
pub target: Option<u32>,
|
|
||||||
pub mark: Option<BattleMark>,
|
|
||||||
pub rounds: u32,
|
|
||||||
pub bursts: u32,
|
|
||||||
/// Ticks left of a reload, 0 when loaded.
|
|
||||||
pub reloading: u32,
|
|
||||||
/// Tracked-contact channels in use and their total, when the radar has any.
|
|
||||||
pub channels: Option<(usize, u8)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BattleReason {
|
|
||||||
pub fn ready(self) -> bool {
|
|
||||||
self.kind == BattleKind::Ready
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The detailed decision (`why`) is the authority on whether a shot goes now: a headline
|
|
||||||
/// that promised a shot it cannot take, or denied one it takes, is corrected here.
|
|
||||||
pub fn settle(&mut self, fires: bool) {
|
|
||||||
match (fires, self.kind == BattleKind::Ready) {
|
|
||||||
(true, false) => {
|
|
||||||
self.kind = BattleKind::Ready;
|
|
||||||
self.block = None;
|
|
||||||
}
|
|
||||||
(false, true) => {
|
|
||||||
self.kind = BattleKind::Blocked;
|
|
||||||
self.block = Some(BattleBlock::Other);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Sim {
|
|
||||||
/// Why battery `index` fires or doesn't, as one typed reason for the target it holds or the
|
|
||||||
/// most threatening one its picture allows. The same predicates `step_sams` uses.
|
|
||||||
pub fn battle_reason(&self, index: usize) -> Option<BattleReason> {
|
|
||||||
self.battle_reason_at(index, None)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The same, for a chosen contact (else the system's target, else the most threatening).
|
|
||||||
pub fn battle_reason_at(&self, index: usize, chosen: Option<u32>) -> Option<BattleReason> {
|
|
||||||
let sam = self.sams.get(index)?;
|
|
||||||
let spec = sam.kind.spec();
|
|
||||||
let now = self.tick;
|
|
||||||
let channels = (spec.sensor > 0.0 && sam.mode != battery::SamMode::LauncherOnly && sam.radar_profile().channels > 0)
|
|
||||||
.then(|| (sam.own_channels_used(now), sam.radar_profile().channels));
|
|
||||||
let reason = |kind, block, target, mark| BattleReason {
|
|
||||||
kind,
|
|
||||||
block,
|
|
||||||
sam: index,
|
|
||||||
target,
|
|
||||||
mark,
|
|
||||||
rounds: sam.missiles,
|
|
||||||
bursts: sam.bursts,
|
|
||||||
reloading: sam.reloading,
|
|
||||||
channels,
|
|
||||||
};
|
|
||||||
if !sam.alive() {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Destroyed), None, None));
|
|
||||||
}
|
|
||||||
if self.hold {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Hold), None, None));
|
|
||||||
}
|
|
||||||
if sam.moving() {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Moving), None, None));
|
|
||||||
}
|
|
||||||
if !sam.kind.armed() {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoWeapon), None, None));
|
|
||||||
}
|
|
||||||
let (missile_on, guns_on) = engagement_counts(&self.sams);
|
|
||||||
let drone_at = |id: u32| self.drones.iter().find(|d| d.id == id);
|
|
||||||
let subject = chosen
|
|
||||||
.and_then(drone_at)
|
|
||||||
.filter(|d| d.alive())
|
|
||||||
.or_else(|| sam.target.or(sam.gun_target).and_then(drone_at).filter(|d| d.alive()))
|
|
||||||
.or_else(|| {
|
|
||||||
self.drones
|
|
||||||
.iter()
|
|
||||||
.filter(|d| {
|
|
||||||
d.alive()
|
|
||||||
&& (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles))
|
|
||||||
|| last_chance(self.last_chance, sam.roles, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target)))
|
|
||||||
})
|
|
||||||
.max_by(|a, b| {
|
|
||||||
let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, now) == 0);
|
|
||||||
area(a).cmp(&area(b)).then(a.threat(sam.pos).total_cmp(&b.threat(sam.pos)))
|
|
||||||
})
|
|
||||||
});
|
|
||||||
let Some(t) = subject else {
|
|
||||||
let block = if sam.roles == 0 {
|
|
||||||
BattleBlock::Hold
|
|
||||||
} else if self.drones.iter().any(|d| d.alive() && sam.seen.contains(&d.id)) {
|
|
||||||
BattleBlock::OutOfRoles
|
|
||||||
} else {
|
|
||||||
BattleBlock::NoTarget
|
|
||||||
};
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(block), None, None));
|
|
||||||
};
|
|
||||||
let track = sam.track(t.id);
|
|
||||||
let mark = track.map(|tr| BattleMark::of(self, sam, tr, now));
|
|
||||||
let has_missile = spec.missile.is_some() && sam.missiles > 0 && sam.part(Part::Launcher) > 0.0;
|
|
||||||
let has_gun = spec.gun.is_some() && sam.bursts > 0 && sam.part(Part::Gun) > 0.0;
|
|
||||||
if sam.reloading > 0 || (!has_missile && !has_gun) {
|
|
||||||
return Some(reason(BattleKind::NoAmmo, None, Some(t.id), mark));
|
|
||||||
}
|
|
||||||
if spec.missile.is_some() && sam.part(Part::Launcher) <= 0.0 && !has_gun {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::LauncherDown), Some(t.id), mark));
|
|
||||||
}
|
|
||||||
let Some(tr) = track else {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoTrack), Some(t.id), mark));
|
|
||||||
};
|
|
||||||
let est = tr.class;
|
|
||||||
let blocks = target_blocks(sam.roles, Some(tr), now, t);
|
|
||||||
let claimed_now = claimed(t, &missile_on, sam.target);
|
|
||||||
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, t, claimed_now);
|
|
||||||
if blocks & ROLE != 0 && !chance {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(if sam.roles == 0 { BattleBlock::Hold } else { BattleBlock::OutOfRoles }), Some(t.id), mark));
|
|
||||||
}
|
|
||||||
let doc = &sam.doctrine;
|
|
||||||
let area = doc.area_blocks(sam.pos, tr, now);
|
|
||||||
let reserve = spec.missile.is_some().then(|| doc.reserve_blocks(sam.missiles, t, est)).unwrap_or(0);
|
|
||||||
if blocks & ROLE == 0 && (area | reserve) != 0 {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Doctrine), Some(t.id), mark));
|
|
||||||
}
|
|
||||||
let est_at = tr.est(now);
|
|
||||||
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
|
|
||||||
let cued = radar_cue(sam, &radars, t.id, now);
|
|
||||||
let role_in_reach = spec.missile.as_ref().is_some_and(|load| {
|
|
||||||
self.drones.iter().any(|o| {
|
|
||||||
sam.track(o.id).is_some_and(|other| {
|
|
||||||
allowed(sam.roles, other, now, o)
|
|
||||||
&& in_reach(load.min, load.max, 1.0, sam.pos, other.est(now))
|
|
||||||
&& doc.area_blocks(sam.pos, other, now) | doc.reserve_blocks(sam.missiles, o, other.class) == 0
|
|
||||||
&& claimed(o, &missile_on, sam.target) < doc.needed(o, other.class)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
});
|
|
||||||
let reach = spec.missile.as_ref().map_or(0, |load| reach_blocks(load.min, load.max, 1.0, sam.pos, est_at));
|
|
||||||
let far_ok = spec.missile.as_ref().is_some_and(|load| {
|
|
||||||
reach == TOO_FAR
|
|
||||||
&& reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0
|
|
||||||
&& far_blocks(self.far_shots, sam, load, cued, role_in_reach) == 0
|
|
||||||
});
|
|
||||||
if spec.missile.is_some() {
|
|
||||||
if reach == TOO_CLOSE || (reach == TOO_FAR && !far_ok) {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::OutOfReach), Some(t.id), mark));
|
|
||||||
}
|
|
||||||
} else if let Some(gun) = &spec.gun {
|
|
||||||
if sam.mount().0.distance(est_at) >= gun.range {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::OutOfReach), Some(t.id), mark));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let own_fire = tr.own_authorizes(now);
|
|
||||||
let gun_ready = spec.gun.is_some() && tr.own_within(now, sight::GUN_PICK_AGE);
|
|
||||||
let authorized = if spec.missile.is_some() {
|
|
||||||
own_fire || (sam.mode == battery::SamMode::LauncherOnly && cued) || far_ok
|
|
||||||
} else {
|
|
||||||
gun_ready
|
|
||||||
};
|
|
||||||
if !authorized {
|
|
||||||
if sam.mode == battery::SamMode::LauncherOnly {
|
|
||||||
// The launcher's picture is the supporting radar's. If that radar has the
|
|
||||||
// contact but every tracked-contact channel is taken, the reason is the
|
|
||||||
// channels, not a missing hand-off.
|
|
||||||
let support = radars.iter().find_map(|r| {
|
|
||||||
let linked = r.alive()
|
|
||||||
&& !r.moving()
|
|
||||||
&& r.radar_up()
|
|
||||||
&& r.radar_profile().products & battery::RadarProfile::FIRE_BIT != 0
|
|
||||||
&& r.link_range() > 0.0
|
|
||||||
&& sam.link_range() > 0.0
|
|
||||||
&& r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range());
|
|
||||||
linked.then(|| r.track(t.id).map(|tr| (*r, *tr))).flatten()
|
|
||||||
});
|
|
||||||
if let Some((radar, tr)) = support {
|
|
||||||
let profile = radar.radar_profile();
|
|
||||||
let used = radar.own_channels_used(now);
|
|
||||||
if profile.channels > 0 && used >= profile.channels as usize && !tr.own_authorizes(now) {
|
|
||||||
let mut busy = reason(BattleKind::ChannelsBusy, None, Some(t.id), mark);
|
|
||||||
busy.channels = Some((used, profile.channels));
|
|
||||||
return Some(busy);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark));
|
|
||||||
}
|
|
||||||
let busy = channels.is_some_and(|(used, total)| used >= total as usize);
|
|
||||||
if busy {
|
|
||||||
return Some(reason(BattleKind::ChannelsBusy, None, Some(t.id), mark));
|
|
||||||
}
|
|
||||||
if tr.own_tick > 0 && tr.own_product == battery::Measure::Refine {
|
|
||||||
return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark));
|
|
||||||
}
|
|
||||||
if tr.own_tick > 0 && tr.own_product == battery::Measure::Fire {
|
|
||||||
return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark));
|
|
||||||
}
|
|
||||||
return Some(reason(BattleKind::ObserveOnly, None, Some(t.id), mark));
|
|
||||||
}
|
|
||||||
let need = doc.needed(t, est);
|
|
||||||
if spec.missile.is_some() && claimed_now >= need {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Claimed), Some(t.id), mark));
|
|
||||||
}
|
|
||||||
if spec.missile.is_none() && guns_on.get(&t.id).copied().unwrap_or(0) > 1 {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Claimed), Some(t.id), mark));
|
|
||||||
}
|
|
||||||
let mount = sam.mount().0;
|
|
||||||
let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell);
|
|
||||||
let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, tr.vel, lead_speed);
|
|
||||||
if aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch) >= 0.15 {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Aiming), Some(t.id), mark));
|
|
||||||
}
|
|
||||||
if sam.preparing.is_some() {
|
|
||||||
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Preparing), Some(t.id), mark));
|
|
||||||
}
|
|
||||||
Some(reason(BattleKind::Ready, None, Some(t.id), mark))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
@@ -616,20 +310,6 @@ fn check(ok: bool, text: impl Into<String>) -> Check {
|
|||||||
Check { ok, reason: CheckReason::Text(text.into()) }
|
Check { ok, reason: CheckReason::Text(text.into()) }
|
||||||
}
|
}
|
||||||
fn part_check(reason: CheckReason) -> Check { Check { ok: false, reason } }
|
fn part_check(reason: CheckReason) -> Check { Check { ok: false, reason } }
|
||||||
fn battle_check(reason: Option<BattleReason>) -> Check {
|
|
||||||
let reason = reason.unwrap_or(BattleReason {
|
|
||||||
kind: BattleKind::Blocked,
|
|
||||||
block: Some(BattleBlock::Other),
|
|
||||||
sam: 0,
|
|
||||||
target: None,
|
|
||||||
mark: None,
|
|
||||||
rounds: 0,
|
|
||||||
bursts: 0,
|
|
||||||
reloading: 0,
|
|
||||||
channels: None,
|
|
||||||
});
|
|
||||||
Check { ok: reason.ready(), reason: CheckReason::Battle(reason) }
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Sim {
|
impl Sim {
|
||||||
/// Why system `index` fires or doesn't, at its current target or at the most threatening
|
/// Why system `index` fires or doesn't, at its current target or at the most threatening
|
||||||
@@ -641,17 +321,14 @@ impl Sim {
|
|||||||
let mut v = vec![check(true, format!("№{} {}: {}", index + 1, spec.name, sam.state.name()))];
|
let mut v = vec![check(true, format!("№{} {}: {}", index + 1, spec.name, sam.state.name()))];
|
||||||
if !sam.alive() {
|
if !sam.alive() {
|
||||||
v.push(check(false, "уничтожен"));
|
v.push(check(false, "уничтожен"));
|
||||||
v.push(battle_check(self.battle_reason(index)));
|
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
if self.hold {
|
if self.hold {
|
||||||
v.push(check(false, "огонь запрещён (/airdef hold off)"));
|
v.push(check(false, "огонь запрещён (/airdef hold off)"));
|
||||||
v.push(battle_check(self.battle_reason(index)));
|
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
if sam.moving() {
|
if sam.moving() {
|
||||||
v.push(check(false, format!("{}: не стреляет", sam.state.name().to_lowercase())));
|
v.push(check(false, format!("{}: не стреляет", sam.state.name().to_lowercase())));
|
||||||
v.push(battle_check(self.battle_reason(index)));
|
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
if !sam.kind.armed() {
|
if !sam.kind.armed() {
|
||||||
@@ -667,8 +344,8 @@ impl Sim {
|
|||||||
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
|
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
|
||||||
)));
|
)));
|
||||||
v.push(check(true, format!("ограничение: {}", profile.limit)));
|
v.push(check(true, format!("ограничение: {}", profile.limit)));
|
||||||
|
v.push(check(true, format!("свои треки: {}, каналы {}/{}", sam.own.len(), sam.own_channels_used(), profile.channels)));
|
||||||
let now = self.tick;
|
let now = self.tick;
|
||||||
v.push(check(true, format!("свои треки: {}, каналы {}/{}", sam.own.len(), sam.own_channels_used(now), profile.channels)));
|
|
||||||
let mut tracks: Vec<&Track> = sam.tracks.iter().filter(|t| t.own_tick > 0).collect();
|
let mut tracks: Vec<&Track> = sam.tracks.iter().filter(|t| t.own_tick > 0).collect();
|
||||||
tracks.sort_by_key(|t| std::cmp::Reverse(t.quality));
|
tracks.sort_by_key(|t| std::cmp::Reverse(t.quality));
|
||||||
for t in tracks.into_iter().take(4) {
|
for t in tracks.into_iter().take(4) {
|
||||||
@@ -687,7 +364,6 @@ impl Sim {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
v.push(check(false, "нет оружия (РЛС, склад, РЭБ, прожектор)"));
|
v.push(check(false, "нет оружия (РЛС, склад, РЭБ, прожектор)"));
|
||||||
v.push(battle_check(self.battle_reason(index)));
|
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
let logistics = self.logistics();
|
let logistics = self.logistics();
|
||||||
@@ -754,7 +430,6 @@ impl Sim {
|
|||||||
format!("нет целей классов [{}]", roles_text(sam.roles))
|
format!("нет целей классов [{}]", roles_text(sam.roles))
|
||||||
};
|
};
|
||||||
v.push(check(false, text));
|
v.push(check(false, text));
|
||||||
v.push(battle_check(self.battle_reason(index)));
|
|
||||||
return v;
|
return v;
|
||||||
};
|
};
|
||||||
let held = sam.target == Some(t.id) || sam.gun_target == Some(t.id);
|
let held = sam.target == Some(t.id) || sam.gun_target == Some(t.id);
|
||||||
@@ -969,21 +644,6 @@ impl Sim {
|
|||||||
fires &= !opening;
|
fires &= !opening;
|
||||||
}
|
}
|
||||||
v.push(check(fires, if fires { "итог: готова стрелять" } else { "итог: стрелять сейчас не может" }));
|
v.push(check(fires, if fires { "итог: готова стрелять" } else { "итог: стрелять сейчас не может" }));
|
||||||
// The one typed reason the monitor, the HUD and the chat show first; the detailed checks
|
|
||||||
// below it explain it. The launch decision above has the final word.
|
|
||||||
let mut headline = self.battle_reason_at(index, Some(t.id)).unwrap_or_else(|| BattleReason {
|
|
||||||
kind: BattleKind::Blocked,
|
|
||||||
block: Some(BattleBlock::Other),
|
|
||||||
sam: index,
|
|
||||||
target: Some(t.id),
|
|
||||||
mark: track.map(|tr| BattleMark::of(self, sam, tr, now)),
|
|
||||||
rounds: sam.missiles,
|
|
||||||
bursts: sam.bursts,
|
|
||||||
reloading: sam.reloading,
|
|
||||||
channels: None,
|
|
||||||
});
|
|
||||||
headline.settle(fires);
|
|
||||||
v.insert(1, Check { ok: headline.ready(), reason: CheckReason::Battle(headline) });
|
|
||||||
v
|
v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1356,129 +1016,6 @@ mod tests {
|
|||||||
assert!((reach_fit(100.0, 400.0) - 0.5).abs() < 1e-9);
|
assert!((reach_fit(100.0, 400.0) - 0.5).abs() < 1e-9);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A track as the battery's picture holds it, from `source`, measured by the battery's own
|
|
||||||
/// radar `own` ticks ago.
|
|
||||||
fn seeded_track(id: u32, source: u32, own_tick: u64, product: battery::Measure, now: u64) -> Track {
|
|
||||||
Track {
|
|
||||||
id,
|
|
||||||
class: ClassEst::Firm(Class::Drone),
|
|
||||||
pos: DVec3::new(0.0, 75.0, -100.0),
|
|
||||||
vel: DVec3::Z,
|
|
||||||
tick: now,
|
|
||||||
own_tick,
|
|
||||||
source,
|
|
||||||
product,
|
|
||||||
quality: 90,
|
|
||||||
own_product: product,
|
|
||||||
own_quality: if own_tick > 0 { 90 } else { 0 },
|
|
||||||
ttl: 400,
|
|
||||||
hits: 3,
|
|
||||||
locked: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_headline_reason_names_observation_waiting_channels_and_ammo() {
|
|
||||||
// Есть только обзор: the contact is on the network's picture, the battery's own radar
|
|
||||||
// has no fire plot, and no channel of its own is taken.
|
|
||||||
let mut sim = Sim::new(7);
|
|
||||||
let id = sim.id();
|
|
||||||
sim.sams.push(Sam::new(id, SamKind::Pantsir, DVec3::new(0.0, 70.0, 0.0), 0.0));
|
|
||||||
let radar = sim.id();
|
|
||||||
sim.sams.push(Sam::new(radar, SamKind::Radar, DVec3::new(50.0, 70.0, 0.0), 0.0));
|
|
||||||
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -100.0), DVec3::Z, DVec3::new(0.0, 70.0, -100.0));
|
|
||||||
let target = sim.drones[0].id;
|
|
||||||
let now = sim.tick;
|
|
||||||
sim.sams[0].tracks.push(seeded_track(target, radar, 0, battery::Measure::Search, now));
|
|
||||||
let reason = sim.battle_reason(0).expect("a reason");
|
|
||||||
assert_eq!(reason.kind, BattleKind::ObserveOnly, "{reason:?}");
|
|
||||||
let mark = reason.mark.expect("the mark");
|
|
||||||
assert_eq!(mark.source, Some(1));
|
|
||||||
assert!(!mark.own);
|
|
||||||
assert_eq!(mark.age, 0);
|
|
||||||
|
|
||||||
// Ждёт сопровождения: a launcher without its own radar waits for the supporting radar's
|
|
||||||
// fire plot; the same network mark is not enough.
|
|
||||||
let mut sim = Sim::new(8);
|
|
||||||
let id = sim.id();
|
|
||||||
let mut launcher = Sam::new(id, SamKind::S400, DVec3::new(0.0, 70.0, 0.0), 0.0);
|
|
||||||
launcher.set_mode(battery::SamMode::LauncherOnly);
|
|
||||||
sim.sams.push(launcher);
|
|
||||||
let radar = sim.id();
|
|
||||||
let mut station = Sam::new(radar, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0), 0.0);
|
|
||||||
station.set_radar_role(battery::RadarRole::Engagement);
|
|
||||||
sim.sams.push(station);
|
|
||||||
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, -300.0), DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
|
|
||||||
let target = sim.drones[0].id;
|
|
||||||
let now = 1;
|
|
||||||
sim.sams[0].tracks.push(seeded_track(target, radar, 0, battery::Measure::Search, now));
|
|
||||||
assert_eq!(sim.battle_reason(0).expect("a reason").kind, BattleKind::AwaitingTrack);
|
|
||||||
|
|
||||||
// Каналы заняты: the supporting radar has the contact but both tracked-contact channels
|
|
||||||
// are held by other contacts.
|
|
||||||
sim.sams[1].tracks.push(seeded_track(901, radar, now, battery::Measure::Fire, now));
|
|
||||||
sim.sams[1].tracks.push(seeded_track(902, radar, now, battery::Measure::Fire, now));
|
|
||||||
sim.sams[1].tracks.push(seeded_track(target, radar, now, battery::Measure::Search, now));
|
|
||||||
let reason = sim.battle_reason(0).expect("a reason");
|
|
||||||
assert_eq!(reason.kind, BattleKind::ChannelsBusy, "{reason:?}");
|
|
||||||
assert_eq!(reason.channels, Some((2, 2)));
|
|
||||||
|
|
||||||
// Нет боезапаса: no rounds and no shells.
|
|
||||||
let mut sim = Sim::new(9);
|
|
||||||
let id = sim.id();
|
|
||||||
let mut sam = Sam::new(id, SamKind::Pantsir, DVec3::new(0.0, 70.0, 0.0), 0.0);
|
|
||||||
sam.missiles = 0;
|
|
||||||
sam.bursts = 0;
|
|
||||||
sim.sams.push(sam);
|
|
||||||
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -100.0), DVec3::Z, DVec3::new(0.0, 70.0, -100.0));
|
|
||||||
let target = sim.drones[0].id;
|
|
||||||
let now = sim.tick;
|
|
||||||
sim.sams[0].tracks.push(seeded_track(target, id, now, battery::Measure::Fire, now));
|
|
||||||
let reason = sim.battle_reason(0).expect("a reason");
|
|
||||||
assert_eq!(reason.kind, BattleKind::NoAmmo, "{reason:?}");
|
|
||||||
assert_eq!((reason.rounds, reason.bursts), (0, 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_headline_reason_can_say_ready_and_defers_to_the_launch_decision() {
|
|
||||||
let mut sim = Sim::new(11);
|
|
||||||
let id = sim.id();
|
|
||||||
sim.sams.push(Sam::new(id, SamKind::S400, DVec3::new(0.0, 70.0, 0.0), 0.0));
|
|
||||||
sim.sams[0].cooldown = 0;
|
|
||||||
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, -300.0), DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
|
|
||||||
let d = sim.drones[0].clone();
|
|
||||||
let now = 1;
|
|
||||||
sim.sams[0].yaw = heading_of(d.pos - sim.sams[0].pos);
|
|
||||||
sim.sams[0].tracks.push(Track {
|
|
||||||
id: d.id,
|
|
||||||
class: ClassEst::Firm(Class::Cruise),
|
|
||||||
pos: d.pos,
|
|
||||||
vel: d.vel,
|
|
||||||
tick: now,
|
|
||||||
own_tick: now,
|
|
||||||
source: id,
|
|
||||||
product: battery::Measure::Fire,
|
|
||||||
quality: 90,
|
|
||||||
own_product: battery::Measure::Fire,
|
|
||||||
own_quality: 90,
|
|
||||||
ttl: 400,
|
|
||||||
hits: 3,
|
|
||||||
locked: false,
|
|
||||||
});
|
|
||||||
let reason = sim.battle_reason(0).expect("a reason");
|
|
||||||
assert_eq!(reason.kind, BattleKind::Ready, "{reason:?}");
|
|
||||||
// The detailed decision is the authority when the two are settled together.
|
|
||||||
let mut blocked = reason;
|
|
||||||
blocked.settle(false);
|
|
||||||
assert_eq!(blocked.kind, BattleKind::Blocked);
|
|
||||||
let mut ready = reason;
|
|
||||||
ready.settle(true);
|
|
||||||
assert_eq!(ready.kind, BattleKind::Ready);
|
|
||||||
// In the diagnostic the typed line is the headline, second only to the state.
|
|
||||||
let checks = sim.why(0);
|
|
||||||
assert!(matches!(checks.get(1).map(|c| &c.reason), Some(CheckReason::Battle(r)) if r.kind == BattleKind::Ready), "{checks:?}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn every_interceptor_lives_long_enough_to_fly_its_reach() {
|
fn every_interceptor_lives_long_enough_to_fly_its_reach() {
|
||||||
// Life × top speed must cover the far end of a heavy system's reach with room to chase; the rest their plain reach.
|
// Life × top speed must cover the far end of a heavy system's reach with room to chase; the rest their plain reach.
|
||||||
|
|||||||
+1
-107
@@ -1,5 +1,5 @@
|
|||||||
//! Text for diagnostics produced by the simulation.
|
//! Text for diagnostics produced by the simulation.
|
||||||
use crate::sim::why::{BattleBlock, BattleKind, BattleMark, BattleReason, CheckReason, PartEffect};
|
use crate::sim::why::{CheckReason, PartEffect};
|
||||||
use crate::sim::{Comps, Part, SamKind};
|
use crate::sim::{Comps, Part, SamKind};
|
||||||
|
|
||||||
fn part_value(part: Part, value: f64) -> String {
|
fn part_value(part: Part, value: f64) -> String {
|
||||||
@@ -25,81 +25,9 @@ pub fn worst(comps: &Comps, kind: SamKind) -> String {
|
|||||||
.map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default()
|
.map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The mark's age and where it came from, in the battery's own picture: a relayed plot names
|
|
||||||
/// its station, never the target's true place or kind.
|
|
||||||
fn mark_text(mark: &BattleMark) -> String {
|
|
||||||
let age = if mark.age == 0 { "сейчас".to_string() } else { format!("{:.1} с назад", mark.age as f64 / 20.0) };
|
|
||||||
let source = if mark.own {
|
|
||||||
"своя РЛС".to_string()
|
|
||||||
} else {
|
|
||||||
mark.source.map_or_else(|| "сеть".to_string(), |i| format!("сеть, РЛС №{}", i + 1))
|
|
||||||
};
|
|
||||||
let mut own = String::new();
|
|
||||||
if let Some(product) = mark.own_product {
|
|
||||||
if !mark.own {
|
|
||||||
own = format!(", своё измерение: {}", product.name());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let forecast = if mark.forecast { ", прогноз" } else { "" };
|
|
||||||
format!(
|
|
||||||
"отметка {age}, источник {source}, {} кач.{} {}{}{forecast}",
|
|
||||||
mark.product.name(),
|
|
||||||
mark.quality,
|
|
||||||
mark.class.name(),
|
|
||||||
own
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn with_mark(text: String, mark: Option<BattleMark>) -> String {
|
|
||||||
match mark {
|
|
||||||
Some(mark) => format!("{text}: {}", mark_text(&mark)),
|
|
||||||
None => text,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one headline reason a battery fires or not, as the player reads it.
|
|
||||||
pub fn battle_text(reason: &BattleReason) -> String {
|
|
||||||
match reason.kind {
|
|
||||||
BattleKind::Ready => with_mark("готов к пуску".into(), reason.mark),
|
|
||||||
BattleKind::ObserveOnly => with_mark("есть только обзор, пуск не разрешён — нужно своё подтверждённое измерение".into(), reason.mark),
|
|
||||||
BattleKind::AwaitingTrack => with_mark("ждёт сопровождения — своё измерение ещё не разрешает пуск".into(), reason.mark),
|
|
||||||
BattleKind::ChannelsBusy => {
|
|
||||||
let channels = reason.channels.map_or_else(|| "каналы заняты".to_string(), |(used, total)| format!("каналы заняты: {used}/{total}"));
|
|
||||||
with_mark(channels, reason.mark)
|
|
||||||
}
|
|
||||||
BattleKind::NoAmmo => {
|
|
||||||
let mut text = format!("нет боезапаса: ракет {}, очередей {}", reason.rounds, reason.bursts);
|
|
||||||
if reason.reloading > 0 {
|
|
||||||
text += &format!(", перезарядка ещё {:.1} с", reason.reloading as f64 / 20.0);
|
|
||||||
}
|
|
||||||
with_mark(text, reason.mark)
|
|
||||||
}
|
|
||||||
BattleKind::Blocked => {
|
|
||||||
let text = match reason.block {
|
|
||||||
Some(BattleBlock::Destroyed) => "уничтожен".to_string(),
|
|
||||||
Some(BattleBlock::Moving) => "на марше, не стреляет".to_string(),
|
|
||||||
Some(BattleBlock::Hold) => "огонь запрещён или роли не заданы".to_string(),
|
|
||||||
Some(BattleBlock::NoWeapon) => "нет оружия (РЛС, склад, РЭБ, прожектор)".to_string(),
|
|
||||||
Some(BattleBlock::NoTarget) => "нет целей в небе".to_string(),
|
|
||||||
Some(BattleBlock::NoTrack) => "цель не обнаружена своей РЛС или сетью".to_string(),
|
|
||||||
Some(BattleBlock::OutOfRoles) => "цель вне ролей комплекса".to_string(),
|
|
||||||
Some(BattleBlock::OutOfReach) => "цель вне дальности".to_string(),
|
|
||||||
Some(BattleBlock::Claimed) => "цель уже занята перехватчиками".to_string(),
|
|
||||||
Some(BattleBlock::Doctrine) => "запрещено доктриной (сектор, охрана или резерв)".to_string(),
|
|
||||||
Some(BattleBlock::Aiming) => "ещё доворачивается на цель".to_string(),
|
|
||||||
Some(BattleBlock::Preparing) => "открывает ТПК".to_string(),
|
|
||||||
Some(BattleBlock::LauncherDown) => "пусковая отказала".to_string(),
|
|
||||||
Some(BattleBlock::Other) | None => "стрелять сейчас не может".to_string(),
|
|
||||||
};
|
|
||||||
with_mark(text, reason.mark)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn reason(reason: &CheckReason) -> String {
|
pub fn reason(reason: &CheckReason) -> String {
|
||||||
match reason {
|
match reason {
|
||||||
CheckReason::Text(text) => text.clone(),
|
CheckReason::Text(text) => text.clone(),
|
||||||
CheckReason::Battle(battle) => battle_text(battle),
|
|
||||||
CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| part_value(*part, *value)).collect::<Vec<_>>().join(", ")),
|
CheckReason::Parts(parts) => format!("узлы: {}", parts.iter().map(|(part, value)| part_value(*part, *value)).collect::<Vec<_>>().join(", ")),
|
||||||
CheckReason::PartEffect(effect) => match effect {
|
CheckReason::PartEffect(effect) => match effect {
|
||||||
PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(),
|
PartEffect::SensorFailed => "РЛС отказала: своих измерений нет, стволы не стреляют, ракеты — по данным сети".into(),
|
||||||
@@ -151,40 +79,6 @@ mod tests {
|
|||||||
assert!(summary < sensor && sensor < tracks, "{lines:?}");
|
assert!(summary < sensor && sensor < tracks, "{lines:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_headline_reason_shows_the_marks_age_and_source_without_the_true_kind() {
|
|
||||||
use crate::sim::battery::Measure;
|
|
||||||
use crate::sim::ClassEst;
|
|
||||||
let mark = BattleMark {
|
|
||||||
age: 46,
|
|
||||||
own_age: None,
|
|
||||||
source: Some(2),
|
|
||||||
own: false,
|
|
||||||
product: Measure::Search,
|
|
||||||
quality: 40,
|
|
||||||
own_product: None,
|
|
||||||
forecast: false,
|
|
||||||
class: ClassEst::Unknown,
|
|
||||||
};
|
|
||||||
let reason = BattleReason {
|
|
||||||
kind: BattleKind::ObserveOnly,
|
|
||||||
block: None,
|
|
||||||
sam: 0,
|
|
||||||
target: Some(7),
|
|
||||||
mark: Some(mark),
|
|
||||||
rounds: 4,
|
|
||||||
bursts: 0,
|
|
||||||
reloading: 0,
|
|
||||||
channels: None,
|
|
||||||
};
|
|
||||||
let text = battle_text(&reason);
|
|
||||||
assert!(text.starts_with("есть только обзор"), "{text}");
|
|
||||||
assert!(text.contains("2.3 с назад"), "{text}");
|
|
||||||
assert!(text.contains("источник сеть, РЛС №3"), "{text}");
|
|
||||||
assert!(text.contains("тип не определён"), "{text}");
|
|
||||||
assert!(!text.contains("Шахед"), "the true kind leaked into the HUD: {text}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn renders_damage_diagnostics() {
|
fn renders_damage_diagnostics() {
|
||||||
assert_eq!(reason(&CheckReason::Parts(vec![(Part::Sensor, 0.4), (Part::Tracks, 0.0)])), "узлы: РЛС 40%, Ход отказ");
|
assert_eq!(reason(&CheckReason::Parts(vec![(Part::Sensor, 0.4), (Part::Tracks, 0.0)])), "узлы: РЛС 40%, Ход отказ");
|
||||||
|
|||||||
@@ -50,8 +50,7 @@ expect.feedback = "№2 С-400: режим launcher"
|
|||||||
[[step]]
|
[[step]]
|
||||||
command = "airdef deploy radar_track"
|
command = "airdef deploy radar_track"
|
||||||
|
|
||||||
# The profile is chosen at deployment (#134): the old role switch is refused,
|
# A deployed radar keeps its equipment profile; only its emissions can be switched.
|
||||||
# and says where the profile comes from instead of retuning the station.
|
|
||||||
[[step]]
|
[[step]]
|
||||||
command = "airdef radar 4 search"
|
command = "airdef radar 4 search"
|
||||||
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в search не меняет оборудование. Доступно on/off."
|
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в search не меняет оборудование. Доступно on/off."
|
||||||
|
|||||||
@@ -65,9 +65,7 @@
|
|||||||
|
|
||||||
Сеть передаёт трек вместе с измерившей станцией, возрастом и качеством. Повторная пересылка не
|
Сеть передаёт трек вместе с измерившей станцией, возрастом и качеством. Повторная пересылка не
|
||||||
освежает измерение и не создаёт права на пуск. Уточнение применяется только к сопоставленному
|
освежает измерение и не создаёт права на пуск. Уточнение применяется только к сопоставленному
|
||||||
контакту, а число каналов ограничено на каждом тике. Канал удерживает только собственное измерение
|
контакту, а число каналов ограничено на каждом тике. Если РЛС сопровождения уничтожена, свёрнута,
|
||||||
станции: когда оно устаревает (станция больше не измеряет контакт), канал освобождается для новой
|
|
||||||
цели, а сетевой обзорный трек остаётся на месте. Если РЛС сопровождения уничтожена, свёрнута,
|
|
||||||
потеряла связь или её измерение устарело, новые пуски прекращаются. Уже вылетевшие ракеты
|
потеряла связь или её измерение устарело, новые пуски прекращаются. Уже вылетевшие ракеты
|
||||||
продолжают штатную игровую логику связи/памяти/самонаведения.
|
продолжают штатную игровую логику связи/памяти/самонаведения.
|
||||||
|
|
||||||
|
|||||||
+1
-4
@@ -254,10 +254,7 @@ HORIZON_HD_TAA=0 --out run-home-bench/out/taa-off` — A/B; `--baseline run-home
|
|||||||
масштаба (`HORIZON_HD_SCALE` или поле в `HdSettings`). Цель: при 0.67 картинка близка к нативной, FPS заметно
|
масштаба (`HORIZON_HD_SCALE` или поле в `HdSettings`). Цель: при 0.67 картинка близка к нативной, FPS заметно
|
||||||
выше. #124 развивает этот путь в общий temporal backend: `ed751714e` добавляет optional `dlss` feature
|
выше. #124 развивает этот путь в общий temporal backend: `ed751714e` добавляет optional `dlss` feature
|
||||||
и `HORIZON_DLSS=1`, previous-frame motion, NGX+HDR bootstrap и display↔linear conversion. Submit:
|
и `HORIZON_DLSS=1`, previous-frame motion, NGX+HDR bootstrap и display↔linear conversion. Submit:
|
||||||
world+linearize → NGX → delinearize; native TAAU остаётся fallback. #137 довёл порядок до контракта:
|
world+linearize → NGX → delinearize; native TAAU остаётся fallback. По умолчанию DLSS рендерит world 2/3,
|
||||||
film/tonemap/UI/capture/present записываются в encoder после delinearize и отправляются одним submit
|
|
||||||
без CPU sync (раньше они читали `taa.target` до записи NGX), а готовность нативной истории отделена от
|
|
||||||
истории NGX — первый fallback-кадр после DLSS не читает пустую/устаревшую native history. По умолчанию DLSS рендерит world 2/3,
|
|
||||||
`HORIZON_HD_SCALE` переопределяет это. Сборка требует `DLSS_SDK` (v310.9.1), `VULKAN_SDK`, clang и
|
`HORIZON_HD_SCALE` переопределяет это. Сборка требует `DLSS_SDK` (v310.9.1), `VULKAN_SDK`, clang и
|
||||||
`--features dlss`; runtime DLL/SO и NVIDIA notices нужны рядом с приложением, не в Git. Полный `cargo xwin build`
|
`--features dlss`; runtime DLL/SO и NVIDIA notices нужны рядом с приложением, не в Git. Полный `cargo xwin build`
|
||||||
на MSVC и prerelease `v0.4.0-dlss-rc1` опубликованы; реальный RTX/Vulkan runtime ещё не проверен.
|
на MSVC и prerelease `v0.4.0-dlss-rc1` опубликованы; реальный RTX/Vulkan runtime ещё не проверен.
|
||||||
|
|||||||
@@ -33,33 +33,6 @@
|
|||||||
137346889/300M, command 129151/1B, failures=0. Лимит памяти 64 MiB не увеличивался. Это
|
137346889/300M, command 129151/1B, failures=0. Лимит памяти 64 MiB не увеличивался. Это
|
||||||
синтетический host без GPU и не приёмка Windows GUI.
|
синтетический host без GPU и не приёмка Windows GUI.
|
||||||
|
|
||||||
### Прореживание не съедает короткие переходы (#142)
|
|
||||||
|
|
||||||
Прореживание #122 не различало непрерывную позу и дискретный факт: при большом числе меняющихся
|
|
||||||
РЛС оно пропускало целиком открытие крышки ТПК (`launch::OPEN_TICKS = 6` тиков, короче шага
|
|
||||||
sampling) и могло убрать уже записанный переход — ракета в реплее вылетала с нарисованной
|
|
||||||
закрытой крышкой, а `spent_cells` менялось только на следующем общем сэмпле.
|
|
||||||
|
|
||||||
Теперь `Recording::note_sams` вызывается каждый тик: позы по-прежнему снимаются на адаптивной
|
|
||||||
сетке `sam_step` из прежнего бюджета 32768, а дискретные переходы (`cap_cell`, `spent_cells`,
|
|
||||||
`radar_on`, режим и роль) и кадры открытия крышки пишутся на том тике, когда произошли, и
|
|
||||||
помечаются как события. Начало открытия дотягивается отдельным ключом на тик раньше, поэтому
|
|
||||||
ramp занимает ровно `OPEN_TICKS`, а не «примерно». Прореживание поз половинит только позы и
|
|
||||||
сохраняет события, первую и последнюю позу.
|
|
||||||
|
|
||||||
У событий свой явный бюджет — 4096 ключей на запись поверх 32768 поз; общий бюджет поз не
|
|
||||||
поднимался. При переполнении старые события перестают быть критическими (прореживаются как
|
|
||||||
позы), новейшие сохраняются: под записью с «болтливым» датчиком реплей остаётся ограниченным,
|
|
||||||
а свежий пуск — точным.
|
|
||||||
|
|
||||||
Проверки: `airdef-core` `sim::record::tests::decimation_keeps_a_cold_launch_cover_ejection_and_the_radar_switch`
|
|
||||||
— 64 вращающихся РЛС + С-400 при `sam_step = 16`, выброс на тике 4103: за тик до выброса
|
|
||||||
`cap_open = 0.8333333` (как в контрольной записи без давления на бюджет), `spent_cells = 0`
|
|
||||||
до и `1` на тике выброса, отмена/закрытие и `radar_on` читаются на своих тиках, повторное
|
|
||||||
прореживание их не убирает;
|
|
||||||
`critical_transitions_have_their_own_explicit_budget` — 64 РЛС, переключающихся каждый тик,
|
|
||||||
1500 тиков: событий ровно 4096, позы в своём бюджете, новейшее переключение точное.
|
|
||||||
|
|
||||||
## Второй налёт из UI: событие, не тик
|
## Второй налёт из UI: событие, не тик
|
||||||
|
|
||||||
Точный лог Windows: `Horizon: mod airdef stopped in UI event (fuel budget 1000000000,
|
Точный лог Windows: `Horizon: mod airdef stopped in UI event (fuel budget 1000000000,
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
{
|
|
||||||
"schema": 1,
|
|
||||||
"issue": 150,
|
|
||||||
"world": "ReplayRanges150",
|
|
||||||
"branch": "agent/150-replay-ranges",
|
|
||||||
"code_commit": "agent/150-replay-ranges (this branch; see git log for the exact SHA)",
|
|
||||||
"bench": "cargo run --release --example replay_bench --features bench-counters (airdef-mod; native, one machine)",
|
|
||||||
"journal": {
|
|
||||||
"ticks": 12000,
|
|
||||||
"seconds": 600,
|
|
||||||
"events": 64000,
|
|
||||||
"scene_events": 65000,
|
|
||||||
"cap_events": 65536,
|
|
||||||
"cap_scene_events": 65536,
|
|
||||||
"note": "a 10-minute raid with both journals nearly full"
|
|
||||||
},
|
|
||||||
"modes": [
|
|
||||||
{
|
|
||||||
"mode": "playback",
|
|
||||||
"frames": 600,
|
|
||||||
"journal_events": 64000,
|
|
||||||
"journal_scene": 65000,
|
|
||||||
"scanned_events": 1203211,
|
|
||||||
"scanned_per_frame": 2005.4,
|
|
||||||
"full_pass_events": 77400000,
|
|
||||||
"p50_us": 32.3,
|
|
||||||
"p95_us": 40.8,
|
|
||||||
"p99_us": 56.5,
|
|
||||||
"max_us": 127.5,
|
|
||||||
"events_bytes": 5120000,
|
|
||||||
"scene_bytes": 4680000,
|
|
||||||
"index_bytes": 131136
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"mode": "reverse_seek",
|
|
||||||
"frames": 600,
|
|
||||||
"journal_events": 64000,
|
|
||||||
"journal_scene": 65000,
|
|
||||||
"scanned_events": 195747,
|
|
||||||
"scanned_per_frame": 326.2,
|
|
||||||
"full_pass_events": 77400000,
|
|
||||||
"p50_us": 3.1,
|
|
||||||
"p95_us": 23.7,
|
|
||||||
"p99_us": 26.3,
|
|
||||||
"max_us": 45.9,
|
|
||||||
"events_bytes": 5120000,
|
|
||||||
"scene_bytes": 4680000,
|
|
||||||
"index_bytes": 131136
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"mode": "pause",
|
|
||||||
"frames": 600,
|
|
||||||
"journal_events": 64000,
|
|
||||||
"journal_scene": 65000,
|
|
||||||
"scanned_events": 1034400,
|
|
||||||
"scanned_per_frame": 1724.0,
|
|
||||||
"full_pass_events": 77400000,
|
|
||||||
"p50_us": 19.8,
|
|
||||||
"p95_us": 20.5,
|
|
||||||
"p99_us": 22.5,
|
|
||||||
"max_us": 40.2,
|
|
||||||
"events_bytes": 5120000,
|
|
||||||
"scene_bytes": 4680000,
|
|
||||||
"index_bytes": 131136
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"mode": "mp4",
|
|
||||||
"frames": 600,
|
|
||||||
"journal_events": 64000,
|
|
||||||
"journal_scene": 65000,
|
|
||||||
"scanned_events": 8386,
|
|
||||||
"scanned_per_frame": 14.0,
|
|
||||||
"full_pass_events": 77400000,
|
|
||||||
"p50_us": 1.6,
|
|
||||||
"p95_us": 1.9,
|
|
||||||
"p99_us": 4.1,
|
|
||||||
"max_us": 90.6,
|
|
||||||
"events_bytes": 5120000,
|
|
||||||
"scene_bytes": 4680000,
|
|
||||||
"index_bytes": 131136
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"meaning": {
|
|
||||||
"scanned_events": "events the by-time readers handed out (bench-counters); before #150 each sound, map-count and object-strike read the whole journal",
|
|
||||||
"full_pass_events": "one whole-journal pass per measured frame, for scale: the readers did several per frame before #150",
|
|
||||||
"p50_us/p95_us/p99_us/max_us": "CPU per frame (playback at x2, 600 frames = 30 s)",
|
|
||||||
"index_bytes": "memory the by-time index adds (kill/hit indices, first hits, and the stable order only for a journal out of time order)"
|
|
||||||
},
|
|
||||||
"equivalence": [
|
|
||||||
"airdef-core: sim::record::tests::time_range_reads_match_the_full_journal_filter",
|
|
||||||
"airdef-core: sim::record::tests::an_out_of_order_journal_reads_by_time_with_stable_ties",
|
|
||||||
"airdef-core: sim::record::tests::prefix_counts_and_first_hits_match_the_journal",
|
|
||||||
"airdef-core: sim::record::tests::scene_time_range_matches_the_full_journal",
|
|
||||||
"airdef-core: sim::record::tests::blast_windows_hold_the_same_blasts_as_a_full_scan",
|
|
||||||
"airdef: replay::engine_tests::event_sounds_are_exactly_the_events_of_the_window_after_any_seek",
|
|
||||||
"airdef: replay::engine_tests::the_map_marks_the_events_up_to_now_in_their_order"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
+1
-1
Submodule horizon updated: 1cadd63387...2bcce64236
Reference in New Issue
Block a user