use crate::buffer::Cell;
use crate::canvas::Canvas;
use crate::common::{
DEFAULT_SEED, EffectRng, TerminalEffect, normalize_effect_size, seeded_rng,
};
use crate::render::halfblock::{HalfBlockField, ROWS_PER_CELL};
use crate::render::palette::{Palette, presets as palette_presets};
use crate::runtime::FrameContext;
use crossterm::style;
use rand::RngExt;
use serde::{Deserialize, Serialize};
const DEPOSIT: f32 = 5.0;
const DECAY: f32 = 0.90;
const SPREAD: f32 = 0.10;
const DEFAULT_LEVELS: usize = 16;
const MAX_CATCH_UP_STEPS: usize = 4;
const TRAIL_FLOOR: f32 = 3.0;
const TRAIL_CEILING: f32 = 64.0;
const ANNEALED_DECAY: f32 = 0.995;
const ANNEAL_STEPS: u64 = 2_500;
const CHURN_EVERY: u32 = 30;
const CHURN_SETTLED: f32 = 0.15;
const MIN_SETTLED_COVERAGE: f32 = 0.002;
const DEFAULT_HOLD_SECONDS: f32 = 4.0;
const FADE_SECONDS: f32 = 1.5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Phase {
Growing,
Holding,
Fading,
}
#[derive(Debug, Clone, Copy)]
struct Agent {
x: f32,
y: f32,
heading: f32,
}
impl Agent {
fn sense(
&self,
trail: &[f32],
width: usize,
height: usize,
dx: f32,
dy: f32,
) -> f32 {
sample(trail, width, height, self.x + dx, self.y + dy)
}
fn advance(&mut self, step: f32, width: usize, height: usize) {
self.x = wrap(self.x + step * self.heading.cos(), width);
self.y = wrap(self.y + step * self.heading.sin(), height);
}
}
#[inline]
fn wrap(value: f32, n: usize) -> f32 {
if !value.is_finite() {
return 0.0;
}
let limit = n as f32;
let wrapped = value % limit;
let wrapped = if wrapped < 0.0 {
wrapped + limit
} else {
wrapped
};
if wrapped >= limit || wrapped < 0.0 {
0.0
} else {
wrapped
}
}
fn sample(trail: &[f32], width: usize, height: usize, x: f32, y: f32) -> f32 {
let fx = wrap(x, width);
let fy = wrap(y, height);
let (x0, y0) = (fx.floor() as usize, fy.floor() as usize);
let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);
let x1 = (x0 + 1) % width;
let y1 = (y0 + 1) % height;
let top = trail[y0 * width + x0] * (1.0 - tx) + trail[y0 * width + x1] * tx;
let bottom = trail[y1 * width + x0] * (1.0 - tx) + trail[y1 * width + x1] * tx;
top * (1.0 - ty) + bottom * ty
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PhysarumOptions {
#[serde(skip)]
pub agents: u32,
pub agent_coeff: f32,
pub sensor_distance: f32,
pub sensor_angle: f32,
pub turn_angle: f32,
pub move_step: f32,
pub decay: f32,
pub spread: f32,
pub substeps: u16,
pub palette: String,
pub settle: bool,
pub hold_seconds: f32,
pub levels: usize,
pub seed: u64,
}
impl Default for PhysarumOptions {
fn default() -> Self {
Self {
agents: DEFAULT_AGENT_COUNT,
agent_coeff: 1.0,
sensor_distance: 9.0,
sensor_angle: 22.5,
turn_angle: 45.0,
move_step: 1.0,
decay: DECAY,
spread: SPREAD,
substeps: 1,
palette: "ocean".to_string(),
levels: DEFAULT_LEVELS,
settle: true,
hold_seconds: DEFAULT_HOLD_SECONDS,
seed: DEFAULT_SEED,
}
}
}
pub const PHYSARUM_AGENT_DENSITY: f32 = 0.002;
pub const MIN_AGENT_COUNT: u32 = 40;
pub const MAX_AGENT_COUNT: u32 = 30_000;
const DEFAULT_AGENT_COUNT: u32 = 320;
pub struct Physarum {
screen_size: (u16, u16),
options: PhysarumOptions,
canvas: Canvas,
field: HalfBlockField,
trail: Vec<f32>,
scratch: Vec<f32>,
colony: Vec<Agent>,
accumulator: f32,
peak: f32,
phase: Phase,
age_steps: u64,
decay: f32,
marked: Vec<bool>,
marked_valid: bool,
phase_timer: f32,
fade: f32,
last_churn: Option<f32>,
rng: EffectRng,
palette: Palette,
}
impl TerminalEffect for Physarum {
fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
self.draw();
self.canvas.commit()
}
fn update(&mut self) {
self.advance(1.0 / 60.0);
}
fn update_with_context(&mut self, context: &FrameContext) {
self.advance(context.delta.as_secs_f32());
}
fn update_size(&mut self, width: u16, height: u16) {
self.screen_size = (width, height);
self.reset();
}
fn reset(&mut self) {
self.canvas.resize(self.screen_size.0, self.screen_size.1);
self.field
.resize(self.screen_size.0 as usize, self.screen_size.1 as usize);
let (width, height) = self.size();
self.trail = vec![0.0; width * height];
self.scratch = vec![0.0; width * height];
self.marked = vec![false; width * height];
self.accumulator = 0.0;
self.peak = 1.0;
self.rng = seeded_rng(self.options.seed, "physarum");
self.start_growing();
self.spawn();
self.seed_trail();
}
}
impl Physarum {
pub fn new(options: PhysarumOptions, screen_size: (u16, u16)) -> Self {
let screen_size = normalize_effect_size(screen_size);
let field =
HalfBlockField::new(screen_size.0 as usize, screen_size.1 as usize);
let (width, height) = (field.row_width(), field.row_height());
let palette = Palette::new(
Palette::new(
palette_presets::by_name(&options.palette)
.unwrap_or(palette_presets::OCEAN)
.to_vec(),
)
.truncated_at_peak()
.expand(options.levels.max(2)),
);
let mut physarum = Self {
screen_size,
canvas: Canvas::new(screen_size.0, screen_size.1),
trail: vec![0.0; width * height],
scratch: vec![0.0; width * height],
colony: Vec::new(),
accumulator: 0.0,
peak: 1.0,
phase: Phase::Growing,
age_steps: 0,
decay: options.decay.clamp(0.0, 1.0),
marked: vec![false; width * height],
marked_valid: false,
phase_timer: 0.0,
fade: 1.0,
last_churn: None,
field,
rng: seeded_rng(DEFAULT_SEED, "physarum"),
palette,
options,
};
physarum.rng = seeded_rng(physarum.options.seed, "physarum");
physarum.spawn();
physarum.seed_trail();
physarum
}
pub fn field_dimensions(&self) -> (usize, usize) {
self.size()
}
pub fn trail_view(&self) -> &[f32] {
&self.trail
}
fn size(&self) -> (usize, usize) {
(
self.field.row_width(),
self.field.row_height().max(ROWS_PER_CELL),
)
}
fn spawn(&mut self) {
let (width, height) = self.size();
self.colony = (0..self.options.agents.max(1))
.map(|_| Agent {
x: self.rng.random_range(0.0..width as f32),
y: self.rng.random_range(0.0..height as f32),
heading: self.rng.random_range(0.0..std::f32::consts::TAU),
})
.collect();
}
fn seed_trail(&mut self) {
let (width, height) = self.size();
for _ in 0..5 {
let cx = self.rng.random_range(0.0..width as f32);
let cy = self.rng.random_range(0.0..height as f32);
let radius: f32 = self.rng.random_range(6.0..18.0);
let span = (radius * 2.0).ceil() as usize;
for dy in 0..span {
for dx in 0..span {
let px =
(cx - radius + dx as f32).rem_euclid(width as f32) as usize;
let py = (cy - radius + dy as f32).rem_euclid(height as f32)
as usize;
let distance = (px as f32 - cx).hypot(py as f32 - cy);
if distance <= radius {
self.trail[py * width + px] = DEPOSIT;
}
}
}
}
}
fn start_growing(&mut self) {
self.phase = Phase::Growing;
self.age_steps = 0;
self.decay = self.options.decay.clamp(0.0, 1.0);
self.marked_valid = false;
self.phase_timer = 0.0;
self.fade = 1.0;
self.last_churn = None;
}
fn annealed_decay(&self) -> f32 {
let start = self.options.decay.clamp(0.0, 1.0);
if self.age_steps >= ANNEAL_STEPS {
return ANNEALED_DECAY.min(1.0);
}
let t = self.age_steps as f32 / ANNEAL_STEPS as f32;
start + (ANNEALED_DECAY - start) * t
}
fn advance(&mut self, delta: f32) {
match self.phase {
Phase::Growing => {}
Phase::Holding => {
self.phase_timer -= delta;
if self.phase_timer <= 0.0 {
self.phase = Phase::Fading;
self.phase_timer = FADE_SECONDS;
}
return;
}
Phase::Fading => {
self.phase_timer -= delta;
self.fade = (self.phase_timer / FADE_SECONDS).clamp(0.0, 1.0);
if self.phase_timer <= 0.0 {
self.reseed();
}
return;
}
}
let substeps = self.options.substeps.max(1) as f32;
self.accumulator += delta * 60.0 * substeps;
let cap =
(MAX_CATCH_UP_STEPS * self.options.substeps.max(1) as usize).max(1);
let mut steps = 0usize;
while self.accumulator >= 1.0 && steps < cap {
self.accumulator -= 1.0;
self.step();
self.age_steps = self.age_steps.saturating_add(1);
if self.options.settle {
self.decay = self.annealed_decay();
if self.age_steps % u64::from(CHURN_EVERY) == 0 {
self.check_convergence();
if self.phase != Phase::Growing {
break;
}
}
}
steps += 1;
}
if steps == cap {
self.accumulator = 0.0;
}
}
fn check_convergence(&mut self) -> Option<f32> {
let (width, height) = self.size();
let mut marked = 0usize;
let mut changed = 0usize;
for (index, value) in self.trail.iter().enumerate() {
let now = *value > TRAIL_FLOOR;
if now {
marked += 1;
}
if self.marked_valid && self.marked[index] != now {
changed += 1;
}
self.marked[index] = now;
}
self.marked_valid = true;
if changed == 0 && marked == 0 {
return None;
}
let churn = changed as f32 / marked.max(1) as f32;
let coverage = marked as f32 / (width * height).max(1) as f32;
self.last_churn = Some(churn);
if self.age_steps < ANNEAL_STEPS {
return Some(churn);
}
if churn <= CHURN_SETTLED && coverage >= MIN_SETTLED_COVERAGE {
self.phase = Phase::Holding;
self.phase_timer = self.options.hold_seconds.max(0.0);
}
Some(churn)
}
fn reseed(&mut self) {
self.trail.iter_mut().for_each(|value| *value = 0.0);
self.scratch.iter_mut().for_each(|value| *value = 0.0);
self.start_growing();
self.spawn();
self.seed_trail();
}
pub fn step(&mut self) {
let (width, height) = self.size();
let sensor = self.options.sensor_distance;
let spread = self.options.sensor_angle.to_radians();
let turn = self.options.turn_angle.to_radians();
for agent in &mut self.colony {
let right = agent.sense(
&self.trail,
width,
height,
sensor * (agent.heading + spread).cos(),
sensor * (agent.heading + spread).sin(),
);
let ahead = agent.sense(
&self.trail,
width,
height,
sensor * agent.heading.cos(),
sensor * agent.heading.sin(),
);
let left = agent.sense(
&self.trail,
width,
height,
sensor * (agent.heading - spread).cos(),
sensor * (agent.heading - spread).sin(),
);
if right > ahead && right > left {
agent.heading += turn;
} else if left > ahead && left > right {
agent.heading -= turn;
}
agent.advance(self.options.move_step, width, height);
let x = wrap(agent.x, width) as usize;
let y = wrap(agent.y, height) as usize;
let cell = &mut self.trail[y * width + x];
*cell = (*cell + DEPOSIT).min(TRAIL_CEILING);
}
self.diffuse(width, height);
}
fn diffuse(&mut self, width: usize, height: usize) {
let spread = self.options.spread.clamp(0.0, 1.0);
let decay = self.decay.clamp(0.0, 1.0);
let centre = 1.0 - spread;
let each = spread / 4.0;
for y in 0..height {
let up = (y + height - 1) % height;
let down = (y + 1) % height;
for x in 0..width {
let left = (x + width - 1) % width;
let right = (x + 1) % width;
let total = self.trail[y * width + x] * centre
+ (self.trail[y * width + left]
+ self.trail[y * width + right]
+ self.trail[up * width + x]
+ self.trail[down * width + x])
* each;
self.scratch[y * width + x] = (total * decay).min(TRAIL_CEILING);
}
}
std::mem::swap(&mut self.trail, &mut self.scratch);
}
fn draw(&mut self) {
let (width, height) = self.size();
let mut frame_peak = f32::MIN;
for value in &self.trail {
frame_peak = frame_peak.max(*value);
}
if frame_peak > f32::MIN {
self.peak += (frame_peak - self.peak) * 0.08;
}
let peak = self.peak.max(f32::MIN_POSITIVE);
for y in 0..height {
for x in 0..width {
let t =
(self.trail[y * width + x] * self.fade / peak).clamp(0.0, 1.0);
let levels = self.palette.len().max(2);
let index =
((t * (levels - 1) as f32).round() as usize).min(levels - 1);
let rgb = match self.palette.sample_index(index) {
style::Color::Rgb { r, g, b } => {
[r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0]
}
_ => [0.0, 0.0, 0.0],
};
self.field.set_row(x, y, rgb);
}
}
self.field
.write_to(&mut self.canvas, crossterm::style::Attribute::Reset);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::render::palette::luminance;
use std::collections::VecDeque;
fn options(seed: u64) -> PhysarumOptions {
PhysarumOptions {
seed,
..PhysarumOptions::default()
}
}
fn fixture(seed: u64) -> Physarum {
Physarum::new(options(seed), (60, 20))
}
fn run(physarum: &mut Physarum, steps: usize) {
for _ in 0..steps {
physarum.step();
}
}
struct Shape {
marked: usize,
components: usize,
largest: usize,
edge_ratio: f32,
}
fn shape(trail: &[f32], width: usize, height: usize, floor: f32) -> Shape {
let above = |i: usize| trail[i] > floor;
let mut seen = vec![false; width * height];
let (mut marked, mut components, mut largest, mut best_ratio) =
(0usize, 0usize, 0usize, 0.0f32);
for start in 0..width * height {
if seen[start] || !above(start) {
continue;
}
components += 1;
let mut cells = Vec::new();
let mut queue = VecDeque::from([start]);
seen[start] = true;
while let Some(i) = queue.pop_front() {
marked += 1;
cells.push(i);
let (x, y) = (i % width, i / width);
for (nx, ny) in [
((x + width - 1) % width, y),
((x + 1) % width, y),
(x, (y + height - 1) % height),
(x, (y + 1) % height),
] {
let n = ny * width + nx;
if !seen[n] && above(n) {
seen[n] = true;
queue.push_back(n);
}
}
}
if cells.len() > largest {
largest = cells.len();
let mut boundary = 0usize;
for i in &cells {
let (x, y) = (i % width, i / width);
for (nx, ny) in [
((x + width - 1) % width, y),
((x + 1) % width, y),
(x, (y + height - 1) % height),
(x, (y + 1) % height),
] {
if !above(ny * width + nx) {
boundary += 1;
}
}
}
best_ratio = boundary as f32 / cells.len() as f32;
}
}
Shape {
marked,
components,
largest,
edge_ratio: best_ratio,
}
}
fn grown(seed: u64, steps: usize) -> (Shape, usize) {
let mut physarum = fixture(seed);
run(&mut physarum, steps);
let (width, height) = physarum.size();
(shape(&physarum.trail, width, height, 3.0), width * height)
}
fn colour_at(physarum: &Physarum, t: f32) -> style::Color {
let levels = physarum.palette.len().max(2);
let index = ((t * (levels - 1) as f32).round() as usize).min(levels - 1);
physarum.palette.sample_index(index)
}
#[test]
fn the_peak_of_the_field_is_drawn_in_the_brightest_colour() {
let physarum = fixture(3);
let top = colour_at(&physarum, 1.0);
let levels = physarum.palette.len();
for index in 0..levels {
let other = physarum.palette.sample_index(index);
assert!(
luminance(top) >= luminance(other) - 1e-4,
"t = 1.0 drew at {top:?} but stop {index} is {other:?}, which is \
brighter"
);
}
assert!(
luminance(top) > 0.5,
"the top of the scale is {top:?}, luma {:.3}, which is not a bright \
colour",
luminance(top)
);
}
#[test]
fn a_grown_field_has_a_cell_at_the_very_top_of_the_scale() {
let mut physarum = fixture(3);
run(&mut physarum, 4_000);
let (width, height) = physarum.size();
let peak = physarum
.trail
.iter()
.copied()
.fold(0.0f32, f32::max)
.max(f32::MIN_POSITIVE);
let at_peak = physarum
.trail
.iter()
.filter(|value| **value >= peak * 0.99)
.count();
assert!(
at_peak > 0,
"no cell reaches the peak of {peak} on a {width}x{height} field, so \
the scale is never exercised at its top"
);
}
fn run_frames(physarum: &mut Physarum, seconds: f32) {
let frame = 1.0 / 60.0;
let mut left = (seconds * 60.0).round() as usize;
while left > 0 {
physarum.update();
left -= 1;
}
let _ = frame;
}
#[test]
fn the_network_settles_holds_and_then_grows_again() {
let mut physarum = Physarum::new(options(3), (60, 20));
let mut held_at = None;
for frame in 0..7_200 {
physarum.update();
if physarum.phase == Phase::Holding && held_at.is_none() {
held_at = Some(frame);
}
}
let held_at = held_at.expect(
"the field never reached Holding in 120 seconds, so the anneal did not \
bring the churn down far enough for the detector to fire",
);
assert!(
held_at > 2_400,
"it settled after only {held_at} frames, which is inside the anneal \
itself"
);
run_frames(&mut physarum, 12.0);
assert_eq!(
physarum.phase,
Phase::Growing,
"after the hold and the fade the effect should be growing again"
);
assert!(
physarum.age_steps < ANNEAL_STEPS,
"the new cycle started at age {} steps, so the anneal will not run \
again",
physarum.age_steps
);
}
#[test]
fn a_held_field_is_drawn_once_and_then_not_at_all() {
let mut physarum = Physarum::new(options(3), (60, 20));
physarum.phase = Phase::Holding;
physarum.phase_timer = 10.0;
physarum.fade = 1.0;
let first = physarum.get_diff();
assert!(
!first.is_empty(),
"the first frame of a hold painted nothing, so there is no picture to \
hold"
);
for _ in 0..30 {
assert!(
physarum.get_diff().is_empty(),
"a held field still emitted cells, so it is not actually frozen"
);
}
}
#[test]
fn an_empty_field_is_never_called_settled() {
let mut physarum = Physarum::new(options(3), (60, 20));
physarum.trail.iter_mut().for_each(|value| *value = 0.0);
physarum.marked_valid = true;
physarum.marked.iter_mut().for_each(|mark| *mark = false);
physarum.phase = Phase::Growing;
for _ in 0..600 {
physarum.update();
}
assert_eq!(
physarum.phase,
Phase::Growing,
"a field with no trail in it was called settled"
);
}
#[test]
fn a_field_that_has_not_finished_growing_is_not_settled() {
let mut physarum = Physarum::new(options(3), (60, 20));
for _ in 0..(CHURN_EVERY as usize * 4) {
physarum.update();
assert_eq!(
physarum.phase,
Phase::Growing,
"the effect held a network it had barely started growing"
);
}
}
#[test]
fn the_shipped_decay_alone_never_settles() {
let mut physarum = Physarum::new(
PhysarumOptions {
settle: false,
..options(3)
},
(60, 20),
);
for _ in 0..7_200 {
physarum.update();
}
assert_eq!(
physarum.phase,
Phase::Growing,
"settle = false still reached a hold, so the flag is not wired up"
);
}
#[test]
fn the_anneal_lowers_the_churn_it_exists_to_lower() {
let churn_of = |settle: bool| -> f32 {
let mut physarum = Physarum::new(
PhysarumOptions {
settle,
..options(3)
},
(60, 20),
);
let mut last = f32::INFINITY;
for _ in 0..9_000 {
physarum.update();
if let Some(churn) = physarum.last_churn {
last = churn;
}
if physarum.phase != Phase::Growing {
break;
}
}
last
};
let annealed = churn_of(true);
let shipped = churn_of(false);
assert!(
annealed < CHURN_SETTLED,
"with the anneal the churn is {annealed:.3}, which is above the \
{CHURN_SETTLED} the detector uses, so the anneal is not reaching a \
fixed point"
);
assert!(
annealed < shipped / 2.0,
"the anneal gave churn {annealed:.3} against {shipped:.3} un-annealed, \
which is not a meaningful reduction"
);
}
#[test]
fn the_decay_in_use_is_the_annealed_one_and_resets_each_cycle() {
let mut physarum = Physarum::new(options(3), (60, 20));
assert_eq!(
physarum.decay, DECAY,
"a fresh effect should start at the configured decay"
);
let mut peak_decay = physarum.decay;
let mut previous_age = 0u64;
let mut rising = true;
for _ in 0..12_000 {
physarum.update();
if physarum.phase != Phase::Growing {
continue;
}
if physarum.decay < peak_decay && physarum.age_steps > previous_age {
rising = false;
break;
}
if physarum.age_steps > previous_age {
rising = true;
previous_age = physarum.age_steps;
peak_decay = peak_decay.max(physarum.decay);
}
}
assert!(rising, "the decay fell without the cycle restarting");
assert!(
peak_decay >= 0.99,
"the decay only ever reached {peak_decay}, so the anneal does not get \
near the {ANNEALED_DECAY} the settled state needs"
);
assert!(
peak_decay <= ANNEALED_DECAY,
"the decay reached {peak_decay}, past the {ANNEALED_DECAY} ceiling"
);
physarum.phase = Phase::Fading;
physarum.phase_timer = 0.01;
run_frames(&mut physarum, 0.1);
let rise = ANNEALED_DECAY - DECAY;
assert!(
physarum.decay < DECAY + rise * 0.01,
"a new cycle is annealing from {} rather than from the configured \
{DECAY}, so it would never grow a network again",
physarum.decay
);
assert!(
physarum.age_steps < 10,
"a new cycle is already {} steps old",
physarum.age_steps
);
}
#[test]
fn the_agents_build_veins_rather_than_a_slab() {
let (s, cells) = grown(3, 4_000);
assert!(
s.marked > 100,
"only {} cells carry trail above the floor, out of {cells}: there is \
no field here to be a network",
s.marked
);
assert!(
s.edge_ratio > 0.30,
"the largest piece has an edge-to-area ratio of {:.2}, so it is a \
filled region rather than a vein",
s.edge_ratio
);
let coverage = s.marked as f32 / cells as f32;
assert!(
coverage < 0.25,
"{:.1}% of the field carries trail, so the veins have merged into a \
slab",
coverage * 100.0
);
}
#[test]
fn a_sensor_distance_too_short_to_see_anything_cannot_build_a_network() {
let measure = |distance: f32| {
let mut physarum = Physarum::new(
PhysarumOptions {
sensor_distance: distance,
..options(5)
},
(200, 60),
);
run(&mut physarum, 4_000);
let (width, height) = physarum.size();
shape(&physarum.trail, width, height, 3.0)
};
let good = measure(9.0);
let bad = measure(1.5);
assert!(
good.components * 3 < bad.components,
"9 cells of sensor distance left {} pieces; 1.5 left {}, which is not \
enough of a difference to be the network",
good.components,
bad.components
);
assert!(
good.largest * 3 > bad.largest,
"the biggest connected piece was {} cells at 9 and {} at 1.5",
good.largest,
bad.largest
);
}
#[test]
fn the_network_survives_a_long_run() {
let (s, cells) = grown(4, 20_000);
assert!(
s.marked > 100,
"after twenty thousand steps only {} cells carry trail: the network \
has decayed away",
s.marked
);
assert!(
s.edge_ratio > 0.30,
"after twenty thousand steps the largest piece is a filled region \
(edge ratio {:.2})",
s.edge_ratio
);
assert!(
s.marked * 4 < cells,
"after twenty thousand steps {:.1}% of the field carries trail, so \
the trail has saturated",
s.marked as f32 / cells as f32 * 100.0
);
}
#[test]
fn the_diffusion_does_not_smear_along_the_sweep_order() {
let (width, height) = (5usize, 5usize);
let mut physarum = Physarum::new(options(6), (6, 4));
physarum.trail = vec![0.0; width * height];
physarum.scratch = vec![0.0; width * height];
physarum.trail[2 * width + 2] = 1.0;
physarum.diffuse(width, height);
assert!(
physarum.trail[2 * width + 1] == physarum.trail[2 * width + 3],
"the two cells beside the source came out at {} and {}, which only an \
in-place stencil would do",
physarum.trail[2 * width + 1],
physarum.trail[2 * width + 3]
);
assert!(
physarum.trail[2 * width + 2] > physarum.trail[2 * width + 1],
"the source cell came out weaker than the cell beside it, so the \
kernel is not weighted towards the centre"
);
}
#[test]
fn the_trail_actually_fades() {
let mut physarum = fixture(7);
physarum.colony.clear();
physarum.trail.fill(0.0);
let (width, _) = physarum.size();
physarum.trail[5 * width + 5] = 10.0;
physarum.step();
let after = physarum.trail[5 * width + 5];
assert!(
after < 10.0 && after > 0.0,
"a lone cell came out as {after}; it should have spread and faded"
);
}
#[test]
fn the_trail_is_capped_so_a_few_pile_ups_cannot_own_the_palette() {
let mut physarum = fixture(8);
let (width, _) = physarum.size();
let index = 7 * width + 7;
for _ in 0..500 {
physarum.colony.clear();
physarum.colony.push(Agent {
x: 7.0,
y: 7.0,
heading: 0.0,
});
physarum.step();
}
assert!(
physarum.trail[index] <= TRAIL_CEILING,
"a cell visited five hundred times came out at {}",
physarum.trail[index]
);
assert!(
physarum.trail[index] > 0.0,
"the capped cell is empty, so the cap is clamping the wrong side"
);
}
#[test]
fn an_agent_at_the_very_edge_of_the_field_does_not_index_past_it() {
let mut physarum = fixture(9);
let (width, height) = physarum.size();
for y in [0.0f32, height as f32 - 0.5, -0.0000001, -1.0] {
for x in [0.0f32, width as f32 - 0.5, -0.0000001, -1.0] {
assert!(sample(&physarum.trail, width, height, x, y).is_finite());
}
}
physarum.colony = vec![Agent {
x: 0.0,
y: 0.0,
heading: -std::f32::consts::FRAC_PI_4,
}];
for _ in 0..50 {
physarum.step();
}
}
#[test]
fn different_seeds_grow_different_networks() {
let mut a = fixture(11);
let mut b = fixture(12);
run(&mut a, 400);
run(&mut b, 400);
assert_ne!(a.trail, b.trail, "the seed changed nothing");
}
#[test]
fn the_same_seed_grows_the_same_network() {
let mut a = fixture(13);
let mut b = fixture(13);
run(&mut a, 400);
run(&mut b, 400);
assert_eq!(a.trail, b.trail, "the same seed produced two pictures");
}
#[test]
fn the_display_peak_follows_the_field_rather_than_a_constant() {
let mut physarum = fixture(15);
run(&mut physarum, 300);
physarum.draw();
let first = physarum.peak;
run(&mut physarum, 300);
physarum.draw();
assert!(first > 0.0, "the display peak never left zero");
assert!(
(physarum.peak - first).abs() < first,
"the display peak moved from {first} to {}, which is not tracking it",
physarum.peak
);
}
#[test]
fn every_emitted_cell_is_inside_the_canvas() {
let mut physarum = fixture(16);
for _ in 0..60 {
physarum.advance(1.0 / 60.0);
for (x, y, _) in physarum.get_diff() {
assert!(x < 60 && y < 20, "({x}, {y}) is outside a 60x20 canvas");
}
}
}
}