use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{DEFAULT_SEED, EffectRng, TerminalEffect, seeded_rng};
use crate::render::BrailleGrid;
use crate::render::braille::{DOTS_X, DOTS_Y};
use crossterm::style;
use rand::RngExt;
use serde::{Deserialize, Serialize};
const DVD_WORDMARK: &str = "\
.....#######################.........#################......
.....#######################........#####################...
.....#######################........######################..
....########################.......########################.
....######.....##############.....#############.....########
....######.......############.....######.######......#######
...#######.......############....######.#######......#######
...######........######.######..######..######.......#######
...######........######.######..######.#######.......#######
...######.......#######..############..#######.......######.
...######......#######...###########...#######.....########.
...######....########....##########....######.....########..
###################.....########.....##################.....
#################.......#######......################.......
###############.........#######......##############.........
############.............#####.......############...........
...........................####.............................
...........................###..............................
...........................##...............................
....................#################.......................
.......###########################################..........
...##################################################.......
.###########.##..###.####....####...####.....##########.....
###############.####.####.##.####.#####.####.############...
#############..#####.####.##.####.######.###.###########....
..############.#####.####....####...####....##########......
.....###############################################........
..............#############################.................";
fn is_blank(symbol: char) -> bool {
symbol == ' ' || symbol == '.'
}
const PALETTE: [(u8, u8, u8); 12] = [
(224, 34, 34),
(171, 98, 26),
(120, 120, 18),
(75, 130, 20),
(20, 135, 20),
(20, 133, 76),
(19, 128, 128),
(31, 117, 204),
(90, 70, 240),
(193, 0, 232),
(194, 31, 209),
(214, 32, 138),
];
const DT: f64 = 1.0 / 60.0;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DvdOptions {
pub logo: String,
pub speed: f32,
pub slope: f32,
pub color_change: ColorChange,
pub start_in_corner: bool,
pub corner_wave: bool,
pub seed: u64,
}
const WAVE_SPEED: f64 = 46.0;
const WAVE_LIFE: f64 = 1.1;
const WAVE_HALF_WIDTH: f64 = 2.0;
const WAVE_GLYPH: char = '\u{00B7}';
const MAX_WAVES: usize = 3;
struct CornerWave {
cx: f64,
cy: f64,
age: f64,
}
const RECOLOR_EVERY_N_BOUNCES: u32 = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ColorChange {
Steady,
#[default]
Bounce,
Corner,
Never,
}
impl ColorChange {
pub const ALL: &'static [ColorChange] = &[
ColorChange::Steady,
ColorChange::Bounce,
ColorChange::Corner,
ColorChange::Never,
];
pub fn should_change(self, hit_x: bool, hit_y: bool, wall_hits: u32) -> bool {
match self {
ColorChange::Steady => {
(hit_x || hit_y) && wall_hits >= RECOLOR_EVERY_N_BOUNCES
}
ColorChange::Bounce => hit_x || hit_y,
ColorChange::Corner => hit_x && hit_y,
ColorChange::Never => false,
}
}
}
impl Default for DvdOptions {
fn default() -> Self {
Self {
logo: String::from(DVD_WORDMARK),
speed: 12.0,
slope: 2.0,
color_change: ColorChange::default(),
start_in_corner: true,
corner_wave: true,
seed: DEFAULT_SEED,
}
}
}
pub struct Dvd {
screen_size: (u16, u16),
options: DvdOptions,
canvas: Canvas,
grid: BrailleGrid,
rows: Vec<Vec<char>>,
x: f64,
y: f64,
vx: f64,
vy: f64,
color_index: usize,
wall_hits: u32,
corner_this_frame: bool,
waves: Vec<CornerWave>,
rng: EffectRng,
}
impl TerminalEffect for Dvd {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.draw()
}
fn update(&mut self) {
self.step(DT);
}
fn update_with_context(&mut self, context: &crate::runtime::FrameContext) {
self.step(context.delta.as_secs_f64().min(0.1));
}
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);
self.reset();
}
fn reset(&mut self) {
self.canvas
.resize(self.screen_size.0.max(1), self.screen_size.1.max(1));
self.rows = Self::parse_logo(&self.options.logo);
self.grid.resize(self.grid_w(), self.grid_h());
self.rng = seeded_rng(self.options.seed, "dvd");
let logo_width = self.logo_width();
let logo_height = self.logo_height();
let max_x = (self.screen_size.0 as f64 - logo_width).max(0.0);
let max_y = (self.screen_size.1 as f64 - logo_height).max(0.0);
let speed = self.options.speed.max(0.1) as f64;
if self.options.start_in_corner {
let corner = self.rng.random_range(0..4);
self.x = if corner & 1 == 0 { 0.0 } else { max_x };
self.y = if corner & 2 == 0 { 0.0 } else { max_y };
let across = speed;
let down = speed / f64::from(self.options.slope).max(0.1);
self.vx = if self.x <= 0.0 { across } else { -across };
self.vy = if self.y <= 0.0 { down } else { -down };
} else {
self.x = max_x / 2.0;
self.y = max_y / 2.0;
self.vx = speed;
self.vy = speed / f64::from(self.options.slope).max(0.1);
}
self.color_index = self.rng.random_range(0..PALETTE.len());
self.wall_hits = 0;
self.corner_this_frame = false;
self.waves.clear();
}
}
impl Dvd {
pub fn new(options: DvdOptions, screen_size: (u16, u16)) -> Self {
let screen_size = (screen_size.0.max(1), screen_size.1.max(1));
let seed = options.seed;
let mut effect = Self {
screen_size,
canvas: Canvas::new(screen_size.0, screen_size.1),
grid: BrailleGrid::new(1, 1),
rows: Vec::new(),
x: 0.0,
y: 0.0,
vx: 1.0,
vy: 1.0,
color_index: 0,
wall_hits: 0,
corner_this_frame: false,
waves: Vec::new(),
rng: seeded_rng(seed, "dvd"),
options,
};
effect.reset();
effect
}
fn parse_logo(logo: &str) -> Vec<Vec<char>> {
let rows: Vec<Vec<char>> = logo
.split('\n')
.filter(|row| !row.trim().is_empty())
.map(|row| row.chars().collect())
.collect();
if rows.is_empty() {
vec![vec!['*']]
} else {
rows
}
}
fn logo_dot_width(&self) -> usize {
self.rows.iter().map(Vec::len).fold(0, usize::max).max(1)
}
fn logo_dot_height(&self) -> usize {
self.rows.len().max(1)
}
fn logo_cells_w(&self) -> usize {
self.logo_dot_width().div_ceil(DOTS_X)
}
fn logo_cells_h(&self) -> usize {
self.logo_dot_height().div_ceil(DOTS_Y)
}
fn grid_w(&self) -> usize {
self.logo_cells_w() + 1
}
fn grid_h(&self) -> usize {
self.logo_cells_h() + 1
}
fn logo_width(&self) -> f64 {
self.logo_cells_w() as f64
}
fn logo_height(&self) -> f64 {
self.logo_cells_h() as f64
}
fn ink_at(&self, dot_x: usize, dot_y: usize) -> bool {
self.rows
.get(dot_y)
.and_then(|row| row.get(dot_x))
.is_some_and(|symbol| !is_blank(*symbol))
}
fn step(&mut self, delta: f64) {
let logo_width = self.logo_width();
let logo_height = self.logo_height();
let max_x = (self.screen_size.0 as f64 - logo_width).max(0.0);
let max_y = (self.screen_size.1 as f64 - logo_height).max(0.0);
self.x += self.vx * delta;
self.y += self.vy * delta;
let mut hit_x = false;
let mut hit_y = false;
if max_x > 0.0 {
if self.x <= 0.0 {
self.x = 0.0;
self.vx = self.vx.abs();
hit_x = true;
} else if self.x >= max_x {
self.x = max_x;
self.vx = -self.vx.abs();
hit_x = true;
}
} else {
self.x = 0.0;
self.vx = 0.0;
}
if max_y > 0.0 {
if self.y <= 0.0 {
self.y = 0.0;
self.vy = self.vy.abs();
hit_y = true;
} else if self.y >= max_y {
self.y = max_y;
self.vy = -self.vy.abs();
hit_y = true;
}
} else {
self.y = 0.0;
self.vy = 0.0;
}
if hit_x || hit_y {
self.wall_hits = self.wall_hits.saturating_add(1);
}
self.corner_this_frame = hit_x && hit_y;
if self.corner_this_frame && self.options.corner_wave {
self.waves.push(CornerWave {
cx: self.x,
cy: self.y,
age: 0.0,
});
if self.waves.len() > MAX_WAVES {
self.waves.remove(0);
}
}
for wave in &mut self.waves {
wave.age += delta;
}
self.waves.retain(|wave| wave.age < WAVE_LIFE);
if self
.options
.color_change
.should_change(hit_x, hit_y, self.wall_hits)
{
self.color_index = (self.color_index + 1) % PALETTE.len();
self.wall_hits = 0;
}
}
fn draw_waves(&mut self, ink: style::Color) {
let style::Color::Rgb { r, g, b } = ink else {
return;
};
let waves: Vec<(f64, f64, f64)> = self
.waves
.iter()
.map(|wave| (wave.cx, wave.cy, wave.age))
.collect();
for (cx, cy, age) in waves {
let remaining = 1.0 - (age / WAVE_LIFE).clamp(0.0, 1.0);
let color = style::Color::Rgb {
r: (r as f64 * remaining) as u8,
g: (g as f64 * remaining) as u8,
b: (b as f64 * remaining) as u8,
};
let radius = WAVE_SPEED * age;
let inner = (radius - WAVE_HALF_WIDTH).max(0.0);
let outer = radius + WAVE_HALF_WIDTH;
let mut r = inner;
while r <= outer {
if r > 0.0 {
self.stamp_ring(cx, cy, r, color);
}
r += 1.0;
}
}
}
fn stamp_ring(&mut self, cx: f64, cy: f64, radius: f64, color: style::Color) {
let samples = (std::f64::consts::TAU * radius).ceil().max(8.0) as usize;
let cell = Cell::new(WAVE_GLYPH, color, style::Attribute::Reset);
for index in 0..samples {
let angle = std::f64::consts::TAU * index as f64 / samples as f64;
let x = (cx + radius * angle.cos()).round();
let y = (cy + radius * angle.sin()).round();
if x < 0.0 || y < 0.0 {
continue;
}
let (x, y) = (x as usize, y as usize);
if x >= self.canvas.width() || y >= self.canvas.height() {
continue;
}
self.canvas.set(x, y, cell);
}
}
fn draw(&mut self) -> Vec<(usize, usize, Cell)> {
let (r, g, b) = PALETTE[self.color_index % PALETTE.len()];
let ink = style::Color::Rgb { r, g, b };
self.grid.clear();
self.canvas.clear();
self.draw_waves(ink);
let left = (self.x * DOTS_X as f64).floor().max(0.0) as usize;
let top = (self.y * DOTS_Y as f64).floor().max(0.0) as usize;
self.paint_at(left, top);
let left_cell = left / DOTS_X;
let top_cell = top / DOTS_Y;
for cell_y in 0..self.grid.height() {
let y = top_cell + cell_y;
if y >= self.canvas.height() {
break;
}
for cell_x in 0..self.grid.width() {
let symbol = self.grid.cell_char(cell_x, cell_y);
if symbol == ' ' {
continue;
}
let x = left_cell + cell_x;
if x >= self.canvas.width() {
continue;
}
self.canvas.set(
x,
y,
Cell::new(symbol, ink, style::Attribute::Reset),
);
}
}
self.canvas.commit()
}
fn paint_at(&mut self, left: usize, top: usize) {
let skew_x = (left % DOTS_X) as isize;
let skew_y = (top % DOTS_Y) as isize;
for cell_y in 0..self.grid.height() {
for cell_x in 0..self.grid.width() {
for dy in 0..DOTS_Y {
for dx in 0..DOTS_X {
let dot_x = (cell_x * DOTS_X + dx) as isize - skew_x;
let dot_y = (cell_y * DOTS_Y + dy) as isize - skew_y;
let raised = dot_x >= 0
&& dot_y >= 0
&& self.ink_at(dot_x as usize, dot_y as usize);
self.grid.set_dot(
cell_x * DOTS_X + dx,
cell_y * DOTS_Y + dy,
raised,
);
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::render::braille::{
DOTS_PER_CELL, braille_bit, braille_dot_position,
};
use std::time::Duration;
fn options() -> DvdOptions {
DvdOptions {
logo: String::from("DVD"),
start_in_corner: false,
..Default::default()
}
}
fn linear(channel: u8) -> f64 {
let c = f64::from(channel) / 255.0;
if c <= 0.04045 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
}
fn luminance(color: (u8, u8, u8)) -> f64 {
0.2126 * linear(color.0)
+ 0.7152 * linear(color.1)
+ 0.0722 * linear(color.2)
}
fn contrast(a: f64, b: f64) -> f64 {
let (hi, lo) = if a > b { (a, b) } else { (b, a) };
(hi + 0.05) / (lo + 0.05)
}
#[test]
fn the_first_colour_is_not_a_near_white_one() {
let (r, g, b) = PALETTE[0];
assert!(
r.min(g).min(b) < 200,
"PALETTE[0] is ({r}, {g}, {b}), close enough to white to disappear on \
a light profile"
);
assert_ne!(PALETTE[0], (235, 235, 245));
}
#[test]
fn every_colour_reads_on_a_light_and_on_a_dark_profile() {
for color in PALETTE {
let lum = luminance(color);
let on_white = contrast(lum, 1.0);
let on_black = contrast(lum, 0.0);
assert!(
on_white >= 3.0,
"{color:?} is only {on_white:.1}:1 on a light profile"
);
assert!(
on_black >= 3.0,
"{color:?} is only {on_black:.1}:1 on a dark profile"
);
}
}
#[test]
fn a_run_always_starts_on_a_legible_colour() {
for seed in 0..64u64 {
let mut effect = Dvd::new(
DvdOptions {
seed,
start_in_corner: true,
..Default::default()
},
(40, 12),
);
effect.get_diff();
let (r, g, b) = PALETTE[effect.color_index];
let lum = luminance((r, g, b));
assert!(
contrast(lum, 1.0) >= 3.0 && contrast(lum, 0.0) >= 3.0,
"seed {seed} started on {r},{g},{b}"
);
}
}
#[test]
fn new_tracks_screen_size() {
let effect = Dvd::new(options(), (80, 24));
assert_eq!(effect.screen_size, (80, 24));
assert_eq!(effect.rows.len(), 1);
}
#[test]
fn new_terminates_at_minimum_size() {
let effect = Dvd::new(options(), (0, 0));
assert_eq!(effect.screen_size, (1, 1));
}
#[test]
fn supports_multiline_logos() {
let mut effect = Dvd::new(options(), (40, 10));
effect.options.logo = String::from("ab\ncd");
effect.reset();
assert_eq!(effect.rows, vec![vec!['a', 'b'], vec!['c', 'd']]);
}
#[test]
fn blank_logo_falls_back_to_a_single_glyph() {
let mut effect = Dvd::new(options(), (40, 10));
effect.options.logo = String::from(" \n ");
effect.reset();
assert_eq!(effect.rows, vec![vec!['*']]);
}
#[test]
fn stays_within_bounds_while_bouncing() {
let mut effect = Dvd::new(options(), (20, 8));
assert_eq!(effect.logo_width(), 2.0, "three dots is two cells");
for _ in 0..600 {
effect.step(1.0 / 60.0);
assert!(effect.x >= 0.0 && effect.x <= (20 - 2) as f64);
assert!(effect.y >= 0.0 && effect.y <= (8 - 1) as f64);
}
}
#[test]
fn oversize_logo_is_pinned_to_the_origin() {
let mut effect = Dvd::new(options(), (2, 1));
effect.options.logo = String::from("TOOLONG");
effect.reset();
for _ in 0..120 {
effect.step(1.0 / 60.0);
assert_eq!(effect.x, 0.0);
assert_eq!(effect.y, 0.0);
}
}
#[test]
fn every_wall_hit_changes_the_colour() {
let mut effect = Dvd::new(
DvdOptions {
color_change: ColorChange::Bounce,
..options()
},
(80, 24),
);
let initial = effect.color_index;
let mut changes = 0usize;
for _ in 0..1800 {
effect.step(1.0 / 60.0);
if effect.color_index != initial {
changes += 1;
}
}
assert!(
changes >= 3,
"the colour changed {changes} times in thirty seconds of bouncing, so \
the logo is effectively one colour. A wall hit every few seconds is \
what makes this read as motion rather than as a still image drifting."
);
}
#[test]
fn the_colour_changes_on_every_bounce() {
let mut effect = Dvd::new(DvdOptions::default(), (80, 24));
assert_eq!(
effect.options.color_change,
ColorChange::Bounce,
"the default has to be a recolour on every wall hit, or the logo sits \
at one colour for whole stretches of its run"
);
let mut seen = std::collections::BTreeSet::new();
let mut previous = effect.color_index;
seen.insert(previous);
let mut bounces = 0u32;
let mut changes = 0usize;
while bounces < 90 {
let (vx, vy) = (effect.vx, effect.vy);
effect.step(1.0 / 60.0);
if effect.vx != vx || effect.vy != vy {
bounces += 1;
}
if effect.color_index != previous {
previous = effect.color_index;
changes += 1;
seen.insert(effect.color_index);
}
}
assert!(
bounces >= 90,
"only saw {bounces} wall hits, so the simulation never got going"
);
assert!(
changes as u32 >= bounces,
"{changes} colour changes over {bounces} wall hits, so some bounces \
did not change the colour"
);
assert!(
changes as u32 <= bounces * 2,
"{changes} colour changes over {bounces} wall hits, so the colour is \
changing on frames that are not bounces"
);
assert!(
changes >= 3,
"only {changes} colour changes over {bounces} wall hits, so the logo \
is effectively one colour"
);
assert!(
seen.len() > 1 && seen.len() <= PALETTE.len(),
"{} distinct colours seen, which is not a rotation of the palette",
seen.len()
);
}
#[test]
fn the_reference_mode_changes_on_every_bounce() {
let mut effect = Dvd::new(
DvdOptions {
color_change: ColorChange::Bounce,
..DvdOptions::default()
},
(80, 24),
);
let initial = effect.color_index;
let mut bounces = 0u32;
let mut changes = 0usize;
let mut previous = initial;
while bounces < 90 {
let (vx, vy) = (effect.vx, effect.vy);
effect.step(1.0 / 60.0);
if effect.vx != vx || effect.vy != vy {
bounces += 1;
}
if effect.color_index != previous {
previous = effect.color_index;
changes += 1;
}
}
assert_eq!(
changes, bounces as usize,
"Bounce mode changed the colour on {changes} of {bounces} wall hits; it \
is meant to be every one of them"
);
assert_ne!(initial, 0, "unreachable, but keeps `initial` read");
}
#[test]
fn corner_mode_changes_only_when_both_axes_reverse_together() {
for (width, height) in [(6u16, 2u16), (20, 20)] {
let mut effect = Dvd::new(
DvdOptions {
color_change: ColorChange::Corner,
..options()
},
(width, height),
);
let initial = effect.color_index;
let mut changes = 0usize;
let mut bounces = 0usize;
for _ in 0..20_000 {
let (vx, vy) = (effect.vx, effect.vy);
effect.step(1.0 / 60.0);
if effect.vx != vx || effect.vy != vy {
bounces += 1;
}
if effect.color_index != initial {
changes += 1;
effect.color_index = initial;
}
}
assert!(
bounces > changes,
"at {width}x{height} the colour changed {changes} times over \
{bounces} wall hits, so corner mode is firing on ordinary \
bounces"
);
}
}
#[test]
fn never_mode_holds_one_colour() {
let mut effect = Dvd::new(
DvdOptions {
color_change: ColorChange::Never,
..options()
},
(80, 24),
);
let initial = effect.color_index;
for _ in 0..5_000 {
effect.step(1.0 / 60.0);
assert_eq!(effect.color_index, initial);
}
}
#[test]
fn the_colour_rule_is_what_each_mode_says() {
for wall_hits in 0..=RECOLOR_EVERY_N_BOUNCES + 3 {
for (hit_x, hit_y) in [(true, false), (false, true), (true, true)] {
assert!(ColorChange::Bounce.should_change(hit_x, hit_y, wall_hits));
}
assert!(!ColorChange::Bounce.should_change(false, false, wall_hits));
assert!(!ColorChange::Corner.should_change(true, false, wall_hits));
assert!(!ColorChange::Corner.should_change(false, true, wall_hits));
assert!(ColorChange::Corner.should_change(true, true, wall_hits));
assert!(!ColorChange::Corner.should_change(false, false, wall_hits));
for (hit_x, hit_y) in [(true, false), (false, true), (true, true)] {
assert!(!ColorChange::Never.should_change(hit_x, hit_y, wall_hits));
}
let expected = wall_hits >= RECOLOR_EVERY_N_BOUNCES;
for (hit_x, hit_y) in [(true, false), (false, true), (true, true)] {
assert_eq!(
ColorChange::Steady.should_change(hit_x, hit_y, wall_hits),
expected,
"a wall hit at {wall_hits} wall hits since the last change"
);
}
assert!(!ColorChange::Steady.should_change(false, false, wall_hits));
}
}
#[test]
fn update_with_context_scales_with_delta() {
let mut fast = Dvd::new(options(), (40, 12));
let mut slow = Dvd::new(options(), (40, 12));
fast.x = 0.0;
slow.x = 0.0;
fast.vx = 10.0;
slow.vx = 10.0;
fast.vy = 0.0;
slow.vy = 0.0;
let fast_context = crate::runtime::FrameContext::new(
(40, 12),
0,
Duration::ZERO,
Duration::from_millis(200),
crate::runtime::InputState::default(),
);
let slow_context = crate::runtime::FrameContext::new(
(40, 12),
0,
Duration::ZERO,
Duration::from_millis(20),
crate::runtime::InputState::default(),
);
fast.update_with_context(&fast_context);
slow.update_with_context(&slow_context);
assert!(fast.x > slow.x);
}
#[test]
fn the_logo_moves_on_enough_frames_to_read_as_motion() {
let mut cells: std::collections::HashMap<(usize, usize), u32> =
Default::default();
let on_screen = |cells: &std::collections::HashMap<(usize, usize), u32>| {
let mut dots = std::collections::HashSet::new();
for (&(x, y), &bits) in cells {
for i in 0..DOTS_PER_CELL {
if bits & (1 << i) != 0 {
let (dx, dy) = braille_dot_position(i);
dots.insert((
x as i64 * DOTS_X as i64 + dx as i64,
y as i64 * DOTS_Y as i64 + dy as i64,
));
}
}
}
dots
};
let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
let mut previous = on_screen(&cells);
let _ = dvd.get_diff();
let mut moved = 0usize;
for _ in 0..600 {
dvd.update();
for (x, y, cell) in dvd.get_diff() {
let bits = if cell.symbol == ' ' {
0
} else {
cell.symbol as u32 - 0x2800
};
cells.insert((x, y), bits);
}
let current = on_screen(&cells);
if current != previous {
moved += 1;
}
previous = current;
}
assert!(
moved >= 200,
"the logo moved on only {moved} of 600 frames, so it holds still for \
most of them and lurches the rest of the time. At 5 cells a second \
that is one frame in six, and it reads as a flicker rather than as \
slow motion -- five identical frames, then a jump."
);
}
#[test]
fn the_vertical_position_resolves_finer_than_a_cell() {
let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
let mut dots = std::collections::BTreeSet::new();
let mut cells = std::collections::BTreeSet::new();
for _ in 0..480 {
dvd.update();
dots.insert((dvd.y * DOTS_Y as f64).floor() as i64);
cells.insert(dvd.y.floor() as i64);
}
let ratio = dots.len() as f32 / cells.len().max(1) as f32;
assert!(
ratio > 3.5,
"{} distinct drawn vertical positions against {} at whole-cell \
resolution, a ratio of {ratio:.2}, so the sub-cell vertical motion \
is not being drawn",
dots.len(),
cells.len()
);
}
#[test]
fn the_wordmark_is_sixty_dots_by_twenty_eight() {
let rows: Vec<&str> = DVD_WORDMARK.split('\n').collect();
assert_eq!(
rows.len(),
28,
"the wordmark is {} rows, not 28",
rows.len()
);
for (index, row) in rows.iter().enumerate() {
assert_eq!(
row.chars().count(),
60,
"row {index} is {} dots wide, not 60: {row:?}",
row.chars().count()
);
}
let alphabet: std::collections::BTreeSet<char> =
DVD_WORDMARK.chars().filter(|c| *c != '\n').collect();
assert_eq!(
alphabet,
['#', '.'].into_iter().collect(),
"the wordmark alphabet is {alphabet:?}, not `#` and `.`"
);
}
#[test]
fn the_wordmark_is_neither_blank_nor_a_solid_slab() {
let total: usize = DVD_WORDMARK.chars().filter(|c| *c != '\n').count();
let ink = DVD_WORDMARK.chars().filter(|c| *c == '#').count();
let coverage = ink as f64 / total as f64;
assert!(
coverage > 0.35 && coverage < 0.80,
"the wordmark is {:.0}% inked ({ink} of {total} dots), which is \
outside the band a wordmark with a reflection sits in",
coverage * 100.0
);
for (index, row) in DVD_WORDMARK.split('\n').enumerate() {
let dots = row.chars().count();
let inked = row.chars().filter(|c| *c == '#').count();
assert!(
inked > 0 && inked < dots,
"row {index} is {inked} of {dots} dots, so it is entirely blank or \
entirely ink: {row:?}"
);
}
}
#[test]
fn the_logo_is_sampled_at_its_sub_cell_offset() {
let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
let (dot_w, dot_h) = (dvd.logo_dot_width(), dvd.logo_dot_height());
let total_ink = (0..dot_w)
.flat_map(|x| (0..dot_h).map(move |y| (x, y)))
.filter(|(x, y)| dvd.ink_at(*x, *y))
.count();
dvd.grid.clear();
dvd.paint_at(0, 0);
let aligned: Vec<Vec<bool>> = (0..dot_h)
.map(|y| (0..dot_w).map(|x| dvd.grid.dot(x, y)).collect())
.collect();
for skew_x in 0..DOTS_X {
for skew_y in 0..DOTS_Y {
dvd.grid.clear();
dvd.paint_at(skew_x, skew_y);
let raised = (0..dvd.grid.dot_width())
.flat_map(|x| (0..dvd.grid.dot_height()).map(move |y| (x, y)))
.filter(|(x, y)| dvd.grid.dot(*x, *y))
.count();
assert_eq!(
raised, total_ink,
"at a skew of ({skew_x},{skew_y}) the grid holds {raised} raised \
dots rather than the wordmark's {total_ink}, so ink has been \
lost or doubled"
);
for (y, row) in aligned.iter().enumerate() {
for (x, expected) in row.iter().enumerate() {
assert_eq!(
dvd.grid.dot(x + skew_x, y + skew_y),
*expected,
"dot ({x},{y}) moved wrong at a skew of \
({skew_x},{skew_y})"
);
}
}
}
}
assert_eq!(dvd.grid.width(), dvd.logo_cells_w() + 1);
assert_eq!(dvd.grid.height(), dvd.logo_cells_h() + 1);
dvd.grid.clear();
dvd.paint_at(1, 1);
assert!(
dvd.grid.dot_width() > dot_w && dvd.grid.dot_height() > dot_h,
"the grid is {}x{} dots, which does not have room for a logo of \
{dot_w}x{dot_h} shifted by a dot",
dvd.grid.dot_width(),
dvd.grid.dot_height()
);
}
#[test]
fn the_wordmark_round_trips_through_braille() {
let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
dvd.grid.clear();
dvd.paint_at(0, 0);
assert_eq!(dvd.logo_cells_w(), 30, "60 dots across at 2 to the cell");
assert_eq!(dvd.logo_cells_h(), 7, "28 dots down at 4 to the cell");
assert_eq!(dvd.grid.width(), 31, "the logo's 30 cells plus the spare");
assert_eq!(dvd.grid.height(), 8, "seven cells plus the spare");
assert_eq!(dvd.grid.dot_width(), 62);
assert_eq!(dvd.grid.dot_height(), 32);
for (dot_x, dot_y, expected, what) in [
(0usize, 0usize, false, "the top-left corner"),
(5, 0, true, "the left stroke of the first D"),
(4, 0, false, "the blank one dot to its left"),
(28, 0, false, "the gap between the D and the V at the top"),
(37, 0, true, "the top of the second letter's left stroke"),
(53, 0, true, "the far end of that letter's top bar"),
(54, 0, false, "the blank beyond it"),
(59, 0, false, "the top-right corner"),
(10, 4, false, "inside the first D's counter"),
(34, 4, true, "a stem of the V"),
(52, 4, true, "the left stroke of the last D"),
(27, 16, true, "the point of the V"),
(26, 16, false, "just left of the point"),
(20, 19, true, "the top bar of the reflection"),
(19, 19, false, "just left of it"),
(30, 20, true, "the middle of the reflection"),
(14, 27, true, "the foot of the reflection"),
(13, 27, false, "just left of the foot"),
(43, 27, false, "just right of the foot"),
(0, 27, false, "the bottom-left corner"),
] {
assert_eq!(
dvd.grid.dot(dot_x, dot_y),
expected,
"dot ({dot_x},{dot_y}) -- {what}"
);
}
for dot_y in 0..dvd.grid.dot_height() {
for dot_x in 0..dvd.grid.dot_width() {
assert_eq!(
dvd.grid.dot(dot_x, dot_y),
dvd.ink_at(dot_x, dot_y),
"dot ({dot_x},{dot_y}) disagrees with the wordmark"
);
}
}
assert_eq!(dvd.grid.cell_char(2, 1), '\u{28ff}', "a solid interior");
assert_eq!(dvd.grid.cell_char(2, 0), '\u{28f8}', "the slanted edge");
assert_eq!(dvd.grid.cell_char(0, 0), ' ', "a cell with no ink");
assert_eq!(dvd.grid.cell_char(29, 6), ' ', "the far bottom corner");
}
#[test]
fn the_default_logo_is_a_real_wordmark() {
let dvd = Dvd::new(DvdOptions::default(), (80, 24));
assert_eq!(dvd.rows.len(), 28, "28 dot rows");
assert_eq!(
dvd.rows.iter().map(Vec::len).max().unwrap_or(0),
60,
"60 dots across"
);
assert_eq!(dvd.logo_width(), 30.0, "60 dots is 30 cells");
assert_eq!(dvd.logo_height(), 7.0, "28 dots is 7 cells");
assert_eq!(dvd.grid.width(), 31, "the logo's cells plus the skew spare");
assert_eq!(dvd.grid.height(), 8);
}
#[test]
fn the_logo_is_never_clipped_and_never_escapes() {
fn dots_of(symbol: char) -> u8 {
u32::from(symbol).saturating_sub(0x2800) as u8
}
let (width, height) = (80u16, 24u16);
let mut template = Dvd::new(DvdOptions::default(), (width, height));
template.grid.clear();
template.paint_at(0, 0);
let max_x = width as f64 - template.logo_width();
let max_y = height as f64 - template.logo_height();
let (dot_w, dot_h) =
(template.logo_dot_width(), template.logo_dot_height());
for x in [0.0, 0.5, max_x - 0.5, max_x] {
for y in [0.0, 0.25, max_y - 0.25, max_y] {
let mut dvd = Dvd::new(DvdOptions::default(), (width, height));
dvd.x = x;
dvd.y = y;
let diff = dvd.get_diff();
let mut written: std::collections::BTreeMap<(usize, usize), u8> =
Default::default();
for (cx, cy, cell) in diff {
assert!(
cx < width as usize && cy < height as usize,
"at ({x}, {y}) the draw emitted ({cx},{cy}), outside the \
terminal"
);
assert_ne!(cell.symbol, ' ', "a blank cell was written");
written.insert((cx, cy), dots_of(cell.symbol));
}
let left = (x * DOTS_X as f64).floor() as usize;
let top = (y * DOTS_Y as f64).floor() as usize;
for dot_j in 0..dot_h {
for dot_i in 0..dot_w {
let screen_x = left + dot_i;
let screen_y = top + dot_j;
let cell_x = screen_x / DOTS_X;
let cell_y = screen_y / DOTS_Y;
let bit = braille_bit(screen_x % DOTS_X, screen_y % DOTS_Y);
let raised = written
.get(&(cell_x, cell_y))
.is_some_and(|bits| bits & bit != 0);
assert_eq!(
raised,
dvd.ink_at(dot_i, dot_j),
"at ({x}, {y}) the wordmark's dot ({dot_i},{dot_j}) is \
not drawn as the bitmap says"
);
}
}
}
}
}
#[test]
fn the_diagonal_is_corrected_for_the_cell_aspect_ratio() {
let dvd = Dvd::new(DvdOptions::default(), (80, 24));
let across_per_down =
(dvd.vx.abs() / dvd.vy.abs().max(f64::MIN_POSITIVE)) as f32;
assert!(
(across_per_down - dvd.options.slope).abs() < 0.01,
"the logo travels {across_per_down} cells across per cell down, but \
slope is {}",
dvd.options.slope
);
assert!(
dvd.options.slope > 1.0,
"a slope of {} draws equal cell deltas, which on this cell aspect \
ratio is a line at 50 to 63 degrees rather than a diagonal",
dvd.options.slope
);
}
#[test]
fn the_speed_gives_movement_on_at_least_a_third_of_frames() {
const THIRD_OF_FRAMES_AT: f32 = 10.0;
let options = DvdOptions::default();
assert!(
options.speed >= THIRD_OF_FRAMES_AT,
"the speed is {}, and below about {THIRD_OF_FRAMES_AT} the logo moves \
on under a third of frames, which reads as a stutter rather than as \
motion",
options.speed
);
assert!(
(THIRD_OF_FRAMES_AT..=18.0).contains(&options.speed),
"the speed is {}, which is outside {THIRD_OF_FRAMES_AT}..=18",
options.speed
);
}
#[test]
fn only_inked_cells_are_written_and_none_of_them_carry_a_background() {
let mut dvd = Dvd::new(DvdOptions::default(), (80, 24));
let opening = dvd.get_diff();
let inked_cells = (0..dvd.grid.height())
.flat_map(|cell_y| (0..dvd.grid.width()).map(move |cx| (cx, cell_y)))
.filter(|(cx, cy)| dvd.grid.cell_char(*cx, *cy) != ' ')
.count();
let bounding_box = dvd.grid.width() * dvd.grid.height();
assert_eq!(
opening.len(),
inked_cells,
"the opening frame wrote {} cells but only {inked_cells} of the logo's \
{bounding_box} have ink, so blank cells are being painted",
opening.len()
);
assert!(
inked_cells < bounding_box,
"{inked_cells} of {bounding_box} cells have ink, so this logo is a slab \
and the test is not measuring what it thinks it is"
);
for (_, _, cell) in &opening {
assert_ne!(cell.symbol, ' ', "a blank cell was written");
assert_eq!(
cell.bg,
style::Color::Reset,
"wrote {:?} with a background of {:?}; braille is one colour per \
cell and the wordmark is a single flat one",
cell.symbol,
cell.bg
);
}
for _ in 0..200 {
dvd.update();
for (_, _, cell) in dvd.get_diff() {
assert_eq!(cell.bg, style::Color::Reset);
}
}
}
#[test]
fn a_frame_costs_the_same_whatever_size_the_terminal_is() {
fn mean_frame_bytes(size: (u16, u16)) -> (usize, usize) {
let mut dvd = Dvd::new(DvdOptions::default(), size);
let opening = {
let mut out: Vec<u8> = Vec::new();
crate::common::write_cells(
&mut out,
size,
&dvd.get_diff(),
crate::session::SessionColors::default(),
)
.expect("writing to a Vec cannot fail");
out.len()
};
let mut total = 0usize;
for _ in 0..120 {
dvd.update();
let mut out: Vec<u8> = Vec::new();
crate::common::write_cells(
&mut out,
size,
&dvd.get_diff(),
crate::session::SessionColors::default(),
)
.expect("writing to a Vec cannot fail");
total += out.len();
}
(opening, total / 120)
}
let (small_open, small) = mean_frame_bytes((80, 24));
let (big_open, big) = mean_frame_bytes((400, 200));
assert!(
small < 1_500 && big < 1_500,
"a frame costs {small} bytes at 80x24 and {big} at 400x200, which is \
more than a 210-cell logo moving a dot at a time should"
);
assert!(
big * 10 <= small * 12,
"a frame costs {small} bytes at 80x24 and {big} at 400x200, so the cost \
scales with the terminal rather than with the logo"
);
assert!(
small_open < 1_500 && big_open < 1_500,
"the opening frame costs {small_open} bytes at 80x24 and {big_open} at \
400x200"
);
}
#[test]
fn diff_stays_in_bounds() {
let mut effect = Dvd::new(options(), (10, 4));
for _ in 0..30 {
effect.update();
for (x, y, _) in effect.get_diff() {
assert!(x < 10 && y < 4);
}
}
}
fn corner_rich() -> Dvd {
Dvd::new(
DvdOptions {
logo: String::from("DVD"),
start_in_corner: false,
color_change: ColorChange::Never,
..Default::default()
},
(400, 200),
)
}
#[test]
fn a_wave_is_thrown_exactly_when_both_axes_reverse_together() {
let mut dvd = corner_rich();
let mut throws = 0u32;
let mut wall_hits = 0u32;
let mut disagreements = 0u32;
for _ in 0..20_000 {
let waves_before = dvd.waves.len();
dvd.update();
let max_x = (dvd.screen_size.0 as f64 - dvd.logo_width()).max(0.0);
let max_y = (dvd.screen_size.1 as f64 - dvd.logo_height()).max(0.0);
let clamped_x = max_x > 0.0 && (dvd.x == 0.0 || dvd.x == max_x);
let clamped_y = max_y > 0.0 && (dvd.y == 0.0 || dvd.y == max_y);
let grew = dvd.waves.len() > waves_before;
let youngest = dvd
.waves
.iter()
.map(|wave| wave.age)
.fold(f64::INFINITY, f64::min);
if dvd.corner_this_frame {
throws += 1;
}
if clamped_x || clamped_y {
wall_hits += 1;
}
if dvd.corner_this_frame != (clamped_x && clamped_y) {
disagreements += 1;
}
if dvd.corner_this_frame != grew {
disagreements += 1;
}
if grew {
assert!(
youngest <= DT * 1.5,
"a new wave is {youngest}s old on the frame it was thrown, so \
it was not zero-age when pushed"
);
}
}
assert_eq!(
disagreements, 0,
"{disagreements} frames where the stored corner flag and the geometry \
disagreed, or where a flag without a wave"
);
assert!(
throws > 5,
"only {throws} corners in 20,000 frames, so this configuration is not \
corner-rich and the rule above was never exercised"
);
assert_eq!(
wall_hits, throws,
"this fixture was chosen because its two bounce periods are equal, so \
every one of its {wall_hits} wall hits should have been a corner"
);
}
#[test]
fn a_single_axis_wall_hit_throws_no_wave() {
let mut dvd = Dvd::new(
DvdOptions {
color_change: ColorChange::Never,
..Default::default()
},
(80, 24),
);
let mut wall_hits = 0u32;
let mut throws = 0u32;
for _ in 0..20_000 {
let before = dvd.wall_hits;
dvd.update();
if dvd.wall_hits != before {
wall_hits += 1;
}
if dvd.corner_this_frame {
throws += 1;
}
}
assert!(
wall_hits > 100,
"only {wall_hits} wall hits in 20,000 frames, so the fixture is not \
exercising the single-axis case"
);
assert!(
throws * 20 < wall_hits,
"{wall_hits} wall hits produced {throws} waves, so the wave is keyed to \
a wall rather than to a corner"
);
}
#[test]
fn a_corner_is_reachable_at_the_shipped_defaults() {
let mut reached = 0;
for seed in [1u64, 2, 3, 4] {
let mut dvd = Dvd::new(
DvdOptions {
color_change: ColorChange::Never,
seed,
..Default::default()
},
(80, 24),
);
for _ in 0..60_000 {
dvd.update();
if dvd.corner_this_frame {
reached += 1;
break;
}
}
}
assert_eq!(
reached, 4,
"only {reached} of four seeded runs at 80x24 with the default wordmark \
reached a corner in 1,000 seconds, so the wave is unreachable in the \
shipped configuration"
);
}
#[test]
fn the_wave_draws_a_ring_at_the_radius_its_age_implies() {
let (cx, cy) = (20.0, 12.0);
let age = 0.5;
let mut dvd = Dvd::new(options(), (80, 24));
dvd.waves.push(CornerWave { cx, cy, age });
let diff = dvd.get_diff();
let ring: Vec<f64> = diff
.iter()
.filter(|(_, _, cell)| cell.symbol == WAVE_GLYPH)
.map(|(x, y, _)| (*x as f64 - cx).hypot(*y as f64 - cy))
.collect();
assert!(
ring.len() > 40,
"the ring drew only {} cells, which is not a ring",
ring.len()
);
let radius = WAVE_SPEED * age;
let tolerance = WAVE_HALF_WIDTH + 0.5 * std::f64::consts::SQRT_2;
let inside = ring.iter().filter(|d| **d < radius - tolerance).count();
let outside = ring.iter().filter(|d| **d > radius + tolerance).count();
let in_band = ring.len() - inside - outside;
assert!(
in_band > 20,
"only {in_band} of {} cells are within the band around r = {radius}",
ring.len()
);
assert_eq!(
inside + outside,
0,
"{inside} cells are inside the band and {outside} are outside it, so \
this is a filled disc and not a ring"
);
}
#[test]
fn the_wave_is_dimmer_than_the_logo() {
let mut dvd = Dvd::new(options(), (80, 24));
dvd.waves.push(CornerWave {
cx: 0.0,
cy: 0.0,
age: 0.2,
});
let diff = dvd.get_diff();
let logo = PALETTE[dvd.color_index % PALETTE.len()];
let (lr, lg, lb) = (logo.0 as f64, logo.1 as f64, logo.2 as f64);
let logo_luma = 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;
let mut wave_seen = false;
for (_, _, cell) in &diff {
if cell.symbol != WAVE_GLYPH {
continue;
}
let style::Color::Rgb { r, g, b } = cell.color else {
panic!("a wave cell is not truecolor: {:?}", cell.color);
};
wave_seen = true;
let luma = 0.2126 * r as f64 + 0.7152 * g as f64 + 0.0722 * b as f64;
assert!(
luma < logo_luma,
"a wave cell is at luma {luma:.1} against the logo's {logo_luma:.1}, \
so the wave is not dimmer than the logo"
);
}
assert!(wave_seen, "the fixture drew no wave cells at all");
}
#[test]
fn the_wave_can_be_turned_off_without_touching_the_colour_rule() {
for mode in ColorChange::ALL {
let mut dvd = Dvd::new(
DvdOptions {
color_change: *mode,
corner_wave: false,
..options()
},
(80, 24),
);
for _ in 0..2_000 {
dvd.update();
let diff = dvd.get_diff();
assert!(
!diff.iter().any(|(_, _, c)| c.symbol == WAVE_GLYPH),
"{mode:?} drew a wave with corner_wave off"
);
}
}
}
#[test]
fn a_wave_writes_a_ring_and_not_its_bounding_box() {
let radius = 60.0;
let mut dvd = Dvd::new(options(), (400, 200));
dvd.waves.push(CornerWave {
cx: 200.0,
cy: 100.0,
age: radius / WAVE_SPEED,
});
let written = dvd
.get_diff()
.iter()
.filter(|(_, _, c)| c.symbol == WAVE_GLYPH)
.count();
let band_area = 2.0 * WAVE_HALF_WIDTH * std::f64::consts::TAU * radius;
assert!(
written as f64 >= band_area * 0.6,
"the ring drew {written} cells, fewer than the {band_area:.0} its own \
area implies, so it has gaps in it"
);
assert!(
(written as f64) < band_area * 3.0,
"the ring drew {written} cells against a {band_area:.0}-cell band, so \
it is filling far more than its own width"
);
assert!(
written < 4_000,
"one wave wrote {written} cells on an 80,000-cell screen"
);
}
#[test]
fn an_expired_wave_is_erased_rather_than_left_on_screen() {
let mut dvd = Dvd::new(options(), (80, 24));
dvd.waves.push(CornerWave {
cx: 40.0,
cy: 12.0,
age: 0.1,
});
let during = dvd.get_diff();
assert!(
during.iter().any(|(_, _, c)| c.symbol == WAVE_GLYPH),
"the fixture drew no ring"
);
let context = crate::runtime::FrameContext::new(
dvd.screen_size,
0,
std::time::Duration::ZERO,
std::time::Duration::from_secs_f64(0.1),
crate::runtime::InputState::default(),
);
for _ in 0..(WAVE_LIFE as usize * 10 + 4) {
dvd.update_with_context(&context);
}
assert!(
dvd.waves.is_empty(),
"a wave {}s old is still alive with a life of {WAVE_LIFE}s",
dvd.waves.first().map_or(0.0, |w| w.age)
);
let after = dvd.get_diff();
assert!(
after.iter().all(|(_, _, c)| c.symbol != WAVE_GLYPH),
"a wave cell survived its own removal"
);
}
}