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,6 +1,7 @@
//! SI units, simulation time (integer ns), multi-rate scheduler, Fidelity, state snapshots, deterministic math
//! SI units, simulation time (integer ns), multi-rate scheduler, Fidelity, state snapshots, deterministic math, logging facade
pub mod fidelity;
pub mod id;
pub mod log;
pub mod math;
pub mod rng;
pub mod sched;

View file

@ -0,0 +1,71 @@
//! Level macros for the log facade.
//!
//! Call shape: `info!("target", "message {}", value)`. The first argument is
//! the target, the rest is a `format!`-style template. Both the target and the
//! formatting arguments are evaluated only when the level is enabled and a
//! sink is installed, so a disabled macro costs one atomic check.
/// Logs at [`Level::Error`](crate::log::Level::Error).
///
/// Call shape: `error!("target", "message {}", value)`.
#[macro_export]
macro_rules! error {
($target:expr, $($arg:tt)+) => {{
let level = $crate::log::Level::Error;
if $crate::log::enabled(level) {
$crate::log::emit(level, $target, format_args!($($arg)+));
}
}};
}
/// Logs at [`Level::Warn`](crate::log::Level::Warn).
///
/// Call shape: `warn!("target", "message {}", value)`.
#[macro_export]
macro_rules! warn {
($target:expr, $($arg:tt)+) => {{
let level = $crate::log::Level::Warn;
if $crate::log::enabled(level) {
$crate::log::emit(level, $target, format_args!($($arg)+));
}
}};
}
/// Logs at [`Level::Info`](crate::log::Level::Info).
///
/// Call shape: `info!("target", "message {}", value)`.
#[macro_export]
macro_rules! info {
($target:expr, $($arg:tt)+) => {{
let level = $crate::log::Level::Info;
if $crate::log::enabled(level) {
$crate::log::emit(level, $target, format_args!($($arg)+));
}
}};
}
/// Logs at [`Level::Debug`](crate::log::Level::Debug).
///
/// Call shape: `debug!("target", "message {}", value)`.
#[macro_export]
macro_rules! debug {
($target:expr, $($arg:tt)+) => {{
let level = $crate::log::Level::Debug;
if $crate::log::enabled(level) {
$crate::log::emit(level, $target, format_args!($($arg)+));
}
}};
}
/// Logs at [`Level::Trace`](crate::log::Level::Trace).
///
/// Call shape: `trace!("target", "message {}", value)`.
#[macro_export]
macro_rules! trace {
($target:expr, $($arg:tt)+) => {{
let level = $crate::log::Level::Trace;
if $crate::log::enabled(level) {
$crate::log::emit(level, $target, format_args!($($arg)+));
}
}};
}

191
crates/core/src/log/mod.rs Normal file
View file

@ -0,0 +1,191 @@
//! Logging facade: five levels, borrowed records and one process-wide sink (D35).
//!
//! Library code writes diagnostics through the level macros:
//!
//! ```
//! use fabrilis_core::log::info;
//! info!("world", "boxes={} seed={}", 12, 7);
//! ```
//!
//! The first macro argument is the target, the rest is a `format!`-style
//! template. The application installs a [`LogSink`] with [`set_sink`] and picks
//! the most detailed level with [`set_level`]. Until a sink is installed every
//! macro is one disabled check: a disabled level neither evaluates nor formats
//! its arguments.
//!
//! A [`Record`] borrows its target and message, so the facade does not allocate;
//! the sink decides what to keep and when to write it.
//!
//! `log` and `tracing` are deliberately not used (D35): this facade has no
//! dependencies and no wall-clock time of its own.
mod macros;
#[cfg(test)]
mod tests;
pub use crate::{debug, error, info, trace, warn};
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Arc, RwLock};
/// How much detail a sink receives.
///
/// The variants are ordered from least to most detailed, so
/// `level <= max_level()` means the record passes the filter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(u8)]
pub enum Level {
/// Work cannot continue: a device or project failed to load.
Error,
/// Work continues with degraded behaviour.
Warn,
/// Lifecycle events, once per event.
#[default]
Info,
/// Summaries and important state changes.
Debug,
/// Per-frame or per-step detail for investigation only.
Trace,
}
impl Level {
/// Position in the filter, lowest first.
#[must_use]
pub const fn rank(self) -> u8 {
self as u8
}
/// Level for `rank`; unknown values fall back to the most detailed level.
const fn from_rank(rank: u8) -> Self {
match rank {
0 => Self::Error,
1 => Self::Warn,
2 => Self::Info,
3 => Self::Debug,
_ => Self::Trace,
}
}
}
impl fmt::Display for Level {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> 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)
}
}
/// One borrowed log message handed to a [`LogSink`].
#[derive(Debug, Clone, Copy)]
pub struct Record<'a> {
/// Severity of the event.
pub level: Level,
/// Module or subsystem that reports the event.
pub target: &'a str,
/// Message, formatted only after the level check.
pub message: fmt::Arguments<'a>,
}
/// Destination for log records: a file, stderr or a test collector.
///
/// The application installs one sink for the whole process. A sink must not
/// panic and should report its own write failures, because the facade has no
/// error channel.
pub trait LogSink: Send + Sync {
/// Receives one record that already passed the level filter.
fn log(&self, record: &Record<'_>);
}
/// Most detailed level that may reach the sink.
static MAX_LEVEL: AtomicU8 = AtomicU8::new(Level::Info as u8);
/// Fast check that a sink is installed, before taking the lock.
static SINK_INSTALLED: AtomicBool = AtomicBool::new(false);
/// The installed sink; `None` keeps the facade silent.
static SINK: RwLock<Option<Arc<dyn LogSink>>> = RwLock::new(None);
/// Returns the most detailed level that is currently enabled.
#[must_use]
pub fn max_level() -> Level {
Level::from_rank(MAX_LEVEL.load(Ordering::Relaxed))
}
/// Sets the most detailed level that may reach the sink.
///
/// Records above this level are dropped before their arguments are formatted.
pub fn set_level(level: Level) {
MAX_LEVEL.store(level.rank(), Ordering::Relaxed);
}
/// Installs `sink`, replacing any previous one, and enables logging.
///
/// The sink stays installed until [`clear_sink`]; installing a new sink is
/// safe at any time.
pub fn set_sink(sink: Arc<dyn LogSink>) {
let mut slot = match SINK.write() {
Ok(slot) => slot,
Err(poisoned) => poisoned.into_inner(),
};
*slot = Some(sink);
SINK_INSTALLED.store(true, Ordering::Release);
}
/// Removes the installed sink and disables logging.
///
/// Mainly for shutdown and tests: normal applications install a sink once.
pub fn clear_sink() {
SINK_INSTALLED.store(false, Ordering::Release);
let mut slot = match SINK.write() {
Ok(slot) => slot,
Err(poisoned) => poisoned.into_inner(),
};
*slot = None;
}
/// Whether a record at `level` would currently reach a sink.
///
/// Both the level filter and the installed sink are checked, so callers can
/// use this to skip expensive message construction.
#[must_use]
pub fn enabled(level: Level) -> bool {
level <= max_level() && SINK_INSTALLED.load(Ordering::Acquire)
}
/// Sends one record to the installed sink when the level is enabled.
///
/// The macros call this after their own [`enabled`] check, so they avoid
/// building `message` for a disabled level. Code that already has formatted
/// arguments may call it directly.
pub fn emit(level: Level, target: &str, message: fmt::Arguments<'_>) {
if !enabled(level) {
return;
}
let record = Record {
level,
target,
message,
};
if let Some(sink) = installed_sink() {
sink.log(&record);
}
}
/// Clones the installed sink without holding the lock while it logs.
fn installed_sink() -> Option<Arc<dyn LogSink>> {
if !SINK_INSTALLED.load(Ordering::Acquire) {
return None;
}
let slot = match SINK.read() {
Ok(slot) => slot,
Err(poisoned) => poisoned.into_inner(),
};
slot.clone()
}

View file

@ -0,0 +1,210 @@
//! Tests for level filtering, sink installation and lazy formatting.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use super::*;
use crate::{debug, error, info, trace, warn};
/// Serializes tests that use the process-wide level and sink.
static GLOBAL: Mutex<()> = Mutex::new(());
/// One recorded call: level, target and already formatted message.
type Entry = (Level, String, String);
/// Collects records in memory for assertions.
#[derive(Default)]
struct Collector {
records: Mutex<Vec<Entry>>,
}
impl Collector {
fn snapshot(&self) -> Vec<Entry> {
match self.records.lock() {
Ok(records) => records.clone(),
Err(poisoned) => poisoned.into_inner().clone(),
}
}
}
impl LogSink for Collector {
fn log(&self, record: &Record<'_>) {
let entry = (
record.level,
record.target.to_owned(),
record.message.to_string(),
);
match self.records.lock() {
Ok(mut records) => records.push(entry),
Err(poisoned) => poisoned.into_inner().push(entry),
}
}
}
/// Acquires the global test lock, recovering it after a failed test.
fn global_lock() -> MutexGuard<'static, ()> {
match GLOBAL.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}
#[test]
fn levels_are_ordered_from_error_to_trace_and_print_lowercase() {
assert!(Level::Error < Level::Warn);
assert!(Level::Warn < Level::Info);
assert!(Level::Info < Level::Debug);
assert!(Level::Debug < Level::Trace);
assert_eq!(Level::Error.to_string(), "error");
assert_eq!(Level::Warn.to_string(), "warn");
assert_eq!(Level::Info.to_string(), "info");
assert_eq!(Level::Debug.to_string(), "debug");
assert_eq!(Level::Trace.to_string(), "trace");
}
#[test]
fn enabled_follows_the_max_level_and_the_installed_sink() {
let _guard = global_lock();
let collector = Arc::new(Collector::default());
set_level(Level::Info);
set_sink(collector);
assert!(enabled(Level::Error));
assert!(enabled(Level::Warn));
assert!(enabled(Level::Info));
assert!(!enabled(Level::Debug));
assert!(!enabled(Level::Trace));
assert_eq!(max_level(), Level::Info);
set_level(Level::Trace);
assert_eq!(max_level(), Level::Trace);
assert!(enabled(Level::Trace));
clear_sink();
assert!(!enabled(Level::Error), "no sink means no logging");
}
#[test]
fn a_disabled_level_does_not_reach_the_sink() {
let _guard = global_lock();
let collector = Arc::new(Collector::default());
set_level(Level::Info);
set_sink(collector.clone());
debug!("test", "too detailed {}", 1);
trace!("test", "even more {}", 2);
info!("test", "kept {}", 3);
warn!("test", "also kept {}", 4);
assert_eq!(
collector.snapshot(),
vec![
(Level::Info, "test".to_owned(), "kept 3".to_owned()),
(Level::Warn, "test".to_owned(), "also kept 4".to_owned()),
]
);
clear_sink();
}
#[test]
fn an_enabled_macro_passes_level_target_and_message() {
let _guard = global_lock();
let collector = Arc::new(Collector::default());
set_level(Level::Debug);
set_sink(collector.clone());
warn!("scene", "bodies={} mass={:.1}", 4, 2.5);
debug!("scene", "camera eye={:.2}", 1.25);
let records = collector.snapshot();
assert_eq!(records.len(), 2);
assert_eq!(
records.first(),
Some(&(
Level::Warn,
"scene".to_owned(),
"bodies=4 mass=2.5".to_owned()
))
);
assert_eq!(
records.get(1),
Some(&(
Level::Debug,
"scene".to_owned(),
"camera eye=1.25".to_owned()
))
);
clear_sink();
}
#[test]
fn a_disabled_macro_does_not_evaluate_or_format_its_arguments() {
let _guard = global_lock();
let collector = Arc::new(Collector::default());
set_level(Level::Info);
set_sink(collector.clone());
let evaluated = AtomicUsize::new(0);
debug!("test", "value={}", {
evaluated.fetch_add(1, Ordering::Relaxed);
42
});
assert_eq!(
evaluated.load(Ordering::Relaxed),
0,
"disabled level ran the argument"
);
assert!(collector.snapshot().is_empty());
set_level(Level::Debug);
debug!("test", "value={}", {
evaluated.fetch_add(1, Ordering::Relaxed);
42
});
assert_eq!(evaluated.load(Ordering::Relaxed), 1);
assert_eq!(
collector.snapshot(),
vec![(Level::Debug, "test".to_owned(), "value=42".to_owned())]
);
clear_sink();
}
#[test]
fn reinstalling_the_sink_replaces_it_without_panicking() {
let _guard = global_lock();
let first = Arc::new(Collector::default());
let second = Arc::new(Collector::default());
set_level(Level::Info);
set_sink(first.clone());
set_sink(second.clone());
info!("test", "second sink");
assert!(first.snapshot().is_empty());
assert_eq!(second.snapshot().len(), 1);
clear_sink();
}
#[test]
fn without_a_sink_nothing_is_enabled_and_nothing_panics() {
let _guard = global_lock();
clear_sink();
set_level(Level::Trace);
assert!(!enabled(Level::Error));
error!("test", "dropped {}", 1);
info!("test", "dropped {}", 2);
warn!("test", "dropped {}", 3);
assert!(!enabled(Level::Info));
}
#[test]
fn a_poisoned_sink_lock_is_recovered_without_a_panic() {
let _guard = global_lock();
clear_sink();
let poison = std::thread::spawn(|| {
let _guard = match SINK.write() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
panic!("poison the sink lock on purpose");
});
assert!(poison.join().is_err(), "the helper thread panics");
let collector = Arc::new(Collector::default());
set_level(Level::Info);
set_sink(collector.clone());
info!("test", "recovered");
assert_eq!(
collector.snapshot(),
vec![(Level::Info, "test".to_owned(), "recovered".to_owned())]
);
clear_sink();
}

View file

@ -91,42 +91,78 @@ macro_rules! quantity {
};
}
quantity!(/// Length, m.
Meters);
quantity!(/// Mass, kg.
Kilograms);
quantity!(/// Time, s (for physics; the scheduler step is set in integer ns).
Seconds);
quantity!(/// Speed, m/s.
MetersPerSecond);
quantity!(/// Force, N.
Newtons);
quantity!(/// Pressure and material stress, Pa.
Pascals);
quantity!(/// Energy, J.
Joules);
quantity!(/// Power, W.
Watts);
quantity!(/// Temperature, K.
Kelvin);
quantity!(/// Electric potential, V.
Volts);
quantity!(/// Current, A.
Amps);
quantity!(/// Resistance, Ohm.
Ohms);
quantity!(/// Angle, rad.
Radians);
quantity!(/// Angular velocity, rad/s.
RadiansPerSecond);
quantity!(/// Acceleration, m/s².
MetersPerSecondSquared);
quantity!(/// Torque, N·m.
NewtonMeters);
quantity!(/// Volume, m³.
CubicMeters);
quantity!(/// Density, kg/m³.
KilogramsPerCubicMeter);
quantity!(
/// Length, m.
Meters
);
quantity!(
/// Mass, kg.
Kilograms
);
quantity!(
/// Time, s (for physics; the scheduler step is set in integer ns).
Seconds
);
quantity!(
/// Speed, m/s.
MetersPerSecond
);
quantity!(
/// Force, N.
Newtons
);
quantity!(
/// Pressure and material stress, Pa.
Pascals
);
quantity!(
/// Energy, J.
Joules
);
quantity!(
/// Power, W.
Watts
);
quantity!(
/// Temperature, K.
Kelvin
);
quantity!(
/// Electric potential, V.
Volts
);
quantity!(
/// Current, A.
Amps
);
quantity!(
/// Resistance, Ohm.
Ohms
);
quantity!(
/// Angle, rad.
Radians
);
quantity!(
/// Angular velocity, rad/s.
RadiansPerSecond
);
quantity!(
/// Acceleration, m/s².
MetersPerSecondSquared
);
quantity!(
/// Torque, N·m.
NewtonMeters
);
quantity!(
/// Volume, m³.
CubicMeters
);
quantity!(
/// Density, kg/m³.
KilogramsPerCubicMeter
);
impl Radians {
/// Converts degrees to radians; degrees exist only at the UI and import boundary.