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,9 @@
//! Dev text log: wall-clock stamped lines with a level, a target and a message.
//! Dev text log: a [`LogSink`] that writes wall-clock stamped lines.
//!
//! 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.
//! the simulation. The app installs [`DevLogSink`] into the `fabrilis_core::log`
//! facade before the startup banner, so every record goes through one filter.
//!
//! Line shape: `unix_s level target message`.
@ -14,68 +15,32 @@ mod tests;
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::Path;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use crate::runtime::metrics::Stats;
use fabrilis_core::log::{Level, LogSink, Record};
/// 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)
}
}
use crate::runtime::metrics::{FrameDetail, Stats};
/// How often a metrics summary line is written, seconds.
const SUMMARY_INTERVAL_SECONDS: u64 = 1;
/// A dev log file, truncated or created when opened.
///
/// The facade already applies the level filter, so the log writes every record
/// it receives.
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.
/// Creates or opens the file, truncating it unless `append` is set.
#[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> {
pub(crate) fn open(path: &Path, append: bool) -> io::Result<Self> {
let file = OpenOptions::new()
.create(true)
.write(true)
@ -84,16 +49,12 @@ impl DevLog {
.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()
@ -113,6 +74,35 @@ impl DevLog {
}
}
/// [`LogSink`] adapter over the shared dev log file.
pub(crate) struct DevLogSink {
log: Arc<Mutex<DevLog>>,
}
impl DevLogSink {
pub(crate) fn new(log: Arc<Mutex<DevLog>>) -> Self {
Self { log }
}
}
impl LogSink for DevLogSink {
fn log(&self, record: &Record<'_>) {
let message = record.message.to_string();
let mut log = lock(&self.log);
if let Err(error) = log.write(record.level, record.target, &message) {
eprintln!("fabrilis: dev log write failed: {error}");
}
}
}
/// Locks the shared dev log, recovering a poisoned mutex without panicking.
pub(crate) fn lock(log: &Mutex<DevLog>) -> MutexGuard<'_, DevLog> {
match log.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
/// 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}")
@ -137,8 +127,21 @@ pub(crate) fn summary(stats: &Stats) -> String {
}
/// 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}")
///
/// The phase fields tell a slow simulation apart from a slow renderer, an
/// expensive overlay or title update, and the `/proc` sampling cost. A frame
/// with small phases but a large `frame_ms` was delayed outside the app.
pub(crate) fn spike(frame: u64, detail: &FrameDetail, trigger: &str) -> String {
format!(
"frame={frame} frame_ms={:.2} physics_step_ms={:.3} render_ms={:.2} overlay_ms={:.2} title_ms={:.2} metrics_us={:.0} steps={} trigger={trigger}",
detail.frame_ms,
detail.physics_step_ms,
detail.render_ms,
detail.overlay_ms,
detail.title_ms,
detail.metrics_us,
detail.steps,
)
}
/// Wall-clock seconds since the Unix epoch, as a float.