fabrilis/crates/worldgen/src/terrain/mod.rs
loki5512344 190ef9cc4b Add design persistence, world rendering, metrics overlay and logs
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.
2026-11-16 23:40:39 +01:00

349 lines
10 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! 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;