Finish M4: cart, log facade, idle diagnostics and terrain LOD

Add the core::log facade with five levels and a sink; migrate the app dev log and enable trace in --dev. Replace the dropped cubes with a four-wheel cart on revolute joints driven by velocity motors, add WASD controls, a golden trajectory and a slope test. Instrument idle frame spikes and throttle the window title. Add chunked terrain LOD with skirts (2368 vs 8192 triangles) while physics keeps the full mesh. Pin Rust 1.100.0; edition stays 2024.
This commit is contained in:
Loki 2026-11-17 14:32:52 +01:00
parent 190ef9cc4b
commit 1042269d7e
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
38 changed files with 2348 additions and 374 deletions

View file

@ -1,8 +1,14 @@
//! The application handler: window installation, resize, redraw and logging.
use std::sync::Arc;
mod title;
#[cfg(test)]
mod tests;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use fabrilis_core::log::{Level, error, info, set_level, set_sink, warn};
use fabrilis_render::Overlay;
use winit::application::ApplicationHandler;
use winit::dpi::PhysicalSize;
@ -13,29 +19,38 @@ use winit::window::{Window, WindowId};
use super::camera::Controls;
use super::config::Config;
use super::devlog::{self, DevLog, Level};
use super::devlog::{self, DevLog, DevLogSink};
use super::gpu::WindowRenderer;
use super::metrics::{CsvLog, FrameWork, Metrics, Row, Stopwatch, spike_reason, unix_now};
use super::metrics::{
CsvLog, FrameDetail, FrameWork, Metrics, Row, Stopwatch, spike_reason, unix_now,
};
use super::scene::View;
use super::sim::Simulation;
use super::{AppError, aspect, log_startup};
use super::{AppError, aspect};
use title::title_due;
/// 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
Level::Trace
} else {
Level::Info
};
set_level(level);
let dev = match &config.log {
Some(path) => Some(
DevLog::open(path, level, config.append)
Some(path) => Some(Arc::new(Mutex::new(
DevLog::open(path, config.append)
.map_err(|error| AppError::Log(format!("{}: {error}", path.display())))?,
),
))),
None => None,
};
// The sink is installed before the event loop, so the startup banner and
// every later record go through the same facade.
if let Some(log) = &dev {
set_sink(Arc::new(DevLogSink::new(Arc::clone(log))));
}
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);
@ -51,7 +66,7 @@ pub(super) fn run() -> Result<(), AppError> {
struct Fabrilis {
config: Config,
csv: Option<CsvLog>,
dev: Option<DevLog>,
dev: Option<Arc<Mutex<DevLog>>>,
frame: u64,
window: Option<Arc<Window>>,
renderer: Option<WindowRenderer>,
@ -60,10 +75,11 @@ struct Fabrilis {
controls: Controls,
metrics: Metrics,
overlay: Overlay,
title_clock: Duration,
}
impl Fabrilis {
fn new(config: Config, csv: Option<CsvLog>, dev: Option<DevLog>) -> Self {
fn new(config: Config, csv: Option<CsvLog>, dev: Option<Arc<Mutex<DevLog>>>) -> Self {
Self {
config,
csv,
@ -76,6 +92,7 @@ impl Fabrilis {
controls: Controls::default(),
metrics: Metrics::default(),
overlay: Overlay::new(),
title_clock: Duration::ZERO,
}
}
@ -91,7 +108,7 @@ impl Fabrilis {
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);
super::log_startup(&self.config, &view, &renderer, &window, &simulation);
self.window = Some(window);
self.renderer = Some(renderer);
self.view = Some(view);
@ -117,39 +134,58 @@ impl Fabrilis {
}
}
/// Refreshes the RTF in the window title at most once per second.
///
/// The clock accumulates frame time instead of reading wall time, so the
/// policy stays testable and frames that are not due pay nothing.
fn update_title(
window: Option<&Window>,
clock: &mut Duration,
frame_time: Duration,
rtf: Option<f32>,
) -> Duration {
*clock = clock.saturating_add(frame_time);
if !title_due(*clock) {
return Duration::ZERO;
}
let (Some(rtf), Some(window)) = (rtf, window) else {
return Duration::ZERO;
};
let start = Stopwatch::start();
window.set_title(&format!("Fabrilis — RTF {rtf:.2}"));
*clock = Duration::ZERO;
start.elapsed()
}
fn redraw(&mut self) {
let Some(view) = self.view.as_mut() else {
let (Some(view), Some(simulation)) = (self.view.as_mut(), self.simulation.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 unix_s = self.csv.is_some().then(unix_now);
let frame_time = self.metrics.frame_time();
let physics_start = Stopwatch::start();
let frame = simulation.advance(&mut view.scene);
let frame = simulation.advance(&mut view.scene, self.controls.drive());
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}"));
}
view.update_terrain_lod(view.camera.eye());
let title = Self::update_title(
self.window.as_deref(),
&mut self.title_clock,
frame_time,
frame.rtf,
);
self.metrics.set_rtf(frame.rtf);
let camera = view.camera.view();
let size = self
.renderer
.as_ref()
.map_or((0, 0), |renderer| renderer.size());
let size = self.renderer.as_ref().map_or((0, 0), WindowRenderer::size);
let overlay_start = Stopwatch::start();
self.overlay.clear();
if size.0 > 0 && size.1 > 0 {
self.metrics.draw_panel(&mut self.overlay);
}
let overlay = overlay_start.elapsed();
let Some(renderer) = self.renderer.as_mut() else {
return;
};
@ -158,7 +194,7 @@ impl Fabrilis {
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());
error!("render", "{error}");
}
let recorded = self.metrics.record(
frame_time,
@ -172,23 +208,25 @@ impl Fabrilis {
return;
}
self.frame = self.frame.saturating_add(1);
self.log_frame(frame_time, slowest_step_ms, sim_seconds, unix_s);
let detail = FrameDetail {
frame_ms: frame_time.as_secs_f32() * 1000.0,
physics_step_ms: slowest_step_ms,
render_ms: render.as_secs_f32() * 1000.0,
overlay_ms: overlay.as_secs_f32() * 1000.0,
title_ms: title.as_secs_f32() * 1000.0,
metrics_us: self.metrics.sample_time().as_secs_f32() * 1_000_000.0,
steps: frame.steps,
};
self.log_frame(detail, 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>,
) {
fn log_frame(&mut self, detail: FrameDetail, 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);
let spike = spike_reason(detail.frame_ms, detail.physics_step_ms);
if let Some(unix_s) = unix_s {
let row = Row {
unix_s,
@ -201,28 +239,23 @@ impl Fabrilis {
&& let Err(error) = csv.record(&row)
{
eprintln!("fabrilis: metrics log write failed: {error}");
write_dev(&mut self.dev, Level::Error, "metrics", &error.to_string());
error!("metrics", "{error}");
}
}
if let Some(dev) = self.dev.as_mut() {
if dev.summary_due() {
write_line(dev, Level::Info, "metrics", &devlog::summary(&stats));
if let Some(dev) = &self.dev {
let summary_due = devlog::lock(dev).summary_due();
if summary_due {
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);
warn!("spike", "{}", devlog::spike(self.frame, &detail, trigger));
}
}
}
/// 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}"),
);
fn report(&self, context: &str, detail: &str) {
error!("app", "{context}: {detail}");
}
/// Flushes the CSV and closes the dev session.
@ -232,7 +265,7 @@ impl Fabrilis {
{
eprintln!("fabrilis: metrics log flush failed: {error}");
}
write_dev(&mut self.dev, Level::Info, "app", "session end");
info!("app", "session end");
}
fn is_escape(event: &KeyEvent) -> bool {
@ -248,20 +281,6 @@ impl Fabrilis {
}
}
/// 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() {

View file

@ -0,0 +1,18 @@
//! Tests for the window title refresh policy.
use std::time::Duration;
use super::title::title_due;
#[test]
fn the_title_is_not_due_before_the_interval() {
assert!(!title_due(Duration::ZERO));
assert!(!title_due(Duration::from_millis(999)));
}
#[test]
fn the_title_is_due_once_the_interval_has_passed() {
assert!(title_due(Duration::from_secs(1)));
assert!(title_due(Duration::from_millis(1_500)));
assert!(title_due(Duration::from_secs(5)));
}

View file

@ -0,0 +1,20 @@
//! Window title refresh policy.
//!
//! The title only carries the simulation clock ratio, which the pacer updates
//! roughly once per second. Asking the compositor for a new title on every
//! frame adds a surface commit per frame on Wayland, so the update is
//! throttled instead.
use std::time::Duration;
/// Minimum wall time between two title updates.
const TITLE_INTERVAL: Duration = Duration::from_secs(1);
/// Whether the title is due after the time accumulated since the last update.
///
/// Pure so the boundary is testable without a wall clock: exactly one second
/// counts as due, everything below does not.
#[must_use]
pub(crate) fn title_due(elapsed: Duration) -> bool {
elapsed >= TITLE_INTERVAL
}