use crate::buffer::{Buffer, Cell};
use crate::render::palette::Palette;
use crossterm::style::{self, Color};
pub const PHOSPHOR_RAMP: &[Color] = &[
Color::Rgb { r: 8, g: 32, b: 24 },
Color::Rgb {
r: 16,
g: 88,
b: 54,
},
Color::Rgb {
r: 32,
g: 156,
b: 86,
},
Color::Rgb {
r: 83,
g: 212,
b: 144,
},
Color::Rgb {
r: 165,
g: 235,
b: 188,
},
Color::Rgb {
r: 255,
g: 255,
b: 255,
},
];
pub const FIELD_PALETTES: &[(&str, &[Color])] = &[
("green", PHOSPHOR_RAMP),
(
"orange",
&[
Color::Rgb { r: 26, g: 10, b: 4 },
Color::Rgb { r: 92, g: 32, b: 8 },
Color::Rgb {
r: 196,
g: 84,
b: 12,
},
Color::Rgb {
r: 255,
g: 140,
b: 32,
},
Color::Rgb {
r: 255,
g: 210,
b: 140,
},
Color::Rgb {
r: 255,
g: 255,
b: 255,
},
],
),
(
"blue",
&[
Color::Rgb { r: 4, g: 10, b: 28 },
Color::Rgb {
r: 10,
g: 32,
b: 96,
},
Color::Rgb {
r: 20,
g: 86,
b: 198,
},
Color::Rgb {
r: 60,
g: 150,
b: 255,
},
Color::Rgb {
r: 150,
g: 210,
b: 255,
},
Color::Rgb {
r: 255,
g: 255,
b: 255,
},
],
),
(
"magenta",
&[
Color::Rgb { r: 28, g: 4, b: 26 },
Color::Rgb {
r: 96,
g: 12,
b: 88,
},
Color::Rgb {
r: 198,
g: 30,
b: 180,
},
Color::Rgb {
r: 255,
g: 96,
b: 226,
},
Color::Rgb {
r: 255,
g: 186,
b: 246,
},
Color::Rgb {
r: 255,
g: 255,
b: 255,
},
],
),
(
"ice",
&[
Color::Rgb { r: 8, g: 12, b: 16 },
Color::Rgb {
r: 40,
g: 58,
b: 72,
},
Color::Rgb {
r: 110,
g: 148,
b: 170,
},
Color::Rgb {
r: 180,
g: 214,
b: 230,
},
Color::Rgb {
r: 232,
g: 244,
b: 250,
},
Color::Rgb {
r: 255,
g: 255,
b: 255,
},
],
),
(
"amber",
&[
Color::Rgb { r: 24, g: 14, b: 2 },
Color::Rgb { r: 90, g: 52, b: 4 },
Color::Rgb {
r: 196,
g: 132,
b: 10,
},
Color::Rgb {
r: 255,
g: 192,
b: 44,
},
Color::Rgb {
r: 255,
g: 232,
b: 168,
},
Color::Rgb {
r: 255,
g: 255,
b: 255,
},
],
),
];
pub fn palette_by_name(name: &str) -> Option<&'static [Color]> {
FIELD_PALETTES
.iter()
.find(|(preset, _)| preset.eq_ignore_ascii_case(name))
.map(|(_, stops)| *stops)
}
pub const DEFAULT_PALETTE_NAME: &str = "green";
pub const DEFAULT_GLYPHS: &str = " .:-=+*#%@";
#[derive(Debug, Clone)]
pub struct GlyphPalette {
glyphs: Vec<char>,
colors: Palette,
}
impl Default for GlyphPalette {
fn default() -> Self {
Self {
glyphs: DEFAULT_GLYPHS.chars().collect(),
colors: Palette::new(PHOSPHOR_RAMP.to_vec()),
}
}
}
impl GlyphPalette {
pub fn new(glyphs: &str, colors: Vec<Color>) -> Self {
let glyphs: Vec<char> = glyphs
.chars()
.filter(|glyph| glyph.is_ascii() && !glyph.is_control())
.collect();
let glyphs = if glyphs.is_empty() {
DEFAULT_GLYPHS.chars().collect()
} else {
glyphs
};
let colors = if colors.is_empty() {
Palette::new(PHOSPHOR_RAMP.to_vec())
} else {
Palette::new(colors)
};
Self { glyphs, colors }
}
pub fn colors(&self) -> &[Color] {
self.colors.stops()
}
pub fn glyphs(&self) -> &[char] {
&self.glyphs
}
pub fn sample(&self, value: f32) -> Cell {
let value = if value.is_nan() {
0.0
} else {
value.clamp(0.0, 1.0)
};
let glyphs = self.glyphs.len();
let colors = self.colors.len();
let glyph_index =
((value * (glyphs - 1) as f32).round() as usize).min(glyphs - 1);
let color_index =
((value * (colors - 1) as f32).round() as usize).min(colors - 1);
Cell::new(
self.glyphs[glyph_index],
self.colors.sample_index(color_index),
style::Attribute::Reset,
)
}
}
#[derive(Debug, Clone, Default)]
pub struct AsciiRenderer {
palette: GlyphPalette,
}
impl AsciiRenderer {
pub fn new(palette: GlyphPalette) -> Self {
Self { palette }
}
pub fn palette(&self) -> &GlyphPalette {
&self.palette
}
pub fn render_field(
&self,
values: &[f32],
width: usize,
height: usize,
buffer: &mut Buffer,
) {
let width = width.min(buffer.width);
let height = height.min(buffer.height);
for y in 0..height {
for x in 0..width {
let index = y * width + x;
let value = values.get(index).copied().unwrap_or_default();
buffer.set(x, y, self.palette.sample(value));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::TerminalEffect;
use crate::ink::{AsciiField, AsciiFieldOptions};
use std::collections::HashSet;
#[test]
fn the_brightest_stop_is_white_and_neutral() {
let top = match PHOSPHOR_RAMP.last() {
Some(Color::Rgb { r, g, b }) => (*r, *g, *b),
other => {
panic!("the top of the phosphor ramp is not a truecolor: {other:?}")
}
};
let (r, g, b) = top;
let spread = r.max(g).max(b) - r.min(g).min(b);
assert_eq!(
spread, 0,
"the brightest stop is rgb({r}, {g}, {b}): the channels differ by \
{spread}, which is a {spread:.1}% tint on the whitest colour in the \
effect and is exactly what the user reported",
);
assert!(
r >= 250,
"the brightest stop is rgb({r}, {g}, {b}) at {r}/255, which is not \
white; the field's brightest cells have to reach the top"
);
}
#[test]
fn the_brightest_value_draws_the_brightest_stop() {
let palette = GlyphPalette::default();
let top = palette
.colors()
.last()
.copied()
.expect("the ramp has a top");
let dim = palette.sample(0.0);
assert_eq!(
dim.color,
palette.colors()[0],
"the bottom of the value \
range did not draw the bottom of the ramp"
);
let bright = palette.sample(1.0);
assert_eq!(bright.color, top, "value 1.0 did not draw the top stop");
assert_eq!(
bright.color,
Color::Rgb {
r: 255,
g: 255,
b: 255
},
"the brightest cell is not white"
);
}
#[test]
fn an_empty_colour_list_falls_back_to_the_phosphor_ramp() {
let palette = GlyphPalette::new(DEFAULT_GLYPHS, Vec::new());
assert_eq!(palette.colors(), PHOSPHOR_RAMP);
assert!(
!palette.colors().is_empty(),
"an empty colour list produced a palette that paints nothing"
);
}
#[test]
fn a_single_colour_paints_the_whole_range() {
let palette = GlyphPalette::new(
DEFAULT_GLYPHS,
vec![Color::Rgb {
r: 10,
g: 20,
b: 30,
}],
);
for value in [0.0f32, 0.25, 0.5, 0.74, 1.0] {
assert_eq!(
palette.sample(value).color,
Color::Rgb {
r: 10,
g: 20,
b: 30
},
"value {value} did not draw the single configured colour"
);
}
}
#[test]
fn a_monochrome_palette_still_shades_by_glyph() {
let palette = GlyphPalette::new(
DEFAULT_GLYPHS,
vec![Color::Rgb {
r: 255,
g: 255,
b: 255,
}],
);
let dim = palette.sample(0.0).symbol;
let bright = palette.sample(1.0).symbol;
assert_ne!(dim, bright, "the glyph does not vary with the value");
}
#[test]
fn no_value_is_asked_to_be_bold() {
let palette = GlyphPalette::default();
for step in 0..=100 {
let value = step as f32 / 100.0;
let cell = palette.sample(value);
assert_eq!(
cell.attr,
style::Attribute::Reset,
"value {value:.2} drew {cell:?}, asking the terminal to brighten \
a colour the ramp has already placed"
);
}
}
#[test]
fn every_named_palette_ends_on_exactly_white() {
assert!(
FIELD_PALETTES.len() >= 2,
"the named palettes are a table with {} entries, so this test is \
checking the default and nothing else",
FIELD_PALETTES.len()
);
for (name, stops) in FIELD_PALETTES {
let top = stops.last().unwrap_or_else(|| {
panic!("the {name} palette is empty, so it paints nothing")
});
assert_eq!(
top,
&Color::Rgb {
r: 255,
g: 255,
b: 255
},
"the {name} palette's brightest stop is {top:?}, which is not pure \
white. This is the bug the user reported twice: a tinted top \
stop reads as a colour cast over the brightest part of the field."
);
}
}
#[test]
fn every_named_palette_is_monotone_in_luminance() {
for (name, stops) in FIELD_PALETTES {
let luma = |color: &Color| -> f64 {
let Color::Rgb { r, g, b } = *color else {
panic!(
"the {name} palette contains {color:?}, which has no \
channels to measure"
)
};
0.299 * f64::from(r) + 0.587 * f64::from(g) + 0.114 * f64::from(b)
};
assert!(
stops.len() >= 3,
"the {name} palette has {} stops, which is a boundary rather than \
a ramp",
stops.len()
);
let mut previous = -1.0;
for (index, stop) in stops.iter().enumerate() {
let here = luma(stop);
assert!(
here >= previous,
"the {name} palette goes dark again at stop {index}: \
{previous:.1} then {here:.1} in luma, so a brighter value \
paints a darker cell"
);
previous = here;
}
}
}
#[test]
fn a_named_palette_paints_the_screen_and_leaves_the_glyphs_alone() {
let mut green = AsciiField::new(AsciiFieldOptions::default(), (120, 40));
let mut orange_field = AsciiField::new(
AsciiFieldOptions {
palette: "orange".to_string(),
..Default::default()
},
(120, 40),
);
let orange = palette_by_name("orange").expect("orange is in the table");
let green_diff = green.get_diff();
let orange_diff = orange_field.get_diff();
assert!(
green_diff.len() == orange_diff.len(),
"the two fields drew {} and {} cells of a 120x40 screen",
green_diff.len(),
orange_diff.len()
);
let green_colors: Vec<Color> =
green_diff.iter().map(|(_, _, cell)| cell.color).collect();
let orange_colors: Vec<Color> =
orange_diff.iter().map(|(_, _, cell)| cell.color).collect();
let green_glyphs: Vec<char> =
green_diff.iter().map(|(_, _, cell)| cell.symbol).collect();
let orange_glyphs: Vec<char> =
orange_diff.iter().map(|(_, _, cell)| cell.symbol).collect();
assert_eq!(
green_glyphs, orange_glyphs,
"changing the palette changed the characters as well"
);
assert_ne!(
green_colors, orange_colors,
"palette = \"orange\" painted the same colours as the default, so the \
name is being parsed and not used"
);
for (index, color) in orange
.iter()
.enumerate()
.take(orange.len().saturating_sub(1))
{
let Color::Rgb { r, g, b } = *color else {
panic!("the orange palette contains {color:?}")
};
assert!(
r > g && g > b,
"orange stop {index} is rgb({r}, {g}, {b}), which is not a warm \
hue: orange is red above green above blue"
);
}
}
#[test]
fn every_named_palettes_brightest_value_paints_its_white() {
for (name, stops) in FIELD_PALETTES {
let palette = GlyphPalette::new(DEFAULT_GLYPHS, stops.to_vec());
assert_eq!(
palette.sample(1.0).color,
Color::Rgb {
r: 255,
g: 255,
b: 255
},
"the {name} palette's value 1.0 did not paint white, so either the \
table's top stop is not what this test thinks it is or the \
sampler is reading the ramp upside down"
);
assert_eq!(
palette.sample(0.0).color,
stops[0],
"the {name} palette's value 0.0 did not paint its darkest stop"
);
}
}
#[test]
fn an_unknown_palette_name_falls_back_rather_than_drawing_nothing() {
for name in ["", "ornage", "grn", "puce", " ", "green ", "ORANGE!"] {
let options = AsciiFieldOptions {
palette: name.to_string(),
..Default::default()
};
let mut field = AsciiField::new(options.clone(), (60, 20));
let diff = field.get_diff();
assert_eq!(
diff.len(),
60 * 20,
"palette = {name:?} drew {} cells of a 60x20 field",
diff.len()
);
let colors: HashSet<Color> =
diff.iter().map(|(_, _, cell)| cell.color).collect();
assert!(
colors.contains(&Color::Rgb {
r: 255,
g: 255,
b: 255
}),
"palette = {name:?} painted {colors:?} and not one of them is \
white, so it did not fall back to the default ramp"
);
}
let mut field = AsciiField::new(
AsciiFieldOptions {
palette: "OrAnGe".to_string(),
..Default::default()
},
(60, 20),
);
let colors: HashSet<Color> = field
.get_diff()
.iter()
.map(|(_, _, cell)| cell.color)
.collect();
let orange = palette_by_name("orange").expect("orange is in the table");
assert!(
colors.iter().all(|color| orange.contains(color)),
"palette = \"OrAnGe\" painted {colors:?}, which is not the orange \
ramp, so the name lookup is case-sensitive"
);
}
#[test]
fn the_named_palette_round_trips_through_toml() {
let config: AsciiFieldOptions =
toml::from_str("palette = \"orange\"\n").expect("a lone key parses");
assert_eq!(
config.palette, "orange",
"the key was not read back, so a config file could not ask for a \
palette by name at all"
);
assert_eq!(
config.colors,
AsciiFieldOptions::default().colors,
"one key in the section silently reset the others"
);
let serialised = toml::to_string(&config).expect("the section serialises");
assert!(
serialised.contains("palette"),
"the key is missing from the serialised form, so --print-config would \
never write it: {serialised}"
);
}
#[test]
fn the_default_named_palette_is_the_phosphor_ramp() {
let named = palette_by_name(DEFAULT_PALETTE_NAME)
.expect("the default palette is in the table");
assert_eq!(
named, PHOSPHOR_RAMP,
"palette = {DEFAULT_PALETTE_NAME:?} is not the ramp this effect has \
always used, so every existing config changes appearance"
);
assert_eq!(
AsciiFieldOptions::default().colors,
PHOSPHOR_RAMP.to_vec(),
"the default `colors` is not the phosphor ramp either, so the two \
knobs disagree about what the default is"
);
}
#[test]
fn the_palette_name_wins_over_a_configured_colour_list() {
let listed = Color::Rgb {
r: 200,
g: 100,
b: 50,
};
let options = AsciiFieldOptions {
palette: "blue".to_string(),
colors: vec![listed],
..Default::default()
};
let mut field = AsciiField::new(options.clone(), (40, 12));
let colors: HashSet<Color> = field
.get_diff()
.iter()
.map(|(_, _, cell)| cell.color)
.collect();
let blue = palette_by_name("blue").expect("blue is in the table");
assert!(
colors.iter().all(|color| blue.contains(color)) && colors.len() > 1,
"palette = \"blue\" alongside a `colors` list painted {colors:?}, so \
the two knobs are not resolving to a single answer"
);
let mut listed_only = AsciiField::new(
AsciiFieldOptions {
palette: String::new(),
..options
},
(40, 12),
);
let colors: HashSet<Color> = listed_only
.get_diff()
.iter()
.map(|(_, _, cell)| cell.color)
.collect();
assert_eq!(
colors,
HashSet::from([listed]),
"setting palette = \"\" did not go back to the `colors` list, so the \
documented escape hatch does not work"
);
}
#[test]
fn cycling_the_glyph_set_keeps_the_named_palette() {
let mut field = AsciiField::new(
AsciiFieldOptions {
palette: "magenta".to_string(),
..Default::default()
},
(40, 12),
);
let magenta = palette_by_name("magenta").expect("magenta is in the table");
for _ in 0..6 {
field.handle_input(&crate::runtime::InputEvent::Key {
key: crate::runtime::Key::Char(']'),
phase: crate::runtime::KeyPhase::Pressed,
});
let colors: HashSet<Color> = field
.get_diff()
.iter()
.map(|(_, _, cell)| cell.color)
.collect();
assert!(
colors.iter().all(|color| magenta.contains(color)),
"after cycling to glyph set {} the field painted {colors:?}, so the \
named palette was dropped by the palette switch",
field.glyph_set_index()
);
}
}
#[test]
fn every_named_palette_is_findable_and_distinct() {
let names: Vec<&str> =
FIELD_PALETTES.iter().map(|(name, _)| *name).collect();
for expected in ["green", "orange", "blue", "magenta", "ice", "amber"] {
assert!(
names.contains(&expected),
"the {expected:?} palette is missing; the names are {names:?}"
);
}
assert_eq!(
names.len(),
FIELD_PALETTES.len(),
"the same name is in the table twice: {names:?}"
);
for (index, (name, stops)) in FIELD_PALETTES.iter().enumerate() {
for (other_name, other) in &FIELD_PALETTES[index + 1..] {
assert_ne!(
stops, other,
"{name} and {other_name} are the same ramp, so one of them is \
a duplicate"
);
}
}
}
#[test]
fn an_unusable_value_saturates_rather_than_panicking() {
let palette = GlyphPalette::default();
let dim = palette.sample(0.0);
let bright = palette.sample(1.0);
for value in [-1.0f32, 2.0, 1.0e9, f32::INFINITY, f32::NAN] {
let cell = palette.sample(value);
assert!(
cell.color == dim.color || cell.color == bright.color,
"value {value} produced {:?}, which is not an endpoint of the ramp",
cell.color
);
}
}
}