use crate::color::Color;
#[derive(Clone, Debug)]
pub struct Palette {
colors: Vec<Color>,
}
impl Palette {
pub fn new(colors: Vec<Color>) -> Self {
assert!(!colors.is_empty(), "palette must have at least one color");
Self { colors }
}
pub fn get(&self, index: usize) -> Color {
self.colors[index % self.colors.len()]
}
pub fn len(&self) -> usize {
self.colors.len()
}
pub fn is_empty(&self) -> bool {
self.colors.is_empty()
}
pub fn tab10() -> Self {
Self::new(vec![
Color::from_rgb8(0x1f, 0x77, 0xb4), Color::from_rgb8(0xff, 0x7f, 0x0e), Color::from_rgb8(0x2c, 0xa0, 0x2c), Color::from_rgb8(0xd6, 0x27, 0x28), Color::from_rgb8(0x94, 0x67, 0xbd), Color::from_rgb8(0x8c, 0x56, 0x4b), Color::from_rgb8(0xe3, 0x77, 0xc2), Color::from_rgb8(0x7f, 0x7f, 0x7f), Color::from_rgb8(0xbc, 0xbd, 0x22), Color::from_rgb8(0x17, 0xbe, 0xcf), ])
}
pub fn sequential(start: Color, end: Color, n: usize) -> Self {
let n = n.max(2);
let colors = (0..n)
.map(|i| start.lerp(end, i as f64 / (n - 1) as f64))
.collect();
Self::new(colors)
}
pub fn viridis() -> Self {
Self::new(vec![
Color::from_rgb8(0x44, 0x01, 0x54), Color::from_rgb8(0x31, 0x68, 0x8e), Color::from_rgb8(0x35, 0xb7, 0x79), Color::from_rgb8(0x90, 0xd7, 0x43), Color::from_rgb8(0xfd, 0xe7, 0x25), ])
}
pub fn rdbu() -> Self {
Self::new(vec![
Color::from_rgb8(0xb2, 0x18, 0x2b), Color::from_rgb8(0xef, 0x8a, 0x62), Color::from_rgb8(0xf7, 0xf7, 0xf7), Color::from_rgb8(0x67, 0xa9, 0xcf), Color::from_rgb8(0x21, 0x66, 0xac), ])
}
pub fn sample(&self, t: f64) -> Color {
let t = t.clamp(0.0, 1.0);
if self.colors.len() == 1 {
return self.colors[0];
}
let max_idx = self.colors.len() - 1;
let scaled = t * max_idx as f64;
let lo = (scaled.floor() as usize).min(max_idx - 1);
let frac = scaled - lo as f64;
self.colors[lo].lerp(self.colors[lo + 1], frac)
}
}
impl Default for Palette {
fn default() -> Self {
Self::tab10()
}
}