Skip to main content

egui_pop_core/slider/
gradient.rs

1//! A slider's gradient track: colours along the bar, so the bar shows
2//! what its value does (a hue, a white balance's temperature).
3//!
4//! The colours are the content, not the theme's: they are drawn as a
5//! strip along the bottom of the bar, under the thumb, and the label and
6//! the value stay on the track's colour.
7
8use egui::epaint::{Mesh, Shape};
9use egui::{Color32, Painter, Rect, pos2};
10
11/// Colours at places along the bar, from 0 (the soft start) to 1 (its
12/// end), blended in between.
13///
14/// ```
15/// use egui::Color32;
16/// use egui_pop_core::slider::Gradient;
17///
18/// let g = Gradient::new([(0.0, Color32::BLACK), (1.0, Color32::WHITE)]);
19/// assert_eq!(g.color_at(0.5), Color32::from_gray(128));
20/// assert_eq!(Gradient::hue().color_at(0.0), Gradient::hue().color_at(1.0));
21/// ```
22#[derive(Clone, Debug, PartialEq)]
23pub struct Gradient {
24    stops: Vec<(f32, Color32)>,
25}
26
27impl Gradient {
28    /// From stops `(place, colour)`, places in `[0, 1]` (sorted here; the
29    /// first and last colours run to the ends).
30    pub fn new(stops: impl IntoIterator<Item = (f32, Color32)>) -> Self {
31        let mut stops: Vec<(f32, Color32)> = stops
32            .into_iter()
33            .filter(|(at, _)| at.is_finite())
34            .map(|(at, c)| (at.clamp(0.0, 1.0), c))
35            .collect();
36        stops.sort_by(|a, b| a.0.total_cmp(&b.0));
37        if stops.is_empty() {
38            stops.push((0.0, Color32::TRANSPARENT));
39        }
40        if let Some(&(at, c)) = stops.first()
41            && at > 0.0
42        {
43            stops.insert(0, (0.0, c));
44        }
45        if let Some(&(at, c)) = stops.last()
46            && at < 1.0
47        {
48            stops.push((1.0, c));
49        }
50        Self { stops }
51    }
52
53    /// Colours spread evenly along the bar.
54    pub fn even(colors: &[Color32]) -> Self {
55        let last = colors.len().saturating_sub(1).max(1) as f32;
56        Self::new(
57            colors
58                .iter()
59                .enumerate()
60                .map(|(i, c)| (i as f32 / last, *c)),
61        )
62    }
63
64    /// `samples` colours of `f` over `[0, 1]` (at least two).
65    pub fn sampled(samples: usize, f: impl Fn(f32) -> Color32) -> Self {
66        let n = samples.max(2);
67        Self::new((0..n).map(|i| {
68            let at = i as f32 / (n - 1) as f32;
69            (at, f(at))
70        }))
71    }
72
73    /// The hue circle, red to red: for a hue in degrees over `0..=360`.
74    pub fn hue() -> Self {
75        Self::sampled(13, |at| {
76            egui::ecolor::Hsva::new(at.rem_euclid(1.0), 0.75, 0.9, 1.0).into()
77        })
78    }
79
80    /// The colour of light from `from` to `to` kelvin (a white balance's
81    /// illuminant: warm at low temperatures, blue at high ones), linear
82    /// in kelvin. [`Gradient::reversed`] shows the correction instead.
83    pub fn temperature(from: f32, to: f32) -> Self {
84        Self::sampled(16, |at| kelvin(from + (to - from) * at))
85    }
86
87    /// The same colours from the other end.
88    pub fn reversed(mut self) -> Self {
89        self.stops.reverse();
90        for s in &mut self.stops {
91            s.0 = 1.0 - s.0;
92        }
93        self
94    }
95
96    /// The colour at a place along the bar.
97    pub fn color_at(&self, at: f32) -> Color32 {
98        let at = at.clamp(0.0, 1.0);
99        let next = self
100            .stops
101            .iter()
102            .position(|(p, _)| *p >= at)
103            .unwrap_or(self.stops.len() - 1);
104        if next == 0 {
105            return self.stops[0].1;
106        }
107        let (a, ca) = self.stops[next - 1];
108        let (b, cb) = self.stops[next];
109        let t = if b > a { (at - a) / (b - a) } else { 1.0 };
110        lerp(ca, cb, t)
111    }
112
113    /// Paints the gradient over `rect`, left to right.
114    pub(crate) fn paint(&self, painter: &Painter, rect: Rect) {
115        let mut mesh = Mesh::default();
116        for (i, (at, c)) in self.stops.iter().enumerate() {
117            let x = rect.left() + rect.width() * at;
118            mesh.colored_vertex(pos2(x, rect.top()), *c);
119            mesh.colored_vertex(pos2(x, rect.bottom()), *c);
120            if i > 0 {
121                let b = 2 * i as u32;
122                mesh.add_triangle(b - 2, b - 1, b);
123                mesh.add_triangle(b - 1, b, b + 1);
124            }
125        }
126        painter.add(Shape::mesh(mesh));
127    }
128
129    /// Paints the gradient over `rect`, bottom to top (a vertical bar's).
130    pub(crate) fn paint_vertical(&self, painter: &Painter, rect: Rect) {
131        let mut mesh = Mesh::default();
132        for (i, (at, c)) in self.stops.iter().enumerate() {
133            let y = rect.bottom() - rect.height() * at;
134            mesh.colored_vertex(pos2(rect.left(), y), *c);
135            mesh.colored_vertex(pos2(rect.right(), y), *c);
136            if i > 0 {
137                let b = 2 * i as u32;
138                mesh.add_triangle(b - 2, b - 1, b);
139                mesh.add_triangle(b - 1, b, b + 1);
140            }
141        }
142        painter.add(Shape::mesh(mesh));
143    }
144}
145
146fn lerp(a: Color32, b: Color32, t: f32) -> Color32 {
147    let l = |x: u8, y: u8| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8;
148    Color32::from_rgba_premultiplied(
149        l(a.r(), b.r()),
150        l(a.g(), b.g()),
151        l(a.b(), b.b()),
152        l(a.a(), b.a()),
153    )
154}
155
156/// The sRGB colour of a black body at `k` kelvin, normalised to its
157/// brightest channel: a fit of the Planckian locus good to a few percent
158/// from 1000 K to 40 000 K, enough for a track.
159fn kelvin(k: f32) -> Color32 {
160    let t = (k.clamp(1000.0, 40_000.0)) / 100.0;
161    let red = if t <= 66.0 {
162        255.0
163    } else {
164        329.7 * (t - 60.0).powf(-0.1332)
165    };
166    let green = if t <= 66.0 {
167        99.47 * t.ln() - 161.12
168    } else {
169        288.12 * (t - 60.0).powf(-0.0755)
170    };
171    let blue = if t >= 66.0 {
172        255.0
173    } else if t <= 19.0 {
174        0.0
175    } else {
176        138.52 * (t - 10.0).ln() - 305.04
177    };
178    let c = |v: f32| v.clamp(0.0, 255.0).round() as u8;
179    Color32::from_rgb(c(red), c(green), c(blue))
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn stops_are_sorted_and_run_to_the_ends() {
188        let g = Gradient::new([(0.75, Color32::WHITE), (0.25, Color32::BLACK)]);
189        assert_eq!(g.color_at(0.0), Color32::BLACK);
190        assert_eq!(g.color_at(1.0), Color32::WHITE);
191        assert_eq!(g.color_at(0.5), Color32::from_gray(128));
192        let r = g.reversed();
193        assert_eq!(r.color_at(0.0), Color32::WHITE);
194    }
195
196    #[test]
197    fn temperature_is_warm_then_blue() {
198        let g = Gradient::temperature(2000.0, 12_000.0);
199        let (warm, cold) = (g.color_at(0.0), g.color_at(1.0));
200        assert!(warm.r() > warm.b(), "{warm:?}");
201        assert!(cold.b() > cold.r(), "{cold:?}");
202        assert_eq!(kelvin(6600.0).r(), 255);
203    }
204}