Add design persistence, world rendering, metrics overlay and logs
Some checks failed
ci / check (macos-latest) (push) Has been cancelled
ci / check (ubuntu-latest) (push) Has been cancelled
ci / check (windows-latest) (push) Has been cancelled

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.
This commit is contained in:
Loki 2026-11-16 23:34:05 +01:00
parent 79928b645b
commit 93075ab1fd
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
107 changed files with 14785 additions and 46 deletions

View file

@ -14,8 +14,12 @@ fabrilis-core = { path = "../core" }
fabrilis-platform = { path = "../platform" }
fabrilis-storage = { path = "../storage" }
fabrilis-modes = { path = "../modes" }
fabrilis-physics = { path = "../physics" }
fabrilis-render = { path = "../render" }
fabrilis-ui = { path = "../ui" }
fabrilis-worldgen = { path = "../worldgen" }
winit = "0.30"
pollster = "0.4"
[build-dependencies]
fabrilis-limits = { path = "../../tools/limits" }

View file

@ -1,3 +1,3 @@
fn main() {
println!("fabrilis: скелет проекта, см. TODO.md");
fn main() -> Result<(), fabrilis_app::runtime::AppError> {
fabrilis_app::runtime::run()
}

View file

@ -0,0 +1,320 @@
//! The application handler: window installation, resize, redraw and logging.
use std::sync::Arc;
use std::time::Duration;
use fabrilis_render::Overlay;
use winit::application::ApplicationHandler;
use winit::dpi::PhysicalSize;
use winit::event::{ElementState, KeyEvent, MouseButton, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::{Window, WindowId};
use super::camera::Controls;
use super::config::Config;
use super::devlog::{self, DevLog, Level};
use super::gpu::WindowRenderer;
use super::metrics::{CsvLog, FrameWork, Metrics, Row, Stopwatch, spike_reason, unix_now};
use super::scene::View;
use super::sim::Simulation;
use super::{AppError, aspect, log_startup};
/// Runs the window loop until the user closes the window or presses Escape.
pub(super) fn run() -> Result<(), AppError> {
let config = super::parse_config();
let csv = super::open_csv(&config)?;
let level = if config.dev {
Level::Debug
} else {
Level::Info
};
let dev = match &config.log {
Some(path) => Some(
DevLog::open(path, level, config.append)
.map_err(|error| AppError::Log(format!("{}: {error}", path.display())))?,
),
None => None,
};
let event_loop = EventLoop::new().map_err(|error| AppError::EventLoop(error.to_string()))?;
event_loop.set_control_flow(ControlFlow::Poll);
let mut application = Fabrilis::new(config, csv, dev);
let result = event_loop.run_app(&mut application);
if let Err(error) = &result {
application.report("event loop", &error.to_string());
}
application.finish();
result.map_err(|error| AppError::EventLoop(error.to_string()))
}
/// The window state plus the diagnostics that observe it.
struct Fabrilis {
config: Config,
csv: Option<CsvLog>,
dev: Option<DevLog>,
frame: u64,
window: Option<Arc<Window>>,
renderer: Option<WindowRenderer>,
view: Option<View>,
simulation: Option<Simulation>,
controls: Controls,
metrics: Metrics,
overlay: Overlay,
}
impl Fabrilis {
fn new(config: Config, csv: Option<CsvLog>, dev: Option<DevLog>) -> Self {
Self {
config,
csv,
dev,
frame: 0,
window: None,
renderer: None,
view: None,
simulation: None,
controls: Controls::default(),
metrics: Metrics::default(),
overlay: Overlay::new(),
}
}
fn install(&mut self, event_loop: &ActiveEventLoop) -> Result<(), AppError> {
let attributes = Window::default_attributes()
.with_title("Fabrilis — RTF ...")
.with_inner_size(PhysicalSize::new(1280, 720));
let window = Arc::new(
event_loop
.create_window(attributes)
.map_err(|error| AppError::Window(error.to_string()))?,
);
let mut view = super::scene::build(aspect(window.inner_size()))?;
let simulation = Simulation::new(&view.terrain, &view.heightmap, &mut view.scene)?;
let renderer = WindowRenderer::new(window.clone())?;
log_startup(self.dev.as_mut(), &self.config, &view, &renderer, &window);
self.window = Some(window);
self.renderer = Some(renderer);
self.view = Some(view);
self.simulation = Some(simulation);
Ok(())
}
fn resize(&mut self, size: PhysicalSize<u32>) {
let result = match &mut self.renderer {
Some(renderer) => renderer.resize(size.width, size.height),
None => return,
};
if let Err(error) = result {
eprintln!("fabrilis: resize failed: {error}");
self.report("resize", &error.to_string());
return;
}
if let Some(view) = &mut self.view {
view.camera.set_aspect(aspect(size));
}
if let Some(window) = &self.window {
window.request_redraw();
}
}
fn redraw(&mut self) {
let Some(view) = self.view.as_mut() else {
return;
};
let Some(simulation) = self.simulation.as_mut() else {
return;
};
let unix_s = if self.csv.is_some() {
Some(unix_now())
} else {
None
};
let frame_time = self.metrics.frame_time();
let physics_start = Stopwatch::start();
let frame = simulation.advance(&mut view.scene);
let physics = physics_start.elapsed();
let slowest_step_ms = simulation.slowest_step().as_secs_f32() * 1000.0;
let sim_seconds = simulation.sim_seconds();
let motion = self.controls.motion(frame.elapsed_seconds);
view.camera.apply(motion);
if let (Some(rtf), Some(window)) = (frame.rtf, &self.window) {
window.set_title(&format!("Fabrilis — RTF {rtf:.2}"));
}
self.metrics.set_rtf(frame.rtf);
let camera = view.camera.view();
let size = self
.renderer
.as_ref()
.map_or((0, 0), |renderer| renderer.size());
self.overlay.clear();
if size.0 > 0 && size.1 > 0 {
self.metrics.draw_panel(&mut self.overlay);
}
let Some(renderer) = self.renderer.as_mut() else {
return;
};
let render_start = Stopwatch::start();
let draw = renderer.draw(&view.scene, &camera, &self.overlay);
let render = render_start.elapsed();
if let Err(error) = draw {
eprintln!("fabrilis: draw failed: {error}");
write_dev(&mut self.dev, Level::Error, "render", &error.to_string());
}
let recorded = self.metrics.record(
frame_time,
FrameWork {
physics,
render,
steps: frame.steps,
},
);
if !recorded {
return;
}
self.frame = self.frame.saturating_add(1);
self.log_frame(frame_time, slowest_step_ms, sim_seconds, unix_s);
}
/// Writes the CSV row and the dev-log summary and spike lines for one frame.
///
/// Both observers run after the frame was drawn and only read the metrics
/// that the overlay already computed.
fn log_frame(
&mut self,
frame_time: Duration,
slowest_step_ms: f32,
sim_seconds: f64,
unix_s: Option<f64>,
) {
let stats = self.metrics.stats();
let frame_ms = frame_time.as_secs_f32() * 1000.0;
let spike = spike_reason(frame_ms, slowest_step_ms);
if let Some(unix_s) = unix_s {
let row = Row {
unix_s,
t_s: sim_seconds,
frame: self.frame,
stats: &stats,
spike: spike.is_some(),
};
if let Some(csv) = self.csv.as_mut()
&& let Err(error) = csv.record(&row)
{
eprintln!("fabrilis: metrics log write failed: {error}");
write_dev(&mut self.dev, Level::Error, "metrics", &error.to_string());
}
}
if let Some(dev) = self.dev.as_mut() {
if dev.summary_due() {
write_line(dev, Level::Info, "metrics", &devlog::summary(&stats));
}
if let Some(trigger) = spike {
let line = devlog::spike(self.frame, frame_ms, slowest_step_ms, trigger);
write_line(dev, Level::Warn, "spike", &line);
}
}
}
/// Logs a failure with its context before the loop gives up on the step.
fn report(&mut self, context: &str, detail: &str) {
write_dev(
&mut self.dev,
Level::Error,
"app",
&format!("{context}: {detail}"),
);
}
/// Flushes the CSV and closes the dev session.
fn finish(&mut self) {
if let Some(csv) = self.csv.as_mut()
&& let Err(error) = csv.flush()
{
eprintln!("fabrilis: metrics log flush failed: {error}");
}
write_dev(&mut self.dev, Level::Info, "app", "session end");
}
fn is_escape(event: &KeyEvent) -> bool {
event.state == ElementState::Pressed
&& event.physical_key == PhysicalKey::Code(KeyCode::Escape)
}
fn key(&mut self, event: &KeyEvent) {
if let PhysicalKey::Code(code) = event.physical_key {
self.controls
.key(code, event.state == ElementState::Pressed);
}
}
}
/// Writes one dev-log line and reports a write failure on stderr.
fn write_line(dev: &mut DevLog, level: Level, target: &str, message: &str) {
if let Err(error) = dev.write(level, target, message) {
eprintln!("fabrilis: dev log write failed: {error}");
}
}
/// Writes one dev-log line when the log is enabled.
fn write_dev(dev: &mut Option<DevLog>, level: Level, target: &str, message: &str) {
if let Some(dev) = dev {
write_line(dev, level, target, message);
}
}
impl ApplicationHandler for Fabrilis {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_some() {
return;
}
if let Err(error) = self.install(event_loop) {
eprintln!("fabrilis: startup failed: {error}");
self.report("startup", &error.to_string());
event_loop.exit();
return;
}
if let Some(window) = &self.window {
window.request_redraw();
}
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
_window_id: WindowId,
event: WindowEvent,
) {
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::KeyboardInput { event, .. } if Self::is_escape(&event) => {
event_loop.exit();
}
WindowEvent::KeyboardInput { event, .. } => self.key(&event),
WindowEvent::MouseInput {
state,
button: MouseButton::Left,
..
} => self.controls.mouse(state),
WindowEvent::CursorMoved { position, .. } => {
self.controls.cursor_moved(position.x, position.y);
}
WindowEvent::Focused(false) => self.controls.release_all(),
WindowEvent::Resized(size) => self.resize(size),
WindowEvent::ScaleFactorChanged { .. } => {
let size = self
.window
.as_ref()
.map_or(PhysicalSize::new(0, 0), |window| window.inner_size());
self.resize(size);
}
WindowEvent::RedrawRequested => self.redraw(),
_ => {}
}
}
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
if let Some(window) = &self.window {
window.request_redraw();
}
}
}

View file

@ -0,0 +1,95 @@
//! Keyboard and mouse state mapped to camera motion.
use winit::event::ElementState;
use winit::keyboard::KeyCode;
use super::Motion;
/// Radians of rotation per pixel of mouse drag.
const LOOK_SENSITIVITY: f32 = 0.0035;
/// Which movement keys are held and how far the mouse was dragged.
#[derive(Default)]
pub(crate) struct Controls {
forward: bool,
back: bool,
left: bool,
right: bool,
up: bool,
down: bool,
fast: bool,
dragging: bool,
cursor: Option<[f64; 2]>,
turn: [f32; 2],
}
impl Controls {
/// Tracks a movement or modifier key.
pub(crate) fn key(&mut self, code: KeyCode, pressed: bool) {
match code {
KeyCode::KeyW | KeyCode::ArrowUp => self.forward = pressed,
KeyCode::KeyS | KeyCode::ArrowDown => self.back = pressed,
KeyCode::KeyA | KeyCode::ArrowLeft => self.left = pressed,
KeyCode::KeyD | KeyCode::ArrowRight => self.right = pressed,
KeyCode::KeyE => self.up = pressed,
KeyCode::KeyQ => self.down = pressed,
KeyCode::ShiftLeft | KeyCode::ShiftRight => self.fast = pressed,
_ => {}
}
}
/// Starts or stops a left-button drag.
pub(crate) fn mouse(&mut self, state: ElementState) {
self.dragging = state == ElementState::Pressed;
if !self.dragging {
self.cursor = None;
}
}
/// Accumulates a drag delta while the left button is held.
pub(crate) fn cursor_moved(&mut self, x: f64, y: f64) {
if self.dragging
&& let Some([last_x, last_y]) = self.cursor
{
self.turn[0] += (x - last_x) as f32 * LOOK_SENSITIVITY;
self.turn[1] -= (y - last_y) as f32 * LOOK_SENSITIVITY;
}
self.cursor = Some([x, y]);
}
/// Drops held keys and drags when the window loses focus.
pub(crate) fn release_all(&mut self) {
self.forward = false;
self.back = false;
self.left = false;
self.right = false;
self.up = false;
self.down = false;
self.fast = false;
self.dragging = false;
self.cursor = None;
self.turn = [0.0, 0.0];
}
/// Builds this frame's motion and consumes the accumulated look deltas.
pub(crate) fn motion(&mut self, seconds: f32) -> Motion {
let [yaw, pitch] = self.turn;
self.turn = [0.0, 0.0];
Motion {
forward: axis(self.forward, self.back),
strafe: axis(self.right, self.left),
lift: axis(self.up, self.down),
yaw,
pitch,
seconds,
fast: self.fast,
}
}
}
/// `+1` when the positive key is held, `-1` when the negative one is.
fn axis(positive: bool, negative: bool) -> f32 {
let positive = if positive { 1.0 } else { 0.0 };
let negative = if negative { 1.0 } else { 0.0 };
positive - negative
}

View file

@ -0,0 +1,137 @@
//! Fly camera with yaw/pitch controls for the window.
mod input;
#[cfg(test)]
mod tests;
pub(crate) use input::Controls;
use fabrilis_core::math;
use fabrilis_render::Camera;
/// Horizontal movement speed, metres per second.
const MOVE_SPEED: f32 = 8.0;
/// Shift multiplier for faster movement.
const FAST_FACTOR: f32 = 3.0;
/// Pitch limit, radians, just below a straight-down or straight-up look.
const PITCH_LIMIT: f32 = 1.45;
const FOV_Y: f32 = 0.9;
const NEAR: f32 = 0.1;
const FAR: f32 = 500.0;
/// Movement and look deltas for one frame.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(crate) struct Motion {
pub forward: f32,
pub strafe: f32,
pub lift: f32,
pub yaw: f32,
pub pitch: f32,
pub seconds: f32,
pub fast: bool,
}
/// A camera placed by an eye position and yaw/pitch angles.
pub(crate) struct FlyCamera {
position: [f32; 3],
yaw: f32,
pitch: f32,
aspect: f32,
}
impl FlyCamera {
/// Places the camera at `eye` looking towards `target`.
pub(crate) fn look_at(eye: [f32; 3], target: [f32; 3], aspect: f32) -> Self {
let delta = [
f64::from(target[0] - eye[0]),
f64::from(target[1] - eye[1]),
f64::from(target[2] - eye[2]),
];
let horizontal = math::sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
let length = math::sqrt(horizontal * horizontal + delta[2] * delta[2]);
let yaw = if horizontal > 1.0e-6 {
math::atan2(delta[1], delta[0])
} else {
0.0
};
let pitch = if length > 1.0e-6 {
math::asin(delta[2] / length)
} else {
0.0
};
Self {
position: eye,
yaw: yaw as f32,
pitch: (pitch as f32).clamp(-PITCH_LIMIT, PITCH_LIMIT),
aspect: aspect.max(0.0001),
}
}
/// Updates the aspect ratio after a surface resize.
pub(crate) fn set_aspect(&mut self, aspect: f32) {
self.aspect = aspect.max(0.0001);
}
/// Applies look deltas first, then moves in the horizontal plane and along Z.
pub(crate) fn apply(&mut self, motion: Motion) {
self.yaw += motion.yaw;
self.pitch = (self.pitch + motion.pitch).clamp(-PITCH_LIMIT, PITCH_LIMIT);
let (sin_yaw, cos_yaw) = math::sin_cos(f64::from(self.yaw));
let (sin_yaw, cos_yaw) = (sin_yaw as f32, cos_yaw as f32);
let seconds = motion.seconds.max(0.0);
let speed = MOVE_SPEED * if motion.fast { FAST_FACTOR } else { 1.0 } * seconds;
let forward = motion.forward * speed;
let strafe = motion.strafe * speed;
self.position[0] += cos_yaw * forward + sin_yaw * strafe;
self.position[1] += sin_yaw * forward - cos_yaw * strafe;
self.position[2] += motion.lift * speed;
}
/// The unit direction the camera looks along.
pub(crate) fn direction(&self) -> [f32; 3] {
let (sin_yaw, cos_yaw) = math::sin_cos(f64::from(self.yaw));
let (sin_pitch, cos_pitch) = math::sin_cos(f64::from(self.pitch));
[
(cos_pitch * cos_yaw) as f32,
(cos_pitch * sin_yaw) as f32,
sin_pitch as f32,
]
}
/// The eye position, for diagnostics.
#[must_use]
pub(crate) fn eye(&self) -> [f32; 3] {
self.position
}
/// The point one metre ahead of the eye, for diagnostics.
#[must_use]
pub(crate) fn target(&self) -> [f32; 3] {
let direction = self.direction();
[
self.position[0] + direction[0],
self.position[1] + direction[1],
self.position[2] + direction[2],
]
}
/// The renderer camera for the current pose.
pub(crate) fn view(&self) -> Camera {
let direction = self.direction();
let target = [
self.position[0] + direction[0],
self.position[1] + direction[1],
self.position[2] + direction[2],
];
Camera::look_at(self.position, target, [0.0, 0.0, 1.0]).with_projection(
FOV_Y,
self.aspect,
NEAR,
FAR,
)
}
}

View file

@ -0,0 +1,103 @@
//! Tests for camera movement and rotation math.
use core::f32::consts::FRAC_PI_2;
use fabrilis_core::math;
use super::{FlyCamera, MOVE_SPEED, Motion, PITCH_LIMIT};
fn close(actual: f32, expected: f32) -> bool {
(actual - expected).abs() < 1.0e-4
}
fn level_camera() -> FlyCamera {
FlyCamera::look_at([0.0, 0.0, 2.0], [1.0, 0.0, 2.0], 1.0)
}
#[test]
fn look_at_starts_level_along_x() {
let direction = level_camera().direction();
assert!(close(direction[0], 1.0));
assert!(close(direction[1], 0.0));
assert!(close(direction[2], 0.0));
}
#[test]
fn yaw_rotation_turns_the_look_direction() {
let mut camera = level_camera();
camera.apply(Motion {
yaw: FRAC_PI_2,
..Motion::default()
});
let direction = camera.direction();
assert!(close(direction[0], 0.0));
assert!(close(direction[1], 1.0));
assert!(close(direction[2], 0.0));
}
#[test]
fn pitch_is_clamped() {
let mut camera = level_camera();
camera.apply(Motion {
pitch: 10.0,
..Motion::default()
});
let direction = camera.direction();
let expected = math::sin(f64::from(PITCH_LIMIT)) as f32;
assert!(close(direction[2], expected));
}
#[test]
fn forward_moves_horizontally_relative_to_yaw() {
let mut camera = level_camera();
camera.apply(Motion {
yaw: FRAC_PI_2,
..Motion::default()
});
let before = camera.view().eye();
camera.apply(Motion {
forward: 1.0,
seconds: 0.5,
..Motion::default()
});
let after = camera.view().eye();
assert!(close(after[0], before[0]));
assert!(close(after[1] - before[1], MOVE_SPEED * 0.5));
assert!(close(after[2], before[2]));
}
#[test]
fn lift_moves_only_vertically() {
let mut camera = level_camera();
let before = camera.view().eye();
camera.apply(Motion {
lift: -1.0,
seconds: 0.5,
..Motion::default()
});
let after = camera.view().eye();
assert!(close(after[0], before[0]));
assert!(close(after[1], before[1]));
assert!(close(after[2] - before[2], -MOVE_SPEED * 0.5));
}
#[test]
fn shift_multiplies_movement_speed() {
let mut slow = level_camera();
let mut fast = level_camera();
let start = slow.view().eye();
slow.apply(Motion {
forward: 1.0,
seconds: 0.1,
..Motion::default()
});
fast.apply(Motion {
forward: 1.0,
seconds: 0.1,
fast: true,
..Motion::default()
});
let slow_distance = slow.view().eye()[0] - start[0];
let fast_distance = fast.view().eye()[0] - start[0];
assert!(close(fast_distance, slow_distance * 3.0));
}

View file

@ -0,0 +1,193 @@
//! Command-line and environment configuration for diagnostics.
//!
//! The parser is pure: arguments and environment values are passed in, so the
//! precedence rules are unit-tested without touching the process.
//!
//! Precedence for each path is command line, then environment, then the
//! `--dev` default. Logs are off unless a path or dev mode asks for them.
#[cfg(test)]
mod tests;
use std::path::PathBuf;
/// Default metrics CSV written by `--dev` when no path is given.
pub(crate) const DEFAULT_METRICS: &str = "fabrilis-metrics.csv";
/// Default dev log written by `--dev` when no path is given.
pub(crate) const DEFAULT_LOG: &str = "fabrilis-dev.log";
/// Environment variable with the metrics CSV path.
const ENV_METRICS: &str = "FABRILIS_METRICS_LOG";
/// Environment variable with the dev log path.
const ENV_LOG: &str = "FABRILIS_LOG";
/// Environment variable that enables dev mode when set to `1`.
const ENV_DEV: &str = "FABRILIS_DEV";
/// Usage text printed for `--help` and after a parse error.
pub(crate) const USAGE: &str = "\
Usage: fabrilis-app [options]
Options:
--metrics-log <path> Write one metrics CSV row per rendered frame
--log <path> Write the dev log to <path>
--dev Verbose mode: default log paths and debug level
--append Append to existing logs instead of truncating
-h, --help Print this help and exit
Environment:
FABRILIS_METRICS_LOG Metrics CSV path (command line wins)
FABRILIS_LOG Dev log path (command line wins)
FABRILIS_DEV=1 Same as --dev
";
/// Resolved diagnostics configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Config {
/// Metrics CSV path; `None` keeps the CSV off.
pub(crate) metrics_log: Option<PathBuf>,
/// Dev log path; `None` keeps the text log off.
pub(crate) log: Option<PathBuf>,
/// Verbose mode: enables the dev log and the debug level.
pub(crate) dev: bool,
/// Append to existing files instead of truncating them at start.
pub(crate) append: bool,
}
/// What the command line asked for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Outcome {
/// Run the application with this configuration.
Run(Config),
/// Print the usage text and exit successfully.
Help,
}
/// A configuration the parser rejected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ConfigError {
/// An argument is not one of the documented flags.
Unknown(String),
/// A flag that takes a path was the last argument.
MissingValue(&'static str),
}
impl core::fmt::Display for ConfigError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Unknown(argument) => write!(formatter, "unknown argument: {argument}"),
Self::MissingValue(flag) => write!(formatter, "missing value for {flag}"),
}
}
}
impl std::error::Error for ConfigError {}
/// Environment values that fill in paths the command line did not set.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Environment {
pub(crate) metrics_log: Option<PathBuf>,
pub(crate) log: Option<PathBuf>,
pub(crate) dev: bool,
}
impl Environment {
/// Reads the documented `FABRILIS_*` variables, ignoring unset ones.
pub(crate) fn from_process() -> Self {
Self {
metrics_log: path_variable(ENV_METRICS),
log: path_variable(ENV_LOG),
dev: std::env::var_os(ENV_DEV).is_some_and(|value| value.to_str() == Some("1")),
}
}
}
impl Config {
/// Parses the process arguments and environment.
pub(crate) fn from_process() -> Result<Outcome, ConfigError> {
let args: Vec<String> = std::env::args_os()
.skip(1)
.map(|argument| argument.to_string_lossy().into_owned())
.collect();
parse(&args, &Environment::from_process())
}
}
/// Parses arguments and resolves them against the environment.
pub(crate) fn parse(args: &[String], env: &Environment) -> Result<Outcome, ConfigError> {
let mut cli = Cli::default();
let mut arguments = args.iter();
while let Some(argument) = arguments.next() {
match argument.as_str() {
"--help" | "-h" => return Ok(Outcome::Help),
"--dev" => cli.dev = true,
"--append" => cli.append = true,
"--metrics-log" => cli.metrics_log = Some(path_value(&mut arguments, "--metrics-log")?),
"--log" => cli.log = Some(path_value(&mut arguments, "--log")?),
argument => inline(&mut cli, argument)?,
}
}
Ok(Outcome::Run(resolve(cli, env)))
}
/// Flags exactly as the command line gave them.
#[derive(Debug, Clone, Default)]
struct Cli {
metrics_log: Option<PathBuf>,
log: Option<PathBuf>,
dev: bool,
append: bool,
}
/// Handles the `--flag=value` spelling of a path flag.
fn inline(cli: &mut Cli, argument: &str) -> Result<(), ConfigError> {
if let Some(value) = argument.strip_prefix("--metrics-log=") {
cli.metrics_log = Some(PathBuf::from(value));
return Ok(());
}
if let Some(value) = argument.strip_prefix("--log=") {
cli.log = Some(PathBuf::from(value));
return Ok(());
}
Err(ConfigError::Unknown(argument.to_owned()))
}
/// The value after a path flag.
fn path_value(
arguments: &mut std::slice::Iter<'_, String>,
flag: &'static str,
) -> Result<PathBuf, ConfigError> {
arguments
.next()
.filter(|value| !value.is_empty())
.map(PathBuf::from)
.ok_or(ConfigError::MissingValue(flag))
}
/// Folds command line and environment into the final configuration.
fn resolve(cli: Cli, env: &Environment) -> Config {
let dev = cli.dev || env.dev;
let metrics_log = cli
.metrics_log
.or_else(|| env.metrics_log.clone())
.or_else(|| dev.then(|| PathBuf::from(DEFAULT_METRICS)));
let log = cli
.log
.or_else(|| env.log.clone())
.or_else(|| dev.then(|| PathBuf::from(DEFAULT_LOG)));
Config {
metrics_log,
log,
dev,
append: cli.append,
}
}
/// A path environment variable, treating an empty value as unset.
fn path_variable(name: &str) -> Option<PathBuf> {
std::env::var_os(name)
.map(PathBuf::from)
.filter(|path| !path.as_os_str().is_empty())
}

View file

@ -0,0 +1,155 @@
//! Tests for the argument and environment parser.
use std::path::PathBuf;
use super::*;
fn args(items: &[&str]) -> Vec<String> {
items.iter().map(|item| (*item).to_owned()).collect()
}
fn run(arguments: &[&str], env: &Environment) -> Config {
match parse(&args(arguments), env) {
Ok(Outcome::Run(config)) => config,
other => panic!("expected a config, got {other:?}"),
}
}
fn path(value: &str) -> Option<PathBuf> {
Some(PathBuf::from(value))
}
#[test]
fn no_flags_leave_both_logs_off() {
let config = run(&[], &Environment::default());
assert_eq!(config, Config::default());
assert_eq!(config.metrics_log, None);
assert_eq!(config.log, None);
}
#[test]
fn flags_set_paths_dev_and_append() {
let config = run(
&[
"--metrics-log",
"run/m.csv",
"--log",
"run/dev.log",
"--dev",
"--append",
],
&Environment::default(),
);
assert_eq!(config.metrics_log, path("run/m.csv"));
assert_eq!(config.log, path("run/dev.log"));
assert!(config.dev);
assert!(config.append);
}
#[test]
fn inline_values_are_accepted() {
let config = run(
&["--metrics-log=a.csv", "--log=b.log"],
&Environment::default(),
);
assert_eq!(config.metrics_log, path("a.csv"));
assert_eq!(config.log, path("b.log"));
}
#[test]
fn an_unknown_flag_is_an_error() {
let error = parse(&args(&["--frobnicate"]), &Environment::default());
assert_eq!(error, Err(ConfigError::Unknown("--frobnicate".to_owned())));
}
#[test]
fn a_path_flag_without_a_value_is_an_error() {
assert_eq!(
parse(&args(&["--metrics-log"]), &Environment::default()),
Err(ConfigError::MissingValue("--metrics-log"))
);
assert_eq!(
parse(&args(&["--log", "", "--dev"]), &Environment::default()),
Err(ConfigError::MissingValue("--log"))
);
}
#[test]
fn help_is_reported_before_any_work() {
assert_eq!(
parse(&args(&["--help"]), &Environment::default()),
Ok(Outcome::Help)
);
assert_eq!(
parse(&args(&["-h", "--dev"]), &Environment::default()),
Ok(Outcome::Help)
);
}
#[test]
fn dev_mode_fills_in_the_default_paths() {
let config = run(&["--dev"], &Environment::default());
assert_eq!(config.metrics_log, path(DEFAULT_METRICS));
assert_eq!(config.log, path(DEFAULT_LOG));
assert!(config.dev);
}
#[test]
fn dev_keeps_an_explicit_path_and_fills_the_other_default() {
let metrics = run(
&["--dev", "--metrics-log", "m.csv"],
&Environment::default(),
);
assert_eq!(metrics.metrics_log, path("m.csv"));
assert_eq!(metrics.log, path(DEFAULT_LOG));
let log = run(&["--dev", "--log", "d.log"], &Environment::default());
assert_eq!(log.metrics_log, path(DEFAULT_METRICS));
assert_eq!(log.log, path("d.log"));
}
#[test]
fn environment_paths_are_used_without_flags() {
let env = Environment {
metrics_log: path("env/metrics.csv"),
log: path("env/dev.log"),
dev: false,
};
let config = run(&[], &env);
assert_eq!(config.metrics_log, path("env/metrics.csv"));
assert_eq!(config.log, path("env/dev.log"));
assert!(!config.dev);
}
#[test]
fn command_line_overrides_environment_too() {
let env = Environment {
metrics_log: path("env/metrics.csv"),
log: path("env/dev.log"),
dev: false,
};
let config = run(&["--metrics-log", "cli/m.csv", "--log", "cli/l.log"], &env);
assert_eq!(config.metrics_log, path("cli/m.csv"));
assert_eq!(config.log, path("cli/l.log"));
}
#[test]
fn environment_dev_keeps_explicit_paths() {
let env = Environment {
metrics_log: path("env/metrics.csv"),
log: None,
dev: true,
};
let config = run(&[], &env);
assert!(config.dev);
assert_eq!(
config.metrics_log,
path("env/metrics.csv"),
"the environment path wins over the dev default"
);
assert_eq!(
config.log,
path(DEFAULT_LOG),
"the missing path gets the default"
);
}

View file

@ -0,0 +1,153 @@
//! Dev text log: wall-clock stamped lines with a level, a target and a message.
//!
//! The logger is a diagnostic observer. It is off unless `--dev`, `--log` or a
//! matching environment variable asks for it, and it never feeds data back into
//! the simulation.
//!
//! Line shape: `unix_s level target message`.
pub(crate) mod startup;
#[cfg(test)]
mod tests;
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::Path;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use crate::runtime::metrics::Stats;
/// How much detail the log records.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Level {
Error,
Warn,
Info,
Debug,
#[allow(
dead_code,
reason = "trace belongs to the documented level set; --dev stops at debug"
)]
Trace,
}
impl Level {
/// Lower bounds `self`, so `self.rank() <= limit.rank()` means "log it".
fn rank(self) -> u8 {
match self {
Self::Error => 0,
Self::Warn => 1,
Self::Info => 2,
Self::Debug => 3,
Self::Trace => 4,
}
}
}
impl core::fmt::Display for Level {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let name = match self {
Self::Error => "error",
Self::Warn => "warn",
Self::Info => "info",
Self::Debug => "debug",
Self::Trace => "trace",
};
formatter.write_str(name)
}
}
/// How often a metrics summary line is written, seconds.
const SUMMARY_INTERVAL_SECONDS: u64 = 1;
/// A dev log file, truncated or created when opened.
pub(crate) struct DevLog {
file: File,
level: Level,
last_summary: Instant,
}
impl DevLog {
/// Creates or opens the file, truncating it unless `append` is set, and
/// records `level` as the most detailed level to write.
#[allow(
clippy::disallowed_methods,
reason = "the dev log is a wall-clock observer of the app loop"
)]
pub(crate) fn open(path: &Path, level: Level, append: bool) -> io::Result<Self> {
let file = OpenOptions::new()
.create(true)
.write(true)
.append(append)
.truncate(!append)
.open(path)?;
Ok(Self {
file,
level,
last_summary: Instant::now(),
})
}
/// Writes one line and flushes it, so the log survives a crash.
pub(crate) fn write(&mut self, level: Level, target: &str, message: &str) -> io::Result<()> {
if level.rank() > self.level.rank() {
return Ok(());
}
let line = format_line(unix_now(), level, target, message);
writeln!(self.file, "{line}")?;
self.file.flush()
}
/// Whether the once-per-second metrics summary is due.
#[allow(
clippy::disallowed_methods,
reason = "the dev log is a wall-clock observer of the app loop"
)]
pub(crate) fn summary_due(&mut self) -> bool {
if self.last_summary.elapsed().as_secs() < SUMMARY_INTERVAL_SECONDS {
return false;
}
self.last_summary = Instant::now();
true
}
}
/// Formats one log line without the trailing newline.
pub(crate) fn format_line(unix_s: f64, level: Level, target: &str, message: &str) -> String {
format!("{unix_s:.3} {level} {target} {message}")
}
/// One-line metrics summary written about once per second.
pub(crate) fn summary(stats: &Stats) -> String {
format!(
"fps={:.1} tps={:.1} frame={:.2}/{:.2} ms physics={:.2}/{:.2} ms render={:.2} ms rtf={:.2} cpu={:.1}% load1={:.2} rss={:.1} MB",
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,
)
}
/// One-line description of a frame that exceeded its budget.
pub(crate) fn spike(frame: u64, frame_ms: f32, step_ms: f32, trigger: &str) -> String {
format!("frame={frame} frame_ms={frame_ms:.2} physics_step_ms={step_ms:.3} trigger={trigger}")
}
/// Wall-clock seconds since the Unix epoch, as a float.
#[allow(
clippy::disallowed_methods,
reason = "the dev log is a wall-clock observer of the app loop"
)]
fn unix_now() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0.0, |elapsed| elapsed.as_secs_f64())
}

View file

@ -0,0 +1,66 @@
//! Startup banner for the dev log: versions, window, world, bodies and GPU.
use std::io;
use fabrilis_worldgen::terrain::TerrainConfig;
use super::{DevLog, Level};
/// Everything the startup lines report, gathered before the loop starts.
pub(crate) struct StartupInfo<'a> {
pub(crate) window: (u32, u32),
pub(crate) scale: f64,
pub(crate) terrain: TerrainConfig,
pub(crate) boxes: usize,
pub(crate) box_mass_kg: f64,
pub(crate) box_size_m: f64,
pub(crate) eye: [f32; 3],
pub(crate) target: [f32; 3],
pub(crate) adapter: &'a str,
pub(crate) driver: &'a str,
pub(crate) surface: &'a str,
pub(crate) metrics_path: Option<&'a str>,
pub(crate) log_path: Option<&'a str>,
pub(crate) dev: bool,
pub(crate) append: bool,
}
/// Writes the startup banner, one line per fact.
pub(crate) fn write(log: &mut DevLog, info: &StartupInfo<'_>) -> io::Result<()> {
let terrain = info.terrain;
let [width, height] = [info.window.0, info.window.1];
let [x, y, z] = info.eye;
let [tx, ty, tz] = info.target;
let lines = [
format!(
"fabrilis-app {} {} {}",
env!("CARGO_PKG_VERSION"),
std::env::consts::OS,
std::env::consts::ARCH
),
format!("window {width}x{height} scale {:.2}", info.scale),
format!(
"terrain seed={} size={} extent={:.1} height_scale={:.1}",
terrain.seed, terrain.size, terrain.extent, terrain.height_scale
),
format!(
"boxes={} mass={:.1} kg size={:.2} m",
info.boxes, info.box_mass_kg, info.box_size_m
),
format!("camera eye=[{x:.2}, {y:.2}, {z:.2}] target=[{tx:.2}, {ty:.2}, {tz:.2}]"),
format!("gpu adapter {}", info.adapter),
format!("gpu driver {}", info.driver),
format!("gpu surface {}", info.surface),
format!(
"metrics_log {} append={} dev={}",
info.metrics_path.unwrap_or("off"),
info.append,
info.dev
),
format!("log {}", info.log_path.unwrap_or("off")),
];
for line in &lines {
log.write(Level::Info, "startup", line)?;
}
Ok(())
}

View file

@ -0,0 +1,120 @@
//! Tests for the dev log line format and its file lifecycle.
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use super::*;
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(name: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-devlog-{name}-{}-{id}",
std::process::id()
));
std::fs::create_dir_all(&path).expect("temp directory");
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
fn a_line_has_a_stable_timestamp_level_target_and_message() {
assert_eq!(
format_line(1_700_000_000.125, Level::Info, "app", "hello"),
"1700000000.125 info app hello"
);
assert_eq!(
format_line(0.0, Level::Warn, "spike", "frame=7"),
"0.000 warn spike frame=7"
);
}
#[test]
fn the_summary_and_spike_lines_are_stable() {
let stats = Stats {
fps: 60.0,
tps: 999.5,
frame_avg_ms: 16.25,
frame_max_ms: 20.5,
physics_avg_ms: 0.5,
physics_max_ms: 1.25,
render_avg_ms: 2.0,
rtf: 1.0,
cpu_percent: 12.5,
load_1m: 0.75,
rss_mb: 312.5,
};
assert_eq!(
summary(&stats),
"fps=60.0 tps=999.5 frame=16.25/20.50 ms physics=0.50/1.25 ms render=2.00 ms rtf=1.00 cpu=12.5% load1=0.75 rss=312.5 MB"
);
assert_eq!(
spike(42, 25.1, 1.25, "frame+physics"),
"frame=42 frame_ms=25.10 physics_step_ms=1.250 trigger=frame+physics"
);
}
#[test]
fn writing_creates_then_truncates_the_file() {
let dir = TempDir::new("create");
let path = dir.path.join("fabrilis-dev.log");
{
let mut log = DevLog::open(&path, Level::Debug, false).expect("create the log");
log.write(Level::Info, "app", "first run").expect("write");
}
assert!(path.is_file(), "the log file exists");
let first = std::fs::read_to_string(&path).expect("read");
assert_eq!(first.lines().count(), 1);
assert!(first.ends_with(" info app first run\n"));
{
let mut log = DevLog::open(&path, Level::Debug, false).expect("truncate the log");
log.write(Level::Warn, "app", "second run").expect("write");
}
let second = std::fs::read_to_string(&path).expect("read");
assert_eq!(second.lines().count(), 1, "the old contents are gone");
assert!(second.ends_with(" warn app second run\n"));
}
#[test]
fn append_keeps_the_previous_lines() {
let dir = TempDir::new("append");
let path = dir.path.join("fabrilis-dev.log");
{
let mut log = DevLog::open(&path, Level::Debug, false).expect("create the log");
log.write(Level::Info, "app", "first").expect("write");
}
{
let mut log = DevLog::open(&path, Level::Debug, true).expect("append the log");
log.write(Level::Info, "app", "second").expect("write");
}
let text = std::fs::read_to_string(&path).expect("read");
assert_eq!(text.lines().count(), 2, "both sessions are kept");
assert!(text.contains("first") && text.contains("second"));
}
#[test]
fn levels_above_the_limit_are_dropped() {
let dir = TempDir::new("levels");
let path = dir.path.join("fabrilis-dev.log");
{
let mut log = DevLog::open(&path, Level::Info, false).expect("create the log");
log.write(Level::Debug, "app", "too detailed")
.expect("write");
log.write(Level::Info, "app", "kept").expect("write");
}
let text = std::fs::read_to_string(&path).expect("read");
assert_eq!(text.lines().count(), 1);
assert!(text.contains("kept"));
assert!(!text.contains("too detailed"));
}

View file

@ -0,0 +1,62 @@
//! Application errors.
use core::fmt;
use fabrilis_render::RenderError;
use fabrilis_worldgen::terrain::TerrainError;
/// A failure that stops the window loop.
#[derive(Debug)]
pub enum AppError {
/// The renderer rejected a device, texture or buffer operation.
Render(RenderError),
/// Terrain generation rejected its configuration.
Terrain(TerrainError),
/// The physics world rejected a body or collider.
Physics(String),
/// The window could not be created.
Window(String),
/// The swap chain could not be acquired or configured.
Surface(String),
/// The event loop itself failed.
EventLoop(String),
/// A diagnostics log file could not be opened or written.
Log(String),
}
impl fmt::Display for AppError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Render(error) => write!(formatter, "{error}"),
Self::Terrain(error) => write!(formatter, "terrain generation failed: {error}"),
Self::Physics(detail) => write!(formatter, "physics failure: {detail}"),
Self::Window(detail) => write!(formatter, "window failure: {detail}"),
Self::Surface(detail) => write!(formatter, "surface failure: {detail}"),
Self::EventLoop(detail) => write!(formatter, "event loop failure: {detail}"),
Self::Log(detail) => write!(formatter, "log failure: {detail}"),
}
}
}
impl std::error::Error for AppError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Render(error) => Some(error),
Self::Terrain(error) => Some(error),
Self::Physics(_) | Self::Window(_) | Self::Surface(_) | Self::EventLoop(_) => None,
Self::Log(_) => None,
}
}
}
impl From<RenderError> for AppError {
fn from(error: RenderError) -> Self {
Self::Render(error)
}
}
impl From<TerrainError> for AppError {
fn from(error: TerrainError) -> Self {
Self::Terrain(error)
}
}

View file

@ -0,0 +1,148 @@
//! Window surface, device and swap chain owned by the application.
use std::sync::Arc;
use fabrilis_render::{Camera, Overlay, RenderError, Renderer, Scene, wgpu};
use winit::window::Window;
use super::AppError;
/// Everything needed to present frames into the winit window.
pub(crate) struct WindowRenderer {
surface: wgpu::Surface<'static>,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
renderer: Renderer,
size: (u32, u32),
gpu: GpuInfo,
}
/// Adapter and surface facts reported to the dev log.
pub(crate) struct GpuInfo {
pub(crate) adapter: String,
pub(crate) driver: String,
pub(crate) surface: String,
}
impl WindowRenderer {
/// Creates the instance, surface, adapter, device and swap chain.
pub(crate) fn new(window: Arc<Window>) -> Result<Self, AppError> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let surface = instance
.create_surface(window.clone())
.map_err(|error| AppError::Surface(error.to_string()))?;
let adapter = request_adapter(&instance, &surface)?;
let (device, queue) =
pollster::block_on(adapter.request_device(&fabrilis_render::gpu::device_descriptor()))
.map_err(|error| RenderError::Device(error.to_string()))?;
let size = window.inner_size();
let width = size.width.max(1);
let height = size.height.max(1);
let capabilities = surface.get_capabilities(&adapter);
let format = capabilities
.formats
.iter()
.copied()
.find(wgpu::TextureFormat::is_srgb)
.or_else(|| capabilities.formats.first().copied())
.ok_or_else(|| AppError::Surface("surface reports no texture formats".to_string()))?;
let mut config = surface
.get_default_config(&adapter, width, height)
.ok_or_else(|| AppError::Surface("surface has no default configuration".to_string()))?;
config.format = format;
config.present_mode = wgpu::PresentMode::AutoVsync;
surface.configure(&device, &config);
let renderer = Renderer::for_surface(&device, &queue, format, (width, height))?;
let info = adapter.get_info();
let driver = if info.driver_info.is_empty() {
format!("{} ({:?})", info.driver, info.backend)
} else {
format!("{} {} ({:?})", info.driver, info.driver_info, info.backend)
};
let gpu = GpuInfo {
adapter: info.name,
driver,
surface: format!("{format:?}"),
};
Ok(Self {
surface,
device,
queue,
config,
renderer,
size: (size.width, size.height),
gpu,
})
}
/// Adapter and surface facts for the startup banner.
pub(crate) fn info(&self) -> &GpuInfo {
&self.gpu
}
/// Reconfigures the swap chain and renderer targets after a window resize.
pub(crate) fn resize(&mut self, width: u32, height: u32) -> Result<(), AppError> {
self.size = (width, height);
self.renderer.resize((width, height))?;
if width == 0 || height == 0 {
return Ok(());
}
self.config.width = width;
self.config.height = height;
self.surface.configure(&self.device, &self.config);
Ok(())
}
/// The current target size in pixels.
pub(crate) fn size(&self) -> (u32, u32) {
self.size
}
/// Acquires a surface frame, draws the scene and the overlay, then presents.
pub(crate) fn draw(
&mut self,
scene: &Scene,
camera: &Camera,
overlay: &Overlay,
) -> Result<(), AppError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(frame)
| wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
let view = frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
self.renderer.draw_to(&view, scene, camera)?;
self.renderer.draw_overlay(&view, overlay)?;
self.queue.present(frame);
Ok(())
}
wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => Ok(()),
wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
self.surface.configure(&self.device, &self.config);
Ok(())
}
wgpu::CurrentSurfaceTexture::Validation => {
Err(AppError::Surface("surface validation error".to_string()))
}
}
}
}
fn request_adapter(
instance: &wgpu::Instance,
surface: &wgpu::Surface<'_>,
) -> Result<wgpu::Adapter, AppError> {
let options = wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(surface),
force_fallback_adapter: false,
..Default::default()
};
let adapter = pollster::block_on(instance.request_adapter(&options))
.map_err(|error| RenderError::Adapter(error.to_string()))?;
Ok(adapter)
}

View file

@ -0,0 +1,141 @@
//! 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();
}
}

View file

@ -0,0 +1,237 @@
//! Rolling frame, physics, render and process metrics for the debug overlay.
//!
//! Wall-clock reads live here: the rest of the application only measures phases
//! through [`Stopwatch`] and never looks at the system clock itself.
mod csv;
mod panel;
mod proc;
#[cfg(test)]
mod tests;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use self::proc::ProcSample;
pub(crate) use csv::{CsvLog, Row, spike_reason, unix_now};
/// Length of the rolling statistics window, seconds.
const WINDOW_SECONDS: f32 = 1.0;
/// Frames kept for the graph.
const HISTORY: usize = 180;
/// Linux `USER_HZ`: `/proc` CPU ticks per second.
const TICKS_PER_SECOND: f32 = 100.0;
/// Physics and render work of one frame, as measured by the caller.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct FrameWork {
pub(crate) physics: Duration,
pub(crate) render: Duration,
pub(crate) steps: u32,
}
/// One frame in the rolling statistics window.
#[derive(Debug, Clone, Copy)]
struct Sample {
at: f32,
frame_ms: f32,
physics_ms: f32,
render_ms: f32,
steps: u32,
cpu_ticks: u32,
}
/// Aggregates over the last second, rebuilt after every frame.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(crate) struct Stats {
pub(crate) fps: f32,
pub(crate) tps: f32,
pub(crate) frame_avg_ms: f32,
pub(crate) frame_max_ms: f32,
pub(crate) physics_avg_ms: f32,
pub(crate) physics_max_ms: f32,
pub(crate) render_avg_ms: f32,
pub(crate) cpu_percent: f32,
pub(crate) load_1m: f32,
pub(crate) rss_mb: f32,
pub(crate) rtf: f32,
}
/// Wall-clock measurement of one phase of a frame.
pub(crate) struct Stopwatch {
start: Instant,
}
impl Stopwatch {
/// Starts a phase measurement.
#[allow(
clippy::disallowed_methods,
reason = "the diagnostics overlay is the one place that measures wall time"
)]
pub(crate) fn start() -> Self {
Self {
start: Instant::now(),
}
}
/// The time spent since [`Stopwatch::start`].
pub(crate) fn elapsed(self) -> Duration {
self.start.elapsed()
}
}
/// The rolling window behind the diagnostics panel.
pub(crate) struct Metrics {
last: Instant,
clock: f32,
window: VecDeque<Sample>,
history: VecDeque<[f32; 2]>,
last_ticks: Option<u64>,
rtf: Option<f32>,
primed: bool,
stats: Stats,
}
impl Default for Metrics {
fn default() -> Self {
Self::new()
}
}
impl Metrics {
/// Starts the frame clock.
#[allow(
clippy::disallowed_methods,
reason = "the diagnostics overlay is the one place that measures wall time"
)]
pub(crate) fn new() -> Self {
Self {
last: Instant::now(),
clock: 0.0,
window: VecDeque::with_capacity(HISTORY),
history: VecDeque::with_capacity(HISTORY),
last_ticks: None,
rtf: None,
primed: false,
stats: Stats::default(),
}
}
/// Wall time since the previous call, that is the previous frame's duration.
#[allow(
clippy::disallowed_methods,
reason = "the diagnostics overlay is the one place that measures wall time"
)]
pub(crate) fn frame_time(&mut self) -> Duration {
let now = Instant::now();
let elapsed = now.duration_since(self.last);
self.last = now;
elapsed
}
/// Keeps the latest simulation-to-wall ratio reported by the pacer.
pub(crate) fn set_rtf(&mut self, rtf: Option<f32>) {
if rtf.is_some() {
self.rtf = rtf;
}
}
/// Adds one frame to the rolling window and refreshes the aggregates.
///
/// The first frame is warm-up: it measures window setup and pipeline
/// compilation, not a steady-state frame, and would dominate the graph.
/// Returns `false` for that frame, so observers can skip it as well.
pub(crate) fn record(&mut self, frame: Duration, work: FrameWork) -> bool {
if !self.primed {
self.primed = true;
return false;
}
let frame_ms = frame.as_secs_f32() * 1000.0;
let physics_ms = work.physics.as_secs_f32() * 1000.0;
let render_ms = work.render.as_secs_f32() * 1000.0;
self.clock += frame.as_secs_f32();
let sample: ProcSample = proc::sample();
let cpu_ticks = match (sample.ticks, self.last_ticks) {
(Some(now), Some(before)) => u32::try_from(now.saturating_sub(before)).unwrap_or(0),
_ => 0,
};
self.last_ticks = sample.ticks.or(self.last_ticks);
self.window.push_back(Sample {
at: self.clock,
frame_ms,
physics_ms,
render_ms,
steps: work.steps,
cpu_ticks,
});
self.trim();
self.stats = self.aggregate(sample);
self.history.push_back([frame_ms, physics_ms]);
if self.history.len() > HISTORY {
self.history.pop_front();
}
true
}
/// The latest rolling values, as shown in the overlay.
pub(crate) fn stats(&self) -> Stats {
self.stats
}
/// Drops samples that fell out of the statistics window.
fn trim(&mut self) {
while self.window.len() > 1 {
let span = self
.window
.front()
.map_or(0.0, |sample| self.clock - sample.at);
if span <= WINDOW_SECONDS {
break;
}
self.window.pop_front();
}
}
/// Folds the window into one-shot averages and maxima.
fn aggregate(&self, sample: ProcSample) -> Stats {
let mut stats = Stats {
load_1m: sample.load_1m,
rss_mb: sample.rss_mb,
rtf: self.rtf.unwrap_or(0.0),
..Stats::default()
};
let Some(first) = self.window.front() else {
return stats;
};
let span = (self.clock - first.at).max(0.0);
let count = self.window.len().saturating_sub(1) as f32;
let mut frame_sum = 0.0;
let mut physics_sum = 0.0;
let mut render_sum = 0.0;
let mut steps = 0;
let mut ticks = 0_u32;
for sample in &self.window {
frame_sum += sample.frame_ms;
physics_sum += sample.physics_ms;
render_sum += sample.render_ms;
steps += sample.steps;
ticks = ticks.saturating_add(sample.cpu_ticks);
stats.frame_max_ms = stats.frame_max_ms.max(sample.frame_ms);
stats.physics_max_ms = stats.physics_max_ms.max(sample.physics_ms);
}
let frames = self.window.len() as f32;
if span > 0.0 {
stats.fps = count / span;
stats.tps = steps as f32 / span;
stats.cpu_percent = ticks as f32 / span / TICKS_PER_SECOND * 100.0;
}
if frames > 0.0 {
stats.frame_avg_ms = frame_sum / frames;
stats.physics_avg_ms = physics_sum / frames;
stats.render_avg_ms = render_sum / frames;
}
stats
}
}

View file

@ -0,0 +1,153 @@
//! Panel layout for the diagnostics overlay: one text line per metric and a
//! scrolling frame-time graph.
use fabrilis_render::{Overlay, OverlayLine, OverlayRect, OverlayText};
use super::{HISTORY, Metrics};
const PANEL_X: f32 = 12.0;
const PANEL_Y: f32 = 12.0;
const PANEL_WIDTH: f32 = 300.0;
const PADDING: f32 = 10.0;
const FONT_SIZE: f32 = 14.0;
const LABEL_SIZE: f32 = 11.0;
const LINE_HEIGHT: f32 = 17.0;
const GRAPH_WIDTH: f32 = 280.0;
const GRAPH_HEIGHT: f32 = 90.0;
const GRAPH_LABEL_SPACE: f32 = 14.0;
const PANEL_COLOR: [f32; 4] = [0.03, 0.04, 0.05, 0.82];
const GRAPH_COLOR: [f32; 4] = [0.0, 0.0, 0.0, 0.45];
const TEXT_COLOR: [f32; 4] = [0.90, 0.93, 0.96, 1.0];
const DIM_COLOR: [f32; 4] = [0.55, 0.60, 0.66, 1.0];
const GRID_COLOR: [f32; 4] = [1.0, 1.0, 1.0, 0.14];
const FRAME_COLOR: [f32; 4] = [0.35, 0.95, 0.55, 1.0];
const FRAME_FILL: [f32; 4] = [0.35, 0.95, 0.55, 0.18];
const PHYSICS_COLOR: [f32; 4] = [1.0, 0.70, 0.25, 1.0];
impl Metrics {
/// Draws the diagnostics panel and its graph into `overlay`.
pub(crate) fn draw_panel(&self, overlay: &mut Overlay) {
let lines = self.lines();
let graph_top = PANEL_Y + PADDING + LINE_HEIGHT * lines.len() as f32 + GRAPH_LABEL_SPACE;
let height = graph_top - PANEL_Y + GRAPH_LABEL_SPACE + GRAPH_HEIGHT + PADDING;
overlay.push_rect(OverlayRect::new(
PANEL_X,
PANEL_Y,
PANEL_WIDTH,
height,
PANEL_COLOR,
));
let mut y = PANEL_Y + PADDING;
for line in &lines {
overlay.push_text(OverlayText::new(
PANEL_X + PADDING,
y,
FONT_SIZE,
TEXT_COLOR,
line.as_str(),
));
y += LINE_HEIGHT;
}
self.draw_graph(overlay, [PANEL_X + PADDING, graph_top]);
}
/// One text line per metric.
fn lines(&self) -> Vec<String> {
let stats = self.stats;
vec![
format!("FPS {:>6.1}", stats.fps),
format!("TPS {:>6.1}", stats.tps),
format!(
"frame {:>6.2} avg {:>6.2} max",
stats.frame_avg_ms, stats.frame_max_ms
),
format!(
"phys {:>6.2} avg {:>6.2} max",
stats.physics_avg_ms, stats.physics_max_ms
),
format!("render {:>6.2} avg", stats.render_avg_ms),
format!("rtf {:>5.2}", stats.rtf),
format!("cpu {:>5.1} %", stats.cpu_percent),
format!("load {:>5.2}", stats.load_1m),
format!("rss {:>6.1} MB", stats.rss_mb),
]
}
/// Frame and physics series with a shared auto-scaled axis.
fn draw_graph(&self, overlay: &mut Overlay, origin: [f32; 2]) {
let [x, y] = origin;
let max = self
.history
.iter()
.map(|point| point[0].max(point[1]))
.fold(1.0_f32, f32::max);
overlay.push_rect(OverlayRect::new(
x,
y,
GRAPH_WIDTH,
GRAPH_HEIGHT,
GRAPH_COLOR,
));
overlay.push_text(OverlayText::new(
x,
y - GRAPH_LABEL_SPACE + 3.0,
LABEL_SIZE,
DIM_COLOR,
format!("{max:.1} ms max"),
));
overlay.push_text(OverlayText::new(
x + GRAPH_WIDTH - 30.0,
y + GRAPH_HEIGHT - LABEL_SIZE - 2.0,
LABEL_SIZE,
DIM_COLOR,
"0 ms",
));
for step in 0..=4 {
let line_y = y + GRAPH_HEIGHT * step as f32 / 4.0;
overlay.push_line(OverlayLine::new(
[x, line_y],
[x + GRAPH_WIDTH, line_y],
1.0,
GRID_COLOR,
));
}
self.draw_series(overlay, origin, max);
}
/// Area fill and polyline for both series, newest point on the right edge.
fn draw_series(&self, overlay: &mut Overlay, origin: [f32; 2], max: f32) {
let [x, y] = origin;
let count = self.history.len();
if count == 0 {
return;
}
let step = GRAPH_WIDTH / (HISTORY - 1) as f32;
let mut previous_frame: Option<[f32; 2]> = None;
let mut previous_physics: Option<[f32; 2]> = None;
for (index, point) in self.history.iter().enumerate() {
let px = x + GRAPH_WIDTH - step * (count - 1 - index) as f32;
let frame = y + GRAPH_HEIGHT - travel(point[0], max);
let physics = y + GRAPH_HEIGHT - travel(point[1], max);
overlay.push_rect(OverlayRect::new(
px,
frame,
step.max(1.0),
(y + GRAPH_HEIGHT - frame).max(0.0),
FRAME_FILL,
));
if let Some(last) = previous_frame {
overlay.push_line(OverlayLine::new(last, [px, frame], 1.5, FRAME_COLOR));
}
if let Some(last) = previous_physics {
overlay.push_line(OverlayLine::new(last, [px, physics], 1.2, PHYSICS_COLOR));
}
previous_frame = Some([px, frame]);
previous_physics = Some([px, physics]);
}
}
}
/// A non-negative value scaled into graph pixels against the axis maximum.
fn travel(value: f32, max: f32) -> f32 {
(value / max).clamp(0.0, 1.0) * GRAPH_HEIGHT
}

View file

@ -0,0 +1,63 @@
//! Process counters read from `/proc`, with neutral fallbacks elsewhere.
//!
//! Every parser is pure: it takes the text of a `/proc` file and returns
//! `None` for malformed input instead of panicking.
/// One read of the process-wide counters.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub(crate) struct ProcSample {
/// User plus system CPU time of the process, in clock ticks.
pub(crate) ticks: Option<u64>,
/// One-minute load average, or zero when unavailable.
pub(crate) load_1m: f32,
/// Resident set size in mebibytes, or zero when unavailable.
pub(crate) rss_mb: f32,
}
/// Reads the counters once; a missing `/proc` leaves the fields at zero.
pub(crate) fn sample() -> ProcSample {
ProcSample {
ticks: read("/proc/self/stat").and_then(|text| parse_stat(&text)),
load_1m: read("/proc/loadavg")
.and_then(|text| parse_loadavg(&text))
.unwrap_or(0.0),
rss_mb: read("/proc/self/status")
.and_then(|text| parse_rss_mb(&text))
.unwrap_or(0.0),
}
}
fn read(path: &str) -> Option<String> {
std::fs::read_to_string(path).ok()
}
/// `utime + stime` from a `/proc/<pid>/stat` line.
///
/// The command name is in parentheses and may contain spaces, so parsing starts
/// after the last closing parenthesis.
pub(crate) fn parse_stat(text: &str) -> Option<u64> {
let close = text.rfind(')')?;
let rest = text.get(close + 1..)?;
// `rest` starts at field 3 (state); utime and stime are fields 14 and 15.
let mut fields = rest.split_whitespace();
let utime = fields.nth(11)?;
let stime = fields.next()?;
let user = utime.parse::<u64>().ok()?;
let system = stime.parse::<u64>().ok()?;
Some(user.saturating_add(system))
}
/// The one-minute load average from a `/proc/loadavg` line.
pub(crate) fn parse_loadavg(text: &str) -> Option<f32> {
let value = text.split_whitespace().next()?.parse::<f32>().ok()?;
(value.is_finite() && value >= 0.0).then_some(value)
}
/// `VmRSS` from a `/proc/<pid>/status` file, converted from kB to MiB.
pub(crate) fn parse_rss_mb(text: &str) -> Option<f32> {
let line = text
.lines()
.find(|line| line.trim_start().starts_with("VmRSS:"))?;
let kilobytes = line.split_whitespace().nth(1)?.parse::<f32>().ok()?;
(kilobytes.is_finite() && kilobytes >= 0.0).then_some(kilobytes / 1024.0)
}

View file

@ -0,0 +1,247 @@
//! Tests for the `/proc` parsers, the rolling metrics window and the CSV log.
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use fabrilis_render::Overlay;
use super::*;
/// A temp directory that removes itself when the test ends.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(name: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-metrics-{name}-{}-{id}",
std::process::id()
));
std::fs::create_dir_all(&path).expect("temp directory");
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
const STAT: &str = "1234 (a) b c) S 1 2 3 4 5 6 7 8 9 10 120 34 0 0 20 0 1 0 1000 0 0";
#[test]
fn stat_ticks_sum_user_and_system_time() {
assert_eq!(proc::parse_stat(STAT), Some(154));
}
#[test]
fn stat_tolerates_parentheses_in_the_command() {
assert_eq!(
proc::parse_stat("9 (x)y) R 1 2 3 4 5 6 7 8 9 10 5 7 0"),
Some(12)
);
}
#[test]
fn malformed_stat_returns_none() {
assert_eq!(proc::parse_stat(""), None);
assert_eq!(proc::parse_stat("1234 (bash"), None);
assert_eq!(proc::parse_stat("1234 (bash) S 1 2 3"), None);
assert_eq!(
proc::parse_stat("1234 (bash) S a b c d e f g h i j x y"),
None
);
}
#[test]
fn loadavg_reads_the_first_field() {
assert_eq!(
proc::parse_loadavg("0.52 0.48 0.45 2/512 12345"),
Some(0.52)
);
assert_eq!(proc::parse_loadavg(""), None);
assert_eq!(proc::parse_loadavg("not a number"), None);
assert_eq!(proc::parse_loadavg("-1.0 0.0 0.0"), None);
}
#[test]
fn status_reads_vmrss_in_mebibytes() {
let text = "Name:\tcat\nState:\tR (running)\nVmRSS:\t 15360 kB\nThreads:\t4\n";
assert_eq!(proc::parse_rss_mb(text), Some(15.0));
assert_eq!(proc::parse_rss_mb("Name:\tcat\n"), None);
assert_eq!(proc::parse_rss_mb("VmRSS:\tgarbage kB\n"), None);
}
#[test]
fn a_spike_becomes_the_window_maximum() {
let mut metrics = Metrics::default();
metrics.record(Duration::from_millis(500), FrameWork::default());
metrics.record(
Duration::from_millis(16),
FrameWork {
physics: Duration::from_millis(1),
render: Duration::from_millis(2),
steps: 16,
},
);
metrics.record(
Duration::from_millis(90),
FrameWork {
physics: Duration::from_millis(12),
render: Duration::from_millis(2),
steps: 18,
},
);
let stats = metrics.stats;
assert!(
(stats.frame_max_ms - 90.0).abs() < 0.5,
"frame max {}",
stats.frame_max_ms
);
assert!(
(stats.physics_max_ms - 12.0).abs() < 0.5,
"physics max {}",
stats.physics_max_ms
);
assert!(
(stats.frame_avg_ms - 53.0).abs() < 0.5,
"frame average {}",
stats.frame_avg_ms
);
assert!(stats.tps > 0.0);
}
#[test]
fn the_panel_draws_text_rectangles_and_lines() {
let mut metrics = Metrics::default();
for _ in 0..4 {
metrics.record(Duration::from_millis(16), FrameWork::default());
}
let mut overlay = Overlay::new();
metrics.draw_panel(&mut overlay);
assert!(overlay.texts.len() >= 9, "one line per metric plus labels");
assert!(!overlay.rects.is_empty(), "panel and graph background");
assert!(!overlay.lines.is_empty(), "grid and series");
assert!(
overlay
.texts
.iter()
.any(|text| text.text.starts_with("FPS")),
"the panel starts with the frame rate"
);
assert!(
overlay.texts.iter().any(|text| text.text.contains("max")),
"the graph labels its maximum"
);
}
#[test]
fn the_graph_keeps_only_the_recent_frames() {
let mut metrics = Metrics::default();
for _ in 0..(HISTORY + 25) {
metrics.record(Duration::from_millis(5), FrameWork::default());
}
assert_eq!(metrics.history.len(), HISTORY);
}
#[test]
fn the_window_holds_about_one_second() {
let mut metrics = Metrics::default();
for _ in 0..200 {
metrics.record(Duration::from_millis(10), FrameWork::default());
}
assert!(
metrics.window.len() <= 101,
"the window keeps {} samples",
metrics.window.len()
);
assert!(metrics.window.len() > 10, "the window is not empty");
}
fn sample_stats() -> Stats {
Stats {
fps: 60.0,
tps: 999.5,
frame_avg_ms: 16.25,
frame_max_ms: 20.5,
physics_avg_ms: 0.5,
physics_max_ms: 1.25,
render_avg_ms: 2.0,
rtf: 1.0,
cpu_percent: 12.5,
load_1m: 0.75,
rss_mb: 312.5,
}
}
fn sample_row(stats: &Stats, frame: u64, spike: bool) -> Row<'_> {
Row {
unix_s: 1_700_000_000.125,
t_s: 4.25,
frame,
stats,
spike,
}
}
#[test]
fn the_csv_header_and_one_row_match_the_documented_columns() {
let stats = sample_stats();
let row = sample_row(&stats, 42, true);
assert_eq!(
csv::HEADER,
"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"
);
assert_eq!(
csv::format_row(&row),
"1700000000.125,4.250,42,60.0,999.5,16.25,20.50,0.50,1.25,2.00,1.00,12.5,0.75,312.5,1"
);
}
#[test]
fn a_spike_needs_a_slow_frame_or_a_slow_step() {
assert_eq!(spike_reason(20.0, 1.0), None);
assert_eq!(spike_reason(20.01, 1.0), Some("frame"));
assert_eq!(spike_reason(10.0, 1.01), Some("physics"));
assert_eq!(spike_reason(30.0, 2.0), Some("frame+physics"));
}
#[test]
fn the_csv_truncates_unless_append_is_set() {
let dir = TempDir::new("csv");
let path = dir.path.join("metrics.csv");
let stats = sample_stats();
{
let mut log = CsvLog::open(&path, false).expect("create the CSV");
log.record(&sample_row(&stats, 1, false))
.expect("first row");
log.flush().expect("flush");
}
{
let mut log = CsvLog::open(&path, true).expect("append to the CSV");
log.record(&sample_row(&stats, 2, true))
.expect("second row");
log.flush().expect("flush");
}
let text = std::fs::read_to_string(&path).expect("read the CSV");
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 3, "one header and two rows");
assert_eq!(lines[0], csv::HEADER, "the header is written once");
assert!(lines[1].starts_with("1700000000.125,4.250,1,"));
assert!(lines[1].ends_with(",0"));
assert!(lines[2].ends_with(",1"));
{
let mut log = CsvLog::open(&path, false).expect("truncate the CSV");
log.record(&sample_row(&stats, 3, false))
.expect("fresh row");
log.flush().expect("flush");
}
let text = std::fs::read_to_string(&path).expect("read the CSV");
assert_eq!(text.lines().count(), 2, "header and one fresh row");
assert!(text.lines().nth(1).is_some_and(|line| line.contains(",3,")));
}

View file

@ -1 +1,101 @@
//! fabrilis-app :: runtime - stub (see docs/ARCHITECTURE.md)
//! winit application loop for the M4c vertical slice.
mod application;
mod camera;
mod config;
mod devlog;
mod error;
mod gpu;
mod metrics;
mod scene;
mod sim;
pub use error::AppError;
use devlog::DevLog;
use devlog::startup::StartupInfo;
use gpu::WindowRenderer;
use scene::View;
use winit::window::Window;
use config::Config;
use metrics::CsvLog;
/// Runs the window loop until the user closes the window or presses Escape.
pub fn run() -> Result<(), AppError> {
application::run()
}
/// Parses the flags and environment, printing usage or the error.
fn parse_config() -> Config {
match Config::from_process() {
Ok(config::Outcome::Run(config)) => config,
Ok(config::Outcome::Help) => {
print!("{}", config::USAGE);
std::process::exit(0);
}
Err(error) => {
eprintln!("fabrilis: {error}");
eprintln!("{}", config::USAGE);
std::process::exit(2);
}
}
}
/// Opens the metrics CSV when a path was configured.
fn open_csv(config: &Config) -> Result<Option<CsvLog>, AppError> {
let Some(path) = &config.metrics_log else {
return Ok(None);
};
CsvLog::open(path, config.append)
.map(Some)
.map_err(|error| AppError::Log(format!("{}: {error}", path.display())))
}
/// Writes the startup banner, reporting a write failure without stopping the app.
fn log_startup(
dev: Option<&mut DevLog>,
config: &Config,
view: &View,
renderer: &WindowRenderer,
window: &Window,
) {
let Some(dev) = dev else {
return;
};
let gpu = renderer.info();
let size = window.inner_size();
let metrics_path = config
.metrics_log
.as_ref()
.map(|path| path.display().to_string());
let log_path = config.log.as_ref().map(|path| path.display().to_string());
let info = StartupInfo {
window: (size.width, size.height),
scale: window.scale_factor(),
terrain: view.terrain_config,
boxes: sim::DROPS.len(),
box_mass_kg: sim::BOX_MASS,
box_size_m: sim::BOX_SIZE,
eye: view.camera.eye(),
target: view.camera.target(),
adapter: &gpu.adapter,
driver: &gpu.driver,
surface: &gpu.surface,
metrics_path: metrics_path.as_deref(),
log_path: log_path.as_deref(),
dev: config.dev,
append: config.append,
};
if let Err(error) = devlog::startup::write(dev, &info) {
eprintln!("fabrilis: dev log write failed: {error}");
}
}
fn aspect(size: winit::dpi::PhysicalSize<u32>) -> f32 {
if size.height == 0 {
1.0
} else {
size.width as f32 / size.height as f32
}
}

View file

@ -0,0 +1,52 @@
//! The seeded world shown by the window: terrain, camera and collider mesh.
use fabrilis_render::{MeshData, Scene};
use fabrilis_worldgen::terrain::{Heightmap, TerrainConfig, TerrainMesh};
use super::AppError;
use super::camera::FlyCamera;
/// Render scene plus the geometry and camera state shared with physics.
pub(crate) struct View {
pub scene: Scene,
pub camera: FlyCamera,
pub heightmap: Heightmap,
pub terrain: TerrainMesh,
/// The parameters the heightmap was generated from.
pub terrain_config: TerrainConfig,
}
/// Builds the M4c slice: seeded heightmap terrain and a fly camera.
pub(crate) fn build(aspect: f32) -> Result<View, AppError> {
let config = TerrainConfig {
seed: 42,
size: 65,
extent: 100.0,
height_scale: 4.0,
..Default::default()
};
let heightmap = Heightmap::generate(config)?;
let terrain = heightmap.mesh();
let mesh = MeshData {
vertices: terrain
.vertices
.iter()
.map(|vertex| [vertex.x as f32, vertex.y as f32, vertex.z as f32])
.collect(),
indices: terrain
.indices
.iter()
.flat_map(|triangle| triangle.iter().copied())
.collect(),
};
let scene = Scene::new(mesh);
let target = heightmap.height_at(0.0, 0.0) as f32;
let camera = FlyCamera::look_at([10.0, -16.0, 7.5], [0.0, 0.0, target], aspect);
Ok(View {
scene,
camera,
heightmap,
terrain,
terrain_config: config,
})
}

View file

@ -0,0 +1,162 @@
//! Fixed-step physics for the boxes shown in the window.
mod pacing;
#[cfg(test)]
mod tests;
use std::time::Duration;
use fabrilis_core::time::SimDelta;
use fabrilis_core::units::Kilograms;
use fabrilis_core::vec::{Quat, Transform, Vec3};
use fabrilis_physics::{BodyDesc, BodyId, PhysicsBackend, RapierBackend, ShapeDesc, TrimeshDesc};
use fabrilis_render::{Instance, Scene};
use fabrilis_worldgen::terrain::{Heightmap, TerrainMesh};
use crate::runtime::AppError;
use crate::runtime::metrics::Stopwatch;
use pacing::{MAX_STEPS, Pacer};
/// Physics rate; the step never changes with the frame time.
const HZ: u64 = 1_000;
/// Edge length of each dropped box, metres.
pub(crate) const BOX_SIZE: f64 = 0.6;
/// Mass of each dropped box, kilograms.
pub(crate) const BOX_MASS: f64 = 4.0;
/// Horizontal offset and drop height above the terrain for each box.
pub(crate) const DROPS: [(f64, f64, f64); 3] =
[(-1.5, 0.4, 2.0), (1.2, -0.8, 3.6), (0.2, 1.8, 5.2)];
/// One colour per box, linear RGBA.
const COLORS: [[f32; 4]; 3] = [
[0.85, 0.35, 0.15, 1.0],
[0.20, 0.55, 0.85, 1.0],
[0.85, 0.75, 0.20, 1.0],
];
struct BoxBody {
id: BodyId,
color: [f32; 4],
}
/// The Rapier world and the boxes it drives.
pub(crate) struct Simulation {
backend: RapierBackend,
boxes: Vec<BoxBody>,
step: SimDelta,
pacer: Pacer,
total_steps: u64,
slowest_step: Duration,
}
impl Simulation {
/// Builds the terrain collider and drops the boxes into the scene.
pub(crate) fn new(
terrain: &TerrainMesh,
heightmap: &Heightmap,
scene: &mut Scene,
) -> Result<Self, AppError> {
let step = SimDelta::from_hz(HZ).ok_or_else(|| {
AppError::Physics("physics step is not a whole nanosecond".to_owned())
})?;
let mut backend = RapierBackend::new();
let collider = TrimeshDesc {
vertices: terrain.vertices.clone(),
indices: terrain.indices.clone(),
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
};
backend
.add_trimesh(collider)
.ok_or_else(|| AppError::Physics("terrain collider was rejected".to_owned()))?;
scene.instances.clear();
let mut boxes = Vec::with_capacity(DROPS.len());
for (offset, color) in DROPS.iter().zip(COLORS) {
let (x, y, drop) = *offset;
let center = Vec3::new(x, y, heightmap.height_at(x, y) + drop + BOX_SIZE * 0.5);
let id = backend.add_body(BodyDesc::dynamic(
ShapeDesc::Cuboid {
half_extents: Vec3::new(BOX_SIZE * 0.5, BOX_SIZE * 0.5, BOX_SIZE * 0.5),
},
Kilograms::new(BOX_MASS),
center,
));
let size = BOX_SIZE as f32;
scene.instances.push(Instance::box_at(
[center.x as f32, center.y as f32, center.z as f32],
[size, size, size],
color,
));
boxes.push(BoxBody { id, color });
}
Ok(Self {
backend,
boxes,
step,
pacer: Pacer::new(),
total_steps: 0,
slowest_step: Duration::ZERO,
})
}
/// Runs the fixed steps owed for this frame and copies transforms to the scene.
///
/// Diagnostics time each step individually, but only observe it: the number
/// of steps, their order and the Rapier calls stay exactly the same, so the
/// resulting state hash does not depend on logging being enabled.
pub(crate) fn advance(&mut self, scene: &mut Scene) -> pacing::Frame {
let frame = self.pacer.advance(self.step.nanos(), MAX_STEPS);
self.slowest_step = Duration::ZERO;
self.total_steps = self.total_steps.saturating_add(u64::from(frame.steps));
for _ in 0..frame.steps {
let step_start = Stopwatch::start();
self.backend.step(self.step);
self.slowest_step = self.slowest_step.max(step_start.elapsed());
}
self.sync(scene);
frame
}
/// Simulated seconds represented by the steps that have actually run.
#[must_use]
pub(crate) fn sim_seconds(&self) -> f64 {
self.total_steps as f64 * self.step.nanos() as f64 / 1_000_000_000.0
}
/// The slowest single physics step of the latest frame.
#[must_use]
pub(crate) fn slowest_step(&self) -> Duration {
self.slowest_step
}
/// Copies every body transform into its rendered instance.
fn sync(&self, scene: &mut Scene) {
for (instance, body) in scene.instances.iter_mut().zip(&self.boxes) {
let Some(transform) = self.backend.body_transform(body.id) else {
continue;
};
instance.model = model(transform, BOX_SIZE as f32);
instance.color = body.color;
}
}
}
/// A column-major model matrix for a rotated, translated box.
fn model(transform: Transform, size: f32) -> [[f32; 4]; 4] {
let [x, y, z] = transform.rotation.to_mat3().cols();
let [px, py, pz] = [
transform.position.x as f32,
transform.position.y as f32,
transform.position.z as f32,
];
[
[x.x as f32 * size, x.y as f32 * size, x.z as f32 * size, 0.0],
[y.x as f32 * size, y.y as f32 * size, y.z as f32 * size, 0.0],
[z.x as f32 * size, z.y as f32 * size, z.z as f32 * size, 0.0],
[px, py, pz, 1.0],
]
}

View file

@ -0,0 +1,102 @@
//! Wall-clock pacing for the fixed-step simulation.
//!
//! The physics step never changes: the wall clock only decides how many whole
//! steps to run for the frame and how far behind the simulation has fallen.
use std::time::{Duration, Instant};
/// Largest number of physics steps run for one rendered frame.
pub(crate) const MAX_STEPS: u32 = 50;
const NS_PER_S: u64 = 1_000_000_000;
/// Wall time beyond this is treated as a stall and not caught up in full.
const MAX_FRAME_NS: u64 = 250_000_000;
/// The RTF measurement window, roughly one second.
const WINDOW_NS: u64 = NS_PER_S;
/// What one frame of wall time asks the simulation to do.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Frame {
/// Whole fixed steps to run before drawing.
pub steps: u32,
/// Paced wall time of the frame, seconds, capped after a stall.
pub elapsed_seconds: f32,
/// Simulated-to-wall ratio for the latest window, once one has filled.
pub rtf: Option<f32>,
}
/// Whole steps that fit into `elapsed_ns`, capped at `max_steps`.
#[must_use]
pub(crate) fn steps_for(elapsed_ns: u64, step_ns: u64, max_steps: u32) -> u32 {
if step_ns == 0 {
return 0;
}
u32::try_from(elapsed_ns / step_ns)
.unwrap_or(max_steps)
.min(max_steps)
}
/// Converts a wall-clock duration to whole nanoseconds without overflowing.
fn nanos(duration: Duration) -> u64 {
u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX)
}
/// An accumulator that turns irregular frame time into fixed steps.
pub(crate) struct Pacer {
last: Instant,
accumulator_ns: u64,
window_wall_ns: u64,
window_sim_ns: u64,
}
impl Pacer {
#[allow(
clippy::disallowed_methods,
reason = "wall clock only paces the app loop"
)]
pub(crate) fn new() -> Self {
Self {
last: Instant::now(),
accumulator_ns: 0,
window_wall_ns: 0,
window_sim_ns: 0,
}
}
/// Consumes the time since the previous call and returns the steps to run.
#[allow(
clippy::disallowed_methods,
reason = "wall clock only paces the app loop"
)]
pub(crate) fn advance(&mut self, step_ns: u64, max_steps: u32) -> Frame {
let now = Instant::now();
let elapsed_ns = nanos(self.last.elapsed());
self.last = now;
let paced_ns = elapsed_ns.min(MAX_FRAME_NS);
self.accumulator_ns = self.accumulator_ns.saturating_add(paced_ns);
let steps = steps_for(self.accumulator_ns, step_ns, max_steps);
let consumed_ns = u64::from(steps).saturating_mul(step_ns);
self.accumulator_ns = self.accumulator_ns.saturating_sub(consumed_ns);
if steps == max_steps && self.accumulator_ns >= step_ns {
// Drop the backlog instead of spiralling into ever longer frames.
self.accumulator_ns = 0;
}
self.window_wall_ns = self.window_wall_ns.saturating_add(elapsed_ns);
self.window_sim_ns = self.window_sim_ns.saturating_add(consumed_ns);
let rtf = if self.window_wall_ns >= WINDOW_NS {
let ratio = self.window_sim_ns as f32 / self.window_wall_ns as f32;
self.window_wall_ns = 0;
self.window_sim_ns = 0;
Some(ratio)
} else {
None
};
Frame {
steps,
elapsed_seconds: paced_ns as f32 / NS_PER_S as f32,
rtf,
}
}
}

View file

@ -0,0 +1,41 @@
//! Tests for the fixed-step accumulator.
use super::pacing::{MAX_STEPS, steps_for};
const STEP_NS: u64 = 1_000_000;
#[test]
fn no_time_means_no_steps() {
assert_eq!(steps_for(0, STEP_NS, MAX_STEPS), 0);
}
#[test]
fn one_millisecond_is_one_step() {
assert_eq!(steps_for(STEP_NS, STEP_NS, MAX_STEPS), 1);
}
#[test]
fn sixteen_milliseconds_are_sixteen_steps() {
assert_eq!(steps_for(16_000_000, STEP_NS, MAX_STEPS), 16);
}
#[test]
fn partial_step_waits_for_the_next_frame() {
assert_eq!(steps_for(999_999, STEP_NS, MAX_STEPS), 0);
assert_eq!(steps_for(1_999_999, STEP_NS, MAX_STEPS), 1);
}
#[test]
fn a_huge_gap_is_capped() {
assert_eq!(steps_for(5_000_000_000, STEP_NS, MAX_STEPS), MAX_STEPS);
}
#[test]
fn a_zero_step_cannot_run() {
assert_eq!(steps_for(16_000_000, 0, MAX_STEPS), 0);
}
#[test]
fn a_zero_cap_runs_nothing() {
assert_eq!(steps_for(16_000_000, STEP_NS, 0), 0);
}