Files
airdef/airdef-mod/src/sim/sensor_tests.rs
T
chexit 858735a4c6 Implement the first full radar-profile slice (#134)
Give the separate radar three real profiles over SamKind::Radar and the
typed catalog variants:

- radar_search: coarse, slow, long-range search plots; no fire authority.
- radar_height: raised mast, local refinement of low plots; no fire authority.
- radar_track: local search, fast revisit, two refined/fire channels.
- radar_multi remains the compatible universal profile, not best everywhere.

Tracks now carry the measuring station, product (search/refine/fire), and
quality (separate from identification), and keep the station's own plot when a
fresher network relay replaces the published position. A relay never refreshes
the measurement or authorizes a launch. Ordinary launches need the battery's
own confirmed fire plot; launcher-only batteries use a supporting radar's own
plot, and the existing heavy far shot keeps its cue-radar exception.

Per-tick refinement/fire work is bounded by profile channels and local search
radius. Off, damage, network and save/replay behavior are preserved: new saves
write the stable profile ID, old role-only lines migrate, and embedded SAM
radars keep their own fire authority. The deploy menu, status lines, map,
monitor, radar scope and /airdef why explain the profile, source, age, quality,
channels and refusal reason.

Models/textures are untouched: all profiles reuse the existing radar
silhouette (the separate art zone remains for its owner).

Tests: profile single/pair/full scenarios and duplicate station, channels,
relay source/age/quality, Off/damage, save migration, replay, embedded and
Multifunction radars, catalog/generator checks, airdef-mod suites, core lib
(non-balance on one thread; the four active balance tests in release) and core
scenarios.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-20 23:11:12 +03:00

691 lines
34 KiB
Rust

//! Radar scan cycles with ageing tracks (#46) and damage to a system's parts (#50).
use super::battery::{Measure, RadarRole};
use super::sight::{swept, FIRE_QUALITY, FORECAST_AGE};
use super::*;
fn flat() -> (Ground, Out) {
(Ground::default(), Out::default())
}
fn radar_at(sim: &mut Sim, kind: SamKind, x: f64) -> usize {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DVec3::new(x, 70.0, 0.0), 0.0));
sim.sams.len() - 1
}
/// A Shahed flying east along z = 40, from x = `from`, high enough to be above any horizon of the systems.
fn drone_from(sim: &mut Sim, from: f64) -> u32 {
sim.add_drone(DroneKind::Shahed, DVec3::new(from, 95.0, 40.0), DVec3::X, DVec3::new(5000.0, 95.0, 40.0));
sim.drones.last().unwrap().id
}
// #46: the radar measures a target when the beam passes it; between passes its track stays where it was measured.
#[test]
fn a_radar_measures_once_a_turn_and_the_track_stays_put_between() {
let mut sim = Sim::new(5);
let (mut ground, mut out) = flat();
let r = radar_at(&mut sim, SamKind::Radar, 0.0);
let id = drone_from(&mut sim, -150.0);
let (mut seen_at, mut last) = (Vec::new(), None::<(u64, DVec3)>);
let mut stale_gap = 0.0f64;
for _ in 0..700 {
sim.step(&mut ground, None, &mut out);
let Some(t) = sim.sams[r].track(id).copied() else { continue };
match last {
Some((tick, pos)) if tick == t.tick => {
assert_eq!(pos, t.pos, "the track moved without a new measurement");
let d = sim.drones.iter().find(|d| d.id == id).unwrap();
stale_gap = stale_gap.max(d.pos.distance(t.pos));
if t.age(sim.tick) > FORECAST_AGE {
assert!(t.forecast(sim.tick));
}
}
_ => seen_at.push(t.tick),
}
last = Some((t.tick, t.pos));
}
assert!(seen_at.len() >= 2, "measured {} times", seen_at.len());
// A turn of the early-warning radar is 140 ticks (less relative to a target that moves round it): never every tick.
assert!(seen_at.windows(2).all(|w| w[1] - w[0] >= 60), "{seen_at:?}");
assert!(stale_gap > 20.0, "the track never fell behind the target ({stale_gap})");
}
#[test]
fn a_beam_crossing_north_between_ticks_still_passes_a_target_there() {
let tau = std::f64::consts::TAU;
assert!(swept(0.01, tau - 0.05, 0.1));
assert!(swept(tau - 0.02, tau - 0.05, 0.1));
assert!(!swept(0.2, tau - 0.05, 0.1));
assert!(!swept(tau - 0.1, tau - 0.05, 0.1));
}
#[test]
fn two_radars_have_their_own_phase_and_the_network_keeps_the_age() {
let mut sim = Sim::new(7);
let (mut ground, mut out) = flat();
let a = radar_at(&mut sim, SamKind::Radar, 0.0);
let b = radar_at(&mut sim, SamKind::Radar, 500.0);
let n = radar_at(&mut sim, SamKind::P1sun, 250.0);
assert_ne!(sim.sams[a].beam, sim.sams[b].beam, "radars start at different phases");
let id = drone_from(&mut sim, -50.0);
let mut relayed = 0;
for _ in 0..800 {
sim.step(&mut ground, None, &mut out);
let own = |s: usize| sim.sams[s].track(id).map_or(0, |t| t.own_tick);
let Some(t) = sim.sams[n].track(id) else { continue };
relayed += 1;
assert_eq!(t.own_tick, 0, "a relayed measurement is not the receiver's own");
assert!(t.tick <= own(a).max(own(b)), "the network made a track fresher than any measurement");
if own(a).max(own(b)) > 0 {
assert_eq!(t.tick, own(a).max(own(b)), "the network holds the freshest measurement");
}
}
assert!(relayed > 100, "the network never passed a track ({relayed})");
}
#[test]
fn a_lock_measures_every_tick_and_a_dead_radar_stops_the_feed() {
let mut sim = Sim::new(3);
let (mut ground, mut out) = flat();
let p = radar_at(&mut sim, SamKind::Pantsir, 0.0);
let net = radar_at(&mut sim, SamKind::P1sun, 100.0);
let id = drone_from(&mut sim, -190.0);
let mut locked = 0;
for _ in 0..600 {
sim.step(&mut ground, None, &mut out);
if sim.sams[p].target == Some(id)
&& let Some(t) = sim.sams[p].track(id)
&& t.age(sim.tick) <= 1
&& t.locked
{
locked += 1;
}
}
assert!(locked > 5, "no fire-control lock ({locked})");
// The radar is destroyed: the network's track is no longer renewed.
let newest = sim.sams[net].tracks.iter().map(|t| t.tick).max();
sim.sams[p].health = 0.0;
let drones = sim.drones.iter().filter(|d| d.alive()).count();
for _ in 0..40 {
sim.step(&mut ground, None, &mut out);
}
assert!(sim.sams[p].tracks.is_empty() && sim.sams[p].seen.is_empty());
if drones > 0 {
assert!(sim.sams[net].tracks.iter().map(|t| t.tick).max() <= newest, "a dead radar still renewed a track");
}
}
#[test]
fn a_failed_radar_gives_no_own_tracks_but_the_network_still_feeds_it() {
let mut sim = Sim::new(9);
let (mut ground, mut out) = flat();
let p = radar_at(&mut sim, SamKind::Patriot, 0.0);
let early = radar_at(&mut sim, SamKind::Radar, 120.0);
let id = drone_from(&mut sim, -150.0);
sim.sams[p].comps.0[Part::Sensor as usize] = 0.0;
// Hold fire: the fed track is now acted on (an unidentified contact is a candidate under the
// general rules, #133), and this test is about the feed, not about the intercept.
sim.sams[p].roles = 0;
for _ in 0..500 {
sim.step(&mut ground, None, &mut out);
}
assert!(!sim.sams[p].radar_up());
assert!(sim.sams[p].own.is_empty(), "a failed radar measured something");
assert!(sim.sams[p].track(id).is_some(), "the network should still feed the system");
// Without its link it is blind.
sim.sams[p].comps.0[Part::Comms as usize] = 0.0;
sim.sams[p].tracks.clear();
for _ in 0..200 {
sim.step(&mut ground, None, &mut out);
}
assert!(sim.sams[p].tracks.is_empty(), "no link, no network tracks");
assert!(sim.sams[early].own.len() >= sim.sams[p].own.len());
}
// #50: a blast hurts the parts nearest to it.
#[test]
fn a_blast_from_behind_hurts_the_link_a_blast_from_the_front_the_drive() {
let at = DVec3::new(0.0, 70.0, 0.0);
let hurt = |dz: f64| {
let mut sim = Sim::new(4);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Patriot, at, 0.0));
let mut out = Out::default();
sim.blast_damage(at + DVec3::new(0.0, 3.0, dz), 2, &Ground::default(), &mut out);
assert!(sim.sams[0].alive());
let c = sim.sams[0].comps;
(1.0 - c.get(Part::Comms), 1.0 - c.get(Part::Mount), 1.0 - c.get(Part::Sensor))
};
let (back_comms, back_mount, _) = hurt(6.0);
let (front_comms, front_mount, _) = hurt(-6.0);
assert!(back_comms > back_mount, "behind: link {back_comms} drive {back_mount}");
assert!(front_mount > front_comms, "front: link {front_comms} drive {front_mount}");
}
#[test]
fn a_close_blast_can_leave_a_firing_but_immobile_system() {
// Over many blasts at moderate range some leave the system able to fire and unable to drive.
let mut found = false;
for seed in 0..60 {
let mut sim = Sim::new(seed);
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::Pantsir, DVec3::new(0.0, 70.0, 0.0), 0.0));
let mut out = Out::default();
sim.tick = seed;
sim.blast_damage(DVec3::new(0.0, 69.0, 6.0 + seed as f64 * 0.06), 3, &Ground::default(), &mut out);
let s = &sim.sams[0];
if s.alive() && s.part(Part::Tracks) <= 0.0 && s.part(Part::Launcher) > 0.0 && s.part(Part::Gun) > 0.0 {
assert!(!sim.order_move(0, DVec3::new(300.0, 70.0, 0.0)), "failed running gear must refuse a march");
assert!(why::missile_blocks(&sim.sams[0]) & why::LAUNCHER_DOWN == 0);
assert!(sim.why(0).iter().any(|c| matches!(c.reason, why::CheckReason::PartEffect(why::PartEffect::TracksFailed))), "{:?}", sim.why(0));
found = true;
break;
}
}
assert!(found, "no seed left it firing but immobile");
}
#[test]
fn a_fresh_own_radar_track_keeps_gun_hits_equal_day_and_night() {
fn firing(seed: u64, night: bool) -> (u32, u32) {
let mut sim = Sim::new(seed);
let (mut ground, mut out) = flat();
let gun = radar_at(&mut sim, SamKind::Gepard, 0.0);
sim.night = night;
sim.add_drone(
DroneKind::Shahed,
DVec3::new(0.0, 95.0, 35.0),
DVec3::ZERO,
DVec3::new(5000.0, 95.0, 35.0),
);
let starting_bursts = sim.sams[gun].bursts;
for _ in 0..240 {
sim.step(&mut ground, None, &mut out);
}
(starting_bursts - sim.sams[gun].bursts, sim.sams[gun].kills)
}
for seed in 0..32 {
let day = firing(seed, false);
let night = firing(seed, true);
assert!(day.0 > 0, "seed {seed} did not fire");
assert_eq!(night, day, "seed {seed}: radar gun changed its fire or kills at night");
}
}
#[test]
fn failed_parts_block_what_they_serve_and_repair_restores_them() {
let mut sim = Sim::new(2);
let g = radar_at(&mut sim, SamKind::Gepard, 0.0);
let p = radar_at(&mut sim, SamKind::Patriot, 400.0);
sim.sams[g].comps.0[Part::Gun as usize] = 0.0;
assert!(!sim.sams[g].gun_up());
assert!(why::gun_blocks(&sim.sams[g], 1, 1, 0.0, 10.0, 90.0, 0) & why::JAMMED != 0);
sim.sams[p].comps.0[Part::Launcher as usize] = 0.0;
assert!(why::missile_blocks(&sim.sams[p]) & why::LAUNCHER_DOWN != 0);
// A worn launcher: fewer cells, a longer reload.
sim.sams[p].comps.0[Part::Launcher as usize] = 0.3;
sim.sams[p].fit_cells();
let full = Sam::new(0, SamKind::Patriot, DVec3::ZERO, 0.0);
assert!(sim.sams[p].cells() < full.cells());
assert!(sim.sams[p].missiles <= sim.sams[p].cells());
assert!(sim.sams[p].reload_time() > full.reload_time());
// A worn mount turns slower, a failed one not at all.
sim.sams[p].comps.0[Part::Mount as usize] = 0.0;
assert_eq!(sim.sams[p].drive_fit(), 0.0);
sim.sams[p].comps.0[Part::Tracks as usize] = 0.0;
assert_eq!(sim.repair(), 2, "both damaged systems are counted");
assert!(sim.sams.iter().all(|s| s.comps.whole() && s.cells() == s.kind.spec().missile.as_ref().map_or(0, |m| m.magazine)));
assert!(sim.later.is_empty(), "repair must not leave cook-offs behind");
assert!(sim.order_move(p, DVec3::new(500.0, 70.0, 0.0)));
}
#[test]
fn the_same_seed_rolls_the_same_scan_and_damage() {
let run = || {
let mut sim = Sim::new(11);
let (mut ground, mut out) = flat();
let r = radar_at(&mut sim, SamKind::Radar, 0.0);
let id = drone_from(&mut sim, -150.0);
let mut ticks = Vec::new();
for _ in 0..500 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.sams[r].track(id) {
ticks.push(t.tick);
}
}
ticks
};
assert_eq!(run(), run());
}
// ---------------------------------------------------------------- #133: the class estimate
#[test]
fn the_classifier_steps_by_the_measurements_alone() {
// The same observed speeds give the same estimate whatever the contact truly is, and a
// contrary measurement replaces the hypothesis instead of being ignored.
let mut est = ClassEst::Unknown;
assert_eq!(est.step(1, 0.6), ClassEst::Unknown, "one blip says nothing of the class");
est = est.step(2, 0.6);
assert_eq!(est, ClassEst::Probable(Class::Drone));
est = est.step(3, 0.62);
assert_eq!(est, ClassEst::Firm(Class::Drone), "agreeing measurements firm the guess");
// The contact proves much faster (or the first readings misled): the hypothesis gives way,
// and one measurement is not enough to firm the new one.
est = est.step(4, 5.0);
assert_eq!(est, ClassEst::Probable(Class::Supersonic));
est = est.step(5, 5.1);
assert_eq!(est, ClassEst::Firm(Class::Supersonic));
// Whatever the true kind, the same observations read the same: a Kinzhal measured as a slow
// propeller is, to the network, a drone until its measurements say otherwise.
assert_eq!(ClassEst::Unknown.step(2, 0.5), ClassEst::Probable(Class::Drone));
}
#[test]
fn the_speed_bands_read_the_games_own_kinds_right() {
// The bands sit between the game's speed clusters: the measured speed of a kind reads as its
// class, so a slow Lancet is no jet and a Shahed no cruise missile. A fast ballistic and a
// supersonic missile fly alike (the Iskander and the Zircon): speed alone leaves that
// ambiguity, documented on `Class::of_speed`.
for kind in DroneKind::ALL {
let spec = kind.spec();
if spec.class == Class::Ballistic && spec.speed < 6.5 {
continue;
}
assert_eq!(Class::of_speed(spec.speed), spec.class, "{kind:?} at {} blocks a tick", spec.speed);
}
assert_eq!(Class::of_speed(5.0), Class::Supersonic, "a fast ballistic and a supersonic fly alike");
}
#[test]
fn the_first_blip_gives_no_class_and_no_speed() {
let mut sim = Sim::new(5);
let (mut ground, mut out) = flat();
let r = radar_at(&mut sim, SamKind::Radar, 0.0);
let id = drone_from(&mut sim, -150.0);
let mut first = None;
for _ in 0..300 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.sams[r].track(id) {
first = Some(*t);
break;
}
}
let t = first.expect("a track of the drone");
assert_eq!(t.hits, 1);
assert_eq!(t.class, ClassEst::Unknown, "the first measurement must not name a class");
assert_eq!(t.vel, DVec3::ZERO, "the true velocity must not leak into the track");
}
#[test]
fn tracks_of_different_kinds_one_class_firm_the_same_estimate() {
// A Shahed and a Gerbera are different machines of one class, flying alike; the picture both
// networks end up holding is the same: a firm slow drone, never a model name. (Faster kinds
// cross this little radar's reach between beam passes: too few measurements to firm anything.)
let roles = SamKind::S400.spec().roles;
let mut seen = Vec::new();
for kind in [DroneKind::Shahed, DroneKind::Gerbera] {
let mut sim = Sim::new(7);
let (mut ground, mut out) = flat();
// One radar: an uninterrupted chain of measurements (two early-warning radars do not
// exchange tracks — a radar is fed only when it serves fire control — so the second one
// would measure from a blank picture, its own chain apart).
radar_at(&mut sim, SamKind::Radar, 0.0);
let from = DVec3::new(-150.0, 95.0, 40.0);
sim.add_drone(kind, from, DVec3::X, DVec3::new(5000.0, 95.0, 40.0));
let id = sim.drones.last().unwrap().id;
let mut est = None;
for _ in 0..700 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.picture().get(&id) {
est = Some(t.class);
}
}
assert_eq!(est, Some(ClassEst::Firm(Class::Drone)), "{kind:?}: {est:?}");
// The wording and the class-dependent decisions come from the estimate, not the machine.
let est = est.unwrap();
seen.push((est, est.name(), est.mark(), est.in_roles(roles)));
}
assert_eq!(seen[0], seen[1], "the same observations read differently for two kinds: {seen:?}");
}
#[test]
fn the_role_policy_keeps_the_unidentified_and_holds_fire_with_no_roles() {
let some = Class::Drone.bit() | Class::Jet.bit();
// An unidentified contact is not a block: it stays a candidate under the general rules.
assert!(ClassEst::Unknown.in_roles(some));
// No roles at all is holding fire: nothing is a candidate, the unidentified included.
assert!(!ClassEst::Unknown.in_roles(0), "hold fire must block the unidentified too");
// A probable guess is a block when its class is out of the roles, and a pass when in them.
assert!(ClassEst::Probable(Class::Drone).in_roles(some));
assert!(!ClassEst::Probable(Class::Cruise).in_roles(some));
assert!(ClassEst::Firm(Class::Jet).in_roles(some));
assert!(!ClassEst::Firm(Class::Ballistic).in_roles(0));
}
#[test]
fn a_gun_lets_go_of_a_track_classified_out_of_its_roles() {
// The Gepard's roles are drones, jets and cruise missiles: a supersonic missile is out of them.
assert_eq!(SamKind::Gepard.spec().roles & Class::Supersonic.bit(), 0);
let mut sim = Sim::new(11);
let (mut ground, mut out) = flat();
let p = radar_at(&mut sim, SamKind::Gepard, 0.0);
sim.add_drone(DroneKind::Zircon, DVec3::new(0.0, 95.0, -60.0), DVec3::Z, DVec3::new(0.0, 70.0, -700.0));
let id = sim.drones.last().unwrap().id;
sim.tick = 10;
let seed = |sim: &mut Sim, class| {
let d = sim.drones[0].clone();
sim.sams[p].tracks.retain(|t| t.id != d.id);
let source = sim.sams[p].id;
sim.sams[p].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: sim.tick, own_tick: sim.tick, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false });
};
// Taken while the class was unknown: the general rules make it a candidate.
seed(&mut sim, ClassEst::Unknown);
sim.step_sams(&mut ground, &mut out);
assert_eq!(sim.sams[p].gun_target, Some(id), "an unidentified track is not its gun target");
// Classified: no longer a class the gun engages, and it is let go instead of being fired at.
seed(&mut sim, ClassEst::Firm(Class::Supersonic));
sim.step_sams(&mut ground, &mut out);
assert_eq!(sim.sams[p].gun_target, None, "the gun kept a track its roles do not cover");
}
#[test]
fn forecasts_and_relays_add_no_confidence() {
let mut sim = Sim::new(7);
let (mut ground, mut out) = flat();
let a = radar_at(&mut sim, SamKind::Radar, 0.0);
let _b = radar_at(&mut sim, SamKind::Radar, 500.0);
let n = radar_at(&mut sim, SamKind::P1sun, 250.0);
let id = drone_from(&mut sim, -50.0);
// The source's own track: while no new measurement lands (the tick unchanged, the track only
// forecast onwards) the estimate must not move — a forecast is not data.
let mut prev: Option<(u64, ClassEst)> = None;
let mut relayed = 0;
for _ in 0..800 {
sim.step(&mut ground, None, &mut out);
if let Some(t) = sim.sams[a].track(id).copied() {
if let Some((tick, class)) = prev {
assert!(t.tick > tick || t.class == class, "a forecast or a re-read firmed the class: {tick}->{:?} {:?}->{:?}", t.tick, class, t.class);
}
prev = Some((t.tick, t.class));
}
// The network's copy carries the estimate as it was, with its measurement's age; passing
// it on adds nothing (the receiver never measures: own_tick stays 0).
if let Some(t) = sim.sams[n].track(id).copied() {
relayed += 1;
assert_eq!(t.own_tick, 0);
let freshest = sim.sams.iter().filter(|s| s.id != sim.sams[n].id).filter_map(|s| s.track(id)).max_by_key(|t| t.tick);
assert_eq!(Some(t.class), freshest.map(|f| f.class), "a relay altered the estimate");
}
}
assert!(relayed > 100, "the network never passed the track ({relayed})");
assert!(prev.is_some_and(|(_, c)| c.class().is_some()), "the source never classified the contact");
}
// ---------------------------------------------------------------- separate radar profiles (#134)
fn radar_with_role(sim: &mut Sim, role: RadarRole, x: f64) -> usize {
let id = sim.id();
let mut sam = Sam::new(id, SamKind::Radar, DVec3::new(x, 70.0, 0.0), 0.0);
sam.set_radar_role(role);
sim.sams.push(sam);
sim.sams.len() - 1
}
fn bearing(from: DVec3, to: DVec3) -> f64 {
(to.x - from.x).atan2(-(to.z - from.z))
}
/// The beam of every radar is pointed at one of `targets` in turn, so a test
/// does not depend on where the initial phase happened to be.
fn sweep(sim: &mut Sim, ground: &mut Ground, radars: &[usize], targets: &[DVec3], tick: u64) {
sim.tick = tick;
for (k, &i) in radars.iter().enumerate() {
let at = targets[(tick as usize + k) % targets.len()];
sim.sams[i].beam = bearing(sim.sams[i].pos, at);
}
sim.update_sight(ground);
}
#[derive(Default, Debug, PartialEq, Eq)]
struct ProfileStats {
first_high: Option<u64>,
first_low_refined: Option<u64>,
first_close_fire: Option<u64>,
max_channels: usize,
search_or_height_authorized: bool,
}
/// A low contact at 330 blocks (above the search/engagement horizon but below
/// the mast's), a high contact at 700/430 (inside the search reach but outside
/// the mast's and engagement's local search), and two close contacts for the
/// tracked-contact channels.
fn profile_world(roles: &[RadarRole]) -> (Sim, Vec<usize>, Vec<u32>, Ground) {
let mut sim = Sim::new(134);
let radars: Vec<usize> = roles.iter().map(|role| radar_with_role(&mut sim, *role, 0.0)).collect();
sim.add_drone(DroneKind::Shahed, DVec3::new(330.0, 95.0, 0.0), DVec3::Z, DVec3::new(330.0, 95.0, 0.0));
let low = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Shahed, DVec3::new(700.0, 500.0, 0.0), DVec3::Z, DVec3::new(700.0, 500.0, 0.0));
let high = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let close1 = sim.drones.last().unwrap().id;
sim.add_drone(DroneKind::Gerbera, DVec3::new(180.0, 130.0, 40.0), DVec3::Z, DVec3::new(180.0, 130.0, 40.0));
let close2 = sim.drones.last().unwrap().id;
(sim, radars, vec![low, high, close1, close2], Ground::default())
}
fn run_profile_world(roles: &[RadarRole], ticks: u64) -> (ProfileStats, Sim, Vec<usize>, Vec<u32>) {
let (mut sim, radars, ids, mut ground) = profile_world(roles);
let [low, high, close1, close2] = [ids[0], ids[1], ids[2], ids[3]];
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
let mut stats = ProfileStats::default();
for tick in 1..=ticks {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
for &i in &radars {
let sam = &sim.sams[i];
for t in sam.tracks.iter().filter(|t| t.own_tick > 0) {
match t.id {
id if id == high && stats.first_high.is_none() => stats.first_high = Some(tick),
id if id == low && t.product == Measure::Refine && stats.first_low_refined.is_none() => stats.first_low_refined = Some(tick),
id if (id == close1 || id == close2) && t.product == Measure::Fire && t.own_authorizes(sim.tick) && stats.first_close_fire.is_none() => stats.first_close_fire = Some(tick),
_ => {}
}
}
if sam.radar_profile().id == "radar_search" || sam.radar_profile().id == "radar_height" {
stats.search_or_height_authorized |= sam.tracks.iter().any(|t| t.own_authorizes(sim.tick));
}
stats.max_channels = stats.max_channels.max(sam.own_channels_used());
}
}
(stats, sim, radars, ids)
}
#[test]
fn each_profile_is_useful_alone_and_the_full_set_covers_all_three_jobs() {
let search = run_profile_world(&[RadarRole::Search], 500).0;
assert!(search.first_high.is_some(), "the search radar gives no early high plot: {search:?}");
assert!(search.first_low_refined.is_none(), "search refined a low contact it does not reach: {search:?}");
assert!(search.first_close_fire.is_none(), "search authorized a launch: {search:?}");
let height = run_profile_world(&[RadarRole::Height], 500).0;
assert!(height.first_high.is_none(), "the mast radar searched beyond its local patch: {height:?}");
assert!(height.first_low_refined.is_some(), "the mast radar did not refine the low contact: {height:?}");
assert!(height.first_close_fire.is_none(), "the mast radar authorized a launch: {height:?}");
let engagement = run_profile_world(&[RadarRole::Engagement], 500).0;
assert!(engagement.first_high.is_none(), "the engagement radar searched beyond its local patch: {engagement:?}");
assert!(engagement.first_low_refined.is_none(), "the engagement radar reached a low contact below the horizon: {engagement:?}");
assert!(engagement.first_close_fire.is_some(), "the engagement radar gave no fire plot: {engagement:?}");
assert!(engagement.max_channels <= 2, "more than two tracked contacts: {engagement:?}");
let search_height = run_profile_world(&[RadarRole::Search, RadarRole::Height], 500).0;
assert!(search_height.first_high.is_some() && search_height.first_low_refined.is_some());
assert!(search_height.first_close_fire.is_none(), "a search/height pair authorized a launch: {search_height:?}");
let search_engagement = run_profile_world(&[RadarRole::Search, RadarRole::Engagement], 500).0;
assert!(search_engagement.first_high.is_some() && search_engagement.first_close_fire.is_some());
assert!(search_engagement.first_low_refined.is_none(), "the pair covered the mast's low gap: {search_engagement:?}");
let height_engagement = run_profile_world(&[RadarRole::Height, RadarRole::Engagement], 500).0;
assert!(height_engagement.first_low_refined.is_some() && height_engagement.first_close_fire.is_some());
assert!(height_engagement.first_high.is_none(), "the pair covered the search's far picture: {height_engagement:?}");
let full = run_profile_world(&[RadarRole::Search, RadarRole::Height, RadarRole::Engagement], 500).0;
assert!(full.first_high.is_some() && full.first_low_refined.is_some() && full.first_close_fire.is_some(), "{full:?}");
assert!(!full.search_or_height_authorized, "a non-fire radar authorized a launch");
// There is no set bonus in the profile table: a duplicated station adds no
// function, and the full set's advantage is only the union of the three jobs.
let duplicate = run_profile_world(&[RadarRole::Search, RadarRole::Search], 500).0;
assert!(duplicate.first_low_refined.is_none() && duplicate.first_close_fire.is_none(), "two search radars invented another function: {duplicate:?}");
}
#[test]
fn network_relay_keeps_source_age_and_quality_but_not_launch_authority() {
let mut sim = Sim::new(1341);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
let receiver = {
let id = sim.id();
let mut s400 = Sam::new(id, SamKind::S400, DVec3::new(20.0, 70.0, 0.0), 0.0);
// A blind receiver: only the network can give it a track.
s400.comps.0[Part::Sensor as usize] = 0.0;
s400.roles = 0xff;
sim.sams.push(s400);
sim.sams.len() - 1
};
sim.add_drone(DroneKind::Shahed, DVec3::new(200.0, 120.0, 0.0), DVec3::Z, DVec3::new(200.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [search, engagement];
for tick in 1..=120 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let own = sim.sams[engagement].track(id).expect("the engagement radar measured the target");
assert_eq!(own.source, sim.sams[engagement].id);
assert_eq!(own.product, Measure::Fire);
assert!(own.quality >= FIRE_QUALITY && own.own_authorizes(sim.tick));
let relayed = sim.sams[receiver].track(id).expect("the network shared the plot");
assert_eq!(relayed.own_tick, 0, "a relay became the receiver's own measurement");
assert_eq!(relayed.tick, own.tick, "a relay refreshed the measurement's age");
assert!(relayed.product == Measure::Fire && relayed.quality == own.quality, "relay lost product/quality");
assert_eq!(relayed.source, sim.sams[engagement].id, "relay lost the measuring station");
assert!(!relayed.own_authorizes(sim.tick));
let opts = why::Opts { last_chance: false, far_shots: false };
{
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
let drone = &sim.drones[0];
assert!(why::basis(&sim.sams[receiver], load, relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_none(), "a relayed plot authorized a launch");
}
// A launcher without a radar may use the supporting radar's own confirmed plot.
sim.sams[receiver].set_mode(battery::SamMode::LauncherOnly);
for tick in 121..=122 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let relayed = *sim.sams[receiver].track(id).expect("the launcher re-received the network plot");
assert!(why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick));
{
let load = sim.sams[receiver].kind.spec().missile.as_ref().unwrap();
let drone = &sim.drones[0];
assert!(why::basis(&sim.sams[receiver], load, &relayed, drone, sim.tick, 0, 1.0, opts, true, false).is_some());
}
// The search radar's plot is coarse: it does not authorize even a launcher.
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[search]], id, sim.tick));
// A broken data link ends the cue even while the radar itself still measures.
sim.sams[engagement].comps.0[Part::Comms as usize] = 0.0;
assert_eq!(sim.sams[engagement].link_range(), 0.0);
assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick), "a broken link still cued a launch");
}
#[test]
fn the_air_picture_prefers_the_better_plot_at_one_tick() {
let mut sim = Sim::new(1345);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let track = radar_with_role(&mut sim, RadarRole::Engagement, 10.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
for tick in 1..=5 {
sweep(&mut sim, &mut ground, &[search, track], &targets, tick);
}
let pic = sim.air_picture();
let t = pic.tracks.iter().find(|t| t.id == id).expect("the raid is on the picture");
assert_eq!(t.source, sim.sams[track].id, "a coarse plot won over the better one at the same tick");
assert_eq!(t.product, Measure::Fire);
assert!(t.own_authorizes(sim.tick));
}
#[test]
fn tracked_channels_are_a_hard_limit_but_the_rest_keep_search_plots() {
let mut sim = Sim::new(1344);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 0.0);
for x in [100.0, 140.0, 180.0, 220.0] {
sim.add_drone(DroneKind::Gerbera, DVec3::new(x, 120.0, 0.0), DVec3::Z, DVec3::new(x, 120.0, 0.0));
}
let mut ground = Ground::default();
let targets: Vec<DVec3> = sim.drones.iter().map(|d| d.pos).collect();
for tick in 1..=40 {
sweep(&mut sim, &mut ground, &[engagement], &targets, tick);
}
let own: Vec<&Track> = sim.sams[engagement].tracks.iter().filter(|t| t.own_tick > 0).collect();
let precise = own.iter().filter(|t| t.own_product != Measure::Search).count();
assert_eq!(precise, 2, "the station refined more contacts than its channels: {own:?}");
assert_eq!(sim.sams[engagement].own_channels_used(), 2);
assert_eq!(own.len(), 4, "a full station stopped giving coarse search plots: {own:?}");
assert!(own.iter().filter(|t| t.own_product == Measure::Search).all(|t| !t.own_authorizes(sim.tick)));
}
#[test]
fn off_and_damage_remove_the_station_and_its_quality_without_touching_neighbours() {
let mut sim = Sim::new(1342);
let search = radar_with_role(&mut sim, RadarRole::Search, 0.0);
let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 20.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(150.0, 120.0, 0.0), DVec3::Z, DVec3::new(150.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [search, engagement];
for tick in 1..=80 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(sim.sams[engagement].track(id).is_some_and(|t| t.own_authorizes(sim.tick)));
let healthy = sim.sams[engagement].track(id).unwrap().own_quality;
// Off: the station emits nothing, its own plots stop, the neighbour still feeds the network.
sim.sams[engagement].radar_on = false;
let before = sim.sams[engagement].track(id).map(|t| t.own_tick);
for tick in 81..=110 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(!sim.sams[engagement].radar_up());
assert_eq!(sim.sams[engagement].track(id).map(|t| t.own_tick), before, "a silent radar renewed its own plot");
assert!(sim.sams[search].track(id).is_some_and(|t| t.own_tick > 0));
// Damage: a worn sensor still measures, with worse quality and no launch right.
sim.sams[engagement].radar_on = true;
sim.sams[engagement].comps.0[Part::Sensor as usize] = 0.2;
for tick in 111..=180 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
let worn = sim.sams[engagement].track(id).expect("a worn radar still measures");
assert!(worn.own_quality < healthy, "damage did not lower quality: {worn:?}");
assert!(!worn.own_authorizes(sim.tick), "a worn sensor still authorized a launch");
}
#[test]
fn multifunction_and_embedded_radars_keep_their_fire_authority() {
let mut sim = Sim::new(1343);
let multi = radar_with_role(&mut sim, RadarRole::Multifunction, 0.0);
let pantsir = radar_at(&mut sim, SamKind::Pantsir, 20.0);
sim.add_drone(DroneKind::Gerbera, DVec3::new(120.0, 120.0, 0.0), DVec3::Z, DVec3::new(120.0, 120.0, 0.0));
let id = sim.drones[0].id;
let mut ground = Ground::default();
let targets = vec![sim.drones[0].pos];
let radars = [multi, pantsir];
for tick in 1..=100 {
sweep(&mut sim, &mut ground, &radars, &targets, tick);
}
assert!(sim.sams[multi].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "the universal profile lost its own fire plot");
assert!(sim.sams[pantsir].track(id).is_some_and(|t| t.own_authorizes(sim.tick)), "an embedded radar lost its own fire plot");
}