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, LANTERN, LOG_SEAT, PixelMap, TELESCOPE};
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/// The character's layout box in sprite pixels (assets/clawd/design/clawd.lua:
20/// a 15 px body with 2 px arms, 13 rows from the top edge to the feet).
21pub const CHARACTER_BOX: (u32, u32) = (19, 13);
22
23/// Number of background bands (vignette + glow, quantised).
24pub const BANDS: u8 = 8;
25/// Width of the ordered-dither zone around each band edge, in bands.
26const DITHER_WIDTH: f64 = 0.4;
27/// 4x4 Bayer matrix.
28const BAYER4: [[u8; 4]; 4] = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];
29
30/// Cell grid geometry for one output size.
31#[derive(Clone, Copy, Debug, PartialEq)]
32pub struct GridSpec {
33    pub cols: u32,
34    pub rows: u32,
35    pub cell_w: u32,
36    pub cell_h: u32,
37    /// Pixel offset of the grid, centring it in the image.
38    pub origin_x: u32,
39    pub origin_y: u32,
40    /// Font size in pixels used to rasterize the glyph atlas.
41    pub font_px: f64,
42}
43
44/// Grid for a pixel size: about [`TARGET_ROWS`] rows, never smaller than 6x11 cells.
45pub fn grid_spec(width: u32, height: u32) -> GridSpec {
46    let cell_h = ((f64::from(height) / f64::from(TARGET_ROWS)).round() as u32).max(MIN_CELL_H);
47    let font_px = f64::from(cell_h) * FONT_TO_CELL;
48    let cell_w = ((font_px * ADVANCE_RATIO).round() as u32).max(MIN_CELL_W);
49    let cols = width / cell_w;
50    let rows = height / cell_h;
51    GridSpec {
52        cols,
53        rows,
54        cell_w,
55        cell_h,
56        origin_x: (width - cols * cell_w) / 2,
57        origin_y: (height - rows * cell_h) / 2,
58        font_px,
59    }
60}
61
62/// One character cell. `glyph` indexes `glyphs::GLYPHS`; `shade` is ink strength.
63#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
64pub struct Cell {
65    pub glyph: u8,
66    pub shade: u8,
67}
68
69/// Radial warm light around a light source.
70#[derive(Clone, Copy, Debug, PartialEq)]
71pub struct Glow {
72    pub cx: f64,
73    pub cy: f64,
74    pub radius: f64,
75}
76
77/// Vignette and glow, quantised into [`BANDS`] background bands.
78///
79/// Band coordinate `c` is continuous in `[0, 8)`: the vignette contributes up to
80/// 4 (bands 0-3, brighter toward the centre) and the glow pulls `c` toward 8
81/// (bands 4-7, warmer toward the light). Ink in bands 4-7 is tinted toward the
82/// accent, so glow and glyph tint come from one lookup.
83#[derive(Clone, Copy, Debug, PartialEq)]
84pub struct Lighting {
85    pub vignette_cx: f64,
86    pub vignette_cy: f64,
87    pub vignette_rx: f64,
88    pub vignette_ry: f64,
89    pub glow: Option<Glow>,
90}
91
92/// Row-invariant terms of the band computation.
93#[derive(Clone, Copy, Debug)]
94pub struct RowTerms {
95    vy2: f64,
96    gy2: f64,
97    bayer_row: usize,
98}
99
100impl Lighting {
101    #[inline]
102    pub fn row_terms(&self, py: u32) -> RowTerms {
103        let y = f64::from(py) + 0.5;
104        let vy = (y - self.vignette_cy) / self.vignette_ry;
105        let gy2 = match self.glow {
106            Some(g) => {
107                let d = y - g.cy;
108                d * d
109            }
110            None => 0.0,
111        };
112        RowTerms {
113            vy2: vy * vy,
114            gy2,
115            bayer_row: (py & 3) as usize,
116        }
117    }
118
119    /// Background band of pixel `(px, py)`. [`Lighting::fill_row`] must agree exactly.
120    #[inline]
121    pub fn band_in_row(&self, rt: &RowTerms, px: u32) -> u8 {
122        let x = f64::from(px) + 0.5;
123        let vx = (x - self.vignette_cx) / self.vignette_rx;
124        let q = (vx * vx + rt.vy2).min(1.0);
125        let v = 1.0 - q;
126        let cv = 3.999 * v * v;
127        let c = match self.glow {
128            Some(g) => {
129                let dx = x - g.cx;
130                let r2 = (dx * dx + rt.gy2) / (g.radius * g.radius);
131                if r2 < 1.0 {
132                    let t = 1.0 - r2;
133                    cv + t * t * (7.999 - cv)
134                } else {
135                    cv
136                }
137            }
138            None => cv,
139        };
140        let b = BAYER4[rt.bayer_row][(px & 3) as usize];
141        let d = ((f64::from(b) + 0.5) / 16.0 - 0.5) * DITHER_WIDTH;
142        (c + d).floor().clamp(0.0, f64::from(BANDS - 1)) as u8
143    }
144
145    /// Background band of one pixel.
146    pub fn band_at(&self, px: u32, py: u32) -> u8 {
147        self.band_in_row(&self.row_terms(py), px)
148    }
149
150    /// Fills one image row with band indices.
151    pub fn fill_row(&self, py: u32, out: &mut [u8]) {
152        let rt = self.row_terms(py);
153        for (px, o) in out.iter_mut().enumerate() {
154            *o = self.band_in_row(&rt, px as u32);
155        }
156    }
157}
158
159/// What a sprite instance shows.
160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
161pub enum SpriteKind {
162    /// The character (placeholder pixel map in M1).
163    Character,
164    Campfire,
165    /// Unattended variant: an empty log seat by the fire.
166    LogSeat,
167    Telescope,
168    Lantern,
169}
170
171impl SpriteKind {
172    /// Every kind, so palettes can reserve all sprite colours up front.
173    pub const ALL: [SpriteKind; 5] = [
174        SpriteKind::Character,
175        SpriteKind::Campfire,
176        SpriteKind::LogSeat,
177        SpriteKind::Telescope,
178        SpriteKind::Lantern,
179    ];
180
181    /// Layout box in sprite pixels. The character's box is the drawn art's
182    /// (body plus arms, feet included), not the placeholder's.
183    pub fn box_size(self) -> (u32, u32) {
184        match self {
185            SpriteKind::Character => CHARACTER_BOX,
186            other => (other.map().width, other.map().height),
187        }
188    }
189
190    pub fn map(self) -> &'static PixelMap {
191        match self {
192            SpriteKind::Character => &CLAWD_PLACEHOLDER,
193            SpriteKind::Campfire => &CAMPFIRE,
194            SpriteKind::LogSeat => &LOG_SEAT,
195            SpriteKind::Telescope => &TELESCOPE,
196            SpriteKind::Lantern => &LANTERN,
197        }
198    }
199}
200
201/// How the character moves over time.
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub enum Motion {
204    /// Fixed spot (left edge x).
205    Stationary { x: i32 },
206    /// Walks back and forth between two left-edge positions; one round trip per period.
207    Pace {
208        x_min: i32,
209        x_max: i32,
210        period_ms: u64,
211    },
212}
213
214/// The character's placement as a pure function of time.
215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
216pub struct CharacterTrack {
217    /// Top edge (feet on the ground line).
218    pub y: i32,
219    pub scale: u32,
220    pub motion: Motion,
221    /// Facing when stationary (toward the main prop).
222    pub face_left: bool,
223}
224
225impl CharacterTrack {
226    /// Sprite placement at `t_ms`. Integer arithmetic only.
227    pub fn at(&self, t_ms: u64) -> SpriteInstance {
228        let (x, mirror) = match self.motion {
229            Motion::Stationary { x } => (x, self.face_left),
230            Motion::Pace {
231                x_min,
232                x_max,
233                period_ms,
234            } => {
235                let span = i64::from(x_max - x_min);
236                let half = (period_ms / 2).max(1) as i64;
237                let ph = (t_ms % period_ms.max(1)) as i64;
238                if ph < half {
239                    ((i64::from(x_min) + span * ph / half) as i32, false)
240                } else {
241                    ((i64::from(x_max) - span * (ph - half) / half) as i32, true)
242                }
243            }
244        };
245        SpriteInstance {
246            kind: SpriteKind::Character,
247            x,
248            y: self.y,
249            scale: self.scale,
250            mirror,
251        }
252    }
253
254    /// Leftmost and rightmost left-edge positions over all time.
255    pub fn x_range(&self) -> (i32, i32) {
256        match self.motion {
257            Motion::Stationary { x } => (x, x),
258            Motion::Pace { x_min, x_max, .. } => (x_min, x_max),
259        }
260    }
261}
262
263/// A sprite placed in the image at an integer nearest-neighbour scale.
264#[derive(Clone, Copy, Debug, PartialEq, Eq)]
265pub struct SpriteInstance {
266    pub kind: SpriteKind,
267    /// Top-left pixel.
268    pub x: i32,
269    pub y: i32,
270    pub scale: u32,
271    pub mirror: bool,
272}
273
274impl SpriteInstance {
275    pub fn width(&self) -> u32 {
276        self.kind.box_size().0 * self.scale
277    }
278    pub fn height(&self) -> u32 {
279        self.kind.box_size().1 * self.scale
280    }
281}
282
283/// Everything needed to render one scene at one size and theme.
284#[derive(Clone, Debug)]
285pub struct SceneGraph {
286    pub width: u32,
287    pub height: u32,
288    pub theme: Theme,
289    pub tod: TimeOfDay,
290    pub buddy: bool,
291    /// The recipe seed (drives the character's state machine).
292    pub seed: u64,
293    pub family: PaletteFamily,
294    pub grid: GridSpec,
295    /// Row-major, `grid.cols * grid.rows`.
296    pub cells: Vec<Cell>,
297    pub lighting: Lighting,
298    /// The activity id, or `None` for an archetype-first fallback scene.
299    pub activity: Option<String>,
300    /// Activity props, drawn in both Buddy states.
301    pub props: Vec<SpriteInstance>,
302    /// Unattended variant, drawn only with Buddy off.
303    pub unattended: Vec<SpriteInstance>,
304    /// The character's track (always laid out; drawn only with Buddy on).
305    pub character: Option<CharacterTrack>,
306    pub emitters: Vec<Emitter>,
307    /// Pixel y of the platform's top surface (where feet stand).
308    pub ground_y: i32,
309    /// Hero time in milliseconds: the frame used for stills and thumbnails.
310    pub t_hero_ms: u64,
311    /// Seamless loop length for periodic elements.
312    pub loop_ms: u64,
313}
314
315impl SceneGraph {
316    #[inline]
317    pub fn cell(&self, col: u32, row: u32) -> Cell {
318        self.cells[(row * self.grid.cols + col) as usize]
319    }
320
321    /// Sprites to draw at `t`, back to front: props, then the character (Buddy
322    /// on) or the unattended variant (Buddy off).
323    pub fn sprites_at(&self, t_ms: u64) -> Vec<SpriteInstance> {
324        let mut out = self.props.clone();
325        if self.buddy {
326            out.extend(self.character.map(|c| c.at(t_ms)));
327        } else {
328            out.extend_from_slice(&self.unattended);
329        }
330        out
331    }
332
333    /// Particles at time `t`, snapped to cells, as `(col, row, particle)`.
334    pub fn particles_at(&self, t_ms: u64) -> Vec<(u32, u32, Particle)> {
335        let g = &self.grid;
336        let mut out = Vec::new();
337        for e in &self.emitters {
338            for p in e.sample(t_ms) {
339                let cx = (p.x - f64::from(g.origin_x)) / f64::from(g.cell_w);
340                let cy = (p.y - f64::from(g.origin_y)) / f64::from(g.cell_h);
341                if cx < 0.0 || cy < 0.0 {
342                    continue;
343                }
344                let (col, row) = (cx.floor() as u32, cy.floor() as u32);
345                if col < g.cols && row < g.rows {
346                    out.push((col, row, p));
347                }
348            }
349        }
350        out
351    }
352}