use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{DEFAULT_SEED, TerminalEffect, seeded_rng};
use crate::render::glyph_ramp::GlyphRamp;
use crate::render::palette::{Palette, presets as palette_presets};
use crossterm::style;
use rand::RngExt;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DonutOptions {
pub inner_radius: f32,
pub outer_radius: f32,
pub rotation_speed_a: f32,
pub rotation_speed_b: f32,
pub distance: f32,
#[serde(skip)]
pub k1: f32,
pub k1_coeff: f32,
pub luminance_chars: Vec<char>,
pub palette: String,
pub seed: u64,
}
impl Default for DonutOptions {
fn default() -> Self {
Self {
inner_radius: 1.0,
seed: DEFAULT_SEED,
outer_radius: 2.0,
rotation_speed_a: DEFAULT_SPEED_A,
rotation_speed_b: DEFAULT_SPEED_B,
distance: 5.5,
k1: 25.0,
k1_coeff: 1.0,
luminance_chars: DEFAULT_LUMINANCE_CHARS.to_vec(),
palette: String::from(DEFAULT_PALETTE),
}
}
}
const DEFAULT_SPEED_A: f32 = 1.32;
const DEFAULT_SPEED_B: f32 = 0.60;
const SPEED_BAND_A: (f32, f32) = (0.65, 1.7);
const SPEED_BAND_B: (f32, f32) = (0.85, 1.35);
const PHASE_SPAN: f32 = std::f32::consts::TAU;
#[derive(Clone, Copy, Debug, PartialEq)]
struct Motion {
speeds: (f32, f32),
phase: (f32, f32),
}
#[inline]
fn finite_or(value: f32, fallback: f32) -> f32 {
if value.is_finite() { value } else { fallback }
}
impl DonutOptions {
fn motion(&self) -> Motion {
let mut rng = seeded_rng(self.seed, "donut.motion");
let mut rate = |configured: f32, fallback: f32, band: (f32, f32)| {
finite_or(configured, fallback) * rng.random_range(band.0..band.1)
};
Motion {
speeds: (
rate(self.rotation_speed_a, DEFAULT_SPEED_A, SPEED_BAND_A),
rate(self.rotation_speed_b, DEFAULT_SPEED_B, SPEED_BAND_B),
),
phase: (
rng.random_range(0.0..PHASE_SPAN),
rng.random_range(0.0..PHASE_SPAN),
),
}
}
}
const THETA_SAMPLES: usize = 314;
const PHI_SAMPLES: usize = THETA_SAMPLES * 2;
const DEFAULT_LUMINANCE_CHARS: &[char] =
&['.', ',', '-', '~', ':', ';', '=', '!', '*', '#', '$', '@'];
fn shade_ramp(configured: &[char]) -> GlyphRamp {
GlyphRamp::new(if configured.is_empty() {
DEFAULT_LUMINANCE_CHARS.to_vec()
} else {
configured.to_vec()
})
}
const DEFAULT_PALETTE: &str = "magma";
const RAMP_FLOOR: style::Color = style::Color::Rgb {
r: 72,
g: 24,
b: 146,
};
const SHADES: usize = 12;
fn donut_colors(name: &str) -> Vec<style::Color> {
let named = palette_presets::by_name(name).unwrap_or(palette_presets::MAGMA);
let mut stops = Vec::with_capacity(4);
stops.push(RAMP_FLOOR);
stops.extend_from_slice(&named[2..named.len().min(5)]);
if stops.len() < 2 {
stops.extend_from_slice(&named[1..]);
}
Palette::new(stops).expand(SHADES)
}
const BRIGHTEST: f32 = std::f32::consts::SQRT_2;
#[inline]
fn shade_index(brightness: f32) -> usize {
let scale = SHADES as f32 / BRIGHTEST;
((brightness * scale) as usize).min(SHADES - 1)
}
#[inline]
fn shape_light(normalised: f32) -> f32 {
normalised * normalised.sqrt()
}
#[inline]
fn shade_index_for(brightness: f32) -> usize {
let normalised = (brightness / BRIGHTEST).clamp(0.0, 1.0);
shade_index(shape_light(normalised) * BRIGHTEST)
}
#[derive(Default)]
struct Scratch {
zbuffer: Vec<f32>,
output: Vec<char>,
shade: Vec<u8>,
sin_theta: Vec<f32>,
cos_theta: Vec<f32>,
sin_phi: Vec<f32>,
cos_phi: Vec<f32>,
theta_steps: usize,
phi_steps: usize,
}
impl Scratch {
fn ensure_angles(&mut self, theta_steps: usize, phi_steps: usize) {
if self.theta_steps == theta_steps && self.phi_steps == phi_steps {
return;
}
let theta =
|i: usize| i as f32 * std::f32::consts::TAU / theta_steps as f32;
let phi = |i: usize| i as f32 * std::f32::consts::TAU / phi_steps as f32;
self.sin_theta = (0..theta_steps).map(|i| theta(i).sin()).collect();
self.cos_theta = (0..theta_steps).map(|i| theta(i).cos()).collect();
self.sin_phi = (0..phi_steps).map(|i| phi(i).sin()).collect();
self.cos_phi = (0..phi_steps).map(|i| phi(i).cos()).collect();
self.theta_steps = theta_steps;
self.phi_steps = phi_steps;
}
}
pub struct Donut {
pub screen_size: (u16, u16),
options: DonutOptions,
canvas: Canvas,
rotation_a: f32,
rotation_b: f32,
motion: Motion,
scratch: Scratch,
}
impl TerminalEffect for Donut {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.render_donut();
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_f32());
}
fn update_size(&mut self, width: u16, height: u16) {
self.screen_size = (width.max(1), height.max(1));
self.canvas.resize(self.screen_size.0, self.screen_size.1);
let min_dimension = self.screen_size.0.min(self.screen_size.1) as f32;
self.options.k1 = min_dimension * 0.8 * self.options.k1_coeff;
}
fn reset(&mut self) {
*self = Self::new(self.options.clone(), self.screen_size);
}
}
impl Donut {
fn advance(&mut self, delta: f32) {
self.rotation_a += self.motion.speeds.0 * delta;
self.rotation_b += self.motion.speeds.1 * delta;
}
pub fn new(options: DonutOptions, screen_size: (u16, u16)) -> Self {
let canvas = Canvas::new(screen_size.0, screen_size.1);
let motion = options.motion();
Self {
screen_size,
options,
canvas,
rotation_a: motion.phase.0,
rotation_b: motion.phase.1,
motion,
scratch: Scratch::default(),
}
}
fn render_donut(&mut self) {
self.canvas.clear();
let width = self.screen_size.0 as usize;
let height = self.screen_size.1 as usize;
let sin_a = self.rotation_a.sin();
let cos_a = self.rotation_a.cos();
let sin_b = self.rotation_b.sin();
let cos_b = self.rotation_b.cos();
let cells = width * height;
if self.scratch.zbuffer.len() != cells {
self.scratch.zbuffer = vec![0.0; cells];
self.scratch.output = vec![' '; cells];
self.scratch.shade = vec![0u8; cells];
} else {
self.scratch.zbuffer.fill(0.0);
self.scratch.output.fill(' ');
self.scratch.shade.fill(0);
}
let outer_radius = finite_or(self.options.outer_radius, 2.0);
let inner_radius = finite_or(self.options.inner_radius, 1.0);
let distance = finite_or(self.options.distance, 5.0);
let k1 = finite_or(self.options.k1, 1.0);
let colors = donut_colors(&self.options.palette);
let half_width = width as f32 / 2.0;
let half_height = height as f32 / 2.0;
let ramp = shade_ramp(&self.options.luminance_chars);
let min_dimension = width.min(height);
let theta_steps =
((min_dimension * THETA_SAMPLES) / 50).clamp(48, THETA_SAMPLES);
let phi_steps = (theta_steps * 2).min(PHI_SAMPLES);
self.scratch.ensure_angles(theta_steps, phi_steps);
let Scratch {
zbuffer,
output,
shade,
sin_theta,
cos_theta,
sin_phi,
cos_phi,
..
} = &mut self.scratch;
for theta_index in 0..theta_steps {
let sin_theta = sin_theta[theta_index];
let cos_theta = cos_theta[theta_index];
let circle_x = outer_radius + inner_radius * cos_theta;
let circle_y = inner_radius * sin_theta;
let cos_a_circle_x = cos_a * circle_x;
let z_base = distance + circle_y * sin_a;
let y_circle_term = circle_y * cos_a * cos_b;
let x_circle_term = circle_y * cos_a * sin_b;
for phi_index in 0..phi_steps {
let sin_phi = sin_phi[phi_index];
let cos_phi = cos_phi[phi_index];
let x = circle_x * (cos_b * cos_phi + sin_a * sin_b * sin_phi)
- x_circle_term;
let y = circle_x * (sin_b * cos_phi - sin_a * cos_b * sin_phi)
+ y_circle_term;
let z = z_base + cos_a_circle_x * sin_phi;
let z_inv = 1.0 / z;
let l = cos_phi * cos_theta * sin_b
- cos_a * cos_theta * sin_phi
- sin_a * sin_theta
+ cos_b * (cos_a * sin_theta - cos_theta * sin_a * sin_phi);
if l <= 0.0 {
continue;
}
let luminance_index = shade_index_for(l);
let x_f = half_width + k1 * z_inv * x;
let y_f = half_height + k1 * z_inv * y * 0.8;
if !(0.0..width as f32).contains(&x_f)
|| !(0.0..height as f32).contains(&y_f)
{
continue;
}
let x_proj = x_f as usize;
let y_proj = y_f as usize;
let idx = y_proj * width + x_proj;
if z_inv > zbuffer[idx] {
zbuffer[idx] = z_inv;
output[idx] = ramp.at(luminance_index);
shade[idx] = luminance_index as u8;
}
}
}
for y in 0..height {
for x in 0..width {
let idx = y * width + x;
let symbol = output[idx];
if symbol == ' ' {
continue;
}
let color = colors[shade[idx] as usize % colors.len()];
self.canvas.set(
x,
y,
Cell::new(symbol, color, style::Attribute::NormalIntensity),
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::{HashMap, HashSet};
use std::time::Duration;
fn brightness(color: &style::Color) -> f32 {
match color {
style::Color::Rgb { r, g, b } => {
(0.299 * f32::from(*r)
+ 0.587 * f32::from(*g)
+ 0.114 * f32::from(*b))
/ 255.0
}
_ => 1.0,
}
}
#[test]
fn a_sample_projected_off_screen_is_not_drawn_into_the_first_row_or_column() {
let mut offenders = Vec::new();
for distance in [1.5f32, 2.0, 2.5, 0.8, 3.0] {
for seed in 1..=3u64 {
let mut donut = Donut::new(
DonutOptions {
distance,
seed,
..DonutOptions::default()
},
(60, 20),
);
for _ in 0..40 {
donut.advance(1.0 / 60.0);
}
let frame = donut.get_diff();
let edge_inked =
frame.iter().filter(|(x, y, _)| *x == 0 || *y == 0).count();
let middle_inked = frame
.iter()
.filter(|(x, y, _)| *x > 5 && *x < 54 && *y > 2 && *y < 17)
.count();
if edge_inked > middle_inked / 4 {
offenders.push(format!(
"distance {distance} seed {seed}: {edge_inked} cells on \
the first row/column against {middle_inked} in the middle"
));
}
}
}
assert!(
offenders.is_empty(),
"the torus is being drawn into row 0 and column 0 from samples that \
projected off screen, which is what a saturating cast does: {offenders:?}"
);
}
fn seeded(seed: u64) -> Donut {
seeded_at(seed, (80, 40))
}
fn seeded_at(seed: u64, size: (u16, u16)) -> Donut {
let mut donut = Donut::new(
DonutOptions {
seed,
..Default::default()
},
size,
);
donut.update_size(size.0, size.1);
donut
}
fn whole_frame(
donut: &mut Donut,
frames: u32,
) -> HashMap<(usize, usize), char> {
let mut picture: HashMap<(usize, usize), char> = HashMap::new();
for frame in 0..=frames {
for (x, y, cell) in donut.get_diff() {
if cell.symbol == ' ' {
picture.remove(&(x, y));
} else {
picture.insert((x, y), cell.symbol);
}
}
if frame < frames {
donut.advance(1.0 / 60.0);
}
}
picture
}
fn difference(
a: &HashMap<(usize, usize), char>,
b: &HashMap<(usize, usize), char>,
) -> f32 {
let union: HashSet<(usize, usize)> =
a.keys().chain(b.keys()).copied().collect();
if union.is_empty() {
return 1.0;
}
let differing = union.iter().filter(|k| a.get(*k) != b.get(*k)).count();
differing as f32 / union.len() as f32
}
fn srgb_to_linear(channel: u8) -> f64 {
let c = f64::from(channel) / 255.0;
if c <= 0.03928 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
}
fn lab(color: &style::Color) -> (f64, f64, f64) {
let (r, g, b) = match color {
style::Color::Rgb { r, g, b } => (*r, *g, *b),
other => panic!("{other:?} has no Lab coordinates"),
};
let (r, g, b) = (srgb_to_linear(r), srgb_to_linear(g), srgb_to_linear(b));
let x = 0.4124 * r + 0.3576 * g + 0.1805 * b;
let y = 0.2126 * r + 0.7152 * g + 0.0722 * b;
let z = 0.0193 * r + 0.1192 * g + 0.9505 * b;
let f = |t: f64| {
if t > 0.008_856 {
t.cbrt()
} else {
7.787 * t + 16.0 / 116.0
}
};
let (fx, fy, fz) = (f(x / 0.950_47), f(y), f(z / 1.088_83));
(116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz))
}
fn delta_e(a: &style::Color, b: &style::Color) -> f64 {
let (l1, a1, b1) = lab(a);
let (l2, a2, b2) = lab(b);
((l1 - l2).powi(2) + (a1 - a2).powi(2) + (b1 - b2).powi(2)).sqrt()
}
const TINTED_BACKGROUND: style::Color = style::Color::Rgb {
r: 60,
g: 70,
b: 85,
};
const CONTRAST_FLOOR: f64 = 45.0;
#[test]
fn the_dark_end_of_the_ramp_is_visible_on_a_tinted_background() {
let ramp = donut_colors(&DonutOptions::default().palette);
assert_eq!(ramp.len(), SHADES);
let floor = ramp[0];
assert_eq!(
floor, RAMP_FLOOR,
"the ramp no longer starts at RAMP_FLOOR, so this test is measuring \
something other than the constant it is about"
);
let distance = delta_e(&floor, &TINTED_BACKGROUND);
assert!(
distance >= CONTRAST_FLOOR,
"the darkest colour the donut draws is {floor:?}, a Delta-E of \
{distance:.1} from a {TINTED_BACKGROUND:?} background, against a \
floor of {CONTRAST_FLOOR}. Below it, the shadowed side of the torus \
is not distinguishable from a cell the effect never drew, and reads \
as a hole rather than as colour."
);
let worst = ramp
.iter()
.map(|color| delta_e(color, &TINTED_BACKGROUND))
.fold(f64::MAX, f64::min);
assert!(
worst >= CONTRAST_FLOOR,
"somewhere in the ramp there is a colour only {worst:.1} from the \
background, so part of the torus disappears into it: {ramp:?}"
);
}
#[test]
fn the_tinted_background_property_survives_every_palette() {
for name in Palette::preset_names() {
let ramp = donut_colors(name);
let distance = delta_e(&ramp[0], &TINTED_BACKGROUND);
assert!(
distance >= CONTRAST_FLOOR,
"palette {name:?} bottoms out at {ramp:?}, only {distance:.1} \
from a {TINTED_BACKGROUND:?} background, so asking for that \
palette undoes the lifted floor"
);
}
}
#[test]
fn the_default_spin_resolves_in_seconds_not_minutes() {
let options = DonutOptions::default();
for (name, speed) in [
("rotation_speed_a", options.rotation_speed_a),
("rotation_speed_b", options.rotation_speed_b),
] {
let revolution = std::f32::consts::TAU / speed;
assert!(
(2.0..=12.0).contains(&revolution),
"{name} is {speed} rad/s, so a revolution takes {revolution:.1}s; \
anything past a few seconds reads as a frozen effect"
);
}
}
#[test]
fn the_default_speeds_are_the_per_frame_values_at_60hz() {
let options = DonutOptions::default();
let frame = std::f32::consts::TAU;
for (speed, per_frame) in [
(options.rotation_speed_a, 0.022f32),
(options.rotation_speed_b, 0.010f32),
] {
assert!(
(speed - per_frame * 60.0).abs() < 0.001,
"{speed} is not {per_frame} rad/frame scaled to 60 Hz"
);
}
assert!(frame > 0.0);
assert_ne!(options.rotation_speed_a, options.rotation_speed_b);
}
#[test]
fn a_second_of_elapsed_time_visibly_turns_the_torus() {
let mut donut = Donut::new(DonutOptions::default(), (80, 40));
let start = donut.rotation_a;
donut.advance(1.0);
let turned = donut.rotation_a - start;
let degrees = turned.to_degrees();
assert!(
degrees > 20.0,
"one second turned the torus {degrees:.1} degrees, which is not \
something you can see"
);
}
#[test]
fn resize_recomputes_projection_scale() {
let options = DonutOptions {
k1: 99.0,
k1_coeff: 1.0,
..Default::default()
};
let mut donut = Donut::new(options, (80, 40));
donut.update_size(10, 20);
assert_eq!(donut.screen_size, (10, 20));
assert_eq!(donut.options.k1, 8.0);
}
#[test]
fn a_resize_on_its_own_leaves_a_canvas_the_size_of_the_screen() {
let mut donut = Donut::new(DonutOptions::default(), (80, 40));
donut.update_size(10, 20);
assert_eq!(
donut.canvas.size(),
(10, 20),
"the canvas kept the old size"
);
let diff = donut.get_diff();
assert!(
diff.len() <= 10 * 20,
"a 10x20 frame reported {} cells, which is more than the screen has",
diff.len()
);
for (x, y, _) in &diff {
assert!(*x < 10 && *y < 20, "drew outside the resized canvas");
}
}
#[test]
fn a_shrink_repaints_the_whole_screen() {
let mut donut = Donut::new(DonutOptions::default(), (80, 40));
donut.get_diff();
donut.update_size(20, 10);
let diff = donut.get_diff();
assert!(!diff.is_empty(), "a shrink reported nothing to repaint");
for (x, y, _) in &diff {
assert!(*x < 20 && *y < 10, "drew outside the shrunk canvas");
}
}
#[test]
fn the_ramp_runs_from_dark_to_light() {
let colors = donut_colors(&DonutOptions::default().palette);
assert_eq!(colors.len(), SHADES);
for (index, pair) in colors.windows(2).enumerate() {
let (dim, bright) = (brightness(&pair[0]), brightness(&pair[1]));
assert!(
dim <= bright,
"COLORS[{index}] is brighter ({dim:.2}) than COLORS[{}] \
({bright:.2}), so the ramp is inverted",
index + 1
);
}
assert!(
brightness(&colors[0]) < brightness(&colors[SHADES - 1]),
"the ramp does not span a range of brightness at all"
);
}
#[test]
fn the_shade_ramp_spans_every_glyph() {
let options = DonutOptions::default();
let ramp = shade_ramp(&options.luminance_chars);
assert_eq!(
SHADES,
ramp.len(),
"the colour ramp and the glyph ramp are different lengths, so \
some glyphs are unreachable and some colours unused"
);
assert_eq!(shade_index(0.0), 0, "the dimmest sample is not the first");
assert_eq!(
shade_index(BRIGHTEST),
SHADES - 1,
"the brightest sample does not reach the top of the ramp"
);
for step in 0..SHADES {
let brightness = BRIGHTEST * step as f32 / (SHADES - 1) as f32;
assert_eq!(shade_index(brightness), step, "shade {step} skipped");
}
}
const POLAR_BINS: usize = 16;
fn mark_polar(
size: (u16, u16),
diff: &[(usize, usize, Cell)],
hit: &mut [bool; POLAR_BINS],
) {
for (x, y, _) in diff {
let dx = *x as f64 + 0.5 - f64::from(size.0) / 2.0;
let dy = *y as f64 + 0.5 - f64::from(size.1) / 2.0;
let angle = dy.atan2(dx).rem_euclid(std::f64::consts::TAU);
let bin =
(angle / (std::f64::consts::TAU / POLAR_BINS as f64)) as usize;
hit[bin.min(POLAR_BINS - 1)] = true;
}
}
fn polar_coverage(size: (u16, u16), diff: &[(usize, usize, Cell)]) -> f64 {
let mut hit = [false; POLAR_BINS];
mark_polar(size, diff, &mut hit);
hit.iter().filter(|reached| **reached).count() as f64 / POLAR_BINS as f64
}
const POSE_STEP: f32 = 0.2;
fn steps_per_turn(donut: &Donut) -> u32 {
let rate = donut.motion.speeds.0.abs().max(1.0e-3);
((std::f32::consts::TAU / (rate * POSE_STEP)).ceil() as u32).max(2) + 1
}
fn shade_histogram(size: (u16, u16), resize: bool) -> [f64; SHADES] {
let ramp = shade_ramp(&DonutOptions::default().luminance_chars);
let mut counts = [0usize; SHADES];
let mut donut = Donut::new(DonutOptions::default(), size);
if resize {
donut.update_size(size.0, size.1);
}
for _ in 0..steps_per_turn(&donut) {
donut.advance(POSE_STEP);
for (_, _, cell) in donut.get_diff() {
if let Some(index) =
ramp.glyphs().iter().position(|g| *g == cell.symbol)
{
counts[index] += 1;
}
}
}
let total: usize = counts.iter().sum();
std::array::from_fn(|index| counts[index] as f64 / total as f64)
}
#[test]
fn the_torus_is_swept_all_the_way_round() {
for size in [(6u16, 6u16), (12, 12), (40, 12), (40, 20), (80, 50)] {
let mut donut = Donut::new(DonutOptions::default(), size);
donut.update_size(size.0, size.1);
donut.get_diff();
let steps = donut.scratch.theta_steps;
assert!(steps > 0, "at {size:?} no angles were sampled at all");
for index in [0, 1, steps / 3, steps / 2, steps - 1] {
let expected = index as f32 * std::f32::consts::TAU / steps as f32;
assert!(
(donut.scratch.sin_theta[index] - expected.sin()).abs() < 1e-6
&& (donut.scratch.cos_theta[index] - expected.cos()).abs()
< 1e-6,
"at {size:?} sample {index} of {steps} is not 2pi*{index}/{steps}"
);
}
let covered = (steps as f64 - 1.0) * std::f64::consts::TAU
/ steps as f64
/ std::f64::consts::TAU;
assert!(
covered >= 0.95,
"at {size:?} the {steps} sampled cross-section angles cover \
{covered:.1}% of a turn, so the rest of the torus is never \
drawn"
);
}
}
#[test]
fn the_drawn_torus_reaches_every_direction() {
for size in [(40u16, 12u16), (40, 20), (80, 50)] {
let mut frames: Vec<f64> = Vec::new();
for seed in 0..6u64 {
let mut donut = seeded_at(seed, size);
let mut hit = [false; POLAR_BINS];
for _ in 0..steps_per_turn(&donut) {
donut.advance(POSE_STEP);
let diff = donut.get_diff();
assert!(
!diff.is_empty(),
"at {size:?} a seeded launch drew nothing at all"
);
mark_polar(size, &diff, &mut hit);
frames.push(polar_coverage(size, &diff));
}
let reached = hit.iter().filter(|h| **h).count();
assert_eq!(
reached,
POLAR_BINS,
"at {size:?} seed {seed} swept a whole turn and {} of the \
{POLAR_BINS} directions around the centre were never lit, so \
a wedge of the torus is not being drawn at any pose",
POLAR_BINS - reached
);
}
frames.sort_by(f64::total_cmp);
let median = frames[frames.len() / 2];
assert!(
median >= 0.95,
"at {size:?} the median frame of a turn reaches only {:.1}% of the \
directions around the centre, so the torus is not filling the \
screen at its usual scale",
median * 100.0
);
}
}
#[test]
fn every_shade_of_the_ramp_reaches_the_screen() {
for size in [(40u16, 12u16), (40, 20), (80, 50)] {
for resize in [true, false] {
let histogram = shade_histogram(size, resize);
let unused: Vec<usize> = histogram
.iter()
.enumerate()
.filter(|(_, share)| **share == 0.0)
.map(|(shade, _)| shade)
.collect();
assert!(
unused.is_empty(),
"at {size:?} (resized: {resize}) shades {unused:?} of the \
twelve were never drawn; the ramp has {SHADES} colours and \
{SHADES} glyphs, and an unreachable colour is an \
unreachable glyph"
);
}
}
}
#[test]
fn the_ramp_is_spread_across_the_drawn_surface() {
for size in [(40u16, 12u16), (40, 20), (80, 50)] {
let histogram = shade_histogram(size, true);
let darkest = histogram.iter().cloned().fold(f64::MAX, f64::min);
let brightest = histogram.iter().cloned().fold(0.0f64, f64::max);
let even = 1.0 / SHADES as f64;
assert!(
darkest >= even * 0.36 && brightest <= even * 2.4,
"at {size:?} the shades run from {:.1}% to {:.1}% of the \
surface, and an even ramp would be {:.1}%; measured: {histogram:?}",
darkest * 100.0,
brightest * 100.0,
even * 100.0
);
}
}
#[test]
fn the_light_curve_is_the_exponent_it_claims_to_be() {
const EXPONENT: f32 = 1.5;
for step in 0..=20 {
let x = step as f32 / 20.0;
let expected = x.powf(EXPONENT);
assert!(
(shape_light(x) - expected).abs() < 1e-6,
"shape_light({x:.2}) is {} and {x:.2}^{EXPONENT} is {expected:.6}",
shape_light(x)
);
}
}
#[test]
fn the_shaped_index_still_reaches_both_ends_of_the_ramp() {
assert_eq!(shade_index_for(0.0), 0);
assert_eq!(shade_index_for(BRIGHTEST), SHADES - 1);
let mut previous = 0;
for step in 0..=200 {
let brightness = BRIGHTEST * step as f32 / 200.0;
let index = shade_index_for(brightness);
assert!(index >= previous, "the shaped index went backwards");
previous = index;
}
}
#[test]
fn no_cell_is_drawn_bold() {
for size in [(40u16, 20u16), (80, 40)] {
let mut donut = Donut::new(DonutOptions::default(), size);
donut.update_size(size.0, size.1);
let diff = donut.get_diff();
assert!(!diff.is_empty(), "at {size:?} nothing was drawn");
for (x, y, cell) in &diff {
assert!(
cell.attr != style::Attribute::Bold,
"the cell at {x},{y} is drawn bold"
);
}
}
}
#[test]
fn no_two_adjacent_ramp_entries_are_indistinguishable() {
let colors = donut_colors(&DonutOptions::default().palette);
for (index, pair) in colors.windows(2).enumerate() {
let gap = brightness(&pair[1]) - brightness(&pair[0]);
assert!(
gap >= 0.03,
"COLORS[{index}] and COLORS[{}] are only {gap:.3} apart in \
luminance, so one of them is never visible",
index + 1
);
}
}
#[test]
fn any_named_palette_renders_and_an_unknown_one_falls_back() {
for name in Palette::preset_names() {
let mut donut = Donut::new(
DonutOptions {
palette: name.to_string(),
..Default::default()
},
(40, 20),
);
donut.update_size(40, 20);
let diff = donut.get_diff();
assert!(!diff.is_empty(), "palette {name:?} drew nothing at all");
let distinct: std::collections::HashSet<style::Color> =
diff.iter().map(|(_, _, cell)| cell.color).collect();
assert!(
distinct.len() >= 2,
"palette {name:?} drew {} distinct colours, so it is not being \
used at all",
distinct.len()
);
for (x, y, _) in &diff {
assert!(
*x < 40 && *y < 20,
"palette {name:?} drew outside the canvas at ({x}, {y})"
);
}
}
assert_eq!(
donut_colors("nonesuch"),
donut_colors(DEFAULT_PALETTE),
"an unknown palette name did not fall back to the default ramp"
);
}
#[test]
fn the_palette_knob_round_trips_through_toml_and_changes_the_output() {
let options: DonutOptions =
toml::from_str("palette = \"ocean\"\n").expect("a lone key parses");
assert_eq!(options.palette, "ocean", "the key was not read back");
assert_eq!(
options.rotation_speed_a,
DonutOptions::default().rotation_speed_a,
"one key in the section silently reset the others"
);
let serialised = toml::to_string(&options).expect("the section serialises");
assert!(
serialised.contains("palette"),
"the key is missing from the serialised form, so --print-config would \
never write it: {serialised}"
);
let frame = |palette: &str| {
let mut donut = Donut::new(
DonutOptions {
palette: palette.to_string(),
..Default::default()
},
(40, 20),
);
donut.update_size(40, 20);
donut
.get_diff()
.into_iter()
.map(|(_, _, cell)| cell.color)
.collect::<std::collections::HashSet<style::Color>>()
};
let magma = frame(DEFAULT_PALETTE);
let ocean = frame("ocean");
assert!(
!magma.is_empty() && !ocean.is_empty(),
"a frame drew no colours"
);
assert_ne!(
magma, ocean,
"palette = \"ocean\" drew exactly the same colours as the default"
);
}
#[test]
fn a_drawn_frame_gets_brighter_with_its_glyphs() {
let mut donut = Donut::new(DonutOptions::default(), (40, 20));
let mut dimmest: Option<(char, f32)> = None;
let mut brightest: Option<(char, f32)> = None;
for step in 0..6u64 {
donut.update_with_context(&crate::runtime::FrameContext::new(
(40, 20),
step,
Duration::ZERO,
Duration::from_secs_f64(1.0 / 30.0),
crate::runtime::InputState::default(),
));
for (_, _, cell) in donut.get_diff() {
let level = brightness(&cell.color);
if cell.symbol == '.' {
dimmest = Some((cell.symbol, level));
}
if cell.symbol == '@' {
brightest = Some((cell.symbol, level));
}
}
}
let (dim_glyph, dim) = dimmest.expect("no dim glyph was ever drawn");
let (bright_glyph, bright) =
brightest.expect("no bright glyph was ever drawn");
assert!(
dim <= bright,
"{dim_glyph} was painted at {dim:.2} and {bright_glyph} at \
{bright:.2}: the ramp is inverted"
);
}
#[test]
fn two_seeds_open_on_different_pictures() {
for (left, right) in [
(42u64, 43u64),
(42, 1),
(42, 2),
(7, 8),
(0, 99),
(5, 12345),
] {
let a = whole_frame(&mut seeded(left), 90);
let b = whole_frame(&mut seeded(right), 90);
let differing = difference(&a, &b);
assert!(
differing > 0.4,
"seeds {left} and {right} are 90 frames into a run and their \
frames differ on {:.0}% of the cells either drew, so the seed is \
not reaching the motion",
differing * 100.0
);
}
}
#[test]
fn the_same_seed_replays_the_same_run() {
let mut a = seeded(2024);
let mut b = seeded(2024);
for step in 0..90u32 {
a.advance(1.0 / 60.0);
b.advance(1.0 / 60.0);
assert_eq!(
a.get_diff(),
b.get_diff(),
"two tori on seed 2024 differ on frame {step}, so the motion is \
not a function of the seed"
);
}
}
#[test]
fn every_seeded_opening_is_a_lit_torus() {
let ramp = shade_ramp(&DonutOptions::default().luminance_chars);
let mut openings: Vec<HashMap<(usize, usize), char>> = Vec::new();
for seed in 0..20u64 {
for size in [(40u16, 12u16), (40, 20), (80, 50)] {
let mut donut = seeded_at(seed, size);
let first = donut.get_diff();
assert!(
!first.is_empty(),
"seed {seed} at {size:?} opened on an empty screen, and the \
torus's shape does not depend on the pose"
);
let mut seen = [false; SHADES];
for (_, _, cell) in &first {
mark_shade(&ramp, &mut seen, cell.symbol);
}
for _ in 0..steps_per_turn(&donut) {
donut.advance(POSE_STEP);
for (_, _, cell) in donut.get_diff() {
mark_shade(&ramp, &mut seen, cell.symbol);
}
}
let unused: Vec<usize> = seen
.iter()
.enumerate()
.filter(|(_, reached)| !**reached)
.map(|(shade, _)| shade)
.collect();
assert!(
unused.is_empty(),
"seed {seed} at {size:?} opens at {:?} and never draws shades \
{unused:?} of the twelve: a pose where part of the ramp is \
unreachable is part of what randomising the opening costs",
donut.rotation_a
);
}
openings.push(whole_frame(&mut seeded(seed), 0));
}
let mut all: Vec<f32> = Vec::new();
for a in 0..openings.len() {
for b in a + 1..openings.len() {
all.push(difference(&openings[a], &openings[b]));
}
}
all.sort_by(f32::total_cmp);
let median = all[all.len() / 2];
let mut closest = 1.0f32;
for (index, picture) in openings.iter().enumerate() {
assert!(
!picture.is_empty(),
"seed {index} drew no cells at all, so there is no picture to \
compare"
);
for other in openings.iter().skip(index + 1) {
closest = closest.min(difference(picture, other));
}
}
assert_eq!(openings.len(), 20, "not every seed was opened");
assert!(
closest > 0.25,
"two of the twenty seeded openings differ on only {:.0}% of their \
cells, so the starting poses are not varied",
closest * 100.0
);
assert!(
median > 0.8,
"the median pair of the twenty openings differs on only {:.0}% of \
their cells, so the poses are varied in name only",
median * 100.0
);
}
fn mark_shade(ramp: &GlyphRamp, seen: &mut [bool; SHADES], symbol: char) {
if let Some(index) = ramp.glyphs().iter().position(|g| *g == symbol) {
seen[index.min(SHADES - 1)] = true;
}
}
#[test]
fn every_seeded_rate_stays_inside_the_band() {
const SEEDS: u64 = 200;
let bands = [
(DEFAULT_SPEED_A, SPEED_BAND_A),
(DEFAULT_SPEED_B, SPEED_BAND_B),
];
let mut phases: Vec<f32> = Vec::new();
for (axis, (configured, band)) in bands.iter().enumerate() {
let (low, high) = (configured * band.0, configured * band.1);
let mut seen_low = f32::INFINITY;
let mut seen_high = f32::NEG_INFINITY;
for seed in 0..SEEDS {
let motion = DonutOptions {
seed,
..Default::default()
}
.motion();
let rate = if axis == 0 {
motion.speeds.0
} else {
motion.speeds.1
};
assert!(
(low..=high).contains(&rate),
"seed {seed} gave axis {axis} a rate of {rate}, outside the \
band {low}..{high}"
);
seen_low = seen_low.min(rate);
seen_high = seen_high.max(rate);
let phase = if axis == 0 {
motion.phase.0
} else {
motion.phase.1
};
assert!(
(0.0..PHASE_SPAN).contains(&phase),
"seed {seed} gave axis {axis} a phase of {phase}, outside \
0..{PHASE_SPAN}"
);
phases.push(phase);
}
let span = high - low;
assert!(
seen_low <= low + 0.03 * span,
"the slowest rate axis {axis} ever drew was {seen_low}, more than \
3% of the band above its floor of {low}: the draw is not using \
the bottom of the range it was given"
);
assert!(
seen_high >= high - 0.03 * span,
"the quickest rate axis {axis} ever drew was {seen_high}, more than \
3% of the band below its ceiling of {high}: the draw is not \
using the top of the range it was given"
);
}
let phase_low = phases.iter().copied().fold(f32::INFINITY, f32::min);
let phase_high = phases.iter().copied().fold(0.0f32, f32::max);
assert!(
phase_low <= 0.03 * PHASE_SPAN && phase_high >= 0.97 * PHASE_SPAN,
"the phases only covered {phase_low:.3}..{phase_high:.3} of \
0..{PHASE_SPAN}, so the opening poses are not being varied"
);
}
#[test]
fn a_configured_rate_keeps_its_sign_and_its_zero() {
for (axis, configured) in [
(0usize, 0.0f32),
(1, 0.0),
(0, -1.0),
(1, -1.0),
(0, -0.02),
(1, -0.02),
] {
for seed in 1..=5u64 {
let options = DonutOptions {
rotation_speed_a: if axis == 0 {
configured
} else {
DEFAULT_SPEED_A
},
rotation_speed_b: if axis == 1 {
configured
} else {
DEFAULT_SPEED_B
},
seed,
..Default::default()
};
let motion = options.motion();
let rate = match axis {
0 => motion.speeds.0,
_ => motion.speeds.1,
};
assert!(
rate.is_finite(),
"a configured {configured} on axis {axis} became a rate of \
{rate} on seed {seed}"
);
assert!(
(rate == 0.0) == (configured == 0.0)
&& rate.is_sign_negative() == configured.is_sign_negative(),
"a configured {configured} on axis {axis} became a rate of \
{rate} on seed {seed}, so the band is not multiplicative"
);
}
}
}
#[test]
fn a_rate_that_is_not_a_number_falls_back_rather_than_emptying_the_frame() {
for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
for axis in 0..2 {
let options = DonutOptions {
rotation_speed_a: if axis == 0 { bad } else { DEFAULT_SPEED_A },
rotation_speed_b: if axis == 1 { bad } else { DEFAULT_SPEED_B },
seed: 11,
..Default::default()
};
let motion = options.motion();
let drawn = [motion.speeds.0, motion.speeds.1];
assert!(
drawn.iter().all(|r| r.is_finite()),
"a rate of {bad} on axis {axis} left the launch with {drawn:?}"
);
let mut donut = Donut::new(options, (80, 40));
donut.update_size(80, 40);
let picture = whole_frame(&mut donut, 0);
assert!(
picture.len() > 200,
"a rate of {bad} on axis {axis} drew {} cells, so the torus \
is not on the screen",
picture.len()
);
}
}
}
}