use crate::buffer::{Buffer, Cell};
use crate::common::{DEFAULT_SEED, TerminalEffect, seeded_rng};
use crate::render::palette::{Palette, lerp};
use crate::runtime::{InputEvent, PointerPhase};
use crossterm::style;
use rand::RngExt;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::f32::consts::PI;
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
pub enum BoidCharset {
#[default]
Simple,
Arrow,
Braille,
Dot,
}
impl BoidCharset {
pub fn chars(&self) -> [char; 8] {
match self {
BoidCharset::Simple => ['▶', '◣', '▼', '◢', '◀', '◤', '▲', '◥'],
BoidCharset::Arrow => ['→', '↘', '↓', '↙', '←', '↖', '↑', '↗'],
BoidCharset::Braille => ['⣤', '⢰', '⣰', '⡆', '⡇', '⠇', '⠛', '⠙'],
BoidCharset::Dot => ['•'; 8],
}
}
pub fn is_directional(&self) -> bool {
!matches!(self, BoidCharset::Dot)
}
}
#[derive(Clone, Copy)]
struct TrailMark {
glyph: char,
color: style::Color,
intensity: f32,
}
#[derive(Clone)]
struct Boid {
position: (f32, f32), velocity: (f32, f32), character: char, color: style::Color, history: VecDeque<(usize, usize)>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct BoidsOptions {
#[serde(skip)]
pub screen_size: (u16, u16),
#[serde(skip)]
pub boid_count: u16,
pub boid_coeff: f32,
separation_weight: f32,
separation_distance: f32,
alignment_weight: f32,
alignment_distance: f32,
cohesion_weight: f32,
cohesion_distance: f32,
drive_factor: f32, swirl_factor: f32, border_factor: f32,
max_speed: f32,
min_speed: f32,
pub charset: BoidCharset,
pub trail_length: u8,
pub seed: u64,
}
impl Default for BoidsOptions {
fn default() -> Self {
Self {
screen_size: Default::default(),
boid_count: 100,
boid_coeff: BOID_DENSITY / 0.5,
separation_weight: 1.5,
separation_distance: 3.0,
alignment_weight: 2.0,
alignment_distance: 15.0,
cohesion_weight: 1.5,
cohesion_distance: 15.0,
drive_factor: 2.0,
swirl_factor: 0.9,
border_factor: 0.7,
max_speed: 0.6,
min_speed: 0.08,
charset: BoidCharset::default(),
trail_length: 5,
seed: DEFAULT_SEED,
}
}
}
const BOID_DENSITY: f32 = 0.05;
const TRAIL_FADE_PER_STEP: f32 = 0.6;
const TRAIL_DECAY: f32 = 0.8;
const TRAIL_FLOOR: f32 = 0.02;
fn speed_palette() -> Palette {
Palette::new(vec![
style::Color::Rgb {
r: 12,
g: 48,
b: 96,
},
style::Color::Rgb {
r: 255,
g: 255,
b: 255,
},
])
}
const TRAIL_BACKGROUND: style::Color = style::Color::Rgb { r: 0, g: 0, b: 0 };
const BORDER_MARGIN: f32 = 0.2;
mod gain {
pub const ALIGNMENT: f32 = 0.3;
pub const COHESION: f32 = 0.06;
pub const SWIRL: f32 = 0.25;
pub const DRIVE: f32 = 0.05;
}
mod shock {
pub const PUSH: f32 = 6.0;
pub const BAND: f32 = 3.0;
pub const SPEED: f32 = 45.0;
pub const DECAY: f32 = 0.975;
pub const FLOOR: f32 = 0.04;
pub const MAX_AGE: f32 = 2.5;
pub const MAX_WAVES: usize = 4;
pub const DRAG_SPACING: f32 = 6.0;
pub const CELL_ASPECT: f32 = 2.0;
}
fn shock_distance(diff: (f32, f32)) -> f32 {
diff.0.hypot(diff.1 * shock::CELL_ASPECT)
}
fn wrapped_column(column: usize, origin: f32, width: f32) -> f32 {
let half = width / 2.0;
((column as f32 - origin + half).rem_euclid(width)) - half
}
#[derive(Debug, Clone, Copy)]
struct Shockwave {
origin: (f32, f32),
radius: f32,
strength: f32,
age: f32,
}
const SHOCK_COLOR: style::Color = style::Color::Rgb {
r: 255,
g: 140,
b: 40,
};
const SHOCK_GLYPH: char = '+';
pub struct Boids {
options: BoidsOptions,
boids: Vec<Boid>,
charset_chars: [char; 8],
speed_palette: Palette,
frame: Buffer,
shown: Buffer,
trail: HashMap<(usize, usize), TrailMark>,
waves: VecDeque<Shockwave>,
pointer_down: bool,
last_wave_at: (f32, f32),
}
impl Boid {
fn new(position: (f32, f32), velocity: (f32, f32)) -> Self {
Self {
position,
velocity,
character: '•',
color: style::Color::White,
history: VecDeque::new(),
}
}
fn speed(&self) -> f32 {
self.velocity.0.hypot(self.velocity.1)
}
fn direction_index(&self) -> usize {
let (vx, vy) = self.velocity;
let angle = vy.atan2(vx);
((angle / PI * 4.0).round() as i32 + 8).rem_euclid(8) as usize
}
fn get_direction_char(&self, charset: &[char; 8]) -> char {
charset[self.direction_index()]
}
fn update_visual(
&mut self,
charset: &[char; 8],
palette: &Palette,
min: f32,
max: f32,
) {
self.character = self.get_direction_char(charset);
self.color = palette.sample(self.speed_fraction(min, max));
}
fn speed_fraction(&self, min: f32, max: f32) -> f32 {
if max <= min {
return 1.0;
}
((self.speed() - min) / (max - min)).clamp(0.0, 1.0)
}
}
impl TerminalEffect for Boids {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.paint()
}
fn update(&mut self) {
self.step(1.0);
}
fn update_with_context(&mut self, context: &crate::runtime::FrameContext) {
let seconds = context.delta.as_secs_f64().min(0.1);
self.step((seconds * 60.0) as f32);
}
fn handle_input(&mut self, event: &InputEvent) {
match event {
InputEvent::Pointer {
position,
phase,
button: _,
} => self.handle_pointer(*position, *phase),
InputEvent::Key { .. } => {}
InputEvent::Resize { .. } => {}
InputEvent::FocusGained | InputEvent::FocusLost => {}
InputEvent::Quit | InputEvent::Ignored => {}
}
}
fn update_size(&mut self, width: u16, height: u16) {
let changed = self.options.screen_size != (width.max(1), height.max(1));
self.options.screen_size = (width.max(1), height.max(1));
self.rebuild_buffers();
let wanted = self.count_for();
if changed || wanted != self.options.boid_count {
self.options.boid_count = wanted;
self.reset();
}
}
fn reset(&mut self) {
*self = Self::new(self.options.clone());
}
}
impl Boids {
fn step(&mut self, scale: f32) {
self.apply_rules(scale);
self.advance_waves(scale);
self.update_positions(scale);
self.fade_trail(scale);
}
fn handle_pointer(&mut self, position: (u16, u16), phase: PointerPhase) {
let (x, y) = (position.0 as f32, position.1 as f32);
match phase {
PointerPhase::Pressed => {
self.pointer_down = true;
self.drop_wave((x, y));
}
PointerPhase::Released => self.pointer_down = false,
PointerPhase::Moved => {
if !self.pointer_down {
return;
}
let travelled = shock_distance((
x - self.last_wave_at.0,
y - self.last_wave_at.1,
));
if travelled >= shock::DRAG_SPACING {
self.drop_wave((x, y));
}
}
PointerPhase::WheelUp
| PointerPhase::WheelDown
| PointerPhase::WheelLeft
| PointerPhase::WheelRight => {}
}
}
fn drop_wave(&mut self, origin: (f32, f32)) {
while self.waves.len() >= shock::MAX_WAVES {
self.waves.pop_front();
}
self.waves.push_back(Shockwave {
origin,
radius: 0.0,
strength: shock::PUSH,
age: 0.0,
});
self.last_wave_at = origin;
}
fn advance_waves(&mut self, scale: f32) {
let decay = shock::DECAY.powf(scale.max(0.0));
let reach = self.reach();
for wave in &mut self.waves {
wave.radius += shock::SPEED * scale / 60.0;
wave.strength *= decay;
wave.age += scale / 60.0;
}
self.waves.retain(|wave| {
wave.strength >= shock::FLOOR
&& wave.age < shock::MAX_AGE
&& wave.radius < reach
});
}
fn reach(&self) -> f32 {
let width = self.options.screen_size.0 as f32;
let height = self.options.screen_size.1 as f32;
(width / 2.0).hypot(height / 2.0 * shock::CELL_ASPECT)
}
fn count_for(&self) -> u16 {
let (width, height) = self.options.screen_size;
let area = width as f32 * height as f32;
((area * 0.5 * self.options.boid_coeff) as u16).clamp(50, 300)
}
pub fn new(options: BoidsOptions) -> Self {
let mut rng = seeded_rng(options.seed, "boids");
let mut options = options;
options.screen_size =
(options.screen_size.0.max(1), options.screen_size.1.max(1));
let width = options.screen_size.0 as usize;
let height = options.screen_size.1 as usize;
let charset_chars = options.charset.chars();
let speed_palette = speed_palette();
let (min_speed, max_speed) = (options.min_speed, options.max_speed);
let mut boids = Vec::with_capacity(options.boid_count as usize);
for _ in 0..options.boid_count {
let position = (
rng.random_range(0.0..width as f32),
rng.random_range(0.0..height as f32),
);
let velocity =
(rng.random_range(-1.0..1.0), rng.random_range(-1.0..1.0));
let mut boid = Boid::new(position, velocity);
boid.update_visual(
&charset_chars,
&speed_palette,
min_speed,
max_speed,
);
boid.history.push_back(boid.cell(width, height));
boids.push(boid);
}
let mut flock = Self {
options,
boids,
charset_chars,
speed_palette,
frame: Buffer::new(width, height),
shown: Buffer::new(width, height),
trail: HashMap::new(),
waves: VecDeque::new(),
pointer_down: false,
last_wave_at: (0.0, 0.0),
};
flock.stamp();
flock
}
fn rebuild_buffers(&mut self) {
let width = self.options.screen_size.0 as usize;
let height = self.options.screen_size.1 as usize;
if (self.frame.width, self.frame.height) == (width, height) {
return;
}
self.frame = Buffer::new(width, height);
self.shown = Buffer::new(width, height);
self.trail.clear();
}
fn toroidal_diff(&self, a: (f32, f32), b: (f32, f32)) -> (f32, f32) {
let width = self.options.screen_size.0 as f32;
let height = self.options.screen_size.1 as f32;
let mut dx = a.0 - b.0;
let mut dy = a.1 - b.1;
if dx > width / 2.0 {
dx -= width;
} else if dx < -width / 2.0 {
dx += width;
}
if dy > height / 2.0 {
dy -= height;
} else if dy < -height / 2.0 {
dy += height;
}
(dx, dy)
}
fn apply_rules(&mut self, scale: f32) {
let num_boids = self.boids.len();
let mut separation_adjustments = vec![(0.0, 0.0); num_boids];
let mut alignment_adjustments = vec![(0.0, 0.0); num_boids];
let mut cohesion_adjustments = vec![(0.0, 0.0); num_boids];
let mut border_adjustments = vec![(0.0, 0.0); num_boids];
for i in 0..num_boids {
let mut separation = (0.0, 0.0);
let mut sep_count = 0;
let mut avg_velocity = (0.0, 0.0);
let mut align_count = 0;
let mut center = (0.0, 0.0);
let mut cohesion_count = 0;
for j in 0..num_boids {
if i == j {
continue;
}
let diff = self
.toroidal_diff(self.boids[j].position, self.boids[i].position);
let distance = diff.0.hypot(diff.1);
#[allow(clippy::collapsible_if)]
if distance < self.options.separation_distance {
if distance > 0.0 {
let factor = 1.0 / distance;
separation.0 -= diff.0 * factor;
separation.1 -= diff.1 * factor;
sep_count += 1;
}
}
if distance < self.options.alignment_distance {
avg_velocity.0 += self.boids[j].velocity.0;
avg_velocity.1 += self.boids[j].velocity.1;
align_count += 1;
}
if distance < self.options.cohesion_distance {
center.0 += diff.0;
center.1 += diff.1;
cohesion_count += 1;
}
}
if sep_count > 0 {
let share = self.options.separation_weight / sep_count as f32;
separation_adjustments[i] =
(separation.0 * share, separation.1 * share);
}
if align_count > 0 {
let avg_vel = (
avg_velocity.0 / align_count as f32,
avg_velocity.1 / align_count as f32,
);
alignment_adjustments[i] = (
(avg_vel.0 - self.boids[i].velocity.0)
* self.options.alignment_weight
* gain::ALIGNMENT,
(avg_vel.1 - self.boids[i].velocity.1)
* self.options.alignment_weight
* gain::ALIGNMENT,
);
}
if cohesion_count > 0 {
let toward_center = (
center.0 / cohesion_count as f32,
center.1 / cohesion_count as f32,
);
let reach = toward_center.0.hypot(toward_center.1);
let coherence =
(reach / self.options.cohesion_distance).clamp(0.0, 1.0);
let swirl_scale =
self.options.swirl_factor * gain::SWIRL * coherence;
let swirl = (-toward_center.1, toward_center.0);
let swirl_normalized = if reach > 0.0 {
(swirl.0 / reach, swirl.1 / reach)
} else {
(0.0, 0.0)
};
cohesion_adjustments[i] = (
toward_center.0 * self.options.cohesion_weight * gain::COHESION
+ swirl_normalized.0 * swirl_scale,
toward_center.1 * self.options.cohesion_weight * gain::COHESION
+ swirl_normalized.1 * swirl_scale,
);
}
border_adjustments[i] = self.border_force(self.boids[i].position);
}
let mut shock_adjustments = vec![(0.0, 0.0); num_boids];
for (i, adjustment) in shock_adjustments.iter_mut().enumerate() {
let boid = &self.boids[i];
*adjustment = self.shock_force(boid.position, boid.velocity);
}
for i in 0..num_boids {
let mut new_vx = self.boids[i].velocity.0;
let mut new_vy = self.boids[i].velocity.1;
new_vx += separation_adjustments[i].0 * scale;
new_vy += separation_adjustments[i].1 * scale;
new_vx += alignment_adjustments[i].0 * scale;
new_vy += alignment_adjustments[i].1 * scale;
new_vx += cohesion_adjustments[i].0 * scale;
new_vy += cohesion_adjustments[i].1 * scale;
new_vx += border_adjustments[i].0 * scale;
new_vy += border_adjustments[i].1 * scale;
new_vx += shock_adjustments[i].0 * scale;
new_vy += shock_adjustments[i].1 * scale;
let speed = new_vx.hypot(new_vy);
if speed > 0.0 {
let normalized_vx = new_vx / speed;
let normalized_vy = new_vy / speed;
new_vx += normalized_vx * self.options.drive_factor * gain::DRIVE;
new_vy += normalized_vy * self.options.drive_factor * gain::DRIVE;
}
new_vx = self.boids[i].velocity.0 * 0.7 + new_vx * 0.3;
new_vy = self.boids[i].velocity.1 * 0.7 + new_vy * 0.3;
let speed = new_vx.hypot(new_vy);
if speed > self.options.max_speed {
let scale = self.options.max_speed / speed;
new_vx *= scale;
new_vy *= scale;
} else if speed < self.options.min_speed && speed > 0.0 {
let scale = self.options.min_speed / speed;
new_vx *= scale;
new_vy *= scale;
}
self.boids[i].velocity = (new_vx, new_vy);
}
}
fn border_force(&self, position: (f32, f32)) -> (f32, f32) {
let width = self.options.screen_size.0 as f32;
let height = self.options.screen_size.1 as f32;
let margin_x = (width * BORDER_MARGIN).max(1.0);
let margin_y = (height * BORDER_MARGIN).max(1.0);
let intrusion = |pos: f32, margin: f32, extent: f32| {
if pos < margin {
1.0 - pos / margin
} else if pos > extent - margin {
1.0 - (extent - pos) / margin
} else {
0.0
}
};
let depth = intrusion(position.0, margin_x, width)
.max(intrusion(position.1, margin_y, height));
if depth <= 0.0 {
return (0.0, 0.0);
}
let (dx, dy) = (width / 2.0 - position.0, height / 2.0 - position.1);
let length = (dx * dx + dy * dy).sqrt();
if length <= 0.0 {
return (0.0, 0.0);
}
let push = self.options.border_factor * depth;
(push * dx / length, push * dy / length)
}
fn shock_force(&self, position: (f32, f32), heading: (f32, f32)) -> (f32, f32) {
let mut total = (0.0f32, 0.0f32);
for wave in &self.waves {
let diff = self.toroidal_diff(position, wave.origin);
let distance = shock_distance(diff);
let offset = (distance - wave.radius).abs();
if offset >= shock::BAND {
continue;
}
let falloff = 1.0 - offset / shock::BAND;
let (ux, uy) = if distance > f32::EPSILON {
(diff.0 / distance, diff.1 / distance)
} else {
let heading_length = heading.0.hypot(heading.1);
if heading_length > f32::EPSILON {
(heading.0 / heading_length, heading.1 / heading_length)
} else {
(1.0, 0.0)
}
};
let push = wave.strength * falloff;
total.0 += ux * push;
total.1 += uy * push;
}
total
}
fn update_positions(&mut self, scale: f32) {
let width = self.options.screen_size.0 as f32;
let height = self.options.screen_size.1 as f32;
let (cols, rows) = (
self.options.screen_size.0 as usize,
self.options.screen_size.1 as usize,
);
let charset_chars = self.charset_chars;
let (min_speed, max_speed) =
(self.options.min_speed, self.options.max_speed);
let keep = self.options.trail_length as usize + 1;
for boid in &mut self.boids {
boid.position.0 += boid.velocity.0 * scale;
boid.position.1 += boid.velocity.1 * scale;
if boid.position.0 < 0.0 {
boid.position.0 += width;
} else if boid.position.0 >= width {
boid.position.0 -= width;
}
if boid.position.1 < 0.0 {
boid.position.1 += height;
} else if boid.position.1 >= height {
boid.position.1 -= height;
}
boid.update_visual(
&charset_chars,
&self.speed_palette,
min_speed,
max_speed,
);
boid.history.push_front(boid.cell(cols, rows));
while boid.history.len() > keep {
boid.history.pop_back();
}
}
}
fn fade_trail(&mut self, scale: f32) {
let decay = TRAIL_DECAY.powf(scale.max(0.0));
self.trail.retain(|_, mark| {
mark.intensity *= decay;
mark.intensity >= TRAIL_FLOOR
});
}
fn stamp(&mut self) {
let (cols, rows) = (
self.options.screen_size.0 as usize,
self.options.screen_size.1 as usize,
);
for boid in &self.boids {
let (character, color) = (boid.character, boid.color);
for (step, cell) in boid.history.iter().enumerate() {
let (x, y) = *cell;
if x >= cols || y >= rows {
continue;
}
let intensity = TRAIL_FADE_PER_STEP.powi(step as i32);
self.trail
.entry((x, y))
.and_modify(|mark| {
if intensity > mark.intensity {
mark.intensity = intensity;
mark.glyph = character;
mark.color = color;
}
})
.or_insert(TrailMark {
glyph: character,
color,
intensity,
});
}
}
}
fn paint(&mut self) -> Vec<(usize, usize, Cell)> {
self.stamp();
self.frame.fill_with(&Cell::default());
for (&(x, y), mark) in &self.trail {
if x >= self.frame.width || y >= self.frame.height {
continue;
}
let faded = lerp(TRAIL_BACKGROUND, mark.color, mark.intensity);
self.frame.set(
x,
y,
Cell::new(mark.glyph, faded, style::Attribute::Reset),
);
}
self.paint_waves();
let cells = self.shown.diff(&self.frame);
for (x, y, cell) in &cells {
self.shown.set(*x, *y, *cell);
}
cells
}
fn paint_waves(&mut self) {
let (cols, rows) = (
self.options.screen_size.0 as usize,
self.options.screen_size.1 as usize,
);
if cols == 0 || rows == 0 {
return;
}
for wave in &self.waves {
let fade = (wave.strength / shock::PUSH).clamp(0.0, 1.0);
let outer = wave.radius + shock::BAND;
let inner = (wave.radius - shock::BAND).max(0.0);
for column in 0..cols {
let offset = wrapped_column(column, wave.origin.0, cols as f32);
let span = shock_distance((offset, 0.0));
if span >= outer {
continue;
}
let depth = if inner <= 0.0 {
1.0
} else {
((outer - span) / (outer - inner)).clamp(0.0, 1.0)
};
let lit = lerp(TRAIL_BACKGROUND, SHOCK_COLOR, fade * depth);
let mut edges = [0.0f32; 4];
let mut count = 0;
for radius in [outer, inner] {
let squared = radius * radius - span * span;
if squared <= 0.0 {
continue;
}
let half_rows = squared.sqrt() / shock::CELL_ASPECT;
edges[count] = wave.origin.1 - half_rows;
edges[count + 1] = wave.origin.1 + half_rows;
count += 2;
}
let x = column;
for &edge in edges.iter().take(count) {
let y = edge.round();
if y < 0.0 || y >= rows as f32 {
continue;
}
let y = y as usize;
if self.trail.contains_key(&(x, y)) {
continue;
}
self.frame.set(
x,
y,
Cell::new(SHOCK_GLYPH, lit, style::Attribute::Reset),
);
}
}
}
}
}
impl Boid {
fn cell(&self, cols: usize, rows: usize) -> (usize, usize) {
let x = self.position.0.round() as isize;
let y = self.position.1.round() as isize;
(
x.rem_euclid(cols.max(1) as isize) as usize,
y.rem_euclid(rows.max(1) as isize) as usize,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
use std::time::Duration;
fn luminance(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,
}
}
fn flock(size: (u16, u16)) -> Boids {
let options = BoidsOptions {
screen_size: size,
boid_count: flock_count(size),
..Default::default()
};
Boids::new(options)
}
fn run(flock: &mut Boids, frames: u32) {
for _ in 0..frames {
flock.update();
flock.get_diff();
}
}
fn flock_count(size: (u16, u16)) -> u16 {
let area = size.0 as f32 * size.1 as f32;
((area * 0.5 * BoidsOptions::default().boid_coeff) as u16).clamp(50, 300)
}
fn flock_with_seed(size: (u16, u16), seed: u64) -> Boids {
let base = BoidsOptions::default();
let options = BoidsOptions {
screen_size: size,
boid_count: flock_count(size),
seed,
..base
};
Boids::new(options)
}
fn mean_nearest_neighbour(flock: &Boids) -> f32 {
flock.boids.iter().fold(0.0f32, |total, boid| {
let nearest = flock
.boids
.iter()
.filter(|other| other.position != boid.position)
.map(|other| {
let diff = flock.toroidal_diff(other.position, boid.position);
diff.0.hypot(diff.1)
})
.fold(f32::INFINITY, f32::min);
total + nearest
}) / flock.boids.len() as f32
}
#[test]
fn resize_recomputes_boid_count() {
let options = BoidsOptions {
screen_size: (80, 40),
boid_count: 10,
boid_coeff: 1.0,
..Default::default()
};
let mut boids = Boids::new(options);
boids.update_size(10, 10);
assert_eq!(boids.options.screen_size, (10, 10));
assert_eq!(boids.options.boid_count, 50);
}
#[test]
fn the_default_flock_is_about_five_percent_of_the_screen() {
let (width, height) = (80u16, 24u16);
let cells = f64::from(width) * f64::from(height);
let count = f64::from(flock((width, height)).options.boid_count);
let coverage = count / cells;
assert!(
(0.04..=0.06).contains(&coverage),
"the default flock covers {:.1}% of an {width}x{height} terminal \
({count:.0} of {cells:.0} cells), which is not the five percent a \
flock needs to read as a shape",
coverage * 100.0
);
}
#[test]
fn a_cell_the_boid_has_left_is_still_drawn_and_dimmer() {
let options = BoidsOptions {
screen_size: (80, 24),
boid_count: 1,
..Default::default()
};
let mut flock = Boids::new(options);
run(&mut flock, 90);
let boid = &flock.boids[0];
let (now, then) = (boid.history[0], boid.history[1]);
assert_ne!(now, then, "the boid did not move in the last frame");
let here = flock.frame.get(now.0, now.1);
let there = flock.frame.get(then.0, then.1);
assert_ne!(
there.symbol, ' ',
"the cell ({}, {}) that the boid just left is blank, so there is no \
trail",
then.0, then.1
);
assert!(
luminance(there.color) < luminance(here.color),
"the cell ({}, {}) the boid left is at brightness {:.2} and the one it \
is on is at {:.2}, so the trail is not dimmer than its head",
then.0,
then.1,
luminance(there.color),
luminance(here.color)
);
assert_eq!(
there.symbol, here.symbol,
"the trail changed glyph on the way out"
);
}
#[test]
fn the_trail_covers_more_cells_than_there_are_boids() {
let mut flock = flock((80, 24));
run(&mut flock, 120);
let lit = (0..flock.frame.height)
.flat_map(|y| (0..flock.frame.width).map(move |x| (x, y)))
.filter(|(x, y)| flock.frame.get(*x, *y).symbol != ' ')
.count();
assert!(
lit > flock.boids.len() * 2,
"{lit} cells are lit for {} boids, so the streak is barely longer \
than the boid that drew it",
flock.boids.len()
);
assert!(
lit < 80 * 24 / 2,
"{lit} of {} cells are lit, which is not a flock over a background",
80 * 24
);
}
#[test]
fn a_trail_cell_goes_back_to_blank_once_nothing_is_stamping_it() {
let mut flock = flock((80, 24));
run(&mut flock, 30);
let lit: HashSet<(usize, usize)> = flock.trail.keys().copied().collect();
assert!(lit.len() > 20, "the flock drew almost nothing");
run(&mut flock, 120);
let stale: Vec<(usize, usize)> = lit
.into_iter()
.filter(|cell| !flock.trail.contains_key(cell))
.collect();
let still_lit = stale
.iter()
.filter(|(x, y)| flock.frame.get(*x, *y).symbol != ' ')
.count();
assert_eq!(
still_lit, 0,
"{} cells that used to hold a trail are still drawn, so the trail \
only ever adds",
still_lit
);
}
#[test]
fn speed_is_legible_across_the_whole_range() {
let slow = speed_palette().sample(0.0);
let quick = speed_palette().sample(1.0);
assert_eq!(
slow,
style::Color::Rgb {
r: 12,
g: 48,
b: 96
}
);
assert_eq!(
quick,
style::Color::Rgb {
r: 255,
g: 255,
b: 255
},
"the top of the ramp is not the brightest colour, so speed still does \
not read"
);
assert!(
luminance(quick) - luminance(slow) > 0.5,
"the whole speed range spans only {:.2} of brightness, so the colour \
is not carrying the speed",
luminance(quick) - luminance(slow)
);
match quick {
style::Color::Rgb { r, g, b } => {
assert!(
r > 200 && g > 200 && b > 200,
"the fastest boid is ({r},{g},{b}); `speed * 128` against a \
max of 0.6 could not produce more than 76 in red"
);
}
other => panic!("the top of the ramp is {other:?}, not a colour"),
}
let base = BoidsOptions::default();
let boid = |speed: f32| Boid {
position: (1.0, 1.0),
velocity: (speed, 0.0),
character: 'x',
color: style::Color::Reset,
history: VecDeque::new(),
};
assert_eq!(
boid(base.min_speed).speed_fraction(base.min_speed, base.max_speed),
0.0
);
assert_eq!(
boid(base.max_speed).speed_fraction(base.min_speed, base.max_speed),
1.0
);
let middle = (base.min_speed + base.max_speed) / 2.0;
assert!(
(boid(middle).speed_fraction(base.min_speed, base.max_speed) - 0.5)
.abs()
< 0.01,
"halfway along the speed range is not halfway along the ramp"
);
assert_eq!(
boid(base.max_speed * 2.0)
.speed_fraction(base.min_speed, base.max_speed),
1.0
);
assert_eq!(boid(0.3).speed_fraction(0.6, 0.6), 1.0);
assert_eq!(boid(0.3).speed_fraction(0.6, 0.1), 1.0);
}
#[test]
fn the_flock_forms_clusters_rather_than_staying_a_gas() {
const SEEDS: [u64; 5] = [1, 2, 3, 4, 5];
const FRAMES: u32 = 240;
let size = (60u16, 30u16);
let start: f32 = SEEDS
.iter()
.map(|seed| mean_nearest_neighbour(&flock_with_seed(size, *seed)))
.sum();
let start = start / SEEDS.len() as f32;
let finish: f32 = SEEDS
.iter()
.map(|seed| {
let mut flock = flock_with_seed(size, *seed);
run(&mut flock, FRAMES);
mean_nearest_neighbour(&flock)
})
.sum();
let finish = finish / SEEDS.len() as f32;
assert!(
finish < start * 0.75,
"the mean distance to the nearest neighbour went from {start:.2} to \
{finish:.2} over {FRAMES} frames. A flock is boids that are closer \
together than chance, so this is a gas either way."
);
}
#[test]
fn a_boid_in_a_corner_is_pushed_towards_the_centre_not_along_one_axis() {
let options = BoidsOptions {
screen_size: (80, 24),
boid_count: 10,
..Default::default()
};
let border = options.border_factor;
let top_speed = options.max_speed;
let flock = Boids::new(options);
let magnitude = |v: (f32, f32)| v.0.hypot(v.1);
for &(x, y) in &[(0.0, 0.0), (79.0, 0.0), (0.0, 23.0), (79.0, 23.0)] {
let (fx, fy) = flock.border_force((x, y));
assert!(
fx.abs() > 0.0 && fy.abs() > 0.0,
"the boid at ({x}, {y}) is pushed ({fx}, {fy}), which is along one \
axis only"
);
assert_eq!(
fx.is_sign_positive(),
x < 40.0,
"the boid at ({x}, {y}) is pushed to the left, away from the middle"
);
assert_eq!(
fy.is_sign_positive(),
y < 12.0,
"the boid at ({x}, {y}) is pushed the wrong way vertically"
);
}
let edge = magnitude(flock.border_force((40.0, 0.0)));
let corner = magnitude(flock.border_force((0.0, 0.0)));
assert!(
(corner - edge).abs() < edge * 0.1,
"a corner is pushed {corner:.2} into the screen where the middle of the \
top edge is pushed {edge:.2}"
);
let maximum = border;
assert!(
corner <= maximum + f32::EPSILON,
"the border rule can add {corner:.2} to a velocity capped at {top_speed}"
);
}
#[test]
fn a_wave_pushes_a_boid_away_from_where_it_was_dropped() {
let mut flock = Boids::new(BoidsOptions {
screen_size: (80, 24),
boid_count: 1,
..Default::default()
});
flock.drop_wave((40.0, 12.0));
for (target, away) in [
((41.0, 12.0), (1.0, 0.0)),
((40.0, 12.0 + 1.0 / shock::CELL_ASPECT), (0.0, 1.0)),
((39.0, 12.0), (-1.0, 0.0)),
((40.0, 12.0 - 1.0 / shock::CELL_ASPECT), (0.0, -1.0)),
] {
let (fx, fy) = flock.shock_force(target, (1.0, 0.0));
assert!(
fx.hypot(fy) > 0.0,
"a wave dropped at (40, 12) does not reach the boid at {target:?}"
);
assert!(
fx * away.0 + fy * away.1 > 0.0,
"a wave dropped at (40, 12) pushes the boid at {target:?} by \
({fx:.2}, {fy:.2}), which is not directly away from it"
);
}
}
#[test]
fn a_wave_only_reaches_a_band_around_its_front() {
let mut flock = Boids::new(BoidsOptions {
screen_size: (80, 24),
boid_count: 1,
..Default::default()
});
flock.drop_wave((40.0, 12.0));
flock.waves[0].radius = 10.0;
let push = |distance: f32| {
flock.shock_force((40.0 + distance, 12.0), (1.0, 0.0)).0
};
let front = push(10.0);
let inside = push(7.5);
let outside = push(6.5);
let far_outside = push(20.0);
assert!(
front > 0.0 && inside > 0.0,
"a wave's own front ({front:.2}) and its trailing edge ({inside:.2}) \
should both be inside the band"
);
assert!(
outside < 0.001,
"a boid half a cell outside the band was pushed {outside:.4}"
);
assert!(
far_outside < 0.001,
"a boid ten cells clear of the band was pushed {far_outside:.4}, so a \
wave is a kick rather than a travelling band"
);
assert!(
front > inside,
"the front of a wave ({front:.2}) is weaker than its trailing edge \
({inside:.2})"
);
assert!(
front <= shock::PUSH + f32::EPSILON,
"a wave pushes by {front:.2}, past the {} it is meant to peak at",
shock::PUSH
);
}
#[test]
fn the_force_tapers_to_nothing_at_the_bands_edge() {
let mut flock = Boids::new(BoidsOptions {
screen_size: (80, 24),
boid_count: 1,
..Default::default()
});
flock.drop_wave((40.0, 12.0));
flock.waves[0].radius = 10.0;
let edge = shock::BAND;
let push = |distance: f32| {
flock.shock_force((40.0 + distance, 12.0), (1.0, 0.0)).0
};
let just_inside = push(10.0 - edge + 0.01);
let just_outside = push(10.0 - edge - 0.01);
let middle = push(10.0);
assert!(
just_outside < 0.001,
"the band does not end: a boid 0.01 cells past its trailing edge is \
still pushed {just_outside:.4}"
);
assert!(
just_inside < middle,
"the force does not taper: {just_inside:.4} at the edge of the band \
against {middle:.4} at its middle"
);
}
#[test]
fn a_boid_clicked_exactly_on_the_head_is_pushed_onward_and_stays_finite() {
let mut flock = Boids::new(BoidsOptions {
screen_size: (80, 24),
boid_count: 1,
..Default::default()
});
flock.boids[0].position = (40.0, 12.0);
flock.boids[0].velocity = (0.0, -0.4);
flock.drop_wave((40.0, 12.0));
let (fx, fy) = flock.shock_force((40.0, 12.0), (0.0, -0.4));
assert!(
fx.is_finite() && fy.is_finite(),
"clicking a boid on the head produced ({fx}, {fy})"
);
assert!(
fy < 0.0,
"a boid clicked on the head is pushed ({fx:.2}, {fy:.2}) rather than \
onward along the (-0.4) heading it was already travelling"
);
assert!(
fx.abs() < f32::EPSILON,
"a boid with a purely vertical heading picked up {fx:.4} of sideways \
force from being clicked on the head"
);
run(&mut flock, 30);
for boid in &flock.boids {
assert!(
boid.position.0.is_finite() && boid.position.1.is_finite(),
"a boid's position went to {:?} after being clicked on the head",
boid.position
);
}
}
#[test]
fn a_wave_reaches_across_the_wrap() {
let mut flock = Boids::new(BoidsOptions {
screen_size: (80, 24),
boid_count: 1,
..Default::default()
});
flock.drop_wave((1.0, 12.0));
let across = flock.shock_force((79.0, 12.0), (1.0, 0.0));
let straight = flock.shock_force((40.0, 12.0), (1.0, 0.0));
assert!(
across.0 < 0.0,
"a wave dropped at column 1 pushed a boid at column 79 to the right \
by {:.2}, so it did not reach across the wrap",
across.0
);
assert!(
straight.0 < 0.001,
"the same wave reached a boid 39 cells away in the ordinary direction \
by {:.4}, so the wrap is not what carried it",
straight.0
);
}
#[test]
fn a_drag_scatters_but_a_hover_does_not() {
let pointer = (40u16, 12u16);
let move_to = |flock: &mut Boids, position: (u16, u16)| {
flock.handle_input(&InputEvent::Pointer {
position,
phase: PointerPhase::Moved,
button: crate::runtime::PointerButton::Left,
});
};
let mut dragged = flock((80, 24));
dragged.handle_input(&InputEvent::Pointer {
position: pointer,
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
for x in 0..80u16 {
move_to(&mut dragged, (x, 12));
}
assert!(
dragged.waves.len() > 1,
"dragging across a whole screen dropped {} wave(s), so the drag is not \
scattering as it goes",
dragged.waves.len()
);
let mut hovered = flock((80, 24));
for x in 0..80u16 {
move_to(&mut hovered, (x, 12));
}
assert!(
hovered.waves.is_empty(),
"a cursor drifting across the screen without a button down dropped {} \
wave(s), so moving the mouse is enough to disturb the flock",
hovered.waves.len()
);
dragged.handle_input(&InputEvent::Pointer {
position: (0, 12),
phase: PointerPhase::Released,
button: crate::runtime::PointerButton::Left,
});
let before = dragged.waves.len();
for x in 0..80u16 {
move_to(&mut dragged, (x, 12));
}
assert_eq!(
dragged.waves.len(),
before,
"the flock kept scattering after the button was released"
);
}
#[test]
fn waves_end_and_the_flock_closes_again() {
let size = (80u16, 24u16);
let mut flock = flock(size);
flock.handle_input(&InputEvent::Pointer {
position: (40, 12),
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
assert_eq!(
flock.waves.len(),
1,
"a click dropped no wave to begin with"
);
run(&mut flock, 900);
assert!(
flock.waves.is_empty(),
"{} wave(s) were still alive fifteen seconds after one click",
flock.waves.len()
);
}
#[test]
fn clicking_spreads_the_flock_and_it_closes_again() {
const SEEDS: [u64; 4] = [11, 22, 33, 44];
const SETTLE: u32 = 180;
const SETTLED: u32 = 30;
let size = (60u16, 30u16);
let centre = (30u16, 15u16);
let after_click = |seed: u64| {
let mut flock = flock_with_seed(size, seed);
run(&mut flock, SETTLE);
flock.handle_input(&InputEvent::Pointer {
position: centre,
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
run(&mut flock, SETTLED);
mean_nearest_neighbour(&flock)
};
let untouched = |seed: u64| {
let mut flock = flock_with_seed(size, seed);
run(&mut flock, SETTLE);
run(&mut flock, SETTLED);
mean_nearest_neighbour(&flock)
};
let opened: f32 = SEEDS.iter().map(|s| after_click(*s)).sum();
let closed: f32 = SEEDS.iter().map(|s| untouched(*s)).sum();
let opened = opened / SEEDS.len() as f32;
let closed = closed / SEEDS.len() as f32;
assert!(
opened > closed * 1.1,
"clicking the middle of the flock left the mean nearest-neighbour \
distance at {opened:.2} against {closed:.2} for a flock left alone. \
A click that does not visibly open the flock up is not doing anything."
);
}
#[test]
fn the_wave_metric_corrects_for_a_tall_cell() {
let across = shock_distance((3.0, 0.0));
let down = shock_distance((0.0, 3.0));
assert_eq!(across, 3.0, "a horizontal cell counts as one cell");
assert!(
down > across * 1.5,
"three cells down is {down:.2} units and three cells across is \
{across:.2}, so the metric is not correcting for a tall cell"
);
let mut flock = Boids::new(BoidsOptions {
screen_size: (80, 24),
boid_count: 1,
..Default::default()
});
flock.drop_wave((40.0, 12.0));
flock.waves[0].radius = 10.0;
let beside = flock.shock_force((50.0, 12.0), (1.0, 0.0)).0;
let six_rows_up = flock.shock_force((40.0, 18.0), (1.0, 0.0)).1;
let six_and_a_half_rows_up = flock.shock_force((40.0, 18.5), (1.0, 0.0)).1;
assert!(
beside > 0.0,
"a boid ten cells beside a wave's front is not pushed"
);
assert!(
six_rows_up > 0.0,
"a boid six rows above a wave's origin is out of its band, but that is \
twelve corrected units and the band runs to thirteen"
);
assert_eq!(
six_and_a_half_rows_up, 0.0,
"a boid six and a half rows above a wave's origin is still within its \
band, so the vertical is not being scaled"
);
}
#[test]
fn the_ring_is_two_edges_with_nothing_between_them() {
let size = (60u16, 30u16);
let cols = size.0 as f32;
let (origin_x, origin_y) = (30usize, 15usize);
let mut flock = flock(size);
flock.get_diff();
flock.handle_input(&InputEvent::Pointer {
position: (origin_x as u16, origin_y as u16),
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
for _ in 0..12 {
flock.update();
}
let radius = flock.waves[0].radius;
assert!(
radius > shock::BAND,
"the wave has not travelled far enough for this test to mean anything: \
its front is at {radius:.2} and the band is {} wide",
shock::BAND
);
let inner = radius - shock::BAND;
let outer = radius + shock::BAND;
let drawn = flock.get_diff();
let ring: Vec<(usize, usize)> = drawn
.iter()
.filter(|(_, _, cell)| cell.symbol == SHOCK_GLYPH)
.map(|(x, y, _)| (*x, *y))
.collect();
assert!(
!ring.is_empty(),
"a wave that has travelled twelve frames drew nothing at all"
);
let on_the_column: Vec<f32> = ring
.iter()
.filter(|(x, _)| *x == origin_x)
.map(|(_, y)| (*y as f32 - origin_y as f32).abs() * shock::CELL_ASPECT)
.collect();
let near =
|target: f32| on_the_column.iter().any(|v| (v - target).abs() <= 1.0);
assert!(
near(inner) && near(outer),
"the ring on its own column crosses at {on_the_column:?} corrected \
units from the origin, but the band's two edges are at {inner:.1} and \
{outer:.1}. Both edges have to be drawn or the band is not a band."
);
let on_the_row: Vec<f32> = ring
.iter()
.filter(|(_, y)| *y == origin_y)
.map(|(x, _)| {
shock_distance((wrapped_column(*x, origin_x as f32, cols), 0.0))
})
.collect();
let in_the_body: Vec<f32> = on_the_row
.iter()
.copied()
.filter(|d| *d > inner - 1.0 && *d < outer - 1.0)
.collect();
assert!(
in_the_body.is_empty(),
"the ring is drawn across the body of its own band on the row through \
the origin, at {in_the_body:?} cells out where the band is \
{inner:.1} to {outer:.1}. A column past a circle's radius does not \
cross it, and clamping its height to zero instead of skipping it \
draws a bar through the band."
);
assert!(
!ring.contains(&(origin_x, origin_y)),
"the ring is drawn over the cell the wave came from"
);
let (leftmost, rightmost) = ring
.iter()
.map(|(x, _)| wrapped_column(*x, origin_x as f32, cols))
.fold((f32::MAX, f32::MIN), |(lo, hi), x| (lo.min(x), hi.max(x)));
assert!(
leftmost <= -outer + 1.0 && rightmost >= outer - 1.0,
"the ring reaches {leftmost:.1} to {rightmost:.1} either side of the \
origin, but the band's outer edge is at {outer:.1}, so it is an arc \
rather than a ring"
);
}
#[test]
fn the_ring_is_centred_where_the_click_was() {
let size = (60u16, 30u16);
let cols = size.0 as f32;
for click in [(10u16, 15u16), (50u16, 15u16), (30u16, 8u16)] {
let mut flock = flock(size);
flock.get_diff();
flock.handle_input(&InputEvent::Pointer {
position: click,
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
for _ in 0..12 {
flock.update();
}
let drawn = flock.get_diff();
let ring: Vec<(usize, usize)> = drawn
.iter()
.filter(|(_, _, cell)| cell.symbol == SHOCK_GLYPH)
.map(|(x, y, _)| (*x, *y))
.collect();
assert!(
!ring.is_empty(),
"no ring was drawn for a click at {click:?}"
);
let reach = flock.waves[0].radius + shock::BAND;
let furthest = ring
.iter()
.map(|(x, y)| {
shock_distance((
wrapped_column(*x, click.0 as f32, cols),
*y as f32 - click.1 as f32,
))
})
.fold(0.0f32, f32::max);
assert!(
furthest <= reach + 1.0,
"a click at {click:?} drew a ring cell {furthest:.1} cells from it, \
but the wave only reaches {reach:.1}, so part of that ring is not \
around the click"
);
}
}
#[test]
fn the_ring_does_not_paint_over_a_boid() {
let size = (60u16, 30u16);
let mut flock = flock(size);
flock.get_diff();
flock.handle_input(&InputEvent::Pointer {
position: (30, 15),
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
for _ in 0..12 {
flock.update();
}
let first_pass: Vec<(usize, usize)> = flock
.get_diff()
.iter()
.filter(|(_, _, cell)| cell.symbol == SHOCK_GLYPH)
.map(|(x, y, _)| (*x, *y))
.collect();
let (cell_x, cell_y) = *first_pass
.first()
.expect("a wave that has travelled twelve frames drew no ring at all");
flock.boids[0].position = (cell_x as f32, cell_y as f32);
flock.boids[0].history.clear();
flock.boids[0].history.push_back((cell_x, cell_y));
flock.stamp();
let boid_glyph = flock.boids[0].character;
flock.get_diff();
assert_eq!(
flock.frame.get(cell_x, cell_y).symbol,
boid_glyph,
"the ring painted over the boid at ({cell_x}, {cell_y}), which would \
make the flock appear to lose members every time a wave passed"
);
let drawn: usize = (0..size.0 as usize)
.flat_map(|x| (0..size.1 as usize).map(move |y| (x, y)))
.filter(|&(x, y)| flock.frame.get(x, y).symbol == SHOCK_GLYPH)
.count();
assert!(
drawn > 0,
"the ring drew nothing at all once a boid was on one of its cells"
);
}
#[test]
fn waves_are_capped_however_fast_they_are_dropped() {
let mut flock = flock((80, 24));
for i in 0..200u16 {
flock.handle_input(&InputEvent::Pointer {
position: (i % 80, 12),
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
}
assert_eq!(
flock.waves.len(),
shock::MAX_WAVES,
"200 clicks left {} waves alive",
flock.waves.len()
);
run(&mut flock, 10);
let pinned = flock
.boids
.iter()
.filter(|boid| boid.speed() >= flock.options.max_speed * 0.999)
.count();
assert!(
pinned < flock.boids.len() / 2,
"{pinned} of {} boids were at the speed cap after a pile of waves, so \
the cap is not holding",
flock.boids.len()
);
}
#[test]
fn reset_drops_the_waves() {
let mut flock = flock((80, 24));
flock.handle_input(&InputEvent::Pointer {
position: (40, 12),
phase: PointerPhase::Pressed,
button: crate::runtime::PointerButton::Left,
});
assert_eq!(flock.waves.len(), 1);
flock.reset();
assert!(
flock.waves.is_empty(),
"a reset flock came back with {} wave(s) still travelling",
flock.waves.len()
);
assert!(!flock.pointer_down, "a reset flock thinks a button is down");
}
#[test]
fn the_border_rule_does_not_reach_the_middle() {
let options = BoidsOptions {
screen_size: (80, 24),
boid_count: 10,
..Default::default()
};
let flock = Boids::new(options);
assert_eq!(flock.border_force((40.0, 12.0)), (0.0, 0.0));
assert_eq!(flock.border_force((25.0, 12.0)), (0.0, 0.0));
assert_eq!(flock.border_force((40.0, 6.0)), (0.0, 0.0));
assert_ne!(flock.border_force((4.0, 12.0)), (0.0, 0.0));
let wide = Boids::new(BoidsOptions {
screen_size: (200, 8),
boid_count: 10,
..Default::default()
});
assert_eq!(wide.border_force((100.0, 4.0)), (0.0, 0.0));
assert_ne!(wide.border_force((2.0, 4.0)), (0.0, 0.0));
let tall = Boids::new(BoidsOptions {
screen_size: (8, 200),
boid_count: 10,
..Default::default()
});
assert_eq!(tall.border_force((4.0, 100.0)), (0.0, 0.0));
assert_ne!(tall.border_force((4.0, 8.0)), (0.0, 0.0));
}
#[test]
fn every_direction_gets_a_distinct_glyph() {
for charset in [
BoidCharset::Simple,
BoidCharset::Arrow,
BoidCharset::Braille,
] {
let chars = charset.chars();
assert!(
charset.is_directional(),
"{charset:?} is meant to show a heading"
);
let distinct: HashSet<char> = chars.iter().copied().collect();
assert_eq!(
distinct.len(),
8,
"{charset:?} maps eight directions onto {} distinct glyphs: {chars:?}",
distinct.len()
);
for glyph in chars {
assert!(
!glyph.is_control(),
"{charset:?} contains the control character {glyph:?}"
);
}
}
assert_eq!(
BoidCharset::Dot
.chars()
.iter()
.collect::<HashSet<_>>()
.len(),
1,
"Dot is documented as directionless, so it should have changed"
);
}
#[test]
fn the_direction_sectors_run_east_then_clockwise_on_screen() {
let headings: [(f32, f32); 8] = [
(1.0, 0.0),
(1.0, 1.0),
(0.0, 1.0),
(-1.0, 1.0),
(-1.0, 0.0),
(-1.0, -1.0),
(0.0, -1.0),
(1.0, -1.0),
];
let expected: String = BoidCharset::Arrow.chars().iter().collect();
let mut drawn = String::new();
for (velocity, glyph) in headings.into_iter().zip(expected.chars()) {
let boid = Boid::new((0.0, 0.0), velocity);
assert_eq!(
boid.get_direction_char(&BoidCharset::Arrow.chars()),
glyph,
"a heading of {velocity:?} drew the wrong glyph. On a terminal y \
grows downwards, so (0, 1) is south and not north."
);
drawn.push(boid.get_direction_char(&BoidCharset::Arrow.chars()));
}
assert_eq!(drawn, expected);
}
#[test]
fn no_boid_is_drawn_bold() {
let mut flock = flock((80, 24));
run(&mut flock, 60);
let bold = (0..flock.frame.height)
.flat_map(|y| (0..flock.frame.width).map(move |x| (x, y)))
.filter(|(x, y)| flock.frame.get(*x, *y).attr == style::Attribute::Bold)
.count();
assert_eq!(bold, 0, "{bold} cells were drawn bold");
}
#[test]
fn the_new_and_the_promoted_settings_round_trip_through_their_toml_names() {
let wanted = r#"
trail_length = 9
charset = "Arrow"
"#;
let parsed: BoidsOptions = toml::from_str(wanted)
.expect("a boids section naming either key parses");
assert_eq!(parsed.trail_length, 9);
assert_eq!(parsed.charset, BoidCharset::Arrow);
let written = toml::to_string(&parsed).expect("serialises");
assert!(
written.contains("trail_length = 9"),
"trail_length did not come back out: {written}"
);
assert!(
written.contains(r#"charset = "Arrow""#),
"charset did not come back out: {written}"
);
let bare: BoidsOptions =
toml::from_str("boid_coeff = 1.0").expect("parses");
assert_eq!(bare.trail_length, BoidsOptions::default().trail_length);
assert_eq!(bare.charset, BoidsOptions::default().charset);
}
#[test]
fn the_first_frame_already_draws_the_flock() {
let mut flock = flock((80, 24));
let diff = flock.paint();
let lit = (0..flock.frame.height)
.flat_map(|y| (0..flock.frame.width).map(move |x| (x, y)))
.filter(|(x, y)| flock.frame.get(*x, *y).symbol != ' ')
.count();
assert!(
lit > 20,
"only {lit} cells were lit on the first frame, so the flock arrives \
late"
);
assert_eq!(
diff.len(),
lit,
"the first frame reported {} cells but {lit} are lit, so the flock \
is drawn on the frame after it should be",
diff.len()
);
}
#[test]
fn a_resize_leaves_nothing_to_draw_off_screen() {
let mut flock = flock((80, 24));
run(&mut flock, 40);
for &(width, height) in &[(20u16, 10u16), (200, 50), (6, 6), (80, 24)] {
flock.update_size(width, height);
let diff = flock.get_diff();
let escaped = diff
.iter()
.any(|(x, y, _)| *x >= width as usize || *y >= height as usize);
assert!(!escaped, "drew outside a {width}x{height} terminal");
assert_eq!(flock.frame.get_size(), (width as usize, height as usize));
run(&mut flock, 20);
}
}
#[test]
fn the_trail_does_not_accumulate_without_bound() {
let mut flock = flock((80, 24));
run(&mut flock, 30);
let early = flock.trail.len();
run(&mut flock, 600);
let late = flock.trail.len();
let cells = 80 * 24;
assert!(
late <= cells,
"{late} cells are lit on a screen with {cells} cells"
);
assert!(
late < early * 3 + 50,
"the lit trail grew from {early} cells to {late} over ten seconds, so \
something is not being faded out"
);
}
#[test]
fn a_stall_does_not_teleport_the_flock() {
let options = BoidsOptions {
screen_size: (80, 24),
boid_count: 50,
..Default::default()
};
let context = crate::runtime::FrameContext::new(
(80, 24),
0,
Duration::from_secs(9),
Duration::from_secs(9),
crate::runtime::InputState::default(),
);
let mut flock = Boids::new(options);
flock.update_with_context(&context);
for boid in &flock.boids {
assert!(
boid.position.0 >= 0.0
&& boid.position.0 < 80.0
&& boid.position.1 >= 0.0
&& boid.position.1 < 24.0,
"a boid is at {:?}, which is off the screen after a nine second \
frame",
boid.position
);
}
}
}