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::focal;
9use crate::glyphs::{self, EMPTY};
10use crate::graph::{Cell, Glow, GridSpec, Lighting, SceneGraph, grid_spec};
11use crate::hash::{hash_label, hash3, unit_from_hash};
12use crate::math::{clamp01, lerp, pm, pow, smoothstep};
13use crate::noise::{fbm1, fbm2, ridged1};
14use crate::palette::{self, PaletteFamily, Theme};
15use crate::particles::{Emitter, EmitterKind, LOOP_MS, ember_set, hero_time};
16use crate::recipe::{GENERATOR_VERSION, SceneRecipe, TimeOfDay};
17use crate::rng::Rng;
18use std::fmt;
19
20/// Smallest supported output size.
21pub const MIN_WIDTH: u32 = 160;
22pub const MIN_HEIGHT: u32 = 90;
23
24/// Render-time inputs that are not part of the recipe.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct BuildOptions {
27    pub width: u32,
28    pub height: u32,
29    pub theme: Theme,
30    /// Show the character (Buddy toggle). Off draws the unattended variant.
31    pub buddy: bool,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum BuildError {
36    UnsupportedVersion(u32),
37    UnknownArchetype(String),
38    UnknownActivity(String),
39    UnknownPalette(String),
40    /// The recipe has no time of day for this theme.
41    ThemeLocked(Theme),
42    TooSmall {
43        width: u32,
44        height: u32,
45    },
46}
47
48impl fmt::Display for BuildError {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        match self {
51            BuildError::UnsupportedVersion(v) => write!(
52                f,
53                "recipe generator_version {v} is not supported (this build is version {GENERATOR_VERSION})"
54            ),
55            BuildError::UnknownArchetype(a) => write!(f, "unknown archetype `{a}`"),
56            BuildError::UnknownActivity(a) => write!(f, "unknown activity `{a}`"),
57            BuildError::UnknownPalette(p) => write!(f, "unknown palette family `{p}`"),
58            BuildError::ThemeLocked(t) => {
59                write!(f, "this scene has no {} variant (theme-locked)", t.as_str())
60            }
61            BuildError::TooSmall { width, height } => write!(
62                f,
63                "{width}x{height} is too small; the minimum is {MIN_WIDTH}x{MIN_HEIGHT}"
64            ),
65        }
66    }
67}
68
69impl std::error::Error for BuildError {}
70
71/// Builds the scene graph for one size, theme and Buddy state.
72pub fn build(recipe: &SceneRecipe, opts: &BuildOptions) -> Result<SceneGraph, BuildError> {
73    if recipe.generator_version != GENERATOR_VERSION {
74        return Err(BuildError::UnsupportedVersion(recipe.generator_version));
75    }
76    if opts.width < MIN_WIDTH || opts.height < MIN_HEIGHT {
77        return Err(BuildError::TooSmall {
78            width: opts.width,
79            height: opts.height,
80        });
81    }
82    let tod = recipe
83        .tod_for(opts.theme)
84        .ok_or(BuildError::ThemeLocked(opts.theme))?;
85    let family_id = match opts.theme {
86        Theme::Light => &recipe.palette.light,
87        Theme::Dark => &recipe.palette.dark,
88    };
89    let family =
90        *palette::family(family_id).ok_or_else(|| BuildError::UnknownPalette(family_id.clone()))?;
91    let activity = match &recipe.activity {
92        Some(id) => Some(
93            builtin_catalog()
94                .get(id)
95                .ok_or_else(|| BuildError::UnknownActivity(id.clone()))?,
96        ),
97        None => None,
98    };
99    match recipe.archetype.as_str() {
100        "canyon" => Ok(canyon(recipe, activity, opts, tod, family)),
101        other => Err(BuildError::UnknownArchetype(other.to_string())),
102    }
103}
104
105pub use crate::focal::sprite_scale;
106
107/// Normalised cell-centre coordinates.
108struct Coords {
109    g: GridSpec,
110    w: f64,
111    h: f64,
112}
113
114impl Coords {
115    fn nx(&self, col: u32) -> f64 {
116        (f64::from(self.g.origin_x) + (f64::from(col) + 0.5) * f64::from(self.g.cell_w)) / self.w
117    }
118    fn ny(&self, row: u32) -> f64 {
119        (f64::from(self.g.origin_y) + (f64::from(row) + 0.5) * f64::from(self.g.cell_h)) / self.h
120    }
121    /// Column containing pixel x (may be outside the grid).
122    fn col_of(&self, px: f64) -> i64 {
123        ((px - f64::from(self.g.origin_x)) / f64::from(self.g.cell_w)).floor() as i64
124    }
125}
126
127/// One cliff layer of the canyon.
128struct CliffLayer {
129    left: &'static [u8],
130    right: &'static [u8],
131    center_top: f64,
132    edge_top: f64,
133    gap: f64,
134    rough: f64,
135    rough_freq: f64,
136    fx: f64,
137    fy: f64,
138    threshold: f64,
139    shade: f64,
140    seed: u64,
141}
142
143impl CliffLayer {
144    /// Silhouette top (normalised y) at normalised x.
145    fn top(&self, x: f64, center: f64, power: f64, aspect: f64) -> f64 {
146        let half = if x < center { center } else { 1.0 - center };
147        let d = ((x - center).abs() / half).min(1.0);
148        let s = clamp01((d - self.gap) / (1.0 - self.gap));
149        let shape = pow(smoothstep(0.0, 1.0, s), power);
150        let ridge = ridged1(self.seed, x * aspect * self.rough_freq, 4);
151        lerp(self.center_top, self.edge_top, shape) - self.rough * (ridge - 0.5)
152    }
153}
154
155fn shade_u8(s: f64) -> u8 {
156    (clamp01(s) * 255.0).round() as u8
157}
158
159/// Picks a glyph from a light-to-heavy family by density, with a seeded jitter of
160/// up to ±0.6 of a step so it doesn't band.
161fn family_glyph(
162    family: &[u8],
163    density: f64,
164    threshold: f64,
165    jitter_seed: u64,
166    col: u32,
167    row: u32,
168) -> u8 {
169    let n = family.len() as f64;
170    let jitter = (unit_from_hash(hash3(jitter_seed, i64::from(col), i64::from(row))) - 0.5) * 1.2;
171    let t = (density - threshold) / (1.0 - threshold) * n + jitter;
172    family[t.floor().clamp(0.0, n - 1.0) as usize]
173}
174
175fn tod_glow(tod: TimeOfDay) -> f64 {
176    match tod {
177        TimeOfDay::Night => 1.0,
178        TimeOfDay::DeepDusk => 0.95,
179        TimeOfDay::Dusk => 0.85,
180        TimeOfDay::GoldenHour => 0.7,
181        TimeOfDay::Morning => 0.55,
182        TimeOfDay::Noon => 0.5,
183    }
184}
185
186/// The canyon archetype: cliffs left and right, an open centre, and a rock ledge
187/// in the gap where the focal group stands. Ported from the prototype's description.
188fn canyon(
189    recipe: &SceneRecipe,
190    activity: Option<&Activity>,
191    opts: &BuildOptions,
192    tod: TimeOfDay,
193    family: PaletteFamily,
194) -> SceneGraph {
195    let (w, h) = (opts.width, opts.height);
196    let (wf, hf) = (f64::from(w), f64::from(h));
197    let aspect = wf / hf;
198    // Object sizes follow the short side; layout fractions follow width/height.
199    let unit = wf.min(hf);
200    let grid = grid_spec(w, h);
201    let co = Coords {
202        g: grid,
203        w: wf,
204        h: hf,
205    };
206    let comp = &recipe.composition;
207    let seed = recipe.seed;
208    let terrain = hash_label(seed, "terrain");
209    let (cols, rows) = (grid.cols, grid.rows);
210    let mut cells = vec![Cell::default(); (cols * rows) as usize];
211
212    // ---- Focal group from the activity: character track, props, light. ----
213    let horizon = pm(comp.horizon_pm);
214    let platform_row = ((horizon * f64::from(rows)).round() as u32).clamp(rows / 3, rows - 4);
215    let ground_y = (grid.origin_y + platform_row * grid.cell_h) as i32;
216    let focal = focal::layout(recipe, activity, w, h, ground_y, grid.cell_w);
217    let (gx0, gx1, group_h) = (focal.x0, focal.x1, focal.height);
218    let group_cx = f64::from(gx0 + gx1) * 0.5;
219
220    // ---- Cliff layers, painted back to front. ----
221    let center = 0.5 + (group_cx / wf - 0.5) * 0.6;
222    let gap = pm(comp.gap_pm);
223    let power = pm(comp.shape_pow_pm);
224    let layers = [
225        CliffLayer {
226            left: &glyphs::FAR_LEFT,
227            right: &glyphs::FAR_RIGHT,
228            center_top: horizon + 0.05,
229            edge_top: (horizon - 0.40).max(0.10),
230            gap: gap * 0.40,
231            rough: 0.07,
232            rough_freq: 9.0,
233            fx: 46.0,
234            fy: 5.0,
235            threshold: 0.30,
236            shade: 0.35,
237            seed: hash_label(terrain, "far"),
238        },
239        CliffLayer {
240            left: &glyphs::MID_LEFT,
241            right: &glyphs::MID_RIGHT,
242            center_top: horizon + 0.22,
243            edge_top: (horizon - 0.48).max(0.07),
244            gap: gap * 0.90,
245            rough: 0.10,
246            rough_freq: 6.0,
247            fx: 34.0,
248            fy: 4.0,
249            threshold: 0.32,
250            shade: 0.60,
251            seed: hash_label(terrain, "mid"),
252        },
253        CliffLayer {
254            left: &glyphs::NEAR,
255            right: &glyphs::NEAR,
256            center_top: 1.20,
257            edge_top: 0.03,
258            gap: (gap * 1.6).min(0.9),
259            rough: 0.12,
260            rough_freq: 4.0,
261            fx: 22.0,
262            fy: 3.0,
263            threshold: 0.30,
264            shade: 0.90,
265            seed: hash_label(terrain, "near"),
266        },
267    ];
268    // Highest silhouette per column, for the sky pass.
269    let mut sky_limit = vec![f64::INFINITY; cols as usize];
270    let jitter_seed = hash_label(terrain, "jitter");
271    for layer in &layers {
272        for col in 0..cols {
273            let nx = co.nx(col);
274            let top = layer.top(nx, center, power, aspect);
275            sky_limit[col as usize] = sky_limit[col as usize].min(top);
276            let family = if nx < center { layer.left } else { layer.right };
277            for row in 0..rows {
278                let ny = co.ny(row);
279                if ny < top {
280                    continue;
281                }
282                let depth = ny - top;
283                let n = fbm2(layer.seed, nx * aspect * layer.fx, ny * layer.fy, 4);
284                let mut d = clamp01((n - 0.5) * 1.9 + 0.5);
285                d *= 0.80 + 0.20 * smoothstep(0.0, 0.10, depth);
286                if d < layer.threshold {
287                    continue; // hole: farther layers show through
288                }
289                let glyph = family_glyph(
290                    family,
291                    d,
292                    layer.threshold,
293                    jitter_seed ^ layer.seed,
294                    col,
295                    row,
296                );
297                let rows_below_top = depth * f64::from(rows);
298                let mut shade = layer.shade * (0.55 + 0.45 * (rows_below_top / 6.0).min(1.0));
299                if row > platform_row {
300                    shade *= 0.5; // ledges below the platform line recede
301                }
302                cells[(row * cols + col) as usize] = Cell {
303                    glyph,
304                    shade: shade_u8(shade),
305                };
306            }
307        }
308    }
309
310    // ---- Breathing room: a dome over the focal group, cleared then dimmed. ----
311    let dome_cx = (group_cx - f64::from(grid.origin_x)) / f64::from(grid.cell_w);
312    let dome_a = f64::from(gx1 - gx0) * 0.5 / f64::from(grid.cell_w) + 3.0;
313    let dome_b = f64::from(group_h) / f64::from(grid.cell_h) + 2.0;
314    let dome = |col: u32, row: u32| -> f64 {
315        let u = (f64::from(col) + 0.5 - dome_cx) / dome_a;
316        let v = (f64::from(row) + 0.5 - f64::from(platform_row)) / dome_b;
317        let (u2, v2) = (u * u, v * v);
318        u2 * u2 + v2 * v2
319    };
320    for row in 0..platform_row {
321        for col in 0..cols {
322            let s = dome(col, row);
323            let cell = &mut cells[(row * cols + col) as usize];
324            if s <= 1.0 {
325                *cell = Cell::default();
326            } else if s <= 2.4 {
327                cell.shade = (f64::from(cell.shade) * 0.55).round() as u8;
328            }
329        }
330    }
331
332    // ---- Platform: a rock ledge rising from the bottom, widening downward. ----
333    let platform_seed = hash_label(terrain, "platform");
334    let margin_px = pm(comp.platform_margin_pm) * unit + 2.0 * f64::from(grid.cell_w);
335    let pc0 = co.col_of(f64::from(gx0) - margin_px);
336    let pc1 = co.col_of(f64::from(gx1) + margin_px);
337    let span_rows = f64::from(rows - platform_row);
338    for row in platform_row..rows {
339        let k = f64::from(row - platform_row);
340        let widen = if k < 3.0 {
341            0.6 * k
342        } else {
343            1.8 + 0.25 * (k - 3.0)
344        };
345        // Edge noise fades in over the first rows, so the top always spans the group.
346        let rough = 9.0 * (k / 3.0).min(1.0);
347        let el = (fbm1(hash_label(platform_seed, "left"), k * 0.22, 3) - 0.5) * rough;
348        let er = (fbm1(hash_label(platform_seed, "right"), k * 0.22, 3) - 0.5) * rough;
349        let c0 = (pc0 as f64 - widen - el).round() as i64;
350        let c1 = (pc1 as f64 + widen + er).round() as i64;
351        // One empty cell of separation so the ledge reads as its own object.
352        for c in [c0 - 1, c1 + 1] {
353            if (0..i64::from(cols)).contains(&c) {
354                cells[(row * cols + c as u32) as usize] = Cell::default();
355            }
356        }
357        let fade = smoothstep(0.0, 1.0, k / span_rows);
358        for c in c0.max(0)..=c1.min(i64::from(cols) - 1) {
359            let col = c as u32;
360            let idx = (row * cols + col) as usize;
361            if k == 0.0 {
362                cells[idx] = Cell {
363                    glyph: glyphs::PLATFORM_TOP,
364                    shade: shade_u8(0.85),
365                };
366                continue;
367            }
368            let n = fbm2(
369                platform_seed,
370                co.nx(col) * aspect * 9.0,
371                co.ny(row) * 38.0,
372                3,
373            );
374            // Biased toward the lighter end of the family so the ledge isn't a solid block.
375            let d = clamp01((n - 0.5) * 1.8 + 0.42);
376            let threshold = 0.20;
377            if d < threshold && k > 1.0 {
378                cells[idx] = Cell::default();
379                continue;
380            }
381            let glyph = family_glyph(
382                &glyphs::PLATFORM,
383                d.max(threshold),
384                threshold,
385                platform_seed,
386                col,
387                row,
388            );
389            cells[idx] = Cell {
390                glyph,
391                shade: shade_u8(lerp(0.80, 0.40, fade)),
392            };
393        }
394    }
395
396    // ---- Sky: stars at night, faint dust by day. Normalised positions, so the
397    // same stars appear at every resolution. ----
398    let (per_aspect, set, lo, hi): (f64, &[u8], f64, f64) = match tod {
399        TimeOfDay::Night => (150.0, &glyphs::STARS, 0.25, 0.75),
400        TimeOfDay::DeepDusk => (95.0, &glyphs::STARS, 0.20, 0.60),
401        TimeOfDay::Dusk => (50.0, &glyphs::STARS, 0.18, 0.50),
402        _ => (35.0, &glyphs::SKY_DUST, 0.12, 0.30),
403    };
404    let star_weights: &[u32] = if set.len() == glyphs::STARS.len() {
405        &[6, 4, 4, 3, 2, 1]
406    } else {
407        &[4, 3, 2, 2]
408    };
409    let mut sky = Rng::stream(seed, "sky");
410    let count = (per_aspect * aspect).round() as u32;
411    for _ in 0..count {
412        let x = sky.unit();
413        let y = sky.unit() * horizon;
414        let gi = sky.weighted_index(star_weights);
415        let shade = sky.range_f64(lo, hi);
416        let col = co.col_of(x * wf);
417        let row = ((y * hf - f64::from(grid.origin_y)) / f64::from(grid.cell_h)).floor() as i64;
418        if col < 0 || row < 0 || col >= i64::from(cols) || row >= i64::from(platform_row) {
419            continue;
420        }
421        let (col, row) = (col as u32, row as u32);
422        let idx = (row * cols + col) as usize;
423        if cells[idx].glyph != EMPTY
424            || co.ny(row) > sky_limit[col as usize] - 0.02
425            || dome(col, row) <= 2.4
426        {
427            continue;
428        }
429        let bright = gi == set.len() - 1;
430        cells[idx] = Cell {
431            glyph: set[gi],
432            shade: shade_u8(if bright { hi } else { shade }),
433        };
434    }
435
436    // ---- Light: vignette at the centre, warm glow around a light source. ----
437    let lighting = Lighting {
438        vignette_cx: wf * 0.5,
439        vignette_cy: hf * 0.5,
440        vignette_rx: wf * 0.75,
441        vignette_ry: hf * 0.75,
442        glow: focal.light.map(|l| Glow {
443            cx: l.cx,
444            cy: l.cy,
445            radius: 0.417 * unit * tod_glow(tod) * l.strength,
446        }),
447    };
448
449    // ---- Embers rising from a flame tip. The hero time comes from the seed's
450    // ember set either way, so it doesn't depend on the activity's props. ----
451    let embers = ember_set(seed);
452    let t_hero_ms = hero_time(&embers);
453    let emitters = focal
454        .embers_at
455        .map(|(x, y)| Emitter {
456            kind: EmitterKind::Embers,
457            origin_x: x,
458            origin_y: y,
459            unit,
460            intensity: match opts.theme {
461                Theme::Dark => 1.0,
462                Theme::Light => 0.85,
463            },
464            embers,
465        })
466        .into_iter()
467        .collect();
468
469    SceneGraph {
470        width: w,
471        height: h,
472        theme: opts.theme,
473        tod,
474        buddy: opts.buddy,
475        family,
476        grid,
477        cells,
478        lighting,
479        activity: recipe.activity.clone(),
480        props: focal.props,
481        unattended: focal.unattended,
482        character: focal.character,
483        emitters,
484        ground_y,
485        t_hero_ms,
486        loop_ms: LOOP_MS,
487    }
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493    use crate::compose::compose;
494    use crate::graph::SpriteKind;
495    use crate::recipe::{Aspect, ContentContext};
496
497    fn graph(seed: u64, w: u32, h: u32, theme: Theme, buddy: bool) -> SceneGraph {
498        let r = compose(seed, Aspect::from_size(w, h), &ContentContext::default());
499        build(
500            &r,
501            &BuildOptions {
502                width: w,
503                height: h,
504                theme,
505                buddy,
506            },
507        )
508        .unwrap()
509    }
510
511    #[test]
512    fn grid_matches_plan_at_4k() {
513        let g = grid_spec(3840, 2160);
514        assert_eq!((g.cell_w, g.cell_h), (11, 20));
515        assert_eq!(g.rows, 108);
516        let small = grid_spec(640, 360);
517        assert_eq!((small.cell_w, small.cell_h), (6, 11));
518    }
519
520    #[test]
521    fn buddy_toggle_keeps_landscape() {
522        let a = graph(7, 960, 540, Theme::Dark, true);
523        let b = graph(7, 960, 540, Theme::Dark, false);
524        assert_eq!(a.cells, b.cells);
525        assert_eq!(a.lighting, b.lighting);
526        assert_ne!(a.sprites_at(0), b.sprites_at(0));
527    }
528
529    #[test]
530    fn feet_on_platform_top_at_all_times() {
531        for seed in 0..30 {
532            // Dark: every activity has a dark variant.
533            let g = graph(seed, 1280, 720, Theme::Dark, true);
534            let row = ((g.ground_y as u32) - g.grid.origin_y) / g.grid.cell_h;
535            for t in (0..20_000).step_by(1_250) {
536                let c = g
537                    .sprites_at(t)
538                    .into_iter()
539                    .find(|s| s.kind == SpriteKind::Character)
540                    .unwrap();
541                assert_eq!(c.y + c.height() as i32, g.ground_y);
542                assert!(c.x >= 0 && c.x + c.width() as i32 <= g.width as i32);
543                // The platform's top row is under the character's feet.
544                let col = ((c.x + c.width() as i32 / 2) as u32 - g.grid.origin_x) / g.grid.cell_w;
545                assert_eq!(
546                    g.cell(col, row).glyph,
547                    glyphs::PLATFORM_TOP,
548                    "seed {seed} t {t}"
549                );
550            }
551        }
552    }
553
554    #[test]
555    fn theme_locked_scenes_refuse_the_other_theme() {
556        let ctx = ContentContext {
557            enabled_activities: vec!["stargaze".into()],
558            ..ContentContext::default()
559        };
560        let r = compose(4, Aspect::from_size(16, 9), &ctx);
561        let opts = BuildOptions {
562            width: 640,
563            height: 360,
564            theme: Theme::Light,
565            buddy: true,
566        };
567        assert_eq!(
568            build(&r, &opts).unwrap_err(),
569            BuildError::ThemeLocked(Theme::Light)
570        );
571        assert!(
572            build(
573                &r,
574                &BuildOptions {
575                    theme: Theme::Dark,
576                    ..opts
577                }
578            )
579            .is_ok()
580        );
581    }
582
583    #[test]
584    fn props_never_overlap_the_character() {
585        for seed in 0..30 {
586            let g = graph(seed, 1920, 1080, Theme::Dark, true);
587            let track = g.character.unwrap();
588            let (lo, hi) = track.x_range();
589            let cw = track.at(0).width() as i32;
590            for p in &g.props {
591                let (px0, px1) = (p.x, p.x + p.width() as i32);
592                assert!(
593                    px1 <= lo || px0 >= hi + cw,
594                    "seed {seed}: {:?} overlaps the character's range",
595                    p.kind
596                );
597            }
598        }
599    }
600
601    #[test]
602    fn rejects_tiny_sizes_and_unknown_archetypes() {
603        let mut r = compose(1, Aspect::from_size(16, 9), &ContentContext::default());
604        let opts = BuildOptions {
605            width: 100,
606            height: 50,
607            theme: Theme::Dark,
608            buddy: true,
609        };
610        assert!(matches!(build(&r, &opts), Err(BuildError::TooSmall { .. })));
611        r.archetype = "volcano".into();
612        let opts = BuildOptions {
613            width: 640,
614            height: 360,
615            ..opts
616        };
617        assert!(matches!(
618            build(&r, &opts),
619            Err(BuildError::UnknownArchetype(_))
620        ));
621    }
622}