matrixr 1.1.0

Animated Matrix-style terminal screensaver
Documentation
use rand::{Rng, RngExt};

pub(crate) const VALUE_EMPTY: i32 = -1;
const VALUE_SPACE: i32 = ' ' as i32;
pub(crate) const VALUE_DOT: i32 = 0;
pub(crate) const VALUE_BAR: i32 = 1;
const VALUE_LAMBDA: i32 = 'λ' as i32;
const TAIL_FADE_DISTANCE_LIMIT: usize = 6;
const DEEP_MOTION_SCALE: u8 = 6;

#[derive(Clone, Copy)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
pub(crate) struct Cell {
    pub(crate) val: i32,
    pub(crate) is_head: bool,
}

impl Default for Cell {
    fn default() -> Self {
        Self {
            val: VALUE_EMPTY,
            is_head: false,
        }
    }
}

pub(crate) struct EngineFlags {
    pub(crate) asynchronous: bool,
    pub(crate) deep: bool,
    pub(crate) old_style: bool,
    pub(crate) dynamic_chars: bool,
    pub(crate) paused: bool,
}

#[derive(Clone, Copy)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
pub(crate) struct Charset {
    rand_min: i32,
    high_num: i32,
    lambda_mode: bool,
}

impl Charset {
    pub(crate) fn from_modes(classic: bool, console_or_xwindow: bool) -> Self {
        let (rand_min, high_num) = if classic {
            (0xff66, 0xff9d)
        } else if console_or_xwindow {
            (166, 217)
        } else {
            (33, 123)
        };

        Self {
            rand_min,
            high_num,
            lambda_mode: false,
        }
    }

    pub(crate) fn with_lambda_mode(mut self, enabled: bool) -> Self {
        self.lambda_mode = enabled;
        self
    }

    fn random_symbol<R: Rng>(&self, rng: &mut R) -> i32 {
        if self.lambda_mode {
            VALUE_LAMBDA
        } else {
            rng.random_range(self.rand_min..self.high_num)
        }
    }

    fn random_oldstyle_selector<R: Rng>(&self, rng: &mut R) -> i32 {
        rng.random_range(self.rand_min..self.high_num + 8)
    }
}

#[cfg_attr(test, derive(Debug, Clone, PartialEq, Eq))]
pub(crate) struct MatrixState {
    width: usize,
    height: usize,
    cells: Vec<Cell>,
    lengths: Vec<usize>,
    spaces: Vec<usize>,
    updates: Vec<u8>,
    deep_progress: Vec<u8>,
}

impl MatrixState {
    pub(crate) fn new<R: Rng>(width: u16, height: u16, rng: &mut R) -> Self {
        let (width, height) = clamp_dimensions(width, height);
        let mut state = Self {
            width,
            height,
            cells: vec![Cell::default(); (height + 1) * width],
            lengths: vec![0; width],
            spaces: vec![0; width],
            updates: vec![1; width],
            deep_progress: (0..width)
                .map(|col| ((col / 2) % usize::from(DEEP_MOTION_SCALE)) as u8)
                .collect(),
        };
        for col in (0..state.width).step_by(2) {
            state.spaces[col] = rng.random_range(1..=state.height);
            state.lengths[col] = rng.random_range(3..=state.max_stream_length());
            state.set_value(1, col, VALUE_SPACE);
            state.updates[col] = rng.random_range(1..=3);
        }
        state
    }

    pub(crate) fn resize<R: Rng>(&mut self, width: u16, height: u16, rng: &mut R) {
        *self = Self::new(width, height, rng);
    }

    pub(crate) fn step<R: Rng>(
        &mut self,
        tick: u8,
        flags: &EngineFlags,
        charset: Charset,
        rng: &mut R,
    ) {
        if flags.paused {
            return;
        }

        for column in (0..self.width).step_by(2) {
            let should_update = if flags.asynchronous {
                tick > self.updates[column]
            } else if flags.deep {
                self.advance_deep_column(column)
            } else {
                true
            };
            if should_update {
                if flags.old_style {
                    self.update_old_style_column(column, charset, rng);
                } else {
                    self.update_new_style_column(column, flags.dynamic_chars, charset, rng);
                }
            }
        }
    }

    pub(crate) fn width(&self) -> usize {
        self.width
    }

    pub(crate) fn height(&self) -> usize {
        self.height
    }

    pub(crate) fn cell(&self, row: usize, col: usize) -> Cell {
        self.cells[self.index(row, col)]
    }

    pub(crate) fn depth_plane(&self, col: usize) -> u8 {
        self.updates[col]
    }

    fn advance_deep_column(&mut self, col: usize) -> bool {
        let increment = match self.depth_plane(col) {
            1 => DEEP_MOTION_SCALE,
            2 => 4,
            _ => 3,
        };
        let progress = self.deep_progress[col] + increment;
        self.deep_progress[col] = progress % DEEP_MOTION_SCALE;
        progress >= DEEP_MOTION_SCALE
    }

    pub(crate) fn tail_distance_to_head(&self, row: usize, col: usize) -> usize {
        let current = self.cell(row, col);
        if current.is_head || current.val == VALUE_DOT {
            return 0;
        }

        let mut distance = 0;
        for next_row in row + 1..=self.height {
            if self.is_blank_at(next_row, col) {
                break;
            }
            distance += 1;
            if distance == TAIL_FADE_DISTANCE_LIMIT {
                break;
            }
            let next = self.cell(next_row, col);
            if next.is_head || next.val == VALUE_DOT {
                break;
            }
        }
        distance
    }

    fn value_at(&self, row: usize, col: usize) -> i32 {
        self.cells[self.index(row, col)].val
    }

    fn set_value(&mut self, row: usize, col: usize, value: i32) {
        let idx = self.index(row, col);
        self.cells[idx].val = value;
    }

    fn set_head(&mut self, row: usize, col: usize, is_head: bool) {
        let idx = self.index(row, col);
        self.cells[idx].is_head = is_head;
    }

    fn max_stream_length(&self) -> usize {
        self.height.saturating_sub(1).max(3)
    }

    fn index(&self, row: usize, col: usize) -> usize {
        row * self.width + col
    }

    fn is_blank_at(&self, row: usize, col: usize) -> bool {
        matches!(self.value_at(row, col), VALUE_SPACE | VALUE_EMPTY)
    }

    fn update_old_style_column<R: Rng>(&mut self, col: usize, charset: Charset, rng: &mut R) {
        for row in (1..self.height).rev() {
            let prev = self.cell(row - 1, col);
            let idx = self.index(row, col);
            self.cells[idx] = prev;
        }

        let random = charset.random_oldstyle_selector(rng);
        let below = self.value_at(1, col);
        if below == VALUE_DOT {
            self.set_value(0, col, VALUE_BAR);
        } else if matches!(below, VALUE_SPACE | VALUE_EMPTY) {
            if self.spaces[col] > 0 {
                self.set_value(0, col, VALUE_SPACE);
                self.spaces[col] -= 1;
            } else {
                if rng.random_ratio(1, 3) {
                    self.set_value(0, col, VALUE_DOT);
                } else {
                    self.set_value(0, col, charset.random_symbol(rng));
                }
                self.spaces[col] = rng.random_range(1..=self.height);
            }
        } else if random > charset.high_num && below != VALUE_BAR {
            self.set_value(0, col, VALUE_SPACE);
        } else {
            self.set_value(0, col, charset.random_symbol(rng));
        }
    }

    fn update_new_style_column<R: Rng>(
        &mut self,
        col: usize,
        dynamic_chars: bool,
        charset: Charset,
        rng: &mut R,
    ) {
        let starts_new_stream =
            self.value_at(0, col) == VALUE_EMPTY && self.value_at(1, col) == VALUE_SPACE;
        if starts_new_stream {
            if self.spaces[col] > 0 {
                self.spaces[col] -= 1;
            } else {
                self.lengths[col] = rng.random_range(3..=self.max_stream_length());
                self.set_value(0, col, charset.random_symbol(rng));
                self.spaces[col] = rng.random_range(1..=self.height);
            }
        }

        let mut i = 0usize;
        let mut first_column_done = false;
        while i <= self.height {
            while i <= self.height && self.is_blank_at(i, col) {
                i += 1;
            }

            if i > self.height {
                break;
            }

            let z = i;
            let mut y = 0usize;
            while i <= self.height && !self.is_blank_at(i, col) {
                self.set_head(i, col, false);
                if dynamic_chars && rng.random_ratio(1, 8) {
                    self.set_value(i, col, charset.random_symbol(rng));
                }
                i += 1;
                y += 1;
            }

            if i > self.height {
                self.set_value(z, col, VALUE_SPACE);
                continue;
            }

            self.set_value(i, col, charset.random_symbol(rng));
            self.set_head(i, col, true);

            if y > self.lengths[col] || first_column_done {
                self.set_value(z, col, VALUE_SPACE);
                self.set_value(0, col, VALUE_EMPTY);
            }
            first_column_done = true;
            i += 1;
        }
    }
}

fn clamp_dimensions(width: u16, height: u16) -> (usize, usize) {
    (usize::from(width.max(10)), usize::from(height.max(10)))
}

#[cfg(test)]
mod tests;