use crate::common::EffectRng;
use crate::rain::digital_rain::DigitalRainOptions;
use rand::{
self, Rng, RngExt,
distr::{Distribution, StandardUniform},
seq::IndexedRandom,
};
use std::sync::LazyLock;
use std::time::Duration;
const CHARACTER_SETS: &[&str] = &[
"012345789", r#":."=*+-<>"#, "ハミヒーウシナモニサワツオリアホテマケメエカキムユラセネスタヌヘ", "¦çリク", ];
static CHARACTERS: LazyLock<Vec<char>> =
LazyLock::new(|| CHARACTER_SETS.concat().chars().collect());
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RainDropStyle {
Front,
Middle,
Back,
Fading,
Gradient,
}
impl RainDropStyle {
pub const ALL: &'static [RainDropStyle] = &[
RainDropStyle::Front,
RainDropStyle::Middle,
RainDropStyle::Back,
RainDropStyle::Fading,
RainDropStyle::Gradient,
];
}
pub struct RainDrop {
pub _drop_id: usize,
pub body: Vec<char>,
pub style: RainDropStyle,
pub fx: u16,
pub fy: f32,
pub max_length: usize,
pub speed: u16,
}
impl Distribution<RainDropStyle> for StandardUniform {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> RainDropStyle {
match rng.random_range(1..=100) {
1..=10 => RainDropStyle::Front,
11..=20 => RainDropStyle::Middle,
21..=40 => RainDropStyle::Back,
41..=50 => RainDropStyle::Fading,
_ => RainDropStyle::Gradient,
}
}
}
impl RainDrop {
pub fn new(
screen_size: (u16, u16),
options: &DigitalRainOptions,
drop_id: usize,
rng: &mut EffectRng,
) -> Self {
let style: RainDropStyle = rng.random();
let fx: u16 = rng.random_range(0..screen_size.0.max(1));
let height = screen_size.1 as usize;
let fy: f32 = rng.random_range(0..(height / 4).max(1)) as f32;
let max_length_ceiling = (2 * height / 3).max(4);
let max_length: usize = rng.random_range(4..=max_length_ceiling);
let speed: u16 =
rng.random_range(options.get_min_speed()..=options.get_max_speed());
let init_length = rng.random_range(1..max_length / 2);
let mut body: Vec<char> = vec![*CHARACTERS.choose(rng).unwrap()];
for _ in 1..init_length {
body.push(*CHARACTERS.choose(rng).unwrap());
}
Self::from_values(drop_id, body, style, fx, fy, max_length, speed)
}
#[inline(always)]
pub fn from_values(
_drop_id: usize,
body: Vec<char>,
style: RainDropStyle,
fx: u16,
fy: f32,
max_length: usize,
speed: u16,
) -> Self {
Self {
_drop_id,
body,
style,
fx,
fy,
max_length,
speed,
}
}
#[inline]
pub fn to_point(&self) -> (u16, u16) {
let x = self.fx;
let y = self.fy.round() as u16;
(x, y)
}
pub fn to_points_vec(&self) -> Vec<(u16, u16, char)> {
let mut points = vec![];
let (head_x, head_y) = self.to_point();
for (index, character) in self.body.iter().enumerate() {
let yy = head_y as i16 - index as i16;
if yy >= 0 {
points.push((head_x, yy as u16, *character));
} else {
break;
};
}
points
}
fn reset(
&mut self,
screen_size: (u16, u16),
options: &DigitalRainOptions,
rng: &mut EffectRng,
) {
self.body.clear();
self.body.insert(0, *CHARACTERS.choose(rng).unwrap());
self.style = rng.random();
self.fy = 0.0;
self.fx = rng.random_range(0..screen_size.0.max(1));
self.speed =
rng.random_range(options.get_min_speed()..=options.get_max_speed());
let (lo, hi) = (
screen_size.1 / 4 + 1,
(screen_size.1 / 2).max(screen_size.1 / 4 + 1),
);
self.max_length = rng.random_range(lo..=hi) as usize;
}
fn grow_condition(&self) -> bool {
self.speed > 8
}
fn grow(&mut self, head_y: u16, rng: &mut EffectRng) {
if self.body.len() >= self.max_length {
self.body.truncate(self.max_length);
return;
};
match self.grow_condition() {
true => {
let delta: i16 = head_y as i16 - self.fy.round() as i16;
if delta > 0 {
for _ in 0..delta as usize {
self.body.insert(0, *CHARACTERS.choose(rng).unwrap());
}
};
}
false => {
let delta: i16 = head_y as i16 - self.fy.round() as i16;
if delta > 0 {
self.body.insert(0, *CHARACTERS.choose(rng).unwrap());
};
}
};
self.body.truncate(self.max_length);
}
pub fn update(
&mut self,
screen_size: (u16, u16),
options: &DigitalRainOptions,
dt: Duration,
rng: &mut EffectRng,
) {
if self.body.is_empty() {
self.reset(screen_size, options, rng);
return;
}
let fy = self.fy + self.speed as f32 * dt.as_secs_f32();
let head_y = fy.round() as u16;
let tail_y = fy.round() as i16 - self.body.len() as i16;
let height = screen_size.1;
if tail_y <= 0 {
self.grow(head_y, rng);
self.fy = fy;
return;
};
if (head_y <= height) && (tail_y > 0) {
self.grow(head_y, rng);
self.fy = fy;
return;
};
if (head_y > height) && (tail_y < height as i16) {
self.fy = fy;
return;
};
if tail_y as u16 >= height {
self.reset(screen_size, options, rng);
};
}
}
#[cfg(test)]
mod tests {
use super::{super::digital_rain::DigitalRainOptions, *};
use crate::common::seeded_rng;
use std::ops::RangeInclusive;
#[test]
fn the_character_pool_is_flattened_in_the_declared_order() {
let expected: Vec<char> = CHARACTER_SETS.concat().chars().collect();
assert_eq!(
*CHARACTERS, expected,
"the pool is not the declared concatenation, so a seeded run is not \
reproducible across processes"
);
assert!(
CHARACTER_SETS.len() > 1,
"the sets were merged into one, which loses the documentation of what \
each group is for"
);
}
#[test]
fn no_character_in_the_pool_is_double_width() {
for set in CHARACTER_SETS {
for glyph in set.chars() {
let ambiguous_or_narrow = glyph.is_ascii()
|| ('\u{00A0}'..='\u{00FF}').contains(&glyph)
|| ('\u{FF61}'..='\u{FF9F}').contains(&glyph);
assert!(
ambiguous_or_narrow,
"{glyph:?} (U+{:04X}) in {set:?} is double-width, and will \
shear the grid",
glyph as u32
);
}
}
}
#[test]
fn the_katakana_are_the_bulk_of_the_pool() {
const HALFWIDTH_KANA: RangeInclusive<char> = '\u{FF61}'..='\u{FF9F}';
const FULLWIDTH_KANA: RangeInclusive<char> = '\u{30A0}'..='\u{30FF}';
const DIGITS: &str = "012345789";
let total = CHARACTERS.len();
let kana = CHARACTERS
.iter()
.filter(|glyph| HALFWIDTH_KANA.contains(*glyph))
.count();
assert!(
kana * 2 > total,
"the pool holds {kana} halfwidth kana of {total} characters, which is \
not a majority, so the balance the user described is gone"
);
assert!(
total >= DIGITS.len() * 2,
"the whole pool is only {total} characters, which is barely longer \
than a drop, so the columns repeat inside themselves and the rain \
reads as scratches"
);
for glyph in CHARACTERS.iter() {
assert!(
!FULLWIDTH_KANA.contains(glyph),
"{glyph:?} (U+{:04X}) is a fullwidth kana and takes two columns, \
which shears the grid",
*glyph as u32
);
}
}
fn get_sane_options() -> DigitalRainOptions {
DigitalRainOptions {
drops_range: (20, 30),
speed_range: (10, 20),
..Default::default()
}
}
#[test]
fn create_new_and_reset() {
let mut rng = seeded_rng(1, "rain_drop_test");
let mut new_drop =
RainDrop::new((100, 100), &get_sane_options(), 1, &mut rng);
assert!(!new_drop.body.is_empty());
assert!(new_drop.speed > 0);
new_drop.reset((100, 100), &get_sane_options(), &mut rng);
assert_eq!(new_drop.fy, 0.0);
assert_eq!(new_drop._drop_id, 1);
assert_eq!(new_drop.body.len(), 1);
}
#[test]
fn generate_a_lot_of_drops() {
let mut rng = seeded_rng(1, "rain_drop_test");
let mut drops = vec![];
for index in 1..=1000 {
drops.push(RainDrop::new(
(100, 100),
&get_sane_options(),
index,
&mut rng,
));
}
assert_eq!(drops.len(), 1000);
}
#[test]
fn to_point() {
let new_drop = RainDrop::from_values(
1,
vec!['a'],
RainDropStyle::Gradient,
10,
10.8,
20,
10,
);
let (x, y) = new_drop.to_point();
assert_eq!(x, 10);
assert_eq!(y, 11);
}
#[test]
fn to_point_vec() {
let new_drop = RainDrop::from_values(
1,
vec!['a', 'b', 'c'],
RainDropStyle::Fading,
10,
10.0,
10,
8,
);
let points = new_drop.to_points_vec();
assert_eq!(points.len(), 3);
assert_eq!(points[0], (10, 10, 'a'));
}
#[test]
fn grow() {
let mut rng = seeded_rng(1, "rain_drop_test");
let mut new_drop = RainDrop::from_values(
1,
vec!['a'],
RainDropStyle::Front,
10,
10.8,
20,
10,
);
new_drop.grow(10, &mut rng);
assert_eq!(new_drop.body.len(), 1);
assert_eq!(new_drop.body.first(), Some(&'a'));
let mut new_drop = RainDrop::from_values(
1,
vec!['b'],
RainDropStyle::Middle,
10,
10.8,
20,
4,
);
new_drop.grow(12, &mut rng);
assert_eq!(new_drop.body.len(), 2);
assert_eq!(new_drop.body.get(1), Some(&'b'));
new_drop.grow(11, &mut rng);
assert_eq!(new_drop.body.len(), 2);
let mut new_drop = RainDrop::from_values(
1,
vec!['c'],
RainDropStyle::Back,
10,
10.8,
3,
4,
);
for _ in 1..10 {
new_drop.grow(12, &mut rng);
}
assert_eq!(new_drop.body.len(), 3);
}
#[test]
fn update() {
let mut rng = seeded_rng(1, "rain_drop_test");
let mut new_drop = RainDrop::from_values(
1,
vec!['c'],
RainDropStyle::Back,
10,
10.8,
3,
10,
);
new_drop.update(
(100, 100),
&get_sane_options(),
Duration::from_millis(1000),
&mut rng,
);
assert_eq!(new_drop.fy.round() as u16, 21);
assert_eq!(new_drop.body.len(), 3);
let mut new_drop =
RainDrop::from_values(1, vec![], RainDropStyle::Middle, 10, 10.8, 3, 8);
new_drop.update(
(100, 100),
&get_sane_options(),
Duration::from_millis(1000),
&mut rng,
);
assert_eq!(new_drop.body.len(), 1);
assert_eq!(new_drop.fy, 0.0);
let mut new_drop = RainDrop::from_values(
1,
vec!['a', 'b', 'c', 'd'],
RainDropStyle::Fading,
10,
2.0,
5,
2,
);
new_drop.update(
(100, 100),
&get_sane_options(),
Duration::from_millis(1000),
&mut rng,
);
assert_eq!(new_drop.body.len(), 5);
assert!((new_drop.fy - new_drop.body.len() as f32) < 0.0);
let mut new_drop = RainDrop::from_values(
1,
vec!['a', 'b', 'c', 'd'],
RainDropStyle::Fading,
10,
30.8,
5,
2,
);
new_drop.update(
(100, 100),
&get_sane_options(),
Duration::from_millis(1000),
&mut rng,
);
assert_eq!(new_drop.body.len(), 5);
assert!(new_drop.fy > 30.0);
let mut new_drop = RainDrop::from_values(
1,
vec!['a', 'b'],
RainDropStyle::Fading,
10,
29.0,
5,
2,
);
new_drop.update(
(100, 100),
&get_sane_options(),
Duration::from_millis(1000),
&mut rng,
);
assert_eq!(new_drop.body.len(), 3);
assert_eq!(new_drop.fy, 31.0);
new_drop.update(
(100, 100),
&get_sane_options(),
Duration::from_millis(1000),
&mut rng,
);
assert_eq!(new_drop.fy, 33.0); }
#[test]
fn out_of_bounds() {
let mut rng = seeded_rng(1, "rain_drop_test");
let mut drops = vec![];
for i in 1..=10 {
drops.push(RainDrop::new((100, 100), &get_sane_options(), i, &mut rng));
}
assert_eq!(drops.len(), 10);
for _ in 1..=1000 {
for drop in drops.iter_mut() {
drop.update(
(100, 100),
&get_sane_options(),
Duration::from_millis(100),
&mut rng,
)
}
}
}
}