//! Electronic warfare, and what the enemy learns. //! //! An EW station jams the satellite navigation of the drones and cruise //! missiles near it (ballistic missiles and the Lancet's optics don't care): //! they lose their route and drift off their aim. It runs only a short while //! before its transmitter overheats, and while it transmits it gives itself //! away. The enemy keeps what it learns — which systems fired and which //! stations jammed (its next drones go for them), and from which bearings its //! raids were shot down or got through (its next raid comes from the best). use super::*; use std::collections::{HashSet, VecDeque}; use std::sync::Arc; /// A route still to be worked out after a retarget (#127). The drone already has its new aim; the job /// gives it a route as the planner's budget allows, and its old route stays until then. #[derive(Clone)] pub(super) struct RouteJob { /// The drone, by id: queue indices move as launches happen. drone: u32, /// The new aim, the drone's navigation error included. aim: DVec3, /// The unit it was sent at (0 when the aim is not a unit). unit: u32, /// The adaptive tick whose picture chose the aim: the knowledge version. version: u64, /// The enemy picture that tick knew, shared by every job of the tick. known: Arc>, } /// How far a station jams. pub const EW_RADIUS: f64 = 350.0; /// Heat a tick on (20 s to overheat), and cooling a tick off (45 s from hot). const HEAT: f64 = 1.0 / 400.0; const COOL: f64 = 1.0 / 900.0; /// After overheating it may switch on again only below this. const READY: f64 = 0.3; /// Approach sectors the enemy keeps score of. pub const SECTORS: usize = 12; #[derive(Default)] pub(super) struct Intel { /// Shot down and got through, by approach sector, over every raid. pub kills: [u32; SECTORS], pub hits: [u32; SECTORS], /// Units that gave themselves away: (id, where, when) — launches, jamming. pub revealed: Vec<(u32, DVec3, u64)>, } impl DroneKind { /// It navigates by satellite: EW throws it off. pub fn jammable(self) -> bool { matches!(self, DroneKind::Shahed | DroneKind::Geran3 | DroneKind::Gerbera | DroneKind::Kh101 | DroneKind::Kalibr) } } /// The sector of a bearing (radians). pub fn sector(bearing: f64) -> usize { ((bearing.rem_euclid(TAU) / TAU) * SECTORS as f64) as usize % SECTORS } impl Sim { /// Switches every EW station on or off; one cooling down after overheating stays off. /// Returns how many are now on, and how many are still too hot. pub fn set_ew(&mut self, on: bool) -> (u32, u32) { let (mut n, mut hot) = (0, 0); for s in self.sams.iter_mut().filter(|s| s.kind == SamKind::Ew && s.alive()) { if on && s.ew_lock { hot += 1; continue; } s.ew_on = on && !s.moving(); n += u32::from(s.ew_on); } (n, hot) } pub fn ew_active(&self) -> bool { self.sams.iter().any(|s| s.ew_on) } /// The stations' heat, and their jamming. pub(super) fn step_ew(&mut self, out: &mut Out) { let now = self.tick; let mut on: Vec = Vec::new(); for s in self.sams.iter_mut().filter(|s| s.kind == SamKind::Ew) { if !s.alive() || s.moving() { s.ew_on = false; } if s.ew_on { s.heat += HEAT; if s.heat >= 1.0 { s.heat = 1.0; s.ew_on = false; s.ew_lock = true; out.messages.push("РЭБ: передатчик перегрет, выключен".into()); out.sound("minecraft:block.fire.extinguish", s.pos, 2.0, 0.7); } } else { s.heat = (s.heat - COOL).max(0.0); if s.ew_lock && s.heat < READY { s.ew_lock = false; } } if s.ew_on { let top = s.pos + DVec3::Y * 2.6 * s.kind.spec().scale; on.push(s.pos); if now % 3 == 0 { out.particles("minecraft:electric_spark", top, 0.6, DVec3::ZERO, 0.2, 3); } if now % 40 == 0 { out.sound("minecraft:block.beacon.ambient", top, 2.0, 1.4); } // A transmitter on the air: the enemy finds it. if now % 20 == 0 { self.intel.revealed.push((s.id, s.pos, now)); } } } if on.is_empty() { return; } for d in self.drones.iter_mut().filter(|d| d.alive() && d.kind.jammable()) { let Some(k) = on.iter().map(|p| 1.0 - horizontal(d.pos - *p).length() / EW_RADIUS).reduce(f64::max) else { continue }; if k <= 0.0 { continue; } // Its fix wanders: the aim drifts, the route is lost. d.route.clear(); d.target += DVec3::new(self.rng.s(), 0.0, self.rng.s()) * (1.2 * k); d.jammed = true; } } /// What the enemy's raids learned: their drones' fates by sector. pub(super) fn learn(&mut self, sector: usize, killed: bool) { if killed { self.intel.kills[sector % SECTORS] += 1; } else { self.intel.hits[sector % SECTORS] += 1; } } /// The bearing a smart raid comes from: the sector its raids got through best, a little random. pub(super) fn best_bearing(&mut self) -> f64 { let score = |i: usize| { let (k, h) = (self.intel.kills[i] as f64, self.intel.hits[i] as f64); (h + 1.0) / (k + h + 2.0) }; let best = (0..SECTORS).max_by(|&a, &b| score(a).total_cmp(&score(b))).unwrap_or(0); // Unknown sectors are worth a look too. let pick = if self.rng.chance(0.3) { (self.rng.f() * SECTORS as f64) as usize } else { best }; (pick as f64 + 0.5 + self.rng.s() * 0.4) / SECTORS as f64 * TAU } /// Units the enemy knows of and would go for, newest first: (id, where). /// One pass over the log: aliveness and duplicates by set, not by rescanning /// the lists for every entry — a big log with many systems must not make the /// planner's snapshot quadratic (#122). pub(super) fn known_units(&self) -> Vec<(u32, DVec3)> { let alive: HashSet = self.sams.iter().filter(|s| s.alive()).map(|s| s.id).collect(); let mut seen: HashSet = HashSet::new(); let mut out: Vec<(u32, DVec3)> = Vec::new(); for &(id, at, observed) in self.intel.revealed.iter().rev() { if self.tick.saturating_sub(observed) >= 6000 { continue; } if !seen.insert(id) { continue; } if alive.contains(&id) { out.push((id, at)); } } out } /// Whether an observation or another disclosure placed this unit in enemy intelligence. pub(super) fn enemy_knows(s: &Sam, known: &[(u32, DVec3)]) -> bool { s.alive() && known.iter().any(|k| k.0 == s.id) } /// During a smart raid: its drones not yet launched go for what just gave itself away (a jamming station /// first, then systems that fired), and drones whose system target is gone pick another. Routes for the /// new aims are worked out over the following ticks, as the planner's share allows (#127). pub(super) fn adapt(&mut self) { if self.tick % 40 == 0 { self.adapt_targets(); } self.replan_retargets(); } /// The adaptive tick: chooses the new aims and leaves a route job for each drone that needs one. The /// old route stays until a new one is ready: a drone is never left with no way round the defences. fn adapt_targets(&mut self) { self.intel.revealed.retain(|r| self.tick - r.2 < 6000); let known = Arc::new(self.known_units()); let ew: Vec<(u32, DVec3)> = known.iter().copied().filter(|(id, _)| self.sams.iter().any(|s| s.id == *id && s.kind == SamKind::Ew)).collect(); if known.is_empty() { return; } let pick = |i: usize, list: &[(u32, DVec3)]| list[i % list.len()]; // The drones sent at a new target: a route job each, to be worked out as the planner's budget allows. let mut jobs: Vec = Vec::new(); let mut n = 0usize; for (_, d) in self.queue.iter_mut().filter(|(_, d)| d.smart) { let hunter = matches!(d.kind, DroneKind::Lancet | DroneKind::Kh22 | DroneKind::Zircon); if !hunter && !(d.kind == DroneKind::Shahed && n % 4 == 0) { n += 1; continue; } // Only those not yet sent at a unit. if known.iter().any(|(_, pos)| pos.distance(d.target - d.err) < 6.0) { continue; } let (unit, at) = if !ew.is_empty() { pick(n, &ew) } else { pick(n, &known) }; d.target = at + d.err; if Self::route_plannable(d) { jobs.push(RouteJob { drone: d.id, aim: d.target, unit, version: self.tick, known: Arc::clone(&known) }); } else { // Nothing will be replanned for it: its old route leads to the old aim, so it goes straight. d.route.clear(); } n += 1; } // In flight: a target system destroyed — the next known one, or keep going. for d in self.drones.iter_mut().filter(|d| d.alive() && d.smart) { let aimed_at_wreck = self.sams.iter().any(|s| !s.alive() && s.pos.distance(d.target - d.err) < 6.0); if aimed_at_wreck { let plannable = Self::route_plannable(d); let next = known .iter() .filter(|k| !plannable || Self::can_turn_to(d, k.1)) .min_by(|a, b| a.1.distance(d.pos).total_cmp(&b.1.distance(d.pos))); if let Some(&(unit, at)) = next { d.target = at + d.err; if plannable { jobs.push(RouteJob { drone: d.id, aim: d.target, unit, version: self.tick, known: Arc::clone(&known) }); } else { d.route.clear(); } } } } for job in jobs { self.queue_route(job); } } /// A kind whose route the replan works out: a Lancet's strike on a unit and the ballistic missiles go /// straight on purpose, as in the raid's own plan. fn route_plannable(d: &Drone) -> bool { let spec = d.kind.spec(); d.smart && spec.ballistic.is_none() && !spec.decoy && d.kind != DroneKind::Lancet } /// Whether a drone can turn onto `at` from where it is. A slow missile with a close target behind /// would only circle it: it finishes the approach it is on instead of turning to another unit (#127). fn can_turn_to(d: &Drone, at: DVec3) -> bool { let spec = d.kind.spec(); let radius = (spec.speed / spec.turn.max(0.01)).max(24.0); let to = horizontal(at - d.pos); if to.length() >= radius * 2.0 { return true; } let heading = horizontal(d.vel).normalize_or_zero(); heading == DVec3::ZERO || heading.dot(to.normalize_or_zero()) > 0.0 } /// Adds a job, replacing an older one for the same drone in place: a drone retargeted again before its /// route was ready must not grow the queue or be planned for an aim it no longer has (#127). fn queue_route(&mut self, job: RouteJob) { if let Some(i) = self.retargets.iter().position(|j| j.drone == job.drone) { if self.retargets[i].version <= job.version { self.retargets[i] = job; } } else { self.retargets.push_back(job); } } /// The drone a job is for: waiting in the queue or already flying. fn drone_of(&self, id: u32) -> Option<&Drone> { self.queue.iter().find(|(_, d)| d.id == id).map(|(_, d)| d).or_else(|| self.drones.iter().find(|d| d.id == id)) } fn drone_of_mut(&mut self, id: u32) -> Option<&mut Drone> { if let Some(i) = self.queue.iter().position(|(_, d)| d.id == id) { return Some(&mut self.queue[i].1); } self.drones.iter_mut().find(|d| d.id == id) } /// Whether a job still says what its drone is doing. A dead drone, an aim changed again, or a unit /// destroyed since cancels the job: the next adaptive tick will make a new one if it is still wanted. fn job_live(&self, job: &RouteJob) -> bool { let Some(d) = self.drone_of(job.drone) else { return false }; if !d.alive() || d.target != job.aim { return false; } job.unit == 0 || !self.sams.iter().any(|s| s.id == job.unit && !s.alive()) } /// The known land of the original plan, sampled on `grid` (NaN where that plan knew nothing). A retarget /// is planned over the same relief as the raid's own routes, never over ground mapped after it (#127). fn retarget_relief(&self, grid: &raid::Grid) -> Option> { let (src, heights) = self.known_relief.as_ref()?; let n = grid.size; let mut out = vec![f32::NAN; (n * n) as usize]; let (x1, z1) = (src.min.x + src.size as f64 * src.cell, src.min.z + src.size as f64 * src.cell); let mut any = false; for i in 0..n { for j in 0..n { let p = grid.centre((i, j), 0.0); if p.x < src.min.x || p.x >= x1 || p.z < src.min.z || p.z >= z1 { continue; } let (si, sj) = src.index(p); let h = heights[(si * src.size + sj) as usize]; if h.is_finite() { out[(i * n + j) as usize] = h; any = true; } } } any.then_some(out) } /// Works the retarget queue: one grid and one set of prices cover the jobs, and the work is the /// planner's share for a tick. A job the budget cannot reach stays queued for the next tick, and its /// drone keeps the old route (or, if it had none, flies straight for a while — never for ever). fn replan_retargets(&mut self) { if self.retargets.is_empty() { return; } let mut jobs = std::mem::take(&mut self.retargets); let mut live = VecDeque::with_capacity(jobs.len()); while let Some(job) = jobs.pop_front() { if self.job_live(&job) { live.push_back(job); } else if let Some(d) = self.drone_of_mut(job.drone) && d.alive() { // No new route will come from this job: the old route is a fallback, not a plan. d.route.clear(); } } jobs = live; if jobs.is_empty() { return; } // One grid over all their starts and goals, with room round them to go by. let (mut lo, mut hi) = (DVec3::splat(f64::INFINITY), DVec3::splat(f64::NEG_INFINITY)); for job in &jobs { let Some(d) = self.drone_of(job.drone) else { continue }; for p in [d.pos, job.aim] { lo = lo.min(p); hi = hi.max(p); } } let span = (hi.x - lo.x).max(hi.z - lo.z) / 2.0 + 450.0; let cell = raid::CELL.max(2.0 * span / raid::CELLS as f64); let centre = (lo + hi) / 2.0; let grid = raid::Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 }; let relief = self.retarget_relief(&grid); let land = relief.as_deref(); let mut prices: HashMap> = HashMap::new(); let mut routes: HashMap<(DroneKind, (i32, i32), (i32, i32)), Vec> = HashMap::new(); let mut work = 0usize; while let Some(job) = jobs.front().cloned() { if work >= raid::WORK_PER_TICK { break; } if !self.job_live(&job) { jobs.pop_front(); continue; } let Some(d) = self.drone_of(job.drone) else { jobs.pop_front(); continue; }; let (pos, kind) = (d.pos, d.kind); let key = (kind, grid.index(pos), grid.index(job.aim)); let route = match routes.get(&key) { Some(r) => r.clone(), None => { if !prices.contains_key(&kind) { let (p, cost) = self.price_grid_known(&grid, kind, land, job.known.as_slice()); work += cost; prices.insert(kind, p); } let relief = land.map(|heights| raid::Relief { heights, slope: (kind.climb_pitch().tan() * 0.5) as f32, floor: (job.aim.y + kind.spec().clearance) as f32, }); let (r, cost) = raid::plan_route_on(&grid, &prices[&kind], relief.as_ref(), pos, job.aim); work += cost; routes.insert(key, r.clone()); r } }; if let Some(d) = self.drone_of_mut(job.drone) { d.route = route; } jobs.pop_front(); } self.retargets = jobs; } /// The drones with a route job still waiting (tests and diagnostics). #[cfg(test)] pub(super) fn retarget_ids(&self) -> Vec { self.retargets.iter().map(|j| j.drone).collect() } }