57a5426e65
build / mod (push) Successful in 4m13s
#101: radars locate sites from launches, /airdef sites, /airdef strike; sites launch slower (15/25/50 ticks) so a strike can come in time. #48: M opens the map on the network's picture, with an editor. #47: guard, sector, reserve and salvo per system. #94: vehicles route round slopes and water and say when they cannot get through. #96: reverb, and a menu switch for the acoustics. #92: generated files are validated before the swap, repo map. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1130 lines
54 KiB
Rust
1130 lines
54 KiB
Rust
//! Scouting the enemy's launch sites and the counter-strike (#101).
|
||
//!
|
||
//! **Finding a site.** Nothing is known by magic. A site shows itself two ways, and only to a radar that is up:
|
||
//! - a launch inside a radar's reach (low targets: the radio horizon, the hills): a *point* sighting, good to a few
|
||
//! percent of the distance;
|
||
//! - a launched drone held on a radar's own track: the track points back to where it came from, a *ray* from where it was
|
||
//! picked up, a few degrees wide, and the time since the launch (the alarm) at the drone's speed gives how far: a range
|
||
//! good to some percent plus a second of launch time. Two radars holding it give two sightings. A ballistic missile's arc
|
||
//! says more: a point sighting, a few percent of the range.
|
||
//!
|
||
//! The sightings of one site are combined by weighted least squares (`solve`): points average, a ray with a range is
|
||
//! a long thin ellipse along it, a bare ray pulls across itself only, and each weighs by how sure it is. The answer carries its own error (`radius`, the 90% circle), which
|
||
//! shrinks with the launches seen and with a second radar holding the same drones. A site whose sightings pin no place
|
||
//! down (bare rays along one line, a circle wider than `max_fix_radius`) is *a bearing*, not yet a place (no `fix`), and
|
||
//! cannot be struck.
|
||
//!
|
||
//! **Striking it.** `order_strike`: one of a few strike missiles (a stock that refills slowly), fired from where the
|
||
//! player stands at the *estimated* place. It flies `STRIKE_SPEED`; on arrival the enemy's cover may shoot it down; else
|
||
//! it lands with its own scatter. The true distance from the site decides: inside `HIT_R` the site is destroyed (stock
|
||
//! burnt, jobs cancelled, wreck and fire), inside `SUPPRESS_R` it is stunned for a while (its launches are delayed, not
|
||
//! cancelled), else it hit the ground beside it and nothing changed. So a badly known site is very likely a wasted missile.
|
||
//!
|
||
//! **Off the map** (`offmap`: no land was found or loaded, so no kit stands anywhere): the site is scouted like any other,
|
||
//! as bearing and range, but there is nothing to see burn. A strike that would have hit just ends its launches
|
||
//! ("halts" them) and says so; the result is not drawn, and a miss is lost beyond the loaded map.
|
||
use super::*;
|
||
use super::sites::{LaunchSite, SiteClass};
|
||
use glam::DVec2;
|
||
|
||
/// Every number of the mechanic.
|
||
pub struct Tune {
|
||
/// Angular error of a track pointing back (radians, 1 sigma): 3 degrees.
|
||
pub track_sigma: f64,
|
||
/// The range from the time of flight: error as a part of the range, and ticks of launch time (times the speed).
|
||
pub range_sigma: (f64, f64),
|
||
/// A ballistic missile's launch point from its arc: error as a part of the distance, and the least.
|
||
pub ballistic_sigma: (f64, f64),
|
||
/// A launch seen by a radar in reach: error as a part of the distance, and the least (blocks).
|
||
pub seen_sigma: (f64, f64),
|
||
/// How high a launch is, for the radar's horizon (blocks over the ground).
|
||
pub launch_height: f64,
|
||
/// A site whose 90% circle is wider than this has no fix (blocks).
|
||
pub max_fix_radius: f64,
|
||
/// Accuracy words: a radius over `rough` is rough, over `fair` fair, else good.
|
||
pub rough: f64,
|
||
pub fair: f64,
|
||
/// Sightings kept for a site.
|
||
pub keep_obs: usize,
|
||
/// Strike missiles at the start and the most held, and ticks to make one more.
|
||
pub stock: u32,
|
||
pub stock_max: u32,
|
||
pub resupply: u32,
|
||
/// Blocks a tick, the farthest target (blocks), and the cruise height over the launch (blocks).
|
||
pub speed: f64,
|
||
pub range: f64,
|
||
pub height: f64,
|
||
/// The missile's own scatter at the aim (blocks, 1 sigma).
|
||
pub cep: f64,
|
||
/// Inside this distance of the site the strike destroys it; inside the second it only stuns it.
|
||
pub hit_r: f64,
|
||
pub suppress_r: f64,
|
||
/// Ticks a stunned site launches nothing.
|
||
pub suppress_ticks: u64,
|
||
/// The chance the enemy's cover shoots the missile down: none, light, heavy; and the shares of sites that have them.
|
||
pub cover_p: [f64; 3],
|
||
pub cover_share: [f64; 2],
|
||
/// Ticks the wreck of a destroyed site smokes.
|
||
pub burn: u64,
|
||
/// A launched drone not taken into account after this many ticks is forgotten.
|
||
pub scout_life: u64,
|
||
}
|
||
|
||
pub const TUNE: Tune = Tune {
|
||
track_sigma: 0.052,
|
||
range_sigma: (0.08, 20.0),
|
||
ballistic_sigma: (0.05, 20.0),
|
||
seen_sigma: (0.04, 8.0),
|
||
launch_height: 4.0,
|
||
max_fix_radius: 800.0,
|
||
rough: 200.0,
|
||
fair: 60.0,
|
||
keep_obs: 64,
|
||
stock: 3,
|
||
stock_max: 4,
|
||
resupply: 6000,
|
||
speed: 8.0,
|
||
range: 4500.0,
|
||
height: 40.0,
|
||
cep: 14.0,
|
||
hit_r: 35.0,
|
||
suppress_r: 90.0,
|
||
suppress_ticks: 600,
|
||
cover_p: [0.0, 0.3, 0.65],
|
||
cover_share: [0.4, 0.75],
|
||
burn: 1800,
|
||
scout_life: 1800,
|
||
};
|
||
|
||
/// The circle is this many one-sigma lengths of the worst direction: it holds about nine in ten of the real errors.
|
||
const RADIUS_K: f64 = 3.0;
|
||
|
||
/// One sighting: a point (`dir` none, `sigma` in blocks), a ray from `at` along `dir` (`sigma` in radians), or a ray with
|
||
/// a range on it (`range`: blocks from `at` to the site and its error): the track says where from, and the time since
|
||
/// the launch flash at the alarm, at the drone's speed, how far.
|
||
#[derive(Clone, Copy, Debug)]
|
||
pub struct Obs {
|
||
pub at: DVec2,
|
||
pub dir: Option<DVec2>,
|
||
pub sigma: f64,
|
||
pub range: Option<(f64, f64)>,
|
||
}
|
||
|
||
impl Obs {
|
||
pub fn point(at: DVec2, sigma: f64) -> Obs {
|
||
Obs { at, dir: None, sigma, range: None }
|
||
}
|
||
pub fn ray(at: DVec2, dir: DVec2, sigma: f64) -> Obs {
|
||
Obs { at, dir: Some(dir), sigma, range: None }
|
||
}
|
||
/// Whether it pins a place down by itself.
|
||
fn places(&self) -> bool {
|
||
self.dir.is_none() || self.range.is_some()
|
||
}
|
||
/// Its weight matrix (a, b, c: symmetric 2x2) and the place it pulls towards, at the guess `p`.
|
||
fn pull(&self, p: DVec2) -> ((f64, f64, f64), DVec2) {
|
||
let Some(u) = self.dir else {
|
||
let w = 1.0 / (self.sigma * self.sigma);
|
||
return ((w, 0.0, w), self.at);
|
||
};
|
||
// The part of the plane across the ray: I - u u^T; along it: u u^T.
|
||
let (ma, mb, mc) = (1.0 - u.x * u.x, -u.x * u.y, 1.0 - u.y * u.y);
|
||
let (na, nb, nc) = (u.x * u.x, u.x * u.y, u.y * u.y);
|
||
match self.range {
|
||
None => {
|
||
// How wide the ray is at the place: its angle times the distance (never trusted nearer than 300).
|
||
let r = (p - self.at).length().clamp(300.0, 12_000.0);
|
||
let w = 1.0 / (self.sigma * r).powi(2);
|
||
((w * ma, w * mb, w * mc), self.at)
|
||
}
|
||
Some((r, sr)) => {
|
||
let (wc, wr) = (1.0 / (self.sigma * r.max(50.0)).powi(2), 1.0 / (sr * sr));
|
||
((wc * ma + wr * na, wc * mb + wr * nb, wc * mc + wr * nc), self.at + u * r)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// What the sightings say.
|
||
#[derive(Clone, Copy, Debug)]
|
||
pub struct Estimate {
|
||
/// Where (x, z), when there is a fix.
|
||
pub pos: DVec2,
|
||
/// The 90% circle, blocks; infinite without a fix.
|
||
pub radius: f64,
|
||
pub fix: bool,
|
||
/// The bearing the site lies on, from where it was seen (compass radians, north 0, east a quarter turn), and its error.
|
||
pub bearing: f64,
|
||
pub bearing_err: f64,
|
||
/// Where the bearing starts (the sightings' centre).
|
||
pub origin: DVec2,
|
||
}
|
||
|
||
/// A compass bearing of `d` (x east, z south): north is -z.
|
||
pub fn compass(d: DVec2) -> f64 {
|
||
d.x.atan2(-d.y).rem_euclid(TAU)
|
||
}
|
||
|
||
/// Combines sightings (weighted least squares). `None` for none.
|
||
pub fn solve(obs: &[Obs]) -> Option<Estimate> {
|
||
if obs.is_empty() {
|
||
return None;
|
||
}
|
||
let n = obs.len() as f64;
|
||
let origin = obs.iter().map(|o| o.at).sum::<DVec2>() / n;
|
||
let mean_dir = obs.iter().filter_map(|o| o.dir).sum::<DVec2>();
|
||
let rays = obs.iter().filter(|o| o.dir.is_some()).count();
|
||
let placed: Vec<&Obs> = obs.iter().filter(|o| o.places()).collect();
|
||
// Where to start: the placing sightings' mean, else far along the rays' mean.
|
||
let mut p = if placed.is_empty() {
|
||
origin + mean_dir.normalize_or_zero() * 1500.0
|
||
} else {
|
||
placed.iter().map(|o| o.pull(origin).1).sum::<DVec2>() / placed.len() as f64
|
||
};
|
||
let (mut lmin, mut ok) = (0.0, false);
|
||
for _ in 0..4 {
|
||
let (mut a, mut b, mut c) = (0.0, 0.0, 0.0);
|
||
let mut v = DVec2::ZERO;
|
||
for o in obs {
|
||
let ((ma, mb, mc), m) = o.pull(p);
|
||
a += ma;
|
||
b += mb;
|
||
c += mc;
|
||
v += DVec2::new(ma * m.x + mb * m.y, mb * m.x + mc * m.y);
|
||
}
|
||
let det = a * c - b * b;
|
||
let half = (a + c) / 2.0;
|
||
let rad = (((a - c) / 2.0).powi(2) + b * b).sqrt();
|
||
lmin = half - rad;
|
||
if det <= 1e-30 || lmin <= 1e-14 {
|
||
ok = false;
|
||
break;
|
||
}
|
||
p = DVec2::new((c * v.x - b * v.y) / det, (a * v.y - b * v.x) / det);
|
||
ok = true;
|
||
}
|
||
let radius = if ok && lmin > 0.0 { RADIUS_K / lmin.sqrt() } else { f64::INFINITY };
|
||
// Bare rays must run towards the place, not away from it, and a circle wider than half the way to it is no fix.
|
||
let ahead = ok && (!placed.is_empty() || (p - origin).dot(mean_dir.normalize_or_zero()) > 150.0);
|
||
let far = (p - origin).length();
|
||
let fix = ok && ahead && p.is_finite() && radius <= TUNE.max_fix_radius && (!placed.is_empty() || radius < 0.5 * far);
|
||
let bearing_err = if rays == 0 { 0.02 } else { obs.iter().filter(|o| o.dir.is_some()).map(|o| o.sigma).fold(0.0, f64::max) / (rays as f64).sqrt() };
|
||
let bearing = if fix || rays == 0 { compass(p - origin) } else { compass(mean_dir) };
|
||
Some(Estimate { pos: if fix { p } else { origin }, radius: if fix { radius } else { f64::INFINITY }, fix, bearing, bearing_err, origin })
|
||
}
|
||
|
||
/// What the player is told of the accuracy.
|
||
pub fn accuracy(e: &Estimate) -> &'static str {
|
||
if !e.fix {
|
||
"только азимут"
|
||
} else if e.radius > TUNE.rough {
|
||
"грубо"
|
||
} else if e.radius > TUNE.fair {
|
||
"средне"
|
||
} else {
|
||
"точно"
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||
pub enum SiteState {
|
||
Active,
|
||
/// Stunned until this tick.
|
||
Stunned(u64),
|
||
/// Destroyed (or, off the map, halted) at this tick.
|
||
Destroyed(u64),
|
||
}
|
||
|
||
/// A site the player's radars have found.
|
||
#[derive(Clone, Debug)]
|
||
pub struct Known {
|
||
pub site: u32,
|
||
pub class: SiteClass,
|
||
pub obs: Vec<Obs>,
|
||
pub est: Option<Estimate>,
|
||
/// Launches seen, and when the last was.
|
||
pub launches: u32,
|
||
pub last: u64,
|
||
pub state: SiteState,
|
||
/// What a strike taught of its cover (0 none, 1 light, 2 heavy).
|
||
pub cover: Option<u8>,
|
||
/// Where the strike on it is aimed, if one is on its way.
|
||
pub aimed: bool,
|
||
}
|
||
|
||
/// A launched drone still to be picked up on a track: (drone, site, class, launched at).
|
||
#[derive(Clone, Copy, Debug)]
|
||
struct Flown {
|
||
drone: u32,
|
||
site: u32,
|
||
class: SiteClass,
|
||
at: u64,
|
||
}
|
||
|
||
/// A strike missile in flight.
|
||
#[derive(Clone, Copy, Debug)]
|
||
pub struct Flight {
|
||
pub id: u32,
|
||
pub site: u32,
|
||
pub from: DVec3,
|
||
/// The aim (x, z).
|
||
pub aim: DVec2,
|
||
pub start: u64,
|
||
pub arrive: u64,
|
||
}
|
||
|
||
#[derive(Default)]
|
||
pub struct Strikes {
|
||
/// Strike missiles left, and ticks towards the next.
|
||
pub stock: u32,
|
||
pub progress: u32,
|
||
pub known: Vec<Known>,
|
||
pub flights: Vec<Flight>,
|
||
flown: Vec<Flown>,
|
||
next: u32,
|
||
/// Smoking wrecks: (where, until).
|
||
wrecks: Vec<(DVec3, u64)>,
|
||
/// Cancelled launches by strike this raid: (site, count), for the raid's report.
|
||
pub cancelled: Vec<(u32, u32)>,
|
||
/// News for the player, said at the next step.
|
||
news: Vec<String>,
|
||
/// Strikes: fired, destroyed, stunned, missed, shot down.
|
||
pub fired: u32,
|
||
pub destroyed: u32,
|
||
pub stunned: u32,
|
||
pub missed: u32,
|
||
pub shot_down: u32,
|
||
/// The enemy's cover forced (tests); else it follows the seed.
|
||
pub cover_override: Option<u8>,
|
||
}
|
||
|
||
impl Strikes {
|
||
pub fn new() -> Self {
|
||
Strikes { stock: TUNE.stock, ..Default::default() }
|
||
}
|
||
/// The stock and its progress as saved: clamped to what is possible.
|
||
pub fn restore(&mut self, stock: u32, progress: u32) {
|
||
self.stock = stock.min(TUNE.stock_max);
|
||
self.progress = if self.stock >= TUNE.stock_max { 0 } else { progress.min(TUNE.resupply - 1) };
|
||
}
|
||
pub fn get(&self, site: u32) -> Option<&Known> {
|
||
self.known.iter().find(|k| k.site == site)
|
||
}
|
||
/// Seconds until the next missile is ready.
|
||
pub fn seconds_to_next(&self) -> u32 {
|
||
(TUNE.resupply - self.progress.min(TUNE.resupply)) / 20
|
||
}
|
||
}
|
||
|
||
/// A standard normal from the seed and three numbers (the combat's random sequence is left alone).
|
||
fn gauss(seed: u64, a: u64, b: u64, c: u64) -> f64 {
|
||
let d = |k| dice(seed, a, b, c * 4 + k);
|
||
(d(0) + d(1) + d(2) - 1.5) * 2.0
|
||
}
|
||
|
||
/// The words for a wind.
|
||
fn wind(bearing: f64) -> &'static str {
|
||
["С", "СВ", "В", "ЮВ", "Ю", "ЮЗ", "З", "СЗ"][((bearing / (TAU / 8.0)).round() as usize) % 8]
|
||
}
|
||
|
||
fn class_name(c: SiteClass) -> &'static str {
|
||
match c {
|
||
SiteClass::Ramp => "дроны",
|
||
SiteClass::Launcher => "крылатые",
|
||
SiteClass::Battery => "баллистические",
|
||
}
|
||
}
|
||
|
||
impl Known {
|
||
/// A line for the list: how far and where from `from`, how sure, and what was seen of it.
|
||
pub fn line(&self, from: DVec3, now: u64) -> String {
|
||
let place = match &self.est {
|
||
Some(e) if e.fix => {
|
||
let d = e.pos - DVec2::new(from.x, from.z);
|
||
format!("{:.0}° {}, {}, ±{:.0} м ({})", compass(d).to_degrees(), wind(compass(d)), crate::panel::distance(d.length()), e.radius, accuracy(e))
|
||
}
|
||
Some(e) => format!("{:.0}° {} ±{:.0}°, дальность неизвестна (только азимут)", e.bearing.to_degrees(), wind(e.bearing), e.bearing_err.to_degrees().max(1.0)),
|
||
None => "место неизвестно".into(),
|
||
};
|
||
let state = match self.state {
|
||
SiteState::Destroyed(_) => " · УНИЧТОЖЕНА".to_string(),
|
||
SiteState::Stunned(until) if until > now => format!(" · подавлена ещё {} с", (until - now) / 20),
|
||
_ => {
|
||
if self.launches == 0 {
|
||
String::new()
|
||
} else if now.saturating_sub(self.last) < 600 {
|
||
" · ведёт пуски".to_string()
|
||
} else {
|
||
" · тихо".to_string()
|
||
}
|
||
}
|
||
};
|
||
let cover = match self.cover {
|
||
Some(0) => " · ПВО не прикрыта",
|
||
Some(_) => " · прикрыта ПВО",
|
||
None => "",
|
||
};
|
||
format!("ПУ №{} ({}): {place}{state}{cover}; пусков замечено {}", self.site, class_name(self.class), self.launches)
|
||
}
|
||
}
|
||
|
||
impl Sim {
|
||
/// Whether the enemy covers this site: 0 none, 1 light, 2 heavy; fixed by the seed and the site.
|
||
pub fn cover_of(&self, site: &LaunchSite) -> u8 {
|
||
if let Some(c) = self.strikes.cover_override {
|
||
return c;
|
||
}
|
||
let r = dice(self.seed, site.id as u64, site.side as u64, 101);
|
||
// A ballistic battery is a prize: guarded more often.
|
||
let r = if site.class == SiteClass::Battery { r * 0.7 } else { r };
|
||
if r < TUNE.cover_share[0] {
|
||
0
|
||
} else if r < TUNE.cover_share[1] {
|
||
1
|
||
} else {
|
||
2
|
||
}
|
||
}
|
||
|
||
/// A drone just left site `site` (a launch the radars may have seen).
|
||
pub(super) fn scout_launch(&mut self, drone: u32, site: u32, kind: DroneKind, at: DVec3) {
|
||
let Some(s) = self.sites.get(site) else { return };
|
||
let (class, offmap, pos) = (s.class, s.offmap, s.pos);
|
||
if self.strikes.flown.len() < 400 {
|
||
self.strikes.flown.push(Flown { drone, site, class, at: self.tick });
|
||
}
|
||
if offmap {
|
||
return;
|
||
}
|
||
// Seen at the launch by a radar that is up and in reach.
|
||
let height = TUNE.launch_height;
|
||
let mut seen: Option<f64> = None;
|
||
for sam in self.sams.iter().filter(|s| s.radar_up()) {
|
||
let dist = horizontal(sam.pos - at).length();
|
||
if dist > sight::reach(sam, kind, height) {
|
||
continue;
|
||
}
|
||
if self.horizons.get(&sam.id).is_some_and(|h| h.hides(sight::antenna(sam), at)) {
|
||
continue;
|
||
}
|
||
seen = Some(seen.map_or(dist, |d: f64| d.min(dist)));
|
||
}
|
||
if let Some(dist) = seen {
|
||
let sigma = (dist * TUNE.seen_sigma.0).max(TUNE.seen_sigma.1);
|
||
let (gx, gz) = (gauss(self.seed, drone as u64, site as u64, 1), gauss(self.seed, drone as u64, site as u64, 2));
|
||
let at = DVec2::new(pos.x + gx * sigma, pos.z + gz * sigma);
|
||
self.add_obs(site, class, Obs::point(at, sigma));
|
||
}
|
||
}
|
||
|
||
/// A sighting of a site: kept, the estimate redone, the player told of news.
|
||
fn add_obs(&mut self, site: u32, class: SiteClass, obs: Obs) {
|
||
let now = self.tick;
|
||
let i = match self.strikes.known.iter().position(|k| k.site == site) {
|
||
Some(i) => i,
|
||
None => {
|
||
self.strikes.known.push(Known { site, class, obs: Vec::new(), est: None, launches: 0, last: now, state: SiteState::Active, cover: None, aimed: false });
|
||
self.strikes.known.len() - 1
|
||
}
|
||
};
|
||
let before = self.strikes.known[i].est;
|
||
let k = &mut self.strikes.known[i];
|
||
k.obs.push(obs);
|
||
if k.obs.len() > TUNE.keep_obs {
|
||
k.obs.remove(0);
|
||
}
|
||
// Every sighting is a launch seen, by the radar at the pad or by the track of what left it.
|
||
k.launches += 1;
|
||
k.last = now;
|
||
k.est = solve(&k.obs);
|
||
let first = before.is_none();
|
||
let words = |e: &Option<Estimate>| e.as_ref().map(accuracy);
|
||
let msg = match (&before, &k.est) {
|
||
(None, Some(e)) if e.fix => Some(format!("РЛС засекла пуски: новая ПУ №{} ({}), место определено ±{:.0} м", site, class_name(class), e.radius)),
|
||
(None, Some(e)) => Some(format!("РЛС засекла пуски: новая ПУ №{} ({}), азимут {:.0}° {}", site, class_name(class), e.bearing.to_degrees(), wind(e.bearing))),
|
||
(Some(b), Some(e)) if !b.fix && e.fix => Some(format!("ПУ №{}: место определено, ±{:.0} м ({})", site, e.radius, accuracy(e))),
|
||
(Some(_), Some(_)) if words(&before) != words(&k.est) => Some(format!("ПУ №{}: точность {}, ±{:.0} м", site, accuracy(k.est.as_ref().unwrap()), k.est.as_ref().unwrap().radius)),
|
||
_ => None,
|
||
};
|
||
let _ = first;
|
||
if let Some(m) = msg {
|
||
self.strikes.news.push(m);
|
||
}
|
||
}
|
||
|
||
/// Once a tick: strike missiles refill, fly and land; launched drones are picked up on tracks; wrecks smoke.
|
||
pub(super) fn step_strikes(&mut self, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
|
||
let now = self.tick;
|
||
out.messages.append(&mut self.strikes.news);
|
||
if self.strikes.stock < TUNE.stock_max {
|
||
self.strikes.progress += 1;
|
||
if self.strikes.progress >= TUNE.resupply {
|
||
self.strikes.progress = 0;
|
||
self.strikes.stock += 1;
|
||
out.messages.push(format!("Ударных ракет в запасе: {}", self.strikes.stock));
|
||
}
|
||
}
|
||
// Launched drones picked up on a track.
|
||
if now % 4 == 0 && !self.strikes.flown.is_empty() {
|
||
let mut new: Vec<(u32, SiteClass, Obs)> = Vec::new();
|
||
let flown = std::mem::take(&mut self.strikes.flown);
|
||
let mut keep = Vec::with_capacity(flown.len());
|
||
for f in flown {
|
||
let Some(d) = self.drones.iter().find(|d| d.id == f.drone).filter(|d| d.alive()) else { continue };
|
||
if now.saturating_sub(f.at) > TUNE.scout_life {
|
||
continue;
|
||
}
|
||
// The tracks of the (up to two) systems whose own radar holds it: each is a sighting of its own.
|
||
let mut held: Vec<(u32, sight::Track)> = self.sams.iter().filter(|s| s.alive()).filter_map(|s| s.track(f.drone).filter(|t| t.own_tick > 0).map(|t| (s.id, *t))).collect();
|
||
if held.is_empty() {
|
||
keep.push(f);
|
||
continue;
|
||
}
|
||
held.sort_by_key(|h| std::cmp::Reverse(h.1.tick));
|
||
held.truncate(2);
|
||
let Some(site) = self.sites.get(f.site) else { continue };
|
||
let truth = DVec2::new(site.pos.x, site.pos.z);
|
||
for (sam, t) in held {
|
||
let from = DVec2::new(t.pos.x, t.pos.z);
|
||
let away = truth - from;
|
||
let dist = away.length();
|
||
if dist < 30.0 {
|
||
continue;
|
||
}
|
||
let (k, c) = (f.drone as u64, f.site as u64 * 64 + sam as u64 % 64);
|
||
if d.kind.spec().ballistic.is_some() {
|
||
let sigma = (dist * TUNE.ballistic_sigma.0).max(TUNE.ballistic_sigma.1);
|
||
let at = DVec2::new(truth.x + gauss(self.seed, k, c, 3) * sigma, truth.y + gauss(self.seed, k, c, 4) * sigma);
|
||
new.push((f.site, f.class, Obs::point(at, sigma)));
|
||
} else {
|
||
// Bearing from the track; range from the time of flight since the launch (the alarm), at the
|
||
// drone's speed: a fraction of the range and a second of launch time.
|
||
let a = away.y.atan2(away.x) + gauss(self.seed, k, c, 5) * TUNE.track_sigma;
|
||
let sr = dist * TUNE.range_sigma.0 + d.kind.spec().speed * TUNE.range_sigma.1;
|
||
let r = (dist + gauss(self.seed, k, c, 6) * sr).max(20.0);
|
||
new.push((f.site, f.class, Obs { range: Some((r, sr)), ..Obs::ray(from, DVec2::new(a.cos(), a.sin()), TUNE.track_sigma) }));
|
||
}
|
||
}
|
||
}
|
||
self.strikes.flown = keep;
|
||
for (site, class, obs) in new {
|
||
self.add_obs(site, class, obs);
|
||
}
|
||
out.messages.append(&mut self.strikes.news);
|
||
}
|
||
// A site gone from the raid is gone from the list.
|
||
let sites = &self.sites;
|
||
self.strikes.known.retain(|k| sites.get(k.site).is_some());
|
||
for k in self.strikes.known.iter_mut() {
|
||
if let SiteState::Stunned(until) = k.state
|
||
&& until <= now
|
||
{
|
||
k.state = SiteState::Active;
|
||
}
|
||
}
|
||
self.fly_strikes(ground, player, out);
|
||
// Wrecks smoke.
|
||
self.strikes.wrecks.retain(|w| w.1 > now);
|
||
for (at, _) in &self.strikes.wrecks {
|
||
out.particles("minecraft:flame", *at + DVec3::Y * 1.2, 1.5, DVec3::new(0.0, 0.05, 0.0), 0.03, 2);
|
||
out.particles("minecraft:large_smoke", *at + DVec3::Y * 1.5, 1.2, DVec3::new(0.0, 0.12, 0.0), 0.03, 2);
|
||
if now % 40 == 0 {
|
||
out.sound("minecraft:block.fire.ambient", *at, 3.0, 0.7);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Strike missiles on their way: drawn, heard, and landed when their time is up.
|
||
fn fly_strikes(&mut self, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
|
||
let now = self.tick;
|
||
let spec = DroneKind::Kalibr.spec();
|
||
let flights = std::mem::take(&mut self.strikes.flights);
|
||
let mut rest = Vec::with_capacity(flights.len());
|
||
for f in flights {
|
||
if now >= f.arrive {
|
||
self.land_strike(f, ground, player, out);
|
||
continue;
|
||
}
|
||
let t = (now - f.start) as f64 / (f.arrive - f.start).max(1) as f64;
|
||
let end = DVec3::new(f.aim.x, f.from.y, f.aim.y);
|
||
let pos = f.from.lerp(end, t) + DVec3::Y * (TUNE.height * (std::f64::consts::PI * t).sin().max(0.0).sqrt());
|
||
let dir = (end - f.from).normalize_or(DVec3::NEG_Z) + DVec3::Y * 0.001;
|
||
let rot = look(dir, 0.0);
|
||
let id = 0x7500_0000 + f.id * PARTS;
|
||
out.model(id, spec.model, pos, rot, spec.scale, false);
|
||
let flicker = 0.7 + 0.3 * self.vis.f();
|
||
if let Engine::Jet(up, back, size) = spec.engine {
|
||
out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * spec.scale, back * spec.scale), rot, spec.scale * size * flicker, true);
|
||
}
|
||
if let Some((event, pitch)) = DroneKind::Kalibr.engine_voice() {
|
||
out.engine(id, event, pos, dir.normalize() * TUNE.speed, 0.8, pitch, false);
|
||
}
|
||
rest.push(f);
|
||
}
|
||
rest.append(&mut self.strikes.flights);
|
||
self.strikes.flights = rest;
|
||
}
|
||
|
||
/// Fires a strike missile at known site `id` from `from`. Returns the line for the player.
|
||
pub fn order_strike(&mut self, id: u32, from: DVec3, out: &mut Out) -> Result<String, String> {
|
||
let k = self.strikes.get(id).ok_or_else(|| format!("ПУ №{id} не найдена: /airdef sites покажет известные"))?;
|
||
let est = k.est.filter(|e| e.fix).ok_or_else(|| {
|
||
format!("ПУ №{id}: места не знаем, только азимут. Нужно больше пусков на виду или вторая РЛС в стороне от первой")
|
||
})?;
|
||
if matches!(k.state, SiteState::Destroyed(_)) {
|
||
return Err(format!("ПУ №{id} уже уничтожена"));
|
||
}
|
||
if self.strikes.flights.iter().any(|f| f.site == id) {
|
||
return Err(format!("По ПУ №{id} ракета уже в полёте"));
|
||
}
|
||
if self.strikes.stock == 0 {
|
||
return Err(format!("Ударных ракет нет: следующая через {} с", self.strikes.seconds_to_next()));
|
||
}
|
||
let dist = (est.pos - DVec2::new(from.x, from.z)).length();
|
||
if dist > TUNE.range {
|
||
return Err(format!("ПУ №{id} дальше дальности удара ({})", crate::panel::distance(TUNE.range)));
|
||
}
|
||
self.strikes.stock -= 1;
|
||
self.strikes.fired += 1;
|
||
self.strikes.next += 1;
|
||
let ticks = (dist / TUNE.speed).ceil().max(20.0) as u64;
|
||
let start = from + DVec3::Y * 1.5;
|
||
self.strikes.flights.push(Flight { id: self.strikes.next, site: id, from: start, aim: est.pos, start: self.tick, arrive: self.tick + ticks });
|
||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == id) {
|
||
k.aimed = true;
|
||
}
|
||
out.sound(DroneKind::Kalibr.launch_sound(), start, 1.0, 1.0);
|
||
out.particles("minecraft:large_smoke", start, 0.6, DVec3::ZERO, 0.05, 30);
|
||
out.particles("minecraft:flame", start, 0.3, DVec3::new(0.0, -0.2, 0.0), 0.05, 12);
|
||
Ok(format!(
|
||
"Удар по ПУ №{id}: ракета пошла в точку ±{:.0} м, лёт {} с, дальше {}. Осталось ударных ракет: {}",
|
||
est.radius,
|
||
ticks / 20,
|
||
crate::panel::distance(dist),
|
||
self.strikes.stock
|
||
))
|
||
}
|
||
|
||
/// A strike arrives.
|
||
fn land_strike(&mut self, f: Flight, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
|
||
let now = self.tick;
|
||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == f.site) {
|
||
k.aimed = false;
|
||
}
|
||
let Some(site) = self.sites.get(f.site).cloned() else {
|
||
out.messages.push(format!("Удар по ПУ №{}: площадка уже свёрнута, ракета ушла в пустоту", f.site));
|
||
return;
|
||
};
|
||
let cover = self.cover_of(&site);
|
||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == f.site) {
|
||
k.cover = Some(cover);
|
||
}
|
||
let spot = |x: f64, z: f64, ground: &mut Ground, fallback: f64| DVec3::new(x, ground.at(DVec3::new(x, 0.0, z), now).unwrap_or(fallback), z);
|
||
// The enemy's cover.
|
||
if dice(self.seed, f.id as u64, f.site as u64, 201) < TUNE.cover_p[cover as usize] {
|
||
self.strikes.shot_down += 1;
|
||
let at = spot(f.aim.x, f.aim.y, ground, site.pos.y) + DVec3::Y * 40.0;
|
||
self.blast_at(at, 0, true, false, ground, player, out);
|
||
self.log(at, record::EventKind::Strike { site: f.site, result: record::StrikeResult::Intercepted });
|
||
out.messages.push(format!("Удар по ПУ №{}: ракета сбита ПВО противника у площадки, цель цела", f.site));
|
||
return;
|
||
}
|
||
// Where it lands: the aim and the missile's scatter; how far from the site decides.
|
||
let (gx, gz) = (gauss(self.seed, f.id as u64, f.site as u64, 7), gauss(self.seed, f.id as u64, f.site as u64, 8));
|
||
let land = DVec2::new(f.aim.x + gx * TUNE.cep, f.aim.y + gz * TUNE.cep);
|
||
let miss = (land - DVec2::new(site.pos.x, site.pos.z)).length();
|
||
let result = if site.offmap && miss <= TUNE.hit_r {
|
||
record::StrikeResult::Halted
|
||
} else if !site.alive {
|
||
record::StrikeResult::Missed
|
||
} else if miss <= TUNE.hit_r {
|
||
record::StrikeResult::Destroyed
|
||
} else if miss <= TUNE.suppress_r {
|
||
record::StrikeResult::Stunned
|
||
} else {
|
||
record::StrikeResult::Missed
|
||
};
|
||
use record::StrikeResult as R;
|
||
if site.offmap {
|
||
// Nothing stands there, nothing is seen: the launches stop or they do not.
|
||
if result == R::Halted {
|
||
let n = self.halt_site(f.site);
|
||
self.strikes.destroyed += 1;
|
||
self.strikes.cancelled.push((f.site, n));
|
||
self.set_state(f.site, SiteState::Destroyed(now));
|
||
self.log(site.pos, record::EventKind::Strike { site: f.site, result });
|
||
out.messages.push(format!("Удар по ПУ №{}: за пределами загруженной карты, результат не виден; пуски оттуда прекратились (отменено {n})", f.site));
|
||
} else {
|
||
self.strikes.missed += 1;
|
||
out.messages.push(format!("Удар по ПУ №{}: за пределами загруженной карты; пуски идут, ракета потеряна", f.site));
|
||
}
|
||
return;
|
||
}
|
||
let at = spot(land.x, land.y, ground, site.pos.y);
|
||
match result {
|
||
R::Destroyed => {
|
||
let stock = site.stock;
|
||
let n = self.destroy_site(f.site);
|
||
self.strikes.destroyed += 1;
|
||
self.strikes.cancelled.push((f.site, n));
|
||
self.set_state(f.site, SiteState::Destroyed(now));
|
||
// Its kit and what it carried: a heavy blast, the rounds cooking off, a fire, a smoking wreck.
|
||
self.blast_at(at, 8, false, true, ground, player, out);
|
||
let loaded = ground.at(at, now).is_some();
|
||
for j in 0..stock.min(8) {
|
||
let when = now + 12 + j as u64 * 9 + (dice(self.seed, f.id as u64, j as u64, 301) * 14.0) as u64;
|
||
let off = DVec3::new(gauss(self.seed, f.id as u64, j as u64, 302) * 4.0, dice(self.seed, f.id as u64, j as u64, 303) * 2.0, gauss(self.seed, f.id as u64, j as u64, 304) * 4.0);
|
||
self.later.push((when, at + off, if loaded { 2 } else { 0 }, true));
|
||
}
|
||
self.strikes.wrecks.push((at, now + TUNE.burn));
|
||
self.log(at, record::EventKind::Strike { site: f.site, result });
|
||
out.messages.push(format!(
|
||
"Удар по ПУ №{}: площадка уничтожена, запас сгорел ({stock}); отменено запусков: {n}",
|
||
f.site
|
||
));
|
||
}
|
||
R::Stunned => {
|
||
if let Some(s) = self.sites.list.iter_mut().find(|s| s.id == f.site) {
|
||
s.next_free = s.next_free.max(now + TUNE.suppress_ticks);
|
||
}
|
||
self.strikes.stunned += 1;
|
||
self.set_state(f.site, SiteState::Stunned(now + TUNE.suppress_ticks));
|
||
self.blast_at(at, 4, false, false, ground, player, out);
|
||
self.log(at, record::EventKind::Strike { site: f.site, result });
|
||
out.messages.push(format!(
|
||
"Удар по ПУ №{}: накрыла рядом ({miss:.0} м), площадка подавлена на {} с, но цела",
|
||
f.site,
|
||
TUNE.suppress_ticks / 20
|
||
));
|
||
}
|
||
_ => {
|
||
self.strikes.missed += 1;
|
||
self.blast_at(at, 4, false, false, ground, player, out);
|
||
self.log(at, record::EventKind::Strike { site: f.site, result: R::Missed });
|
||
out.messages.push(format!("Удар по ПУ №{}: промах на {miss:.0} м, площадка цела, пуски идут", f.site));
|
||
}
|
||
}
|
||
}
|
||
|
||
fn set_state(&mut self, site: u32, state: SiteState) {
|
||
if let Some(k) = self.strikes.known.iter_mut().find(|k| k.site == site) {
|
||
k.state = state;
|
||
}
|
||
}
|
||
|
||
/// A blast of `tnt` at `at` with the game's own blast code; the land is only broken where it is loaded.
|
||
fn blast_at(&mut self, at: DVec3, tnt: u32, small: bool, _fire: bool, ground: &mut Ground, player: Option<DVec3>, out: &mut Out) {
|
||
let keep = self.damage;
|
||
self.damage = keep && tnt > 0 && ground.at(at, self.tick).is_some();
|
||
self.explode(at, tnt, small, ground, player, out);
|
||
self.damage = keep;
|
||
}
|
||
|
||
/// Lines for `/airdef sites`.
|
||
pub fn site_lines(&self, from: DVec3) -> Vec<String> {
|
||
let now = self.tick;
|
||
let mut v: Vec<String> = self.strikes.known.iter().map(|k| {
|
||
let mut s = k.line(from, now);
|
||
if self.truth
|
||
&& let Some(site) = self.sites.get(k.site)
|
||
{
|
||
let err = k.est.filter(|e| e.fix).map(|e| (e.pos - DVec2::new(site.pos.x, site.pos.z)).length());
|
||
s += &format!(" [истина: {:.0} {:.0}{}]", site.pos.x, site.pos.z, err.map_or(String::new(), |e| format!(", ошибка {e:.0} м")));
|
||
}
|
||
s
|
||
}).collect();
|
||
if v.is_empty() {
|
||
v.push("Известных ПУ нет: их находят РЛС по пускам и трекам вылетевших целей".into());
|
||
}
|
||
v.push(format!(
|
||
"Ударных ракет: {}/{}{} · в полёте {} · дальность {}",
|
||
self.strikes.stock,
|
||
TUNE.stock_max,
|
||
if self.strikes.stock < TUNE.stock_max { format!(" (следующая через {} с)", self.strikes.seconds_to_next()) } else { String::new() },
|
||
self.strikes.flights.len(),
|
||
crate::panel::distance(TUNE.range)
|
||
));
|
||
v
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
/// A ray from `at` towards `truth`, with the sigma's worth of noise the sim would give it.
|
||
fn ray(truth: DVec2, at: DVec2, k: u64, sigma: f64) -> Obs {
|
||
let a = (truth - at).y.atan2((truth - at).x) + gauss(7, k, 1, 5) * sigma;
|
||
Obs::ray(at, DVec2::new(a.cos(), a.sin()), sigma)
|
||
}
|
||
|
||
#[test]
|
||
fn a_sites_location_narrows_with_launches_and_with_a_second_radar() {
|
||
let truth = DVec2::new(100.0, 3000.0);
|
||
// One place of seeing: the rays run nearly parallel, so it is a bearing, not a place.
|
||
let one: Vec<Obs> = (0..20).map(|k| ray(truth, DVec2::new(-30.0 + k as f64 * 3.0, 0.0), k, TUNE.track_sigma)).collect();
|
||
let e = solve(&one).unwrap();
|
||
assert!(!e.fix, "one radar fixed a site 3 km out: {e:?}");
|
||
assert!((compass(truth - e.origin) - e.bearing).abs() < 0.06, "the bearing is about right: {e:?}");
|
||
// Two radars 1.2 km apart: a place, and the circle shrinks with the launches.
|
||
let two = |n: u64| -> Vec<Obs> {
|
||
(0..n).map(|k| ray(truth, if k % 2 == 0 { DVec2::new(-600.0, 0.0) } else { DVec2::new(600.0, 0.0) }, k, TUNE.track_sigma)).collect()
|
||
};
|
||
let (few, many) = (solve(&two(4)).unwrap(), solve(&two(40)).unwrap());
|
||
assert!(many.fix && many.radius < few.radius * 0.6, "radius {} with 4, {} with 40", few.radius, many.radius);
|
||
assert!(many.radius < TUNE.max_fix_radius && (many.pos - truth).length() < many.radius * 1.5, "{:?} radius {}", many.pos, many.radius);
|
||
// Points average too: more sightings, a smaller circle.
|
||
let pts = |n: u64| -> Vec<Obs> { (0..n).map(|k| Obs::point(truth + DVec2::new(gauss(3, k, 1, 1), gauss(3, k, 1, 2)) * 20.0, 20.0)).collect() };
|
||
let (p1, p9) = (solve(&pts(1)).unwrap(), solve(&pts(9)).unwrap());
|
||
assert!(p1.fix && (p1.radius - 60.0).abs() < 1e-6 && p9.radius < p1.radius / 2.5, "{} {}", p1.radius, p9.radius);
|
||
assert!(solve(&[]).is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn the_stated_circle_holds_about_nine_in_ten_of_the_real_errors() {
|
||
let truth = DVec2::new(100.0, 3000.0);
|
||
let mut within = 0;
|
||
for seed in 0..200u64 {
|
||
let obs: Vec<Obs> = (0..40u64)
|
||
.map(|k| {
|
||
let at = if k % 2 == 0 { DVec2::new(-600.0, 0.0) } else { DVec2::new(600.0, 0.0) };
|
||
let a = (truth - at).y.atan2((truth - at).x) + gauss(seed, k, 1, 5) * TUNE.track_sigma;
|
||
Obs::ray(at, DVec2::new(a.cos(), a.sin()), TUNE.track_sigma)
|
||
})
|
||
.collect();
|
||
let e = solve(&obs).unwrap();
|
||
within += usize::from((e.pos - truth).length() <= e.radius);
|
||
}
|
||
assert!((165..=196).contains(&within), "{within} of 200 inside the circle");
|
||
}
|
||
|
||
#[test]
|
||
fn a_track_with_a_time_of_flight_range_places_the_site_and_more_of_them_narrow_it() {
|
||
let truth = DVec2::new(100.0, 3000.0);
|
||
let ranged = |n: u64, seed: u64| -> Vec<Obs> {
|
||
(0..n)
|
||
.map(|k| {
|
||
let at = DVec2::new(-40.0 + gauss(seed, k, 9, 1) * 30.0, 2200.0 + gauss(seed, k, 9, 2) * 30.0);
|
||
let away = truth - at;
|
||
let a = away.y.atan2(away.x) + gauss(seed, k, 1, 5) * TUNE.track_sigma;
|
||
let sr = away.length() * TUNE.range_sigma.0 + 20.0;
|
||
Obs { range: Some((away.length() + gauss(seed, k, 1, 6) * sr, sr)), ..Obs::ray(at, DVec2::new(a.cos(), a.sin()), TUNE.track_sigma) }
|
||
})
|
||
.collect()
|
||
};
|
||
let (mut within, mut shrink) = (0, 0);
|
||
for seed in 0..100u64 {
|
||
let (one, many) = (solve(&ranged(1, seed)).unwrap(), solve(&ranged(16, seed)).unwrap());
|
||
within += usize::from((many.pos - truth).length() <= many.radius);
|
||
shrink += usize::from(many.radius < one.radius * 0.5);
|
||
}
|
||
assert!(within >= 80, "{within} of 100 inside the circle");
|
||
assert_eq!(shrink, 100);
|
||
// Even one is a (rough) place for a site 800 blocks away.
|
||
assert!(solve(&ranged(1, 1)).unwrap().fix);
|
||
}
|
||
|
||
/// A ramp 300 blocks south of the origin with `n` shaheds queued 40 ticks apart, and a radar `radar` blocks from it
|
||
/// (None: no radar).
|
||
fn scene(seed: u64, n: u32, radar: Option<DVec3>) -> (Sim, Ground, Out, u32) {
|
||
let mut sim = Sim::new(seed);
|
||
sim.strikes.cover_override = Some(0);
|
||
if let Some(at) = radar {
|
||
let id = sim.id();
|
||
sim.sams.push(Sam::new(id, SamKind::Patriot, at, 0.0));
|
||
}
|
||
let id = sim.sites.add(LaunchSite {
|
||
id: 0,
|
||
side: 0,
|
||
sector: 0,
|
||
bearing: 0.0,
|
||
class: SiteClass::Ramp,
|
||
pos: DVec3::new(0.0, 64.0, 300.0),
|
||
range: 300.0,
|
||
water: false,
|
||
stock: n,
|
||
planned: n,
|
||
alive: true,
|
||
next_free: 0,
|
||
offmap: false,
|
||
});
|
||
for i in 0..n {
|
||
let site = sim.sites.get(id).unwrap().clone();
|
||
let d = sim.make_drone(DroneKind::Shahed, site.muzzle(i), -DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
|
||
sim.sites.job(d.id, id);
|
||
sim.queue.push((10 + i as u64 * 40, d));
|
||
}
|
||
(sim, Ground::default(), Out::default(), id)
|
||
}
|
||
|
||
fn run(sim: &mut Sim, ground: &mut Ground, out: &mut Out, ticks: u32) {
|
||
for _ in 0..ticks {
|
||
sim.step(ground, None, out);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn launches_seen_by_a_radar_in_reach_locate_the_site_and_the_circle_shrinks() {
|
||
let (mut sim, mut ground, mut out, id) = scene(11, 12, Some(DVec3::new(0.0, 64.0, 200.0)));
|
||
assert!(sim.strikes.known.is_empty(), "nothing is known before a launch");
|
||
let mut radii = Vec::new();
|
||
for _ in 0..500 {
|
||
sim.step(&mut ground, None, &mut out);
|
||
if let Some(e) = sim.strikes.get(id).and_then(|k| k.est) {
|
||
if radii.last() != Some(&e.radius) {
|
||
radii.push(e.radius);
|
||
}
|
||
}
|
||
}
|
||
let k = sim.strikes.get(id).expect("the radar found the site");
|
||
assert!(k.launches >= 8, "{} launches seen", k.launches);
|
||
let e = k.est.unwrap();
|
||
assert!(e.fix && e.radius < 40.0, "{e:?}");
|
||
let truth = DVec2::new(0.0, 300.0);
|
||
assert!((e.pos - truth).length() < e.radius + 15.0, "off by {}", (e.pos - truth).length());
|
||
assert!(radii.first().unwrap() > radii.last().unwrap(), "{radii:?}");
|
||
assert!(out.messages.iter().any(|m| m.contains("новая ПУ")), "{:?}", out.messages);
|
||
// The site is not known to a sim with no radar: nothing by magic.
|
||
let (mut blind, mut g2, mut o2, _) = scene(11, 12, None);
|
||
run(&mut blind, &mut g2, &mut o2, 500);
|
||
assert!(blind.strikes.known.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn a_strike_on_a_known_site_ends_its_launches() {
|
||
let (mut sim, mut ground, mut out, id) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0)));
|
||
run(&mut sim, &mut ground, &mut out, 200);
|
||
assert!(sim.strikes.get(id).is_some_and(|k| k.est.is_some_and(|e| e.fix)));
|
||
let before = sim.launched;
|
||
assert!(before >= 3 && before < 14, "{before}");
|
||
let player = DVec3::new(0.0, 64.0, 0.0);
|
||
let said = sim.order_strike(id, player, &mut out).unwrap();
|
||
assert!(said.contains("ПУ"), "{said}");
|
||
assert_eq!(sim.strikes.stock, TUNE.stock - 1);
|
||
assert!(sim.order_strike(id, player, &mut out).is_err(), "a second missile at the same site while one flies");
|
||
out.messages.clear();
|
||
run(&mut sim, &mut ground, &mut out, 400);
|
||
let site = sim.sites.get(id).unwrap();
|
||
assert!(!site.alive && site.stock == 0, "{:?} / {:?}", out.messages, site);
|
||
assert!(sim.queue.is_empty(), "the jobs are cancelled");
|
||
assert!(sim.launched < 14 && sim.launched >= before, "launched {}", sim.launched);
|
||
assert!(out.messages.iter().any(|m| m.contains("уничтожена") && m.contains("отменено")), "{:?}", out.messages);
|
||
assert!(sim.strikes.wrecks.len() == 1 && sim.fires.list.len() == 1, "a wreck and a fire");
|
||
assert!(!sim.blasts.is_empty() || sim.tick > 0);
|
||
assert!(matches!(sim.strikes.get(id).unwrap().state, SiteState::Destroyed(_)));
|
||
assert!(sim.order_strike(id, player, &mut out).is_err(), "destroyed already");
|
||
// The result is on the record for replays and stats.
|
||
assert_eq!((sim.strikes.fired, sim.strikes.destroyed), (1, 1));
|
||
}
|
||
|
||
#[test]
|
||
fn a_strike_on_a_badly_known_site_misses_and_changes_nothing() {
|
||
let (mut sim, mut ground, mut out, id) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0)));
|
||
run(&mut sim, &mut ground, &mut out, 120);
|
||
// What the radars hold is wrong by 400 blocks, and says it is.
|
||
// (No radar sees any more: the estimate stays as it is.)
|
||
sim.sams.clear();
|
||
let k = sim.strikes.known.iter_mut().find(|k| k.site == id).unwrap();
|
||
let mut e = k.est.unwrap();
|
||
e.pos += DVec2::new(400.0, 0.0);
|
||
e.radius = 450.0;
|
||
k.est = Some(e);
|
||
sim.strikes.known[0].obs.clear();
|
||
let queued = sim.queue.len();
|
||
sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
|
||
out.messages.clear();
|
||
run(&mut sim, &mut ground, &mut out, 300);
|
||
assert!(out.messages.iter().any(|m| m.contains("промах")), "{:?}", out.messages);
|
||
let site = sim.sites.get(id).unwrap();
|
||
assert!(site.alive && site.stock > 0);
|
||
assert!(sim.queue.len() + sim.launched as usize >= 14 - 1 && sim.queue.len() <= queued, "the queue is not written off by a hit on the soil beside it");
|
||
assert_eq!((sim.strikes.destroyed, sim.strikes.missed), (0, 1));
|
||
// A near miss only stuns: launches wait, nothing is cancelled.
|
||
let (mut stunned, mut other) = (0, 0);
|
||
for seed in 20..32 {
|
||
let (mut sim, mut ground, mut out, id) = scene(seed, 14, Some(DVec3::new(0.0, 64.0, 200.0)));
|
||
run(&mut sim, &mut ground, &mut out, 120);
|
||
sim.sams.clear();
|
||
let k = sim.strikes.known.iter_mut().find(|k| k.site == id).unwrap();
|
||
let mut e = k.est.unwrap();
|
||
e.pos = DVec2::new(0.0, 300.0 + 62.0);
|
||
k.est = Some(e);
|
||
sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
|
||
let queued = sim.queue.len();
|
||
run(&mut sim, &mut ground, &mut out, 300);
|
||
if sim.strikes.stunned == 1 {
|
||
stunned += 1;
|
||
assert!(sim.sites.get(id).unwrap().alive);
|
||
assert!(sim.queue.len() + 1 >= queued.min(sim.queue.len() + 1), "stunned launches are delayed, not cancelled");
|
||
assert!(sim.sites.get(id).unwrap().stock > 0 || sim.queue.is_empty());
|
||
} else {
|
||
other += 1;
|
||
}
|
||
}
|
||
assert!(stunned >= 8 && other <= 4, "{stunned} stunned, {other} other");
|
||
}
|
||
|
||
#[test]
|
||
fn a_site_known_only_by_bearing_cannot_be_struck() {
|
||
let (mut sim, _, mut out, id) = scene(3, 4, None);
|
||
sim.strikes.known.push(Known {
|
||
site: id,
|
||
class: SiteClass::Ramp,
|
||
obs: Vec::new(),
|
||
est: solve(&[ray(DVec2::new(0.0, 300.0), DVec2::new(0.0, 0.0), 1, TUNE.track_sigma)]),
|
||
launches: 1,
|
||
last: 0,
|
||
state: SiteState::Active,
|
||
cover: None,
|
||
aimed: false,
|
||
});
|
||
assert!(!sim.strikes.known[0].est.unwrap().fix);
|
||
let e = sim.order_strike(id, DVec3::ZERO, &mut out).unwrap_err();
|
||
assert!(e.contains("азимут"), "{e}");
|
||
assert_eq!(sim.strikes.stock, TUNE.stock, "no missile spent");
|
||
assert!(sim.order_strike(99, DVec3::ZERO, &mut out).is_err());
|
||
}
|
||
|
||
#[test]
|
||
fn stock_is_limited_range_is_limited_and_it_refills_slowly() {
|
||
let (mut sim, mut ground, mut out, id) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0)));
|
||
run(&mut sim, &mut ground, &mut out, 120);
|
||
// Too far.
|
||
assert!(sim.order_strike(id, DVec3::new(0.0, 64.0, 300.0 - TUNE.range - 100.0), &mut out).is_err());
|
||
sim.strikes.stock = 0;
|
||
let e = sim.order_strike(id, DVec3::ZERO, &mut out).unwrap_err();
|
||
assert!(e.contains("нет"), "{e}");
|
||
sim.strikes.progress = TUNE.resupply - 1;
|
||
run(&mut sim, &mut ground, &mut out, 2);
|
||
assert_eq!((sim.strikes.stock, sim.strikes.progress), (1, 1));
|
||
}
|
||
|
||
#[test]
|
||
fn enemy_cover_shoots_some_strikes_down_and_none_with_no_cover() {
|
||
let mut down = [0u32; 3];
|
||
for cover in 0..3u8 {
|
||
for seed in 1..=30u64 {
|
||
let (mut sim, mut ground, mut out, id) = scene(seed, 14, Some(DVec3::new(0.0, 64.0, 200.0)));
|
||
sim.strikes.cover_override = Some(cover);
|
||
run(&mut sim, &mut ground, &mut out, 120);
|
||
sim.order_strike(id, DVec3::ZERO, &mut out).unwrap();
|
||
run(&mut sim, &mut ground, &mut out, 200);
|
||
down[cover as usize] += sim.strikes.shot_down;
|
||
}
|
||
}
|
||
assert_eq!(down[0], 0);
|
||
assert!(down[1] > 3 && down[1] < 20 && down[2] > down[1], "{down:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn an_off_map_site_is_found_by_bearing_and_a_strike_there_only_ends_its_launches() {
|
||
let mut sim = Sim::new(5);
|
||
sim.strikes.cover_override = Some(0);
|
||
// Two radars apart watch the start of an off-map site's drones.
|
||
for x in [-150.0, 150.0] {
|
||
let id = sim.id();
|
||
sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::new(x, 64.0, 0.0), 0.0));
|
||
}
|
||
let id = sim.sites.add(LaunchSite {
|
||
id: 0,
|
||
side: 0,
|
||
sector: 0,
|
||
bearing: 0.0,
|
||
class: SiteClass::Ramp,
|
||
pos: DVec3::new(0.0, 70.0, 700.0),
|
||
range: 700.0,
|
||
water: false,
|
||
stock: 30,
|
||
planned: 30,
|
||
alive: true,
|
||
next_free: 0,
|
||
offmap: true,
|
||
});
|
||
for i in 0..30 {
|
||
let mut d = sim.make_drone(DroneKind::Shahed, DVec3::new(0.0, 70.0, 700.0), -DVec3::Z, DVec3::new(0.0, 70.0, 0.0));
|
||
d.vel = DVec3::new(0.0, 0.0, -2.0);
|
||
sim.sites.job(d.id, id);
|
||
sim.queue.push((1 + i * 40, d));
|
||
}
|
||
let (mut ground, mut out) = (Ground::default(), Out::default());
|
||
// Shaheds crawl: it takes a while for the first to come into a radar's reach.
|
||
run(&mut sim, &mut ground, &mut out, 1500);
|
||
let k = sim.strikes.get(id).expect("scouted like any other site");
|
||
assert!(k.est.is_some(), "no launch is seen off the map, but the drones' tracks point back");
|
||
// Nothing to destroy there ...
|
||
assert_eq!(sim.destroy_site(id), 0);
|
||
// ... and the shot aims at what is known: force a good fix to test the outcome.
|
||
let k = sim.strikes.known.iter_mut().find(|k| k.site == id).unwrap();
|
||
k.est = Some(Estimate { pos: DVec2::new(0.0, 700.0), radius: 20.0, fix: true, bearing: 3.14, bearing_err: 0.01, origin: DVec2::ZERO });
|
||
sim.order_strike(id, DVec3::new(0.0, 64.0, 0.0), &mut out).unwrap();
|
||
out.messages.clear();
|
||
let wrecks = sim.fires.list.len();
|
||
run(&mut sim, &mut ground, &mut out, 500);
|
||
assert!(out.messages.iter().any(|m| m.contains("за пределами") && m.contains("прекратились")), "{:?}", out.messages);
|
||
assert!(sim.queue.is_empty() && !sim.sites.get(id).unwrap().alive);
|
||
// Nothing drawn: no wreck, no fire, no blast of its own.
|
||
assert_eq!((sim.strikes.wrecks.len(), sim.fires.list.len()), (0, wrecks));
|
||
}
|
||
|
||
#[test]
|
||
fn a_strike_leaves_one_event_for_the_replay_and_a_scenario_keeps_the_stock() {
|
||
let (mut sim, mut ground, mut out, id) = scene(11, 14, Some(DVec3::new(0.0, 64.0, 200.0)));
|
||
run(&mut sim, &mut ground, &mut out, 100);
|
||
// A recording is running (the launched drones started it): the strike lands in it.
|
||
sim.order_strike(id, DVec3::ZERO, &mut out).unwrap();
|
||
run(&mut sim, &mut ground, &mut out, 200);
|
||
let count = |r: &record::Recording| r.events.iter().filter(|e| matches!(e.kind, record::EventKind::Strike { .. })).count();
|
||
let n = sim.rec.iter().chain(sim.replays.iter()).map(count).sum::<usize>();
|
||
assert_eq!(n, 1);
|
||
// Saves: the stock and its progress come back, clamped to what is possible.
|
||
let mut s = Strikes::new();
|
||
s.restore(2, 4000);
|
||
assert_eq!((s.stock, s.progress), (2, 4000));
|
||
s.restore(99, 5);
|
||
assert_eq!((s.stock, s.progress), (TUNE.stock_max, 0));
|
||
s.restore(1, u32::MAX);
|
||
assert_eq!((s.stock, s.progress), (1, TUNE.resupply - 1));
|
||
}
|
||
|
||
/// The fixed scenario of the issue: a raid, a radar that opens its site by the launches, a strike that cancels the
|
||
/// launches left, and the raid's report that says so.
|
||
#[test]
|
||
fn a_planned_raid_loses_its_remaining_launches_to_a_strike_and_the_report_says_so() {
|
||
use super::sites::testland::{Land, serve};
|
||
let land = Land(|_, _| 64);
|
||
let (mut ground, mut out) = (Ground::default(), Out::default());
|
||
let mut sim = Sim::new(21);
|
||
sim.strikes.cover_override = Some(0);
|
||
let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 30)], approach: Approach::Sector, dist: 300.0, aim: Aim::Objects };
|
||
sim.order_raid(&order, &[DVec3::new(0.0, 70.0, 0.0)], &mut out);
|
||
let mut n = 0;
|
||
while sim.planning() {
|
||
serve(&mut ground, &land, sim.tick);
|
||
sim.step(&mut ground, None, &mut out);
|
||
n += 1;
|
||
assert!(n < 1000);
|
||
}
|
||
let site = sim.sites.list.iter().find(|s| s.class == SiteClass::Ramp).unwrap().clone();
|
||
// A radar near the ramp, fitted after the planning (the enemy chose its ground away from the defence).
|
||
let id = sim.id();
|
||
sim.sams.push(Sam::new(id, SamKind::Patriot, site.pos + DVec3::new(60.0, 0.0, 0.0), 0.0));
|
||
let mut struck = false;
|
||
let mut left_at_strike = 0;
|
||
for _ in 0..3000 {
|
||
serve(&mut ground, &land, sim.tick);
|
||
sim.step(&mut ground, None, &mut out);
|
||
if !struck && sim.strikes.get(site.id).is_some_and(|k| k.est.is_some_and(|e| e.fix && e.radius < 40.0)) && sim.sites.pending(site.id) > 3 {
|
||
left_at_strike = sim.sites.pending(site.id);
|
||
sim.order_strike(site.id, DVec3::new(0.0, 70.0, 0.0), &mut out).unwrap();
|
||
struck = true;
|
||
}
|
||
}
|
||
assert!(struck, "the radar never opened the site");
|
||
let cut = out.messages.iter().find(|m| m.contains("Налёт сорван")).unwrap_or_else(|| panic!("{:?}", out.messages));
|
||
assert!(cut.contains(&format!("№{}", site.id)), "{cut}");
|
||
assert!(out.messages.iter().any(|m| m.contains("Налёт окончен")), "the raid is closed, not held open");
|
||
assert!(sim.queue.is_empty() && sim.sites.pending(site.id) == 0);
|
||
assert!(left_at_strike > 3);
|
||
}
|
||
}
|