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

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

View file

@ -0,0 +1,269 @@
//! Chunked level of detail for the render terrain.
//!
//! [`Heightmap::mesh_lod`] still returns one [`TerrainMesh`], but the map is cut
//! into square chunks and each chunk keeps only every `step`-th grid node. The
//! step is a power of two chosen by the distance from the camera to the chunk
//! centre, so geometry near the camera keeps full resolution while distant
//! chunks cost far fewer triangles. Vertical skirts around each chunk hide the
//! cracks between neighbours with different steps.
//!
//! The collider is not reduced: physics keeps the full-resolution
//! [`Heightmap::mesh`]. This is the first LOD step; a ring or clipmap can follow
//! later without changing this API.
use fabrilis_core::math;
use fabrilis_core::vec::Vec3;
use super::{Heightmap, TerrainMesh};
/// Tuning for [`Heightmap::mesh_lod`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LodConfig {
/// Cells along one side of a chunk; `0` is treated as `1`.
pub chunk_cells: usize,
/// Largest node step between kept vertices; clamped to a power of two and
/// to the chunk size, and at least one.
pub max_step: usize,
/// Depth of the vertical skirts around every chunk, m; values below zero
/// are treated as zero and non-finite values as zero.
pub skirt_m: f64,
/// Distance from the camera at which the step doubles, m; values below one
/// are treated as one.
pub switch_m: f64,
}
impl Default for LodConfig {
/// 16-cell chunks, at most eight-node steps, one-metre skirts and a level
/// every 18 m.
fn default() -> Self {
Self {
chunk_cells: 16,
max_step: 8,
skirt_m: 1.0,
switch_m: 18.0,
}
}
}
/// One chunk of the LOD mesh: a node range in the height grid plus its step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LodChunk {
/// First node of the chunk along X and Y, in grid indices.
pub origin: [usize; 2],
/// Chunk size in cells along X and Y; the last chunk may be shorter.
pub cells: [usize; 2],
/// Kept-node step along both axes, a power of two.
pub step: usize,
}
impl Heightmap {
/// The chunks [`Self::mesh_lod`] would build, in row-major order.
///
/// The chunk grid depends only on `chunk_cells` and the map size; the
/// camera position only changes each chunk's [`LodChunk::step`]. Useful for
/// diagnostics and tests.
#[must_use]
pub fn lod_chunks(&self, center: Vec3, config: LodConfig) -> Vec<LodChunk> {
let chunk_cells = config.chunk_cells.max(1);
let total = self.size().saturating_sub(1);
let mut chunks = Vec::new();
let mut y0 = 0;
while y0 < total {
let cells_y = chunk_cells.min(total - y0);
let mut x0 = 0;
while x0 < total {
let cells_x = chunk_cells.min(total - x0);
let origin = [x0, y0];
let cells = [cells_x, cells_y];
let step = self.chunk_step(center, config, origin, cells);
chunks.push(LodChunk {
origin,
cells,
step,
});
x0 = x0.saturating_add(chunk_cells);
}
y0 = y0.saturating_add(chunk_cells);
}
chunks
}
/// A chunked LOD mesh for a camera at `center`; see [`LodConfig`].
///
/// The result is one [`TerrainMesh`] in world coordinates, wound
/// counter-clockwise from above like [`Self::mesh`]. Chunks near `center`
/// keep every node, farther chunks keep every second, fourth, ... node up to
/// `config.max_step`. Each chunk gets a vertical skirt `config.skirt_m` deep.
///
/// Parameters are clamped as documented on [`LodConfig`], so no input
/// panics, and two identical calls return bit-identical meshes.
#[must_use]
pub fn mesh_lod(&self, center: Vec3, config: LodConfig) -> TerrainMesh {
let skirt = if config.skirt_m.is_finite() {
config.skirt_m.max(0.0)
} else {
0.0
};
let mut mesh = TerrainMesh::default();
for chunk in self.lod_chunks(center, config) {
self.push_chunk(&mut mesh, &chunk, skirt);
}
mesh
}
/// The power-of-two step for one chunk, from the camera distance.
fn chunk_step(
&self,
center: Vec3,
config: LodConfig,
origin: [usize; 2],
cells: [usize; 2],
) -> usize {
let spacing = self.spacing();
let half = self.extent() * 0.5;
let chunk_x = (origin[0] as f64 + cells[0] as f64 * 0.5) * spacing - half;
let chunk_y = (origin[1] as f64 + cells[1] as f64 * 0.5) * spacing - half;
let dx = center.x - chunk_x;
let dy = center.y - chunk_y;
let distance = math::sqrt(dx * dx + dy * dy);
let cap = power_of_two_floor(config.max_step.max(1))
.min(power_of_two_floor(cells[0].min(cells[1]).max(1)));
if !distance.is_finite() {
return cap;
}
let switch = if config.switch_m.is_finite() {
config.switch_m.max(1.0)
} else {
1.0
};
let mut step = 1;
while step < cap && distance >= switch * step as f64 {
step *= 2;
}
step
}
/// Appends one chunk's surface and skirt to `mesh`.
fn push_chunk(&self, mesh: &mut TerrainMesh, chunk: &LodChunk, skirt: f64) {
let xs = node_line(chunk.origin[0], chunk.cells[0], chunk.step);
let ys = node_line(chunk.origin[1], chunk.cells[1], chunk.step);
let base = mesh.vertices.len();
let spacing = self.spacing();
let half = self.extent() * 0.5;
for &j in &ys {
let y = j as f64 * spacing - half;
for &i in &xs {
let x = i as f64 * spacing - half;
mesh.vertices.push(Vec3::new(x, y, self.node(i, j)));
}
}
mesh.indices.extend(build_indices(xs.len(), ys.len(), base));
if skirt > 0.0 {
push_skirt(mesh, base, xs.len(), ys.len(), skirt);
}
}
}
/// Largest power of two not above `value`, and at least one.
fn power_of_two_floor(value: usize) -> usize {
let mut result: usize = 1;
while result.saturating_mul(2) <= value {
result *= 2;
}
result
}
/// Two counter-clockwise triangles per cell of a `columns × rows` grid.
///
/// Indices are shifted by `base`, so several grids can share one vertex buffer.
pub(super) fn build_indices(columns: usize, rows: usize, base: usize) -> Vec<[u32; 3]> {
let cells_x = columns.saturating_sub(1);
let cells_y = rows.saturating_sub(1);
let mut indices = Vec::with_capacity(2 * cells_x * cells_y);
let shift = vertex_index(base);
for j in 0..cells_y {
for i in 0..cells_x {
let bottom_left = (j * columns + i) as u32 + shift;
let bottom_right = bottom_left + 1;
let top_left = bottom_left + columns as u32;
let top_right = top_left + 1;
indices.push([bottom_left, bottom_right, top_right]);
indices.push([bottom_left, top_right, top_left]);
}
}
indices
}
/// Grid nodes to keep along one chunk axis, always including the last node.
fn node_line(start: usize, cells: usize, step: usize) -> Vec<usize> {
let step = step.max(1);
let end = start + cells;
let mut line = Vec::with_capacity(cells / step + 2);
let mut index = start;
while index < end {
line.push(index);
index += step;
}
if line.last().copied() != Some(end) {
line.push(end);
}
line
}
/// Perimeter top vertices of a `columns × rows` chunk, counter-clockwise in XY.
fn perimeter(columns: usize, rows: usize) -> Vec<usize> {
let mut ring = Vec::with_capacity(2 * (columns + rows));
ring.extend(0..columns);
ring.extend((1..rows).map(|row| row * columns + columns - 1));
ring.extend(
(0..columns - 1)
.rev()
.map(|column| (rows - 1) * columns + column),
);
ring.extend((1..rows - 1).rev().map(|row| row * columns));
ring
}
/// Wall vertex index; the grid is capped at `MAX_SIZE²` vertices, so `u32` holds it.
fn vertex_index(value: usize) -> u32 {
value as u32
}
/// Appends a vertical skirt around the chunk surface that starts at `base`.
///
/// The ring is counter-clockwise, so `[top, bottom_next, top_next]` and
/// `[top, bottom, bottom_next]` face outwards. The walls start exactly at the
/// border nodes, so the top surface is not modified.
fn push_skirt(mesh: &mut TerrainMesh, base: usize, columns: usize, rows: usize, skirt: f64) {
if columns < 2 || rows < 2 {
return;
}
let ring = perimeter(columns, rows);
let bottom_base = mesh.vertices.len();
for &top in &ring {
let Some(vertex) = mesh.vertices.get(base + top).copied() else {
return;
};
mesh.vertices
.push(Vec3::new(vertex.x, vertex.y, vertex.z - skirt));
}
let count = ring.len();
for (edge, &top) in ring.iter().enumerate() {
let next = (edge + 1) % count;
let Some(&next_top) = ring.get(next) else {
continue;
};
let a_bottom = bottom_base + edge;
let b_bottom = bottom_base + next;
mesh.indices.push([
vertex_index(base + top),
vertex_index(b_bottom),
vertex_index(base + next_top),
]);
mesh.indices.push([
vertex_index(base + top),
vertex_index(a_bottom),
vertex_index(b_bottom),
]);
}
}

View file

@ -10,6 +10,10 @@ use fabrilis_core::vec::Vec3;
use crate::noise::{Noise, fbm};
mod lod;
pub use lod::{LodChunk, LodConfig};
/// Smallest accepted grid resolution; two nodes still form one cell.
const MIN_SIZE: usize = 2;
@ -259,7 +263,7 @@ impl Heightmap {
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);
let indices = lod::build_indices(nodes, nodes, 0);
TerrainMesh { vertices, indices }
}
@ -318,24 +322,6 @@ 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 {

View file

@ -328,3 +328,202 @@ fn errors_implement_display_and_error() {
let dynamic: &dyn std::error::Error = &error;
assert_eq!(dynamic.to_string(), text);
}
/// The flat map used by the LOD tests: same 65 nodes over 100 m as the window,
/// so every node coordinate is binary-exact.
fn lod_map() -> Heightmap {
Heightmap::generate(TerrainConfig {
size: 65,
extent: 100.0,
height_scale: 0.0,
..TerrainConfig::default()
})
.expect("the LOD test config is valid")
}
fn lod_config() -> LodConfig {
LodConfig {
chunk_cells: 16,
max_step: 8,
skirt_m: 1.0,
switch_m: 18.0,
}
}
/// The camera stands near the middle, off the grid centre.
fn lod_center() -> Vec3 {
Vec3::new(10.0, -16.0, 7.0)
}
/// The chunk that owns a cell; every cell belongs to exactly one chunk.
fn chunk_at(chunks: &[LodChunk], cell: [usize; 2]) -> &LodChunk {
chunks
.iter()
.find(|chunk| {
cell[0] >= chunk.origin[0]
&& cell[0] < chunk.origin[0] + chunk.cells[0]
&& cell[1] >= chunk.origin[1]
&& cell[1] < chunk.origin[1] + chunk.cells[1]
})
.expect("the cell belongs to a chunk")
}
#[test]
fn lod_mesh_stays_inside_the_map_and_uses_flat_heights_and_skirts() {
let map = lod_map();
let config = lod_config();
let mesh = map.mesh_lod(lod_center(), config);
assert!(!mesh.vertices.is_empty());
let half = map.extent() * 0.5;
for vertex in &mesh.vertices {
assert!(vertex.x.is_finite() && vertex.y.is_finite() && vertex.z.is_finite());
assert!(vertex.x >= -half && vertex.x <= half);
assert!(vertex.y >= -half && vertex.y <= half);
assert!(vertex.z == 0.0 || vertex.z == -config.skirt_m);
}
assert!(mesh.vertices.iter().any(|vertex| vertex.z == 0.0));
assert!(
mesh.vertices
.iter()
.any(|vertex| vertex.z == -config.skirt_m)
);
}
#[test]
fn lod_mesh_has_fewer_triangles_than_the_full_mesh() {
let map = lod_map();
let full = map.mesh();
let lod = map.mesh_lod(lod_center(), lod_config());
assert!(
lod.indices.len() < full.indices.len(),
"lod {} triangles, full {}",
lod.indices.len(),
full.indices.len()
);
}
#[test]
fn lod_mesh_is_deterministic() {
let map = lod_map();
let first = map.mesh_lod(lod_center(), lod_config());
let second = map.mesh_lod(lod_center(), lod_config());
assert_eq!(first.vertices.len(), second.vertices.len());
assert_eq!(first.indices.len(), second.indices.len());
for (left, right) in first.vertices.iter().zip(&second.vertices) {
assert_eq!(left.x.to_bits(), right.x.to_bits());
assert_eq!(left.y.to_bits(), right.y.to_bits());
assert_eq!(left.z.to_bits(), right.z.to_bits());
}
assert_eq!(first.indices, second.indices);
}
#[test]
fn lod_steps_grow_with_distance_from_the_camera() {
let map = lod_map();
let config = lod_config();
let chunks = map.lod_chunks(lod_center(), config);
for chunk in &chunks {
assert!(
chunk.step.is_power_of_two(),
"step {} is not a power of two",
chunk.step
);
assert!(chunk.step <= config.max_step);
assert!(chunk.step <= chunk.cells[0].min(chunk.cells[1]));
}
// The camera sits at grid (38.4, 21.8), in the chunk starting at (32, 16);
// the opposite corner is the farthest chunk.
let near = chunk_at(&chunks, [38, 21]);
let far = chunk_at(&chunks, [0, 0]);
assert_eq!(
near.step, 1,
"the chunk under the camera is full resolution"
);
assert!(
far.step > near.step,
"far step {} should exceed near step {}",
far.step,
near.step
);
}
#[test]
fn lod_chunks_cover_every_cell_exactly_once() {
let map = lod_map();
let config = lod_config();
let chunks = map.lod_chunks(lod_center(), config);
let cells = map.size() - 1;
let mut covered = vec![0u32; cells * cells];
for chunk in &chunks {
for j in chunk.origin[1]..chunk.origin[1] + chunk.cells[1] {
for i in chunk.origin[0]..chunk.origin[0] + chunk.cells[0] {
covered[j * cells + i] += 1;
}
}
}
assert!(covered.iter().all(|count| *count == 1));
assert_eq!(chunks.len(), 16, "four chunks per axis on a 64-cell map");
}
#[test]
fn lod_skirts_surround_every_chunk() {
let map = lod_map();
let config = lod_config();
let chunks = map.lod_chunks(lod_center(), config);
let mesh = map.mesh_lod(lod_center(), config);
let expected: usize = chunks
.iter()
.map(|chunk| {
let columns = chunk.cells[0].div_ceil(chunk.step) + 1;
let rows = chunk.cells[1].div_ceil(chunk.step) + 1;
2 * (columns + rows) - 4
})
.sum();
let bottom = mesh
.vertices
.iter()
.filter(|vertex| vertex.z == -config.skirt_m)
.count();
assert_eq!(bottom, expected);
}
#[test]
fn lod_triangles_face_up_or_are_vertical_walls() {
let map = lod_map();
let mesh = map.mesh_lod(lod_center(), lod_config());
let mut up = 0;
for triangle in &mesh.indices {
let area = triangle_z(&mesh.vertices, triangle);
assert!(area >= 0.0, "a triangle is wound downwards: {area}");
if area > 0.0 {
up += 1;
}
}
assert!(up > 0, "the surface has upward triangles");
assert!(up < mesh.indices.len(), "the walls are vertical");
}
#[test]
fn degenerate_lod_parameters_do_not_panic() {
let map = lod_map();
let config = LodConfig {
chunk_cells: 0,
max_step: 0,
skirt_m: -5.0,
switch_m: 0.0,
};
let mesh = map.mesh_lod(Vec3::new(f64::NAN, f64::INFINITY, 0.0), config);
assert!(!mesh.vertices.is_empty());
assert!(mesh.vertices.iter().all(|vertex| vertex.z == 0.0));
let tiny = Heightmap::generate(TerrainConfig {
size: 2,
extent: 10.0,
height_scale: 0.0,
..TerrainConfig::default()
})
.expect("a two-node map is valid");
for chunk in tiny.lod_chunks(Vec3::new(0.0, 0.0, 0.0), config) {
assert_eq!(chunk.step, 1);
}
assert!(!tiny.mesh_lod(Vec3::ZERO, config).indices.is_empty());
}