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 = character_colours();
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/// The character's colours in the order palettes have listed them since
165/// version 0.10.0. Palette indices follow this order, so it is frozen: a
166/// colour new art brings goes after these (in RGB order), and older scenes
167/// keep their indices however the sheets are named.
168const CHARACTER_ORDER: [Rgb; 16] = [
169    Rgb::hex(0xE8957A),
170    Rgb::hex(0xD9785C),
171    Rgb::hex(0xB85E45),
172    Rgb::hex(0x261A16),
173    Rgb::hex(0x5B4B8A),
174    Rgb::hex(0xFFE9A0),
175    Rgb::hex(0xC9A45C),
176    Rgb::hex(0x413566),
177    Rgb::hex(0x7A5234),
178    Rgb::hex(0x4E3422),
179    Rgb::hex(0x3B4450),
180    Rgb::hex(0xEEEAE0),
181    Rgb::hex(0xC8452E),
182    Rgb::hex(0x2A2624),
183    Rgb::hex(0x933022),
184    Rgb::hex(0xC8C2B0),
185];
186
187/// The built-in character's colours: the frozen order, then any others.
188fn character_colours() -> Vec<Rgb> {
189    let mut extra: Vec<Rgb> = clairlune_sprites::builtin_character()
190        .colors()
191        .into_iter()
192        .filter(|c| !CHARACTER_ORDER.contains(c))
193        .collect();
194    extra.sort_by_key(|c| (c.r, c.g, c.b));
195    CHARACTER_ORDER.iter().copied().chain(extra).collect()
196}
197
198/// Ink level `0..=LEVELS` from glyph alpha and cell shade (both 0-255).
199#[inline]
200pub fn ink_level(alpha: u8, shade: u8) -> u8 {
201    let v = u32::from(alpha) * u32::from(shade) * u32::from(LEVELS);
202    ((v + 65025 / 2) / 65025) as u8
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use clairlune_scene::palette::FAMILIES;
209
210    #[test]
211    fn every_family_fits_the_budget() {
212        for f in &FAMILIES {
213            let p = IndexedPalette::new(f);
214            assert!(p.len() <= 255, "{}: {}", f.id, p.len());
215            assert!(p.sprite_index(Rgb::hex(0xD9785C)).is_some());
216        }
217    }
218
219    #[test]
220    fn every_character_colour_has_a_slot_and_the_old_ones_keep_theirs() {
221        let p = IndexedPalette::new(&FAMILIES[0]);
222        for c in clairlune_sprites::builtin_character().colors() {
223            assert!(p.sprite_index(c).is_some(), "{c:?} has no palette entry");
224        }
225        // The frozen order comes first among the character's colours.
226        let colours = character_colours();
227        assert_eq!(&colours[..CHARACTER_ORDER.len()], &CHARACTER_ORDER);
228    }
229
230    #[test]
231    fn ink_level_range() {
232        assert_eq!(ink_level(0, 255), 0);
233        assert_eq!(ink_level(255, 255), LEVELS);
234        assert_eq!(ink_level(255, 0), 0);
235    }
236}