Record unit decisions and show their replay moments (#153)

This commit is contained in:
2026-12-02 00:01:03 +03:00
parent b882dc3c2b
commit dfb306edd7
7 changed files with 513 additions and 16 deletions
+257
View File
@@ -0,0 +1,257 @@
//! Recorded choices at the firing checks, on the same clock as the replay.
use super::{ClassEst, Sam, battery::Measure, memory, why};
use std::collections::{HashMap, VecDeque};
const MAX_ENTRIES: usize = 4096;
const MAX_STREAMS: usize = 1024;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Channel {
Unit,
Gun,
Launcher,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Block {
Hold,
Moving,
Reload,
Empty,
NoSelection,
WaitingForTerrain,
Terrain,
Aim,
Opening,
BusyWithGroundShot,
Cooldown,
GunFault,
LauncherFault,
NoLock,
Range,
}
impl Block {
pub(super) fn gun(bits: u8) -> Self {
if bits & why::RELOADING != 0 {
Self::Reload
} else if bits & why::NO_ROUNDS != 0 {
Self::Empty
} else if bits & why::JAMMED != 0 {
Self::GunFault
} else if bits & why::NO_LOCK != 0 {
Self::NoLock
} else if bits & (why::NOT_AIMED | why::AIM_ERROR) != 0 {
Self::Aim
} else if bits & why::OUT_OF_RANGE != 0 {
Self::Range
} else {
Self::Cooldown
}
}
pub(super) fn launcher(bits: u8) -> Self {
if bits & why::RELOADING != 0 {
Self::Reload
} else if bits & why::NO_ROUNDS != 0 {
Self::Empty
} else if bits & why::LAUNCHER_DOWN != 0 {
Self::LauncherFault
} else {
Self::Cooldown
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Outcome {
Held(Block),
Burst,
BurstMissed,
BurstHit,
Launched(u32),
Intercepted(u32),
InterceptorMissed(u32),
InterceptorEnded(u32),
}
/// What the unit itself measured or received, with IDs fixed at recording time.
#[derive(Clone, Copy, Debug)]
pub struct Mark {
pub source: u32,
pub age: u16,
pub own: bool,
pub quality: u8,
pub product: Measure,
pub class: ClassEst,
}
#[derive(Clone, Copy, Debug)]
pub struct Entry {
pub at: u32,
pub unit: u32,
pub target: Option<u32>,
pub channel: Channel,
pub outcome: Outcome,
pub mark: Option<Mark>,
}
#[derive(Default)]
pub struct History {
entries: VecDeque<Entry>,
last: HashMap<(u32, Channel), (Option<u32>, Outcome)>,
truncated: bool,
}
impl History {
pub fn entries(&self) -> impl DoubleEndedIterator<Item = &Entry> {
self.entries.iter()
}
pub fn truncated(&self) -> bool {
self.truncated
}
pub(super) fn resume(&mut self, unit: u32, channel: Channel) {
self.last.remove(&(unit, channel));
}
pub(super) fn note(
&mut self,
at: u32,
now: u64,
sam: &Sam,
channel: Channel,
target: Option<u32>,
outcome: Outcome,
) {
let key = (sam.id, channel);
if matches!(outcome, Outcome::Held(_)) {
if self.last.get(&key) == Some(&(target, outcome)) {
return;
}
if self.last.len() == MAX_STREAMS && !self.last.contains_key(&key) {
self.truncated = true;
return;
}
self.last.insert(key, (target, outcome));
} else {
self.last.remove(&key);
}
let mark = target.and_then(|id| sam.track(id)).map(|track| Mark {
source: track.source,
age: track.age(now).min(u64::from(u16::MAX)) as u16,
own: track.source == sam.id,
quality: track.quality,
product: track.product,
class: track.class,
});
// A refusal is for a public track, or the absence of a selected track.
// An actual shot still identifies the track it was fired at.
let target = if matches!(outcome, Outcome::Held(_)) && mark.is_none() {
None
} else {
target
};
self.push(Entry {
at,
unit: sam.id,
target,
channel,
outcome,
mark,
});
}
pub(super) fn outcome(
&mut self,
at: u32,
unit: u32,
target: u32,
channel: Channel,
outcome: Outcome,
) {
self.push(Entry {
at,
unit,
target: Some(target),
channel,
outcome,
mark: None,
});
}
fn push(&mut self, entry: Entry) {
if self.entries.len() == MAX_ENTRIES {
self.entries.pop_front();
self.truncated = true;
}
self.entries.push_back(entry);
}
pub(super) fn close(&mut self) {
self.last = HashMap::new();
}
pub(super) fn bytes(&self) -> usize {
memory::vecdeque_bytes(&self.entries)
+ memory::map_bytes(
self.last.capacity(),
size_of::<((u32, Channel), (Option<u32>, Outcome))>(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::SamKind;
use glam::DVec3;
#[test]
fn deduplicates_continuous_refusals_and_preserves_a_known_miss() {
let sam = Sam::new(16, SamKind::S400, DVec3::ZERO, 0.0);
let mut history = History::default();
for at in 0..100 {
history.note(
at,
u64::from(at),
&sam,
Channel::Unit,
None,
Outcome::Held(Block::Hold),
);
}
history.note(
100,
100,
&sam,
Channel::Launcher,
Some(93),
Outcome::Launched(94),
);
history.outcome(
130,
sam.id,
93,
Channel::Launcher,
Outcome::InterceptorMissed(94),
);
let entries: Vec<_> = history.entries().collect();
assert_eq!(entries.len(), 3);
assert_eq!(entries[0].at, 0);
assert_eq!(entries[1].outcome, Outcome::Launched(94));
assert_eq!(entries[2].outcome, Outcome::InterceptorMissed(94));
}
#[test]
fn a_full_journal_keeps_recent_entries_and_marks_the_gap() {
let mut history = History::default();
for at in 0..MAX_ENTRIES as u32 + 3 {
history.outcome(at, 16, 93, Channel::Gun, Outcome::BurstHit);
}
assert!(history.truncated());
assert_eq!(history.entries().count(), MAX_ENTRIES);
assert_eq!(history.entries().next().unwrap().at, 3);
}
}
+78 -6
View File
@@ -41,6 +41,7 @@ pub mod outcome;
mod units;
pub mod why;
mod breakthrough;
pub mod decision;
pub mod world;
pub mod memory;
pub use memory::MemoryReport;
@@ -2432,6 +2433,7 @@ impl Sim {
// ------------------------------------------------ air defence
fn step_sams(&mut self, ground: &mut Ground, out: &mut Out) {
use decision::{Block, Channel, Outcome as Decision};
for sam in &mut self.sams {
sam.sync_tube_cells();
if (self.hold && !sam.preparing.is_some_and(|p| p.ground)) || !sam.alive() || sam.moving() || sam.reloading > 0 || sam.part(Part::Launcher) <= 0.0 {
@@ -2443,6 +2445,12 @@ impl Sim {
for i in 0..self.sams.len() {
if self.sams[i].alive() && !self.sams[i].moving() && self.sams[i].kind != SamKind::Optical {
self.sams[i].state = SamState::Hold;
if let Some(rec) = &mut self.rec
&& self.sams[i].kind.armed()
&& !self.sams[i].tracks.is_empty()
{
rec.decisions.note(rec.len, self.tick, &self.sams[i], Channel::Unit, None, Decision::Held(Block::Hold));
}
}
self.draw_sam(i, out);
}
@@ -2492,6 +2500,12 @@ impl Sim {
}
}
if self.sams[i].moving() {
if let Some(rec) = &mut self.rec
&& self.sams[i].kind.armed()
&& !self.sams[i].tracks.is_empty()
{
rec.decisions.note(rec.len, self.tick, &self.sams[i], Channel::Unit, None, Decision::Held(Block::Moving));
}
continue;
}
if !self.sams[i].kind.armed() {
@@ -2631,6 +2645,20 @@ impl Sim {
} else {
SamState::Search
};
if let Some(rec) = &mut self.rec {
rec.decisions.resume(sam.id, Channel::Gun);
rec.decisions.resume(sam.id, Channel::Launcher);
if !sam.tracks.is_empty() {
let block = match sam.state {
SamState::Reload => Block::Reload,
SamState::Waiting => Block::Empty,
_ => Block::NoSelection,
};
rec.decisions.note(rec.len, now, sam, Channel::Unit, None, Decision::Held(block));
} else {
rec.decisions.resume(sam.id, Channel::Unit);
}
}
// Nothing to fire at: the mount watches the nearest track of its classes (by the class
// the network estimates, the unknown among them: a reaction a turn shorter), else it
// goes back to the rest position, under the drive's limits like any other turn.
@@ -2652,6 +2680,15 @@ impl Sim {
}
continue;
};
if let Some(rec) = &mut self.rec {
rec.decisions.resume(sam.id, Channel::Unit);
if sam.target.is_none() {
rec.decisions.resume(sam.id, Channel::Launcher);
}
if sam.gun_target.is_none() {
rec.decisions.resume(sam.id, Channel::Gun);
}
}
let (mount, _) = sam.mount();
let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell);
let (aim_id, aim_pos, aim_vel) = aim;
@@ -2733,17 +2770,26 @@ impl Sim {
// The aim point is the track's forecast: the farther it is from the truth, the more shells miss.
let off = est.distance(t.pos);
let p = gun.p * sam.gun_fit() * dark / (t.kind.spec().stealth * (1.0 + (off / 8.0).powi(2))) * (1.0 - dist / (gun.range * 1.3)).max(0.35);
if self.rng.chance(p) {
let hit = self.rng.chance(p);
if let Some(rec) = &mut self.rec {
let outcome = if hit { Decision::Burst } else { Decision::BurstMissed };
rec.decisions.note(rec.len, now, sam, Channel::Gun, Some(gt), outcome);
}
if hit {
gun_hits.push((gt, sam.id));
} else {
out.particles("minecraft:crit", t.pos, 1.2, DVec3::ZERO, 0.2, 4);
}
} else if let Some(rec) = &mut self.rec {
rec.decisions.note(rec.len, now, sam, Channel::Gun, Some(gt), Decision::Held(Block::gun(blocks)));
}
}
}
// Missiles.
if let (Some(load), Some(mt)) = (&spec.missile, sam.target) {
let ready = why::missile_blocks(sam) == 0 && !sam.preparing.is_some_and(|p| p.ground);
let blocks = why::missile_blocks(sam);
let busy = sam.preparing.is_some_and(|p| p.ground);
let ready = blocks == 0 && !busy;
// The missile turns after its boost, but the launcher must point near the target.
let t = sam.track(mt).filter(|_| drone_at.contains_key(&mt)).map(|tr| tr.est(now));
let aligned = why::missile_aligned(spec.family, sam.yaw, mount, t, aim_id, mt, aim_error);
@@ -2773,13 +2819,23 @@ impl Sim {
} else {
0
};
let fire = land == 0 && ready && aligned && sam.prepare_tube(mt, now);
if !fire && let Some(rec) = &mut self.rec {
let block = if land == terrain::WAIT { Block::WaitingForTerrain }
else if land != 0 { Block::Terrain }
else if blocks != 0 { Block::launcher(blocks) }
else if busy { Block::BusyWithGroundShot }
else if !aligned { Block::Aim }
else { Block::Opening };
rec.decisions.note(rec.len, now, sam, Channel::Launcher, Some(mt), Decision::Held(block));
}
if land == terrain::WAIT {
// The land under the shot is not known yet: it waits.
} else if land != 0 {
sam.cancel_prepare();
retarget(&mut missile_on, Some(mt), None);
sam.target = None;
} else if ready && aligned && sam.prepare_tube(mt, now) {
} else if fire {
sam.eject_cell(n);
// Past its normal reach: a long shot, and the next waits.
if sam.kind.far_shooter() && t.is_some_and(|t| t.distance(sam.pos) >= load.max) {
@@ -2822,6 +2878,11 @@ impl Sim {
.map(|tr| Fix { pos: tr.pos, vel: tr.vel, tick: tr.tick, seeker: false });
let spec = kind.spec();
let id = self.id();
if let Some(rec) = &mut self.rec
&& let Some(unit) = self.sams.iter().find(|s| s.id == sam)
{
rec.decisions.note(rec.len, self.tick, unit, Channel::Launcher, Some(target), Decision::Launched(id));
}
let v0 = if spec.cold > 0 { spec.eject } else { 0.8 };
self.breakthrough_launch(target);
self.missiles.push(Missile { id, kind, pos: muzzle, vel: dir * v0, target, sam, age: 0, hold: 0, fix, seen: 0 });
@@ -2847,8 +2908,11 @@ impl Sim {
self.fx.push((id, Fx::Tracer { pos, vel, life }));
}
for (t, by) in gun_hits {
if let Some(i) = self.drones.iter().position(|d| d.id == t) {
let _ = self.shoot_down(i, by, None, ground, out);
if let Some(i) = self.drones.iter().position(|d| d.id == t)
&& self.shoot_down(i, by, None, ground, out).is_some()
&& let Some(rec) = &mut self.rec
{
rec.decisions.outcome(rec.len, by, t, Channel::Gun, Decision::BurstHit);
}
}
for i in 0..self.sams.len() {
@@ -3088,11 +3152,12 @@ impl Sim {
self.fireball(m.pos, 2.5 * m.kind.spec().scale, 7);
out.particles("minecraft:explosion", m.pos, 0.4, DVec3::ZERO, 0.0, 3);
out.sound(sound::BLAST_AIR, m.pos, 1.0, 1.25);
let mut hit = false;
if let Some(t) = target.and_then(|t| self.drones.iter().position(|d| d.id == t)) {
self.drones[t].engaged = self.drones[t].engaged.saturating_sub(1);
if kill {
let (at, closing) = impacts[&mid];
let _ = self.shoot_down_by(t, sam, Some(mid), Impact::missile(m.kind, at, closing), ground, out);
hit = self.shoot_down_by(t, sam, Some(mid), Impact::missile(m.kind, at, closing), ground, out).is_some();
}
}
// A missile that lost its target frees it for others.
@@ -3101,6 +3166,13 @@ impl Sim {
{
d.engaged = d.engaged.saturating_sub(1);
}
if let Some(rec) = &mut self.rec {
use decision::{Channel, Outcome};
let outcome = if hit { Outcome::Intercepted(mid) }
else if !kill && impacts.contains_key(&mid) { Outcome::InterceptorMissed(mid) }
else { Outcome::InterceptorEnded(mid) };
rec.decisions.outcome(rec.len, sam, m.target, Channel::Launcher, outcome);
}
}
}
for m in &self.missiles {
+6 -2
View File
@@ -168,6 +168,7 @@ impl Recording {
index: HashMap::new(),
events: Vec::new(),
scene: None,
decisions: decision::History::default(),
tally: Tally::default(),
sams: Vec::new(),
objects: Vec::new(),
@@ -584,6 +585,7 @@ pub struct Recording {
pub events: Vec<Event>,
/// None is the legacy event/track-only format.
pub scene: Option<SceneJournal>,
pub decisions: decision::History,
/// The failures counted during the raid.
pub tally: Tally,
/// The systems and objects as they stood: (id, kind, where).
@@ -834,6 +836,7 @@ impl Recording {
index: HashMap::new(),
events: Vec::new(),
scene: Some(SceneJournal::default()),
decisions: decision::History::default(),
tally: Tally::default(),
sams: sim.sams.iter().map(|s| (s.id, s.kind, s.pos)).collect(),
objects: sim.targets.clone(),
@@ -859,6 +862,7 @@ impl Recording {
/// `Sim` calls this once the raid is over; its own events are always appended in time order
/// (ties in the order they happened), so the index is only built for a journal altered later.
pub fn close(&mut self) {
self.decisions.close();
self.closed = true;
if self.events.windows(2).all(|w| w[0].at <= w[1].at) {
self.time_order = None;
@@ -976,7 +980,7 @@ impl Recording {
let tracks = vec_bytes(&self.tracks)
+ self.tracks.iter().map(|t| vec_bytes(&t.points)).sum::<usize>()
+ map_bytes(self.index.len(), std::mem::size_of::<u32>() + std::mem::size_of::<usize>());
let mut journal = vec_bytes(&self.events);
let mut journal = vec_bytes(&self.events) + self.decisions.bytes();
if let Some(scene) = &self.scene {
journal += vec_bytes(&scene.events)
+ map_bytes(scene.tracks.len(), std::mem::size_of::<(u32, u32)>() + std::mem::size_of::<(bool, bool, DVec3)>())
@@ -1517,7 +1521,7 @@ impl Sim {
}
done.len = done.len.saturating_sub(done.quiet.saturating_sub(40));
done.close();
if !done.events.is_empty() || done.scene.as_ref().is_some_and(|s| !s.events.is_empty()) {
if !done.events.is_empty() || done.scene.as_ref().is_some_and(|s| !s.events.is_empty()) || done.decisions.entries().next().is_some() {
self.replays.push(done);
if self.replays.len() > KEPT {
self.replays.remove(0);