1use egui::Color32;
11use facett_core::Theme;
12
13#[derive(Clone, Copy, Debug)]
16pub struct Ramp {
17 stops: [Color32; 3],
19}
20
21impl Ramp {
22 pub fn sequential(th: &Theme) -> Self {
25 let low = lerp_color(th.bg, th.accent, 0.25);
28 Self { stops: [low, th.accent, th.glow] }
29 }
30
31 pub fn diverging(th: &Theme) -> Self {
34 Self { stops: [th.accent, th.text_dim, th.glow] }
35 }
36
37 pub fn at(&self, t: f32) -> Color32 {
39 let t = t.clamp(0.0, 1.0);
40 if t <= 0.5 {
41 lerp_color(self.stops[0], self.stops[1], t * 2.0)
42 } else {
43 lerp_color(self.stops[1], self.stops[2], (t - 0.5) * 2.0)
44 }
45 }
46
47 pub fn stops(&self) -> [Color32; 3] {
49 self.stops
50 }
51}
52
53pub use facett_core::look::color::lerp_color;
56
57pub fn normalize(v: f64, min: f64, max: f64) -> f32 {
60 if max.is_nan() || min.is_nan() || max <= min {
61 return 0.5;
62 }
63 (((v - min) / (max - min)) as f32).clamp(0.0, 1.0)
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn lerp_endpoints_and_mid() {
72 let a = Color32::from_rgb(0, 0, 0);
73 let b = Color32::from_rgb(100, 200, 50);
74 assert_eq!(lerp_color(a, b, 0.0), a);
75 assert_eq!(lerp_color(a, b, 1.0), b);
76 let m = lerp_color(a, b, 0.5);
77 assert_eq!((m.r(), m.g(), m.b()), (50, 100, 25));
78 }
79
80 #[test]
81 fn ramp_hits_its_stops() {
82 let r = Ramp::sequential(&Theme::default());
83 let [lo, mid, hi] = r.stops();
84 assert_eq!(r.at(0.0), lo);
85 assert_eq!(r.at(0.5), mid);
86 assert_eq!(r.at(1.0), hi);
87 }
88
89 #[test]
90 fn ramp_clamps_out_of_range() {
91 let r = Ramp::diverging(&Theme::sci_fi());
92 assert_eq!(r.at(-3.0), r.at(0.0));
93 assert_eq!(r.at(9.0), r.at(1.0));
94 }
95
96 #[test]
97 fn normalize_handles_degenerate_range() {
98 assert_eq!(normalize(5.0, 5.0, 5.0), 0.5);
99 assert_eq!(normalize(0.0, 0.0, 10.0), 0.0);
100 assert_eq!(normalize(10.0, 0.0, 10.0), 1.0);
101 assert_eq!(normalize(2.5, 0.0, 10.0), 0.25);
102 assert_eq!(normalize(-1.0, 0.0, 10.0), 0.0);
104 assert_eq!(normalize(99.0, 0.0, 10.0), 1.0);
105 }
106}