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);
}

View file

@ -123,6 +123,10 @@ 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.
@ -189,6 +193,13 @@ impl Mul<Seconds> for RadiansPerSecond {
Radians(self.0 * rhs.0)
}
}
impl Mul<CubicMeters> for KilogramsPerCubicMeter {
type Output = Kilograms;
#[inline]
fn mul(self, rhs: CubicMeters) -> Kilograms {
Kilograms(self.0 * rhs.0)
}
}
#[cfg(test)]
mod tests;

View file

@ -39,3 +39,10 @@ fn derived_motion_units() {
let rate = RadiansPerSecond(3.0);
assert_eq!(rate * Seconds(2.0), Radians(6.0));
}
#[test]
fn volume_and_density_give_mass() {
let volume = CubicMeters(0.002);
let steel = KilogramsPerCubicMeter(7_850.0);
assert!(((steel * volume).get() - 15.7).abs() < 1e-9);
}

View file

@ -1 +1,89 @@
//! fabrilis-materials :: db - stub (see docs/ARCHITECTURE.md)
//! A small material database keyed by a lowercase ASCII name.
//!
//! `BTreeMap` keeps iteration order deterministic (docs/DETERMINISM.md).
use std::collections::BTreeMap;
use fabrilis_core::units::{KilogramsPerCubicMeter, Pascals};
/// Mechanical properties of a homogeneous material, in SI units.
#[derive(Debug, Clone, PartialEq)]
pub struct Material {
/// Lowercase ASCII identifier, unique within a database.
pub name: String,
/// Density, kg/m³.
pub density: KilogramsPerCubicMeter,
/// Young's modulus, Pa.
pub youngs_modulus: Pascals,
/// Yield strength, Pa.
pub yield_strength: Pascals,
}
/// Materials addressed by name.
#[derive(Debug, Clone, Default)]
pub struct MaterialDb {
materials: BTreeMap<String, Material>,
}
impl MaterialDb {
/// An empty database.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// A database with the built-in materials: `steel`, `aluminium`, `pla`.
#[must_use]
pub fn with_builtins() -> Self {
let mut db = Self::new();
for material in builtins() {
let _replaced = db.insert(material);
}
db
}
/// Inserts or replaces a material and returns the previous entry.
pub fn insert(&mut self, material: Material) -> Option<Material> {
self.materials.insert(material.name.clone(), material)
}
/// Looks up a material by name.
#[must_use]
pub fn get(&self, name: &str) -> Option<&Material> {
self.materials.get(name)
}
/// Iterates over materials in name order.
pub fn iter(&self) -> impl Iterator<Item = (&str, &Material)> + '_ {
self.materials
.iter()
.map(|(name, material)| (name.as_str(), material))
}
}
/// The three built-in materials, in name order.
fn builtins() -> [Material; 3] {
[
Material {
name: String::from("aluminium"),
density: KilogramsPerCubicMeter(2700.0),
youngs_modulus: Pascals(69.0e9),
yield_strength: Pascals(200.0e6),
},
Material {
name: String::from("pla"),
density: KilogramsPerCubicMeter(1240.0),
youngs_modulus: Pascals(3.5e9),
yield_strength: Pascals(50.0e6),
},
Material {
name: String::from("steel"),
density: KilogramsPerCubicMeter(7850.0),
youngs_modulus: Pascals(210.0e9),
yield_strength: Pascals(250.0e6),
},
]
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,56 @@
use fabrilis_core::units::{KilogramsPerCubicMeter, Pascals};
use super::*;
#[test]
fn builtins_are_present() {
let db = MaterialDb::with_builtins();
let steel = db.get("steel").unwrap();
assert_eq!(steel.density, KilogramsPerCubicMeter(7850.0));
assert_eq!(steel.youngs_modulus, Pascals(210.0e9));
assert_eq!(steel.yield_strength, Pascals(250.0e6));
let aluminium = db.get("aluminium").unwrap();
assert_eq!(aluminium.density, KilogramsPerCubicMeter(2700.0));
assert_eq!(aluminium.youngs_modulus, Pascals(69.0e9));
assert_eq!(aluminium.yield_strength, Pascals(200.0e6));
let pla = db.get("pla").unwrap();
assert_eq!(pla.density, KilogramsPerCubicMeter(1240.0));
assert_eq!(pla.youngs_modulus, Pascals(3.5e9));
assert_eq!(pla.yield_strength, Pascals(50.0e6));
assert!(db.get("unobtainium").is_none());
}
#[test]
fn iter_is_sorted_and_empty_by_default() {
let db = MaterialDb::with_builtins();
let names: Vec<&str> = db.iter().map(|(name, _)| name).collect();
assert_eq!(names, ["aluminium", "pla", "steel"]);
let empty = MaterialDb::new();
assert_eq!(empty.iter().count(), 0);
assert!(empty.get("steel").is_none());
}
#[test]
fn insert_replaces_and_returns_old() {
let mut db = MaterialDb::new();
let custom = Material {
name: String::from("steel"),
density: KilogramsPerCubicMeter(8000.0),
youngs_modulus: Pascals(200.0e9),
yield_strength: Pascals(300.0e6),
};
assert!(db.insert(custom.clone()).is_none());
assert_eq!(db.get("steel"), Some(&custom));
let replacement = Material {
density: KilogramsPerCubicMeter(8100.0),
..custom.clone()
};
let old = db.insert(replacement.clone()).unwrap();
assert_eq!(old, custom);
assert_eq!(db.get("steel"), Some(&replacement));
}

View file

@ -1 +1,144 @@
//! fabrilis-materials :: massprops - stub (see docs/ARCHITECTURE.md)
//! Mass, centre of mass and inertia tensor of a closed triangle mesh.
//!
//! The mesh is decomposed into signed tetrahedra from the origin:
//! `V = a · (b × c) / 6` per triangle `(a, b, c)`. Summing the signed
//! contributions over a watertight surface gives the volume, the first moment and
//! the second moment directly, without any absolute-value branch.
//!
//! The caller must validate that the mesh is watertight and consistently oriented
//! outwards (signed volume positive). A closed mesh with inverted winding yields a
//! negative signed volume and is rejected here; an open mesh yields a wrong volume
//! and cannot be detected from the triangle soup alone.
use fabrilis_core::units::{CubicMeters, Kilograms, KilogramsPerCubicMeter};
use fabrilis_core::vec::{Mat3, Vec3};
/// Volumes at or below this bound (m³) are treated as degenerate.
const MIN_VOLUME: f64 = 1e-12;
/// Mass properties of a solid, in SI units.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MassProperties {
/// Enclosed volume, m³.
pub volume: CubicMeters,
/// Mass, kg.
pub mass: Kilograms,
/// Centre of mass, m, in the mesh's axes.
pub center_of_mass: Vec3,
/// Inertia tensor about the centre of mass, kg·m², in world axes.
pub inertia: Mat3,
}
/// The signed volume enclosed by a triangle soup, m³.
///
/// Positive for a closed mesh wound outwards. No validation is performed here;
/// [`from_triangles`] is the checked entry point.
#[must_use]
pub fn signed_volume(triangles: &[[Vec3; 3]]) -> f64 {
triangles
.iter()
.map(|&[a, b, c]| a.dot(b.cross(c)) / 6.0)
.sum()
}
/// Mass properties of a closed, outward-oriented triangle mesh.
///
/// Returns `None` for empty or degenerate meshes (|volume| at or below
/// `MIN_VOLUME`), for a signed volume that is not positive (inverted or
/// inconsistent winding), for non-finite vertices or density, and for a
/// zero/negative density. Watertightness itself must be validated by the caller.
#[must_use]
pub fn from_triangles(
triangles: &[[Vec3; 3]],
density: KilogramsPerCubicMeter,
) -> Option<MassProperties> {
let density = density.get();
if !density.is_finite() || density <= 0.0 {
return None;
}
let mut accumulator = MomentAccumulator::default();
for &[a, b, c] in triangles {
if !a.is_finite() || !b.is_finite() || !c.is_finite() {
return None;
}
accumulator.add(a, b, c);
}
accumulator.finish(density)
}
/// Second moment about the origin, stored as `(xx, yy, zz, xy, xz, yz)`.
#[derive(Default)]
struct MomentAccumulator {
volume: f64,
first: Vec3,
second: [f64; 6],
}
impl MomentAccumulator {
/// Adds the tetrahedron `(0, a, b, c)` with its signed volume.
fn add(&mut self, a: Vec3, b: Vec3, c: Vec3) {
let s = a + b + c;
let tetra_volume = a.dot(b.cross(c)) / 6.0;
self.volume += tetra_volume;
// Centroid of the tetrahedron is `s / 4`.
self.first += s * (tetra_volume * 0.25);
let scale = tetra_volume / 20.0;
let [xx, yy, zz, xy, xz, yz] = &mut self.second;
*xx += scale * (a.x * a.x + b.x * b.x + c.x * c.x + s.x * s.x);
*yy += scale * (a.y * a.y + b.y * b.y + c.y * c.y + s.y * s.y);
*zz += scale * (a.z * a.z + b.z * b.z + c.z * c.z + s.z * s.z);
*xy += scale * (a.x * a.y + b.x * b.y + c.x * c.y + s.x * s.y);
*xz += scale * (a.x * a.z + b.x * b.z + c.x * c.z + s.x * s.z);
*yz += scale * (a.y * a.z + b.y * b.z + c.y * c.z + s.y * s.z);
}
/// Applies the parallel-axis theorem and builds the result.
fn finish(&self, density: f64) -> Option<MassProperties> {
if !self.volume.is_finite() || self.volume <= MIN_VOLUME {
return None;
}
let mass = density * self.volume;
let center = self.first / self.volume;
if !mass.is_finite() || !center.is_finite() {
return None;
}
let inertia = self.inertia_about(center, mass);
if !inertia_is_finite(inertia) {
return None;
}
Some(MassProperties {
volume: CubicMeters(self.volume),
mass: Kilograms(mass),
center_of_mass: center,
inertia,
})
}
/// Inertia about the given point: `tr(C) I - C` shifted by the parallel axis.
fn inertia_about(&self, center: Vec3, mass: f64) -> Mat3 {
let [xx, yy, zz, xy, xz, yz] = self.second;
let (dx, dy, dz) = (center.x, center.y, center.z);
// Covariance is geometric (units of m⁵); density turns it into kg·m².
let density = mass / self.volume;
// `|d|² I - d dᵀ` moves the origin of the moments to `center`.
let i_xx = density * (yy + zz) - mass * (dy * dy + dz * dz);
let i_yy = density * (xx + zz) - mass * (dx * dx + dz * dz);
let i_zz = density * (xx + yy) - mass * (dx * dx + dy * dy);
let i_xy = mass * dx * dy - density * xy;
let i_xz = mass * dx * dz - density * xz;
let i_yz = mass * dy * dz - density * yz;
Mat3::from_cols(
Vec3::new(i_xx, i_xy, i_xz),
Vec3::new(i_xy, i_yy, i_yz),
Vec3::new(i_xz, i_yz, i_zz),
)
}
}
/// True when every entry of the matrix is finite.
fn inertia_is_finite(inertia: Mat3) -> bool {
inertia.cols().iter().all(|column| column.is_finite())
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,222 @@
use fabrilis_core::math::{PI, TAU, sin_cos};
use fabrilis_core::units::KilogramsPerCubicMeter;
use fabrilis_core::vec::Vec3;
use super::*;
const DENSITY: KilogramsPerCubicMeter = KilogramsPerCubicMeter(1000.0);
/// Closed cube with outward winding; `faces` index the eight corners.
fn cube_triangles(center: Vec3, side: f64) -> Vec<[Vec3; 3]> {
let h = side * 0.5;
let corners = [
Vec3::new(-h, -h, -h),
Vec3::new(h, -h, -h),
Vec3::new(h, h, -h),
Vec3::new(-h, h, -h),
Vec3::new(-h, -h, h),
Vec3::new(h, -h, h),
Vec3::new(h, h, h),
Vec3::new(-h, h, h),
]
.map(|corner| center + corner);
let faces = [
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[1, 2, 6],
[1, 6, 5],
[0, 4, 7],
[0, 7, 3],
[3, 7, 6],
[3, 6, 2],
[0, 1, 5],
[0, 5, 4],
];
faces
.iter()
.map(|&[a, b, c]| [corners[a], corners[b], corners[c]])
.collect()
}
/// Latitude-longitude sphere with outward winding; poles are duplicated.
fn sphere_triangles(radius: f64, stacks: usize, slices: usize) -> Vec<[Vec3; 3]> {
let mut rings = Vec::with_capacity((stacks + 1) * slices);
for stack in 0..=stacks {
let theta = -PI / 2.0 + PI * stack as f64 / stacks as f64;
let (sin_theta, cos_theta) = sin_cos(theta);
for slice in 0..slices {
let phi = TAU * slice as f64 / slices as f64;
let (sin_phi, cos_phi) = sin_cos(phi);
rings.push(Vec3::new(
radius * cos_theta * cos_phi,
radius * cos_theta * sin_phi,
radius * sin_theta,
));
}
}
let mut triangles = Vec::with_capacity(stacks * slices * 2);
for stack in 0..stacks {
let lower = stack * slices;
let upper = lower + slices;
for slice in 0..slices {
let next = (slice + 1) % slices;
triangles.push([
rings[lower + slice],
rings[lower + next],
rings[upper + next],
]);
triangles.push([
rings[lower + slice],
rings[upper + next],
rings[upper + slice],
]);
}
}
triangles
}
/// Closed cylinder about Z with outward winding, caps fan-triangulated.
fn cylinder_triangles(radius: f64, height: f64, slices: usize) -> Vec<[Vec3; 3]> {
let half = height * 0.5;
let mut bottom = Vec::with_capacity(slices);
let mut top = Vec::with_capacity(slices);
for slice in 0..slices {
let angle = TAU * slice as f64 / slices as f64;
let (sin, cos) = sin_cos(angle);
bottom.push(Vec3::new(radius * cos, radius * sin, -half));
top.push(Vec3::new(radius * cos, radius * sin, half));
}
let mut triangles = Vec::with_capacity(slices * 4);
for slice in 0..slices {
let next = (slice + 1) % slices;
triangles.push([bottom[slice], bottom[next], top[next]]);
triangles.push([bottom[slice], top[next], top[slice]]);
triangles.push([Vec3::new(0.0, 0.0, half), top[slice], top[next]]);
triangles.push([Vec3::new(0.0, 0.0, -half), bottom[next], bottom[slice]]);
}
triangles
}
/// Diagonal of an inertia tensor, kg·m².
fn inertia_diagonal(inertia: Mat3) -> [f64; 3] {
let columns = inertia.cols();
[columns[0].x, columns[1].y, columns[2].z]
}
fn close(actual: f64, expected: f64, tolerance: f64) -> bool {
(actual - expected).abs() <= tolerance
}
fn assert_close(actual: f64, expected: f64, tolerance: f64) {
assert!(
(actual - expected).abs() <= tolerance,
"expected {expected}, got {actual}"
);
}
#[test]
fn cube_centred_at_origin() {
let mesh = cube_triangles(Vec3::ZERO, 1.0);
assert_close(signed_volume(&mesh), 1.0, 1e-12);
let props = from_triangles(&mesh, DENSITY).unwrap();
assert!(close(props.volume.get(), 1.0, 1e-12));
assert!(close(props.mass.get(), 1000.0, 1e-12));
assert!(close(props.center_of_mass.x, 0.0, 1e-12));
assert!(close(props.center_of_mass.y, 0.0, 1e-12));
assert!(close(props.center_of_mass.z, 0.0, 1e-12));
let expected = 1000.0 / 6.0;
for diagonal in inertia_diagonal(props.inertia) {
assert_close(diagonal, expected, 1e-12);
}
let columns = props.inertia.cols();
assert_close(columns[0].y, 0.0, 1e-12);
assert_close(columns[0].z, 0.0, 1e-12);
assert_close(columns[1].x, 0.0, 1e-12);
assert_close(columns[1].z, 0.0, 1e-12);
assert_close(columns[2].x, 0.0, 1e-12);
assert_close(columns[2].y, 0.0, 1e-12);
}
#[test]
fn cube_translated_keeps_inertia() {
let offset = Vec3::new(2.0, -1.0, 0.5);
let mesh = cube_triangles(offset, 1.0);
let props = from_triangles(&mesh, DENSITY).unwrap();
assert_close(props.volume.get(), 1.0, 1e-12);
assert_close(props.center_of_mass.x, offset.x, 1e-12);
assert_close(props.center_of_mass.y, offset.y, 1e-12);
assert_close(props.center_of_mass.z, offset.z, 1e-12);
// The origin moments are large, so the parallel-axis subtraction loses a few
// digits: 1e-9 absolute on values around 167 kg·m².
let expected = props.mass.get() / 6.0;
for diagonal in inertia_diagonal(props.inertia) {
assert!(close(diagonal, expected, 1e-9));
}
}
#[test]
fn sphere_volume_and_inertia() {
let radius = 0.5;
let mesh = sphere_triangles(radius, 32, 64);
let props = from_triangles(&mesh, DENSITY).unwrap();
let expected_volume = 4.0 / 3.0 * PI * radius * radius * radius;
assert!(close(
props.volume.get(),
expected_volume,
expected_volume * 0.01
));
let expected_inertia = 0.4 * props.mass.get() * radius * radius;
for diagonal in inertia_diagonal(props.inertia) {
assert!(close(diagonal, expected_inertia, expected_inertia * 0.02));
}
}
#[test]
fn cylinder_inertia_about_its_axis() {
let (radius, height) = (0.4, 1.2);
let mesh = cylinder_triangles(radius, height, 64);
let props = from_triangles(&mesh, KilogramsPerCubicMeter(2700.0)).unwrap();
let expected_volume = PI * radius * radius * height;
assert!(close(
props.volume.get(),
expected_volume,
expected_volume * 0.01
));
let expected = 0.5 * props.mass.get() * radius * radius;
assert!(close(props.inertia.cols()[2].z, expected, expected * 0.02));
// The cylinder is centred on the origin.
assert_close(props.center_of_mass.z, 0.0, 1e-12);
}
#[test]
fn rejects_open_or_inverted_soup() {
assert!(from_triangles(&[], DENSITY).is_none());
// Inverted winding: volume is negative, so the orientation is wrong.
let mut inverted = cube_triangles(Vec3::ZERO, 1.0);
for triangle in &mut inverted {
triangle.swap(1, 2);
}
assert_close(signed_volume(&inverted), -1.0, 1e-12);
assert!(from_triangles(&inverted, DENSITY).is_none());
// A single triangle through the origin encloses no volume.
let flat = [[Vec3::ZERO, Vec3::X, Vec3::Y]];
assert_eq!(signed_volume(&flat), 0.0);
assert!(from_triangles(&flat, DENSITY).is_none());
}
#[test]
fn rejects_bad_density() {
let mesh = cube_triangles(Vec3::ZERO, 1.0);
assert!(from_triangles(&mesh, KilogramsPerCubicMeter(0.0)).is_none());
assert!(from_triangles(&mesh, KilogramsPerCubicMeter(-100.0)).is_none());
assert!(from_triangles(&mesh, KilogramsPerCubicMeter(f64::INFINITY)).is_none());
}
#[test]
fn rejects_non_finite_vertices() {
let mut mesh = cube_triangles(Vec3::ZERO, 1.0);
mesh[0][0].x = f64::NAN;
assert!(from_triangles(&mesh, DENSITY).is_none());
}

View file

@ -1 +1,50 @@
//! fabrilis-materials :: strength - stub (see docs/ARCHITECTURE.md)
//! A minimal static strength check at a single stress value.
//!
//! The load path and stress distribution are the caller's business; this module
//! only compares a stress with the material's yield strength.
use fabrilis_core::units::Pascals;
/// Yield data used for a static check.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Strength {
/// Yield strength of the material, Pa.
pub yield_strength: Pascals,
}
impl Strength {
/// Yield strength divided by the applied stress.
///
/// `None` for a non-positive or non-finite stress, and when the resulting
/// factor is not finite.
#[must_use]
pub fn factor_of_safety(self, stress: Pascals) -> Option<f64> {
let stress = stress.get();
if !stress.is_finite() || stress <= 0.0 {
return None;
}
let factor = self.yield_strength.get() / stress;
if factor.is_finite() {
Some(factor)
} else {
None
}
}
/// True when the factor of safety reaches `required`.
///
/// `required` must be finite and positive; any invalid input is unsafe.
#[must_use]
pub fn is_safe(self, stress: Pascals, required: f64) -> bool {
if !required.is_finite() || required <= 0.0 {
return false;
}
match self.factor_of_safety(stress) {
Some(factor) => factor >= required,
None => false,
}
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,43 @@
use fabrilis_core::units::Pascals;
use super::*;
fn steel() -> Strength {
Strength {
yield_strength: Pascals(250.0e6),
}
}
#[test]
fn factor_of_safety_is_yield_over_stress() {
let factor = steel().factor_of_safety(Pascals(100.0e6)).unwrap();
assert!((factor - 2.5).abs() < 1e-12);
let factor = steel().factor_of_safety(Pascals(250.0e6)).unwrap();
assert!((factor - 1.0).abs() < 1e-12);
assert!(steel().factor_of_safety(Pascals(500.0e6)).unwrap() < 1.0);
}
#[test]
fn factor_of_safety_rejects_bad_stress() {
assert!(steel().factor_of_safety(Pascals(0.0)).is_none());
assert!(steel().factor_of_safety(Pascals(-1.0)).is_none());
assert!(steel().factor_of_safety(Pascals(f64::NAN)).is_none());
assert!(steel().factor_of_safety(Pascals(f64::INFINITY)).is_none());
}
#[test]
fn is_safe_compares_with_required_factor() {
assert!(steel().is_safe(Pascals(100.0e6), 2.5));
assert!(!steel().is_safe(Pascals(100.0e6), 2.6));
assert!(steel().is_safe(Pascals(250.0e6), 1.0));
assert!(!steel().is_safe(Pascals(250.0e6), 1.1));
}
#[test]
fn is_safe_rejects_invalid_input() {
assert!(!steel().is_safe(Pascals(0.0), 1.0));
assert!(!steel().is_safe(Pascals(-10.0), 1.0));
assert!(!steel().is_safe(Pascals(100.0e6), 0.0));
assert!(!steel().is_safe(Pascals(100.0e6), -1.0));
assert!(!steel().is_safe(Pascals(100.0e6), f64::NAN));
}

View file

@ -28,5 +28,8 @@ fabrilis-bridge = { path = "../bridge" }
fabrilis-worldgen = { path = "../worldgen" }
fabrilis-scripting = { path = "../scripting" }
[dev-dependencies]
fabrilis-sensors = { path = "../sensors" }
[build-dependencies]
fabrilis-limits = { path = "../../tools/limits" }

View file

@ -0,0 +1,129 @@
//! M4c regression: the three dropped boxes settle upright and stay put.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
reason = "test helper: a failure should abort the test"
)]
use fabrilis_core::time::SimDelta;
use fabrilis_core::units::Kilograms;
use fabrilis_core::vec::{Quat, Vec3};
use fabrilis_physics::RapierBackend;
use fabrilis_physics::backend::{BodyDesc, PhysicsBackend, ShapeDesc, TrimeshDesc};
use fabrilis_worldgen::terrain::{Heightmap, TerrainConfig};
const BOX: f64 = 0.6;
const DROPS: [(f64, f64, f64); 3] = [(-1.5, 0.4, 2.0), (1.2, -0.8, 3.6), (0.2, 1.8, 5.2)];
#[test]
fn dropped_boxes_settle_and_stop() {
let mut config = TerrainConfig {
seed: 42,
size: 65,
extent: 100.0,
height_scale: 4.0,
..TerrainConfig::default()
};
config.frequency = 2.0;
let map = Heightmap::generate(config).expect("terrain");
let mesh = map.mesh();
let mut world = RapierBackend::new();
world
.add_trimesh(TrimeshDesc {
vertices: mesh.vertices,
indices: mesh.indices,
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
})
.expect("terrain collider");
let mut bodies = Vec::new();
for (x, y, drop) in DROPS {
let center = Vec3::new(x, y, map.height_at(x, y) + drop + BOX * 0.5);
bodies.push(world.add_body(BodyDesc::dynamic(
ShapeDesc::Cuboid {
half_extents: Vec3::new(BOX * 0.5, BOX * 0.5, BOX * 0.5),
},
Kilograms::new(4.0),
center,
)));
}
let dt = SimDelta::from_hz(1_000).expect("1 kHz");
let mut before = Vec::new();
for step in 0..5_000 {
world.step(dt);
if step == 3_999 {
before = bodies
.iter()
.map(|&body| world.body_transform(body).expect("body").position)
.collect();
}
}
for (index, &body) in bodies.iter().enumerate() {
let transform = world.body_transform(body).expect("body");
let ground = map.height_at(transform.position.x, transform.position.y);
println!(
"box {index}: pos {:?} ground {ground:.3}",
transform.position
);
assert!(
transform.position.z >= ground - 0.05,
"box {index} sank through the terrain"
);
let moved = (transform.position - before[index]).length();
assert!(moved < 1e-3, "box {index} still moves: {moved}");
}
}
/// Diagnostic: `cargo test -p fabrilis-modes --test box_drops -- --ignored --nocapture`.
#[test]
#[ignore = "diagnostic timing, not a pass/fail test"]
#[allow(
clippy::disallowed_methods,
reason = "diagnostic timing uses the wall clock on purpose"
)]
fn physics_step_time_spikes() {
let config = TerrainConfig {
seed: 42,
size: 65,
extent: 100.0,
height_scale: 4.0,
frequency: 2.0,
..TerrainConfig::default()
};
let map = Heightmap::generate(config).expect("terrain");
let mesh = map.mesh();
let mut world = RapierBackend::new();
world
.add_trimesh(TrimeshDesc {
vertices: mesh.vertices,
indices: mesh.indices,
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
})
.expect("terrain collider");
for (x, y, drop) in DROPS {
let center = Vec3::new(x, y, map.height_at(x, y) + drop + BOX * 0.5);
world.add_body(BodyDesc::dynamic(
ShapeDesc::Cuboid {
half_extents: Vec3::new(BOX * 0.5, BOX * 0.5, BOX * 0.5),
},
Kilograms::new(4.0),
center,
));
}
let dt = SimDelta::from_hz(1_000).expect("1 kHz");
let mut times = Vec::with_capacity(5_000);
for _ in 0..5_000 {
let start = std::time::Instant::now();
world.step(dt);
times.push((start.elapsed().as_secs_f64() * 1_000.0, times.len()));
}
let total: f64 = times.iter().map(|&(ms, _)| ms).sum();
let mut sorted = times.clone();
sorted.sort_by(|a, b| b.0.total_cmp(&a.0));
println!("mean step {:.3} ms, total {:.1} ms", total / 5_000.0, total);
for &(ms, index) in sorted.iter().take(10) {
println!("slow step {index}: {ms:.3} ms");
}
}

View file

@ -0,0 +1,150 @@
//! M2 closed loop: a link on a revolute joint is lifted by a PD controller that reads
//! a delayed encoder instead of the ground-truth state.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
reason = "test helper: a failure should abort the test"
)]
use fabrilis_core::snapshot::hash::StateHasher;
use fabrilis_core::time::SimDelta;
use fabrilis_core::units::{Kilograms, Radians};
use fabrilis_core::vec::{Quat, Vec3};
use fabrilis_physics::backend::{BodyDesc, PhysicsBackend, ShapeDesc};
use fabrilis_physics::joints::RevoluteDesc;
use fabrilis_physics::{BodyId, JointId, RapierBackend};
use fabrilis_sensors::encoder::{Encoder, EncoderConfig};
const KP: f64 = 400.0;
const KD: f64 = 25.0;
const TARGET: f64 = 0.0;
const STEPS: usize = 3_000;
const GOLDEN: u64 = 0x014e_e966_1ea1_d0ce;
struct Rig {
world: RapierBackend,
encoder: Encoder,
link: BodyId,
joint: JointId,
dt: SimDelta,
previous_raw: f64,
continuous: f64,
}
impl Rig {
fn new(start_degrees: f64) -> Self {
let mut world = RapierBackend::new();
let base = world.add_body(BodyDesc::fixed(
ShapeDesc::Cuboid {
half_extents: Vec3::new(0.05, 0.05, 0.05),
},
Vec3::ZERO,
));
let start = Quat::from_axis_angle(Vec3::Y, Radians::from_degrees(start_degrees))
.expect("the Y axis is non-zero");
let mut link_desc = BodyDesc::dynamic(
ShapeDesc::Cuboid {
half_extents: Vec3::new(0.5, 0.05, 0.05),
},
Kilograms::new(1.0),
start.rotate(Vec3::new(0.5, 0.0, 0.0)),
);
link_desc.rotation = start;
let link = world.add_body(link_desc);
let joint = world.add_revolute(RevoluteDesc::new(
base,
link,
Vec3::Y,
Vec3::ZERO,
Vec3::new(-0.5, 0.0, 0.0),
));
let mut encoder = Encoder::new(
EncoderConfig {
resolution_bits: 16,
noise_sigma: 0.0,
bias: 0.0,
delay_steps: 1,
},
1,
)
.expect("the encoder configuration is valid");
let dt = SimDelta::from_hz(1_000).expect("1 kHz divides a second");
let first_truth = world.joint_angle(joint).expect("the joint exists");
let _primed = encoder.sample(first_truth);
let previous_raw = encoder.sample(first_truth).get();
Self {
world,
encoder,
link,
joint,
dt,
previous_raw,
continuous: wrap_to_pi(previous_raw),
}
}
fn control_step(&mut self) -> Radians {
let truth = self
.world
.joint_angle(self.joint)
.expect("the joint exists");
let raw = self.encoder.sample(truth).get();
let delta = wrap_to_pi(raw - self.previous_raw);
self.continuous += delta;
self.previous_raw = raw;
let rate = delta / self.dt.as_seconds().get();
let torque = KP * (TARGET - self.continuous) - KD * rate;
self.world.apply_torque(self.link, Vec3::Y * torque);
self.world.step(self.dt);
self.world
.joint_angle(self.joint)
.expect("the joint exists")
}
fn state(&self) -> (f64, f64) {
let transform = self
.world
.body_transform(self.link)
.expect("the link exists");
(transform.position.z, transform.rotation.y)
}
}
fn run() -> (f64, f64, u64) {
let mut rig = Rig::new(60.0);
let mut hasher = StateHasher::new();
let mut final_angle = 0.0;
let mut tail_max: f64 = 0.0;
for step in 0..STEPS {
let angle = rig.control_step();
let (z, qy) = rig.state();
hasher.write_u64(step as u64);
hasher.write_f64(angle.get());
hasher.write_f64(z);
hasher.write_f64(qy);
final_angle = angle.get();
if step > 1_000 {
tail_max = tail_max.max((angle.get() - TARGET).abs());
}
}
(final_angle, tail_max, hasher.finish())
}
#[test]
fn pd_controller_lifts_the_link_to_the_target_angle() {
let (final_angle, tail_max, _) = run();
assert!(final_angle.abs() < 0.02, "final angle = {final_angle}");
assert!(tail_max < 0.02, "tail maximum error = {tail_max}");
}
#[test]
fn the_closed_loop_is_deterministic() {
let (_, _, hash) = run();
assert_eq!(hash, GOLDEN, "new hash: {hash:#018x}");
}
fn wrap_to_pi(angle: f64) -> f64 {
let two_pi = fabrilis_core::math::TAU;
(angle + core::f64::consts::PI).rem_euclid(two_pi) - core::f64::consts::PI
}

View file

@ -0,0 +1,129 @@
//! M4a: terrain generated from a seed carries a body without falling through.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
reason = "test helper: a failure should abort the test"
)]
use fabrilis_core::snapshot::hash::StateHasher;
use fabrilis_core::time::SimDelta;
use fabrilis_core::units::Kilograms;
use fabrilis_core::vec::{Quat, Vec3};
use fabrilis_physics::RapierBackend;
use fabrilis_physics::backend::{BodyDesc, PhysicsBackend, ShapeDesc, TrimeshDesc};
use fabrilis_worldgen::terrain::{Heightmap, TerrainConfig};
const STEPS: usize = 3_000;
fn terrain(seed: u64, height_scale: f64, size: usize) -> (RapierBackend, Heightmap) {
let config = TerrainConfig {
seed,
size,
extent: 100.0,
height_scale,
frequency: 2.0,
octaves: 4,
..TerrainConfig::default()
};
let map = Heightmap::generate(config).expect("the terrain configuration is valid");
let mesh = map.mesh();
let mut world = RapierBackend::new();
let terrain = world
.add_trimesh(TrimeshDesc {
vertices: mesh.vertices,
indices: mesh.indices,
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
})
.expect("the terrain mesh is valid");
assert!(world.body_transform(terrain).is_some());
(world, map)
}
#[test]
fn a_ball_rests_on_flat_terrain() {
let (mut world, _map) = terrain(1, 0.0, 33);
let radius = 0.25;
let ball = world.add_body(BodyDesc::dynamic(
ShapeDesc::Ball { radius },
Kilograms::new(1.0),
Vec3::new(0.0, 0.0, 3.0),
));
let dt = SimDelta::from_hz(1_000).expect("1 kHz divides a second");
for _ in 0..STEPS {
world.step(dt);
}
let z = world
.body_transform(ball)
.expect("the ball exists")
.position
.z;
assert!((z - radius).abs() < 0.02, "ball z = {z}");
}
#[test]
fn a_box_stays_above_a_seeded_relief() {
let (world, map) = terrain(42, 4.0, 65);
let mut world = world;
let start = map.height_at(0.0, 0.0) + 3.0;
let body = world.add_body(BodyDesc::dynamic(
ShapeDesc::Cuboid {
half_extents: Vec3::new(0.25, 0.25, 0.1),
},
Kilograms::new(5.0),
Vec3::new(0.0, 0.0, start),
));
let dt = SimDelta::from_hz(1_000).expect("1 kHz divides a second");
for _ in 0..STEPS {
world.step(dt);
}
let position = world.body_transform(body).expect("the box exists").position;
assert!(position.is_finite());
let ground = map.height_at(position.x, position.y);
assert!(
position.z >= ground - 0.05,
"box at {position:?} below terrain {ground}"
);
}
#[test]
fn the_terrain_scene_is_deterministic() {
let (first, second) = (run_scene(), run_scene());
assert_eq!(first.0.x.to_bits(), second.0.x.to_bits());
assert_eq!(first.0.y.to_bits(), second.0.y.to_bits());
assert_eq!(first.0.z.to_bits(), second.0.z.to_bits());
assert_eq!(first.1, second.1);
}
#[test]
fn the_terrain_trajectory_matches_golden() {
let (_, hash) = run_scene();
assert_eq!(hash, GOLDEN, "new hash: {hash:#018x}");
}
const GOLDEN: u64 = 0xbb09_e470_43d3_1f2e;
fn run_scene() -> (Vec3, u64) {
let (mut world, map) = terrain(42, 4.0, 65);
let start = map.height_at(0.0, 0.0) + 3.0;
let body = world.add_body(BodyDesc::dynamic(
ShapeDesc::Cuboid {
half_extents: Vec3::new(0.25, 0.25, 0.1),
},
Kilograms::new(5.0),
Vec3::new(0.0, 0.0, start),
));
let dt = SimDelta::from_hz(1_000).expect("1 kHz divides a second");
let mut hasher = StateHasher::new();
let mut last = Vec3::ZERO;
for step in 0..1_000 {
world.step(dt);
last = world.body_transform(body).expect("the box exists").position;
hasher.write_u64(step as u64);
hasher.write_f64(last.x);
hasher.write_f64(last.y);
hasher.write_f64(last.z);
}
(last, hasher.finish())
}

View file

@ -11,6 +11,7 @@ workspace = true
[dependencies]
fabrilis-core = { path = "../core" }
rapier3d-f64 = { version = "0.36", features = ["enhanced-determinism"] }
[build-dependencies]
fabrilis-limits = { path = "../../tools/limits" }

View file

@ -1 +1,149 @@
//! fabrilis-physics :: backend - stub (see docs/ARCHITECTURE.md)
//! The engine-agnostic physics contract.
//!
//! Subsystems above physics talk to this trait, never to Rapier directly. All
//! values cross the boundary in SI units and the project's Z-up world frame
//! (docs/COORDINATES.md).
use fabrilis_core::time::SimDelta;
use fabrilis_core::units::{Kilograms, Radians};
use fabrilis_core::vec::{Quat, Transform, Vec3};
use crate::joints::{JointId, RevoluteDesc};
/// A handle to a body owned by a [`PhysicsBackend`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BodyId(pub(crate) u32);
impl BodyId {
/// The dense index behind the handle, for snapshots and diagnostics.
#[must_use]
pub const fn index(self) -> u32 {
self.0
}
}
/// Whether a body is immovable or integrated by the solver.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BodyKind {
/// Static geometry: infinite mass, never moves.
Fixed,
/// Simulated body: moves under gravity, contacts and joint reactions.
Dynamic,
}
/// The collision shape of a body.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ShapeDesc {
/// A box aligned with the body frame, given by its half extents.
Cuboid {
/// Half the box size along each local axis, metres.
half_extents: Vec3,
},
/// A sphere centred on the body frame.
Ball {
/// Radius, metres.
radius: f64,
},
}
/// A static triangle mesh, used for terrain.
///
/// The mesh owns its vertex buffers, so unlike [`ShapeDesc`] it is not `Copy`;
/// it is passed to [`PhysicsBackend::add_trimesh`] by value. Dynamic trimesh
/// bodies are out of scope for now: the created body is always fixed.
#[derive(Debug, Clone, PartialEq)]
pub struct TrimeshDesc {
/// Mesh vertices in the local frame of the body, metres.
pub vertices: Vec<Vec3>,
/// Zero-based triangles indexing `vertices`, one triangle per entry.
pub indices: Vec<[u32; 3]>,
/// World position of the local frame, metres.
pub position: Vec3,
/// World orientation of the local frame.
pub rotation: Quat,
}
/// Everything needed to create a body.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BodyDesc {
/// Fixed or dynamic.
pub kind: BodyKind,
/// Total mass, kilograms; ignored for fixed bodies.
pub mass: Kilograms,
/// Collision shape.
pub shape: ShapeDesc,
/// Initial world position, metres.
pub position: Vec3,
/// Initial orientation.
pub rotation: Quat,
}
impl BodyDesc {
/// A dynamic body at rest with no rotation.
#[must_use]
pub fn dynamic(shape: ShapeDesc, mass: Kilograms, position: Vec3) -> Self {
Self {
kind: BodyKind::Dynamic,
mass,
shape,
position,
rotation: Quat::IDENTITY,
}
}
/// A fixed body at rest with no rotation.
#[must_use]
pub fn fixed(shape: ShapeDesc, position: Vec3) -> Self {
Self {
kind: BodyKind::Fixed,
mass: Kilograms::ZERO,
shape,
position,
rotation: Quat::IDENTITY,
}
}
}
/// The simulation operations available to the rest of the engine.
pub trait PhysicsBackend {
/// Adds a body and returns its handle.
fn add_body(&mut self, desc: BodyDesc) -> BodyId;
/// Adds a static triangle mesh (terrain) and returns its handle.
///
/// The mesh is fixed terrain: it never moves and is not integrated by the
/// solver. `vertices` are in the local frame; `position` and `rotation`
/// place that frame in the Z-up world. Indices are zero-based triangles;
/// winding follows the right-hand rule (counter-clockwise seen from the
/// front), while terrain contacts themselves are two-sided.
///
/// Returns `None` for an empty mesh, an empty index list, out-of-range
/// indices, non-finite vertices or placement, or a degenerate/zero-area
/// mesh that Rapier rejects. Invalid input never panics and leaves the
/// backend usable. Dynamic trimesh bodies are out of scope for now.
fn add_trimesh(&mut self, desc: TrimeshDesc) -> Option<BodyId>;
/// Adds a revolute joint between two existing bodies and returns its handle.
fn add_revolute(&mut self, desc: RevoluteDesc) -> JointId;
/// Drives a joint towards `target` with a spring-like position motor.
///
/// `stiffness` and `damping` use the backend's motor units; unknown joints are
/// ignored. See [`RapierBackend`](crate::rapier::RapierBackend) for the model.
fn set_motor_position(&mut self, joint: JointId, target: Radians, stiffness: f64, damping: f64);
/// Sets the world-frame torque for the next step, N·m; replaces the previous one.
///
/// A controller calls this every step; unknown bodies are ignored.
fn apply_torque(&mut self, body: BodyId, torque: Vec3);
/// Advances the simulation by `dt`.
fn step(&mut self, dt: SimDelta);
/// The current world transform of a body, or `None` for an unknown handle.
fn body_transform(&self, id: BodyId) -> Option<Transform>;
/// The current angle of a revolute joint in `[-π, π]`, or `None` for an
/// unknown handle.
fn joint_angle(&self, id: JointId) -> Option<Radians>;
}

View file

@ -1 +1,49 @@
//! fabrilis-physics :: joints - stub (see docs/ARCHITECTURE.md)
//! Joint descriptions shared by every backend.
use fabrilis_core::vec::Vec3;
use crate::backend::BodyId;
/// A handle to a joint owned by a [`PhysicsBackend`](crate::backend::PhysicsBackend).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct JointId(pub(crate) u32);
impl JointId {
/// The dense index behind the handle, for snapshots and diagnostics.
#[must_use]
pub const fn index(self) -> u32 {
self.0
}
}
/// A hinge that allows only relative rotation around `axis`.
///
/// `anchor_a` and `anchor_b` are the same physical point expressed in each
/// body's local frame, so a correct joint starts with the anchors coincident.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RevoluteDesc {
/// The body the joint frame is measured from.
pub body_a: BodyId,
/// The body that rotates relative to `body_a`.
pub body_b: BodyId,
/// Hinge axis in the local frames of both bodies; normalized by the backend.
pub axis: Vec3,
/// Hinge point in the local frame of `body_a`, metres.
pub anchor_a: Vec3,
/// Hinge point in the local frame of `body_b`, metres.
pub anchor_b: Vec3,
}
impl RevoluteDesc {
/// A hinge with the given bodies, axis and local anchors.
#[must_use]
pub fn new(body_a: BodyId, body_b: BodyId, axis: Vec3, anchor_a: Vec3, anchor_b: Vec3) -> Self {
Self {
body_a,
body_b,
axis,
anchor_a,
anchor_b,
}
}
}

View file

@ -3,3 +3,7 @@ pub mod backend;
pub mod contact;
pub mod joints;
pub mod rapier;
pub use backend::{BodyDesc, BodyId, BodyKind, PhysicsBackend, ShapeDesc, TrimeshDesc};
pub use joints::{JointId, RevoluteDesc};
pub use rapier::RapierBackend;

View file

@ -1 +1,268 @@
//! fabrilis-physics :: rapier - stub (see docs/ARCHITECTURE.md)
//! Rapier adapter: translates the project's SI/Z-up descriptions into Rapier
//! handles and copies state back. See docs/DETERMINISM.md for the Rapier
//! determinism caveats.
use fabrilis_core::time::SimDelta;
use fabrilis_core::units::{Kilograms, Radians};
use fabrilis_core::vec::{Quat, Transform, Vec3};
use rapier3d_f64::dynamics::{
CCDSolver, ImpulseJointHandle, ImpulseJointSet, IntegrationParameters, IslandManager,
JointAxis, MultibodyJointSet, RevoluteJoint, RevoluteJointBuilder, RigidBodyBuilder,
RigidBodyHandle, RigidBodySet, SoftBodySet,
};
use rapier3d_f64::geometry::{ColliderBuilder, ColliderSet, DefaultBroadPhase, NarrowPhase};
use rapier3d_f64::math::{Pose, Rotation, Vector};
use rapier3d_f64::pipeline::PhysicsPipeline;
use crate::backend::{BodyDesc, BodyId, BodyKind, PhysicsBackend, ShapeDesc, TrimeshDesc};
use crate::joints::{JointId, RevoluteDesc};
/// Standard gravity in the project's Z-up world frame, m/s².
pub const EARTH_GRAVITY: Vec3 = Vec3::new(0.0, 0.0, -9.81);
/// A Rapier world behind the [`PhysicsBackend`] trait.
pub struct RapierBackend {
gravity: Vector,
integration: IntegrationParameters,
pipeline: PhysicsPipeline,
islands: IslandManager,
broad_phase: DefaultBroadPhase,
narrow_phase: NarrowPhase,
bodies: RigidBodySet,
colliders: ColliderSet,
joints: ImpulseJointSet,
multibody_joints: MultibodyJointSet,
soft_bodies: SoftBodySet,
ccd_solver: CCDSolver,
body_handles: Vec<RigidBodyHandle>,
joint_handles: Vec<Option<ImpulseJointHandle>>,
}
impl RapierBackend {
/// A world with standard gravity, Z down 9.81 m/s².
#[must_use]
pub fn new() -> Self {
Self::with_gravity(EARTH_GRAVITY)
}
/// A world with an explicit gravity vector, m/s².
#[must_use]
pub fn with_gravity(gravity: Vec3) -> Self {
Self {
gravity: vector(gravity),
integration: IntegrationParameters::default(),
pipeline: PhysicsPipeline::new(),
islands: IslandManager::new(),
broad_phase: DefaultBroadPhase::default(),
narrow_phase: NarrowPhase::new(),
bodies: RigidBodySet::new(),
colliders: ColliderSet::new(),
joints: ImpulseJointSet::new(),
multibody_joints: MultibodyJointSet::new(),
soft_bodies: SoftBodySet::new(),
ccd_solver: CCDSolver::new(),
body_handles: Vec::new(),
joint_handles: Vec::new(),
}
}
fn body_handle(&self, id: BodyId) -> Option<RigidBodyHandle> {
self.body_handles.get(id.0 as usize).copied()
}
fn joint_handle(&self, id: JointId) -> Option<ImpulseJointHandle> {
self.joint_handles.get(id.0 as usize).copied().flatten()
}
}
impl Default for RapierBackend {
fn default() -> Self {
Self::new()
}
}
impl PhysicsBackend for RapierBackend {
fn add_body(&mut self, desc: BodyDesc) -> BodyId {
let builder = match desc.kind {
BodyKind::Fixed => RigidBodyBuilder::fixed(),
BodyKind::Dynamic => RigidBodyBuilder::dynamic(),
};
let pose = Pose::from_parts(vector(desc.position), rotation(desc.rotation));
let handle = self.bodies.insert(builder.pose(pose).build());
let collider = collider(desc.shape, desc.mass);
self.colliders
.insert_with_parent(collider, handle, &mut self.bodies);
let id = BodyId(self.body_handles.len() as u32);
self.body_handles.push(handle);
id
}
fn add_trimesh(&mut self, desc: TrimeshDesc) -> Option<BodyId> {
// Frame placement first: a non-finite pose must be rejected before any
// Rapier data exists. Rapier normalizes the quaternion itself; a zero
// quaternion falls back to the identity.
if !desc.position.is_finite() || !quat_is_finite(desc.rotation) {
return None;
}
let (vertices, indices) = trimesh_buffers(desc.vertices, desc.indices)?;
// Rapier rejects an empty index list; other degenerate meshes are
// reported through the error result instead of panicking.
let collider = ColliderBuilder::trimesh(vertices, indices).ok()?;
let pose = Pose::from_parts(vector(desc.position), rotation(desc.rotation));
let handle = self
.bodies
.insert(RigidBodyBuilder::fixed().pose(pose).build());
self.colliders
.insert_with_parent(collider, handle, &mut self.bodies);
let id = BodyId(self.body_handles.len() as u32);
self.body_handles.push(handle);
Some(id)
}
fn add_revolute(&mut self, desc: RevoluteDesc) -> JointId {
let id = JointId(self.joint_handles.len() as u32);
let Some(body_a) = self.body_handle(desc.body_a) else {
self.joint_handles.push(None);
return id;
};
let Some(body_b) = self.body_handle(desc.body_b) else {
self.joint_handles.push(None);
return id;
};
let axis = desc.axis.normalized().unwrap_or(Vec3::Z);
// Linked bodies often overlap around a hinge, so contacts between the pair
// are disabled; both still collide with the rest of the world.
let joint = RevoluteJointBuilder::new(vector(axis))
.local_anchor1(vector(desc.anchor_a))
.local_anchor2(vector(desc.anchor_b))
.contacts_enabled(false);
let handle = self.joints.insert(body_a, body_b, joint, true);
self.joint_handles.push(Some(handle));
id
}
fn set_motor_position(
&mut self,
joint: JointId,
target: Radians,
stiffness: f64,
damping: f64,
) {
let Some(handle) = self.joint_handle(joint) else {
return;
};
let Some(entry) = self.joints.get_mut(handle, true) else {
return;
};
entry
.data
.set_motor_position(JointAxis::AngX, target.get(), stiffness, damping);
}
fn apply_torque(&mut self, body: BodyId, torque: Vec3) {
let Some(handle) = self.body_handle(body) else {
return;
};
if let Some(entry) = self.bodies.get_mut(handle) {
// Rapier keeps user torques until they are cleared, so this sets the torque
// for the coming step instead of accumulating it every step.
entry.reset_torques(true);
entry.add_torque(vector(torque), true);
}
}
fn step(&mut self, dt: SimDelta) {
let seconds = dt.as_seconds().get();
if seconds <= 0.0 {
return;
}
self.integration.dt = seconds;
self.pipeline.step(
self.gravity,
&self.integration,
&mut self.islands,
&mut self.broad_phase,
&mut self.narrow_phase,
&mut self.bodies,
&mut self.colliders,
&mut self.joints,
&mut self.multibody_joints,
&mut self.soft_bodies,
&mut self.ccd_solver,
&(),
&(),
);
}
fn body_transform(&self, id: BodyId) -> Option<Transform> {
let body = self.bodies.get(self.body_handle(id)?)?;
let translation = body.translation();
let rotation = body.rotation();
Some(Transform::new(
Vec3::new(translation.x, translation.y, translation.z),
Quat::new(rotation.w, rotation.x, rotation.y, rotation.z),
))
}
fn joint_angle(&self, id: JointId) -> Option<Radians> {
let joint = self.joints.get(self.joint_handle(id)?)?;
let body_a = self.bodies.get(joint.body1())?;
let body_b = self.bodies.get(joint.body2())?;
let revolute = RevoluteJoint { data: joint.data };
Some(Radians::new(
revolute.angle(body_a.rotation(), body_b.rotation()),
))
}
}
fn vector(v: Vec3) -> Vector {
Vector::new(v.x, v.y, v.z)
}
fn rotation(q: Quat) -> Rotation {
let unit = q.normalize().unwrap_or(Quat::IDENTITY);
Rotation::from_xyzw(unit.x, unit.y, unit.z, unit.w)
}
fn collider(shape: ShapeDesc, mass: Kilograms) -> ColliderBuilder {
let builder = match shape {
ShapeDesc::Cuboid { half_extents } => {
ColliderBuilder::cuboid(half_extents.x, half_extents.y, half_extents.z)
}
ShapeDesc::Ball { radius } => ColliderBuilder::ball(radius),
};
builder.mass(mass.get())
}
fn quat_is_finite(q: Quat) -> bool {
q.w.is_finite() && q.x.is_finite() && q.y.is_finite() && q.z.is_finite()
}
/// Validates a trimesh and converts it to Rapier's point type.
///
/// Rapier does not check index bounds while building its BVH and would panic or
/// read garbage on a bad index, so every index is validated here first. A mesh
/// needs at least one triangle, hence at least three vertices.
fn trimesh_buffers(
vertices: Vec<Vec3>,
indices: Vec<[u32; 3]>,
) -> Option<(Vec<Vector>, Vec<[u32; 3]>)> {
if indices.is_empty() || vertices.len() < 3 {
return None;
}
let vertex_count = u32::try_from(vertices.len()).ok()?;
if indices.iter().flatten().any(|&index| index >= vertex_count) {
return None;
}
let mut points = Vec::with_capacity(vertices.len());
for vertex in vertices {
if !vertex.is_finite() {
return None;
}
points.push(vector(vertex));
}
Some((points, indices))
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,285 @@
use super::*;
use crate::backend::{BodyDesc, BodyId, PhysicsBackend, ShapeDesc, TrimeshDesc};
use crate::joints::{JointId, RevoluteDesc};
use fabrilis_core::time::SimDelta;
use fabrilis_core::units::{Kilograms, Radians};
use fabrilis_core::vec::{Quat, Vec3};
fn step_at(hz: u64) -> SimDelta {
SimDelta::from_hz(hz).expect("1 kHz divides a second evenly")
}
fn build_motor_world() -> (RapierBackend, BodyId, JointId) {
let mut world = RapierBackend::new();
let base = world.add_body(BodyDesc::fixed(
ShapeDesc::Cuboid {
half_extents: Vec3::new(0.05, 0.05, 0.05),
},
Vec3::ZERO,
));
let link = world.add_body(BodyDesc::dynamic(
ShapeDesc::Cuboid {
half_extents: Vec3::new(0.5, 0.05, 0.05),
},
Kilograms::new(1.0),
Vec3::new(0.5, 0.0, 0.0),
));
let joint = world.add_revolute(RevoluteDesc::new(
base,
link,
Vec3::Z,
Vec3::ZERO,
Vec3::new(-0.5, 0.0, 0.0),
));
world.set_motor_position(joint, Radians::new(1.0), 100.0, 20.0);
(world, link, joint)
}
#[test]
fn free_body_falls_under_gravity() {
let mut world = RapierBackend::new();
let body = world.add_body(BodyDesc::dynamic(
ShapeDesc::Ball { radius: 0.2 },
Kilograms::new(1.0),
Vec3::new(0.0, 0.0, 10.0),
));
let dt = step_at(1_000);
let steps = 100;
for _ in 0..steps {
world.step(dt);
}
let z = world
.body_transform(body)
.expect("the body exists")
.position
.z;
let t = (steps as f64) * dt.as_seconds().get();
let expected = 10.0 - 0.5 * EARTH_GRAVITY.z.abs() * t * t;
assert!(z < 10.0);
assert!(
(z - expected).abs() < 1e-3,
"z = {z}, expected = {expected}"
);
}
#[test]
fn motor_reaches_target_angle() {
let (mut world, _link, joint) = build_motor_world();
let dt = step_at(1_000);
for _ in 0..2_000 {
world.step(dt);
}
let angle = world.joint_angle(joint).expect("the joint exists");
assert!((angle.get() - 1.0).abs() <= 0.02, "angle = {}", angle.get());
for _ in 0..200 {
world.step(dt);
let settled = world.joint_angle(joint).expect("the joint exists");
assert!(
(settled.get() - 1.0).abs() <= 0.02,
"settled angle = {}",
settled.get()
);
}
}
#[test]
fn identical_worlds_match_bitwise() {
let (mut first, first_body, first_joint) = build_motor_world();
let (mut second, second_body, second_joint) = build_motor_world();
let dt = step_at(1_000);
for _ in 0..500 {
first.step(dt);
second.step(dt);
}
let a = first.body_transform(first_body).expect("the body exists");
let b = second.body_transform(second_body).expect("the body exists");
assert_eq!(a.position.x.to_bits(), b.position.x.to_bits());
assert_eq!(a.position.y.to_bits(), b.position.y.to_bits());
assert_eq!(a.position.z.to_bits(), b.position.z.to_bits());
assert_eq!(a.rotation.w.to_bits(), b.rotation.w.to_bits());
assert_eq!(a.rotation.x.to_bits(), b.rotation.x.to_bits());
assert_eq!(a.rotation.y.to_bits(), b.rotation.y.to_bits());
assert_eq!(a.rotation.z.to_bits(), b.rotation.z.to_bits());
let angle_a = first.joint_angle(first_joint).expect("the joint exists");
let angle_b = second.joint_angle(second_joint).expect("the joint exists");
assert_eq!(angle_a.get().to_bits(), angle_b.get().to_bits());
}
#[test]
fn unknown_ids_return_none() {
let mut world = RapierBackend::new();
assert!(world.body_transform(BodyId(u32::MAX)).is_none());
assert!(world.joint_angle(JointId(u32::MAX)).is_none());
world.set_motor_position(JointId(7), Radians::new(1.0), 1.0, 1.0);
assert!(world.body_transform(BodyId(7)).is_none());
assert!(world.joint_angle(JointId(7)).is_none());
}
fn flat_terrain() -> TrimeshDesc {
TrimeshDesc {
vertices: vec![
Vec3::new(-5.0, -5.0, 0.0),
Vec3::new(5.0, -5.0, 0.0),
Vec3::new(5.0, 5.0, 0.0),
Vec3::new(-5.0, 5.0, 0.0),
],
indices: vec![[0, 1, 2], [0, 2, 3]],
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
}
}
fn dropped_ball(world: &mut RapierBackend, radius: f64, position: Vec3) -> BodyId {
world.add_body(BodyDesc::dynamic(
ShapeDesc::Ball { radius },
Kilograms::new(1.0),
position,
))
}
#[test]
fn ball_settles_on_flat_trimesh() {
let mut world = RapierBackend::new();
let terrain = world
.add_trimesh(flat_terrain())
.expect("flat terrain is valid");
assert!(world.body_transform(terrain).is_some());
let radius = 0.25;
let ball = dropped_ball(&mut world, radius, Vec3::new(0.75, -0.5, 5.0));
let dt = step_at(1_000);
for _ in 0..2_000 {
world.step(dt);
}
let resting = world
.body_transform(ball)
.expect("the ball exists")
.position;
assert!(
(resting.z - radius).abs() <= 0.05,
"resting z = {}, radius = {radius}",
resting.z
);
for _ in 0..500 {
world.step(dt);
let z = world
.body_transform(ball)
.expect("the ball exists")
.position
.z;
assert!((z - radius).abs() <= 0.05, "drifted z = {z}");
}
}
#[test]
fn trimesh_worlds_match_bitwise() {
let mut first = RapierBackend::new();
let mut second = RapierBackend::new();
assert!(first.add_trimesh(flat_terrain()).is_some());
assert!(second.add_trimesh(flat_terrain()).is_some());
let first_ball = dropped_ball(&mut first, 0.25, Vec3::new(0.75, -0.5, 5.0));
let second_ball = dropped_ball(&mut second, 0.25, Vec3::new(0.75, -0.5, 5.0));
let dt = step_at(1_000);
for _ in 0..500 {
first.step(dt);
second.step(dt);
}
let a = first.body_transform(first_ball).expect("the ball exists");
let b = second.body_transform(second_ball).expect("the ball exists");
assert_eq!(a.position.x.to_bits(), b.position.x.to_bits());
assert_eq!(a.position.y.to_bits(), b.position.y.to_bits());
assert_eq!(a.position.z.to_bits(), b.position.z.to_bits());
}
#[test]
fn invalid_trimesh_is_rejected_and_backend_stays_usable() {
let mut world = RapierBackend::new();
let empty_vertices = TrimeshDesc {
vertices: Vec::new(),
indices: vec![[0, 1, 2]],
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
};
let empty_indices = TrimeshDesc {
vertices: flat_terrain().vertices,
indices: Vec::new(),
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
};
let out_of_range = TrimeshDesc {
vertices: flat_terrain().vertices,
indices: vec![[0, 1, 4]],
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
};
let mut non_finite_vertices = flat_terrain().vertices;
non_finite_vertices[0] = Vec3::new(f64::NAN, 0.0, 0.0);
let non_finite = TrimeshDesc {
vertices: non_finite_vertices,
indices: vec![[0, 1, 2]],
position: Vec3::ZERO,
rotation: Quat::IDENTITY,
};
for desc in [empty_vertices, empty_indices, out_of_range, non_finite] {
assert!(world.add_trimesh(desc).is_none());
}
let ball = dropped_ball(&mut world, 0.2, Vec3::new(0.0, 0.0, 1.0));
let dt = step_at(1_000);
world.step(dt);
let z = world
.body_transform(ball)
.expect("the ball exists")
.position
.z;
assert!(z < 1.0, "the ball did not fall, z = {z}");
}
/// Height of the plane through the origin with `normal` at `x`, `y`.
fn plane_z(normal: Vec3, x: f64, y: f64) -> f64 {
-(normal.x * x + normal.y * y) / normal.z
}
#[test]
fn ball_stays_above_inclined_trimesh() {
let rotation =
Quat::from_axis_angle(Vec3::Y, Radians::new(0.3)).expect("the Y axis is nonzero");
let terrain = TrimeshDesc {
vertices: vec![
Vec3::new(-50.0, -50.0, 0.0),
Vec3::new(50.0, -50.0, 0.0),
Vec3::new(50.0, 50.0, 0.0),
Vec3::new(-50.0, 50.0, 0.0),
],
indices: vec![[0, 1, 2], [0, 2, 3]],
position: Vec3::ZERO,
rotation,
};
let normal = rotation.rotate(Vec3::Z);
let mut world = RapierBackend::new();
assert!(world.add_trimesh(terrain).is_some());
let radius = 0.25;
let ball = dropped_ball(&mut world, radius, Vec3::new(0.0, 0.0, 3.0));
let dt = step_at(1_000);
for step in 0..2_000 {
world.step(dt);
let position = world
.body_transform(ball)
.expect("the ball exists")
.position;
let surface = plane_z(normal, position.x, position.y);
assert!(
position.z > surface,
"step {step}: z = {} under surface {surface}",
position.z
);
}
let position = world
.body_transform(ball)
.expect("the ball exists")
.position;
let surface = plane_z(normal, position.x, position.y);
assert!(
(position.z - surface - radius / normal.z).abs() <= 0.1,
"ball left the slope: z = {}, surface = {surface}",
position.z
);
}

View file

@ -11,6 +11,9 @@ workspace = true
[dependencies]
fabrilis-core = { path = "../core" }
bytemuck = { version = "1", features = ["derive"] }
fontdue = "0.9"
wgpu = "30"
[build-dependencies]
fabrilis-limits = { path = "../../tools/limits" }

128
crates/render/src/camera.rs Normal file
View file

@ -0,0 +1,128 @@
//! Renderer-local perspective camera.
//!
//! The camera works in the world frame: Z is up and the projection targets the
//! WebGPU depth range `0..=1`. All arithmetic is `f32` because the camera only
//! feeds the renderer and never the authoritative simulation.
use fabrilis_core::math;
type Mat4 = [[f32; 4]; 4];
type Vec3 = [f32; 3];
/// A right-handed perspective camera with an explicit look-at pose.
#[derive(Debug, Clone, Copy)]
pub struct Camera {
eye: Vec3,
target: Vec3,
up: Vec3,
fov_y: f32,
aspect: f32,
near: f32,
far: f32,
}
impl Camera {
/// A camera at `eye` looking at `target`, with sensible projection defaults.
#[must_use]
pub fn look_at(eye: Vec3, target: Vec3, up: Vec3) -> Self {
Self {
eye,
target,
up,
fov_y: 0.9,
aspect: 1.0,
near: 0.1,
far: 500.0,
}
}
/// Replaces the projection parameters, clamping them to usable values.
#[must_use]
pub fn with_projection(mut self, fov_y: f32, aspect: f32, near: f32, far: f32) -> Self {
self.fov_y = fov_y.clamp(0.01, 3.0);
self.aspect = aspect.max(0.0001);
self.near = near.max(0.0001);
self.far = far.max(self.near + 0.0001);
self
}
/// Updates the aspect ratio after a surface resize.
pub fn set_aspect(&mut self, aspect: f32) {
self.aspect = aspect.max(0.0001);
}
/// The eye position in world space.
#[must_use]
pub fn eye(&self) -> Vec3 {
self.eye
}
/// The combined view-projection matrix in column-major order.
#[must_use]
pub fn view_projection(&self) -> Mat4 {
multiply(&self.projection(), &self.view())
}
fn view(&self) -> Mat4 {
let forward = normalize(sub(self.target, self.eye), [0.0, 1.0, 0.0]);
let side = normalize(cross(forward, self.up), [1.0, 0.0, 0.0]);
let up = cross(side, forward);
[
[side[0], up[0], -forward[0], 0.0],
[side[1], up[1], -forward[1], 0.0],
[side[2], up[2], -forward[2], 0.0],
[
-dot(side, self.eye),
-dot(up, self.eye),
dot(forward, self.eye),
1.0,
],
]
}
fn projection(&self) -> Mat4 {
let scale = 1.0 / math::tan(f64::from(self.fov_y) * 0.5) as f32;
let depth = self.far / (self.near - self.far);
[
[scale / self.aspect, 0.0, 0.0, 0.0],
[0.0, scale, 0.0, 0.0],
[0.0, 0.0, depth, -1.0],
[0.0, 0.0, depth * self.near, 0.0],
]
}
}
fn sub(left: Vec3, right: Vec3) -> Vec3 {
[left[0] - right[0], left[1] - right[1], left[2] - right[2]]
}
fn dot(left: Vec3, right: Vec3) -> f32 {
left[0] * right[0] + left[1] * right[1] + left[2] * right[2]
}
fn cross(left: Vec3, right: Vec3) -> Vec3 {
[
left[1] * right[2] - left[2] * right[1],
left[2] * right[0] - left[0] * right[2],
left[0] * right[1] - left[1] * right[0],
]
}
fn normalize(vector: Vec3, fallback: Vec3) -> Vec3 {
let length = dot(vector, vector).sqrt();
if length > 1.0e-6 {
[vector[0] / length, vector[1] / length, vector[2] / length]
} else {
fallback
}
}
fn multiply(left: &Mat4, right: &Mat4) -> Mat4 {
let mut product = [[0.0; 4]; 4];
for (column, output) in product.iter_mut().enumerate() {
for (row, value) in output.iter_mut().enumerate() {
*value = (0..4).map(|k| left[k][row] * right[column][k]).sum();
}
}
product
}

View file

@ -1 +0,0 @@
//! fabrilis-render :: ctx - stub (see docs/ARCHITECTURE.md)

View file

@ -0,0 +1,37 @@
//! Renderer errors.
use core::fmt;
/// Why a renderer resource could not be created or used.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RenderError {
/// No suitable GPU adapter was found.
Adapter(String),
/// The logical device could not be created.
Device(String),
/// A window surface operation failed.
Surface(String),
/// A texture could not be allocated or read back.
Texture(String),
/// A buffer could not be allocated or mapped.
Buffer(String),
/// The requested pixel format is not supported by the readback path.
UnsupportedFormat(String),
}
impl fmt::Display for RenderError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Adapter(detail) => write!(formatter, "GPU adapter unavailable: {detail}"),
Self::Device(detail) => write!(formatter, "GPU device unavailable: {detail}"),
Self::Surface(detail) => write!(formatter, "surface failure: {detail}"),
Self::Texture(detail) => write!(formatter, "texture failure: {detail}"),
Self::Buffer(detail) => write!(formatter, "buffer failure: {detail}"),
Self::UnsupportedFormat(detail) => {
write!(formatter, "unsupported pixel format: {detail}")
}
}
}
}
impl std::error::Error for RenderError {}

View file

@ -0,0 +1,100 @@
//! Headless GPU device creation.
//!
//! The window path lives in the application: it owns the surface and passes the
//! device and queue to [`crate::Renderer`].
use std::future::Future;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
use crate::RenderError;
/// A logical device and its queue, created without a window surface.
#[derive(Debug, Clone)]
pub struct Gpu {
device: wgpu::Device,
queue: wgpu::Queue,
}
impl Gpu {
/// Requests a high-performance adapter, retrying with a fallback adapter.
pub fn headless() -> Result<Self, RenderError> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = request_adapter(&instance)?;
let (device, queue) = block_on(adapter.request_device(&device_descriptor()))
.map_err(|error| RenderError::Device(error.to_string()))?;
Ok(Self { device, queue })
}
/// The device that owns renderer resources.
#[must_use]
pub fn device(&self) -> &wgpu::Device {
&self.device
}
/// The queue used to upload data and submit commands.
#[must_use]
pub fn queue(&self) -> &wgpu::Queue {
&self.queue
}
}
/// Device limits and features used by both the app and headless tests.
#[must_use]
pub fn device_descriptor() -> wgpu::DeviceDescriptor<'static> {
wgpu::DeviceDescriptor {
label: Some("fabrilis device"),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::default(),
experimental_features: wgpu::ExperimentalFeatures::default(),
memory_hints: wgpu::MemoryHints::default(),
trace: wgpu::Trace::Off,
}
}
fn request_adapter(instance: &wgpu::Instance) -> Result<wgpu::Adapter, RenderError> {
let options = wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: false,
..Default::default()
};
match block_on(instance.request_adapter(&options)) {
Ok(adapter) => Ok(adapter),
Err(primary) => {
let fallback = wgpu::RequestAdapterOptions {
force_fallback_adapter: true,
..options
};
block_on(instance.request_adapter(&fallback)).map_err(|secondary| {
RenderError::Adapter(format!("{primary}; fallback adapter: {secondary}"))
})
}
}
}
struct ThreadWake(Thread);
impl Wake for ThreadWake {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
fn wake_by_ref(self: &Arc<Self>) {
self.0.unpark();
}
}
/// Blocks on a future without pulling in an async runtime.
fn block_on<F: Future>(future: F) -> F::Output {
let waker = Waker::from(Arc::new(ThreadWake(thread::current())));
let mut context = Context::from_waker(&waker);
let mut future = std::pin::pin!(future);
loop {
match future.as_mut().poll(&mut context) {
Poll::Ready(value) => return value,
Poll::Pending => thread::park(),
}
}
}

View file

@ -1 +0,0 @@
//! fabrilis-render :: instancing - stub (see docs/ARCHITECTURE.md)

View file

@ -1,5 +1,22 @@
//! Custom wgpu renderer: clipmap terrain, instancing, compute culling, view modes (stress, temperature)
pub mod ctx;
pub mod instancing;
pub mod terrain;
pub mod views;
//! Custom wgpu renderer: depth-tested terrain meshes, instanced boxes, one
//! directional light.
//!
//! The renderer is not part of the authoritative simulation: it may use `f32`
//! and never reads wall-clock time. Headless use builds a [`Gpu`] and renders
//! into an offscreen texture; the app owns its surface and calls
//! [`Renderer::draw_to`].
pub mod camera;
pub mod error;
pub mod gpu;
pub mod overlay;
pub mod renderer;
pub mod scene;
pub use camera::Camera;
pub use error::RenderError;
pub use gpu::Gpu;
pub use overlay::{Overlay, OverlayLine, OverlayRect, OverlayText};
pub use renderer::Renderer;
pub use scene::{Instance, MeshData, Scene};
pub use wgpu;

View file

@ -0,0 +1,193 @@
//! CPU-side glyph packing for the overlay text atlas.
//!
//! The atlas is a single `R8` image: one byte of coverage per texel. Glyphs are
//! packed shelf by shelf and cached by `(char, pixel size)`, so a glyph is
//! rasterized and uploaded once per size.
/// Edge length of the square atlas texture, texels.
pub(super) const SIZE: u32 = 1024;
/// Empty texels kept between glyphs so linear filtering cannot bleed.
const PADDING: u32 = 1;
/// UV of a texel that is always opaque white, shared by solid rectangles and
/// lines so they can use the text pipeline.
pub(super) const WHITE_UV: [f32; 2] = [1.0 / 1024.0, 1.0 / 1024.0];
/// A rectangle of the atlas that has to be uploaded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Region {
pub(super) x: u32,
pub(super) y: u32,
pub(super) w: u32,
pub(super) h: u32,
}
/// A rasterized glyph placed in the atlas.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Glyph {
pub(super) uv: [f32; 2],
pub(super) uv_size: [f32; 2],
pub(super) xmin: i32,
pub(super) ymin: i32,
pub(super) width: u32,
pub(super) height: u32,
pub(super) advance: f32,
}
/// One rasterized bitmap handed to the atlas.
pub(super) struct Raster<'a> {
pub(super) bitmap: &'a [u8],
pub(super) width: u32,
pub(super) height: u32,
pub(super) xmin: i32,
pub(super) ymin: i32,
pub(super) advance: f32,
}
struct Entry {
ch: char,
size_bits: u32,
glyph: Glyph,
}
/// Packed glyph coverage plus the cache that maps characters onto it.
pub(super) struct GlyphAtlas {
pixels: Vec<u8>,
entries: Vec<Entry>,
cursor_x: u32,
cursor_y: u32,
shelf: u32,
dirty: Vec<Region>,
}
impl GlyphAtlas {
/// An empty atlas with a small white block at the origin.
pub(super) fn new() -> Self {
let mut pixels = vec![0; (SIZE * SIZE) as usize];
// A two by two white block at the origin; sampling its centre stays white
// even when filtering drifts by half a texel.
pixels[0..2].fill(255);
let second_row = SIZE as usize;
pixels[second_row..second_row + 2].fill(255);
Self {
pixels,
entries: Vec::new(),
cursor_x: 2 + PADDING,
cursor_y: 0,
shelf: 2,
dirty: vec![Region {
x: 0,
y: 0,
w: 2,
h: 2,
}],
}
}
/// The raw coverage buffer, `SIZE * SIZE` bytes.
pub(super) fn pixels(&self) -> &[u8] {
&self.pixels
}
/// The number of cached glyphs.
#[allow(dead_code, reason = "read by the overlay atlas test")]
pub(super) fn len(&self) -> usize {
self.entries.len()
}
/// A region that still has to be uploaded to the GPU.
pub(super) fn take_dirty(&mut self) -> Vec<Region> {
std::mem::take(&mut self.dirty)
}
/// The cached glyph for `ch` at a pixel size, if any.
pub(super) fn get(&self, ch: char, size_bits: u32) -> Option<&Glyph> {
self.entries
.iter()
.find(|entry| entry.ch == ch && entry.size_bits == size_bits)
.map(|entry| &entry.glyph)
}
/// Packs a rasterized glyph and returns its placement.
///
/// Returns `None` when the glyph is already cached or the atlas has no room
/// left for it.
pub(super) fn insert(
&mut self,
ch: char,
size_bits: u32,
raster: &Raster<'_>,
) -> Option<Glyph> {
if self.get(ch, size_bits).is_some() {
return None;
}
let (x, y) = self.reserve(raster.width, raster.height)?;
let glyph = Glyph {
uv: [x as f32 / SIZE as f32, y as f32 / SIZE as f32],
uv_size: [
raster.width as f32 / SIZE as f32,
raster.height as f32 / SIZE as f32,
],
xmin: raster.xmin,
ymin: raster.ymin,
width: raster.width,
height: raster.height,
advance: raster.advance,
};
self.write(x, y, raster);
self.entries.push(Entry {
ch,
size_bits,
glyph,
});
Some(glyph)
}
/// Finds a free shelf slot for a `width` by `height` bitmap.
fn reserve(&mut self, width: u32, height: u32) -> Option<(u32, u32)> {
if width == 0 || height == 0 {
// Invisible glyphs (spaces) still need a cache entry, not texels.
return Some((0, 0));
}
if width + 2 * PADDING > SIZE || height + PADDING > SIZE {
return None;
}
if self.cursor_x + width + PADDING > SIZE {
self.cursor_y += self.shelf + PADDING;
self.cursor_x = 0;
self.shelf = 0;
}
if self.cursor_y + height + PADDING > SIZE {
return None;
}
let spot = (self.cursor_x, self.cursor_y);
self.cursor_x += width + PADDING;
self.shelf = self.shelf.max(height);
Some(spot)
}
/// Copies a bitmap into the coverage buffer and marks the region dirty.
fn write(&mut self, x: u32, y: u32, raster: &Raster<'_>) {
if raster.width == 0 || raster.height == 0 {
return;
}
for row in 0..raster.height {
let source = (row * raster.width) as usize;
let target = ((y + row) * SIZE + x) as usize;
let length = raster.width as usize;
if let (Some(from), Some(to)) = (
raster.bitmap.get(source..source + length),
self.pixels.get_mut(target..target + length),
) {
to.copy_from_slice(from);
}
}
self.dirty.push(Region {
x,
y,
w: raster.width,
h: raster.height,
});
}
}

View file

@ -0,0 +1,123 @@
//! Screen-space 2D overlay drawn after the 3D scene.
//!
//! The overlay is a list of rectangles, lines and text in target pixels with the
//! origin at the top-left. One triangle batch draws all of it with depth testing
//! disabled and alpha blending: solid shapes sample a white texel of the glyph
//! atlas, text samples glyph coverage.
mod atlas;
mod pass;
mod text;
#[cfg(test)]
mod tests;
pub(crate) use pass::{OverlayRenderer, Target};
/// A filled rectangle in target pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OverlayRect {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub color: [f32; 4],
}
impl OverlayRect {
/// A rectangle at `(x, y)` with a size and a linear RGBA colour.
#[must_use]
pub fn new(x: f32, y: f32, w: f32, h: f32, color: [f32; 4]) -> Self {
Self { x, y, w, h, color }
}
}
/// A straight line of a given width in target pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OverlayLine {
pub from: [f32; 2],
pub to: [f32; 2],
pub width: f32,
pub color: [f32; 4],
}
impl OverlayLine {
/// A line from `from` to `to` with a width and a linear RGBA colour.
#[must_use]
pub fn new(from: [f32; 2], to: [f32; 2], width: f32, color: [f32; 4]) -> Self {
Self {
from,
to,
width,
color,
}
}
}
/// One line of ASCII text, anchored at its top-left corner.
#[derive(Debug, Clone, PartialEq)]
pub struct OverlayText {
pub x: f32,
pub y: f32,
pub size: f32,
pub color: [f32; 4],
pub text: String,
}
impl OverlayText {
/// Text at `(x, y)` in pixels with a font size and a linear RGBA colour.
#[must_use]
pub fn new(x: f32, y: f32, size: f32, color: [f32; 4], text: impl Into<String>) -> Self {
Self {
x,
y,
size,
color,
text: text.into(),
}
}
}
/// Everything the overlay pass draws in one frame.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Overlay {
pub rects: Vec<OverlayRect>,
pub lines: Vec<OverlayLine>,
pub texts: Vec<OverlayText>,
}
impl Overlay {
/// An empty overlay.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Drops all shapes but keeps the allocated buffers.
pub fn clear(&mut self) {
self.rects.clear();
self.lines.clear();
self.texts.clear();
}
/// Whether the overlay would draw nothing.
#[must_use]
pub fn is_empty(&self) -> bool {
self.rects.is_empty() && self.lines.is_empty() && self.texts.is_empty()
}
/// Queues a filled rectangle.
pub fn push_rect(&mut self, rect: OverlayRect) {
self.rects.push(rect);
}
/// Queues a line.
pub fn push_line(&mut self, line: OverlayLine) {
self.lines.push(line);
}
/// Queues a text line.
pub fn push_text(&mut self, text: OverlayText) {
self.texts.push(text);
}
}

View file

@ -0,0 +1,106 @@
//! Vertex layout and quad assembly for the overlay batch.
use bytemuck::{Pod, Zeroable};
use super::super::OverlayLine;
use super::super::atlas::WHITE_UV;
/// A single overlay vertex: clip-space position, atlas UV and colour.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
pub(super) struct Vertex {
pub(super) position: [f32; 2],
pub(super) uv: [f32; 2],
pub(super) color: [f32; 4],
}
pub(super) const ATTRIBUTES: [wgpu::VertexAttribute; 3] = [
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 0,
shader_location: 0,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 8,
shader_location: 1,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 16,
shader_location: 2,
},
];
/// UV rectangle of the always-white atlas texel.
pub(super) fn solid_uv() -> [f32; 4] {
[WHITE_UV[0], WHITE_UV[1], WHITE_UV[0], WHITE_UV[1]]
}
/// Pixels to normalized device coordinates; the overlay's y axis points down.
fn ndc(x: f32, y: f32, size: (u32, u32)) -> [f32; 2] {
let width = size.0.max(1) as f32;
let height = size.1.max(1) as f32;
[x / width * 2.0 - 1.0, 1.0 - y / height * 2.0]
}
/// Appends an axis-aligned quad as two triangles.
pub(super) fn push_quad(
vertices: &mut Vec<Vertex>,
size: (u32, u32),
rect: [f32; 4],
uv: [f32; 4],
color: [f32; 4],
) {
let [x, y, w, h] = rect;
if w <= 0.0 || h <= 0.0 {
return;
}
let top_left = ndc(x, y, size);
let bottom_right = ndc(x + w, y + h, size);
let corners = [
([top_left[0], top_left[1]], [uv[0], uv[1]]),
([bottom_right[0], top_left[1]], [uv[2], uv[1]]),
([bottom_right[0], bottom_right[1]], [uv[2], uv[3]]),
([top_left[0], bottom_right[1]], [uv[0], uv[3]]),
];
push_corners(vertices, corners, color);
}
/// Appends a line as a quad expanded along its normal.
pub(super) fn push_segment(vertices: &mut Vec<Vertex>, size: (u32, u32), line: &OverlayLine) {
let [x0, y0] = line.from;
let [x1, y1] = line.to;
let dx = x1 - x0;
let dy = y1 - y0;
let length = (dx * dx + dy * dy).sqrt();
if length <= f32::EPSILON || line.width <= 0.0 {
return;
}
let half = line.width * 0.5;
let nx = -dy / length * half;
let ny = dx / length * half;
let uv = WHITE_UV;
let corners = [
(ndc(x0 + nx, y0 + ny, size), uv),
(ndc(x1 + nx, y1 + ny, size), uv),
(ndc(x1 - nx, y1 - ny, size), uv),
(ndc(x0 - nx, y0 - ny, size), uv),
];
push_corners(vertices, corners, line.color);
}
/// Appends two triangles for four pixel-space corners.
fn push_corners(vertices: &mut Vec<Vertex>, corners: [([f32; 2], [f32; 2]); 4], color: [f32; 4]) {
const INDICES: [usize; 6] = [0, 1, 2, 0, 2, 3];
for index in INDICES {
let Some((position, uv)) = corners.get(index) else {
continue;
};
vertices.push(Vertex {
position: *position,
uv: *uv,
color,
});
}
}

View file

@ -0,0 +1,327 @@
//! The overlay render pass: one triangle batch with alpha blending, no depth.
mod geometry;
use std::sync::Mutex;
use wgpu::util::DeviceExt;
use self::geometry::{ATTRIBUTES, Vertex, push_quad, push_segment, solid_uv};
use super::Overlay;
use super::atlas::{GlyphAtlas, Region, SIZE};
use super::text::TextRasterizer;
/// GPU state of the overlay pass.
///
/// The glyph atlas grows while drawing, so it sits behind a mutex: that keeps
/// [`crate::Renderer::draw_overlay`] callable through a shared reference.
pub(crate) struct OverlayRenderer {
state: Mutex<State>,
}
struct State {
pipeline: wgpu::RenderPipeline,
bind_group: wgpu::BindGroup,
texture: wgpu::Texture,
rasterizer: TextRasterizer,
}
/// The colour view and pixel size the overlay draws into.
#[derive(Clone, Copy)]
pub(crate) struct Target<'a> {
pub(crate) view: &'a wgpu::TextureView,
pub(crate) size: (u32, u32),
}
/// A recorded vertex batch: pipeline, atlas binding and geometry.
struct Batch<'a> {
pipeline: &'a wgpu::RenderPipeline,
bind_group: &'a wgpu::BindGroup,
vertices: &'a [Vertex],
}
impl OverlayRenderer {
/// Creates the atlas texture, sampler, bind group and pipeline.
pub(crate) fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
) -> Self {
let texture = create_atlas_texture(device);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("fabrilis atlas sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let layout = create_layout(device);
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fabrilis atlas"),
layout: &layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&sampler),
},
],
});
let pipeline = create_pipeline(device, format, &layout);
let mut rasterizer = TextRasterizer::new();
upload_atlas(queue, &texture, &mut rasterizer);
Self {
state: Mutex::new(State {
pipeline,
bind_group,
texture,
rasterizer,
}),
}
}
/// Draws the overlay over whatever is already in the target.
pub(crate) fn draw(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
target: Target<'_>,
overlay: &Overlay,
) {
if target.size.0 == 0 || target.size.1 == 0 || overlay.is_empty() {
return;
}
let Ok(mut guard) = self.state.lock() else {
return;
};
let State {
pipeline,
bind_group,
texture,
rasterizer,
} = &mut *guard;
let mut vertices = Vec::with_capacity(
overlay.rects.len() * 6 + overlay.lines.len() * 6 + overlay.texts.len() * 24,
);
for rect in &overlay.rects {
push_quad(
&mut vertices,
target.size,
[rect.x, rect.y, rect.w, rect.h],
solid_uv(),
rect.color,
);
}
for line in &overlay.lines {
push_segment(&mut vertices, target.size, line);
}
for item in &overlay.texts {
for quad in rasterizer.layout(item) {
push_quad(&mut vertices, target.size, quad.rect, quad.uv, item.color);
}
}
// Layout may have rasterized new glyphs, so upload after it.
upload_atlas(queue, texture, rasterizer);
submit(
device,
queue,
target,
Batch {
pipeline,
bind_group,
vertices: &vertices,
},
);
}
}
/// Uploads the vertex batch and records the overlay pass.
fn submit(device: &wgpu::Device, queue: &wgpu::Queue, target: Target<'_>, batch: Batch<'_>) {
let vertices = batch.vertices;
if vertices.is_empty() {
return;
}
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("fabrilis overlay vertices"),
contents: bytemuck::cast_slice(vertices),
usage: wgpu::BufferUsages::VERTEX,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("fabrilis overlay frame"),
});
{
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: target.view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fabrilis overlay pass"),
color_attachments: &attachments,
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(batch.pipeline);
pass.set_bind_group(0, batch.bind_group, &[]);
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw(0..vertices.len() as u32, 0..1);
}
queue.submit([encoder.finish()]);
}
fn create_atlas_texture(device: &wgpu::Device) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: Some("fabrilis glyph atlas"),
size: wgpu::Extent3d {
width: SIZE,
height: SIZE,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
})
}
fn create_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("fabrilis overlay layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
})
}
fn create_pipeline(
device: &wgpu::Device,
format: wgpu::TextureFormat,
layout: &wgpu::BindGroupLayout,
) -> wgpu::RenderPipeline {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("fabrilis overlay shader"),
source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("overlay.wgsl"))),
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("fabrilis overlay pipeline layout"),
bind_group_layouts: &[Some(layout)],
immediate_size: 0,
});
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("fabrilis overlay pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: 32,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &ATTRIBUTES,
})],
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
cull_mode: None,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
}
/// Uploads every atlas region written since the previous frame.
fn upload_atlas(queue: &wgpu::Queue, texture: &wgpu::Texture, rasterizer: &mut TextRasterizer) {
let regions = rasterizer.take_dirty();
if regions.is_empty() {
return;
}
let atlas = rasterizer.atlas();
for region in regions {
let (data, row) = padded_region(atlas, region);
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d {
x: region.x,
y: region.y,
z: 0,
},
aspect: wgpu::TextureAspect::All,
},
&data,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(row),
rows_per_image: Some(region.h),
},
wgpu::Extent3d {
width: region.w,
height: region.h,
depth_or_array_layers: 1,
},
);
}
}
/// Copies one atlas region into a row-padded staging buffer.
fn padded_region(atlas: &GlyphAtlas, region: Region) -> (Vec<u8>, u32) {
let row =
region.w.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let mut data = vec![0; (row * region.h) as usize];
let pixels = atlas.pixels();
let length = region.w as usize;
for line in 0..region.h {
let source = ((region.y + line) * SIZE + region.x) as usize;
let target = (line * row) as usize;
if let (Some(from), Some(to)) = (
pixels.get(source..source + length),
data.get_mut(target..target + length),
) {
to.copy_from_slice(from);
}
}
(data, row)
}

View file

@ -0,0 +1,29 @@
struct VertexInput {
@location(0) position: vec2<f32>,
@location(1) uv: vec2<f32>,
@location(2) color: vec4<f32>,
};
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
};
@vertex
fn vs_main(input: VertexInput) -> VertexOutput {
var output: VertexOutput;
output.clip_position = vec4<f32>(input.position, 0.0, 1.0);
output.uv = input.uv;
output.color = input.color;
return output;
}
@group(0) @binding(0) var atlas: texture_2d<f32>;
@group(0) @binding(1) var atlas_sampler: sampler;
@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
let coverage = textureSample(atlas, atlas_sampler, input.uv).r;
return vec4<f32>(input.color.rgb, input.color.a * coverage);
}

View file

@ -0,0 +1,156 @@
//! Headless tests for the screen-space overlay.
use super::atlas::{GlyphAtlas, Raster};
use super::text::font_path;
use super::{Overlay, OverlayLine, OverlayRect, OverlayText};
use crate::{Camera, Gpu, MeshData, Renderer, Scene};
use wgpu::TextureFormat;
const SIZE: u32 = 64;
const FORMAT: TextureFormat = TextureFormat::Rgba8UnormSrgb;
fn setup() -> (Gpu, Renderer) {
let gpu = Gpu::headless().expect("headless adapter");
let renderer =
Renderer::new(gpu.device(), gpu.queue(), FORMAT, (SIZE, SIZE)).expect("renderer");
(gpu, renderer)
}
fn empty_scene() -> Scene {
Scene::new(MeshData::default())
}
fn camera() -> Camera {
Camera::look_at([0.0, 0.0, 5.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0])
}
fn pixel_at(pixels: &[u8], x: u32, y: u32) -> [u8; 4] {
let index = ((y * SIZE + x) * 4) as usize;
[
pixels[index],
pixels[index + 1],
pixels[index + 2],
pixels[index + 3],
]
}
#[test]
fn red_rect_changes_pixels() {
let (_gpu, mut renderer) = setup();
let mut overlay = Overlay::new();
overlay.push_rect(OverlayRect::new(
16.0,
16.0,
32.0,
32.0,
[1.0, 0.0, 0.0, 1.0],
));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("draw");
let pixels = renderer.pixels().expect("pixels");
assert_eq!(pixels.len(), (SIZE * SIZE * 4) as usize);
let inside = pixel_at(&pixels, 32, 32);
assert!(
inside[0] > 200 && inside[1] < 40 && inside[2] < 40,
"the rect must be red: {inside:?}"
);
let outside = pixel_at(&pixels, 2, 2);
assert!(
outside[0] < 120,
"the corner must keep the clear colour: {outside:?}"
);
}
#[test]
fn white_line_changes_pixels() {
let (_gpu, mut renderer) = setup();
let mut overlay = Overlay::new();
overlay.push_line(OverlayLine::new(
[4.0, 32.0],
[60.0, 32.0],
3.0,
[1.0, 1.0, 1.0, 1.0],
));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("draw");
let pixels = renderer.pixels().expect("pixels");
let on_line = pixel_at(&pixels, 32, 32);
assert!(
on_line.iter().take(3).all(|channel| *channel > 200),
"the line must be white: {on_line:?}"
);
let off_line = pixel_at(&pixels, 32, 4);
assert!(
off_line[0] < 120,
"away from the line the background stays: {off_line:?}"
);
}
#[test]
fn text_draws_pixels_when_a_font_exists() {
if font_path().is_none() {
return;
}
let (_gpu, mut renderer) = setup();
let mut overlay = Overlay::new();
overlay.push_text(OverlayText::new(
4.0,
4.0,
20.0,
[1.0, 1.0, 1.0, 1.0],
"FPS 60",
));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("draw");
let pixels = renderer.pixels().expect("pixels");
let covered = (4..60)
.flat_map(|x| (4..28).map(move |y| (x, y)))
.filter(|(x, y)| pixel_at(&pixels, *x, *y)[0] > 150)
.count();
assert!(covered > 0, "the text must cover at least one pixel");
}
#[test]
fn atlas_does_not_duplicate_glyphs() {
let mut atlas = GlyphAtlas::new();
let _ = atlas.take_dirty();
let bitmap = [255u8; 16];
let raster = Raster {
bitmap: &bitmap,
width: 4,
height: 4,
xmin: 0,
ymin: 0,
advance: 5.0,
};
let size = 14.0f32.to_bits();
let first = atlas.insert('A', size, &raster).expect("first insert");
assert_eq!(atlas.take_dirty().len(), 1, "one upload per new glyph");
assert!(
atlas.insert('A', size, &raster).is_none(),
"the same glyph is not packed twice"
);
assert!(
atlas.take_dirty().is_empty(),
"no upload for a cached glyph"
);
assert_eq!(atlas.len(), 1);
let cached = atlas.get('A', size).expect("cached glyph");
assert_eq!(cached.uv, first.uv);
}
#[test]
fn zero_size_target_is_skipped() {
let (_gpu, mut renderer) = setup();
renderer.resize((0, 0)).expect("resize to zero");
let mut overlay = Overlay::new();
overlay.push_rect(OverlayRect::new(0.0, 0.0, 8.0, 8.0, [1.0; 4]));
renderer
.draw_with_overlay(&empty_scene(), &camera(), &overlay)
.expect("skipped draw");
assert!(renderer.pixels().expect("pixels").is_empty());
}

View file

@ -0,0 +1,136 @@
//! Font loading and glyph layout for the overlay text.
use std::path::Path;
use fontdue::{Font, FontSettings};
use super::OverlayText;
use super::atlas::{Glyph, GlyphAtlas, Raster, Region};
/// Font files tried in order; the first one that exists is loaded.
const FONT_PATHS: [&str; 5] = [
"/usr/share/fonts/noto/NotoSans-Regular.ttf",
"/usr/share/fonts/TTF/DejaVuSans.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/System/Library/Fonts/Helvetica.ttc",
"C:\\Windows\\Fonts\\segoeui.ttf",
];
/// One textured glyph quad in overlay pixels, origin top-left.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct GlyphQuad {
pub(super) rect: [f32; 4],
pub(super) uv: [f32; 4],
}
/// The first font file that exists on this machine, if any.
pub(super) fn font_path() -> Option<&'static str> {
FONT_PATHS
.iter()
.copied()
.find(|path| Path::new(path).is_file())
}
/// Rasterizes text and caches glyph coverage in the atlas.
pub(super) struct TextRasterizer {
font: Option<Font>,
atlas: GlyphAtlas,
}
impl TextRasterizer {
/// Loads the first available font; without one, text is skipped.
pub(super) fn new() -> Self {
Self {
font: load_font(),
atlas: GlyphAtlas::new(),
}
}
/// Regions of the atlas that were written since the last call.
pub(super) fn take_dirty(&mut self) -> Vec<Region> {
self.atlas.take_dirty()
}
/// The packed coverage that backs the glyph quads.
pub(super) fn atlas(&self) -> &GlyphAtlas {
&self.atlas
}
/// Lays one line of ASCII text out into covered quads.
pub(super) fn layout(&mut self, text: &OverlayText) -> Vec<GlyphQuad> {
let mut quads = Vec::new();
if self.font.is_none() {
return quads;
}
let size = text.size.max(1.0);
let bits = size.to_bits();
let baseline = text.y + self.ascent(size);
let mut pen = text.x;
for ch in text.text.chars() {
if !ch.is_ascii() {
continue;
}
let Some(glyph) = self.glyph(ch, size, bits) else {
continue;
};
if glyph.width > 0 && glyph.height > 0 {
let x = pen + glyph.xmin as f32;
let y = baseline - glyph.ymin as f32 - glyph.height as f32;
quads.push(GlyphQuad {
rect: [x, y, glyph.width as f32, glyph.height as f32],
uv: [
glyph.uv[0],
glyph.uv[1],
glyph.uv[0] + glyph.uv_size[0],
glyph.uv[1] + glyph.uv_size[1],
],
});
}
pen += glyph.advance;
}
quads
}
/// Distance from the top of the text box down to the baseline.
fn ascent(&self, size: f32) -> f32 {
self.font
.as_ref()
.and_then(|font| font.horizontal_line_metrics(size))
.map_or(size * 0.8, |line| line.ascent)
}
/// The cached glyph for `ch`, rasterizing and packing it on first use.
fn glyph(&mut self, ch: char, size: f32, bits: u32) -> Option<Glyph> {
if let Some(cached) = self.atlas.get(ch, bits) {
return Some(*cached);
}
let font = self.font.as_ref()?;
let (metrics, bitmap) = font.rasterize(ch, size);
let raster = Raster {
bitmap: &bitmap,
width: metrics.width as u32,
height: metrics.height as u32,
xmin: metrics.xmin,
ymin: metrics.ymin,
advance: metrics.advance_width,
};
if let Some(packed) = self.atlas.insert(ch, bits, &raster) {
return Some(packed);
}
// The atlas is full: keep the pen moving but draw nothing.
Some(Glyph {
uv: [0.0, 0.0],
uv_size: [0.0, 0.0],
xmin: 0,
ymin: 0,
width: 0,
height: 0,
advance: metrics.advance_width,
})
}
}
fn load_font() -> Option<Font> {
let data = std::fs::read(font_path()?).ok()?;
Font::from_bytes(data, FontSettings::default()).ok()
}

View file

@ -0,0 +1,306 @@
//! Depth-tested scene renderer with an optional offscreen colour target.
mod pipeline;
mod target;
#[cfg(test)]
mod tests;
use pipeline::Pipelines;
use crate::overlay::{Overlay, OverlayRenderer, Target};
use crate::{Camera, RenderError, Scene};
/// A renderer that owns its pipelines, depth buffer and optional colour target.
pub struct Renderer {
device: wgpu::Device,
queue: wgpu::Queue,
format: wgpu::TextureFormat,
size: (u32, u32),
offscreen: bool,
pipelines: Pipelines,
overlay: OverlayRenderer,
depth: Option<(wgpu::Texture, wgpu::TextureView)>,
color: Option<(wgpu::Texture, wgpu::TextureView)>,
}
impl Renderer {
/// Builds a renderer with an offscreen colour target for pixel readback.
pub fn new(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
size: (u32, u32),
) -> Result<Self, RenderError> {
Self::create(device, queue, format, size, true)
}
/// Builds a renderer that draws directly into a caller-provided view.
pub fn for_surface(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
size: (u32, u32),
) -> Result<Self, RenderError> {
Self::create(device, queue, format, size, false)
}
fn create(
device: &wgpu::Device,
queue: &wgpu::Queue,
format: wgpu::TextureFormat,
size: (u32, u32),
offscreen: bool,
) -> Result<Self, RenderError> {
let pipelines = pipeline::build(device, format);
let overlay = OverlayRenderer::new(device, queue, format);
let mut renderer = Self {
device: device.clone(),
queue: queue.clone(),
format,
size,
offscreen,
pipelines,
overlay,
depth: None,
color: None,
};
renderer.allocate_targets()?;
Ok(renderer)
}
/// Replaces the depth and colour targets after a resize.
pub fn resize(&mut self, size: (u32, u32)) -> Result<(), RenderError> {
if size == self.size {
return Ok(());
}
self.size = size;
self.depth = None;
self.color = None;
self.allocate_targets()
}
/// The current target size in pixels.
#[must_use]
pub fn size(&self) -> (u32, u32) {
self.size
}
/// Draws the scene into the offscreen colour target.
pub fn draw(&mut self, scene: &Scene, camera: &Camera) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
let (_, view) = self.color.as_ref().ok_or_else(|| {
RenderError::Texture("renderer has no offscreen colour target".to_string())
})?;
self.render(view, scene, camera);
Ok(())
}
/// Draws the scene into a surface texture view owned by the caller.
pub fn draw_to(
&self,
view: &wgpu::TextureView,
scene: &Scene,
camera: &Camera,
) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
self.render(view, scene, camera);
Ok(())
}
/// Draws the 2D overlay into a target view, on top of what is already there.
pub fn draw_overlay(
&self,
view: &wgpu::TextureView,
overlay: &Overlay,
) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
self.overlay.draw(
&self.device,
&self.queue,
Target {
view,
size: self.size,
},
overlay,
);
Ok(())
}
/// Draws the scene and then the overlay into the offscreen colour target.
pub fn draw_with_overlay(
&mut self,
scene: &Scene,
camera: &Camera,
overlay: &Overlay,
) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
self.draw(scene, camera)?;
let (_, view) = self.color.as_ref().ok_or_else(|| {
RenderError::Texture("renderer has no offscreen colour target".to_string())
})?;
self.draw_overlay(view, overlay)
}
/// Reads the offscreen target back as tightly packed RGBA8 pixels.
pub fn pixels(&self) -> Result<Vec<u8>, RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(Vec::new());
}
let (texture, _) = self.color.as_ref().ok_or_else(|| {
RenderError::Texture("renderer has no offscreen colour target".to_string())
})?;
self.read_texture(texture)
}
fn render(&self, view: &wgpu::TextureView, scene: &Scene, camera: &Camera) {
let Some((_, depth)) = &self.depth else {
return;
};
self.write_globals(camera);
let geometry = self.prepare_geometry(scene);
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("fabrilis frame"),
});
{
let attachments = [Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(pipeline::CLEAR_COLOR),
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fabrilis scene pass"),
color_attachments: &attachments,
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(&self.pipelines.pipeline);
pass.set_bind_group(0, &self.pipelines.bind_group, &[]);
geometry.draw_mesh(&mut pass, &self.pipelines);
geometry.draw_boxes(&mut pass, &self.pipelines);
}
self.queue.submit([encoder.finish()]);
}
fn write_globals(&self, camera: &Camera) {
let globals = pipeline::Globals::new(camera.view_projection(), camera.eye());
self.queue
.write_buffer(&self.pipelines.globals, 0, bytemuck::bytes_of(&globals));
}
fn prepare_geometry(&self, scene: &Scene) -> Geometry {
let terrain = pipeline::RawInstance {
model: crate::Instance::IDENTITY,
color: scene.mesh_color,
};
self.queue.write_buffer(
&self.pipelines.terrain_instance,
0,
bytemuck::bytes_of(&terrain),
);
Geometry {
mesh_vertices: upload_vertices(&self.device, scene),
mesh_indices: upload_indices(&self.device, scene),
mesh_index_count: scene.mesh.indices.len() as u32,
boxes: upload_instances(&self.device, scene),
instance_count: scene.instances.len() as u32,
}
}
}
struct Geometry {
mesh_vertices: Option<wgpu::Buffer>,
mesh_indices: Option<wgpu::Buffer>,
mesh_index_count: u32,
boxes: Option<wgpu::Buffer>,
instance_count: u32,
}
impl Geometry {
fn draw_mesh(&self, pass: &mut wgpu::RenderPass<'_>, pipelines: &Pipelines) {
let (Some(vertices), Some(indices)) = (&self.mesh_vertices, &self.mesh_indices) else {
return;
};
pass.set_vertex_buffer(0, vertices.slice(..));
pass.set_vertex_buffer(1, pipelines.terrain_instance.slice(..));
pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(0..self.mesh_index_count, 0, 0..1);
}
fn draw_boxes(&self, pass: &mut wgpu::RenderPass<'_>, pipelines: &Pipelines) {
let Some(instances) = &self.boxes else {
return;
};
pass.set_vertex_buffer(0, pipelines.cube_vertices.slice(..));
pass.set_vertex_buffer(1, instances.slice(..));
pass.set_index_buffer(pipelines.cube_indices.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(0..pipelines.cube_index_count, 0, 0..self.instance_count);
}
}
fn upload_vertices(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer> {
if scene.mesh.vertices.is_empty() {
return None;
}
Some(pipeline::upload(
device,
"fabrilis mesh vertices",
bytemuck::cast_slice(&scene.mesh.vertices),
wgpu::BufferUsages::VERTEX,
))
}
fn upload_indices(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer> {
if scene.mesh.indices.is_empty() {
return None;
}
Some(pipeline::upload(
device,
"fabrilis mesh indices",
bytemuck::cast_slice(&scene.mesh.indices),
wgpu::BufferUsages::INDEX,
))
}
fn upload_instances(device: &wgpu::Device, scene: &Scene) -> Option<wgpu::Buffer> {
if scene.instances.is_empty() {
return None;
}
let instances: Vec<pipeline::RawInstance> = scene
.instances
.iter()
.map(|instance| pipeline::RawInstance {
model: instance.model,
color: instance.color,
})
.collect();
Some(pipeline::upload(
device,
"fabrilis box instances",
bytemuck::cast_slice(&instances),
wgpu::BufferUsages::VERTEX,
))
}

View file

@ -0,0 +1,274 @@
//! Pipeline, bind group, uniform block and static geometry shared by all frames.
use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;
/// Depth format used by the depth buffer.
pub(crate) const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
/// Background colour cleared before every pass.
pub(crate) const CLEAR_COLOR: wgpu::Color = wgpu::Color {
r: 0.05,
g: 0.06,
b: 0.08,
a: 1.0,
};
/// Per-frame uniform block; must match `Globals` in the WGSL shader.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
pub(crate) struct Globals {
pub view_proj: [[f32; 4]; 4],
pub light_dir: [f32; 4],
pub camera_pos: [f32; 4],
}
impl Globals {
pub(crate) fn new(view_proj: [[f32; 4]; 4], camera_pos: [f32; 3]) -> Self {
Self {
view_proj,
light_dir: [0.35, -0.55, 0.75, 0.0],
camera_pos: [camera_pos[0], camera_pos[1], camera_pos[2], 1.0],
}
}
}
/// One GPU instance: a column-major model matrix and a colour.
#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
pub(crate) struct RawInstance {
pub model: [[f32; 4]; 4],
pub color: [f32; 4],
}
const MESH_ATTRIBUTES: [wgpu::VertexAttribute; 1] = [wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x3,
offset: 0,
shader_location: 0,
}];
const INSTANCE_ATTRIBUTES: [wgpu::VertexAttribute; 5] = [
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 0,
shader_location: 1,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 16,
shader_location: 2,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 32,
shader_location: 3,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 48,
shader_location: 4,
},
wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x4,
offset: 64,
shader_location: 5,
},
];
/// Resource set built once per surface format.
pub(crate) struct Pipelines {
pub pipeline: wgpu::RenderPipeline,
pub bind_group: wgpu::BindGroup,
pub globals: wgpu::Buffer,
pub cube_vertices: wgpu::Buffer,
pub cube_indices: wgpu::Buffer,
pub cube_index_count: u32,
pub terrain_instance: wgpu::Buffer,
}
/// Builds the render pipeline, uniform binding and the unit-cube geometry.
pub(crate) fn build(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipelines {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("fabrilis mesh shader"),
source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("shader.wgsl"))),
});
let layout = create_bind_group_layout(device);
let (globals, bind_group) = create_globals(device, &layout);
let pipeline = create_pipeline(device, format, &shader, &layout);
let (cube_vertices, cube_indices, cube_index_count) = cube_geometry(device);
let terrain_instance = upload(
device,
"fabrilis terrain instance",
bytemuck::bytes_of(&identity_instance()),
wgpu::BufferUsages::VERTEX,
);
Pipelines {
pipeline,
bind_group,
globals,
cube_vertices,
cube_indices,
cube_index_count,
terrain_instance,
}
}
/// Uploads data into a fresh buffer with `usage | COPY_DST`.
pub(crate) fn upload(
device: &wgpu::Device,
label: &str,
data: &[u8],
usage: wgpu::BufferUsages,
) -> wgpu::Buffer {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(label),
contents: data,
usage: usage | wgpu::BufferUsages::COPY_DST,
})
}
fn identity_instance() -> RawInstance {
RawInstance {
model: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
],
color: [1.0; 4],
}
}
const CUBE_FACES: [([f32; 3], [f32; 3], [f32; 3]); 6] = [
([-0.5, -0.5, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
([-0.5, -0.5, -0.5], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]),
([0.5, -0.5, -0.5], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
([-0.5, -0.5, -0.5], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
([-0.5, 0.5, -0.5], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
([-0.5, -0.5, -0.5], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]),
];
fn cube_geometry(device: &wgpu::Device) -> (wgpu::Buffer, wgpu::Buffer, u32) {
let mut vertices = Vec::with_capacity(24);
let mut indices = Vec::with_capacity(36);
for (origin, axis_u, axis_v) in CUBE_FACES {
let base = vertices.len() as u32;
for (u, v) in [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] {
vertices.push([
origin[0] + axis_u[0] * u + axis_v[0] * v,
origin[1] + axis_u[1] * u + axis_v[1] * v,
origin[2] + axis_u[2] * u + axis_v[2] * v,
]);
}
indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
}
let vertex_buffer = upload(
device,
"fabrilis cube vertices",
bytemuck::cast_slice(&vertices),
wgpu::BufferUsages::VERTEX,
);
let index_buffer = upload(
device,
"fabrilis cube indices",
bytemuck::cast_slice(&indices),
wgpu::BufferUsages::INDEX,
);
(vertex_buffer, index_buffer, indices.len() as u32)
}
fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("fabrilis globals layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
})
}
fn create_globals(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
) -> (wgpu::Buffer, wgpu::BindGroup) {
let globals = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fabrilis globals"),
size: std::mem::size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fabrilis globals"),
layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: globals.as_entire_binding(),
}],
});
(globals, bind_group)
}
fn create_pipeline(
device: &wgpu::Device,
format: wgpu::TextureFormat,
shader: &wgpu::ShaderModule,
layout: &wgpu::BindGroupLayout,
) -> wgpu::RenderPipeline {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("fabrilis pipeline layout"),
bind_group_layouts: &[Some(layout)],
immediate_size: 0,
});
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("fabrilis scene pipeline"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: shader,
entry_point: Some("vs_main"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
buffers: &[
Some(wgpu::VertexBufferLayout {
array_stride: 12,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &MESH_ATTRIBUTES,
}),
Some(wgpu::VertexBufferLayout {
array_stride: 80,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &INSTANCE_ATTRIBUTES,
}),
],
},
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
cull_mode: None,
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH_FORMAT,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::Less),
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: shader,
entry_point: Some("fs_main"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
}

View file

@ -0,0 +1,48 @@
struct Globals {
view_proj: mat4x4<f32>,
light_dir: vec4<f32>,
camera_pos: vec4<f32>,
};
@group(0) @binding(0) var<uniform> globals: Globals;
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) model_0: vec4<f32>,
@location(2) model_1: vec4<f32>,
@location(3) model_2: vec4<f32>,
@location(4) model_3: vec4<f32>,
@location(5) color: vec4<f32>,
};
struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) world_position: vec3<f32>,
@location(1) color: vec4<f32>,
};
@vertex
fn vs_main(input: VertexInput) -> VertexOutput {
let model = mat4x4<f32>(
input.model_0,
input.model_1,
input.model_2,
input.model_3,
);
let world = model * vec4<f32>(input.position, 1.0);
var output: VertexOutput;
output.clip_position = globals.view_proj * world;
output.world_position = world.xyz;
output.color = input.color;
return output;
}
@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
// Flat face normal from screen-space derivatives; this keeps the mesh data
// to positions only, and two-sided shading tolerates either triangle winding.
let normal = normalize(cross(dpdx(input.world_position), dpdy(input.world_position)));
let light = normalize(globals.light_dir.xyz);
let diffuse = 0.25 + 0.75 * abs(dot(normal, light));
return vec4<f32>(input.color.rgb * diffuse, input.color.a);
}

View file

@ -0,0 +1,149 @@
//! Offscreen targets and pixel readback.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use super::Renderer;
use super::pipeline;
use crate::RenderError;
impl Renderer {
pub(super) fn allocate_targets(&mut self) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
let depth = create_texture(
&self.device,
"fabrilis depth",
pipeline::DEPTH_FORMAT,
self.size,
wgpu::TextureUsages::RENDER_ATTACHMENT,
);
self.depth = Some(depth);
if self.offscreen {
let color = create_texture(
&self.device,
"fabrilis colour",
self.format,
self.size,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
);
self.color = Some(color);
}
Ok(())
}
pub(super) fn read_texture(&self, texture: &wgpu::Texture) -> Result<Vec<u8>, RenderError> {
let bgra = match self.format {
wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba8UnormSrgb => false,
wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb => true,
other => {
return Err(RenderError::UnsupportedFormat(format!("{other:?}")));
}
};
let (width, height) = self.size;
let row_bytes = width * 4;
let padded_row = row_bytes.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
* wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let output = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fabrilis readback"),
size: u64::from(padded_row) * u64::from(height),
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("fabrilis readback"),
});
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &output,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded_row),
rows_per_image: Some(height),
},
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
self.queue.submit([encoder.finish()]);
let mut pixels = map_and_copy(&self.device, &output, padded_row, row_bytes, height)?;
if bgra {
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel.swap(0, 2);
}
}
Ok(pixels)
}
}
fn create_texture(
device: &wgpu::Device,
label: &str,
format: wgpu::TextureFormat,
size: (u32, u32),
usage: wgpu::TextureUsages,
) -> (wgpu::Texture, wgpu::TextureView) {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size.0,
height: size.1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
});
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
(texture, view)
}
fn map_and_copy(
device: &wgpu::Device,
buffer: &wgpu::Buffer,
padded_row: u32,
row_bytes: u32,
height: u32,
) -> Result<Vec<u8>, RenderError> {
let failed = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&failed);
buffer
.slice(..)
.map_async(wgpu::MapMode::Read, move |result| {
if result.is_err() {
flag.store(true, Ordering::SeqCst);
}
});
device
.poll(wgpu::PollType::wait_indefinitely())
.map_err(|error| RenderError::Buffer(error.to_string()))?;
if failed.load(Ordering::SeqCst) {
return Err(RenderError::Buffer("readback mapping failed".to_string()));
}
let view = buffer
.slice(..)
.get_mapped_range()
.map_err(|error| RenderError::Buffer(error.to_string()))?;
let mut pixels = Vec::with_capacity((row_bytes * height) as usize);
for row in view.chunks(padded_row as usize) {
pixels.extend(row.iter().take(row_bytes as usize).copied());
}
drop(view);
buffer.unmap();
Ok(pixels)
}

View file

@ -0,0 +1,135 @@
//! Headless rendering tests.
use super::*;
use crate::{Camera, Gpu, Instance, MeshData, Scene};
const SIZE: u32 = 256;
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
fn setup(size: (u32, u32)) -> (Gpu, Renderer) {
let gpu = Gpu::headless().expect("headless adapter");
let renderer = Renderer::new(gpu.device(), gpu.queue(), FORMAT, size).expect("renderer");
(gpu, renderer)
}
fn sloped_terrain() -> Scene {
let mesh = MeshData {
vertices: vec![
[-2.0, -2.0, -0.6],
[2.0, -2.0, 0.6],
[2.0, 2.0, 0.6],
[-2.0, 2.0, -0.6],
],
indices: vec![0, 1, 2, 0, 2, 3],
};
let mut scene = Scene::new(mesh);
scene.instances.push(Instance::box_at(
[0.0, 0.0, 1.2],
[1.0, 1.0, 1.0],
[0.9, 0.4, 0.2, 1.0],
));
scene
}
fn orbit_camera() -> Camera {
Camera::look_at([4.0, -6.0, 5.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0])
.with_projection(0.9, 1.0, 0.1, 100.0)
}
fn pixel_at(pixels: &[u8], size: (u32, u32), x: u32, y: u32) -> [u8; 4] {
let index = (y * size.0 + x) as usize * 4;
[
pixels[index],
pixels[index + 1],
pixels[index + 2],
pixels[index + 3],
]
}
#[test]
fn renders_terrain_and_box() {
let (_gpu, mut renderer) = setup((SIZE, SIZE));
let scene = sloped_terrain();
renderer.draw(&scene, &orbit_camera()).expect("draw");
let pixels = renderer.pixels().expect("pixels");
assert_eq!(pixels.len(), (SIZE * SIZE * 4) as usize);
let corner = pixel_at(&pixels, (SIZE, SIZE), 2, 2);
let centre = pixel_at(&pixels, (SIZE, SIZE), SIZE / 2, SIZE / 2);
assert_ne!(
corner, centre,
"the scene must cover the centre of the frame"
);
let covered = pixels
.as_chunks::<4>()
.0
.iter()
.filter(|pixel| {
pixel
.iter()
.zip(corner.iter())
.any(|(channel, reference)| channel.abs_diff(*reference) > 8)
})
.count();
assert!(
covered > (SIZE * SIZE / 10) as usize,
"only {covered} pixels differ from the corner"
);
}
#[test]
fn resize_reallocates_the_pixel_buffer() {
let (_gpu, mut renderer) = setup((SIZE, SIZE));
let scene = sloped_terrain();
renderer.draw(&scene, &orbit_camera()).expect("first draw");
renderer.resize((64, 96)).expect("resize");
assert_eq!(renderer.size(), (64, 96));
renderer.draw(&scene, &orbit_camera()).expect("second draw");
let pixels = renderer.pixels().expect("pixels");
assert_eq!(pixels.len(), (64 * 96 * 4) as usize);
}
#[test]
fn zero_size_target_is_skipped() {
let (_gpu, mut renderer) = setup((SIZE, SIZE));
let scene = sloped_terrain();
renderer.resize((0, 0)).expect("resize to zero");
renderer
.draw(&scene, &orbit_camera())
.expect("skipped draw");
assert!(renderer.pixels().expect("pixels").is_empty());
renderer.resize((32, 32)).expect("resize back");
renderer
.draw(&scene, &orbit_camera())
.expect("draw after resize");
assert_eq!(
renderer.pixels().expect("pixels").len(),
(32 * 32 * 4) as usize
);
}
#[test]
fn near_box_covers_far_box() {
let (_gpu, mut renderer) = setup((SIZE, SIZE));
let mut scene = Scene::new(MeshData::default());
scene.instances.push(Instance::box_at(
[0.0, 0.0, 0.0],
[2.0, 2.0, 2.0],
[1.0, 0.0, 0.0, 1.0],
));
scene.instances.push(Instance::box_at(
[0.0, 4.0, 0.0],
[2.0, 2.0, 2.0],
[0.0, 0.0, 1.0, 1.0],
));
let camera = Camera::look_at([0.0, -8.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0])
.with_projection(0.9, 1.0, 0.1, 100.0);
renderer.draw(&scene, &camera).expect("draw");
let pixels = renderer.pixels().expect("pixels");
let centre = pixel_at(&pixels, (SIZE, SIZE), SIZE / 2, SIZE / 2);
assert!(
centre[0] > centre[2],
"near red box should cover the far blue one: {centre:?}"
);
}

View file

@ -0,0 +1,80 @@
//! Scene data handed to the renderer: one triangle mesh plus instanced boxes.
type Mat4 = [[f32; 4]; 4];
/// A triangle mesh with positions in metres and `u32` triangle indices.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MeshData {
/// Vertex positions in world space.
pub vertices: Vec<[f32; 3]>,
/// Triples of vertex indices.
pub indices: Vec<u32>,
}
impl MeshData {
/// The number of complete triangles in the mesh.
#[must_use]
pub fn triangle_count(&self) -> usize {
self.indices.len() / 3
}
}
/// One drawable box: a model matrix and a flat colour.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Instance {
/// Column-major model matrix.
pub model: Mat4,
/// Linear RGBA colour.
pub color: [f32; 4],
}
impl Instance {
/// The identity model matrix.
pub const IDENTITY: Mat4 = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
/// Builds an instance from a model matrix and a colour.
#[must_use]
pub fn new(model: Mat4, color: [f32; 4]) -> Self {
Self { model, color }
}
/// A box centred at `center` with the given size along each axis.
#[must_use]
pub fn box_at(center: [f32; 3], size: [f32; 3], color: [f32; 4]) -> Self {
let model = [
[size[0], 0.0, 0.0, 0.0],
[0.0, size[1], 0.0, 0.0],
[0.0, 0.0, size[2], 0.0],
[center[0], center[1], center[2], 1.0],
];
Self::new(model, color)
}
}
/// Everything the renderer draws in one frame.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Scene {
/// The terrain surface.
pub mesh: MeshData,
/// Colour multiplied into the terrain vertices.
pub mesh_color: [f32; 4],
/// Boxes drawn with instancing.
pub instances: Vec<Instance>,
}
impl Scene {
/// A scene with one terrain mesh and the default terrain colour.
#[must_use]
pub fn new(mesh: MeshData) -> Self {
Self {
mesh,
mesh_color: [0.34, 0.46, 0.29, 1.0],
instances: Vec::new(),
}
}
}

View file

@ -1 +0,0 @@
//! fabrilis-render :: terrain - stub (see docs/ARCHITECTURE.md)

View file

@ -1 +0,0 @@
//! fabrilis-render :: views - stub (see docs/ARCHITECTURE.md)

View file

@ -13,6 +13,8 @@ workspace = true
fabrilis-core = { path = "../core" }
fabrilis-materials = { path = "../materials" }
fabrilis-storage = { path = "../storage" }
serde = { version = "1", features = ["derive"] }
ron = "0.12"
[build-dependencies]
fabrilis-limits = { path = "../../tools/limits" }

View file

@ -0,0 +1,275 @@
//! Indexed triangle mesh and its validation rules.
//!
//! The mesh is the common result of the STL and OBJ importers. Neither format
//! stores units, so positions are in metres only after the caller applies
//! [`Mesh::scaled`] with the source unit factor (see docs/COORDINATES.md).
use core::fmt;
use fabrilis_core::units::CubicMeters;
use fabrilis_core::vec::Vec3;
use std::collections::BTreeMap;
/// A closed, indexed triangle mesh in metres.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Mesh {
/// Vertex positions, metres.
pub positions: Vec<Vec3>,
/// Triangles as three indices into [`Self::positions`].
pub indices: Vec<[u32; 3]>,
}
impl Mesh {
/// Builds a mesh, rejecting triangles that reference a missing vertex.
pub fn new(positions: Vec<Vec3>, indices: Vec<[u32; 3]>) -> Result<Self, MeshError> {
let mesh = Self { positions, indices };
mesh.check_indices()?;
Ok(mesh)
}
/// Every triangle as a position triple.
///
/// Triangles whose indices point outside the position list are skipped; a
/// mesh built through [`Self::new`] never has any.
pub fn triangles(&self) -> impl Iterator<Item = [Vec3; 3]> + '_ {
self.indices
.iter()
.filter_map(|triangle| self.triangle(*triangle))
}
/// Scales every position by `factor`.
///
/// Use `0.001` for millimetres, `0.01` for centimetres and `1.0` for metres
/// (see docs/COORDINATES.md).
#[must_use]
pub fn scaled(self, factor: f64) -> Self {
Self {
positions: self
.positions
.into_iter()
.map(|point| point * factor)
.collect(),
indices: self.indices,
}
}
/// Signed volume, m³, from the divergence theorem: `Σ a·(b×c)/6`.
///
/// `None` for an empty mesh, a triangle with a missing vertex or a non-finite
/// sum. A positive value means outward winding; see [`Self::validate`].
#[must_use]
pub fn signed_volume(&self) -> Option<f64> {
if self.indices.is_empty() {
return None;
}
let mut six_volume = 0.0;
for triangle in &self.indices {
let [a, b, c] = self.triangle(*triangle)?;
six_volume += a.dot(b.cross(c));
}
let volume = six_volume / 6.0;
volume.is_finite().then_some(volume)
}
/// Total surface area, m².
#[must_use]
pub fn area(&self) -> f64 {
self.triangles()
.map(|[a, b, c]| (b - a).cross(c - a).length() * 0.5)
.sum()
}
/// Checks that the mesh is a closed surface with outward winding.
///
/// Every coordinate must be finite, every triangle must have area, every
/// undirected edge must be shared by exactly two triangles and traversed in
/// opposite directions, and the signed volume must be positive. This is the
/// check docs/TESTING.md requires before mass and inertia are computed.
pub fn validate(&self) -> Result<MeshReport, MeshError> {
if self.indices.is_empty() {
return Err(MeshError::Empty);
}
self.check_indices()?;
self.check_triangles()?;
self.check_edges()?;
let volume = self
.signed_volume()
.ok_or(MeshError::NonFinite { triangle: 0 })?;
if volume <= 0.0 {
return Err(MeshError::Inverted { volume });
}
Ok(MeshReport {
vertices: self.positions.len(),
triangles: self.indices.len(),
volume: CubicMeters::new(volume),
degenerate: 0,
})
}
/// The three positions of a triangle, or `None` when an index is missing.
fn triangle(&self, [a, b, c]: [u32; 3]) -> Option<[Vec3; 3]> {
let a = *self.positions.get(a as usize)?;
let b = *self.positions.get(b as usize)?;
let c = *self.positions.get(c as usize)?;
Some([a, b, c])
}
fn check_indices(&self) -> Result<(), MeshError> {
for (triangle, corners) in self.indices.iter().enumerate() {
for &corner in corners {
if corner as usize >= self.positions.len() {
return Err(MeshError::BadIndex { triangle });
}
}
}
Ok(())
}
fn check_triangles(&self) -> Result<(), MeshError> {
for (index, triangle) in self.indices.iter().enumerate() {
let [a, b, c] = self
.triangle(*triangle)
.ok_or(MeshError::BadIndex { triangle: index })?;
if [a, b, c].iter().any(|point| !point.is_finite()) {
return Err(MeshError::NonFinite { triangle: index });
}
if (b - a).cross(c - a).length_squared() == 0.0 {
return Err(MeshError::Degenerate { triangle: index });
}
}
Ok(())
}
fn check_edges(&self) -> Result<(), MeshError> {
let mut edges: BTreeMap<(u32, u32), EdgeUse> = BTreeMap::new();
for triangle in &self.indices {
let [a, b, c] = *triangle;
for (start, end) in [(a, b), (b, c), (c, a)] {
let key = if start < end {
(start, end)
} else {
(end, start)
};
let edge = edges.entry(key).or_default();
if start < end {
edge.forward += 1;
} else {
edge.backward += 1;
}
}
}
let broken = edges
.values()
.filter(|edge| edge.forward + edge.backward != 2)
.count();
if broken > 0 {
return Err(MeshError::NotWatertight {
undirected_edges: broken,
});
}
if let Some((edge, _)) = edges.iter().find(|(_, edge)| edge.forward != 1) {
return Err(MeshError::InconsistentWinding { edge: *edge });
}
Ok(())
}
}
/// How many triangles traverse an undirected edge in each direction.
#[derive(Default)]
struct EdgeUse {
/// Triangles going from the smaller index to the larger one.
forward: usize,
/// Triangles going from the larger index to the smaller one.
backward: usize,
}
/// What [`Mesh::validate`] measured on a valid mesh.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MeshReport {
/// Number of vertices, including unused ones.
pub vertices: usize,
/// Number of triangles.
pub triangles: usize,
/// Enclosed volume, m³.
pub volume: CubicMeters,
/// Degenerate triangles found; always zero for a valid mesh.
pub degenerate: usize,
}
/// Why a mesh or an imported file was rejected.
#[derive(Debug, Clone, PartialEq)]
pub enum MeshError {
/// The input has no triangles.
Empty,
/// A triangle references a vertex outside the position list.
BadIndex {
/// Zero-based triangle number.
triangle: usize,
},
/// A triangle has a non-finite coordinate.
NonFinite {
/// Zero-based triangle number.
triangle: usize,
},
/// A triangle has zero area.
Degenerate {
/// Zero-based triangle number.
triangle: usize,
},
/// Edges are not shared by exactly two triangles.
NotWatertight {
/// Number of undirected edges with the wrong number of uses.
undirected_edges: usize,
},
/// An edge is traversed twice in the same direction.
InconsistentWinding {
/// The undirected edge, smaller index first.
edge: (u32, u32),
},
/// The signed volume is not positive, so the winding points inward.
Inverted {
/// The measured signed volume, m³.
volume: f64,
},
/// A line of the source file could not be parsed.
///
/// For binary STL `line` is the one-based triangle number.
Malformed {
/// One-based line number in the text, or triangle number in binary STL.
line: usize,
/// What went wrong.
reason: String,
},
}
impl fmt::Display for MeshError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => write!(formatter, "mesh has no triangles"),
Self::BadIndex { triangle } => {
write!(formatter, "triangle {triangle} references a missing vertex")
}
Self::NonFinite { triangle } => {
write!(formatter, "triangle {triangle} has a non-finite coordinate")
}
Self::Degenerate { triangle } => {
write!(formatter, "triangle {triangle} has zero area")
}
Self::NotWatertight { undirected_edges } => write!(
formatter,
"mesh is not watertight: {undirected_edges} undirected edges are not shared by exactly two triangles"
),
Self::InconsistentWinding { edge } => write!(
formatter,
"edge ({}, {}) is traversed twice in the same direction",
edge.0, edge.1
),
Self::Inverted { volume } => write!(
formatter,
"signed volume {volume} is not positive; the winding points inward"
),
Self::Malformed { line, reason } => write!(formatter, "line {line}: {reason}"),
}
}
}
impl std::error::Error for MeshError {}

View file

@ -1 +1,18 @@
//! fabrilis-scene :: import - stub (see docs/ARCHITECTURE.md)
//! Mesh import and validation: STL (binary and ASCII) and OBJ.
//!
//! Both formats store triangles without units or axes, so the caller records the
//! source units and converts with [`Mesh::scaled`] (docs/COORDINATES.md).
//! Validation is separate from parsing: an importer returns a mesh, and
//! [`Mesh::validate`] proves it is closed, has outward winding and a positive
//! volume before mass and inertia are computed (docs/TESTING.md).
pub mod mesh;
pub mod obj;
pub mod stl;
pub use mesh::{Mesh, MeshError, MeshReport};
pub use obj::from_obj;
pub use stl::from_stl;
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,134 @@
//! OBJ import: the `v` and `f` subset needed for rigid parts.
//!
//! Supported statements:
//!
//! - `v x y z` — vertex position; extra components such as `w` are ignored;
//! - `f ...` — a polygon with three or more corners, fan-triangulated; a corner
//! may be written as `v`, `v/vt`, `v//vn` or `v/vt/vn`, and the vertex index
//! may be positive (one-based) or negative (relative to the vertices seen so
//! far).
//!
//! Comments and the `vt`, `vn`, `o`, `g`, `s`, `usemtl` and `mtllib` statements
//! are ignored. Any other statement is rejected as unsupported: this is a
//! documented subset, not a full OBJ reader. Units and axes are not stored in
//! OBJ; apply [`Mesh::scaled`] with the project factor (docs/COORDINATES.md).
use core::str::SplitWhitespace;
use fabrilis_core::vec::Vec3;
use super::mesh::{Mesh, MeshError};
/// Imports the vertex and face subset of a Wavefront OBJ file.
pub fn from_obj(text: &str) -> Result<Mesh, MeshError> {
let mut positions = Vec::new();
let mut indices = Vec::new();
for (index, line) in text.lines().enumerate() {
parse_line(line, index + 1, &mut positions, &mut indices)?;
}
if indices.is_empty() {
return Err(MeshError::Empty);
}
Mesh::new(positions, indices)
}
fn parse_line(
line: &str,
number: usize,
positions: &mut Vec<Vec3>,
indices: &mut Vec<[u32; 3]>,
) -> Result<(), MeshError> {
let content = line.split('#').next().unwrap_or_default();
let mut words = content.split_whitespace();
let Some(keyword) = words.next() else {
return Ok(());
};
match keyword {
"v" => parse_vertex(words, number, positions),
"f" => parse_face(words, number, positions.len(), indices),
"vt" | "vn" | "o" | "g" | "s" | "usemtl" | "mtllib" => Ok(()),
other => Err(malformed(
number,
format!("unsupported OBJ statement `{other}`"),
)),
}
}
fn parse_vertex(
mut words: SplitWhitespace<'_>,
number: usize,
positions: &mut Vec<Vec3>,
) -> Result<(), MeshError> {
let x = coordinate(&mut words, number)?;
let y = coordinate(&mut words, number)?;
let z = coordinate(&mut words, number)?;
positions.push(Vec3::new(x, y, z));
Ok(())
}
fn parse_face(
words: SplitWhitespace<'_>,
number: usize,
vertex_count: usize,
indices: &mut Vec<[u32; 3]>,
) -> Result<(), MeshError> {
let mut corners = Vec::new();
for word in words {
corners.push(parse_corner(word, number, vertex_count)?);
}
let Some((&first, rest)) = corners.split_first() else {
return Err(short_face(number));
};
if rest.len() < 2 {
return Err(short_face(number));
}
for pair in rest.windows(2) {
if let [a, b] = pair {
indices.push([first, *a, *b]);
}
}
Ok(())
}
/// Resolves one face corner such as `7`, `7/2`, `7//3` or `7/2/3`.
fn parse_corner(word: &str, number: usize, vertex_count: usize) -> Result<u32, MeshError> {
let mut parts = word.split('/');
let vertex = parts.next().unwrap_or_default();
if vertex.is_empty() || parts.count() > 2 {
return Err(bad_corner(word, number));
}
let Ok(raw) = vertex.parse::<i64>() else {
return Err(bad_corner(word, number));
};
let resolved = match raw {
0 => return Err(malformed(number, "OBJ vertex indices are one-based")),
relative if relative < 0 => vertex_count as i64 + relative,
absolute => absolute - 1,
};
if resolved < 0 {
return Err(bad_corner(word, number));
}
u32::try_from(resolved).map_err(|_| bad_corner(word, number))
}
fn coordinate(words: &mut SplitWhitespace<'_>, line: usize) -> Result<f64, MeshError> {
let Some(word) = words.next() else {
return Err(malformed(line, "missing vertex coordinate"));
};
word.parse()
.map_err(|_| malformed(line, format!("`{word}` is not a valid coordinate")))
}
fn short_face(line: usize) -> MeshError {
malformed(line, "face needs at least three vertices".to_string())
}
fn bad_corner(word: &str, line: usize) -> MeshError {
malformed(line, format!("`{word}` is not a valid face corner"))
}
fn malformed(line: usize, reason: impl Into<String>) -> MeshError {
MeshError::Malformed {
line,
reason: reason.into(),
}
}

View file

@ -0,0 +1,256 @@
//! STL import for binary and ASCII files.
//!
//! STL stores a triangle soup without shared vertices and without units. Import
//! welds vertices whose coordinates are bitwise equal after the `f32` → `f64`
//! conversion, so a well-formed file becomes a watertight indexed mesh. Welding
//! uses the bit pattern, so `-0.0` and `0.0` stay distinct: a file that mixes
//! signed zero can keep a seam and fail [`Mesh::validate`]. Normals are ignored;
//! the winding of the `vertex` lines is authoritative and validation checks it.
//!
//! Units are not stored either, so apply [`Mesh::scaled`] with the project unit
//! factor (millimetres by default, see docs/COORDINATES.md).
use core::str::SplitWhitespace;
use fabrilis_core::vec::Vec3;
use std::collections::BTreeMap;
use super::mesh::{Mesh, MeshError};
/// Bytes before the triangle count in a binary STL file.
const HEADER: usize = 80;
/// Bytes in one binary STL triangle record: one normal and three vertices.
const RECORD: usize = 50;
/// Bytes occupied by the normal at the start of a record; the normal is ignored.
const NORMAL: usize = 12;
/// Imports a binary or ASCII STL file.
///
/// Binary detection requires at least 84 bytes and an exact match between the
/// file length and `84 + 50 × triangle count`; anything else is parsed as ASCII.
pub fn from_stl(bytes: &[u8]) -> Result<Mesh, MeshError> {
if let Some(count) = binary_triangles(bytes) {
return from_binary(bytes, count);
}
from_ascii(bytes)
}
/// The declared triangle count when `bytes` is a binary STL file.
fn binary_triangles(bytes: &[u8]) -> Option<usize> {
let count = u32::from_le_bytes(four_bytes(bytes, HEADER)?) as usize;
let expected = (HEADER + 4).checked_add(RECORD.checked_mul(count)?)?;
(expected == bytes.len()).then_some(count)
}
fn from_binary(bytes: &[u8], count: usize) -> Result<Mesh, MeshError> {
if count == 0 {
return Err(MeshError::Empty);
}
let mut welder = Welder::default();
let mut indices = Vec::with_capacity(count);
for triangle in 0..count {
let start = HEADER + 4 + triangle * RECORD;
let points = binary_triangle(bytes, start).ok_or_else(|| truncated(triangle + 1))?;
indices.push(points.map(|point| welder.index(point)));
}
Mesh::new(welder.positions, indices)
}
/// Three vertices of one binary record; the normal at `start` is skipped.
fn binary_triangle(bytes: &[u8], start: usize) -> Option<[Vec3; 3]> {
let mut points = [Vec3::ZERO; 3];
for (index, slot) in points.iter_mut().enumerate() {
let base = start + NORMAL + index * 12;
let x = f32::from_le_bytes(four_bytes(bytes, base)?);
let y = f32::from_le_bytes(four_bytes(bytes, base + 4)?);
let z = f32::from_le_bytes(four_bytes(bytes, base + 8)?);
*slot = Vec3::new(f64::from(x), f64::from(y), f64::from(z));
}
Some(points)
}
fn four_bytes(bytes: &[u8], offset: usize) -> Option<[u8; 4]> {
let end = offset.checked_add(4)?;
bytes.get(offset..end)?.try_into().ok()
}
fn truncated(line: usize) -> MeshError {
MeshError::Malformed {
line,
reason: "truncated binary STL triangle".to_string(),
}
}
fn from_ascii(bytes: &[u8]) -> Result<Mesh, MeshError> {
let text = core::str::from_utf8(bytes).map_err(|error| MeshError::Malformed {
line: line_at(bytes, error.valid_up_to()),
reason: "STL text is not valid UTF-8".to_string(),
})?;
let mut parser = Ascii::default();
for (index, line) in text.lines().enumerate() {
parser.line(line, index + 1)?;
}
parser.finish()
}
fn line_at(bytes: &[u8], offset: usize) -> usize {
bytes.get(..offset).map_or(1, |prefix| {
1 + prefix.iter().filter(|byte| **byte == b'\n').count()
})
}
/// State of the ASCII facet grammar.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum Stage {
/// Between facets.
#[default]
Idle,
/// After `facet normal`, before `outer loop`.
Facet,
/// Inside `outer loop`.
Loop,
/// After `endloop`, before `endfacet`.
Closed,
}
/// A small state machine over ASCII STL keywords.
#[derive(Default)]
struct Ascii {
welder: Welder,
indices: Vec<[u32; 3]>,
stage: Stage,
loop_vertices: Vec<u32>,
last_line: usize,
}
impl Ascii {
fn line(&mut self, text: &str, number: usize) -> Result<(), MeshError> {
self.last_line = number;
let mut words = text.split_whitespace();
let Some(keyword) = words.next() else {
return Ok(());
};
match keyword.to_ascii_lowercase().as_str() {
"solid" | "endsolid" => Ok(()),
"facet" => self.facet(words, number),
"outer" => self.outer(words, number),
"vertex" => self.vertex(words, number),
"endloop" => self.end_loop(number),
"endfacet" => self.end_facet(number),
other => Err(malformed(
number,
format!("unexpected STL keyword `{other}`"),
)),
}
}
fn facet(&mut self, mut words: SplitWhitespace<'_>, number: usize) -> Result<(), MeshError> {
if self.stage != Stage::Idle {
return Err(malformed(number, "`facet` without `endfacet`"));
}
let kind = words.next().unwrap_or_default();
if !kind.eq_ignore_ascii_case("normal") {
return Err(malformed(number, "expected `facet normal`"));
}
for _ in 0..3 {
number_value(&mut words, number, "normal component")?;
}
self.stage = Stage::Facet;
Ok(())
}
fn outer(&mut self, mut words: SplitWhitespace<'_>, number: usize) -> Result<(), MeshError> {
let kind = words.next().unwrap_or_default();
if self.stage != Stage::Facet || !kind.eq_ignore_ascii_case("loop") {
return Err(malformed(number, "expected `outer loop` after `facet`"));
}
self.loop_vertices.clear();
self.stage = Stage::Loop;
Ok(())
}
fn vertex(&mut self, mut words: SplitWhitespace<'_>, number: usize) -> Result<(), MeshError> {
if self.stage != Stage::Loop {
return Err(malformed(number, "`vertex` outside `outer loop`"));
}
let x = number_value(&mut words, number, "vertex coordinate")?;
let y = number_value(&mut words, number, "vertex coordinate")?;
let z = number_value(&mut words, number, "vertex coordinate")?;
let index = self.welder.index(Vec3::new(x, y, z));
self.loop_vertices.push(index);
Ok(())
}
fn end_loop(&mut self, number: usize) -> Result<(), MeshError> {
if self.stage != Stage::Loop {
return Err(malformed(number, "`endloop` outside a loop"));
}
let corners: [u32; 3] = self.loop_vertices.as_slice().try_into().map_err(|_| {
malformed(
number,
"an STL facet must have exactly three vertices".to_string(),
)
})?;
self.indices.push(corners);
self.loop_vertices.clear();
self.stage = Stage::Closed;
Ok(())
}
fn end_facet(&mut self, number: usize) -> Result<(), MeshError> {
if self.stage != Stage::Closed {
return Err(malformed(number, "`endfacet` without a complete facet"));
}
self.stage = Stage::Idle;
Ok(())
}
fn finish(self) -> Result<Mesh, MeshError> {
if self.stage != Stage::Idle {
return Err(malformed(self.last_line, "unterminated STL facet"));
}
if self.indices.is_empty() {
return Err(MeshError::Empty);
}
Mesh::new(self.welder.positions, self.indices)
}
}
/// One floating-point token, with a line number for the error.
fn number_value(
words: &mut SplitWhitespace<'_>,
line: usize,
what: &str,
) -> Result<f64, MeshError> {
let Some(word) = words.next() else {
return Err(malformed(line, format!("missing {what}")));
};
word.parse()
.map_err(|_| malformed(line, format!("`{word}` is not a valid {what}")))
}
fn malformed(line: usize, reason: impl Into<String>) -> MeshError {
MeshError::Malformed {
line,
reason: reason.into(),
}
}
/// Interns vertices by the bit pattern of their coordinates.
#[derive(Default)]
struct Welder {
positions: Vec<Vec3>,
lookup: BTreeMap<(u64, u64, u64), u32>,
}
impl Welder {
fn index(&mut self, point: Vec3) -> u32 {
let key = (point.x.to_bits(), point.y.to_bits(), point.z.to_bits());
if let Some(&index) = self.lookup.get(&key) {
return index;
}
let index = self.positions.len() as u32;
self.positions.push(point);
self.lookup.insert(key, index);
index
}
}

View file

@ -0,0 +1,283 @@
use super::*;
use fabrilis_core::vec::Vec3;
fn close(actual: f64, expected: f64) -> bool {
(actual - expected).abs() <= 1e-9 * expected.abs().max(1.0)
}
fn cube_positions() -> Vec<Vec3> {
vec![
Vec3::new(0.0, 0.0, 0.0),
Vec3::new(1.0, 0.0, 0.0),
Vec3::new(1.0, 1.0, 0.0),
Vec3::new(0.0, 1.0, 0.0),
Vec3::new(0.0, 0.0, 1.0),
Vec3::new(1.0, 0.0, 1.0),
Vec3::new(1.0, 1.0, 1.0),
Vec3::new(0.0, 1.0, 1.0),
]
}
/// The unit cube with outward winding, two triangles per side.
const UNIT_CUBE: [[u32; 3]; 12] = [
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[2, 3, 7],
[2, 7, 6],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
];
fn cube_mesh() -> Mesh {
Mesh::new(cube_positions(), UNIT_CUBE.to_vec()).expect("the unit cube has in-range indices")
}
fn cube_triangles() -> Vec<[Vec3; 3]> {
cube_mesh().triangles().collect()
}
fn ascii_stl(triangles: &[[Vec3; 3]]) -> String {
let mut text = String::from("solid cube\n");
for [a, b, c] in triangles {
text.push_str(" facet normal 0 0 0\n outer loop\n");
for point in [a, b, c] {
text.push_str(&format!(
" vertex {} {} {}\n",
point.x, point.y, point.z
));
}
text.push_str(" endloop\n endfacet\n");
}
text.push_str("endsolid cube\n");
text
}
fn binary_stl(triangles: &[[Vec3; 3]]) -> Vec<u8> {
let mut bytes = vec![0u8; 80];
bytes.extend_from_slice(&(triangles.len() as u32).to_le_bytes());
for [a, b, c] in triangles {
for _ in 0..3 {
bytes.extend_from_slice(&0f32.to_le_bytes());
}
for point in [a, b, c] {
for value in [point.x, point.y, point.z] {
bytes.extend_from_slice(&(value as f32).to_le_bytes());
}
}
bytes.extend_from_slice(&0u16.to_le_bytes());
}
bytes
}
const OBJ_CUBE: &str = "\
v 0 0 0
v 1 0 0
v 1 1 0
v 0 1 0
v 0 0 1
v 1 0 1
v 1 1 1
v 0 1 1
f 1 4 3 2
f 5 6 7 8
f 1 2 6 5
f 3 4 8 7
f 1 5 8 4
f 2 3 7 6
";
const OBJ_TETRA_RELATIVE: &str = "\
v 0 0 0
v 1 0 0
v 0 1 0
v 0 0 1
f -4 -2 -3
f -4 -3 -1
f -3 -2 -1
f -4 -1 -2
";
#[test]
fn ascii_stl_cube_validates_and_welds_vertices() {
let text = ascii_stl(&cube_triangles());
let mesh = from_stl(text.as_bytes()).expect("the ASCII cube imports");
assert_eq!(mesh.positions.len(), 8, "36 facet vertices weld into 8");
assert_eq!(mesh.triangles().count(), 12);
let report = mesh.validate().expect("the cube is watertight");
assert_eq!(report.vertices, 8);
assert_eq!(report.triangles, 12);
assert_eq!(report.degenerate, 0);
assert!(close(report.volume.get(), 1.0), "volume {report:?}");
assert!(close(mesh.area(), 6.0), "area {}", mesh.area());
}
#[test]
fn binary_stl_cube_matches_the_ascii_result() {
let bytes = binary_stl(&cube_triangles());
assert_eq!(bytes.len(), 84 + 50 * 12);
let mesh = from_stl(&bytes).expect("the binary cube imports");
assert_eq!(mesh.positions.len(), 8);
assert_eq!(mesh.triangles().count(), 12);
let report = mesh.validate().expect("the cube is watertight");
assert!(close(report.volume.get(), 1.0), "volume {report:?}");
assert!(close(mesh.area(), 6.0), "area {}", mesh.area());
}
#[test]
fn obj_quad_faces_are_fan_triangulated() {
let mesh = from_obj(OBJ_CUBE).expect("the OBJ cube imports");
assert_eq!(mesh.positions.len(), 8);
assert_eq!(
mesh.triangles().count(),
12,
"six quads become 12 triangles"
);
let report = mesh.validate().expect("the cube is watertight");
assert_eq!(report.vertices, 8);
assert_eq!(report.triangles, 12);
assert!(close(report.volume.get(), 1.0), "volume {report:?}");
assert!(close(mesh.area(), 6.0), "area {}", mesh.area());
}
#[test]
fn obj_negative_indices_resolve_relative_to_the_end() {
let mesh = from_obj(OBJ_TETRA_RELATIVE).expect("relative indices resolve");
assert_eq!(mesh.positions.len(), 4);
assert_eq!(mesh.triangles().count(), 4);
let report = mesh.validate().expect("the tetrahedron is watertight");
assert!(close(report.volume.get(), 1.0 / 6.0), "volume {report:?}");
}
#[test]
fn open_mesh_is_not_watertight() {
let indices = UNIT_CUBE.iter().take(11).copied().collect();
let mesh = Mesh::new(cube_positions(), indices).expect("indices are in range");
let error = mesh
.validate()
.expect_err("a missing triangle opens the surface");
assert!(
matches!(
error,
MeshError::NotWatertight {
undirected_edges: 3
}
),
"unexpected error {error:?}"
);
}
#[test]
fn reversed_triangle_breaks_the_winding() {
let mut indices = UNIT_CUBE.to_vec();
if let Some(last) = indices.last_mut() {
*last = [1, 5, 6];
}
let mesh = Mesh::new(cube_positions(), indices).expect("indices are in range");
let error = mesh
.validate()
.expect_err("one reversed triangle breaks winding");
assert!(
matches!(error, MeshError::InconsistentWinding { .. }),
"unexpected error {error:?}"
);
}
#[test]
fn fully_reversed_cube_is_inverted() {
let indices = UNIT_CUBE.iter().map(|&[a, b, c]| [a, c, b]).collect();
let mesh = Mesh::new(cube_positions(), indices).expect("indices are in range");
match mesh
.validate()
.expect_err("inward winding has negative volume")
{
MeshError::Inverted { volume } => assert!(close(volume, -1.0), "volume {volume}"),
other => panic!("expected Inverted, got {other:?}"),
}
}
#[test]
fn out_of_range_index_is_rejected() {
let error = Mesh::new(vec![Vec3::ZERO], vec![[0, 1, 2]]).expect_err("one vertex is not enough");
assert_eq!(error, MeshError::BadIndex { triangle: 0 });
let text = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 4\n";
let error = from_obj(text).expect_err("the face names a missing vertex");
assert_eq!(error, MeshError::BadIndex { triangle: 0 });
}
#[test]
fn empty_input_is_rejected() {
assert!(matches!(from_obj(""), Err(MeshError::Empty)));
assert!(matches!(
from_obj("# only a comment\n"),
Err(MeshError::Empty)
));
assert!(matches!(from_stl(b""), Err(MeshError::Empty)));
}
#[test]
fn scaled_converts_millimetres_to_metres() {
let millimetres = cube_mesh().scaled(1000.0);
let triangles: Vec<_> = millimetres.triangles().collect();
let imported = from_stl(&binary_stl(&triangles)).expect("the millimetre cube imports");
let cubic_millimetres = imported.signed_volume().expect("closed mesh");
assert!(
close(cubic_millimetres, 1.0e9),
"volume {cubic_millimetres}"
);
let metres = imported.scaled(0.001);
assert_eq!(metres.indices.len(), 12);
let report = metres.validate().expect("the metre cube is valid");
assert!(close(report.volume.get(), 1.0), "volume {report:?}");
}
#[test]
fn degenerate_triangle_is_rejected() {
let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y];
let mesh = Mesh::new(positions, vec![[0, 0, 1]]).expect("indices are in range");
assert_eq!(
mesh.validate().expect_err("a repeated corner has no area"),
MeshError::Degenerate { triangle: 0 }
);
}
#[test]
fn non_finite_vertex_is_rejected() {
let positions = vec![Vec3::new(f64::NAN, 0.0, 0.0), Vec3::Y, Vec3::Z];
let mesh = Mesh::new(positions, vec![[0, 1, 2]]).expect("indices are in range");
assert_eq!(
mesh.validate().expect_err("NaN is not a coordinate"),
MeshError::NonFinite { triangle: 0 }
);
}
#[test]
fn malformed_obj_face_reports_its_line() {
let text = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 nope\n";
let error = from_obj(text).expect_err("the face corner is not a number");
assert!(
matches!(error, MeshError::Malformed { line: 4, .. }),
"unexpected error {error:?}"
);
}
#[test]
fn malformed_stl_line_reports_its_line() {
let text = "solid cube\n nonsense here\nendsolid cube\n";
let error = from_stl(text.as_bytes()).expect_err("the keyword is unknown");
assert!(
matches!(error, MeshError::Malformed { line: 2, .. }),
"unexpected error {error:?}"
);
}

View file

@ -0,0 +1,114 @@
//! Mass properties of a part and of a whole design.
//!
//! A part's result already has its centre of mass and inertia in the design frame:
//! the mesh is measured in its own axes and then moved by the pose. Aggregating
//! parts therefore needs only the parallel-axis theorem, with `d` measured from
//! the assembly centre of mass.
use fabrilis_core::units::{CubicMeters, Kilograms};
use fabrilis_core::vec::{Mat3, Vec3};
use fabrilis_materials::db::MaterialDb;
use fabrilis_materials::massprops::{MassProperties, from_triangles};
use fabrilis_storage::blob::BlobStore;
use super::{Design, Part, SceneError, load_mesh};
impl Part {
/// Mass, centre of mass and inertia of this part in the design frame.
///
/// The centre of mass is moved by the pose, and the inertia about the part's
/// centre of mass is rotated into design axes (`R I Rᵀ`).
pub fn mass(
&self,
materials: &MaterialDb,
store: &BlobStore,
) -> Result<MassProperties, SceneError> {
let transform = self.pose.to_transform().ok_or(SceneError::BadPose)?;
let mesh = load_mesh(store, self.mesh)?;
let material = materials
.get(&self.material)
.ok_or_else(|| SceneError::UnknownMaterial(self.material.clone()))?;
let triangles: Vec<[Vec3; 3]> = mesh.triangles().collect();
let local = from_triangles(&triangles, material.density).ok_or(SceneError::BadMass)?;
let rotation = transform.rotation.to_mat3();
Ok(MassProperties {
volume: local.volume,
mass: local.mass,
center_of_mass: transform.transform_point(local.center_of_mass),
inertia: rotation * local.inertia * rotation.transpose(),
})
}
}
impl Design {
/// Mass, centre of mass and inertia of the assembly.
///
/// Total mass is the sum of the parts, the centre of mass is mass-weighted,
/// and each part's inertia is shifted to the assembly centre with the
/// parallel-axis theorem. An empty design is an error, not a zero mass.
pub fn mass_properties(
&self,
materials: &MaterialDb,
store: &BlobStore,
) -> Result<MassProperties, SceneError> {
let parts: Vec<MassProperties> = self
.parts
.iter()
.map(|part| part.mass(materials, store))
.collect::<Result<_, SceneError>>()?;
if parts.is_empty() {
return Err(SceneError::EmptyDesign);
}
let total_mass: f64 = parts.iter().map(|part| part.mass.get()).sum();
let weighted = parts.iter().fold(Vec3::ZERO, |sum, part| {
sum + part.center_of_mass * part.mass.get()
});
let center_of_mass = weighted / total_mass;
if !total_mass.is_finite() || total_mass <= 0.0 || !center_of_mass.is_finite() {
return Err(SceneError::BadMass);
}
let mut inertia = Mat3::from_diagonal(Vec3::ZERO);
for part in &parts {
let offset = part.center_of_mass - center_of_mass;
inertia = sum_matrices(
inertia,
parallel_axis(part.inertia, part.mass.get(), offset),
);
}
let volume: f64 = parts.iter().map(|part| part.volume.get()).sum();
if !inertia_is_finite(inertia) || !volume.is_finite() {
return Err(SceneError::BadMass);
}
Ok(MassProperties {
volume: CubicMeters::new(volume),
mass: Kilograms::new(total_mass),
center_of_mass,
inertia,
})
}
}
/// Adds `m (|d|² I − d dᵀ)` to `inertia`.
fn parallel_axis(inertia: Mat3, mass: f64, offset: Vec3) -> Mat3 {
let (x, y, z) = (offset.x, offset.y, offset.z);
let square = offset.length_squared();
let shift = Mat3::from_cols(
Vec3::new(mass * (square - x * x), -mass * x * y, -mass * x * z),
Vec3::new(-mass * y * x, mass * (square - y * y), -mass * y * z),
Vec3::new(-mass * z * x, -mass * z * y, mass * (square - z * z)),
);
sum_matrices(inertia, shift)
}
fn sum_matrices(left: Mat3, right: Mat3) -> Mat3 {
let [lx, ly, lz] = left.cols();
let [rx, ry, rz] = right.cols();
Mat3::from_cols(lx + rx, ly + ry, lz + rz)
}
fn inertia_is_finite(inertia: Mat3) -> bool {
inertia
.cols()
.iter()
.all(|column| column.x.is_finite() && column.y.is_finite() && column.z.is_finite())
}

View file

@ -0,0 +1,84 @@
//! Mesh blobs: the RON form stored in a content-addressed blob store.
//!
//! The mesh is stored once per distinct geometry; parts reference it by
//! [`BlobHash`](fabrilis_storage::blob::BlobHash) (docs/STORAGE.md).
use fabrilis_core::vec::Vec3;
use fabrilis_storage::blob::{BlobHash, BlobStore};
use serde::{Deserialize, Serialize};
use crate::import::{Mesh, from_stl};
use super::{Part, Pose, SceneError};
/// The on-disk mesh form: arrays instead of core math types, which have no serde.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct StoredMesh {
positions: Vec<[f64; 3]>,
indices: Vec<[u32; 3]>,
}
/// Serialises the mesh as RON and stores it, returning its content hash.
///
/// Storing identical geometry twice is a no-op: the hash, and therefore the file,
/// is the same.
pub fn store_mesh(store: &mut BlobStore, mesh: &Mesh) -> Result<BlobHash, SceneError> {
let stored = StoredMesh {
positions: mesh
.positions
.iter()
.map(|point| [point.x, point.y, point.z])
.collect(),
indices: mesh.indices.clone(),
};
let text = ron::ser::to_string_pretty(&stored, ron::ser::PrettyConfig::default())
.map_err(|error| SceneError::MeshBlob(error.to_string()))?;
Ok(store.put(text.as_bytes())?)
}
/// Reads a stored mesh and validates it as a closed, outward-wound surface.
pub fn load_mesh(store: &BlobStore, hash: BlobHash) -> Result<Mesh, SceneError> {
let bytes = store.get(hash)?;
let text =
core::str::from_utf8(&bytes).map_err(|error| SceneError::MeshBlob(error.to_string()))?;
let stored: StoredMesh =
ron::from_str(text).map_err(|error| SceneError::MeshBlob(error.to_string()))?;
let positions = stored
.positions
.iter()
.map(|&[x, y, z]| Vec3::new(x, y, z))
.collect();
let mesh = Mesh::new(positions, stored.indices)?;
mesh.validate()?;
Ok(mesh)
}
/// Imports an STL part: parse, scale to metres, validate, then store the mesh.
///
/// STL carries neither units nor axes, so `unit_scale` is the source unit factor
/// (`0.001` for millimetres, `1.0` for metres); see docs/COORDINATES.md.
#[allow(
clippy::too_many_arguments,
reason = "the STL import inputs are independent scalars; a group struct would obscure the call site"
)]
pub fn add_part_from_stl(
store: &mut BlobStore,
name: &str,
stl: &[u8],
unit_scale: f64,
material: &str,
pose: Pose,
) -> Result<Part, SceneError> {
if !unit_scale.is_finite() || unit_scale <= 0.0 {
return Err(SceneError::BadScale(unit_scale));
}
let mesh = from_stl(stl)?.scaled(unit_scale);
mesh.validate()?;
let hash = store_mesh(store, &mesh)?;
Ok(Part {
name: name.to_string(),
mesh: hash,
material: material.to_string(),
pose,
})
}

View file

@ -1 +1,193 @@
//! fabrilis-scene :: model - stub (see docs/ARCHITECTURE.md)
//! Design model: named rigid parts and their mass properties.
//!
//! A part references its mesh by content hash, so one copy of a mesh serves every
//! part that uses it (docs/STORAGE.md). Poses are plain arrays because the core
//! math types intentionally do not depend on serde; conversion to [`Transform`]
//! normalises the quaternion and rejects degenerate input.
mod mass;
mod mesh;
mod persist;
use core::fmt;
use std::io;
use fabrilis_core::vec::{Quat, Transform, Vec3};
use fabrilis_storage::blob::BlobHash;
use fabrilis_storage::format::FormatError;
use serde::{Deserialize, Serialize};
use crate::import::MeshError;
pub use mesh::{add_part_from_stl, load_mesh, store_mesh};
pub use persist::DESIGN_FILE;
/// A serialisable rigid pose: position in metres and a `wxyz` quaternion.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Pose {
/// Position, m.
pub position: [f64; 3],
/// Rotation as a `wxyz` quaternion; not necessarily unit length.
pub rotation: [f64; 4],
}
impl Default for Pose {
fn default() -> Self {
Self {
position: [0.0; 3],
rotation: [1.0, 0.0, 0.0, 0.0],
}
}
}
impl Pose {
/// The corresponding [`Transform`], or `None` for a non-finite position or a
/// zero/non-finite quaternion.
#[must_use]
pub fn to_transform(self) -> Option<Transform> {
let position = Vec3::new(self.position[0], self.position[1], self.position[2]);
if !position.is_finite() {
return None;
}
let rotation = Quat::new(
self.rotation[0],
self.rotation[1],
self.rotation[2],
self.rotation[3],
)
.normalize()?;
Some(Transform::new(position, rotation))
}
/// The pose that places a transform, keeping its quaternion as given.
#[must_use]
pub fn from_transform(transform: Transform) -> Self {
Self {
position: [
transform.position.x,
transform.position.y,
transform.position.z,
],
rotation: [
transform.rotation.w,
transform.rotation.x,
transform.rotation.y,
transform.rotation.z,
],
}
}
}
/// One rigid part: a mesh, a material and a pose in the design's frame.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Part {
/// Name, unique within the design by convention.
pub name: String,
/// Content hash of the stored mesh.
pub mesh: BlobHash,
/// Material name in a [`fabrilis_materials::db::MaterialDb`].
pub material: String,
/// Placement of the part's mesh in the design frame.
pub pose: Pose,
}
/// A named collection of parts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Design {
/// Design name.
pub name: String,
/// Parts in insertion order.
pub parts: Vec<Part>,
}
impl Design {
/// An empty design.
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
parts: Vec::new(),
}
}
/// Appends a part.
pub fn push(&mut self, part: Part) {
self.parts.push(part);
}
}
/// Why a design, a mesh blob or a mass computation failed.
#[derive(Debug)]
pub enum SceneError {
/// Reading or writing a project file failed.
Io(io::Error),
/// The versioned scene envelope is invalid.
Format(FormatError),
/// The mesh itself is invalid before it is stored.
Mesh(MeshError),
/// A stored mesh blob cannot be decoded.
MeshBlob(String),
/// The material name is not in the database.
UnknownMaterial(String),
/// The pose has a non-finite position or a zero/non-finite rotation.
BadPose,
/// The unit scale must be finite and positive.
BadScale(f64),
/// There is nothing to aggregate.
EmptyDesign,
/// Aggregated mass properties are not finite.
BadMass,
}
impl fmt::Display for SceneError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(error) => write!(formatter, "project I/O failed: {error}"),
Self::Format(error) => write!(formatter, "scene format error: {error}"),
Self::Mesh(error) => write!(formatter, "mesh error: {error}"),
Self::MeshBlob(reason) => write!(formatter, "stored mesh is invalid: {reason}"),
Self::UnknownMaterial(name) => write!(formatter, "unknown material `{name}`"),
Self::BadPose => write!(
formatter,
"pose has a non-finite position or a zero/non-finite rotation"
),
Self::BadScale(scale) => {
write!(formatter, "unit scale {scale} must be finite and positive")
}
Self::EmptyDesign => write!(formatter, "design has no parts"),
Self::BadMass => write!(formatter, "aggregated mass properties are not finite"),
}
}
}
impl std::error::Error for SceneError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) => Some(error),
Self::Format(error) => Some(error),
Self::Mesh(error) => Some(error),
_ => None,
}
}
}
impl From<io::Error> for SceneError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
impl From<FormatError> for SceneError {
fn from(error: FormatError) -> Self {
Self::Format(error)
}
}
impl From<MeshError> for SceneError {
fn from(error: MeshError) -> Self {
Self::Mesh(error)
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,76 @@
//! Reading and writing `scene.ron` in a project folder.
//!
//! Version 0 of the scene format had no per-part `pose`; the migration below fills
//! in the identity pose, so an old cart opens without edits.
use std::collections::BTreeMap;
use fabrilis_storage::format::{from_ron_with_migrations, to_ron};
use fabrilis_storage::migrate::{MigrateError, Migration};
use fabrilis_storage::project::Project;
use super::{Design, Pose, SceneError};
/// File name of the design inside a project.
pub const DESIGN_FILE: &str = "scene.ron";
impl Design {
/// Writes the design as a versioned RON envelope in the project.
pub fn save(&self, project: &Project) -> Result<(), SceneError> {
let text = to_ron(self)?;
project.write_text(DESIGN_FILE, &text)?;
Ok(())
}
/// Reads the design, migrating older scene versions forward.
pub fn load(project: &Project) -> Result<Self, SceneError> {
let text = project.read_text(DESIGN_FILE)?;
Ok(from_ron_with_migrations(&text, &migrations())?)
}
}
fn migrations() -> BTreeMap<u32, Migration> {
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, add_identity_pose as Migration);
steps
}
/// Version 0 → 1: every part gains the identity pose.
fn add_identity_pose(mut value: ron::Value) -> Result<ron::Value, MigrateError> {
let ron::Value::Map(ref mut design) = value else {
return Err(MigrateError::step(0, "scene payload is not a map"));
};
let Some(parts) = design.get_mut(&ron::Value::from("parts")) else {
return Err(MigrateError::step(0, "scene payload has no parts"));
};
let ron::Value::Seq(parts) = parts else {
return Err(MigrateError::step(0, "scene parts are not a list"));
};
for part in parts.iter_mut() {
let ron::Value::Map(part) = part else {
return Err(MigrateError::step(0, "a scene part is not a map"));
};
if part.get(&ron::Value::from("pose")).is_none() {
let _previous = part.insert("pose", pose_value(Pose::default()));
}
}
Ok(value)
}
/// The RON form of a pose, for migrations over [`ron::Value`].
fn pose_value(pose: Pose) -> ron::Value {
let position = pose
.position
.iter()
.map(|&value| ron::Value::from(value))
.collect();
let rotation = pose
.rotation
.iter()
.map(|&value| ron::Value::from(value))
.collect();
let mut map = ron::Map::new();
let _previous = map.insert("position", ron::Value::Seq(position));
let _previous = map.insert("rotation", ron::Value::Seq(rotation));
ron::Value::Map(map)
}

View file

@ -0,0 +1,223 @@
//! Pose conversion, mesh blobs and per-part mass properties.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use fabrilis_core::vec::{Transform, Vec3};
use fabrilis_materials::db::MaterialDb;
use fabrilis_storage::blob::BlobStore;
use super::{Design, Pose, SceneError, add_part_from_stl, load_mesh, store_mesh};
use crate::import::from_stl;
/// A directory removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-scene-{label}-{}-{counter}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self { path }
}
fn blobs(&self) -> BlobStore {
BlobStore::new(self.path.join("blobs"))
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// A box with the given full extents, centred at the origin, as an ASCII STL.
fn box_stl(x: f64, y: f64, z: f64) -> String {
let (hx, hy, hz) = (x * 0.5, y * 0.5, z * 0.5);
let vertices = [
(-hx, -hy, -hz),
(hx, -hy, -hz),
(hx, hy, -hz),
(-hx, hy, -hz),
(-hx, -hy, hz),
(hx, -hy, hz),
(hx, hy, hz),
(-hx, hy, hz),
];
let triangles = [
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[3, 7, 6],
[3, 6, 2],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
];
let mut text = String::from("solid box\n");
for triangle in triangles {
text.push_str("facet normal 0 0 0\nouter loop\n");
for index in triangle {
let (vx, vy, vz) = vertices[index];
text.push_str(&format!("vertex {vx} {vy} {vz}\n"));
}
text.push_str("endloop\nendfacet\n");
}
text.push_str("endsolid box\n");
text
}
#[test]
fn pose_identity_round_trips() {
let pose = Pose::default();
let transform = pose.to_transform().unwrap();
assert_eq!(transform, Transform::IDENTITY);
assert_eq!(Pose::from_transform(transform), pose);
}
#[test]
fn pose_normalises_the_quaternion() {
let pose = Pose {
position: [1.0, 2.0, 3.0],
rotation: [2.0, 0.0, 0.0, 0.0],
};
let transform = pose.to_transform().unwrap();
assert_eq!(transform.position, Vec3::new(1.0, 2.0, 3.0));
assert!((transform.rotation.norm_squared() - 1.0).abs() < 1e-12);
assert!((transform.rotation.w - 1.0).abs() < 1e-12);
}
#[test]
fn pose_rejects_degenerate_values() {
let zero_rotation = Pose {
position: [0.0; 3],
rotation: [0.0; 4],
};
assert!(zero_rotation.to_transform().is_none());
let non_finite = Pose {
position: [f64::NAN, 0.0, 0.0],
rotation: [1.0, 0.0, 0.0, 0.0],
};
assert!(non_finite.to_transform().is_none());
}
#[test]
fn cube_mass_matches_the_density() {
let temp = TempDir::new("cube-mass");
let mut store = temp.blobs();
let side = 0.1;
let stl = box_stl(side, side, side);
let part = add_part_from_stl(
&mut store,
"cube",
stl.as_bytes(),
1.0,
"steel",
Pose::default(),
)
.unwrap();
let properties = part.mass(&MaterialDb::with_builtins(), &store).unwrap();
let expected = 7_850.0 * side * side * side;
assert!((properties.mass.get() - expected).abs() / expected < 1e-5);
assert!(properties.center_of_mass.length() < 1e-12);
let diagonal = expected * side * side / 6.0;
assert!((properties.inertia.cols()[0].x - diagonal).abs() / diagonal < 1e-5);
}
#[test]
fn pose_translation_moves_the_center_of_mass() {
let temp = TempDir::new("pose-mass");
let mut store = temp.blobs();
let stl = box_stl(0.1, 0.1, 0.1);
let pose = Pose {
position: [1.0, -2.0, 3.5],
rotation: [1.0, 0.0, 0.0, 0.0],
};
let part = add_part_from_stl(&mut store, "cube", stl.as_bytes(), 1.0, "steel", pose).unwrap();
let properties = part.mass(&MaterialDb::with_builtins(), &store).unwrap();
assert!((properties.center_of_mass.x - 1.0).abs() < 1e-12);
assert!((properties.center_of_mass.y + 2.0).abs() < 1e-12);
assert!((properties.center_of_mass.z - 3.5).abs() < 1e-12);
}
#[test]
fn stored_meshes_are_content_addressed() {
let temp = TempDir::new("mesh-blob");
let mut store = temp.blobs();
let mesh = from_stl(box_stl(0.2, 0.3, 0.4).as_bytes()).unwrap();
let first = store_mesh(&mut store, &mesh).unwrap();
let second = store_mesh(&mut store, &mesh).unwrap();
assert_eq!(first, second);
let files = std::fs::read_dir(store.root()).unwrap().count();
assert_eq!(files, 1);
assert_eq!(load_mesh(&store, first).unwrap(), mesh);
}
#[test]
fn an_unknown_material_is_reported() {
let temp = TempDir::new("material");
let mut store = temp.blobs();
let stl = box_stl(0.1, 0.1, 0.1);
let part = add_part_from_stl(
&mut store,
"cube",
stl.as_bytes(),
1.0,
"unobtainium",
Pose::default(),
)
.unwrap();
let error = part.mass(&MaterialDb::new(), &store).unwrap_err();
assert!(matches!(error, SceneError::UnknownMaterial(name) if name == "unobtainium"));
}
#[test]
fn two_cubes_aggregate_by_the_parallel_axis_theorem() {
let temp = TempDir::new("aggregate");
let mut store = temp.blobs();
let side = 0.1;
let mass = 7_850.0 * side * side * side;
let stl = box_stl(side, side, side);
let offset = 0.2;
let mut design = Design::new("pair");
for (name, x) in [("left", -offset), ("right", offset)] {
let pose = Pose {
position: [x, 0.0, 0.0],
rotation: [1.0, 0.0, 0.0, 0.0],
};
design
.push(add_part_from_stl(&mut store, name, stl.as_bytes(), 1.0, "steel", pose).unwrap());
}
let properties = design
.mass_properties(&MaterialDb::with_builtins(), &store)
.unwrap();
let expected_mass = 2.0 * mass;
assert!((properties.mass.get() - expected_mass).abs() / expected_mass < 1e-5);
assert!(properties.center_of_mass.length() < 1e-12);
let own = mass * side * side / 6.0;
let expected_yy = 2.0 * (own + mass * offset * offset);
assert!((properties.inertia.cols()[0].x - 2.0 * own).abs() / (2.0 * own) < 1e-5);
assert!((properties.inertia.cols()[1].y - expected_yy).abs() / expected_yy < 1e-5);
}

View file

@ -0,0 +1,87 @@
//! M3 seam: an STL part is validated as a closed mesh and its mass is computed from
//! the material density.
#![allow(
clippy::unwrap_used,
reason = "test helper: a failure should abort the test"
)]
use fabrilis_core::units::KilogramsPerCubicMeter;
use fabrilis_materials::db::MaterialDb;
use fabrilis_materials::massprops::from_triangles;
use fabrilis_scene::import::{Mesh, from_stl};
/// A cube of the given side, centred at the origin, as an ASCII STL.
fn cube_stl(side: f64) -> String {
let h = side * 0.5;
let vertices = [
(-h, -h, -h),
(h, -h, -h),
(h, h, -h),
(-h, h, -h),
(-h, -h, h),
(h, -h, h),
(h, h, h),
(-h, h, h),
];
let triangles = [
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[3, 7, 6],
[3, 6, 2],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
];
let mut text = String::from("solid cube\n");
for triangle in triangles {
text.push_str(" facet normal 0 0 0\n outer loop\n");
for index in triangle {
let (x, y, z) = vertices[index];
text.push_str(&format!(" vertex {x} {y} {z}\n"));
}
text.push_str(" endloop\n endfacet\n");
}
text.push_str("endsolid cube\n");
text
}
#[test]
fn stl_cube_mass_matches_the_analytic_value() {
let mesh = from_stl(cube_stl(1.0).as_bytes()).expect("the cube parses");
let report = mesh.validate().expect("the cube is closed");
assert!((report.volume.get() - 1.0).abs() < 1e-12);
let steel = MaterialDb::with_builtins();
let density = steel.get("steel").expect("steel is built in").density;
let mass = from_triangles(&mesh.triangles().collect::<Vec<_>>(), density)
.expect("a closed cube has mass properties");
assert!((mass.mass.get() - 7_850.0).abs() < 1.0);
assert!(mass.center_of_mass.length() < 1e-12);
let inertia = mass.mass.get() / 6.0;
assert!((mass.inertia.cols()[0].x - inertia).abs() < 1e-6);
}
#[test]
fn millimetre_stl_scaled_to_metres_keeps_the_mass() {
let mesh = from_stl(cube_stl(1_000.0).as_bytes())
.expect("the cube parses")
.scaled(0.001);
let report = mesh.validate().expect("the cube is closed");
assert!((report.volume.get() - 1.0).abs() < 1e-9);
let density = KilogramsPerCubicMeter::new(2_700.0);
let mass = from_triangles(&mesh.triangles().collect::<Vec<_>>(), density)
.expect("a closed cube has mass properties");
assert!((mass.mass.get() - 2_700.0).abs() < 1.0);
}
#[test]
fn an_open_mesh_is_rejected_before_mass_is_computed() {
let mut mesh: Mesh = from_stl(cube_stl(1.0).as_bytes()).expect("the cube parses");
mesh.indices.pop();
assert!(mesh.validate().is_err());
}

View file

@ -0,0 +1,229 @@
//! M3 seam: an STL cart is saved, loaded back and its mass is compared with the
//! analytic value.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use fabrilis_materials::db::MaterialDb;
use fabrilis_scene::model::{DESIGN_FILE, Design, Pose, add_part_from_stl};
use fabrilis_storage::project::Project;
/// A directory removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-persistence-{label}-{}-{counter}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// A box with the given full extents, centred at the origin, as an ASCII STL.
fn box_stl(x: f64, y: f64, z: f64) -> String {
let (hx, hy, hz) = (x * 0.5, y * 0.5, z * 0.5);
let vertices = [
(-hx, -hy, -hz),
(hx, -hy, -hz),
(hx, hy, -hz),
(-hx, hy, -hz),
(-hx, -hy, hz),
(hx, -hy, hz),
(hx, hy, hz),
(-hx, hy, hz),
];
let triangles = [
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[3, 7, 6],
[3, 6, 2],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
];
let mut text = String::from("solid box\n");
for triangle in triangles {
text.push_str("facet normal 0 0 0\nouter loop\n");
for index in triangle {
let (vx, vy, vz) = vertices[index];
text.push_str(&format!("vertex {vx} {vy} {vz}\n"));
}
text.push_str("endloop\nendfacet\n");
}
text.push_str("endsolid box\n");
text
}
fn pose_at(x: f64, y: f64, z: f64) -> Pose {
Pose {
position: [x, y, z],
rotation: [1.0, 0.0, 0.0, 0.0],
}
}
#[test]
fn a_cart_round_trips_and_its_mass_matches_the_analytic_value() {
let temp = TempDir::new("cart");
let project = Project::create(&temp.path).unwrap();
let mut blobs = project.blobs();
let mut design = Design::new("cart");
let body = box_stl(0.4, 0.2, 0.1);
design.push(
add_part_from_stl(
&mut blobs,
"body",
body.as_bytes(),
1.0,
"steel",
pose_at(0.0, 0.0, 0.0),
)
.unwrap(),
);
let wheel = box_stl(0.1, 0.1, 0.1);
for (name, y) in [("left", 0.15), ("right", -0.15)] {
design.push(
add_part_from_stl(
&mut blobs,
name,
wheel.as_bytes(),
1.0,
"aluminium",
pose_at(0.0, y, -0.05),
)
.unwrap(),
);
}
design.save(&project).unwrap();
let text = project.read_text(DESIGN_FILE).unwrap();
assert!(text.contains("format_version: 1"));
assert!(text.contains("payload:"));
assert!(project.path(DESIGN_FILE).is_file());
let loaded = Design::load(&project).unwrap();
assert_eq!(loaded.name, design.name);
assert_eq!(loaded.parts, design.parts);
let materials = MaterialDb::with_builtins();
let properties = loaded.mass_properties(&materials, &blobs).unwrap();
let expected = 7_850.0 * 0.4 * 0.2 * 0.1 + 2.0 * 2_700.0 * 0.1 * 0.1 * 0.1;
let error = (properties.mass.get() - expected).abs() / expected;
assert!(error < 0.01, "mass error {error} exceeds 1 %");
assert!(properties.center_of_mass.is_finite());
assert!(
properties
.inertia
.cols()
.iter()
.all(|column| column.is_finite())
);
assert!(properties.inertia.determinant() > 0.0);
}
#[test]
fn identical_meshes_share_one_blob_and_one_table_entry() {
let temp = TempDir::new("dedup");
let project = Project::create(&temp.path).unwrap();
let mut blobs = project.blobs();
let wheel = box_stl(0.1, 0.1, 0.1);
let first = add_part_from_stl(
&mut blobs,
"left",
wheel.as_bytes(),
1.0,
"aluminium",
Pose::default(),
)
.unwrap();
let second = add_part_from_stl(
&mut blobs,
"right",
wheel.as_bytes(),
1.0,
"aluminium",
Pose::default(),
)
.unwrap();
assert_eq!(first.mesh, second.mesh);
let files = std::fs::read_dir(project.path("blobs")).unwrap().count();
assert_eq!(files, 1);
}
#[test]
fn a_version_zero_scene_is_migrated_to_identity_poses() {
let temp = TempDir::new("migrate");
let project = Project::create(&temp.path).unwrap();
let version_zero = "\
(
format_version: 0,
payload: (
name: \"cart\",
parts: [
(
name: \"body\",
mesh: \"0123456789abcdef\",
material: \"steel\",
),
],
),
)
";
project.write_text(DESIGN_FILE, version_zero).unwrap();
let design = Design::load(&project).unwrap();
assert_eq!(design.parts.len(), 1);
assert_eq!(design.parts[0].pose, Pose::default());
design.save(&project).unwrap();
let upgraded = project.read_text(DESIGN_FILE).unwrap();
assert!(upgraded.contains("format_version: 1"));
assert_eq!(Design::load(&project).unwrap().parts, design.parts);
}
#[test]
fn a_newer_scene_version_is_rejected() {
let temp = TempDir::new("future");
let project = Project::create(&temp.path).unwrap();
let version_two = "(format_version: 2, payload: (name: \"cart\", parts: []))";
project.write_text(DESIGN_FILE, version_two).unwrap();
assert!(Design::load(&project).is_err());
}
#[test]
fn a_missing_scene_file_is_a_not_found_error() {
let temp = TempDir::new("missing");
let project = Project::create(&temp.path).unwrap();
let error = Design::load(&project).unwrap_err();
let message = error.to_string();
assert!(
message.contains("No such file") || message.contains("os error 2"),
"{message}"
);
}

View file

@ -0,0 +1,35 @@
//! A fixed-length FIFO that models the transport delay of a sensor bus.
use std::collections::VecDeque;
/// A FIFO of `steps` samples.
///
/// The queue starts filled with `initial`, so the first `steps` calls to
/// [`Delay::push`] report that value while the queue drains.
#[derive(Debug, Clone, PartialEq)]
pub struct Delay<T> {
initial: T,
queue: VecDeque<T>,
}
impl<T: Clone> Delay<T> {
/// A delay of `steps` samples, reporting `initial` until the queue fills.
pub fn new(steps: usize, initial: T) -> Self {
Self {
initial: initial.clone(),
queue: core::iter::repeat_n(initial, steps).collect(),
}
}
/// Pushes a new sample and returns the one measured `steps` samples ago, or the
/// new sample itself when the delay is zero.
pub fn push(&mut self, value: T) -> T {
if self.queue.is_empty() {
return value;
}
self.queue.push_back(value);
self.queue
.pop_front()
.unwrap_or_else(|| self.initial.clone())
}
}

View file

@ -1 +1,139 @@
//! fabrilis-sensors :: encoder - stub (see docs/ARCHITECTURE.md)
//! Quadrature encoder model: quantization, bias, noise and transport delay.
//!
//! A full revolution is split into `2^resolution_bits` counts. The sensor quantizes
//! the true angle, adds a constant bias and Gaussian noise, and reports the result
//! through a FIFO delay, so a controller sees the past, not the present.
use fabrilis_core::math;
use fabrilis_core::rng::Rng;
use fabrilis_core::units::Radians;
use crate::delay::Delay;
use crate::noise::Noise;
/// One full revolution, rad.
const FULL_TURN: f64 = math::TAU;
/// Smallest accepted `resolution_bits`; one bit still gives two counts per revolution.
const MIN_BITS: u8 = 1;
/// Largest accepted `resolution_bits`; `2^31` counts per revolution fits `u32` and `i64`.
const MAX_BITS: u8 = 31;
/// Encoder parameters.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EncoderConfig {
/// Counts per revolution is `2^resolution_bits`; must be in `1..=31`.
pub resolution_bits: u8,
/// Standard deviation of the Gaussian noise, rad.
pub noise_sigma: f64,
/// Constant measurement offset, rad.
pub bias: f64,
/// Transport delay in samples.
pub delay_steps: usize,
}
impl Default for EncoderConfig {
/// A 12-bit encoder without noise, bias or delay.
fn default() -> Self {
Self {
resolution_bits: 12,
noise_sigma: 0.0,
bias: 0.0,
delay_steps: 0,
}
}
}
/// Why an [`Encoder`] could not be created.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EncoderError {
/// The bit count is outside `1..=31`, so the count grid is unusable.
ResolutionOutOfRange(u8),
}
impl core::fmt::Display for EncoderError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::ResolutionOutOfRange(bits) => write!(
f,
"encoder resolution of {bits} bits is outside {MIN_BITS}..={MAX_BITS}"
),
}
}
}
impl std::error::Error for EncoderError {}
/// An angle encoder with quantization, noise, bias and delay.
#[derive(Debug, Clone)]
pub struct Encoder {
resolution_bits: u8,
counts: u64,
noise: Noise,
bias: f64,
delay: Delay<Radians>,
rng: Rng,
}
impl Encoder {
/// Creates an encoder, or reports an unusable resolution.
pub fn new(config: EncoderConfig, seed: u64) -> Result<Self, EncoderError> {
let bits = config.resolution_bits;
if !(MIN_BITS..=MAX_BITS).contains(&bits) {
return Err(EncoderError::ResolutionOutOfRange(bits));
}
Ok(Self {
resolution_bits: bits,
counts: 1u64 << bits,
noise: Noise::new(config.noise_sigma),
bias: config.bias,
delay: Delay::new(config.delay_steps, Radians::ZERO),
rng: Rng::new(seed),
})
}
/// Declared resolution in bits.
#[inline]
#[must_use]
pub fn resolution_bits(&self) -> u8 {
self.resolution_bits
}
/// Counts per full revolution, `2^resolution_bits`.
#[inline]
#[must_use]
pub fn counts_per_revolution(&self) -> u64 {
self.counts
}
/// Measures `true_angle`.
///
/// The angle is quantized to the nearest count, ties round up (towards `+∞`), and
/// the count is wrapped modulo `2^resolution_bits`, so the quantized angle always
/// lies in `[0, TAU)`. Bias and noise are added after quantization, then the value
/// goes through the delay FIFO. Non-finite input is measured as `0` rad.
///
/// Until the FIFO fills, the reported value is the initial `0` rad.
pub fn sample(&mut self, true_angle: Radians) -> Radians {
let quantized = self.quantize(true_angle);
let biased = quantized.get() + self.bias;
let measured = Radians(self.noise.apply(biased, &mut self.rng));
self.delay.push(measured)
}
fn quantize(&self, angle: Radians) -> Radians {
let counts = self.counts as f64;
let step = FULL_TURN / counts;
let scaled = angle.get() / step;
if !scaled.is_finite() {
return Radians::ZERO;
}
// Ties round up; `floor` and `rem_euclid` are exact IEEE operations.
let count = (scaled + 0.5).floor().rem_euclid(counts);
Radians(count * step)
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,176 @@
use fabrilis_core::math;
use fabrilis_core::units::Radians;
use super::*;
/// Counts per revolution for the small test encoder.
const COUNTS: f64 = 1024.0;
/// One count of the test encoder, rad.
const STEP: f64 = math::TAU / COUNTS;
fn quiet() -> EncoderConfig {
EncoderConfig {
resolution_bits: 10,
noise_sigma: 0.0,
bias: 0.0,
delay_steps: 0,
}
}
fn build(config: EncoderConfig) -> Encoder {
Encoder::new(config, 42).expect("test resolution is valid")
}
/// An angle that sits exactly on the count grid.
fn grid(count: f64) -> Radians {
Radians::new(count * STEP)
}
#[test]
fn rejects_an_unusable_resolution() {
let zero = Encoder::new(
EncoderConfig {
resolution_bits: 0,
..quiet()
},
1,
);
assert_eq!(zero.err(), Some(EncoderError::ResolutionOutOfRange(0)));
let wide = Encoder::new(
EncoderConfig {
resolution_bits: 32,
..quiet()
},
1,
);
assert_eq!(wide.err(), Some(EncoderError::ResolutionOutOfRange(32)));
for bits in [1, 12, 31] {
let encoder = Encoder::new(
EncoderConfig {
resolution_bits: bits,
..quiet()
},
1,
);
assert!(encoder.is_ok(), "bits {bits}");
}
assert_eq!(build(quiet()).counts_per_revolution(), 1024);
assert_eq!(build(quiet()).resolution_bits(), 10);
}
#[test]
fn a_quiet_encoder_passes_grid_angles_through_bitwise() {
let mut encoder = build(quiet());
for count in [0.0, 1.0, 3.0, 512.0, 1023.0] {
let angle = grid(count);
assert_eq!(
encoder.sample(angle).get().to_bits(),
angle.get().to_bits(),
"count {count}"
);
}
}
#[test]
fn quantization_snaps_to_the_nearest_count() {
let mut encoder = build(quiet());
let cases = [
(3.4, 3.0),
(3.49, 3.0),
(3.5, 4.0),
(3.6, 4.0),
(-0.4, 0.0),
(-0.5, 0.0),
(-0.6, 1023.0),
];
for (input, expected) in cases {
let measured = encoder.sample(Radians::new(input * STEP));
assert_eq!(
measured.get().to_bits(),
grid(expected).get().to_bits(),
"input {input} count"
);
}
}
#[test]
fn a_full_turn_wraps_to_zero() {
let mut encoder = build(quiet());
let measured = encoder.sample(Radians::new(math::TAU));
assert_eq!(measured.get().to_bits(), 0.0_f64.to_bits());
}
#[test]
fn a_non_finite_angle_is_measured_as_zero() {
let mut encoder = build(quiet());
assert_eq!(
encoder.sample(Radians::new(f64::INFINITY)).get().to_bits(),
0.0_f64.to_bits()
);
assert_eq!(
encoder.sample(Radians::new(f64::NAN)).get().to_bits(),
0.0_f64.to_bits()
);
}
#[test]
fn bias_shifts_the_quantized_angle() {
let mut encoder = build(EncoderConfig {
bias: STEP,
..quiet()
});
assert_eq!(
encoder.sample(Radians::ZERO).get().to_bits(),
STEP.to_bits()
);
}
#[test]
fn delay_reports_the_sample_from_n_steps_ago() {
let mut encoder = build(EncoderConfig {
delay_steps: 3,
..quiet()
});
let mut measured = Vec::new();
for count in [10.0, 20.0, 30.0, 40.0, 50.0] {
measured.push(encoder.sample(grid(count)));
}
let expected = [grid(0.0), grid(0.0), grid(0.0), grid(10.0), grid(20.0)];
for (value, want) in measured.iter().zip(expected) {
assert_eq!(value.get().to_bits(), want.get().to_bits());
}
}
#[test]
fn the_same_seed_repeats_and_different_seeds_differ() {
let noisy = EncoderConfig {
noise_sigma: 0.01,
delay_steps: 2,
..quiet()
};
let mut a = Encoder::new(noisy, 7).expect("test resolution is valid");
let mut b = Encoder::new(noisy, 7).expect("test resolution is valid");
let mut c = Encoder::new(noisy, 8).expect("test resolution is valid");
let mut differs = false;
for step in 0..50 {
let angle = grid(f64::from(step) * 7.0);
let (first, repeated, other) = (a.sample(angle), b.sample(angle), c.sample(angle));
assert_eq!(first.get().to_bits(), repeated.get().to_bits());
differs |= first.get().to_bits() != other.get().to_bits();
}
assert!(differs);
}
#[test]
fn noise_stays_finite_over_many_samples() {
let mut encoder = build(EncoderConfig {
noise_sigma: 10.0,
delay_steps: 4,
..quiet()
});
for step in 0..10_000 {
let measured = encoder.sample(Radians::new(f64::from(step) * 1e-3));
assert!(measured.get().is_finite(), "step {step}");
}
}

View file

@ -1 +1,137 @@
//! fabrilis-sensors :: imu - stub (see docs/ARCHITECTURE.md)
//! Inertial measurement unit: a gyro and an accelerometer with noise, bias and delay.
//!
//! The model is deliberately minimal: no magnetometer and no sensor fusion, so the
//! caller supplies the true orientation and receives a perturbed measurement of it.
//! Noise applies to every output component, bias to the measured vectors, and the
//! whole sample goes through a FIFO.
use fabrilis_core::rng::Rng;
use fabrilis_core::units::RadiansPerSecond;
use fabrilis_core::vec::{Quat, Vec3};
use crate::delay::Delay;
use crate::noise::Noise;
/// IMU parameters.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ImuConfig {
/// Standard deviation of the Gaussian noise, applied to every output component.
///
/// Orientation components are dimensionless, angular velocity is in rad/s and
/// acceleration in m/s², so one sigma serves all three at modest accuracy.
pub noise_sigma: f64,
/// Constant additive offset of angular velocity and acceleration, per component.
///
/// Orientation carries no bias: a constant quaternion offset is not a rotation.
pub bias: f64,
/// Transport delay in samples.
pub delay_steps: usize,
}
impl Default for ImuConfig {
/// An IMU without noise, bias or delay.
fn default() -> Self {
Self {
noise_sigma: 0.0,
bias: 0.0,
delay_steps: 0,
}
}
}
/// One IMU measurement, expressed in the body frame.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ImuSample {
/// Measured orientation of the body in the world frame.
pub orientation: Quat,
/// Measured angular velocity, rad/s.
pub angular_velocity: Vec3,
/// Measured proper acceleration, m/s².
pub acceleration: Vec3,
}
impl ImuSample {
/// The value reported until the delay FIFO fills.
pub const AT_REST: Self = Self {
orientation: Quat::IDENTITY,
angular_velocity: Vec3::ZERO,
acceleration: Vec3::ZERO,
};
}
/// A gyro and an accelerometer with noise, bias and delay.
#[derive(Debug, Clone)]
pub struct Imu {
noise: Noise,
bias: f64,
delay: Delay<ImuSample>,
rng: Rng,
}
impl Imu {
/// Creates an IMU; every configuration is valid.
#[must_use]
pub fn new(config: ImuConfig, seed: u64) -> Self {
Self {
noise: Noise::new(config.noise_sigma),
bias: config.bias,
delay: Delay::new(config.delay_steps, ImuSample::AT_REST),
rng: Rng::new(seed),
}
}
/// Measures one instant of the true state.
///
/// The gyro models a single body axis: the scalar `angular_velocity` is the rate
/// about body Z, and X and Y measure only noise and bias. Orientation components
/// are perturbed independently and renormalized, but only when noise is enabled,
/// so a noise-free IMU reproduces the input bit for bit.
///
/// Until the FIFO fills, the reported sample is [`ImuSample::AT_REST`].
pub fn sample(
&mut self,
true_orientation: Quat,
angular_velocity: RadiansPerSecond,
acceleration: Vec3,
) -> ImuSample {
let noise = self.noise;
let bias = self.bias;
let rng = &mut self.rng;
let orientation = measured_orientation(true_orientation, noise, rng);
let rate = Vec3::new(0.0, 0.0, angular_velocity.get());
let measured = ImuSample {
orientation,
angular_velocity: measured_vec3(rate, noise, bias, rng),
acceleration: measured_vec3(acceleration, noise, bias, rng),
};
self.delay.push(measured)
}
}
fn measured_orientation(true_orientation: Quat, noise: Noise, rng: &mut Rng) -> Quat {
if noise.is_zero() {
return true_orientation;
}
let q = Quat::new(
true_orientation.w + noise.sample(rng),
true_orientation.x + noise.sample(rng),
true_orientation.y + noise.sample(rng),
true_orientation.z + noise.sample(rng),
);
q.normalize().unwrap_or(true_orientation)
}
fn measured_vec3(true_value: Vec3, noise: Noise, bias: f64, rng: &mut Rng) -> Vec3 {
Vec3::new(
measured_component(true_value.x, noise, bias, rng),
measured_component(true_value.y, noise, bias, rng),
measured_component(true_value.z, noise, bias, rng),
)
}
fn measured_component(true_value: f64, noise: Noise, bias: f64, rng: &mut Rng) -> f64 {
bias + noise.apply(true_value, rng)
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,139 @@
use fabrilis_core::units::RadiansPerSecond;
use fabrilis_core::vec::{Quat, Vec3};
use super::*;
fn quiet() -> ImuConfig {
ImuConfig {
noise_sigma: 0.0,
bias: 0.0,
delay_steps: 0,
}
}
fn truth() -> (Quat, RadiansPerSecond, Vec3) {
(
Quat::IDENTITY,
RadiansPerSecond::new(0.75),
Vec3::new(1.5, -2.25, 9.81),
)
}
#[test]
fn a_quiet_imu_reproduces_the_true_state_bitwise() {
let mut imu = Imu::new(quiet(), 21);
let (orientation, rate, acceleration) = truth();
let sample = imu.sample(orientation, rate, acceleration);
assert_eq!(sample.orientation, orientation);
assert_eq!(sample.angular_velocity.x, 0.0);
assert_eq!(sample.angular_velocity.y, 0.0);
assert_eq!(sample.angular_velocity.z.to_bits(), rate.get().to_bits());
assert_eq!(sample.acceleration.x.to_bits(), acceleration.x.to_bits());
assert_eq!(sample.acceleration.y.to_bits(), acceleration.y.to_bits());
assert_eq!(sample.acceleration.z.to_bits(), acceleration.z.to_bits());
}
#[test]
fn delay_reports_the_rest_sample_until_the_queue_fills() {
let mut imu = Imu::new(
ImuConfig {
delay_steps: 2,
..quiet()
},
3,
);
let (orientation, rate, acceleration) = truth();
assert_eq!(
imu.sample(orientation, rate, acceleration),
ImuSample::AT_REST
);
assert_eq!(
imu.sample(orientation, rate, acceleration),
ImuSample::AT_REST
);
let delayed = imu.sample(orientation, rate, acceleration);
assert_eq!(delayed.orientation, orientation);
assert_eq!(delayed.angular_velocity.z.to_bits(), rate.get().to_bits());
assert_eq!(delayed.acceleration.z.to_bits(), acceleration.z.to_bits());
}
#[test]
fn bias_offsets_angular_velocity_and_acceleration() {
let mut imu = Imu::new(
ImuConfig {
bias: 0.5,
..quiet()
},
4,
);
let (orientation, rate, acceleration) = truth();
let sample = imu.sample(orientation, rate, acceleration);
assert_eq!(sample.angular_velocity.x, 0.5);
assert_eq!(
sample.angular_velocity.z.to_bits(),
(0.5 + rate.get()).to_bits()
);
assert_eq!(
sample.acceleration.x.to_bits(),
(0.5 + acceleration.x).to_bits()
);
assert_eq!(sample.orientation, orientation);
}
#[test]
fn a_non_zero_rate_lands_on_the_z_axis_only() {
let mut imu = Imu::new(quiet(), 5);
let (_, rate, acceleration) = truth();
let sample = imu.sample(Quat::IDENTITY, rate, acceleration);
assert_eq!(sample.angular_velocity, Vec3::new(0.0, 0.0, rate.get()));
}
#[test]
fn the_same_seed_repeats_and_different_seeds_differ() {
let noisy = ImuConfig {
noise_sigma: 0.01,
bias: 0.001,
delay_steps: 1,
};
let mut a = Imu::new(noisy, 6);
let mut b = Imu::new(noisy, 6);
let mut c = Imu::new(noisy, 7);
let (orientation, rate, acceleration) = truth();
let mut differs = false;
for _ in 0..50 {
let first = a.sample(orientation, rate, acceleration);
let repeated = b.sample(orientation, rate, acceleration);
let other = c.sample(orientation, rate, acceleration);
assert_eq!(
first.acceleration.z.to_bits(),
repeated.acceleration.z.to_bits()
);
assert_eq!(
first.orientation.w.to_bits(),
repeated.orientation.w.to_bits()
);
differs |= first.acceleration.z.to_bits() != other.acceleration.z.to_bits();
}
assert!(differs);
}
#[test]
fn noise_stays_finite_and_the_orientation_stays_normalized() {
let mut imu = Imu::new(
ImuConfig {
noise_sigma: 0.05,
bias: 0.1,
delay_steps: 3,
},
8,
);
let (orientation, rate, acceleration) = truth();
for step in 0..10_000 {
let sample = imu.sample(orientation, rate, acceleration);
let norm = sample.orientation.norm_squared();
assert!((norm - 1.0).abs() < 1e-12, "step {step}: norm {norm}");
assert!(sample.orientation.w.is_finite(), "step {step}");
assert!(sample.angular_velocity.is_finite(), "step {step}");
assert!(sample.acceleration.is_finite(), "step {step}");
}
}

View file

@ -1,4 +1,5 @@
//! IMU, encoders, current sensors: noise, bias, delay, sampling
mod delay;
pub mod encoder;
pub mod imu;
pub mod noise;

View file

@ -1 +1,69 @@
//! fabrilis-sensors :: noise - stub (see docs/ARCHITECTURE.md)
//! Additive white Gaussian noise for sensor models.
//!
//! Sampling uses the Box-Muller transform over the seeded [`Rng`], so a sequence is
//! identical on every platform (docs/DETERMINISM.md). A zero sigma returns exactly
//! `0.0` and does not touch the generator, which lets a noise-free sensor reproduce
//! its input bit for bit.
use fabrilis_core::math;
use fabrilis_core::rng::Rng;
/// Gaussian noise with standard deviation `sigma`, in the units of the measured value.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Noise {
sigma: f64,
}
impl Noise {
/// Creates a noise source with standard deviation `sigma`.
///
/// A negative, zero or non-finite `sigma` disables the noise; the sign of `sigma`
/// carries no meaning here.
#[inline]
#[must_use]
pub fn new(sigma: f64) -> Self {
let sigma = if sigma.is_finite() && sigma > 0.0 {
sigma
} else {
0.0
};
Self { sigma }
}
/// The standard deviation in the units of the measured value.
#[inline]
#[must_use]
pub fn sigma(self) -> f64 {
self.sigma
}
/// True when this source adds nothing and leaves the generator untouched.
#[inline]
#[must_use]
pub fn is_zero(self) -> bool {
self.sigma == 0.0
}
/// One sample from a normal distribution with mean `0.0` and standard deviation
/// `sigma`.
///
/// A zero sigma returns exactly `0.0` and does not advance `rng`.
pub fn sample(self, rng: &mut Rng) -> f64 {
if self.sigma == 0.0 {
return 0.0;
}
// `u1` lies in `(0, 1]`, so the logarithm stays finite, and `u2` in `[0, 1)`.
let u1 = 1.0 - rng.next_f64();
let u2 = rng.next_f64();
let radius = math::sqrt(-2.0 * math::ln(u1));
self.sigma * radius * math::cos(math::TAU * u2)
}
/// `value` with one noise sample added.
pub fn apply(self, value: f64, rng: &mut Rng) -> f64 {
value + self.sample(rng)
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,74 @@
use fabrilis_core::rng::Rng;
use super::*;
#[test]
fn zero_sigma_returns_zero_and_keeps_the_generator_untouched() {
let mut rng = Rng::new(5);
assert_eq!(Noise::new(0.0).sample(&mut rng), 0.0);
let mut reference = Rng::new(5);
assert_eq!(rng.next_u64(), reference.next_u64());
}
#[test]
fn zero_sigma_passes_the_value_through_bitwise() {
let mut rng = Rng::new(6);
let value = -1.234_567_890_123e-7;
let measured = Noise::new(0.0).apply(value, &mut rng);
assert_eq!(measured.to_bits(), value.to_bits());
}
#[test]
fn negative_and_non_finite_sigma_disable_the_noise() {
assert_eq!(Noise::new(-1.0).sigma(), 0.0);
assert_eq!(Noise::new(f64::NAN).sigma(), 0.0);
assert_eq!(Noise::new(f64::INFINITY).sigma(), 0.0);
assert!(Noise::new(-1.0).is_zero());
assert_eq!(Noise::new(0.5).sigma(), 0.5);
}
#[test]
fn samples_are_finite_and_match_the_sigma() {
let sigma = 0.25;
let noise = Noise::new(sigma);
let mut rng = Rng::new(17);
let count = 100_000_u32;
let mut sum = 0.0;
let mut sum_squared = 0.0;
for _ in 0..count {
let value = noise.sample(&mut rng);
assert!(value.is_finite(), "{value}");
sum += value;
sum_squared += value * value;
}
let n = f64::from(count);
let mean = sum / n;
let variance = sum_squared / n - mean * mean;
assert!(mean.abs() < 0.01, "mean {mean}");
assert!(
(variance - sigma * sigma).abs() < 0.005,
"variance {variance}"
);
}
#[test]
fn the_same_seed_repeats_the_sequence() {
let noise = Noise::new(0.5);
let mut a = Rng::new(3);
let mut b = Rng::new(3);
for _ in 0..100 {
assert_eq!(
noise.sample(&mut a).to_bits(),
noise.sample(&mut b).to_bits()
);
}
}
#[test]
fn different_seeds_differ() {
let noise = Noise::new(1.0);
let mut a = Rng::new(1);
let mut b = Rng::new(2);
let differs = (0..8).any(|_| noise.sample(&mut a).to_bits() != noise.sample(&mut b).to_bits());
assert!(differs);
}

View file

@ -11,6 +11,8 @@ workspace = true
[dependencies]
fabrilis-core = { path = "../core" }
serde = { version = "1", features = ["derive"] }
ron = "0.12"
[build-dependencies]
fabrilis-limits = { path = "../../tools/limits" }

View file

@ -1 +1,143 @@
//! fabrilis-storage :: blob - stub (see docs/ARCHITECTURE.md)
//! Content-addressed blob storage.
//!
//! A blob is named by an FNV-1a 64-bit hash of its bytes, so equal contents are
//! stored once and a file can be checked against its name (docs/STORAGE.md). The
//! hash detects accidental corruption and deduplicates saves; it is not a
//! cryptographic digest and does not resist a deliberate collision.
use core::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use serde::de::Error as DeError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// FNV-1a 64-bit offset basis.
const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
/// FNV-1a 64-bit prime.
const PRIME: u64 = 0x0000_0100_0000_01b3;
/// Hex digits in a serialised hash.
const HEX_DIGITS: usize = 16;
/// Distinguishes temporary files written by concurrent saves in one process.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
/// The content hash of a blob.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BlobHash(u64);
impl BlobHash {
/// Hashes the bytes with FNV-1a 64.
#[must_use]
pub fn hash(bytes: &[u8]) -> Self {
let mut value = OFFSET_BASIS;
for &byte in bytes {
value ^= u64::from(byte);
value = value.wrapping_mul(PRIME);
}
Self(value)
}
/// The hash as 16 lowercase hex digits, the blob's file name.
#[must_use]
pub fn to_hex(self) -> String {
format!("{:016x}", self.0)
}
/// Parses 16 hex digits, uppercase or lowercase.
#[must_use]
pub fn from_hex(text: &str) -> Option<Self> {
if text.len() != HEX_DIGITS || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return None;
}
u64::from_str_radix(text, 16).ok().map(Self)
}
}
impl fmt::Display for BlobHash {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{:016x}", self.0)
}
}
impl Serialize for BlobHash {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_hex())
}
}
impl<'de> Deserialize<'de> for BlobHash {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
Self::from_hex(&text).ok_or_else(|| DeError::custom("blob hash must be 16 hex digits"))
}
}
/// A directory of blobs named by their content hash.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlobStore {
root: PathBuf,
}
impl BlobStore {
/// Uses `root` as the directory that holds the blob files.
#[must_use]
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
/// The directory holding the blobs.
#[must_use]
pub fn root(&self) -> &Path {
&self.root
}
/// Writes `bytes` unless the same contents are already stored.
///
/// The file is written under a temporary name and renamed into place, so a
/// reader never sees a partial blob even if the process stops mid-write.
pub fn put(&self, bytes: &[u8]) -> io::Result<BlobHash> {
let hash = BlobHash::hash(bytes);
let path = self.path(hash);
if path.is_file() {
return Ok(hash);
}
fs::create_dir_all(&self.root)?;
let temp = temp_path(&self.root);
fs::write(&temp, bytes)?;
if let Err(error) = fs::rename(&temp, &path) {
let _ = fs::remove_file(&temp);
return Err(error);
}
Ok(hash)
}
/// Reads the blob back; a missing file is an [`io::ErrorKind::NotFound`].
pub fn get(&self, hash: BlobHash) -> io::Result<Vec<u8>> {
fs::read(self.path(hash))
}
/// The file that holds `hash`, whether or not it exists yet.
#[must_use]
pub fn path(&self, hash: BlobHash) -> PathBuf {
self.root.join(hash.to_hex())
}
/// True when the blob is stored.
#[must_use]
pub fn contains(&self, hash: BlobHash) -> bool {
self.path(hash).is_file()
}
}
/// A temporary file name that cannot collide with a hash file.
fn temp_path(root: &Path) -> PathBuf {
let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
let pid = std::process::id();
root.join(format!(".{pid}-{counter}.blob-tmp"))
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,99 @@
//! Blob hashing, hex round trips and content-addressed storage.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use super::{BlobHash, BlobStore};
/// A directory removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-blob-{label}-{}-{counter}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
fn fnv1a_matches_the_reference_vectors() {
assert_eq!(BlobHash::hash(b"").to_hex(), "cbf29ce484222325");
assert_eq!(BlobHash::hash(b"a").to_hex(), "af63dc4c8601ec8c");
assert_eq!(BlobHash::hash(b"foobar").to_hex(), "85944171f73967e8");
}
#[test]
fn hex_round_trips_and_rejects_bad_input() {
let hash = BlobHash::hash(b"payload");
let hex = hash.to_hex();
assert_eq!(hex.len(), 16);
assert_eq!(BlobHash::from_hex(&hex), Some(hash));
assert_eq!(BlobHash::from_hex(&hex.to_uppercase()), Some(hash));
assert_eq!(BlobHash::from_hex(""), None);
assert_eq!(BlobHash::from_hex("xyz"), None);
assert_eq!(BlobHash::from_hex("0123456789abcde"), None);
assert_eq!(BlobHash::from_hex("0123456789abcdeg"), None);
}
#[test]
fn serde_uses_the_hex_string_form() {
let hash = BlobHash::hash(b"scene");
let text = ron::to_string(&hash).unwrap();
assert_eq!(text, format!("\"{}\"", hash.to_hex()));
assert_eq!(ron::from_str::<BlobHash>(&text).unwrap(), hash);
assert!(ron::from_str::<BlobHash>("\"not-a-hash\"").is_err());
}
#[test]
fn put_get_and_contains_round_trip() {
let temp = TempDir::new("round-trip");
let store = BlobStore::new(&temp.path);
let hash = store.put(b"hello blob").unwrap();
assert!(store.contains(hash));
assert_eq!(store.get(hash).unwrap(), b"hello blob");
assert_eq!(store.path(hash), temp.path.join(hash.to_hex()));
assert!(store.path(hash).is_file());
}
#[test]
fn storing_the_same_bytes_twice_keeps_one_file() {
let temp = TempDir::new("dedup");
let store = BlobStore::new(&temp.path);
let first = store.put(b"same").unwrap();
let second = store.put(b"same").unwrap();
assert_eq!(first, second);
let files = std::fs::read_dir(&temp.path).unwrap().count();
assert_eq!(files, 1);
}
#[test]
fn a_missing_blob_is_not_found() {
let temp = TempDir::new("missing");
let store = BlobStore::new(&temp.path);
let hash = BlobHash::hash(b"never stored");
assert!(!store.contains(hash));
let error = store.get(hash).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
}

View file

@ -1 +1,123 @@
//! fabrilis-storage :: format - stub (see docs/ARCHITECTURE.md)
//! Versioned RON files.
//!
//! Every saved file is an [`Envelope`] with a `format_version` field, so a newer
//! build can reject data it does not understand and an older one can migrate it
//! forward through the chain in [`crate::migrate`].
use core::fmt;
use std::collections::BTreeMap;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::migrate::{self, MigrateError, Migration};
/// The format version written by this build.
pub const CURRENT_VERSION: u32 = 1;
/// A payload with the version of the schema it follows.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Envelope<T> {
/// Schema version of `payload`.
pub format_version: u32,
/// The document itself.
pub payload: T,
}
/// Serialises `payload` as a pretty RON envelope at [`CURRENT_VERSION`].
pub fn to_ron<T: Serialize>(payload: &T) -> Result<String, FormatError> {
let envelope = Envelope {
format_version: CURRENT_VERSION,
payload,
};
ron::ser::to_string_pretty(&envelope, ron::ser::PrettyConfig::default())
.map_err(|error| FormatError::Encode(error.to_string()))
}
/// Reads an envelope written at [`CURRENT_VERSION`].
///
/// Older documents are rejected because no migration steps are known here; use
/// [`from_ron_with_migrations`] to supply them.
pub fn from_ron<T: DeserializeOwned>(text: &str) -> Result<T, FormatError> {
from_ron_with_migrations(text, &BTreeMap::new())
}
/// Reads an envelope, migrates an older payload forward, then decodes it.
///
/// A version newer than [`CURRENT_VERSION`] is always rejected: a newer file may
/// contain fields this build would silently drop.
pub fn from_ron_with_migrations<T: DeserializeOwned>(
text: &str,
steps: &BTreeMap<u32, Migration>,
) -> Result<T, FormatError> {
let envelope: Envelope<ron::Value> =
ron::from_str(text).map_err(|error| FormatError::Parse(error.to_string()))?;
if envelope.format_version > CURRENT_VERSION {
return Err(FormatError::TooNew {
found: envelope.format_version,
current: CURRENT_VERSION,
});
}
let payload = migrate::migrate_value(
envelope.payload,
envelope.format_version,
CURRENT_VERSION,
steps,
)?;
payload
.into_rust()
.map_err(|error| FormatError::Decode(error.to_string()))
}
/// Why a file could not be read or written.
#[derive(Debug)]
pub enum FormatError {
/// The text is not a RON envelope.
Parse(String),
/// The payload could not be serialised.
Encode(String),
/// The payload does not match the requested type after migration.
Decode(String),
/// The file was written by a newer build.
TooNew {
/// Version found in the file.
found: u32,
/// Version this build understands.
current: u32,
},
/// A migration step failed.
Migration(MigrateError),
}
impl From<MigrateError> for FormatError {
fn from(error: MigrateError) -> Self {
Self::Migration(error)
}
}
impl fmt::Display for FormatError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Parse(reason) => write!(formatter, "cannot parse the RON envelope: {reason}"),
Self::Encode(reason) => write!(formatter, "cannot encode the RON payload: {reason}"),
Self::Decode(reason) => write!(formatter, "cannot decode the RON payload: {reason}"),
Self::TooNew { found, current } => write!(
formatter,
"format version {found} is newer than the supported version {current}"
),
Self::Migration(error) => write!(formatter, "migration failed: {error}"),
}
}
}
impl std::error::Error for FormatError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Migration(error) => Some(error),
_ => None,
}
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,90 @@
//! Envelope versioning and guarded decoding.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use super::{CURRENT_VERSION, FormatError, from_ron, from_ron_with_migrations, to_ron};
use crate::migrate::{MigrateError, Migration};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Document {
answer: f64,
}
/// A step from version 0 to version 1: add one to `answer`.
fn add_one(mut value: ron::Value) -> Result<ron::Value, MigrateError> {
let ron::Value::Map(ref mut document) = value else {
return Err(MigrateError::step(0, "document is not a map"));
};
let Some(answer) = document.get_mut(&ron::Value::from("answer")) else {
return Err(MigrateError::step(0, "document has no answer"));
};
let ron::Value::Number(number) = answer else {
return Err(MigrateError::step(0, "answer is not a number"));
};
let incremented = (*number).into_f64() + 1.0;
*answer = ron::Value::from(incremented);
Ok(value)
}
fn steps() -> BTreeMap<u32, Migration> {
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, add_one as Migration);
steps
}
#[test]
fn a_payload_round_trips_at_the_current_version() {
let text = to_ron(&Document { answer: 42.0 }).unwrap();
assert!(text.contains("format_version: 1"));
assert!(text.contains("payload:"));
let document: Document = from_ron(&text).unwrap();
assert_eq!(document, Document { answer: 42.0 });
}
#[test]
fn a_newer_version_is_rejected() {
let text = format!(
"(format_version: {}, payload: (answer: 1.0))",
CURRENT_VERSION + 1
);
let error = from_ron::<Document>(&text).unwrap_err();
assert!(matches!(error, FormatError::TooNew { .. }));
}
#[test]
fn an_older_version_needs_a_registered_step() {
let text = "(format_version: 0, payload: (answer: 41.0))";
let error = from_ron::<Document>(text).unwrap_err();
assert!(matches!(
error,
FormatError::Migration(MigrateError::MissingStep { version: 0, .. })
));
}
#[test]
fn an_older_version_is_migrated_before_decoding() {
let text = "(format_version: 0, payload: (answer: 41.0))";
let document: Document = from_ron_with_migrations(text, &steps()).unwrap();
assert_eq!(document, Document { answer: 42.0 });
}
#[test]
fn a_payload_of_the_wrong_shape_is_a_decode_error() {
let text = "(format_version: 1, payload: 7.0)";
let error = from_ron::<Document>(text).unwrap_err();
assert!(matches!(error, FormatError::Decode(_)));
}
#[test]
fn malformed_text_is_a_parse_error() {
let error = from_ron::<Document>("this is not RON").unwrap_err();
assert!(matches!(error, FormatError::Parse(_)));
}

View file

@ -1 +1,101 @@
//! fabrilis-storage :: migrate - stub (see docs/ARCHITECTURE.md)
//! Forward-only schema migrations over RON values.
//!
//! A migration upgrades the payload of one format version to the next. Steps are
//! kept in a [`BTreeMap`] so the chain is explicit and missing links are reported
//! instead of silently skipped (docs/STORAGE.md).
use core::fmt;
use std::collections::BTreeMap;
/// A step from version `version` to `version + 1` over the payload.
pub type Migration = fn(ron::Value) -> Result<ron::Value, MigrateError>;
/// Why a migration chain could not be applied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MigrateError {
/// The caller asked to go backwards; saved data is never downgraded.
Downgrade {
/// Version of the loaded value.
from: u32,
/// Requested version, lower than `from`.
to: u32,
},
/// No step is registered for the version that needs upgrading.
MissingStep {
/// Version without a step.
version: u32,
/// Version the chain was asked to reach.
to: u32,
},
/// A step rejected the value it was given.
Step {
/// Version the failing step reads.
version: u32,
/// What was wrong with the value.
reason: String,
},
}
impl MigrateError {
/// Builds [`Self::Step`] for a step that rejects its input.
#[must_use]
pub fn step(version: u32, reason: impl Into<String>) -> Self {
Self::Step {
version,
reason: reason.into(),
}
}
}
impl fmt::Display for MigrateError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Downgrade { from, to } => {
write!(
formatter,
"cannot migrate version {from} back to version {to}"
)
}
Self::MissingStep { version, to } => write!(
formatter,
"no migration from version {version} while migrating to version {to}"
),
Self::Step { version, reason } => {
write!(
formatter,
"migration from version {version} failed: {reason}"
)
}
}
}
}
impl std::error::Error for MigrateError {}
/// Applies the steps from `from` up to `to`, one version at a time.
///
/// `steps[version]` must upgrade version `version` to `version + 1`. `from == to`
/// is a no-op. A downgrade, a missing step or a rejecting step is an error; the
/// value is left untouched on failure.
pub fn migrate_value(
mut value: ron::Value,
from: u32,
to: u32,
steps: &BTreeMap<u32, Migration>,
) -> Result<ron::Value, MigrateError> {
if to < from {
return Err(MigrateError::Downgrade { from, to });
}
let mut version = from;
while version < to {
let step = steps
.get(&version)
.ok_or(MigrateError::MissingStep { version, to })?;
value = step(value)?;
version += 1;
}
Ok(value)
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,94 @@
//! Migration chains: ordering, missing links and downgrades.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::collections::BTreeMap;
use super::{MigrateError, Migration, migrate_value};
/// Version 0 → 1: adds the field `a`.
fn insert_a(mut value: ron::Value) -> Result<ron::Value, MigrateError> {
let ron::Value::Map(ref mut document) = value else {
return Err(MigrateError::step(0, "document is not a map"));
};
let _previous = document.insert("a", 1);
Ok(value)
}
/// Version 1 → 2: adds the field `b`.
fn insert_b(mut value: ron::Value) -> Result<ron::Value, MigrateError> {
let ron::Value::Map(ref mut document) = value else {
return Err(MigrateError::step(1, "document is not a map"));
};
let _previous = document.insert("b", 2);
Ok(value)
}
fn empty_document() -> ron::Value {
ron::Value::Map(ron::Map::new())
}
#[test]
fn a_two_step_chain_applies_in_order() {
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, insert_a as Migration);
let _previous = steps.insert(1, insert_b as Migration);
let migrated = migrate_value(empty_document(), 0, 2, &steps).unwrap();
let ron::Value::Map(document) = migrated else {
panic!("a migration must return a map");
};
assert_eq!(
document.get(&ron::Value::from("a")),
Some(&ron::Value::from(1))
);
assert_eq!(
document.get(&ron::Value::from("b")),
Some(&ron::Value::from(2))
);
}
#[test]
fn a_missing_step_stops_the_chain() {
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, insert_a as Migration);
let error = migrate_value(empty_document(), 0, 2, &steps).unwrap_err();
assert_eq!(error, MigrateError::MissingStep { version: 1, to: 2 });
}
#[test]
fn a_downgrade_is_rejected_before_any_step_runs() {
let error = migrate_value(empty_document(), 2, 0, &BTreeMap::new()).unwrap_err();
assert_eq!(error, MigrateError::Downgrade { from: 2, to: 0 });
}
#[test]
fn equal_versions_are_a_no_op() {
let value = empty_document();
let migrated = migrate_value(value.clone(), 3, 3, &BTreeMap::new()).unwrap();
assert_eq!(migrated, value);
}
#[test]
fn a_rejecting_step_reports_its_version() {
fn reject(value: ron::Value) -> Result<ron::Value, MigrateError> {
let _ignored = value;
Err(MigrateError::step(0, "malformed payload"))
}
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, reject as Migration);
let error = migrate_value(empty_document(), 0, 1, &steps).unwrap_err();
assert!(matches!(
error,
MigrateError::Step {
version: 0,
ref reason
} if reason == "malformed payload"
));
}

View file

@ -1 +1,104 @@
//! fabrilis-storage :: project - stub (see docs/ARCHITECTURE.md)
//! A project folder: the save format described in docs/STORAGE.md.
//!
//! A project is a directory with a `blobs/` subdirectory for content-addressed
//! files and small RON documents at its root. Text files are written through a
//! temporary file and renamed into place, so an interrupted save cannot leave a
//! half-written document behind.
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use crate::blob::BlobStore;
/// Subdirectory holding the blobs.
const BLOB_DIRECTORY: &str = "blobs";
/// Distinguishes temporary files written by concurrent saves in one process.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
/// An existing project directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Project {
root: PathBuf,
}
impl Project {
/// Creates the directory, its parents and the blob store.
pub fn create(root: impl Into<PathBuf>) -> io::Result<Self> {
let root = root.into();
fs::create_dir_all(&root)?;
fs::create_dir_all(root.join(BLOB_DIRECTORY))?;
Ok(Self { root })
}
/// Opens an existing directory; a missing path is [`io::ErrorKind::NotFound`].
pub fn open(root: impl Into<PathBuf>) -> io::Result<Self> {
let root = root.into();
if root.is_dir() {
Ok(Self { root })
} else {
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("project directory {} does not exist", root.display()),
))
}
}
/// The project directory.
#[must_use]
pub fn root(&self) -> &Path {
&self.root
}
/// The blob store under `root/blobs`.
#[must_use]
pub fn blobs(&self) -> BlobStore {
BlobStore::new(self.root.join(BLOB_DIRECTORY))
}
/// A file path inside the project; the file need not exist.
#[must_use]
pub fn path(&self, name: &str) -> PathBuf {
self.root.join(name)
}
/// Writes a text document atomically.
pub fn write_text(&self, name: &str, text: &str) -> io::Result<()> {
write_atomic(&self.path(name), text)
}
/// Reads a text document written with [`Self::write_text`].
pub fn read_text(&self, name: &str) -> io::Result<String> {
fs::read_to_string(self.path(name))
}
}
/// Writes through a temporary file in the same directory, then renames.
fn write_atomic(path: &Path, text: &str) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let temp = temp_path(path);
fs::write(&temp, text)?;
if let Err(error) = fs::rename(&temp, path) {
let _ = fs::remove_file(&temp);
return Err(error);
}
Ok(())
}
/// A temporary sibling of `path` that cannot collide with the target name.
fn temp_path(path: &Path) -> PathBuf {
let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
let pid = std::process::id();
let name = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("file");
path.with_file_name(format!(".{name}.{pid}-{counter}.tmp"))
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,94 @@
//! Project folders: creation, atomic text files and the blob directory.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use super::Project;
/// A directory removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-project-{label}-{}-{counter}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[test]
fn create_makes_the_root_and_the_blob_directory() {
let temp = TempDir::new("create");
let root = temp.path.join("new-project");
let project = Project::create(&root).unwrap();
assert_eq!(project.root(), root);
assert!(root.is_dir());
assert!(root.join("blobs").is_dir());
}
#[test]
fn open_requires_an_existing_directory() {
let temp = TempDir::new("open");
let missing = temp.path.join("absent");
let error = Project::open(&missing).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
let project = Project::create(&temp.path).unwrap();
assert_eq!(Project::open(project.root()).unwrap().root(), temp.path);
}
#[test]
fn text_round_trips_and_replaces_atomically() {
let temp = TempDir::new("text");
let project = Project::create(&temp.path).unwrap();
project.write_text("scene.ron", "first").unwrap();
assert_eq!(project.read_text("scene.ron").unwrap(), "first");
project.write_text("scene.ron", "second").unwrap();
assert_eq!(project.read_text("scene.ron").unwrap(), "second");
let leftovers: Vec<String> = std::fs::read_dir(project.root())
.unwrap()
.filter_map(|entry| entry.ok())
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.filter(|name| name.starts_with('.'))
.collect();
assert!(leftovers.is_empty(), "temporary files left: {leftovers:?}");
}
#[test]
fn paths_are_rooted_in_the_project() {
let temp = TempDir::new("path");
let project = Project::create(&temp.path).unwrap();
assert_eq!(project.path("scene.ron"), temp.path.join("scene.ron"));
}
#[test]
fn blobs_live_in_the_blobs_subdirectory() {
let temp = TempDir::new("blobs");
let project = Project::create(&temp.path).unwrap();
let store = project.blobs();
let hash = store.put(b"mesh").unwrap();
assert!(store.contains(hash));
assert!(project.path("blobs").join(hash.to_hex()).is_file());
}

View file

@ -1 +1,121 @@
//! fabrilis-worldgen :: noise - stub (see docs/ARCHITECTURE.md)
//! Deterministic 2D value noise.
//!
//! Values sit on an integer lattice and are interpolated with a smoothstep curve.
//! The lattice value comes from SplitMix64 mixing of the seed and both lattice
//! coordinates, so the result uses integer arithmetic only: no floating-point
//! hashing, no `std` transcendental functions, the same output on every platform.
//! See docs/DETERMINISM.md.
/// SplitMix64 increment; mixing a seed with it keeps seed `0` from being special.
const GAMMA: u64 = 0x9E37_79B9_7F4A_7C15;
/// Odd multipliers that spread the two lattice axes before the finaliser runs.
const X_PRIME: u64 = 0xD6E8_FEB8_6659_FD93;
const Y_PRIME: u64 = 0xA076_1D64_78BD_642F;
/// Scale that turns the top 53 bits of a hash into `[0, 1)`.
const UNIT: f64 = 1.0 / (1u64 << 53) as f64;
/// The SplitMix64 finaliser: a bijective avalanche on 64 bits.
#[inline]
fn mix(mut z: u64) -> u64 {
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
/// Hashes one lattice point; pure integer arithmetic, so it is portable.
#[inline]
fn lattice_hash(seed: u64, ix: i64, iy: i64) -> u64 {
let horizontal = mix(seed.wrapping_add(GAMMA) ^ (ix as u64).wrapping_mul(X_PRIME));
mix(horizontal ^ (iy as u64).wrapping_mul(Y_PRIME))
}
/// Maps a hash to a lattice value in `[-1, 1)`; the 53-bit mantissa is exact.
#[inline]
fn lattice_value(hash: u64) -> f64 {
((hash >> 11) as f64 * UNIT).mul_add(2.0, -1.0)
}
/// Smoothstep: `3t² - 2t³`, with zero first derivative at both ends.
#[inline]
fn smoothstep(t: f64) -> f64 {
t * t * (3.0 - 2.0 * t)
}
/// A seeded 2D value-noise field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Noise {
seed: u64,
}
impl Noise {
/// Creates a field from a seed; every seed is valid.
#[inline]
#[must_use]
pub const fn new(seed: u64) -> Self {
Self { seed }
}
/// Samples the field at `(x, y)`, returning a value in `[-1, 1]`.
///
/// Non-finite coordinates sample as `0`, so callers never see NaN.
#[must_use]
pub fn sample(&self, x: f64, y: f64) -> f64 {
if !x.is_finite() || !y.is_finite() {
return 0.0;
}
// `as i64` saturates for coordinates beyond the lattice range, which keeps
// the result finite and deterministic instead of wrapping.
let base_x = x.floor();
let base_y = y.floor();
let ix = base_x as i64;
let iy = base_y as i64;
let tx = smoothstep(x - base_x);
let ty = smoothstep(y - base_y);
let bottom_left = lattice_value(lattice_hash(self.seed, ix, iy));
let bottom_right = lattice_value(lattice_hash(self.seed, ix.wrapping_add(1), iy));
let top_left = lattice_value(lattice_hash(self.seed, ix, iy.wrapping_add(1)));
let top_right = lattice_value(lattice_hash(
self.seed,
ix.wrapping_add(1),
iy.wrapping_add(1),
));
let bottom = bottom_left + (bottom_right - bottom_left) * tx;
let top = top_left + (top_right - top_left) * tx;
bottom + (top - bottom) * ty
}
}
/// Fractal Brownian motion: octaves summed low to high, each one `lacunarity`
/// times denser and `gain` times weaker.
///
/// The sum is divided by the total amplitude, so the result stays in `[-1, 1]`
/// for every gain and octave count. Octaves are added in a fixed order, which
/// makes the result bit-reproducible.
///
/// Six arguments are the natural shape of the call; bundling octaves and both
/// multipliers into a struct would only add a type at every call site.
#[allow(
clippy::too_many_arguments,
reason = "noise coordinates plus three independent fBm parameters; a params struct adds no clarity"
)]
#[must_use]
pub fn fbm(noise: &Noise, x: f64, y: f64, octaves: u8, lacunarity: f64, gain: f64) -> f64 {
let mut frequency = 1.0;
let mut amplitude = 1.0;
let mut total = 0.0;
let mut weight = 0.0;
for _ in 0..octaves {
total += amplitude * noise.sample(x * frequency, y * frequency);
weight += amplitude;
frequency *= lacunarity;
amplitude *= gain;
}
if weight > 0.0 { total / weight } else { 0.0 }
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,96 @@
use super::*;
#[test]
fn sample_stays_in_range() {
let noise = Noise::new(7);
for j in -32..=32 {
for i in -32..=32 {
let x = f64::from(i) * 0.37;
let y = f64::from(j) * 0.41;
let value = noise.sample(x, y);
assert!((-1.0..=1.0).contains(&value), "value {value} at ({x}, {y})");
}
}
}
#[test]
fn same_seed_repeats_exactly() {
let a = Noise::new(1234);
let b = Noise::new(1234);
for step in 0..100 {
let x = f64::from(step) * 0.13;
let y = f64::from(step) * 0.29;
assert_eq!(a.sample(x, y).to_bits(), b.sample(x, y).to_bits());
}
}
#[test]
fn different_seeds_differ() {
let a = Noise::new(1);
let b = Noise::new(2);
assert_ne!(a.sample(0.5, 0.5), b.sample(0.5, 0.5));
}
#[test]
fn lattice_points_are_reproducible_by_hash() {
let noise = Noise::new(99);
assert_eq!(
noise.sample(0.0, 0.0),
lattice_value(lattice_hash(99, 0, 0))
);
assert_eq!(
noise.sample(-3.0, 5.0),
lattice_value(lattice_hash(99, -3, 5))
);
}
#[test]
fn interpolation_is_continuous_across_cells() {
// A value-noise field is continuous, so stepping over a lattice boundary
// changes the sample only slightly.
let noise = Noise::new(5);
let left = noise.sample(0.999, 0.25);
let right = noise.sample(1.001, 0.25);
assert!((left - right).abs() < 1e-2);
}
#[test]
fn non_finite_coordinates_sample_as_zero() {
let noise = Noise::new(3);
assert_eq!(noise.sample(f64::NAN, 0.5), 0.0);
assert_eq!(noise.sample(0.5, f64::INFINITY), 0.0);
assert_eq!(noise.sample(f64::NEG_INFINITY, f64::NAN), 0.0);
}
#[test]
fn huge_coordinates_do_not_overflow() {
let noise = Noise::new(3);
for value in [1e300, -1e300, f64::MAX, f64::MIN] {
let sampled = noise.sample(value, value);
assert!((-1.0..=1.0).contains(&sampled));
}
}
#[test]
fn fbm_single_octave_equals_the_field() {
let noise = Noise::new(11);
assert_eq!(fbm(&noise, 0.7, -1.3, 1, 2.0, 0.5), noise.sample(0.7, -1.3));
}
#[test]
fn fbm_stays_in_range_for_many_octaves() {
let noise = Noise::new(21);
for j in 0..16 {
for i in 0..16 {
let x = f64::from(i) * 0.31;
let y = f64::from(j) * 0.17;
let value = fbm(&noise, x, y, 8, 2.0, 0.5);
assert!((-1.0..=1.0).contains(&value));
}
}
}
#[test]
fn fbm_with_zero_octaves_is_zero() {
assert_eq!(fbm(&Noise::new(1), 0.3, 0.4, 0, 2.0, 0.5), 0.0);
}

View file

@ -1 +1,349 @@
//! fabrilis-worldgen :: terrain - stub (see docs/ARCHITECTURE.md)
//! Terrain heightmap and its render/collider mesh.
//!
//! The world is Z-up, so terrain is a height field `z = f(x, y)` sampled on a
//! square grid centred at the origin: `x` and `y` cover `[-extent/2, extent/2]`
//! and `z` covers `[0, height_scale]`. Row-major storage keeps `i` along X and
//! `j` along Y. One map feeds both the renderer and the colliders (D14).
//! See docs/COORDINATES.md.
use fabrilis_core::vec::Vec3;
use crate::noise::{Noise, fbm};
/// Smallest accepted grid resolution; two nodes still form one cell.
const MIN_SIZE: usize = 2;
/// Largest accepted grid resolution; `size²` vertices still fit `u32` indices.
const MAX_SIZE: usize = 4096;
/// Octave bounds; more octaves cost more and add little below one sample per cell.
const MIN_OCTAVES: u8 = 1;
const MAX_OCTAVES: u8 = 8;
/// Terrain generation parameters.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TerrainConfig {
/// Seed of the noise field; the same seed gives the same heights.
pub seed: u64,
/// Nodes per axis, in `2..=4096`.
pub size: usize,
/// Side length of the map, m.
pub extent: f64,
/// Vertical span, m; `0` makes a flat map.
pub height_scale: f64,
/// Noise cycles across the map; larger values mean smaller features.
pub frequency: f64,
/// Octaves of fractal noise, in `1..=8`.
pub octaves: u8,
/// Frequency multiplier between octaves; must be greater than one.
pub lacunarity: f64,
/// Amplitude multiplier between octaves, in `[0, 1]`.
pub gain: f64,
}
impl Default for TerrainConfig {
/// A 64 x 64 grid over 100 m, up to 10 m tall.
fn default() -> Self {
Self {
seed: 0,
size: 64,
extent: 100.0,
height_scale: 10.0,
frequency: 2.0,
octaves: 4,
lacunarity: 2.0,
gain: 0.5,
}
}
}
impl TerrainConfig {
/// Distance between neighbouring nodes, m.
#[must_use]
fn spacing(&self) -> f64 {
self.extent / (self.size - 1) as f64
}
}
/// Why a [`Heightmap`] could not be generated.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TerrainError {
/// The grid resolution is outside `2..=4096`.
SizeOutOfRange(usize),
/// The map side is not finite and positive.
InvalidExtent(f64),
/// The height scale is not finite and non-negative.
InvalidHeightScale(f64),
/// The noise frequency is not finite and positive.
InvalidFrequency(f64),
/// The octave count is outside `1..=8`.
OctavesOutOfRange(u8),
/// The octave frequency multiplier is not finite and greater than one.
InvalidLacunarity(f64),
/// The octave amplitude multiplier is outside `[0, 1]`.
InvalidGain(f64),
}
impl core::fmt::Display for TerrainError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::SizeOutOfRange(size) => write!(
formatter,
"terrain size {size} is outside {MIN_SIZE}..={MAX_SIZE}"
),
Self::InvalidExtent(extent) => {
write!(
formatter,
"terrain extent {extent} is not finite and positive"
)
}
Self::InvalidHeightScale(scale) => write!(
formatter,
"terrain height scale {scale} is not finite and non-negative"
),
Self::InvalidFrequency(frequency) => write!(
formatter,
"terrain frequency {frequency} is not finite and positive"
),
Self::OctavesOutOfRange(octaves) => write!(
formatter,
"terrain octaves {octaves} is outside {MIN_OCTAVES}..={MAX_OCTAVES}"
),
Self::InvalidLacunarity(value) => write!(
formatter,
"terrain lacunarity {value} is not finite and greater than one"
),
Self::InvalidGain(value) => {
write!(formatter, "terrain gain {value} is not in [0, 1]")
}
}
}
}
impl std::error::Error for TerrainError {}
/// Rejects parameters that would panic or produce a meaningless map.
fn validate(config: &TerrainConfig) -> Result<(), TerrainError> {
if !(MIN_SIZE..=MAX_SIZE).contains(&config.size) {
return Err(TerrainError::SizeOutOfRange(config.size));
}
if !positive_finite(config.extent) {
return Err(TerrainError::InvalidExtent(config.extent));
}
if !(config.height_scale.is_finite() && config.height_scale >= 0.0) {
return Err(TerrainError::InvalidHeightScale(config.height_scale));
}
if !positive_finite(config.frequency) {
return Err(TerrainError::InvalidFrequency(config.frequency));
}
if !(MIN_OCTAVES..=MAX_OCTAVES).contains(&config.octaves) {
return Err(TerrainError::OctavesOutOfRange(config.octaves));
}
if !(config.lacunarity.is_finite() && config.lacunarity > 1.0) {
return Err(TerrainError::InvalidLacunarity(config.lacunarity));
}
if !(config.gain.is_finite() && (0.0..=1.0).contains(&config.gain)) {
return Err(TerrainError::InvalidGain(config.gain));
}
Ok(())
}
#[inline]
fn positive_finite(value: f64) -> bool {
value.is_finite() && value > 0.0
}
/// A generated heightmap with bilinear sampling and a triangle mesh.
#[derive(Debug, Clone)]
pub struct Heightmap {
config: TerrainConfig,
heights: Vec<f64>,
}
impl Heightmap {
/// Generates the map, or reports the first invalid parameter.
pub fn generate(config: TerrainConfig) -> Result<Self, TerrainError> {
validate(&config)?;
let noise = Noise::new(config.seed);
let half = config.extent * 0.5;
let spacing = config.spacing();
let noise_scale = config.frequency / config.extent;
let mut heights = Vec::with_capacity(config.size * config.size);
for j in 0..config.size {
let y = j as f64 * spacing - half;
for i in 0..config.size {
let x = i as f64 * spacing - half;
let value = fbm(
&noise,
x * noise_scale,
y * noise_scale,
config.octaves,
config.lacunarity,
config.gain,
);
heights.push((value * 0.5 + 0.5).clamp(0.0, 1.0) * config.height_scale);
}
}
Ok(Self { config, heights })
}
/// Nodes per axis.
#[inline]
#[must_use]
pub fn size(&self) -> usize {
self.config.size
}
/// Side length of the map, m.
#[inline]
#[must_use]
pub fn extent(&self) -> f64 {
self.config.extent
}
/// Distance between neighbouring nodes, m.
#[inline]
#[must_use]
pub fn spacing(&self) -> f64 {
self.config.spacing()
}
/// Heights in row-major order, `size × size`, `i` along X and `j` along Y.
#[inline]
#[must_use]
pub fn heights(&self) -> &[f64] {
&self.heights
}
/// Bilinearly interpolates the height at world `(x, y)`.
///
/// Coordinates outside the map clamp to its border; non-finite coordinates
/// clamp to the nearest edge (`NaN` to the low edge) instead of panicking.
#[must_use]
pub fn height_at(&self, x: f64, y: f64) -> f64 {
self.height_at_grid(self.grid_coordinate(x), self.grid_coordinate(y))
}
/// The surface normal at world `(x, y)`, pointing up.
///
/// Uses central differences, one-sided at the border, and returns `+Z` when
/// the gradient is degenerate.
#[must_use]
pub fn normal_at(&self, x: f64, y: f64) -> Vec3 {
let gx = self.grid_coordinate(x);
let gy = self.grid_coordinate(y);
let last = (self.config.size - 1) as f64;
let (xm, xp) = neighbours(gx, last);
let (ym, yp) = neighbours(gy, last);
let dx = (xp - xm) * self.spacing();
let dy = (yp - ym) * self.spacing();
let slope_x = (self.height_at_grid(xp, gy) - self.height_at_grid(xm, gy)) / dx;
let slope_y = (self.height_at_grid(gx, yp) - self.height_at_grid(gx, ym)) / dy;
Vec3::new(-slope_x, -slope_y, 1.0)
.normalized()
.unwrap_or(Vec3::Z)
}
/// A triangle mesh at full resolution; see [`Self::mesh_with_step`].
#[must_use]
pub fn mesh(&self) -> TerrainMesh {
self.mesh_with_step(1)
}
/// A triangle mesh that keeps every `step`-th node, for cheap colliders.
///
/// `step` is clamped to at least one; the grid keeps the first and last node,
/// so a step of two on an odd-sized map halves the node count.
#[must_use]
pub fn mesh_with_step(&self, step: usize) -> TerrainMesh {
let step = step.max(1);
let nodes = (self.config.size - 1) / step + 1;
let vertices = self.build_vertices(nodes, step);
let indices = build_indices(nodes);
TerrainMesh { vertices, indices }
}
fn build_vertices(&self, nodes: usize, step: usize) -> Vec<Vec3> {
let half = self.config.extent * 0.5;
let spacing = self.spacing();
let mut vertices = Vec::with_capacity(nodes * nodes);
for j in 0..nodes {
let grid_j = j * step;
let y = grid_j as f64 * spacing - half;
for i in 0..nodes {
let grid_i = i * step;
let x = grid_i as f64 * spacing - half;
vertices.push(Vec3::new(x, y, self.node(grid_i, grid_j)));
}
}
vertices
}
/// The stored height at a grid node; both indices are below `size`.
#[inline]
fn node(&self, i: usize, j: usize) -> f64 {
self.heights[j * self.config.size + i]
}
/// World coordinate to a fractional grid coordinate in `[0, size - 1]`.
fn grid_coordinate(&self, value: f64) -> f64 {
let last = (self.config.size - 1) as f64;
if value.is_nan() {
return 0.0;
}
let offset = value + self.config.extent * 0.5;
(offset / self.spacing()).clamp(0.0, last)
}
/// Bilinear interpolation in grid coordinates, which must be clamped.
fn height_at_grid(&self, gx: f64, gy: f64) -> f64 {
let last = self.config.size - 1;
let i0 = (gx.floor() as usize).min(last - 1);
let j0 = (gy.floor() as usize).min(last - 1);
let tx = gx - i0 as f64;
let ty = gy - j0 as f64;
let bottom_left = self.node(i0, j0);
let bottom_right = self.node(i0 + 1, j0);
let top_left = self.node(i0, j0 + 1);
let top_right = self.node(i0 + 1, j0 + 1);
// Exact at `t = 0` and `t = 1`, so node samples match the stored heights.
let bottom = bottom_left * (1.0 - tx) + bottom_right * tx;
let top = top_left * (1.0 - tx) + top_right * tx;
bottom * (1.0 - ty) + top * ty
}
}
/// The grid positions used for a difference at `position`, clamped to the map.
fn neighbours(position: f64, last: f64) -> (f64, f64) {
((position - 1.0).max(0.0), (position + 1.0).min(last))
}
/// Two counter-clockwise triangles per cell, joined into `u32` indices.
fn build_indices(nodes: usize) -> Vec<[u32; 3]> {
let cells = nodes.saturating_sub(1);
let mut indices = Vec::with_capacity(2 * cells * cells);
let row = nodes as u32;
for j in 0..cells {
for i in 0..cells {
let bottom_left = (j * nodes + i) as u32;
let bottom_right = bottom_left + 1;
let top_left = bottom_left + row;
let top_right = top_left + 1;
indices.push([bottom_left, bottom_right, top_right]);
indices.push([bottom_left, top_right, top_left]);
}
}
indices
}
/// A triangle mesh of the terrain surface, ready for a renderer or a collider.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TerrainMesh {
/// Vertex positions in world space, metres.
pub vertices: Vec<Vec3>,
/// Triangles, wound counter-clockwise when viewed from above (`+Z`).
pub indices: Vec<[u32; 3]>,
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,330 @@
use fabrilis_core::vec::Vec3;
use super::*;
/// FNV-1a over the little-endian bit patterns of the heights.
///
/// The bit patterns are used so the hash does not depend on the host endianness
/// or on formatting, only on the exact `f64` values (docs/DETERMINISM.md).
fn hash_heights(heights: &[f64]) -> u64 {
let mut hash: u64 = 0xCBF2_9CE4_8422_2325;
for height in heights {
for byte in height.to_bits().to_le_bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01B3);
}
}
hash
}
/// The reference map used by the sampling and mesh tests; its spacing (3.125 m)
/// and half extent (50 m) are exact binary values, so grid nodes land exactly.
fn reference_map() -> Heightmap {
let config = TerrainConfig {
seed: 42,
size: 33,
extent: 100.0,
height_scale: 10.0,
frequency: 2.0,
octaves: 4,
..TerrainConfig::default()
};
Heightmap::generate(config).expect("the reference config is valid")
}
fn flat_map() -> Heightmap {
let config = TerrainConfig {
height_scale: 0.0,
..TerrainConfig::default()
};
Heightmap::generate(config).expect("a zero height scale is valid")
}
#[test]
fn flat_terrain_has_zero_height_and_up_normals() {
let map = flat_map();
assert_eq!(map.heights().len(), map.size() * map.size());
for height in map.heights() {
assert_eq!(*height, 0.0);
}
for j in -5..=5 {
for i in -5..=5 {
let x = f64::from(i) * 12.5;
let y = f64::from(j) * 7.25;
assert_eq!(map.height_at(x, y), 0.0);
assert_eq!(map.normal_at(x, y), Vec3::Z);
}
}
}
#[test]
fn default_config_has_the_documented_values() {
let config = TerrainConfig::default();
assert_eq!(config.size, 64);
assert_eq!(config.extent, 100.0);
assert_eq!(config.height_scale, 10.0);
assert_eq!(config.frequency, 2.0);
assert_eq!(config.octaves, 4);
assert_eq!(config.lacunarity, 2.0);
assert_eq!(config.gain, 0.5);
assert_eq!(config.spacing(), 100.0 / 63.0);
}
#[test]
fn same_seed_reproduces_heights_bitwise() {
let first = reference_map();
let second = reference_map();
let left: Vec<u64> = first.heights().iter().map(|h| h.to_bits()).collect();
let right: Vec<u64> = second.heights().iter().map(|h| h.to_bits()).collect();
assert_eq!(left, right);
}
#[test]
fn different_seed_changes_heights() {
let other = Heightmap::generate(TerrainConfig {
seed: 43,
..reference_map().config
})
.expect("the config is valid");
assert_ne!(reference_map().heights(), other.heights());
}
#[test]
fn golden_height_hash_is_pinned() {
// This hash covers every height of the reference map. If it changes, the
// generator changed: regenerate the whole terrain, not just this constant.
// A deliberate algorithm change requires updating this value in the same
// commit and noting why in the commit message.
const GOLDEN: u64 = 0x9C4F_677D_8BE3_CCB8;
let actual = hash_heights(reference_map().heights());
assert_eq!(
actual, GOLDEN,
"golden height hash changed to {actual:#018x}"
);
}
#[test]
fn height_at_grid_nodes_returns_stored_heights_exactly() {
let map = reference_map();
let spacing = map.spacing();
let half = map.extent() * 0.5;
for j in 0..map.size() {
for i in 0..map.size() {
let x = i as f64 * spacing - half;
let y = j as f64 * spacing - half;
assert_eq!(map.height_at(x, y), map.heights()[j * map.size() + i]);
}
}
}
#[test]
fn midpoints_interpolate_bilinearly() {
let map = reference_map();
let spacing = map.spacing();
let half = map.extent() * 0.5;
let size = map.size();
for j in [0, 1, 15, size - 2] {
for i in [0, 1, 15, size - 2] {
let x = (i as f64 + 0.5) * spacing - half;
let y = (j as f64 + 0.5) * spacing - half;
let corners = map.heights()[j * size + i]
+ map.heights()[j * size + i + 1]
+ map.heights()[(j + 1) * size + i]
+ map.heights()[(j + 1) * size + i + 1];
let expected = corners * 0.25;
let actual = map.height_at(x, y);
assert!((actual - expected).abs() < 1e-12, "{actual} != {expected}");
}
}
}
#[test]
fn sampling_clamps_borders_and_non_finite_coordinates() {
let map = reference_map();
let last = map.size() - 1;
let low = map.height_at(-1e9, -1e9);
let high = map.height_at(1e9, 1e9);
assert_eq!(low, map.heights()[0]);
assert_eq!(high, map.heights()[last * map.size() + last]);
assert_eq!(map.height_at(f64::NAN, f64::NAN), low);
assert_eq!(map.height_at(f64::INFINITY, 0.0), map.height_at(1e9, 0.0));
assert_eq!(map.normal_at(f64::NAN, f64::NAN), map.normal_at(-1e9, -1e9));
}
#[test]
fn normal_points_against_the_gradient_and_is_a_unit_vector() {
let map = reference_map();
let spacing = map.spacing();
let half = map.extent() * 0.5;
let size = map.size();
// Find an interior node with a clear slope; flat spots have a zero gradient
// and would not exercise the direction check.
let (i, j) = (1..size - 1)
.flat_map(|j| (1..size - 1).map(move |i| (i, j)))
.find(|&(i, j)| {
let dx = map.heights()[j * size + i + 1] - map.heights()[j * size + i - 1];
let dy = map.heights()[(j + 1) * size + i] - map.heights()[(j - 1) * size + i];
dx.abs() + dy.abs() > 0.5
})
.expect("the reference map has a slope somewhere");
let x = i as f64 * spacing - half;
let y = j as f64 * spacing - half;
let slope_x =
(map.heights()[j * size + i + 1] - map.heights()[j * size + i - 1]) / (2.0 * spacing);
let slope_y =
(map.heights()[(j + 1) * size + i] - map.heights()[(j - 1) * size + i]) / (2.0 * spacing);
let normal = map.normal_at(x, y);
assert!((normal.length() - 1.0).abs() < 1e-12);
assert!(normal.z > 0.0);
assert!(
(normal.x + slope_x / (1.0 + slope_x * slope_x + slope_y * slope_y).sqrt()).abs() < 1e-12
);
assert!(
(normal.y + slope_y / (1.0 + slope_x * slope_x + slope_y * slope_y).sqrt()).abs() < 1e-12
);
assert!(normal.x * slope_x <= 0.0);
assert!(normal.y * slope_y <= 0.0);
}
fn triangle_z(vertices: &[Vec3], indices: &[u32; 3]) -> f64 {
let a = vertices[indices[0] as usize];
let b = vertices[indices[1] as usize];
let c = vertices[indices[2] as usize];
(b - a).cross(c - a).z
}
#[test]
fn mesh_has_grid_vertices_and_upward_triangles() {
let map = Heightmap::generate(TerrainConfig {
size: 9,
height_scale: 2.0,
..TerrainConfig::default()
})
.expect("the config is valid");
let mesh = map.mesh();
assert_eq!(mesh.vertices.len(), map.size() * map.size());
assert_eq!(mesh.indices.len(), 2 * (map.size() - 1) * (map.size() - 1));
for triangle in &mesh.indices {
assert!(triangle_z(&mesh.vertices, triangle) > 0.0);
}
for (index, vertex) in mesh.vertices.iter().enumerate() {
let i = index % map.size();
let j = index / map.size();
assert_eq!(vertex.z, map.heights()[j * map.size() + i]);
}
}
#[test]
fn mesh_with_step_halves_the_grid_and_keeps_winding() {
let map = reference_map();
let mesh = map.mesh_with_step(2);
let nodes = 17;
assert_eq!(mesh.vertices.len(), nodes * nodes);
assert_eq!(mesh.indices.len(), 2 * (nodes - 1) * (nodes - 1));
for triangle in &mesh.indices {
assert!(triangle_z(&mesh.vertices, triangle) > 0.0);
}
assert_eq!(map.mesh_with_step(0), map.mesh());
}
fn config_with(mutate: impl FnOnce(&mut TerrainConfig)) -> TerrainConfig {
let mut config = TerrainConfig::default();
mutate(&mut config);
config
}
#[test]
fn grid_extent_and_scale_errors_are_rejected() {
let cases = [
(
config_with(|config| config.size = 1),
TerrainError::SizeOutOfRange(1),
),
(
config_with(|config| config.size = MAX_SIZE + 1),
TerrainError::SizeOutOfRange(MAX_SIZE + 1),
),
(
config_with(|config| config.extent = 0.0),
TerrainError::InvalidExtent(0.0),
),
(
config_with(|config| config.extent = -5.0),
TerrainError::InvalidExtent(-5.0),
),
(
config_with(|config| config.height_scale = -1.0),
TerrainError::InvalidHeightScale(-1.0),
),
];
for (config, expected) in cases {
assert_eq!(Heightmap::generate(config).unwrap_err(), expected);
}
}
#[test]
fn noise_parameter_errors_are_rejected() {
let cases = [
(
config_with(|config| config.frequency = 0.0),
TerrainError::InvalidFrequency(0.0),
),
(
config_with(|config| config.frequency = f64::INFINITY),
TerrainError::InvalidFrequency(f64::INFINITY),
),
(
config_with(|config| config.octaves = 0),
TerrainError::OctavesOutOfRange(0),
),
(
config_with(|config| config.octaves = 9),
TerrainError::OctavesOutOfRange(9),
),
(
config_with(|config| config.lacunarity = 1.0),
TerrainError::InvalidLacunarity(1.0),
),
(
config_with(|config| config.gain = -0.5),
TerrainError::InvalidGain(-0.5),
),
(
config_with(|config| config.gain = 1.5),
TerrainError::InvalidGain(1.5),
),
];
for (config, expected) in cases {
assert_eq!(Heightmap::generate(config).unwrap_err(), expected);
}
}
#[test]
fn non_finite_parameter_payloads_are_rejected() {
// `NaN` is never equal to itself, so its payload is checked separately.
let nan_extent = Heightmap::generate(config_with(|config| config.extent = f64::NAN));
assert!(matches!(
nan_extent,
Err(TerrainError::InvalidExtent(value)) if value.is_nan()
));
let nan_gain = Heightmap::generate(config_with(|config| config.gain = f64::NAN));
assert!(matches!(
nan_gain,
Err(TerrainError::InvalidGain(value)) if value.is_nan()
));
let infinite_lacunarity =
Heightmap::generate(config_with(|config| config.lacunarity = f64::INFINITY));
assert!(matches!(
infinite_lacunarity,
Err(TerrainError::InvalidLacunarity(value)) if value.is_infinite()
));
}
#[test]
fn errors_implement_display_and_error() {
let error = TerrainError::SizeOutOfRange(0);
let text = error.to_string();
assert!(text.contains('0'));
let dynamic: &dyn std::error::Error = &error;
assert_eq!(dynamic.to_string(), text);
}