LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
M4.3: geometry — manual transforms as one homography in the geometry frame, Constrain Crop
Brandon Thomas733e59f84e2a
diff --git a/crates/pipeline/src/geometry.rs b/crates/pipeline/src/geometry.rsindex 7b4b7df7b..38aa10174 100644--- a/crates/pipeline/src/geometry.rs+++ b/crates/pipeline/src/geometry.rs@@ -6,7 +6,7 @@//! lens correction and perspective, at the source's size. Everything is sampled in one resample.use lightcraft_develop::{DevelopSettings, EmbeddedLens};-use lightcraft_geom::{Affine, CropGeometry, Orientation, Point, Rect};+use lightcraft_geom::{Affine, CropGeometry, Homography, Orientation, Point, Rect};use lightcraft_raster::resample::{Filter, resize};use lightcraft_raster::{Rgb32f, par_rows};@@ -44,8 +44,15 @@ impl Frame {let (ow, oh) = if orient.swaps_axes() { (src_h as f64, src_w as f64) } else { (src_w as f64, src_h as f64) };let crop = if apply_crop { s.crop.geometry } else { CropGeometry::default() };let lens = lens.map(|l| reorient_lens(l, orient, src_w as f64, src_h as f64));- let warp = Warp::from_settings(ow, oh, s, lens.as_ref());- Frame {+ let mut warp = Warp::from_settings(ow, oh, s, lens.as_ref());+ let persp = perspective(s, ow, oh);+ if persp != Homography::IDENTITY+ && let Some(inv) = persp.inverse()+ {+ warp.persp = persp;+ warp.persp_inv = inv;+ }+ let mut f = Frame {src_w,src_h,orient,@@ -55,7 +62,39 @@ impl Frame {flip_h: apply_crop && s.crop.flip_h,flip_v: apply_crop && s.crop.flip_v,warp: (!warp.is_identity()).then_some(warp),+ };+ if apply_crop && s.geometry.constrain_crop {+ f.constrain_to_image();}+ f+ }++ /// "Constrain Crop": shrink the crop about its centre until it contains no area outside the warped source.+ fn constrain_to_image(&mut self) {+ let Some(wp) = self.warp.as_ref().filter(|w| w.moves_pixels()) else { return };+ let a = self.crop.output_to_source(self.ow, self.oh, 1.0, 1.0);+ let (w, h) = (self.ow, self.oh);+ let fits = |t: f64| {+ (0..=48).all(|i| {+ let u = i as f64 / 48.0;+ [(u, 0.0), (u, 1.0), (0.0, u), (1.0, u)].iter().all(|&(x, y)| {+ let p = Point::new(0.5 + t * (x - 0.5), 0.5 + t * (y - 0.5));+ let s = wp.to_source(a.apply(p), 1);+ s.x >= -1e-6 * w && s.y >= -1e-6 * h && s.x <= w * (1.0 + 1e-6) && s.y <= h * (1.0 + 1e-6)+ })+ })+ };+ if fits(1.0) {+ return;+ }+ let (mut lo, mut hi) = (0.0, 1.0);+ for _ in 0..30 {+ let m = (lo + hi) / 2.0;+ if fits(m) { lo = m } else { hi = m }+ }+ let t = lo.max(0.02);+ let r = self.crop.rect;+ self.crop.rect = Rect::from_center(r.center(), r.width() * t, r.height() * t);}/// Add automatically estimated lateral CA (`[α_R, α_B]`, see [`crate::optics::estimate_lateral_ca`]).@@ -182,6 +221,15 @@ impl Frame {}}+/// The perspective homography of the settings (Upright, then the manual Transform sliders), lens-corrected →+/// transformed, in centred coordinates.+pub fn perspective(s: &DevelopSettings, _ow: f64, _oh: f64) -> Homography {+ if !s.section_enabled("geometry") {+ return Homography::IDENTITY;+ }+ crate::transform::manual(&s.geometry)+}+/// One resample through the warp: `o2t` maps output px → transformed px, the warp maps those to source px/// (scaled by `sx, sy` into `base`).fn sample_warped(base: &Rgb32f, sx: f64, sy: f64, wp: &Warp, o2t: Affine, w: usize, h: usize) -> Rgb32f {diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rsindex b6404fa64..9ca2ab09d 100644--- a/crates/pipeline/src/lib.rs+++ b/crates/pipeline/src/lib.rs@@ -27,6 +27,7 @@ pub mod optics;pub mod profiles;pub mod spots;mod tone;+pub mod transform;use lightcraft_develop::{DevelopSettings, Treatment};use lightcraft_raster::{Histogram, Plane, Rgb32f, Rgba8, par_rows};diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rsindex d8f8d09f6..6d3c097cc 100644--- a/crates/pipeline/src/tests_geometry.rs+++ b/crates/pipeline/src/tests_geometry.rs@@ -177,3 +177,100 @@ fn optics_preview_matches_export() {let err = mean_abs_diff_downscaled(&small, &big);assert!(err < 4.0, "mean abs error {err}");}++// ------------------------------------------------------------------------------------------ M4.3 transforms++/// Source whose content is a straight grid after the forward transform `h` (centred coordinates of a `w × h`+/// image): each source pixel shows the grid at its transformed position.+fn keystoned_grid(w: usize, h: usize, fwd: lightcraft_geom::Homography, step: f64) -> Rgb32f {+ let l = w.max(h) as f64 / 2.0;+ let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0);+ synth(+ w,+ h,+ move |p| {+ let q = fwd.apply(Point::new((p.x - cx) / l, (p.y - cy) / l));+ Point::new(cx + q.x * l, cy + q.y * l)+ },+ move |p| [grid_value(p, step); 3],+ )+}++#[test]+fn manual_vertical_keystone_widens_the_top() {+ let g = lightcraft_develop::Geometry { vertical: -50.0, ..Default::default() };+ let hm = crate::transform::manual(&g);+ let (tl, tr) = (hm.apply(Point::new(-1.0, -0.66)), hm.apply(Point::new(1.0, -0.66)));+ let (bl, br) = (hm.apply(Point::new(-1.0, 0.66)), hm.apply(Point::new(1.0, 0.66)));+ assert!(tr.x - tl.x > (br.x - bl.x) * 1.15, "top {} bottom {}", tr.x - tl.x, br.x - bl.x);+ let c = hm.apply(Point::new(0.0, 0.0));+ assert!(c.dist(Point::new(0.0, 0.0)) < 1e-9, "centre stays put");+ let g = lightcraft_develop::Geometry { horizontal: -50.0, ..Default::default() };+ let hm = crate::transform::manual(&g);+ let (lt, lb) = (hm.apply(Point::new(-0.9, -0.6)), hm.apply(Point::new(-0.9, 0.6)));+ let (rt, rb) = (hm.apply(Point::new(0.9, -0.6)), hm.apply(Point::new(0.9, 0.6)));+ assert!(lb.y - lt.y > rb.y - rt.y, "left side enlarged");+}++#[test]+fn manual_transforms_straighten_known_keystone() {+ let (w, h) = (480usize, 320usize);+ for g in [+ lightcraft_develop::Geometry { vertical: -40.0, ..Default::default() },+ lightcraft_develop::Geometry { horizontal: 35.0, rotate: 3.0, ..Default::default() },+ lightcraft_develop::Geometry { vertical: 25.0, aspect: 30.0, scale: 110.0, offset_x: 6.0, offset_y: -4.0, ..Default::default() },+ ] {+ // the source was "shot" with the inverse transform; correcting with `g` must give the straight grid back+ let fwd = crate::transform::manual(&g);+ let src = keystoned_grid(w, h, fwd, 40.0);+ let s = DevelopSettings { geometry: g.clone(), ..Default::default() };+ let img = render(&src, &SourceInfo::default(), &s, &RenderRequest::fit(w, h)).image;+ let xs: Vec<f64> = [60usize, 150, 260].iter().map(|&y| line_x(&img, y, 200.0, 15.0)).collect();+ let ys: Vec<f64> = [60usize, 220, 420].iter().map(|&x| line_y(&img, x, 200.0, 15.0)).collect();+ assert!(spread(&xs) < 1.0 && (xs[0] - 200.0).abs() < 1.0, "{g:?}: vertical line at {xs:?}");+ assert!(spread(&ys) < 1.0 && (ys[0] - 200.0).abs() < 1.0, "{g:?}: horizontal line at {ys:?}");+ // and without the correction the lines are not straight/where they belong+ let raw = render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(w, h)).image;+ let rx: Vec<f64> = [60usize, 150, 260].iter().map(|&y| line_x(&raw, y, 200.0, 15.0)).collect();+ let ry: Vec<f64> = [60usize, 220, 420].iter().map(|&x| line_y(&raw, x, 200.0, 15.0)).collect();+ assert!(spread(&rx) > 1.5 || spread(&ry) > 1.5 || (rx[0] - 200.0).abs() > 1.5, "{g:?}: source should be distorted");+ }+}++fn blank_fraction(img: &Rgba8) -> f64 {+ let blank =+ crate::render(&Rgb32f::filled(4, 4, crate::geometry::BLANK), &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(4, 4))+ .image+ .get(1, 1);+ img.data.iter().filter(|p| (0..3).all(|i| (p[i] as i32 - blank[i] as i32).abs() <= 1)).count() as f64 / img.len() as f64+}++#[test]+fn constrain_crop_removes_blank_areas() {+ let src = Rgb32f::from_fn(300, 200, |x, y| [0.05 + 0.002 * x as f32, 0.1 + 0.002 * y as f32, 0.3]);+ let mut s = DevelopSettings::default();+ s.geometry.vertical = -60.0;+ s.geometry.rotate = 4.0;+ let free = render(&src, &SourceInfo::default(), &s, &RenderRequest::fit(300, 300)).image;+ assert!(blank_fraction(&free) > 0.03, "keystone leaves blank corners: {}", blank_fraction(&free));+ s.geometry.constrain_crop = true;+ let c = render(&src, &SourceInfo::default(), &s, &RenderRequest::fit(300, 300)).image;+ assert_eq!((c.width, c.height), (free.width, free.height), "constrain keeps the aspect");+ assert!(blank_fraction(&c) < 0.002, "constrained: {}", blank_fraction(&c));+}++#[test]+fn transforms_preview_matches_export() {+ let src = lightcraft_scenes::demo_library()[4].render(960, 640);+ let mut s = DevelopSettings::default();+ s.geometry.vertical = -30.0;+ s.geometry.horizontal = 15.0;+ s.geometry.rotate = 2.5;+ s.geometry.scale = 105.0;+ s.geometry.constrain_crop = true;+ let small = render(&src, &SourceInfo::default(), &s, &RenderRequest::fit(240, 240)).image;+ let big = render(&src, &SourceInfo::default(), &s, &RenderRequest::fit(960, 960)).image;+ assert_eq!(small.width * 4, big.width);+ let err = mean_abs_diff_downscaled(&small, &big);+ assert!(err < 4.0, "mean abs error {err}");+}diff --git a/crates/pipeline/src/transform.rs b/crates/pipeline/src/transform.rsnew file mode 100644index 000000000..113ea97f6--- /dev/null+++ b/crates/pipeline/src/transform.rs@@ -0,0 +1,89 @@+//! Perspective transforms: the manual Transform sliders (vertical/horizontal keystone, rotate, aspect, scale,+//! offset) as one homography, composed with the Upright correction.+//!+//! All homographies here map *lens-corrected* centred coordinates to *transformed* centred coordinates, where+//! centred coordinates are `(p − image centre) / (long edge / 2)`. Keystone corrections are modelled as a virtual+//! camera rotation `K·R·K⁻¹` (focal length [`DEFAULT_FOCAL`] in those units), re-centred so the image centre stays+//! put and its local scale is preserved.++use lightcraft_develop::Geometry;+use lightcraft_geom::Homography;++/// Assumed focal length in half-long-edge units (≈ 27 mm on a 36 mm-wide frame).+pub const DEFAULT_FOCAL: f64 = 1.5;+/// Vertical/Horizontal ±100 → virtual camera rotation (radians).+const KEYSTONE_MAX: f64 = 0.5;++pub type Mat3 = [[f64; 3]; 3];++pub fn mat_mul(a: &Mat3, b: &Mat3) -> Mat3 {+ let mut r = [[0.0; 3]; 3];+ for i in 0..3 {+ for j in 0..3 {+ r[i][j] = (0..3).map(|k| a[i][k] * b[k][j]).sum();+ }+ }+ r+}++pub fn to_h(m: &Mat3) -> Homography {+ Homography([m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2]])+}++/// `K·R·K⁻¹` for a rotation `r` (rows) and focal length `f`.+pub fn rotation_homography(r: &Mat3, f: f64) -> Homography {+ let k = [[f, 0.0, 0.0], [0.0, f, 0.0], [0.0, 0.0, 1.0]];+ let ki = [[1.0 / f, 0.0, 0.0], [0.0, 1.0 / f, 0.0], [0.0, 0.0, 1.0]];+ to_h(&mat_mul(&k, &mat_mul(r, &ki)))+}++pub fn rot_x(a: f64) -> Mat3 {+ let (s, c) = a.sin_cos();+ [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]+}++pub fn rot_y(a: f64) -> Mat3 {+ let (s, c) = a.sin_cos();+ [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]+}++/// Translate so the origin maps to itself and scale so the local area there is unchanged.+pub fn recentre(h: &Homography) -> Homography {+ let o = h.apply(lightcraft_geom::Point::new(0.0, 0.0));+ let t = Homography([1.0, 0.0, -o.x, 0.0, 1.0, -o.y, 0.0, 0.0, 1.0]).mul(h);+ // Jacobian at the origin (numerically)+ let e = 1e-4;+ let px = t.apply(lightcraft_geom::Point::new(e, 0.0));+ let py = t.apply(lightcraft_geom::Point::new(0.0, e));+ let det = ((px.x * py.y - px.y * py.x) / (e * e)).abs();+ let s = if det > 1e-12 { 1.0 / det.sqrt() } else { 1.0 };+ Homography([s, 0.0, 0.0, 0.0, s, 0.0, 0.0, 0.0, 1.0]).mul(&t)+}++/// The manual Transform sliders as a homography (lens-corrected → transformed, centred coordinates).+/// Signs (like Lightroom): Vertical − widens the top (fixes converging verticals shot from below), Horizontal −+/// enlarges the left side, Rotate + turns the image clockwise, Aspect + stretches vertically, Scale > 100 zooms in,+/// Offset X + moves the image right, Offset Y + moves it up.+pub fn manual(g: &Geometry) -> Homography {+ let mut h = Homography::IDENTITY;+ if g.vertical != 0.0 || g.horizontal != 0.0 {+ let r = mat_mul(&rot_y(g.horizontal / 100.0 * KEYSTONE_MAX), &rot_x(-g.vertical / 100.0 * KEYSTONE_MAX));+ h = recentre(&rotation_homography(&r, DEFAULT_FOCAL));+ }+ if g.rotate != 0.0 {+ let (s, c) = g.rotate.to_radians().sin_cos();+ h = Homography([c, -s, 0.0, s, c, 0.0, 0.0, 0.0, 1.0]).mul(&h);+ }+ if g.aspect != 0.0 {+ let k = (g.aspect / 200.0).exp2();+ h = Homography([1.0 / k, 0.0, 0.0, 0.0, k, 0.0, 0.0, 0.0, 1.0]).mul(&h);+ }+ let s = (g.scale / 100.0).clamp(0.1, 10.0);+ if s != 1.0 {+ h = Homography([s, 0.0, 0.0, 0.0, s, 0.0, 0.0, 0.0, 1.0]).mul(&h);+ }+ if g.offset_x != 0.0 || g.offset_y != 0.0 {+ h = Homography([1.0, 0.0, g.offset_x / 100.0 * 0.5, 0.0, 1.0, -g.offset_y / 100.0 * 0.5, 0.0, 0.0, 1.0]).mul(&h);+ }+ h+}diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rsindex e9d066e0b..37ea4ef5c 100644--- a/crates/ui-egui/src/panels/right.rs+++ b/crates/ui-egui/src/panels/right.rs@@ -133,6 +133,12 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {});divider(ui);header(ui, "Geometry");+ padded(ui, |ui| {+ let mut c = d.geometry.constrain_crop;+ if ui.checkbox(&mut c, "Constrain Crop").changed() {+ let _ = app.run("develop.merge", json!({"settings": {"geometry": {"constrain_crop": c}}, "label": "Constrain Crop"}));+ }+ });for spec in lightcraft_develop::controls::in_section(lightcraft_develop::Section::Geometry).filter(|c| c.id != "crop.angle") {let v = lightcraft_develop::controls::get(&d, spec.id).unwrap_or(spec.default);let out = slider(ui, spec, v, true, None);