Files
airdef/airdef-mod/examples/replay_bench.rs
T
chexit 5f00a2a16b 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>
2026-11-21 09:52:20 +03:00

262 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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!("]");
}