Catalog typed battery variants (#91)

The battery deploy pieces (s400_launcher, s500_launcher, radar_search/
track/height) were described three times: the menu table and the
configuration match in lib.rs, and a chained id list in commands.rs. One
catalog decision instead: catalog/content.json gains a variants section
(mode/role reuse the existing SamMode/RadarRole save keys), gen_catalog.py
generates catalog::UnitVariant rows, and the loader rejects duplicates,
unknown kinds/modes and id collisions with kinds or items. The battery
menu, its click handler and the deploy completion read the generated
table; the historical row order and labels are unchanged.

No variant carries its own balance: per-variant ammo profiles stay open
pending a confirmed profile and an explicitly labelled game abstraction
(PAC-3 note on #91), so no new specs, no new matches and no save/replay
change - a variant is only a deploy key over the same kind.

Checks: gen_catalog.py --check and gen_models.py --check clean, the
python catalog/asset and sound tests pass, airdef-core 234 unit + 8
scenarios, airdef-mod 69 unit + 1 boundary + 5 scenarios (save/load and
state round trips included), zero failures.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
2026-11-20 18:38:23 +03:00
parent 306af49744
commit c59bfe9e54
9 changed files with 162 additions and 25 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ fn on_off() -> Value {
/// `/airdef ...` as `lib.rs` accepts it.
pub fn tree() -> Tree {
let wave_kinds: Vec<&str> = DroneKind::ALL.iter().map(|k| k.spec().key).chain(["mix"]).collect();
let deploy_kinds: Vec<&str> = SamKind::ALL.iter().map(|k| k.key()).chain(["s400_launcher", "s500_launcher", "radar_search", "radar_track", "radar_height"]).collect();
let deploy_kinds: Vec<&str> = SamKind::ALL.iter().map(|k| k.key()).chain(crate::sim::catalog::VARIANTS.iter().map(|v| v.id)).collect();
let armed: Vec<&str> = SamKind::ARMED.iter().map(|k| k.key()).chain(["all"]).collect();
let toggle = |word: &str| Node::lit(word).then(Node::arg("on/off", on_off()).runs());
Tree::new("airdef").runs().with([
+14 -21
View File
@@ -206,27 +206,19 @@ enum Page {
}
const MENU_KINDS: u32 = 1;
const BATTERY_ROWS: u32 = 5;
const BTN_BATTERY: u32 = 22;
const BATTERY_DEPLOY: [(&str, &str); 5] = [
("s400_launcher", "С-400 — отдельная пусковая"),
("s500_launcher", "С-500 — отдельная пусковая"),
("radar_search", "РЛС обзора"),
("radar_track", "РЛС сопровождения"),
("radar_height", "Мачтовая РЛС"),
];
const BATTERY_ROWS: u32 = sim::catalog::VARIANTS.len() as u32;
/// A battery deploy piece from the catalog: a unit kind or one of its variants.
fn deploy_configuration(key: &str) -> Option<(SamKind, sim::battery::SamMode, sim::battery::RadarRole)> {
use sim::battery::{RadarRole as R, SamMode as M};
Some(match key {
"s400_launcher" => (SamKind::S400, M::LauncherOnly, R::Multifunction),
"s500_launcher" => (SamKind::S500, M::LauncherOnly, R::Multifunction),
"radar_search" => (SamKind::Radar, M::Integrated, R::Search),
"radar_track" => (SamKind::Radar, M::Integrated, R::Engagement),
"radar_height" => (SamKind::Radar, M::Integrated, R::Height),
_ => (SamKind::from_key(key)?, M::Integrated, R::Multifunction),
})
match sim::catalog::variant(key) {
Some(v) => Some((v.kind, v.mode, v.role)),
// A bare kind deploys its ordinary integrated configuration.
None => Some((SamKind::from_key(key)?, M::Integrated, R::Multifunction)),
}
}
const BTN_HOLD: u32 = 10;
const BTN_SHADER: u32 = 11;
const BTN_DAMAGE: u32 = 12;
@@ -1590,7 +1582,7 @@ impl AirDef {
}
Page::BatteryDeploy => {
title = "Размещение батареи — клик создаёт технику перед игроком".into();
widgets.push(Widget::List(ListWidget { id: BATTERY_ROWS, rows: BATTERY_DEPLOY.iter().map(|(_, name)| (*name).to_string()).collect(), selected: None }));
widgets.push(Widget::List(ListWidget { id: BATTERY_ROWS, rows: sim::catalog::VARIANTS.iter().map(|v| v.label.to_string()).collect(), selected: None }));
widgets.push(Widget::Button(ButtonWidget { id: BTN_BACK, label: "← Назад".into() }));
}
Page::Replays => {
@@ -2116,8 +2108,8 @@ impl Mod for AirDef {
return;
}
(Page::BatteryDeploy, BATTERY_ROWS) => {
if let Some((key, _)) = BATTERY_DEPLOY.get(row as usize) {
match self.deploy_configured(key) {
if let Some(v) = sim::catalog::VARIANTS.get(row as usize) {
match self.deploy_configured(v.id) {
Ok(message) => say(&message),
Err(error) => say(&error),
}
@@ -2621,8 +2613,9 @@ mod tests {
assert_eq!(sim::catalog::UNITS[3].kind, SamKind::S400);
assert_eq!(sim::catalog::UNITS[4].kind, SamKind::S500);
assert_eq!(sim::catalog::UNITS[10].kind, SamKind::Radar);
for (key, _) in BATTERY_DEPLOY {
assert!(deploy_configuration(key).is_some());
for v in sim::catalog::VARIANTS {
let (actual, mode, role) = deploy_configuration(v.id).unwrap();
assert_eq!((actual, mode, role), (v.kind, v.mode, v.role));
}
for kind in SamKind::ALL {
let (actual, mode, role) = deploy_configuration(kind.key()).unwrap();
+39 -1
View File
@@ -3,7 +3,7 @@
//! Balance and rendering remain in `DroneSpec` and `SamSpec`: the catalog
//! refers to those typed definitions instead of copying their values. The
//! first eleven drone entries retain the historical positional wave-save order.
use super::{DroneKind, SamKind};
use super::{battery::RadarRole, battery::SamMode, DroneKind, SamKind};
#[derive(Clone, Copy, Debug)]
pub struct Aircraft {
@@ -19,6 +19,19 @@ impl Aircraft {
pub fn id(self) -> &'static str { self.kind.spec().key }
}
/// A variant of a complex: a configuration over an existing kind, deployed
/// under its own command/menu id. Not new balance.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UnitVariant {
/// Existing command/menu key; changing it requires an explicit migration.
pub id: &'static str,
pub kind: SamKind,
pub mode: SamMode,
pub role: RadarRole,
/// The deploy menu's row.
pub label: &'static str,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GroundStrike {
/// Game-only RM48U coordinate-strike profile for S-400. Evidence: official agency report,
@@ -59,6 +72,7 @@ pub mod sound {
// Generated entries keep the historical raid and unit ordering.
include!("catalog_entries.rs");
include!("unit_variants_generated.rs");
/// Existing positional serialization makes the first entries' order part of the save format.
const fn raid_count() -> usize {
@@ -132,6 +146,10 @@ pub fn deploy_item(id: &str) -> Option<SamKind> {
UNITS.iter().find(|entry| entry.deploy_item == id).map(|entry| entry.kind)
}
pub fn variant(id: &str) -> Option<&'static UnitVariant> {
VARIANTS.iter().find(|variant| variant.id == id)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -173,6 +191,26 @@ mod tests {
assert_eq!(&RAID_KINDS[..11], &[Gerbera, Shahed, Geran3, Lancet, Kh101, Kalibr, Kh22, Zircon, Iskander, Kinzhal, Oreshnik]);
}
/// A variant is a configuration of an existing kind, one row in the catalog,
/// under an id that stays out of the other identities' keys; the battery-menu
/// order is part of the UI's tested behaviour.
#[test]
fn variants_configure_existing_units_under_free_ids() {
let ids: Vec<&str> = VARIANTS.iter().map(|v| v.id).collect();
assert_eq!(ids, ["s400_launcher", "s500_launcher", "radar_search", "radar_track", "radar_height"]);
for v in VARIANTS {
assert!(UNITS.iter().any(|unit| unit.kind == v.kind), "{} configures an unknown kind", v.id);
assert!(SamKind::from_key(v.id).is_none(), "{} shadows a unit kind", v.id);
assert!(!INVENTORY.contains(&format!("airdef:{}", v.id).as_str()), "{} doubles an item", v.id);
assert!(!v.label.is_empty());
assert_eq!(variant(v.id).map(|u| (u.kind, u.mode, u.role)), Some((v.kind, v.mode, v.role)));
}
let launcher = variant("s400_launcher").unwrap();
assert_eq!((launcher.kind, launcher.mode, launcher.role), (SamKind::S400, SamMode::LauncherOnly, RadarRole::Multifunction));
assert_eq!(VARIANTS[4].id, "radar_height");
assert!(variant("miss").is_none() && variant("s400").is_none());
}
/// The catalog is the only copy of the numbers: a kind without a row, or a row under
/// another kind, would be a silent balance change.
#[test]
@@ -0,0 +1,8 @@
// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.
pub const VARIANTS: &[UnitVariant] = &[
UnitVariant { id: "s400_launcher", kind: SamKind::S400, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-400 — отдельная пусковая" },
UnitVariant { id: "s500_launcher", kind: SamKind::S500, mode: SamMode::LauncherOnly, role: RadarRole::Multifunction, label: "С-500 — отдельная пусковая" },
UnitVariant { id: "radar_search", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Search, label: "РЛС обзора" },
UnitVariant { id: "radar_track", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Engagement, label: "РЛС сопровождения" },
UnitVariant { id: "radar_height", kind: SamKind::Radar, mode: SamMode::Integrated, role: RadarRole::Height, label: "Мачтовая РЛС" },
];
+37
View File
@@ -128,6 +128,43 @@
"item": "deploy_light"
}
],
"variants": [
{
"id": "s400_launcher",
"kind": "S400",
"mode": "launcher",
"role": "multi",
"label": "С-400 — отдельная пусковая"
},
{
"id": "s500_launcher",
"kind": "S500",
"mode": "launcher",
"role": "multi",
"label": "С-500 — отдельная пусковая"
},
{
"id": "radar_search",
"kind": "Radar",
"mode": "integrated",
"role": "search",
"label": "РЛС обзора"
},
{
"id": "radar_track",
"kind": "Radar",
"mode": "integrated",
"role": "engagement",
"label": "РЛС сопровождения"
},
{
"id": "radar_height",
"kind": "Radar",
"mode": "integrated",
"role": "height",
"label": "Мачтовая РЛС"
}
],
"items": [
{
"id": "designator",
+21
View File
@@ -4,6 +4,27 @@
Рабочая ветка `kimi-work`; issues не закрывать, публиковать комментарии с коммитом и проверками.
Движок — отдельный `chexit/horizon-airdef`, ветка `airdef`, подключён точным gitlink `horizon/`.
## #91: типизированные варианты комплексов — первый slice (20 ноября 2026)
Ветка `agent/91-variants` (worktree `/tmp/airdef-issue91`), база `60f1bf0fd`
(рабочая ветка `kimi-work`), движок `ed751714e` не менялся. Минимальный вариант,
который требует текущий код: развёртывание «элементов батареи» (`s400_launcher`,
`s500_launcher`, `radar_search/track/height`) описывалось тремя разрозненными
ручными списками — таблица меню `BATTERY_DEPLOY` и `match` конфигурации в `lib.rs`
и цепочка ids в `commands.rs`. Они сведены в каталог: `catalog/content.json → variants`
(ключи `mode`/`role` переиспользуют существовавшие ключи сохранений `SamMode`/`RadarRole`),
`gen_catalog.py` генерирует `unit_variants_generated.rs` → `catalog::UnitVariant`
(`id/kind/mode/role/label`), Python-валидация отвергает дубли, чужие kinds/modes,
совпадение с ключами/предметами. Меню батареи, клик по строке и Tab-дополнение
`deploy` читают таблицу; генерация порядка строк прежняя, тексты прежние. **Профили
боезапаса по вариантам не заводились**: для «разных ракет/профилей по батареям» требуется
согласованный профиль и явно подписанная игровая абстракция (замечание ревью по
PAC-3 в комментарии #91) — следующий slice, не этот. Save/replay/тексты не менялись:
вариант — только ключ развёртывания поверх тех же полей `sam`, сейв-формат, порядок
и `durable mark` без изменений. То же видно и в `airdef-core` (общая симуляция).
Остаток #91: профили боезапаса по вариантам, объединение Python-генераторов и других списков,
игровая приёмка.
## Текущее состояние: 4 ноября 2026
Последнее продолжение пяти задач: [CONTINUATION-2026-11-04.md](CONTINUATION-2026-11-04.md).
+1 -1
View File
@@ -17,7 +17,7 @@
| #87 | Каноническое SDK-free ядро `airdef-core`, используется модом и сценариями | Дальнейшее отделение текстового/визуального вывода домена от адаптера |
| #88 | Типизированный журнал измеренных переходов; read-only Snapshot для Smoke/Shown; записанные пожары, позы, пуски и зажигание | Перевести оставшиеся model/audio adapters и режиссёра на общий снимок; замер полной 10-минутной записи |
| #89 | Session владеет Live/Replay/Export; явные часы/поколения; единый cleanup; задержанный звук следует часам показа; выход в заголовок завершает показ одним cleanup (хук `frame`, `Session::world_left`); движок освобождает temp/лог ошибки энкодера и не трогает готовый MP4 | Реальный короткий MP4 проверен 4 ноября (звук/видео, отмена, ошибка SDK и энкодера, повторный запуск, совпадение кадров и хвоста очереди, сохранность прежнего MP4). Остаётся: 10-минутный экспорт; приёмка Windows/Linux |
| #91 | Общий каталог доступности и потребители меню/инвентаря; явный RM48U-профиль; корректные подписи очередей; `catalog/specs.json` — единственный источник числовых строк, из него генерируются Rust-таблицы для мода и `airdef-core`, CI проверяет свежесть | Варианты комплексов (разные ракеты/профили по батареям) и игровая приёмка; каталог остаётся статичными данными, не динамическим ECS |
| #91 | Общий каталог доступности и потребители меню/инвентаря; явный RM48U-профиль; корректные подписи очередей; `catalog/specs.json` — единственный источник числовых строк, из него генерируются Rust-таблицы для мода и `airdef-core`, CI проверяет свежесть; первый типизированный slice вариантов комплексов: `catalog/content.json → variants` описывает существующие ключи развёртывания элементов батареи (`s400_launcher`…), вариант = `id/kind/mode/role/label` без нового баланса, таблица `catalog::VARIANTS` генерируется и потребляется меню/командами, ручные параллельные списки в `lib.rs`/`commands.rs` удалены | Профили боезапаса по вариантам (разные ракеты/боекомплекты по батареям) не заводились: обязательное условие — зафиксированный профиль и явная игровая абстракция (см. поправку ревью о PAC-3 в комментарии #91); далее полная игровая приёмка; каталог остаётся статичными данными, не динамическим ECS |
| #92 | Authored overrides, проверка ссылок/PNG/границ, manifest, безопасная транзакционная генерация; registry/texture/icon modules | Дальнейшее ручное улучшение контента относится к #115 |
| #96 | Акустические пути; измеренные синтетические occlusion/echo/reverb fixtures; лицензии и исходные notices в архивах; настоящий MP4 с акустикой: пары on/off, статусы ready, окклюзия/поглощение и диффузный wet-остаток в замкнутой геометрии | Прослушивание, игровой массовый звук/CPU, чистый хвост/RT60 в MP4; точность RT60 пока по допуску 35%, не 15% |
| #102 | Pinned engine/API30, packer/build identity; smoke/acoustics/capture-owner/light/source/owner-scoped camera milestones; fallback/владение; WASM27 и flat stress271; измеренный callback fuel; JSON provenance/failure tests; Metal/no-audio smoke; URL/Git-регрессия; camera-ready по закодированному кадру с per-run/per-world сбросом; GPU-приёмка monitor/main-view на Metal/offscreen (Apple M5) | Старое69-шаговое утверждение о перекрытии отозвано; визуальная/Windows-GPU приёмка картинки камер, полные query/voice/peak budgets, GPU/готовый MP4 и Windows-приёмка остаются |
+22
View File
@@ -13,6 +13,10 @@ 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_]+"
# 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():
@@ -29,6 +33,24 @@ def load():
referenced.extend(entry["item"] for entry in group if entry["item"] is not None)
if len(referenced) != len(set(referenced)) or not set(referenced) <= set(ids):
raise ValueError("duplicate or unregistered content item")
unit_kinds = {entry["kind"] for entry in data["units"]}
taken = set(referenced) | unit_kinds | set(ids)
for variant in data["variants"]:
where = f"variants[{variant['id']}]"
if set(variant) != {"id", "kind", "mode", "role", "label"}:
raise ValueError(f"{where}: expected keys id, kind, mode, role, label, got {sorted(variant)}")
if not re.fullmatch(r"[a-z0-9_]+", variant["id"]):
raise ValueError(f"{where}: invalid variant id {variant['id']!r}")
if variant["kind"] not in unit_kinds:
raise ValueError(f"{where}: unknown unit kind {variant['kind']}")
if variant["mode"] not in CONFIG_MODES or variant["role"] not in CONFIG_ROLES:
raise ValueError(f"{where}: unknown configuration {variant['mode']}/{variant['role']}")
if not isinstance(variant["label"], str) or not variant["label"]:
raise ValueError(f"{where}: expected a menu label")
if variant["id"] in taken:
raise ValueError(f"{where}: variant id collides with an existing identity or kind")
if len({v["id"] for v in data["variants"]}) != len(data["variants"]):
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']}")
+19 -1
View File
@@ -14,6 +14,8 @@ CLASSES = {"drone": "Drone", "jet": "Jet", "cruise": "Cruise", "supersonic": "Su
"ballistic": "Ballistic"}
FAMILIES = {"trainable": "Trainable", "gun": "Gun", "turret": "Turret", "vertical": "Vertical",
"static": "Static", "truck": "Truck", "light": "Light"}
MODES = {"integrated": "Integrated", "launcher": "LauncherOnly"}
ROLES = {"multi": "Multifunction", "search": "Search", "engagement": "Engagement", "height": "Height"}
SOUND_PREFIX = "sound::"
@@ -304,16 +306,32 @@ def generate_unit_specs(data):
return "\n".join(lines + ["];", ""])
def generate_variants(data):
"""A variant of a complex is one record: a deploy id over an existing unit's
typed configuration (`battery::SamMode`, `battery::RadarRole`). No balance of
its own — everything but the label comes from the unit rows it points at."""
lines = ["// Generated by tools/gen_catalog.py from catalog/content.json. Do not edit.",
"pub const VARIANTS: &[UnitVariant] = &["]
for entry in data["variants"]:
mode = MODES[entry["mode"]]
role = ROLES[entry["role"]]
lines.append(f" UnitVariant {{ id: {text(entry['id'])}, kind: SamKind::{entry['kind']}, "
f"mode: SamMode::{mode}, role: RadarRole::{role}, label: {text(entry['label'])} }},")
return "\n".join(lines + ["];", ""])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
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())),
(sound_output, generate_sound_ids(load_sounds())),
(SPEC_OUTPUT, generate_specs(specs)),
(UNIT_SPEC_OUTPUT, generate_unit_specs(specs)))
(UNIT_SPEC_OUTPUT, generate_unit_specs(specs)),
(variant_output, generate_variants(load())))
for path, generated in outputs:
if args.check:
if not path.exists() or path.read_text(encoding="utf-8") != generated: