diff --git a/airdef-mod/src/sim/mod.rs b/airdef-mod/src/sim/mod.rs index 84b04ef..e1d651f 100644 --- a/airdef-mod/src/sim/mod.rs +++ b/airdef-mod/src/sim/mod.rs @@ -1416,6 +1416,8 @@ pub struct Sim { /// The next blast's id (separate from `next`, so the other units' ids stay as they were). blast_seq: u32, next: u32, + /// The optical probe sequence: a ready post is served oldest-probe first (fair queue, #138). + optical_seq: u64, /// The combat randomness: what is rolled for aim, hits, damage and raids. Drawing, sound and camera never /// spend it (#85). pub rng: Rng, @@ -1529,6 +1531,7 @@ impl Sim { blasts: Vec::new(), blast_seq: 0, next: 1, + optical_seq: 0, rng: Rng::new(seed), vis: Rng::new(seed ^ 0x5DEE_CE66_D1CE_4E5B), fx_next: 0, diff --git a/airdef-mod/src/sim/optical.rs b/airdef-mod/src/sim/optical.rs index e5bfd3b..ccee26b 100644 --- a/airdef-mod/src/sim/optical.rs +++ b/airdef-mod/src/sim/optical.rs @@ -16,6 +16,12 @@ //! mode in this first version. Weather/fog is not in the simulation API yet, so only the game's own //! day/night state and the world geometry are used here. //! +//! An automatic contact is kept while it is within the optics' own reach; after a few failed probes +//! it is let go and not picked again for a while, so a visible alternative can be tried without the +//! post thrashing between hopeless contacts. A player's explicit command is different: it waits +//! until the player changes it, and the status says so. Ready posts are served oldest-probe first, +//! so posts whose phases coincide all get their turn under the same per-tick probe budget. +//! //! #133 owns the shared class-estimate contract. The observation stays an independent //! [`OpticalObservation`] — never a [`Track`] — and the explicit adapter [`Sim::apply_optical_classes`] //! feeds its [`OpticalClassEstimate`] into the class of the network's existing tracks through @@ -48,6 +54,14 @@ const LOCAL_CANDIDATES: usize = 8; const TERRAIN_SAMPLES: usize = 6; /// A relayed track older than this is not worth turning the head for. const CUE_MAX_AGE: u64 = 120; +/// Consecutive failed probes before an automatic contact is let go. +const MISS_LIMIT: u32 = 3; +/// Unknown world geometry is a wait, not a verdict: it takes longer to let a contact go. +const UNKNOWN_LIMIT: u32 = 8; +/// Ticks a contact let go after failures is not picked again (no constant switching). +const RETRY_AFTER: u64 = PERIOD * 20; +/// Let-go contacts remembered at once. +const AVOID_MAX: usize = 8; /// What the post is doing, in the words the map and monitor use. #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] @@ -192,6 +206,12 @@ pub struct Optical { /// The freshest relayed track: a direction to look, never a measurement and never a track. cue: Option, checks: u64, + /// Consecutive failed probes of the current automatic contact. + misses: u32, + /// Automatic contacts let go after failures: not picked again before the tick (anti-thrash). + avoid: Vec<(u32, u64)>, + /// The probe sequence number this post was last served at: the fair queue serves the oldest. + served: Option, } impl Optical { @@ -238,6 +258,7 @@ impl Optical { fn clear_activity(&mut self) { self.target = None; self.held = 0; + self.misses = 0; self.state = OpticalState::Searching; self.block = None; } @@ -245,6 +266,7 @@ impl Optical { self.target = None; self.commanded = None; self.held = 0; + self.misses = 0; self.observations = 0; self.seen = None; self.state = OpticalState::Searching; @@ -253,18 +275,42 @@ impl Optical { fn select(&mut self, id: Option) { if self.target != id { self.held = 0; - self.observations = 0; + self.misses = 0; self.seen = None; - // The old picture belongs to the old contact: it must not be read as this one's. - self.observation = None; + // The old picture belongs to the old contact: it must not be read as this one's. Letting + // the contact go (None) or picking the same one again keeps it: it is a record and ages. + if let Some(id) = id { + if !self.observation.is_some_and(|o| o.target == id) { + self.observations = 0; + self.observation = None; + } + } } self.target = id; self.block = None; self.state = if id.is_some() { OpticalState::Holding } else { OpticalState::Searching }; } + fn avoided(&self, id: u32, now: u64) -> bool { + self.avoid.iter().any(|&(other, until)| other == id && until > now) + } + /// Let an automatic contact go after its failed probes and keep it out of the next picks for a + /// while, so the post can try a visible alternative instead of thrashing on this one. + fn release(&mut self, id: u32, now: u64) { + self.target = None; + self.held = 0; + self.misses = 0; + self.state = OpticalState::Searching; + self.block = None; + self.seen = None; + self.avoid.retain(|&(_, until)| until > now); + self.avoid.push((id, now + RETRY_AFTER)); + if self.avoid.len() > AVOID_MAX { + self.avoid.remove(0); + } + } /// A short line for the panel and the monitor: status, class and uncertainty, never a model name. pub fn status_text(&self) -> String { - match self.state { + let body = match self.state { OpticalState::Searching => "ищет".into(), OpticalState::Holding => "занят: удерживает контакт".into(), OpticalState::Observing => match self.observation { @@ -275,7 +321,8 @@ impl Optical { Some(b) => format!("нет видимости: {}", b.name()), None => "нет видимости".into(), }, - } + }; + if self.commanded.is_some() { format!("по команде: {body}") } else { body } } fn report(&self, post: u32, index: usize, now: u64, night: bool) -> OpticalReport { OpticalReport { @@ -290,6 +337,7 @@ impl Optical { required: self.required(night), seen: self.seen(now).map(|(_, p)| p), checks: self.checks, + commanded: self.commanded, night, } } @@ -305,6 +353,8 @@ pub struct OpticalReport { pub state: OpticalState, pub block: Option, pub target: Option, + /// The contact the player has pinned, if any: the post waits for it until the command changes. + pub commanded: Option, pub observation: Option, pub observations: u32, pub held: u32, @@ -324,7 +374,7 @@ impl OpticalReport { format!("оптический пост №{}", self.index) } pub fn line(&self) -> String { - match self.state { + let body = match self.state { OpticalState::Searching => "ищет".into(), OpticalState::Holding => format!("занят: удерживает контакт {}/{}", self.held, self.required), OpticalState::Observing => match self.observation { @@ -340,7 +390,8 @@ impl OpticalReport { Some(b) => format!("нет видимости: {}", b.name()), None => "нет видимости".into(), }, - } + }; + if self.commanded.is_some() { format!("по команде: {body}") } else { body } } /// The observation's age, if it has one; an old observation only ages. pub fn age(&self, now: u64) -> Option { @@ -377,6 +428,7 @@ impl Sim { if sam.optical.target != target { sam.optical.target = None; sam.optical.held = 0; + sam.optical.misses = 0; sam.optical.observations = 0; sam.optical.seen = None; // An explicit switch drops the old contact's picture; it was never this contact's. @@ -387,33 +439,39 @@ impl Sim { true } - /// The post's own pick: a manual/network cue first, then its narrow near sector. At most one contact. + /// The post's own pick: a manual command, the contact it already holds, a cue within reach or + /// the near sector, and only then a far cue that merely points the head. At most one contact. fn optical_target(&self, i: usize, now: u64, alive: &std::collections::HashSet) -> Option { let sam = &self.sams[i]; let optical = &sam.optical; let alive = |id: u32| alive.contains(&id); + // A player's command keeps its contact until the command changes, reachable or not. if let Some(id) = optical.commanded() { if alive(id) { return Some(id); } } - if let Some(id) = optical.target() { - if let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive()) { - if d.pos.distance(sam.pos) <= CUE_RANGE { - return Some(id); - } - } + // Keep the current contact while it is still within the optics' own reach: observations + // accumulate instead of the post hopping between equally good contacts. + if let Some(id) = optical.target() + && alive(id) + && !optical.avoided(id, now) + && let Some(d) = self.drones.iter().find(|d| d.id == id && d.alive()) + && d.pos.distance(sam.pos) <= RANGE + { + return Some(id); } - // The network's freshest cue: the post measures it itself, the relay only points the head. + // A cue within reach is a known contact: the head turns to it and the post measures it itself. if let Some(t) = optical.cue() && t.age(now) <= CUE_MAX_AGE && alive(t.id) - && t.est(now).distance(sam.pos) <= CUE_RANGE + && !optical.avoided(t.id, now) + && t.est(now).distance(sam.pos) <= RANGE { return Some(t.id); } - // Nothing cued: search a narrow near sector, nearest first, comparing no more than a few. - // The sector is the head's (`dish`, which turns while it searches), not the base's heading. + // Search a narrow near sector, nearest first, comparing no more than a few. The sector is + // the head's (`dish`, which turns while it searches), not the base's heading. let mut local: Vec<(f64, u32)> = self .drones .iter() @@ -421,7 +479,7 @@ impl Sim { .filter_map(|d| { let rel = d.pos - sam.pos; let dist = rel.length(); - if dist > RANGE { + if dist > RANGE || optical.avoided(d.id, now) { return None; } let bearing = heading_of(rel); @@ -430,7 +488,19 @@ impl Sim { .collect(); local.sort_by(|a, b| a.0.total_cmp(&b.0)); local.truncate(LOCAL_CANDIDATES); - local.first().map(|&(_, id)| id) + if let Some(&(_, id)) = local.first() { + return Some(id); + } + // A far cue points the head but never displaces a visible local contact above. + if let Some(t) = optical.cue() + && t.age(now) <= CUE_MAX_AGE + && alive(t.id) + && !optical.avoided(t.id, now) + && t.est(now).distance(sam.pos) <= CUE_RANGE + { + return Some(t.id); + } + None } /// One tick of every optical post: age state, then spend the bounded line-of-sight budget. @@ -481,22 +551,31 @@ impl Sim { sam.dish = (sam.dish + 0.02) % TAU; } } - // Fair round-robin: a crowd of posts does not starve the last ones for ever. - let start = (now as usize) % posts.len(); + // A fair queue over the posts ready this tick: the post probed longest ago goes first, so + // posts whose phases coincide all get their turn. The per-tick probe budget still caps work. + let mut ready: Vec = posts + .iter() + .copied() + .filter(|&i| { + let sam = &self.sams[i]; + sam.alive() + && !sam.moving() + && sam.part(Part::Sensor) > 0.0 + && now % PERIOD == (sam.id / PARTS) as u64 % PERIOD + }) + .collect(); + ready.sort_by(|&a, &b| { + self.sams[a] + .optical + .served + .cmp(&self.sams[b].optical.served) + .then(self.sams[a].id.cmp(&self.sams[b].id)) + }); let mut checks = 0usize; - for k in 0..posts.len() { + for i in ready { if checks >= CHECKS_PER_TICK { break; } - let i = posts[(start + k) % posts.len()]; - // A dead, moving or blinded post spends none of the tick's probe budget. - if !self.sams[i].alive() || self.sams[i].moving() || self.sams[i].part(Part::Sensor) <= 0.0 { - continue; - } - let phase = (self.sams[i].id / PARTS) as u64 % PERIOD; - if now % PERIOD != phase { - continue; - } let Some(target) = self.optical_target(i, now, &alive) else { self.sams[i].optical.select(None); continue; @@ -516,10 +595,14 @@ impl Sim { let night = self.night; let sight = line_of_sight(ground, from, to, now, range, night); checks += 1; + self.optical_seq = self.optical_seq.wrapping_add(1); + let seq = self.optical_seq; let sam = &mut self.sams[i]; sam.optical.checks += 1; + sam.optical.served = Some(seq); match sight { Ok(()) => { + sam.optical.misses = 0; sam.optical.block = None; sam.optical.seen = Some((target, d.pos, d.vel, now)); sam.optical.held = sam.optical.held.saturating_add(1); @@ -554,11 +637,19 @@ impl Sim { sam.optical.held = 0; sam.optical.block = Some(block); sam.optical.state = OpticalState::NoSight; + // A player's pin waits for the player. An automatic contact that keeps failing + // is let go, then left out of the picks for a while so an alternative can win. + if sam.optical.commanded().is_none() { + sam.optical.misses = sam.optical.misses.saturating_add(1); + let limit = if block == SightBlock::UnknownGeometry { UNKNOWN_LIMIT } else { MISS_LIMIT }; + if sam.optical.misses >= limit { + sam.optical.release(target, now); + } + } } } // The post's own state is `OpticalState`: it never claims a fire-control track. sam.state = SamState::Search; - sam.optical.target = Some(target); } self.apply_optical_classes(); } @@ -707,7 +798,8 @@ mod tests { let post = optical_at(&mut sim, 0.0, 0.0, 0.0); flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -200.0), DVec3::new(0.5, 0.0, -0.6)); let mut ground = clear_ground(); - run(&mut sim, &mut ground, 200); + // Two night probes: beyond the reduced reach, before the post lets the contact go. + run(&mut sim, &mut ground, 2 * PERIOD); let r = sim.optical_report(post).unwrap(); assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.block, Some(SightBlock::Night)); @@ -734,11 +826,17 @@ mod tests { flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::new(0.5, 0.0, -0.6)); let mut ground = clear_ground(); ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -4), fill: world::Fill::Full }], 0); - run(&mut sim, &mut ground, 200); + run(&mut sim, &mut ground, 2 * PERIOD); let r = sim.optical_report(post).unwrap(); assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.block, Some(SightBlock::Obstacle)); assert!(r.observation.is_none()); + // With no alternative the post lets the blocked contact go after its failed probes; it does + // not sit on it for ever, and it may try again only after the retry delay. + run(&mut sim, &mut ground, MISS_LIMIT as u64 * PERIOD + 2); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.target, None); + assert_eq!(r.state, OpticalState::Searching); // The same clear land and sky, but no answered sections: unknown, not clear. let mut unknown = Sim::new(5); @@ -752,10 +850,15 @@ mod tests { } } ground.answer(cols, 0); - run(&mut unknown, &mut ground, 200); + run(&mut unknown, &mut ground, 2 * PERIOD); let r = unknown.optical_report(post).unwrap(); assert_eq!(r.block, Some(SightBlock::UnknownGeometry)); assert!(r.observation.is_none()); + // Waiting for the world is bounded too: the unknown line is not an eternal block. + run(&mut unknown, &mut ground, UNKNOWN_LIMIT as u64 * PERIOD + 2); + let r = unknown.optical_report(post).unwrap(); + assert_eq!(r.target, None); + assert_eq!(r.state, OpticalState::Searching); } // Once the view is lost, the old observation only ages: no new observation is invented. @@ -769,13 +872,20 @@ mod tests { let first = sim.optical_report(post).unwrap().observation.expect("no day observation"); let count = sim.optical_report(post).unwrap().observations; sim.night = true; + // The first night probes fail: the old picture is not refreshed. + run(&mut sim, &mut ground, 2 * PERIOD); + let mid = sim.optical_report(post).unwrap(); + assert_eq!(mid.state, OpticalState::NoSight); + assert_eq!(mid.block, Some(SightBlock::Night)); + assert_eq!(mid.observation.unwrap().tick, first.tick); + // The post lets the contact go and only rechecks it now and then; the old observation ages. run(&mut sim, &mut ground, 300); let r = sim.optical_report(post).unwrap(); let last = r.observation.expect("the old observation was thrown away"); assert_eq!(last.tick, first.tick, "a new observation was invented while the view was lost"); assert_eq!(r.observations, count); assert!(last.age(sim.tick) > 200); - assert_eq!(r.state, OpticalState::NoSight); + assert_ne!(r.state, OpticalState::Observing); } // The class comes from observable motion, never from DroneKind: two true models with the same @@ -841,12 +951,17 @@ mod tests { }); let mut ground = clear_ground(); // The cue is fresh only for its `CUE_MAX_AGE`; the contact is beyond the optics' own reach. - run(&mut sim, &mut ground, 60); + run(&mut sim, &mut ground, 2 * PERIOD); let r = sim.optical_report(post).unwrap(); assert_eq!(r.target, Some(id)); assert_eq!(r.state, OpticalState::NoSight); assert_eq!(r.block, Some(SightBlock::OutOfRange)); assert!(r.observation.is_none() && r.observations == 0, "a relayed track became a measurement"); + // A far cue may point the head, but after a few failed probes the post lets it go. + run(&mut sim, &mut ground, MISS_LIMIT as u64 * PERIOD + 2); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.target, None); + assert_eq!(r.state, OpticalState::Searching); } // A searching post turns its head: a near contact outside the base heading comes into the sector. @@ -927,12 +1042,98 @@ mod tests { run(&mut sim, &mut ground, 60); let r = sim.optical_report(post).unwrap(); assert_eq!(r.target, Some(far)); + assert_eq!(r.commanded, Some(far)); + assert!(r.line().starts_with("по команде"), "the pin is not in the status: {}", r.line()); + // A manual pin is predictable: it waits even when the contact leaves the optics' reach. + sim.drones.iter_mut().find(|d| d.id == far).unwrap().pos = DVec3::new(0.0, 95.0, -500.0); + run(&mut sim, &mut ground, 60); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.target, Some(far), "a manual pin was dropped when the contact left the reach"); + assert_eq!(r.block, Some(SightBlock::OutOfRange)); + assert!(r.line().starts_with("по команде"), "{}", r.line()); assert!(sim.assign_optical(post, Some(near))); run(&mut sim, &mut ground, 10); assert_eq!(sim.optical_report(post).unwrap().target, Some(near)); + assert!(sim.assign_optical(post, None)); + run(&mut sim, &mut ground, 10); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.commanded, None); + assert!(!r.line().contains("по команде"), "{}", r.line()); assert!(!sim.assign_optical(post, Some(u32::MAX)), "a dead contact cannot be assigned"); } + // #138: a contact that leaves the optics' reach must not keep the post for ever. The visible + // alternative is picked instead, and it is observed once the post has had its bounded probes. + #[test] + fn an_unreachable_contact_yields_to_a_visible_alternative() { + let mut sim = Sim::new(21); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + let gone = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -50.0), DVec3::ZERO); + let alt = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -90.0), DVec3::ZERO); + let mut ground = clear_ground(); + run(&mut sim, &mut ground, 30); + assert_eq!(sim.optical_report(post).unwrap().target, Some(gone), "the near contact was not picked"); + // The held contact is moved far outside the optics' own reach; the alternative stays visible. + sim.drones.iter_mut().find(|d| d.id == gone).unwrap().pos = DVec3::new(0.0, 95.0, -500.0); + run(&mut sim, &mut ground, 20); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.target, Some(alt), "the post still sat on the unreachable contact"); + assert_ne!(r.block, Some(SightBlock::OutOfRange)); + run(&mut sim, &mut ground, 200); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.target, Some(alt)); + let obs = r.observation.expect("the visible alternative was never observed"); + assert_eq!(obs.target, alt); + } + + // #138: a contact hidden behind a wall is let go after its failed probes, not held for ever, + // and the post observes the visible alternative in the same sector. + #[test] + fn a_blocked_contact_yields_to_a_visible_alternative() { + let mut sim = Sim::new(22); + let post = optical_at(&mut sim, 0.0, 0.0, 0.0); + let hidden = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(0.0, 95.0, -100.0), DVec3::ZERO); + let alt = flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(20.0, 95.0, -100.0), DVec3::ZERO); + let mut ground = clear_ground(); + // A wall on the hidden contact's line only: the alternative at x=20 clears it. + ground.world.answer(vec![world::SectionAnswer { sec: (0, 5, -6), fill: world::Fill::Full }], 0); + run(&mut sim, &mut ground, 300); + let r = sim.optical_report(post).unwrap(); + assert_eq!(r.target, Some(alt), "the post never tried the visible alternative to {hidden}"); + assert_eq!(r.state, OpticalState::Observing); + assert_eq!(r.observation.expect("no observation of the alternative").target, alt); + } + + // #138: five posts whose phases coincide must all advance under the per-tick probe budget. The + // ready queue serves the post probed longest ago first, so the fifth is not starved for ever. + #[test] + fn five_posts_in_one_phase_each_get_their_turn() { + let mut sim = Sim::new(23); + let mut posts = Vec::new(); + for k in 0..5 { + let x = k as f64 * 5.0; + let post = optical_at(&mut sim, x, 0.0, 0.0); + flat_drone(&mut sim, DroneKind::Shahed, DVec3::new(x, 95.0, -100.0), DVec3::ZERO); + posts.push(post); + // The contact consumed one id; three ordinary ids make four between deployments, so + // every post lands in the same `(id / PARTS) % PERIOD` phase. + for _ in 0..3 { + sim.id(); + } + } + assert!( + posts.iter().all(|&post| (post / PARTS) as u64 % PERIOD == (posts[0] / PARTS) as u64 % PERIOD), + "the posts do not share a phase: {posts:?}" + ); + let mut ground = clear_ground(); + run(&mut sim, &mut ground, 500); + let counts: Vec = posts.iter().map(|&p| sim.optical_report(p).unwrap().observations).collect(); + assert!(counts.iter().all(|&c| c > 0), "a post never got a probe in 500 ticks: {counts:?}"); + let min = counts.iter().copied().min().unwrap(); + let max = counts.iter().copied().max().unwrap(); + assert!(max - min <= 1, "the phase collision starved a post: {counts:?}"); + } + // A dead post neither probes nor invents an observation. #[test] fn a_dead_post_does_not_probe() {