use std::f64::consts::TAU;
use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{DEFAULT_SEED, TerminalEffect, seeded_rng};
use crate::render::braille::{BrailleGrid, DOTS_X, DOTS_Y};
use crossterm::style::{self, Color};
use rand::RngExt;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SolarSystemOptions {
pub seed: u64,
pub tilt: f64,
pub camera_speed: f64,
pub year_speed: f64,
pub radius_exponent: f64,
pub sun_size: f64,
pub orbits: bool,
pub rings: bool,
pub stars: usize,
}
impl Default for SolarSystemOptions {
fn default() -> Self {
Self {
seed: DEFAULT_SEED,
tilt: 60.0,
camera_speed: 0.0,
year_speed: 0.1,
radius_exponent: 0.55,
sun_size: 1.8,
orbits: true,
rings: true,
stars: 160,
}
}
}
struct Body {
#[cfg_attr(not(test), allow(dead_code))]
name: &'static str,
semi_major: f64,
period: f64,
radius_km: f64,
inclination: f64,
node: f64,
color: [u8; 3],
}
const PLANETS: &[Body] = &[
Body {
name: "Mercury",
semi_major: 0.3871,
period: 0.2408,
radius_km: 2439.7,
inclination: 7.005,
node: 48.33,
color: [156, 150, 143],
},
Body {
name: "Venus",
semi_major: 0.7233,
period: 0.6152,
radius_km: 6051.8,
inclination: 3.395,
node: 76.68,
color: [226, 208, 156],
},
Body {
name: "Earth",
semi_major: 1.0,
period: 1.0,
radius_km: 6371.0,
inclination: 0.0,
node: 0.0,
color: [74, 142, 206],
},
Body {
name: "Mars",
semi_major: 1.5237,
period: 1.8808,
radius_km: 3389.5,
inclination: 1.850,
node: 49.56,
color: [204, 96, 62],
},
Body {
name: "Jupiter",
semi_major: 5.2026,
period: 11.862,
radius_km: 69911.0,
inclination: 1.304,
node: 100.46,
color: [212, 174, 128],
},
Body {
name: "Saturn",
semi_major: 9.5549,
period: 29.457,
radius_km: 58232.0,
inclination: 2.485,
node: 113.66,
color: [228, 208, 162],
},
Body {
name: "Uranus",
semi_major: 19.218,
period: 84.011,
radius_km: 25362.0,
inclination: 0.773,
node: 74.01,
color: [152, 222, 226],
},
Body {
name: "Neptune",
semi_major: 30.110,
period: 164.79,
radius_km: 24622.0,
inclination: 1.770,
node: 131.78,
color: [78, 108, 224],
},
];
const SATURN: usize = 5;
const RING_TILT: f64 = 26.73;
const RING_INNER: f64 = 1.05;
const RING_OUTER: f64 = 1.7;
const SUN_GLOW_REACH: f64 = 1.9;
const SUN: [u8; 3] = [255, 238, 176];
const GLOW: [u8; 3] = [150, 96, 34];
const BODY_EXPONENT: f64 = 0.45;
const BODY_GAIN_CELLS: f64 = 0.85;
const SUN_GAIN_CELLS: f64 = 0.45;
const CAMERA_DISTANCE_RATIO: f64 = 3.0;
const STAR_SHELL_RATIO: f64 = 1.2;
const ORBIT_DASH_DOTS: f64 = 3.0;
const FIT_BODY: usize = 5;
const MARGIN: f64 = 1.5;
#[derive(Clone, Copy)]
struct Star {
position: (f64, f64, f64),
brightness: f64,
}
struct Projected {
x: f64,
y: f64,
depth: f64,
along: f64,
}
pub struct SolarSystem {
pub screen_size: (u16, u16),
options: SolarSystemOptions,
canvas: Canvas,
dots: BrailleGrid,
cell_colors: Vec<Option<Color>>,
cell_depths: Vec<f64>,
stars: Vec<Star>,
azimuth: f64,
years: f64,
}
impl TerminalEffect for SolarSystem {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.canvas.clear();
self.dots.clear();
for slot in &mut self.cell_colors {
*slot = None;
}
for slot in &mut self.cell_depths {
*slot = f64::INFINITY;
}
let scale = self.fit_scale();
if scale > 0.0 {
self.draw_stars(scale);
if self.options.orbits {
self.draw_orbits(scale);
}
self.draw_bodies(scale);
}
self.flush();
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(width, height);
self.dots.resize(width as usize, height as usize);
let cells = self.dots.width() * self.dots.height();
self.cell_colors = vec![None; cells];
self.cell_depths = vec![f64::INFINITY; cells];
}
fn reset(&mut self) {
let (width, height) = self.screen_size;
self.update_size(width, height);
self.stars = Self::make_stars(&self.options);
self.azimuth = 0.0;
self.years = 0.0;
}
}
impl SolarSystem {
pub fn new(options: SolarSystemOptions, screen_size: (u16, u16)) -> Self {
let width = screen_size.0.max(1) as usize;
let height = screen_size.1.max(1) as usize;
Self {
screen_size,
dots: BrailleGrid::new(width, height),
cell_colors: vec![None; width * height],
cell_depths: vec![f64::INFINITY; width * height],
stars: Self::make_stars(&options),
canvas: Canvas::new(screen_size.0.max(1), screen_size.1.max(1)),
azimuth: 0.0,
years: 0.0,
options,
}
}
fn rate(value: f64) -> f64 {
if value.is_finite() {
value.max(0.0)
} else {
0.0
}
}
fn advance(&mut self, delta: f64) {
self.azimuth += Self::rate(self.options.camera_speed).to_radians() * delta;
self.years += Self::rate(self.options.year_speed) * delta;
}
fn make_stars(options: &SolarSystemOptions) -> Vec<Star> {
let mut rng = seeded_rng(options.seed, "solarsystem");
let exponent = guard_exponent(options.radius_exponent);
let outer = PLANETS
.iter()
.map(|p| p.semi_major.powf(exponent))
.fold(0.0f64, f64::max);
let radius = outer * STAR_SHELL_RATIO;
(0..options.stars)
.map(|_| {
let z: f64 = rng.random_range(-1.0..1.0);
let theta: f64 = rng.random_range(0.0..TAU);
let planar = (1.0 - z * z).max(0.0).sqrt();
Star {
position: (
radius * planar * theta.cos(),
radius * planar * theta.sin(),
radius * z,
),
brightness: rng.random_range(0.3..1.0),
}
})
.collect()
}
fn tilt(&self) -> f64 {
let degrees = self.options.tilt;
if degrees.is_finite() {
degrees.clamp(0.0, 90.0)
} else {
SolarSystemOptions::default().tilt
}
}
fn view(&self) -> (f64, f64, f64, f64) {
let radians = self.tilt().to_radians();
(
radians.sin(),
radians.cos(),
self.azimuth.sin(),
self.azimuth.cos(),
)
}
fn tilt_cosine(&self) -> f64 {
self.tilt().to_radians().cos().abs().max(0.15)
}
fn camera_distance(&self) -> f64 {
self.outermost_radius() * CAMERA_DISTANCE_RATIO
}
fn exponent(&self) -> f64 {
guard_exponent(self.options.radius_exponent)
}
fn outermost_radius(&self) -> f64 {
let exponent = self.exponent();
PLANETS
.iter()
.map(|p| p.semi_major.powf(exponent))
.fold(0.0f64, f64::max)
}
fn drawn_radius(&self, planet: &Body) -> f64 {
planet.semi_major.powf(self.exponent())
}
fn body_radius_cells(&self, radius_km: f64) -> f64 {
(radius_km / 6371.0).powf(BODY_EXPONENT) * BODY_GAIN_CELLS
}
fn sun_radius_cells(&self) -> f64 {
let size = self.options.sun_size;
if !(size.is_finite() && size > 0.0) {
return 0.0;
}
size * SUN_GAIN_CELLS
}
fn fit_scale(&self) -> f64 {
let width = f64::from(self.screen_size.0);
let height = f64::from(self.screen_size.1);
if !(width > 0.0 && height > 0.0) {
return 0.0;
}
let radius = self.drawn_radius(&PLANETS[FIT_BODY]);
let distance = self.camera_distance();
let reach = radius * distance / (distance - radius).max(f64::EPSILON);
let vertical = self.tilt_cosine();
let by_width = (width / 2.0 - MARGIN) / reach.max(f64::EPSILON);
let by_height =
(height / 2.0 - MARGIN) / (reach * vertical).max(f64::EPSILON);
by_width.min(by_height).max(0.0)
}
fn project(&self, point: (f64, f64, f64), scale: f64) -> Option<Projected> {
let (sin_tilt, cos_tilt, sin_azimuth, cos_azimuth) = self.view();
let (x, y, z) = point;
let y1 = y * cos_tilt - z * sin_tilt;
let along = y * sin_tilt + z * cos_tilt;
let x2 = x * cos_azimuth + y1 * sin_azimuth;
let y2 = -x * sin_azimuth + y1 * cos_azimuth;
let distance = self.camera_distance();
let depth = distance - along;
if depth <= distance * 0.02 {
return None;
}
let focal = scale * distance;
Some(Projected {
x: f64::from(self.screen_size.0) / 2.0 + x2 * focal / depth,
y: f64::from(self.screen_size.1) / 2.0 - y2 * focal / depth,
depth,
along,
})
}
fn raise(&mut self, dot_x: isize, dot_y: isize, depth: f64, color: Color) {
let (dot_width, dot_height) =
(self.dots.dot_width(), self.dots.dot_height());
if dot_x < 0
|| dot_y < 0
|| dot_x as usize >= dot_width
|| dot_y as usize >= dot_height
{
return;
}
let (dot_x, dot_y) = (dot_x as usize, dot_y as usize);
self.dots.raise_dot(dot_x, dot_y);
let cell_x = dot_x / DOTS_X;
let cell_y = dot_y / DOTS_Y;
let index = cell_y * self.dots.width() + cell_x;
if depth < self.cell_depths[index] {
self.cell_depths[index] = depth;
self.cell_colors[index] = Some(color);
}
}
fn mark(&mut self, at: (f64, f64), color: Color, depth: f64) {
if !(at.0.is_finite() && at.1.is_finite()) {
return;
}
let dot_x = (at.0 * DOTS_X as f64).floor() as isize;
let dot_y = (at.1 * DOTS_Y as f64).floor() as isize;
self.raise(dot_x, dot_y, depth, color);
}
fn draw_stars(&mut self, scale: f64) {
for index in 0..self.stars.len() {
let star = self.stars[index];
let Some(p) = self.project(star.position, scale) else {
continue;
};
if p.along > 0.0 {
continue;
}
let level = 70.0 + 150.0 * star.brightness;
self.mark(
(p.x, p.y),
Color::Rgb {
r: level as u8,
g: level as u8,
b: (level * 1.06).min(255.0) as u8,
},
p.depth,
);
}
}
fn draw_orbits(&mut self, scale: f64) {
for planet in PLANETS {
let radius = self.drawn_radius(planet);
let color = rgb(dim(planet.color, 0.55));
let circumference = TAU * radius * scale * DOTS_X as f64;
let samples = (circumference * 2.0).clamp(64.0, 2048.0) as usize;
let start = self.mean_anomaly(planet);
let mut previous: Option<Projected> = None;
let mut since_last = ORBIT_DASH_DOTS;
for step in 0..samples {
let angle = start + TAU * step as f64 / samples as f64;
let point = self.orbit_point(planet, radius, angle);
let Some(p) = self.project(point, scale) else {
previous = None;
since_last = ORBIT_DASH_DOTS;
continue;
};
since_last += match previous {
Some(q) => ((p.x - q.x) * DOTS_X as f64)
.hypot((p.y - q.y) * DOTS_Y as f64),
None => ORBIT_DASH_DOTS,
};
previous = Some(Projected {
x: p.x,
y: p.y,
depth: p.depth,
along: p.along,
});
if since_last >= ORBIT_DASH_DOTS {
since_last = 0.0;
self.mark((p.x, p.y), color, p.depth);
}
}
}
}
fn mean_anomaly(&self, planet: &Body) -> f64 {
if !planet.period.is_finite() || planet.period <= 0.0 {
return 0.0;
}
(self.years / planet.period * TAU) % TAU
}
fn orbit_point(
&self,
planet: &Body,
radius: f64,
angle: f64,
) -> (f64, f64, f64) {
let inclination = planet.inclination.to_radians();
let node = planet.node.to_radians();
let (sin_i, cos_i) = inclination.sin_cos();
let (sin_n, cos_n) = node.sin_cos();
let x_plane = radius * angle.cos();
let y_plane = radius * angle.sin();
let x_tilted = x_plane;
let y_tilted = y_plane * cos_i;
let z_tilted = y_plane * sin_i;
(
x_tilted * cos_n - y_tilted * sin_n,
x_tilted * sin_n + y_tilted * cos_n,
z_tilted,
)
}
fn draw_bodies(&mut self, scale: f64) {
self.draw_sun(scale);
let mut order: Vec<(f64, usize)> = PLANETS
.iter()
.enumerate()
.map(|(index, planet)| {
let radius = self.drawn_radius(planet);
let point =
self.orbit_point(planet, radius, self.mean_anomaly(planet));
let depth = self
.project(point, scale)
.map_or(f64::INFINITY, |p| p.depth);
(depth, index)
})
.collect();
order.sort_by(|a, b| b.0.total_cmp(&a.0));
for (_, index) in order {
let planet = &PLANETS[index];
let radius = self.drawn_radius(planet);
let centre =
self.orbit_point(planet, radius, self.mean_anomaly(planet));
if index == SATURN && self.options.rings {
self.draw_rings(planet, centre, scale);
}
self.draw_disc(
centre,
self.body_radius_cells(planet.radius_km),
planet.color,
scale,
);
}
}
fn draw_sun(&mut self, scale: f64) {
let core = self.sun_radius_cells();
if core <= 0.0 {
return;
}
let Some(centre) = self.project((0.0, 0.0, 0.0), scale) else {
return;
};
let on_screen = core * SUN_GLOW_REACH;
if !on_screen.is_finite() || on_screen <= 0.0 {
return;
}
let grid_w = self.screen_size.0 as isize * DOTS_X as isize;
let grid_h = self.screen_size.1 as isize * DOTS_Y as isize;
let dot_reach = ((on_screen * DOTS_X as f64).ceil() as isize)
.clamp(0, grid_w.max(grid_h));
let dot_x0 = (centre.x * DOTS_X as f64).floor() as isize;
let dot_y0 = (centre.y * DOTS_Y as f64).floor() as isize;
let core_fraction = (1.0 / SUN_GLOW_REACH).clamp(0.0, 1.0);
for dy in -dot_reach..=dot_reach {
for dx in -dot_reach..=dot_reach {
let distance = (dx as f64).hypot(dy as f64) / DOTS_X as f64;
if distance > on_screen {
continue;
}
let falloff =
(distance / on_screen - core_fraction) / (1.0 - core_fraction);
let t = falloff.clamp(0.0, 1.0);
if falloff > 0.0 && speckle(dx as u32, dy as u32) > 1.0 - t {
continue;
}
let color = [
(SUN[0] as f64 + (GLOW[0] as f64 - SUN[0] as f64) * t) as u8,
(SUN[1] as f64 + (GLOW[1] as f64 - SUN[1] as f64) * t) as u8,
(SUN[2] as f64 + (GLOW[2] as f64 - SUN[2] as f64) * t) as u8,
];
self.raise(dot_x0 + dx, dot_y0 + dy, centre.depth, rgb(color));
}
}
}
fn draw_rings(&mut self, planet: &Body, centre: (f64, f64, f64), scale: f64) {
self.draw_ring_edges(planet, centre, scale, &[RING_INNER, RING_OUTER]);
}
fn draw_ring_edges(
&mut self,
planet: &Body,
centre: (f64, f64, f64),
scale: f64,
edges: &[f64],
) {
let Some(p) = self.project(centre, scale) else {
return;
};
let body = self.body_radius_cells(planet.radius_km);
let tilt = RING_TILT.to_radians();
let cos_t = tilt.cos();
let color = rgb(dim(planet.color, 0.8));
let samples = 160;
for step in 0..samples {
let angle = TAU * step as f64 / samples as f64;
let (sin_a, cos_a) = angle.sin_cos();
for &edge in edges {
let r = body * edge;
self.mark(
(p.x + r * cos_a, p.y - r * sin_a * cos_t),
color,
p.depth,
);
}
}
}
fn draw_disc(
&mut self,
centre: (f64, f64, f64),
radius_cells: f64,
color: [u8; 3],
scale: f64,
) {
let Some(p) = self.project(centre, scale) else {
return;
};
let on_screen = radius_cells.max(0.5 / DOTS_X as f64);
let dot_x0 = (p.x * DOTS_X as f64).floor() as isize;
let dot_y0 = (p.y * DOTS_Y as f64).floor() as isize;
let reach = (on_screen * DOTS_X as f64).ceil() as isize;
let vertical =
(reach as f64 * DOTS_Y as f64 / DOTS_X as f64).ceil() as isize;
for dy in -vertical..=vertical {
for dx in -reach..=reach {
if (dx as f64).hypot(dy as f64) > reach as f64 {
continue;
}
self.raise(dot_x0 + dx, dot_y0 + dy, p.depth, rgb(color));
}
}
}
fn flush(&mut self) {
let width = self.dots.width();
for cell_y in 0..self.dots.height().min(self.canvas.height()) {
for cell_x in 0..width.min(self.canvas.width()) {
let Some(color) = self.cell_colors[cell_y * width + cell_x] else {
continue;
};
let symbol = self.dots.cell_char(cell_x, cell_y);
if symbol == '\u{2800}' {
continue;
}
self.canvas.set(
cell_x,
cell_y,
Cell::new(symbol, color, style::Attribute::Reset),
);
}
}
}
}
fn speckle(x: u32, y: u32) -> f64 {
let mut h = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
h ^= h >> 29;
h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9);
h ^= h >> 32;
(h >> 40) as f64 / (1u64 << 24) as f64
}
fn guard_exponent(value: f64) -> f64 {
if value.is_finite() && value > 0.0 {
value
} else {
SolarSystemOptions::default().radius_exponent
}
}
fn dim(color: [u8; 3], factor: f64) -> [u8; 3] {
[
(color[0] as f64 * factor) as u8,
(color[1] as f64 * factor) as u8,
(color[2] as f64 * factor) as u8,
]
}
fn rgb(color: [u8; 3]) -> Color {
Color::Rgb {
r: color[0],
g: color[1],
b: color[2],
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::{BTreeMap, HashSet};
fn drawn(size: (u16, u16), frames: u64) -> Vec<Vec<char>> {
let mut system = SolarSystem::new(SolarSystemOptions::default(), size);
for _ in 0..frames {
system.advance(1.0 / 60.0);
}
let mut grid = vec![vec![' '; size.0 as usize]; size.1 as usize];
for (x, y, cell) in system.get_diff() {
grid[y][x] = cell.symbol;
}
grid
}
fn inked(size: (u16, u16)) -> usize {
drawn(size, 0)
.iter()
.flatten()
.filter(|c| **c != ' ')
.count()
}
#[test]
fn the_system_draws_something() {
for size in [(80u16, 24u16), (200, 50), (400, 200), (40, 12), (12, 40)] {
assert!(
inked(size) > size.0 as usize / 2,
"at {}x{} only {} cells were drawn",
size.0,
size.1,
inked(size)
);
}
}
#[test]
fn the_orbital_periods_are_the_real_ones() {
let by_name = |name: &str| {
PLANETS
.iter()
.find(|p| p.name == name)
.unwrap_or_else(|| panic!("no planet called {name}"))
};
let ratio = |a: &str, b: &str| by_name(a).period / by_name(b).period;
assert!(
(ratio("Mercury", "Earth") - 0.2408).abs() < 1.0e-4,
"Mercury's year is {} of Earth's, not 0.2408",
ratio("Mercury", "Earth")
);
assert!(
(ratio("Earth", "Mars") - 0.5317).abs() < 1.0e-3,
"Earth's year is {} of Mars's, not 0.5317",
ratio("Earth", "Mars")
);
assert!(
(ratio("Earth", "Jupiter") - 0.0843).abs() < 1.0e-3,
"Earth's year is {} of Jupiter's, not 0.0843",
ratio("Earth", "Jupiter")
);
for pair in PLANETS.windows(2) {
assert!(
pair[0].period < pair[1].period,
"{} has a longer year than {}",
pair[0].name,
pair[1].name
);
}
}
#[test]
fn the_orbits_are_ellipses_not_circles() {
let size = (120u16, 40u16);
let system = SolarSystem::new(SolarSystemOptions::default(), size);
let scale = system.fit_scale();
let jupiter = &PLANETS[4];
let radius = system.drawn_radius(jupiter);
let mut min_x = f64::MAX;
let mut max_x = f64::MIN;
let mut min_y = f64::MAX;
let mut max_y = f64::MIN;
for step in 0..360 {
let angle = TAU * step as f64 / 360.0;
let point = system.orbit_point(jupiter, radius, angle);
if let Some(p) = system.project(point, scale) {
min_x = min_x.min(p.x);
max_x = max_x.max(p.x);
min_y = min_y.min(p.y);
max_y = max_y.max(p.y);
}
}
let across = max_x - min_x;
let down = max_y - min_y;
assert!(
across > 0.0 && down > 0.0,
"Jupiter's orbit projected to nothing: {across} by {down}"
);
let ratio = down / across;
assert!(
(0.2..0.95).contains(&ratio),
"Jupiter's orbit is {across:.1} across by {down:.1} down, a ratio of \
{ratio:.2}. A ratio near 1 is a circle, which means the tilt is not \
reaching the projection; a ratio near 0 is edge-on.",
);
}
#[test]
fn moving_the_camera_changes_the_view() {
let size = (120u16, 40u16);
let at_azimuth = |degrees: f64| {
let mut system = SolarSystem::new(SolarSystemOptions::default(), size);
system.azimuth = degrees.to_radians();
system.get_diff()
};
let first = at_azimuth(0.0);
let quarter = at_azimuth(90.0);
assert_ne!(
first, quarter,
"swinging the camera 90 degrees drew exactly the same frame, so the \
azimuth is not reaching the projection"
);
}
#[test]
fn the_near_side_of_an_orbit_is_drawn_larger_than_the_far_side() {
let size = (120u16, 40u16);
let ratio_for = |index: usize| {
let mut system = SolarSystem::new(SolarSystemOptions::default(), size);
let scale = system.fit_scale();
let radius = system.drawn_radius(&PLANETS[index]);
system.azimuth = 0.0;
let near = system.project((0.0, radius, 0.0), scale).unwrap();
let far = system.project((0.0, -radius, 0.0), scale).unwrap();
assert!(
near.depth < far.depth,
"{}'s two ends came out at the same depth: {} and {}",
PLANETS[index].name,
near.depth,
far.depth
);
far.depth / near.depth
};
let jupiter = ratio_for(4);
let neptune = ratio_for(7);
assert!(
jupiter > 1.15,
"Jupiter's near and far sides differ by only {jupiter:.2}x, so the \
perspective is too weak to read as depth"
);
assert!(
neptune > 1.5,
"Neptune's near and far sides differ by only {neptune:.2}x"
);
assert!(
neptune > jupiter,
"Neptune is further from the camera's axis than Jupiter, so it must \
show *more* perspective, not less: {neptune:.2}x against \
{jupiter:.2}x"
);
}
#[test]
fn the_fit_uses_the_screen_without_running_off_it() {
for size in [
(80u16, 24u16),
(200, 50),
(400, 200),
(40, 12),
(12, 40),
(200, 8),
] {
let system = SolarSystem::new(SolarSystemOptions::default(), size);
let scale = system.fit_scale();
assert!(
scale > 0.0 && scale.is_finite(),
"at {}x{} the fitted scale is {scale}",
size.0,
size.1
);
let radius = system.drawn_radius(&PLANETS[FIT_BODY]);
let distance = system.camera_distance();
let reach = radius * distance / (distance - radius);
let across = 2.0 * reach * scale;
assert!(
across <= f64::from(size.0) - 1.0,
"at {}x{} the fitted orbit is {across:.1} cells across on an \
{} cell screen",
size.0,
size.1,
size.0
);
}
}
#[test]
fn the_inner_system_is_readable_on_a_screen_with_room_for_it() {
for size in [(80u16, 24u16), (120, 40), (200, 50), (400, 200)] {
let system = SolarSystem::new(SolarSystemOptions::default(), size);
let inner = system.drawn_radius(&PLANETS[0]) * system.fit_scale();
assert!(
inner > 1.0,
"at {}x{} Mercury's orbit has a radius of {inner:.2} cells, so \
the inner system is a dot",
size.0,
size.1
);
}
}
#[test]
fn true_scale_is_available_and_is_a_dot() {
let true_scale_options = SolarSystemOptions {
radius_exponent: 1.0,
..Default::default()
};
let compressed = {
let system = SolarSystem::new(SolarSystemOptions::default(), (80, 24));
system.drawn_radius(&PLANETS[0]) * system.fit_scale()
};
let true_scale = {
let system = SolarSystem::new(true_scale_options, (80, 24));
system.drawn_radius(&PLANETS[0]) * system.fit_scale()
};
assert!(
true_scale < compressed / 2.0,
"at true scale Mercury's orbit has a radius of {true_scale:.3} cells \
against {compressed:.3} compressed, so the exponent is not doing the \
work it is documented as doing"
);
}
#[test]
fn a_planet_in_front_of_the_sun_is_not_painted_over() {
let size = (120u16, 40u16);
let mut system = SolarSystem::new(SolarSystemOptions::default(), size);
let scale = system.fit_scale();
let earth = &PLANETS[2];
let radius = system.drawn_radius(earth);
let point = system.orbit_point(earth, radius, TAU / 4.0);
let Some(p) = system.project(point, scale) else {
panic!("the fixture projected nothing");
};
assert!(
p.depth < system.camera_distance(),
"the fixture put the planet behind the sun, so it proves nothing"
);
let sun_depth = system
.project((0.0, 0.0, 0.0), scale)
.map(|p| p.depth)
.unwrap();
assert!(
p.depth < sun_depth,
"a planet nearer the camera than the sun must beat the sun in the \
depth buffer, but came out at {} against {sun_depth}",
p.depth
);
let diff = system.get_diff();
let cell_x = p.x.floor() as isize;
let cell_y = p.y.floor() as isize;
let drawn = diff
.iter()
.find(|(x, y, _)| *x as isize == cell_x && *y as isize == cell_y);
assert!(
drawn.is_some(),
"nothing was drawn at the planet's own position ({cell_x}, {cell_y})"
);
}
#[test]
fn everything_drawn_is_a_braille_character() {
let size = (120u16, 40u16);
let mut system = SolarSystem::new(SolarSystemOptions::default(), size);
for _ in 0..8 {
system.advance(1.0 / 60.0);
}
let diff = system.get_diff();
assert!(!diff.is_empty(), "nothing was drawn");
for (x, y, cell) in diff {
assert!(
('\u{2800}'..='\u{28FF}').contains(&cell.symbol),
"cell ({x}, {y}) is {:?}, which is not a braille character",
cell.symbol
);
assert_ne!(
cell.symbol, '\u{2800}',
"cell ({x}, {y}) is a blank braille glyph, so a cell was written \
for nothing -- the byte volume goes up and the background stops \
showing through"
);
}
}
#[test]
fn the_frame_does_not_paint_the_whole_screen() {
let size = (200u16, 50u16);
let mut system = SolarSystem::new(SolarSystemOptions::default(), size);
let diff = system.get_diff();
let total = usize::from(size.0) * usize::from(size.1);
assert!(
diff.len() < total / 2,
"{} of {total} cells were written, so the background is being \
painted rather than showing through",
diff.len()
);
}
#[test]
fn no_cell_is_bold_and_every_colour_is_a_truecolor_triple() {
let size = (120u16, 40u16);
let mut system = SolarSystem::new(SolarSystemOptions::default(), size);
for _ in 0..4 {
system.advance(1.0 / 60.0);
}
let mut seen: HashSet<(u8, u8, u8)> = HashSet::new();
for (x, y, cell) in system.get_diff() {
assert_eq!(
cell.attr,
style::Attribute::Reset,
"cell ({x}, {y}) is bold, which brightens a truecolor foreground \
into something the palette did not ask for"
);
match cell.color {
Color::Rgb { r, g, b } => {
seen.insert((r, g, b));
}
other => {
panic!("cell ({x}, {y}) is {other:?}, not a truecolor triple")
}
}
}
assert!(
seen.len() >= 8,
"only {} distinct colours were drawn, so the planets are not \
distinguishable from each other",
seen.len()
);
}
#[test]
fn nothing_is_drawn_outside_the_screen() {
for size in [(80u16, 24u16), (200, 50), (12, 40), (40, 12), (9, 9)] {
let mut system = SolarSystem::new(SolarSystemOptions::default(), size);
for _ in 0..5 {
system.advance(1.0 / 60.0);
}
for (x, y, _) in system.get_diff() {
assert!(
x < size.0 as usize && y < size.1 as usize,
"at {}x{} a cell was emitted at ({x}, {y})",
size.0,
size.1
);
}
}
}
#[test]
fn the_keys_round_trip_through_toml() {
let options: SolarSystemOptions =
toml::from_str("tilt = 45.0\ncamera_speed = 12.0\nrings = false\n")
.expect("three keys parse");
assert_eq!(options.tilt, 45.0);
assert_eq!(options.camera_speed, 12.0);
assert!(!options.rings);
assert_eq!(
options.year_speed,
SolarSystemOptions::default().year_speed,
"three keys in the section silently reset the others"
);
let serialised = toml::to_string(&options).expect("the section serialises");
for key in [
"seed",
"tilt",
"camera_speed",
"year_speed",
"radius_exponent",
"sun_size",
"orbits",
"rings",
"stars",
] {
assert!(
serialised.contains(key),
"{key} is missing from the serialised form: {serialised}"
);
}
}
#[test]
fn a_degenerate_config_draws_something_anyway() {
type Setter = (&'static str, fn(&mut SolarSystemOptions, f64));
let fields: [Setter; 4] = [
("radius_exponent", |o, v| o.radius_exponent = v),
("tilt", |o, v| o.tilt = v),
("sun_size", |o, v| o.sun_size = v),
("year_speed", |o, v| o.year_speed = v),
];
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
for (name, set) in fields {
let mut options = SolarSystemOptions::default();
set(&mut options, bad);
let mut system = SolarSystem::new(options, (80, 24));
system.advance(1.0);
assert!(
inked_of(&mut system) > 20,
"{name} = {bad} drew almost nothing"
);
}
}
}
fn inked_of(system: &mut SolarSystem) -> usize {
system
.get_diff()
.iter()
.filter(|(_, _, cell)| cell.symbol != ' ')
.count()
}
#[test]
fn the_incremental_frame_agrees_with_a_full_repaint() {
let size = (80u16, 24u16);
let options = SolarSystemOptions::default();
let frames = 3u64;
let delta = 1.0 / 60.0;
let mut live = SolarSystem::new(options.clone(), size);
let mut incremental = Vec::new();
for _ in 0..frames {
live.advance(delta);
incremental = live.get_diff();
}
let mut reference = SolarSystem::new(options, size);
for _ in 0..frames {
reference.advance(delta);
}
let truth: BTreeMap<(usize, usize), char> = reference
.get_diff()
.into_iter()
.map(|(x, y, cell)| ((x, y), cell.symbol))
.collect();
let mut disagreed = Vec::new();
for (x, y, cell) in &incremental {
match truth.get(&(*x, *y)) {
Some(symbol) if *symbol == cell.symbol => {}
Some(symbol) => disagreed.push(format!(
"({x}, {y}) sent {:?} but the frame draws {symbol:?}",
cell.symbol
)),
None if cell.symbol == ' ' || cell.symbol == '\u{2800}' => {}
None => disagreed.push(format!(
"({x}, {y}) sent {:?} but the frame is blank there",
cell.symbol
)),
}
}
assert!(
disagreed.is_empty(),
"the incremental diff disagrees with a full repaint on {} cells, so \
the terminal is being told to draw something the effect did not \
draw. First few: {}",
disagreed.len(),
disagreed
.iter()
.take(6)
.cloned()
.collect::<Vec<_>>()
.join("; ")
);
assert!(
!incremental.is_empty(),
"the third frame was empty, so this test is comparing nothing"
);
}
#[test]
fn the_sky_is_reproducible_and_seed_sensitive() {
let frame = |seed: u64, frames: u64| {
let options = SolarSystemOptions {
seed,
..Default::default()
};
let mut system = SolarSystem::new(options, (80, 24));
for _ in 0..frames {
system.advance(1.0 / 60.0);
}
system.get_diff()
};
for frames in [0u64, 1, 30] {
assert_eq!(
frame(1234, frames),
frame(1234, frames),
"two systems at seed 1234 differ after {frames} frames"
);
assert_ne!(
frame(1234, frames),
frame(4321, frames),
"seeds 1234 and 4321 drew the same sky after {frames} frames"
);
}
}
#[derive(Debug, Default, Clone, Copy)]
struct Reach {
dots: usize,
cells: f64,
across: f64,
}
#[derive(Clone, Copy)]
enum Subject {
Planet,
Ring(f64),
}
fn reach_of(size: (u16, u16), frames: u64, subject: Subject) -> Reach {
let mut system = SolarSystem::new(SolarSystemOptions::default(), size);
for _ in 0..frames {
system.advance(1.0 / 60.0);
}
let scale = system.fit_scale();
let saturn = &PLANETS[SATURN];
let centre = system.orbit_point(
saturn,
system.drawn_radius(saturn),
system.mean_anomaly(saturn),
);
let projected = system
.project(centre, scale)
.expect("Saturn is behind the camera at every rotation tested here");
let (centre_x, centre_y) = (
(projected.x * DOTS_X as f64).floor(),
(projected.y * DOTS_Y as f64).floor(),
);
system.dots.clear();
match subject {
Subject::Planet => system.draw_disc(
centre,
system.body_radius_cells(saturn.radius_km),
saturn.color,
scale,
),
Subject::Ring(edge) => {
system.draw_ring_edges(saturn, centre, scale, &[edge])
}
}
let mut reach = Reach::default();
system.dots.for_each_dot(|x, y, raised| {
if raised {
let dx = x as f64 - centre_x;
let dy = y as f64 - centre_y;
reach.dots += 1;
reach.cells = reach
.cells
.max((dx / DOTS_X as f64).hypot(dy / DOTS_Y as f64));
reach.across = reach.across.max(dx.abs());
}
});
reach
}
#[test]
fn the_rings_are_a_ring_around_a_planet_and_not_a_hoop_around_a_solar_system() {
const ROTATIONS: [u64; 4] = [0, 300, 900, 1500];
let mut ratios = Vec::new();
for size in [(80u16, 24u16), (200u16, 50u16)] {
for frames in ROTATIONS {
let planet = reach_of(size, frames, Subject::Planet);
let inner = reach_of(size, frames, Subject::Ring(RING_INNER));
let outer = reach_of(size, frames, Subject::Ring(RING_OUTER));
assert!(
planet.dots > 0 && inner.dots > 0 && outer.dots > 0,
"on {size:?} at frame {frames} the planet raised {} dots, the \
inner edge {} and the outer {}, so this measured nothing",
planet.dots,
inner.dots,
outer.dots
);
let ratio = outer.cells / planet.cells;
ratios.push(ratio);
assert!(
(1.3..=2.0).contains(&ratio),
"on {size:?} at frame {frames} the outer ring edge reaches \
{:.2} cells from Saturn's centre and the planet is {:.2}, so \
the ring is {ratio:.1} times the body -- past 2.0 it is a hoop \
drawn across the picture rather than rings on a planet",
outer.cells,
planet.cells
);
assert!(
inner.cells >= planet.cells * 0.95,
"on {size:?} at frame {frames} the inner ring edge is only \
{:.2} cells out against a planet of {:.2}, so the ring starts \
inside the body",
inner.cells,
planet.cells
);
let band = outer.cells - inner.cells;
let band_dots = outer.across - inner.across;
assert!(
band >= 1.0,
"on {size:?} at frame {frames} the two ring edges are {band:.2} \
cells apart, so they are one edge and not an annulus"
);
assert!(
band_dots >= 2.0,
"on {size:?} at frame {frames} the two ring edges are \
{band_dots:.0} dots apart across, which is not enough to read \
as two edges"
);
}
}
let widest = ratios.iter().cloned().fold(0.0f64, f64::max);
let narrowest = ratios.iter().cloned().fold(f64::INFINITY, f64::min);
assert!(
widest - narrowest < 0.1,
"the ring measures {narrowest:.2} times the planet on one terminal and \
{widest:.2} on another, so the ring is being sized in world units \
and the planet in cells"
);
}
}