2498 lines
116 KiB
Rust
2498 lines
116 KiB
Rust
//! Raids are recorded for their replays: every drone's and interceptor's
|
||
//! track (a point every other tick, falling wrecks included) and what
|
||
//! happened (shot down, by what; hits; systems lost; the Oreshnik's split).
|
||
//! A recording starts with the first strike drone in the sky and ends when the sky
|
||
//! has been clear a while; the last few are kept. A recon aircraft is a role of its own
|
||
//! and is not part of the strike's replay (#135).
|
||
use super::*;
|
||
|
||
/// A system's pose at a moment of a recording.
|
||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||
pub struct SamKey {
|
||
/// The recording's tick.
|
||
pub at: u32,
|
||
/// Relative to the recording's origin.
|
||
pos: [f32; 3],
|
||
heading: f32,
|
||
/// Where the launcher or turret points.
|
||
yaw: f32,
|
||
pitch: f32,
|
||
/// The antenna's turn.
|
||
dish: f32,
|
||
/// A searchlight's beam: how far it runs free (to 8 blocks), 0 when it is off.
|
||
beam: f32,
|
||
/// Hull and component health at the sampled tick.
|
||
health: f32,
|
||
parts: [f32; 6],
|
||
mode: battery::SamMode,
|
||
radar_role: battery::RadarRole,
|
||
radar_on: bool,
|
||
spent_cells: u8,
|
||
cap_cell: u8,
|
||
cap_open: f32,
|
||
/// A discrete transition or a frame of a tube cover's opening rather than a pose sample (#142):
|
||
/// decimation keeps it, within its own budget.
|
||
event: bool,
|
||
}
|
||
|
||
impl SamKey {
|
||
fn of(sam: &Sam, origin: DVec3, at: u32) -> Self {
|
||
let p = sam.pos - origin;
|
||
SamKey {
|
||
at,
|
||
pos: [p.x as f32, p.y as f32, p.z as f32],
|
||
heading: sam.heading as f32,
|
||
yaw: sam.yaw as f32,
|
||
pitch: sam.pitch as f32,
|
||
dish: sam.dish as f32,
|
||
beam: if sam.beam_on { ((sam.beam_free / 8.0).round() * 8.0).max(8.0) as f32 } else { 0.0 },
|
||
health: sam.health as f32,
|
||
parts: sam.comps.0.map(|v| v as f32),
|
||
mode: sam.mode,
|
||
radar_role: sam.radar_role,
|
||
radar_on: sam.radar_on,
|
||
spent_cells: sam.spent_cells,
|
||
cap_cell: sam.cap_cell,
|
||
cap_open: sam.cap_open,
|
||
event: false,
|
||
}
|
||
}
|
||
/// The same pose (to within what could be seen).
|
||
fn same(&self, o: &SamKey) -> bool {
|
||
let near = |a: f32, b: f32, e: f32| (a - b).abs() < e;
|
||
(0..3).all(|i| near(self.pos[i], o.pos[i], 0.01))
|
||
&& near(self.heading, o.heading, 0.002)
|
||
&& near(self.yaw, o.yaw, 0.002)
|
||
&& near(self.pitch, o.pitch, 0.002)
|
||
&& near(self.dish, o.dish, 0.002)
|
||
&& self.beam == o.beam
|
||
&& self.health == o.health
|
||
&& self.parts == o.parts
|
||
&& self.mode == o.mode && self.radar_role == o.radar_role && self.radar_on == o.radar_on
|
||
&& self.spent_cells == o.spent_cells && self.cap_cell == o.cap_cell
|
||
&& near(self.cap_open, o.cap_open, 0.001)
|
||
}
|
||
/// The states a replay reads as facts rather than as interpolated poses: which round is spent,
|
||
/// which tube the cover opens, whether the radar emits, and the mount's configuration.
|
||
fn discrete(&self) -> (battery::SamMode, battery::RadarRole, bool, u8, u8) {
|
||
(self.mode, self.radar_role, self.radar_on, self.spent_cells, self.cap_cell)
|
||
}
|
||
/// The tube cover's stage: shut, on its way open, or wide.
|
||
fn cover(&self) -> u8 { cover_stage(self.cap_open) }
|
||
}
|
||
|
||
/// The cover's stage an opening (`launch::OPEN_TICKS` long) passes through.
|
||
fn cover_stage(open: f32) -> u8 {
|
||
if open <= 0.0 { 0 } else if open < 1.0 { 1 } else { 2 }
|
||
}
|
||
|
||
/// A system through a recording: its poses (a new one only when it changed, with the
|
||
/// stillness before it marked), and when it was lost.
|
||
pub struct SamTrack {
|
||
pub id: u32,
|
||
pub kind: SamKind,
|
||
pub keys: Vec<SamKey>,
|
||
/// The recording's tick it was destroyed.
|
||
pub lost: Option<u32>,
|
||
}
|
||
|
||
/// `a` turned toward `b` by `f` the short way round.
|
||
fn turn(a: f32, b: f32, f: f32) -> f32 {
|
||
let tau = std::f32::consts::TAU;
|
||
let d = (b - a + std::f32::consts::PI).rem_euclid(tau) - std::f32::consts::PI;
|
||
a + d * f
|
||
}
|
||
|
||
impl SamTrack {
|
||
/// The pose at `t` (the recording's ticks, fractional); None before the system was first seen.
|
||
pub fn pose(&self, t: f64) -> Option<SamKey> {
|
||
let first = self.keys.first()?;
|
||
if t < first.at as f64 {
|
||
return None;
|
||
}
|
||
let i = self.keys.partition_point(|k| k.at as f64 <= t).saturating_sub(1);
|
||
let a = self.keys[i];
|
||
let Some(b) = self.keys.get(i + 1) else { return Some(a) };
|
||
let f = ((t - a.at as f64) / (b.at - a.at).max(1) as f64).clamp(0.0, 1.0) as f32;
|
||
let l = |x: f32, y: f32| x + (y - x) * f;
|
||
Some(SamKey {
|
||
at: a.at,
|
||
pos: [l(a.pos[0], b.pos[0]), l(a.pos[1], b.pos[1]), l(a.pos[2], b.pos[2])],
|
||
heading: turn(a.heading, b.heading, f),
|
||
yaw: turn(a.yaw, b.yaw, f),
|
||
pitch: l(a.pitch, b.pitch),
|
||
dish: turn(a.dish, b.dish, f),
|
||
beam: a.beam,
|
||
health: a.health,
|
||
parts: a.parts,
|
||
mode: a.mode,
|
||
radar_role: a.radar_role,
|
||
radar_on: a.radar_on,
|
||
spent_cells: a.spent_cells,
|
||
cap_cell: a.cap_cell,
|
||
cap_open: if a.cap_cell == b.cap_cell && a.spent_cells == b.spent_cells { l(a.cap_open, b.cap_open) } else { a.cap_open },
|
||
event: false,
|
||
})
|
||
}
|
||
/// The system as it stood at `t`, as a ghost to draw with the ids from `id`.
|
||
pub fn ghost(&self, origin: DVec3, t: f64, id: u32) -> Option<Sam> {
|
||
let k = self.pose(t)?;
|
||
let pos = origin + DVec3::new(k.pos[0] as f64, k.pos[1] as f64, k.pos[2] as f64);
|
||
let mut sam = Sam::new(id, self.kind, pos, k.heading as f64);
|
||
sam.yaw = k.yaw as f64;
|
||
sam.pitch = k.pitch as f64;
|
||
sam.dish = k.dish as f64;
|
||
sam.beam_on = k.beam > 0.0;
|
||
sam.beam_free = k.beam as f64;
|
||
sam.health = if self.lost.is_some_and(|l| t >= l as f64) { 0.0 } else { k.health as f64 };
|
||
sam.comps = Comps(k.parts.map(|v| v as f64));
|
||
sam.mode = k.mode;
|
||
sam.radar_role = k.radar_role;
|
||
sam.radar_on = k.radar_on;
|
||
sam.spent_cells = k.spent_cells;
|
||
sam.cap_cell = k.cap_cell;
|
||
sam.cap_open = k.cap_open;
|
||
Some(sam)
|
||
}
|
||
}
|
||
|
||
#[cfg(any(test, feature = "test-fixtures"))]
|
||
impl Recording {
|
||
/// A recording of `len` ticks with nothing in it (for the planner's tests).
|
||
pub fn blank(len: u32) -> Self {
|
||
Recording {
|
||
number: 1,
|
||
started_at: 0,
|
||
origin: DVec3::ZERO,
|
||
len,
|
||
tracks: Vec::new(),
|
||
index: HashMap::new(),
|
||
events: Vec::new(),
|
||
scene: None,
|
||
decisions: decision::History::default(),
|
||
tally: Tally::default(),
|
||
sams: Vec::new(),
|
||
objects: Vec::new(),
|
||
sam_tracks: Vec::new(),
|
||
sam_index: HashMap::new(),
|
||
sam_keys: 0,
|
||
sam_events: 0,
|
||
sam_step: STEP,
|
||
track_step: STEP,
|
||
track_points: 0,
|
||
ticks: Vec::new(),
|
||
times: Vec::new(),
|
||
quiet: 0,
|
||
closed: false,
|
||
time_order: None,
|
||
kills: Vec::new(),
|
||
hits: Vec::new(),
|
||
first_hits: Vec::new(),
|
||
}
|
||
}
|
||
/// A straight track from `from` to `to` over the ticks `first..=last` (every `STEP`).
|
||
pub fn straight(&mut self, id: u32, what: What, first: u32, last: u32, from: DVec3, to: DVec3) {
|
||
let n = ((last - first) / STEP).max(1) as usize;
|
||
let points = (0..=n).map(|k| {
|
||
let p = from.lerp(to, k as f64 / n as f64);
|
||
[p.x as f32, p.y as f32, p.z as f32]
|
||
});
|
||
self.index.insert(id, self.tracks.len());
|
||
self.tracks.push(Track { id, what, first, points: points.collect(), step: STEP, due: 0, fell: None });
|
||
self.track_points += n + 1;
|
||
}
|
||
}
|
||
|
||
impl Recording {
|
||
/// The searchlights' beams at `t` as the recording had them (position and direction from the
|
||
/// recorded poses, none for a lost light), never the live state.
|
||
pub fn beams(&self, t: f64) -> Vec<lights::Beam> {
|
||
self.sam_tracks.iter().filter_map(|st| st.ghost(self.origin, t, st.id)?.spot_beam()).collect()
|
||
}
|
||
}
|
||
|
||
/// Ticks between a track's points.
|
||
pub const STEP: u32 = 2;
|
||
/// The flight tracks' share of a recording's memory: 2 MiB of points. Beyond it the points are
|
||
/// thinned (every other kept, the ticks between them doubled) — the same flights drawn at half
|
||
/// the resolution, the #142 pattern for the systems' poses. A recording is kept four times over
|
||
/// (live and three replays) inside the 64 MiB the whole mod lives in.
|
||
const MAX_TRACK_POINTS: usize = (2 << 20) / std::mem::size_of::<[f32; 3]>();
|
||
/// The longest recording (10 minutes) and how many are kept.
|
||
const LONGEST: u32 = 12_000;
|
||
const KEPT: usize = 3;
|
||
/// SAM poses share a fixed memory budget; under pressure old poses are thinned and new ones slow down.
|
||
const MAX_SAM_KEYS: usize = 32_768;
|
||
/// Discrete transitions and cover-opening frames have their own small budget (#142): they are
|
||
/// facts a replay must not lose, but they may not spend the pose budget either. When it runs out
|
||
/// the oldest stop being critical (the newest are kept) and decimation may thin them as poses.
|
||
const MAX_SAM_EVENTS: usize = 4_096;
|
||
|
||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||
pub enum What {
|
||
Drone(DroneKind),
|
||
/// An interceptor and the system that fired it.
|
||
Missile(MissileKind, u32),
|
||
/// A counter-strike missile on its way to a launch site (#109).
|
||
Strike,
|
||
/// An explicitly profiled ground strike and its physical carrier.
|
||
StrikeCarrier(u32),
|
||
}
|
||
|
||
pub struct Track {
|
||
pub id: u32,
|
||
pub what: What,
|
||
/// The recording's tick of its first point.
|
||
pub first: u32,
|
||
/// Its points, `step` ticks apart, relative to the recording's origin.
|
||
points: Vec<[f32; 3]>,
|
||
/// Ticks between the points: `STEP`, doubled when the recording thins its points under
|
||
/// its memory budget (the #142 pattern for the systems' poses).
|
||
step: u32,
|
||
/// Sampling calls to skip before the next point (`step / STEP - 1`): the callers sample a
|
||
/// track on their own grid (the recording's ticks for flights, the flight's age for a
|
||
/// strike carrier), so the thinning counts calls, not ticks — the phase stays the track's.
|
||
due: u32,
|
||
/// When it was shot down (a drone falling from then on).
|
||
pub fell: Option<u32>,
|
||
}
|
||
|
||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||
pub enum EventKind {
|
||
/// A drone shot down: by which system (its index then), with a missile or the guns, and how it ended
|
||
/// (rolled once, live; a replay reads it and never rolls).
|
||
Kill { drone: u32, kind: DroneKind, sam: u32, sam_kind: SamKind, sam_index: usize, missile: Option<u32>, outcome: Outcome },
|
||
/// A drone's warhead went off where it aimed: at an object, a system, or the land.
|
||
Hit { drone: u32, kind: DroneKind, power: u32, object: Option<usize>, sam: Option<(SamKind, usize)> },
|
||
/// A system destroyed.
|
||
SamLost { sam: u32, kind: SamKind, index: usize },
|
||
/// The Oreshnik's bus or a block splitting.
|
||
Split { drone: u32 },
|
||
/// A drone's warhead went off against the land or a building short of its aim.
|
||
Crash { drone: u32, kind: DroneKind, power: u32 },
|
||
/// A counter-strike on a launch site landed (#101): where it landed and how it ended. Launch sites themselves are
|
||
/// not drawn in a replay.
|
||
Strike { site: u32, result: StrikeResult },
|
||
}
|
||
|
||
/// How a strike on a launch site ended.
|
||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||
pub enum StrikeResult {
|
||
Destroyed,
|
||
/// The site was stunned for a while.
|
||
Stunned,
|
||
Missed,
|
||
/// Shot down by the enemy's cover.
|
||
Intercepted,
|
||
/// Off the map: its launches ended, nothing to see.
|
||
Halted,
|
||
/// It met the land or a building short of its aim (#106): it went off there.
|
||
Blocked,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug)]
|
||
pub struct Event {
|
||
pub at: u32,
|
||
pub pos: DVec3,
|
||
pub kind: EventKind,
|
||
}
|
||
|
||
/// One step of a short after-action chain: отметка → передача → захват → пуск → исход.
|
||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||
pub enum ChainStepKind {
|
||
/// The contact first appears on the battery's picture.
|
||
Mark,
|
||
/// The plot's source changes (a relay became the battery's own measurement, or the reverse).
|
||
Handoff,
|
||
/// The battery's own radar locks it.
|
||
Lock,
|
||
/// The battery launches an interceptor at it.
|
||
Launch,
|
||
/// What came of the chain: shot down, broke through, lost.
|
||
Outcome,
|
||
}
|
||
|
||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||
pub enum ChainOutcome {
|
||
Destroyed,
|
||
/// The target reached its aim (an object, a system, the land).
|
||
Hit,
|
||
Lost,
|
||
/// The recording ended or the chain was cut short.
|
||
Unfinished,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug)]
|
||
pub struct ChainStep {
|
||
pub kind: ChainStepKind,
|
||
pub at: u32,
|
||
/// The recorded event a replay can open (the outcome), when there is one.
|
||
pub event: Option<usize>,
|
||
/// For the mark and the handoff: the plot is the battery's own measurement.
|
||
pub own: bool,
|
||
/// For a launch: the interceptor's id.
|
||
pub missile: Option<u32>,
|
||
}
|
||
|
||
/// A battery's short engagement history for one contact, built from the recording's measured
|
||
/// scene transitions and events. At most one step of each kind: no inferred beats.
|
||
#[derive(Clone, Debug)]
|
||
pub struct Chain {
|
||
pub sam: u32,
|
||
pub target: u32,
|
||
pub steps: Vec<ChainStep>,
|
||
pub outcome: ChainOutcome,
|
||
}
|
||
|
||
impl Chain {
|
||
pub fn marked_at(&self) -> u32 {
|
||
self.steps.first().map_or(0, |s| s.at)
|
||
}
|
||
|
||
pub fn step(&self, kind: ChainStepKind) -> Option<&ChainStep> {
|
||
self.steps.iter().find(|s| s.kind == kind)
|
||
}
|
||
|
||
pub fn launched(&self) -> bool {
|
||
self.step(ChainStepKind::Launch).is_some()
|
||
}
|
||
|
||
/// A contact that appeared on the picture and was never launched at.
|
||
pub fn missed(&self) -> bool {
|
||
!self.launched()
|
||
}
|
||
|
||
/// The event a replay clip opens on: the outcome when there is one, else nothing.
|
||
pub fn outcome_event(&self) -> Option<usize> {
|
||
self.step(ChainStepKind::Outcome).and_then(|s| s.event)
|
||
}
|
||
}
|
||
|
||
/// Measured scene transitions. These are facts, not inferred cinematic beats.
|
||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||
pub enum SceneKind {
|
||
MissileLaunch { missile: u32, sam: u32, target: u32, kind: MissileKind, sound: &'static str, pitch: f32 },
|
||
MotorIgnition { missile: u32, kind: MissileKind, sound: Option<&'static str> },
|
||
MotorBurnout { missile: u32, kind: MissileKind },
|
||
MotorEnergyLost { missile: u32, kind: MissileKind, speed: f64 },
|
||
TrackAcquired { sam: u32, target: u32, ever_own: bool },
|
||
TrackLost { sam: u32, target: u32 },
|
||
TrackSource { sam: u32, target: u32, ever_own: bool },
|
||
TrackLock { sam: u32, target: u32, locked: bool },
|
||
FireStarted { fire: u32, age: u32, life: u32, size: f32, quiet: bool, shown: bool, water: Option<bool> },
|
||
FireChanged { fire: u32, age: u32, life: u32, size: f32, quiet: bool, shown: bool, water: Option<bool> },
|
||
FireEnded { fire: u32 },
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||
pub struct SceneEvent {
|
||
pub at: u32,
|
||
pub pos: DVec3,
|
||
pub kind: SceneKind,
|
||
}
|
||
|
||
/// At most this many scene transitions per recording; overflow is explicitly marked. The
|
||
/// journal's share of the 64 MiB the whole mod lives in: a recording is kept four times over
|
||
/// (live and three replays), and ~24k events of ~72 B are ~1.7 MiB each.
|
||
const MAX_SCENE_EVENTS: usize = 24_576;
|
||
/// Track transitions (acquire, handoff, lock, lost) are the journal's bulk under a large raid:
|
||
/// every system's radar sees every contact, so they grow with systems × contacts, not with what
|
||
/// happened. They have their own smaller budget (~0.6 MiB); beyond it the later ones are not
|
||
/// recorded — the chains of the contacts that came first stay whole, and the launches, fires and
|
||
/// outcomes (the facts a replay reads) keep the rest of the journal.
|
||
const MAX_SCENE_TRACK_EVENTS: usize = 8_192;
|
||
|
||
#[derive(Default)]
|
||
pub struct SceneJournal {
|
||
events: Vec<SceneEvent>,
|
||
pub truncated: bool,
|
||
/// How many of the events are track transitions (their own budget, `MAX_SCENE_TRACK_EVENTS`).
|
||
track_events: usize,
|
||
tracks: HashMap<(u32, u32), (bool, bool, DVec3)>,
|
||
fires: HashMap<u32, (DVec3, u32, f32, bool, bool, Option<bool>)>,
|
||
fire_events: Vec<usize>,
|
||
launches: HashMap<u32, usize>,
|
||
ignitions: HashMap<u32, usize>,
|
||
burnouts: HashMap<u32, usize>,
|
||
}
|
||
|
||
impl SceneJournal {
|
||
pub fn track_limit_reached(&self) -> bool {
|
||
self.track_events >= MAX_SCENE_TRACK_EVENTS
|
||
}
|
||
|
||
/// Read-only transitions in chronological order.
|
||
pub fn events(&self) -> &[SceneEvent] { &self.events }
|
||
|
||
/// The transitions at the recording's ticks `lo..hi` (fractional), in the order they
|
||
/// happened: the same set the full journal filter gave (`lo <= at < hi`). The journal is
|
||
/// only ever appended to with the recording's growing tick, so its order is the time order.
|
||
pub fn events_between(&self, lo: f64, hi: f64) -> &[SceneEvent] {
|
||
let start = self.events.partition_point(|e| (e.at as f64) < lo);
|
||
let end = self.events.partition_point(|e| (e.at as f64) < hi);
|
||
#[cfg(feature = "bench-counters")]
|
||
scanned((end.saturating_sub(start)) as u64);
|
||
&self.events[start..end.max(start)]
|
||
}
|
||
|
||
#[cfg(feature = "test-fixtures")]
|
||
pub fn fixture_push(&mut self, event: SceneEvent) { self.push(event); }
|
||
|
||
fn push(&mut self, event: SceneEvent) {
|
||
debug_assert!(self.events.last().is_none_or(|last| last.at <= event.at), "scene events are kept in time order");
|
||
if self.events.len() >= MAX_SCENE_EVENTS { self.truncated = true; return; }
|
||
if matches!(event.kind, SceneKind::TrackAcquired { .. } | SceneKind::TrackLost { .. } | SceneKind::TrackSource { .. } | SceneKind::TrackLock { .. }) {
|
||
if self.track_events >= MAX_SCENE_TRACK_EVENTS { return; }
|
||
self.track_events += 1;
|
||
}
|
||
let index = self.events.len();
|
||
match event.kind {
|
||
SceneKind::MissileLaunch { missile, .. } => { self.launches.insert(missile, index); }
|
||
SceneKind::MotorIgnition { missile, .. } => { self.ignitions.insert(missile, index); }
|
||
SceneKind::MotorBurnout { missile, .. } => { self.burnouts.insert(missile, index); }
|
||
SceneKind::FireStarted { .. } | SceneKind::FireChanged { .. } | SceneKind::FireEnded { .. } => self.fire_events.push(index),
|
||
_ => {}
|
||
}
|
||
self.events.push(event);
|
||
}
|
||
}
|
||
|
||
/// The events of a recording at a time range, each with its index in the journal, in the order
|
||
/// they are read by time: the journal's own order (every recording `Sim` makes appends events
|
||
/// with the growing tick, ties in the order they happened), or the stable index built when a
|
||
/// journal closed out of order.
|
||
pub struct EventRange<'a> {
|
||
events: &'a [Event],
|
||
order: Option<&'a [u32]>,
|
||
range: std::ops::Range<usize>,
|
||
}
|
||
|
||
impl<'a> Iterator for EventRange<'a> {
|
||
type Item = (usize, &'a Event);
|
||
fn next(&mut self) -> Option<Self::Item> {
|
||
let i = self.range.next()?;
|
||
let j = self.order.map_or(i, |order| order[i] as usize);
|
||
#[cfg(feature = "bench-counters")]
|
||
scanned(1);
|
||
Some((j, &self.events[j]))
|
||
}
|
||
fn size_hint(&self) -> (usize, Option<usize>) { self.range.size_hint() }
|
||
}
|
||
|
||
impl ExactSizeIterator for EventRange<'_> {}
|
||
|
||
/// Whether a tick is before the range's lower bound.
|
||
fn before(at: f64, lo: std::ops::Bound<f64>) -> bool {
|
||
match lo {
|
||
std::ops::Bound::Included(x) => at < x,
|
||
std::ops::Bound::Excluded(x) => at <= x,
|
||
std::ops::Bound::Unbounded => false,
|
||
}
|
||
}
|
||
|
||
/// Whether a tick is at or before the range's upper bound.
|
||
fn up_to(at: f64, hi: std::ops::Bound<f64>) -> bool {
|
||
match hi {
|
||
std::ops::Bound::Included(x) => at <= x,
|
||
std::ops::Bound::Excluded(x) => at < x,
|
||
std::ops::Bound::Unbounded => true,
|
||
}
|
||
}
|
||
|
||
#[cfg(feature = "bench-counters")]
|
||
static SCANNED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||
|
||
/// Counts the events a time-range read hands out (the replay benchmark's scan count).
|
||
#[cfg(feature = "bench-counters")]
|
||
fn scanned(n: u64) {
|
||
SCANNED.fetch_add(n, std::sync::atomic::Ordering::Relaxed);
|
||
}
|
||
|
||
/// The events the time-range reads handed out since the last call, and a fresh count
|
||
/// (`bench-counters` builds only; 0 and nothing counted otherwise).
|
||
#[cfg(feature = "bench-counters")]
|
||
pub fn scanned_events() -> u64 {
|
||
SCANNED.swap(0, std::sync::atomic::Ordering::Relaxed)
|
||
}
|
||
|
||
/// Whether the scan counters are built in (see `scanned_events`).
|
||
#[cfg(feature = "bench-counters")]
|
||
pub const fn scan_counters() -> bool { true }
|
||
|
||
#[cfg(not(feature = "bench-counters"))]
|
||
pub fn scanned_events() -> u64 { 0 }
|
||
|
||
#[cfg(not(feature = "bench-counters"))]
|
||
pub const fn scan_counters() -> bool { false }
|
||
|
||
/// Why interceptors and systems failed, as far as it was counted: only these are known.
|
||
#[derive(Clone, Copy, Default, PartialEq, Debug)]
|
||
pub struct Tally {
|
||
/// Interceptors that reached their fuse and did not kill (the hit chance failed).
|
||
pub missed: u32,
|
||
/// Interceptors whose life ran out with the target still flying.
|
||
pub expired: u32,
|
||
/// Interceptors whose post-burn speed fell below their guidance threshold.
|
||
pub energy_lost: u32,
|
||
/// Interceptors whose target was gone (shot down by another, or lost) before they arrived.
|
||
pub orphaned: u32,
|
||
/// Times a system lost the track of the target it held, which was still in the sky.
|
||
pub tracks_lost: u32,
|
||
/// Times a system ran dry and began waiting for a reload truck.
|
||
pub ammo_waits: u32,
|
||
/// Interceptors lost against the land or a building on their way.
|
||
pub blocked: u32,
|
||
/// Interceptors that blew up in the air short of land they could not climb over.
|
||
pub scrubbed: u32,
|
||
}
|
||
|
||
impl Tally {
|
||
pub fn since(self, start: Tally) -> Tally {
|
||
Tally {
|
||
missed: self.missed.saturating_sub(start.missed),
|
||
expired: self.expired.saturating_sub(start.expired),
|
||
energy_lost: self.energy_lost.saturating_sub(start.energy_lost),
|
||
orphaned: self.orphaned.saturating_sub(start.orphaned),
|
||
tracks_lost: self.tracks_lost.saturating_sub(start.tracks_lost),
|
||
ammo_waits: self.ammo_waits.saturating_sub(start.ammo_waits),
|
||
blocked: self.blocked.saturating_sub(start.blocked),
|
||
scrubbed: self.scrubbed.saturating_sub(start.scrubbed),
|
||
}
|
||
}
|
||
/// The non-zero counts as a line, or nothing.
|
||
pub fn text(&self) -> String {
|
||
let parts: Vec<String> = [
|
||
(self.missed, "промахов по взрывателю"),
|
||
(self.expired, "ракет выработали ресурс"),
|
||
(self.energy_lost, "ракет потеряли скорость после выгорания"),
|
||
(self.orphaned, "ракет остались без цели"),
|
||
(self.tracks_lost, "потерь трека"),
|
||
(self.ammo_waits, "ожиданий БК"),
|
||
(self.blocked, "ракет разбились о препятствие"),
|
||
(self.scrubbed, "ракет самоуничтожились у рельефа"),
|
||
]
|
||
.into_iter()
|
||
.filter(|p| p.0 > 0)
|
||
.map(|p| format!("{} {}", p.0, p.1))
|
||
.collect();
|
||
parts.join(", ")
|
||
}
|
||
}
|
||
|
||
pub struct Recording {
|
||
/// Which raid of the session (1, 2, …).
|
||
pub number: u32,
|
||
pub started_at: u64,
|
||
pub origin: DVec3,
|
||
/// Its length in ticks.
|
||
pub len: u32,
|
||
pub tracks: Vec<Track>,
|
||
index: HashMap<u32, usize>,
|
||
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).
|
||
pub sams: Vec<(u32, SamKind, DVec3)>,
|
||
pub objects: Vec<DVec3>,
|
||
/// Every system's poses through the raid (the drawing of a replay: where it stood, which way
|
||
/// it pointed, whether it was still whole).
|
||
pub sam_tracks: Vec<SamTrack>,
|
||
sam_index: HashMap<u32, usize>,
|
||
sam_keys: usize,
|
||
/// How many of `sam_keys` are critical transitions (#142).
|
||
sam_events: usize,
|
||
sam_step: u32,
|
||
/// Ticks between the flight tracks' points now (doubled when they are thinned), and how
|
||
/// many points they hold together (`MAX_TRACK_POINTS`).
|
||
track_step: u32,
|
||
track_points: usize,
|
||
/// The game's tick number as sampled with the clock: (recording tick, game tick). A replay
|
||
/// shows the world's blocks as of this time.
|
||
ticks: Vec<(u32, u64)>,
|
||
/// The world clock's time of day as (recording tick, day ticks), sampled on every
|
||
/// `TIME_STEP`-th tick the clock was known: replays show the sky of the raid, not the current
|
||
/// one. A tick the clock was unknown has no sample (a gap), so a late start or a lost clock
|
||
/// never shifts later samples; empty when the clock was never known.
|
||
times: Vec<(u32, u64)>,
|
||
/// Ticks the sky has been clear.
|
||
quiet: u32,
|
||
/// Whether `close` settled the answers read by time (a recording served to a replay has).
|
||
closed: bool,
|
||
/// The event journal read by time when its own order cannot be trusted: a stable index into
|
||
/// `events`, built when the recording closed. `None` when the journal itself is in time order
|
||
/// (every recording `Sim` made), which is the usual case and needs no index.
|
||
time_order: Option<Vec<u32>>,
|
||
/// The kills and the hits, in time order (indices into `events`): the map's running counts.
|
||
kills: Vec<u32>,
|
||
hits: Vec<u32>,
|
||
/// For each object, the first event that hit it (an index into `events`).
|
||
first_hits: Vec<Option<u32>>,
|
||
}
|
||
|
||
/// Ticks between the recording's clock samples.
|
||
const TIME_STEP: u32 = 20;
|
||
|
||
impl Track {
|
||
/// Ticks between its points (`STEP` unless the recording thinned them under its budget).
|
||
pub fn step(&self) -> u32 {
|
||
self.step
|
||
}
|
||
/// How many points it holds (the memory diagnostics read it).
|
||
pub fn points_len(&self) -> usize {
|
||
self.points.len()
|
||
}
|
||
/// Where it was at `t` (the recording's ticks, fractional), if it was.
|
||
pub fn at(&self, origin: DVec3, t: f64) -> Option<DVec3> {
|
||
let k = (t - self.first as f64) / self.step as f64;
|
||
if k < 0.0 || self.points.is_empty() || k > (self.points.len() - 1) as f64 {
|
||
return None;
|
||
}
|
||
let i = (k.floor() as usize).min(self.points.len() - 1);
|
||
let j = (i + 1).min(self.points.len() - 1);
|
||
let f = k - i as f64;
|
||
let p = |q: [f32; 3]| DVec3::new(q[0] as f64, q[1] as f64, q[2] as f64);
|
||
Some(origin + p(self.points[i]).lerp(p(self.points[j]), f))
|
||
}
|
||
/// Which way it was flying at `t`.
|
||
pub fn dir(&self, origin: DVec3, t: f64) -> DVec3 {
|
||
let a = self.at(origin, t - STEP as f64).or_else(|| self.at(origin, t));
|
||
let b = self.at(origin, t + STEP as f64).or_else(|| self.at(origin, t));
|
||
match (a, b) {
|
||
(Some(a), Some(b)) => (b - a).normalize_or(DVec3::NEG_Z),
|
||
_ => DVec3::NEG_Z,
|
||
}
|
||
}
|
||
/// Its `i`-th point (every `step` ticks from `first`), if it has one.
|
||
pub fn sample(&self, origin: DVec3, i: usize) -> Option<DVec3> {
|
||
self.points.get(i).map(|q| origin + DVec3::new(q[0] as f64, q[1] as f64, q[2] as f64))
|
||
}
|
||
/// The tick of its last point.
|
||
pub fn last(&self) -> u32 {
|
||
self.first + (self.points.len().max(1) as u32 - 1) * self.step
|
||
}
|
||
/// Its points, every `every`-th, up to tick `t`.
|
||
pub fn path(&self, origin: DVec3, every: usize, t: f64) -> Vec<DVec3> {
|
||
let p = |q: &[f32; 3]| origin + DVec3::new(q[0] as f64, q[1] as f64, q[2] as f64);
|
||
let upto = ((t - self.first as f64) / self.step as f64).floor();
|
||
if upto < 0.0 {
|
||
return Vec::new();
|
||
}
|
||
let upto = (upto as usize).min(self.points.len().saturating_sub(1));
|
||
let mut out: Vec<DVec3> = self.points[..=upto].iter().step_by(every.max(1)).map(p).collect();
|
||
if upto % every.max(1) != 0 {
|
||
out.push(p(&self.points[upto]));
|
||
}
|
||
out
|
||
}
|
||
}
|
||
|
||
/// A fire as a replay shows it: what the events lit and kept alight, merged as the live fires are.
|
||
#[derive(Clone, Copy, Debug)]
|
||
pub struct ReplayFire {
|
||
pub at: DVec3,
|
||
/// The recording's tick it was lit.
|
||
pub start: u32,
|
||
pub life: u32,
|
||
pub size: f32,
|
||
/// Age already accumulated before recording began.
|
||
pub age_offset: u32,
|
||
pub quiet: bool,
|
||
pub shown: bool,
|
||
pub water: Option<bool>,
|
||
/// The event that lit it (the models' ids).
|
||
pub key: usize,
|
||
}
|
||
|
||
/// The look of an interception by the drone's warhead: (fireball radius, ticks it burns, loudness).
|
||
/// A bare decoy pops; a big warhead lights the sky. The same in the live raid and its replay.
|
||
pub fn kill_look(kind: DroneKind) -> (f32, u32, f32) {
|
||
let (size, life, gain, _) = outcome::look(kind, Outcome::DisabledFalling);
|
||
(size, life, gain)
|
||
}
|
||
|
||
/// The fire a strike's end leaves (0: none): the wreck of a site burns long, a crater a while.
|
||
pub fn strike_power(result: StrikeResult) -> u32 {
|
||
match result {
|
||
StrikeResult::Destroyed => 3,
|
||
StrikeResult::Stunned => 2,
|
||
StrikeResult::Missed | StrikeResult::Blocked => 1,
|
||
StrikeResult::Intercepted | StrikeResult::Halted => 0,
|
||
}
|
||
}
|
||
|
||
/// The longest a blast burns, ticks: the biggest warhead's `SIZE`/`LIFE` (`blast_spec`), the bound
|
||
/// the by-time read of a replay's blasts uses.
|
||
const MAX_BLAST_LIFE: u32 = 26 * 9;
|
||
/// How long a recording's smoke billows are kept alive past their event, ticks (`replay_smoke_blasts`).
|
||
const SMOKE_WINDOW: f64 = 900.0;
|
||
|
||
/// A blast's look for an event: (fireball radius, ticks it burns). The live blasts use the same.
|
||
pub fn blast_spec(kind: EventKind) -> (f32, u32) {
|
||
const SIZE: [f32; 5] = [2.5, 4.5, 7.0, 10.0, 13.0];
|
||
const LIFE: [u32; 5] = [11, 11, 18, 22, 26];
|
||
match kind {
|
||
EventKind::Kill { kind, outcome, .. } => {
|
||
let (size, life, _, _) = outcome::look(kind, outcome);
|
||
(size, life)
|
||
}
|
||
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
|
||
let p = (power as usize).min(4);
|
||
(SIZE[p], LIFE[p] * 9)
|
||
}
|
||
EventKind::SamLost { .. } => (8.0, 18 * 9),
|
||
EventKind::Split { .. } => (2.0, 7 * 9),
|
||
EventKind::Strike { result, .. } => match result {
|
||
StrikeResult::Destroyed => (SIZE[4], LIFE[4] * 9),
|
||
StrikeResult::Stunned | StrikeResult::Missed | StrikeResult::Blocked => (SIZE[3], LIFE[3] * 9),
|
||
StrikeResult::Intercepted => (SIZE[0], LIFE[0] * 9),
|
||
StrikeResult::Halted => (0.0, 0),
|
||
},
|
||
}
|
||
}
|
||
|
||
/// The blasts of the recording's events burning at `t` (its ticks, fractional): the same
|
||
/// `Blast`s the live simulation keeps, with `start` in the recording's ticks and the event's
|
||
/// own id range. A pure function of `t`, so a seek or a pause shows the same frame.
|
||
pub fn replay_blasts(rec: &Recording, t: f64) -> Vec<Blast> {
|
||
replay_blasts_from_events(rec, t, false)
|
||
}
|
||
|
||
/// Recorded smoke billows persist after the short visual blast expires. Keep the same event
|
||
/// classification and geometry within the bounded 900-tick smoke window.
|
||
pub fn replay_smoke_blasts(rec: &Recording, t: f64) -> Vec<Blast> {
|
||
replay_blasts_from_events(rec, t, true)
|
||
}
|
||
|
||
fn replay_blasts_from_events(rec: &Recording, t: f64, keep_expired: bool) -> Vec<Blast> {
|
||
// Only the events whose blast or smoke can still be alight at `t` are read: a window back
|
||
// from now, not the whole journal.
|
||
let events = if keep_expired {
|
||
rec.events_span(t - SMOKE_WINDOW, t)
|
||
} else {
|
||
rec.events_window(t - MAX_BLAST_LIFE as f64, t)
|
||
};
|
||
events
|
||
.filter_map(|(k, e)| {
|
||
let (size, life) = blast_spec(e.kind);
|
||
let age = t - e.at as f64;
|
||
(if keep_expired { (0.0..=SMOKE_WINDOW).contains(&age) } else { (0.0..life as f64).contains(&age) })
|
||
.then_some(Blast { id: 0x4000_0000 | k as u32, at: e.pos, size, start: e.at as u64, life })
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// The fires burning at `t` in the recording: events within 6 blocks of a fire still burning
|
||
/// feed it (the greater size, the longer life), as `Sim::ignite` does; those after it died light
|
||
/// a new one. A pure function of `t`.
|
||
pub fn replay_fires(rec: &Recording, t: f64) -> Vec<ReplayFire> {
|
||
if let Some(scene) = rec.scene.as_ref().filter(|s| !s.truncated) {
|
||
let mut active: HashMap<u32, ReplayFire> = HashMap::new();
|
||
// The fire transitions up to `t` (the journal and its fire indices are in time order).
|
||
let end = scene.fire_events.partition_point(|&i| (scene.events[i].at as f64) <= t);
|
||
#[cfg(feature = "bench-counters")]
|
||
scanned(end as u64);
|
||
for &index in &scene.fire_events[..end] {
|
||
let e = &scene.events[index];
|
||
match e.kind {
|
||
SceneKind::FireStarted { fire, age, life, size, quiet, shown, water }
|
||
| SceneKind::FireChanged { fire, age, life, size, quiet, shown, water } => {
|
||
active.insert(fire, ReplayFire { at: e.pos, start: e.at.saturating_sub(age), age_offset: age.saturating_sub(e.at), life, size, quiet, shown, water, key: fire as usize });
|
||
}
|
||
SceneKind::FireEnded { fire } => { active.remove(&fire); }
|
||
_ => {}
|
||
}
|
||
}
|
||
let mut fires: Vec<_> = active.into_values().filter(|f| t - f.start as f64 + (f.age_offset as f64) < f.life as f64).collect();
|
||
fires.sort_by_key(|f| f.key);
|
||
return fires;
|
||
}
|
||
let mut fires: Vec<ReplayFire> = Vec::new();
|
||
for (k, e) in rec.events_until(t) {
|
||
let power = match e.kind {
|
||
EventKind::Crash { power, .. } => power,
|
||
EventKind::Hit { power, .. } => power.max(1),
|
||
EventKind::SamLost { .. } => 2,
|
||
EventKind::Strike { result, .. } => strike_power(result),
|
||
_ => continue,
|
||
};
|
||
let (size, life) = (fires::size_for(power), fires::life_for(power));
|
||
let alive = |f: &ReplayFire| e.at < f.start + f.life;
|
||
if let Some(f) = fires.iter_mut().find(|f| alive(f) && f.at.distance(e.pos) < 6.0) {
|
||
f.size = f.size.max(size);
|
||
f.life = f.life.max(e.at - f.start + life);
|
||
} else {
|
||
fires.push(ReplayFire { at: e.pos, start: e.at, life, size, age_offset: 0, quiet: false, shown: true, water: None, key: k });
|
||
}
|
||
}
|
||
fires.retain(|f| t < (f.start + f.life) as f64);
|
||
fires
|
||
}
|
||
|
||
impl Recording {
|
||
fn new(number: u32, sim: &Sim) -> Self {
|
||
let origin = sim.targets.first().copied().or_else(|| sim.sams.first().map(|s| s.pos)).unwrap_or(DVec3::ZERO);
|
||
Recording {
|
||
number,
|
||
started_at: sim.tick,
|
||
origin: origin.floor(),
|
||
len: 0,
|
||
tracks: Vec::new(),
|
||
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(),
|
||
sam_tracks: Vec::new(),
|
||
sam_index: HashMap::new(),
|
||
sam_keys: 0,
|
||
sam_events: 0,
|
||
sam_step: STEP,
|
||
track_step: STEP,
|
||
track_points: 0,
|
||
ticks: Vec::new(),
|
||
times: Vec::new(),
|
||
quiet: 0,
|
||
closed: false,
|
||
time_order: None,
|
||
kills: Vec::new(),
|
||
hits: Vec::new(),
|
||
first_hits: Vec::new(),
|
||
}
|
||
}
|
||
/// Settles what a finished recording answers by time: the map's running counts, each
|
||
/// object's first hit, and a stable time index when the journal itself is not in time order.
|
||
/// `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;
|
||
} else {
|
||
let mut order: Vec<u32> = (0..self.events.len() as u32).collect();
|
||
order.sort_by_key(|&i| self.events[i as usize].at);
|
||
self.time_order = Some(order);
|
||
}
|
||
let mut first: Vec<Option<u32>> = vec![None; self.objects.len()];
|
||
let mut kills = Vec::new();
|
||
let mut hits = Vec::new();
|
||
{
|
||
let events = &self.events;
|
||
let mut note = |i: usize, e: &Event| match e.kind {
|
||
EventKind::Kill { .. } => kills.push(i as u32),
|
||
EventKind::Hit { object, .. } => {
|
||
hits.push(i as u32);
|
||
if let Some(o) = object
|
||
&& let Some(slot) = first.get_mut(o)
|
||
&& slot.is_none_or(|j| events[j as usize].at > e.at)
|
||
{
|
||
*slot = Some(i as u32);
|
||
}
|
||
}
|
||
_ => {}
|
||
};
|
||
match &self.time_order {
|
||
None => events.iter().enumerate().for_each(|(i, e)| note(i, e)),
|
||
Some(order) => order.iter().for_each(|&i| {
|
||
let i = i as usize;
|
||
note(i, &events[i]);
|
||
}),
|
||
}
|
||
}
|
||
self.kills = kills;
|
||
self.hits = hits;
|
||
self.first_hits = first;
|
||
}
|
||
|
||
/// The events at the recording's ticks `lo..hi` (fractional), in the order they happened:
|
||
/// the same set and order the full journal filter gave (`lo <= at < hi`).
|
||
pub fn events_between(&self, lo: f64, hi: f64) -> EventRange<'_> {
|
||
self.event_range(std::ops::Bound::Included(lo), std::ops::Bound::Excluded(hi))
|
||
}
|
||
|
||
/// The events up to and including the recording's tick `t`, in the order they happened.
|
||
pub fn events_until(&self, t: f64) -> EventRange<'_> {
|
||
self.event_range(std::ops::Bound::Unbounded, std::ops::Bound::Included(t))
|
||
}
|
||
|
||
/// The events with `lo < at <= hi`: a window that runs back from a moment (a blast's or a
|
||
/// piece's life).
|
||
pub(crate) fn events_window(&self, lo: f64, hi: f64) -> EventRange<'_> {
|
||
self.event_range(std::ops::Bound::Excluded(lo), std::ops::Bound::Included(hi))
|
||
}
|
||
|
||
/// The events with `lo <= at <= hi` (a window that runs back from a moment, closed at both ends).
|
||
pub(crate) fn events_span(&self, lo: f64, hi: f64) -> EventRange<'_> {
|
||
self.event_range(std::ops::Bound::Included(lo), std::ops::Bound::Included(hi))
|
||
}
|
||
|
||
fn event_range(&self, lo: std::ops::Bound<f64>, hi: std::ops::Bound<f64>) -> EventRange<'_> {
|
||
let (start, end) = match &self.time_order {
|
||
None => {
|
||
let start = self.events.partition_point(|e| before(e.at as f64, lo));
|
||
let end = self.events.partition_point(|e| up_to(e.at as f64, hi));
|
||
(start, end.max(start))
|
||
}
|
||
Some(order) => {
|
||
let start = order.partition_point(|&i| before(self.events[i as usize].at as f64, lo));
|
||
let end = order.partition_point(|&i| up_to(self.events[i as usize].at as f64, hi));
|
||
(start, end.max(start))
|
||
}
|
||
};
|
||
EventRange { events: &self.events, order: self.time_order.as_deref(), range: start..end }
|
||
}
|
||
|
||
/// The kills up to and including tick `t` (the raid map's header).
|
||
pub fn kills_until(&self, t: f64) -> usize {
|
||
if !self.closed {
|
||
return self.events.iter().filter(|e| (e.at as f64) <= t && matches!(e.kind, EventKind::Kill { .. })).count();
|
||
}
|
||
self.kills.partition_point(|&i| (self.events[i as usize].at as f64) <= t)
|
||
}
|
||
|
||
/// The hits up to and including tick `t` (the raid map's header).
|
||
pub fn hits_until(&self, t: f64) -> usize {
|
||
if !self.closed {
|
||
return self.events.iter().filter(|e| (e.at as f64) <= t && matches!(e.kind, EventKind::Hit { .. })).count();
|
||
}
|
||
self.hits.partition_point(|&i| (self.events[i as usize].at as f64) <= t)
|
||
}
|
||
|
||
/// Whether the object at `object` had been hit by tick `t` (the map's marks shrink once).
|
||
pub fn object_struck(&self, object: usize, t: f64) -> bool {
|
||
match self.first_hits.get(object) {
|
||
Some(&Some(i)) => (self.events[i as usize].at as f64) <= t,
|
||
Some(&None) => false,
|
||
// A recording that was never closed: no index, the journal answers.
|
||
None => self.events.iter().any(|e| (e.at as f64) <= t && matches!(e.kind, EventKind::Hit { object: Some(o), .. } if o == object)),
|
||
}
|
||
}
|
||
|
||
/// What the recording holds, about: tracks and their points, the event and scene
|
||
/// journals, the systems' poses and the by-time index (see `sim::memory`).
|
||
pub fn bytes(&self) -> usize {
|
||
let (tracks, journal, poses, misc) = self.memory_parts();
|
||
tracks + journal + poses + misc
|
||
}
|
||
|
||
/// The recording's memory in four parts: the flight tracks and their points, the event
|
||
/// and scene journals, the systems' poses, and the rest (index, snapshots, clocks).
|
||
pub fn memory_parts(&self) -> (usize, usize, usize, usize) {
|
||
use super::memory::{map_bytes, vec_bytes};
|
||
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) + 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)>())
|
||
+ map_bytes(scene.fires.len(), std::mem::size_of::<u32>() + std::mem::size_of::<(DVec3, u32, f32, bool, bool, Option<bool>)>())
|
||
+ vec_bytes(&scene.fire_events)
|
||
+ map_bytes(scene.launches.len(), std::mem::size_of::<u32>() + std::mem::size_of::<usize>())
|
||
+ map_bytes(scene.ignitions.len(), std::mem::size_of::<u32>() + std::mem::size_of::<usize>())
|
||
+ map_bytes(scene.burnouts.len(), std::mem::size_of::<u32>() + std::mem::size_of::<usize>());
|
||
}
|
||
let poses = vec_bytes(&self.sam_tracks)
|
||
+ self.sam_tracks.iter().map(|t| vec_bytes(&t.keys)).sum::<usize>()
|
||
+ map_bytes(self.sam_index.len(), std::mem::size_of::<u32>() + std::mem::size_of::<usize>());
|
||
let misc = vec_bytes(&self.ticks)
|
||
+ vec_bytes(&self.times)
|
||
+ vec_bytes(&self.sams)
|
||
+ vec_bytes(&self.objects)
|
||
+ self.index_bytes()
|
||
+ std::mem::size_of::<Tally>();
|
||
(tracks, journal, poses, misc)
|
||
}
|
||
|
||
/// The bytes the by-time index adds to a recording (its own journal aside).
|
||
pub fn index_bytes(&self) -> usize {
|
||
let order = self.time_order.as_ref().map_or(0, |o| o.capacity() * std::mem::size_of::<u32>());
|
||
order
|
||
+ self.kills.capacity() * std::mem::size_of::<u32>()
|
||
+ self.hits.capacity() * std::mem::size_of::<u32>()
|
||
+ self.first_hits.capacity() * std::mem::size_of::<Option<u32>>()
|
||
}
|
||
|
||
/// Halves each track's poses, keeping its critical transitions, its first and its last key (#142).
|
||
fn thin_sam_poses(&mut self) {
|
||
for track in &mut self.sam_tracks {
|
||
let len = track.keys.len();
|
||
let mut kept = 0;
|
||
let mut poses = 0;
|
||
for read in 0..len {
|
||
let key = track.keys[read];
|
||
let keep = if key.event {
|
||
true
|
||
} else {
|
||
poses += 1;
|
||
poses % 2 == 1 || read + 1 == len
|
||
};
|
||
if keep {
|
||
track.keys[kept] = key;
|
||
kept += 1;
|
||
}
|
||
}
|
||
track.keys.truncate(kept);
|
||
track.keys.shrink_to_fit();
|
||
}
|
||
self.count_sam_keys();
|
||
self.sam_step = self.sam_step.saturating_mul(2).min(LONGEST);
|
||
}
|
||
/// The transitions' budget ran out: the oldest stop being critical, so decimation may thin them
|
||
/// as poses. The newest transitions, which a replay is watched closest for, are kept (#142).
|
||
fn thin_sam_events(&mut self) {
|
||
let mut over = self.sam_events.saturating_sub(MAX_SAM_EVENTS);
|
||
while over > 0 {
|
||
let mut demoted = 0;
|
||
for track in &mut self.sam_tracks {
|
||
if over == 0 { break; }
|
||
if let Some(key) = track.keys.iter_mut().find(|key| key.event) {
|
||
key.event = false;
|
||
over -= 1;
|
||
demoted += 1;
|
||
}
|
||
}
|
||
if demoted == 0 { break; }
|
||
}
|
||
self.count_sam_keys();
|
||
}
|
||
fn count_sam_keys(&mut self) {
|
||
self.sam_keys = self.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
||
self.sam_events = self.sam_tracks.iter().map(|track| track.keys.iter().filter(|key| key.event).count()).sum();
|
||
}
|
||
|
||
/// Notes the systems' poses at the recording's tick `now`: a pose only when it changed, with
|
||
/// the pose it held marked before it so a replay doesn't glide through the stillness.
|
||
///
|
||
/// Poses are sampled on the adaptive `sam_step` grid under its own budget, but the cover's
|
||
/// opening (`launch::OPEN_TICKS`, shorter than a decimated interval) and the discrete
|
||
/// transitions — a round ejected, a tube cancelled, the radar switched, the mount's
|
||
/// configuration — are facts: they are kept on the tick they happen, in their own budget (#142).
|
||
fn note_sams(&mut self, sams: &[Sam], now: u32) {
|
||
let pose_due = now % self.sam_step == 0;
|
||
for sam in sams {
|
||
let key = SamKey::of(sam, self.origin, now);
|
||
let i = *self.sam_index.entry(sam.id).or_insert_with(|| {
|
||
self.sam_tracks.push(SamTrack { id: sam.id, kind: sam.kind, keys: Vec::new(), lost: None });
|
||
self.sam_tracks.len() - 1
|
||
});
|
||
let track = &mut self.sam_tracks[i];
|
||
let before = track.keys.len();
|
||
let Some(last) = track.keys.last().copied() else {
|
||
track.keys.push(key);
|
||
self.sam_keys += 1;
|
||
continue;
|
||
};
|
||
if last.same(&key) {
|
||
continue;
|
||
}
|
||
// The cover's opening is short: its first frame only differs from the shut pose by a
|
||
// fraction, so the stage's start is backdated to the tick it began (#142).
|
||
if last.cover() == 0 && key.cover() == 1 && now > last.at + 1 {
|
||
track.keys.push(SamKey { at: now - 1, cap_open: 0.0, event: true, ..key });
|
||
}
|
||
let transitioning = last.discrete() != key.discrete() || last.cover() != key.cover();
|
||
// Every frame of the cover's own movement is kept, so the stage's six ticks survive intact.
|
||
let moving = key.cover() == 1 && last.cap_open != key.cap_open;
|
||
if transitioning || moving {
|
||
let mut event = key;
|
||
event.event = true;
|
||
track.keys.push(event);
|
||
} else if pose_due {
|
||
if last.at + self.sam_step < now {
|
||
track.keys.push(SamKey { at: now - self.sam_step, event: false, ..last });
|
||
}
|
||
track.keys.push(key);
|
||
}
|
||
let added = track.keys.len() - before;
|
||
self.sam_keys += added;
|
||
self.sam_events += track.keys[before..].iter().filter(|key| key.event).count();
|
||
}
|
||
if self.sam_events > MAX_SAM_EVENTS {
|
||
self.thin_sam_events();
|
||
}
|
||
if self.sam_keys.saturating_sub(self.sam_events) > MAX_SAM_KEYS {
|
||
self.thin_sam_poses();
|
||
}
|
||
}
|
||
/// Actual launch, if observed during this recording. Missing is not proof of no launch:
|
||
/// the recording may have started late or the bounded journal may have filled.
|
||
pub fn missile_launch(&self, missile: u32) -> Option<&SceneEvent> {
|
||
let scene = self.scene.as_ref()?;
|
||
scene.events.get(*scene.launches.get(&missile)?)
|
||
}
|
||
|
||
/// Actual motor ignition, when it was recorded.
|
||
pub fn missile_ignition(&self, missile: u32) -> Option<&SceneEvent> {
|
||
let scene = self.scene.as_ref()?;
|
||
scene.events.get(*scene.ignitions.get(&missile)?)
|
||
}
|
||
|
||
/// Recorded ignition takes precedence; older/incomplete tracks retain their original fallback.
|
||
pub fn missile_is_lit(&self, tr: &Track, t: f64, cold: u32) -> bool {
|
||
if let Some(scene) = &self.scene
|
||
&& let Some(index) = scene.burnouts.get(&tr.id)
|
||
&& t >= scene.events[*index].at as f64 { return false; }
|
||
if let Some(event) = self.missile_ignition(tr.id) {
|
||
let burn = match tr.what { What::Missile(kind, _) => kind.burn_ticks(), _ => return false };
|
||
return t >= event.at as f64 && t < event.at as f64 + burn as f64;
|
||
}
|
||
if self.missile_launch(tr.id).is_some() && self.scene.as_ref().is_some_and(|s| !s.truncated) { return false; }
|
||
let age = t - tr.first as f64;
|
||
let burn = match tr.what { What::Missile(kind, _) => kind.burn_ticks(), _ => return false };
|
||
age > cold as f64 && age <= (cold + burn) as f64
|
||
}
|
||
|
||
fn note_tracks(&mut self, sams: &[Sam]) {
|
||
let Some(journal) = &mut self.scene else { return };
|
||
let mut current = HashMap::new();
|
||
for sam in sams {
|
||
for track in &sam.tracks {
|
||
let key = (sam.id, track.id);
|
||
let state = (track.own_tick > 0, track.locked, track.pos);
|
||
let old = journal.tracks.get(&key).copied();
|
||
if old.is_none() {
|
||
journal.push(SceneEvent { at: self.len, pos: track.pos, kind: SceneKind::TrackAcquired { sam: sam.id, target: track.id, ever_own: state.0 } });
|
||
} else if old.is_some_and(|old| old.0 != state.0) {
|
||
journal.push(SceneEvent { at: self.len, pos: track.pos, kind: SceneKind::TrackSource { sam: sam.id, target: track.id, ever_own: state.0 } });
|
||
}
|
||
if (old.is_none() && state.1) || old.is_some_and(|old| old.1 != state.1) {
|
||
journal.push(SceneEvent { at: self.len, pos: track.pos, kind: SceneKind::TrackLock { sam: sam.id, target: track.id, locked: state.1 } });
|
||
}
|
||
current.insert(key, state);
|
||
}
|
||
}
|
||
let mut lost: Vec<_> = journal.tracks.iter().filter(|(key, _)| !current.contains_key(key)).map(|(key, state)| (*key, state.2)).collect();
|
||
lost.sort_by_key(|(key, _)| *key);
|
||
for ((sam, target), pos) in lost {
|
||
journal.push(SceneEvent { at: self.len, pos, kind: SceneKind::TrackLost { sam, target } });
|
||
}
|
||
journal.tracks = current;
|
||
}
|
||
|
||
/// Sample actual fire state after the simulation update, including existing fires at start.
|
||
fn note_fires(&mut self, fires: &[fires::Fire], now: u64) {
|
||
let Some(journal) = &mut self.scene else { return };
|
||
let mut current = HashMap::new();
|
||
for fire in fires {
|
||
let state = (fire.at, fire.life, fire.size, fire.quiet, fire.shown, fire.surface_is_water());
|
||
let age = now.saturating_sub(fire.start).min(u32::MAX as u64) as u32;
|
||
let kind = match journal.fires.get(&fire.id) {
|
||
None => Some(SceneKind::FireStarted { fire: fire.id, age, life: fire.life, size: fire.size, quiet: fire.quiet, shown: fire.shown, water: state.5 }),
|
||
Some(old) if *old != state => Some(SceneKind::FireChanged { fire: fire.id, age, life: fire.life, size: fire.size, quiet: fire.quiet, shown: fire.shown, water: state.5 }),
|
||
_ => None,
|
||
};
|
||
if let Some(kind) = kind { journal.push(SceneEvent { at: self.len, pos: fire.at, kind }); }
|
||
current.insert(fire.id, state);
|
||
}
|
||
let mut ended: Vec<_> = journal.fires.iter().filter(|(id, _)| !current.contains_key(id)).map(|(id, state)| (*id, state.0)).collect();
|
||
ended.sort_by_key(|(id, _)| *id);
|
||
for (fire, pos) in ended { journal.push(SceneEvent { at: self.len, pos, kind: SceneKind::FireEnded { fire } }); }
|
||
journal.fires = current;
|
||
}
|
||
|
||
/// The game's tick at the recording's tick `t` (fractional), if it was known: the samples run
|
||
/// on at the pace of the ticks between them (a pause or a gap is a step).
|
||
pub fn world_tick(&self, t: f64) -> Option<u64> {
|
||
let t = t.max(0.0);
|
||
let i = self.ticks.partition_point(|s| s.0 as f64 <= t).checked_sub(1).or(if self.ticks.is_empty() { None } else { Some(0) })?;
|
||
let (ta, a) = self.ticks[i];
|
||
let ahead = (t - ta as f64).max(0.0);
|
||
Some(match self.ticks.get(i + 1) {
|
||
Some(&(tb, b)) if b >= a && b - a <= 2 * (tb - ta).max(1) as u64 => a + (ahead.min((tb - ta) as f64) * (b - a) as f64 / (tb - ta).max(1) as f64) as u64,
|
||
_ => a + ahead as u64,
|
||
})
|
||
}
|
||
/// The game tick the recording began at.
|
||
pub fn first_tick(&self) -> Option<u64> {
|
||
self.ticks.first().map(|s| s.1)
|
||
}
|
||
fn point(&mut self, id: u32, what: What, pos: DVec3) {
|
||
let rel = pos - self.origin;
|
||
let q = [rel.x as f32, rel.y as f32, rel.z as f32];
|
||
let now = self.len;
|
||
match self.index.get(&id) {
|
||
Some(&i) => {
|
||
let track = &mut self.tracks[i];
|
||
// The first point is exact (a birth, a muzzle); the rest fall on the track's
|
||
// own sampling grid, which the thinning doubles with the points it keeps.
|
||
if track.due > 0 {
|
||
track.due -= 1;
|
||
return;
|
||
}
|
||
track.points.push(q);
|
||
track.due = track.step / STEP - 1;
|
||
self.track_points += 1;
|
||
}
|
||
None => {
|
||
self.index.insert(id, self.tracks.len());
|
||
self.tracks.push(Track { id, what, first: now, points: vec![q], step: self.track_step, due: self.track_step / STEP - 1, fell: None });
|
||
self.track_points += 1;
|
||
}
|
||
}
|
||
if self.track_points > MAX_TRACK_POINTS {
|
||
self.thin_track_points();
|
||
}
|
||
}
|
||
/// Halves every track's points (the first stays, then every other), doubling the ticks
|
||
/// between them: the same flights drawn at half the resolution, within the budget (the
|
||
/// #142 pattern for the systems' poses). The next points fall on the new grid.
|
||
fn thin_track_points(&mut self) {
|
||
for track in &mut self.tracks {
|
||
let mut kept = 0;
|
||
for read in (0..track.points.len()).step_by(2) {
|
||
track.points[kept] = track.points[read];
|
||
kept += 1;
|
||
}
|
||
track.points.truncate(kept);
|
||
track.points.shrink_to_fit();
|
||
track.step = track.step.saturating_mul(2);
|
||
track.due = track.step / STEP - 1;
|
||
}
|
||
self.track_step = self.track_step.saturating_mul(2);
|
||
self.track_points = self.tracks.iter().map(|t| t.points.len()).sum();
|
||
}
|
||
/// The time of day (ticks, 24000 a day) the world showed at the recording's tick `t`: the
|
||
/// clock as sampled, run on between samples at the pace it ran (a jump is a step), or None
|
||
/// when the clock was not known (the replay then shows the world's own time).
|
||
pub fn day_time(&self, t: f64) -> Option<u64> {
|
||
let t = t.max(0.0);
|
||
// The last sample at or before `t`; none before the first one means unknown.
|
||
let i = self.times.partition_point(|s| s.0 as f64 <= t).checked_sub(1)?;
|
||
let (ta, a) = self.times[i];
|
||
match self.times.get(i + 1) {
|
||
// Neighbouring samples with no gap between: run on at the pace between them.
|
||
Some(&(tb, b)) if tb - ta <= TIME_STEP && b >= a && b - a <= 2 * TIME_STEP as u64 => {
|
||
let f = ((t - ta as f64) / (tb - ta) as f64).clamp(0.0, 1.0);
|
||
Some(a + ((b - a) as f64 * f) as u64)
|
||
}
|
||
_ => Some(a),
|
||
}
|
||
}
|
||
pub fn track(&self, id: u32) -> Option<&Track> {
|
||
self.index.get(&id).map(|&i| &self.tracks[i])
|
||
}
|
||
/// Sampled pose at the replay time, falling back to the old static snapshot.
|
||
pub fn sam_at(&self, id: u32, t: f64) -> Option<(SamKind, DVec3)> {
|
||
if let Some(track) = self.sam_tracks.iter().find(|s| s.id == id) {
|
||
let pose = track.pose(t)?;
|
||
return Some((track.kind, self.origin + DVec3::new(pose.pos[0] as f64, pose.pos[1] as f64, pose.pos[2] as f64)));
|
||
}
|
||
self.sam(id)
|
||
}
|
||
|
||
/// The system with this id as it stood.
|
||
pub fn sam(&self, id: u32) -> Option<(SamKind, DVec3)> {
|
||
self.sams.iter().find(|s| s.0 == id).map(|s| (s.1, s.2))
|
||
}
|
||
|
||
/// The battery's short chains through this raid, one per contact, in the order they began:
|
||
/// the picture's own transitions (mark, handoff, lock, launch) and the recorded outcome.
|
||
/// `battery` filters by system id; None keeps all. A recording with no scene journal (the
|
||
/// legacy format) has no chains, and a truncated one may miss a later step — that is marked
|
||
/// by `SceneJournal::truncated`, never guessed.
|
||
pub fn chains(&self, battery: Option<u32>) -> Vec<Chain> {
|
||
let Some(scene) = &self.scene else { return Vec::new() };
|
||
let mut chains: std::collections::BTreeMap<(u32, u32), Chain> = std::collections::BTreeMap::new();
|
||
for event in scene.events() {
|
||
match event.kind {
|
||
SceneKind::TrackAcquired { sam, target, ever_own } => {
|
||
let chain = chains.entry((sam, target)).or_insert_with(|| Chain {
|
||
sam,
|
||
target,
|
||
steps: Vec::new(),
|
||
outcome: ChainOutcome::Unfinished,
|
||
});
|
||
if chain.steps.is_empty() {
|
||
chain.steps.push(ChainStep { kind: ChainStepKind::Mark, at: event.at, event: None, own: ever_own, missile: None });
|
||
}
|
||
}
|
||
SceneKind::TrackSource { sam, target, ever_own } => {
|
||
if let Some(chain) = chains.get_mut(&(sam, target))
|
||
&& chain.step(ChainStepKind::Handoff).is_none()
|
||
{
|
||
chain.steps.push(ChainStep { kind: ChainStepKind::Handoff, at: event.at, event: None, own: ever_own, missile: None });
|
||
}
|
||
}
|
||
SceneKind::TrackLock { sam, target, locked: true } => {
|
||
if let Some(chain) = chains.get_mut(&(sam, target))
|
||
&& chain.step(ChainStepKind::Lock).is_none()
|
||
{
|
||
chain.steps.push(ChainStep { kind: ChainStepKind::Lock, at: event.at, event: None, own: true, missile: None });
|
||
}
|
||
}
|
||
SceneKind::MissileLaunch { sam, target, missile, .. } => {
|
||
if let Some(chain) = chains.get_mut(&(sam, target))
|
||
&& chain.step(ChainStepKind::Launch).is_none()
|
||
{
|
||
chain.steps.push(ChainStep { kind: ChainStepKind::Launch, at: event.at, event: None, own: true, missile: Some(missile) });
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
// The outcomes are the recorded events; a kill identifies its chain by the battery and
|
||
// the target, or by the interceptor when another battery's kill shares the target.
|
||
for (index, event) in self.events.iter().enumerate() {
|
||
match event.kind {
|
||
EventKind::Kill { drone, sam, missile, .. } => {
|
||
let mut keys = vec![(sam, drone)];
|
||
if let Some(missile) = missile {
|
||
keys.extend(chains.iter().filter(|(_, c)| c.steps.iter().any(|s| s.missile == Some(missile))).map(|(k, _)| *k));
|
||
}
|
||
for key in keys {
|
||
if let Some(chain) = chains.get_mut(&key) {
|
||
set_chain_outcome(chain, ChainOutcome::Destroyed, event.at, Some(index));
|
||
}
|
||
}
|
||
}
|
||
EventKind::Hit { drone, .. } => {
|
||
// This is the contact's outcome, whatever it hit. A system named in
|
||
// the impact is the object hit, not the observer on the chain.
|
||
for ((_, target), chain) in chains.iter_mut() {
|
||
if *target == drone {
|
||
set_chain_outcome(chain, ChainOutcome::Hit, event.at, Some(index));
|
||
}
|
||
}
|
||
}
|
||
EventKind::Crash { drone, .. } => {
|
||
for ((_, target), chain) in chains.iter_mut() {
|
||
if *target == drone && chain.outcome == ChainOutcome::Unfinished && !chain.launched() {
|
||
set_chain_outcome(chain, ChainOutcome::Lost, event.at, Some(index));
|
||
}
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
// A contact dropped without an outcome and never fired at was missed, not engaged.
|
||
for event in scene.events() {
|
||
if let SceneKind::TrackLost { sam, target } = event.kind
|
||
&& let Some(chain) = chains.get_mut(&(sam, target))
|
||
&& chain.outcome == ChainOutcome::Unfinished
|
||
&& !chain.launched()
|
||
{
|
||
set_chain_outcome(chain, ChainOutcome::Lost, event.at, None);
|
||
}
|
||
}
|
||
let mut out: Vec<Chain> = chains
|
||
.into_values()
|
||
.filter(|c| battery.is_none_or(|id| c.sam == id))
|
||
.filter(|c| !c.steps.is_empty())
|
||
.collect();
|
||
out.sort_by_key(|c| (c.marked_at(), c.sam, c.target));
|
||
out
|
||
}
|
||
}
|
||
|
||
/// Sets a chain's outcome, keeping the strongest one seen (shot down beats a hit, a hit beats a
|
||
/// lost or unfinished chain) and at most one outcome step.
|
||
fn set_chain_outcome(chain: &mut Chain, outcome: ChainOutcome, at: u32, event: Option<usize>) {
|
||
let rank = |o: ChainOutcome| match o {
|
||
ChainOutcome::Destroyed => 3,
|
||
ChainOutcome::Hit => 2,
|
||
ChainOutcome::Lost => 1,
|
||
ChainOutcome::Unfinished => 0,
|
||
};
|
||
if rank(chain.outcome) > rank(outcome) {
|
||
return;
|
||
}
|
||
chain.outcome = outcome;
|
||
chain.steps.retain(|s| s.kind != ChainStepKind::Outcome);
|
||
chain.steps.push(ChainStep { kind: ChainStepKind::Outcome, at, event, own: false, missile: None });
|
||
}
|
||
|
||
impl Sim {
|
||
/// The recording of raid `number`, while it is kept.
|
||
pub fn replay(&self, number: u32) -> Option<&Recording> {
|
||
self.replays.iter().find(|r| r.number == number)
|
||
}
|
||
/// The recording in progress, if a raid is being recorded (the memory diagnostics read it).
|
||
pub fn recording(&self) -> Option<&Recording> {
|
||
self.rec.as_ref()
|
||
}
|
||
}
|
||
|
||
impl Sim {
|
||
/// Counts something in the session's tally and in the recording going on.
|
||
pub(super) fn note(&mut self, f: impl Fn(&mut Tally)) {
|
||
f(&mut self.tally);
|
||
if let Some(r) = &mut self.rec {
|
||
f(&mut r.tally);
|
||
}
|
||
}
|
||
|
||
/// Record an actual transition without modifying gameplay or random state.
|
||
pub(super) fn scene_event(&mut self, pos: DVec3, kind: SceneKind) {
|
||
if let Some(r) = &mut self.rec {
|
||
if let Some(journal) = &mut r.scene {
|
||
journal.push(SceneEvent { at: r.len, pos, kind });
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Append an already-applied fact. This never changes the live world.
|
||
pub(super) fn record_event(&mut self, pos: DVec3, kind: EventKind) {
|
||
if let Some(r) = &mut self.rec {
|
||
let at = r.len;
|
||
if let EventKind::Kill { drone, .. } = kind
|
||
&& let Some(&i) = r.index.get(&drone)
|
||
{
|
||
r.tracks[i].fell = Some(at);
|
||
}
|
||
if let EventKind::SamLost { sam, .. } = kind
|
||
&& let Some(&i) = r.sam_index.get(&sam)
|
||
{
|
||
r.sam_tracks[i].lost.get_or_insert(at);
|
||
}
|
||
debug_assert!(r.events.last().is_none_or(|e| e.at <= at), "events are kept in time order");
|
||
r.events.push(Event { at, pos, kind });
|
||
}
|
||
}
|
||
|
||
/// Open before the combat update so transitions on the first active tick are not lost.
|
||
/// A recon aircraft neither opens nor holds a strike's recording (#135).
|
||
pub(super) fn begin_recording_if_active(&mut self) {
|
||
if self.rec.is_none()
|
||
&& (self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id)) || !self.strikes.flights.is_empty() || !self.strikes.pending.is_empty())
|
||
{
|
||
self.recordings += 1;
|
||
self.rec = Some(Recording::new(self.recordings, self));
|
||
}
|
||
}
|
||
|
||
pub(super) fn record_strike_launch(&mut self, id: u32, carrier: u32, at: DVec3) {
|
||
self.begin_recording_if_active();
|
||
if let Some(r) = &mut self.rec {
|
||
r.point(0x7100_0000 | id, What::StrikeCarrier(carrier), at);
|
||
}
|
||
}
|
||
|
||
/// Once a tick: starts a recording with the first drone or counter-strike in the air, adds the tracks' points,
|
||
/// ends it when the sky has been clear 5 s.
|
||
pub(super) fn record(&mut self) {
|
||
// Wrecks still falling (far off they fall a long while) don't keep it going. A counter-strike is a recorded
|
||
// object in its own right (#109): it holds the recording open until it lands, whatever the sky is doing.
|
||
// A recon flight is not part of the strike's replay: it neither opens nor holds a
|
||
// recording open. The strike's own drones and interceptors do (#135).
|
||
let busy = self.drones.iter().any(|d| d.alive() && !recon::is_drone_id(d.id))
|
||
|| !self.missiles.is_empty()
|
||
|| !self.queue.is_empty()
|
||
|| !self.strikes.flights.is_empty()
|
||
|| !self.strikes.pending.is_empty();
|
||
self.begin_recording_if_active();
|
||
let Some(r) = &mut self.rec else { return };
|
||
r.note_tracks(&self.sams);
|
||
r.note_fires(&self.fires.list, self.tick);
|
||
if r.len % TIME_STEP == 0 {
|
||
if let Some(dt) = self.day_time {
|
||
r.times.push((r.len, dt));
|
||
}
|
||
r.ticks.push((r.len, self.engine_tick));
|
||
}
|
||
// Poses share the adaptive grid inside; the discrete transitions and the cover's short
|
||
// opening must be seen on the tick they happen, whatever the grid (#142).
|
||
r.note_sams(&self.sams, r.len);
|
||
if r.len % STEP == 0 {
|
||
for d in self.drones.iter().filter(|d| !recon::is_drone_id(d.id)) {
|
||
r.point(d.id, What::Drone(d.kind), d.pos);
|
||
}
|
||
for m in &self.missiles {
|
||
r.point(m.id, What::Missile(m.kind, m.sam), m.pos);
|
||
}
|
||
for f in self.strikes.flights.iter().filter(|f| f.carrier.is_none()) {
|
||
r.point(f.track(), What::Strike, f.pos);
|
||
}
|
||
}
|
||
// Physical strikes start with an exact muzzle point at launch. Continue that track on a
|
||
// flight-relative STEP grid; global recording parity can be offset by the launch tick.
|
||
for f in &self.strikes.flights {
|
||
let Some(carrier) = f.carrier else { continue };
|
||
let age = self.tick.saturating_sub(f.start);
|
||
if age > 0 && age % STEP as u64 == 0 {
|
||
r.point(f.track(), What::StrikeCarrier(carrier), f.pos);
|
||
}
|
||
}
|
||
r.len += 1;
|
||
r.quiet = if busy { 0 } else { r.quiet + 1 };
|
||
if r.quiet >= 100 || r.len >= LONGEST {
|
||
let mut done = self.rec.take().unwrap();
|
||
if let Some(scene) = &mut done.scene {
|
||
scene.tracks = HashMap::new();
|
||
scene.fires = HashMap::new();
|
||
}
|
||
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()) || done.decisions.entries().next().is_some() {
|
||
self.replays.push(done);
|
||
if self.replays.len() > KEPT {
|
||
self.replays.remove(0);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Draws the recording's drones and interceptors as they were at `t`, as ghosts: ids from `base`.
|
||
pub fn draw_ghosts(&self, rec: &Recording, t: f64, base: u32, out: &mut Out) {
|
||
let base_id = base;
|
||
for (k, tr) in rec.tracks.iter().enumerate() {
|
||
let Some(pos) = tr.at(rec.origin, t) else { continue };
|
||
let dir = tr.dir(rec.origin, t);
|
||
let id = base + k as u32 * PARTS;
|
||
match tr.what {
|
||
What::Drone(kind) => {
|
||
let spec = kind.spec();
|
||
let s = spec.scale;
|
||
let falling = tr.fell.is_some_and(|f| t >= f as f64);
|
||
let mut rot = look(dir, 0.0);
|
||
if falling {
|
||
let spin = (t - tr.fell.unwrap_or(0) as f64) * 0.35;
|
||
rot = rot * DQuat::from_rotation_z(spin) * DQuat::from_rotation_x(-0.6);
|
||
out.model(id, spec.model, pos, rot, s, false);
|
||
out.model(id + 1, "airdef:flame", pos, rot, 0.6 + 0.2 * ((t * 1.7).sin() + 1.0), true);
|
||
continue;
|
||
}
|
||
if !matches!(kind, DroneKind::OreshnikBlock | DroneKind::OreshnikSub) {
|
||
out.model(id, spec.model, pos, rot, s, false);
|
||
}
|
||
match spec.engine {
|
||
Engine::Prop(back, size) => {
|
||
let at = pos + rot * DVec3::new(0.0, 0.0, back * s);
|
||
out.model(id + 1, "airdef:shahed_prop", at, rot * DQuat::from_rotation_z(t * 1.1), s * size, false);
|
||
}
|
||
Engine::Jet(up, back, size) => {
|
||
out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * s, back * s), rot, s * size, true);
|
||
}
|
||
Engine::Rocket(back, size) => {
|
||
if matches!(kind, DroneKind::OreshnikBlock | DroneKind::OreshnikSub) {
|
||
out.model(id + 1, "airdef:reentry", pos, rot, s, true);
|
||
} else if spec.ballistic.is_none() || t - (tr.first as f64) < 60.0 {
|
||
out.model(id + 1, "airdef:flame", pos + rot * DVec3::new(0.0, 0.0, back * s + size), rot, size, true);
|
||
} else {
|
||
out.model(id + 1, "airdef:reentry", pos, rot, s * 0.6, true);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
What::Missile(kind, _) => {
|
||
let spec = kind.spec();
|
||
let rot = look(dir, 0.0) * DQuat::from_rotation_z(t * 0.3);
|
||
out.model(id, spec.model, pos, rot, spec.scale, false);
|
||
if rec.missile_is_lit(tr, t, spec.cold) && spec.flame > 0.0 {
|
||
let back = (spec.rear - 8.0) / 16.0 * spec.scale + spec.flame;
|
||
out.model(id + 1, "airdef:flame", pos + rot * DVec3::new(0.0, 0.0, back), rot, spec.flame, true);
|
||
}
|
||
}
|
||
What::StrikeCarrier(_) => super::strike::round_visual(
|
||
out,
|
||
id,
|
||
pos,
|
||
look(dir, 0.0),
|
||
t - tr.first as f64 >= super::strike::EJECT_TICKS as f64,
|
||
),
|
||
What::Strike => {
|
||
// The same model, flame and turn the live flight drew (#106, #109).
|
||
let spec = DroneKind::Kalibr.spec();
|
||
let rot = look(dir, 0.0);
|
||
out.model(id, spec.model, pos, rot, spec.scale, false);
|
||
if let Engine::Jet(up, back, size) = spec.engine {
|
||
let flicker = 0.7 + 0.3 * (t * 1.7).sin().abs();
|
||
out.model(id + 1, "airdef:geran3_flame", pos + rot * DVec3::new(0.0, up * spec.scale, back * spec.scale), rot, spec.scale * size * flicker, true);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// The air-defence systems as they stood: where, which way, the launcher or turret where it
|
||
// pointed, a wreck once lost.
|
||
let mut rng = Rng(1);
|
||
for (k, st) in rec.sam_tracks.iter().enumerate() {
|
||
if let Some(ghost) = st.ghost(rec.origin, t, base + 0x0040_0000 + k as u32 * PARTS) {
|
||
units::draw_sam_model(&ghost, &mut rng, out);
|
||
}
|
||
}
|
||
// The protected objects as marked in the raid (struck ones shrink), not the live ones.
|
||
for (i, p) in rec.objects.iter().enumerate() {
|
||
let struck = rec.object_struck(i, t);
|
||
let bob = (t * 0.1 + i as f64).sin() * 0.25;
|
||
let rot = DQuat::from_rotation_y(t * 0.08);
|
||
out.model(base + 0x00e0_0000 + i as u32 * PARTS, "airdef:target", *p + DVec3::Y * (1.6 + bob), rot, if struck { 0.4 } else { 0.8 }, true);
|
||
}
|
||
// Fires: what the events left burning (the flames dim and the smoke thickens with time),
|
||
// out when their life ends.
|
||
for f in replay_fires(rec, t) {
|
||
let age = t - f.start as f64 + f.age_offset as f64;
|
||
let (mut flame, mut smoke) = fires::replay_fire_of(f.size, f.life, age);
|
||
if f.water == Some(true) { flame = 0.0; smoke *= 0.5; }
|
||
if f.quiet || !f.shown { flame = 0.0; }
|
||
let id = base + 0x00c0_0000 + f.key as u32 * PARTS;
|
||
if flame > 0.05 {
|
||
let wob = 1.0 + 0.15 * (age * 0.9 + f.key as f64).sin();
|
||
out.model(id, "airdef:flame", f.at + DVec3::Y * 0.5, DQuat::from_rotation_y(age * 0.07), (flame as f64 * 0.8 * wob).max(0.05), true);
|
||
}
|
||
if smoke > 0.1 && (age as u64) % 3 == 0 {
|
||
out.particles("minecraft:large_smoke", f.at + DVec3::Y, 0.8, DVec3::new(0.0, 0.1, 0.0), 0.03, 1 + (smoke * 2.0) as u32);
|
||
}
|
||
}
|
||
// The pieces a breakup or an air detonation threw off, from the recorded outcome (never a new roll): the same
|
||
// pieces the live raid made, moved by the same flight, a pure function of the time.
|
||
for (k, e) in rec.events_window(t - outcome::PIECE_LIFE as f64, t) {
|
||
let EventKind::Kill { drone, outcome, .. } = e.kind else { continue };
|
||
let age = t - e.at as f64;
|
||
if outcome == Outcome::DisabledFalling || !(0.0..outcome::PIECE_LIFE as f64).contains(&age) {
|
||
continue;
|
||
}
|
||
let base = rec
|
||
.track(drone)
|
||
.and_then(|tr| Some((tr.at(rec.origin, e.at as f64)? - tr.at(rec.origin, e.at as f64 - STEP as f64)?) / STEP as f64))
|
||
.unwrap_or(DVec3::ZERO);
|
||
let seed = (k as u64).wrapping_mul(0x2545_f491_4f6c_dd1d) ^ e.at as u64;
|
||
for (n, p) in outcome::pieces(seed, outcome, base).iter().enumerate() {
|
||
if age as u32 >= p.life {
|
||
continue;
|
||
}
|
||
let at = outcome::piece_at(e.pos, p, age as u32);
|
||
let id = base_id + 0x0060_0000 + (k as u32 * 16 + n as u32) * PARTS;
|
||
out.model(id, "airdef:debris", at, outcome::piece_rot(p, age as u32), p.scale, false);
|
||
if p.burns && (age as u32) % 3 == 0 {
|
||
out.particles("minecraft:large_smoke", at, 0.1, DVec3::new(0.0, 0.03, 0.0), 0.01, 1);
|
||
}
|
||
}
|
||
}
|
||
// Blasts: with the shader effects on, the post pass and the HD lights draw them from
|
||
// `replay_blasts` (the same as the live ones); the models are the fallback without them.
|
||
if self.shader {
|
||
return;
|
||
}
|
||
for (k, e) in rec.events_window(t - 30.0, t) {
|
||
let age = t - e.at as f64;
|
||
if !(0.0..30.0).contains(&age) {
|
||
continue;
|
||
}
|
||
let (size, _) = blast_spec(e.kind);
|
||
let size = size as f64;
|
||
let f = age / 30.0;
|
||
let s = size * (f * 4.0).min(1.0) * (1.0 - f * f);
|
||
let id = base + 0x0080_0000 + k as u32 * PARTS;
|
||
let spin = DQuat::from_rotation_y(age * 0.05);
|
||
out.model(id, "airdef:fireball", e.pos + DVec3::Y * age * 0.04, spin, s.max(0.01), true);
|
||
if age < 4.0 {
|
||
out.model(id + 1, "airdef:flash", e.pos, spin, size * 0.6, true);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
fn sam_at(x: f64, heading: f64, yaw: f64) -> Sam {
|
||
let mut s = Sam::new(7, SamKind::S400, DVec3::new(x, 64.0, 0.0), heading);
|
||
s.yaw = yaw;
|
||
s
|
||
}
|
||
|
||
#[test]
|
||
fn battle_chains_keep_four_or_five_measured_steps_and_filter_by_battery() {
|
||
let mut r = Recording::blank(400);
|
||
r.sams = vec![(10, SamKind::Pantsir, DVec3::ZERO), (20, SamKind::S400, DVec3::new(200.0, 64.0, 0.0))];
|
||
let mut scene = SceneJournal::default();
|
||
let at = |at: u32, kind| SceneEvent { at, pos: DVec3::ZERO, kind };
|
||
scene.push(at(20, SceneKind::TrackAcquired { sam: 10, target: 7, ever_own: false }));
|
||
scene.push(at(30, SceneKind::TrackSource { sam: 10, target: 7, ever_own: true }));
|
||
scene.push(at(40, SceneKind::TrackLock { sam: 10, target: 7, locked: true }));
|
||
scene.push(at(50, SceneKind::MissileLaunch { missile: 500, sam: 10, target: 7, kind: MissileKind::M57e6, sound: "airdef:launch.pantsir", pitch: 1.0 }));
|
||
scene.push(at(70, SceneKind::TrackLost { sam: 10, target: 7 }));
|
||
r.scene = Some(scene);
|
||
r.events.push(Event {
|
||
at: 60,
|
||
pos: DVec3::ZERO,
|
||
kind: EventKind::Kill { drone: 7, kind: DroneKind::Shahed, sam: 10, sam_kind: SamKind::Pantsir, sam_index: 0, missile: Some(500), outcome: Outcome::DisabledFalling },
|
||
});
|
||
let chains = r.chains(None);
|
||
assert_eq!(chains.len(), 1);
|
||
let chain = &chains[0];
|
||
let kinds: Vec<ChainStepKind> = chain.steps.iter().map(|s| s.kind).collect();
|
||
assert_eq!(kinds, vec![ChainStepKind::Mark, ChainStepKind::Handoff, ChainStepKind::Lock, ChainStepKind::Launch, ChainStepKind::Outcome]);
|
||
assert_eq!(chain.outcome, ChainOutcome::Destroyed);
|
||
assert_eq!(chain.outcome_event(), Some(0));
|
||
assert!(!chain.missed());
|
||
assert_eq!(chain.marked_at(), 20);
|
||
assert_eq!(r.chains(Some(10)).len(), 1);
|
||
assert!(r.chains(Some(20)).is_empty(), "the filter picked another battery");
|
||
|
||
// A contact marked and lost without a launch is a missed chain, not an engagement.
|
||
let mut r = Recording::blank(100);
|
||
r.sams = vec![(10, SamKind::Pantsir, DVec3::ZERO)];
|
||
let mut scene = SceneJournal::default();
|
||
scene.push(at(10, SceneKind::TrackAcquired { sam: 10, target: 8, ever_own: false }));
|
||
scene.push(at(50, SceneKind::TrackLost { sam: 10, target: 8 }));
|
||
r.scene = Some(scene);
|
||
let chain = &r.chains(None)[0];
|
||
assert!(chain.missed());
|
||
assert_eq!(chain.outcome, ChainOutcome::Lost);
|
||
assert_eq!(chain.steps.len(), 2);
|
||
assert_eq!(chain.outcome_event(), None);
|
||
}
|
||
|
||
#[test]
|
||
fn a_recorded_impact_stays_in_every_observers_chain_when_the_track_ends() {
|
||
let mut r = Recording::blank(100);
|
||
r.sams = vec![(10, SamKind::Pantsir, DVec3::ZERO), (20, SamKind::S400, DVec3::X)];
|
||
let mut scene = SceneJournal::default();
|
||
for sam in [10, 20] {
|
||
scene.push(SceneEvent { at: 10, pos: DVec3::ZERO, kind: SceneKind::TrackAcquired { sam, target: 7, ever_own: false } });
|
||
}
|
||
for sam in [10, 20] {
|
||
scene.push(SceneEvent { at: 51, pos: DVec3::ZERO, kind: SceneKind::TrackLost { sam, target: 7 } });
|
||
}
|
||
r.scene = Some(scene);
|
||
r.events.push(Event {
|
||
at: 50,
|
||
pos: DVec3::ZERO,
|
||
kind: EventKind::Hit { drone: 7, kind: DroneKind::Shahed, power: 2, object: None, sam: Some((SamKind::S400, 1)) },
|
||
});
|
||
for id in [10, 20] {
|
||
let chains = r.chains(Some(id));
|
||
assert_eq!(chains.len(), 1);
|
||
assert_eq!(chains[0].outcome, ChainOutcome::Hit);
|
||
assert_eq!(chains[0].outcome_event(), Some(0));
|
||
assert_eq!(chains[0].step(ChainStepKind::Outcome).unwrap().at, 50);
|
||
assert!(chains[0].missed());
|
||
}
|
||
}
|
||
|
||
fn recording() -> Recording {
|
||
Recording::blank(0)
|
||
}
|
||
|
||
#[test]
|
||
fn replay_seeks_radar_emission_stepwise() {
|
||
let mut r = recording();
|
||
let sam = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
|
||
r.note_sams(&[sam], 0);
|
||
let mut off = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
|
||
off.radar_on = false;
|
||
r.note_sams(&[off], 10);
|
||
assert!(r.sam_tracks[0].ghost(r.origin, 9.0, 1).unwrap().radar_on);
|
||
assert!(!r.sam_tracks[0].ghost(r.origin, 10.0, 1).unwrap().radar_on);
|
||
assert!(r.sam_tracks[0].ghost(r.origin, 0.0, 1).unwrap().radar_on);
|
||
}
|
||
|
||
#[test]
|
||
fn replay_preserves_a_separate_radars_profile() {
|
||
let mut r = recording();
|
||
for (at, role) in [(0, battery::RadarRole::Search), (10, battery::RadarRole::Height), (20, battery::RadarRole::Engagement)] {
|
||
let mut sam = Sam::new(1, SamKind::Radar, DVec3::ZERO, 0.0);
|
||
sam.set_radar_role(role);
|
||
r.note_sams(&[sam], at);
|
||
}
|
||
assert_eq!(r.sam_tracks[0].ghost(r.origin, 1.0, 1).unwrap().radar_profile().id, "radar_search");
|
||
assert_eq!(r.sam_tracks[0].ghost(r.origin, 11.0, 1).unwrap().radar_profile().id, "radar_height");
|
||
assert_eq!(r.sam_tracks[0].ghost(r.origin, 21.0, 1).unwrap().radar_profile().id, "radar_track");
|
||
}
|
||
|
||
#[test]
|
||
fn replay_preserves_launcher_configuration_and_individual_cover_poses() {
|
||
let mut r = recording();
|
||
let mut sam = sam_at(0.0, 0.0, 0.0);
|
||
sam.set_mode(battery::SamMode::LauncherOnly);
|
||
sam.cap_cell = 2;
|
||
sam.cap_open = 0.5;
|
||
sam.spent_cells = 1;
|
||
r.note_sams(&[sam], 10);
|
||
for t in [10.0, 40.0, 10.0] {
|
||
let ghost = r.sam_tracks[0].ghost(r.origin, t, 160).unwrap();
|
||
assert_eq!(ghost.mode, battery::SamMode::LauncherOnly);
|
||
assert_eq!((ghost.spent_cells, ghost.cap_cell, ghost.cap_open), (1, 2, 0.5));
|
||
let mut out = Out::default();
|
||
units::draw_sam_model(&ghost, &mut Rng::new(1), &mut out);
|
||
assert_eq!(out.models.iter().filter(|m| m.name == "airdef:tpk_cap").count(), 4);
|
||
assert!(!out.models.iter().any(|m| m.name == "airdef:radar_panel"));
|
||
}
|
||
}
|
||
|
||
fn physical_strike(record_len: Option<u32>) -> (Sim, u32, DVec3) {
|
||
use crate::sim::sites::{LaunchSite, SiteClass};
|
||
use crate::sim::strike::{Estimate, Known, SiteState};
|
||
use glam::DVec2;
|
||
|
||
let mut sim = Sim::new(11);
|
||
sim.tick = 100 + u64::from(record_len.unwrap_or(0));
|
||
if let Some(len) = record_len {
|
||
let mut rec = Recording::new(1, &sim);
|
||
rec.len = len;
|
||
sim.rec = Some(rec);
|
||
}
|
||
let site = 1;
|
||
sim.sites.list.push(LaunchSite {
|
||
id: site,
|
||
side: 0,
|
||
sector: 0,
|
||
bearing: 0.0,
|
||
class: SiteClass::Ramp,
|
||
pos: DVec3::new(0.0, 64.0, 300.0),
|
||
range: 300.0,
|
||
water: false,
|
||
stock: 0,
|
||
planned: 0,
|
||
alive: true,
|
||
next_free: 0,
|
||
offmap: false,
|
||
});
|
||
sim.strikes.known.push(Known {
|
||
site,
|
||
class: SiteClass::Ramp,
|
||
obs: Vec::new(),
|
||
est: Some(Estimate {
|
||
pos: DVec2::new(0.0, 300.0),
|
||
radius: 5.0,
|
||
fix: true,
|
||
bearing: 0.0,
|
||
bearing_err: 0.01,
|
||
origin: DVec2::ZERO,
|
||
}),
|
||
launches: 1,
|
||
last: 0,
|
||
state: SiteState::Active,
|
||
aimed: false,
|
||
});
|
||
sim.order_test_strike(site, DVec3::new(0.0, 64.0, 0.0), &mut Out::default())
|
||
.unwrap();
|
||
let flight = &mut sim.strikes.flights[0];
|
||
let (id, muzzle) = (flight.id, flight.pos);
|
||
let carrier = 77;
|
||
flight.carrier = Some(carrier);
|
||
sim.record_strike_launch(id, carrier, muzzle);
|
||
(sim, id, muzzle)
|
||
}
|
||
|
||
#[test]
|
||
fn physical_strike_track_keeps_muzzle_and_samples_on_flight_relative_grid() {
|
||
// A fresh recording starts at launch; the other cases launch into odd/even positions on
|
||
// an existing recording's global grid.
|
||
for record_len in [None, Some(1), Some(2)] {
|
||
let (mut sim, id, muzzle) = physical_strike(record_len);
|
||
let track_id = 0x7100_0000 | id;
|
||
{
|
||
let rec = sim.rec.as_ref().unwrap();
|
||
let track = rec.track(track_id).unwrap();
|
||
assert_eq!(track.what, What::StrikeCarrier(77));
|
||
assert_eq!(track.points.len(), 1, "the launch records exactly one muzzle point");
|
||
assert_eq!(track.at(rec.origin, track.first as f64), Some(muzzle));
|
||
}
|
||
|
||
for age in 1..=4u64 {
|
||
sim.tick += 1;
|
||
let pos = muzzle + DVec3::Z * (age as f64 * 8.0);
|
||
sim.strikes.flights[0].pos = pos;
|
||
sim.record();
|
||
let rec = sim.rec.as_ref().unwrap();
|
||
let track = rec.track(track_id).unwrap();
|
||
let expected_samples = 1 + (age / STEP as u64) as usize;
|
||
assert_eq!(track.points.len(), expected_samples, "flight age {age}, recording len {}", record_len.unwrap_or(0));
|
||
assert_eq!(track.at(rec.origin, track.first as f64), Some(muzzle));
|
||
if age % STEP as u64 == 0 {
|
||
assert_eq!(track.at(rec.origin, (track.first + age as u32) as f64), Some(pos));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn full_recording_bounds_sam_keys_without_freezing_their_poses() {
|
||
let mut r = recording();
|
||
let mut sams: Vec<_> = (0..64)
|
||
.map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0))
|
||
.collect();
|
||
for now in (0..LONGEST).step_by(STEP as usize) {
|
||
for sam in &mut sams {
|
||
sam.dish = now as f64 * 0.01;
|
||
}
|
||
r.note_sams(&sams, now);
|
||
}
|
||
let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
||
let allocated: usize = r.sam_tracks.iter().map(|track| track.keys.capacity()).sum();
|
||
assert_eq!(keys, r.sam_keys);
|
||
assert_eq!(r.sam_events, 0, "a turning dish is a pose, not a transition");
|
||
assert!(keys <= MAX_SAM_KEYS, "a full recording retained {keys} SamKeys");
|
||
assert!(allocated <= 2 * MAX_SAM_KEYS, "SamKey allocations reached {} MiB", allocated * size_of::<SamKey>() / (1024 * 1024));
|
||
assert!(r.sam_step > STEP, "the rotating radars never engaged adaptive sampling");
|
||
let last = r.sam_tracks[0].pose(LONGEST as f64).unwrap();
|
||
assert!(last.at >= LONGEST - 64, "poses stopped at tick {}", last.at);
|
||
assert!(last.dish > 100.0, "the final radar pose was not recorded");
|
||
}
|
||
|
||
// #142: sixty-four turning radars on a 16-tick pose grid plus a cold S-400 launch. The
|
||
// cover's six-tick opening, the ejection and the spent cell must survive the decimation, and
|
||
// so must the radar's switch and a cancelled cover, on the tick they happened.
|
||
#[test]
|
||
fn decimation_keeps_a_cold_launch_cover_ejection_and_the_radar_switch() {
|
||
let mut r = recording();
|
||
let mut sams: Vec<_> = (0..64).map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0)).collect();
|
||
sams.push(Sam::new(100, SamKind::S400, DVec3::ZERO, 0.0));
|
||
let turned_off = 5_usize;
|
||
// The pose budget of a long recording has already slowed the sampling down.
|
||
r.sam_step = 16;
|
||
let eject = 4103u32;
|
||
let start = eject - launch::OPEN_TICKS as u32;
|
||
let (reopen, close, switch) = (4120u32, 4122u32, 4131u32);
|
||
for now in 0..4_200 {
|
||
for sam in &mut sams[..64] {
|
||
sam.dish = now as f64 * 0.01;
|
||
}
|
||
let s400 = sams.len() - 1;
|
||
if now == start {
|
||
assert!(!sams[s400].prepare_tube(7, now as u64));
|
||
} else if (start + 1..=eject).contains(&now) {
|
||
if sams[s400].prepare_tube(7, now as u64) {
|
||
assert_eq!(now, eject);
|
||
sams[s400].eject_cell(0);
|
||
}
|
||
} else if (reopen..close).contains(&now) {
|
||
// A second opening, cancelled before it is wide: the cover closes.
|
||
sams[s400].prepare_tube(7, now as u64);
|
||
} else if now == close {
|
||
sams[s400].cancel_prepare();
|
||
}
|
||
if now == switch {
|
||
sams[turned_off].radar_on = false;
|
||
}
|
||
r.note_sams(&sams, now);
|
||
}
|
||
let track = |id: u32| r.sam_tracks.iter().find(|track| track.id == id).unwrap();
|
||
let pose = |id: u32, t: f64| track(id).pose(t).unwrap();
|
||
let s400 = track(100);
|
||
assert!(s400.keys.len() < 32, "the launch track kept {} keys", s400.keys.len());
|
||
// The cover was shut before the stage and opens exactly over `OPEN_TICKS` ticks.
|
||
assert_eq!(pose(100, f64::from(start - 1)).cap_open, 0.0);
|
||
for k in 1..launch::OPEN_TICKS as u32 {
|
||
let want = k as f32 / launch::OPEN_TICKS as f32;
|
||
let got = pose(100, f64::from(start + k)).cap_open;
|
||
assert!((got - want).abs() < 1e-5, "tick {} of the opening: {got} not {want}", start + k);
|
||
}
|
||
assert!(s400.keys.iter().any(|k| k.at == start && k.event && k.cap_open == 0.0), "the stage's start key is kept");
|
||
// The last tick before the ejection: the cover stands five sixths open, not shut.
|
||
assert!((pose(100, f64::from(eject - 1)).cap_open - 5.0 / 6.0).abs() < 1e-5);
|
||
// The ejection: the cell is spent on its own tick, not on the next pose sample.
|
||
assert_eq!(pose(100, f64::from(eject - 1)).spent_cells, 0);
|
||
assert_eq!(pose(100, f64::from(eject)).spent_cells, 1);
|
||
assert!(track(100).keys.iter().any(|k| k.at == eject && k.event));
|
||
// The cancelled opening closes the cover on the tick it was cancelled.
|
||
assert!(pose(100, f64::from(close - 1)).cap_open > 0.0);
|
||
assert_eq!(pose(100, f64::from(close)).cap_open, 0.0);
|
||
// The radar's switch is on its own tick, between two 16-tick pose samples.
|
||
assert!(pose(turned_off as u32, f64::from(switch - 1)).radar_on);
|
||
assert!(!pose(turned_off as u32, f64::from(switch)).radar_on);
|
||
assert!(track(turned_off as u32).keys.iter().any(|k| k.at == switch && k.event));
|
||
// Later decimation halves poses only: the recorded launch still reads as it did.
|
||
r.thin_sam_poses();
|
||
r.thin_sam_poses();
|
||
let track = |id: u32| r.sam_tracks.iter().find(|track| track.id == id).unwrap();
|
||
let pose = |id: u32, t: f64| track(id).pose(t).unwrap();
|
||
assert!((pose(100, f64::from(eject - 1)).cap_open - 5.0 / 6.0).abs() < 1e-5);
|
||
assert_eq!(pose(100, f64::from(eject)).spent_cells, 1);
|
||
assert!(!pose(turned_off as u32, f64::from(switch)).radar_on);
|
||
}
|
||
|
||
// #142: the transitions have their own explicit budget. A recording that chatters must stay
|
||
// bounded, and the newest transitions — what a replay is watched closest for — stay exact.
|
||
#[test]
|
||
fn critical_transitions_have_their_own_explicit_budget() {
|
||
let mut r = recording();
|
||
let mut sams: Vec<_> = (0..64).map(|id| Sam::new(id, SamKind::Radar, DVec3::ZERO, 0.0)).collect();
|
||
let ticks = 1_500u32;
|
||
for now in 0..ticks {
|
||
for sam in &mut sams {
|
||
sam.radar_on = now % 2 == 0;
|
||
}
|
||
r.note_sams(&sams, now);
|
||
}
|
||
let keys: usize = r.sam_tracks.iter().map(|track| track.keys.len()).sum();
|
||
assert_eq!(keys, r.sam_keys);
|
||
assert_eq!(r.sam_events, MAX_SAM_EVENTS, "the transitions' budget is explicit");
|
||
assert!(keys <= MAX_SAM_KEYS + MAX_SAM_EVENTS + sams.len(), "{keys} SamKeys retained");
|
||
assert!(keys - r.sam_events <= MAX_SAM_KEYS, "poses broke their own budget");
|
||
// The newest switch reads exactly; the oldest transitions were the ones let go.
|
||
let newest = r.sam_tracks[0].pose(f64::from(ticks - 1)).unwrap();
|
||
assert_eq!(newest.radar_on, (ticks - 1) % 2 == 0);
|
||
assert!(r.sam_tracks[0].keys.iter().any(|key| key.at == ticks - 1 && key.event));
|
||
let earliest = r.sam_tracks[0].keys.iter().position(|key| key.event);
|
||
assert!(earliest.is_none_or(|i| r.sam_tracks[0].keys[i].at > ticks / 2), "old transitions hold on to the budget");
|
||
}
|
||
|
||
#[test]
|
||
fn a_system_keeps_its_pose_through_stillness_and_moves_when_it_moved() {
|
||
let mut r = recording();
|
||
// Still for 20 ticks, then the turret swings and the vehicle drives.
|
||
for now in (0..=20).step_by(STEP as usize) {
|
||
r.note_sams(&[sam_at(0.0, 0.0, 0.0)], now);
|
||
}
|
||
assert_eq!(r.sam_tracks[0].keys.len(), 1, "stillness is one key");
|
||
r.note_sams(&[sam_at(4.0, 0.0, 1.0)], 22);
|
||
let t = &r.sam_tracks[0];
|
||
let pose = |tick: f64| t.pose(tick).unwrap();
|
||
// Held at the old pose until just before the change, not gliding over the stillness.
|
||
assert!(pose(10.0).pos[0].abs() < 1e-6 && pose(10.0).yaw.abs() < 1e-6);
|
||
assert!(pose(20.0).pos[0].abs() < 1e-6);
|
||
// Half way through the move.
|
||
assert!((pose(21.0).pos[0] - 2.0).abs() < 1e-4 && (pose(21.0).yaw - 0.5).abs() < 1e-4);
|
||
assert!((pose(100.0).pos[0] - 4.0).abs() < 1e-6);
|
||
}
|
||
|
||
#[test]
|
||
fn recorder_is_passive_and_combat_effects_do_not_depend_on_it() {
|
||
let kind = EventKind::Crash { drone: 1, kind: DroneKind::Shahed, power: 2 };
|
||
let mut recording = Sim::new(4);
|
||
recording.rec = Some(Recording::new(1, &recording));
|
||
recording.record_event(DVec3::ZERO, kind);
|
||
assert!(recording.fires.list.is_empty(), "recording a fact must not ignite the live world");
|
||
assert_eq!(recording.rec.as_ref().unwrap().events.len(), 1);
|
||
let mut without = Sim::new(4);
|
||
without.emit_combat_event(DVec3::ZERO, kind);
|
||
assert_eq!(without.fires.list.len(), 1, "the domain effect must run without a recorder");
|
||
let mut with = Sim::new(4);
|
||
with.rec = Some(Recording::new(1, &with));
|
||
with.emit_combat_event(DVec3::ZERO, kind);
|
||
assert_eq!(with.fires.list.len(), 1);
|
||
assert_eq!(with.rec.as_ref().unwrap().events.len(), 1);
|
||
assert_eq!(with.fires.list[0].size, without.fires.list[0].size);
|
||
}
|
||
|
||
#[test]
|
||
fn recorded_sam_health_and_parts_are_stepwise_and_seekable() {
|
||
let mut r = recording();
|
||
let mut sam = Sam::new(7, SamKind::Patriot, DVec3::ZERO, 0.0);
|
||
r.note_sams(std::slice::from_ref(&sam), 0);
|
||
sam.health = 0.4;
|
||
sam.comps.0[Part::Sensor as usize] = 0.25;
|
||
r.note_sams(std::slice::from_ref(&sam), 10);
|
||
let st = &r.sam_tracks[0];
|
||
let before = st.ghost(r.origin, 9.0, 7).unwrap();
|
||
let damaged = st.ghost(r.origin, 10.0, 7).unwrap();
|
||
assert_eq!(before.health, 1.0);
|
||
assert!((damaged.health - 0.4).abs() < 1e-6);
|
||
assert_eq!(damaged.comps.get(Part::Sensor), 0.25);
|
||
assert_eq!(st.ghost(r.origin, 10.0, 7).unwrap().comps, damaged.comps);
|
||
}
|
||
|
||
#[test]
|
||
fn sampled_track_and_fire_transitions_follow_real_changes() {
|
||
let mut sim = Sim::new(3);
|
||
let id = sim.id();
|
||
sim.sams.push(Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0));
|
||
let mut r = Recording::new(1, &sim);
|
||
let tr = sight::Track {
|
||
id: 77,
|
||
class: ClassEst::Firm(Class::Drone),
|
||
pos: DVec3::Z * 100.0,
|
||
vel: -DVec3::Z,
|
||
tick: 1,
|
||
own_tick: 1,
|
||
source: 1,
|
||
product: battery::Measure::Fire,
|
||
quality: 80,
|
||
own_product: battery::Measure::Fire,
|
||
own_quality: 80,
|
||
ttl: 10,
|
||
hits: 1,
|
||
locked: false,
|
||
};
|
||
sim.sams[0].tracks.push(tr);
|
||
r.note_tracks(&sim.sams);
|
||
r.len = 1;
|
||
sim.sams[0].tracks[0].locked = true;
|
||
r.note_tracks(&sim.sams);
|
||
r.len = 2;
|
||
sim.sams[0].tracks.clear();
|
||
r.note_tracks(&sim.sams);
|
||
let events = &r.scene.as_ref().unwrap().events;
|
||
assert!(matches!(events[0].kind, SceneKind::TrackAcquired { sam, target: 77, ever_own: true } if sam == id));
|
||
assert!(matches!(events[1].kind, SceneKind::TrackLock { sam, target: 77, locked: true } if sam == id));
|
||
assert!(matches!(events[2].kind, SceneKind::TrackLost { sam, target: 77 } if sam == id));
|
||
|
||
sim.ignite(DVec3::ZERO, 1, None);
|
||
let fire = sim.fires.list[0].id;
|
||
r.note_fires(&sim.fires.list, sim.tick);
|
||
assert_eq!(replay_fires(&r, 2.0)[0].size, 1.0);
|
||
sim.ignite(DVec3::ZERO, 4, None);
|
||
r.len += 1;
|
||
r.note_fires(&sim.fires.list, sim.tick);
|
||
assert_eq!(replay_fires(&r, 3.0)[0].size, 3.0);
|
||
assert_eq!(replay_fires(&r, 2.0)[0].size, 1.0, "seeking back uses old fire state");
|
||
sim.fires.extinguish();
|
||
r.len += 1;
|
||
r.note_fires(&sim.fires.list, sim.tick);
|
||
assert!(replay_fires(&r, 4.0).is_empty());
|
||
let events = &r.scene.as_ref().unwrap().events;
|
||
assert!(events.iter().any(|e| matches!(e.kind, SceneKind::FireStarted { fire: id, .. } if id == fire)));
|
||
assert!(events.iter().any(|e| matches!(e.kind, SceneKind::FireChanged { fire: id, size, .. } if id == fire && size == 3.0)));
|
||
assert!(events.iter().any(|e| matches!(e.kind, SceneKind::FireEnded { fire: id } if id == fire)));
|
||
}
|
||
|
||
#[test]
|
||
fn replay_fire_uses_sampled_existing_age_water_and_end() {
|
||
let mut r = recording();
|
||
let mut scene = SceneJournal::default();
|
||
scene.push(SceneEvent { at: 0, pos: DVec3::X, kind: SceneKind::FireStarted { fire: 7, age: 50, life: 100, size: 1.0, quiet: false, shown: true, water: Some(true) } });
|
||
scene.push(SceneEvent { at: 10, pos: DVec3::X, kind: SceneKind::FireEnded { fire: 7 } });
|
||
r.scene = Some(scene);
|
||
let a = replay_fires(&r, 5.0);
|
||
assert_eq!(a.len(), 1);
|
||
assert_eq!((a[0].start, a[0].age_offset, a[0].water), (0, 50, Some(true)));
|
||
assert!(replay_fires(&r, 11.0).is_empty());
|
||
let b = replay_fires(&r, 5.0);
|
||
assert_eq!((a[0].start, a[0].age_offset, a[0].water), (b[0].start, b[0].age_offset, b[0].water));
|
||
}
|
||
|
||
#[test]
|
||
fn scene_journal_is_bounded_and_incomplete_is_marked() {
|
||
let mut j = SceneJournal::default();
|
||
for i in 0..=MAX_SCENE_EVENTS {
|
||
j.push(SceneEvent { at: i as u32, pos: DVec3::ZERO, kind: SceneKind::FireEnded { fire: i as u32 } });
|
||
}
|
||
assert_eq!(j.events.len(), MAX_SCENE_EVENTS);
|
||
assert!(j.truncated);
|
||
}
|
||
|
||
#[test]
|
||
fn ten_minute_transition_stream_is_bounded() {
|
||
let started = std::time::Instant::now();
|
||
let mut sim = Sim::new(5);
|
||
for _ in 0..4 {
|
||
let id = sim.id();
|
||
let mut sam = Sam::new(id, SamKind::Patriot, DVec3::ZERO, 0.0);
|
||
for target in 1..=4 {
|
||
sam.tracks.push(sight::Track {
|
||
id: target,
|
||
class: ClassEst::Firm(Class::Drone),
|
||
pos: DVec3::Z,
|
||
vel: DVec3::ZERO,
|
||
tick: 1,
|
||
own_tick: 1,
|
||
source: sam.id,
|
||
product: battery::Measure::Fire,
|
||
quality: 80,
|
||
own_product: battery::Measure::Fire,
|
||
own_quality: 80,
|
||
ttl: 1,
|
||
hits: 1,
|
||
locked: false,
|
||
});
|
||
}
|
||
sim.sams.push(sam);
|
||
}
|
||
let mut r = Recording::new(1, &sim);
|
||
for t in 0..12_000 {
|
||
r.len = t;
|
||
for sam in &mut sim.sams { for tr in &mut sam.tracks { tr.locked = t % 2 == 0; } }
|
||
r.note_tracks(&sim.sams);
|
||
}
|
||
let scene = r.scene.as_ref().unwrap();
|
||
// A pure track-transition stream stops at the transitions' own budget: the rest of the
|
||
// journal stays free for the launches, fires and outcomes.
|
||
assert_eq!(scene.events.len(), MAX_SCENE_TRACK_EVENTS);
|
||
assert!(!scene.truncated);
|
||
eprintln!("scene stress: 12000 ticks, {} events, event storage {:.2} MiB, elapsed {:?}", scene.events.len(), scene.events.capacity() * std::mem::size_of::<SceneEvent>() / (1024 * 1024), started.elapsed());
|
||
}
|
||
|
||
#[test]
|
||
fn real_launch_and_ignition_are_recorded_with_ids_and_sound() {
|
||
let mut sim = Sim::new(0x87);
|
||
let sam = sim.id();
|
||
sim.sams.push(Sam::new(sam, SamKind::Patriot, DVec3::new(0.0, 64.0, 0.0), 0.0));
|
||
let mut out = Out::default();
|
||
for (i, kind) in [DroneKind::Shahed, DroneKind::Kh101, DroneKind::Iskander].into_iter().enumerate() {
|
||
sim.launch(kind, DVec3::new(i as f64 * 100.0, 110.0, 800.0), -DVec3::Z, DVec3::new(0.0, 64.0, 0.0), &mut out);
|
||
}
|
||
let mut ground = Ground::default();
|
||
for _ in 0..600 {
|
||
let wanted = ground.take_wanted();
|
||
ground.answer(wanted.into_iter().map(|(x, z)| (x, z, 64)).collect(), sim.tick);
|
||
out = Out::default();
|
||
sim.step(&mut ground, None, &mut out);
|
||
if sim.rec.as_ref().and_then(|r| r.scene.as_ref()).is_some_and(|j| j.events.iter().any(|e| matches!(e.kind, SceneKind::MotorIgnition { .. }))) { break; }
|
||
}
|
||
let r = sim.rec.as_ref().expect("recording");
|
||
let launch = r.scene.as_ref().unwrap().events.iter().find(|e| matches!(e.kind, SceneKind::MissileLaunch { .. })).expect("actual launch");
|
||
let missile = match launch.kind { SceneKind::MissileLaunch { missile, sam: source, sound, .. } => { assert_eq!(source, sam); assert_eq!(sound, "airdef:launch.patriot"); missile }, _ => unreachable!() };
|
||
let ignition = r.missile_ignition(missile).expect("actual ignition");
|
||
assert!(ignition.at >= launch.at);
|
||
assert_eq!(r.missile_launch(missile).unwrap().pos, launch.pos);
|
||
}
|
||
|
||
// #76: a replay's searchlights point where the recording had them, from the recorded pose.
|
||
#[test]
|
||
fn a_replay_has_the_recorded_searchlight_beams() {
|
||
let mut r = recording();
|
||
let mut light = Sam::new(9, SamKind::Light, DVec3::new(10.0, 64.0, 0.0), 0.0);
|
||
light.beam_on = true;
|
||
light.beam_free = 300.0;
|
||
light.yaw = 1.0;
|
||
light.pitch = 0.8;
|
||
r.note_sams(&[light], 0);
|
||
// Swung round and switched off later.
|
||
let mut later = Sam::new(9, SamKind::Light, DVec3::new(10.0, 64.0, 0.0), 0.0);
|
||
later.yaw = 2.0;
|
||
later.pitch = 0.8;
|
||
r.note_sams(&[later], 100);
|
||
assert!(r.beams(-1.0).is_empty(), "nothing before it was seen");
|
||
let b = r.beams(0.0);
|
||
assert_eq!(b.len(), 1);
|
||
assert_eq!(b[0].id, 9);
|
||
assert!((b[0].free - 304.0).abs() < 1e-6 || (b[0].free - 296.0).abs() < 1e-6, "free {}", b[0].free);
|
||
assert!(b[0].dir.y > 0.5, "pointing up: {:?}", b[0].dir);
|
||
assert!(r.beams(100.0).is_empty(), "switched off");
|
||
r.sam_tracks[0].lost = Some(50);
|
||
assert!(r.beams(10.0).len() == 1 && r.beams(60.0).is_empty(), "a lost light has no beam");
|
||
}
|
||
|
||
#[test]
|
||
fn a_system_first_seen_later_is_not_drawn_before() {
|
||
let mut r = recording();
|
||
r.note_sams(&[sam_at(0.0, 0.0, 0.0)], 40);
|
||
assert!(r.sam_tracks[0].pose(10.0).is_none());
|
||
assert!(r.sam_tracks[0].pose(40.0).is_some());
|
||
}
|
||
|
||
#[test]
|
||
fn angles_turn_the_short_way_and_a_lost_system_is_a_wreck() {
|
||
let mut r = recording();
|
||
r.note_sams(&[sam_at(0.0, 0.0, 6.2)], 0);
|
||
r.note_sams(&[sam_at(0.0, 0.0, 0.1)], 2);
|
||
let t = &mut r.sam_tracks[0];
|
||
let mid = t.pose(1.0).unwrap().yaw;
|
||
assert!(!(0.2..6.0).contains(&mid), "through zero, not back round: {mid}");
|
||
assert!(t.ghost(DVec3::ZERO, 1.0, 0).unwrap().alive());
|
||
t.lost = Some(30);
|
||
assert!(t.ghost(DVec3::ZERO, 29.0, 0).unwrap().alive());
|
||
assert!(!t.ghost(DVec3::ZERO, 31.0, 0).unwrap().alive());
|
||
}
|
||
|
||
#[test]
|
||
fn the_games_tick_is_known_through_the_recording() {
|
||
let mut r = recording();
|
||
assert_eq!(r.world_tick(5.0), None);
|
||
r.ticks = vec![(0, 1000), (20, 1020), (40, 1040), (60, 1100)];
|
||
assert_eq!(r.first_tick(), Some(1000));
|
||
assert_eq!(r.world_tick(0.0), Some(1000));
|
||
assert_eq!(r.world_tick(10.0), Some(1010));
|
||
assert_eq!(r.world_tick(30.0), Some(1030));
|
||
// A jump of the game's ticks between samples (the recording paused or a gap) is a step.
|
||
assert_eq!(r.world_tick(50.0), Some(1040 + 10));
|
||
assert_eq!(r.world_tick(70.0), Some(1100 + 10));
|
||
}
|
||
|
||
// #97: the kill's outcome is a recorded fact: a replay draws the pieces of that outcome and rolls nothing;
|
||
// an event without one (an old recording) is the plain fall it always was.
|
||
#[test]
|
||
fn a_replay_shows_the_recorded_outcome() {
|
||
let mut sim = Sim::new(5);
|
||
sim.rec = Some(Recording::new(1, &sim));
|
||
let sam = sim.id();
|
||
sim.sams.push(Sam::new(sam, SamKind::Patriot, DVec3::new(0.0, 70.0, 0.0), 0.0));
|
||
sim.add_drone(DroneKind::Shahed, DVec3::new(0.0, 120.0, 300.0), DVec3::X, DVec3::new(900.0, 70.0, 0.0));
|
||
let at = sim.drones[0].pos;
|
||
let live = sim.shoot_down_by(0, sam, None, Impact::missile(MissileKind::M77n6, at, 6.0), &Ground::default(), &mut Out::default()).unwrap();
|
||
let rec = sim.rec.take().unwrap();
|
||
let recorded = rec.events.iter().find_map(|e| if let EventKind::Kill { outcome, .. } = e.kind { Some(outcome) } else { None });
|
||
assert_eq!(recorded, Some(live), "the live outcome is what was recorded");
|
||
let pieces = |rec: &Recording, t: f64| {
|
||
let mut out = Out::default();
|
||
sim.draw_ghosts(rec, t, 0x5000_0000, &mut out);
|
||
out.models.iter().filter(|m| m.name == "airdef:debris").count()
|
||
};
|
||
let at_tick = rec.events[0].at as f64;
|
||
// The same frame twice is the same (a pure function of the time), and the pieces are the outcome's.
|
||
let mut forced = Recording { events: rec.events.clone(), ..Recording::blank(200) };
|
||
for (outcome, want) in [(Outcome::AirDetonation, true), (Outcome::Breakup, true), (Outcome::DisabledFalling, false)] {
|
||
if let EventKind::Kill { outcome: o, .. } = &mut forced.events[0].kind {
|
||
*o = outcome;
|
||
}
|
||
assert_eq!(pieces(&forced, at_tick + 5.0), pieces(&forced, at_tick + 5.0));
|
||
assert_eq!(pieces(&forced, at_tick + 5.0) > 0, want, "{outcome:?}");
|
||
assert_eq!(pieces(&forced, at_tick + f64::from(outcome::PIECE_LIFE) + 1.0), 0, "the pieces are gone in time");
|
||
}
|
||
// Its flash and sound are the outcome's too.
|
||
let spec = |o| {
|
||
let mut e = rec.events[0];
|
||
if let EventKind::Kill { outcome, .. } = &mut e.kind {
|
||
*outcome = o;
|
||
}
|
||
blast_spec(e.kind)
|
||
};
|
||
assert!(spec(Outcome::AirDetonation).0 > spec(Outcome::DisabledFalling).0);
|
||
assert_eq!(spec(Outcome::default()).0, kill_look(DroneKind::Shahed).0, "an old recording looks as it did");
|
||
}
|
||
|
||
// #150: the by-time readers give exactly the events a full journal filter gave, in order.
|
||
#[test]
|
||
fn time_range_reads_match_the_full_journal_filter() {
|
||
let mut r = recording();
|
||
r.events = vec![
|
||
Event { at: 5, pos: DVec3::X, kind: EventKind::Split { drone: 1 } },
|
||
Event { at: 5, pos: DVec3::Y, kind: EventKind::SamLost { sam: 2, kind: SamKind::Patriot, index: 0 } },
|
||
Event { at: 40, pos: DVec3::Z, kind: EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power: 2, object: Some(0), sam: None } },
|
||
Event { at: 90, pos: DVec3::ZERO, kind: EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: 1 } },
|
||
];
|
||
r.close();
|
||
let indices = |f: &dyn Fn(f64) -> bool| r.events.iter().enumerate().filter(|(_, e)| f(e.at as f64)).map(|(i, _)| i).collect::<Vec<_>>();
|
||
for &(lo, hi) in &[(0.0, 6.0), (5.0, 5.0), (5.0, 40.0), (6.0, 40.0), (0.0, 100.0), (40.5, 90.0), (91.0, 200.0)] {
|
||
let want = indices(&|at| (lo..hi).contains(&at));
|
||
assert_eq!(r.events_between(lo, hi).map(|(i, _)| i).collect::<Vec<_>>(), want, "{lo}..{hi}");
|
||
}
|
||
let want = indices(&|at| at <= 40.0);
|
||
assert_eq!(r.events_until(40.0).map(|(i, _)| i).collect::<Vec<_>>(), want);
|
||
assert_eq!(r.events_until(4.0).count(), 0, "nothing before the first event");
|
||
assert_eq!(r.events_between(200.0, 100.0).count(), 0, "an empty range never runs back");
|
||
}
|
||
|
||
// #150: a journal whose own order is not by time (merged or altered later) is read through
|
||
// the stable index `close` builds; ties keep the order they were recorded in.
|
||
#[test]
|
||
fn an_out_of_order_journal_reads_by_time_with_stable_ties() {
|
||
let mut r = recording();
|
||
let ev = |at, tag: u32| Event { at, pos: DVec3::new(tag as f64, 0.0, 0.0), kind: EventKind::Split { drone: tag } };
|
||
r.events = vec![ev(50, 0), ev(10, 1), ev(50, 2), ev(10, 3), ev(90, 4)];
|
||
r.close();
|
||
let tags = |range: EventRange<'_>| range.map(|(_, e)| match e.kind { EventKind::Split { drone } => drone, _ => unreachable!() }).collect::<Vec<_>>();
|
||
assert_eq!(tags(r.events_between(0.0, 100.0)), vec![1, 3, 0, 2, 4], "by time, ties as recorded");
|
||
assert_eq!(tags(r.events_between(50.0, 91.0)), vec![0, 2, 4]);
|
||
assert_eq!(tags(r.events_until(50.0)), vec![1, 3, 0, 2]);
|
||
// The index is only built for a journal out of order: a recording in order carries none.
|
||
assert!(r.time_order.is_some());
|
||
let mut ordered = recording();
|
||
ordered.events = vec![ev(10, 1), ev(50, 0)];
|
||
ordered.close();
|
||
assert!(ordered.time_order.is_none());
|
||
assert_eq!(ordered.index_bytes(), 0);
|
||
}
|
||
|
||
// #150: the map's counts and each object's first hit come from the index `close` settles.
|
||
#[test]
|
||
fn prefix_counts_and_first_hits_match_the_journal() {
|
||
let kill = |at| Event { at, pos: DVec3::ZERO, kind: EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 1, sam_kind: SamKind::S400, sam_index: 0, missile: None, outcome: Outcome::Breakup } };
|
||
let hit = |at, object, power| Event { at, pos: DVec3::ZERO, kind: EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power, object: Some(object), sam: None } };
|
||
let mut r = recording();
|
||
r.objects = vec![DVec3::ZERO, DVec3::X];
|
||
r.len = 200;
|
||
// The second hit of the first object is recorded before the first: time decides, not order.
|
||
r.events = vec![hit(60, 0, 2), hit(40, 1, 3), kill(20), hit(40, 0, 1), kill(80)];
|
||
r.close();
|
||
for t in [0.0, 19.0, 20.0, 39.9, 40.0, 59.0, 60.0, 79.0, 80.0, 200.0] {
|
||
let kills = r.events.iter().filter(|e| (e.at as f64) <= t && matches!(e.kind, EventKind::Kill { .. })).count();
|
||
let hits = r.events.iter().filter(|e| (e.at as f64) <= t && matches!(e.kind, EventKind::Hit { .. })).count();
|
||
assert_eq!(r.kills_until(t), kills, "kills at {t}");
|
||
assert_eq!(r.hits_until(t), hits, "hits at {t}");
|
||
}
|
||
assert!(!r.object_struck(0, 39.9));
|
||
assert!(r.object_struck(0, 40.0), "the earliest hit, though recorded second");
|
||
assert!(r.object_struck(1, 40.0));
|
||
assert!(!r.object_struck(2, 200.0), "no such object");
|
||
// A recording that was never closed answers from the journal itself.
|
||
let mut open = recording();
|
||
open.objects = vec![DVec3::ZERO];
|
||
open.events = vec![hit(40, 0, 1)];
|
||
assert_eq!((open.kills_until(100.0), open.hits_until(100.0)), (0, 1));
|
||
assert!(open.object_struck(0, 40.0));
|
||
}
|
||
|
||
// #150: a recording that ends gets its by-time answers settled (the sim closes it).
|
||
#[test]
|
||
fn a_finished_recording_settles_its_time_index() {
|
||
let mut sim = Sim::new(1);
|
||
sim.rec = Some(Recording::new(1, &sim));
|
||
sim.record_event(DVec3::ZERO, EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power: 1, object: Some(0), sam: None });
|
||
let r = sim.rec.as_mut().unwrap();
|
||
r.objects = vec![DVec3::ZERO];
|
||
r.quiet = 99;
|
||
sim.record();
|
||
let done = &sim.replays[0];
|
||
assert!(done.closed, "the sim closes a finished recording");
|
||
assert!(!done.object_struck(0, -1.0));
|
||
assert!(done.object_struck(0, 100.0));
|
||
assert_eq!((done.kills_until(100.0), done.hits_until(100.0)), (0, 1));
|
||
}
|
||
|
||
// #150: the scene journal's range reader gives what the full journal filter gave.
|
||
#[test]
|
||
fn scene_time_range_matches_the_full_journal() {
|
||
let mut j = SceneJournal::default();
|
||
for (at, fire) in [(0, 1), (0, 2), (10, 1), (25, 3), (25, 2), (40, 1)] {
|
||
j.push(SceneEvent { at, pos: DVec3::ZERO, kind: SceneKind::FireEnded { fire } });
|
||
}
|
||
for &(lo, hi) in &[(0.0, 1.0), (0.0, 10.0), (10.0, 10.0), (0.0, 26.0), (25.0, 25.5), (26.0, 100.0)] {
|
||
let want: Vec<u32> = j.events().iter().filter(|e| (lo..hi).contains(&(e.at as f64))).map(|e| e.at).collect();
|
||
let got: Vec<u32> = j.events_between(lo, hi).iter().map(|e| e.at).collect();
|
||
assert_eq!(got, want, "{lo}..{hi}");
|
||
}
|
||
}
|
||
|
||
// #150: the blasts (and the smoke) are read in a window back from `t`, not from the whole
|
||
// journal: the same blasts, ids and order as a full scan gives.
|
||
#[test]
|
||
fn blast_windows_hold_the_same_blasts_as_a_full_scan() {
|
||
let mut r = recording();
|
||
r.len = 2000;
|
||
r.events = (0..40)
|
||
.map(|i| Event {
|
||
at: i * 50,
|
||
pos: DVec3::new(i as f64, 70.0, 0.0),
|
||
kind: match i % 4 {
|
||
0 => EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power: (i / 4) as u32 % 5, object: None, sam: None },
|
||
1 => EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: 2 },
|
||
2 => EventKind::SamLost { sam: 3, kind: SamKind::Patriot, index: 0 },
|
||
_ => EventKind::Strike { site: 1, result: StrikeResult::Destroyed },
|
||
},
|
||
})
|
||
.collect();
|
||
r.close();
|
||
let naive = |t: f64, smoke: bool| -> Vec<(u32, u64, u32)> {
|
||
r.events
|
||
.iter()
|
||
.enumerate()
|
||
.filter_map(|(k, e)| {
|
||
let (_, life) = blast_spec(e.kind);
|
||
let age = t - e.at as f64;
|
||
let keep = if smoke { (0.0..=SMOKE_WINDOW).contains(&age) } else { (0.0..life as f64).contains(&age) };
|
||
keep.then_some((0x4000_0000 | k as u32, e.at as u64, life))
|
||
})
|
||
.collect()
|
||
};
|
||
for t in [0.0, 1.0, 49.0, 50.0, 50.5, 100.0, 233.0, 234.0, 235.0, 466.0, 999.5, 1800.0, 2000.0] {
|
||
let got: Vec<_> = replay_blasts(&r, t).iter().map(|b| (b.id, b.start, b.life)).collect();
|
||
assert_eq!(got, naive(t, false), "blasts at {t}");
|
||
let got: Vec<_> = replay_smoke_blasts(&r, t).iter().map(|b| (b.id, b.start, b.life)).collect();
|
||
assert_eq!(got, naive(t, true), "smoke at {t}");
|
||
}
|
||
}
|
||
|
||
// #150: no blast burns longer than the window its read uses.
|
||
#[test]
|
||
fn every_blast_life_fits_the_read_window() {
|
||
for (power, result) in (0..5).map(|p| (p, StrikeResult::Destroyed)) {
|
||
let kinds = [
|
||
EventKind::Hit { drone: 1, kind: DroneKind::Oreshnik, power, object: None, sam: None },
|
||
EventKind::Crash { drone: 1, kind: DroneKind::Oreshnik, power },
|
||
EventKind::SamLost { sam: 1, kind: SamKind::S400, index: 0 },
|
||
EventKind::Split { drone: 1 },
|
||
EventKind::Strike { site: 1, result },
|
||
];
|
||
for kind in kinds {
|
||
assert!(blast_spec(kind).1 <= MAX_BLAST_LIFE, "{kind:?}");
|
||
}
|
||
}
|
||
for outcome in [Outcome::DisabledFalling, Outcome::Breakup, Outcome::AirDetonation] {
|
||
for kind in [DroneKind::Shahed, DroneKind::Kinzhal, DroneKind::Oreshnik, DroneKind::OreshnikSub] {
|
||
let e = EventKind::Kill { drone: 1, kind, sam: 1, sam_kind: SamKind::S400, sam_index: 0, missile: None, outcome };
|
||
assert!(blast_spec(e).1 <= MAX_BLAST_LIFE, "{kind:?} {outcome:?}");
|
||
}
|
||
}
|
||
}
|
||
}
|