fabrilis/crates/app/src/runtime/metrics/csv.rs
loki5512344 190ef9cc4b Add design persistence, world rendering, metrics overlay and logs
M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
2026-11-16 23:40:39 +01:00

141 lines
4 KiB
Rust

//! Per-frame metrics CSV writer and the spike rule shared with the dev log.
//!
//! The writer is a passive observer: it reads values that the overlay already
//! computed and never calls into physics or the renderer.
use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::Path;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use super::Stats;
/// The one header line, in the documented column order.
pub(crate) const HEADER: &str = "unix_s,t_s,frame,fps,tps,frame_ms,frame_max_ms,physics_ms,physics_max_ms,render_ms,rtf,cpu_pct,load1,rss_mb,spike";
/// A frame longer than this is a spike, milliseconds.
const FRAME_BUDGET_MS: f32 = 20.0;
/// A single physics step longer than this is a spike, milliseconds.
const STEP_BUDGET_MS: f32 = 1.0;
/// At most one flush per this interval while logging, seconds.
const FLUSH_INTERVAL_SECONDS: u64 = 1;
/// One row of the metrics CSV.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Row<'a> {
/// Wall-clock seconds at the start of the frame.
pub(crate) unix_s: f64,
/// Simulated seconds before this frame was drawn.
pub(crate) t_s: f64,
/// Number of the rendered frame, starting at one.
pub(crate) frame: u64,
/// The same rolling values the overlay shows.
pub(crate) stats: &'a Stats,
/// Whether the frame or one of its physics steps blew its budget.
pub(crate) spike: bool,
}
/// Formats a row exactly as the header orders it.
pub(crate) fn format_row(row: &Row<'_>) -> String {
let stats = row.stats;
format!(
"{:.3},{:.3},{},{:.1},{:.1},{:.2},{:.2},{:.2},{:.2},{:.2},{:.2},{:.1},{:.2},{:.1},{}",
row.unix_s,
row.t_s,
row.frame,
stats.fps,
stats.tps,
stats.frame_avg_ms,
stats.frame_max_ms,
stats.physics_avg_ms,
stats.physics_max_ms,
stats.render_avg_ms,
stats.rtf,
stats.cpu_percent,
stats.load_1m,
stats.rss_mb,
u8::from(row.spike),
)
}
/// Why a frame counts as a spike, or `None` when it fits the budget.
pub(crate) fn spike_reason(frame_ms: f32, slowest_step_ms: f32) -> Option<&'static str> {
match (frame_ms > FRAME_BUDGET_MS, slowest_step_ms > STEP_BUDGET_MS) {
(true, true) => Some("frame+physics"),
(true, false) => Some("frame"),
(false, true) => Some("physics"),
(false, false) => None,
}
}
/// Wall-clock seconds since the Unix epoch.
#[allow(
clippy::disallowed_methods,
reason = "the metrics CSV stamps the frame start with wall-clock time"
)]
pub(crate) fn unix_now() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0.0, |elapsed| elapsed.as_secs_f64())
}
/// An open metrics CSV file.
pub(crate) struct CsvLog {
file: File,
last_flush: Instant,
}
impl CsvLog {
/// Opens the file, truncating it unless `append` is set. The header is
/// written when the file starts empty, so an appended file keeps one.
#[allow(
clippy::disallowed_methods,
reason = "the metrics writer throttles flushes with wall-clock time"
)]
pub(crate) fn open(path: &Path, append: bool) -> io::Result<Self> {
let has_rows = append && fs::metadata(path).is_ok_and(|meta| meta.len() > 0);
let mut file = OpenOptions::new()
.create(true)
.write(true)
.append(append)
.truncate(!append)
.open(path)?;
if !has_rows {
file.write_all(HEADER.as_bytes())?;
file.write_all(b"\n")?;
}
Ok(Self {
file,
last_flush: Instant::now(),
})
}
/// Writes one row and flushes at most once per second.
pub(crate) fn record(&mut self, row: &Row<'_>) -> io::Result<()> {
writeln!(self.file, "{}", format_row(row))?;
if self.last_flush.elapsed().as_secs() >= FLUSH_INTERVAL_SECONDS {
self.flush()?;
}
Ok(())
}
/// Pushes buffered rows to disk and restarts the flush interval.
#[allow(
clippy::disallowed_methods,
reason = "the metrics writer throttles flushes with wall-clock time"
)]
pub(crate) fn flush(&mut self) -> io::Result<()> {
self.file.flush()?;
self.last_flush = Instant::now();
Ok(())
}
}
impl Drop for CsvLog {
fn drop(&mut self) {
// The final flush is best effort: dropping must not abort the process.
let _ = self.file.flush();
}
}