Skip to main content

clairlune_render/
palette.rs

1//! The indexed palette of one rendering (at most 255 colours).
2//!
3//! Layout (by construction, so every pixel lands on an entry):
4//!
5//! | Indices | Entries |
6//! |---|---|
7//! | 0-7 | background bands (vignette 0-3, warm glow 4-7) |
8//! | 8-55 | ink: band x 6 levels (ink in glow bands is tinted toward the accent) |
9//! | 56-103 | ember particles: band x 6 levels |
10//! | 104.. | sprite colours |
11//! | 255 | reserved (GIF transparency) |
12
13use clairlune_scene::graph::BANDS;
14use clairlune_scene::graph::SpriteKind;
15use clairlune_scene::{PaletteFamily, Rgb};
16
17/// Ink levels per band (glyph alpha x shade, quantised).
18pub const LEVELS: u8 = 6;
19pub const INK_BASE: u8 = BANDS;
20pub const EMBER_BASE: u8 = INK_BASE + BANDS * LEVELS;
21pub const SPRITE_BASE: u8 = EMBER_BASE + BANDS * LEVELS;
22/// Reserved for GIF transparency; never used by a rendered pixel.
23pub const TRANSPARENT_INDEX: u8 = 255;
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct IndexedPalette {
27    colors: Vec<Rgb>,
28}
29
30impl IndexedPalette {
31    /// A palette from stored colours (scene packages), in the layout `new`
32    /// produces.
33    pub fn from_colors(colors: Vec<Rgb>) -> Self {
34        IndexedPalette { colors }
35    }
36
37    /// The palette a scene graph renders with: generator 4 and later give
38    /// light scenes a stronger ink ramp (below); everything else keeps the
39    /// original, linear one.
40    pub fn for_graph(graph: &clairlune_scene::SceneGraph) -> Self {
41        let strong = graph.generator >= 4 && graph.family.theme == clairlune_scene::Theme::Light;
42        Self::with_ramp(&graph.family, strong)
43    }
44
45    /// The original palette: ink levels blend linearly from background to
46    /// ink.
47    pub fn new(family: &PaletteFamily) -> Self {
48        Self::with_ramp(family, false)
49    }
50
51    /// With `strong`, ink levels follow `1 - (1 - l/6)^1.8`: thin strokes and
52    /// faint far layers come out about twice as dark, so ASCII on a light
53    /// background reads as clearly as light strokes on a dark one. Full ink
54    /// stays full ink.
55    fn with_ramp(family: &PaletteFamily, strong: bool) -> Self {
56        let level = |l: u8| -> f64 {
57            let x = f64::from(l) / f64::from(LEVELS);
58            if strong {
59                1.0 - clairlune_scene::math::pow(1.0 - x, 1.8)
60            } else {
61                x
62            }
63        };
64        let mut colors = Vec::with_capacity(128);
65        let band = |b: u8| -> Rgb {
66            if b < 4 {
67                family.bg_edge.mix(family.bg_center, f64::from(b) / 3.0)
68            } else {
69                let t = family.glow_strength * f64::from(b - 3) / 4.0;
70                family.bg_center.mix(family.accent, t)
71            }
72        };
73        for b in 0..BANDS {
74            colors.push(band(b));
75        }
76        for b in 0..BANDS {
77            let ink = if b < 4 {
78                family.ink
79            } else {
80                family
81                    .ink
82                    .mix(family.accent, family.tint_strength * f64::from(b - 3) / 4.0)
83            };
84            for l in 1..=LEVELS {
85                colors.push(band(b).mix(ink, level(l)));
86            }
87        }
88        for b in 0..BANDS {
89            for l in 1..=LEVELS {
90                colors.push(band(b).mix(family.ember, f64::from(l) / f64::from(LEVELS)));
91            }
92        }
93        debug_assert_eq!(colors.len(), SPRITE_BASE as usize);
94        // Props, the character, then props added since (their own order keeps
95        // older scenes' palette indices).
96        let (early, late) = SpriteKind::ALL.split_at(SpriteKind::BEFORE_CHARACTER);
97        let early = early.iter().flat_map(|k| k.map().palette());
98        let character = clairlune_sprites::builtin_character().colors();
99        let late = late.iter().flat_map(|k| k.map().palette());
100        for rgb in early.chain(character).chain(late) {
101            if !colors[SPRITE_BASE as usize..].contains(&rgb) {
102                colors.push(rgb);
103            }
104        }
105        assert!(
106            colors.len() <= TRANSPARENT_INDEX as usize,
107            "palette over budget"
108        );
109        Self { colors }
110    }
111
112    pub fn len(&self) -> usize {
113        self.colors.len()
114    }
115
116    pub fn is_empty(&self) -> bool {
117        self.colors.is_empty()
118    }
119
120    pub fn colors(&self) -> &[Rgb] {
121        &self.colors
122    }
123
124    /// `r g b` triplets for a PNG/GIF palette chunk.
125    pub fn rgb_bytes(&self) -> Vec<u8> {
126        self.colors.iter().flat_map(|c| [c.r, c.g, c.b]).collect()
127    }
128
129    /// Ink entry for a background band and level `1..=LEVELS`.
130    #[inline]
131    pub fn ink(band: u8, level: u8) -> u8 {
132        INK_BASE + band * LEVELS + level - 1
133    }
134
135    /// Ember entry for a background band and level `1..=LEVELS`.
136    #[inline]
137    pub fn ember(band: u8, level: u8) -> u8 {
138        EMBER_BASE + band * LEVELS + level - 1
139    }
140
141    /// Adds sprite colours it lacks (a character drawn with colours the
142    /// built-in art doesn't use), as far as the budget allows.
143    pub fn with_sprite_colors(mut self, extra: impl IntoIterator<Item = Rgb>) -> Self {
144        for rgb in extra {
145            if self.colors.len() >= TRANSPARENT_INDEX as usize {
146                break;
147            }
148            if self.sprite_index(rgb).is_none() {
149                self.colors.push(rgb);
150            }
151        }
152        self
153    }
154
155    /// Palette index of a sprite colour.
156    pub fn sprite_index(&self, rgb: Rgb) -> Option<u8> {
157        self.colors[SPRITE_BASE as usize..]
158            .iter()
159            .position(|&c| c == rgb)
160            .map(|i| SPRITE_BASE + i as u8)
161    }
162}
163
164/// Ink level `0..=LEVELS` from glyph alpha and cell shade (both 0-255).
165#[inline]
166pub fn ink_level(alpha: u8, shade: u8) -> u8 {
167    let v = u32::from(alpha) * u32::from(shade) * u32::from(LEVELS);
168    ((v + 65025 / 2) / 65025) as u8
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use clairlune_scene::palette::FAMILIES;
175
176    #[test]
177    fn every_family_fits_the_budget() {
178        for f in &FAMILIES {
179            let p = IndexedPalette::new(f);
180            assert!(p.len() <= 255, "{}: {}", f.id, p.len());
181            assert!(p.sprite_index(Rgb::hex(0xD9785C)).is_some());
182        }
183    }
184
185    #[test]
186    fn ink_level_range() {
187        assert_eq!(ink_level(0, 255), 0);
188        assert_eq!(ink_level(255, 255), LEVELS);
189        assert_eq!(ink_level(255, 0), 0);
190    }
191}