use crate::graphics::BlendMode;
use crate::writer::backdrops::{additive_color, mirror, over_color};
const COLOURS: [[f32; 4]; 8] = [
[0.0, 0.0, 0.0, 0.0],
[1.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
[0.4, 0.2, 0.0, 1.0],
[0.25, 0.0, 0.25, 0.5],
[0.1, 0.3, 0.05, 0.3],
[0.6, 0.1, 0.9, 0.95],
[0.02, 0.0, 0.01, 0.02],
];
const EPSILON: f32 = 1.0e-5;
fn plus_lighter(source: [f32; 4], backdrop: [f32; 4]) -> [f32; 4] {
std::array::from_fn(|channel| (source[channel] + backdrop[channel]).min(1.0))
}
fn plus_darker(source: [f32; 4], backdrop: [f32; 4]) -> [f32; 4] {
let alpha = (source[3] + backdrop[3]).min(1.0);
std::array::from_fn(|channel| {
if channel == 3 {
alpha
} else {
(alpha - (source[3] - source[channel]) - (backdrop[3] - backdrop[channel])).max(0.0)
}
})
}
fn source_over(source: [f32; 4], backdrop: [f32; 4]) -> [f32; 4] {
std::array::from_fn(|channel| source[channel] + backdrop[channel] * (1.0 - source[3]))
}
#[test]
fn drawing_the_over_colour_onto_the_backdrop_gives_the_additive_result() {
for (operator, reference) in [
(BlendMode::PlusLighter, plus_lighter as fn(_, _) -> _),
(BlendMode::PlusDarker, plus_darker),
] {
for source in COLOURS {
for backdrop in COLOURS {
let over = over_color(operator, source, backdrop);
assert!(
(0.0..=1.0).contains(&over[3])
&& over[..3].iter().all(|c| (0.0..=over[3]).contains(c)),
"{operator:?}: {over:?} drawn for source {source:?} on {backdrop:?} must be \
a premultiplied colour"
);
let drawn = source_over(over, backdrop);
let expected = reference(source, backdrop);
assert!(
drawn
.iter()
.zip(expected)
.all(|(a, e)| (a - e).abs() < EPSILON),
"{operator:?}: source {source:?} on {backdrop:?}: drawing {over:?} gives \
{drawn:?}, expected {expected:?}"
);
}
}
}
}
#[test]
fn plus_darker_subtracts_the_complements_of_opaque_layers() {
let result = additive_color(
BlendMode::PlusDarker,
[0.6, 0.8, 1.0, 1.0],
[0.7, 0.1, 1.0, 1.0],
);
let expected = [0.3, 0.0, 1.0, 1.0];
assert!(
result
.iter()
.zip(expected)
.all(|(a, e)| (a - e).abs() < EPSILON),
"opaque layers give 1 − ((1 − cs) + (1 − cb)), clamped at zero: {result:?}, expected \
{expected:?}"
);
}
#[test]
fn mirroring_reflects_pixel_centres_across_each_edge_and_repeats() {
let cases = [
(4.5, 4.5),
(-0.5, 0.5),
(10.5, 9.5),
(-10.5, 9.5),
(21.5, 1.5),
(-25.0, 5.0),
];
for (value, expected) in cases {
let mirrored = mirror(value, 0.0, 10.0);
assert!(
(mirrored - expected).abs() < EPSILON,
"{value} mirrored into 0..10 is {mirrored}, expected {expected}"
);
}
assert!(
(mirror(48.0, 50.0, 200.0) - 52.0).abs() < EPSILON,
"an offset box mirrors about its own edge"
);
}