use crate::buffer::{Buffer, Cell};
use crate::canvas::Canvas;
use crate::common::{DEFAULT_SEED, EffectRng, TerminalEffect, seeded_rng};
use crate::render::glyph_ramp::{self, GlyphRamp};
use crossterm::style;
use serde::{Deserialize, Serialize};
use std::f64::consts::{PI, SQRT_2};
use std::sync::LazyLock;
const SQRT_3: f64 = 1.732_050_807_568_877_2;
const SQRT_5: f64 = 2.236_067_977_499_79;
const SQRT_7: f64 = 2.645_751_311_064_590_7;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PlasmaOptions {
pub time_scale: f64,
pub spatial_scale: f64,
pub color_speed: f64,
pub glyphs: String,
pub seed: u64,
}
impl Default for PlasmaOptions {
fn default() -> Self {
Self {
time_scale: 0.5,
seed: DEFAULT_SEED,
spatial_scale: 1.0,
color_speed: DEFAULT_COLOR_SPEED,
glyphs: DEFAULT_GLYPHS.to_string(),
}
}
}
const DEFAULT_COLOR_SPEED: f64 = 4.0;
const PALETTE_SATURATION: f64 = 1.0;
const PALETTE_MIN_VALUE: f64 = 0.40;
const PALETTE_LEN: usize = 256;
const DEFAULT_GLYPHS: &str = " '.-:=;*+X#O%&M@";
const VALUE_BOUNDARIES: [f64; 15] = [
0.237, 0.295, 0.337, 0.372, 0.402, 0.431, 0.459, 0.487, 0.515, 0.544, 0.573,
0.604, 0.639, 0.683, 0.737,
];
const STEP_LUT_LEN: usize = 1 << 16;
static STEP_LUT: LazyLock<[u8; STEP_LUT_LEN]> = LazyLock::new(|| {
let mut table = [0u8; STEP_LUT_LEN];
for (bucket, slot) in table.iter_mut().enumerate() {
let value = bucket as f64 / (STEP_LUT_LEN - 1) as f64;
*slot = VALUE_BOUNDARIES.partition_point(|bound| *bound <= value) as u8;
}
table
});
#[derive(Clone, Copy)]
struct Segment {
low: f64,
inv_span: f64,
out_low: f64,
out_span: f64,
}
static SEGMENTS: [Segment; 16] = {
let mut built = [Segment {
low: 0.0,
inv_span: 0.0,
out_low: 0.0,
out_span: 0.0,
}; 16];
let mut index = 0;
while index < 16 {
let (low, high) = match index {
0 => (0.0, VALUE_BOUNDARIES[0]),
15 => (VALUE_BOUNDARIES[14], 1.0),
_ => (VALUE_BOUNDARIES[index - 1], VALUE_BOUNDARIES[index]),
};
let (out_low, out_high) = match index {
0 => (0.0, 0.5 / 15.0),
15 => (14.5 / 15.0, 1.0),
_ => ((index as f64 - 0.5) / 15.0, (index as f64 + 0.5) / 15.0),
};
built[index] = Segment {
low,
inv_span: if high > low { 1.0 / (high - low) } else { 0.0 },
out_low,
out_span: out_high - out_low,
};
index += 1;
}
built
};
fn glyph_value(value: f64) -> f64 {
let value = if value.is_nan() {
0.0
} else {
value.clamp(0.0, 1.0)
};
let bucket = ((value * (STEP_LUT_LEN - 1) as f64).round() as usize)
.min(STEP_LUT_LEN - 1);
let index = STEP_LUT[bucket] as usize;
let segment = SEGMENTS[index];
let fraction = ((value - segment.low) * segment.inv_span).clamp(0.0, 1.0);
segment.out_low + fraction * segment.out_span
}
fn glyph_ramp(configured: &str) -> GlyphRamp {
let glyphs: Vec<char> = configured
.chars()
.filter(|glyph| {
!glyph.is_control() && glyph_ramp::is_ambiguous_or_narrow(*glyph)
})
.collect();
if glyphs.is_empty() {
GlyphRamp::from_text(DEFAULT_GLYPHS)
} else {
GlyphRamp::new(glyphs)
}
}
const CELL_ASPECT: f64 = 1.2;
#[derive(Debug, Clone, Copy)]
struct DivisorBand {
center: f64,
jitter: f64,
}
impl DivisorBand {
const fn new(center: f64, jitter: f64) -> Self {
Self { center, jitter }
}
fn draw(&self, rng: &mut EffectRng) -> f64 {
use rand::RngExt;
self.center * rng.random_range(1.0 - self.jitter..=1.0 + self.jitter)
}
}
const WAVE_DIVISOR: DivisorBand = DivisorBand::new(8.0, 0.30);
const SWEEP_DIVISOR: DivisorBand = DivisorBand::new(16.0, 0.30);
const RING_DIVISOR: DivisorBand = DivisorBand::new(4.0, 0.25);
const BREATH_DIVISOR: DivisorBand = DivisorBand::new(5.5, 0.30);
const DIAGONAL_DIVISOR: DivisorBand = DivisorBand::new(12.0, 0.30);
const SWEEP_DEPTH: f64 = 0.25;
const RING_DEPTH: f64 = 0.9;
const BREATH_DEPTH: f64 = 0.55;
const DIAGONAL_DEPTH: f64 = 0.6;
const TIME_FREQ_RIPPLE: f64 = 0.5;
const TIME_FREQ_WAVE: f64 = SQRT_2 / 2.0;
const TIME_FREQ_SWEEP: f64 = SQRT_3 / 2.0;
const TIME_FREQ_DIAGONAL: f64 = SQRT_5 / 2.0;
const TIME_FREQ_BREATH: f64 = SQRT_7 / 2.0;
#[derive(Debug, Clone, Copy, PartialEq)]
struct FieldTuning {
wave_divisor: f64,
sweep_divisor: f64,
ring_divisor: f64,
breath_divisor: f64,
diagonal_divisor: f64,
phase: [f64; 5],
}
impl FieldTuning {
fn from_seed(seed: u64) -> Self {
use rand::RngExt;
let mut rng = seeded_rng(seed, "plasma");
Self {
wave_divisor: WAVE_DIVISOR.draw(&mut rng),
sweep_divisor: SWEEP_DIVISOR.draw(&mut rng),
ring_divisor: RING_DIVISOR.draw(&mut rng),
breath_divisor: BREATH_DIVISOR.draw(&mut rng),
diagonal_divisor: DIAGONAL_DIVISOR.draw(&mut rng),
phase: std::array::from_fn(|_| rng.random_range(0.0..2.0 * PI)),
}
}
fn wave(&self, x: f64, now: f64) -> f64 {
((x / self.wave_divisor - (now * TIME_FREQ_WAVE).cos()) + self.phase[0])
.sin()
}
fn sweep(&self, y: f64, now: f64) -> f64 {
((y / self.sweep_divisor - (now * TIME_FREQ_SWEEP).sin() * SWEEP_DEPTH)
+ self.phase[1])
.sin()
}
fn ring(&self, radius: f64, now: f64) -> f64 {
((radius / self.ring_divisor - (now * TIME_FREQ_RIPPLE).sin() * RING_DEPTH)
+ self.phase[2])
.sin()
}
fn breath(&self, radius: f64, now: f64) -> f64 {
((radius / self.breath_divisor
+ (now * TIME_FREQ_BREATH).cos() * BREATH_DEPTH)
+ self.phase[3])
.sin()
}
fn diagonal(&self, x: f64, y: f64, now: f64) -> f64 {
(((x + y) / self.diagonal_divisor
- (now * TIME_FREQ_DIAGONAL).cos() * DIAGONAL_DEPTH)
+ self.phase[4])
.sin()
}
fn value(&self, x: f64, y: f64, now: f64, w: f64, h: f64, scale: f64) -> f64 {
let radius = ((x - w / 2.0).powi(2) + (y - h / 2.0).powi(2)).sqrt();
let value = (128.0
+ (128.0 * self.wave(x * scale, now))
+ 128.0
+ (128.0 * self.sweep(y * scale, now))
+ 128.0
+ (128.0 * self.ring(radius * scale, now))
+ 128.0
+ (128.0 * self.breath(radius * scale, now))
+ 128.0
+ (128.0 * self.diagonal(x * scale, y * scale, now)))
/ 5.0;
(value / 256.0).clamp(0.0, 1.0)
}
}
pub struct Plasma {
pub screen_size: (u16, u16),
options: PlasmaOptions,
canvas: Canvas,
time: f64,
palette: Vec<style::Color>,
ramp: GlyphRamp,
tuning: FieldTuning,
}
impl TerminalEffect for Plasma {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.canvas.clear();
Self::update_plasma(
self.screen_size,
self.time,
self.options.color_speed,
self.options.spatial_scale,
&self.palette,
&self.ramp,
&self.tuning,
self.canvas.surface_mut(),
);
self.canvas.commit()
}
fn update(&mut self) {
self.advance(1.0 / 60.0);
}
fn update_with_context(&mut self, context: &crate::runtime::FrameContext) {
self.advance(context.delta.as_secs_f32());
}
fn update_size(&mut self, width: u16, height: u16) {
self.screen_size = (width, height);
self.canvas.resize(self.screen_size.0, self.screen_size.1);
self.reset();
}
fn reset(&mut self) {
self.canvas
.resize(self.screen_size.0.max(1), self.screen_size.1.max(1));
self.time = 0.0;
}
}
impl Plasma {
fn advance(&mut self, delta: f32) {
self.time += self.options.time_scale * delta as f64;
}
pub fn new(options: PlasmaOptions, screen_size: (u16, u16)) -> Self {
let canvas = Canvas::new(screen_size.0, screen_size.1);
let time = 0.0;
let palette = Self::generate_palette();
let ramp = glyph_ramp(&options.glyphs);
let tuning = FieldTuning::from_seed(options.seed);
Self {
screen_size,
options,
canvas,
time,
palette,
ramp,
tuning,
}
}
fn generate_palette() -> Vec<style::Color> {
(0..PALETTE_LEN)
.map(|i| {
let hue = i as f64 / PALETTE_LEN as f64;
let value = PALETTE_MIN_VALUE
+ (1.0 - PALETTE_MIN_VALUE) * (PI * hue).sin().abs();
let (r, g, b) = Self::hsv_to_rgb(hue, PALETTE_SATURATION, value);
style::Color::Rgb { r, g, b }
})
.collect()
}
fn hsv_to_rgb(hue: f64, saturation: f64, value: f64) -> (u8, u8, u8) {
let sector = (hue * 6.0).floor();
let f = hue * 6.0 - sector;
let p = value * (1.0 - saturation);
let q = value * (1.0 - f * saturation);
let t = value * (1.0 - (1.0 - f) * saturation);
let (r, g, b) = match (sector as i64).rem_euclid(6) {
0 => (value, t, p),
1 => (q, value, p),
2 => (p, value, t),
3 => (p, q, value),
4 => (t, p, value),
_ => (value, p, q),
};
let to_byte =
|channel: f64| (channel * 255.0).round().clamp(0.0, 255.0) as u8;
(to_byte(r), to_byte(g), to_byte(b))
}
#[allow(clippy::too_many_arguments)]
fn update_plasma(
size: (u16, u16),
now: f64,
color_speed: f64,
spatial_scale: f64,
palette: &[style::Color],
ramp: &GlyphRamp,
tuning: &FieldTuning,
buffer: &mut Buffer,
) {
let width = size.0 as usize;
let height = size.1 as usize;
let w = width as f64;
let h = height as f64 * CELL_ASPECT;
for y in 0..height {
let y_units = y as f64 * CELL_ASPECT;
for x in 0..width {
let value =
tuning.value(x as f64, y_units, now, w, h, spatial_scale);
let color_idx = (value * (PALETTE_LEN - 1) as f64
+ now * color_speed)
.rem_euclid(PALETTE_LEN as f64)
as usize;
let cell_color = palette[color_idx];
let cell = Cell::new(
ramp.sample(glyph_value(value) as f32),
cell_color,
style::Attribute::Reset,
);
buffer.set(x, y, cell);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn the_palette_is_saturated_rather_than_a_pale_wash() {
let palette = Plasma::generate_palette();
for (i, color) in palette.iter().enumerate() {
let style::Color::Rgb { r, g, b } = *color else {
panic!("palette entry {i} is not a truecolor value: {color:?}");
};
let (hi, lo) = (i32::from(r.max(g).max(b)), i32::from(r.min(g).min(b)));
assert!(
hi - lo >= 64,
"palette entry {i} is ({r}, {g}, {b}): a chroma of {} is a pale wash, \
not a colour",
hi - lo
);
assert!(
lo <= 128,
"palette entry {i} is ({r}, {g}, {b}): nothing in it is dark"
);
}
}
#[test]
fn every_drawn_colour_comes_from_the_palette() {
let palette = Plasma::generate_palette();
let mut plasma = Plasma::new(PlasmaOptions::default(), (24, 8));
for frame in 0..3000u64 {
plasma.time = frame as f64 * 0.5;
assert_palette_colours(&plasma.get_diff(), &palette, frame);
}
}
#[test]
fn a_negative_time_still_cycles_the_palette() {
let mut plasma = Plasma::new(PlasmaOptions::default(), (24, 8));
plasma.time = -500.0;
let colours: HashSet<style::Color> = plasma
.get_diff()
.iter()
.map(|(_, _, cell)| cell.color)
.collect();
assert!(
colours.len() > 1,
"a negative time froze the whole screen on one palette entry: \
{colours:?}"
);
}
fn assert_palette_colours(
cells: &[(usize, usize, crate::buffer::Cell)],
palette: &[style::Color],
frame: u64,
) {
for (_, _, cell) in cells {
assert!(
palette.contains(&cell.color),
"frame {frame} drew {:?}, which is not a palette entry",
cell.color
);
}
}
#[test]
fn the_default_palette_speed_leaves_the_screen_alone_between_frames() {
let options = PlasmaOptions::default();
let per_frame = options.color_speed * options.time_scale / 60.0;
assert!(
per_frame < 1.0 / 24.0,
"the palette moves {per_frame:.3} entries per frame, so about {:.0}% \
of the screen changes colour every frame",
per_frame * 100.0
);
let seconds_per_entry = (1.0 / 60.0) / per_frame;
assert!(
seconds_per_entry < 1.0,
"one palette step takes {seconds_per_entry:.1}s, which is too slow to see"
);
}
#[test]
fn plasma_cells_are_not_blanket_bold() {
let mut plasma = Plasma::new(PlasmaOptions::default(), (40, 12));
let diff = plasma.get_diff();
assert!(!diff.is_empty(), "nothing was drawn");
for (x, y, cell) in diff {
assert_eq!(
cell.attr,
style::Attribute::Reset,
"cell ({x}, {y}) is still bold"
);
}
}
#[test]
fn the_glyph_is_a_function_of_the_plasma_value() {
let size = (120u16, 40u16);
let mut plasma = Plasma::new(PlasmaOptions::default(), size);
let by_value = drawn_by_value(&mut plasma, size);
let lowest = by_value.first().expect("nothing was drawn");
let highest = by_value.last().expect("nothing was drawn");
assert_ne!(
lowest.1, highest.1,
"the dimmest cell ({:.3}) and the brightest ({:.3}) both drew {:?}, \
so the glyph is not a function of the value",
lowest.0, highest.0, lowest.1
);
let distinct: HashSet<char> = by_value.iter().map(|(_, g)| *g).collect();
assert!(
distinct.len() >= 4,
"a 120x40 frame drew only {} distinct glyphs ({distinct:?}), so the \
value is barely reaching the ramp at all",
distinct.len()
);
}
#[test]
fn the_glyph_ramp_runs_sparse_to_dense_with_the_value() {
let size = (120u16, 40u16);
let mut plasma = Plasma::new(PlasmaOptions::default(), size);
let by_value = drawn_by_value(&mut plasma, size);
let mut highest_seen = 0usize;
for (value, glyph) in &by_value {
let index = plasma
.ramp
.glyphs()
.iter()
.position(|candidate| candidate == glyph)
.unwrap_or_else(|| panic!("{glyph:?} is not in the ramp"));
assert!(
index >= highest_seen,
"value {value:.3} drew {glyph:?} (ramp step {index}) after the \
sparser step {highest_seen} had already been used, so the ramp \
is running backwards"
);
highest_seen = index;
}
}
#[test]
fn the_rendered_value_is_not_pinned_to_either_end_of_the_ramp() {
let size = (200u16, 50u16);
let mut plasma = Plasma::new(PlasmaOptions::default(), size);
let ramp = plasma.ramp.clone();
let steps = ramp.len();
const WINDOW: f64 = 64.0 * std::f64::consts::PI;
const FRAMES: u64 = 48;
let mut at_bottom = 0usize;
let mut at_top = 0usize;
let mut total = 0usize;
let mut used: HashSet<usize> = HashSet::new();
for frame in 0..FRAMES {
plasma.time = WINDOW * frame as f64 / FRAMES as f64;
for (x, y, cell) in plasma.get_diff() {
let value = value_at(size, x, y, plasma.time);
let index = ramp.index_for(glyph_value(value) as f32);
used.insert(index);
if index == 0 {
at_bottom += 1;
}
if index == steps - 1 {
at_top += 1;
}
total += 1;
assert_eq!(
cell.symbol,
ramp.sample(glyph_value(value) as f32),
"cell ({x}, {y}) at value {value:.3} drew {:?} rather than \
the ramp's own step",
cell.symbol
);
}
}
let bottom = at_bottom as f64 / total as f64;
let top = at_top as f64 / total as f64;
assert!(
bottom < 0.10,
"{:.1}% of samples sit on ramp step 0, so a large region of the \
screen is pinned against the bottom of the range",
bottom * 100.0
);
assert!(
top < 0.10,
"{:.1}% of samples sit on ramp step {}, the top of the ramp",
top * 100.0,
steps - 1
);
let mut vmin = 1.0f64;
let mut vmax = 0.0f64;
for step in 0..400 {
let now = step as f64 * WINDOW / 400.0;
for y in 0..size.1 as usize {
for x in 0..size.0 as usize {
let v = value_at(size, x, y, now);
vmin = vmin.min(v);
vmax = vmax.max(v);
}
}
}
assert_eq!(
used.len(),
steps,
"only {} of {steps} ramp steps were reached; the field spans \
{vmin:.4} to {vmax:.4} over the window, so the ramp divides more \
than the field uses",
used.len()
);
}
#[test]
fn every_glyph_of_the_default_ramp_carries_its_share_of_the_screen() {
let size = (200u16, 50u16);
let shares = glyph_shares(size, 200);
let measured = describe_shares(&shares);
for (step, share) in shares.iter().enumerate() {
assert!(
*share <= 0.20,
"ramp step {step} covers {share:.2}% of a {size:?} screen over 200 \
frames, so it is a shade in name only; the whole distribution is \
[{measured}]"
);
assert!(
*share >= 0.01,
"ramp step {step} covers {share:.2}% of a {size:?} screen over 200 \
frames, so it is effectively not drawn at all; the whole \
distribution is [{measured}]"
);
}
}
#[test]
fn a_short_terminal_thins_the_ends_of_the_ramp() {
let size = (80u16, 24u16);
let shares = glyph_shares(size, 200);
let measured = describe_shares(&shares);
let steps = shares.len();
let busiest = shares.iter().copied().fold(0.0f64, f64::max);
assert!(
busiest <= 0.20,
"at {size:?} one glyph covers {busiest:.2}% of the screen, so the \
calibration is not reaching the small case at all; the whole \
distribution is [{measured}]"
);
let used = shares.iter().filter(|share| **share > 0.0).count();
assert!(
used >= 14,
"only {used} of {steps} ramp steps were drawn at {size:?}, so the ramp \
is barely being used on a small screen; the whole distribution is \
[{measured}]"
);
}
fn describe_shares(shares: &[f64]) -> String {
let ramp = glyph_ramp(&PlasmaOptions::default().glyphs);
let described: Vec<String> = ramp
.glyphs()
.iter()
.zip(shares.iter())
.map(|(glyph, share)| format!("{glyph:?} {:.2}%", share * 100.0))
.collect();
let line = described.join(", ");
println!("plasma glyph shares: {line}");
line
}
fn glyph_shares(size: (u16, u16), frames: u64) -> Vec<f64> {
glyph_shares_for(size, frames, PlasmaOptions::default().seed)
}
fn glyph_shares_for(size: (u16, u16), frames: u64, seed: u64) -> Vec<f64> {
let ramp = glyph_ramp(&PlasmaOptions::default().glyphs);
let tuning = FieldTuning::from_seed(seed);
let mut counts = vec![0usize; ramp.len()];
let mut total = 0usize;
for frame in 0..frames {
let now = frame as f64 * 0.5;
for y in 0..size.1 as usize {
for x in 0..size.0 as usize {
let v = value_at_with(&tuning, size, x, y, now);
let g = glyph_value(v);
let i = ramp.index_for(g as f32);
counts[i] += 1;
total += 1;
}
}
}
assert!(total > 0, "the run drew nothing at all");
counts.iter().map(|c| *c as f64 / total as f64).collect()
}
#[test]
fn the_lookup_tables_agree_with_the_boundaries_they_replace() {
let search = |value: f64| {
let index = VALUE_BOUNDARIES.partition_point(|b| *b <= value);
let (low, high) = match index {
0 => (0.0, VALUE_BOUNDARIES[0]),
15 => (VALUE_BOUNDARIES[14], 1.0),
_ => (VALUE_BOUNDARIES[index - 1], VALUE_BOUNDARIES[index]),
};
let (out_low, out_high) = match index {
0 => (0.0, 0.5 / 15.0),
15 => (14.5 / 15.0, 1.0),
_ => ((index as f64 - 0.5) / 15.0, (index as f64 + 0.5) / 15.0),
};
let fraction = if high <= low {
0.0
} else {
((value - low) / (high - low)).clamp(0.0, 1.0)
};
out_low + fraction * (out_high - out_low)
};
let mut probes: Vec<f64> = vec![0.0, 1.0, 0.5, 1.0 / 3.0];
for bound in VALUE_BOUNDARIES {
for delta in [-1e-9f64, -1e-7, 0.0, 1e-9, 1e-7] {
probes.push((bound + delta).clamp(0.0, 1.0));
}
}
for step in 0..=2000 {
probes.push(f64::from(step) / 2000.0);
}
let tolerance = 0.5 / (STEP_LUT_LEN - 1) as f64;
let count = probes.len();
let mut worst = 0.0f64;
for value in &probes {
worst = worst.max((glyph_value(*value) - search(*value)).abs());
}
assert!(
worst <= tolerance,
"the lookup tables disagree with the boundary search by {worst:.9} over \
{count} probes, which is more than the {tolerance:.9} their resolution \
allows"
);
}
#[test]
fn the_value_remap_is_monotone_and_reaches_both_ends() {
let samples = 20_000;
let mut previous = f64::NEG_INFINITY;
for step in 0..=samples {
let value = step as f64 / samples as f64;
let remapped = glyph_value(value);
assert!(
remapped >= previous,
"glyph_value went backwards: {value:.5} mapped to {remapped:.5} \
after {previous:.5}"
);
previous = remapped;
}
assert_eq!(glyph_value(0.0), 0.0, "the bottom of the range is not 0");
assert_eq!(glyph_value(1.0), 1.0, "the top of the range is not 1");
assert_eq!(
glyph_value(f64::NAN),
glyph_value(0.0),
"a NaN value did not read as the bottom of the range"
);
let ramp = glyph_ramp(&PlasmaOptions::default().glyphs);
let mut reached: HashSet<usize> = HashSet::new();
for step in 0..=samples {
reached.insert(
ramp.index_for(glyph_value(step as f64 / samples as f64) as f32),
);
}
assert_eq!(
reached.len(),
ramp.len(),
"only {} of {} ramp steps have a non-empty preimage under glyph_value, \
so the calibration has a step the field can never draw",
reached.len(),
ramp.len()
);
}
#[test]
fn the_value_boundaries_are_a_sorted_interior_table() {
assert_eq!(
VALUE_BOUNDARIES.len(),
15,
"there are sixteen ramp steps, so fifteen boundaries separate them"
);
for pair in VALUE_BOUNDARIES.windows(2) {
assert!(
pair[1] > pair[0],
"the boundaries run backwards: {} then {}",
pair[0],
pair[1]
);
}
for bound in VALUE_BOUNDARIES {
assert!(
(0.0..1.0).contains(&bound),
"the boundary {bound} is not inside the value range, so a step of \
the ramp can never be reached on one side of it"
);
}
let lowest = VALUE_BOUNDARIES[0];
let highest = 1.0 - VALUE_BOUNDARIES[VALUE_BOUNDARIES.len() - 1];
let ratio = highest / lowest;
assert!(
(0.7..1.4).contains(&ratio),
"the value range below the first boundary is {lowest:.3} and above the \
last is {highest:.3}, a ratio of {ratio:.2}, so the calibration is \
lopsided: one end of the ramp covers a different amount of the field \
from the other"
);
}
#[test]
fn the_bottom_rows_are_not_the_busiest_rows() {
let size = (200u16, 50u16);
for now in [0.0, 0.37, 1.1, 2.6, 4.3, 7.1] {
let (top, bottom) = row_change_ratio(size, now);
assert!(
bottom < top * 1.15,
"at t={now} the bottom four rows changed {:.2}x as fast as the top \
four, so the bottom of the screen is flickering",
bottom / top
);
}
}
#[test]
fn the_field_is_not_stretched_vertically() {
let size = (400u16, 200u16);
let scale = PlasmaOptions::default().spatial_scale;
let tuning = default_tuning();
let at = |x: f64, y: f64| sample(&tuning, size, x, y, 0.0, scale);
let mut horizontal = 0.0f64;
let mut horizontal_samples = 0.0f64;
let mut vertical = 0.0f64;
let mut vertical_samples = 0.0f64;
for y in (0..size.1).step_by(2) {
for x in (0..size.0 - 1).step_by(2) {
let y_units = f64::from(y) * CELL_ASPECT;
horizontal += (at(f64::from(x + 1), y_units)
- at(f64::from(x), y_units))
.abs();
horizontal_samples += 1.0;
}
}
for y in (0..size.1 - 1).step_by(2) {
for x in (0..size.0).step_by(2) {
let xu = f64::from(x);
vertical += (at(xu, f64::from(y + 1) * CELL_ASPECT)
- at(xu, f64::from(y) * CELL_ASPECT))
.abs();
vertical_samples += 1.0;
}
}
let ratio =
(vertical / vertical_samples) / (horizontal / horizontal_samples);
assert!(
(0.4..1.2).contains(&ratio),
"the field changes {ratio:.2}x as fast going down a column as it \
does going across a row, so the radial terms are ellipses rather \
than circles"
);
}
#[test]
fn the_glyph_ramp_round_trips_through_toml() {
let options: PlasmaOptions =
toml::from_str("glyphs = \" .oO@\"").expect("a lone key parses");
assert_eq!(options.glyphs, " .oO@", "the key was not read back");
assert_eq!(
options.time_scale,
PlasmaOptions::default().time_scale,
"one key in the section silently reset the others"
);
let serialised = toml::to_string(&options).expect("the section serialises");
assert!(
serialised.contains("glyphs"),
"the key is missing from the serialised form, so --print-config \
would never write it: {serialised}"
);
}
#[test]
fn an_unusable_glyph_config_falls_back_to_the_default_ramp() {
for configured in ["", "\u{7}\u{1}", "\u{4E2D}"] {
let ramp = glyph_ramp(configured);
assert_eq!(
ramp.glyphs(),
DEFAULT_GLYPHS.chars().collect::<Vec<char>>(),
"{configured:?} did not fall back to the documented default"
);
}
assert_ne!(
DEFAULT_GLYPHS,
glyph_ramp::presets::SHADE,
"the default has become SHADE, which is documented as non-monotonic"
);
assert_ne!(
DEFAULT_GLYPHS,
glyph_ramp::presets::BLOCKS,
"the default has become the block elements again"
);
}
#[test]
fn a_configured_glyph_ramp_is_drawn_in_the_order_given() {
let options = PlasmaOptions {
glyphs: " .:oO@".to_string(),
..Default::default()
};
let mut plasma = Plasma::new(options, (120, 40));
let ramp = plasma.ramp.clone();
assert_eq!(ramp.glyphs(), &[' ', '.', ':', 'o', 'O', '@']);
let drawn: HashSet<char> = plasma
.get_diff()
.iter()
.map(|(_, _, cell)| cell.symbol)
.collect();
for glyph in &drawn {
assert!(
ramp.glyphs().contains(glyph),
"{glyph:?} is not in the configured ramp"
);
}
assert!(
drawn.len() >= 4,
"the configured ramp was barely used: {drawn:?}"
);
}
#[test]
fn the_default_ramp_is_ascii_and_contains_no_block_elements() {
let configured = PlasmaOptions::default().glyphs;
for glyph in configured.chars() {
assert!(
glyph.is_ascii(),
"the default ramp contains {glyph:?} (U+{:04X}); the user asked \
for ASCII characters",
glyph as u32
);
assert!(
!('\u{2580}'..='\u{259F}').contains(&glyph),
"the default ramp contains the block element {glyph:?} \
(U+{:04X}), which is what was asked to be taken out",
glyph as u32
);
}
let mut plasma = Plasma::new(PlasmaOptions::default(), (120, 40));
for glyph in plasma.ramp.glyphs() {
assert!(
glyph.is_ascii() && !('\u{2580}'..='\u{259F}').contains(glyph),
"the ramp the effect draws from is {glyph:?} (U+{:04X})",
*glyph as u32
);
}
let drawn: HashSet<char> = plasma
.get_diff()
.iter()
.map(|(_, _, cell)| cell.symbol)
.collect();
assert!(
drawn.len() >= 4,
"the ASCII default ramp was barely used: {drawn:?}"
);
}
#[test]
fn the_default_ramp_is_ordered_by_estimated_ink_coverage() {
const INK_BY_COVERAGE: &[(char, f32)] = &[
(' ', 0.0), ('\'', 2.0), ('.', 5.0), ('-', 7.0), (':', 11.0), ('=', 12.0), (';', 14.0), ('*', 15.0), ('+', 16.0), ('X', 21.0), ('#', 27.0), ('O', 30.0), ('%', 33.0), ('&', 38.0), ('M', 42.0), ('@', 46.0), ];
let ink = |glyph: char| -> f32 {
match INK_BY_COVERAGE.iter().find(|(c, _)| *c == glyph) {
Some((_, coverage)) => *coverage,
None => panic!(
"{glyph:?} (U+{:04X}) is not in the ink table, so the ramp has \
grown a character whose weight has not been argued about. Add \
it, with a reason.",
glyph as u32
),
}
};
let shade_inversions: Vec<String> = glyph_ramp::presets::SHADE
.chars()
.collect::<Vec<char>>()
.windows(2)
.filter(|pair| ink(pair[1]) < ink(pair[0]))
.map(|pair| format!("{}{}", pair[0], pair[1]))
.collect();
assert_eq!(
shade_inversions,
[":-", "+*"],
"the ink table no longer finds the inversions it is supposed to find \
in SHADE, so it cannot be trusted to clear the default ramp"
);
let ramp = glyph_ramp(&PlasmaOptions::default().glyphs);
let glyphs = ramp.glyphs();
assert!(
glyphs.len() >= 8,
"the default ramp has {} steps, too few to carry a smooth value \
across a whole screen",
glyphs.len()
);
for pair in glyphs.windows(2) {
assert!(
ink(pair[1]) >= ink(pair[0]),
"ramp steps {}{} run backwards -- {}% then {}% -- so a rising \
value makes the field lighter there",
pair[0],
pair[1],
ink(pair[0]),
ink(pair[1])
);
}
const TIE_RESOLUTION: f32 = 3.0;
const EXPECTED_TIES: &[&str] =
&[" '", "'.", ".-", ":=", "=;", ";*", "*+", "#O", "O%"];
let mut measured: Vec<String> = glyphs
.windows(2)
.filter(|pair| (ink(pair[1]) - ink(pair[0])).abs() <= TIE_RESOLUTION)
.map(|pair| format!("{}{}", pair[0], pair[1]))
.collect();
measured.sort();
let mut named: Vec<String> =
EXPECTED_TIES.iter().map(|t| t.to_string()).collect();
named.sort();
assert_eq!(
measured, named,
"the set of adjacent ramp pairs within the ink table's resolution \
has changed, so either a glyph crossed a boundary or a new tie \
appeared; both need saying out loud"
);
}
#[test]
fn the_field_is_the_five_terms_normalised() {
let size = (200u16, 50u16);
let w = f64::from(size.0);
let h = f64::from(size.1) * CELL_ASPECT;
let scale = PlasmaOptions::default().spatial_scale;
for seed in [DEFAULT_SEED, 0, 1, 987_654_321] {
let tuning = FieldTuning::from_seed(seed);
for now in [0.0, 0.5, 3.7] {
for y in [0usize, 13, 39] {
for x in [0usize, 41, 119] {
let xu = x as f64;
let yu = y as f64 * CELL_ASPECT;
let radius = ((xu - w / 2.0).powi(2)
+ (yu - h / 2.0).powi(2))
.sqrt();
let sines = tuning.wave(xu * scale, now)
+ tuning.sweep(yu * scale, now)
+ tuning.ring(radius * scale, now)
+ tuning.breath(radius * scale, now)
+ tuning.diagonal(xu * scale, yu * scale, now);
let expected = (0.5 + sines / 10.0).clamp(0.0, 1.0);
let drawn = tuning.value(xu, yu, now, w, h, scale);
assert!(
(drawn - expected).abs() < 1e-12,
"seed {seed} at ({x}, {y}) and t={now}: the value is \
{drawn:.6} where the five terms normalised give \
{expected:.6}, so the sum's divisor is not its term \
count"
);
}
}
}
}
}
#[test]
fn the_field_does_not_go_up_and_down() {
const ONE_SECOND: f64 = 0.5;
const MAX_VERTICAL_DRIFT: f64 = 1.6;
for size in [(200u16, 50u16), (400, 200), (80, 24)] {
let ratio = vertical_to_horizontal_drift(size, ONE_SECOND);
assert!(
ratio < MAX_VERTICAL_DRIFT,
"at {size:?} the field drifts {ratio:.2}x as far downwards every \
second as it does sideways, so it is going up and down. The old \
field measured 5.81 here, and putting the sweep term's depth \
back to 2.0 while leaving everything else alone measures 1.88."
);
}
let speed = drift_speed((200, 50), ONE_SECOND);
assert!(
speed > 0.25,
"the field's pattern is drifting at {speed:.3} cells a second, so it \
has stopped travelling altogether -- which satisfies every bound \
above while drawing a still picture"
);
}
fn drift_speed(size: (u16, u16), dt: f64) -> f64 {
let mut total = 0.0f64;
let mut count = 0.0f64;
for seed in SAMPLE_SEEDS {
let tuning = FieldTuning::from_seed(seed);
for now in DRIFT_SAMPLES {
let (ux, uy) = advection_velocity(size, now, dt, &tuning);
total += (ux * ux + uy * uy).sqrt();
count += 1.0;
}
}
total / count
}
#[test]
fn the_field_has_a_diagonal() {
const MIN_ASYMMETRY: f64 = 0.05;
for size in [(200u16, 50u16), (400, 200), (80, 24)] {
let asymmetry = mean_diagonal_asymmetry(size);
assert!(
asymmetry > MIN_ASYMMETRY,
"at {size:?} the field changes by the same amount along the two \
diagonals to within {:.1}%, so its structure is still only \
stripes and rings: every term is a function of x, of y or of \
the radius, and the field has no grain",
asymmetry * 100.0
);
}
}
#[test]
fn the_two_ring_terms_do_not_repeat_inside_the_screen() {
const CAP: f64 = 240.0;
const STEP: f64 = 0.001;
assert_eq!(
radial_joint_period(
RING_DIVISOR.center,
BREATH_DIVISOR.center,
CAP,
STEP
),
None,
"the two ring divisors' centres still come back to themselves within \
{CAP} corrected units, so they are still in a harmonic relationship"
);
let old = radial_joint_period(4.0, 8.0, CAP, STEP).expect(
"the search did not find the old pair's repeat at 16*pi, so it cannot \
be trusted to report that the new pair has none",
);
assert!(
(old - 16.0 * PI).abs() <= STEP,
"the old pair's repeat was found at {old:.4} rather than at 16*pi = {}, \
so the search is measuring something other than the joint period",
16.0 * PI
);
for seed in 0..200u64 {
let tuning =
FieldTuning::from_seed(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15));
assert_eq!(
radial_joint_period(
tuning.ring_divisor,
tuning.breath_divisor,
CAP,
STEP
),
None,
"seed {seed} drew ring divisors {:.4} and {:.4}, whose rings \
repeat within {CAP} corrected units -- inside the screen",
tuning.ring_divisor,
tuning.breath_divisor
);
}
}
#[test]
fn two_seeds_draw_different_fields_on_the_first_frame() {
let size = (120u16, 40u16);
let first_frame = |seed: u64| {
let tuning = FieldTuning::from_seed(seed);
(0..size.1 as usize)
.flat_map(|y| {
(0..size.0 as usize)
.map(move |x| value_at_with(&tuning, size, x, y, 0.0))
})
.collect::<Vec<f64>>()
};
let baseline = first_frame(DEFAULT_SEED);
for other in [0u64, 1, 43, 987_654_321] {
let candidate = first_frame(other);
assert_ne!(
candidate, baseline,
"seed {other} draws the same first frame as the default, so the \
seed is not reaching the field"
);
let mean: f64 = candidate
.iter()
.zip(&baseline)
.map(|(a, b)| (a - b).abs())
.sum::<f64>()
/ baseline.len() as f64;
assert!(
mean > 0.1,
"seed {other} differs from the default by a mean of {mean:.4} on \
the first frame, which is the same picture"
);
}
}
#[test]
fn one_seed_always_draws_the_same_field() {
let size = (120u16, 40u16);
for seed in [DEFAULT_SEED, 0, 1, 43, u64::MAX] {
let first = FieldTuning::from_seed(seed);
let second = FieldTuning::from_seed(seed);
assert_eq!(first, second, "seed {seed} drew two different tunings");
for now in [0.0, 0.5, 3.7] {
for y in [0usize, 13, 39] {
for x in [0usize, 41, 119] {
assert_eq!(
value_at_with(&first, size, x, y, now),
value_at_with(&second, size, x, y, now),
"seed {seed} drew different values at ({x}, {y})"
);
}
}
}
}
}
#[test]
fn the_seeded_divisors_stay_inside_their_bands() {
const SEEDS: u64 = 200;
let bands = [
("wave", WAVE_DIVISOR),
("sweep", SWEEP_DIVISOR),
("ring", RING_DIVISOR),
("breath", BREATH_DIVISOR),
("diagonal", DIAGONAL_DIVISOR),
];
let mut measured: Vec<[f64; 5]> = Vec::new();
for seed in 0..SEEDS {
measured.push(draw_divisors(seed));
}
for (index, (name, band)) in bands.iter().enumerate() {
let column: Vec<f64> = measured.iter().map(|row| row[index]).collect();
let low = column.iter().copied().fold(f64::INFINITY, f64::min);
let high = column.iter().copied().fold(0.0f64, f64::max);
let band_low = band.center * (1.0 - band.jitter);
let band_high = band.center * (1.0 + band.jitter);
assert!(
low >= band_low && high <= band_high,
"the {name} divisor ranged over {low:.3} to {high:.3} over {SEEDS} \
seeds, outside its band of {band_low:.3} to {band_high:.3}: a \
divisor near zero is a flat wash and one near the screen's width \
is a single band, and neither is a plasma"
);
assert!(
low > 0.0,
"the {name} divisor was drawn as {low}, so the term has no \
structure at all -- the band has lost its floor"
);
}
for (index, (name, _)) in bands.iter().enumerate() {
let others: Vec<f64> = bands
.iter()
.enumerate()
.filter(|(other, _)| *other != index)
.map(|(_, (_, band))| band.center)
.collect();
let mine = bands[index].1.center;
assert!(
others.iter().all(|other| (other - mine).abs() > 0.5),
"the {name} divisor's centre is {mine}, which is the same as \
another term's to within half a cell, so the two terms are one \
term drawn twice"
);
}
}
fn draw_divisors(seed: u64) -> [f64; 5] {
let tuning =
FieldTuning::from_seed(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15));
[
tuning.wave_divisor,
tuning.sweep_divisor,
tuning.ring_divisor,
tuning.breath_divisor,
tuning.diagonal_divisor,
]
}
#[test]
fn the_calibration_holds_across_seeds_not_just_the_default_one() {
const MIN_SHARE: f64 = 0.02;
const MAX_SHARE: f64 = 0.20;
let size = (200u16, 50u16);
for seed in [
DEFAULT_SEED,
0u64,
1,
7,
13,
99,
1234,
5150,
65535,
987_654_321,
] {
let shares = glyph_shares_for(size, 60, seed);
let busiest = shares.iter().copied().fold(0.0f64, f64::max);
let sparsest = shares.iter().copied().fold(1.0f64, f64::min);
assert!(
busiest <= MAX_SHARE && sparsest >= MIN_SHARE,
"seed {seed} puts {busiest:.1}% of the screen on one glyph and \
{sparsest:.1}% on another, so the calibration fitted at 200x50 \
does not reach every launch: [{shares:?}]"
);
}
}
#[test]
fn the_field_does_not_come_back_to_where_it_was() {
const SEARCH_FROM: f64 = 0.05;
const SEARCH_TO: f64 = 200.0;
const SEARCH_STEP: f64 = 0.001;
const CYCLE_TOLERANCE: f64 = 1.0e-6;
let frequencies = [
TIME_FREQ_RIPPLE,
TIME_FREQ_WAVE,
TIME_FREQ_SWEEP,
TIME_FREQ_DIAGONAL,
TIME_FREQ_BREATH,
];
let mut steps = (SEARCH_TO - SEARCH_FROM) / SEARCH_STEP;
let mut best: Option<(f64, f64)> = None;
while steps >= 0.0 {
let period = SEARCH_FROM + steps * SEARCH_STEP;
let worst = frequencies
.iter()
.map(|f| {
let cycles = f * period / (2.0 * PI);
(cycles - cycles.round()).abs()
})
.fold(0.0f64, f64::max);
if best.is_none_or(|(_, previous)| worst < previous) {
best = Some((period, worst));
}
if worst <= CYCLE_TOLERANCE {
panic!(
"a period of {period:.3} units advances all {} time \
frequencies ({frequencies:?}) by a whole number of cycles, \
to within {CYCLE_TOLERANCE:e}, so the field repeats on it",
frequencies.len()
);
}
steps -= 1.0;
}
let (period, worst) = best.expect("the search ran at least once");
assert!(
worst > CYCLE_TOLERANCE,
"the closest approach to a common period in the whole search was \
{period:.3} units, off by {worst:.2e} cycles"
);
for (label, period) in [
("8*pi, the period it had", 8.0 * PI),
("2*pi", 2.0 * PI),
("pi", PI),
] {
let mut total = 0.0f64;
let mut samples = 0.0f64;
for now in [0.0, 3.1, 7.7, 11.3, 19.9, 26.3] {
for y in 0..24usize {
for x in 0..80usize {
total += (value_at((80, 24), x, y, now)
- value_at((80, 24), x, y, now + period))
.abs();
samples += 1.0;
}
}
}
let mean = total / samples;
assert!(
mean > 0.01,
"at {label} the field is back where it was: the mean absolute \
difference across a whole 80x24 screen is {mean:.5}, so the \
screen looks the same after {period:.2} units of `plasma.time`"
);
}
let mut drift = 0.0f64;
let mut samples = 0.0f64;
for now in [0.0, 3.1, 7.7, 11.3, 19.9, 26.3] {
for y in 0..24usize {
for x in 0..80usize {
drift += (value_at((80, 24), x, y, now)
- value_at((80, 24), x, y, now + 0.5))
.abs();
samples += 1.0;
}
}
}
let mean = drift / samples;
assert!(
mean > 0.001,
"the field changes by {mean:.6} in half a unit of `plasma.time`, so it \
has stopped moving altogether -- which would satisfy every check \
above while drawing nothing"
);
}
const DRIFT_SAMPLES: [f64; 6] = [0.0, 0.37, 2.6, 7.1, 19.9, 33.7];
const SAMPLE_SEEDS: [u64; 4] = [DEFAULT_SEED, 0, 1, 987_654_321];
fn advection_velocity(
size: (u16, u16),
now: f64,
dt: f64,
tuning: &FieldTuning,
) -> (f64, f64) {
const H: f64 = 1.0e-3;
let (mut sxx, mut sxy, mut syy) = (0.0f64, 0.0f64, 0.0f64);
let (mut sx, mut sy) = (0.0f64, 0.0f64);
let scale = PlasmaOptions::default().spatial_scale;
for y in 0..size.1 as usize {
for x in 0..size.0 as usize {
let xu = x as f64;
let yu = y as f64 * CELL_ASPECT;
let rate = (sample(tuning, size, xu, yu, now + dt, scale)
- sample(tuning, size, xu, yu, now, scale))
/ dt;
let dvdx = (sample(tuning, size, xu + H, yu, now, scale)
- sample(tuning, size, xu - H, yu, now, scale))
/ (2.0 * H);
let dvdy = (sample(tuning, size, xu, yu + H, now, scale)
- sample(tuning, size, xu, yu - H, now, scale))
/ (2.0 * H);
sxx += dvdx * dvdx;
sxy += dvdx * dvdy;
syy += dvdy * dvdy;
sx += dvdx * rate;
sy += dvdy * rate;
}
}
let det = sxx * syy - sxy * sxy;
if det <= f64::EPSILON {
return (0.0, 0.0);
}
(
-(syy * sx - sxy * sy) / det,
-(-sxy * sx + sxx * sy) / det / CELL_ASPECT,
)
}
fn vertical_to_horizontal_drift(size: (u16, u16), dt: f64) -> f64 {
let mut across = 0.0f64;
let mut down = 0.0f64;
for seed in SAMPLE_SEEDS {
let tuning = FieldTuning::from_seed(seed);
for now in DRIFT_SAMPLES {
let (ux, uy) = advection_velocity(size, now, dt, &tuning);
across += ux.abs();
down += uy.abs();
}
}
let samples = (SAMPLE_SEEDS.len() * DRIFT_SAMPLES.len()) as f64;
(down / samples) / (across / samples).max(1e-9)
}
fn diagonal_asymmetry(size: (u16, u16), now: f64, tuning: &FieldTuning) -> f64 {
let scale = PlasmaOptions::default().spatial_scale;
let (mut down_right, mut up_right) = (0.0f64, 0.0f64);
for y in 0..size.1 as usize {
for x in 0..size.0 as usize {
let xu = x as f64;
let yu = y as f64 * CELL_ASPECT;
let here = sample(tuning, size, xu, yu, now, scale);
down_right +=
(sample(tuning, size, xu + 1.0, yu + CELL_ASPECT, now, scale)
- here)
.abs();
up_right +=
(sample(tuning, size, xu + 1.0, yu - CELL_ASPECT, now, scale)
- here)
.abs();
}
}
let mean = (down_right + up_right) / 2.0;
if mean <= 0.0 {
return 0.0;
}
(down_right - up_right).abs() / mean
}
fn mean_diagonal_asymmetry(size: (u16, u16)) -> f64 {
let mut total = 0.0f64;
for seed in SAMPLE_SEEDS {
let tuning = FieldTuning::from_seed(seed);
for now in DRIFT_SAMPLES {
total += diagonal_asymmetry(size, now, &tuning);
}
}
total / (SAMPLE_SEEDS.len() * DRIFT_SAMPLES.len()) as f64
}
fn radial_joint_period(
first: f64,
second: f64,
cap: f64,
step: f64,
) -> Option<f64> {
let coarsest = first.min(second);
let tolerance = 0.75 * step / (2.0 * PI * coarsest);
let mut shift = step;
while shift <= cap {
let cycles = |divisor: f64| {
let c = shift / (2.0 * PI * divisor);
(c - c.round()).abs()
};
if cycles(first) <= tolerance && cycles(second) <= tolerance {
return Some(shift);
}
shift += step;
}
None
}
fn default_tuning() -> FieldTuning {
FieldTuning::from_seed(PlasmaOptions::default().seed)
}
fn value_at(size: (u16, u16), x: usize, y: usize, now: f64) -> f64 {
value_at_with(&default_tuning(), size, x, y, now)
}
fn value_at_with(
tuning: &FieldTuning,
size: (u16, u16),
x: usize,
y: usize,
now: f64,
) -> f64 {
sample(
tuning,
size,
x as f64,
y as f64 * CELL_ASPECT,
now,
PlasmaOptions::default().spatial_scale,
)
}
fn sample(
tuning: &FieldTuning,
size: (u16, u16),
x: f64,
y: f64,
now: f64,
scale: f64,
) -> f64 {
tuning.value(
x,
y,
now,
f64::from(size.0),
f64::from(size.1) * CELL_ASPECT,
scale,
)
}
fn drawn_by_value(plasma: &mut Plasma, size: (u16, u16)) -> Vec<(f64, char)> {
let now = plasma.time;
let mut by_value: Vec<(f64, char)> = plasma
.get_diff()
.iter()
.map(|(x, y, cell)| (value_at(size, *x, *y, now), cell.symbol))
.collect();
by_value.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
by_value
}
fn row_change_ratio(size: (u16, u16), now: f64) -> (f64, f64) {
let scale = PlasmaOptions::default().spatial_scale;
let tuning = default_tuning();
let mut per_row = vec![0.0f64; size.1 as usize];
for (y, row) in per_row.iter_mut().enumerate() {
for x in 0..size.0 as usize {
let xu = x as f64;
*row += (sample(
&tuning,
size,
xu,
(y + 1) as f64 * CELL_ASPECT,
now,
scale,
) - sample(
&tuning,
size,
xu,
y as f64 * CELL_ASPECT,
now,
scale,
))
.abs();
}
}
let width = f64::from(size.0);
let mean =
|rows: &[f64]| rows.iter().sum::<f64>() / rows.len() as f64 / width;
(mean(&per_row[..4]), mean(&per_row[per_row.len() - 4..]))
}
}