Skip to main content

clairlune_scene/
particles.rs

1//! Seeded, periodic particles. Each particle's state is a pure function of
2//! `t mod life`, and every life divides the loop length, so animations loop
3//! seamlessly (needed for GIF export, free for live mode).
4
5use crate::glyphs::EMBERS;
6use crate::math::{TAU, pow, sin};
7use crate::rng::Rng;
8
9/// Loop length shared by all periodic elements in M1.
10pub const LOOP_MS: u64 = 6000;
11/// Particle lifetimes. Each divides [`LOOP_MS`].
12const LIVES_MS: [u32; 4] = [1000, 1500, 2000, 3000];
13
14/// How fast particles move. Pace 0 is the original motion, kept so scenes
15/// saved with it play exactly as they were saved. Pace 1 (generator 4 on)
16/// is calm: embers drift up slowly, snow and dust float, effects linger, so
17/// a smooth frame rate shows slow motion rather than a frantic one. Every
18/// life still divides [`LOOP_MS`], so GIFs loop seamlessly.
19pub const CALM_PACE: u8 = 1;
20/// Calm ember lives.
21const CALM_LIVES_MS: [u32; 3] = [2000, 3000, 6000];
22/// Hero-time search: candidates every 500 ms in the first 10 s.
23const HERO_STEP_MS: u64 = 500;
24const HERO_CANDIDATES: u64 = 20;
25/// Clustering bucket size in units of image height.
26const HERO_BUCKET: f64 = 0.03;
27
28/// One ember, in units of image height, relative to the emitter origin.
29#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
30pub struct Ember {
31    life_ms: u32,
32    phase_ms: u32,
33    x0: f64,
34    drift: f64,
35    rise: f64,
36    wobble: f64,
37    wobble_cycles: f64,
38    wobble_phase: f64,
39    max_level: f64,
40    glyph_bias: u32,
41}
42
43/// A particle sample in pixels with an ink level `1..=6`.
44#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
45pub struct Particle {
46    pub x: f64,
47    pub y: f64,
48    pub glyph: u8,
49    pub level: u8,
50    /// Drawn in ink colour (snow, rain, dust) instead of ember colour.
51    pub ink: bool,
52}
53
54#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
55pub enum EmitterKind {
56    /// Upward-drifting plume that widens with height.
57    Embers,
58    /// Screen-wide weather particles.
59    Weather(WeatherKind),
60}
61
62/// A particle emitter placed in the image.
63#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
64pub struct Emitter {
65    pub kind: EmitterKind,
66    /// Origin in pixels.
67    pub origin_x: f64,
68    pub origin_y: f64,
69    /// Pixels per normalised unit (the image height).
70    pub unit: f64,
71    /// Multiplies every particle's level (dimmer in daylight).
72    pub intensity: f64,
73    pub embers: Vec<Ember>,
74    /// Weather particles (empty for embers).
75    pub drops: Vec<Drop>,
76    /// Image size in pixels, for screen-space weather.
77    pub size: (f64, f64),
78    /// How fast the weather moves (see [`CALM_PACE`]); 0 in older scenes.
79    #[serde(default)]
80    pub pace: u8,
81}
82
83/// The ember set for a seed at a pace. Independent of size and theme, so the
84/// hero time is too.
85pub fn ember_set(seed: u64, pace: u8) -> Vec<Ember> {
86    if pace >= CALM_PACE {
87        return calm_ember_set(seed);
88    }
89    let mut rng = Rng::stream(seed, "particles");
90    let count = rng.range_u32(44, 72);
91    (0..count)
92        .map(|_| {
93            let life_ms = LIVES_MS[rng.weighted_index(&[1, 2, 3, 2])];
94            Ember {
95                life_ms,
96                phase_ms: rng.below(life_ms),
97                x0: rng.range_f64(-0.010, 0.010),
98                drift: rng.range_f64(-0.075, 0.075),
99                rise: rng.range_f64(0.16, 0.38),
100                wobble: rng.range_f64(0.002, 0.012),
101                wobble_cycles: f64::from(rng.range_u32(1, 3)),
102                wobble_phase: rng.unit(),
103                max_level: f64::from(rng.range_u32(4, 6)),
104                glyph_bias: rng.below(2),
105            }
106        })
107        .collect()
108}
109
110/// Calm embers: longer lives, a short rise and little drift, so they float up
111/// from the fire instead of shooting off.
112fn calm_ember_set(seed: u64) -> Vec<Ember> {
113    let mut rng = Rng::stream(seed, "particles_calm");
114    let count = rng.range_u32(36, 56);
115    (0..count)
116        .map(|_| {
117            let life_ms = CALM_LIVES_MS[rng.weighted_index(&[1, 3, 2])];
118            Ember {
119                life_ms,
120                phase_ms: rng.below(life_ms),
121                x0: rng.range_f64(-0.010, 0.010),
122                drift: rng.range_f64(-0.035, 0.035),
123                rise: rng.range_f64(0.07, 0.16),
124                wobble: rng.range_f64(0.002, 0.008),
125                wobble_cycles: f64::from(rng.range_u32(1, 2)),
126                wobble_phase: rng.unit(),
127                max_level: f64::from(rng.range_u32(4, 6)),
128                glyph_bias: rng.below(2),
129            }
130        })
131        .collect()
132}
133
134/// Offset of an ember at time `t`, in units of height, plus glyph and level.
135fn ember_state(e: &Ember, t_ms: u64) -> Option<(f64, f64, u8, f64)> {
136    let life = u64::from(e.life_ms);
137    // (Reduced first: no overflow however late `t_ms` is.)
138    let age = (t_ms % life + u64::from(e.phase_ms)) % life;
139    let p = age as f64 / life as f64;
140    if p >= 0.96 {
141        return None;
142    }
143    let dy = -e.rise * p;
144    let wob = e.wobble * p * sin(TAU * (e.wobble_cycles * p + e.wobble_phase));
145    let dx = e.x0 + e.drift * pow(p, 1.5) + wob;
146    let level = e.max_level * pow(1.0 - p, 0.8);
147    let stage = ((p * 4.0) as u32 + e.glyph_bias).min(EMBERS.len() as u32 - 1);
148    Some((dx, dy, EMBERS[stage as usize], level))
149}
150
151impl Emitter {
152    /// Whether it can play: a damaged saved scene may hold an ember with no
153    /// life or a drop with a glyph that doesn't exist.
154    pub fn is_sound(&self) -> bool {
155        self.embers.iter().all(|e| e.life_ms > 0)
156            && self
157                .drops
158                .iter()
159                .all(|d| usize::from(d.glyph) < crate::glyphs::GLYPHS.len() && d.cycles < u32::MAX)
160    }
161
162    /// All live particles at time `t`, in pixels.
163    pub fn sample(&self, t_ms: u64) -> Vec<Particle> {
164        match self.kind {
165            EmitterKind::Embers => self
166                .embers
167                .iter()
168                .filter_map(|e| ember_state(e, t_ms))
169                .filter_map(|(dx, dy, glyph, level)| {
170                    let lv = (level * self.intensity).round();
171                    if lv < 1.0 {
172                        return None;
173                    }
174                    Some(Particle {
175                        x: self.origin_x + dx * self.unit,
176                        y: self.origin_y + dy * self.unit,
177                        glyph,
178                        level: lv.min(6.0) as u8,
179                        ink: false,
180                    })
181                })
182                .collect(),
183            EmitterKind::Weather(kind) => self
184                .drops
185                .iter()
186                .filter_map(|d| {
187                    let (x, y, glyph, level) = if self.pace >= CALM_PACE {
188                        calm_drop_state(kind, d, t_ms)?
189                    } else {
190                        drop_state(kind, d, t_ms)
191                    };
192                    Some(Particle {
193                        x: x * self.size.0,
194                        y: y * self.size.1,
195                        glyph,
196                        level,
197                        ink: kind.ink(),
198                    })
199                })
200                .collect(),
201        }
202    }
203}
204
205/// Picks the hero time: among candidate frames in the first 10 s, the one whose
206/// particles are most evenly spread (lowest sum of squared bucket counts).
207/// Ties go to the earliest frame. Depends only on the seed.
208pub fn hero_time(embers: &[Ember]) -> u64 {
209    let mut best = (u64::MAX, 0u64);
210    let mut buckets: Vec<(i64, i64)> = Vec::with_capacity(embers.len());
211    for k in 0..HERO_CANDIDATES {
212        let t = k * HERO_STEP_MS;
213        buckets.clear();
214        for e in embers {
215            if let Some((dx, dy, _, _)) = ember_state(e, t) {
216                buckets.push((
217                    (dx / HERO_BUCKET).floor() as i64,
218                    (dy / HERO_BUCKET).floor() as i64,
219                ));
220            }
221        }
222        buckets.sort_unstable();
223        let mut score = 0u64;
224        let mut i = 0;
225        while i < buckets.len() {
226            let mut j = i;
227            while j < buckets.len() && buckets[j] == buckets[i] {
228                j += 1;
229            }
230            let n = (j - i) as u64;
231            score += n * n;
232            i = j;
233        }
234        if score < best.0 {
235            best = (score, t);
236        }
237    }
238    best.1
239}
240
241/// Screen-wide weather (PLAN.md section 4.2, step 6). Every motion completes a
242/// whole number of cycles per [`LOOP_MS`], so weather loops seamlessly.
243#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
244pub enum WeatherKind {
245    Snow,
246    Rain,
247    Fireflies,
248    Leaves,
249    Dust,
250    /// Blossom petals drifting down and across.
251    Petals,
252    /// Low mist drifting along the ground.
253    Fog,
254    /// Snow driven sideways by the wind, thick.
255    Blizzard,
256    /// Ash falling slowly (a volcano's).
257    Ash,
258    /// Ice crystals glinting in cold, still air.
259    Sparkle,
260    /// Confetti tumbling down.
261    Confetti,
262}
263
264impl WeatherKind {
265    /// The kind for a recipe's weather id (`none` and `stars` have no particles).
266    pub fn from_id(id: &str) -> Option<Self> {
267        match id {
268            "snow" => Some(WeatherKind::Snow),
269            "rain" => Some(WeatherKind::Rain),
270            "fireflies" => Some(WeatherKind::Fireflies),
271            "leaves" => Some(WeatherKind::Leaves),
272            "dust" => Some(WeatherKind::Dust),
273            "petals" => Some(WeatherKind::Petals),
274            "fog" => Some(WeatherKind::Fog),
275            "blizzard" => Some(WeatherKind::Blizzard),
276            "ash" => Some(WeatherKind::Ash),
277            "sparkle" => Some(WeatherKind::Sparkle),
278            "confetti" => Some(WeatherKind::Confetti),
279            _ => None,
280        }
281    }
282
283    /// Ink-coloured (cool) or ember-coloured (warm, glowing).
284    pub fn ink(self) -> bool {
285        matches!(
286            self,
287            WeatherKind::Snow
288                | WeatherKind::Rain
289                | WeatherKind::Dust
290                | WeatherKind::Fog
291                | WeatherKind::Blizzard
292                | WeatherKind::Ash
293                | WeatherKind::Sparkle
294        )
295    }
296}
297
298/// One weather particle, in normalised screen coordinates.
299#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
300pub struct Drop {
301    x0: f64,
302    y0: f64,
303    /// Whole vertical (or horizontal, for dust) wraps per loop.
304    wraps: u32,
305    sway: f64,
306    cycles: u32,
307    phase: f64,
308    glyph: u8,
309    level: u8,
310    /// Calm pace: how far it falls (or drifts) over one life, in screen
311    /// heights (widths for dust). 0 in older scenes.
312    #[serde(default)]
313    fall: f64,
314}
315
316/// Calm pace: each weather particle's life, by kind (each divides LOOP_MS).
317fn calm_life_ms(kind: WeatherKind) -> u64 {
318    match kind {
319        WeatherKind::Rain => 2000,
320        _ => 6000,
321    }
322}
323
324/// The weather particles for a seed; the count scales with the aspect ratio.
325pub fn weather_set(kind: WeatherKind, seed: u64, aspect: f64, pace: u8) -> Vec<Drop> {
326    let mut drops = old_weather_set(kind, seed, aspect);
327    if pace >= CALM_PACE {
328        // Separate draws, so the older pace's particles stay exactly as they
329        // were.
330        let mut rng = Rng::stream(seed, "weather_fall");
331        for d in &mut drops {
332            d.fall = match kind {
333                WeatherKind::Snow => rng.range_f64(0.10, 0.22),
334                WeatherKind::Rain => rng.range_f64(0.18, 0.30),
335                WeatherKind::Leaves => rng.range_f64(0.12, 0.24),
336                WeatherKind::Dust => rng.range_f64(0.06, 0.12),
337                WeatherKind::Petals => rng.range_f64(0.14, 0.26),
338                WeatherKind::Fog => rng.range_f64(0.03, 0.07),
339                WeatherKind::Blizzard => rng.range_f64(0.25, 0.4),
340                WeatherKind::Ash => rng.range_f64(0.06, 0.14),
341                WeatherKind::Confetti => rng.range_f64(0.16, 0.28),
342                WeatherKind::Fireflies | WeatherKind::Sparkle => 0.0,
343            };
344        }
345    }
346    drops
347}
348
349fn old_weather_set(kind: WeatherKind, seed: u64, aspect: f64) -> Vec<Drop> {
350    use crate::glyphs::id;
351    let mut rng = Rng::stream(seed, "weather_particles");
352    let per = match kind {
353        WeatherKind::Snow => 70.0,
354        WeatherKind::Rain => 110.0,
355        WeatherKind::Fireflies => 14.0,
356        WeatherKind::Leaves => 22.0,
357        WeatherKind::Dust => 40.0,
358        WeatherKind::Petals => 34.0,
359        WeatherKind::Fog => 26.0,
360        WeatherKind::Blizzard => 150.0,
361        WeatherKind::Ash => 55.0,
362        WeatherKind::Sparkle => 30.0,
363        WeatherKind::Confetti => 45.0,
364    };
365    let count = (per * aspect).round() as u32;
366    (0..count)
367        .map(|_| {
368            let x0 = rng.unit();
369            let y0 = rng.unit();
370            let phase = rng.unit();
371            let big = rng.chance(1, 4);
372            match kind {
373                WeatherKind::Snow => Drop {
374                    x0,
375                    y0,
376                    wraps: rng.range_u32(1, 2),
377                    sway: rng.range_f64(0.003, 0.010),
378                    cycles: rng.range_u32(1, 3),
379                    phase,
380                    glyph: if big {
381                        id('*')
382                    } else {
383                        *rng.choose(&[id('.'), id('\''), id('`')])
384                    },
385                    level: if big { 5 } else { rng.range_u32(2, 4) as u8 },
386                    fall: 0.0,
387                },
388                WeatherKind::Rain => Drop {
389                    x0,
390                    y0,
391                    wraps: rng.range_u32(6, 9),
392                    sway: 0.0,
393                    cycles: 1,
394                    phase,
395                    glyph: *rng.choose(&[id('/'), id('|'), id('\'')]),
396                    level: rng.range_u32(2, 3) as u8,
397                    fall: 0.0,
398                },
399                WeatherKind::Fireflies => Drop {
400                    x0,
401                    // Low in the scene, among the terrain.
402                    y0: 0.45 + 0.5 * y0,
403                    wraps: rng.range_u32(1, 3),
404                    sway: rng.range_f64(0.01, 0.03),
405                    cycles: rng.range_u32(1, 2),
406                    phase,
407                    glyph: id('.'),
408                    level: 0,
409                    fall: 0.0,
410                },
411                WeatherKind::Leaves => Drop {
412                    x0,
413                    y0,
414                    wraps: 1,
415                    sway: rng.range_f64(0.01, 0.03),
416                    cycles: rng.range_u32(2, 3),
417                    phase,
418                    glyph: *rng.choose(&[id(','), id('`'), id('\'')]),
419                    level: rng.range_u32(2, 4) as u8,
420                    fall: 0.0,
421                },
422                WeatherKind::Dust => Drop {
423                    x0,
424                    y0: 0.3 + 0.65 * y0,
425                    wraps: 1,
426                    sway: rng.range_f64(0.002, 0.008),
427                    cycles: rng.range_u32(1, 2),
428                    phase,
429                    glyph: *rng.choose(&[id('.'), id('`')]),
430                    level: rng.range_u32(1, 2) as u8,
431                    fall: 0.0,
432                },
433                WeatherKind::Petals => Drop {
434                    x0,
435                    y0,
436                    wraps: 1,
437                    sway: rng.range_f64(0.01, 0.025),
438                    cycles: rng.range_u32(2, 3),
439                    phase,
440                    glyph: *rng.choose(&[id('\''), id('`'), id(','), id('*')]),
441                    level: rng.range_u32(3, 5) as u8,
442                    fall: 0.0,
443                },
444                WeatherKind::Fog => Drop {
445                    x0,
446                    // Low, along the land.
447                    y0: 0.55 + 0.4 * y0,
448                    wraps: 1,
449                    sway: rng.range_f64(0.002, 0.006),
450                    cycles: 1,
451                    phase,
452                    glyph: *rng.choose(&[id('~'), id('-'), id('='), id('~')]),
453                    level: rng.range_u32(1, 2) as u8,
454                    fall: 0.0,
455                },
456                WeatherKind::Blizzard => Drop {
457                    x0,
458                    y0,
459                    wraps: rng.range_u32(2, 4),
460                    sway: rng.range_f64(0.002, 0.006),
461                    cycles: 1,
462                    phase,
463                    glyph: if big {
464                        id('*')
465                    } else {
466                        *rng.choose(&[id('.'), id('\''), id('-'), id('`')])
467                    },
468                    level: if big { 5 } else { rng.range_u32(2, 4) as u8 },
469                    fall: 0.0,
470                },
471                WeatherKind::Ash => Drop {
472                    x0,
473                    y0,
474                    wraps: 1,
475                    sway: rng.range_f64(0.004, 0.012),
476                    cycles: rng.range_u32(1, 2),
477                    phase,
478                    glyph: *rng.choose(&[id('.'), id('`'), id(','), id('.')]),
479                    level: rng.range_u32(1, 3) as u8,
480                    fall: 0.0,
481                },
482                WeatherKind::Sparkle => Drop {
483                    x0,
484                    // The air over the land, not the top of the sky.
485                    y0: 0.15 + 0.8 * y0,
486                    wraps: rng.range_u32(1, 3),
487                    sway: 0.0,
488                    cycles: 1,
489                    phase,
490                    glyph: id('.'),
491                    level: 0,
492                    fall: 0.0,
493                },
494                WeatherKind::Confetti => Drop {
495                    x0,
496                    y0,
497                    wraps: 1,
498                    sway: rng.range_f64(0.008, 0.02),
499                    cycles: rng.range_u32(2, 4),
500                    phase,
501                    glyph: *rng.choose(&[id('-'), id('|'), id('/'), id('\\')]),
502                    level: rng.range_u32(3, 5) as u8,
503                    fall: 0.0,
504                },
505            }
506        })
507        .collect()
508}
509
510fn frac(x: f64) -> f64 {
511    x - x.floor()
512}
513
514/// Position (normalised), glyph and level of a weather particle at `t`.
515fn drop_state(kind: WeatherKind, d: &Drop, t_ms: u64) -> (f64, f64, u8, u8) {
516    use crate::glyphs::id;
517    let u = (t_ms % LOOP_MS) as f64 / LOOP_MS as f64;
518    let wave = |cycles: u32, phase: f64| sin(TAU * (f64::from(cycles) * u + phase));
519    match kind {
520        WeatherKind::Snow | WeatherKind::Leaves => (
521            frac(d.x0 + d.sway * wave(d.cycles, d.phase)),
522            frac(d.y0 + f64::from(d.wraps) * u),
523            d.glyph,
524            d.level,
525        ),
526        WeatherKind::Rain => (d.x0, frac(d.y0 + f64::from(d.wraps) * u), d.glyph, d.level),
527        WeatherKind::Fireflies => {
528            // Wander on a small closed curve and pulse.
529            let glow = 0.5 + 0.5 * wave(d.wraps, d.phase * 2.0);
530            let level = (1.0 + 4.0 * glow).round() as u8;
531            (
532                frac(d.x0 + d.sway * wave(d.cycles, d.phase)),
533                d.y0 + 0.5 * d.sway * wave(d.cycles + 1, d.phase + 0.25),
534                if level >= 4 { id('*') } else { d.glyph },
535                level,
536            )
537        }
538        WeatherKind::Dust | WeatherKind::Fog => (
539            frac(d.x0 + f64::from(d.wraps) * u),
540            d.y0 + d.sway * wave(d.cycles, d.phase),
541            d.glyph,
542            d.level,
543        ),
544        WeatherKind::Petals | WeatherKind::Ash | WeatherKind::Confetti => (
545            frac(d.x0 + 0.3 * u + d.sway * wave(d.cycles, d.phase)),
546            frac(d.y0 + f64::from(d.wraps) * u),
547            d.glyph,
548            d.level,
549        ),
550        WeatherKind::Blizzard => (
551            frac(d.x0 + 0.8 * f64::from(d.wraps) * u),
552            frac(d.y0 + f64::from(d.wraps) * u),
553            d.glyph,
554            d.level,
555        ),
556        WeatherKind::Sparkle => {
557            // Still; each crystal catches the light now and then.
558            let glint = sin(TAU * (f64::from(d.wraps) * u + d.phase)).max(0.0);
559            let glint = glint * glint * glint * glint;
560            let level = (5.0 * glint).round() as u8;
561            let glyph = match level {
562                5 => id('*'),
563                3 | 4 => id('+'),
564                _ => d.glyph,
565            };
566            (d.x0, d.y0, glyph, level)
567        }
568    }
569}
570
571/// A weather particle at the calm pace: it appears, drifts `fall` over its
572/// life while swaying, and fades out, then starts again. `None` while fully
573/// faded. Fireflies keep their wandering (already slow).
574fn calm_drop_state(kind: WeatherKind, d: &Drop, t_ms: u64) -> Option<(f64, f64, u8, u8)> {
575    if matches!(kind, WeatherKind::Fireflies | WeatherKind::Sparkle) {
576        let s = drop_state(kind, d, t_ms);
577        return (s.3 > 0).then_some(s);
578    }
579    let life = calm_life_ms(kind);
580    let p = frac((t_ms % life) as f64 / life as f64 + d.phase);
581    // Fade in over the first fifth, out over the last fifth.
582    let fade = (p / 0.2).min((1.0 - p) / 0.2).min(1.0);
583    let level = (f64::from(d.level) * fade).round() as u8;
584    if level == 0 {
585        return None;
586    }
587    // One slow sway per life.
588    let sway = d.sway * sin(TAU * (p + d.phase));
589    Some(match kind {
590        WeatherKind::Dust | WeatherKind::Fog => {
591            (frac(d.x0 + d.fall * p), d.y0 + sway, d.glyph, level)
592        }
593        WeatherKind::Rain => (d.x0, frac(d.y0 + d.fall * p), d.glyph, level),
594        // Carried across as they fall: petals, ash and confetti by a breeze,
595        // a blizzard by a gale.
596        WeatherKind::Petals | WeatherKind::Ash => (
597            frac(d.x0 + 0.5 * d.fall * p + sway),
598            frac(d.y0 + d.fall * p),
599            d.glyph,
600            level,
601        ),
602        WeatherKind::Blizzard => (
603            frac(d.x0 + 0.9 * d.fall * p + sway),
604            frac(d.y0 + d.fall * p),
605            d.glyph,
606            level,
607        ),
608        WeatherKind::Confetti => {
609            // Tumbling: the bit turns as it falls.
610            use crate::glyphs::id;
611            const TURN: [u8; 4] = [id('-'), id('\\'), id('|'), id('/')];
612            let turn = TURN[((p * 8.0 + d.phase * 4.0) as usize) % 4];
613            (frac(d.x0 + sway), frac(d.y0 + d.fall * p), turn, level)
614        }
615        _ => (frac(d.x0 + sway), frac(d.y0 + d.fall * p), d.glyph, level),
616    })
617}
618
619/// Particle presets attached to an anchor of the character (activity effects).
620#[derive(Clone, Copy, Debug, PartialEq, Eq)]
621pub enum Preset {
622    /// Magic: sparks flying out from a point (a wand tip).
623    Sparkles,
624    /// Faint wisps rising from a point (a mug, a kettle).
625    Steam,
626    /// Music notes floating up and sideways (a guitar).
627    Notes,
628    /// Snow kicked up behind skis: short arcs backwards, quick.
629    SnowSpray,
630    /// Soap bubbles from a wand: drifting up and away, growing, then popping.
631    Bubbles,
632}
633
634impl Preset {
635    pub fn from_id(id: &str) -> Option<Self> {
636        match id {
637            "sparkles" => Some(Preset::Sparkles),
638            "steam" => Some(Preset::Steam),
639            "notes" => Some(Preset::Notes),
640            "snow_spray" => Some(Preset::SnowSpray),
641            "bubbles" => Some(Preset::Bubbles),
642            _ => None,
643        }
644    }
645}
646
647/// A preset particle: offset from its anchor in sprite pixels (y down), glyph, level 1-6.
648#[derive(Clone, Copy, Debug, PartialEq)]
649pub struct PresetParticle {
650    pub dx: f64,
651    pub dy: f64,
652    pub glyph: u8,
653    pub level: u8,
654}
655
656/// Particles of a preset at time `t`. Seeded and periodic in [`LOOP_MS`], like the
657/// embers, so GIF loops stay seamless.
658pub fn preset_particles(preset: Preset, seed: u64, t_ms: u64, pace: u8) -> Vec<PresetParticle> {
659    use crate::glyphs::id;
660    let calm = pace >= CALM_PACE;
661    let (label, count, lives): (&str, u32, &[u32]) = match (preset, calm) {
662        (Preset::Sparkles, false) => ("fx_sparkles", 9, &[1000, 1500, 2000]),
663        (Preset::Steam, false) => ("fx_steam", 5, &[2000, 3000]),
664        (Preset::Notes, false) => ("fx_notes", 4, &[1500, 2000, 3000]),
665        // Calm: the same shapes, lingering about twice as long.
666        (Preset::Sparkles, true) => ("fx_sparkles", 9, &[2000, 3000]),
667        (Preset::Steam, true) => ("fx_steam", 5, &[3000, 6000]),
668        (Preset::Notes, true) => ("fx_notes", 4, &[3000, 6000]),
669        // Spray is quick even at the calm pace: it's thrown, not drifting.
670        (Preset::SnowSpray, false) => ("fx_snow_spray", 8, &[600, 1000]),
671        (Preset::SnowSpray, true) => ("fx_snow_spray", 8, &[1000, 1500]),
672        (Preset::Bubbles, false) => ("fx_bubbles", 7, &[2000, 3000]),
673        (Preset::Bubbles, true) => ("fx_bubbles", 7, &[3000, 6000]),
674    };
675    let mut rng = Rng::stream(seed, label);
676    let mut out = Vec::new();
677    for _ in 0..count {
678        let life = *rng.choose(lives);
679        let phase = rng.below(life);
680        let a = rng.unit();
681        let b = rng.unit();
682        let c = rng.unit();
683        let p = ((t_ms + u64::from(phase)) % u64::from(life)) as f64 / f64::from(life);
684        match preset {
685            Preset::Sparkles => {
686                // Out from the tip in a random direction, fading.
687                let ang = TAU * a;
688                let dist = (1.0 + 5.0 * b) * p;
689                let level = (6.0 * (1.0 - p)).round() as u8;
690                if level == 0 {
691                    continue;
692                }
693                let glyph = [id('*'), id('+'), id('\''), id('.')][((p * 4.0) as usize).min(3)];
694                out.push(PresetParticle {
695                    dx: dist * sin(ang + TAU / 4.0),
696                    dy: -dist * sin(ang) - 1.5 * p,
697                    glyph,
698                    level,
699                });
700            }
701            Preset::Steam => {
702                // Rising and swaying, faint.
703                let rise = (8.0 + 6.0 * b) * p;
704                let sway = 1.2 * sin(TAU * (p + c)) * p;
705                let level = (4.0 * (1.0 - p) + 0.5).round() as u8;
706                if level == 0 || p < 0.08 {
707                    continue;
708                }
709                let glyph = [id('\''), id('~'), id('`'), id('.')][((p * 4.0) as usize).min(3)];
710                out.push(PresetParticle {
711                    dx: sway + 0.5 * (a - 0.5),
712                    dy: -rise - 1.0,
713                    glyph,
714                    level,
715                });
716            }
717            Preset::SnowSpray => {
718                // Backwards (negative dx: behind the skier) on a low arc.
719                let back = (1.5 + 6.0 * b) * p;
720                let up = (2.0 + 3.0 * a) * p - 5.0 * p * p;
721                let level = (5.0 * (1.0 - p) + 0.5).round() as u8;
722                if level == 0 {
723                    continue;
724                }
725                let glyph = [id('*'), id('\''), id('.'), id(',')][((p * 4.0) as usize).min(3)];
726                out.push(PresetParticle {
727                    dx: -back - 1.0 - c,
728                    dy: -up,
729                    glyph,
730                    level,
731                });
732            }
733            Preset::Bubbles => {
734                // Off downwind and up, bobbing; bigger as they go, popping
735                // into a star at the end.
736                let drift = (3.0 + 7.0 * b) * p;
737                let rise = (5.0 + 6.0 * a) * p;
738                let bob = 0.8 * sin(TAU * (1.5 * p + c));
739                let glyph = if p > 0.92 {
740                    id('*')
741                } else if p > 0.45 {
742                    id('O')
743                } else if p > 0.12 {
744                    id('o')
745                } else {
746                    id('.')
747                };
748                out.push(PresetParticle {
749                    dx: 1.0 + drift + bob * 0.5,
750                    dy: -rise - 1.0 + bob,
751                    glyph,
752                    level: if p > 0.92 { 3 } else { 5 },
753                });
754            }
755            Preset::Notes => {
756                // Up and out to one side, swaying, fading.
757                let side = if a < 0.5 { -1.0 } else { 1.0 };
758                let rise = (6.0 + 5.0 * b) * p;
759                let level = (5.0 * (1.0 - p) + 0.5).round() as u8;
760                if level == 0 {
761                    continue;
762                }
763                out.push(PresetParticle {
764                    dx: side * (1.0 + 3.0 * p) + 0.8 * sin(TAU * (2.0 * p + c)),
765                    dy: -rise - 1.0,
766                    glyph: crate::glyphs::NOTES[(b * 2.0) as usize % 2],
767                    level,
768                });
769            }
770        }
771    }
772    out
773}
774
775#[cfg(test)]
776mod weather_tests {
777    use super::*;
778
779    const KINDS: [WeatherKind; 11] = [
780        WeatherKind::Snow,
781        WeatherKind::Rain,
782        WeatherKind::Fireflies,
783        WeatherKind::Leaves,
784        WeatherKind::Dust,
785        WeatherKind::Petals,
786        WeatherKind::Fog,
787        WeatherKind::Blizzard,
788        WeatherKind::Ash,
789        WeatherKind::Sparkle,
790        WeatherKind::Confetti,
791    ];
792
793    fn emitter(kind: WeatherKind, pace: u8) -> Emitter {
794        Emitter {
795            kind: EmitterKind::Weather(kind),
796            origin_x: 0.0,
797            origin_y: 0.0,
798            unit: 1.0,
799            intensity: 1.0,
800            embers: Vec::new(),
801            drops: weather_set(kind, 9, 16.0 / 9.0, pace),
802            size: (1920.0, 1080.0),
803            pace,
804        }
805    }
806
807    #[test]
808    fn weather_loops_and_moves() {
809        for pace in [0, CALM_PACE] {
810            for kind in KINDS {
811                let e = emitter(kind, pace);
812                assert!(!e.drops.is_empty());
813                assert_eq!(
814                    e.sample(1234),
815                    e.sample(1234 + LOOP_MS),
816                    "{kind:?} pace {pace}"
817                );
818                assert_ne!(
819                    e.sample(0),
820                    e.sample(700),
821                    "{kind:?} pace {pace} should move"
822                );
823            }
824        }
825    }
826
827    /// Mean speed of the particles that move smoothly between `t` and
828    /// `t + 100 ms` (respawns excluded), in screen heights per second.
829    fn mean_speed(kind: WeatherKind, pace: u8) -> f64 {
830        let e = emitter(kind, pace);
831        let (mut sum, mut n) = (0.0, 0usize);
832        for k in 0..60u64 {
833            let t = k * 100;
834            for d in &e.drops {
835                let at = |t| match pace {
836                    0 => Some(drop_state(kind, d, t)),
837                    _ => calm_drop_state(kind, d, t),
838                };
839                if let (Some(a), Some(b)) = (at(t), at(t + 100)) {
840                    let (dx, dy) = ((b.0 - a.0) * 16.0 / 9.0, b.1 - a.1);
841                    let dist = (dx * dx + dy * dy).sqrt();
842                    if dist < 0.3 {
843                        sum += dist * 10.0;
844                        n += 1;
845                    }
846                }
847            }
848        }
849        sum / n.max(1) as f64
850    }
851
852    #[test]
853    fn the_calm_pace_is_calm() {
854        for kind in KINDS {
855            let (old, calm) = (mean_speed(kind, 0), mean_speed(kind, CALM_PACE));
856            // Rain and a blizzard are meant to be quick.
857            let cap = if matches!(kind, WeatherKind::Rain | WeatherKind::Blizzard) {
858                0.2
859            } else {
860                0.06
861            };
862            assert!(calm <= cap, "{kind:?}: {calm:.3} screen heights a second");
863            if !matches!(kind, WeatherKind::Fireflies | WeatherKind::Sparkle) {
864                assert!(calm < old * 0.6, "{kind:?}: calm {calm:.3} vs {old:.3}");
865            }
866        }
867    }
868
869    #[test]
870    fn the_original_pace_is_unchanged() {
871        // Older scenes keep their motion: no `fall`, the original formula.
872        let e = emitter(WeatherKind::Snow, 0);
873        assert!(e.drops.iter().all(|d| d.fall == 0.0));
874        let calm = emitter(WeatherKind::Snow, CALM_PACE);
875        assert_eq!(
876            e.drops.iter().map(|d| (d.x0, d.y0)).collect::<Vec<_>>(),
877            calm.drops.iter().map(|d| (d.x0, d.y0)).collect::<Vec<_>>()
878        );
879    }
880}
881
882#[cfg(test)]
883mod preset_tests {
884    use super::*;
885
886    #[test]
887    fn presets_loop_and_vary() {
888        for pace in [0, CALM_PACE] {
889            for preset in [Preset::Sparkles, Preset::Steam, Preset::Notes] {
890                assert_eq!(
891                    preset_particles(preset, 3, 700, pace),
892                    preset_particles(preset, 3, 700 + LOOP_MS, pace)
893                );
894                assert_ne!(
895                    preset_particles(preset, 3, 700, pace),
896                    preset_particles(preset, 3, 1900, pace)
897                );
898                assert!(
899                    !preset_particles(preset, 3, 0, pace).is_empty()
900                        || !preset_particles(preset, 3, 500, pace).is_empty()
901                );
902            }
903        }
904    }
905}
906
907#[cfg(test)]
908mod tests {
909    use super::*;
910
911    fn embers(pace: u8) -> Emitter {
912        Emitter {
913            kind: EmitterKind::Embers,
914            origin_x: 100.0,
915            origin_y: 200.0,
916            unit: 1000.0,
917            intensity: 1.0,
918            embers: ember_set(5, pace),
919            drops: Vec::new(),
920            size: (0.0, 0.0),
921            pace,
922        }
923    }
924
925    #[test]
926    fn particles_loop_seamlessly() {
927        for pace in [0, CALM_PACE] {
928            let e = embers(pace);
929            assert_eq!(e.sample(1234), e.sample(1234 + LOOP_MS));
930            assert_eq!(e.sample(0), e.sample(LOOP_MS * 3));
931        }
932    }
933
934    #[test]
935    fn calm_embers_float_up_slowly() {
936        // The fastest ember's rise, in image heights a second.
937        let fastest = |set: &[Ember]| {
938            set.iter()
939                .map(|e| e.rise / (f64::from(e.life_ms) / 1000.0))
940                .fold(0.0, f64::max)
941        };
942        let (old, calm) = (fastest(&ember_set(5, 0)), fastest(&ember_set(5, CALM_PACE)));
943        assert!(calm <= 0.08, "calm embers rise {calm:.3} heights a second");
944        assert!(
945            old > 0.2,
946            "the original pace is kept for older scenes ({old:.3})"
947        );
948    }
949
950    #[test]
951    fn hero_time_is_stable_and_in_range() {
952        for pace in [0, CALM_PACE] {
953            let set = ember_set(5, pace);
954            let t = hero_time(&set);
955            assert_eq!(t, hero_time(&ember_set(5, pace)));
956            assert!(t < HERO_STEP_MS * HERO_CANDIDATES);
957        }
958    }
959}