//! What a system's radar holds. Small targets come up late (the radar's reach //! goes with the fourth root of their cross-section), low ones later still //! (over the curve of the earth, scaled to the game's distances), and the land //! hides what flies behind hills and woods: each system keeps its horizon, the //! highest the land rises seen from its antenna, ray by ray round it. //! //! A radar does not know where everything is all the time. Its beam sweeps round //! (a period by the kind of radar; an electronic one also revisits what it holds //! more often), a target is measured when the beam passes it, with a chance that //! falls with range and size, and the measurement is kept as a *track*: where it //! was measured, how fast it then seemed to go (from the measured places, never //! the target's own figures), and when. Between measurements the track is //! carried on by that velocity (a forecast, shown as one), and after three missed //! scans it is dropped. A fire-control lock on a target the system is engaging is //! a dedicated channel: it measures every tick while the target is in reach and in //! sight. The track also carries what the measurements say of the contact's class, //! the estimate growing only on real measurements: a forecast, a relayed copy adds //! nothing to it. The network passes tracks with the age of their measurement; //! relaying makes none of them fresher. use super::*; /// Rays round a radar, and blocks between the land's samples along them. const RAYS: usize = 48; const STEP: f64 = 16.0; /// How far units share their tracks (the network's data links). pub(super) const LINK: f64 = 2250.0; /// A launcher fires on a track no older than this (ticks); a gun needs its own radar's, newer than `GUN_AGE`. pub(super) const MISSILE_AGE: u64 = 120; pub(super) const GUN_AGE: u64 = 3; /// A fire plot below this quality is not confirmed enough to authorize a launch. pub const FIRE_QUALITY: u8 = 50; /// A gun takes a target its radar measured this recently (then the lock refreshes it every tick). pub(super) const GUN_PICK_AGE: u64 = 40; /// A track older than this is shown as a forecast. pub const FORECAST_AGE: u64 = 20; /// Radio horizon: `HORIZON * (√mast + √height)` blocks. pub(super) const HORIZON: f64 = 35.0; /// Anything this near is seen (and heard), whatever hides it. pub(super) const NEAR: f64 = 24.0; pub(super) struct Horizon { /// Per ray, per sample out: the steepest rise of the land so far (tan of its elevation). pub(super) rays: Vec>, antenna: DVec3, reach: f64, } impl Horizon { fn build(antenna: DVec3, reach: f64, ground: &mut Ground, now: u64) -> Self { let steps = (reach / STEP).ceil() as usize + 1; let rays = (0..RAYS) .map(|r| { let a = r as f64 / RAYS as f64 * TAU; let dir = DVec3::new(a.sin(), 0.0, a.cos()); let mut top = f32::NEG_INFINITY; (1..=steps) .map(|k| { let d = k as f64 * STEP; // Unknown land (not loaded, not answered yet) hides nothing. if let Some(g) = ground.at(antenna + dir * d, now) { top = top.max(((g - antenna.y) / d) as f32); } top }) .collect() }) .collect(); Self { rays, antenna, reach } } fn matches(&self, sam: &Sam) -> bool { self.antenna == antenna(sam) && self.reach == sensor_span(sam) } /// Whether the land between the antenna and `p` rises over the line to it. pub(super) fn hides(&self, antenna: DVec3, p: DVec3) -> bool { let rel = p - antenna; let flat = (rel.x * rel.x + rel.z * rel.z).sqrt(); let k = (flat / STEP) as usize; if k == 0 { return false; } let a = rel.x.atan2(rel.z).rem_euclid(TAU); let ray = &self.rays[(a / TAU * RAYS as f64).round() as usize % RAYS]; let top = ray[(k - 1).min(ray.len() - 1)]; ((rel.y / flat) as f32) < top } } /// Where a unit's radar antenna is. pub(super) fn antenna(sam: &Sam) -> DVec3 { sam.pos + DVec3::Y * sam.sensor_mast() } fn sensor_span(sam: &Sam) -> f64 { sam.kind.spec().sensor * sam.radar_profile().reach } /// How far a system's search radar reaches for this kind at `height` over the land: /// its own reach (worse when damaged) for the target's size, under the radio horizon. pub(super) fn reach(sam: &Sam, kind: DroneKind, height: f64) -> f64 { let spec = sam.kind.spec(); if spec.sensor <= 0.0 { return 0.0; } let radar = spec.sensor * sam.radar_fit() * sam.radar_profile().reach * kind.rcs().powf(0.25); let horizon = HORIZON * (sam.sensor_mast().sqrt() + height.max(0.0).sqrt()); radar.min(horizon).max(NEAR) } /// The low flyer the command map shows the radars' coverage for: a Shahed over the land. const LOW_KIND: DroneKind = DroneKind::Shahed; /// A radar as the command map sees it: where its antenna is and how far it reaches a low flyer. #[derive(Clone, Copy)] pub struct LowSensor { pub id: u32, pub ant: DVec3, /// The ground under the unit (a place whose land is unknown is taken as level with it). pub base: f64, pub reach: f64, /// Its horizon is known: the land hides what it hides. pub terrain: bool, } /// Rays of `Sim::low_rim`. pub const RIM_RAYS: usize = RAYS; impl Ground { /// The land's height at `p` from what the game has already answered; asks for nothing. pub fn peek(&self, p: DVec3) -> Option { const LAT: i32 = super::terrain::LATTICE; let k = (p.x.floor() as i32, p.z.floor() as i32); let hit = self.known.get(&k).or_else(|| { self.known.get(&(k.0.div_euclid(LAT) * LAT + LAT / 2, k.1.div_euclid(LAT) * LAT + LAT / 2)) }); hit.and_then(|&(y, _)| land_height(y)) } } impl Sim { /// A radar for a unit of `kind` at `pos` as the map draws it; `id`: the unit it is (its parts and horizon), None for a ghost. pub fn low_sensor(&self, kind: SamKind, pos: DVec3, id: Option) -> Option { let spec = kind.spec(); if spec.sensor <= 0.0 || id.and_then(|i| self.sams.iter().find(|s| s.id == i)).is_some_and(|s| s.mode == battery::SamMode::LauncherOnly) { return None; } let fit = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_fit()); let height = LOW_KIND.spec().clearance; let mast = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(spec.mast, |s| s.sensor_mast()); let factor = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).map_or(1.0, |s| s.radar_profile().reach); let radar = spec.sensor * fit * factor * LOW_KIND.rcs().powf(0.25); let reach = radar.min(HORIZON * (mast.sqrt() + height.sqrt())).max(NEAR); let terrain = id.and_then(|i| self.sams.iter().find(|s| s.id == i)).is_some_and(|s| self.horizons.get(&s.id).is_some_and(|h| h.matches(s))); Some(LowSensor { id: id.unwrap_or(u32::MAX), ant: pos + DVec3::Y * mast, base: pos.y, reach, terrain }) } /// The radars that are up now. pub fn low_sensors(&self) -> Vec { self.sams.iter().filter(|s| s.radar_up()).filter_map(|s| self.low_sensor(s.kind, s.pos, Some(s.id))).collect() } /// Whether the radar sees a low flyer (over the land) at the column (`x`, `z`): in its reach and not behind the land. pub fn low_sees(&self, ground: &Ground, s: &LowSensor, x: f64, z: f64) -> bool { let (dx, dz) = (x - s.ant.x, z - s.ant.z); let d2 = dx * dx + dz * dz; if d2 > s.reach * s.reach { return false; } if !s.terrain || d2 <= NEAR * NEAR { return true; } let Some(h) = self.horizons.get(&s.id) else { return true }; let g = ground.peek(DVec3::new(x, 0.0, z)).unwrap_or(s.base); !h.hides(s.ant, DVec3::new(x, g + LOW_KIND.spec().clearance, z)) } /// Per ray round the radar, how far a low flyer is seen before the land first hides it (at most the reach). pub fn low_rim(&self, ground: &Ground, s: &LowSensor) -> Vec { let mut out = vec![s.reach as f32; RAYS]; let Some(h) = self.horizons.get(&s.id).filter(|_| s.terrain) else { return out }; let steps = ((s.reach / STEP) as usize).min(h.rays[0].len()); let height = LOW_KIND.spec().clearance; for (r, o) in out.iter_mut().enumerate() { let a = r as f64 / RAYS as f64 * TAU; let (sx, sz) = (a.sin(), a.cos()); for k in 1..=steps { let d = k as f64 * STEP; if d <= NEAR { continue; } let p = DVec3::new(s.ant.x + sx * d, 0.0, s.ant.z + sz * d); let y = ground.peek(p).unwrap_or(s.base) + height - s.ant.y; if ((y / d) as f32) < h.rays[r][k - 1] { *o = (d - STEP).max(NEAR) as f32; break; } } } out } } /// How a kind's radar looks round. pub(super) struct Scan { /// Ticks for the beam to go round. pub period: u32, /// An electronic radar: what it holds it revisits at once a third of the period, between the beam's passes. pub agile: bool, } impl SamKind { pub(super) fn scan(self) -> Scan { let (period, agile) = match self { SamKind::Patriot => (30, true), SamKind::S400 => (36, true), SamKind::S500 => (24, true), SamKind::IrisT | SamKind::Nasams => (40, true), SamKind::Buk => (50, false), SamKind::Tor | SamKind::Pantsir => (40, false), SamKind::Gepard => (50, false), // The early-warning radar: a big antenna turning slowly. SamKind::Radar => (140, false), _ => (40, false), }; Scan { period, agile } } } /// How well a track says what it is. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Ident { /// One measurement: something is there. Unknown, /// Measured again: a drone or missile by how it flies. Probable, /// Held by a lock or by several measurements. Confirmed, } impl Ident { pub fn name(self) -> &'static str { match self { Ident::Unknown => "неопознана", Ident::Probable => "предположительно воздушная цель", Ident::Confirmed => "подтверждена", } } } /// What a system knows of one target: the last measurement, not the target itself. /// /// The track never carries the target's type or its true velocity (#133): `class` is what the /// radars inferred from the measurements so far, `vel` the speed those measurements showed — /// none from the first blip, then the change of the measured places between real measurements, /// smoothed a little. The forecast and the guns live with that. #[derive(Clone, Copy, Debug)] pub struct Track { pub id: u32, /// What the radars make of it from the measurements (never the target's own type). pub class: ClassEst, /// Where it was measured and how fast it seemed to go then (blocks, blocks a tick). pub pos: DVec3, pub vel: DVec3, /// When that was, and when this system's own radar last measured it (0: never, the network's only). pub tick: u64, pub own_tick: u64, /// The station that measured the latest plot, and what it is good for. pub source: u32, pub product: battery::Measure, /// Measurement quality (0..100), separate from identification (`hits`). pub quality: u8, /// This system's own measurement provenance. A fresher relay may replace /// the published plot without granting or erasing the station's own right. pub own_product: battery::Measure, pub own_quality: u8, /// Ticks the track lives without a new measurement. pub ttl: u32, pub hits: u8, /// The last own measurement came from a fire-control lock. pub locked: bool, } /// What the player's side knows of the air: the network's tracks as last measured, never the drones themselves. pub struct AirPicture { pub now: u64, pub tracks: Vec, /// No system is deployed: the tracks are the sky as it is. pub unaided: bool, } impl AirPicture { pub fn get(&self, id: u32) -> Option<&Track> { self.tracks.iter().find(|t| t.id == id) } /// The track nearest to a point, by its forecast place. pub fn nearest(&self, to: DVec3) -> Option<&Track> { self.tracks.iter().min_by(|a, b| a.est(self.now).distance(to).total_cmp(&b.est(self.now).distance(to))) } } impl Track { pub fn age(&self, now: u64) -> u64 { now.saturating_sub(self.tick) } /// Where the target should be by now, carrying the last measurement on: the forecast, not a measurement. pub fn est(&self, now: u64) -> DVec3 { self.pos + self.vel * self.age(now) as f64 } pub fn forecast(&self, now: u64) -> bool { self.age(now) > FORECAST_AGE } /// Own radar measured it within `age` ticks. pub fn own_within(&self, now: u64, age: u64) -> bool { self.own_tick > 0 && now.saturating_sub(self.own_tick) <= age } /// The station's own measurement was a confirmed fire plot, fresh enough. /// A relayed plot has `own_tick == 0` and never passes this test. pub fn own_fire_within(&self, now: u64, age: u64) -> bool { self.own_within(now, age) && self.own_product.allows_fire() && self.own_quality >= FIRE_QUALITY } /// Own plot good enough for a launcher's ordinary shot. pub fn own_authorizes(&self, now: u64) -> bool { self.own_fire_within(now, MISSILE_AGE) } /// Who measured the latest plot, as an ID (`0`: no station). pub fn measured_by(&self) -> Option { (self.source != 0).then_some(self.source) } /// One passive optical look at this contact (#136): refines the class alone. The plot, its /// age, source, quality and the station's own fire rights are untouched — optics never /// authorize a shot and never make a track fresher. pub fn refine_class_optical(&mut self, class: Class, uncertainty: f64) { self.class = self.class.step_optical(class, uncertainty); } pub fn ident(&self) -> Ident { match self.hits { 0 | 1 => Ident::Unknown, 2 => Ident::Probable, _ => Ident::Confirmed, } } /// How far the forecast may be off, blocks: grows with the age. pub fn uncertainty(&self, now: u64) -> f64 { 1.0 + self.age(now) as f64 * (0.05 + self.vel.length() * 0.1) } } impl Sam { /// Fictional antenna height and scan characteristics for gameplay roles. pub(super) fn sensor_mast(&self) -> f64 { self.kind.spec().mast + self.radar_profile().mast } pub(super) fn scan_profile(&self) -> Scan { if self.kind != SamKind::Radar { return self.kind.scan(); } let profile = self.radar_profile(); Scan { period: profile.cycle, agile: profile.agile } } /// Ticks for its beam to go round (longer when the radar is damaged). pub(super) fn scan_ticks(&self) -> f64 { self.scan_profile().period as f64 / self.radar_fit().max(0.2) } /// Its own radar works: it has one, it is not failed and the unit is deployed. pub fn radar_up(&self) -> bool { self.radar_on && self.mode != battery::SamMode::LauncherOnly && self.alive() && !self.moving() && self.kind.spec().sensor > 0.0 && self.part(Part::Sensor) > 0.0 } /// Its jammer is really on the air: the switch, a live station and a deployed one. The same /// state `step_ew` transmits in, so a look names jamming only while the transmitter works. pub fn ew_up(&self) -> bool { self.ew_on && !self.ew_lock && self.alive() && !self.moving() } pub fn track(&self, id: u32) -> Option<&Track> { self.tracks.iter().find(|t| t.id == id) } /// Refined/fire channels this station is currently using. pub fn own_channels_used(&self) -> usize { self.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count() } } /// Whether a beam that moved from `from` by `w` radians this tick passed `bearing` (all angles taken round 2π, /// so a beam crossing north between two ticks still passes a target there). pub(super) fn swept(bearing: f64, from: f64, w: f64) -> bool { (bearing - from).rem_euclid(TAU) < w } /// A new measurement into a list of tracks (the index maps ids to places): a fresher one replaces an older. fn merge(tracks: &mut Vec, index: &mut HashMap, t: Track) { match index.get(&t.id) { Some(&k) => { let mine = &mut tracks[k]; // Prefer the fresher plot; at the same tick the better one (a fire plot // over a coarse search plot), without making anything newer. if t.tick > mine.tick || (t.tick == mine.tick && t.quality > mine.quality) { // A relayed plot is published with its source/quality, but it // neither refreshes nor erases this station's own measurement and its right. let (own_tick, own_product, own_quality, locked) = if t.own_tick > 0 { (t.own_tick, t.own_product, t.own_quality, t.locked) } else { (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 }; } } None => { index.insert(t.id, tracks.len()); tracks.push(t); } } } /// 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 { let ratio = ratio.clamp(0.0, 1.0); let base = match profile.id { "radar_search" => 46.0 - 14.0 * ratio, "radar_height" => 74.0 - 12.0 * ratio + if height < 120.0 { 8.0 } else if height < 200.0 { 3.0 } else { 0.0 }, "radar_track" => 88.0 - 12.0 * ratio, "radar_multi" => 72.0 - 14.0 * ratio, _ => 78.0 - 14.0 * ratio, }; // A search plot is coarse whatever the profile; only a matched refinement or // a fire plot gets the profile's accuracy. let base = if product == battery::Measure::Search { base.min(48.0) } else { base }; (base * sam.radar_fit()).round().clamp(5.0, 99.0) as u8 } impl Sim { /// Rebuilds the systems' horizons in turn, then lets each radar's beam pass the sky: new measurements /// into the tracks, old tracks out, and the network's tracks shared. pub(super) fn update_sight(&mut self, ground: &mut Ground) { let now = self.tick; // A role, mast or location change invalidates the cached terrain immediately. for sam in &self.sams { if sam.radar_up() && self.horizons.get(&sam.id).is_some_and(|h| !h.matches(sam)) { self.horizons.insert(sam.id, Horizon::build(antenna(sam), sensor_span(sam), ground, now)); } } // One horizon every few ticks: the land answers come in over time. if !self.sams.is_empty() && now % 3 == 0 { let radars: Vec = (0..self.sams.len()).filter(|&i| self.sams[i].radar_up()).collect(); if !radars.is_empty() { let i = radars[(now / 3) as usize % radars.len()]; let sam = &self.sams[i]; let h = Horizon::build(antenna(sam), sensor_span(sam), ground, now); self.horizons.insert(sam.id, h); } } let alive: std::collections::HashSet = self.sams.iter().filter(|s| s.radar_up()).map(|s| s.id).collect(); self.horizons.retain(|id, _| alive.contains(id)); // Each drone's height over the land under it (or over the systems' ground, unknown). let heights: Vec> = self.drones.iter().map(|d| ground.at(d.pos, now).map(|g| d.pos.y - g)).collect(); let drone_at: HashMap = self.drones.iter().enumerate().map(|(k, d)| (d.id, k)).collect(); let seed = self.seed; 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())); if !sam.alive() || sam.moving() { sam.tracks.clear(); continue; } if !sam.radar_up() { continue; } index.clear(); index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k))); let spec = sam.kind.spec(); let profile = sam.radar_profile(); let scan = sam.scan_profile(); let period = sam.scan_ticks(); let w = TAU / period; let (b0, ttl) = (sam.beam, ((period * 3.0) as u32).max(60)); sam.beam = (b0 + w) % TAU; let at = antenna(sam); let horizon = self.horizons.get(&sam.id); let local = spec.sensor * profile.local; // Channels already refining or holding fire plots. Search plots do not use one. let mut used = sam.tracks.iter().filter(|t| t.own_tick > 0 && t.own_product != battery::Measure::Search).count(); let mut fresh: Vec = Vec::new(); for (d, h) in self.drones.iter().zip(&heights) { if !d.alive() { continue; } let rel = d.pos - at; let dist = rel.length(); if dist > spec.sensor * profile.reach.max(1.0) * 1.2 { continue; } let locked = sam.target == Some(d.id) || sam.gun_target == Some(d.id); let held = index.get(&d.id).map(|&k| sam.tracks[k]); // The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round). let in_beam = swept(rel.x.atan2(-rel.z), b0, w); let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64); // A network plot cues a fire-quality radar to look, but is never itself a // measurement: reach, terrain, probability and noise still apply. let cue = profile.allows(battery::Measure::Fire) && held.is_some_and(|t| t.own_tick == 0 && t.age(now) <= MISSILE_AGE); if !(in_beam || locked || revisit || cue) { continue; } // The separate stations search their own patch; a cue or an already held // contact may be followed beyond it, never an arbitrary target of the map. if profile.local < 1.0 && dist > local && !locked && !(cue || held.is_some_and(|t| t.own_tick > 0)) { continue; } // The tracked-contact channels are a hard limit: work per tick stays bounded // and a full station does not silently refine the whole sky. A station already // refining a contact keeps its channel; a new refinement needs a free one, and // without one the station still publishes its ordinary coarse search plot. let own_held = held.is_some_and(|t| t.own_tick > 0); let holds_channel = own_held && held.is_some_and(|t| t.own_product != battery::Measure::Search); let mut product = if profile.allows(battery::Measure::Fire) { battery::Measure::Fire } else if profile.allows(battery::Measure::Refine) && held.is_some() { // Refinement only applies to a contact already matched, own or network. battery::Measure::Refine } else { battery::Measure::Search }; let wants_channel = product != battery::Measure::Search && !holds_channel; if profile.channels > 0 && wants_channel && used >= profile.channels as usize { product = battery::Measure::Search; } let height = h.unwrap_or(d.pos.y - sam.pos.y); let reach = reach(sam, d.kind, height); if dist > reach || (dist > NEAR && horizon.is_some_and(|hz| hz.hides(at, d.pos))) { continue; } let key = (sam.id as u64) << 32 | d.id as u64; // A target in the beam is measured with a chance that falls towards the edge of reach and // with the target's stealth; one the radar already follows is lost only now and then. let p = if locked || revisit { 0.985 } else { ((0.97 - 0.5 * (dist / reach).powi(3)) / d.kind.spec().stealth.sqrt()).clamp(0.05, 0.97) }; if dist > NEAR && dice(seed, now, key, 0) >= p { continue; } let sigma = if locked { 0.3 } else { profile.sigma + dist * profile.spread }; let noise = DVec3::new(dice(seed, now, key, 1) - 0.5, (dice(seed, now, key, 2) - 0.5) * profile.vertical, dice(seed, now, key, 3) - 0.5) * 2.0 * sigma; let measured = d.pos + noise; let quality = plot_quality(sam, profile, product, dist / reach.max(1.0), height); if profile.channels > 0 && wants_channel && product != battery::Measure::Search { 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 { 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())) } _ => (DVec3::ZERO, ClassEst::Unknown), }; fresh.push(Track { id: d.id, class, pos: measured, vel, tick: now, own_tick: now, source: sam.id, product, quality, own_product: product, own_quality: quality, ttl, hits, locked, }); } for t in fresh { merge(&mut sam.tracks, &mut index, t); } } // The network: every unit gets the tracks the radars within data-link range measured themselves, // with the time they were measured: a relayed track is never fresher than its measurement. // Fictional passive observation: hostile aircraft within 1600 blocks fix an emitting radar // every 20 ticks. Silence leaves the previous report to age normally. if now % 20 == 0 { for s in self.sams.iter().filter(|s| s.radar_up()) { if self.drones.iter().any(|d| d.alive() && d.pos.distance(s.pos) <= 1600.0) { self.intel.observe(s, now, ew::Seen::Emission); } } } let shared: Vec<(u32, DVec3, f64, Vec)> = self .sams .iter() .filter(|s| s.radar_up() && s.link_range() > 0.0) .map(|s| (s.id, s.pos, s.link_range(), s.tracks.iter().filter(|t| t.own_tick > 0 && t.own_tick == t.tick).copied().collect::>())) .filter(|s| !s.3.is_empty()) .collect(); // One freshest track per radar is all a cue needs: the posts never walk every contact. let cues: Vec<(u32, DVec3, f64, Track)> = if self.sams.iter().any(|s| s.kind == SamKind::Optical) { shared .iter() .filter_map(|(id, at, range, tracks)| tracks.iter().max_by_key(|t| t.tick).map(|t| (*id, *at, *range, *t))) .collect() } else { Vec::new() }; for sam in &mut self.sams { if sam.kind == SamKind::Optical { // An optical post receives a cue, not a track: the freshest network measurement within // link range only points its head, and none of it enters `tracks`, `seen` or `own`. sam.seen.clear(); sam.own.clear(); if sam.alive() && !sam.moving() && sam.link_range() > 0.0 { let mine = sam.link_range(); let mut best: Option = None; for (id, at, range, t) in &cues { if *id != sam.id && at.distance(sam.pos) <= range.min(mine) && best.is_none_or(|b: Track| t.tick > b.tick) { best = Some(*t); } } if let Some(t) = best { sam.optical.offer_cue(t); } } continue; } if sam.alive() && !sam.moving() && (sam.kind.armed() || (sam.kind == SamKind::Radar && sam.radar_role == battery::RadarRole::Engagement)) && sam.link_range() > 0.0 && !shared.is_empty() { index.clear(); index.extend(sam.tracks.iter().enumerate().map(|(k, t)| (t.id, k))); let mine = sam.link_range(); for (id, at, range, tracks) in &shared { if *id != sam.id && at.distance(sam.pos) <= range.min(mine) { for t in tracks { merge(&mut sam.tracks, &mut index, Track { own_tick: 0, own_product: battery::Measure::Search, own_quality: 0, ..*t }); } } } } sam.seen.clear(); sam.own.clear(); for t in &sam.tracks { sam.seen.push(t.id); if t.own_within(now, t.ttl as u64) { sam.own.push(t.id); } } } // Passive optics (#136) look after the network has spoken: a cue is only a cue, and every // observation it makes is its own, never a track and never an emission. self.update_optics(ground); } /// Whether any system's radar holds this drone (the player's radar shows only those). pub fn tracked(&self, id: u32) -> bool { self.sams.iter().any(|s| s.seen.contains(&id)) } /// The air picture as the player's panel and radar read it (the only thing they read). pub fn air_picture(&self) -> AirPicture { let now = self.tick; // With no system deployed there is no radar to be blind: the sky as it is (the same fallback the screens // always had); a network's picture is only what it holds. let unaided = self.sams.is_empty(); let mut tracks: Vec = if unaided { self.drones .iter() // No system is deployed: no estimation happens, the fallback is the sky as it is // (the screens have always had it), with the figures a system would show. .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: 100, own_product: battery::Measure::Fire, own_quality: 100, ttl: 1, hits: 3, locked: false, }) .collect() } else { self.picture().into_values().collect() }; tracks.sort_by_key(|t| t.id); AirPicture { now, tracks, unaided } } /// The freshest track of each drone any system holds: the air picture. At one /// tick the better plot (quality, then product) is the one the player sees. pub fn picture(&self) -> HashMap { let mut best: HashMap = HashMap::new(); for t in self.sams.iter().flat_map(|s| s.tracks.iter()) { if best.get(&t.id).is_none_or(|b| (t.tick, t.quality, t.product) > (b.tick, b.quality, b.product)) { best.insert(t.id, *t); } } best } } #[cfg(test)] mod low_view_tests { use super::*; /// A radar on level land (70) with a hill east of it (140 high, x 128..160): the east ray is cut at the hill, the others are not. fn world() -> (Sim, Ground, u32) { let mut sim = Sim::new(3); let id = sim.id(); sim.sams.push(Sam::new(id, SamKind::Buk, DVec3::new(0.0, 70.0, 0.0), 0.0)); let mut ground = Ground::default(); let cols: Vec<(i32, i32, i32)> = (-60..60).map(|k| (k * 16, 0, if (128..160).contains(&(k * 16)) { 140 } else { 70 })).collect(); ground.answer(cols, 0); let h = Horizon::build(antenna(&sim.sams[0]), sim.sams[0].kind.spec().sensor, &mut ground, 0); sim.horizons.insert(id, h); (sim, ground, id) } #[test] fn the_land_cuts_the_coverage_edge_behind_a_hill() { let (sim, ground, id) = world(); let ls = sim.low_sensor(SamKind::Buk, DVec3::new(0.0, 70.0, 0.0), Some(id)).unwrap(); assert!(ls.terrain && ls.reach > 200.0, "{}", ls.reach); let rim = sim.low_rim(&ground, &ls); let east = rim[RIM_RAYS / 4]; assert!((128.0..=176.0).contains(&east), "east edge {east}"); // Rays whose land is unknown hide nothing: the whole reach. assert_eq!(rim[0], ls.reach as f32); assert_eq!(rim[RIM_RAYS * 3 / 4], ls.reach as f32); assert!(sim.low_sees(&ground, &ls, -200.0, 0.0)); assert!(sim.low_sees(&ground, &ls, 100.0, 0.0)); assert!(!sim.low_sees(&ground, &ls, 200.0, 0.0), "behind the hill"); assert!(!sim.low_sees(&ground, &ls, ls.reach + 50.0, 0.0), "out of reach"); // A ghost (no horizon) sees the whole circle. let ghost = sim.low_sensor(SamKind::Buk, DVec3::new(0.0, 70.0, 0.0), None).unwrap(); assert!(sim.low_sees(&ground, &ghost, 200.0, 0.0)); } // The map's tint asks `low_sees` for a cell of a coarse grid at every radar that reaches it, and the edges // ask `low_rim`: with a Polygon's worth of systems both stay cheap (native time, a few ms; wasm is a few times that). #[test] fn coverage_of_128_systems_is_cheap() { let (mut sim, mut ground, _) = world(); for i in 0..127 { let id = sim.id(); let pos = DVec3::new((i % 16) as f64 * 40.0 - 300.0, 70.0, (i / 16) as f64 * 40.0 - 150.0); sim.sams.push(Sam::new(id, SamKind::Buk, pos, 0.0)); let k = sim.sams.len() - 1; let h = Horizon::build(antenna(&sim.sams[k]), sim.sams[k].kind.spec().sensor, &mut ground, 0); sim.horizons.insert(id, h); } let sensors = sim.low_sensors(); assert_eq!(sensors.len(), 128); let t = std::time::Instant::now(); let mut seen = 0; for cy in 0..28 { for cx in 0..36 { let (x, z) = (cx as f64 * 30.0 - 500.0, cy as f64 * 30.0 - 400.0); // Worst case for the early exit: a cell no radar sees is tested against all that reach it. if sensors.iter().any(|s| sim.low_sees(&ground, s, x, z)) { seen += 1; } } } let tint = t.elapsed(); let t = std::time::Instant::now(); let rims: usize = sensors.iter().take(3).map(|s| sim.low_rim(&ground, s).len()).sum(); eprintln!("tint of 1008 cells: {tint:?} ({seen} seen); 3 rims: {:?} ({rims})", t.elapsed()); assert!(seen > 0 && tint.as_millis() < 100, "{tint:?}"); } } #[cfg(test)] mod relay_tests { use super::*; /// 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] fn a_repeated_relay_adds_no_confidence_and_stays_foreign() { let ours = Track { id: 7, class: ClassEst::Unknown, pos: DVec3::new(0.0, 100.0, 0.0), vel: DVec3::ZERO, tick: 90, own_tick: 90, source: 1, product: battery::Measure::Fire, quality: 80, own_product: battery::Measure::Fire, own_quality: 80, ttl: 400, hits: 1, locked: false }; let relay = Track { id: 7, class: ClassEst::Probable(Class::Drone), pos: DVec3::new(0.0, 100.0, -10.0), vel: DVec3::X, tick: 100, own_tick: 0, source: 2, product: battery::Measure::Fire, quality: 90, own_product: battery::Measure::Search, own_quality: 0, ttl: 400, hits: 2, locked: false }; let mut tracks = vec![ours]; let mut index: HashMap = HashMap::from([(7, 0)]); merge(&mut tracks, &mut index, relay); assert_eq!(tracks[0].own_tick, 90, "a relayed track is not the receiver's own measurement"); for _ in 0..5 { merge(&mut tracks, &mut index, relay); } assert_eq!(tracks.len(), 1, "a relay of a held measurement is one track"); assert_eq!(tracks[0].hits, 2, "a repeated relay added confidence"); assert_eq!(tracks[0].class, ClassEst::Probable(Class::Drone), "a relay altered the estimate"); assert_eq!(tracks[0].tick, 100, "a relay refreshed the measurement"); assert_eq!(tracks[0].own_tick, 90, "a relay became the receiver's own"); } }