use crate::input::LumaImage;
use crate::matrix::sampler::{Homography, sample_bilinear};
pub(crate) fn warp_into(img: &LumaImage, h_fwd: &Homography, out_w: u32, out_h: u32) -> LumaImage {
let Some(h_inv) = h_fwd.inverse() else {
return img.clone();
};
#[expect(
clippy::cast_precision_loss,
reason = "pixel coordinates bounded by Limits::max_dimension — exact in f32"
)]
let (sw, sh) = (img.width() as f32 - 1.0, img.height() as f32 - 1.0);
let mut data = Vec::with_capacity((out_w * out_h) as usize);
#[expect(
clippy::cast_precision_loss,
reason = "pixel coordinates bounded by Limits::max_dimension — exact in f32"
)]
for y in 0..out_h {
for x in 0..out_w {
let sampled = match h_inv.apply(x as f32, y as f32) {
Some((sx, sy)) if sx >= -0.5 && sx <= sw + 0.5 && sy >= -0.5 && sy <= sh + 0.5 => {
sample_bilinear(img, sx, sy)
}
_ => 255,
};
data.push(sampled);
}
}
LumaImage::new(data, out_w, out_h)
}
pub(crate) fn warp(img: &LumaImage, h_fwd: &Homography) -> LumaImage {
warp_into(img, h_fwd, img.width(), img.height())
}
pub(crate) fn perspective_tilt(img: &LumaImage, angle_deg: f32) -> LumaImage {
#[expect(
clippy::cast_precision_loss,
reason = "dimensions bounded by Limits::max_dimension"
)]
let (w, h) = (img.width() as f32 - 1.0, img.height() as f32 - 1.0);
let inset = w * (sin_cos_degrees(angle_deg).0 * 0.5);
let quad = [(inset, 0.0), (w - inset, 0.0), (w, h), (0.0, h)];
let Some(unit_to_quad) = Homography::unit_square_to_quad(quad) else {
return img.clone();
};
let to_unit = Homography([1.0 / w, 0.0, 0.0, 0.0, 1.0 / h, 0.0, 0.0, 0.0, 1.0]);
let fwd = compose(&unit_to_quad, &to_unit);
warp(img, &fwd)
}
pub(crate) fn rotate(img: &LumaImage, angle_deg: f32) -> LumaImage {
#[expect(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "dimensions bounded by Limits::max_dimension; ceil of a non-negative bound"
)]
{
let (w, h) = (img.width() as f32, img.height() as f32);
let (sin, cos) = sin_cos_degrees(angle_deg);
let (sin64, cos64) = f64::from(angle_deg).to_radians().sin_cos();
let (w64, h64) = (f64::from(img.width()), f64::from(img.height()));
let out_w = (w64 * cos64.abs() + h64 * sin64.abs() - 1e-6).ceil() as u32;
let out_h = (w64 * sin64.abs() + h64 * cos64.abs() - 1e-6).ceil() as u32;
let (cx, cy) = ((w - 1.0) / 2.0, (h - 1.0) / 2.0);
let (dx, dy) = ((out_w as f32 - 1.0) / 2.0, (out_h as f32 - 1.0) / 2.0);
let fwd = Homography([
cos,
-sin,
dx - cos * cx + sin * cy,
sin,
cos,
dy - sin * cx - cos * cy,
0.0,
0.0,
1.0,
]);
warp_into(img, &fwd, out_w, out_h)
}
}
#[expect(
clippy::cast_possible_truncation,
reason = "the one rounding of the f64 evaluation to f32"
)]
fn sin_cos_degrees(angle_deg: f32) -> (f32, f32) {
let (sin, cos) = f64::from(angle_deg.to_radians()).sin_cos();
(sin as f32, cos as f32)
}
pub(crate) fn compose(a: &Homography, b: &Homography) -> Homography {
let (m, n) = (&a.0, &b.0);
let mut out = [0.0f32; 9];
for row in 0..3 {
for col in 0..3 {
out[row * 3 + col] =
m[row * 3] * n[col] + m[row * 3 + 1] * n[3 + col] + m[row * 3 + 2] * n[6 + col];
}
}
Homography(out)
}
pub(crate) fn shadow_gradient(img: &LumaImage, strength: f32) -> LumaImage {
let w = img.width();
#[expect(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "bounded pixel math, result clamped"
)]
let data = img
.data()
.iter()
.enumerate()
.map(|(i, &px)| {
let x = (i as u32 % w) as f32 / w.max(1) as f32;
let factor = 1.0 - strength * (1.0 - x);
(f32::from(px) * factor).clamp(0.0, 255.0) as u8
})
.collect();
LumaImage::new(data, w, img.height())
}
pub(crate) fn glare_blob(img: &LumaImage, cx: f32, cy: f32, radius: f32) -> LumaImage {
let w = img.width();
#[expect(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "bounded pixel math, result clamped"
)]
let data = img
.data()
.iter()
.enumerate()
.map(|(i, &px)| {
let x = (i as u32 % w) as f32;
let y = (i as u32 / w) as f32;
let d2 = (x - cx) * (x - cx) + (y - cy) * (y - cy);
let boost = 255.0 * (f64::from(-d2 / (radius * radius)).exp() as f32);
(f32::from(px) + boost).clamp(0.0, 255.0) as u8
})
.collect();
LumaImage::new(data, w, img.height())
}
pub(crate) fn exposure(img: &LumaImage, delta: i16) -> LumaImage {
let data = img
.data()
.iter()
.map(|&px| {
let shifted = i16::from(px).saturating_add(delta).clamp(0, 255);
#[expect(clippy::cast_sign_loss, reason = "clamped to 0..=255")]
{
shifted as u8
}
})
.collect();
LumaImage::new(data, img.width(), img.height())
}
#[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 identity_warp_is_exact() {
let img = checker(16);
let out = warp(&img, &Homography::identity());
assert_eq!(out.data(), img.data());
}
#[test]
fn zero_angle_rotation_preserves_rectangular_pixels_exactly() {
let img = LumaImage::new(
vec![
0, 255, 17, 90, 33, 201, 64, 7, 128, 240, 52, 180, 99, 221, 11, 155, 42, 80,
],
6,
3,
);
let out = rotate(&img, 0.0);
assert_eq!((out.width(), out.height()), (6, 3));
assert_eq!(out.data(), img.data());
}
#[test]
fn warp_into_paints_white_beyond_each_half_pixel_boundary() {
let img = LumaImage::new(vec![0; 4 * 3], 4, 3);
for (source_x, source_y) in [(3.75, 1.0), (1.0, 2.75), (-0.75, 1.0), (1.0, -0.75)] {
let forward = Homography([1.0, 0.0, -source_x, 0.0, 1.0, -source_y, 0.0, 0.0, 1.0]);
let out = warp_into(&img, &forward, 1, 1);
assert_eq!((out.width(), out.height()), (1, 1));
assert_eq!(out.data(), &[255], "source ({source_x}, {source_y})");
}
}
#[test]
fn warp_into_antialiases_each_half_pixel_boundary_with_truncation() {
let img = LumaImage::new(vec![0; 4 * 3], 4, 3);
for (source_x, source_y, expected) in [
(3.5, 1.0, 127),
(1.0, 2.5, 127),
(-0.5, 1.0, 127),
(1.0, -0.5, 127),
(3.25, 1.0, 63),
(1.0, 2.25, 63),
(-0.25, 1.0, 63),
(1.0, -0.25, 63),
(3.0, 1.0, 0),
(1.0, 2.0, 0),
(0.0, 1.0, 0),
(1.0, 0.0, 0),
(1.5, 1.0, 0),
] {
let forward = Homography([1.0, 0.0, -source_x, 0.0, 1.0, -source_y, 0.0, 0.0, 1.0]);
let out = warp_into(&img, &forward, 1, 1);
assert_eq!((out.width(), out.height()), (1, 1));
assert_eq!(out.data(), &[expected], "source ({source_x}, {source_y})");
}
}
#[test]
fn rotation_90_maps_top_left_to_top_right_region() {
let mut data = vec![255u8; 9 * 9];
data[0] = 0; let img = LumaImage::new(data, 9, 9);
let out = rotate(&img, 90.0);
assert!(
out.data()[8] < 128,
"rotated corner dark: {:?}",
&out.data()[..9]
);
assert!(out.data()[0] > 128, "origin now white");
}
#[test]
fn rotate_expands_the_canvas_to_the_rotated_bounding_box() {
let img = checker(15);
let out = rotate(&img, 40.0);
assert_eq!((out.width(), out.height()), (22, 22));
let out90 = rotate(&img, 90.0);
assert_eq!((out90.width(), out90.height()), (15, 15));
let rect = LumaImage::new(vec![255u8; 15 * 9], 15, 9);
let out_r = rotate(&rect, 40.0);
assert_eq!((out_r.width(), out_r.height()), (18, 17));
}
#[test]
fn perspective_tilt_zero_is_near_identity() {
let img = checker(12);
let out = perspective_tilt(&img, 0.0);
let diffs = img
.data()
.iter()
.zip(out.data())
.filter(|(a, b)| a != b)
.count();
assert!(diffs < 8, "near-identity expected, {diffs} diffs");
}
#[test]
fn perspective_tilt_pulls_top_corners_inward() {
let mut data = vec![255u8; 21 * 21];
for y in 0..6 {
for x in 0..6 {
data[y * 21 + x] = 0;
}
}
let img = LumaImage::new(data, 21, 21);
let out = perspective_tilt(&img, 40.0);
assert_eq!(out.data()[0], 255);
assert!(out.data()[..42].iter().any(|&p| p < 100));
}
#[test]
fn shadow_gradient_darkens_left_only() {
let img = LumaImage::new(vec![200u8; 8], 8, 1);
let out = shadow_gradient(&img, 0.5);
assert!(out.data()[0] < 110, "left darkened: {}", out.data()[0]);
assert!(
out.data()[7] >= 185,
"right nearly intact: {}",
out.data()[7]
);
let mut prev = 0u8;
for &px in out.data() {
assert!(px >= prev, "monotonic left→right");
prev = px;
}
}
#[test]
fn glare_blob_peaks_at_center() {
let img = LumaImage::new(vec![60u8; 9 * 9], 9, 9);
let out = glare_blob(&img, 4.0, 4.0, 2.0);
let center = out.data()[4 * 9 + 4];
let corner = out.data()[0];
assert!(center > 200, "center blown out: {center}");
assert!(corner < 80, "corner barely affected: {corner}");
}
#[test]
fn exposure_saturates_both_ways() {
let img = LumaImage::new(vec![10, 128, 250], 3, 1);
assert_eq!(exposure(&img, 40).data(), &[50, 168, 255]);
assert_eq!(exposure(&img, -40).data(), &[0, 88, 210]);
}
#[test]
fn compose_is_exact_matrix_product() {
let a = Homography([2.0, 3.0, 5.0, 7.0, 11.0, 13.0, 17.0, 19.0, 23.0]);
let out = compose(&a, &Homography::identity());
assert_eq!(out.0, a.0, "compose ∘ identity is a no-op on `a`");
}
#[test]
fn shadow_gradient_ramp_is_normalized_column() {
let img = LumaImage::new(vec![240u8; 4], 4, 1);
let out = shadow_gradient(&img, 1.0);
assert_eq!(out.data(), &[0, 60, 120, 180]);
}
#[test]
fn glare_blob_distance_metric_is_pinned() {
let img = LumaImage::new(vec![0u8; 5 * 3], 5, 3);
let out = glare_blob(&img, 3.0, 1.0, 1.0);
let px = |c: usize, r: usize| out.data()[r * 5 + c];
assert_eq!(px(3, 1), 255, "blob centre peaks at 255");
assert!(px(0, 1) < 30, "far pixel stays dark: {}", px(0, 1));
assert!(px(3, 0) < 150, "above-centre not blown out: {}", px(3, 0));
assert!(px(3, 2) > 60, "below-centre stays lit: {}", px(3, 2));
}
#[test]
fn rotate_matrix_terms_are_pinned() {
let mut data = vec![255u8; 15 * 15];
for y in 2..9 {
for x in 2..9 {
data[y * 15 + x] = 0;
}
}
let img = LumaImage::new(data, 15, 15);
let out = rotate(&img, 40.0);
assert_eq!((out.width(), out.height()), (22, 22));
let px = |c: usize, r: usize| out.data()[r * 22 + c];
assert!(px(10, 7) < 64, "block interior dark: {}", px(10, 7));
assert!(px(10, 8) < 64, "block interior dark: {}", px(10, 8));
assert!(
px(17, 8) > 200,
"sin-flip cell stays background: {}",
px(17, 8)
);
assert!(
px(21, 8) > 200,
"tx-sign cell stays background: {}",
px(21, 8)
);
assert!(
px(16, 8) > 200,
"tx-ratio cell stays background: {}",
px(16, 8)
);
assert!(
px(10, 17) > 200,
"ty-sign cell stays background: {}",
px(10, 17)
);
assert!(
px(10, 13) > 200,
"ty-ratio cell stays background: {}",
px(10, 13)
);
}
#[test]
fn perspective_tilt_geometry_is_pinned() {
let img = LumaImage::new(vec![0u8; 31 * 31], 31, 31);
let out = perspective_tilt(&img, 72.0);
let px = |c: usize, r: usize| out.data()[r * 31 + c];
assert!(px(16, 0) > 128, "top-right boundary bg: {}", px(16, 0));
assert!(px(15, 0) < 128, "top-edge interior black: {}", px(15, 0));
assert!(px(0, 0) > 128, "inset-vacated corner bg: {}", px(0, 0));
assert!(px(0, 30) < 128, "bottom-left stays black: {}", px(0, 30));
assert!(px(5, 20) < 128, "interior stays black: {}", px(5, 20));
assert!(px(20, 0) > 128, "far top background: {}", px(20, 0));
}
#[test]
fn stress_angle_sines_and_cosines_are_correctly_rounded() {
let pinned: [(f32, u32, u32); 17] = [
(5.0, 0x3db2_7eb5, 0x3f7f_069e),
(10.0, 0x3e31_d0d4, 0x3f7c_1c5c),
(14.0, 0x3e77_ba60, 0x3f78_654d),
(15.0, 0x3e84_83ee, 0x3f77_46ea),
(18.0, 0x3e9e_377a, 0x3f73_7871),
(20.0, 0x3eaf_1d43, 0x3f70_8fb2),
(22.0, 0x3ebf_cc6f, 0x3f6d_5bec),
(25.0, 0x3ed8_616c, 0x3f68_03c9),
(26.0, 0x3ee0_722f, 0x3f66_175e),
(30.0, 0x3f00_0000, 0x3f5d_b3d7),
(34.0, 0x3f0f_2744, 0x3f54_3bcf),
(35.0, 0x3f12_d5e8, 0x3f51_b3f3),
(38.0, 0x3f1d_9bfe, 0x3f49_bb13),
(40.0, 0x3f24_8dba, 0x3f44_1b7d),
(42.0, 0x3f2b_4c25, 0x3f3e_3ebd),
(45.0, 0x3f35_04f3, 0x3f35_04f3),
(50.0, 0x3f44_1b7d, 0x3f24_8dbb),
];
for (angle, sin, cos) in pinned {
let (s, c) = sin_cos_degrees(std::hint::black_box(angle));
assert_eq!(
(s.to_bits(), c.to_bits()),
(sin, cos),
"{angle}°: sin {s} · cos {c}"
);
}
}
}