Files
airdef/airdef-mod/src/commands.rs
T
chexit 8afe691301
build / mod (push) Failing after 32s
Add typed battle reasons and short engagement chains (#148)
A battery's "why" now starts with one typed reason shared by the monitor,
the HUD and the chat: only observation, waiting for a track, busy channels,
no ammunition, or ready. It carries the age and the station of the mark it
is about, and `/airdef why <n> source` moves the monitor to that station.
The reason is computed from the same predicates the launch decision uses,
and the detailed decision settles it, so a headline cannot promise or deny
a shot the simulation does not take.

The after-action review builds 4-5 measured steps per contact from the
recording's scene journal and events: mark, handoff, lock, launch, outcome.
The menu lists them per battery with a filter and opens a replay frame on
a click (the outcome clip, else the map held at the launch or mark);
`/airdef chains [battery]` prints the same list. Missing transitions stay
missing and marked as no launch, never guessed, and the normal HUD still
shows only the battery's own picture.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 09:42:10 +03:00

315 lines
15 KiB
Rust

//! The `/airdef` command tree: the one description the game's chat box (colours, errors,
//! Tab completion), the help line and the tests read (#98). The handler in `lib.rs` still
//! splits its line itself; this tree decides what reaches it.
use crate::sim::{DroneKind, SamKind};
use horizon_mod_sdk::tree::{Node, Opt, Tree, Value};
/// The suggestion list of the saved scenarios' names (`command::set_suggestions`).
pub const SCENARIOS: &str = "scenarios";
fn on_off() -> Value {
Value::choice(["on", "off"])
}
/// `/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(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([
Node::lit("menu").runs(),
Node::lit("capabilities").runs(),
Node::lit("monitor").runs(),
Node::lit("grid").runs(),
Node::lit("replay").runs().with([
Node::lit("map").runs(),
Node::lit("full").runs(),
Node::lit("reel").runs(),
Node::lit("film").runs().with([
Node::arg("режим", Value::choice(["best", "all"])).runs(),
Node::arg("N", Value::int_from(1)).runs(),
]),
// The words after `export` come in any order: a name, best/all/N, key=value options.
Node::lit("export").runs().then(
Node::options(
"параметры",
vec![
Opt::new("fps", Value::int_from(1)),
Opt::new("size", Value::word()),
Opt::new("crf", Value::int_from(0)),
Opt::new("sec", Value::Number(Some(0.0), None)),
Opt::flag("noaudio"),
],
Some(vec!["best".into(), "all".into()]),
)
.runs(),
),
Node::lit("stop").runs(),
]),
Node::lit("scenario").with([
Node::lit("save").then(
Node::arg("имя", Value::word()).runs().then(Node::arg("fresh", Value::choice(["fresh"])).runs()),
),
Node::lit("load").then(
Node::arg("имя", Value::names(SCENARIOS)).runs().then(Node::arg("force", Value::choice(["force"])).runs()),
),
Node::lit("list").runs(),
Node::lit("delete").then(Node::arg("имя", Value::names(SCENARIOS)).runs()),
]),
Node::lit("why").runs().then(
Node::arg("номер", Value::int_from(1)).runs().then(Node::lit("source").runs()),
),
Node::lit("chains").runs().then(Node::arg("батарея", Value::int_from(1)).runs()),
Node::lit("raid").runs(),
Node::lit("sites").runs(),
Node::lit("ground-stock").then(Node::arg("склад", Value::int_from(1)).then(Node::arg("количество", Value::int_from(0)).runs())),
Node::lit("ground-cancel").then(Node::arg("комплекс", Value::int_from(1)).runs()),
Node::lit("ground-unload").then(Node::arg("комплекс", Value::int_from(1)).runs()),
Node::lit("ground-load").then(Node::arg("комплекс", Value::int_from(1)).runs()),
Node::lit("strike").then(Node::arg("номер", Value::int_from(1)).runs()),
Node::lit("repair").runs(),
Node::lit("import").runs(),
toggle("ew"),
Node::lit("flare").runs(),
Node::lit("move").then(Node::arg("номер", Value::int_from(1)).runs()),
Node::lit("target").then(Node::lit("here").runs()),
Node::lit("give").runs(),
Node::lit("battery").runs().then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::choice(["integrated", "launcher"])).runs())),
Node::lit("radar").then(Node::arg("номер", Value::int_from(1)).then(Node::arg("режим", Value::Word(vec!["on".into(), "off".into()])).runs())),
Node::lit("deploy").then(Node::arg("комплекс", Value::choice(deploy_kinds)).runs()),
Node::lit("wave").then(
Node::arg("тип", Value::choice(wave_kinds)).runs().then(
Node::arg("кол-во", Value::int(1, 80)).runs().then(Node::arg("дальность", Value::number(60.0, 4000.0)).runs()),
),
),
Node::lit("clear").runs(),
Node::lit("targets").then(Node::lit("clear").runs()),
toggle("damage"),
toggle("truth"),
Node::lit("shader").then(Node::arg("режим", Value::choice(["on", "off", "hd"])).runs()),
toggle("hold"),
toggle("lastchance"),
Node::lit("roles").runs().then(
Node::arg("комплекс", Value::choice(armed)).then(
Node::arg(
"классы",
Value::Word(["default", "all", "drone", "jet", "cruise", "supersonic", "ballistic"].map(String::from).to_vec()),
)
.runs(),
),
),
Node::lit("doctrine").runs().then(Node::arg("номер", Value::word()).with([
Node::lit("reserve").then(Node::arg("K", Value::int(0, 64)).runs()),
Node::lit("salvo").then(Node::arg("залп", Value::choice(["eco", "normal", "heavy"])).runs()),
Node::lit("sector").with([
Node::lit("off").runs(),
Node::arg("центр°", Value::number(-720.0, 720.0)).then(Node::arg("полуширина°", Value::number(0.0, 180.0)).runs()),
]),
Node::lit("guard").with([Node::lit("off").runs(), Node::arg("объекты", Value::word()).runs()]),
Node::lit("reset").runs(),
])),
Node::lit("recon").runs(),
Node::lit("stats").runs(),
])
}
/// The help line, from the same tree.
pub fn help() -> String {
tree().usage()
}
/// The scenario names after `name` is saved (once, in the order saved).
pub fn names_after_save(mut all: Vec<String>, name: &str) -> Vec<String> {
if !all.iter().any(|n| n == name) {
all.push(name.to_string());
}
all
}
/// The scenario names after `name` is deleted.
pub fn names_after_delete(mut all: Vec<String>, name: &str) -> Vec<String> {
all.retain(|n| n != name);
all
}
/// Registers the tree with the game, and the scenario names it suggests.
pub fn register(scenarios: &[String]) {
horizon_mod_sdk::command::set_suggestions(SCENARIOS, scenarios);
if let Err(e) = tree().register() {
horizon_mod_sdk::warn(&format!("airdef: command tree refused: {e}"));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ok(line: &str) {
if let Err(e) = tree().parse(line) {
panic!("`{line}` should parse: {e}");
}
}
fn bad_at(line: &str) -> usize {
match tree().parse(line) {
Ok(_) => panic!("`{line}` should not parse"),
Err(e) => e.at,
}
}
fn complete(line: &str, scenarios: &[&str]) -> Vec<String> {
let names: Vec<String> = scenarios.iter().map(|s| s.to_string()).collect();
tree().complete(line, &|_| names.clone())
}
/// Every branch of the old `HELP` line and of the handler's match parses, with its
/// options.
#[test]
fn every_branch_of_the_handler_parses() {
for line in [
"", "menu", "capabilities", "monitor", "grid", "give", "raid", "repair", "import", "flare", "clear", "stats", "recon", "roles",
"replay", "replay map", "replay full", "replay reel", "replay film", "replay film best", "replay film all",
"replay film 3", "replay export", "replay export mine", "replay export best", "replay export all", "replay export 3",
"replay export mine all fps=30 size=1280x720 crf=18 sec=12.5 noaudio", "replay export fps=60", "replay stop",
"scenario save a", "scenario save a fresh", "scenario load a", "scenario load a force", "scenario list",
"scenario delete a", "why", "why 2", "why 2 source", "chains", "chains 2", "ew on", "ew off", "move 4", "target here", "targets clear",
"sites", "strike 3", "battery", "battery 1 launcher", "battery 1 integrated", "radar 2 on", "radar 2 off", "radar 2 engagement", "radar 2 search", "deploy s400_launcher", "deploy s500_launcher", "deploy radar_search", "deploy radar_track", "deploy radar_height", "deploy patriot", "deploy light", "deploy s400", "wave mix", "wave shahed", "wave shahed 20", "wave kh101 80 800", "wave shahed 20 4000",
"wave oreshnik 1 60", "damage on", "damage off", "truth on", "shader hd", "shader off", "shader on", "hold on", "lastchance on", "lastchance off",
"roles all default", "doctrine", "doctrine 1 reserve 4", "doctrine all salvo eco", "doctrine 2 sector 90 45", "doctrine 2 sector off", "doctrine 1 guard 1,2", "doctrine 1 reset", "roles patriot drone,jet", "roles pantsir all", "roles tor ballistic",
] {
ok(line);
}
}
#[test]
fn the_trees_kinds_are_the_enums_own() {
for k in SamKind::ALL {
ok(&format!("deploy {}", k.key()));
}
for k in DroneKind::ALL {
ok(&format!("wave {}", k.spec().key));
}
for k in SamKind::ARMED {
ok(&format!("roles {} all", k.key()));
}
}
#[test]
fn numbers_and_words_outside_what_the_handler_takes_are_refused_where_they_are() {
assert_eq!(bad_at("wave shahed 0"), 12);
assert_eq!(bad_at("wave shahed 81"), 12);
assert_eq!(bad_at("wave shahed 5 59"), 14);
assert_eq!(bad_at("wave shahed 5 4001"), 14);
assert_eq!(bad_at("wave shahed x"), 12);
assert_eq!(bad_at("wave scud"), 5);
assert_eq!(bad_at("wave"), 4);
assert_eq!(bad_at("deploy tank"), 7);
assert_eq!(bad_at("deploy"), 6);
assert_eq!(bad_at("ew maybe"), 3);
assert_eq!(bad_at("shader ultra"), 7);
assert_eq!(bad_at("why 0"), 4);
assert_eq!(bad_at("why x"), 4);
assert_eq!(bad_at("move"), 4);
assert_eq!(bad_at("move 0"), 5);
assert_eq!(bad_at("strike"), 6);
assert_eq!(bad_at("strike 0"), 7);
assert_eq!(bad_at("sites 1"), 6);
assert_eq!(bad_at("scenario"), 8);
assert_eq!(bad_at("scenario load"), 13);
assert_eq!(bad_at("scenario wipe"), 9);
assert_eq!(bad_at("scenario save a keep"), 16);
assert_eq!(bad_at("target there"), 7);
assert_eq!(bad_at("roles tank all"), 6);
assert_eq!(bad_at("roles patriot"), 13);
assert_eq!(bad_at("replay sideways"), 7);
assert_eq!(bad_at("replay film best now"), 17);
assert_eq!(bad_at("nothing"), 0);
assert_eq!(bad_at("menu 1"), 5);
}
/// The key=value options of `replay export` stay what `start_export` reads.
#[test]
fn export_options_are_checked_by_key_and_value() {
assert_eq!(bad_at("replay export fps=0"), 14);
assert_eq!(bad_at("replay export fps=x"), 14);
assert_eq!(bad_at("replay export fps"), 14);
assert_eq!(bad_at("replay export noaudio=1"), 14);
assert_eq!(bad_at("replay export fps=30 fps=60"), 21);
assert_eq!(bad_at("replay export sec=-1"), 14);
assert_eq!(bad_at("replay export crf=-2"), 14);
assert_eq!(bad_at("replay export size="), 14);
let p = tree().parse("replay export mine fps=30 noaudio").unwrap();
assert_eq!(p.get("параметры"), Some("mine fps=30 noaudio"));
}
#[test]
fn completion_offers_the_next_word_only() {
let top = complete("", &[]);
for w in ["menu", "monitor", "grid", "replay", "scenario", "why", "raid", "repair", "import", "ew", "flare", "move",
"target", "give", "deploy", "wave", "clear", "targets", "damage", "truth", "shader", "hold", "lastchance", "roles", "doctrine", "stats", "recon", "sites", "strike", "ground-stock", "ground-load", "ground-unload", "ground-cancel", "chains"] {
assert!(top.contains(&w.to_string()), "{w} in {top:?}");
}
assert_eq!(top.len(), 37);
assert_eq!(complete("rep", &[]), ["repair", "replay"]);
assert_eq!(complete("replay ", &[]), ["export", "film", "full", "map", "reel", "stop"]);
assert_eq!(complete("replay film ", &[]), ["all", "best"]);
assert_eq!(complete("scenario ", &[]), ["delete", "list", "load", "save"]);
assert_eq!(complete("wave ", &[]).len(), 14);
assert!(complete("wave s", &[]).contains(&"shahed".to_string()));
assert_eq!(complete("shader ", &[]), ["hd", "off", "on"]);
assert_eq!(complete("replay export ", &[]), ["all", "best", "crf=", "fps=", "noaudio", "sec=", "size="]);
assert_eq!(complete("replay export fps=30 no", &[]), ["noaudio"]);
assert!(complete("menu ", &[]).is_empty());
assert!(complete("wave nothing ", &[]).is_empty());
}
/// A station's profile is fixed at deployment: completion offers only emission, while an
/// old role word still reaches the handler's explanation instead of a bare parse error.
#[test]
fn radar_completion_offers_emission_only() {
let words = complete("radar 1 ", &[]);
assert_eq!(words.len(), 2, "{words:?}");
assert!(words.contains(&"on".to_string()) && words.contains(&"off".to_string()));
for old in ["multi", "search", "engagement", "height"] {
assert!(tree().parse(&format!("radar 1 {old}")).is_ok(), "`{old}` should reach the handler");
}
}
/// The names follow the data: after a save the new name is offered, after a delete it is gone.
#[test]
fn scenario_names_follow_a_save_and_a_delete() {
let mut all: Vec<String> = Vec::new();
let names = |all: &[String]| -> Vec<String> { tree().complete("scenario load ", &|_| all.to_vec()) };
assert!(names(&all).is_empty());
all = names_after_save(all, "base");
all = names_after_save(all, "night");
all = names_after_save(all, "base");
assert_eq!(names(&all), ["base", "night"]);
let of = |all: &[String], line: &str| tree().complete(line, &|_| all.to_vec());
assert_eq!(of(&all, "scenario delete n"), ["night"]);
all = names_after_delete(all, "base");
assert_eq!(names(&all), ["night"]);
assert_eq!(of(&all, "scenario delete "), ["night"]);
all = names_after_delete(all, "night");
assert!(names(&all).is_empty());
}
#[test]
fn the_help_line_is_the_trees() {
let help = help();
assert!(help.starts_with("/airdef menu | capabilities | monitor | grid | replay "), "{help}");
assert!(help.contains("scenario save <имя> [fresh]"), "{help}");
assert!(help.contains("wave <тип> [<кол-во> [<дальность>]]"), "{help}");
assert!(help.ends_with("| stats"), "{help}");
assert!(help.contains("export [fps=… size=… crf=… sec=… noaudio]"), "{help}");
assert!(help.contains("deploy <комплекс>"), "{help}");
}
/// The nodes handed to the game are a tree the game accepts.
#[test]
fn the_nodes_are_flat_and_ordered() {
let nodes = tree().nodes();
assert!(nodes.len() < 512, "{}", nodes.len());
assert!(nodes.iter().enumerate().all(|(i, n)| n.children.iter().all(|&c| c as usize > i)));
}
}