use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::TerminalEffect;
use crate::render::glyph_ramp::{self, GlyphRamp};
use crate::render::palette::Palette;
use crate::terrain::noise::PerlinNoise;
use crossterm::style;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TerrainOptions {
pub seed: u64,
pub scale: f64,
pub octaves: i32,
pub persistence: f64,
pub scroll_speed: f64,
pub relief: f64,
pub far_relief: f64,
pub parallax: f64,
pub glyphs: String,
}
impl Default for TerrainOptions {
fn default() -> Self {
Self {
seed: crate::common::DEFAULT_SEED,
scale: DEFAULT_SCALE,
octaves: 4,
persistence: 0.5,
scroll_speed: DEFAULT_SCROLL_SPEED,
relief: DEFAULT_RELIEF,
far_relief: DEFAULT_FAR_RELIEF,
parallax: DEFAULT_PARALLAX,
glyphs: DEFAULT_GLYPHS.to_string(),
}
}
}
const DEFAULT_SCALE: f64 = 8.0;
const DEFAULT_SCROLL_SPEED: f64 = 0.9;
const DEFAULT_RELIEF: f64 = 1.0;
const DEFAULT_FAR_RELIEF: f64 = 0.5;
const DEFAULT_PARALLAX: f64 = 0.35;
const FAR_SEED_SALT: u64 = 0xFA4_2AD1_5A9D_0001;
const FAR_OCTAVES: i32 = 2;
const FAR_RIDGE_FRACTION: f64 = 0.16;
const _: () = assert!(
FAR_RIDGE_FRACTION < HORIZON_FRACTION,
"the far ridge must sit above the near one, or the dim layer is drawn in front \
of the bright one and the picture inverts"
);
const NEAR_LIT: style::Color = style::Color::Rgb {
r: 226,
g: 232,
b: 242,
};
const FAR_FILL: style::Color = style::Color::Rgb {
r: 58,
g: 74,
b: 104,
};
const FAR_LIT: style::Color = style::Color::Rgb {
r: 104,
g: 124,
b: 158,
};
const GROUND: &[style::Color] = &[
style::Color::Rgb {
r: 148,
g: 156,
b: 170,
},
style::Color::Rgb {
r: 112,
g: 120,
b: 134,
},
style::Color::Rgb {
r: 82,
g: 88,
b: 100,
},
style::Color::Rgb {
r: 62,
g: 67,
b: 78,
},
];
const MAX_RELIEF_FRACTION: f64 = 0.45;
const DEFAULT_GLYPHS: &str = ".:-=+*#%@";
const HORIZON_FRACTION: f64 = 0.32;
const SKY: &[style::Color] = &[
style::Color::Rgb { r: 6, g: 8, b: 26 },
style::Color::Rgb {
r: 26,
g: 44,
b: 84,
},
style::Color::Rgb {
r: 126,
g: 148,
b: 186,
},
];
fn glyph_ramp(configured: &str) -> GlyphRamp {
let glyphs: Vec<char> = configured
.chars()
.filter(|glyph| {
!glyph.is_control() && glyph_ramp::is_ambiguous_or_narrow(*glyph)
})
.collect();
if glyphs.is_empty() {
GlyphRamp::from_text(DEFAULT_GLYPHS)
} else {
GlyphRamp::new(glyphs)
}
}
pub struct Terrain {
pub screen_size: (u16, u16),
options: TerrainOptions,
canvas: Canvas,
near_noise: PerlinNoise,
far_noise: PerlinNoise,
ramp: GlyphRamp,
sky: Palette,
ground: Palette,
offset: f64,
}
impl TerminalEffect for Terrain {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.canvas.clear();
self.render(self.offset);
self.canvas.commit()
}
fn update(&mut self) {
self.advance(1.0 / 60.0);
}
fn update_with_context(&mut self, context: &crate::runtime::FrameContext) {
self.advance(context.delta.as_secs_f64());
}
fn update_size(&mut self, width: u16, height: u16) {
self.screen_size = (width, height);
self.canvas.resize(self.screen_size.0, self.screen_size.1);
self.reset();
}
fn reset(&mut self) {
self.canvas
.resize(self.screen_size.0.max(1), self.screen_size.1.max(1));
self.near_noise = PerlinNoise::new(self.options.seed);
self.far_noise = PerlinNoise::new(self.options.seed ^ FAR_SEED_SALT);
self.offset = 0.0;
}
}
impl Terrain {
pub fn new(options: TerrainOptions, screen_size: (u16, u16)) -> Self {
let canvas = Canvas::new(screen_size.0, screen_size.1);
let near_noise = PerlinNoise::new(options.seed);
let far_noise = PerlinNoise::new(options.seed ^ FAR_SEED_SALT);
Self {
screen_size,
ramp: glyph_ramp(&options.glyphs),
sky: Palette::new(SKY.to_vec()),
ground: Palette::new(GROUND.to_vec()),
offset: 0.0,
options,
canvas,
near_noise,
far_noise,
}
}
fn advance(&mut self, delta: f64) {
self.offset += self.options.scroll_speed * delta;
}
fn parallax_rate(&self) -> f64 {
if self.options.parallax.is_finite() {
self.options.parallax.max(0.0)
} else {
DEFAULT_PARALLAX
}
}
fn far_offset(&self) -> f64 {
self.offset * self.parallax_rate()
}
fn surface_row(
&self,
noise: &PerlinNoise,
octaves: i32,
x: usize,
offset: f64,
centre: usize,
span: f64,
) -> usize {
let period = Self::noise_period(self.options.scale);
let travelled = x as f64 + offset;
let raw = noise.octave_noise_2d(
travelled,
0.0,
octaves,
self.options.persistence,
1.0 / period,
);
let row = centre as f64 - raw * span;
let (low, high) = Self::surface_bounds(self.screen_size.1 as usize);
(row.round().clamp(low as f64, high as f64)) as usize
}
fn surface_bounds(height: usize) -> (usize, usize) {
if height <= 1 {
return (0, 0);
}
if height == 2 {
return (1, 1);
}
(1, height - 2)
}
fn surface_span(&self, relief: f64, horizon: usize) -> f64 {
let period = Self::noise_period(self.options.scale);
let relief = if relief.is_finite() {
relief.max(0.0)
} else {
DEFAULT_RELIEF
};
let height = self.screen_size.1 as usize;
let ground_rows = height.saturating_sub(horizon).max(1) as f64;
(period * relief).min(ground_rows * MAX_RELIEF_FRACTION)
}
fn noise_period(scale: f64) -> f64 {
if scale.is_finite() && scale > 0.0 {
scale
} else {
DEFAULT_SCALE
}
}
#[cfg(test)]
fn noise_frequency(scale: f64) -> f64 {
1.0 / Self::noise_period(scale)
}
fn horizon_row(size: (u16, u16)) -> usize {
let height = size.1 as usize;
if height <= 1 {
return 0;
}
let horizon = (height as f64 * HORIZON_FRACTION).round() as usize;
horizon.clamp(1, height - 1)
}
fn far_ridge_row(size: (u16, u16)) -> usize {
let height = size.1 as usize;
if height <= 1 {
return 0;
}
let row = (height as f64 * FAR_RIDGE_FRACTION).round() as usize;
row.clamp(1, Self::horizon_row(size))
}
#[cfg(test)]
fn silhouette_density(size: (u16, u16)) -> f64 {
let terrain = Terrain::new(TerrainOptions::default(), size);
let rows = terrain.near_surface_rows(0.0);
if rows.len() < 2 {
return 0.0;
}
let steps = rows.windows(2).filter(|w| w[0] != w[1]).count();
steps as f64 / (rows.len() - 1) as f64
}
fn near_surface_rows(&self, offset: f64) -> Vec<usize> {
let centre = Self::horizon_row(self.screen_size);
let span = self.surface_span(self.options.relief, centre);
let noise = &self.near_noise;
let octaves = self.options.octaves;
(0..self.screen_size.0 as usize)
.map(|x| self.surface_row(noise, octaves, x, offset, centre, span))
.collect()
}
fn far_surface_rows(&self, offset: f64) -> Vec<usize> {
let centre = Self::far_ridge_row(self.screen_size);
let span = self.surface_span(self.options.far_relief, centre);
let noise = &self.far_noise;
(0..self.screen_size.0 as usize)
.map(|x| self.surface_row(noise, FAR_OCTAVES, x, offset, centre, span))
.collect()
}
fn render(&mut self, offset: f64) {
let size = self.screen_size;
let width = size.0 as usize;
let height = size.1 as usize;
if width == 0 || height == 0 {
return;
}
let horizon = Self::horizon_row(size);
let near_rows = self.near_surface_rows(offset);
let far_rows = self.far_surface_rows(self.far_offset());
let ground_depth = height.saturating_sub(horizon).max(1) as f32;
let lit_glyph = self.ramp.sample(1.0);
let far_glyph = self.ramp.sample(0.0);
let surface = self.canvas.surface_mut();
for y in 0..height {
let sky_colour = Self::sky_colour(y, horizon, &self.sky);
for x in 0..width {
let near_top = near_rows[x];
let far_top = far_rows[x];
let cell = if y < near_top.min(far_top) {
Cell::new(' ', sky_colour, style::Attribute::Reset)
} else if y < near_top {
let colour = if y == far_top { FAR_LIT } else { FAR_FILL };
Cell::new(far_glyph, colour, style::Attribute::Reset)
} else if y == near_top {
Cell::new(lit_glyph, NEAR_LIT, style::Attribute::Reset)
} else {
let depth =
((y - near_top) as f32 / ground_depth).clamp(0.0, 1.0);
Cell::new(
self.ramp.sample(depth),
self.ground.sample(depth),
style::Attribute::Reset,
)
};
surface.set(x, y, cell);
}
}
}
fn sky_colour(y: usize, horizon: usize, sky: &Palette) -> style::Color {
let t = (y as f32 / (horizon.max(1) - 1) as f32).clamp(0.0, 1.0);
sky.sample(t * HORIZON_SKY_FRACTION)
}
}
const HORIZON_SKY_FRACTION: f32 = 0.72;
#[cfg(test)]
mod tests {
use super::*;
use std::collections::{BTreeMap, HashSet};
fn luminance(colour: style::Color) -> f32 {
match colour {
style::Color::Rgb { r, g, b } => {
0.2126 * f32::from(r)
+ 0.7152 * f32::from(g)
+ 0.0722 * f32::from(b)
}
_ => f32::NAN,
}
}
const TONE_CONTRAST: f32 = 1.25;
fn is_brighter(lit: style::Color, under: style::Color) -> bool {
luminance(lit) > luminance(under) * TONE_CONTRAST
}
fn surface(size: (u16, u16)) -> Vec<usize> {
Terrain::new(TerrainOptions::default(), size).near_surface_rows(0.0)
}
fn far_surface(size: (u16, u16)) -> Vec<usize> {
Terrain::new(TerrainOptions::default(), size).far_surface_rows(0.0)
}
fn mean_frame_diff(size: (u16, u16), frames: u64) -> f64 {
let mut terrain = Terrain::new(TerrainOptions::default(), size);
terrain.get_diff();
let mut total = 0usize;
for _ in 0..frames {
terrain.advance(1.0 / 60.0);
total += terrain.get_diff().len();
}
total as f64 / frames as f64
}
struct Frame {
glyphs: Vec<Vec<char>>,
colours: BTreeMap<(usize, usize), style::Color>,
near: Vec<usize>,
far: Vec<usize>,
}
impl Frame {
fn new(size: (u16, u16), frames: u64) -> Self {
let mut terrain = Terrain::new(TerrainOptions::default(), size);
for _ in 0..frames {
terrain.advance(1.0 / 60.0);
}
Self::with(&mut terrain)
}
fn with(terrain: &mut Terrain) -> Self {
let size = terrain.screen_size;
let near = terrain.near_surface_rows(terrain.offset);
let far = terrain.far_surface_rows(terrain.far_offset());
let mut glyphs = vec![vec![' '; size.0 as usize]; size.1 as usize];
let mut colours = BTreeMap::new();
for (x, y, cell) in terrain.get_diff() {
glyphs[y][x] = cell.symbol;
colours.insert((x, y), cell.color);
}
Self {
glyphs,
colours,
near,
far,
}
}
fn glyph(&self, x: usize, y: usize) -> char {
self.glyphs[y][x]
}
fn colour(&self, x: usize, y: usize) -> style::Color {
self.colours
.get(&(x, y))
.copied()
.unwrap_or(style::Color::Reset)
}
fn far_visible_fraction(&self) -> f64 {
let width = self.near.len();
if width == 0 {
return 0.0;
}
let shown = self
.far
.iter()
.zip(&self.near)
.filter(|(far, near)| far < near)
.count();
shown as f64 / width as f64
}
}
#[test]
fn there_is_a_surface_and_it_is_not_a_straight_line() {
for size in [(80u16, 24u16), (200, 50), (400, 200)] {
for (label, rows, minimum) in [
("near", surface(size), 3usize),
("far", far_surface(size), 2),
] {
assert_eq!(
rows.len(),
size.0 as usize,
"every column needs a {label} surface row"
);
let low = *rows.iter().min().unwrap();
let high = *rows.iter().max().unwrap();
assert!(
high - low >= minimum,
"at {}x{} the {label} surface spans only {} rows, from {low} to \
{high}, so the top of that ridge is a straight line and there \
is no landscape in the picture",
size.0,
size.1,
high - low
);
}
}
}
#[test]
fn the_ground_reaches_the_bottom_row_in_every_column() {
for size in [
(80u16, 24u16),
(200, 50),
(400, 200),
(1, 9),
(9, 3),
(6, 6),
(20, 8),
] {
let height = size.1 as usize;
for (label, rows) in
[("near", surface(size)), ("far", far_surface(size))]
{
for (x, &top) in rows.iter().enumerate() {
assert!(
top < height,
"at {}x{} column {x} has its {label} surface at row {top} of \
{height}, so that column has no ground at all",
size.0,
size.1
);
}
}
}
}
#[test]
fn every_column_keeps_at_least_one_row_of_sky() {
for size in [(80u16, 24u16), (200, 50), (400, 200), (1, 9), (9, 3)] {
for (label, rows) in
[("near", surface(size)), ("far", far_surface(size))]
{
for (x, &top) in rows.iter().enumerate() {
assert!(
top >= 1,
"at {}x{} column {x} has its {label} surface at row {top}, so \
that column has no sky",
size.0,
size.1
);
}
}
}
}
#[test]
fn no_ground_is_drawn_above_its_own_columns_surface() {
let size = (80u16, 24u16);
let frame = Frame::new(size, 0);
for x in 0..size.0 as usize {
let highest = frame.far[x].min(frame.near[x]);
for y in 0..highest {
let cell = frame.glyph(x, y);
assert_eq!(
cell, ' ',
"at ({x}, {y}) the ground starts at row {highest} -- the far \
ridge is on {} and the near one on {} -- but this cell was \
drawn as {cell:?}",
frame.far[x], frame.near[x]
);
}
}
}
#[test]
fn every_column_is_sky_then_far_then_near_and_stops_there() {
for size in [(80u16, 24u16), (200, 50), (400, 200), (20, 8)] {
let frame = Frame::new(size, 0);
let height = size.1 as usize;
for x in 0..size.0 as usize {
let (far, near) = (frame.far[x], frame.near[x]);
for y in 0..height {
let colour = frame.colour(x, y);
if y >= near && y > near {
assert!(
colour != FAR_FILL && colour != FAR_LIT,
"at {}x{} cell ({x}, {y}) is below the near surface on row \
{near} but was drawn in the far layer's colour, so the \
near ridge is not occluding the far one",
size.0,
size.1
);
assert!(
is_brighter(NEAR_LIT, colour),
"at {}x{} cell ({x}, {y}) in the near fill is at {} against \
a lit rim at {}, so the fill is as bright as its own rim",
size.0,
size.1,
luminance(colour),
luminance(NEAR_LIT)
);
continue;
}
let (expected, band) = if y < far.min(near) {
assert_eq!(
frame.glyph(x, y),
' ',
"at {}x{} cell ({x}, {y}) is above both surfaces and was \
drawn as {:?} rather than sky",
size.0,
size.1,
frame.glyph(x, y)
);
continue;
} else if y < near {
(if y == far { FAR_LIT } else { FAR_FILL }, "far")
} else {
(NEAR_LIT, "near")
};
assert_eq!(
colour, expected,
"at {}x{} cell ({x}, {y}) belongs to the {band} band -- the \
far ridge is on {far} and the near one on {near} -- and was \
drawn in the other one",
size.0, size.1
);
}
}
}
}
#[test]
fn the_relief_is_not_so_flat_that_the_ground_is_a_slab() {
for size in [(80u16, 24u16), (200, 50), (400, 200)] {
let density = Terrain::silhouette_density(size);
assert!(
(0.05..0.75).contains(&density),
"at {}x{} the surface moves between only {:.1}% of adjacent \
columns, so the top of the ground is a straight line. Above \
about 75% it is a picket fence instead.",
size.0,
size.1,
density * 100.0
);
}
}
#[test]
fn relief_zero_is_a_slab_and_more_relief_moves_the_surface_more() {
let spread_at = |relief: f64| {
let options = TerrainOptions {
relief,
..Default::default()
};
let rows = Terrain::new(options, (80, 24)).near_surface_rows(0.0);
rows.iter().max().unwrap() - rows.iter().min().unwrap()
};
assert_eq!(
spread_at(0.0),
0,
"with no relief every column's surface is on the same row, so the \
ground is a rectangle with a ruler along the top"
);
let half = spread_at(0.5);
let full = spread_at(DEFAULT_RELIEF);
assert!(
half >= 2,
"half the relief gave a spread of only {half} rows"
);
assert!(
full > half,
"the default relief {DEFAULT_RELIEF} spread the surface {full} rows \
against {half} at half, so the knob is not reaching the surface row"
);
let huge = spread_at(50.0);
assert_eq!(
huge, full,
"relief 50 spread the surface {huge} rows against {full} at the \
default, so the amplitude is not capped and a large relief would \
drive the surface off the screen"
);
}
#[test]
fn far_relief_reaches_the_far_ridge_and_is_capped_like_the_near_one() {
let spread_at = |far_relief: f64| {
let options = TerrainOptions {
far_relief,
..Default::default()
};
let rows = Terrain::new(options, (80, 24)).far_surface_rows(0.0);
rows.iter().max().unwrap() - rows.iter().min().unwrap()
};
assert_eq!(
spread_at(0.0),
0,
"with no far_relief every column's far surface is on the same row, so \
the distant layer is a band with a ruler along the top"
);
let quarter = spread_at(DEFAULT_FAR_RELIEF / 2.0);
let default = spread_at(DEFAULT_FAR_RELIEF);
assert!(
default >= 2,
"the default far_relief {DEFAULT_FAR_RELIEF} spread the far surface only \
{default} rows, so the distant layer has no shape in it"
);
assert!(
default > quarter,
"the default far_relief spread the far surface {default} rows against \
{quarter} at half of it, so the knob is not reaching the far surface"
);
let capped = spread_at(2.0);
assert_eq!(
spread_at(50.0),
capped,
"far_relief 50 spread the far surface differently from far_relief 2, so \
the amplitude is not capped and a large far_relief would drive the \
distant layer off the top of the screen"
);
assert!(
capped > default,
"past the cap the far surface spread {capped} rows against {default} at \
the default, so the cap is not binding where it should"
);
}
#[test]
fn the_landscape_has_the_same_shape_at_every_screen_height() {
let density = |size: (u16, u16)| {
let options = TerrainOptions {
relief: 0.5,
..Default::default()
};
let rows = Terrain::new(options, size).near_surface_rows(0.0);
let steps = rows.windows(2).filter(|w| w[0] != w[1]).count();
steps as f64 / (rows.len() - 1) as f64
};
let short = density((200, 24));
let tall = density((200, 200));
assert!(
(short - tall).abs() < 0.05,
"the same relief gave {short:.3} step density on a 24 row screen and \
{tall:.3} on a 200 row one, so the landscape changes shape with the \
terminal"
);
}
#[test]
fn a_degenerate_relief_falls_back_rather_than_drawing_nothing() {
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -3.0, 7.0] {
let options = TerrainOptions {
relief: bad,
..Default::default()
};
let terrain = Terrain::new(options, (80, 24));
let span = terrain.surface_span(bad, Terrain::horizon_row((80, 24)));
assert!(
span.is_finite() && span >= 0.0,
"relief {bad} produced a surface span of {span}"
);
}
}
#[test]
fn a_degenerate_far_relief_or_parallax_falls_back_rather_than_drawing_nothing()
{
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -3.0, 7.0] {
let terrain = Terrain::new(
TerrainOptions {
far_relief: bad,
..Default::default()
},
(80, 24),
);
let span = terrain.surface_span(bad, Terrain::far_ridge_row((80, 24)));
assert!(
span.is_finite() && span >= 0.0,
"far_relief {bad} produced a surface span of {span}"
);
let terrain = Terrain::new(
TerrainOptions {
parallax: bad,
..Default::default()
},
(80, 24),
);
let rate = terrain.parallax_rate();
assert!(
rate.is_finite() && rate >= 0.0,
"parallax {bad} produced a rate of {rate}"
);
assert!(
terrain.far_offset().is_finite(),
"parallax {bad} produced a far offset of {}",
terrain.far_offset()
);
}
let terrain = Terrain::new(
TerrainOptions {
parallax: f64::NAN,
..Default::default()
},
(80, 24),
);
assert_eq!(
terrain.parallax_rate(),
DEFAULT_PARALLAX,
"a NaN parallax did not fall back to the documented default"
);
}
#[test]
fn the_ground_gets_darker_with_depth() {
let luminance = |c: style::Color| match c {
style::Color::Rgb { r, g, b } => {
0.2126 * f32::from(r)
+ 0.7152 * f32::from(g)
+ 0.0722 * f32::from(b)
}
_ => f32::NAN,
};
for size in [(80u16, 24u16), (200, 50)] {
let rows = surface(size);
let frame = Frame::new(size, 0);
let deep_columns: Vec<usize> = rows
.iter()
.enumerate()
.filter(|&(_, &top)| top < size.1 as usize / 2)
.map(|(x, _)| x)
.collect();
assert!(
deep_columns.len() > size.0 as usize / 4,
"at {}x{} only {} columns have room for a ground body, so there is \
nothing to compare",
size.0,
size.1,
deep_columns.len()
);
for &x in &deep_columns {
let top = rows[x];
let shallow = frame.colour(x, top);
let deepest = frame.colour(x, size.1 as usize - 1);
assert!(
is_brighter(shallow, deepest),
"at {}x{} column {x} is {} at the surface and {} at the bottom, \
so the ground does not get darker going down",
size.0,
size.1,
luminance(shallow),
luminance(deepest)
);
}
}
}
#[test]
fn the_two_ridges_are_two_landscapes_and_not_one_twice() {
fn correlation(a: &[f64], b: &[f64]) -> f64 {
let n = a.len() as f64;
let mean_a = a.iter().sum::<f64>() / n;
let mean_b = b.iter().sum::<f64>() / n;
let covariance: f64 = a
.iter()
.zip(b)
.map(|(x, y)| (x - mean_a) * (y - mean_b))
.sum();
let spread_a: f64 = a.iter().map(|x| (x - mean_a).powi(2)).sum();
let spread_b: f64 = b.iter().map(|y| (y - mean_b).powi(2)).sum();
covariance / (spread_a * spread_b).sqrt()
}
let size = (400u16, 50u16);
let frame = Frame::new(size, 0);
let near: Vec<f64> = frame.near.iter().map(|&r| r as f64).collect();
let far: Vec<f64> = frame.far.iter().map(|&r| r as f64).collect();
let worst = (-24i64..=24)
.map(|shift| {
let distance = shift.unsigned_abs() as usize;
let base = if shift < 0 {
0..far.len() - distance
} else {
distance..far.len()
};
let shifted: Vec<f64> = far[distance..].to_vec();
correlation(&near[base], &shifted).abs()
})
.fold(0.0f64, f64::max);
assert!(
worst < 0.5,
"the far ridge's profile correlates with the near one's at {worst:.2} at \
the worst of 49 horizontal shifts, so the two layers are the same \
landscape drawn twice rather than two landscapes"
);
}
#[test]
fn the_far_ridge_is_drawn_across_the_frame_at_the_default_settings() {
for size in [(80u16, 24u16), (200, 50), (400, 200), (6, 6), (20, 8)] {
let frame = Frame::new(size, 0);
let visible = frame.far_visible_fraction();
assert!(
visible > 0.5,
"at {}x{} the far ridge is above the near one in only {:.0}% of \
columns, so the second layer is a scrap at one edge of the frame",
size.0,
size.1,
visible * 100.0
);
}
}
#[test]
fn a_far_ridge_above_the_near_one_is_occluded_rather_than_drawn_over_it() {
let size = (200u16, 50u16);
let options = TerrainOptions {
relief: 6.0,
far_relief: 6.0,
..Default::default()
};
let mut terrain = Terrain::new(options, size);
let near = terrain.near_surface_rows(0.0);
let far = terrain.far_surface_rows(0.0);
let height = size.1 as usize;
let occluded = far.iter().zip(&near).filter(|(f, n)| **f > **n).count();
assert!(
occluded > 0,
"no column has the far ridge behind the near one, so this \
configuration did not reach the occlusion path at all"
);
let painted = Frame::with(&mut terrain);
for (x, (&far, &near)) in far.iter().zip(&near).enumerate() {
for y in near..height {
let colour = painted.colour(x, y);
assert_ne!(
colour, FAR_FILL,
"cell ({x}, {y}) is below the near surface on row {near} and the \
far surface is on {far}, so the near ridge is in front, but the \
cell was drawn in the far layer's fill"
);
assert_ne!(
colour, FAR_LIT,
"cell ({x}, {y}) is below the near surface on row {near} but was \
drawn in the far layer's lit edge"
);
}
}
}
#[test]
fn each_ridge_is_lit_along_its_own_edge_and_the_rim_is_brighter_than_its_fill()
{
for size in [(80u16, 24u16), (200, 50), (400, 200)] {
let frame = Frame::new(size, 0);
let height = size.1 as usize;
for (x, (&near, &far)) in frame.near.iter().zip(&frame.far).enumerate()
{
assert_eq!(
frame.colour(x, near),
NEAR_LIT,
"at {}x{} column {x} has its near surface on row {near}, and that \
row is the lit edge, but it was not drawn in the rim colour",
size.0,
size.1
);
if near + 1 < height {
assert!(
is_brighter(NEAR_LIT, frame.colour(x, near + 1)),
"at {}x{} column {x} has a rim at {} and the row under it at \
{}, so the rim is not {}x brighter than its own fill",
size.0,
size.1,
luminance(NEAR_LIT),
luminance(frame.colour(x, near + 1)),
TONE_CONTRAST
);
}
if far < near {
assert_eq!(
frame.colour(x, far),
FAR_LIT,
"at {}x{} column {x} shows the far ridge from row {far}, and \
that row is its lit edge, but it was not drawn in the far \
rim colour",
size.0,
size.1
);
if far + 1 < near {
assert!(
is_brighter(FAR_LIT, frame.colour(x, far + 1)),
"at {}x{} the far rim in column {x} is at {} and the row \
under it at {}, so the far rim is not {}x brighter than \
the far layer's own fill",
size.0,
size.1,
luminance(FAR_LIT),
luminance(frame.colour(x, far + 1)),
TONE_CONTRAST
);
}
}
}
}
}
#[test]
fn the_layer_tones_are_ordered_far_fill_far_rim_near_rim_near_fill() {
let size = (200u16, 50u16);
let frame = Frame::new(size, 0);
let height = size.1 as usize;
let mut brightest_fill = f32::NEG_INFINITY;
for (x, (&near, &far)) in frame.near.iter().zip(&frame.far).enumerate() {
if far < near {
for y in (far + 1)..near {
brightest_fill =
brightest_fill.max(luminance(frame.colour(x, y)));
}
}
for y in (near + 1)..height {
brightest_fill = brightest_fill.max(luminance(frame.colour(x, y)));
}
}
assert!(
is_brighter(FAR_LIT, FAR_FILL),
"the far layer's fill is at {} against its own rim at {}, so the distant \
ridge has no edge",
luminance(FAR_FILL),
luminance(FAR_LIT)
);
assert!(
is_brighter(NEAR_LIT, FAR_LIT),
"the far rim is at {} against the near rim at {}, so the two ridges do \
not separate by brightness",
luminance(FAR_LIT),
luminance(NEAR_LIT)
);
assert!(
brightest_fill > luminance(FAR_FILL) * TONE_CONTRAST,
"the far fill is at {} against the brightest cell of the near ground at \
{brightest_fill:.0}, so the distant layer competes with the one in front \
of it",
luminance(FAR_FILL)
);
assert!(
luminance(NEAR_LIT) > brightest_fill * TONE_CONTRAST,
"the brightest cell of the near ground is at {brightest_fill:.0} against a \
rim at {}, so the near ridge has no edge",
luminance(NEAR_LIT)
);
}
#[test]
fn the_ground_is_one_unbroken_run_from_its_surface_to_the_bottom() {
for size in [(80u16, 24u16), (200, 50), (400, 200), (20, 8)] {
let frame = Frame::new(size, 0);
let height = size.1 as usize;
for (x, &top) in frame.near.iter().enumerate() {
let first = (0..height)
.find(|&y| frame.glyph(x, y) != ' ')
.unwrap_or(height);
assert_eq!(
first,
frame.far[x].min(top),
"at {}x{} column {x} draws its first ground cell on row {first}, \
but the far surface is on {} and the near one on {top}",
size.0,
size.1,
frame.far[x]
);
for y in top..height {
assert_ne!(
frame.glyph(x, y),
' ',
"at {}x{} cell ({x}, {y}) is below the near surface on row \
{top} but drew as a space, so the ground has a hole in it",
size.0,
size.1
);
}
}
}
}
#[test]
fn neither_ridge_is_a_flat_constant_row() {
for size in [(80u16, 24u16), (200, 50), (400, 200)] {
let frame = Frame::new(size, 0);
let height = size.1 as usize;
let mut near_tops: HashSet<usize> = HashSet::new();
let mut far_tops: HashSet<usize> = HashSet::new();
for x in 0..size.0 as usize {
if let Some(first) = (0..height).find(|&y| frame.glyph(x, y) != ' ')
{
near_tops.insert(first);
if frame.far[x] < frame.near[x] {
far_tops.insert(frame.far[x]);
}
}
}
assert!(
near_tops.len() >= 3,
"at {}x{} the top edge of the near ground sits on only {} distinct \
rows, so it is a straight line and there is no landscape in the \
picture",
size.0,
size.1,
near_tops.len()
);
assert!(
far_tops.len() >= 3,
"at {}x{} the top edge of the far ridge sits on only {} distinct \
rows, so the distant layer is a band with a ruler along the top",
size.0,
size.1,
far_tops.len()
);
}
}
#[test]
fn the_far_ridge_scrolls_more_slowly_than_the_near_one() {
fn best_shift(before: &[usize], after: &[usize], limit: i64) -> f64 {
let mean_error = |shift: i64| -> f64 {
let (mut total, mut pairs) = (0.0, 0.0);
for (x, &row) in before.iter().enumerate() {
let moved = x as i64 + shift;
if moved < 0 || moved >= after.len() as i64 {
continue;
}
let difference = row as f64 - after[moved as usize] as f64;
total += difference * difference;
pairs += 1.0;
}
total / pairs
};
let mut best = 0;
let mut best_error = f64::INFINITY;
for shift in -limit..=limit {
let error = mean_error(shift);
if error < best_error {
best_error = error;
best = shift;
}
}
let (left, middle, right) =
(mean_error(best - 1), mean_error(best), mean_error(best + 1));
let curvature = left - 2.0 * middle + right;
if curvature <= 0.0 {
return best as f64;
}
best as f64 + 0.5 * (left - right) / curvature
}
let size = (200u16, 50u16);
let options = TerrainOptions::default();
let seconds = 9.0;
let frames = (seconds * 60.0) as u64;
let mut terrain = Terrain::new(options.clone(), size);
let near_before = terrain.near_surface_rows(0.0);
let far_before = terrain.far_surface_rows(0.0);
for _ in 0..frames {
terrain.advance(1.0 / 60.0);
}
let near_after = terrain.near_surface_rows(terrain.offset);
let far_after = terrain.far_surface_rows(terrain.far_offset());
let limit = 12i64;
let near_shift = best_shift(&near_before, &near_after, limit);
let far_shift = best_shift(&far_before, &far_after, limit);
for (label, shift) in [("near", near_shift), ("far", far_shift)] {
assert!(
shift.abs() < limit as f64 - 1.0,
"the {label} ridge's best-matching shift is {shift:.2} cells, which is \
at the edge of the -{limit}..={limit} range that was searched, so the \
measurement is a fact about the range rather than about the picture"
);
}
let expected = options.scroll_speed * seconds;
assert!(
(near_shift + expected).abs() < 0.5,
"the near ridge travelled {expected:.1} cells in {seconds}s but its \
surface matches itself best at a shift of {near_shift:.2}"
);
assert!(
(far_shift + expected * options.parallax).abs() < 0.4,
"the far ridge should have travelled {:.1} cells at parallax {} but its \
surface matches itself best at a shift of {far_shift:.2}",
expected * options.parallax,
options.parallax
);
let ratio = far_shift / near_shift;
assert!(
(0.0..0.6).contains(&ratio),
"the far ridge travels at {ratio:.2} of the near ridge's rate, which is \
not visibly slower"
);
}
#[test]
fn the_default_ground_ramp_is_ascii_and_not_block_elements() {
for glyph in DEFAULT_GLYPHS.chars() {
assert!(
glyph.is_ascii(),
"the default ground ramp contains {glyph:?}, which is not ASCII"
);
assert!(
!(('\u{2580}'..='\u{259F}').contains(&glyph)),
"the default ground ramp contains the block element {glyph:?}"
);
}
}
#[test]
fn the_ascii_ground_ramp_documents_the_two_pairs_that_run_backwards() {
let ramp = GlyphRamp::from_text(DEFAULT_GLYPHS);
let glyphs = ramp.glyphs();
let expected_ink = |g: char| -> f32 {
match g {
' ' => 0.0,
'.' => 0.05,
':' => 0.1,
'-' => 0.15,
'=' => 0.25,
'+' => 0.2,
'*' => 0.3,
'#' => 0.4,
'%' => 0.5,
'@' => 0.6,
_ => f32::NAN,
}
};
let backwards: Vec<(char, char)> = glyphs
.windows(2)
.filter(|w| expected_ink(w[1]) < expected_ink(w[0]))
.map(|w| (w[0], w[1]))
.collect();
assert_eq!(
backwards,
vec![('=', '+')],
"the ramp's backwards pairs changed. Either the set was edited -- in \
which case update this list and the DEFAULT_GLYPHS comment -- or the \
inversion was accepted and is no longer the one documented."
);
}
#[test]
fn the_ground_is_never_drawn_as_a_space() {
assert!(
!DEFAULT_GLYPHS.contains(' '),
"the default ground ramp opens with a space, so the top row of the \
ground is indistinguishable from the sky"
);
let size = (80u16, 24u16);
let frame = Frame::new(size, 0);
for (x, (&near, &far)) in frame.near.iter().zip(&frame.far).enumerate() {
for y in far.min(near)..near {
assert_ne!(
frame.glyph(x, y),
' ',
"cell ({x}, {y}) is inside the far ridge, between its surface on \
{far} and the near one on {near}, but drew as a space, so the \
distant layer has a hole in it"
);
}
for y in near..size.1 as usize {
assert_ne!(
frame.glyph(x, y),
' ',
"cell ({x}, {y}) is below the surface at row {near} but drew \
as a space, so the ground has a hole in it"
);
}
}
}
#[test]
fn the_second_frame_is_different_from_the_first() {
let mut terrain = Terrain::new(TerrainOptions::default(), (80, 24));
terrain.get_diff();
for _ in 0..30 {
terrain.advance(1.0 / 60.0);
}
let second = terrain.get_diff();
assert!(
!second.is_empty(),
"the frame after 30 updates was empty, so the terrain is still static"
);
}
#[test]
fn the_terrain_keeps_scrolling_rather_than_moving_once() {
let mut terrain = Terrain::new(TerrainOptions::default(), (80, 24));
let mut frames: Vec<Vec<(usize, usize, Cell)>> = Vec::new();
for _ in 0..4 {
terrain.advance(1.0 / 60.0);
frames.push(terrain.get_diff());
}
for (index, pair) in frames.windows(2).enumerate() {
assert_ne!(
pair[0],
pair[1],
"frames {index} and {} are identical, so the scroll stalled",
index + 1
);
}
}
#[test]
fn the_scroll_honours_the_frame_delta() {
let run = |delta: f64| {
let mut terrain = Terrain::new(TerrainOptions::default(), (80, 24));
for _ in 0..60 {
terrain.advance(delta);
}
(terrain.offset, terrain.get_diff())
};
let slow = run(1.0 / 60.0);
let fast = run(0.05);
assert!(
(fast.0 - slow.0 * 3.0).abs() < 1.0e-9,
"60 frames at 0.05s each advanced {:.3} against {:.3} at 1/60s, \
which is not 3x",
fast.0,
slow.0
);
assert!(
(fast.0 - slow.0).abs() > 0.5,
"the two rates ended {:.4} apart, which is too little to move the \
ground visibly",
(fast.0 - slow.0).abs()
);
}
#[test]
fn the_scroll_moves_the_silhouette_and_not_only_the_shading() {
let mut terrain = Terrain::new(TerrainOptions::default(), (80, 24));
let near_first = terrain.near_surface_rows(terrain.offset);
let far_first = terrain.far_surface_rows(terrain.far_offset());
for _ in 0..120 {
terrain.advance(1.0 / 60.0);
}
let near_later = terrain.near_surface_rows(terrain.offset);
let far_later = terrain.far_surface_rows(terrain.far_offset());
for (label, (first, later)) in [
("near", (&near_first, &near_later)),
("far", (&far_first, &far_later)),
] {
let moved = first.iter().zip(later).filter(|(a, b)| a != b).count();
assert!(
moved > 0,
"after two seconds at the default scroll speed not one column's \
{label} surface had moved, so that layer is standing still"
);
}
}
#[test]
fn the_scroll_is_fast_enough_to_see_without_being_a_conveyor_belt() {
let options = TerrainOptions::default();
let period = TerrainOptions::default().scale;
let seconds_per_period = period / options.scroll_speed;
let far_seconds = seconds_per_period / options.parallax;
assert!(
(2.0..30.0).contains(&seconds_per_period),
"at scroll_speed {} one {period} cell ridge takes {seconds_per_period:.1}s \
to cross the screen, which is outside the 2 to 30 second band: under \
2s the ground stops reading as distance, over 30s it is not motion",
options.scroll_speed
);
assert!(
(2.0..30.0).contains(&far_seconds),
"at parallax {} the far ridge takes {far_seconds:.1}s to cross the \
screen, which is outside the same 2 to 30 second band the near ridge \
is held to",
options.parallax
);
}
#[test]
fn scale_is_a_zoom_and_says_so_in_its_direction() {
let at = Terrain::noise_frequency;
let base = at(8.0);
assert!(
(at(4.0) - base * 2.0).abs() < 1.0e-12,
"half the period, twice the frequency"
);
assert!(
(at(16.0) - base / 2.0).abs() < 1.0e-12,
"double the period, half the frequency"
);
assert_eq!(at(8.0), base);
assert!(
at(2.0) > at(16.0),
"a smaller scale is a shorter period, so it must be the higher frequency"
);
}
#[test]
fn a_smaller_period_gives_a_more_jagged_silhouette() {
let density_at = |scale: f64| {
let options = TerrainOptions {
scale,
relief: 4.0 / scale,
..Default::default()
};
let rows = Terrain::new(options, (80, 24)).near_surface_rows(0.0);
rows.windows(2).filter(|w| w[0] != w[1]).count() as f64
/ (rows.len() - 1) as f64
};
let close = density_at(4.0);
let far = density_at(16.0);
assert!(
close > far * 1.5,
"at the same amplitude a 4 cell period turns the silhouette on \
{:.1}% of adjacent columns against {:.1}% at 16 cells, so zooming \
in does not make the landscape more detailed",
close * 100.0,
far * 100.0
);
}
#[test]
fn the_period_stays_usable() {
let period = TerrainOptions::default().scale;
assert!(
(6.0..=12.0).contains(&period),
"a period of {period} cells is outside the 6 to 12 band: below 6 the \
ridges alias, above 12 the ground is a smooth wash"
);
let finest = period / 2f64.powi(TerrainOptions::default().octaves - 1);
assert!(
finest >= 0.8,
"the finest octave has a period of {finest:.2} cells, below the ~1 \
cell at which the surface can represent it"
);
}
#[test]
fn a_degenerate_scale_falls_back_rather_than_drawing_nothing() {
let good = Terrain::noise_frequency(TerrainOptions::default().scale);
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let frequency = Terrain::noise_frequency(bad);
assert!(
frequency.is_finite() && frequency > 0.0,
"scale {bad} produced a frequency of {frequency}"
);
assert_eq!(frequency, good, "scale {bad} did not fall back");
}
}
#[test]
fn the_horizon_leaves_room_for_sky_and_ground_at_every_size() {
for (width, height) in [(6u16, 6u16), (8, 200), (200, 8), (1, 1), (1, 9)] {
let horizon = Terrain::horizon_row((width, height));
let far = Terrain::far_ridge_row((width, height));
assert!(
horizon < height as usize,
"at {width}x{height} the horizon is row {horizon}, so there is no \
ground at all"
);
assert!(
far <= horizon,
"at {width}x{height} the far ridge is row {far} and the near one \
{horizon}, so the dim layer would be drawn in front of the bright one"
);
let frame = Frame::new((width, height), 0);
let has_sky = frame.glyphs.iter().flatten().any(|&c| c == ' ');
let has_ground = frame.glyphs.iter().flatten().any(|&c| c != ' ');
if height == 1 {
assert!(has_ground, "a one-row terminal was drawn as sky");
} else {
assert!(has_sky, "at {width}x{height} nothing was drawn as sky");
}
assert!(
has_ground,
"at {width}x{height} nothing was drawn as ground"
);
}
}
#[test]
fn the_sky_darkens_towards_the_zenith_and_stays_below_its_haze() {
let size = (80u16, 24u16);
let mut terrain = Terrain::new(TerrainOptions::default(), size);
let diff = terrain.get_diff();
let sky: Vec<(usize, u8)> = diff
.iter()
.filter(|(_, _, cell)| cell.symbol == ' ')
.filter_map(|(_, y, cell)| match cell.color {
style::Color::Rgb { r, .. } => Some((*y, r)),
_ => None,
})
.collect();
assert!(sky.len() > 20, "the fixture produced almost no sky");
let zenith = sky
.iter()
.find(|(y, _)| *y == 0)
.expect("row 0 is sky in every column")
.1;
let brightest = sky.iter().map(|(_, r)| *r).max().unwrap();
assert!(
brightest > zenith,
"the top row is {zenith} and the brightest sky anywhere is \
{brightest}: the sky is not darker at the top"
);
assert!(
brightest <= 140,
"the brightest sky is {brightest}, brighter than the haze the ramp \
ends on (126)"
);
let levels: HashSet<u8> = sky.iter().map(|(_, r)| *r).collect();
assert!(
levels.len() >= 3,
"the sky took only {levels:?}, so it is a flat fill"
);
}
#[test]
fn no_cell_is_bold() {
let mut terrain = Terrain::new(TerrainOptions::default(), (80, 24));
for _ in 0..8 {
terrain.advance(1.0 / 60.0);
}
let diff = terrain.get_diff();
assert!(!diff.is_empty(), "nothing was drawn");
for (x, y, cell) in diff {
assert_eq!(
cell.attr,
style::Attribute::Reset,
"cell ({x}, {y}) is still bold, which brightens the top of the \
ramp into white"
);
}
}
#[test]
fn the_noise_is_still_reproducible_and_still_seed_sensitive() {
let first_frame = |seed: u64, frames: u64| {
let options = TerrainOptions {
seed,
..Default::default()
};
let mut terrain = Terrain::new(options, (60, 20));
for _ in 0..frames {
terrain.advance(1.0 / 60.0);
}
terrain.get_diff()
};
for frames in [0u64, 1, 45] {
let a = first_frame(1234, frames);
let b = first_frame(1234, frames);
let c = first_frame(4321, frames);
assert_eq!(
a, b,
"two terrains at seed 1234 drew differently after {frames} frames"
);
assert_ne!(
a, c,
"seeds 1234 and 4321 drew the same terrain after {frames} frames, \
so the seed is not reaching the noise"
);
}
}
#[test]
fn the_new_keys_round_trip_through_toml() {
let options: TerrainOptions = toml::from_str(
"scroll_speed = 2.5\nrelief = 0.3\nfar_relief = 0.9\nparallax = 0.2\nglyphs = \" .oO@\"\n",
)
.expect("five keys parse");
assert_eq!(options.scroll_speed, 2.5);
assert_eq!(options.relief, 0.3);
assert_eq!(options.far_relief, 0.9);
assert_eq!(options.parallax, 0.2);
assert_eq!(options.glyphs, " .oO@");
assert_eq!(
options.scale,
TerrainOptions::default().scale,
"five keys in the section silently reset the others"
);
let defaults = TerrainOptions::default();
assert_eq!(defaults.far_relief, DEFAULT_FAR_RELIEF);
assert_eq!(defaults.parallax, DEFAULT_PARALLAX);
assert!(
defaults.parallax < 1.0,
"the default parallax is {} , so the far ridge scrolls at the same rate \
as the near one and there is no parallax at all",
defaults.parallax
);
let serialised = toml::to_string(&options).expect("the section serialises");
for key in [
"seed",
"scale",
"octaves",
"persistence",
"scroll_speed",
"relief",
"far_relief",
"parallax",
"glyphs",
] {
assert!(
serialised.contains(key),
"{key} is missing from the serialised form, so --print-config \
would not write it: {serialised}"
);
}
}
#[test]
fn an_unusable_glyph_config_falls_back_to_the_default_ramp() {
for configured in ["", "\u{7}\u{1}", "\u{4E2D}"] {
let ramp = glyph_ramp(configured);
assert_eq!(
ramp.glyphs(),
DEFAULT_GLYPHS.chars().collect::<Vec<char>>(),
"{configured:?} did not fall back to the documented default"
);
}
assert!(
DEFAULT_GLYPHS.is_ascii(),
"the documented default is no longer the ASCII ramp"
);
}
#[test]
fn the_surfaces_cost_one_noise_sample_per_column_per_ridge_not_per_cell() {
let size = (400u16, 200u16);
let terrain = Terrain::new(TerrainOptions::default(), size);
assert_eq!(
terrain.near_surface_rows(0.0).len(),
usize::from(size.0),
"the near surface should be computed once per column"
);
assert_eq!(
terrain.far_surface_rows(0.0).len(),
usize::from(size.0),
"the far surface should be computed once per column"
);
let mut painted = Terrain::new(TerrainOptions::default(), size);
let drawn_cells = painted.get_diff().len();
assert_eq!(
drawn_cells,
usize::from(size.0) * usize::from(size.1),
"at 400x200 the frame should touch every cell, got {drawn_cells}"
);
}
#[test]
fn a_frame_of_two_silhouettes_changes_few_cells() {
let mean = mean_frame_diff((400, 200), 300);
assert!(
mean < 900.0,
"the frame changed {mean:.0} cells on average at 400x200, so something \
is being recomputed per cell rather than per column -- the removed \
grain did this at 1,161"
);
}
}