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

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