//! The conditions that decide whether a system fires, as predicates: `step_sams` decides with //! them, and `Sim::why` lists them for a chosen system (`/airdef why`, the monitor), so the //! explanation can't drift from the behaviour. Each predicate returns the set of reasons it //! fails (bits; 0 is a pass), so the diagnostic names the reasons and the simulation only asks //! whether there are none. use super::*; // ---------------------------------------------------------------- choosing a target /// Why a drone is not a candidate for a system at all. pub(super) const DEAD: u8 = 1; pub(super) const ROLE: u8 = 2; pub(super) const UNSEEN: u8 = 4; /// Its track is older than a launcher fires on. pub(super) const STALE: u8 = 8; const CLASS_PENDING: u8 = 16; /// Why a drone is not a candidate for a system at all. The role is checked against the track's /// *estimated* class, never the target's own (#133): an unidentified track is not blocked — the /// explicit policy is that it stays a candidate under the general rules (a system with no roles /// is holding its fire: nothing is a candidate for it) — and a probable or firm class out of the /// roles is, with the reason named in `why`. pub(super) fn target_blocks(roles: u8, track: Option<&Track>, now: u64, d: &Drone) -> u8 { (if d.alive() { 0 } else { DEAD }) | (if track.is_some_and(|t| t.class.in_roles(roles)) { 0 } else { ROLE }) | (if track.is_some() { 0 } else { UNSEEN }) | (if track.is_some_and(|t| t.age(now) > sight::MISSILE_AGE) { STALE } else { 0 }) } /// Alive, of a class the system engages (or not yet classified), and on its picture (own radar /// or the network's), fresh enough. pub(super) fn allowed(roles: u8, track: &Track, now: u64, d: &Drone) -> bool { target_blocks(roles, Some(track), now, d) == 0 } fn firing_blocks(sam: &Sam, track: Option<&Track>, now: u64, d: &Drone) -> u8 { let blocks = target_blocks(sam.roles, track, now, d); if blocks & ROLE == 0 && sam.specializes_in_missiles() && track.is_some_and(|t| !matches!(t.class, ClassEst::Firm(_))) { blocks | CLASS_PENDING } else { blocks } } pub(super) const TOO_CLOSE: u8 = 1; pub(super) const TOO_FAR: u8 = 2; /// Missile range: `min` to `max * k` (a target already held may stray to 1.1 × max). pub(super) fn reach_blocks(min: f64, max: f64, k: f64, pos: DVec3, at: DVec3) -> u8 { let dist = at.distance(pos); (if dist >= min { 0 } else { TOO_CLOSE }) | (if dist < max * k { 0 } else { TOO_FAR }) } pub(super) fn in_reach(min: f64, max: f64, k: f64, pos: DVec3, at: DVec3) -> bool { reach_blocks(min, max, k, pos, at) == 0 } /// Interceptors a target has or will have: in flight, and other systems' launchers on it. pub(super) fn claimed(d: &Drone, missile_on: &HashMap, had_target: Option) -> u32 { let on = missile_on.get(&d.id).copied().unwrap_or(0) - u32::from(had_target == Some(d.id)); d.engaged + on } /// Ticks until the target reaches its aim at its present speed. pub(super) fn arrival(d: &Drone) -> f64 { d.pos.distance(d.target) / d.vel.length().max(0.1) } /// Shoot-look-shoot that grows with urgency: a ballistic missile gets a pair, anything else one; a target /// this close to its aim (ticks) has one more interceptor allowed on it at once, closer still another, and in the last seconds a fourth. /// The class is the track's estimate (#133): an unidentified contact is treated as not ballistic. pub(super) const URGENT: f64 = 240.0; pub(super) const DESPERATE: f64 = 110.0; pub(super) const FINAL: f64 = 60.0; pub(super) fn needed(d: &Drone, class: ClassEst) -> u32 { let base = if class.class() == Some(Class::Ballistic) { 2 } else { 1 }; let t = arrival(d); base + u32::from(t < URGENT) + u32::from(t < DESPERATE) + u32::from(t < FINAL) } /// Ticks a launcher may hold a target without launching before it lets go, and how long it then keeps away from it. pub(super) const HOLD_MAX: u32 = 24; pub(super) const SHY_TICKS: u64 = 120; // ---------------------------------------------------------------- the grounds to launch on /// A known, out-of-role contact may receive an emergency shot if it is closing on its game aim. pub(super) const LAST_CHANCE_TICKS: f64 = 120.0; const SPECIALIST_LAST_CHANCE_TICKS: f64 = 80.0; fn closing_arrival(d: &Drone) -> f64 { let to_aim = d.target - d.pos; let distance = to_aim.length(); let closing = d.vel.dot(to_aim.normalize_or_zero()); if closing > 0.1 { distance / closing } else { f64::INFINITY } } fn last_chance(on: bool, sam: &Sam, class: ClassEst, d: &Drone, claimed: u32) -> bool { if !on || sam.roles == 0 || class.class().is_none() || class.in_roles(sam.roles) || claimed > 0 { return false; } if sam.specializes_in_missiles() { matches!(class, ClassEst::Firm(_)) && sam.missiles > sam.last_chance_reserve() && closing_arrival(d) < SPECIALIST_LAST_CHANCE_TICKS } else { arrival(d) < LAST_CHANCE_TICKS } } /// The big radar's cue (heavy systems only): they may fire out to `FAR_K` × max at a target the radar holds. pub(super) const FAR_K: f64 = 1.6; /// Ticks between one system's long shots; the share of the magazine it keeps for them; the radar track's age. pub(super) const FAR_COOLDOWN: u32 = 300; pub(super) const FAR_RADAR_AGE: u64 = 150; impl SamKind { /// Whether the kind takes long shots on a big radar's data. pub(super) fn far_shooter(self) -> bool { matches!(self, SamKind::S400 | SamKind::S500 | SamKind::Patriot) } } /// A live big radar in data-link reach of `sam` that measured `id` recently. pub(super) fn radar_cue(sam: &Sam, radars: &[&Sam], id: u32, now: u64) -> bool { radars.iter().any(|r| { r.radar_profile().products & battery::RadarProfile::FIRE_BIT != 0 && r.link_range() > 0.0 && sam.link_range() > 0.0 && r.alive() && !r.moving() && r.radar_up() && r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range()) && r.track(id).is_some_and(|t| { let age = if sam.mode == battery::SamMode::LauncherOnly { sight::MISSILE_AGE } else { FAR_RADAR_AGE }; t.own_fire_within(now, age) }) }) } /// The ground beyond `max`: a long shot is allowed (the system, its launcher and magazine, the flag, a cue). pub(super) fn far_blocks(on: bool, sam: &Sam, load: &units::MissileLoad, cued: bool, in_reach_of_any: bool) -> u8 { (if on && sam.kind.far_shooter() { 0 } else { FAR_OFF }) | (if cued { 0 } else { FAR_NO_CUE }) | (if sam.far_cooldown == 0 { 0 } else { FAR_WAIT }) | (if sam.missiles * 2 >= load.magazine { 0 } else { FAR_LOW }) | (if in_reach_of_any { FAR_BUSY } else { 0 }) } pub(super) const FAR_OFF: u8 = 1; pub(super) const FAR_NO_CUE: u8 = 2; pub(super) const FAR_WAIT: u8 = 4; pub(super) const FAR_LOW: u8 = 8; pub(super) const FAR_BUSY: u8 = 16; /// Why a system may launch at a target: its role, the last chance, or a long shot on the radar's cue. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) enum Basis { Role, LastChance, FarShot, } impl Sam { /// Heavy launchers with a role mask that excludes ordinary drones conserve their rounds. pub(super) fn specializes_in_missiles(&self) -> bool { matches!(self.kind, SamKind::S400 | SamKind::S500) && self.roles & Class::Drone.bit() == 0 } fn last_chance_reserve(&self) -> u32 { let air_capacity = self.cells().saturating_sub(self.ground_rounds); air_capacity.div_ceil(2).max(self.doctrine.reserve) } pub(super) fn shot_priority(&self, class: ClassEst, basis: Basis) -> u8 { if basis == Basis::LastChance { return 0; } if !self.specializes_in_missiles() { return 1; } match class.class() { Some(Class::Ballistic) => 4, Some(Class::Supersonic) => 3, Some(Class::Cruise) => 2, _ => 1, } } } /// What is switched on beyond the roles (the sim's settings). #[derive(Clone, Copy)] pub(super) struct Opts { pub last_chance: bool, pub far_shots: bool, } /// Whether, and on what basis, `sam` may launch at `d` on `track`: `k` stretches the reach (a held target /// may stray); `claimed` is the interceptors others have on it; `cued` that a big radar holds it; and /// `role_in_reach` that the system has a target of its roles in range anyway (no long shots then). #[allow(clippy::too_many_arguments)] pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Drone, now: u64, claimed: u32, k: f64, opts: Opts, cued: bool, role_in_reach: bool) -> Option { // A launch rests on the battery's own confirmed fire plot. A launcher // without its own radar may use a supporting radar's own fire plot; a // relayed plot, a search plot or a height refinement never authorizes an // ordinary shot. A heavy system's *far* shot is the exception it already // had: it may use the cue radar's own confirmed fire plot beyond its reach. let own = track.own_authorizes(now); if sam.mode == battery::SamMode::LauncherOnly { if !cued { return None; } } else if !own && !cued { return None; } let blocks = firing_blocks(sam, Some(track), now, d); if blocks & !ROLE != 0 { return None; } let est = track.class; let reach = reach_blocks(load.min, load.max, k, sam.pos, track.est(now)); if blocks & ROLE == 0 { // The doctrine (sector, protected objects, reserve) rules over the role's shots and the long ones; the last chance is past it. if sam.doctrine.area_blocks(sam.pos, track, now) | sam.doctrine.reserve_blocks(sam.missiles, d, est) != 0 { return None; } if reach == 0 { // A normal shot belongs to the battery's own confirmed measurement; // a launcher-only battery uses its supporting radar's (checked above). return (own || sam.mode == battery::SamMode::LauncherOnly).then_some(Basis::Role); } let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, track.est(now)) == 0; return (far && far_blocks(opts.far_shots, sam, load, cued, role_in_reach) == 0).then_some(Basis::FarShot); } (reach == 0 && (own || sam.mode == battery::SamMode::LauncherOnly) && last_chance(opts.last_chance, sam, est, d, claimed)).then_some(Basis::LastChance) } /// The kill chance of an interceptor that met its target `dist` from the launcher whose reach is `max`: /// whole up to `max`, falling linearly to half at `FAR_K` × max. pub(super) fn reach_fit(max: f64, dist: f64) -> f64 { 1.0 - 0.5 * ((dist - max) / (max * (FAR_K - 1.0))).clamp(0.0, 1.0) } /// A gun's candidates: measured by the system's own radar a moment ago and within the gun's tracking range /// (by the track's forecast, not the target's true place). pub(super) fn gun_candidate(roles: u8, doc: &doctrine::Doctrine, track: &Track, now: u64, gun_track: f64, pos: DVec3, d: &Drone) -> bool { allowed(roles, track, now, d) && doc.area_blocks(pos, track, now) == 0 && track.own_within(now, sight::GUN_PICK_AGE) && track.est(now).distance(pos) < gun_track } /// How many systems have each drone as their missile target and as their gun target. pub(super) fn engagement_counts(sams: &[Sam]) -> (HashMap, HashMap) { let mut missile_on = HashMap::new(); let mut guns_on = HashMap::new(); for s in sams { retarget(&mut missile_on, None, s.target); retarget(&mut guns_on, None, s.gun_target); } (missile_on, guns_on) } // ---------------------------------------------------------------- aiming /// Where the lead point is and the yaw and pitch that point the mount at it. pub(super) fn aim_wants(mount: DVec3, at: DVec3, vel: DVec3, lead_speed: f64) -> (DVec3, f64, f64) { let lead = at + vel * (at.distance(mount) / lead_speed); let to = lead - mount; let want_yaw = heading_of(to); let want_pitch = (to.y / to.length().max(0.01)).asin().clamp(-0.1, 1.45); (lead, want_yaw, want_pitch) } /// How far the mount still is from the aim, over the axes this family aims. pub(super) fn aim_error(family: Family, yaw: f64, pitch: f64, want_yaw: f64, want_pitch: f64) -> f64 { let yaw_error = angle_diff(yaw, want_yaw).abs(); match family { Family::Trainable | Family::Vertical => yaw_error, _ => yaw_error + (want_pitch - pitch).abs(), } } // ---------------------------------------------------------------- firing pub(super) const COOLDOWN: u8 = 1; pub(super) const RELOADING: u8 = 2; pub(super) const NO_ROUNDS: u8 = 4; /// The launcher has failed. pub(super) const LAUNCHER_DOWN: u8 = 8; /// What keeps a loaded launcher from firing now (aim aside). pub(super) fn missile_blocks(s: &Sam) -> u8 { (if s.part(Part::Launcher) > 0.0 { 0 } else { LAUNCHER_DOWN }) | (if s.cooldown == 0 { 0 } else { COOLDOWN }) | (if s.reloading == 0 { 0 } else { RELOADING }) | (if s.missiles > 0 { 0 } else { NO_ROUNDS }) } /// The launcher points near enough: a trainable one only by its training, a turret by its /// whole aim at this target, the vertical ones need nothing. pub(super) fn missile_aligned(family: Family, yaw: f64, mount: DVec3, t: Option, aim_id: u32, mt: u32, aim_error: f64) -> bool { match family { Family::Trainable => t.is_some_and(|t| angle_diff(yaw, heading_of(t - mount)).abs() < 0.15), Family::Turret => aim_id == mt && aim_error < 0.15, _ => true, } } pub(super) const NOT_AIMED: u8 = 8; pub(super) const AIM_ERROR: u8 = 16; pub(super) const OUT_OF_RANGE: u8 = 32; /// The gun is jammed (for a while, or failed). pub(super) const JAMMED: u8 = 64; /// Its radar has no fresh measurement of the target. pub(super) const NO_LOCK: u8 = 128; /// What keeps a gun from firing now: the turret on another target, not yet laid, out of range, /// and the gun's own cooldown, reload and shells (`COOLDOWN`, `RELOADING`, `NO_ROUNDS` bits). pub(super) fn gun_blocks(s: &Sam, aim_id: u32, gt: u32, aim_error: f64, dist: f64, range: f64, now: u64) -> u8 { (if aim_id == gt { 0 } else { NOT_AIMED }) | (if s.gun_up() { 0 } else { JAMMED }) | (if s.track(gt).is_some_and(|t| t.own_within(now, sight::GUN_AGE)) { 0 } else { NO_LOCK }) | (if aim_error < 0.1 { 0 } else { AIM_ERROR }) | (if dist < range { 0 } else { OUT_OF_RANGE }) | (if s.gun_cooldown == 0 { 0 } else { COOLDOWN }) | (if s.reloading == 0 { 0 } else { RELOADING }) | (if s.bursts > 0 { 0 } else { NO_ROUNDS }) } // ---------------------------------------------------------------- the saturation audit (#145) /// Why the armed systems hold their fire, counted over every (system, alive drone) pair at the /// moment of the call: the same predicates `step_sams` decides with, in the decision's order, so /// each pair lands on the first ground that stops it. On demand only — the diagnostic a /// regression scenario reads, never per-tick work. A pair the system would launch at now counts /// as `ready`; the interceptor outcomes (a launch that missed) are the session's [`Tally`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct LaunchAudit { /// The system's picture holds no track of the drone at all. pub no_track: u32, /// Its track is older than a launcher fires on (`MISSILE_AGE`). pub stale: u32, /// No own confirmed fire plot: a relayed or search plot, quality below `FIRE_QUALITY`, or own /// measurement too old — the track is there but does not authorize a launch. pub no_authority: u32, /// The estimated class is out of the system's roles, and no last chance applies. pub role: u32, /// The doctrine (sector, guarded objects, reserve) holds the shot. pub doctrine: u32, /// The forecast place is beyond the missile's reach, and no long shot is allowed. pub out_of_reach: u32, /// Enough interceptors are on it already (`doctrine.needed`). pub claimed: u32, /// The launcher is not ready: cooldown, reload, no rounds, failed. pub not_ready: u32, /// The mount is not laid on the target yet. pub not_aimed: u32, /// The land ruled the shot out (the cached verdict; an uncached one resolves within a tick). pub terrain: u32, /// Nothing stops the pair: the system would launch at it now. pub ready: u32, } impl LaunchAudit { /// The non-zero counts as a line, for a scenario report. pub fn text(&self) -> String { let parts = [ (self.no_track, "нет трассы"), (self.stale, "трасса протухла"), (self.no_authority, "нет права на пуск"), (self.role, "вне ролей"), (self.doctrine, "доктрина"), (self.out_of_reach, "вне дальности"), (self.claimed, "занята перехватчиками"), (self.not_ready, "пусковая не готова"), (self.not_aimed, "не наведена"), (self.terrain, "рельеф"), (self.ready, "готова стрелять"), ]; parts.iter().filter(|(n, _)| *n > 0).map(|(n, name)| format!("{name}: {n}")).collect::>().join(", ") } } impl Sim { pub(super) fn last_chance_for(&self, sam: &Sam, class: ClassEst, d: &Drone, claimed: u32) -> bool { last_chance(self.last_chance, sam, class, d, claimed) && !self.has_role_cover(sam, class, d) } /// A shorter-range role weapon with a usable track and time to engage. fn has_role_cover(&self, fallback: &Sam, class: ClassEst, d: &Drone) -> bool { let now = self.tick; let specialist = fallback.specializes_in_missiles(); let lead = if specialist { (closing_arrival(d) - 20.0).clamp(0.0, 60.0) } else { (arrival(d) - 20.0).clamp(0.0, 40.0) }; let reach = fallback.kind.range(); self.sams.iter().any(|sam| { if sam.id == fallback.id || !sam.alive() || sam.moving() || sam.reloading > 0 || sam.kind.range() >= reach { return false; } let Some(track) = sam.track(d.id) else { return false }; let estimate = if specialist && !matches!(track.class, ClassEst::Firm(_)) { class } else { track.class }; if estimate.class().is_none() { return false; } if !estimate.in_roles(sam.roles) || track.age(now) > sight::MISSILE_AGE || sam.doctrine.area_blocks(sam.pos, track, now) != 0 { return false; } let at = track.est(now); let soon = at + track.vel * lead; let closest = |to: DVec3, ready: u32| { let speed_sq = track.vel.length_squared(); let nearest = if speed_sq > 1e-6 { (to - at).dot(track.vel) / speed_sq } else { 0.0 }; at + track.vel * nearest.clamp(f64::from(ready).min(lead), lead) }; let available = |target: Option| target.is_none_or(|id| id == d.id); let spec = sam.kind.spec(); let gun = spec.gun.as_ref().is_some_and(|gun| { let mount = sam.mount().0; sam.gun_up() && sam.bursts > 0 && f64::from(sam.gun_cooldown) <= lead && available(sam.gun_target) && track.own_within(now, sight::GUN_PICK_AGE) && closest(mount, sam.gun_cooldown).distance(mount) < gun.range }); gun || spec.missile.as_ref().is_some_and(|load| { let authority = if sam.mode == battery::SamMode::LauncherOnly { self.sams.iter().any(|radar| radar_cue(sam, &[radar], d.id, now)) } else { track.own_authorizes(now) }; sam.missiles > 0 && f64::from(sam.cooldown) <= lead && sam.part(Part::Launcher) > 0.0 && (!sam.specializes_in_missiles() || matches!(track.class, ClassEst::Firm(_))) && available(sam.target) && !sam.preparing.is_some_and(|p| p.ground) && sam.terrain_verdict(d.id, now).is_none_or(|v| v == 0) && sam.doctrine.reserve_blocks(sam.missiles, d, estimate) == 0 && closest(sam.pos, sam.cooldown).distance(sam.pos) < load.max && (at + track.vel * f64::from(sam.cooldown)).distance(sam.pos).max(soon.distance(sam.pos)) >= load.min && authority }) }) } /// The saturation audit: every armed system against every alive drone, attributed to the first /// ground that stops the shot. Reads the tracks' estimates and provenance, never the target's /// own class or velocity (#133). pub fn launch_audit(&self) -> LaunchAudit { let mut a = LaunchAudit::default(); let now = self.tick; let (missile_on, _) = engagement_counts(&self.sams); let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect(); let opts = Opts { last_chance: self.last_chance, far_shots: self.far_shots }; for sam in &self.sams { let Some(load) = sam.kind.spec().missile.as_ref() else { continue }; if !sam.alive() || sam.moving() { continue; } let spec = sam.kind.spec(); let mount = sam.mount().0; let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell); let cued = |id: u32| !radars.is_empty() && radar_cue(sam, &radars, id, now); // Long shots only while nothing of the system's roles is in its normal reach. let role_in_reach = !radars.is_empty() && sam.tracks.iter().any(|tr| { self.drones.iter().find(|d| d.id == tr.id).is_some_and(|d| { claimed(d, &missile_on, sam.target) < sam.doctrine.needed(d, tr.class) && basis(sam, load, tr, d, now, claimed(d, &missile_on, sam.target), 1.0, opts, cued(tr.id), true) == Some(Basis::Role) }) }); for d in self.drones.iter().filter(|d| d.alive()) { let Some(tr) = sam.track(d.id) else { a.no_track += 1; continue; }; let blocks = firing_blocks(sam, Some(tr), now, d); if blocks & STALE != 0 { a.stale += 1; continue; } let own = tr.own_authorizes(now); let cue = cued(d.id); let authorized = if sam.mode == battery::SamMode::LauncherOnly { cue } else { own || cue }; if !authorized { a.no_authority += 1; continue; } let est = tr.class; let free = claimed(d, &missile_on, sam.target); let chance = blocks & ROLE != 0 && self.last_chance_for(sam, est, d, free); if blocks & CLASS_PENDING != 0 || (blocks & ROLE != 0 && !chance) { a.role += 1; continue; } if blocks & ROLE == 0 && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, d, est) != 0 { a.doctrine += 1; continue; } let est_at = tr.est(now); let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est_at); let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0 && far_blocks(opts.far_shots, sam, load, cue, role_in_reach) == 0; if reach != 0 && !(far && blocks & ROLE == 0) { a.out_of_reach += 1; continue; } if reach == 0 && !(own || sam.mode == battery::SamMode::LauncherOnly) { a.no_authority += 1; continue; } if free >= sam.doctrine.needed(d, est) { a.claimed += 1; continue; } if missile_blocks(sam) != 0 { a.not_ready += 1; continue; } let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, tr.vel, lead_speed); let err = aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch); if !missile_aligned(spec.family, sam.yaw, mount, Some(est_at), d.id, d.id, err) { a.not_aimed += 1; continue; } if sam.terrain_verdict(d.id, now).unwrap_or(0) != 0 { a.terrain += 1; continue; } a.ready += 1; } } a } } // ---------------------------------------------------------------- the diagnostic /// A diagnostic condition and its structured or legacy reason. #[derive(Debug)] pub struct Check { pub ok: bool, pub reason: CheckReason, } #[derive(Debug)] pub enum CheckReason { /// Diagnostics not yet migrated to typed reasons. Text(String), Parts(Vec<(Part, f64)>), PartEffect(PartEffect), /// The one headline reason a battery fires or does not, shared by the sim, the monitor and /// the chat command. Battle(BattleReason), } // ---------------------------------------------------------------- the one headline reason /// What a battery's picture holds of a contact: the newest plot, its age and the station that /// made it. Only what the battery itself can know: a relayed plot's source, never the drone's /// true kind or place. #[derive(Clone, Copy, PartialEq, Debug)] pub struct BattleMark { /// Ticks since the newest measurement (any station). pub age: u64, /// Ticks since this battery's own radar measured it, if it ever did. pub own_age: Option, /// The station that made the newest plot, as an index into `Sim::sams`. pub source: Option, /// The newest plot is this battery's own measurement. pub own: bool, /// What the newest plot is good for. pub product: battery::Measure, pub quality: u8, /// This battery's own measurement's product, if it has one. pub own_product: Option, /// The plot is carried on as a forecast, not a fresh measurement. pub forecast: bool, /// The class the picture estimated, never the target's own kind. pub class: ClassEst, } impl BattleMark { fn of(sim: &Sim, sam: &Sam, track: &sight::Track, now: u64) -> Self { BattleMark { age: track.age(now), own_age: (track.own_tick > 0).then(|| now.saturating_sub(track.own_tick)), source: sim.sams.iter().position(|s| s.id == track.source), own: track.source == sam.id, product: track.product, quality: track.quality, own_product: (track.own_tick > 0).then_some(track.own_product), forecast: track.forecast(now), class: track.class, } } } /// The headline state of a battery, in the words the player asks with. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum BattleKind { /// It can fire at the target it holds now. Ready, /// Есть только обзор: a search plot or a relayed one, no fire-quality measurement. ObserveOnly, /// Ждёт сопровождения: its own radar is refining, or a launcher waits for a supporting /// radar's fire plot. AwaitingTrack, /// Каналы заняты: every tracked-contact channel of its radar is in use by other contacts. ChannelsBusy, /// Нет боезапаса: no rounds and no shells, or reloading. NoAmmo, /// Something else stops it, named by `block`. Blocked, } /// What stops a battery that is otherwise ready to engage. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum BattleBlock { Destroyed, Moving, Hold, NoWeapon, NoTarget, NoTrack, ClassPending, OutOfRoles, OutOfReach, Claimed, Doctrine, Aiming, Preparing, LauncherDown, Other, } /// The one reason, in a typed form. `mark` is the contact's own picture (age, source, product); /// a hidden truth never enters it. #[derive(Clone, Copy, PartialEq, Debug)] pub struct BattleReason { pub kind: BattleKind, pub block: Option, pub sam: usize, pub target: Option, pub mark: Option, pub rounds: u32, pub bursts: u32, /// Ticks left of a reload, 0 when loaded. pub reloading: u32, /// Tracked-contact channels in use and their total, when the radar has any. pub channels: Option<(usize, u8)>, } impl BattleReason { pub fn ready(self) -> bool { self.kind == BattleKind::Ready } /// The detailed decision (`why`) is the authority on whether a shot goes now: a headline /// that promised a shot it cannot take, or denied one it takes, is corrected here. pub fn settle(&mut self, fires: bool) { match (fires, self.kind == BattleKind::Ready) { (true, false) => { self.kind = BattleKind::Ready; self.block = None; } (false, true) => { self.kind = BattleKind::Blocked; self.block = Some(BattleBlock::Other); } _ => {} } } } impl Sim { /// Why battery `index` fires or doesn't, as one typed reason for the target it holds or the /// most threatening one its picture allows. The same predicates `step_sams` uses. pub fn battle_reason(&self, index: usize) -> Option { self.battle_reason_at(index, None) } /// The same, for a chosen contact (else the system's target, else the most threatening). pub fn battle_reason_at(&self, index: usize, chosen: Option) -> Option { let sam = self.sams.get(index)?; let spec = sam.kind.spec(); let now = self.tick; let channels = (spec.sensor > 0.0 && sam.mode != battery::SamMode::LauncherOnly && sam.radar_profile().channels > 0) .then(|| (sam.own_channels_used(now), sam.radar_profile().channels)); let reason = |kind, block, target, mark| BattleReason { kind, block, sam: index, target, mark, rounds: sam.missiles, bursts: sam.bursts, reloading: sam.reloading, channels, }; if !sam.alive() { return Some(reason(BattleKind::Blocked, Some(BattleBlock::Destroyed), None, None)); } if self.hold { return Some(reason(BattleKind::Blocked, Some(BattleBlock::Hold), None, None)); } if sam.moving() { return Some(reason(BattleKind::Blocked, Some(BattleBlock::Moving), None, None)); } if !sam.kind.armed() { return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoWeapon), None, None)); } let (missile_on, guns_on) = engagement_counts(&self.sams); let drone_at = |id: u32| self.drones.iter().find(|d| d.id == id); let subject = chosen .and_then(drone_at) .filter(|d| d.alive()) .or_else(|| sam.target.or(sam.gun_target).and_then(drone_at).filter(|d| d.alive())) .or_else(|| { self.drones .iter() .filter(|d| { d.alive() && (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles)) || self.last_chance_for(sam, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target))) }) .max_by(|a, b| { let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, now) == 0); area(a).cmp(&area(b)).then(a.threat(sam.pos).total_cmp(&b.threat(sam.pos))) }) }); let Some(t) = subject else { let block = if sam.roles == 0 { BattleBlock::Hold } else if self.drones.iter().any(|d| d.alive() && sam.seen.contains(&d.id)) { BattleBlock::OutOfRoles } else { BattleBlock::NoTarget }; return Some(reason(BattleKind::Blocked, Some(block), None, None)); }; let track = sam.track(t.id); let mark = track.map(|tr| BattleMark::of(self, sam, tr, now)); let has_missile = spec.missile.is_some() && sam.missiles > 0 && sam.part(Part::Launcher) > 0.0; let has_gun = spec.gun.is_some() && sam.bursts > 0 && sam.part(Part::Gun) > 0.0; if sam.reloading > 0 || (!has_missile && !has_gun) { return Some(reason(BattleKind::NoAmmo, None, Some(t.id), mark)); } if spec.missile.is_some() && sam.part(Part::Launcher) <= 0.0 && !has_gun { return Some(reason(BattleKind::Blocked, Some(BattleBlock::LauncherDown), Some(t.id), mark)); } let Some(tr) = track else { return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoTrack), Some(t.id), mark)); }; let est = tr.class; let blocks = firing_blocks(sam, Some(tr), now, t); let claimed_now = claimed(t, &missile_on, sam.target); if blocks & CLASS_PENDING != 0 { return Some(reason(BattleKind::Blocked, Some(BattleBlock::ClassPending), Some(t.id), mark)); } let chance = blocks & ROLE != 0 && self.last_chance_for(sam, est, t, claimed_now); if blocks & ROLE != 0 && !chance { return Some(reason(BattleKind::Blocked, Some(if sam.roles == 0 { BattleBlock::Hold } else { BattleBlock::OutOfRoles }), Some(t.id), mark)); } let doc = &sam.doctrine; let area = doc.area_blocks(sam.pos, tr, now); let reserve = spec.missile.is_some().then(|| doc.reserve_blocks(sam.missiles, t, est)).unwrap_or(0); if blocks & ROLE == 0 && (area | reserve) != 0 { return Some(reason(BattleKind::Blocked, Some(BattleBlock::Doctrine), Some(t.id), mark)); } let est_at = tr.est(now); let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect(); let cued = radar_cue(sam, &radars, t.id, now); let role_in_reach = spec.missile.as_ref().is_some_and(|load| { self.drones.iter().any(|o| { sam.track(o.id).is_some_and(|other| { firing_blocks(sam, Some(other), now, o) == 0 && in_reach(load.min, load.max, 1.0, sam.pos, other.est(now)) && doc.area_blocks(sam.pos, other, now) | doc.reserve_blocks(sam.missiles, o, other.class) == 0 && claimed(o, &missile_on, sam.target) < doc.needed(o, other.class) }) }) }); let reach = spec.missile.as_ref().map_or(0, |load| reach_blocks(load.min, load.max, 1.0, sam.pos, est_at)); let far_ok = spec.missile.as_ref().is_some_and(|load| { reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0 && far_blocks(self.far_shots, sam, load, cued, role_in_reach) == 0 }); if spec.missile.is_some() { if reach == TOO_CLOSE || (reach == TOO_FAR && !far_ok) { return Some(reason(BattleKind::Blocked, Some(BattleBlock::OutOfReach), Some(t.id), mark)); } } else if let Some(gun) = &spec.gun { if sam.mount().0.distance(est_at) >= gun.range { return Some(reason(BattleKind::Blocked, Some(BattleBlock::OutOfReach), Some(t.id), mark)); } } let own_fire = tr.own_authorizes(now); let gun_ready = spec.gun.is_some() && tr.own_within(now, sight::GUN_PICK_AGE); let authorized = if spec.missile.is_some() { own_fire || (sam.mode == battery::SamMode::LauncherOnly && cued) || far_ok } else { gun_ready }; if !authorized { if sam.mode == battery::SamMode::LauncherOnly { // The launcher's picture is the supporting radar's. If that radar has the // contact but every tracked-contact channel is taken, the reason is the // channels, not a missing hand-off. let support = radars.iter().find_map(|r| { let linked = r.alive() && !r.moving() && r.radar_up() && r.radar_profile().products & battery::RadarProfile::FIRE_BIT != 0 && r.link_range() > 0.0 && sam.link_range() > 0.0 && r.pos.distance(sam.pos) <= r.link_range().min(sam.link_range()); linked.then(|| r.track(t.id).map(|tr| (*r, *tr))).flatten() }); if let Some((radar, tr)) = support { let profile = radar.radar_profile(); let used = radar.own_channels_used(now); if profile.channels > 0 && used >= profile.channels as usize && !tr.own_authorizes(now) { let mut busy = reason(BattleKind::ChannelsBusy, None, Some(t.id), mark); busy.channels = Some((used, profile.channels)); return Some(busy); } } return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark)); } let busy = channels.is_some_and(|(used, total)| used >= total as usize); if busy { return Some(reason(BattleKind::ChannelsBusy, None, Some(t.id), mark)); } if tr.own_tick > 0 && tr.own_product == battery::Measure::Refine { return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark)); } if tr.own_tick > 0 && tr.own_product == battery::Measure::Fire { return Some(reason(BattleKind::AwaitingTrack, None, Some(t.id), mark)); } return Some(reason(BattleKind::ObserveOnly, None, Some(t.id), mark)); } let need = doc.needed(t, est); if spec.missile.is_some() && claimed_now >= need { return Some(reason(BattleKind::Blocked, Some(BattleBlock::Claimed), Some(t.id), mark)); } if spec.missile.is_none() && guns_on.get(&t.id).copied().unwrap_or(0) > 1 { return Some(reason(BattleKind::Blocked, Some(BattleBlock::Claimed), Some(t.id), mark)); } let mount = sam.mount().0; let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell); let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, tr.vel, lead_speed); if aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch) >= 0.15 { return Some(reason(BattleKind::Blocked, Some(BattleBlock::Aiming), Some(t.id), mark)); } if sam.preparing.is_some() { return Some(reason(BattleKind::Blocked, Some(BattleBlock::Preparing), Some(t.id), mark)); } Some(reason(BattleKind::Ready, None, Some(t.id), mark)) } } #[derive(Debug, PartialEq)] pub enum PartEffect { SensorFailed, SensorDamaged { fit: f64 }, MountFailed { yaw_degrees: f64 }, MountDamaged { fit: f64 }, LauncherFailed, LauncherDamaged { cells: u32, capacity: u32, reload_seconds: f64 }, GunFailed, GunDamaged { fit: f64 }, TracksFailed, TracksDamaged { speed: f64 }, CommsFailed, CommsDamaged { range: f64 }, } impl Check { #[cfg(test)] pub(super) fn legacy_text(&self) -> &str { match &self.reason { CheckReason::Text(text) => text, _ => "" } } } fn check(ok: bool, text: impl Into) -> Check { Check { ok, reason: CheckReason::Text(text.into()) } } fn part_check(reason: CheckReason) -> Check { Check { ok: false, reason } } fn battle_check(reason: Option) -> Check { let reason = reason.unwrap_or(BattleReason { kind: BattleKind::Blocked, block: Some(BattleBlock::Other), sam: 0, target: None, mark: None, rounds: 0, bursts: 0, reloading: 0, channels: None, }); Check { ok: reason.ready(), reason: CheckReason::Battle(reason) } } impl Sim { /// Why system `index` fires or doesn't, at its current target or at the most threatening /// drone of a class it engages; computed on demand from the very predicates `step_sams` /// uses. The last line is the verdict. pub fn why(&self, index: usize) -> Vec { let Some(sam) = self.sams.get(index) else { return vec![check(false, "Нет такой техники")] }; let spec = sam.kind.spec(); let mut v = vec![check(true, format!("№{} {}: {}", index + 1, spec.name, sam.state.name()))]; if !sam.alive() { v.push(check(false, "уничтожен")); v.push(battle_check(self.battle_reason(index))); return v; } if self.hold { v.push(check(false, "огонь запрещён (/airdef hold off)")); v.push(battle_check(self.battle_reason(index))); return v; } if sam.moving() { v.push(check(false, format!("{}: не стреляет", sam.state.name().to_lowercase()))); v.push(battle_check(self.battle_reason(index))); return v; } if !sam.kind.armed() { if sam.kind == SamKind::Radar { let profile = sam.radar_profile(); v.push(check(true, format!( "профиль {} [{}]: {}, оборот {:.1} с, каналы {}, локальный поиск {}", profile.name, profile.id, profile.products_text(), profile.cycle as f64 / 20.0, profile.channels, if profile.local >= 1.0 { "во всей дальности".to_string() } else { format!("{:.0}% дальности", profile.local * 100.0) }, ))); v.push(check(true, format!("ограничение: {}", profile.limit))); let now = self.tick; v.push(check(true, format!("свои треки: {}, каналы {}/{}", sam.own.len(), sam.own_channels_used(now), profile.channels))); let mut tracks: Vec<&Track> = sam.tracks.iter().filter(|t| t.own_tick > 0).collect(); tracks.sort_by_key(|t| std::cmp::Reverse(t.quality)); for t in tracks.into_iter().take(4) { v.push(check( t.own_authorizes(now), format!( "цель {}: {} ({}), качество {}, возраст {:.1} с{}", t.id, t.own_product.name(), if t.own_authorizes(now) { "право на пуск" } else { "пуск не разрешает" }, t.own_quality, now.saturating_sub(t.own_tick) as f64 / 20.0, if t.own_authorizes(now) { "" } else { "; нужно подтверждённое измерение станции" }, ), )); } } v.push(check(false, "нет оружия (РЛС, склад, РЭБ, прожектор)")); v.push(battle_check(self.battle_reason(index))); return v; } let (missile_on, guns_on) = engagement_counts(&self.sams); let alive = self.drones.iter().filter(|d| d.alive()).count(); let now = self.tick; let seen = self.drones.iter().filter(|d| d.alive() && sam.seen.contains(&d.id)).count(); let own = self.drones.iter().filter(|d| d.alive() && sam.own.contains(&d.id)).count(); v.push(check(alive > 0, format!("в небе {alive}, на картине {seen} (своя РЛС {own}, остальные по сети)"))); // The parts: what is worn or failed and what it costs. if !sam.comps.whole() { let parts = Part::ALL.into_iter().filter(|p| p.on(sam.kind) && sam.comps.get(*p) < 1.0) .map(|p| (p, sam.comps.get(p))).collect(); v.push(part_check(CheckReason::Parts(parts))); } for p in Part::ALL { if !p.on(sam.kind) || sam.part_state(p) == PartState::Ok { continue; } let failed = sam.part_state(p) == PartState::Failed; let effect = match (p, failed) { (Part::Sensor, true) => PartEffect::SensorFailed, (Part::Sensor, false) => PartEffect::SensorDamaged { fit: sam.radar_fit() }, (Part::Mount, true) => PartEffect::MountFailed { yaw_degrees: sam.yaw.to_degrees().rem_euclid(360.0) }, (Part::Mount, false) => PartEffect::MountDamaged { fit: sam.drive_fit() }, (Part::Launcher, true) => PartEffect::LauncherFailed, (Part::Launcher, false) => PartEffect::LauncherDamaged { cells: sam.cells(), capacity: spec.missile.as_ref().map_or(0, |m| m.magazine), reload_seconds: sam.reload_time() as f64 / 20.0 }, (Part::Gun, true) => PartEffect::GunFailed, (Part::Gun, false) => PartEffect::GunDamaged { fit: sam.gun_fit() }, (Part::Tracks, true) => PartEffect::TracksFailed, (Part::Tracks, false) => PartEffect::TracksDamaged { speed: sam.drive_speed() }, (Part::Comms, true) => PartEffect::CommsFailed, (Part::Comms, false) => PartEffect::CommsDamaged { range: sam.link_range() }, }; v.push(part_check(CheckReason::PartEffect(effect))); } if sam.jam > 0 { v.push(check(false, format!("орудие заклинило, ещё {:.1} с", sam.jam as f64 / 20.0))); } let drone_at = |id: u32| self.drones.iter().find(|d| d.id == id); let subject = sam.target.or(sam.gun_target).and_then(drone_at).or_else(|| { self.drones .iter() // Of what the system's picture holds: a track of its roles' classes (or not yet // classified), or a known out-of-role one about to hit (the last chance) — never // the target's own class (#133). .filter(|d| d.alive() && (sam.track(d.id).is_some_and(|tr| tr.class.in_roles(sam.roles)) || self.last_chance_for(sam, sam.track(d.id).map_or(ClassEst::Unknown, |tr| tr.class), d, claimed(d, &missile_on, sam.target)))) .max_by(|a, b| { // What the doctrine lets the system shoot at comes first; then the most threatening. let area = |d: &Drone| sam.track(d.id).is_none_or(|tr| sam.doctrine.area_blocks(sam.pos, tr, self.tick) == 0); area(a).cmp(&area(b)).then(a.threat(sam.pos).total_cmp(&b.threat(sam.pos))) }) }); let Some(t) = subject else { // Nothing to look at: either the sky holds nothing for this system, or it holds only // tracks whose estimated class is out of the roles — the reasons differ and are named (#133). let held = self.drones.iter().any(|d| d.alive() && sam.seen.contains(&d.id)); // No roles is holding fire: a reason of its own, not an empty class filter. let text = if sam.roles == 0 { "роль: система не ведёт огонь (роли не заданы) — ни одна цель не выбирается".to_string() } else if held { format!("цели на картине есть, но не в ролях [{}] (классы по оценке)", roles_text(sam.roles)) } else { format!("нет целей классов [{}]", roles_text(sam.roles)) }; v.push(check(false, text)); v.push(battle_check(self.battle_reason(index))); return v; }; let held = sam.target == Some(t.id) || sam.gun_target == Some(t.id); let dist = sam.track(t.id).map_or(t.pos, |tr| tr.est(self.tick)).distance(sam.pos); let track = sam.track(t.id); v.push(check( true, format!("цель: {} {}, {}", track.map_or_else(|| ClassEst::Unknown.name(), |tr| tr.class.name()), if held { "(сопровождается)" } else { "(самая опасная)" }, super::distance(dist)), )); let est = track.map_or(ClassEst::Unknown, |tr| tr.class); let blocks = firing_blocks(sam, track, now, t); // Where the system believes the target is: its track's forecast (the true place only when it has no track). let est_at = track.map_or(t.pos, |tr| tr.est(now)); let evel = track.map_or(t.vel, |tr| tr.vel); let first_claim = claimed(t, &missile_on, sam.target); let chance = blocks & ROLE != 0 && self.last_chance_for(sam, est, t, first_claim); let role_text = if blocks & CLASS_PENDING != 0 { "роль: комплекс ждёт подтверждения класса цели".to_string() } else if blocks & ROLE == 0 { match est { ClassEst::Unknown => "роль: тип не определён — цель ведётся по общим правилам, классовые ограничения не применяются".to_string(), _ => format!("роль: {} в ролях [{}]", est.name(), roles_text(sam.roles)), } } else if chance { format!( "последний шанс: {} не в ролях [{}], но до цели {:.0} с, перехватчиков на ней нет", est.name(), roles_text(sam.roles), if sam.specializes_in_missiles() { closing_arrival(t) } else { arrival(t) } / 20.0 ) } else if sam.roles == 0 { "роль: система не ведёт огонь (роли не заданы) — цель не выбирается".to_string() } else { format!("роль: {} не в ролях [{}]", est.name(), roles_text(sam.roles)) }; v.push(check(blocks & (CLASS_PENDING | ROLE) == 0 || chance, role_text)); if self.last_chance && sam.roles != 0 && sam.specializes_in_missiles() && blocks & (CLASS_PENDING | ROLE) == ROLE { let reserve = sam.last_chance_reserve(); if sam.missiles <= reserve { v.push(check(false, format!("последний шанс: сохранён резерв для основных целей ({}/{reserve})", sam.missiles))); } else if self.has_role_cover(sam, est, t) { v.push(check(false, "последний шанс: цель прикрывает комплекс ближнего действия".to_string())); } } // The doctrine: which of its settings let the shot through or stopped it. The last chance is past them. let doc = &sam.doctrine; let area = track.map_or(0, |tr| doc.area_blocks(sam.pos, tr, now)); let held_back = if spec.missile.is_some() { doc.reserve_blocks(sam.missiles, t, est) } else { 0 }; if !doc.is_default() { v.push(check(true, format!("доктрина: {}", doc.text(&self.targets)))); } if area & doctrine::OUT_SECTOR != 0 { let bearing = heading_of(est_at - sam.pos).to_degrees().rem_euclid(360.0); v.push(check(chance, format!("вне сектора {}: цель на {bearing:.0}°{}", doc.sector_text(), if chance { " — последний шанс сильнее" } else { "" }))); } else if doc.sector.is_some() { v.push(check(true, format!("в секторе {}", doc.sector_text()))); } if area & doctrine::NO_THREAT != 0 { v.push(check(chance, format!("не угрожает охраняемым объектам ({}){}", doc.guards.iter().map(|g| doctrine::object_name(&self.targets, *g)).collect::>().join(", "), if chance { " — последний шанс сильнее" } else { "" }))); } else if let Some(g) = track.and_then(|tr| doc.threatens(tr, now)) { v.push(check(true, format!("прикрывает {}: цель идёт на него", doctrine::object_name(&self.targets, doc.guards[g])))); } if held_back != 0 { v.push(check(chance, format!("сохраняет резерв {}: ракет {}, цель не срочная{}", doc.reserve, sam.missiles, if chance { " — последний шанс сильнее" } else { "" }))); } else if doc.reserve > 0 && sam.missiles <= doc.reserve { v.push(check(true, format!("резерв {} открыт: цель срочная (до удара {:.0} с)", doc.reserve, arrival(t) / 20.0))); } let detect = match (track, sam.own.contains(&t.id)) { (Some(tr), own) => { let kind = if own { "своей РЛС" } else { "по сети (стволы не стреляют)" }; let age = tr.age(now) as f64 / 20.0; let lock = if tr.own_within(now, sight::GUN_AGE) && tr.locked { ", захват" } else { "" }; let how = if tr.forecast(now) { format!("прогноз ±{:.0} м", tr.uncertainty(now)) } else { "измерение".to_string() }; let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect(); let authority = tr.own_authorizes(now) || (sam.mode == battery::SamMode::LauncherOnly && radar_cue(sam, &radars, t.id, now)); format!( "трек {kind}: {}, возраст {age:.1} с, {how}{lock}, {}, {}; право на пуск: {}", tr.ident().name(), tr.class.name(), if blocks & STALE != 0 { "устарел" } else { "годен" }, if authority { "своё подтверждённое измерение" } else { "нет (сеть или обзор не дают права)" } ) } _ => "не обнаружена ни своей РЛС, ни сетью".to_string(), }; v.push(check(blocks & (UNSEEN | STALE) == 0, detect)); if sam.mode == battery::SamMode::LauncherOnly { let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect(); let connected = radar_cue(sam, &radars, t.id, now); v.push(check(connected, if connected { "внешняя РЛС: свежий трек по связи" } else { "внешняя РЛС: нет свежего трека или связи" }.to_string())); } else if sam.kind.spec().sensor > 0.0 { let period = sam.scan_ticks(); v.push(check( sam.radar_up(), if sam.radar_up() { format!("обзор: оборот {:.1} с{}, луч на {:.0}°", period / 20.0, if sam.scan_profile().agile { ", электронный, цели в треке чаще" } else { "" }, sam.beam.to_degrees()) } else { "обзор: РЛС не работает".to_string() }, )); } // Ammunition and its supply. let mut rounds = String::new(); if let Some(load) = &spec.missile { rounds += &format!("ракет {}/{} ", sam.missiles, load.magazine); } if let Some(gun) = &spec.gun { rounds += &format!("очередей {}/{} ", sam.bursts, gun.bursts); } let supply = if sam.reloading > 0 { format!("перезарядка, ещё {:.1} с", sam.reloading as f64 / 20.0) } else if sam.empty { "пуст, ждёт пополнения со склада или ТЗМ".into() } else { "боезапас есть".into() }; v.push(check(sam.reloading == 0 && !sam.empty && (sam.missiles > 0 || sam.bursts > 0), format!("{rounds}— {supply}"))); let mount = sam.mount().0; let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell); let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, evel, lead_speed); let err = aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch); let vertical = spec.family == Family::Vertical; let mut fires = false; if let Some(load) = &spec.missile { let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est_at); // Beyond the normal reach, a heavy system may fire on a big radar's cue. let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect(); let cued = radar_cue(sam, &radars, t.id, now); let role_in_reach = self.drones.iter().any(|o| { sam.track(o.id).is_some_and(|tr| firing_blocks(sam, Some(tr), now, o) == 0 && in_reach(load.min, load.max, 1.0, sam.pos, tr.est(now)) && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, o, tr.class) == 0 && claimed(o, &missile_on, sam.target) < sam.doctrine.needed(o, tr.class)) }); let far = reach == TOO_FAR && reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0; let far_ok = far && track.is_some_and(|tr| basis(sam, load, tr, t, now, 0, 1.0, Opts { last_chance: self.last_chance, far_shots: self.far_shots }, cued, role_in_reach) == Some(Basis::FarShot)); if far { let fb = far_blocks(self.far_shots, sam, load, cued, role_in_reach); let mut no = Vec::new(); for (bit, name) in [ (FAR_OFF, "не для этого комплекса"), (FAR_NO_CUE, "нет свежего трека большой РЛС"), (FAR_WAIT, "дальний пуск уже был недавно"), (FAR_LOW, "меньше половины боезапаса"), (FAR_BUSY, "есть цель в обычной дальности"), ] { if fb & bit != 0 { no.push(name); } } v.push(check(far_ok, if far_ok { format!("дальний пуск по РЛС: цель на {} дальше обычных {}", super::distance(dist), super::distance(load.max)) } else { format!("дальний пуск по РЛС не разрешён: {}", no.join(", ")) })); } let free = first_claim; let need = sam.doctrine.needed(t, est); v.push(check(free < need, format!("цель занята перехватчиками: {free} из {need} (залп {}){}", doc.salvo.name(), if free < need { "" } else { " — другие уже на ней" }))); let mb = missile_blocks(sam); let mut why = Vec::new(); if mb & COOLDOWN != 0 { why.push(format!("интервал пусков ({:.1} с)", sam.cooldown as f64 / 20.0)); } if mb & RELOADING != 0 { why.push("перезарядка".to_string()); } if mb & NO_ROUNDS != 0 { why.push("нет ракет".to_string()); } if mb & LAUNCHER_DOWN != 0 { why.push("пусковая отказала".to_string()); } v.push(check(mb == 0, if mb == 0 { "пусковая готова".to_string() } else { format!("пусковая не готова: {}", why.join(", ")) })); let aligned = missile_aligned(spec.family, sam.yaw, mount, Some(est_at), t.id, t.id, err); let turn = if vertical { "вертикальный старт" } else { "доворот" }; v.push(check(aligned, format!("{turn}: ошибка наведения {:.0}°{}", err.to_degrees(), if aligned { "" } else { " — ещё доворачивается" }))); // The land: the verdict the launch decision gave this target (`terrain::launch_blocks`) a moment ago. let land = sam.terrain_verdict(t.id, now).unwrap_or(0); if land != 0 { v.push(check( false, if land & terrain::MASKED != 0 { "рельеф: цель за рельефом — ракета не стартует, ждём, пока цель выйдет из-за него" } else { "рельеф: траектория перекрыта рельефом — подняться над ним ракета не может" }, )); } let doc_ok = chance || area | held_back == 0; let own = track.is_some_and(|tr| tr.own_authorizes(now)); let authorized = own || (sam.mode == battery::SamMode::LauncherOnly && cued) || far_ok; let grounds = authorized && blocks & !ROLE == 0 && (blocks & ROLE == 0 || chance) && doc_ok && (reach == 0 || far_ok); fires |= grounds && free < need && mb == 0 && aligned && land == 0; } if let Some(gun) = &spec.gun { let on_it = guns_on.get(&t.id).copied().unwrap_or(0) - u32::from(sam.gun_target == Some(t.id)); let cand = track.is_some_and(|tr| gun_candidate(sam.roles, &sam.doctrine, tr, now, gun.track, sam.pos, t)); v.push(check( cand, format!( "орудие: сопровождение до {}, цель на {}, других орудий на ней {on_it}{}", super::distance(gun.track), super::distance(dist), if cand { "" } else { " — вне сопровождения (нужна своя РЛС)" } ), )); let gb = gun_blocks(sam, t.id, t.id, err, mount.distance(est_at), gun.range, now); let mut why = Vec::new(); for (bit, name) in [ (AIM_ERROR, format!("орудие ещё наводится ({:.0}°)", err.to_degrees())), (OUT_OF_RANGE, format!("дальше {}", super::distance(gun.range))), (COOLDOWN, "пауза между очередями".to_string()), (RELOADING, "перезарядка".to_string()), (NO_ROUNDS, "нет снарядов".to_string()), (JAMMED, "орудие заклинило".to_string()), (NO_LOCK, "нет свежего захвата своей РЛС".to_string()), ] { if gb & bit != 0 { why.push(name); } } v.push(check(gb == 0, if gb == 0 { "орудие готово".to_string() } else { format!("орудие не стреляет: {}", why.join(", ")) })); fires |= gb == 0 && cand; } if let Some(p) = sam.preparing { let opening = p.ground || now.saturating_sub(p.start) < launch::OPEN_TICKS; v.push(check(!opening, format!("подготовка пуска: открывается крышка ТПК №{}", p.cell + 1))); fires &= !opening; } v.push(check(fires, if fires { "итог: готова стрелять" } else { "итог: стрелять сейчас не может" })); // The one typed reason the monitor, the HUD and the chat show first; the detailed checks // below it explain it. The launch decision above has the final word. let mut headline = self.battle_reason_at(index, Some(t.id)).unwrap_or_else(|| BattleReason { kind: BattleKind::Blocked, block: Some(BattleBlock::Other), sam: index, target: Some(t.id), mark: track.map(|tr| BattleMark::of(self, sam, tr, now)), rounds: sam.missiles, bursts: sam.bursts, reloading: sam.reloading, channels: None, }); headline.settle(fires); v.insert(1, Check { ok: headline.ready(), reason: CheckReason::Battle(headline) }); v } } #[cfg(test)] mod tests { use super::*; #[test] fn why_names_the_reason_a_system_does_not_fire() { let mut sim = Sim::new(3); let id = sim.id(); sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::new(0.0, 70.0, 0.0), 0.0)); let mut ground = Ground::default(); let mut out = Out::default(); sim.sams[0].roles = 0; sim.raid(DroneKind::Shahed, DVec3::new(0.0, 70.0, 0.0), 1, 200.0, &mut out); for _ in 0..60 { sim.step(&mut ground, None, &mut out); } let w = sim.why(0); assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); sim.sams[0].roles = 0xFF; assert!(sim.why(0).iter().any(|c| c.legacy_text().starts_with("роль"))); } use super::sites::testland::{Land, serve}; fn setup(kind: SamKind) -> (Sim, Ground, Land i32>, Out) { let mut sim = Sim::new(5); let id = sim.id(); sim.sams.push(Sam::new(id, kind, DVec3::new(0.0, 70.0, 0.0), 0.0)); (sim, Ground::default(), Land(|_, _| 64), Out::default()) } /// Steps `ticks` or until something is fired; returns the drone's ticks to its aim at the first launch. fn until_fired(sim: &mut Sim, ground: &mut Ground, land: &Land i32>, out: &mut Out, ticks: u32) -> Option { for _ in 0..ticks { serve(ground, land, sim.tick); sim.step(ground, None, out); if sim.sams[0].fired > 0 { return sim.drones.first().map(arrival); } } None } /// A Shahed `blocks` short of its aim, which is `80` out from the system, coming in along z. fn shahed_at(sim: &mut Sim, blocks: f64) { sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -80.0 - blocks), DVec3::Z, DVec3::new(0.0, 70.0, -80.0)); } /// The system's picture holds the drone as a contact whose class is already estimated — as if /// the network had passed enough measurements (#133). The sim's own radar then keeps the /// estimate up from its measurements alone. fn seed_classified(sim: &mut Sim, class: ClassEst) { let now = sim.tick; let d = sim.drones[0].clone(); sim.sams[0].tracks.retain(|t| t.id != d.id); let source = sim.sams[0].id; sim.sams[0].tracks.push(Track { id: d.id, class, pos: d.pos, vel: d.vel, tick: now, own_tick: now, source, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false }); } #[test] fn last_chance_leaves_a_drone_for_a_ready_short_range_battery() { let (mut sim, _, _, _) = setup(SamKind::S500); sim.tick = 100; shahed_at(&mut sim, 45.0); seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); let id = sim.id(); let mut gun = Sam::new(id, SamKind::Gepard, DVec3::new(5.0, 70.0, 0.0), 0.0); gun.tracks.push(Track { source: id, ..sim.sams[0].tracks[0] }); sim.sams.push(gun); let chance = |s: &Sim| s.last_chance_for(&s.sams[0], ClassEst::Firm(Class::Drone), &s.drones[0], 0); assert!(!chance(&sim)); sim.sams[1].bursts = 0; assert!(chance(&sim), "an empty gun may not block the fallback shot"); sim.sams[1].bursts = 20; sim.sams[1].pos.x = 500.0; assert!(chance(&sim), "a gun outside engagement range may not block the fallback shot"); } #[test] fn an_empty_s400_stays_empty_until_external_stock_pays_for_a_reload() { let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); sim.sams[0].missiles = 0; for _ in 0..900 { serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); } assert_eq!((sim.sams[0].missiles, sim.sams[0].reloading), (0, 0)); assert!(sim.sams[0].empty); let id = sim.id(); let mut depot = Sam::new(id, SamKind::Depot, DVec3::new(10.0, 70.0, 0.0), 0.0); depot.clear_ammo(); depot.set_ammo(AmmoKind::S400Missile, 1); sim.sams.push(depot); for _ in 0..450 { serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); } assert_eq!((sim.sams[0].missiles, sim.sams[1].ammo_stock.get(AmmoKind::S400Missile), sim.sams[1].cargo), (4, 0, 0)); } #[test] fn last_chance_fires_at_a_class_out_of_roles_only_when_it_is_about_to_hit() { // The S-400 does not engage drones by default. assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0); let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); shahed_at(&mut sim, 60.0); // Classified as a drone by the picture: the roles block it, the last chance is what fires. seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); let at = until_fired(&mut sim, &mut ground, &land, &mut out, 140).expect("the S-400 never fired on a Shahed about to hit"); assert!(at < SPECIALIST_LAST_CHANCE_TICKS, "fired with {at:.0} ticks to go"); // The diagnostic names why: first the role block, then the last chance. let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); shahed_at(&mut sim, 100.0); seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); let mut saw_block = false; let mut saw_chance = false; for _ in 0..220 { serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); let w = sim.why(0); saw_block |= w.iter().any(|c| c.legacy_text().contains("не в ролях")); saw_chance |= w.iter().any(|c| c.legacy_text().starts_with("последний шанс")); if saw_chance || sim.sams[0].fired > 0 { break; } } assert!(saw_block, "the role block was never named"); assert!(saw_chance, "the last chance was never named"); } #[test] fn last_chance_waits_for_a_target_far_from_its_aim() { let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); // In plain view 120 blocks off, but flying away from its aim, 480 blocks (800 ticks) ahead. sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -120.0), DVec3::NEG_Z, DVec3::new(0.0, 70.0, -600.0)); // Classified as a drone: out of the S-400's roles, and not about to hit: nothing fires. seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a Shahed far from its aim"); let w = sim.why(0); // Still named as what it was: a contact on the picture, out of the roles. assert!(w.last().is_some_and(|c| !c.ok) && w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс"))); } #[test] fn specialist_last_chance_protects_reserve_and_rejects_receding_targets() { for kind in [SamKind::S400, SamKind::S500] { let (mut sim, _, _, _) = setup(kind); shahed_at(&mut sim, 45.0); let class = ClassEst::Firm(Class::Drone); assert!(sim.last_chance_for(&sim.sams[0], class, &sim.drones[0], 0)); sim.drones[0].vel = -sim.drones[0].vel; assert!(!sim.last_chance_for(&sim.sams[0], class, &sim.drones[0], 0)); sim.drones[0].vel = -sim.drones[0].vel; sim.sams[0].missiles = sim.sams[0].last_chance_reserve(); assert!(!sim.last_chance_for(&sim.sams[0], class, &sim.drones[0], 0)); } } #[test] fn a_ballistic_track_preempts_the_s400s_held_cruise_target() { let (mut sim, mut ground, _, mut out) = setup(SamKind::S400); sim.tick = 100; sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 100.0, -180.0), DVec3::Z, DVec3::ZERO); seed_classified(&mut sim, ClassEst::Firm(Class::Cruise)); sim.sams[0].target = Some(sim.drones[0].id); sim.add_drone(DroneKind::Kinzhal, DVec3::new(0.0, 100.0, -400.0), DVec3::Z, DVec3::ZERO); let cruise = sim.sams[0].tracks[0]; let ballistic = &sim.drones[1]; let id = ballistic.id; sim.sams[0].tracks.push(Track { id, pos: ballistic.pos, vel: ballistic.vel, class: ClassEst::Firm(Class::Ballistic), ..cruise }); sim.step_sams(&mut ground, &mut out); assert_eq!(sim.sams[0].target, Some(id)); } #[test] fn last_chance_is_off_when_switched_off_and_with_no_roles() { for (off, roles) in [(true, 30u8), (false, 0u8)] { let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); sim.last_chance = !off; sim.sams[0].roles = roles; shahed_at(&mut sim, 60.0); seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 140).is_none(), "fired with last chance off={off}, roles {roles}"); } } #[test] fn last_chance_leaves_a_target_that_already_has_an_interceptor_on_it() { let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); shahed_at(&mut sim, 60.0); seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); // Another system's interceptor is on it. let id = sim.drones[0].id; sim.drones[0].engaged = 1; assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 40).is_none(), "fired at {id} that is claimed"); } #[test] fn a_probable_class_out_of_roles_is_blocked_and_named() { // The S-400 does not engage drones. A track only *probably* a drone is already a block: // the guess is a class, not an unidentified contact. assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0); let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -120.0), DVec3::NEG_Z, DVec3::new(0.0, 70.0, -600.0)); seed_classified(&mut sim, ClassEst::Probable(Class::Drone)); // A target taken before the class was estimated: the diagnostic names the probable class. sim.sams[0].target = Some(sim.drones[0].id); let want = format!("роль: вероятно дрон не в ролях [{}]", roles_text(SamKind::S400.spec().roles)); let w = sim.why(0); assert!(w.iter().any(|c| c.legacy_text() == want), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); assert!(!w.iter().any(|c| c.legacy_text().starts_with("последний шанс"))); // And nothing fires at it while it is far from its aim. assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 150).is_none(), "fired at a probable drone far from its aim"); } #[test] fn hold_fire_blocks_an_unclassified_contact_and_says_so() { // No roles: nothing is a candidate, the unidentified included. Running the sim must not // turn it into a target. let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); sim.sams[0].roles = 0; shahed_at(&mut sim, 60.0); seed_classified(&mut sim, ClassEst::Unknown); assert!(until_fired(&mut sim, &mut ground, &land, &mut out, 200).is_none(), "fired while holding fire"); let w = sim.why(0); assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); } #[test] fn a_held_unknown_target_on_a_system_holding_fire_is_explained_without_a_panic() { // The target was taken before the roles were emptied: the diagnostic must name the hold, // not unwrap a class the estimate does not have. let (mut sim, _, _, _) = setup(SamKind::S400); shahed_at(&mut sim, 60.0); seed_classified(&mut sim, ClassEst::Unknown); sim.sams[0].target = Some(sim.drones[0].id); sim.sams[0].roles = 0; let w = sim.why(0); assert!(w.last().is_some_and(|c| !c.ok), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); assert!(w.iter().any(|c| c.legacy_text().contains("не ведёт огонь")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); } #[test] fn specialists_require_confirmed_class_but_explicit_drone_roles_restore_normal_fire() { for kind in [SamKind::S400, SamKind::S500] { assert_eq!(kind.spec().roles & (Class::Drone.bit() | Class::Jet.bit()), 0); } let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); sim.last_chance = false; shahed_at(&mut sim, 60.0); let id = sim.drones[0].id; let roles = sim.sams[0].roles; let mut saw_open = false; for _ in 0..300 { serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); let Some(t) = sim.sams[0].track(id).copied() else { continue }; if t.class != ClassEst::Unknown { break; } saw_open = true; assert_eq!(why::target_blocks(roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "an unidentified contact must not be role-blocked"); assert_eq!(why::firing_blocks(&sim.sams[0], Some(&t), sim.tick, &sim.drones[0]), why::CLASS_PENDING); let w = sim.why(0); assert!(w.iter().any(|c| c.legacy_text().contains("ждёт подтверждения класса")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); sim.sams[0].roles |= Class::Drone.bit(); assert_eq!(why::firing_blocks(&sim.sams[0], Some(&t), sim.tick, &sim.drones[0]), 0); let w = sim.why(0); assert!(w.iter().any(|c| c.legacy_text().contains("по общим правилам"))); break; } assert!(saw_open, "the contact was never seen unidentified"); // Classified as a drone, out of the roles: blocked, and the diagnostic says so. let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); sim.last_chance = false; shahed_at(&mut sim, 60.0); seed_classified(&mut sim, ClassEst::Firm(Class::Drone)); let id = sim.drones[0].id; for _ in 0..40 { serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); if sim.sams[0].track(id).is_some_and(|t| t.class == ClassEst::Firm(Class::Drone)) { break; } } let t = *sim.sams[0].track(id).expect("the track"); assert_ne!(why::target_blocks(sim.sams[0].roles, Some(&t), sim.tick, &sim.drones[0]) & why::ROLE, 0, "a classified out-of-role contact must be blocked"); let w = sim.why(0); assert!(w.iter().any(|c| c.legacy_text().contains("не в ролях")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); sim.sams[0].roles |= Class::Drone.bit(); assert_eq!(why::firing_blocks(&sim.sams[0], Some(&t), sim.tick, &sim.drones[0]), 0, "the explicit drone role enables an ordinary shot"); // Holding fire (no roles at all): nothing is a candidate, the unidentified either. let d = sim.drones[0].clone(); let unknown = Track { id: d.id, class: ClassEst::Unknown, pos: d.pos, vel: DVec3::ZERO, tick: 0, own_tick: 0, source: 0, product: battery::Measure::Search, quality: 40, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 1, locked: false }; assert_ne!(why::target_blocks(0, Some(&unknown), 0, &d) & why::ROLE, 0, "with no roles (hold fire) even the unknown is blocked"); } /// A Kh101 `dist` from the origin on the far side, at height, coming in along z; a radar beside the system. fn far_setup(radar: bool, dist: f64) -> (Sim, Ground, Land i32>, Out) { let (mut sim, ground, land, out) = setup(SamKind::S400); if radar { let id = sim.id(); sim.sams.push(Sam::new(id, SamKind::Radar, DVec3::new(40.0, 70.0, 0.0), 0.0)); } sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, -dist), DVec3::Z, DVec3::new(0.0, 70.0, 0.0)); (sim, ground, land, out) } /// The radar's measurement of every live drone, fresh this tick (as if its beam had just passed). fn radar_sees(sim: &mut Sim) { let now = sim.tick; let tracks: Vec = sim .drones .iter() .filter(|d| d.alive()) .map(|d| Track { id: d.id, class: ClassEst::Firm(d.kind.spec().class), pos: d.pos, vel: d.vel, tick: now, own_tick: now, source: 0, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false, }) .collect(); for r in sim.sams.iter_mut().filter(|s| s.kind == SamKind::Radar) { for t in &tracks { r.tracks.retain(|o| o.id != t.id); r.tracks.push(Track { source: r.id, ..*t }); } } } fn fire_far(sim: &mut Sim, ground: &mut Ground, land: &Land i32>, out: &mut Out, ticks: u32) -> u32 { for _ in 0..ticks { radar_sees(sim); serve(ground, land, sim.tick); sim.step(ground, None, out); } sim.sams[0].fired } #[test] fn heavy_systems_shoot_far_on_a_radars_cue_but_not_without_one() { let max = SamKind::S400.spec().missile.as_ref().unwrap().max; let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4); assert!(fire_far(&mut sim, &mut ground, &land, &mut out, 80) >= 1, "no long shot at 1.4 x max with a radar"); let w = sim.why(0); assert!(w.iter().any(|c| c.legacy_text().starts_with("дальний пуск по РЛС")), "{:?}", w.iter().map(|c| c.legacy_text()).collect::>()); // No radar, no shot (the system's own radar may well see it: that is not a cue). let (mut sim, mut ground, land, mut out) = far_setup(false, max * 1.4); assert_eq!(fire_far(&mut sim, &mut ground, &land, &mut out, 80), 0, "a long shot with no radar"); // And a kind that is not a heavy one never does. let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4); sim.far_shots = false; assert_eq!(fire_far(&mut sim, &mut ground, &land, &mut out, 80), 0, "a long shot with them switched off"); } #[test] fn a_long_shot_waits_out_its_cooldown_and_for_nothing_closer() { let max = SamKind::S400.spec().missile.as_ref().unwrap().max; // Two far targets: one long shot, the second waits its 300 ticks. let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4); sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, max * 1.4), DVec3::NEG_Z, DVec3::new(0.0, 70.0, 0.0)); assert_eq!(fire_far(&mut sim, &mut ground, &land, &mut out, 70), 1, "not exactly one long shot in the cooldown"); // A closer target in normal reach: the far one is not fired at while it stands. let (mut sim, mut ground, land, mut out) = far_setup(true, max * 1.4); let far = sim.drones[0].id; sim.add_drone(DroneKind::Kh101, DVec3::new(300.0, 120.0, 0.0), DVec3::NEG_X, DVec3::new(0.0, 70.0, 0.0)); // The launcher must finish opening its TPK after the initial readiness cooldown. for _ in 0..40 + launch::OPEN_TICKS { radar_sees(&mut sim); serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); assert!(!sim.missiles.iter().any(|m| m.target == far), "a long shot while a closer target was in reach"); } assert!(sim.sams[0].fired > 0, "the closer target was not fired at"); } #[test] fn cold_launch_opens_before_spending_and_lights_only_after_ejection() { let (mut sim, mut ground, land, mut out) = setup(SamKind::S400); sim.last_chance = false; sim.sams[0].cooldown = 0; sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 160.0, -300.0), DVec3::Z, DVec3::ZERO); let initial = sim.sams[0].missiles; for _ in 0..200 { serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); if sim.sams[0].preparing.is_some() { break; } } assert!(sim.sams[0].preparing.is_some(), "a real tracked target must open a TPK"); assert_eq!(sim.sams[0].missiles, initial); assert!(sim.missiles.is_empty()); // Loss during opening cancels without creating or consuming a missile. sim.sams[0].health = 0.0; sim.step(&mut ground, None, &mut out); assert!(sim.sams[0].preparing.is_none() && sim.missiles.is_empty()); assert_eq!(sim.sams[0].missiles, initial); sim.sams[0].health = 1.0; sim.sams[0].cooldown = 0; for _ in 0..200 { out = Out::default(); serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); if !sim.missiles.is_empty() { break; } } let m = sim.missiles.first().expect("ejection after reopening"); let (id, kind) = (m.id, m.kind); assert_eq!(sim.sams[0].missiles, initial - 1); assert_eq!(sim.sams[0].spent_cells.count_ones(), 1); assert!(!m.engine_lit()); assert!(!out.engines.iter().any(|e| e.key == 0x4000_0000 | id)); let mut last_speed = m.vel.length(); for _ in 0..kind.lit_after() + 3 { out = Out::default(); serve(&mut ground, &land, sim.tick); sim.step(&mut ground, None, &mut out); let m = sim.missiles.iter().find(|m| m.id == id).expect("cold launch remains in flight"); let voice = out.engines.iter().any(|e| e.key == 0x4000_0000 | id); assert_eq!(voice, m.engine_lit()); if m.engine_lit() { assert!(m.vel.length() > last_speed, "the lit motor must accelerate"); } last_speed = m.vel.length(); } } #[test] fn the_kill_chance_falls_to_half_at_the_far_end() { assert_eq!(reach_fit(100.0, 80.0), 1.0); assert_eq!(reach_fit(100.0, 100.0), 1.0); assert!((reach_fit(100.0, 130.0) - 0.75).abs() < 1e-9); assert!((reach_fit(100.0, 160.0) - 0.5).abs() < 1e-9); assert!((reach_fit(100.0, 400.0) - 0.5).abs() < 1e-9); } /// A track as the battery's picture holds it, from `source`, measured by the battery's own /// radar `own` ticks ago. fn seeded_track(id: u32, source: u32, own_tick: u64, product: battery::Measure, now: u64) -> Track { Track { id, class: ClassEst::Firm(Class::Drone), pos: DVec3::new(0.0, 75.0, -100.0), vel: DVec3::Z, tick: now, own_tick, source, product, quality: 90, own_product: product, own_quality: if own_tick > 0 { 90 } else { 0 }, ttl: 400, hits: 3, locked: false, } } #[test] fn the_headline_reason_names_observation_waiting_channels_and_ammo() { // Есть только обзор: the contact is on the network's picture, the battery's own radar // has no fire plot, and no channel of its own is taken. let mut sim = Sim::new(7); let id = sim.id(); sim.sams.push(Sam::new(id, SamKind::Pantsir, DVec3::new(0.0, 70.0, 0.0), 0.0)); let radar = sim.id(); sim.sams.push(Sam::new(radar, SamKind::Radar, DVec3::new(50.0, 70.0, 0.0), 0.0)); sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -100.0), DVec3::Z, DVec3::new(0.0, 70.0, -100.0)); let target = sim.drones[0].id; let now = sim.tick; sim.sams[0].tracks.push(seeded_track(target, radar, 0, battery::Measure::Search, now)); let reason = sim.battle_reason(0).expect("a reason"); assert_eq!(reason.kind, BattleKind::ObserveOnly, "{reason:?}"); let mark = reason.mark.expect("the mark"); assert_eq!(mark.source, Some(1)); assert!(!mark.own); assert_eq!(mark.age, 0); // Ждёт сопровождения: a launcher without its own radar waits for the supporting radar's // fire plot; the same network mark is not enough. let mut sim = Sim::new(8); let id = sim.id(); let mut launcher = Sam::new(id, SamKind::S400, DVec3::new(0.0, 70.0, 0.0), 0.0); launcher.set_mode(battery::SamMode::LauncherOnly); sim.sams.push(launcher); let radar = sim.id(); let mut station = Sam::new(radar, SamKind::Radar, DVec3::new(10.0, 70.0, 0.0), 0.0); station.set_radar_role(battery::RadarRole::Engagement); sim.sams.push(station); sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, -300.0), DVec3::Z, DVec3::new(0.0, 70.0, 0.0)); let target = sim.drones[0].id; let now = 1; sim.sams[0].tracks.push(Track { class: ClassEst::Firm(Class::Cruise), ..seeded_track(target, radar, 0, battery::Measure::Search, now) }); assert_eq!(sim.battle_reason(0).expect("a reason").kind, BattleKind::AwaitingTrack); // Каналы заняты: the supporting radar has the contact but both tracked-contact channels // are held by other contacts. sim.sams[1].tracks.push(seeded_track(901, radar, now, battery::Measure::Fire, now)); sim.sams[1].tracks.push(seeded_track(902, radar, now, battery::Measure::Fire, now)); sim.sams[1].tracks.push(seeded_track(target, radar, now, battery::Measure::Search, now)); let reason = sim.battle_reason(0).expect("a reason"); assert_eq!(reason.kind, BattleKind::ChannelsBusy, "{reason:?}"); assert_eq!(reason.channels, Some((2, 2))); // Нет боезапаса: no rounds and no shells. let mut sim = Sim::new(9); let id = sim.id(); let mut sam = Sam::new(id, SamKind::Pantsir, DVec3::new(0.0, 70.0, 0.0), 0.0); sam.missiles = 0; sam.bursts = 0; sim.sams.push(sam); sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 75.0, -100.0), DVec3::Z, DVec3::new(0.0, 70.0, -100.0)); let target = sim.drones[0].id; let now = sim.tick; sim.sams[0].tracks.push(seeded_track(target, id, now, battery::Measure::Fire, now)); let reason = sim.battle_reason(0).expect("a reason"); assert_eq!(reason.kind, BattleKind::NoAmmo, "{reason:?}"); assert_eq!((reason.rounds, reason.bursts), (0, 0)); } #[test] fn the_headline_reason_can_say_ready_and_defers_to_the_launch_decision() { let mut sim = Sim::new(11); let id = sim.id(); sim.sams.push(Sam::new(id, SamKind::S400, DVec3::new(0.0, 70.0, 0.0), 0.0)); sim.sams[0].cooldown = 0; sim.add_drone(DroneKind::Kh101, DVec3::new(0.0, 300.0, -300.0), DVec3::Z, DVec3::new(0.0, 70.0, 0.0)); let d = sim.drones[0].clone(); let now = 1; sim.sams[0].yaw = heading_of(d.pos - sim.sams[0].pos); sim.sams[0].tracks.push(Track { id: d.id, class: ClassEst::Firm(Class::Cruise), pos: d.pos, vel: d.vel, tick: now, own_tick: now, source: id, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Fire, own_quality: 90, ttl: 400, hits: 3, locked: false, }); let reason = sim.battle_reason(0).expect("a reason"); assert_eq!(reason.kind, BattleKind::Ready, "{reason:?}"); // The detailed decision is the authority when the two are settled together. let mut blocked = reason; blocked.settle(false); assert_eq!(blocked.kind, BattleKind::Blocked); let mut ready = reason; ready.settle(true); assert_eq!(ready.kind, BattleKind::Ready); // In the diagnostic the typed line is the headline, second only to the state. let checks = sim.why(0); assert!(matches!(checks.get(1).map(|c| &c.reason), Some(CheckReason::Battle(r)) if r.kind == BattleKind::Ready), "{checks:?}"); } #[test] fn every_interceptor_lives_long_enough_to_fly_its_reach() { // Life × top speed must cover the far end of a heavy system's reach with room to chase; the rest their plain reach. for kind in SamKind::ARMED { let Some(load) = kind.spec().missile.as_ref() else { continue }; let m = load.kind.spec(); let reach = load.max * if kind.far_shooter() { FAR_K } else { 1.0 }; assert!(m.life as f64 * m.speed > reach * 1.2, "{}: {} x {} does not cover {reach}", kind.name(), m.life, m.speed); } } }