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