1use crate::activity::{Activity, Catalog, builtin_catalog};
8use crate::glyphs::{self, EMPTY};
9use crate::graph::{Cell, Glow, Lighting, SceneGraph, grid_for};
10use crate::hash::hash_label;
11use crate::math::pm;
12use crate::palette::{self, PaletteFamily, Theme};
13use crate::particles::{
14 CALM_PACE, Emitter, EmitterKind, LOOP_MS, WeatherKind, ember_set, hero_time, weather_set,
15};
16use crate::recipe::{GENERATOR_VERSION, OLDEST_GENERATOR_VERSION, SceneRecipe, TimeOfDay};
17use crate::rng::Rng;
18use crate::{focal, terrain};
19use std::fmt;
20
21pub const MIN_WIDTH: u32 = 160;
23pub const MIN_HEIGHT: u32 = 90;
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct BuildOptions {
28 pub width: u32,
29 pub height: u32,
30 pub theme: Theme,
31 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 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
72pub fn build(recipe: &SceneRecipe, opts: &BuildOptions) -> Result<SceneGraph, BuildError> {
74 build_with(builtin_catalog(), recipe, opts)
75}
76
77pub fn build_with(
80 catalog: &Catalog,
81 recipe: &SceneRecipe,
82 opts: &BuildOptions,
83) -> Result<SceneGraph, BuildError> {
84 if !(OLDEST_GENERATOR_VERSION..=GENERATOR_VERSION).contains(&recipe.generator_version) {
85 return Err(BuildError::UnsupportedVersion(recipe.generator_version));
86 }
87 if opts.width < MIN_WIDTH || opts.height < MIN_HEIGHT {
88 return Err(BuildError::TooSmall {
89 width: opts.width,
90 height: opts.height,
91 });
92 }
93 let tod = recipe
94 .tod_for(opts.theme)
95 .ok_or(BuildError::ThemeLocked(opts.theme))?;
96 let family_id = match opts.theme {
97 Theme::Light => &recipe.palette.light,
98 Theme::Dark => &recipe.palette.dark,
99 };
100 let family =
101 *palette::family(family_id).ok_or_else(|| BuildError::UnknownPalette(family_id.clone()))?;
102 let activity = match &recipe.activity {
103 Some(id) => Some(
104 catalog
105 .get(id)
106 .ok_or_else(|| BuildError::UnknownActivity(id.clone()))?,
107 ),
108 None => None,
109 };
110 if !terrain::PAINTED.contains(&recipe.archetype.as_str()) {
111 return Err(BuildError::UnknownArchetype(recipe.archetype.clone()));
112 }
113 Ok(build_scene(recipe, activity, opts, tod, family))
114}
115
116pub use crate::focal::sprite_scale;
117
118fn tod_glow(tod: TimeOfDay) -> f64 {
119 match tod {
120 TimeOfDay::Night => 1.0,
121 TimeOfDay::DeepDusk => 0.95,
122 TimeOfDay::Dusk => 0.85,
123 TimeOfDay::GoldenHour => 0.7,
124 TimeOfDay::Morning => 0.55,
125 TimeOfDay::Noon => 0.5,
126 }
127}
128
129fn build_scene(
132 recipe: &SceneRecipe,
133 activity: Option<&Activity>,
134 opts: &BuildOptions,
135 tod: TimeOfDay,
136 family: PaletteFamily,
137) -> SceneGraph {
138 let pace = if recipe.generator_version >= 4 {
141 CALM_PACE
142 } else {
143 0
144 };
145 let (w, h) = (opts.width, opts.height);
146 let (wf, hf) = (f64::from(w), f64::from(h));
147 let aspect = wf / hf;
148 let unit = wf.min(hf);
150 let zoom = recipe.zoom_factor();
151 let grid = grid_for(w, h, zoom);
152 let comp = &recipe.composition;
153 let seed = recipe.seed;
154 let (cols, rows) = (grid.cols, grid.rows);
155 let mut cells = vec![Cell::default(); (cols * rows) as usize];
156
157 let horizon = pm(comp.horizon_pm);
159 let platform_row = ((horizon * f64::from(rows)).round() as u32).clamp(rows / 3, rows - 4);
160 let ground_y = (grid.origin_y + platform_row * grid.cell_h) as i32;
161 let focal = focal::layout(recipe, activity, w, h, ground_y, grid.cell_w, grid.cell_h);
162 let (gx0, gx1, group_h) = (focal.x0, focal.x1, focal.height);
163 let group_cx = f64::from(gx0 + gx1) * 0.5;
164
165 let ctx = terrain::Ctx {
166 recipe,
167 co: terrain::Coords {
168 g: grid,
169 w: wf,
170 h: hf,
171 },
172 aspect,
173 unit,
174 cols,
175 rows,
176 horizon,
177 platform_row,
178 terrain: hash_label(seed, "terrain"),
179 gx0,
180 gx1,
181 group_cx,
182 tod,
183 unsheltered: std::cell::RefCell::new(vec![None; cols as usize]),
184 };
185 let co = &ctx.co;
186
187 let journeying = recipe.is_journey()
191 && activity.is_some_and(|a| a.motion.kind == crate::activity::MotionKind::Journey);
192 let journeyed = if journeying {
193 terrain::journey(&recipe.archetype, &ctx, &mut cells)
194 } else {
195 None
196 };
197 let sky_limit = match &journeyed {
198 Some(j) => j.sky_limit.clone(),
199 None => terrain::background(&recipe.archetype, &ctx, &mut cells),
200 };
201
202 let dome_cx = (group_cx - f64::from(grid.origin_x)) / f64::from(grid.cell_w);
204 let dome_a = f64::from(gx1 - gx0) * 0.5 / f64::from(grid.cell_w) + 3.0;
205 let dome_b = f64::from(group_h) / f64::from(grid.cell_h) + 2.0;
206 let dome = |col: u32, row: u32| -> f64 {
207 let u = (f64::from(col) + 0.5 - dome_cx) / dome_a;
208 let v = (f64::from(row) + 0.5 - f64::from(platform_row)) / dome_b;
209 let (u2, v2) = (u * u, v * v);
210 u2 * u2 + v2 * v2
211 };
212 let dome_rows = if journeyed.is_some() { 0 } else { platform_row };
214 let flight = activity
217 .and_then(|a| a.motion.altitude)
218 .filter(|_| journeyed.is_some());
219 if let (Some(alt), Some(track)) = (flight, focal.character) {
220 let cw = f64::from(crate::graph::CHARACTER_BOX.0 * track.scale);
221 let fx = f64::from(track.x_range().0) + cw * 0.5;
222 let fy = alt * hf - f64::from(group_h) * 0.5;
223 let a = (cw * 0.5 + 3.0 * f64::from(grid.cell_w)) / f64::from(grid.cell_w);
224 let b = (f64::from(group_h) * 0.5 + 0.03 * hf) / f64::from(grid.cell_h) + 2.0;
225 let (ccx, ccy) = (
226 (fx - f64::from(grid.origin_x)) / f64::from(grid.cell_w),
227 (fy - f64::from(grid.origin_y)) / f64::from(grid.cell_h),
228 );
229 for row in 0..rows {
230 for col in 0..cols {
231 let u = (f64::from(col) + 0.5 - ccx) / a;
232 let v = (f64::from(row) + 0.5 - ccy) / b;
233 let s = u * u * u * u + v * v * v * v;
234 let cell = &mut cells[(row * cols + col) as usize];
235 if s <= 1.0 {
236 *cell = Cell::default();
237 } else if s <= 2.4 {
238 cell.shade = (f64::from(cell.shade) * 0.55).round() as u8;
239 }
240 }
241 }
242 }
243 for row in 0..dome_rows {
244 for col in 0..cols {
245 let s = dome(col, row);
246 let cell = &mut cells[(row * cols + col) as usize];
247 if s <= 1.0 {
248 *cell = Cell::default();
249 } else if s <= 2.4 {
250 cell.shade = (f64::from(cell.shade) * 0.55).round() as u8;
251 }
252 }
253 }
254
255 let before_platform = (recipe.look == "dither").then(|| cells.clone());
260 if journeyed.is_none() {
261 terrain::platform(&recipe.archetype, &ctx, &mut cells);
262 }
263 if let (Some(a), Some(track)) = (activity, focal.character)
265 && a.trail.as_deref() == Some("ski_tracks")
266 && platform_row + 1 < rows
267 {
268 let (lo, hi) = track.x_range();
269 let cw = (crate::graph::CHARACTER_BOX.0 * track.scale) as i32;
270 let c0 = co.col_of(f64::from(lo)).max(0) as u32;
271 let c1 = (co.col_of(f64::from(hi + cw)).max(0) as u32).min(cols - 1);
272 for col in c0..=c1 {
273 let glyph = if col % 5 == 0 {
274 glyphs::id('-')
275 } else {
276 glyphs::id('=')
277 };
278 cells[((platform_row + 1) * cols + col) as usize] = Cell {
279 glyph,
280 shade: terrain::shade_u8(0.55),
281 };
282 }
283 }
284 let water = (recipe.archetype == "shore").then(|| terrain::shore::open_water(&ctx));
285
286 let (per_aspect, set, lo, hi): (f64, &[u8], f64, f64) = match tod {
289 TimeOfDay::Night => (150.0, &glyphs::STARS, 0.25, 0.75),
290 TimeOfDay::DeepDusk => (95.0, &glyphs::STARS, 0.20, 0.60),
291 TimeOfDay::Dusk => (50.0, &glyphs::STARS, 0.18, 0.50),
292 _ => (35.0, &glyphs::SKY_DUST, 0.12, 0.30),
293 };
294 let star_weights: &[u32] = if set.len() == glyphs::STARS.len() {
295 &[6, 4, 4, 3, 2, 1]
296 } else {
297 &[4, 3, 2, 2]
298 };
299 let mut sky = Rng::stream(seed, "sky");
300 let count = (per_aspect * aspect).round() as u32;
301 for _ in 0..count {
302 let x = sky.unit();
303 let y = sky.unit() * horizon;
304 let gi = sky.weighted_index(star_weights);
305 let shade = sky.range_f64(lo, hi);
306 let col = co.col_of(x * wf);
307 let row = ((y * hf - f64::from(grid.origin_y)) / f64::from(grid.cell_h)).floor() as i64;
308 if col < 0 || row < 0 || col >= i64::from(cols) || row >= i64::from(platform_row) {
309 continue;
310 }
311 let (col, row) = (col as u32, row as u32);
312 let idx = (row * cols + col) as usize;
313 if cells[idx].glyph != EMPTY
314 || co.ny(row) > sky_limit[col as usize] - 0.02
315 || (journeyed.is_none() && dome(col, row) <= 2.4)
316 {
317 continue;
318 }
319 let bright = gi == set.len() - 1;
320 cells[idx] = Cell {
321 glyph: set[gi],
322 shade: terrain::shade_u8(if bright { hi } else { shade }),
323 };
324 }
325
326 if recipe.look == "dither" {
328 let land_line = ctx.land_line(&sky_limit);
329 let ground: Vec<bool> = match &before_platform {
330 Some(before) => before.iter().zip(&cells).map(|(a, b)| a != b).collect(),
331 None => vec![false; cells.len()],
332 };
333 crate::look::dither(
334 &ctx,
335 &mut cells,
336 &crate::look::Dither {
337 sky_limit: &land_line,
338 theme: opts.theme,
339 tod,
340 contrast: &recipe.contrast,
341 dome: &dome,
342 sea_top: (recipe.archetype == "shore").then(|| terrain::shore::sea_top(&ctx)),
343 ground: &ground,
344 },
345 );
346 } else {
347 crate::look::line_contrast(&mut cells, &recipe.contrast);
348 }
349
350 let lighting = Lighting {
352 vignette_cx: wf * 0.5,
353 vignette_cy: hf * 0.5,
354 vignette_rx: wf * 0.75,
355 vignette_ry: hf * 0.75,
356 glow: focal.light.map(|l| Glow {
357 cx: l.cx,
358 cy: l.cy,
359 radius: 0.417 * unit * zoom * tod_glow(tod) * l.strength,
360 }),
361 };
362
363 let embers = ember_set(seed, pace);
366 let t_hero_ms = hero_time(&embers);
367 let emitters = focal
368 .embers_at
369 .map(|(x, y)| Emitter {
370 kind: EmitterKind::Embers,
371 origin_x: x,
372 origin_y: y,
373 unit: unit * zoom,
375 intensity: match opts.theme {
376 Theme::Dark => 1.0,
377 Theme::Light => 0.85,
378 },
379 embers,
380 drops: Vec::new(),
381 size: (wf, hf),
382 pace,
383 })
384 .into_iter()
385 .collect();
386 let mut emitters: Vec<Emitter> = emitters;
389 if let Some(kind) = WeatherKind::from_id(&recipe.weather)
390 && (kind != WeatherKind::Confetti || recipe.generator_version >= 4)
392 && kind.shows_at(tod)
393 {
394 emitters.push(Emitter {
395 kind: EmitterKind::Weather(kind),
396 origin_x: 0.0,
397 origin_y: 0.0,
398 unit,
399 intensity: 1.0,
400 embers: Vec::new(),
401 drops: weather_set(kind, seed, aspect, pace),
402 size: (wf, hf),
403 pace,
404 });
405 }
406
407 let journey = journeyed.zip(focal.character).map(|(j, track)| {
410 let cw = (crate::graph::CHARACTER_BOX.0 * track.scale) as i64;
411 let feet_x = track.x_range().0 + (cw / 2) as i32;
412 let half = (cw * 3 / 10).max(1);
413 let n = j.surface.len() as i64;
414 let under = |x: i64| {
415 (x - half..=x + half)
416 .map(|k| j.surface[k.rem_euclid(n) as usize])
417 .fold(f64::INFINITY, f64::min)
418 };
419 let ground = match activity.and_then(|a| a.motion.altitude) {
420 Some(alt) => {
423 let clear = 0.05 * hf;
424 (0..n)
425 .map(|x| {
426 let wave =
427 crate::math::sin(crate::math::TAU * 2.0 * x as f64 / n.max(1) as f64);
428 let line = alt * hf + 0.012 * hf * wave;
429 line.min(under(x) - clear).max(f64::from(group_h)).round() as i32
430 })
431 .collect()
432 }
433 None => (0..n).map(|x| under(x).round() as i32).collect(),
434 };
435 let mut layers = j.layers;
436 for l in &mut layers {
437 if recipe.look == "dither" {
438 crate::look::dither_strip(&mut l.cells, l.cols, opts.theme, &recipe.contrast);
439 } else {
440 crate::look::line_contrast(&mut l.cells, &recipe.contrast);
441 }
442 }
443 let loop_ms = if comp.journey_pace_c > 0 {
447 let near = layers.last().map_or(0, |l| u64::from(l.cols * l.turns));
448 let ms = near * 100_000 / u64::from(comp.journey_pace_c);
449 let step = LOOP_MS;
450 ((ms + step / 2) / step).max(2) * step
451 } else {
452 u64::from(comp.journey_ms)
453 };
454 crate::graph::Journey {
455 loop_ms,
456 layers,
457 ground,
458 feet_x,
459 }
460 });
461
462 SceneGraph {
463 width: w,
464 height: h,
465 theme: opts.theme,
466 tod,
467 buddy: opts.buddy,
468 seed: recipe.seed,
469 family,
470 grid,
471 cells,
472 lighting,
473 activity: recipe.activity.clone(),
474 props: focal.props,
475 unattended: focal.unattended,
476 character: focal.character,
477 emitters,
478 ground_y,
479 t_hero_ms,
480 loop_ms: LOOP_MS,
481 pace,
482 generator: recipe.generator_version,
483 water,
484 journey,
485 zoom,
486 }
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492 use crate::compose::compose;
493 use crate::graph::SpriteKind;
494 use crate::graph::grid_spec;
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 let theme = if r.tod_for(theme).is_some() {
501 theme
502 } else {
503 match theme {
504 Theme::Dark => Theme::Light,
505 Theme::Light => Theme::Dark,
506 }
507 };
508 build(
509 &r,
510 &BuildOptions {
511 width: w,
512 height: h,
513 theme,
514 buddy,
515 },
516 )
517 .unwrap()
518 }
519
520 #[test]
521 fn grid_matches_plan_at_4k() {
522 let g = grid_spec(3840, 2160);
523 assert_eq!((g.cell_w, g.cell_h), (11, 20));
524 assert_eq!(g.rows, 108);
525 let small = grid_spec(640, 360);
526 assert_eq!((small.cell_w, small.cell_h), (6, 11));
527 }
528
529 #[test]
530 fn buddy_toggle_keeps_landscape() {
531 let a = graph(7, 960, 540, Theme::Dark, true);
532 let b = graph(7, 960, 540, Theme::Dark, false);
533 assert_eq!(a.cells, b.cells);
534 assert_eq!(a.lighting, b.lighting);
535 assert_ne!(a.sprites_at(0), b.sprites_at(0));
536 }
537
538 #[test]
539 fn feet_on_platform_top_at_all_times() {
540 for seed in 0..30 {
541 let g = graph(seed, 1280, 720, Theme::Dark, true);
543 let archetype = compose(
544 seed,
545 Aspect::from_size(1280, 720),
546 &ContentContext::default(),
547 )
548 .archetype;
549 let row = ((g.ground_y as u32) - g.grid.origin_y) / g.grid.cell_h;
550 for t in (0..20_000).step_by(1_250) {
551 let c = g
552 .sprites_at(t)
553 .into_iter()
554 .find(|s| s.kind == SpriteKind::Character)
555 .unwrap();
556 if g.character.is_some_and(|t| t.flies()) {
557 assert!(c.y >= 0 && c.y + c.height() as i32 <= g.height as i32);
559 continue;
560 }
561 if let Some(j) = &g.journey {
562 let ground = j.ground_at(g.grid.cell_w, g.grid.origin_x, t).unwrap();
564 assert_eq!(c.y + c.height() as i32, ground, "seed {seed} t {t}");
565 assert!(c.y >= 0 && ground < g.height as i32);
566 continue;
567 }
568 assert_eq!(c.y + c.height() as i32, g.ground_y);
569 assert!(c.x >= 0 && c.x + c.width() as i32 <= g.width as i32);
570 let col = ((c.x + c.width() as i32 / 2) as u32 - g.grid.origin_x) / g.grid.cell_w;
572 assert_eq!(
573 g.cell(col, row).glyph,
574 terrain::platform_top(&archetype),
575 "seed {seed} t {t}"
576 );
577 }
578 }
579 }
580
581 #[test]
582 fn theme_locked_scenes_refuse_the_other_theme() {
583 let ctx = ContentContext {
584 enabled_activities: vec!["stargaze".into()],
585 ..ContentContext::default()
586 };
587 let r = compose(4, Aspect::from_size(16, 9), &ctx);
588 let opts = BuildOptions {
589 width: 640,
590 height: 360,
591 theme: Theme::Light,
592 buddy: true,
593 };
594 assert_eq!(
595 build(&r, &opts).unwrap_err(),
596 BuildError::ThemeLocked(Theme::Light)
597 );
598 assert!(
599 build(
600 &r,
601 &BuildOptions {
602 theme: Theme::Dark,
603 ..opts
604 }
605 )
606 .is_ok()
607 );
608 }
609
610 #[test]
611 fn props_never_overlap_the_character() {
612 for seed in 0..30 {
613 let g = graph(seed, 1920, 1080, Theme::Dark, true);
614 let track = g.character.unwrap();
615 if track.flies() {
616 continue; }
618 let (lo, hi) = track.x_range();
619 let cw = track.at(0).width() as i32;
620 for p in &g.props {
621 let (px0, px1) = (p.x, p.x + p.width() as i32);
622 assert!(
623 px1 <= lo || px0 >= hi + cw,
624 "seed {seed}: {:?} overlaps the character's range",
625 p.kind
626 );
627 }
628 }
629 }
630
631 #[test]
632 fn rejects_tiny_sizes_and_unknown_archetypes() {
633 let mut r = compose(1, Aspect::from_size(16, 9), &ContentContext::default());
634 let theme = if r.tod_for(Theme::Dark).is_some() {
636 Theme::Dark
637 } else {
638 Theme::Light
639 };
640 let opts = BuildOptions {
641 width: 100,
642 height: 50,
643 theme,
644 buddy: true,
645 };
646 assert!(matches!(build(&r, &opts), Err(BuildError::TooSmall { .. })));
647 r.archetype = "atlantis".into();
648 let opts = BuildOptions {
649 width: 640,
650 height: 360,
651 ..opts
652 };
653 assert!(matches!(
654 build(&r, &opts),
655 Err(BuildError::UnknownArchetype(_))
656 ));
657 }
658}