//! The raid the player orders from the menu: how many of each kind, from //! where, how far out and at what; and ready-made raids to start from. use crate::sim::{Aim, Approach, DroneKind, RaidOrder}; /// The historical raid order is owned by the shared content catalog. pub use crate::sim::catalog::RAID_KINDS as KINDS; /// What a click on a kind's row steps its number through. const STEPS: [u32; 12] = [0, 1, 2, 3, 4, 6, 8, 10, 15, 20, 30, 40]; pub const DISTANCES: [f64; 7] = [200.0, 300.0, 500.0, 800.0, 1500.0, 2500.0, 4000.0]; /// The nearest and farthest start a raid may be ordered at (blocks). pub const DIST_MIN: f64 = 60.0; pub const DIST_MAX: f64 = 4000.0; pub struct Preset { pub name: &'static str, kinds: &'static [(DroneKind, u32)], approach: Approach, aim: Aim, } pub const PRESETS: [Preset; 7] = [ Preset { name: "Рой Шахедов", kinds: &[(DroneKind::Gerbera, 10), (DroneKind::Shahed, 20), (DroneKind::Geran3, 4)], approach: Approach::TwoSectors, aim: Aim::Objects, }, Preset { name: "Массированный удар", kinds: &[ (DroneKind::Gerbera, 8), (DroneKind::Shahed, 12), (DroneKind::Geran3, 4), (DroneKind::Kh101, 4), (DroneKind::Kalibr, 4), (DroneKind::Kh22, 2), (DroneKind::Iskander, 2), ], approach: Approach::AllSides, aim: Aim::Smart, }, Preset { name: "Баллистика", kinds: &[(DroneKind::Gerbera, 4), (DroneKind::Iskander, 4), (DroneKind::Kinzhal, 2)], approach: Approach::Sector, aim: Aim::ObjectsAndSams, }, Preset { name: "Гиперзвук", kinds: &[(DroneKind::Kh22, 3), (DroneKind::Zircon, 4), (DroneKind::Kinzhal, 3)], approach: Approach::TwoSectors, aim: Aim::Smart, }, Preset { name: "Орешник с прикрытием", kinds: &[(DroneKind::Gerbera, 6), (DroneKind::Shahed, 10), (DroneKind::Iskander, 2), (DroneKind::Oreshnik, 1)], approach: Approach::Sector, aim: Aim::Smart, }, Preset { name: "Подавление ПВО", kinds: &[(DroneKind::Gerbera, 8), (DroneKind::Lancet, 8), (DroneKind::Shahed, 8), (DroneKind::Kh22, 4)], approach: Approach::AllSides, aim: Aim::Smart, }, Preset { name: "Пусто", kinds: &[], approach: Approach::Sector, aim: Aim::Objects }, ]; pub struct WaveConfig { pub counts: [u32; KINDS.len()], pub approach: Approach, pub dist: f64, pub aim: Aim, /// The last preset applied. pub preset: usize, } impl Default for WaveConfig { fn default() -> Self { let mut w = WaveConfig { counts: [0; KINDS.len()], approach: Approach::Sector, dist: 300.0, aim: Aim::Smart, preset: 1 }; w.apply(1); w } } impl WaveConfig { pub fn apply(&mut self, preset: usize) { let p = &PRESETS[preset % PRESETS.len()]; self.preset = preset % PRESETS.len(); self.counts = [0; KINDS.len()]; for &(kind, n) in p.kinds { if let Some(i) = KINDS.iter().position(|k| *k == kind) { self.counts[i] = n; } } self.approach = p.approach; self.aim = p.aim; } /// The words of a scenario's `wave` line: counts, approach, distance, aim, preset. pub fn text(&self) -> String { let counts: Vec = self.counts.iter().map(u32::to_string).collect(); let approach = Approach::ALL.iter().position(|a| *a == self.approach).unwrap_or(0); let aim = Aim::ALL.iter().position(|a| *a == self.aim).unwrap_or(0); format!("{} {approach} {} {aim} {}", counts.join(","), self.dist, self.preset) } /// Whether `w` are words `parse` would read whole: an error says which is wrong (#86). pub fn check(&self, w: &[&str]) -> Result<(), String> { if let Some(c) = w.first() { if c.split(',').take(KINDS.len()).any(|v| v.parse::().is_err()) { return Err(format!("число по типам: «{c}»")); } } if w.get(1).is_some_and(|v| v.parse::().ok().is_none_or(|i| i >= Approach::ALL.len())) { return Err(format!("подход: «{}»", w[1])); } if w.get(2).is_some_and(|v| v.parse::().ok().is_none_or(|d| !d.is_finite())) { return Err(format!("дальность: «{}»", w[2])); } if w.get(3).is_some_and(|v| v.parse::().ok().is_none_or(|i| i >= Aim::ALL.len())) { return Err(format!("цель налёта: «{}»", w[3])); } if w.get(4).is_some_and(|v| v.parse::().is_err()) { return Err(format!("набор: «{}»", w[4])); } Ok(()) } /// Reads `text`'s words; what does not parse keeps its value. pub fn parse(&mut self, w: &[&str]) { if let Some(c) = w.first() { for (i, v) in c.split(',').take(KINDS.len()).enumerate() { if let Ok(n) = v.parse::() { self.counts[i] = n.min(80); } } } if let Some(a) = w.get(1).and_then(|v| v.parse::().ok()).and_then(|i| Approach::ALL.get(i)) { self.approach = *a; } if let Some(d) = w.get(2).and_then(|v| v.parse::().ok()) { self.dist = d.clamp(DIST_MIN, DIST_MAX); } if let Some(a) = w.get(3).and_then(|v| v.parse::().ok()).and_then(|i| Aim::ALL.get(i)) { self.aim = *a; } if let Some(p) = w.get(4).and_then(|v| v.parse::().ok()) { self.preset = p % PRESETS.len(); } } /// The next number for kind `i`, back to 0 after the last. pub fn step(&mut self, i: usize) { let n = self.counts[i]; self.counts[i] = STEPS.iter().copied().find(|&s| s > n).unwrap_or(0); } pub fn total(&self) -> u32 { self.counts.iter().sum() } pub fn order(&self) -> RaidOrder { RaidOrder { kinds: KINDS.iter().copied().zip(self.counts).filter(|k| k.1 > 0).collect(), approach: self.approach, dist: self.dist, aim: self.aim, } } /// A combined strike of about `n`, as `/airdef wave mix n` orders it. pub fn mix(n: u32, dist: f64) -> RaidOrder { RaidOrder::mix(n, dist) } } #[cfg(test)] mod catalog_tests { use super::*; use crate::sim::catalog::{AIRCRAFT, UNITS, VARIANTS}; fn assets() -> std::path::PathBuf { std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets/airdef") } fn item_exists(item: &str) { let name = item.strip_prefix("airdef:").expect("item namespace"); for path in [format!("items/{name}.json"), format!("models/item/{name}.json")] { assert!(assets().join(&path).is_file(), "{item}: missing {path}"); } let definition = std::fs::read_to_string(assets().join(format!("items/{name}.json"))).unwrap(); assert!(definition.contains(&format!("airdef:item/{name}")), "{item}: wrong item model"); let model = std::fs::read_to_string(assets().join(format!("models/item/{name}.json"))).unwrap(); // The icon reference may be an alias of an existing texture (the optical post uses the // radar icon until its own asset lands, #136); what matters is that the PNG it names exists. let layer = model .split("\"layer0\": \"") .nth(1) .and_then(|s| s.split('"').next()) .unwrap_or_else(|| panic!("{item}: no icon reference")); let texture = layer.strip_prefix("airdef:item/").unwrap_or_else(|| panic!("{item}: bad icon reference {layer}")); let png = std::fs::read(assets().join(format!("textures/item/{texture}.png"))).unwrap(); assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "{item}: invalid PNG signature"); } fn model_exists(model: &str) { let name = model.strip_prefix("airdef:").expect("model namespace"); let path = assets().join(format!("models/block/{name}.json")); assert!(path.is_file(), "missing model {}", path.display()); } #[test] fn catalog_resources_exist() { for aircraft in AIRCRAFT { model_exists(aircraft.kind.spec().model()); if let Some(item) = aircraft.launch_item { item_exists(item); } } for unit in UNITS { item_exists(unit.deploy_item); let p = &unit.kind.spec().parts; model_exists(p.body); for model in [p.launcher, p.pack, p.dish.map(|v| v.0), p.spinner.map(|v| v.0)].into_iter().flatten() { model_exists(model); } for (model, _, _) in p.fixed { model_exists(model); } } for variant in VARIANTS { item_exists(variant.deploy_item); } } #[test] fn inventory_entries_match_catalog_and_scenario_order_round_trips() { let catalogued = |item: &str| { AIRCRAFT.iter().any(|a| a.launch_item == Some(item)) || UNITS.iter().any(|u| u.deploy_item == item) || VARIANTS.iter().any(|v| v.deploy_item == item) }; for item in AIRCRAFT.iter().filter_map(|a| a.launch_item) .chain(UNITS.iter().map(|u| u.deploy_item)) .chain(VARIANTS.iter().map(|v| v.deploy_item)) { assert_eq!(crate::ITEMS.iter().filter(|i| **i == item).count(), 1, "{item}"); } for item in crate::ITEMS.iter().filter(|i| i.starts_with("airdef:launch_") || i.starts_with("airdef:deploy_")) { assert!(catalogued(item), "uncatalogued item {item}"); } let mut wave = WaveConfig::default(); for (i, count) in wave.counts.iter_mut().enumerate() { *count = i as u32; } let text = wave.text(); let mut restored = WaveConfig::default(); restored.parse(&text.split_whitespace().collect::>()); assert_eq!(restored.counts, wave.counts); assert_eq!(restored.order().kinds, KINDS.iter().copied().zip(wave.counts).filter(|(_, n)| *n > 0).collect::>()); } }