diff --git a/airdef-mod/src/lib.rs b/airdef-mod/src/lib.rs index 0c8f9d6..bc55ce8 100644 --- a/airdef-mod/src/lib.rs +++ b/airdef-mod/src/lib.rs @@ -3301,7 +3301,7 @@ impl Mod for AirDef { say(&format!("{}: {}", kind.name(), if names.is_empty() { "ничего".into() } else { names.join(", ") })); } say(&format!( - "Последний шанс: {} (комплекс стреляет и по классу вне ролей, если цель вот-вот попадёт; /airdef lastchance on|off)", + "Последний шанс: {} (может разрешить пуск по цели вне ролей перед попаданием; /airdef lastchance on|off)", if self.sim.last_chance { "вкл" } else { "выкл" } )); Some("Классы: drone, jet, cruise, supersonic, ballistic (или all). /airdef roles <комплекс|all> <классы|default>".into()) @@ -3334,7 +3334,7 @@ impl Mod for AirDef { self.sim.last_chance = *v == "on"; self.dirty = true; Some(if self.sim.last_chance { - "Последний шанс: вкл — комплекс стреляет и по классу вне ролей, если цель вот-вот попадёт".into() + "Последний шанс: вкл. Со штатными ролями С-400 и С-500 ждут подтверждённый тип и угрозу попадания менее чем через 4 с. Если цель прикрывает ближний комплекс или остался только резерв, пуска не будет.".into() } else { "Последний шанс: выкл — комплексы стреляют только по своим ролям".into() }) diff --git a/airdef-mod/src/sim/battery.rs b/airdef-mod/src/sim/battery.rs index 684730c..6d4a40d 100644 --- a/airdef-mod/src/sim/battery.rs +++ b/airdef-mod/src/sim/battery.rs @@ -234,6 +234,7 @@ impl Sam { if self.radar_role != role { self.radar_role = role; self.tracks.clear(); + self.class_plots.clear(); self.seen.clear(); self.own.clear(); } @@ -245,6 +246,7 @@ impl Sam { if self.mode != mode { self.mode = mode; self.tracks.clear(); + self.class_plots.clear(); self.seen.clear(); self.own.clear(); self.target = None; diff --git a/airdef-mod/src/sim/breakthrough.rs b/airdef-mod/src/sim/breakthrough.rs index 91d51eb..c4341bd 100644 --- a/airdef-mod/src/sim/breakthrough.rs +++ b/airdef-mod/src/sim/breakthrough.rs @@ -218,6 +218,7 @@ fn reason_text(reason: &why::BattleReason) -> &'static str { Some(B::NoWeapon) => "нет оружия", Some(B::NoTarget) => "нет цели", Some(B::NoTrack) => "нет трассы", + Some(B::ClassPending) => "ждёт подтверждения класса цели", Some(B::OutOfRoles) => "вне ролей", Some(B::OutOfReach) => "вне дальности", Some(B::Claimed) => "занята перехватчиками", diff --git a/airdef-mod/src/sim/damage.rs b/airdef-mod/src/sim/damage.rs index 2747ab3..07bfd7d 100644 --- a/airdef-mod/src/sim/damage.rs +++ b/airdef-mod/src/sim/damage.rs @@ -290,6 +290,7 @@ impl Sim { sam.gun_target = None; sam.reloading = 0; sam.tracks.clear(); + sam.class_plots.clear(); sam.seen.clear(); sam.own.clear(); let spec = sam.kind.spec(); diff --git a/airdef-mod/src/sim/memory.rs b/airdef-mod/src/sim/memory.rs index 4373ed3..95392ad 100644 --- a/airdef-mod/src/sim/memory.rs +++ b/airdef-mod/src/sim/memory.rs @@ -152,7 +152,9 @@ impl Sim { + vec_bytes(&self.later) + vec_bytes(&self.flares) + vec_bytes(&self.lit); - r.tracks = self.sams.iter().map(|s| vec_bytes(&s.tracks)).sum::() + r.tracks = self.sams.iter().map(|s| { + vec_bytes(&s.tracks) + map_bytes(s.class_plots.capacity(), std::mem::size_of::<(u32, sight::ClassPlot)>()) + }).sum::() + map_bytes(self.horizons.len(), std::mem::size_of::() + std::mem::size_of::()) + self.horizons.values().map(|h| vec_bytes(&h.rays) + h.rays.iter().map(|ray| vec_bytes(ray)).sum::()).sum::(); r.recording = self.rec.as_ref().map_or(0, |rec| rec.bytes()); diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 65636f0..945e7c1 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -1242,6 +1242,7 @@ pub struct Sam { /// Where its radar beam points (radians), and the tracks it holds: its own radar's and the network's. pub(super) beam: f64, pub tracks: Vec, + class_plots: HashMap, /// The ids of the tracks it holds this tick: its own radar's and the network's. pub seen: Vec, /// The drones its own radar (or optics) holds: guns need these. @@ -1327,6 +1328,7 @@ impl Sam { jam: 0, beam: id as f64 * 2.4, tracks: Vec::new(), + class_plots: HashMap::new(), seen: Vec::new(), own: Vec::new(), kill_view: None, @@ -2511,24 +2513,37 @@ impl Sim { // and not taken again for a while: another system gets it. let shy = |id: u32| me.shy.is_some_and(|(s, until)| s == id && until > now); let stuck = me.held > why::HOLD_MAX; - let keep = had_target.filter(|t| !stuck && tracks.iter().any(|tr| { - tr.id == *t && basis(tr, 1.1, false).is_some_and(|b| b != why::Basis::LastChance) - })); - keep.or_else(|| { - let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(tr, d)); - // Long shots only while nothing of the system's roles is in its normal reach. - let role_in_reach = !radars.is_empty() && tracks.iter().any(|tr| free(tr) && basis(tr, 1.0, true) == Some(why::Basis::Role)); - tracks - .iter() - .filter(|tr| free(tr) && !shy(tr.id)) - .filter_map(|tr| { - let b = basis(tr, if had_target == Some(tr.id) { 1.1 } else { 1.0 }, role_in_reach)?; - let d = drone(tr)?; - Some((b != why::Basis::LastChance, d.threat_at(pos, tr.est(now)), d.id)) - }) - .max_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))) - .map(|(_, _, id)| id) - }) + let free = |tr: &Track| drone(tr).is_some_and(|d| claimed(d) < needed(tr, d)); + // Long shots only while nothing of the system's roles is in its normal reach. + let role_in_reach = !radars.is_empty() && tracks.iter().any(|tr| free(tr) && basis(tr, 1.0, true) == Some(why::Basis::Role)); + let keep = had_target.filter(|_| !stuck).and_then(|id| { + let tr = tracks.iter().find(|tr| tr.id == id)?; + let b = basis(tr, 1.1, role_in_reach)?; + (b != why::Basis::LastChance).then_some((me.shot_priority(tr.class, b), id)) + }); + if let Some((_, id)) = keep + && !me.specializes_in_missiles() + { + return Some(id); + } + tracks + .iter() + .filter(|tr| free(tr) && !shy(tr.id)) + .filter_map(|tr| { + if keep.is_some_and(|(held, _)| me.shot_priority(tr.class, why::Basis::Role) <= held) { + return None; + } + let b = basis(tr, if had_target == Some(tr.id) { 1.1 } else { 1.0 }, role_in_reach)?; + let priority = me.shot_priority(tr.class, b); + if keep.is_some_and(|(held, _)| priority <= held) { + return None; + } + let d = drone(tr)?; + Some((priority, d.threat_at(pos, tr.est(now)), d.id)) + }) + .max_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))) + .map(|(_, _, id)| id) + .or(keep.map(|(_, id)| id)) }); // Guns: the nearest, spread over the targets the other guns and missiles aren't on. let gun_target = spec.gun.as_ref().map(|gun| { diff --git a/airdef-mod/src/sim/regress.rs b/airdef-mod/src/sim/regress.rs index 8d8678a..9c6e77d 100644 --- a/airdef-mod/src/sim/regress.rs +++ b/airdef-mod/src/sim/regress.rs @@ -440,7 +440,7 @@ fn smart_order_routes_every_kind_on_the_snapshot_it_was_ordered_with() { let extra = sim.id(); let extra_at = DVec3::new(0.0, 70.0, 150.0); if extra_at_order { - sim.intel.note(extra, SamKind::S400, extra_at, true, sim.tick, ew::Seen::Emission); + sim.intel.note(extra, SamKind::Patriot, extra_at, true, sim.tick, ew::Seen::Emission); } let mut ground = Ground::default(); let land = Land(|_, _| 64); @@ -467,7 +467,7 @@ fn smart_order_routes_every_kind_on_the_snapshot_it_was_ordered_with() { starved += 1; continue; } - sim.intel.note(extra, SamKind::S400, extra_at, true, sim.tick, ew::Seen::Emission); + sim.intel.note(extra, SamKind::Patriot, extra_at, true, sim.tick, ew::Seen::Emission); added = true; } serve(&mut ground, &land, sim.tick); @@ -481,7 +481,7 @@ fn smart_order_routes_every_kind_on_the_snapshot_it_was_ordered_with() { } sim.queue.iter().map(|(_, d)| (d.kind, d.target, d.route.clone())).collect() } - // The S400 engages jet drones, not propeller ones: Geran3 is the kind its report moves. + // Patriot's stock roles include jet drones: Geran3 is the kind its report moves. let waited = fly(false, true); assert_eq!(waited, fly(false, false), "a contact disclosed while the plan waited for the land changed its routes"); assert_ne!(waited, fly(true, false), "the test does not distinguish the order's picture from a later one"); @@ -498,17 +498,17 @@ fn retarget_jobs_of_one_version_age_at_their_own_tick() { let aim = DVec3::new(1000.0, 70.0, 0.0); let threat = sim.id(); let threat_at = DVec3::new(0.0, 70.0, 0.0); - sim.sams.push(Sam::new(threat, SamKind::S400, threat_at, 0.0)); + sim.sams.push(Sam::new(threat, SamKind::Patriot, threat_at, 0.0)); let target = sim.id(); - sim.sams.push(Sam::new(target, SamKind::S400, aim, 0.0)); + sim.sams.push(Sam::new(target, SamKind::Patriot, aim, 0.0)); // The version sits one tick inside the emission belief's TTL: at the version the threat is // believed to see on its own radar; one tick later the current picture would not believe it. let version = ew::CONTACT_TTL - 1; - let contact = |id: u32, at: DVec3, tick: u64| ew::Contact { id, kind: SamKind::S400, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 }; + let contact = |id: u32, at: DVec3, tick: u64| ew::Contact { id, kind: SamKind::Patriot, at, tick, seen: ew::Seen::Emission, emission: Some(tick), destroyed: None, launches: 0 }; let known = std::sync::Arc::new(ew::KnowledgeSnapshot { tick: version, contacts: vec![contact(threat, threat_at, 0), contact(target, aim, version)], marks: Vec::new() }); - sim.intel.note(target, SamKind::S400, aim, true, version, ew::Seen::Emission); + sim.intel.note(target, SamKind::Patriot, aim, true, version, ew::Seen::Emission); fn add(sim: &mut Sim, version: u64, known: std::sync::Arc, target: u32, start: DVec3, aim: DVec3, flat: &std::sync::Arc) -> u32 { - // A jet drone: the S400's published roles engage it, so the belief in its radar prices it. + // A jet drone: Patriot's published roles engage it, so the belief in its radar prices it. let mut d = sim.make_drone(DroneKind::Geran3, start, DVec3::X, aim); d.smart = true; d.err = DVec3::ZERO; @@ -534,7 +534,7 @@ fn retarget_jobs_of_one_version_age_at_their_own_tick() { let r2 = retarget_route(&sim, second); assert_eq!(r1, r2, "a job of the same version aged its contacts with the current tick"); // An explicitly new retarget: a fresh report of the threat at the new version is priced again. - sim.intel.note(threat, SamKind::S400, threat_at, true, version + 1, ew::Seen::Emission); + sim.intel.note(threat, SamKind::Patriot, threat_at, true, version + 1, ew::Seen::Emission); let fresh = std::sync::Arc::new(ew::KnowledgeSnapshot { tick: version + 1, contacts: vec![contact(threat, threat_at, version + 1), contact(target, aim, version)], marks: Vec::new() }); let third = add(&mut sim, version + 1, fresh, target, start, aim, &flat); sim.adapt(); diff --git a/airdef-mod/src/sim/sight.rs b/airdef-mod/src/sim/sight.rs index 2265dce..6e14ff1 100644 --- a/airdef-mod/src/sim/sight.rs +++ b/airdef-mod/src/sim/sight.rs @@ -418,7 +418,8 @@ fn merge(tracks: &mut Vec, index: &mut HashMap, t: Track) { (mine.own_tick, mine.own_product, mine.own_quality, mine.locked) }; let hits = mine.hits.max(t.hits); - *mine = Track { own_tick, own_product, own_quality, hits, locked, ..t }; + let class = if t.class == ClassEst::Unknown { mine.class } else { t.class }; + *mine = Track { own_tick, own_product, own_quality, hits, locked, class, ..t }; } } None => { @@ -428,6 +429,26 @@ fn merge(tracks: &mut Vec, index: &mut HashMap, t: Track) { } } +/// One local measurement used as a baseline for classifying speed. Fusing +/// positions from different sensors a tick apart can turn noise into speed. +#[derive(Clone, Copy)] +pub(super) struct ClassPlot { + pos: DVec3, + tick: u64, + sigma: f64, + networked: bool, +} + +impl ClassPlot { + fn classify(self, next: Self, previous: ClassEst) -> Option { + let elapsed = (next.tick - self.tick) as f64; + // Let the contact move a measurable distance before using another plot. + // Even a radar locked every tick has too much noise over one tick. + let min_ticks = (2.5 * (self.sigma + next.sigma)).max(6.0); + (elapsed >= min_ticks).then(|| previous.step(3, self.pos.distance(next.pos) / elapsed)) + } +} + /// A plot's quality (0..100). It uses only the measured geometry and the /// station's own fit, never the target's hidden state. fn plot_quality(sam: &Sam, profile: battery::RadarProfile, product: battery::Measure, ratio: f64, height: f64) -> u8 { @@ -480,9 +501,16 @@ impl Sim { let mut index: HashMap = HashMap::new(); for sam in &mut self.sams { // A track of a drone that is gone is dropped (the kill is seen), so is one not renewed for its time. - sam.tracks.retain(|t| now - t.tick <= t.ttl as u64 && drone_at.get(&t.id).is_some_and(|&k| self.drones[k].alive())); + sam.tracks.retain(|t| { + let keep = now - t.tick <= t.ttl as u64 && drone_at.get(&t.id).is_some_and(|&k| self.drones[k].alive()); + if !keep { + sam.class_plots.remove(&t.id); + } + keep + }); if !sam.alive() || sam.moving() { sam.tracks.clear(); + sam.class_plots.clear(); continue; } if !sam.radar_up() { @@ -577,17 +605,26 @@ impl Sim { used += 1; } let hits = held.map_or(1, |t| t.hits.saturating_add(1)); - // What this measurement says of the contact's class and speed, from the measured - // places alone: the first blip gives neither; a later one, the change of place over - // the ticks since the last real measurement (not a forecast's), smoothed into what - // the track held so the class does not flap on one noisy pair (#133). - let (vel, class) = match held { + let vel = match held { Some(p) if p.tick < now => { let seen = (measured - p.pos) / (now - p.tick) as f64; - let vel = if p.hits <= 1 { seen } else { p.vel + (seen - p.vel) / f64::from(p.hits.min(4)) }; - (vel, p.class.step(hits, vel.length())) + if p.hits <= 1 { seen } else { p.vel + (seen - p.vel) / f64::from(p.hits.min(4)) } } - _ => (DVec3::ZERO, ClassEst::Unknown), + _ => DVec3::ZERO, + }; + let plot = ClassPlot { pos: measured, tick: now, sigma, networked: false }; + let previous_class = held.map_or(ClassEst::Unknown, |t| t.class); + let baseline = sam.class_plots.entry(d.id).or_insert(plot); + baseline.networked |= held.is_some_and(|p| p.source != sam.id); + let class = if !baseline.networked { + // A station measuring independently retains the velocity + // estimate from its own successive observations. + previous_class.step(hits, vel.length()) + } else if let Some(estimate) = baseline.classify(plot, previous_class) { + *baseline = ClassPlot { networked: true, ..plot }; + estimate + } else { + previous_class }; fresh.push(Track { id: d.id, @@ -814,6 +851,17 @@ mod low_view_tests { mod relay_tests { use super::*; + #[test] + fn class_samples_ignore_noise_between_nearby_ticks() { + let sample = |tick, error| ClassPlot { pos: DVec3::X * (tick as f64 * 0.6 + error), tick, sigma: 8.0, networked: true }; + let baseline = sample(10, -8.0); + assert_eq!(baseline.classify(sample(11, 8.0), ClassEst::Unknown), None); + let next = sample(50, 8.0); + let probable = baseline.classify(next, ClassEst::Unknown).unwrap(); + assert_eq!(probable, ClassEst::Probable(Class::Drone)); + assert_eq!(next.classify(sample(90, -8.0), probable), Some(ClassEst::Firm(Class::Drone))); + } + /// A relayed measurement: its class and hits arrive as they were, the receiver's own age is /// kept, and passing the same message again adds nothing (#133). #[test] diff --git a/airdef-mod/src/sim/unit_specs_generated.rs b/airdef-mod/src/sim/unit_specs_generated.rs index 1731876..a531f98 100644 --- a/airdef-mod/src/sim/unit_specs_generated.rs +++ b/airdef-mod/src/sim/unit_specs_generated.rs @@ -116,7 +116,7 @@ const UNIT_SPEC_S400: SamSpec = SamSpec { reload: 420, scale: 1.5, rest_pitch: HALF_PI - 0.02, - roles: 30, + roles: 28, family: Family::Vertical, parts: Parts { body: "airdef:s400_chassis", diff --git a/airdef-mod/src/sim/why.rs b/airdef-mod/src/sim/why.rs index 5e21328..36a2951 100644 --- a/airdef-mod/src/sim/why.rs +++ b/airdef-mod/src/sim/why.rs @@ -13,6 +13,7 @@ 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 @@ -32,6 +33,15 @@ 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; @@ -75,14 +85,26 @@ pub(super) const SHY_TICKS: u64 = 120; // ---------------------------------------------------------------- the grounds to launch on -/// Last chance (`/airdef lastchance`): a track of a *known* class the system does not engage that -/// is about to hit, with nobody's interceptor on it, is shot at anyway; a system told to hold fire -/// (no roles) keeps to it. An unidentified track is no last-chance case: it is already a candidate -/// under the general rules (#133). +/// 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; -pub(super) fn last_chance(on: bool, roles: u8, class: ClassEst, d: &Drone, claimed: u32) -> bool { - on && roles != 0 && !class.in_roles(roles) && claimed == 0 && arrival(d) < LAST_CHANCE_TICKS +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. @@ -137,6 +159,33 @@ pub(super) enum Basis { 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 { @@ -160,7 +209,7 @@ pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Dro } else if !own && !cued { return None; } - let blocks = target_blocks(sam.roles, Some(track), now, d); + let blocks = firing_blocks(sam, Some(track), now, d); if blocks & !ROLE != 0 { return None; } @@ -179,7 +228,7 @@ pub(super) fn basis(sam: &Sam, load: &units::MissileLoad, track: &Track, d: &Dro 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.roles, est, d, claimed)).then_some(Basis::LastChance) + (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`: @@ -328,13 +377,18 @@ impl LaunchAudit { impl Sim { pub(super) fn last_chance_for(&self, sam: &Sam, class: ClassEst, d: &Drone, claimed: u32) -> bool { - last_chance(self.last_chance, sam.roles, class, d, claimed) && !self.has_role_cover(sam, d) + 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, d: &Drone) -> bool { + fn has_role_cover(&self, fallback: &Sam, class: ClassEst, d: &Drone) -> bool { let now = self.tick; - let lead = (arrival(d) - 20.0).clamp(0.0, 40.0); + 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 @@ -343,20 +397,33 @@ impl Sim { return false; } let Some(track) = sam.track(d.id) else { return false }; - if track.class.class().is_none() || !allowed(sam.roles, track, now, d) + 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) - && at.distance(mount).min(soon.distance(mount)) < gun.range + && 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 { @@ -365,11 +432,12 @@ impl Sim { 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, track.class) == 0 - && (in_reach(load.min, load.max, 1.0, sam.pos, at) - || in_reach(load.min, load.max, 1.0, sam.pos, soon)) + && 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 }) }) @@ -406,7 +474,7 @@ impl Sim { a.no_track += 1; continue; }; - let blocks = target_blocks(sam.roles, Some(tr), now, d); + let blocks = firing_blocks(sam, Some(tr), now, d); if blocks & STALE != 0 { a.stale += 1; continue; @@ -421,7 +489,7 @@ impl Sim { 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 & ROLE != 0 && !chance { + if blocks & CLASS_PENDING != 0 || (blocks & ROLE != 0 && !chance) { a.role += 1; continue; } @@ -556,6 +624,7 @@ pub enum BattleBlock { NoWeapon, NoTarget, NoTrack, + ClassPending, OutOfRoles, OutOfReach, Claimed, @@ -685,8 +754,11 @@ impl Sim { return Some(reason(BattleKind::Blocked, Some(BattleBlock::NoTrack), Some(t.id), mark)); }; let est = tr.class; - let blocks = target_blocks(sam.roles, Some(tr), now, t); + 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)); @@ -703,7 +775,7 @@ impl Sim { 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| { - allowed(sam.roles, other, now, o) + 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) @@ -959,13 +1031,15 @@ impl Sim { 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 = target_blocks(sam.roles, track, now, t); + 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 & ROLE == 0 { + 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)), @@ -975,14 +1049,24 @@ impl Sim { "последний шанс: {} не в ролях [{}], но до цели {:.0} с, перехватчиков на ней нет", est.name(), roles_text(sam.roles), - arrival(t) / 20.0 + 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 & ROLE == 0 || chance, role_text)); + 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)); @@ -1068,7 +1152,7 @@ impl Sim { 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| allowed(sam.roles, tr, now, o) && 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)) + 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)); @@ -1291,7 +1375,7 @@ mod tests { // 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 < LAST_CHANCE_TICKS, "fired with {at:.0} ticks to go"); + 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); @@ -1326,6 +1410,37 @@ mod tests { 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)] { @@ -1396,12 +1511,10 @@ mod tests { } #[test] - fn roles_read_the_estimate_an_unidentified_track_is_not_blocked() { - // #133: the role filter reads the track's estimated class, never the target's own. While - // the contact is unidentified the S-400 (its roles exclude drones) keeps it as a candidate - // under the general rules — the explicit policy, named in why; once the estimate firms as - // a drone, the block applies and why names that instead. - assert_eq!(SamKind::S400.spec().roles & Class::Drone.bit(), 0, "the S-400 does not engage drones"); + 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); @@ -1417,8 +1530,13 @@ mod tests { } 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::>()); + 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"); @@ -1439,6 +1557,8 @@ mod tests { 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 }; diff --git a/airdef-mod/src/why_view.rs b/airdef-mod/src/why_view.rs index ddacd54..0b70a12 100644 --- a/airdef-mod/src/why_view.rs +++ b/airdef-mod/src/why_view.rs @@ -82,6 +82,7 @@ pub fn battle_text(reason: &BattleReason) -> String { Some(BattleBlock::NoWeapon) => "нет оружия (РЛС, склад, РЭБ, прожектор)".to_string(), Some(BattleBlock::NoTarget) => "нет целей в небе".to_string(), Some(BattleBlock::NoTrack) => "цель не обнаружена своей РЛС или сетью".to_string(), + Some(BattleBlock::ClassPending) => "ждёт подтверждения класса цели".to_string(), Some(BattleBlock::OutOfRoles) => "цель вне ролей комплекса".to_string(), Some(BattleBlock::OutOfReach) => "цель вне дальности".to_string(), Some(BattleBlock::Claimed) => "цель уже занята перехватчиками".to_string(), diff --git a/airdef-mod/tests/budgets/wasm_flat_budget.toml b/airdef-mod/tests/budgets/wasm_flat_budget.toml index 2857163..6fb3c6d 100644 --- a/airdef-mod/tests/budgets/wasm_flat_budget.toml +++ b/airdef-mod/tests/budgets/wasm_flat_budget.toml @@ -1018,7 +1018,7 @@ frames = 10 command = "airdef stats" # Finite-ammunition checkpoint after extending the game ranges. With no depot, # the two waves exhaust the initial stock. The previous baseline used free reloads. -expect.feedback = "В воздухе: 184, ракет: 0, ПВО: 64, сбито: 135, поражений: 2161, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 4881 секций (228 КБ), запросов 12163, неизвестно 0, лучей 303646 (ударов 1226, неизв. 135), клеток 1944815; взрывы в блоках: 2176 (подтверждено 0, без перемен 88, нет чанка 1946), чужих ответов 0" +expect.feedback = "В воздухе: 184, ракет: 0, ПВО: 64, сбито: 132, поражений: 2199, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 4785 секций (224 КБ), запросов 12079, неизвестно 0, лучей 307306 (ударов 822, неизв. 152), клеток 1960898; взрывы в блоках: 2214 (подтверждено 0, без перемен 83, нет чанка 1989), чужих ответов 0" # The Windows #122 path: a Smart order through the UI launch function (`airdef raid` # is the wave screen's ПУСК button handler) with a fat intel log and EW up — twice. @@ -1068,4 +1068,4 @@ command = "airdef stats" # The two late Smart raids also run with finite stock. At this point the # launchers still have no supply depot. # The late Smart orders use the coarse observation picture from #135. -expect.feedback = "В воздухе: 25, ракет: 0, ПВО: 68, сбито: 142, поражений: 2692, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 7327 секций (343 КБ), запросов 16853, неизвестно 0, лучей 399783 (ударов 2350, неизв. 904), клеток 3864646; взрывы в блоках: 2792 (подтверждено 0, без перемен 155, нет чанка 2637), чужих ответов 0" +expect.feedback = "В воздухе: 25, ракет: 0, ПВО: 68, сбито: 133, поражений: 2730, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 7309 секций (342 КБ), запросов 16741, неизвестно 0, лучей 406150 (ударов 2235, неизв. 1073), клеток 3915183; взрывы в блоках: 2829 (подтверждено 0, без перемен 165, нет чанка 2664), чужих ответов 0" diff --git a/airdef-mod/tests/saturation.rs b/airdef-mod/tests/saturation.rs index f0cb185..ea9ed54 100644 --- a/airdef-mod/tests/saturation.rs +++ b/airdef-mod/tests/saturation.rs @@ -125,11 +125,12 @@ fn run_to(ticks: u64) -> Sim { } /// No depot is deployed in this fixture. Both waves spend the initial ammunition; -/// the checkpoint records the combat outcome with finite magazines and the extended ranges. -const REPLICA_KILLS: u32 = 144; -const REPLICA_HITS: u32 = 2152; +/// the checkpoint records the outcome with finite magazines and the heavy batteries' +/// confirmed-class engagement rules. +const REPLICA_KILLS: u32 = 129; +const REPLICA_HITS: u32 = 2202; const REPLICA_AIRBORNE: usize = 184; -const REPLICA_FIRED: u32 = 355; +const REPLICA_FIRED: u32 = 344; #[test] fn checkpoint_replica_matches_the_finite_ammunition_baseline() { diff --git a/catalog/specs.json b/catalog/specs.json index 7c2ba3c..04ee7e0 100644 --- a/catalog/specs.json +++ b/catalog/specs.json @@ -426,7 +426,7 @@ "reload": 420, "scale": 1.5, "rest_pitch": {"half_pi": -0.02}, - "roles": 30, + "roles": 28, "family": "vertical", "parts": { "body": "airdef:s400_chassis", diff --git a/tools/airdef.py b/tools/airdef.py index 8c43cd2..d47d1ec 100644 --- a/tools/airdef.py +++ b/tools/airdef.py @@ -715,7 +715,7 @@ def test_wasm(): BUDGET_SCENARIO = "tests/budgets/wasm_flat_budget.toml" -BUDGET_ASSERTED_SHA256 = "adc10637892159e450458e33b036ccf210ebbf9b7fb05bb3d428d41df5569a8e" +BUDGET_ASSERTED_SHA256 = "894b9191dcb5ad59449cc0fa8ffbd1ab0567bc7c70144b534a48bfa49ed6b509" def fuel_measurements(output):