use crate::buffer::Cell;
use crate::canvas::Canvas;
use crossterm::style::{Attribute, Color};
pub const POSES: usize = 3;
const BODY_TOP: f32 = 0.78;
const BODY_BOT: f32 = 0.20;
pub const EYE: f32 = 0.03;
const MOUTH: f32 = 0.34;
const BARBEL: f32 = 0.18;
const EYE_CHARS: [char; 5] = ['o', 'O', '@', '0', '©'];
const MOUTH_CHARS: [char; 2] = ['<', '>'];
const BARBEL_CHARS: [char; 2] = ['v', 'V'];
#[cfg(test)]
const STROKES: [char; 9] = ['/', '\\', '|', '-', '_', ',', '\'', '`', '.'];
pub struct CharArt {
frames: Vec<Vec<Vec<char>>>,
width: usize,
height: usize,
}
impl CharArt {
pub fn new(frames: Vec<Vec<Vec<char>>>) -> Self {
assert_eq!(
frames.len(),
POSES,
"a species has {POSES} frames, one per point of the tail beat",
);
let width = frames[0][0].len();
let height = frames[0].len();
for (pose, frame) in frames.iter().enumerate() {
assert_eq!(
frame.len(),
height,
"pose {pose} has {} rows and pose 0 has {height}",
frame.len(),
);
for (row, line) in frame.iter().enumerate() {
assert_eq!(
line.len(),
width,
"pose {pose} row {row} is {} characters wide and the sprite is \
{width}",
line.len(),
);
}
}
Self {
frames,
width,
height,
}
}
pub fn cells_wide(&self) -> usize {
self.width
}
pub fn cells_tall(&self) -> usize {
self.height
}
pub fn cells(
&self,
pose: usize,
) -> impl Iterator<Item = (i32, i32, char, f32)> + '_ {
let pose = pose % POSES;
(0..self.height).flat_map(move |y| {
(0..self.width).filter_map(move |x| {
let ch = self.frames[pose][y][x];
if ch == ' ' {
return None;
}
Some((x as i32, y as i32, ch, Self::shade_of(ch, y, self.height)))
})
})
}
pub fn mirrored(&self) -> CharArt {
CharArt {
frames: self
.frames
.iter()
.map(|frame| {
frame
.iter()
.map(|line| line.iter().rev().copied().collect())
.collect()
})
.collect(),
width: self.width,
height: self.height,
}
}
pub fn blit(
&self,
canvas: &mut Canvas,
pose: usize,
left: i32,
top: i32,
ramp: &dyn Fn(f32) -> Color,
bg_of: &dyn Fn(usize) -> Color,
) {
for (x, y, ch, shade) in self.cells(pose) {
let (sx, sy) = (left + x, top + y);
if sx < 0 || sy < 0 {
continue;
}
let (sx, sy) = (sx as usize, sy as usize);
if sx >= canvas.width() || sy >= canvas.height() {
continue;
}
canvas.set(
sx,
sy,
Cell::with_bg(ch, ramp(shade), bg_of(sy), Attribute::Reset),
);
}
}
fn shade_of(ch: char, y: usize, height: usize) -> f32 {
if EYE_CHARS.contains(&ch) {
return EYE;
}
if MOUTH_CHARS.contains(&ch) {
return MOUTH;
}
if BARBEL_CHARS.contains(&ch) {
return BARBEL;
}
let t = if height <= 1 {
0.0
} else {
y as f32 / (height - 1) as f32
};
BODY_TOP + (BODY_BOT - BODY_TOP) * t
}
}
#[derive(Debug, Clone, Copy)]
pub struct CharSpecies {
pub name: &'static str,
pub frames: [&'static [&'static str]; POSES],
pub depth: f32,
pub chroma: f32,
pub color: Color,
pub cruise: f32,
}
pub fn species(entry: &CharSpecies) -> CharArt {
let frames = &entry.frames;
let frames: Vec<Vec<Vec<char>>> = frames
.iter()
.map(|frame| {
let width = frame.iter().map(|r| r.chars().count()).max().unwrap_or(0);
frame
.iter()
.map(|row| {
let mut line: Vec<char> = row.chars().collect();
line.resize(width, ' ');
line
})
.collect()
})
.collect();
CharArt::new(frames)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aquarium::art::CHAR_SPECIES;
fn all() -> Vec<(&'static str, CharArt)> {
CHAR_SPECIES.iter().map(|e| (e.name, species(e))).collect()
}
#[test]
fn the_table_is_rectangular() {
for e in CHAR_SPECIES {
let w = e.frames[0][0].chars().count();
let h = e.frames[0].len();
for (f, frame) in e.frames.iter().enumerate() {
assert_eq!(
frame.len(),
h,
"{}: frame {f} has {} rows and frame 0 has {h}",
e.name,
frame.len()
);
for (r, row) in frame.iter().enumerate() {
assert_eq!(
row.chars().count(),
w,
"{}: frame {f} row {r} is {} characters wide and the sprite is {w}",
e.name,
row.chars().count()
);
}
}
}
}
#[test]
fn a_character_fish_is_drawn_and_not_stamped() {
for (name, a) in all() {
for pose in 0..POSES {
let (x0, x1, y0, y1) = ink_extent(&a, pose);
let (bw, bh) = (x1 - x0 + 1, y1 - y0 + 1);
let ink = count_ink(&a, pose);
let fill = ink as f32 / (bw * bh) as f32;
assert!(
fill < 0.85,
"{name} pose {pose} fills {:.0}% of its own {bw}x{bh} box. A \
character fish is a drawing; a stamped one is nearly solid.",
fill * 100.0
);
let glyphs: std::collections::BTreeSet<char> =
glyph_list(&a, pose).into_iter().collect();
assert!(
glyphs.len() >= 6,
"{name} pose {pose} is drawn from {glyphs:?} -- {n} distinct \
glyphs. That is a stamp.",
n = glyphs.len()
);
let strokes: std::collections::BTreeSet<char> = glyphs
.iter()
.filter(|c| STROKES.contains(*c))
.copied()
.collect();
assert!(
strokes.len() >= 4,
"{name} pose {pose} draws its contour from {strokes:?}, which is \
not a contour."
);
}
}
}
#[test]
fn a_fish_leaves_holes_in_its_own_bounding_box() {
for (name, a) in all() {
for pose in 0..POSES {
let (x0, x1, y0, y1) = ink_extent(&a, pose);
let cells = (x1 - x0 + 1) * (y1 - y0 + 1);
let ink = count_ink(&a, pose);
let holes = cells - ink;
assert!(
holes > 0,
"{name} pose {pose} fills every one of the {} cells in its own \
bounding box. That is a stamp.",
cells
);
let interior: usize = (y0..=y1)
.map(|y| {
(x0..=x1)
.filter(|x| cell_at(&a, pose, *x, y).is_none())
.count()
})
.sum();
assert!(
interior > cells / 8,
"{name} pose {pose} has {interior} gaps in its {cells}-cell box, \
which is a padded edge rather than a shape."
);
}
}
}
#[test]
fn the_frames_differ_only_in_the_tail() {
for (name, a) in all() {
let tail_start = a.cells_wide() * 2 / 3;
for pose in 0..POSES - 1 {
let mut differs = false;
for y in 0..a.cells_tall() {
for x in 0..a.cells_wide() {
if cell_at(&a, pose, x, y) == cell_at(&a, pose + 1, x, y) {
continue;
}
differs = true;
assert!(
x >= tail_start,
"{name}: frames {pose} and {} differ at column {x}, in front \
of the tail third of {tail_start}. A fish whose head \
changes between frames reads as twitching.",
pose + 1
);
}
}
assert!(
differs,
"{name}: frames {pose} and {} are identical",
pose + 1
);
}
}
}
#[test]
fn every_frame_has_the_same_head() {
for (name, a) in all() {
let tail_start = a.cells_wide() * 2 / 3;
for pose in 1..POSES {
for y in 0..a.cells_tall() {
for x in 0..tail_start {
assert_eq!(
cell_at(&a, 0, x, y),
cell_at(&a, pose, x, y),
"{name}: frame {pose} differs from frame 0 at ({x},{y}), \
which is the head. A hand-aligned frame that loses the \
eye still passes the tail-only test."
);
}
}
}
}
}
#[test]
fn there_is_an_eye_and_it_is_toward_the_front() {
for (name, a) in all() {
for pose in 0..POSES {
let ex = leftmost_eye(&a, pose).unwrap_or_else(|| {
panic!("{name} pose {pose} has no eye at all")
});
assert!(
ex < a.cells_wide() * 2 / 3,
"{name} pose {pose}: the eye is at column {ex} of {}, which is the \
tail end. A fish with its eye at the tail is a fish drawn \
backwards.",
a.cells_wide()
);
}
}
}
#[test]
fn the_body_is_lit_from_above() {
for (name, a) in all() {
for pose in 0..POSES {
let per_row: Vec<Option<f32>> = (0..a.cells_tall())
.map(|y| {
let v: Vec<f32> = (0..a.cells_wide())
.filter_map(|x| cell_at(&a, pose, x, y).map(|(_, s)| s))
.filter(|s| *s >= BODY_BOT && *s <= BODY_TOP)
.collect();
if v.is_empty() {
None
} else {
Some(v.iter().sum::<f32>() / v.len() as f32)
}
})
.collect();
let lit = per_row.iter().filter(|m| m.is_some()).count();
assert!(
lit * 2 >= a.cells_tall(),
"{name} pose {pose} has body in {lit} of {} rows; there is little \
to light",
a.cells_tall()
);
let last =
per_row.iter().flatten().copied().fold(f32::MAX, f32::min);
let first =
per_row.iter().flatten().copied().fold(f32::MIN, f32::max);
assert!(
first > last,
"{name} pose {pose}: the ramp does not vary at all across the body"
);
for w in per_row.windows(2) {
if let (Some(above), Some(below)) = (w[0], w[1]) {
assert!(
below <= above + 1e-6,
"{name} pose {pose}: a lower row is lighter ({below:.2}) \
than the one above it ({above:.2}). This tank is lit \
from above."
);
}
}
}
}
}
#[test]
fn a_mirrored_fish_faces_the_other_way_and_keeps_its_eye_toward_the_front() {
for (name, a) in all() {
let m = a.mirrored();
for pose in 0..POSES {
for y in 0..a.cells_tall() {
for x in 0..a.cells_wide() {
assert_eq!(
cell_at(&a, pose, x, y),
cell_at(&m, pose, a.cells_wide() - 1 - x, y),
"{name}: pose {pose} row {y} is not mirrored at column {x}"
);
}
}
let before =
leftmost_eye(&a, pose).expect("the drawing lost its eye");
let want = a.cells_wide() - 1 - before;
let row = (0..a.cells_tall())
.find(|y| {
cell_at(&a, pose, before, *y)
.map(|(_, s)| s == EYE)
.unwrap_or(false)
})
.unwrap_or_else(|| {
panic!("{name}: the eye column has no eye on it")
});
assert_eq!(
cell_at(&m, pose, want, row).map(|(_, s)| s),
Some(EYE),
"{name}: the eye at column {before} should mirror to {want} and did \
not. The rows came round but the columns did not."
);
assert!(
want >= a.cells_wide() / 3,
"{name}: after mirroring, the eye is at column {want} of {} -- \
still at the snout.",
a.cells_wide()
);
}
}
}
#[test]
fn no_glyph_is_wider_than_one_cell() {
for (name, a) in all() {
for pose in 0..POSES {
for (x, y, ch, _) in a.cells(pose) {
assert!(
(ch as u32) < 0x100,
"{name} pose {pose} has a multi-byte glyph {ch:?} at ({x},{y})"
);
}
}
}
}
#[test]
#[should_panic(expected = "rows")]
fn a_sprite_with_a_missing_row_is_rejected() {
let mut frames = vec![vec![vec!['x'; 4], vec!['x'; 4]]; POSES];
frames[1].pop();
CharArt::new(frames);
}
#[test]
#[should_panic(expected = "wide")]
fn a_sprite_with_a_ragged_row_is_rejected() {
let mut frames = vec![vec![vec!['x'; 4], vec!['x'; 4]]; POSES];
frames[2] = vec![vec!['x'; 4], vec!['x'; 3]];
CharArt::new(frames);
}
#[test]
#[should_panic(expected = "frames")]
fn a_sprite_with_the_wrong_frame_count_is_rejected() {
CharArt::new(vec![vec![vec!['x'; 4]], vec![vec!['x'; 4]]]);
}
#[test]
fn a_wing_trails_behind_its_head_rather_than_standing_on_it() {
const DORSAL: &[&str] = &["longfin", "bigeye", "stipple"];
for (name, art) in all() {
if !DORSAL.contains(&name) {
continue;
}
let eye = leftmost_eye(&art, 0).unwrap_or_else(|| {
panic!("{name}: has no eye, so this test has no head to compare the wing against")
});
let (top_row, wing_start) = (0..art.cells_tall())
.filter_map(|y| {
(0..art.cells_wide())
.find(|&x| {
cell_at(&art, 0, x, y)
.map(|(g, _)| g != ' ')
.unwrap_or(false)
})
.map(|x| (y, x))
})
.min_by_key(|&(y, _)| y)
.unwrap_or_else(|| panic!("{name}: draws nothing at all"));
assert!(
wing_start > eye,
"{name}: its topmost ink is at row {top_row}, column {wing_start}, and \
its eye is at column {eye}. The fin starts at or ahead of the eye, \
so it stands on the head instead of trailing back from it."
);
}
}
fn leftmost_eye(a: &CharArt, pose: usize) -> Option<usize> {
(0..a.cells_wide()).find(|x| {
(0..a.cells_tall()).any(|y| {
cell_at(a, pose, *x, y)
.map(|(_, shade)| shade == EYE)
.unwrap_or(false)
})
})
}
fn cell_at(
a: &CharArt,
pose: usize,
x: usize,
y: usize,
) -> Option<(char, f32)> {
a.cells(pose)
.find(|(cx, cy, _, _)| *cx == x as i32 && *cy == y as i32)
.map(|(_, _, ch, s)| (ch, s))
}
fn glyph_list(a: &CharArt, pose: usize) -> Vec<char> {
a.cells(pose).map(|(_, _, ch, _)| ch).collect()
}
fn count_ink(a: &CharArt, pose: usize) -> usize {
a.cells(pose).count()
}
fn ink_extent(a: &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)
}
}