Keep unfinished retarget routes in a bounded job queue (#127)

A mass retarget used to clear every selected drone's route before the planner's per-tick work ran out: the rest flew straight for ever. Route jobs now carry the drone id, new aim, target unit, knowledge version and the intel snapshot, stay in a FIFO across ticks and are drained under the same WORK_PER_TICK. An old safe route is kept until its replacement is ready; a cancelled job falls back to a straight run. Jobs are replaced in place per drone, cancelled when the drone or unit is gone, and retarget routes reuse the original plan's known relief. An in-flight drone no longer turns to a unit behind its turning circle. Core release tests, adapter tests and the real WASM contract pass.
This commit is contained in:
2026-11-06 12:05:36 +03:00
parent dc36d67eb7
commit 6f7b041c8b
7 changed files with 369 additions and 57 deletions
+190 -47
View File
@@ -8,7 +8,24 @@
//! 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;
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<Vec<(u32, DVec3)>>,
}
/// How far a station jams.
pub const EW_RADIUS: f64 = 350.0;
@@ -157,23 +174,30 @@ impl Sim {
}
/// 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.
/// 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 {
return;
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 = self.known_units();
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()].1;
// The drones sent at a new target: (waiting in the queue, index), to get a new route.
let mut retargeted: Vec<(bool, usize)> = Vec::new();
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<RouteJob> = Vec::new();
let mut n = 0usize;
for (qi, (_, d)) in self.queue.iter_mut().enumerate().filter(|(_, (_, d))| d.smart) {
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;
@@ -183,50 +207,145 @@ impl Sim {
if known.iter().any(|(_, pos)| pos.distance(d.target - d.err) < 6.0) {
continue;
}
let to = if !ew.is_empty() { pick(n, &ew) } else { pick(n, &known) };
d.target = to + d.err;
d.route.clear();
retargeted.push((true, qi));
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 (di, d) in self.drones.iter_mut().enumerate().filter(|(_, d)| d.alive() && d.smart) {
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 next = known.iter().min_by(|a, b| a.1.distance(d.pos).total_cmp(&b.1.distance(d.pos)));
if let Some((_, at)) = next {
d.target = *at + d.err;
d.route.clear();
retargeted.push((false, di));
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();
}
}
}
}
self.replan_routes(&retargeted);
for job in jobs {
self.queue_route(job);
}
}
/// Routes round the known defences for drones that were just sent at a new target, from where they are
/// (or wait). One grid and one set of prices cover them all, and the work is the planner's share for a
/// tick: those left over fly straight, as they did before there was a replan. A Lancet's strike on a
/// unit and the ballistic missiles go straight on purpose, as in the raid's own plan.
fn replan_routes(&mut self, jobs: &[(bool, usize)]) {
let drone = |s: &Sim, (queued, i): (bool, usize)| if queued { s.queue[i].1.clone() } else { s.drones[i].clone() };
let jobs: Vec<(bool, usize)> = jobs
.iter()
.copied()
.filter(|&j| {
let d = drone(self, j);
let spec = d.kind.spec();
d.smart && spec.ballistic.is_none() && !spec.decoy && d.kind != DroneKind::Lancet
})
.collect();
/// 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<Vec<f32>> {
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 &j in &jobs {
let d = drone(self, j);
for p in [d.pos, d.target] {
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);
}
@@ -235,31 +354,55 @@ impl Sim {
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<DroneKind, Vec<f32>> = HashMap::new();
let mut routes: HashMap<(DroneKind, (i32, i32), (i32, i32)), Vec<DVec3>> = HashMap::new();
let mut work = 0usize;
for j in jobs {
let d = drone(self, j);
while let Some(job) = jobs.front().cloned() {
if work >= raid::WORK_PER_TICK {
break;
}
let key = (d.kind, grid.index(d.pos), grid.index(d.target));
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(&d.kind) {
let (p, cost) = self.price_grid(&grid, d.kind);
if !prices.contains_key(&kind) {
let (p, cost) = self.price_grid_known(&grid, kind, land, job.known.as_slice());
work += cost;
prices.insert(d.kind, p);
prices.insert(kind, p);
}
let (r, cost) = raid::plan_route(&grid, &prices[&d.kind], d.pos, d.target);
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
}
};
let d = if j.0 { &mut self.queue[j.1].1 } else { &mut self.drones[j.1] };
d.route = route;
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<u32> {
self.retargets.iter().map(|j| j.drone).collect()
}
}