From 7612d159633fb9360d634ece898bdcb5a9c6d2a0 Mon Sep 17 00:00:00 2001 From: chexit Date: Wed, 2 Dec 2026 18:22:22 +0300 Subject: [PATCH] Finish AirDef catalog, route, stock and observation fixes Refs #91, #114, #118, #135. Show the latest recorded unit decision in the native card (#153). --- airdef-mod/assets/airdef/lang/en_us.json | 26 +- airdef-mod/assets/airdef/lang/ru_ru.json | 26 +- airdef-mod/generated-manifest.txt | 4 +- airdef-mod/src/battery_view.rs | 2 +- airdef-mod/src/layout.rs | 18 +- airdef-mod/src/lib.rs | 20 +- airdef-mod/src/map.rs | 2 +- airdef-mod/src/monitor.rs | 2 +- airdef-mod/src/post.rs | 7 + airdef-mod/src/recon_view.rs | 10 +- airdef-mod/src/sim/battery.rs | 30 +- airdef-mod/src/sim/catalog.rs | 8 +- airdef-mod/src/sim/catalog_entries.rs | 2 +- airdef-mod/src/sim/damage.rs | 27 +- airdef-mod/src/sim/durable.rs | 12 +- airdef-mod/src/sim/ew.rs | 15 +- airdef-mod/src/sim/logistics.rs | 22 +- airdef-mod/src/sim/mod.rs | 70 +--- airdef-mod/src/sim/observe.rs | 2 + airdef-mod/src/sim/orders.rs | 18 +- airdef-mod/src/sim/recon.rs | 233 ++++++++++- airdef-mod/src/sim/route.rs | 272 +++++++++---- airdef-mod/src/sim/sight.rs | 6 +- airdef-mod/src/sim/smart_tests.rs | 2 + airdef-mod/src/sim/specs_generated.rs | 68 ++++ airdef-mod/src/sim/strike.rs | 29 +- airdef-mod/src/sim/unit_specs_generated.rs | 65 ++++ airdef-mod/src/sim/units.rs | 45 +-- airdef-mod/src/sim/world.rs | 42 +- airdef-mod/src/village.rs | 9 +- .../tests/budgets/wasm_flat_budget.toml | 3 +- catalog/content.json | 367 ------------------ catalog/specs.json | 81 ++++ docs/REPO-MAP.md | 4 +- tools/airdef.py | 2 +- tools/airdef_assets/catalog.py | 75 ++-- tools/gen_catalog.py | 34 +- tools/test_gen_assets.py | 19 +- 38 files changed, 942 insertions(+), 737 deletions(-) diff --git a/airdef-mod/assets/airdef/lang/en_us.json b/airdef-mod/assets/airdef/lang/en_us.json index d8e0612..79ce368 100644 --- a/airdef-mod/assets/airdef/lang/en_us.json +++ b/airdef-mod/assets/airdef/lang/en_us.json @@ -98,13 +98,16 @@ "block.airdef.searchlight_burnt": "Прожектор (остов)", "block.airdef.searchlight_head_burnt": "Голова прожектора (остов)", "item.airdef.designator": "Целеуказатель", + "item.airdef.deploy_s400_launcher": "Развернуть С-400 (пусковая)", + "item.airdef.deploy_s500_launcher": "Развернуть С-500 (пусковая)", + "item.airdef.deploy_radar_search": "Развернуть РЛС обзора", + "item.airdef.deploy_radar_track": "Развернуть РЛС сопровождения", + "item.airdef.deploy_radar_height": "Развернуть мачтовую РЛС", + "item.airdef.mover": "Пульт перемещения", + "item.airdef.flare_gun": "Осветительная ракета", + "item.airdef.remover": "Свернуть ПВО", "item.airdef.launch_shahed": "Пуск: Шахед-136", "item.airdef.launch_geran3": "Пуск: Герань-3", - "item.airdef.deploy_patriot": "Развернуть Patriot", - "item.airdef.deploy_gepard": "Развернуть Гепард", - "item.airdef.deploy_pantsir": "Развернуть Панцирь-С1", - "item.airdef.deploy_s400": "Развернуть С-400", - "item.airdef.deploy_s500": "Развернуть С-500", "item.airdef.launch_lancet": "Пуск: Ланцет-3", "item.airdef.launch_kh101": "Пуск: Х-101", "item.airdef.launch_kalibr": "Пуск: Калибр", @@ -113,6 +116,11 @@ "item.airdef.launch_iskander": "Пуск: Искандер-М", "item.airdef.launch_kinzhal": "Пуск: Кинжал", "item.airdef.launch_oreshnik": "Пуск: Орешник", + "item.airdef.deploy_patriot": "Развернуть Patriot", + "item.airdef.deploy_gepard": "Развернуть Гепард", + "item.airdef.deploy_pantsir": "Развернуть Панцирь-С1", + "item.airdef.deploy_s400": "Развернуть С-400", + "item.airdef.deploy_s500": "Развернуть С-500", "item.airdef.deploy_irist": "Развернуть IRIS-T SLM", "item.airdef.deploy_nasams": "Развернуть NASAMS", "item.airdef.deploy_buk": "Развернуть Бук-М2", @@ -124,14 +132,6 @@ "item.airdef.deploy_ew": "Развернуть станцию РЭБ", "item.airdef.deploy_light": "Развернуть прожектор", "item.airdef.deploy_optical": "Развернуть оптический пост", - "item.airdef.deploy_s400_launcher": "Развернуть С-400 (пусковая)", - "item.airdef.deploy_s500_launcher": "Развернуть С-500 (пусковая)", - "item.airdef.deploy_radar_search": "Развернуть РЛС обзора", - "item.airdef.deploy_radar_track": "Развернуть РЛС сопровождения", - "item.airdef.deploy_radar_height": "Развернуть мачтовую РЛС", - "item.airdef.mover": "Пульт перемещения", - "item.airdef.flare_gun": "Осветительная ракета", - "item.airdef.remover": "Свернуть ПВО", "item.airdef.cam_shahed": "Шахед-136", "item.airdef.cam_geran3": "Герань-3", "item.airdef.cam_lancet": "Ланцет-3", diff --git a/airdef-mod/assets/airdef/lang/ru_ru.json b/airdef-mod/assets/airdef/lang/ru_ru.json index d8e0612..79ce368 100644 --- a/airdef-mod/assets/airdef/lang/ru_ru.json +++ b/airdef-mod/assets/airdef/lang/ru_ru.json @@ -98,13 +98,16 @@ "block.airdef.searchlight_burnt": "Прожектор (остов)", "block.airdef.searchlight_head_burnt": "Голова прожектора (остов)", "item.airdef.designator": "Целеуказатель", + "item.airdef.deploy_s400_launcher": "Развернуть С-400 (пусковая)", + "item.airdef.deploy_s500_launcher": "Развернуть С-500 (пусковая)", + "item.airdef.deploy_radar_search": "Развернуть РЛС обзора", + "item.airdef.deploy_radar_track": "Развернуть РЛС сопровождения", + "item.airdef.deploy_radar_height": "Развернуть мачтовую РЛС", + "item.airdef.mover": "Пульт перемещения", + "item.airdef.flare_gun": "Осветительная ракета", + "item.airdef.remover": "Свернуть ПВО", "item.airdef.launch_shahed": "Пуск: Шахед-136", "item.airdef.launch_geran3": "Пуск: Герань-3", - "item.airdef.deploy_patriot": "Развернуть Patriot", - "item.airdef.deploy_gepard": "Развернуть Гепард", - "item.airdef.deploy_pantsir": "Развернуть Панцирь-С1", - "item.airdef.deploy_s400": "Развернуть С-400", - "item.airdef.deploy_s500": "Развернуть С-500", "item.airdef.launch_lancet": "Пуск: Ланцет-3", "item.airdef.launch_kh101": "Пуск: Х-101", "item.airdef.launch_kalibr": "Пуск: Калибр", @@ -113,6 +116,11 @@ "item.airdef.launch_iskander": "Пуск: Искандер-М", "item.airdef.launch_kinzhal": "Пуск: Кинжал", "item.airdef.launch_oreshnik": "Пуск: Орешник", + "item.airdef.deploy_patriot": "Развернуть Patriot", + "item.airdef.deploy_gepard": "Развернуть Гепард", + "item.airdef.deploy_pantsir": "Развернуть Панцирь-С1", + "item.airdef.deploy_s400": "Развернуть С-400", + "item.airdef.deploy_s500": "Развернуть С-500", "item.airdef.deploy_irist": "Развернуть IRIS-T SLM", "item.airdef.deploy_nasams": "Развернуть NASAMS", "item.airdef.deploy_buk": "Развернуть Бук-М2", @@ -124,14 +132,6 @@ "item.airdef.deploy_ew": "Развернуть станцию РЭБ", "item.airdef.deploy_light": "Развернуть прожектор", "item.airdef.deploy_optical": "Развернуть оптический пост", - "item.airdef.deploy_s400_launcher": "Развернуть С-400 (пусковая)", - "item.airdef.deploy_s500_launcher": "Развернуть С-500 (пусковая)", - "item.airdef.deploy_radar_search": "Развернуть РЛС обзора", - "item.airdef.deploy_radar_track": "Развернуть РЛС сопровождения", - "item.airdef.deploy_radar_height": "Развернуть мачтовую РЛС", - "item.airdef.mover": "Пульт перемещения", - "item.airdef.flare_gun": "Осветительная ракета", - "item.airdef.remover": "Свернуть ПВО", "item.airdef.cam_shahed": "Шахед-136", "item.airdef.cam_geran3": "Герань-3", "item.airdef.cam_lancet": "Ланцет-3", diff --git a/airdef-mod/generated-manifest.txt b/airdef-mod/generated-manifest.txt index 69aa977..1603fca 100644 --- a/airdef-mod/generated-manifest.txt +++ b/airdef-mod/generated-manifest.txt @@ -142,8 +142,8 @@ b4d98a938486d49db28c6c7a608ca3b6ab0c9c3eac266ecf12c7dd931cc28f93 assets/airdef/ 489799dcb5b441e9d4be8bfb3d73a6ebd5fdf2b5ee614b62f38b85bb2fbfad75 assets/airdef/items/launch_zircon.json 6b6da5887aa8d9bc987b2c181c243bc2afdd5846a869818f699b59204e559929 assets/airdef/items/mover.json 177f7535e4c52ed975d6f737c2b2acb7741b7a928955c8899aced85211443bbf assets/airdef/items/remover.json -ddfba1d8e940c870b43268a5d8ebae130a4061f2f734a750df4bfd54452c8012 assets/airdef/lang/en_us.json -ddfba1d8e940c870b43268a5d8ebae130a4061f2f734a750df4bfd54452c8012 assets/airdef/lang/ru_ru.json +c10367467f45c274e92d534199c2851520140507903a5d4287f12ed403c92be5 assets/airdef/lang/en_us.json +c10367467f45c274e92d534199c2851520140507903a5d4287f12ed403c92be5 assets/airdef/lang/ru_ru.json b9b5b5bec33a77e944552c225ee2f526ab9820fa8fca4b3ccf311f2a325925ee assets/airdef/models/block/amraam_missile.json c54e6b24ab69e9d9a2dbbbc63fe2ac60fa37735bf644500ddd5c3de0b91908cf assets/airdef/models/block/barge.json a4198ff647de5866919f9b82a3d53e6486fc56cc9f175f7907951d063a6f4526 assets/airdef/models/block/beam.json diff --git a/airdef-mod/src/battery_view.rs b/airdef-mod/src/battery_view.rs index 77659c9..a1d6359 100644 --- a/airdef-mod/src/battery_view.rs +++ b/airdef-mod/src/battery_view.rs @@ -100,7 +100,7 @@ pub fn sam_status(sam: &Sam, now: u64) -> String { text += &format!(" перезарядка {}с", sam.reloading.div_ceil(20)); } else { if let Some(magazine) = sam.kind.missile_magazine() { - if sam.kind == SamKind::S400 { + if sam.kind.supports_rm48u() { text += &format!(" ПВО {} · RM48U {} / {} ячеек", sam.missiles, sam.ground_rounds, sam.cells()); if sam.ground_return { text += " · ожидает вывоза RM48U"; } } else { diff --git a/airdef-mod/src/layout.rs b/airdef-mod/src/layout.rs index dc46d67..7c7aa9b 100644 --- a/airdef-mod/src/layout.rs +++ b/airdef-mod/src/layout.rs @@ -133,7 +133,9 @@ impl Layout { None => break, } } - let ground_rounds = l.num(22, "заряжено RM48U", 0.0, 4.0)?.unwrap_or(0.0) as u32; + let supports_ground = kind.supports_rm48u(); + let shared_cells = if supports_ground { kind.missile_magazine().unwrap_or(0) } else { 0 }; + let ground_rounds = l.num(22, "заряжено RM48U", 0.0, COUNT)?.unwrap_or(0.0) as u32; let ground_stock = l.num(23, "запас RM48U", 0.0, COUNT)?.unwrap_or(0.0) as u32; let air_48n6_stock = l.num(24, "снятый боезапас ПВО", 0.0, COUNT)?.unwrap_or(0.0) as u32; let mode = match l.w.get(25) { @@ -149,7 +151,7 @@ impl Layout { Some(v) => v.parse::().map_err(|_| l.bad("пустые контейнеры", "нужно целое число 0..255"))?, }; let ground_request = l.num(28, "заявка RM48U", 0.0, 1.0)?.unwrap_or(0.0) == 1.0; - if ground_request && kind != SamKind::S400 { return Err(l.bad("заявка RM48U", "нужен С-400")); } + if ground_request && !supports_ground { return Err(l.bad("заявка RM48U", "нужен совместимый профиль")); } 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); @@ -157,7 +159,7 @@ impl Layout { 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 (ground_return && (!supports_ground || 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("роль РЛС", "роль поддерживается только отдельной РЛС")); } @@ -167,14 +169,14 @@ impl Layout { } // 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")); + if mode == sim::battery::SamMode::LauncherOnly && !sim::catalog::has_separate_launcher(kind) { + return Err(l.bad("режим", "отдельная пусковая для этого типа недоступна")); } - if (kind != SamKind::S400 && ground_rounds != 0) || (!matches!(kind, SamKind::Depot | SamKind::Tzm) && (ground_stock != 0 || air_48n6_stock != 0)) { + if (!supports_ground && ground_rounds != 0) || (!matches!(kind, SamKind::Depot | SamKind::Tzm) && (ground_stock != 0 || air_48n6_stock != 0)) { return Err(l.bad("боезапас", "несовместимый тип техники")); } - if let Some((m, _, _, _)) = ammo && m + ground_rounds > 4 && kind == SamKind::S400 { - return Err(l.bad("боезапас", "больше четырёх ячеек")); + if supports_ground && ammo.map_or(0, |(missiles, ..)| missiles) + ground_rounds > shared_cells { + return Err(l.bad("боезапас", &format!("больше {shared_cells} ячеек"))); } 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 }); } diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs index 0d411eb..0c8f9d6 100644 --- a/airdef-mod/src/lib.rs +++ b/airdef-mod/src/lib.rs @@ -1883,6 +1883,16 @@ impl AirDef { widgets.push(Widget::Text(TextWidget { id: 0, text, color: 0 })); } } + self.post.decisions = post::recorded_choices( + self.sim.recording().into_iter().chain(self.sim.replays.iter().rev()), id, + ).take(1).collect(); + let recorded = self.post.decisions.first().map(|row| format!( + "Последнее записанное · налёт №{} {} · {}", row.raid, + replay::clock(f64::from(row.entry.at)), post::decision_label(row.entry.outcome), + )).unwrap_or_else(|| "Последнее записанное · записей решений нет".into()); + for text in ui_lines(&recorded) { + widgets.push(Widget::Text(TextWidget { id: 0, text, color: 0 })); + } let mut actions = vec![ (Action::Checks, "Статус и отметка"), (Action::Map, "Показать на карте"), @@ -1896,6 +1906,9 @@ impl AirDef { { actions.push((Action::Source(source.id), "Источник отметки")); } + if !self.post.decisions.is_empty() { + actions.push((Action::LatestDecision, "Последнее записанное решение")); + } actions.push((Action::History, "История решений")); actions.push((Action::Pin, if self.post.pinned == Some(id) { "Открепить" } else { "Закрепить в списке и сетке" })); self.post.actions = actions.iter().map(|(action, _)| *action).collect(); @@ -1913,9 +1926,7 @@ impl AirDef { } Page::UnitHistory(id, _) => { let recordings = || self.sim.recording().into_iter().chain(self.sim.replays.iter().rev()); - self.post.decisions = recordings().flat_map(|rec| rec.decisions.entries().rev() - .filter(move |entry| entry.unit == id) - .map(|&entry| post::RecordedChoice { raid: rec.number, entry })) + self.post.decisions = post::recorded_choices(recordings(), id) .take(POST_DECISION_LIMIT + 1) .collect(); let shortened = self.post.decisions.len() > POST_DECISION_LIMIT; @@ -2644,6 +2655,9 @@ impl Mod for AirDef { self.open_menu(Page::Unit(source, post::From::Source)); } Some(post::Action::History) => self.open_menu(Page::UnitHistory(unit, from)), + Some(post::Action::LatestDecision) if !self.post.decisions.is_empty() => { + self.open_menu(Page::UnitDecision(unit, from, 0)); + } Some(post::Action::Pin) => { self.post.pinned = (self.post.pinned != Some(unit)).then_some(unit); self.post.page = 0; diff --git a/airdef-mod/src/map.rs b/airdef-mod/src/map.rs index a40445f..46f1ed3 100644 --- a/airdef-mod/src/map.rs +++ b/airdef-mod/src/map.rs @@ -2817,7 +2817,7 @@ impl AirDef { lines.push((format!("Груз RM48U: {} · 48Н6: {}{}", sam.ground_stock, sam.air_48n6_stock, if sam.return_cargo { " · возврат на склад" } else { "" }), WHITE)); } if k.armed() { - if sam.kind == SamKind::S400 { lines.push((format!("Ударных RM48U: {} (общие ячейки с ПВО){}", sam.ground_rounds, if sam.ground_return { " · ожидает вывоза" } else if sam.ground_request { " · ожидает доставки" } else { "" }), WHITE)); } + if sam.kind.supports_rm48u() { lines.push((format!("Ударных RM48U: {} (общие ячейки с ПВО){}", sam.ground_rounds, if sam.ground_return { " · ожидает вывоза" } else if sam.ground_request { " · ожидает доставки" } else { "" }), WHITE)); } lines.push((format!("Боезапас: {} ракет, {} очередей{}", sam.missiles, sam.bursts, if sam.reloading > 0 { format!(" · перезарядка {} с", sam.reloading / 20) } else { String::new() }), WHITE)); lines.push((format!("Дальность огня: {}", distance(k.range())), WHITE)); } diff --git a/airdef-mod/src/monitor.rs b/airdef-mod/src/monitor.rs index 8d9c0f4..7b6f4af 100644 --- a/airdef-mod/src/monitor.rs +++ b/airdef-mod/src/monitor.rs @@ -312,7 +312,7 @@ fn cell(sim: &Sim, index: usize, x: f32, y: f32, w: f32, h: f32, s: &mut Vec(recordings: impl Iterator + 'a, unit: u32) -> impl Iterator + 'a { + recordings.flat_map(move |rec| rec.decisions.entries().rev() + .filter(move |entry| entry.unit == unit) + .map(move |&entry| RecordedChoice { raid: rec.number, entry })) +} + pub fn decision_label(outcome: decision::Outcome) -> &'static str { use decision::{Block as B, Outcome as O}; match outcome { diff --git a/airdef-mod/src/recon_view.rs b/airdef-mod/src/recon_view.rs index 53b3415..f710756 100644 --- a/airdef-mod/src/recon_view.rs +++ b/airdef-mod/src/recon_view.rs @@ -80,7 +80,7 @@ pub fn intent_name(intent: &str) -> &'static str { /// and the priority the planner prices it at. pub fn mark_line(m: &ReconReport) -> String { let role = m.role.map(|k| format!(" ({})", role_name(k))).unwrap_or_default(); - format!( + let mut line = format!( "Отметка {}: {}{} · {} · {} · {} · {} с назад · приоритет {}", m.id, category_name(m.category), @@ -90,7 +90,11 @@ pub fn mark_line(m: &ReconReport) -> String { confidence_name(m.confidence), m.age / 20, m.priority - ) + ); + if m.launches != 0 { + line.push_str(&format!(" · замечено пусков {}", m.launches)); + } + line } /// Why the mark has the priority it does: the observed role, the freshness and the quality, each @@ -190,7 +194,7 @@ mod tests { let qual = Quality::from_key(quality).unwrap(); let role_enum = role.and_then(crate::sim::battery::RadarRole::from_key); let (f, q, r) = priority_parts(confidence, qual, cat, role_enum); - ReconReport { id, area: DVec3::ZERO, radius: 120.0, category, role, source: "flyby", age, quality, confidence, live: true, priority: f * 4 + q * 3 + r } + ReconReport { id, area: DVec3::ZERO, radius: 120.0, category, role, source: "flyby", launches: 0, age, quality, confidence, live: true, priority: f * 4 + q * 3 + r } } fn sortie(drone: u32, phase: &'static str, zones_left: usize, report_in: Option) -> ReconSortieReport { diff --git a/airdef-mod/src/sim/battery.rs b/airdef-mod/src/sim/battery.rs index 5a64d02..684730c 100644 --- a/airdef-mod/src/sim/battery.rs +++ b/airdef-mod/src/sim/battery.rs @@ -241,7 +241,7 @@ impl Sam { } /// Change the physical configuration. Invalid combinations leave the unit untouched. pub fn set_mode(&mut self, mode: SamMode) -> bool { - if mode == SamMode::LauncherOnly && !matches!(self.kind, SamKind::S400 | SamKind::S500) { return false; } + if mode == SamMode::LauncherOnly && !catalog::has_separate_launcher(self.kind) { return false; } if self.mode != mode { self.mode = mode; self.tracks.clear(); @@ -269,7 +269,7 @@ impl Sim { self.sams.iter().enumerate().filter_map(|(index, sam)| { if sam.kind == SamKind::Radar { Some(BatteryStatus::Radar { index, role: sam.radar_role, emitting: sam.radar_on, operational: sam.radar_up() && sam.link_range() > 0.0 }) - } else if matches!(sam.kind, SamKind::S400 | SamKind::S500) { + } else if catalog::has_separate_launcher(sam.kind) { let linked = self.sams.iter().any(|r| r.kind == SamKind::Radar && r.radar_role.authorizes() && r.radar_up() && r.link_range() > 0.0 && sam.link_range() > 0.0 && r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range())); Some(BatteryStatus::Launcher { index, kind: sam.kind, mode: sam.mode, linked }) } else { None } @@ -540,30 +540,32 @@ mod emission_tests { assert_eq!(sim.sams[1].track(id).unwrap().own_tick, 0); assert_eq!(sim.sams[1].track(id).unwrap().tick, 20); assert!(!sim.sams[1].radar_up()); - // The emitting source is fixed by the drone; the silent receiver is not. - let picture = sim.picture_of_defences(); + // The emitting source gives the drone a coarse area. The silent receiver stays hidden. + let picture = sim.knowledge_now().observations(); assert_eq!(picture.len(), 1); - assert_eq!((picture[0].id, picture[0].at), (1, DVec3::ZERO)); - assert_eq!(picture[0].seen, ew::Seen::Emission); + let signal = picture[0]; + assert!(recon::is_mark(signal.id) && !signal.exact()); + assert_eq!((signal.channel, signal.kind), (recon::Source::Emission, None)); sim.sams[0].radar_on = false; // The truth moving is not an observation: the contact keeps the observed place. sim.sams[0].pos = DVec3::new(400.0, 0.0, 0.0); sim.tick = 40; sim.update_sight(&mut ground); assert_eq!(sim.sams[1].track(id).unwrap().tick, 20); - let picture = sim.picture_of_defences(); - assert_eq!(picture.len(), 1); - assert_eq!(picture[0].at, DVec3::ZERO, "a hidden move changed the picture"); - // A fresh emission fix re-places it where seen then. + assert_eq!(sim.knowledge_now().observations(), picture, "a hidden move changed the picture"); + // A fresh witnessed emission moves the estimated area. sim.sams[0].radar_on = true; sim.tick = 60; sim.update_sight(&mut ground); - assert_eq!(sim.picture_of_defences()[0].at, DVec3::new(400.0, 0.0, 0.0)); + let moved = sim.knowledge_now().observations()[0]; + assert_eq!(moved.id, signal.id); + assert!(moved.at != signal.at && moved.at != sim.sams[0].pos); + assert!(moved.at.distance(sim.sams[0].pos) < moved.radius); sim.sams[0].radar_on = false; // Other disclosure channels still reveal a silent unit. - sim.intel.observe(&sim.sams[1], 60, ew::Seen::Launch); - assert!(sim.known_live(2)); + sim.recon.signal(&sim.sams[1], 60, recon::Source::Launch); + assert!(sim.knowledge_now().observations().iter().any(|o| o.channel == recon::Source::Launch && !o.exact())); sim.tick = 6060; - assert!(sim.picture_of_defences().is_empty(), "an unrefreshed contact never ages out"); + assert!(sim.knowledge_now().observations().is_empty(), "an unrefreshed contact never ages out"); } } diff --git a/airdef-mod/src/sim/catalog.rs b/airdef-mod/src/sim/catalog.rs index 2b6fd27..16777bf 100644 --- a/airdef-mod/src/sim/catalog.rs +++ b/airdef-mod/src/sim/catalog.rs @@ -71,7 +71,9 @@ impl Unit { /// Whether the unit has a gun; callers need no access to the private weapon profile. pub fn has_gun(self) -> bool { self.kind.spec().gun.is_some() } pub fn ground_strike(self) -> GroundStrike { - if self.kind == SamKind::S400 { GroundStrike::Rm48uGame } else { GroundStrike::Unavailable { reason: "Для этой техники не задан профиль удара по координатам" } } + self.kind.spec().ground_strike.unwrap_or(GroundStrike::Unavailable { + reason: "Для этой техники не задан профиль удара по координатам", + }) } } @@ -173,6 +175,10 @@ pub fn variant(id: &str) -> Option<&'static UnitVariant> { VARIANTS.iter().find(|variant| variant.id == id) } +pub fn has_separate_launcher(kind: SamKind) -> bool { + VARIANTS.iter().any(|variant| variant.kind == kind && variant.mode == SamMode::LauncherOnly) +} + #[cfg(test)] mod tests { use super::*; diff --git a/airdef-mod/src/sim/catalog_entries.rs b/airdef-mod/src/sim/catalog_entries.rs index 86afb87..51580a4 100644 --- a/airdef-mod/src/sim/catalog_entries.rs +++ b/airdef-mod/src/sim/catalog_entries.rs @@ -1,4 +1,4 @@ -// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit. +// Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit. pub const AIRCRAFT: &[Aircraft] = &[ Aircraft { kind: Gerbera, launch_item: None, raid: true }, Aircraft { kind: Shahed, launch_item: Some("airdef:launch_shahed"), raid: true }, diff --git a/airdef-mod/src/sim/damage.rs b/airdef-mod/src/sim/damage.rs index 011f994..2747ab3 100644 --- a/airdef-mod/src/sim/damage.rs +++ b/airdef-mod/src/sim/damage.rs @@ -135,17 +135,7 @@ fn blast_exposure(ground: &Ground, from: DVec3, centre: DVec3, size: f64, now: u 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, - MissileKind::IrisT => 0.6, - MissileKind::Amraam => 0.5, - MissileKind::M9m317 => 1.2, - MissileKind::M9m338 => 0.4, - MissileKind::P1sun => 0.1, - } + self.spec().launcher_blast } } @@ -159,20 +149,7 @@ impl DroneKind { /// Strike accuracy: the CEP (blocks; half the strikes land within it, the scatter is Rayleigh) /// and the share of strikes with a rare gross navigation fault, which lands beyond `MISS_RADIUS`. pub(super) fn accuracy(self) -> (f64, f64) { - match self { - DroneKind::Shahed => (1.2, 0.03), - DroneKind::Geran3 => (1.0, 0.03), - DroneKind::Lancet => (0.8, 0.02), - DroneKind::Gerbera => (1.5, 0.04), - DroneKind::Kh101 => (1.3, 0.05), - DroneKind::Kalibr => (1.3, 0.05), - DroneKind::Kh22 => (1.6, 0.06), - DroneKind::Zircon => (1.5, 0.06), - DroneKind::Iskander => (1.4, 0.06), - DroneKind::Kinzhal => (1.5, 0.06), - // The bus and its blocks: the blocks are aimed by the split, so only the bus's own error applies. - DroneKind::Oreshnik | DroneKind::OreshnikBlock | DroneKind::OreshnikSub => (1.6, 0.08), - } + self.spec().accuracy } } diff --git a/airdef-mod/src/sim/durable.rs b/airdef-mod/src/sim/durable.rs index c819fd3..dbbefc5 100644 --- a/airdef-mod/src/sim/durable.rs +++ b/airdef-mod/src/sim/durable.rs @@ -385,7 +385,7 @@ impl Sim { for m in self.recon.marks.values().take(MAX_RECON_MARKS) { let truth = self.recon.truth.get(&m.id).copied().unwrap_or(0); let line = format!( - "airreconmark {} {} {} {} {} {} {} {} {} {} {} {} {}\n", + "airreconmark {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}\n", m.id, truth, coord(m.area.x), @@ -399,6 +399,8 @@ impl Sim { m.observed, m.reported, m.looks, + m.launches, + m.last_launch.map_or_else(|| "-".into(), |t| t.to_string()), ); if !add(&line) { break; @@ -684,7 +686,7 @@ impl Sim { recon.drone_next = drone_next; } "airreconmark" => { - if w.len() != 14 { + if !matches!(w.len(), 14 | 16) { return Err(l.bad("отметка разведки", "нужны id, юнит, место, категория, источник, качество и времена")); } let id = l.int(1, "id отметки", 0, i64::from(u32::MAX))? as u32; @@ -707,6 +709,10 @@ impl Sim { let observed = l.int(11, "такт наблюдения", 0, tick as i64)? as u64; let reported = l.int(12, "такт донесения", 0, tick as i64)? as u64; let looks = l.int(13, "число взглядов", 0, u16::MAX as i64)? as u16; + let launches = if w.len() == 16 { l.int(14, "видимые пуски", 0, u16::MAX as i64)? as u16 } else { 0 }; + let last_launch = if w.len() == 16 && w[15] != "-" { + Some(l.int(15, "такт последнего пуска", 0, tick as i64)? as u64) + } else { None }; if recon.marks.contains_key(&id) { return Err(l.bad("id отметки", "отметка записана дважды")); } @@ -722,6 +728,8 @@ impl Sim { reported, quality, looks, + launches, + last_launch, }); let slot = id.saturating_sub(recon::ID_BASE); recon.next = recon.next.max(slot); diff --git a/airdef-mod/src/sim/ew.rs b/airdef-mod/src/sim/ew.rs index 1c3aa20..7f75a39 100644 --- a/airdef-mod/src/sim/ew.rs +++ b/airdef-mod/src/sim/ew.rs @@ -551,11 +551,13 @@ impl Intel { self.conditions = conditions; } - /// The one writer of contacts: what was seen of `s`, at its place, this moment. + /// Fixture for the old exact disclosure format. New observations go through recon marks. + #[cfg(test)] pub(super) fn observe(&mut self, s: &Sam, now: u64, seen: Seen) { self.note(s.id, s.kind, s.pos, s.alive(), now, seen); } + #[cfg(test)] pub(super) fn note(&mut self, id: u32, kind: SamKind, at: DVec3, alive: bool, now: u64, seen: Seen) { let c = self.contacts.entry(id).or_insert(Contact { id, kind, at, tick: now, seen, emission: None, destroyed: None, launches: 0 }); // The newest observation wins; a fresh look at a live unit clears an old wreck call. @@ -657,9 +659,12 @@ impl Sim { if now % 40 == 0 { out.sound("minecraft:block.beacon.ambient", top, 2.0, 1.4); } - // A transmitter on the air: the enemy finds it. - if now % 20 == 0 { - self.intel.observe(s, now, Seen::Jamming); + // A hostile aircraft experiencing interference can report an area. + if now % 20 == 0 && s.ew_up() && self.drones.iter().any(|d| d.alive() + && !recon::is_drone_id(d.id) && d.kind.jammable() + && horizontal(d.pos - s.pos).length_squared() < EW_RADIUS * EW_RADIUS) + { + self.recon.signal(s, now, recon::Source::Jamming); } } } @@ -1445,6 +1450,7 @@ pub struct ReconReport { pub role: Option<&'static str>, /// "flyby", "emission", "jamming" or "launch". pub source: &'static str, + pub launches: u16, pub age: u64, /// "coarse" or "refined". pub quality: &'static str, @@ -1622,6 +1628,7 @@ impl Sim { category: m.category.name(), role: m.role.map(|r| r.key()), source: m.source.name(), + launches: m.launches, age: m.age(now), quality: m.quality.name(), confidence: m.confidence(now), diff --git a/airdef-mod/src/sim/logistics.rs b/airdef-mod/src/sim/logistics.rs index 81fda40..6b69ca3 100644 --- a/airdef-mod/src/sim/logistics.rs +++ b/airdef-mod/src/sim/logistics.rs @@ -5,7 +5,7 @@ impl Sim { /// Prepare one explicitly typed round at a nearby living depot. Any displaced air round is retained there. pub fn load_ground_round(&mut self, i: usize) -> Result { let s = self.sams.get(i).ok_or("Нет такого комплекса")?; - if s.kind != SamKind::S400 { return Err("Для этого комплекса нет игрового профиля RM48U".into()); } + if !s.kind.supports_rm48u() { return Err("Для этого комплекса нет игрового профиля RM48U".into()); } if !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 { return Err("Комплекс должен быть исправен и развёрнут".into()); } @@ -40,7 +40,7 @@ impl Sim { /// Return a loaded ground round to a nearby depot; restore a previously removed air round if available. pub fn unload_ground_round(&mut self, i: usize) -> Result { let s = self.sams.get(i).ok_or("Нет такого комплекса")?; - if s.kind != SamKind::S400 || !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 || s.ground_rounds == 0 { + if !s.kind.supports_rm48u() || !s.alive() || s.moving() || s.preparing.is_some() || s.reloading > 0 || s.part(Part::Launcher) <= 0.0 || s.ground_rounds == 0 { return Err("Нужен исправный развёрнутый С-400 с загруженной RM48U".into()); } if s.ground_return { return Err("Заявка на вывоз RM48U уже ожидает ТЗМ".into()); } @@ -66,7 +66,7 @@ impl Sim { pub fn cancel_ground_request(&mut self, i: usize) -> Result { let s = self.sams.get_mut(i).ok_or("Нет такого комплекса")?; - if s.kind != SamKind::S400 || (!s.ground_request && !s.ground_return) { return Err("Нет ожидающей заявки RM48U".into()); } + if !s.kind.supports_rm48u() || (!s.ground_request && !s.ground_return) { return Err("Нет ожидающей заявки RM48U".into()); } s.ground_request = false; s.ground_return = false; Ok(format!("С-400 №{}: заявка RM48U отменена", i + 1)) @@ -111,12 +111,12 @@ impl Sim { // untouched and only real RM48U demand pulls the truck away from its watch. let return_cargo = truck.return_cargo && truck.ground_stock > 0; let can_pick = truck.ground_stock == 0 && truck.air_48n6_stock < TRUCK_LOAD; - let claim_pending = return_cargo || (can_pick && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return)); + let claim_pending = return_cargo || (can_pick && self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_return)); let taken: Vec = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect(); let target = if return_cargo { self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock < STOCK_LIMIT && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) } else if can_pick { - self.sams.iter().filter(|s| s.kind == SamKind::S400 && s.alive() && s.ground_return && s.ground_rounds > 0 && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) + self.sams.iter().filter(|s| s.kind.supports_rm48u() && s.alive() && s.ground_return && s.ground_rounds > 0 && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) } else { None }.map(|s| (s.id, s.pos)); @@ -148,7 +148,7 @@ impl Sim { // The impossible return still outranks a mere stock run: without RM48U demand // the truck holds its watch (and drops a stale job) exactly as before. let supply_demand = (self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request)) - || (self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request) + || (self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request) && self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0)); if !supply_demand { self.sams[t].job = None; @@ -158,11 +158,11 @@ impl Sim { // Typed strike cargo takes precedence over generic reloads. Jobs are reconstructed // after loading a save; the request and physical cargo survive independently. let typed_work = truck.ground_stock > 0 || truck.air_48n6_stock > 0 || - (self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request) + (self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request) && self.sams.iter().any(|s| s.kind == SamKind::Depot && s.alive() && s.ground_stock > 0)); if typed_work { if let Some(id) = self.sams[t].job { - let valid = self.sams.iter().find(|s| s.id == id).is_some_and(|s| s.alive() && !self.routes.out_of_reach(truck_id, s.id, now) && (s.kind == SamKind::Depot || (self.sams[t].ground_stock > 0 && s.kind == SamKind::S400 && s.ground_request))); + let valid = self.sams.iter().find(|s| s.id == id).is_some_and(|s| s.alive() && !self.routes.out_of_reach(truck_id, s.id, now) && (s.kind == SamKind::Depot || (self.sams[t].ground_stock > 0 && s.kind.supports_rm48u() && s.ground_request))); if !valid { self.sams[t].job = None; } } if let Some(id) = self.sams[t].job { @@ -180,11 +180,11 @@ impl Sim { // The last reserved round left the truck: nothing marks as return cargo any more. if self.sams[t].ground_stock == 0 { self.sams[t].return_cargo = false; } } - if self.sams[t].ground_stock == 0 && self.sams[j].ground_stock > 0 && self.sams[t].air_48n6_stock == 0 && self.sams.iter().any(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request) { + if self.sams[t].ground_stock == 0 && self.sams[j].ground_stock > 0 && self.sams[t].air_48n6_stock == 0 && self.sams.iter().any(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request) { self.sams[j].ground_stock -= 1; self.sams[t].ground_stock += 1; } - } else if self.sams[j].kind == SamKind::S400 && self.sams[j].ground_request && !self.sams[j].moving() && self.sams[j].preparing.is_none() && self.sams[j].reloading == 0 && self.sams[j].part(Part::Launcher) > 0.0 && self.sams[j].ground_rounds < self.sams[j].cells() && self.sams[t].ground_stock > 0 { + } else if self.sams[j].kind.supports_rm48u() && self.sams[j].ground_request && !self.sams[j].moving() && self.sams[j].preparing.is_none() && self.sams[j].reloading == 0 && self.sams[j].part(Part::Launcher) > 0.0 && self.sams[j].ground_rounds < self.sams[j].cells() && self.sams[t].ground_stock > 0 { let displaced = u32::from(self.sams[j].missiles + self.sams[j].ground_rounds >= self.sams[j].cells()); self.sams[j].missiles -= displaced; self.sams[j].ground_rounds += 1; @@ -207,7 +207,7 @@ impl Sim { } let taken: Vec = self.sams.iter().filter(|s| s.kind == SamKind::Tzm && s.alive() && s.id != truck_id).filter_map(|s| s.job).collect(); let next = if self.sams[t].ground_stock > 0 && self.sams.iter().any(|s| s.alive() && s.ground_request) { - self.sams.iter().filter(|s| s.kind == SamKind::S400 && s.alive() && s.ground_request && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && s.ground_rounds < s.cells() && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) + self.sams.iter().filter(|s| s.kind.supports_rm48u() && s.alive() && s.ground_request && !s.moving() && s.preparing.is_none() && s.reloading == 0 && s.part(Part::Launcher) > 0.0 && s.ground_rounds < s.cells() && !taken.contains(&s.id) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) } else { self.sams.iter().filter(|s| s.kind == SamKind::Depot && s.alive() && (self.sams[t].air_48n6_stock > 0 || (self.sams[t].ground_stock > 0 && s.ground_stock < STOCK_LIMIT) || (self.sams[t].ground_stock == 0 && s.ground_stock > 0)) && !self.routes.out_of_reach(truck_id, s.id, now)).min_by(|a,b| a.pos.distance(at).total_cmp(&b.pos.distance(at))) }.map(|s| (s.id, s.pos)); diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 9ecfa85..65636f0 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -766,25 +766,6 @@ pub fn roles_text(mask: u8) -> String { Class::ALL.iter().filter(|c| mask & c.bit() != 0).map(|c| c.letter()).collect::>().join("") } -#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] -pub enum DroneKind { - Shahed, - Geran3, - Lancet, - Gerbera, - Kh101, - Kalibr, - Kh22, - Zircon, - Iskander, - Kinzhal, - /// An IRBM: its bus releases six blocks high over the target. - Oreshnik, - /// One of the Oreshnik's blocks: it splits into six glowing submunitions. - OreshnikBlock, - OreshnikSub, -} - /// What a drone carries on its tail. #[derive(Clone, Copy)] enum Engine { @@ -810,6 +791,8 @@ pub struct DroneSpec { dive: f64, /// Primed TNT on impact. warhead: u32, + /// Impact scatter in blocks and the probability of a large miss in the game. + accuracy: (f64, f64), scale: f64, engine: Engine, /// No warhead: it only draws fire. @@ -838,21 +821,6 @@ impl DroneSpec { } impl DroneKind { - pub const ALL: [DroneKind; 13] = [ - DroneKind::Shahed, - DroneKind::Geran3, - DroneKind::Lancet, - DroneKind::Gerbera, - DroneKind::Kh101, - DroneKind::Kalibr, - DroneKind::Kh22, - DroneKind::Zircon, - DroneKind::Iskander, - DroneKind::Kinzhal, - DroneKind::Oreshnik, - DroneKind::OreshnikBlock, - DroneKind::OreshnikSub, - ]; /// The sound of a launch from the ground: a light catapult shot, a rocket booster, a heavy ballistic launch. pub fn launch_sound(self) -> &'static str { self.spec().launch_sound @@ -1008,22 +976,10 @@ impl Drone { // ---------------------------------------------------------------- interceptors -#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] -pub enum MissileKind { - Pac3, - M57e6, - M48n6, - M77n6, - IrisT, - Amraam, - M9m317, - M9m338, - /// Not a missile: an interceptor drone, slow and cheap, that rams Shaheds. - P1sun, -} - struct MissileSpec { model: &'static str, + /// Extra game blast damage when a loaded round burns in its launcher. + launcher_blast: f64, speed: f64, accel: f64, turn: f64, @@ -2256,14 +2212,16 @@ impl Sim { } } - /// What the enemy's munitions just watched (#127): for every impact, the fate of each known - /// unit near it — dead or alive as the explosion showed, at the place it showed. Units the - /// blasts missed keep their contacts exactly as they were: unobserved is unobserved. + /// What the enemy's munitions just watched (#127): a destroyed known unit near an impact is + /// removed from the planner's leads. Surviving contacts keep their last observed areas. fn observe_outcomes(&mut self, impacts: &[(u32, DroneKind, DVec3, u32)]) { let now = self.tick; for &(_, _, pos, _) in impacts { for s in self.sams.iter().filter(|s| s.pos.distance(pos) < 16.0) { - self.intel.outcome(s.id, s.alive(), s.pos, now); + if !s.alive() { + self.intel.outcome(s.id, false, s.pos, now); + self.recon.forget_wreck(s.id); + } } } } @@ -2865,9 +2823,11 @@ impl Sim { t.ammo_waits += ammo_waits; }); for (kind, muzzle, dir, target, sam) in launches { - // A launch gives the system away: the enemy saw it fire, no more than that. - if let Some(s) = self.sams.iter().find(|s| s.id == sam) { - self.intel.observe(s, self.tick, ew::Seen::Launch); + // A witnessed launch reveals a launcher's area, not its type or loadout. + if let Some(s) = self.sams.iter().find(|s| s.id == sam) + && recon::has_signal_witness(&self.drones, s.pos) + { + self.recon.signal(s, self.tick, recon::Source::Launch); } // It leaves with the track the system fired on (#66). let fix = self diff --git a/airdef-mod/src/sim/observe.rs b/airdef-mod/src/sim/observe.rs index a5851db..f8672f9 100644 --- a/airdef-mod/src/sim/observe.rs +++ b/airdef-mod/src/sim/observe.rs @@ -198,6 +198,8 @@ mod tests { reported: observed, quality: recon::Quality::Coarse, looks: 1, + launches: 0, + last_launch: None, } } diff --git a/airdef-mod/src/sim/orders.rs b/airdef-mod/src/sim/orders.rs index 20fc8d3..cd9ab13 100644 --- a/airdef-mod/src/sim/orders.rs +++ b/airdef-mod/src/sim/orders.rs @@ -170,14 +170,8 @@ impl Sim { let next = sam.pos + ahead * step; // The column and chassis clearance ahead: a wall, low ceiling or a change after planning // turns the vehicle back to the planner. Unknown voxels remain a wait, never a drive. - let Some(y) = ground.at(next, now) else { - if route.wait_ahead() { - finish_move(sam, routes, n, now, Some(route::Why::NoMap), out); - } - continue; - }; - match route.clearance(ground, next, now) { - route::Clearance::Clear => {} + let y = match route.clearance(ground, next, now) { + route::Clearance::Clear(height) => height, route::Clearance::Pending => { if route.wait_ahead() { finish_move(sam, routes, n, now, Some(route::Why::NoMap), out); @@ -185,10 +179,16 @@ impl Sim { continue; } route::Clearance::Blocked => { + // The folded footprint already fits at the current position. When + // a wide turn would clip a wall, finish the turn before judging the route. + if turning > 0.45 { + sam.yaw = sam.heading; + continue; + } route.blocked_ahead(next, sam.pos); continue; } - } + }; route.ahead_ok(); let rise = y - sam.pos.y; if rise > route::STEP_UP || rise < -route::STEP_DOWN { diff --git a/airdef-mod/src/sim/recon.rs b/airdef-mod/src/sim/recon.rs index 766ae9d..a303561 100644 --- a/airdef-mod/src/sim/recon.rs +++ b/airdef-mod/src/sim/recon.rs @@ -34,6 +34,8 @@ pub const REFINE_GAP: u64 = 600; /// is the unit's place: the reported point is a cell centre, jittered away from it. pub const COARSE_AREA: f64 = 120.0; pub const REFINED_AREA: f64 = 48.0; +/// Existing game radius in which an ordinary aircraft can report a nearby signal. +const SIGNAL_WITNESS_RANGE: f64 = 1600.0; /// How long a mark is remembered (five minutes, as a disclosure contact). pub const MARK_TTL: u64 = 6000; /// How long a checked empty zone is not worth another look (unless there is nothing else). @@ -65,6 +67,11 @@ pub fn is_drone_id(id: u32) -> bool { id >= DRONE_BASE } +pub(super) fn has_signal_witness(drones: &[Drone], at: DVec3) -> bool { + drones.iter().any(|drone| drone.alive() && !is_drone_id(drone.id) + && drone.pos.distance_squared(at) <= SIGNAL_WITNESS_RANGE * SIGNAL_WITNESS_RANGE) +} + /// What a look can tell about a unit's role, in the terms the game already publishes. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Category { @@ -201,7 +208,10 @@ pub struct Mark { /// The tick its report arrived (for the record; confidence is age alone). pub(super) reported: u64, pub(super) quality: Quality, + /// Delivered close looks only. Passive signals may keep an area fresh but cannot refine it. pub(super) looks: u16, + pub(super) launches: u16, + pub(super) last_launch: Option, } impl Mark { @@ -301,6 +311,8 @@ impl Recon { mix(m.observed); mix(m.reported); mix(u64::from(m.looks)); + mix(u64::from(m.launches)); + mix(m.last_launch.unwrap_or(u64::MAX)); mix(m.quality as u64); mix(m.category as u64); mix(m.source as u64); @@ -362,6 +374,77 @@ impl Recon { self.truth.iter().find_map(|(id, t)| (*t == truth).then(|| self.marks.get(id).copied()).flatten()) } + fn insert_mark(&mut self, truth: u32, mut mark: Mark) { + if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 { + return; + } + self.next += 1; + mark.id = ID_BASE + self.next; + self.truth.insert(mark.id, truth); + self.marks.insert(mark.id, mark); + } + + /// A witnessed game event gives an area and what the event itself showed. Only a sortie can + /// improve visual classification; repeating the same periodic signal cannot do so. + pub(super) fn signal(&mut self, sam: &Sam, now: u64, source: Source) { + let category = match source { + Source::Emission => Category::Radar, + Source::Jamming => Category::Ew, + Source::Launch => Category::Launcher, + Source::Flyby => return, + }; + let cell = (sam.pos / COARSE_AREA).round(); + let salt = (cell.x as i64 as u32) ^ (cell.z as i64 as u32).rotate_left(16); + let area = area_of(sam.pos, COARSE_AREA, salt); + if let Some(old) = self.mark_for_truth(sam.id) { + let mark = self.marks.get_mut(&old.id).unwrap(); + if source == Source::Launch && mark.last_launch.is_none_or(|t| t < now) { + mark.launches = mark.launches.saturating_add(1); + mark.last_launch = Some(now); + } + if (old.looks != 0 && old.live(now) && same_area(&old, area, COARSE_AREA)) + || (now == old.observed && old.source == Source::Launch) + { + return; + } + mark.area = area; + mark.radius = COARSE_AREA; + mark.category = category; + mark.role = None; + mark.source = source; + mark.observed = now; + mark.reported = now; + mark.quality = Quality::Coarse; + mark.looks = 0; + } else { + self.insert_mark(sam.id, Mark { + id: 0, + area, + radius: COARSE_AREA, + category, + role: None, + source, + observed: now, + reported: now, + quality: Quality::Coarse, + looks: 0, + launches: u16::from(source == Source::Launch), + last_launch: (source == Source::Launch).then_some(now), + }); + } + } + + /// Only a new close look or a witnessed destruction removes a lead about a wreck. + pub(super) fn forget_wreck(&mut self, truth: u32) { + if let Some(mark) = self.mark_for_truth(truth) { + self.marks.remove(&mark.id); + self.truth.remove(&mark.id); + } + for sortie in &mut self.sorties { + sortie.pending.retain(|look| look.truth != truth); + } + } + /// A report that has arrived. The same observation twice changes nothing; a genuinely /// later look updates the mark and may refine it. The mark keeps its synthetic id. pub(super) fn report(&mut self, look: Look, now: u64) { @@ -369,7 +452,11 @@ impl Recon { match existing { Some(id) => { let Some(old) = self.marks.get(&id).copied() else { return }; - if look.observed <= old.observed { + // A visual report spent time in transit. A fresher signal in the same area + // can coexist with that first close look, but cannot supersede a newer place + // or an actual observation that the position is now wrecked. + let agrees_with_signal = old.looks == 0 && !look.wreck && same_area(&old, look.area, look.radius); + if look.observed <= old.observed && !agrees_with_signal { return; } // The flight saw the wreck itself: the station is off the planner's leads, and @@ -379,8 +466,15 @@ impl Recon { self.truth.remove(&id); return; } - let refine = look.observed.saturating_sub(old.observed) >= REFINE_GAP; + let agrees = same_area(&old, look.area, look.radius); + let refine = agrees && old.looks != 0 && look.quality == Quality::Refined; let m = self.marks.get_mut(&id).unwrap(); + if !agrees { + m.looks = 0; + m.quality = Quality::Coarse; + m.role = None; + m.radius = COARSE_AREA; + } m.area = look.area; m.radius = if refine { REFINED_AREA } else { m.radius }; m.category = look.category; @@ -398,14 +492,8 @@ impl Recon { if look.wreck { return; } - if self.marks.len() >= MAX_MARKS || self.next >= MARK_TOP - ID_BASE - 1 { - return; - } - self.next += 1; - let id = ID_BASE + self.next; - self.truth.insert(id, look.truth); - self.marks.insert(id, Mark { - id, + self.insert_mark(look.truth, Mark { + id: 0, area: look.area, radius: look.radius, category: look.category, @@ -415,6 +503,8 @@ impl Recon { reported: now, quality: look.quality, looks: 1, + launches: 0, + last_launch: None, }); } } @@ -434,6 +524,12 @@ impl Recon { } } +fn same_area(mark: &Mark, area: DVec3, radius: f64) -> bool { + let reach = mark.radius.max(radius); + horizontal(mark.area - area).length_squared() <= reach * reach + && (mark.area.y - area.y).abs() <= 16.0 +} + /// The rounded place a zone is remembered by (the report, not the truth). pub(super) fn zone_key(center: DVec3) -> (i64, i64) { (center.x.round() as i64, center.z.round() as i64) @@ -446,7 +542,7 @@ pub(super) fn area_of(at: DVec3, cell: f64, salt: u32) -> DVec3 { let h = salt.wrapping_mul(2_654_435_761).rotate_left(7) ^ k.wrapping_mul(2_246_822_519); (f64::from(h % 1000) / 1000.0 - 0.5) * cell * 0.6 }; - DVec3::new((at.x / cell).round() * cell + j(1), at.y, (at.z / cell).round() * cell + j(2)) + DVec3::new((at.x / cell).round() * cell + j(1), (at.y / 8.0).round() * 8.0, (at.z / cell).round() * cell + j(2)) } /// One look through a zone: the units inside it, as the channels can tell them. The true @@ -484,13 +580,17 @@ pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone, }); continue; } - let refine = old.is_some_and(|m| now.saturating_sub(m.observed) >= REFINE_GAP); + let coarse = area_of(s.pos, COARSE_AREA, salt); + let refine = old.is_some_and(|m| m.looks != 0 && same_area(&m, coarse, COARSE_AREA) + && (m.quality == Quality::Refined || now.saturating_sub(m.observed) >= REFINE_GAP)); let quality = if refine { Quality::Refined } else { Quality::Coarse }; let cell = if refine { REFINED_AREA } else { COARSE_AREA }; let category = Category::of(s.kind); // A launch is a public event already watched by the disclosure channel; a look that // passes just after one can name that source too. Health, magazine and link never are. - let launched = intel.contacts().get(&s.id).is_some_and(|c| c.seen == ew::Seen::Launch && now.saturating_sub(c.tick) < 200); + let launched = s.launched > 0 + || old.and_then(|m| m.last_launch).is_some_and(|t| now.saturating_sub(t) < 200) + || intel.contacts().get(&s.id).is_some_and(|c| c.seen == ew::Seen::Launch && now.saturating_sub(c.tick) < 200); // The switch is intent, not work: a radar is an emitter only while `radar_up`, a jammer // only while the transmitter is really on the air. A silent, packed or failed one is // just a unit the flyby saw. @@ -504,7 +604,7 @@ pub(super) fn look(sams: &[Sam], state: &Recon, intel: &ew::Intel, zone: &Zone, let role = (refine && s.kind == SamKind::Radar).then_some(s.radar_role); out.push(Look { truth: s.id, - area: area_of(s.pos, cell, salt), + area: if refine { area_of(s.pos, cell, salt) } else { coarse }, radius: cell, category, role, @@ -722,6 +822,107 @@ mod tests { (s.drone, sim.tick) } + #[test] + fn ordinary_flyby_reports_an_emitting_area_without_unit_truth() { + let run = |kind, at: DVec3, skip_id| { + let mut sim = Sim::new(135); + if skip_id { + sim.id(); + } + let real_id = sam(&mut sim, kind, at); + sim.add_drone(DroneKind::Shahed, at + DVec3::new(20.0, 100.0, 0.0), DVec3::X, at); + sim.tick = 20; + sim.update_sight(&mut Ground::default()); + let observations = sim.knowledge_now().observations(); + assert!(sim.enemy_picture().contacts.is_empty()); + assert_eq!(observations.len(), 1); + let observation = observations[0]; + assert!(is_mark(observation.id) && observation.id != real_id); + assert_eq!((observation.kind, observation.role, observation.quality), (None, None, Quality::Coarse)); + assert_eq!((observation.channel, observation.category), (Source::Emission, Category::Radar)); + assert!(observation.radius > 0.0 && observation.at.distance(at) > 1.0); + + sim.sams[0].radar_on = false; + sim.sams[0].pos.x += 630.0; + sim.tick += 20; + sim.update_sight(&mut Ground::default()); + assert_eq!(sim.knowledge_now().observations(), observations); + observation + }; + let a = run(SamKind::Radar, DVec3::new(37.25, 70.0, 19.75), false); + let b = run(SamKind::Patriot, DVec3::new(42.25, 71.0, 21.75), true); + assert_eq!(a, b, "same-area emission revealed exact unit type, ID or location"); + } + + #[test] + fn a_scout_alone_does_not_send_an_immediate_emission_or_jamming_report() { + let mut sim = Sim::new(135); + let at = DVec3::new(37.25, 70.0, 19.75); + sam(&mut sim, SamKind::Radar, at); + let jammer = sam(&mut sim, SamKind::Ew, at + DVec3::X * 50.0); + sim.sams.iter_mut().find(|s| s.id == jammer).unwrap().ew_on = true; + sim.add_drone(DroneKind::Gerbera, at + DVec3::Y * 90.0, DVec3::X, at); + sim.drones[0].id = DRONE_BASE + 1; + sim.tick = 20; + sim.update_sight(&mut Ground::default()); + sim.step_ew(&mut Out::default()); + assert!(sim.knowledge_now().observations().is_empty()); + + sim.add_drone(DroneKind::Shahed, at + DVec3::Y * 90.0, DVec3::X, at); + sim.update_sight(&mut Ground::default()); + sim.step_ew(&mut Out::default()); + let observations = sim.knowledge_now().observations(); + assert!(observations.iter().any(|o| o.channel == Source::Emission)); + assert!(observations.iter().any(|o| o.channel == Source::Jamming && o.category == Category::Ew)); + } + + #[test] + fn delayed_look_can_classify_an_area_without_turning_signals_into_visual_looks() { + let mut sim = Sim::new(135); + let at = DVec3::new(37.25, 70.0, 19.75); + sam(&mut sim, SamKind::Patriot, at); + let unit = &sim.sams[0]; + let zone = Zone { center: at, radius: ZONE_RADIUS }; + sim.recon.signal(unit, 20, Source::Emission); + sim.recon.signal(unit, 660, Source::Emission); + let signal = sim.recon.mark_for_truth(unit.id).unwrap(); + assert!(signal.looks == 0 && signal.quality == Quality::Coarse); + let pending = look(&sim.sams, &sim.recon, &sim.intel, &zone, 670)[0]; + sim.recon.signal(unit, 720, Source::Emission); + sim.recon.report(pending, 760); + let visual = sim.recon.mark_for_truth(unit.id).unwrap(); + assert_eq!((visual.id, visual.category, visual.looks), (signal.id, Category::Launcher, 1)); + let refined = look(&sim.sams, &sim.recon, &sim.intel, &zone, 1280)[0]; + assert_eq!(refined.quality, Quality::Refined); + sim.recon.report(refined, 1370); + sim.recon.signal(unit, 1380, Source::Emission); + sim.recon.signal(unit, 1380, Source::Launch); + sim.recon.signal(unit, 1380, Source::Launch); + sim.recon.signal(unit, 1400, Source::Launch); + let mark = sim.recon.mark_for_truth(unit.id).unwrap(); + assert_eq!((mark.quality, mark.launches, mark.last_launch), (Quality::Refined, 2, Some(1400))); + sim.tick = 1400; + assert_eq!(sim.enemy_picture().recon[0].launches, 2); + + let text = sim.air_text().unwrap(); + let mut loaded = Sim::new(1); + loaded.restore_air(Sim::parse_air(&text).unwrap().unwrap()); + let loaded = loaded.recon.marks[&mark.id]; + assert_eq!((loaded.launches, loaded.last_launch), (2, Some(1400))); + assert!(loaded.area.distance(mark.area) < 0.02); + + let legacy = text.lines().map(|line| { + if line.starts_with("airreconmark ") { + line.rsplitn(3, ' ').last().unwrap() + } else { + line + } + }).collect::>().join("\n"); + let mut loaded = Sim::new(1); + loaded.restore_air(Sim::parse_air(&legacy).unwrap().unwrap()); + assert_eq!((loaded.recon.marks[&mark.id].launches, loaded.recon.marks[&mark.id].last_launch), (0, None)); + } + // #135: before anything is observed the recon flight and the strike's decisions are a // function of the seed, the objectives and the published plan alone. Two hidden layouts // -- different kinds and places, neither observed -- order the same flight and aims. @@ -1101,6 +1302,8 @@ mod tests { reported: observed, quality, looks: 1, + launches: 0, + last_launch: None, }; r.marks.insert(ID_BASE + 1, mark(ID_BASE + 1, DVec3::ZERO, Category::Radar, Some(battery::RadarRole::Engagement), 100, Quality::Refined)); r.marks.insert(ID_BASE + 2, mark(ID_BASE + 2, DVec3::X, Category::Launcher, None, 100, Quality::Refined)); @@ -1128,7 +1331,7 @@ mod tests { for quality in [Quality::Coarse, Quality::Refined] { for category in [Category::Unknown, Category::Radar, Category::Launcher, Category::Gun, Category::Ew, Category::Support] { for role in [None, Some(battery::RadarRole::Search), Some(battery::RadarRole::Engagement), Some(battery::RadarRole::Height), Some(battery::RadarRole::Multifunction)] { - let m = Mark { id: ID_BASE + 1, area: DVec3::ZERO, radius: COARSE_AREA, category, role, source: Source::Flyby, observed: 0, reported: 0, quality, looks: 1 }; + let m = Mark { id: ID_BASE + 1, area: DVec3::ZERO, radius: COARSE_AREA, category, role, source: Source::Flyby, observed: 0, reported: 0, quality, looks: 1, launches: 0, last_launch: None }; assert_eq!(m.confidence(now), confidence); let (f, q, r) = priority_parts(confidence, quality, category, role); assert_eq!(f * 4 + q * 3 + r, m.priority(now), "{confidence:?} {quality:?} {category:?} {role:?}"); diff --git a/airdef-mod/src/sim/route.rs b/airdef-mod/src/sim/route.rs index 496d21b..242e3da 100644 --- a/airdef-mod/src/sim/route.rs +++ b/airdef-mod/src/sim/route.rs @@ -66,7 +66,7 @@ pub(super) enum Drive { /// Result of checking the vehicle's clearance at its next position. pub(super) enum Clearance { - Clear, + Clear(f64), Blocked, Pending, } @@ -105,20 +105,22 @@ impl Chassis { } /// Every voxel whose square intersects the conservative footprint, including grazing corners. - fn samples(self) -> Vec<(i32, i32)> { - let r = self.radius.ceil() as i32; - (-r..=r).flat_map(|x| (-r..=r).filter_map(move |z| { - let dx = (f64::from(x.abs()) - 0.5).max(0.0); - let dz = (f64::from(z.abs()) - 0.5).max(0.0); + fn samples(self, pos: DVec3) -> impl Iterator { + let min_x = (pos.x - self.radius).floor() as i32; + let max_x = (pos.x + self.radius).floor() as i32; + let min_z = (pos.z - self.radius).floor() as i32; + let max_z = (pos.z + self.radius).floor() as i32; + (min_x..=max_x).flat_map(move |x| (min_z..=max_z).filter_map(move |z| { + let dx = (f64::from(x) - pos.x).max(pos.x - (f64::from(x) + 1.0)).max(0.0); + let dz = (f64::from(z) - pos.z).max(pos.z - (f64::from(z) + 1.0)).max(0.0); (dx * dx + dz * dz <= self.radius * self.radius).then_some((x, z)) - })).collect() + })) } } #[derive(Clone, Copy)] struct Info { h: f32, - ok: bool, } enum Eval { @@ -127,6 +129,45 @@ enum Eval { Pending, } +/// Look below the reachable ceiling rather than lifting a vehicle onto an overhang. +/// The heightmap still distinguishes exposed water from dry solid surfaces. +fn support(ground: &mut Ground, x: i32, z: i32, near: f64, up: f64, down: f64, now: u64) -> Eval { + let column = ground.column(x, z, 1024); + if ground.known.get(&(x, z)).is_some_and(|&(_, tick)| tick == STALE) { + return Eval::Pending; + } + let top = match column { + None => return Eval::Pending, + Some(None) => return Eval::Bad, + Some(Some(top)) => top, + }; + let low = (near - down).ceil() as i32 - 1; + let high = (near + up).floor() as i32 - 1; + let top = top as i32 - 1; + if top < low { + return Eval::Bad; + } + let mut section = None; + match ground.world.road_block(&mut section, x, top, z, now) { + None => return Eval::Pending, + // The motion-blocking map includes the surface of an open body of water. + Some(Some(true)) => {} + Some(_) => return Eval::Bad, + } + if top <= high { + return Eval::Ok((top + 1) as f32); + } + for y in (low..=high).rev() { + match ground.world.road_block(&mut section, x, y, z, now) { + Some(Some(true)) => return Eval::Ok((y + 1) as f32), + Some(Some(false)) => {} + None => return Eval::Pending, + Some(None) => return Eval::Bad, + } + } + Eval::Bad +} + #[derive(PartialEq)] struct Open(f32, (i32, i32)); impl Eq for Open {} @@ -255,6 +296,7 @@ impl Route { self.lo = (self.start.0.min(goal.0) - margin, self.start.1.min(goal.1) - margin); self.hi = (self.start.0.max(goal.0) + margin, self.start.1.max(goal.1) + margin); self.g.clear(); + self.cells.clear(); self.came.clear(); self.open.clear(); self.parked.clear(); @@ -267,7 +309,7 @@ impl Route { self.partial = false; self.work_approach = false; self.work_wait = 0; - self.cells.insert(self.start, Info { h: pos.y as f32, ok: true }); + self.cells.insert(self.start, Info { h: pos.y as f32 }); self.g.insert(self.start, 0.0); let h = self.heur(self.start); self.open.push(Open(h, self.start)); @@ -277,79 +319,60 @@ impl Route { (self.to_goal(c) * 1.1) as f32 } - fn eval(&mut self, ground: &mut Ground, now: u64, c: (i32, i32)) -> Eval { + fn eval(&mut self, ground: &mut Ground, now: u64, c: (i32, i32), near: f64, climb: f64) -> Eval { if let Some(i) = self.cells.get(&c) { - return if i.ok { Eval::Ok(i.h) } else { Eval::Bad }; + return Eval::Ok(i.h); } if self.bad.contains(&c) { return Eval::Bad; } - let p = self.centre(c); - let (x, z) = (p.x.floor() as i32, p.z.floor() as i32); - let verdict = match ground.column(x, z, 1024) { - None => return Eval::Pending, - Some(None) => Info { h: 0.0, ok: false }, - Some(Some(h)) => { - // The height is the top of what blocks motion or holds a fluid: water has nothing solid under it. - let top = DVec3::new(f64::from(x) + 0.5, h, f64::from(z) + 0.5); - match ground.world.sweep(top + DVec3::Y * 0.5, top - DVec3::Y * 0.5, false, now) { - world::Sweep::Hit { .. } => Info { h: h as f32, ok: true }, - world::Sweep::Clear => Info { h: h as f32, ok: false }, - world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => return Eval::Pending, - world::Sweep::Unknown { .. } => Info { h: h as f32, ok: false }, - } - } - }; - if verdict.ok { - match self.clearance_at(ground, DVec3::new(f64::from(x) + 0.5, f64::from(verdict.h), f64::from(z) + 0.5), now) { - Clearance::Clear => {} - Clearance::Blocked => { - let blocked = Info { h: verdict.h, ok: false }; - self.cells.insert(c, blocked); - return Eval::Bad; - } - Clearance::Pending => return Eval::Pending, - } + let verdict = self.road_at(ground, self.centre(c).with_y(near), climb, climb.max(STEP_DOWN), now); + if let Eval::Ok(h) = verdict { + self.cells.insert(c, Info { h }); } - self.cells.insert(c, verdict); - if verdict.ok { Eval::Ok(verdict.h) } else { Eval::Bad } + verdict } - /// Check a chassis-sized footprint against sampled support columns and voxel headroom. - /// Unknown columns or sections are pending so neither search nor motion assumes they are open. - fn clearance_at(&self, ground: &mut Ground, pos: DVec3, now: u64) -> Clearance { - let base = pos.y; + /// Check support and headroom for the complete folded chassis. Unknown or just changed voxels + /// remain pending so neither search nor motion assumes they are open. + fn road_at(&self, ground: &mut Ground, pos: DVec3, climb: f64, drop: f64, now: u64) -> Eval { + let (cx, cz) = (pos.x.floor() as i32, pos.z.floor() as i32); + let base = match support(ground, cx, cz, pos.y, climb, drop, now) { + Eval::Ok(h) => f64::from(h), + other => return other, + }; + let up = if self.truck { 2.0 } else { STEP_UP }; let mut pending = false; - for (dx, dz) in self.chassis.samples() { - let x = pos.x.floor() as i32 + dx; - let z = pos.z.floor() as i32 + dz; - let Some(column) = ground.column(x, z, 1024) else { pending = true; continue }; - let Some(h) = column else { return Clearance::Blocked }; - let dh = h - base; - let up = if self.truck { 2.0 } else { STEP_UP }; - if dh > up || dh < -STEP_DOWN { - return Clearance::Blocked; - } - let top = DVec3::new(f64::from(x) + 0.5, h + 0.05, f64::from(z) + 0.5); - if self.truck && dx == 0 && dz == 0 { - match ground.world.sweep(top, top - DVec3::Y * 0.55, false, now) { - world::Sweep::Hit { .. } => {} - world::Sweep::Clear => return Clearance::Blocked, - _ => { pending = true; continue; } + for (x, z) in self.chassis.samples(pos) { + let h = if x == cx && z == cz { + base + } else { + match support(ground, x, z, base, up, STEP_DOWN, now) { + Eval::Ok(h) => f64::from(h), + Eval::Pending => { pending = true; continue; } + Eval::Bad => return Eval::Bad, + } + }; + let mut section = None; + let top = h.max(base); + for y in top as i32..(top + self.chassis.height).ceil() as i32 { + match ground.world.road_block(&mut section, x, y, z, now) { + Some(Some(false)) => {} + None => { pending = true; break; } + Some(_) => return Eval::Bad, } } - match ground.world.sweep(top, top + DVec3::Y * self.chassis.height, false, now) { - world::Sweep::Clear => {} - world::Sweep::Unknown { pending: true, .. } | world::Sweep::Wait { .. } => pending = true, - world::Sweep::Unknown { .. } | world::Sweep::Hit { .. } => return Clearance::Blocked, - } } - if pending { Clearance::Pending } else { Clearance::Clear } + if pending { Eval::Pending } else { Eval::Ok(base as f32) } } /// Recheck the envelope at the live position, since obstacles may change after planning. pub(super) fn clearance(&self, ground: &mut Ground, pos: DVec3, now: u64) -> Clearance { - self.clearance_at(ground, pos, now) + match self.road_at(ground, pos, STEP_UP, STEP_DOWN, now) { + Eval::Ok(h) => Clearance::Clear(f64::from(h)), + Eval::Bad => Clearance::Blocked, + Eval::Pending => Clearance::Pending, + } } /// Relaxes the edge from the opened cell `c` to `nb`; parks it when the land between isn't known yet. @@ -360,8 +383,10 @@ impl Route { let (di, dj) = (nb.0 - c.0, nb.1 - c.1); let len = if di != 0 && dj != 0 { std::f64::consts::SQRT_2 } else { 1.0 }; let dist = len * f64::from(self.cell); + let slope = self.slope; + let allow = |l: f64| (slope * l).max(STEP_UP); let Some(h0) = self.cells.get(&c).map(|i| f64::from(i.h)) else { return }; - let h1 = match self.eval(ground, now, nb) { + let h1 = match self.eval(ground, now, nb, h0, allow(dist)) { Eval::Ok(h) => f64::from(h), Eval::Bad => return, Eval::Pending => return self.park(c, nb), @@ -369,7 +394,7 @@ impl Route { // A diagonal doesn't cut a corner of something in the way. if di != 0 && dj != 0 { for side in [(c.0 + di, c.1), (c.0, c.1 + dj)] { - match self.eval(ground, now, side) { + match self.eval(ground, now, side, h0, allow(f64::from(self.cell))) { Eval::Ok(h) if (f64::from(h) - h0).abs() <= (self.slope * f64::from(self.cell)).max(STEP_UP) => {} Eval::Pending => return self.park(c, nb), _ => return, @@ -379,13 +404,12 @@ impl Route { // Between the centres: a wall one block thick or a ditch there is what the centres don't show. let (a, b) = (self.centre(c), self.centre(nb)); let mid = (a + b) * 0.5; - let hm = match ground.column(mid.x.floor() as i32, mid.z.floor() as i32, 1024) { - None => return self.park(c, nb), - Some(None) => return, - Some(Some(h)) => h, - }; let half = dist * 0.5; - let allow = |l: f64| (self.slope * l).max(STEP_UP); + let hm = match self.road_at(ground, mid.with_y(h0), allow(half), STEP_DOWN, now) { + Eval::Pending => return self.park(c, nb), + Eval::Bad => return, + Eval::Ok(h) => f64::from(h), + }; if (hm - h0).abs() > allow(half) || (h1 - hm).abs() > allow(half) || hm - h0 < -STEP_DOWN * (half / 2.0).max(1.0) { return; } @@ -411,7 +435,15 @@ impl Route { /// Works on the search: at most `budget` cells. fn search(&mut self, ground: &mut Ground, now: u64, mut budget: usize) { if !self.goal_checked { - match self.eval(ground, now, self.cell_of(self.dest)) { + let x = self.dest.x.floor() as i32; + let z = self.dest.z.floor() as i32; + let goal = match ground.column(x, z, 1024) { + // Orders made while flying above an exposed road still mean the ground below. + Some(Some(top)) => self.road_at(ground, self.dest.with_y(self.dest.y.min(top)), STEP_UP, STEP_DOWN, now), + Some(None) => Eval::Bad, + None => Eval::Pending, + }; + match goal { Eval::Bad => { self.failed = Some(Why::Goal); return; @@ -465,8 +497,7 @@ impl Route { } if self.open.is_empty() { if self.parked.is_empty() { - let goal = self.cell_of(self.dest); - self.failed = Some(if self.slack == 0.0 && !self.cells.get(&goal).is_none_or(|i| i.ok) { Why::Goal } else { Why::NoWay }); + self.failed = Some(Why::NoWay); } else { let since = *self.stuck_since.get_or_insert(now); if now.saturating_sub(since) > WAIT_MAP { @@ -526,13 +557,11 @@ impl Route { let c = self.cell_of(at); if c != self.cell_of(pos) { self.bad.insert(c); - self.cells.insert(c, Info { h: 0.0, ok: false }); } else { // In the cell itself: the stretch ahead, one cell on. let d = horizontal(at - pos).normalize_or(DVec3::X) * f64::from(self.cell); let c = self.cell_of(pos + d); self.bad.insert(c); - self.cells.insert(c, Info { h: 0.0, ok: false }); } self.replans += 1; if self.replans > REPLANS { @@ -737,7 +766,7 @@ mod tests { #[test] fn footprint_checks_voxels_grazed_between_their_centres() { - let cells = Chassis { radius: 2.75, height: 3.0 }.samples(); + let cells: Vec<_> = Chassis { radius: 2.75, height: 3.0 }.samples(DVec3::new(0.5, 64.0, 0.5)).collect(); assert!(cells.contains(&(3, 1)), "the body reaches the near corner of this voxel"); assert!(cells.contains(&(-3, -1))); assert!(!cells.contains(&(3, 3))); @@ -761,6 +790,82 @@ mod tests { ground.world.serve(src, sections, now); } + #[derive(Default)] + struct Overhang { + lowered: bool, + } + + impl Overhang { + fn spans(x: i32, z: i32) -> bool { + (16..32).contains(&x) && (-120..120).contains(&z) + } + + fn answer(&self, ground: &mut Ground, tick: u64) { + let columns = ground.take_wanted().into_iter().map(|(x, z)| { + (x, z, if Self::spans(x, z) { 73 } else { 64 }) + }).collect(); + ground.answer(columns, tick); + let sections = ground.world.take_wanted(tick); + ground.world.serve(self, sections, tick); + } + } + + impl world::WorldSource for Overhang { + fn solid(&self, x: i32, y: i32, z: i32) -> Option { + Some(y < 64 || Self::spans(x, z) && (y == 72 || self.lowered && y == 65)) + } + } + + fn march_under_overhang(lower_after_planning: bool) -> (Sim, bool, bool) { + let mut src = Overhang::default(); + let mut sim = Sim::new(3); + let mut ground = Ground::default(); + let mut out = Out::default(); + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::S400, DVec3::new(0.5, 64.0, 0.5), 0.0)); + assert!(sim.order_move(0, DVec3::new(60.5, 64.0, 0.5))); + let mut crossed = false; + let mut replanned = false; + for _ in 0..4000 { + sim.tick += 1; + src.answer(&mut ground, sim.tick); + sim.step_moves(&mut ground, &mut out); + let unit = &sim.sams[0]; + if lower_after_planning && !src.lowered && unit.pos.x > 5.0 { + assert!(sim.routes.map.get(&id).is_some_and(|route| route.phase == Phase::Follow)); + src.lowered = true; + // A new block under the deck changes the navigable road without changing the heightmap. + let changed: Vec<_> = (-8..8).map(|z| (1, 4, z)).collect(); + ground.world.changed(1, false, &changed); + } + if src.lowered { + replanned |= sim.routes.map.get(&id).is_some_and(|route| route.replans > 0); + assert!(unit.pos.x + Chassis::for_kind(unit.kind).radius <= 16.0, "entered the changed ceiling at {:?}", unit.pos); + } + if Overhang::spans(unit.pos.x.floor() as i32, unit.pos.z.floor() as i32) { + assert_eq!(unit.pos.y, 64.0); + crossed = true; + } + if !unit.moving() { + break; + } + } + (sim, crossed, replanned) + } + + #[test] + fn a_vehicle_can_follow_the_lower_road_under_a_bridge_deck() { + let (sim, crossed, _) = march_under_overhang(false); + let unit = &sim.sams[0]; + assert!(crossed && !unit.moving() && unit.pos.x > 59.0, "ended at {:?}", unit.pos); + } + + #[test] + fn a_new_low_ceiling_on_a_planned_road_stops_the_vehicle_and_replans() { + let (sim, crossed, replanned) = march_under_overhang(true); + assert!(replanned && !crossed && !sim.sams[0].moving(), "ended at {:?}", sim.sams[0].pos); + } + #[test] fn a_supply_truck_builds_a_bridge_then_crosses_it() { struct Creek(HashSet<(i32, i32)>); @@ -885,6 +990,13 @@ mod tests { assert!(!s.moving() && s.pos.distance(DVec3::new(100.0, 64.0, 30.5)) < 3.0, "pos={:?} state={:?} messages={:?} route={route:?}", s.pos, s.state, out.messages); } + #[test] + fn an_order_from_above_an_open_road_still_reaches_the_ground() { + let (sim, _, _) = march(|_, _| 64, |_, _| 64, DVec3::new(30.5, 110.0, 0.5), 1500); + let unit = &sim.sams[0]; + assert!(!unit.moving() && unit.pos.distance(DVec3::new(30.5, 64.0, 0.5)) < 1.0, "ended at {:?}", unit.pos); + } + // A point-column route fits through this one-block slit, but the S-400 chassis does not. #[test] fn s400_rejects_a_one_block_corridor() { diff --git a/airdef-mod/src/sim/sight.rs b/airdef-mod/src/sim/sight.rs index cfd1a0c..2265dce 100644 --- a/airdef-mod/src/sim/sight.rs +++ b/airdef-mod/src/sim/sight.rs @@ -612,12 +612,12 @@ impl Sim { } // The network: every unit gets the tracks the radars within data-link range measured themselves, // with the time they were measured: a relayed track is never fresher than its measurement. - // Fictional passive observation: hostile aircraft within 1600 blocks fix an emitting radar + // Fictional passive observation: hostile aircraft within 1600 blocks report an emitter's area // every 20 ticks. Silence leaves the previous report to age normally. if now % 20 == 0 { for s in self.sams.iter().filter(|s| s.radar_up()) { - if self.drones.iter().any(|d| d.alive() && d.pos.distance(s.pos) <= 1600.0) { - self.intel.observe(s, now, ew::Seen::Emission); + if recon::has_signal_witness(&self.drones, s.pos) { + self.recon.signal(s, now, recon::Source::Emission); } } } diff --git a/airdef-mod/src/sim/smart_tests.rs b/airdef-mod/src/sim/smart_tests.rs index 5f9e6d2..6fd1113 100644 --- a/airdef-mod/src/sim/smart_tests.rs +++ b/airdef-mod/src/sim/smart_tests.rs @@ -20,6 +20,8 @@ fn mark(id: u32, at: DVec3, category: recon::Category, observed: u64) -> recon:: reported: observed, quality: recon::Quality::Coarse, looks: 1, + launches: 0, + last_launch: None, } } diff --git a/airdef-mod/src/sim/specs_generated.rs b/airdef-mod/src/sim/specs_generated.rs index b43d8cf..4047ee2 100644 --- a/airdef-mod/src/sim/specs_generated.rs +++ b/airdef-mod/src/sim/specs_generated.rs @@ -20,6 +20,36 @@ const HANDOVER: f64 = 10.0; const TRUCK_LOAD: u32 = 2; const STOCK_LIMIT: u32 = 1000000; +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +pub enum DroneKind { + Shahed, + Geran3, + Lancet, + Gerbera, + Kh101, + Kalibr, + Kh22, + Zircon, + Iskander, + Kinzhal, + Oreshnik, + OreshnikBlock, + OreshnikSub, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +pub enum MissileKind { + Pac3, + M57e6, + M48n6, + M77n6, + IrisT, + Amraam, + M9m317, + M9m338, + P1sun, +} + const DRONE_SPEC_SHAHED: DroneSpec = DroneSpec { name: "Шахед-136", key: "shahed", @@ -30,6 +60,7 @@ const DRONE_SPEC_SHAHED: DroneSpec = DroneSpec { clearance: 18.0, dive: 32.0, warhead: 3, + accuracy: (1.2, 0.03), scale: 1.3, engine: Engine::Prop(1.34, 1.0), decoy: false, @@ -51,6 +82,7 @@ const DRONE_SPEC_GERAN3: DroneSpec = DroneSpec { clearance: 18.0, dive: 50.0, warhead: 2, + accuracy: (1.0, 0.03), scale: 1.15, engine: Engine::Jet(0.34, 1.55, 1.0), decoy: false, @@ -72,6 +104,7 @@ const DRONE_SPEC_LANCET: DroneSpec = DroneSpec { clearance: 10.0, dive: 38.0, warhead: 1, + accuracy: (0.8, 0.02), scale: 0.9, engine: Engine::Prop(0.93, 0.55), decoy: false, @@ -93,6 +126,7 @@ const DRONE_SPEC_GERBERA: DroneSpec = DroneSpec { clearance: 15.0, dive: 30.0, warhead: 0, + accuracy: (1.5, 0.04), scale: 1.1, engine: Engine::Prop(1.03, 0.9), decoy: true, @@ -114,6 +148,7 @@ const DRONE_SPEC_KH101: DroneSpec = DroneSpec { clearance: 12.0, dive: 26.0, warhead: 6, + accuracy: (1.3, 0.05), scale: 1.6, engine: Engine::Jet(-0.27, 1.4, 0.6), decoy: false, @@ -135,6 +170,7 @@ const DRONE_SPEC_KALIBR: DroneSpec = DroneSpec { clearance: 15.0, dive: 26.0, warhead: 5, + accuracy: (1.3, 0.05), scale: 1.5, engine: Engine::Jet(-0.2, 1.5, 0.6), decoy: false, @@ -156,6 +192,7 @@ const DRONE_SPEC_KH22: DroneSpec = DroneSpec { clearance: 40.0, dive: 150.0, warhead: 7, + accuracy: (1.6, 0.06), scale: 1.8, engine: Engine::Rocket(1.5, 1.3), decoy: false, @@ -177,6 +214,7 @@ const DRONE_SPEC_ZIRCON: DroneSpec = DroneSpec { clearance: 30.0, dive: 110.0, warhead: 6, + accuracy: (1.5, 0.06), scale: 1.4, engine: Engine::Rocket(1.5, 1.1), decoy: false, @@ -198,6 +236,7 @@ const DRONE_SPEC_ISKANDER: DroneSpec = DroneSpec { clearance: 0.0, dive: 0.0, warhead: 8, + accuracy: (1.4, 0.06), scale: 1.8, engine: Engine::Rocket(1.5, 1.6), decoy: false, @@ -219,6 +258,7 @@ const DRONE_SPEC_KINZHAL: DroneSpec = DroneSpec { clearance: 0.0, dive: 0.0, warhead: 8, + accuracy: (1.5, 0.06), scale: 1.7, engine: Engine::Rocket(1.5, 1.5), decoy: false, @@ -240,6 +280,7 @@ const DRONE_SPEC_ORESHNIK: DroneSpec = DroneSpec { clearance: 0.0, dive: 0.0, warhead: 0, + accuracy: (1.6, 0.08), scale: 2.6, engine: Engine::Rocket(1.5, 2.4), decoy: false, @@ -261,6 +302,7 @@ const DRONE_SPEC_ORESHNIKBLOCK: DroneSpec = DroneSpec { clearance: 0.0, dive: 0.0, warhead: 4, + accuracy: (1.6, 0.08), scale: 1.6, engine: Engine::Rocket(1.0, 1.0), decoy: false, @@ -282,6 +324,7 @@ const DRONE_SPEC_ORESHNIKSUB: DroneSpec = DroneSpec { clearance: 0.0, dive: 0.0, warhead: 3, + accuracy: (1.6, 0.08), scale: 1.1, engine: Engine::Rocket(1.0, 1.0), decoy: false, @@ -295,6 +338,7 @@ const DRONE_SPEC_ORESHNIKSUB: DroneSpec = DroneSpec { const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec { model: "airdef:pac3", + launcher_blast: 0.8, speed: 5.5, accel: 0.35, turn: 0.3, @@ -315,6 +359,7 @@ const MISSILE_SPEC_PAC3: MissileSpec = MissileSpec { const MISSILE_SPEC_M57E6: MissileSpec = MissileSpec { model: "airdef:m57e6", + launcher_blast: 0.45, speed: 5.0, accel: 0.5, turn: 0.32, @@ -335,6 +380,7 @@ const MISSILE_SPEC_M57E6: MissileSpec = MissileSpec { const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec { model: "airdef:m48n6", + launcher_blast: 1.8, speed: 7.0, accel: 0.5, turn: 0.22, @@ -355,6 +401,7 @@ const MISSILE_SPEC_M48N6: MissileSpec = MissileSpec { const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec { model: "airdef:m77n6", + launcher_blast: 2.2, speed: 9.0, accel: 0.6, turn: 0.22, @@ -375,6 +422,7 @@ const MISSILE_SPEC_M77N6: MissileSpec = MissileSpec { const MISSILE_SPEC_IRIST: MissileSpec = MissileSpec { model: "airdef:irist_missile", + launcher_blast: 0.6, speed: 7.0, accel: 0.5, turn: 0.35, @@ -395,6 +443,7 @@ const MISSILE_SPEC_IRIST: MissileSpec = MissileSpec { const MISSILE_SPEC_AMRAAM: MissileSpec = MissileSpec { model: "airdef:amraam_missile", + launcher_blast: 0.5, speed: 6.0, accel: 0.45, turn: 0.3, @@ -415,6 +464,7 @@ const MISSILE_SPEC_AMRAAM: MissileSpec = MissileSpec { const MISSILE_SPEC_M9M317: MissileSpec = MissileSpec { model: "airdef:m48n6", + launcher_blast: 1.2, speed: 6.5, accel: 0.5, turn: 0.25, @@ -435,6 +485,7 @@ const MISSILE_SPEC_M9M317: MissileSpec = MissileSpec { const MISSILE_SPEC_M9M338: MissileSpec = MissileSpec { model: "airdef:m57e6", + launcher_blast: 0.4, speed: 5.5, accel: 0.6, turn: 0.4, @@ -455,6 +506,7 @@ const MISSILE_SPEC_M9M338: MissileSpec = MissileSpec { const MISSILE_SPEC_P1SUN: MissileSpec = MissileSpec { model: "airdef:p1sun", + launcher_blast: 0.1, speed: 2.8, accel: 0.12, turn: 0.3, @@ -474,6 +526,22 @@ const MISSILE_SPEC_P1SUN: MissileSpec = MissileSpec { }; impl DroneKind { + pub const ALL: [DroneKind; 13] = [ + DroneKind::Shahed, + DroneKind::Geran3, + DroneKind::Lancet, + DroneKind::Gerbera, + DroneKind::Kh101, + DroneKind::Kalibr, + DroneKind::Kh22, + DroneKind::Zircon, + DroneKind::Iskander, + DroneKind::Kinzhal, + DroneKind::Oreshnik, + DroneKind::OreshnikBlock, + DroneKind::OreshnikSub, + ]; + /// Its row of numbers from `catalog/specs.json`. pub fn spec(self) -> &'static DroneSpec { match self { diff --git a/airdef-mod/src/sim/strike.rs b/airdef-mod/src/sim/strike.rs index 8ea5a35..7e1ae54 100644 --- a/airdef-mod/src/sim/strike.rs +++ b/airdef-mod/src/sim/strike.rs @@ -730,8 +730,11 @@ impl Sim { && s.alive() && !s.moving() && s.reloading == 0 && s.cooldown == 0 && s.part(Part::Launcher) > 0.0 && s.ground_rounds > u32::from(s.ground_return) && s.preparing.is_none() && dist <= TUNE.range) .then_some((i, dist)) - }).min_by(|(i,a), (j,b)| self.sams[*j].ground_rounds.cmp(&self.sams[*i].ground_rounds) - .then(a.total_cmp(b)).then(self.sams[*i].id.cmp(&self.sams[*j].id))) + }).min_by(|(i,a), (j,b)| { + let available = |s: &Sam| s.ground_rounds.saturating_sub(u32::from(s.ground_return)); + available(&self.sams[*j]).cmp(&available(&self.sams[*i])) + .then(a.total_cmp(b)).then(self.sams[*i].id.cmp(&self.sams[*j].id)) + }) .ok_or("Нет готового С-400 с загруженной RM48U в игровой дальности; подготовьте боезапас у склада")?; let sam = &mut self.sams[i]; sam.sync_tube_cells(); @@ -774,8 +777,9 @@ impl Sim { sam.launched = 12; sam.fired += 1; let dist = (p.aim - DVec2::new(sam.pos.x, sam.pos.z)).length(); - // The launch betrays the carrier: the enemy saw it fire, no more than that. - self.intel.observe(&self.sams[i], self.tick, ew::Seen::Launch); + if recon::has_signal_witness(&self.drones, sam.pos) { + self.recon.signal(sam, self.tick, recon::Source::Launch); + } self.strikes.fired += 1; self.strikes.next += 1; // The counted flight includes the unlit ejection: the missile is honest about @@ -1396,6 +1400,23 @@ mod tests { assert!(sim.sams[0].ground_return); } + #[test] + fn carrier_selection_ranks_unreserved_rounds_before_distance_and_id() { + let mut sim = Sim::new(11); + let site = fixed_site(&mut sim, DVec3::new(0.0, 64.0, 500.0), 0); + for (id, z, reserved) in [(1, 400.0, true), (2, 200.0, false)] { + let mut sam = Sam::new(id, SamKind::S400, DVec3::new(0.0, 0.0, z), 0.0); + sam.missiles = 2; sam.ground_rounds = 2; sam.ground_return = reserved; sam.cooldown = 0; + sim.sams.push(sam); + } + let mut out = Out::default(); + sim.order_strike(site, DVec3::ZERO, &mut out).unwrap(); + assert_eq!(sim.strikes.pending[0].carrier, 2); + sim.tick += launch::OPEN_TICKS; + sim.prepare_ground_strikes(&mut out); + assert_eq!((sim.sams[0].ground_rounds, sim.sams[1].ground_rounds), (2, 1)); + } + #[test] fn ground_orders_reserve_the_carrier_and_target_until_ejection() { let mut sim = Sim::new(11); diff --git a/airdef-mod/src/sim/unit_specs_generated.rs b/airdef-mod/src/sim/unit_specs_generated.rs index 982ac55..1731876 100644 --- a/airdef-mod/src/sim/unit_specs_generated.rs +++ b/airdef-mod/src/sim/unit_specs_generated.rs @@ -5,10 +5,32 @@ const NAMED_BATTERY_RADAR: &[(&str, f64, f64)] = &[("airdef:radar_trailer", 0.0, const NAMED_BATTERY_SPINNER: Option<(&str, f64, f64, f64, f64)> = Some(("airdef:radar_panel", 0.9, 4.2, 0.9, -0.3)); const NAMED_TUBE_PIVOT: DVec3 = DVec3::new(0.0, -0.5, 1.5); +#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] +pub enum SamKind { + Patriot, + Gepard, + Pantsir, + S400, + S500, + IrisT, + Nasams, + Buk, + Tor, + P1sun, + Radar, + Depot, + Tzm, + Ew, + Light, + Optical, +} + const UNIT_SPEC_PATRIOT: SamSpec = SamSpec { name: "Patriot", key: "patriot", + village_cost: 5, missile: Some(MissileLoad { kind: MissileKind::Pac3, magazine: 4, min: 10.0, max: 950.0, interval: 16 }), + ground_strike: None, gun: None, reload: 220, scale: 1.3, @@ -33,7 +55,9 @@ const UNIT_SPEC_PATRIOT: SamSpec = SamSpec { const UNIT_SPEC_GEPARD: SamSpec = SamSpec { name: "Гепард", key: "gepard", + village_cost: 2, missile: None, + ground_strike: None, gun: Some(GunSpec { range: 180.0, track: 260.0, p: 0.3, bursts: 160, shell: 10.0, slew: (0.22, 0.16) }), reload: 160, scale: 1.25, @@ -58,7 +82,9 @@ const UNIT_SPEC_GEPARD: SamSpec = SamSpec { const UNIT_SPEC_PANTSIR: SamSpec = SamSpec { name: "Панцирь-С1", key: "pantsir", + village_cost: 3, missile: Some(MissileLoad { kind: MissileKind::M57e6, magazine: 12, min: 25.0, max: 330.0, interval: 14 }), + ground_strike: None, gun: Some(GunSpec { range: 125.0, track: 185.0, p: 0.25, bursts: 140, shell: 9.0, slew: (0.25, 0.18) }), reload: 280, scale: 1.3, @@ -83,7 +109,9 @@ const UNIT_SPEC_PANTSIR: SamSpec = SamSpec { const UNIT_SPEC_S400: SamSpec = SamSpec { name: "С-400", key: "s400", + village_cost: 5, missile: Some(MissileLoad { kind: MissileKind::M48n6, magazine: 4, min: 30.0, max: 1300.0, interval: 20 }), + ground_strike: Some(catalog::GroundStrike::Rm48uGame), gun: None, reload: 420, scale: 1.5, @@ -108,7 +136,9 @@ const UNIT_SPEC_S400: SamSpec = SamSpec { const UNIT_SPEC_S500: SamSpec = SamSpec { name: "С-500", key: "s500", + village_cost: 6, missile: Some(MissileLoad { kind: MissileKind::M77n6, magazine: 2, min: 40.0, max: 1850.0, interval: 20 }), + ground_strike: None, gun: None, reload: 520, scale: 1.6, @@ -133,7 +163,9 @@ const UNIT_SPEC_S500: SamSpec = SamSpec { const UNIT_SPEC_IRIST: SamSpec = SamSpec { name: "IRIS-T SLM", key: "irist", + village_cost: 4, missile: Some(MissileLoad { kind: MissileKind::IrisT, magazine: 8, min: 15.0, max: 600.0, interval: 10 }), + ground_strike: None, gun: None, reload: 300, scale: 1.4, @@ -158,7 +190,9 @@ const UNIT_SPEC_IRIST: SamSpec = SamSpec { const UNIT_SPEC_NASAMS: SamSpec = SamSpec { name: "NASAMS", key: "nasams", + village_cost: 4, missile: Some(MissileLoad { kind: MissileKind::Amraam, magazine: 6, min: 10.0, max: 450.0, interval: 14 }), + ground_strike: None, gun: None, reload: 260, scale: 1.3, @@ -183,7 +217,9 @@ const UNIT_SPEC_NASAMS: SamSpec = SamSpec { const UNIT_SPEC_BUK: SamSpec = SamSpec { name: "Бук-М2", key: "buk", + village_cost: 4, missile: Some(MissileLoad { kind: MissileKind::M9m317, magazine: 4, min: 20.0, max: 675.0, interval: 18 }), + ground_strike: None, gun: None, reload: 400, scale: 1.4, @@ -208,7 +244,9 @@ const UNIT_SPEC_BUK: SamSpec = SamSpec { const UNIT_SPEC_TOR: SamSpec = SamSpec { name: "Тор-М2", key: "tor", + village_cost: 3, missile: Some(MissileLoad { kind: MissileKind::M9m338, magazine: 8, min: 8.0, max: 350.0, interval: 8 }), + ground_strike: None, gun: None, reload: 300, scale: 1.3, @@ -233,7 +271,9 @@ const UNIT_SPEC_TOR: SamSpec = SamSpec { const UNIT_SPEC_P1SUN: SamSpec = SamSpec { name: "P1-SUN", key: "p1sun", + village_cost: 3, missile: Some(MissileLoad { kind: MissileKind::P1sun, magazine: 8, min: 5.0, max: 675.0, interval: 12 }), + ground_strike: None, gun: None, reload: 240, scale: 1.1, @@ -258,7 +298,9 @@ const UNIT_SPEC_P1SUN: SamSpec = SamSpec { const UNIT_SPEC_RADAR: SamSpec = SamSpec { name: "РЛС дальнего обнаружения", key: "radar", + village_cost: 2, missile: None, + ground_strike: None, gun: None, reload: 0, scale: 1.5, @@ -283,7 +325,9 @@ const UNIT_SPEC_RADAR: SamSpec = SamSpec { const UNIT_SPEC_DEPOT: SamSpec = SamSpec { name: "Склад боеприпасов", key: "depot", + village_cost: 2, missile: None, + ground_strike: None, gun: None, reload: 0, scale: 1.5, @@ -308,7 +352,9 @@ const UNIT_SPEC_DEPOT: SamSpec = SamSpec { const UNIT_SPEC_TZM: SamSpec = SamSpec { name: "ТЗМ", key: "tzm", + village_cost: 2, missile: None, + ground_strike: None, gun: None, reload: 0, scale: 1.3, @@ -333,7 +379,9 @@ const UNIT_SPEC_TZM: SamSpec = SamSpec { const UNIT_SPEC_EW: SamSpec = SamSpec { name: "Станция РЭБ", key: "ew", + village_cost: 2, missile: None, + ground_strike: None, gun: None, reload: 0, scale: 1.3, @@ -358,7 +406,9 @@ const UNIT_SPEC_EW: SamSpec = SamSpec { const UNIT_SPEC_LIGHT: SamSpec = SamSpec { name: "Прожектор", key: "light", + village_cost: 1, missile: None, + ground_strike: None, gun: None, reload: 0, scale: 1.2, @@ -383,7 +433,9 @@ const UNIT_SPEC_LIGHT: SamSpec = SamSpec { const UNIT_SPEC_OPTICAL: SamSpec = SamSpec { name: "Оптический пост", key: "optical", + village_cost: 1, missile: None, + ground_strike: None, gun: None, reload: 0, scale: 1.0, @@ -406,6 +458,19 @@ const UNIT_SPEC_OPTICAL: SamSpec = SamSpec { }; impl SamKind { + pub const ARMED: [SamKind; 10] = [ + SamKind::Patriot, + SamKind::Gepard, + SamKind::Pantsir, + SamKind::S400, + SamKind::S500, + SamKind::IrisT, + SamKind::Nasams, + SamKind::Buk, + SamKind::Tor, + SamKind::P1sun, + ]; + /// Its row of numbers from `catalog/specs.json`. pub fn spec(self) -> &'static SamSpec { match self { diff --git a/airdef-mod/src/sim/units.rs b/airdef-mod/src/sim/units.rs index 8a6c863..1fa636d 100644 --- a/airdef-mod/src/sim/units.rs +++ b/airdef-mod/src/sim/units.rs @@ -5,32 +5,6 @@ //! wrecks, saving and move orders; only what they carry differs. use super::*; -#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] -pub enum SamKind { - Patriot, - Gepard, - Pantsir, - S400, - S500, - IrisT, - Nasams, - Buk, - Tor, - P1sun, - /// A long-range search radar: no weapons, it feeds the network. - Radar, - /// An ammunition depot: the reload trucks fill up there. - Depot, - /// A transport-loader: drives missiles from a depot to the systems. - Tzm, - /// An electronic-warfare station: jams the drones' navigation while switched on. - Ew, - /// A searchlight: lights up targets at night for the guns. - Light, - /// A passive optical observation post: no radar, no weapon, one class observation at a time (#136). - Optical, -} - /// How a vehicle is put together: how its launcher or turret moves and is drawn. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Family { @@ -112,7 +86,10 @@ pub(super) struct Drive { pub struct SamSpec { pub name: &'static str, pub key: &'static str, + /// Points to deploy this unit in the village campaign. + pub village_cost: u32, pub(super) missile: Option, + pub(super) ground_strike: Option, pub(super) gun: Option, pub(super) reload: u32, pub(super) scale: f64, @@ -150,19 +127,6 @@ include!("unit_specs_generated.rs"); impl SamKind { pub const ALL: [SamKind; super::catalog::UNIT_COUNT] = super::catalog::UNIT_KINDS; - /// The ones that shoot (the roles menu lists these). - pub const ARMED: [SamKind; 10] = [ - SamKind::Patriot, - SamKind::Gepard, - SamKind::Pantsir, - SamKind::S400, - SamKind::S500, - SamKind::IrisT, - SamKind::Nasams, - SamKind::Buk, - SamKind::Tor, - SamKind::P1sun, - ]; pub fn name(self) -> &'static str { self.spec().name } @@ -185,6 +149,9 @@ impl SamKind { pub fn missile_magazine(self) -> Option { self.spec().missile.as_ref().map(|m| m.magazine) } + pub fn supports_rm48u(self) -> bool { + self.spec().ground_strike == Some(catalog::GroundStrike::Rm48uGame) + } /// Whether it has a gun (its bursts are read by the status line). pub fn has_gun(self) -> bool { self.spec().gun.is_some() diff --git a/airdef-mod/src/sim/world.rs b/airdef-mod/src/sim/world.rs index 2d051cb..2f059d2 100644 --- a/airdef-mod/src/sim/world.rs +++ b/airdef-mod/src/sim/world.rs @@ -36,6 +36,20 @@ pub enum Fill { Mixed(Box<[u8; 512]>), } +impl Fill { + fn block(&self, x: i32, y: i32, z: i32) -> Option { + match self { + Fill::Unknown => None, + Fill::Empty => Some(false), + Fill::Full => Some(true), + Fill::Mixed(bits) => { + let i = ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize; + Some(bits[i >> 3] >> (i & 7) & 1 != 0) + } + } + } +} + /// An answer for a section, as the game gives it. pub struct SectionAnswer { pub sec: Sec, @@ -530,19 +544,23 @@ impl WorldCache { self.unread_pending = true; return None; }; - match &entry.fill { - Fill::Unknown => { - // Asked and answered unknown: no chunk there. Asked again (or not at all yet): waiting. - self.unread_pending = entry.stale && entry.since == 0; - None - } - Fill::Empty => Some(false), - Fill::Full => Some(true), - Fill::Mixed(bits) => { - let i = ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize; - Some(bits[i >> 3] >> (i & 7) & 1 != 0) - } + if entry.fill == Fill::Unknown { + // Asked and answered unknown: no chunk there. Asked again (or not at all yet): waiting. + self.unread_pending = entry.stale && entry.since == 0; } + entry.fill.block(x, y, z) + } + + /// Vehicle motion waits for a new mask after a notified block change. As with the height map, + /// `None` means pending and `Some(None)` means the host could not read this column. + pub(super) fn road_block(&mut self, last: &mut Option, x: i32, y: i32, z: i32, now: u64) -> Option> { + let s = sec_of(x, y, z); + if *last != Some(s) { + *last = Some(s); + self.touch(s, true, now); + } + let entry = self.secs.get(&s)?; + (!entry.stale).then(|| entry.fill.block(x, y, z)) } /// Whether the block is known to hold no solid block, with the sky above it diff --git a/airdef-mod/src/village.rs b/airdef-mod/src/village.rs index 41c13fd..882ee56 100644 --- a/airdef-mod/src/village.rs +++ b/airdef-mod/src/village.rs @@ -105,14 +105,7 @@ pub(crate) struct Village { } pub(crate) fn cost(kind: SamKind) -> u32 { - match kind { - SamKind::Light | SamKind::Optical => 1, - SamKind::Gepard | SamKind::Radar | SamKind::Depot | SamKind::Tzm | SamKind::Ew => 2, - SamKind::Pantsir | SamKind::Tor | SamKind::P1sun => 3, - SamKind::IrisT | SamKind::Nasams | SamKind::Buk => 4, - SamKind::Patriot | SamKind::S400 => 5, - SamKind::S500 => 6, - } + kind.spec().village_cost } pub(crate) fn active(village: Option) -> bool { diff --git a/airdef-mod/tests/budgets/wasm_flat_budget.toml b/airdef-mod/tests/budgets/wasm_flat_budget.toml index 3f08ab7..2857163 100644 --- a/airdef-mod/tests/budgets/wasm_flat_budget.toml +++ b/airdef-mod/tests/budgets/wasm_flat_budget.toml @@ -1067,4 +1067,5 @@ frames = 100 command = "airdef stats" # The two late Smart raids also run with finite stock. At this point the # launchers still have no supply depot. -expect.feedback = "В воздухе: 24, ракет: 0, ПВО: 68, сбито: 143, поражений: 2688, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 7307 секций (342 КБ), запросов 16768, неизвестно 0, лучей 400901 (ударов 2567, неизв. 971), клеток 3894960; взрывы в блоках: 2783 (подтверждено 0, без перемен 145, нет чанка 2638), чужих ответов 0" +# The late Smart orders use the coarse observation picture from #135. +expect.feedback = "В воздухе: 25, ракет: 0, ПВО: 68, сбито: 142, поражений: 2692, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 7327 секций (343 КБ), запросов 16853, неизвестно 0, лучей 399783 (ударов 2350, неизв. 904), клеток 3864646; взрывы в блоках: 2792 (подтверждено 0, без перемен 155, нет чанка 2637), чужих ответов 0" diff --git a/catalog/content.json b/catalog/content.json index 2bb4429..2f0d457 100644 --- a/catalog/content.json +++ b/catalog/content.json @@ -1,137 +1,4 @@ { - "aircraft": [ - { - "kind": "Gerbera", - "item": null, - "raid": true - }, - { - "kind": "Shahed", - "item": "launch_shahed", - "raid": true - }, - { - "kind": "Geran3", - "item": "launch_geran3", - "raid": true - }, - { - "kind": "Lancet", - "item": "launch_lancet", - "raid": true - }, - { - "kind": "Kh101", - "item": "launch_kh101", - "raid": true - }, - { - "kind": "Kalibr", - "item": "launch_kalibr", - "raid": true - }, - { - "kind": "Kh22", - "item": "launch_kh22", - "raid": true - }, - { - "kind": "Zircon", - "item": "launch_zircon", - "raid": true - }, - { - "kind": "Iskander", - "item": "launch_iskander", - "raid": true - }, - { - "kind": "Kinzhal", - "item": "launch_kinzhal", - "raid": true - }, - { - "kind": "Oreshnik", - "item": "launch_oreshnik", - "raid": true - }, - { - "kind": "OreshnikBlock", - "item": null, - "raid": false - }, - { - "kind": "OreshnikSub", - "item": null, - "raid": false - } - ], - "units": [ - { - "kind": "Patriot", - "item": "deploy_patriot" - }, - { - "kind": "Gepard", - "item": "deploy_gepard" - }, - { - "kind": "Pantsir", - "item": "deploy_pantsir" - }, - { - "kind": "S400", - "item": "deploy_s400" - }, - { - "kind": "S500", - "item": "deploy_s500" - }, - { - "kind": "IrisT", - "item": "deploy_irist" - }, - { - "kind": "Nasams", - "item": "deploy_nasams" - }, - { - "kind": "Buk", - "item": "deploy_buk" - }, - { - "kind": "Tor", - "item": "deploy_tor" - }, - { - "kind": "P1sun", - "item": "deploy_p1sun" - }, - { - "kind": "Radar", - "item": "deploy_radar" - }, - { - "kind": "Depot", - "item": "deploy_depot" - }, - { - "kind": "Tzm", - "item": "deploy_tzm" - }, - { - "kind": "Ew", - "item": "deploy_ew" - }, - { - "kind": "Light", - "item": "deploy_light" - }, - { - "kind": "Optical", - "item": "deploy_optical" - } - ], "variants": [ { "id": "s400_launcher", @@ -184,240 +51,6 @@ 50 ] }, - { - "id": "launch_shahed", - "title": "Пуск: Шахед-136", - "color": [ - 90, - 92, - 96 - ] - }, - { - "id": "launch_geran3", - "title": "Пуск: Герань-3", - "color": [ - 30, - 30, - 34 - ] - }, - { - "id": "deploy_patriot", - "title": "Развернуть Patriot", - "color": [ - 76, - 86, - 58 - ] - }, - { - "id": "deploy_gepard", - "title": "Развернуть Гепард", - "color": [ - 104, - 84, - 54 - ] - }, - { - "id": "deploy_pantsir", - "title": "Развернуть Панцирь-С1", - "color": [ - 82, - 96, - 60 - ] - }, - { - "id": "deploy_s400", - "title": "Развернуть С-400", - "color": [ - 60, - 80, - 50 - ] - }, - { - "id": "deploy_s500", - "title": "Развернуть С-500", - "color": [ - 108, - 110, - 80 - ] - }, - { - "id": "launch_lancet", - "title": "Пуск: Ланцет-3", - "color": [ - 70, - 78, - 66 - ] - }, - { - "id": "launch_kh101", - "title": "Пуск: Х-101", - "color": [ - 84, - 88, - 92 - ] - }, - { - "id": "launch_kalibr", - "title": "Пуск: Калибр", - "color": [ - 150, - 154, - 156 - ] - }, - { - "id": "launch_kh22", - "title": "Пуск: Х-22", - "color": [ - 226, - 228, - 222 - ] - }, - { - "id": "launch_zircon", - "title": "Пуск: Циркон", - "color": [ - 52, - 54, - 52 - ] - }, - { - "id": "launch_iskander", - "title": "Пуск: Искандер-М", - "color": [ - 108, - 110, - 80 - ] - }, - { - "id": "launch_kinzhal", - "title": "Пуск: Кинжал", - "color": [ - 60, - 62, - 60 - ] - }, - { - "id": "launch_oreshnik", - "title": "Пуск: Орешник", - "color": [ - 230, - 120, - 40 - ] - }, - { - "id": "deploy_irist", - "title": "Развернуть IRIS-T SLM", - "color": [ - 76, - 86, - 58 - ] - }, - { - "id": "deploy_nasams", - "title": "Развернуть NASAMS", - "color": [ - 76, - 86, - 58 - ] - }, - { - "id": "deploy_buk", - "title": "Развернуть Бук-М2", - "color": [ - 82, - 96, - 60 - ] - }, - { - "id": "deploy_tor", - "title": "Развернуть Тор-М2", - "color": [ - 108, - 110, - 80 - ] - }, - { - "id": "deploy_p1sun", - "title": "Развернуть P1-SUN", - "color": [ - 52, - 54, - 52 - ] - }, - { - "id": "deploy_radar", - "title": "Развернуть РЛС дальнего обнаружения", - "color": [ - 108, - 110, - 80 - ] - }, - { - "id": "deploy_depot", - "title": "Развернуть склад боеприпасов", - "color": [ - 92, - 78, - 48 - ] - }, - { - "id": "deploy_tzm", - "title": "Развернуть ТЗМ", - "color": [ - 82, - 96, - 60 - ] - }, - { - "id": "deploy_ew", - "title": "Развернуть станцию РЭБ", - "color": [ - 108, - 110, - 80 - ] - }, - { - "id": "deploy_light", - "title": "Развернуть прожектор", - "color": [ - 52, - 54, - 52 - ] - }, - { - "id": "deploy_optical", - "title": "Развернуть оптический пост", - "color": [ - 70, - 110, - 90 - ] - }, { "id": "deploy_s400_launcher", "title": "Развернуть С-400 (пусковая)", diff --git a/catalog/specs.json b/catalog/specs.json index 58f85e9..7c2ba3c 100644 --- a/catalog/specs.json +++ b/catalog/specs.json @@ -21,6 +21,9 @@ "drones": [ { "kind": "Shahed", + "accuracy": [1.2, 0.03], + "item": {"id": "launch_shahed", "title": "Пуск: Шахед-136", "color": [90, 92, 96]}, + "raid_slot": 1, "key": "shahed", "name": "Шахед-136", "model": "airdef:shahed", @@ -42,6 +45,9 @@ }, { "kind": "Geran3", + "accuracy": [1.0, 0.03], + "item": {"id": "launch_geran3", "title": "Пуск: Герань-3", "color": [30, 30, 34]}, + "raid_slot": 2, "key": "geran3", "name": "Герань-3", "model": "airdef:geran3", @@ -63,6 +69,9 @@ }, { "kind": "Lancet", + "accuracy": [0.8, 0.02], + "item": {"id": "launch_lancet", "title": "Пуск: Ланцет-3", "color": [70, 78, 66]}, + "raid_slot": 3, "key": "lancet", "name": "Ланцет-3", "model": "airdef:lancet", @@ -84,6 +93,9 @@ }, { "kind": "Gerbera", + "accuracy": [1.5, 0.04], + "item": null, + "raid_slot": 0, "key": "gerbera", "name": "Гербера", "model": "airdef:gerbera", @@ -105,6 +117,9 @@ }, { "kind": "Kh101", + "accuracy": [1.3, 0.05], + "item": {"id": "launch_kh101", "title": "Пуск: Х-101", "color": [84, 88, 92]}, + "raid_slot": 4, "key": "kh101", "name": "Х-101", "model": "airdef:kh101", @@ -126,6 +141,9 @@ }, { "kind": "Kalibr", + "accuracy": [1.3, 0.05], + "item": {"id": "launch_kalibr", "title": "Пуск: Калибр", "color": [150, 154, 156]}, + "raid_slot": 5, "key": "kalibr", "name": "Калибр", "model": "airdef:kalibr", @@ -147,6 +165,9 @@ }, { "kind": "Kh22", + "accuracy": [1.6, 0.06], + "item": {"id": "launch_kh22", "title": "Пуск: Х-22", "color": [226, 228, 222]}, + "raid_slot": 6, "key": "kh22", "name": "Х-22", "model": "airdef:kh22", @@ -168,6 +189,9 @@ }, { "kind": "Zircon", + "accuracy": [1.5, 0.06], + "item": {"id": "launch_zircon", "title": "Пуск: Циркон", "color": [52, 54, 52]}, + "raid_slot": 7, "key": "zircon", "name": "Циркон", "model": "airdef:zircon", @@ -189,6 +213,9 @@ }, { "kind": "Iskander", + "accuracy": [1.4, 0.06], + "item": {"id": "launch_iskander", "title": "Пуск: Искандер-М", "color": [108, 110, 80]}, + "raid_slot": 8, "key": "iskander", "name": "Искандер-М", "model": "airdef:iskander", @@ -210,6 +237,9 @@ }, { "kind": "Kinzhal", + "accuracy": [1.5, 0.06], + "item": {"id": "launch_kinzhal", "title": "Пуск: Кинжал", "color": [60, 62, 60]}, + "raid_slot": 9, "key": "kinzhal", "name": "Кинжал", "model": "airdef:kinzhal", @@ -231,6 +261,9 @@ }, { "kind": "Oreshnik", + "accuracy": [1.6, 0.08], + "item": {"id": "launch_oreshnik", "title": "Пуск: Орешник", "color": [230, 120, 40]}, + "raid_slot": 10, "key": "oreshnik", "name": "Орешник", "model": "airdef:iskander", @@ -252,6 +285,9 @@ }, { "kind": "OreshnikBlock", + "accuracy": [1.6, 0.08], + "item": null, + "raid_slot": null, "key": "oreshnik_block", "name": "Орешник: блок", "model": "airdef:reentry", @@ -273,6 +309,9 @@ }, { "kind": "OreshnikSub", + "accuracy": [1.6, 0.08], + "item": null, + "raid_slot": null, "key": "oreshnik_sub", "name": "Орешник: суббоеприпас", "model": "airdef:reentry", @@ -296,6 +335,8 @@ "units": [ { "kind": "Patriot", + "village_cost": 5, + "item": {"id": "deploy_patriot", "title": "Развернуть Patriot", "color": [76, 86, 58]}, "key": "patriot", "name": "Patriot", "missile": {"kind": "Pac3", "magazine": 4, "min": 10.0, "max": 950.0, "interval": 16}, @@ -321,6 +362,8 @@ }, { "kind": "Gepard", + "village_cost": 2, + "item": {"id": "deploy_gepard", "title": "Развернуть Гепард", "color": [104, 84, 54]}, "key": "gepard", "name": "Гепард", "missile": null, @@ -346,6 +389,8 @@ }, { "kind": "Pantsir", + "village_cost": 3, + "item": {"id": "deploy_pantsir", "title": "Развернуть Панцирь-С1", "color": [82, 96, 60]}, "key": "pantsir", "name": "Панцирь-С1", "missile": {"kind": "M57e6", "magazine": 12, "min": 25.0, "max": 330.0, "interval": 14}, @@ -371,6 +416,9 @@ }, { "kind": "S400", + "village_cost": 5, + "item": {"id": "deploy_s400", "title": "Развернуть С-400", "color": [60, 80, 50]}, + "ground_strike": "rm48u_game", "key": "s400", "name": "С-400", "missile": {"kind": "M48n6", "magazine": 4, "min": 30.0, "max": 1300.0, "interval": 20}, @@ -396,6 +444,8 @@ }, { "kind": "S500", + "village_cost": 6, + "item": {"id": "deploy_s500", "title": "Развернуть С-500", "color": [108, 110, 80]}, "key": "s500", "name": "С-500", "missile": {"kind": "M77n6", "magazine": 2, "min": 40.0, "max": 1850.0, "interval": 20}, @@ -421,6 +471,8 @@ }, { "kind": "IrisT", + "village_cost": 4, + "item": {"id": "deploy_irist", "title": "Развернуть IRIS-T SLM", "color": [76, 86, 58]}, "key": "irist", "name": "IRIS-T SLM", "missile": {"kind": "IrisT", "magazine": 8, "min": 15.0, "max": 600.0, "interval": 10}, @@ -446,6 +498,8 @@ }, { "kind": "Nasams", + "village_cost": 4, + "item": {"id": "deploy_nasams", "title": "Развернуть NASAMS", "color": [76, 86, 58]}, "key": "nasams", "name": "NASAMS", "missile": {"kind": "Amraam", "magazine": 6, "min": 10.0, "max": 450.0, "interval": 14}, @@ -471,6 +525,8 @@ }, { "kind": "Buk", + "village_cost": 4, + "item": {"id": "deploy_buk", "title": "Развернуть Бук-М2", "color": [82, 96, 60]}, "key": "buk", "name": "Бук-М2", "missile": {"kind": "M9m317", "magazine": 4, "min": 20.0, "max": 675.0, "interval": 18}, @@ -496,6 +552,8 @@ }, { "kind": "Tor", + "village_cost": 3, + "item": {"id": "deploy_tor", "title": "Развернуть Тор-М2", "color": [108, 110, 80]}, "key": "tor", "name": "Тор-М2", "missile": {"kind": "M9m338", "magazine": 8, "min": 8.0, "max": 350.0, "interval": 8}, @@ -521,6 +579,8 @@ }, { "kind": "P1sun", + "village_cost": 3, + "item": {"id": "deploy_p1sun", "title": "Развернуть P1-SUN", "color": [52, 54, 52]}, "key": "p1sun", "name": "P1-SUN", "missile": {"kind": "P1sun", "magazine": 8, "min": 5.0, "max": 675.0, "interval": 12}, @@ -546,6 +606,8 @@ }, { "kind": "Radar", + "village_cost": 2, + "item": {"id": "deploy_radar", "title": "Развернуть РЛС дальнего обнаружения", "color": [108, 110, 80]}, "key": "radar", "name": "РЛС дальнего обнаружения", "missile": null, @@ -571,6 +633,8 @@ }, { "kind": "Depot", + "village_cost": 2, + "item": {"id": "deploy_depot", "title": "Развернуть склад боеприпасов", "color": [92, 78, 48]}, "key": "depot", "name": "Склад боеприпасов", "missile": null, @@ -596,6 +660,8 @@ }, { "kind": "Tzm", + "village_cost": 2, + "item": {"id": "deploy_tzm", "title": "Развернуть ТЗМ", "color": [82, 96, 60]}, "key": "tzm", "name": "ТЗМ", "missile": null, @@ -621,6 +687,8 @@ }, { "kind": "Ew", + "village_cost": 2, + "item": {"id": "deploy_ew", "title": "Развернуть станцию РЭБ", "color": [108, 110, 80]}, "key": "ew", "name": "Станция РЭБ", "missile": null, @@ -646,6 +714,8 @@ }, { "kind": "Light", + "village_cost": 1, + "item": {"id": "deploy_light", "title": "Развернуть прожектор", "color": [52, 54, 52]}, "key": "light", "name": "Прожектор", "missile": null, @@ -671,6 +741,8 @@ }, { "kind": "Optical", + "village_cost": 1, + "item": {"id": "deploy_optical", "title": "Развернуть оптический пост", "color": [70, 110, 90]}, "key": "optical", "name": "Оптический пост", "missile": null, @@ -698,6 +770,7 @@ "missiles": [ { "kind": "Pac3", + "launcher_blast": 0.8, "model": "airdef:pac3", "speed": 5.5, "accel": 0.35, @@ -718,6 +791,7 @@ }, { "kind": "M57e6", + "launcher_blast": 0.45, "model": "airdef:m57e6", "speed": 5.0, "accel": 0.5, @@ -738,6 +812,7 @@ }, { "kind": "M48n6", + "launcher_blast": 1.8, "model": "airdef:m48n6", "speed": 7.0, "accel": 0.5, @@ -758,6 +833,7 @@ }, { "kind": "M77n6", + "launcher_blast": 2.2, "model": "airdef:m77n6", "speed": 9.0, "accel": 0.6, @@ -778,6 +854,7 @@ }, { "kind": "IrisT", + "launcher_blast": 0.6, "model": "airdef:irist_missile", "speed": 7.0, "accel": 0.5, @@ -798,6 +875,7 @@ }, { "kind": "Amraam", + "launcher_blast": 0.5, "model": "airdef:amraam_missile", "speed": 6.0, "accel": 0.45, @@ -818,6 +896,7 @@ }, { "kind": "M9m317", + "launcher_blast": 1.2, "model": "airdef:m48n6", "speed": 6.5, "accel": 0.5, @@ -838,6 +917,7 @@ }, { "kind": "M9m338", + "launcher_blast": 0.4, "model": "airdef:m57e6", "speed": 5.5, "accel": 0.6, @@ -858,6 +938,7 @@ }, { "kind": "P1sun", + "launcher_blast": 0.1, "model": "airdef:p1sun", "speed": 2.8, "accel": 0.12, diff --git a/docs/REPO-MAP.md b/docs/REPO-MAP.md index 057ccd7..e1f2de2 100644 --- a/docs/REPO-MAP.md +++ b/docs/REPO-MAP.md @@ -38,7 +38,7 @@ - `python3 tools/gen_models.py` — перегенерировать. - `python3 tools/gen_models.py --check` — только сравнить, выход 1 при различиях. PNG сверяются по пикселям: байты файла зависят от zlib в сборке Pillow, и Linux (CI) или Windows сжимают те же пиксели иначе, чем macOS. Правленными вручную считаются только файлы, чьи байты разошлись со своей строкой manifest. Сама запись (`gen_models.py` без `--check`) и manifest остаются побайтовыми. -`catalog/specs.json` — единственный источник числовых профилей симуляции: строки `DroneSpec`, `MissileSpec`/`MissileKind` (включая RCS, seeker, звук пуска и голос мотора), `SamSpec` (оружие, части моделей, приводы, датчик), общие константы (гравитация, высота раскрытия «Орешника», логистика) и именованные наборы частей. `tools/gen_catalog.py` создаёт из него `airdef-mod/src/sim/specs_generated.rs` (включается в `mod.rs`; тот же файл компилирует `airdef-core`) и `airdef-mod/src/sim/unit_specs_generated.rs` (включается в `units.rs`). Эти два файла не редактировать вручную. `tools/airdef_assets/catalog.py::load_specs` проверяет схему, звуковые ссылки, наборы kinds против `content.json`, ссылки на именованные части и заполненность всех строк; `gen_catalog.py --check` в CI ловит расхождение. Значения — игровой масштаб, не реальные характеристики техники. +`catalog/specs.json` хранит типы техники, параметры симуляции и их пульты. Из строки техники генератор получает Rust-тип, модель, боекомплект, регистрацию предмета и доступность в меню и командах. `raid_slot` задаёт позицию аппарата в сохранённых составах налётов. Для нового выбираемого аппарата используйте следующий свободный слот. `tools/gen_catalog.py` создаёт `catalog_entries.rs`, `specs_generated.rs` и `unit_specs_generated.rs` для мода и `airdef-core`. Валидатор проверяет уникальность ключей и слотов, ссылки на звуки, совместимость боекомплекта и именованные части. `gen_catalog.py --check` в CI проверяет актуальность Rust-файлов. Все параметры заданы в масштабе игры. `catalog/sounds.json` хранит звуковые ID, дальности и наличие дальнего варианта; `tools/gen_catalog.py` экспортирует ID для Rust, а `tools/gen_sounds.py` создаёт `airdef-mod/assets/airdef/sounds/*.ogg` и `sounds.json`. Этот генератор не использует manifest и не входит в проверку `gen_models.py`. @@ -55,7 +55,7 @@ - `tools/airdef_assets/bounds.py` экспортирует габариты итоговых моделей для headless-навигации; authored overrides входят в расчёт. - `tools/gen_tex.py` отвечает за вывод процедурных текстур и иконок; переиспользуемые примитивы палитры также находятся здесь. - `tools/airdef_assets/texture_catalog.py` связывает стабильную палитру и процедурные функции с текстурами моделей, не смешивая каталог с геометрией. -- `catalog/content.json` задаёт идентичности техники и предметов и оформление предметов; `tools/airdef_assets/icons.py` читает его и содержит чистую функцию рендера иконки с явными параметрами `(name, color, seed)`. +- `catalog/content.json` задаёт варианты развёртывания существующей техники и оформление общих инструментов и пультов вариантов. `tools/airdef_assets/icons.py` получает оформление пультов из обеих таблиц и рендерит иконку по `(name, color, seed)`. - `tools/airdef_assets/pipeline.py` проверяет manifest, рассчитывает безопасный план обновления и откатывает записи при исключении. - `airdef-mod/source-assets/assets/airdef/` — источник авторских переопределений. Генератор объединяет его с процедурными ресурсами во временном дереве, проверяет ссылки/JSON/PNG, затем устанавливает runtime-файлы. - `airdef-mod/assets/` и `airdef-mod/data/` — упакованные generated output. Не редактируйте их вручную; добавляйте авторские исходники в `source-assets`. diff --git a/tools/airdef.py b/tools/airdef.py index 44d41f0..8c43cd2 100644 --- a/tools/airdef.py +++ b/tools/airdef.py @@ -715,7 +715,7 @@ def test_wasm(): BUDGET_SCENARIO = "tests/budgets/wasm_flat_budget.toml" -BUDGET_ASSERTED_SHA256 = "9122cdac879f7db79fe10de3d0bef4646e3d7391e3716f6f46c0c19c07564634" +BUDGET_ASSERTED_SHA256 = "adc10637892159e450458e33b036ccf210ebbf9b7fb05bb3d428d41df5569a8e" def fuel_measurements(output): diff --git a/tools/airdef_assets/catalog.py b/tools/airdef_assets/catalog.py index 06aeccc..a949841 100644 --- a/tools/airdef_assets/catalog.py +++ b/tools/airdef_assets/catalog.py @@ -13,15 +13,38 @@ MUZZLES = {"none", "patriot", "pantsir", "grid", "rails", "cells"} ENGINES = {"prop": {"type", "back", "size"}, "jet": {"type", "up", "back", "size"}, "rocket": {"type", "back", "size"}} MODEL = r"airdef:[a-z0-9_]+" +GROUND_STRIKES = {"rm48u_game": ("Rm48uGame", "M48n6")} # The keys of the existing simulation enums, written once here so the generator and # Rust keep to one encoding. A new enum variant needs its key added here. CONFIG_MODES = {"integrated", "launcher"} CONFIG_ROLES = {"multi", "search", "engagement", "height"} -def load(): +def load(specs=None): + """Project items and deployment identities from their simulation rows.""" data = json.loads(PATH.read_text(encoding="utf-8")) - items = data["items"] + _exact(data, {"items", "variants"}, "content.json") + if specs is None: + specs = json.loads(SPECS.read_text(encoding="utf-8")) + drones = specs["drones"] + slots = sorted(_integer(row["raid_slot"], f"{row['kind']}.raid_slot") for row in drones if row["raid_slot"] is not None) + if slots != list(range(len(slots))): + raise ValueError("raid slots must be unique and contiguous") + ordered = sorted(drones, key=lambda row: row["raid_slot"] if row["raid_slot"] is not None else len(slots)) + items = list(data["items"]) + for row in [*ordered, *specs["units"]]: + if row["item"] is not None: + items.append(row["item"]) + for item in items: + _exact(item, {"id", "title", "color"}, "item") + _text(item["id"], "item.id", r"[a-z0-9_]+") + _text(item["title"], "item.title") + if not isinstance(item["color"], list) or len(item["color"]) != 3 or any(type(c) is not int or not 0 <= c <= 255 for c in item["color"]): + raise ValueError(f"invalid icon color for {item['id']}") + data["items"] = items + data["aircraft"] = [{"kind": row["kind"], "item": row["item"]["id"] if row["item"] else None, + "raid": row["raid_slot"] is not None} for row in ordered] + data["units"] = [{"kind": row["kind"], "item": row["item"]["id"]} for row in specs["units"]] ids = [item["id"] for item in items] if len(ids) != len(set(ids)): raise ValueError("duplicate item ID in content catalog") @@ -53,9 +76,6 @@ def load(): 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"]): raise ValueError("duplicate variant id in content catalog") - for item in items: - if len(item["color"]) != 3 or any(not isinstance(c, int) or not 0 <= c <= 255 for c in item["color"]): - raise ValueError(f"invalid icon color for {item['id']}") return data @@ -189,12 +209,13 @@ def _rest_pitch(entry, where): def load_specs(): """Load the numeric profiles shared by Rust and Python, validating every reference.""" - return validate_specs(json.loads(SPECS.read_text(encoding="utf-8")), load(), - {entry["event"] for entry in load_sounds()}) + data = validate_specs(json.loads(SPECS.read_text(encoding="utf-8")), {entry["event"] for entry in load_sounds()}) + load(data) + return data -def validate_specs(data, content, events): - """Check a specs document against the content identities and registered sound events. +def validate_specs(data, events): + """Check profile rows and their registered sound events. Nothing here names a unit or aircraft kind: a new type only needs its catalog entry. """ @@ -255,13 +276,13 @@ def validate_specs(data, content, events): for i, entry in enumerate(data["missiles"]): where = f"missiles[{i}]" _exact(entry, {"kind", "model", "speed", "accel", "turn", "boost", "cold", "eject", "eject_drag", - "pk", "fuse", "life", "scale", "flame", "rear", "seeker", "launch_sound", "voice"}, where) + "pk", "fuse", "life", "scale", "flame", "rear", "seeker", "launch_sound", "voice", "launcher_blast"}, where) kind = _text(entry["kind"], f"{where}.kind", r"[A-Z][A-Za-z0-9]*") if kind in missile_kinds: raise ValueError(f"{where}: duplicate missile kind {kind}") missile_kinds.add(kind) _text(entry["model"], f"{where}.model", MODEL) - for field in ("speed", "accel", "turn", "pk", "fuse", "scale", "flame", "rear", "seeker"): + for field in ("speed", "accel", "turn", "pk", "fuse", "scale", "flame", "rear", "seeker", "launcher_blast"): _number(entry[field], f"{where}.{field}", 0) _integer(entry["boost"], f"{where}.boost") _integer(entry["cold"], f"{where}.cold") @@ -278,8 +299,8 @@ def validate_specs(data, content, events): keys = set() for i, entry in enumerate(data["drones"]): where = f"drones[{i}]" - _exact(entry, {"kind", "key", "name", "model", "speed", "turn", "cruise", "clearance", "dive", - "warhead", "scale", "engine", "decoy", "stealth", "sound", "class", "ballistic", + _exact(entry, {"kind", "key", "name", "item", "raid_slot", "model", "speed", "turn", "cruise", "clearance", "dive", + "warhead", "accuracy", "scale", "engine", "decoy", "stealth", "sound", "class", "ballistic", "rcs", "launch_sound"}, where) kind = _text(entry["kind"], f"{where}.kind", r"[A-Z][A-Za-z0-9]*") drone_kinds.append(kind) @@ -292,6 +313,12 @@ def validate_specs(data, content, events): for field in ("speed", "turn", "cruise", "clearance", "dive", "scale", "stealth", "rcs"): _number(entry[field], f"{where}.{field}", 0) _integer(entry["warhead"], f"{where}.warhead") + accuracy = entry["accuracy"] + if not isinstance(accuracy, list) or len(accuracy) != 2: + raise ValueError(f"{where}.accuracy: expected [scatter, large miss probability]") + _number(accuracy[0], f"{where}.accuracy[0]", 0) + if _number(accuracy[1], f"{where}.accuracy[1]", 0) > 1: + raise ValueError(f"{where}.accuracy[1]: probability exceeds one") if not isinstance(entry["decoy"], bool): raise ValueError(f"{where}.decoy: expected a boolean") engine = entry["engine"] @@ -314,9 +341,12 @@ def validate_specs(data, content, events): used_missiles = set() for i, entry in enumerate(data["units"]): where = f"units[{i}]" - _exact(entry, {"kind", "key", "name", "missile", "gun", "reload", "scale", "rest_pitch", - "roles", "family", "parts", "mount", "pivot", "muzzle", "sensor", "mast"}, where) + profile = {"ground_strike"} if isinstance(entry, dict) and "ground_strike" in entry else set() + _exact(entry, {"kind", "key", "name", "item", "missile", "gun", "reload", "scale", "rest_pitch", + "roles", "family", "parts", "mount", "pivot", "muzzle", "sensor", "mast", "village_cost"} | profile, where) kind = _text(entry["kind"], f"{where}.kind", r"[A-Z][A-Za-z0-9]*") + if entry["item"] is None: + raise ValueError(f"{where}.item: deployed units need an item") unit_kinds.append(kind) key = _text(entry["key"], f"{where}.key", r"[a-z0-9_]+") if key in keys: @@ -324,6 +354,7 @@ def validate_specs(data, content, events): keys.add(key) _text(entry["name"], f"{where}.name") _integer(entry["reload"], f"{where}.reload") + _integer(entry["village_cost"], f"{where}.village_cost", 1) _number(entry["scale"], f"{where}.scale", 0) _rest_pitch(entry["rest_pitch"], f"{where}.rest_pitch") _integer(entry["roles"], f"{where}.roles") @@ -355,6 +386,10 @@ def validate_specs(data, content, events): _number(missile["min"], f"{where}.missile.min", 0) _number(missile["max"], f"{where}.missile.max", 0) _integer(missile["interval"], f"{where}.missile.interval", 1) + if profile: + name = _text(entry["ground_strike"], f"{where}.ground_strike") + if name not in GROUND_STRIKES or missile is None or missile["kind"] != GROUND_STRIKES[name][1]: + raise ValueError(f"{where}.ground_strike: incompatible shared magazine") gun = entry["gun"] if gun is not None: _exact(gun, {"range", "track", "p", "bursts", "shell", "slew"}, f"{where}.gun") @@ -366,14 +401,8 @@ def validate_specs(data, content, events): for j, v in enumerate(gun["slew"]): _number(v, f"{where}.gun.slew[{j}]", 0) - if set(drone_kinds) != {entry["kind"] for entry in content["aircraft"]}: - raise ValueError("specs.json drones and content.json aircraft disagree") - if len(drone_kinds) != len(content["aircraft"]): - raise ValueError("specs.json drones and content.json aircraft differ in count") - if set(unit_kinds) != {entry["kind"] for entry in content["units"]}: - raise ValueError("specs.json units and content.json units disagree") - if len(unit_kinds) != len(content["units"]): - raise ValueError("specs.json units and content.json units differ in count") + if len(set(drone_kinds)) != len(drone_kinds) or len(set(unit_kinds)) != len(unit_kinds): + raise ValueError("duplicate kind in specs.json") missing = used_missiles - missile_kinds if missing: raise ValueError(f"units reference missiles without a profile: {sorted(missing)}") diff --git a/tools/gen_catalog.py b/tools/gen_catalog.py index b2ffbbd..5570efa 100644 --- a/tools/gen_catalog.py +++ b/tools/gen_catalog.py @@ -4,7 +4,7 @@ import argparse from pathlib import Path import re -from airdef_assets.catalog import load, load_specs, load_sounds +from airdef_assets.catalog import GROUND_STRIKES, load, load_specs, load_sounds OUTPUT = Path(__file__).resolve().parents[1] / "airdef-mod/src/sim/catalog_entries.rs" SPEC_OUTPUT = OUTPUT.with_name("specs_generated.rs") @@ -20,7 +20,7 @@ SOUND_PREFIX = "sound::" def generate(data): - lines = ["// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.", + lines = ["// Generated by tools/gen_catalog.py from catalog/specs.json. Do not edit.", "pub const AIRCRAFT: &[Aircraft] = &["] for entry in data["aircraft"]: kind, item = entry["kind"], entry["item"] @@ -147,6 +147,7 @@ def drone_profile(entry): f" clearance: {num(entry['clearance'])},", f" dive: {num(entry['dive'])},", f" warhead: {integer(entry['warhead'])},", + f" accuracy: ({num(entry['accuracy'][0])}, {num(entry['accuracy'][1])}),", f" scale: {num(entry['scale'])},", f" engine: {motor},", f" decoy: {str(entry['decoy']).lower()},", @@ -164,6 +165,7 @@ def missile_profile(entry): voice = entry["voice"] lines = [f"const MISSILE_SPEC_{entry['kind'].upper()}: MissileSpec = MissileSpec {{", f" model: {text(entry['model'])},", + f" launcher_blast: {num(entry['launcher_blast'])},", f" speed: {num(entry['speed'])},", f" accel: {num(entry['accel'])},", f" turn: {num(entry['turn'])},", @@ -198,10 +200,14 @@ def unit_profile(entry): gun_expr = (f"Some(GunSpec {{ range: {num(gun['range'])}, track: {num(gun['track'])}, p: {num(gun['p'])}, " f"bursts: {integer(gun['bursts'])}, shell: {num(gun['shell'])}, " f"slew: ({num(gun['slew'][0])}, {num(gun['slew'][1])}) }})") + ground = entry.get("ground_strike") + ground_expr = f"Some(catalog::GroundStrike::{GROUND_STRIKES[ground][0]})" if ground is not None else "None" lines = [f"const UNIT_SPEC_{entry['kind'].upper()}: SamSpec = SamSpec {{", f" name: {text(entry['name'])},", f" key: {text(entry['key'])},", + f" village_cost: {integer(entry['village_cost'])},", f" missile: {missile_expr},", + f" ground_strike: {ground_expr},", f" gun: {gun_expr},", f" reload: {integer(entry['reload'])},", f" scale: {num(entry['scale'])},", @@ -218,6 +224,11 @@ def unit_profile(entry): return "\n".join(lines) +def kind_enum(name, entries): + return ["#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]", f"pub enum {name} {{", + *(f" {entry['kind']}," for entry in entries), "}", ""] + + def generate_specs(data): """The simulation's numeric rows, generated for both the mod and airdef-core.""" shared = data["shared"] @@ -243,12 +254,15 @@ def generate_specs(data): f"const TRUCK_LOAD: u32 = {integer(shared['logistics']['truck_load'])};", f"const STOCK_LIMIT: u32 = {integer(shared['logistics']['stock_limit'])};", ""] + lines += kind_enum("DroneKind", data["drones"]) + lines += kind_enum("MissileKind", data["missiles"]) for entry in data["drones"]: lines += [drone_profile(entry), ""] for entry in data["missiles"]: lines += [missile_profile(entry), ""] - lines += ["impl DroneKind {", - " /// Its row of numbers from `catalog/specs.json`.", + lines += ["impl DroneKind {", f" pub const ALL: [DroneKind; {len(data['drones'])}] = ["] + lines += [f" DroneKind::{entry['kind']}," for entry in data["drones"]] + lines += [" ];", "", " /// Its row of numbers from `catalog/specs.json`.", " pub fn spec(self) -> &'static DroneSpec {", " match self {"] for entry in data["drones"]: @@ -289,10 +303,13 @@ def generate_unit_specs(data): else: lines.append(f"const NAMED_{name.upper()}: DVec3 = DVec3::new({', '.join(num(v) for v in value)});") lines.append("") + lines += kind_enum("SamKind", data["units"]) for entry in data["units"]: lines += [unit_profile(entry), ""] - lines += ["impl SamKind {", - " /// Its row of numbers from `catalog/specs.json`.", + armed = [entry for entry in data["units"] if entry["gun"] is not None or entry["missile"] is not None] + lines += ["impl SamKind {", f" pub const ARMED: [SamKind; {len(armed)}] = ["] + lines += [f" SamKind::{entry['kind']}," for entry in armed] + lines += [" ];", "", " /// Its row of numbers from `catalog/specs.json`.", " pub fn spec(self) -> &'static SamSpec {", " match self {"] for entry in data["units"]: @@ -332,11 +349,12 @@ def main(): sound_output = OUTPUT.with_name("catalog_sound_ids.rs") variant_output = OUTPUT.with_name("unit_variants_generated.rs") specs = load_specs() - outputs = ((OUTPUT, generate(load())), + content = load(specs) + outputs = ((OUTPUT, generate(content)), (sound_output, generate_sound_ids(load_sounds())), (SPEC_OUTPUT, generate_specs(specs)), (UNIT_SPEC_OUTPUT, generate_unit_specs(specs)), - (variant_output, generate_variants(load()))) + (variant_output, generate_variants(content))) for path, generated in outputs: if args.check: if not path.exists() or path.read_text(encoding="utf-8") != generated: diff --git a/tools/test_gen_assets.py b/tools/test_gen_assets.py index 1900842..89b80c8 100644 --- a/tools/test_gen_assets.py +++ b/tools/test_gen_assets.py @@ -34,17 +34,22 @@ class ContentCatalogTests(unittest.TestCase): self.assertEqual(language[f"item.airdef.{name}"], title) self.assertTrue((root / "airdef-mod/data/airdef/horizon/item" / (name + ".json")).is_file()) - def test_a_new_unit_kind_needs_only_catalog_entries(self): - # The validator must not carry its own list of kind names: a hypothetical unit is - # accepted from a specs row plus its content entry, with no code change. + def test_a_new_unit_kind_needs_one_catalog_row(self): + from gen_catalog import generate, generate_unit_specs + data = json.loads(json.dumps(catalog.load_specs())) - content = json.loads(json.dumps(catalog.load())) template = next(entry for entry in data["units"] if entry["gun"] is not None) - added = dict(template, kind="TestGun", key="testgun", name="Test gun") + item = {"id": "deploy_testgun", "title": "Test remote", "color": [42, 42, 42]} + added = dict(template, kind="TestGun", key="testgun", name="Test gun", item=item) data["units"].append(added) - content["units"].append({"kind": "TestGun", "item": None}) events = {entry["event"] for entry in catalog.load_sounds()} - catalog.validate_specs(data, content, events) + catalog.validate_specs(data, events) + content = catalog.load(data) + self.assertIn(item, content["items"]) + self.assertIn('kind: SamKind::TestGun, deploy_item: "airdef:deploy_testgun"', generate(content)) + generated = generate_unit_specs(data) + self.assertIn(" TestGun,", generated) + self.assertIn(" SamKind::TestGun,", generated) class ManifestTests(unittest.TestCase):