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    /// Birds crossing high up, flapping and gliding (by day).
263    Birds,
264    /// Butterflies fluttering low over the land (by day).
265    Butterflies,
266    /// Dandelion seeds drifting across on the breeze, rising a little.
267    Seeds,
268    /// Shooting stars streaking down the sky now and then (after dark).
269    ShootingStars,
270}
271
272impl WeatherKind {
273    /// The kind for a recipe's weather id (`none` and `stars` have no particles).
274    pub fn from_id(id: &str) -> Option<Self> {
275        match id {
276            "snow" => Some(WeatherKind::Snow),
277            "rain" => Some(WeatherKind::Rain),
278            "fireflies" => Some(WeatherKind::Fireflies),
279            "leaves" => Some(WeatherKind::Leaves),
280            "dust" => Some(WeatherKind::Dust),
281            "petals" => Some(WeatherKind::Petals),
282            "fog" => Some(WeatherKind::Fog),
283            "blizzard" => Some(WeatherKind::Blizzard),
284            "ash" => Some(WeatherKind::Ash),
285            "sparkle" => Some(WeatherKind::Sparkle),
286            "confetti" => Some(WeatherKind::Confetti),
287            "birds" => Some(WeatherKind::Birds),
288            "butterflies" => Some(WeatherKind::Butterflies),
289            "seeds" => Some(WeatherKind::Seeds),
290            "shooting_stars" => Some(WeatherKind::ShootingStars),
291            _ => None,
292        }
293    }
294
295    /// Ink-coloured (cool) or ember-coloured (warm, glowing).
296    pub fn ink(self) -> bool {
297        matches!(
298            self,
299            WeatherKind::Snow
300                | WeatherKind::Rain
301                | WeatherKind::Dust
302                | WeatherKind::Fog
303                | WeatherKind::Blizzard
304                | WeatherKind::Ash
305                | WeatherKind::Sparkle
306                | WeatherKind::Birds
307                | WeatherKind::Seeds
308                | WeatherKind::ShootingStars
309        )
310    }
311
312    /// Whether it shows at this time of day: fireflies and shooting stars
313    /// after dark, birds and butterflies by day, the rest at any time.
314    pub fn shows_at(self, tod: crate::recipe::TimeOfDay) -> bool {
315        use crate::recipe::TimeOfDay as T;
316        let dark = matches!(tod, T::Dusk | T::DeepDusk | T::Night);
317        match self {
318            WeatherKind::Fireflies | WeatherKind::ShootingStars => dark,
319            WeatherKind::Birds | WeatherKind::Butterflies => !dark,
320            _ => true,
321        }
322    }
323}
324
325/// One weather particle, in normalised screen coordinates.
326#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug, PartialEq)]
327pub struct Drop {
328    x0: f64,
329    y0: f64,
330    /// Whole vertical (or horizontal, for dust) wraps per loop.
331    wraps: u32,
332    sway: f64,
333    cycles: u32,
334    phase: f64,
335    glyph: u8,
336    level: u8,
337    /// Calm pace: how far it falls (or drifts) over one life, in screen
338    /// heights (widths for dust). 0 in older scenes.
339    #[serde(default)]
340    fall: f64,
341}
342
343/// Calm pace: each weather particle's life, by kind (each divides LOOP_MS).
344fn calm_life_ms(kind: WeatherKind) -> u64 {
345    match kind {
346        WeatherKind::Rain => 2000,
347        _ => 6000,
348    }
349}
350
351/// The weather particles for a seed; the count scales with the aspect ratio.
352pub fn weather_set(kind: WeatherKind, seed: u64, aspect: f64, pace: u8) -> Vec<Drop> {
353    let mut drops = old_weather_set(kind, seed, aspect);
354    if pace >= CALM_PACE {
355        // Separate draws, so the older pace's particles stay exactly as they
356        // were.
357        let mut rng = Rng::stream(seed, "weather_fall");
358        for d in &mut drops {
359            d.fall = match kind {
360                WeatherKind::Snow => rng.range_f64(0.10, 0.22),
361                WeatherKind::Rain => rng.range_f64(0.18, 0.30),
362                WeatherKind::Leaves => rng.range_f64(0.12, 0.24),
363                WeatherKind::Dust => rng.range_f64(0.06, 0.12),
364                WeatherKind::Petals => rng.range_f64(0.14, 0.26),
365                WeatherKind::Fog => rng.range_f64(0.03, 0.07),
366                WeatherKind::Blizzard => rng.range_f64(0.25, 0.4),
367                WeatherKind::Ash => rng.range_f64(0.06, 0.14),
368                WeatherKind::Confetti => rng.range_f64(0.16, 0.28),
369                WeatherKind::Birds => rng.range_f64(0.12, 0.2),
370                WeatherKind::Butterflies => rng.range_f64(0.04, 0.08),
371                WeatherKind::Seeds => rng.range_f64(0.1, 0.2),
372                // A streak's drop, set per star (see `shooting_stars`).
373                WeatherKind::ShootingStars => d.fall,
374                WeatherKind::Fireflies | WeatherKind::Sparkle => 0.0,
375            };
376        }
377    }
378    if kind == WeatherKind::Birds {
379        flock(&mut drops);
380    }
381    drops
382}
383
384/// Birds fly in threes: each follows the first of its three in a small V,
385/// a little behind it, one above and one below, keeping its pace.
386fn flock(drops: &mut [Drop]) {
387    for i in 0..drops.len() {
388        let place = i % 3;
389        if place == 0 {
390            continue;
391        }
392        let lead = drops[i - place];
393        let side = if place == 1 { -1.0 } else { 1.0 };
394        drops[i] = Drop {
395            x0: frac(lead.x0 - 0.012),
396            y0: lead.y0 + side * 0.014,
397            phase: lead.phase,
398            sway: lead.sway,
399            cycles: lead.cycles,
400            wraps: lead.wraps,
401            fall: lead.fall,
402            ..drops[i]
403        };
404    }
405}
406
407fn old_weather_set(kind: WeatherKind, seed: u64, aspect: f64) -> Vec<Drop> {
408    use crate::glyphs::id;
409    if kind == WeatherKind::ShootingStars {
410        return shooting_stars(seed, aspect);
411    }
412    let mut rng = Rng::stream(seed, "weather_particles");
413    let per = match kind {
414        WeatherKind::Snow => 70.0,
415        WeatherKind::Rain => 110.0,
416        WeatherKind::Fireflies => 14.0,
417        WeatherKind::Leaves => 22.0,
418        WeatherKind::Dust => 40.0,
419        WeatherKind::Petals => 34.0,
420        WeatherKind::Fog => 26.0,
421        WeatherKind::Blizzard => 150.0,
422        WeatherKind::Ash => 55.0,
423        WeatherKind::Sparkle => 30.0,
424        WeatherKind::Confetti => 45.0,
425        WeatherKind::Birds => 6.0,
426        WeatherKind::Butterflies => 8.0,
427        WeatherKind::Seeds => 24.0,
428        WeatherKind::ShootingStars => 0.0,
429    };
430    let count = (per * aspect).round() as u32;
431    (0..count)
432        .map(|_| {
433            let x0 = rng.unit();
434            let y0 = rng.unit();
435            let phase = rng.unit();
436            let big = rng.chance(1, 4);
437            match kind {
438                WeatherKind::Snow => Drop {
439                    x0,
440                    y0,
441                    wraps: rng.range_u32(1, 2),
442                    sway: rng.range_f64(0.003, 0.010),
443                    cycles: rng.range_u32(1, 3),
444                    phase,
445                    glyph: if big {
446                        id('*')
447                    } else {
448                        *rng.choose(&[id('.'), id('\''), id('`')])
449                    },
450                    level: if big { 5 } else { rng.range_u32(2, 4) as u8 },
451                    fall: 0.0,
452                },
453                WeatherKind::Rain => Drop {
454                    x0,
455                    y0,
456                    wraps: rng.range_u32(6, 9),
457                    sway: 0.0,
458                    cycles: 1,
459                    phase,
460                    glyph: *rng.choose(&[id('/'), id('|'), id('\'')]),
461                    level: rng.range_u32(2, 3) as u8,
462                    fall: 0.0,
463                },
464                WeatherKind::Fireflies => Drop {
465                    x0,
466                    // Low in the scene, among the terrain.
467                    y0: 0.45 + 0.5 * y0,
468                    wraps: rng.range_u32(1, 3),
469                    sway: rng.range_f64(0.01, 0.03),
470                    cycles: rng.range_u32(1, 2),
471                    phase,
472                    glyph: id('.'),
473                    level: 0,
474                    fall: 0.0,
475                },
476                WeatherKind::Leaves => Drop {
477                    x0,
478                    y0,
479                    wraps: 1,
480                    sway: rng.range_f64(0.01, 0.03),
481                    cycles: rng.range_u32(2, 3),
482                    phase,
483                    glyph: *rng.choose(&[id(','), id('`'), id('\'')]),
484                    level: rng.range_u32(2, 4) as u8,
485                    fall: 0.0,
486                },
487                WeatherKind::Dust => Drop {
488                    x0,
489                    y0: 0.3 + 0.65 * y0,
490                    wraps: 1,
491                    sway: rng.range_f64(0.002, 0.008),
492                    cycles: rng.range_u32(1, 2),
493                    phase,
494                    glyph: *rng.choose(&[id('.'), id('`')]),
495                    level: rng.range_u32(1, 2) as u8,
496                    fall: 0.0,
497                },
498                WeatherKind::Petals => Drop {
499                    x0,
500                    y0,
501                    wraps: 1,
502                    sway: rng.range_f64(0.01, 0.025),
503                    cycles: rng.range_u32(2, 3),
504                    phase,
505                    glyph: *rng.choose(&[id('\''), id('`'), id(','), id('*')]),
506                    level: rng.range_u32(3, 5) as u8,
507                    fall: 0.0,
508                },
509                WeatherKind::Fog => Drop {
510                    x0,
511                    // Low, along the land.
512                    y0: 0.55 + 0.4 * y0,
513                    wraps: 1,
514                    sway: rng.range_f64(0.002, 0.006),
515                    cycles: 1,
516                    phase,
517                    glyph: *rng.choose(&[id('~'), id('-'), id('='), id('~')]),
518                    level: rng.range_u32(1, 2) as u8,
519                    fall: 0.0,
520                },
521                WeatherKind::Blizzard => Drop {
522                    x0,
523                    y0,
524                    wraps: rng.range_u32(2, 4),
525                    sway: rng.range_f64(0.002, 0.006),
526                    cycles: 1,
527                    phase,
528                    glyph: if big {
529                        id('*')
530                    } else {
531                        *rng.choose(&[id('.'), id('\''), id('-'), id('`')])
532                    },
533                    level: if big { 5 } else { rng.range_u32(2, 4) as u8 },
534                    fall: 0.0,
535                },
536                WeatherKind::Ash => Drop {
537                    x0,
538                    y0,
539                    wraps: 1,
540                    sway: rng.range_f64(0.004, 0.012),
541                    cycles: rng.range_u32(1, 2),
542                    phase,
543                    glyph: *rng.choose(&[id('.'), id('`'), id(','), id('.')]),
544                    level: rng.range_u32(1, 3) as u8,
545                    fall: 0.0,
546                },
547                WeatherKind::Sparkle => Drop {
548                    x0,
549                    // The air over the land, not the top of the sky.
550                    y0: 0.15 + 0.8 * y0,
551                    wraps: rng.range_u32(1, 3),
552                    sway: 0.0,
553                    cycles: 1,
554                    phase,
555                    glyph: id('.'),
556                    level: 0,
557                    fall: 0.0,
558                },
559                WeatherKind::Confetti => Drop {
560                    x0,
561                    y0,
562                    wraps: 1,
563                    sway: rng.range_f64(0.008, 0.02),
564                    cycles: rng.range_u32(2, 4),
565                    phase,
566                    glyph: *rng.choose(&[id('-'), id('|'), id('/'), id('\\')]),
567                    level: rng.range_u32(3, 5) as u8,
568                    fall: 0.0,
569                },
570                WeatherKind::Birds => Drop {
571                    x0,
572                    // High in the sky.
573                    y0: 0.08 + 0.3 * y0,
574                    wraps: 1,
575                    sway: rng.range_f64(0.004, 0.012),
576                    cycles: rng.range_u32(1, 2),
577                    phase,
578                    glyph: id('v'),
579                    level: rng.range_u32(3, 4) as u8,
580                    fall: 0.0,
581                },
582                WeatherKind::Butterflies => Drop {
583                    x0,
584                    // Low over the land.
585                    y0: 0.5 + 0.4 * y0,
586                    wraps: 1,
587                    sway: rng.range_f64(0.006, 0.016),
588                    cycles: 1,
589                    phase,
590                    glyph: id('x'),
591                    level: rng.range_u32(4, 5) as u8,
592                    fall: 0.0,
593                },
594                WeatherKind::Seeds => Drop {
595                    x0,
596                    y0,
597                    wraps: 1,
598                    sway: rng.range_f64(0.006, 0.018),
599                    cycles: rng.range_u32(1, 3),
600                    phase,
601                    glyph: *rng.choose(&[id('*'), id('.'), id('\''), id('*')]),
602                    level: rng.range_u32(2, 4) as u8,
603                    fall: 0.0,
604                },
605                WeatherKind::ShootingStars => unreachable!("made by `shooting_stars`"),
606            }
607        })
608        .collect()
609}
610
611/// Shooting stars: each is a head and a fading tail of three, sharing one
612/// path (`sway` across and `fall` down, over one streak); `cycles` is the
613/// place in the streak, 0 for the head. Two or so across the screen.
614fn shooting_stars(seed: u64, aspect: f64) -> Vec<Drop> {
615    use crate::glyphs::id;
616    let mut rng = Rng::stream(seed, "shooting_stars");
617    let count = (1.1 * aspect).round().max(1.0) as u32;
618    let mut drops = Vec::new();
619    for _ in 0..count {
620        let right = rng.chance(1, 2);
621        let across = rng.range_f64(0.14, 0.24) * if right { 1.0 } else { -1.0 };
622        let x0 = if right {
623            rng.range_f64(0.05, 0.7)
624        } else {
625            rng.range_f64(0.3, 0.95)
626        };
627        let y0 = rng.range_f64(0.04, 0.3);
628        let fall = rng.range_f64(0.08, 0.14);
629        let phase = rng.unit();
630        let tail = if right { id('\\') } else { id('/') };
631        for i in 0..4u32 {
632            drops.push(Drop {
633                x0,
634                y0,
635                wraps: 1,
636                sway: across,
637                cycles: i,
638                phase,
639                glyph: if i == 0 { id('*') } else { tail },
640                level: 5 - i.min(3) as u8,
641                fall,
642            });
643        }
644    }
645    drops
646}
647
648/// Where a shooting star's drop is at `p` through its life (it streaks over
649/// the first tenth), or `None` while it isn't showing.
650fn streak(d: &Drop, p: f64) -> Option<(f64, f64, u8, u8)> {
651    const SHOWS: f64 = 0.1;
652    if p >= SHOWS {
653        return None;
654    }
655    // The tail trails the head by a few hundredths of the streak.
656    let s = p / SHOWS - 0.06 * f64::from(d.cycles);
657    if s < 0.0 {
658        return None;
659    }
660    // Brightest mid-streak, gone at its end.
661    let glow = (s * 4.0).min((1.0 - s) * 3.0).clamp(0.0, 1.0);
662    let level = (f64::from(d.level) * glow).round() as u8;
663    (level > 0).then(|| (frac(d.x0 + d.sway * s), d.y0 + d.fall * s, d.glyph, level))
664}
665
666fn frac(x: f64) -> f64 {
667    x - x.floor()
668}
669
670/// Position (normalised), glyph and level of a weather particle at `t`.
671fn drop_state(kind: WeatherKind, d: &Drop, t_ms: u64) -> (f64, f64, u8, u8) {
672    use crate::glyphs::id;
673    let u = (t_ms % LOOP_MS) as f64 / LOOP_MS as f64;
674    let wave = |cycles: u32, phase: f64| sin(TAU * (f64::from(cycles) * u + phase));
675    match kind {
676        WeatherKind::Snow | WeatherKind::Leaves => (
677            frac(d.x0 + d.sway * wave(d.cycles, d.phase)),
678            frac(d.y0 + f64::from(d.wraps) * u),
679            d.glyph,
680            d.level,
681        ),
682        WeatherKind::Rain => (d.x0, frac(d.y0 + f64::from(d.wraps) * u), d.glyph, d.level),
683        WeatherKind::Fireflies => {
684            // Wander on a small closed curve and pulse.
685            let glow = 0.5 + 0.5 * wave(d.wraps, d.phase * 2.0);
686            let level = (1.0 + 4.0 * glow).round() as u8;
687            (
688                frac(d.x0 + d.sway * wave(d.cycles, d.phase)),
689                d.y0 + 0.5 * d.sway * wave(d.cycles + 1, d.phase + 0.25),
690                if level >= 4 { id('*') } else { d.glyph },
691                level,
692            )
693        }
694        WeatherKind::Dust | WeatherKind::Fog => (
695            frac(d.x0 + f64::from(d.wraps) * u),
696            d.y0 + d.sway * wave(d.cycles, d.phase),
697            d.glyph,
698            d.level,
699        ),
700        WeatherKind::Petals | WeatherKind::Ash | WeatherKind::Confetti => (
701            frac(d.x0 + 0.3 * u + d.sway * wave(d.cycles, d.phase)),
702            frac(d.y0 + f64::from(d.wraps) * u),
703            d.glyph,
704            d.level,
705        ),
706        WeatherKind::Blizzard => (
707            frac(d.x0 + 0.8 * f64::from(d.wraps) * u),
708            frac(d.y0 + f64::from(d.wraps) * u),
709            d.glyph,
710            d.level,
711        ),
712        WeatherKind::Birds => {
713            // Across the sky once a loop, wings beating, then gliding.
714            let flap = sin(TAU * (24.0 * u + d.phase)) > 0.2;
715            (
716                frac(d.x0 + f64::from(d.wraps) * u),
717                d.y0 + d.sway * wave(d.cycles, d.phase),
718                if flap { id('v') } else { id('-') },
719                d.level,
720            )
721        }
722        WeatherKind::Butterflies => {
723            // A wandering loop, bobbing, wings opening and closing.
724            let open = sin(TAU * (60.0 * u + d.phase)) > 0.0;
725            (
726                frac(d.x0 + 0.3 * u + d.sway * wave(d.cycles, d.phase)),
727                d.y0 + 0.5 * d.sway * wave(d.cycles + 2, d.phase + 0.25),
728                if open { id('x') } else { id('+') },
729                d.level,
730            )
731        }
732        WeatherKind::Seeds => (
733            frac(d.x0 + 0.3 * u + d.sway * wave(d.cycles, d.phase)),
734            frac(d.y0 - f64::from(d.wraps) * u * 0.5 + 1.0),
735            d.glyph,
736            d.level,
737        ),
738        WeatherKind::ShootingStars => {
739            let p = frac(u * f64::from(d.wraps) + d.phase);
740            streak(d, p).unwrap_or((d.x0, d.y0, d.glyph, 0))
741        }
742        WeatherKind::Sparkle => {
743            // Still; each crystal catches the light now and then.
744            let glint = sin(TAU * (f64::from(d.wraps) * u + d.phase)).max(0.0);
745            let glint = glint * glint * glint * glint;
746            let level = (5.0 * glint).round() as u8;
747            let glyph = match level {
748                5 => id('*'),
749                3 | 4 => id('+'),
750                _ => d.glyph,
751            };
752            (d.x0, d.y0, glyph, level)
753        }
754    }
755}
756
757/// A weather particle at the calm pace: it appears, drifts `fall` over its
758/// life while swaying, and fades out, then starts again. `None` while fully
759/// faded. Fireflies keep their wandering (already slow).
760fn calm_drop_state(kind: WeatherKind, d: &Drop, t_ms: u64) -> Option<(f64, f64, u8, u8)> {
761    if matches!(kind, WeatherKind::Fireflies | WeatherKind::Sparkle) {
762        let s = drop_state(kind, d, t_ms);
763        return (s.3 > 0).then_some(s);
764    }
765    let life = calm_life_ms(kind);
766    let p = frac((t_ms % life) as f64 / life as f64 + d.phase);
767    if kind == WeatherKind::ShootingStars {
768        return streak(d, p);
769    }
770    // Fade in over the first fifth, out over the last fifth.
771    let fade = (p / 0.2).min((1.0 - p) / 0.2).min(1.0);
772    let level = (f64::from(d.level) * fade).round() as u8;
773    if level == 0 {
774        return None;
775    }
776    // One slow sway per life.
777    let sway = d.sway * sin(TAU * (p + d.phase));
778    Some(match kind {
779        WeatherKind::Dust | WeatherKind::Fog => {
780            (frac(d.x0 + d.fall * p), d.y0 + sway, d.glyph, level)
781        }
782        WeatherKind::Rain => (d.x0, frac(d.y0 + d.fall * p), d.glyph, level),
783        // Carried across as they fall: petals, ash and confetti by a breeze,
784        // a blizzard by a gale.
785        WeatherKind::Petals | WeatherKind::Ash => (
786            frac(d.x0 + 0.5 * d.fall * p + sway),
787            frac(d.y0 + d.fall * p),
788            d.glyph,
789            level,
790        ),
791        WeatherKind::Blizzard => (
792            frac(d.x0 + 0.9 * d.fall * p + sway),
793            frac(d.y0 + d.fall * p),
794            d.glyph,
795            level,
796        ),
797        WeatherKind::Confetti => {
798            // Tumbling: the bit turns as it falls.
799            use crate::glyphs::id;
800            const TURN: [u8; 4] = [id('-'), id('\\'), id('|'), id('/')];
801            let turn = TURN[((p * 8.0 + d.phase * 4.0) as usize) % 4];
802            (frac(d.x0 + sway), frac(d.y0 + d.fall * p), turn, level)
803        }
804        // Gliding across; the wings beat in bursts.
805        WeatherKind::Birds => {
806            use crate::glyphs::id;
807            let beat = ((p * 40.0 + d.phase * 7.0) as usize) % 6 < 3;
808            let glyph = if beat && ((p * 160.0) as usize).is_multiple_of(2) {
809                id('v')
810            } else {
811                id('-')
812            };
813            (frac(d.x0 + d.fall * p), d.y0 + sway * 0.5, glyph, level)
814        }
815        // Drifting along slowly, bobbing, wings opening and closing.
816        WeatherKind::Butterflies => {
817            use crate::glyphs::id;
818            let bob = 0.006 * sin(TAU * (3.0 * p + d.phase));
819            let open = ((p * 90.0) as usize).is_multiple_of(2);
820            (
821                frac(d.x0 + d.fall * p + sway),
822                d.y0 + bob,
823                if open { id('x') } else { id('+') },
824                level,
825            )
826        }
827        // Mostly across on the breeze, rising a little.
828        WeatherKind::Seeds => (
829            frac(d.x0 + 0.8 * d.fall * p + sway),
830            frac(d.y0 - 0.25 * d.fall * p + 1.0),
831            d.glyph,
832            level,
833        ),
834        _ => (frac(d.x0 + sway), frac(d.y0 + d.fall * p), d.glyph, level),
835    })
836}
837
838/// Particle presets attached to an anchor of the character (activity effects).
839#[derive(Clone, Copy, Debug, PartialEq, Eq)]
840pub enum Preset {
841    /// Magic: sparks flying out from a point (a wand tip).
842    Sparkles,
843    /// Faint wisps rising from a point (a mug, a kettle).
844    Steam,
845    /// Music notes floating up and sideways (a guitar).
846    Notes,
847    /// Snow kicked up behind skis: short arcs backwards, quick.
848    SnowSpray,
849    /// Soap bubbles from a wand: drifting up and away, growing, then popping.
850    Bubbles,
851    /// Water from a watering can's rose: falling in short arcs.
852    Drops,
853}
854
855impl Preset {
856    pub fn from_id(id: &str) -> Option<Self> {
857        match id {
858            "sparkles" => Some(Preset::Sparkles),
859            "steam" => Some(Preset::Steam),
860            "notes" => Some(Preset::Notes),
861            "snow_spray" => Some(Preset::SnowSpray),
862            "bubbles" => Some(Preset::Bubbles),
863            "drops" => Some(Preset::Drops),
864            _ => None,
865        }
866    }
867}
868
869/// A preset particle: offset from its anchor in sprite pixels (y down), glyph, level 1-6.
870#[derive(Clone, Copy, Debug, PartialEq)]
871pub struct PresetParticle {
872    pub dx: f64,
873    pub dy: f64,
874    pub glyph: u8,
875    pub level: u8,
876}
877
878/// Particles of a preset at time `t`. Seeded and periodic in [`LOOP_MS`], like the
879/// embers, so GIF loops stay seamless.
880pub fn preset_particles(preset: Preset, seed: u64, t_ms: u64, pace: u8) -> Vec<PresetParticle> {
881    use crate::glyphs::id;
882    let calm = pace >= CALM_PACE;
883    let (label, count, lives): (&str, u32, &[u32]) = match (preset, calm) {
884        (Preset::Sparkles, false) => ("fx_sparkles", 9, &[1000, 1500, 2000]),
885        (Preset::Steam, false) => ("fx_steam", 5, &[2000, 3000]),
886        (Preset::Notes, false) => ("fx_notes", 4, &[1500, 2000, 3000]),
887        // Calm: the same shapes, lingering about twice as long.
888        (Preset::Sparkles, true) => ("fx_sparkles", 9, &[2000, 3000]),
889        (Preset::Steam, true) => ("fx_steam", 5, &[3000, 6000]),
890        (Preset::Notes, true) => ("fx_notes", 4, &[3000, 6000]),
891        // Spray is quick even at the calm pace: it's thrown, not drifting.
892        (Preset::SnowSpray, false) => ("fx_snow_spray", 8, &[600, 1000]),
893        (Preset::SnowSpray, true) => ("fx_snow_spray", 8, &[1000, 1500]),
894        (Preset::Bubbles, false) => ("fx_bubbles", 7, &[2000, 3000]),
895        (Preset::Bubbles, true) => ("fx_bubbles", 7, &[3000, 6000]),
896        // Water falls: quick at any pace.
897        (Preset::Drops, false) => ("fx_drops", 8, &[600, 1000]),
898        (Preset::Drops, true) => ("fx_drops", 8, &[1000, 1500]),
899    };
900    let mut rng = Rng::stream(seed, label);
901    let mut out = Vec::new();
902    for _ in 0..count {
903        let life = *rng.choose(lives);
904        let phase = rng.below(life);
905        let a = rng.unit();
906        let b = rng.unit();
907        let c = rng.unit();
908        let p = ((t_ms + u64::from(phase)) % u64::from(life)) as f64 / f64::from(life);
909        match preset {
910            Preset::Sparkles => {
911                // Out from the tip in a random direction, fading.
912                let ang = TAU * a;
913                let dist = (1.0 + 5.0 * b) * p;
914                let level = (6.0 * (1.0 - p)).round() as u8;
915                if level == 0 {
916                    continue;
917                }
918                let glyph = [id('*'), id('+'), id('\''), id('.')][((p * 4.0) as usize).min(3)];
919                out.push(PresetParticle {
920                    dx: dist * sin(ang + TAU / 4.0),
921                    dy: -dist * sin(ang) - 1.5 * p,
922                    glyph,
923                    level,
924                });
925            }
926            Preset::Steam => {
927                // Rising and swaying, faint.
928                let rise = (8.0 + 6.0 * b) * p;
929                let sway = 1.2 * sin(TAU * (p + c)) * p;
930                let level = (4.0 * (1.0 - p) + 0.5).round() as u8;
931                if level == 0 || p < 0.08 {
932                    continue;
933                }
934                let glyph = [id('\''), id('~'), id('`'), id('.')][((p * 4.0) as usize).min(3)];
935                out.push(PresetParticle {
936                    dx: sway + 0.5 * (a - 0.5),
937                    dy: -rise - 1.0,
938                    glyph,
939                    level,
940                });
941            }
942            Preset::SnowSpray => {
943                // Backwards (negative dx: behind the skier) on a low arc.
944                let back = (1.5 + 6.0 * b) * p;
945                let up = (2.0 + 3.0 * a) * p - 5.0 * p * p;
946                let level = (5.0 * (1.0 - p) + 0.5).round() as u8;
947                if level == 0 {
948                    continue;
949                }
950                let glyph = [id('*'), id('\''), id('.'), id(',')][((p * 4.0) as usize).min(3)];
951                out.push(PresetParticle {
952                    dx: -back - 1.0 - c,
953                    dy: -up,
954                    glyph,
955                    level,
956                });
957            }
958            Preset::Bubbles => {
959                // Off downwind and up, bobbing; bigger as they go, popping
960                // into a star at the end.
961                let drift = (3.0 + 7.0 * b) * p;
962                let rise = (5.0 + 6.0 * a) * p;
963                let bob = 0.8 * sin(TAU * (1.5 * p + c));
964                let glyph = if p > 0.92 {
965                    id('*')
966                } else if p > 0.45 {
967                    id('O')
968                } else if p > 0.12 {
969                    id('o')
970                } else {
971                    id('.')
972                };
973                out.push(PresetParticle {
974                    dx: 1.0 + drift + bob * 0.5,
975                    dy: -rise - 1.0 + bob,
976                    glyph,
977                    level: if p > 0.92 { 3 } else { 5 },
978                });
979            }
980            Preset::Drops => {
981                // Out of the rose and down, a little forward, falling
982                // faster as they go.
983                let ahead = (0.5 + 1.5 * b) * p;
984                let down = (2.0 + 2.0 * a) * p + 8.0 * p * p;
985                let level = (4.0 * (1.0 - 0.6 * p) + 0.5).round() as u8;
986                let glyph = [id('\''), id('.'), id(','), id('.')][((p * 4.0) as usize).min(3)];
987                out.push(PresetParticle {
988                    dx: ahead + 0.6 * (c - 0.5),
989                    dy: down,
990                    glyph,
991                    level,
992                });
993            }
994            Preset::Notes => {
995                // Up and out to one side, swaying, fading.
996                let side = if a < 0.5 { -1.0 } else { 1.0 };
997                let rise = (6.0 + 5.0 * b) * p;
998                let level = (5.0 * (1.0 - p) + 0.5).round() as u8;
999                if level == 0 {
1000                    continue;
1001                }
1002                out.push(PresetParticle {
1003                    dx: side * (1.0 + 3.0 * p) + 0.8 * sin(TAU * (2.0 * p + c)),
1004                    dy: -rise - 1.0,
1005                    glyph: crate::glyphs::NOTES[(b * 2.0) as usize % 2],
1006                    level,
1007                });
1008            }
1009        }
1010    }
1011    out
1012}
1013
1014#[cfg(test)]
1015mod weather_tests {
1016    use super::*;
1017
1018    const KINDS: [WeatherKind; 15] = [
1019        WeatherKind::Snow,
1020        WeatherKind::Rain,
1021        WeatherKind::Fireflies,
1022        WeatherKind::Leaves,
1023        WeatherKind::Dust,
1024        WeatherKind::Petals,
1025        WeatherKind::Fog,
1026        WeatherKind::Blizzard,
1027        WeatherKind::Ash,
1028        WeatherKind::Sparkle,
1029        WeatherKind::Confetti,
1030        WeatherKind::Birds,
1031        WeatherKind::Butterflies,
1032        WeatherKind::Seeds,
1033        WeatherKind::ShootingStars,
1034    ];
1035
1036    fn emitter(kind: WeatherKind, pace: u8) -> Emitter {
1037        Emitter {
1038            kind: EmitterKind::Weather(kind),
1039            origin_x: 0.0,
1040            origin_y: 0.0,
1041            unit: 1.0,
1042            intensity: 1.0,
1043            embers: Vec::new(),
1044            drops: weather_set(kind, 9, 16.0 / 9.0, pace),
1045            size: (1920.0, 1080.0),
1046            pace,
1047        }
1048    }
1049
1050    #[test]
1051    fn weather_loops_and_moves() {
1052        for pace in [0, CALM_PACE] {
1053            for kind in KINDS {
1054                let e = emitter(kind, pace);
1055                assert!(!e.drops.is_empty());
1056                assert_eq!(
1057                    e.sample(1234),
1058                    e.sample(1234 + LOOP_MS),
1059                    "{kind:?} pace {pace}"
1060                );
1061                if kind == WeatherKind::ShootingStars {
1062                    // Shows only now and then: somewhere in the loop it
1063                    // streaks, moving from one frame to the next.
1064                    let shown: Vec<_> = (0..60u64)
1065                        .map(|k| e.sample(k * 100))
1066                        .filter(|s| s.iter().any(|p| p.level > 0))
1067                        .collect();
1068                    assert!(
1069                        shown.len() >= 2 && shown.windows(2).any(|w| w[0] != w[1]),
1070                        "{kind:?} pace {pace} should streak"
1071                    );
1072                    continue;
1073                }
1074                assert_ne!(
1075                    e.sample(0),
1076                    e.sample(700),
1077                    "{kind:?} pace {pace} should move"
1078                );
1079            }
1080        }
1081    }
1082
1083    /// Mean speed of the particles that move smoothly between `t` and
1084    /// `t + 100 ms` (respawns excluded), in screen heights per second.
1085    fn mean_speed(kind: WeatherKind, pace: u8) -> f64 {
1086        let e = emitter(kind, pace);
1087        let (mut sum, mut n) = (0.0, 0usize);
1088        for k in 0..60u64 {
1089            let t = k * 100;
1090            for d in &e.drops {
1091                let at = |t| match pace {
1092                    0 => Some(drop_state(kind, d, t)),
1093                    _ => calm_drop_state(kind, d, t),
1094                };
1095                if let (Some(a), Some(b)) = (at(t), at(t + 100)) {
1096                    let (dx, dy) = ((b.0 - a.0) * 16.0 / 9.0, b.1 - a.1);
1097                    let dist = (dx * dx + dy * dy).sqrt();
1098                    if dist < 0.3 {
1099                        sum += dist * 10.0;
1100                        n += 1;
1101                    }
1102                }
1103            }
1104        }
1105        sum / n.max(1) as f64
1106    }
1107
1108    #[test]
1109    fn the_calm_pace_is_calm() {
1110        for kind in KINDS {
1111            // A shooting star is meant to streak (and shows a tenth of the
1112            // time).
1113            if kind == WeatherKind::ShootingStars {
1114                continue;
1115            }
1116            let (old, calm) = (mean_speed(kind, 0), mean_speed(kind, CALM_PACE));
1117            // Rain and a blizzard are meant to be quick.
1118            let cap = if matches!(kind, WeatherKind::Rain | WeatherKind::Blizzard) {
1119                0.2
1120            } else {
1121                0.06
1122            };
1123            assert!(calm <= cap, "{kind:?}: {calm:.3} screen heights a second");
1124            if !matches!(kind, WeatherKind::Fireflies | WeatherKind::Sparkle) {
1125                assert!(calm < old * 0.6, "{kind:?}: calm {calm:.3} vs {old:.3}");
1126            }
1127        }
1128    }
1129
1130    #[test]
1131    fn the_original_pace_is_unchanged() {
1132        // Older scenes keep their motion: no `fall`, the original formula.
1133        let e = emitter(WeatherKind::Snow, 0);
1134        assert!(e.drops.iter().all(|d| d.fall == 0.0));
1135        let calm = emitter(WeatherKind::Snow, CALM_PACE);
1136        assert_eq!(
1137            e.drops.iter().map(|d| (d.x0, d.y0)).collect::<Vec<_>>(),
1138            calm.drops.iter().map(|d| (d.x0, d.y0)).collect::<Vec<_>>()
1139        );
1140    }
1141}
1142
1143#[cfg(test)]
1144mod preset_tests {
1145    use super::*;
1146
1147    #[test]
1148    fn presets_loop_and_vary() {
1149        for pace in [0, CALM_PACE] {
1150            for preset in [Preset::Sparkles, Preset::Steam, Preset::Notes] {
1151                assert_eq!(
1152                    preset_particles(preset, 3, 700, pace),
1153                    preset_particles(preset, 3, 700 + LOOP_MS, pace)
1154                );
1155                assert_ne!(
1156                    preset_particles(preset, 3, 700, pace),
1157                    preset_particles(preset, 3, 1900, pace)
1158                );
1159                assert!(
1160                    !preset_particles(preset, 3, 0, pace).is_empty()
1161                        || !preset_particles(preset, 3, 500, pace).is_empty()
1162                );
1163            }
1164        }
1165    }
1166}
1167
1168#[cfg(test)]
1169mod tests {
1170    use super::*;
1171
1172    fn embers(pace: u8) -> Emitter {
1173        Emitter {
1174            kind: EmitterKind::Embers,
1175            origin_x: 100.0,
1176            origin_y: 200.0,
1177            unit: 1000.0,
1178            intensity: 1.0,
1179            embers: ember_set(5, pace),
1180            drops: Vec::new(),
1181            size: (0.0, 0.0),
1182            pace,
1183        }
1184    }
1185
1186    #[test]
1187    fn particles_loop_seamlessly() {
1188        for pace in [0, CALM_PACE] {
1189            let e = embers(pace);
1190            assert_eq!(e.sample(1234), e.sample(1234 + LOOP_MS));
1191            assert_eq!(e.sample(0), e.sample(LOOP_MS * 3));
1192        }
1193    }
1194
1195    #[test]
1196    fn calm_embers_float_up_slowly() {
1197        // The fastest ember's rise, in image heights a second.
1198        let fastest = |set: &[Ember]| {
1199            set.iter()
1200                .map(|e| e.rise / (f64::from(e.life_ms) / 1000.0))
1201                .fold(0.0, f64::max)
1202        };
1203        let (old, calm) = (fastest(&ember_set(5, 0)), fastest(&ember_set(5, CALM_PACE)));
1204        assert!(calm <= 0.08, "calm embers rise {calm:.3} heights a second");
1205        assert!(
1206            old > 0.2,
1207            "the original pace is kept for older scenes ({old:.3})"
1208        );
1209    }
1210
1211    #[test]
1212    fn hero_time_is_stable_and_in_range() {
1213        for pace in [0, CALM_PACE] {
1214            let set = ember_set(5, pace);
1215            let t = hero_time(&set);
1216            assert_eq!(t, hero_time(&ember_set(5, pace)));
1217            assert!(t < HERO_STEP_MS * HERO_CANDIDATES);
1218        }
1219    }
1220}