Files
airdef/airdef-mod/src/layout.rs
T
chexit e85e7a18d0 DLSS on/off toggle in the mod settings, persisted per world
The More page (N → Огонь, ремонт, эффекты…) gains a DLSS row next to
Акустика. Default on: a world without a saved choice leaves the engine's
own default (on where supported). The row reads render.dlss-status (API
level 33): with a DLSS device it toggles live; without one it says
«недоступен», and an on-request is kept and applied at the next launch —
a graceful no-op, never an error. The request is saved in the world's
layout (`dlss true|false`, older saves load unchanged) and re-applied on
world load; the engine persists it in horizon-graphics.txt for the next
start's device opening. /airdef capabilities reports the DLSS state too.

Graphics-only: no resolution control (the player's own Horizon settings
stay in charge) and no sim changes. Engine gitlink → b2cc11c45
(agent/dlss-toggle): the dlss graphics setting, the live evaluation gate,
the dlss control command and the level-33 SDK imports.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 15:06:25 +03:00

372 lines
22 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The text of a saved layout (the autosave, the body of a scenario) read and checked as a whole before
//! anything of the scene is touched (#86). `Layout::parse` is pure: it either returns every record with its
//! values proven (finite, in range, within the limits) or the line and field that are wrong; `AirDef` swaps the
//! scene for it only after that. Lines it doesn't know are skipped, so older and newer files read alike.
use super::*;
/// Most systems and most objects one file may hold.
pub const MAX_UNITS: usize = 2000;
/// Largest coordinate: the world's border and then some.
const COORD: f64 = 3.0e7;
/// Largest count (missiles, bursts, cargo, reload ticks).
const COUNT: f64 = 1.0e6;
pub struct SamRec {
pub kind: SamKind,
pub pos: DVec3,
pub heading: f64,
pub roles: Option<u8>,
pub health: Option<f64>,
pub cargo: Option<u32>,
/// Missiles, bursts, empty, reloading: older saves have no ammunition (full).
pub ammo: Option<(u32, u32, bool, u32)>,
pub dest: Option<DVec3>,
/// The parts, from the sensor on; older saves have fewer or none.
pub comps: Vec<f64>,
pub ground_rounds: u32,
pub ground_request: bool,
pub ground_return: bool,
pub return_cargo: bool,
pub ground_stock: u32,
pub air_48n6_stock: u32,
pub mode: sim::battery::SamMode,
pub radar_role: sim::battery::RadarRole,
/// The stable profile ID when the file names one (new saves); old files
/// have only the role key, which migrates to the matching profile.
pub radar_profile: Option<sim::battery::RadarProfile>,
pub spent_cells: u8,
pub radar_on: bool,
}
#[derive(Default)]
pub struct Layout {
pub sams: Vec<SamRec>,
pub targets: Vec<(DVec3, f64)>,
pub damage: Option<bool>,
pub last_chance: Option<bool>,
pub seed: Option<u64>,
pub wave: Option<Vec<String>>,
pub far: Option<bool>,
pub acoustics: Option<bool>,
/// The player's DLSS request; absent in older saves (the engine's own
/// default applies: on where supported).
pub dlss: Option<bool>,
pub effects: Option<(bool, bool)>,
pub roles: Vec<(SamKind, u8)>,
/// Fire doctrines by the system's place in the file (#47).
pub doctrines: Vec<(usize, sim::doctrine::Doctrine)>,
/// Strike missiles in stock and ticks towards the next (#101).
pub strikes: Option<(u32, u32)>,
}
/// One line's words, with the line number for the messages.
struct Line<'a> {
n: usize,
word: &'a str,
w: Vec<&'a str>,
}
impl Line<'_> {
fn bad(&self, field: &str, why: &str) -> String {
format!("строка {}: «{}», поле {field}: {why}", self.n, self.word)
}
/// A finite number in `lo..=hi`; `None` where the field is absent.
fn num(&self, i: usize, field: &str, lo: f64, hi: f64) -> Result<Option<f64>, String> {
let Some(v) = self.w.get(i) else { return Ok(None) };
let x: f64 = v.parse().map_err(|_| self.bad(field, &format!("«{v}» не число")))?;
if !x.is_finite() {
return Err(self.bad(field, &format!("«{v}» не конечное число")));
}
if x < lo || x > hi {
return Err(self.bad(field, &format!("{x} вне допустимого {lo}..{hi}")));
}
Ok(Some(x))
}
fn need(&self, i: usize, field: &str, lo: f64, hi: f64) -> Result<f64, String> {
self.num(i, field, lo, hi)?.ok_or_else(|| self.bad(field, "строка оборвана"))
}
fn flag(&self, i: usize, field: &str) -> Result<Option<bool>, String> {
match self.w.get(i) {
None => Ok(None),
Some(&"true") => Ok(Some(true)),
Some(&"false") => Ok(Some(false)),
Some(v) => Err(self.bad(field, &format!("«{v}»: нужно true или false"))),
}
}
fn kind(&self, i: usize) -> Result<SamKind, String> {
let v = self.w.get(i).ok_or_else(|| self.bad("тип", "строка оборвана"))?;
SamKind::from_key(v).ok_or_else(|| self.bad("тип", &format!("неизвестный тип «{v}»")))
}
fn xyz(&self, i: usize, field: &str) -> Result<DVec3, String> {
Ok(DVec3::new(self.need(i, field, -COORD, COORD)?, self.need(i + 1, field, -COORD, COORD)?, self.need(i + 2, field, -COORD, COORD)?))
}
}
impl Layout {
pub fn parse(text: &str) -> Result<Layout, String> {
let mut out = Layout::default();
for (n, raw) in text.lines().enumerate() {
let w: Vec<&str> = raw.split_whitespace().collect();
let Some(&word) = w.first() else { continue };
let l = Line { n: n + 1, word, w };
match word {
"sam" => {
if out.sams.len() >= MAX_UNITS {
return Err(l.bad("число комплексов", &format!("больше {MAX_UNITS}")));
}
let kind = l.kind(1)?;
let pos = l.xyz(2, "координаты")?;
let heading = l.need(5, "курс", -1.0e6, 1.0e6)?;
let roles = l.num(6, "роли", 0.0, 255.0)?.map(|r| r as u8);
let health = l.num(7, "прочность", 0.0, 1.0)?;
let cargo = l.num(8, "груз", 0.0, COUNT)?.map(|c| c as u32);
let ammo = match (l.num(9, "ракеты", 0.0, COUNT)?, l.num(10, "очереди", 0.0, COUNT)?) {
(Some(m), Some(b)) => Some((m as u32, b as u32, l.num(11, "пуст", 0.0, 1.0)? == Some(1.0), l.num(12, "перезарядка", 0.0, COUNT)?.map_or(0, |r| r as u32))),
_ => None,
};
// "- - -": no destination.
let dest = if l.w.get(13) == Some(&"-") { None } else if l.w.len() > 13 { Some(l.xyz(13, "цель движения")?) } else { None };
let mut comps = Vec::new();
for k in 0..6 {
match l.num(16 + k, "часть", 0.0, 1.0)? {
Some(c) => comps.push(c),
None => break,
}
}
let ground_rounds = l.num(22, "заряжено RM48U", 0.0, 4.0)?.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) {
None => sim::battery::SamMode::Integrated,
Some(v) => sim::battery::SamMode::from_key(v).ok_or_else(|| l.bad("режим", "integrated или launcher"))?,
};
let radar_role = match l.w.get(26) {
None => sim::battery::RadarRole::Multifunction,
Some(v) => sim::battery::RadarRole::from_key(v).ok_or_else(|| l.bad("роль РЛС", "multi, search, engagement или height"))?,
};
let spent_cells = match l.w.get(27) {
None => 0,
Some(v) => v.parse::<u8>().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")); }
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);
let radar_profile = match l.w.get(32) {
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 radar_role != sim::battery::RadarRole::Multifunction && kind != SamKind::Radar {
return Err(l.bad("роль РЛС", "роль поддерживается только отдельной РЛС"));
}
if let Some(profile) = radar_profile {
if kind != SamKind::Radar { return Err(l.bad("профиль РЛС", "профиль поддерживается только отдельной РЛС")); }
if profile.role() != radar_role { return Err(l.bad("профиль РЛС", "профиль и роль не совпадают")); }
}
// 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 (kind != SamKind::S400 && 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("боезапас", "больше четырёх ячеек"));
}
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 });
}
"target" => {
if out.targets.len() >= MAX_UNITS {
return Err(l.bad("число объектов", &format!("больше {MAX_UNITS}")));
}
let pos = l.xyz(1, "координаты")?;
let hp = l.num(4, "прочность", 0.0, 100.0)?.unwrap_or(100.0);
out.targets.push((pos, hp));
}
"damage" => out.damage = l.flag(1, "значение")?,
"lastchance" => out.last_chance = l.flag(1, "значение")?,
"strikes" => out.strikes = Some((l.need(1, "запас", 0.0, COUNT)? as u32, l.num(2, "до следующей", 0.0, COUNT)?.map_or(0, |v| v as u32))),
"far" => out.far = l.flag(1, "значение")?,
"acoustics" => out.acoustics = l.flag(1, "значение")?,
"dlss" => out.dlss = l.flag(1, "значение")?,
"effects" => out.effects = Some((l.flag(1, "шейдер")?.unwrap_or(true), l.flag(2, "HD")?.unwrap_or(false))),
"seed" => {
let v = l.w.get(1).ok_or_else(|| l.bad("значение", "строка оборвана"))?;
out.seed = Some(v.parse::<u64>().map_err(|_| l.bad("значение", &format!("«{v}» не число")))?);
}
"wave" => {
crate::wave::WaveConfig::default().check(&l.w[1..]).map_err(|e| l.bad("налёт", &e))?;
out.wave = Some(l.w[1..].iter().map(|s| s.to_string()).collect());
}
"doctrine" => {
// doctrine <system> <salvo> <reserve> <sector centre|-> <half|-> <guards> [x y z]...
let at = l.need(1, "комплекс", 0.0, MAX_UNITS as f64)? as usize;
let salvo = l.w.get(2).and_then(|v| sim::doctrine::Salvo::from_key(v)).ok_or_else(|| l.bad("залп", "eco, normal или heavy"))?;
let reserve = l.need(3, "резерв", 0.0, sim::doctrine::MAX_RESERVE as f64)? as u32;
let sector = if l.w.get(4) == Some(&"-") { None } else { Some((l.need(4, "центр сектора", -1.0e6, 1.0e6)?, l.need(5, "полуширина", 0.0, 7.0)?)) };
let n = l.need(6, "число объектов", 0.0, 64.0)? as usize;
let guards = (0..n).map(|k| l.xyz(7 + 3 * k, "охраняемый объект")).collect::<Result<Vec<_>, _>>()?;
out.doctrines.push((at, sim::doctrine::Doctrine { guards, sector, reserve, salvo }));
}
"roles" => {
let kind = l.kind(1)?;
out.roles.push((kind, l.need(2, "роли", 0.0, 255.0)? as u8));
}
_ => {}
}
}
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn battery_modes_load_and_old_layouts_default() {
let old = Layout::parse("sam s400 0 70 0 0").unwrap();
assert_eq!(old.sams[0].mode, sim::battery::SamMode::Integrated);
assert!(old.sams[0].radar_on);
assert_eq!(old.sams[0].radar_role, sim::battery::RadarRole::Multifunction);
let data = "sam s400 0 70 0 0 30 1 0 4 0 0 0 - - - 1 1 1 1 1 1 0 0 0 launcher multi 5\nsam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated engagement";
let l = Layout::parse(data).unwrap();
assert_eq!(l.sams[0].mode, sim::battery::SamMode::LauncherOnly);
assert_eq!(l.sams[0].spent_cells, 5);
assert_eq!(l.sams[1].radar_role, sim::battery::RadarRole::Engagement);
assert_eq!(l.sams[1].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT), "an old role-only line migrates");
assert!(!Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 false")).unwrap().sams[0].radar_on);
assert!(Layout::parse(&data.replace("launcher multi 5", "launcher multi 5 0 nope")).is_err());
assert!(Layout::parse(&data.replace("engagement", "invalid")).is_err());
assert!(Layout::parse(&data.replace("launcher multi 5", "launcher multi 256")).is_err());
}
fn key() -> &'static str {
SamKind::Patriot.key()
}
#[test]
fn an_optical_post_loads_by_its_catalog_key() {
let l = Layout::parse("sam optical 10 70 20 0.5\n").unwrap();
assert_eq!(l.sams[0].kind, SamKind::Optical);
assert_eq!(l.sams[0].mode, sim::battery::SamMode::Integrated);
}
// #86: the issue's file, and the other ways a saved state can be wrong: refused whole, with the line
#[test]
fn a_damaged_state_is_refused_as_a_whole_with_its_line_and_field() {
let good = format!("sam {} 10 70 20 0.5\ntarget 1 2 3 100\n", key());
assert!(Layout::parse(&good).is_ok());
let cases: Vec<(String, usize, &str)> = vec![
("target NaN inf 0 -100\nsam s400 NaN 70 0 0\n".into(), 1, "координаты"),
(format!("{good}target 1 inf 3 100\n"), 3, "не конечное"),
(format!("{good}target 1 2 3 -100\n"), 3, "прочность"),
(format!("{good}target 1 2 3 NaN\n"), 3, "не конечное"),
(format!("{good}target 1 2\n"), 3, "оборвана"),
(format!("{good}sam {} 1 2\n", key()), 3, "оборвана"),
(format!("{good}sam nosuchkind 1 2 3 0\n"), 3, "тип"),
(format!("{good}sam {} 1 2 3 0 0 7.5\n", key()), 3, "прочность"),
(format!("{good}sam {} 1 2 3 0 0 1 0 1 1 0 0 - - - 0.5 abc\n", key()), 3, "часть"),
(format!("{good}sam {} 1e400 2 3 0\n", key()), 3, "координаты"),
(format!("{good}seed twelve\n"), 3, "значение"),
(format!("{good}wave 1,2,x 0 300 0 1\n"), 3, "налёт"),
(format!("{good}damage maybe\n"), 3, "значение"),
];
for (text, line, what) in cases {
let e = Layout::parse(&text).err().unwrap_or_else(|| panic!("accepted: {text}"));
assert!(e.contains(&format!("строка {line}")) && e.contains(what), "{e} for {text}");
}
let many = "target 0 0 0 100\n".repeat(MAX_UNITS + 1);
assert!(Layout::parse(&many).is_err(), "no limit on the number of objects");
}
#[test]
fn the_dlss_request_round_trips_and_old_saves_keep_the_engine_default() {
assert_eq!(Layout::parse("dlss false\n").unwrap().dlss, Some(false));
assert_eq!(Layout::parse("dlss true\n").unwrap().dlss, Some(true));
assert!(Layout::parse("dlss maybe\n").is_err());
// Older saves have no line: the engine's own default (on) applies.
assert_eq!(Layout::parse("damage true\n").unwrap().dlss, None);
}
#[test]
fn radar_profile_ids_round_trip_and_old_roles_map_to_them() {
let old = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated search";
let l = Layout::parse(old).unwrap();
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Search);
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::SEARCH));
let new = "sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated engagement 0 0 true false false radar_track";
let l = Layout::parse(new).unwrap();
assert_eq!(l.sams[0].radar_profile, Some(sim::battery::RadarProfile::ENGAGEMENT));
assert_eq!(l.sams[0].radar_role, sim::battery::RadarRole::Engagement);
assert_eq!(
Layout::parse("sam radar 1 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated multi 0 0 true false false radar_multi").unwrap().sams[0].radar_profile,
Some(sim::battery::RadarProfile::MULTI)
);
// A profile and the legacy role must agree; a profile on a non-radar is refused.
assert!(Layout::parse(&new.replace("engagement 0", "search 0")).is_err());
assert!(Layout::parse(&new.replace("sam radar", "sam s400").replace("engagement", "multi")).is_err());
assert!(Layout::parse(&new.replace("radar_track", "radar_unknown")).is_err());
assert_eq!(sim::battery::RadarProfile::from_id("multi"), Some(sim::battery::RadarProfile::MULTI));
}
// #86: files made by older builds (no ammunition, no parts, no destination marks) and unknown lines still load
#[test]
fn older_valid_saves_still_load() {
let old = format!(
"sam {k} 10.5 70 -20 1.57\nsam {k} 1 2 3 0 3 0.8 2\nsam {k} 1 2 3 0 3 0.8 2 4 12 1 30 - - -\nsam {k} 1 2 3 0 3 1 0 4 12 0 0 5 70 5 1 0.9 0.8 0.7 0.6 0.5\ntarget 5 6 7\ntarget 5 6 7 0\ndamage false\nfar true\neffects true false\nroles {k} 3\nfuture-line with words\nscenario 1\nname x\nworld state-0\nseed 123456789\nwave 0,1,0,2,0,0,0,0,0 1 300 0 1\n",
k = key()
);
let l = Layout::parse(&old).expect("an old valid save was refused");
assert_eq!((l.sams.len(), l.targets.len()), (4, 2));
assert_eq!(l.targets[0].1, 100.0);
assert_eq!(l.sams[2].ammo, Some((4, 12, true, 30)));
assert!(l.sams[2].dest.is_none() && l.sams[3].dest == Some(DVec3::new(5.0, 70.0, 5.0)));
assert_eq!(l.sams[3].comps.len(), 6);
assert_eq!((l.damage, l.far, l.effects, l.seed), (Some(false), Some(true), Some((true, false)), Some(123456789)));
assert_eq!(l.roles.len(), 1);
// Saves without strikes load as before; with them, the stock is read (and refused when wrong).
assert_eq!(l.strikes, None);
assert_eq!(Layout::parse("strikes 2 3500\n").unwrap().strikes, Some((2, 3500)));
assert!(Layout::parse("strikes -1 0\n").is_err() && Layout::parse("strikes x\n").is_err());
// What the build writes now reads back (a wave line from the menu's own text).
let w = crate::wave::WaveConfig::default().text();
assert!(Layout::parse(&format!("wave {w}\n")).is_ok(), "{w}");
}
#[test]
fn typed_ground_ammo_is_persistent_and_incompatible_layout_is_refused() {
let text = "sam s400 0 70 0 0 30 1 0 2 0 0 0 - - - 1 1 1 1 1 1 2 0 0\nsam depot 0 70 10 0 0 1 30 0 0 0 0 - - - 1 1 1 1 1 1 0 7 2\n";
let layout = Layout::parse(text).unwrap();
assert_eq!((layout.sams[0].ground_rounds, layout.sams[0].ammo.unwrap().0), (2, 2));
assert_eq!((layout.sams[1].ground_stock, layout.sams[1].air_48n6_stock), (7, 2));
assert!(Layout::parse(&text.replace("s400", "patriot")).is_err());
assert!(Layout::parse(&text.replace("0 2 0 0 0 -", "0 4 0 0 0 -")).is_err());
}
#[test]
fn typed_truck_cargo_and_delivery_request_load_from_save() {
let text = "sam s400 200 70 0 0 30 1 0 4 0 0 0 - - - 1 1 1 1 1 1 0 0 0 integrated multi 0 1\nsam tzm 0 70 0 0 0 1 0 0 0 0 0 - - - 1 1 1 1 1 1 0 1 0 integrated multi 0 0\n";
let l = Layout::parse(text).unwrap();
assert!(l.sams[0].ground_request);
assert_eq!(l.sams[1].ground_stock, 1);
assert!(Layout::parse(&text.replace("sam s400", "sam patriot")).is_err());
}
#[test]
fn the_save_line_is_what_the_layout_reads() {
let mut d = crate::sim::doctrine::Doctrine { salvo: crate::sim::doctrine::Salvo::Economy, reserve: 3, ..Default::default() };
d.sector = Some((1.5, 0.5));
d.guards = vec![DVec3::new(1.0, 2.0, 3.0)];
let text = format!("sam {} 0 70 0 0\ndoctrine 0 {}\n", SamKind::Patriot.key(), d.save_text());
let l = crate::layout::Layout::parse(&text).unwrap();
assert_eq!(l.doctrines, vec![(0, d)]);
assert!(crate::layout::Layout::parse("doctrine 0 loud 1 - - 0\n").is_err());
assert!(crate::layout::Layout::parse("doctrine 0 eco 1 - - 2 1 2 3\n").is_err(), "guards cut short");
}
}