Read replay events by their time ranges, not the whole journal (#150)
The replay's sounds, the raid map's counts and the struck objects now read the recording's event and scene journals by time instead of every pass over the whole journal: partition points over the journals (with a stable time index built at close only when a journal is out of order), the map's kill and hit prefix indices, each object's first hit, and marker/time-line paths that stop at the map's shape cap. Blasts, smoke, debris and the fire replay read bounded windows back from the moment. The sets, order and names stay exactly as they were: tests compare every reader against the full journal filter, including tied times, out-of-order journals and arbitrary forward and back seeks. The replay_bench example measures a 10-minute raid with nearly full journals (playback, reverse seek, pause, MP4); its result is docs/measurements/issue-150-replay-ranges.json. Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
@@ -9,5 +9,7 @@ glam = "0.30"
|
||||
|
||||
[features]
|
||||
test-fixtures = []
|
||||
# Counts the events the by-time journal readers hand out (the `replay_bench` example).
|
||||
bench-counters = []
|
||||
|
||||
[workspace]
|
||||
|
||||
@@ -8,6 +8,10 @@ description = "AirDef: long-range drones and air defence for the AirDef fork of
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[features]
|
||||
# Counts the events the by-time readers hand out (the `replay_bench` example); off in the mod build.
|
||||
bench-counters = ["airdef-core/bench-counters"]
|
||||
|
||||
[dependencies]
|
||||
airdef-core = { path = "../airdef-core" }
|
||||
horizon-mod-sdk = { path = "../horizon/crates/horizon-mod-sdk" }
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
//! Replay hot-path benchmark (#150): a 10-minute raid with its journals almost full.
|
||||
//!
|
||||
//! Plays the recording the ways a player does — ordinary playback, reverse seeks, a pause and
|
||||
//! an MP4 export (the director's film) — and reports the CPU per frame (p50/p95/p99) and the
|
||||
//! events the by-time readers handed out. Run it with the counters built in:
|
||||
//!
|
||||
//! cargo run --release --example replay_bench --features bench-counters
|
||||
//!
|
||||
//! Without `bench-counters` the scanned-events numbers read 0. Native timings compare runs on
|
||||
//! one machine; they say nothing about the WASM build or the GPU.
|
||||
use airdef::film::{Film, Which};
|
||||
use airdef::replay::{Control, Mode, Player};
|
||||
use airdef::sim::record::{Event, EventKind, Recording, SceneEvent, SceneJournal, SceneKind, StrikeResult, What};
|
||||
use airdef::sim::{DroneKind, Ground, MissileKind, Out, SamKind, Sim};
|
||||
use glam::DVec3;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The longest recording, ticks (10 minutes at 20 a second).
|
||||
const TICKS: u32 = 12_000;
|
||||
/// The event journal's cap, and the scene journal's (`MAX_SCENE_EVENTS`), nearly reached.
|
||||
const EVENTS: usize = 64_000;
|
||||
const SCENE: usize = 65_000;
|
||||
/// Frames measured per mode (20 a second, half a minute of playback; a film frame is 0.05 s).
|
||||
const FRAMES: usize = 600;
|
||||
const LISTENER: DVec3 = DVec3::new(0.0, 70.0, 0.0);
|
||||
|
||||
/// A 10-minute raid's recording: 200 flights, a nearly full event journal and scene journal,
|
||||
/// the objects, systems, tracks and the fires — the journal a busy raid leaves.
|
||||
fn recording() -> Recording {
|
||||
let mut rec = Recording::blank(TICKS);
|
||||
rec.number = 1;
|
||||
rec.len = TICKS;
|
||||
rec.origin = DVec3::ZERO;
|
||||
rec.sams = (0..8).map(|i| (10 + i, SamKind::S400, DVec3::new(i as f64 * 120.0, 64.0, 400.0))).collect();
|
||||
rec.objects = (0..8).map(|i| DVec3::new(i as f64 * 90.0, 70.0, 0.0)).collect();
|
||||
// 200 flights, each a few hundred ticks of the raid (a point every 2 ticks): the map and
|
||||
// the ghosts draw them, the sounds read their launches.
|
||||
for k in 0..200u32 {
|
||||
let first = k * 55 % (TICKS - 700);
|
||||
let last = first + 600;
|
||||
let what = match k % 4 {
|
||||
0 => What::Drone(DroneKind::Geran3),
|
||||
1 => What::Drone(DroneKind::Shahed),
|
||||
2 => What::Missile(MissileKind::M48n6, 10 + k % 8),
|
||||
_ => What::Strike,
|
||||
};
|
||||
rec.straight(1000 + k, what, first, last, DVec3::new(-2000.0, 100.0, k as f64 * 5.0), DVec3::new(500.0, 70.0, k as f64 * 5.0));
|
||||
}
|
||||
// The events: interceptions, hits, losses and splits spread through the raid.
|
||||
rec.events = (0..EVENTS)
|
||||
.map(|i| {
|
||||
let at = (i as u64 * u64::from(TICKS) / EVENTS as u64) as u32;
|
||||
let drone = 1000 + (i as u32 * 7 % 200);
|
||||
let pos = DVec3::new((i % 40) as f64 * 10.0, 95.0, (i % 17) as f64 * 12.0);
|
||||
let kind = match i % 10 {
|
||||
0 | 1 => EventKind::Kill { drone, kind: DroneKind::Geran3, sam: 10, sam_kind: SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() },
|
||||
2 | 3 => EventKind::Hit { drone, kind: DroneKind::Geran3, power: (i % 5) as u32, object: Some(i % 8), sam: None },
|
||||
4 | 5 => EventKind::Crash { drone, kind: DroneKind::Geran3, power: (i % 5) as u32 },
|
||||
6 => EventKind::SamLost { sam: 10 + (i % 8) as u32, kind: SamKind::S400, index: i % 8 },
|
||||
7 => EventKind::Split { drone },
|
||||
_ => EventKind::Strike { site: 1, result: StrikeResult::Destroyed },
|
||||
};
|
||||
Event { at, pos, kind }
|
||||
})
|
||||
.collect();
|
||||
// The scene journal: launches and ignitions (the exact sounds), track changes and fires.
|
||||
let mut scene = SceneJournal::default();
|
||||
for i in 0..SCENE {
|
||||
let at = (i as u64 * u64::from(TICKS) / SCENE as u64) as u32;
|
||||
let missile = 5000 + (i as u32 % 300);
|
||||
let pos = DVec3::new((i % 30) as f64 * 8.0, 66.0, 300.0);
|
||||
let kind = match i % 100 {
|
||||
// Fires are a small share of a raid's transitions (hundreds over ten minutes).
|
||||
0 => SceneKind::FireStarted { fire: (i / 100) as u32, age: 0, life: 4000, size: 1.0, quiet: false, shown: true, water: Some(false) },
|
||||
1 => SceneKind::FireEnded { fire: (i / 100) as u32 },
|
||||
2 | 3 => SceneKind::MissileLaunch { missile, sam: 10, target: 2000, kind: MissileKind::M48n6, sound: "airdef:launch.s400", pitch: 1.0 },
|
||||
4 | 5 => SceneKind::MotorIgnition { missile, kind: MissileKind::M48n6, sound: Some("airdef:launch.s400") },
|
||||
6 => SceneKind::MotorBurnout { missile, kind: MissileKind::M48n6 },
|
||||
7 => SceneKind::MotorEnergyLost { missile, kind: MissileKind::M48n6, speed: 4.0 },
|
||||
8 | 9 => SceneKind::TrackAcquired { sam: 10, target: 2000 + (i as u32 % 200), ever_own: true },
|
||||
_ => SceneKind::TrackLost { sam: 10, target: 2000 + (i as u32 % 200) },
|
||||
};
|
||||
scene.fixture_push(SceneEvent { at, pos, kind });
|
||||
}
|
||||
rec.scene = Some(scene);
|
||||
rec.close();
|
||||
rec
|
||||
}
|
||||
|
||||
/// Answers the ground queries the replays make with a flat 70-block land, as the game would.
|
||||
fn settle(ground: &mut Ground, now: u64) {
|
||||
let wanted = ground.take_wanted();
|
||||
if !wanted.is_empty() {
|
||||
ground.answer(wanted.into_iter().map(|(x, z)| (x, z, 70)).collect(), now);
|
||||
}
|
||||
}
|
||||
|
||||
fn percentile(sorted: &[Duration], p: f64) -> f64 {
|
||||
if sorted.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let i = (((sorted.len() - 1) as f64) * p).round() as usize;
|
||||
sorted[i].as_secs_f64() * 1e6
|
||||
}
|
||||
|
||||
struct Measured {
|
||||
mode: &'static str,
|
||||
frames: usize,
|
||||
scanned: u64,
|
||||
cpu: Vec<Duration>,
|
||||
}
|
||||
|
||||
impl Measured {
|
||||
fn cpu_p(&self, p: f64) -> f64 {
|
||||
let mut sorted = self.cpu.clone();
|
||||
sorted.sort_unstable();
|
||||
percentile(&sorted, p)
|
||||
}
|
||||
fn json(&self, rec: &Recording, sim: &Sim) -> String {
|
||||
let events_bytes = rec.events.capacity() * std::mem::size_of::<Event>();
|
||||
let scene_events = rec.scene.as_ref().map_or(0, |s| s.events().len());
|
||||
let scene_bytes = scene_events * std::mem::size_of::<SceneEvent>();
|
||||
let index_bytes: usize = sim.replays.iter().map(Recording::index_bytes).sum();
|
||||
format!(
|
||||
"{{\"mode\":\"{}\",\"frames\":{},\"journal_events\":{},\"journal_scene\":{},\
|
||||
\"scanned_events\":{},\"scanned_per_frame\":{:.1},\"full_pass_events\":{},\
|
||||
\"p50_us\":{:.1},\"p95_us\":{:.1},\"p99_us\":{:.1},\"max_us\":{:.1},\
|
||||
\"events_bytes\":{},\"scene_bytes\":{},\"index_bytes\":{}}}",
|
||||
self.mode,
|
||||
self.frames,
|
||||
rec.events.len(),
|
||||
scene_events,
|
||||
self.scanned,
|
||||
self.scanned as f64 / self.frames.max(1) as f64,
|
||||
// One whole-journal pass per frame: what the readers did before the ranges (#150).
|
||||
(rec.events.len() + scene_events) as u64 * self.frames as u64,
|
||||
self.cpu_p(0.50),
|
||||
self.cpu_p(0.95),
|
||||
self.cpu_p(0.99),
|
||||
self.cpu.iter().copied().max().unwrap_or_default().as_secs_f64() * 1e6,
|
||||
events_bytes,
|
||||
scene_bytes,
|
||||
index_bytes,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Steps the replay's clock to `t` the way the wheel does (5 s a press), so the seek resets the
|
||||
/// sound cursor and the shot as a player's would.
|
||||
fn seek_to(p: &mut Player, rec: &Recording, t: f64) {
|
||||
for _ in 0..((t.max(0.0) / 100.0) as usize) {
|
||||
p.control(Control::Forward, rec);
|
||||
}
|
||||
}
|
||||
|
||||
fn sim_with(rec: Recording) -> (Sim, u64) {
|
||||
let mut sim = Sim::new(1);
|
||||
sim.replays.push(rec);
|
||||
(sim, 1)
|
||||
}
|
||||
|
||||
/// Ordinary playback from a moment near the end of the raid, time running at ×2.
|
||||
fn playback() -> Measured {
|
||||
let (sim, mut tick) = sim_with(recording());
|
||||
let rec = &sim.replays[0];
|
||||
let mut p = Player::new(1, Mode::Full, &sim);
|
||||
seek_to(&mut p, rec, rec.len as f64 - 1_200.0);
|
||||
let mut ground = Ground::default();
|
||||
let mut out = Out::default();
|
||||
let _ = airdef::sim::record::scanned_events();
|
||||
let mut cpu = Vec::with_capacity(FRAMES);
|
||||
for _ in 0..FRAMES {
|
||||
let started = Instant::now();
|
||||
p.tick(&sim, &mut ground, LISTENER, &mut out);
|
||||
settle(&mut ground, tick);
|
||||
tick += 1;
|
||||
cpu.push(started.elapsed());
|
||||
out = Out::default();
|
||||
}
|
||||
Measured { mode: "playback", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
|
||||
}
|
||||
|
||||
/// Reverse seeks: five seconds back every frame, then a frame of playback.
|
||||
fn reverse_seek() -> Measured {
|
||||
let (sim, mut tick) = sim_with(recording());
|
||||
let rec = &sim.replays[0];
|
||||
let mut p = Player::new(1, Mode::Full, &sim);
|
||||
seek_to(&mut p, rec, rec.len as f64 - 200.0);
|
||||
let mut ground = Ground::default();
|
||||
let mut out = Out::default();
|
||||
let _ = airdef::sim::record::scanned_events();
|
||||
let mut cpu = Vec::with_capacity(FRAMES);
|
||||
for _ in 0..FRAMES {
|
||||
let started = Instant::now();
|
||||
p.control(Control::Back, rec);
|
||||
p.tick(&sim, &mut ground, LISTENER, &mut out);
|
||||
settle(&mut ground, tick);
|
||||
tick += 1;
|
||||
cpu.push(started.elapsed());
|
||||
out = Out::default();
|
||||
}
|
||||
Measured { mode: "reverse_seek", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
|
||||
}
|
||||
|
||||
/// A pause held while frames keep coming (the HUD and the ghosts stay, nothing sounds).
|
||||
fn paused() -> Measured {
|
||||
let (sim, mut tick) = sim_with(recording());
|
||||
let rec = &sim.replays[0];
|
||||
let mut p = Player::new(1, Mode::Full, &sim);
|
||||
seek_to(&mut p, rec, rec.len as f64 * 0.75);
|
||||
p.control(Control::Pause, rec);
|
||||
let mut ground = Ground::default();
|
||||
let mut out = Out::default();
|
||||
let _ = airdef::sim::record::scanned_events();
|
||||
let mut cpu = Vec::with_capacity(FRAMES);
|
||||
for _ in 0..FRAMES {
|
||||
let started = Instant::now();
|
||||
p.tick(&sim, &mut ground, LISTENER, &mut out);
|
||||
settle(&mut ground, tick);
|
||||
tick += 1;
|
||||
cpu.push(started.elapsed());
|
||||
out = Out::default();
|
||||
}
|
||||
Measured { mode: "pause", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
|
||||
}
|
||||
|
||||
/// An MP4 export: the director's film, its frames prepared and drawn as the game records them.
|
||||
fn mp4() -> Measured {
|
||||
let (sim, mut tick) = sim_with(recording());
|
||||
let rec = &sim.replays[0];
|
||||
let film = Film::build(rec, Which::Best).expect("the raid has moments to film");
|
||||
let mut p = Player::new(1, Mode::Film(Box::new(film)), &sim);
|
||||
p.wait = true;
|
||||
p.clean = true;
|
||||
let mut ground = Ground::default();
|
||||
let mut out = Out::default();
|
||||
let _ = airdef::sim::record::scanned_events();
|
||||
let mut cpu = Vec::with_capacity(FRAMES);
|
||||
for _ in 0..FRAMES {
|
||||
let started = Instant::now();
|
||||
p.tick(&sim, &mut ground, LISTENER, &mut out);
|
||||
settle(&mut ground, tick);
|
||||
tick += 1;
|
||||
cpu.push(started.elapsed());
|
||||
out = Out::default();
|
||||
}
|
||||
Measured { mode: "mp4", frames: FRAMES, scanned: airdef::sim::record::scanned_events(), cpu }
|
||||
}
|
||||
|
||||
pub fn main() {
|
||||
let (playback, reverse_seek, paused, mp4) = (playback(), reverse_seek(), paused(), mp4());
|
||||
let (sim, _) = sim_with(recording());
|
||||
let rec = &sim.replays[0];
|
||||
if !airdef::sim::record::scan_counters() {
|
||||
eprintln!("replay_bench: scanned events read 0; rerun with --features bench-counters");
|
||||
}
|
||||
let rows = [playback.json(rec, &sim), reverse_seek.json(rec, &sim), paused.json(rec, &sim), mp4.json(rec, &sim)];
|
||||
println!("[");
|
||||
println!("{}", rows.join(",\n"));
|
||||
println!("]");
|
||||
}
|
||||
@@ -19,14 +19,14 @@ mod engines;
|
||||
mod commands;
|
||||
mod layout;
|
||||
mod map;
|
||||
mod film;
|
||||
pub mod film;
|
||||
mod monitor;
|
||||
mod overlay;
|
||||
mod panel;
|
||||
mod presentation;
|
||||
mod radar;
|
||||
mod recon_view;
|
||||
mod replay;
|
||||
pub mod replay;
|
||||
mod scene;
|
||||
mod smoke;
|
||||
pub use airdef_core::sim;
|
||||
|
||||
+135
-27
@@ -596,7 +596,7 @@ impl Player {
|
||||
/// Sounds as the camera hears them: moved so the player stands where the camera is.
|
||||
fn sounds(&mut self, rec: &Recording, listener: DVec3, out: &mut Out) {
|
||||
let heard = |p: DVec3| listener + (p - self.eye);
|
||||
for e in rec.events.iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) {
|
||||
for (_, e) in rec.events_between(self.heard, self.t) {
|
||||
let event = match e.kind {
|
||||
EventKind::Kill { kind, outcome, .. } => crate::sim::outcome::look(kind, outcome).3,
|
||||
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
|
||||
@@ -617,7 +617,7 @@ impl Player {
|
||||
}
|
||||
// New recordings carry the exact launch and ignition sounds and their actual positions.
|
||||
if let Some(scene) = &rec.scene {
|
||||
for e in scene.events().iter().filter(|e| (self.heard..self.t).contains(&(e.at as f64))) {
|
||||
for e in scene.events_between(self.heard, self.t) {
|
||||
match e.kind {
|
||||
crate::sim::record::SceneKind::MissileLaunch { sound, pitch, .. } => out.sound(sound, heard(e.pos), 1.0, pitch),
|
||||
crate::sim::record::SceneKind::MotorIgnition { sound: Some(sound), .. } => out.sound(sound, heard(e.pos), 1.0, 1.0),
|
||||
@@ -844,9 +844,9 @@ impl Player {
|
||||
// The full replay follows what comes next: the next event within 6 s, else the drone
|
||||
// nearest its target.
|
||||
Mode::Full => rec
|
||||
.events
|
||||
.iter()
|
||||
.position(|e| (self.t - 30.0..self.t + 120.0).contains(&(e.at as f64)))
|
||||
.events_between(self.t - 30.0, self.t + 120.0)
|
||||
.next()
|
||||
.map(|(i, _)| i)
|
||||
.or(if self.shot.0 != usize::MAX && (rec.events[self.shot.0].at as f64) > self.t - 60.0 { Some(self.shot.0) } else { None }),
|
||||
Mode::Map | Mode::Film(_) => None,
|
||||
};
|
||||
@@ -1070,29 +1070,13 @@ impl Player {
|
||||
s.push(fill(prev.0 - 1.5, prev.1 - 1.5, 3.0, 3.0, head));
|
||||
}
|
||||
}
|
||||
// Events so far.
|
||||
for e in rec.events.iter().filter(|e| (e.at as f64) <= self.t) {
|
||||
let (x, y) = at(e.pos);
|
||||
if !inside((x, y)) {
|
||||
continue;
|
||||
}
|
||||
match e.kind {
|
||||
EventKind::Kill { .. } => {
|
||||
s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040));
|
||||
s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040));
|
||||
}
|
||||
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
|
||||
let r = 2.0 + power as f32;
|
||||
s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020));
|
||||
}
|
||||
EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)),
|
||||
EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)),
|
||||
EventKind::Strike { .. } => s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFA040)),
|
||||
}
|
||||
}
|
||||
// Events so far, in their order. The header's counts come from the recording's prefix
|
||||
// index, not from walking the journal again; past the shape cap nothing drawn here
|
||||
// survives `truncate`.
|
||||
s.extend(event_marks(rec, self.t, &at, &inside, 1024usize.saturating_sub(s.len())));
|
||||
// Header, legend, time line.
|
||||
let kills = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Kill { .. })).count();
|
||||
let hits = rec.events.iter().filter(|e| (e.at as f64) <= self.t && matches!(e.kind, EventKind::Hit { .. })).count();
|
||||
let kills = rec.kills_until(self.t);
|
||||
let hits = rec.hits_until(self.t);
|
||||
let state = if self.paused { "ПАУЗА".to_string() } else { format!("×{}", self.speed) };
|
||||
s.push(text(format!("КАРТА НАЛЁТА №{} · {} / {} {state} · сбито {kills} · прилётов {hits}", rec.number, clock(self.t), clock(rec.len as f64)), 8.0, 6.0, 0xFF9FE0FF, false));
|
||||
let legend = "красный: цели · серый: ложные · жёлтый: перехватчики · x сбит · квадрат: прилёт";
|
||||
@@ -1111,6 +1095,10 @@ impl Player {
|
||||
s.push(fill(tx, ty, tw, 3.0, 0x60FFFFFF));
|
||||
let len = rec.len.max(1) as f32;
|
||||
for e in &rec.events {
|
||||
// The line is cut at 1024 shapes: past that, a mark would not be kept.
|
||||
if s.len() >= 1024 {
|
||||
break;
|
||||
}
|
||||
let x = tx + tw * e.at as f32 / len;
|
||||
let c = match e.kind {
|
||||
EventKind::Kill { .. } => 0xFFFFE040,
|
||||
@@ -1128,6 +1116,42 @@ impl Player {
|
||||
}
|
||||
}
|
||||
|
||||
/// The marks of the events up to `t` on the raid map, in the order they happened: a kill as a
|
||||
/// cross, a hit as a square, a lost system as a dark square, a split and a strike as dots. Reads
|
||||
/// the journal by time (`events_until`) and stops at `room` shapes, the rest of the map's cap.
|
||||
fn event_marks(
|
||||
rec: &Recording,
|
||||
t: f64,
|
||||
at: &impl Fn(DVec3) -> (f32, f32),
|
||||
inside: &impl Fn((f32, f32)) -> bool,
|
||||
room: usize,
|
||||
) -> Vec<Shape> {
|
||||
let mut s = Vec::new();
|
||||
for (_, e) in rec.events_until(t) {
|
||||
if s.len() >= room {
|
||||
break;
|
||||
}
|
||||
let (x, y) = at(e.pos);
|
||||
if !inside((x, y)) {
|
||||
continue;
|
||||
}
|
||||
match e.kind {
|
||||
EventKind::Kill { .. } => {
|
||||
s.push(line((x - 2.5, y - 2.5), (x + 2.5, y + 2.5), 1.2, 0xFFFFE040));
|
||||
s.push(line((x + 2.5, y - 2.5), (x - 2.5, y + 2.5), 1.2, 0xFFFFE040));
|
||||
}
|
||||
EventKind::Hit { power, .. } | EventKind::Crash { power, .. } => {
|
||||
let r = 2.0 + power as f32;
|
||||
s.push(fill(x - r, y - r, r * 2.0, r * 2.0, 0xB0FF3020));
|
||||
}
|
||||
EventKind::SamLost { .. } => s.push(fill(x - 4.0, y - 4.0, 8.0, 8.0, 0xFF200000)),
|
||||
EventKind::Split { .. } => s.push(fill(x - 2.0, y - 2.0, 4.0, 4.0, 0xFFFF9020)),
|
||||
EventKind::Strike { .. } => s.push(fill(x - 3.0, y - 3.0, 6.0, 6.0, 0xFFFFA040)),
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The ground the map shows, as [lo x, lo z, hi x, hi z]: everything that
|
||||
/// flew (not the ballistic falls), with the systems and objects, or round the
|
||||
/// origin when nothing did.
|
||||
@@ -1432,6 +1456,90 @@ mod engine_tests {
|
||||
assert!(host.0.is_empty());
|
||||
}
|
||||
|
||||
// #150: the sounds of a window are exactly the events it holds: the same set, order and
|
||||
// names after any seek, forward or back, empty or spanning ties.
|
||||
#[test]
|
||||
fn event_sounds_are_exactly_the_events_of_the_window_after_any_seek() {
|
||||
use crate::sim::catalog::sound;
|
||||
use crate::sim::record::{Event, EventKind};
|
||||
let mut rec = Recording::blank(1000);
|
||||
rec.events = [10u32, 10, 25, 40, 40, 40, 75, 130]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, at)| Event {
|
||||
at,
|
||||
pos: DVec3::new(i as f64, 80.0, 0.0),
|
||||
kind: EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: (i % 5) as u32 },
|
||||
})
|
||||
.collect();
|
||||
let names = |lo: f64, hi: f64| -> Vec<&'static str> {
|
||||
rec.events
|
||||
.iter()
|
||||
.filter(|e| (lo..hi).contains(&(e.at as f64)))
|
||||
.map(|e| match e.kind {
|
||||
EventKind::Crash { power, .. } => [sound::BLAST_AIR, sound::BLAST_MEDIUM, sound::BLAST_BIG, sound::BLAST_HEAVY, sound::BLAST_HUGE][(power as usize).min(4)],
|
||||
_ => unreachable!(),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut p = player(&rec);
|
||||
let mut out = Out::default();
|
||||
for &(heard, t) in &[(0.0, 11.0), (10.0, 10.0), (11.0, 25.0), (10.0, 40.0), (25.0, 40.5), (40.0, 41.0), (40.0, 75.0), (75.0, 130.5), (130.0, 0.0), (41.0, 25.0), (10.5, 40.0)] {
|
||||
out.sounds.clear();
|
||||
p.heard = heard;
|
||||
p.t = t;
|
||||
p.sounds(&rec, DVec3::ZERO, &mut out);
|
||||
let got: Vec<&'static str> = out.sounds.iter().map(|s| s.0).collect();
|
||||
assert_eq!(got, names(heard, t), "{heard}..{t}");
|
||||
}
|
||||
}
|
||||
|
||||
// #150: the map draws every event up to now, in its order, and reads only that far.
|
||||
#[test]
|
||||
fn the_map_marks_the_events_up_to_now_in_their_order() {
|
||||
use crate::sim::record::{Event, EventKind, StrikeResult};
|
||||
let ev = |at, kind| Event { at, pos: DVec3::new(at as f64, 0.0, 0.0), kind };
|
||||
let mut rec = Recording::blank(1000);
|
||||
rec.events = vec![
|
||||
ev(100, EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 1, sam_kind: crate::sim::SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() }),
|
||||
ev(200, EventKind::Hit { drone: 1, kind: DroneKind::Geran3, power: 2, object: None, sam: None }),
|
||||
ev(300, EventKind::Crash { drone: 1, kind: DroneKind::Geran3, power: 1 }),
|
||||
ev(400, EventKind::SamLost { sam: 1, kind: crate::sim::SamKind::S400, index: 0 }),
|
||||
ev(500, EventKind::Split { drone: 1 }),
|
||||
ev(600, EventKind::Strike { site: 1, result: StrikeResult::Stunned }),
|
||||
ev(900, EventKind::Kill { drone: 1, kind: DroneKind::Geran3, sam: 1, sam_kind: crate::sim::SamKind::S400, sam_index: 0, missile: None, outcome: Default::default() }),
|
||||
];
|
||||
rec.close();
|
||||
let at = |p: DVec3| (p.x as f32, 0.0);
|
||||
let all = |_: (f32, f32)| true;
|
||||
let colors = |shapes: Vec<Shape>| shapes
|
||||
.iter()
|
||||
.map(|s| match s {
|
||||
Shape::Fill(f) => f.color,
|
||||
Shape::Quad(q) => q.color,
|
||||
_ => 0,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
// The kill's cross, then the hit, the crash, the lost system and the split: the earlier
|
||||
// events only, in their order.
|
||||
assert_eq!(
|
||||
colors(event_marks(&rec, 500.0, &at, &all, usize::MAX)),
|
||||
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020, 0xB0FF3020, 0xFF200000, 0xFFFF9020]
|
||||
);
|
||||
assert_eq!(
|
||||
colors(event_marks(&rec, 600.0, &at, &all, usize::MAX)),
|
||||
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020, 0xB0FF3020, 0xFF200000, 0xFFFF9020, 0xFFFFA040]
|
||||
);
|
||||
// The map's shape cap stops the reading; nothing past it would be kept anyway.
|
||||
assert_eq!(event_marks(&rec, 600.0, &at, &all, 3).len(), 3);
|
||||
// What lies outside the map is skipped, the rest keeps its order.
|
||||
let left = |(x, _): (f32, f32)| x < 250.0;
|
||||
assert_eq!(
|
||||
colors(event_marks(&rec, 600.0, &at, &left, usize::MAX)),
|
||||
vec![0xFFFFE040, 0xFFFFE040, 0xB0FF3020]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_replay_is_silent() {
|
||||
let rec = recording();
|
||||
|
||||
+410
-33
@@ -179,6 +179,11 @@ impl Recording {
|
||||
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`).
|
||||
@@ -388,10 +393,22 @@ impl SceneJournal {
|
||||
/// 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; }
|
||||
let index = self.events.len();
|
||||
match event.kind {
|
||||
@@ -405,6 +422,74 @@ impl SceneJournal {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -493,6 +578,17 @@ pub struct Recording {
|
||||
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.
|
||||
@@ -578,6 +674,12 @@ pub fn strike_power(result: StrikeResult) -> u32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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];
|
||||
@@ -616,13 +718,18 @@ pub fn replay_smoke_blasts(rec: &Recording, t: f64) -> Vec<Blast> {
|
||||
}
|
||||
|
||||
fn replay_blasts_from_events(rec: &Recording, t: f64, keep_expired: bool) -> Vec<Blast> {
|
||||
rec.events
|
||||
.iter()
|
||||
.enumerate()
|
||||
// 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..=900.0).contains(&age) } else { (0.0..life as f64).contains(&age) })
|
||||
(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()
|
||||
@@ -634,9 +741,12 @@ fn replay_blasts_from_events(rec: &Recording, t: f64, keep_expired: bool) -> Vec
|
||||
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();
|
||||
for &index in &scene.fire_events {
|
||||
// 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];
|
||||
if e.at as f64 > t { break; }
|
||||
match e.kind {
|
||||
SceneKind::FireStarted { fire, age, life, size, quiet, shown, water }
|
||||
| SceneKind::FireChanged { fire, age, life, size, quiet, shown, water } => {
|
||||
@@ -651,10 +761,7 @@ pub fn replay_fires(rec: &Recording, t: f64) -> Vec<ReplayFire> {
|
||||
return fires;
|
||||
}
|
||||
let mut fires: Vec<ReplayFire> = Vec::new();
|
||||
for (k, e) in rec.events.iter().enumerate() {
|
||||
if e.at as f64 > t {
|
||||
break;
|
||||
}
|
||||
for (k, e) in rec.events_until(t) {
|
||||
let power = match e.kind {
|
||||
EventKind::Crash { power, .. } => power,
|
||||
EventKind::Hit { power, .. } => power.max(1),
|
||||
@@ -697,8 +804,130 @@ impl Recording {
|
||||
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.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)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -1092,6 +1321,7 @@ impl Sim {
|
||||
{
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -1168,6 +1398,7 @@ impl Sim {
|
||||
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()) {
|
||||
self.replays.push(done);
|
||||
if self.replays.len() > KEPT {
|
||||
@@ -1257,7 +1488,7 @@ impl Sim {
|
||||
}
|
||||
// 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.events.iter().any(|e| e.at as f64 <= t && matches!(e.kind, EventKind::Hit { object: Some(o), .. } if o == i));
|
||||
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);
|
||||
@@ -1280,7 +1511,7 @@ impl Sim {
|
||||
}
|
||||
// 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.iter().enumerate() {
|
||||
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) {
|
||||
@@ -1308,7 +1539,7 @@ impl Sim {
|
||||
if self.shader {
|
||||
return;
|
||||
}
|
||||
for (k, e) in rec.events.iter().enumerate() {
|
||||
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;
|
||||
@@ -1381,26 +1612,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn recording() -> Recording {
|
||||
Recording {
|
||||
number: 1,
|
||||
origin: DVec3::ZERO,
|
||||
len: 0,
|
||||
tracks: Vec::new(),
|
||||
index: HashMap::new(),
|
||||
events: Vec::new(),
|
||||
scene: None,
|
||||
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,
|
||||
ticks: Vec::new(),
|
||||
times: Vec::new(),
|
||||
quiet: 0,
|
||||
}
|
||||
Recording::blank(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1959,4 +2171,169 @@ mod tests {
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"issue": 150,
|
||||
"world": "ReplayRanges150",
|
||||
"branch": "agent/150-replay-ranges",
|
||||
"code_commit": "agent/150-replay-ranges (this branch; see git log for the exact SHA)",
|
||||
"bench": "cargo run --release --example replay_bench --features bench-counters (airdef-mod; native, one machine)",
|
||||
"journal": {
|
||||
"ticks": 12000,
|
||||
"seconds": 600,
|
||||
"events": 64000,
|
||||
"scene_events": 65000,
|
||||
"cap_events": 65536,
|
||||
"cap_scene_events": 65536,
|
||||
"note": "a 10-minute raid with both journals nearly full"
|
||||
},
|
||||
"modes": [
|
||||
{
|
||||
"mode": "playback",
|
||||
"frames": 600,
|
||||
"journal_events": 64000,
|
||||
"journal_scene": 65000,
|
||||
"scanned_events": 1203211,
|
||||
"scanned_per_frame": 2005.4,
|
||||
"full_pass_events": 77400000,
|
||||
"p50_us": 32.3,
|
||||
"p95_us": 40.8,
|
||||
"p99_us": 56.5,
|
||||
"max_us": 127.5,
|
||||
"events_bytes": 5120000,
|
||||
"scene_bytes": 4680000,
|
||||
"index_bytes": 131136
|
||||
},
|
||||
{
|
||||
"mode": "reverse_seek",
|
||||
"frames": 600,
|
||||
"journal_events": 64000,
|
||||
"journal_scene": 65000,
|
||||
"scanned_events": 195747,
|
||||
"scanned_per_frame": 326.2,
|
||||
"full_pass_events": 77400000,
|
||||
"p50_us": 3.1,
|
||||
"p95_us": 23.7,
|
||||
"p99_us": 26.3,
|
||||
"max_us": 45.9,
|
||||
"events_bytes": 5120000,
|
||||
"scene_bytes": 4680000,
|
||||
"index_bytes": 131136
|
||||
},
|
||||
{
|
||||
"mode": "pause",
|
||||
"frames": 600,
|
||||
"journal_events": 64000,
|
||||
"journal_scene": 65000,
|
||||
"scanned_events": 1034400,
|
||||
"scanned_per_frame": 1724.0,
|
||||
"full_pass_events": 77400000,
|
||||
"p50_us": 19.8,
|
||||
"p95_us": 20.5,
|
||||
"p99_us": 22.5,
|
||||
"max_us": 40.2,
|
||||
"events_bytes": 5120000,
|
||||
"scene_bytes": 4680000,
|
||||
"index_bytes": 131136
|
||||
},
|
||||
{
|
||||
"mode": "mp4",
|
||||
"frames": 600,
|
||||
"journal_events": 64000,
|
||||
"journal_scene": 65000,
|
||||
"scanned_events": 8386,
|
||||
"scanned_per_frame": 14.0,
|
||||
"full_pass_events": 77400000,
|
||||
"p50_us": 1.6,
|
||||
"p95_us": 1.9,
|
||||
"p99_us": 4.1,
|
||||
"max_us": 90.6,
|
||||
"events_bytes": 5120000,
|
||||
"scene_bytes": 4680000,
|
||||
"index_bytes": 131136
|
||||
}
|
||||
],
|
||||
"meaning": {
|
||||
"scanned_events": "events the by-time readers handed out (bench-counters); before #150 each sound, map-count and object-strike read the whole journal",
|
||||
"full_pass_events": "one whole-journal pass per measured frame, for scale: the readers did several per frame before #150",
|
||||
"p50_us/p95_us/p99_us/max_us": "CPU per frame (playback at x2, 600 frames = 30 s)",
|
||||
"index_bytes": "memory the by-time index adds (kill/hit indices, first hits, and the stable order only for a journal out of time order)"
|
||||
},
|
||||
"equivalence": [
|
||||
"airdef-core: sim::record::tests::time_range_reads_match_the_full_journal_filter",
|
||||
"airdef-core: sim::record::tests::an_out_of_order_journal_reads_by_time_with_stable_ties",
|
||||
"airdef-core: sim::record::tests::prefix_counts_and_first_hits_match_the_journal",
|
||||
"airdef-core: sim::record::tests::scene_time_range_matches_the_full_journal",
|
||||
"airdef-core: sim::record::tests::blast_windows_hold_the_same_blasts_as_a_full_scan",
|
||||
"airdef: replay::engine_tests::event_sounds_are_exactly_the_events_of_the_window_after_any_seek",
|
||||
"airdef: replay::engine_tests::the_map_marks_the_events_up_to_now_in_their_order"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user