use crate::aquarium::charart::{self, CharArt, CharSpecies};
use crate::render::braille::{BrailleGrid, DOTS_PER_CELL, DOTS_X, DOTS_Y};
use crate::render::palette;
use crossterm::style::Color;
pub const POSES: usize = 4;
pub fn sources() -> impl Iterator<Item = Source<'static>> + Clone {
SPECIES
.iter()
.map(Source::Dots)
.chain(CHAR_SPECIES.iter().map(Source::Chars))
}
#[derive(Debug, Clone, Copy)]
pub enum Source<'a> {
Dots(&'a Species),
Chars(&'a CharSpecies),
}
impl Source<'_> {
pub fn name(&self) -> &'static str {
match self {
Source::Dots(s) => s.name,
Source::Chars(s) => s.name,
}
}
pub fn depth(&self) -> f32 {
match self {
Source::Dots(s) => s.depth,
Source::Chars(s) => s.depth,
}
}
pub fn chroma(&self) -> f32 {
match self {
Source::Dots(s) => s.chroma,
Source::Chars(s) => s.chroma,
}
}
pub fn color(&self) -> Color {
match self {
Source::Dots(s) => s.color,
Source::Chars(s) => s.color,
}
}
pub fn is_chars(&self) -> bool {
matches!(self, Source::Chars(_))
}
pub fn cycle(&self) -> usize {
match self {
Source::Dots(_) => POSES,
Source::Chars(_) => 1,
}
}
pub fn cruise(&self) -> f32 {
match self {
Source::Dots(s) => s.cruise,
Source::Chars(s) => s.cruise,
}
}
pub fn char_art(&self) -> Option<CharArt> {
match self {
Source::Dots(_) => None,
Source::Chars(s) => Some(charart::species(s)),
}
}
}
pub enum Sprite {
Dots(Box<FishArt>),
Chars(Box<CharArt>),
}
impl Sprite {
pub fn cells_wide(&self) -> usize {
match self {
Sprite::Dots(a) => a.cells_wide(),
Sprite::Chars(a) => a.cells_wide(),
}
}
pub fn cells_tall(&self) -> usize {
match self {
Sprite::Dots(a) => a.cells_tall(),
Sprite::Chars(a) => a.cells_tall(),
}
}
pub fn faces_left(&self, pose: usize) -> Option<bool> {
const FRONT: f32 = 0.40;
const BACK: f32 = 0.65;
let (eye, width) = match self {
Sprite::Dots(a) => {
let (dx, _) = (0..a.height())
.flat_map(|dy| (0..a.width()).map(move |dx| (dx, dy)))
.find(|(dx, dy)| a.part_at(*dx, *dy) == Part::Eye)?;
(dx as f32, a.width() as f32)
}
Sprite::Chars(a) => {
let x = a
.cells(pose)
.find(|(_, _, _, shade)| *shade == charart::EYE)?
.0;
(x as f32, a.cells_wide() as f32)
}
};
let where_ = eye / width;
if where_ <= FRONT {
Some(true)
} else if where_ >= BACK {
Some(false)
} else {
None
}
}
pub fn for_each_cell(
&self,
pose: usize,
mut f: impl FnMut(i32, i32, char, f32),
) {
match self {
Sprite::Dots(a) => {
for (x, y, ch, shade) in a.cells() {
f(x, y, ch, shade);
}
}
Sprite::Chars(a) => {
for (x, y, ch, shade) in a.cells(pose) {
f(x, y, ch, shade);
}
}
}
}
}
const WAVE_AMPLITUDE: f32 = 0.35;
const WAVE_START: f32 = 0.45;
const WAVE_LENGTH: f32 = 0.7;
fn wave_offset(t: f32, phase: f32) -> f32 {
let rear = ((t - WAVE_START) / (1.0 - WAVE_START)).clamp(0.0, 1.0);
rear * (std::f32::consts::TAU * (phase - WAVE_LENGTH * t)).sin()
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Belly {
Symmetric,
Keel,
Flat { level: f32 },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FinStyle {
Triangle,
Sickle,
Rounded,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TailFork {
Rounded,
Forked { depth: f32 },
}
#[derive(Debug, Clone, Copy)]
pub enum Markings {
None,
Lateral { y: f32, half: f32 },
Bars {
count: f32,
from: f32,
to: f32,
strength: f32,
},
Mottled { amount: f32 },
}
#[derive(Debug, Clone, Copy)]
pub struct Species {
#[cfg_attr(not(test), allow(dead_code))]
pub name: &'static str,
pub length: usize,
pub girth: f32,
peak: f32,
blunt: f32,
taper: f32,
belly: Belly,
pub dorsal: &'static [(f32, f32)],
pub anal: &'static [(f32, f32)],
pub caudal: (f32, f32, TailFork),
pub fin_style: FinStyle,
pub barbels: bool,
pub markings: Markings,
pub depth: f32,
pub chroma: f32,
pub color: Color,
pub cruise: f32,
}
pub static SPECIES: &[Species] = &[
Species {
name: "neon",
length: 22,
girth: 2.6,
peak: 0.38,
blunt: 1.45,
taper: 1.55,
belly: Belly::Keel,
dorsal: &[(0.26, 0.0), (0.46, 0.65), (0.60, 0.0)],
anal: &[(0.56, 0.0), (0.67, 0.85), (0.78, 0.0)],
caudal: (0.80, 0.85, TailFork::Rounded),
fin_style: FinStyle::Rounded,
barbels: false,
markings: Markings::Lateral { y: -0.1, half: 0.5 },
depth: 0.60,
chroma: 0.9,
color: Color::Rgb {
r: 150,
g: 235,
b: 240,
},
cruise: 0.70,
},
Species {
name: "tetra",
length: 28,
girth: 4.6,
peak: 0.34,
blunt: 1.15,
taper: 1.45,
belly: Belly::Symmetric,
dorsal: &[(0.28, 0.0), (0.40, 0.57), (0.54, 0.0)],
anal: &[(0.56, 0.0), (0.68, 0.41), (0.80, 0.0)],
caudal: (0.82, 0.89, TailFork::Forked { depth: 0.39 }),
fin_style: FinStyle::Triangle,
barbels: false,
markings: Markings::Bars {
count: 1.0,
from: 0.05,
to: 0.20,
strength: 0.85,
},
depth: 0.45,
chroma: 0.85,
color: Color::Rgb {
r: 240,
g: 150,
b: 60,
},
cruise: 0.65,
},
];
pub static CHAR_SPECIES: &[CharSpecies] = &[
CharSpecies {
name: "longfin",
depth: 0.08,
chroma: 1.0,
color: Color::Rgb {
r: 250,
g: 214,
b: 120,
},
cruise: 0.9,
frames: [
&[
r" /`-._ ",
r" _/,.._/ ",
r" ,-' , `-:,.-')",
r" : o ):'; _ { ",
r" `-. `' _,.-\`.\)",
r" `\\``\,-' ",
],
&[
r" /`-._ ",
r" _/,.._/ ) ",
r" ,-' , `-:,.-'{",
r" : o ):'; _ ) ",
r" `-. `' _,.-\`.\|",
r" `\\``\,-' | ",
],
&[
r" /`-._ ",
r" _/,.._/ ",
r" ,-' , `-:,.-' ",
r" : o ):'; _ { ",
r" `-. `' _,.-\`.`{",
r" `\\``\,-' ) ",
],
],
},
CharSpecies {
name: "bigeye",
depth: 0.14,
chroma: 0.95,
color: Color::Rgb {
r: 228,
g: 234,
b: 245,
},
cruise: 0.85,
frames: [
&[
r" /\ ",
r" _/./ ",
r" ,-' `-:.,-'/ ",
r" > O )<) _ ( ",
r" `-._ _.:' `-.\\ ",
r" `` \; ",
],
&[
r" /\ ",
r" _/./ / ",
r" ,-' `-:.,-'( ",
r" > O )<) _ \\ ",
r" `-._ _.:' `-. ",
r" `` \; ",
],
&[
r" /\ ",
r" _/./ ",
r" ,-' `-:.,-' ",
r" > O )<) _ / ",
r" `-._ _.:' `-.( ",
r" `` \; \\ ",
],
],
},
CharSpecies {
name: "slashback",
depth: 0.20,
chroma: 0.9,
color: Color::Rgb {
r: 150,
g: 220,
b: 160,
},
cruise: 0.8,
frames: [
&[
r"O o ",
r" _\_ o ",
r">('> \\ o\ . ",
r" //\___= ",
r" '' ",
],
&[
r"O o o ",
r" _\_ . ",
r">('> \\ o\ = ",
r" //\___ ",
r" '' ",
],
&[
r"O o ",
r" _\_ ",
r">('> \\ o\ o ",
r" //\___ . ",
r" '' = ",
],
],
},
CharSpecies {
name: "fry",
depth: 0.26,
chroma: 0.5,
color: Color::Rgb {
r: 240,
g: 210,
b: 150,
},
cruise: 0.35,
frames: [
&[r"|\.-*-. ", r"|( ( 0 ) ", r"|/`*-*` "],
&[r"|\.-*-/ ", r"|( ( 0 ", r"|/`*-*` )"],
&[r"|\.-*-. ", r"|( ( 0 ) ", r"|/`*-*-) "],
],
},
CharSpecies {
name: "stipple",
depth: 0.32,
chroma: 1.0,
color: Color::Rgb {
r: 200,
g: 170,
b: 235,
},
cruise: 0.7,
frames: [
&[
r" /`·.¸ ",
r" /¸...¸`:· ",
r" ¸.·´ ¸ `·.¸.·´) ",
r": © ):´; ¸ { ",
r" `·.¸ `· ¸.·´\`·¸) ",
r" `\\´´\¸.·´ ",
],
&[
r" /`·.¸ ",
r" /¸...¸`:· ",
r" ¸.·´ ¸ `·.¸.·´{ ",
r": © ):´; ¸ ) ",
r" `·.¸ `· ¸.·´\`·¸| ",
r" `\\´´\¸.·´ | ",
],
&[
r" /`·.¸ ",
r" /¸...¸`:· ",
r" ¸.·´ ¸ `·.¸.·´ ",
r": © ):´; ¸ { ",
r" `·.¸ `· ¸.·´\`·¸`{",
r" `\\´´\¸.·´ ) ",
],
],
},
];
fn body_shape(t: f32, peak: f32, blunt: f32, taper: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
let peak = peak.clamp(0.05, 0.95);
if t <= 0.0 || t >= 1.0 {
return 0.0;
}
if t < peak {
let u = (t / peak).clamp(0.0, 1.0);
(std::f32::consts::FRAC_PI_2 * u)
.sin()
.powf(1.0 / blunt.max(0.2))
} else {
let v = ((t - peak) / (1.0 - peak)).clamp(0.0, 1.0);
(std::f32::consts::FRAC_PI_2 * v).cos().powf(taper.max(0.2))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Part {
Flesh,
Dorsal,
Anal,
Eye,
Catchlight,
Barbel,
Tail,
Stripe,
Bar,
}
impl Part {
pub fn tag(self) -> char {
match self {
Part::Flesh => '.',
Part::Dorsal => 'D',
Part::Anal => 'A',
Part::Eye => 'O',
Part::Catchlight => '*',
Part::Barbel => 'b',
Part::Tail => 'T',
Part::Stripe => '=',
Part::Bar => '|',
}
}
}
pub struct FishArt {
grid: BrailleGrid,
shade: Vec<f32>,
part: Vec<Part>,
length: usize,
height: usize,
natural: (usize, usize),
cells_w: usize,
cells_h: usize,
}
impl FishArt {
pub fn width(&self) -> usize {
self.length
}
pub fn height(&self) -> usize {
self.height
}
pub fn body_length(&self) -> usize {
self.natural.0
}
pub fn raised_dots(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
let (w, h) = (self.length, self.height);
(0..h).flat_map(move |dy| {
(0..w).filter_map(move |dx| self.grid.dot(dx, dy).then_some((dx, dy)))
})
}
pub fn body_height(&self) -> usize {
self.natural.1
}
pub fn cells_wide(&self) -> usize {
self.cells_w
}
pub fn cells_tall(&self) -> usize {
self.cells_h
}
pub fn part_at(&self, dot_x: usize, dot_y: usize) -> Part {
if dot_x >= self.length || dot_y >= self.height {
return Part::Flesh;
}
self.part[dot_y * self.length + dot_x]
}
pub fn shade_at(&self, dot_x: usize, dot_y: usize) -> f32 {
if dot_x >= self.length || dot_y >= self.height {
return 0.0;
}
self.shade[dot_y * self.length + dot_x]
}
pub fn dot(&self, dot_x: usize, dot_y: usize) -> bool {
self.grid.dot(dot_x, dot_y)
}
pub fn cell_char(&self, cell_x: usize, cell_y: usize) -> char {
self.grid.cell_char(cell_x, cell_y)
}
pub fn cells(&self) -> impl Iterator<Item = (i32, i32, char, f32)> + '_ {
(0..self.cells_h).flat_map(move |cell_y| {
(0..self.cells_w).filter_map(move |cell_x| {
let symbol = self.grid.cell_char(cell_x, cell_y);
if symbol == ' ' {
return None;
}
Some((
cell_x as i32,
cell_y as i32,
symbol,
self.cell_shade(cell_x, cell_y),
))
})
})
}
pub fn shifted(&self, px: usize, py: usize) -> FishArt {
let (cw, ch) = (self.cells_w, self.cells_h);
let (out_w, out_h) = (cw * DOTS_X, ch * DOTS_Y);
let mut out = FishArt {
grid: BrailleGrid::new(cw, ch),
shade: vec![0.0; out_w * out_h],
part: vec![Part::Flesh; out_w * out_h],
length: out_w,
height: out_h,
natural: self.natural,
cells_w: cw,
cells_h: ch,
};
for oy in 0..out_h {
for ox in 0..out_w {
let (mx, my) = (ox + px, oy + py);
if mx < self.length && my < self.height && self.grid.dot(mx, my) {
out.grid.raise_dot(ox, oy);
out.shade[oy * out_w + ox] = self.shade[my * self.length + mx];
out.part[oy * out_w + ox] = self.part[my * self.length + mx];
}
}
}
out
}
pub fn mirrored(&self) -> FishArt {
let mut out = FishArt {
grid: BrailleGrid::new(self.cells_w + 1, self.cells_h + 1),
shade: vec![0.0; self.length * self.height],
part: vec![Part::Flesh; self.length * self.height],
length: self.length,
height: self.height,
natural: self.natural,
cells_w: self.cells_w,
cells_h: self.cells_h,
};
for y in 0..self.height {
for x in 0..self.length {
let dst_x = self.length - 1 - x;
if self.grid.dot(x, y) {
out.grid.raise_dot(dst_x, y);
out.shade[y * self.length + dst_x] =
self.shade[y * self.length + x];
out.part[y * self.length + dst_x] =
self.part[y * self.length + x];
}
}
}
out
}
fn cell_shade(&self, cell_x: usize, cell_y: usize) -> f32 {
let (dx0, dy0) = (cell_x * DOTS_X, cell_y * DOTS_Y);
let (mut sum, mut n) = (0.0f32, 0usize);
for sub in 0..DOTS_PER_CELL {
let (dx, dy) = (dx0 + sub % DOTS_X, dy0 + sub / DOTS_X);
if self.grid.dot(dx, dy) {
sum += self.shade_at(dx, dy);
n += 1;
}
}
if n == 0 { 0.0 } else { sum / n as f32 }
}
}
pub fn shade_colour(base: Color, shade: f32) -> Color {
let t = shade.clamp(0.0, 1.0);
let (belly, dorsal) = if let Color::Rgb { r, g, b } = base {
(
Color::Rgb {
r: (r as f32 * 0.52 + 18.0).clamp(0.0, 255.0) as u8,
g: (g as f32 * 0.56 + 24.0).clamp(0.0, 255.0) as u8,
b: (b as f32 * 0.58 + 30.0).clamp(0.0, 255.0) as u8,
},
Color::Rgb {
r: (r as f32 * 0.42 + 152.0).clamp(0.0, 255.0) as u8,
g: (g as f32 * 0.42 + 166.0).clamp(0.0, 255.0) as u8,
b: (b as f32 * 0.42 + 176.0).clamp(0.0, 255.0) as u8,
},
)
} else {
(base, base)
};
if t < 0.5 {
palette::lerp(belly, base, t * 2.0)
} else {
palette::lerp(base, dorsal, (t - 0.5) * 2.0)
}
}
pub fn rasterise(species: &Species, pose: usize) -> FishArt {
rasterise_at(species, pose, WAVE_AMPLITUDE)
}
pub fn rasterise_at(species: &Species, pose: usize, amplitude: f32) -> FishArt {
let length = species.length.max(8);
let girth = species.girth;
let dorsal_max = species
.dorsal
.iter()
.map(|(_, h)| *h * girth)
.fold(0.0f32, f32::max);
let anal_max = species
.anal
.iter()
.map(|(_, h)| *h * girth)
.fold(0.0f32, f32::max);
let above = species.girth + dorsal_max + 0.5;
let below = species.girth + anal_max + 0.5;
let height = ((above + below).ceil() as usize).max(8);
let spine = above;
let (cells_w, cells_h) = (length.div_ceil(DOTS_X), height.div_ceil(DOTS_Y));
let stride = length + DOTS_X;
let padded_h = height + DOTS_Y - 1;
let mut art = FishArt {
grid: BrailleGrid::new(cells_w + 1, cells_h + 1),
shade: vec![0.0; stride * padded_h],
part: vec![Part::Flesh; stride * padded_h],
length: stride,
height: padded_h,
natural: (length, height),
cells_w,
cells_h,
};
let tail_start = ((species.caudal.0).clamp(0.3, 0.96) * (length - 1) as f32)
.round() as usize;
let tail_start = tail_start.min(length - 2);
let ped = body_shape(
tail_start as f32 / (length - 1) as f32,
species.peak,
species.blunt,
species.taper,
) * species.girth;
let (ped_up, ped_down) = half_extents(species, ped);
let eye_r = (species.girth * 0.28).max(1.5);
let mut eye_x = ((length as f32) * 0.10).round() as usize;
for dx in 0..length {
let s = body_shape(
dx as f32 / (length - 1) as f32,
species.peak,
species.blunt,
species.taper,
) * species.girth;
if s >= eye_r * 1.6 {
eye_x = dx;
break;
}
}
let eye_depth = body_shape(
eye_x as f32 / (length - 1) as f32,
species.peak,
species.blunt,
species.taper,
) * species.girth;
let eye_y = spine - (eye_depth * 0.42).max(0.5);
let dorsal_centre = fin_centre(species.dorsal);
let anal_centre = fin_centre(species.anal);
let phase = pose as f32 / POSES as f32;
for dx in 0..length {
let t = dx as f32 / (length - 1) as f32;
let in_tail = dx >= tail_start;
let tail_len = (length - 1 - tail_start).max(1) as f32;
let (body_up, body_down, dorsal_h, anal_h) = if in_tail {
let f = ((dx - tail_start) as f32 / tail_len).clamp(0.0, 1.0);
let flare = f.sqrt() * (1.0 - 0.12 * f.powi(6));
let reach = species.caudal.1 * girth;
(
ped_up + (reach - ped_up).max(0.0) * flare,
ped_down + (reach - ped_down).max(0.0) * flare,
0.0,
0.0,
)
} else {
let s =
body_shape(t, species.peak, species.blunt, species.taper) * girth;
let (up, down) = half_extents(species, s);
(
up,
down,
shape_fin(
species.fin_style,
t,
interpolate(species.dorsal, t) * girth,
dorsal_centre.0,
dorsal_centre.1,
),
shape_fin(
species.fin_style,
t,
interpolate(species.anal, t) * girth,
anal_centre.0,
anal_centre.1,
),
)
};
let t = dx as f32 / (length - 1).max(1) as f32;
let axis = spine + amplitude * girth * wave_offset(t, phase);
let top = axis - body_up;
let bottom = axis + body_down;
for dy in 0..height {
let y = dy as f32;
let d = y - axis;
if species.barbels
&& !in_tail
&& dx <= eye_x
&& (y - (axis + species.girth * 0.74)).abs() < 0.6
{
art.grid.raise_dot(dx, dy);
art.shade[dy * stride + dx] = 0.28;
art.part[dy * stride + dx] = Part::Barbel;
continue;
}
let (shade, part) = if y >= top && y <= bottom {
let signed = if body_up + body_down > 0.0 {
(-d / (body_up + body_down) * 2.0).clamp(-1.0, 1.0)
} else {
0.0
};
let mut base = 0.51 + 0.29 * signed;
let mut part = if in_tail { Part::Tail } else { Part::Flesh };
match species.markings {
Markings::None => {}
Markings::Lateral { y: ly, half } => {
if (signed / 2.0 - ly / 2.0).abs() < half / 2.0 {
base = 0.88;
part = Part::Stripe;
}
}
Markings::Bars {
count,
from,
to,
strength,
} => {
if t >= from && t <= to && count >= 1.0 {
let period = (to - from).max(1e-3) / count;
let phase = ((t - from) / period).fract();
if phase < 0.34 {
base *= 1.0 - strength;
part = Part::Bar;
}
}
}
Markings::Mottled { amount } => {
if hash_dot(dx as i32, dy as i32) < amount {
base *= 0.80;
}
}
}
let ex = dx as f32 - eye_x as f32;
let ey = y - eye_y;
if (ex * ex + ey * ey).sqrt() <= eye_r {
base = 0.03;
part = Part::Eye;
if ex <= -0.5 && ey <= -0.5 && eye_r >= 1.2 {
base = 1.0;
part = Part::Catchlight;
}
}
(base, part)
} else if y < top && y >= top - dorsal_h {
(1.0, Part::Dorsal)
} else if y > bottom && y <= bottom + anal_h {
(0.0, Part::Anal)
} else {
continue;
};
if in_tail && let TailFork::Forked { depth } = species.caudal.2 {
let to_tip = (length - 1 - dx) as f32;
let notch =
depth * girth * (1.0 - to_tip / (tail_len * 0.7).max(1.0));
if to_tip < tail_len * 0.7 && d.abs() < notch.max(0.0) {
continue;
}
}
art.grid.raise_dot(dx, dy);
art.shade[dy * stride + dx] = shade;
art.part[dy * stride + dx] = part;
}
}
art
}
fn half_extents(species: &Species, shape: f32) -> (f32, f32) {
let up = shape;
let down = match species.belly {
Belly::Symmetric => shape,
Belly::Keel => shape * 0.88,
Belly::Flat { level } => shape.min(species.girth * level),
};
(up, down)
}
fn shape_fin(
style: FinStyle,
t: f32,
raw: f32,
centre: f32,
half_span: f32,
) -> f32 {
if raw <= 0.0 || half_span <= 1e-4 {
return 0.0;
}
match style {
FinStyle::Triangle => {
let u = ((t - centre) / (half_span * 0.85)).abs().clamp(0.0, 1.0);
(1.0 - u * u) * raw
}
FinStyle::Rounded => {
let u = ((t - centre) / (half_span * 0.65)).abs().clamp(0.0, 1.0);
(1.0 - u * u) * raw
}
FinStyle::Sickle => {
let before =
((t - (centre - half_span)) / half_span.max(1e-4)).clamp(0.0, 1.0);
let after =
(1.0 - ((t - centre) / half_span.max(1e-4)).clamp(0.0, 1.0)) * 1.6;
before.min(1.0).min(after.clamp(0.0, 1.0)).powf(0.7) * raw
}
}
}
fn fin_centre(points: &[(f32, f32)]) -> (f32, f32) {
let mut best = (0.0f32, 0.0f32);
let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
for (t, h) in points {
if *h > best.1 {
best = (*t, *h);
}
lo = lo.min(*t);
hi = hi.max(*t);
}
(best.0, ((hi - lo) * 0.5).max(1e-4))
}
fn interpolate(points: &[(f32, f32)], t: f32) -> f32 {
if points.is_empty() {
return 0.0;
}
if t <= points[0].0 {
return points[0].1;
}
let last = points[points.len() - 1];
if t >= last.0 {
return last.1;
}
for pair in points.windows(2) {
let (t0, v0) = pair[0];
let (t1, v1) = pair[1];
if t >= t0 && t <= t1 {
let span = t1 - t0;
if span <= f32::EPSILON {
return v1;
}
return v0 + (v1 - v0) * ((t - t0) / span);
}
}
last.1
}
fn hash_dot(x: i32, y: i32) -> f32 {
let mut h =
(x as u32).wrapping_mul(0x9E37_79B1) ^ (y as u32).wrapping_mul(0x85EB_CA6B);
h ^= h >> 15;
h = h.wrapping_mul(0xC2B2_AE35);
h ^= h >> 13;
(h & 0xFFFF) as f32 / 65535.0
}
#[cfg(test)]
mod tests {
use super::*;
const GRID: usize = 32;
const MIN_DISTINCT: f32 = 0.012;
const MEDIAN_DISTINCT: f32 = 0.04;
const ASPECT_NORM: f32 = 2.0;
use crate::render::palette::perceptual_distance;
fn normalised_profile(species: &Species, samples: usize) -> Vec<f32> {
let fish = rasterise(species, 0);
let (w, h) = (fish.width(), fish.height());
let mut per_column = vec![0.0f32; w];
for (x, slot) in per_column.iter_mut().enumerate() {
*slot = (0..h).filter(|y| fish.dot(x, *y)).count() as f32;
}
let peak = per_column.iter().copied().fold(0.0f32, f32::max).max(1.0);
(0..samples)
.map(|i| {
let t = (i as f32 + 0.5) / samples as f32;
let x = ((t * w as f32) as usize).min(w - 1);
per_column[x] / peak
})
.collect()
}
fn profile_distance(a: &[f32], b: &[f32]) -> f32 {
let n = a.len().min(b.len());
let sum: f32 = (0..n).map(|i| (a[i] - b[i]).powi(2)).sum();
(sum / n.max(1) as f32).sqrt()
}
#[test]
fn the_species_are_not_the_same_fish_at_different_lengths() {
const SAMPLES: usize = 48;
const MIN_DISTANCE: f32 = 0.055;
let profiles: Vec<Vec<f32>> = SPECIES
.iter()
.map(|s| normalised_profile(s, SAMPLES))
.collect();
let mut closest = f32::INFINITY;
let mut closest_pair = ("", "");
for i in 0..SPECIES.len() {
for j in (i + 1)..SPECIES.len() {
let d = profile_distance(&profiles[i], &profiles[j]);
if d < closest {
closest = d;
closest_pair = (SPECIES[i].name, SPECIES[j].name);
}
assert!(
d > MIN_DISTANCE,
"{} and {} differ by only {d:.3} in body profile, so they are \
the same fish at two lengths; a tank of one animal is a \
pattern, not a shoal",
SPECIES[i].name,
SPECIES[j].name
);
}
}
assert!(
closest > MIN_DISTANCE,
"closest pair is {} and {} at {closest:.3}",
closest_pair.0,
closest_pair.1
);
}
#[test]
fn every_species_is_pointed_at_the_nose_and_tapered_at_the_tail() {
for species in SPECIES {
let fish = rasterise(species, 0);
let (w, h) = (fish.width(), fish.height());
let per_column: Vec<f32> = (0..w)
.map(|x| (0..h).filter(|y| fish.dot(x, *y)).count() as f32)
.collect();
let peak = per_column.iter().copied().fold(0.0f32, f32::max);
assert!(
peak > 3.0,
"{}: its deepest column holds {peak} dots; there is no fish here",
species.name
);
assert!(
per_column[0] < peak * 0.4,
"{}: its first column holds {:.0} dots against a peak of {peak}, so \
the head is a vertical wall",
species.name,
per_column[0]
);
let fifth = (w / 5).max(1);
let nose = per_column[..fifth].iter().sum::<f32>() / fifth as f32;
let tail = per_column[w - fifth..].iter().sum::<f32>() / fifth as f32;
assert!(
nose < peak * 0.8,
"{}: the first fifth of its length averages {nose:.1} dots against \
a peak of {peak}",
species.name
);
assert!(
tail < peak * 0.7,
"{}: the last fifth averages {tail:.1} dots against a peak of \
{peak}; the fish does not taper to anything",
species.name
);
}
}
#[test]
fn the_body_is_solid_and_nothing_in_a_fish_is_dithered() {
for species in SPECIES {
let fish = rasterise(species, 0);
let (w, h) = (fish.width(), fish.height());
let mut ink = 0usize;
let mut holes: Vec<(usize, usize)> = Vec::new();
for y in 0..h {
for x in 0..w {
if fish.dot(x, y) {
ink += 1;
continue;
}
let up = y > 0 && fish.dot(x, y - 1);
let down = y + 1 < h && fish.dot(x, y + 1);
let left = x > 0 && fish.dot(x - 1, y);
let right = x + 1 < w && fish.dot(x + 1, y);
if up && down && left && right {
holes.push((x, y));
}
}
}
assert!(
ink > 40,
"{}: only {ink} dots of ink; there is no fish here",
species.name
);
assert!(
holes.is_empty(),
"{}: {} dots are enclosed by its own ink, the first at {:?}. A \
fish whose flesh is a dither pattern is a halftone screen laid \
over the animal.",
species.name,
holes.len(),
holes.first()
);
}
}
#[test]
fn every_species_draws_two_attached_fins_a_tone_step_from_its_body() {
for species in SPECIES {
let fish = rasterise(species, 0);
let (w, h) = (fish.width(), fish.height());
let is_flesh = |x: isize, y: isize| -> bool {
x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && {
let (x, y) = (x as usize, y as usize);
fish.dot(x, y) && fish.part_at(x, y) == Part::Flesh
}
};
let reaches_flesh = |x: usize, y: usize| -> bool {
const REACH: usize = 3;
let mut seen = std::collections::HashSet::new();
let mut frontier = vec![(x as isize, y as isize)];
seen.insert((x, y));
for _ in 0..REACH * REACH {
let mut next = Vec::new();
for (cx, cy) in frontier {
if is_flesh(cx, cy) {
return true;
}
for (dx, dy) in [(-1isize, 0isize), (1, 0), (0, -1), (0, 1)]
{
let (nx, ny) = (cx + dx, cy + dy);
if nx < 0
|| ny < 0
|| nx as usize >= w
|| ny as usize >= h
{
continue;
}
if seen.insert((nx as usize, ny as usize))
&& fish.dot(nx as usize, ny as usize)
{
next.push((nx, ny));
}
}
}
frontier = next;
}
false
};
let mut dorsal = 0usize;
let mut anal = 0usize;
let mut floating: Vec<(usize, usize)> = Vec::new();
for y in 0..h {
for x in 0..w {
let part = fish.part_at(x, y);
if !matches!(part, Part::Dorsal | Part::Anal) {
continue;
}
if part == Part::Dorsal {
dorsal += 1
} else {
anal += 1
};
if !reaches_flesh(x, y) {
floating.push((x, y));
}
}
}
assert!(
floating.is_empty(),
"{}: {} fin dots cannot reach the body at all, the first at {:?}. A \
fin that is not joined to the animal is a bar floating above it.",
species.name,
floating.len(),
floating.first()
);
assert!(
dorsal >= 3,
"{}: only {dorsal} dorsal-fin dots",
species.name
);
assert!(
anal >= 3,
"{}: only {anal} anal-fin dots, so it has no bottom fin at all",
species.name
);
}
}
#[test]
fn a_fin_is_a_step_away_from_the_flesh_it_sits_on() {
for species in SPECIES {
let fish = rasterise(species, 0);
let (w, h) = (fish.width(), fish.height());
let mut flesh = (f32::INFINITY, f32::NEG_INFINITY);
for y in 0..h {
for x in 0..w {
if fish.dot(x, y) && fish.part_at(x, y) == Part::Flesh {
let s = fish.shade_at(x, y);
flesh.0 = flesh.0.min(s);
flesh.1 = flesh.1.max(s);
}
}
}
assert!(
flesh.0 > 0.10,
"{}: its flesh reaches down to {:.2} of the ramp, so it is already \
as dark as an anal fin",
species.name,
flesh.0
);
assert!(
flesh.1 < 0.90,
"{}: its flesh reaches up to {:.2} of the ramp, so it is already as \
light as a dorsal fin",
species.name,
flesh.1
);
}
}
#[test]
fn no_fin_is_too_short_to_land_on_a_row() {
const MIN_FIN: f32 = 1.5;
for species in SPECIES {
for (what, points) in
[("dorsal", species.dorsal), ("anal", species.anal)]
{
let tallest = points
.iter()
.map(|(_, h)| *h * species.girth)
.fold(0.0f32, f32::max);
if tallest == 0.0 {
continue; }
assert!(
tallest >= MIN_FIN,
"{}: its {what} fin peaks at {tallest:.1} dots, under {MIN_FIN}. A \
fin that short falls between rows and is drawn on some \
columns and not others.",
species.name
);
}
}
}
#[test]
fn a_large_fish_has_one_catchlight_that_lifts_its_cell() {
for species in SPECIES {
let fish = rasterise(species, 0);
let (w, h) = (fish.width(), fish.height());
assert!(
(0..w)
.flat_map(|x| (0..h).map(move |y| (x, y)))
.any(|(x, y)| fish.part_at(x, y) == Part::Eye),
"{}: no pupil, so nothing for a catchlight to be on",
species.name
);
let glint: Vec<(usize, usize)> = (0..w)
.flat_map(|x| (0..h).map(move |y| (x, y)))
.filter(|(x, y)| fish.part_at(*x, *y) == Part::Catchlight)
.collect();
assert_eq!(
glint.len(),
1,
"{}: {} catchlight dots. It must be exactly one, because a \
catchlight is only visible if it is alone in its cell.",
species.name,
glint.len()
);
let (gx, gy) = glint[0];
let (cx, cy) = (gx / DOTS_X, gy / DOTS_Y);
let mut with = 0.0f32;
let mut without = 0.0f32;
let mut n = 0.0f32;
for dy in 0..DOTS_Y {
for dx in 0..DOTS_X {
let (px, py) = (cx * DOTS_X + dx, cy * DOTS_Y + dy);
if px >= fish.length || py >= fish.height {
continue;
}
let shade = fish.shade_at(px, py);
with += shade;
n += 1.0;
without += if (px, py) == (gx, gy) { 0.03 } else { shade };
}
}
let lift = with / n - without / n;
assert!(
lift > 0.10,
"{}: its catchlight at ({gx},{gy}) lifts its cell's mean by only \
{lift:.3}. One dot of light is only visible if it brightens the \
cell, and this one does not.",
species.name
);
}
}
#[test]
fn the_head_does_not_move_and_the_rear_does() {
for species in SPECIES {
let natural = rasterise(species, 0).body_length();
let rigid_end = (WAVE_START * (natural - 1) as f32).round() as usize;
for a in 0..POSES {
for b in (a + 1)..POSES {
let fa = rasterise(species, a);
let fb = rasterise(species, b);
let mut head_moved = None;
let mut rear_moved = false;
for x in 0..fa.width() {
for y in 0..fa.height() {
if fa.dot(x, y) == fb.dot(x, y) {
continue;
}
if x < rigid_end {
head_moved = Some(x);
} else {
rear_moved = true;
}
}
}
assert!(
head_moved.is_none(),
"{}: poses {a} and {b} differ at dot column {}, in front of \
the wave's start at {rigid_end} -- a fish whose head changes \
between poses reads as twitching",
species.name,
head_moved.unwrap_or(0)
);
assert!(
rear_moved,
"{}: poses {a} and {b} are identical behind column {rigid_end}, \
so the fish does not swim",
species.name
);
}
}
}
}
#[test]
fn the_wave_bends_the_body_and_not_only_the_caudal_fin() {
for species in SPECIES {
let a = rasterise(species, 0);
let b = rasterise(species, 1);
let tail_start = ((species.caudal.0).clamp(0.3, 0.96)
* (a.body_length() - 1) as f32)
.round() as usize;
let moving_in_front = (0..tail_start)
.filter(|&x| (0..a.height()).any(|y| a.dot(x, y) != b.dot(x, y)))
.count();
assert!(
moving_in_front >= 2,
"{}: only {moving_in_front} dot columns in front of the caudal at \
{tail_start} change between poses. The body ahead of the fin is \
rigid, so this is a fish with a swinging tail rather than a fish \
swimming, which is the pendulum this replaced.",
species.name
);
}
}
#[test]
fn the_wave_moves_enough_dots_to_be_seen() {
const MIN_FRACTION_MOVING: f32 = 0.10;
for species in SPECIES {
let a = rasterise(species, 0);
let b = rasterise(species, POSES / 2);
let ink = a.raised_dots().count().max(b.raised_dots().count());
let moved = (0..a.height())
.flat_map(|y| (0..a.width()).map(move |x| (x, y)))
.filter(|&(x, y)| a.dot(x, y) != b.dot(x, y))
.count();
let fraction = moved as f32 / ink as f32;
assert!(
fraction >= MIN_FRACTION_MOVING,
"{}: only {moved} of {ink} dots change between opposite poses \
({:.0}%, floor {:.0}%). The tail is moving less than a dot, so no \
dots move and the fish slides.",
species.name,
fraction * 100.0,
MIN_FRACTION_MOVING * 100.0
);
}
}
#[test]
fn the_tail_tip_does_not_travel_further_than_half_the_fish_is_deep() {
const MAX_TIP_TRAVEL_IN_BODY_DEPTHS: f32 = 0.5;
for species in SPECIES {
let fish = rasterise(species, 0);
let natural = fish.body_length();
let tail_start = ((species.caudal.0).clamp(0.3, 0.96)
* (natural - 1) as f32)
.round() as usize;
let flesh_depth = (0..tail_start.min(fish.width()))
.map(|x| {
let ys: Vec<usize> = (0..fish.height())
.filter(|&y| {
fish.dot(x, y) && fish.part_at(x, y) == Part::Flesh
})
.collect();
ys.last().map(|hi| hi + 1 - ys[0]).unwrap_or(0)
})
.max()
.unwrap_or(0);
assert!(
flesh_depth > 0,
"{}: no raised flesh at all in front of its caudal, so there is no \
body depth to measure.",
species.name
);
let travel = 2.0 * WAVE_AMPLITUDE * species.girth;
let ratio = travel / flesh_depth as f32;
assert!(
ratio <= MAX_TIP_TRAVEL_IN_BODY_DEPTHS,
"{}: its tail tip travels {travel:.2} dots per beat against a body \
{flesh_depth} dots deep -- {ratio:.2} of its own depth, over the \
{MAX_TIP_TRAVEL_IN_BODY_DEPTHS} limit. That is a vibration, not a \
swim.",
species.name
);
}
}
#[test]
fn the_beat_sweeps_rather_than_snapping_between_two_extremes() {
for species in SPECIES {
let tip: Vec<f32> = (0..POSES)
.map(|pose| wave_offset(1.0, pose as f32 / POSES as f32))
.collect();
let lo = tip.iter().cloned().fold(f32::MAX, f32::min);
let hi = tip.iter().cloned().fold(f32::MIN, f32::max);
let between = tip.iter().filter(|&&o| o > lo && o < hi).count();
assert!(
between >= 2,
"{}: over the cycle its tail tip never sits strictly between the \
extremes {lo:.3} and {hi:.3} -- it visits {between} intermediate \
position(s) out of {POSES}: {tip:?}. That is a pendulum, a fish \
alternating between two extremes, and not a wave. POSES = {POSES} \
cannot sample a beat finely enough.",
species.name
)
}
}
#[test]
fn no_two_poses_are_the_same_picture() {
for species in SPECIES {
let sets: Vec<_> = (0..POSES).map(|p| rasterise(species, p)).collect();
for a in 0..POSES {
for b in (a + 1)..POSES {
let same = (0..sets[a].height()).all(|y| {
(0..sets[a].width())
.all(|x| sets[a].dot(x, y) == sets[b].dot(x, y))
});
assert!(
!same,
"{}: pose {a} and pose {b} are the same picture, so the beat \
has no motion in it at all",
species.name
);
}
}
}
}
#[test]
fn nothing_is_clipped_by_its_own_bitmap() {
for species in SPECIES {
let fish = rasterise(species, 0);
let (w, h) = (fish.width(), fish.height());
let (x0, x1, _y0, y1) = ink_extent(&fish);
assert!(
x0 == 0 || x1 < w,
"{}: its ink starts at {x0}, so the bitmap is wider than the fish",
species.name
);
assert!(
x1 + 1 < w,
"{}: its ink ends at {x1} of {w} dots, so the one-dot horizontal \
shift phase has no slack and will clip the fish",
species.name
);
assert!(
y1 + 3 < h,
"{}: its ink ends at {y1} of {h} dots, so the three-row vertical \
shift phases have no slack and will clip the fish",
species.name
);
}
}
#[test]
fn a_mirrored_fish_is_the_same_fish_facing_the_other_way() {
for species in SPECIES {
let right = rasterise(species, 0);
let left = right.mirrored();
let (w, h) = (right.width(), right.height());
let mut ink = 0usize;
for y in 0..h {
for x in 0..w {
assert_eq!(
right.dot(x, y),
left.dot(w - 1 - x, y),
"{}: row {y} is not mirrored at column {x}",
species.name
);
if right.dot(x, y) {
ink += 1;
}
}
}
assert_eq!(
ink,
(0..h)
.flat_map(|y| (0..w).map(move |x| (x, y)))
.filter(|(x, y)| left.dot(*x, *y))
.count(),
"{}: mirroring changed how much ink there is",
species.name
);
}
}
#[test]
fn a_shifted_fish_loses_at_most_its_thin_edges() {
for species in SPECIES {
let base = rasterise(species, 0);
let (w, h) = (base.width(), base.height());
let base_ink = (0..h)
.flat_map(|y| (0..w).map(move |x| (x, y)))
.filter(|(x, y)| base.dot(*x, *y))
.count();
for py in 0..DOTS_Y {
for px in 0..DOTS_X {
let shifted = base.shifted(px, py);
let (sw, sh) = (shifted.width(), shifted.height());
let ink = (0..sh)
.flat_map(|y| (0..sw).map(move |x| (x, y)))
.filter(|(x, y)| shifted.dot(*x, *y))
.count();
let kept = ink as f32 / base_ink as f32;
assert!(
kept > 0.80,
"{}: phase ({px},{py}) kept only {:.0}% of its ink \
({ink} of {base_ink}); the sub-cell shift is cutting into \
the fish, not moving it",
species.name,
kept * 100.0
);
}
}
}
}
#[test]
fn a_fish_is_lit_from_above() {
for species in SPECIES {
let fish = rasterise(species, 0);
let (w, h) = (fish.width(), fish.height());
let mut shades: Vec<f32> = (0..w)
.flat_map(|x| (0..h).map(move |y| (x, y)))
.filter(|(x, y)| {
fish.dot(*x, *y) && fish.part_at(*x, *y) == Part::Flesh
})
.map(|(x, y)| fish.shade_at(x, y))
.collect();
assert!(
shades.len() > 20,
"{}: only {} dots of unadorned body",
species.name,
shades.len()
);
shades.sort_by(|a, b| a.partial_cmp(b).unwrap());
let quartile = (shades.len() / 4).max(1);
let bottom: f32 =
shades[..quartile].iter().sum::<f32>() / quartile as f32;
let top: f32 = shades[shades.len() - quartile..].iter().sum::<f32>()
/ quartile as f32;
assert!(
top > bottom + 0.25,
"{}: its darkest flesh averages {bottom:.2} and its lightest {top:.2}. \
A fish lit from below is a fish lit from nowhere.",
species.name
);
}
}
#[test]
fn the_shading_ramp_has_a_flank() {
let base = crossterm::style::Color::Rgb {
r: 200,
g: 120,
b: 40,
};
let belly = shade_colour(base, 0.0);
let low = shade_colour(base, 0.25);
let flank = shade_colour(base, 0.5);
let high = shade_colour(base, 0.75);
let back = shade_colour(base, 1.0);
let lums = [belly, low, flank, high, back].map(palette::luminance);
for pair in lums.windows(2) {
assert!(
pair[1] > pair[0],
"the ramp is not monotonic: {lums:?} in OKLab luminance"
);
}
assert_ne!(
flank, back,
"the flank and the back are the same colour, so the ramp has two stops \
wearing three names"
);
assert!(
perceptual_distance(flank, back) > 0.05,
"the flank and the back are only {:.3} apart",
perceptual_distance(flank, back)
);
}
#[test]
fn the_species_occupy_separate_depth_bands_with_room_to_spread() {
const SPREAD: f32 = 0.44;
let mut bands: Vec<(&str, f32)> =
sources().map(|s| (s.name(), s.depth())).collect();
bands.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
for pair in bands.windows(2) {
let gap = (pair[1].1 - pair[0].1).abs();
assert!(
gap < SPREAD,
"{} and {} are {gap:.2} apart in depth and a fish's depth is \
jittered by {SPREAD}, so they overlap -- which is the point. But a \
gap *larger* than the spread would put each species in its own \
horizontal stripe and the tank would read as rows.",
pair[0].0,
pair[1].0
);
}
let (lo, hi) = (bands[0].1, bands[bands.len() - 1].1);
assert!(
hi - lo > 0.5,
"the species' depths span only {hi:.2} - {lo:.2} = {:.2}; there is no \
volume in this tank",
hi - lo
);
}
#[test]
fn the_character_species_are_the_near_ones() {
for s in sources() {
let (name, depth, chars) = (s.name(), s.depth(), s.is_chars());
if chars {
assert!(
depth < 0.35,
"{name} is drawn in characters but sits at depth {depth:.2}. \
Characters carry a face, and a face is only legible up close."
);
} else {
assert!(
depth > 0.35,
"{name} is drawn in braille but sits at depth {depth:.2}. Braille \
is a silhouette, and a silhouette is all a distant fish has."
);
}
}
}
#[test]
fn the_dot_species_are_proportioned_for_square_dots() {
const BANDS: &[(&str, f32, f32)] = &[
("neon", 2.10, 2.70),
("tetra", 1.75, 2.20),
];
for (i, species) in SPECIES.iter().enumerate() {
let (mut x0, mut y0) = (usize::MAX, usize::MAX);
let (mut x1, mut y1) = (0usize, 0usize);
for pose in 0..POSES {
for (x, y) in rasterise(species, pose).raised_dots() {
x0 = x0.min(x);
y0 = y0.min(y);
x1 = x1.max(x);
y1 = y1.max(y);
}
}
let (w, h) = (
rasterise(species, 0).width(),
rasterise(species, 0).height(),
);
let ratio = (x1 - x0 + 1) as f32 / (y1 - y0 + 1) as f32;
let (name, lo, hi) = BANDS[i];
assert_eq!(name, species.name, "the band table is out of order");
assert!(
(lo..=hi).contains(&ratio),
"{}: {w}x{h} dots of bitmap hold a {ratio:.2}:1 animal, outside \
{lo}-{hi}. One number for a round fish and a spindle is what made \
this file draw bars.",
species.name
);
}
}
#[test]
fn the_character_species_are_all_spindles_of_the_same_proportion() {
const BAND: (f32, f32) = (1.25, 2.00);
let mut measured: Vec<(&str, f32)> = Vec::new();
for s in CHAR_SPECIES {
let a = crate::aquarium::charart::species(s);
let (x0, x1, y0, y1) = char_ink_extent(&a, 0);
let (w, h) = (x1 - x0 + 1, y1 - y0 + 1);
let ratio = w as f32 / (h as f32 * 2.0);
assert!(
(BAND.0..=BAND.1).contains(&ratio),
"{}: {w} columns by {h} rows of ink is {ratio:.2}:1 once the cell's \
2:1 height is accounted for, outside {:.2}-{:.2}. This set is five \
spindles and this is the band that says so.",
s.name,
BAND.0,
BAND.1
);
measured.push((s.name, ratio));
}
let lo = measured.iter().map(|(_, r)| *r).fold(f32::MAX, f32::min);
let hi = measured.iter().map(|(_, r)| *r).fold(f32::MIN, f32::max);
assert!(
hi - lo < 0.65,
"the set's aspect spread is {:.2}, from {lo:.2} to {hi:.2} in {measured:?}. \
A band wide enough for that is not a band.",
hi - lo
);
}
#[test]
fn no_two_species_are_the_same_animal() {
let profiles: Vec<(&str, Vec<f32>)> =
sources().map(|s| (s.name(), silhouette(s).0)).collect();
assert_eq!(
profiles.len(),
SPECIES.len() + CHAR_SPECIES.len(),
"the tank's species list changed shape"
);
let mut every: Vec<f32> = Vec::new();
for (i, (name_a, a)) in profiles.iter().enumerate() {
for (name_b, b) in profiles.iter().skip(i + 1) {
let difference =
a.iter().zip(b).map(|(x, y)| (x - y).abs()).sum::<f32>()
/ a.len() as f32;
assert!(
difference > MIN_DISTINCT,
"{name_a} and {name_b} differ by only {difference:.4} of mean \
density once both are resampled to {GRID}x{GRID}. Two species \
that are the same drawing twice is not a shoal, it is a \
pattern."
);
every.push(difference);
}
}
every.sort_by(|a, b| a.partial_cmp(b).unwrap());
let median = every[every.len() / 2];
assert!(
median > MEDIAN_DISTINCT,
"the median pair differs by only {median:.4} over {} pairs. Every pair \
clears a floor of {MIN_DISTINCT} and the set is still one animal.",
every.len()
);
}
#[test]
fn the_silhouette_comparator_can_tell_one_species_from_two() {
let profiles: Vec<(&str, Vec<f32>)> =
sources().map(|s| (s.name(), silhouette(s).0)).collect();
let difference = |a: &[f32], b: &[f32]| {
a.iter().zip(b).map(|(x, y)| (x - y).abs()).sum::<f32>()
/ a.len() as f32
};
for (i, (name, a)) in profiles.iter().enumerate() {
for (other, b) in profiles.iter().skip(i + 1) {
assert!(
difference(a, b) > MIN_DISTINCT,
"{name} and {other} differ by {:.4}, which is inside the \
threshold of {MIN_DISTINCT}, so the real pairs have nothing to \
clear",
difference(a, b)
);
}
}
let (name, a) = &profiles[0];
let again = silhouette(sources().next().unwrap()).0;
assert_eq!(
*name, profiles[0].0,
"the same species produced two different names"
);
assert!(
difference(a, &again) < f32::EPSILON,
"the same species silhouettes to {:.6} of difference. `silhouette` is \
not a function of its species.",
difference(a, &again)
);
let (name, a) = &profiles[0];
let ones = vec![1.0f32; a.len()];
let mean = a.iter().sum::<f32>() / a.len() as f32;
let flat = vec![mean; a.len()];
assert!(
difference(&flat, &ones) > 0.04,
"a flat {name} and a full one differ by only {:.4}, so the metric's \
whole range is below its own threshold",
difference(&flat, &ones)
);
}
fn silhouette(s: Source<'_>) -> (Vec<f32>, f32) {
let n = GRID * GRID;
#[allow(clippy::needless_late_init)]
let marks: Vec<(f32, f32)>;
let (ink_w, ink_h) = match s {
Source::Dots(sp) => {
let fish = rasterise(sp, 0);
let (x0, x1, y0, y1) = ink_extent(&fish);
let (w, h) = (x1 - x0 + 1, y1 - y0 + 1);
marks = fish
.raised_dots()
.map(|(dx, dy)| {
((dx - x0) as f32 / w as f32, (dy - y0) as f32 / h as f32)
})
.collect();
(fish.cells_wide(), fish.cells_tall())
}
Source::Chars(sp) => {
let a = crate::aquarium::charart::species(sp);
let (x0, x1, y0, y1) = char_ink_extent(&a, 0);
let (w, h) = (x1 - x0 + 1, y1 - y0 + 1);
marks = a
.cells(0)
.map(|(x, y, _, _)| {
let (dx, dy) = (x as usize - x0, y as usize - y0);
(dx as f32 / w as f32, dy as f32 / h as f32)
})
.collect();
(a.cells_wide(), a.cells_tall())
}
};
let aspect = ink_w as f32 / (ink_h as f32 * 2.0);
let mut grid = vec![0.0f32; n];
for (fx, fy) in marks {
let gx =
((fx * aspect / ASPECT_NORM * GRID as f32) as usize).min(GRID - 1);
let gy = ((fy * GRID as f32) as usize).min(GRID - 1);
grid[gy * GRID + gx] = 1.0;
}
let mut out = vec![0.0f32; n];
for y in 0..GRID {
for x in 0..GRID {
let mut sum = 0.0;
let mut count = 0.0;
for dy in -1i32..=1 {
for dx in -1i32..=1 {
let (nx, ny) = (x as i32 + dx, y as i32 + dy);
if (0..GRID as i32).contains(&nx)
&& (0..GRID as i32).contains(&ny)
{
sum += grid[ny as usize * GRID + nx as usize];
count += 1.0;
}
}
}
out[y * GRID + x] = sum / count;
}
}
(out, aspect)
}
fn char_ink_extent(
a: &crate::aquarium::charart::CharArt,
pose: usize,
) -> (usize, usize, usize, usize) {
let (w, h) = (a.cells_wide(), a.cells_tall());
let (mut x0, mut x1, mut y0, mut y1) = (w, 0usize, h, 0usize);
for (x, y, _, _) in a.cells(pose) {
let (x, y) = (x as usize, y as usize);
x0 = x0.min(x);
x1 = x1.max(x);
y0 = y0.min(y);
y1 = y1.max(y);
}
(x0, x1, y0, y1)
}
#[test]
fn the_eye_reaches_the_terminal() {
for species in SPECIES {
for pose in 0..POSES {
let fish = rasterise(species, pose);
let eye_cells: std::collections::BTreeSet<(usize, usize)> = (0
..fish.width())
.flat_map(|dx| (0..fish.height()).map(move |dy| (dx, dy)))
.filter(|(dx, dy)| fish.part_at(*dx, *dy) == Part::Eye)
.map(|(dx, dy)| (dx / DOTS_X, dy / DOTS_Y))
.collect();
assert!(
!eye_cells.is_empty(),
"{} pose {pose} has no eye dots at all",
species.name
);
let mut eye_shade = f32::MAX;
let mut flank_shade = 0.0f32;
let mut flank_cells = 0usize;
for (x, y, _glyph, shade) in fish.cells() {
let key = (x as usize, y as usize);
if eye_cells.contains(&key) {
eye_shade = eye_shade.min(shade);
} else {
flank_shade += shade;
flank_cells += 1;
}
}
let flank = flank_shade / flank_cells.max(1) as f32;
assert!(
eye_shade < f32::MAX,
"{}: {} eye dots fall outside every cell the fish draws",
species.name,
eye_cells.len()
);
assert!(
eye_shade < flank - 0.25,
"{}: the darkest cell on its eye resamples to {eye_shade:.2} \
against a flank of {flank:.2}. The eye is in the part map and \
the shade map and it is not on the screen: a braille cell is \
eight dots and one colour, so a pupil smaller than a cell is \
averaged away.",
species.name
);
}
}
}
#[test]
fn a_hostile_species_renders_rather_than_panicking() {
for hostile in [
Species {
length: 0,
girth: 0.0,
peak: 0.0,
blunt: 0.0,
taper: 0.0,
dorsal: &[],
anal: &[],
caudal: (1.0, 0.0, TailFork::Rounded),
markings: Markings::Bars {
count: 0.0,
from: 1.0,
to: 0.0,
strength: 2.0,
},
..SPECIES[0]
},
Species {
length: 4,
girth: f32::NAN,
peak: 1.0,
blunt: -1.0,
taper: f32::INFINITY,
dorsal: &[(0.0, f32::NAN)],
caudal: (0.0, 1e9, TailFork::Forked { depth: 1e9 }),
..SPECIES[0]
},
Species {
markings: Markings::Mottled { amount: 5.0 },
barbels: true,
..SPECIES[0]
},
] {
let fish = rasterise(&hostile, 0);
let (w, h) = (fish.width(), fish.height());
assert!(w > 0 && h > 0);
let _ = fish.cells().count();
let _ = fish.mirrored().cells().count();
let _ = fish.shifted(1, 3).cells().count();
}
}
fn ink_extent(fish: &FishArt) -> (usize, usize, usize, usize) {
let (w, h) = (fish.width(), fish.height());
let (mut x0, mut x1, mut y0, mut y1) = (w, 0usize, h, 0usize);
for y in 0..h {
for x in 0..w {
if fish.dot(x, y) {
x0 = x0.min(x);
x1 = x1.max(x);
y0 = y0.min(y);
y1 = y1.max(y);
}
}
}
(x0, x1, y0, y1)
}
}