Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7f52c40d99 | |||
| 8afe691301 | |||
| bd2d8f4fed | |||
| 41ab52e802 | |||
| 433e1500e2 | |||
| 01765027b1 | |||
| 24b8cce11b | |||
| 502d94c528 |
@@ -193,7 +193,9 @@ 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 с чисто
|
||||||
@@ -204,7 +206,12 @@ API 31 форка) и следуют за взглядом покадрово;
|
|||||||
целью, потом за перехватчиком (или смотрит из пушки, со стороны на прилёт), в момент сбития время замедляется;
|
целью, потом за перехватчиком (или смотрит из пушки, со стороны на прилёт), в момент сбития время замедляется;
|
||||||
- **полный повтор** — весь налёт, камера-режиссёр сама выбирает, за чем следить; колесо — перемотка, стрелки — скорость;
|
- **полный повтор** — весь налёт, камера-режиссёр сама выбирает, за чем следить; колесо — перемотка, стрелки — скорость;
|
||||||
- **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения
|
- **лучшие моменты** — нарезка до 8 самых интересных событий (перехват баллистики и гиперзвука, поражения
|
||||||
объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты.
|
объектов, потерянные комплексы, разделение «Орешника») с титрами и замедлением; колесо листает моменты;
|
||||||
|
- **цепочки боя** — меню N → «Повторы…» → «Цепочки боя»: по каждому контакту короткая строка
|
||||||
|
«отметка → передача → захват → пуск → исход» из 4–5 измеренных переходов записи, без домыслов. Видны
|
||||||
|
время каждого шага, батарея и контакт, у пропущенных контактов — «без пуска». Фильтр по батарее
|
||||||
|
переключает список; клик открывает кадр повтора (клип исхода, а если исхода нет — карту налёта на
|
||||||
|
моменте пуска или отметки). То же списком: `/airdef chains [номер батареи]`.
|
||||||
|
|
||||||
Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. Управление (подсказка
|
Повтор идёт на весь экран с леттербоксом; звук слышен так, как его слышала бы камера. Управление (подсказка
|
||||||
показывается в начале, после нажатия и на паузе): **← →** — перемотка на 5 с (в нарезке — соседний момент),
|
показывается в начале, после нажатия и на паузе): **← →** — перемотка на 5 с (в нарезке — соседний момент),
|
||||||
@@ -230,6 +237,18 @@ API 31 форка) и следуют за взглядом покадрово;
|
|||||||
- `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — три разные игровые РЛС с устойчивыми профилями в каталоге. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав, профиль, цикл, продукты измерения и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию. Профиль РЛС задаётся при размещении и не переключается на ходу: `radar <номер> on|off` сохраняется. Обзорная станция даёт редкие грубые отметки и область поиска; мачтовая уточняет низкие контакты над рельефом; сопровождения ищет локально, ведёт ограниченное число точных треков и только её собственное подтверждённое измерение разрешает пуск. Сеть передаёт источник, возраст и качество, но повторная пересылка не освежает измерение. Старые С-400/С-500 сохраняют сборную конфигурацию, старые роли РЛС при загрузке сопоставляются с профилями. [Устройство игровой батареи и пуска](docs/BATTERIES-AND-COLD-LAUNCH.md).
|
- `/airdef 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, нужны читы);
|
||||||
|
|||||||
@@ -57,7 +57,10 @@ 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::arg("номер", Value::int_from(1)).runs()),
|
Node::lit("why").runs().then(
|
||||||
|
Node::arg("номер", Value::int_from(1)).runs().then(Node::lit("source").runs()),
|
||||||
|
),
|
||||||
|
Node::lit("chains").runs().then(Node::arg("батарея", Value::int_from(1)).runs()),
|
||||||
Node::lit("raid").runs(),
|
Node::lit("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())),
|
||||||
@@ -168,7 +171,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", "ew on", "ew off", "move 4", "target here", "targets clear",
|
"scenario delete a", "why", "why 2", "why 2 source", "chains", "chains 2", "ew on", "ew off", "move 4", "target here", "targets clear",
|
||||||
"sites", "strike 3", "battery", "battery 1 launcher", "battery 1 integrated", "radar 2 on", "radar 2 off", "radar 2 engagement", "radar 2 search", "deploy s400_launcher", "deploy s500_launcher", "deploy radar_search", "deploy radar_track", "deploy radar_height", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000",
|
"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",
|
||||||
@@ -242,10 +245,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"] {
|
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel", "chains"] {
|
||||||
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
|
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
|
||||||
}
|
}
|
||||||
assert_eq!(top.len(), 36);
|
assert_eq!(top.len(), 37);
|
||||||
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
|
assert_eq!(complete("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"]);
|
||||||
|
|||||||
@@ -79,6 +79,8 @@ 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.
|
||||||
@@ -206,6 +208,8 @@ 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).
|
||||||
@@ -246,6 +250,9 @@ 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;
|
||||||
@@ -1311,6 +1318,23 @@ 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);
|
||||||
@@ -1638,6 +1662,7 @@ 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 => {
|
||||||
@@ -1647,11 +1672,40 @@ 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();
|
||||||
@@ -1886,6 +1940,7 @@ 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(),
|
||||||
@@ -2321,6 +2376,37 @@ 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;
|
||||||
@@ -2492,11 +2578,53 @@ 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
|
||||||
@@ -2760,6 +2888,7 @@ 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(),
|
||||||
|
|||||||
+175
-38
@@ -5,14 +5,22 @@
|
|||||||
//! 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 and the truth's each): a full raid still fits
|
/// The most markers of one picture (the network's, the truth's and the interceptors' each): a full
|
||||||
/// the HUD's 1024 shapes — a marker is four sides and a label.
|
/// raid still fits 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).
|
||||||
@@ -86,6 +94,50 @@ 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.
|
||||||
@@ -97,20 +149,17 @@ 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 network's tracks, nearest first: a full raid keeps the closest markers.
|
// The frame's counts: what got a marker and what did not — out of the frame (behind the camera
|
||||||
let mut tracks: Vec<&Track> = pic.tracks.iter().collect();
|
// or past an edge) or past the budget. The header keeps the two apart (#141).
|
||||||
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 hidden = tracks.len().saturating_sub(MAX_MARKERS);
|
let mut offscreen = 0usize;
|
||||||
for t in tracks.into_iter().take(MAX_MARKERS) {
|
let mut capped = 0usize;
|
||||||
let e = t.est(now);
|
// The network's tracks: the nearest visible keep the markers; a target behind the camera no
|
||||||
let dist = e.distance(player);
|
// longer spends one, so a crowd behind cannot crowd out the target in frame.
|
||||||
let Some(p) = project(e) else { hidden += 1; continue };
|
let net = pick(pic.tracks.iter(), |t| t.est(now), |t| half(t.est(now).distance(player)), player, gui, &project);
|
||||||
let h = half(dist);
|
offscreen += net.offscreen;
|
||||||
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
|
capped += net.capped;
|
||||||
hidden += 1;
|
for (t, p, h) in net.marks {
|
||||||
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)
|
||||||
@@ -128,16 +177,17 @@ 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 mut drones: Vec<_> = sim.drones.iter().filter(|d| d.alive()).collect();
|
let real = pick(
|
||||||
drones.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
|
sim.drones.iter().filter(|d| d.alive()),
|
||||||
hidden += drones.len().saturating_sub(MAX_MARKERS);
|
|d| d.pos,
|
||||||
for d in drones.into_iter().take(MAX_MARKERS) {
|
|d| half(d.pos.distance(player)) + 2.0,
|
||||||
let Some(p) = project(d.pos) else { hidden += 1; continue };
|
player,
|
||||||
let h = half(d.pos.distance(player)) + 2.0;
|
gui,
|
||||||
if p.x < h || p.x > gui.0 - h || p.y < h || p.y > gui.1 - h {
|
&project,
|
||||||
hidden += 1;
|
);
|
||||||
continue;
|
offscreen += real.offscreen;
|
||||||
}
|
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));
|
||||||
@@ -145,24 +195,18 @@ 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).
|
// the network never hid them (the radar has always shown them). They keep their own budget.
|
||||||
let mut missiles: Vec<_> = sim.missiles.iter().collect();
|
let own = pick(sim.missiles.iter(), |m| m.pos, |_| MISSILE_HALF, player, gui, &project);
|
||||||
missiles.sort_by(|a, b| a.pos.distance(player).total_cmp(&b.pos.distance(player)));
|
for (_, p, h) in own.marks {
|
||||||
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 and what stayed behind the camera
|
// explicitly marked. The counts say what the frame holds, what left it, and what the budget cut.
|
||||||
// or past the edges.
|
let counts = format!("в кадре {shown}, за кадром {offscreen}, сверх бюджета {capped}");
|
||||||
let head = if truth {
|
let head = if truth {
|
||||||
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · в кадре {shown}, за кадром {hidden}")
|
format!("ОБЗОР · ИСТИНА (песочница): белые рамки — реальные дроны · {counts}")
|
||||||
} else {
|
} else {
|
||||||
format!("ОБЗОР · данные сети РЛС · в кадре {shown}, за кадром {hidden}")
|
format!("ОБЗОР · данные сети РЛС · {counts}")
|
||||||
};
|
};
|
||||||
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
|
||||||
@@ -201,6 +245,17 @@ 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));
|
||||||
@@ -282,6 +337,88 @@ 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));
|
||||||
|
|||||||
+107
-1
@@ -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::{EventKind, Recording, STEP, StrikeResult, What};
|
use crate::sim::record::{Chain, ChainOutcome, ChainStepKind, 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,6 +187,67 @@ 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];
|
||||||
@@ -299,6 +360,16 @@ impl Player {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Opens the replay at a recording tick (a chain's launch or mark), holding that frame.
|
||||||
|
pub fn seek(&mut self, rec: &Recording, at: f64) {
|
||||||
|
self.t = at.clamp(0.0, rec.len as f64);
|
||||||
|
self.heard = self.t;
|
||||||
|
self.shot = (usize::MAX, 0);
|
||||||
|
self.fade = 0;
|
||||||
|
self.card = 0;
|
||||||
|
self.paused = true;
|
||||||
|
}
|
||||||
|
|
||||||
/// The wheel: scrubs the map and the full replay, skips clips.
|
/// 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 };
|
||||||
@@ -1102,6 +1173,41 @@ 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() {
|
||||||
|
|||||||
@@ -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,6 +414,7 @@ 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 {
|
||||||
@@ -715,8 +716,8 @@ impl Sim {
|
|||||||
recon_expect.push((pending, zones));
|
recon_expect.push((pending, zones));
|
||||||
}
|
}
|
||||||
"airrecobs" => {
|
"airrecobs" => {
|
||||||
if w.len() != 11 {
|
if w.len() != 11 && w.len() != 12 {
|
||||||
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("наблюдение разведки", "строка без разведчика"));
|
||||||
@@ -739,7 +740,10 @@ 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;
|
||||||
recon.sorties[at].pending.push(recon::Look { truth, area, radius, category, role, quality, source, observed });
|
// An older save has no wreck flag: every pending look it holds is of a unit
|
||||||
|
// 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,6 +1416,8 @@ 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,
|
||||||
@@ -1529,6 +1531,7 @@ 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,
|
||||||
|
|||||||
+239
-38
@@ -16,6 +16,12 @@
|
|||||||
//! 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
|
||||||
@@ -48,6 +54,14 @@ 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)]
|
||||||
@@ -192,6 +206,12 @@ 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 {
|
||||||
@@ -238,6 +258,7 @@ 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;
|
||||||
}
|
}
|
||||||
@@ -245,6 +266,7 @@ 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;
|
||||||
@@ -253,18 +275,42 @@ 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.observations = 0;
|
self.misses = 0;
|
||||||
self.seen = None;
|
self.seen = None;
|
||||||
// The old picture belongs to the old contact: it must not be read as this one's.
|
// The old picture belongs to the old contact: it must not be read as this one's. Letting
|
||||||
self.observation = None;
|
// the contact go (None) or picking the same one again keeps it: it is a record and ages.
|
||||||
|
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 {
|
||||||
match self.state {
|
let body = 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 {
|
||||||
@@ -275,7 +321,8 @@ 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 {
|
||||||
@@ -290,6 +337,7 @@ 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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -305,6 +353,8 @@ 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,
|
||||||
@@ -324,7 +374,7 @@ impl OpticalReport {
|
|||||||
format!("оптический пост №{}", self.index)
|
format!("оптический пост №{}", self.index)
|
||||||
}
|
}
|
||||||
pub fn line(&self) -> String {
|
pub fn line(&self) -> String {
|
||||||
match self.state {
|
let body = 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 {
|
||||||
@@ -340,7 +390,8 @@ 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> {
|
||||||
@@ -377,6 +428,7 @@ 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.
|
||||||
@@ -387,33 +439,39 @@ impl Sim {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The post's own pick: a manual/network cue first, then its narrow near sector. At most one contact.
|
/// The post's own pick: a manual command, the contact it already holds, a cue within reach or
|
||||||
|
/// 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(id) = optical.target() {
|
// Keep the current contact while it is still within the optics' own reach: observations
|
||||||
if let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive()) {
|
// accumulate instead of the post hopping between equally good contacts.
|
||||||
if d.pos.distance(sam.pos) <= CUE_RANGE {
|
if let Some(id) = optical.target()
|
||||||
return Some(id);
|
&& alive(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);
|
||||||
}
|
}
|
||||||
// The network's freshest cue: the post measures it itself, the relay only points the head.
|
// A cue within reach is a known contact: the head turns to it and the post measures it itself.
|
||||||
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)
|
||||||
&& t.est(now).distance(sam.pos) <= CUE_RANGE
|
&& !optical.avoided(t.id, now)
|
||||||
|
&& t.est(now).distance(sam.pos) <= RANGE
|
||||||
{
|
{
|
||||||
return Some(t.id);
|
return Some(t.id);
|
||||||
}
|
}
|
||||||
// Nothing cued: search a narrow near sector, nearest first, comparing no more than a few.
|
// Search a narrow near sector, nearest first, comparing no more than a few. The sector is
|
||||||
// The sector is the head's (`dish`, which turns while it searches), not the base's heading.
|
// 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()
|
||||||
@@ -421,7 +479,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 {
|
if dist > RANGE || optical.avoided(d.id, now) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let bearing = heading_of(rel);
|
let bearing = heading_of(rel);
|
||||||
@@ -430,7 +488,19 @@ 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);
|
||||||
local.first().map(|&(_, id)| id)
|
if let Some(&(_, id)) = local.first() {
|
||||||
|
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.
|
||||||
@@ -481,22 +551,31 @@ impl Sim {
|
|||||||
sam.dish = (sam.dish + 0.02) % TAU;
|
sam.dish = (sam.dish + 0.02) % TAU;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Fair round-robin: a crowd of posts does not starve the last ones for ever.
|
// A fair queue over the posts ready this tick: the post probed longest ago goes first, so
|
||||||
let start = (now as usize) % posts.len();
|
// posts whose phases coincide all get their turn. The per-tick probe budget still caps work.
|
||||||
|
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 k in 0..posts.len() {
|
for i in ready {
|
||||||
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;
|
||||||
@@ -516,10 +595,14 @@ 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);
|
||||||
@@ -554,11 +637,19 @@ 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();
|
||||||
}
|
}
|
||||||
@@ -707,7 +798,8 @@ 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();
|
||||||
run(&mut sim, &mut ground, 200);
|
// Two night probes: beyond the reduced reach, before the post lets the contact go.
|
||||||
|
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));
|
||||||
@@ -734,11 +826,17 @@ 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, 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::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);
|
||||||
@@ -752,10 +850,15 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
ground.answer(cols, 0);
|
ground.answer(cols, 0);
|
||||||
run(&mut unknown, &mut ground, 200);
|
run(&mut unknown, &mut ground, 2 * PERIOD);
|
||||||
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.
|
||||||
@@ -769,13 +872,20 @@ 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_eq!(r.state, OpticalState::NoSight);
|
assert_ne!(r.state, OpticalState::Observing);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
@@ -841,12 +951,17 @@ 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, 60);
|
run(&mut sim, &mut ground, 2 * PERIOD);
|
||||||
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.
|
||||||
@@ -927,12 +1042,98 @@ 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() {
|
||||||
|
|||||||
+255
-23
@@ -11,7 +11,9 @@
|
|||||||
//! 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.
|
//! second independent look may refine the area and (for a radar) its role. A wreck a look
|
||||||
|
//! 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;
|
||||||
|
|
||||||
@@ -240,6 +242,8 @@ 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)]
|
||||||
@@ -368,6 +372,13 @@ 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;
|
||||||
@@ -383,6 +394,10 @@ 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;
|
||||||
}
|
}
|
||||||
@@ -446,6 +461,29 @@ 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 };
|
||||||
@@ -453,17 +491,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_on => Source::Jamming,
|
SamKind::Ew if s.ew_up() => Source::Jamming,
|
||||||
SamKind::Radar if s.radar_on => Source::Emission,
|
SamKind::Radar if s.radar_up() => 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),
|
||||||
@@ -473,6 +511,7 @@ 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
|
||||||
@@ -795,6 +834,7 @@ 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();
|
||||||
@@ -824,35 +864,224 @@ 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
|
||||||
// #135: the channel matters. A silent radar is seen only by the flyby, a transmitting
|
// its switch still on, makes no mark and no lead; its report is an empty observation.
|
||||||
// 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 the_source_is_the_channel_that_showed_the_unit() {
|
fn a_fresh_wreck_makes_no_mark_and_no_lead() {
|
||||||
|
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));
|
||||||
sim.recon.checked.clear();
|
let source = |sim: &Sim, id: u32| super::look(&sim.sams, &sim.recon, &sim.intel, &zone, sim.tick).into_iter().find(|l| l.truth == id).map(|l| l.source);
|
||||||
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;
|
fn unit(sim: &mut Sim, id: u32) -> &mut Sam {
|
||||||
|
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), Source::Launch);
|
assert_eq!(source(&sim, s400), Some(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), Source::Launch);
|
assert_eq!(source(&sim, s400), Some(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
|
||||||
@@ -1043,6 +1272,7 @@ 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();
|
||||||
@@ -1071,6 +1301,7 @@ 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);
|
||||||
@@ -1117,6 +1348,7 @@ mod tests {
|
|||||||
quality: Quality::Coarse,
|
quality: Quality::Coarse,
|
||||||
source: Source::Flyby,
|
source: Source::Flyby,
|
||||||
observed: 100,
|
observed: 100,
|
||||||
|
wreck: false,
|
||||||
},
|
},
|
||||||
100,
|
100,
|
||||||
);
|
);
|
||||||
|
|||||||
+432
-26
@@ -30,6 +30,9 @@ pub struct SamKey {
|
|||||||
spent_cells: u8,
|
spent_cells: u8,
|
||||||
cap_cell: u8,
|
cap_cell: u8,
|
||||||
cap_open: f32,
|
cap_open: f32,
|
||||||
|
/// A discrete transition or a frame of a tube cover's opening rather than a pose sample (#142):
|
||||||
|
/// decimation keeps it, within its own budget.
|
||||||
|
event: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SamKey {
|
impl SamKey {
|
||||||
@@ -51,6 +54,7 @@ impl SamKey {
|
|||||||
spent_cells: sam.spent_cells,
|
spent_cells: sam.spent_cells,
|
||||||
cap_cell: sam.cap_cell,
|
cap_cell: sam.cap_cell,
|
||||||
cap_open: sam.cap_open,
|
cap_open: sam.cap_open,
|
||||||
|
event: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// The same pose (to within what could be seen).
|
/// The same pose (to within what could be seen).
|
||||||
@@ -68,6 +72,18 @@ impl SamKey {
|
|||||||
&& self.spent_cells == o.spent_cells && self.cap_cell == o.cap_cell
|
&& self.spent_cells == o.spent_cells && self.cap_cell == o.cap_cell
|
||||||
&& near(self.cap_open, o.cap_open, 0.001)
|
&& near(self.cap_open, o.cap_open, 0.001)
|
||||||
}
|
}
|
||||||
|
/// The states a replay reads as facts rather than as interpolated poses: which round is spent,
|
||||||
|
/// which tube the cover opens, whether the radar emits, and the mount's configuration.
|
||||||
|
fn discrete(&self) -> (battery::SamMode, battery::RadarRole, bool, u8, u8) {
|
||||||
|
(self.mode, self.radar_role, self.radar_on, self.spent_cells, self.cap_cell)
|
||||||
|
}
|
||||||
|
/// The tube cover's stage: shut, on its way open, or wide.
|
||||||
|
fn cover(&self) -> u8 { cover_stage(self.cap_open) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cover's stage an opening (`launch::OPEN_TICKS` long) passes through.
|
||||||
|
fn cover_stage(open: f32) -> u8 {
|
||||||
|
if open <= 0.0 { 0 } else if open < 1.0 { 1 } else { 2 }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A system through a recording: its poses (a new one only when it changed, with the
|
/// A system through a recording: its poses (a new one only when it changed, with the
|
||||||
@@ -115,6 +131,7 @@ impl SamTrack {
|
|||||||
spent_cells: a.spent_cells,
|
spent_cells: a.spent_cells,
|
||||||
cap_cell: a.cap_cell,
|
cap_cell: a.cap_cell,
|
||||||
cap_open: if a.cap_cell == b.cap_cell && a.spent_cells == b.spent_cells { l(a.cap_open, b.cap_open) } else { a.cap_open },
|
cap_open: if a.cap_cell == b.cap_cell && a.spent_cells == b.spent_cells { l(a.cap_open, b.cap_open) } else { a.cap_open },
|
||||||
|
event: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
/// The system as it stood at `t`, as a ghost to draw with the ids from `id`.
|
/// The system as it stood at `t`, as a ghost to draw with the ids from `id`.
|
||||||
@@ -157,6 +174,7 @@ impl Recording {
|
|||||||
sam_tracks: Vec::new(),
|
sam_tracks: Vec::new(),
|
||||||
sam_index: HashMap::new(),
|
sam_index: HashMap::new(),
|
||||||
sam_keys: 0,
|
sam_keys: 0,
|
||||||
|
sam_events: 0,
|
||||||
sam_step: STEP,
|
sam_step: STEP,
|
||||||
ticks: Vec::new(),
|
ticks: Vec::new(),
|
||||||
times: Vec::new(),
|
times: Vec::new(),
|
||||||
@@ -190,6 +208,10 @@ const LONGEST: u32 = 12_000;
|
|||||||
const KEPT: usize = 3;
|
const KEPT: usize = 3;
|
||||||
/// SAM poses share a fixed memory budget; under pressure old poses are thinned and new ones slow down.
|
/// SAM poses share a fixed memory budget; under pressure old poses are thinned and new ones slow down.
|
||||||
const MAX_SAM_KEYS: usize = 32_768;
|
const MAX_SAM_KEYS: usize = 32_768;
|
||||||
|
/// Discrete transitions and cover-opening frames have their own small budget (#142): they are
|
||||||
|
/// facts a replay must not lose, but they may not spend the pose budget either. When it runs out
|
||||||
|
/// the oldest stop being critical (the newest are kept) and decimation may thin them as poses.
|
||||||
|
const MAX_SAM_EVENTS: usize = 4_096;
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||||
pub enum What {
|
pub enum What {
|
||||||
@@ -253,6 +275,77 @@ pub struct Event {
|
|||||||
pub kind: EventKind,
|
pub kind: EventKind,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One step of a short after-action chain: отметка → передача → захват → пуск → исход.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum ChainStepKind {
|
||||||
|
/// The contact first appears on the battery's picture.
|
||||||
|
Mark,
|
||||||
|
/// The plot's source changes (a relay became the battery's own measurement, or the reverse).
|
||||||
|
Handoff,
|
||||||
|
/// The battery's own radar locks it.
|
||||||
|
Lock,
|
||||||
|
/// The battery launches an interceptor at it.
|
||||||
|
Launch,
|
||||||
|
/// What came of the chain: shot down, broke through, lost.
|
||||||
|
Outcome,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum ChainOutcome {
|
||||||
|
Destroyed,
|
||||||
|
/// The target reached its aim (an object, a system, the land).
|
||||||
|
Hit,
|
||||||
|
Lost,
|
||||||
|
/// The recording ended or the chain was cut short.
|
||||||
|
Unfinished,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct ChainStep {
|
||||||
|
pub kind: ChainStepKind,
|
||||||
|
pub at: u32,
|
||||||
|
/// The recorded event a replay can open (the outcome), when there is one.
|
||||||
|
pub event: Option<usize>,
|
||||||
|
/// For the mark and the handoff: the plot is the battery's own measurement.
|
||||||
|
pub own: bool,
|
||||||
|
/// For a launch: the interceptor's id.
|
||||||
|
pub missile: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A battery's short engagement history for one contact, built from the recording's measured
|
||||||
|
/// scene transitions and events. At most one step of each kind: no inferred beats.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Chain {
|
||||||
|
pub sam: u32,
|
||||||
|
pub target: u32,
|
||||||
|
pub steps: Vec<ChainStep>,
|
||||||
|
pub outcome: ChainOutcome,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Chain {
|
||||||
|
pub fn marked_at(&self) -> u32 {
|
||||||
|
self.steps.first().map_or(0, |s| s.at)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn step(&self, kind: ChainStepKind) -> Option<&ChainStep> {
|
||||||
|
self.steps.iter().find(|s| s.kind == kind)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn launched(&self) -> bool {
|
||||||
|
self.step(ChainStepKind::Launch).is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A contact that appeared on the picture and was never launched at.
|
||||||
|
pub fn missed(&self) -> bool {
|
||||||
|
!self.launched()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The event a replay clip opens on: the outcome when there is one, else nothing.
|
||||||
|
pub fn outcome_event(&self) -> Option<usize> {
|
||||||
|
self.step(ChainStepKind::Outcome).and_then(|s| s.event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Measured scene transitions. These are facts, not inferred cinematic beats.
|
/// Measured scene transitions. These are facts, not inferred cinematic beats.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
pub enum SceneKind {
|
pub enum SceneKind {
|
||||||
@@ -387,6 +480,8 @@ pub struct Recording {
|
|||||||
pub sam_tracks: Vec<SamTrack>,
|
pub sam_tracks: Vec<SamTrack>,
|
||||||
sam_index: HashMap<u32, usize>,
|
sam_index: HashMap<u32, usize>,
|
||||||
sam_keys: usize,
|
sam_keys: usize,
|
||||||
|
/// How many of `sam_keys` are critical transitions (#142).
|
||||||
|
sam_events: usize,
|
||||||
sam_step: u32,
|
sam_step: u32,
|
||||||
/// The game's tick number as sampled with the clock: (recording tick, game tick). A replay
|
/// The game's tick number as sampled with the clock: (recording tick, game tick). A replay
|
||||||
/// shows the world's blocks as of this time.
|
/// shows the world's blocks as of this time.
|
||||||
@@ -597,37 +692,70 @@ impl Recording {
|
|||||||
sam_tracks: Vec::new(),
|
sam_tracks: Vec::new(),
|
||||||
sam_index: HashMap::new(),
|
sam_index: HashMap::new(),
|
||||||
sam_keys: 0,
|
sam_keys: 0,
|
||||||
|
sam_events: 0,
|
||||||
sam_step: STEP,
|
sam_step: STEP,
|
||||||
ticks: Vec::new(),
|
ticks: Vec::new(),
|
||||||
times: Vec::new(),
|
times: Vec::new(),
|
||||||
quiet: 0,
|
quiet: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn thin_sam_tracks(&mut self) {
|
/// Halves each track's poses, keeping its critical transitions, its first and its last key (#142).
|
||||||
|
fn thin_sam_poses(&mut self) {
|
||||||
for track in &mut self.sam_tracks {
|
for track in &mut self.sam_tracks {
|
||||||
let len = track.keys.len();
|
let len = track.keys.len();
|
||||||
let mut kept = 0;
|
let mut kept = 0;
|
||||||
for read in (0..len).step_by(2) {
|
let mut poses = 0;
|
||||||
track.keys[kept] = track.keys[read];
|
for read in 0..len {
|
||||||
kept += 1;
|
let key = track.keys[read];
|
||||||
}
|
let keep = if key.event {
|
||||||
if len % 2 == 0 && len > 0 {
|
true
|
||||||
track.keys[kept] = track.keys[len - 1];
|
} else {
|
||||||
kept += 1;
|
poses += 1;
|
||||||
|
poses % 2 == 1 || read + 1 == len
|
||||||
|
};
|
||||||
|
if keep {
|
||||||
|
track.keys[kept] = key;
|
||||||
|
kept += 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
track.keys.truncate(kept);
|
track.keys.truncate(kept);
|
||||||
track.keys.shrink_to_fit();
|
track.keys.shrink_to_fit();
|
||||||
}
|
}
|
||||||
self.sam_keys = self.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
self.count_sam_keys();
|
||||||
self.sam_step = self.sam_step.saturating_mul(2).min(LONGEST);
|
self.sam_step = self.sam_step.saturating_mul(2).min(LONGEST);
|
||||||
}
|
}
|
||||||
|
/// The transitions' budget ran out: the oldest stop being critical, so decimation may thin them
|
||||||
|
/// as poses. The newest transitions, which a replay is watched closest for, are kept (#142).
|
||||||
|
fn thin_sam_events(&mut self) {
|
||||||
|
let mut over = self.sam_events.saturating_sub(MAX_SAM_EVENTS);
|
||||||
|
while over > 0 {
|
||||||
|
let mut demoted = 0;
|
||||||
|
for track in &mut self.sam_tracks {
|
||||||
|
if over == 0 { break; }
|
||||||
|
if let Some(key) = track.keys.iter_mut().find(|key| key.event) {
|
||||||
|
key.event = false;
|
||||||
|
over -= 1;
|
||||||
|
demoted += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if demoted == 0 { break; }
|
||||||
|
}
|
||||||
|
self.count_sam_keys();
|
||||||
|
}
|
||||||
|
fn count_sam_keys(&mut self) {
|
||||||
|
self.sam_keys = self.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
||||||
|
self.sam_events = self.sam_tracks.iter().map(|track| track.keys.iter().filter(|key| key.event).count()).sum();
|
||||||
|
}
|
||||||
|
|
||||||
/// Notes the systems' poses at the recording's tick `now`: a pose only when it changed, with
|
/// Notes the systems' poses at the recording's tick `now`: a pose only when it changed, with
|
||||||
/// the pose it held marked before it so a replay doesn't glide through the stillness.
|
/// the pose it held marked before it so a replay doesn't glide through the stillness.
|
||||||
|
///
|
||||||
|
/// Poses are sampled on the adaptive `sam_step` grid under its own budget, but the cover's
|
||||||
|
/// opening (`launch::OPEN_TICKS`, shorter than a decimated interval) and the discrete
|
||||||
|
/// transitions — a round ejected, a tube cancelled, the radar switched, the mount's
|
||||||
|
/// configuration — are facts: they are kept on the tick they happen, in their own budget (#142).
|
||||||
fn note_sams(&mut self, sams: &[Sam], now: u32) {
|
fn note_sams(&mut self, sams: &[Sam], now: u32) {
|
||||||
if now % self.sam_step != 0 {
|
let pose_due = now % self.sam_step == 0;
|
||||||
return;
|
|
||||||
}
|
|
||||||
for sam in sams {
|
for sam in sams {
|
||||||
let key = SamKey::of(sam, self.origin, now);
|
let key = SamKey::of(sam, self.origin, now);
|
||||||
let i = *self.sam_index.entry(sam.id).or_insert_with(|| {
|
let i = *self.sam_index.entry(sam.id).or_insert_with(|| {
|
||||||
@@ -636,20 +764,41 @@ impl Recording {
|
|||||||
});
|
});
|
||||||
let track = &mut self.sam_tracks[i];
|
let track = &mut self.sam_tracks[i];
|
||||||
let before = track.keys.len();
|
let before = track.keys.len();
|
||||||
match track.keys.last().copied() {
|
let Some(last) = track.keys.last().copied() else {
|
||||||
None => track.keys.push(key),
|
track.keys.push(key);
|
||||||
Some(last) if last.same(&key) => {}
|
self.sam_keys += 1;
|
||||||
Some(last) => {
|
continue;
|
||||||
if last.at + self.sam_step < now {
|
};
|
||||||
track.keys.push(SamKey { at: now - self.sam_step, ..last });
|
if last.same(&key) {
|
||||||
}
|
continue;
|
||||||
track.keys.push(key);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
self.sam_keys += track.keys.len() - before;
|
// The cover's opening is short: its first frame only differs from the shut pose by a
|
||||||
|
// fraction, so the stage's start is backdated to the tick it began (#142).
|
||||||
|
if last.cover() == 0 && key.cover() == 1 && now > last.at + 1 {
|
||||||
|
track.keys.push(SamKey { at: now - 1, cap_open: 0.0, event: true, ..key });
|
||||||
|
}
|
||||||
|
let transitioning = last.discrete() != key.discrete() || last.cover() != key.cover();
|
||||||
|
// Every frame of the cover's own movement is kept, so the stage's six ticks survive intact.
|
||||||
|
let moving = key.cover() == 1 && last.cap_open != key.cap_open;
|
||||||
|
if transitioning || moving {
|
||||||
|
let mut event = key;
|
||||||
|
event.event = true;
|
||||||
|
track.keys.push(event);
|
||||||
|
} else if pose_due {
|
||||||
|
if last.at + self.sam_step < now {
|
||||||
|
track.keys.push(SamKey { at: now - self.sam_step, event: false, ..last });
|
||||||
|
}
|
||||||
|
track.keys.push(key);
|
||||||
|
}
|
||||||
|
let added = track.keys.len() - before;
|
||||||
|
self.sam_keys += added;
|
||||||
|
self.sam_events += track.keys[before..].iter().filter(|key| key.event).count();
|
||||||
}
|
}
|
||||||
if self.sam_keys > MAX_SAM_KEYS {
|
if self.sam_events > MAX_SAM_EVENTS {
|
||||||
self.thin_sam_tracks();
|
self.thin_sam_events();
|
||||||
|
}
|
||||||
|
if self.sam_keys.saturating_sub(self.sam_events) > MAX_SAM_KEYS {
|
||||||
|
self.thin_sam_poses();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// Actual launch, if observed during this recording. Missing is not proof of no launch:
|
/// Actual launch, if observed during this recording. Missing is not proof of no launch:
|
||||||
@@ -789,6 +938,119 @@ impl Recording {
|
|||||||
pub fn sam(&self, id: u32) -> Option<(SamKind, DVec3)> {
|
pub fn sam(&self, id: u32) -> Option<(SamKind, DVec3)> {
|
||||||
self.sams.iter().find(|s| s.0 == id).map(|s| (s.1, s.2))
|
self.sams.iter().find(|s| s.0 == id).map(|s| (s.1, s.2))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The battery's short chains through this raid, one per contact, in the order they began:
|
||||||
|
/// the picture's own transitions (mark, handoff, lock, launch) and the recorded outcome.
|
||||||
|
/// `battery` filters by system id; None keeps all. A recording with no scene journal (the
|
||||||
|
/// legacy format) has no chains, and a truncated one may miss a later step — that is marked
|
||||||
|
/// by `SceneJournal::truncated`, never guessed.
|
||||||
|
pub fn chains(&self, battery: Option<u32>) -> Vec<Chain> {
|
||||||
|
let Some(scene) = &self.scene else { return Vec::new() };
|
||||||
|
let mut chains: std::collections::BTreeMap<(u32, u32), Chain> = std::collections::BTreeMap::new();
|
||||||
|
for event in scene.events() {
|
||||||
|
match event.kind {
|
||||||
|
SceneKind::TrackAcquired { sam, target, ever_own } => {
|
||||||
|
let chain = chains.entry((sam, target)).or_insert_with(|| Chain {
|
||||||
|
sam,
|
||||||
|
target,
|
||||||
|
steps: Vec::new(),
|
||||||
|
outcome: ChainOutcome::Unfinished,
|
||||||
|
});
|
||||||
|
if chain.steps.is_empty() {
|
||||||
|
chain.steps.push(ChainStep { kind: ChainStepKind::Mark, at: event.at, event: None, own: ever_own, missile: None });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SceneKind::TrackSource { sam, target, ever_own } => {
|
||||||
|
if let Some(chain) = chains.get_mut(&(sam, target))
|
||||||
|
&& chain.step(ChainStepKind::Handoff).is_none()
|
||||||
|
{
|
||||||
|
chain.steps.push(ChainStep { kind: ChainStepKind::Handoff, at: event.at, event: None, own: ever_own, missile: None });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SceneKind::TrackLock { sam, target, locked: true } => {
|
||||||
|
if let Some(chain) = chains.get_mut(&(sam, target))
|
||||||
|
&& chain.step(ChainStepKind::Lock).is_none()
|
||||||
|
{
|
||||||
|
chain.steps.push(ChainStep { kind: ChainStepKind::Lock, at: event.at, event: None, own: true, missile: None });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SceneKind::MissileLaunch { sam, target, missile, .. } => {
|
||||||
|
if let Some(chain) = chains.get_mut(&(sam, target))
|
||||||
|
&& chain.step(ChainStepKind::Launch).is_none()
|
||||||
|
{
|
||||||
|
chain.steps.push(ChainStep { kind: ChainStepKind::Launch, at: event.at, event: None, own: true, missile: Some(missile) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The outcomes are the recorded events; a kill identifies its chain by the battery and
|
||||||
|
// the target, or by the interceptor when another battery's kill shares the target.
|
||||||
|
for (index, event) in self.events.iter().enumerate() {
|
||||||
|
match event.kind {
|
||||||
|
EventKind::Kill { drone, sam, missile, .. } => {
|
||||||
|
let mut keys = vec![(sam, drone)];
|
||||||
|
if let Some(missile) = missile {
|
||||||
|
keys.extend(chains.iter().filter(|(_, c)| c.steps.iter().any(|s| s.missile == Some(missile))).map(|(k, _)| *k));
|
||||||
|
}
|
||||||
|
for key in keys {
|
||||||
|
if let Some(chain) = chains.get_mut(&key) {
|
||||||
|
set_chain_outcome(chain, ChainOutcome::Destroyed, event.at, Some(index));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EventKind::Hit { drone, sam, .. } => {
|
||||||
|
let by_sam = sam.and_then(|(_, i)| self.sams.get(i).map(|s| s.0));
|
||||||
|
for ((_, target), chain) in chains.iter_mut() {
|
||||||
|
if *target == drone && by_sam.is_none_or(|id| id == chain.sam) {
|
||||||
|
set_chain_outcome(chain, ChainOutcome::Hit, event.at, Some(index));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EventKind::Crash { drone, .. } => {
|
||||||
|
for ((_, target), chain) in chains.iter_mut() {
|
||||||
|
if *target == drone && !chain.launched() {
|
||||||
|
set_chain_outcome(chain, ChainOutcome::Lost, event.at, Some(index));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A contact dropped without an outcome and never fired at was missed, not engaged.
|
||||||
|
for event in scene.events() {
|
||||||
|
if let SceneKind::TrackLost { sam, target } = event.kind
|
||||||
|
&& let Some(chain) = chains.get_mut(&(sam, target))
|
||||||
|
&& !chain.launched()
|
||||||
|
{
|
||||||
|
set_chain_outcome(chain, ChainOutcome::Lost, event.at, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out: Vec<Chain> = chains
|
||||||
|
.into_values()
|
||||||
|
.filter(|c| battery.is_none_or(|id| c.sam == id))
|
||||||
|
.filter(|c| !c.steps.is_empty())
|
||||||
|
.collect();
|
||||||
|
out.sort_by_key(|c| (c.marked_at(), c.sam, c.target));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets a chain's outcome, keeping the strongest one seen (shot down beats a hit, a hit beats a
|
||||||
|
/// lost or unfinished chain) and at most one outcome step.
|
||||||
|
fn set_chain_outcome(chain: &mut Chain, outcome: ChainOutcome, at: u32, event: Option<usize>) {
|
||||||
|
let rank = |o: ChainOutcome| match o {
|
||||||
|
ChainOutcome::Destroyed => 3,
|
||||||
|
ChainOutcome::Hit => 2,
|
||||||
|
ChainOutcome::Lost => 1,
|
||||||
|
ChainOutcome::Unfinished => 0,
|
||||||
|
};
|
||||||
|
if rank(chain.outcome) > rank(outcome) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
chain.outcome = outcome;
|
||||||
|
chain.steps.retain(|s| s.kind != ChainStepKind::Outcome);
|
||||||
|
chain.steps.push(ChainStep { kind: ChainStepKind::Outcome, at, event, own: false, missile: None });
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Sim {
|
impl Sim {
|
||||||
@@ -874,9 +1136,10 @@ impl Sim {
|
|||||||
}
|
}
|
||||||
r.ticks.push((r.len, self.engine_tick));
|
r.ticks.push((r.len, self.engine_tick));
|
||||||
}
|
}
|
||||||
|
// Poses share the adaptive grid inside; the discrete transitions and the cover's short
|
||||||
|
// opening must be seen on the tick they happen, whatever the grid (#142).
|
||||||
|
r.note_sams(&self.sams, r.len);
|
||||||
if r.len % STEP == 0 {
|
if r.len % STEP == 0 {
|
||||||
let now = r.len;
|
|
||||||
r.note_sams(&self.sams, now);
|
|
||||||
for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) {
|
for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) {
|
||||||
r.point(d.id, What::Drone(d.kind), d.pos);
|
r.point(d.id, What::Drone(d.kind), d.pos);
|
||||||
}
|
}
|
||||||
@@ -1074,6 +1337,49 @@ mod tests {
|
|||||||
s
|
s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn battle_chains_keep_four_or_five_measured_steps_and_filter_by_battery() {
|
||||||
|
let mut r = Recording::blank(400);
|
||||||
|
r.sams = vec![(10, SamKind::Pantsir, DVec3::ZERO), (20, SamKind::S400, DVec3::new(200.0, 64.0, 0.0))];
|
||||||
|
let mut scene = SceneJournal::default();
|
||||||
|
let at = |at: u32, kind| SceneEvent { at, pos: DVec3::ZERO, kind };
|
||||||
|
scene.push(at(20, SceneKind::TrackAcquired { sam: 10, target: 7, ever_own: false }));
|
||||||
|
scene.push(at(30, SceneKind::TrackSource { sam: 10, target: 7, ever_own: true }));
|
||||||
|
scene.push(at(40, SceneKind::TrackLock { sam: 10, target: 7, locked: true }));
|
||||||
|
scene.push(at(50, SceneKind::MissileLaunch { missile: 500, sam: 10, target: 7, kind: MissileKind::M57e6, sound: "airdef:launch.pantsir", pitch: 1.0 }));
|
||||||
|
scene.push(at(70, SceneKind::TrackLost { sam: 10, target: 7 }));
|
||||||
|
r.scene = Some(scene);
|
||||||
|
r.events.push(Event {
|
||||||
|
at: 60,
|
||||||
|
pos: DVec3::ZERO,
|
||||||
|
kind: EventKind::Kill { drone: 7, kind: DroneKind::Shahed, sam: 10, sam_kind: SamKind::Pantsir, sam_index: 0, missile: Some(500), outcome: Outcome::DisabledFalling },
|
||||||
|
});
|
||||||
|
let chains = r.chains(None);
|
||||||
|
assert_eq!(chains.len(), 1);
|
||||||
|
let chain = &chains[0];
|
||||||
|
let kinds: Vec<ChainStepKind> = chain.steps.iter().map(|s| s.kind).collect();
|
||||||
|
assert_eq!(kinds, vec![ChainStepKind::Mark, ChainStepKind::Handoff, ChainStepKind::Lock, ChainStepKind::Launch, ChainStepKind::Outcome]);
|
||||||
|
assert_eq!(chain.outcome, ChainOutcome::Destroyed);
|
||||||
|
assert_eq!(chain.outcome_event(), Some(0));
|
||||||
|
assert!(!chain.missed());
|
||||||
|
assert_eq!(chain.marked_at(), 20);
|
||||||
|
assert_eq!(r.chains(Some(10)).len(), 1);
|
||||||
|
assert!(r.chains(Some(20)).is_empty(), "the filter picked another battery");
|
||||||
|
|
||||||
|
// A contact marked and lost without a launch is a missed chain, not an engagement.
|
||||||
|
let mut r = Recording::blank(100);
|
||||||
|
r.sams = vec![(10, SamKind::Pantsir, DVec3::ZERO)];
|
||||||
|
let mut scene = SceneJournal::default();
|
||||||
|
scene.push(at(10, SceneKind::TrackAcquired { sam: 10, target: 8, ever_own: false }));
|
||||||
|
scene.push(at(50, SceneKind::TrackLost { sam: 10, target: 8 }));
|
||||||
|
r.scene = Some(scene);
|
||||||
|
let chain = &r.chains(None)[0];
|
||||||
|
assert!(chain.missed());
|
||||||
|
assert_eq!(chain.outcome, ChainOutcome::Lost);
|
||||||
|
assert_eq!(chain.steps.len(), 2);
|
||||||
|
assert_eq!(chain.outcome_event(), None);
|
||||||
|
}
|
||||||
|
|
||||||
fn recording() -> Recording {
|
fn recording() -> Recording {
|
||||||
Recording {
|
Recording {
|
||||||
number: 1,
|
number: 1,
|
||||||
@@ -1089,6 +1395,7 @@ mod tests {
|
|||||||
sam_tracks: Vec::new(),
|
sam_tracks: Vec::new(),
|
||||||
sam_index: HashMap::new(),
|
sam_index: HashMap::new(),
|
||||||
sam_keys: 0,
|
sam_keys: 0,
|
||||||
|
sam_events: 0,
|
||||||
sam_step: STEP,
|
sam_step: STEP,
|
||||||
ticks: Vec::new(),
|
ticks: Vec::new(),
|
||||||
times: Vec::new(),
|
times: Vec::new(),
|
||||||
@@ -1244,6 +1551,7 @@ mod tests {
|
|||||||
let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
||||||
let allocated: usize = r.sam_tracks.iter().map(|track| track.keys.capacity()).sum();
|
let allocated: usize = r.sam_tracks.iter().map(|track| track.keys.capacity()).sum();
|
||||||
assert_eq!(keys, r.sam_keys);
|
assert_eq!(keys, r.sam_keys);
|
||||||
|
assert_eq!(r.sam_events, 0, "a turning dish is a pose, not a transition");
|
||||||
assert!(keys <= MAX_SAM_KEYS, "a full recording retained {keys} SamKeys");
|
assert!(keys <= MAX_SAM_KEYS, "a full recording retained {keys} SamKeys");
|
||||||
assert!(allocated <= 2 * MAX_SAM_KEYS, "SamKey allocations reached {} MiB", allocated * size_of::<SamKey>() / (1024 * 1024));
|
assert!(allocated <= 2 * MAX_SAM_KEYS, "SamKey allocations reached {} MiB", allocated * size_of::<SamKey>() / (1024 * 1024));
|
||||||
assert!(r.sam_step > STEP, "the rotating radars never engaged adaptive sampling");
|
assert!(r.sam_step > STEP, "the rotating radars never engaged adaptive sampling");
|
||||||
@@ -1252,6 +1560,104 @@ mod tests {
|
|||||||
assert!(last.dish > 100.0, "the final radar pose was not recorded");
|
assert!(last.dish > 100.0, "the final radar pose was not recorded");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #142: sixty-four turning radars on a 16-tick pose grid plus a cold S-400 launch. The
|
||||||
|
// cover's six-tick opening, the ejection and the spent cell must survive the decimation, and
|
||||||
|
// so must the radar's switch and a cancelled cover, on the tick they happened.
|
||||||
|
#[test]
|
||||||
|
fn decimation_keeps_a_cold_launch_cover_ejection_and_the_radar_switch() {
|
||||||
|
let mut r = recording();
|
||||||
|
let mut sams: Vec<_> = (0..64).map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0)).collect();
|
||||||
|
sams.push(Sam::new(100, SamKind::S400, DVec3::ZERO, 0.0));
|
||||||
|
let turned_off = 5_usize;
|
||||||
|
// The pose budget of a long recording has already slowed the sampling down.
|
||||||
|
r.sam_step = 16;
|
||||||
|
let eject = 4103u32;
|
||||||
|
let start = eject - launch::OPEN_TICKS as u32;
|
||||||
|
let (reopen, close, switch) = (4120u32, 4122u32, 4131u32);
|
||||||
|
for now in 0..4_200 {
|
||||||
|
for sam in &mut sams[..64] {
|
||||||
|
sam.dish = now as f64 * 0.01;
|
||||||
|
}
|
||||||
|
let s400 = sams.len() - 1;
|
||||||
|
if now == start {
|
||||||
|
assert!(!sams[s400].prepare_tube(7, now as u64));
|
||||||
|
} else if (start + 1..=eject).contains(&now) {
|
||||||
|
if sams[s400].prepare_tube(7, now as u64) {
|
||||||
|
assert_eq!(now, eject);
|
||||||
|
sams[s400].eject_cell(0);
|
||||||
|
}
|
||||||
|
} else if (reopen..close).contains(&now) {
|
||||||
|
// A second opening, cancelled before it is wide: the cover closes.
|
||||||
|
sams[s400].prepare_tube(7, now as u64);
|
||||||
|
} else if now == close {
|
||||||
|
sams[s400].cancel_prepare();
|
||||||
|
}
|
||||||
|
if now == switch {
|
||||||
|
sams[turned_off].radar_on = false;
|
||||||
|
}
|
||||||
|
r.note_sams(&sams, now);
|
||||||
|
}
|
||||||
|
let track = |id: u32| r.sam_tracks.iter().find(|track| track.id == id).unwrap();
|
||||||
|
let pose = |id: u32, t: f64| track(id).pose(t).unwrap();
|
||||||
|
let s400 = track(100);
|
||||||
|
assert!(s400.keys.len() < 32, "the launch track kept {} keys", s400.keys.len());
|
||||||
|
// The cover was shut before the stage and opens exactly over `OPEN_TICKS` ticks.
|
||||||
|
assert_eq!(pose(100, f64::from(start - 1)).cap_open, 0.0);
|
||||||
|
for k in 1..launch::OPEN_TICKS as u32 {
|
||||||
|
let want = k as f32 / launch::OPEN_TICKS as f32;
|
||||||
|
let got = pose(100, f64::from(start + k)).cap_open;
|
||||||
|
assert!((got - want).abs() < 1e-5, "tick {} of the opening: {got} not {want}", start + k);
|
||||||
|
}
|
||||||
|
assert!(s400.keys.iter().any(|k| k.at == start && k.event && k.cap_open == 0.0), "the stage's start key is kept");
|
||||||
|
// The last tick before the ejection: the cover stands five sixths open, not shut.
|
||||||
|
assert!((pose(100, f64::from(eject - 1)).cap_open - 5.0 / 6.0).abs() < 1e-5);
|
||||||
|
// The ejection: the cell is spent on its own tick, not on the next pose sample.
|
||||||
|
assert_eq!(pose(100, f64::from(eject - 1)).spent_cells, 0);
|
||||||
|
assert_eq!(pose(100, f64::from(eject)).spent_cells, 1);
|
||||||
|
assert!(track(100).keys.iter().any(|k| k.at == eject && k.event));
|
||||||
|
// The cancelled opening closes the cover on the tick it was cancelled.
|
||||||
|
assert!(pose(100, f64::from(close - 1)).cap_open > 0.0);
|
||||||
|
assert_eq!(pose(100, f64::from(close)).cap_open, 0.0);
|
||||||
|
// The radar's switch is on its own tick, between two 16-tick pose samples.
|
||||||
|
assert!(pose(turned_off as u32, f64::from(switch - 1)).radar_on);
|
||||||
|
assert!(!pose(turned_off as u32, f64::from(switch)).radar_on);
|
||||||
|
assert!(track(turned_off as u32).keys.iter().any(|k| k.at == switch && k.event));
|
||||||
|
// Later decimation halves poses only: the recorded launch still reads as it did.
|
||||||
|
r.thin_sam_poses();
|
||||||
|
r.thin_sam_poses();
|
||||||
|
let track = |id: u32| r.sam_tracks.iter().find(|track| track.id == id).unwrap();
|
||||||
|
let pose = |id: u32, t: f64| track(id).pose(t).unwrap();
|
||||||
|
assert!((pose(100, f64::from(eject - 1)).cap_open - 5.0 / 6.0).abs() < 1e-5);
|
||||||
|
assert_eq!(pose(100, f64::from(eject)).spent_cells, 1);
|
||||||
|
assert!(!pose(turned_off as u32, f64::from(switch)).radar_on);
|
||||||
|
}
|
||||||
|
|
||||||
|
// #142: the transitions have their own explicit budget. A recording that chatters must stay
|
||||||
|
// bounded, and the newest transitions — what a replay is watched closest for — stay exact.
|
||||||
|
#[test]
|
||||||
|
fn critical_transitions_have_their_own_explicit_budget() {
|
||||||
|
let mut r = recording();
|
||||||
|
let mut sams: Vec<_> = (0..64).map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0)).collect();
|
||||||
|
let ticks = 1_500u32;
|
||||||
|
for now in 0..ticks {
|
||||||
|
for sam in &mut sams {
|
||||||
|
sam.radar_on = now % 2 == 0;
|
||||||
|
}
|
||||||
|
r.note_sams(&sams, now);
|
||||||
|
}
|
||||||
|
let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
||||||
|
assert_eq!(keys, r.sam_keys);
|
||||||
|
assert_eq!(r.sam_events, MAX_SAM_EVENTS, "the transitions' budget is explicit");
|
||||||
|
assert!(keys <= MAX_SAM_KEYS + MAX_SAM_EVENTS + sams.len(), "{keys} SamKeys retained");
|
||||||
|
assert!(keys - r.sam_events <= MAX_SAM_KEYS, "poses broke their own budget");
|
||||||
|
// The newest switch reads exactly; the oldest transitions were the ones let go.
|
||||||
|
let newest = r.sam_tracks[0].pose(f64::from(ticks - 1)).unwrap();
|
||||||
|
assert_eq!(newest.radar_on, (ticks - 1) % 2 == 0);
|
||||||
|
assert!(r.sam_tracks[0].keys.iter().any(|key| key.at == ticks - 1 && key.event));
|
||||||
|
let earliest = r.sam_tracks[0].keys.iter().position(|key| key.event);
|
||||||
|
assert!(earliest.is_none_or(|i| r.sam_tracks[0].keys[i].at > ticks / 2), "old transitions hold on to the budget");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_system_keeps_its_pose_through_stillness_and_moves_when_it_moved() {
|
fn a_system_keeps_its_pose_through_stillness_and_moves_when_it_moved() {
|
||||||
let mut r = recording();
|
let mut r = recording();
|
||||||
|
|||||||
@@ -363,6 +363,11 @@ 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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -287,6 +287,312 @@ 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(), sam.radar_profile().channels));
|
||||||
|
let reason = |kind, block, target, mark| BattleReason {
|
||||||
|
kind,
|
||||||
|
block,
|
||||||
|
sam: index,
|
||||||
|
target,
|
||||||
|
mark,
|
||||||
|
rounds: sam.missiles,
|
||||||
|
bursts: sam.bursts,
|
||||||
|
reloading: sam.reloading,
|
||||||
|
channels,
|
||||||
|
};
|
||||||
|
if !sam.alive() {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Destroyed), None, None));
|
||||||
|
}
|
||||||
|
if self.hold {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Hold), None, None));
|
||||||
|
}
|
||||||
|
if sam.moving() {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Moving), None, None));
|
||||||
|
}
|
||||||
|
if !sam.kind.armed() {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoWeapon), None, None));
|
||||||
|
}
|
||||||
|
let (missile_on, guns_on) = engagement_counts(&self.sams);
|
||||||
|
let drone_at = |id: u32| self.drones.iter().find(|d| d.id == id);
|
||||||
|
let subject = chosen
|
||||||
|
.and_then(drone_at)
|
||||||
|
.filter(|d| d.alive())
|
||||||
|
.or_else(|| sam.target.or(sam.gun_target).and_then(drone_at).filter(|d| d.alive()))
|
||||||
|
.or_else(|| {
|
||||||
|
self.drones
|
||||||
|
.iter()
|
||||||
|
.filter(|d| {
|
||||||
|
d.alive()
|
||||||
|
&& (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles))
|
||||||
|
|| last_chance(self.last_chance, sam.roles, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target)))
|
||||||
|
})
|
||||||
|
.max_by(|a, b| {
|
||||||
|
let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, now) == 0);
|
||||||
|
area(a).cmp(&area(b)).then(a.threat(sam.pos).total_cmp(&b.threat(sam.pos)))
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let Some(t) = subject else {
|
||||||
|
let block = if sam.roles == 0 {
|
||||||
|
BattleBlock::Hold
|
||||||
|
} else if self.drones.iter().any(|d| d.alive() && sam.seen.contains(&d.id)) {
|
||||||
|
BattleBlock::OutOfRoles
|
||||||
|
} else {
|
||||||
|
BattleBlock::NoTarget
|
||||||
|
};
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(block), None, None));
|
||||||
|
};
|
||||||
|
let track = sam.track(t.id);
|
||||||
|
let mark = track.map(|tr| BattleMark::of(self, sam, tr, now));
|
||||||
|
let has_missile = spec.missile.is_some() && sam.missiles > 0 && sam.part(Part::Launcher) > 0.0;
|
||||||
|
let has_gun = spec.gun.is_some() && sam.bursts > 0 && sam.part(Part::Gun) > 0.0;
|
||||||
|
if sam.reloading > 0 || (!has_missile && !has_gun) {
|
||||||
|
return Some(reason(BattleKind::NoAmmo, None, Some(t.id), mark));
|
||||||
|
}
|
||||||
|
if spec.missile.is_some() && sam.part(Part::Launcher) <= 0.0 && !has_gun {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::LauncherDown), Some(t.id), mark));
|
||||||
|
}
|
||||||
|
let Some(tr) = track else {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoTrack), Some(t.id), mark));
|
||||||
|
};
|
||||||
|
let est = tr.class;
|
||||||
|
let blocks = target_blocks(sam.roles, Some(tr), now, t);
|
||||||
|
let claimed_now = claimed(t, &missile_on, sam.target);
|
||||||
|
let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, t, claimed_now);
|
||||||
|
if blocks & ROLE != 0 && !chance {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(if sam.roles == 0 { BattleBlock::Hold } else { BattleBlock::OutOfRoles }), Some(t.id), mark));
|
||||||
|
}
|
||||||
|
let doc = &sam.doctrine;
|
||||||
|
let area = doc.area_blocks(sam.pos, tr, now);
|
||||||
|
let reserve = spec.missile.is_some().then(|| doc.reserve_blocks(sam.missiles, t, est)).unwrap_or(0);
|
||||||
|
if blocks & ROLE == 0 && (area | reserve) != 0 {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Doctrine), Some(t.id), mark));
|
||||||
|
}
|
||||||
|
let est_at = tr.est(now);
|
||||||
|
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
|
||||||
|
let cued = radar_cue(sam, &radars, t.id, now);
|
||||||
|
let role_in_reach = spec.missile.as_ref().is_some_and(|load| {
|
||||||
|
self.drones.iter().any(|o| {
|
||||||
|
sam.track(o.id).is_some_and(|other| {
|
||||||
|
allowed(sam.roles, other, now, o)
|
||||||
|
&& in_reach(load.min, load.max, 1.0, sam.pos, other.est(now))
|
||||||
|
&& doc.area_blocks(sam.pos, other, now) | doc.reserve_blocks(sam.missiles, o, other.class) == 0
|
||||||
|
&& claimed(o, &missile_on, sam.target) < doc.needed(o, other.class)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let reach = spec.missile.as_ref().map_or(0, |load| reach_blocks(load.min, load.max, 1.0, sam.pos, est_at));
|
||||||
|
let far_ok = spec.missile.as_ref().is_some_and(|load| {
|
||||||
|
reach == TOO_FAR
|
||||||
|
&& reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0
|
||||||
|
&& far_blocks(self.far_shots, sam, load, cued, role_in_reach) == 0
|
||||||
|
});
|
||||||
|
if spec.missile.is_some() {
|
||||||
|
if reach == TOO_CLOSE || (reach == TOO_FAR && !far_ok) {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::OutOfReach), Some(t.id), mark));
|
||||||
|
}
|
||||||
|
} else if let Some(gun) = &spec.gun {
|
||||||
|
if sam.mount().0.distance(est_at) >= gun.range {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::OutOfReach), Some(t.id), mark));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let own_fire = tr.own_authorizes(now);
|
||||||
|
let gun_ready = spec.gun.is_some() && tr.own_within(now, sight::GUN_PICK_AGE);
|
||||||
|
let authorized = if spec.missile.is_some() {
|
||||||
|
own_fire || (sam.mode == battery::SamMode::LauncherOnly && cued) || far_ok
|
||||||
|
} else {
|
||||||
|
gun_ready
|
||||||
|
};
|
||||||
|
if !authorized {
|
||||||
|
if sam.mode == battery::SamMode::LauncherOnly {
|
||||||
|
// The launcher's picture is the supporting radar's. If that radar has the
|
||||||
|
// contact but every tracked-contact channel is taken, the reason is the
|
||||||
|
// channels, not a missing hand-off.
|
||||||
|
let support = radars.iter().find_map(|r| {
|
||||||
|
let linked = r.alive()
|
||||||
|
&& !r.moving()
|
||||||
|
&& r.radar_up()
|
||||||
|
&& r.radar_profile().products & battery::RadarProfile::FIRE_BIT != 0
|
||||||
|
&& r.link_range() > 0.0
|
||||||
|
&& sam.link_range() > 0.0
|
||||||
|
&& r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range());
|
||||||
|
linked.then(|| r.track(t.id).map(|tr| (*r, *tr))).flatten()
|
||||||
|
});
|
||||||
|
if let Some((radar, tr)) = support {
|
||||||
|
let profile = radar.radar_profile();
|
||||||
|
let used = radar.own_channels_used();
|
||||||
|
if profile.channels > 0 && used >= profile.channels as usize && !tr.own_authorizes(now) {
|
||||||
|
let mut busy = reason(BattleKind::ChannelsBusy, None, Some(t.id), mark);
|
||||||
|
busy.channels = Some((used, profile.channels));
|
||||||
|
return Some(busy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark));
|
||||||
|
}
|
||||||
|
let busy = channels.is_some_and(|(used, total)| used >= total as usize);
|
||||||
|
if busy {
|
||||||
|
return Some(reason(BattleKind::ChannelsBusy, None, Some(t.id), mark));
|
||||||
|
}
|
||||||
|
if tr.own_tick > 0 && tr.own_product == battery::Measure::Refine {
|
||||||
|
return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark));
|
||||||
|
}
|
||||||
|
if tr.own_tick > 0 && tr.own_product == battery::Measure::Fire {
|
||||||
|
return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark));
|
||||||
|
}
|
||||||
|
return Some(reason(BattleKind::ObserveOnly, None, Some(t.id), mark));
|
||||||
|
}
|
||||||
|
let need = doc.needed(t, est);
|
||||||
|
if spec.missile.is_some() && claimed_now >= need {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Claimed), Some(t.id), mark));
|
||||||
|
}
|
||||||
|
if spec.missile.is_none() && guns_on.get(&t.id).copied().unwrap_or(0) > 1 {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Claimed), Some(t.id), mark));
|
||||||
|
}
|
||||||
|
let mount = sam.mount().0;
|
||||||
|
let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell);
|
||||||
|
let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, tr.vel, lead_speed);
|
||||||
|
if aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch) >= 0.15 {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Aiming), Some(t.id), mark));
|
||||||
|
}
|
||||||
|
if sam.preparing.is_some() {
|
||||||
|
return Some(reason(BattleKind::Blocked, Some(BattleBlock::Preparing), Some(t.id), mark));
|
||||||
|
}
|
||||||
|
Some(reason(BattleKind::Ready, None, Some(t.id), mark))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
@@ -310,6 +616,20 @@ 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
|
||||||
@@ -321,14 +641,17 @@ 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() {
|
||||||
@@ -364,6 +687,7 @@ 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();
|
||||||
@@ -430,6 +754,7 @@ 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);
|
||||||
@@ -644,6 +969,21 @@ 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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1016,6 +1356,129 @@ 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.
|
||||||
|
|||||||
+107
-1
@@ -1,5 +1,5 @@
|
|||||||
//! Text for diagnostics produced by the simulation.
|
//! Text for diagnostics produced by the simulation.
|
||||||
use crate::sim::why::{CheckReason, PartEffect};
|
use crate::sim::why::{BattleBlock, BattleKind, BattleMark, BattleReason, CheckReason, PartEffect};
|
||||||
use crate::sim::{Comps, Part, SamKind};
|
use crate::sim::{Comps, Part, SamKind};
|
||||||
|
|
||||||
fn part_value(part: Part, value: f64) -> String {
|
fn part_value(part: Part, value: f64) -> String {
|
||||||
@@ -25,9 +25,81 @@ pub fn worst(comps: &Comps, kind: SamKind) -> String {
|
|||||||
.map(|p| part_value_on(*p, comps.get(*p), kind)).unwrap_or_default()
|
.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(),
|
||||||
@@ -79,6 +151,40 @@ 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,13 +50,15 @@ 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,
|
||||||
|
# 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.feedback = "№4 РЛС: роль search"
|
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в search не меняет оборудование. Доступно on/off."
|
||||||
|
|
||||||
[[step]]
|
[[step]]
|
||||||
command = "airdef radar 4 engagement"
|
command = "airdef radar 4 engagement"
|
||||||
expect.feedback = "№4 РЛС: роль engagement"
|
expect.error = "Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в engagement не меняет оборудование. Доступно on/off."
|
||||||
|
|
||||||
[[step]]
|
[[step]]
|
||||||
command = "airdef radar 4 off"
|
command = "airdef radar 4 off"
|
||||||
|
|||||||
+4
-1
@@ -254,7 +254,10 @@ 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. По умолчанию DLSS рендерит world 2/3,
|
world+linearize → NGX → delinearize; native TAAU остаётся fallback. #137 довёл порядок до контракта:
|
||||||
|
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,6 +33,33 @@
|
|||||||
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
-1
Submodule horizon updated: 2bcce64236...1cadd63387
Reference in New Issue
Block a user