Smart raids, wave menu, radar detection (horizon, RCS, terrain), vulnerable SAMs, busiest-first grid

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 23:08:49 +03:00
parent 43346aecfe
commit 8fd28a2de2
16 changed files with 1387 additions and 54 deletions
+37 -5
View File
@@ -39,8 +39,37 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает мо
| Свернуть ПВО | убирает ближайший комплекс у точки под прицелом |
**Командный пункт:** клавиша **N** или `/airdef menu`. В нём список комплексов: выбери комплекс и включай или выключай классы целей
(дроны, реактивные дроны, крылатые, сверхзвуковые, баллистика), есть сброс по умолчанию. Там же переключатели огня ПВО,
монитора, эффектов и разрушений.
(дроны, реактивные дроны, крылатые, сверхзвуковые, баллистика), есть сброс по умолчанию. Там же кнопки «Командный
пункт» (сетка), «Налёт…» и «Огонь, ремонт, эффекты…» (огонь ПВО, ремонт всех, эффекты, разрушения).
**Налёт (меню N → «Налёт: состав и запуск…»):** на первой странице состав — клик по типу листает число
(0, 1, 2, 3, 4, 6, 8, 10, 15, 20, 30, 40); на второй — готовый вариант («Рой Шахедов», «Массированный удар»,
«Баллистика», «Гиперзвук», «Орешник с прикрытием», «Подавление ПВО»), откуда (один сектор, два, со всех сторон,
волнами по типам), дальность старта, цели и **ПУСК**. Цели:
- *только объекты* — всё летит по отмеченным объектам (или по игроку, если их нет);
- *объекты и ПВО* — треть ударных средств бьёт по случайным комплексам;
- *умный противник* — планировщик знает, где стоят комплексы и что видят их РЛС: ведёт дроны и крылатые ракеты
маршрутами в обход зон поражения, низко, за рельефом и через мёртвые зоны; «Герберы» прилетают на 15 с раньше,
чтобы оттянуть ракеты; «Ланцеты» идут по Гепардам и Панцирям, Х-22/Циркон и часть баллистики — по дальнобойным
комплексам; всё остальное стартует со сдвигом так, чтобы прилететь одновременно.
После налёта приходит отчёт: сколько сбито и прорвалось, ракет ПВО потрачено, комплексов потеряно, урон объектам.
**Обнаружение.** РЛС видит цель не дальше, чем позволяют:
- её размер: дальность растёт как корень четвёртой степени из ЭПР — Х-101 и Ланцет видно примерно вдвое ближе, чем Х-22;
- радиогоризонт: низколетящую цель видно поздно (Шахед на 25 м — с ~250 м, баллистику — издалека);
- рельеф и лес: за холмом цель не видна (каждый комплекс строит свой горизонт по 48 лучам; рельеф известен в
прогруженных чанках);
- вблизи (24 м) видно всё.
Радар игрока и мониторы показывают только то, что держат РЛС; в сводке видно «Вне видимости РЛС: N».
Мёртвые зоны — ближе минимальной дальности ракет (Patriot 10 м, Панцирь 25, С-400 30, С-500 40).
**Повреждения.** Взрыв рядом с комплексом повреждает его: он хуже поворачивается, хуже видит и попадает,
дымит, ниже 35% горит. Уничтоженный остаётся горящим остовом, его боекомплект детонирует: чем больше ракет
оставалось, тем мощнее взрыв и дольше вторичные (у Гепарда рвутся снаряды); соседние комплексы тоже могут
пострадать. Объекты (Целеуказатель или `/airdef target here`) имеют прочность, она видна в сводке. Ремонт —
кнопкой в меню или `/airdef repair`.
**Монитор комплекса:** клавиша **K** листает комплексы по очереди, после последнего монитор скрывается. Слева вверху показано:
- состояние комплекса (поиск, сопровождение, доворот, захват, пуск, огонь, перезарядка, огонь запрещён);
@@ -48,13 +77,16 @@ CI: `.gitea/workflows/build.yml` на каждый пуш собирает мо
- камера комплекса: настоящий вид мира из точки комплекса (второй рендер форка), с зумом на цель — тепловизор
при сопровождении, в поиске днём цвет, ночью ПНВ; рамка захвата, дальность, высота, скорость и пеленг.
**Командный пункт ПВО (сетка):** клавиша **J** (или `/airdef grid`, или кнопка в меню N) — на весь экран сетка из
всех комплексов (до 8): у каждого состояние, РЛС, живая камера и боекомплект. Повторное J закрывает.
**Командный пункт ПВО (сетка):** клавиша **J** (или `/airdef grid`, или кнопка в меню N) — на весь экран сетка
до 8 комплексов: у каждого состояние, РЛС, живая камера, прочность и боекомплект. Если комплексов больше, показываются
самые занятые (стреляют, держат захват, сопровождают, горят), раз в 2 секунды; комплекс с монитора K — всегда.
Повторное J закрывает.
Клавиши N, K и J можно переназначить в «Настройки → Моды».
Команды:
- `/airdef wave <тип> [кол-во] [дальность]` — налёт на ближайшую цель. Типы: `shahed`, `geran3`, `lancet`, `gerbera`, `kh101`, `kalibr`, `kh22`, `zircon`, `iskander`, `kinzhal`, `oreshnik` и `mix` (комбинированный удар: «Герберы», шахеды, Герани-3, Х-101, «Калибры» и «Искандер»);
- `/airdef wave <тип> [кол-во] [дальность]` — налёт на ближайшую цель. Типы: `shahed`, `geran3`, `lancet`, `gerbera`, `kh101`, `kalibr`, `kh22`, `zircon`, `iskander`, `kinzhal`, `oreshnik` и `mix` (комбинированный удар двумя секторами: «Герберы», шахеды, Герани-3, Х-101, «Калибры», Х-22, Циркон, «Искандер», «Кинжал», при 30+ — «Орешник»);
- `/airdef raid` — налёт, настроенный в меню; `/airdef target here` — отметить объект под ногами; `/airdef repair` — ремонт;
- `/airdef roles` — показать, по каким классам целей работает каждый комплекс; `/airdef roles <patriot|gepard|pantsir|s400|s500|all> <классы|default>` — задать (классы через запятую: `drone`, `jet`, `cruise`, `supersonic`, `ballistic` или `all`), например `/airdef roles s400 cruise,ballistic`;
- `/airdef deploy <patriot|gepard|pantsir|s400|s500>` — поставить комплекс в 8 блоках перед собой;
- `/airdef hold on|off` — запретить или разрешить ПВО огонь, удобно для съёмки ударов;
+215 -24
View File
@@ -16,6 +16,7 @@ mod monitor;
mod panel;
mod radar;
mod sim;
mod wave;
use sim::{Class, DroneKind, Ground, Out, Sam, SamKind, Sim};
const ITEMS: [&str; 17] = [
@@ -48,6 +49,10 @@ struct AirDef {
monitor_shown: bool,
/// Every system's monitor in a grid (J).
grid: bool,
/// The systems the grid shows (ids), the busiest, chosen every few seconds.
grid_ids: Vec<u32>,
/// The raid the wave menu orders.
wave: wave::WaveConfig,
/// The menu's page while it is open.
menu: Option<Page>,
/// Where the player is, for the sounds' delay and far variants.
@@ -71,6 +76,11 @@ fn travels(event: &str) -> bool {
enum Page {
Main,
Roles(SamKind),
/// The raid's make-up, then its parameters and the launch.
Wave,
WaveGo,
/// Fire, repair, effects, damage.
More,
}
const MENU_KINDS: u32 = 1;
@@ -79,6 +89,16 @@ const BTN_SHADER: u32 = 11;
const BTN_DAMAGE: u32 = 12;
const BTN_MONITOR: u32 = 13;
const BTN_GRID: u32 = 14;
const BTN_WAVE: u32 = 15;
const BTN_REPAIR: u32 = 16;
const WAVE_KINDS: u32 = 2;
const BTN_PRESET: u32 = 30;
const BTN_APPROACH: u32 = 31;
const BTN_DIST: u32 = 32;
const BTN_AIM: u32 = 33;
const BTN_LAUNCH: u32 = 34;
const BTN_NEXT: u32 = 35;
const BTN_MORE: u32 = 17;
const BTN_CLASS: u32 = 100;
const BTN_ALL: u32 = 120;
const BTN_DEFAULT: u32 = 121;
@@ -117,9 +137,13 @@ impl AirDef {
Some(at) => {
if let Some(i) = self.sim.targets.iter().position(|t| t.distance(at) < 3.0) {
self.sim.targets.remove(i);
if i < self.sim.target_health.len() {
self.sim.target_health.remove(i);
}
say("Цель снята");
} else {
self.sim.targets.push(at);
self.sim.target_health.push(100.0);
say(&format!("Цель отмечена: {:.0} {:.0} {:.0}", at.x, at.y, at.z));
}
self.dirty = true;
@@ -314,10 +338,11 @@ impl AirDef {
fn save(&mut self) {
let mut text = String::new();
for s in &self.sim.sams {
text += &format!("sam {} {} {} {} {} {}\n", s.kind.key(), s.pos.x, s.pos.y, s.pos.z, s.heading, s.roles);
text += &format!("sam {} {} {} {} {} {} {}\n", s.kind.key(), s.pos.x, s.pos.y, s.pos.z, s.heading, s.roles, s.health);
}
for t in &self.sim.targets {
text += &format!("target {} {} {}\n", t.x, t.y, t.z);
for (i, t) in self.sim.targets.iter().enumerate() {
let h = self.sim.target_health.get(i).copied().unwrap_or(100.0);
text += &format!("target {} {} {} {h}\n", t.x, t.y, t.z);
}
text += &format!("damage {}\n", self.sim.damage);
for (kind, roles) in &self.sim.roles {
@@ -345,12 +370,16 @@ impl AirDef {
if let Some(r) = w.get(6).and_then(|v| v.parse().ok()) {
sam.roles = r;
}
if let Some(h) = num(7) {
sam.health = h.clamp(0.0, 1.0);
}
self.sim.sams.push(sam);
}
}
Some(&"target") => {
if let (Some(x), Some(y), Some(z)) = (num(1), num(2), num(3)) {
self.sim.targets.push(DVec3::new(x, y, z));
self.sim.target_health.push(num(4).unwrap_or(100.0));
}
}
Some(&"damage") => self.sim.damage = w.get(1) != Some(&"false"),
@@ -373,6 +402,63 @@ impl AirDef {
}
impl AirDef {
/// What a raid strikes: the marked objects, else where the player stands.
fn objects(&self, player: DVec3) -> Vec<DVec3> {
let live: Vec<DVec3> = self
.sim
.targets
.iter()
.enumerate()
.filter(|(i, _)| self.sim.target_health.get(*i).is_none_or(|h| *h > 0.0))
.map(|(_, t)| *t)
.collect();
if live.is_empty() { vec![player] } else { live }
}
fn launch_wave(&mut self, out: &mut Out) -> Result<(), String> {
let p = player().ok_or("Нет игрока")?;
if self.wave.total() == 0 {
return Err("Налёт пуст: выберите типы и число".into());
}
let objects = self.objects(DVec3::new(p.x, p.y, p.z));
self.sim.order_raid(&self.wave.order(), &objects, out);
Ok(())
}
/// The systems the grid shows: the busiest (firing, locking, hit, burning) first, the
/// monitored one always; those shown keep a head start, so the grid doesn't flicker.
fn pick_grid(&mut self) {
let shown = &self.grid_ids;
let mut scored: Vec<(f64, u32)> = self
.sim
.sams
.iter()
.enumerate()
.map(|(i, s)| {
let busy = match s.state {
sim::SamState::Launch | sim::SamState::Fire => 100.0,
sim::SamState::Lock => 85.0,
sim::SamState::Slew => 75.0,
sim::SamState::Track => 65.0,
sim::SamState::Reload => 30.0,
sim::SamState::Search => 10.0,
sim::SamState::Hold => 5.0,
sim::SamState::Destroyed => if s.burning() { 90.0 } else { 1.0 },
};
let near = self.sim.watched(s).map_or(0.0, |d| 15.0 * (1.0 - (d.pos.distance(s.pos) / s.kind.range()).min(1.0)));
let hurt = if s.alive() && s.health < 0.7 { 15.0 } else { 0.0 };
let keep = if shown.contains(&s.id) { 12.0 } else { 0.0 };
let pinned = if self.monitor == Some(i) { 1000.0 } else { 0.0 };
(busy + near + hurt + keep + pinned + s.seen.len().min(5) as f64, s.id)
})
.collect();
scored.sort_by(|a, b| b.0.total_cmp(&a.0));
let mut ids: Vec<u32> = scored.iter().take(8).map(|s| s.1).collect();
// Shown in the order they were deployed, so a cell stays put while it stays chosen.
ids.sort_by_key(|id| self.sim.sams.iter().position(|s| s.id == *id));
self.grid_ids = ids;
}
fn cycle_monitor(&mut self) {
self.monitor = match self.monitor {
None if !self.sim.sams.is_empty() => Some(0),
@@ -398,18 +484,44 @@ impl AirDef {
})
.collect();
widgets.push(Widget::List(ListWidget { id: MENU_KINDS, rows, selected: None }));
let _ = &self.monitor;
widgets.push(Widget::Button(ButtonWidget { id: BTN_GRID, label: "Командный пункт: все комплексы (J)".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_WAVE, label: "Налёт: состав и запуск…".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_MORE, label: "Огонь, ремонт, эффекты…".into() }));
}
Page::More => {
title = "AirDef — управление".to_string();
widgets.push(Widget::Button(ButtonWidget {
id: BTN_HOLD,
label: format!("Огонь ПВО: {}", if self.sim.hold { "запрещён" } else { "разрешён" }),
}));
let monitor = match self.monitor.and_then(|i| self.sim.sams.get(i).map(|s| (i, s))) {
Some((i, s)) => format!("{} №{}", s.kind.name(), i + 1),
None => "скрыт".into(),
};
widgets.push(Widget::Button(ButtonWidget { id: BTN_MONITOR, label: format!("Монитор: {monitor}") }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_GRID, label: "Командный пункт: все комплексы (J)".into() }));
let broken = self.sim.sams.iter().filter(|s| s.health < 1.0).count();
widgets.push(Widget::Button(ButtonWidget { id: BTN_REPAIR, label: format!("Ремонт всех (повреждено: {broken})") }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_SHADER, label: format!("Эффекты: {}", onoff(self.sim.shader)) }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_DAMAGE, label: format!("Разрушения: {}", onoff(self.sim.damage)) }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
Page::Wave => {
let w = &self.wave;
title = format!("Налёт: {} целей — клик по строке меняет число", w.total());
let rows = wave::KINDS
.iter()
.zip(w.counts)
.map(|(k, n)| format!("{} — {}", k.spec().name, if n == 0 { "нет".to_string() } else { n.to_string() }))
.collect();
widgets.push(Widget::List(ListWidget { id: WAVE_KINDS, rows, selected: None }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_NEXT, label: "Параметры и пуск →".into() }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
Page::WaveGo => {
let w = &self.wave;
title = format!("Налёт: {} целей", w.total());
widgets.push(Widget::Button(ButtonWidget { id: BTN_PRESET, label: format!("Готовый: {}", wave::PRESETS[w.preset].name) }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_APPROACH, label: format!("Откуда: {}", w.approach.name()) }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_DIST, label: format!("Старт: {}", panel::distance(w.dist)) }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_AIM, label: format!("Цели: {}", w.aim.name()) }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_LAUNCH, label: format!("▶ ПУСК ({})", w.total()) }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Состав".into() }));
}
Page::Roles(kind) => {
title = format!("{} ({}) — по каким целям стрелять", kind.name(), panel::distance(kind.range()));
@@ -449,7 +561,7 @@ impl AirDef {
}
}
const HELP: &str = "/airdef menu | monitor | grid | give | deploy <комплекс> | wave <тип|mix> [кол-во] [дальность] | clear | targets clear | damage on|off | shader on|off | hold on|off | roles [комплекс классы] | stats";
const HELP: &str = "/airdef menu | monitor | grid | raid | repair | target here | give | deploy <комплекс> | wave <тип|mix> [кол-во] [дальность] | clear | targets clear | damage on|off | shader on|off | hold on|off | roles [комплекс классы] | stats";
impl Mod for AirDef {
fn init() -> Result<(Self, Registration), String> {
@@ -462,6 +574,8 @@ impl Mod for AirDef {
monitor: None,
monitor_shown: false,
grid: false,
grid_ids: Vec::new(),
wave: wave::WaveConfig::default(),
menu: None,
listener: DVec3::ZERO,
pending: Vec::new(),
@@ -500,8 +614,14 @@ impl Mod for AirDef {
self.draw_hud(DVec3::new(p.x, p.y, p.z), p.yaw);
// The monitors and the cameras they show.
if self.grid {
render::set_hud(&monitor::grid(&self.sim, render::gui_size()));
let views: Vec<_> = self.sim.sams.iter().take(8).map(|s| monitor::camera(&self.sim, s)).collect();
let stale = self.grid_ids.iter().any(|id| !self.sim.sams.iter().any(|s| s.id == *id));
if self.sim.tick % 40 == 0 || stale || self.grid_ids.len() < self.sim.sams.len().min(8) {
self.pick_grid();
}
let picked: Vec<usize> =
self.grid_ids.iter().filter_map(|id| self.sim.sams.iter().position(|s| s.id == *id)).collect();
render::set_hud(&monitor::grid(&self.sim, &picked, render::gui_size()));
let views: Vec<_> = picked.iter().map(|&i| monitor::camera(&self.sim, &self.sim.sams[i])).collect();
render::set_views(&views);
self.monitor_shown = true;
} else {
@@ -534,15 +654,75 @@ impl Mod for AirDef {
}
return;
}
(Page::Main, BTN_HOLD) => self.sim.hold = !self.sim.hold,
(Page::More, BTN_HOLD) => self.sim.hold = !self.sim.hold,
(Page::Main, BTN_MONITOR) => self.cycle_monitor(),
(Page::Main, BTN_WAVE) => {
self.open_menu(Page::Wave);
return;
}
(Page::More, BTN_REPAIR) => {
self.sim.repair();
self.dirty = true;
}
(Page::Wave, WAVE_KINDS) => {
if (row as usize) < wave::KINDS.len() {
self.wave.step(row as usize);
}
}
(Page::WaveGo, BTN_PRESET) => {
let next = self.wave.preset + 1;
self.wave.apply(next);
}
(Page::WaveGo, BTN_APPROACH) => {
let all = sim::Approach::ALL;
let i = all.iter().position(|a| *a == self.wave.approach).unwrap_or(0);
self.wave.approach = all[(i + 1) % all.len()];
}
(Page::WaveGo, BTN_DIST) => {
let all = wave::DISTANCES;
let i = all.iter().position(|d| *d == self.wave.dist).unwrap_or(0);
self.wave.dist = all[(i + 1) % all.len()];
}
(Page::WaveGo, BTN_AIM) => {
let all = sim::Aim::ALL;
let i = all.iter().position(|a| *a == self.wave.aim).unwrap_or(0);
self.wave.aim = all[(i + 1) % all.len()];
}
(Page::WaveGo, BTN_LAUNCH) => {
let mut out = Out::default();
match self.launch_wave(&mut out) {
Ok(()) => {
self.emit(out);
self.menu = None;
ui::close_screen();
return;
}
Err(e) => say(&e),
}
}
(Page::Wave, BTN_BACK) | (Page::More, BTN_BACK) => {
self.open_menu(Page::Main);
return;
}
(Page::Wave, BTN_NEXT) => {
self.open_menu(Page::WaveGo);
return;
}
(Page::WaveGo, BTN_BACK) => {
self.open_menu(Page::Wave);
return;
}
(Page::Main, BTN_MORE) => {
self.open_menu(Page::More);
return;
}
(Page::Main, BTN_GRID) => {
self.grid = true;
self.menu = None;
ui::close_screen();
return;
}
(Page::Main, BTN_SHADER) => {
(Page::More, BTN_SHADER) => {
self.sim.shader = !self.sim.shader;
if self.sim.shader {
render::set_post(include_str!("../shaders/effects.wgsl"));
@@ -550,7 +730,7 @@ impl Mod for AirDef {
render::clear_post();
}
}
(Page::Main, BTN_DAMAGE) => {
(Page::More, BTN_DAMAGE) => {
self.sim.damage = !self.sim.damage;
self.dirty = true;
}
@@ -619,28 +799,39 @@ impl Mod for AirDef {
.nearest_target(DVec3::new(p.x, p.y, p.z))
.unwrap_or(DVec3::new(p.x, p.y, p.z));
if *kind == "mix" {
// A combined strike: decoys first, then Shaheds, jets and cruise missiles.
let n = count.max(4);
self.sim.raid(DroneKind::Gerbera, target, n / 3 + 1, dist, &mut out);
self.sim.raid(DroneKind::Shahed, target, n / 3 + 1, dist + 40.0, &mut out);
self.sim.raid(DroneKind::Geran3, target, n / 6 + 1, dist + 200.0, &mut out);
self.sim.raid(DroneKind::Kh101, target, n / 6 + 1, dist + 500.0, &mut out);
self.sim.raid(DroneKind::Kalibr, target, n / 8 + 1, dist + 700.0, &mut out);
self.sim.raid(DroneKind::Iskander, target, n / 12 + 1, dist, &mut out);
let objects = self.objects(DVec3::new(p.x, p.y, p.z));
self.sim.order_raid(&wave::WaveConfig::mix(count, dist), &objects, &mut out);
} else {
let kind = DroneKind::from_key(kind).ok_or(
"Тип: shahed, geran3, lancet, gerbera, kh101, kalibr, kh22, zircon, iskander, kinzhal или mix",
"Тип: shahed, geran3, lancet, gerbera, kh101, kalibr, kh22, zircon, iskander, kinzhal, oreshnik или mix",
)?;
self.sim.raid(kind, target, count, dist, &mut out);
}
None
}
["raid"] => {
self.launch_wave(&mut out)?;
None
}
["repair"] => {
let n = self.sim.repair();
self.dirty = true;
Some(format!("Отремонтировано комплексов: {n}; объекты восстановлены"))
}
["clear"] => {
self.sim.clear();
Some("Небо очищено".to_string())
}
["target", "here"] => {
let p = player().ok_or("Нет игрока")?;
self.sim.targets.push(DVec3::new(p.x, p.y, p.z));
self.sim.target_health.push(100.0);
self.dirty = true;
Some(format!("Объект №{} отмечен здесь", self.sim.targets.len()))
}
["targets", "clear"] => {
self.sim.targets.clear();
self.sim.target_health.clear();
self.dirty = true;
Some("Цели убраны".to_string())
}
+42 -6
View File
@@ -111,7 +111,8 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
}
let target = sim.watched(sam);
let mut seen = 0;
for d in sim.drones.iter().filter(|d| d.alive()) {
// Only what its own radar holds.
for d in sim.drones.iter().filter(|d| d.alive() && sam.seen.contains(&d.id)) {
let rel = d.pos - sam.pos;
let flat = (rel.x * rel.x + rel.z * rel.z).sqrt();
if flat > reach * 1.25 {
@@ -133,9 +134,30 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec<Sha
s.push(fill(rx - 1.5, ry - 1.5, 3.0, 3.0, 0xFF40A0FF));
s.push(text(fit(format!("РЛС {} · {}", distance(reach), seen), rr * 2.0 + 4.0), x + 4.0, y + h - 10.0, 0xFF80FF90));
// Its health under the radar: a bar, red when it is low.
if sam.alive() && sam.health < 1.0 {
let bw = rr * 2.0;
let hc = if sam.health < 0.35 { 0xFFFF3030 } else if sam.health < 0.7 { 0xFFFFB030 } else { 0xFF60FF60 };
s.push(fill(x + 4.0, ry + rr + 1.0, bw, 2.0, 0x80000000));
s.push(fill(x + 4.0, ry + rr + 1.0, bw * sam.health as f32, 2.0, hc));
}
// The camera, at the right: the world as the system sees it, thermal.
let cx = rx + rr + 6.0;
let (cy, cw, ch) = (y + 15.0, x + w - 4.0 - cx, h - 28.0);
if !sam.alive() {
// A dead system shows a dead screen.
s.push(fill(cx, cy, cw, ch, 0xFF100606));
let noise = (tick * 2654435761) % 997;
for i in 0..24 {
let nx = cx + ((noise as f32 * (i + 3) as f32 * 13.7) % cw);
let ny = cy + ((noise as f32 * (i + 7) as f32 * 7.3) % ch);
s.push(fill(nx, ny, 3.0, 1.0, 0x60FFFFFF));
}
s.push(text("НЕТ СВЯЗИ", cx + cw / 2.0 - render::text_width("НЕТ СВЯЗИ") / 2.0, cy + ch / 2.0 - 4.0, 0xFFFF4040));
s.push(text(if sam.burning() { "горит" } else { "уничтожен" }, cx, y + h - 10.0, 0xFFFF8060));
return;
}
s.push(fill(cx - 1.0, cy - 1.0, cw + 2.0, ch + 2.0, 0xFF203020));
// Searching: colour by day, night vision at night; tracking: thermal.
let night = horizon_mod_sdk::game::get_clock().is_some_and(|c| (13000..23000).contains(&(c.day_time % 24000)));
@@ -195,13 +217,27 @@ pub fn draw(sim: &Sim, index: usize) -> Vec<Shape> {
}
/// Every system in a grid over the screen.
pub fn grid(sim: &Sim, (gw, gh): (f32, f32)) -> Vec<Shape> {
pub fn grid(sim: &Sim, picked: &[usize], (gw, gh): (f32, f32)) -> Vec<Shape> {
let mut s = Vec::new();
let n = sim.sams.len().min(8);
let n = picked.len().min(8);
s.push(fill(0.0, 0.0, gw, gh, 0xE0050806));
s.push(text(
fit(
format!("КОМАНДНЫЙ ПУНКТ ПВО · комплексов {n} · целей {} · сбито {} · J закрыть", sim.drones.iter().filter(|d| d.alive()).count(), sim.kills),
{
let total = sim.sams.len();
let busy = sim
.sams
.iter()
.filter(|s| !matches!(s.state, SamState::Search | SamState::Hold | SamState::Destroyed))
.count();
let lost = sim.sams.iter().filter(|s| !s.alive()).count();
let shown = if total > n { format!("показано {n} из {total}") } else { format!("комплексов {total}") };
format!(
"КОМАНДНЫЙ ПУНКТ ПВО · {shown} · в работе {busy} · потеряно {lost} · целей {} · сбито {} · J закрыть",
sim.drones.iter().filter(|d| d.alive()).count(),
sim.kills
)
},
gw - 16.0,
),
8.0,
@@ -221,8 +257,8 @@ pub fn grid(sim: &Sim, (gw, gh): (f32, f32)) -> Vec<Shape> {
let (top, gap) = (18.0, 4.0);
let cw = (gw - gap * (cols as f32 + 1.0)) / cols as f32;
let ch = ((gh - top - gap * rows as f32) / rows as f32).min(cw * 0.62);
for i in 0..n {
let (c, r) = (i % cols, i / cols);
for (k, &i) in picked.iter().take(n).enumerate() {
let (c, r) = (k % cols, k / cols);
let x = gap + c as f32 * (cw + gap);
let y = top + r as f32 * (ch + gap);
cell(sim, i, x, y, cw, ch, &mut s);
+16
View File
@@ -55,6 +55,22 @@ pub fn summary(sim: &Sim, air: &[&Drone], player: DVec3) -> Vec<Line> {
));
}
}
if !sim.queue.is_empty() {
lines.push(line(format!("Ещё взлетает: {}", sim.queue.len()), PINK));
}
let hidden = air.iter().filter(|d| !sim.sams.is_empty() && !sim.tracked(d.id)).count();
if hidden > 0 {
lines.push(line(format!("Вне видимости РЛС: {hidden}"), GREY));
}
if !sim.target_health.is_empty() {
let list: Vec<String> = sim.target_health.iter().map(|h| format!("{h:.0}%")).collect();
let worst = sim.target_health.iter().copied().fold(100.0, f64::min);
lines.push(line(format!("Объекты: {}", list.join(" ")), if worst < 50.0 { RED } else { GREEN }));
}
let lost = sim.sams.iter().filter(|s| !s.alive()).count();
if lost > 0 {
lines.push(line(format!("Потеряно комплексов: {lost}"), RED));
}
if !sim.missiles.is_empty() {
lines.push(line(format!("Перехватчиков в полёте: {}", sim.missiles.len()), YELLOW));
}
+3 -1
View File
@@ -108,7 +108,9 @@ pub fn draw(sim: &Sim, player: DVec3, yaw: f32) -> Vec<Shape> {
}
}
let mut far = 0;
for d in &sim.drones {
// The air picture is what the systems' radars hold; with none deployed, everything.
let any = !sim.sams.is_empty();
for d in sim.drones.iter().filter(|d| !any || !d.alive() || sim.tracked(d.id)) {
match scope(d.pos) {
Some((x, y, bearing)) => {
let a = fade(bearing);
+197
View File
@@ -0,0 +1,197 @@
//! Air defence can be hit too: a blast near a system damages it (it turns
//! slower, sees less, hits worse, smokes, then burns), a destroyed one leaves
//! a burning wreck and its magazine cooks off — the more missiles or shells
//! were left in it, the bigger the blast and the longer the secondary ones.
//! Marked objects take the same blasts.
use super::*;
/// By blast power (as `explode` grades it): how far it reaches a vehicle, and how hard it hits one at the centre.
const REACH: [f64; 5] = [4.0, 7.0, 12.0, 18.0, 26.0];
const HIT: [f64; 5] = [0.2, 0.45, 0.85, 1.25, 1.7];
/// Health points an object loses at the centre of a blast.
const OBJECT_HIT: [f64; 5] = [2.0, 6.0, 14.0, 26.0, 40.0];
impl MissileKind {
/// The explosive a missile left in a burning launcher adds (TNT).
fn charge(self) -> f64 {
match self {
MissileKind::Pac3 => 0.8,
MissileKind::M57e6 => 0.45,
MissileKind::M48n6 => 1.8,
MissileKind::M77n6 => 2.2,
}
}
}
impl Sim {
/// A blast of `power` (0 to 4) at `pos`: the systems and objects round it take damage.
pub(super) fn blast_damage(&mut self, pos: DVec3, power: usize, out: &mut Out) {
let (reach, hit) = (REACH[power], HIT[power]);
let mut destroyed = Vec::new();
for (i, sam) in self.sams.iter_mut().enumerate() {
if !sam.alive() {
continue;
}
// The vehicle is a few blocks long: measured from its hull.
let d = (sam.pos.distance(pos) - 2.5).max(0.0);
if d >= reach {
continue;
}
let k = 1.0 - d / reach;
let before = sam.health;
sam.health -= hit * k * k * if d < 1.0 { 1.5 } else { 1.0 };
if sam.health <= 0.0 {
destroyed.push(i);
} else if before >= 0.5 && sam.health < 0.5 {
out.messages.push(format!("{} №{} повреждён", sam.kind.name(), i + 1));
}
}
for i in destroyed {
self.destroy(i, out);
}
for (i, t) in self.targets.iter().enumerate() {
let d = t.distance(pos);
let r = reach * 1.6;
if d < r {
if let Some(h) = self.target_health.get_mut(i) {
let before = *h;
*h = (*h - OBJECT_HIT[power] * (1.0 - d / r)).max(0.0);
if before > 0.0 && *h <= 0.0 {
out.messages.push(format!("ОБЪЕКТ №{} УНИЧТОЖЕН", i + 1));
}
}
}
}
}
/// System `i` destroyed: its magazine goes up, the wreck burns.
fn destroy(&mut self, i: usize, out: &mut Out) {
let now = self.tick;
let sam = &mut self.sams[i];
sam.health = 0.0;
sam.burn = 900;
sam.state = SamState::Destroyed;
sam.target = None;
sam.gun_target = None;
sam.reloading = 0;
let spec = sam.kind.spec();
let missiles = sam.missiles;
let bursts = sam.bursts;
sam.missiles = 0;
sam.bursts = 0;
let pos = sam.pos + DVec3::Y;
out.messages.push(format!("{} №{} УНИЧТОЖЕН", sam.kind.name(), i + 1));
let charge = spec.missile.as_ref().map_or(0.0, |m| m.kind.charge() * missiles as f64) + bursts as f64 / 60.0;
// The vehicle's own fuel and the first of its load at once, then the rest cooking off.
let first = (1.0 + charge * 0.6).round().clamp(1.0, 8.0) as u32;
self.later.push((now + 2, pos, first, false));
for k in 0..missiles {
let when = now + 15 + (k as u64) * 12 + (self.rng.f() * 25.0) as u64;
let at = pos + DVec3::new(self.rng.s() * 3.0, self.rng.f() * 2.0, self.rng.s() * 3.0);
let tnt = if charge > 4.0 && self.rng.chance(0.4) { 2 } else { 1 };
self.later.push((when, at, tnt, true));
}
// Shells pop in strings.
for k in 0..(bursts / 12).min(14) {
let when = now + 10 + (k as u64) * 6 + (self.rng.f() * 8.0) as u64;
let at = pos + DVec3::new(self.rng.s() * 2.0, self.rng.f() * 1.5, self.rng.s() * 2.0);
self.later.push((when, at, 0, true));
}
}
/// The blasts whose time has come.
pub(super) fn step_later(&mut self, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
let now = self.tick;
let due: Vec<_> = self.later.iter().filter(|l| l.0 <= now).copied().collect();
self.later.retain(|l| l.0 > now);
for (_, pos, tnt, small) in due {
self.explode(pos, tnt, small, ground, player, out);
if small {
// Something flies out of a burning launcher.
out.particles("minecraft:lava", pos, 0.8, DVec3::new(0.0, 0.3, 0.0), 0.3, 12);
out.particles("minecraft:firework", pos, 0.5, DVec3::new(0.0, 0.2, 0.0), 0.25, 10);
}
}
}
/// Damaged systems smoke, wrecks burn.
pub(super) fn step_wrecks(&mut self, out: &mut Out) {
let tick = self.tick;
for sam in &mut self.sams {
let top = sam.pos + DVec3::Y * (1.5 * sam.kind.spec().scale);
if !sam.alive() {
if sam.burn > 0 {
sam.burn -= 1;
out.particles("minecraft:flame", top, 1.0, DVec3::new(0.0, 0.05, 0.0), 0.03, 3);
out.particles("minecraft:large_smoke", top, 0.8, DVec3::new(0.0, 0.12, 0.0), 0.03, 2);
if tick % 8 == 0 {
out.particles("minecraft:campfire_cosy_smoke", top, 1.0, DVec3::new(0.0, 0.07, 0.0), 0.01, 1);
}
if tick % 40 == 0 {
out.sound("minecraft:block.fire.ambient", top, 3.0, 0.7);
}
} else if tick % 12 == 0 {
out.particles("minecraft:campfire_signal_smoke", top, 0.6, DVec3::new(0.0, 0.05, 0.0), 0.01, 1);
}
} else if sam.health < 0.7 {
let every = if sam.health < 0.35 { 2 } else { 5 };
if tick % every == 0 {
out.particles("minecraft:large_smoke", top, 0.4, DVec3::new(0.0, 0.08, 0.0), 0.02, 1);
}
if sam.health < 0.35 && tick % 3 == 0 {
out.particles("minecraft:flame", top, 0.3, DVec3::ZERO, 0.01, 1);
}
}
}
}
}
impl Sam {
/// Its wreck still burns.
pub fn burning(&self) -> bool {
self.burn > 0
}
}
impl Sim {
/// Repairs every system (wrecks rebuilt, magazines full) and object.
pub fn repair(&mut self) -> u32 {
let mut n = 0;
for sam in &mut self.sams {
if sam.health < 1.0 {
n += 1;
}
let spec = sam.kind.spec();
sam.health = 1.0;
sam.burn = 0;
sam.state = SamState::Search;
sam.reloading = 0;
sam.missiles = spec.missile.as_ref().map_or(0, |m| m.magazine);
sam.bursts = spec.gun.as_ref().map_or(0, |g| g.bursts);
}
for h in &mut self.target_health {
*h = 100.0;
}
n
}
/// A wreck: the hull sunk and turned, the launcher or turret thrown down beside it.
pub(super) fn draw_wreck(&self, i: usize, out: &mut Out) {
let sam = &self.sams[i];
let s = sam.kind.spec().scale;
let tilt = DQuat::from_rotation_y(sam.heading) * DQuat::from_rotation_z(0.12) * DQuat::from_rotation_x(-0.06);
let hull = sam.pos + DVec3::Y * (0.5 * s - 0.35);
let side = DQuat::from_rotation_y(sam.heading) * DVec3::new(1.8 * s, 0.0, 0.6 * s);
let thrown = DQuat::from_rotation_y(sam.heading + 1.1) * DQuat::from_rotation_z(1.2);
let (body, part) = match sam.kind {
SamKind::Patriot => ("airdef:patriot_trailer", "airdef:patriot_launcher"),
SamKind::Gepard => ("airdef:gepard_hull", "airdef:gepard_turret"),
SamKind::Pantsir => ("airdef:pantsir_truck", "airdef:pantsir_turret"),
SamKind::S400 => ("airdef:s400_chassis", "airdef:s400_tubes"),
SamKind::S500 => ("airdef:s500_chassis", "airdef:s500_tubes"),
};
out.model(sam.id, body, hull, tilt, s, false);
out.model(sam.id + 1, part, sam.pos + side + DVec3::Y * 0.4 * s, thrown, s, false);
}
}
@@ -9,6 +9,11 @@
use glam::{DQuat, DVec3};
use std::collections::HashMap;
mod damage;
mod raid;
mod sight;
pub use raid::{Approach, Aim, RaidOrder};
pub const TAU: f64 = std::f64::consts::TAU;
const HALF_PI: f64 = std::f64::consts::FRAC_PI_2;
@@ -158,6 +163,7 @@ fn angle_diff(from: f64, to: f64) -> f64 {
pub struct Ground {
known: HashMap<(i32, i32), (i32, u64)>,
wanted: Vec<(i32, i32)>,
asked: std::collections::HashSet<(i32, i32)>,
}
impl Ground {
@@ -167,13 +173,13 @@ impl Ground {
let key = (p.x.floor() as i32, p.z.floor() as i32);
match self.known.get(&key) {
Some(&(y, when)) => {
if now.saturating_sub(when) > 200 && !self.wanted.contains(&key) {
if now.saturating_sub(when) > 200 && self.wanted.len() < 256 && self.asked.insert(key) {
self.wanted.push(key);
}
(y > -64).then_some(f64::from(y))
}
None => {
if self.wanted.len() < 256 && !self.wanted.contains(&key) {
if self.wanted.len() < 256 && self.asked.insert(key) {
self.wanted.push(key);
}
None
@@ -184,11 +190,12 @@ impl Ground {
for (x, z, y) in answers {
self.known.insert((x, z), (y, now));
}
if self.known.len() > 20_000 {
self.known.retain(|_, (_, when)| now - *when < 400);
if self.known.len() > 300_000 {
self.known.retain(|_, (_, when)| now - *when < 2000);
}
}
pub fn take_wanted(&mut self) -> Vec<(i32, i32)> {
self.asked.clear();
std::mem::take(&mut self.wanted)
}
/// Explosions change the land: forget what was known round them.
@@ -272,7 +279,7 @@ pub fn roles_text(mask: u8) -> String {
/// Ballistic flight's gravity, blocks a tick².
const GRAVITY: f64 = 0.05;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum DroneKind {
Shahed,
Geran3,
@@ -586,6 +593,25 @@ impl DroneKind {
pub fn from_key(key: &str) -> Option<Self> {
Self::ALL.into_iter().find(|k| k.spec().key == key)
}
/// Its radar cross-section, a Shahed's 0.3: radars see it from as far as its fourth root allows.
pub fn rcs(self) -> f64 {
match self {
DroneKind::Shahed => 0.3,
DroneKind::Geran3 => 0.4,
DroneKind::Lancet => 0.08,
// Corner reflectors make the decoy look as big as a Shahed.
DroneKind::Gerbera => 0.4,
DroneKind::Kh101 => 0.05,
DroneKind::Kalibr => 0.15,
DroneKind::Kh22 => 1.0,
DroneKind::Zircon => 0.4,
DroneKind::Iskander => 0.6,
DroneKind::Kinzhal => 0.5,
DroneKind::Oreshnik => 2.0,
DroneKind::OreshnikBlock => 0.4,
DroneKind::OreshnikSub => 0.08,
}
}
}
/// Height over the target where the Oreshnik's blocks release their submunitions.
@@ -613,6 +639,10 @@ pub struct Drone {
age: u32,
/// Interceptors on their way to it.
pub engaged: u32,
/// Points it flies by on its way (a planned raid), the next first.
route: Vec<DVec3>,
/// Hugs the land all the way, under the radars.
low: bool,
}
impl Drone {
@@ -856,6 +886,7 @@ pub enum SamState {
Fire,
Reload,
Hold,
Destroyed,
}
impl SamState {
@@ -869,6 +900,7 @@ impl SamState {
SamState::Fire => "ОГОНЬ",
SamState::Reload => "ПЕРЕЗАРЯДКА",
SamState::Hold => "ОГОНЬ ЗАПРЕЩЁН",
SamState::Destroyed => "УНИЧТОЖЕН",
}
}
pub fn color(self) -> u32 {
@@ -880,6 +912,7 @@ impl SamState {
SamState::Launch | SamState::Fire => 0xFFFFFF,
SamState::Reload => 0x80A0FF,
SamState::Hold => 0xA0A0A0,
SamState::Destroyed => 0xFF2020,
}
}
}
@@ -911,6 +944,12 @@ pub struct Sam {
pub fired: u32,
/// The classes of target it engages (`Class::bit`s).
pub roles: u8,
/// 1 whole, 0 destroyed: a damaged system turns slower, sees less and hits worse.
pub health: f64,
/// Ticks its wreck still burns.
burn: u32,
/// The drones its radar holds this tick.
pub seen: Vec<u32>,
}
impl Sam {
@@ -938,8 +977,18 @@ impl Sam {
roles: spec.roles,
state: SamState::Search,
launched: 0,
health: 1.0,
burn: 0,
seen: Vec::new(),
}
}
pub fn alive(&self) -> bool {
self.health > 0.0
}
/// How well it still works: turning, aiming, its radar's reach.
fn fitness(&self) -> f64 {
0.45 + 0.55 * self.health.clamp(0.0, 1.0)
}
fn base(&self) -> DQuat {
DQuat::from_rotation_y(self.heading)
}
@@ -998,6 +1047,12 @@ impl Sam {
pub fn status(&self) -> String {
let spec = self.kind.spec();
let mut text = spec.name.to_string();
if !self.alive() {
return text + " УНИЧТОЖЕН";
}
if self.health < 1.0 {
text += &format!(" ({:.0}%)", self.health * 100.0);
}
if self.reloading > 0 {
text += &format!(" перезарядка {}с", self.reloading.div_ceil(20));
} else {
@@ -1047,6 +1102,16 @@ pub struct Sim {
pub shader: bool,
/// Air defence holds fire.
pub hold: bool,
/// What the land hides round each system's radar, by system id.
horizons: HashMap<u32, sight::Horizon>,
/// Blasts to come: (tick, where, TNT, small) — a magazine cooking off.
later: Vec<(u64, DVec3, u32, bool)>,
/// A planned raid's drones waiting for their launch tick.
pub queue: Vec<(u64, Drone)>,
/// Each marked object's health, 0 to 100 (`targets`' order).
pub target_health: Vec<f64>,
/// The raid in progress, for its report.
wave: Option<raid::WaveStats>,
}
/// Ids: objects get multiples of 16, their parts the low bits.
@@ -1071,6 +1136,11 @@ impl Sim {
damage: true,
shader: false,
hold: false,
horizons: HashMap::new(),
later: Vec::new(),
queue: Vec::new(),
target_health: Vec::new(),
wave: None,
}
}
pub fn id(&mut self) -> u32 {
@@ -1115,6 +1185,8 @@ impl Sim {
spin: 0.0,
age: 0,
engaged: 0,
route: Vec::new(),
low: false,
});
self.launched += 1;
}
@@ -1151,16 +1223,23 @@ impl Sim {
self.missiles.clear();
self.fx.clear();
self.blasts.clear();
self.queue.clear();
self.wave = None;
}
/// One game tick.
pub fn step(&mut self, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
self.tick += 1;
self.release_queue();
self.step_drones(ground, player, out);
self.step_later(ground, player, out);
self.update_sight(ground);
self.step_sams(out);
self.step_missiles(out);
self.step_fx(ground, out);
self.draw_targets(out);
self.step_wrecks(out);
self.report_wave(out);
let now = self.tick;
self.blasts.retain(|b| now - b.start < b.life as u64);
}
@@ -1273,9 +1352,20 @@ impl Sim {
}
continue;
}
if d.flight == Flight::Cruise && horizontal(d.target - d.pos).length() < spec.dive {
if d.flight == Flight::Cruise && d.route.len() <= 1 && horizontal(d.target - d.pos).length() < spec.dive {
d.flight = Flight::Dive;
}
// A planned route: the next point, then the next.
// Reached when near (as near as it can turn), or passed: behind it and close.
let radius = (spec.speed / spec.turn.max(0.01)).max(24.0);
while d.route.len() > 1
&& d.route.first().is_some_and(|w| {
let to = horizontal(*w - d.pos);
to.length() < radius * 0.8 || (to.dot(horizontal(d.vel)) < 0.0 && to.length() < radius * 2.5)
})
{
d.route.remove(0);
}
let goal = if d.flight == Flight::Dive {
d.target
} else {
@@ -1286,7 +1376,10 @@ impl Sim {
(Some(g), None) | (None, Some(g)) => g + spec.clearance,
(None, None) => d.target.y + spec.clearance,
};
DVec3::new(d.target.x, (d.target.y + spec.cruise).max(floor), d.target.z)
let to = d.route.first().copied().unwrap_or(d.target);
// Under the radars: as low as the land lets it, all the way.
let height = if d.low { floor.max(d.target.y + 4.0) } else { (d.target.y + spec.cruise).max(floor) };
DVec3::new(to.x, height, to.z)
};
let rate = if d.flight == Flight::Dive { spec.turn * 3.5 } else { spec.turn };
let old = d.vel.normalize_or(DVec3::NEG_Z);
@@ -1330,7 +1423,20 @@ impl Sim {
self.drones.retain(|d| !removed.contains(&d.id));
for (kind, pos, vel, target) in released {
let id = self.id();
self.drones.push(Drone { id, kind, pos, vel, target, flight: Flight::Ballistic, roll: 0.0, spin: 1.0, age: 60, engaged: 0 });
self.drones.push(Drone {
id,
kind,
pos,
vel,
target,
flight: Flight::Ballistic,
roll: 0.0,
spin: 1.0,
age: 60,
engaged: 0,
route: Vec::new(),
low: false,
});
}
for d in &self.drones {
let spec = d.kind.spec();
@@ -1412,6 +1518,7 @@ impl Sim {
out.jolt((1.0 - d / reach) as f32 * strength, [0.8, 0.8, 1.6, 2.2, 3.0][power]);
}
}
self.blast_damage(pos, power, out);
if self.damage && tnt > 0 {
for i in 0..tnt {
out.commands.push(format!(
@@ -1471,7 +1578,9 @@ impl Sim {
fn step_sams(&mut self, out: &mut Out) {
if self.hold {
for i in 0..self.sams.len() {
self.sams[i].state = SamState::Hold;
if self.sams[i].alive() {
self.sams[i].state = SamState::Hold;
}
self.draw_sam(i, out);
}
return;
@@ -1481,6 +1590,14 @@ impl Sim {
let mut tracers: Vec<(u32, DVec3, DVec3, u32)> = Vec::new();
for i in 0..self.sams.len() {
let spec = self.sams[i].kind.spec();
if !self.sams[i].alive() {
let sam = &mut self.sams[i];
sam.state = SamState::Destroyed;
sam.target = None;
sam.gun_target = None;
continue;
}
let fit = self.sams[i].fitness();
{
let sam = &mut self.sams[i];
sam.cooldown = sam.cooldown.saturating_sub(1);
@@ -1500,7 +1617,8 @@ impl Sim {
let pos = self.sams[i].pos;
let me = self.sams[i].id;
let roles = self.sams[i].roles;
let allowed = |d: &Drone| d.alive() && roles & d.kind.spec().class.bit() != 0;
let seen = self.sams[i].seen.clone();
let allowed = |d: &Drone| d.alive() && roles & d.kind.spec().class.bit() != 0 && seen.contains(&d.id);
// Interceptors a target has or will have: in flight, and other systems' launchers on it.
let claimed = |d: &Drone| {
d.engaged + self.sams.iter().filter(|s| s.id != me && s.target == Some(d.id)).count() as u32
@@ -1542,6 +1660,10 @@ impl Sim {
let aim = sam.gun_target.or(sam.target).and_then(|t| self.drones.iter().find(|d| d.id == t));
sam.launched = sam.launched.saturating_sub(1);
let Some(aim) = aim else {
// Out of missiles and nothing to shoot: reload now, guns or not.
if spec.missile.is_some() && sam.missiles == 0 && sam.reloading == 0 {
sam.reloading = spec.reload;
}
sam.state = if sam.reloading > 0 { SamState::Reload } else { SamState::Search };
sam.yaw = slew(sam.yaw, sam.heading, 0.03);
sam.pitch += (spec.rest_pitch - sam.pitch) * 0.05;
@@ -1554,9 +1676,10 @@ impl Sim {
let want_yaw = heading_of(to);
let want_pitch = (to.y / to.length().max(0.01)).asin().clamp(-0.1, 1.45);
let (yaw_rate, pitch_rate) = spec.gun.as_ref().map_or((0.05, 0.05), |g| g.slew);
let (yaw_rate, pitch_rate) = (yaw_rate * fit, pitch_rate * fit);
match sam.kind {
SamKind::S400 | SamKind::S500 => {} // vertical launch: no aiming
SamKind::Patriot => sam.yaw = slew(sam.yaw, want_yaw, 0.12),
SamKind::Patriot => sam.yaw = slew(sam.yaw, want_yaw, 0.12 * fit),
_ => {
sam.yaw = slew(sam.yaw, want_yaw, yaw_rate);
sam.pitch = slew(sam.pitch, want_pitch, pitch_rate);
@@ -1612,7 +1735,7 @@ impl Sim {
let event = if sam.kind == SamKind::Pantsir { "airdef:gun.pantsir" } else { "airdef:gun.gepard" };
out.sound(event, mount, 1.0, 0.95 + self.rng.f() as f32 * 0.1);
}
let p = gun.p / t.kind.spec().stealth * (1.0 - dist / (gun.range * 1.3)).max(0.35);
let p = gun.p * fit / t.kind.spec().stealth * (1.0 - dist / (gun.range * 1.3)).max(0.35);
if self.rng.chance(p) {
gun_hits.push((gt, sam.id));
} else {
@@ -1684,6 +1807,10 @@ impl Sim {
}
fn draw_sam(&mut self, i: usize, out: &mut Out) {
if !self.sams[i].alive() {
self.draw_wreck(i, out);
return;
}
let sam = &self.sams[i];
let base = sam.base();
let s = sam.scale();
@@ -1746,6 +1873,7 @@ impl Sim {
fn step_missiles(&mut self, out: &mut Out) {
let mut done: Vec<(u32, Option<u32>, bool, u32)> = Vec::new(); // (missile, target, kill, sam)
let sams_fit: HashMap<u32, f64> = self.sams.iter().map(|s| (s.id, s.fitness())).collect();
for m in &mut self.missiles {
m.age += 1;
let spec = m.kind.spec();
@@ -1781,7 +1909,8 @@ impl Sim {
if (rel0 + delta * k).length() < spec.fuse {
// A target faster than the interceptor is hard to hit.
let ratio = (spec.speed / t.vel.length().max(0.1)).min(1.0).powf(1.5);
let kill = self.rng.chance(spec.pk * ratio / t.kind.spec().stealth.sqrt());
let fit = sams_fit.get(&m.sam).copied().unwrap_or(1.0);
let kill = self.rng.chance(spec.pk * fit * ratio / t.kind.spec().stealth.sqrt());
done.push((m.id, Some(t.id), kill, m.sam));
continue;
}
+435
View File
@@ -0,0 +1,435 @@
//! Raids to order: what flies (kinds and numbers), from where, and at what.
//! The smart enemy plans: it knows where the systems are and what they see,
//! sends decoys first to draw their missiles, sends Lancets at the guns and
//! fast missiles at the long-range systems, routes its drones round the
//! systems' reach and low under their radars (through the dead zones and
//! behind hills), and times every launch so that all of it arrives at once.
use super::*;
use std::collections::BinaryHeap;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Approach {
/// From one sector, ±20°.
Sector,
/// From two sectors far apart.
TwoSectors,
/// From every side.
AllSides,
/// From one sector, a kind at a time, 15 s apart.
Waves,
}
impl Approach {
pub const ALL: [Approach; 4] = [Approach::Sector, Approach::TwoSectors, Approach::AllSides, Approach::Waves];
pub fn name(self) -> &'static str {
match self {
Approach::Sector => "один сектор",
Approach::TwoSectors => "два сектора",
Approach::AllSides => "со всех сторон",
Approach::Waves => "волнами",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Aim {
/// The marked objects.
Objects,
/// The objects, and a third of the drones at air defence.
ObjectsAndSams,
/// The planner chooses targets and routes, and times the strike.
Smart,
}
impl Aim {
pub const ALL: [Aim; 3] = [Aim::Objects, Aim::ObjectsAndSams, Aim::Smart];
pub fn name(self) -> &'static str {
match self {
Aim::Objects => "только объекты",
Aim::ObjectsAndSams => "объекты и ПВО",
Aim::Smart => "умный противник",
}
}
}
pub struct RaidOrder {
pub kinds: Vec<(DroneKind, u32)>,
pub approach: Approach,
/// How far out the drones start (ballistic missiles from their own range).
pub dist: f64,
pub aim: Aim,
}
/// The raid in progress: the counts at its start, for the report.
pub(super) struct WaveStats {
kills: u32,
hits: u32,
launched: u32,
fired: u32,
sams: usize,
objects: f64,
size: u32,
}
/// The planner's grid: cells this big, at most this many a side.
const CELL: f64 = 16.0;
const CELLS: i32 = 120;
/// The planner's grid over a raid: its corner, its cells' size and how many a side.
struct Grid {
min: DVec3,
cell: f64,
size: i32,
}
impl Grid {
fn index(&self, p: DVec3) -> (i32, i32) {
let n = self.size;
((((p.x - self.min.x) / self.cell) as i32).clamp(0, n - 1), (((p.z - self.min.z) / self.cell) as i32).clamp(0, n - 1))
}
fn centre(&self, (i, j): (i32, i32), y: f64) -> DVec3 {
DVec3::new(self.min.x + (i as f64 + 0.5) * self.cell, y, self.min.z + (j as f64 + 0.5) * self.cell)
}
}
/// The cheapest way over `grid` from `from` to `to` by its prices (A*): points along it, `to` last.
fn plan_route(grid: &Grid, prices: &[f32], from: DVec3, to: DVec3) -> Vec<DVec3> {
let n = grid.size;
let at = |(i, j): (i32, i32)| (i * n + j) as usize;
let start = grid.index(from);
let goal = grid.index(to);
let mut best = vec![f32::INFINITY; (n * n) as usize];
let mut came = vec![u32::MAX; (n * n) as usize];
let mut open = BinaryHeap::new();
best[at(start)] = 0.0;
open.push(Open(0.0, start));
let h = |(i, j): (i32, i32)| (((i - goal.0) as f64).powi(2) + ((j - goal.1) as f64).powi(2)).sqrt();
while let Some(Open(f, c)) = open.pop() {
if c == goal {
break;
}
let g = best[at(c)];
// A stale entry: this cell was reached cheaper since.
if f > f64::from(g) + h(c) + 1e-3 {
continue;
}
for (di, dj) in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)] {
let nb = (c.0 + di, c.1 + dj);
if nb.0 < 0 || nb.1 < 0 || nb.0 >= n || nb.1 >= n {
continue;
}
let len = if di != 0 && dj != 0 { std::f32::consts::SQRT_2 } else { 1.0 };
// The target's own cell is where it must go, whatever covers it.
let price = if nb == goal { len } else { len * prices[at(nb)] };
let ng = g + price;
if ng < best[at(nb)] {
best[at(nb)] = ng;
came[at(nb)] = at(c) as u32;
open.push(Open(f64::from(ng) + h(nb), nb));
}
}
}
if came[at(goal)] == u32::MAX {
return vec![to];
}
let mut cells = vec![goal];
let mut c = at(goal);
while came[c] != u32::MAX && c != at(start) {
c = came[c] as usize;
cells.push(((c as i32) / n, (c as i32) % n));
}
cells.reverse();
let mut route: Vec<DVec3> = cells.iter().skip(2).step_by(3).map(|&c| grid.centre(c, to.y)).collect();
route.retain(|p| horizontal(*p - to).length() > grid.cell * 2.0);
route.push(to);
route
}
/// A cell in the A* queue: the cheapest first.
#[derive(PartialEq)]
struct Open(f64, (i32, i32));
impl Eq for Open {}
impl Ord for Open {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other.0.total_cmp(&self.0)
}
}
impl PartialOrd for Open {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Sim {
/// Launches a raid on `objects` (at least one point).
pub fn order_raid(&mut self, order: &RaidOrder, objects: &[DVec3], out: &mut Out) -> u32 {
let Some(&centre) = objects.first() else { return 0 };
let now = self.tick;
let total: u32 = order.kinds.iter().map(|k| k.1).sum();
if total == 0 {
return 0;
}
let bearing = self.rng.f() * TAU;
let second = bearing + std::f64::consts::PI * (0.6 + self.rng.f() * 0.6);
let smart = order.aim == Aim::Smart;
// (drone, its flight time to the target in ticks, how early it should arrive, its wave's delay)
let mut planned: Vec<(Drone, f64, f64, f64)> = Vec::new();
// One grid over the whole raid; each kind's prices are worked out once, routes are shared
// by the drones of a kind going from about the same bearing to the same target.
let span = order.dist + 450.0;
let cell = CELL.max(2.0 * span / CELLS as f64);
let grid = Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 };
let mut prices: HashMap<DroneKind, Vec<f32>> = HashMap::new();
let mut routes: HashMap<(DroneKind, i32, i32, i32), Vec<DVec3>> = HashMap::new();
for (group, &(kind, count)) in order.kinds.iter().enumerate() {
let spec = kind.spec();
for _ in 0..count {
let a = match order.approach {
Approach::Sector | Approach::Waves => bearing + self.rng.s() * 0.35,
Approach::TwoSectors => (if self.rng.chance(0.5) { bearing } else { second }) + self.rng.s() * 0.3,
Approach::AllSides => self.rng.f() * TAU,
};
let object = objects[(self.rng.f() * objects.len() as f64) as usize % objects.len()];
let (target, at_sam) = self.choose_target(kind, object, order.aim);
let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0);
let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0;
let height = if spec.ballistic.is_some() { 10.0 } else if spec.cruise > 0.0 { spec.cruise } else { 25.0 };
let from = centre + DVec3::new(a.sin() * dist, height + self.rng.s() * 6.0, a.cos() * dist);
let mut d = self.make_drone(kind, from, horizontal(aim - from), aim);
let mut path = from.distance(aim);
if smart && spec.ballistic.is_none() && !spec.decoy && !at_sam.is_some_and(|_| kind == DroneKind::Lancet) {
let key = (kind, (a.rem_euclid(TAU) / 0.35) as i32, (target.x / 24.0) as i32, (target.z / 24.0) as i32);
let route = match routes.get(&key) {
Some(r) => r.clone(),
None => {
if !prices.contains_key(&kind) {
let p = self.price_grid(&grid, kind);
prices.insert(kind, p);
}
let r = plan_route(&grid, &prices[&kind], from, aim);
routes.insert(key, r.clone());
r
}
};
// Each drone a little off the shared line.
d.route = route.iter().map(|p| *p + DVec3::new(self.rng.s() * 6.0, 0.0, self.rng.s() * 6.0)).collect();
d.low = matches!(spec.class, Class::Drone | Class::Jet | Class::Cruise);
path = route_length(from, &d.route, aim);
}
let time = match d.flight {
Flight::Ballistic => {
let flat = horizontal(aim - from).length();
(flat / spec.speed).max(30.0)
}
_ => path / spec.speed,
};
// Decoys come 15 s ahead, the rest together; "waves" one kind after another.
let early = if spec.decoy { 300.0 } else { 0.0 };
let wave_gap = if order.approach == Approach::Waves { group as f64 * 300.0 } else { 0.0 };
planned.push((d, time, early, wave_gap));
}
}
// Timing: smart raids arrive at once; others leave at once (a moment apart).
let arrive = planned.iter().map(|(_, t, e, g)| t + e - g).fold(0.0, f64::max);
for (d, time, early, gap) in planned {
let wait = if smart { arrive - (early - gap) - time } else { gap + self.rng.f() * 40.0 };
self.queue.push((now + wait.clamp(0.0, 2400.0) as u64, d));
}
self.wave = Some(WaveStats {
kills: self.kills,
hits: self.hits,
launched: self.launched,
fired: self.sams.iter().map(|s| s.fired).sum(),
sams: self.sams.iter().filter(|s| s.alive()).count(),
objects: self.target_health.iter().sum(),
size: total,
});
let what = if smart { "умный противник" } else { order.approach.name() };
out.messages.push(format!("ВОЗДУШНАЯ ТРЕВОГА: налёт, {total} целей ({what})"));
out.sound("minecraft:event.raid.horn", centre, 64.0, 1.0);
total
}
/// A drone ready to fly from `from`, not yet in the sky.
pub(super) fn make_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) -> Drone {
let id = self.id();
let spec = kind.spec();
let (vel, flight) = if spec.ballistic.is_some() {
let flat = horizontal(target - from);
let time = (flat.length() / spec.speed).max(30.0);
let up = (target.y - from.y + 0.5 * GRAVITY * time * time) / time;
(flat / time + DVec3::Y * up, Flight::Ballistic)
} else {
(dir.normalize_or(DVec3::NEG_Z) * spec.speed, Flight::Cruise)
};
Drone {
id,
kind,
pos: from,
vel,
target,
flight,
roll: 0.0,
spin: 0.0,
age: 0,
engaged: 0,
route: Vec::new(),
low: false,
}
}
/// What a drone goes for: an object, or (by its kind and the raid's aim) a system. Returns the
/// point and the system's id.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim) -> (DVec3, Option<u32>) {
let alive: Vec<&Sam> = self.sams.iter().filter(|s| s.alive()).collect();
if alive.is_empty() || kind.spec().decoy || aim == Aim::Objects {
return (object, None);
}
let pick = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
(!list.is_empty()).then(|| {
let s = list[(r * list.len() as f64) as usize % list.len()];
(s.pos, s.id)
})
};
let r = self.rng.f();
let roll = self.rng.f();
if aim == Aim::ObjectsAndSams {
return if roll < 0.33 { pick(&alive, r).map_or((object, None), |(p, id)| (p, Some(id))) } else { (object, None) };
}
// Smart: each kind at what it is good against.
let guns: Vec<&Sam> = alive.iter().copied().filter(|s| matches!(s.kind, SamKind::Gepard | SamKind::Pantsir)).collect();
let long: Vec<&Sam> = alive.iter().copied().filter(|s| matches!(s.kind, SamKind::S400 | SamKind::S500 | SamKind::Patriot)).collect();
let choice = match kind {
DroneKind::Lancet if roll < 0.75 => pick(&guns, r).or_else(|| pick(&alive, r)),
DroneKind::Kh22 | DroneKind::Zircon if roll < 0.45 => pick(&long, r),
DroneKind::Iskander | DroneKind::Kinzhal if roll < 0.3 => pick(&long, r),
DroneKind::Shahed | DroneKind::Geran3 if roll < 0.2 => pick(&alive, r),
_ => None,
};
choice.map_or((object, None), |(p, id)| (p, Some(id)))
}
/// The price of each cell of `grid` for this kind flying low: 1, and much more where a
/// system sees it there (its radar's reach for it, the land) and can shoot it.
fn price_grid(&self, grid: &Grid, kind: DroneKind) -> Vec<f32> {
let spec = kind.spec();
let height = spec.clearance.max(6.0);
let n = grid.size;
let mut prices = vec![1.0f32; (n * n) as usize];
for s in self.sams.iter().filter(|s| s.alive() && s.roles & spec.class.bit() != 0) {
let sp = s.kind.spec();
let (lo, hi) = sp.missile.as_ref().map_or((0.0, 0.0), |m| (m.min, m.max));
let gun = sp.gun.as_ref().map_or(0.0, |g| g.range);
let radar = sight::reach(s, kind, height);
let far = hi.max(gun).min(radar);
let at = sight::antenna(s);
let horizon = self.horizons.get(&s.id);
// Only the cells round it.
let (ci, cj) = grid.index(s.pos);
let r = (far / grid.cell).ceil() as i32 + 1;
for i in (ci - r).max(0)..=(ci + r).min(n - 1) {
for j in (cj - r).max(0)..=(cj + r).min(n - 1) {
let p = grid.centre((i, j), s.pos.y + height);
let d = horizontal(p - s.pos).length();
if d > far {
continue;
}
let missile = (lo..hi).contains(&d);
if !(missile || d < gun) {
continue;
}
if horizon.is_some_and(|h| h.hides(at, p)) {
continue;
}
prices[(i * n + j) as usize] += if missile { 30.0 } else { 18.0 };
}
}
}
prices
}
/// A planned raid's drones take off when their time comes.
pub(super) fn release_queue(&mut self) {
let now = self.tick;
if self.queue.iter().all(|q| q.0 > now) {
return;
}
let (go, wait): (Vec<_>, Vec<_>) = std::mem::take(&mut self.queue).into_iter().partition(|q| q.0 <= now);
self.queue = wait;
for (_, d) in go {
self.drones.push(d);
self.launched += 1;
}
}
/// When the raid is over: what it cost both sides.
pub(super) fn report_wave(&mut self, out: &mut Out) {
let Some(w) = &self.wave else { return };
if !self.queue.is_empty() || self.drones.iter().any(|d| d.alive()) || !self.missiles.is_empty() || self.tick % 20 != 0 {
return;
}
let kills = self.kills - w.kills;
let through = self.hits - w.hits;
let launched = self.launched - w.launched;
let fired: u32 = self.sams.iter().map(|s| s.fired).sum::<u32>() - w.fired;
let lost = w.sams.saturating_sub(self.sams.iter().filter(|s| s.alive()).count());
let objects = if self.target_health.is_empty() {
String::new()
} else {
let now: f64 = self.target_health.iter().sum();
format!(", объекты {:.0}% (потеряно {:.0}%)", now / self.target_health.len() as f64, (w.objects - now) / self.target_health.len() as f64)
};
out.messages.push(format!(
"Налёт окончен: сбито {kills} из {launched} (заявлено {}), прорвалось {through}; ракет ПВО {fired}; потеряно комплексов {lost}{objects}",
w.size
));
self.wave = None;
}
}
fn route_length(from: DVec3, route: &[DVec3], to: DVec3) -> f64 {
let mut at = from;
let mut len = 0.0;
for p in route.iter().chain(std::iter::once(&to)) {
len += horizontal(*p - at).length();
at = *p;
}
len
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_smart_raid_plans_and_flies_in_time() {
let mut sim = Sim::new(7);
for (i, kind) in SamKind::ALL.into_iter().enumerate() {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(-30.0 + 15.0 * i as f64, 70.0, 0.0), 0.0));
}
let mut ground = Ground::default();
let mut out = Out::default();
for _ in 0..30 {
sim.step(&mut ground, None, &mut out);
}
let t = std::time::Instant::now();
let order = RaidOrder {
kinds: vec![(DroneKind::Gerbera, 8), (DroneKind::Shahed, 12), (DroneKind::Kh101, 4), (DroneKind::Iskander, 2)],
approach: Approach::AllSides,
dist: 300.0,
aim: Aim::Smart,
};
sim.order_raid(&order, &[DVec3::new(0.0, 70.0, -40.0)], &mut out);
eprintln!("planned in {:?}, queued {}", t.elapsed(), sim.queue.len());
let t = std::time::Instant::now();
for k in 0..4000 {
let s = std::time::Instant::now();
out = Out::default();
sim.step(&mut ground, None, &mut out);
assert!(s.elapsed().as_millis() < 200, "tick {k} took {:?}", s.elapsed());
}
eprintln!("4000 ticks in {:?}, kills {} hits {}", t.elapsed(), sim.kills, sim.hits);
assert!(sim.queue.is_empty() && !sim.drones.iter().any(|d| d.alive()), "the raid never ended");
}
}
+120
View File
@@ -0,0 +1,120 @@
//! What a system's radar holds. Small targets come up late (the radar's reach
//! goes with the fourth root of their cross-section), low ones later still
//! (over the curve of the earth, scaled to the game's distances), and the land
//! hides what flies behind hills and woods: each system keeps its horizon, the
//! highest the land rises seen from its antenna, ray by ray round it.
use super::*;
/// Rays round a radar, and blocks between the land's samples along them.
const RAYS: usize = 48;
const STEP: f64 = 16.0;
/// The antenna's height over the vehicle's ground.
const MAST: f64 = 5.0;
/// Radio horizon: `HORIZON * (√mast + √height)` blocks.
const HORIZON: f64 = 35.0;
/// Anything this near is seen (and heard), whatever hides it.
const NEAR: f64 = 24.0;
pub(super) struct Horizon {
/// Per ray, per sample out: the steepest rise of the land so far (tan of its elevation).
rays: Vec<Vec<f32>>,
}
impl Horizon {
fn build(antenna: DVec3, reach: f64, ground: &mut Ground, now: u64) -> Self {
let steps = (reach / STEP).ceil() as usize + 1;
let rays = (0..RAYS)
.map(|r| {
let a = r as f64 / RAYS as f64 * TAU;
let dir = DVec3::new(a.sin(), 0.0, a.cos());
let mut top = f32::NEG_INFINITY;
(1..=steps)
.map(|k| {
let d = k as f64 * STEP;
// Unknown land (not loaded, not answered yet) hides nothing.
if let Some(g) = ground.at(antenna + dir * d, now) {
top = top.max(((g - antenna.y) / d) as f32);
}
top
})
.collect()
})
.collect();
Self { rays }
}
/// Whether the land between the antenna and `p` rises over the line to it.
pub(super) fn hides(&self, antenna: DVec3, p: DVec3) -> bool {
let rel = p - antenna;
let flat = (rel.x * rel.x + rel.z * rel.z).sqrt();
let k = (flat / STEP) as usize;
if k == 0 {
return false;
}
let a = rel.x.atan2(rel.z).rem_euclid(TAU);
let ray = &self.rays[(a / TAU * RAYS as f64).round() as usize % RAYS];
let top = ray[(k - 1).min(ray.len() - 1)];
((rel.y / flat) as f32) < top
}
}
/// Where a system's radar is.
pub(super) fn antenna(sam: &Sam) -> DVec3 {
sam.pos + DVec3::Y * MAST
}
/// How far a system's search radar reaches for this kind at `height` over the land:
/// its own reach (worse when damaged) for the target's size, under the radio horizon.
pub(super) fn reach(sam: &Sam, kind: DroneKind, height: f64) -> f64 {
let radar = sam.kind.range() * 1.3 * sam.fitness() * kind.rcs().powf(0.25);
let horizon = HORIZON * (MAST.sqrt() + height.max(0.0).sqrt());
radar.min(horizon).max(NEAR)
}
impl Sim {
/// Rebuilds the systems' horizons in turn, and what each radar holds now.
pub(super) fn update_sight(&mut self, ground: &mut Ground) {
let now = self.tick;
// One horizon every few ticks: the land answers come in over time.
if !self.sams.is_empty() && now % 3 == 0 {
let alive: Vec<usize> = (0..self.sams.len()).filter(|&i| self.sams[i].alive()).collect();
if !alive.is_empty() {
let i = alive[(now / 3) as usize % alive.len()];
let sam = &self.sams[i];
let h = Horizon::build(antenna(sam), sam.kind.range() * 1.3, ground, now);
self.horizons.insert(sam.id, h);
}
}
self.horizons.retain(|id, _| self.sams.iter().any(|s| s.id == *id && s.alive()));
// Each drone's height over the land under it (or over the systems' ground, unknown).
let heights: Vec<Option<f64>> =
self.drones.iter().map(|d| ground.at(d.pos, now).map(|g| d.pos.y - g)).collect();
for sam in &mut self.sams {
sam.seen.clear();
if !sam.alive() {
continue;
}
let at = antenna(sam);
let horizon = self.horizons.get(&sam.id);
for (d, h) in self.drones.iter().zip(&heights) {
if !d.alive() {
continue;
}
let dist = d.pos.distance(at);
let height = h.unwrap_or(d.pos.y - sam.pos.y);
if dist > reach(sam, d.kind, height) {
continue;
}
if dist > NEAR && horizon.is_some_and(|hz| hz.hides(at, d.pos)) {
continue;
}
sam.seen.push(d.id);
}
}
}
/// Whether any system's radar holds this drone (the player's radar shows only those).
pub fn tracked(&self, id: u32) -> bool {
self.sams.iter().any(|s| s.seen.contains(&id))
}
}
+145
View File
@@ -0,0 +1,145 @@
//! The raid the player orders from the menu: how many of each kind, from
//! where, how far out and at what; and ready-made raids to start from.
use crate::sim::{Aim, Approach, DroneKind, RaidOrder};
/// The kinds a raid can have, in the menu's order.
pub const KINDS: [DroneKind; 11] = [
DroneKind::Gerbera,
DroneKind::Shahed,
DroneKind::Geran3,
DroneKind::Lancet,
DroneKind::Kh101,
DroneKind::Kalibr,
DroneKind::Kh22,
DroneKind::Zircon,
DroneKind::Iskander,
DroneKind::Kinzhal,
DroneKind::Oreshnik,
];
/// What a click on a kind's row steps its number through.
const STEPS: [u32; 12] = [0, 1, 2, 3, 4, 6, 8, 10, 15, 20, 30, 40];
pub const DISTANCES: [f64; 4] = [200.0, 300.0, 500.0, 800.0];
pub struct Preset {
pub name: &'static str,
kinds: &'static [(DroneKind, u32)],
approach: Approach,
aim: Aim,
}
pub const PRESETS: [Preset; 7] = [
Preset {
name: "Рой Шахедов",
kinds: &[(DroneKind::Gerbera, 10), (DroneKind::Shahed, 20), (DroneKind::Geran3, 4)],
approach: Approach::TwoSectors,
aim: Aim::Objects,
},
Preset {
name: "Массированный удар",
kinds: &[
(DroneKind::Gerbera, 8),
(DroneKind::Shahed, 12),
(DroneKind::Geran3, 4),
(DroneKind::Kh101, 4),
(DroneKind::Kalibr, 4),
(DroneKind::Kh22, 2),
(DroneKind::Iskander, 2),
],
approach: Approach::AllSides,
aim: Aim::Smart,
},
Preset {
name: "Баллистика",
kinds: &[(DroneKind::Gerbera, 4), (DroneKind::Iskander, 4), (DroneKind::Kinzhal, 2)],
approach: Approach::Sector,
aim: Aim::ObjectsAndSams,
},
Preset {
name: "Гиперзвук",
kinds: &[(DroneKind::Kh22, 3), (DroneKind::Zircon, 4), (DroneKind::Kinzhal, 3)],
approach: Approach::TwoSectors,
aim: Aim::Smart,
},
Preset {
name: "Орешник с прикрытием",
kinds: &[(DroneKind::Gerbera, 6), (DroneKind::Shahed, 10), (DroneKind::Iskander, 2), (DroneKind::Oreshnik, 1)],
approach: Approach::Sector,
aim: Aim::Smart,
},
Preset {
name: "Подавление ПВО",
kinds: &[(DroneKind::Gerbera, 8), (DroneKind::Lancet, 8), (DroneKind::Shahed, 8), (DroneKind::Kh22, 4)],
approach: Approach::AllSides,
aim: Aim::Smart,
},
Preset { name: "Пусто", kinds: &[], approach: Approach::Sector, aim: Aim::Objects },
];
pub struct WaveConfig {
pub counts: [u32; KINDS.len()],
pub approach: Approach,
pub dist: f64,
pub aim: Aim,
/// The last preset applied.
pub preset: usize,
}
impl Default for WaveConfig {
fn default() -> Self {
let mut w = WaveConfig { counts: [0; KINDS.len()], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart, preset: 1 };
w.apply(1);
w
}
}
impl WaveConfig {
pub fn apply(&mut self, preset: usize) {
let p = &PRESETS[preset % PRESETS.len()];
self.preset = preset % PRESETS.len();
self.counts = [0; KINDS.len()];
for &(kind, n) in p.kinds {
if let Some(i) = KINDS.iter().position(|k| *k == kind) {
self.counts[i] = n;
}
}
self.approach = p.approach;
self.aim = p.aim;
}
/// The next number for kind `i`, back to 0 after the last.
pub fn step(&mut self, i: usize) {
let n = self.counts[i];
self.counts[i] = STEPS.iter().copied().find(|&s| s > n).unwrap_or(0);
}
pub fn total(&self) -> u32 {
self.counts.iter().sum()
}
pub fn order(&self) -> RaidOrder {
RaidOrder {
kinds: KINDS.iter().copied().zip(self.counts).filter(|k| k.1 > 0).collect(),
approach: self.approach,
dist: self.dist,
aim: self.aim,
}
}
/// A combined strike of about `n`, as `/airdef wave mix n` orders it.
pub fn mix(n: u32, dist: f64) -> RaidOrder {
let n = n.max(4);
let mut kinds = vec![
(DroneKind::Gerbera, n / 4 + 1),
(DroneKind::Shahed, n / 3 + 1),
(DroneKind::Geran3, n / 8 + 1),
(DroneKind::Kh101, n / 8 + 1),
(DroneKind::Kalibr, n / 10 + 1),
(DroneKind::Kh22, n / 16),
(DroneKind::Zircon, n / 20),
(DroneKind::Iskander, n / 12 + 1),
(DroneKind::Kinzhal, n / 16),
];
if n >= 30 {
kinds.push((DroneKind::Oreshnik, 1));
}
kinds.retain(|k| k.1 > 0);
RaidOrder { kinds, approach: Approach::TwoSectors, dist, aim: Aim::Objects }
}
}
@@ -1,7 +1,7 @@
From 3de7a6875140a107e28563cc44489b55f5794517 Mon Sep 17 00:00:00 2001
From: chexit <chexit@duck.com>
Date: Wed, 28 Oct 2026 12:37:45 +0300
Subject: [PATCH 1/5] Mod API (AirDef fork): world models, client particles,
Subject: [PATCH 1/6] Mod API (AirDef fork): world models, client particles,
sounds, ground heights
render.set-models draws block models with an interpolated pose per id;
@@ -1,7 +1,7 @@
From a6d64e6415bf618539af464e521091e72b72d72f Mon Sep 17 00:00:00 2001
From: chexit <chexit@duck.com>
Date: Wed, 28 Oct 2026 12:39:45 +0300
Subject: [PATCH 2/5] cargo-horizon-mod: report particles and sounds
Subject: [PATCH 2/6] cargo-horizon-mod: report particles and sounds
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
@@ -1,7 +1,7 @@
From ee79b3562feebe51959a01f1585a9e85bd53ccb5 Mon Sep 17 00:00:00 2001
From: chexit <chexit@duck.com>
Date: Wed, 28 Oct 2026 13:33:10 +0300
Subject: [PATCH 3/5] Mod API (AirDef fork): full-screen post pass for mods
Subject: [PATCH 3/6] Mod API (AirDef fork): full-screen post pass for mods
render.set-post compiles a mod's WGSL after a prelude (camera matrices,
time, 256 vec4 of params, the world's colour and depth) and runs it after
@@ -1,7 +1,7 @@
From 2b137dbbedd540daeebc7f5e387847aeb56a1355 Mon Sep 17 00:00:00 2001
From: chexit <chexit@duck.com>
Date: Wed, 28 Oct 2026 22:09:30 +0300
Subject: [PATCH 4/5] Mod models: draw far models as scaled impostors past the
Subject: [PATCH 4/6] Mod models: draw far models as scaled impostors past the
far plane, cull at 4096
---
@@ -1,7 +1,7 @@
From c8ebca6e0af68630e65211844b34d25c5b985c03 Mon Sep 17 00:00:00 2001
From: chexit <chexit@duck.com>
Date: Wed, 28 Oct 2026 22:31:00 +0300
Subject: [PATCH 5/5] Mod cameras: render.set-views draws the world from other
Subject: [PATCH 5/6] Mod cameras: render.set-views draws the world from other
points into pictures that HUD view shapes show (API level 9)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,30 @@
From 8d2261fc4f8072c32e454139cfea7a8c0cd9d664 Mon Sep 17 00:00:00 2001
From: chexit <chexit@duck.com>
Date: Wed, 28 Oct 2026 23:08:21 +0300
Subject: [PATCH 6/6] Mods: more fuel per tick and per event (AirDef plans
raids)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
crates/horizon-mods/src/runtime.rs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs
index 01000dfeb..a551b7376 100644
--- a/crates/horizon-mods/src/runtime.rs
+++ b/crates/horizon-mods/src/runtime.rs
@@ -108,9 +108,9 @@ const MEMORY: usize = 64 << 20;
/// Fuel (about one unit per WebAssembly instruction) per call: a bound on
/// runaway loops, far above the hooks' time budgets.
const FUEL_INIT: u64 = 2_000_000_000;
-const FUEL_TICK: u64 = 50_000_000;
+const FUEL_TICK: u64 = 300_000_000;
const FUEL_FRAME: u64 = 10_000_000;
-const FUEL_EVENT: u64 = 100_000_000;
+const FUEL_EVENT: u64 = 1_000_000_000;
/// Blocks a mod may set per `world.set-blocks` call.
pub const BLOCKS_PER_CALL: usize = 4096;
/// Chat lines a mod may show per call, HUD lines and their length.
--
2.54.0 (Apple Git-157)