Implement the first full radar-profile slice (#134)

Give the separate radar three real profiles over SamKind::Radar and the
typed catalog variants:

- radar_search: coarse, slow, long-range search plots; no fire authority.
- radar_height: raised mast, local refinement of low plots; no fire authority.
- radar_track: local search, fast revisit, two refined/fire channels.
- radar_multi remains the compatible universal profile, not best everywhere.

Tracks now carry the measuring station, product (search/refine/fire), and
quality (separate from identification), and keep the station's own plot when a
fresher network relay replaces the published position. A relay never refreshes
the measurement or authorizes a launch. Ordinary launches need the battery's
own confirmed fire plot; launcher-only batteries use a supporting radar's own
plot, and the existing heavy far shot keeps its cue-radar exception.

Per-tick refinement/fire work is bounded by profile channels and local search
radius. Off, damage, network and save/replay behavior are preserved: new saves
write the stable profile ID, old role-only lines migrate, and embedded SAM
radars keep their own fire authority. The deploy menu, status lines, map,
monitor, radar scope and /airdef why explain the profile, source, age, quality,
channels and refusal reason.

Models/textures are untouched: all profiles reuse the existing radar
silhouette (the separate art zone remains for its owner).

Tests: profile single/pair/full scenarios and duplicate station, channels,
relay source/age/quality, Off/damage, save migration, replay, embedded and
Multifunction radars, catalog/generator checks, airdef-mod suites, core lib
(non-balance on one thread; the four active balance tests in release) and core
scenarios.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
2026-11-20 22:30:10 +03:00
parent ac7521936d
commit 858735a4c6
25 changed files with 1074 additions and 122 deletions
+1 -1
View File
@@ -219,7 +219,7 @@ API мода `render.set-lights` (до 512, плавно интерполиру
- `/airdef sites` — известные пусковые площадки (ПУ). РЛС с прямой видимостью может заметить сам пуск и получить неточную позицию; несколько наблюдённых пусков уточняют её. Обнаруженный позже дрон даёт только слабое предположение об обратном курсе: скрытые координаты площадки и время невидимого старта не используются. Повторные треки одного полёта не создают ложную точность.
- `/airdef strike <номер ПУ>` — ручной удар по разведанной площадке из готового физического С-400 с отдельно загруженной RM48U (игровой профиль, #118). Четыре ячейки делятся с боезапасом ПВО; приказ резервирует носитель и ячейку, открывает крышку и списывает одну ударную ракету при выбросе. Выбирается готовый комплекс с наибольшим остатком RM48U, затем ближайший к цели. Есть открытие ТПК, выброс, отложенное включение двигателя и разгон, ограниченная игровая траектория, столкновения и запись пуска. Несуществующее «ПВО площадки» не перехватывает ракету по броску вероятности.
- `/airdef ground-stock <номер склада> <количество>` — задать остаток RM48U для sandbox-сценария (по умолчанию 0). `/airdef ground-load <номер С-400>` загружает одну ракету у склада либо заказывает ТЗМ; `ground-unload` возвращает её у склада либо заказывает вывоз; `ground-cancel` отменяет ожидающую заявку. Доставка и обратный вывоз через ТЗМ реализованы, запас и груз сохраняются. [Пошаговый пример](docs/GROUND-STRIKES.md). Совместимость профиля основана на [публикации ГУР](https://gur.gov.ua/content/warsanctions-hur-mo-rozkryvaie-budovu-komponentnu-bazu-ta-pidpryiemstva-kooperatsii-z-vyrobnytstva-udarnykh-raket-rm48u.html); это сообщение ведомства, не независимая сертификация. Дальность, форма полёта и оформление условны для Minecraft.
- `/airdef deploy s400_launcher` и `s500_launcher` — отдельные пусковые без своей РЛС; `radar_search`, `radar_track`, `radar_height` — обзорная, сопровождающая и мачтовая игровые РЛС. Они также доступны через меню N → «Разместить элементы батареи…». `/airdef battery` показывает состав и связь; `/airdef battery <номер> integrated|launcher` меняет конфигурацию, `/airdef radar <номер> multi|search|engagement|height` — роль отдельной РЛС. Обзорная РЛС передаёт подсказки; станция сопровождения должна сама получить свежее измерение, чтобы разрешить пуск. Старые С-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 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 deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
+53 -17
View File
@@ -1,23 +1,34 @@
//! Player-facing labels for battery configuration and status.
use crate::sim::battery::{BatteryStatus, RadarRole, SamMode};
use crate::sim::battery::{BatteryStatus, RadarProfile, SamMode};
use crate::sim::{Sam, SamKind};
pub fn radar_role_name(role: RadarRole) -> &'static str {
match role {
RadarRole::Multifunction => "многофункциональная",
RadarRole::Search => "обзорная",
RadarRole::Engagement => "сопровождения",
RadarRole::Height => "мачтовая",
}
/// One profile's functions in a line the player can read.
pub fn radar_profile_line(profile: RadarProfile) -> String {
let channels = if profile.channels == 0 { "без каналов уточнения".to_string() } else { format!("каналы {}", profile.channels) };
format!(
"{} [{}]: {}, оборот {:.1} с, {}, локальный поиск {}; развёртывание: {}",
profile.name,
profile.id,
profile.products_text(),
profile.cycle as f64 / 20.0,
channels,
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
profile.deployment,
)
}
pub fn status(status: BatteryStatus) -> String {
match status {
BatteryStatus::Radar { index, role, emitting, operational } => format!(
"№{} РЛС: {}, излучение {}, {}", index + 1, radar_role_name(role),
if emitting { "вкл" } else { "выкл" },
if operational { "работает" } else { "нет связи или РЛС не работает" }
),
BatteryStatus::Radar { index, role, emitting, operational } => {
let profile = role.profile();
format!(
"№{} РЛС: {}; излучение {}, {}",
index + 1,
radar_profile_line(profile),
if emitting { "вкл" } else { "выкл" },
if operational { "работает" } else { "нет связи или РЛС не работает" }
)
}
BatteryStatus::Launcher { index, kind, mode, linked } => format!(
"№{} {}: {}{}", index + 1, kind.name(), mode.key(),
if mode == SamMode::LauncherOnly {
@@ -52,7 +63,13 @@ pub fn sam_status(sam: &Sam) -> String {
}
SamKind::Radar => {
let broken = if sam.comps.whole() { String::new() } else { format!(" [{}]", crate::why_view::worst(&sam.comps, sam.kind)) };
return format!("{text}: целей {}{broken}", sam.own.len());
let profile = sam.radar_profile();
let channels = if profile.channels == 0 {
"без уточнения".to_string()
} else {
format!("каналы {}/{}", sam.own_channels_used(), profile.channels)
};
return format!("{text} «{}»: {}; целей {}{broken}, {channels}", profile.name, profile.products_text(), sam.own.len());
}
SamKind::Light => return format!("{text}{}", if sam.target.is_some() { ": в луче цель" } else { "" }),
_ => {}
@@ -90,6 +107,7 @@ pub fn sam_status(sam: &Sam) -> String {
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::battery::RadarRole;
use crate::sim::{Part, Sam, SamKind, SamState};
use glam::DVec3;
@@ -119,7 +137,7 @@ mod tests {
let mut radar = Sam::new(4, SamKind::Radar, DVec3::ZERO, 0.0);
radar.own.push(7);
radar.comps.0[Part::Sensor as usize] = 0.0;
assert_eq!(sam_status(&radar), "РЛС дальнего обнаружения: целей 1 [РЛС отказ]");
assert_eq!(sam_status(&radar), "РЛС дальнего обнаружения «многофункциональная»: обзор, уточнение, пуск; целей 1 [РЛС отказ], каналы 0/3");
let mut depot = Sam::new(5, SamKind::Depot, DVec3::ZERO, 0.0);
depot.cargo = 2;
@@ -153,10 +171,28 @@ mod tests {
assert_eq!(sam_status(&dead), "С-400 УНИЧТОЖЕН");
}
#[test]
fn profiles_explain_their_different_functions() {
for role in [RadarRole::Search, RadarRole::Height, RadarRole::Engagement, RadarRole::Multifunction] {
let text = radar_profile_line(role.profile());
assert!(text.contains(role.profile().id));
assert!(text.contains(&format!("оборот {:.1} с", role.profile().cycle as f64 / 20.0)));
}
assert!(radar_profile_line(RadarRole::Search.profile()).contains("без каналов"));
assert!(radar_profile_line(RadarRole::Engagement.profile()).contains("каналы 2"));
assert!(radar_profile_line(RadarRole::Height.profile()).contains("уточнение"));
}
#[test]
fn renders_battery_status_in_existing_format() {
assert_eq!(status(BatteryStatus::Radar { index: 0, role: RadarRole::Search, emitting: false, operational: false }), "№1 РЛС: обзорная, излучение выкл, нет связи или РЛС не работает");
assert_eq!(status(BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }), "№2 РЛС: сопровождения, излучение вкл, работает");
assert_eq!(
status(BatteryStatus::Radar { index: 0, role: RadarRole::Search, emitting: false, operational: false }),
"№1 РЛС: дальнего обзора [radar_search]: обзор, оборот 8.5 с, без каналов уточнения, локальный поиск во всей дальности; развёртывание: крупная стационарная антенна; излучение выкл, нет связи или РЛС не работает"
);
assert_eq!(
status(BatteryStatus::Radar { index: 1, role: RadarRole::Engagement, emitting: true, operational: true }),
"№2 РЛС: сопровождения [radar_track]: обзор, уточнение, пуск, оборот 3.5 с, каналы 2, локальный поиск 12% дальности; развёртывание: мобильная панель; излучение вкл, работает"
);
assert_eq!(status(BatteryStatus::Launcher { index: 2, kind: SamKind::S400, mode: SamMode::LauncherOnly, linked: true }), "№3 С-400: launcher, РЛС связана");
assert_eq!(status(BatteryStatus::Launcher { index: 3, kind: SamKind::S500, mode: SamMode::LauncherOnly, linked: false }), "№4 С-500: launcher, нет связанной РЛС сопровождения");
assert_eq!(status(BatteryStatus::Launcher { index: 4, kind: SamKind::S400, mode: SamMode::Integrated, linked: false }), "№5 С-400: integrated");
+13 -1
View File
@@ -73,7 +73,7 @@ pub fn tree() -> Tree {
Node::lit("target").then(Node::lit("here").runs()),
Node::lit("give").runs(),
Node::lit("battery").runs().then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::choice(["integrated", "launcher"])).runs())),
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("роль", Value::choice(["on", "off", "multi", "search", "engagement", "height"])).runs())),
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::Word(vec!["on".into(), "off".into()])).runs())),
Node::lit("deploy").then(Node::arg("комплекс", Value::choice(deploy_kinds)).runs()),
Node::lit("wave").then(
Node::arg("тип", Value::choice(wave_kinds)).runs().then(
@@ -258,6 +258,18 @@ mod tests {
assert!(complete("wave nothing ", &[]).is_empty());
}
/// A station's profile is fixed at deployment: completion offers only emission, while an
/// old role word still reaches the handler's explanation instead of a bare parse error.
#[test]
fn radar_completion_offers_emission_only() {
let words = complete("radar 1 ", &[]);
assert_eq!(words.len(), 2, "{words:?}");
assert!(words.contains(&"on".to_string()) && words.contains(&"off".to_string()));
for old in ["multi", "search", "engagement", "height"] {
assert!(tree().parse(&format!("radar 1 {old}")).is_ok(), "`{old}` should reach the handler");
}
}
/// The names follow the data: after a save the new name is offered, after a delete it is gone.
#[test]
fn scenario_names_follow_a_save_and_a_delete() {
+36 -1
View File
@@ -31,6 +31,9 @@ pub struct SamRec {
pub air_48n6_stock: u32,
pub mode: sim::battery::SamMode,
pub radar_role: sim::battery::RadarRole,
/// The stable profile ID when the file names one (new saves); old files
/// have only the role key, which migrates to the matching profile.
pub radar_profile: Option<sim::battery::RadarProfile>,
pub spent_cells: u8,
pub radar_on: bool,
}
@@ -147,10 +150,20 @@ impl Layout {
let radar_on = l.flag(29, "излучение РЛС")?.unwrap_or(true);
let ground_return = l.flag(30, "заявка на вывоз RM48U")?.unwrap_or(false);
let return_cargo = l.flag(31, "возвращаемый груз RM48U")?.unwrap_or(false);
let radar_profile = match l.w.get(32) {
None => None,
Some(v) => Some(sim::battery::RadarProfile::from_id(v).ok_or_else(|| l.bad("профиль РЛС", "radar_multi, radar_search, radar_track или radar_height"))?),
};
if (ground_return && (kind != SamKind::S400 || ground_request || ground_rounds == 0)) || (return_cargo && (kind != SamKind::Tzm || ground_stock == 0)) { return Err(l.bad("возврат RM48U", "несовместимое состояние")); }
if radar_role != sim::battery::RadarRole::Multifunction && kind != SamKind::Radar {
return Err(l.bad("роль РЛС", "роль поддерживается только отдельной РЛС"));
}
if let Some(profile) = radar_profile {
if kind != SamKind::Radar { return Err(l.bad("профиль РЛС", "профиль поддерживается только отдельной РЛС")); }
if profile.role() != radar_role { return Err(l.bad("профиль РЛС", "профиль и роль не совпадают")); }
}
// An old line has only the role: it migrates to the matching profile.
let radar_profile = radar_profile.or((kind == SamKind::Radar).then(|| sim::battery::RadarProfile::of(radar_role)));
if mode == sim::battery::SamMode::LauncherOnly && !matches!(kind, SamKind::S400 | SamKind::S500) {
return Err(l.bad("режим", "пусковая поддерживается только С-400 и С-500"));
}
@@ -160,7 +173,7 @@ impl Layout {
if let Some((m, _, _, _)) = ammo && m + ground_rounds > 4 && kind == SamKind::S400 {
return Err(l.bad("боезапас", "больше четырёх ячеек"));
}
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock, mode, radar_role, spent_cells, ground_request, radar_on, ground_return, return_cargo });
out.sams.push(SamRec { kind, pos, heading, roles, health, cargo, ammo, dest, comps, ground_rounds, ground_stock, air_48n6_stock, mode, radar_role, radar_profile, spent_cells, ground_request, radar_on, ground_return, return_cargo });
}
"target" => {
if out.targets.len() >= MAX_UNITS {
@@ -220,6 +233,7 @@ mod tests {
assert_eq!(l.sams[0].mode, sim::battery::SamMode::LauncherOnly);
assert_eq!(l.sams[0].spent_cells, 5);
assert_eq!(l.sams[1].radar_role, sim::battery::RadarRole::Engagement);
assert_eq!(l.sams[1].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT), "an old role-only line migrates");
assert!(!Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 false")).unwrap().sams[0].radar_on);
assert!(Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 nope")).is_err());
assert!(Layout::parse(&data.replace("engagement", "invalid")).is_err());
@@ -258,6 +272,27 @@ mod tests {
assert!(Layout::parse(&many).is_err(), "no limit on the number of objects");
}
#[test]
fn radar_profile_ids_round_trip_and_old_roles_map_to_them() {
let old = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated search";
let l = Layout::parse(old).unwrap();
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Search);
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::SEARCH));
let new = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated engagement 0 0 true false false radar_track";
let l = Layout::parse(new).unwrap();
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT));
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Engagement);
assert_eq!(
Layout::parse("sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated multi 0 0 true false false radar_multi").unwrap().sams[0].radar_profile,
Some(sim::battery::RadarProfile::MULTI)
);
// A profile and the legacy role must agree; a profile on a non-radar is refused.
assert!(Layout::parse(&new.replace("engagement 0", "search 0")).is_err());
assert!(Layout::parse(&new.replace("sam radar", "sam s400").replace("engagement", "multi")).is_err());
assert!(Layout::parse(&new.replace("radar_track", "radar_unknown")).is_err());
assert_eq!(sim::battery::RadarProfile::from_id("multi"), Some(sim::battery::RadarProfile::MULTI));
}
// #86: files made by older builds (no ammunition, no parts, no destination marks) and unknown lines still load
#[test]
fn older_valid_saves_still_load() {
+37 -11
View File
@@ -900,8 +900,9 @@ impl AirDef {
// The parts' states (sensor, mount, launcher, gun, tracks, comms) close the line; older saves lack them.
let comps = if fresh { new.comps } else { s.comps };
let parts = comps.0.iter().map(|v| format!("{v:.3}")).collect::<Vec<_>>().join(" ");
let profile = if s.kind == SamKind::Radar { format!(" {}", s.radar_profile().id) } else { String::new() };
text += &format!(
"sam {} {} {} {} {} {} {} {} {} {} {} {} {dest} {parts} {} {} {} {} {} {} {} {} {} {}\n",
"sam {} {} {} {} {} {} {} {} {} {} {} {} {dest} {parts} {} {} {} {} {} {} {} {} {} {}{profile}\n",
s.kind.key(),
s.pos.x,
s.pos.y,
@@ -1054,7 +1055,9 @@ impl AirDef {
sam.air_48n6_stock = r.air_48n6_stock;
sam.fit_cells();
sam.set_mode(r.mode);
sam.set_radar_role(r.radar_role);
// New saves name the stable profile; old ones only the role, which
// parses to the same profile (`Layout::parse`).
sam.set_radar_role(r.radar_profile.map_or(r.radar_role, |p| p.role()));
sam.radar_on = r.radar_on;
sam.spent_cells = r.spent_cells;
sam.sync_tube_cells();
@@ -1552,7 +1555,8 @@ impl AirDef {
self.sim.sams.push(sam);
self.sim.settle(id);
self.dirty = true;
Ok(format!("{} развёрнут ({}, {})", kind.name(), mode.key(), role.key()))
let profile = if kind == SamKind::Radar { format!(", профиль {}", role.profile().id) } else { String::new() };
Ok(format!("{} развёрнут ({}, {}{profile})", kind.name(), mode.key(), role.key()))
}
fn open_menu(&mut self, page: Page) {
@@ -1583,7 +1587,11 @@ impl AirDef {
}
Page::BatteryDeploy => {
title = "Размещение батареи — клик создаёт технику перед игроком".into();
widgets.push(Widget::List(ListWidget { id: BATTERY_ROWS, rows: sim::catalog::VARIANTS.iter().map(|v| v.label.to_string()).collect(), selected: None }));
widgets.push(Widget::List(ListWidget {
id: BATTERY_ROWS,
rows: sim::catalog::VARIANTS.iter().map(|v| format!("{} — {}", v.label, v.description)).collect(),
selected: None,
}));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
Page::Replays => {
@@ -2345,7 +2353,7 @@ impl Mod for AirDef {
["battery"] => {
let status = self.sim.battery_status();
for entry in status { say(&battery_view::status(entry)); }
Some("/airdef battery <номер> integrated|launcher; /airdef radar <номер> on|off|multi|search|engagement|height".into())
Some("/airdef battery <номер> integrated|launcher; /airdef radar <номер> on|off; профиль задаётся deploy radar_search|radar_track|radar_height".into())
}
["battery", n, mode] => {
let i = n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("Нужен номер комплекса")?;
@@ -2363,13 +2371,12 @@ impl Mod for AirDef {
self.dirty = true;
Some(format!("№{} {}: излучение РЛС {}", i + 1, sam.kind.name(), state))
}
["radar", n, role] => {
let i = n.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).ok_or("Нужен номер РЛС")?;
["radar", _n, role] => {
let role = sim::battery::RadarRole::from_key(role).ok_or("Роль: multi, search, engagement или height")?;
let sam = self.sim.sams.get_mut(i).ok_or("Нет такого комплекса")?;
if !sam.set_radar_role(role) { return Err("Нужна отдельная РЛС".into()); }
self.dirty = true;
Some(format!("№{} РЛС: роль {}", i + 1, role.key()))
return Err(format!(
"Профиль РЛС задаётся при размещении (deploy radar_search|radar_track|radar_height); переключение в {} не меняет оборудование. Доступно on/off.",
role.key()
));
}
["wave", kind, rest @ ..] => {
let count = rest.first().and_then(|v| v.parse().ok()).unwrap_or(5u32).clamp(1, 80);
@@ -2628,6 +2635,25 @@ mod tests {
use super::*;
#[test]
fn radar_profile_survives_a_state_round_trip() {
let mut game = test_mod();
for role in [sim::battery::RadarRole::Search, sim::battery::RadarRole::Height, sim::battery::RadarRole::Engagement] {
let id = game.sim.id();
let mut radar = Sam::new(id, SamKind::Radar, DVec3::new(role as i32 as f64 * 10.0, 70.0, 0.0), 0.0);
radar.set_radar_role(role);
game.sim.sams.push(radar);
}
let saved = game.state_text(false, false);
assert!(saved.contains("radar_search") && saved.contains("radar_height") && saved.contains("radar_track"));
let mut restored = test_mod();
restored.apply_state(&saved).unwrap();
assert_eq!(
restored.sim.sams.iter().map(|s| s.radar_profile().id).collect::<Vec<_>>(),
vec!["radar_search", "radar_height", "radar_track"]
);
}
fn test_mod() -> AirDef {
AirDef {
sim: Sim::new(1),
+21 -4
View File
@@ -657,7 +657,20 @@ fn track_lines(sim: &Sim, t: &Track, player: Option<DVec3>, lines: &mut Vec<(Str
format!("Статус: {}{}", t.ident().name(), if forecast { format!(" · прогноз {} с", age / 20) } else { format!(" · измерение {} с назад", age / 20) }),
if forecast { YELLOW } else { GREEN },
));
lines.push((format!("Источник: {}", if t.own_within(now, t.ttl as u64) { "своя РЛС" } else { "сеть (чужое измерение)" }), WHITE));
let source = sim.sams.iter().enumerate().find(|(_, s)| s.id == t.source).map_or(
if t.source == 0 { "неизвестен".to_string() } else { format!("№? ({})", t.source) },
|(n, s)| format!("№{} {} ({})", n + 1, s.kind.name(), s.radar_profile().id),
);
lines.push((format!("Источник: {} · измерил {}", if t.own_within(now, t.ttl as u64) { "своя РЛС" } else { "сеть (чужое измерение)" }, source), WHITE));
lines.push((format!("Продукт: {} · качество {}%", t.product.name(), t.quality), WHITE));
let authority = if t.own_authorizes(now) {
"у измерившей станции пригодно для пуска".to_string()
} else if t.own_tick > 0 {
format!("измерение станции {} с назад, для пуска не пригодно", now.saturating_sub(t.own_tick) / 20)
} else {
"передано сетью: собственного измерения нет, нужен огневой трек станции".to_string()
};
lines.push((format!("Пуск: {authority}"), if t.own_authorizes(now) { GREEN } else { YELLOW }));
if t.locked {
lines.push(("Огневой захват: да".into(), YELLOW));
}
@@ -2637,7 +2650,11 @@ impl AirDef {
let k = sam.kind;
lines.push((format!("{} №{}", k.name(), n + 1), CYAN));
if k == SamKind::Radar {
lines.push((format!("Роль РЛС: {}", crate::battery_view::radar_role_name(sam.radar_role)), WHITE));
let profile = sam.radar_profile();
lines.push((format!("Профиль РЛС: {} [{}]", profile.name, profile.id), WHITE));
lines.push((crate::battery_view::radar_profile_line(profile), GREY));
lines.push((format!("Ограничение: {}", profile.limit), GREY));
lines.push((format!("Каналы: {}/{} · профиль задан при размещении", sam.own_channels_used(), profile.channels), GREY));
} else if sam.mode == sim::battery::SamMode::LauncherOnly {
lines.push(("Отдельная пусковая: внешняя РЛС сопровождения".into(), WHITE));
}
@@ -2928,7 +2945,7 @@ mod tests {
assert_eq!(hover_at(&sim, &ui), Some(Hover::Drone(id)));
// A measured track is hoverable in the honest picture too.
sim.truth = false;
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, ttl: 200, hits: 3, locked: false };
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: sim::battery::Measure::Search, quality: 40, own_product: sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: false };
sim.sams[0].tracks.push(t);
assert_eq!(hover_at(&sim, &ui), Some(Hover::Track(id)));
// Away from the marker there is nothing.
@@ -2940,7 +2957,7 @@ mod tests {
#[test]
fn the_network_card_never_claims_a_target_and_lists_its_status_and_interception() {
let (mut sim, id, _) = hover_fixture();
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::new(0.0, 0.0, 0.5), tick: 0, own_tick: 0, ttl: 200, hits: 3, locked: true };
let t = Track { id, class: sim::ClassEst::Firm(sim::Class::Drone), pos: DVec3::new(0.0, 64.0, 0.0), vel: DVec3::new(0.0, 0.0, 0.5), tick: 0, own_tick: 0, source: 0, product: sim::battery::Measure::Search, quality: 40, own_product: sim::battery::Measure::Search, own_quality: 0, ttl: 200, hits: 3, locked: true };
sim.sams[0].tracks.push(t);
let mut lines = Vec::new();
track_lines(&sim, &t, Some(DVec3::ZERO), &mut lines);
+3 -1
View File
@@ -171,7 +171,9 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
let radar_text = if spec.sensor <= 0.0 {
format!("сеть · {seen}")
} else if radar_up {
format!("РЛС {} · {}", distance(reach), seen)
let profile = sam.radar_profile();
let channels = if profile.channels == 0 { String::new() } else { format!(" · {}/{}", sam.own_channels_used(), profile.channels) };
format!("{} · {} · {}{channels}", profile.name, distance(reach), seen)
} else {
"РЛС ОТКАЗ".to_string()
};
+1 -1
View File
@@ -59,7 +59,7 @@ pub fn summary(sim: &Sim, pic: &AirPicture, player: DVec3) -> Vec<Line> {
let e = t.est(now);
let mark = if t.forecast(now) { format!(" ~{}с", t.age(now) / 20) } else { String::new() };
lines.push(line(
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч{mark}", t.class.name(), distance(e.distance(player)), e.y - player.y, kmh(t.vel)),
format!("Ближ.: {} {} выс.{:.0} {:.0}км/ч · {} кач.{}{mark}", t.class.name(), distance(e.distance(player)), e.y - player.y, kmh(t.vel), t.product.name(), t.quality),
PINK,
));
}
+7 -1
View File
@@ -197,12 +197,18 @@ pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec<Shape> {
match scope(pos) {
Some((x, y, bearing)) => {
// Fresh: bright and red; a forecast: orange, fading as it ages towards the track's drop.
// The product is visible: a coarse search plot is amber, a refinement yellow, a fire plot red.
let fresh_color = match t.product {
crate::sim::battery::Measure::Search => 0xFFB060,
crate::sim::battery::Measure::Refine => 0xFFE070,
crate::sim::battery::Measure::Fire => 0xFF4040,
};
let (a, color) = if pic.unaided {
(fade(bearing), 0xFF4040)
} else if t.forecast(now) {
((1.0 - t.age(now) as f64 / t.ttl.max(1) as f64 * 0.7).max(0.3), 0xFFB040)
} else {
(1.0, 0xFF4040)
(1.0, fresh_color)
};
let (x, y) = inside(x, y, cx, cy, r);
marks.push((x, y, t.class, color, a, vel));
+243 -4
View File
@@ -33,8 +33,199 @@ impl RadarRole {
pub fn from_key(key: &str) -> Option<Self> {
match key { "multi" => Some(Self::Multifunction), "search" => Some(Self::Search), "engagement" => Some(Self::Engagement), "height" => Some(Self::Height), _ => None }
}
pub fn authorizes(self) -> bool { matches!(self, Self::Multifunction | Self::Engagement) }
pub(super) fn reach_factor(self) -> f64 { match self { Self::Multifunction => 1.0, Self::Search => 1.15, Self::Engagement => 0.8, Self::Height => 1.05 } }
pub fn profile(self) -> RadarProfile { RadarProfile::of(self) }
pub fn authorizes(self) -> bool { self.profile().products & RadarProfile::FIRE_BIT != 0 }
}
/// What a measurement is good for. A search plot is a warning, a refined
/// plot fixes a matched contact, and a fire plot is a confirmed measurement
/// a launcher may use. Quality (0..100) is separate from identification:
/// a well-measured track can still be an unknown type (#133).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum Measure {
#[default]
Search,
Refine,
Fire,
}
impl Measure {
pub fn name(self) -> &'static str {
match self { Self::Search => "обзор", Self::Refine => "уточнение", Self::Fire => "пригоден для пуска" }
}
pub fn allows_fire(self) -> bool { self == Self::Fire }
}
/// A radar profile: a stable catalog identity over the existing `SamKind::Radar`.
/// The numbers are fictional game settings. The silhouette is shared with the
/// existing radar model: this slice does not add art (a separate owner's zone).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RadarProfile {
/// Stable content ID; old saves only have `RadarRole`, which maps here.
pub id: &'static str,
pub name: &'static str,
/// Allowed measurement products (`SEARCH_BIT`, `REFINE_BIT`, `FIRE_BIT`).
pub products: u8,
/// Ticks for the beam to go round.
pub cycle: u32,
/// Electronic revisit of held contacts between beam passes.
pub agile: bool,
/// Extra antenna height over the unit's spec mast (blocks).
pub mast: f64,
/// Search reach, a factor of the unit's sensor.
pub reach: f64,
/// Local search radius, a factor of the unit's sensor (1: the whole reach).
pub local: f64,
/// Simultaneous refined/fire channels; 0 means only search plots.
pub channels: u8,
/// Measurement error scale (blocks) and its growth per block of range.
pub sigma: f64,
pub spread: f64,
/// Vertical error as a share of the horizontal one.
pub vertical: f64,
pub deployment: &'static str,
/// The limit the profile deliberately keeps, shown in the UI.
pub limit: &'static str,
}
impl RadarProfile {
pub const SEARCH_BIT: u8 = 1;
pub const REFINE_BIT: u8 = 2;
pub const FIRE_BIT: u8 = 4;
pub const MULTI: RadarProfile = RadarProfile {
id: "radar_multi",
name: "многофункциональная",
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
cycle: 140,
agile: false,
mast: 0.0,
reach: 1.0,
local: 0.55,
channels: 3,
sigma: 0.7,
spread: 0.004,
vertical: 0.75,
deployment: "стационарная",
limit: "универсальная: уступает специализированным по циклу, каналам и точности",
};
pub const SEARCH: RadarProfile = RadarProfile {
id: "radar_search",
name: "дальнего обзора",
products: Self::SEARCH_BIT,
cycle: 170,
agile: false,
mast: 0.0,
reach: 1.15,
local: 1.0,
channels: 0,
sigma: 1.0,
spread: 0.008,
vertical: 1.0,
deployment: "крупная стационарная антенна",
limit: "редкие грубые отметки; своего права на пуск не даёт",
};
pub const ENGAGEMENT: RadarProfile = RadarProfile {
id: "radar_track",
name: "сопровождения",
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
cycle: 70,
agile: true,
mast: 0.0,
reach: 0.8,
local: 0.12,
channels: 2,
sigma: 0.35,
spread: 0.002,
vertical: 0.6,
deployment: "мобильная панель",
limit: "локальный поиск и два канала; сеть лишь подсказывает, измеряет станция",
};
pub const HEIGHT: RadarProfile = RadarProfile {
id: "radar_height",
name: "мачта низких высот",
products: Self::SEARCH_BIT | Self::REFINE_BIT,
cycle: 140,
agile: false,
mast: 8.0,
reach: 1.05,
local: 0.15,
channels: 3,
sigma: 0.5,
spread: 0.003,
vertical: 0.35,
deployment: "шасси с поднятой антенной",
limit: "уточняет низкие контакты над рельефом; сквозь препятствия не видит и права на пуск не даёт",
};
/// A weapon's own radar: it measures for its own fire control. Kept out of
/// the separate radar roles so embedded radars keep working as before.
pub const EMBEDDED: RadarProfile = RadarProfile {
id: "embedded",
name: "РЛС комплекса",
products: Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT,
cycle: 0,
agile: false,
mast: 0.0,
reach: 1.0,
local: 1.0,
channels: 0,
sigma: 0.8,
spread: 0.004,
// The old embedded scan drew its vertical error at half the horizontal one.
vertical: 0.5,
deployment: "встроенная",
limit: "обслуживает только свой комплекс",
};
pub fn of(role: RadarRole) -> Self {
match role {
RadarRole::Multifunction => Self::MULTI,
RadarRole::Search => Self::SEARCH,
RadarRole::Engagement => Self::ENGAGEMENT,
RadarRole::Height => Self::HEIGHT,
}
}
/// Old saves write the role key; new saves write the stable profile ID.
/// Both read here, so a legacy `search` line maps to `radar_search`.
pub fn from_id(id: &str) -> Option<Self> {
match id {
"radar_multi" | "multi" => Some(Self::MULTI),
"radar_search" | "search" => Some(Self::SEARCH),
"radar_track" | "engagement" => Some(Self::ENGAGEMENT),
"radar_height" | "height" => Some(Self::HEIGHT),
_ => None,
}
}
pub fn role(self) -> RadarRole {
match self.id {
"radar_search" => RadarRole::Search,
"radar_track" => RadarRole::Engagement,
"radar_height" => RadarRole::Height,
_ => RadarRole::Multifunction,
}
}
pub fn allows(self, product: Measure) -> bool {
match product {
Measure::Search => self.products & Self::SEARCH_BIT != 0,
Measure::Refine => self.products & Self::REFINE_BIT != 0,
Measure::Fire => self.products & Self::FIRE_BIT != 0,
}
}
pub fn products_text(self) -> &'static str {
match self.products {
p if p == Self::SEARCH_BIT | Self::REFINE_BIT | Self::FIRE_BIT => "обзор, уточнение, пуск",
p if p == Self::SEARCH_BIT | Self::REFINE_BIT => "обзор, уточнение",
p if p == Self::SEARCH_BIT | Self::FIRE_BIT => "обзор, пуск",
_ => "обзор",
}
}
}
impl Sam {
/// The profile this unit measures with. Embedded radars keep their kind's
/// own scan and reach; only the separate radar uses a selectable profile.
pub fn radar_profile(&self) -> RadarProfile {
if self.kind == SamKind::Radar { RadarProfile::of(self.radar_role) } else { RadarProfile::EMBEDDED }
}
}
impl Sam {
@@ -113,7 +304,22 @@ mod tests {
}
fn track(now: u64) -> Track {
Track { id: 42, class: ClassEst::Firm(Class::Cruise), pos: DVec3::new(0.0, 100.0, -200.0), vel: DVec3::ZERO, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false }
Track {
id: 42,
class: ClassEst::Firm(Class::Cruise),
pos: DVec3::new(0.0, 100.0, -200.0),
vel: DVec3::ZERO,
tick: now,
own_tick: now,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 400,
hits: 3,
locked: false,
}
}
#[test]
@@ -251,6 +457,24 @@ mod tests {
assert!(sight::reach(&r, DroneKind::Kh101, 5000.0) > base_reach);
}
#[test]
fn profiles_have_stable_ids_and_deliberately_different_limits() {
let search = RadarRole::Search.profile();
let height = RadarRole::Height.profile();
let engagement = RadarRole::Engagement.profile();
let multi = RadarRole::Multifunction.profile();
assert_eq!((search.id, height.id, engagement.id, multi.id), ("radar_search", "radar_height", "radar_track", "radar_multi"));
assert!(!RadarRole::Search.authorizes() && !RadarRole::Height.authorizes() && RadarRole::Engagement.authorizes());
assert_eq!(search.products, RadarProfile::SEARCH_BIT);
assert_eq!(height.products, RadarProfile::SEARCH_BIT | RadarProfile::REFINE_BIT);
assert_ne!(search.cycle, engagement.cycle);
assert!(height.mast > search.mast && height.mast > engagement.mast);
assert!(engagement.channels < multi.channels && height.channels > 0 && search.channels == 0);
assert!(search.local > height.local && height.local > engagement.local);
assert_eq!(RadarProfile::from_id(search.id), Some(search));
assert_eq!(RadarProfile::from_id("search"), Some(search), "legacy role keys map to profiles");
}
#[test]
fn launcher_has_no_own_map_sensor_and_mode_switch_drops_stale_tracks() {
let mut sim = Sim::new(3);
@@ -294,7 +518,22 @@ mod emission_tests {
receiver.radar_on = false;
sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 70.0, -100.0), DVec3::Z, DVec3::ZERO);
let id = sim.drones[0].id;
source.tracks.push(Track { id, class: ClassEst::Firm(Class::Cruise), pos: sim.drones[0].pos, vel: DVec3::ZERO, tick: 20, own_tick: 20, ttl: 200, hits: 2, locked: false });
source.tracks.push(Track {
id,
class: ClassEst::Firm(Class::Cruise),
pos: sim.drones[0].pos,
vel: DVec3::ZERO,
tick: 20,
own_tick: 20,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 200,
hits: 2,
locked: false,
});
sim.sams.extend([source, receiver]);
let mut ground = Ground::default();
sim.update_sight(&mut ground);
+19 -2
View File
@@ -3,7 +3,7 @@
//! Balance and rendering remain in `DroneSpec` and `SamSpec`: the catalog
//! refers to those typed definitions instead of copying their values. The
//! first eleven drone entries retain the historical positional wave-save order.
use super::{battery::RadarRole, battery::SamMode, DroneKind, SamKind};
use super::{battery::RadarProfile, battery::RadarRole, battery::SamMode, DroneKind, SamKind};
#[derive(Clone, Copy, Debug)]
pub struct Aircraft {
@@ -30,6 +30,15 @@ pub struct UnitVariant {
pub role: RadarRole,
/// The deploy menu's row.
pub label: &'static str,
/// What the configuration is for (shown in the deploy menu).
pub description: &'static str,
}
impl UnitVariant {
/// The typed radar profile behind a separate radar variant.
pub fn radar_profile(self) -> Option<RadarProfile> {
(self.kind == SamKind::Radar).then(|| RadarProfile::of(self.role))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -202,8 +211,16 @@ mod tests {
assert!(UNITS.iter().any(|unit| unit.kind == v.kind), "{} configures an unknown kind", v.id);
assert!(SamKind::from_key(v.id).is_none(), "{} shadows a unit kind", v.id);
assert!(!INVENTORY.contains(&format!("airdef:{}", v.id).as_str()), "{} doubles an item", v.id);
assert!(!v.label.is_empty());
assert!(!v.label.is_empty() && !v.description.is_empty());
assert_eq!(variant(v.id).map(|u| (u.kind, u.mode, u.role)), Some((v.kind, v.mode, v.role)));
if v.kind == SamKind::Radar {
let profile = v.radar_profile().expect("a radar variant has a profile");
assert_eq!(profile.id, v.id, "the stable profile ID is the variant ID");
assert_eq!(profile.role(), v.role);
assert!(profile.channels <= 3 && profile.cycle > 0);
} else {
assert!(v.radar_profile().is_none());
}
}
let launcher = variant("s400_launcher").unwrap();
assert_eq!((launcher.kind, launcher.mode, launcher.role), (SamKind::S400, SamMode::LauncherOnly, RadarRole::Multifunction));
+16 -1
View File
@@ -168,7 +168,22 @@ mod tests {
use super::*;
fn track(pos: DVec3, vel: DVec3) -> Track {
Track { id: 1, class: ClassEst::Unknown, pos, vel, tick: 0, own_tick: 0, ttl: 100, hits: 3, locked: false }
Track {
id: 1,
class: ClassEst::Unknown,
pos,
vel,
tick: 0,
own_tick: 0,
source: 0,
product: battery::Measure::Search,
quality: 40,
own_product: battery::Measure::Search,
own_quality: 0,
ttl: 100,
hits: 3,
locked: false,
}
}
#[test]
+45 -2
View File
@@ -1099,6 +1099,19 @@ mod tests {
assert!(r.sam_tracks[0].ghost(r.origin, 0.0, 1).unwrap().radar_on);
}
#[test]
fn replay_preserves_a_separate_radars_profile() {
let mut r = recording();
for (at, role) in [(0, battery::RadarRole::Search), (10, battery::RadarRole::Height), (20, battery::RadarRole::Engagement)] {
let mut sam = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
sam.set_radar_role(role);
r.note_sams(&[sam], at);
}
assert_eq!(r.sam_tracks[0].ghost(r.origin, 1.0, 1).unwrap().radar_profile().id, "radar_search");
assert_eq!(r.sam_tracks[0].ghost(r.origin, 11.0, 1).unwrap().radar_profile().id, "radar_height");
assert_eq!(r.sam_tracks[0].ghost(r.origin, 21.0, 1).unwrap().radar_profile().id, "radar_track");
}
#[test]
fn replay_preserves_launcher_configuration_and_individual_cover_poses() {
let mut r = recording();
@@ -1290,7 +1303,22 @@ mod tests {
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0));
let mut r = Recording::new(1, &sim);
let tr = sight::Track { id: 77, class: ClassEst::Firm(Class::Drone), pos: DVec3::Z * 100.0, vel: -DVec3::Z, tick: 1, own_tick: 1, ttl: 10, hits: 1, locked: false };
let tr = sight::Track {
id: 77,
class: ClassEst::Firm(Class::Drone),
pos: DVec3::Z * 100.0,
vel: -DVec3::Z,
tick: 1,
own_tick: 1,
source: 1,
product: battery::Measure::Fire,
quality: 80,
own_product: battery::Measure::Fire,
own_quality: 80,
ttl: 10,
hits: 1,
locked: false,
};
sim.sams[0].tracks.push(tr);
r.note_tracks(&sim.sams);
r.len = 1;
@@ -1356,7 +1384,22 @@ mod tests {
let id = sim.id();
let mut sam = Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0);
for target in 1..=4 {
sam.tracks.push(sight::Track { id: target, class: ClassEst::Firm(Class::Drone), pos: DVec3::Z, vel: DVec3::ZERO, tick: 1, own_tick: 1, ttl: 1, hits: 1, locked: false });
sam.tracks.push(sight::Track {
id: target,
class: ClassEst::Firm(Class::Drone),
pos: DVec3::Z,
vel: DVec3::ZERO,
tick: 1,
own_tick: 1,
source: sam.id,
product: battery::Measure::Fire,
quality: 80,
own_product: battery::Measure::Fire,
own_quality: 80,
ttl: 1,
hits: 1,
locked: false,
});
}
sim.sams.push(sam);
}
+37 -10
View File
@@ -1103,9 +1103,23 @@ fn behind_ridge(land: &Land<impl Fn(i32, i32) -> i32>, crest: i32, kind: SamKind
// It crawls along the far side of the ridge, 20 blocks over the land.
let there = (land.0)(x as i32, 0) as f64;
sim.add_drone(DroneKind::Shahed, DVec3::new(x, there + 20.0, -100.0), DVec3::Z, DVec3::new(x, there, 3000.0));
let id = sim.drones[0].id;
for _ in 0..ticks {
sim.step(&mut ground, None, &mut out);
answer_land(&mut ground, land, sim.tick);
// The scenario is about the interceptor's path over the ridge, not about
// where the plot came from: give the system the crest radar's plot as its
// own confirmed fire measurement (separate authority is tested in
// `a_system_does_not_fire_at_a_target_masked_by_a_hill`).
if let Some(t) = sim.sams[1].track(id).copied() {
let mut own = t;
own.source = sim.sams[0].id;
own.own_tick = sim.tick;
own.own_product = battery::Measure::Fire;
own.own_quality = 90;
sim.sams[0].tracks.retain(|o| o.id != id);
sim.sams[0].tracks.push(own);
}
}
sim
}
@@ -1131,27 +1145,25 @@ fn a_system_does_not_fire_at_a_target_masked_by_a_hill() {
answer_land(&mut ground, land, sim.tick);
}
sim.add_drone(DroneKind::Gerbera, DVec3::new(200.0, 84.0, -60.0), DVec3::Z, DVec3::new(200.0, 64.0, 3000.0));
let mut masked = 0u32;
let mut seen = false;
let mut told = false;
for _ in 0..300 {
sim.step(&mut ground, None, &mut out);
answer_land(&mut ground, land, sim.tick);
seen |= sim.sams[0].seen.len() == 1;
masked += sim.sams[0].terrain.values().filter(|(_, b)| *b == terrain::MASKED).count() as u32;
// `why` names the reason while the verdict stands.
told |= sim.why(0).iter().any(|c| !c.ok && c.legacy_text().contains("за рельефом"));
// The network shows the target, but the Tor has no own confirmed plot,
// so `why` must say that no launch is authorized.
told |= sim.why(0).iter().any(|c| !c.ok && c.legacy_text().contains("право на пуск: нет"));
}
(sim, seen, masked, told)
(sim, seen, told)
};
let (open, seen, _, _) = shot(&flat);
let (open, seen, _) = shot(&flat);
assert!(seen && open.sams[0].fired > 0, "control: with a clear line the Tor must fire (seen {seen}, fired {})", open.sams[0].fired);
let (shut, seen, masked, told) = shot(&hill);
let (shut, seen, told) = shot(&hill);
assert!(seen, "the network must have shown the target to the Tor");
assert_eq!(shut.sams[0].fired, 0, "the Tor fired at a target behind the hill");
assert!(masked > 0, "no launch was judged and refused for the land");
assert_eq!(shut.tally.blocked + shut.tally.scrubbed, 0);
assert!(told, "`why` never named the land as the reason");
assert!(told, "`why` never named the missing own fire plot");
}
// A long-range system lofts over a low ridge (its interceptor does not hit it) but not over a mountain.
@@ -2433,7 +2445,22 @@ fn recorded_ignition_is_cold_ticks_after_ejection_and_replay_follows_it() {
// the test is about the launch stages, not about the scan's chance.
let now = sim.tick;
let tracks: Vec<sight::Track> = sim.drones.iter().filter(|d| d.alive())
.map(|d| sight::Track { id: d.id, class: ClassEst::Firm(d.kind.spec().class), pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false })
.map(|d| sight::Track {
id: d.id,
class: ClassEst::Firm(d.kind.spec().class),
pos: d.pos,
vel: d.vel,
tick: now,
own_tick: now,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 400,
hits: 3,
locked: false,
})
.collect();
sim.sams[0].tracks.retain(|t| !tracks.iter().any(|n| n.id == t.id));
sim.sams[0].tracks.extend(tracks);
+270 -2
View File
@@ -1,5 +1,6 @@
//! Radar scan cycles with ageing tracks (#46) and damage to a system's parts (#50).
use super::sight::{swept, FORECAST_AGE};
use super::battery::{Measure, RadarRole};
use super::sight::{swept, FIRE_QUALITY, FORECAST_AGE};
use super::*;
fn flat() -> (Ground, Out) {
@@ -376,7 +377,8 @@ fn a_gun_lets_go_of_a_track_classified_out_of_its_roles() {
let seed = |sim: &mut Sim, class| {
let d = sim.drones[0].clone();
sim.sams[p].tracks.retain(|t| t.id != d.id);
sim.sams[p].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: sim.tick, own_tick: sim.tick, ttl: 400, hits: 3, locked: false });
let source = sim.sams[p].id;
sim.sams[p].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: sim.tick, own_tick: sim.tick, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false });
};
// Taken while the class was unknown: the general rules make it a candidate.
seed(&mut sim, ClassEst::Unknown);
@@ -420,3 +422,269 @@ fn forecasts_and_relays_add_no_confidence() {
assert!(relayed > 100, "the network never passed the track ({relayed})");
assert!(prev.is_some_and(|(_, c)| c.class().is_some()), "the source never classified the contact");
}
// ---------------------------------------------------------------- separate radar profiles (#134)
fn radar_with_role(sim: &mut Sim, role: RadarRole, x: f64) -> usize {
let id = sim.id();
let mut sam = Sam::new(id, SamKind::Radar, DVec3::new(x, 70.0, 0.0), 0.0);
sam.set_radar_role(role);
sim.sams.push(sam);
sim.sams.len() - 1
}
fn bearing(from: DVec3, to: DVec3) -> f64 {
(to.x - from.x).atan2(-(to.z - from.z))
}
/// The beam of every radar is pointed at one of `targets` in turn, so a test
/// does not depend on where the initial phase happened to be.
fn sweep(sim: &mut Sim, ground: &mut Ground, radars: &[usize], targets: &[DVec3], tick: u64) {
sim.tick = tick;
for (k, &i) in radars.iter().enumerate() {
let at = targets[(tick as usize + k) % targets.len()];
sim.sams[i].beam = bearing(sim.sams[i].pos, at);
}
sim.update_sight(ground);
}
#[derive(Default, Debug, PartialEq, Eq)]
struct ProfileStats {
first_high: Option<u64>,
first_low_refined: Option<u64>,
first_close_fire: Option<u64>,
max_channels: usize,
search_or_height_authorized: bool,
}
/// A low contact at 330 blocks (above the search/engagement horizon but below
/// the mast's), a high contact at 700/430 (inside the search reach but outside
/// the mast's and engagement's local search), and two close contacts for the
/// tracked-contact channels.
fn profile_world(roles: &[RadarRole]) -> (Sim, Vec<usize>, Vec<u32>, Ground) {
let mut sim = Sim::new(134);
let radars: Vec<usize> = roles.iter().map(|role| radar_with_role(&mut sim, *role, 0.0)).collect();
sim.add_drone(DroneKind::Shahed, DVec3::new(330.0, 95.0, 0.0), DVec3::Z, DVec3::new(330.0, 95.0, 0.0));
let low = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Shahed, DVec3::new(700.0, 500.0, 0.0), DVec3::Z, DVec3::new(700.0, 500.0, 0.0));
let high = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let close1 = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Gerbera, DVec3::new(180.0, 130.0, 40.0), DVec3::Z, DVec3::new(180.0, 130.0, 40.0));
let close2 = sim.drones.last().unwrap().id;
(sim, radars, vec![low, high, close1, close2], Ground::default())
}
fn run_profile_world(roles: &[RadarRole], ticks: u64) -> (ProfileStats, Sim, Vec<usize>, Vec<u32>) {
let (mut sim, radars, ids, mut ground) = profile_world(roles);
let [low, high, close1, close2] = [ids[0], ids[1], ids[2], ids[3]];
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
let mut stats = ProfileStats::default();
for tick in 1..=ticks {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
for &i in &radars {
let sam = &sim.sams[i];
for t in sam.tracks.iter().filter(|t| t.own_tick > 0) {
match t.id {
id if id == high && stats.first_high.is_none() => stats.first_high = Some(tick),
id if id == low && t.product == Measure::Refine && stats.first_low_refined.is_none() => stats.first_low_refined = Some(tick),
id if (id == close1 || id == close2) && t.product == Measure::Fire && t.own_authorizes(sim.tick) && stats.first_close_fire.is_none() => stats.first_close_fire = Some(tick),
_ => {}
}
}
if sam.radar_profile().id == "radar_search" || sam.radar_profile().id == "radar_height" {
stats.search_or_height_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
}
stats.max_channels = stats.max_channels.max(sam.own_channels_used());
}
}
(stats, sim, radars, ids)
}
#[test]
fn each_profile_is_useful_alone_and_the_full_set_covers_all_three_jobs() {
let search = run_profile_world(&[RadarRole::Search], 500).0;
assert!(search.first_high.is_some(), "the search radar gives no early high plot: {search:?}");
assert!(search.first_low_refined.is_none(), "search refined a low contact it does not reach: {search:?}");
assert!(search.first_close_fire.is_none(), "search authorized a launch: {search:?}");
let height = run_profile_world(&[RadarRole::Height], 500).0;
assert!(height.first_high.is_none(), "the mast radar searched beyond its local patch: {height:?}");
assert!(height.first_low_refined.is_some(), "the mast radar did not refine the low contact: {height:?}");
assert!(height.first_close_fire.is_none(), "the mast radar authorized a launch: {height:?}");
let engagement = run_profile_world(&[RadarRole::Engagement], 500).0;
assert!(engagement.first_high.is_none(), "the engagement radar searched beyond its local patch: {engagement:?}");
assert!(engagement.first_low_refined.is_none(), "the engagement radar reached a low contact below the horizon: {engagement:?}");
assert!(engagement.first_close_fire.is_some(), "the engagement radar gave no fire plot: {engagement:?}");
assert!(engagement.max_channels <= 2, "more than two tracked contacts: {engagement:?}");
let search_height = run_profile_world(&[RadarRole::Search, RadarRole::Height], 500).0;
assert!(search_height.first_high.is_some() && search_height.first_low_refined.is_some());
assert!(search_height.first_close_fire.is_none(), "a search/height pair authorized a launch: {search_height:?}");
let search_engagement = run_profile_world(&[RadarRole::Search, RadarRole::Engagement], 500).0;
assert!(search_engagement.first_high.is_some() && search_engagement.first_close_fire.is_some());
assert!(search_engagement.first_low_refined.is_none(), "the pair covered the mast's low gap: {search_engagement:?}");
let height_engagement = run_profile_world(&[RadarRole::Height, RadarRole::Engagement], 500).0;
assert!(height_engagement.first_low_refined.is_some() && height_engagement.first_close_fire.is_some());
assert!(height_engagement.first_high.is_none(), "the pair covered the search's far picture: {height_engagement:?}");
let full = run_profile_world(&[RadarRole::Search, RadarRole::Height, RadarRole::Engagement], 500).0;
assert!(full.first_high.is_some() && full.first_low_refined.is_some() && full.first_close_fire.is_some(), "{full:?}");
assert!(!full.search_or_height_authorized, "a non-fire radar authorized a launch");
// There is no set bonus in the profile table: a duplicated station adds no
// function, and the full set's advantage is only the union of the three jobs.
let duplicate = run_profile_world(&[RadarRole::Search, RadarRole::Search], 500).0;
assert!(duplicate.first_low_refined.is_none() && duplicate.first_close_fire.is_none(), "two search radars invented another function: {duplicate:?}");
}
#[test]
fn network_relay_keeps_source_age_and_quality_but_not_launch_authority() {
let mut sim = Sim::new(1341);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
let receiver = {
let id = sim.id();
let mut s400 = Sam::new(id, SamKind::S400, DVec3::new(20.0, 70.0, 0.0), 0.0);
// A blind receiver: only the network can give it a track.
s400.comps.0[Part::Sensor as usize] = 0.0;
s400.roles = 0xff;
sim.sams.push(s400);
sim.sams.len() - 1
};
sim.add_drone(DroneKind::Shahed, DVec3::new(200.0, 120.0, 0.0), DVec3::Z, DVec3::new(200.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [search, engagement];
for tick in 1..=120 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let own = sim.sams[engagement].track(id).expect("the engagement radar measured the target");
assert_eq!(own.source, sim.sams[engagement].id);
assert_eq!(own.product, Measure::Fire);
assert!(own.quality >= FIRE_QUALITY && own.own_authorizes(sim.tick));
let relayed = sim.sams[receiver].track(id).expect("the network shared the plot");
assert_eq!(relayed.own_tick, 0, "a relay became the receiver's own measurement");
assert_eq!(relayed.tick, own.tick, "a relay refreshed the measurement's age");
assert!(relayed.product == Measure::Fire && relayed.quality == own.quality, "relay lost product/quality");
assert_eq!(relayed.source, sim.sams[engagement].id, "relay lost the measuring station");
assert!(!relayed.own_authorizes(sim.tick));
let opts = why::Opts { last_chance: false, far_shots: false };
{
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
let drone = &sim.drones[0];
assert!(why::basis(&sim.sams[receiver], load, relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_none(), "a relayed plot authorized a launch");
}
// A launcher without a radar may use the supporting radar's own confirmed plot.
sim.sams[receiver].set_mode(battery::SamMode::LauncherOnly);
for tick in 121..=122 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let relayed = *sim.sams[receiver].track(id).expect("the launcher re-received the network plot");
assert!(why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick));
{
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
let drone = &sim.drones[0];
assert!(why::basis(&sim.sams[receiver], load, &relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_some());
}
// The search radar's plot is coarse: it does not authorize even a launcher.
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[search]], id, sim.tick));
// A broken data link ends the cue even while the radar itself still measures.
sim.sams[engagement].comps.0[Part::Comms as usize] = 0.0;
assert_eq!(sim.sams[engagement].link_range(), 0.0);
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick), "a broken link still cued a launch");
}
#[test]
fn the_air_picture_prefers_the_better_plot_at_one_tick() {
let mut sim = Sim::new(1345);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let track = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
for tick in 1..=5 {
sweep(&mut sim, &mut ground, &[search, track], &targets, tick);
}
let pic = sim.air_picture();
let t = pic.tracks.iter().find(|t| t.id == id).expect("the raid is on the picture");
assert_eq!(t.source, sim.sams[track].id, "a coarse plot won over the better one at the same tick");
assert_eq!(t.product, Measure::Fire);
assert!(t.own_authorizes(sim.tick));
}
#[test]
fn tracked_channels_are_a_hard_limit_but_the_rest_keep_search_plots() {
let mut sim = Sim::new(1344);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 0.0);
for x in [100.0, 140.0, 180.0, 220.0] {
sim.add_drone(DroneKind::Gerbera, DVec3::new(x, 120.0, 0.0), DVec3::Z, DVec3::new(x, 120.0, 0.0));
}
let mut ground = Ground::default();
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
for tick in 1..=40 {
sweep(&mut sim, &mut ground, &[engagement], &targets, tick);
}
let own: Vec<&Track> = sim.sams[engagement].tracks.iter().filter(|t| t.own_tick > 0).collect();
let precise = own.iter().filter(|t| t.own_product != Measure::Search).count();
assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}");
assert_eq!(sim.sams[engagement].own_channels_used(), 2);
assert_eq!(own.len(), 4, "a full station stopped giving coarse search plots: {own:?}");
assert!(own.iter().filter(|t| t.own_product == Measure::Search).all(|t| !t.own_authorizes(sim.tick)));
}
#[test]
fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() {
let mut sim = Sim::new(1342);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 20.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(150.0, 120.0, 0.0), DVec3::Z, DVec3::new(150.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [search, engagement];
for tick in 1..=80 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(sim.sams[engagement].track(id).is_some_and(|t| t.own_authorizes(sim.tick)));
let healthy = sim.sams[engagement].track(id).unwrap().own_quality;
// Off: the station emits nothing, its own plots stop, the neighbour still feeds the network.
sim.sams[engagement].radar_on = false;
let before = sim.sams[engagement].track(id).map(|t| t.own_tick);
for tick in 81..=110 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(!sim.sams[engagement].radar_up());
assert_eq!(sim.sams[engagement].track(id).map(|t| t.own_tick), before, "a silent radar renewed its own plot");
assert!(sim.sams[search].track(id).is_some_and(|t| t.own_tick > 0));
// Damage: a worn sensor still measures, with worse quality and no launch right.
sim.sams[engagement].radar_on = true;
sim.sams[engagement].comps.0[Part::Sensor as usize] = 0.2;
for tick in 111..=180 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let worn = sim.sams[engagement].track(id).expect("a worn radar still measures");
assert!(worn.own_quality < healthy, "damage did not lower quality: {worn:?}");
assert!(!worn.own_authorizes(sim.tick), "a worn sensor still authorized a launch");
}
#[test]
fn multifunction_and_embedded_radars_keep_their_fire_authority() {
let mut sim = Sim::new(1343);
let multi = radar_with_role(&mut sim, RadarRole::Multifunction, 0.0);
let pantsir = radar_at(&mut sim, SamKind::Pantsir, 20.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [multi, pantsir];
for tick in 1..=100 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(sim.sams[multi].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "the universal profile lost its own fire plot");
assert!(sim.sams[pantsir].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "an embedded radar lost its own fire plot");
}
+126 -25
View File
@@ -27,6 +27,8 @@ pub(super) const LINK: f64 = 2250.0;
/// A launcher fires on a track no older than this (ticks); a gun needs its own radar's, newer than `GUN_AGE`.
pub(super) const MISSILE_AGE: u64 = 120;
pub(super) const GUN_AGE: u64 = 3;
/// A fire plot below this quality is not confirmed enough to authorize a launch.
pub const FIRE_QUALITY: u8 = 50;
/// A gun takes a target its radar measured this recently (then the lock refreshes it every tick).
pub(super) const GUN_PICK_AGE: u64 = 40;
/// A track older than this is shown as a forecast.
@@ -90,7 +92,7 @@ pub(super) fn antenna(sam: &Sam) -> DVec3 {
}
fn sensor_span(sam: &Sam) -> f64 {
sam.kind.spec().sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 }
sam.kind.spec().sensor * sam.radar_profile().reach
}
/// How far a system's search radar reaches for this kind at `height` over the land:
@@ -100,7 +102,7 @@ pub(super) fn reach(sam: &Sam, kind: DroneKind, height: f64) -> f64 {
if spec.sensor <= 0.0 {
return 0.0;
}
let radar = spec.sensor * sam.radar_fit() * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor() } else { 1.0 } * kind.rcs().powf(0.25);
let radar = spec.sensor * sam.radar_fit() * sam.radar_profile().reach * kind.rcs().powf(0.25);
let horizon = HORIZON * (sam.sensor_mast().sqrt() + height.max(0.0).sqrt());
radar.min(horizon).max(NEAR)
}
@@ -145,7 +147,7 @@ impl Sim {
let fit = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_fit());
let height = LOW_KIND.spec().clearance;
let mast = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(spec.mast, |s| s.sensor_mast());
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).filter(|s| s.kind == SamKind::Radar).map_or(1.0, |s| s.radar_role.reach_factor());
let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_profile().reach);
let radar = spec.sensor * fit * factor * LOW_KIND.rcs().powf(0.25);
let reach = radar.min(HORIZON * (mast.sqrt() + height.sqrt())).max(NEAR);
let terrain = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).is_some_and(|s| self.horizons.get(&s.id).is_some_and(|h| h.matches(s)));
@@ -262,6 +264,15 @@ pub struct Track {
/// When that was, and when this system's own radar last measured it (0: never, the network's only).
pub tick: u64,
pub own_tick: u64,
/// The station that measured the latest plot, and what it is good for.
pub source: u32,
pub product: battery::Measure,
/// Measurement quality (0..100), separate from identification (`hits`).
pub quality: u8,
/// This system's own measurement provenance. A fresher relay may replace
/// the published plot without granting or erasing the station's own right.
pub own_product: battery::Measure,
pub own_quality: u8,
/// Ticks the track lives without a new measurement.
pub ttl: u32,
pub hits: u8,
@@ -302,6 +313,19 @@ impl Track {
pub fn own_within(&self, now: u64, age: u64) -> bool {
self.own_tick > 0 && now.saturating_sub(self.own_tick) <= age
}
/// The station's own measurement was a confirmed fire plot, fresh enough.
/// A relayed plot has `own_tick == 0` and never passes this test.
pub fn own_fire_within(&self, now: u64, age: u64) -> bool {
self.own_within(now, age) && self.own_product.allows_fire() && self.own_quality >= FIRE_QUALITY
}
/// Own plot good enough for a launcher's ordinary shot.
pub fn own_authorizes(&self, now: u64) -> bool {
self.own_fire_within(now, MISSILE_AGE)
}
/// Who measured the latest plot, as an ID (`0`: no station).
pub fn measured_by(&self) -> Option<u32> {
(self.source != 0).then_some(self.source)
}
pub fn ident(&self) -> Ident {
match self.hits {
0 | 1 => Ident::Unknown,
@@ -318,16 +342,12 @@ impl Track {
impl Sam {
/// Fictional antenna height and scan characteristics for gameplay roles.
pub(super) fn sensor_mast(&self) -> f64 {
self.kind.spec().mast + if self.kind == SamKind::Radar && self.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 }
self.kind.spec().mast + self.radar_profile().mast
}
pub(super) fn scan_profile(&self) -> Scan {
if self.kind != SamKind::Radar { return self.kind.scan(); }
match self.radar_role {
battery::RadarRole::Multifunction => self.kind.scan(),
battery::RadarRole::Search => Scan { period: 170, agile: false },
battery::RadarRole::Engagement => Scan { period: 70, agile: true },
battery::RadarRole::Height => Scan { period: 140, agile: false },
}
let profile = self.radar_profile();
Scan { period: profile.cycle, agile: profile.agile }
}
/// Ticks for its beam to go round (longer when the radar is damaged).
pub(super) fn scan_ticks(&self) -> f64 {
@@ -340,6 +360,10 @@ impl Sam {
pub fn track(&self, id: u32) -> Option<&Track> {
self.tracks.iter().find(|t| t.id == id)
}
/// Refined/fire channels this station is currently using.
pub fn own_channels_used(&self) -> usize {
self.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count()
}
}
/// Whether a beam that moved from `from` by `w` radians this tick passed `bearing` (all angles taken round 2π,
@@ -353,10 +377,18 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
match index.get(&t.id) {
Some(&k) => {
let mine = &mut tracks[k];
if t.tick > mine.tick {
let (own_tick, locked) = (mine.own_tick, if t.own_tick > 0 { t.locked } else { mine.locked });
// Prefer the fresher plot; at the same tick the better one (a fire plot
// over a coarse search plot), without making anything newer.
if t.tick > mine.tick || (t.tick == mine.tick && t.quality > mine.quality) {
// A relayed plot is published with its source/quality, but it
// neither refreshes nor erases this station's own measurement and its right.
let (own_tick, own_product, own_quality, locked) = if t.own_tick > 0 {
(t.own_tick, t.own_product, t.own_quality, t.locked)
} else {
(mine.own_tick, mine.own_product, mine.own_quality, mine.locked)
};
let hits = mine.hits.max(t.hits);
*mine = Track { own_tick: if t.own_tick > 0 { t.own_tick } else { own_tick }, hits, locked, ..t };
*mine = Track { own_tick, own_product, own_quality, hits, locked, ..t };
}
}
None => {
@@ -366,6 +398,23 @@ fn merge(tracks: &mut Vec<Track>, index: &mut HashMap<u32, usize>, t: Track) {
}
}
/// A plot's quality (0..100). It uses only the measured geometry and the
/// station's own fit, never the target's hidden state.
fn plot_quality(sam: &Sam, profile: battery::RadarProfile, product: battery::Measure, ratio: f64, height: f64) -> u8 {
let ratio = ratio.clamp(0.0, 1.0);
let base = match profile.id {
"radar_search" => 46.0 - 14.0 * ratio,
"radar_height" => 74.0 - 12.0 * ratio + if height < 120.0 { 8.0 } else if height < 200.0 { 3.0 } else { 0.0 },
"radar_track" => 88.0 - 12.0 * ratio,
"radar_multi" => 72.0 - 14.0 * ratio,
_ => 78.0 - 14.0 * ratio,
};
// A search plot is coarse whatever the profile; only a matched refinement or
// a fire plot gets the profile's accuracy.
let base = if product == battery::Measure::Search { base.min(48.0) } else { base };
(base * sam.radar_fit()).round().clamp(5.0, 99.0) as u8
}
impl Sim {
/// Rebuilds the systems' horizons in turn, then lets each radar's beam pass the sky: new measurements
/// into the tracks, old tracks out, and the network's tracks shared.
@@ -409,6 +458,7 @@ impl Sim {
index.clear();
index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k)));
let spec = sam.kind.spec();
let profile = sam.radar_profile();
let scan = sam.scan_profile();
let period = sam.scan_ticks();
let w = TAU / period;
@@ -416,6 +466,9 @@ impl Sim {
sam.beam = (b0 + w) % TAU;
let at = antenna(sam);
let horizon = self.horizons.get(&sam.id);
let local = spec.sensor * profile.local;
// Channels already refining or holding fire plots. Search plots do not use one.
let mut used = sam.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count();
let mut fresh: Vec<Track> = Vec::new();
for (d, h) in self.drones.iter().zip(&heights) {
if !d.alive() {
@@ -423,7 +476,7 @@ impl Sim {
}
let rel = d.pos - at;
let dist = rel.length();
if dist > spec.sensor * if sam.kind == SamKind::Radar { sam.radar_role.reach_factor().max(1.0) * 1.2 } else { 1.2 } {
if dist > spec.sensor * profile.reach.max(1.0) * 1.2 {
continue;
}
let locked = sam.target == Some(d.id) || sam.gun_target == Some(d.id);
@@ -431,13 +484,36 @@ impl Sim {
// The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round).
let in_beam = swept(rel.x.atan2(-rel.z), b0, w);
let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64);
// A search radar's network track cues this fictional tracking radar to look, but is
// never itself a measurement: reach, terrain, probability and noise still apply.
let cue = sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement
// A network plot cues a fire-quality radar to look, but is never itself a
// measurement: reach, terrain, probability and noise still apply.
let cue = profile.allows(battery::Measure::Fire)
&& held.is_some_and(|t| t.own_tick == 0 && t.age(now) <= MISSILE_AGE);
if !(in_beam || locked || revisit || cue) {
continue;
}
// The separate stations search their own patch; a cue or an already held
// contact may be followed beyond it, never an arbitrary target of the map.
if profile.local < 1.0 && dist > local && !locked && !(cue || held.is_some_and(|t| t.own_tick > 0)) {
continue;
}
// The tracked-contact channels are a hard limit: work per tick stays bounded
// and a full station does not silently refine the whole sky. A station already
// refining a contact keeps its channel; a new refinement needs a free one, and
// without one the station still publishes its ordinary coarse search plot.
let own_held = held.is_some_and(|t| t.own_tick > 0);
let holds_channel = own_held && held.is_some_and(|t| t.own_product != battery::Measure::Search);
let mut product = if profile.allows(battery::Measure::Fire) {
battery::Measure::Fire
} else if profile.allows(battery::Measure::Refine) && held.is_some() {
// Refinement only applies to a contact already matched, own or network.
battery::Measure::Refine
} else {
battery::Measure::Search
};
let wants_channel = product != battery::Measure::Search && !holds_channel;
if profile.channels > 0 && wants_channel && used >= profile.channels as usize {
product = battery::Measure::Search;
}
let height = h.unwrap_or(d.pos.y - sam.pos.y);
let reach = reach(sam, d.kind, height);
if dist > reach || (dist > NEAR && horizon.is_some_and(|hz| hz.hides(at, d.pos))) {
@@ -454,9 +530,13 @@ impl Sim {
if dist > NEAR && dice(seed, now, key, 0) >= p {
continue;
}
let sigma = if locked { 0.3 } else if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement { 0.45 + dist * 0.002 } else { 0.8 + dist * 0.004 };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * 0.5, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
let sigma = if locked { 0.3 } else { profile.sigma + dist * profile.spread };
let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * profile.vertical, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma;
let measured = d.pos + noise;
let quality = plot_quality(sam, profile, product, dist / reach.max(1.0), height);
if profile.channels > 0 && wants_channel && product != battery::Measure::Search {
used += 1;
}
let hits = held.map_or(1, |t| t.hits.saturating_add(1));
// What this measurement says of the contact's class and speed, from the measured
// places alone: the first blip gives neither; a later one, the change of place over
@@ -477,6 +557,11 @@ impl Sim {
vel,
tick: now,
own_tick: now,
source: sam.id,
product,
quality,
own_product: product,
own_quality: quality,
ttl,
hits,
locked,
@@ -512,7 +597,7 @@ impl Sim {
for (id, at, range, tracks) in &shared {
if *id != sam.id && at.distance(sam.pos) <= range.min(mine) {
for t in tracks {
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, ..*t });
merge(&mut sam.tracks, &mut index, Track { own_tick: 0, own_product: battery::Measure::Search, own_quality: 0, ..*t });
}
}
}
@@ -545,7 +630,22 @@ impl Sim {
// No system is deployed: no estimation happens, the fallback is the sky as it is
// (the screens have always had it), with the figures a system would show.
.filter(|d| d.alive())
.map(|d| Track { id: d.id, class: ClassEst::Firm(d.kind.spec().class), pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 1, hits: 3, locked: false })
.map(|d| Track {
id: d.id,
class: ClassEst::Firm(d.kind.spec().class),
pos: d.pos,
vel: d.vel,
tick: now,
own_tick: now,
source: 0,
product: battery::Measure::Fire,
quality: 100,
own_product: battery::Measure::Fire,
own_quality: 100,
ttl: 1,
hits: 3,
locked: false,
})
.collect()
} else {
self.picture().into_values().collect()
@@ -554,11 +654,12 @@ impl Sim {
AirPicture { now, tracks, unaided }
}
/// The freshest track of each drone any system holds: the air picture.
/// The freshest track of each drone any system holds: the air picture. At one
/// tick the better plot (quality, then product) is the one the player sees.
pub fn picture(&self) -> HashMap<u32, Track> {
let mut best: HashMap<u32, Track> = HashMap::new();
for t in self.sams.iter().flat_map(|s| s.tracks.iter()) {
if best.get(&t.id).is_none_or(|b| t.tick > b.tick) {
if best.get(&t.id).is_none_or(|b| (t.tick, t.quality, t.product) > (b.tick, b.quality, b.product)) {
best.insert(t.id, *t);
}
}
@@ -645,8 +746,8 @@ mod relay_tests {
/// kept, and passing the same message again adds nothing (#133).
#[test]
fn a_repeated_relay_adds_no_confidence_and_stays_foreign() {
let ours = Track { id: 7, class: ClassEst::Unknown, pos: DVec3::new(0.0, 100.0, 0.0), vel: DVec3::ZERO, tick: 90, own_tick: 90, ttl: 400, hits: 1, locked: false };
let relay = Track { id: 7, class: ClassEst::Probable(Class::Drone), pos: DVec3::new(0.0, 100.0, -10.0), vel: DVec3::X, tick: 100, own_tick: 0, ttl: 400, hits: 2, locked: false };
let ours = Track { id: 7, class: ClassEst::Unknown, pos: DVec3::new(0.0, 100.0, 0.0), vel: DVec3::ZERO, tick: 90, own_tick: 90, source: 1, product: battery::Measure::Fire, quality: 80, own_product: battery::Measure::Fire, own_quality: 80, ttl: 400, hits: 1, locked: false };
let relay = Track { id: 7, class: ClassEst::Probable(Class::Drone), pos: DVec3::new(0.0, 100.0, -10.0), vel: DVec3::X, tick: 100, own_tick: 0, source: 2, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 2, locked: false };
let mut tracks = vec![ours];
let mut index: HashMap<u32, usize> = HashMap::from([(7, 0)]);
merge(&mut tracks, &mut index, relay);
+16 -1
View File
@@ -1083,7 +1083,22 @@ mod tests {
sim.drones.push(d);
sim.tick = hidden_launch_tick;
sim.scout_launch(drone, id, DroneKind::Shahed, DVec3::new(hidden_x, 70.0, 700.0));
let track = sight::Track { id: drone, class: ClassEst::Firm(Class::Drone), pos: DVec3::new(0.0, 100.0, 1000.0), vel: -DVec3::Z * 5.0, tick: 100, own_tick: 100, ttl: 100, hits: 3, locked: false };
let track = sight::Track {
id: drone,
class: ClassEst::Firm(Class::Drone),
pos: DVec3::new(0.0, 100.0, 1000.0),
vel: -DVec3::Z * 5.0,
tick: 100,
own_tick: 100,
source: 1,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 100,
hits: 3,
locked: false,
};
sim.sams[0].tracks.push(track);
sim.tick = 100;
sim.step_strikes(&mut ground, None, &mut out);
@@ -1,8 +1,8 @@
// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.
pub const VARIANTS: &[UnitVariant] = &[
UnitVariant { id: "s400_launcher", kind: SamKind::S400, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-400 — отдельная пусковая" },
UnitVariant { id: "s500_launcher", kind: SamKind::S500, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-500 — отдельная пусковая" },
UnitVariant { id: "radar_search", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Search, label: "РЛС обзора" },
UnitVariant { id: "radar_track", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Engagement, label: "РЛС сопровождения" },
UnitVariant { id: "radar_height", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Height, label: "Мачтовая РЛС" },
UnitVariant { id: "s400_launcher", kind: SamKind::S400, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-400 — отдельная пусковая", description: "Пусковая С-400 без своей РЛС: работает по данным сети." },
UnitVariant { id: "s500_launcher", kind: SamKind::S500, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-500 — отдельная пусковая", description: "Пусковая С-500 без своей РЛС: работает по данным сети." },
UnitVariant { id: "radar_search", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Search, label: "РЛС обзора", description: "Дальний обзор: редкие грубые отметки и область поиска; права на пуск не даёт." },
UnitVariant { id: "radar_track", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Engagement, label: "РЛС сопровождения", description: "Сопровождение: локальный поиск, два канала точных треков; собственное измерение даёт право на пуск." },
UnitVariant { id: "radar_height", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Height, label: "Мачтовая РЛС", description: "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт." },
];
+1 -1
View File
@@ -333,7 +333,7 @@ pub(super) fn draw_sam_model(sam: &Sam, rng: &mut Rng, out: &mut Out) {
part(out, model, sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s), base, s);
}
if let Some((model, h, back, size, tilt)) = parts.spinner {
let extra = if sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Height { 8.0 } else { 0.0 };
let extra = if sam.kind == SamKind::Radar { sam.radar_profile().mast } else { 0.0 };
let foot = sam.pos + up + DVec3::Y * h * s + base * DVec3::new(0.0, 0.0, back * s);
for segment in 0..(extra as u32 / 2) {
part(out, "airdef:radar_mast", foot + DVec3::Y * (segment as f64 * 2.0 + 0.5), base, 1.0);
+83 -11
View File
@@ -101,14 +101,17 @@ impl SamKind {
/// A live big radar in data-link reach of `sam` that measured `id` recently.
pub(super) fn radar_cue(sam: &Sam, radars: &[&Sam], id: u32, now: u64) -> bool {
radars.iter().any(|r| {
r.radar_role.authorizes()
r.radar_profile().products & battery::RadarProfile::FIRE_BIT != 0
&& r.link_range() > 0.0
&& sam.link_range() > 0.0
&& r.alive()
&& !r.moving()
&& r.radar_up()
&& r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range())
&& r.track(id).is_some_and(|t| t.own_tick > 0 && now.saturating_sub(t.own_tick) <= if sam.mode == battery::SamMode::LauncherOnly { sight::MISSILE_AGE } else { FAR_RADAR_AGE })
&& r.track(id).is_some_and(|t| {
let age = if sam.mode == battery::SamMode::LauncherOnly { sight::MISSILE_AGE } else { FAR_RADAR_AGE };
t.own_fire_within(now, age)
})
})
}
@@ -146,7 +149,17 @@ pub(super) struct Opts {
/// `role_in_reach` that the system has a target of its roles in range anyway (no long shots then).
#[allow(clippy::too_many_arguments)]
pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Drone, now: u64, claimed: u32, k: f64, opts: Opts, cued: bool, role_in_reach: bool) -> Option<Basis> {
if sam.mode == battery::SamMode::LauncherOnly && !cued { return None; }
// A launch rests on the battery's own confirmed fire plot. A launcher
// without its own radar may use a supporting radar's own fire plot; a
// relayed plot, a search plot or a height refinement never authorizes an
// ordinary shot. A heavy system's *far* shot is the exception it already
// had: it may use the cue radar's own confirmed fire plot beyond its reach.
let own = track.own_authorizes(now);
if sam.mode == battery::SamMode::LauncherOnly {
if !cued { return None; }
} else if !own && !cued {
return None;
}
let blocks = target_blocks(sam.roles, Some(track), now, d);
if blocks & !ROLE != 0 {
return None;
@@ -159,12 +172,14 @@ pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Dro
return None;
}
if reach == 0 {
return Some(Basis::Role);
// A normal shot belongs to the battery's own confirmed measurement;
// a launcher-only battery uses its supporting radar's (checked above).
return (own || sam.mode == battery::SamMode::LauncherOnly).then_some(Basis::Role);
}
let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, track.est(now)) == 0;
return (far && far_blocks(opts.far_shots, sam, load, cued, role_in_reach) == 0).then_some(Basis::FarShot);
}
(reach == 0 && last_chance(opts.last_chance, sam.roles, est, d, claimed)).then_some(Basis::LastChance)
(reach == 0 && (own || sam.mode == battery::SamMode::LauncherOnly) && last_chance(opts.last_chance, sam.roles, est, d, claimed)).then_some(Basis::LastChance)
}
/// The kill chance of an interceptor that met its target `dist` from the launcher whose reach is `max`:
@@ -317,6 +332,37 @@ impl Sim {
return v;
}
if !sam.kind.armed() {
if sam.kind == SamKind::Radar {
let profile = sam.radar_profile();
v.push(check(true, format!(
"профиль {} [{}]: {}, оборот {:.1} с, каналы {}, локальный поиск {}",
profile.name,
profile.id,
profile.products_text(),
profile.cycle as f64 / 20.0,
profile.channels,
if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) },
)));
v.push(check(true, format!("ограничение: {}", profile.limit)));
v.push(check(true, format!("свои треки: {}, каналы {}/{}", sam.own.len(), sam.own_channels_used(), profile.channels)));
let now = self.tick;
let mut tracks: Vec<&Track> = sam.tracks.iter().filter(|t| t.own_tick > 0).collect();
tracks.sort_by_key(|t| std::cmp::Reverse(t.quality));
for t in tracks.into_iter().take(4) {
v.push(check(
t.own_authorizes(now),
format!(
"цель {}: {} ({}), качество {}, возраст {:.1} с{}",
t.id,
t.own_product.name(),
if t.own_authorizes(now) { "право на пуск" } else { "пуск не разрешает" },
t.own_quality,
now.saturating_sub(t.own_tick) as f64 / 20.0,
if t.own_authorizes(now) { "" } else { "; нужно подтверждённое измерение станции" },
),
));
}
}
v.push(check(false, "нет оружия (РЛС, склад, РЭБ, прожектор)"));
return v;
}
@@ -447,7 +493,15 @@ impl Sim {
let age = tr.age(now) as f64 / 20.0;
let lock = if tr.own_within(now, sight::GUN_AGE) && tr.locked { ", захват" } else { "" };
let how = if tr.forecast(now) { format!("прогноз ±{:.0} м", tr.uncertainty(now)) } else { "измерение".to_string() };
format!("трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}, {}", tr.ident().name(), tr.class.name(), if blocks & STALE != 0 { "устарел для пуска" } else { "годен для пуска" })
let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect();
let authority = tr.own_authorizes(now) || (sam.mode == battery::SamMode::LauncherOnly && radar_cue(sam, &radars, t.id, now));
format!(
"трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}, {}; право на пуск: {}",
tr.ident().name(),
tr.class.name(),
if blocks & STALE != 0 { "устарел" } else { "годен" },
if authority { "своё подтверждённое измерение" } else { "нет (сеть или обзор не дают права)" }
)
}
_ => "не обнаружена ни своей РЛС, ни сетью".to_string(),
};
@@ -549,7 +603,9 @@ impl Sim {
));
}
let doc_ok = chance || area | held_back == 0;
let grounds = (sam.mode != battery::SamMode::LauncherOnly || cued) && blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok);
let own = track.is_some_and(|tr| tr.own_authorizes(now));
let authorized = own || (sam.mode == battery::SamMode::LauncherOnly && cued) || far_ok;
let grounds = authorized && blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok);
fires |= grounds && free < need && mb == 0 && aligned && land == 0;
}
if let Some(gun) = &spec.gun {
@@ -648,7 +704,8 @@ mod tests {
let now = sim.tick;
let d = sim.drones[0].clone();
sim.sams[0].tracks.retain(|t| t.id != d.id);
sim.sams[0].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false });
let source = sim.sams[0].id;
sim.sams[0].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: now, own_tick: now, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false });
}
#[test]
@@ -810,7 +867,7 @@ mod tests {
assert!(w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::<Vec<_>>());
// Holding fire (no roles at all): nothing is a candidate, the unidentified either.
let d = sim.drones[0].clone();
let unknown = Track { id: d.id, class: ClassEst::Unknown, pos: d.pos, vel: DVec3::ZERO, tick: 0, own_tick: 0, ttl: 400, hits: 1, locked: false };
let unknown = Track { id: d.id, class: ClassEst::Unknown, pos: d.pos, vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: battery::Measure::Search, quality: 40, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 1, locked: false };
assert_ne!(why::target_blocks(0, Some(&unknown), 0, &d) & why::ROLE, 0, "with no roles (hold fire) even the unknown is blocked");
}
@@ -832,12 +889,27 @@ mod tests {
.drones
.iter()
.filter(|d| d.alive())
.map(|d| Track { id: d.id, class: ClassEst::Firm(d.kind.spec().class), pos: d.pos, vel: d.vel, tick: now, own_tick: now, ttl: 400, hits: 3, locked: false })
.map(|d| Track {
id: d.id,
class: ClassEst::Firm(d.kind.spec().class),
pos: d.pos,
vel: d.vel,
tick: now,
own_tick: now,
source: 0,
product: battery::Measure::Fire,
quality: 90,
own_product: battery::Measure::Fire,
own_quality: 90,
ttl: 400,
hits: 3,
locked: false,
})
.collect();
for r in sim.sams.iter_mut().filter(|s| s.kind == SamKind::Radar) {
for t in &tracks {
r.tracks.retain(|o| o.id != t.id);
r.tracks.push(*t);
r.tracks.push(Track { source: r.id, ..*t });
}
}
}
+10 -5
View File
@@ -134,35 +134,40 @@
"kind": "S400",
"mode": "launcher",
"role": "multi",
"label": "С-400 — отдельная пусковая"
"label": "С-400 — отдельная пусковая",
"description": "Пусковая С-400 без своей РЛС: работает по данным сети."
},
{
"id": "s500_launcher",
"kind": "S500",
"mode": "launcher",
"role": "multi",
"label": "С-500 — отдельная пусковая"
"label": "С-500 — отдельная пусковая",
"description": "Пусковая С-500 без своей РЛС: работает по данным сети."
},
{
"id": "radar_search",
"kind": "Radar",
"mode": "integrated",
"role": "search",
"label": "РЛС обзора"
"label": "РЛС обзора",
"description": "Дальний обзор: редкие грубые отметки и область поиска; права на пуск не даёт."
},
{
"id": "radar_track",
"kind": "Radar",
"mode": "integrated",
"role": "engagement",
"label": "РЛС сопровождения"
"label": "РЛС сопровождения",
"description": "Сопровождение: локальный поиск, два канала точных треков; собственное измерение даёт право на пуск."
},
{
"id": "radar_height",
"kind": "Radar",
"mode": "integrated",
"role": "height",
"label": "Мачтовая РЛС"
"label": "Мачтовая РЛС",
"description": "Мачтовая: поднятая антенна уточняет низкие контакты над рельефом; права на пуск не даёт."
}
],
"items": [
+24 -12
View File
@@ -42,24 +42,36 @@
/airdef battery
```
Нумерацию существующей техники показывает `/airdef battery`. Чтобы переоборудовать её:
Нумерацию существующей техники показывает `/airdef battery`:
```text
/airdef battery <номер С-400 или С-500> launcher
/airdef radar <номер РЛС> search
/airdef radar <номер другой РЛС> engagement
/airdef battery <номер С-400 или С-500> integrated
/airdef radar <номер РЛС> on|off
```
Можно оставить одну многофункциональную РЛС (`multi`) и несколько пусковых.
Поисковая/мачтовая РЛС даёт подсказку, но не разрешает огонь сама. РЛС сопровождения принимает
подсказку и должна **сама измерить** цель в своей игровой досягаемости и с учётом рельефа.
Чужой трек не превращается в собственное измерение. После этого связанные пусковые используют
общую картину и существующее распределение целей. Если РЛС сопровождения уничтожена, свёрнута,
Профиль РЛС задаётся при размещении (`radar_search`, `radar_track`, `radar_height`) и не
переключается на ходу: `radar <номер> search|engagement|height` больше не меняет оборудование.
Можно оставить одну многофункциональную РЛС (`multi`, старые сохранения) и несколько пусковых.
- **Обзорная** (`radar_search`): широкая дальность и ранние грубые отметки, медленный оборот,
без каналов уточнения. Права на пуск не даёт.
- **Мачтовая** (`radar_height`): поднятая антенна и лучшее вертикальное измерение уточняют низкие
контакты в локальной зоне; рельеф по-прежнему скрывает цель. Права на пуск не даёт.
- **Сопровождения** (`radar_track`): локальный поиск, электронный оборот, два канала точных
треков. Сеть может подсказать, но станция должна **сама измерить** цель; только собственное
подтверждённое измерение разрешает пуск.
- **Многофункциональная** (`multi`): совместимый универсальный вариант, но не лучший во всём.
Сеть передаёт трек вместе с измерившей станцией, возрастом и качеством. Повторная пересылка не
освежает измерение и не создаёт права на пуск. Уточнение применяется только к сопоставленному
контакту, а число каналов ограничено на каждом тике. Если РЛС сопровождения уничтожена, свёрнута,
потеряла связь или её измерение устарело, новые пуски прекращаются. Уже вылетевшие ракеты
продолжают штатную игровую логику связи/памяти/самонаведения.
Старые миры и обычные `/airdef deploy s400` / `s500` сохраняют сборную конфигурацию `integrated`.
Режимы, роли, боезапас и использованные контейнеры сохраняются с миром и сценариями.
Режимы, роли, боезапас и использованные контейнеры сохраняются с миром и сценариями; новые
сохранения пишут устойчивый ID профиля, старые строки только с ролью читаются как те же профили.
У прежнего игрового С-500 был магазин на четыре ракеты при двух нарисованных ТПК;
теперь он согласован с двумя физическими ячейками. При загрузке старой расстановки
его загруженный остаток ограничивается новой вместимостью, как при обычном восстановлении боезапаса.
@@ -96,9 +108,9 @@
## Ограничения
Роли РЛС и мачта пока используют общую модель машины, с разным поведением/отображением антенны.
Отдельные точные модели 91Н6/92Н6/96Л6, машина КП, ручная принадлежность к батарее, отдельные
каналы сопровождения и кабельное снабжение пока не добавлены. Подробные режимы и параметры реальных
Все три профиля пока используют общий силуэт машины и антенны (отдельная художественная зона
владельца): различаются поведение, цикл, точность, каналы и подпись. Точные модели 91Н6/92Н6/96Л6,
машина КП, ручная принадлежность к батарее и кабельное снабжение не добавлены. Подробные режимы и параметры реальных
комплексов не моделируются. В следующей серии добавлены конечная работа двигателя/coast (#120),
доставка RM48U через ТЗМ (#118), переключение излучения (#121) и укрытия от непрямого blast (#119).
Текущий объём и ограничения описаны в [техническом журнале](CODEX-HANDOFF.md).
+1
View File
@@ -31,6 +31,7 @@
| #118 | Физический С-400/RM48U, четыре общие ячейки, конечные запасы; доставка и обратный вывоз ТЗМ, резерв/отмена, возврат снятой ПВО; обе фазы вывозного маршрута сохраняются; carrier/крышки/выброс/зажигание/разгон в записи; фантомное ПВО удалено | Визуальная приёмка пуска и маршрутов на сложном рельефе; другие носители не добавлены без подтверждённого профиля |
| #128 | Невыполнимый возврат RM48U (ПУ движется/повреждена, маршрут недоступен, заявку уже везёт другая ТЗМ, у склада нет места) больше не блокирует ТЗМ: заявка сохраняется, свободная ТЗМ исполняет независимые заявки на доставку; выполнимый возврат снова в приоритете; консервация боеприпасов и save-restore посреди маршрута покрыты регрессиями | Игровая приёмка маршрутов на сложном рельефе остаётся за #118 |
| #129 | Единые стадии пуска: выброс без мотора (`cold` 20/24 тика у С-400/С-500, 8 у IRIS-T/Тора), зажигание в текущей позиции, departure с плавным ростом тяги/темпа поворота, наведение только после `cold + boost`; рельсовые ракеты получили spool тяги без холодного выброса, P1-SUN — без струи; RM48U согласован на 20 тиков; live/replay/export читают записанное зажигание; `pk`, максимальные скорости и коллизии не менялись | Парные replay-MP4 до/после и кадры сняты на одном мире/seed/сценарии (Metal/offscreen); измеренный сдвиг первой вспышки 0,233 → 0,900 с. Остаётся человеческая визуальная оценка композиции, very-close план выброса; live-видео, Windows/Linux и живое прослушивание не проверялись |
| #134 | Три самостоятельных игровых профиля отдельных РЛС (`radar_search`, `radar_track`, `radar_height`) с устойчивыми ID, циклом/каналами/локальным поиском и разрешёнными продуктами измерения; `on/off` сохраняется, переключение роли на ходу отклоняется; встроенные РЛС комплексов сохраняют своё право на пуск. Сеть передаёт измерившую станцию, возраст и качество, но повторная пересылка не освежает измерение и не даёт права на пуск. Пуск требует собственного подтверждённого огневого трека (или внешней огневой РЛС для отдельной пусковой и дальнего пуска). Карта/монитор/`why` показывают профиль, источник, продукт, качество, каналы и причину отказа; старые сейвы мигрируют по роли, replay хранит профиль. Тесты: сценарий профилей по отдельности/парами/втроём, дублирование, каналы, off/повреждение/связь, relay, миграция и replay | Общий силуэт машины у трёх профилей (различаются поведение, подписи и статусы); публикация наблюдаемой роли РЛС в картине противника (#127) не расширена; визуальная приёмка на Windows/Linux и живые замеры совокупной картины не проводились |
Для #118 RM48U — явно условный Minecraft-профиль. Существование сочетания опирается на сообщение ведомства,
а игровые параметры не выдаются за реальные. `ground-stock` — команда подготовки sandbox-сценария,
+4 -2
View File
@@ -37,8 +37,8 @@ def load():
taken = set(referenced) | unit_kinds | set(ids)
for variant in data["variants"]:
where = f"variants[{variant['id']}]"
if set(variant) != {"id", "kind", "mode", "role", "label"}:
raise ValueError(f"{where}: expected keys id, kind, mode, role, label, got {sorted(variant)}")
if set(variant) != {"id", "kind", "mode", "role", "label", "description"}:
raise ValueError(f"{where}: expected keys id, kind, mode, role, label, description, got {sorted(variant)}")
if not re.fullmatch(r"[a-z0-9_]+", variant["id"]):
raise ValueError(f"{where}: invalid variant id {variant['id']!r}")
if variant["kind"] not in unit_kinds:
@@ -47,6 +47,8 @@ def load():
raise ValueError(f"{where}: unknown configuration {variant['mode']}/{variant['role']}")
if not isinstance(variant["label"], str) or not variant["label"]:
raise ValueError(f"{where}: expected a menu label")
if not isinstance(variant["description"], str) or not variant["description"]:
raise ValueError(f"{where}: expected a description")
if variant["id"] in taken:
raise ValueError(f"{where}: variant id collides with an existing identity or kind")
if len({v["id"] for v in data["variants"]}) != len(data["variants"]):
+2 -1
View File
@@ -316,7 +316,8 @@ def generate_variants(data):
mode = MODES[entry["mode"]]
role = ROLES[entry["role"]]
lines.append(f" UnitVariant {{ id: {text(entry['id'])}, kind: SamKind::{entry['kind']}, "
f"mode: SamMode::{mode}, role: RadarRole::{role}, label: {text(entry['label'])} }},")
f"mode: SamMode::{mode}, role: RadarRole::{role}, label: {text(entry['label'])}, "
f"description: {text(entry['description'])} }},")
return "\n".join(lines + ["];", ""])