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    pub fn new(family: &PaletteFamily) -> Self {
38        let mut colors = Vec::with_capacity(128);
39        let band = |b: u8| -> Rgb {
40            if b < 4 {
41                family.bg_edge.mix(family.bg_center, f64::from(b) / 3.0)
42            } else {
43                let t = family.glow_strength * f64::from(b - 3) / 4.0;
44                family.bg_center.mix(family.accent, t)
45            }
46        };
47        for b in 0..BANDS {
48            colors.push(band(b));
49        }
50        for b in 0..BANDS {
51            let ink = if b < 4 {
52                family.ink
53            } else {
54                family
55                    .ink
56                    .mix(family.accent, family.tint_strength * f64::from(b - 3) / 4.0)
57            };
58            for l in 1..=LEVELS {
59                colors.push(band(b).mix(ink, f64::from(l) / f64::from(LEVELS)));
60            }
61        }
62        for b in 0..BANDS {
63            for l in 1..=LEVELS {
64                colors.push(band(b).mix(family.ember, f64::from(l) / f64::from(LEVELS)));
65            }
66        }
67        debug_assert_eq!(colors.len(), SPRITE_BASE as usize);
68        for kind in SpriteKind::ALL {
69            for rgb in kind.map().palette() {
70                if !colors[SPRITE_BASE as usize..].contains(&rgb) {
71                    colors.push(rgb);
72                }
73            }
74        }
75        for rgb in clairlune_sprites::builtin_character().colors() {
76            if !colors[SPRITE_BASE as usize..].contains(&rgb) {
77                colors.push(rgb);
78            }
79        }
80        assert!(
81            colors.len() <= TRANSPARENT_INDEX as usize,
82            "palette over budget"
83        );
84        Self { colors }
85    }
86
87    pub fn len(&self) -> usize {
88        self.colors.len()
89    }
90
91    pub fn is_empty(&self) -> bool {
92        self.colors.is_empty()
93    }
94
95    pub fn colors(&self) -> &[Rgb] {
96        &self.colors
97    }
98
99    /// `r g b` triplets for a PNG/GIF palette chunk.
100    pub fn rgb_bytes(&self) -> Vec<u8> {
101        self.colors.iter().flat_map(|c| [c.r, c.g, c.b]).collect()
102    }
103
104    /// Ink entry for a background band and level `1..=LEVELS`.
105    #[inline]
106    pub fn ink(band: u8, level: u8) -> u8 {
107        INK_BASE + band * LEVELS + level - 1
108    }
109
110    /// Ember entry for a background band and level `1..=LEVELS`.
111    #[inline]
112    pub fn ember(band: u8, level: u8) -> u8 {
113        EMBER_BASE + band * LEVELS + level - 1
114    }
115
116    /// Palette index of a sprite colour.
117    pub fn sprite_index(&self, rgb: Rgb) -> Option<u8> {
118        self.colors[SPRITE_BASE as usize..]
119            .iter()
120            .position(|&c| c == rgb)
121            .map(|i| SPRITE_BASE + i as u8)
122    }
123}
124
125/// Ink level `0..=LEVELS` from glyph alpha and cell shade (both 0-255).
126#[inline]
127pub fn ink_level(alpha: u8, shade: u8) -> u8 {
128    let v = u32::from(alpha) * u32::from(shade) * u32::from(LEVELS);
129    ((v + 65025 / 2) / 65025) as u8
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use clairlune_scene::palette::FAMILIES;
136
137    #[test]
138    fn every_family_fits_the_budget() {
139        for f in &FAMILIES {
140            let p = IndexedPalette::new(f);
141            assert!(p.len() <= 255, "{}: {}", f.id, p.len());
142            assert!(p.sprite_index(Rgb::hex(0xD9785C)).is_some());
143        }
144    }
145
146    #[test]
147    fn ink_level_range() {
148        assert_eq!(ink_level(0, 255), 0);
149        assert_eq!(ink_level(255, 255), LEVELS);
150        assert_eq!(ink_level(255, 0), 0);
151    }
152}