diff --git a/airdef-mod/src/sim/durable.rs b/airdef-mod/src/sim/durable.rs index dbd4475..e8b4d3b 100644 --- a/airdef-mod/src/sim/durable.rs +++ b/airdef-mod/src/sim/durable.rs @@ -849,27 +849,32 @@ impl Sim { self.known_relief = save.known_relief; self.drones = save.drones; self.queue = save.queue; - self.recon = save.recon; let alive: std::collections::HashSet = self.drones.iter().map(|d| d.id).chain(self.queue.iter().map(|(_, d)| d.id)).collect(); - self.recon.retain_drones(&alive); - self.recon.expire(self.tick); self.retargets.clear(); // A job's picture is its version's: the contacts observed no later than it, plus its own - // target (whose last saved observation stands in for one made after the version). - let mut by_version: HashMap>> = HashMap::new(); + // target (whose last saved observation stands in for one made after the version), and the + // recon marks reported by then. The snapshot keeps the version's tick: the job ages its + // contacts at that tick, not at the tick the restored queue reaches it (#146). + let mut by_version: HashMap> = HashMap::new(); for rec in save.jobs { let known = by_version.entry(rec.version).or_insert_with(|| { - let picture: Vec = save + let contacts: Vec = save .contacts .iter() .filter(|c| c.tick <= rec.version || c.id == rec.unit) .copied() .collect(); - std::sync::Arc::new(picture) + let marks = save.recon.leads(rec.version).into_iter().filter(|m| m.observed <= rec.version).collect(); + std::sync::Arc::new(ew::KnowledgeSnapshot { tick: rec.version, contacts, marks }) }); let job = ew::RouteJob::restored(rec.id, rec.drone, rec.aim, rec.unit, rec.version, rec.intent, std::sync::Arc::clone(known), rec.relief); self.retargets.push_back(job); } + // The recon memory goes back after the jobs' snapshots were read from the save's own: a + // job's version keeps the marks reported by then, not what survives today's expiry. + self.recon = save.recon; + self.recon.retain_drones(&alive); + self.recon.expire(self.tick); // Jobs the saved picture no longer stands behind, and anything past the bound, go now. self.prune_air() } @@ -1008,7 +1013,8 @@ mod durable_tests { sim.queue.push((300, queued)); // Two pending jobs: one of the plan, one a replacement, both with their own version. let job = |id, drone, aim, unit, version, intent| { - ew::RouteJob::restored(id, drone, aim, unit, version, intent, std::sync::Arc::new(sim.intel.contacts().values().copied().collect()), sim.known_relief.clone()) + let known = ew::KnowledgeSnapshot { tick: version, contacts: sim.intel.contacts().values().copied().collect(), marks: Vec::new() }; + ew::RouteJob::restored(id, drone, aim, unit, version, intent, std::sync::Arc::new(known), sim.known_relief.clone()) }; sim.retargets.push_back(job(5, sim.drones[0].id, sim.drones[0].target, ids[0], 100, ew::Intent::React)); let queued_target = sim.queue[0].1.target; @@ -1132,7 +1138,7 @@ mod durable_tests { let kept = sim.retargets.len(); let some = sim.retargets[0].clone(); // A job for a drone that is not here. - sim.retargets.push_back(ew::RouteJob::restored(900, 999_999, DVec3::ZERO, 0, sim.tick, ew::Intent::Plan, std::sync::Arc::new(Vec::new()), None)); + sim.retargets.push_back(ew::RouteJob::restored(900, 999_999, DVec3::ZERO, 0, sim.tick, ew::Intent::Plan, std::sync::Arc::new(ew::KnowledgeSnapshot::empty(sim.tick)), None)); // A job whose aim is no longer its drone's. let mut stale = some.clone(); stale.id = 901; diff --git a/airdef-mod/src/sim/ew.rs b/airdef-mod/src/sim/ew.rs index 14fb366..8b92bec 100644 --- a/airdef-mod/src/sim/ew.rs +++ b/airdef-mod/src/sim/ew.rs @@ -114,8 +114,9 @@ pub(super) struct RouteJob { pub(super) unit: u32, /// The adaptive tick whose picture chose the aim: the knowledge version. pub(super) version: u64, - /// The enemy picture that tick knew, shared by every job of the tick. - pub(super) known: Arc>, + /// The enemy knowledge that tick chose the aim from, shared by every job of the tick: its + /// contacts are aged at its own tick, not at the tick the job gets its budget (#146). + pub(super) known: Arc, /// The land that tick's plan knew, shared by every job of the version. A later plan replacing the /// global snapshot must not change a pending job's relief (#127). pub(super) relief: Option>, @@ -125,14 +126,14 @@ pub(super) struct RouteJob { impl RouteJob { /// A job of this tick's picture; the id and the priority follow from the intent. - fn new(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc>, relief: Option>) -> Self { + fn new(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc, relief: Option>) -> Self { Self { id, drone, aim, unit, version, known, relief, intent } } pub(super) fn priority(&self) -> u8 { self.intent.priority() } /// A job read back from a save: its id, aim, unit, version, picture and relief are the file's. - pub(super) fn restored(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc>, relief: Option>) -> Self { + pub(super) fn restored(id: u32, drone: u32, aim: DVec3, unit: u32, version: u64, intent: Intent, known: Arc, relief: Option>) -> Self { Self { id, drone, aim, unit, version, known, relief, intent } } } @@ -190,7 +191,7 @@ impl RouteJob { aim: DVec3, unit: u32, version: u64, - known: Arc>, + known: Arc, relief: Option>, ) -> Self { Self { id: drone, drone, aim, unit, version, known, relief, intent: Intent::Plan } @@ -371,6 +372,27 @@ impl Contact { } } +/// One version of the enemy's knowledge (#146): the tick it was observed at, the disclosure +/// contacts and the recon marks live then. A smart order chooses its targets and prices every +/// kind's routes on this one snapshot; a retarget version ages its contacts at its own tick, +/// never at the tick the planner's budget happens to reach the job. The current time may cancel +/// a stale job, but it never re-ages the snapshot the job was chosen from. +#[derive(Clone)] +pub(super) struct KnowledgeSnapshot { + /// The tick the contacts and marks were observed at. + pub(super) tick: u64, + pub(super) contacts: Vec, + pub(super) marks: Vec, +} + +impl KnowledgeSnapshot { + /// A version that knows nothing: for a job whose picture is empty. + #[cfg(test)] + pub(super) fn empty(tick: u64) -> Self { + Self { tick, contacts: Vec::new(), marks: Vec::new() } + } +} + /// The radar reach the enemy's planners price by: the type's published figure, undamaged /// and role-default. What a unit suffers or is configured to while unobserved is not in it. pub(super) fn published_reach(kind: SamKind, drone: DroneKind, height: f64) -> f64 { @@ -564,6 +586,12 @@ impl Sim { out } + /// The knowledge this moment holds, as one snapshot for a whole decision (#146): the tick, + /// the contacts and the recon marks, read once and never re-read per kind or per job. + pub(super) fn knowledge_now(&self) -> KnowledgeSnapshot { + KnowledgeSnapshot { tick: self.tick, contacts: self.picture_of_defences(), marks: self.recon.leads(self.tick) } + } + /// Whether the picture holds a live contact for this unit: what the old revelation log /// answered at a scan, now one map lookup. pub(super) fn known_live(&self, id: u32) -> bool { @@ -593,8 +621,10 @@ impl Sim { fn adapt_targets(&mut self) { self.intel.expire(self.tick); self.recon.expire(self.tick); - let picture = Arc::new(self.picture_of_defences()); - let leads = self.recon.leads(self.tick); + // One knowledge version for every aim and job this adaptive tick chooses (#146). + let knowledge = Arc::new(self.knowledge_now()); + let picture = &knowledge.contacts; + let leads = &knowledge.marks; if picture.is_empty() && leads.is_empty() { return; } @@ -639,7 +669,7 @@ impl Sim { d.intent = Intent::React; d.aim = d.aim.replaced(c.id, now, c.confidence(now)); if Self::route_plannable(d) { - jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&picture), relief.clone())); + jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&knowledge), relief.clone())); job_next += 1; } else { d.route.clear(); @@ -676,7 +706,7 @@ impl Sim { // A first assignment is not a switch: the aim's clock starts here, the count is kept. d.aim = Aim { unit, since: now, switches: d.aim.switches, confidence: Some(confidence) }; if Self::route_plannable(d) { - jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&picture), relief.clone())); + jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::React, Arc::clone(&knowledge), relief.clone())); job_next += 1; } else { // Nothing will be replanned for it: its old route leads to the old aim, so it goes straight. @@ -739,7 +769,7 @@ impl Sim { d.intent = Intent::Replace; d.aim = d.aim.replaced(unit, now, confidence); if plannable { - jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Replace, Arc::clone(&picture), relief.clone())); + jobs.push(RouteJob::new(job_next, d.id, d.target, d.aim.unit, now, Intent::Replace, Arc::clone(&knowledge), relief.clone())); job_next += 1; } else { d.route.clear(); @@ -1007,7 +1037,7 @@ impl Sim { Some(r) => r.clone(), None => { if !prices.contains_key(&(kind, version)) { - let (p, cost) = self.price_grid_known(&grid, kind, land, job.known.as_slice()); + let (p, cost) = self.price_grid_known(&grid, kind, land, &job.known); work += cost; prices.insert((kind, version), p); } @@ -1854,7 +1884,7 @@ mod intent_tests { d.smart = true; let id = d.id; sim.drones.push(d); - sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 0.0), 0, 1, Arc::new(Vec::new()), None)); + sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 0.0), 0, 1, Arc::new(KnowledgeSnapshot::empty(1)), None)); } assert_eq!(sim.retargets.len(), JOBS_MAX); // A replacement is worth less than a plan's objective: the queue refuses it. @@ -1862,7 +1892,7 @@ mod intent_tests { d.smart = true; let id = d.id; sim.drones.push(d); - sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 50.0), 0, 2, Arc::new(Vec::new()), None).with_intent(Intent::Replace)); + sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 50.0), 0, 2, Arc::new(KnowledgeSnapshot::empty(2)), None).with_intent(Intent::Replace)); assert_eq!(sim.retargets.len(), JOBS_MAX, "a worthless job grew the queue"); // Nothing queued is a replacement: a replacement is the lowest priority and does displace one. sim.retargets.iter_mut().for_each(|j| j.intent = Intent::Replace); @@ -1870,7 +1900,7 @@ mod intent_tests { d.smart = true; let id = d.id; sim.drones.push(d); - sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 60.0), 0, 2, Arc::new(Vec::new()), None).with_intent(Intent::Plan)); + sim.queue_route(RouteJob::for_test(id, DVec3::new(1000.0, 70.0, 60.0), 0, 2, Arc::new(KnowledgeSnapshot::empty(2)), None).with_intent(Intent::Plan)); assert_eq!(sim.retargets.len(), JOBS_MAX, "the bound was broken"); assert!(sim.retargets.back().is_some_and(|j| j.drone == id && j.intent == Intent::Plan), "the plan's job did not make room"); } diff --git a/airdef-mod/src/sim/raid.rs b/airdef-mod/src/sim/raid.rs index cb1a398..7ce5d90 100644 --- a/airdef-mod/src/sim/raid.rs +++ b/airdef-mod/src/sim/raid.rs @@ -100,6 +100,9 @@ struct Item { /// A raid being planned: its drones, the prices and routes so far, and the planned ones. pub(super) struct Plan { grid: Grid, + /// The one knowledge version the whole order was chosen on and is routed on (#146): every + /// kind's prices are worked out on it, whenever the budget reaches that kind. + knowledge: ew::KnowledgeSnapshot, prices: HashMap>, routes: HashMap<(DroneKind, i32, i32, i32), Vec>, items: Vec, @@ -280,13 +283,14 @@ impl Sim { return 0; } let smart = order.aim == Aim::Smart; - // The planner's picture of the layout: one snapshot for the whole order. It is - // read-only while the plan is built, and taking it per drone made a big second order - // quadratic in the force's size (#122); a map of contacts makes it linear in them (#127). - let picture = self.picture_of_defences(); + // The planner's picture of the layout: one snapshot for the whole order, kept in the plan + // (#146). It is read-only while the plan is built, and taking it per drone made a big second + // order quadratic in the force's size (#122); a map of contacts makes it linear in them (#127). + let knowledge = self.knowledge_now(); + let picture = &knowledge.contacts; // The partial picture the recon flights have radioed home. It is memory, not the // force: a mark has an area, a category and an age, never a unit's exact place (#135). - let leads = self.recon.leads(self.tick); + let leads = &knowledge.marks; // A smart enemy comes from where its raids got through best. let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU }; // The raid's sides (1, 2, or 4-5): its launch sites go there (#100). @@ -299,7 +303,7 @@ impl Sim { let grid = Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 }; let mut items = Vec::new(); // A smart raid goes for the radars too (a few strikers each); the others pick as they always did. - let radar_jobs = if smart { self.radar_strikes(&order.kinds, &picture) } else { Vec::new() }; + let radar_jobs = if smart { self.radar_strikes(&order.kinds, picture, leads) } else { Vec::new() }; let mut index = 0usize; for (group, &(kind, count)) in order.kinds.iter().enumerate() { let spec = kind.spec(); @@ -329,8 +333,8 @@ impl Sim { let confidence = picture .iter() .find(|c| c.id == id) - .map(|c| c.confidence(self.tick)) - .or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(self.tick))); + .map(|c| c.confidence(knowledge.tick)) + .or_else(|| leads.iter().find(|c| c.id == id).map(|c| c.confidence(knowledge.tick))); d.intent = if job.is_some() { ew::Intent::Sead } else { ew::Intent::Plan }; d.aim = confidence.map_or_else(|| ew::Aim::point(self.tick), |c| ew::Aim::unit(id, self.tick, c)); } else { @@ -352,6 +356,7 @@ impl Sim { } self.plan = Some(Plan { grid, + knowledge, prices: HashMap::new(), routes: HashMap::new(), items, @@ -465,7 +470,7 @@ impl Sim { None => { if !plan.prices.contains_key(&kind) { let heights = (!plan.heights.is_empty()).then_some(plan.heights.as_slice()); - let (p, cost) = self.price_grid_on(&plan.grid, kind, heights); + let (p, cost) = self.price_grid_on(&plan.grid, kind, heights, &plan.knowledge); work += cost; plan.prices.insert(kind, p); } @@ -546,6 +551,13 @@ impl Sim { self.plan.as_ref().map(|p| p.items.iter().map(|i| (i.d.aim.unit, i.d.intent)).collect()).unwrap_or_default() } + /// The plan's grid, land, knowledge version and the prices worked out so far (#146; tests). + #[cfg(test)] + pub(super) fn plan_pricing(&self) -> Option<(Grid, Vec, ew::KnowledgeSnapshot, HashMap>)> { + let p = self.plan.as_ref()?; + Some((p.grid, p.heights.clone(), p.knowledge.clone(), p.prices.clone())) + } + /// A drone ready to fly from `from`, not yet in the sky. pub(super) fn make_drone(&mut self, kind: DroneKind, from: DVec3, dir: DVec3, target: DVec3) -> Drone { let id = self.id(); @@ -591,10 +603,11 @@ impl Sim { /// the last observed place and id for those that go for one. Each radar /// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid. /// Only contacts the picture still trusts: a doubtful one (aged, never re-seen) is not worth a missile. - pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact]) -> Vec> { + pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], picture: &[ew::Contact], leads: &[recon::Mark]) -> Vec> { // Exact disclosure contacts and recon marks of radars, best first. The order is the // observed role, freshness and quality -- never the id: a hidden station has no id, - // and a big observed radar is worth more than a modest one (#135). + // and a big observed radar is worth more than a modest one (#135). Both lists are the + // order's own knowledge version, not a later picture (#146). let now = self.tick; let mut radars: Vec<(u8, u64, u32, DVec3)> = picture .iter() @@ -607,7 +620,7 @@ impl Sim { }; (seen * 10 + 3, c.tick, c.id, c.at) }) - .chain(self.recon.leads(now).into_iter().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area))) + .chain(leads.iter().copied().filter(|m| m.category == recon::Category::Radar && m.confidence(now) >= ew::Confidence::Probable).map(|m| (m.priority(now), m.observed, m.id, m.area))) .collect(); radars.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.2.cmp(&b.2))); let radars: Vec<(u32, DVec3)> = radars.into_iter().map(|(_, _, id, at)| (id, at)).collect(); @@ -681,25 +694,28 @@ impl Sim { /// system sees it there (its radar's reach for it, the land) and can shoot it. #[cfg(test)] pub(super) fn price_grid(&self, grid: &Grid, kind: DroneKind) -> (Vec, usize) { - self.price_grid_on(grid, kind, None) + self.price_grid_on(grid, kind, None, &self.knowledge_now()) } - /// The same over the picture this moment holds: a smart plan's own prices are priced on the - /// picture the plan was ordered with (#127). Later observations change nothing here. - pub(super) fn price_grid_on(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>) -> (Vec, usize) { - self.price_grid_known(grid, kind, land, &self.picture_of_defences()) + /// The same over a knowledge version given explicitly: a smart plan's prices are priced on the + /// snapshot the plan was ordered with (#127, #146), whenever the budget reaches this kind. + /// Later observations change nothing here. + pub(super) fn price_grid_on(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, knowledge: &ew::KnowledgeSnapshot) -> (Vec, usize) { + self.price_grid_known(grid, kind, land, knowledge) } - /// The same over a picture of the defences: a retarget is priced on the picture its target was - /// chosen from, so the jobs of one adaptive tick do not each see a different world (#127). Every + /// The same over a snapshot of the defences: a retarget is priced on the knowledge its target was + /// chosen from, so the jobs of one adaptive tick do not each see a different world (#127), and a + /// job reached on a later tick still ages its contacts at its own version's tick (#146). Every /// capability read here is the contact's published kind and the contact's own observations — /// never the unit's actual switch settings, damage, roles, link health or magazine. - pub(super) fn price_grid_known(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, picture: &[ew::Contact]) -> (Vec, usize) { + pub(super) fn price_grid_known(&self, grid: &Grid, kind: DroneKind, land: Option<&[f32]>, knowledge: &ew::KnowledgeSnapshot) -> (Vec, usize) { let mut cost = 0; let spec = kind.spec(); let height = spec.clearance.max(6.0); let n = grid.size; - let now = self.tick; + let now = knowledge.tick; + let picture = &knowledge.contacts; let mut prices = vec![1.0f32; (n * n) as usize]; // Known jamming stations: drones that navigate by satellite keep away. if kind.jammable() { @@ -1067,23 +1083,23 @@ mod tests { sim.sams.push(radar); let kinds = [(DroneKind::Kh22, 8)]; let none = Vec::new(); - assert!(sim.radar_strikes(&kinds, &none).iter().all(Option::is_none)); + assert!(sim.radar_strikes(&kinds, &none, &[]).iter().all(Option::is_none)); sim.tick = 20; sim.intel.observe(&sim.sams[0], sim.tick, ew::Seen::Emission); // The truth moving after the fix is not an observation: the strike goes to the seen place. sim.sams[0].pos = DVec3::new(900.0, 70.0, 900.0); sim.tick = 40; let picture = sim.picture_of_defences(); - let jobs = sim.radar_strikes(&kinds, &picture); + let jobs = sim.radar_strikes(&kinds, &picture, &[]); assert_eq!(jobs.iter().flatten().count(), 2); assert!(jobs.iter().flatten().all(|job| *job == (old, 1))); // An old contact is not worth a strike either. sim.tick = 3021; let picture = sim.picture_of_defences(); - assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none), "a doubtful contact was struck"); + assert!(sim.radar_strikes(&kinds, &picture, &[]).iter().all(Option::is_none), "a doubtful contact was struck"); sim.tick = 6020; let picture = sim.picture_of_defences(); - assert!(sim.radar_strikes(&kinds, &picture).iter().all(Option::is_none)); + assert!(sim.radar_strikes(&kinds, &picture, &[]).iter().all(Option::is_none)); } #[test] diff --git a/airdef-mod/src/sim/recon.rs b/airdef-mod/src/sim/recon.rs index fde327f..766ae9d 100644 --- a/airdef-mod/src/sim/recon.rs +++ b/airdef-mod/src/sim/recon.rs @@ -1176,7 +1176,7 @@ mod tests { d.aim = ew::Aim::unit(mark.id, sim.tick, mark.confidence(sim.tick)); let drone = d.id; sim.drones.push(d); - sim.retargets.push_back(ew::RouteJob::restored(900, drone, mark.area, mark.id, sim.tick, ew::Intent::Plan, std::sync::Arc::new(Vec::new()), None)); + sim.retargets.push_back(ew::RouteJob::restored(900, drone, mark.area, mark.id, sim.tick, ew::Intent::Plan, std::sync::Arc::new(ew::KnowledgeSnapshot::empty(sim.tick)), None)); let text = sim.air_text().expect("a recon flight is durable"); assert!(text.contains("airrecon"), "the recon section was not written"); let mut back = Sim::new(6); @@ -1307,7 +1307,7 @@ mod tests { sim.recon.report(look(2, battery::RadarRole::Engagement), 1000); let id_of = |truth: u32| sim.recon.truth.iter().find_map(|(id, t)| (*t == truth).then_some(*id)).unwrap(); let (modest, big) = (id_of(1), id_of(2)); - let jobs = sim.radar_strikes(&[(DroneKind::Kh22, 8)], &[]); + let jobs = sim.radar_strikes(&[(DroneKind::Kh22, 8)], &[], &sim.recon.leads(sim.tick)); let first: Vec = jobs.iter().flatten().map(|(_, id)| *id).collect(); assert_eq!(first.first().copied(), Some(big), "seed {seed}: a modest station was offered the first striker"); assert!(first.contains(&modest), "seed {seed}: the modest station got no striker at all"); diff --git a/airdef-mod/src/sim/regress.rs b/airdef-mod/src/sim/regress.rs index 11db96e..258c54d 100644 --- a/airdef-mod/src/sim/regress.rs +++ b/airdef-mod/src/sim/regress.rs @@ -382,14 +382,14 @@ fn same_relief_different_known_snapshots_do_not_share_prices_or_routes() { destroyed: None, launches: 0, }; - let known_all = std::sync::Arc::new(vec![contact(threat, threat_at), contact(target, aim)]); - let known_target = std::sync::Arc::new(vec![contact(target, aim)]); + let known_all = std::sync::Arc::new(super::ew::KnowledgeSnapshot { tick: 1, contacts: vec![contact(threat, threat_at), contact(target, aim)], marks: Vec::new() }); + let known_target = std::sync::Arc::new(super::ew::KnowledgeSnapshot { tick: 2, contacts: vec![contact(target, aim)], marks: Vec::new() }); // The picture holds both units: a job's unit is alive only while the picture believes in it. - for c in known_all.iter() { + for c in known_all.contacts.iter() { sim.intel.note(c.id, c.kind, c.at, true, 0, super::ew::Seen::Emission); } - let mut add = |known: std::sync::Arc>, version: u64| -> u32 { + let mut add = |known: std::sync::Arc, version: u64| -> u32 { let mut d = sim.make_drone(DroneKind::Kh22, start, DVec3::X, aim); d.smart = true; d.err = DVec3::ZERO; @@ -420,6 +420,137 @@ fn same_relief_different_known_snapshots_do_not_share_prices_or_routes() { assert_eq!(r1, r3, "jobs of one knowledge version did not reuse their route cache"); } +// #146: one Smart order, two kinds, the land answers starved while the plan waits and a visible +// contact disclosed mid-wait: every kind's targets and routes stay on the snapshot the order was +// chosen with, not on whatever the picture holds when the budget reaches that kind. The plan is +// driven by `plan_step` alone so no adaptive tick retargets the queue before it is read. +#[test] +fn smart_order_routes_every_kind_on_the_snapshot_it_was_ordered_with() { + use super::sites::testland::{serve, Land}; + // What the order's drones end up with: kind, aim and route, in the plan's own order. + fn fly(extra_at_order: bool, extra_mid_wait: bool) -> Vec<(DroneKind, DVec3, Vec)> { + let mut sim = Sim::new(146); + let radar = sim.id(); + sim.sams.push(Sam::new(radar, SamKind::Radar, DVec3::new(120.0, 70.0, 0.0), 0.0)); + sim.intel.observe(&sim.sams[0], sim.tick, ew::Seen::Emission); + sim.targets.push(DVec3::new(0.0, 70.0, 0.0)); + sim.target_health.push(100.0); + 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); + } + let mut ground = Ground::default(); + let land = Land(|_, _| 64); + let mut out = Out::default(); + let order = RaidOrder { kinds: vec![(DroneKind::Shahed, 6), (DroneKind::Geran3, 4)], approach: Approach::AllSides, dist: 300.0, aim: Aim::Smart }; + let at = sim.tick; + assert_eq!(sim.order_raid(&order, &sim.targets.clone(), &mut out), 10); + let (_, _, knowledge, _) = sim.plan_pricing().expect("the order was not accepted"); + assert_eq!(knowledge.tick, at, "the plan does not keep the tick it was ordered at"); + assert!(knowledge.contacts.iter().any(|c| c.id == radar)); + assert_eq!(knowledge.contacts.iter().any(|c| c.id == extra), extra_at_order); + let (mut starved, mut added) = (0, !extra_mid_wait); + for _ in 0..600 { + if !sim.planning() { + break; + } + let mapping = sim.plan_pricing().is_some_and(|(_, h, _, _)| !h.is_empty()); + if mapping && !added { + // The game tells of no land for a while: the plan waits for the relief, and the + // contact arrives while it waits, after the targets were already chosen. + if starved < 10 { + sim.plan_step(Some(&mut ground), &mut out); + sim.tick += 1; + starved += 1; + continue; + } + sim.intel.note(extra, SamKind::S400, extra_at, true, sim.tick, ew::Seen::Emission); + added = true; + } + serve(&mut ground, &land, sim.tick); + sim.plan_step(Some(&mut ground), &mut out); + sim.tick += 1; + } + assert!(!sim.planning(), "the plan never finished"); + assert!(added, "the mid-wait contact was never disclosed"); + if extra_mid_wait { + assert!(sim.picture_of_defences().iter().any(|c| c.id == extra), "the disclosure did not reach the picture"); + } + 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. + 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"); +} + +// #146: two jobs of one knowledge version, worked out on different ticks across the boundary +// where the current picture would stop believing a contact's own sensor, price the same world. +// An explicitly new retarget, with a fresh report of its own, may use the new report. +#[test] +fn retarget_jobs_of_one_version_age_at_their_own_tick() { + let mut sim = Sim::new(146); + let flat = flat_relief(); + let start = DVec3::new(-1000.0, 100.0, 0.0); + 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)); + let target = sim.id(); + sim.sams.push(Sam::new(target, SamKind::S400, 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 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); + 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. + let mut d = sim.make_drone(DroneKind::Geran3, start, DVec3::X, aim); + d.smart = true; + d.err = DVec3::ZERO; + d.target = aim; + d.route = vec![start, aim]; + // Past the switch cap: the adaptive tick may not turn these drones onto anything else. + d.aim = ew::Aim { unit: target, since: version, switches: ew::SWITCH_CAP, confidence: Some(ew::Confidence::Confirmed) }; + let id = d.id; + sim.queue.push((0, d)); + sim.retargets.push_back(ew::RouteJob::for_test(id, aim, target, version, known, Some(flat.clone()))); + id + } + let first = add(&mut sim, version, known.clone(), target, start, aim, &flat); + sim.tick = version; + sim.adapt(); + assert!(sim.retargets.is_empty(), "the first job was not finished"); + let r1 = retarget_route(&sim, first); + // The same version and the same snapshot, reached one tick past the boundary. + let second = add(&mut sim, version, known.clone(), target, start, aim, &flat); + sim.tick = version + 1; + sim.adapt(); + assert!(sim.retargets.is_empty(), "the second job was not finished"); + 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); + 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(); + assert!(sim.retargets.is_empty(), "the new job was not finished"); + let r3 = retarget_route(&sim, third); + assert_eq!(r1, r3, "an explicitly new retarget could not use the new report"); + // A new version without a new report: its own tick is past the boundary, so it no longer + // believes the threat's radar and flies the direct line. This is what the same-version job + // above must NOT do, and what makes the two versions distinguishable. + let stale = std::sync::Arc::new(ew::KnowledgeSnapshot { tick: version + 1, contacts: known.contacts.clone(), marks: Vec::new() }); + let fourth = add(&mut sim, version + 1, stale, target, start, aim, &flat); + sim.adapt(); + assert!(sim.retargets.is_empty(), "the fourth job was not finished"); + let r4 = retarget_route(&sim, fourth); + assert_ne!(r1, r4, "the test does not distinguish believing the threat from not believing it"); + assert_ne!(r3, r4, "a new version without a new report kept the old belief"); +} + // #31: a big cache of fresh columns is not scanned on every answer #[test] fn big_ground_cache_is_swept_rarely() {