use crate::input::LumaImage;
use crate::report::Point;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Homography(pub [f32; 9]);
impl Homography {
#[cfg(test)]
pub(crate) fn identity() -> Self {
Self([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0])
}
pub(crate) fn apply(&self, x: f32, y: f32) -> Option<(f32, f32)> {
let m = &self.0;
let w = m[6] * x + m[7] * y + m[8];
if w.abs() < f32::EPSILON {
return None;
}
Some((
(m[0] * x + m[1] * y + m[2]) / w,
(m[3] * x + m[4] * y + m[5]) / w,
))
}
pub(crate) fn inverse(&self) -> Option<Self> {
let m = &self.0;
let det = m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6])
+ m[2] * (m[3] * m[7] - m[4] * m[6]);
if det.abs() < 1e-12 {
return None;
}
let inv_det = 1.0 / det;
Some(Self([
(m[4] * m[8] - m[5] * m[7]) * inv_det,
(m[2] * m[7] - m[1] * m[8]) * inv_det,
(m[1] * m[5] - m[2] * m[4]) * inv_det,
(m[5] * m[6] - m[3] * m[8]) * inv_det,
(m[0] * m[8] - m[2] * m[6]) * inv_det,
(m[2] * m[3] - m[0] * m[5]) * inv_det,
(m[3] * m[7] - m[4] * m[6]) * inv_det,
(m[1] * m[6] - m[0] * m[7]) * inv_det,
(m[0] * m[4] - m[1] * m[3]) * inv_det,
]))
}
pub(crate) fn unit_square_to_quad(quad: [(f32, f32); 4]) -> Option<Self> {
let [(x0, y0), (x1, y1), (x2, y2), (x3, y3)] = quad;
let dx1 = x1 - x2;
let dx2 = x3 - x2;
let dy1 = y1 - y2;
let dy2 = y3 - y2;
let sx = x0 - x1 + x2 - x3;
let sy = y0 - y1 + y2 - y3;
let den = dx1 * dy2 - dx2 * dy1;
if den.abs() < 1e-12 {
return None;
}
let g = (sx * dy2 - dx2 * sy) / den;
let h = (dx1 * sy - sx * dy1) / den;
Some(Self([
x1 - x0 + g * x1,
x3 - x0 + h * x3,
x0,
y1 - y0 + g * y1,
y3 - y0 + h * y3,
y0,
g,
h,
1.0,
]))
}
}
#[expect(
clippy::cast_possible_truncation,
reason = "floor() output bounded by the f32 pixel-coordinate domain"
)]
pub(crate) fn sample_bilinear(img: &LumaImage, x: f32, y: f32) -> u8 {
let x0 = x.floor();
let y0 = y.floor();
let fx = x - x0;
let fy = y - y0;
let (ix, iy) = (x0 as i64, y0 as i64);
let [top_left, top_right, bottom_left, bottom_right] =
interior(img, ix, iy).unwrap_or_else(|| bordered(img, ix, iy));
let top = f32::from(top_left) * (1.0 - fx) + f32::from(top_right) * fx;
let bottom = f32::from(bottom_left) * (1.0 - fx) + f32::from(bottom_right) * fx;
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "clamped to 0.0..=255.0"
)]
{
(top * (1.0 - fy) + bottom * fy).clamp(0.0, 255.0) as u8
}
}
fn interior(img: &LumaImage, ix: i64, iy: i64) -> Option<[u8; 4]> {
let (width, height) = (img.width() as usize, img.height() as usize);
let (ix, iy) = (usize::try_from(ix).ok()?, usize::try_from(iy).ok()?);
if ix + 1 >= width || iy + 1 >= height {
return None;
}
let data = img.data();
let top = iy * width + ix;
let bottom = top + width;
let (top, bottom) = (&data[top..top + 2], &data[bottom..bottom + 2]);
Some([top[0], top[1], bottom[0], bottom[1]])
}
#[cold]
fn bordered(img: &LumaImage, ix: i64, iy: i64) -> [u8; 4] {
let (w, h) = (i64::from(img.width()), i64::from(img.height()));
let fetch = |px: i64, py: i64| -> u8 {
if px < 0 || py < 0 || px >= w || py >= h {
255
} else {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "bounds-checked above against u32-sized dimensions"
)]
let idx = (py as usize) * (img.width() as usize) + (px as usize);
img.data()[idx]
}
};
[
fetch(ix, iy),
fetch(ix + 1, iy),
fetch(ix, iy + 1),
fetch(ix + 1, iy + 1),
]
}
pub(crate) struct GridSampler<'a> {
img: &'a LumaImage,
unit_to_image: Homography,
modules: u32,
}
impl<'a> GridSampler<'a> {
pub(crate) fn new(img: &'a LumaImage, corners: [Point; 4], modules: u32) -> Option<Self> {
let quad = corners.map(|p| (p.x, p.y));
Some(Self {
img,
unit_to_image: Homography::unit_square_to_quad(quad)?,
modules,
})
}
#[expect(
clippy::cast_precision_loss,
reason = "module indices ≤ 177, exact in f32"
)]
pub(crate) fn module(&self, mx: i32, my: i32) -> Option<u8> {
let denom = self.modules as f32 + 1.0;
let (ux, uy) = ((mx as f32 + 0.5) / denom, (my as f32 + 0.5) / denom);
let (x, y) = self.unit_to_image.apply(ux, uy)?;
Some(sample_bilinear(self.img, x, y))
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::cast_precision_loss,
clippy::float_cmp
)]
use super::*;
fn checker(side: u32) -> LumaImage {
let data = (0..side * side)
.map(|i| {
let (x, y) = (i % side, i / side);
if (x + y) % 2 == 0 { 0 } else { 255 }
})
.collect();
LumaImage::new(data, side, side)
}
#[test]
fn homography_inverse_roundtrips() {
let h = Homography::unit_square_to_quad([(2.0, 1.0), (10.0, 0.5), (11.0, 9.0), (1.5, 8.0)])
.unwrap();
let inv = h.inverse().unwrap();
for (x, y) in [(0.0, 0.0), (0.5, 0.5), (1.0, 0.0), (0.25, 0.75)] {
let (fx, fy) = h.apply(x, y).unwrap();
let (bx, by) = inv.apply(fx, fy).unwrap();
assert!((bx - x).abs() < 1e-4 && (by - y).abs() < 1e-4, "({x},{y})");
}
}
#[test]
fn unit_square_maps_corners_onto_quad() {
let quad = [(3.0, 2.0), (20.0, 3.0), (19.0, 22.0), (2.0, 20.0)];
let h = Homography::unit_square_to_quad(quad).unwrap();
let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)];
for (unit, expected) in corners.iter().zip(quad) {
let (x, y) = h.apply(unit.0, unit.1).unwrap();
assert!(
(x - expected.0).abs() < 1e-3 && (y - expected.1).abs() < 1e-3,
"unit {unit:?} → ({x},{y}) expected {expected:?}"
);
}
}
#[test]
fn bilinear_weights_average_the_checker() {
let img = checker(2);
assert_eq!(sample_bilinear(&img, 0.0, 0.0), 0);
assert_eq!(sample_bilinear(&img, 1.0, 0.0), 255);
assert_eq!(sample_bilinear(&img, 0.5, 0.5), 127);
assert_eq!(sample_bilinear(&img, 0.25, 0.0), 63);
}
#[test]
fn inverse_matches_hand_computed_adjugate() {
let h = Homography([2.0, 3.0, 5.0, 7.0, 11.0, 13.0, 17.0, 19.0, 29.0]);
let expected: [f32; 9] = [
-1.0, -1.0 / 9.0, 2.0 / 9.0, -0.25, 0.375, -0.125, 0.75, -13.0 / 72.0, -1.0 / 72.0, ];
let inv = h.inverse().expect("nonsingular");
for (k, (&got, want)) in inv.0.iter().zip(expected).enumerate() {
assert!(
(got - want).abs() < 1e-4,
"inv[{k}] = {got}, want {want} (a wrong det rescales EVERY element)"
);
}
}
#[test]
fn inverse_of_singular_is_none() {
let singular = Homography([1.0, 2.0, 3.0, 2.0, 4.0, 6.0, 1.0, 1.0, 1.0]);
assert!(singular.inverse().is_none());
}
#[test]
fn apply_projecting_to_infinity_returns_none() {
let h = Homography([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]);
assert!(h.apply(0.0, 5.0).is_none());
assert_eq!(h.apply(2.0, 5.0), Some((1.0, 2.5)));
}
#[test]
fn apply_at_exactly_epsilon_w_still_projects() {
let h = Homography([1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, f32::EPSILON]);
let got = h.apply(2.0, 4.0);
assert!(got.is_some(), "w == EPSILON is finite under strict `<`");
assert_eq!(got.unwrap(), (2.0 / f32::EPSILON, 4.0 / f32::EPSILON));
}
#[test]
fn inverse_at_exactly_the_determinant_threshold_still_inverts() {
let h = Homography([1e-12, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
assert!(
h.inverse().is_some(),
"det == 1e-12 is non-singular under the strict `<` guard"
);
}
#[test]
fn unit_square_to_quad_at_exactly_the_den_threshold_still_builds() {
let quad = [(1.0, 1.0), (1e-12, 0.0), (0.0, 0.0), (0.0, 1.0)];
assert!(
Homography::unit_square_to_quad(quad).is_some(),
"den == 1e-12 is non-singular under strict `<`"
);
let collinear = [(0.0, 0.0), (2.0, 0.0), (4.0, 0.0), (6.0, 0.0)];
assert!(Homography::unit_square_to_quad(collinear).is_none());
}
#[test]
fn bilinear_bottom_row_read_and_weight_are_load_bearing() {
let img = LumaImage::new(vec![10, 20, 30, 40], 2, 2);
assert_eq!(sample_bilinear(&img, 0.5, 0.5), 25);
assert_eq!(sample_bilinear(&img, 0.0, 0.75), 25);
}
#[test]
fn unit_square_to_quad_projects_interior_points_exactly() {
let quad = [(0.0, 0.0), (1.0, 0.0), (2.0, 2.0), (0.0, 1.0)];
let h = Homography::unit_square_to_quad(quad).expect("nonsingular quad");
let cases = [
((0.0, 0.0), (0.0, 0.0)), ((1.0, 0.0), (1.0, 0.0)),
((1.0, 1.0), (2.0, 2.0)),
((0.0, 1.0), (0.0, 1.0)),
((0.5, 0.5), (0.5, 0.5)), ((0.5, 0.0), (0.4, 0.0)), ((0.25, 0.25), (0.2, 0.2)),
];
for ((u, v), (ex, ey)) in cases {
let (x, y) = h.apply(u, v).expect("finite");
assert!(
(x - ex).abs() < 1e-5 && (y - ey).abs() < 1e-5,
"({u},{v}) → ({x},{y}), want ({ex},{ey})"
);
}
}
fn numbered() -> LumaImage {
LumaImage::new((10..30).collect(), 5, 4)
}
fn pixel_or_white(img: &LumaImage, x: i64, y: i64) -> u8 {
let row = usize::try_from(y)
.ok()
.and_then(|y| img.data().chunks(img.width() as usize).nth(y));
usize::try_from(x)
.ok()
.and_then(|x| row?.get(x).copied())
.unwrap_or(255)
}
#[test]
fn both_neighbour_readers_answer_the_definition_at_every_position() {
let img = numbered();
for iy in -2..=5 {
for ix in -2..=6 {
let want = [
pixel_or_white(&img, ix, iy),
pixel_or_white(&img, ix + 1, iy),
pixel_or_white(&img, ix, iy + 1),
pixel_or_white(&img, ix + 1, iy + 1),
];
assert_eq!(bordered(&img, ix, iy), want, "bordered ({ix},{iy})");
let inside = (0..4).contains(&ix) && (0..3).contains(&iy);
assert_eq!(
interior(&img, ix, iy),
inside.then_some(want),
"interior ({ix},{iy})"
);
}
}
}
#[test]
fn the_interior_reader_declines_a_position_no_image_holds() {
let img = numbered();
assert_eq!(interior(&img, i64::MAX, 1), None);
assert_eq!(interior(&img, 1, i64::MAX), None);
assert_eq!(interior(&img, i64::MIN, i64::MIN), None);
}
#[test]
fn a_sample_blends_the_same_way_inside_and_on_the_border() {
let img = numbered();
assert_eq!(sample_bilinear(&img, 1.25, 1.5), 18);
assert_eq!(sample_bilinear(&img, 4.5, 1.25), 137);
assert_eq!(sample_bilinear(&img, 1.5, 3.75), 197);
assert_eq!(sample_bilinear(&img, -0.5, -0.5), 193);
}
}