Skip to main content

clairlune_scene/
build.rs

1//! `build(recipe, size, theme, buddy) -> SceneGraph`.
2//!
3//! All layout math uses normalised coordinates (0..1) sampled at cell centres, so
4//! the same recipe gives the same landscape at any resolution; only the cell
5//! sampling changes. Buddy is a render flag: it changes sprites, never cells.
6
7use crate::activity::{Activity, builtin_catalog};
8use crate::glyphs::{self, EMPTY};
9use crate::graph::{Cell, Glow, Lighting, SceneGraph, grid_spec};
10use crate::hash::hash_label;
11use crate::math::pm;
12use crate::palette::{self, PaletteFamily, Theme};
13use crate::particles::{
14    Emitter, EmitterKind, LOOP_MS, WeatherKind, ember_set, hero_time, weather_set,
15};
16use crate::recipe::{GENERATOR_VERSION, SceneRecipe, TimeOfDay};
17use crate::rng::Rng;
18use crate::{focal, terrain};
19use std::fmt;
20
21/// Smallest supported output size.
22pub const MIN_WIDTH: u32 = 160;
23pub const MIN_HEIGHT: u32 = 90;
24
25/// Render-time inputs that are not part of the recipe.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct BuildOptions {
28    pub width: u32,
29    pub height: u32,
30    pub theme: Theme,
31    /// Show the character (Buddy toggle). Off draws the unattended variant.
32    pub buddy: bool,
33}
34
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub enum BuildError {
37    UnsupportedVersion(u32),
38    UnknownArchetype(String),
39    UnknownActivity(String),
40    UnknownPalette(String),
41    /// The recipe has no time of day for this theme.
42    ThemeLocked(Theme),
43    TooSmall {
44        width: u32,
45        height: u32,
46    },
47}
48
49impl fmt::Display for BuildError {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self {
52            BuildError::UnsupportedVersion(v) => write!(
53                f,
54                "recipe generator_version {v} is not supported (this build is version {GENERATOR_VERSION})"
55            ),
56            BuildError::UnknownArchetype(a) => write!(f, "unknown archetype `{a}`"),
57            BuildError::UnknownActivity(a) => write!(f, "unknown activity `{a}`"),
58            BuildError::UnknownPalette(p) => write!(f, "unknown palette family `{p}`"),
59            BuildError::ThemeLocked(t) => {
60                write!(f, "this scene has no {} variant (theme-locked)", t.as_str())
61            }
62            BuildError::TooSmall { width, height } => write!(
63                f,
64                "{width}x{height} is too small; the minimum is {MIN_WIDTH}x{MIN_HEIGHT}"
65            ),
66        }
67    }
68}
69
70impl std::error::Error for BuildError {}
71
72/// Builds the scene graph for one size, theme and Buddy state.
73pub fn build(recipe: &SceneRecipe, opts: &BuildOptions) -> Result<SceneGraph, BuildError> {
74    if recipe.generator_version != GENERATOR_VERSION {
75        return Err(BuildError::UnsupportedVersion(recipe.generator_version));
76    }
77    if opts.width < MIN_WIDTH || opts.height < MIN_HEIGHT {
78        return Err(BuildError::TooSmall {
79            width: opts.width,
80            height: opts.height,
81        });
82    }
83    let tod = recipe
84        .tod_for(opts.theme)
85        .ok_or(BuildError::ThemeLocked(opts.theme))?;
86    let family_id = match opts.theme {
87        Theme::Light => &recipe.palette.light,
88        Theme::Dark => &recipe.palette.dark,
89    };
90    let family =
91        *palette::family(family_id).ok_or_else(|| BuildError::UnknownPalette(family_id.clone()))?;
92    let activity = match &recipe.activity {
93        Some(id) => Some(
94            builtin_catalog()
95                .get(id)
96                .ok_or_else(|| BuildError::UnknownActivity(id.clone()))?,
97        ),
98        None => None,
99    };
100    if !terrain::PAINTED.contains(&recipe.archetype.as_str()) {
101        return Err(BuildError::UnknownArchetype(recipe.archetype.clone()));
102    }
103    Ok(build_scene(recipe, activity, opts, tod, family))
104}
105
106pub use crate::focal::sprite_scale;
107
108fn tod_glow(tod: TimeOfDay) -> f64 {
109    match tod {
110        TimeOfDay::Night => 1.0,
111        TimeOfDay::DeepDusk => 0.95,
112        TimeOfDay::Dusk => 0.85,
113        TimeOfDay::GoldenHour => 0.7,
114        TimeOfDay::Morning => 0.55,
115        TimeOfDay::Noon => 0.5,
116    }
117}
118
119/// The shared scene pipeline. The archetype only paints its background layers
120/// and its platform (`terrain`); everything else is the same for every scene.
121fn build_scene(
122    recipe: &SceneRecipe,
123    activity: Option<&Activity>,
124    opts: &BuildOptions,
125    tod: TimeOfDay,
126    family: PaletteFamily,
127) -> SceneGraph {
128    let (w, h) = (opts.width, opts.height);
129    let (wf, hf) = (f64::from(w), f64::from(h));
130    let aspect = wf / hf;
131    // Object sizes follow the short side; layout fractions follow width/height.
132    let unit = wf.min(hf);
133    let grid = grid_spec(w, h);
134    let comp = &recipe.composition;
135    let seed = recipe.seed;
136    let (cols, rows) = (grid.cols, grid.rows);
137    let mut cells = vec![Cell::default(); (cols * rows) as usize];
138
139    // ---- Focal group from the activity: character track, props, light. ----
140    let horizon = pm(comp.horizon_pm);
141    let platform_row = ((horizon * f64::from(rows)).round() as u32).clamp(rows / 3, rows - 4);
142    let ground_y = (grid.origin_y + platform_row * grid.cell_h) as i32;
143    let focal = focal::layout(recipe, activity, w, h, ground_y, grid.cell_w);
144    let (gx0, gx1, group_h) = (focal.x0, focal.x1, focal.height);
145    let group_cx = f64::from(gx0 + gx1) * 0.5;
146
147    let ctx = terrain::Ctx {
148        recipe,
149        co: terrain::Coords {
150            g: grid,
151            w: wf,
152            h: hf,
153        },
154        aspect,
155        unit,
156        cols,
157        rows,
158        horizon,
159        platform_row,
160        terrain: hash_label(seed, "terrain"),
161        gx0,
162        gx1,
163        group_cx,
164        tod,
165    };
166    let co = &ctx.co;
167
168    // ---- The archetype's background layers, painted back to front. ----
169    let sky_limit = terrain::background(&recipe.archetype, &ctx, &mut cells);
170
171    // ---- Breathing room: a dome over the focal group, cleared then dimmed. ----
172    let dome_cx = (group_cx - f64::from(grid.origin_x)) / f64::from(grid.cell_w);
173    let dome_a = f64::from(gx1 - gx0) * 0.5 / f64::from(grid.cell_w) + 3.0;
174    let dome_b = f64::from(group_h) / f64::from(grid.cell_h) + 2.0;
175    let dome = |col: u32, row: u32| -> f64 {
176        let u = (f64::from(col) + 0.5 - dome_cx) / dome_a;
177        let v = (f64::from(row) + 0.5 - f64::from(platform_row)) / dome_b;
178        let (u2, v2) = (u * u, v * v);
179        u2 * u2 + v2 * v2
180    };
181    for row in 0..platform_row {
182        for col in 0..cols {
183            let s = dome(col, row);
184            let cell = &mut cells[(row * cols + col) as usize];
185            if s <= 1.0 {
186                *cell = Cell::default();
187            } else if s <= 2.4 {
188                cell.shade = (f64::from(cell.shade) * 0.55).round() as u8;
189            }
190        }
191    }
192
193    // ---- The archetype's platform under the focal group. ----
194    terrain::platform(&recipe.archetype, &ctx, &mut cells);
195
196    // ---- Sky: stars at night, faint dust by day. Normalised positions, so the
197    // same stars appear at every resolution. ----
198    let (per_aspect, set, lo, hi): (f64, &[u8], f64, f64) = match tod {
199        TimeOfDay::Night => (150.0, &glyphs::STARS, 0.25, 0.75),
200        TimeOfDay::DeepDusk => (95.0, &glyphs::STARS, 0.20, 0.60),
201        TimeOfDay::Dusk => (50.0, &glyphs::STARS, 0.18, 0.50),
202        _ => (35.0, &glyphs::SKY_DUST, 0.12, 0.30),
203    };
204    let star_weights: &[u32] = if set.len() == glyphs::STARS.len() {
205        &[6, 4, 4, 3, 2, 1]
206    } else {
207        &[4, 3, 2, 2]
208    };
209    let mut sky = Rng::stream(seed, "sky");
210    let count = (per_aspect * aspect).round() as u32;
211    for _ in 0..count {
212        let x = sky.unit();
213        let y = sky.unit() * horizon;
214        let gi = sky.weighted_index(star_weights);
215        let shade = sky.range_f64(lo, hi);
216        let col = co.col_of(x * wf);
217        let row = ((y * hf - f64::from(grid.origin_y)) / f64::from(grid.cell_h)).floor() as i64;
218        if col < 0 || row < 0 || col >= i64::from(cols) || row >= i64::from(platform_row) {
219            continue;
220        }
221        let (col, row) = (col as u32, row as u32);
222        let idx = (row * cols + col) as usize;
223        if cells[idx].glyph != EMPTY
224            || co.ny(row) > sky_limit[col as usize] - 0.02
225            || dome(col, row) <= 2.4
226        {
227            continue;
228        }
229        let bright = gi == set.len() - 1;
230        cells[idx] = Cell {
231            glyph: set[gi],
232            shade: terrain::shade_u8(if bright { hi } else { shade }),
233        };
234    }
235
236    // ---- Light: vignette at the centre, warm glow around a light source. ----
237    let lighting = Lighting {
238        vignette_cx: wf * 0.5,
239        vignette_cy: hf * 0.5,
240        vignette_rx: wf * 0.75,
241        vignette_ry: hf * 0.75,
242        glow: focal.light.map(|l| Glow {
243            cx: l.cx,
244            cy: l.cy,
245            radius: 0.417 * unit * tod_glow(tod) * l.strength,
246        }),
247    };
248
249    // ---- Embers rising from a flame tip. The hero time comes from the seed's
250    // ember set either way, so it doesn't depend on the activity's props. ----
251    let embers = ember_set(seed);
252    let t_hero_ms = hero_time(&embers);
253    let emitters = focal
254        .embers_at
255        .map(|(x, y)| Emitter {
256            kind: EmitterKind::Embers,
257            origin_x: x,
258            origin_y: y,
259            unit,
260            intensity: match opts.theme {
261                Theme::Dark => 1.0,
262                Theme::Light => 0.85,
263            },
264            embers,
265            drops: Vec::new(),
266            size: (wf, hf),
267        })
268        .into_iter()
269        .collect();
270    // ---- Weather across the whole screen (fireflies only after dark). ----
271    let mut emitters: Vec<Emitter> = emitters;
272    if let Some(kind) = WeatherKind::from_id(&recipe.weather)
273        && (kind != WeatherKind::Fireflies
274            || matches!(
275                tod,
276                TimeOfDay::Dusk | TimeOfDay::DeepDusk | TimeOfDay::Night
277            ))
278    {
279        emitters.push(Emitter {
280            kind: EmitterKind::Weather(kind),
281            origin_x: 0.0,
282            origin_y: 0.0,
283            unit,
284            intensity: 1.0,
285            embers: Vec::new(),
286            drops: weather_set(kind, seed, aspect),
287            size: (wf, hf),
288        });
289    }
290
291    SceneGraph {
292        width: w,
293        height: h,
294        theme: opts.theme,
295        tod,
296        buddy: opts.buddy,
297        seed: recipe.seed,
298        family,
299        grid,
300        cells,
301        lighting,
302        activity: recipe.activity.clone(),
303        props: focal.props,
304        unattended: focal.unattended,
305        character: focal.character,
306        emitters,
307        ground_y,
308        t_hero_ms,
309        loop_ms: LOOP_MS,
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316    use crate::compose::compose;
317    use crate::graph::SpriteKind;
318    use crate::recipe::{Aspect, ContentContext};
319
320    fn graph(seed: u64, w: u32, h: u32, theme: Theme, buddy: bool) -> SceneGraph {
321        let r = compose(seed, Aspect::from_size(w, h), &ContentContext::default());
322        build(
323            &r,
324            &BuildOptions {
325                width: w,
326                height: h,
327                theme,
328                buddy,
329            },
330        )
331        .unwrap()
332    }
333
334    #[test]
335    fn grid_matches_plan_at_4k() {
336        let g = grid_spec(3840, 2160);
337        assert_eq!((g.cell_w, g.cell_h), (11, 20));
338        assert_eq!(g.rows, 108);
339        let small = grid_spec(640, 360);
340        assert_eq!((small.cell_w, small.cell_h), (6, 11));
341    }
342
343    #[test]
344    fn buddy_toggle_keeps_landscape() {
345        let a = graph(7, 960, 540, Theme::Dark, true);
346        let b = graph(7, 960, 540, Theme::Dark, false);
347        assert_eq!(a.cells, b.cells);
348        assert_eq!(a.lighting, b.lighting);
349        assert_ne!(a.sprites_at(0), b.sprites_at(0));
350    }
351
352    #[test]
353    fn feet_on_platform_top_at_all_times() {
354        for seed in 0..30 {
355            // Dark: every activity has a dark variant.
356            let g = graph(seed, 1280, 720, Theme::Dark, true);
357            let archetype = compose(
358                seed,
359                Aspect::from_size(1280, 720),
360                &ContentContext::default(),
361            )
362            .archetype;
363            let row = ((g.ground_y as u32) - g.grid.origin_y) / g.grid.cell_h;
364            for t in (0..20_000).step_by(1_250) {
365                let c = g
366                    .sprites_at(t)
367                    .into_iter()
368                    .find(|s| s.kind == SpriteKind::Character)
369                    .unwrap();
370                assert_eq!(c.y + c.height() as i32, g.ground_y);
371                assert!(c.x >= 0 && c.x + c.width() as i32 <= g.width as i32);
372                // The platform's top row is under the character's feet.
373                let col = ((c.x + c.width() as i32 / 2) as u32 - g.grid.origin_x) / g.grid.cell_w;
374                assert_eq!(
375                    g.cell(col, row).glyph,
376                    terrain::platform_top(&archetype),
377                    "seed {seed} t {t}"
378                );
379            }
380        }
381    }
382
383    #[test]
384    fn theme_locked_scenes_refuse_the_other_theme() {
385        let ctx = ContentContext {
386            enabled_activities: vec!["stargaze".into()],
387            ..ContentContext::default()
388        };
389        let r = compose(4, Aspect::from_size(16, 9), &ctx);
390        let opts = BuildOptions {
391            width: 640,
392            height: 360,
393            theme: Theme::Light,
394            buddy: true,
395        };
396        assert_eq!(
397            build(&r, &opts).unwrap_err(),
398            BuildError::ThemeLocked(Theme::Light)
399        );
400        assert!(
401            build(
402                &r,
403                &BuildOptions {
404                    theme: Theme::Dark,
405                    ..opts
406                }
407            )
408            .is_ok()
409        );
410    }
411
412    #[test]
413    fn props_never_overlap_the_character() {
414        for seed in 0..30 {
415            let g = graph(seed, 1920, 1080, Theme::Dark, true);
416            let track = g.character.unwrap();
417            let (lo, hi) = track.x_range();
418            let cw = track.at(0).width() as i32;
419            for p in &g.props {
420                let (px0, px1) = (p.x, p.x + p.width() as i32);
421                assert!(
422                    px1 <= lo || px0 >= hi + cw,
423                    "seed {seed}: {:?} overlaps the character's range",
424                    p.kind
425                );
426            }
427        }
428    }
429
430    #[test]
431    fn rejects_tiny_sizes_and_unknown_archetypes() {
432        let mut r = compose(1, Aspect::from_size(16, 9), &ContentContext::default());
433        let opts = BuildOptions {
434            width: 100,
435            height: 50,
436            theme: Theme::Dark,
437            buddy: true,
438        };
439        assert!(matches!(build(&r, &opts), Err(BuildError::TooSmall { .. })));
440        r.archetype = "volcano".into();
441        let opts = BuildOptions {
442            width: 640,
443            height: 360,
444            ..opts
445        };
446        assert!(matches!(
447            build(&r, &opts),
448            Err(BuildError::UnknownArchetype(_))
449        ));
450    }
451}