Skip to main content

clairlune_render/
journey.rs

1//! Journeys (docs/scrolling-scenes.md): the layers that scroll past, baked
2//! once into strips and laid over the still background at each frame's
3//! offsets. A strip holds ink levels, not colours: ink takes its colour
4//! from the background band under it (vignette, glow), and the bands stay
5//! where they are on screen while the land moves.
6
7use crate::IndexedImage;
8use crate::atlas::GlyphAtlas;
9use crate::palette::{IndexedPalette, ink_level};
10use clairlune_scene::glyphs::EMPTY;
11use clairlune_scene::{Cell, SceneGraph};
12
13/// A strip pixel that lets what is behind show through.
14const CLEAR: u8 = u8::MAX;
15
16/// One layer as pixels: `CLEAR`, 0 (the band: hides what is behind) or an
17/// ink level, for the rows from `y0` down.
18#[derive(Clone, Debug, Default)]
19struct LevelStrip {
20    /// Width in pixels: the period.
21    period: usize,
22    y0: usize,
23    rows: usize,
24    levels: Vec<u8>,
25}
26
27/// A journey's moving layers, ready to lay over the still background.
28#[derive(Clone, Debug)]
29pub struct JourneyBake {
30    strips: Vec<LevelStrip>,
31    /// The background bands of the rows from `y0` down (what a strip's
32    /// ink is coloured by).
33    bands: Vec<u8>,
34    y0: usize,
35}
36
37impl JourneyBake {
38    /// `None` for a scene that stays put.
39    pub fn new(graph: &SceneGraph, atlas: &GlyphAtlas) -> Option<Self> {
40        let journey = graph.journey.as_ref()?;
41        let g = &graph.grid;
42        let (cw, ch) = (g.cell_w as usize, g.cell_h as usize);
43        let mut strips = Vec::with_capacity(journey.layers.len());
44        for layer in &journey.layers {
45            let lc = layer.cols as usize;
46            let cell = |col: usize, row: usize| layer.cells[row * lc + col];
47            let Some(first) =
48                (0..g.rows as usize).find(|&r| (0..lc).any(|c| cell(c, r) != Cell::default()))
49            else {
50                strips.push(LevelStrip::default());
51                continue;
52            };
53            let period = lc * cw;
54            let rows = (g.rows as usize - first) * ch;
55            let mut levels = vec![CLEAR; period * rows];
56            for row in first..g.rows as usize {
57                for col in 0..lc {
58                    let c = cell(col, row);
59                    if c == Cell::default() {
60                        continue;
61                    }
62                    let mask = atlas.mask(c.glyph);
63                    let (x0, y0) = (col * cw, (row - first) * ch);
64                    for my in 0..ch {
65                        let line = &mut levels[(y0 + my) * period + x0..][..cw];
66                        for (p, &a) in line.iter_mut().zip(&mask[my * cw..(my + 1) * cw]) {
67                            *p = if c.glyph == EMPTY || a == 0 {
68                                0
69                            } else {
70                                ink_level(a, c.shade)
71                            };
72                        }
73                    }
74                }
75            }
76            strips.push(LevelStrip {
77                period,
78                y0: g.origin_y as usize + first * ch,
79                rows,
80                levels,
81            });
82        }
83        let (w, h) = (graph.width as usize, graph.height as usize);
84        let y0 = strips
85            .iter()
86            .filter(|s| s.rows > 0)
87            .map(|s| s.y0)
88            .min()
89            .unwrap_or(h);
90        let mut bands = vec![0u8; (h - y0) * w];
91        for (i, row) in bands.chunks_exact_mut(w).enumerate() {
92            graph.lighting.fill_row((y0 + i) as u32, row);
93        }
94        Some(JourneyBake { strips, bands, y0 })
95    }
96
97    /// Bytes it holds: each moving layer over its whole period, and the
98    /// bands.
99    pub fn bytes(&self) -> usize {
100        self.strips.iter().map(|s| s.levels.len()).sum::<usize>() + self.bands.len()
101    }
102
103    /// The first row the moving layers reach: above it the frame is the
104    /// still background's.
105    pub fn band_top(&self) -> u32 {
106        self.y0 as u32
107    }
108
109    /// The background at `t_ms` into `out`: the still background, then each
110    /// strip from its offset, back to front.
111    pub fn draw(
112        &self,
113        graph: &SceneGraph,
114        still: &IndexedImage,
115        t_ms: u64,
116        out: &mut IndexedImage,
117    ) {
118        out.pixels.copy_from_slice(&still.pixels);
119        self.lay_strips(graph, t_ms, out);
120    }
121
122    /// [`JourneyBake::draw`] from [`JourneyBake::band_top`] down only: the
123    /// rows above are left as they are in `out`.
124    pub fn draw_band(
125        &self,
126        graph: &SceneGraph,
127        still: &IndexedImage,
128        t_ms: u64,
129        out: &mut IndexedImage,
130    ) {
131        let from = self.y0.min(out.height as usize) * out.width as usize;
132        out.pixels[from..].copy_from_slice(&still.pixels[from..]);
133        self.lay_strips(graph, t_ms, out);
134    }
135
136    fn lay_strips(&self, graph: &SceneGraph, t_ms: u64, out: &mut IndexedImage) {
137        let Some(journey) = graph.journey.as_ref() else {
138            return;
139        };
140        let g = &graph.grid;
141        let w = graph.width as usize;
142        let (gx, gw) = (g.origin_x as usize, (g.cols * g.cell_w) as usize);
143        for (i, s) in self.strips.iter().enumerate() {
144            if s.rows == 0 || s.period < gw {
145                continue;
146            }
147            let off = journey.offset_px(i, g.cell_w, t_ms) as usize;
148            // The screen shows the strip from `off`, wrapping round once.
149            let first = (s.period - off).min(gw);
150            for r in 0..s.rows {
151                let y = s.y0 + r;
152                if y >= graph.height as usize {
153                    break;
154                }
155                let src = &s.levels[r * s.period..(r + 1) * s.period];
156                let band = &self.bands[(y - self.y0) * w + gx..][..gw];
157                let dst = &mut out.pixels[y * w + gx..][..gw];
158                lay(&mut dst[..first], &src[off..off + first], &band[..first]);
159                if first < gw {
160                    lay(&mut dst[first..], &src[..gw - first], &band[first..]);
161                }
162            }
163        }
164    }
165
166    /// [`JourneyBake::draw`] into a new image.
167    pub fn background_at(
168        &self,
169        graph: &SceneGraph,
170        still: &IndexedImage,
171        t_ms: u64,
172    ) -> IndexedImage {
173        let mut out = still.clone();
174        self.draw(graph, still, t_ms, &mut out);
175        out
176    }
177}
178
179/// One run of a strip over the frame.
180fn lay(dst: &mut [u8], src: &[u8], band: &[u8]) {
181    for ((d, &v), &b) in dst.iter_mut().zip(src).zip(band) {
182        if v != CLEAR {
183            *d = if v == 0 { b } else { IndexedPalette::ink(b, v) };
184        }
185    }
186}