#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Dither {
#[default]
None,
Bayer4,
Bayer8,
}
const BAYER4: [[f32; 4]; 4] = [
[0.0 / 16.0, 8.0 / 16.0, 2.0 / 16.0, 10.0 / 16.0],
[12.0 / 16.0, 4.0 / 16.0, 14.0 / 16.0, 6.0 / 16.0],
[3.0 / 16.0, 11.0 / 16.0, 1.0 / 16.0, 9.0 / 16.0],
[15.0 / 16.0, 7.0 / 16.0, 13.0 / 16.0, 5.0 / 16.0],
];
const BAYER8: [[f32; 4]; 4] = [
[0.0 / 64.0, 32.0 / 64.0, 8.0 / 64.0, 40.0 / 64.0],
[48.0 / 64.0, 16.0 / 64.0, 56.0 / 64.0, 24.0 / 64.0],
[12.0 / 64.0, 44.0 / 64.0, 4.0 / 64.0, 36.0 / 64.0],
[60.0 / 64.0, 28.0 / 64.0, 52.0 / 64.0, 20.0 / 64.0],
];
impl Dither {
pub fn at(&self, x: usize, y: usize) -> f32 {
match self {
Dither::None => 0.5,
Dither::Bayer4 => BAYER4[x % 4][y % 4],
Dither::Bayer8 => BAYER8[x % 4][y % 4],
}
}
pub fn levels(&self) -> usize {
match self {
Dither::None => 1,
Dither::Bayer4 => 16,
Dither::Bayer8 => 64,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_dither_is_a_constant_offset() {
for x in 0..9 {
for y in 0..9 {
assert_eq!(Dither::None.at(x, y), 0.5);
}
}
}
#[test]
fn the_offset_is_stable_for_a_coordinate() {
for dither in [Dither::Bayer4, Dither::Bayer8] {
let first = dither.at(3, 5);
for _ in 0..100 {
assert_eq!(dither.at(3, 5), first);
}
}
}
#[test]
fn offsets_stay_in_range() {
for dither in [Dither::None, Dither::Bayer4, Dither::Bayer8] {
for x in 0..16 {
for y in 0..16 {
let v = dither.at(x, y);
assert!(
(0.0..1.0).contains(&v),
"{dither:?} produced {v} at ({x},{y})"
);
}
}
}
}
#[test]
fn bayer4_produces_sixteen_distinct_levels() {
let mut seen = std::collections::HashSet::new();
for x in 0..4 {
for y in 0..4 {
seen.insert(Dither::Bayer4.at(x, y).to_bits());
}
}
assert_eq!(seen.len(), 16, "the 4x4 matrix is not a permutation");
}
#[test]
fn the_matrix_tiles_seamlessly() {
let base: std::collections::HashSet<u32> = (0..4)
.flat_map(|x| (0..4).map(move |y| (x, y)))
.map(|(x, y)| Dither::Bayer4.at(x, y).to_bits())
.collect();
for ox in 0..5 {
for oy in 0..5 {
let window: std::collections::HashSet<u32> = (0..4)
.flat_map(|x| (0..4).map(move |y| (x, y)))
.map(|(x, y)| Dither::Bayer4.at(x + ox, y + oy).to_bits())
.collect();
assert_eq!(window, base, "the tiling breaks at offset ({ox},{oy})");
}
}
}
#[test]
fn level_counts_match_the_matrices() {
assert_eq!(Dither::None.levels(), 1);
assert_eq!(Dither::Bayer4.levels(), 16);
assert_eq!(Dither::Bayer8.levels(), 64);
}
}