Skip to main content

clairlune_scene/
graph.rs

1//! The scene graph: a resolution-specific, theme-specific description of what to
2//! draw. Static layers are a grid of glyph cells; animated elements are sprite
3//! instances and particle emitters.
4
5use crate::palette::{PaletteFamily, Theme};
6use crate::particles::{Emitter, Particle};
7use crate::placeholder::{CAMPFIRE, CLAWD_PLACEHOLDER, LOG_SEAT, PixelMap};
8use crate::recipe::TimeOfDay;
9
10/// Advance width of the bundled monospace font (JetBrains Mono) per em.
11pub const ADVANCE_RATIO: f64 = 0.6;
12/// Font pixel size relative to the cell height.
13pub const FONT_TO_CELL: f64 = 0.9;
14/// Target number of rows, so the look is consistent from 720p to 4K.
15pub const TARGET_ROWS: u32 = 108;
16pub const MIN_CELL_W: u32 = 6;
17pub const MIN_CELL_H: u32 = 11;
18
19/// Number of background bands (vignette + glow, quantised).
20pub const BANDS: u8 = 8;
21/// Width of the ordered-dither zone around each band edge, in bands.
22const DITHER_WIDTH: f64 = 0.4;
23/// 4x4 Bayer matrix.
24const BAYER4: [[u8; 4]; 4] = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];
25
26/// Cell grid geometry for one output size.
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct GridSpec {
29    pub cols: u32,
30    pub rows: u32,
31    pub cell_w: u32,
32    pub cell_h: u32,
33    /// Pixel offset of the grid, centring it in the image.
34    pub origin_x: u32,
35    pub origin_y: u32,
36    /// Font size in pixels used to rasterize the glyph atlas.
37    pub font_px: f64,
38}
39
40/// Grid for a pixel size: about [`TARGET_ROWS`] rows, never smaller than 6x11 cells.
41pub fn grid_spec(width: u32, height: u32) -> GridSpec {
42    let cell_h = ((f64::from(height) / f64::from(TARGET_ROWS)).round() as u32).max(MIN_CELL_H);
43    let font_px = f64::from(cell_h) * FONT_TO_CELL;
44    let cell_w = ((font_px * ADVANCE_RATIO).round() as u32).max(MIN_CELL_W);
45    let cols = width / cell_w;
46    let rows = height / cell_h;
47    GridSpec {
48        cols,
49        rows,
50        cell_w,
51        cell_h,
52        origin_x: (width - cols * cell_w) / 2,
53        origin_y: (height - rows * cell_h) / 2,
54        font_px,
55    }
56}
57
58/// One character cell. `glyph` indexes `glyphs::GLYPHS`; `shade` is ink strength.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub struct Cell {
61    pub glyph: u8,
62    pub shade: u8,
63}
64
65/// Radial warm light around a light source.
66#[derive(Clone, Copy, Debug, PartialEq)]
67pub struct Glow {
68    pub cx: f64,
69    pub cy: f64,
70    pub radius: f64,
71}
72
73/// Vignette and glow, quantised into [`BANDS`] background bands.
74///
75/// Band coordinate `c` is continuous in `[0, 8)`: the vignette contributes up to
76/// 4 (bands 0-3, brighter toward the centre) and the glow pulls `c` toward 8
77/// (bands 4-7, warmer toward the light). Ink in bands 4-7 is tinted toward the
78/// accent, so glow and glyph tint come from one lookup.
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct Lighting {
81    pub vignette_cx: f64,
82    pub vignette_cy: f64,
83    pub vignette_rx: f64,
84    pub vignette_ry: f64,
85    pub glow: Option<Glow>,
86}
87
88/// Row-invariant terms of the band computation.
89#[derive(Clone, Copy, Debug)]
90pub struct RowTerms {
91    vy2: f64,
92    gy2: f64,
93    bayer_row: usize,
94}
95
96impl Lighting {
97    #[inline]
98    pub fn row_terms(&self, py: u32) -> RowTerms {
99        let y = f64::from(py) + 0.5;
100        let vy = (y - self.vignette_cy) / self.vignette_ry;
101        let gy2 = match self.glow {
102            Some(g) => {
103                let d = y - g.cy;
104                d * d
105            }
106            None => 0.0,
107        };
108        RowTerms {
109            vy2: vy * vy,
110            gy2,
111            bayer_row: (py & 3) as usize,
112        }
113    }
114
115    /// Background band of pixel `(px, py)`. [`Lighting::fill_row`] must agree exactly.
116    #[inline]
117    pub fn band_in_row(&self, rt: &RowTerms, px: u32) -> u8 {
118        let x = f64::from(px) + 0.5;
119        let vx = (x - self.vignette_cx) / self.vignette_rx;
120        let q = (vx * vx + rt.vy2).min(1.0);
121        let v = 1.0 - q;
122        let cv = 3.999 * v * v;
123        let c = match self.glow {
124            Some(g) => {
125                let dx = x - g.cx;
126                let r2 = (dx * dx + rt.gy2) / (g.radius * g.radius);
127                if r2 < 1.0 {
128                    let t = 1.0 - r2;
129                    cv + t * t * (7.999 - cv)
130                } else {
131                    cv
132                }
133            }
134            None => cv,
135        };
136        let b = BAYER4[rt.bayer_row][(px & 3) as usize];
137        let d = ((f64::from(b) + 0.5) / 16.0 - 0.5) * DITHER_WIDTH;
138        (c + d).floor().clamp(0.0, f64::from(BANDS - 1)) as u8
139    }
140
141    /// Background band of one pixel.
142    pub fn band_at(&self, px: u32, py: u32) -> u8 {
143        self.band_in_row(&self.row_terms(py), px)
144    }
145
146    /// Fills one image row with band indices.
147    pub fn fill_row(&self, py: u32, out: &mut [u8]) {
148        let rt = self.row_terms(py);
149        for (px, o) in out.iter_mut().enumerate() {
150            *o = self.band_in_row(&rt, px as u32);
151        }
152    }
153}
154
155/// What a sprite instance shows.
156#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157pub enum SpriteKind {
158    /// The character (placeholder pixel map in M1).
159    Character,
160    Campfire,
161    /// Unattended variant: an empty log seat by the fire.
162    LogSeat,
163}
164
165impl SpriteKind {
166    pub fn map(self) -> &'static PixelMap {
167        match self {
168            SpriteKind::Character => &CLAWD_PLACEHOLDER,
169            SpriteKind::Campfire => &CAMPFIRE,
170            SpriteKind::LogSeat => &LOG_SEAT,
171        }
172    }
173}
174
175/// A sprite placed in the image at an integer nearest-neighbour scale.
176#[derive(Clone, Copy, Debug, PartialEq, Eq)]
177pub struct SpriteInstance {
178    pub kind: SpriteKind,
179    /// Top-left pixel.
180    pub x: i32,
181    pub y: i32,
182    pub scale: u32,
183    pub mirror: bool,
184}
185
186impl SpriteInstance {
187    pub fn width(&self) -> u32 {
188        self.kind.map().width * self.scale
189    }
190    pub fn height(&self) -> u32 {
191        self.kind.map().height * self.scale
192    }
193}
194
195/// Everything needed to render one scene at one size and theme.
196#[derive(Clone, Debug)]
197pub struct SceneGraph {
198    pub width: u32,
199    pub height: u32,
200    pub theme: Theme,
201    pub tod: TimeOfDay,
202    pub buddy: bool,
203    pub family: PaletteFamily,
204    pub grid: GridSpec,
205    /// Row-major, `grid.cols * grid.rows`.
206    pub cells: Vec<Cell>,
207    pub lighting: Lighting,
208    /// Drawn in order, after particles.
209    pub sprites: Vec<SpriteInstance>,
210    pub emitters: Vec<Emitter>,
211    /// Pixel y of the platform's top surface (where feet stand).
212    pub ground_y: i32,
213    /// Hero time in milliseconds: the frame used for stills and thumbnails.
214    pub t_hero_ms: u64,
215    /// Seamless loop length for periodic elements.
216    pub loop_ms: u64,
217}
218
219impl SceneGraph {
220    #[inline]
221    pub fn cell(&self, col: u32, row: u32) -> Cell {
222        self.cells[(row * self.grid.cols + col) as usize]
223    }
224
225    /// Particles at time `t`, snapped to cells, as `(col, row, particle)`.
226    pub fn particles_at(&self, t_ms: u64) -> Vec<(u32, u32, Particle)> {
227        let g = &self.grid;
228        let mut out = Vec::new();
229        for e in &self.emitters {
230            for p in e.sample(t_ms) {
231                let cx = (p.x - f64::from(g.origin_x)) / f64::from(g.cell_w);
232                let cy = (p.y - f64::from(g.origin_y)) / f64::from(g.cell_h);
233                if cx < 0.0 || cy < 0.0 {
234                    continue;
235                }
236                let (col, row) = (cx.floor() as u32, cy.floor() as u32);
237                if col < g.cols && row < g.rows {
238                    out.push((col, row, p));
239                }
240            }
241        }
242        out
243    }
244}