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::{
8    BASKET, BOOK_CLOSED, BUCKET, CAMP_STOVE, CAMPFIRE, CHESS_TABLE, CLAWD_PLACEHOLDER, COFFEE_MUG,
9    EASEL, FALLEN_HAT, GUITAR_REST, KITE_REST, LANTERN, LOG_SEAT, PICNIC_BASKET, PRACTICE_WALL,
10    PixelMap, SKIS_REST, SNOWMAN, SPELLBOOK, STONE_PILE, TELESCOPE,
11};
12use crate::recipe::TimeOfDay;
13
14/// Advance width of the bundled monospace font (JetBrains Mono) per em.
15pub const ADVANCE_RATIO: f64 = 0.6;
16/// Font pixel size relative to the cell height.
17pub const FONT_TO_CELL: f64 = 0.9;
18/// Target number of rows, so the look is consistent from 720p to 4K.
19pub const TARGET_ROWS: u32 = 108;
20pub const MIN_CELL_W: u32 = 6;
21pub const MIN_CELL_H: u32 = 11;
22
23/// The character's layout box in sprite pixels (assets/clawd/design/clawd.lua:
24/// a 15 px body with 2 px arms, 13 rows from the top edge to the feet).
25pub const CHARACTER_BOX: (u32, u32) = (19, 13);
26
27/// Number of background bands (vignette + glow, quantised).
28pub const BANDS: u8 = 8;
29/// Width of the ordered-dither zone around each band edge, in bands.
30const DITHER_WIDTH: f64 = 0.4;
31/// 4x4 Bayer matrix.
32const BAYER4: [[u8; 4]; 4] = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]];
33
34/// Cell grid geometry for one output size.
35#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
36pub struct GridSpec {
37    pub cols: u32,
38    pub rows: u32,
39    pub cell_w: u32,
40    pub cell_h: u32,
41    /// Pixel offset of the grid, centring it in the image.
42    pub origin_x: u32,
43    pub origin_y: u32,
44    /// Font size in pixels used to rasterize the glyph atlas.
45    pub font_px: f64,
46}
47
48/// Grid for a pixel size: about [`TARGET_ROWS`] rows, never smaller than 6x11 cells.
49pub fn grid_spec(width: u32, height: u32) -> GridSpec {
50    grid_with_rows(width, height, f64::from(TARGET_ROWS))
51}
52
53/// Grid for a pixel size at a zoom (see `recipe::zoom_factor`): stood further
54/// back, the land has finer text, as far as the smallest cell allows.
55pub fn grid_for(width: u32, height: u32, zoom: f64) -> GridSpec {
56    if zoom >= 1.0 {
57        return grid_spec(width, height);
58    }
59    grid_with_rows(width, height, f64::from(TARGET_ROWS) / zoom.sqrt())
60}
61
62fn grid_with_rows(width: u32, height: u32, rows: f64) -> GridSpec {
63    let cell_h = ((f64::from(height) / rows).round() as u32).max(MIN_CELL_H);
64    let font_px = f64::from(cell_h) * FONT_TO_CELL;
65    let cell_w = ((font_px * ADVANCE_RATIO).round() as u32).max(MIN_CELL_W);
66    let cols = width / cell_w;
67    let rows = height / cell_h;
68    GridSpec {
69        cols,
70        rows,
71        cell_w,
72        cell_h,
73        origin_x: (width - cols * cell_w) / 2,
74        origin_y: (height - rows * cell_h) / 2,
75        font_px,
76    }
77}
78
79/// One character cell. `glyph` indexes `glyphs::GLYPHS`; `shade` is ink strength.
80#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
81pub struct Cell {
82    pub glyph: u8,
83    pub shade: u8,
84}
85
86/// Radial warm light around a light source.
87#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
88pub struct Glow {
89    pub cx: f64,
90    pub cy: f64,
91    pub radius: f64,
92}
93
94/// Vignette and glow, quantised into [`BANDS`] background bands.
95///
96/// Band coordinate `c` is continuous in `[0, 8)`: the vignette contributes up to
97/// 4 (bands 0-3, brighter toward the centre) and the glow pulls `c` toward 8
98/// (bands 4-7, warmer toward the light). Ink in bands 4-7 is tinted toward the
99/// accent, so glow and glyph tint come from one lookup.
100#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
101pub struct Lighting {
102    pub vignette_cx: f64,
103    pub vignette_cy: f64,
104    pub vignette_rx: f64,
105    pub vignette_ry: f64,
106    pub glow: Option<Glow>,
107}
108
109/// Row-invariant terms of the band computation.
110#[derive(Clone, Copy, Debug)]
111pub struct RowTerms {
112    vy2: f64,
113    gy2: f64,
114    bayer_row: usize,
115}
116
117impl Lighting {
118    #[inline]
119    pub fn row_terms(&self, py: u32) -> RowTerms {
120        let y = f64::from(py) + 0.5;
121        let vy = (y - self.vignette_cy) / self.vignette_ry;
122        let gy2 = match self.glow {
123            Some(g) => {
124                let d = y - g.cy;
125                d * d
126            }
127            None => 0.0,
128        };
129        RowTerms {
130            vy2: vy * vy,
131            gy2,
132            bayer_row: (py & 3) as usize,
133        }
134    }
135
136    /// Background band of pixel `(px, py)`. [`Lighting::fill_row`] must agree exactly.
137    #[inline]
138    pub fn band_in_row(&self, rt: &RowTerms, px: u32) -> u8 {
139        let x = f64::from(px) + 0.5;
140        let vx = (x - self.vignette_cx) / self.vignette_rx;
141        let q = (vx * vx + rt.vy2).min(1.0);
142        let v = 1.0 - q;
143        let cv = 3.999 * v * v;
144        let c = match self.glow {
145            Some(g) => {
146                let dx = x - g.cx;
147                let r2 = (dx * dx + rt.gy2) / (g.radius * g.radius);
148                if r2 < 1.0 {
149                    let t = 1.0 - r2;
150                    cv + t * t * (7.999 - cv)
151                } else {
152                    cv
153                }
154            }
155            None => cv,
156        };
157        let b = BAYER4[rt.bayer_row][(px & 3) as usize];
158        let d = ((f64::from(b) + 0.5) / 16.0 - 0.5) * DITHER_WIDTH;
159        (c + d).floor().clamp(0.0, f64::from(BANDS - 1)) as u8
160    }
161
162    /// Fills one image row with band indices.
163    pub fn fill_row(&self, py: u32, out: &mut [u8]) {
164        let rt = self.row_terms(py);
165        for (px, o) in out.iter_mut().enumerate() {
166            *o = self.band_in_row(&rt, px as u32);
167        }
168    }
169}
170
171/// What a sprite instance shows.
172#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
173pub enum SpriteKind {
174    /// The character (placeholder pixel map in M1).
175    Character,
176    Campfire,
177    /// Unattended variant: an empty log seat by the fire.
178    LogSeat,
179    Telescope,
180    Lantern,
181    Spellbook,
182    CampStove,
183    CoffeeMug,
184    FallenHat,
185    BookClosed,
186    GuitarRest,
187    Bucket,
188    KiteRest,
189    StonePile,
190    Easel,
191    Snowman,
192    Basket,
193    PicnicBasket,
194    ChessTable,
195    PracticeWall,
196    SkisRest,
197}
198
199impl SpriteKind {
200    /// How many of [`ALL`](Self::ALL) reserve their colours before the
201    /// character's in a palette. Kinds added later go after them, so the
202    /// palette indices of scenes made before stay the same.
203    pub const BEFORE_CHARACTER: usize = 12;
204
205    /// Every kind, so palettes can reserve all sprite colours up front. New
206    /// kinds go at the end.
207    pub const ALL: [SpriteKind; 21] = [
208        SpriteKind::Character,
209        SpriteKind::Campfire,
210        SpriteKind::LogSeat,
211        SpriteKind::Telescope,
212        SpriteKind::Lantern,
213        SpriteKind::Spellbook,
214        SpriteKind::CampStove,
215        SpriteKind::CoffeeMug,
216        SpriteKind::FallenHat,
217        SpriteKind::BookClosed,
218        SpriteKind::GuitarRest,
219        SpriteKind::Bucket,
220        SpriteKind::KiteRest,
221        SpriteKind::StonePile,
222        SpriteKind::Easel,
223        SpriteKind::Snowman,
224        SpriteKind::Basket,
225        SpriteKind::PicnicBasket,
226        SpriteKind::ChessTable,
227        SpriteKind::PracticeWall,
228        SpriteKind::SkisRest,
229    ];
230
231    /// Layout box in sprite pixels. The character's box is the drawn art's
232    /// (body plus arms, feet included), not the placeholder's.
233    pub fn box_size(self) -> (u32, u32) {
234        match self {
235            SpriteKind::Character => CHARACTER_BOX,
236            other => (other.map().width, other.map().height),
237        }
238    }
239
240    pub fn map(self) -> &'static PixelMap {
241        match self {
242            SpriteKind::Character => &CLAWD_PLACEHOLDER,
243            SpriteKind::Campfire => &CAMPFIRE,
244            SpriteKind::LogSeat => &LOG_SEAT,
245            SpriteKind::Telescope => &TELESCOPE,
246            SpriteKind::Lantern => &LANTERN,
247            SpriteKind::Spellbook => &SPELLBOOK,
248            SpriteKind::CampStove => &CAMP_STOVE,
249            SpriteKind::CoffeeMug => &COFFEE_MUG,
250            SpriteKind::FallenHat => &FALLEN_HAT,
251            SpriteKind::BookClosed => &BOOK_CLOSED,
252            SpriteKind::GuitarRest => &GUITAR_REST,
253            SpriteKind::Bucket => &BUCKET,
254            SpriteKind::KiteRest => &KITE_REST,
255            SpriteKind::StonePile => &STONE_PILE,
256            SpriteKind::Easel => &EASEL,
257            SpriteKind::Snowman => &SNOWMAN,
258            SpriteKind::Basket => &BASKET,
259            SpriteKind::PicnicBasket => &PICNIC_BASKET,
260            SpriteKind::ChessTable => &CHESS_TABLE,
261            SpriteKind::PracticeWall => &PRACTICE_WALL,
262            SpriteKind::SkisRest => &SKIS_REST,
263        }
264    }
265}
266
267/// How the character moves over time.
268#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
269pub enum Motion {
270    /// Fixed spot (left edge x).
271    Stationary { x: i32 },
272    /// Walks back and forth between two left-edge positions; one round trip per period.
273    Pace {
274        x_min: i32,
275        x_max: i32,
276        period_ms: u64,
277    },
278    /// Flies back and forth like `Pace`, `lift` pixels above the ground,
279    /// bobbing `bob` pixels up and down once every `bob_ms`.
280    Fly {
281        x_min: i32,
282        x_max: i32,
283        period_ms: u64,
284        lift: i32,
285        bob: i32,
286        bob_ms: u64,
287    },
288}
289
290/// A smooth up-and-down of `amp` pixels with period `period_ms`, from two
291/// parabolas (integer arithmetic, so the same on every platform).
292pub fn bob_offset(t_ms: u64, period_ms: u64, amp: i32) -> i32 {
293    let half = (period_ms / 2).max(1) as i64;
294    let p = (t_ms % (2 * half as u64)) as i64;
295    let q = p % half;
296    let v = 4 * q * (half - q) * i64::from(amp) / (half * half);
297    (if p < half { -v } else { v }) as i32
298}
299
300/// Left edge and facing at `t_ms` while going back and forth.
301fn back_and_forth(x_min: i32, x_max: i32, period_ms: u64, t_ms: u64) -> (i32, bool) {
302    let span = i64::from(x_max - x_min);
303    let half = (period_ms / 2).max(1) as i64;
304    let ph = (t_ms % period_ms.max(1)) as i64;
305    if ph < half {
306        ((i64::from(x_min) + span * ph / half) as i32, false)
307    } else {
308        ((i64::from(x_max) - span * (ph - half) / half) as i32, true)
309    }
310}
311
312/// The character's placement as a pure function of time.
313#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
314pub struct CharacterTrack {
315    /// Top edge (feet on the ground line).
316    pub y: i32,
317    pub scale: u32,
318    pub motion: Motion,
319    /// Facing when stationary (toward the main prop).
320    pub face_left: bool,
321}
322
323impl CharacterTrack {
324    /// Sprite placement at `t_ms`. Integer arithmetic only.
325    pub fn at(&self, t_ms: u64) -> SpriteInstance {
326        let (x, y, mirror) = match self.motion {
327            Motion::Stationary { x } => (x, self.y, self.face_left),
328            Motion::Pace {
329                x_min,
330                x_max,
331                period_ms,
332            } => {
333                let (x, mirror) = back_and_forth(x_min, x_max, period_ms, t_ms);
334                (x, self.y, mirror)
335            }
336            Motion::Fly {
337                x_min,
338                x_max,
339                period_ms,
340                lift,
341                bob,
342                bob_ms,
343            } => {
344                let (x, mirror) = back_and_forth(x_min, x_max, period_ms, t_ms);
345                (x, self.y - lift + bob_offset(t_ms, bob_ms, bob), mirror)
346            }
347        };
348        SpriteInstance {
349            kind: SpriteKind::Character,
350            x,
351            y,
352            scale: self.scale,
353            mirror,
354        }
355    }
356
357    /// Whether the character leaves the ground (flying, or on the water):
358    /// its feet aren't on the platform.
359    pub fn flies(&self) -> bool {
360        matches!(self.motion, Motion::Fly { .. })
361    }
362
363    /// Leftmost and rightmost left-edge positions over all time.
364    pub fn x_range(&self) -> (i32, i32) {
365        match self.motion {
366            Motion::Stationary { x } => (x, x),
367            Motion::Pace { x_min, x_max, .. } | Motion::Fly { x_min, x_max, .. } => (x_min, x_max),
368        }
369    }
370}
371
372/// A cell of a scrolling layer that is inside the layer's silhouette but
373/// draws nothing: it hides what is behind. (`Cell::default()` in a layer is
374/// outside it: what is behind shows through.)
375pub const HOLE: Cell = Cell {
376    glyph: crate::glyphs::EMPTY,
377    shade: 1,
378};
379
380/// One layer of a journey: a strip of cells as tall as the grid whose right
381/// edge continues into its left edge, moving `turns` whole strip widths per
382/// loop.
383#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq)]
384pub struct ScrollLayer {
385    /// Strip width in cells (the period).
386    pub cols: u32,
387    /// Whole strip widths it moves per loop.
388    pub turns: u32,
389    /// `cols * grid.rows` cells, row-major: `Cell::default()` is see-through,
390    /// [`HOLE`] hides what is behind. Not stored in a package's JSON.
391    #[serde(skip)]
392    pub cells: Vec<Cell>,
393}
394
395/// A scene whose camera travels (docs/scrolling-scenes.md): layers slide
396/// past at their own speeds over the still background (sky, far peaks) and
397/// all come around again after `loop_ms`. Integer arithmetic only, so every
398/// frame is the same everywhere.
399#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq)]
400pub struct Journey {
401    pub loop_ms: u64,
402    /// Back to front; the last is the one the character walks on.
403    pub layers: Vec<ScrollLayer>,
404    /// Pixel y the feet stand at, for each pixel column of the last layer's
405    /// strip (the highest ground under the feet there).
406    pub ground: Vec<i32>,
407    /// Screen x of the character's centre.
408    pub feet_x: i32,
409}
410
411impl Journey {
412    /// How far layer `i` has moved at `t_ms`, in pixels within its strip.
413    pub fn offset_px(&self, i: usize, cell_w: u32, t_ms: u64) -> u32 {
414        let l = &self.layers[i];
415        let period = u64::from(l.cols) * u64::from(cell_w);
416        let t = t_ms % self.loop_ms.max(1);
417        ((u64::from(l.turns) * period * t / self.loop_ms.max(1)) % period.max(1)) as u32
418    }
419
420    /// Where the feet stand at `t_ms` (pixel y), given the grid's left edge.
421    pub fn ground_at(&self, cell_w: u32, origin_x: u32, t_ms: u64) -> Option<i32> {
422        let last = self.layers.len().checked_sub(1)?;
423        let period = self.ground.len() as i64;
424        if period == 0 {
425            return None;
426        }
427        let off = i64::from(self.offset_px(last, cell_w, t_ms));
428        let x = (i64::from(self.feet_x) - i64::from(origin_x) + off).rem_euclid(period);
429        Some(self.ground[x as usize])
430    }
431}
432
433/// A sprite placed in the image at an integer nearest-neighbour scale.
434#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
435pub struct SpriteInstance {
436    pub kind: SpriteKind,
437    /// Top-left pixel.
438    pub x: i32,
439    pub y: i32,
440    pub scale: u32,
441    pub mirror: bool,
442}
443
444impl SpriteInstance {
445    pub fn width(&self) -> u32 {
446        self.kind.box_size().0 * self.scale
447    }
448    pub fn height(&self) -> u32 {
449        self.kind.box_size().1 * self.scale
450    }
451}
452
453/// Everything needed to render one scene at one size and theme.
454#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
455pub struct SceneGraph {
456    pub width: u32,
457    pub height: u32,
458    pub theme: Theme,
459    pub tod: TimeOfDay,
460    pub buddy: bool,
461    /// The recipe seed (drives the character's state machine).
462    pub seed: u64,
463    /// Not stored in scene packages (playback uses the package's palette).
464    #[serde(skip, default = "crate::palette::fallback_family")]
465    pub family: PaletteFamily,
466    pub grid: GridSpec,
467    /// Row-major, `grid.cols * grid.rows`. Not stored in scene packages,
468    /// which keep the baked background instead.
469    #[serde(skip)]
470    pub cells: Vec<Cell>,
471    pub lighting: Lighting,
472    /// The activity id, or `None` for an archetype-first fallback scene.
473    pub activity: Option<String>,
474    /// Activity props, drawn in both Buddy states.
475    pub props: Vec<SpriteInstance>,
476    /// Unattended variant, drawn only with Buddy off.
477    pub unattended: Vec<SpriteInstance>,
478    /// The character's track (always laid out; drawn only with Buddy on).
479    pub character: Option<CharacterTrack>,
480    pub emitters: Vec<Emitter>,
481    /// Pixel y of the platform's top surface (where feet stand).
482    pub ground_y: i32,
483    /// Hero time in milliseconds: the frame used for stills and thumbnails.
484    pub t_hero_ms: u64,
485    /// Seamless loop length for periodic elements.
486    pub loop_ms: u64,
487    /// How fast particles and effects move (`particles::CALM_PACE`); 0 in
488    /// scenes saved before the calm pace, which keep their motion.
489    #[serde(default)]
490    pub pace: u8,
491    /// The generator version that built it (0 in older saved scenes); the
492    /// palette follows it, so older scenes keep their colours.
493    #[serde(default)]
494    pub generator: u32,
495    /// A point on open water near the focal group, in pixels (the shore:
496    /// just past the pier's end), for effects that reach the water.
497    #[serde(default)]
498    pub water: Option<(i32, i32)>,
499    /// A travelling scene: layers that scroll past, ground under the feet.
500    #[serde(default)]
501    pub journey: Option<Journey>,
502    /// The focal group's size against the closest zoom (1, 1/2, 1/4): what
503    /// reaches out from it (a kite's string, a stone's skips) scales too.
504    #[serde(default = "full_zoom")]
505    pub zoom: f64,
506}
507
508fn full_zoom() -> f64 {
509    1.0
510}
511
512impl SceneGraph {
513    #[inline]
514    pub fn cell(&self, col: u32, row: u32) -> Cell {
515        self.cells[(row * self.grid.cols + col) as usize]
516    }
517
518    /// Sprites to draw at `t`, back to front: props, then the character (Buddy
519    /// on) or the unattended variant (Buddy off).
520    pub fn sprites_at(&self, t_ms: u64) -> Vec<SpriteInstance> {
521        let mut out = self.props.clone();
522        if self.buddy {
523            out.extend(self.character.map(|c| self.on_ground(c.at(t_ms), t_ms)));
524        } else {
525            out.extend_from_slice(&self.unattended);
526        }
527        out
528    }
529
530    /// The character placed for `t_ms`: on a journey its feet follow the
531    /// ground going by under them; otherwise unchanged.
532    pub fn on_ground(&self, mut s: SpriteInstance, t_ms: u64) -> SpriteInstance {
533        if let Some(j) = &self.journey
534            && s.kind == SpriteKind::Character
535            && let Some(y) = j.ground_at(self.grid.cell_w, self.grid.origin_x, t_ms)
536        {
537            s.y += y - self.ground_y;
538        }
539        s
540    }
541
542    /// Particles at time `t` that fall inside the grid, at their own pixel
543    /// positions (`particle.x`, `particle.y` are their centres).
544    pub fn particles_in_grid(&self, t_ms: u64) -> Vec<Particle> {
545        let g = &self.grid;
546        let (x0, y0) = (f64::from(g.origin_x), f64::from(g.origin_y));
547        let x1 = x0 + f64::from(g.cols * g.cell_w);
548        let y1 = y0 + f64::from(g.rows * g.cell_h);
549        self.emitters
550            .iter()
551            .flat_map(|e| e.sample(t_ms))
552            .filter(|p| p.x >= x0 && p.y >= y0 && p.x < x1 && p.y < y1)
553            .collect()
554    }
555
556    /// Particles at time `t`, snapped to cells, as `(col, row, particle)`.
557    pub fn particles_at(&self, t_ms: u64) -> Vec<(u32, u32, Particle)> {
558        let g = &self.grid;
559        let mut out = Vec::new();
560        for e in &self.emitters {
561            for p in e.sample(t_ms) {
562                let cx = (p.x - f64::from(g.origin_x)) / f64::from(g.cell_w);
563                let cy = (p.y - f64::from(g.origin_y)) / f64::from(g.cell_h);
564                if cx < 0.0 || cy < 0.0 {
565                    continue;
566                }
567                let (col, row) = (cx.floor() as u32, cy.floor() as u32);
568                if col < g.cols && row < g.rows {
569                    out.push((col, row, p));
570                }
571            }
572        }
573        out
574    }
575}