mod colors;
use colors::COLORS;
const STEP: u8 = 51;
const AMOUNTS: usize = 6;
const LAST_STEP: u8 = 4;
const WHOLE: u32 = 51 * 51 * 51 * 51;
pub(super) fn rgb(inks: [u8; 4]) -> [u8; 3] {
let steps = inks.map(|ink| (ink / STEP).min(LAST_STEP));
let mut sums = [0_u32; 3];
for corner in 0..16_u8 {
let mut index = 0;
let mut weight = 1_u32;
for (axis, (&ink, &step)) in inks.iter().zip(&steps).enumerate() {
let above = ink - step * STEP;
let end = corner >> (3 - axis) & 1 == 1;
index = index * AMOUNTS + usize::from(step) + usize::from(end);
weight *= u32::from(if end { above } else { STEP - above });
}
if weight == 0 {
continue;
}
let color = COLORS.get(index).copied().unwrap_or([0; 3]);
for (sum, value) in sums.iter_mut().zip(color) {
*sum += weight * u32::from(value);
}
}
sums.map(|sum| u8::try_from((sum + WHOLE / 2) / WHOLE).unwrap_or(u8::MAX))
}
#[cfg(test)]
mod tests {
use super::*;
fn table(places: [usize; 4]) -> [u8; 3] {
let index = places
.iter()
.fold(0, |index, &place| index * AMOUNTS + place);
COLORS[index]
}
#[test]
fn the_amounts_of_the_table_give_its_colors() {
for index in 0..COLORS.len() {
let places = [index / 216, index / 36 % 6, index / 6 % 6, index % 6];
let inks = places.map(|place| u8::try_from(place * 51).unwrap());
assert_eq!(rgb(inks), table(places), "{inks:?}");
}
}
#[test]
fn an_ink_between_two_amounts_takes_both_by_its_distance() {
for (black, low, high) in [(61, 1, 2), (254, 4, 5)] {
let above = u32::from(black) - 51 * u32::try_from(low).unwrap();
let [from, to] = [table([0, 0, 0, low]), table([0, 0, 0, high])];
let got = rgb([0, 0, 0, black]);
for channel in 0..3 {
let sum = u32::from(from[channel]) * (51 - above) + u32::from(to[channel]) * above;
assert_eq!(u32::from(got[channel]), (sum + 25) / 51, "{black}");
}
}
let corners = [[1, 0, 0, 3], [1, 0, 0, 4], [2, 0, 0, 3], [2, 0, 0, 4]].map(table);
let weights = [26 * 26, 26 * 25, 25 * 26, 25 * 25];
let got = rgb([76, 0, 0, 178]);
for channel in 0..3 {
let sum: u32 = corners
.iter()
.zip(weights)
.map(|(color, weight)| u32::from(color[channel]) * weight)
.sum();
assert_eq!(u32::from(got[channel]), (sum + 1300) / 2601);
}
}
#[test]
fn full_ink_is_the_last_amount() {
assert_eq!(rgb([255; 4]), table([5; 4]));
assert_eq!(rgb([255, 0, 0, 0]), table([5, 0, 0, 0]));
assert_eq!(rgb([0, 255, 102, 0]), table([0, 5, 2, 0]));
}
}